diff --git "a/599.jsonl" "b/599.jsonl" new file mode 100644--- /dev/null +++ "b/599.jsonl" @@ -0,0 +1,650 @@ +{"seq_id":"281996055","text":"from rcwa import Source, Layer, LayerStack, Crystal, Solver, TriangularGrating\nfrom rcwa.utils import Plotter\nfrom rcwa.shorthand import complexArray\nimport numpy as np\n\n\ndef solve_system():\n\n reflection_layer = Layer(er=1.0, ur=1.0)\n transmission_layer = Layer(er=9.0, ur=1.0)\n\n wavelength = 0.5\n deg = np.pi / 180\n k0 = 2*np.pi/wavelength\n theta = 60 * deg\n phi = 1*deg\n pTEM = 1/np.sqrt(2)*complexArray([1,1j])\n source = Source(wavelength=wavelength, theta=theta, phi=phi, pTEM=pTEM, layer=reflection_layer)\n lattice_vector = [1.0, 0, 0]\n\n crystal_thickness = 0.5\n\n N_harmonics = 11\n\n grating = TriangularGrating(period=2, thickness=0.5, n=4, n_void=1, Nx=500)\n layer_stack = LayerStack(*grating.slice(), incident_layer=reflection_layer, transmission_layer=transmission_layer)\n\n solver_1d = Solver(layer_stack, source, N_harmonics)\n results = solver_1d.solve()\n return results\n\n\nif __name__ == '__main__':\n results = solve_system()\n # Get the amplitude reflection and transmission coefficients\n (rxCalculated, ryCalculated, rzCalculated) = (results['rx'], results['ry'], results['rz'])\n (txCalculated, tyCalculated, tzCalculated) = (results['tx'], results['ty'], results['tz'])\n\n # Get the diffraction efficiencies R and T and overall reflection and transmission coefficients R and T\n (R, T, RTot, TTot) = (results['R'], results['T'], results['RTot'], results['TTot'])\n print(RTot, TTot, RTot+TTot)\n","sub_path":"rcwa/examples/diffraction_grating_triangular_1D.py","file_name":"diffraction_grating_triangular_1D.py","file_ext":"py","file_size_in_byte":1474,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"335899511","text":"import matplotlib.pyplot as plt\nimport numpy as np\nfrom matplotlib.backends.backend_pdf import PdfPages\n\ndef main():\n\tpp = PdfPages('result.pdf')\n\tshow_data('conv.dat', pp, 'Convolution')\n\tshow_data('convfft.dat', pp, 'Convolution FFT')\n\tshow_data('corr.dat', pp, 'Correlation')\n\tshow_data('corrfft.dat', pp, 'Correlation FFT')\n\n\tpp.close()\n\n\ndef load_data(file_name):\n\treturn np.genfromtxt(file_name)\n\n\ndef show_data(file_name, out_file, title):\n\tc_complex = load_data(file_name)\n\n\tplt.figure(figsize = (8, 5))\n\tplt.title(title)\n\n\tplt.stem(c_complex, linefmt='r-', basefmt='k-')\n\tplt.savefig(out_file, format='pdf')\n\tplt.close()\n\nif __name__ == \"__main__\":\n\tmain()","sub_path":"laba2/cos.py","file_name":"cos.py","file_ext":"py","file_size_in_byte":671,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"155224230","text":"import sys\nimport gzip\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nfrom sklearn.metrics import confusion_matrix\n\ndef feed_confusion_matrix(filename, th, sp = -2, cp = -1):\n f = gzip.open(filename)\n y_true = []\n y_pred = []\n for line in f:\n \n v = line.rstrip().split()\n y_true.append(int(v[cp]))\n if float(v[sp]) <= th:\n\n y_pred.append(1)\n\n else:\n\n y_pred.append(0)\n\n f.close()\n\n return(y_true, y_pred)\n\ndef print_confusion_matrix(confusion_matrix, class_names, figsize = (4,3), fontsize=14):\n \"\"\"Prints a confusion matrix, as returned by sklearn.metrics.confusion_matrix, as a heatmap.\n \n Arguments\n ---------\n confusion_matrix: numpy.ndarray\n The numpy.ndarray object returned from a call to sklearn.metrics.confusion_matrix. \n Similarly constructed ndarrays can also be used.\n class_names: list\n An ordered list of class names, in the order they index the given confusion matrix.\n figsize: tuple\n A 2-long tuple, the first value determining the horizontal size of the ouputted figure,\n the second determining the vertical size. Defaults to (10,7).\n fontsize: int\n Font size for axes labels. Defaults to 14.\n \n Returns\n -------\n matplotlib.figure.Figure\n The resulting confusion matrix figure\n \"\"\"\n df_cm = pd.DataFrame(\n confusion_matrix, index=class_names, columns=class_names, \n )\n fig = plt.figure(figsize=figsize)\n try:\n heatmap = sns.heatmap(df_cm, annot=True, fmt=\"d\")\n except ValueError:\n raise ValueError(\"Confusion matrix values must be integers.\")\n heatmap.yaxis.set_ticklabels(heatmap.yaxis.get_ticklabels(), rotation=0, ha='right', fontsize=fontsize)\n heatmap.xaxis.set_ticklabels(heatmap.xaxis.get_ticklabels(), rotation=45, ha='right', fontsize=fontsize)\n plt.ylabel('True label')\n plt.xlabel('Predicted label')\n plt.tight_layout()\n return(fig)\n\nif __name__ == '__main__':\n filename = sys.argv[1]\n th = float(sys.argv[2])\n figname = sys.argv[3]\n class_names = [\"non-Kunitz\", \"Kunitz\"]\n\n y_true, y_pred = feed_confusion_matrix(filename, th)\n # test\n #print(y_true)\n #print(y_pred)\n\n confMat = confusion_matrix(y_true, y_pred)\n # test\n #print(confMat)\n\n fig = print_confusion_matrix(confMat, class_names, fontsize=10)\n \n plt.savefig(figname, type=\"png\", dpi=96)\n plt.show()\n","sub_path":"LB1/prj/kunitz_BPTI_blast/src/confMatPrettyPrint.py","file_name":"confMatPrettyPrint.py","file_ext":"py","file_size_in_byte":2484,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"427147456","text":"from pylab import *\nfrom scipy import *\nfrom scipy.linalg import solve\n\ndef f(a, b):\n\tfa = 5*cos(a) + 6*cos(a+b) - 10\n\tfb = 5*sin(a) + 6*sin(a+b) - 4\n\treturn [fa,fb];\n\ndef main():\n\tx = [0.7, 0.7]\n\tjac = jacobi(f, x)\n\tfx = f(x[0], x[1])\n\twhile [fx[i]!=0 for i in range(len(fx))] == len(fx)*[True]: \n\t\tjac = jacobi(f, x)\n\t\tdx = solve(jac, [-fx[i] for i in range(len(fx))])\n\t\tx = [x[i]+dx[i] for i in range(len(x))]\n\t\tfx = f(x[0], x[1])\n\tprint(x)\n\ndef jacobi(f, ab, eps = 1e-8):\n\targs = [[ab[0]+eps, ab[1]], [ab[0], ab[1]+eps]]\n\tfx = [f(ab[0], ab[1]) for x in range(len(ab))]\n\tfxp = [f(*args[x]) for x in range(len(ab))]\n\tfor i in range(len(ab)):\n\t\tfor n in range(len(ab)):\n\t\t\tfxp[i][n] = (fxp[i][n] - fx[i][n]) / eps\n\tfxf = [[fxp[0][0], fxp[1][0]], [fxp[0][1], fxp[1][1]]] # Flip\n\treturn fxf\n\nif __name__ == \"__main__\":\n\tmain()","sub_path":"ass2/task1.py","file_name":"task1.py","file_ext":"py","file_size_in_byte":825,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"346003060","text":"\"\"\"Main class for search.\"\"\"\nfrom .async_search_client import AsyncSearchClient\nfrom typing import List, Dict\n\n\nclass Searcher(AsyncSearchClient):\n \"\"\"A 'main' class for search.\"\"\"\n\n def __init__(self, *args):\n \"\"\"\n Create a Searcher.\n\n Args:\n args: Existing AsyncSearchClients. Searcher will search the query on each one.\n \"\"\"\n self.search_clients = args\n\n def initialize(self, *args, **kwargs):\n \"\"\"Initialize each search client.\"\"\"\n for sc in self.search_clients:\n sc.initialize(*args, **kwargs)\n\n async def search(self, filename: str, serv, *args, **kwargs) -> List[Dict]:\n \"\"\"\n Search using all async search clients.\n\n Args:\n filename: The filename to search for\n serv_id: The channel/guild to search in\n kwargs: Any search options.\n\n Returns:\n A list of files that match the search criteria with no duplicate file ids.\n \"\"\"\n files = []\n for search_client in self.search_clients:\n res = await search_client.search(filename, serv, *args, **kwargs)\n files.extend(res)\n # files = [val async for search_client in self.search_clients for val in ]\n ids = set()\n no_duplicate_files = []\n for file in files:\n if file['objectID'] not in ids:\n no_duplicate_files.append(file)\n ids.add(file['objectID'])\n return no_duplicate_files\n\n async def create_doc(self, *args, **kwargs):\n \"\"\"Create docs in each search client.\"\"\"\n for sc in self.search_clients:\n await sc.create_doc(*args, **kwargs)\n\n async def remove_doc(self, *args, **kwargs):\n \"\"\"Delete docs in each search client.\"\"\"\n for sc in self.search_clients:\n await sc.remove_doc(*args, **kwargs)\n","sub_path":"python/search/searcher.py","file_name":"searcher.py","file_ext":"py","file_size_in_byte":1873,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"156213275","text":"import datetime\nimport os\nimport subprocess\nimport re\nimport string\n\n\n# This file is the \"user level commands\" and the mapping from the\n# touch tone codes to the functions.\n\n# user functions or \"marcos\" below are some examples.\n# the commands here work on both ports.\n# for commands that should work on the port where they came in...\n# a command can affect the other port....\n\ndef test123(port):\n print(\"test123\")\n port.tx.tailBeepWav = '../sounds/Tink.wav'\n sys.stdout.flush()\n\ndef test456(port):\n print(\"test456\")\n port.tx.tailBeepWav = '../sounds/Submarine.wav'\n sys.stdout.flush()\n\ndef test789(port):\n print(\"test789\")\n port.tx.tailBeepWav = '../sounds/Glass.wav'\n sys.stdout.flush()\n\ndef cmdWithArg(port,arg):\n print(\"port %d command got %d\" %(port.portnum, arg))\n sys.stdout.flush()\n\ndef beepMethod(port,arg):\n port.tx.beepMethod = arg\n print(\"port %d Tail Method Set to %d\" %(port.portnum,arg))\n sys.stdout.flush()\n\ndef rptDown(port):\n print(\"Shutting down\")\n port1.tx.down()\n port2.tx.down()\n GPIO.cleanup()\n exit(-1)\n\ndef setLinkState(port,arg) :\n port.linkState = arg # should probably queue some message\n if(arg == 0) :\n port.linkVotes = 0\n\ndef linkBoth(port,arg) :\n setLinkState(port,arg)\n setLinkState(port.other,arg)\n \ndef talkingClock(card,prefix = 'its'):\n dt = datetime.datetime.now()\n ds = dt.strftime(\"%I %M %p, %A %B %_d\")\n myTime = prefix + \" \"+ ds\n# device = string.replace(card,'sysdefault:CARD=','')\n device = card.replace('sysdefault:CARD=','')\n os.environ['ALSA_CARD'] = device\n subprocess.call(['/usr/bin/espeak', myTime], shell=False)\n\n\n# command table.\n# the command table can be in the format of the long list or you can add things like shown at the end.\n#\ncmdlist =[(\"123$\",\"test123\"), # the $ at the end forces an exact match\n (\"456\",\"test456\"),\n (\"789\",\"test789\")]\ncmdlist = cmdlist + [(\"123(\\d+)\", \"cmdWithArg\")] # rexexp type argument needed 1 or more decimal digits.\ncmdlist = cmdlist + [(\"DDDDD\", \"rptDown\")]\ncmdlist = cmdlist + [(\"2337(\\d)\", \"beepMethod\")]\ncmdlist = cmdlist + [(\"5465(\\d)\", \"linkBoth\")]\n\n# command processor\ndef cmdprocess (q,port) :\n \"\"\" This is a touch tone command processor routine. There is a queue\nand a process thread for each port it gets the port specific touch\ntone queue and the port for context. Its up to a command to decide if\nit acts globally or uses port context \"\"\"\n while (True) :\n tone = str(q.get()) # block until somthing is ready\n if (tone == \" \") : # terminator at end of rx\n if(len(port.cmd) >0) :\n found = 0\n for c in cmdlist :\n print(c)\n (name,func) = c\n m = re.match(name,port.cmd)\n if(m != None) :\n found = 1\n if(len(m.groups()) ==1) :\n result = eval(func+\"(port,\"+m.group(1)+\")\")\n else:\n result = eval(func+\"(port)\")\n break\n if(not found) :\n print(\"oops not found\") # que no sound\n\n port.cmd = \"\" # null out the command\n else :\n port.cmd = port.cmd + tone\n print(\"Port\" + str(port.portnum) + \": \" + tone)\n","sub_path":"python/mycmd.py","file_name":"mycmd.py","file_ext":"py","file_size_in_byte":3366,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"283947982","text":"import httplib2\nimport json\nimport os\nimport random\nimport requests\nimport string\n\nfrom flask import Flask, flash, jsonify, redirect, request\nfrom flask import make_response, render_template, url_for\nfrom flask import session as login_session\nfrom oauth2client.client import flow_from_clientsecrets\nfrom oauth2client.client import FlowExchangeError\nfrom sqlalchemy import create_engine, asc\nfrom sqlalchemy.ext.declarative import declarative_base\nfrom sqlalchemy.orm import relationship, sessionmaker\nfrom werkzeug.utils import secure_filename\n\nfrom models import Base, Breed, Group, User\n\nCLIENT_ID = json.loads(open('/var/www/catalog/app/client_secrets.json',\n 'r').read())['web']['client_id']\n\n# Connect to database and create database session\nengine = create_engine('postgresql://catalog:catalog@localhost/catalog')\nBase.metadata.bind = engine\nDBSession = sessionmaker(bind=engine)\nsession = DBSession()\n\napp = Flask(__name__)\napp.config['UPLOADS'] = '/var/www/catalog/app/static'\n\n# Show all groups\n@app.route('/')\n@app.route('/groups/')\ndef showGroups():\n groups = session.query(Group)\n return render_template('groups.html', groups=groups)\n\n\n# JSON endpoint for showing all groups\n@app.route('/groups/JSON/')\ndef showGroupsJSON():\n groups = session.query(Group)\n return jsonify(groups=[g.serialize for g in groups])\n\n\n# Show all breeds for a given group\n@app.route('/groups//')\n@app.route('/groups//breeds/')\ndef showGroupBreeds(group_id):\n if 'user_id' in login_session:\n user = login_session['user_id']\n else:\n user = ''\n group = session.query(Group).filter_by(id=group_id).one()\n breeds = session.query(Breed).filter_by(group_id=group_id)\n breeds = breeds.order_by(asc(Breed.name)).all()\n return render_template('breeds.html',\n breeds=breeds, group=group, user_id=user)\n\n\n# JSON endpoint for showing all breeds for a given group\n@app.route('/groups//breeds/JSON/')\ndef showGoupBreedsJSON(group_id):\n breeds = session.query(Breed).filter_by(group_id=group_id).all()\n return jsonify(Breeds=[b.serialize for b in breeds])\n\n\n# Show info for a specific breed\n@app.route('/groups//breeds//')\ndef showBreedInfo(group_id, breed_id):\n if 'user_id' in login_session:\n user = login_session['user_id']\n else:\n user = ''\n group = session.query(Group).filter_by(id=group_id).one()\n breed = session.query(Breed).filter_by(id=breed_id).one()\n return render_template('breedInfo.html',\n breed=breed, group=group, user_id=user)\n\n\n# JSON endpoint for info on a specific breed\n@app.route('/groups//breeds//JSON/')\ndef showBreedInfoJSON(group_id, breed_id):\n breed = session.query(Breed).filter_by(id=breed_id).one()\n return jsonify(breed.serialize)\n\n\n# Add a new breed to a group\n@app.route('/groups//breeds/add/', methods=['GET', 'POST'])\ndef addBreed(group_id):\n if 'username' not in login_session:\n return redirect('/showLogin')\n group = session.query(Group).filter_by(id=group_id).one()\n if request.method == 'POST':\n newBreed = Breed(name=request.form['name'],\n description=request.form['description'],\n height=request.form['height'],\n weight=request.form['weight'],\n group_id=group_id,\n user_id=login_session['user_id'])\n session.add(newBreed)\n session.commit()\n\n if 'picture' in request.files:\n picture = request.files['picture']\n if picture.filename != '':\n filename = 'breed%s.jpg' % newBreed.id\n picture.save(os.path.join(app.config['UPLOADS'], filename))\n newBreed.picture = filename\n session.add(newBreed)\n session.commit()\n\n flash('New Breed %s Successfully Created' % newBreed.name)\n return redirect(url_for('showBreedInfo',\n breed_id=newBreed.id, group_id=group.id))\n else:\n return render_template('addBreed.html', group=group)\n\n\n# Edit a breed\n@app.route('/groups//breeds//edit/',\n methods=['GET', 'POST'])\ndef editBreed(group_id, breed_id):\n if 'username' not in login_session:\n return redirect('/showLogin')\n breed = session.query(Breed).filter_by(id=breed_id).one()\n if login_session['user_id'] != breed.user_id:\n flash('Access Denied')\n return redirect(url_for('showGroupBreeds', group_id=group_id))\n else:\n group = session.query(Group).filter_by(id=group_id).one()\n if request.method == 'POST':\n breed.name = request.form['name']\n breed.description = request.form['description']\n breed.height = request.form['height']\n breed.weight = request.form['weight']\n\n if 'picture' in request.files:\n picture = request.files['picture']\n if picture.filename != '':\n filename = 'breed%s.jpg' % breed.id\n picture.save(os.path.join(app.config['UPLOADS'], filename))\n breed.picture = filename\n\n session.add(breed)\n session.commit()\n flash('Breed Successfully Edited')\n return redirect(url_for('showBreedInfo',\n breed_id=breed.id, group_id=group_id))\n else:\n return render_template('editBreed.html', breed=breed, group=group)\n\n\n# Delete a breed\n@app.route('/groups//breeds//delete/',\n methods=['GET', 'POST'])\ndef deleteBreed(group_id, breed_id):\n if 'username' not in login_session:\n return redirect('/showLogin')\n breed = session.query(Breed).filter_by(id=breed_id).one()\n if login_session['user_id'] != breed.user_id:\n flash('Access Denied')\n return redirect(url_for('showGroupBreeds', group_id=group_id))\n else:\n group = session.query(Group).filter_by(id=group_id).one()\n if request.method == 'POST':\n if breed.picture:\n os.remove(os.path.join(app.config['UPLOADS'], breed.picture))\n\n session.delete(breed)\n session.commit()\n flash('Breed Successfully Deleted')\n return redirect(url_for('showGroupBreeds', group_id=group_id))\n else:\n return render_template('deleteBreed.html',\n breed=breed, group=group)\n\n\n# Display login page\n@app.route('/showLogin/')\ndef showLogin():\n state = ''.join(random.choice(string.ascii_uppercase +\n string.digits) for x in xrange(32))\n login_session['state'] = state\n return render_template('login.html', STATE=state)\n\n\n# Log in\n@app.route('/login', methods=['POST'])\ndef login():\n # Validate state token\n if request.args.get('state') != login_session['state']:\n response = make_response(json.dumps('Invalid state parameter.'), 401)\n response.headers['Content-Type'] = 'application/json'\n return response\n\n provider = request.args.get('provider')\n\n if provider == 'google':\n gconnect(request.data)\n\n elif provider == 'facebook':\n fbconnect(request.data)\n\n # See if user exists; if not, create a new one\n user_id = getUserID(login_session['email'])\n if not user_id:\n user_id = createUser(login_session)\n login_session['user_id'] = user_id\n\n # Display the successful login message\n output = ''\n output += '

Welcome, '\n output += login_session['username']\n output += '!

'\n flash(\"You are now logged in as %s\" % login_session['username'])\n return output\n\n\n# Log in (Google)\ndef gconnect(auth_code):\n try:\n # Upgrade the authorization code into a credentials object\n oauth_flow = flow_from_clientsecrets('/var/www/catalog/app/client_secrets.json', scope='')\n oauth_flow.redirect_uri = 'postmessage'\n credentials = oauth_flow.step2_exchange(auth_code)\n except FlowExchangeError:\n response = make_response(\n json.dumps('Failed to upgrade the authorization code.'), 401)\n response.headers['Content-Type'] = 'application/json'\n return response\n\n # Check that the access token is valid.\n access_token = credentials.access_token\n url = ('https://www.googleapis.com/oauth2/v1/tokeninfo?access_token=%s'\n % access_token)\n h = httplib2.Http()\n result = json.loads(h.request(url, 'GET')[1])\n\n # If there was an error in the access token info, abort.\n if result.get('error') is not None:\n response = make_response(json.dumps(result.get('error')), 500)\n response.headers['Content-Type'] = 'application/json'\n return response\n\n # Verify that the access token is used for the intended user.\n gplus_id = credentials.id_token['sub']\n if result['user_id'] != gplus_id:\n response = make_response(\n json.dumps(\"Token's user ID doesn't match given user ID.\"), 401)\n response.headers['Content-Type'] = 'application/json'\n return response\n\n # Verify that the access token is valid for this app.\n if result['issued_to'] != CLIENT_ID:\n response = make_response(\n json.dumps(\"Token's client ID does not match app's.\"), 401)\n response.headers['Content-Type'] = 'application/json'\n return response\n\n stored_access_token = login_session.get('access_token')\n stored_gplus_id = login_session.get('gplus_id')\n if stored_access_token is not None and gplus_id == stored_gplus_id:\n response = make_response(json.dumps('User is already connected.'),\n 200)\n response.headers['Content-Type'] = 'application/json'\n return response\n\n # Store the access token in the session for later use.\n login_session['provider'] = 'google'\n login_session['access_token'] = credentials.access_token\n login_session['gplus_id'] = gplus_id\n\n # Get user info\n userinfo_url = \"https://www.googleapis.com/oauth2/v1/userinfo\"\n params = {'access_token': credentials.access_token, 'alt': 'json'}\n answer = requests.get(userinfo_url, params=params)\n\n data = answer.json()\n\n login_session['username'] = data['name']\n login_session['email'] = data['email']\n\n\n# Log in (Facebook)\ndef fbconnect(access_token):\n # Exchange client token for long-lived server-side token\n app_id = json.loads(open('/var/www/catalog/app/fb_client_secrets.json',\n 'r').read())['web']['app_id']\n app_secret = json.loads(open('/var/www/catalog/app/fb_client_secrets.json',\n 'r').read())['web']['app_secret']\n url = ('https://graph.facebook.com/oauth/access_token?'\n 'grant_type=fb_exchange_token&client_id=%s&client_secret=%s'\n '&fb_exchange_token=%s' % (app_id, app_secret, access_token))\n h = httplib2.Http()\n result = h.request(url, 'GET')[1]\n\n # Use token to get user info from API\n userinfo_url = \"https://graph.facebook.com/v2.8/me\"\n token = result.split(',')[0].split(':')[1].replace('\"', '')\n\n url = ('https://graph.facebook.com/v2.8/me?access_token=%s'\n '&fields=name,id,email' % token)\n h = httplib2.Http()\n result = h.request(url, 'GET')[1]\n data = json.loads(result)\n\n login_session['provider'] = 'facebook'\n login_session['username'] = data[\"name\"]\n login_session['email'] = data[\"email\"]\n login_session['facebook_id'] = data[\"id\"]\n\n\n# Log out\n@app.route('/logout')\ndef logout():\n if 'provider' in login_session:\n if login_session['provider'] == 'google':\n gdisconnect()\n del login_session['gplus_id']\n del login_session['access_token']\n if login_session['provider'] == 'facebook':\n fbdisconnect()\n del login_session['facebook_id']\n\n del login_session['username']\n del login_session['email']\n del login_session['user_id']\n del login_session['provider']\n\n flash(\"You have successfully been logged out.\")\n return redirect(url_for('showGroups'))\n else:\n flash(\"You are not logged in.\")\n return redirect(url_for('showGroups'))\n\n\n# Log out (Google)\ndef gdisconnect():\n access_token = login_session.get('access_token')\n if access_token is None:\n response = make_response(json.dumps('User not connected.'), 401)\n response.headers['Content-Type'] = 'application/json'\n return response\n url = ('https://accounts.google.com/o/oauth2/revoke?token=%s'\n % login_session['access_token'])\n h = httplib2.Http()\n result = h.request(url, 'GET')[0]\n if result['status'] != '200':\n response = make_response(json.dumps('Failed to revoke token.', 400))\n response.headers['Content-Type'] = 'application/json'\n return response\n\n\n# Log out (Facebook)\ndef fbdisconnect():\n facebook_id = login_session['facebook_id']\n url = 'https://graph.facebook.com/%s/permissions' % facebook_id\n h = httplib2.Http()\n result = h.request(url, 'DELETE')[1]\n\n\n# Create a new user in the database\ndef createUser(login_session):\n newUser = User(name=login_session['username'],\n email=login_session['email'])\n session.add(newUser)\n session.commit()\n user = session.query(User).filter_by(email=login_session['email']).one()\n return user.id\n\n\n# Get a user from the database by id\ndef getUserInfo(user_id):\n user = session.query(User).filter_by(id=user_id).one()\n return user\n\n\n# Get a user from the database by email\ndef getUserID(email):\n try:\n user = session.query(User).filter_by(email=email).one()\n return user.id\n except:\n return None\n\n\nif __name__ == '__main__':\n app.run()\n","sub_path":"app/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":13950,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"467749569","text":"from pedalpark import app, data\nfrom flask import request, jsonify\nfrom pygeocoder import Geocoder\nfrom bson import json_util\n\n\"\"\" All location related methods \"\"\"\n\n@app.route('/near')\ndef near():\n\targs = request.args\n\tlimit = 1\n\tif 'limit' in args: limit = int(args.get('limit'))\n\tif 'lat' in args and 'long' in args:\n\t\tla = float(args.get('lat'))\n\t\tlo = float(args.get('long'))\n\telif 'address' in args:\n\t\taddress = args.get('address')\n\t\tcoordinates = latlong_from_address(address)\n\t\tla = coordinates[0]\n\t\tlo = coordinates[1]\n\telse:\n\t\treturn jsonify(success=False)\n\n\tlocations = find_nearest_neighbours(la,lo,limit)\n\tlocations_json = []\n\tfor location in locations: locations_json.append(json_util.dumps(location))\n\treturn jsonify(success=True,locations=locations_json)\n\ndef find_nearest_neighbours(latitude,longitude,count):\n\tneighbours = data.geo_find_db(data.coll(),'coordinates',latitude,longitude,count)\n\treturn neighbours\n\ndef latlong_from_address(address):\n\treturn Geocoder.geocode(address)[0].coordinates","sub_path":"pedalpark/location.py","file_name":"location.py","file_ext":"py","file_size_in_byte":1012,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"594035743","text":"from collections import deque\r\n\r\nprime = [True for i in range(10001)]\r\nfor i in range(2, 101):\r\n if prime[i]:\r\n j = i * 2\r\n while j < 10001:\r\n prime[j] = False\r\n j += i\r\ndef bfs():\r\n q = deque()\r\n q.append([a, 0])\r\n visit = [0 for i in range(10000)]\r\n visit[a] = 1\r\n while q:\r\n num, cnt = q.popleft()\r\n if num == b: return cnt\r\n if num < 1000: continue\r\n for i in [1, 10, 100, 1000]:\r\n n = num - num % (i * 10) // i * i\r\n for j in range(10):\r\n if visit[n] == 0 and prime[n]:\r\n visit[n] = 1\r\n q.append([n, cnt + 1])\r\n n += i\r\nt = int(input())\r\nfor i in range(t):\r\n a, b = map(int, input().split())\r\n res = bfs()\r\n if res == None:\r\n print(\"Impossible\")\r\n else:\r\n print(res)","sub_path":"practice/DFS와 BFS/소수 경로.py","file_name":"소수 경로.py","file_ext":"py","file_size_in_byte":869,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"444179328","text":"#!/usr/bin/env python3\n\nclass Account(object):\n\n \"\"\"\n dffd\n \"\"\"\n\n def __init__(self, rate):\n\n self.__amt=0\n self.rate=rate\n\n @property\n def amount(self):\n\n return self.__amt\n\n @property\n def cny(self):\n\n return self.__amt* self.rate\n\n @amount.setter\n def amount(self, value):\n\n if value < 0:\n print(\"sorry ,no negative amout in the account.\")\n\n return\n self.__amt = value\n\nif __name__=='__main__':\n\n acc = Account(rate=6.6)\n\n acc.amount=20\n print(\"Dollar amount:\",acc.amount)\n print(\" In cny:\",acc.cny)\n\n acc.mount = -100\n print(\"Dollar amout:\",acc.amount)\n","sub_path":"python/实验楼-类 -代码/property.py","file_name":"property.py","file_ext":"py","file_size_in_byte":671,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"598842398","text":"'''\n\n'''\ndef chorus(student):\n dpl = [1 for _ in range(len(student))]\n dpr = [1 for _ in range(len(student))]\n dp = [0 for _ in range(len(student))]\n\n for i in range(len(dpl)):\n for j in range(i):\n if student[i] > student[j]:\n dpl[i] = max(dpl[i], dpl[j]+1)\n\n for i in range(len(dpr)-1, -1, -1):\n for j in range(i+1, len(dpr)):\n if student[i] > student[j]:\n dpr[i] = max(dpr[i], dpr[j]+1)\n\n maxk=0\n for k in range(len(dp)):\n dp[k] = dpl[k]+dpr[k]-1\n\n return max(dp)\n\nwhile True:\n try:\n N=int(input())\n listStudent=list(map(int,input().split()))\n maxs=chorus(listStudent)\n print(N-maxs)\n except:\n break","sub_path":"sing.py","file_name":"sing.py","file_ext":"py","file_size_in_byte":739,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"232580431","text":"#!/usr/bin/env pybricks-micropython\nfrom pybricks.hubs import EV3Brick\nfrom pybricks.ev3devices import (Motor, TouchSensor, ColorSensor,\n InfraredSensor, UltrasonicSensor, GyroSensor)\nfrom pybricks.parameters import Port, Stop, Direction, Button, Color\nfrom pybricks.tools import wait, StopWatch, DataLog\nfrom pybricks.robotics import DriveBase\nfrom pybricks.media.ev3dev import SoundFile, ImageFile\n\n\n# This program requires LEGO EV3 MicroPython v2.0 or higher.\n# Click \"Open user guide\" on the EV3 extension tab for more information.\n\n\n# Create your objects here.\ndef turnGradualGyro():\n ev3 = EV3Brick()\n\n\n # Write your program here.\n #Initialize motors\n cMotor = Motor(Port.C)\n dMotor = Motor(Port.D)\n rr = DriveBase(cMotor, dMotor, 56, 60)\n\n # Intialize sensors \n p4FSensor = GyroSensor(Port.S4)\n p4FSensor.reset_angle(0)\n\n # Write your program here.\n #Asks for the angle the user wants the robot to turn\n i = 90\n def GradualGyroTurnC(robot, degrees):\n #Sets variables and measures gyro angle\n initialGyro = p4FSensor.angle()\n newAngle = 0\n steering = 100\n speed = 0\n #Make robot keep on turning until it has reached the inputed degrees\n while newAngle < degrees:\n robot.drive(speed, steering)\n speed = speed+0.1\n newAngle = initialGyro + p4FSensor.angle()\n print(\"Angle is \" + str(newAngle))\n print(\"Speed is \" + str(speed))\n #Robot stops after reaching inputed degrees\n robot.stop(Stop.COAST)\n\n def GradualGyroTurnAC(robot, degrees):\n #Sets variables and measures gyro angle\n initialGyro = p4FSensor.angle()\n newAngle = 0\n steering = -100\n speed = 0\n #Make robot keep on turning until it has reached the inputed degrees\n while newAngle > degrees:\n robot.drive(speed, steering)\n speed = speed+0.1\n newAngle = initialGyro + p4FSensor.angle()\n print(\"Angle is \" + str(newAngle))\n print(\"Speed is \" + str(speed))\n #Robot stops after reaching inputed degrees\n robot.stop(Stop.COAST)\n\n if i > 0:\n #if angle is positive then turn clockwise\n GradualGyroTurnC(rr, i)\n elif i < 0:\n #if angle is negative then turn anticlockwise\n GradualGyroTurnAC(rr, i)\n else:\n #if angle is 0 then don't durn\n print(\"Invalid Angle\")\n","sub_path":"Ryan/masterProgam/TurnGradualGyro.py","file_name":"TurnGradualGyro.py","file_ext":"py","file_size_in_byte":2476,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"102124119","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Apr 14 10:44:18 2021\n\n@author: juliafoyer\n\"\"\"\n\nimport anndata as an\n\nfrom ST_LDA_functions import *\nfrom test_ST_LDA_functions import *\n\nK = 3\nalpha = 5\nbeta = 0.1\nGibbs_iterations = 50\n\npath = \"/Users/juliafoyer/Documents/Skolarbete/Masters_thesis/Scripts/spatial-data-synth/20210402100654897026-synth-data.h5ad\"\nadata = an.read_h5ad(path)\nadata = prepare_data(adata,select_hvg=False)\n\numi_factors = assign_random(adata, K)\n\nn_spots,n_genes = adata.shape\nids,dt,wt = get_ids_dt_wt(adata,umi_factors, K)#, alpha = alpha, beta = beta)\nnz = get_nz(dt)\n\n#gibbsSampling(umi_factors, ids, dt, wt, nz, Gibbs_iterations)\n\n#Gibbs sampling\nfor it in range(Gibbs_iterations):\n for d, doc in enumerate(ids):\n for index, w in enumerate(doc):\n draw_new_factor(umi_factors, dt, wt, nz, d, index, w)\n \nplot_theta(adata, dt)","sub_path":"LDA_implemented.py","file_name":"LDA_implemented.py","file_ext":"py","file_size_in_byte":898,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"493627676","text":"\"\"\"Scrape sample cases in Atcoder.\"\"\"\n\nimport requests\nfrom bs4 import BeautifulSoup\nimport re\nimport sys\nimport config\n\n\"\"\"\n:param level: contest level(lower case)\n:param round: number of round(ex 092)\n:param prob: problem(a,b,c,d...)\n\n:output_files: \"ABC/abc092/sample/\"直下にinputとanswerファイルを作成\n\"\"\"\n\n# パラメータセット\nargs = sys.argv\nlevel = args[1]\nround = int(args[2])\nprob = args[3]\nLOGIN_URL = \"https://beta.atcoder.jp/login\"\n\n# セッション開始\nsession = requests.session()\n\n# csrf_token取得\nr = session.get(LOGIN_URL)\ns = BeautifulSoup(r.text, 'lxml')\n\ncsrf_token = s.find(attrs={'name': 'csrf_token'}).get('value')\n\n\n# ログイン\nlogin_info = {\n \"csrf_token\": csrf_token,\n \"username\": config.USERNAME,\n \"password\": config.PASSWORD\n}\n\nresult = session.post(LOGIN_URL, data=login_info)\nresult.raise_for_status()\n\n\ntarget_url = \"https://beta.atcoder.jp/contests/{level}{round:03d}/tasks/{level}{round:03d}_{prob}\".format(\n level=level, round=round, prob=prob)\n\nhtml = session.get(target_url)\nhtml.raise_for_status()\nsoup = BeautifulSoup(html.text, 'lxml')\n\nlang = soup.find(\"span\", class_=\"lang-ja\")\n\nfile_i = 0\n\nif lang is None:\n result = soup.find_all(\"pre\")\nelse:\n result = lang.find_all(\"pre\")\n\nif len(result) == 0:\n print(\"Error in Scraping.\")\nelse:\n print(\"Create sample files...\")\n\n for i in range(len(result)):\n content = result[i].string\n if content is None:\n continue\n\n if file_i % 2 == 0:\n filename = \"input_{}_{}.txt\".format(prob, file_i // 2 + 1)\n else:\n filename = \"answer_{}_{}.txt\".format(prob, file_i // 2 + 1)\n\n file_i += 1\n path_w = \"{level_camel}/{level}{round:03d}/sample_{prob}/{filename}\".format(\n level_camel=level.upper(), level=level, round=round, prob=prob, filename=filename)\n print(path_w)\n with open(path_w, mode='w') as f:\n f.write(content.lstrip())\n print(\"Complete!\")\n","sub_path":"cpp/scrape_sample.py","file_name":"scrape_sample.py","file_ext":"py","file_size_in_byte":1986,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"452528080","text":"#coding=utf-8\r\n\"\"\"\r\npython 3.6\r\n--------------------------------------------\r\nICP grabber\r\nAuthor: Vincent\r\nFunction: 1.Get domains by IP from file \"ipList.txt\", output to file \"sites.txt\"\r\n 2.Port scan those IPs\r\n 3.Get Websites' ICP and check it right\r\n--------------------------------------------\r\n\"\"\"\r\nfrom urllib import request\r\nimport re\r\n\r\n#Parameter: url is \"http://s.tool.chinaz.com/same?=+ip\"\r\n#function: Spider url's content, or domain's name, output to \"sites.txt\"\r\ndef getDomains(url):\r\n response = request.urlopen(url)\r\n page = response.read()\r\n page = page.decode('utf-8')\r\n #print(page)\r\n\r\n var = r'window.open\\(\\'http://\\S+\\'\\)'\r\n rr = re.compile(var)\r\n sites = rr.findall(page)\r\n #print(sites)\r\n\r\n var2 = \"http://[\\w+\\-*.]+\"\r\n rr2 = re.compile(var2)\r\n fp = open(\"sites.txt\", \"a\")\r\n for st in sites:\r\n st = rr2.findall(st)\r\n str = \"\".join(st)\r\n print(str)\r\n fp.write(str+\"\\n\")\r\n fp.close()\r\n\r\ndef main():\r\n#url = 'http://s.tool.chinaz.com/same'\r\n#data = input(\"请输入ip地址: \")\r\n for data in open(\"ipList.txt\", \"rb\"):\r\n url = 'http://s.tool.chinaz.com/same'\r\n data = str(data, encoding=\"utf-8\")\r\n url = url+'?s='+ data\r\n getDomains(url)\r\n\r\nif __name__ == '__main__':\r\n fp = open(\"sites.txt\", \"w\")\r\n fp.close()\r\n main()","sub_path":"ip2domainName.py","file_name":"ip2domainName.py","file_ext":"py","file_size_in_byte":1367,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"314984950","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Apr 8 16:57:34 2021\n\n@author: justi\n\"\"\"\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nclass Spin:\n def __init__(self,name,JHH,JHF):\n self.name = name\n while len(JHH) < 5:\n JHH.append(0)\n self.JHH = JHH\n self.JHF = JHF\n\n\n#parameters \ntime = 100/1000 #100 ms - x axis\ndelta = 20/1000 #delta delay - 20 ms\n\ndef transfer_func(spin,time = time): #plots transfer fuction for perfect echo with HF evolution\n \n x = np.arange(0, time, 0.0001)\n pi = np.pi\n JHF = spin.JHF\n JHH = spin.JHH\n if JHF == 0:\n HF_factor = 0#1\n else:\n HF_factor = np.sin(np.pi*JHF*x)\n term1 = np.cos(np.pi*x*JHH[0])**2 * np.cos(np.pi*JHH[1]*x)**2 * np.cos(np.pi*JHH[2]*x)**2 * np.cos(np.pi*JHH[3]*x)**2\n term2 = np.sin(pi*JHH[0]*x)**2 * np.cos(pi*JHH[1]*x) * np.cos(pi*JHH[2]*x) * np.cos(pi*JHH[3]*x) * np.cos(pi*JHH[4]*x) \n term3 = np.sin(pi*JHH[1]*x)**2 * np.cos(pi*JHH[0]*x) * np.cos(pi*JHH[2]*x) * np.cos(pi*JHH[3]*x) * np.cos(pi*JHH[4]*x) \n term4 = np.sin(pi*JHH[2]*x)**2 * np.cos(pi*JHH[1]*x) * np.cos(pi*JHH[0]*x) * np.cos(pi*JHH[3]*x) * np.cos(pi*JHH[4]*x) \n term5 = np.sin(pi*JHH[3]*x)**2 * np.cos(pi*JHH[1]*x) * np.cos(pi*JHH[2]*x) * np.cos(pi*JHH[0]*x) * np.cos(pi*JHH[4]*x) \n term6 = np.sin(pi*JHH[4]*x)**2 * np.cos(pi*JHH[1]*x) * np.cos(pi*JHH[2]*x) * np.cos(pi*JHH[3]*x) * np.cos(pi*JHH[0]*x) \n \n y = (term1 + term2 + term3 + term4 + term5 + term6) * HF_factor\n \n \n return plt.plot(x,y,label=spin.name)\n\n\ndef transfer_func_delta(spin,delta = delta, time=time): #plots transfer function with delta delay for second spin echo\n \n x = np.arange(0, time, 0.0001)\n pi = np.pi\n JHF = spin.JHF\n JHH = spin.JHH\n delta_factor = np.sin(pi*JHF*(x+delta)) * np.cos(pi*JHH[0]*delta)* np.cos(pi*JHH[1]*delta)* np.cos(pi*JHH[2]*delta) * np.cos(pi*JHH[3]*delta)\n \n term1 = np.cos(np.pi*x*JHH[0])**2 * np.cos(np.pi*JHH[1]*x)**2 * np.cos(np.pi*JHH[2]*x)**2 * np.cos(np.pi*JHH[3]*x)**2\n term2 = np.sin(pi*JHH[0]*x)**2 * np.cos(pi*JHH[1]*x) * np.cos(pi*JHH[2]*x) * np.cos(pi*JHH[3]*x) * np.cos(pi*JHH[4]*x) \n term3 = np.sin(pi*JHH[1]*x)**2 * np.cos(pi*JHH[0]*x) * np.cos(pi*JHH[2]*x) * np.cos(pi*JHH[3]*x) * np.cos(pi*JHH[4]*x) \n term4 = np.sin(pi*JHH[2]*x)**2 * np.cos(pi*JHH[1]*x) * np.cos(pi*JHH[0]*x) * np.cos(pi*JHH[3]*x) * np.cos(pi*JHH[4]*x) \n term5 = np.sin(pi*JHH[3]*x)**2 * np.cos(pi*JHH[1]*x) * np.cos(pi*JHH[2]*x) * np.cos(pi*JHH[0]*x) * np.cos(pi*JHH[4]*x) \n term6 = np.sin(pi*JHH[4]*x)**2 * np.cos(pi*JHH[1]*x) * np.cos(pi*JHH[2]*x) * np.cos(pi*JHH[3]*x) * np.cos(pi*JHH[0]*x) \n \n y = (term1 + term2 + term3 + term4 + term5 + term6) * delta_factor\n \n return plt.plot(x,y,label=spin.name)\n \n\ndef get_xy_data(plot):\n x = (plot[0][0].get_xdata())\n xy = np.empty([len(x),len(plot)+1])\n xy[:,0] = x\n for i in list(range(len(plot))):\n xy[:,i+1] = plot[i][0].get_ydata()\n \n return xy\n \n\n#alpha glucose\ns1 = Spin('H1',[3.9],3.7) #arguments are spin name, list of JHH couplings, JHF coupling\ns2 = Spin('H2',[3.9,9.4],13.1)\ns3 = Spin('H3',[9.5,8.9],54.3)\ns4 = Spin('H4',[8.9,10.2],13.8)\ns5 = Spin('H5',[10.2,2.3,4.9],0)\ns6 = Spin('H6',[2.3,12.2],1.8)\ns6a = Spin(\"H6'\",[5.,12.3],0)\n\n#betaglucose\ns1b = Spin('H1',[8.0],0)\ns2b = Spin('H2',[8.0,9.1],13.7)\ns3b = Spin('H3',[9.1,8.8],52.9)\ns4b = Spin('H4',[8.9,10.],13.8)\ns5b = Spin('H5',[10.0,2.2,5.6],1.3)\ns6b = Spin('H6',[2.2,12.4],1.5)\ns6ab = Spin(\"H6'\",[5.5,12.4],0)\n\n\n#plot1\nplt.figure()\nplot1 = [transfer_func(s1),\ntransfer_func(s2),\ntransfer_func(s3),\ntransfer_func(s4),\ntransfer_func(s5),\ntransfer_func(s6),\ntransfer_func(s6a)]\nplt.legend(bbox_to_anchor=(1.04,0.5), loc=\"center left\")\nplt.title('PE transfer function alpha-glucose')\nxy_alpha = get_xy_data(plot1)\n#plot2\nplt.figure()\nplot2= [transfer_func(s1b),\ntransfer_func(s2b),\ntransfer_func(s3b),\ntransfer_func(s4b),\ntransfer_func(s5b),\ntransfer_func(s6b),\ntransfer_func(s6ab)]\nplt.legend(bbox_to_anchor=(1.04,0.5), loc=\"center left\")\nplt.title('PE transfer function beta-glucose')\nxy_beta = get_xy_data(plot2)\n#plot 3\nplt.figure()\nplot3 = [transfer_func_delta(s1),\ntransfer_func_delta(s2),\ntransfer_func_delta(s3),\ntransfer_func_delta(s4),\ntransfer_func_delta(s5),\ntransfer_func_delta(s6),\ntransfer_func_delta(s6a)]\nplt.legend()\nplt.legend(bbox_to_anchor=(1.04,0.5), loc=\"center left\")\nplt.title('PE transfer function alpha-glucose with delta=' + str(delta))\nxy_alpha_with_delta = get_xy_data(plot3)\n#plot 4\nplt.figure()\nplot4 = [transfer_func_delta(s1b),\ntransfer_func_delta(s2b),\ntransfer_func_delta(s3b),\ntransfer_func_delta(s4b),\ntransfer_func_delta(s5b),\ntransfer_func_delta(s6b),\ntransfer_func_delta(s6ab)]\nplt.legend(bbox_to_anchor=(1.04,0.5), loc=\"center left\")\nplt.title('PE transfer function beta-glucose with delta=' + str(delta))\nxy_beta_with_delta = get_xy_data(plot4)\n\n\n","sub_path":"perfect echo.py","file_name":"perfect echo.py","file_ext":"py","file_size_in_byte":4902,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"71767757","text":"#!/usr/bin/env python\n\n\"\"\"\ndbupdater.py: Scrapes all UNSW COMP courses and populates the data into a MongoDB database (mlab)\n Scrapes all the programming languages (on wiki) and puts it in to the database\nNOTES:\n- Collections are the tables in SQL\n- Inserting a document is same as inserting a row in SQL\n- Example of a document { 'key 1' : value 1, \n 'key 2' : value 2,\n 'key 3' : value 3 } \n -> SQL version would be |key 1|key 2|key 3| (columns) and |value 1|value 2|value 3| (a row)\n\"\"\"\n\n# import statements\nfrom bs4 import BeautifulSoup\nfrom datetime import datetime\nfrom pymongo import MongoClient\nimport urllib.request\nimport re\n\n# add document to database (checks if document already exists first)\n# input parameters:\n# - document: A row of data\n# - collection_name: The collection where the row of data is to be stored\ndef add_doc(document, collection_name):\n collection = db[collection_name] # getting the right collection (if it doesn't exist, it will create it) \n # to store the documents\n if collection.count_documents(document, limit = 1) == 0:\n collection.insert_one(document)\n else:\n print(\"Document already exists in database!\")\n\n# scrape all COMP courses and any additional useful data\n# input parameters:\n# - base_url: The url to scrape the COMP courses (i.e. UNSW Timetable for COMP)\ndef scrape_courses(base_url):\n try:\n webpage = urllib.request.urlopen(base_url) # connect to UNSW website for COMP timetables\n except:\n print('Error! URL is invalid.')\n\n soup = BeautifulSoup(webpage, 'html.parser')\n tables = soup.find_all('table') # get the table of elements that contains the \n # code for the comp courses along with the course name\n for table in [tables[8], tables[11]]:\n # tables[8] = Undergraduate Courses, tables[11] = Postgraduate Courses \n # get the course code and name elements from the table\n tr = table.find_all('a', href=re.compile(r'[A-Z]{4}[0-9]{4}\\.html'))\n \n for i in range(0, len(tr), 2): # fetch pairwise items (course_code, course_name)\n course_code = tr[i].text \n course_name = tr[i+1].text\n doc = { 'code': course_code, \n 'name': course_name }\n add_doc(doc, 'comp_courses') # add document to collection (if it does not exist)\n\n# get the list of all the programming languages in Wikipedia\n# input parameters:\n# - base_url: The url to scrape the list of programming languages\ndef scrape_prog(base_url):\n try:\n webpage = urllib.request.urlopen(base_url) # connect to Wikipedia page for the programming languages list\n except:\n print('Error! URL is invalid.')\n\n # fetch all the lists in the html code and find the ones with the programming languages\n soup = BeautifulSoup(webpage, 'html.parser')\n lists = soup.find_all('ul')\n\n # lists of all the programming languages [A to Z] are the lists[5],...,lists[31]\n # each lists has bullet points of programming languages\n for prog_list in lists[5:32]: \n bullet_pts = prog_list.find_all('li')\n for bullet in bullet_pts:\n prog_lang = str(bullet.text).strip().rstrip() # programming language from the list\n doc = { 'name': prog_lang }\n add_doc(doc, 'prog_langs') # add document to collection (if it does not exist)\n\n# DEBUGGING ONLY: Print the first five rows of data from each collection\ndef display_db():\n # fetch the first five documents in the collections\n collections = db.list_collection_names()\n for collection_name in collections:\n if collection_name not in ['objectlabs-system.admin.collections', 'objectlabs-system', 'system.indexes']: # ignore system collections\n print(\"COLLECTION NAME:\", collection_name)\n collection = db[collection_name]\n for doc in collection.find({}, {'_id': 0}).limit(5): # print all keys except the '_id' key\n print(doc)\n print(\"\")\n\nif __name__ == \"__main__\":\n # connect to the MongoDB account (mlab)\n credientials = open('db_credentials.txt', 'r') # external file storing the credentials\n conn_url = credientials.readline().rstrip() # get the database connection url\n client = MongoClient(conn_url) # connect to the database remotely\n db = client['code-unity-database'] # selecting the database\n \n # scrape the COMP courses from UNSW timetable in the current year\n curr_year = datetime.now().year\n courses_url = \"http://timetable.unsw.edu.au/\" + str(curr_year) + \"/COMPKENS.html\"\n #scrape_courses(courses_url) # comment this out if DEBUGGING below\n\n # scrape all the programming laguages list from Wikipedia\n prog_list_url = \"https://en.wikipedia.org/wiki/List_of_programming_languages\"\n #scrape_prog(prog_list_url) # comment this out if DEBUGGING below \n \n # DEBUGGING ONLY: Print first five rows of data from each collection\n display_db()","sub_path":"scraper.py","file_name":"scraper.py","file_ext":"py","file_size_in_byte":5129,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"199324193","text":"import airflow\n\nfrom airflow import DAG\n\nfrom airflow.contrib.operators.snowflake_operator import SnowflakeOperator\n#from airflow.operators import TriggerDagRunOperator\n\nargs = {\n 'owner': 'airflow',\n 'email': ['swapnilspra@gmail.com'],\n 'depends_on_past': False,\n 'start_date': airflow.utils.dates.days_ago(0)\n}\n\n\ndef auto_confirm_run_dag(context, dag_run_obj):\n return (dag_run_obj)\n\ndag = DAG(dag_id='A_Snowflake_operator1', default_args=args, schedule_interval='@daily')\t\n\n\n\nETL_SCHEMA_SETUP = SnowflakeOperator(\n task_id='ETL_Schema_setup',\n snowflake_conn_id='snowflake_default', \n sql=['DROP SCHEMA IF EXISTS __ETL_DAILY_SCHEMA__;', 'CREATE SCHEMA IF NOT EXISTS __ETL_DAILY_SCHEMA__;'],\n warehouse='ISC_DW',\n database='INFOSCOUT_SANDBOX',\n dag=dag\n )\n\nsql_File = '/sql/__ETL_DAILY_SCHEMA__user.sql'\nsql_insert= '/sql/ETL_USER_INSERT.sql'\n\nETL_USER = SnowflakeOperator(\n task_id='ETL_user',\n snowflake_conn_id='snowflake_default', \n sql=['DROP TABLE IF EXISTS __ETL_DAILY_SCHEMA__.user CASCADE;',sql_File,sql_insert],\n warehouse='ISC_DW',\n database='INFOSCOUT_SANDBOX',\n dag=dag\n )\n\nsql_full_receipt_insert= '/sql/ETL_FULL_RECEIPT_INSERT.sql'\n\nFULL_RECEIPT_BATCH = SnowflakeOperator(\n task_id='Full_receipt',\n snowflake_conn_id='snowflake_default', \n sql=['DROP TABLE IF EXISTS __ETL_DAILY_SCHEMA__.etl_batch CASCADE;', 'CREATE TABLE __ETL_DAILY_SCHEMA__.etl_batch ( receipt_id integer NOT NULL);',sql_full_receipt_insert],\n warehouse='ISC_DW',\n database='INFOSCOUT_SANDBOX',\n dag=dag\n )\n\n\n#trigger = TriggerDagRunOperator (\n# task_id='start-SnowflakeDag2',\n# trigger_dag_id=\"A_snowflake_operator2\",\n# python_callable=auto_confirm_run_dag,\n# dag=dag\n# )\n\n\n\n\n#ETL_SCHEMA_SETUP.set_downstream(ETL_SCHEMA_SETUP)\nETL_SCHEMA_SETUP.set_downstream(ETL_USER)\nETL_SCHEMA_SETUP.set_downstream(FULL_RECEIPT_BATCH)\n#ETL_USER.set_downstream(trigger)\n\n","sub_path":"airflow/airflow/dags/SnowflakeDag1.py","file_name":"SnowflakeDag1.py","file_ext":"py","file_size_in_byte":1891,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"550609770","text":"T = int(input())\n\nfor tc in range(1, T+1):\n N = int(input())\n pascal = [[0]*(k+1) for k in range(N)]\n pascal[0][0] = 1\n\n for i in range(1, N):\n for j in range(i+1):\n if j == 0 or j == i:\n pascal[i][j] = 1\n else:\n pascal[i][j] = pascal[i-1][j-1] + pascal[i-1][j]\n\n print('#{}'.format(tc))\n for row in pascal:\n print(*row)\n","sub_path":"swea/0811_2005.py","file_name":"0811_2005.py","file_ext":"py","file_size_in_byte":405,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"135970149","text":"from functools import wraps\nimport telegram\nfrom telegram import Update, ReplyKeyboardMarkup, ChatAction, InlineKeyboardButton, InlineKeyboardMarkup\nfrom telegram.ext import CallbackContext\n\nimport config\nfrom db_manager import DB_manager\nfrom services.mail_traking_notifycations import short_report, full_report\n\ndb_manager = DB_manager()\nbot = telegram.Bot(token=config.TOKEN)\n\n\ndef send_typing_action(func):\n \"\"\"Sends typing action while processing func command.\"\"\"\n\n @wraps(func)\n def command_func(update, context, *args, **kwargs):\n context.bot.send_chat_action(chat_id=update.effective_message.chat_id, action=ChatAction.TYPING)\n return func(update, context, *args, **kwargs)\n\n return command_func\n\n\n\n\n\n\n\n@send_typing_action\ndef StartHandler(update: Update, context: CallbackContext):\n # b.write_user_position(update.message.chat_id, \"main\")\n\n print(f\"New message from {update.message.chat_id} , text : {update.message.text}\")\n\n\n user_id = update.message.from_user.id\n if not db_manager.user_exist(user_id): db_manager.add_user(user_id)\n db_manager.update_user_position(user_id, \"StartHandler\")\n db_manager.debug_info()\n\n keyboard = [\n [telegram.KeyboardButton(\"Добавить отправление ➕\")],\n [telegram.KeyboardButton(\"Мои отправления ✉\")]\n ]\n\n reply_markup = ReplyKeyboardMarkup(keyboard)\n update.message.reply_text('Пожалуйста выберете!', reply_markup=reply_markup)\n\n@send_typing_action\ndef AddDeparture(update: Update, context: CallbackContext):\n # b.write_user_position(update.message.chat_id, \"main\")\n print(f\"New message from {update.message.chat_id} , text : {update.message.text}\")\n\n\n user_id = update.message.from_user.id\n db_manager.update_user_position(user_id, \"AddDeparture\")\n db_manager.debug_info()\n\n keyboard = [\n [telegram.KeyboardButton(\"Назад ◀️\")],\n ]\n\n reply_markup = ReplyKeyboardMarkup(keyboard)\n update.message.reply_text(\"Трек номер:\", reply_markup=reply_markup)\n\n@send_typing_action\ndef MyDepartures(update: Update, context: CallbackContext):\n print(f\"New message from {update.message.chat_id} , text : {update.message.text}\")\n\n\n user_id = update.message.from_user.id\n db_manager.update_user_position(user_id, \"MyDepartures\")\n db_manager.debug_info()\n\n keyboard = [\n [telegram.KeyboardButton(\"Назад ◀️\")],\n ]\n\n if len(db_manager.get_user_departures(user_id)) == 0:\n departures = \"Нет отправлений\"\n else:\n departures = db_manager.get_user_departures(user_id)\n\n reply_markup = ReplyKeyboardMarkup(keyboard)\n update.message.reply_text(departures, reply_markup=reply_markup)\n\n@send_typing_action\ndef Other(update: Update, context: CallbackContext):\n # b.write_user_position(update.message.chat_id, \"main\")\n\n user_id = update.message.from_user.id\n position = db_manager.get_user_position(user_id)[0]\n db_manager.debug_info()\n if position == \"AddDeparture\":\n response = short_report(update.message.text)\n if response != \"Трек код не найден\":\n\n db_manager.add_user_departures(user_id, update.message.text, response)\n keyboard = [\n [\n InlineKeyboardButton(\"Полный отчет\", callback_data='full_report|'+update.message.text),\n ]\n ]\n reply_markup = InlineKeyboardMarkup(keyboard)\n update.message.reply_text(response, reply_markup=reply_markup)\n else:\n bot.send_message(update.message.chat_id, response)\n\n print(f\"New message from {update.message.chat_id} , text : {update.message.text}\")\n\n\ndef button(update: Update, context: CallbackContext):\n query = update.callback_query\n\n # CallbackQueries need to be answered, even if no notification to the user is needed\n # Some clients may have trouble otherwise. See https://core.telegram.org/bots/api#callbackquery\n query.answer()\n if query.data.split(\"|\")[0] == \"full_report\":\n query.edit_message_text(text=full_report(query.data.split(\"|\")[1]))","sub_path":"handlers.py","file_name":"handlers.py","file_ext":"py","file_size_in_byte":4161,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"545891998","text":"import numpy as np\nimport matplotlib.pyplot as plt\n\n\ndef func(x):\n return np.tan(0.5*x+0.2)-x*x\n\n\ndef func2(x):\n return abs(x) * (np.tan(0.5*x+0.2)-x*x)\n\n\na = int(input())\n#points = np.linspace(-1, 1, a) дефолтное разбиение\npoints = [np.cos(((2*i - 1) / (2 * a)) * np.pi) for i in range(a)] #чебыш\nprint (points)\nLagrange = np.poly1d(np.zeros(a))\nfor i in range(0, a):\n omega = np.poly(np.concatenate((points[0:i], points[i+1:])))\n Li = omega / np.polyval(omega, points[i])\n Lagrange = np.polyadd(Lagrange, func(points[i]) * Li)\ncoordX = np.linspace(-1, 1, 100)\ncoordY1 = func(coordX)\ncoordY2 = np.polyval(Lagrange, coordX)\nfig, ax = plt.subplots()\nax.plot(coordX, coordY1, color=\"blue\", label=\"func1\")\nax.plot(coordX, coordY2, color=\"red\", label=\"interpolation\")\nplt.show()\nprint(Lagrange)\n\n","sub_path":"interpolation.py","file_name":"interpolation.py","file_ext":"py","file_size_in_byte":830,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"407073347","text":"m_rating = open(\"C:/Users/Gaoxiang/Desktop/232E/PROJ2/project_2_data/movie_rating.txt\",\"r\")\nm_ID = open(\"C:/Users/Gaoxiang/Desktop/232E/PROJ2/project_2_data/MoiveID.txt\",\"r\")\nID_R = open(\"C:/Users/Gaoxiang/Desktop/232E/PROJ2/project_2_data/IDRating.txt\",\"w\")\n\nratingDict={}\nfor lines in m_rating.readlines(): \n tokens=lines.split(\"\\t\\t\") \n ratingDict[tokens[0].replace('\\n','')]=tokens[1].replace('\\n','')\nprint (ratingDict[tokens[0]])\nprint (tokens[0])\nidDict={}\nfor lines in m_ID.readlines():\n tokens=lines.split(\"\\t\")\n idDict[tokens[0].replace('\\n','')]=tokens[1].replace('\\n','')\n\nprint (idDict[tokens[0]])\n\nfor movie in idDict:\n if movie in ratingDict:\n s='%s\\t%s\\n'%(str(idDict[movie]),str(ratingDict[movie]))\n ID_R.write(s)\nm_rating.close()\nm_ID.close()\nID_R.close()","sub_path":"project2/P7_ID_Rating.py","file_name":"P7_ID_Rating.py","file_ext":"py","file_size_in_byte":808,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"619220522","text":"class Automovil:\n def __init__(self, modelo,marca,color,estado, motor):\n self._modelo= modelo\n self._marca = marca\n self._color = color\n self._estado = 'en reposo'\n self._motor = motor(cilindro = 5)\n\n def acelerar(self, tipo = 'despacio'):\n if tipo == 'rapido':\n self._motor.inyecta_gasolina(10)\n else:\n self._motor.inyecta_gasolina(3)\n self._estado = 'en movimiento'\n \n\nclass Motor:\n def __init__(self, cilindros, tipo ='gasolina'):\n self._cilindros = cilindros\n self._tipo = tipo\n self._temperatura = 0\n \n def inyecta_gasolina(self,cantidad ):\n self._cantidad = 20\n print('La cantidad de Gasolina es {}'.format(self._cantidad))\n pass\n\nif __name__== \"__main__\":\n motor = Motor('Roberto', 'Renault')\n motor.inyecta_gasolina(cantidad=20)\n\n\n\n","sub_path":"TALLER_PYHTON/exercises_Python/asociacion.py","file_name":"asociacion.py","file_ext":"py","file_size_in_byte":888,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"261884077","text":"import numpy as np\nimport cv2\n\n\ncap = cv2.VideoCapture(1)\nfgbg = cv2.BackgroundSubtractorMOG(30, 4, 0.1)\n\nwhile(True):\n ret, frame = cap.read()\n frame = cv2.flip(frame, 1)\n frame = cv2.resize(frame, None, fx=0.5, fy=0.5, interpolation=cv2.INTER_CUBIC)\n gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)\n\n fgmask = fgbg.apply(frame)\n\n cv2.imshow('mask', fgmask)\n\n if cv2.waitKey(1) & 0xFF == ord('q'):\n break\n\ncap.release()\ncv2.destroyAllWindows()\n","sub_path":"bgmask.py","file_name":"bgmask.py","file_ext":"py","file_size_in_byte":472,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"157801529","text":"import os\n\nfrom torch.utils.data import DataLoader\nfrom torchvision import transforms\n\nfrom dataset.kaggle_casting_dataset import KaggleCastingDataset\nfrom logger import logger\nfrom properties import APPLICATION_PROPERTIES\n\n\nclass DatasetFactory(object):\n\n def __init__(self):\n self.train_dataset = None\n self.val_dataset = None\n self.test_dataset = None\n\n self.train_dataloader = None\n self.val_dataloader = None\n self.test_dataloader = None\n\n @classmethod\n def create(cls, data_name):\n dataset_factory = cls()\n\n train_dataset = None\n val_dataset = None\n test_dataset = None\n\n train_dataloader = None\n val_dataloader = None\n test_dataloader = None\n\n if data_name == \"kaggle_casting_data\":\n train_dataset = KaggleCastingDataset(\n root=os.path.join(APPLICATION_PROPERTIES.DATA_DIRECTORY_PATH, \"kaggle_casting_data\", \"train\"),\n transform=transforms.Compose([\n transforms.Grayscale(),\n transforms.ToTensor()\n ])\n )\n test_dataset = KaggleCastingDataset(\n root=os.path.join(APPLICATION_PROPERTIES.DATA_DIRECTORY_PATH, \"kaggle_casting_data\", \"test\"),\n transform=transforms.Compose([\n transforms.Grayscale(),\n transforms.ToTensor()\n ])\n )\n\n train_dataloader = DataLoader(\n dataset=train_dataset,\n batch_size=32,\n shuffle=True\n )\n test_dataloader = DataLoader(\n dataset=test_dataset,\n batch_size=32,\n shuffle=False\n )\n elif data_name == \"data_1\":\n pass\n\n # Set\n dataset_factory.train_dataset = train_dataset\n dataset_factory.val_dataset = val_dataset\n dataset_factory.test_dataset = test_dataset\n\n dataset_factory.train_dataloader = train_dataloader\n dataset_factory.val_dataloader = val_dataloader\n dataset_factory.test_dataloader = test_dataloader\n\n logger.info(f\"Data selected : '{data_name}'\")\n return dataset_factory\n","sub_path":"dataset/factory.py","file_name":"factory.py","file_ext":"py","file_size_in_byte":2246,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"287395176","text":"from urllib.request import urlopen\nfrom io import StringIO\nimport csv\n\nhtml = \"http://pythonscraping.com/files/MontyPythonAlbums.csv\"\ndata = urlopen(html).read().decode(\"ascii\", \"ignore\")\ndata_file = StringIO(data)\ncsvreader = csv.reader(data_file)\n\n# for row in csvreader:\n# \tprint(\"The album \\\"\" + row[0] + \"\\\" was released in \" + str(row[1]))\n\n############ Alternative printer\ndictreader = csv.DictReader(data_file)\nprint(dictreader.fieldnames)\nfor row in dictreader:\n\tprint(row)","sub_path":"Python/scraping/oreily/basic/down_csv.py","file_name":"down_csv.py","file_ext":"py","file_size_in_byte":482,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"643047156","text":"print(\"Responda as perguntas para identificarmos a sua condição atual\\\r\nResponda S para sim e N para não.\")\r\nv = []\r\np1 = input(\"Telefonou para vítima?: \")\r\nv.append(p1)\r\n\r\np2 = input(\"Esteve no local do crime?: \")\r\nv.append(p2)\r\n\r\np3 = input(\"Mora perto da vítima?: \")\r\nv.append(p3)\r\n\r\np4 = input(\"Devia para a vítima?: \")\r\nv.append(p4)\r\n\r\np5 = input(\"Já trabalhou com a vítima?: \")\r\nv.append(p5)\r\n\r\ncont = 0\r\nfor i in range(5):\r\n if v[i] == 's':\r\n cont+=1\r\n\r\nif cont == 5:\r\n print(\"ASSASSINO TU ÉS!\")\r\nelif cont == 3 or cont ==4:\r\n print(\"CÚMPLICE!\")\r\nelif cont ==2:\r\n print(\"suspeito apenas.\")\r\nelse:\r\n print(\"Você não é suspeito.\")\r\n","sub_path":"perguntas com string.py","file_name":"perguntas com string.py","file_ext":"py","file_size_in_byte":672,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"463856270","text":"##直接作用于for循环的数据类型:\r\n#1.集合数据类型:如list,tuple,dict,set,str等\r\n#2.generator:生成器和带yield的generator function\r\n#这些可以直接作用于for循环的对象统称��可迭代对象:Iterable对象\r\n\r\n\r\n##1********\r\n#可以使用isinstance()判断一个对象是否是Iterable的对象:\r\nfrom collections import Iterable\r\nisinstance([],Iterable) #list\r\nisinstance({},Iterable) #tuple\r\nisinstance('abc',Iterable) #str\r\nisinstance((x for x in range(10)),Iterable) #generator\r\nisinstance(100,Iterable) #-》False\r\n\r\n#True,False在Shell中\r\n\r\n##2*********\r\n#instance()判断是否是Iterator\r\nfrom collections import Iterator\r\nisinstance((x for x in range(10)),Iterator) #T\r\nisinstance([],Iterator) #F\r\nisinstance({},Iterator) #F\r\nisinstance('abc',Iterator) #F\r\n#generator是Iterator对象,但list、dict、str是Iterable,却不是Iterator\r\n\r\n#可作用于for循环 #可被next不断调用并返回下一个值\r\n#Iterable对象 > #迭代器:Iterator >#生成器:generator\r\n\r\n\r\n##3*****Iterable—>Iterator:iter()\r\nisinstance(iter([]),Iterator)\r\nisinstance(iter('abc'),Iterator)\r\n\r\n#Iterator表示一个惰性序列,只有在需要下一个数据时才会计算\r\n\r\n\r\n##4***********\r\n#for循环本质上就是通过不断调用next()函数实现的:\r\nfor x in [1,2,3,4,5]:\r\n pass\r\n#完全等价于:\r\nit = iter([1,2,3,4,5]) #首先获得Iterator对象\r\n#循环:\r\nwhile True:\r\n try:\r\n #获得下一个值\r\n x = next(it)\r\n except StopIteration:\r\n #退出循环\r\n break\r\n\r\n#可迭代对象中的元素都是存放在内存中,都是有限的,\r\n#而迭代器的对象本质上可以不包含元素,而是通过next()来不断获取。\r\n\r\n\r\n\r\n#question:\r\n#为何?\r\n##o=triangles()\r\n##next(o)\r\n##next(o)\r\n##这种值会不断迭代,\r\n##而\r\n##next(triangles())\r\n##next(triangles())\r\n##却一直返回[1]?\r\n#o=triangles() next(o) next(o)是对同一个对象进行迭代,\r\n##next(triangles()) next(triangles())两次next是对不同对象进行迭代,\r\n##每一次triangles()返回的都是一个新的对象\r\n","sub_path":"18-高级特性之迭代器.py","file_name":"18-高级特性之迭代器.py","file_ext":"py","file_size_in_byte":2326,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"73450658","text":"import shlex\nimport os\nfrom jose import jwt\n\nfrom jumpscale import j\n\nfrom zerorobot.config.data_repo import _parse_zdb\n\nlogger = j.logger.get('zrobot_statup')\n\niyo_pub_key = \"\"\"-----BEGIN PUBLIC KEY-----\nMHYwEAYHKoZIzj0CAQYFK4EEACIDYgAES5X8XrfKdx9gYayFITc89wad4usrk0n2\n7MjiGYvqalizeSWTHEpnd7oea9IQ8T5oJjMVH5cc0H5tFSKilFFeh//wngxIyny6\n6+Vq5t5B0V0Ehy01+2ceEon2Y0XDkIKv\n-----END PUBLIC KEY-----\"\"\"\n\n\ndef configure_local_client():\n j.sal.fs.createDir('/opt/code/local/stdorg/config/j.clients.zos_protocol')\n j.sal.fs.writeFile('/opt/code/local/stdorg/config/j.clients.zos_protocol/local.toml', \"\"\"\n db = 0\n host = '127.0.0.1'\n password_ = ''\n port = 6379\n ssl = true\n timeout = 120\n unixsocket = '/tmp/redis.sock'\n \"\"\")\n\n\ndef get_admin_organization(kernel_args):\n \"\"\"\n decide which organization to use to protect admin endpoint of the 0-robot API\n\n first we check if there is a farmer_id token\n if it exists, we extract the organization from it and use it\n if it doesn't we check if there is an organization kernel parameter and use it\n if still don't have an organization, we return None\n \"\"\"\n\n org = None\n token = kernel_args.get('farmer_id')\n if token:\n try:\n claims = jwt.decode(token, iyo_pub_key)\n except jwt.ExpiredSignatureError:\n logger.info(\"farmer_id expired, trying to refresh\")\n try:\n token = j.clients.itsyouonline.refresh_jwt_token(token)\n except Exception as err:\n logger.error('fail to refresh farmer_id. \\\n To fix this, generate a new farmer id, update your kernel with it and reboot the machine')\n raise\n\n claims = jwt.decode(token, iyo_pub_key)\n\n for scope in claims.get('scope'):\n if scope.find('user:memberof:') != -1:\n org = scope[len('user:memberof:'):]\n break\n else:\n org = kernel_args.get('admin_organization')\n if not org:\n org = kernel_args.get('organization')\n\n logger.info(\"admin organization found: %s\" % org)\n return org\n\n\ndef get_user_organization(kernel_args):\n org = kernel_args.get('user_organization')\n if org:\n logger.info(\"user organization found: %s\" % org)\n return org\n\n\ndef read_kernel():\n \"\"\"\n read the kernel parameter passed to the host machine\n return a dict container the key/value of the arguments\n \"\"\"\n with open('/proc/cmdline') as f:\n line = f.read()\n\n args = {}\n line = line.strip()\n for kv in shlex.split(line):\n ss = kv.split('=', 1)\n if len(ss) == 2:\n args[ss[0]] = ss[1]\n elif len(ss) <= 1:\n args[ss[0]] = None\n return args\n\n\ndef migrate_from_zeroos_to_threefold():\n zeroos_services = '/opt/var/data/zrobot/zrobot_data/github.com/zero-os'\n if j.sal.fs.exists(zeroos_services):\n j.sal.fs.removeDirTree(zeroos_services)\n\n\ndef read_config_repo_config():\n \"\"\"\n detect if zdb data repository is configured and return the url to the zdb if any\n\n :return: zdb url or None if not configured\n :rtype: str or None\n \"\"\"\n\n logger.info(\"detect if zdb data repository is configured\")\n\n data_path = '/opt/var/data/zrobot/zrobot_data/data_repo.yaml'\n if not j.sal.fs.exists(data_path):\n logger.info(\"no zdb data repository configuration found\")\n return None\n\n repo = j.data.serializer.yaml.load(data_path)\n zdb_url = repo.get('zdb_url')\n if not zdb_url:\n logger.error(\"wrong format in zdb data repository configuration\")\n return None\n\n try:\n _parse_zdb(zdb_url)\n return zdb_url\n except ValueError:\n logger.error(\"zdb url has wrong format in zdb data repository configuration: %s\", zdb_url)\n return None\n\n\ndef start_robot():\n kernel_args = read_kernel()\n args = ['zrobot', 'server', 'start', '--mode', 'node']\n\n admin_org = get_admin_organization(kernel_args)\n if admin_org:\n args.extend(['--admin-organization', admin_org])\n\n user_org = get_user_organization(kernel_args)\n if user_org:\n args.extend(['--user-organization', user_org])\n\n if 'development' in kernel_args or 'god' in kernel_args or 'support' in kernel_args:\n args.append('--god')\n\n zdb_url = read_config_repo_config()\n if zdb_url:\n args.extend(['--data-repo', zdb_url])\n\n template_repo = 'https://github.com/threefoldtech/0-templates#development'\n args.extend(['--template-repo', template_repo])\n\n logger.info('starting node robot: %s', ' '.join(args))\n\n os.execv('usr/local/bin/zrobot', args)\n\n\ndef main():\n migrate_from_zeroos_to_threefold()\n configure_local_client()\n start_robot()\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"utils/scripts/autobuild/startup.py","file_name":"startup.py","file_ext":"py","file_size_in_byte":4773,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"71050482","text":"import datetime\nimport time\nfrom enum import Enum\n\nimport click\nimport vk\nfrom vk.exceptions import VkAPIError\n\ntoday = datetime.date.today()\nADULT_BIRTH_DATE = datetime.date(today.year - 18, today.month, today.day)\n\nBAN_COMMENTARY = 'Бан по ограничению 18+ (предварительно). Для разбана/подтверждения возраста написать любому из ' \\\n 'администраторов группы.'\n\naccess_token = \"TOKEN\"\nsession = vk.Session(access_token=access_token)\nvk_api = vk.API(session, v='5.92')\n\n\nclass Status(Enum):\n is_adult = 'adult'\n not_adult = 'not_adult'\n unknown = 'unknown'\n\n\nclass Subscriber:\n id: int\n status: Status\n\n def __init__(self, id: int, status: Status) -> None:\n self.id = id\n self.status = status\n\n def ban(self):\n try:\n vk_api.groups.ban(\n group_id=121768940,\n owner_id=self.id,\n comment=BAN_COMMENTARY,\n comment_visible=1\n )\n except VkAPIError as e:\n if 'Captcha needed' not in e.message:\n raise e\n data = e.error_data\n captcha_sid = data.get('captcha_sid')\n captcha_img = data.get('captcha_img')\n\n print(f'CAPTCHA LINK {captcha_img}')\n captcha_key = input('Input text from captcha: ')\n\n try:\n vk_api.groups.ban(\n group_id=121768940,\n owner_id=self.id,\n comment=BAN_COMMENTARY,\n comment_visible=1,\n captcha_sid=captcha_sid,\n captcha_key=captcha_key\n )\n except:\n pass\n\n\ndef fetch_items(func, **kwargs):\n result = list()\n count, counter = 1, 0\n while counter < count:\n response = func(offset=counter, **kwargs)\n count = response.get('count')\n items = response.get('items')\n result.extend(items)\n counter += len(items)\n time.sleep(0.5)\n return result\n\n\ndef has_birth_year(bdate: str):\n dot_count = bdate.count('.')\n if dot_count >= 2:\n return True\n return False\n\n\ndef is_adult(birth_date: datetime.date):\n return birth_date <= ADULT_BIRTH_DATE\n\n\ndef str_to_date(birth_date: str) -> datetime.date:\n birth_date_split = birth_date.split('.')\n return datetime.date(\n day=int(birth_date_split[0]),\n month=int(birth_date_split[1]),\n year=int(birth_date_split[2])\n )\n\n\ndef main(count: int):\n banned_users = fetch_items(vk_api.groups.getBanned, group_id=121768940, count=200)\n subscribers = fetch_items(vk_api.groups.getMembers, group_id='box_review', fields='bdate')\n\n banned_ids = [user['profile']['id'] for user in banned_users if user.get('profile')]\n\n subscribers_data = list()\n for user in subscribers:\n _id = user.get('id')\n bdate = user.get('bdate')\n\n if _id in banned_ids:\n print(f'User {_id} already banned')\n continue\n\n if not bdate:\n subscribers_data.append(Subscriber(id=_id, status=Status.unknown))\n continue\n\n if not has_birth_year(bdate):\n subscribers_data.append(Subscriber(id=_id, status=Status.unknown))\n continue\n\n if is_adult(str_to_date(bdate)):\n subscribers_data.append(Subscriber(id=_id, status=Status.is_adult))\n continue\n\n subscribers_data.append(Subscriber(id=_id, status=Status.not_adult))\n\n children = [sub for sub in subscribers_data if sub.status in [Status.not_adult]]\n\n print(f'{len(children)} users wil be banned')\n for child in children:\n print(f'Ban user {child.id}')\n child.ban()\n print(f'User {child.id} successfully banned')\n time.sleep(0.3)\n\n print('Done')\n\n\n@click.command()\n@click.option('--count',\n default=200,\n type=int,\n help='Amount of users will be banned at this session, 0 if you want ban all users'\n )\ndef ban(count):\n click.echo(f'count {count}')\n\n\nif __name__ == '__main__':\n ban()\n","sub_path":"script.py","file_name":"script.py","file_ext":"py","file_size_in_byte":4181,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"357486447","text":"from rest_framework import mixins, viewsets\nfrom django.http import JsonResponse\nfrom . import models\nfrom . import serializers\n\n\nclass AccountViewSet(mixins.ListModelMixin,\n mixins.UpdateModelMixin,\n mixins.RetrieveModelMixin,\n mixins.CreateModelMixin,\n viewsets.GenericViewSet):\n \"\"\"\n API endpoint that allows accounts to be viewed.\n\n list:\n Return all the accounts available.\n\n create:\n Create an account.\n\n update:\n Update an account.\n\n retrieve:\n Return a given account.\n \"\"\"\n\n model = models.Account\n serializer_class = serializers.AccountSerializer\n queryset = models.Account.objects.all()\n\n\n def get_serializer_class(self):\n serializer_class = self.serializer_class\n\n if self.request.method == 'PUT':\n serializer_class = serializers.AccountWithoutName\n\n return serializer_class\n\n\n\n\ndef fizzbuzz(request):\n x = request.GET.get('x', 100)\n x = int(x)\n\n response = {'x': x, \"fizzbuzz\": ''.join((solve_fizz(i) for i in range(1,x)))}\n return JsonResponse(response)\n\n\ndef fizzbuzz2(request):\n x = request.GET.get('x', 100)\n x = int(x)\n\n response = {'x': x, \"fizzbuzz\": [solve_fizz(i) for i in range(1,x)]}\n return JsonResponse(response)\n\n\ndef solve_fizz(x: int)->str:\n ans = ''\n if x % 3 == 0:\n ans += 'Fizz'\n\n if x%5 == 0:\n ans += 'Buzz'\n\n if not ans:\n return str(x)\n\n return ans","sub_path":"challenge/accounts/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1534,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"632803322","text":"\"\"\"initial\n\nRevision ID: 5acf5349484\nRevises: None\nCreate Date: 2015-10-06 20:27:34.051765\n\n\"\"\"\n\n# revision identifiers, used by Alembic.\nrevision = '5acf5349484'\ndown_revision = None\n\nfrom alembic import op\nimport sqlalchemy as sa\n\n\ndef upgrade():\n ### commands auto generated by Alembic - please adjust! ###\n op.create_table('pessoas',\n sa.Column('id', sa.Integer(), nullable=False),\n sa.Column('telefone', sa.String(length=11), nullable=True),\n sa.Column('celular', sa.String(length=11), nullable=True),\n sa.Column('type', sa.String(length=50), nullable=True),\n sa.PrimaryKeyConstraint('id')\n )\n op.create_table('candidatos',\n sa.Column('id', sa.Integer(), nullable=False),\n sa.Column('nome', sa.String(length=64), nullable=False),\n sa.ForeignKeyConstraint(['id'], ['pessoas.id'], ),\n sa.PrimaryKeyConstraint('id')\n )\n op.create_table('empregadores',\n sa.Column('id', sa.Integer(), nullable=False),\n sa.Column('empresa', sa.String(length=64), nullable=False),\n sa.ForeignKeyConstraint(['id'], ['pessoas.id'], ),\n sa.PrimaryKeyConstraint('id')\n )\n op.create_table('usuarios',\n sa.Column('id', sa.Integer(), nullable=False),\n sa.Column('email', sa.String(length=64), nullable=False),\n sa.Column('senha_hash', sa.String(length=128), nullable=False),\n sa.Column('status', sa.String(length=25), nullable=False),\n sa.Column('id_pessoa', sa.Integer(), nullable=False),\n sa.ForeignKeyConstraint(['id_pessoa'], ['pessoas.id'], ),\n sa.PrimaryKeyConstraint('id')\n )\n op.create_index(op.f('ix_usuarios_email'), 'usuarios', ['email'], unique=True)\n ### end Alembic commands ###\n\n\ndef downgrade():\n ### commands auto generated by Alembic - please adjust! ###\n op.drop_index(op.f('ix_usuarios_email'), table_name='usuarios')\n op.drop_table('usuarios')\n op.drop_table('empregadores')\n op.drop_table('candidatos')\n op.drop_table('pessoas')\n ### end Alembic commands ###\n","sub_path":"migrations/versions/5acf5349484_initial.py","file_name":"5acf5349484_initial.py","file_ext":"py","file_size_in_byte":1970,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"446041177","text":"#! /usr/bin/env python\nfrom __future__ import print_function\n\nimport sys\nimport copy\nimport rospy\nimport moveit_commander\nimport moveit_msgs.msg as moveit_msg_lib\nimport std_msgs.msg as standard_mag_lib\nimport geometry_msgs.msg as geometry_msg_lib\nfrom math import pi\nfrom math import radians, degrees\nfrom std_msgs.msg import String\nfrom moveit_commander.conversions import pose_to_list\n\nrobot_model = \"UR3\"\n\nrobot, scene, move_group, display_trajectory_publisher, planning_frame, eef_link, group_names = None, None, None, None, None, None, None\n\n\ndef setup(info, **kwargs):\n global robot, scene, move_group, display_trajectory_publisher, planning_frame, eef_link, group_names\n moveit_commander.roscpp_initialize(sys.argv)\n rospy.init_node('ur3_test_node', anonymous=True)\n robot = moveit_commander.RobotCommander()\n scene = moveit_commander.PlanningSceneInterface()\n group_name = kwargs.get('movegroup', 'manipulator')\n move_group = moveit_commander.MoveGroupCommander(group_name)\n display_trajectory_publisher = rospy.Publisher('/move_group/display_planned_path'\n , moveit_msg_lib.DisplayTrajectory\n , queue_size=20)\n\n planning_frame = move_group.get_planning_frame()\n eef_link = move_group.get_end_effector_link()\n group_names = robot.get_group_names()\n robot_state = robot.get_current_state()\n\n if info:\n print('==== Reference frame: {}'.format(planning_frame))\n print('==== End effector ==: {}'.format(eef_link))\n print('==== Robot groups ==: {}'.format(group_names))\n print('==== Robot state ===: {}'.format(robot_state))\n\n\ndef default_robot_position(robot_model):\n if robot_model == \"UR3\" and len(move_group.get_current_joint_values()) == 6:\n joint_state = []\n joint_state.append(-pi / 4)\n joint_state.append(-pi / 2)\n joint_state.append(-pi / 2)\n joint_state.append(-pi / 2)\n joint_state.append(pi)\n joint_state.append(-pi / 2)\n\n move_group.go(joint_state, wait=True)\n move_group.stop()\n\ndef all_zero(robot_model):\n if robot_model == \"UR3\" and len(move_group.get_current_joint_values()) == 6:\n joint_state = []\n joint_state.append(0)\n joint_state.append(0)\n joint_state.append(0)\n joint_state.append(0)\n joint_state.append(0)\n joint_state.append(0)\n\n move_group.go(joint_state, wait=True)\n move_group.stop()\n\ndef match_unity(robot_model):\n if robot_model == \"UR3\" and len(move_group.get_current_joint_values()) == 6:\n joint_state = []\n\n offset_base = 45.0\n offset_shoulder = -90.0\n offset_elbow = 0\n offset_wrist1 = -90.0\n offset_wrist2 = 0\n offset_wrist3 = 0\n\n joint_state.append(0 + radians(offset_base))\n joint_state.append(0 + radians(offset_shoulder))\n joint_state.append(0 + radians(offset_elbow))\n joint_state.append(0 + radians(offset_wrist1))\n joint_state.append(0 + radians(offset_wrist2))\n joint_state.append(0 + radians(offset_wrist3))\n\n move_group.go(joint_state, wait=True)\n move_group.stop()\n\ndef rotation_dance(robot_model, dance_length=20):\n if robot_model == \"UR3\" and len(move_group.get_current_joint_values()) == 6:\n joint_state = move_group.get_current_joint_values()\n for _ in range(dance_length):\n\n for i in range(len(joint_state)):\n joint_state[i] += 0.1\n\n move_group.go(joint_state, wait=True)\n\n move_group.stop()\n\ndef display_plan(plan): # to use it, you need to open rviz UI, pass argument UI:=true when you roslaunch robot.launch\n trajectory_msg = moveit_msg_lib.DisplayTrajectory()\n trajectory_msg.trajectory_start = robot.get_current_state()\n trajectory_msg.trajectory.append(plan)\n display_trajectory_publisher.publish(trajectory_msg)\n\n print(\"==== plan is being visualized\")\n rospy.sleep(5)\n\ndef generate_plan():\n\n target_pose = geometry_msg_lib.Pose()\n target_pose.orientation.w = 1.0\n target_pose.position.x = 0.7\n target_pose.position.y = -0.05\n target_pose.position.z = 1.1\n move_group.set_pose_target(target_pose)\n return move_group.plan()\n\ndef clear_target():\n move_group.clear_pose_targets()\n\ndef go_to_joint_goal(info):\n joint_state = move_group.get_current_joint_values()\n if info:\n print('==== Detect robot with {} joints'.format(len(joint_state)))\n print('==== joint state is of type {}'.format(type(joint_state)))\n print('==== joint state of the 6 joints of UR3 are {}'.format(joint_state))\n\n joint_state[0] = -pi / 3\n joint_state[1] = -pi / 4\n joint_state[2] = -pi / 4\n joint_state[3] = -pi / 1\n joint_state[4] = -pi / 3\n joint_state[5] = -pi / 2\n # ur3 robot has only 6 joints, namely 6DoF\n\n move_group.go(joint_state, wait=True)\n\n move_group.stop()\n\n\n\n\ndef go_to_pos_goal(info):\n destination_pos = geometry_msg_lib.Pose()\n #destination_pos.orientation.x = 0.5\n #destination_pos.orientation.y = 0.5\n #destination_pos.orientation.z = -0.5\n destination_pos.orientation.w = 1.0\n\n #destination_pos.position.x = -0.18\n\n #destination_pos.position.y = -0.23\n\n # destination_pos.position.z = 1.24\n\n destination_pos.position.x = 0.4\n\n destination_pos.position.y = 0.1\n\n destination_pos.position.z = 0.4\n\n #move_group.set_current_state_as_start_state()\n\n move_group.set_pose_target(destination_pos)\n\n\n\n plan = move_group.plan()\n if info:\n\n print('==== The Planner returns plan of:\\n {}'.format(plan))\n\n plan = move_group.go(wait=True)\n\n if info:\n print('==== plan executed : {}'.format(plan))\n\n move_group.stop()\n move_group.clear_pose_targets()\n return plan\n\n\nif __name__ == '__main__':\n setup(info=True, movegroup='manipulator')\n #all_zero(robot_model)\n #go_to_pos_goal(info=True)\n #match_unity(robot_model)\n #go_to_joint_goal(info=True)\n default_robot_position(robot_model)\n\n\n\n\n\n # rotation_dance(robot_model, 5)\n # default_robot_position(robot_model)\n\n # go_to_pos_goal(info=True)\n\n","sub_path":"src/ur3_test/scripts/ur3_test_dev.py","file_name":"ur3_test_dev.py","file_ext":"py","file_size_in_byte":6199,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"206451708","text":"from django.contrib.auth.decorators import login_required\nfrom django.shortcuts import render, redirect\n\nfrom toastmaster_track.track.forms import OfficerForm\nfrom toastmaster_track.track.models import Officer\n\n\n@login_required\ndef detail(request):\n context = {\n 'officers': Officer.objects.all()\n }\n\n return render(request, 'officer/detail.html', context)\n\n\n@login_required\ndef create(request):\n if request.method == 'POST':\n form = OfficerForm(request.POST)\n\n if form.is_valid():\n form.save()\n\n return redirect('officer_detail')\n else:\n form = OfficerForm()\n context = {\n 'form': form,\n }\n return render(request, 'officer/create.html', context)\n\n\n@login_required\ndef edit(request, officer_id):\n officer = Officer.objects.get(pk=officer_id)\n\n if request.method == 'POST':\n form = OfficerForm(request.POST, instance=officer)\n\n if form.is_valid():\n form.save()\n\n return redirect('officer_detail')\n else:\n form = OfficerForm(instance=officer)\n context = {\n 'form': form,\n }\n return render(request, 'officer/edit.html', context)\n\n\n@login_required\ndef delete(request, officer_id):\n officer = Officer.objects.get(pk=officer_id)\n\n if request.method == 'POST':\n officer.delete()\n\n return redirect('officer_detail')\n else:\n context = {\n 'officer': officer\n }\n\n return render(request, 'officer/delete.html', context)\n","sub_path":"toastmaster_track/track/views/officer.py","file_name":"officer.py","file_ext":"py","file_size_in_byte":1544,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"619728111","text":"import pygame\nimport random\nimport os\n\nFPS=60\nWIDTH=500\nHEIGHT=600\n\nBLACK=(0,0,0)\nWHITE=(255,255,255)\nRED=(255,0,0)\nGREEN=(0,255,0)\nYELLOW=(255,255,0)\n\n# Game Init and Create Window\npygame.init()\nscreen=pygame.display.set_mode((WIDTH,HEIGHT))\npygame.display.set_caption(\"My First Game\")\nclock=pygame.time.Clock()\n\n# Load Images\nbackground_img=pygame.image.load(os.path.join(\"img\",\"background.png\")).convert()\nplayer_img=pygame.image.load(os.path.join(\"img\",\"player.png\")).convert()\nbullet_img=pygame.image.load(os.path.join(\"img\",\"bullet.png\")).convert()\nrock_imgs = []\nfor i in range(7):\n rock_imgs.append(pygame.image.load(os.path.join(\"img\",f\"rock{i}.png\")).convert())\n\n# Load Font\nfont_name=pygame.font.match_font('arial')\n\ndef draw_text(surf,text,size,x,y):\n font=pygame.font.Font(font_name, size)\n text_surface=font.render(text,True,WHITE)\n text_rect=text_surface.get_rect()\n text_rect.centerx=x\n text_rect.top=y\n surf.blit(text_surface,text_rect)\n\n\nclass Player(pygame.sprite.Sprite):\n def __init__(self):\n pygame.sprite.Sprite.__init__(self)\n self.image=pygame.transform.scale(player_img, (50,38)) \n self.image.set_colorkey(BLACK)\n self.rect=self.image.get_rect()\n self.radius = 20\n self.rect.centerx = WIDTH / 2\n self.rect.bottom = HEIGHT - 10\n self.speedx=8\n \n def update(self):\n key_pressed=pygame.key.get_pressed()\n if key_pressed[pygame.K_RIGHT]:\n self.rect.x += self.speedx\n if key_pressed[pygame.K_LEFT]:\n self.rect.x -= self.speedx \n if self.rect.right > WIDTH: \n self.rect.right = WIDTH\n if self.rect.left < 0:\n self.rect.left=0\n \n def shoot(self):\n bullet=Bullet(self.rect.centerx, self.rect.top)\n all_sprites.add(bullet)\n bullets.add(bullet)\n\nclass Rock(pygame.sprite.Sprite):\n def __init__(self):\n pygame.sprite.Sprite.__init__(self)\n self.image_ori=random.choice(rock_imgs)\n self.image_ori.set_colorkey(BLACK)\n self.image=self.image_ori.copy() \n self.rect=self.image.get_rect()\n self.radius=int(self.rect.width *0.85/2)\n self.rect.x = random.randrange(0, WIDTH - self.rect.width )\n self.rect.y = random.randrange(-180, -100)\n self.speedx = random.randrange(-3, 3)\n self.speedy = random.randrange(2, 5)\n self.total_degree=0\n self.rot_degree=random.randrange(-3, 3)\n\n def rotate(self):\n self.total_degree += self.rot_degree\n self.total_degree = self.total_degree%360\n self.image=pygame.transform.rotate(self.image_ori , self.total_degree)\n center=self.rect.center\n self.rect=self.image.get_rect()\n self.rect.center=center \n\n def update(self):\n self.rotate()\n self.rect.y += self.speedy\n self.rect.x += self.speedx\n if self.rect.top > HEIGHT or self.rect.left > WIDTH or self.rect.right < 0:\n self.rect.x = random.randrange(0, WIDTH - self.rect.width )\n self.rect.y = random.randrange(-100, -40)\n self.speedx = random.randrange(-3, 3)\n self.speedy = random.randrange(2, 10)\n\nclass Bullet(pygame.sprite.Sprite):\n ## Get Plane's Position self,x,y\n def __init__(self,x,y):\n pygame.sprite.Sprite.__init__(self)\n self.image=bullet_img\n self.image.set_colorkey(BLACK )\n self.rect=self.image.get_rect()\n self.rect.centerx = x\n self.rect.bottom = y\n self.speed = -10\n \n def update(self):\n self.rect.y += self.speed\n if self.rect.bottom < 0:\n self.kill()\n \n# Sprites\nall_sprites=pygame.sprite.Group()\nrocks = pygame.sprite.Group()\nbullets = pygame.sprite.Group()\nplayer=Player()\nall_sprites.add(player)\nfor i in range(8):\n r=Rock()\n all_sprites.add(r)\n rocks.add(r)\nscore = 0\n\n# Game Loop\nrunning=True\nwhile running:\n clock.tick(FPS)\n # Get Input\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n running=False\n elif event.type ==pygame.KEYDOWN:\n if event.key == pygame.K_SPACE:\n player.shoot()\n\n # Update Game\n all_sprites.update()\n hits = pygame.sprite.groupcollide(rocks, bullets , True, True )\n for hit in hits:\n score += hit.radius\n r=Rock()\n all_sprites.add(r)\n rocks.add(r)\n \n # Flase = Rock not Kill\n hits = pygame.sprite.spritecollide(player, rocks, False,pygame.sprite.collide_circle)\n if hits:\n running = False\n\n # Game Display\n screen.fill(BLACK)\n screen.blit(background_img , (0,0))\n all_sprites.draw(screen)\n draw_text(screen, str(score), 18, WIDTH/2, 10)\n pygame.display.update()\n\npygame.quit() ","sub_path":"game13.py","file_name":"game13.py","file_ext":"py","file_size_in_byte":4780,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"541414225","text":"import os\nimport torch\nfrom torch.utils.data import Dataset, DataLoader, random_split\n\n\ndef create_loaders(full, batch_size, val_split, shuffle=True, min_val=1):\n \"\"\"Split full dataset into training and validation\n\n :param torch.utils.data.Dataset full: Entire dataset\n :param int batch_size: Number of samples per batch\n :param float val_split: Percent of full dataset to use for validation\n :param bool shuffle: Whether loaders should shuffle batches each epoch\n :param int min_val: Minimum size of validation set\n :return tuple(torch.utils.data.DataLoader): Train and validation loaders\n \"\"\"\n val_size = int(min(min_val, val_split * len(full)))\n train_size = len(full) - val_size\n train, val = random_split(full, [train_size, val_size])\n train_loader = DataLoader(train, batch_size, shuffle)\n val_loader = DataLoader(val, batch_size, shuffle)\n return train_loader, val_loader\n\n\nclass BaseDataset(Dataset):\n \"\"\"Base class for PyTorch dataset\n\n Performs check for whether dataset has been previously downloaded, and\n prompts use to do so if not. Subclasses must implement the ``download``,\n ``__getitem__``, and ``__len__`` methods.\n\n :param str local: Filepath where the dataset is expected to be\n \"\"\"\n\n def __init__(self, local):\n self.local = local\n self.device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\n self.check_local()\n\n def __getitem__(self, idx):\n raise NotImplementedError\n\n def __len__(self):\n raise NotImplementedError\n\n def download(self, *args, **kwargs):\n raise NotImplementedError\n\n def check_local(self):\n \"\"\"Determine whether dataset has been downloaded, if not prompt user\"\"\"\n if os.path.exists(self.local):\n return\n answer = input('Local dataset not found, would you like to download? [y/n] ')\n while answer.lower() not in ['y', 'n']:\n answer = input('Please enter y or n: ')\n if answer == 'y':\n print('Starting download...')\n try:\n self.download()\n except:\n print(f'Error downloading')\n else:\n print('Exiting without download')\n","sub_path":"torcharch/data.py","file_name":"data.py","file_ext":"py","file_size_in_byte":2228,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"238188907","text":"from concurrent import futures\n\nimport grpc\nimport pytest\n\nfrom xain_fl.coordinator.coordinator import Coordinator\nfrom xain_fl.coordinator.coordinator_grpc import CoordinatorGrpc\nfrom xain_fl.cproto import coordinator_pb2_grpc, hellonumproto_pb2_grpc\nfrom xain_fl.cproto.numproto_server import NumProtoServer\n\n\n@pytest.fixture\ndef greeter_server():\n server = grpc.server(futures.ThreadPoolExecutor(max_workers=1))\n hellonumproto_pb2_grpc.add_NumProtoServerServicer_to_server(\n NumProtoServer(), server\n )\n server.add_insecure_port(\"localhost:50051\")\n server.start()\n yield\n server.stop(0)\n\n\n@pytest.fixture\ndef coordinator_service():\n server = grpc.server(futures.ThreadPoolExecutor(max_workers=1))\n coordinator = Coordinator(\n minimum_participants_in_round=10, fraction_of_participants=1.0\n )\n coordinator_grpc = CoordinatorGrpc(coordinator)\n coordinator_pb2_grpc.add_CoordinatorServicer_to_server(coordinator_grpc, server)\n server.add_insecure_port(\"localhost:50051\")\n server.start()\n yield coordinator_grpc\n server.stop(0)\n\n\n@pytest.fixture\ndef participant_stub():\n channel = grpc.insecure_channel(\"localhost:50051\")\n stub = coordinator_pb2_grpc.CoordinatorStub(channel)\n\n return stub\n","sub_path":"xain_fl/cproto/conftest.py","file_name":"conftest.py","file_ext":"py","file_size_in_byte":1260,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"14891557","text":"#Trabalho 1 - Inteligência Artificial\n#Érick de Oliveira Teixeira - 2017001437\n#Algoritmo Genético para otimização da função f(x) = x^2 para 0 <= x <= 31\n#Versão para testes com crossover por média dos pais\n\nfrom random import randint\nimport numpy as np\nimport sys\n\nglobal tam_pop, prob_mutacao, nro_ger\n\n#Captura dos parâmetros do AG:\ntam_pop = int(sys.argv[1]) #Tamanho da população\nprob_mutacao = float(sys.argv[2]) #Probabilidade de mutação\nnro_ger = int(sys.argv[3]) #Número de gerações\nqnt_exec = int(sys.argv[4]) #Quantidade de execuções\n\n#Escrita no arquivo de log\nnome_arq = str(tam_pop)+'_'+str(prob_mutacao*100)+'%_'+str(nro_ger)+'_media_freq.txt'\npath_arq = 'Testes/'+nome_arq\narq = open(path_arq,'w')\narq.write('Tamanho da população: ' + str(tam_pop) + '\\n')\narq.write('Taxa de mutação: ' + str(prob_mutacao*100) + ' %\\n')\narq.write('Número de gerações: ' + str(nro_ger) + '\\n')\narq.write('Operador de cruzamento: Média\\n')\narq.write('Quantidade de execuções: {}\\n\\n'.format(str(qnt_exec)))\n\nif nro_ger == 0:\n\tprint(\"Favor inserir nro de gerações maior que 0\")\n\tsys.exit()\n\ndef funcao(x): #Funcão a ser utilizada\n\treturn x**2\n\ndef geraIndividuo(): #Gera cromossomo randômico\n\tindividuo = []\n\tfor i in range(0,5):\n\t\tcromossomo = randint(0,1)\n\t\tindividuo.append(cromossomo)\n\treturn individuo\n\ndef geraPopulacao(): #Gera população randômica\n\tpopulacao = []\n\tfor i in range(0,tam_pop):\n\t\tpopulacao.append(geraIndividuo())\n\treturn populacao\n\ndef bitsToDec(cromossomos): #Converte os bits dos cromossomos para decimal\n\tsoma = cromossomos[4]\n\tsoma += cromossomos[3] * 2\n\tsoma += cromossomos[2] * 4\n\tsoma += cromossomos[1] * 8\n\tsoma += cromossomos[0] * 16\n\treturn soma\n\ndef calcAptidao(populacao): #Calcula a aptidão dos indivíduos da população\n\tsoma = 0\n\taptidao = []\n\tfor individuo in populacao:\n\t\tsoma += funcao(bitsToDec(individuo)) #Somatório de f(x)\n\tfor individuo in populacao:\n\t\taptidao.append(funcao(bitsToDec(individuo))/soma) #Probabilidade de Seleção do indivíduo\n\treturn aptidao\n\ndef selecionar(populacao, aptidao): #seleciona 2 indivíduos da população baseado na aptidão\n\tselecionados = []\n\tescolhas = np.random.choice(len(populacao), 2, p=aptidao, replace=False)\n\tselecionados.append(populacao[escolhas[0]])\n\tselecionados.append(populacao[escolhas[1]])\n\treturn selecionados\n\ndef get_bin(x):\n\tbits = []\n\tnbin = format(x, 'b')\n\tif len(nbin) < 5:\n\t\tfor i in range(0,5-len(nbin)):\n\t\t\tbits.append(0)\n\tfor char in nbin:\n\t\tif char == '0':\n\t\t\tbits.append(0)\n\t\telse:\n\t\t\tbits.append(1)\n\treturn bits\n\ndef crossover(selecionados): #Realiza o crossover e aplica mutação (se for o caso)\n\tpai1 = selecionados[0]\n\tpai2 = selecionados[1]\n\tmedia = int((bitsToDec(pai1)+bitsToDec(pai2))/2) #Calcula média entre os dois pais\n\tfilho = get_bin(media) #Forma o filho com base na média dos dois pais\n\tflags_mutacao_f = np.random.choice(2, 5, p=[1-prob_mutacao,prob_mutacao], replace=True) #Flags para indicar se ocorrerá mutação nos cromossomos do filho\n\tcont = 0\n\tfor flag in flags_mutacao_f: #Aplica mutações no filho 1 (se for o caso)\n\t\tif flag == 1 and filho[cont] == 0:\n\t\t\tfilho[cont] = 1\n\t\telif flag == 1 and filho[cont] == 1:\n\t\t\tfilho[cont] = 0\n\t\tcont += 1\t\n\treturn filho\n\ndef ordenaPopulacao(populacao): #Ordena populacao[] para valores decrescentes de f(x)\n\telementos = tam_pop-1\n\tordenado = False\n\twhile not ordenado: #Aplicação adaptada do algoritmo BubbleSort\n\t\tordenado = True\n\t\tfor i in range(elementos):\n\t\t\tif bitsToDec(populacao[i]) < bitsToDec(populacao[i+1]):\n\t\t\t\tpopulacao[i], populacao[i+1] = populacao[i+1],populacao[i]\n\t\t\t\tordenado = False\n\treturn populacao\n\ncont = 0\nmelhores = []\nwhile cont < qnt_exec:\n\tger_atual = 1 #Geração atual\n\tpop = geraPopulacao() #Gera população inicial\n\tfor i in range(0,nro_ger): #Início da evolução\n\t\tapt = calcAptidao(pop) #Calcula aptidão\n\t\tsel = selecionar(pop,apt) #Seleciona 2 indivíduos\n\t\tprox_ger = [] #Variável que guarda os integrantes da proxima geração\n\t\tfor j in range(0,int(tam_pop)): #Gera a quantidade de filhos suficiente para formar a próxima geração\n\t\t\tsel = selecionar(pop,apt)\n\t\t\tfilho = crossover(sel)\n\t\t\tprox_ger.append(filho)\n\t\tpop = prox_ger #Atualiza a geração com os novos indivíduos formados\n\t\tger_atual += 1\n\n\tpop = ordenaPopulacao(pop) #Ordena a população com vase em valores decrescentes de f(x)\n\tmelhores.append(bitsToDec(pop[0]))\n\tcont += 1\n\nm = np.array(melhores)\nuniqueValues, occurCount = np.unique(m, return_counts=True)\n\nfor i in range(0,len(occurCount)):\n\tfreq = round((occurCount[i]*100)/qnt_exec,2)\n\tprint('x = {}: {} ocorrencia(s) -- {} %'.format(uniqueValues[i],occurCount[i],freq))\n\tarq.write('x = {}: {} ocorrencia(s) -- {} %'.format(uniqueValues[i],occurCount[i],freq)+'\\n')\narq.close()","sub_path":"ag_media_test.py","file_name":"ag_media_test.py","file_ext":"py","file_size_in_byte":4759,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"334249367","text":"from django.db.models.aggregates import Avg\nfrom django.shortcuts import render\nfrom django.shortcuts import render\nfrom django.db import models\nfrom .models import User, Occupation, Category, Film, Rate\nimport datetime as dt\nimport collections\nimport operator\n\n\ndef populate(request):\n populate_categories()\n populate_occupations()\n populate_users()\n populate_films()\n populate_ratings()\n print(\"success\")\n return render(request, 'films/index.html')\n\n\ndef date_parser(date_str):\n try:\n return dt.datetime.strptime(date_str, \"%d-%b-%Y\")\n except:\n return None\n\n\ndef populate_occupations():\n Occupation.objects.all().delete()\n with open(\"/home/andres/AII/Django/practica1/ml-100k/u.occupation\", \"r\") as occupations_file:\n occupations = [line.rstrip() for line in occupations_file.readlines()]\n occupation_array = [Occupation(name=o) for o in occupations]\n Occupation.objects.bulk_create(occupation_array)\n\n\ndef populate_categories():\n Category.objects.all().delete()\n with open(\"/home/andres/AII/Django/practica1/ml-100k/u.genre\", \"r\") as categories_file:\n categories = [line.rstrip().split(\"|\") for line in categories_file.readlines()]\n category_array = [Category(c[1], c[0]) for c in categories[:-1]] # -1 because there is a blank line at the end\n Category.objects.bulk_create(category_array)\n\n\ndef populate_users():\n User.objects.all().delete()\n with open(\"/home/andres/AII/Django/practica1/ml-100k/u.user\", \"r\") as users_file:\n users = [line.rstrip().split(\"|\") for line in users_file]\n users_array = [User(uid=u[0], age=u[1], sex=u[2], postal_code=u[4], occupation=Occupation.objects.get(name=u[3]))\n for u in users]\n User.objects.bulk_create(users_array)\n\n\ndef populate_films():\n Film.objects.all().delete()\n with open(\"/home/andres/AII/Django/practica1/ml-100k/u.item\", \"rb\") as films_file:\n films = [line.decode(\"latin1\").rstrip().split(\"|\") for line in films_file]\n films_array = [Film(fid=f[0], title=f[1], year=date_parser(f[2]), url=f[4]) for f in films]\n Film.objects.bulk_create(films_array)\n\n\ndef populate_ratings():\n Rate.objects.all().delete()\n with open(\"/home/andres/AII/Django/practica1/ml-100k/u.data\", \"r\") as ratings_file:\n ratings = [line.rstrip().split(\"\\t\") for line in ratings_file]\n ratings_array = [Rate(user=User.objects.get(uid=r[0]), film=Film.objects.get(fid=r[1]), number=r[2]) for r in\n ratings]\n Rate.objects.bulk_create(ratings_array)\n\n\ndef index(request):\n return render(request, 'films/index.html')\n\n\ndef form_user(request):\n context = {}\n if request.method == 'POST':\n form = user_id_form(request.POST)\n if form.is_valid():\n user_id = form.cleaned_data['userId']\n rates = Rate.objects.filter(user=user_id)\n context.__setitem__('rates', rates)\n else:\n form = user_id_form()\n\n context.__setitem__('form', form)\n\n return render(request, 'films/form.html', context)\n\n\ndef form_film(request):\n context = {}\n if request.method == 'POST':\n form = film_year_form(request.POST)\n if form.is_valid():\n year_form = form.cleaned_data['year']\n print(year_form.year)\n films = Film.objects.filter(year__year=year_form.year)\n context.__setitem__('films', films)\n else:\n form = film_year_form()\n\n context.__setitem__('form', form)\n\n return render(request, 'films/films_form.html', context)\n\n\ndef show_top_films(request):\n films = Film.objects.annotate(avg_rating=Avg('rate__number')).order_by('-avg_rating')[:5]\n return render(request, 'films/top_films.html', {'films': films})\n\n\ndef show_user_by_occupation(request):\n users = User.objects.raw('SELECT * FROM FILMS_USER GROUP BY OCCUPATION_ID')\n\n return render(request, 'films/show_users.html', {'users': users})\n","sub_path":"Django/practica1/practica1/films/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3922,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"653745271","text":"import fnmatch, os\n\nprint(\"\\n *** List All Files Under User Defined LocalDrive. *** \\n\")\ndrive = input(\" Enter the Drive Letter : \").upper()\nfile_format = input(\" Enter the file format : \")\nrootPath = drive+\":/\"\npattern = '*.'+file_format\n\nprint(\"\\n\")\ncount = 0\nfor root, dirs, files in os.walk(rootPath):\n\tfor filename in fnmatch.filter(files, pattern):\n\t\tprint(os.path.join(root, filename))\n\t\tcount += 1\n\nprint(\"\\n Totally {} files in the .{} format under {} drive.. \".format(count, file_format, drive))\n","sub_path":"Begineers/ListLocalFiles.py","file_name":"ListLocalFiles.py","file_ext":"py","file_size_in_byte":506,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"507157931","text":"'''\nCreated on May 25, 2016\nUpdated on November 14, 2016\n\n@author: mitch_000\n\n@todo: \ncommands\nvideo duration\nmp3 metadata\n ~pytaglib\n'''\n\nimport os\nimport re\nfrom requests import request\nfrom datetime import datetime\nfrom threading import Thread\nimport tkinter as tk\nfrom tkinter import ttk\nfrom urllib import request\nfrom PIL import ImageTk, Image\nfrom bs4 import BeautifulSoup\nimport youtube_dl\nimport error\n\nversion = \"2.4.0\"\n\n\ndef searchForResults(youtubeName, album, playlist, bitrate, downloadRate, programDir):\n \n youtubeNameFormatted = youtubeName.replace(\" \",\"+\")\n \n if(playlist == 0):\n searchUrl = \"https://www.youtube.com/results?sp=EgIQAQ%253D%253D&q=\" + youtubeNameFormatted\n if(playlist == 1):\n searchUrl = \"https://www.youtube.com/results?sp=EgIQAw%253D%253D&q=\" + youtubeNameFormatted\n\n try:\n searchPageConnection = request.urlopen(searchUrl)\n except:\n error.searchError()\n return\n \n searchPageObj = searchPageConnection.read()\n searchHTML = str(searchPageObj)\n searchHTML = cleanUpHTML(searchHTML)\n pageSoup = BeautifulSoup(searchHTML,\"html.parser\")\n \n formatResults(pageSoup, album, playlist, bitrate, downloadRate, programDir)\n \n \ndef formatResults(pageSoup, album, playlist, bitrate, downloadRate, programDir):\n \n listOfImgs = []\n for img in pageSoup.find_all(\"span\"):\n if([\"yt-thumb-simple\"] == img.get(\"class\")):\n if(\"/yts/\" in img.find(\"img\").get(\"src\")):\n listOfImgs.append(img.find(\"img\").get(\"data-thumb\"))\n else:\n listOfImgs.append(img.find(\"img\").get(\"src\"))\n\n listOfLinks = []\n listOfResults = []\n \n for hTag in pageSoup.find_all(\"h3\"):\n for link in hTag.find_all(\"a\"):\n try:\n #if not an ad add to results\n if(\"https://googleads.g.doubleclick.net/\" not in str(link.get(\"href\"))):\n \n listOfResults.append(str(link.get_text()))\n listOfLinks.append(\"http://www.youtube.com\"+link.get(\"href\"))\n except:\n error.formatResultError()\n continue\n \n generateResultGui( listOfResults, listOfLinks, listOfImgs, album, playlist, bitrate, downloadRate, programDir)\n \n \ndef generateResultGui( listOfResults, listOfLinks, listOfImgs, album, playlist, bitrate, downloadRate, programDir):\n resultWin = tk.Toplevel()\n choice = tk.IntVar()\n count = 0\n for img in listOfImgs:\n try:\n imageFile = request.urlopen(img)\n except:\n error.formatResultError()\n continue\n \n photo = ImageTk.PhotoImage(Image.open(imageFile).resize((100,70), Image.ANTIALIAS))\n photoLabel = ttk.Label(resultWin , image = photo)\n photoLabel.image = photo\n photoLabel.grid(row = count,column = 0,sticky = \"w\" )\n \n count = count + 1\n if(count > 7):\n break\n \n count = 0\n \n for result in listOfResults:\n radioLabel = ttk.Radiobutton(resultWin,text=result ,variable = choice, value = count)\n radioLabel.grid(row = count,column = 1,sticky = \"w\" )\n count = count + 1\n if(count>7):\n break\n \n albumName = tk.StringVar()\n \n if(album == 1):\n albumLabel = ttk.Label(resultWin,text = \"album/folder name: \")\n albumName.set(\"\")\n albumEntry = ttk.Entry(resultWin , width = 20, textvariable = albumName)\n albumLabel.grid(row = count,column = 0, sticky = \"w\")\n albumEntry.grid(row = count,column = 0, sticky = \"e\")\n \n downloadButton = ttk.Button(resultWin , text = \"download\", command = lambda: Thread( target = download , args = ( listOfLinks[choice.get()],album, playlist,bitrate,albumName.get(),downloadRate,resultWin, programDir)).start() )\n downloadButton.grid(row = count+1 , sticky = \"w\")\n resultWin.mainloop()\n \n \ndef download(url,album,playlist,bitrate,albumName,downloadRate,win, programDir):\n \n win.destroy()\n if(playlist == 1):\n playlist = False\n else:\n playlist = True\n bitrate = str(bitrate)\n ydl_opts = {\n 'format': 'bestaudio/best', # choice of quality \n 'postprocessors': [{\n 'key': 'FFmpegExtractAudio',\n 'preferredcodec': 'mp3',\n 'preferredquality': bitrate\n }], # only keep the audio\n #'logger': loggerWindow(),\n 'audioformat' : \"mp3\", # convert to mp3 \n 'noplaylist' : playlist, # only download single song, not playlist\n \"ffmpeglocation\" : programDir,\n \"ffmpeg_location\" : programDir,\n \"ignoreerrors\": True,\n \"quiet\": True,\n 'outtmpl':'%(title)s.%(ext)s',\n \"restrictfilenames\" : True,\n \"downloadrate\":downloadRate , \n 'progress_hooks': [downloadHook]\n }\n url = [url]\n with youtube_dl.YoutubeDL(ydl_opts) as ydl:\n if(album == 1):\n createNewAlbum(albumName , programDir)\n try:\n ydl.download(url)\n except:\n error.downloadError()\n else:\n goToDownLoadFolder(programDir)\n ydl.download(url)\n \n \n \n''' \n progress_hooks: A list of functions that get called on download\n progress, with a dictionary with the entries\n * status: One of \"downloading\", \"error\", or \"finished\".\n Check this first and ignore unknown values.\n If status is one of \"downloading\", or \"finished\", the\n following properties may also be present:\n * filename: The final filename (always present)\n * tmpfilename: The filename we're currently writing to\n * downloaded_bytes: Bytes on disk\n * total_bytes: Size of the whole file, None if unknown\n * total_bytes_estimate: Guess of the eventual file size,\n None if unavailable.\n * elapsed: The number of seconds since download started.\n * eta: The estimated time in seconds, None if unknown\n * speed: The download speed in bytes/second, None if\n unknown\n * fragment_index: The counter of the currently\n downloaded video fragment.\n * fragment_count: The number of fragments (= individual\n files that will be merged)\n Progress hooks are guaranteed to be called at least once\n (with status \"finished\") if the download is successful.\ndef downloadHook(d):\n if d['status'] == 'finished':\n print('Done downloading, now converting ...')\n \n\ndef downloadHook(d):\n try:\n #print(d['eta'], end=\"\\r\")\n print(\"eta\")\n print('{0}\\r'.format(d[\"eta\"]))\n\n except:\n pass\n \n'''\n \n \ndef createNewAlbum(albumName, programDir):\n #print(albumName)\n os.chdir(programDir)\n os.chdir(\"..\")\n currentDirectory = os.getcwd()\n albumDirectory = currentDirectory + \"\\\\\" + albumName\n #checking for existance of albumfolder\n #print(albumDirectory)\n try:\n if(os.path.isdir(albumDirectory) == False):\n os.mkdir(albumDirectory) \n except:\n error.albumCreationError()\n \n os.chdir(albumDirectory)\n\n\ndef goToDownLoadFolder( programDir):\n os.chdir(programDir)\n os.chdir(\"..\")\n currentDirectory = os.getcwd()\n downloadsDirectory = currentDirectory + \"\\\\Downloads\"\n \n #checking for existance of database\n try:\n if(os.path.isdir(downloadsDirectory) == False):\n os.mkdir(\"Downloads\")\n except:\n error.downloadFolderCreationError()\n \n os.chdir(downloadsDirectory)\n\n\nclass loggerWindow(object):\n \n def debug(self,msg):\n pass\n \n def warning(self, msg):\n pass\n\n def error(self, msg):\n pass\n\n\ndef saveConfig(album,playlist,bitrate):\n date = datetime.now()\n os.chdir(programDir)\n configFile = open(\"config.cfg\", \"w\")\n configFile.write()\n \n \ndef cleanUpHTML(html):\n #gets rid of all the uninterperated html\n html = html.replace(\"\\\\n\",\"\")\n html = re.sub(r\"\\\\x..\" , '' , html)\n return html\n\n\n ","sub_path":"src/client/model/functions.py","file_name":"functions.py","file_ext":"py","file_size_in_byte":8104,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"353662567","text":"#!/usr/bin/python3\n\nimport platform\nimport telebot\nimport requests\nfrom config import BotConfig\nfrom threading import Timer\n\nRESTART_TIMEOUT = 20\nCHECK_RATE_TIMEOUT = 10*60\n\n\nclass NullObject(object):\n def __init__(self):\n pass\n\n def __repr__(self):\n return \"It's universal object, that can be used instead of any other object\"\n\n def __getattr__(self, item):\n print(\"relay request {}\".format(item))\n return lambda *args, **kwargs: None\n\n\ndef get_relay_obj():\n \"\"\"Check current platform type, return NullObject for all platform except armv7l\"\"\"\n if platform.machine() == 'armv7l':\n import relay_control\n return relay_control.Relay()\n else:\n return NullObject()\n\n\ndef delayed_start(bot, message, relay):\n relay.relay_on()\n bot.send_message(message.chat.id, 'System start again')\n\n\ndef check_hashrate(bot, message, wallet, relay):\n print(\"check_hashrate\")\n Timer(CHECK_RATE_TIMEOUT, check_hashrate, [bot, message]).start()\n URL = \"https://api.nanopool.org/v1/eth/hashrate/\" + wallet\n r = requests.get(url=URL)\n data = r.json()\n\n if data['data'] < 120:\n bot.send_message(message.chat.id, 'Hash rate is low: {}'.format(data['data']))\n elif data['data'] < 50:\n bot.send_message(message.chat.id, 'Hash rate is critical low: {}'.format(data['data']))\n relay.relay_off()\n bot.send_message(message.chat.id, 'System restart is in process')\n Timer(20, delayed_start, [bot, message]).start()\n\n\ndef main():\n bot_config = BotConfig()\n bot_id = bot_config.get_telegram_id()\n bot = telebot.TeleBot(token=bot_id)\n relay = get_relay_obj()\n\n @bot.message_handler(commands=['help'])\n def help_message(message):\n markup = telebot.types.ReplyKeyboardMarkup(row_width=2)\n itembtn1 = telebot.types.KeyboardButton('/start')\n itembtn2 = telebot.types.KeyboardButton('/stop')\n itembtn3 = telebot.types.KeyboardButton('/reset')\n itembtn4 = telebot.types.KeyboardButton('/get_rate')\n markup.add(itembtn1, itembtn2, itembtn3, itembtn4)\n bot.send_message(message.chat.id, \"Choose command:\", reply_markup=markup)\n\n @bot.message_handler(commands=['start'])\n def start_command(message):\n relay.relay_on()\n bot.send_message(message.chat.id, 'System start is Ok')\n Timer(10*60, check_hashrate, [bot, message, bot_config.get_wallet(), relay]).start()\n\n @bot.message_handler(commands=['restart'])\n def restart_command(message):\n relay.relay_off()\n bot.send_message(message.chat.id, 'System restart is in process')\n Timer(RESTART_TIMEOUT, delayed_start, [bot, message]).start()\n\n @bot.message_handler(commands=['get_rate'])\n def get_rate_command(message):\n URL = \"https://api.nanopool.org/v1/eth/hashrate/\" + bot_config.get_wallet()\n r = requests.get(url=URL)\n data = r.json()\n bot.send_message(message.chat.id, 'Hash rate: {}'.format(data['data']))\n\n @bot.message_handler(commands=['stop'])\n def stop_command(message):\n relay.relay_off()\n bot.send_message(message.chat.id, 'System stopped')\n\n bot.polling()\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"remoute_relay.py","file_name":"remoute_relay.py","file_ext":"py","file_size_in_byte":3215,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"23705068","text":"#!/usr/bin/env python\n\nimport unittest\nfrom setup import redisom, clear_redis_testdata\n\n\nclass SampleSet(redisom.Set):\n pass\n\n\nclass SetTestCase(unittest.TestCase):\n def setUp(self):\n clear_redis_testdata()\n\n def tearDown(self):\n clear_redis_testdata()\n\n def test_common_operations(self):\n fruits = SampleSet(key='fruits')\n fruits.add('apples')\n fruits.add('oranges')\n fruits.add('bananas', 'tomatoes')\n fruits.add(['strawberries', 'blackberries'])\n\n self.assertEqual(\n {'apples', 'oranges', 'bananas',\n 'tomatoes', 'strawberries', 'blackberries'}, fruits.all())\n\n # remove\n fruits.remove('apples')\n fruits.remove('bananas', 'blackberries')\n fruits.remove(['tomatoes', 'strawberries'])\n\n self.assertEqual({'oranges'}, fruits.all())\n\n # in\n self.assertTrue('oranges' in fruits)\n self.assertTrue('apples' not in fruits)\n\n # len\n self.assertEqual(1, len(fruits))\n\n # pop\n self.assertEqual('oranges', fruits.pop())\n\n def test_access_redis_methods(self):\n s = SampleSet('new_set')\n s.sadd('a')\n s.sadd('b')\n s.srem('b')\n self.assertEqual('a', s.spop())\n s.sadd('a')\n self.assert_('a' in s.members)\n s.sadd('b')\n self.assertEqual(2, s.scard())\n self.assert_(s.sismember('a'))\n conn = redisom.default_connection()\n conn.sadd('other_set', 'a')\n conn.sadd('other_set', 'b')\n conn.sadd('other_set', 'c')\n self.assert_(s.srandmember() in {'a', 'b'})\n\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"test/test_set.py","file_name":"test_set.py","file_ext":"py","file_size_in_byte":1671,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"98314870","text":"import apache_beam as beam\nimport apache_beam.transforms.window as window\nfrom apache_beam.io.external.kafka import ReadFromKafka, WriteToKafka\nfrom apache_beam.options.pipeline_options import PipelineOptions\n\n\nbrokers = 'localhost:9092'\nkafka_topic = 'stocks'\n\n\ndef run_pipeline():\n options = PipelineOptions(\n# runner = \"DirectRunner\",\n runner = \"PortableRunner\",\n job_endpoint = \"localhost:8099\",\n environment_type = \"LOOPBACK\"\n )\n #print(options)\n\n# options = PipelineOptions([\n# \"--runner=PortableRunner\",\n# \"--job_endpoint=localhost:8099\",\n# \"--environment_type=LOOPBACK\"\n# ])\n\n # beam_options = PipelineOptions(\n # beam_args,\n # runner='DataflowRunner',\n # project='my-project-id',\n # job_name='unique-job-name',\n # temp_location='gs://my-bucket/temp',\n # region='us-central1')\n\n\n #pipeline_options = PipelineOptions()\n# with beam.Pipeline(options = options) as p:\n with beam.Pipeline() as p:\n (p\n# | beam.Create(['alpha','beta', 'gamma'])\n | 'Read from Kafka' >> ReadFromKafka(consumer_config=\n {\n 'bootstrap.servers': brokers\n ,'auto.offset.reset': 'latest'\n ,'session.timeout.ms': '12000'\n# ,'request.timeout.ms.config': 120000\n }\n , topics=[kafka_topic])\n | 'Print' >> beam.Map(lambda x : print('*' * 100, '\\n', x))\n )\n # | 'Window of 10 seconds' >> beam.WindowInto(window.FixedWindows(10))\n # | 'Group by key' >> beam.GroupByKey()\n # | 'Sum word counts' >> beam.Map(lambda kv: (kv[0], sum(kv[1])))\n # | 'Write to Kafka' >> WriteToKafka(producer_config={'bootstrap.servers': kafka_bootstrap},\n # topic='demo-output'))\n # )\n\nif __name__ == '__main__':\n run_pipeline()\n ","sub_path":"scripts/1/beam_kafka_consumer_print.py","file_name":"beam_kafka_consumer_print.py","file_ext":"py","file_size_in_byte":1932,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"390151325","text":"import numpy as np\nimport matplotlib.pyplot as plt\n\n\ntrain_data1 = np.load('data3.npy')\ntrain_lab1 = np.load('lab3.npy')\n\ni = 3\nplt.imshow(train_data1[i])\nplt.savefig('img.png')\nprint(train_lab1[i])","sub_path":"Data/load_data.py","file_name":"load_data.py","file_ext":"py","file_size_in_byte":198,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"621568085","text":"import tensorflow as tf\nfrom flask import Flask,jsonify,request\nimport json\n#import pandas as pd\napp = Flask(__name__)\n@app.route('/add',methods=['POST'])\ndef add():\n x=tf.placeholder(dtype=tf.int32)\n y=tf.placeholder(dtype=tf.int32)\n# c=tf.add(x,y)\n# print(c)\n# sess=tf.session()\n data=request.get_json()\n# query=json.dumps(data)\n# query=pd.DataFrame(data)\n a=data['x']\n b=data['y']\n# data=json.dumps(data,encoding='UTF-8',default=str)\n sess=tf.Session()\n results=tf.add(a,b)\n# results=tf.placeholder(dtype=tf.int32)\n return jsonify({'sum':str(sess.run(results)),'x':a,'y':b})\nif __name__ == \"__main__\":\n app.run(host='0.0.0.0')\n","sub_path":"flask_app.py","file_name":"flask_app.py","file_ext":"py","file_size_in_byte":738,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"287714672","text":"from ranger.api.commands import Command\n\nclass show_files_in_path_finder(Command):\n \"\"\"\n :show_files_in_path_finder\n\n Present selected files in finder\n \"\"\"\n\n def execute(self):\n import subprocess\n files = \",\".join(['\"{0}\" as POSIX file'.format(file.path) for file in self.fm.thistab.get_selection()])\n reveal_script = \"tell application \\\"Path Finder\\\" to reveal {{{0}}}\".format(files)\n # reveal_script = \"tell application \\\"Finder\\\" to reveal {{{0}}}\".format(files)\n activate_script = \"tell application \\\"Path Finder\\\" to activate\"\n # activate_script = \"tell application \\\"Finder\\\" to set frontmost to true\"\n script = \"osascript -e '{0}' -e '{1}'\".format(reveal_script, activate_script)\n self.fm.notify(script)\n subprocess.check_output([\"osascript\", \"-e\", reveal_script, \"-e\", activate_script])\n\nclass show_files_in_finder(Command):\n \"\"\"\n :show_files_in_finder\n\n Present selected files in finder\n \"\"\"\n\n def execute(self):\n import subprocess\n files = \",\".join(['\"{0}\" as POSIX file'.format(file.path) for file in self.fm.thistab.get_selection()])\n reveal_script = \"tell application \\\"Finder\\\" to reveal {{{0}}}\".format(files)\n activate_script = \"tell application \\\"Finder\\\" to set frontmost to true\"\n script = \"osascript -e '{0}' -e '{1}'\".format(reveal_script, activate_script)\n self.fm.notify(script)\n subprocess.check_output([\"osascript\", \"-e\", reveal_script, \"-e\", activate_script])\n\nclass toggle_flat(Command):\n \"\"\"\n :toggle_flat\n\n Flattens or unflattens the directory view.\n \"\"\"\n\n def execute(self):\n if self.fm.thisdir.flat == 0:\n self.fm.thisdir.unload()\n self.fm.thisdir.flat = -1\n self.fm.thisdir.load_content()\n else:\n self.fm.thisdir.unload()\n self.fm.thisdir.flat = 0\n self.fm.thisdir.load_content()\n\nclass fzf_select(Command):\n \"\"\"\n :fzf_select\n\n Find a file using fzf.\n\n With a prefix argument select only directories.\n\n See: https://github.com/junegunn/fzf\n \"\"\"\n def execute(self):\n import subprocess\n import os.path\n if self.quantifier:\n # match only directories\n command=\"find -L . \\( -path '*/\\.*' -o -fstype 'dev' -o -fstype 'proc' \\) -prune \\\n -o -type d -print 2> /dev/null | sed 1d | cut -b3- | fzf +m\"\n else:\n # match files and directories\n command=\"find -L . \\( -path '*/\\.*' -o -fstype 'dev' -o -fstype 'proc' \\) -prune \\\n -o -print 2> /dev/null | sed 1d | cut -b3- | fzf +m\"\n fzf = self.fm.execute_command(command, universal_newlines=True, stdout=subprocess.PIPE)\n stdout, stderr = fzf.communicate()\n if fzf.returncode == 0:\n fzf_file = os.path.abspath(stdout.rstrip('\\n'))\n if os.path.isdir(fzf_file):\n self.fm.cd(fzf_file)\n else:\n self.fm.select_file(fzf_file)\n","sub_path":"ranger/.config/ranger/commands.py","file_name":"commands.py","file_ext":"py","file_size_in_byte":3025,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"183580295","text":"# Modifed from R2C\n\"\"\"\nDataloaders for VCR\n\"\"\"\nimport json\nimport pickle\nimport os\nimport collections\nimport numpy as np\nimport numpy\nimport torch\nfrom allennlp.data.dataset import Batch\nfrom allennlp.data.fields import TextField, ListField, LabelField, SequenceLabelField, ArrayField, MetadataField\nfrom allennlp.data.instance import Instance\nfrom allennlp.data.token_indexers import ELMoTokenCharactersIndexer\nfrom allennlp.data.tokenizers import Token\nfrom allennlp.data.vocabulary import Vocabulary\nfrom allennlp.nn.util import get_text_field_mask\nfrom torch.utils.data import Dataset\nfrom dataloaders.box_utils import load_image, resize_image, to_tensor_and_normalize\nfrom dataloaders.mask_utils import make_mask\nfrom dataloaders.bert_field import BertField\nimport h5py\nfrom copy import deepcopy\nfrom tqdm import tqdm\nimport cv2\nfrom torchvision import transforms\n\nfrom .vcr_data_utils import data_iter, data_iter_test, data_iter_item\n\nfrom .bert_data_utils import InputExample, InputFeatures, get_one_image_feature_npz_screening_parameters, get_image_feat_reader, faster_RCNN_feat_reader, screen_feature\n\nfrom .bert_field import IntArrayField\n\nfrom visualbert.pytorch_pretrained_bert.fine_tuning import _truncate_seq_pair, random_word\nfrom visualbert.pytorch_pretrained_bert.tokenization import BertTokenizer\n\nGENDER_NEUTRAL_NAMES = ['Casey', 'Riley', 'Jessie', 'Jackie', 'Avery', 'Jaime', 'Peyton', 'Kerry', 'Jody', 'Kendall',\n 'Peyton', 'Skyler', 'Frankie', 'Pat', 'Quinn']\n\n# Here's an example jsonl\n# {\n# \"movie\": \"3015_CHARLIE_ST_CLOUD\",\n# \"objects\": [\"person\", \"person\", \"person\", \"car\"],\n# \"interesting_scores\": [0],\n# \"answer_likelihood\": \"possible\",\n# \"img_fn\": \"lsmdc_3015_CHARLIE_ST_CLOUD/3015_CHARLIE_ST_CLOUD_00.23.57.935-00.24.00.783@0.jpg\",\n# \"metadata_fn\": \"lsmdc_3015_CHARLIE_ST_CLOUD/3015_CHARLIE_ST_CLOUD_00.23.57.935-00.24.00.783@0.json\",\n# \"answer_orig\": \"No she does not\",\n# \"question_orig\": \"Does 3 feel comfortable?\",\n# \"rationale_orig\": \"She is standing with her arms crossed and looks disturbed\",\n# \"question\": [\"Does\", [2], \"feel\", \"comfortable\", \"?\"],\n# \"answer_match_iter\": [3, 0, 2, 1],\n# \"answer_sources\": [3287, 0, 10184, 2260],\n# \"answer_choices\": [\n# [\"Yes\", \"because\", \"the\", \"person\", \"sitting\", \"next\", \"to\", \"her\", \"is\", \"smiling\", \".\"],\n# [\"No\", \"she\", \"does\", \"not\", \".\"],\n# [\"Yes\", \",\", \"she\", \"is\", \"wearing\", \"something\", \"with\", \"thin\", \"straps\", \".\"],\n# [\"Yes\", \",\", \"she\", \"is\", \"cold\", \".\"]],\n# \"answer_label\": 1,\n# \"rationale_choices\": [\n# [\"There\", \"is\", \"snow\", \"on\", \"the\", \"ground\", \",\", \"and\",\n# \"she\", \"is\", \"wearing\", \"a\", \"coat\", \"and\", \"hate\", \".\"],\n# [\"She\", \"is\", \"standing\", \"with\", \"her\", \"arms\", \"crossed\", \"and\", \"looks\", \"disturbed\", \".\"],\n# [\"She\", \"is\", \"sitting\", \"very\", \"rigidly\", \"and\", \"tensely\", \"on\", \"the\", \"edge\", \"of\", \"the\",\n# \"bed\", \".\", \"her\", \"posture\", \"is\", \"not\", \"relaxed\", \"and\", \"her\", \"face\", \"looks\", \"serious\", \".\"],\n# [[2], \"is\", \"laying\", \"in\", \"bed\", \"but\", \"not\", \"sleeping\", \".\",\n# \"she\", \"looks\", \"sad\", \"and\", \"is\", \"curled\", \"into\", \"a\", \"ball\", \".\"]],\n# \"rationale_sources\": [1921, 0, 9750, 25743],\n# \"rationale_match_iter\": [3, 0, 2, 1],\n# \"rationale_label\": 1,\n# \"img_id\": \"train-0\",\n# \"question_number\": 0,\n# \"annot_id\": \"train-0\",\n# \"match_fold\": \"train-0\",\n# \"match_index\": 0,\n# }\n\nVIDEO_EXTENSIONS = ('.avi', '.mp4')\n\ndef is_video_file(f):\n return f.lower().endswith(VIDEO_EXTENSIONS)\n\ndef video_to_tensor(vid):\n return torch.from_numpy(vid.transpose([3, 0, 1, 2]))\n\nclass MPIIDataset(Dataset):\n def __init__(self, args):\n super(MPIIDataset, self).__init__()\n\n self.args = args\n self.annots_path = args.annots_path\n self.split_name = args.split_name\n self.data_root = args.data_root\n\n # Map each video file name to its annotated description\n self.annots = self.parse_annots(self.annots_path)\n\n # Map each video file name to its absolute location\n self.movies = self.parse_video_files(self.data_root)\n\n self.annots = {key:value for key, value in self.annots.items()\n if key in self.movies.keys()}\n self.movies = {key:value for key, value in self.movies.items()\n if key in self.annots.keys()}\n\n self.vocab = Vocabulary()\n\n self.do_lower_case = args.do_lower_case\n self.bert_model_name = args.bert_model_name\n\n self.max_seq_length = args.max_seq_length\n self.tokenizer = BertTokenizer.from_pretrained(self.bert_model_name, do_lower_case=self.do_lower_case)\n self.pretraining = args.pretraining\n\n # This is for pretraining\n self.masked_lm_prob = 0.15\n self.max_predictions_per_seq = 20\n self.max_video_frames = 12\n\n self.rows = 224\n self.cols = 224\n\n self.transform_frame = transforms.Compose([transforms.ToPILImage(),\n transforms.Resize((self.rows, self.cols)),\n transforms.ToTensor(),\n transforms.Normalize([0.5] * 3, [0.5] * 3)])\n\n def parse_video_files(self, data_root):\n movies = collections.defaultdict()\n for root, _, files in os.walk(data_root):\n for f in files:\n if (is_video_file(f)):\n filename = os.path.abspath(os.path.join(root, f))\n movie_name = os.path.basename(os.path.dirname(filename))\n movies[os.path.splitext(f)[0]] = {\"filename\": filename, \"movie_name\": movie_name}\n\n return movies\n\n def parse_annots(self, annots_path):\n annots = collections.defaultdict()\n with open(annots_path, 'r') as f:\n for line in f:\n line = line.split()\n filename, start_time, end_time, caption = line[0], line[1], line[2], line[-1]\n annots[filename] = {\"start_time\": start_time, \"end_time\": end_time, \"caption\": caption}\n return annots\n\n @classmethod\n def splits(cls, args):\n data_root = args.data_root\n\n copy_args = deepcopy(args)\n copy_args.split_name = \"training\"\n copy_args.annots_path = os.path.join(data_root, \"LSMDC16_annos_{}.csv\".format(copy_args.split_name))\n\n trainset = cls(copy_args)\n trainset.is_train = True\n\n copy_args = deepcopy(args)\n copy_args.split_name = \"val\"\n copy_args.annots_path = os.path.join(data_root, \"LSMDC16_annos_{}.csv\".format(copy_args.split_name))\n\n validationset = cls(copy_args)\n validationset.is_train = False\n\n testset = validationset\n\n return trainset, validationset, testset\n\n def __len__(self):\n return len(self.annots)\n\n def _get_video_frames(self, filename):\n if filename is not None:\n vc = cv2.VideoCapture(filename)\n length = int(vc.get(cv2.CAP_PROP_FRAME_COUNT))\n\n frames = []\n count = 0\n return_val = True\n while count < length and return_val:\n return_val, frame = vc.read()\n frames.append(frame)\n count += 1\n\n vc.release()\n else:\n length = 0\n frames = []\n\n video_tensor = torch.zeros([3, self.max_video_frames, self.rows, self.cols])\n\n if len(frames) <= self.max_video_frames:\n num_frames = len(frames)\n indexes = range(len(frames))\n else:\n num_frames = self.max_video_frames\n indexes = range(len(frames))\n step = len(frames) // self.max_video_frames\n indexes = range(0, len(frames), step)[:self.max_video_frames]\n\n for vidx, fidx in enumerate(indexes):\n video_tensor[:, vidx, :, :] = self.transform_frame(frames[fidx])\n\n return np.array(num_frames), video_tensor\n\n def __getitem__(self, index):\n sample = {}\n\n all_keys = [k for k in self.annots.keys()]\n video_id_0 = all_keys[index]\n start_time_0 = self.annots[video_id_0][\"start_time\"]\n\n video_file_0 = self.movies[video_id_0][\"filename\"]\n movie_name_0 = self.movies[video_id_0][\"movie_name\"]\n\n video_id_1 = [vid for vid in self.annots.keys() \\\n if vid != video_id_0 \\\n and self.movies[vid][\"movie_name\"] == movie_name_0 \\\n and self.annots[vid][\"start_time\"] > start_time_0]\n\n if len(video_id_1):\n video_id_1 = np.random.choice(video_id_1)\n video_file_1 = self.movies[video_id_1][\"filename\"]\n else:\n video_id_1 = None\n\n if video_id_1 is not None and (self.args.get(\"next_video\", True) or self.args.get(\"two_sentence\", True)):\n if np.random.random() > 0.5:\n video_frames_0, video_0 = self._get_video_frames(video_file_0)\n video_frames_1, video_1 = self._get_video_frames(video_file_1)\n caption_0 = self.annots[video_id_0][\"caption\"]\n caption_1 = self.annots[video_id_1][\"caption\"]\n next_video_label = np.array([1])\n else:\n video_frames_1, video_1 = self._get_video_frames(video_file_0)\n video_frames_0, video_0 = self._get_video_frames(video_file_1)\n caption_1 = self.annots[video_id_0][\"caption\"]\n caption_0 = self.annots[video_id_1][\"caption\"]\n next_video_label = np.array([0])\n\n sample[\"video_0\"] = ArrayField(video_0)\n sample[\"video_1\"] = ArrayField(video_1)\n sample[\"video_frames_0\"] = IntArrayField(video_frames_0)\n sample[\"video_frames_1\"] = IntArrayField(video_frames_1)\n\n sample[\"next_video_label\"] = IntArrayField(next_video_label)\n sample[\"is_random_next\"] = IntArrayField(next_video_label)\n\n subword_tokens_0 = self.tokenizer.tokenize(caption_0)\n subword_tokens_1 = self.tokenizer.tokenize(caption_1)\n\n bert_example = InputExample(unique_id = index,\n text_a = subword_tokens_0, text_b = subword_tokens_1,\n is_correct = next_video_label,\n max_seq_length = self.max_seq_length)\n\n else:\n video_frames_0, video_0 = self._get_video_frames(video_file_0)\n video_frames_1, video_1 = self._get_video_frames(None)\n\n sample[\"video_0\"] = ArrayField(video_0)\n sample[\"video_1\"] = ArrayField(video_1)\n sample[\"video_frames_0\"] = IntArrayField(video_frames_0)\n sample[\"video_frames_1\"] = IntArrayField(video_frames_1)\n sample[\"next_video_label\"] = IntArrayField(np.array([0]))\n sample[\"is_random_next\"] = IntArrayField(np.array([0]))\n\n caption_0 = self.annots[video_id_0][\"caption\"]\n subword_tokens_0 = self.tokenizer.tokenize(caption_0)\n bert_example = InputExample(unique_id = index, text_a = subword_tokens_0,\n text_b = None, is_correct = None,\n max_seq_length = self.max_seq_length)\n\n bert_feature = InputFeatures.convert_one_example_to_features_pretraining(\n example = bert_example, tokenizer = self.tokenizer,\n probability = self.masked_lm_prob)\n\n bert_feature.insert_field_into_dict(sample)\n\n return Instance(sample)\n\n @staticmethod\n def collate_fn(data):\n if isinstance(data[0], Instance):\n batch = Batch(data)\n td = batch.as_tensor_dict()\n return td\n else:\n images, instances = zip(*data)\n images = torch.stack(images, 0)\n\n batch = Batch(instances)\n td = batch.as_tensor_dict()\n if 'question' in td:\n td['question_mask'] = get_text_field_mask(td['question'], num_wrapping_dims=1)\n td['question_tags'][td['question_mask'] == 0] = -2 # Padding\n if \"answer\" in td:\n td['answer_mask'] = get_text_field_mask(td['answers'], num_wrapping_dims=1)\n td['answer_tags'][td['answer_mask'] == 0] = -2\n\n td['box_mask'] = torch.all(td['boxes'] >= 0, -1).long()\n td['images'] = images\n return td\n","sub_path":"dataloaders/mpii_dataset.py","file_name":"mpii_dataset.py","file_ext":"py","file_size_in_byte":12425,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"385901833","text":"import os\nimport time\nimport asyncio\n\ndef GetJavaPath():\n flag = False\n paths = os.environ['path'].split(';')\n for path in paths:\n if 'jdk' in path:\n flag = True\n break\n if flag == True:\n return 'OK'\n else:\n return 'NO'\n\ndef Get_jar(path):\n jars = []\n for root, dirs, files in os.walk(path, topdown=False):\n for name in files:\n jars.append((os.path.join(root, name)))\n\n jars = [file for file in jars if 'jar' in file]\n return jars\n\nasync def GetClassInside(filename):\n cmd =\"jar.exe -tf %s\"%filename \n classes = os.popen(cmd).read().split('\\n')\n return classes\n\nasync def fun(filename):\n a = await GetClassInside(filename)\n\nif __name__ == \"__main__\":\n path = input('pls input path:')\n if path:\n jars = Get_jar(path)\n else:\n jars = Get_jar('.')\n \n time1 = time.time()\n tasks = []\n loop = asyncio.get_event_loop()\n\n for jar in jars:\n tasks.append(fun(jar))\n \n loop.run_until_complete(asyncio.wait(tasks))\n loop.close()\n\n \n print('解析%d个jar包,耗时%.2fs'%(len(jars),time.time()-time1))\n","sub_path":"tools/findclass_async.py","file_name":"findclass_async.py","file_ext":"py","file_size_in_byte":1156,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"580267998","text":"\n'''\n对于i个物品在j空间下能装满的大小dp[i][j]:\n不放第i个物品\ndp[i][j] = dp[i-1][j]\n放第i个物品\ndp[i][j] = dp[i-1][j-A[i]]+A[i]\n所以转移方程是dp[i][j] = max(dp[i-1][j], dp[i-1][j-A[i]]+A[i])\n'''\nclass Solution:\n \"\"\"\n @param m: An integer m denotes the size of a backpack\n @param A: Given n items with size A[i]\n @return: The maximum size\n \"\"\"\n def backPack(self, m, A):\n if A is None or len(A) == 0 or m < 0:\n return 0\n dp = [0 for _ in range(m+1)]\n for i in range(len(A)):\n for j in range(m, 0, -1):\n if j >= A[i]:\n dp[j] = max(dp[j], dp[j-A[i]] + A[i])\n return dp[m]","sub_path":"dp/92_backpack.py","file_name":"92_backpack.py","file_ext":"py","file_size_in_byte":704,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"74637176","text":"import scrapy\nfrom scrapy.selector import Selector\nfrom wk2hw1.items import Wk2Hw1Item\n\n\nclass MoviesSpider(scrapy.Spider):\n name = 'movies'\n allowed_domains = ['maoyan.com']\n\n # start_urls = ['http://maoyan.com/']\n #\n # def parse(self, response):\n # pass\n\n def start_requests(self):\n url = 'https://maoyan.com/films?showType=3'\n yield scrapy.Request(url=url, callback=self.parse)\n\n def parse(self, response):\n movies = Selector(response=response).xpath('//div[@class=\"movie-hover-info\"]')\n item = Wk2Hw1Item()\n\n for movie in movies:\n film_name = movie.xpath('./div[1]/span/text()').extract()\n\n film_genre = movie.xpath('./div[2]/text()').extract()[1].strip('\\n').strip()\n play_date = movie.xpath('./div[4]/text()').extract()[1].strip('\\n').strip()\n item['film_name'] = film_name\n item['play_date'] = play_date\n item['film_genre'] = film_genre\n\n yield item\n","sub_path":"week02/wk2hw1/wk2hw1/spiders/movies.py","file_name":"movies.py","file_ext":"py","file_size_in_byte":997,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"216817925","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\n__author__ = \"Fireclaw the Fox\"\n__license__ = \"\"\"\nSimplified BSD (BSD 2-Clause) License.\nSee License.txt or http://opensource.org/licenses/BSD-2-Clause for more info\n\"\"\"\n\nfrom direct.gui import DirectGuiGlobals as DGG\nDGG.BELOW = \"below\"\n\nfrom direct.gui.DirectFrame import DirectFrame\n#from direct.gui.DirectOptionMenu import DirectOptionMenu\nfrom directGuiOverrides.DirectOptionMenu import DirectOptionMenu\n\nclass MenuBar():\n def __init__(self):\n screenWidthPx = base.getSize()[0]\n\n color = (\n (0.25, 0.25, 0.25, 1), # Normal\n (0.35, 0.35, 1, 1), # Click\n (0.25, 0.25, 1, 1), # Hover\n (0.1, 0.1, 0.1, 1)) # Disabled\n\n #\n # Menubar\n #\n self.menuBar = DirectFrame(\n frameColor=(0.25, 0.25, 0.25, 1),\n frameSize=(0,screenWidthPx,-12, 12),\n pos=(0, 0, -12),\n parent=base.pixel2d)\n\n x = 0\n\n self.file = DirectOptionMenu(\n text_fg=(1,1,1,1),\n text_scale=0.8,\n items=[\"New\", \"Save\", \"Load\", \"Quit\"],\n pos=(x, 0, -5),\n frameSize=(0,65/21,-7/21,17/21),\n frameColor=color,\n scale=21,\n relief=DGG.FLAT,\n item_text_fg=(1,1,1,1),\n item_text_scale=0.8,\n highlightScale=(0.8,0.8),\n item_relief=DGG.FLAT,\n item_frameColor=color,\n item_pad=(0.2, 0.2),\n highlightColor=color[2],\n popupMenuLocation=DGG.BELOW,\n command=self.toolbarFileCommand,\n parent=self.menuBar)\n self.file[\"text\"] = \"File\"\n\n x += 65\n\n self.view = DirectOptionMenu(\n text_fg=(1,1,1,1),\n text_scale=0.8,\n items=[\"Zoom In\", \"Zoom Out\", \"Zoom 100%\"],\n pos=(x, 0, -5),\n frameSize=(0,65/21,-7/21,17/21),\n frameColor=color,\n scale=21,\n relief=DGG.FLAT,\n item_text_fg=(1,1,1,1),\n item_text_scale=0.8,\n highlightScale=(0.8,0.8),\n item_relief=DGG.FLAT,\n item_frameColor=color,\n item_pad=(0.2, 0.2),\n highlightColor=color[2],\n popupMenuLocation=DGG.BELOW,\n command=self.toolbarViewCommand,\n parent=self.menuBar)\n self.view[\"text\"] = \"View\"\n\n x += 65\n\n self.tools = DirectOptionMenu(\n text_fg=(1,1,1,1),\n text_scale=0.8,\n items=[\"Delete Nodes\", \"Copy Nodes\", \"Refresh\"],\n pos=(x, 0, -5),\n frameSize=(0,65/21,-7/21,17/21),\n frameColor=color,\n scale=21,\n relief=DGG.FLAT,\n item_text_fg=(1,1,1,1),\n item_text_scale=0.8,\n highlightScale=(0.8,0.8),\n item_relief=DGG.FLAT,\n item_frameColor=color,\n item_pad=(0.2, 0.2),\n highlightColor=color[2],\n popupMenuLocation=DGG.BELOW,\n command=self.toolbarToolsCommand,\n parent=self.menuBar)\n self.tools[\"text\"] = \"Tools\"\n\n x += 65\n\n\n self.nodeMap = {\n \"Numeric Input\":\"NumericNode\",\n \"Addition\":\"AddNode\",\n \"Divide\":\"DivideNode\",\n \"Multiply\":\"MultiplyNode\",\n \"Boolean Value\":\"BoolNode\",\n \"Boolean And\":\"BoolAnd\",\n \"Boolean Or\":\"BoolOr\",\n \"Simple Output\":\"TestOutNode\"\n }\n\n self.nodes = DirectOptionMenu(\n text_fg=(1,1,1,1),\n text_scale=0.8,\n items=list(self.nodeMap.keys()),\n pos=(x, 0, -5),\n frameSize=(0,65/21,-7/21,17/21),\n frameColor=color,\n scale=21,\n relief=DGG.FLAT,\n item_text_fg=(1,1,1,1),\n item_text_scale=0.8,\n highlightScale=(0.8,0.8),\n item_relief=DGG.FLAT,\n item_frameColor=color,\n item_pad=(0.2, 0.2),\n highlightColor=color[2],\n popupMenuLocation=DGG.BELOW,\n command=self.toolbarNodesCommand,\n parent=self.menuBar)\n self.nodes[\"text\"] = \"Nodes\"\n\n def toolbarFileCommand(self, selection):\n if selection == \"New\":\n base.messenger.send(\"new\")\n elif selection == \"Save\":\n base.messenger.send(\"save\")\n elif selection == \"Load\":\n base.messenger.send(\"load\")\n elif selection == \"Quit\":\n base.messenger.send(\"quit\")\n\n self.file[\"text\"] = \"File\"\n\n def toolbarToolsCommand(self, selection):\n if selection == \"Delete Nodes\":\n base.messenger.send(\"removeNode\")\n elif selection == \"Copy Nodes\":\n taskMgr.doMethodLater(0.2, base.messenger.send, \"delayedCopyFromMenu\", extraArgs=[\"copyNodes\"])\n #base.messenger.send(\"copyNodes\")\n elif selection == \"Refresh\":\n base.messenger.send(\"refreshNodes\")\n #elif selection == \"Options\":\n # base.messenger.send(\"showSettings\")\n #elif selection == \"Help\":\n # base.messenger.send(\"showHelp\")\n\n self.tools[\"text\"] = \"Tools\"\n\n def toolbarViewCommand(self, selection):\n if selection == \"Zoom In\":\n base.messenger.send(\"zoom\", [True])\n elif selection == \"Zoom Out\":\n base.messenger.send(\"zoom\", [False])\n elif selection == \"Zoom 100%\":\n base.messenger.send(\"zoom_reset\")\n\n self.view[\"text\"] = \"View\"\n\n def toolbarNodesCommand(self, selection):\n base.messenger.send(\"addNode\", [self.nodeMap[selection]])\n\n self.nodes[\"text\"] = \"Nodes\"\n\n def resizeFrame(self):\n screenWidthPx = base.getSize()[0]\n self.menuBar[\"frameSize\"] = (0,screenWidthPx,-12, 12)\n self.menuBar.setPos(0, 0, -12)\n","sub_path":"MenuBar.py","file_name":"MenuBar.py","file_ext":"py","file_size_in_byte":5840,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"20536512","text":"import time\n\n\ndef log(*args, **kwargs):\n # time.time() 返回 unix time\n # 如何把 unix time 转换为普通人类可以看懂的格式呢?\n format = '%Y/%m/%d %H:%M:%S'\n value = time.localtime(int(time.time()))\n dt = time.strftime(format, value)\n print(dt, *args, **kwargs)\n\n\ndef ensure(condition, message):\n if not condition:\n log('xxxxx 测试失败', message)\n else:\n log('>>>>> 测试成功', message)\n\n\ndef isEquals(a, b, message):\n import json\n if json.dumps(a) == json.dumps(b):\n log('*** {} 测试成功, 大侄子牛逼呀'.format(message))\n else:\n log('xxxxx 测试失败 结果({}) 预期({}), {}'.format(a, b, message))\n\n\nimport random\n\n\ndef random_num(num1, num2):\n return random.randint(num1, num2)\n\n\ndef exchange(list, i, j):\n temp = list[i]\n list[i] = list[j]\n list[j] = temp\n\n\n\ndef load_codes():\n path = \"code.txt\"\n list = []\n with open(path) as all:\n for line in all:\n list.append(line)\n return list\n\ndef find2(s1, s2):\n # s1 s2 都是 string\n # 两个 str 的长度不限\n # 返回 s2 在 s1 中的下标, 从 0 开始, 如果不存在则返回 -1\n space = len(s2)\n for i in range(len(s1)):\n str = s1[i : i + space:]\n # log('str', str, i)\n if str == s2:\n # log('i', i, s2)\n return i\n return -1\n pass\n\ndef test_find2():\n find2('01234567', '345')\n \n# test_find2()\n\n\ndef find_between(str, left, right):\n s = str\n center = ''\n l = find2(s, left)\n data = s[l:: ]\n # log('data', data)\n r = find2(data, right) + l\n start = l + len(left)\n end = r\n # log('start', start, 'end', end)\n if start > 0 and end > 0:\n center = s[start: end:]\n # log('center', center)\n return center\n pass\n\ndef test_find_between():\n msg = 'find_between'\n s1 = 'meet ## halfway'\n s2 = 'meet ## ##way'\n left = '#<'\n right = '># '\n isEquals(find_between(s1, left, right), 'gua', msg)\n isEquals(find_between(s2, left, right), 'gua', msg)\n\n# test_find_between()\n\ndef load_file(path):\n p = path\n with open(p, 'rb') as f:\n data = f.read()\n return data\n pass\n\ndef is_space(str):\n r = False\n for s in str:\n if s == ' ':\n return True\n return r\n\n\ndef list_from_str(str):\n list = []\n if not is_space(str): # 是否包含空格\n list.append(str)\n else:\n list = str.split(' ')\n return list\n\ndef cut_blank(str):\n r = ''\n for i in str:\n if i != ' ':\n r += i\n return r\n\n\"\"\"\"\n注意 下面几题中的参数 op 是 operator(操作符) 的缩写\nop 是 string 类型, 值是 '+' '-' '*' '/' 其中之一\na b 分别是 2 个数字\n根据 op 对 a b 运算并返回结果(加减乘除)\n\"\"\"\n\n\ndef apply(operator, a, b):\n op = operator\n if op == '+':\n return a + b\n elif op == '-':\n return a - b\n elif op == '*':\n return a * b\n elif op == '/':\n return a / b\n\n\n\"\"\"\nop 是 '+' '-' '*' '/' 其中之一\noprands 是一个只包含数字的 array\n根据 op 对 oprands 中的元素进行运算并返回结果\n例如, 下面的调用返回 -4\nvar n = apply_list('-', [3, 4, 2, 1])\nlog(n)\n// 结果是 -4, 用第一个数字减去所有的数字\n\"\"\"\n\n\ndef apply_list(op, oprands):\n result = oprands[0]\n i = 1\n while i < len(oprands):\n result = apply(op, result, oprands[i])\n # log('result', i, result)\n i += 1\n return result\n\n\n\"\"\"\n 实现 apply_compare 函数\n参数如下\nexpression 是一个 array(数组), 包含了 3 个元素\n第一个元素是 op, 值是 '>' '<' '==' 其中之一\n剩下两个元素分别是 2 个数字\n根据 op 对数字运算并返回结果(结果是 true 或者 false)\n\"\"\"\n\n\ndef apply_compare(expression):\n op = expression[0]\n a = expression[1]\n b = expression[2]\n if op == '>':\n return a > b\n elif op == '<':\n return a < b\n elif op == '==':\n return a == b\n\n\n\"\"\"\n参数如下\nexpression 是一个 array\nexpression 中第一个元素是上面几题的 op, 剩下的元素是和 op 对应的值\n根据 expression 运算并返回结果\n\"\"\"\n\n\ndef apply_ops(expression):\n op = expression[0]\n if op in '+-*/':\n oprands = expression[1: len(expression)]\n log('oprand', oprands)\n return apply_list(op, oprands)\n else:\n return apply_compare(expression)","sub_path":"else.gua/gua03/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":4455,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"351007414","text":"# -*- coding: utf-8 -*-\nfrom openerp import models, api, fields, _\nfrom openerp.exceptions import ValidationError\n\n\nclass AccountInvoice(models.Model):\n _inherit = \"account.invoice\"\n\n late_delivery_work_acceptance_id = fields.Many2one(\n 'purchase.work.acceptance',\n string='Late Delivery Acceptance',\n domain=[('total_fine', '>', 0.0), ('invoiced', '=', False)],\n copy=False,\n readonly=True,\n states={'draft': [('readonly', False)]},\n help=\"List Purchase Work Acceptance with total_fine > 0.0 \"\n \"and not already invoiced\",\n )\n wa_id = fields.Many2one(\n comodel_name='purchase.work.acceptance',\n string='Work Acceptance',\n readonly=True,\n help=\"Related WA and Invoice\",\n )\n wa_origin_id = fields.Many2one(\n comodel_name='purchase.work.acceptance',\n readonly=True,\n help=\"WA First time, Use case cancel WA and set to draft\",\n )\n date_accept = fields.Date(\n related='wa_id.date_accept',\n string='Acceptance Date',\n help='Related from Acceptance Date in Work Acceptance',\n readonly=True,\n )\n date_transfer = fields.Date(\n string='Transfer Date',\n compute='_compute_date_transfer',\n help='Computed from Date Done in IN',\n )\n\n @api.multi\n @api.depends('wa_id')\n def _compute_date_transfer(self):\n picking = self.env['stock.picking']\n for rec in self:\n if rec.wa_id:\n picking_id = picking.search([\n ('acceptance_id', '=', rec.wa_id.id)])\n rec.date_transfer = \\\n picking_id and picking_id.date_done or False\n\n @api.multi\n def _compute_wa_id_from_origin(self):\n for rec in self:\n rec.wa_id = rec.wa_origin_id\n\n @api.model\n def _get_account_id_from_product(self, product, fpos):\n account_id = product.property_account_expense.id\n if not account_id:\n categ = product.categ_id\n account_id = categ.property_account_expense_categ.id\n if not account_id:\n raise ValidationError(\n _('Define an expense account for this '\n 'product: \"%s\" (id:%d).') %\n (product.name, product.id,))\n if fpos:\n account_id = fpos.map_account(account_id)\n return account_id\n\n @api.onchange('late_delivery_work_acceptance_id')\n def _onchange_late_delivery_work_acceptance_id(self):\n # This method is called from Customer invoice to charge penalty\n if self.late_delivery_work_acceptance_id:\n self.invoice_line = []\n acceptance = self.late_delivery_work_acceptance_id\n self.taxbranch_id = acceptance.order_id.taxbranch_id\n penalty_line = self.env['account.invoice.line'].new()\n # amount_penalty = acceptance.total_fine_cal\n amount_penalty = acceptance.total_fine\n if acceptance.is_manual_fine:\n amount_penalty = acceptance.manual_fine\n company = self.env.user.company_id\n activity_group = company.delivery_penalty_activity_group_id\n activity = company.delivery_penalty_activity_id\n if not activity_group or not activity:\n raise ValidationError(_('No AG/A for late delivery has been '\n 'set in Account Settings!'))\n sign = self.type in ('out_invoice', 'out_refund') and 1 or -1\n penalty_line.activity_group_id = activity_group\n penalty_line.activity_id = activity\n penalty_line.account_id = activity.account_id\n penalty_line.name = (u'%s WA เลขที่ %s' %\n (activity.account_id.name, acceptance.name,))\n penalty_line.quantity = 1.0\n penalty_line.price_unit = sign * amount_penalty\n # If chart field is required, try getting from the PO line\n if penalty_line.require_chartfield:\n purchase = self.late_delivery_work_acceptance_id.order_id\n lines = purchase.order_line.filtered('require_chartfield').\\\n sorted(lambda l: l.price_subtotal, reverse=True)\n if lines:\n penalty_line.project_id = lines[0].project_id\n penalty_line.section_id = lines[0].section_id\n penalty_line.invest_asset_id = lines[0].invest_asset_id\n penalty_line.invest_construction_phase_id = \\\n lines[0].invest_construction_phase_id\n penalty_line.fund_id = lines[0].fund_id\n penalty_line.cost_control_id = lines[0].cost_control_id\n self.invoice_line += penalty_line\n","sub_path":"pabi_purchase_work_acceptance/models/account_invoice.py","file_name":"account_invoice.py","file_ext":"py","file_size_in_byte":4796,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"181674568","text":"# uncompyle6 version 3.7.4\n# Python bytecode 3.6 (3379)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: build/bdist.linux-x86_64/egg/bibliopixel/colors/printer.py\n# Compiled at: 2019-08-11 12:22:47\n# Size of source mod 2**32: 379 bytes\nfrom ..util import log\nfrom . import names\n\ndef printer(colors, use_hex=False):\n if not colors:\n return\n try:\n colors[0][0]\n except:\n assert len(colors) % 3 == 0\n colors = zip(*[iter(colors)] * 3)\n\n for i, color in enumerate(colors):\n log.printer('%2d:' % i, names.color_to_name(color, use_hex))","sub_path":"pycfiles/BiblioPixel-3.4.45-py3.6/printer.cpython-36.py","file_name":"printer.cpython-36.py","file_ext":"py","file_size_in_byte":632,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"255126575","text":"from database import Base\nfrom sqlalchemy import Column, Integer, String\nfrom sqlalchemy.types import DateTime\n\nclass Items(Base):\n \"\"\"\n Items table\n \"\"\"\n __tablename__ = 'items'\n id = Column(Integer, primary_key=True)\n name = Column(String(256))\n quantity = Column(Integer)\n description = Column(String(256))\n date_added = Column(DateTime())\n\n def __repr__(self):\n return '{ Item_id : %s, name:%s, quantity:%s, description:%s, date_added:%s}' % (self.id, self.name, self.quantity, self.description, self.date_added)\n","sub_path":"models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":554,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"597440749","text":"import urllib.request\nimport json \nimport time\nfrom PIL import Image\nfrom PIL import ImageFont \nfrom PIL import ImageDraw\n\ndef get_views():\n views = 1000000\n return views \n\ndef views_to_string(views): \n ret = []\n curr = 0 \n v = str(views)[::-1]\n for idx, i in enumerate(v):\n if idx % 3 == 0 and idx > 0: \n ret.append(\",\") \n ret.append(i)\n \n return \"\".join(ret[::-1])\n\ndef create_thumbnail(views): \n view_string = views_to_string(views)\n\n img = Image.open(\"sample-in.JPG\")\n draw = ImageDraw.Draw(img)\n font = ImageFont.truetype(\"Corp-Bold.otf\", 90)\n draw.text((510,100), view_string + \" VIEWS\", (50, 205, 50), font=font)\n draw.text((520,200), \"Likes\", (50, 205, 50), font=font)\n draw.text((530,300), \"Dislikes\", (50, 205, 50), font=font)\n draw.text((540,400), \"Comments\", (50, 205, 50), font=font)\n img.save(\"thumbnail.jpg\")\n\ndef main():\n # STEP 1: Get Video Views\n current_views = get_views()\n create_thumbnail(current_views)\n print(\"Finish The thumbnails\") \nif __name__ == \"__main__\":\n main()\n\n\n\n\n\n","sub_path":"Youtube_Thumnail_maker/updateThumbnail/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1096,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"446473168","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\nimport sys\nfrom os import path\nimport subprocess\n\nfrom nose_parameterized import parameterized\n\nfrom wdom.testing import TestCase\n\nroot = path.dirname(path.dirname(path.dirname(path.abspath(__file__))))\n\ncases = [\n ('wdom', 'css'),\n ('wdom', 'document'),\n ('wdom', 'element'),\n ('wdom', 'event'),\n ('wdom', 'interface'),\n ('wdom', 'misc'),\n ('wdom', 'node'),\n ('wdom', 'options'),\n ('wdom', 'parser'),\n ('wdom', 'tag'),\n ('wdom', 'testing'),\n ('wdom', 'web_node'),\n ('wdom', 'webif'),\n ('wdom', 'window'),\n ('wdom', 'server'),\n ('wdom.server', 'base'),\n ('wdom.server', 'handler'),\n ('wdom.server', '_tornado'),\n ('wdom', 'themes'),\n ('wdom.themes', 'default'),\n ('wdom.themes', 'kube'),\n ('wdom.examples', 'data_binding'),\n ('wdom.examples', 'rev_text'),\n ('wdom.examples', 'theming'),\n]\ntry:\n import aiohttp\n cases.append(('wdom.server', '_aiohttp'))\n del aiohttp\nexcept ImportError:\n pass\n\n\nclass TestImportModules(TestCase):\n @parameterized.expand(cases)\n def test_import(self, from_, import_):\n cmd = 'from {0} import {1}\\nlist(vars({1}).items())'\n proc = subprocess.Popen(\n [sys.executable, '-c', cmd.format(from_, import_)],\n stdout=subprocess.PIPE,\n stderr=subprocess.STDOUT,\n cwd=root,\n )\n proc.wait()\n if proc.returncode != 0:\n print(proc.stdout.read())\n self.assertEqual(proc.returncode, 0)\n\n def test_wdom_import(self):\n cmd = 'import wdom\\nlist(vars(wdom).items())'\n proc = subprocess.Popen(\n [sys.executable, '-c', cmd],\n stdout=subprocess.PIPE,\n stderr=subprocess.STDOUT,\n cwd=root,\n )\n proc.wait()\n if proc.returncode != 0:\n print(proc.stdout.read())\n self.assertEqual(proc.returncode, 0)\n","sub_path":"wdom/tests/test_imports.py","file_name":"test_imports.py","file_ext":"py","file_size_in_byte":1940,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"369084663","text":"import itertools\nfrom query_grammar import *\nfrom estnltk import *\n\nclass Match:\n def __init__(self, index, group=None, weight=1):\n '''Represents match at index\n '''\n assert 0 < weight <= 1, 'Weight must be between 0 and 1'\n self.index = index\n self.group = group\n\n def __str__(self):\n return 'M({})'.format(self.index)\n\n def __repr__(self):\n return str(self)\n\ninf = float('inf')\n_inf = -inf\n\n\ndef left_right(match, leftmost=inf, rightmost = _inf):\n if isinstance(match, Match):\n return (match.index, match.index)\n else:\n lr = [left_right(i) for i in match]\n leftmost = min([i[0] for i in lr] + [leftmost])\n rightmost = max([i[1] for i in lr] + [rightmost])\n return (leftmost, rightmost)\n\ndef left(match):\n return left_right(match)[0]\n\ndef right(match):\n return left_right(match)[1]\n\n\ndef distance(a, b, inorder=False):\n #TODO: Needs a better thought-out spec. This is just a hack for demonstration\n\n al, ar = left_right(a)\n bl, br = left_right(b)\n if inorder:\n res = bl - ar\n else:\n res = min([\n abs(al-bl),\n abs(ar-bl),\n abs(al-br),\n abs(ar-br)\n ])\n return res\n\n\ndef build_tree(root, estnltk_text, inverse = False):\n if isinstance(root, Word):\n for ind, word in enumerate(estnltk_text.split_by_words()):\n if not inverse:\n if root.matches(word):\n yield [Match(ind, group = root.meta.get('group', None))]\n else:\n if not root.matches(word):\n yield [Match(ind, group = root.meta.get('group', None))]\n\n elif hasattr(root, 'nested'):\n #!NB must come before AND check\n assert len(root.nodes) == 3\n a, b, c = root.nodes\n a_tree = (build_tree(a, estnltk_text, inverse=inverse))\n b_tree = (build_tree(b, estnltk_text, inverse=inverse))\n c_tree = (build_tree(c, estnltk_text, inverse=inverse))\n yield from ((a_t, b_t, c_t) for a_t, b_t, c_t in itertools.product(a_tree, b_tree, c_tree)\n if 0 < left(b_t) - right(a_t) <= root.slop and 0 < left(c_t) - right(b_t) <= root.slop)\n\n elif hasattr(root, 'consecutive'):\n #!NB must come before AND check\n assert len(root.nodes) == 2\n a, b = root.nodes\n a_tree = (build_tree(a, estnltk_text, inverse=inverse))\n b_tree = (build_tree(b, estnltk_text, inverse=inverse))\n yield from ((a_t, b_t) for a_t, b_t in itertools.product(a_tree, b_tree)\n if 0 < distance(a_t, b_t, inorder=root.inorder) <= root.slop)\n\n elif isinstance(root, Word.AND):\n subtrees = (build_tree(node, estnltk_text, inverse=inverse) for node in root.nodes)\n yield from itertools.product(*subtrees)\n\n elif isinstance(root, Word.OR):\n subtrees = (build_tree(node, estnltk_text, inverse=inverse) for node in root.nodes)\n yield from itertools.chain(*subtrees)\n\n elif isinstance(root, Word.NOT):\n yield from build_tree(root.nodes[0], estnltk_text, inverse=not inverse)\n\n elif isinstance(root, Word.IMPLIES):\n #a >> b\n a, b = root.nodes\n\n #And trees\n subtrees = (build_tree(node, estnltk_text, inverse=inverse) for node in root.nodes)\n yield from itertools.product(*subtrees)\n\n\n a_not_tree = list(build_tree(a, estnltk_text, inverse=not inverse))\n b_not_tree = list(build_tree(b, estnltk_text, inverse=not inverse))\n\n yield from itertools.product(a_not_tree, b_not_tree)\n\n b_tree = list(build_tree(b, estnltk_text, inverse=inverse))\n\ndef flatten_matches(tr):\n if isinstance(tr, Match):\n return [tr]\n else:\n subs = list(itertools.chain(*(flatten_matches(i) for i in tr)))\n return subs\n\n","sub_path":"query_tree.py","file_name":"query_tree.py","file_ext":"py","file_size_in_byte":3841,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"602536847","text":"# -- coding:utf-8 --\r\n\r\nimport requests\r\nimport globals\r\n\r\nr = requests.post('http://%s:%s/delete_db/' % (globals.server_ip, globals.server_port))\r\nif r.status_code == 200:\r\n print('删库成功')\r\nelse:\r\n print('删库失败')\r\n","sub_path":"SchoolJudgeSummary/delete_db.py","file_name":"delete_db.py","file_ext":"py","file_size_in_byte":235,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"237086819","text":"def climbing(n):\n '''\n Problem:\n Climbing stairs\n You are climbing a stair case.It takes n steps to reach the top \n Each time you can either climb 1 or 2 steps \n In how many distinct ways can you climb to the the top \n\n 1.Define the objective function \n f(i) --> nu of distinct ways to reach the ith stair \n 2.identify the base cases\n f(0) = 1\n 3. break down to the simplest sub-problem \n 4.Write down a recurrences relation for optimized objective function \n f(n) = f(n-1) + f(n-2)\n 5.Order of excution is \n ---> Bottom up \n 6.Where to look for the answer \n dp[n-1]\n\n '''\n # Make our dp array with the two base cases and we'll prefill \n dp = [0] * (n+1)\n dp[0] = 1 \n dp[1] = 1 \n # print(dp)\n i = 2 \n while i < len(dp):\n dp[i] = dp[i-1] + dp[i-2]\n i +=1 \n print(dp[n]) \n '''\n Time complexity is o(n)\n space complexity is o(n) ---. we allocate to an array of size n\n ''' \n\n# climbing(4) \n# Lets optimize our solution by reducing the space complexity \n# if n was 1000,000 ===> used up 8 mb \n\n\ndef cli(n):\n # [1,1,2,3]\n # a b c\n # a b c \n # all we need to do is shift the numbers \n i = 2 \n a = 1 \n b = 1 \n while i <= n:\n c = a +b \n a = b \n b = c \n i+=1 \n print(c) \n # so for this function the space complexity is o(1)\n # but in this function is n == 1,000,000 then spce = 0.2 mb \n'''\nNow we can either make 1,2,3 steps \nour objective \nf(i) is the number of distinct wys to reach the ith stair \n3. Base cases \nf(0) = 1 ---> means if we have 0 stairs ways is one to choose not to do anything \nf(1) = 1 \nf(2) = \n'''\n\n\n","sub_path":".history/climbingStairs_20200709191333.py","file_name":"climbingStairs_20200709191333.py","file_ext":"py","file_size_in_byte":1689,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"456599365","text":"from math import *\r\n\r\n\r\n# Initialize parameters\r\nS = 214.95\r\nr = 0.06\r\nsigma = 0.37\r\nT = (20/365)\r\nN = 100\r\noption = 'Call'\r\n\r\ndef euro(S,r,sigma,K,N,option):\r\n # Compute more constants\r\n v = r-0.5*sigma**2\r\n deltaT = T/N\r\n disc = exp(-r*deltaT)\r\n dxu = sqrt((sigma**2)*deltaT+(v*deltaT)**2)\r\n dxd = -dxu\r\n # p = (exp(r*deltaT)-d)/(u-d) # probability of going up\r\n pu = 0.5+0.5*((v*deltaT)/dxu)\r\n pd = 1-pu\r\n\r\n # Initialize arrays\r\n St = [0]*(N+1)\r\n C = [0]*(N+1)\r\n\r\n # Initialize asset prices at maturity N\r\n St[0] = S*exp(N*dxd)\r\n for j in range(1,N):\r\n St[j] = St[j-1]*exp(dxu-dxd)\r\n\r\n # Initialize option values at maturity\r\n for j in range(0, N):\r\n if option == 'Call':\r\n C[j] = max(0.0, St[j] - K)\r\n elif option == 'Put':\r\n C[j] = max(0.0, K - St[j])\r\n\r\n # Step back through the tree\r\n for i in range(N-1, 0):\r\n for j in range(0, i):\r\n C[j] = disc*(pu*C[j+1]+pd*C[j])\r\n if option == 'Call':\r\n return C[int(N/2)]\r\n elif option == 'Put':\r\n return C[int(N/2)]\r\n\r\nKs = [70,115,120,121,123,125,126,129,130,141]\r\nfor i in Ks:\r\n print('For K=',i,'OptionV =',euro(S,r,sigma,i,N,option))","sub_path":"binomial.py","file_name":"binomial.py","file_ext":"py","file_size_in_byte":1226,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"197024912","text":"import pickle\nimport pandas as pd\nimport datetime\n\nprint(f\"Opening stocks dictionary... {datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')}\")\nwith open('all_stocks_max_period.pickle', 'rb') as stock_file:\n all_stocks_data = pickle.load(stock_file)\n\n# Computing the minimum dates of all stocks \nstock_codes = all_stocks_data.keys()\nmin_date_all_stocks = dict() \nfor stock_code in stock_codes:\n min_date_all_stocks[stock_code] = all_stocks_data[stock_code].index.min()\n\n# Cretaing a dataframe of stock codes and their minimum dates \nmin_time_stamps = pd.to_datetime(pd.Series(min_date_all_stocks.values()))\ndf_min_dates = pd.concat([pd.Series(stock_codes), min_time_stamps], axis=1)\ndf_min_dates.columns = ['Stock Code', 'Min Date']\ndf_min_dates.sort_values(ascending=True, by='Min Date', inplace=True)\n\n# Filtering stocks only for dates post 01-01-2001 \nall_stocks_data_post_2001 = dict()\nfor stock_code in all_stocks_data.keys():\n df = all_stocks_data[stock_code]\n df.drop(columns=['Stock Splits', 'Dividends'], inplace=True)\n df = df[df.index>datetime.datetime(2001, 1, 1)]\n # Removing columns with no data\n all_stocks_data_post_2001[stock_code] = df\n\n# Checking the updated dates for the 20 oldest stocks\ncount = 1\nfor stock, date in zip(df_min_dates['Stock Code'], df_min_dates['Min Date']):\n print(f\"For stock: {stock}\")\n print(f\"\\tOld date: {date}\", end=\" \")\n print(f\"\\tNew date: {all_stocks_data_post_2001[stock].index.min()}\\n\")\n if count==20:\n break\n count += 1\n \n# Creating a pickle file for the updated dictionary\nprint(\"Dumping the filtered data to a pickle file...\")\nwith open('all_stocks_data_post_2001.pkl', 'wb') as file:\n pickle.dump(all_stocks_data_post_2001, file)\n\nprint(f\"Dumping Completed... {datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')}\")\n\n\n###############################################################################\n\n\n# Opening stocks dictionary... 2021-10-27 10:52:34\n# For stock: TATAMOTORS.NS\n# \tOld date: 1995-12-25 00:00:00 \tNew date: 2001-01-02 00:00:00\n\n# For stock: MFSL.NS\n# \tOld date: 1996-01-01 00:00:00 \tNew date: 2001-01-02 00:00:00\n\n# For stock: ANDHRAPAP.NS\n# \tOld date: 1996-01-01 00:00:00 \tNew date: 2001-01-02 00:00:00\n\n# For stock: RELINFRA.NS\n# \tOld date: 1996-01-01 00:00:00 \tNew date: 2001-01-02 00:00:00\n\n# For stock: RIIL.NS\n# \tOld date: 1996-01-01 00:00:00 \tNew date: 2001-01-02 00:00:00\n\n# For stock: GHCL.NS\n# \tOld date: 1996-01-01 00:00:00 \tNew date: 2001-01-02 00:00:00\n\n# For stock: SAIL.NS\n# \tOld date: 1996-01-01 00:00:00 \tNew date: 2001-01-02 00:00:00\n\n# For stock: SBIN.NS\n# \tOld date: 1996-01-01 00:00:00 \tNew date: 2001-01-02 00:00:00\n\n# For stock: FEDERALBNK.NS\n# \tOld date: 1996-01-01 00:00:00 \tNew date: 2001-01-02 00:00:00\n\n# For stock: ESCORTS.NS\n# \tOld date: 1996-01-01 00:00:00 \tNew date: 2001-01-02 00:00:00\n\n# For stock: EIHOTEL.NS\n# \tOld date: 1996-01-01 00:00:00 \tNew date: 2001-01-02 00:00:00\n\n# For stock: EICHERMOT.NS\n# \tOld date: 1996-01-01 00:00:00 \tNew date: 2001-01-02 00:00:00\n\n# For stock: DRREDDY.NS\n# \tOld date: 1996-01-01 00:00:00 \tNew date: 2001-01-02 00:00:00\n\n# For stock: DEEPAKFERT.NS\n# \tOld date: 1996-01-01 00:00:00 \tNew date: 2001-01-02 00:00:00\n\n# For stock: SUNPHARMA.NS\n# \tOld date: 1996-01-01 00:00:00 \tNew date: 2001-01-02 00:00:00\n\n# For stock: CIPLA.NS\n# \tOld date: 1996-01-01 00:00:00 \tNew date: 2001-01-02 00:00:00\n\n# For stock: CENTURYTEX.NS\n# \tOld date: 1996-01-01 00:00:00 \tNew date: 2001-01-02 00:00:00\n\n# For stock: TATACHEM.NS\n# \tOld date: 1996-01-01 00:00:00 \tNew date: 2001-01-02 00:00:00\n\n# For stock: TATACONSUM.NS\n# \tOld date: 1996-01-01 00:00:00 \tNew date: 2001-01-02 00:00:00\n\n# For stock: TATAINVEST.NS\n# \tOld date: 1996-01-01 00:00:00 \tNew date: 2001-01-02 00:00:00\n\n# Dumping the filtered data to a pickle file...\n# Dumping Completed... 2021-10-27 10:53:02","sub_path":"data_preparation/data_prep_1.py","file_name":"data_prep_1.py","file_ext":"py","file_size_in_byte":3844,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"138398889","text":"import sys\nfrom Trubi import *\nfrom math import pow,ceil\nfrom PyQt5 import QtCore, QtGui, QtWidgets\n\n#dn=203\n#dm=203\n#delta=56.5\n#l0=9\n#lm=0\n#Km=1.05\nclass MyWin(QtWidgets.QMainWindow):\n def __init__(self, parent= None):\n QtWidgets.QWidget.__init__(self, parent)\n self.ui = Ui_MainWindow()\n self.ui.setupUi(self)\n\n self.ui.ButtonRaschet.clicked.connect(self.Diametr)\n\n def Diametr(self):\n dn= int(self.ui.DiametrNaruzh1.text())\n delta = float(self.ui.Tolshina1.text())\n db=(dn-2*delta)/1000\n self.ui.VnutrneniyDiametr1.setText(str(db))\n\n\n\nif __name__==\"__main__\":\n app = QtWidgets.QApplication(sys.argv)\n myapp = MyWin()\n myapp.show()\n sys.exit(app.exec_())","sub_path":"UBTS10.py","file_name":"UBTS10.py","file_ext":"py","file_size_in_byte":731,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"300275433","text":"import random\n\nfrom flask import Flask, render_template\nfrom flask_cors import CORS\nimport sqlite3\n\napp = Flask(__name__, template_folder = 'build', static_folder = 'build/static')\nCORS(app)\n\n# this is just for warmup\n@app.route('/hello')\ndef hello():\n return 'Hello from backend'\n\n@app.route('/services/randomcity')\ndef services_randomcity():\n randomCities = [\n 'Madrid', 'Hamburg', 'Rome', 'Kaoshiung',\n 'Brisbane', 'Shantou', 'Warsaw', 'Hangzhou',\n 'Fortaleza', 'Chengdu', 'Kwangju', 'Kano',\n 'Houston', 'Casablanca', 'Fukuoka', 'Hanoi',\n 'Karachi', 'Dhaka', 'Beijing', 'Saigon'\n ]\n return { 'Name': random.choice(randomCities) }\n\n@app.route('/')\ndef react():\n return render_template('index.html')\n\n#database helpers\ndef dict_factory(cursor, row):\n d = {}\n for idx, col in enumerate(cursor.description):\n d[col[0]] = row[idx]\n return d\n\ndef run_query(query):\n\n # revert before deploying\n # connection = sqlite3.connect(\"/home/ubuntu/flaskapp/cities.db\")\n connection = sqlite3.connect(\"cities.db\")\n\n connection.row_factory = dict_factory\n cursor = connection.cursor()\n cursor.execute(query)\n connection.commit()\n rows = cursor.fetchall()\n row_count = cursor.rowcount\n connection.close()\n return { 'rows': rows, 'row_count': row_count }\n\n# now the real api\n@app.route('/api/all')\ndef api_all():\n try:\n query = ('SELECT * FROM cities')\n rows = run_query(query)['rows']\n response = {'Cities': rows, 'Status': 0 }\n except Exception as e:\n response = {'Status': -1, 'Message': str(e) }\n return response\n\n@app.route('/api/add////')\ndef api_add(name, population, longitude, latitude):\n print('Hello there')\n try:\n query = \"INSERT INTO cities ('Name', 'Population', 'Longitude', 'Latitude') VALUES (\" + \\\n \"'\" + name + \"'\" + \",\" + population + \",\" + longitude + \",\" + latitude + \")\"\n row_count = run_query(query)['row_count']\n if (row_count == 1):\n response = {'Status': 0 }\n else:\n response = {'Status': -1 }\n\n except Exception as e:\n response = {'Status': -1, 'Message': str(e) }\n return response\n\n@app.route('/api/delete/')\ndef api_delete(counter):\n try:\n query = \"DELETE FROM cities WHERE Counter = \" + counter\n row_count = run_query(query)['row_count']\n if (row_count == 1):\n response = {'Status': 0 }\n else:\n response = {'Status': -1 }\n\n except Exception as e:\n response = {'Status': -1, 'Message': str(e) }\n\n print('Response from delete: ', response)\n return response\n\n@app.route('/api/movein//')\ndef api_movein(counter, how_many):\n try:\n query = \"SELECT Population FROM cities WHERE Counter = \" + counter\n query_result = run_query(query)['rows']\n if (len(query_result) == 0):\n response = {'Status': -1}\n else:\n new_population = query_result[0]['Population'] + how_many\n query = \"UPDATE cities SET Population = \" + str(new_population) + \" WHERE Counter = \" + counter\n row_count = run_query(query)['row_count']\n if (row_count == 1):\n response = {'Status': 0 }\n else:\n response = {'Status': -1 }\n except Exception as e:\n response = {'Status': -1, 'Message': str(e) }\n\n return response\n \n@app.route('/api/moveout//')\ndef api_moveout(counter, how_many):\n try:\n query = \"SELECT Population FROM cities WHERE Counter = \" + counter\n query_result = run_query(query)['rows']\n if (len(query_result) == 0):\n response = {'Status': -1}\n else:\n current_population = query_result[0]['Population']\n if (current_population <= how_many):\n raise Exception('Trying to create a ghost city')\n else:\n new_population = query_result[0]['Population'] - how_many\n query = \"UPDATE cities SET Population = \" + str(new_population) + \" WHERE Counter = \" + counter\n row_count = run_query(query)['row_count']\n if (row_count == 1):\n response = {'Status': 0 }\n else:\n response = {'Status': -1 }\n except Exception as e:\n response = {'Status': -1, 'Message': str(e) }\n\n return response\n \nif __name__ == '__main__':\n app.run(host = '0.0.0.0', debug = True)","sub_path":"facility/app_old.py","file_name":"app_old.py","file_ext":"py","file_size_in_byte":4433,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"216955209","text":"from django.conf.urls import patterns, include, url\n\n# Uncomment the next two lines to enable the admin:\nfrom django.contrib import admin\nadmin.autodiscover()\n\nurlpatterns = patterns('',\n # Examples:\n # url(r'^$', 'mysite.views.home', name='home'),\n # url(r'^mysite/', include('mysite.foo.urls')),\n\n # Uncomment the admin/doc line below to enable admin documentation:\n # url(r'^admin/doc/', include('django.contrib.admindocs.urls')),\n\n url(r'^tinymce/', include('tinymce.urls')),\n\n # Uncomment the next line to enable the admin:\n url(r'^admin/', include(admin.site.urls)),\n\n url(r'^$', 'app.views.showToday'),\n url(r'^(?P\\d+)-(?P\\d+).html$', 'app.views.showDay', name='day'),\n url(r'^entry/(?P\\d+).html$', 'app.views.showEntry', name='entry_detail'),\n\n)\n\n\n","sub_path":"mysite/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":812,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"76526836","text":"import numpy as np\n\ndef Euler(fcn, Tspan, I, Nt):\n \"\"\"\n Solve u' = fcn(u,t) for t in Tspan = [t0,te], \n u(t0) = I by a simple finite difference method.\n \"\"\"\n dt = (Tspan[1]-Tspan[0])/float(Nt)\n t = np.linspace(Tspan[0], Tspan[1], Nt+1)\n u = np.zeros(Nt+1)\n\n u[0] = I\n for n in range(Nt):\n dt = t[n+1] - t[n]\n u[n+1] = u[n] + dt*fcn( u[n], t[n] )\n \n return u, t\n\ndef visualize(u, t, I):\n import matplotlib.pyplot as plt\n plt.plot(t, u, 'r--o')\n t_fine = np.linspace(0, t[-1], 101) # for u_ex\n u_ex = u_exact(t_fine, I)\n plt.plot(t_fine, u_ex, 'b-')\n plt.legend(['numerical','exact'], loc='upper left')\n plt.xlabel('t')\n plt.ylabel('u')\n plt.grid(True)\n dt = t[1] - t[0]\n plt.title('dt=%g' % dt)\n umin = 1.1*u_ex.min(); umax = 0.5\n plt.axis([t[0], t[-1], umin, umax])\n plt.grid(True)\n plt.savefig('tmp1.eps'); plt.savefig('tmp1.pdf')\n plt.show()\n\nif __name__ == '__main__':\n def fcn(u, t):\n return u*np.sin(t) \n\n def u_exact(t, I):\n return I*np.exp( 1 - np.cos(t) )\n\n I = -1; Tspan = [0,10]; Nt = 50\n\n u, t = Euler(fcn, Tspan, I, Nt)\n visualize(u , t , I)\n","sub_path":"Euler_v1.py","file_name":"Euler_v1.py","file_ext":"py","file_size_in_byte":1179,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"391147607","text":"# Colors that can be used to color blocks.\n\n\nBLACK = 30\nRED = 31\nGREEN = 32\nYELLOW = 33\nBLUE = 34\nMAGENTA = 35\nCYAN = 36\nWHITE = 37\n\nALL_COLORS = [BLACK,RED,GREEN,YELLOW,BLUE,MAGENTA,CYAN,WHITE]\n\ndef is_proper_color(color):\n \"\"\"\n Check whether the given color is a proper color.\n - True if the given color is one of the colors defined above.\n ASSUMPTIONS\n - None\n \"\"\"\n return color in ALL_COLORS\n\ndef get_random_color():\n \"\"\"\n Return a random color.\n \"\"\"\n import random\n return random.choice(ALL_COLORS)\n\ndef get_color_name(color):\n \"\"\"\n Return the name for the given color.\n - The function returns the name for the color as used in the GUI.\n ASSUMPTIONS\n - The given color is a proper color.\n \"\"\"\n assert is_proper_color(color)\n if color == BLACK:\n return \"black\"\n elif color == RED:\n return \"red\"\n elif color == GREEN:\n return \"green\"\n elif color == YELLOW:\n return \"yellow\"\n elif color == BLUE:\n return \"blue\"\n elif color == MAGENTA:\n return \"magenta\"\n elif color == CYAN:\n return \"cyan\"\n elif color == WHITE:\n return \"white\"\n\n\n","sub_path":"Color.py","file_name":"Color.py","file_ext":"py","file_size_in_byte":1213,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"631282420","text":"import os\nfrom pathlib import Path\nimport shutil\nfrom skimage import io\nimport random\nimport cv2\nfrom sklearn.utils import Bunch\nimport numpy as np\nfrom skimage.feature import hog\n\n\n\n#function use to separate the training and testing set\ndef split_dataset(path):\n dir=os.getcwd()\n for folderName, subfolders, filenames in os.walk(path):\n try:\n #\n os.mkdir(dir+\"\\\\\"+path+\"\\\\Training\")\n os.mkdir(dir+\"\\\\\"+path+\"\\\\Testing\")\n except OSError:\n print (\"Creation of the directory failed\" )\n else:\n print (\"Successfully created the directory \")\n for subfolder in subfolders:\n try:\n os.mkdir(dir+\"\\\\\"+path+\"\\\\Training\\\\\"+subfolder)\n os.mkdir(dir+\"\\\\\"+path+\"\\\\Testing\\\\\"+subfolder)\n except OSError:\n print (\"Creation of the directory failed\")\n else:\n print (\"Successfully created the directory \")\n print(folderName)\n print(subfolder)\n for r, d, f in os.walk(folderName+\"/\"+subfolder):\n size=len(f)\n print(f)\n for x in range(int(size*0.3)):\n file = random.choice(f)\n shutil.move(os.path.join(folderName+\"/\"+subfolder, file), dir+\"\\\\\"+path+\"\\\\Training\\\\\"+subfolder+\"\\\\\"+file)\n f.remove(file)\n for x in range(int(size-size*0.3)+1):\n file = random.choice(f)\n shutil.move(os.path.join(folderName+\"/\"+subfolder, file), dir+\"\\\\\"+path+\"\\\\Testing\\\\\"+subfolder+\"\\\\\"+file)\n f.remove(file)\n os.rmdir(dir+\"\\\\\"+path+\"\\\\\"+subfolder)\ndef load_files_supervised_learning(pathTrain,pathTest):\n dir = os.getcwd()\n image_dir_train = Path(pathTrain)\n image_dir_test = Path(pathTest)\n folders = [directory for directory in image_dir_train.iterdir() if directory.is_dir()]\n imageTabTrain=[]\n for i, direc in enumerate(folders):\n for file in direc.iterdir():\n img = io.imread(file)\n imageTabTrain.append([img.flatten(),i])\n random.shuffle(imageTabTrain)\n folders = [directory for directory in image_dir_test.iterdir() if directory.is_dir()]\n imageTabTest = []\n for i, direc in enumerate(folders):\n for file in direc.iterdir():\n img = io.imread(file)\n imageTabTest.append([img.flatten(), i])\n random.shuffle(imageTabTest)\n train=[]\n train_target=[]\n for (tab, num) in imageTabTrain:\n train.append(tab)\n train_target.append(num)\n train = np.array(train)\n train_target = np.array(train_target)\n test=[]\n test_target=[]\n for (tab, num) in imageTabTest:\n test.append(tab)\n test_target.append(num)\n test = np.array(test)\n test_target = np.array(test_target)\n return Bunch(dataTrain=train, targetTrain=train_target,dataTest=test, targetTest=test_target)\ndef load_files_unsupervised_learning_hog(option):\n PIXELS_PER_CELL = (7, 7)\n CELLS_PER_BLOCK = (1, 1)\n NORMALIZE = True\n BLOCK_NORM = \"L1\"\n image_dir = os.listdir(option)\n imageTab = []\n for i in range(len(image_dir)):\n image_dir[i] = int(str(image_dir[i])[:-4])\n image_dir.sort()\n for i in range(len(image_dir)):\n img = cv2.imread(\"H:/Desktop/SVM/DataTest/label/\" + str(image_dir[i]) + \".png\", 0)\n H = hog(img,\n orientations=9,\n pixels_per_cell=PIXELS_PER_CELL,\n cells_per_block=CELLS_PER_BLOCK,\n transform_sqrt=NORMALIZE,\n block_norm=BLOCK_NORM)\n imageTab.append(H)\n\n\n imageTab = np.array(imageTab)\n return Bunch(data=imageTab, file_name=image_dir)\n","sub_path":"fileManagement/fileManagement.py","file_name":"fileManagement.py","file_ext":"py","file_size_in_byte":3755,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"293311656","text":"import sys\n\n# Given: A collection of at most 10 DNA strings of equal length (at most 1 kbp) in FASTA format.\n#\n# Return: A consensus string and profile matrix for the collection.\n# (If several possible consensus strings exist, then you may return any one of them.)\nfile_path = sys.argv[1]\nfile = open(file_path, \"r\")\n\ndictionary = {}\nStrings = []\nProfile = []\nProfileA = \"A:\"\nProfileC = \"C:\"\nProfileG = \"G:\"\nProfileT = \"T:\"\nConsensus = \"\"\n\n# Stores each DNA string in a dictionary with the string as the value and the\n# ID as its key.\nfor line in file.readlines():\n if line.startswith('>'):\n key = line.rstrip(\"\\n\")[1:]\n String = \"\"\n else:\n String += line.rstrip(\"\\n\")\n dictionary[key] = String\n\n# Creates list 'Strings' with all of the Stringvalues from the dictionary\n# get(key) -> getValue of key 'key'\nfor key in dictionary:\n Strings.append(dictionary.get(key))\n\n# Creates Profile for all DNA strings. Counts the occurence of each nucleotide\n# at every position and returns a matrix.\nfor i in range(len(Strings[0])):\n counterA = 0\n counterT = 0\n counterC = 0\n counterG = 0\n for Sequence in Strings:\n if Sequence[i] == 'A':\n counterA += 1\n if Sequence[i] == 'C':\n counterC += 1\n if Sequence[i] == 'G':\n counterG += 1\n if Sequence[i] == 'T':\n counterT += 1\n ProfileA += str(counterA)\n ProfileC += str(counterC)\n ProfileG += str(counterG)\n ProfileT += str(counterT)\nProfile.extend((ProfileA, ProfileC, ProfileG, ProfileT))\nfor i in range(4):\n string_revised = ((Profile[i])[:2]) + \" \" + \" \".join((Profile[i])[2:])\n print(string_revised)\n\n# Takes the matrix into account and returns the Consensus of the matrix as\n# a string.\nedge = (len(Strings[0]) - 1) # edge of the String List\nfor i in range(len(Strings[0])):\n maxCons = None\n maxConsCount = 0\n for NucleotideFreq in Profile:\n if (i == edge):\n maxConsCountNuc = int(NucleotideFreq[2 + i:])\n else:\n maxConsCountNuc = int(NucleotideFreq[2 + i:i - edge])\n if (maxConsCountNuc > maxConsCount):\n maxConsCount = maxConsCountNuc\n maxCons = NucleotideFreq[0]\n if (NucleotideFreq == Profile[3]):\n Consensus += maxCons\nprint(Consensus)\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"Bioinformatics_Stronghold/Consensus_and_Profile.py","file_name":"Consensus_and_Profile.py","file_ext":"py","file_size_in_byte":2336,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"55883765","text":"from django.conf.urls import url\n\nfrom . import views\n\nurlpatterns = [\n url(r'^$', views.index, name='index'),\n url(r'^(?P[0-9]+)/$', views.recipedetails, name='recipedetails'),\n url(r'^(?P[0-9]+)/editrecipe$', views.EditRecipe.as_view(), name='editrecipe'),\n url(r'^addrecipe/$', views.addrecipe, name='addrecipe'),\n url(r'^(?P[0-9]+)/updaterecipe/$', views.updaterecipe, name='updaterecipe'),\n url(r'^(?P[0-9]+)/updateingredient/$', views.updateingredient, name='updateingredient'),\n]\n","sub_path":"menu/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":539,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"226255524","text":"# -*- coding: utf-8 -*-\n# @Time : 2019/1/28 12:09\n# @Author : xxx\n# @Email : xxx@admin.com\n# @File : server.py\n# @Software: PyCharm\n\nimport socket\nfrom threading import Thread\n\nsk = socket.socket()\nsk.bind(('127.0.0.1',9000))\nsk.listen()\n\ndef talk(conn):\n while True:\n conn.send(b'hello')\n\nwhile True:\n conn,addr = sk.accept()\n Thread(target=talk,args = (conn,)).start()","sub_path":"day28/多线程实现socket server/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":395,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"259353719","text":"from bs4 import BeautifulSoup\nimport requests\nimport random\n\n\ndef get_page():\n return requests.get('http://172.31.150.230:8080/userList').text\n\n\ndef get_name_list():\n bs = BeautifulSoup(get_page(), \"lxml\")\n tr_list = bs.find_all('tr')[1:]\n names = []\n for tr in tr_list:\n names.append(tr.find_all('td')[2].get_text())\n return names\n\n\ndef get_student_id_list():\n bs = BeautifulSoup(get_page(), \"lxml\")\n tr_list = bs.find_all('tr')[1:]\n ids = []\n for tr in tr_list:\n ids.append(tr.find_all('td')[3].get_text())\n return ids\n\n\ndef get_name_id_tuple_list():\n return [i for i in zip(get_name_list(), get_student_id_list())]\n\n\nif __name__ == '__main__':\n name_id = get_name_id_tuple_list()\n random.shuffle(name_id)\n for index in range(0, len(name_id)):\n print('team{0} {1} {2}'.format(index + 1, name_id[index][0], name_id[index][1]))\n","sub_path":"read_user_list.py","file_name":"read_user_list.py","file_ext":"py","file_size_in_byte":894,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"59834576","text":"import math\n\ndef gallons(x):\n gallonsamount = x / 350\n return gallonsamount\n\nshape = input(\"Do you wanna do a square or a circle?: \")\n\nif shape == \"square\":\n while True:\n try:\n length = int(input(\"What's the length of room feet? :\"))\n width = int(input(\"What's the width of room feet? :\"))\n\n except ValueError:\n print(\"Sorry, that's not a number.\")\n continue\n # better try again... Return to the start of the loop\n else:\n # age was successfully parsed!\n # we're ready to exit the loop.\n break\n\n areaFeet = length * width\n gallons = gallons(areaFeet)\n result = math.ceil(gallons)\n\n print(\"You will need to purchase\", result, \"of paint to cover\", areaFeet, \"square feet.\")\n\nelif shape == \"circle\":\n while True:\n try:\n radius = int(input(\"What the radius of the circle?: \"))\n except ValueError:\n print(\"Sorry, that's not a no.\")\n continue\n else:\n break\n\n areaCircle = round(((radius ** 2) * math.pi), 1)\n gallons = gallons(areaCircle)\n result = math.ceil(gallons)\n\n print(\"You will need to purchase\", result, \"of paint to cover\", areaCircle, \"square feet.\")\n","sub_path":"9-PaintCalc.py","file_name":"9-PaintCalc.py","file_ext":"py","file_size_in_byte":1253,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"254270737","text":"import numpy as np\nimport math\nimport pickle\nimport tensorflow as tf\nimport matplotlib.pyplot as plt\nimport os\nos.environ[\"TF_CPP_MIN_LOG_LEVEL\"] = \"2\"\nimport time\nimport keras\nfrom keras.models import Sequential, Model, load_model\nfrom keras.layers import Dense, Dropout, Conv2D, Conv2DTranspose, LeakyReLU, BatchNormalization, Softmax, Input, InputLayer, ReLU\nimport random\n# import pydotplus\n# import pydot \n# from keras.utils.vis_utils import model_to_dot\n# keras.utils.vis_utils.pydot = pydot\nfrom keras.utils.vis_utils import plot_model\n# from importlib import reload\n# reload(keras.utils.vis_utils)\n\n\nconfig = tf.compat.v1.ConfigProto(gpu_options = \n tf.compat.v1.GPUOptions(per_process_gpu_memory_fraction=0.8)\n# device_count = {'GPU': 1}\n)\nconfig.gpu_options.allow_growth = True\nsession = tf.compat.v1.Session(config=config)\ntf.compat.v1.keras.backend.set_session(session)\n\n\nconfigFile = configparser.ConfigParser()\nconfigFile.read('settings.ini')\nconfig = configFile['DEFAULT']\n\n# Settings\ncompanies_version = config['CompaniesVersion']\nmodel_type = int(config['ModelType'])\nnum_classes = int(config['NumClasses'])\nnum_anchors = int(config['NumAnchors'])\n\nwidth = int(config['ModelWidth'])\nheight = int(config['ModelHeight'])\nbatch_size_ini = int(config['BatchSize'])\nnum_train = int(config['NumTrain'])\nnum_val = int(config['NumVal'])\nnum_epochs = int(config['NumEpochs'])\n\ngenerator_path = config['GeneratorPath']\ngt_decoder_path = config['GroundTruth']\nspacygrid_path = config['SpacygridPath']\n\nif not os.path.exists(spacygrid_path):\n os.makedirs(spacygrid_path)\n\nspacy_gt = gt_decoder_path + \"x_spacy/\"\nseg_path = gt_decoder_path + \"seg/\"\nbox_path = gt_decoder_path + \"box/\"\ncoord_path = gt_decoder_path + \"coord/\"\n\nchannels = 96\n\ntotal_array = []\n\nfor i in range(8000):\n total_array.append(f\"{i}\")\n\nrandom.shuffle(total_array)\n\ntrain_ids = total_array[:6000]\nval_ids = total_array[6000:8000]\n\npart_list = {'train': train_ids, 'validation': val_ids}\n\ndef add_block_a(inputL, channelsIn, channelsOut):\n conv1 = Conv2D(channelsIn, kernel_size=3, activation='relu', strides=2)(inputL)\n batch1 = BatchNormalization()(conv1)\n conv2 = Conv2D(channelsOut, kernel_size=3, activation='relu', padding=\"same\")(batch1)\n batch2 = BatchNormalization()(conv2)\n conv3 = Conv2D(channelsOut, kernel_size=3, activation='relu', padding=\"same\")(batch2)\n batch3 = BatchNormalization()(conv3)\n outBa = Dropout(0.1)(batch3)\n return outBa\n\ndef add_block_a_dash(inputL, channelsIn, channelsOut):\n conv1 = Conv2D(channelsIn, kernel_size=3, activation='relu', strides=2)(inputL)\n batch1 = BatchNormalization()(conv1)\n conv2 = Conv2D(channelsOut, kernel_size=3, activation='relu', padding=\"same\", dilation_rate=1)(batch1)\n batch2 = BatchNormalization()(conv2)\n conv3 = Conv2D(channelsOut, kernel_size=3, activation='relu', padding=\"same\", dilation_rate=1)(batch2)\n batch3 = BatchNormalization()(conv3)\n outBaD = Dropout(0.1)(batch3)\n return outBaD\n\ndef add_block_b(inputL, channelsIn, channelsOut):\n conv1 = Conv2D(channelsIn, kernel_size=1, activation='relu')(inputL)\n batch1 = BatchNormalization()(conv1)\n conv2 = Conv2DTranspose(channelsOut, kernel_size=3, activation='relu', strides=2)(batch1)\n batch2 = BatchNormalization()(conv2)\n conv3 = Conv2D(channelsOut, kernel_size=3, activation='relu', padding=\"same\", dilation_rate=1)(batch2)\n batch3 = BatchNormalization()(conv3)\n conv4 = Conv2D(channelsOut, kernel_size=3, activation='relu', padding=\"same\", dilation_rate=1)(batch3)\n batch4 = BatchNormalization()(conv4)\n outBb = Dropout(0.1)(batch4)\n return outBb\n\ndef add_block_c(inputL, channelsIn, channelsOut):\n conv1 = Conv2D(channelsIn, kernel_size=1, activation='relu')(inputL)\n batch1 = BatchNormalization()(conv1)\n conv2 = Conv2DTranspose(channelsOut, kernel_size=3, activation='relu', strides=2)(batch1)\n batch2 = BatchNormalization()(conv2)\n outBc = Dropout(0.1)(batch2)\n return outBc\n\ndef add_block_d_e(inputL, channelsIn, channelsOut):\n conv1 = Conv2D(channelsIn, kernel_size=3, activation='relu', padding=\"same\")(inputL)\n batch1 = BatchNormalization()(conv1)\n conv2 = Conv2D(channelsIn, kernel_size=3, activation='relu', padding=\"same\")(batch1)\n batch2 = BatchNormalization()(conv2)\n conv3 = Conv2DTranspose(channelsOut, kernel_size=3, activation='relu', strides=2)(batch2)\n batch3 = BatchNormalization()(conv3)\n outBd = Softmax()(batch3)\n return outBd\n\ndef add_block_f(inputL, channelsIn, channelsOut):\n conv1 = Conv2D(channelsIn, kernel_size=3, activation='relu', padding=\"same\")(inputL)\n batch1 = BatchNormalization()(conv1)\n conv2 = Conv2D(channelsIn, kernel_size=3, activation='relu', padding=\"same\")(batch1)\n batch2 = BatchNormalization()(conv2)\n conv3 = Conv2DTranspose(channelsOut, kernel_size=3, activation='relu', strides=2)(batch2)\n batch3 = BatchNormalization()(conv3)\n outBf = LeakyReLU()(batch3)\n return outBf\n\ndef build_network():\n inputL = Input(shape=(height, width, channels))\n # Encoder\n blockA = add_block_a(inputL, channels, 2*channels) # first a block\n blockA2 = add_block_a(blockA, 2*channels,4*channels) # second a block \n blockAd = add_block_a_dash(blockA2, 4*channels,8*channels) # a' block\n\n encoder = Model(inputL, blockAd, name=\"Encoder\")\n\n latentDim =Input(shape=(44, 31, 8*channels))\n\n # Semantic decoder\n blockB = add_block_b(latentDim, 8*channels, 4*channels)\n blockC = add_block_c(blockB, 4*channels, 2*channels)\n blockD = add_block_d_e(blockC, 2*channels, num_classes)\n\n segDecoder = Model(latentDim, blockD, name=\"SegDecoder\")\n\n # BBox decoder\n blockB = add_block_b(latentDim, 8*channels, 4*channels)\n blockC = add_block_c(blockB, 4*channels, 2*channels)\n blockE = add_block_d_e(blockC, 2*channels, 2*num_anchors)\n\n boxDecoder = Model(latentDim, blockE, name=\"BoxDecoder\")\n\n # Coord decoder\n blockB = add_block_b(latentDim, 8*channels, 4*channels)\n blockC = add_block_c(blockB, 4*channels, 2*channels)\n blockF = add_block_f(blockC, 2*channels, 4*num_anchors)\n\n coordDecoder = Model(latentDim, blockF, name=\"CoordDecoder\")\n\n outputDecoders=[]\n if model_type == 1:\n outputDecoders.append(segDecoder(encoder(inputL)))\n if model_type == 2:\n outputDecoders.append(segDecoder(encoder(inputL)))\n outputDecoders.append(boxDecoder(encoder(inputL)))\n if model_type == 3:\n outputDecoders.append(segDecoder(encoder(inputL)))\n outputDecoders.append(boxDecoder(encoder(inputL)))\n outputDecoders.append(coordDecoder(encoder(inputL)))\n\n autoencoder = Model(inputs=inputL, outputs=outputDecoders, name=\"CompleteModel\")\n return autoencoder\n\nclass MyDataGenerator(tf.keras.utils.Sequence):\n def __init__(self, list_IDs, batch_size=5):\n self.list_IDs = list_IDs\n self.batch_size = batch_size\n self.shuffle = False\n self.on_epoch_end()\n\n def __len__(self):\n return math.ceil(self.total / self.batch_size)\n \n def __getitem__(self, idx):\n idxs = [i for i in range(idx*self.batch_size,(idx+1)*self.batch_size)]\n batch_X = np.zeros((self.batch_size, height, width, channels))\n batch_Y_Seg = np.zeros((self.batch_size, height-3, width-1, num_classes))\n batch_Y_Box = np.zeros((self.batch_size, height-3, width-1, 2*num_anchors))\n batch_Y_Coord = np.zeros((self.batch_size, height-3, width-1, 4*num_anchors))\n for i in range(self.batch_size):\n x = np.load(spacy_gt + str(idxs[i])+\".npy\")\n seg = np.load(seg_path + str(idxs[i])+\".npy\")\n box = np.load(box_path + str(idxs[i])+\".npy\")\n coord = np.load(coord_path + str(idxs[i])+\".npy\")\n batch_X[i] = x\n batch_Y_Seg[i] = seg\n batch_Y_Box[i] = box\n batch_Y_Coord[i] = coord\n \n if model_type == 1:\n y = batch_Y_Seg\n if model_type == 2:\n y = {\"SegDecoder\": batch_Y_Seg, \"BoxDecoder\": batch_Y_Box }\n if model_type == 3:\n y = {\"SegDecoder\": batch_Y_Seg, \"BoxDecoder\": batch_Y_Box, \"CoordDecoder\": batch_Y_Coord}\n return batch_X, y\n\n def on_epoch_end(self):\n 'Updates indexes after each epoch'\n self.indexes = np.arange(len(self.list_IDs))\n if self.shuffle == True:\n np.random.shuffle(self.indexes)\n\ntotal = num_train + num_val\n\nTrainGenerator = MyDataGenerator(start=0, end=num_train)\nValidGenerator = MyDataGenerator(start=num_train, end=total)\n\ncp_folder = spacygrid_path + \"models/\" + model_type + \"/CPs/\" \nif not os.path.exists(cp_folder):\n os.makedirs(cp_folder)\ncheckpoint_path = cp_folder + companies_version + \"_\"+ str(total) +\"I-{epoch:03d}E-{loss:03f}L-{val_loss:03f}VL.h5\"\ncp_callback = tf.keras.callbacks.ModelCheckpoint(filepath=checkpoint_path, monitor='val_loss', save_best_only=True, save_weights_only=True, verbose=1)\n\nmodel = build_network()\n\nif model_type == 1:\n losses = {\"SegDecoder\": \"categorical_crossentropy\"}\n lossWeights = {\"SegDecoder\": 1.0}\nif model_type == 2:\n losses = {\"SegDecoder\": \"categorical_crossentropy\", \"BoxDecoder\": \"binary_crossentropy\",}\n lossWeights = {\"SegDecoder\": 1.0, \"BoxDecoder\": 1.0}\nif model_type == 3:\n losses = {\"SegDecoder\": \"categorical_crossentropy\", \"BoxDecoder\": \"binary_crossentropy\", \"CoordDecoder\": \"huber_loss\",}\n lossWeights = {\"SegDecoder\": 1.0, \"BoxDecoder\": 1.0, \"CoordDecoder\": 1.0}\n\nmodel.compile(optimizer='adam', loss=losses, loss_weights=lossWeights, metrics=[\"acc\"])\n\nhistory = model.fit(TrainGenerator, validation_data=ValidGenerator, callbacks=[cp_callback], epochs=num_epochs) \nmodel.save(spacygrid_path + \"models/\" + model_type + \"/\" + companies_version + \"_\"+ str(total) +\"I-\" + str(num_epochs) + \"E.md\")\n\nnp.save(spacygrid_path + \"models/\" + model_type + \"/\" + companies_version + \"_\"+ str(total) +\"I-\" + str(num_epochs) + \"E_metrics.npy\", history.history)\n\nprint(history.history)\n","sub_path":"src/4_2_SpacyGrid_Model.py","file_name":"4_2_SpacyGrid_Model.py","file_ext":"py","file_size_in_byte":10028,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"471342870","text":"\n###########################################################################\n## Class Date\n###########################################################################\n\nclass Date( object ):\n\n __name = [ \"Invalid\", \"January\", \"February\", \"March\", \"April\", \n \"May\", \"June\", \"July\", \"August\", \"September\", \"October\", \n \"November\", \"December\" ]\n\n __days = [ 0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 ]\n \n def __init__( self, month=0, day=0, year=0 ):\n \n \"\"\" Construct a Date using three integers. \"\"\"\n \n self.__month = month\n self.__day = day\n self.__year = year\n self.__valid = self.__validate()\n if not self.__valid:\n self.__month = 0\n self.__day = 0\n self.__year = 0\n\n def __repr__( self ):\n\n \"\"\" Return a string as the formal representation a Date. \"\"\"\n\n out_str = \"Class Date: {:02d}/{:02d}/{:04d}\" \\\n .format( self.__month, self.__day, self.__year )\n\n return out_str\n\n def __str__( self ):\n\n \"\"\" Return a string (mm/dd/yyyy) to represent a Date. \"\"\"\n\n out_str = \"{:02d}/{:02d}/{:04d}\" \\\n .format( self.__month, self.__day, self.__year )\n\n return out_str\n\n def __validate( self ):\n\n # Check the month, day and year for validity\n # (does not account for leap years)\n\n flag = False\n\n if (1 <= self.__month <= 12) and \\\n (1 <= self.__day <= Date.__days[self.__month] ) and \\\n (0 <= self.__year):\n \n flag = True\n \n return flag\n\n def is_valid( self ):\n\n \"\"\" Return Boolean flag (valid date?) \"\"\"\n\n return self.__valid\n\n def from_iso( self, iso_str ):\n\n \"\"\" Convert a string (yyyy-mm-dd) into a Date. \"\"\"\n if \" \" in iso_str:\n year, month, day = [ int( n ) for n in iso_str.split()]\n else:\n year, month, day = [ int( n ) for n in iso_str.split( '-' )]\n \n self.__month = month\n self.__day = day\n self.__year = year\n self.__valid = self.__validate()\n if not self.__valid:\n self.__month = 0\n self.__day = 0\n self.__year = 0\n\n\n def from_mdy( self, mdy_str ):\n\n \"\"\" Convert a string (Mmmmm dd, yyyy) into a Date. \"\"\"\n\n mdy_list = mdy_str.replace(\",\",\"\").split()\n \n self.__month = Date.__name.index( mdy_list[0] )\n self.__day = int( mdy_list[1].strip() )\n self.__year = int( mdy_list[2].strip() )\n self.__valid = self.__validate()\n if not self.__valid:\n self.__month = 0\n self.__day = 0\n self.__year = 0\n\n def to_iso( self ):\n\n \"\"\" Return a string (yyyy-mm-dd) to represent a Date. \"\"\"\n\n iso_str = \"{:04d}-{:02d}-{:02d}\" \\\n .format( self.__year, self.__month, self.__day )\n\n return iso_str\n\n def to_mdy( self ):\n\n \"\"\" Return a string (Mmmmm dd, yyyy) to represent a Date. \"\"\"\n\n mdy_str = \"{:s} {:d}, {:04d}\" \\\n .format( Date.__name[self.__month], self.__day, self.__year )\n\n return mdy_str\n\n","sub_path":"lab12/date.py","file_name":"date.py","file_ext":"py","file_size_in_byte":3204,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"141236086","text":"import re\nimport requests\nfrom urllib.parse import urljoin\n\nheaders = {\n 'Cookie': '_abcde_qweasd=0; _abcde_qweasd=0; bdshare_firstime=1578460431003; UM_distinctid=16fb896a4171b5-063181e4bdeca9-504f221b-1fa400-16fb896a418891; CNZZDATA1253551727=1118628257-1579346291-%7C1579346291; BAIDU_SSP_lcr=https://www.baidu.com/link?url=QZxDTzpe3XB2Q1_dvvQ4UxdpCiyBZohqsEU9nMFL1T7&wd=&eqid=c357d038002f7628000000065e230bd8; Hm_lvt_169609146ffe5972484b0957bd1b46d6=1578492510,1578523933,1579315582,1579355102; Hm_lpvt_169609146ffe5972484b0957bd1b46d6=1579355110',\n 'Host': 'www.xbiquge.la',\n 'Referer': 'http://www.xbiquge.la/1/1690/',\n 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.88 Safari/537.36'\n}\n\nnumber = 0\nurl = \"http://www.xbiquge.la/1/1690/1267524.html\"\nwhile number <= 50:\n r = requests.get(url, headers=headers)\n r.encoding = r.apparent_encoding\n html = r.text\n\n pattern_title = re.compile('

(.*?)

', re.S)\n pattern_content = re.compile('
(.*?)
', re.S)\n pattern_lines = re.compile('\\ \\ \\ \\ (.*?)\\\\r
\\\\r
', re.S)\n pattern_next_url = re.compile('→ 下一章', re.S)\n\n try:\n title = pattern_title.findall(html)\n contents = pattern_content.findall(html)\n lines = pattern_lines.findall(contents[0])\n next_url = pattern_next_url.findall(html)[0]\n\n url = urljoin(url, next_url)\n print(url)\n with open(\"庆余年\\chapter-{}.txt\".format(number), 'w') as f:\n f.write(title[0] + '\\n')\n for line in lines:\n f.write(line + '\\n')\n print(line)\n number += 1\n except:\n pass","sub_path":"Demos/QYN.py","file_name":"QYN.py","file_ext":"py","file_size_in_byte":1760,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"8927058","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\ndef make_ngram(data, n):\n ngram = []\n for i in range(len(data) - n + 1):\n ngram.append(data[i:n+i])\n return ngram\n \ndef main():\n w1 = \"paraparaparadise\"\n w2 = \"paragraph\"\n ngram1 = make_ngram(w1, 2)\n ngram2 = make_ngram(w2, 2)\n x = set(ngram1)\n y = set(ngram2)\n print(x | y)\n print(x & y)\n print(x - y)\n print('se' in x)\n print('se' in y)\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"Chapter01/06.py","file_name":"06.py","file_ext":"py","file_size_in_byte":478,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"520052610","text":"import argparse\nfrom .run import run_day\n\n\ndef main() -> None:\n parser = argparse.ArgumentParser()\n parser.add_argument('day', type=str)\n parser.add_argument('-2', '--part2', action='store_true')\n\n args = parser.parse_args()\n day = args.day\n\n # Extract day from file name.\n if 'day' in day:\n day = int(day[3:5])\n else:\n day = int(day)\n\n result = run_day(day, args.part2)\n print(result)\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"2021/aoc2021/__main__.py","file_name":"__main__.py","file_ext":"py","file_size_in_byte":470,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"139914865","text":"from copy import deepcopy\n\nfrom point import Point\n\ndef get_possible_moves(game_map, mech, start_pos):\n moves = [(start_pos)]\n visited = [(start_pos)]\n\n _get_possible_moves(game_map, mech, start_pos, moves, visited)\n\n return moves\n\ndef _get_possible_moves(game_map, mech, start_pos, moves, visited):\n mech = deepcopy(mech)\n mech.move -= 1\n\n if mech.move < 0:\n return\n\n north = Point(start_pos.x, start_pos.y - 1)\n east = Point(start_pos.x + 1, start_pos.y)\n south = Point(start_pos.x, start_pos.y + 1)\n west = Point(start_pos.x - 1, start_pos.y)\n\n print(\"Pos is: \" + str(start_pos.x) + \" \" + str(start_pos.y))\n if north.y >= 0:\n if north not in moves and north not in visited:\n # If tile is not solid, it's obvious mech can move there...\n # TODO: However non-massive unit should also check\n # if there is a body of water, example: Freeze Tank\n if not game_map.get_tile(north).is_solid():\n print(\"Tile to north is not solid, I can move there\")\n moves.append(north)\n visited.append(north)\n _get_possible_moves(game_map, mech, north, moves, visited)\n\n # Tile is solid? It's not a problem for a flying mech\n elif mech.is_flying():\n # We cannot append such move, it's illegal (it would cause\n # the mech to be over mountain, mech, vek or building\n # which is not allowed\n print(\"I'm flying, I can move north\")\n visited.append(north)\n _get_possible_moves(game_map, mech, north, moves, visited)\n\n # Tile occupied by a vek? Not a problem for maneuverable mech\n elif mech.is_maneuverable() and game_map.get_tile(north).has_vek():\n # We cannot append such move, as the mech would end up\n # over vek, which is not allowed\n print(\"I'm maneuverable, I can move north\")\n visited.append(north)\n _get_possible_moves(game_map, mech, north, moves, visited)\n\n print(\"Pos is: \" + str(start_pos.x) + \" \" + str(start_pos.y))\n if east.x < game_map.get_x_length():\n if east not in moves and east not in visited:\n if not game_map.get_tile(east).is_solid():\n print(\"Tile to east is not solid, I can move there\")\n moves.append(east)\n visited.append(east)\n _get_possible_moves(game_map, mech, east, moves, visited)\n elif mech.is_flying():\n print(\"I'm flying, I can move east\")\n visited.append(east)\n _get_possible_moves(game_map, mech, east, moves, visited)\n elif mech.is_maneuverable() and game_map.get_tile(east).has_vek():\n print(\"I'm maneuverable, I can move east\")\n visited.append(east)\n _get_possible_moves(game_map, mech, east, moves, visited)\n\n print(\"Pos is: \" + str(start_pos.x) + \" \" + str(start_pos.y))\n if south.y < game_map.get_y_length():\n if south not in moves and south not in visited:\n if not game_map.get_tile(south).is_solid():\n print(\"Tile to south is not solid, I can move there\")\n moves.append(south)\n visited.append(south)\n _get_possible_moves(game_map, mech, south, moves, visited)\n elif mech.is_flying():\n print(\"I'm flying, I can move south\")\n visited.append(south)\n _get_possible_moves(game_map, mech, south, moves, visited)\n elif mech.is_maneuverable() and game_map.get_tile(south).has_vek():\n print(\"I'm maneuverable, I can move south\")\n visited.append(south)\n _get_possible_moves(game_map, mech, south, moves, visited)\n\n print(\"Pos is: \" + str(start_pos.x) + \" \" + str(start_pos.y))\n if west.x >= 0:\n if west not in moves and west not in visited:\n if not game_map.get_tile(west).is_solid():\n print(\"Tile to west is not solid, I can move there\")\n moves.append(west)\n visited.append(west)\n _get_possible_moves(game_map, mech, west, moves, visited)\n elif mech.is_flying():\n print(\"I'm flying, I can move west\")\n visited.append(west)\n _get_possible_moves(game_map, mech, west, moves, visited)\n elif mech.is_maneuverable() and game_map.get_tile(west).has_vek():\n print(\"I'm maneuverable, I can move west\")\n visited.append(west)\n _get_possible_moves(game_map, mech, west, moves, visited)\n\ndef push(game_map, from_pos, to_pos):\n # We assume that this will be a one tile push\n # We assume that from_pos is correct\n if to_pos.x >= game_map.get_x_length():\n print(\"Cannot push object out of map: X\")\n return\n\n if to_pos.y >= game_map.get_y_length():\n print(\"Cannot push object out of map: Y\")\n return\n\n from_tile = game_map.get_tile(from_pos)\n if not from_tile.has_mech() and not from_tile.has_vek():\n print(\"There is no movable object\")\n return\n\n to_tile = game_map.get_tile(to_pos)\n if to_tile.is_solid():\n from_tile.push_damage(1)\n to_tile.push_damage(1)\n return\n\n # Okay, so the \"to\" tile is not solid, so we push an object there\n if from_tile.has_mech():\n to_tile.mech = from_tile.get_mech()\n from_tile.mech = None\n return\n\n if from_tile.has_vek():\n to_tile.vek = from_tile.get_vek()\n from_tile.vek = None\n return\n\n # This will be implemented later\n raise NotImplemented\n\n\n\n\n","sub_path":"helpers.py","file_name":"helpers.py","file_ext":"py","file_size_in_byte":5771,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"34216515","text":"import base64\n\nfrom nf_common_source.code.services.identification_services.uuid_service.uuid_helpers.uuid_factory import create_uuid_from_base85_string\nfrom nf_common_source.code.services.identification_services.uuid_service.uuid_helpers.uuid_factory import create_uuid_from_canonical_format_string\n\n\ndef convert_base85_to_canonical_format(\n uuid_as_base85):\n uuid = \\\n create_uuid_from_base85_string(\n uuid_as_base85)\n\n return \\\n uuid\n\n\ndef convert_canonical_format_to_base85(\n uuid_as_canonical_format):\n uuid_from_canonical_format = \\\n create_uuid_from_canonical_format_string(\n uuid_as_canonical_format)\n\n uuid_as_base85 = \\\n base64.b85encode(\n uuid_from_canonical_format.bytes)\n\n uuid_as_base85_string = \\\n uuid_as_base85.decode()\n\n return \\\n uuid_as_base85_string\n","sub_path":"nf_common_source/code/services/identification_services/uuid_service/uuid_helpers/uuid_converter.py","file_name":"uuid_converter.py","file_ext":"py","file_size_in_byte":877,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"392449901","text":"import RPi.GPIO as GPIO\nimport time\nimport numpy as np\n\nGPIO.setwarnings(False)\nGPIO.cleanup()\nGPIO.setmode(GPIO.BCM)\n\nRB = 16 #red button\nGB = 12 #green button\nWB = 25 #white button\nRL = 27 #red led\nGL = 17 #green led\nWL = 4 #white led\nEL = 26 #ez led\nHL = 19 #hard led\nSB = 21 #start button\nDB = 20 #difficulty button\n\n#set up inputs and outputs\nGPIO.setup(RB, GPIO.IN, pull_up_down=GPIO.PUD_UP)\nGPIO.setup(GB, GPIO.IN, pull_up_down=GPIO.PUD_UP)\nGPIO.setup(WB, GPIO.IN, pull_up_down=GPIO.PUD_UP)\nGPIO.setup(SB, GPIO.IN, pull_up_down=GPIO.PUD_UP)\nGPIO.setup(DB, GPIO.IN, pull_up_down=GPIO.PUD_UP)\nGPIO.setup(RL, GPIO.OUT)\nGPIO.setup(GL, GPIO.OUT)\nGPIO.setup(WL, GPIO.OUT)\nGPIO.setup(EL, GPIO.OUT)\nGPIO.setup(HL, GPIO.OUT)\n\n#global variables\nmode = 0 #easy or hard mode\ngp = 0 #gameplay position\nkey = [] #answer key\nguessno = 0 #guess number\nstreak = 0 #streak amount\n\n#function resets the global variables\ndef reset():\n global mode\n mode = 0\n global gp\n gp = 0\n global key\n key = []\n global guessno\n guessno = 0\n\n#turns on the green LED\ndef green_light():\n GPIO.output(GL, GPIO.HIGH)\n GPIO.output(RL, GPIO.LOW)\n GPIO.output(WL, GPIO.LOW)\n \n#turns on the red LED \ndef red_light():\n GPIO.output(GL, GPIO.LOW)\n GPIO.output(RL, GPIO.HIGH)\n GPIO.output(WL, GPIO.LOW)\n\n#turns on the white LED\ndef white_light():\n GPIO.output(GL, GPIO.LOW)\n GPIO.output(RL, GPIO.LOW)\n GPIO.output(WL, GPIO.HIGH)\n\n#turns off all LEDs\ndef pause_time():\n GPIO.output(GL, GPIO.LOW)\n GPIO.output(RL, GPIO.LOW)\n GPIO.output(WL, GPIO.LOW)\n\n#enables easy mode\ndef easymode():\n GPIO.output(HL, GPIO.LOW)\n time.sleep(0.01)\n GPIO.output(EL, GPIO.HIGH)\n time.sleep(0.01)\n global mode\n mode = 0\n print('Easy Mode Enabled')\n\n#enabled hard mode\ndef hardmode():\n GPIO.output(EL, GPIO.LOW)\n time.sleep(0.01)\n GPIO.output(HL, GPIO.HIGH)\n time.sleep(0.01)\n global mode\n mode = 1\n print('Hard Mode Enabled')\n\n#prepares a new game, defaults to easy mode\ndef startup():\n GPIO.output(WL, GPIO.LOW)\n GPIO.output(GL, GPIO.LOW)\n GPIO.output(RL, GPIO.LOW)\n easymode()\n print('To start a new MEMORY GAME, press the BLUE button')\n print('To toggle difficulty, use BLACK button')\n\n#win circumstance\ndef win():\n reset()\n print('You have WON the GAME!')\n global streak\n streak += 1\n print('Streak: {}'.format(streak))\n for i in range(10):\n white_light()\n time.sleep(0.1)\n green_light()\n time.sleep(0.1)\n red_light()\n time.sleep(0.1)\n pause_time()\n startup()\n\n#losing circumstance\ndef lose():\n global streak\n streak = 0\n global mode\n if mode == 0:\n print('You have lost the game on EASY mode...really?')\n elif mode == 1:\n print('You have lost the game, maybe try EASY mode?')\n reset()\n startup() \n\n#checks the answer input\ndef checkanswer(x):\n global guessno\n global key\n print('Input Recieved')\n \n if x == key[guessno]:\n guessno += 1\n if guessno == len(key):\n win()\n else:\n lose()\n \ndef ezgame():\n global gp\n gp = 1\n randnums = np.random.randint(0,3,5)\n global key\n key = randnums\n \n i = 0\n while i < len(randnums):\n if randnums[i] == 0:\n red_light()\n elif randnums[i] == 1:\n green_light()\n elif randnums[i] == 2:\n white_light()\n \n time.sleep(1)\n pause_time()\n time.sleep(0.5)\n i += 1\n gp = 2\n\ndef hardgame():\n global gp\n gp = 1\n randnums = np.random.randint(0,3,8)\n global key\n key = randnums\n \n i = 0\n while i < len(randnums):\n if randnums[i] == 0:\n red_light()\n elif randnums[i] == 1:\n green_light()\n elif randnums[i] == 2:\n white_light()\n \n time.sleep(1)\n pause_time()\n time.sleep(0.3)\n i += 1\n gp = 2\n\n\nstartup()\nwhile True:\n st = GPIO.input(SB)\n dif_in = GPIO.input(DB)\n wb_in = GPIO.input(WB)\n gb_in = GPIO.input(GB)\n rb_in = GPIO.input(RB)\n \n if dif_in == False:\n #checks whether or not the game has started\n if gp == 0:\n if mode == 0:\n hardmode()\n elif mode == 1:\n easymode()\n else:\n print('Difficulty cannot be changed during the game!')\n time.sleep(0.5) \n\n if st == False:\n print('Game Beginning in 3 seconds!')\n time.sleep(3)\n if mode == 0:\n ezgame()\n elif mode == 1:\n hardgame()\n time.sleep(.03)\n print('Input your answer now!')\n \n if wb_in == False:\n if gp == 2:\n checkanswer(2)\n else:\n print('Cannot enter answer at this time')\n time.sleep(0.2)\n \n if gb_in == False:\n if gp == 2:\n checkanswer(1)\n else:\n print('Cannot enter answer at this time')\n time.sleep(0.2)\n \n if rb_in == False:\n if gp == 2:\n checkanswer(0)\n else:\n print('Cannot enter answer at this time')\n time.sleep(0.2)\n \n \n \n \n","sub_path":"memgame.py","file_name":"memgame.py","file_ext":"py","file_size_in_byte":5247,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"557881704","text":"\"\"\"\nDriver for the SG90 PWM-controlled servo\n\nUse the `value()` method to turn the servo to a given value.\n\nUse `release()` to power the motor off.\n\nBy default, the servo is positioned in degrees, -90 to +90.\nTo use different units, set \"min_value\" and \"max_value\" to the min/max\nvalues you wish to use.\n\nCalibrate the servo by setting min_pulse_ms and max_pulse_ms.\nThe datasheet says pulse width should be 1ms to 2ms.\n\"\"\"\n\nimport machine\n\nclass SG90:\n def __init__(\n self, pin,\n min_value=-90, max_value=90,\n min_pulse_ms=1, max_pulse_ms=2,\n freq=50,\n ):\n if isinstance(pin, int):\n pin = machine.Pin(pin, machine.Pin.OUT)\n self._min_value = min_value\n self._max_value = max_value\n self._value_range = max_value - min_value\n period_ms = 1000 / freq\n self._min_duty = min_pulse_ms / period_ms * 1024\n self._max_duty = max_pulse_ms / period_ms * 1024\n if not (0 < self._min_duty < self._max_duty < 1024):\n raise ValueError('pulse width or freq out of range')\n self._duty_range = self._max_duty - self._min_duty\n self._pwm = machine.PWM(pin, freq=freq, duty=0)\n\n def value(self, value=None):\n if value is None:\n duty = self._pwm.duty()\n if duty == 0:\n return None\n else:\n duty = self._pwm.duty()\n normalized = (duty - self._min_duty) / self._duty_range\n return normalized * self._value_range + self._min_value\n else:\n normalized = (value - self._min_value) / self._value_range\n duty = int(normalized * self._duty_range + self._min_duty)\n self._pwm.duty(duty)\n\n __call__ = value\n\n def release(self):\n self._pwm.duty(0)\n\n def __repr__(self):\n if self._pwm.duty() == 0:\n duty_repr = 'off'\n else:\n duty_repr = self.value()\n return ''.format(duty_repr)\n\n def demo(self):\n from time import sleep\n self.value(self._max_value)\n sleep(0.5)\n self.value(self._min_value)\n sleep(0.5)\n self.release()\n","sub_path":"drivers/olab_servo.py","file_name":"olab_servo.py","file_ext":"py","file_size_in_byte":2171,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"360496732","text":"ntl = {\n \"zero\": 0,\n \"one\": 1,\n \"two\": 2,\n \"three\": 3,\n \"four\": 4,\n \"five\": 5,\n \"six\": 6,\n \"seven\": 7,\n \"eight\": 8,\n \"nine\": 9,\n\n \"0\": \"zero\",\n \"1\": \"one\",\n \"2\": \"two\",\n \"3\": \"three\",\n \"4\": \"four\",\n \"5\": \"five\",\n \"6\": \"six\",\n \"7\": \"seven\",\n \"8\": \"eight\",\n \"9\": \"nine\",\n}\n\n\ndef checkKey(dict, key):\n if key in dict.keys():\n return True\n else:\n return False\n\n\nprint('Enter any number(1 - 9) in letters.')\nprint('Type quit to terminate the program.')\nwhile True:\n inp = input('> ')\n if inp.isdigit():\n print(ntl.get(inp))\n elif inp.isdigit() == False:\n if inp == \"quit\":\n break\n elif checkKey(ntl, inp):\n print(ntl.get(inp))\n else:\n print(\"That is not in the dictionary.\")\n\n else:\n print(\"I don't understand that.\")\n","sub_path":"py/Dictionaries/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":873,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"182753846","text":"st = 'Create a list of the first letters of every word in this string'\r\n#1st variant\r\nlst = []\r\nlst_letter = []\r\nst_list = st.split(' ')\r\nfor word in st_list:\r\n lst.append(word)\r\n for letter in word[0]:\r\n lst_letter.append(letter)\r\n\r\nprint(lst_letter)\r\n\r\n#2nd variant\r\nlst2 = [words[0] for words in st.split()]\r\nprint(lst2)\r\n","sub_path":"Create a list of the first letters of every word in this string.py","file_name":"Create a list of the first letters of every word in this string.py","file_ext":"py","file_size_in_byte":338,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"474466066","text":"from django.views.generic.base import TemplateView\nfrom django.views.generic.list import ListView\nfrom django.views.generic.edit import FormView\nfrom .forms import BucketItemForm, ClientForm\nfrom django.forms import formset_factory\nfrom django.http import HttpResponseRedirect\nfrom stock.models import Market\nfrom .cart import Cart\n\n\nclass MarketListView(ListView):\n model = Market\n template_name = \"bucket/market_list.html\"\n\nclass BucketItemFormView(FormView):\n template_name = \"bucket/bucketitem_form.html\"\n form_class = formset_factory(BucketItemForm,extra=0)\n success_url = \"/checkout/\"\n\n def get_initial(self):\n market_pk = self.kwargs.get('market_pk')\n cart = Cart(self.request.session)\n market_cart = cart.get_market(market_pk)\n initial = market_cart[\"products\"]\n return initial\n\n def form_valid(self, formset):\n market_pk = self.kwargs.get('market_pk')\n cart = Cart(self.request.session)\n cart.set_market(market_pk,formset)\n return HttpResponseRedirect(self.get_success_url())\n\nclass BucketCreateView(FormView):\n template_name = \"bucket/bucket_form.html\"\n form_class = ClientForm\n success_url = '/thanks/'\n\n def form_valid(self, form):\n cart = Cart(self.request.session)\n cart.save(form)\n return HttpResponseRedirect(self.get_success_url())\n\n def get_context_data(self, **kwargs):\n context = super().get_context_data(**kwargs)\n cart = Cart(self.request.session)\n context['total_price'] = cart.total_price()\n return context\n\nclass BucketCreatedView(TemplateView):\n template_name = \"bucket/thanks.html\"\n","sub_path":"click_collect/click_collect/bucket/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1660,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"421310590","text":"class Solution:\n def totalNQueens(self, n: int) -> int:\n def rec(col, horizontal, diag, anti_diag):\n if col == n:\n return 1\n\n res = 0\n\n for row in range(n):\n if row not in horizontal and (row + col) not in diag and (row - col) not in anti_diag:\n horizontal[row] = True\n diag[row + col] = True\n anti_diag[row - col] = True\n res += rec(col + 1, horizontal, diag, anti_diag)\n del horizontal[row]\n del diag[row + col]\n del anti_diag[row - col]\n\n return res\n\n return rec(0, {}, {}, {})\n","sub_path":"Leetcode/52. N-Queens II.py","file_name":"52. N-Queens II.py","file_ext":"py","file_size_in_byte":705,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"118710806","text":"#===============================================================================\r\n# Copyright (C) 2012 Diego Duclos\r\n# Copyright (C) 2013 Anton Vorobyov\r\n#\r\n# This code is free software; you can redistribute it and/or modify\r\n# it under the terms of the BSD license (see the file LICENSE.txt\r\n# included with the distribution).\r\n#===============================================================================\r\n\r\n\r\nimport json\r\nimport os\r\nfrom collections import OrderedDict\r\n\r\nimport reverence\r\n\r\n\r\nclass StubbingEncoder(json.JSONEncoder):\r\n \"\"\"\r\n Objects which cannot be serialized are replaced with stub\r\n \"\"\"\r\n\r\n def default(self, o):\r\n if isinstance(o, reverence.fsd.FSD_Dict):\r\n return dict(o)\r\n if isinstance(o, reverence.fsd._FixedSizeList):\r\n return tuple(o)\r\n if isinstance(o, reverence.fsd.FSD_Object):\r\n new = {}\r\n for attrName in o.attributes:\r\n new[attrName] = getattr(o, attrName, None)\r\n return new\r\n if isinstance(o, reverence.fsd.FSD_NamedVector):\r\n vector = OrderedDict()\r\n aliasData = o.schema['aliases']\r\n for alias in sorted(aliasData, key=aliasData.get):\r\n index = aliasData[alias]\r\n vector[alias] = o.data[index]\r\n return vector\r\n return 'unserializable class {}'.format(type(o))\r\n\r\n\r\nclass JsonWriter:\r\n \"\"\"Json writer, takes input from the rowSetProcessor and writes it out to json files in the given folder, one file per table\"\"\"\r\n def __init__(self, tableName, header, lines, folder, indent=None):\r\n self.tableName = tableName\r\n self.header = header\r\n self.lines = lines\r\n self.folder = folder\r\n self.indent = indent\r\n\r\n def run(self):\r\n dataList = []\r\n header = self.header\r\n\r\n # Data in the lines isn't always in primitive format\r\n # It might be wrapped in various classes that implement dict like interfaces\r\n # Dump it all in a \"real\" dict so json doesn't complain\r\n for line in self.lines:\r\n try:\r\n dataList.append({k: line[k] for k in header})\r\n except:\r\n print(line)\r\n raise\r\n if not os.path.exists(self.folder):\r\n os.makedirs(self.folder, mode=0o755)\r\n json.dump(\r\n dataList,\r\n open(os.path.join(self.folder, '{}.json'.format(self.tableName)), 'w'),\r\n cls=StubbingEncoder,\r\n indent=self.indent,\r\n encoding='cp1252'\r\n )\r\n","sub_path":"phobos/writer/jsonWriter.py","file_name":"jsonWriter.py","file_ext":"py","file_size_in_byte":2587,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"585420089","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Wed Jul 8 19:08:51 2020\r\n\r\n@author: MurthySatyavolu\r\n\"\"\"\r\n\r\nimport csv\r\n\r\nwith open('example.txt') as csvfile:\r\n readCSV = csv.reader(csvfile, delimiter=',')\r\n dates = []\r\n colors = []\r\n for row in readCSV:\r\n color = row[3]\r\n date = row[0]\r\n\r\n dates.append(date)\r\n colors.append(color)\r\n\r\n print(dates)\r\n print(colors)\r\n\r\n # now, remember our lists?\r\n\r\n whatColor = input('What color do you wish to know the date of?:')\r\n coldex = colors.index(whatColor)\r\n print(coldex)\r\n theDate = dates[coldex]\r\n print('The date of',whatColor,'is:',theDate)\r\n \r\n#1/2/2014,5,8,red\r\n#1/3/2014,5,2,green\r\n#1/4/2014,9,1,blue","sub_path":"read_specific_columns_csv.py","file_name":"read_specific_columns_csv.py","file_ext":"py","file_size_in_byte":715,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"66370355","text":"import re\nimport json\nimport requests\nimport time\n\nfrom prettytable import PrettyTable\n\n\ndef getHtml(url, page):\n data = {\n 'page': page,\n 'num': 100,\n 'sort': 'symbol',\n 'asc': 1,\n 'node': 'cyb',\n 'symbol': '',\n '_s_r_a': 'page'}\n headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:56.0) Gecko/20100101 Firefox/56.0'}\n\n try:\n page = requests.post(url, data=data, headers=headers)\n page.encoding = 'gbk'\n html = page.text\n return html\n except:\n return \"\"\n\n\ndef getdata(html):\n data = html.replace(':', '\":')\n data = data.replace(',', ',\"')\n data = data.replace('{', '{\"')\n data = data.replace('\"{', '{')\n data = re.sub('\\d+\":\\d+\":\\d+', '', data)\n data = json.loads(data)\n\n row = PrettyTable()\n row.field_names = [\"代码\", \"名称\", \"最新价\", \"涨跌额\", \"涨跌幅\", \"买入\", \"卖出\", \"昨收\", \"今开\", \"最高\"\n , \"最低\", \"成交量/手\", \"成交额/万\"]\n i = 0\n for item in data:\n row.add_row((item['symbol'], item['name'], item['trade'], item['pricechange'], item['changepercent']\n , item['buy'], item['sell'], item['settlement'], item['open'], item['high']\n , item['low'], item['volume'], item['amount']))\n i = i+1\n\n print(row)\n print(i)\n\nif __name__ == '__main__':\n url = 'http://vip.stock.finance.sina.com.cn/quotes_service/api/json_v2.php/Market_Center.getHQNodeData?'\n for p in range(1, 8):\n html = getHtml(url,p)\n getdata(html)\n time.sleep(5)","sub_path":"hq/hqsina.py","file_name":"hqsina.py","file_ext":"py","file_size_in_byte":1603,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"503337619","text":"from Core.getDatabase import getDatabase\n\n# 用来存储一个用户对应的多个身份证的关系:[用户账号(username),身份证号(card)] 1:m\n\nclass IdentityTable():\n def __init__(self):\n pass\n\n # 返回一个用户所绑定的所有身份证\n def find(self, username):\n client, cursor = getDatabase('identity_collections') # or cursor = db.test_collections auto create the collection\n _list = cursor.find({'username': username})\n client.close()\n return _list\n\n # 为一个用户添加一个身份证\n def insert(self, username, card, name, phone):\n client, cursor = getDatabase('identity_collections')\n\n if cursor.find_one({'username': username, 'card': card}) == None:\n cursor.insert_one({'username': username, 'card': card, 'name': name, 'phone': phone})\n client.close()\n\n # 为一个用户删除一个身份证\n def delete(self, username, card):\n client, cursor = getDatabase('identity_collections')\n b = cursor.find_one({'username': username, 'card' : card})\n\n if b == None:\n client.close()\n return False # 该用户没绑定该身份证\n else:\n cursor.delete_one(b)\n client.close()\n return True # 删除成功\n","sub_path":"Core/IdentityTable.py","file_name":"IdentityTable.py","file_ext":"py","file_size_in_byte":1302,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"93624823","text":"from django.http import HttpResponseRedirect\nfrom django.conf import settings\n\n\ndef ajax_only(f):\n\n def wrap(request, *args, **kwargs):\n if not settings.DEBUG:\n if not request.is_ajax():\n if 'HTTP_REFERER' in request.META:\n return HttpResponseRedirect(request.META['HTTP_REFERER'])\n else:\n returnurl = request.build_absolute_uri(request.path)\n returnurl = returnurl[:-len(request.path_info)]\n return HttpResponseRedirect(returnurl)\n return f(request, *args, **kwargs)\n\n wrap.__doc__ = f.__doc__\n wrap.__name__ = f.__name__\n return wrap\n","sub_path":"branches/mrtardis-v2/tardis/tardis_portal/ajax.py","file_name":"ajax.py","file_ext":"py","file_size_in_byte":679,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"483376374","text":"#!/usr/bin/env python3\n\nfrom pyln.client import Plugin\n\nimport json\nimport os.path\n\n\nplugin = Plugin()\n\n\n@plugin.init()\ndef init(configuration, options, plugin):\n if os.path.exists('moves.json'):\n jd = {}\n with open('moves.json', 'r') as f:\n jd = f.read()\n plugin.coin_moves = json.loads(jd)\n else:\n plugin.coin_moves = []\n\n\n@plugin.subscribe(\"coin_movement\")\ndef notify_coin_movement(plugin, coin_movement, **kwargs):\n idx = coin_movement['movement_idx']\n plugin.log(\"{} coins movement version: {}\".format(idx, coin_movement['version']))\n plugin.log(\"{} coins node: {}\".format(idx, coin_movement['node_id']))\n plugin.log(\"{} coins mvt_type: {}\".format(idx, coin_movement['type']))\n plugin.log(\"{} coins account: {}\".format(idx, coin_movement['account_id']))\n plugin.log(\"{} coins credit: {}\".format(idx, coin_movement['credit']))\n plugin.log(\"{} coins debit: {}\".format(idx, coin_movement['debit']))\n plugin.log(\"{} coins tag: {}\".format(idx, coin_movement['tag']))\n plugin.log(\"{} coins timestamp: {}\".format(idx, coin_movement['timestamp']))\n plugin.log(\"{} coins coin_type: {}\".format(idx, coin_movement['coin_type']))\n\n for f in ['payment_hash', 'utxo_txid', 'vout', 'txid', 'part_id', 'blockheight']:\n if f in coin_movement:\n plugin.log(\"{} coins {}: {}\".format(idx, f, coin_movement[f]))\n\n plugin.coin_moves.append(coin_movement)\n\n # we save to disk so that we don't get borked if the node restarts\n # assumes notification calls are synchronous (not thread safe)\n with open('moves.json', 'w') as f:\n f.write(json.dumps(plugin.coin_moves))\n\n\n@plugin.method('listcoinmoves_plugin')\ndef return_moves(plugin):\n result = []\n if os.path.exists('moves.json'):\n jd = {}\n with open('moves.json', 'r') as f:\n jd = f.read()\n result = json.loads(jd)\n return {'coin_moves': result}\n\n\nplugin.run()\n","sub_path":"tests/plugins/coin_movements.py","file_name":"coin_movements.py","file_ext":"py","file_size_in_byte":1947,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"622612235","text":"import gi\n\ngi.require_version(\"Gtk\", \"3.0\")\nfrom gi.repository import Gtk, Gdk\n\nimport os\n\nfrom treeview import TreeViewCommon, PATTERN_OPTIONS, OBJECT_OPTIONS\nfrom fswatch import ThreadNotify\nfrom progresswindow import ThreadProgress\nfrom accelerators import Accelerator\n\nNAME_DICT = {\"All\": None,\n \"Audio\": \"audio-x-generic\",\n \"Compressed\": \"package-x-generic\",\n \"Document\": \"text-x-generic\",\n \"Executable\": \"application-x-executable\",\n \"Folder\": \"folder\",\n \"Picture\": \"image-x-generic\",\n \"Video\": \"video-x-generic\"}\n\nWIN_ACTION_DICT = {\"update_filesystem\": (\"win.update_filesystem\", (\"u\",),),\n \"close_window\": (\"win.close_window\", (\"w\",),),\n \"show_filters\": (\"win.show_filters\", (\"f\",),),\n \"show_statusbar\": (\"win.show_statusbar\", (\"s\",),),\n \"copy\": (\"win.copy\", (\"c\",),),\n \"open\": (\"win.open\", (\"o\",),),\n \"open_path\": (\"win.open_path\", (\"p\",),)}\n\n@Gtk.Template(filename=\"../ui/preferences.ui\")\nclass PreferenceDialog(Gtk.Dialog):\n __gtype_name__ = \"PreferenceDialog\"\n\n preferences_ok_button = Gtk.Template.Child()\n\n simple_button = Gtk.Template.Child()\n case_button = Gtk.Template.Child()\n whole_word_button = Gtk.Template.Child()\n regex_button = Gtk.Template.Child()\n\n name_button = Gtk.Template.Child()\n path_button = Gtk.Template.Child()\n\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.pattern_mode = PATTERN_OPTIONS[0]\n self.object_mode = OBJECT_OPTIONS[1]\n self.preferences_ok_button.connect(\"clicked\", self.on_ok_clicked)\n\n self.simple_button.connect(\"toggled\", self.on_word_button_toggled)\n self.case_button.connect(\"toggled\", self.on_word_button_toggled)\n self.whole_word_button.connect(\"toggled\", self.on_word_button_toggled)\n self.regex_button.connect(\"toggled\", self.on_word_button_toggled)\n\n self.name_button.connect(\"toggled\", self.on_object_button_toggled)\n self.path_button.connect(\"toggled\", self.on_object_button_toggled)\n\n self.connect(\"delete-event\", self.on_preferences_delete_event)\n\n def on_ok_clicked(self, widget):\n self.hide()\n\n def on_word_button_toggled(self, widget):\n self.pattern_mode = widget.get_property(\"label\")\n\n def on_object_button_toggled(self, widget):\n self.object_mode = widget.get_property(\"label\")\n\n def on_preferences_delete_event(self, widget, event):\n self.hide()\n return True\n\n@Gtk.Template(filename=\"../ui/searchwindow.ui\")\nclass SearchApplicationWindow(Gtk.ApplicationWindow, TreeViewCommon):\n __gtype_name__ = \"SearchApplicationWindow\"\n\n treeview = Gtk.Template.Child()\n search_entry = Gtk.Template.Child()\n statusbar = Gtk.Template.Child()\n status_label = Gtk.Template.Child()\n text_combobox = Gtk.Template.Child()\n combobox_headbar = Gtk.Template.Child()\n show_filters_button = Gtk.Template.Child()\n show_statusbar_button = Gtk.Template.Child()\n\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.set_treeview()\n\n self.search_entry.connect(\"populate-popup\", self.on_search_contextmenu_popup)\n self.search_entry.connect(\"search-changed\", self.on_search_change)\n self.text_combobox.connect(\"changed\", self.on_combobox_change)\n self.preferences_dialog = PreferenceDialog()\n self.clipboard = Gtk.Clipboard.get(Gdk.SELECTION_CLIPBOARD)\n self.thread_notifier = None\n self.connect(\"delete-event\", self.on_window_delete_event)\n\n def do_realize(self):\n Gtk.ApplicationWindow.do_realize(self)\n app = self.get_application()\n\n WIN_CALLBACK_DICT = {\"update_filesystem\": self.update_filesystem_callback,\n \"close_window\": self.close_window_callback,\n \"show_filters\": self.show_filters_callback,\n \"show_statusbar\": self.show_statusbar_callback,\n \"copy\": self.copy_callback,\n \"open\": self.open_callback,\n \"open_path\": self.open_path_callback}\n Accelerator.register_actions(app, WIN_ACTION_DICT, WIN_CALLBACK_DICT, win=self)\n\n def close_window_callback(self, action, parameter):\n self.destroy()\n\n def add_filesystem_watches(self):\n for data in self.data_list:\n if os.path.exists(data[2]):\n self.watch_manager.add_watch(data[2], self.mask)\n\n def update_filesystem_callback(self, action, parameter):\n ThreadNotify.add_notify(self)\n ThreadProgress.show_progress(self)\n\n def show_filters_callback(self, action, parameter):\n if self.show_filters_button.get_active():\n self.combobox_headbar.show()\n else:\n self.combobox_headbar.hide()\n\n def show_statusbar_callback(self, action, parameter):\n if self.show_statusbar_button.get_active():\n self.statusbar.show()\n else:\n self.statusbar.hide()\n\n def copy_callback(self, action, parameter):\n self.copy_treeview()\n\n def open_callback(self, action, parameter):\n self.open_treeview()\n\n def open_path_callback(self, action, parameter):\n self.open_path_treeview()\n\n def on_window_delete_event(self, widget, event):\n if self.thread_notifier:\n self.thread_notifier.stop()\n self.destroy()\n return True\n\n def on_search_contextmenu_popup(self, widget, menu):\n menu.remove(menu.get_children()[-1])\n menu.show_all()\n\n def on_search_change(self, widget):\n self.sort_switch = True\n self.keyword_filter = self.search_entry.get_text()\n self.filter_model.refilter()\n self.apply_model()\n\n def on_combobox_change(self, widget):\n self.class_filter = NAME_DICT[self.text_combobox.get_active_text()]\n self.filter_model.refilter()\n self.apply_model()","sub_path":"source/searchwindow.py","file_name":"searchwindow.py","file_ext":"py","file_size_in_byte":6068,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"518185706","text":"# largest no. in a list\n\n'''list1 = [1, 2, 3, 4, 5]\n\nmax = list1[0]\n\nfor i in list1:\n \n if i > max:\n \n max = i\n \nprint('largest number in list is', max)'''\n\n\n\n\nlist1 = []\n\nlength = int(input('enter list length: '))\n\nfor i in range(length):\n \n data = int(input())\n \n list1.append(data)\n \nmax = list1[0] \n\nfor x in list1:\n \n if x > max:\n \n max = x\n \nprint('largest number is', max) \n \n \n \n \n \n \n \n \n \n \n \n\n \n \n \n \n\n\n","sub_path":"03_lists/_03_largestnumberinalist.py","file_name":"_03_largestnumberinalist.py","file_ext":"py","file_size_in_byte":546,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"276463901","text":"#! python3\n# inputvalidation.py - input validation with the help of available modules.\nimport random\n\nimport pyinputplus as pyip\nimport time\n\n\ndef takenumber():\n numberOfQuestions = 10\n correctAnswers = 0\n for questionNumber in range(numberOfQuestions):\n num1 = random.randint(0, 9)\n num2 = random.randint(0, 9)\n\n prompt = '#%s: %s x %s = ' % (questionNumber, num1, num2)\n try:\n # Right answers are handled by allowRegexes.\n # Wrong answers are handled by blockRegexes, with a custom message.\n #print(pyip.inputNum('>>>>>', min=4, lessThan=10, timeout=10, limit=2, default=5))\n #print(pyip.inputNum(allowRegexes=[r'(Q|W|E|R|T|Y)+', r'zero']))\n pyip.inputNum(prompt, allowRegexes=['^%s$' %(num1 * num2)],\n blockRegexes=[('.*', 'In-Correct')], timeout=8, limit=3)\n except pyip.TimeoutException:\n print('Out of time!')\n except pyip.RetryLimitException:\n print('Out of tries!')\n else:\n # This block runs if no exceptions were raised in the try block.\n print('Correct!')\n correctAnswers += 1\n time.sleep(1) # Brief pause to let user see the result.\n print('Score: %s / %s' % (correctAnswers, numberOfQuestions))\n\n\ntakenumber()","sub_path":"inputvalidation.py","file_name":"inputvalidation.py","file_ext":"py","file_size_in_byte":1339,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"321280395","text":"import vk_api\nimport math\nimport pandas as pd\nimport wikipediaapi\nimport random\nimport numpy as np\nimport re\nimport pymorphy2\nmorph = pymorphy2.MorphAnalyzer()\nfrom vk_api.utils import get_random_id\nfrom vk_api.longpoll import VkLongPoll, VkEventType\n\n\nclass Bot : \n \n def __init__(self, token):\n self.session = vk_api.VkApi(token = token) #создаем сессию \n self.vk = self.session.get_api() \n self.wiki = wikipediaapi.Wikipedia('ru') #устанавливаем локаль википедии \n self.RequestDataBase = pd.DataFrame({'Request':[],'Reply':[]}) #создаем таблицу с запросами, на которые бот не смог ответить\n self.event = None\n self.HelloBase = ['Привет!', 'Здравствуй!', 'Хеллоу)', 'Привеееет.', 'Прив)']\n self.firstMessage = \"\"\" Я могу ответить на твой вопрос. Чтобы задать вопрос напиши: Расскажи про/о или просто напиши запрос со знаком вопроса. \"\"\"\n self.ByeBase = ['До встречи !', 'Пока', 'Пок!']\n self.FunctionDict = { #создаем словарь, где ключь - клюечая фраза, а объект - функция ответа\n \"расскажи (про|о) .*|что такое .*|.*\\?+\": self.WikiRequest,\n \"при+в\\w*\\.?|здра+в\\.?|ха+й\\.?|хел+о+у\\.?|здаро+ва*\\.?|he+llo\\.?|hi+\\.?\": self.Greeting,\n \"по+ка*\\.?|по+ки+\\.?|проща+й\\.?|давай\\.?|до (связи\\.?|встречи\\.?|свидания\\.?)\":self.Bye,\n #\"масса .*\":self.Radius_Black_Hole,\n }\n \n def EventSender(self, event): #сендер для ивета(в питоне нормальной инкапсуляции нет, но пусть будет так)\n self.event = event\n print(self.vk.api.messages.getById())\n\n \n def KeywordSearch(self):\n NoReply = True\n self.event.text = self.event.text.lower() #приводим строку запроса к нижнему регистру\n for key in self.FunctionDict.keys(): #перебираем все возможные ключи, это нужно оптимизировать, но пока хз как\n if (re.fullmatch(key, self.event.text)): #если ключевая фраза есть в запросе, вызываем обработчик\n self.FunctionDict[key](key)\n NoReply = False \n if NoReply: #если ответ не нашелся запишим запрос в список запросов без ответа\n self.DefoltReport('')\n df = pd.DataFrame({'Request':[str(self.event.text)],'Reply':['NoN']}).append(self.RequestDataBase)\n self.RequestDataBase = df\n \n \n def DefoltReport(self, key): #ключивые фразы не обнаружены -> даем дефолтный ответ\n if self.event.from_user:\n self.vk.messages.send(user_id=self.event.user_id, message='Я тебя не понимаю' ,random_id=get_random_id())\n elif self.event.from_chat:\n self.vk.messages.send(user_id=self.event.chat_id, message='Я тебя не понимаю',random_id=get_random_id())\n \n \n def Greeting(self, key): #приветствие\n if self.event.from_user:\n tmp = np.random.choice(self.HelloBase) + self.firstMessage\n self.vk.messages.send(user_id=self.event.user_id, message=tmp,random_id=get_random_id())\n elif self.event.from_chat:\n self.vk.messages.send(user_id=self.event.chat_id, message=tmp,random_id=get_random_id())\n \n \n def WikiRequest(self, key): #запрос википедии\n #request = self.event.text[self.event.text.rfind(key)+ len(key):] #отрезаем лишнее от запроса\n tmp = re.sub('расскажи (про|о)|что такое|\\??',repl='',string=self.event.text)\n print('Debug1 %s' % self.event.text)\n print('Debug %s' % tmp)\n word = morph.parse(tmp)[0]\n try:\n request = word.inflect({'nomn'}).word\n except:\n self.vk.messages.send(user_id=self.event.user_id, message='Это не вопрос!',random_id=get_random_id())\n return;\n print('MORPH = %s' % request)\n page_py = self.wiki.page(request) #запрашиваем страницу вики\n if page_py.exists(): #страница существует\n reply = str(page_py.summary) + '\\n' + str(page_py.fullurl) #выкачиваем краткую справки и добавляем ссылку еа полную статью\n if self.event.from_user:\n self.vk.messages.send(user_id=self.event.user_id, message='Вот что я нашёл: \\n' + reply,random_id=get_random_id())\n elif self.event.from_chat:\n self.vk.messages.send(user_id=self.event.chat_id, message='Вот что я нашёл: \\n' + reply,random_id=get_random_id())\n else : #страница не нашлась\n #добавляем запрос в таблицу\n df = pd.DataFrame({'Request':[str(request)],'Reply':['NoN']}).append(self.RequestDataBase)\n self.RequestDataBase = df\n if self.event.from_user:\n self.vk.messages.send(user_id=self.event.user_id, message='я ничего не нашел' ,random_id=get_random_id())\n elif self.event.from_chat:\n self.vk.messages.send(user_id=self.event.chat_id, message='я ничего не нашел',random_id=get_random_id())\n \n def Bye(self, key): #прощание\n if self.event.from_user:\n self.vk.messages.send(user_id=self.event.user_id, message=np.random.choice(self.ByeBase,size = 1),random_id=get_random_id())\n elif self.event.from_chat:\n self.vk.messages.send(user_id=self.event.chat_id, message=np.random.choice(self.ByeBase, size = 1),random_id=get_random_id())\n \n \n \n \n \n \n \n \n \n","sub_path":"botVK/BotProcessing.py","file_name":"BotProcessing.py","file_ext":"py","file_size_in_byte":6336,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"216154397","text":"from rdflib.namespace import ClosedNamespace\nfrom rdflib import URIRef\n\nDcterms = ClosedNamespace(\n uri=URIRef(\"http://purl.org/dc/terms/\"),\n terms=[\n \"title\"\n ]\n)\n\nSBOL2 = ClosedNamespace(\n uri=URIRef(\"http://sbols.org/v2#\"),\n terms=[\n # types\n \"ComponentDefinition\",\n \"Component\",\n \"ModuleDefinition\",\n \"Module\",\n \"Interaction\",\n \"Participation\",\n \"MapsTo\",\n \"Sequence\",\n \"SequenceConstraint\",\n \"FunctionalComponent\",\n\n # predicates\n \"component\",\n \"displayId\",\n \"type\",\n \"role\",\n \"persistentIdentity\",\n \"version\",\n \"interaction\",\n \"participant\",\n \"mapsTo\",\n \"sequence\",\n \"access\",\n \"definition\",\n \"direction\",\n \"refinement\",\n \"sequenceConstraint\",\n \"functionalComponent\",\n \"module\",\n \"participation\",\n \"encoding\",\n \"elements\",\n \"restriction\",\n\n # terms\n \"precedes\",\n \"local\",\n \"remote\",\n \"private\",\n \"public\",\n \"none\",\n \"useLocal\",\n \"useRemote\",\n \"merge\",\n \"verifyIdentical\"\n ]\n)\n\nBiopax = ClosedNamespace(\n uri=URIRef(\"http://www.biopax.org/release/biopax-level3.owl#\"),\n terms=[\n \"DnaRegion\",\n \"RnaRegion\",\n \"Protein\",\n \"Complex\",\n \"SmallMolecule\"\n ]\n)\n","sub_path":"pysbolgraph/terms.py","file_name":"terms.py","file_ext":"py","file_size_in_byte":1434,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"534308962","text":"from PyQt5 import QtWidgets, QtGui, QtCore\nfrom PyQt5.QtCore import Qt, QBasicTimer\nfrom PyQt5.QtWidgets import (QGraphicsItem, QGraphicsRectItem, QGraphicsScene,\n QGraphicsView, QGraphicsTextItem, QFrame)\nfrom PyQt5.QtGui import QBrush, QColor\nfrom player import Player\nfrom enemy import Enemy\nfrom platform import Platform\nfrom price import Price\nfrom camera import Camera\nfrom map import Map\nfrom goal import Goal\nimport globals\nimport json\n\n\n\nclass Scene(QGraphicsScene):\n def __init__(self, cam, menu, parent = None):\n QGraphicsScene.__init__(self, parent)\n\n self.prices = []\n self.time = 0\n self.menu = menu\n\n # Tallennetaan painetut nappaimet\n self.keys_pressed = set()\n\n self.timer = QBasicTimer()\n self.timer.start(globals.FRAME_SPEED, self)\n\n bg = QGraphicsRectItem()\n bg.setRect(0,0, globals.SCREEN_WIDTH*4, globals.SCREEN_HEIGHT)\n bg.setBrush(QBrush(QtGui.QColor(128, 191, 255)))\n self.addItem(bg)\n\n self.player = Player()\n self.addItem(self.player)\n\n #Luodaan maailma\n self.map = Map()\n for i in range(int(globals.SCREEN_HEIGHT / 40)):\n for j in range(int((globals.SCREEN_WIDTH*4) / 40)):\n if self.map.map[i][j] > 0:\n self.platform = Platform(j*40, i*40, self.map.map[i][j])\n self.addItem(self.platform)\n\n self.enemy = Enemy(500, 200)\n self.addItem(self.enemy)\n\n #Luodaan palkinnot\n self.price1 = Price(250, 350)\n self.addItem(self.price1)\n self.prices.append(self.price1)\n\n self.price2 = Price(750, 500)\n self.addItem(self.price2)\n self.prices.append(self.price2)\n\n self.price3 = Price(650, 300)\n self.addItem(self.price3)\n self.prices.append(self.price3)\n\n self.price4 = Price(1330, 250)\n self.addItem(self.price4)\n self.prices.append(self.price4)\n\n self.price5 = Price(1455, 500)\n self.addItem(self.price5)\n self.prices.append(self.price5)\n\n self.price6 = Price(1830, 250)\n self.addItem(self.price6)\n self.prices.append(self.price6)\n\n self.price7 = Price(2100, 100)\n self.addItem(self.price7)\n self.prices.append(self.price7)\n\n self.price8 = Price(2490, 500)\n self.addItem(self.price8)\n self.prices.append(self.price8)\n\n self.price9 = Price(2770, 200)\n self.addItem(self.price9)\n self.prices.append(self.price9)\n\n self.price10 = Price(3100, 205)\n self.addItem(self.price10)\n self.prices.append(self.price10)\n\n self.font = QtGui.QFont()\n self.font.setPointSize(15)\n\n self.points = QtWidgets.QGraphicsTextItem('Prices: ' + str(self.player.points) + '/' + str(len(self.prices)))\n self.points.setDefaultTextColor(QtGui.QColor(38, 38, 38))\n self.points.setFont(self.font)\n self.addItem(self.points)\n\n self.display = QtWidgets.QGraphicsTextItem('Time: ' + str(int(self.time)))\n self.display.setDefaultTextColor(QtGui.QColor(38, 38, 38))\n self.display.setFont(self.font)\n self.display.setPos(200, 1)\n self.addItem(self.display)\n\n self.goal = Goal(3000, 440)\n self.addItem(self.goal)\n\n\n self.view = cam\n self.view.update_scene(self)\n\n\n def mousePressEvent(self, event):\n if not self.player.alive:\n self.menu.update_hs()\n self.view.update_scene(self.menu)\n if self.player.win:\n self.menu.update_hs()\n self.view.update_scene(self.menu)\n\n def keyPressEvent(self, event):\n self.keys_pressed.add(event.key())\n\n def keyReleaseEvent(self, event):\n if event.key() != 32:\n self.keys_pressed.remove(event.key())\n\n def timerEvent(self, event):\n self.game_update()\n self.view.ensureVisible(self.player, 350, 0)\n self.update()\n self.time += 0.016\n self.display_update()\n\n def score_update(self, price):\n self.removeItem(price)\n self.removeItem(self.points)\n price.deleted = True\n self.player.points += 1\n self.points = QtWidgets.QGraphicsTextItem('Prices: ' + str(self.player.points) + '/' + str(len(self.prices)))\n self.points.setDefaultTextColor(QtGui.QColor(38, 38, 38))\n self.points.setFont(self.font)\n self.move_score()\n self.addItem(self.points)\n\n\n def move_score(self):\n self.points.setPos(self.view.mapToScene(1, -3).x(), 0)\n self.display.setPos(self.view.mapToScene(200, -3).x(), 0)\n\n def game_over(self):\n game_over = QtWidgets.QGraphicsTextItem('GAME OVER')\n game_over.setDefaultTextColor(QtGui.QColor(255, 0, 0))\n go_font = QtGui.QFont()\n go_font.setPointSize(40)\n game_over.setFont(go_font)\n game_over.setPos(self.view.mapToScene(1, -3).x() + 175, 150)\n self.addItem(game_over)\n\n def game_win(self):\n game_win = QtWidgets.QGraphicsTextItem('WINNER!!!')\n game_win.setDefaultTextColor(QtGui.QColor(0, 128, 0))\n go_font = QtGui.QFont()\n go_font.setPointSize(40)\n game_win.setFont(go_font)\n game_win.setPos(self.view.mapToScene(1, -3).x() + 175, 90)\n self.addItem(game_win)\n\n with open('static/highscore.json') as f:\n data = json.load(f)\n highscore = data[\"highscore\"]\n if self.time < highscore:\n new_highscore = QtWidgets.QGraphicsTextItem('New Highscore: ' + str(int(self.time)))\n new_highscore.setDefaultTextColor(QtGui.QColor(0, 128, 0))\n new_highscore.setFont(self.font)\n new_highscore.setPos(self.view.mapToScene(1, -3).x() + 230, 170)\n self.addItem(new_highscore)\n with open('static/highscore.json', \"w\") as f:\n write = {\"highscore\": self.time}\n json.dump(write, f)\n\n\n def game_update(self):\n self.player.player_update(self.keys_pressed, self.enemy, self.timer, self.prices, self.map, self.goal)\n self.enemy.enemy_update(self.map)\n for price in self.prices:\n if price.price_update() and not price.deleted:\n self.score_update(price)\n #Pelaaja kuoli\n if not self.player.alive:\n self.game_over()\n if self.player.win:\n self.game_win()\n\n self.move_score()\n if not self.enemy.alive and not self.enemy.deleted:\n self.removeItem(self.enemy)\n self.enemy.deleted = True\n\n def display_update(self):\n self.removeItem(self.display)\n self.display = QtWidgets.QGraphicsTextItem('Time: ' + str(int(self.time)))\n self.display.setDefaultTextColor(QtGui.QColor(38, 38, 38))\n self.display.setFont(self.font)\n self.display.setPos(300, 1)\n self.move_score()\n self.addItem(self.display)\n","sub_path":"src/scene.py","file_name":"scene.py","file_ext":"py","file_size_in_byte":6951,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"400598134","text":"from django.shortcuts import render\nimport json\nfrom django.http import HttpResponse,HttpResponseRedirect\nfrom django.template import RequestContext, loader\nfrom django.shortcuts import render_to_response\n\nfrom django.shortcuts import render\nfrom django.http import HttpResponseRedirect\nfrom .forms import SearchForm,SearchTextForm\nfrom django.core.urlresolvers import reverse\nfrom elasticsearch import Elasticsearch\nfrom django import template\n\nregister = template.Library()\n\n\n\ndef view_json(request):\n\n\n if request.method=='POST':\n\n #data=json.load(open('/home/siddhu/gstudio/data/rcs-repo/Nodes/0/1/d/57c7c1ad16b51c39fe82dc10.json'))\n form = SearchForm(request.POST)\n if form.is_valid():\n Search = form.cleaned_data['Search']\n data = json.load(open('/home/siddhu/gstudio/data/glite-rcs-repo/Nodes/f/1/1/'+Search+'.json'))\n #return HttpResponseRedirect('/views_json/')\n #t = loader.get_template('test.html')\n #c = RequestContext(request, {'data123': json.dumps(data)})\n #return HttpResponse(t.render(c), content_type=\"application/json\")\n #return render_to_response('test.html',context_instance=RequestContext(request, {'data123': data, 'form': form})) ... django 1.7\n return render(request, 'test.html', {'data123': data, 'form': form})\n\n #else:\n #form = SearchForm()\n #return HttpResponseRedirect('/')\n\n #return render_to_response('test.html', context_instance=RequestContext(request, {'data123': data,'form':form}))\n return render(request, 'test.html', {})\n\n\n\ndef search(request):\n if request.method=='POST':\n form = SearchTextForm(request.POST)\n\n if form.is_valid():\n es = Elasticsearch('http://10.1.0.229:9200')\n\n Search = form.cleaned_data['SearchText']\n\n Search.encode('utf8')\n filter_field = form.cleaned_data['filter_field']\n educational_filter_field = form.cleaned_data['educational_filter_field']\n target_group_filter_field = form.cleaned_data['target_group_filter_field']\n source_filter_field = form.cleaned_data['source_filter_field']\n language_filter_field = form.cleaned_data['language_filter_field']\n educationalsubject_filter_field = form.cleaned_data['educationalsubject_filter_field']\n\n allfilters={\"filter_field\":filter_field,\"educational_filter_field\":educational_filter_field ,\"target_group_filter_field\":target_group_filter_field,\"source_filter_field\":source_filter_field\n ,\"language_filter_field\":language_filter_field, \"educationalsubject_filter_field\":educationalsubject_filter_field}\n selected_filters={}\n\n temp = ''\n\n if filter_field == 'all' :\n filter_field=('audios','videos','images')\n\n for key,value in allfilters.items():\n if value != 'sel' and value != 'stg' and value != 'ss' and value != 'sl' and value != 'ses':\n selected_filters.update({key:value})\n\n\n for key,value in selected_filters.items():\n if key == 'educational_filter_field' :\n temp_educational_filter_field='{\"term\":{\"attribute_set.educationallevel\":'+'\"'+educational_filter_field+'\"'+'}},'\n temp=temp+temp_educational_filter_field\n print(temp)\n elif key == 'target_group_filter_field':\n temp_target_group_filter_field='{\"term\":{\"attribute_set.audience\":'+'\"'+target_group_filter_field+'\"'+'}},'\n temp=temp+temp_target_group_filter_field\n elif key == 'source_filter_field':\n temp_source_filter_field = '{\"term\":{\"attribute_set.source\":' + '\"' + source_filter_field + '\"' + '}},'\n temp = temp + temp_source_filter_field\n elif key == 'language_filter_field':\n temp_language_filter_field = '{\"term\":{\"language\":' + '\"' + language_filter_field + '\"' + '}},'\n temp = temp + temp_language_filter_field\n elif key == 'educationalsubject_filter_field':\n temp_educationalsubject_filter_field = '{\"term\":{\"attribute_set.educationalsubject\":' + '\"' + educationalsubject_filter_field + '\"' + '}},'\n temp = temp + temp_educationalsubject_filter_field\n\n\n\n if (( Search not in [None, ''] and (selected_filters['filter_field'] == 'all' or selected_filters['filter_field'] == 'videos' or selected_filters['filter_field'] == 'audios' or selected_filters['filter_field'] == 'documents' or selected_filters['filter_field'] == 'images'))\n and educational_filter_field == 'sel' and target_group_filter_field == 'stg' and source_filter_field == 'ss' and language_filter_field == 'sl' and educationalsubject_filter_field == 'ses'):\n print('first if block')\n res = es.search(index=\"gstudio-lite\", doc_type=filter_field, body={\"query\": { \"multi_match\":{ \"query\": Search, \"fields\": [ \"name\", \"tags\",\"content\" ]} } }\n ,scroll=\"10m\",size=\"30\")\n\n #print(\"%d documents found:\" % res['hits']['total'])\n\n elif ( Search in [None, ''] ):\n print('elif')\n if ((selected_filters['filter_field'] == 'all' or selected_filters['filter_field'] == 'videos' or selected_filters['filter_field'] == 'audios' or selected_filters['filter_field'] == 'documents' or selected_filters['filter_field'] == 'images')\n and educational_filter_field == 'sel' and target_group_filter_field == 'stg' and source_filter_field == 'ss' and language_filter_field == 'sl' and educationalsubject_filter_field == 'ses'):\n res = es.search(index=\"gstudio-lite\", doc_type=filter_field, body={\n \"query\": {\"bool\": {\"must\": [{\"term\": {\"status\": \"published\"}}]}}},\n scroll=\"10m\", size=\"30\")\n\n else:\n res = es.search(index=\"gstudio-lite\", doc_type=filter_field, body={\n \"query\": {\"bool\": {\"must\": [{\"term\": {\"status\": \"published\"}}, eval(str(temp))]}}},\n scroll=\"10m\", size=\"30\")\n else:\n print(temp)\n res = es.search(index=\"gstudio-lite\", doc_type=filter_field, body={\"query\": {\"bool\": {\"must\":[{\"multi_match\": {\"query\": Search, \"fields\": [\"name\", \"tags\", \"content\"]}}, {\"term\": { \"status\": \"published\" }}, eval(str(temp)) ]}}}, scroll=\"10m\", size=\"30\",)\n\n doc={}\n\n #for doc in res['hits']['hits']:\n #print(\"%s) %s\" % (doc['_id'], doc['_source']['content']))\n # print()\n return render(request, 'search.html', {'hits':res['hits']['hits'],'total_hits': res['hits']['total'],'form': form})\n else:\n form = SearchTextForm()\n #return HttpResponseRedirect('/')\n\n return render(request, 'search.html', {'form': form})\n\n","sub_path":"gliteapp/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":7055,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"527916923","text":"import unittest\nfrom analyses.summary import summary\nfrom test_helpers.create_testdata import get_testdata_as_dataset\n\nclass TestSummary(unittest.TestCase):\n\n def setUp(self):\n self.testdata = get_testdata_as_dataset()\n self.testcolumn = self.testdata.get_column('col0')\n\n\n def test_summary_works_as_expected(self):\n\n summaryresult = summary(self.testcolumn)\n\n median = summaryresult[0]\n mean = summaryresult[1]\n stdev = summaryresult[2]\n\n decimals = 2\n\n self.assertAlmostEqual(54.67, mean, places=decimals)\n self.assertAlmostEqual(53.0 , median, places=decimals)\n self.assertAlmostEqual(16.87, stdev, places=decimals)\n","sub_path":"src/tests/analysis_tests/summary_test.py","file_name":"summary_test.py","file_ext":"py","file_size_in_byte":698,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"143699059","text":"answers_1 = {\n 'answer1': 'Ookan',\n 'answer2': 'Eeji',\n 'answer3': 'Eeta',\n 'answer4': 'Eerin',\n 'answer5': 'Aarun',\n 'answer6': 'One',\n 'answer7': 'Two',\n 'answer8': 'Three',\n 'answer9': 'Four',\n 'answer10': 'Five'\n}\n\nanswers_2 = {\n 'answer1': 'Eefa',\n 'answer2': 'Eeje',\n 'answer3': 'Eejo',\n 'answer4': 'Eesan',\n 'answer5': 'Eewa',\n 'answer6': 'Ten',\n 'answer7': 'Seven',\n 'answer8': 'Six',\n 'answer9': 'Nine',\n 'answer10': 'Eight'\n}\n\n\ndef getGrade1(props):\n answers_right = 0\n for answer in props:\n if props[answer] == answers_1[answer]:\n answers_right += 1\n return answers_right\n\n\ndef getGrade2(props):\n answers_right = 0\n for answer in props:\n if props[answer] == answers_2[answer]:\n answers_right += 1\n return answers_right\n\n\nfeedback_message1 = {\n 'percentage': '',\n 'message': ''\n}\n\nfeedback_message2 = {\n 'percentage': '',\n 'message': ''\n}\n\n\ndef feedback1(props):\n questions_right = getGrade1(props)\n # percent = f'{str(questions_right*10)}%'\n percent = str(questions_right*10) + '%'\n feedback_message1.update({'percentage': percent})\n if questions_right >= 8:\n feedback_message1.update({'message': f'Wow! You scored a {percent}. Great Job! Come back again soon for more practice.'})\n if questions_right >= 6 and questions_right <= 7:\n feedback_message1.update({'message': f'You scored a {percent}. Not bad. Practice this lesson more and you can get an even better score.'})\n if questions_right < 6:\n feedback_message1.update({'message': f'Unfortunately, you scored a {percent}. Don\\'t worry. Practice this lesson again and again and you can get an even better score.'})\n return feedback_message1\n\n\ndef feedback2(props):\n questions_right = getGrade2(props)\n # percent = f'{str(questions_right*10)}%'\n percent = str(questions_right*10) + '%'\n feedback_message2.update({'percentage': percent})\n if questions_right >= 8:\n feedback_message2.update({'message': f'Wow! You scored a {percent}. Great Job! Come back again soon for more practice.'})\n if questions_right >= 6 and questions_right <= 7:\n feedback_message2.update({'message': f'You scored a {percent}. Not bad. Practice this lesson more and you can get an even better score.'})\n if questions_right < 6:\n feedback_message2.update({'message': f'Unfortunately, you scored a {percent}. Don\\'t worry. Practice this lesson again and again and you can get an even better score.'})\n return feedback_message2\n","sub_path":"model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":2579,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"446952879","text":"from html.parser import HTMLParser\nfrom Course import Schedule\nimport json\n\ncurrentTag = \"\"\nvalidTags = [\"table\",\"td\",\"tr\",\"th\"]\ncourseName = \"\"\ncourseCode = \"\"\ncourseAU = \"\"\ncurrentData = []\ndata = {}\nclass MyHTMLParser(HTMLParser):\n \n def handle_starttag(self, tag, attrs):\n global currentTag\n \n if(tag in validTags):\n currentTag = tag\n\n def handle_endtag(self, tag):\n global currentTag\n global currentData\n global data\n global courseCode, courseName, courseAU\n \n currentTag = \"\"\n # if len is 3: new course\n # if len is 6: new index\n # if len is 5: new entry, same index\n if(tag == \"tr\"):\n if(len(currentData) == 3):\n courseCode = currentData[0]\n courseName = currentData[1]\n courseAU = currentData[2]\n data[courseCode] = []\n else:\n if(len(currentData) == 5):\n currentData = [\"\"] + currentData\n currentData.append(\"\")\n elif(len(currentData) == 6):\n if(currentData[0].isdigit()):\n currentData.append(\"\")\n else:\n currentData = [\"\"] + currentData\n if(len(currentData) == 7):\n data[courseCode].append(currentData)\n currentData = []\n\n def handle_data(self, data):\n global currentData\n \n if(currentTag != \"\" and data.strip() != \"\"):\n if(currentTag == \"td\"):\n currentData.append(data)\n\nparser = MyHTMLParser()\n\nwith open(\"Class Schedule.html\", \"r\", encoding='utf-8') as f:\n lines = f.readlines()\n print(len(lines))\n\nparser.feed(\"\".join(lines[:]))\n\ns = []\nfor key, value in data.items():\n currentIndex = \"\"\n for val in value:\n sch = Schedule()\n if(val[0] != \"\"):\n currentIndex = val[0]\n sch.code = key\n sch.index = currentIndex\n sch.type = val[1]\n sch.group = val[2]\n sch.day = val[3]\n sch.time = val[4]\n sch.venue = val[5]\n sch.remark = val[6]\n s.append(sch.__dict__)\n\nschList = json.dumps(s)\n\nwith open(\"schedules.json\", \"w\") as f:\n f.write(schList)\n \n#print(data[\"CZ1007\"])\n","sub_path":"classParser.py","file_name":"classParser.py","file_ext":"py","file_size_in_byte":2317,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"306824195","text":"import pickle as pkl\nfrom flask import Flask, request, jsonify, render_template\n\napp = Flask(__name__)\nmodel = pkl.load(open(\"notebook/token_predictor_model.pkl\", 'rb'))\n\n\n@app.route('/predict/')\ndef predict():\n \"\"\"\n example:http://0.0.0.0:8000/predict/?forecast=3\n :return: [{\"day\":0,\"prediction\":129298.36155585825},{\"day\":1,\"prediction\":129471.13316899545},{\"day\":2,\"prediction\":129404.59708590152}]\n \"\"\"\n data = request.args.get(\"forecast\")\n data = int(data)\n\n predictions = model.forecast(steps=data)\n\n output = predictions[0]\n\n output_json = []\n for i in range(len(output)):\n pred_dict = {}\n pred_dict = {\"day\": i+1,\"prediction\":output[i]}\n output_json.append(pred_dict)\n return jsonify(output_json)\n\n\nif __name__ == \"__main__\":\n app.run(debug=True)\n","sub_path":"app/deploy_ml/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":813,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"6531690","text":"'''\nTests helper function\n'''\nimport pytest\nimport pyhecdss\n@pytest.mark.parametrize(\"pathname\", [\"//SIN/////\",\"/SAMPLE/SIN/////\",\"///WAVE////\",\"/SAMPLE/SIN/WAVE/01JAN1990/15MIN/SAMPLE1/\"])\ndef test_get_rts(pathname):\n filename='test1.dss'\n matching_list=pyhecdss.get_rts(filename, pathname)\n assert len(matching_list) == 1\n #breakpoint()\n dfsin,units,ptype=matching_list[0]\n assert len(dfsin) > 10\n\n \n\n","sub_path":"tests/test_helper.py","file_name":"test_helper.py","file_ext":"py","file_size_in_byte":424,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"437178592","text":"#Import per eseguire il programma\nfrom __future__ import print_function\n#import PIL\nimport matplotlib.pyplot as plt\nimport matplotlib.patches as patches\nimport os\nimport cv2\nimport numpy as np\nimport requests as rq\nimport time\nimport matplotlib.image as pli\nimport time as timer\nfrom random import seed\nfrom random import randint\n#ip=!ifconfig eth0 | grep -Po 'inet \\K([\\d\\.]+)'\nip='192.168.0.32'\n#from IPython.core.display import HTML\n#HTML(''%ip)\n# take a snapshot\ndef snap(i, pref):\n url = \"http://%s:3000/image\"%(ip)\n r = rq.get(url)\n file = \"%s-%d.jpg\"%(pref,i)\n content = r.content\n with open(file, \"wb\") as f:\n f.write(content)\n return file\n#Analizzare la foto per vedere se c'è la palla\ndir = \"./data/ok\"\nfiles = [ f\"{dir}/{file}\" for file in os.listdir(dir) ]\nclasses = None\nwith open(\"yolov3.txt\", 'r') as f:\n classes = [line.strip() for line in f.readlines()]\nCOLORS = np.random.uniform(0, 255, size=(len(classes), 3))\nnet = cv2.dnn.readNet(\"yolov3.weights\", \"yolov3.cfg\")\n\ndef get_output_layers(net):\n layer_names = net.getLayerNames()\n output_layers = [layer_names[i[0] - 1] for i in net.getUnconnectedOutLayers()]\n return output_layers\ndef draw_prediction(img, class_id, confidence, x, y, x_plus_w, y_plus_h):\n label = str(classes[class_id])\n color = COLORS[class_id]\n cv2.rectangle(img, (x,y), (x_plus_w,y_plus_h), color, 2)\n cv2.putText(img, label, (x-10,y-10), cv2.FONT_HERSHEY_SIMPLEX, 0.5, color, 2)\n \n#Applicare lo YOLO\ndef app_yolo(ft):\n frame=np.zeros((32,32,3), np.uint8)\n frame[16,0:31,:]=255\n ret,buf=cv2.imencode(ft,frame)\n f=cv2.imdecode(buf,cv2.IMREAD_COLOR)\n n = 1\n image = cv2.imread(ft)\n Width = image.shape[1]\n Height = image.shape[0]\n scale = 0.00392\n\n blob = cv2.dnn.blobFromImage(image, scale, (416,416), (0,0,0), True, crop=False)\n net.setInput(blob)\n outs = net.forward(get_output_layers(net))\n\n class_ids = []\n confidences = []\n boxes = []\n conf_threshold = 0.5\n nms_threshold = 0.4\n for out in outs:\n for detection in out:\n scores = detection[5:]\n class_id = np.argmax(scores)\n confidence = scores[class_id]\n if confidence > 0.5:\n center_x = int(detection[0] * Width)\n center_y = int(detection[1] * Height)\n w = int(detection[2] * Width)\n h = int(detection[3] * Height)\n x = center_x - w / 2\n y = center_y - h / 2\n class_ids.append(class_id)\n confidences.append(float(confidence))\n boxes.append([x, y, w, h])\n \n indices = cv2.dnn.NMSBoxes(boxes, confidences, conf_threshold, nms_threshold)\n for i in indices:\n i = i[0]\n box = boxes[i]\n x = box[0]\n y = box[1]\n w = box[2]\n h = box[3]\n draw_prediction(image, class_ids[i], confidences[i], round(x), round(y), round(x+w), round(y+h))\n return (class_ids, boxes, image)\n#print (x,y,w,h)\ndef find_ball(class_ids, boxes, image):\n \n fnd = False\n time = 100\n step_move = 100\n step_rotate = 10\n dir = \"\"\n t = randint(0,10000000)\n i=class_ids.index(32)\n box = boxes[i]\n x = box[0]\n y = box[1]\n w = box[2]\n h = box[3]\n #in base ai calcoli si muove\n if (x > image.shape[1]/2+w+50):\n dir = \"right/%d\" % step_rotate \n if (x < image.shape[1]/2-w-50):\n dir = \"left/%d\" % step_rotate\n if (image.shape[1]/2-w-50<=x) and (x<=image.shape[1]/2+w+50):\n step_move = 400\n dir = \"forward/%d\" % step_move\n if image.shape[0]/2 1.25:\n return False\n if self.l < 0.25 or self.l > 1.25:\n return False\n if self.e < 1 or self.e > 150:\n return False\n if self.n < 1 or self.n > 4:\n return False\n return True\n\n def __str__(self):\n return \"r: {}, lambda: {}, epoch: {}, n: {}, val: {}\".format(self.r, self.l, self.e, self.n, self._val)\n\n def saveJson(self):\n with open('%d.json' % p, 'w') as f:\n data = {\n 'r': self.r,\n 'lambda': self.l,\n 'epoch': self.e,\n 'n': self.n,\n 'val': self.val\n }\n json.dump(data, f)\n\n def run(self, quiet=False):\n ncs_para = ncs.NCS_CParameter(\n tmax=300000, lambda_exp=self.l, r=self.r, epoch=self.e, N=self.n)\n print(self)\n ncs_c = ncs.NCS_C(ncs_para, p)\n ncs_res = ncs_c.loop(quiet=quiet, seeds=0)\n print(ncs_res)\n self._val = ncs_res\n\n @property\n def val(self):\n if self._val is None:\n self.run(False)\n return self._val\n\n\ndef sa():\n T = 1000 # initiate temperature\n Tmin = 10 # minimum value of terperature\n\n param = Parameter.fromJson()\n\n k = 50 # times of internal circulation\n res = 0 # initiate result\n t = 0 # time\n while T >= Tmin:\n param.run(False)\n print(param.val)\n for i in range(k):\n # generate a new x in the neighboorhood of x by transform function\n new_param = Parameter(\n param.r +\n np.random.uniform(low=-0.0005, high=0.0005) * T,\n param.l +\n np.random.uniform(low=-0.0005, high=0.0005) * T,\n param.e, param.n\n )\n print(new_param)\n if new_param.check():\n new_param.run(True)\n if new_param.val < param.val:\n print(\"Programly jump to\", new_param)\n print(\"New result:\", new_param.val)\n param = new_param\n else:\n # metropolis principle\n p = exp(-1e4 * (new_res.val - res.val) / T)\n r = np.random.uniform(low=0, high=1)\n if r > p:\n print(\"Randomly jump to\", new_param)\n print(\"Probability\", p)\n param = new_param\n t += 1\n print(t)\n T = 1000 / (1+t)\n\n print(param.val)\n\ndef random():\n np.random.seed(int(os.getpid() + time.time() + 114514))\n param = Parameter(\n np.random.uniform(low=0.4, high=1.1),\n np.random.uniform(low=0.4, high=1.1),\n np.random.randint(10, 125),\n np.random.randint(1, 3),\n )\n # if not param.check():\n # return\n best = Parameter.fromJson()\n if best.val > param.val:\n param.saveJson()\n\n\nif __name__ == '__main__':\n param = Parameter.fromJson('7.json')\n print(param.val)\n # with Pool(2) as p:\n # for i in range(100000):\n # p.apply_async(random, args=())\n # p.close()\n # p.join()\n","sub_path":"CS303/lab4-6/work/SA12.py","file_name":"SA12.py","file_ext":"py","file_size_in_byte":3877,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"29896179","text":"from openerp import models, fields,api\n#from openerp.osv import fields, osv\n\nfrom openerp.exceptions import except_orm, Warning, RedirectWarning,ValidationError\nfrom openerp.addons.hr_payroll_ezra.parameters import constants as genx\n\nMONTH_QUARTER_SELECTION = [\n (1, '1st Half'),\n (2, '2nd Half')\n]\n\n\nclass payroll_temp_detail(models.Model):\n _name = 'hr.payroll.detail.temp'\n _description = 'Temp Payroll detail'\n _order = 'employee_id,payroll_detail_date'\n\n #payroll_main_temp_id = fields.Many2one('hr.payroll.main.temp', ondelete = 'cascade')\n payroll_detail_id = fields.Many2one('hr.payroll.main', ondelete = 'cascade')\n\n name = fields.Char('Payroll Detail Name')\n employee_id = fields.Many2one('hr.employee', 'Employee Name')\n employee_project_assign = fields.Many2one('res.partner', 'Project Assigned')\n is_reliever = fields.Boolean('Reliever?')\n\n # Gross Pay\n basic_pay_perday = fields.Float('Basic Pay (day)', default=0, digits=(18,2))\n basic_pay_perday_rate = fields.Float('Basic Pay (day)', default=0, digits=(18,2))\n basic_pay_amount = fields.Float('Amount', default=0, digits=(18,2))\n\n # Incentive Leaves\n basic_pay_leaves_perhour = fields.Float('Incentive Leave (hour)', default=0, digits=(18,2))\n basic_pay_leaves_amount = fields.Float('Amount', default=0, digits=(18,2))\n\n reg_otpay_perhour = fields.Float('Regular Overtime (hr)', default=0, digits=(18,2))\n reg_otpay_amount = fields.Float('Amount', default=0, digits=(18,2))\n\n reg_nightdiff_perhour = fields.Float('Night Differential (hr)', default=0, digits=(18,2))\n reg_nightdiffy_amount = fields.Float('Amount', default=0, digits=(18,2))\n\n # Restday\n basic_pay_restday_perhour = fields.Float('Rest Day worked (hr)', default=0, digits=(18,2))\n basic_pay_restday_amount = fields.Float('Amount', default=0, digits=(18,2))\n\n #Restday OT\n basic_pay_restday_ot_perhour = fields.Float('Restday worked Overtime (hr)', default=0, digits=(18,2))\n basic_pay_restday_ot_amount = fields.Float('Amount', default=0, digits=(18,2))\n\n reg_straightduty_perhour = fields.Float('Straight Duty (hr)', default=0, digits=(18,2))\n reg_straightduty_amount = fields.Float('Amount', default=0, digits=(18,2))\n\n cola_rate_perday = fields.Float('COLA (day)', default=0, digits=(18,2))\n cola_amount = fields.Float('Amount', default=0, digits=(18,2))\n\n reg_hol_pay_perday = fields.Float('Legal Holiday (day)', default=0, digits=(18,2))\n reg_hol_pay_amount = fields.Float('Amount', default=0, digits=(18,2))\n\n reg_hol_work_pay_perhour = fields.Float('Legal Holiday worked (hr)', default=0, digits=(18,2))\n reg_hol_work_pay_amount = fields.Float('Amount', default=0, digits=(18,2))\n\n reg_hol_otpay_perhour = fields.Float('Legal Holiday overtime (hr)', default=0, digits=(18,2))\n reg_hol_otpay_amount = fields.Float('Amount', default=0, digits=(18,2))\n\n reg_spechol_perhour = fields.Float('Special Holiday worked (hr)', default=0, digits=(18,2))\n reg_spechol_amount = fields.Float('Amount', default=0, digits=(18,2))\n\n reg_spechol_otpay_perhour = fields.Float('Special Holiday overtime (hr)', default=0, digits=(18,2))\n reg_spechol_otpay_amount = fields.Float('Amount', default=0, digits=(18,2))\n other_incentive = fields.Float('Others', default=0, digits=(18,2))\n\n # Deduction for Gross Pay\n tardiness = fields.Float('Tardiness (Min)', digits=(18,2))\n tardiness_permin_rate = fields.Float('Rate (min)', default=0, digits=(18,2))\n tardiness_amount = fields.Float('Amount', default=0, digits=(18,2))\n\n undertime = fields.Float('Undertime (Min)', digits=(18,2))\n tardiness_pay_permin_rate = fields.Float('Rate (min)', default=0, digits=(18,2))\n undertime_amount = fields.Float('Amount', default=0, digits=(18,2))\n\n gross_salary = fields.Float('Gross Salary', default=0, digits=(18,2))\n\n # End Gross Pay\n\n # Deductions\n # SSS Deduction\n sss_premium = fields.Float('SSS Premium', default=0, digits=(18,2))\n sss_loan = fields.Float('SSS Loans', default=0, digits=(18,2))\n\n # Pagibig Deduction\n hdmf_premium = fields.Float('Pagibig Premium', default=0, digits=(18,2))\n hdmf_salary_loan = fields.Float('Pagibig Salary Loan', default=0, digits=(18,2))\n hdmf_calamity_loan = fields.Float('Pagibig Calamity Loan', default=0, digits=(18,2))\n\n # Philhealth Deduction\n hmo_premium = fields.Float('Philhealth', default=0, digits=(18,2))\n other_deductions = fields.Float('Others', default=0, digits=(18,2))\n\n deductions = fields.Float('Total Deduction', default=0, digits=(18,2))\n # End Deductions\n\n # Net Pay\n net_pay = fields.Float('Net Pay', default=0, digits=(18,2))\n # End Net Pay\n\n #Tax\n computed_tax = fields.Float('Withholding Tax', default=0)\n\n #Other Information\n month_half_period = fields.Integer('Month Quarter')\n month_name_period = fields.Selection(genx.MONTH_SELECTION,'Month Name')\n year_payroll_period = fields.Integer('Year')\n payroll_detail_date = fields.Date('Payroll Date')\n\n #For Report Generation\n @api.one\n def getCompanyName(self):\n #Get Company Information\n company = self.env['res.company'].search([('id', '=', 1)])\n self.company_name = company.name.upper()\n\n return company.name\n\n @api.one\n def getCompanyAddress(self):\n #Get Company Information\n company = self.env['res.company'].search([('id', '=', 1)])\n self.company_address = company.street + ' ' + company.street2 + ' ' + company.city + ' City'\n\n @api.one\n def getCompanyContact(self):\n #Get Company Information\n company = self.env['res.company'].search([('id', '=', 1)])\n\n self.company_contact = 'Tel Nos.' + str(company.phone) + ' : Telefax No.' + str(company.fax)\n\n @api.one\n def getIdentification(self):\n self.my_id = self.id\n\n company_name = fields.Char('Company Name', store=False, compute ='getCompanyName', default = getCompanyName)\n company_address = fields.Char('Company Address', store=False, compute ='getCompanyAddress', default = getCompanyAddress)\n company_contact = fields.Char('Company Contact', store=False, compute ='getCompanyContact', default = getCompanyContact)\n\n incentive_id = fields.One2many('payroll.detail.incentives', 'payroll_detail_id','incentive breakdown ID')\n deduction_id = fields.One2many('payroll.detail.deduction', 'payroll_detail_id','Deduction breakdown ID')\n my_id = fields.Integer('My ID', compute ='getIdentification')\n\n\nclass payslip_per_Employee(models.TransientModel):\n _name = 'payroll.payslip.employee'\n\n employee_id = fields.Many2one('hr.employee', 'Employee', required=True)\n month_of_from = fields.Selection(genx.MONTH_SELECTION, 'From the Month of', required=True, default = 1)\n month_quarter_from = fields.Selection(MONTH_QUARTER_SELECTION, 'Month Quarter', required=True, default = 1)\n month_year_from = fields.Integer('Year', required=True, default = genx.YEAR_NOW)\n\n\n month_of_to = fields.Selection(genx.MONTH_SELECTION, 'To the Month of', required=True, default = 12)\n month_quarter_to = fields.Selection(MONTH_QUARTER_SELECTION, 'Month Quarter', required=True, default = 2)\n month_year_to = fields.Integer('Year', required=True, default = genx.YEAR_NOW)\n\n\n\n def print_report(self, cr, uid, ids, context=None):\n\n model_payroll_detail_temp_create = self.pool.get(\"hr.payroll.detail.temp\")\n\n model_payroll_detail_temp= self.pool.get(\"hr.payroll.detail.temp\").browse(cr,uid,ids,context=None)\n\n model_payroll_detail_temp_create.search(cr,uid,[('create_uid', '=',uid)],context=context)\n\n\n unlink_ids= []\n\n #unlink_ids = [pay_detail.id for pay_detail in model_payroll_detail_temp_create.browse(cr,uid,ids,context=None)]\n for pay_detail in model_payroll_detail_temp_create.browse(cr,uid,ids,context=None):\n #print(pay_detail.create_uid)\n #raise Warning(pay_detail.id)\n unlink_ids.append(pay_detail.id)\n\n #raise Warning(unlink_ids)\n\n model_payroll_detail_temp_create.unlink(cr, uid, unlink_ids, context=context)\n\n\n model_payroll_detail= self.pool.get(\"hr.payroll.detail\")\n pay_ids = model_payroll_detail.search(cr,uid,[('create_uid', '=',uid)],context=context)\n\n\n for payroll_detail in model_payroll_detail.browse(cr,uid,pay_ids,context=None):\n dict_save = {\n 'payroll_detail_id':payroll_detail.payroll_detail_id.id,\n 'name':payroll_detail.name,\n 'employee_id':payroll_detail.employee_id.id,\n 'employee_project_assign':payroll_detail.employee_project_assign.id,\n 'is_reliever':payroll_detail.is_reliever,\n 'basic_pay_perday':payroll_detail.basic_pay_perday,\n 'basic_pay_perday_rate':payroll_detail.basic_pay_perday_rate,\n 'basic_pay_amount':payroll_detail.basic_pay_amount,\n 'basic_pay_leaves_perhour':payroll_detail.basic_pay_leaves_perhour,\n 'basic_pay_leaves_amount':payroll_detail.basic_pay_leaves_amount,\n 'reg_otpay_perhour':payroll_detail.reg_otpay_perhour,\n 'reg_otpay_amount':payroll_detail.reg_otpay_amount,\n 'reg_nightdiff_perhour':payroll_detail.reg_nightdiff_perhour,\n 'reg_nightdiffy_amount':payroll_detail.reg_nightdiffy_amount,\n 'basic_pay_restday_perhour':payroll_detail.basic_pay_restday_perhour,\n 'basic_pay_restday_amount':payroll_detail.basic_pay_restday_amount,\n 'basic_pay_restday_ot_perhour':payroll_detail.basic_pay_restday_ot_perhour,\n 'basic_pay_restday_ot_amount':payroll_detail.basic_pay_restday_ot_amount,\n 'reg_straightduty_perhour':payroll_detail.reg_straightduty_perhour,\n 'reg_straightduty_amount':payroll_detail.reg_straightduty_amount,\n 'cola_rate_perday':payroll_detail.cola_rate_perday,\n 'cola_amount':payroll_detail.cola_amount,\n 'reg_hol_pay_perday':payroll_detail.reg_hol_pay_perday,\n 'reg_hol_pay_amount':payroll_detail.reg_hol_pay_amount,\n 'reg_hol_work_pay_perhour':payroll_detail.reg_hol_work_pay_perhour,\n 'reg_hol_work_pay_amount':payroll_detail.reg_hol_work_pay_amount,\n 'reg_hol_otpay_perhour':payroll_detail.reg_hol_otpay_perhour,\n 'reg_hol_otpay_amount':payroll_detail.reg_hol_otpay_amount,\n 'reg_spechol_perhour':payroll_detail.reg_spechol_perhour,\n 'reg_spechol_amount':payroll_detail.reg_spechol_amount,\n 'reg_spechol_otpay_perhour':payroll_detail.reg_spechol_otpay_perhour,\n 'reg_spechol_otpay_amount':payroll_detail.reg_spechol_otpay_amount,\n 'other_incentive':payroll_detail.other_incentive,\n 'tardiness':payroll_detail.tardiness,\n 'tardiness_permin_rate':payroll_detail.tardiness_permin_rate,\n 'tardiness_amount':payroll_detail.tardiness_amount,\n 'undertime':payroll_detail.undertime,\n 'tardiness_pay_permin_rate':payroll_detail.tardiness_pay_permin_rate,\n 'undertime_amount':payroll_detail.undertime_amount,\n 'gross_salary':payroll_detail.gross_salary,\n 'sss_premium':payroll_detail.sss_premium,\n 'sss_loan':payroll_detail.sss_loan,\n 'hdmf_premium':payroll_detail.hdmf_premium,\n 'hdmf_salary_loan':payroll_detail.hdmf_salary_loan,\n 'hdmf_calamity_loan':payroll_detail.hdmf_calamity_loan,\n 'hmo_premium':payroll_detail.hmo_premium,\n 'other_deductions':payroll_detail.other_deductions,\n 'deductions':payroll_detail.deductions,\n 'net_pay':payroll_detail.net_pay,\n 'computed_tax':payroll_detail.computed_tax,\n 'month_half_period':payroll_detail.month_half_period,\n 'month_name_period':payroll_detail.month_name_period,\n 'year_payroll_period':payroll_detail.year_payroll_period,\n 'payroll_detail_date':payroll_detail.payroll_detail_date,\n 'incentive_id':payroll_detail.incentive_id,\n 'deduction_id':payroll_detail.deduction_id,}\n\n model_payroll_detail_temp_create.create(cr, uid, dict_save)\n\n if context is None:\n context = {}\n\n data = self.read(cr, uid, ids, ['employee_id'], context=context)[0]\n #data= self.pool.get(\"hr.payroll.detail\").browse(cr,uid,ids,context=None)\n #raise Warning(ids)\n #x_data = {'employee_id': self.employee_id}\n\n #raise Warning(data)\n obj = self.pool.get('hr.payroll.detail.temp')\n ids = obj.search(cr, uid, [('employee_id','=',9729)])\n\n #raise Warning(ids)\n #x_data = {'employee_id':9729}\n datas = {\n 'ids': ids,\n 'model': 'hr.payroll.detail.temp',\n 'form': data\n }\n #return self.pool['report'].get_action(\n #cr, uid, [], 'hr_payroll_ezra.report_payslip_employee', data=datas, context=context )\n\n return {\n 'type': 'ir.actions.report.xml',\n 'report_name': 'hr_payroll_ezra.report_payslip_employee',\n 'datas': datas,\n }\n #pass\n\n\n","sub_path":"openerp/addons/hr_payroll_ezra/wizard/payroll_payslip_employee.py","file_name":"payroll_payslip_employee.py","file_ext":"py","file_size_in_byte":13428,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"147266340","text":"\nn,m = map(int, input().split(' '))\ngraph=[list(map(int, input())) for _ in range(m)]\n\ndef dbfs (x,y):\n if x<=-1 or x>=n or y<=-1 or y>=m :\n return False\n\n if graph[x][y]==0:\n graph[x][y]=1\n dbfs(x-1,y)\n dbfs(x+1,y)\n dbfs(x,y-1)\n dbfs(x,y+1)\n return True\n\n return False\nresult =0\nfor i in range(n):\n for j in range(m):\n if dbfs(i,j)==True:\n result+=1\nprint(result)\n","sub_path":"020503.py","file_name":"020503.py","file_ext":"py","file_size_in_byte":444,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"604625123","text":"#coding: utf-8\nfrom django.shortcuts import render\nfrom django.views.generic import ListView, CreateView, UpdateView\nfrom django.core.urlresolvers import reverse as r, reverse_lazy\nfrom django.shortcuts import render, render_to_response, get_object_or_404, redirect\nfrom django.http import HttpResponseRedirect\n\nfrom .models import Carro, Revendedor\nfrom .forms import CarroForm, RevendedorForm\n\n\n\nclass CarrosListView(ListView):\n\tmodel = Carro\n\ttemplate_name = 'carros/carros.html'\n\tcontext_object_name = 'carros'\n\ndef carros(request):\n return render(request, \"carros/carros.html\", { \"carros\": Carro.objects.all() })\n\nclass CarroCreateView(CreateView):\n\tmodel = Carro\n\ttemplate_name ='carros/incluir.html'\n\tform_class= CarroForm\n\tsuccess_url = reverse_lazy('carros:carros')\n\ndef incluir_carro(request):\n\tif request.POST:\n\t\tform = CarroForm(request.POST)\n\t\tif form.is_valid():\n\t\t\tform.save()\n\t\t\treturn HttpResponseRedirect(r('carros:carros'))\n\t\telse:\n\t\t\treturn render(request, \"carros/incluir.html\", { 'form':form })\n\telse:\n\t\treturn render(request, \"carros/incluir.html\", {'form':CarroForm()})\n\nclass CarroUpdateView(UpdateView):\n\tmodel = Carro\n\ttemplate_name ='carros/editar.html'\n\tform_class= CarroForm\n\tsuccess_url = reverse_lazy('carros:carros')\n\ndef editar_carro(request, pk):\n\n\tcarro = get_object_or_404(Carro, pk=pk)\n\tif request.method == 'POST':\n\t\tform = CarroForm(request.POST, instance=carro)\n\t\tif form.is_valid():\n\t\t\tform.save()\n\t\t\treturn HttpResponseRedirect(r('carros:carros'))\n\t\telse:\n\t\t\treturn render(request, \"carros/incluir.html\", { 'form':form })\n\telse:\n\t\treturn render(request, \"carros/editar.html\", {'form':CarroForm(instance=carro)})\n\n\n\nclass RevendedorListView(ListView):\n\tmodel = Revendedor\n\ttemplate_name = 'carros/revendedores.html'\n\tcontext_object_name = 'revendedores'\n\n\nclass RevendedorCreateView(CreateView):\n\tmodel = Revendedor\n\ttemplate_name ='carros/revendedor_incluir.html'\n\tform_class= RevendedorForm\n\tsuccess_url = reverse_lazy('carros:revendedores')\n\nclass RevendedorUpdateView(UpdateView):\n\tmodel = Revendedor\n\ttemplate_name ='carros/revendedor_editar.html'\n\tform_class= RevendedorForm\n\tsuccess_url = reverse_lazy('carros:revendedores')\n\n","sub_path":"carros/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2178,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"148884167","text":"from infra.fixtures.set_audit_user import set_audit_user\nfrom infra.fixtures.menu_item import MenuItemTuple, load_menus\nfrom infra.fixtures.menu_description import MenuDescriptionTuple\n\nset_audit_user()\n# Load Menus\ncommon_menus = (\n MenuItemTuple(item_description=\"Common Business Objects Module\", parent_menu_name=\"Application Main Menu\", display_sequence=20, resource_code=None,\n menu_description_tuple=(\n MenuDescriptionTuple(language_code='ms', menu_description=u'Modul Objek-objek Perniagaan Lazim'),\n )\n ),\n # Auth Menu\n MenuItemTuple(item_description=\"Maintain Common Master Files\", parent_menu_name=\"Common Business Objects Module|Application Main Menu\", \n display_sequence=10, resource_code=None,\n menu_description_tuple=(\n MenuDescriptionTuple(language_code='ms', menu_description=u'Penyelenggaraan Fail-fail Induk Lazim'),\n )\n ),\n # Items for menu\n MenuItemTuple(item_description=\"Maintain Currencies\", \n parent_menu_name=\"Maintain Common Master Files|Common Business Objects Module\", display_sequence=10, resource_code='MAINT-CURRENCY',\n menu_description_tuple=None\n ),\n MenuItemTuple(item_description=\"Maintain Exchange Rates\", \n parent_menu_name=\"Maintain Common Master Files|Common Business Objects Module\", display_sequence=20, resource_code='MAINT-FOREX-RATE',\n menu_description_tuple=None\n ),\n MenuItemTuple(item_description=\"Maintain Countries\", \n parent_menu_name=\"Maintain Common Master Files|Common Business Objects Module\", display_sequence=30, resource_code='MAINT-COUNTRY',\n menu_description_tuple=None\n ),\n MenuItemTuple(item_description=\"Maintain Companies\", \n parent_menu_name=\"Maintain Common Master Files|Common Business Objects Module\", display_sequence=40, resource_code='MAINT-COMPANY',\n menu_description_tuple=None\n ),\n MenuItemTuple(item_description=\"Maintain Branches\", \n parent_menu_name=\"Maintain Common Master Files|Common Business Objects Module\", display_sequence=50, resource_code='MAINT-BRANCH',\n menu_description_tuple=None\n ),\n MenuItemTuple(item_description=\"Maintain Billing Types\", \n parent_menu_name=\"Maintain Common Master Files|Common Business Objects Module\", display_sequence=60, resource_code='MAINT-BILLING-TYPE',\n menu_description_tuple=None\n ),\n MenuItemTuple(item_description=\"Maintain Charge Methods\", \n parent_menu_name=\"Maintain Common Master Files|Common Business Objects Module\", display_sequence=70, resource_code='MAINT-CHARGE-METHOD',\n menu_description_tuple=None\n ),\n MenuItemTuple(item_description=\"Maintain Charge Schedules\", \n parent_menu_name=\"Maintain Common Master Files|Common Business Objects Module\", display_sequence=80, resource_code='MAINT-CHARGE-SCHEDULE',\n menu_description_tuple=None\n ),\n MenuItemTuple(item_description=\"Maintain Payment Terms\", \n parent_menu_name=\"Maintain Common Master Files|Common Business Objects Module\", display_sequence=90, resource_code='MAINT-PAYMENT-TERM',\n menu_description_tuple=None\n ),\n MenuItemTuple(item_description=\"Maintain Party Categories\", \n parent_menu_name=\"Maintain Common Master Files|Common Business Objects Module\", display_sequence=100, resource_code='MAINT-PARTY-CATEGORY',\n menu_description_tuple=None\n ),\n MenuItemTuple(item_description=\"Maintain Parties\", \n parent_menu_name=\"Maintain Common Master Files|Common Business Objects Module\", display_sequence=110, resource_code='MAINT-PARTY',\n menu_description_tuple=None\n ),\n MenuItemTuple(item_description=\"Maintain Payment Methods\", \n parent_menu_name=\"Maintain Common Master Files|Common Business Objects Module\", display_sequence=120, resource_code='MAINT-PAY-METHOD',\n menu_description_tuple=None\n ),\n MenuItemTuple(item_description=\"Maintain Clearing Zones\", \n parent_menu_name=\"Maintain Common Master Files|Common Business Objects Module\", display_sequence=130, resource_code='MAINT-CLEAR-ZONE',\n menu_description_tuple=None\n ),\n MenuItemTuple(item_description=\"Maintain Banks\", \n parent_menu_name=\"Maintain Common Master Files|Common Business Objects Module\", display_sequence=140, resource_code='MAINT-BANK',\n menu_description_tuple=None\n ),\n MenuItemTuple(item_description=\"Maintain Bank Branches\", \n parent_menu_name=\"Maintain Common Master Files|Common Business Objects Module\", display_sequence=150, resource_code='MAINT-BANK-BRANCH',\n menu_description_tuple=None\n ),\n )\nload_menus(common_menus)\n","sub_path":"common/fixtures/menu_item.py","file_name":"menu_item.py","file_ext":"py","file_size_in_byte":5035,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"366668064","text":"import numpy as np\nimport cv2 as cv2\nfrom tqdm import tqdm\nimport matplotlib.pyplot as plt\nfrom time import time\n\ndef to_u(a):\n a -= np.min(a)\n a /= np.max(a)\n a *= 255\n return np.uint8(a)\n\ndef optical_flow(one, two,pure=False, pyr_scale = 0.5, levels=1, winsize = 2, iterations = 2, poly_n = 5, poly_sigma = 1.1, flags = 0, only_flow = False):\n \"\"\"\n method taken from (https://chatbotslife.com/autonomous-vehicle-speed-estimation-from-dashboard-cam-ca96c24120e4)\n \"\"\"\n one_g = cv2.cvtColor(one, cv2.COLOR_RGB2GRAY)\n two_g = cv2.cvtColor(two, cv2.COLOR_RGB2GRAY)\n hsv = np.zeros(np.array(one).shape) # hsv = np.zeros((392,640, 3))\n\n # set saturation\n hsv[:,:,1] = cv2.cvtColor(two, cv2.COLOR_RGB2HSV)[:,:,1]\n # obtain dense optical flow paramters\n flow = cv2.calcOpticalFlowFarneback(one_g, two_g, flow=None, #https://www.programcreek.com/python/example/89313/cv2.calcOpticalFlowFarneback\n pyr_scale=pyr_scale, levels=levels, winsize=winsize, #15 je bil winsize\n iterations=iterations,\n poly_n=poly_n, poly_sigma=poly_sigma, flags=flags)\n if only_flow:\n return flow\n # convert from cartesian to polar\n mag, ang = cv2.cartToPolar(flow[..., 0], flow[..., 1])\n # hue corresponds to direction\n\n if not pure:\n # ang is in radians (0 to 2pi)\n hsv[:,:,0] = ang * (255/ np.pi / 2)\n # value corresponds to magnitude\n #hsv[:,:,2] = cv2.normalize(mag,None,0,255,cv2.NORM_MINMAX)\n # convert HSV to int32's\n hsv = np.asarray(hsv, dtype= np.float32)\n return hsv\n else:\n return mag, ang\n\n\n\ndef generator_from_video(file = 'C:/ultrasound_testing\\ALOKA_US/26081958/20181220/26081958_20181220_MSK-_VIDEO_0003.AVI', maxframes = 2000):\n \"\"\"\n :param file: string file location\n :param maxframes: int frames to array\n :return:\n \"\"\"\n vidcap = cv2.VideoCapture(file)\n array=[]\n frame = 0\n success, image = vidcap.read()\n while success:\n array.append(image)\n frame+=1\n success, image = vidcap.read()\n yield np.array(image)\n #while True:\n # yield array[np.random.randint(0,frame)]\n\ndef array_from_video(file = 'C:/ultrasound_testing\\ALOKA_US/26081958/20181220/26081958_20181220_MSK-_VIDEO_0003.AVI', maxframes = 2000):\n \"\"\"\n :param file: string file location\n :param maxframes: int frames to array\n :return:\n \"\"\"\n vidcap = cv2.VideoCapture(file)\n array=[]\n frame = 0\n success, image = vidcap.read()\n while success:\n array.append(image)\n frame+=1\n success, image = vidcap.read()\n #array.append(np.array(image))\n return np.array(array)\n\ndef array_to_video(array, file = \"../{}.avi\".format(time()), to_u_ = True):\n out = cv2.VideoWriter(file, apiPreference=0, fourcc=cv2.VideoWriter_fourcc(*'DIVX'), fps=18,\n frameSize=(array[0].shape[1], array[0].shape[0]))\n for frame in array:\n if frame.dtype != np.uint8 and to_u_:\n frame= to_u(frame)\n out.write(frame)\n\n\ndef optical_flow_from_array(array, pyr_scale = 0.5, levels=1, winsize = 2, iterations = 2, poly_n = 5, poly_sigma = 1.1, flags = 0):\n prev_frame = []\n optical_f = []\n for frame in array:\n if prev_frame == []:\n prev_frame = frame\n optical_f.append(np.zeros(shape=frame.shape, dtype=frame.dtype))\n else:\n of = optical_flow(prev_frame, frame,pure=False, pyr_scale=pyr_scale, levels=levels, winsize=winsize, iterations=iterations, poly_n=poly_n, poly_sigma=poly_sigma, flags=flags)\n #std = np.std(of)\n #of[of < ] = 0 #100\n #optical_f.append(to_u(of))\n optical_f.append(np.uint8(of))\n prev_frame = frame\n return np.array(optical_f)\n\n\n#plt.imshow(array_from_video()[55])\n#plt.show()","sub_path":"cv2utils.py","file_name":"cv2utils.py","file_ext":"py","file_size_in_byte":3952,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"250299973","text":"from django.urls import path\nfrom django.conf.urls import include\nfrom .views import AnimalListView, AddAnimal, AnimalDetailView, EditAnimal, MedicalHistoryView, \\\n MedhistoryListView, MedicalHistoryAdd\n\n\nurlpatterns = [\n path('animallist/', AnimalListView.as_view(), name='animal_list'),\n path('add/', AddAnimal.as_view(), name='add_animal'),\n path('edit//', EditAnimal.as_view(), name='edit_animal'),\n path('animal/', AnimalDetailView.as_view(), name='animal_detail'),\n path('medlist//', MedhistoryListView.as_view(), name='med_list'),\n path('meddetail//', MedicalHistoryView.as_view(), name='med_detail'),\n path('medadd/', MedicalHistoryAdd.as_view(), name='med_add'),\n path('api/', include('animals.API.urls'), name='api')\n]\n","sub_path":"animals/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":803,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"582080671","text":"# /index.py\nfrom flask import Flask, request, jsonify, render_template, make_response\nimport os\n# import dialogflow\nimport requests\nimport json\n# import pusher\n\napp = Flask(__name__)\n\n@app.route('/json', methods=['POST'])\ndef json_example():\n\n # validate the request body contains JSON\n if request.is_json:\n\n # Parse the JSON into a Python dictionary\n req = request.get_json()\n\n response_body = {\n \"message\" : \"JSON received!\",\n \"sender\" : req.get(\"name\")\n }\n\n res = make_response(jsonify(response_body), 200)\n\n # Returns a string along with an HTTP Request Status Code\n return res\n \n else:\n\n # The Request body wasn't JSON so return a 400 HTTP status code \n return make_response(\n jsonify(\n {\"message\" : \"Request body must be JSON\"}\n ), 400)\n\n@app.route('/read', methods=['GET'])\ndef read_json():\n return \"oinpepê!\"\n\n# run Flask app\nif __name__ == \"__main__\":\n app.run() ","sub_path":"index.py","file_name":"index.py","file_ext":"py","file_size_in_byte":1021,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"336995648","text":"\nimport matplotlib as plt\nfrom copy import *\nimport os\n\nimport scipy.io as sio\n\nfrom scipy.sparse import rand\n\nimport random\n\nimport json\nimport argparse\n\nimport pickle\n\nimport argparse\n\nfrom numpy import arange\nfrom pyNN.utility import get_simulator, init_logging, normalized_filename\nimport numpy as np\nimport numpy\n\nimport pylab as plt\nimport spynnaker8 as sim\nfrom pyNN.utility.plotting import Figure, Panel\n\n# SpiNNaker setup\nsim.setup()\n# +---------------------------------------------------------------------------+\n# | General Parameters |\n# +---------------------------------------------------------------------------+\n\n# Population parameters\nmodel = sim.IF_curr_exp\nsim.set_number_of_neurons_per_core(sim.IF_curr_exp, 50)\ncell_params = {'cm': 0.25,\n 'i_offset': 0.0,\n 'tau_m': 10.0,\n 'tau_refrac': 2.0,\n 'tau_syn_E': 5.0,\n 'tau_syn_I': 5.0,\n 'v_reset': -70.0,\n 'v_rest': -65.0,\n 'v_thresh': -50.0\n }\n# === Configure the simulator ================================================\n\n# sim, options = get_simulator((\"--plot-figure\", \"Plot the simulation results to a file.\", {\"action\": \"store_true\"}),\n# (\"--debug\", \"Print debugging information\"))\n\noptions = argparse.Namespace(debug=None, plot_figure=True, simulator='nest')\n\n\nif options.debug:\n init_logging(None, debug=True)\n\n\n# prefs.devices.genn.cuda_path = '/usr/local/cuda-10.0'\n# prefs.devices.genn.path = '/home/le/Installation/packages/genn-3.2.0'\n#\n# # set_device('cpp_standalone', directory='STDP_standalone',build_on_run=False)\n# set_device('cpp_standalone')\n\nrandom.seed = 2020\nnumpy.random.RandomState(seed = 2020)\n\n\n# # load parameters\n# with open('MBSNN_params.yaml' , 'rb') as f:\n# params = yaml.safe_load(f)\n\n# ##global\n\n# nb_pn = params['NB_Neuron']['PN']\n# nb_kc = params['NB_Neuron']['KC']\n# nb_en = params['NB_Neuron']['EN']\n\nnb_pn = 210\nnb_kc = 20000\nnb_en = 1\n\nnb_pn2kc = 5\n\n\nclass MB_LE(object):\n\n def __init__(self, dvs_input, sim_t, w_kc2kc=0):\n\n self.w_kc2kc = w_kc2kc\n\n self.sim_t = sim_t\n\n self.pn_neuron_idx = range(0 , nb_pn , nb_pn / 5)\n self.kc_neuron_idx = range(0 , nb_kc , nb_kc / 10)\n\n self.spike_source = sim.Population(nb_pn, sim.SpikeSourceArray(spike_times = dvs_input),label = \"DVS\")\n self.pns = sim.Population(nb_pn , model(**cell_params), label = \"PN\")\n self.kcs = sim.Population(nb_kc , model(**cell_params) , label = \"KC\")\n self.kcs_a = sim.Population(nb_kc ,model(**cell_params), label = \"KC_A\")\n self.ens = sim.Population(nb_en ,model(**cell_params) , label = \"EN\")\n self.ens_a = sim.Population(nb_en , model(**cell_params), label = \"EN_A\")\n\n self.dvs2pn = sim.Projection(self.spike_source , self.pns , sim.OneToOneConnector() ,\n sim.StaticSynapse(weight = 0.3, delay = 1.0) ,\n receptor_type = 'excitatory')\n self.pn2kc = sim.Projection(self.pns , self.kcs , sim.FixedTotalNumberConnector(nb_pn2kc*nb_kc) ,\n sim.StaticSynapse(weight = 0.3 , delay = 1.0) ,\n receptor_type = 'excitatory')\n self.pn2kc_a = sim.Projection(self.pns , self.kcs_a , sim.FixedTotalNumberConnector(nb_pn2kc*nb_kc) ,\n sim.StaticSynapse(weight = 0.3 , delay = 1.0) ,\n receptor_type = 'excitatory')\n self.kc2en = sim.Projection(self.kcs , self.ens , sim.AllToAllConnector() ,\n sim.StaticSynapse(weight = 0.15 , delay = 1.0) ,\n receptor_type = 'excitatory')\n self.kc_a2en_a = sim.Projection(self.kcs_a , self.ens_a , sim.AllToAllConnector() ,\n sim.StaticSynapse(weight = 0.15 , delay = 1.0) ,\n receptor_type = 'excitatory')\n self.kc_a2kc_a = sim.Projection(self.kcs , self.kcs_a , sim.AllToAllConnector() ,\n sim.StaticSynapse(weight = 0.1 , delay = 1.0) ,\n receptor_type = 'excitatory')\n \n self.ens.record(['v', 'spikes'])\n self.ens_a.record(['v', 'spikes'])\n \n def run_sim(self):\n sim.run(self.sim_t)\n\n # === Save the results, optionally plot a figure =============================\n\n# filename = normalized_filename(\"Results\" , \"Izhikevich\" , \"pkl\" ,\n# options.simulator , sim.num_processes())\n# self.ens.write_data(filename , annotations = {'script_name': __file__})\n\n if options.plot_figure:\n from pyNN.utility.plotting import Figure , Panel\n\n data = self.ens.get_data().segments[0]\n v = data.filter(name = \"v\")[0]\n # u = data.filter(name=\"u\")[0]\n Figure(\n Panel(v , ylabel = \"Membrane potential (mV)\" , xticks = True ,\n xlabel = \"Time (ms)\" , yticks = True) ,\n # Panel(u, ylabel=\"u variable (units?)\"),\n annotations = \"Simulated with %s\" % options.simulator.upper()\n ).save(\"en.png\")\n\n\n # === Clean up and quit ========================================================\n\n sim.end()\n\n # else:\n # print 'MBSNN is testing'\n # self.net.add(self.S_kc2kc_learned,self.kc2kc_STM)\n # self.dvs.set_spikes(self.pre_learning_input[0], self.pre_learning_input[1] * ms)\n # self.net.run(self.pre_learning_input[1][-1] * ms)\n # self.dvs.set_spikes(self.sim_input[0] , self.sim_input[1] * ms)\n # self.net.run(self.sim_input[1][-1] * ms - self.pre_learning_input[1][-1] * ms)\n\n\n","sub_path":"PYNN_PN2EN.py","file_name":"PYNN_PN2EN.py","file_ext":"py","file_size_in_byte":5868,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"124502191","text":"# 可变和不可变类型\r\n# 列表是可变的(Mutable)\r\na = [1, 2, 3, 4]\r\na\r\n\r\n# 通过索引改变:\r\n\r\na[0] = 100\r\na\r\n\r\n# 通过方法改变:\r\na.insert(3, 200)\r\na\r\n\r\na.sort()\r\na\r\n\r\n# 字符串是不可变的(Immutable)\r\ns = \"hello world\"\r\ns\r\n'''\r\n字符串方法只是返回一个新字符串,并不改变原来的值:\r\n\r\nIn [7]:\r\nprint s.replace('world', 'Mars')\r\nprint s\r\nhello Mars\r\nhello world\r\n如果想改变字符串的值,可以用重新赋值的方法:\r\n\r\nIn [8]:\r\ns = \"hello world\"\r\ns = s.replace('world', 'Mars')\r\nprint s\r\nhello Mars\r\n或者用 bytearray 代替字符串:\r\n\r\nIn [9]:\r\ns = bytearray('abcde')\r\ns[1:3] = '12'\r\ns\r\nOut[9]:\r\nbytearray(b'a12de')\r\n\r\n字符串不可变的原因¶\r\n其一,列表可以通过以下的方法改变,而字符串不支持这样的变化。\r\n\r\nIn [10]:\r\na = [1, 2, 3, 4]\r\nb = a\r\n此时, a 和 b 指向同一块区域,改变 b 的值, a 也会同时改变:\r\n\r\nIn [11]:\r\nb[0] = 100\r\na\r\nOut[11]:\r\n[100, 2, 3, 4]\r\n其二,是字符串与整数浮点数一样被认为是基本类型,而基本类型在Python中是不可变的。\r\n\r\n'''\r\n\r\n\r\n'''\r\n可变数据类型\r\nlist, dictionary, set, numpy array, user defined objects\r\n\r\n不可变数据类型\r\ninteger, float, long, complex, string, tuple, frozenset\r\n'''\r\n","sub_path":"var/notes/python/essentials/004-mutable-and-immutable-date-types.py","file_name":"004-mutable-and-immutable-date-types.py","file_ext":"py","file_size_in_byte":1294,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"334788637","text":"import sys\n\n# 1 7 19 37 61\ndef solution(n):\n temp = 1\n count = 1\n while True:\n if n <= temp:\n print(count)\n return\n temp += 6 * count\n count += 1\n\n\nsolution(int(sys.stdin.readline()))","sub_path":"python/implementation/2292_벌집.py","file_name":"2292_벌집.py","file_ext":"py","file_size_in_byte":235,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"88887537","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('accounts', '0002_workperiod_workshift'),\n ('tagging', '0003_auto_20150401_1337'),\n ]\n\n operations = [\n migrations.AddField(\n model_name='operation',\n name='work_period',\n field=models.ForeignKey(default=1, to='accounts.WorkPeriod', related_name='operations'),\n preserve_default=False,\n ),\n ]\n","sub_path":"mapping/tagging/migrations/0004_operation_work_period.py","file_name":"0004_operation_work_period.py","file_ext":"py","file_size_in_byte":545,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"652639528","text":"import os\nimport pytest\n\n\ndef pytest_configure(config):\n \"\"\"Register the mark pytest.markusefixturesif() to py.test\"\"\"\n config.addinivalue_line(\"markers\",\n \"usefixturesif(condition, fixture_name, ...): mark test to use fixtures if condition returns True\")\n\n\ndef pytest_runtest_setup(item):\n \"\"\"Add pytest.markusefixturesif() to py.test\"\"\"\n marker = item.get_marker('usefixturesif')\n if marker is not None:\n for info in marker:\n if info.args[0]:\n if isinstance(info.args[1], (list, tuple)):\n item.fixturenames.extend(info.args[1])\n else:\n item.fixturenames.extend(info.args[1:])\n","sub_path":"pytest_usefixturesif.py","file_name":"pytest_usefixturesif.py","file_ext":"py","file_size_in_byte":706,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"624578292","text":"# 3rd party\nimport scipy.ndimage\n\n# myami\nimport pyami.imagefun\n\n# local\nfrom redux.pipe import Pipe\nfrom redux.pipe import shape_converter\n\nclass Shape(Pipe):\n\trequired_args = {'shape': shape_converter}\n\n\t@classmethod\n\tdef run(cls, input, shape):\n\n\t\t# that was easy\n\t\tif input.shape == shape:\n\t\t\treturn input\n\n\t\t# make sure shape is same dimensions as input image\n\t\t# rgb input image would have one extra dimension\n\t\tif len(shape) != len(input.shape):\n\t\t\tif len(shape) +1 != len(input.shape):\n\t\t\t\traise ValueError('mismatch in number of dimensions: %s -> %s' % (input.shape, shape))\n\t\t\telse:\n\t\t\t\tis_rgb=True\n\t\telse:\n\t\t\tis_rgb=False\n\n\t\t# determine whether to use imagefun.bin or scipy.ndimage.zoom\n\t\tbinfactors = []\n\t\tzoomfactors = []\n\t\tfor i in range(len(shape)):\n\t\t\tzoomfactors.append(float(shape[i])/float(input.shape[i]))\n\n\t\t\t## for rgb, binning not implemented\n\t\t\tif is_rgb:\n\t\t\t\tbinfactors.append(1)\n\t\t\t\tcontinue\n\t\t\telse:\n\t\t\t\tbinfactors.append(input.shape[i] / shape[i])\n\n\t\t\t# bin <1 not allowed (when output bigger than input)\n\t\t\tif binfactors[i] == 0:\n\t\t\t\tbinfactors[i] = 1\n\n\t\t\t# check original shape is divisible by new shape\n\t\t\tif input.shape[i] % shape[i]:\n\t\t\t\t# binning alone will not work, try initial bin, then interp\n\t\t\t\tstart = binfactors[i]\n\t\t\t\tfor trybin in range(start, 0, -1):\n\t\t\t\t\tif input.shape[i] % trybin:\n\t\t\t\t\t\tcontinue\n\t\t\t\t\tbinfactors[i] = trybin\n\t\t\t\t\tzoomfactors[i] *= binfactors[i]\n\t\t\t\t\tbreak\n\t\t\telse:\n\t\t\t\t# just use bin\n\t\t\t\tzoomfactors[i] = 1.0\n\n\t\t## don't zoom 3rd axis of rgb image\n\t\tif is_rgb:\n\t\t\tzoomfactors.append(1.0)\n\n\t\toutput = input\n\n\t\t## run bin if any bin factors not 1\n\t\tif binfactors:\n\t\t\tfor binfactor in binfactors:\n\t\t\t\tif binfactor != 1:\n\t\t\t\t\toutput = pyami.imagefun.bin(output, binfactors[0], binfactors[1])\n\t\t\t\t\tbreak\n\n\t\t## run zoom if any zoom factors not 1.0\n\t\tif zoomfactors:\n\t\t\tfor zoomfactor in zoomfactors:\n\t\t\t\tif zoomfactor != 1.0:\n\t\t\t\t\toutput = scipy.ndimage.zoom(output, zoomfactors)\n\t\t\t\t\tbreak\n\n\t\treturn output\n\n\tdef make_dirname(self):\n\t\tdims = map(str, self.kwargs['shape'])\n\t\tdims = 'x'.join(dims)\n\t\tself._dirname = dims\n\n","sub_path":"lib/python2.7/site-packages/redux/pipes/shape.py","file_name":"shape.py","file_ext":"py","file_size_in_byte":2080,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"47279244","text":"import os\nimport warnings\nimport abc\nimport pandas as pd\nimport cudf\n\nfrom .task import Task\nfrom .taskSpecSchema import TaskSpecSchema\nfrom .portsSpecSchema import PortsSpecSchema\n\nfrom ._node import _Node\n\n\n__all__ = ['Node']\n\n\nclass _PortsMixin(object):\n '''Mixed class must have (doesn't have to implement i.e. relies on\n NotImplementedError) \"ports_setup\" method otherwise raises AttributeError.\n '''\n def _using_ports(self):\n '''Check if the :meth:`ports_setup` is implemented. If it is return\n True otherwise return False i.e. ports API or no-ports API.\n '''\n try:\n _ = self.ports_setup()\n has_ports = True\n except NotImplementedError:\n has_ports = False\n return has_ports\n\n def __get_io_port(self, io=None, full_port_spec=False):\n input_ports, output_ports = self.ports_setup()\n if io in ('in',):\n io_ports = input_ports\n else:\n io_ports = output_ports\n\n if io_ports is None:\n io_ports = dict()\n\n if not full_port_spec:\n io_ports = list(io_ports.keys())\n\n return io_ports\n\n def _get_input_ports(self, full_port_spec=False):\n return self.__get_io_port(io='in', full_port_spec=full_port_spec)\n\n def _get_output_ports(self, full_port_spec=False):\n return self.__get_io_port(io='out', full_port_spec=full_port_spec)\n\n\nclass Node(_PortsMixin, _Node):\n '''Base class for implementing gQuant plugins i.e. nodes. A node processes\n tasks within a gQuant task graph.\n\n If one desires to use ports API then must implement the following method:\n\n :meth: ports_setup\n Defines ports for the node. Refer to ports_setup docstring for\n further details.\n\n A node implementation must override the following methods:\n\n :meth: columns_setup\n Define expected columns in dataframe processing. If\n inputs/outputs are not dataframes then implement a pass through\n without details. Ex.:\n def columns_setup(self):\n pass\n When processing dataframes define expected columns. Ex.:\n # non-port API\n def columns_setup(self):\n self.required = {'x': 'float64',\n 'y': 'float64'}\n\n # ports API\n def columns_setup(self):\n self.required = {\n 'iport0_name': {'x': 'float64',\n 'y': 'float64'}\n 'iport1_name': some_dict,\n etc.\n }\n Refer to columns_setup docstring for further details.\n\n :meth: process\n Main functionaliy or processing logic of the Node. Refer to\n process docstring for further details.\n\n '''\n\n cache_dir = '.cache'\n\n def __init__(self, task):\n # make sure is is a task object\n assert isinstance(task, Task)\n self._task_obj = task # save the task obj\n self.uid = task[TaskSpecSchema.task_id]\n self.conf = task[TaskSpecSchema.conf]\n self.load = task.get(TaskSpecSchema.load, False)\n self.save = task.get(TaskSpecSchema.save, False)\n\n self.required = {}\n self.addition = {}\n self.deletion = {}\n # Retention must be None instead of empty dict. This replaces anything\n # set by required/addition/retention. An empty dict is a valid setting\n # for retention therefore use None instead of empty dict.\n self.retention = None\n self.rename = {}\n self.delayed_process = False\n # customized the column setup\n self.columns_setup()\n self.profile = False # by default, do not profile\n\n if self._using_ports():\n PortsSpecSchema.validate_ports(self.ports_setup())\n\n def ports_setup(self):\n \"\"\"Virtual method for specifying inputs/outputs ports. Implement if\n desire to use ports API for Nodes in a TaskGraph. Leave un-implemented\n for non-ports API.\n\n Must return an instance of NodePorts that adheres to PortsSpecSchema.\n Refer to PortsSpecSchema and NodePorts in module:\n gquant.dataframe_flow.portsSpecSchema\n\n Ex. empty no-ports but still implement ports API.\n node_ports = NodePorts()\n return node_ports\n\n Ex. ports for inputs and outputs. (typical case)\n inports = {\n 'iport0_name': {\n PortsSpecSchema.port_type: cudf.DataFrame\n },\n 'iport1_name': {\n PortsSpecSchema.port_type: cudf.DataFrame,\n PortsSpecSchema.optional: True\n }\n }\n\n outports = {\n 'oport0_name': {\n PortsSpecSchema.port_type: cudf.DataFrame\n },\n 'oport1_name': {\n PortsSpecSchema.port_type: cudf.DataFrame,\n PortsSpecSchema.optional: True\n }\n }\n\n node_ports = NodePorts(inports=inports, outports=outports)\n return node_ports\n\n :return: Node ports\n :rtype: NodePorts\n\n \"\"\"\n raise NotImplementedError\n\n @abc.abstractmethod\n def columns_setup(self):\n \"\"\"\n All children class should implement this.\n It is used to compute the input/output column names and types by\n defining the diff between input and output dataframe columns.\n\n The self.delayed_process flag is by default set to False. It can be\n overwritten here to True. For native dataframe API calls, dask cudf\n support the distribution computation. But the dask_cudf dataframe does\n not support GPU customized kernels directly. We can use to_delayed and\n from_delayed low level interfaces of dask_cudf to add this support.\n In order to use Dask (for distributed computation i.e. multi-gpu in\n examples later on) we set the flag and the framework\n handles dask_cudf dataframes automatically under the hood.\n\n `self.required`, `self.addition`, `self.deletion` and `self.retention`\n are python dictionaries, where keys are column names and values are\n column types. `self.rename` is a python dictionary where both keys and\n values are column names.\n\n `self.required` defines the required columns in the input dataframes\n `self.addition` defines the addional columns in the output dataframe\n Only one of `self.deletion` and `self.retention` is needed to define\n removed columns. `self.deletion` is to define the removed columns in\n the output dataframe. `self.retention` defines the remaining columns.\n\n Example column types:\n * int64\n * int32\n * float64\n * float32\n * datetime64[ms]\n\n There is a special syntax to use variable for column names. If the\n the key is `@xxxx`, it will `xxxx` as key to look up the value in the\n `self.conf` variable.\n\n \"\"\"\n self.required = {}\n self.addition = {}\n self.deletion = {}\n # Retention must be None instead of empty dict. This replaces anything\n # set by required/addition/retention. An empty dict is a valid setting\n # for retention therefore use None instead of empty dict.\n self.retention = None\n self.rename = {}\n\n @abc.abstractmethod\n def process(self, inputs):\n \"\"\"\n process the input dataframe. Children class is required to override\n this\n\n Arguments\n -------\n inputs: list or dictionary\n Depending on if ports_setup is implemented or not i.e. ports API\n or no-ports API, the inputs is a list (no ports API) or a\n dictionary (ports API).\n NO PORTS:\n list of input dataframes. dataframes order in the list matters\n Ex: inputs = [df0, df1, df2, etc.]\n Within the context of connected nodes in a task-graph a\n task spec specifies inputs as a list of task-ids of input\n tasks. During task-graph run the inputs setup for process\n will be a list of outputs from those tasks (corresponding\n to task-spec task-ids ) in the order set in the task-spec.\n Ex.:\n TaskSpecSchema.inputs: [\n some_task_id,\n some_other_task_id,\n etc.\n ]\n Within the process access the dataframes (data inputs) as:\n df0 = inputs[0] # from some_task_id\n df1 = inputs[1] # from some_other_task_id\n etc.\n PORTS:\n dictionary keyed by port name as defined in ports_setup.\n Ex.:\n inputs = {\n iport0: df0,\n iport1: df1,\n etc.\n }\n The difference with no-ports case is that the task-spec\n for inputs is a dictionary keyed by port names with values\n being task-ids of input tasks \".\" port output of the input\n tasks. Ex.:\n TaskSpecSchema.inputs: {\n iport0: some_task_id.some_oport,\n iport1: some_other_task_id.some_oport,\n etc.\n }\n Within the process access the dataframes (data inputs) as:\n df0 = inputs[iport0] # from some_task_id some_oport\n df1 = inputs[iport1] # from some_other_task_id some_oport\n etc.\n\n Returns\n -------\n dataframe\n The output can be anything representable in python. Typically it's\n a processed dataframe.\n NO PORTS:\n Return some dataframe or output. Ex.:\n df = cudf.DataFrame() # or maybe it can from an input\n # do some calculations and populate df.\n return df\n PORTS:\n Mostly the same as NO PORTS but must return a dictionary keyed\n by output ports (as defined in ports_setup). Ex.:\n df = cudf.DataFrame() # or maybe it can from an input\n # do some calculations and populate df.\n return {oport: df}\n \"\"\"\n output = None\n return output\n\n def load_cache(self, filename=None):\n \"\"\"\n Defines the behavior of how to load the cache file from the `filename`.\n Node can override this method. Default implementation assumes cudf\n dataframes.\n\n Arguments\n -------\n filename: str\n filename of the cache file. Leave as none to use default.\n\n \"\"\"\n cache_dir = os.getenv('GQUANT_CACHE_DIR', self.cache_dir)\n if filename is None:\n filename = cache_dir + '/' + self.uid + '.hdf5'\n\n if self._using_ports():\n output_df = {}\n with pd.HDFStore(filename, mode='r') as hf:\n for oport, pspec in \\\n self._get_output_ports(full_port_spec=True).items():\n ptype = pspec.get(PortsSpecSchema.port_type)\n ptype = [ptype] if not isinstance(ptype, list) else ptype\n key = '{}/{}'.format(self.uid, oport)\n # check hdf store for the key\n if key not in hf:\n raise Exception(\n 'The task \"{}\" port \"{}\" key \"{}\" not found in '\n 'the hdf file \"{}\". Cannot load from cache.'\n .format(self.uid, oport, key, filename)\n )\n if cudf.DataFrame not in ptype:\n warnings.warn(\n RuntimeWarning,\n 'Task \"{}\" port \"{}\" port type is not set to '\n 'cudf.DataFrame. Attempting to load port data '\n 'with cudf.read_hdf.'.format(self.uid, oport))\n output_df[oport] = cudf.read_hdf(hf, key)\n else:\n output_df = cudf.read_hdf(filename, key=self.uid)\n\n return output_df\n\n def save_cache(self, output_df):\n '''Defines the behavior for how to save the output of a node to\n filesystem cache. Default implementation assumes cudf dataframes.\n\n :param output_df: The output from :meth:`process`. For saving to hdf\n requires that the dataframe(s) have `to_hdf` method.\n '''\n cache_dir = os.getenv('GQUANT_CACHE_DIR', self.cache_dir)\n os.makedirs(cache_dir, exist_ok=True)\n filename = cache_dir + '/' + self.uid + '.hdf5'\n if self._using_ports():\n with pd.HDFStore(filename, mode='w') as hf:\n for oport, odf in output_df.items():\n # check for to_hdf attribute\n if not hasattr(odf, 'to_hdf'):\n raise Exception(\n 'Task \"{}\" port \"{}\" output object is missing '\n '\"to_hdf\" attribute. Cannot save to cache.'\n .format(self.uid, oport))\n\n dtype = '{}'.format(type(odf)).lower()\n if 'dataframe' not in dtype:\n warnings.warn(\n RuntimeWarning,\n 'Task \"{}\" port \"{}\" port type is not a dataframe.'\n ' Attempting to save to hdf with \"to_hdf\" method.'\n .format(self.uid, oport))\n key = '{}/{}'.format(self.uid, oport)\n odf.to_hdf(hf, key, format='table', data_columns=True)\n else:\n output_df.to_hdf(filename, key=self.uid)\n","sub_path":"gquant/dataframe_flow/node.py","file_name":"node.py","file_ext":"py","file_size_in_byte":14126,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"271319683","text":"__author__ = 'rechner'\n\nfrom common.gcd import *\nfrom common.primes import *\n\n\ndef I(n):\n for m in range(n - 2, 0, -1):\n if modinv(m, n) == m:\n return m\n\n\nN = 10000\nU = 0\npr = prime_list(N)\ncoef = [0 for p in pr]\nisprime = prime_array(N)\n\n\ndef g(m, n, i):\n global U, pr, coef\n if m > 1 and m * m % n == 1:\n # print(' ' + str(m))\n U = m\n else:\n while i < len(pr) and m * pr[i] < U:\n if coef[i] == 0:\n g(m * pr[i], n, i)\n i += 1\n\n\ncnt = 0\n\n\ndef f(n, i):\n global N, U, pr, coef, isprime, cnt\n res = 1\n # print(cnt)\n cnt += 1\n if isprime[n] is not True:\n U = n // 2\n g(1, n, 0)\n if U != n // 2:\n res = n - U\n # print(n, res, I(n))\n while i < len(pr) and n * pr[i] < N:\n coef[i] += 1\n res += f(n * pr[i], i)\n coef[i] -= 1\n i += 1\n return res\n\n\n# print(f(1,0)-2)\n\nprint(I(100))\nprint(I(4))\nprint(I(25))\n","sub_path":"pe451/pe451.py","file_name":"pe451.py","file_ext":"py","file_size_in_byte":969,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"339496388","text":"#!/usr/bin/env python\nimport rospy\nimport time\nfrom sensor_msgs.msg import Joy\nfrom geometry_msgs.msg import Twist\n\n# init ros publisher to publish velocity \nvel_pub = rospy.Publisher('cmd_vel', Twist, queue_size=1)\n# init enable moving flag\nenable_mv_flag = False\n\n# func that convert joy msg to velocity\ndef joy_teleop(msg):\n # coeff to control speed\n k_speed = 0.5\n # if press \"X\" enable moving\n if msg.buttons[0] == 1:\n enable_mv_flag = True\n # if press \"O\" disable moving \n if msg.buttons[1] == 1:\n enable_mv_flag = False\n # while \"R1\" button is pressed enable speed boost\n if msg.buttons[7] == 1:\n k_speed = 1\n # if enable mv flag true, convert joy to vel and publish it\n if enable_mv_flag:\n # init cmd_vel msg use Twist type which contain angular and linear vel\n cmd_vel = Twist()\n # convert left stick value to angular vel\n cmd_vel.angular.x = msg.axes[0] * k_speed\n # convert right stick value to linear vel\n cmd_vel.linear.x = msg.axes[3] * k_speed\n # publish cmd_vel \n vel_pub.publish(cmd_vel)\n # else publish 0 vel to cmd_vel\n else:\n cmd_vel = Twist()\n vel_pub.publish(cmd_vel)\n\n# initialization\nif __name__ == '__main__':\n\n\t# setup ros node\n\trospy.init_node('jetbot_joy_teleop')\n # init subscriber to recieve joy msg\n\trospy.Subscriber('joy', Joy, joy_teleop)\n \n\t# start running\n\trospy.spin()\n\n","sub_path":"scripts/jetbot_joystick.py","file_name":"jetbot_joystick.py","file_ext":"py","file_size_in_byte":1442,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"277552430","text":"import numpy as np\r\nimport basic_file_app\r\nimport matplotlib.pyplot as plt\r\nfrom scipy.interpolate import interp1d\r\n\r\n\r\nclass FWHM:\r\n def __init__(self, array, file_name, energy_list):\r\n self.file_name = file_name[:-4]\r\n self.spectrum = array\r\n self.energy_list = energy_list\r\n self.result = np.empty([1, 5])\r\n self.range_for_selection = 0.006\r\n self.all_results = np.zeros([1, 5])\r\n self.offset_const = 10000\r\n print(self.offset_const, 'base line offset')\r\n\r\n def plot_fulls_spectra(self):\r\n plt.figure(3)\r\n plt.plot(self.spectrum[:, 0], self.spectrum[:, 1])\r\n plt.xlabel(\"nm\")\r\n plt.ylabel(\"counts/s\")\r\n plt.legend()\r\n\r\n def offset(self):\r\n plt.figure(4)\r\n plt.plot(self.spectrum[:100,0], self.spectrum[:100,1])\r\n return np.mean(self.spectrum[:20,1])\r\n\r\n def find_max(self, array):\r\n return np.amax(array[:, 1])\r\n\r\n def spectral_selection(self, selection_energy):\r\n index = np.where(self.spectrum[:, 0] <= selection_energy)[0][0]\r\n index_L = np.where(self.spectrum[:, 0] <= selection_energy + self.range_for_selection)[0][0]\r\n index_R = np.where(self.spectrum[:, 0] <= selection_energy - self.range_for_selection)[0][0]\r\n print(index_L, index_R, \"index selected energy: \", selection_energy, )\r\n return self.spectrum[index_L:index_R, :]\r\n\r\n\r\n def substracte_baseline(self):\r\n self.spectrum[:,1] = self.spectrum[:,1] - self.offset_const\r\n return self.spectrum\r\n\r\n def interpolate_spectral_selection(self, selected_energy):\r\n subarray = self.spectral_selection(selected_energy)\r\n #linear interpolation\r\n f = interp1d(subarray[:,0],subarray[:,1])\r\n xnew = np.linspace(subarray[0,0], subarray[-1,0], num=150, endpoint= True)\r\n plt.figure(2)\r\n plt.plot(subarray[:,0],subarray[:,1], '.', xnew, f(xnew), '-')\r\n plt.xlim(1.22,1.2)\r\n plt.ylim(0,1.1E7)\r\n return np.stack((xnew, f(xnew)), axis = 1)\r\n\r\n\r\n\r\n def find_FWHM(self, array, max_counts):\r\n zero_line = 0\r\n half_max = (max_counts - zero_line) / 2\r\n # gives for one peak stepfunction\r\n # width of step function is FWHM\r\n d = np.where(array[:, 1] - half_max >= 0)[0][0]\r\n indexL_upper = d\r\n indexR_lower = np.where(array[indexL_upper:, 1] - half_max <= 0)[0][0] + indexL_upper\r\n indexL_lower = d - 1\r\n indexR_upper = indexR_lower + 1\r\n plt.figure(2)\r\n plt.scatter(array[:, 0], array[:, 1], marker=\".\", s=3, alpha = 0.5)\r\n plt.hlines(y=array[indexL_lower, 1], xmin=array[0, 0], xmax=array[-1, 0], color=\"g\")\r\n plt.hlines(y=array[indexL_upper, 1], xmin=array[0, 0], xmax=array[-1, 0], color=\"r\")\r\n FWHM = array[indexL_lower, 0] - array[indexR_lower, 0]\r\n FWHM_upper = array[indexL_upper, 0] - array[indexR_upper, 0]\r\n return FWHM, FWHM_upper\r\n\r\n\r\n def full_width_half_max_interpolated(self, selection_energy):\r\n self.result[0, 0] = selection_energy\r\n sub_array = self.interpolate_spectral_selection(selection_energy)\r\n self.result[0, 1] = self.find_max(sub_array)\r\n fwhm_low, fwhm_up = self.find_FWHM(sub_array, self.result[0, 1])\r\n self.result[0, 2] = fwhm_low\r\n self.result[0, 3] = fwhm_up\r\n avg = (fwhm_low + fwhm_up) / 2\r\n print(fwhm_up, fwhm_low, 0.5*(fwhm_up+fwhm_low), \"fwhm up, fwhm low, fwhm avg\")\r\n self.result[0, 4] = selection_energy / avg\r\n\r\n return self.result\r\n\r\n def batch_over_energy_list(self):\r\n for x in self.energy_list:\r\n self.all_results = np.concatenate((self.all_results, self.full_width_half_max_interpolated(x)), axis=0)\r\n\r\n self.all_results = self.all_results[1:, :]\r\n plt.figure(1)\r\n plt.scatter(self.all_results[:, 0], self.all_results[:, 4], label=self.file_name[9:14], alpha=0.9, s=10, marker=\"x\")\r\n plt.xlabel(\"nm\")\r\n plt.ylabel(\"Delta lambda/ lambda\")\r\n plt.legend()\r\n print(self.all_results)\r\n return self.all_results\r\n\r\n def prepare_header(self):\r\n # insert header line and change index\r\n header_names = (\r\n ['nm', 'max_counts/s', 'delta lambda FWHM low', 'delta_lambda FWHM up', \"lambda/delta_lambda(avg)\"])\r\n names = (\r\n ['file:' + str(self.file_name), '##########', '########', 'taken fwhm from existing points linear interpolated ',\r\n '......'])\r\n parameter_info = (\r\n ['description:', \"FWHM determination\", \"max_counts/2\",\r\n \"taken at for next point over and under the half-max counts\", 'xxxxx'])\r\n return np.vstack((parameter_info, names, header_names, self.all_results))\r\n\r\n def save_data(self):\r\n result = self.prepare_header()\r\n print('...saving:', self.file_name)\r\n np.savetxt(self.file_name + '_resolution' + \".txt\", result, delimiter=' ',\r\n header='string', comments='',\r\n fmt='%s')\r\n\r\n\r\npath = \"data/A9_Lrot56_105ms_Gonio1460/LT18350/px_shifted_cal/px_cal/\"\r\n\r\n\r\nlambda_list = (1.50, 1.526, 1.226, 1.21, 1.419, 1.675, 1.705, 1.38)\r\n\r\n\r\nfile_list = basic_file_app.get_file_list(path)\r\navg_over_stack = basic_file_app.StackMeanValue(file_list, path, 0, 2, 4)\r\navg_array = avg_over_stack.get_result()\r\n\r\ndef open_file(file_name, path):\r\n spectral = basic_file_app.load_1d_array(path + '/' + file_name, 0, 4)\r\n counts = basic_file_app.load_1d_array(path + '/' + file_name, 2, 4)\r\n return basic_file_app.stack_arrays(spectral, counts, 1)\r\n\r\n\r\nplt.figure(11)\r\nplt.plot(avg_array[:,0], avg_array[:,1], label = \"A9_Lrot56_105ms_Gonio1460LT18350_avg\")\r\nplt.legend()\r\nfor x in file_list:\r\n\r\n file = open_file(x, path)\r\n plt.figure(10)\r\n plt.plot(file[:,0], file[:,1])\r\n plt.xlim(1.4, 1.5)\r\n\r\n\r\ntesting = FWHM(avg_array, \"A9_Lrot56_105ms_Gonio1460LT18350_avg_wo____\", lambda_list)\r\ntesting.substracte_baseline()\r\ntesting.batch_over_energy_list()\r\ntesting.save_data()\r\n\r\n\r\n\r\n#batch\r\n#for x in file_list:\r\n # array = open_file(path, x)\r\n # name = x[:-4]\r\n # Test = FWHM(array, name, lambda_list)\r\n #Test.substracte_baseline()\r\n #Test.batch_over_energy_list()\r\n #Test.save_data()\r\n\r\n\r\n\r\n\r\nplt.figure(1)\r\nplt.savefig(\"FWHM_A9_Lrot56_105ms_Gonio1460LT18350_px_shifted\" + \".png\", bbox_inches=\"tight\", dpi=500)\r\nplt.show()\r\n\r\n","sub_path":"quick_resolution.py","file_name":"quick_resolution.py","file_ext":"py","file_size_in_byte":6397,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"565140608","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Apr 1 16:57:23 2019\n\n@author: lapi7\n\"\"\"\n\nimport xlsxwriter\nb = ['0.0656', '0.0713', '0.077', '0.0827']\nworkbook = xlsxwriter.Workbook('b.xlsx')\nworksheet = workbook.add_worksheet()\n\n\n \n\ncol = 0\n\nfor row, data in enumerate(b):\n worksheet.write_column(row, col, data)\n\nworkbook.close()\n\n\n#ds = pd.DataFrame(b)\n#ds.to_csv(\"b.csv\", encoding=\"utf-8\", index=None)\n#print(\"fin\")","sub_path":"Tarea No.4/practica_py/exportar arreglo.py","file_name":"exportar arreglo.py","file_ext":"py","file_size_in_byte":424,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"358287184","text":"from django.shortcuts import render, redirect\nfrom django.utils.datastructures import MultiValueDictKeyError\nfrom app.models import Product, Order\nfrom .forms import OrderForm, AdminRegisterForm\nfrom django.contrib import messages\nfrom django.utils import timezone\nfrom datetime import datetime\nfrom django.views.generic import View\nfrom django.core.mail import send_mail\n\n# Creating views here\nnow = timezone.now()\n\n\n# currentDT = datetime.datetime.now()\n\n# For clients(choosing products)\ndef add_item_to_order(request):\n hour = int(datetime.strftime(datetime.now(), \"%H\"))\n queryset = Product.objects.all()\n if request.method == \"POST\":\n form = OrderForm(request.POST)\n if form.is_valid():\n try:\n product_uid = form.data['product_uid']\n product_count = int(request.POST[product_uid])\n product = Product.objects.get(slug__iexact=product_uid)\n order = form.save(commit=False)\n order.name_product = product\n order.count = product_count\n order.summary = product_count * product.price\n order.comment = \"\" + order.comment\n order.save()\n except MultiValueDictKeyError:\n return redirect('home')\n\n return render(request, 'app/base.html', {'product_list': queryset})\n else:\n return render(request, 'app/base.html', {'product_list': queryset, 'hour': hour})\n\n\n# For new admins(registration fom)\ndef register(request):\n if request.method == 'POST':\n form = AdminRegisterForm(request.POST)\n if form.is_valid():\n form.save()\n username = form.cleaned_data.get('username')\n messages.success(request, f'Account created for {username}!')\n if request.user.is_authenticated:\n return redirect('/order_list')\n else:\n return redirect('/login')\n else:\n return redirect('/register')\n else:\n if request.user.is_authenticated:\n return redirect('/order_list')\n else:\n form = AdminRegisterForm()\n return render(request, 'registration/register.html', {'form': form})\n\n\n# For admins(the common list of orders)\ndef show_order_list(request):\n if request.user.is_authenticated:\n queryset = Order.objects.all()\n total = 0\n total_count = 0\n for item in queryset:\n total = total + item.summary\n total_count = total_count + item.count\n return render(request, 'app/order_list.html', {'order_list': queryset, 'total': total,\n 'total_count': total_count})\n else:\n return redirect('/register')\n\n\n# For admins(an email sending)\nclass SendFormEmail(View):\n\n def get(self, request):\n if request.user.is_authenticated:\n # Get the form data\n name = request.GET.get('name', None)\n email = request.GET.get('email', None)\n message = request.GET.get('message', None)\n\n # Send Email\n send_mail(\n 'Subject - FoodMenu',\n 'Hello ' + name + ',\\n' + message,\n 'sender@example.com', # Admin\n [\n email,\n ]\n )\n # Redirect to same page after form submit\n messages.success(request, ('Email sent successfully.'))\n return redirect('/email_sending')\n else:\n return redirect('/register')\n\n","sub_path":"app/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3563,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"382038442","text":"import numpy as np\nimport matplotlib.pyplot as plt\nimport sklearn\nimport sklearn.datasets\nimport sklearn.linear_model\nfrom cv_test.planar_utils import plot_decision_boundary, sigmoid, load_planar_dataset, load_extra_datasets\n\n# get_ipython().magic('matplotlib inline')\n\nnp.random.seed(1) # set a seed so that the results are consistent\nX, Y = load_planar_dataset()\nprint(X, Y)\nprint(X.shape, Y.shape)\n\n\n# Visualize the data:\nplt.scatter(X[0, :], X[1, :], c=Y, s=40, cmap=plt.cm.Spectral)\n\nshape_X = X.shape\nshape_Y = Y.shape\nm = Y.shape[1] # training set size\n\n\nprint('The shape of X is: ' + str(shape_X))\nprint('The shape of Y is: ' + str(shape_Y))\nprint('I have m = %d training examples!' % (m))\n\nclf = sklearn.linear_model.LogisticRegressionCV()\nclf.fit(X.T, Y.T)\n\nplot_decision_boundary(lambda x: clf.predict(x), X, Y)\nplt.title(\"Logistic Regression\")\nplt.show()\n# Print accuracy\nLR_predictions = clf.predict(X.T)\nprint('Accuracy of logistic regression: %d ' % float(\n (np.dot(Y, LR_predictions) + np.dot(1 - Y, 1 - LR_predictions)) / float(Y.size) * 100) +\n '% ' + \"(percentage of correctly labelled datapoints)\")\n\n\ndef layer_sizes(X, Y):\n n_x = X.shape[0] # size of input layer\n n_h = 4\n n_y = Y.shape[0] # size of output layer\n print(X.shape)\n return n_x, n_h, n_y\n\n\ndef initialize_parameters(n_x, n_h, n_y):\n np.random.seed(2) # we set up a seed so that your output matches ours although the initialization is random.\n\n ### START CODE HERE ### (≈ 4 lines of code)\n W1 = np.random.randn(n_h, n_x) * 0.01\n b1 = np.zeros(shape=(n_h, 1))\n W2 = np.random.randn(n_y, n_h) * 0.01\n b2 = np.zeros(shape=(n_y, 1))\n\n assert (W1.shape == (n_h, n_x))\n assert (b1.shape == (n_h, 1))\n assert (W2.shape == (n_y, n_h))\n assert (b2.shape == (n_y, 1))\n\n parameters = {\"W1\": W1,\n \"b1\": b1,\n \"W2\": W2,\n \"b2\": b2}\n\n return parameters\n\n\ndef forward_propagation(X, parameters):\n W1 = parameters['W1']\n b1 = parameters['b1']\n W2 = parameters['W2']\n b2 = parameters['b2']\n\n Z1 = np.dot(W1, X) + b1\n A1 = np.tanh(Z1)\n Z2 = np.dot(W2, A1) + b2\n A2 = sigmoid(Z2)\n\n assert (A2.shape == (1, X.shape[1]))\n\n cache = {\"Z1\": Z1,\n \"A1\": A1,\n \"Z2\": Z2,\n \"A2\": A2}\n\n return A2, cache\n\n\ndef compute_cost(A2, Y, parameters):\n m = Y.shape[1] # number of example\n print(A2.shape)\n print(Y.shape)\n cost = np.sum(np.multiply(np.log(A2), Y) + np.multiply((1 - Y), np.log(1 - A2))) * (- 1 / m)\n print(cost)\n\n cost = float(np.squeeze(cost)) # makes sure cost is the dimension we expect.\n print(cost) # E.g., turns [[17]] into 17\n assert(isinstance(cost, float))\n\n return cost\n\n\ndef backward_propagation(parameters, cache, X, Y):\n m = X.shape[1]\n W1 = parameters['W1']\n W2 = parameters['W2']\n A1 = cache['A1']\n A2 = cache['A2']\n\n dZ2 = A2 - Y\n dW2 = (1 / m) * np.dot(dZ2, A1.T)\n db2 = (1 / m) * np.sum(dZ2, axis=1, keepdims=True)\n dZ1 = np.multiply(np.dot(W2.T, dZ2), 1 - np.power(A1, 2))\n dW1 = (1 / m) * np.dot(dZ1, X.T)\n db1 = (1 / m) * np.sum(dZ1, axis=1, keepdims=True)\n\n grads = {\"dW1\": dW1,\n \"db1\": db1,\n \"dW2\": dW2,\n \"db2\": db2}\n\n return grads\n\n\ndef update_parameters(parameters, grads, learning_rate=1.2):\n W1 = parameters[\"W1\"]\n b1 = parameters[\"b1\"]\n W2 = parameters[\"W2\"]\n b2 = parameters[\"b2\"]\n\n dW1 = grads[\"dW1\"]\n db1 = grads[\"db1\"]\n dW2 = grads[\"dW2\"]\n db2 = grads[\"db2\"]\n\n W1 = W1 - learning_rate * dW1\n b1 = b1 - learning_rate * db1\n W2 = W2 - learning_rate * dW2\n b2 = b2 - learning_rate * db2\n\n parameters = {\"W1\": W1,\n \"b1\": b1,\n \"W2\": W2,\n \"b2\": b2}\n\n return parameters\n\n\ndef nn_model(X, Y, n_h, num_iterations=10000, print_cost=False):\n\n np.random.seed(3)\n n_x = layer_sizes(X, Y)[0]\n n_y = layer_sizes(X, Y)[2]\n\n parameters = initialize_parameters(n_x, n_h, n_y)\n\n # Loop (gradient descent)\n\n for i in range(0, num_iterations):\n\n ### START CODE HERE ### (≈ 4 lines of code)\n # Forward propagation. Inputs: \"X, parameters\". Outputs: \"A2, cache\".\n A2, cache = forward_propagation(X, parameters)\n\n # Cost function. Inputs: \"A2, Y, parameters\". Outputs: \"cost\".\n cost = compute_cost(A2, Y, parameters)\n\n # Backpropagation. Inputs: \"parameters, cache, X, Y\". Outputs: \"grads\".\n grads = backward_propagation(parameters, cache, X, Y)\n\n # Gradient descent parameter update. Inputs: \"parameters, grads\". Outputs: \"parameters\".\n parameters = update_parameters(parameters, grads)\n\n ### END CODE HERE ###\n\n # Print the cost every 1000 iterations\n if print_cost and i % 1000 == 0:\n print(\"Cost after iteration %i: %f\" % (i, cost))\n\n return parameters\n\n\ndef predict(parameters, X):\n A2, cache = forward_propagation(X, parameters)\n predictions = np.round(A2)\n\n return predictions\n\n\nparameters = nn_model(X, Y, n_h=4, num_iterations=10000, print_cost=True)\n\n# Plot the decision boundary\nplot_decision_boundary(lambda x: predict(parameters, x.T), X, Y)\nplt.title(\"Decision Boundary for hidden layer size \" + str(4))\nplt.show()\n\npredictions = predict(parameters, X)\nprint('Accuracy: %d' % float((np.dot(Y, predictions.T) + np.dot(1 - Y, 1 - predictions.T)) / float(Y.size) * 100) + '%')\n\nplt.figure(figsize=(16, 32))\nhidden_layer_sizes = [1, 2, 3, 4, 5, 20, 50]\nfor i, n_h in enumerate(hidden_layer_sizes):\n plt.subplot(5, 2, i + 1)\n plt.title('Hidden Layer of size %d' % n_h)\n parameters = nn_model(X, Y, n_h, num_iterations=5000)\n plot_decision_boundary(lambda x: predict(parameters, x.T), X, Y)\n plt.show()\n predictions = predict(parameters, X)\n accuracy = float((np.dot(Y, predictions.T) + np.dot(1 - Y, 1 - predictions.T)) / float(Y.size) * 100)\n print(\"Accuracy for {} hidden units: {} %\".format(n_h, accuracy))\n\nnoisy_circles, noisy_moons, blobs, gaussian_quantiles, no_structure = load_extra_datasets()\n\ndatasets = {\"noisy_circles\": noisy_circles,\n \"noisy_moons\": noisy_moons,\n \"blobs\": blobs,\n \"gaussian_quantiles\": gaussian_quantiles}\n\ndataset = \"noisy_moons\"\n\nX, Y = datasets[dataset]\nX, Y = X.T, Y.reshape(1, Y.shape[0])\n\n# make blobs binary\nif dataset == \"blobs\":\n Y = Y % 2\n\n# Visualize the data\nplt.scatter(X[0, :], X[1, :], c=Y, s=40, cmap=plt.cm.Spectral);\n\n# Build a model with a n_h-dimensional hidden layer\nparameters = nn_model(X, Y, n_h=4, num_iterations=10000, print_cost=True)\n# Plot the decision boundary\nplot_decision_boundary(lambda x: predict(parameters, x.T), X, Y)\nplt.title(\"Decision Boundary for hidden layer size \" + str(4))\nplt.show()\n# Print accuracy\npredictions = predict(parameters, X)\nprint('Accuracy: %d' % float((np.dot(Y, predictions.T) + np.dot(1 - Y, 1 - predictions.T)) / float(Y.size) * 100) + '%')\n","sub_path":"cv_test/Planar_data_classification_with_onehidden_layer_v6c.py","file_name":"Planar_data_classification_with_onehidden_layer_v6c.py","file_ext":"py","file_size_in_byte":6981,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"127931910","text":"from flask import Flask, render_template, flash, redirect, url_for\nimport odoorpc\nfrom forms import RegisterForm\nfrom flask_login import current_user\n\n\napp = Flask(__name__)\napp.config['SECRET_KEY'] = '49b748edf74a4077ec4b7d956b12ce6e'\napp.config['SQLALCHEMY_DATABASE_URI'] = 'postgresql://quocanh:123@localhost/flask-blog'\n\n# Prepare the connection to the server\nodoo = odoorpc.ODOO('localhost', port=8069)\n\n# Check available databases\nprint(odoo.db.list())\n\n# Login\nodoo.login('project', 'admin', 'admin')\n\n\n@app.route(\"/\")\ndef home():\n books = odoo.env['books'].search([])\n book = odoo.execute('books', 'read', books)\n\n category = odoo.env['category'].search([])\n cate = odoo.execute('category', 'read', category)\n\n return render_template(\"home.html\", book=book, cate=cate)\n\n@app.route(\"/detail/\")\ndef book_detail(id):\n category = odoo.env['category'].search([])\n cate = odoo.execute('category', 'read', category)\n\n book = odoo.env['books'].browse(id)\n\n return render_template(\"book_detail.html\", cate=cate, book=book)\n\n\n\n@app.route(\"/contact\")\ndef register():\n form = RegisterForm()\n if form.validate_on_submit():\n flash('You have been login')\n return redirect('home')\n\n return render_template(\"register.html\", form=form, title=\"Register Form \")\n\nif __name__ == '__main__':\n app.run(debug=True)\n","sub_path":"my-website/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1360,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"142776953","text":"'''\r\nCreated on Dec 29, 2017\r\n\r\n@author: Surya\r\n'''\r\n#!/bin/python3\r\n\r\n\r\n\r\ndef solve(n, s, d, m):\r\n # Complete this function\r\n count=0\r\n if(n==1):\r\n x=1\r\n else:\r\n x=n-1\r\n for i in range(0,x):\r\n array=[]\r\n for j in range(i,i+m):\r\n array.append(s[j])\r\n if(j==len(s)-1):\r\n break \r\n \r\n if(sum(array)==d):\r\n count+=1\r\n return count \r\n\r\n\r\nn = int(input().strip())\r\ns = list(map(int, input().strip().split(' ')))\r\nd, m = input().strip().split(' ')\r\nd, m = [int(d), int(m)]\r\n\r\nresult = solve(n, s, d, m)\r\nprint(result)\r\n\r\n","sub_path":"hackerrankalgo_python/BirthdayChocolate.py","file_name":"BirthdayChocolate.py","file_ext":"py","file_size_in_byte":632,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"220642166","text":"from rest_framework import permissions, viewsets\n\nfrom authentication.models import Account\nfrom authentication.permissions import IsAccountOwner\nfrom authentication.serializers import AccountSerializer\n\n\n# Django REST Framework offers a feature called viewsets.\n# The ModelViewSet offers an interface for listing, creating, retrieving,\n# updating and destroying objects of a given model.\nclass AccountViewSet(viewsets.ModelViewSet):\n\t# The 'username' attribute of the Account model is used to lookup accounts\n\tlookup_field = 'username'\n\t#Django uses tbe specified queryset and serializer to perform the viewset actions\n\tqueryset = Account.objects.all()\n\tserializer_class = AccountSerializer\n\n\t# returns True if method called is defined in SAFE_METHODS || is 'POST' || the\n\t# user is authenticated and is an account owner as defined by those methods\n\t# filters users who call update() and delete() to auth's and owners\n\tdef get_permissions(self):\n\t\tif self.request.method in permissions.SAFE_METHODS:\n\t\t\treturn (permissions.AllowAny(),)\n\n\t\tif self.request.method == 'POST':\n\t\t\treturn (permissions.AllowAny(),)\n\n\t\treturn (permissions.IsAuthenticated(), IsAccountOwner(),)\n\n\t# overrides the viewset's create() method because serializer.save() will\n\t# save a user's password a the literal attribute name of 'password'\n\t# which is poor security and creates a login problem\n\tdef create(self, request):\n\t\tserializer = self.serializer_class(data=request.data)\n\n\t\tif serializer.is_valid():\n\t\t\tAccount.objects.create_user(**serializer.validated_data)\n\n\t\t\treturn Response(serializer.validated_data, status=status.HTTP_201_CREATED)\n\n\t\treturn Response({\n\t\t\t'status': 'Bad request',\n\t\t\t'message': 'Account could not be created with received data.'\n\t\t\t}, status=status.HTTP_400_BAD_REQUEST)","sub_path":"server/authentication/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1776,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"556461371","text":"import numpy as np\n\nCAND = 16\nMAP_TABLE = {2**i: i for i in range(1,CAND)}\nMAP_TABLE[0] = 0\n\ndef change_to_onehot(board):\n ret = np.zeros(shape=(4,4,CAND),dtype=float)\n for r in range(4):\n for c in range(4):\n ret[r,c,MAP_TABLE[board[r,c]]] = 1\n return ret\n\n\n","sub_path":"MyCode/onehot.py","file_name":"onehot.py","file_ext":"py","file_size_in_byte":285,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"470090068","text":"#---------------------------------------------------------------------------\n# Copyright 2015 The Open Source Electronic Health Record Alliance\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#---------------------------------------------------------------------------\nfrom selenium import webdriver\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.common.action_chains import ActionChains\nimport argparse\nimport unittest\nimport re\nimport time\nimport selenium_utils as Utils\n\nclass test_menus(unittest.TestCase):\n\n @classmethod\n def tearDownClass(cls):\n global driver\n driver.close()\n\n # def test_09_node(self):\n # # # ********************************************\n # # #TODO: Find a way to click on circle for collapsing of a node\n # # # ********************************************\n # global driver\n # driver.find_element_by_link_text(\"VHA BFF Demo\").click()\n # driver.find_element_by_link_text(\"VistA Menus\").click()\n # nodes = driver.find_elements_by_class_name('node')\n # print len(nodes)\n # # oldSize = len(nodes)\n # # print nodes\n # # print nodes[-1].text\n # # print nodes[0].text\n\n # #time.sleep(30)\n # #for node in nodes:\n\n # ActionChains(driver).move_to_element(nodes[-1].find_element_by_tag_name(\"circle\")).double_click(nodes[-1]).perform()\n # time.sleep(5)\n # nodes = driver.find_elements_by_class_name('node')\n # print len(nodes)\n #print \"*********************\"\n #print oldSize\n #print newSize\n #print \"*********************\"\n #self.assertTrue(newSize != oldSize)\n\n def test_01_reset(self):\n global driver\n oldSize = len(driver.find_elements_by_class_name('node'))\n button = driver.find_element_by_xpath(\"//button[contains(@onclick,'_collapseAllNode')]\")\n button.click()\n time.sleep(1)\n button = driver.find_element_by_xpath(\"//button[contains(@onclick,'_resetAllNode')]\")\n button.click()\n newSize = len(driver.find_elements_by_class_name('node'))\n self.assertTrue(oldSize == newSize)\n\n def test_collapse(self):\n global driver\n oldSize = len(driver.find_elements_by_class_name('node'))\n button = driver.find_element_by_xpath(\"//button[contains(@onclick,'_collapseAllNode')]\")\n button.click()\n time.sleep(1)\n newSize = len(driver.find_elements_by_class_name('node'))\n self.assertTrue(oldSize > newSize)\n\n def test_04_autocomplete(self):\n target_menu_text = \"Core Applications\"\n global driver\n ac_form = driver.find_element_by_id(\"autocomplete\")\n ac_form.clear()\n ac_form.send_keys(target_menu_text)\n time.sleep(1)\n ac_list = driver.find_elements_by_class_name('ui-menu-item')\n for option in ac_list:\n ac_option = option.find_element_by_tag_name('a')\n if(re.search(target_menu_text,ac_option.text)):\n ac_option.click()\n time.sleep(1)\n node_list = driver.find_elements_by_class_name('node')\n self.assertTrue(node_list[-1].text == target_menu_text)\n\n def test_05_menuAutoComplete(self):\n target_menu_text = \"Monitor Taskman\"\n global driver\n ac_form = driver.find_element_by_id(\"option_autocomplete\")\n ac_form.clear()\n ac_form.send_keys(target_menu_text)\n time.sleep(1)\n ac_list = driver.find_elements_by_class_name('ui-menu-item')\n for option in ac_list:\n ac_option = option.find_element_by_tag_name('a')\n if(re.search(target_menu_text,ac_option.text)):\n ac_option.click()\n time.sleep(1)\n # Now being to compare images to match paths\n driver.save_screenshot(\"path_image_pass_new.png\")\n self.assertTrue(Utils.compareImg(\"path_image_pass\"))\n\n def test_06_menuAutoCompleteFail(self):\n target_menu_text = \"Problem Device report\"\n global driver\n ac_form = driver.find_element_by_id(\"option_autocomplete\")\n ac_form.clear()\n ac_form.send_keys(target_menu_text)\n time.sleep(1)\n ac_list = driver.find_elements_by_class_name('ui-menu-item')\n for option in ac_list:\n ac_option = option.find_element_by_tag_name('a')\n if(re.search(target_menu_text,ac_option.text)):\n ac_option.click()\n time.sleep(1)\n # Now being to compare images to match paths\n driver.save_screenshot(\"path_image_fail_new.png\")\n self.assertFalse(Utils.compareImg(\"path_image_fail\"))\n\n def test_07_menuAutoCompleteFail2(self):\n target_menu_text = \"Process Insurance Buffer\"\n global driver\n ac_form = driver.find_element_by_id(\"option_autocomplete\")\n ac_form.clear()\n ac_form.send_keys(target_menu_text)\n time.sleep(1)\n ac_list = driver.find_elements_by_class_name('ui-menu-item')\n for option in ac_list:\n ac_option = option.find_element_by_tag_name('a')\n if(re.search(target_menu_text,ac_option.text)):\n ac_option.click()\n time.sleep(1)\n # Now being to compare images to match paths\n driver.save_screenshot(\"path_image_fail2_new.png\")\n self.assertFalse(Utils.compareImg(\"path_image_fail2\"))\n\n\n def test_03_legend(self):\n color_options = [\"#E0E0E0\",'']\n global driver\n legend_list = driver.find_elements_by_class_name('legend')\n for item in legend_list[1:]:\n item.click()\n color_options[1]=item.find_element_by_tag_name('text').get_attribute(\"fill\")\n node_list = driver.find_elements_by_class_name('node')\n for node in node_list:\n node_fill = node.find_element_by_tag_name('text').get_attribute(\"fill\")\n self.assertTrue(node_fill in color_options )\n time.sleep(1)\n\nif __name__ == '__main__':\n parser =argparse.ArgumentParser(description=\"\")\n parser.add_argument(\"-r\",dest = 'webroot', required=True, help=\"Web root of the ViViaN(TM) instance to test. eg. http://code.osehra.org/vivian/\")\n result = vars(parser.parse_args())\n driver = webdriver.Firefox()\n driver.get(result['webroot'] + \"/vista_menus.php\")\n suite = unittest.TestLoader().loadTestsFromTestCase(test_menus)\n unittest.TextTestRunner(verbosity=2).run(suite)","sub_path":"Visual/test/test_menus.py","file_name":"test_menus.py","file_ext":"py","file_size_in_byte":6393,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"488297209","text":"# | Copyright 2012-2016 Karlsruhe Institute of Technology\n# |\n# | Licensed under the Apache License, Version 2.0 (the \"License\");\n# | you may not use this file except in compliance with the License.\n# | You may obtain a copy of the License at\n# |\n# | http://www.apache.org/licenses/LICENSE-2.0\n# |\n# | Unless required by applicable law or agreed to in writing, software\n# | distributed under the License is distributed on an \"AS IS\" BASIS,\n# | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# | See the License for the specific language governing permissions and\n# | limitations under the License.\n\nfrom grid_control.parameters.pfactory_base import UserParameterFactory\nfrom grid_control.parameters.psource_base import ParameterError, ParameterSource\nfrom python_compat import ifilter, sorted\n\n# Parameter factory which evaluates a parameter module string\nclass ModularParameterFactory(UserParameterFactory):\n\talias = ['modular']\n\n\tdef _getUserSource(self, pExpr):\n\t\t# Wrap psource factory functions\n\t\tdef createWrapper(clsName):\n\t\t\tdef wrapper(*args):\n\t\t\t\tparameterClass = ParameterSource.getClass(clsName)\n\t\t\t\ttry:\n\t\t\t\t\treturn parameterClass.create(self._paramConfig, self._repository, *args)\n\t\t\t\texcept Exception:\n\t\t\t\t\traise ParameterError('Error while creating %r with arguments %r' % (parameterClass.__name__, args))\n\t\t\treturn wrapper\n\t\tuserFun = {}\n\t\tfor clsInfo in ParameterSource.getClassList():\n\t\t\tfor clsName in ifilter(lambda name: name != 'depth', clsInfo.keys()):\n\t\t\t\tuserFun[clsName] = createWrapper(clsName)\n\t\ttry:\n\t\t\treturn eval(pExpr, dict(userFun)) # pylint:disable=eval-used\n\t\texcept Exception:\n\t\t\tself._log.warning('Available functions: %s', sorted(userFun.keys()))\n\t\t\traise\n","sub_path":"packages/grid_control/parameters/pfactory_modular.py","file_name":"pfactory_modular.py","file_ext":"py","file_size_in_byte":1725,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"209478590","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*- \n#\n# Licensed under the GNU General Public License, version 3.\n# See the file http://www.gnu.org/licenses/gpl.txt\n\nfrom pisi.actionsapi import autotools\nfrom pisi.actionsapi import pisitools\nfrom pisi.actionsapi import shelltools\nfrom pisi.actionsapi import get\n\nWorkDir = 'tuxcards'\n\ndef setup():\n pisitools.dosed(\"tuxcards.pro\", \"/usr/local/doc/tuxcards\", \"/usr/share/tuxcards\")\n pisitools.dosed(\"tuxcards.pro\", \"/usr/local\", \"/usr\")\n pisitools.dosed(\"src/CTuxCardsConfiguration.cpp\", \"/usr/local/doc/tuxcards\", \"/usr/share/tuxcards\")\n pisitools.dosed(\"src/gui/dialogs/configurationDialog/IConfigurationDialog.ui\", \"/usr/local/bin\", \"/usr/bin\")\n shelltools.system(\"/usr/qt/4/bin/qmake tuxcards.pro\")\n\ndef build():\n autotools.make()\n\ndef install():\n pisitools.dodoc(\"COPYING\", \"AUTHORS\")\n pisitools.insinto(\"/usr/share/pixmaps\", \"src/icons/attic/lo32-app-tuxcards.xpm\", \"tuxcards.xpm\")\n\n pisitools.dobin(\"tuxcards\")\n","sub_path":"corporate2/stable/office/misc/tuxcards/actions.py","file_name":"actions.py","file_ext":"py","file_size_in_byte":986,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"95695425","text":"#Kelsey Nguyen\n#CPE 202 Section 7\n#Project 1\n\n#int (number), int (base) --> str\n#Recursive function that returns a string representing num in the base b\ndef convert(num, b):\n#Step 1: Make string variable (digits, in this case) that allows user to index into a table of characters to support bases greater than 10\n#Step 2: Base condition - if num is less than b, convert single digit number to a string using a lookup (digits) & append to list\n #Step 3: Concatenate number in list to a string and return the concatenated string\n#Step 4: Else, let x be equal to the recursive call (convert function) + the string representation of the reaminder\n #Step 5: Append x to list\n #Step 6: Concatenate numbers in list to a string and return the concatenated string\n\n digits = \"0123456789ABCDEF\" #string variable holding a sequence of characters to represent digits past 9\n recur_lst = [] #recur_lst represents an empty list\n remainder = num%b #remainder variable represents the remainder num%b\n if num < b: #base case\n recur_lst.append(digits[num])\n return \"\".join(recur_lst)\n else:\n x = convert(num // b, b) + digits[remainder]\n recur_lst.append(x)\n return \"\".join(recur_lst)\n\n\n","sub_path":"Project1/base_convert.py","file_name":"base_convert.py","file_ext":"py","file_size_in_byte":1250,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"538849215","text":"# Realizar un programa que imprima 25 términos de la serie 11 - 22 - 33 - 44, etc. \n#(No se ingresan valores por teclado)\n\ndef while_exercise4():\n i = 0\n j = 11\n while (i < 25):\n print(f'{j}', end =' - ')\n j += 11\n i += 1\n\nwhile_exercise4()\n ","sub_path":"week3/while4.py","file_name":"while4.py","file_ext":"py","file_size_in_byte":276,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"328139599","text":"import quicksortmod\nfrom math import atan2\nimport math\n\nclass Point:\n\tdef __init__(self, vx=0, vy=0):\n\t\tself.x=vx\n\t\tself.y=vy\n\ndef location(a,b,p):#determina en que posicion se encuentra p respecto al segmento ab\n\tcp1 =(b.x - a.x)*(p.y-a.y)-(b.y-a.y)*(p.x-a.x)\n\tif cp1 > 0:return 1 #esta a la izquierda\n\telse: return -1#esta a la derecha\n\ndef dist1(a,b,c):#mide distancia entre el segmento ab y el punto c\n\tabx = b.x-a.x\n\taby = b.y-a.y\n\tnum = abx*(a.y-c.y)-aby*(a.x-c.x)\n\tif num<0:\n\t\tnum = -num\n\treturn num\n\ndef qhull(a,b,set,hull):#conquistar\n\tif len(set)==0:return\n\tif len(set)==1 :\n\t\tp = set[0]\n\t\tset.remove(p)\n\t\thull.append(p)\n\t\treturn\n\tdst = -1\n\tptolejano = -1\n\tfor i in range(len(set)):#encuentra el punto con mayor distancia respecto ab\n\t\tp = set[i]\n\t\tdistance = dist1(a,b,p)\n\t\tif distance>dst:\n\t\t\tdst = distance\n\t\t\tptolejano = i\n\tp = set[ptolejano]\n\tset.remove(p)\n\thull.append(p)\n\tleftap = []\n\tif len(set)==0:return\n\tfor j in range(len(set)):#inserta todo lo que este a la izquierda de el segmento ap para volver a respetir el proceso\n\t\tm = set[j]\n\t\tif location(a,p,m)==1:\n\t\t\tleftap.append(m)\n\tleftpb = []\n\tif len(set)==0:return\n\tfor k in range(len(set)):#inserta todo lo que este a la izquierda de pb para respetir todo\n\t\tm = set[k]\n\t\tif location(p,b,m) == 1:\n\t\t\tleftpb.append(m)\n\tqhull(a,p,leftap,hull)\n\tqhull(p,b,leftpb,hull)\n\ndef quickhull(points):#dividir\n\tconvexhull = []\n\tmin = 0\n\tmax = 0\n\tminx = Point(points[0].x,points[0].y)\n\tmaxx = Point(points[0].x,points[0].y)\n\tfor i in range(len(points)):#encuentra los puntos extremos\n\t\tif points[i].x<=minx.x:\n\t\t\tif points[i].x == minx.x:\n\t\t\t\tif points[i].y=maxx.x:\n\t\t\tif points[i].x == maxx.x :\n\t\t\t\tif points[i].y> (i % 16)) & 1)\n if len(out_text) % 128 != 0:\n for j in range(128 - len(out_text) % 128):\n out_text.append(0)\n return out_text\n\n\ndef bit2uni(in_text, length): # 二进制转换为unicode\n out_text = []\n temp = 0\n for i in range(length):\n temp = temp | (int(in_text[i]) << (i % 16))\n if i % 16 == 15:\n out_text.append(temp)\n temp = 0\n return out_text\n\n\ndef byte2bit(inchar,length):\n outbit=[]\n for i in range(length*8):\n outbit.append((inchar[int(i/8)]>>(i%8))&1)#一次左移一bit\n return outbit\n\n\ndef uni2str(in_text, length): # unicode转换为字符串\n out_text = \"\"\n for i in range(length):\n out_text = out_text + chr(in_text[i])\n return out_text\n\n\ndef str28str(in_text): # key转换为8字节\n s = '0123456789ABCDEFGHIJKLMNOPQRSTUV'\n d = ''\n h = in_text.encode('utf-8')\n a = hashlib.md5(h).hexdigest()\n for f in range(8):\n g = ord(a[f])\n d += s[(g ^ ord(a[f + 8])) - g & 0x1F]\n\n return d;\n\n\ndef SChange(in_32): # 输入32位bit list\n sout = []\n for i in range(4):\n s1_1 = in_32[4 * i:4 * i + 3]\n s1_2 = in_32[4 * i + 4:4 * i + 7]\n x = '0b'\n y = '0b'\n for j in s1_1:\n x += str(j)\n for j in s1_2:\n y += str(j)\n z = str(bin(s[int(x, 2)][int(y, 2)]))[2:]\n lent = len(z)\n if lent < 8:\n for j in range(8 - lent):\n z = '0' + z\n sout.append(z)\n sout_end = ''\n for i in sout:\n sout_end += i\n return sout_end\n\n\ndef leftMove(in_text, bit): # 输入32位bit string 和 移的位数\n output = in_text[bit:] + in_text[:bit]\n return output\n\n\ndef LChange(in_32): # 输入32位bit string\n c = int(in_32, 2) ^ int(leftMove(in_32, 2), 2) ^ int(leftMove(in_32, 10), 2) ^ int(leftMove(in_32, 18), 2) ^ int(\n leftMove(in_32, 24), 2)\n b = str(bin(c))[2:]\n lent = len(b)\n if lent < 32:\n for j in range(32 - lent):\n b = '0' + b\n return b\n\n\ndef _LChange(in_32):\n c = int(in_32, 2) ^ int(leftMove(in_32, 13), 2) ^ int(leftMove(in_32, 23), 2)\n b = str(bin(c))[2:]\n lent = len(b)\n if lent < 32:\n for j in range(32 - lent):\n b = '0' + b\n return b\n\n\ndef TChange(in_32): # 输入数字,输出int\n bit = (32 - len(str(bin(in_32))[2:-1])) * '0' + str(bin(in_32))[2:-1]\n sout = SChange(bit)\n lout = LChange(sout)\n lout = int('0b' + lout, 2)\n return lout\n\n\ndef _TChange(in_32): # 输入数字 输出int\n sout = SChange(in_32)\n lout = _LChange(sout)\n lout = int('0b' + lout, 2)\n return lout\n\n\ndef dealKey(in_key): # 输入128位list 输出 32*32 list\n RoundKey = []\n SK0b = '0b'\n SK1b = '0b'\n SK2b = '0b'\n SK3b = '0b'\n for i in range(32):\n SK0b += str(in_key[i])\n SK1b += str(in_key[32 + i])\n SK2b += str(in_key[64 + i])\n SK3b += str(in_key[96 + i])\n SK0 = int(SK0b, 2)\n SK1 = int(SK1b, 2)\n SK2 = int(SK2b, 2)\n SK3 = int(SK3b, 2)\n\n K0 = SK0 ^ FK[0]\n K1 = SK1 ^ FK[1]\n K2 = SK2 ^ FK[2]\n K3 = SK3 ^ FK[3]\n\n K = [K0, K1, K2, K3]\n\n for i in range(32):\n a = K[i + 1] ^ K[i + 2] ^ K[i + 3] ^ CK[i]\n b = str(bin(a))[2:]\n\n lent = len(b)\n if lent < 32:\n for j in range(32 - lent):\n b = '0' + b\n c = []\n for j in b:\n c.append(j)\n\n K.append(K[i] ^ _TChange(c))\n for j in range(4, 36):\n RoundKey.append(K[j])\n\n return RoundKey # int list\n\n\ndef Encode(in_text, inkey, ifen): # 输入128位二进制list和string key,分组数量\n X1b = '0b'\n X2b = '0b'\n X3b = '0b'\n X4b = '0b'\n\n termNum = len(in_text)\n\n key = ''\n for i in inkey:\n key += i\n\n dKey = str28str(key)\n key = str2uni(dKey, len(dKey))\n dKey = uni2bit(key, len(key))\n\n if ifen:\n roundKey = dealKey(dKey)\n else:\n roundKey = dealKey(dKey)\n roundKey.reverse()\n\n C = []\n\n for k in range(termNum):\n c = []\n X = []\n X1b = ''\n X2b = ''\n X3b = ''\n X4b = ''\n for i in range(32):\n X1b += str(in_text[k][i])\n X2b += str(in_text[k][32 + i])\n X3b += str(in_text[k][64 + i])\n X4b += str(in_text[k][96 + i])\n\n X = [int(X1b, 2), int(X2b, 2), int(X3b, 2), int(X4b, 2)]\n for i in range(0, 32):\n X.append(X[i] ^ TChange(roundKey[i] ^ X[i + 1] ^ X[i + 2] ^ X[i + 3]))\n for i in range(32, 36):\n a = '0' * (32 - len(str(bin(X[i]))[2:])) + str(bin(X[i]))[2:]\n\n c.append(a)\n\n c.reverse()\n\n for i in c:\n for j in i:\n C.append(j)\n return C # 输出二进制list\n\n\ndef NMDealIn(in_text):\n str = str2uni(in_text, len(in_text))\n bit = uni2bit(str, len(str))\n termNum = len(bit) // 128\n out = []\n for i in range(termNum):\n a = bit[i * 128:128 * (i + 1)]\n out.append(a)\n\n return out\n\n\ndef NMDealOut(in_text):\n uni = bit2uni(in_text, len(in_text))\n str = uni2str(uni, len(uni))\n\n return str\n\n\ndef FLEnDealIn(fileName):\n fl = open(fileName, 'rb')\n byte = fl.read()\n\n b64 = base64.b64encode(byte)\n string = b64.decode('utf-8')\n print(string)\n uni = str2uni(string, len(string))\n bit = uni2bit(uni, len(uni))\n print(bit)\n termNum = len(bit) // 128\n out = []\n for i in range(termNum):\n a = bit[i * 128:128 * (i + 1)]\n out.append(a)\n return out\n\n\ndef FLEnDealOut(saveName, Cypher):\n fl = open(saveName, 'wb')\n text = bit2asc(Cypher, len(Cypher))\n out = ''\n for i in text:\n out += chr(i)\n cout = bytes(out, encoding=\"utf8\")\n fl.write(cout)\n\n fl.close()\n return 0\n\n\ndef FLDeDealIn(fileName):\n fl = open(fileName, 'rb')\n byte = fl.read()\n string = bytes.decode(byte)\n tup = []\n for i in string:\n a = ord(i)\n tup.append(a)\n # print(tup)\n bit = byte2bit(tup, len(tup))\n termNum = len(bit) // 128\n out = []\n for i in range(termNum):\n a = bit[i * 128:128 * (i + 1)]\n out.append(a)\n\n return out\n\n\ndef FLDeDealOut(saveName, Cypher):\n uni = bit2uni(Cypher, len(Cypher))\n stri = uni2str(uni, len(uni))\n byte = base64.b64decode(stri)\n fl = open(saveName, 'wb')\n fl.write(byte)\n fl.close()\n return 0\n\n\ndef NMEN(in_text, key):\n message = NMDealIn(in_text)\n cypher = Encode(message, key, 1)\n\n out = NMDealOut(cypher)\n return out\n\n\ndef NMDE(in_text, key):\n message = NMDealIn(in_text)\n\n cypher = Encode(message, key, 0)\n\n out = NMDealOut(cypher)\n return out\n\n\ndef FLEN(fileName, saveName, key):\n bit = FLEnDealIn(fileName)\n cypher = Encode(bit, key, 1)\n FLEnDealOut(saveName, cypher)\n return 0\n\n\ndef FLDE(fileName, saveName, key):\n print(fileName)\n bit = FLDeDealIn(fileName)\n cypher = Encode(bit, key, 0)\n print(cypher)\n FLDeDealOut(saveName, cypher)\n return 0\n","sub_path":"extend/EN.py","file_name":"EN.py","file_ext":"py","file_size_in_byte":9956,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"151869866","text":"from django.urls import path\nfrom . import views\n\napp_name = 'imom'\nurlpatterns = [\n path('home', views.Home.as_view(), name='home'),\n path('transcript/', views.transcript, name='transcript'),\n path('summary/', views.summary, name='summary'),\n path('delete/', views.delete, name='delete'),\n path('dwnld_summary/', views.download_summary, name='dwnld_summary'),\n path('dwnld_transcript/', views.download_transcript, name='dwnld_transcript'),\n]","sub_path":"imom/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":504,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"219112117","text":"\"\"\"\r\n@author: Aus\r\n@file: onnx_test.py\r\n@time: 2021/3/28 15:31\r\n\"\"\"\r\nfrom io import BytesIO\r\nimport onnxruntime\r\nimport numpy as np\r\nfrom PIL import Image\r\nimport argparse\r\nimport cv2\r\nimport yaml\r\nimport lib.config.alphabets as alphabets\r\nfrom easydict import EasyDict as edict\r\nfrom torch.autograd import Variable\r\nimport torch\r\nimport lib.utils.utils as utils\r\ndef parse_arg():\r\n parser = argparse.ArgumentParser(description=\"demo\")\r\n\r\n parser.add_argument('--cfg', help='experiment configuration filename', type=str, default='lib/config/360CC_config.yaml')\r\n parser.add_argument('--image_path', type=str, default='img/7ca442da0d6ccdb2603fff36e98fe7db.jpg', help='the path to your image')\r\n parser.add_argument('--checkpoint', type=str, default='output/360CC/crnn/2021-06-08-14-21/checkpoints\\checkpoint_97_acc_1.0000.pth',\r\n help='the path to your checkpoints')\r\n\r\n args = parser.parse_args()\r\n\r\n with open(args.cfg, 'r') as f:\r\n config = yaml.load(f,Loader=yaml.FullLoader)\r\n config = edict(config)\r\n\r\n config.DATASET.ALPHABETS = alphabets.alphabet\r\n config.MODEL.NUM_CLASSES = len(config.DATASET.ALPHABETS)\r\n\r\n return config\r\nclass ONNXModel(object):\r\n def __init__(self, onnx_path):\r\n \"\"\"\r\n :param onnx_path:\r\n \"\"\"\r\n self.onnx_session = onnxruntime.InferenceSession(onnx_path)\r\n self.input_name = self.get_input_name(self.onnx_session)\r\n self.output_name = self.get_output_name(self.onnx_session)\r\n # print(\"input_name:{}\".format(self.input_name))\r\n # print(\"output_name:{}\".format(self.output_name))\r\n\r\n def get_output_name(self, onnx_session):\r\n \"\"\"\r\n output_name = onnx_session.get_outputs()[0].name\r\n :param onnx_session:\r\n :return:\r\n \"\"\"\r\n output_name = []\r\n for node in onnx_session.get_outputs():\r\n output_name.append(node.name)\r\n return output_name\r\n\r\n def get_input_name(self, onnx_session):\r\n \"\"\"\r\n input_name = onnx_session.get_inputs()[0].name\r\n :param onnx_session:\r\n :return:\r\n \"\"\"\r\n input_name = []\r\n for node in onnx_session.get_inputs():\r\n input_name.append(node.name)\r\n return input_name\r\n\r\n def get_input_feed(self, input_name, image_numpy):\r\n \"\"\"\r\n input_feed={self.input_name: image_numpy}\r\n :param input_name:\r\n :param image_numpy:\r\n :return:\r\n \"\"\"\r\n input_feed = {}\r\n for name in input_name:\r\n input_feed[name] = image_numpy\r\n return input_feed\r\n\r\n def to_numpy(self, file, shape, gray=False):\r\n if isinstance(file, np.ndarray):\r\n img = Image.fromarray(file)\r\n elif isinstance(file, bytes):\r\n img = Image.open(BytesIO(file))\r\n pass\r\n else:\r\n img = Image.open(file)\r\n\r\n widht, hight = shape\r\n # 改变大小 并保证其不失真\r\n img = img.convert('RGB')\r\n if gray:\r\n img = img.convert('L')\r\n img = img.resize((widht, hight), Image.ANTIALIAS)\r\n\r\n # 转换成矩阵\r\n image_numpy = np.array(img) # (widht, hight, 3)\r\n if gray:\r\n image_numpy = np.expand_dims(image_numpy,0)\r\n image_numpy = image_numpy.transpose(0, 1, 2)\r\n else:\r\n image_numpy = image_numpy.transpose(2,0,1) # 转置 (3, widht, hight)\r\n image_numpy = np.expand_dims(image_numpy,0)\r\n # 数据归一化\r\n image_numpy = image_numpy.astype(np.float32) / 255.0\r\n return image_numpy\r\n\r\n\r\n\r\n\r\nclass CRNN(ONNXModel):\r\n def __init__(self, onnx_path=\"model_onnx.onnx\", char_dict=\"lib/dataset/txt/char_std_5990.txt\"):\r\n super(CRNN, self).__init__(onnx_path)\r\n #with open(char_dict, 'rb') as file:\r\n #char_dict = {num: char.strip().decode('gbk', 'ignore') for num, char in enumerate(file.readlines())}\r\n\r\n with open(char_dict, 'r', encoding='utf-8') as f:\r\n data = f.read()\r\n self.characters = data.split('\\n')\r\n\r\n\r\n def decect(self, img):\r\n config=parse_arg()\r\n h, w = img.shape\r\n # fisrt step: resize the height and width of image to (32, x)\r\n img = cv2.resize(img, (0, 0), fx=config.MODEL.IMAGE_SIZE.OW / w , fy=config.MODEL.IMAGE_SIZE.H / h,\r\n interpolation=cv2.INTER_CUBIC)\r\n # second step: keep the ratio of image's text same with training\r\n h, w = img.shape\r\n w_cur = int(img.shape[1] / (config.MODEL.IMAGE_SIZE.OW / config.MODEL.IMAGE_SIZE.W))\r\n img = cv2.resize(img, (0, 0), fx=w_cur / w, fy=1.0, interpolation=cv2.INTER_CUBIC)\r\n img = np.reshape(img, (config.MODEL.IMAGE_SIZE.H, w_cur, 1))\r\n # normalize\r\n img = img.astype(np.float32)\r\n img = (img / 255. - config.DATASET.MEAN) / config.DATASET.STD\r\n img = img.transpose([2, 0, 1])\r\n image_numpy = np.expand_dims(img, 0)\r\n input_feed = self.get_input_feed(self.input_name, image_numpy)\r\n out = self.onnx_session.run(self.output_name, input_feed=input_feed)[0]\r\n preds=torch.from_numpy(out)\r\n _, preds = preds.max(2)\r\n preds = preds.transpose(1, 0).contiguous().view(-1)\r\n preds_size = Variable(torch.IntTensor([preds.size(0)]))\r\n converter = utils.strLabelConverter(config.DATASET.ALPHABETS)\r\n sim_pred = converter.decode(preds.data, preds_size.data, raw=False)\r\n #print(sim_pred)\r\n return sim_pred\r\n\r\n\r\nif __name__ == '__main__':\r\n import time\r\n crnn_model_path=\"crnn.onnx\"\r\n file = \"000ae60d6d5e9cc885f67164b0bbbd22.jpg\"\r\n rnet2 = CRNN(crnn_model_path)\r\n s = time.time()\r\n img = cv2.imread(file)\r\n img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\r\n out = rnet2.decect(img)\r\n print(time.time() -s)\r\n","sub_path":"onnx_test.py","file_name":"onnx_test.py","file_ext":"py","file_size_in_byte":5861,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"276383149","text":"# coding: utf-8\n\n\"\"\"\n LiveAgent API\n\n This page contains complete API documentation for LiveAgent software. To display additional info and examples for specific API method, just click on the method name in the list below.

To be able to make API requests you need to generate an API key in your admin panel first. [See this article for detailed info.](https://support.liveagent.com/741982-API-key)

Additional info about more advanced agent, contact or ticket API filters can be found [in this article](https://support.liveagent.com/513528-APIv3-advanced-filter-examples).

If you have any question or doubts regarding this API, please do not hesitate to contact our support team. # noqa: E501\n\n OpenAPI spec version: 3.0.0\n Contact: support@qualityunit.com\n Generated by: https://github.com/swagger-api/swagger-codegen.git\n\"\"\"\n\n\nimport pprint\nimport re # noqa: F401\n\nimport six\n\n\nclass TicketInformation(object):\n \"\"\"NOTE: This class is auto generated by the swagger code generator program.\n\n Do not edit the class manually.\n \"\"\"\n\n \"\"\"\n Attributes:\n swagger_types (dict): The key is attribute name\n and the value is attribute type.\n attribute_map (dict): The key is attribute name\n and the value is json key in definition.\n \"\"\"\n swagger_types = {\n 'id': 'str',\n 'ownerid': 'str',\n 'owner_contactid': 'str',\n 'departmentid': 'str',\n 'agentid': 'str',\n 'status': 'str',\n 'tags': 'str',\n 'code': 'str',\n 'channel_type': 'str',\n 'date_created': 'str',\n 'public_access_urlcode': 'str',\n 'subject': 'str',\n 'custom_fields': 'list[CustomFields]'\n }\n\n attribute_map = {\n 'id': 'id',\n 'ownerid': 'ownerid',\n 'owner_contactid': 'owner_contactid',\n 'departmentid': 'departmentid',\n 'agentid': 'agentid',\n 'status': 'status',\n 'tags': 'tags',\n 'code': 'code',\n 'channel_type': 'channel_type',\n 'date_created': 'date_created',\n 'public_access_urlcode': 'public_access_urlcode',\n 'subject': 'subject',\n 'custom_fields': 'custom_fields'\n }\n\n def __init__(self, id=None, ownerid=None, owner_contactid=None, departmentid=None, agentid=None, status=None, tags=None, code=None, channel_type=None, date_created=None, public_access_urlcode=None, subject=None, custom_fields=None): # noqa: E501\n \"\"\"TicketInformation - a model defined in Swagger\"\"\" # noqa: E501\n\n self._id = None\n self._ownerid = None\n self._owner_contactid = None\n self._departmentid = None\n self._agentid = None\n self._status = None\n self._tags = None\n self._code = None\n self._channel_type = None\n self._date_created = None\n self._public_access_urlcode = None\n self._subject = None\n self._custom_fields = None\n self.discriminator = None\n\n if id is not None:\n self.id = id\n if ownerid is not None:\n self.ownerid = ownerid\n if owner_contactid is not None:\n self.owner_contactid = owner_contactid\n if departmentid is not None:\n self.departmentid = departmentid\n if agentid is not None:\n self.agentid = agentid\n if status is not None:\n self.status = status\n if tags is not None:\n self.tags = tags\n if code is not None:\n self.code = code\n if channel_type is not None:\n self.channel_type = channel_type\n if date_created is not None:\n self.date_created = date_created\n if public_access_urlcode is not None:\n self.public_access_urlcode = public_access_urlcode\n if subject is not None:\n self.subject = subject\n if custom_fields is not None:\n self.custom_fields = custom_fields\n\n @property\n def id(self):\n \"\"\"Gets the id of this TicketInformation. # noqa: E501\n\n\n :return: The id of this TicketInformation. # noqa: E501\n :rtype: str\n \"\"\"\n return self._id\n\n @id.setter\n def id(self, id):\n \"\"\"Sets the id of this TicketInformation.\n\n\n :param id: The id of this TicketInformation. # noqa: E501\n :type: str\n \"\"\"\n\n self._id = id\n\n @property\n def ownerid(self):\n \"\"\"Gets the ownerid of this TicketInformation. # noqa: E501\n\n\n :return: The ownerid of this TicketInformation. # noqa: E501\n :rtype: str\n \"\"\"\n return self._ownerid\n\n @ownerid.setter\n def ownerid(self, ownerid):\n \"\"\"Sets the ownerid of this TicketInformation.\n\n\n :param ownerid: The ownerid of this TicketInformation. # noqa: E501\n :type: str\n \"\"\"\n\n self._ownerid = ownerid\n\n @property\n def owner_contactid(self):\n \"\"\"Gets the owner_contactid of this TicketInformation. # noqa: E501\n\n\n :return: The owner_contactid of this TicketInformation. # noqa: E501\n :rtype: str\n \"\"\"\n return self._owner_contactid\n\n @owner_contactid.setter\n def owner_contactid(self, owner_contactid):\n \"\"\"Sets the owner_contactid of this TicketInformation.\n\n\n :param owner_contactid: The owner_contactid of this TicketInformation. # noqa: E501\n :type: str\n \"\"\"\n\n self._owner_contactid = owner_contactid\n\n @property\n def departmentid(self):\n \"\"\"Gets the departmentid of this TicketInformation. # noqa: E501\n\n\n :return: The departmentid of this TicketInformation. # noqa: E501\n :rtype: str\n \"\"\"\n return self._departmentid\n\n @departmentid.setter\n def departmentid(self, departmentid):\n \"\"\"Sets the departmentid of this TicketInformation.\n\n\n :param departmentid: The departmentid of this TicketInformation. # noqa: E501\n :type: str\n \"\"\"\n\n self._departmentid = departmentid\n\n @property\n def agentid(self):\n \"\"\"Gets the agentid of this TicketInformation. # noqa: E501\n\n\n :return: The agentid of this TicketInformation. # noqa: E501\n :rtype: str\n \"\"\"\n return self._agentid\n\n @agentid.setter\n def agentid(self, agentid):\n \"\"\"Sets the agentid of this TicketInformation.\n\n\n :param agentid: The agentid of this TicketInformation. # noqa: E501\n :type: str\n \"\"\"\n\n self._agentid = agentid\n\n @property\n def status(self):\n \"\"\"Gets the status of this TicketInformation. # noqa: E501\n\n\n :return: The status of this TicketInformation. # noqa: E501\n :rtype: str\n \"\"\"\n return self._status\n\n @status.setter\n def status(self, status):\n \"\"\"Sets the status of this TicketInformation.\n\n\n :param status: The status of this TicketInformation. # noqa: E501\n :type: str\n \"\"\"\n\n self._status = status\n\n @property\n def tags(self):\n \"\"\"Gets the tags of this TicketInformation. # noqa: E501\n\n\n :return: The tags of this TicketInformation. # noqa: E501\n :rtype: str\n \"\"\"\n return self._tags\n\n @tags.setter\n def tags(self, tags):\n \"\"\"Sets the tags of this TicketInformation.\n\n\n :param tags: The tags of this TicketInformation. # noqa: E501\n :type: str\n \"\"\"\n\n self._tags = tags\n\n @property\n def code(self):\n \"\"\"Gets the code of this TicketInformation. # noqa: E501\n\n\n :return: The code of this TicketInformation. # noqa: E501\n :rtype: str\n \"\"\"\n return self._code\n\n @code.setter\n def code(self, code):\n \"\"\"Sets the code of this TicketInformation.\n\n\n :param code: The code of this TicketInformation. # noqa: E501\n :type: str\n \"\"\"\n\n self._code = code\n\n @property\n def channel_type(self):\n \"\"\"Gets the channel_type of this TicketInformation. # noqa: E501\n\n\n :return: The channel_type of this TicketInformation. # noqa: E501\n :rtype: str\n \"\"\"\n return self._channel_type\n\n @channel_type.setter\n def channel_type(self, channel_type):\n \"\"\"Sets the channel_type of this TicketInformation.\n\n\n :param channel_type: The channel_type of this TicketInformation. # noqa: E501\n :type: str\n \"\"\"\n\n self._channel_type = channel_type\n\n @property\n def date_created(self):\n \"\"\"Gets the date_created of this TicketInformation. # noqa: E501\n\n\n :return: The date_created of this TicketInformation. # noqa: E501\n :rtype: str\n \"\"\"\n return self._date_created\n\n @date_created.setter\n def date_created(self, date_created):\n \"\"\"Sets the date_created of this TicketInformation.\n\n\n :param date_created: The date_created of this TicketInformation. # noqa: E501\n :type: str\n \"\"\"\n\n self._date_created = date_created\n\n @property\n def public_access_urlcode(self):\n \"\"\"Gets the public_access_urlcode of this TicketInformation. # noqa: E501\n\n\n :return: The public_access_urlcode of this TicketInformation. # noqa: E501\n :rtype: str\n \"\"\"\n return self._public_access_urlcode\n\n @public_access_urlcode.setter\n def public_access_urlcode(self, public_access_urlcode):\n \"\"\"Sets the public_access_urlcode of this TicketInformation.\n\n\n :param public_access_urlcode: The public_access_urlcode of this TicketInformation. # noqa: E501\n :type: str\n \"\"\"\n\n self._public_access_urlcode = public_access_urlcode\n\n @property\n def subject(self):\n \"\"\"Gets the subject of this TicketInformation. # noqa: E501\n\n\n :return: The subject of this TicketInformation. # noqa: E501\n :rtype: str\n \"\"\"\n return self._subject\n\n @subject.setter\n def subject(self, subject):\n \"\"\"Sets the subject of this TicketInformation.\n\n\n :param subject: The subject of this TicketInformation. # noqa: E501\n :type: str\n \"\"\"\n\n self._subject = subject\n\n @property\n def custom_fields(self):\n \"\"\"Gets the custom_fields of this TicketInformation. # noqa: E501\n\n\n :return: The custom_fields of this TicketInformation. # noqa: E501\n :rtype: list[CustomFields]\n \"\"\"\n return self._custom_fields\n\n @custom_fields.setter\n def custom_fields(self, custom_fields):\n \"\"\"Sets the custom_fields of this TicketInformation.\n\n\n :param custom_fields: The custom_fields of this TicketInformation. # noqa: E501\n :type: list[CustomFields]\n \"\"\"\n\n self._custom_fields = custom_fields\n\n def to_dict(self):\n \"\"\"Returns the model properties as a dict\"\"\"\n result = {}\n\n for attr, _ in six.iteritems(self.swagger_types):\n value = getattr(self, attr)\n if isinstance(value, list):\n result[attr] = list(map(\n lambda x: x.to_dict() if hasattr(x, \"to_dict\") else x,\n value\n ))\n elif hasattr(value, \"to_dict\"):\n result[attr] = value.to_dict()\n elif isinstance(value, dict):\n result[attr] = dict(map(\n lambda item: (item[0], item[1].to_dict())\n if hasattr(item[1], \"to_dict\") else item,\n value.items()\n ))\n else:\n result[attr] = value\n if issubclass(TicketInformation, dict):\n for key, value in self.items():\n result[key] = value\n\n return result\n\n def to_str(self):\n \"\"\"Returns the string representation of the model\"\"\"\n return pprint.pformat(self.to_dict())\n\n def __repr__(self):\n \"\"\"For `print` and `pprint`\"\"\"\n return self.to_str()\n\n def __eq__(self, other):\n \"\"\"Returns true if both objects are equal\"\"\"\n if not isinstance(other, TicketInformation):\n return False\n\n return self.__dict__ == other.__dict__\n\n def __ne__(self, other):\n \"\"\"Returns true if both objects are not equal\"\"\"\n return not self == other\n","sub_path":"liveagent_api/models/ticket_information.py","file_name":"ticket_information.py","file_ext":"py","file_size_in_byte":12269,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"390561058","text":"#!/usr/bin/env python\n\nimport re\n\nbooks = [\n \"A Study in Scarlet\",\n \"The Sign of the Four\",\n \"The Hound of the Baskervilles\",\n \"The Valley of Fear\",\n \"The Adventures of Sherlock Holmes\",\n \"The Memoirs of Sherlock Holmes\",\n \"The Return of Sherlock Holmes\",\n \"His Last Bow\",\n \"The Case-Book of Sherlock Holmes\",\n]\n\nrx_article = re.compile(r'^(the|a|an)\\s+', re.I) # <1>\n\ndef strip_articles(title): # <2>\n stripped_title = rx_article.sub('', title.lower()) # <3>\n return stripped_title\n\nfor book in sorted(books, key=strip_articles): # <4>\n print(book)\n","sub_path":"EXAMPLES/sort_holmes.py","file_name":"sort_holmes.py","file_ext":"py","file_size_in_byte":590,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"434531838","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\"\"\"\n:mod:`views.py`\n==================\n\n.. module:: views.py\n :platform: Unix, Windows\n :synopsis:\n\n.. moduleauthor:: hbldh \n\nCreated on 2014-09-09, 15:08\n\n\"\"\"\n\nfrom __future__ import division\nfrom __future__ import print_function\nfrom __future__ import unicode_literals\nfrom __future__ import absolute_import\n\nimport re\nimport json\nimport itertools\n\nfrom flask import render_template, render_template_string, jsonify, request, redirect, url_for, session\nfrom flask.ext.login import login_user, logout_user, current_user, login_required\nimport dropbox\nfrom bson import ObjectId\n\nfrom vsfarkiv import app, mongo\nfrom vsfarkiv.auth import LoginForm\nfrom vsfarkiv.forms import SearchForm\n\n\n@app.route('/', methods=['GET', 'POST'])\ndef index():\n lf = LoginForm()\n if lf.validate_on_submit():\n login_user(lf.user, remember=lf.remember_me.data)\n session['remember_me'] = lf.remember_me.data\n return redirect('/news')\n present_now = {\n 'n_sheetmusic': mongo.db.documents.find({'type': 'sheetmusic'}).count(),\n 'n_audio': mongo.db.documents.find({'type': 'recording'}).count(),\n 'n_video': mongo.db.documents.find({'type': 'video'}).count(),\n 'n_papers': mongo.db.documents.find({'type': 'paper'}).count(),\n 'n_publications': mongo.db.documents.find({'type': 'publication', 'data.available': 1}).count(),\n 'n_historical_docs': mongo.db.documents.find({'type': 'historical_document'}).count()\n }\n return render_template('index.html',\n title='Värmlands Spelmansförbunds Arkiv',\n form=lf,\n present_now=present_now)\n\n\n@app.route('/news')\n@login_required\ndef news():\n news_docs = list(mongo.db.news.find({}).sort([('published', -1), ]))\n return render_template('news.html',\n title='VSF Arkiv | Nyheter',\n news_docs=news_docs)\n\n\n@app.route('/search', methods=['GET', 'POST'])\n@login_required\ndef search():\n sf = SearchForm()\n if request.method == 'POST':\n sf.song_type.data = \",\".join([x for x in request.form.getlist('song_type[]')])\n sf.tags.data = \",\".join([x for x in request.form.getlist('tags[]')])\n if sf.validate_on_submit():\n query = {}\n if len(sf.search_text.data) > 0:\n query['display_name'] = re.compile(sf.search_text.data, re.IGNORECASE)\n if len(request.form.getlist('song_type[]')) > 0:\n query['data.type'] = {'$in': request.form.getlist('song_type[]')}\n if len(request.form.getlist('tags[]')) > 0:\n query['tags'] = {'$in': request.form.getlist('tags[]')}\n search_results = list(mongo.db.documents.find(query))\n else:\n # TODO: Handle!\n search_results = None\n else:\n query = {}\n if request.args.get('tags'):\n query['tags'] = request.args.get('tags').split(',')\n if request.args.get('song_type'):\n query['data'] = {\"type\": request.args.get('type').split(',')}\n if request.args.get('text'):\n query['display_name'] = re.compile(request.args.get('text'), re.IGNORECASE)\n\n if query:\n search_results = list(mongo.db.documents.find(query))\n else:\n search_results = None\n\n song_types_list = [\n x.get('_id') for x in list(mongo.db.documents.aggregate([\n {'$project': {'_id': 0, 'data.type': 1}},\n {'$group': {'_id': '$data.type'}}]))\n ]\n tags_list = [\n x.get('_id') for x in list(mongo.db.documents.aggregate([\n {'$project': {'_id': 0, 'tags': 1}},\n {'$unwind': '$tags'},\n {'$group': {'_id': '$tags'}}]))\n ]\n return render_template('search.html',\n title='VSF Arkiv | Sök',\n form=sf,\n song_types_list=song_types_list,\n tags_list=tags_list,\n search_results=search_results)\n\n\n@app.route('/search_for_tag/', methods=['GET'])\n@login_required\ndef search_for_tag(tag):\n query = {}\n query['tags'] = {'$in': [tag, ]}\n search_results = list(mongo.db.documents.find(query))\n\n song_types_list = [\n x.get('_id') for x in list(mongo.db.documents.aggregate([\n {'$project': {'_id': 0, 'data.type': 1}},\n {'$group': {'_id': '$data.type'}}]))\n ]\n tags_list = [\n x.get('_id') for x in list(mongo.db.documents.aggregate([\n {'$project': {'_id': 0, 'tags': 1}},\n {'$unwind': '$tags'},\n {'$group': {'_id': '$tags'}}]))\n ]\n\n sf = SearchForm()\n\n return render_template('search.html',\n title='VSF Arkiv | Sök',\n form=sf,\n song_types_list=song_types_list,\n tags_list=tags_list,\n search_results=search_results)\n\n\n@app.route('/item/')\n@login_required\ndef item_page(oid):\n doc = mongo.db.documents.find_one({'_id': ObjectId(oid)})\n kwargs = {}\n if doc:\n kwargs['parent'] = mongo.db.documents.find_one({'_id': doc.get('parent')})\n if doc.get('type') == 'sheetmusic':\n template = 'item_sheetmusic.html'\n elif doc.get('type') == 'publication':\n template = 'item_publication.html'\n children = doc.get('children', []) if doc.get('children', []) is not None else []\n kwargs['documents'] = mongo.db.documents.find(\n {'_id': {'$in': children}}).sort((('data.number', 1), ('data.track_number', 1)))\n elif doc.get('type') == 'paper':\n template = 'item_paper.html'\n elif doc.get('type') == 'historical_document':\n template = 'item_historical_document.html'\n elif doc.get('type') == 'record':\n template = 'item_record.html'\n children = doc.get('children', []) if doc.get('children', []) is not None else []\n kwargs['recordings'] = mongo.db.documents.find(\n {'type': 'recording', '_id': {'$in': children}}).sort((('data.track_number', 1),))\n elif doc.get('type') == 'recording':\n template = \"item_recording.html\"\n kwargs['recordings'] = mongo.db.documents.find({'_id': doc.get('parent', None)})\n elif doc.get('type') == 'video':\n template = \"item_video.html\"\n else:\n template = None\n\n kwargs['related_documents'] = mongo.db.documents.find(\n {'_id': {'$in': doc.get('related_documents', [])}})\n kwargs['related_media'] = mongo.db.documents.find(\n {'_id': {'$in': doc.get('related_media', [])}})\n kwargs['prev_doc'] = None\n kwargs['next_doc'] = None\n\n return render_template(template,\n title='VSF Arkiv | {0}'.format(doc.get('display_name')),\n doc=doc,\n **kwargs)\n\n\n@app.route('/timeline')\n@login_required\ndef timeline():\n events = [hd.get('data').get('timeline_event') for hd in mongo.db.documents.find({'type': 'historical_document'})]\n timeline_json = {\n 'title': {\n \"media\": {\n \"url\": \"{{ url_for('static', filename='images/logo.png') }}\",\n },\n \"text\": {\n \"headline\": \"Värmlands Spelmansförbund, 1929 - 2015\",\n \"text\": \"

Vår nyaste del i arkivet: en samling historiska dokument, tidningsurklipp och bilder, \"\n \"inscannade och sorterade för att här erbjudas i kronologisk ordning!

\"\n },\n },\n 'events': events,\n 'eras': [],\n 'scale': 'human'\n }\n return render_template('timeline.html',\n title='VSF Arkiv | Tidslinje',\n timeline_json=render_template_string(json.dumps(timeline_json)))\n\n\n@app.route('/noter/alla')\n@login_required\ndef sheetmusic_all():\n all_sheets = list(mongo.db.documents.find({'type': 'sheetmusic'}))\n parents = list(set(filter(None, [n.get('parent') for n in all_sheets])))\n parents_dict = {d.get('_id'): d for d in mongo.db.documents.find({'_id': {'$in': parents}})}\n return render_template('list_all_sheetmusic.html',\n title='VSF Arkiv | Alla Notblad',\n sheetmusic=all_sheets,\n parents=parents_dict)\n\n\n@app.route('/noter/numrerade')\n@login_required\ndef sheetmusic_numbered():\n numbered_sheets = list(mongo.db.documents.find({'type': 'sheetmusic', 'subtype': 'numbered'}))\n return render_template('list_numbered.html',\n title='VSF Arkiv | Numrerade Notblad',\n sheetmusic=numbered_sheets)\n\n\n@app.route('/noter/ovriga')\n@login_required\ndef sheetmusic_nonnumbered():\n nonnumbered_sheets = list(mongo.db.documents.find({'type': 'sheetmusic', 'subtype': 'non-numbered'}))\n parents = list(set(filter(None, [n.get('parent') for n in nonnumbered_sheets])))\n parents_dict = {d.get('_id'): d for d in mongo.db.documents.find({'_id': {'$in': parents}})}\n return render_template('list_nonnumbered.html',\n title='VSF Arkiv | Övriga Notblad',\n sheetmusic=nonnumbered_sheets,\n parents=parents_dict)\n\n\n@app.route('/noter/haften')\n@login_required\ndef sheetmusic_publications():\n publications = list(mongo.db.documents.find({'type': 'publication'}))\n available_publications = filter(lambda x: not x.get('data', {}).get('license', False) and\n x.get('data', {}).get('available', False), publications)\n licensed_available_publications = filter(lambda x: x.get('data', {}).get('license', False) and\n x.get('data', {}).get('available', False), publications)\n licensed_nonavailable_publications = filter(lambda x: x.get('data', {}).get('license', False) and\n not x.get('data', {}).get('available', False), publications)\n\n return render_template('list_publications.html',\n title='VSF Arkiv | Nothäften',\n publications=available_publications,\n licensed_available_publications=licensed_available_publications,\n licensed_nonavailable_publications=licensed_nonavailable_publications)\n\n\n@app.route('/tidning')\n@login_required\ndef papers():\n papers = mongo.db.documents.find(\n {'type': 'paper', 'subtype': 'vfolk'}).sort((('data.year', -1), ('data.number', -1)))\n papers_by_year = [(key, list(group)) for key, group in itertools.groupby(papers, lambda x: x.get('data').get('year'))]\n return render_template('list_papers.html',\n title='VSF Arkiv | Värmländsk Folkmusik',\n papers=papers_by_year)\n\n\n@app.route('/audio')\n@login_required\ndef audio():\n records = mongo.db.documents.find({'type': 'record'})\n free_audio = mongo.db.documents.find({'type': 'standalone_audio'})\n return render_template('list_recordings.html',\n title='VSF Arkiv | Ljudklipp',\n records=records,\n free_audio=free_audio)\n\n\n@app.route('/video')\n@login_required\ndef video():\n videos = mongo.db.documents.find({'type': 'video'})\n return render_template('list_video.html',\n title='VSF Arkiv | Videoklipp',\n videos=videos)\n\n\n# API methods\n\n@app.route('/download/')\n@login_required\ndef download_document(oid):\n doc = mongo.db.documents.find_one({'_id': ObjectId(oid)}, {'_id': 0, 'path': 1})\n dbox = dropbox.client.DropboxClient(app.config.get('DROPBOX_ACCESS_TOKEN'))\n return redirect(dbox.media(doc.get('path')).get('url'))\n\n\n@app.route('/media/')\n@login_required\ndef link_media(oid):\n doc = mongo.db.documents.find_one({'_id': ObjectId(oid)}, {'_id': 0, 'path': 1})\n dbox = dropbox.client.DropboxClient(app.config.get('DROPBOX_ACCESS_TOKEN'))\n return jsonify(**{\"url\": dbox.media(doc.get('path')).get('url')})\n\n\n@app.route('/change/', methods=['POST'])\n@login_required\ndef change(oid):\n output = {}\n if current_user.is_admin:\n data_to_set = request.json\n for k in data_to_set:\n data_to_set[k] = data_to_set[k].strip() if isinstance(data_to_set[k], basestring) else data_to_set[k]\n if mongo.db.documents.find_one({'_id': ObjectId(oid)}):\n results = mongo.db.documents.update_one({'_id': ObjectId(oid)}, {'$set': data_to_set})\n output = results.raw_result\n try:\n output['electionId'] = str(output.get('electionId', 'NoID'))\n output['lastOp'] = output.get('lastOp').time\n except:\n pass\n return jsonify(**output)\n\n\n@app.route('/addrelation/', methods=['POST'])\n@login_required\ndef add_relation(oid):\n output1 = {}\n if current_user.is_admin:\n data_to_set = request.json\n field_name = 'related_documents'\n collection_name = \"documents\"\n\n related_item = mongo.db[collection_name].find_one({'_id': ObjectId(data_to_set.get('oid'))})\n if related_item:\n if mongo.db.documents.find_one({'_id': ObjectId(oid)}):\n collection_to_add_relation_in = mongo.db.documents\n else:\n return jsonify(**output1)\n results = collection_to_add_relation_in.update_one(\n {'_id': ObjectId(oid)},\n {'$addToSet': {field_name: ObjectId(data_to_set.get('oid'))}})\n results2 = collection_to_add_relation_in.update_one(\n {'_id': data_to_set.get('oid')},\n {'$addToSet': {field_name: ObjectId(oid)}})\n output1 = results.raw_result\n output2 = results2.raw_results\n try:\n output1['electionId'] = str(output1.get('electionId', 'NoID'))\n output1['lastOp'] = output1.get('lastOp').time\n output2['electionId'] = str(output2.get('electionId', 'NoID'))\n output2['lastOp'] = output2.get('lastOp').time\n except:\n pass\n\n return jsonify(**{\"output1\": output1, \"output2\": output2})\n","sub_path":"vsfarkiv/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":14506,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"202608670","text":"from doubly_linked_list import DoublyLinkedList\n\nclass LRUCache:\n\t\"\"\"\n\tOur LRUCache class keeps track of\n\t\t* the max number of nodes it can hold\n\t\t* the current number of nodes it is holding\n\t\t* a doubly-linked list that holds the key-value entries in the correct order\n\t\t* as well as a storage dict that provides fast access to every node stored in the cache.\n\t\"\"\"\n\tdef __init__(self, limit=10):\n\t\tself.limit = limit\n\t\tself.length = 0\n\t\tself.dll = DoublyLinkedList()\n\t\tself.store = {}\n\n\t\"\"\"\n\tRetrieves the value associated with the given key.\n\tAlso needs to move the key-value pair to the end of the order such that the pair is considered most-recently used.\n\t\n\tReturns the value associated with the key or None if the key-value pair doesn't exist in the cache.\n\t\"\"\"\n\tdef get(self, key):\n\t\t# print(24, key)\n\t\tif key in self.store:\n\t\t\tcurrent = self.store[key]\n\t\t\t# print(25, current.value)\n\n\t\t\tself.dll.move_to_front(current)\n\t\t\treturn current.value[1]\n\n\t\telse:\n\t\t\treturn None\n\n\n\t\"\"\"\n\tAdds the given key-value pair to the cache.\n\tThe newly-added pair should be considered the most-recently used entry in the cache.\n\n\tIf the cache is already at max capacity\tbefore this entry is added,\n\tthen the oldest entry in the cache needs to be removed to make room.\n\t\n\tIf key already exists in the cache,\n\toverwrite the old value associated with the key with the newly-specified value.\n\t\"\"\"\n\tdef set(self, key, value):\n\t\t# print(47, key, value)\n\t\tif key in self.store:\n\t\t\t# if store item exists\n\t\t\tcurrent = self.store[key]\n\t\t\tcurrent.value = (key, value)\n\t\t\tself.dll.move_to_front(current)\n\t\t\treturn current.value\n\n\t\t# if not already in the store\n\t\t# chk and prepare length first\n\t\tif self.length == self.limit:\n\t\t\tself.length -= 1\n\t\t\tdel self.store[self.dll.tail.value[0]]\n\t\t\tself.dll.remove_from_tail()\n\n\t\t# NOW add to the store\n\t\tself.length += 1\n\t\tself.dll.add_to_head((key,value))\n\t\tself.store[key] = self.dll.head\n\n\n\nf = LRUCache()\n\nf.set('item1', 'a')\nf.set('item2', 'b')\nf.set('item3', 'c')\nf.set('item2', 'z')\n\n# print(f.get('item1'))\n# print(f.get('item2')) \n\n","sub_path":"lru_cache/lru_cache.py","file_name":"lru_cache.py","file_ext":"py","file_size_in_byte":2061,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"514375056","text":"#!/bin/python3\n\"\"\"\nThe xrandr names (DP-1, DP-2) for my monitors tends to flip around depending on\nwhich one happens to become active first. This script figures out which is which\nby the EDID, and runs xrandr to apply the layout correctly.\n\n\"\"\"\n\nimport re\nimport subprocess\nimport time\nimport os\n\n# map from arbitrary descriptions of my monitors to their serial numbers, as\n# reported by the last 16 hexadecimal characters in the first line of their\n# EDID. (Run xrandr --verbose)\nnames_serials = {\n 'l': '0469a12894840200',\n 'r': '0469f627f0960100',\n}\n\nedid_re = re.compile(r'([\\w\\d-]+)\\sconnected.*?00ffffffffffff00([\\d\\w]{16})',\n re.S)\n\nif __name__ == '__main__':\n serials_rnames = {\n hexstr: name\n for name, hexstr in edid_re.findall(\n subprocess.check_output(['xrandr', '--verbose']).decode('utf-8'))\n }\n\n def monitor(s):\n return serials_rnames[names_serials[s]]\n\n xrandrcmd = '''\n xrandr\n --output HDMI-2 --off\n --output HDMI-1 --off\n '''\n try:\n xrandrcmd += f'''\n --output eDP-1 --primary --mode 1920x1080 --pos 1080x1080 --rotate normal\n --output {monitor('r')} --mode 1920x1080 --pos 1080x0 --rotate normal\n --output {monitor('l')} --mode 1920x1080 --pos 0x0 --rotate right\n '''\n except KeyError:\n xrandrcmd += '''\n --output eDP-1 --primary --mode 1920x1080 --pos 0x0 --rotate normal\n --output DP-2 --off\n --output DP-1 --off\n '''\n print(xrandrcmd)\n subprocess.check_call(xrandrcmd.split())\n\n time.sleep(2)\n # if which feh && [ -e $HOME/.wallpaper ]; then\n filename = f\"{os.environ['HOME']}/.wallpaper\"\n subprocess.check_call([\"feh\", \"--bg-fill\", \"--no-xinerama\", filename])\n","sub_path":"bin/randr.py","file_name":"randr.py","file_ext":"py","file_size_in_byte":1808,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"122446443","text":"#!/usr/bin/env python2\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun Jul 30 15:19:38 2017\n\n@author: lilllianpetersen\n\"\"\"\nimport numpy as np\n\ndef rolling_median(var,window):\n '''var: array-like. One dimension\n window: Must be odd'''\n n=len(var)\n halfW=int(window/2)\n med=np.zeros(shape=(var.shape))\n for j in range(halfW,n-halfW):\n med[j]=np.ma.median(var[j-halfW:j+halfW+1])\n \n for j in range(0,halfW):\n w=2*j+1\n med[j]=np.ma.median(var[j-w/2:j+w/2+1])\n i=n-j-1\n med[i]=np.ma.median(var[i-w/2:i+w/2+1])\n \n return med ","sub_path":"other/CSTA_AMC_Code/Part1_Predict_Grain_Harvests/creating_model/running_median.py","file_name":"running_median.py","file_ext":"py","file_size_in_byte":583,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"490591018","text":"#!/usr/bin/env python\n#coding=utf-8\n\n#======================================================================\n# Program: Neural Network Dose Distribution\n# Author: James Keal\n# Date: 2016/09/12\n#======================================================================\n\n'''\ncomment\n'''\n\nfrom __future__ import print_function\n\nimport time\nimport numpy as np\nimport numpy.random as rnd\n\ndef all_coords_shuffled(dose, margin, n_samples=None):\n start_time = time.time()\n coord_list = []\n for d in range(len(dose)):\n for i in range(margin, dose[d].shape[0]-margin):\n for j in range(margin, dose[d].shape[1]-margin):\n for k in range(margin, dose[d].shape[2]-margin):\n coord_list.append([d,i,j,k])\n\n assert n_samples <= len(coord_list)\n coord_list = np.array(coord_list)\n rnd.shuffle(coord_list)\n print(time.time() - start_time)\n return coord_list[0:n_samples]\n\ndef monte_carlo(dose, margin, n_samples):\n start_time = time.time()\n coord_list = []\n\n for n in range(n_samples):\n d = rnd.choice(len(dose))\n r = rnd.rand(3)\n i = int(r[0]*(dose[d].shape[0]-2*margin)) + margin\n j = int(r[1]*(dose[d].shape[1]-2*margin)) + margin\n k = int(r[2]*(dose[d].shape[2]-2*margin)) + margin\n coord_list.append([d,i,j,k])\n\n coord_list = np.array(coord_list)\n print(time.time() - start_time)\n return coord_list\n\ndef latin_hypercube(dose, margin, n_samples):\n start_time = time.time()\n coord_list = []\n print(time.time() - start_time)\n return coord_list\n\ndef guassian_latin_hypercube(dose, margin, n_samples):\n start_time = time.time()\n coord_list = []\n print(time.time() - start_time)\n return coord_list\n","sub_path":"sampling_methods.py","file_name":"sampling_methods.py","file_ext":"py","file_size_in_byte":1752,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"427877950","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Nov 7 14:50:06 2018\n\n@author: zhoumengzhi\n\"\"\"\n\nimport matplotlib.pyplot as plt\nimport pandas as pd\nfrom pprint import pprint\nfrom sklearn.cluster import KMeans\nfrom sklearn import preprocessing\nfrom sklearn import cluster\nfrom sklearn import decomposition\nfrom sklearn.metrics import silhouette_samples, silhouette_score\n#from sklearn.cluster import Ward\n\n#Clustering Analysis \n\n#read data into python panda.dataframe\noutput = pd.read_csv('cleandata.csv' , sep=',', encoding='latin1')\n#print 1st 10 rows data\nprint(output[:10])\n\n\n#ward clustering\ndef ward():\n #ward clustering\n #drop na value\n output.clean=output.dropna()\n \n print('ward method')\n\n \n #normalize dataset: prepare for k-means\n #data1=pd.concat([output.clean['wind_speed'], output.clean['visibility'], output.clean['temp'],output.clean['gust_speed'],output.clean['filed_airspeed_kts']], axis=1, keys=['windspeed', 'visibility','temp','gust_speed','airspeed'])\n data1=pd.concat([output.clean['wind_speed'],output.clean['visibility'],output.clean['gust_speed'],output.clean['filed_airspeed_kts']], axis=1, keys=['windspeed','visibility','gust_speed','airspeed'])\n\n \n x = data1.values\n minmax = preprocessing.MinMaxScaler()\n xscale = minmax.fit_transform(x)\n normalizedDataFrame = pd.DataFrame(xscale)\n pprint(normalizedDataFrame[:10])\n \n \n #Use ward to get cluster\n klist = [2,5,10] #set up a list for k value\n for k in klist: \n ward = cluster.AgglomerativeClustering(n_clusters=k,linkage='ward')\n cluster_labels = ward.fit_predict(normalizedDataFrame)\n \n #plot graph for kmeans cluster\n pca2D = decomposition.PCA(2)\n plot_columns = pca2D.fit_transform(normalizedDataFrame)\n plt.scatter(x=plot_columns[:,0], y=plot_columns[:,1], c=cluster_labels)\n plt.show()\n \n #Measure Silhouette procedure\n silhouetterate = silhouette_score(normalizedDataFrame, cluster_labels)\n print(\"For ward cluster number k = \", k, \"Silhouette_score = :\", silhouetterate)\n \n \nward()\n \n#kmeans clustring\ndef kmeans_silhouetterate(): \n #k-means clustering\n #drop na value\n output.clean=output.dropna()\n \n print('kmeans method')\n\n \n #normalize dataset: prepare for k-means\n data2=pd.concat([output.clean['wind_speed'],output.clean['visibility'],output.clean['gust_speed'],output.clean['filed_airspeed_kts']], axis=1, keys=['windspeed','visibility','gust_speed','airspeed'])\n\n x = data2.values\n minmax = preprocessing.MinMaxScaler()\n xscale = minmax.fit_transform(x)\n normalizedDataFrame = pd.DataFrame(xscale)\n pprint(normalizedDataFrame[:10])\n \n #Use k-means to get cluster\n klist = [2,5,10] #set up a list for k value\n for k in klist: \n kmeans = KMeans(n_clusters=k)\n cluster_labels = kmeans.fit_predict(normalizedDataFrame)\n #centroids = kmeans.cluster_centers_\n #print (centroids)\n \n #plot graph for kmeans cluster\n pca2D = decomposition.PCA(2)\n plot_columns = pca2D.fit_transform(normalizedDataFrame)\n plt.scatter(x=plot_columns[:,0], y=plot_columns[:,1], c=cluster_labels)\n plt.show()\n \n #Measure Silhouette procedure\n silhouetterate = silhouette_score(normalizedDataFrame, cluster_labels)\n print(\"For k_means cluster number k = \", k, \"Silhouette_score = :\", silhouetterate)\n\nkmeans_silhouetterate()\n\n#dbscan clustering\ndef dbscan():\n #dbscan clustering\n #drop na value\n output.clean=output.dropna()\n \n print('dbscan method')\n \n #normalize dataset: prepare for k-means\n data3=pd.concat([output.clean['wind_speed'],output.clean['visibility'],output.clean['gust_speed'],output.clean['filed_airspeed_kts']], axis=1, keys=['windspeed','visibility','gust_speed','airspeed'])\n\n x = data3.values\n minmax = preprocessing.MinMaxScaler()\n xscale = minmax.fit_transform(x)\n normalizedDataFrame = pd.DataFrame(xscale)\n pprint(normalizedDataFrame[:10])\n \n #Use dbscan to get clster\n elist = [0.05,0.2,0.5] #set up a list for eps value\n for e in elist: \n dbscan = cluster.DBSCAN(eps=e)\n cluster_labels = dbscan.fit_predict(normalizedDataFrame)\n \n #plot graph for kmeans cluster\n pca2D = decomposition.PCA(2)\n plot_columns = pca2D.fit_transform(normalizedDataFrame)\n plt.scatter(x=plot_columns[:,0], y=plot_columns[:,1], c=cluster_labels)\n plt.show()\n \n #Measure Silhouette procedure\n silhouetterate = silhouette_score(normalizedDataFrame, cluster_labels)\n print(\"For DBSCAN eps = \", e, \"Silhouette_score = :\", silhouetterate)\n\ndbscan() \n \n \n \n \n ","sub_path":"Part2/Part 2 content/Clustering/clustering.py","file_name":"clustering.py","file_ext":"py","file_size_in_byte":4822,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"139740736","text":"import numpy as np\n\n# Pulling Values from whichever window you want\n# Note: Make sure the time-ends (in seconds) of your window\n# match a time in the time_array of the simulation\n\ndef getData(file_path, var_name):\n \"\"\"\n Load the data from a csv file\n :param file_path:\n :param var_name: name of variable to load (check NC output)\n :return: numpy array of data\n \"\"\"\n data = np.loadtxt(\"{0}_{1}.csv\".format(file_path, var_name), delimiter = ',')\n print(var_name, ', arr length:', data.size)\n return data\n\n\ndef getTimeArray(file_path):\n \"\"\"\n Return the time array of the simulation.\n This is used because in the simulations where state['time'] is NOT updated,\n the time array will be all zeros, which you can't index.\n We want a time array we can index.\n \"\"\"\n time_step = 10 * (60)\n \"\"\"SAVE STEP IS KEY\"\"\"\n save_step = 36 * time_step\n time_arr = getData(file_path, 'time')\n time_arr = np.arange(0, time_arr.size*save_step, save_step)\n return time_arr\n\n\ndef getTimeIndices(time_arr, start_time, end_time):\n \"\"\"\n Find the indices in the time array that correspond to the start and end times identified\n :param time_arr:\n :param start_time:\n :param end_time:\n :return: indices, start and end\n \"\"\"\n start_i = np.where(time_arr == start_time)[0][0]\n end_i = np.where(time_arr == end_time)[0][0]\n return start_i, end_i\n\n\ndef getWindow(data, start_i, end_i):\n \"\"\"\n return the window of data between the time indices\n :param data:\n :param start_i:\n :param end_i:\n :return:\n \"\"\"\n return data[start_i:end_i + 1]\n\n\ndef printWindowValues(file_path, var_name, start_time, end_time):\n \"\"\"\n Print the values (Mean, Median, STD) of the chosen variable within the time window\n :param file_path:\n :param var_name:\n :param start_time:\n :param end_time:\n :return:\n \"\"\"\n data = getData(file_path, var_name)\n time_arr = getTimeArray(file_path)\n start_i, end_i = getTimeIndices(time_arr, start_time, end_time)\n data_window = getWindow(data, start_i, end_i)\n\n print('Var:', var_name)\n print('Start:', start_time)\n print('End:', end_time)\n print('Mean:', np.mean(data_window))\n print('Median:', np.median(data_window))\n print('STD:', np.std(data_window))\n\n\ndef writeEQProfile(data, var_name, file_path):\n \"\"\"\n Write the EQ profile of a chosen variable into a csv file as a numpy array\n :param data: EQ profile\n :param var_name:\n :param file_path:\n :return:\n \"\"\"\n csv_name = '{0}_eqProfile_{1}.csv'.format(file_path, var_name)\n np.savetxt(csv_name, data, delimiter=',')\n print(\"EQ Profile: \", var_name)\n\n\ndef writeEQTable1Values(file_path, start_time, end_time):\n \"\"\"\n Write out the EQ values and profiles of the time window into various files\n :param file_path:\n :param start_time:\n :param end_time:\n :return:\n \"\"\"\n def getEQValue(var_name):\n \"\"\"\n Get the EQ value or profile for a chosen variable\n :param var_name:\n :return:\n \"\"\"\n data = getData(file_path, var_name)\n data_window = getWindow(data, start_i, end_i)\n return np.mean(data_window, axis = 0)\n\n time_arr = getTimeArray(file_path)\n start_i, end_i = getTimeIndices(time_arr, start_time, end_time)\n\n lwflx = getEQValue('lwflx')\n swflx = getEQValue('swflx')\n LwToa = getEQValue('LwToa')\n SwToa = getEQValue('SwToa')\n SwSrf = getEQValue('SwSrf')\n LwSrf = getEQValue('LwSrf')\n\n\n Ts = getEQValue('Ts')\n precc = getEQValue('precc')\n SrfLatFlx = getEQValue('SrfLatFlx')\n SrfSenFlx = getEQValue('SrfSenFlx')\n\n net_rad = lwflx + swflx\n net_toa = SwToa + LwToa\n net_surf = SwSrf + LwSrf + SrfLatFlx + SrfSenFlx\n\n t_air = getEQValue('T')\n writeEQProfile(t_air, 'air_temperature', file_path)\n writeEQProfile(net_rad, 'net_radiation', file_path)\n\n str_list = ['STARTtime', 'ENDtime', 'NETtoa', 'NETsurf', 'SWtoa',\n 'LWtoa', 'SWsurf', 'LWsurf', 'LH', 'SH', 'Ts', 'Prec']\n val_list = [start_time, end_time, net_toa, net_surf, SwToa,\n LwToa, SwSrf, LwSrf, SrfLatFlx, SrfSenFlx, Ts, precc]\n txt_file = open('{0}_eqTable1Values.txt'.format(file_path), 'w')\n\n assert len(str_list) == len(val_list), \"Not the same length of strings and values.\"\n for i in range(len(str_list)):\n str_i = str_list[i]\n val_i = val_list[i]\n out_statement = '{0}: {1}'.format(str_i, val_i)\n print(out_statement)\n txt_file.write(out_statement + '\\n')\n\n return str_list, val_list\n\n\n# Parameters\nbase_path = '/home/haynes13/climt_files'\n\njob_name = 'shanshan_control'\nprint('JOB:', job_name)\nfile_path = '{0}/{1}/{1}'.format(base_path, job_name)\nstart_day = 9950\nend_day = 10950 - 1\nstart_time = np.float(start_day * (24 * 60 * 60))\nend_time = np.float((end_day) * (24 * 60 * 60))\n\n# Procedures\nwriteEQTable1Values(file_path, start_time, end_time)\n","sub_path":"pullWindowValues.Shanshan.py","file_name":"pullWindowValues.Shanshan.py","file_ext":"py","file_size_in_byte":4983,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"450666488","text":"import json\nimport requests\nimport time\nimport urllib.parse\n\nTOKEN = \"499561911:AAFHaBMl67ieOSjjZ0MDYdOEMby-NJahp1g\"\nURL = \"https://api.telegram.org/bot{}/\".format(TOKEN)\nmaterias = [\"Sistemas de Informação\", \"Compiladores\", \"Banco de Dados II\", \"Redes I\", \"MDS II\"]\nlink_prova = \"https://drive.google.com/file/d/1nHl346achwzY4_2cf9ZX7t4-bL_XTgIh/view?usp=sharing\"\n\n\ndef get_url(url):\n response = requests.get(url)\n content = response.content.decode(\"utf8\")\n return content\n\ndef get_json(url):\n content = get_url(url)\n js = json.loads(content)\n return js\n\ndef get_updates(offset=None):\n url = URL + \"getUpdates?timeout=100\"\n if offset:\n url += \"&offset={}\".format(offset)\n js = get_json(url)\n return js\n\ndef get_last_update_id(updates):\n update_ids = []\n for update in updates[\"result\"]:\n update_ids.append(int(update[\"update_id\"]))\n return max(update_ids)\n\ndef handle_updates(updates):\n for update in updates[\"result\"]:\n try:\n text = update[\"message\"][\"text\"]\n chat = update[\"message\"][\"chat\"][\"id\"]\n username = update[\"message\"][\"chat\"][\"username\"]\n if text.startswith(\"/\"):\n #items = db.get_items(chat)\n if text == \"/start\":\n #keyboard = build_keyboard(items)\n send_message(\"Olá \"+username+\" serei seu parceiro na sua jornada durante o curso de SI da UNEB. atualmente posso lhe ajudar com esses comandos: \", chat)\n send_message(\"*/prova:* Lista as provas antigas da matéria a ser selecionada.\\n */prova nome_da_materia:* Lista as provas antigas das matérias com o nome passado.\", chat, \"Markdown\")\n elif text == \"/help\":\n send_message(\"Olá \"+username+\", atualmente posso lhe ajudar com esses comandos: \", chat)\n send_message(\"*/prova:* Lista as provas antigas da matéria a ser selecionada.\\n */prova nome_da_materia:* Lista as provas antigas desta matéria.\", chat, \"Markdown\")\n elif text.startswith(\"/prova\"):\n school_theme = text.split(\"/prova\", 1)[1]\n if school_theme == \"\":\n send_message(\"[Compila 2016.1](\"+link_prova+\")\\n[Banco de Dados](\"+link_prova+\")\", chat, \"Markdown\")\n else:\n send_message(\"[Compila 2017.2](\"+link_prova+\")\", chat, \"Markdown\")\n except KeyError:\n pass\n\ndef get_last_chat_info(updates):\n num_updates = len(updates[\"result\"])\n last_update = num_updates - 1\n text = updates[\"result\"][last_update][\"message\"][\"text\"]\n chat_id = updates[\"result\"][last_update][\"message\"][\"chat\"][\"id\"]\n text.encode('utf-8')\n return (text, chat_id)\n\ndef send_message(text, chat_id, reply_markup=None):\n print(\"Received: \"+text)\n text1 = urllib.parse.quote_plus(text)\n #print(\"Must send: \" + text1)\n url = URL + \"sendMessage?text={}&chat_id={}\".format(text, chat_id)\n if reply_markup == \"Markdown\":\n url += \"&parse_mode={}\".format(\"Markdown\")\n elif reply_markup:\n url += \"&reply_markup={}\".format(reply_markup)\n get_url(url)\n\ndef build_keyboard(items):\n '''keyboard = [[item] for item in items]\n reply_markup = {\"keyboard\":keyboard, \"one_time_keyboard\": True}\n return json.dumps(reply_markup)'''\n\ndef main():\n last_update_id = None\n while True:\n print(\"Waiting messages...\")\n updates = get_updates(last_update_id)\n if len(updates[\"result\"]) > 0:\n last_update_id = get_last_update_id(updates) + 1\n handle_updates(updates)\n\nif __name__ == '__main__':\n main()\n","sub_path":"leobot.py","file_name":"leobot.py","file_ext":"py","file_size_in_byte":3667,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"544620012","text":"#!/usr/bin/env python3\n\nimport sys\n\nclass airlines:\n def __init__(self, name, departure, arrival):\n self.name = name\n self.departure = departure\n self.arrival = arrival\n self.total = 0\n def updateVals(self, departure, arrival):\n self.departure += departure\n self.arrival += arrival\n\nallCarriers = []\nfound = False\n\nfor line in sys.stdin:\n line = line.strip()\n arrivalD = \"0\"\n departureD = \"0\"\n arr = line.split('\\t', 3)\n\n if(len(arr) > 1):\n departureD = arr[1]\n if(len(arr) > 2):\n arrivalD = arr[2]\n\n departureD = int(departureD)\n arrivalD = int(arrivalD)\n\n for i in allCarriers:\n if(i.name == arr[0]):\n i.updateVals(departureD, arrivalD)\n found = True\n break\n\n if(not found):\n newCarrier = airlines(arr[0], departureD, arrivalD)\n allCarriers.append(newCarrier)\n\n found = False\n #exit()\n\n\nmaxMin = []\n\n#add the total delay time\nfor i in allCarriers:\n i.total = i.arrival + i.departure\n maxMin.append(i.total)\n\nmaxMin.sort()\n\nfor j in range(len(maxMin)):\n for i in allCarriers:\n if(i.total == maxMin[j]):\n print(\"{0}{1}{2}{3}{4}{5}{6}\".format(i.name, \": departureDelay - \", i.departure, \", arrivalDelay- \", i.arrival, \", total- \", i.total))\n break\n\nprint(\"---------------------------------------\")\nmaxVal = max(maxMin)\nminVal = min(maxMin)\n\nfor i in range(len(maxMin)):\n if(allCarriers[i].total == maxVal):\n print(\"{0}{1}\".format(allCarriers[i].name, \" has the worst on-time performance\"))\n if(allCarriers[i].total == minVal):\n print(\"{0}{1}\".format(allCarriers[i].name, \" has the best on-time performance\"))\n","sub_path":"mapperReducer/bestWorstReduce.py","file_name":"bestWorstReduce.py","file_ext":"py","file_size_in_byte":1726,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"209364349","text":"#!/usr/bin/python\n\nfrom flask import Blueprint, jsonify, request\nfrom repositories import word_repository\nfrom utils.word_utils import to_words_dto\n\nword_service = Blueprint('word_service', __name__)\n\n@word_service.route(\"/word\", methods=[\"POST\", \"DELETE\"])\ndef add_or_remove_word():\n if request.method == \"POST\":\n room_id = int(request.args.get(\"roomId\"))\n user_id = int(request.args.get(\"userId\"))\n round_id_raw = request.args.get(\"roundId\")\n round_id = (int(round_id_raw)\n if round_id_raw is not None and round_id_raw.isdigit()\n else None)\n word = request.args.get(\"word\")\n word_repository.create_word(room_id, user_id, round_id, word)\n elif request.method == \"DELETE\":\n word_id = int(request.args.get(\"wordId\"))\n word_repository.remove_word(word_id)\n\n return \"{}\"\n\n@word_service.route(\"/words\", methods=[\"GET\"])\ndef get_words():\n room_id = int(request.args.get(\"roomId\"))\n round_id_raw = request.args.get(\"roundId\")\n round_id = int(round_id_raw) if round_id_raw is not None and round_id_raw.isdigit() else None\n word_entities = word_repository.get_words(room_id, round_id)\n words_dto = to_words_dto(word_entities)\n return words_dto\n\n@word_service.route(\"/word\", methods=[\"GET\"])\ndef get_word():\n word_id = int(request.args.get(\"wordId\"))\n word_entity = word_repository.get_word(word_id)\n word = {\n \"wordId\": word_entity.WordId,\n \"userId\": word_entity.UserId,\n \"word\": word_entity.Word\n }\n return jsonify(word)\n","sub_path":"service/artmaster/artmaster/services/word_service.py","file_name":"word_service.py","file_ext":"py","file_size_in_byte":1555,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"491828120","text":"# 파일을 읽어서 내가 원하는 형식으로 리턴하는 함수\n# ex) csv 파일을 읽어서 dictionary 형식으로 리턴하기\n\n# pickle : 파이썬 자료형 / 반드시 binary 모드로 오픈해야 함 / 다른 언어와 호환성은 없음\n# 저장하기 : pickle.dump(data, file) -> 파일은 'wb'로 오픈한 파일 객체 (binary)\n# 불러오기 : pickle.load(file) -> 파일은 'rb'로 오픈한 파일 객체 (binary)\nimport pickle\n\n# 파일을 열어 라인으로 리턴하는 함수\ndef load(fpath):\n with open(fpath, 'rt', encoding='utf-8') as f:\n return f.readlines() # 라인의 리스트 형식\n \n# 학생 이름 : key, 성적 리스트 : value --> 사전으로 만드는 함수\ndef convert(lines):\n data = {} # data 변수는 stack에, 빈 사전은 heap에 저장됨\n for line in lines[1:]:\n line = line.replace('\\n', '') # 개행문자 삭제\n name = line.split(',')[0] # 학생 이름\n scores = line.split(',')[1:] # 성적들\n data[name] = list(map(int,scores)) # int로 변경 후 사전으로 등록\n \n # TIP: map함수를 이용하여 개행문자가 포함된 문자를 int로 변환하여도 영향을 미치지 않음\n # 이를 white 문자라고 함 (공백, 엔터, 탭 ...)\n \n return data # heap에 있는 사전의 참조값을 리턴\n\n# load 함수에서 예외 처리를 하면, 아래 load 라인은 괜찮지만 print 라인이 또 다시 오류 발생 \n\n# 저장 함수\ndef save(fpath, data):\n with open(fpath, 'wb') as f:\n pickle.dump(data,f)\n\n# 흐름 제어 함수\ndef main():\n try:\n lines = load('data.csv')\n # fpath = input('파일명 : ') # 파일명을 받아서 열 수도 있음\n # lines = load(fpath)\n data = convert(lines)\n # print(data) # 확인용\n save('data.dat',data)\n\n except Exception as e:\n print('예외 발생 : ', e)\n\nmain()\n\n# print(data) -> 이는 오류 발생 / main 함수에서 data를 리턴하지 않았기 때문\n\n# \\u : 유니코드\n# feff : 어떤 문자열로 코딩되었는지 일종의 식별자","sub_path":"ch14/ex06.py","file_name":"ex06.py","file_ext":"py","file_size_in_byte":2130,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"486259693","text":"import redis\nimport json\nimport threading\nimport time\nimport yaml\n\nwith open(\"/config/config.yml\", 'r') as stream:\n try:\n config = yaml.load(stream)\n except yaml.YAMLError as exc:\n print(\"Cannot open the config file!\")\n exit()\n\n#######################\n#RECOMMENDATION ENGINE#\n#######################\n\n# Redis\nredis = redis.Redis(host=config['redis']['host'], port=config['redis']['port'])\npubsub = redis.pubsub()\n\n# Requested users\nwaiting = dict()\n\ndef getProfile(userid, callback):\n # Request\n print(\"Sending update request of profile:%s\" % userid, flush=True)\n redis.publish('profile_server', json.dumps({\"cmd\": \"GET\", \"id\": userid}))\n\n waiting[userid] = {\"timer\": threading.Timer(config['recommendation_engine']['max_delay'], getProfileFromCache, [userid]), \"callback\": callback, \"startat\": time.time()}\n waiting[userid][\"timer\"].start()\n\ndef getProfileFromCache(userid):\n if userid not in waiting:\n return\n\n print(\"Getting profile:%s from redis after %s sec\" % (userid, time.time() - waiting[userid][\"startat\"]), flush=True)\n\n waiting[userid][\"timer\"].cancel()\n callback = waiting[userid][\"callback\"]\n del waiting[userid]\n\n try:\n data = redis.get(\"profile:%s\" % userid).decode(\"utf-8\")\n profile = json.loads(data)\n except:\n profile = {}\n\n callback(profile)\n\ndef msgHandler(msg):\n data = json.loads(msg['data'].decode(\"utf-8\"))\n cmd = data['cmd']\n\n print(\"Message recived: %s\" % data, flush=True)\n\n if cmd == \"UPDATED\":\n id = data['id']\n getProfileFromCache(id)\n \ndef debugData(data):\n print(\"Data recived: %s\" % data, flush=True)\n\nif __name__ == \"__main__\":\n print(\"Creating listener...\")\n pubsub.subscribe(**{'recommendation_engine': msgHandler})\n thread = pubsub.run_in_thread(sleep_time=0.001)\n\n while True:\n cmd = input()\n getProfile(cmd, debugData)\n\n ","sub_path":"recommendation_engine/recommendation_engine.py","file_name":"recommendation_engine.py","file_ext":"py","file_size_in_byte":1920,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"66851234","text":"#!/usr/bin/env python2.7\nimport sys\nfrom sys import argv\nimport pandas as pd\nimport numpy as np\nimport xarray as xr\nimport matplotlib.pyplot as plt\nimport ncplotlib as ncplt\n\ndef compare(axes, dycoms_var, converted_monc, colour_dycoms, colour_monc, title, ylim, ylabel):\n # Average\n dycoms_var[0].plot(color=colour_dycoms, ax=axes, label=\"S05 Ensemble Mean\")\n # First and third percentiles \n dycoms_var[4].plot(color=colour_dycoms, ax=axes, alpha=0.5)\n dycoms_var[5].plot(color=colour_dycoms, ax=axes, alpha=0.5)\n axes.fill_between(dycoms_var.time, dycoms_var[4], dycoms_var[5], color=colour_dycoms, alpha=0.5, label=\"S05 Ensemble 1st & 3rd percentiles\")\n # Max and min\n dycoms_var[2].plot(color=colour_dycoms, ax=axes, alpha=0.2)\n dycoms_var[3].plot(color=colour_dycoms, ax=axes, alpha=0.2)\n axes.fill_between(dycoms_var.time, dycoms_var[2], dycoms_var[3], color=colour_dycoms, alpha=0.2, label=\"S05 Ensemble Max & Min\")\n \n # MONC simulation\n converted_monc.plot(color=colour_monc, ax=axes, label=\"MONC sim\")\n \n axes.set_ylim(0, ylim)\n axes.set_xlabel(\"Time [s]\")\n axes.set_ylabel(ylabel)\n axes.set_title(title)\n\n\ndef comp_profile(axes, dycoms_var, converted_monc, colour_dycoms, colour_monc, title):\n # Average\n dycoms_var[0][4].plot(y=dycoms_var[0][4].dims[0], color=colour_dycoms, ax=axes, label=\"S05 Ensemble Mean\")\n # First and third percentiles \n dycoms_var[4][4].plot(y=dycoms_var[4][4].dims[0], color=colour_dycoms, ax=axes, alpha=0.5)\n dycoms_var[5][4].plot(y=dycoms_var[5][4].dims[0], color=colour_dycoms, ax=axes, alpha=0.5)\n axes.fill_betweenx(dycoms_var[dycoms_var[0].dims[1]], dycoms_var[4][4], dycoms_var[5][4], color=colour_dycoms, alpha=0.5, label=\"S05 Ensemble 1st & 3rd percentiles\")\n # Max and min\n dycoms_var[2][4].plot(y=dycoms_var[2][4].dims[0], color=colour_dycoms, ax=axes, alpha=0.2)\n dycoms_var[3][4].plot(y=dycoms_var[3][4].dims[0], color=colour_dycoms, ax=axes, alpha=0.2)\n axes.fill_betweenx(dycoms_var[dycoms_var[0].dims[1]], dycoms_var[2][4], dycoms_var[3][4], color=colour_dycoms, alpha=0.2, label=\"S05 Ensemble Max & Min\")\n # MONC simulation\n ind1 = (np.abs(converted_monc[converted_monc.dims[0]] - 10800)).argmin() # changed this to be 4th not 5th\n ind2 = (np.abs(converted_monc[converted_monc.dims[0]] - 14040)).argmin()\n \n if len(converted_monc.dims)==2:\n line = np.mean(converted_monc[[ind1,ind2],:], axis=(0)).plot(y=converted_monc.dims[-1], color=colour_monc, label=\"MONC sim\")\n elif len(converted_monc.dims)==4:\n line = np.mean(converted_monc[[ind1,ind2],:,:,:], axis=(0,1,2)).plot(y=converted_monc.dims[-1], color=colour_monc, label=\"MONC sim\")\n \n axes.set_ylim(0, 1200)\n axes.set_xlabel(dycoms_var.name + \" [\" + dycoms_var.units + \"]\")\n axes.set_ylabel(\"Height [m]\")\n axes.set_title(title)\n\n return line\n\n\n\n# Open datasets\nnc_mnc = sys.argv[1]\nnc_dcms = \"./S05_LES.nc\"\nDS_monc = xr.open_dataset(nc_mnc)\nDS_dycoms = xr.open_dataset(nc_dcms)\n\nset_monc_colour = \"fuchsia\"\nset_dycoms_colour = \"blue\"\n\n### Find key values from options database:\n\nfor n, i in enumerate(DS_monc.options_database):\n if str(i.values[0]) == \"b'qlcrit'\":\n qlcritn = n\n elif str(i.values[0]) == \"b'rlvap'\":\n rlvapn = n\n elif str(i.values[0]) == \"b'cp'\":\n cpn = n\n\nqlcritn = 1e-5\nrlvapn = 2.47e6\ncpn = 1015.0\n\n### Cloud Boundaries ###\n#fig, axes = plt.subplots()\nfig = plt.figure(figsize=(15,12))\n#fig, ax = plt.subplots(3, 5)\n#ax = subplot2grid((3,1), (0,0), rowspan=1, colspan=1)\n#fig.add_subplot(3, 1, 1)\naxes = fig.add_subplot(3,5,1)\n# Convert clbas \nclbas_ave = np.mean(DS_monc.clbas, axis=(1,2))\n#cltop_ave = np.mean(DS_monc.cltop, axis=(1,2))\n\n# Average for cloud base and top\nDS_dycoms.zb_bar[0].plot(color=set_dycoms_colour, ax=axes)\nDS_dycoms.zi_bar[0].plot(color=set_dycoms_colour, ax=axes)\n# First and third percentiles cloud base \nDS_dycoms.zb_bar[4].plot(color=set_dycoms_colour, ax=axes, alpha=0.5)\nDS_dycoms.zb_bar[5].plot(color=set_dycoms_colour, ax=axes, alpha=0.5)\naxes.fill_between(DS_dycoms.zb_bar.time, DS_dycoms.zb_bar[4], DS_dycoms.zb_bar[5], color=set_dycoms_colour, alpha=0.5)\n# Max and min cloud base\nDS_dycoms.zb_bar[2].plot(color=set_dycoms_colour, ax=axes, alpha=0.2)\nDS_dycoms.zb_bar[3].plot(color=set_dycoms_colour, ax=axes, alpha=0.2)\naxes.fill_between(DS_dycoms.zb_bar.time, DS_dycoms.zb_bar[2], DS_dycoms.zb_bar[3], color=set_dycoms_colour, alpha=0.2)\n# First and third percentiles cloud top\nDS_dycoms.zi_bar[4].plot(color=set_dycoms_colour, ax=axes, alpha=0.5)\nDS_dycoms.zi_bar[5].plot(color=set_dycoms_colour, ax=axes, alpha=0.5)\naxes.fill_between(DS_dycoms.zi_bar.time, DS_dycoms.zi_bar[4], DS_dycoms.zi_bar[5], color=set_dycoms_colour, alpha=0.5)\n# Max and min cloud top\nDS_dycoms.zi_bar[2].plot(color=set_dycoms_colour, ax=axes, alpha=0.2)\nDS_dycoms.zi_bar[3].plot(color=set_dycoms_colour, ax=axes, alpha=0.2)\naxes.fill_between(DS_dycoms.zi_bar.time, DS_dycoms.zi_bar[2], DS_dycoms.zi_bar[3], color=set_dycoms_colour, alpha=0.2)\n\n# MONC simulation\nclbas_ave.plot(color=set_monc_colour, ax=axes)\n#cltop_ave.plot(color=set_monc_colour, ax=axes)\n\naxes.set_ylim(0, 1000)\naxes.set_xlabel(\"Time [s]\")\naxes.set_ylabel(\"Height [m]\")\naxes.set_title(\"Cloud Boundaries\")\n\n\n### Inversion height ### --- based on 8 g/kg isoline\nqt=DS_monc.q_vapour + DS_monc.q_cloud_liquid_mass + DS_monc.q_rain_mass\nqt_avexy=np.mean(qt, axis=(1,2))\nt=qt_avexy.dims[0]\ntimeseries=qt_avexy[t]\nindices = []\n\n# find index in each time step closest to isoline\nfor time in qt_avexy:\n idx = np.abs(time - 0.008).argmin()\n indices.append(int(idx.values))\n\n# find corresponding height\nheight = []\nfor i in indices:\n height.append(int(qt_avexy[qt_avexy.dims[1]][i].values))\n\n# plot heights\nplt.plot(qt_avexy[qt_avexy.dims[0]], height, color=set_monc_colour)\n#plt.savefig(\"Cloudboundaries.png\")\n#plt.show()\n\n\n### LWP ###\n#fig, axes = plt.subplots()\naxes = fig.add_subplot(3, 5, 2)\n# Convert lwp_mean\nclbas_avex = np.mean(DS_monc.clbas, axis=1)\nlwp_mean_gkg = DS_monc.LWP_mean*1000\n\ncompare(axes, DS_dycoms.lwp_bar, lwp_mean_gkg, set_dycoms_colour, set_monc_colour, \"Liquid Water Path\", 80, \"LWP [g kg^(-1)]\")\n#plt.legend()\n#plt.savefig(\"LWP_comp.png\")\n#plt.show() \n\n\n### Cloud Fraction ### --- this depends on qlcrit being index 243 in options database \n#fig, axes = plt.subplots()\naxes = fig.add_subplot(3, 5, 3)\n#real_cfrac = np.mean(np.mean(DS_monc.q_cloud_liquid_mass>=float(qlcritn), axis=3)>0.0, axis=(1,2))\nsumz = DS_monc.q_cloud_liquid_mass.sum(dim=\"z\")\nreal_cfrac = sumz.where(sumz.values < 1e-5, 1).where(sumz.values > 1e-5, 0).mean(dim=[\"x\",\"y\"])[:10]\ncompare(axes, DS_dycoms.cfrac, real_cfrac, set_dycoms_colour, set_monc_colour, \"Cloud Fraction\", 1, \"Cloud Fraction [%]\")\n#plt.savefig(\"cloudfrac.png\")\n#plt.show()\n\n###mibs_cfrac1 = np.mean(((DS_monc.q_cloud_liquid_number.sum(dim=\"z\")>=1)+0), axis=(1,2))\n###fig, axes = plt.subplots()\n###mibs_cfrac2 = np.mean(DS_monc.total_cloud_fraction, axis=1)\n###compare(axes, DS_dycoms.cfrac, mibs_cfrac2, set_dycoms_colour, set_monc_colour, \"Cloud Fraction 2\", 1, \"Cloud Fraction [%]\")\n### TKE ###\n#fig, axes = plt.subplots()\naxes = fig.add_subplot(3, 5, 4)\ntke_mean = (DS_monc.reske_mean + DS_monc.subke_mean)*1000 # sum of averages = average of sum\ncompare(axes, DS_dycoms.tke, tke_mean, set_dycoms_colour, set_monc_colour, \"TKE\", 1000, \"tke\")\n#plt.savefig(\"tke.png\")\n#plt.show()\n#\n#### Heat Flux ###\n#fig, axes = plt.subplots()\n#compare(axes, DS_dycoms.lhf_bar, DS_monc.lathf_mean, set_dycoms_colour, set_monc_colour, \"Latent Heat Flux\", 120, \"Latent Heat Flux [W m^(-2)]\")\n#plt.savefig(\"latflux.png\")\n#plt.show()\n#\n#fig, axes = plt.subplots()\n#compare(axes, DS_dycoms.shf_bar, DS_monc.senhf_mean, set_dycoms_colour, set_monc_colour, \"Sensible Heat Flux\", 120, \"Sensible Heat Flux [W m^(-2)]\")\n#plt.savefig(\"senflux.png\")\n#plt.show()\n#\n#plt.show()\n### Winds ###\n#fig, axes = plt.subplots()\n\naxes = fig.add_subplot(3,5,6)\ncomp_profile(axes, DS_dycoms.u, DS_monc.u, set_dycoms_colour, set_monc_colour, \"U Mean Wind\")\n#plt.savefig(\"uwind.png\")\n#plt.show()\n\n#fig, axes = plt.subplots()\naxes = fig.add_subplot(3,5,7)\ncomp_profile(axes, DS_dycoms.v, DS_monc.v, set_dycoms_colour, set_monc_colour, \"V Mean Wind\")\n#plt.savefig(\"vwind.png\")\n#plt.show()\n\n\n### Liquid potential temperature ###\nindex_list=[0, 1, 2, 3, 5, 6]\nthref_reduce=[]\nfor i in index_list:\n thref_reduce.append(DS_monc.thref[i])\n\nabsolute_T = np.mean(DS_monc.th[:6], axis=(1,2)) + thref_reduce\nmean_abs_T = np.mean(absolute_T[4:5], axis=0) # average over 4th hour so lpot calc will be with the 4th hour absT but shouldn't matter for the rest since only taking the 4th hour anyway.\n\n#fig, axes = plt.subplots()\naxes = fig.add_subplot(3,5,8)\ntheta=DS_monc.theta_mean\nlpot=theta - (float(rlvapn)*theta/(float(cpn)*mean_abs_T))*DS_monc.liquid_mmr_mean\ncomp_profile(axes, DS_dycoms.thetal, lpot, set_dycoms_colour, set_monc_colour, \"Theta_l\")\n#plt.savefig(\"thetal.png\")\n#plt.show()\n\n'''\n# Calculating theta from thetal values:\nthetatop = 297.5 + (1500 - 840)**(1/3)\nthetal = [289, 289, 299, thetatop]\nT = 289\nrl = [0.0, 0.000475, 0.0, 0.0]\ntheta = []\nfor i, n in enumerate(thetal):\n theta.append(n*(1 - (2.47e6/1015.0)*(float(rl[i])/T)))\n\n# note that when cloud_liquid_mass profile is false then rl is all 0 so just is potential temp.\n'''\n\n\n\n#### Density ###\n#fig, axes = plt.subplots()\n#comp_profile(axes, DS_dycoms.dn0, DS_monc.rho, set_dycoms_colour, set_monc_colour, \"Density [kg m^(-3)]\")\n#plt.show()\n#plt.savefig(\"density.png\")\n#\n### Liquid Water Mixing Ratio ###\n#fig, axes = plt.subplots()\naxes = fig.add_subplot(3,5,9)\nmonc_lmmr = DS_monc.liquid_mmr_mean*1000\ncomp_profile(axes, DS_dycoms.rl, monc_lmmr, set_dycoms_colour, set_monc_colour, \"Liquid Mass Mixing Ratio\")\n#plt.savefig(\"liquidmmr.png\")\n#plt.show()\n\n\n### Total mass mixing ratio ###\n#fig,axes = plt.subplots()\naxes = fig.add_subplot(3,5,10)\ntotal_mmr=DS_monc.q_vapour + DS_monc.q_cloud_liquid_mass + DS_monc.q_rain_mass\ntotal_mmr_mean=DS_monc.vapour_mmr_mean + DS_monc.liquid_mmr_mean\ncomp_profile(axes, DS_dycoms.rt, total_mmr*1000, set_dycoms_colour, set_monc_colour, \"Total Mass Mixing Ratio - q fields\")\ncomp_profile(axes, DS_dycoms.rt, total_mmr_mean*1000, set_dycoms_colour, \"orange\", \"Total Mass Mixing Ratio\")\n#plt.savefig(\"totalmmr.png\")\n#plt.show()\n\n### u variance ###\n#fig, axes = plt.subplots()\naxes = fig.add_subplot(3,5,11)\ncomp_profile(axes, DS_dycoms.u_var, DS_monc.uu_mean, set_dycoms_colour, set_monc_colour, \"uu variance\")\n#plt.savefig(\"uvar.png\")\n#plt.show()\n\n### v variance ###\n#fig, axes = plt.subplots()\naxes = fig.add_subplot(3,5,12)\ncomp_profile(axes, DS_dycoms.v_var, DS_monc.vv_mean, set_dycoms_colour, set_monc_colour, \"vv variance\")\n#plt.savefig(\"vvar.png\")\n#plt.show()\n\n### w variance ###\n#fig, axes = plt.subplots()\naxes = fig.add_subplot(3,5,13)\ncomp_profile(axes, DS_dycoms.w_var, DS_monc.ww_mean, set_dycoms_colour, set_monc_colour, \"w variance\")\n#plt.savefig(\"wvar.png\")\n#plt.show()\n\n### w third moment ###\n#fig, axes = plt.subplots()\naxes = fig.add_subplot(3,5,14)\ncomp_profile(axes, DS_dycoms.w_skw, DS_monc.www_mean, set_dycoms_colour, set_monc_colour, \"w third moment\")\n#plt.savefig(\"wwwmean.png\")\n#plt.show()\n#\n#\n\n#### res TKE ###\n#fig, axes = plt.subplots()\n#tke = 0.5*(DS_monc.uu_mean + DS_monc.vv_mean + DS_monc.ww_mean)\n#tkeres_mean = tke - DS_monc.tkesg_mean\n#comp_profile(axes, DS_dycoms.E, tkeres_mean, set_dycoms_colour, set_monc_colour, \"Resolved TKE\")\n#plt.savefig(\"restke.png\")\n#plt.show()\n#\n#### sfs TKE ###\n#fig, axes = plt.subplots()\n#comp_profile(axes, DS_dycoms.e, DS_monc.tkesg_mean, set_dycoms_colour, set_monc_colour, \"Subfilter TKE\")\n#plt.savefig(\"subtke.png\")\n#plt.show()\n#\n#\n#### Shear ###\n#fig, axes = plt.subplots()\n##sheartmp=DS_monc.resolved_shear_production + DS_monc.subgrid_shear_stress\n#comp_profile(axes, DS_dycoms.shr_prd, DS_monc.resolved_shear_production, set_dycoms_colour, set_monc_colour, \"Shear Production\")\n##comp_profile(axes, DS_dycoms.shr_prd, DS_monc.subgrid_shear_stress, set_dycoms_colour, set_monc_colour, \"Shear Production\")\n##comp_profile(axes, DS_dycoms.shr_prd, sheartmp, set_dycoms_colour, set_monc_colour, \"Shear Production\")\n#plt.savefig(\"shear\")\n#plt.show()\n#\n#\n### Buoyancy ###\n#fig, axes = plt.subplots()\naxes = fig.add_subplot(3,5,15)\ncomp_profile(axes, DS_dycoms.boy_prd, DS_monc.resolved_buoyant_production, set_dycoms_colour, set_monc_colour, \"Buoyant Production\")\n#plt.savefig(\"buoyancy\")\n#plt.show()\n#\n#### sfs Buoyancy flux ### --- not confident about this\n#fig, axes = plt.subplots()\n#sfs_boy = DS_monc.uw_buoyancy + DS_monc.vw_buoyancy + DS_monc.ww_buoyancy\n#comp_profile(axes, DS_dycoms.sfs_boy, sfs_boy, set_dycoms_colour, set_monc_colour, \"Subfilter Buoyancy Flux\")\n#plt.show()\n#\n#\n#### Transport ### --- not confident about this\n#fig, axes = plt.subplots()\n#transport = DS_monc.pressure_transport + DS_monc.resolved_turbulent_transport\n#comp_profile(axes, DS_dycoms.transport, transport, set_dycoms_colour, set_monc_colour, \"Resolved transport\")\n#comp_profile(axes, DS_dycoms.transport, DS_monc.pressure_transport, set_dycoms_colour, set_monc_colour, \"Resolved transport\")\n#comp_profile(axes, DS_dycoms.transport, DS_monc.resolved_turbulent_transport, set_dycoms_colour, set_monc_colour, \"Resolved transport\")\n#plt.show()\n#\n#\n#### Dissipation ###\n#fig, axes = plt.subplots()\n#comp_profile(axes, DS_dycoms.dissipation, DS_monc.dissipation_mean, set_dycoms_colour, set_monc_colour, \"Dissipation\")\n#plt.show()\n#\n#\n#### Storage ### --- not confident about this\n#fig, axes = plt.subplots()\n#comp_profile(axes, DS_dycoms.storage, DS_monc.tke_tendency, set_dycoms_colour, set_monc_colour, \"Storage\")\n#plt.show()\nplt.tight_layout()\nplt.savefig(nc_mnc[:-3] + \"_comp.png\")\nplt.show()\n","sub_path":"dycoms_plots.py","file_name":"dycoms_plots.py","file_ext":"py","file_size_in_byte":13763,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"158653487","text":"import torch\nimport torch.nn as nn\nimport torchvision.models as models\n\n\nclass EncoderCNN(nn.Module):\n def __init__(self, embed_size):\n super(EncoderCNN, self).__init__()\n resnet = models.resnet50(pretrained=True)\n for param in resnet.parameters():\n param.requires_grad_(False)\n \n modules = list(resnet.children())[:-1]\n self.resnet = nn.Sequential(*modules)\n self.embed = nn.Linear(resnet.fc.in_features, embed_size)\n\n def forward(self, images):\n features = self.resnet(images)\n features = features.view(features.size(0), -1)\n features = self.embed(features)\n return features\n \n\nclass DecoderRNN(nn.Module):\n def __init__(self, embed_size, hidden_size, vocab_size, num_layers=1):\n super().__init__()\n self.embed_size = embed_size\n self.hidden_size = hidden_size\n self.vocab_size = vocab_size\n self.num_layers = num_layers\n \n self.embed = nn.Embedding(vocab_size, embed_size)\n self.lstm = nn.LSTM(self.embed_size, self.hidden_size, self.num_layers, dropout = 0, batch_first=True)\n \n self.fc = nn.Linear(self.hidden_size, self.vocab_size)\n \n self.init_weights()\n \n def init_weights(self):\n ''' Initialize weights for fully connected layer '''\n initrange = 0.1\n \n # Set bias tensor to all zeros\n self.fc.bias.data.fill_(0)\n # FC weights as random uniform\n self.fc.weight.data.uniform_(-1, 1)\n \n def forward(self, features, captions):\n captions = captions[:, :-1]\n captions = self.embed(captions)\n inputs = torch.cat((features.unsqueeze(1), captions), dim=1)\n outputs, _ = self.lstm(inputs)\n outputs = self.fc(outputs)\n \n return outputs\n\n def sample(self, inputs, states=None, max_len=20):\n \" accepts pre-processed image tensor (inputs) and returns predicted sentence (list of tensor ids of length max_len) \"\n output = []\n while (len(output) < max_len):\n output_i, states = self.lstm(inputs,states)\n output_i = self.fc(output_i.squeeze(dim = 1))\n _, word_index = torch.max(output_i, 1)\n output.append(word_index.cpu().numpy()[0].item())\n if (word_index == 1):\n break\n inputs = self.embed(word_index) \n inputs = inputs.unsqueeze(1)\n return output","sub_path":"model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":2465,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"432889180","text":"#!/usr/bin/env python3\n\n\"\"\" Module to test exercise2.py \"\"\"\n\n__author__ = \"Sam Novak and Jodie Church\"\n\n__copyright__ = \"2014 Sam Novak and Jodie Church\"\n__license__ = \"MIT License\"\n\n__status__ = \"Prototype\"\n\n\nimport pytest\nfrom exercise2 import checksum\n\n\ndef test_checksum():\n \"\"\"\n Inputs that are the correct format and length\n \"\"\"\n assert checksum(\"786936224306\") is True\n assert checksum(\"085392132225\") is True\n assert checksum(\"717951000841\") is False\n assert checksum(\"123456789123\") is False\n\n\ndef test_input():\n \"\"\"\n Inputs that are the incorrect format and length\n \"\"\"\n with pytest.raises(TypeError):\n checksum(1.0) # Test float\n checksum(786936224306) # Test Integer\n\n with pytest.raises(ValueError):\n checksum(\"1\") # test length of input\n checksum(\"1234567890\")\n\n","sub_path":"test_exercise2.py","file_name":"test_exercise2.py","file_ext":"py","file_size_in_byte":843,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"185862088","text":"import logging.config\nimport os\nfrom flask import Flask, Blueprint\nfrom api.restplus import api\nfrom api.heroes.heroes import heroes\nfrom api.heroes.abilities import abilities\n\n\napp = Flask(__name__)\nlogging_conf_path = os.path.normpath(os.path.join(os.path.dirname(__file__), 'logging.conf'))\nlogging.config.fileConfig(logging_conf_path)\nlog = logging.getLogger(__name__)\n\ndef configure(flask_app):\n flask_app.config['ERROR_404_HELP'] = True\n\n\ndef initialise_app(flask_app):\n # do some config\n blueprint = Blueprint('api', __name__, url_prefix='/api')\n api.init_app(blueprint)\n api.add_namespace(heroes)\n api.add_namespace(abilities)\n flask_app.register_blueprint(blueprint)\n\n\ndef main():\n log.info('Running the heroes-api')\n configure(app)\n initialise_app(app)\n app.run(debug=True)\n\n\nif __name__ == '__main__':\n main()\n\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":858,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"484481487","text":"\n\n#calss header\nclass _LANE():\n\tdef __init__(self,): \n\t\tself.name = \"LANE\"\n\t\tself.definitions = [u'a narrow road in the countryside or in a town: ', u'a special strip of a road, sports track, or swimming pool that is used to keep vehicles or competitors separate: ', u'a route across the sea or through the air that ships or aircraft regularly sail or fly along: ']\n\n\t\tself.parents = []\n\t\tself.childen = []\n\t\tself.properties = []\n\t\tself.jsondata = {}\n\n\n\t\tself.specie = 'nouns'\n\n\n\tdef run(self, obj1 = [], obj2 = []):\n\t\treturn self.jsondata\n","sub_path":"xai/brain/wordbase/nouns/_lane.py","file_name":"_lane.py","file_ext":"py","file_size_in_byte":540,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"542410531","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat Jul 6 21:12:36 2019\n\n@author: constatza\n\"\"\"\nimport matplotlib.pyplot as plt\n\nfrom fem.core.entities import Model, Node, DOFtype, Load\nfrom fem.core.assemblers import ProblemStructural, ElementMaterialOnlyStiffnessProvider\nfrom fem.core.materials import ElasticMaterial2D, StressState2D\nfrom fem.core.elements import Quad4\nfrom fem.core.solvers import LinearSystem, CholeskySolver\nimport fem.analyzers as analyzers\n\nmodel = Model()\n\nmodel.nodes_dictionary[1] = Node(ID=1, X=0.0, Y=0.0, Z=0.0)\nmodel.nodes_dictionary[2] = Node(ID=2, X=10.0, Y=0.0, Z=0.0)\nmodel.nodes_dictionary[3] = Node(ID=3, X=10.0, Y=10.0, Z=0.0)\nmodel.nodes_dictionary[4] = Node(ID=4, X=0.0, Y=10.0, Z=0.0)\n\nmodel.nodes_dictionary[1].constraints = [DOFtype.X, DOFtype.Y]\nmodel.nodes_dictionary[4].constraints = [DOFtype.X, DOFtype.Y]\n\nload1 = Load(magnitude=500, node=model.nodes_dictionary[2], DOF=DOFtype.X)\nload2 = Load(magnitude=500, node=model.nodes_dictionary[3], DOF=DOFtype.X)\nmodel.loads.append(load1)\nmodel.loads.append(load2)\n\nmaterial = ElasticMaterial2D(stress_state=StressState2D.plain_stress,\n young_modulus=3.76,\n poisson_ratio=0.3779)\n\nquad = Quad4(material=material, thickness=1)\nelement1 = Quad4(ID=1, material=material, element_type=quad, thickness=1)\nfor i in range(1,5):\n element1.add_node(model.nodes_dictionary[i])\t\t\t\n\nmodel.elements_dictionary[1] = element1\n\nmodel.connect_data_structures()\n\nlinear_system = LinearSystem(model.forces)\nsolver = CholeskySolver(linear_system)\n \nprovider = ProblemStructural(model)\nprovider.stiffness_provider = ElementMaterialOnlyStiffnessProvider()\nchild_analyzer = analyzers.Linear(solver)\nparent_analyzer = analyzers.Static(provider, child_analyzer, linear_system)\n\n\nfor i in range(20000):\n \n parent_analyzer.build_matrices()\n parent_analyzer.initialize()\n parent_analyzer.solve()\n\nu = linear_system.solution\n\n#plt.figure()\n#plt.plot(u, linestyle=' ', marker='.')\n#plt.show()","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2021,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"151270396","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport nsq\nfrom ptt_crawler import Board\n\n\ndef fetch_list(board_name, nsqd='127.0.0.1:4150', stop=None):\n '''抓取文章連結、丟 queue\n\n Options:\n --stop= 終止文章網址/ID\n --nsqd=\n '''\n\n board = Board(board_name)\n writer = nsq.Writer([nsqd])\n topic = 'ptt:' + board_name\n\n for article in board.articles():\n writer.pub(topic, article.path)\n\n\nif __name__ == '__main__':\n import clime.now\n","sub_path":"tools/fetch_list.py","file_name":"fetch_list.py","file_ext":"py","file_size_in_byte":507,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"628459023","text":"__author__ = 'Rune'\n# -*- coding: utf-8 -*-\nimport urllib.request\nimport urllib.parse\nimport bs4\nimport re\nimport codecs\nimport json\nimport unicodedata\n\ntilbudsurl = 'http://www.tilbudsugen.dk/tilbud/'\ntilbudsfilsti = \"D:/Projekter/TilbudsCrawler/OfferDetection/OfferDescription.json\"\n\ndef GetPrices(search_term, item_string, broadcategory):\n\n data = {}\n data['search_item'] = search_term\n data['organic_get_val'] = 'off'\n data['border_get_val'] = 'off'\n data['key_hole_get_val'] = 'off'\n data['order_by'] = 'price_quantity_mult'\n data['chains_string'] = 'alle'\n\n params = urllib.parse.urlencode(data)\n url = \"http://www.tilbudsugen.dk/ajax_getSearch.php\"\n\n response = urllib.request.urlopen(url+\"?%s\" %params)\n html = response.read()\n soup = bs4.BeautifulSoup(html)\n res = soup.select(\"tr\")\n tilbud = []\n\n for tablerow in res:\n if item_string in tablerow.prettify().lower() or broadcategory:\n tilbud.append(tablerow)\n\n with codecs.open('offerdata.txt', 'a', encoding=\"utf-8\") as outfile:\n for elem in tilbud:\n try:\n #print(elem.prettify())\n store = elem.contents[0].contents[0].attrs['href'].split(\"/\")[2]\n search_term = search_term\n brand = elem.contents[3].text\n amount = elem.contents[4].text\n price = elem.contents[5].text\n #http://stackoverflow.com/questions/4289331/python-extract-numbers-from-a-string\n price = re.findall(\"[-+]?\\d+[\\.]?\\d*\", price)\n price = float(price[1])\n priceamount = elem.contents[6].text.split(\"/\")[0]\n img = elem.contents[7].contents[0].attrs['src']\n jsonitemline = { 'store' : store, 'search_term' : search_term, 'brand' : brand, 'amount' : amount, 'price' : price, 'priceamount' : priceamount, 'link' : img}\n json.dump(jsonitemline, outfile, ensure_ascii=False)\n outfile.write(\"\\n\")\n except:\n continue\n\nofferfile = json.load(open(tilbudsfilsti, 'r', encoding=\"utf-8\"))\nfor line in offerfile:\n GetPrices(line['tilbudsurl'], line['tilbudsstreng'], line['bredkategori'])","sub_path":"OfferDetection/GetPrices.py","file_name":"GetPrices.py","file_ext":"py","file_size_in_byte":2224,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"600169217","text":"from tkinter import *\nfrom tkinter import messagebox\nfrom Janela_Comprador import Janela_Comprador\nfrom Finalizando_Compra import Finalizando_Compra\n\nclass Verificar_Cliente(Toplevel):\n\n def __init__(self, parent):\n\n super().__init__(parent)\n self.geometry('200x140+800+300')\n self.title('Verificar Comprador')\n self.transient(parent)\n self.grab_set()\n\n\n self.btn_pesquisar = Button(self, width=10, text='Pesquisar', command = lambda: self.pesquisar(self.findlist(self.format(self.readfile('Cadastro_Comprador')), self.txt_cpf.get())))\n\n self.lbl_cpf = Label(self, width=10, text='CPF')\n\n self.txt_cpf = Entry(self,width=20)\n\n self.btn_pesquisar.place(x=50, y=100)\n\n self.lbl_cpf.place(x= -10, y=50)\n\n self.txt_cpf.place(x=50, y=50)\n\n\n\n def readfile(self, file):\n f = open(file, 'r')\n a = f.read()\n f.close()\n return a\n\n def format(self, a):\n s = a.split('\\n')\n for i in range(0, len(s)):\n s[i] = s[i].split(':')\n s.pop()\n return s\n\n def findlist(self, lista, id):\n for i in lista:\n if i[0] == id:\n return i\n\n return False\n\n def pesquisar(self, cpf):\n if cpf == (self.findlist(self.format(self.readfile('Cadastro_Vendedor')), cpf)):\n\n Janela_Comprador(self)\n\n else:\n Finalizando_Compra(self)\n\n def destroy(self):\n if messagebox.askokcancel('Confirmação', 'Deseja sair?'):\n super().destroy()\n\n","sub_path":"Verificar_Cliente.py","file_name":"Verificar_Cliente.py","file_ext":"py","file_size_in_byte":1551,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"262427446","text":"from django import forms\nfrom .models import Task\n\n\nclass TaskForm(forms.Form):\n text = forms.CharField(\n max_length=20\n )\n checked = forms.BooleanField(required=False)\n\n\nclass TaskModelForm(forms.ModelForm):\n class Meta:\n model = Task\n fields = [\n 'text',\n 'checked'\n ]\n labels = {\n 'text': 'Input text here'\n }\n help_texts = {\n 'text': 'input'\n }\n error_messages = {\n 'text': {\n 'max_length': 'max length'\n }\n }\n widgets = {\n # 'checked': forms.RadioSelect\n # 'text': forms.Textarea\n }\n\n def clean(self):\n text = self.data['text']\n if text == 'text':\n raise forms.ValidationError(\n {\n 'text': 'mistake text'\n }\n )\n\n # def clean_text(self):\n # text = self.cleaned_data['text']\n","sub_path":"django_proj2/myapp/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":975,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"312172305","text":"import math\nfrom random import *\n\nimport matplotlib.pyplot as plt\nimport numpy as np\n\n\nclass Strategy:\n num_strategy = 0\n def __init__(self,period=756):\n Strategy.num_strategy += 1\n self.period = period\n self.volatility = [0]\n self.volatility_freq = [0]\n self.market = [1]\n self.volatility = np.random.normal(0.0001,0.015,period)\n if max(abs(self.volatility)) > 0.1:\n self.volatility = self.volatility / max(abs(self.volatility)) * 0.1\n for i in self.volatility:\n self.market.append((self.market[-1] * (1 + i)))\n\n def start_strategy(self,start_date,end_date,frequence=5):\n self.frequence = frequence\n self.capital = [10000000000]\n self.cost = []\n self.share = [0]\n for i in range(start_date - 1,end_date):\n if i % self.frequence == 0:\n self.share.append((self.share[-1] + 10 / self.market[i]))\n self.cost.append((10 * (len(self.share) - 1) / self.share[-1]))\n self.capital.append((self.capital[-1] - 10))\n self.market_freq = [self.market[i] for i in range(start_date - 1,end_date) if i % self.frequence == 0]\n self.strategy_return = np.array(self.market_freq) / np.array(self.cost)\n\n def plot_market(self,start_date,end_date,frequence=1):\n self.market_freq = [self.market[i] for i in range(start_date - 1,end_date) if i % frequence == 0]\n plt.plot(self.market_freq)\n plt.show()\n\n def plot_compare(self,start_date,end_date):\n self.market_freq = [self.market[i] for i in range(start_date - 1,end_date) if i % self.frequence == 0]\n plt.plot(self.cost)\n plt.plot(self.market_freq)\n plt.plot(np.array(self.market_freq) / np.array(self.cost))\n plt.legend(['strategy','market','alpha'])\n plt.show()\n\n def plot_volatility(self,frequence=1):\n self.volatility_freq = [self.volatility[i] for i in range(self.period) if i % frequence == 0]\n plt.hist(self.volatility_freq,bins=round(math.sqrt(self.period)))\n plt.show()\n\nif __name__=='__main__':\n period = 10000\n s1 = Strategy(period)\n s1.plot_market(1,period,50)\n # s1.start_strategy(1,756,3)\n # s1.plot_strategy()\n # s1.plot_compare(1,756)\n # s1.plot_volatility()\n","sub_path":"strategy.py","file_name":"strategy.py","file_ext":"py","file_size_in_byte":2309,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"543339911","text":"# -*- coding: UTF-8 -*-\nfrom flask import Flask, request, render_template\nfrom werkzeug.utils import secure_filename\nfrom model import db\nfrom model import Webrtc\nimport uuid\nimport os\nimport subprocess\nimport json\n\n\napp = Flask(__name__)\n\n\n@app.route('/audiovideo')\ndef upload_file():\n return render_template('index.html')\n\n\n@app.route('/audiovideo', methods=['GET', 'POST'])\ndef audiovideo():\n if request.method == 'POST':\n # 將影像存成.webm\n print(request.data)\n print(request.files)\n file = request.files['audiovideo']\n uuidName = str(uuid.uuid1())\n filename_webm = uuidName + \".mkv\"\n filename = secure_filename(filename_webm)\n file_save_path = os.path.join('.', 'static', 'uploads', filename_webm)\n file.save(file_save_path)\n\n # 轉檔 webm->mkv H.264\n '''\n outFile = uuidName + \".mkv\"\n upload_path_mkv = os.path.join('.', 'static', 'uploads', outFile)\n subprocess.call(['ffmpeg', '-i', file_save_path, upload_path_mkv])\n '''\n\n # 寫入\n names = Webrtc(uuidName)\n db.session.add(names)\n db.session.commit()\n\n return \"susses\"\n\n\nif __name__ == \"__main__\":\n app.run(host=\"0.0.0.0\", port=8882, ssl_context=(\n \"./rtc-video-room-cert.pem\",\n \"./rtc-video-room-key.pem\"\n ))\n","sub_path":"webRTC_upload_viedo/app_offline_transfer_sqlite.py","file_name":"app_offline_transfer_sqlite.py","file_ext":"py","file_size_in_byte":1337,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"502954720","text":"import socket\nimport sys\nimport random\nimport re\nfrom bot_commands import parseXML\nfrom bot_commands import writeXML\nfrom bot_commands import delXML\nfrom config import *\nfrom time import sleep\n\n\nclass IRC:\n def __init__(self):\n self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n self.readbuffer = \"\"\n\n def connect(self):\n print(\"CONNECTING\")\n self.socket.connect((HOST, PORT))\n self.socket.send(bytes(\"PASS {}\\r\\n\".format(PASS), \"UTF-8\"))\n self.socket.send(bytes(\"NICK {}\\r\\n\".format(NICK), \"UTF-8\"))\n self.socket.send(bytes(\"USER {} {} bla :{}\\r\\n\".format(NICK, NICK, NICK), \"UTF-8\"))\n self.socket.send(bytes(\"CAP REQ :twitch.tv/membership\\r\\n\", \"UTF-8\"))\n self.socket.send(bytes(\"CAP REQ :twitch.tv/commands\\r\\n\", \"UTF-8\"))\n self.socket.send(bytes(\"CAP REQ :twitch.tv/tags\\r\\n\", \"UTF-8\"))\n self.socket.send(bytes(\"JOIN #{}\\r\\n\".format(CHAN), \"UTF-8\"));\n print(\"CONNECTED\")\n\n def send(self, msg):\n # print(\"{}: {}\".format(self.name, msg))\n self.socket.send(bytes(\"PRIVMSG #{} : {}\\r\\n\".format(CHAN, msg), \"UTF-8\"))\n\n def join(self, channel):\n self.socket.send(bytes(\"JOIN {}\\r\\n\".format(channel), \"UTF-8\"))\n\n def part(self, channel):\n self.socket.send(bytes(\"PART {}\\r\\n\".format(channel), \"UTF-8\"))\n\n def op(self, user, channel):\n self.socket.send(bytes(\"MODE {} +o {}\\r\\n\".format(user, channel), \"UTF-8\"))\n\n def deop(self, user, channel):\n self.socket.send(bytes(\"MODE {} -o {}\\r\\n\".format(user, channel), \"UTF-8\"))\n\n def voice(self, user, channel):\n self.socket.send(bytes(\"MODE {} +v {}\\r\\n\".format(user, channel), \"UTF-8\"))\n\n def devoice(self, user, channel):\n self.socket.send(bytes(\"MODE {} -v {}\\r\\n\".format(user, channel), \"UTF-8\"))\n\n def addcommand(self, command, msg):\n commands = parseXML(\"commands.xml\", CHAN)\n if command not in commands:\n commands[command] = msg\n writeXML(command,msg, CHAN)\n self.send(\"{0} has been created!\".format(command))\n else:\n self.send(\"{0} already exists!\".format(command))\n\n def delcommand(self, command):\n commands = parseXML(\"commands.xml\", CHAN)\n if command in commands:\n delXML(command, CHAN)\n self.send(\"{0} has been deleted!\".format(command))\n else:\n self.send(\"{0} doesn't exist!\".format(command))\n def editcommand(self, command, newmsg):\n commands = parseXML(\"commands.xml\", CHAN)\n if command in commands:\n delXML(command, CHAN)\n writeXML(command, newmsg, CHAN)\n self.send(\"{0} has been edited!\".format(command))\n else:\n self.send(\"{0} doesn't exist!\".format(command))\n\n def run(self):\n self.connect()\n MODT = False\n while True:\n self.readbuffer = self.readbuffer + self.socket.recv(1024).decode(\"UTF-8\")\n temp = str.split(self.readbuffer, \"\\n\")\n self.readbuffer=temp.pop()\n\n for line in temp:\n #print(line)\n # Checks whether the message is PING because its a method of Twitch to check if you're afk\n if (line[0:4] == \"PING\"):\n self.socket.send(bytes(\"PONG %s\\r\\n\" % line[5::], \"UTF-8\"))\n else:\n # Splits the given string so we can work with it better\n parts = line.split(\":\")\n\n if \"QUIT\" not in parts[1] and \"JOIN\" not in parts[1] and \"PART\" not in parts[1]:\n try:\n # Sets the message variable to the actual message sent\n message = parts[2][:len(parts[2]) - 1]\n except:\n message = \"\"\n # Sets the username variable to the actual username\n usernamesplit = parts[1].split(\"!\")\n username = usernamesplit[0]\n\n # Only works after twitch is done announcing stuff (MODT = Message of the day)\n if MODT:\n print(username + \": \" + message)\n\n # You can add all your plain commands here\n command = message.split(\" \")[0]\n commands = parseXML(\"commands.xml\", CHAN)\n\n if \"cloudGasm\" in message:\n self.send(\"cloudGasm\")\n\n if command in commands.keys():\n self.send(commands[command].replace(\"[user]\", username))\n\n if command == \"!commands\":\n c = \"\"\n for cur_command in commands.keys():\n c += \"{}, \".format(cur_command)\n self.send(\"{} the commands for {} are {}\".format(username, CHAN, c))\n\n if command == \"!benry\":\n self.send(\"Have a happy Benry {}!\".format(username))\n if command == \"!hug\":\n self.send(\"{} hugs {}\".format(username, message.replace(command, \"\")))\n if command == \"!kawaii\":\n kawaii = random.randint(0, 10)\n if kawaii < 5 and kawaii > 2:\n self.send(\"{} is Kawaii~desu ʕ༼◕ ౪ ◕✿༽ʔ\".format(username))\n else:\n self.send(\"{} is not Kawaii~desu ლ(ಥ Д ಥ )ლ)\".format(username))\n if command == \"!spam\" and username == \"rave340\":\n for i in range(15):\n self.send(message.replace(command, \"\"))\n if command == \"!ravebot\":\n self.send(\"I am ravebot 3.0, created by twitter.com/rave340, fear me {}!\".format(username))\n if VULGAR:\n if command == \"!swag\":\n self.send(\"Fuck you {}!\".format(username))\n if \"user-type=mod\" in line:\n if command == \"!addcommand\":\n self.addcommand(message.split(\" \")[1], \" \".join(message.split(\" \")[2::]))\n if command == \"!delcommand\":\n self.delcommand(message.split(\" \")[1])\n if command == \"!editcommand\":\n self.editcommand(message.split(\" \")[1], \" \".join(message.split(\" \")[2::]))\n\n for l in parts:\n if \"End of /NAMES list\" in l:\n MODT = True\n sleep(1/RATE)\ndef main():\n ravebot = IRC()\n ravebot.run()\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"src/bot.py","file_name":"bot.py","file_ext":"py","file_size_in_byte":7097,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"143098751","text":"\nimport os\nimport math\n\n\n# 创建文件夹\ndef mkdir(path):\n try:\n os.makedirs(path)\n except:\n pass\n\n\n# 找出文件夹下所有文件\ndef listfiles(rootdir, prefix='.xml'):\n file = []\n for parent, dirnames, filenames in os.walk(rootdir):\n if parent == rootdir:\n for filename in filenames:\n if filename.endswith(prefix):\n file.append(rootdir + filename)\n return file\n else:\n pass\n\n\n# 夹角公式\nclass VectorCompare:\n # 计算矢量大小\n # 计算平方和\n def magnitude(self, concordance):\n total = 0\n for word, count in concordance.items():\n total += count ** 2\n return math.sqrt(total)\n\n # 计算矢量之间的 cos 值\n def relation(self, concordance1, concordance2):\n topvalue = 0\n for word, count in concordance1.items():\n if word in concordance2:\n # 计算相乘的和\n topvalue += count * concordance2[word]\n return topvalue / (self.magnitude(concordance1) * self.magnitude(concordance2))\n\n\n# 将图片转换为矢量\ndef buildvector(im):\n d1 = {}\n count = 0\n for i in im.getdata():\n d1[count] = i\n count += 1\n return d1\n\n\n# 生成所有的字母\ndef gen_all_letters(case_sensitive = False):\n low_set = [chr(x) for x in range(ord('a'), ord('z') + 1)]\n up_set = []\n if case_sensitive:\n up_set = [chr(x) for x in range(ord('A'), ord('Z') + 1)]\n return low_set + up_set\n\n","sub_path":"src/util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":1540,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"407666836","text":"import matplotlib\nmatplotlib.use('Agg')\nimport numpy as np\nfrom fanova import fANOVA\nimport fanova.visualizer\nimport matplotlib.pyplot as plt\nimport ConfigSpace\nfrom ConfigSpace.hyperparameters import UniformFloatHyperparameter\n\nimport os\npath = os.path.dirname(os.path.realpath(__file__))\n\nresponse_type = 'time'\n\n# directory in which you can find all plots\nplot_dir = path + '/test_plots_'+response_type\n\n# artificial dataset (here: features)\nfeatures = np.loadtxt(path + '/scmnist-features.csv', delimiter=\",\")\nresponses = np.loadtxt(path + '/scmnist-responses-'+response_type+'.csv', delimiter=\",\")\n\ndef get_hyperparameter_search_space(seed=None):\n \"\"\"\n Neural Network search space based on a best effort using the scikit-learn\n implementation. Note that for state of the art performance, other packages\n could be preferred.\n\n Parameters\n ----------\n seed: int\n Random seed that will be used to sample random configurations\n\n Returns\n -------\n cs: ConfigSpace.ConfigurationSpace\n The configuration space object\n \"\"\"\n cs = ConfigSpace.ConfigurationSpace('ResNet18_classifier', seed)\n # batch_size = ConfigSpace.UniformIntegerHyperparameter(\n # name='batch_size', lower=1, upper=256, log=True, default_value=128)\n # learning_rate = ConfigSpace.CategoricalHyperparameter(\n # name='learning_rate', choices=['constant', 'invscaling', 'adaptive'], default_value='constant')\n learning_rate_init = ConfigSpace.UniformFloatHyperparameter(\n name='learning_rate_init', lower=1e-6, upper=1, log=True, default_value=1e-1)\n\n epochs = ConfigSpace.UniformIntegerHyperparameter(\n name='epochs', lower=1, upper=200, default_value=150)\n batch_size = ConfigSpace.CategoricalHyperparameter(\n name='batch_size', choices=[32, 64, 128, 256, 512], default_value=128)\n # shuffle = ConfigSpace.CategoricalHyperparameter(\n # name='shuffle', choices=[True, False], default_value=True)\n momentum = ConfigSpace.UniformFloatHyperparameter(\n name='momentum', lower=0, upper=1, default_value=0.9)\n weight_decay = ConfigSpace.UniformFloatHyperparameter(\n name='weight_decay', lower=1e-6, upper=1e-2, log=True, default_value=5e-4)\n\n cs.add_hyperparameters([\n batch_size,\n learning_rate_init,\n epochs,\n # shuffle,\n momentum,\n weight_decay,\n ])\n\n return cs\n\ncs = get_hyperparameter_search_space()\n\n# create an instance of fanova with trained forest and ConfigSpace\nf = fANOVA(X = features, Y = responses, config_space=cs, n_trees=16, seed=7)\n\n# marginal of particular parameter:\n# dims = (1, )\n# res = f.quantify_importance(dims)\n# print(res)\n\n# visualizations:\n# first create an instance of the visualizer with fanova object and configspace\nvis = fanova.visualizer.Visualizer(f, cs, plot_dir)\n# plot marginals for each parameter\nfor i in range(5):\n\tvis.plot_marginal(i, show=False)\n\tplt.savefig(plot_dir+'/'+str(i)+'.png')\n\tplt.clf()\n","sub_path":"fanova/5param/fanova-run-scmnist.py","file_name":"fanova-run-scmnist.py","file_ext":"py","file_size_in_byte":2982,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"632197750","text":"import time\r\nimport paho.mqtt.client as mqtt\r\nimport Adafruit_DHT\r\n\r\nMQTT_HOST = \"maqiatto.com\"\r\nMQTT_PORT = 1883\r\nMQTT_KEEPALIVE_INTERVAL = 60\r\nMQTT_TOPIC = \"gapple95@naver.com/harang\"\r\n\r\nsensor = Adafruit_DHT.DHT11\r\ndht_pin = 2\r\n\r\ndef on_publish(client, userdata, mid):\r\n print(\"Message Published...\")\r\n\r\nclient = mqtt.Client()\r\n\r\n# Register publish callback function\r\nclient.on_publish = on_publish\r\n\r\n# Connect with MQTT Broker\r\nclient.username_pw_set(\"gapple95@naver.com\",\"jhj1530314q@\");\r\nclient.connect(MQTT_HOST, MQTT_PORT, MQTT_KEEPALIVE_INTERVAL)\r\n\r\nwhile True:\r\n try:\r\n time.sleep(1)\r\n hum, temp = Adafruit_DHT.read_retry(sensor, dht_pin)\r\n value = '{{\"temp\": {}, \"humid\": {} }}'.format(temp, hum)\r\n client.publish(MQTT_TOPIC, value)\r\n print(value)\r\n\r\n except KeyboardInterrupt:\r\n break\r\n\r\nclient.loop_forever()\r\n\r\nclient.disconnect()\r\n","sub_path":"exercise/mqtt/pub-dht.py","file_name":"pub-dht.py","file_ext":"py","file_size_in_byte":898,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"252508543","text":"# -*- coding: utf-8 -*-\n# @Time : 2021/8/19 下午8:41\n# @Author : WuDiDaBinGe\n# @FileName: config.py\n# @Software: PyCharm\nimport time\n\nimport torch\nimport gensim\nimport numpy as np\nfrom tensorboardX import SummaryWriter\n\n\nclass Topic_Config(object):\n def __init__(self, dataset):\n self.vocab_path = '../dataset/vocab.txt'\n self.device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') # 设备\n self.train_path = dataset + '/datagrand_2021_train.csv' # 训练集\n self.test_path = dataset + '/datagrand_2021_test.csv'\n self.log_path = dataset + '/log/wtm/'\n self.writer = SummaryWriter(self.log_path + time.strftime('%m-%d_%H.%M', time.localtime()))\n self.save_path = dataset + '/saved_dict/wae/' + time.strftime('%m-%d_%H.%M',\n time.localtime()) + '.ckpt' # 模型训练结果\n # train's hyper parameter\n self.n_topic = 10\n self.batch_size = 512\n self.epoch = 10000\n self.lr = 1e-3\n self.dist = 'gmm-ctm'\n self.beta = 1.0\n self.dropout = 0.0\n","sub_path":"config/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":1141,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"298606000","text":"# Copyright 2021 Google LLC\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\"\"\"Common utility functions for ML modules.\"\"\"\nfrom typing import Dict, Union\n\nimport numpy as np\n\n\ndef assert_label_values_are_valid(labels: np.ndarray) -> None:\n \"\"\"Asserts whether labels contains both and only 1.0 and 0.0 values.\n\n Args:\n labels: An array of true binary labels represented by 1.0 and 0.0.\n \"\"\"\n assert set(labels) == {\n 0.0, 1.0\n }, ('labels should contain both and only 1.0 and 0.0 values.')\n\n\ndef assert_prediction_values_are_valid(predictions: np.ndarray) -> None:\n \"\"\"Asserts predictions contains values between 0.0 and 1.0.\n\n Args:\n predictions: An array of predicted probabilities between 0.0 and 1.0.\n \"\"\"\n assert ((0.0 <= min(predictions)) and (max(predictions) <= 1.0)), (\n 'probability_predictions should only contain values between 0.0 and 1.0')\n\n\ndef assert_label_and_prediction_length_match(labels: np.ndarray,\n predictions: np.ndarray) -> None:\n \"\"\"Asserts labels and predictions have the same length.\n\n Args:\n labels: An array of true binary labels represented by 1.0 and 0.0.\n predictions: An array of predicted probabilities between 0.0 and 1.0.\n \"\"\"\n assert len(labels) == len(predictions), (\n 'labels and predictions should have the same length')\n\n\ndef read_file(file_path: str) -> str:\n \"\"\"Reads and returns contents of the file.\n\n Args:\n file_path: File path.\n\n Returns:\n content: File content.\n\n Raises:\n FileNotFoundError: If the provided file is not found.\n \"\"\"\n try:\n with open(file_path, 'r') as stream:\n content = stream.read()\n except FileNotFoundError:\n raise FileNotFoundError(f'The file \"{file_path}\" could not be found.')\n else:\n return content\n\n\ndef configure_sql(sql_path: str, query_params: Dict[str, Union[str, int,\n float]]) -> str:\n \"\"\"Configures parameters of SQL script with variables supplied from Airflow.\n\n Args:\n sql_path: Path to SQL script.\n query_params: Configuration containing query parameter values.\n\n Returns:\n sql_script: String representation of SQL script with parameters assigned.\n \"\"\"\n sql_script = read_file(sql_path)\n\n params = {}\n for param_key, param_value in query_params.items():\n # If given value is list of strings (ex. 'a,b,c'), create tuple of\n # strings (ex. ('a', 'b', 'c')) to pass to SQL IN operator.\n if isinstance(param_value, str) and ',' in param_value:\n params[param_key] = tuple(param_value.split(','))\n else:\n params[param_key] = param_value\n\n return sql_script.format(**params)\n","sub_path":"py/gps_building_blocks/ml/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":3170,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"262739759","text":"class Vote:\n votes = dict()\n ballots = list(list())\n\n def __init__(self, voteList):\n self.ballots = voteList\n\n def computeWinners(self):\n for vote in self.ballots:\n for mark in vote:\n self.votes[mark] = 0\n for vote in self.ballots:\n for mark in vote:\n if mark not in self.votes:\n self.votes[mark] = 0\n self.votes[mark] += 1\n\n def getWinners(self):\n return self.votes\n","sub_path":"vote_summation.py","file_name":"vote_summation.py","file_ext":"py","file_size_in_byte":496,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"117544487","text":"# $Id: BAMBUProd_AODSIMtauembedded.py,v 1.7 2013/05/06 18:23:22 pharris Exp $\n\nimport FWCore.ParameterSet.Config as cms\n\nprocess = cms.Process('FILLER')\n\n# import of standard configurations\nprocess.load('Configuration/StandardSequences/Services_cff')\nprocess.load('FWCore/MessageService/MessageLogger_cfi')\nprocess.load('Configuration.StandardSequences.GeometryDB_cff')\nprocess.load('Configuration/StandardSequences/MagneticField_38T_cff')\nprocess.load('Configuration/StandardSequences/FrontierConditions_GlobalTag_cff')\nprocess.load('Configuration/EventContent/EventContent_cff')\n\nprocess.configurationMetadata = cms.untracked.PSet(\n version = cms.untracked.string('Mit_029'),\n annotation = cms.untracked.string('AODSIM'),\n name = cms.untracked.string('BambuProduction')\n)\n\nprocess.maxEvents = cms.untracked.PSet(\n input = cms.untracked.int32(-1)\n)\n\nprocess.options = cms.untracked.PSet(\n Rethrow = cms.untracked.vstring('ProductNotFound'),\n fileMode = cms.untracked.string('NOMERGE'),\n)\n\n# input source\nprocess.source = cms.Source(\"PoolSource\",\n fileNames = cms.untracked.vstring('/store/results/higgs/DoubleMuParked/StoreResults-Run2012D_22Jan2013_v1_RHembedded_trans1_tau115_ptelec1_20had1_18_v1-f456bdbb960236e5c696adfe9b04eaae/DoubleMuParked/USER/StoreResults-Run2012D_22Jan2013_v1_RHembedded_trans1_tau115_ptelec1_20had1_18_v1-f456bdbb960236e5c696adfe9b04eaae/0000/1AB39CBC-B7B0-E211-BDE0-00266CF3DFE0.root')\n)\n#process.source.inputCommands = cms.untracked.vstring(\"keep *\",\n# \"drop *_MEtoEDMConverter_*_*\",\n# \"drop L1GlobalTriggerObjectMapRecord_hltL1GtObjectMap__HLT\")\n\n# other statements\nprocess.GlobalTag.globaltag = 'START53_V15::All'\n\nprocess.add_(cms.Service(\"ObjectService\"))\n\nprocess.load(\"MitProd.BAMBUSequences.BambuFillAODSIM_cfi\")\n\nprocess.MitTreeFiller.TreeWriter.fileName = 'XX-MITDATASET-XX'\n\nprocess.load('TauAnalysis/MCEmbeddingTools/embeddingKineReweight_cff')\nprocess.embeddingKineReweightRECembedding.inputFileName = cms.FileInPath('TauAnalysis/MCEmbeddingTools/data/embeddingKineReweight_recEmbedding_mutau.root')\n# process.embeddingKineReweightRECembedding.inputFileName = cms.FileInPath('TauAnalysis/MCEmbeddingTools/data/embeddingKineReweight_recEmbedding_etau.root')\n# process.embeddingKineReweightRECembedding.inputFileName = cms.FileInPath('TauAnalysis/MCEmbeddingTools/data/embeddingKineReweight_recEmbedding_emu.root')\n\nfrom MitProd.TreeFiller.filltauembedded_cff import *\nfilltauembedded(process.MitTreeFiller) \nprocess.MitTreeFiller.MergedConversions.checkTrackRef = cms.untracked.bool(False)\nprocess.MitTreeFiller.EmbedWeight.useGenInfo = True\n\nprocess.bambu_step = cms.Path(process.BambuFillAODSIM)\n\n# schedule definition\nprocess.schedule = cms.Schedule(process.bambu_step)\n\n","sub_path":"Configuration/python/BAMBUProd_AODSIMtauembedded.py","file_name":"BAMBUProd_AODSIMtauembedded.py","file_ext":"py","file_size_in_byte":2869,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"501940179","text":"import logging\n\nfrom lxml import html\nimport simplejson\n\nfrom . import util\nfrom . import helpers\nfrom .session import Session\nfrom .xpath import xpb\n\n\nlog = logging.getLogger(__name__)\n\n\n@util.n_partialable\nclass PhotoUploader(object):\n\n _uri = 'https://www.okcupid.com/ajaxuploader'\n\n def __init__(self, filename, session=None, user_id=None, authcode=None):\n self._session = session or Session.login()\n self._filename = filename\n if not (user_id and authcode):\n photo_tree = html.fromstring(self._session.okc_get(\n 'profile/{0}/photos#upload'.format(self._session.log_in_name)\n ).content)\n self._authcode = authcode or helpers.get_authcode(photo_tree)\n self._user_id = user_id or helpers.get_current_user_id(photo_tree)\n\n @property\n def pic_id(self):\n return self._response_dict['id']\n\n @property\n def height(self):\n return self._response_dict['height']\n\n @property\n def width(self):\n return self._response_dict['width']\n\n def upload(self):\n with open(self._filename, 'rb') as file_object:\n files = {'file': (self._filename, file_object,\n 'image/jpeg', {'Expires': '0'})}\n response = self._session.post(self._uri, files=files)\n response_script_text = xpb.script.get_text_(\n html.fromstring(response.content)\n )\n self._response_dict = self._get_response_json(response_script_text)\n return self._response_dict\n\n def _get_response_json(self, response_text):\n start = response_text.find('res =') + 5\n end = response_text.find('};') + 1\n response_text = response_text[start:end]\n log.info(simplejson.dumps({'photo_upload_response': response_text}))\n return simplejson.loads(response_text)\n\n @property\n def _confirm_parameters(self):\n return {\n 'userid': self._user_id,\n 'albumid': 0,\n 'authcode': self._authcode,\n 'okc_api': 1,\n 'picid': self.pic_id,\n 'picture.add_ajax': 1,\n 'use_new_upload': 1,\n 'caption': 1,\n 'height': self.height,\n 'width': self.width,\n }\n\n def confirm(self):\n return self._session.okc_get('photoupload',\n params=self._confirm_parameters)\n\n def upload_and_confirm(self):\n self.upload()\n self.confirm()\n return self._response_dict\n","sub_path":"okcupyd/photo.py","file_name":"photo.py","file_ext":"py","file_size_in_byte":2524,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"178216794","text":"import threading\nimport re\nimport socket\nfrom queue import Queue\n\n\nprint_lock=threading.Lock()\nq_target=Queue()\n\ndef portscan(target):\n s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)\n s.settimeout(2)\n try:\n print('connecting '+target)\n con=s.connect((target,22))\n with print_lock:\n device_name=re.findall(r'raspberry.+',socket.gethostbyaddr(target)[0])[0]\n if device_name=='':\n device_name=re.findall(r'+.raspberry',socket.gethostbyaddr(target)[0])[0]\n \n if device_name!='':\n print('got '+target)\n q_target.put(target)\n s.close()\n \n except:\n pass\nq=Queue()\ndef threader():\n while True:\n worker=q.get()\n portscan(worker)\n q.task_done()\n\nfor thds in range(0,8):\n t=threading.Thread(target=threader)\n t.daemon=True\n t.start()\ncounter=0\nfor subnet in range(7,254):\n for worker in range(1,254):\n host='61.177.'+str(subnet)+'.'+str(worker)\n q.put(host)\n counter+=1 \n if counter==8:\n q.join()\n counter=0\nprint(q_target.get())\n","sub_path":"portscan_rasp.py","file_name":"portscan_rasp.py","file_ext":"py","file_size_in_byte":1155,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"35154973","text":"\r\n\r\nclass Result:\r\n def __init__(self, resultId, raceId, driverId, constructorId, grid, positionOrder, points, rank):\r\n self.resultId = resultId\r\n self.raceId = raceId\r\n self.driverId = driverId\r\n self.constructorId = constructorId\r\n self.grid = grid\r\n self.positionOrder = positionOrder\r\n self.points = points\r\n self.rank = rank\r\n","sub_path":"source/model/Result.py","file_name":"Result.py","file_ext":"py","file_size_in_byte":390,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"417995925","text":"#!/usr/bin/env python\n\n# The line at the very top tells the cpu that will be excuting this job\n# which python to use and how to find it.\n# Without that line this sould just be a simple text file and you would\n# specifically need to type on the command line: python name_of_file.py\n\n# The lines below set up important parameters for the slurm scheduling system\n# The first line tells the slurm scheduler which partition to send the job to\n# The next two lines tells which account to use.\n# The last two lines with the -o and -e flags tell where to write out the\n# error and output text files. These are useful when debugging code. They\n# Are simple text files that cat be viewed with the commands cat or less.\n# The directory where these files are written must be created before otherwise\n# you won't have access to the output and error text files.\n\n#SBATCH --partition centos7_default-partition\n#SBATCH --account acc_psb6351\n#SBATCH --qos pq_psb6351\n#SBATCH -o /scratch/kcrooks/crash/preproc_o\n#SBATCH -e /scratch/kcrooks/crash/preproc_e\n\n# The following commands are specific to python programming.\n# Tools that you'll need for your code must be imported.\n# You can import modules directly without renaming them (e.g., import os)\n# Or you can import and rename things (e.g., import pandas as pd)\n# Or you can import specific features of a module (e.g., from nipype.interfaces.utility import Function)\n# It is traditional in python programming to import everything\n# you might need at the top of your script. However, the only rule\n# is modules must be imported before they are used. Also, functions code that begins with def nameoffunc(inputtofunc):\n# require importing their own modules\n\nimport os\nfrom glob import glob\n\n# Import new things that we'll need\nimport pandas as pd\nimport numpy as np\nimport nipype.interfaces.afni as afni\nimport nipype.interfaces.fsl as fsl\nimport nipype.interfaces.freesurfer as fs\nfrom nipype.interfaces.utility import Function\nimport nibabel as nb\nimport json\nimport nipype.interfaces.io as nio\nimport nipype.pipeline.engine as pe\nimport nipype.interfaces.utility as util\nimport nipype.algorithms.rapidart as rapidart\n\n# Below I am assigning a list with one string element to the variable named sid\n# I do this because I want to iterate over subject ids (aka., sids) and I want\n# to treat 021 as a whole and not as separate parts of the string which is\n# also iterable. I know this is a list because of the [] brackets\nsids = ['021']\n\n# Below I set up some important directories for getting data and writing\n# files that I won't need in the end. I use the os command path.join to\n# combine different string elements into a path strcuture that will work\n# across operating systems. The below is only quasi correct because in the last\n# string element of both the func_dir and fmap_dir variables I indicate\n# directory structures with the '/' string. This forward slash is only\n# relevant for linux and osx operating systems....windows uses something different '\\\\'\n# I am also using f string formatting to insert the first element of the\n# sids list variable into the string.\nbase_dir = '/home/kcroo010/mattfeld_2020'\nwork_dir = '/scratch/kcrooks'\nfunc_dir = os.path.join(base_dir, f'dset/sub-{sids[0]}/func')\nfmap_dir = os.path.join(base_dir, f'dset/sub-{sids[0]}/fmap')\nfs_dir = os.path.join(base_dir, 'derivatives', 'freesurfer')\n\n# Get a list of my study task json and nifti converted files\n# I am using the glob function from glob that take a string as input\n# That string can contain wildcards to grab multiple files that meet\n# the string completion. I also, use the function sorted to order them\n# so that the func_files and fmap_files are in the same order based on\n# alphanumeric numbering criteria. This is important when I get\n# specific elements from a .json file for a func file to preprocess.\n# Be careful!!!! glob will return an empty list if your wildcard\n# string completion comes up empty rather than crash. Make sure you\n# have no typos.\n# I plan to replace these lines with a nipype datagrabber soon.\nfunc_json = sorted(glob(func_dir + '/*.json'))\nfunc_files = sorted(glob(func_dir + '/*.nii.gz'))\nfmap_files = sorted(glob(fmap_dir + '/*func*.nii.gz'))\n\n# Here I am building a function that eliminates the\n# mapnode directory structure and assists in saving\n# all of the outputs into a single directory.\n# This is a function because it starts with the word def\n# and then has the functon name followed by paraentheses.\n# The name inside the parentheses is a variable name that represents\n# the input to the function. In this case I'm providing a variable\n# called func_files. I will iterate over the length of the func_files\n# variable to append tuples to a list variable called subs that have\n# the ways I want to substitute names later in the datasink. In this\n# case I am getting ride of those names so that everything is saved\n# in the same directory in the end.\ndef get_subs(func_files):\n '''Produces Name Substitutions for Each Contrast'''\n subs = []\n for curr_run in range(len(func_files)):\n subs.append(('_tshifter%d' %curr_run, ''))\n subs.append(('_volreg%d' %curr_run, ''))\n subs.append(('_smooth%d' %curr_run, ''))\n return subs\n\ndef getbtthresh(medianvals):\n \"\"\"Get the brightness threshold for SUSAN.\"\"\"\n return [0.75*val for val in medianvals]\n\ndef getusans(inlist):\n \"\"\"Return the usans at the right threshold.\"\"\"\n return [[tuple([val[0],0.75*val[1]])] for val in inlist]\n\ndef get_aparc_aseg(files):\n for name in files:\n if 'aparc+aseg' in name:\n return name\n raise ValueError('aparc+aseg.mgz not found')\n\n# Here I am building a function that takes in a\n# text file that includes the number of outliers\n# at each volume and then finds which volume (e.g., index)\n# has the minimum number of outliers (e.g., min)\n# searching over the first 201 volumes\n# If the index function returns a list because there were\n# multiple volumes with the same outlier count, pick the first one\ndef best_vol(outlier_count):\n best_vol_num = outlier_count.index(min(outlier_count[:200]))\n if isinstance(best_vol_num, list):\n best_vol_num = best_vol_num[0]\n return best_vol_num\n\n# Here I am creating a list of lists containing the slice timing for each study run\nslice_timing_list = [] # Here I define an empty list variable\nfor curr_json in func_json: # Here I am iterating over the variable func_json that was deefined above through the sorted glob\n curr_json_data = open(curr_json) # I need to open the json file\n curr_func_metadata = json.load(curr_json_data) # Then I need to load the json file\n slice_timing_list.append(curr_func_metadata['SliceTiming'])\n\n# Here I am establishing a nipype work flow that I will eventually execute\n# Code here become less python specific and more nipype specific. They share similarites\n# but have some unique pecularities to take note.\npsb6351_wf = pe.Workflow(name='psb6351_wf') # First I create a workflow...this will serve as the backbone of the pipeline\npsb6351_wf.base_dir = work_dir + f'/psb6351workdir/sub-{sids[0]}' # I define the working directory where I want preliminary files to be written\npsb6351_wf.config['execution']['use_relative_paths'] = True # I assign a execution variable to use relative paths...TRYING TO USE THIS TO FIX A BUG?\n\n# Create a Function node to substitute names of files created during pipeline\n# In nipype you create nodes using the pipeline engine that was imported earlier.\n# In this case I am sepcifically creating a function node with an input called func_files\n# and expects an output (what the function returns) called subs. The actual function\n# which was created above is called get_subs.\n# I can assign the input either through a workflow connect syntax or by simplying hardcoding it.\n# in this case I hard coded it by saying that .inputs.func_files = func_files\ngetsubs = pe.Node(Function(input_names=['func_files'],\n output_names=['subs'],\n function=get_subs),\n name='getsubs')\ngetsubs.inputs.func_files = func_files\n\n# Here I am inputing just the first run functional data\n# I want to use afni's 3dToutcount to find the number of\n# outliers at each volume. I will use this information to\n# later select the earliest volume with the least number of outliers\n# to serve as the base for the motion correction\nid_outliers = pe.Node(afni.OutlierCount(),\n name = 'id_outliers')\nid_outliers.inputs.in_file = func_files[0]\nid_outliers.inputs.automask = True\nid_outliers.inputs.legendre = True\nid_outliers.inputs.polort = 4\nid_outliers.inputs.out_file = 'outlier_file'\n\n\n# Create a Function node to identify the best volume based\n# on the number of outliers at each volume. I'm searching\n# for the index in the first 201 volumes that has the\n# minimum number of outliers and will use the min() function\n# I will use the index function to get the best vol.\ngetbestvol = pe.Node(Function(input_names=['outlier_count'],\n output_names=['best_vol_num'],\n function=best_vol),\n name='getbestvol')\npsb6351_wf.connect(id_outliers, 'out_file', getbestvol, 'outlier_count')\n\n# Extract the earliest volume with the\n# fewest outliers of the first run as the reference\nextractref = pe.Node(fsl.ExtractROI(t_size=1),\n name = \"extractref\")\nextractref.inputs.in_file = func_files[0]\n#extractref.inputs.t_min = int(np.ceil(nb.load(study_func_files[0]).shape[3]/2)) #PICKING MIDDLE\npsb6351_wf.connect(getbestvol, 'best_vol_num', extractref, 't_min')\n\n# Below is the command that runs AFNI's 3dvolreg command.\n# this is the node that performs the motion correction\n# I'm iterating over the functional files which I am passing\n# functional data from the slice timing correction node before\n# I'm using the earliest volume with the least number of outliers\n# during the first run as the base file to register to.\nvolreg = pe.MapNode(afni.Volreg(),\n iterfield=['in_file'],\n name = 'volreg')\nvolreg.inputs.outputtype = 'NIFTI_GZ'\nvolreg.inputs.zpad = 4\nvolreg.inputs.in_file = func_files\npsb6351_wf.connect(extractref, 'roi_file', volreg, 'basefile')\n\n'''\nMcFlirt motion correct\n'''\n\n# Below is the command that runs RAPIDART detection\n# This is the node that captures outliers in motion and intensity\n# Using zintensity thresholds of 1, 2, 3, or 4\n# And when using norm_threshold of 2, 1, 0.5, or 0.2\nrapidart_detect = pe. MapNode(rapidart.ArtifactDetect(),\n iterfield = ['realigned_files', 'realignment_parameters'],\n name = 'rapidart_detect')\nrapidart_detect.inputs.parameter_source = 'AFNI'\nrapidart_detect.inputs.mask_type = 'spm_global'\nrapidart_detect.inputs.norm_threshold = 1.0 #Based on nipype guidelines\nrapidart_detect.inputs.zintensity_threshold = 3.0 #Based on nipype guidelines\nrapidart_detect.inputs.global_threshold = 10.0\nrapidart_detect.inputs.use_differences = [True, False]\nrapidart_detect.inputs.use_norm = True\npsb6351_wf.connect(volreg, 'out_file', rapidart_detect, 'realigned_files')\npsb6351_wf.connect(volreg, 'oned_file', rapidart_detect, 'realignment_parameters')\n\n# Below is the command that runs AFNI's 3dTshift command\n# this is the node that performs the slice timing correction\n# I input the study func files as a list and the slice timing\n# as a list of lists. I'm using a MapNode to iterate over the two.\n# this should allow me to parallelize this on the HPC\ntshifter = pe.MapNode(afni.TShift(),\n iterfield=['in_file','slice_timing'],\n name = 'tshifter')\ntshifter.inputs.tr = '1.76'\ntshifter.inputs.slice_timing = slice_timing_list\ntshifter.inputs.outputtype = 'NIFTI_GZ'\npsb6351_wf.connect(volreg, 'out_file', tshifter, 'in_file')\n\n# Calculate the transformation matrix from EPI space to FreeSurfer space\n# using the BBRegister command\nfs_register = pe.Node(fs.BBRegister(init='fsl'),\n name ='fs_register')\nfs_register.inputs.contrast_type = 't2'\nfs_register.inputs.out_fsl_file = True\nfs_register.inputs.subject_id = f'sub-{sids[0]}'\nfs_register.inputs.subjects_dir = fs_dir\npsb6351_wf.connect(extractref, 'roi_file', fs_register, 'source_file')\n\n# Add a mapnode to spatially blur the data\n# save the outputs to the datasink\nsp_blur = pe.MapNode(afni.BlurToFWHM(), iterfield=['in_file'], name= 'sp_blur')\nsp_blur.inputs.fwhm = 2.5 #size of blurring (in mm); Some schools of thought - 3x voxel size, 6 for single subject (credit Donisha), AFNI for 4, 2-2.5x voxel (Aaron)\nsp_blur.inputs.automask = True\nsp_blur.inputs.num_threads = 1 #1 default, try not to go over 4\nsp_blur.inputs.outputtype = 'NIFTI_GZ'\n#sp_blur.inputs.out_file = 'sp_blur_4mm_1th'\npsb6351_wf.connect(tshifter, 'out_file', sp_blur, 'in_file')\n\n# Temporal smoothing\ntmp_smooth = pe.MapNode(afni.TSmooth(),\n iterfield=['in_file'],\n name= 'tmp_smooth')\ntmp_smooth.inputs.adaptive = 5\ntmp_smooth.inputs.lin = True\ntmp_smooth.inputs.outputtype = 'NIFTI_GZ'\npsb6351_wf.connect(sp_blur, 'out_file', tmp_smooth, 'in_file')\n\n# Register a source file to fs space and create a brain mask in source space\n# The node below creates the Freesurfer source\nfssource = pe.Node(nio.FreeSurferSource(),\n name ='fssource')\nfssource.inputs.subject_id = f'sub-{sids[0]}'\nfssource.inputs.subjects_dir = fs_dir\n\n# Extract aparc+aseg brain mask, binarize, and dilate by 1 voxel\nfs_threshold = pe.Node(fs.Binarize(min=0.5, out_type='nii'),\n name ='fs_threshold')\nfs_threshold.inputs.dilate = 1\npsb6351_wf.connect(fssource, ('aparc_aseg', get_aparc_aseg), fs_threshold, 'in_file')\n\n# Transform the binarized aparc+aseg file to the EPI space\n# use a nearest neighbor interpolation\nfs_voltransform = pe.Node(fs.ApplyVolTransform(inverse=True),\n name='fs_transform')\nfs_voltransform.inputs.subjects_dir = fs_dir\nfs_voltransform.inputs.interp = 'nearest'\npsb6351_wf.connect(extractref, 'roi_file', fs_voltransform, 'source_file')\npsb6351_wf.connect(fs_register, 'out_reg_file', fs_voltransform, 'reg_file')\npsb6351_wf.connect(fs_threshold, 'binary_file', fs_voltransform, 'target_file')\n\n# Mask the functional runs with the extracted mask\nmaskfunc = pe.MapNode(fsl.ImageMaths(suffix='_bet',\n op_string='-mas'),\n iterfield=['in_file'],\n name = 'maskfunc')\npsb6351_wf.connect(tshifter, 'out_file', maskfunc, 'in_file')\npsb6351_wf.connect(fs_voltransform, 'transformed_file', maskfunc, 'in_file2')\n\n'''\n# Smooth each run using SUSAn with the brightness threshold set to 75%\n# of the median value for each run and a mask constituting the mean functional\nsmooth_median = pe.MapNode(fsl.ImageStats(op_string='-k %s -p 50'),\n iterfield = ['in_file'],\n name='smooth_median')\npsb6351_wf.connect(maskfunc, 'out_file', smooth_median, 'in_file')\npsb6351_wf.connect(fs_voltransform, 'transformed_file', smooth_median, 'mask_file')\n\n# Calculate the mean functional\nsmooth_meanfunc = pe.MapNode(fsl.ImageMaths(op_string='-Tmean',\n suffix='_mean'),\n iterfield=['in_file'],\n name='smooth_meanfunc')\npsb6351_wf.connect(maskfunc, 'out_file', smooth_meanfunc, 'in_file')\n\nsmooth_merge = pe.Node(util.Merge(2, axis='hstack'),\n name='smooth_merge')\npsb6351_wf.connect(smooth_meanfunc, 'out_file', smooth_merge, 'in1')\npsb6351_wf.connect(smooth_median, 'out_stat', smooth_merge, 'in2')\n\n# Below is the code for smoothing using the susan algorithm from FSL that\n# limits smoothing based on different tissue classes\nsmooth = pe.MapNode(fsl.SUSAN(),\n iterfield=['in_file', 'brightness_threshold', 'usans', 'fwhm'],\n name='smooth')\nsmooth.inputs.fwhm=[2.0, 4.0, 6.0, 8.0, 10.0, 12.0]\npsb6351_wf.connect(maskfunc, 'out_file', smooth, 'in_file')\npsb6351_wf.connect(smooth_median, ('out_stat', getbtthresh), smooth, 'brightness_threshold')\npsb6351_wf.connect(smooth_merge, ('out', getusans), smooth, 'usans')\n'''\n\n# Below is the node that collects all the data and saves\n# the outputs that I am interested in. Here in this node\n# I use the substitutions input combined with the earlier\n# function to get rid of nesting\ndatasink = pe.Node(nio.DataSink(), name=\"datasink\")\ndatasink.inputs.base_directory = os.path.join(base_dir, 'derivatives/preproc')\ndatasink.inputs.container = f'sub-{sids[0]}'\npsb6351_wf.connect(tshifter, 'out_file', datasink, 'sltime_corr')\npsb6351_wf.connect(sp_blur, 'out_file', datasink, 'spatial_smoothing')\npsb6351_wf.connect(tmp_smooth, 'out_file', datasink, 'temporal_smoothing')\npsb6351_wf.connect(extractref, 'roi_file', datasink, 'study_ref')\n# psb6351_wf.connect(calc_distor_corr, 'source_warp', datasink, 'distortion')\npsb6351_wf.connect(volreg, 'out_file', datasink, 'motion.@corrfile')\npsb6351_wf.connect(volreg, 'oned_matrix_save', datasink, 'motion.@matrix')\npsb6351_wf.connect(volreg, 'oned_file', datasink, 'motion.@par')\npsb6351_wf.connect(rapidart_detect, 'outlier_files', datasink, 'artifact_detect')\npsb6351_wf.connect(fs_register, 'out_reg_file', datasink, 'register.@reg_file')\npsb6351_wf.connect(fs_register, 'min_cost_file', datasink, 'register.@reg_cost')\npsb6351_wf.connect(fs_register, 'out_fsl_file', datasink, 'register.@reg_fsl_file')\n# psb6351_wf.connect(smooth, 'smoothed_file', datasink, 'funcsmoothed')\npsb6351_wf.connect(getsubs, 'subs', datasink, 'substitutions')\n\n# The following two lines set a work directory outside of my\n# local git repo and runs the workflow\npsb6351_wf.run(plugin='SLURM',\n plugin_args={'sbatch_args': ('--partition centos7_IB_44C_512G --qos pq_psb6351 --account acc_psb6351'),\n 'overwrite':True})\n","sub_path":"code/psb6351_preproc.py","file_name":"psb6351_preproc.py","file_ext":"py","file_size_in_byte":17996,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"345753043","text":"import cv2\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport tensorflow.compat.v1 as tf\n\nimport flowlib\nimport models\n\n\ndef load_image(path: str) -> np.ndarray:\n img = cv2.imread(path, cv2.IMREAD_COLOR)\n\n # OpenCV stores images as BGR, but the model expects RGB.\n img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)\n\n # Convert to float and add batch dimension.\n return np.expand_dims(img.astype(np.float32) / 255., axis=0)\n\n\nif __name__ == \"__main__\":\n # Graph construction.\n image1_placeholder = tf.placeholder(tf.float32, [1, 384, 512, 3])\n image2_placeholder = tf.placeholder(tf.float32, [1, 384, 512, 3])\n flownet2 = models.FlowNet2()\n inputs = {\"input_a\": image1_placeholder, \"input_b\": image2_placeholder}\n predicted_flow = flownet2.run(inputs)[\"flow\"]\n\n # Load inputs.\n image1 = load_image(\"example/0img0.ppm\")\n image2 = load_image(\"example/0img1.ppm\")\n\n ckpt_file = \"checkpoints/FlowNet2/flownet-2.ckpt-0\"\n saver = tf.train.Saver()\n\n with tf.Session() as sess:\n saver.restore(sess, ckpt_file)\n feed_dict = {image1_placeholder: image1, image2_placeholder: image2}\n predicted_flow_np = sess.run(predicted_flow, feed_dict=feed_dict)\n\n # Show visualization.\n flow_image = flowlib.flow_to_image(predicted_flow_np[0])\n plt.imshow(flow_image)\n plt.show()\n","sub_path":"demo.py","file_name":"demo.py","file_ext":"py","file_size_in_byte":1286,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"611775998","text":"#!/usr/local/bin/python3\n\n#-*- coding: utf-8 -*-\n\nimport sys, getopt \nfrom weibopy.auth import OAuthHandler\nfrom weibopy.api import API\nfrom weibopy.error import WeibopError\nimport webbrowser\nimport pymysql\nimport time\n\n\nDEFAULT_FETCH_USERS_NUMBER\t= 1\nDEFAULT_ONE_PAGE_COUNT\t\t= 100\nDEFAULT_CITY_CODE\t\t= 11 # beijing\n\nAPP_KEY\t\t\t\t= 1830868372\nAPP_SECRET\t\t\t= \"\"\"425d41c01a336ab667e4b92fc64812ac\"\"\"\nBACK_URL\t\t\t= \"http://www.bubargain.com/backurl\"\n\nclass Mode:\n FROM_DB = 1\n FROM_NAME = 2\n\nclass Logging:\n func_name = ''\n\n def __init__(self, func_name):\n self.func_name = func_name\n\n @staticmethod\n def get_logger(func_name):\n return Logging(func_name.upper())\n\n @staticmethod\n def timestamp():\n return time.strftime('%Y-%m-%d %X', time.localtime(time.time()))\n\n def info(self, content):\n print(Logging.timestamp() + \" INFO [\" + self.func_name + \"]: \" + content)\n\n def warning(self, content):\n print(Logging.timestamp() + \" WARNING [\" + self.func_name + \"]: \" + content)\n\n def error(self, content):\n print(Logging.timestamp() + \" ERROR [\" + self.func_name + \"]: \" + content)\n\n\n# global vars:\ng_city_code \t\t= DEFAULT_CITY_CODE\ng_one_page_count\t= DEFAULT_ONE_PAGE_COUNT \ng_fetch_users_number\t= DEFAULT_FETCH_USERS_NUMBER\ng_stored_counter\t= 0\ng_mode\t\t\t= Mode.FROM_DB\ng_name\t\t\t= \"\"\ng_person_counter\t= 0\n\n\ndef do_auth():\n logging = Logging.get_logger('do_auth')\n auth = OAuthHandler(APP_KEY, APP_SECRET, BACK_URL)\n auth_url = auth.get_authorization_url()\n request_token_key = auth.request_token.key\n request_token_secret = auth.request_token.secret\n auth.set_request_token(request_token_key, request_token_secret)\n webbrowser.open(auth_url)\n verifier = input(\"Verifier: \").strip()\n access_token = auth.get_access_token(verifier)\n ATK = access_token.key\n ATS = access_token.secret\n auth.setAccessToken(ATK, ATS)\n api = API(auth)\n user = api.verify_credentials()\n logging.info(\"We are uing API from account: [uid = %s, name = %s]\" % (user.id, user.screen_name))\n return api\n\n\ndef fetch_one_user_statuses(api, _uid):\n logging = Logging.get_logger('fetch_one_user_statuses')\n all_statuses = []\n page_number = 1\n logging.info(\"count = %s\" % g_one_page_count)\n logging.info(\"page = %s\" % page_number)\n statuses = api.user_timeline(user_id=_uid, count=g_one_page_count, page=page_number)\n statuses_number = len(statuses)\n logging.info(\"Get %d statuses this time.\" % statuses_number)\n all_statuses.extend(get_statuses_data(statuses, statuses_number, _uid)) \n while (statuses_number > 0):\n page_number += 1\n statuses = api.user_timeline(user_id=_uid, count=g_one_page_count, page=page_number)\n statuses_number = len(statuses)\n logging.info(\"Get %d statuses this time.\" % statuses_number)\n if (0 == statuses_number):\n logging.info(\"Have got all statuses of the user: %s\" % _uid)\n break;\n else:\n all_statuses.extend(get_statuses_data(statuses, statuses_number, _uid)) \n #logging.info(\"all_statuses: %s \" % all_statuses)\n return all_statuses\n \n\ndef get_statuses_data(statuses, number, uid):\n logging = Logging.get_logger('get_statuses_data')\n data = []\n for index in range(0, number):\n if ('转发微博。' != statuses[index].text):\n gender = statuses[index].user.gender\n location = statuses[index].user.location\n loc = location.split(' ')\n province = loc[0]\n city = loc[1]\n weibo_id = str(statuses[index].id)\n created_at = str(statuses[index].created_at)\n source = statuses[index].source\n text = statuses[index].text\n data.append((uid, gender, province, city, weibo_id, created_at, source, text))\n #logging.info(str(data))\n return data\n\n\n\ndef is_exist(conn, weibo_id):\n logging = Logging.get_logger('is_exist')\n cursor = conn.cursor()\n sql = \"select id from statuses where weibo_id = %s\"\n param = weibo_id\n n = cursor.execute(sql, param)\n if (0 == n):\n cursor.close()\n return False\n elif (1 == n):\n #logging.info(\"Exist in users, uid = %s\" % uid)\n cursor.close()\n return True\n else:\n logging.error(\"Error Occured when check the uid = %s in users\" % uid)\n cursor.close()\n conn.close()\n logging.info(\"Stored \" + str(g_stored_counter) + \" New Person In Total!\")\n sys.exit(1)\n\n\n\n\ndef store_one_user_statuses(conn, statuses):\n global g_stored_counter\n logging = Logging.get_logger('store_one_user_statuses')\n cursor = conn.cursor()\n sql = \"insert into statuses (uid, gender, province, city, weibo_id, created_at, source, text) values(%s,%s,%s,%s,%s,%s,%s,%s)\"\n for s in statuses:\n #logging.info(\"one of them statuses: \" + str(s))\n if (not is_exist(conn, s[1])):\n #logging.info(\"This is a new status\")\n #logging.info(\"current status: %s\" % str(s))\n param = s\n n = cursor.execute(sql, param)\n if (1 == n):\n #logging.info(\"Store statuses uid = %s weibo_id = %s OK!!\" % (uid, s[1]))\n g_stored_counter += 1\n else:\n logging.error(\"Error Occured when store the status of uid = %s, weibo_id = %s +++=================------>>>>>>>>>>><<<<<<<<<<<------===============\" % (s[0], s[1]))\n cursor.close()\n return False\n else:\n pass\n cursor.close()\n return True\n\n\n\ndef fetch_users(conn):\n logging = Logging.get_logger('fetch_users')\n if (Mode.FROM_DB == g_mode):\n logging.info(\"DB MODE!!! \")\n sql = \"select uid from users limit %s\"\n param = int(g_fetch_users_number)\n elif (Mode.FROM_NAME == g_mode):\n return [(g_name,)]\n else:\n logging.error(\"MODE IS NOT EXIST!!! ====================<><><><><><><><><><>==================== \")\n return False\n cursor = conn.cursor()\n n = cursor.execute(sql, param)\n if (Mode.FROM_DB == g_mode and g_fetch_users_number == n):\n logging.info(\"Fetch %d users Successfully\" % n)\n uids = cursor.fetchall()\n cursor.close()\n logging.info(\"To Process Users: \" + str(uids))\n return uids\n elif (Mode.FROM_DB == g_mode and n >= 0):\n logging.info(\"There is less than %d users, Fetched %d users Successfully\" % (g_fetch_users_number, n))\n uids = cursor.fetchall()\n cursor.close()\n return uids\n elif (Mode.FROM_NAME == g_mode and 1 == n):\n logging.info(\"Fetched user: %s Successfully!\" % g_name)\n uid = cursor.fetchone()\n logging.info(\"name: %s uid: %s\" % (g_name, str(uid)))\n cursor.close()\n return [uid]\n elif (0 == n):\n logging.warning(\"NO SUCH USER in DB!\")\n cursor.close()\n return False\n else:\n logging.error(\"Database Operation ERROR!! n = %d\" % n)\n cursor.close()\n return False\n \n\ndef fetch_store_one_user_statuses(conn, api, uid):\n logging = Logging.get_logger('fetch_store_one_user_statuses')\n fetch_result = fetch_one_user_statuses(api, uid)\n #logging.info(\"fetch_result: %s\" % fetch_result)\n if (False == fetch_result):\n logging.error(\"ERROR Occured when fetching statuses\")\n return False\n else:\n logging.info(\"Fetch statuses of uid: %s OK!!\" % uid)\n if (False == store_one_user_statuses(conn, fetch_result)):\n logging.error(\"ERROR Occured when storing statuses!\")\n return False\n else:\n logging.info(\"Store statuses of uid: %s OK!!\" % uid)\n return True\n\n\ndef fetch_store_statuses(conn, api, uids):\n global g_person_counter\n logging = Logging.get_logger('fetch_store_statuses')\n logging.info(\"uids: %s\" % str(uids))\n for uid in uids:\n g_person_counter += 1\n logging.info(\"----------=-=-=-=-=-=-=-=-=-=========================--==-=-=-=-=->.>.>.>.>.>.>>>>>> person: %d START!!\" % g_person_counter)\n if (True == fetch_store_one_user_statuses(conn, api, uid[0])):\n logging.info(\"-----------=-=-=-=-=-=-=-=-=-==========================---=-=-=-=-=-=-=-=-=--=-=-=-=-=-=-=>>>>>>>>>>> person: %d END!!\" % g_person_counter)\n else:\n logging.error(\"Error Occured when process the person: %d uid: %s\", (g_person_counter, uid[0]))\n return False \n logging.info(\"Fetch and Store %d persons Successfully!\" % g_person_counter)\n return True\n\ndef fetch_statuses_to_database(conn):\n logging = Logging.get_logger('fetch_statuses_to_database')\n fetch_users_result = fetch_users(conn)\n if (False == fetch_users_result):\n logging.error(\"Error Occured When Fetching Users!!\")\n logging.info(\"Stored \" + str(g_stored_counter) + \" New Person In Total!\")\n sys.exit(1)\n else:\n logging.info(\"Fetch users OK!!\")\n uids = fetch_users_result\n logging.info(\"Start to do Auth!!! ==============>>>>> ^_^\")\n api = do_auth()\n logging.info(\"Done Auth!!! ==============>>>>> ^_^\")\n if (True == fetch_store_statuses(conn, api, uids)):\n logging.info(\"Store All statuses Successfully!!!\")\n return True\n else:\n logging.error(\"Store All statuses Failed!!!\")\n return False\n\n\n\n\ndef main():\n global g_one_page_count, g_fetch_users_number, g_mode, g_name\n logging = Logging.get_logger('main')\n try:\n opts,args = getopt.getopt(sys.argv[1:],\"p:c:u:n:\")\n for op,value in opts:\n if op == \"-p\":\n g_one_page_count = int(value)\n elif op == \"-u\":\n g_fetch_users_number = int(value)\n elif op == \"-n\":\n g_name = str(value)\n logging.info(g_name)\n g_mode = Mode.FROM_NAME\n print(opts) \n print(args) \n except getopt.GetoptError:\n logging.error(\"Params are not defined well!\")\n logging.info(\"Stored \" + str(g_stored_counter) + \" New Person In Total!\")\n sys.exit(1)\n\n logging.info(\"START\")\n conn = pymysql.connect(host=\"ec2-204-236-172-73.us-west-1.compute.amazonaws.com\", user=\"root\", passwd=\"RooT\", db=\"spider\", charset=\"utf8\")\n fetch_statuses_to_database(conn)\n conn.close()\n logging.info(\"Stored \" + str(g_stored_counter) + \" New Statuses In Total!\")\n logging.info(\"END\")\n\n\n\n\nif __name__ == \"__main__\":\n main()\n\n\n","sub_path":"weibo_content.py","file_name":"weibo_content.py","file_ext":"py","file_size_in_byte":10509,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"640641104","text":"#!/bin/python3\n\nimport re\n\ndef is_anagram(str1, str2):\n pattern = r'[\\s*&%#.\\'^?]+'\n \n s1 = re.sub(pattern, \"\", str1)\n s2 = re.sub(pattern, \"\", str2)\n if len(s1) != len(s2):\n return False\n for c in s1:\n if c not in s2:\n return False\n return True\n\ndef main():\n print('input first string')\n str1 = input()\n print('input second string')\n str2 = input()\n result = is_anagram(str1, str2)\n print(result)\n\n\nif __name__=='__main__':\n main()\n\n\n\n\n\n\n\n\n","sub_path":"hackerrank/geeks/anagram.py","file_name":"anagram.py","file_ext":"py","file_size_in_byte":508,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"341627527","text":"# Environment -- a data structure for Scheme environments\r\n\r\n# An Environment is a list of frames. Each frame represents a scope\r\n# in the program and contains a set of name-value pairs. The first\r\n# frame in the environment represents the innermost scope.\r\n\r\n# For the code below, I am assuming that a frame is implemented\r\n# as an association list, i.e., a list of two-element lists. E.g.,\r\n# the association list ((x 1) (y 2)) associates the value 1 with x\r\n# and the value 2 with y.\r\n\r\n# To implement environments in an object-oriented style, it would\r\n# be better to define a Frame class and make an Environment a list\r\n# of such Frame objects or to implement a frame as a hash table.\r\n\r\n# You need the following methods for modifying environments:\r\n# - constructors:\r\n# - create the empty environment (an environment with an empty frame)\r\n# - add an empty frame to the front of an existing environment\r\n# - lookup the value for a name (for implementing variable lookup)\r\n# if the name exists in the innermost scope, return the value\r\n# if it doesn't exist, look it up in the enclosing scope\r\n# if we don't find the name, it is an error\r\n# - define a name (for implementing define and parameter passing)\r\n# if the name already exists in the innermost scope, update the value\r\n# otherwise add a name-value pair as first element to the innermost scope\r\n# - assign to a name (for implementing set!)\r\n# if the name exists in the innermost scope, update the value\r\n# if it doesn't exist, perform the assignment in the enclosing scope\r\n# if we don't find the name, it is an error\r\n\r\n\r\nimport sys\r\nimport os.path\r\nfrom Tree import Node\r\nfrom Tree import IntLit\r\nfrom Tree import StrLit\r\nfrom Tree import Ident\r\nfrom Tree import Nil\r\nfrom Tree import Cons\r\nfrom Tree import BuiltIn, TreeBuilder\r\nfrom Parse import Parser, Scanner\r\nclass Environment(Node):\r\n # An Environment is implemented like a Cons node, in which\r\n # every list element (every frame) is an association list.\r\n # Instead of Nil(), we use None to terminate the list.\r\n\r\n def __init__(self, e = None):\r\n self.frame = Nil.getInstance() # the innermost scope, an assoc list\r\n self.env = e # the enclosing environment\r\n\r\n def isEnvironment(self):\r\n return True\r\n\r\n def print(self, n, p=False):\r\n for _ in range(n):\r\n sys.stdout.write(' ')\r\n sys.stdout.write(\"#{Environment\")\r\n if self.frame != None:\r\n self.frame.print(abs(n) + 4)\r\n if self.env != None:\r\n self.env.print(abs(n) + 4)\r\n for _ in range(abs(n)):\r\n sys.stdout.write(' ')\r\n sys.stdout.write(\" }\\n\")\r\n sys.stdout.flush()\r\n\r\n # This is not in an object-oriented style, it's more or less a\r\n # translation of the Scheme assq function.\r\n @staticmethod\r\n def __find(id, alist):\r\n if not alist.isPair():\r\n return None \t# in Scheme we'd return #f\r\n else:\r\n bind = alist.getCar()\r\n if id.getName() == bind.getCar().getName():\r\n # return a list containing the value as only element\r\n return bind.getCdr()\r\n else:\r\n return Environment.__find(id, alist.getCdr())\r\n\r\n def lookup(self, id):\r\n val = Environment.__find(id, self.frame)\r\n if val == None and self.env == None:\r\n self._error(\"undefined variable \" + id.getName())\r\n return Nil.getInstance()\r\n elif val == None:\r\n # look up the identifier in the enclosing scope\r\n return self.env.lookup(id)\r\n else:\r\n # get the value out of the list we got from find()\r\n return val.getCar()\r\n\r\n def define(self, id, value):\r\n self.frame = Cons(Cons(id,value), self.frame)\r\n\r\n #This function is __find, modified to update rather than lookup values\r\n def __recursiveAssign(self, id, value, alist):\r\n if not alist.isPair():\r\n sys.stderr.write(\"ERROR: ENVIRONMENT IS EMPTY\") #should never reach this, but error in place just in case\r\n else:\r\n bind = alist.getCar()\r\n if id.getName() == bind.getCar().getName():\r\n bind.setCdr(Cons(value, Nil.getInstance()))\r\n else:\r\n self.__recursiveAssign(id,value, alist.getCdr())\r\n\r\n def assign(self, id, value):\r\n if self.lookup(id) is not Nil.getInstance():\r\n #Implement similar to find:\r\n self.__recursiveAssign(id, value, self.frame)\r\n return Nil.getInstance()\r\n elif self.env != None:\r\n return self.env.assign(id,value)\r\n else:\r\n sys.stderr.write('ERROR: NAME NOT FOUND')\r\n \r\n @classmethod\r\n def populateEnvironment(cls, env, init_file):\r\n scanner = Scanner(open(init_file))\r\n builder = TreeBuilder()\r\n parser = Parser(scanner, builder)\r\n root = parser.parseExp()\r\n while root != None:\r\n root.eval(env)\r\n root = parser.parseExp()\r\n \r\nif __name__ == \"__main__\":\r\n env = Environment()\r\n env.define(Ident(\"foo\"), IntLit(42))\r\n env.print(0)\r\n","sub_path":"Tree/Environment.py","file_name":"Environment.py","file_ext":"py","file_size_in_byte":5217,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"1644259","text":"import matplotlib.pyplot as plt\nfrom sklearn.manifold import TSNE\n\n\nplt.switch_backend('agg')\n\n\ndef show_t_sne(latent, labels, title):\n if latent.shape[1] != 2:\n latent = TSNE().fit_transform(latent)\n plt.figure(figsize=(10, 10))\n plt.scatter(latent[:, 0], latent[:, 1], c=labels, edgecolors='none') # cmap=cmap,cmap=plt.get_cmap(\"tab10\", 7)\n plt.title(title)\n plt.axis(\"off\")\n plt.tight_layout()\n\n print(\"saving tsne figure as tsne.png\")\n plt.savefig(\"tsne.png\")\n","sub_path":"scvi/visualization.py","file_name":"visualization.py","file_ext":"py","file_size_in_byte":496,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"85027148","text":"\"\"\"empty message\n\nRevision ID: 037abb94fc0d\nRevises: b05085b969b8\nCreate Date: 2016-04-29 22:47:26.643480\n\n\"\"\"\n\n# revision identifiers, used by Alembic.\nrevision = '037abb94fc0d'\ndown_revision = 'b05085b969b8'\n\nfrom alembic import op\nimport sqlalchemy as sa\n\n\ndef upgrade():\n ### commands auto generated by Alembic - please adjust! ###\n op.add_column('USUARIOS', sa.Column('EMAIL', sa.String(), nullable=True))\n op.add_column('USUARIOS', sa.Column('NOME', sa.String(), nullable=True))\n op.add_column('USUARIOS', sa.Column('SENHA', sa.String(), nullable=True))\n op.drop_column('USUARIOS', 'email')\n op.drop_column('USUARIOS', 'senha')\n op.drop_column('USUARIOS', 'nome')\n ### end Alembic commands ###\n\n\ndef downgrade():\n ### commands auto generated by Alembic - please adjust! ###\n op.add_column('USUARIOS', sa.Column('nome', sa.VARCHAR(), autoincrement=False, nullable=True))\n op.add_column('USUARIOS', sa.Column('senha', sa.VARCHAR(), autoincrement=False, nullable=True))\n op.add_column('USUARIOS', sa.Column('email', sa.VARCHAR(), autoincrement=False, nullable=True))\n op.drop_column('USUARIOS', 'SENHA')\n op.drop_column('USUARIOS', 'NOME')\n op.drop_column('USUARIOS', 'EMAIL')\n ### end Alembic commands ###\n","sub_path":"migrations/versions/037abb94fc0d_.py","file_name":"037abb94fc0d_.py","file_ext":"py","file_size_in_byte":1258,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"448283966","text":"'''\n@Description: \n@version: \n@Author: chenhao\n@Date: 2020-03-26 15:07:51\n@LastEditors: chenhao\n@LastEditTime: 2020-03-26 15:32:29\n'''\n\n\"\"\"\nGiven a binary search tree with non-negative values, find the minimum absolute difference between values of any two nodes.\n\nExample:\nInput:\n\n 1\n \\\n 3\n /\n 2\n\nOutput:\n1\n\nExplanation:\nThe minimum absolute difference is 1, which is the difference between 2 and 1 (or between 2 and 3).\n\nNote:\nThere are at least two nodes in this BST.\nThis question is the same as 783: https://leetcode.com/problems/minimum-distance-between-bst-nodes/\n\"\"\"\n\n\n# Definition for a binary tree node.\nclass TreeNode:\n def __init__(self, x):\n self.val = x\n self.left = None\n self.right = None\n\nclass Solution:\n def getMinimumDifference(self, root: TreeNode) -> int:\n preNode = None\n minDiff = float('inf')\n \n def inOrder(node):\n if not node:\n return\n nonlocal preNode\n nonlocal minDiff\n inOrder(node.left)\n if preNode:\n minDiff = min(minDiff, node.val - preNode.val)\n preNode = node\n inOrder(node.right)\n \n inOrder(root)\n return minDiff","sub_path":"4_Tree/Binary Search Tree/530. Minimum Absolute Difference in BST.py","file_name":"530. Minimum Absolute Difference in BST.py","file_ext":"py","file_size_in_byte":1248,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"191634757","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Aug 10 14:46:56 2020\n\n@author: yash\n\"\"\"\n# ###Binary Search Approach\n# O(n) time | O(1) space\ndef findThreeLargestNumbers(array):\n threeLargest = [None for i in range(3)] # [None, None, None]\n for num in array:\n updateLargest(threeLargest, num)\n return threeLargest\n\ndef updateLargest(threeLargest, num):\n if threeLargest[2] is None or num > threeLargest[2]:\n shiftAndUpdate(threeLargest, num, 2)\n elif threeLargest[1] is None or num > threeLargest[1]:\n shiftAndUpdate(threeLargest, num, 1)\n elif threeLargest[0] is None or num > threeLargest[0]:\n shiftAndUpdate(threeLargest, num, 0)\n\ndef shiftAndUpdate(array, num, indx):\n #[0,1,2]\n #[y,z,num]\n #for i in range(0, 2+1)\n #if i == 1:\n \n \n \n for i in range(indx+1):\n if i == indx:\n array[i] = num\n else:\n array[i] = array[i+1]\n \nprint(findThreeLargestNumbers([12,3,-3,51312,12,34,121]))\n ","sub_path":"FindThreeLargestNumbers.py","file_name":"FindThreeLargestNumbers.py","file_ext":"py","file_size_in_byte":1046,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"47475884","text":"import time\nimport select\nimport sys\nimport termios, atexit \n\n# save the terminal settings\nfd = sys.stdin.fileno()\nnew_term = termios.tcgetattr(fd)\nold_term = termios.tcgetattr(fd)\n\n# new terminal setting unbuffered\n# ICANON = Non-canonical mode.\n# ~ mean bit flip, like 0001 to 1110\nnew_term[3] = (new_term[3] & ~termios.ICANON & ~termios.ECHO)\n\n# switch to normal terminal\ndef set_normal_term():\n termios.tcsetattr(fd, termios.TCSAFLUSH, old_term)\n\n# switch to unbuffered terminal\ndef set_curses_term():\n termios.tcsetattr(fd, termios.TCSAFLUSH, new_term)\n\ndef timerInput(timer):\n ret = ''\n nowTime = time.time()\n\n while True:\n if time.time() - nowTime > timer:\n break\n if kbhit():\n _ch = getch()\n if ord(_ch) == ord(\"\\b\"):\n sys.stdin.write('\\n')\n ret = ret[0:-1]\n putch(ret, flush=True)\n if ord(_ch) == ord(\"\\n\"):\n break;\n else:\n ret += _ch\n putch(ret)\n print(\"\\n\")\n set_normal_term()\n return ret\n\ndef getch(readByte=1):\n return sys.stdin.read(readByte)\n\ndef kbhit():\n set_curses_term()\n dr, _, _ = select.select([sys.stdin], [], [], 0)\n # Return if dr is same with empty list.\n return dr != []\n\ndef putch(_ch, flush=False):\n if flush:\n sys.stdout.write('\\r')\n for _ in range(0, len(_ch)):\n sys.stdout.write(' ')\n sys.stdout.flush()\n sys.stdout.write('\\r' + _ch)\n sys.stdout.flush()\n\natexit.register(set_normal_term)\n","sub_path":"PythonCode/timerInput.py","file_name":"timerInput.py","file_ext":"py","file_size_in_byte":1563,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"515195093","text":"# This is a sample Python script.\n\n# Press Shift+F10 to execute it or replace it with your code.\n# Press Double Shift to search everywhere for classes, files, tool windows, actions, and settings.\nfrom queue import PriorityQueue\n\nimport pandas as pd\nimport easygui\nimport numpy as np\n\n# Press the green button in the gutter to run the script.\nfrom numpy.core._multiarray_umath import arange\n\n\ndef main():\n return easygui.fileopenbox()\n\n\ndef entrega_eficiente(entregasTable):\n aux = 0\n entregasTable\n print(table)\n valorMaximo = []\n for x in range(0,3):\n valorMaximo.append(int(entregasTable[x][2]))\n\n valor = np.array(valorMaximo).max()\n entrega = \"\"\n for x in range(0,len(matrizEntregas)):\n if int(matrizEntregas[x][2]) == valor:\n entrega = matrizEntregas[x][0:]\n break\n\n return entrega\n\n\ndef dataFrameInput(name):\n return pd.read_csv(name)\n\n\ndef proxima_entrega(objetivo):\n\n for x in arange(0,len(matrizEntregas)-1):\n listaEntrega = []\n if matrizEntregas[x][1] == objetivo[1]:\n listaEntrega = matrizEntregas[x+1][0:]\n return listaEntrega\n listaEntrega = [-1]\n return listaEntrega\n\n\n\ndef busca(raiz, objetivo,):\n q = PriorityQueue()\n custo = 0\n tempo = objetivo[0]\n q.put((custo,raiz,[raiz]))\n\n while not q.empty():\n listaCidade = []\n listaCidade = q.get()\n cidade = listaCidade[1]\n\n if cidade == objetivo[1]:\n custoTotal = calcular_entrega(listaCidade[2])\n print(\"Tempo :{} \".format(custoTotal*2))\n print(\"Caminho : {}\".format(listaCidade[2]))\n print(\"Lucro : {}\".format(objetivo[2]))\n\n listaTotal.append(int(objetivo[2]))\n listaEntrega = proxima_entrega(objetivo)\n for x in arange(len(matrizEntregas)-1):\n if int(listaEntrega[0]) == -1:\n print(\"Lucro Total : {}\".format(sum(listaTotal)))\n return\n if (custoTotal*2)+int(objetivo[0]) <= int(listaEntrega[0]):\n return busca('A',listaEntrega)\n else:\n return busca('A',proxima_entrega(listaEntrega))\n print(\"Lucro Total : {}\".format(sum(listaTotal)))\n return\n\n cidades_ad = deliveryCidades[cidade]\n\n for cidade_ad,custoCidade in cidades_ad.items():\n if listaCidade[2].count(cidade_ad):\n continue\n\n else:\n q.put((custoCidade, cidade_ad, listaCidade[2] + [cidade_ad]))\n custo = int(custoCidade)+ custo\n\n\ndef calcular_entrega(rota):\n valor_da_rota = 0\n for x in arange(0,len(rota)-1):\n valor_da_rota = int(deliveryCidades[rota[x]][rota[x+1]])+valor_da_rota\n return valor_da_rota\n\n\ntable = pd.read_csv('C:/Users/vitor/Downloads/entrada-trabalho - complexa - entrada 2 - entrada-trabalho - complexa - entrada 2 (1).csv')\nprint(table.columns[0])\n\nprint(table.to_numpy())\ntableMatriz = table.to_numpy()\nprint(tableMatriz[1][0])\nnuberOFVetex = int(table.columns[0])\naphabet = ['A', 'B', 'C', 'D','E','F','G','H','I','J']\ninterationNumber = 0\nlista = [1, 2, 3]\n\nlistaDelivery = []\ndeliveryCidades = {}\nfor x in range(1, nuberOFVetex + 1):\n v = np.array(tableMatriz[x][:nuberOFVetex])\n v = list(v)\n cidades={}\n count = 0\n for i in v:\n if int(i) != 0:\n cidades[aphabet[count]] = i\n count = count + 1\n deliveryCidades[aphabet[x - 1]] = cidades\n\nnumberOfDelirery = int(tableMatriz[nuberOFVetex + 1][0])\nprint(deliveryCidades)\n\nfor x in range(nuberOFVetex + 2, nuberOFVetex + 2 + numberOfDelirery):\n listaAux = np.array(tableMatriz[x][:3])\n listaAux = list(listaAux)\n listaDelivery.append(listaAux)\n\nprint(listaDelivery)\n\nmatrizEntregas = np.array(listaDelivery).reshape(numberOfDelirery, 3)\n\nentregaAinda = True\n\n\n\nlistaTotal = [0]\nobjetivoLista = entrega_eficiente(matrizEntregas)\nbusca('A',objetivoLista)\n\n\n\nprint(matrizEntregas)\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":4000,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"246693205","text":"import os\nimport netifaces\nimport logging\nimport xmltodict\n\ntry:\n import StringIO\nexcept ImportError:\n from io import StringIO\n\nfrom pyang.__init__ import Context, FileRepository\nfrom pyang.translators.yin import YINPlugin\n\n\nclass Bash():\n def __init__(self, command):\n command = command + \" 2>&1\"\n self.pipe = os.popen(command)\n self.output = self.pipe.read()\n self.exit_code = self.pipe.close()\n if self.exit_code is not None:\n logging.debug (\"Error code: \"+str(self.exit_code)+\" -Due to command: \"+str(command)+\" - Message: \"+self.output)\n \n def get_output(self):\n return self.output\n\n\ndef get_mac_address(configuration_interface):\n interfaces = netifaces.interfaces()\n for interface in interfaces:\n if interface == configuration_interface:\n return netifaces.ifaddresses(interface)[17][0]['addr']\n\n\ndef _transform_yang_to_dict(yang_model_string): \n class Opts(object):\n def __init__(self, yin_canonical=False, yin_pretty_strings=True):\n self.yin_canonical = yin_canonical\n self.yin_pretty_strings = yin_pretty_strings\n ctx = Context(FileRepository())\n yang_mod = ctx.add_module('yang', yang_model_string, format='yang')\n \n yin = YINPlugin()\n modules = []\n modules.append(yang_mod)\n ctx.opts = Opts()\n yin_string = StringIO()\n yin.emit(ctx=ctx, modules=modules, fd=yin_string)\n xml = yin_string.getvalue()\n return xmltodict.parse(xml)\n\n\ndef validate_json(json_instance, yang_model):\n yang_model_dict = _transform_yang_to_dict(yang_model)\n working_dir = '/tmp/'\n Bash('cd '+working_dir+' \\n cp /usr/local/share/yang/modules/ietf/* .')\n\n # Save temporary on disk the xml and the yang model\n yang_file_name = yang_model_dict['module']['@name']+\".yang\"\n yang_name = yang_model_dict['module']['@name']\n with open (working_dir+yang_file_name, \"w\") as yang_model_file:\n yang_model_file.write(yang_model)\n json_file_name = yang_name+\".json\"\n with open (working_dir+json_file_name, \"w\") as yang_model_file:\n yang_model_file.write(json_instance)\n\n Bash('cd '+working_dir+' \\n yang2dsdl -t config '+yang_file_name)\n Bash('cd '+working_dir+' \\n pyang -f jtox -o '+yang_name+'.jtox '+yang_name+'.yang')\n Bash('cd '+working_dir+' \\n json2xml -t config -o '+yang_name+'.xml '+yang_name+'.jtox '+yang_name+'.json')\n response = Bash('cd /tmp/ \\n yang2dsdl -s -j -b '+yang_name+' -t config -v '+yang_name+'.xml')\n return response.exit_code, response.get_output()\n\ndef check_validity_initial_params(params):\n res_params = []\n if len(params) < 3:\n return(\"Error to start: usage start_gunicorn.py \")\n else:\n #Check nf_type\n if params[1] != \"docker\" and params[1] != \"vm\":\n return(\"Error to start: can be 'docker' or 'vm'\")\n nf_type = params[1]\n res_params.append(nf_type)\n\n # Check datadisk_path\n if params[2].isdigit():\n return(\"Error to start: can not be a number\")\n datadisk_path = params[2]\n res_params.append(datadisk_path)\n\n return res_params\n","sub_path":"configuration-functions/common/cf_core/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":3193,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"429105717","text":"\"\"\"Uses trained neural network to predict graph types for each page of paper PDF\r\n\"\"\"\r\n\r\nimport os.path\r\nimport argparse\r\nimport urllib\r\n\r\nimport tempfile\r\nimport subprocess\r\nimport glob\r\nimport itertools\r\n\r\nfrom fastai.vision import *\r\n\r\ntry:\r\n import numpy as np\r\n import pandas as pd\r\n from sklearn.neighbors import NearestNeighbors\r\n\r\n import skimage.io\r\n import matplotlib.pyplot as plt\r\n from colorspacious import cspace_convert\r\nexcept:\r\n print('Calculations will fail if this is a worker')\r\n\r\n\r\ndef detect_graph_types_from_iiif(paper_id, pages, learner, debug=False):\r\n \"\"\"Pull images from iiif server\r\n \"\"\"\r\n\r\n print(paper_id, pages)\r\n\r\n url = \"http://127.0.0.1:8182/iiif/2/biorxiv:{}.full.pdf/full/560,560/0/default.png?page={}\"\r\n images = [open_image(io.BytesIO(requests.get(url.format(paper_id, pg)).content)) for pg in range(1, pages+1)]\r\n \r\n return detect_graph_types_from_list(images, learner)\r\n\r\n\r\ndef detect_graph_types_from_list(images, learner):\r\n \"\"\"Predicts graph types for each image and returns pages with bar graphs\r\n \"\"\"\r\n page_predictions = np.array([predict_graph_type(images[idx], learner) for idx in range(0, len(images))])\r\n bar_pages = np.where(page_predictions == 'bar')[0] + 1 #add 1 to page idx such that page counting starts at 1\r\n pie_pages = np.where(page_predictions == 'pie')[0] + 1\r\n hist_pages = np.where(page_predictions == 'hist')[0] + 1\r\n bardot_pages = np.where(page_predictions == 'bardot')[0] + 1\r\n box_pages = np.where(page_predictions == 'box')[0] + 1\r\n dot_pages = np.where(page_predictions == 'dot')[0] + 1\r\n violin_pages = np.where(page_predictions == 'violin')[0] + 1\r\n positive_pages = hist_pages.tolist() + bardot_pages.tolist() + box_pages.tolist() + dot_pages.tolist() + violin_pages.tolist()\r\n if len(positive_pages) > 0:\r\n positive_pages = list(set(positive_pages)) #remove duplicates and sort\r\n positive_pages.sort()\r\n\r\n class_pages = dict(); \r\n class_pages['bar'] = bar_pages.tolist()\r\n class_pages['pie'] = pie_pages.tolist()\r\n class_pages['hist'] = hist_pages.tolist()\r\n class_pages['bardot'] = bardot_pages.tolist()\r\n class_pages['box'] = box_pages.tolist()\r\n class_pages['dot'] = dot_pages.tolist()\r\n class_pages['violin'] = violin_pages.tolist()\r\n class_pages['positive'] = positive_pages\r\n \r\n\r\n return class_pages\r\n\r\n\r\ndef predict_graph_type(img, learner):\r\n \"\"\"Use fastai model on each image to predict types of pages\r\n \"\"\"\r\n class_names = {\r\n \"0\": [\"approp\"],\r\n \"1\": [\"bar\"],\r\n \"2\": [\"bardot\"],\r\n \"3\": [\"box\"],\r\n \"4\": [\"dot\"],\r\n \"5\": [\"hist\"],\r\n \"6\": [\"other\"],\r\n \"7\": [\"pie\"],\r\n \"8\": [\"text\"],\r\n \"9\": [\"violin\"]\r\n }\r\n \r\n pred_class,pred_idx,outputs = learner.predict(img)\r\n \r\n if pred_idx.sum().tolist() == 0: #if there is no predicted class \r\n #(=no class over threshold) give out class with highest prediction probability\r\n highest_pred = str(np.argmax(outputs).tolist())\r\n pred_class = class_names[highest_pred]\r\n else: \r\n pred_class = pred_class.obj #extract class name as text\r\n \r\n return(pred_class)\r\n\r\n","sub_path":"detect_bargraph.py","file_name":"detect_bargraph.py","file_ext":"py","file_size_in_byte":3240,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"265871306","text":"\n\nfrom xai.brain.wordbase.verbs._refine import _REFINE\n\n#calss header\nclass _REFINES(_REFINE, ):\n\tdef __init__(self,): \n\t\t_REFINE.__init__(self)\n\t\tself.name = \"REFINES\"\n\t\tself.specie = 'verbs'\n\t\tself.basic = \"refine\"\n\t\tself.jsondata = {}\n","sub_path":"xai/brain/wordbase/verbs/_refines.py","file_name":"_refines.py","file_ext":"py","file_size_in_byte":238,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"428377845","text":"\"\"\"\n2.4 Настройка ожиданий\nЗадание: ждем нужный текст на странице\nПопробуем теперь написать программу, которая будет бронировать нам дом для отдыха по строго заданной цене.\n Более высокая цена нас не устраивает, а по более низкой цене объект успеет забронировать кто-то другой.\n\n\"\"\"\n\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.support.ui import WebDriverWait\nfrom selenium.webdriver.support import expected_conditions as EC\nfrom selenium import webdriver\nimport math\nimport time\ndef calc(x):\n return str(math.log(abs(12*math.sin(int(x)))))\ntry:\n link = \"http://suninjuly.github.io/explicit_wait2.html\"\n browser = webdriver.Chrome('C:\\\\Users\\\\Mixa\\\\.vscode\\\\chromedriver.exe')\n browser.get(link)\n\n konpka = browser.find_element_by_css_selector('#book')\n\n button = WebDriverWait(browser, 12).until(\n EC.text_to_be_present_in_element((By.ID,'price'), '100')\n )\n konpka.click()\n\n x_1 = browser.find_element_by_css_selector('#input_value')\n x = x_1.text\n\n y = calc(x)\n\n pole = browser.find_element_by_css_selector('#answer')\n pole.send_keys(y)\n\n submit = browser.find_element_by_css_selector('#solve')\n submit.click()\n\nfinally:\n\n time.sleep(10)\n browser.quit()\n\n\n\n\n\n","sub_path":"ojidanie.py","file_name":"ojidanie.py","file_ext":"py","file_size_in_byte":1468,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"19313018","text":"# uncompyle6 version 3.7.4\n# Python bytecode 3.7 (3394)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: C:\\Users\\sboon\\AppData\\Local\\Temp\\pip-install-ptdbtr91\\quarchpy\\quarchpy\\calibration\\calibration_classes.py\n# Compiled at: 2020-03-25 05:10:07\n# Size of source mod 2**32: 8937 bytes\nimport pkg_resources, datetime, xml.etree.ElementTree, quarchpy\n\nclass TestSummary:\n\n def __init__(self, calibrationType=None, channel=None, testName=None, passed=None, worstCase=None):\n self.calibrationType = calibrationType\n self.channel = channel\n self.testName = testName\n self.passed = passed\n self.worstCase = worstCase\n\n def niceToString(self):\n retString = str(self.calibrationType) + str(self.channel) + str(self.testName)\n return retString\n\n\nclass CalibrationHeaderInformation:\n\n def __init__(self):\n self.quarchEnclosureSerial = None\n self.quarchInternalSerial = None\n self.quarchEnclosurePosition = None\n self.idnStr = None\n self.quarchFirmware = None\n self.quarchFpga = None\n self.calInstrumentId = None\n self.quarchpyVersion = None\n self.calCoreVersion = None\n self.calTime = None\n self.calNotes = ''\n self.calTemperature = 'NA'\n self.calFileVersion = '1.0'\n self.calibrationType = None\n self.result = None\n self.testSummaryList = []\n\n def toXmlText(self):\n headerObject = ElementTree.Element('Header')\n quarchModuleObject = ElementTree.SubElement(headerObject, 'QuarchModule')\n ElementTree.SubElement(quarchModuleObject, 'EnclosureSerial').text = self.quarchEnclosureSerial\n ElementTree.SubElement(quarchModuleObject, 'InternalSerial').text = self.quarchInternalSerial\n if 'QTL1995' in self.quarchEnclosureSerial.upper():\n ElementTree.SubElement(quarchModuleObject, 'EnclosurePosition').text = self.quarchEnclosurePosition\n ElementTree.SubElement(quarchModuleObject, 'ModuleFirmware').text = self.quarchFirmware\n ElementTree.SubElement(quarchModuleObject, 'ModuleFpga').text = self.quarchFpga\n calInstrumentObject = ElementTree.SubElement(headerObject, 'CalInstrument')\n ElementTree.SubElement(calInstrumentObject, 'Identity').text = self.calInstrumentId\n CalSoftwareObject = ElementTree.SubElement(headerObject, 'CalSoftware')\n ElementTree.SubElement(CalSoftwareObject, 'QuarchPy').text = self.quarchpyVersion\n ElementTree.SubElement(CalSoftwareObject, 'CalCoreVersion').text = self.calCoreVersion\n ElementTree.SubElement(CalSoftwareObject, 'CalFileVersion').text = self.calFileVersion\n ElementTree.SubElement(headerObject, 'CalTime').text = self.calTime\n ElementTree.SubElement(headerObject, 'calNotes').text = self.calNotes\n return ElementTree.tostring(headerObject)\n\n def toReportText(self):\n reportTitle = 'CALIBRATION REPORT\\n' if 'cal' in str(self.calibrationType).lower() else 'VERIFICATION REPORT\\n'\n reportText = ''\n reportText += reportTitle\n reportText += '---------------------------------\\n'\n reportText += '\\n'\n reportText += 'Quarch Enclosure#: '\n reportText += self.quarchEnclosureSerial + '\\n'\n reportText += 'Quarch Serial#: '\n reportText += self.quarchInternalSerial + '\\n'\n if 'QTL1995' in self.quarchEnclosureSerial.upper():\n reportText += 'Quarch Enclosure Position#: '\n reportText += self.quarchEnclosurePosition + '\\n'\n reportText += 'Quarch Versions: '\n reportText += 'FW:' + self.quarchFirmware + ', FPGA: ' + self.quarchFpga + '\\n'\n reportText += '\\n'\n reportText += 'Calibration Instrument#:\\n'\n reportText += self.calInstrumentId + '\\n'\n reportText += '\\n'\n reportText += 'Calibration Versions:\\n'\n reportText += 'QuarchPy Version: ' + str(self.quarchpyVersion) + '\\n'\n reportText += 'Calibration Version: ' + str(self.calCoreVersion) + '\\n'\n reportText += '\\n'\n reportText += 'Calibration Details:\\n'\n reportText += 'Calibration Type: ' + str(self.calibrationType) + '\\n'\n reportText += 'Calibration Time: ' + str(self.calTime) + '\\n'\n reportText += 'Calibration Notes: ' + str(self.calNotes) + '\\n'\n reportText += '\\n'\n reportText += '---------------------------------\\n'\n reportText += '\\n'\n return reportText\n\n\ndef populateCalHeader_Keithley(calHeader, myCalInstrument):\n calHeader.calInstrumentId = myCalInstrument.sendCommandQuery('*IDN?')\n\n\ndef populateCalHeader_POM(calHeader, myDevice, calAction):\n pass\n\n\ndef populateCalHeader_HdPpm(calHeader, myDevice, calAction):\n calHeader.quarchEnclosureSerial = myDevice.sendCommand('*ENCLOSURE?')\n if calHeader.quarchEnclosureSerial.find('QTL') == -1:\n calHeader.quarchEnclosureSerial = 'QTL' + calHeader.quarchEnclosureSerial\n else:\n calHeader.quarchEnclosurePosition = myDevice.sendCommand('*POSITION?')\n calHeader.quarchInternalSerial = myDevice.sendCommand('*SERIAL?')\n if calHeader.quarchInternalSerial.find('QTL') == -1:\n calHeader.quarchInternalSerial = 'QTL' + calHeader.quarchInternalSerial\n else:\n calHeader.idnStr = myDevice.sendCommand('*IDN?')\n pos = calHeader.idnStr.upper().find('FPGA 1:')\n if pos != -1:\n versionStr = calHeader.idnStr[pos + 7:]\n pos = versionStr.find('\\n')\n if pos != -1:\n versionStr = versionStr[:pos].strip()\n else:\n versionStr = 'NOT-FOUND'\n calHeader.quarchFpga = versionStr.strip()\n pos = calHeader.idnStr.upper().find('PROCESSOR:')\n if pos != -1:\n versionStr = calHeader.idnStr[pos + 10:]\n pos = versionStr.find('\\n')\n if pos != -1:\n versionStr = versionStr[:pos].strip()\n else:\n pass\n else:\n versionStr = 'NOT-FOUND'\n calHeader.quarchFirmware = versionStr.strip()\n calHeader.calibrationType = calAction\n\n\ndef populateCalHeader_System(calHeader):\n calHeader.calCoreVersion = quarchpy.calibration.calCodeVersion\n calHeader.quarchpyVersion = pkg_resources.get_distribution('quarchpy').version\n calHeader.calTime = datetime.datetime.now()\n\n\ndef addTestSummary(calHeader):\n print('')\n\n\nclass ModuleResultsInformation:\n\n def __init__(self):\n self.calibrationStatus = False\n self.channelResults = []\n self.calibrationHeader = None\n\n def saveTextReport(self, outputPath):\n if 'QTL1995' in self.quarchEnclosureSerial.upper():\n fileName = calibrationHeader.quarchEnclosureSerial + ' - ' + calibrationHeader.quarchEnclosurePosition + ' - ' + self.calibrationType + ' - ' + self.calTime + '.txt'\n else:\n fileName = calibrationHeader.quarchEnclosureSerial + ' - ' + self.calibrationType + ' - ' + self.calTime + '.txt'\n f = open(fileName, 'w')\n f.write(calibrationHeader.toReportText())\n\n\nclass CalibrationResultsInformation:\n\n def __init__(self):\n self.calibrationName = None\n self.calibrationStatus = None\n self.calibrationSummary = None\n self.reportText = None\n self.reportXml = None","sub_path":"pycfiles/quarchpy-2.0.14-py2.py3-none-any/calibration_classes.cpython-37.py","file_name":"calibration_classes.cpython-37.py","file_ext":"py","file_size_in_byte":7439,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"568390760","text":"# uncompyle6 version 3.7.4\n# Python bytecode 2.6 (62161)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: \\dev\\Python26\\Lib\\site-packages\\requirejs\\templateloader\\filesystem.py\n# Compiled at: 2012-02-26 00:12:41\n\"\"\"\nBased on django templateloader\n\"\"\"\nimport re\nfrom django.conf import settings\nfrom django.contrib.staticfiles import finders\nfrom django.template.base import TemplateDoesNotExist\nfrom django.template.loader import BaseLoader\nfrom django.utils._os import safe_join\n\nclass Loader(BaseLoader):\n is_usable = True\n included_files = []\n processed_files = []\n PLACEHOLDER = ''\n JS_RE = re.compile('^\\\\s*//= include ([^#]*)(#.*)?$', re.I)\n\n def __init__(self, *args, **kwargs):\n self.included_files = []\n self.processed_files = []\n super(Loader, self).__init__(*args, **kwargs)\n\n def get_template_sources(self, template_name, template_dirs=None):\n \"\"\"\n Returns the absolute paths to \"template_name\", when appended to each\n directory in \"template_dirs\". Any paths that don't lie inside one of the\n template dirs are excluded from the result set, for security reasons.\n \"\"\"\n if not template_dirs:\n template_dirs = settings.TEMPLATE_DIRS\n for template_dir in template_dirs:\n try:\n yield safe_join(template_dir, template_name)\n except UnicodeDecodeError:\n raise\n except ValueError:\n pass\n\n def load_template_source(self, template_name, template_dirs=None):\n tried = []\n for filepath in self.get_template_sources(template_name, template_dirs):\n try:\n file = open(filepath)\n try:\n return (\n self.process_template(file.read().decode(settings.FILE_CHARSET)), filepath)\n finally:\n file.close()\n\n except IOError:\n tried.append(filepath)\n\n if tried:\n error_msg = 'Tried %s' % tried\n else:\n error_msg = 'Your TEMPLATE_DIRS setting is empty. Change it to point to at least one template directory.'\n raise TemplateDoesNotExist(error_msg)\n\n load_template_source.is_usable = True\n\n def process_template(self, content):\n self.find_js(content)\n indent = self.get_include_placeholder_indent(content)\n js_libs_include = ('' % filepath for filepath in self.included_files)\n content = content.replace(self.PLACEHOLDER, ('\\n%s' % indent).join(js_libs_include))\n return content\n\n def find_static_file(self, filename):\n found_file = None\n for finder in finders.get_finders():\n found_file = finder.find(filename)\n if found_file is not None:\n break\n\n if found_file is None:\n raise Exception('RequireJS: Cannot find file %s to import' % filename)\n return found_file\n\n def find_js(self, content, before_filename=None):\n for line in content.split('\\n'):\n match = self.JS_RE.match(line)\n if match:\n filename = match.group(1).strip()\n if filename not in self.included_files:\n if before_filename is None:\n self.included_files.append(filename)\n else:\n self.included_files.insert(self.included_files.index(before_filename), filename)\n if filename not in self.processed_files:\n static_filename = self.find_static_file(filename)\n file = open(static_filename)\n try:\n self.find_js(file.read().decode(settings.FILE_CHARSET), filename)\n finally:\n file.close()\n\n self.processed_files.append(filename)\n\n return\n\n PLACEHOLDER_INDENT_RE = re.compile('^(\\\\s*)\\\\s*', re.I | re.M)\n\n def get_include_placeholder_indent(self, content):\n match = self.PLACEHOLDER_INDENT_RE.match(content)\n if match:\n return match.group(1).strip('\\n')\n return ''\n\n\n_loader = Loader()","sub_path":"pycfiles/django-requirejs-0.1.0.win32/filesystem.py","file_name":"filesystem.py","file_ext":"py","file_size_in_byte":4367,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"249736597","text":"# 20190313 프로그래밍 입문\n# 별 도착 시간 계산\n# 지구에서 가장 가까운 별은 프록시마 켄타우리(Proxima Centauri) 별이라고 한다.\n# 프록시마 켄타우리는 지ㄹ구로부터 (40 X 10^12 Km) 떨어져 있다고 한다.\n# 빛의 속도 (3 X 10^8 m/s)로 프록시마 켄타우리까지 간다면 시간이 얼마나 걸리는지 직접 계산해보기로 하자.\n\nspeedOfLight = 3 * 10 ** 5\ndistance = 40 * 10 ** 12\n\ntotalTime = speedOfLight / distance * 3600 * 24 * 365\nprint(totalTime)\n","sub_path":"20190313 Practice/Lab09.py","file_name":"Lab09.py","file_ext":"py","file_size_in_byte":527,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"90704519","text":"\"\"\"Module for opening paths containing Rainmeter-specific or Windows environment variables.\"\"\"\n\nimport os\nimport re\nimport threading\n\nimport sublime\nimport sublime_plugin\n\nfrom . import rainmeter\nfrom . import logger\n\n\n# Files to open with sublime instead of the system default\nSETTINGS = sublime.load_settings(\"Rainmeter.sublime-settings\")\nDEF_EXTS = SETTINGS.get(\"rainmeter_default_open_sublime_extensions\", \"\")\n\nif DEF_EXTS is not None:\n DEF_EXTS = DEF_EXTS.strip().strip(r\"|\").strip()\nelse:\n DEF_EXTS = \"\"\n\nADD_EXTS = SETTINGS.get(\"rainmeter_open_sublime_extensions\", \"\")\n\nif ADD_EXTS is not None:\n ADD_EXTS = ADD_EXTS.strip().strip(r\"|\").strip()\nelse:\n ADD_EXTS = \"\"\n\nSUBLIME_FILES = re.compile(\"(?i).*\\\\.(\" + ADD_EXTS + \"|\" + DEF_EXTS + \")\\\\b\")\n\n\ndef open_path(path, transient=False):\n \"\"\"Try to open a path.\n\n A path could be opened either as:\n\n * a file or folder path or\n * URL in the system default application, or\n * in Sublime if it's a text file.\n\n Use transient=True to open a file in Sublime without assigning it a tab.\n A tab will be created once the buffer is modified.\n\n Will return False if the path doesn't exist in the file system, and\n True otherwise.\n \"\"\"\n if not path:\n return False\n\n if not os.path.exists(path):\n return False\n\n sublime.set_timeout(lambda: sublime.status_message(\"Opening \" + path), 10)\n if SUBLIME_FILES.search(path):\n if transient:\n sublime.set_timeout(\n lambda: sublime.active_window().open_file(path,\n sublime.TRANSIENT),\n 10)\n else:\n sublime.set_timeout(\n lambda: sublime.active_window().open_file(path),\n 10)\n else:\n os.startfile(path)\n\n return True\n\n\ndef open_url(url):\n \"\"\"Try opening a url with the system default for urls.\n\n Will return False if it's not a url, and True otherwise.\n \"\"\"\n if re.match(r\"(?i)(https?|ftp)://\", url.strip()):\n os.startfile(url)\n sublime.set_timeout(lambda: sublime.status_message(\"Opening \" + url),\n 10)\n return True\n else:\n return False\n\n\nclass TryOpenThread(threading.Thread):\n \"\"\"A wrapper method to handle threading for opening line embedded URLs.\"\"\"\n\n def __init__(self, line, region, opn):\n \"\"\"Construct a thread for opening URL embedded in a line.\"\"\"\n self.line = line\n self.region = region\n self.opn = opn\n threading.Thread.__init__(self)\n\n def __find_prior_quotation_mark(self):\n lastquote = self.region.a - 1\n while lastquote >= 0 and self.line[lastquote] != \"\\\"\":\n lastquote -= 1\n\n return lastquote\n\n def __open_selected_text(self):\n # 1. Selected text\n selected = self.line[self.region.a:self.region.b]\n if self.opn(selected):\n logger.info(\"Open selected text\")\n return True\n\n def __find_next_quotation_mark(self):\n nextquote = self.region.b\n while nextquote == len(self.line) or self.line[nextquote] != \"\\\"\":\n nextquote += 1\n\n return nextquote\n\n def __open_enclosed_string(self):\n # 2. String enclosed in double quotes\n # Find the quotes before the current point (if any)\n lastquote = self.__find_prior_quotation_mark()\n\n if not lastquote < 0 and self.line[lastquote] == \"\\\"\":\n # Find the quote after the current point (if any)\n nextquote = self.__find_next_quotation_mark()\n\n if not nextquote == len(self.line) \\\n and self.line[nextquote] == \"\\\"\":\n string = self.line[lastquote: nextquote].strip(\"\\\"\")\n if self.opn(string):\n logger.info(\"Open string enclosed in quotes: \" + string)\n return True\n\n def __find_front_nearest_whitespace(self):\n # Find the space before the current point (if any)\n lastspace = self.region.a - 1\n while lastspace >= 0 \\\n and self.line[lastspace] != \" \" \\\n and self.line[lastspace] != \"\\t\":\n lastspace -= 1\n\n # Set to zero if nothing was found until the start of the line\n lastspace = max(lastspace, 0)\n\n return lastspace\n\n def __find_back_nearest_whitespace(self):\n # Find the space after the current point (if any)\n nextspace = self.region.b\n while nextspace < len(self.line) \\\n and self.line[nextspace] != \" \" \\\n and self.line[nextspace] != \"\\t\":\n nextspace += 1\n\n return nextspace\n\n def __is_front_space(self, lastspace):\n return lastspace == 0 \\\n or self.line[lastspace] == \" \" \\\n or self.line[lastspace] == \"\\t\"\n\n def __is_back_space(self, nextspace):\n return nextspace >= len(self.line) \\\n or self.line[nextspace] == \" \" \\\n or self.line[nextspace] == \"\\t\"\n\n def __open_whitespaced_region(self):\n # 3. Region from last whitespace to next whitespace\n\n lastspace = self.__find_front_nearest_whitespace()\n if self.__is_front_space(lastspace):\n\n nextspace = self.__find_back_nearest_whitespace()\n if self.__is_back_space(nextspace):\n string = self.line[lastspace: nextspace].strip()\n if self.opn(string):\n logger.info(\"Open string enclosed in whitespace: \" + string)\n return True\n\n def __open_after_equals_sign(self):\n # 4. Everything after the first \\\"=\\\" until the end\n # of the line (strip quotes)\n mtch = re.search(r\"=\\s*(.*)\\s*$\", self.line)\n if mtch and self.opn(mtch.group(1).strip(\"\\\"\")):\n logger.info(\"Open text after \\\"=\\\": \" + mtch.group(1).strip(\"\\\"\"))\n return True\n\n def __open_whole_line(self):\n # 5. Whole line (strip comment character at start)\n stripmatch = re.search(r\"^[ \\t;]*?([^ \\t;].*)\\s*$\", self.line)\n if self.opn(stripmatch.group(1)):\n logger.info(\"Open whole line: \" + stripmatch.group(1))\n return\n\n def run(self):\n \"\"\"Run the thread.\"\"\"\n return self.__open_selected_text() or \\\n self.__open_enclosed_string() or \\\n self.__open_whitespaced_region() or \\\n self.__open_after_equals_sign() or \\\n self.__open_whole_line()\n\n\nclass RainmeterOpenPathsCommand(sublime_plugin.TextCommand):\n \"\"\"Try to open paths on lines in the current selection.\n\n Will try to open paths to files, folders or URLs on each line in the\n current selection. To achieve this, the following substrings of each line\n intersecting the selection are tested:\n\n 1. The string inside the selection\n 2. The string between possible quotes preceding and following the\n selection, if any\n 3. The string between the preceding and following whitespace\n 4. Everything after the first \"=\" on the line until the end of the line\n 5. The whole line, stripped of preceding semicolons\n \"\"\"\n\n def __split_selection_by_new_lines(self, selection):\n # Split all regions into individual segments on lines (using nicely\n # confusing python syntax).\n return [\n j for i in [\n self.view.split_by_newlines(region)\n for region in selection\n ]\n for j in i\n ]\n\n def __open_each_line_by_thread(self, lines):\n \"\"\"Identify segments in selected lines and tries to open them each in a new thread.\n\n This can be resource intensive.\n \"\"\"\n fnm = self.view.file_name()\n\n def opn(string):\n \"\"\"Simple callback method to apply multiple opening operations.\n\n An URL can be either external or internal and thus is opened differently.\n \"\"\"\n opened = open_path(rainmeter.make_path(string, fnm)) or open_url(string)\n if opened:\n logger.info(\"found file or url '\" + string + \"' to open\")\n\n for linereg in lines:\n wholeline = self.view.line(linereg)\n thread = TryOpenThread(self.view.substr(wholeline),\n sublime.Region(linereg.a - wholeline.a,\n linereg.b - wholeline.a),\n opn)\n thread.start()\n\n def run(self, _):\n \"\"\"Detect various scenarios of file paths and try to open them one after the other.\n\n :param _: _ edit unused\n \"\"\"\n selection = self.view.sel()\n lines = self.__split_selection_by_new_lines(selection)\n\n loaded_settings = sublime.load_settings(\"Rainmeter.sublime-settings\")\n max_open_lines = loaded_settings.get(\"rainmeter_max_open_lines\", 40)\n\n # Refuse if too many lines selected to avoid freezing\n\n if len(lines) > max_open_lines:\n accept = sublime.ok_cancel_dialog(\n \"You are trying to open \" +\n str(len(lines)) + \" lines.\\n\" +\n \"That's a lot, and could take some time. Try anyway?\")\n if not accept:\n return\n\n self.__open_each_line_by_thread(lines)\n\n def is_enabled(self):\n \"\"\"Check if current syntax is rainmeter.\"\"\"\n israinmeter = self.view.score_selector(self.view.sel()[0].a,\n \"source.rainmeter\")\n\n return israinmeter > 0\n\n def is_visible(self):\n \"\"\"It is visible if it is in Rainmeter scope.\"\"\"\n return self.is_enabled()\n","sub_path":"rainopen.py","file_name":"rainopen.py","file_ext":"py","file_size_in_byte":9654,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"518799781","text":"from flask import Flask, request\n\napp = Flask(__name__)\n\n@app.route('/')\ndef hello_world():\n user = [{'user_id':1,'username':'richie','email':'email.com'},\n {'user_id':2,'username':'2','email':'2.com'},\n {'user_id':3,'username':'3','email':'3.com'}]\n return {'users':user}","sub_path":"app/api/view/hello_world.py","file_name":"hello_world.py","file_ext":"py","file_size_in_byte":300,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"200791752","text":"import argparse\nimport sys, os\nfrom google.ads.googleads.client import GoogleAdsClient\nfrom google.ads.googleads.errors import GoogleAdsException\n\n# Location IDs are listed here:\n# https://developers.google.com/google-ads/api/reference/data/geotargets\n# and they can also be retrieved using the GeoTargetConstantService as shown\n# here: https://developers.google.com/google-ads/api/docs/targeting/location-targeting\n#_DEFAULT_LOCATION_IDS = [\"1023191\"] # location ID for New York, NY\n_DEFAULT_LOCATION_IDS = [\"2702\"] #location ID for Singapore\n# A language criterion ID. For example, specify 1000 for English. For more\n# information on determining this value, see the below link:\n# https://developers.google.com/google-ads/api/reference/data/codes-formats#expandable-7\n_DEFAULT_LANGUAGE_ID = \"1000\" # language ID for English\n\n\n# [START generate_keyword_ideas]\ndef Gen_kw_ideas(\n client, customer_id, location_ids, language_id, keyword_texts\n):\n keyword_plan_idea_service = client.get_service(\"KeywordPlanIdeaService\")\n keyword_competition_level_enum = client.get_type(\n \"KeywordPlanCompetitionLevelEnum\"\n ).KeywordPlanCompetitionLevel\n keyword_plan_network = client.get_type(\n \"KeywordPlanNetworkEnum\"\n ).KeywordPlanNetwork.GOOGLE_SEARCH_AND_PARTNERS\n location_rns = _map_locations_ids_to_resource_names(client, location_ids)\n language_rn = client.get_service(\n \"LanguageConstantService\"\n ).language_constant_path(language_id)\n\n # Either keywords or a page_url are required to generate keyword ideas\n # so this raises an error if neither are provided.\n if not (keyword_texts):\n raise ValueError(\n \"At least one of keywords or page URL is required, \"\n \"but neither was specified.\"\n )\n\n # Only one of the fields \"url_seed\", \"keyword_seed\", or\n # \"keyword_and_url_seed\" can be set on the request, depending on whether\n # keywords, a page_url or both were passed to this function.\n request = client.get_type(\"GenerateKeywordIdeasRequest\")\n request.customer_id = customer_id\n request.language = language_rn\n request.geo_target_constants = location_rns\n request.include_adult_keywords = False\n request.keyword_plan_network = keyword_plan_network\n\n # To generate keyword ideas with only a page_url and no keywords we need\n # to initialize a UrlSeed object with the page_url as the \"url\" field.\n #if not keyword_texts and page_url:\n # request.url_seed.url = page_url\n\n # To generate keyword ideas with only a list of keywords and no page_url\n # we need to initialize a KeywordSeed object and set the \"keywords\" field\n # to be a list of StringValue objects.\n if keyword_texts:\n request.keyword_seed.keywords.extend(keyword_texts)\n\n # To generate keyword ideas using both a list of keywords and a page_url we\n # need to initialize a KeywordAndUrlSeed object, setting both the \"url\" and\n # \"keywords\" fields.\n #if keyword_texts and page_url:\n # request.keyword_and_url_seed.url = page_url\n # request.keyword_and_url_seed.keywords.extend(keyword_texts)\n\n keyword_ideas = keyword_plan_idea_service.generate_keyword_ideas(\n request=request\n )\n\n for idea in keyword_ideas:\n competition_value = idea.keyword_idea_metrics.competition.name\n print(\n f'Keyword idea text \"{idea.text}\" has '\n f'\"{idea.keyword_idea_metrics.avg_monthly_searches}\" '\n f'average monthly searches and \"{competition_value}\" '\n \"competition.\\n\"\n )\n # [END generate_keyword_ideas]\n\n\ndef map_keywords_to_string_values(client, keyword_texts):\n keyword_protos = []\n for keyword in keyword_texts:\n string_val = client.get_type(\"StringValue\")\n string_val.value = keyword\n keyword_protos.append(string_val)\n return keyword_protos\n\n\ndef _map_locations_ids_to_resource_names(client, location_ids):\n \"\"\"Converts a list of location IDs to resource names.\n Args:\n client: an initialized GoogleAdsClient instance.\n location_ids: a list of location ID strings.\n Returns:\n a list of resource name strings using the given location IDs.\n \"\"\"\n build_resource_name = client.get_service(\n \"GeoTargetConstantService\"\n ).geo_target_constant_path\n return [build_resource_name(location_id) for location_id in location_ids]\n\n#my own function for button to insert keywords\ndef button_insert_keywords(keywords):\n listofkeywords = []\n listofkeywords.append(keywords)\n Gen_kw_ideas( \n client = GoogleAdsClient.load_from_dict(credentials),\n customer_id = \"1_\",\n location_ids=[\"2702\"],\n language_id=\"1000\",\n keyword_texts=listofkeywords)\n\n\n","sub_path":"api/generate_keyword_ideas.py","file_name":"generate_keyword_ideas.py","file_ext":"py","file_size_in_byte":4752,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"466270727","text":"#vjezba\n#remote_machine_info.py\n\nimport socket\ndef get_remote_machine_info():\n remote_host = 'www.aspira.hr'\n try:\n print (\"IP address: %s\" %socket.gethostbyname(remote_host))\n except socket.error as err_msg:\n print (\"%s: %s\" %(remote_host, err_msg))\nif __name__ == '__main__':\n get_remote_machine_info()\n\n#local_machine_info.py\n\ndef print_machine_info():\n host_name = socket.gethostname()\n ip_address = socket.gethostbyname(host_name)\n print (\"Host name: %s\" % host_name)\n print (\"IP address: %s\" % ip_address)\nif __name__ == '__main__':\n print_machine_info()\n\n#find_service_name.py\n\ndef find_service_name():\n protocolname = 'tcp'\n for port in [80, 25]:\n print (\"Port: %s => service name: %s\" %(port, socket.getservbyport(port,\nprotocolname)))\n\n print (\"Port: %s => service name: %s\" %(53, socket.getservbyport(53, 'udp')))\nif __name__ == '__main__':\n find_service_name()\n \nprint(socket.gethostbyaddr('8.8.8.8'))\n\n\n","sub_path":"Vjezba1/Vjezba.py","file_name":"Vjezba.py","file_ext":"py","file_size_in_byte":934,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"75540637","text":"# -*- coding: utf-8 -*-\n\"\"\"\n\nField('name', email=True)\n\n\"\"\"\nimport re\n\nfrom ..utils import validatable\n\nemail_regex = re.compile(\n r\"^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\\.[a-zA-Z0-9-.]+$\",\n re.IGNORECASE\n)\n\n\n@validatable(cast_as=str)\ndef email(value):\n \"\"\"\n Return if the provided value is an email.\n \"\"\"\n return email_regex.match(value)\n","sub_path":"goaltender/validators/email.py","file_name":"email.py","file_ext":"py","file_size_in_byte":351,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"370360584","text":"import os\nimport config\nimport exceptions\nfrom constants import NEW_DIR, CURRENT_DIR, SOLVED_DIR\nimport incoming\nimport recipes\nfrom classes import Target\n\n\ndef enumerate_target(target: Target):\n print(f'Processing target {target}')\n output = []\n recipes.run_all_recipe_books(target, output)\n for line in output:\n print(line)\n\n\ndef _check():\n paths = [NEW_DIR, CURRENT_DIR, SOLVED_DIR]\n for path in paths:\n if not os.path.isdir(path):\n raise exceptions.PathMissingException(path)\n\n\nclass LHFE:\n def __init__(self, debug):\n self.debug = debug\n _check()\n\n incoming.initial_tick()\n incoming.tick()\n\n while config.target_stack.not_empty():\n while config.target_stack.not_empty():\n next_target = config.target_stack.pop()\n enumerate_target(next_target)\n incoming.tick()\n\n @classmethod\n def start(cls, debug=True):\n print(f'Initialising (debug={debug})')\n print(f'Using dir \"{os.getcwd()}\"')\n return cls(debug)\n","sub_path":"Current Competition/LHFE/lhfe.py","file_name":"lhfe.py","file_ext":"py","file_size_in_byte":1065,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"639756418","text":"#!python3\n\nimport turtle as tt\nimport math\n\ndef mx( d ):\n tt.up()\n x,y = tt.pos()\n tt.goto( x+d, y )\n tt.down()\n\ndef my( d ):\n tt.up()\n x,y = tt.pos()\n tt.goto( x, y+d )\n tt.down()\n\ndef mov(x,y):\n tt.up()\n tt.goto( x, y )\n tt.down()\n\n\ncol = tt.color\n\ndef cc( radius ): # cc = circle\n tt.up()\n tt.fd(radius)\n tt.left(90)\n tt.down()\n\n tt.begin_fill()\n tt.circle(radius)\n tt.end_fill()\n\n tt.up()\n tt.right(90)\n tt.bk(radius)\n tt.down()\n\ndef moon( radius ):\n x,y = tt.pos()\n tt.seth(0)\n\n tt.up()\n tt.bk(radius)\n tt.down()\n\n start_pos = tt.pos()\n\n tt.color('brown', '#fbbf4b' ) # '#C08040')\n tt.begin_fill()\n\n angle_left_turn = 170\n tt.right( (180-angle_left_turn)/2 )\n\n i = 0\n while True:\n tt.fd(radius*2)\n tt.left( angle_left_turn)\n # print(i, tt.pos(), abs(tt.pos()) )\n i+=1\n if abs(tt.pos()- start_pos) < 1 :\n break\n\n tt.end_fill() \n\n tt.color( 'black', 'white' )\n mov(x,y)\n tt.seth(0)\n\ndef pt(r, n):\n tt.penup()\n tt.goto(0, -r)\n tt.seth(0)\n tt.pendown()\n tt.color( '#C08040' ) # '#fbbf4b' )\n small_r = math.sin( math.pi/n) * r\n \n for i in range(n):\n tt.penup()\n tt.home()\n tt.seth((360/n)*i)\n tt.fd(r)\n tt.left((360/n)*0.5)\n tt.pendown()\n tt.begin_fill()\n tt.circle(small_r,180)\n tt.end_fill()\n\n mov(0,0)\n tt.seth(0)\n tt.color( 'black' )\n\ndef test():\n col( '#f5cf9c' )\n cc(300)\n petal(300,20)\n patt(300)\n\n\nif __name__ == '__main__':\n tt.speed(10)\n\n # test()\n\n col( '#f5cf9c' )\n\n import code\n code.interact(local=locals())\n","sub_path":"turtle/logo.py","file_name":"logo.py","file_ext":"py","file_size_in_byte":1707,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"497072680","text":"from django.conf import settings\nfrom django.conf.urls import patterns, include, url\nfrom django.contrib import admin\n\nurlpatterns = patterns('',\n url('', include('main.urls', namespace='main')),\n url(r'^admin/', include(admin.site.urls)),\n)\n\n\nif settings.DEBUG:\n urlpatterns += patterns('',\n # Для доступа к MEDIA-файлам при разработке\n url(\n r'^media/(?P.*)$',\n 'django.views.static.serve',\n kwargs={'document_root': settings.MEDIA_ROOT}\n ),\n )\n","sub_path":"src/project/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":549,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"190419708","text":"from HTMLTestRunner import HTMLTestRunner\nfrom email.mime.text import MIMEText\nfrom email.header import Header\nimport smtplib\nimport unittest\nimport time\nimport os\n\n\n\ndef send_mail(file_new):\n\tf=open(file_new,'rb') \n\tmail_body=f.read()\n\tf.close()\n\n\tmsg=MIMEText(mail_body,'html','utf-8')\n\tmsg['Subject']=Header('自动化测试报告','utf-8')\n\tsmtp=smtplib.SMTP()\n\tsmtp.connect('smtp.qq.com')\n\tsmtp.login('1172533210@qq.com','xbpyjhmfbmysgjgh')\n\tsmtp.sendmail('1172533210@qq.com','1172533210@qq.com',msg.as_string())\n\tsmtp.quit()\n\tprint('email has send out!')\n\n\ndef new_report(testreport):\n\tlists=os.listdir(testreport)\n\tlists.sort(key=lambda fn:os.path.getmtime(testreport+'\\\\'+fn))\n\tfile_new=os.path.join(testreport,lists[-1])\n\tprint(file_new)\n\treturn file_new\n\nif __name__ == '__main__':\n\n#\ttest_dir='C:\\\\Users\\\\ZMD\\\\Desktop\\\\mztestpro\\\\bbs\\\\test_case'\n#\ttest_report='C:\\\\Users\\\\ZMD\\\\Desktop\\\\mztestpro\\\\bbs\\\\report'\n\ttest_report='../report/'\n#\tprint(test_report)\n\n\tdiscover=unittest.defaultTestLoader.discover('',pattern='*_test.py')\n\tnow_time=time.strftime(\"%Y-%m-%d %H-%M-%S\")\n\tprint(now_time)\n\tfile_name=test_report+now_time+'result.html'\n\tfp=open(file_name,'wb')\n\trunnner=HTMLTestRunner(stream=fp,title='后台管理测试报告',description='用例执行情况:')\n\trunnner.run(discover)\n\tfp.close()\n\tnew_report=new_report(test_report)\n\tsend_mail(new_report)","sub_path":"muggle/test_case/runtest.py","file_name":"runtest.py","file_ext":"py","file_size_in_byte":1371,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"292905235","text":"# -*- coding: UTF-8 -*-\r\nimport requests, json, facebook\r\nimport config\r\n\r\ntoken = config.config_token\r\npayload = {'method':'get','access_token':token}\r\ngraph=facebook.GraphAPI(token)\r\n\r\nuser_id = '100004906542709'\r\nuser_id = '100005863156117'\r\nuser_id = '100005383896449'\r\nr_groups = requests.get('https://graph.facebook.com/' + user_id + '/groups', params=payload).json()\r\nprint(r_groups)\r\nr_name = requests.get(\"https://graph.facebook.com/\" + user_id + \"?fields=name\", params=payload).json()\r\nprint('Các groups mà {} đã tham gia là: '.format(r_name['name']))\r\ni = 0\r\nfor group in r_groups['data']:\r\n i += 1\r\n group_name = group['name']\r\n group_id = group['id']\r\n group_privacy = group['privacy']\r\n print(str(i) + '. Group ' + group_privacy + ' : ' + group_name + ' có ID: ' + group_id)","sub_path":"get_group.py","file_name":"get_group.py","file_ext":"py","file_size_in_byte":809,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"15985373","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Sun Apr 30 15:59:55 2020\r\n\r\n@author: Lvws\r\nemail: 1129309258@qq.com\r\ngithub: https://github.com/lvws/python-breakpoint-restart-Python-\r\n\r\nFunction:\r\nthis module make it easy for any python script recorde results after some time-consuming task;\r\nso if some unpredictable errors happened and crashed your script, it can pass the funcs that has already \r\nsuccessfully finished, just begin from the breakpoint;\r\n\r\nMethod:\r\na. before run your task,import this module, and at the fist run step -- Brestart.preRunCheck() ;\r\ncheck if something wrong ,and wether it needs breakpoint restart;\r\nb. use @Brestart.logFunc to decorate the functions that cost much time,make it a recorde point;\r\nc. finally Brestart.end() at the last run step ,can clear temp log and do not affect next run. \r\n\"\"\"\r\n\r\nimport time,types,pickle,sys,os\r\n\r\nclass Brestart():\r\n\r\n @classmethod\r\n def preRunCheck(self):\r\n \"\"\"\r\n check if something wrong at last time running,and get the info from the log file.\r\n \"\"\"\r\n __recodefile = os.path.join(os.path.dirname(sys.argv[0]),'.'+os.path.basename(sys.argv[0])+'.pkl')\r\n globals()[\"__recodefile\"] = __recodefile\r\n globals()[\"__runtag\"] = 0\r\n globals()[\"_aRunlst\"] = []\r\n globals()[\"_nRunlst\"] = []\r\n globals()[\"__dic\"] = {} \r\n if os.path.exists(__recodefile):\r\n f = open(__recodefile,'rb')\r\n globals()[\"__dic\"] = pickle.load(f)\r\n f.close()\r\n globals()[\"_aRunlst\"] = [x for x in globals()[\"__dic\"][\"__nRunlst\"]]\r\n\r\n # recode if the variable can be pickled, \r\n @classmethod\r\n def add(self):\r\n globals()['_addN'] += 1\r\n\r\n @classmethod\r\n def filter(self,value):\r\n filterTp = [types.FunctionType,types.new_class,types.prepare_class,types.ModuleType] # types cannot be picked\r\n if type(value) == list:\r\n for i in value:\r\n self.filter(i)\r\n if type(value) == dict:\r\n for i in value:\r\n self.filter(value[i])\r\n if type(value) in filterTp:\r\n self.add()\r\n \r\n # recode runinfo and write to log file\r\n @classmethod\r\n def storeTmp(self):\r\n keys = [x for x in globals().keys()] # get variables now \r\n dic = {}\r\n for key in keys:\r\n globals()['_addN'] = 0\r\n self.filter(globals()[key])\r\n if globals()['_addN'] != 0 : continue # do not pickle unpicklable variables\r\n dic['_' + key] = globals()[key] # add prefix to make sure it cannot confused with variables newly generated\r\n with open(globals()[\"__recodefile\"],'wb') as f:\r\n pickle.dump(dic,f)\r\n\r\n @classmethod\r\n def logFuncTest(self,func):\r\n \"\"\"\r\n this decorator can make recode point Test\r\n \"\"\"\r\n def run(*args,**kargs):\r\n globals()[\"_nRunlst\"].append(func.__name__) # recode func name\r\n # pass steps has already fininshed\r\n if globals().get(\"_aRunlst\"):\r\n try: \r\n globals().get(\"_aRunlst\").remove(func.__name__)\r\n print(\"Pass\")\r\n return\r\n except:\r\n raise Exception(\"running sequence change, please remove log file manually\")\r\n\r\n # pass value to variables (last recode form log file); only run once\r\n if globals()[\"__runtag\"] == 0: \r\n for key in globals()[\"__dic\"]:\r\n if key == \"___dic\":continue\r\n globals()[key[1:]] = globals()[\"__dic\"][key]\r\n globals()[\"__runtag\"] = 1\r\n\r\n now = time.time()\r\n print(\"Now Running: \" + func.__name__)\r\n func(*args,**kargs)\r\n print(\"function over,use time: \" + str((time.time() - now)))\r\n self.storeTmp() # recode every success run\r\n return run\r\n\r\n @classmethod\r\n def logFunc(self,func):\r\n \"\"\"\r\n this decorator can make recode point \r\n \"\"\"\r\n def run(*args,**kargs):\r\n globals()[\"_nRunlst\"].append(func.__name__) \r\n if globals().get(\"_aRunlst\"):\r\n try: \r\n globals().get(\"_aRunlst\").remove(func.__name__)\r\n return\r\n except:\r\n raise Exception(\"running sequence change, please remove log file manually\")\r\n\r\n if globals()[\"__runtag\"] == 0: \r\n for key in globals()[\"__dic\"]:\r\n if key == \"___dic\":continue\r\n globals()[key[1:]] = globals()[\"__dic\"][key]\r\n globals()[\"__runtag\"] = 1\r\n\r\n func(*args,**kargs)\r\n self.storeTmp() \r\n return run\r\n\r\n # if it end successfuly remove log file\r\n @classmethod\r\n def end(self):\r\n os.remove(globals()[\"__recodefile\"])","sub_path":"Brestart2/Brestart2/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":4927,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"295955281","text":"import functools\n\nfrom .axes import WithAxes\nfrom .nodeset import NodeSetFunctions\nfrom .xf_func import _xf, LogicOperatorMixin\nfrom .property import Property\n\n\nclass Node(WithAxes, NodeSetFunctions, LogicOperatorMixin):\n \"\"\"\n \"\"\"\n\n def __init__(self, node='.', version=1):\n self._node = node\n self.version = version\n self.clauses = []\n self._inverted = False\n\n def copy(self):\n n = Node(self._node)\n n.clauses = list(self.clauses)\n n._inverted = self._inverted\n n.version = self.version\n return n\n\n __copy__ = copy\n\n def render(self):\n last_one = -1 if (self.clauses and self.clauses[-1] == 'or') else None\n clause_data = ' '.join(self.clauses[:last_one])\n if clause_data:\n clause_data = \"[{}]\".format(clause_data)\n rendered = self._node + clause_data\n\n if self._inverted:\n rendered = \"not(\" + rendered + \")\"\n return rendered\n\n def __str__(self):\n return self.render()\n\n def __eq__(self, other):\n return self.render() == other.render()\n\n def _xf(self, name, *args, **kwargs):\n return _xf(name, self, *args, **kwargs)\n\n def where(self, clause):\n\n def replace_not_equal(clause):\n for neq in {'!=', '<>'}:\n if neq in clause:\n return \"not({})\".format(clause.replace(neq, '='))\n else:\n return clause\n\n new_node = self.copy()\n\n if hasattr(clause, 'render'):\n clause = clause.render()\n else:\n clause = replace_not_equal(clause)\n if self.clauses and not self.clauses[-1] == 'or':\n new_node.clauses.append(\"and\")\n new_node.clauses.append(clause)\n return new_node\n\n def __getattr__(self, item):\n def add_or_and_clause(name):\n method = getattr(self, item[len(name):])\n if self.clauses and not self.clauses[-1] == name:\n self.clauses.append(name)\n return method\n\n if item.startswith('_'):\n item = item[1:]\n\n if item == '':\n return Property(\".\", self)\n else:\n return Property(\"@\" + item, self)\n\n elif item.startswith('not_'):\n return functools.partial(getattr(self, item[3:]), negate=True)\n\n elif item.startswith('or_'):\n return add_or_and_clause('or')\n\n elif item.startswith('and_'):\n return add_or_and_clause('and')\n\n if isinstance(self, Node) and self == Node():\n return Node(item)\n else:\n return self.node(item)\n\n def __getitem__(self, item):\n try:\n item_num = int(item)\n return Node(self.render() + \"[{}]\".format(int(item)))\n except ValueError:\n return self.copy()._[item]\n\n# TODO: convert these to singletons\n_ = Node()._\nroot = Node('/')","sub_path":"course3/test_envi/utils/xpathbuilder/node.py","file_name":"node.py","file_ext":"py","file_size_in_byte":2939,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"384309659","text":"import argparse\nimport os\nfrom tools import *\nfrom gui import *\n\nAppIconDir = \"/usr/share/applications/\" #Change to suit your system. Should be universal to Ubuntu.\n\nclass ApplicationInformation():\n def __init__(self,name):\n self.sudo = False\n self.applicationName = name\n self.comment = None\n self.gname = None\n self.xpath = None\n self.ipath = None\n self.type=\"Application\"\n self.sNotify=\"true\"\n self.categories=None\n self.mType=\"text/plain\"\n \n\n\nif __name__ == \"__main__\":\n usingGUI = False\n parser = argparse.ArgumentParser(description='Creates an icon for an application')\n parser.add_argument('--gui', nargs=1, action='store', metavar='filename',default = '', help='GUI version of program')\n parser.add_argument('--cmd', nargs=1, action='store', metavar='filename',default = '', help='Terminal version of program')\n\n args = parser.parse_args()\n if((args.gui != '') and (args.cmd != '')):\n print(\"Too many arguments. Rerun the program with either --gui or --cmd\")\n exit()\n if(args.gui!=''):\n AppData = ApplicationInformation(args.gui[0])\n usingGUI = True\n if(args.cmd!=''):\n AppData = ApplicationInformation(args.cmd[0])\n if(usingGUI):\n displayFirstWindow(AppData)\n displaySecondWindow(AppData)\n else:\n start()\n AppData.sudo = sudoCheck()\n AppData.comment = readUserInput(\"Enter comment about the application: \")\n AppData.gname = readUserInput(\"Enter a generic name for the application: \")\n AppData.xpath = readUserInput(\"Enter the full path to the application's executable: \")\n AppData.ipath = readUserInput(\"Enter the icon image name: \")\n AppData.categories = readUserInput(\"Enter the categories that the application falls under: \")\n \n try:\n desktopFile = open(AppIconDir+AppData.applicationName+\".desktop\",\"w\")\n except IOError:\n print (\"Could not open file. Exiting Program...\")\n \n desktopFile.write(\"[Desktop Entry]\\n\")\n desktopFile.write(\"Name=\"+ AppData.applicationName+\"\\n\")\n desktopFile.write(\"Comment=\"+AppData.comment+\"\\n\")\n desktopFile.write(\"GenericName=\"+AppData.gname+\"\\n\")\n if(AppData.sudo):\n desktopFile.write(\"Exec=gksudo -u root \"+AppData.xpath+\" %U\\n\")\n else:\n desktopFile.write(\"Exec=\"+AppData.xpath+\" %U\\n\")\n desktopFile.write(\"Icon=\"+AppData.ipath+\"\\n\")\n desktopFile.write(\"Type=Application\\n\")\n desktopFile.write(\"StartupNotify=true\\n\")\n desktopFile.write(\"Categories=\"+AppData.categories+\"\\n\")\n desktopFile.write(\"MimeType=text/plain\")\n desktopFile.close()\n try:\n os.system(\"chmod a+x \"+AppIconDir+AppData.applicationName+\".desktop\")\n except:\n print( \"Error setting runnable permissions for \"+AppData.applicationName+\".desktop\")\n os.remove(AppIconDir+AppData.applicationName+\".desktop\")\n if(usingGUI):\n displayThirdWindow(AppData)\n \n ","sub_path":"UbuntuIconCreator/Python/IconCreator.py","file_name":"IconCreator.py","file_ext":"py","file_size_in_byte":3000,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"438769453","text":"__author__ = 'alefur'\nfrom spsClient import bigFont\nfrom spsClient.modulerow import ModuleRow\nfrom spsClient.sac.ccd import CcdPanel\nfrom spsClient.sac.stage import StagePanel\nfrom spsClient.widgets import ValueGB, ControlDialog\n\n\nclass SacRow(ModuleRow):\n def __init__(self, aitModule):\n ModuleRow.__init__(self, module=aitModule, actorName='sac', actorLabel='SAC')\n\n self.state = ValueGB(self, 'metaFSM', '', 0, '{:s}', fontSize=bigFont)\n self.substate = ValueGB(self, 'metaFSM', '', 1, '{:s}', fontSize=bigFont)\n\n self.pentaPosition = ValueGB(self, 'lsPenta', 'Penta', 2, '{:.3f}', fontSize=bigFont)\n self.detectorPosition = ValueGB(self, 'lsDetector', 'Detector', 2, '{:.3f}', fontSize=bigFont)\n self.controlDialog = SacDialog(self)\n\n @property\n def customWidgets(self):\n\n return [self.state, self.substate, self.pentaPosition, self.detectorPosition]\n\n\nclass SacDialog(ControlDialog):\n def __init__(self, sacRow):\n ControlDialog.__init__(self, moduleRow=sacRow)\n\n self.detectorPanel = StagePanel(self, 'detector')\n self.pentaPanel = StagePanel(self, 'penta')\n self.ccdPanel = CcdPanel(self)\n\n self.tabWidget.addTab(self.detectorPanel, 'Detector Stage')\n self.tabWidget.addTab(self.pentaPanel, 'Penta Stage')\n self.tabWidget.addTab(self.ccdPanel, 'CCD')\n\n @property\n def customWidgets(self):\n return [self.reload] + self.detectorPanel.allWidgets+ self.pentaPanel.allWidgets + self.ccdPanel.allWidgets\n","sub_path":"python/spsClient/sac/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1527,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"235610131","text":"\nimport os\nimport sys\nos.environ[\"CUDA_VISIBLE_DEVICES\"] = \"1\"\nimport time\n\n\nimport matplotlib\n# Force matplotlib to not use any Xwindows backend.\nmatplotlib.use('Agg')\n\nimport skimage.io as img_io\nimport numpy as np\n\nfrom matplotlib import pyplot as plt\n\nimport tensorflow as tf\nfrom tensorflow.contrib import layers as ly\n\ngpu_opt = tf.ConfigProto(gpu_options = tf.GPUOptions(per_process_gpu_memory_fraction=0.95 , allow_growth=True) \n ,device_count={'GPU': 1})\nlogdir=\"VAE-ver0\"\nprocessing_input = lambda x : (x/255-0.5)*2\ninverse_processing = lambda x : (x/2+0.5)*255\n\nl_file_name = (\"KL_loss_1.csv\" , \"MSE_loss_1.csv\")\n\nfig = plt.figure(figsize=[12,4])\nfor i , f in enumerate(l_file_name):\n ax = fig.add_subplot(1,2,i+1)\n ax.set_title(f[0:-4])\n d = np.genfromtxt(os.path.join( \"tmp/{}\".format(logdir) , f),skip_header=1 , delimiter=\",\")\n l = d[:,2]\n ax.plot( range(0,200000 , 200) , l , c=\"orange\")\n ax.grid()\nplt.savefig(\"{}/fig1_2.png\".format(sys.argv[2]))\nplt.show()\n\n\n## load data\ndata_root = sys.argv[1]\ntrain_path = os.path.join( data_root , \"train\" )\ntest_path = os.path.join( data_root , \"test\" )\n\ntrain_attribute = np.genfromtxt( train_path+\".csv\" , delimiter=\",\" , skip_header=0 , dtype=\"str\")\ntest_attribute = np.genfromtxt( test_path+\".csv\" , delimiter=\",\" , skip_header=0 , dtype=\"str\")\n\nattr = train_attribute[0,1::]\nprint(\"Attribute : \")\nprint(\" , \".join(attr[1:8]))\nprint(\" , \".join(attr[8::]))\n\ntrain_id = train_attribute[1:,0]\ntrain_attribute = train_attribute[1:,1::].astype(\"float\")\n\ntest_id = test_attribute[1:,0]\ntest_attribute = test_attribute[1:,1::].astype(\"float\")\n\n## load image\ntrain_img = []\nfor f in train_id:\n train_img.append( img_io.imread( os.path.join( train_path , f ) ) )\n \n\ntest_img = []\nfor f in test_id:\n test_img.append( img_io.imread( os.path.join( test_path , f ) ) )\n\ntrain_img = np.array(train_img).astype(\"float\")\ntest_img = np.array(test_img).astype(\"float\")\n \nprint(\"Shape of training data :\" , train_img.shape)\nprint(\"Shape of testing data :\" , test_img.shape)\n\n\ntrain_data = processing_input(train_img)\ntest_data = processing_input(test_img)\n\n\nVAE_graph = tf.Graph()\n\ndef reconstruct_layer(inputs , tr=True):\n x = ly.fully_connected(inputs , 2048 , trainable=tr \n , scope=\"fc_1\")\n x = tf.reshape( x , shape=[-1,1,1,2048] )\n\n x = ly.conv2d_transpose(x , 512 , [2,2] , padding=\"VALID\" , trainable=tr\n , scope=\"Conv2DT_1\")\n x = ly.conv2d_transpose(x , 256 , [5,5] , padding=\"VALID\" , trainable=tr\n , scope=\"Conv2DT_2\")\n x = ly.batch_norm(x , trainable=tr , scope=\"bc_1\")\n x = ly.conv2d_transpose(x , 128 , [6,6] , stride=[2,2] , padding=\"VALID\" \n , trainable=tr , scope=\"Conv2DT_3\")\n\n x = ly.batch_norm(x , reuse=tf.AUTO_REUSE , scope=\"bc_2\")\n x = ly.conv2d_transpose(x , 64 , [9,9] , stride=[4,4] , padding=\"SAME\" \n , trainable=tr , scope=\"Conv2DT_4\")\n\n out = ly.conv2d(x , 3 , [1,1] , padding=\"VALID\" , activation_fn=tf.nn.tanh \n , trainable=tr , scope=\"To_rgb\")\n return out\n \n\n\nwith VAE_graph.as_default():\n latent_dim = 1024\n \n with tf.name_scope(\"Input\"):\n img = tf.placeholder( shape=[None , 64,64,3] , dtype=tf.float32 )\n \n with tf.name_scope(\"Encode\"):\n with tf.name_scope(\"block1\"):\n _ = ly.conv2d( img , 64 , [5,5] , padding=\"VALID\" )\n _ = ly.conv2d( _ , 96 , [3,3] , padding=\"VALID\" )\n block_1 = ly.avg_pool2d( _ , [3,3] , stride=[2,2] , padding=\"VALID\" )\n \n with tf.name_scope(\"block2\"):\n _ = ly.batch_norm(block_1)\n _ = ly.conv2d( _ , 96 , [3,3] , padding=\"VALID\" )\n _ = ly.conv2d( _ , 128 , [3,3] , padding=\"VALID\" )\n block_2 = ly.max_pool2d( _ , [3,3] , stride=[2,2] , padding=\"VALID\" )\n \n with tf.name_scope(\"block3\"):\n _ = ly.batch_norm(block_2)\n _ = ly.conv2d( _ , 128 , [3,3] , padding=\"VALID\" )\n _ = ly.conv2d( _ , 256 , [1,1] , padding=\"VALID\" )\n _ = ly.conv2d( _ , 256 , [3,3] , padding=\"VALID\" )\n block_3 = ly.avg_pool2d( _ , [2,2] , stride=[1,1] , padding=\"VALID\" )\n \n with tf.name_scope(\"block4\"):\n _ = ly.batch_norm(block_3)\n _ = ly.conv2d( _ , 512 , [3,3] , stride=[2,2] , padding=\"VALID\" )\n block_4 = ly.conv2d( _ , 2048 , [2,2] , padding=\"VALID\" )\n \n flat_code = tf.reshape( block_4 , shape=[-1,2048] , name=\"flat\")\n \n with tf.name_scope(\"z_code\"):\n z_mean = ly.fully_connected(flat_code , latent_dim , activation_fn=tf.nn.tanh , scope=\"z_mean\")\n z_log_var = ly.fully_connected(flat_code , latent_dim , activation_fn=tf.nn.leaky_relu , scope=\"z_log_var\")\n \n with tf.name_scope(\"Sampling\"):\n epsi = tf.random_normal( shape=tf.shape(z_log_var) )\n z = z_mean + epsi*tf.exp(z_log_var/2)\n\n with tf.name_scope(\"Decode\"):\n with tf.variable_scope(\"shared_decoder\"):\n img_reconstruct = reconstruct_layer(z)\n \n \n with tf.name_scope(\"Infer\"):\n with tf.variable_scope(\"shared_decoder\" , reuse=True):\n Infer_img = reconstruct_layer(z_mean , tr=False )\n Infer_loss = tf.reduce_mean( tf.square(Infer_img-img ))\n ## Assign random vector to z \n with tf.name_scope(\"random_infer\"):\n with tf.variable_scope(\"shared_decoder\" , reuse=True):\n random_z = tf.placeholder(shape=[None,latent_dim] , dtype=tf.float32)\n Infer_by_random = reconstruct_layer(random_z , tr=False)\n \n \n with tf.name_scope(\"Loss\"):\n with tf.name_scope(\"KL_loss\"):\n kl_loss = -0.5*tf.reduce_sum( 1+z_log_var-tf.square(z_mean)-tf.exp(z_log_var) ,axis=-1 )\n \n \n with tf.name_scope(\"MSE_loss\"):\n dim = 1\n for d in img.shape[1::]:\n dim *= int(d)\n mse_loss = tf.reduce_mean( tf.reshape(tf.square(img - img_reconstruct) , [-1,dim]),axis=-1)\n \n \n loss = tf.reduce_mean(mse_loss+5e-5*kl_loss)\n tf.summary.scalar(\"Loss/KL_loss\" , tf.reduce_mean(kl_loss)) \n tf.summary.scalar(\"Loss/MSE_loss\" , tf.reduce_mean(mse_loss))\n tf.summary.scalar(\"Total_loss\" , loss)\n \n with tf.name_scope(\"Train_strategy\"):\n decay_policy = tf.train.exponential_decay(2e-4 , decay_rate=0.9 , decay_steps=4000 , global_step=1000)\n opt_operation = tf.train.AdamOptimizer(learning_rate=decay_policy).minimize(loss)\n \n second_opt_operation = tf.train.AdamOptimizer(1e-6).minimize(loss)\n \n init = tf.global_variables_initializer()\n \n# merged_log = tf.summary.merge_all()\n# VAE_writer = tf.summary.FileWriter(\"tb_logs/VAE_ver0\" , graph=VAE_graph)\n \n saver = tf.train.Saver()\n\n\nsess = tf.Session(graph=VAE_graph , config=gpu_opt)\n\nsaver.restore(sess,\"model_para/VAE-ver0\")\n\ndef concat_img(g , col=10):\n concat_all_img = []\n img_count = g.shape[0]\n row_padding = np.zeros(shape=[1 , g.shape[2]*col+col-1,3])\n col_padding = np.zeros(shape=[g.shape[1],1,3])\n for i in range(img_count//col):\n a = g[i*col]\n for j in range(1,col):\n a = np.concatenate( [ a , col_padding , g[ i*col+j ] ] , axis=1 )\n concat_all_img.append(a)\n if i == (img_count//col-1):\n break\n concat_all_img.append(row_padding)\n return np.concatenate( concat_all_img , axis=0 )\n\n\n\npr_img_path = \"tmp/{}\".format(\"VAE-ver0\")\nif not os.path.exists(pr_img_path):\n os.mkdir(pr_img_path)\nprint(pr_img_path)\n\n\nidx = [2314,402,1111,399,41,2169,432,683,218,2455]\n\nplt.style.use(\"classic\")\n\ntest_reconstruct = sess.run(Infer_img , feed_dict={img:test_data[idx]})\n\ntest_reconstruct = np.concatenate([test_img[idx] , inverse_processing(test_reconstruct)] , axis=0)\n\nplt.figure(figsize=(15,4))\nplt.imshow(concat_img(test_reconstruct).astype(\"int\"))\nplt.axis(\"off\")\nplt.savefig(\"{}/fig1_3.png\".format(sys.argv[2]))\n\n\nbatch_z = np.load(\"{}/random_z.npy\".format(pr_img_path))\nrandom_reconstruct = sess.run( Infer_by_random , feed_dict={random_z:batch_z} )\nrandom_reconstruct = inverse_processing(random_reconstruct)\nrandom_reconstruct = concat_img(random_reconstruct , col=8)\n\nplt.figure(figsize=[15,10])\nplt.imshow(random_reconstruct.astype(\"int\"))\nplt.axis(\"off\")\nplt.savefig(\"{}/fig1_4.png\".format(sys.argv[2]))\nplt.show()\n\nfrom sklearn.manifold import TSNE\nprint(\"TSNE\")\nstart_time = time.time()\n\n\nstart = 0\ntest_latent_space = []\n\n# idx = np.random.choice(np.arange(test_data.shape[0]) , size=1000 , replace=False)\nidx = np.load(\"{}/sample_test_data_idx.npy\".format(\"tmp/VAE-ver0\"))\ntest_data = test_data[idx]\n\nbatch_size=100\nfor l in range(test_data.shape[0]//batch_size):\n test_latent_space.append( sess.run(z_mean , feed_dict={img:test_data[start:start+batch_size]}))\n start+=batch_size\n# test_latent_space.append(sess.run(z_mean , feed_dict={img:test_data[start:start+batch_size]}))\n\ntest_latent_space = np.concatenate(test_latent_space , axis=0)\n\n\nreduction_z = TSNE(random_state=1).fit_transform(test_latent_space)\n\n\ni = 2\ntest_attr = test_attribute[:,i:i+1][idx]\nplt.style.use(\"ggplot\")\n\nfig, ax = plt.subplots(figsize=[8,6])\nplt.title(attr[i])\nlabel = [\"non-black\" , \"black\"]\ncolor = [\"navy\" , \"orange\" ]\nfor i in range(2):\n idx = test_attr.reshape(-1)==i\n ax.scatter(reduction_z[idx,0],reduction_z[idx,1] , c=color[i] , label=label[i])\n\nplt.legend()\nplt.savefig(\"{}/fig1_5.png\".format(sys.argv[2]))\nplt.show()\nprint(\"Finish tSNE transform. Time :\" , time.time()-start_time)\n\n","sub_path":"CeleGAN/VAE.py","file_name":"VAE.py","file_ext":"py","file_size_in_byte":9670,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"172222797","text":"inputData = open(\"input.txt\", \"r\")\nlines = inputData.readlines()\n\n# Find total fuel accounting for the mass of each fuel\n# Calculate mass of fuel, divide by 3, round down, then subtract 2.\n# If mass for fuel is 0 or negative, stop calculating, else, keeping calculating\n# Return sum of total fuel for each mass module\n\n\ndef getTotalFuel(mass):\n fuel = int(float(mass) / 3) - 2\n if (fuel <= 0):\n return 0\n else:\n return fuel + getTotalFuel(fuel)\n\n\nprint(sum(list(map(getTotalFuel, lines))))\n","sub_path":"Day1/secondPart.py","file_name":"secondPart.py","file_ext":"py","file_size_in_byte":513,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"129509287","text":"# How Flask gives access to the information the user sent to the server?\n\n# Reference: http://code-maven.com/echo-with-flask-and-python\n\n# Imports\nfrom flask import Flask\nfrom flask import request\n\n# Create an instance of class \"Flask\" with name of running application as the arg \napp = Flask(__name__)\n\n# Decorate or wrap the function inside the app.route function\n@app.route('/') # Responds to request of '/' and sends back HTML snippet\ndef hello():\n \"\"\"\n - action property of form element: tells browser where to send data when user clicks on submit button\n - method attribute: tells browser which method to use\n - When user clicks on submit button the browser will send a GET request to /echo \n \"\"\"\n temp = \"\"\"
\n \n \n
\n \"\"\"\n return temp\n\n# : Name of the field \"text\" is the name of the input element in the HTML\n# \n \n@app.route(\"/echo\") # This route maps the \"/echo\" url to echo function\ndef echo():\n \"\"\"\n - request has an attribute called args \n - args: It is a dictionary holding the data received in the URL\n - Instead of directly accessing the \"text\" key using request.args[\"text\"] use GET method\n - GET method and supply empty string as default value: request.args.get(\"text\", '')\n \"\"\"\n output = request.args.get(\"text\", \"\")\n #output = request.args['text'] # Using http://localhost:5000/echo returns \"Bad Request\"\n return \"You entered: \" + output\n \n \nif __name__ == '__main__':\n # Debug mode gives detailed message in case of an error. Note: Debug mode is HIGHLY INSECURE\n app.run(debug=True)","sub_path":"flask_examples/Example_Get_Post_Request/app_get.py","file_name":"app_get.py","file_ext":"py","file_size_in_byte":1728,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"98427870","text":"import time\ndef get_current_sec():\n\treturn time.time()\n\ndef get_real_time(t):\n\tt=time.localtime(t)\n\tyear=str(t[0])\n\tmonth=str(t[1])\n\tif len(month)==1:\n\t\tmonth='0'+month\n\tday=str(t[2])\n\tif len(day)==1:\n\t\tday='0'+day\n\thour=str(t[3])\n\tif len(hour)==1:\n\t\thour='0'+hour\n\tminute=str(t[4])\n\tif len(minute)==1:\n\t\tminute='0'+minute\n\tsecond=str(t[5])\n\tif len(second)==1:\n\t\tsecond='0'+second\n\treturn year+'-'+month+'-'+day+' '+hour+':'+minute+':'+second\n","sub_path":"time_functions.py","file_name":"time_functions.py","file_ext":"py","file_size_in_byte":443,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"636143618","text":"from em import Error\nfrom em import Interpreter\nfrom io import StringIO\nimport os\nimport shutil\nimport sys\nfrom xml.sax.saxutils import escape\n\ntemplate_basepath = os.path.normpath(\n os.path.join(os.path.dirname(__file__), '..', 'templates'))\n\n\ntemplate_hook = None\n\n\ndef expand_template(template_name, data, options=None):\n global template_hook\n output = StringIO()\n try:\n interpreter = Interpreter(output=output, options=options)\n template_path = os.path.join(template_basepath, template_name)\n # create copy before manipulating\n data = dict(data)\n data['ESCAPE'] = _escape_value\n data['SNIPPET'] = _expand_snippet\n interpreter.file(open(template_path), locals=data)\n value = output.getvalue()\n if template_hook:\n template_hook(template_name, data, value)\n return value\n except Exception as e:\n print(\"%s processing template '%s'\" %\n (e.__class__.__name__, template_name), file=sys.stderr)\n raise\n finally:\n interpreter.shutdown()\n\n\ndef _escape_value(value):\n if isinstance(value, list):\n value = [_escape_value(v) for v in value]\n elif isinstance(value, set):\n value = set([_escape_value(v) for v in value])\n elif isinstance(value, str):\n value = escape(value)\n return value\n\n\ndef _expand_snippet(snippet_name, **kwargs):\n template_name = 'snippet/%s.xml.em' % snippet_name\n try:\n value = expand_template(template_name, kwargs)\n return value\n except Error as e:\n print(\"%s in snippet '%s': %s\" %\n (e.__class__.__name__, snippet_name, str(e)), file=sys.stderr)\n sys.exit(1)\n\n\ndef create_dockerfile(template_name, data, dockerfile_dir):\n data['template_name'] = template_name\n\n wrapper_scripts = {}\n wrapper_script_path = os.path.join(\n os.path.dirname(os.path.dirname(__file__)), 'scripts', 'wrapper')\n for filename in os.listdir(wrapper_script_path):\n if not filename.endswith('.py'):\n continue\n abs_file_path = os.path.join(wrapper_script_path, filename)\n with open(abs_file_path, 'r') as h:\n content = h.read()\n wrapper_scripts[filename] = content\n data['wrapper_scripts'] = wrapper_scripts\n\n content = expand_template(template_name, data)\n dockerfile = os.path.join(dockerfile_dir, 'Dockerfile')\n print(\"Generating Dockerfile '%s':\" % dockerfile)\n for line in content.splitlines():\n print(' ', line)\n with open(dockerfile, 'w') as h:\n h.write(content)\n","sub_path":"ros_buildfarm/templates.py","file_name":"templates.py","file_ext":"py","file_size_in_byte":2579,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"350740820","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue May 22 15:47:09 2018\n\n@author: 20166843\n\"\"\"\nimport access\nimport pandas as pd\nimport numpy as np\n\ndatabase = access.db\nconversationList = []\n\nairlines_id = [\"56377143\", \"106062176\", \"18332190\", \"22536055\", \"124476322\", \"26223583\", \"2182373406\", \"38676903\",\n \"1542862735\", \"253340062\", \"218730857\", \"45621423\", \"20626359\"]\nairlines_names = [\"KLM\", \"AirFrance\", \"British_Airways\", \"AmericanAir\", \"Lufthansa\", \"AirBerlin\", \"AirBerlin assist\",\n \"easyJet\", \"RyanAir\", \"SingaporeAir\", \"Qantas\", \"EtihadAirways\", \"VirginAtlantic\"]\nairlines_other_id = [\"56377143\", \"106062176\", \"18332190\", \"124476322\", \"26223583\", \"2182373406\", \"38676903\",\n \"1542862735\", \"253340062\", \"218730857\", \"45621423\", \"20626359\"]\nairlines_other_names = [\"KLM\", \"AirFrance\", \"British_Airways\", \"Lufthansa\", \"AirBerlin\", \"AirBerlin assist\", \"easyJet\",\n \"RyanAir\", \"SingaporeAir\", \"Qantas\", \"EtihadAirways\", \"VirginAtlantic\"]\n\n\nclass Conversation:\n \n tweets = {}\n reply_ids = []\n \n def __init__(self, tweets = {}):\n self.length = 0\n self.tweets_lst = []\n if tweets != {}:\n Conversation.tweets = tweets\n \n \n def setup(user_id, user_name):\n Conversation.user_id = user_id\n Conversation.user_name = user_name\n \n \n\n def addTweetDict(tweet_id, user, text, time, lang, reply_user = '', reply_tweet = ''):\n Conversation.tweets[tweet_id] = Tweet(tweet_id, user, text, time, lang, reply_user, reply_tweet)\n\n def addTweetConversation(self, tweet_id, end = False):\n tweet = Conversation.tweets[tweet_id]\n if end:\n self.tweets_lst.append(tweet_id)\n else:\n self.tweets_lst = [tweet_id] + self.tweets_lst\n \n tweet_id = tweet.reply_tweet\n if tweet.reply_tweet in Conversation.tweets.keys():\n self.addTweetConversation(tweet_id)\n elif tweet_id != None:\n if self.getTweet(tweet_id):\n self.addTweetConversation(tweet_id)\n \n self.length = len(self)\n\n def getTweet(self, tweetid):\n \n if tweetid in Conversation.tweets.keys():\n return Conversation.tweets[tweetid]\n else:\n q = \"\"\"SELECT * FROM tweets WHERE tweet_id == {}\"\"\".format(tweetid)\n cursor = database.cursor()\n \n try:\n cursor.execute(q)\n tweet = cursor.fetchall()[0]\n database.commit()\n \"\"\"id, date, user, text, replt tweet, reply user, lang\"\"\"\n Conversation.tweets[tweetid] = Tweet(tweet[0], tweet[2], tweet[3],\n tweet[1], tweet[6], tweet[4], tweet[5])\n return True\n except:\n database.commit()\n return None\n \n \n def addTweets(start_date = '2016-02-01 00:00:00', end_date = '2017-06-01 00:00:00'):\n\n query = \"\"\"SELECT * FROM tweets WHERE (user_id == {} OR\n in_reply_to_user_id == {} OR text LIKE '%@{}%') AND\n datetime(created_at) >= datetime('{}') AND\n datetime(created_at) < datetime('{}');\"\"\".format(Conversation.user_id, \n Conversation.user_id, Conversation.user_name, start_date, end_date)\n cursor = database.cursor()\n cursor.execute(query)\n result = cursor.fetchall()\n database.commit()\n for row in result:\n tweet_id = row[0]\n created = row[1]\n user = row[2]\n text = row[3]\n reply_tweet = row[4]\n reply_user = row[5]\n lang = row[6]\n Conversation.addTweetDict(tweet_id, user, text, created, lang,\n reply_user, reply_tweet)\n\n def replyIdList():\n query = \"\"\"SELECT in_reply_to_tweet_id FROM tweets\n WHERE in_reply_to_tweet_id NOT NULL;\"\"\"\n cursor = database.cursor()\n cursor.execute(query)\n result = cursor.fetchall()\n database.commit()\n Conversation.reply_ids = set([i[0] for i in result if i != 'None'])\n \n \n def containsUser(self):\n contains = False\n for tweet in self.tweets_lst:\n tweet = Conversation.tweets[tweet]\n if tweet.user == Conversation.user_id:\n contains = True\n return contains\n \n\n def __len__(self):\n if True:\n return len(self.tweets_lst)\n tweet = Conversation.tweets[self.tweets_lst[0]]\n if tweet.reply_tweet != '':\n return len(self.tweets_lst) + 1\n elif tweet.user in airlines_id and tweet.reply_user != None:\n return len(self.tweets_lst) + 1\n else:\n return len(self.tweets_lst)\n\n def __return__(self):\n return [Conversation.tweets[tweet] for tweet in self.tweets_lst]\n \n \nclass Tweet:\n \n def __init__(self, tweet_id, user, text, time, lang, reply_user = '', reply_tweet = ''):\n self.tweet_id = tweet_id\n self.user = user\n self.text = text\n self.lang = lang\n self.reply_user = reply_user\n self.reply_tweet = reply_tweet\n self.time = time\n \n def __str__(self):\n return 'ID:{} user:{} text:{} lang:{} reply_user:{} reply_tweet:{} created:{}'.format(self.tweet_id,\n self.user, self.text, self.lang, self.reply_user, self.reply_tweet, self.time)\n \ndef listToDict(lst):\n dicti = {}\n for i in lst:\n if str(i) in dicti.keys():\n dicti[str(i)] = dicti[str(i)] + 1\n else:\n dicti[str(i)] = 1\n return dicti\n \ndef makeConversations(user_id, user_name):\n Conversation.setup(user_id, user_name)\n Conversation.replyIdList()\n Conversation.addTweets()\n\n for tweet_id in list(Conversation.tweets.keys()):\n if not tweet_id in Conversation.reply_ids:\n conversation = Conversation()\n conversation.addTweetConversation(tweet_id)\n if conversation.length > 1 and conversation.containsUser():\n conversationList.append(conversation)\n times = [len(conv) for conv in conversationList]\n return listToDict(times)\n\n\nmakeConversations(user_id = '22536055', user_name='AmericanAir')\ntimes = [len(conv) for conv in conversationList]\n\ndicti = listToDict(times)\nprint(dicti)\n\n\n \ndef processTweet(tweet):\n # process the tweets\n \n #Convert to lower case\n tweet = tweet.lower()\n #Convert www.* or https?://* to URL\n tweet = re.sub('((www.[^\\s]+)|(https?://[^\\s]+))','URL',tweet)\n #Convert @username to AT_USER\n tweet = re.sub('@[^\\s]+','AT_USER',tweet)\n #Remove additional white spaces\n tweet = re.sub('[\\s]+', ' ', tweet)\n #Replace #word with word\n tweet = re.sub(r'#([^\\s]+)', r'\\1', tweet)\n #trim\n return tweet\n\ntweet_ids_lst = []\ntweet_text_lst = []\ntweet_sentiment_score = []\ncounter = 0\nfor key in Conversation.tweets.keys():\n tweet_ids_lst.append(key)\n \n proctweet = processTweet(Conversation.tweets[key].text)\n tweet_text_lst.append(proctweet)\n \n blob = TextBlob(proctweet)\n tweet_sentiment_score.append(blob.sentiment.polarity)\n print(counter)\n counter += 1\n\n\nfor i in range(len(tweet_ids_lst)):\n conversation.tweets[tweet_ids_lst[i]].sentiment = tweet_sentiment_score[i]\n\n\n","sub_path":"Sentiment.py","file_name":"Sentiment.py","file_ext":"py","file_size_in_byte":7340,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"9000159","text":"# is_in_comparison.py\n\nprimeNumbers = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29]\n\nprint(2 in primeNumbers)\nprint(12 in primeNumbers)\n\ninputNum = int(input(\"30 이하의 자연수를 입력해주세요: \"))\nisPrime = False\n\nif inputNum > 30 or inputNum < 1:\n print(\"잘못된 입력입니다\")\nelse:\n if inputNum in primeNumbers:\n isPrime = True\n\n if isPrime is True:\n print(str(inputNum) + \": 소수입니다\")\n else: \n print(str(inputNum) + \": 소수가 아닙니다\")","sub_path":"season1/day4_compound_loop1/in_comparison.py","file_name":"in_comparison.py","file_ext":"py","file_size_in_byte":496,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"41503940","text":"\"\"\"\nThe files are in a variety of formats. This script will convert all to pdf.\n\"\"\"\nfrom glob import glob\nimport shutil\n\nimport pandas as pd\nimport tabula\nimport odf\n\ndef main():\n \"\"\"\n Convert all files to csv files, saved in directory csvfiles.\n \"\"\"\n dirname = \"csvfiles\"\n\n # old excel files\n for filename in glob(\"*xls\"):\n print(filename)\n df = pd.read_excel(filename, sheet_name=None)\n for i, d in enumerate(df.values(), 1):\n outfile = f\"{dirname}/{i}_\" + filename.replace(\"xls\", \"csv\")\n print(outfile)\n d.to_csv(outfile)\n\n # modern excel files\n for filename in glob(\"*xlsx\"):\n print(filename)\n df = pd.read_excel(filename, sheet_name=None)\n for i, d in enumerate(df.values(), 1):\n outfile = f\"{dirname}/{i}_\" + filename.replace(\"xlsx\", \"csv\") \n print(outfile)\n d.to_csv(outfile)\n\n # open office files\n for filename in glob(\"*ods\"):\n print(filename)\n df = pd.read_excel(filename, sheet_name=None, engine=\"odf\")\n for i, d in enumerate(df.values(), 1):\n outfile = f\"{dirname}/{i}_\" + filename.replace(\"ods\", \"csv\")\n print(outfile)\n d.to_csv(outfile)\n\n # pdf files, 1 table per file\n for filename in glob(\"*pdf\"):\n print(filename)\n df = tabula.read_pdf(filename, pages=1)[0]\n outfile = f\"{dirname}/1_\" + filename.replace(\"pdf\", \"csv\")\n print(outfile)\n df.to_csv(f\"{dirname}/1_\" + filename.replace(\"pdf\", \"csv\"))\n\n # copy csv files\n for filename in glob(\"*csv\"):\n print(filename)\n shutil.copyfile(filename, f\"1_{dirname}/{filename}\")\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"converttocsv.py","file_name":"converttocsv.py","file_ext":"py","file_size_in_byte":1725,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"301102054","text":"import logging\nimport os\nfrom src.controller.constants.constants_dto import ConstantsDTO\n\n\nclass ConstantsFactory():\n\n @staticmethod\n def get_constants_dto(enviroment=None):\n if enviroment==\"development\":\n return ConstantsFactory.__get_development_constants()\n elif enviroment==\"production\":\n return ConstantsFactory.__get_production_constants()\n else:\n return None\n\n @staticmethod\n def __get_production_constants():\n return ConstantsDTO(\n transaction_endpoint=\"/transactions\",\n log_endpoint=\"/logs\",\n health_endpoint=\"/health\",\n status_endpoint=\"/status\",\n homepage_endpoint=\"/\",\n webscket_endpoint=\"/websocket\",\n filter_endpoint=\"/filter\",\n log_file=\"./src/controller/logs/processing_node.log\",\n default_loggin_level=logging.INFO,\n eureka_app_name=\"OutputHandler\",\n eureka_heartbeat_interval=15,\n eureka_host= os.environ.get(\"EUREKA_SERVICE_SERVICE_HOST\"),\n eureka_port=int(os.environ.get(\"EUREKA_SERVICE_SERVICE_PORT\")),\n output_host=os.environ.get(\"MS_OUTPUT_SERVICE_ROUTE_HOST\"),\n output_port=int(os.environ.get(\"MS_OUTPUT_SERVICE_ROUTE_PORT\")),\n mysql_host=os.environ.get(\"MYSQL_SERVICE_SERVICE_HOST\"),\n mysql_port=int(os.environ.get(\"MYSQL_SERVICE_SERVICE_PORT\")),\n mysql_database=\"transactions\",\n mysql_user=\"innocloud\",\n mysql_pass=\"1234\"\n )\n\n @staticmethod\n def __get_development_constants():\n return ConstantsDTO(\n transaction_endpoint=\"/transactions\",\n log_endpoint=\"/logs\",\n health_endpoint=\"/health\",\n status_endpoint=\"/status\",\n homepage_endpoint=\"/\",\n webscket_endpoint=\"/websocket\",\n filter_endpoint=\"/filter\",\n log_file=\"./src/controller/logs/processing_node.log\",\n default_loggin_level=logging.INFO,\n eureka_app_name=\"OutputHandler\",\n eureka_heartbeat_interval=15,\n eureka_host= \"192.168.56.102\",\n eureka_port=8080,\n output_host=\"localhost\",\n output_port=9992,\n mysql_host=\"192.168.56.102\",\n mysql_port=3306,\n mysql_database=\"transactions\",\n mysql_user=\"innocloud\",\n mysql_pass=\"1234\"\n )\n","sub_path":"src/controller/constants/constants_factory.py","file_name":"constants_factory.py","file_ext":"py","file_size_in_byte":2447,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"273458825","text":"\nimport pyodbc\nimport csv\nimport pandas as pd\ncon = pyodbc.connect('DRIVER={ODBC Driver 13 for SQL Server};SERVER=172.16.100.7;DATABASE=JV3_JDI_PIM;UID=uatuser;PWD=uat@123')\n\n\ncur = con.cursor()\nquerystring = \"select * from testing\"\ncur.execute(querystring)\n\nrow = cur.fetchall()\n\n\nwith open('abcd.user', 'w', newline= '') as f:\n a = csv.writer(f, delimiter=',')\n a.writerows(row) ## closing paren added\n\nu_cols = ['name', 'age', 'class']\nusers = pd.read_csv('test1.csv', sep=',', names=u_cols,encoding='latin-1')\nprint (users)","sub_path":"movie-recommendation-using-turicreate/db.py","file_name":"db.py","file_ext":"py","file_size_in_byte":534,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"199226583","text":"#3-3\nclass froggo(object):\n\n def __init__(self, c, xpos, ypos, xspeed):\n self.c = c\n self.xpos = xpos\n self.ypos = ypos\n self.xspeed = xspeed\n \n def display(self):\n stroke(0)\n fill(self.c)\n rectMode(CENTER)\n rect(self.xpos, self.ypos, 20, 10);\n \n def drive(self):\n self.xpos = self.xpos + self.xspeed;\n if self.xpos > width:\n self.xpos = 0\n \nmyfroggo1 = froggo(color(255, 144, 133), 0, 150, 3)\nmyfroggo2 = froggo(color(0, 255, 130), 0, 50, 13)\nmyfroggo3 = froggo(color(1, 144, 133), 0, 80,10)\nmyfroggo4 = froggo(color(22, 255, 130), 0, 5, 1)\n \ndef setup():\n size(200,200)\n\ndef draw(): \n background(255)\n myfroggo1.drive()\n myfroggo1.display()\n myfroggo2.drive()\n myfroggo2.display()\n myfroggo3.drive()\n myfroggo3.display()\n myfroggo4.drive()\n myfroggo4.display()\n#I changed a number of the parameters from the Car example given, and renamed it to froggo.\n#I gave the frogs a variety of green shade, but for one.\n#Because I thought the coral was cute.\n#I also changed where they appeared in their neat little frog race.\n#And gave them different speeds. \n#Some frogs just weren't feeling this race and move slowly.\nclass squiggleline(object):\n c=color(255)\n \ndef draw():\n frameRate(5)\n println(pmouseX - mouseX)\n \ndef setup():\n size(200, 200)\n strokeWeight(8)\n\n\ndef draw():\n line(mouseX, mouseY, pmouseX, pmouseY)\n#3-4 \n#Not sure if all of this is supposed to be in the same code, but I'm completing the tasks.\n#I named the class squiggle and set the color to black?\n#I think?\n#I made a draw function that creates a line that stays written on the background.\n#Orginally, the background autorefreshed so the lines wouldn't stay. Removing this piece of code makes the drawing stay.\n#Now the line stays. \n#I also changed the frame rate, size and stroke weight to something managable.\n#3-5\n#I haven't been able to make more than one element run at once. \n#I think part of this has to do with some updates to python. For example, the keyPress code didn't work and I had to find a different one online.\n#I think in theory, that if we didn't redefine the draw function each time, the code would stay visible.\n#But I'm not how to do this, since draw is a set function in processing. I think it's like print?\n","sub_path":"Lab 3/processing2/processing2.pyde","file_name":"processing2.pyde","file_ext":"pyde","file_size_in_byte":2343,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"36727671","text":"import xarray as xr\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport matplotlib\nimport matplotlib.gridspec as gridspec\nfrom matplotlib.gridspec import GridSpec\nfrom matplotlib import rcParams, animation\nfrom matplotlib import style\nfrom matplotlib.ticker import MaxNLocator\nfrom datetime import datetime,timedelta\nmatplotlib.rcParams['animation.embed_limit'] = 2**128\n\ndef animate_unburned(ds):\n \n # get colors\n c = plt.rcParams['axes.prop_cycle'].by_key()['color']\n \n # set style\n style.use('seaborn-notebook')\n \n # set up figure\n fig = plt.figure(\n tight_layout = True,\n figsize = [13,5]\n )\n \n # define axes\n gs = gridspec.GridSpec(8,4)\n ax0 = fig.add_subplot(gs[3:,:])\n ax1 = fig.add_subplot(gs[0:3,0])\n ax2 = fig.add_subplot(gs[0:3,1])\n ax3 = fig.add_subplot(gs[0:3,2])\n ax4 = fig.add_subplot(gs[0:3,3])\n ax5 = fig.add_subplot(gs[3:,0])\n ax6 = fig.add_subplot(gs[3:,1])\n ax7 = fig.add_subplot(gs[3:,2])\n ax8 = fig.add_subplot(gs[3:,3])\n \n # get list of dates\n dates = pd.date_range(\n start = '2005-10-01',\n periods = 365,\n freq = 'D'\n )\n \n def update(frame):\n \n ##########################\n ### RUNOFF TIME SERIES ###\n ##########################\n \n # clear all\n ax1.cla()\n \n # add runoff time series\n ax1.fill_between(\n x = ds.t.values,\n y1 = 0,\n y2 = ds.net_runoff_unburned.mean(dim=['group','sample']),\n color = 'silver',\n alpha = 0.2\n )\n \n ax1.fill_between(\n x = ds.isel(t=slice(None,frame)).t.values,\n y1 = 0,\n y2 = ds.isel(t=slice(None,frame)).net_runoff_unburned.mean(dim=['group','sample']),\n color = c[0],\n alpha = 0.5\n )\n \n # housekeeping\n ax1.set_ylim([-100,1000])\n plt.setp(ax1.get_xticklabels(), visible=False)\n plt.setp(ax1.get_yticklabels(), visible=False)\n ax1.spines['top'].set_visible(False)\n ax1.spines['bottom'].set_visible(False)\n ax1.spines['left'].set_visible(False)\n ax1.spines['right'].set_visible(False)\n ax1.tick_params(top = False)\n ax1.tick_params(bottom = False)\n ax1.tick_params(left = False)\n ax1.tick_params(right = False)\n \n ##########################\n ### SOIL TIME SERIES ###\n ##########################\n \n # clear all\n ax2.cla()\n \n # add soil time series\n ax2.fill_between(\n x = ds.t.values,\n y1 = 0,\n y2 = ds.soil_unburned.mean(dim=['group','sample']),\n color = 'silver',\n alpha = 0.2\n )\n \n ax2.fill_between(\n x = ds.isel(t=slice(None,frame)).t.values,\n y1 = 0,\n y2 = ds.isel(t=slice(None,frame)).soil_unburned.mean(dim=['group','sample']),\n color = c[1],\n alpha = 0.5\n )\n \n # housekeeping\n ax2.set_ylim([-100,1000])\n plt.setp(ax2.get_xticklabels(), visible=False)\n plt.setp(ax2.get_yticklabels(), visible=False)\n ax2.spines['top'].set_visible(False)\n ax2.spines['bottom'].set_visible(False)\n ax2.spines['left'].set_visible(False)\n ax2.spines['right'].set_visible(False)\n ax2.tick_params(top = False)\n ax2.tick_params(bottom = False)\n ax2.tick_params(left = False)\n ax2.tick_params(right = False)\n \n ######################\n ### ET TIME SERIES ###\n ######################\n \n # clear all\n ax3.cla()\n \n # add soil time series\n ax3.fill_between(\n x = ds.t.values,\n y1 = 0,\n y2 = ds.et_unburned.mean(dim=['group','sample']),\n color = 'silver',\n alpha = 0.2\n )\n \n ax3.fill_between(\n x = ds.isel(t=slice(None,frame)).t.values,\n y1 = 0,\n y2 = ds.isel(t=slice(None,frame)).et_unburned.mean(dim=['group','sample']),\n color = c[2],\n alpha = 0.5\n )\n \n # housekeeping\n ax3.set_ylim([-100,1000])\n plt.setp(ax3.get_xticklabels(), visible=False)\n plt.setp(ax3.get_yticklabels(), visible=False)\n ax3.spines['top'].set_visible(False)\n ax3.spines['bottom'].set_visible(False)\n ax3.spines['left'].set_visible(False)\n ax3.spines['right'].set_visible(False)\n ax3.tick_params(top = False)\n ax3.tick_params(bottom = False)\n ax3.tick_params(left = False)\n ax3.tick_params(right = False)\n \n #######################\n ### SWE TIME SERIES ###\n #######################\n\n # clear all\n ax4.cla()\n \n # add swe timeseries\n ax4.fill_between(\n x = ds.t.values,\n y1 = 0,\n y2 = ds.swe_burned.mean(dim=['group','sample']),\n color = 'silver',\n alpha = 0.05\n )\n \n ax4.fill_between(\n x = ds.t.values,\n y1 = 0,\n y2 = ds.swe_unburned.mean(dim=['group','sample']),\n color = 'silver',\n alpha = 0.05\n )\n \n ax4.fill_between(\n x = ds.isel(t=slice(None,frame)).t.values,\n y1 = 0,\n y2 = ds.isel(t=slice(None,frame)).swe_unburned.mean(dim=['group','sample']),\n color = 'tab:grey',\n alpha = 0.3,\n label = 'Unburned'\n )\n \n ax4.fill_between(\n x = ds.isel(t=slice(None,frame)).t.values,\n y1 = 0,\n y2 = ds.isel(t=slice(None,frame)).swe_burned.mean(dim=['group','sample']),\n color = c[3],\n alpha = 0.5,\n label = 'Burned'\n )\n \n # add peak and melt markers\n \n if frame < dates.get_loc(ds.swe_burned.attrs['peak']):\n mc = 'silver'\n alph = 0.05\n \n else:\n mc = c[3]\n alph = 0.5\n \n ax4.scatter(\n x = ds.swe_burned.attrs['peak'],\n y = ds.swe_burned.mean(dim=['group','sample']).sel(t=ds.swe_burned.attrs['peak'])+60,\n marker = 'v',\n color = mc,\n alpha = alph\n )\n \n if frame < dates.get_loc(ds.swe_unburned.attrs['peak']):\n mc = 'silver'\n alph = 0.1\n \n else:\n mc = 'tab:grey'\n alph = 0.5\n \n ax4.scatter(\n x = ds.swe_unburned.attrs['peak'],\n y = ds.swe_unburned.mean(dim=['group','sample']).sel(t=ds.swe_unburned.attrs['peak'])+60,\n marker = 'v',\n color = mc,\n alpha = alph\n )\n \n if frame < dates.get_loc(ds.swe_burned.attrs['melted']):\n mc = 'silver'\n alph = 0.05\n \n else:\n mc = c[3]\n alph = 0.5\n \n ax4.scatter(\n x = ds.swe_burned.attrs['melted'],\n y = ds.swe_burned.mean(dim=['group','sample']).sel(t=ds.swe_burned.attrs['melted'])-60,\n marker = '^',\n color = mc,\n alpha = alph\n )\n \n if frame < dates.get_loc(ds.swe_unburned.attrs['melted']):\n mc = 'silver'\n alph = 0.05\n \n else:\n mc = 'tab:grey'\n alph = 0.5\n \n ax4.scatter(\n x = ds.swe_unburned.attrs['melted'],\n y = ds.swe_unburned.mean(dim=['group','sample']).sel(t=ds.swe_unburned.attrs['melted'])-60,\n marker = '^',\n color = mc,\n alpha = alph\n )\n \n # housekeeping\n ax4.set_ylim([-100,1000])\n plt.setp(ax4.get_xticklabels(), visible=False)\n plt.setp(ax4.get_yticklabels(), visible=False)\n ax4.spines['top'].set_visible(False)\n ax4.spines['bottom'].set_visible(False)\n ax4.spines['left'].set_visible(False)\n ax4.spines['right'].set_visible(False)\n ax4.tick_params(top = False)\n ax4.tick_params(bottom = False)\n ax4.tick_params(left = False)\n ax4.tick_params(right = False)\n \n ######################\n ### RUNOFF SCATTER ###\n ######################\n \n # clear all\n ax5.cla()\n \n # add center line\n ax5.axhline(\n 0,\n linestyle = '--',\n linewidth = 1,\n color = 'silver',\n alpha = 0.5\n )\n \n # add runoff mpd scatter\n ds.isel(t=frame).sel(group='MPD').plot.scatter(\n ax = ax5,\n x = 'init_soil_burned',\n y = 'norm_net_runoff_unburned',\n color = c[0],\n marker = 'o',\n add_guide = False,\n alpha = 0.6,\n label = 'MPD'\n )\n \n # add runoff nn scatter\n ds.isel(t=frame).sel(group='NN').plot.scatter(\n ax = ax5,\n x = 'init_soil_burned',\n y = 'norm_net_runoff_unburned',\n color = c[0],\n marker = 'x',\n add_guide = False,\n alpha = 0.3,\n label = 'NN'\n )\n \n # add runoff r scatter\n ds.isel(t=frame).sel(group='R').plot.scatter(\n ax = ax5,\n x = 'init_soil_burned',\n y = 'norm_net_runoff_unburned',\n color = c[0],\n marker = 's',\n add_guide = False,\n alpha = 0.1,\n label = 'R'\n )\n \n # housekeeping\n ax5.set_xlim([278,295])\n ax5.set_ylim([-25,25])\n ax5.set_ylabel('Depth [mm]')\n ax5.set_xlabel('')\n ax5.set_title('Net Runoff')\n ax5.spines['right'].set_visible(False)\n ax5.spines['top'].set_visible(False)\n ax5.tick_params(left = False)\n ax5.tick_params(bottom = False)\n ax5.set_xticks([280,293])\n ax5.set_yticks([-25,0,25])\n ax5.legend(\n loc = 'lower right',\n fontsize = 'x-small'\n )\n \n ######################\n ### SOIL SCATTER ###\n ######################\n \n # clear all\n ax6.cla()\n \n # add center line\n ax6.axhline(\n 0,\n linestyle = '--',\n linewidth = 1,\n color = 'silver',\n alpha = 0.5\n )\n \n # add soil mpd scatter\n ds.isel(t=frame).sel(group='MPD').plot.scatter(\n ax = ax6,\n x = 'init_soil_burned',\n y = 'norm_soil_unburned',\n color = c[1],\n marker = 'o',\n add_guide = False,\n alpha = 0.6,\n label = 'MPD'\n )\n \n # add soil nn scatter\n ds.isel(t=frame).sel(group='NN').plot.scatter(\n ax = ax6,\n x = 'init_soil_burned',\n y = 'norm_soil_unburned',\n color = c[1],\n marker = 'x',\n add_guide = False,\n alpha = 0.3,\n label = 'NN'\n )\n \n # add soil r scatter\n ds.isel(t=frame).sel(group='R').plot.scatter(\n ax = ax6,\n x = 'init_soil_burned',\n y = 'norm_soil_unburned',\n color = c[1],\n marker = 's',\n add_guide = False,\n alpha = 0.1,\n label = 'R'\n )\n \n # housekeeping\n ax6.set_xlim([278,295])\n ax6.set_ylim([-25,25])\n ax6.set_ylabel('')\n ax6.set_xlabel('')\n ax6.set_title('$\\Delta$ Soil Storage')\n ax6.spines['right'].set_visible(False)\n ax6.spines['top'].set_visible(False)\n ax6.tick_params(left = False)\n ax6.tick_params(bottom = False)\n ax6.set_xticks([280,293])\n ax6.set_yticks([-25,0,25])\n ax6.legend(\n loc = 'lower right',\n fontsize = 'x-small'\n )\n \n ######################\n ### ET SCATTER ###\n ######################\n \n # clear all\n ax7.cla()\n \n # add center line\n ax7.axhline(\n 0,\n linestyle = '--',\n linewidth = 1,\n color = 'silver',\n alpha = 0.5\n )\n \n # add et mpd scatter\n ds.isel(t=frame).sel(group='MPD').plot.scatter(\n ax = ax7,\n x = 'init_soil_burned',\n y = 'norm_et_unburned',\n color = c[2],\n marker = 'o',\n add_guide = False,\n alpha = 0.6,\n label = 'MPD'\n )\n \n # add et nn scatter\n ds.isel(t=frame).sel(group='NN').plot.scatter(\n ax = ax7,\n x = 'init_soil_burned',\n y = 'norm_et_unburned',\n color = c[2],\n marker = 'x',\n add_guide = False,\n alpha = 0.3,\n label = 'NN'\n )\n \n # add et r scatter\n ds.isel(t=frame).sel(group='R').plot.scatter(\n ax = ax7,\n x = 'init_soil_burned',\n y = 'norm_et_unburned',\n color = c[2],\n marker = 's',\n add_guide = False,\n alpha = 0.1,\n label = 'R'\n )\n \n # housekeeping\n ax7.set_xlim([278,295])\n ax7.set_ylim([-25,25])\n ax7.set_ylabel('')\n ax7.set_xlabel('')\n ax7.set_title('ET')\n ax7.spines['right'].set_visible(False)\n ax7.spines['top'].set_visible(False)\n ax7.tick_params(left = False)\n ax7.tick_params(bottom = False)\n ax7.set_xticks([280,293])\n ax7.set_yticks([-25,0,25])\n ax7.legend(\n loc = 'lower right',\n fontsize = 'x-small'\n )\n \n ######################\n ### SWE SCATTER ###\n ######################\n \n # clear all\n ax8.cla()\n \n # add center line\n ax8.axhline(\n 0,\n linestyle = '--',\n linewidth = 1,\n color = 'silver',\n alpha = 0.5\n )\n \n # add swe mpd scatter\n ds.isel(t=frame).sel(group='MPD').plot.scatter(\n ax = ax8,\n x = 'init_soil_burned',\n y = 'norm_swe_unburned',\n color = 'tab:grey',\n marker = 'o',\n add_guide = False,\n alpha = 0.6,\n label = 'MPD'\n )\n \n # add swe nn scatter\n ds.isel(t=frame).sel(group='NN').plot.scatter(\n ax = ax8,\n x = 'init_soil_burned',\n y = 'norm_swe_unburned',\n color = 'tab:grey',\n marker = 'x',\n add_guide = False,\n alpha = 0.3,\n label = 'NN'\n )\n \n # add swe r scatter\n ds.isel(t=frame).sel(group='R').plot.scatter(\n ax = ax8,\n x = 'init_soil_burned',\n y = 'norm_swe_unburned',\n color = 'tab:grey',\n marker = 's',\n add_guide = False,\n alpha = 0.1,\n label = 'R'\n )\n \n # housekeeping\n ax8.set_xlim([278,295])\n ax8.set_ylim([-25,25])\n ax8.set_ylabel('')\n ax8.set_xlabel('')\n ax8.set_title('SWE')\n ax8.spines['right'].set_visible(False)\n ax8.spines['top'].set_visible(False)\n ax8.tick_params(left = False)\n ax8.tick_params(bottom = False)\n ax8.set_xticks([280,293])\n ax8.set_yticks([-25,0,25])\n ax8.legend(\n loc = 'lower right',\n fontsize = 'x-small'\n )\n \n ##########################\n ### FINAL HOUSEKEEPING ###\n ##########################\n \n fig.suptitle('Unburned Areas\\n' + str(dates[frame])[:10])\n \n ax0.spines['top'].set_visible(False)\n ax0.spines['bottom'].set_visible(False)\n ax0.spines['left'].set_visible(False)\n ax0.spines['right'].set_visible(False)\n ax0.tick_params(top = False)\n ax0.tick_params(bottom = False)\n ax0.tick_params(left = False)\n ax0.tick_params(right = False)\n ax0.set_xticks([])\n ax0.set_yticks([])\n ax0.set_xlabel('Initial Soil Storage [mm]',labelpad=25)\n \n \n anim = animation.FuncAnimation(\n fig,\n update,\n frames = 365,\n interval = 100,\n repeat = False\n )\n \n plt.close()\n \n return anim","sub_path":"pfAnimateUNBURNED.py","file_name":"pfAnimateUNBURNED.py","file_ext":"py","file_size_in_byte":16660,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"116589442","text":"import binascii\n\nn = 7 # number of ciphertexts in the current directory\n\nciphertexts = []\nfor i in range(1,n+1):\n\tctext = open('ctext' + str(i) + '.txt','r').read()\n\tciphertexts.append(binascii.unhexlify(ctext))\n\nsize_ctext = len(ciphertexts[0])\n\n'''\nThe idea is to associate each character with a state.\nIn order to do that, for every character in every message\nwe store a tuple (s,c) where\n\t- s = state\n\t- c = possible character\nThe possible values for s is:\n\t- -1: without information yet\n\t- 0 : the character is a letter (but unknown)\n\t- 1 : the character is a known letter (stored in c) or a space\n\t- 2 : the character is known (stored in c)\n\n'''\n\nplaintexts = []\nfor i in range(n):\n\tplaintexts.append([(-1,'') for j in range(size_ctext)])\n\nspace = 32\nfor i in range(n-1):\n\tfor k in range(1,n):\n\t\tfor j in range(size_ctext):\n\t\t\tc = ciphertexts[i][j] ^ ciphertexts[(i+k)%n][j]\n\t\t\tbits = format(c,'08b')[:2]\n\n\t\t\tstate1 = plaintexts[i][j]\n\t\t\tstate2 = plaintexts[(i+k)%n][j]\n\t\t\tletter = chr(space ^ c)\n\n\t\t\tif state1[0] == -1:\n\t\t\t\tif bits == '00': state1 = (0,'')\n\t\t\t\tif bits == '01': \n\t\t\t\t\tif state2[1] == ' ':\n\t\t\t\t\t\tstate1 = (2,letter)\n\t\t\t\t\telse:\n\t\t\t\t\t\tstate1 = (1,letter)\n\n\t\t\telif state1[0] == 0:\n\t\t\t\tif bits == '01': state1 = (2,letter)\n\n\t\t\telif state1[0] == 1:\n\t\t\t\tif bits == '00': state1 = (2,state1[1])\n\t\t\t\tif bits == '01': \n\t\t\t\t\tif state1[1] != letter:\n\t\t\t\t\t\tstate1 = (2,' ')\n\t\t\t\t\telse:\n\t\t\t\t\t\tpass\n\n\t\t\tif state2[0] == -1:\n\t\t\t\tif bits == '00': state2 = (0,'')\n\t\t\t\tif bits == '01': \n\t\t\t\t\tif state1[1] == ' ':\n\t\t\t\t\t\tstate2 = (2,letter)\n\t\t\t\t\telse:\n\t\t\t\t\t\tstate2 = (1,letter)\n\n\t\t\telif state2[0] == 0:\n\t\t\t\tif bits == '01': state2 = (2,letter)\n\n\t\t\telif state2[0] == 1:\n\t\t\t\tif bits == '00': state2 = (2,state2[1])\n\t\t\t\tif bits == '01': \n\t\t\t\t\tif state2[1] != letter:\n\t\t\t\t\t\tstate2 = (2,' ')\n\t\t\t\t\telse:\n\t\t\t\t\t\tpass\t\n\n\t\t\tplaintexts[i][j] = state1\n\t\t\tplaintexts[(i+k)%n][j] = state2 \n\n\t\tmesg = []\n\t\tfor j in range(size_ctext):\n\t\t\tif plaintexts[i][j][0] == -1:\n\t\t\t\tmesg.append(']')\n\t\t\tif plaintexts[i][j][0] == 0:\n\t\t\t\tmesg.append('>')\t\t\t\t\t\t\t\n\t\t\tif plaintexts[i][j][0] == 1:\n\t\t\t\tmesg.append('^')\n\t\t\t\tmesg.append(plaintexts[i][j][1])\n\t\t\tif plaintexts[i][j][0] == 2:\n\t\t\t\tmesg.append(plaintexts[i][j][1])\n\t\t\n\t\tprint(''.join(mesg))\n\n\tprint('\\n')\n\nprint('\\n')\n\nfor i in range(n):\n\tmesg = []\n\tfor j in range(size_ctext):\n\t\tif plaintexts[i][j][0] == -1:\n\t\t\tmesg.append(']')\n\t\tif plaintexts[i][j][0] == 0:\n\t\t\tmesg.append('>')\t\t\t\t\t\t\t\n\t\tif plaintexts[i][j][0] == 1:\n\t\t\tmesg.append('^')\n\t\t\tmesg.append(plaintexts[i][j][1])\n\t\tif plaintexts[i][j][0] == 2:\n\t\t\tmesg.append(plaintexts[i][j][1])\n\t\t\n\tprint(''.join(mesg))\n","sub_path":"onetime_pad.py","file_name":"onetime_pad.py","file_ext":"py","file_size_in_byte":2594,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"645941761","text":"from sklearn import tree\nfrom read_data import *\nmax_model = None\nmax_valacc = 0\nvals3 = (0,0,0)\nfor d in range (1, 20):\n for mins in range (2, 10):\n for minleaf in range(1, 10):\n clf = tree.DecisionTreeClassifier(criterion=\"entropy\", max_depth=d, min_samples_split=mins, min_samples_leaf=minleaf)\n model = clf.fit(train_data, train_labels)\n valid_score = 100.0 * model.score(valid_data, valid_labels)\n print (d, mins, minleaf, valid_score)\n if valid_score > max_valacc:\n max_valacc = valid_score\n max_model = model\n vals3 = (d, mins, minleaf)\n'''\nmin_sample_split : The minimum number of samples required to split an internal node\nmin_samples_leaf : The minimum number of samples required to be at a leaf node\nmax_depth : The maximum depth of the tree. If None, then nodes are expanded until all leaves are pure or until all leaves contain less than min_samples_split samples.\n'''\nprint (\"Parameters\", vals3)\ntrain_score = 100.0 * max_model.score(train_data, train_labels)\nvalid_score = 100.0 * max_model.score(valid_data, valid_labels)\ntest_score = 100.0 * max_model.score(test_data, test_labels)\n\nprint (train_score, valid_score, test_score)\n","sub_path":"Assignment3/q1/q1d.py","file_name":"q1d.py","file_ext":"py","file_size_in_byte":1255,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"58928776","text":"from flask import Flask, render_template, request, redirect, url_for, Blueprint, flash\nfrom models.post import Post\nfrom flask_login import current_user\nfrom instagram_web.util.helpers import upload_file_to_s3\nfrom app import app\n\nposts_blueprint = Blueprint('posts',\n __name__,\n template_folder='templates')\n\n@posts_blueprint.route('/new', methods=['GET'])\ndef new():\n return render_template('posts/new.html')\n\n@posts_blueprint.route('/', methods=['POST'])\ndef create():\n if \"newpic\" not in request.files:\n return \"No newpic key in request.files\"\n\n file = request.files[\"newpic\"]\n\n if file.filename == \"\":\n return \"Please select a file\"\n\n\t# D.\n if file and current_user.is_authenticated:\n # if file and allowed_file(file.filename):\n # file.filename = secure_filename(file.filename)\n filename = file.filename\n # output = upload_file_to_s3(file, app.config[\"S3_BUCKET\"], filename=str(current_user.id)+'/'+filename)\n upload_file_to_s3(file, app.config[\"S3_BUCKET\"], filename=str(current_user.id)+'/'+filename)\n new_post = Post(user_id = current_user.id, post_image = filename)\n new_post.save()\n return redirect(url_for('users.show', username=current_user.username))\n #http://my-bucket-now.s3.amazonaws.com/Screenshot_168.png\n\n else:\n return redirect(\"/\")\n","sub_path":"instagram_web/blueprints/posts/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1405,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"158839311","text":"#!/usr/bin/env python3\n\n\nfrom response import Response\nfrom request import Request\nfrom config import Config\nfrom datetime import datetime\nimport sys\nimport traceback\n\n\nclass MVCException:\n\n httpState = {\n 'ImportError': 404,\n }\n\n @staticmethod\n def debug(name, msg, tb):\n errfile = '%s'\n errfile = errfile % tb[-1].split('\\n')[0].strip()\n s = \"

\"\n s += '请求信息: %s

'\n s += \"异常信息 (%s):

\"\n s += '  %s

'\n s = s % (Request.url, errfile, msg)\n\n s += \"异常类:
  %s

\" % name.__name__\n\n s += \"异常栈信息:
\"\n for i in tb:\n m = i.split(\"\\n\")\n s += \"  \" + m[0] + \"
\"\n s += '    '\n s += m[1]\n s += '

'\n\n s += \"
\"\n s += \"配置信息:

\"\n for k, v in Config.items():\n if not isinstance(v, dict):\n s += '%s: %s

' % (k, v)\n continue\n\n s += '%s:

' % k\n\n for ks in v:\n s += '  '\n s += '%s: %s

'\n s = s % (ks, v[ks])\n\n s += \"
\"\n s += \"环境变量:

\"\n for e in Request.env:\n s += '%s: %s' % (e, Request.env[e])\n s += '

'\n\n s += \"

\"\n\n return s\n\n @staticmethod\n def log(name, msg, tb):\n # 时间 IP PATH 错误位置 错误信息\n time = datetime.now().strftime(\"%F %T\")\n errfile = tb[-1].split('\\n')[0].strip()\n s = \"[%s] %s->%s (%s) %s\" % (time, Request.addr, Request.path,\n errfile, msg)\n\n print(s, file=open(Config.LOG_FILE, \"a\"))\n\n return '

%s

' % Config.DEFAULT['ERROR']\n\n @staticmethod\n def do():\n name, msg, tb = sys.exc_info()\n tb = traceback.format_tb(tb)\n\n if Config.DEBUG:\n body = MVCException.debug(name, msg, tb)\n else:\n body = MVCException.log(name, msg, tb)\n\n return Response(body, MVCException.httpState.get(name.__name__, 400))\n\n\n","sub_path":"kyo/python/web/mvc/core/exception.py","file_name":"exception.py","file_ext":"py","file_size_in_byte":2436,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"326758466","text":"from __future__ import print_function\nfrom collections import Counter\nimport string\nimport re\nimport argparse\nimport json\nimport sys\ndef normalize_answer(s):\n \"\"\"Lower text and remove punctuation, articles and extra whitespace.\"\"\"\n def remove_articles(text):\n return re.sub(r'\\b(a|an|the)\\b', ' ', text)\n\n def white_space_fix(text):\n return ' '.join(text.split())\n\n def remove_punc(text):\n exclude = set(string.punctuation)\n return ''.join(ch for ch in text if ch not in exclude)\n\n def lower(text):\n return text.lower()\n\n return white_space_fix(remove_articles(remove_punc(lower(s))))\ndef f1_score(prediction, ground_truth):\n prediction_tokens = normalize_answer(prediction).split()\n ground_truth_tokens = normalize_answer(ground_truth).split()\n common = Counter(prediction_tokens) & Counter(ground_truth_tokens)\n num_same = sum(common.values())\n if num_same == 0:\n return 0\n precision = 1.0 * num_same / len(prediction_tokens)\n recall = 1.0 * num_same / len(ground_truth_tokens)\n f1 = (2 * precision * recall) / (precision + recall)\n return f1\n\nf=open(\"/Users/apple/Downloads/project_3/out_pred6.txt\",\"r\",encoding='utf-8')\nlines=f.readlines()\ncorrect_count=0\ntotal_count=0\nf1=0\nfor line in lines: \n span=line.split('\\t')\n span[-1]=span[-1].strip()\n span_id=span[0]\n span_num=span[2:]\n g_s=list(range(int(span_num[0]),int(span_num[1])+1))\n p_s=list(range(int(span_num[2]),int(span_num[3])+1))\n ground_truth_span=' '.join([str(x) for x in g_s])\n prediction_span=' '.join([str(x) for x in p_s])\n f1=f1+f1_score(prediction_span,ground_truth_span)\n total_count+=1\n if span_num[0]==span_num[2] and span_num[1]==span_num[3]:\n correct_count+=1\nave_f1=f1/total_count\nprint(ave_f1)\nave_acc=correct_count/total_count\nprint(ave_acc)\n\n","sub_path":"evaluation/EMF1.py","file_name":"EMF1.py","file_ext":"py","file_size_in_byte":1850,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"503116504","text":"from kart import Kart\nfrom kart import miners, mappers, renderers, modifiers\n\nkart = Kart()\n\n\ndef tag_dict(site):\n site[\"tag_post_count\"] = {}\n for tag in site[\"tags\"]:\n posts = site[\"posts\"]\n post_num = len([post for post in posts if tag[\"slug\"] in post[\"tags\"]])\n site[\"tag_post_count\"][tag[\"slug\"]] = post_num\n\n\nkart.miners = [\n miners.DefaultPostMiner(\"posts\"),\n miners.DefaultCollectionMiner(\"tags\"),\n miners.DefaultCollectionMiner(\"projects\"),\n miners.DefaultDataMiner(),\n miners.DefaultPageMiner(),\n]\n\nkart.mappers = [\n mappers.DefaultBlogMapper(base_url=\"/blog\"),\n mappers.DefaultCollectionMapper(\n collection_name=\"projects\", template=\"project.html\"\n ),\n mappers.DefaultPageMapper(),\n mappers.DefaultFeedMapper(),\n]\n\nkart.modifiers = [modifiers.TagModifier(), modifiers.RuleModifier([tag_dict])]\n\nkart.renderers = [\n renderers.DefaultSiteRenderer(),\n renderers.DefaultFeedRenderer(collections=[\"posts\", \"projects\"]),\n renderers.DefaultSitemapRenderer(),\n]\n\nkart.config[\"name\"] = \"Giacomo Caironi\"\nkart.config[\"base_url\"] = \"https://giacomocaironi.github.io\"\n\nkart.run()\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1152,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"181983984","text":"# coding=utf-8\n\n\"\"\"Custom Implementations of various Qt Widgets\"\"\"\n\nimport PyQt4.QtGui as qg\nimport PyQt4.QtCore as qc\nfrom Misc.GlobalVars import *\n\n\n# Organization\nclass GuiSimpleGroup(qg.QGraphicsItemGroup):\n \"\"\"Simplifies adding unnamed Qt items to a shared group\"\"\"\n def __init__(self, selectable=False):\n super(GuiSimpleGroup, self).__init__()\n if selectable:\n self.setFlag(qSelectable, enabled=True)\n\n def add(self, item, pos_x=None, pos_y=None, pen=None, brush=None, color=None, tooltip=None, selectable=False):\n \"\"\"Adds a new item with specifiable attributes\"\"\"\n self.addToGroup(item)\n if pos_x and pos_y: item.setPos(pos_x, pos_y)\n if pen: item.setPen(pen)\n if brush: item.setBrush(brush)\n if color: item.setDefaultTextColor(color)\n if tooltip: item.setToolTip(tooltip)\n if selectable: item.setFlag(qSelectable, enabled=True)\n\n\nclass GuiSimpleFrame(qg.QGroupBox):\n \"\"\"A Frame with name and grid\"\"\"\n def __init__(self, name):\n super(GuiSimpleFrame, self).__init__(name)\n self.grid = qg.QGridLayout()\n self.setLayout(self.grid)\n\n def addWidget(self, widget, *args):\n \"\"\"Reimplement grid addWidget\"\"\"\n self.grid.addWidget(widget, *args)\n\n\n# Custom Animation Objects\nclass GuiObjectWithAnim(object):\n \"\"\"Object with Qt Animation Properties\"\"\"\n def __init__(self, parent_obj):\n self.parent_obj = parent_obj\n # Animation Boolean\n self.running = False\n\n def reset_timers_anims(self, duration):\n \"\"\"Resets timers and animations with new durations\"\"\"\n # Timer\n self.timer = qc.QTimeLine(duration)\n self.timer.setCurveShape(qc.QTimeLine.LinearCurve)\n self.timer.setFrameRange(0, duration * 1000)\n # Animation Object\n self.anim = qg.QGraphicsItemAnimation()\n self.anim.setItem(self.parent_obj)\n self.anim.setTimeLine(self.timer)\n\n\nclass GuiTextWithAnim(qg.QGraphicsTextItem, GuiObjectWithAnim):\n \"\"\"Qt Text Object with Animation Properties\"\"\"\n def __init__(self, text, color, z_stack):\n qg.QGraphicsTextItem.__init__(self, text)\n GuiObjectWithAnim.__init__(self, parent_obj=self)\n self.setDefaultTextColor(color)\n self.setZValue(z_stack)\n\n\nclass GuiLineWithAnim(qg.QGraphicsLineItem, GuiObjectWithAnim):\n \"\"\"Qt Line Object with Animation Properties\"\"\"\n def __init__(self, dimensions, color, z_stack):\n qg.QGraphicsLineItem.__init__(self, *dimensions) # @dimensions: x, y, w, h\n GuiObjectWithAnim.__init__(self, parent_obj=self)\n self.setPen(color)\n self.setZValue(z_stack)\n\n\n# Custom Entry Types\nclass GuiEntryWithWarning(qg.QLineEdit):\n \"\"\"A line entry with a triggerable visual warning\"\"\"\n def __init__(self, default_text=''):\n super(GuiEntryWithWarning, self).__init__()\n self.visual_warning_stage = 0\n if default_text:\n self.setText(str(default_text))\n\n def visual_warning(self, times_to_flash=3):\n \"\"\"Triggers several flashes from white to red, num defined by times_to_flash\"\"\"\n if self.visual_warning_stage == times_to_flash:\n self.setStyleSheet(qBgWhite)\n self.visual_warning_stage = 0\n return\n if self.visual_warning_stage % 2 == 0:\n self.setStyleSheet(qBgRed)\n else:\n self.setStyleSheet(qBgWhite)\n self.visual_warning_stage += 1\n qc.QTimer.singleShot(150, lambda t=times_to_flash: self.visual_warning(t))\n\n\nclass GuiIntOnlyEntry(GuiEntryWithWarning):\n \"\"\"An entry that takes only integers, with options for boundary values and max digits allowed\"\"\"\n def __init__(self, max_digits=None, default_text='', minimum=None, maximum=None):\n super(GuiIntOnlyEntry, self).__init__(default_text)\n self.max_digits = max_digits\n self.last_valid_entry = str(default_text)\n self.min = minimum\n self.max = maximum\n self.initialize()\n\n def initialize(self):\n \"\"\"Sets up entry conditions and connects signals/slots\"\"\"\n if self.max_digits:\n self.setMaxLength(self.max_digits)\n self.textEdited.connect(self.check_text_edit)\n\n def check_text_edit(self):\n \"\"\"Checks that entries are valid\"\"\"\n # Check if we entered a space before the text\n if self.text().startswith(' '):\n self.setText(self.last_valid_entry)\n self.setCursorPosition(0)\n # Main check\n text = self.text().strip()\n if not text:\n self.last_valid_entry = ''\n pos = 0\n else:\n try:\n # did we input a valid integer?\n int(text)\n except ValueError:\n # if not, we revert to entry before it was invalid\n pos = self.cursorPosition() - 1\n else:\n # if valid integer, we update the last valid data\n self.last_valid_entry = text\n pos = self.cursorPosition()\n # we check if our valid integer is beyond the min/max bounds we set\n if self.min and (int(text) < self.min):\n self.last_valid_entry = str(self.min)\n elif self.max and (int(text) > self.max):\n self.last_valid_entry = str(self.max)\n self.setText(self.last_valid_entry)\n self.setCursorPosition(pos)\n\n def set_min_max_value(self, minimum, maximum):\n \"\"\"sets the min/max values of the entry\"\"\"\n self.min = minimum\n self.max = maximum\n\n\nclass GuiDropdownWithWarning(qg.QComboBox):\n \"\"\"A line entry with a triggerable visual warning\"\"\"\n def __init__(self, default_text=''):\n super(GuiDropdownWithWarning, self).__init__()\n self.visual_warning_stage = 0\n if default_text:\n self.setText(str(default_text))\n\n def visual_warning(self, times_to_flash=3):\n \"\"\"Triggers several flashes from white to red, num defined by times_to_flash\"\"\"\n if self.visual_warning_stage == times_to_flash:\n self.setStyleSheet(qBgWhite)\n self.visual_warning_stage = 0\n return\n if self.visual_warning_stage % 2 == 0:\n self.setStyleSheet(qBgRed)\n else:\n self.setStyleSheet(qBgWhite)\n self.visual_warning_stage += 1\n qc.QTimer.singleShot(150, lambda t=times_to_flash: self.visual_warning(t))\n\n\n# Custom Buttons\nclass GuiFlipBtn(qg.QPushButton):\n \"\"\"A PushButton with 2 states; single toggle function\"\"\"\n def __init__(self, default_msg, flipped_msg, default_color='', flipped_color=''):\n super(GuiFlipBtn, self).__init__(default_msg)\n if default_color:\n self.setStyleSheet(default_color)\n self.state = 'default'\n self.default = default_msg, default_color\n self.flipped = flipped_msg, flipped_color\n\n def toggle_state(self):\n \"\"\"Flip the message and color of button\"\"\"\n if self.state == 'default':\n self.state = 'flipped'\n self.setText(self.flipped[0])\n self.setStyleSheet(self.flipped[1])\n elif self.state == 'flipped':\n self.state = 'default'\n self.setText(self.default[0])\n self.setStyleSheet(self.default[1])\n\n\nclass GuiMultiStateBtn(qg.QPushButton):\n \"\"\"A PushButton with multiple states\"\"\"\n def __init__(self, default_msg, default_color=None, **states):\n super(GuiMultiStateBtn, self).__init__(default_msg)\n if default_color:\n self.setStyleSheet(default_color)\n self.default = default_msg, default_color\n for state in states:\n setattr(self, state, states[state])\n\n def toggle_state(self, state):\n \"\"\"Flip the message and color of button\"\"\"\n state = getattr(self, state)\n self.setText(state[0])\n self.setStyleSheet(state[1])\n","sub_path":"QT_Mouse_Track_Stim/GUI/MiscWidgets.py","file_name":"MiscWidgets.py","file_ext":"py","file_size_in_byte":7925,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"543039079","text":"import os\nimport os.path as op\nimport shutil\nfrom pathlib import Path\nfrom pdf2image import convert_from_path\nimport PIL\nimport subprocess\nimport sys\nimport argparse\n\n\ndef convert_from_pdf_to_png(path_to_pdf, path_to_png):\n pages = convert_from_path(path_to_pdf, 500)\n pages[0].save(path_to_png, 'PNG')\n\n\ndef trim_png(path_to_input, path_to_output):\n im = PIL.Image.open(path_to_input)\n bg = PIL.Image.new(im.mode, im.size, im.getpixel((0,0)))\n diff = PIL.ImageChops.difference(im, bg)\n diff = PIL.ImageChops.add(diff, diff, 2.0, -100)\n bbox = diff.getbbox()\n if bbox:\n im.crop(bbox).save(path_to_output)\n\ndef convert_tex_to_trimmedpng(path_to_input):\n # paths refs\n # path_to_input = rf\"C:\\Users\\devoted_w\\Documents\\snippets_tops\\sth-knowledge\\mini_projects\\proj_latex\\input\\test.tex\"\n input_filename = op.basename(path_to_input)\n cwd = op.abspath(op.join(path_to_input, op.pardir, op.pardir))\n path_to_tempdir = op.join(cwd, \"temp\")\n path_to_input_copy = op.join(path_to_tempdir, input_filename)\n path_to_intermediate = Path(path_to_input_copy).with_name(\"intermediate\").with_suffix(\".png\")\n path_to_output = Path(cwd).joinpath(\"output\").joinpath(input_filename).with_suffix(\".png\")\n\n # proper work\n os.mkdir(path_to_tempdir)\n shutil.copyfile(path_to_input, path_to_input_copy)\n os.system(f'cd temp && pdflatex -shell-escape {input_filename}')\n convert_from_pdf_to_png(Path(path_to_input_copy).with_suffix(\".pdf\"), path_to_intermediate)\n trim_png(path_to_intermediate, path_to_output)\n shutil.rmtree(path_to_tempdir)\n try:\n subprocess.Popen(rf'explorer /select,\"{path_to_output}\"')\n except FileNotFoundError:\n # subprocess.Popen(f'xdg-open {path_to_output.parent}/')\n os.system(f'xdg-open {path_to_output.parent}')\n\n\ndef parse_arguments(input_):\n input_ = input_[1:]\n parser = argparse.ArgumentParser()\n parser.add_argument('path_to_input', type=str)\n return parser.parse_args(input_)\n\n\ndef main(input):\n parsed_args = parse_arguments(input)\n convert_tex_to_trimmedpng(**vars(parsed_args))\n return 0\n\n\nif __name__ == '__main__':\n sys.exit(main(sys.argv))","sub_path":"mini_projects/proj_latex/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2183,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"92343274","text":"import zipfile\nimport os\n\nzipArray = [\n\t\".nuxt\",\n\t\"server\",\n\t\"static\",\n\t\"nuxt.config.js\",\n\t\"package.json\",\n]\n\ndef zip_dirs(dirArray):\n\tpwd = os.getcwd()\n\tpwdName = os.path.basename(pwd)\n\tzipfilename = pwdName + \".zip\"\n\tz = zipfile.ZipFile(zipfilename,'w',zipfile.ZIP_DEFLATED)\n\tamount = float(0)\n\tcount = 0\n\tfor path in dirArray:\n\t\tif os.path.isdir(path) :\n\t\t\tfor root, dirs, files in os.walk(path) :\n\t\t\t\tamount +=len(files)\n\t\t\t\tfor file in files:\n\t\t\t\t\tfpath = root + os.sep + file\n\t\t\t\t\tz.write(fpath) \t\n\t\t\t\t\tcount +=1\t\t\t\t\t\n\n\t\telse :\n\t\t\tz.write(path)\n\t\t\tamount +=1\n\t\t\tcount +=1 \n\t\tprint (\"\\r\" + str(count) + \"/\" + str(int(amount))) +\"(\"+(str(round(count / amount * 100,2)))+\"%)\",\n\n\n\tz.close()\n\tprint ('Finish')\n\nif __name__ == '__main__':\n\tzip_dirs(zipArray)","sub_path":"shum-buildr/zip.py","file_name":"zip.py","file_ext":"py","file_size_in_byte":761,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"119994714","text":"# File :app.py\nfrom appium import webdriver\nfrom page.basepage import BasePage\nfrom page.main_page import MainPage\n\n\nclass App(BasePage):\n def start(self):\n if self.driver is None:\n caps = {\n \"platformName\": \"android\",\n \"deviceName\": \"127.0.0.1:7555\",\n \"appPackage\": \"com.tencent.wework\",\n \"appActivity\": \".launch.LaunchSplashActivity\",\n \"noReset\": \"true\",\n \"ensureWebviewsHavePages\": True,\n # 设置页面等待空闲状态时间为0s\n \"settings[waitForIdleTimeout]\": 0\n }\n self.driver = webdriver.Remote(\"http://localhost:4723/wd/hub\", caps)\n self.driver.implicitly_wait(10)\n else:\n # 自动拉取Capabilities配置信息启动,不需要任何初始化操作\n self.driver.launch_app()\n return self\n\n def restart(self):\n self.driver.quit()\n self.driver.launch_app()\n return self\n\n def stop(self):\n self.driver.quit()\n return self\n\n def goto_main(self) -> MainPage:\n return MainPage(self.driver)\n","sub_path":"test-app/page/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1161,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"423978019","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun Sep 23 15:04:34 2018\n\n@author: jeanmarioml\n\"\"\"\n\n#Perceptron de UMA camada\n\ninputs = [-1, 7, 5]\nweights = [0.8, 0.1, 0]\n\ndef soma(_input, _weight):\n s = 0\n for i in range(3):\n # print(inputs[i])\n # print(weights[i])\n s += _input[i] * _weight[i]\n return s\n \n \ns = soma(inputs,weights)\n\ndef stepFunction(_sum):\n if(_sum >= 1):\n return 1\n return 0\n\nresult = stepFunction(s)","sub_path":"RNA-python/one_layer_perceptron.py","file_name":"one_layer_perceptron.py","file_ext":"py","file_size_in_byte":489,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"83156214","text":"import json\nfrom collections import defaultdict\n\n# NaiveBayes for training\n\n#traingingDict structure:\n#{\"politics\":{\"word_probability\":{\"all\":...,\"four\":...,...},\"class_probability\":...,\"class_tokens\":...},\n# \"business\":{\"word_probability\":{\"all\":...,\"four\":...,...},\"class_probability\":...,\"class_tokens\":...},\n# \"entertainment\":{\"word_probability\":{\"all\":...,\"four\":...,...},\"class_probability\":...,\"class_tokens\":...}\n#}\n \nclass training():\n \n def calCondProb(self, trainingDict, classname):\n trainingDict[classname]['word_prob'] = defaultdict(int)\n sum_class_tokens = 0\n for token in trainingDict[classname]['class_tokens']:\n trainingDict[classname]['word_prob'][token] += 1\n sum_class_tokens += 1\n \n # calculate probability for each token\n # condProb[class][token] = (occurrenceOfToken + 1) / (sumOfAllTokens + differentTokens)\n classTokenSet = set (trainingDict[classname]['class_tokens'])\n for token in trainingDict[classname]['class_tokens']:\n Tct = trainingDict[classname]['word_prob'][token] \n trainingDict[classname]['word_prob'][token] = 1.0 * ( Tct + 1 )/(sum_class_tokens + len(classTokenSet))\n\n \n def extractVocabulary (self, rootPath, classname, Queries, stpoWordsList):\n class_tokens = []\n NcDocs = 0\n for queryname in Queries:\n fileName = rootPath + classname + '\\\\' + queryname + '.json'\n f = open(fileName, 'r')\n for line in f.readlines():\n result = json.loads(line.strip('\\n'))\n text = result['description']\n NcDocs += 1\n for word in text.split():\n class_tokens.append(word)\n return class_tokens, NcDocs\n \n \n def buildTrainingDict(self, rootPath, classNames, Queries, stpoWordsList): \n # extract vocabulary from all the docs\n trainingDict = defaultdict (defaultdict)\n for classname in classNames:\n class_tokens, NcDocs = self.extractVocabulary(rootPath, classname, Queries, stpoWordsList)\n trainingDict[classname]['class_tokens'] = class_tokens \n trainingDict[classname]['class_prob'] = NcDocs\n \n # count all the docs\n NtDocs = 0\n for classname in classNames:\n NtDocs += trainingDict[classname]['class_prob']\n \n # calculate the prior probability for each class \n # and condition probablity for each token\n vocabulary = set()\n for classname in classNames:\n trainingDict[classname]['class_prob'] = (1.0 * trainingDict[classname]['class_prob'] )/ NtDocs\n trainingDict[classname]['class_words_prob'] = self.calCondProb(trainingDict, classname)\n vocabulary = vocabulary.union( set(trainingDict[classname]['class_tokens']) ) \n \n return trainingDict, vocabulary\n \n\n","sub_path":"HW3/src/training.py","file_name":"training.py","file_ext":"py","file_size_in_byte":2957,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"165157283","text":"\"\"\"\n:copyright: (c) 2014 Building Energy Inc\n\"\"\"\nimport json\n\nfrom django.utils.unittest import TestCase\nfrom django.http import HttpResponse, HttpResponseForbidden\nfrom seed.lib.superperms.orgs.models import (\n ROLE_VIEWER,\n ROLE_MEMBER,\n ROLE_OWNER,\n Organization,\n OrganizationUser,\n)\nfrom seed.landing.models import SEEDUser as User\n\n\n#\n# Copied wholesale from django-brake's tests\n# https://github.com/gmcquillan/django-brake/blob/master/brake/tests/tests.py\nfrom seed.lib.superperms.orgs import decorators\n\n\nclass FakeRequest(object):\n \"\"\"A simple request stub.\"\"\"\n __name__ = 'FakeRequest'\n method = 'POST'\n META = {'REMOTE_ADDR': '127.0.0.1'}\n path = 'fake_login_path'\n body = None\n\n def __init__(self, headers=None):\n if headers:\n self.META.update(headers)\n\n\nclass FakeClient(object):\n \"\"\"An extremely light-weight test client.\"\"\"\n\n def _gen_req(self, view_func, data, headers, method='POST', **kwargs):\n request = FakeRequest(headers)\n if 'user' in kwargs:\n request.user = kwargs.get('user')\n if callable(view_func):\n # since we check for a GET first for organization_id, then the body\n setattr(request, 'GET', {})\n setattr(request, method, data)\n request.body = json.dumps(data)\n return view_func(request)\n\n return request\n\n def get(self, view_func, data, headers=None, **kwargs):\n return self._gen_req(view_func, data, headers, method='GET', **kwargs)\n\n def post(self, view_func, data, headers=None, **kwargs):\n return self._gen_req(view_func, data, headers, **kwargs)\n\n\n# These are test functions wrapped in decorators.\n\n@decorators.has_perm('derp')\ndef _fake_view_no_perm_name(request):\n return HttpResponse()\n\n\n@decorators.has_perm('can_invite_member')\ndef _fake_invite_user(request):\n return HttpResponse()\n\n\nclass TestDecorators(TestCase):\n def setUp(self):\n super(TestDecorators, self).setUp()\n self.client = FakeClient()\n self.fake_org = Organization.objects.create(name='fake org')\n self.fake_member = User.objects.create(\n username='fake_member',\n email='fake_member@asdf.com'\n )\n self.fake_superuser = User.objects.create_superuser(\n username='fake_super_member',\n password='so fake, so real',\n email='fake_super_member@asdf.com'\n )\n self.fake_owner = User.objects.create(\n username='fake_owner',\n email='fake_owner@asdf.com'\n )\n self.fake_viewer = User.objects.create(\n username='fake_viewer',\n email='fake_viewer@asdf.com'\n )\n self.owner_org_user = OrganizationUser.objects.create(\n user=self.fake_owner,\n organization=self.fake_org,\n role_level=ROLE_OWNER\n )\n self.member_org_user = OrganizationUser.objects.create(\n user=self.fake_member,\n organization=self.fake_org,\n role_level=ROLE_MEMBER\n )\n self.viewer_org_user = OrganizationUser.objects.create(\n user=self.fake_viewer,\n organization=self.fake_org,\n role_level=ROLE_VIEWER\n )\n self.superuser_org_user = OrganizationUser.objects.create(\n user=self.fake_superuser,\n organization=self.fake_org,\n role_level=ROLE_VIEWER\n )\n\n def tearDown(self):\n \"\"\"WTF DJANGO.\"\"\"\n User.objects.all().delete()\n Organization.objects.all().delete()\n OrganizationUser.objects.all().delete()\n super(TestDecorators, self).tearDown()\n\n # Test has_perm in various permutations.\n\n def test_has_perm_w_no_org(self):\n \"\"\"We should return BadRequest if there's no org.\"\"\"\n self.client.user = User.objects.create(username='f', email='d@d.com')\n resp = self.client.post(\n _fake_view_no_perm_name,\n {'organization_id': 0},\n user=self.client.user\n )\n error_msg = {\n 'status': 'error', 'message': 'Organization does not exist'\n }\n\n self.assertEqual(resp.status_code, 403)\n self.assertEqual(resp.__class__, HttpResponseForbidden)\n self.assertDictEqual(json.loads(resp.content), error_msg)\n\n def test_has_perm_user_not_in_org(self):\n \"\"\"We should reject requests from a user not in this org.\"\"\"\n self.client.user = User.objects.create(username='f', email='d@d.com')\n resp = self.client.post(\n _fake_view_no_perm_name,\n {'organization_id': self.fake_org.pk},\n user=self.client.user\n )\n\n error_msg = {\n 'status': 'error', 'message': 'No relationship to organization'\n }\n\n self.assertEqual(resp.status_code, 403)\n self.assertDictEqual(json.loads(resp.content), error_msg)\n\n def test_has_perm_w_no_perm_name(self):\n \"\"\"Default to false if an undefined perm is spec'ed\"\"\"\n self.client.user = self.fake_member\n resp = self.client.post(\n _fake_view_no_perm_name,\n {'organization_id': self.fake_org.pk},\n user=self.fake_member\n )\n\n self.assertEqual(resp.status_code, 403)\n\n def test_has_perm_w_super_user(self):\n \"\"\"Make sure that a superuser is ignored if setting is True.\"\"\"\n super_user = User.objects.create(username='databaser')\n\n resp = self.client.post(\n _fake_invite_user,\n {'organization_id': self.fake_org.pk},\n user=self.fake_member\n )\n\n error_msg = {\n 'status': 'error', 'message': 'Permission denied'\n }\n\n self.assertEqual(resp.status_code, 403)\n self.assertDictEqual(json.loads(resp.content), error_msg)\n\n super_user.is_superuser = True\n super_user.save()\n\n # Note that our super_user isn't associated withn *any* Orgs.\n self.client.user = super_user\n resp = self.client.post(\n _fake_invite_user,\n {'organization_id': self.fake_org.pk},\n user=super_user\n )\n\n self.assertEqual(resp.__class__, HttpResponse)\n\n def test_has_perm_good_case(self):\n \"\"\"Test that we actually allow people through.\"\"\"\n self.client.user = self.fake_owner\n resp = self.client.post(\n _fake_invite_user,\n {'organization_id': self.fake_org.pk},\n user=self.fake_owner\n )\n\n self.assertEqual(resp.__class__, HttpResponse)\n\n # Test boolean functions for permission logic.\n\n def test_requires_parent_org_owner(self):\n \"\"\"Correctly suss out parent org owners.\"\"\"\n self.assertTrue(decorators.requires_parent_org_owner(\n self.owner_org_user\n ))\n self.assertFalse(decorators.requires_parent_org_owner(\n self.member_org_user\n ))\n\n baby_org = Organization.objects.create(name='baby')\n # Add Viewer from the parent org as the owner of the child org.\n baby_ou = OrganizationUser.objects.create(\n user=self.fake_viewer, organization=baby_org\n )\n baby_org.parent_org = self.fake_org\n baby_org.save()\n\n # Even though we're owner for this org, it's not a parent org.\n self.assertFalse(decorators.requires_parent_org_owner(baby_ou))\n\n def test_can_create_sub_org(self):\n \"\"\"Only an owner can create sub orgs.\"\"\"\n self.assertTrue(decorators.can_create_sub_org(self.owner_org_user))\n self.assertFalse(decorators.can_create_sub_org(self.member_org_user))\n self.assertFalse(decorators.can_create_sub_org(self.viewer_org_user))\n\n def test_can_remove_org(self):\n \"\"\"Only an owner can create sub orgs.\"\"\"\n self.assertTrue(decorators.can_remove_org(self.owner_org_user))\n self.assertFalse(decorators.can_remove_org(self.member_org_user))\n self.assertFalse(decorators.can_remove_org(self.viewer_org_user))\n\n def test_can_invite_member(self):\n \"\"\"Only an owner can create sub orgs.\"\"\"\n self.assertTrue(decorators.can_invite_member(self.owner_org_user))\n self.assertFalse(decorators.can_invite_member(self.member_org_user))\n self.assertFalse(decorators.can_invite_member(self.viewer_org_user))\n\n def test_can_remove_member(self):\n \"\"\"Only an owner can create sub orgs.\"\"\"\n self.assertTrue(decorators.can_remove_member(self.owner_org_user))\n self.assertFalse(decorators.can_remove_member(self.member_org_user))\n self.assertFalse(decorators.can_remove_member(self.viewer_org_user))\n\n def test_can_modify_query_thresh(self):\n \"\"\"Only an parent owner can modify query thresholds.\"\"\"\n self.assertTrue(\n decorators.can_modify_query_thresh(self.owner_org_user)\n )\n self.assertFalse(decorators.can_modify_query_thresh(\n self.member_org_user\n ))\n self.assertFalse(decorators.can_modify_query_thresh(\n self.viewer_org_user\n ))\n\n def test_can_view_sub_org_settings(self):\n \"\"\"Only an parent owner can create sub orgs.\"\"\"\n self.assertTrue(\n decorators.can_view_sub_org_settings(self.owner_org_user)\n )\n self.assertFalse(\n decorators.can_view_sub_org_settings(self.member_org_user)\n )\n self.assertFalse(\n decorators.can_view_sub_org_settings(self.viewer_org_user)\n )\n\n def test_can_view_sub_org_fields(self):\n \"\"\"Only an parent owner can create sub orgs.\"\"\"\n self.assertTrue(\n decorators.can_view_sub_org_fields(self.owner_org_user)\n )\n self.assertFalse(\n decorators.can_view_sub_org_fields(self.member_org_user)\n )\n self.assertFalse(\n decorators.can_view_sub_org_fields(self.viewer_org_user)\n )\n\n def test_requires_owner(self):\n \"\"\"Test ownerness.\"\"\"\n self.assertTrue(decorators.requires_owner(self.owner_org_user))\n self.assertFalse(decorators.requires_owner(self.member_org_user))\n self.assertFalse(decorators.requires_owner(self.viewer_org_user))\n\n def test_requires_owner_w_child_org_and_parent_owner(self):\n \"\"\"Parent owners are as child owners.\"\"\"\n baby_org = Organization.objects.create(name='baby')\n baby_org.parent_org = self.fake_org\n baby_org.save()\n\n self.assertTrue(decorators.requires_owner(self.owner_org_user))\n\n def test_requires_member(self):\n \"\"\"Test membership.\"\"\"\n self.assertTrue(decorators.requires_member(self.member_org_user))\n self.assertTrue(decorators.requires_member(self.member_org_user))\n self.assertFalse(decorators.requires_member(self.viewer_org_user))\n\n def test_requires_viewer(self):\n \"\"\"Test viewership.\"\"\"\n self.assertTrue(decorators.requires_viewer(self.owner_org_user))\n self.assertTrue(decorators.requires_viewer(self.member_org_user))\n self.assertTrue(decorators.requires_viewer(self.viewer_org_user))\n\n def test_requires_superuser(self):\n \"\"\"Test superusership.\"\"\"\n self.assertFalse(decorators.requires_superuser(self.owner_org_user))\n self.assertFalse(decorators.requires_superuser(self.member_org_user))\n self.assertFalse(decorators.requires_superuser(self.viewer_org_user))\n self.assertTrue(decorators.requires_superuser(self.superuser_org_user))\n","sub_path":"seed/lib/superperms/tests/test_decorators.py","file_name":"test_decorators.py","file_ext":"py","file_size_in_byte":11478,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"99452949","text":"from django.shortcuts import render\nfrom client.models import Client\nfrom django.forms import ModelForm\n\n\nclass ClientForm(ModelForm):\n class Meta:\n model = Client\n fields = \"__all__\"\n\n# Create your views here.\ndef client(request):\n if request.method == \"POST\":\n form = ClientForm(request.POST)\n form.save()\n # name = request.GET.get(\"client_name\")\n # surname = request.GET.get(\"client_surname\")\n # age = request.GET.get(\"client_age\")\n\n # if name and surname and age:\n # Client.objects.create(name=name,surname=surname,age=age)\n\n \n clients = Client.objects.all()\n return render(request,\"client/client.html\",{\"clients\":clients})\n\ndef client_detail(request,id):\n client = Client.objects.get(id=id)\n return render(request,\"client/detail.html\",{\"client\":client})","sub_path":"mysite/client/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":826,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"472198000","text":"from typing import Dict\nfrom functools import lru_cache\n\n\ndef fib1(num: int) -> int:\n if num < 2:\n return num\n\n return fib1(num - 2) + fib1(num - 1)\n\n\n# cache implementação propria\ncache: Dict[int, int] = {0: 0, 1: 1}\n\ndef fib2(num: int) -> int:\n if num not in cache:\n cache[num] = fib2(num - 1) + fib2(num - 2)\n \n return cache[num]\n\n\n# cache do propria da linguagem\n@lru_cache(maxsize=None)\ndef fib3(num: int) -> int:\n\tif num < 2:\n\t\treturn num\n\n\treturn cache[num]\n\n\ndef fib4(num: int) -> int:\n\tlast_num: int = 0\n\tnext_num: int = 1\n\n\tfor _ in range(1, num):\n\t\tlast_num, next_num = next_num, last_num + next_num\n\n\treturn next_num\n\n\ndef fib5(num: int) -> int:\n\tyield 0\n\tif (num > 0): yield 1\n\n\tlast_num: int = 0\n\tnext_num: int = 1\n\n\tfor _ in range(1, num):\n\t\tlast_num, next_num = next_num, last_num + next_num\n\t\tyield next_num\n\n\nif __name__ == \"__main__\":\n\tfib_num = 12\n\tprint(fib1(fib_num))\n\tprint(fib2(fib_num))\n\tprint(fib3(fib_num))\n\tprint(fib4(fib_num))\n\tprint([n for n in fib5(fib_num)][-1])\n","sub_path":"fibonnaci.py","file_name":"fibonnaci.py","file_ext":"py","file_size_in_byte":1026,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"360575420","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# Copyright 2011, Florent Lamiraux, Thomas Moulard, JRL, CNRS/AIST\n#\n# This file is part of dynamic-graph.\n# dynamic-graph is free software: you can redistribute it and/or\n# modify it under the terms of the GNU Lesser General Public License\n# as published by the Free Software Foundation, either version 3 of\n# the License, or (at your option) any later version.\n#\n# dynamic-graph is distributed in the hope that it will be useful, but\n# WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n# General Lesser Public License for more details. You should have\n# received a copy of the GNU Lesser General Public License along with\n# dynamic-graph. If not, see .\n\nfrom __future__ import print_function\nimport numpy as np\nfrom dynamic_graph import plug\nfrom dynamic_graph.sot.core import FeatureVisualPoint, Task\nfrom dynamic_graph.sot.motion_planner import VispPointProjection\nfrom dynamic_graph.sot.motion_planner.math import *\nfrom dynamic_graph.sot.motion_planner.motion_plan.tools import *\n\nfrom dynamic_graph.sot.motion_planner.motion_plan.motion.abstract import *\n\nclass MotionVisualPoint(Motion):\n yaml_tag = u'visual-point'\n\n type = None\n gain = None\n objectName = None\n\n def __init__(self, motion, yamlData, defaultDirectories):\n checkDict('interval', yamlData)\n\n Motion.__init__(self, motion, yamlData)\n\n self.objectName = yamlData['object-name']\n self.frameName = yamlData['frame-name']\n\n self.gain = yamlData.get('gain', 1.)\n\n # Cannot change the stack dynamically for now.\n if self.interval[0] != 0 and self.interval[1] != motion.duration:\n raise NotImplementedError\n\n # Desired feature\n self.fvpDes = FeatureVisualPoint('fvpDes'+str(id(yamlData)))\n self.fvpDes.xy.value = (0., 0.)\n\n # Feature\n self.vispPointProjection = VispPointProjection('vpp'+str(id(yamlData)))\n self.vispPointProjection.cMo.value = (\n (1., 0., 0., 0.),\n (0., 1., 0., 0.),\n (0., 0., 1., 1.),\n (0., 0., 0., 1.),)\n self.vispPointProjection.cMoTimestamp.value = (0., 0.)\n\n self.fvp = FeatureVisualPoint('fvp'+str(id(yamlData)))\n plug(self.vispPointProjection.xy, self.fvp.xy)\n plug(self.vispPointProjection.Z, self.fvp.Z)\n\n self.fvp.Z.value = 1.\n self.fvp.sdes.value = self.fvpDes\n self.fvp.selec.value = '11'\n plug(motion.robot.frames[self.frameName].jacobian, self.fvp.Jq)\n\n self.fvp.error.recompute(self.fvp.error.time + 1)\n self.fvp.jacobian.recompute(self.fvp.jacobian.time + 1)\n\n # Task\n self.task = Task('task_fvp_'+str(id(yamlData)))\n self.task.add(self.fvp.name)\n self.task.controlGain.value = self.gain\n\n self.task.error.recompute(self.task.error.time + 1)\n self.task.jacobian.recompute(self.task.jacobian.time + 1)\n\n # Push the task into supervisor.\n motion.supervisor.addTask(self.task.name,\n self.interval[0], self.interval[1],\n self.priority,\n #FIXME: HRP-2 specific\n (6 + 14, 6 + 15))\n\n def __str__(self):\n msg = \"visual point motion (frame: {0}, object: {1})\"\n return msg.format(self.frameName, self.objectName)\n\n def setupTrace(self, trace):\n for s in ['xy', 'Z']:\n addTrace(self.robot, trace, self.vispPointProjection.name, s)\n\n for s in ['xy']:\n addTrace(self.robot, trace, self.fvpDes.name, s)\n\n for s in ['xy', 'Z', 'error']:\n addTrace(self.robot, trace, self.fvp.name, s)\n\n for s in ['error']:\n addTrace(self.robot, trace, self.task.name, s)\n","sub_path":"src/dynamic_graph/sot/motion_planner/motion_plan/motion/visual_point.py","file_name":"visual_point.py","file_ext":"py","file_size_in_byte":3903,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"327551336","text":"import keras\nfrom keras.models import load_model\nimport os\nimport numpy as np\nimport parser\n\nclasses = ['DR','FT','LP']\nclassifier = load_model('../models/rec2/rec2_model.h5')\nfrom PIL import ImageFile\nImageFile.LOAD_TRUNCATED_IMAGES = True\nfrom keras.preprocessing import image\nIMAGE_FOLDER = './TC1/ABCD/validation/LP/'\nimages = os.listdir(IMAGE_FOLDER)\ncount=0\nfor filename in images:\n\ttest_image = image.load_img(IMAGE_FOLDER+ filename, target_size = (128, 128))\n\ttest_image = image.img_to_array(test_image)\n\ttest_image = np.expand_dims(test_image, axis = 0)\n\tresult = classifier.predict(test_image)\n\tprint(filename + \" -> \" + classes[np.argmax(result)])\n\tif classes[np.argmax(result)] == 'DR':\n\t\tcount+=1\nprint(\"\\n correct count = \"+ str(count) +\"\\n total count = \"+str(len(images))+\"\\n\")\nprint(\"Percentage:\" + str((count)/len(images)*100)+\"%\")\nprint(\"\\n\")\n","sub_path":"rec2/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":862,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"611665615","text":"import pickle\nimport os\nimport cv2\nimport numpy as np\nimport matplotlib.image as mpimg\n\ncal_dir = \"./camera_cal/\"\ncal_file = \"./calibration_pickle.p\"\n\ndef camera_calibration(board_size=(9, 6)):\n if os.path.isfile(cal_file):\n with open(cal_file, mode='rb') as f:\n dist_pickle = pickle.load(f)\n else:\n cal_images = os.listdir(cal_dir)\n\n objpoints = [] # 3d points in real world space\n imgpoints = [] # 2d points in image plane.\n\n # prepare object points, like (0,0,0), (1,0,0), (2,0,0) ....,(6,5,0)\n objp = np.zeros((6*9, 3), np.float32)\n objp[:, :2] = np.mgrid[0:9, 0:6].T.reshape(-1, 2)\n\n for path in cal_images:\n cal_image = mpimg.imread(cal_dir + path)\n gray = cv2.cvtColor(cal_image, cv2.COLOR_RGB2GRAY)\n ret, corners = cv2.findChessboardCorners(gray, board_size, None)\n if ret == True:\n objpoints.append(objp)\n imgpoints.append(corners)\n\n # Get Camera matrix and distortion coefficients\n ret, mtx, dist, _, _ = cv2.calibrateCamera(objpoints, imgpoints, gray.shape[::-1], None, None)\n\n # Save the result\n dist_pickle = {}\n dist_pickle[\"mtx\"] = mtx\n dist_pickle[\"dist\"] = dist\n pickle.dump(dist_pickle, open(cal_file, \"wb\"))\n print(\"##### Camera Calibration Finished #####\")\n return dist_pickle\n\n\ndef abs_sobel_thresh(image, orient='x', sobel_kernel=3, thresh=(0, 255)):\n gray = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY)\n if orient == 'x':\n abs_sobel = np.absolute(\n cv2.Sobel(gray, cv2.CV_64F, 1, 0, ksize=sobel_kernel))\n elif orient == 'y':\n abs_sobel = np.absolute(\n cv2.Sobel(gray, cv2.CV_64F, 0, 1, ksize=sobel_kernel))\n\n scale_sobel = np.uint8(255 * abs_sobel / np.max(abs_sobel))\n grad_binary = np.zeros_like(scale_sobel)\n grad_binary[(scale_sobel >= thresh[0]) & (scale_sobel <= thresh[1])] = 1\n return grad_binary\n\n\ndef dir_threshold(image, sobel_kernel=3, thresh=(0, np.pi/2)):\n # Calculate gradient direction\n # Apply threshold\n gray = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY)\n absx = np.absolute(cv2.Sobel(gray, cv2.CV_64F, 1, 0, ksize=sobel_kernel))\n absy = np.absolute(cv2.Sobel(gray, cv2.CV_64F, 0, 1, ksize=sobel_kernel))\n grad_dir = np.arctan2(absy, absx)\n\n dir_binary = np.zeros_like(grad_dir)\n dir_binary[(grad_dir >= thresh[0]) & (grad_dir <= thresh[1])] = 1\n return dir_binary\n\n\ndef hls_threshold(image, ch='S', thresh=(0, 255)):\n hls = cv2.cvtColor(image, cv2.COLOR_RGB2HLS)\n if ch == 'H':\n value = hls[:, :, 0]\n elif ch == 'L':\n value = hls[:, :, 1]\n elif ch == 'S':\n value = hls[:, :, 2]\n\n hls_binary = np.zeros_like(value)\n hls_binary[(value > thresh[0]) & (value <= thresh[1])] = 1\n return hls_binary\n\n\n","sub_path":"util_function.py","file_name":"util_function.py","file_ext":"py","file_size_in_byte":2858,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"412557237","text":"# uncompyle6 version 3.7.4\n# Python bytecode 2.7 (62211)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: build/bdist.macosx-10.15-x86_64/egg/batchcompute/core/api.py\n# Compiled at: 2019-11-25 04:45:47\nimport sys, uuid, base64, hmac\nfrom hashlib import sha1 as sha\nfrom batchcompute.utils import RequestClient, str_md5, utf8, iget, gmt_time, import_json, get_region, get_api_version\nfrom batchcompute.utils.constants import API_VERSION, PY2, PY3, API_VERSION\nfrom batchcompute.utils import constants\njson = import_json()\n\nclass Api(object):\n \"\"\"\n A simple api implemention for batch compute, which supply operations for\n users to connect to BatchCompute service.\n \"\"\"\n prefix = 'x-acs-'\n version = API_VERSION\n\n def __init__(self, endpoint, access_id, secret_key, auth_token, security, **headers):\n self.endpoint = endpoint\n self.host = endpoint\n if security:\n self.port = constants.SECURITY_SERVICE_PORT\n else:\n self.port = constants.SERVICE_PORT\n self.id_, self.key = access_id, secret_key\n self.token = auth_token.strip()\n self.accept = 'application/json'\n self.content_type = 'application/json'\n self.sign_method = 'HMAC-SHA1'\n self.sign_version = '1.0'\n self.provider = 'acs'\n self.rc = RequestClient(self.host, self.port)\n self.url_sep = '/'\n self.user_defined_headers = headers\n\n def raw_headers(self, body):\n \"\"\"\n Headers without 'Authorization' key-value pair.\n \"\"\"\n date = gmt_time()\n h = dict()\n h['Date'] = date\n h['x-acs-region-id'] = get_region(self.endpoint)\n h['x-acs-access-key-id'] = self.id_\n if self.token:\n h['x-acs-security-token'] = self.token\n h['x-acs-signature-method'] = self.sign_method\n h['x-acs-signature-version'] = self.sign_version\n h['x-acs-version'] = get_api_version()\n h['x-acs-signature-nonce'] = str(uuid.uuid1())\n h['Accept'] = self.accept\n h['Content-Type'] = self.content_type\n h['User-Agent'] = 'Mozilla/5.0 (Windows NT 6.1)'\n if body:\n h['contentMd5'] = str_md5(body)\n h['Content-Length'] = len(body)\n else:\n h['Content-Length'] = 0\n h.update(self.user_defined_headers)\n return h\n\n def get_auth(self, method, path='', params={}, body='', headers={}):\n \"\"\"\n Provides an implemention to signature user's http request.\n\n Returns the signatured string which will be included in the http\n request headers for BatchCompute to identify users.\n \"\"\"\n\n def normalize(url, h):\n \"\"\"\n To join all key-value pairs whose key starts with `self.prefix`\n in http headers.\n \"\"\"\n _ = lambda s: s.lower().strip()\n assert_prefix = lambda k: _(k).startswith(self.prefix)\n pairs = [ '%s:%s\\n' % (_(k), utf8(h[k])) for k in sorted(h.keys()) if assert_prefix(k)\n ]\n return ('').join(pairs) + url\n\n h = headers\n md5, type_ = iget(h, 'Content-MD5'), iget(h, 'Content-Type')\n date, accept = iget(h, 'Date'), iget(h, 'Accept')\n key = utf8(self.key)\n url = self.rc.get_url(path, params)\n canonicalized_part = normalize(url, h)\n _ = lambda s: s.strip()\n meta_info = [method, _(accept), _(md5), _(type_), date, canonicalized_part]\n plain_text = ('\\n').join(meta_info)\n if PY3:\n key = bytes(key, 'ascii')\n plain_text = bytes(plain_text, 'ascii')\n m = hmac.new(key, plain_text, sha)\n encoded_text = base64.b64encode(m.digest())\n if PY3:\n encoded_text = str(encoded_text, encoding='ascii')\n result = '%s %s:%s' % (self.provider, self.id_, encoded_text)\n return result\n\n def get_headers(self, method, path='', params={}, body=''):\n h = self.raw_headers(body)\n h['Authorization'] = self.get_auth(method, path, params, body, h)\n return h\n\n def attr_join(self, attrs):\n s = ''\n if isinstance(attrs, str):\n s = attrs\n elif isinstance(attrs, (list, tuple)):\n s = ('/').join(attrs)\n return s\n\n def url_join(self, url_list):\n valid_entries = filter(lambda x: x, url_list)\n return self.url_sep + self.url_sep.join(valid_entries)\n\n def get(self, resource, resource_id='', attrs='', params={}):\n entity_list = [resource, resource_id]\n if attrs:\n entity_list.append(self.attr_join(attrs))\n path = self.url_join(entity_list)\n h = self.get_headers('GET', path, params)\n res = self.rc.get(path, params, h)\n return res\n\n def post(self, resource, resource_id='', attrs='', params={}, body=''):\n entity_list = [resource, resource_id]\n if attrs:\n entity_list.append(self.attr_join(attrs))\n path = self.url_join(entity_list)\n if isinstance(body, dict):\n b = json.dumps(body)\n else:\n b = body\n h = self.get_headers('POST', path, params, b)\n res = self.rc.post(path, params, h, body=b)\n return res\n\n def put(self, resource, resource_id, attrs='', params={}, body=''):\n entity_list = [resource, resource_id]\n if attrs:\n entity_list.append(self.attr_join(attrs))\n path = self.url_join(entity_list)\n if isinstance(body, dict):\n b = json.dumps(body)\n else:\n b = body\n h = self.get_headers('PUT', path, params, b)\n res = self.rc.put(path, params, h, b)\n return res\n\n def patch(self, resource, resource_id, attrs='', params={}, body=''):\n entity_list = [resource, resource_id]\n if attrs:\n entity_list.append(self.attr_join(attrs))\n path = self.url_join(entity_list)\n if isinstance(body, dict):\n b = json.dumps(body)\n else:\n b = body\n h = self.get_headers('PATCH', path, params, b)\n res = self.rc.patch(path, params, h, b)\n return res\n\n def delete(self, resource, resource_id, attrs='', params={}):\n entity_list = [resource, resource_id]\n if attrs:\n entity_list.append(self.attr_join(attrs))\n path = self.url_join(entity_list)\n h = self.get_headers('DELETE', path, params=params)\n res = self.rc.delete(path, params, h)\n return res","sub_path":"pycfiles/batchcompute-2.1.5-py2.7/api.py","file_name":"api.py","file_ext":"py","file_size_in_byte":6562,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"648013230","text":"import argparse\nimport os\nimport pandas as pd\n\ndef aggregate_spend(filepath, metacategory):\n\n meta_cat_col = \"meta_category\"\n cat_col = \"category\"\n amount_col = \"Amount\"\n spend_df = pd.read_csv(filepath)\n \n spend_df = spend_df[spend_df[meta_cat_col] == metacategory]\n \n print(spend_df.groupby([cat_col])[amount_col].sum().reset_index())\n\nif __name__ == \"__main__\":\n \n parser = argparse.ArgumentParser(description=\"Aggregates category spend\")\n parser.add_argument(\"filename\", \n help=\"name of input file\")\n parser.add_argument(\"-r\", \"--rootpath\",\n default=os.path.join(os.getcwd().replace(\"/src/visualization\", \"\"), \"data\", \"monthly\"),\n help=\"filepath location where filename resides. Defaults to /data/monthly\"\n )\n parser.add_argument(\"-m\", \"--metacategory\",\n help=\"meta_category to filter\",\n default=\"Discretionary\"\n )\n \n args = parser.parse_args()\n \n csv_path = os.path.join(args.rootpath, args.filename)\n aggregate_spend(csv_path, args.metacategory)","sub_path":"src/visualization/aggregate_discretionary_spend.py","file_name":"aggregate_discretionary_spend.py","file_ext":"py","file_size_in_byte":1046,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"484248445","text":"from typing import List\nfrom app.core.database import db\nfrom app.models.sites_model import Sites\nfrom datetime import datetime\nfrom pymongo.collection import ReturnDocument\n\n\ndef create(item: Sites):\n item.date_insert = datetime.utcnow()\n item.disabled = False\n if hasattr(item, \"date_update\"):\n delattr(item, \"date_update\")\n if hasattr(item, \"id\"):\n delattr(item, \"id\")\n if hasattr(item, \"username_update\"):\n delattr(item, \"username_update\")\n ret = db.sites.insert_one(item.dict(by_alias=True))\n return ret\n\n\ndef update(item: Sites):\n if hasattr(item, \"date_insert\"):\n delattr(item, \"date_insert\")\n if hasattr(item, \"username_insert\"):\n delattr(item, \"username_insert\")\n if hasattr(item, \"disabled\"):\n delattr(item, \"disabled\")\n item.date_update = datetime.utcnow()\n ret = db.sites.find_one_and_update(\n {\"_id\": item.id, \"disabled\": False},\n {\"$set\": item.dict(by_alias=True)},\n return_document=ReturnDocument.AFTER,\n )\n return ret\n\n\ndef delete(item: Sites):\n item.date_update = datetime.utcnow()\n ret = db.sites.find_one_and_update(\n {\"_id\": item.id, \"disabled\": False},\n {\n \"$set\": {\n \"disabled\": True,\n \"date_update\": item.date_update,\n \"username_update\": item.username_update,\n }\n },\n return_document=ReturnDocument.AFTER,\n )\n return ret\n\n\ndef getByID(item: Sites):\n finded = db.sites.find_one({\"_id\": item.id, \"disabled\": False})\n if finded is not None:\n return Sites(**finded)\n else:\n return None\n\n\ndef get():\n finded = db.sites.find({\"disabled\": False})\n items = []\n for find in finded:\n items.append(Sites(**find))\n return items\n\ndef getByName(item: Sites) -> List[Sites]:\n finded = db.sites.find({\"name\": item.name, \"disabled\": False})\n items = []\n for find in finded:\n items.append(Sites(**find))\n return items\n\ndef getByNameAndNotID(item: Sites):\n finded = db.sites.find({\"name\": item.name, \"disabled\": False, \"_id\" : {\"$not\": {\"$eq\": item.id}}})\n items = []\n for find in finded:\n items.append(Sites(**find))\n return items\n\n\ndef search(item: Sites):\n if item.type == \"\":\n finded = db.sites.find(\n {\n \"$and\": [\n {\"disabled\": False},\n {\n \"$or\": [\n {\"name\": {\"$regex\": item.name, \"$options\": \"i\"}},\n ]\n },\n ]\n }\n )\n else:\n finded = db.sites.find(\n {\n \"$and\": [\n {\"disabled\": False},\n {\"type\": item.type},\n {\n \"$or\": [\n {\"name\": {\"$regex\": item.name, \"$options\": \"i\"}},\n ]\n },\n ]\n }\n )\n items = []\n for find in finded:\n items.append(Sites(**find))\n return items\n","sub_path":"app/services/sites_service.py","file_name":"sites_service.py","file_ext":"py","file_size_in_byte":3004,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"572631309","text":"import pygame\nfrom math import sin, cos, pi\nimport random\nfrom time import sleep\nfrom pathlib import Path\n\npygame.init()\ngame = pygame.display.set_mode((1000, 562))\npygame.display.set_caption(\"羽球高高手\")\nclock = pygame.time.Clock()\n\nIMG_PATH = Path(__file__).resolve().parent / '圖檔'\nMUSIC_PATH = Path(__file__).resolve().parent / '音效'\n\n# ball obj\nx_ball = 500\ny_ball = 100\nr_ball = 10\nv_ball = 3\nrad = pi / 180\nang = random.choice([180, 0])\nangle = -ang * rad\nvx_ball = cos(angle) * v_ball\nvy_ball = sin(angle) * v_ball\ngrav = 0.09\n\n\ndef serve(scorer):\n global x_ball, y_ball, vx_ball, vy_ball, angle\n sleep(0.5)\n x_ball = 500\n y_ball = 100\n angle = -0 * rad if scorer == 1 else -180 * rad\n vx_ball = cos(angle) * v_ball\n vy_ball = sin(angle) * v_ball\n\n\ndef get_ball(img_name):\n # pygame.draw.circle(game, (0, 255, 0), (int(float(x_ball)), int(float(y_ball))), r_ball, 0)\n path = IMG_PATH / img_name\n ball = pygame.image.load(str(path))\n ball = pygame.transform.scale(ball, (40, 40))\n game.blit(ball, (int(float(x_ball)), int(float(y_ball))))\n\n\n# p1 obj\nx_p1 = 150\ny_p1 = 412\nw_p1 = 50\nh_p1 = 150\nv_p1 = 5\n\n\ndef get_p(img_name, x, y, w, h):\n path = IMG_PATH / img_name\n p1 = pygame.image.load(str(path))\n p1 = pygame.transform.scale(p1, (80, 120))\n game.blit(p1, ((x, y), (w, h)))\n\n\n# p2 obj\nx_p2 = 800\ny_p2 = 412\nw_p2 = 50\nh_p2 = 150\nv_p2 = 5\n\n# net obj # 原始數值(495, 362, 10, 200),改過的數值調成與背景網子的範圍相同\nx_net = 495\ny_net = 315\nw_net = 43\nh_net = 400\n\n\ndef get_net():\n game1 = game.convert_alpha() # 把中間包括背景網子的黑色長方形調為透明\n pygame.draw.rect(game1, (0, 0, 0, 0), ((x_net, y_net), (w_net, h_net)))\n\n\ndef text_score():\n pygame.font.init()\n font = pygame.font.Font(\"ARCADECLASSIC.TTF\", 80)\n return font\n\ndef text_name():\n pygame.font.init()\n font1 = pygame.font.Font(\"ARCADECLASSIC.TTF\", 30)\n return font1\n\ndef text_cele():\n font = pygame.font.Font(\"ARCADECLASSIC.TTF\", 50)\n return font\n\ndef text_button():\n font = pygame.font.Font(\"ARCADECLASSIC.TTF\", 50)\n return font\n\n# p1圖片左右移動轉換\ndef move(cnt, img1, img2, img3):\n if (cnt // 6) % 3 == 0:\n get_p(img1, x_p1, y_p1, w_p1, h_p1)\n cnt += 1\n elif (cnt // 6) % 3 == 1:\n get_p(img2, x_p1, y_p1, w_p1, h_p1)\n cnt += 1\n else:\n get_p(img3, x_p1, y_p1, w_p1, h_p1)\n cnt += 1\n return cnt\n\n\ndef jump(img1):\n get_p(img1, x_p1, y_p1, w_p1, h_p1)\n\ndef restart():\n while True: # 遊戲進入畫面操作\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n pygame.quit()\n\n game.blit(enter_picture, (0, 5))\n game.blit(text_score().render(str(0), False, (255, 215, 0)), (390, 60))\n game.blit(text_score().render(str(0), False, (255, 215, 0)), (550, 60))\n game.blit(welcome, (265, 150))\n game.blit(button_start, (450, 265))\n game.blit(button_quit, (462, 346)) \n buttons = pygame.mouse.get_pressed()\n x1, y1 = pygame.mouse.get_pos()\n if x1 >= 400 and x1 <= 628 and y1 >= 262 and y1 <= 318:\n if buttons[0]:\n # playing = True\n break\n elif x1 >=400 and x1 <= 628 and y1 >= 343 and y1 <= 399:\n if buttons[0]:\n pygame.quit()\n\n# 解除殘影\ndef return_background():\n game.blit(picture, (0, 0))\n game.blit(p1_score_text, (390, 60))\n game.blit(p2_score_text, (550, 60))\n game.blit(p1_name, (20, 0))\n game.blit(p2_name, (860, 0))\n if p1_win and not p2_win:\n game.blit(p1_win_text, (200, 300))\n elif p2_win and not p1_win:\n game.blit(p2_win_text, (700, 300))\n\np1_name = text_name().render('P LAYER 1', False, (255, 215, 0))\np2_name = text_name().render('P LAYER 2', False, (255, 215, 0))\n\nwelcome = text_score().render('ARE YOU READY', False, (255, 215, 0))\nbutton_start = text_button().render('START', False, (255, 215, 0))\nbutton_quit = text_button().render('QUIT', False, (255, 215, 0))\n\np1_score = 0\np2_score = 0\n\nenter_picture = pygame.image.load(str(IMG_PATH) + str('/') + '進入畫面.png')\nenter_picture = pygame.transform.scale(enter_picture, (1000, 562))\n\npicture = pygame.image.load(str(IMG_PATH) + str('/') + '羽球背景.jpg')\npicture = pygame.transform.scale(picture, (1000, 562))\nrect = picture.get_rect()\nrect = rect.move((0, 0))\n\n# 背景音\nmusic_path = MUSIC_PATH / \"背景音-選項3.mp3\"\npygame.mixer.music.load(str(music_path))\npygame.mixer.music.set_volume(0.2)\npygame.mixer.music.play(loops = 0, start = 0.0)\n\n# 擊球音效\nhit_ball_voice = pygame.mixer.Sound(str(MUSIC_PATH) + str('/') + '打擊聲-1.mp3')\nhit_ball_voice.set_volume(0.25)\n\n# 殺球音效\nkill_ball_voice = pygame.mixer.Sound(str(MUSIC_PATH) + str('/') + '打擊聲-2.mp3')\nkill_ball_voice.set_volume(0.25)\n\np1_win_text = text_cele().render('P LAYER 1 WINS!', False, (255, 215, 0))\np2_win_text = text_cele().render('P LAYER 2 WINS!', False, (255, 215, 0))\n\nisJump_p1 = False # 跳的判斷\njumpCount_p1 = 10\nisJump_p2 = False\njumpCount_p2 = 10\n\nIDEN = 20 # 擊球判定\n\nisHit_p1 = False\nisHit_p2 = False\n\ncnt = 0\n\nstart = True\nwhile start: # 遊戲進入畫面操作\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n pygame.quit()\n\n game.blit(enter_picture, (0, 5))\n game.blit(text_score().render(str(0), False, (255, 215, 0)), (390, 60))\n game.blit(text_score().render(str(0), False, (255, 215, 0)), (550, 60))\n game.blit(welcome, (265, 150))\n game.blit(button_start, (450, 265))\n game.blit(button_quit, (462, 346))\n \n buttons = pygame.mouse.get_pressed()\n x1, y1 = pygame.mouse.get_pos()\n if x1 >= 400 and x1 <= 628 and y1 >= 262 and y1 <= 318:\n if buttons[0]:\n start = False\n elif x1 >=400 and x1 <= 628 and y1 >= 343 and y1 <= 399:\n if buttons[0]:\n pygame.quit()\n pygame.display.update()\n# restart = False\nplaying = True \nwhile playing:\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n pygame.quit()\n\n game.blit(picture, rect)\n\n # text\n p1_score_text = text_score().render(str(p1_score), False, (255, 215, 0))\n p2_score_text = text_score().render(str(p2_score), False, (255, 215, 0))\n\n game.blit(p1_score_text, (390, 60))\n game.blit(p2_score_text, (550, 60))\n game.blit(p1_name, (20, 0))\n game.blit(p2_name, (860, 0))\n\n # 慶祝訊息\n\n \n keys = pygame.key.get_pressed()\n if keys[pygame.K_ESCAPE]:\n pygame.quit()\n\n # p1擊球判定\n if not isHit_p1:\n if not isJump_p1:\n if x_p1 - IDEN < x_ball < x_p1 + w_p1 + IDEN and y_ball > y_p1 - IDEN:\n if keys[pygame.K_z] and 0 <= x_p1 <= 250:\n vx_ball = cos(-10 * random.uniform(6.5, 8.0) * rad) * 9\n vy_ball = sin(-10 * random.uniform(6.5, 8.0) * rad) * 10\n pygame.mixer.Sound.play(hit_ball_voice)\n isHit_p1 = True\n elif keys[pygame.K_z] and 250 < x_p1 <= 500:\n vx_ball = cos(-10 * random.uniform(6.5, 8.0) * rad) * 7\n vy_ball = sin(-10 * random.uniform(6.5, 8.0) * rad) * 8\n pygame.mixer.Sound.play(hit_ball_voice)\n isHit_p1 = True\n elif keys[pygame.K_x] and 0 <= x_p1 <= 250:\n vx_ball = cos(-10 * random.uniform(4.0, 4.5) * rad) * 7.0\n vy_ball = sin(-10 * random.uniform(4.0, 4.5) * rad) * 7.5\n pygame.mixer.Sound.play(hit_ball_voice)\n isHit_p1 = True\n elif keys[pygame.K_x] and 250 < x_p1 <= 375:\n vx_ball = cos(-10 * random.uniform(4.0, 4.5) * rad) * 6.5\n vy_ball = sin(-10 * random.uniform(4.0, 4.5) * rad) * 5.5\n pygame.mixer.Sound.play(hit_ball_voice)\n isHit_p1 = True\n elif keys[pygame.K_x] and 375 < x_p1 <= 500:\n vx_ball = cos(-10 * random.uniform(6.5, 7.5) * rad) * 5.5\n vy_ball = sin(-10 * random.uniform(6.5, 7.5) * rad) * 5.5\n pygame.mixer.Sound.play(hit_ball_voice)\n isHit_p1 = True\n else:\n if x_p1 - IDEN < x_ball < x_p1 + w_p1 + IDEN and y_ball < 400:\n if keys[pygame.K_c]:\n vx_ball = cos(10 * random.uniform(3.5, 5.0) * rad) * 35\n vy_ball = sin(10 * random.uniform(3.5, 5.0) * rad) * 25\n pygame.mixer.Sound.play(kill_ball_voice)\n isHit_p1 = True\n else:\n if x_ball >= 500 or y_ball >= 562 or (x_net < x_ball < x_net + w_net and y_net < y_ball <= y_net + h_net):\n isHit_p1 = False\n\n # p2擊球判定\n if not isHit_p2:\n if not isJump_p2:\n if x_p2 - IDEN < x_ball < x_p2 + w_p2 + IDEN and y_ball > y_p2 - IDEN:\n if keys[pygame.K_l] and 500 <= x_p2 <= 625:\n vx_ball = cos(-10 * random.uniform(10.5, 11.5) * rad) * 5.5\n vy_ball = sin(-10 * random.uniform(10.5, 11.5) * rad) * 5.5\n pygame.mixer.Sound.play(hit_ball_voice)\n isHit_p2 = True\n elif keys[pygame.K_l] and 625 < x_p2 <= 750:\n vx_ball = cos(-10 * random.uniform(11.5, 12.0) * rad) * 6.5\n vy_ball = sin(-10 * random.uniform(11.5, 12.0) * rad) * 5.5\n pygame.mixer.Sound.play(hit_ball_voice)\n isHit_p2 = True\n elif keys[pygame.K_l] and 750 < x_p2 <= 1000:\n vx_ball = cos(-10 * random.uniform(13.0, 13.5) * rad) * 7.0\n vy_ball = sin(-10 * random.uniform(13.0, 13.5) * rad) * 7.5\n pygame.mixer.Sound.play(hit_ball_voice)\n isHit_p2 = True\n elif keys[pygame.K_k] and 500 <= x_p2 <= 750:\n vx_ball = cos(-10 * random.uniform(10.0, 11.5) * rad) * 7 # 11.5 13.5\n vy_ball = sin(-10 * random.uniform(10.0, 11.5) * rad) * 8\n pygame.mixer.Sound.play(hit_ball_voice)\n isHit_p2 = True\n elif keys[pygame.K_k] and 750 < x_p2 <= 1000:\n vx_ball = cos(-10 * random.uniform(10.0, 11.5) * rad) * 9\n vy_ball = sin(-10 * random.uniform(10.0, 11.5) * rad) * 10\n pygame.mixer.Sound.play(hit_ball_voice)\n isHit_p2 = True\n else:\n if x_p2 - IDEN < x_ball < x_p2 + w_p2 + IDEN and y_ball < 400:\n if keys[pygame.K_SEMICOLON]:\n vx_ball = cos(-10 * random.uniform(21.5, 23.0) * rad) * 35\n vy_ball = sin(-10 * random.uniform(21.5, 23.0) * rad) * 25\n pygame.mixer.Sound.play(kill_ball_voice)\n isHit_p2 = True\n else:\n if x_ball <= 500 or y_ball >= 562 or (x_net < x_ball < x_net + w_net and y_net < y_ball <= y_net + h_net):\n isHit_p2 = False\n\n # 觸網\n if x_net < x_ball < x_net + w_net and y_net < y_ball <= y_net + h_net:\n if vx_ball > 0:\n p2_score += 1\n serve(2) # 2\n else:\n p1_score += 1\n serve(1)\n\n # 落地和出界\n if y_ball > 562 or x_ball > 1000 or x_ball < 0:\n if (0 < x_ball < x_net and y_ball > 562) or (x_ball > 1000):\n p2_score += 1\n serve(2) # 2\n elif (x_net + w_net < x_ball < 1000 and y_ball > 562) or (x_ball < 0):\n p1_score += 1\n serve(1)\n\n # p1 movement\n get_p(\"blue_4.png\", x_p1, y_p1, w_p1, h_p1)\n if keys[pygame.K_a]:\n return_background()\n x_p1 -= v_p1\n cnt = move(cnt, \"blue_4.png\", \"blue_run_01.png\", \"blue_run_02.png\")\n if x_p1 <= 0:\n x_p1 = 0\n elif keys[pygame.K_d]:\n return_background()\n x_p1 += v_p1\n cnt = move(cnt, \"blue_4.png\", \"blue_run_01.png\", \"blue_run_02.png\")\n if x_p1 + w_p1 >= 495:\n x_p1 = 495 - w_p1\n\n if not isJump_p1:\n if keys[pygame.K_w]:\n return_background()\n jump('blue_5.png')\n isJump_p1 = True\n else:\n return_background()\n jump('blue_5.png')\n if jumpCount_p1 >= -10:\n neg_p1 = 1\n if jumpCount_p1 < 0:\n neg_p1 = -1\n y_p1 -= (jumpCount_p1 ** 2) * neg_p1 * 0.4\n jumpCount_p1 -= 0.5\n else:\n isJump_p1 = False\n jumpCount_p1 = 10\n\n # p2 movement\n get_p(\"red_2.png\", x_p2, y_p2, w_p2, h_p2)\n if keys[pygame.K_LEFT]:\n x_p2 -= v_p2\n if x_p2 <= 495 + w_net:\n x_p2 = 495 + w_net\n elif keys[pygame.K_RIGHT]:\n x_p2 += v_p2\n if x_p2 + w_p2 >= 1000:\n x_p2 = 1000 - w_p2\n\n if not isJump_p2:\n if keys[pygame.K_UP]:\n isJump_p2 = True\n else:\n if jumpCount_p2 >= -10:\n neg_p2 = 1\n if jumpCount_p2 < 0:\n neg_p2 = -1\n y_p2 -= (jumpCount_p2 ** 2) * neg_p2 * 0.4 # 用參數調整起跳與落地速度\n jumpCount_p2 -= 0.5\n else:\n isJump_p2 = False\n jumpCount_p2 = 10\n\n # net\n get_net()\n\n # ball\n if vx_ball > 0:\n get_ball('去背羽球.png')\n else:\n get_ball('去背羽球_球頭向左.png')\n vy_ball += grav\n x_ball += vx_ball\n y_ball += vy_ball\n \n p1_win = False\n p2_win = False\n if p1_score == 1:\n p1_win = True\n restart()\n game.blit(p1_win_text, (100, 300))\n p1_score = 0\n p2_score = 0\n elif p2_score == 1:\n p2_win = True\n restart()\n game.blit(p2_win_text, (600, 300))\n p1_score = 0\n p2_score = 0\n \n pygame.display.flip()\n clock.tick(200)\n\n# 二碰 ok\n# 球的角度和速度需調整 ok\n# 殺球(角度、速度、gravity要調整) ok\n# 開始介面 ok\n# 網子高度要調整(背景圖) ok\n# 球要有兩個方向(球頭朝對面) ok\n# 場地線調整\n# 重新開始按鈕(Optional:暫停鍵)\n# 音效\n# P2的人物動作合併\n","sub_path":"不能重新開始 wwww.py","file_name":"不能重新開始 wwww.py","file_ext":"py","file_size_in_byte":14234,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"265541272","text":"import unittest\nfrom django.forms import ChoiceField\nfrom mock import Mock, patch, PropertyMock\nfrom mangrove.datastore.database import DatabaseManager\nfrom mangrove.form_model.field import TextField\nfrom datawinners.project.models import Project\nfrom datawinners.project.questionnaire_fields import EntityField, FormField\n\nclass TestSubjectField(unittest.TestCase):\n def test_create_entity_list_for_reporters(self):\n with patch (\"datawinners.project.questionnaire_fields.EntityField._data_sender_choice_fields\") as ds_choice_fields:\n\n choices = ChoiceField(choices=[('rep1', 'ashwin'), ('rep2', 'pooja')])\n ds_choice_fields.return_value = choices\n project = Project(entity_type=\"reporter\")\n subject_field = EntityField(Mock(spec = DatabaseManager), project)\n question_field = Mock(spec=TextField)\n question_code = PropertyMock(return_value=\"eid\")\n type(question_field).code = question_code\n\n result_field = subject_field.create(question_field, 'reporter')\n\n self.assertEquals(result_field.get('eid'),choices)\n\n def test_create_entity_list_for_subjects(self):\n with patch (\"datawinners.project.questionnaire_fields.EntityField._subject_choice_fields\") as subject_choice_fields:\n\n choices = ChoiceField(choices=[('sub1', 'one_subject'), ('sub2', 'another_subject')])\n subject_choice_fields.return_value = choices\n project = Project(entity_type=\"some_subject\")\n\n subject_field = EntityField(Mock(spec = DatabaseManager), project)\n question_field = Mock(spec=TextField)\n question_code = PropertyMock(return_value=\"eid\")\n type(question_field).code = question_code\n\n result_field = subject_field.create(question_field, 'some_subject')\n\n self.assertEquals(result_field.get('eid'),choices)\n","sub_path":"datawinners/project/tests/test_subject_field.py","file_name":"test_subject_field.py","file_ext":"py","file_size_in_byte":1901,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"64986015","text":"# This module isn't very pythonic, but I was hoping to decrease the time/memory\n# footprint by avoiding copying strings around more than necessary.\n\n\nclass Doodad:\n def __init__(self, **kwargs):\n self.__dict__.update(kwargs)\n\n\nclass Token:\n def __init__(self, lexer_state, type, **attrs):\n self.loc = lexer_state._token_loc\n self.type = type\n self.__dict__.update(attrs)\n\n\nclass Lexer:\n # Token types\n LITERAL = 1\n REPLACEMENT = 2\n DIRECTIVE = 3\n NESTED_MOLD = 4\n\n def __init__(self, text, *, filename='', line=1):\n self.filename = filename\n self._text = text\n self._length = len(text)\n self._offset = 0\n self._line = line\n self._left_of_line = True\n self._inject_end_at_newline = False\n self._inject_end_now = False\n self._eat_next_whitespace = False\n\n def _get_char(self):\n if self._offset >= self._length:\n raise StopIteration\n\n ret = self._text[self._offset]\n self._offset += 1\n if ret == '\\n':\n self._line += 1\n self._left_of_line = True\n elif ret != '\\t' and ret != '\\n' and ret != ' ':\n self._left_of_line = False\n return ret\n\n def _peek_char(self, distance=0):\n off = self._offset + distance\n return self._text[off] if off < self._length else '\\0'\n\n def _force_eof(self):\n self._offset = self._length\n\n def _make_loc(self):\n return Doodad(filename=self.filename, offset=self._offset, line=self._line)\n\n def _syntax_error(self, message):\n raise SyntaxError(message,\n (self._token_loc.filename, self._token_loc.line, 0, ''))\n\n\n def __iter__(self):\n return self\n\n def __next__(self):\n self._token_loc = self._make_loc()\n ch = self._peek_char(0)\n\n if ch == '$':\n ch = self._peek_char(1)\n if ch == '!':\n ch2 = self._peek_char(2)\n if ch2 >= 'a' and ch2 <= 'z' or ch2 >= 'A' and ch2 <= 'Z' or ch2 in {\"'\", '\"'}:\n self._get_char()\n return self._collect_heuristically(self.REPLACEMENT, False, unescaped=True)\n if ch2 == '{':\n self._get_char()\n return self._collect_bounded(self.REPLACEMENT, unescaped=True)\n if ch >= 'a' and ch <= 'z' or ch >= 'A' and ch <= 'Z' or ch in {\"'\", '\"'}:\n return self._collect_heuristically(self.REPLACEMENT, False)\n if ch == '{':\n return self._collect_bounded(self.REPLACEMENT)\n if ch == '$':\n if self._peek_char(2) == '{':\n return self._collect_bounded(self.NESTED_MOLD)\n self._get_char()\n return Token(self, self.LITERAL, data=self._get_char())\n if ch == '\\n':\n self._get_char()\n self._get_char()\n if self._inject_end_at_newline:\n self._inject_end_at_newline = False\n self._inject_end_now = True\n self._eat_next_whitespace = True\n elif ch == '!':\n ch = self._peek_char(1)\n if ch >= 'a' and ch <= 'z' and self._left_of_line:\n return self._collect_heuristically(self.DIRECTIVE, True)\n if ch == '{':\n return self._collect_bounded(self.DIRECTIVE)\n if ch == '#': # Comment\n self._skip_line_comment()\n return next(self)\n\n if self._inject_end_now:\n self._inject_end_now = False\n return Token(self, self.DIRECTIVE, data='end')\n\n if self._eat_next_whitespace:\n self._eat_next_whitespace = False\n while True:\n ch = self._peek_char()\n if ch == '\\n':\n self._get_char()\n if self._inject_end_at_newline:\n self._inject_end_at_newline = False\n return Token(self, self.DIRECTIVE, data='end')\n elif ch in {' ', '\\t'}:\n self._get_char()\n else:\n break\n return next(self)\n\n return self._collect_literal()\n\n\n def _collect_literal(self):\n token_start = self._offset\n while True:\n ch = self._peek_char()\n if ch == '$' or ch == '!' or ch == '\\0':\n break\n if ch == '\\n' and self._inject_end_at_newline:\n self._inject_end_at_newline = False\n self._inject_end_now = True\n break\n self._get_char()\n\n if token_start == self._offset:\n self._get_char() # Guarantee at least one char is collected\n ret = self._text[token_start : self._offset]\n return Token(self, self.LITERAL, data=ret)\n\n def _collect_heuristically(self, token_type, stop_on_newline_only, *, unescaped=False):\n self._get_char()\n token_start = self._offset\n nest_paren = nest_square = nest_brace = 0\n\n while True:\n ch = self._peek_char()\n if ch >= 'a' and ch <= 'z' or ch >= 'A' and ch <= 'Z' or ch == '_':\n self._get_char()\n continue\n elif ch == '.':\n ch = self._peek_char(1)\n if ch >= 'a' and ch <= 'z' or ch >= 'A' and ch <= 'Z' or ch == '_':\n self._get_char()\n self._get_char()\n continue\n elif ch == \"'\" or ch == '\"':\n if stop_on_newline_only or nest_paren or nest_square or nest_brace or token_start == self._offset:\n self._skip_string_literal()\n continue\n elif ch == '(': self._get_char(); nest_paren += 1; continue\n elif ch == '[': self._get_char(); nest_square += 1; continue\n elif ch == '{': self._get_char(); nest_brace += 1; continue\n elif ch == ')' and nest_paren > 0: self._get_char(); nest_paren -= 1; continue\n elif ch == ']' and nest_square > 0: self._get_char(); nest_square -= 1; continue\n elif ch == '}' and nest_brace > 0: self._get_char(); nest_brace -= 1; continue\n elif ch == ':' and stop_on_newline_only and not (nest_paren or nest_square or nest_brace):\n break\n elif ch == '\\\\' and stop_on_newline_only and self._peek_char(1) == '\\n':\n self._get_char()\n self._get_char()\n continue\n elif ch == '\\0':\n if nest_paren or nest_square or nest_brace:\n self._syntax_error('Unexpected end of file in replacement')\n break\n elif ch == '#' and stop_on_newline_only: # ALlow comments after line directives\n break # The comment is skipped further down in this function\n\n if not stop_on_newline_only or ch == '\\n':\n if nest_paren == 0 and nest_square == 0 and nest_brace == 0:\n break\n\n self._get_char() # Consume the previously peeked char\n\n end_offset = self._offset\n\n if stop_on_newline_only:\n if ch == '#':\n while self._get_char() != '\\n':\n pass\n elif ch == '\\n':\n self._get_char()\n elif ch == ':':\n self._get_char()\n self._eat_next_whitespace = True\n self._left_of_line = True # Allows a !directive to follow a colon\n self._inject_end_at_newline = True\n\n data = self._text[token_start : end_offset]\n return Token(self, token_type, data=data, one_liner=ch == ':', unescaped=unescaped)\n\n def _collect_bounded(self, token_type, *, unescaped=False):\n while self._get_char() != '{':\n pass\n token_start = self._offset\n levels = 1\n\n while True:\n ch = self._peek_char()\n if ch == '\\0':\n self._syntax_error('Unexpected end of file in replacement')\n elif ch == \"'\" or ch == '\"':\n self._skip_string_literal()\n elif ch == '{':\n self._get_char()\n levels += 1\n elif ch == '}':\n self._get_char()\n levels -= 1\n if not levels:\n break\n else:\n self._get_char()\n\n data = self._text[token_start : self._offset - 1]\n return Token(self, token_type, data=data, unescaped=unescaped)\n\n\n def _skip_line_comment(self):\n while True:\n ch = self._get_char()\n if ch == '\\n':\n break\n\n def _skip_string_literal(self):\n delimiter = self._get_char()\n if self._peek_char(0) == delimiter:\n self._get_char()\n if self._peek_char(0) == delimiter:\n return self._skip_triple_string_literal()\n return\n\n while True:\n ch = self._peek_char()\n if ch == '\\0':\n self._syntax_error('Unexpected end of file in string literal')\n self._get_char()\n if ch == delimiter:\n break\n\n def _skip_triple_string_literal(self):\n delimiter = self._get_char()\n while True:\n ch = self._get_char()\n if ch == delimiter:\n ch = self._get_char()\n if ch == delimiter:\n if self._get_char() == delimiter:\n return\n","sub_path":"lexer.py","file_name":"lexer.py","file_ext":"py","file_size_in_byte":9597,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"517868770","text":"class Tree(object):\n def __init__(self):\n self.left = None\n self.child = []\n self.data = []\n\n def createChildren(self, amount):\n for i in range(0, amount):\n self.child.append(Tree())\n\n def setChildrenValues(self, list):\n for i in range(0, len(list)):\n self.data.append(list[i])\n\n\nroot = Tree()\nroot.createChildren(1)\nroot.setChildrenValues([[\"King Shan\",\"Queen Anga\"]])\nprint(root.child[0].data[0])\nroot.createChildren(4)\nroot.setChildrenValues([[\"Ish\"], [\"Chit\", \"Ambi\"], [\"Vich\", \"Lika\"], [\"Satya\", \"Vyan\"]])\nroot.child[1].createChildren(2)\nroot.child[1].setChildrenValues([[\"Crita\", \"Jaya\"], [\"Vrita\"]])\nroot.child[2].createChildren(2)\nroot.child[2].setChildrenValues([[\"Vila\", \"Jnki\"], [\"Chika\", \"Kpila\"]])\nroot.child[3].createChildren(3)\nroot.child[3].setChildrenValues([[\"Satvya\", \"Asva\"], [\"Savya\", \"Krpi\"], [\"Saayan\", \"Mina\"]])\nroot.child[1].child[0].createChildren(2)\nroot.child[1].child[0].setChildernValue([[\"Jata\"], [\"Driya\", \"Mnu\"]])\nroot.child[2].child[0].createChildren(1)\nroot.child[2].child[0].setChildernValue([[\"Lavnya\", \"Gru\"]])\nroot.child[3].child[1].createChildren(1)\nroot.child[3].child[1].setChildernValue([[\"Kriya\"]])\nroot.child[3].child[2].createChildren(1)\nroot.child[3].child[2].setChildernValue([[\"Misa\"]])\n","sub_path":"Geektrust Problems/family_table/familytree.py","file_name":"familytree.py","file_ext":"py","file_size_in_byte":1302,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"609390334","text":"# !/usr/bin/env python3\n\"\"\"\nword_embeddings.py\n\nThis script:\n- saves the body of every article into a file\n- performs preprocessing and tokenization\n- Trains word embeddings\n\"\"\"\n\nfrom main import *\nfrom gensim.models import Word2Vec\nfrom nltk.corpus import stopwords\nfrom collections import Counter\nimport nltk\nimport re\nimport os\nimport string\nimport json\n\ndef body_text(cop_selection=None, surpress_print=True):\n\t\"\"\"\n\tThis module takes the textbody from every article in the dataset and preprocesses it.\n\t\"\"\"\n\n\tf1 = open(\"embeddings/articlebodies.txt\", \"w+\")\n\tcop_data = read_data(cop_selection, surpress_print)\n\tarticles = []\n\n\t# We create a stopwords dictionary to remove the stopwords from the articletext later on\n\tstop_words = nltk.corpus.stopwords.words(\"english\")\n\tstopwords_dict = Counter(stop_words)\n\n\t# This loop adds every article body into a temporary plain text file\n\tfor cop in cop_data:\n\t\tarticles = cop_data[cop]['articles']\n\t\tfor article in articles:\n\t\t\tarticle_text = article[\"body\"].lower().replace(\"\\n\", \" \")\n\t\t\t# Remove the stop words, we find them to not be informative for training word embeddings\n\t\t\tarticle_text = \" \".join([word for word in article_text.split() if word not in stopwords_dict])\n\t\t\tf1.write(article_text)\n\tf1.close()\n\ndef tokenization():\n\t\"\"\"\n\tThis module tokenizes the plain text from the articles utilizing NLTK's tokenizers.\n\t\"\"\"\n\tvocabulary = []\n\tf2 = open(\"embeddings/articlebodies.txt\", \"r\")\n\ttextbody = f2.read()\n\t\n\t# Tokenize the text into a list of sentences first\n\tsentences = nltk.tokenize.sent_tokenize(textbody)\n\tprint(\"Sentence tokenization complete\")\n\tfor sentence in sentences:\n\t\t# Tokenize every sentence and add to a vocabulary list containing every word in the dataset\n\t\twords = nltk.tokenize.word_tokenize(sentence)\n\t\tvocabulary.append(words)\n\n\tprint(\"Word tokenization complete\")\n\tf2.close()\n\treturn vocabulary\n\ndef train_embeddings():\n\t\"\"\"\n\tThis module trains the word embeddings on the training set of COP 1-24.\n\tIt then saves the embeddings as a .json file.\n\t\"\"\"\n\tvocabulary = tokenization()\n\n\t# Train and save the word2vec model\n\tmodel = Word2Vec(vocabulary, size=100, window=10, min_count=15, workers=4)\n\tprint(\"Model trained\")\n\tmodel.wv.save_word2vec_format(\"embeddings/word_embeddings.txt\", binary=False)\n\tprint(\"Model saved\")\n\n\t# From the trained word2vec model, create a dictionary with the tokens/words as keys and vectors as values\n\tf3 = open(\"embeddings/word_embeddings.txt\", \"r\")\n\tv = {\"vectors\": {}}\n\tfor line in f3:\n\t\t# During training, we found that some lines in the document were empty. We skip those lines with try/except\n\t\ttry:\n\t\t\tw, n = line.split(\" \", 1)\n\t\t\tv[\"vectors\"][w] = list(map(float, n.split()))\n\t\texcept ValueError:\n\t\t\tpass\n\tv = v[\"vectors\"]\n\n\tprint(\"Converted to JSON\")\n\t# Save the .json file containing the dictionary of word embeddings\n\twith open(\"embeddings/word_embeddings.txt\"[:-4] + \".json\", \"w\") as out:\n\t\tjson.dump(v, out)\n\tf3.close()\n\n\ndef main():\n\tbody_text()\n\ttrain_embeddings()\n\n\t# Remove the temporary plain text files\n\tos.remove(\"embeddings/articlebodies.txt\")\n\tos.remove(\"embeddings/word_embeddings.txt\")\n\n\nif __name__ == \"__main__\":\n\tmain()","sub_path":"word_embeddings.py","file_name":"word_embeddings.py","file_ext":"py","file_size_in_byte":3151,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"123577897","text":"H, W, N, M = list(map(int, input().split()))\nlights = [list(map(lambda x: int(x) - 1, input().split())) for _ in range(N)]\nblocks = [list(map(lambda x: int(x) - 1, input().split())) for _ in range(M)]\n\ngrid = [['']*W for _ in range(H)]\n\nfor h, w in blocks:\n grid[h][w] = 'B'\n\nfor h, w in lights:\n grid[h][w] = 'RC'\n # 右\n dw = 1\n while w+dw < W:\n if grid[h][w+dw] in ['B', 'C', 'RC', 'CR']:\n break\n grid[h][w+dw] += 'C' \n dw += 1\n # 左\n dw = -1\n while w+dw >= 0:\n if grid[h][w+dw] in ['B', 'C', 'RC', 'CR']:\n break\n grid[h][w+dw] += 'C'\n dw -= 1\n # 下\n dh = 1\n while h+dh < H:\n if grid[h+dh][w] in ['B', 'R', 'RC', 'CR']:\n break\n grid[h+dh][w] += 'R'\n dh += 1\n # 上\n dh = -1\n while h+dh >= 0:\n if grid[h+dh][w] in ['B', 'R', 'RC', 'CR']:\n break\n grid[h+dh][w] += 'R'\n dh -= 1\nans = H*W\nfor h in range(H):\n for w in range(W):\n if grid[h][w] in ['', 'B']:\n ans -= 1\nprint(ans)","sub_path":"old/ABC182/E.py","file_name":"E.py","file_ext":"py","file_size_in_byte":1077,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"504971903","text":"import os\nfrom datetime import timedelta\nBASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))\nROOT = os.path.dirname(os.path.realpath(__file__))\nENV = os.getenv(\"NEO_WISH_ENV\")\n\n# neo3 cli rpc address\nFAUCET_CLI = 'http://127.0.0.1:30332'\nCAPTCHA_SECRET = \"6LfNuZkUAAAAAAg4Hy1EqXto5U7O1wBII8ZajAzd\" \n\nclass Config(object):\n\n SQLALCHEMY_TRACK_MODIFICATIONS = False\n\n POSTGRES = {\n 'user': 'neo_faucet',\n 'pw': 'neo_faucet',\n 'db': 'neo3_faucet',\n 'host': 'localhost',\n 'port': '5432',\n }\n\n SQLALCHEMY_DATABASE_URI = 'postgresql://%(user)s:%(pw)s@%(host)s:%(port)s/%(db)s' % POSTGRES\n RATELIMIT_ENABLED = True\n DROP_AMOUNT = 50000000000\n\n # flask config\n SECRET_KEY = os.urandom(\n 24) # session secret key,init random string when app start\n PERMANENT_SESSION_LIFETIME = timedelta(seconds=1200) # session expire time\n\n # Github config\n # local\n # GITHUB_CLIENT_ID = '205be6d17715fd71c4b2'\n # GITHUB_CLIENT_SECRET = '083391b15a1e7e36f12732c7f40b028f00b1e8aa'\n # test\n \n # prod\n GITHUB_CLIENT_ID = '332dbac3756470c983b6'\n GITHUB_CLIENT_SECRET = '08184bd1fdcccee3bccb59c34cb40099637c0c04'\n\n if ENV==\"test\":\n GITHUB_CLIENT_ID = 'cf5c80adab6f96806e05'\n GITHUB_CLIENT_SECRET = '4583c7c12ee734744566be5dee95d77b18a00258'\n\n \n \n\n\n","sub_path":"config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":1365,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"162684929","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\n\n\"\"\"\nmcopte.py\nCreated 18.2.2015\n\nGoal: Calculate the memory capacity depending on changing parameters\n\tsigma and tau, which determine the recurrent and input weight distributions.\n\tA difference from mcopt.py is that this script fixes tau and produced only\n\t1D graph (but with error-bars)\n\"\"\"\n\n\nimport numpy as np\nfrom numpy import sum, random, meshgrid, zeros, linspace, average, std, sqrt\nfrom matplotlib import pyplot as plt\n\nfrom library.mc3 import memory_capacity\nfrom library.ortho import orthogonality\n\nq = 100\n\ntaus = [10**-7, 10**-8]\nposun = 0\n\n#taus = [0.00001, 0.000001, 10**-7, 10**-8]\n#posun = 4\n#taus = [0.1, 0.01, 0.001, 0.0001, 0.00001, 0.000001, 10**-7, 10**-8]\n\nnp.savetxt('saved/taus.txt', taus)\n\nsigmas = linspace(0.08, 0.095, 20)\nnp.savetxt('saved/sigmas.txt', sigmas)\n\n#tau = 0.0001\nINSTANCES = 1000\n\nY = zeros(len(sigmas))\nYerr = zeros(len(sigmas))\n\nfor ti, tau in enumerate(taus):\n\tprint(tau, \"of\", str(taus))\n\tfor i, sigma in enumerate(sigmas):\n\t\tmcs = zeros(INSTANCES)\n\t\tfor inm in range(INSTANCES):\n\t\t\tW = random.normal(0, sigma, [q, q])\n\t\t\tWI = random.uniform(-tau, tau, [q, 1])\n\t\t\tmcs[inm] = sum(memory_capacity(W, WI, memory_max=q, runs=1, iterations=15000, iterations_skipped=10000, iterations_coef_measure=1000)[0])\n\t\tY[i] = average(mcs)\n\t\tYerr[i] = std(mcs) # / sqrt(INSTANCES)\n\t\tprint(i,\"of\", len(sigmas))\n\n\tnp.savetxt('saved/avg-t'+str(ti + posun)+'.txt', Y)\n\tnp.savetxt('saved/std-t'+str(ti + posun)+'.txt', Yerr)\n\n\tplt.errorbar(sigmas, Y, yerr=Yerr, label=(\"$\\\\tau={0}$\".format(tau)))\n\nplt.grid(True)\nplt.xlabel(\"sigma: $W = N(0, \\\\sigma)$\")\nplt.ylabel(\"MC, errbar: $1 \\\\times \\\\sigma$\")\nplt.legend(loc=3)\n#plt.title(\"tau = {0}\".format(tau))\n\n\nplt.show()\n\ndef replot():\n\tplt.errorbar(sigmas, Y, yerr=Yerr, label=(\"$\\\\tau={0}$\".format(tau)))\n\tplt.grid(True)\n\tplt.xlabel(\"sigma: $W = N(0, \\\\sigma)$\")\n\tplt.ylabel(\"MC, errbar: $1 \\\\times \\\\sigma$\")\n\tplt.legend(loc=3)\n\t#plt.title(\"tau = {0}\".format(tau))\n\n\n\tplt.show()\n\n\n\n","sub_path":"rado/2015-02/mcopt-1d-error/mcopte.py","file_name":"mcopte.py","file_ext":"py","file_size_in_byte":2004,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"641789490","text":"import random, codecs, math\nfrom scipy import interpolate\n#import matplotlib.pyplot as plt\n\nTEST = False\n\nNO_FUNCTIONS = 4 # the number of transformations, like 3 or 4\nSPLITS = 6 # number of processes to fork into\nif TEST == True:\n BETWEEN = 50\n SEQUENCE_LENGTH = 4 # the number of key frames to interpolate between\n ITERATIONS = 9\nelse:\n BETWEEN = 800 # the number of frames between key frames\n SEQUENCE_LENGTH = 10\n ITERATIONS = 13\n\n# make NO_FUNCTIONS copies of a spline for each parameter\n# the number of points on the spline is SEQUENCE_LENGTH\n# each point is random\n\nsplines = {}\nfor param in [\"rotate\", \"xscale\", \"yscale\", \"xshift\", \"yshift\", \"red\", \"green\", \"blue\"]:\n for function_number in range(1,NO_FUNCTIONS+1):\n spline_points = []\n for point_number in range(SEQUENCE_LENGTH-1):\n if param.find(\"rotate\") != -1:\n spline_points.append(random.random()*2.0*math.pi)\n elif param.find(\"shift\") != -1 or param.find(\"scale\") != -1:\n #spline_points.append(random.random()*2.0 - 1.0)\n spline_points.append(random.random()*0.5 + 0.25)\n else:\n spline_points.append(random.randint(0,255))\n # add the first point as the last, so we return to it\n spline_points.append(spline_points[0])\n #print(spline_points)\n # interpolate\n x = range(0, SEQUENCE_LENGTH*BETWEEN, BETWEEN)\n tck = interpolate.splrep(x, spline_points)\n splines[param+str(function_number)] = tck\n\n#print(splines)\n\nifs_calls = []\nx = []\ny = []\nfor frame in range(0,(SEQUENCE_LENGTH-1)*BETWEEN):\n command = \"~/ifs/ifs \"\n for param in [\"rotate\", \"xscale\", \"yscale\", \"xshift\", \"yshift\", \"red\", \"green\", \"blue\"]:\n for function_number in range(1,NO_FUNCTIONS+1):\n command += \"--\" + param + str(function_number) + \" \"\n command += str(interpolate.splev(frame, splines[param+str(function_number)])) + \" \"\n if param.find(\"xscale\") != -1 and function_number == 1:\n x.append(frame)\n y.append(interpolate.splev(frame, splines[\"xscale1\"]))\n command += \"--iterations \"+str(ITERATIONS)\n #print(command)\n ifs_calls.append(command)\n\n#plt.plot(x, y)\n#plt.show()\n\n#render_sequence = range((SEQUENCE_LENGTH-1)*BETWEEN)\n#random.shuffle(render_sequence)\n\ncommands = []\n#commands.append(\"#!/bin/bash\")\n#wait_for_memory = \"while [ $(free -m | sed '2q;d' | awk -v N=7 '{print $N}' ) -lt 10000 ]; do sleep 3; done; \"\nwait_for_memory = \"while [ $(ps | grep -c 'convert' ) -ne 0 ]; do sleep $(($RANDOM%10 + 3)); done; \"\nfor frame_number in range((SEQUENCE_LENGTH-1)*BETWEEN):\n head = \"frame\" + str(frame_number).zfill(4)\n png = head + \".png\"\n commands.append('if [ ! -s ./'+png+' ]; then '+ifs_calls[frame_number]+' --filename '+str(frame_number%SPLITS)+'; '+ wait_for_memory + 'convert -verbose -format png -resize 3840x2160 -normalize -flip ifs'+str(frame_number%SPLITS)+'.bmp '+png+'; fi')\n\n\ncommands.append(\"while [ $(ls *.png | wc -l) -lt \" + str((SEQUENCE_LENGTH-1)*BETWEEN) + \" ]; do sleep 10; done; sleep 30; ffmpeg -r 30 -i frame%04d.png movie.mp4; totem movie.mp4\")\ncodecs.open(\"render.sh\", \"w\", \"utf8\").write(\"\\n\".join(commands))\n\nprint('for F in $(seq 0 '+str(SPLITS-1)+'); do cat render.sh | awk ' + \"'NR%6=='\" + '\"$F\" > fork\"$F\".sh; (bash fork\"$F\".sh &); sleep 3; done')\n","sub_path":"animation.py","file_name":"animation.py","file_ext":"py","file_size_in_byte":3387,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"585876306","text":"from docxtpl import DocxTemplate\n\n\ndef create_letter_from_template(context, file_path):\n\n try:\n doc = DocxTemplate(\"my_template.docx\")\n doc.render(context)\n doc.save(file_path + \"\\\\\" + \"generated_doc.docx\")\n return True\n except Exception as e:\n print(\"DOC file creation error\", e)\n return False\n","sub_path":"docx_edit.py","file_name":"docx_edit.py","file_ext":"py","file_size_in_byte":343,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"377403345","text":"\"\"\"empty message\n\nRevision ID: 0369a028f800\nRevises: 995a315cb6b7\nCreate Date: 2021-08-11 16:20:05.158834\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = '0369a028f800'\ndown_revision = '995a315cb6b7'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.create_table('article_type',\n sa.Column('id', sa.Integer(), autoincrement=True, nullable=False),\n sa.Column('type_name', sa.String(length=20), nullable=False),\n sa.PrimaryKeyConstraint('id')\n )\n op.add_column('article', sa.Column('type_id', sa.Integer(), nullable=False))\n op.create_foreign_key(None, 'article', 'article_type', ['type_id'], ['id'])\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.drop_constraint(None, 'article', type_='foreignkey')\n op.drop_column('article', 'type_id')\n op.drop_table('article_type')\n # ### end Alembic commands ###\n","sub_path":"migrations/versions/0369a028f800_.py","file_name":"0369a028f800_.py","file_ext":"py","file_size_in_byte":1044,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"284628447","text":"import random\r\nimport numpy as np\r\nimport time\r\n\r\nwhile True:\r\n number_of_players = int(input(\"Enter number of players:(At least 2 players)\"))\r\n if number_of_players > 1:\r\n break\r\n\r\n\r\ndef deck_making():\r\n ranks = [2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]\r\n color = [\"Trefl\", \"Karo\", \"Kier\", \"Pik\"]\r\n deck = []\r\n card = []\r\n number_of_decks = int(np.ceil(number_of_players / 6))\r\n for i in range(number_of_decks):\r\n for k in color:\r\n for j in ranks:\r\n card.append(j)\r\n card.append(k+str(i))\r\n deck.append(card)\r\n card = []\r\n random.shuffle(deck)\r\n return deck\r\n\r\n\r\n\r\n\r\ndef dealing(deck, number_of_players):\r\n list_of_players = []\r\n for i in range(number_of_players):\r\n list_of_players.append([])\r\n\r\n while len(deck) != 0:\r\n for i in range(number_of_players):\r\n if len(deck) != 0:\r\n list_of_players[i].append(deck[0])\r\n deck.pop(0)\r\n else:\r\n break\r\n return list_of_players\r\n\r\n\r\n\r\n\r\ndef fight(list_of_players, extra_stos = [], winers = [],):\r\n war = []\r\n stos = []\r\n winers2 = []\r\n #licznik = 0\r\n in_game = []\r\n for j in range(len(list_of_players)):\r\n #licznik += len(list_of_players[j])\r\n #print('a', list_of_players[j])\r\n if len(list_of_players[j]) == 0:\r\n winers.append(str(\"Player\" + str(j)))\r\n pass\r\n\r\n else:\r\n #print(\"player\", j, \"has\", len(list_of_players[j]))\r\n in_game.append(j)\r\n #print(\"players in game\",in_game)\r\n stos.append(list_of_players[j][0])\r\n print('player', j, \"put\", list_of_players[j][0])\r\n list_of_players[j].pop(0)\r\n #print(\"liczba kart\", licznik)\r\n copy_stos = stos.copy()\r\n copy_stos.sort()\r\n if len(copy_stos) > 1:\r\n if copy_stos[0][0] != copy_stos[1][0]:\r\n war.append(stos.index(copy_stos[0]))\r\n print('player numer', war, 'lost')\r\n stos.extend(extra_stos)\r\n list_of_players[in_game[war[0]]].extend(stos)\r\n stos = []\r\n\r\n else:\r\n war.append(stos.index(copy_stos[0]))\r\n for k in range(len(stos)):\r\n if k != 0:\r\n if copy_stos[0][0] == copy_stos[k][0]:\r\n index2 = stos.index(copy_stos[k])\r\n war.append(index2)\r\n war_copy = war.copy()\r\n for i in range(len(war_copy)):\r\n war[i] = list_of_players[i]\r\n fight(war,stos)\r\n\r\n else:\r\n stos.extend(extra_stos)\r\n list_of_players[in_game[0]].extend(stos)\r\n stos = []\r\n\r\n for w in winers:\r\n if w not in winers2:\r\n winers2.append(w)\r\n\r\n return winers2\r\n\r\n\r\ncard_deck = deck_making()\r\nplayers = dealing(card_deck, number_of_players)\r\n#print(type(number_of_players))\r\nwhile True:\r\n winers3 = fight(players)\r\n if len(winers3) == number_of_players:\r\n break\r\n time.sleep(1)\r\n\r\nprint(\"Winers in sequence\", winers3)\r\n","sub_path":"version for more players.py","file_name":"version for more players.py","file_ext":"py","file_size_in_byte":3145,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"6466788","text":"import os\n\nfrom tenclouds.imagescale2.settings import *\n\nDEF_HOST = '0.0.0.0'\nDEF_PORT = 12345\n\nDEF_WIDTH = 100\nDEF_HEIGHT = 100\nDEF_USE_FIT = False\n\nHASHING_ALGORITHM = 'md5'\nSALT = ''\n\nlocal_settings = os.path.join(os.path.dirname(__file__), 'local.py')\nif os.path.isfile(local_settings):\n from local import *\n\nAUTHORISATION = ('SaltedUrlHash', [HASHING_ALGORITHM, SALT], {})\n","sub_path":"urlannotator/settings/imagescale2.py","file_name":"imagescale2.py","file_ext":"py","file_size_in_byte":381,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"13023308","text":"import jieba\r\nimport pandas as pd\r\nfrom tqdm import tqdm\r\nimport numpy as np\r\nimport torch\r\nimport torch.nn as nn\r\nimport torch.optim as optim\r\nfrom gensim.models import KeyedVectors\r\nfrom sklearn.model_selection import train_test_split\r\n\r\nSENTENCE_LIMIT_SIZE=200\r\nEMBEDDING_SIZE=300\r\nBATCH_SIZE = 128\r\nLEARNING_RATE = 1e-3\r\n\r\nstopwordFile='.\\Data/stopwords.txt'\r\ntrainFile='./Data/multi_brand3000.csv'\r\nwordLabelFile = 'wordLabel.txt'\r\nlengthFile = 'length.txt'\r\n\r\ndef read_stopword(file):\r\n data = open(file, 'r', encoding='utf-8').read().split('\\n')\r\n\r\n return data\r\n\r\ndef loaddata(trainfile,stopwordfile):\r\n a=pd.read_csv(trainfile,encoding='gbk')\r\n stoplist = read_stopword(stopwordfile)\r\n text=a['rateContent']\r\n y=a['price']\r\n x=[]\r\n\r\n for line in text:\r\n line=str(line)\r\n title_seg = jieba.cut(line, cut_all=False)\r\n use_list = []\r\n for w in title_seg:\r\n if w in stoplist:\r\n continue\r\n else:\r\n use_list.append(w)\r\n x.append(use_list)\r\n\r\n return x,y\r\n\r\n\r\ndef dataset(trainfile,stopwordfile):\r\n word_to_idx = {}\r\n idx_to_word = {}\r\n stoplist = read_stopword(stopwordfile)\r\n a = pd.read_csv(trainfile,encoding='gbk')\r\n datas=a['rateContent']\r\n datas = list(filter(None, datas))\r\n try:\r\n for line in datas:\r\n line=str(line)\r\n title_seg = jieba.cut(line, cut_all=False)\r\n length = 2\r\n for w in title_seg:\r\n if w in stoplist:\r\n continue\r\n if w in word_to_idx:\r\n word_to_idx[w] += 1\r\n length+=1\r\n else:\r\n word_to_idx[w] = length\r\n except:\r\n pass\r\n word_to_idx[''] = 0\r\n word_to_idx[''] =1\r\n idx_to_word[0] = ''\r\n idx_to_word[1] = ''\r\n return word_to_idx\r\n\r\na=dataset(trainFile,stopwordFile)\r\nprint(len(a))\r\nb={v: k for k, v in a.items()}\r\nVOCAB_SIZE = 352217\r\nx,y=loaddata(trainFile,stopwordFile)\r\ndef convert_text_to_token(sentence, word_to_token_map=a, limit_size=SENTENCE_LIMIT_SIZE):\r\n unk_id = word_to_token_map[\"\"]\r\n pad_id = word_to_token_map[\"\"]\r\n\r\n # 对句子进行token转换,对于未在词典中出现过的词用unk的token填充\r\n tokens = [word_to_token_map.get(word, unk_id) for word in sentence]\r\n\r\n if len(tokens) < limit_size: #补齐\r\n tokens.extend([0] * (limit_size - len(tokens)))\r\n else: #截断\r\n tokens = tokens[:limit_size]\r\n\r\n return tokens\r\n\r\nx_data=[convert_text_to_token(sentence) for sentence in x]\r\nx_data=np.array(x_data)\r\nwvmodel=KeyedVectors.load_word2vec_format('word60.vector')\r\nstatic_embeddings = np.zeros([VOCAB_SIZE,EMBEDDING_SIZE ])\r\nfor word, token in tqdm(a.items()):\r\n\r\n if word in wvmodel.vocab.keys():\r\n static_embeddings[token, :] = wvmodel[word]\r\n elif word == '':\r\n static_embeddings[token, :] = np.zeros(EMBEDDING_SIZE)\r\n else:\r\n static_embeddings[token, :] = 0.2 * np.random.random(EMBEDDING_SIZE) - 0.1\r\n\r\nprint(static_embeddings.shape)\r\n\r\nX_train,X_test,y_train,y_test=train_test_split(x_data, y, test_size=0.3)\r\n\r\ndef get_batch(x,y,batch_size=BATCH_SIZE, shuffle=True):\r\n assert x.shape[0] == y.shape[0], print(\"error shape!\")\r\n\r\n\r\n n_batches = int(x.shape[0] / batch_size) #统计共几个完整的batch\r\n\r\n for i in range(n_batches - 1):\r\n x_batch = x[i*batch_size: (i+1)*batch_size]\r\n y_batch = y[i*batch_size: (i+1)*batch_size]\r\n\r\n yield x_batch, y_batch\r\n\r\nimport torch.nn.functional as F\r\n\r\nclass GlobalMaxPool1d(nn.Module):\r\n def __init__(self):\r\n super(GlobalMaxPool1d, self).__init__()\r\n\r\n def forward(self, x):\r\n return torch.max_pool1d(x, kernel_size=x.shape[-1])\r\n\r\n\r\nclass TextRCNN(nn.Module):\r\n def __init__(self, vocab_size, embedding_dim, hidden_size, num_labels=2):\r\n super(TextRCNN, self).__init__()\r\n self.embedding = nn.Embedding(vocab_size, embedding_dim)\r\n self.lstm = nn.LSTM(input_size=embedding_dim, hidden_size=hidden_size,\r\n batch_first=True, bidirectional=True)\r\n self.globalmaxpool = GlobalMaxPool1d()\r\n self.dropout = nn.Dropout(.5)\r\n self.linear1 = nn.Linear(embedding_dim + 2 * hidden_size, 256)\r\n self.linear2 = nn.Linear(256, num_labels)\r\n\r\n def forward(self, x): # x: [batch,L]\r\n x_embed = self.embedding(x) # x_embed: [batch,L,embedding_size]\r\n last_hidden_state, (c, h) = self.lstm(x_embed) # last_hidden_state: [batch,L,hidden_size * num_bidirectional]\r\n out = torch.cat((x_embed, last_hidden_state),\r\n 2) # out: [batch,L,embedding_size + hidden_size * num_bidirectional]\r\n # print(out.shape)\r\n out = F.relu(self.linear1(out))\r\n out = out.permute(dims=[0, 2, 1]) # out: [batch,embedding_size + hidden_size * num_bidirectional,L]\r\n out = self.globalmaxpool(out).squeeze(-1) # out: [batch,embedding_size + hidden_size * num_bidirectional]\r\n # print(out.shape)\r\n out = self.dropout(out) # out: [batch,embedding_size + hidden_size * num_bidirectional]\r\n out = self.linear2(out) # out: [batch,num_labels]\r\n return out\r\n\r\ndef resnet_cifar(net, input_data):\r\n x = net.embedding(input_data)\r\n out1, (final_hidden_state, final_cell_state) = net.lstm(x)\r\n out = torch.cat((x, out1),\r\n 2)\r\n out = F.relu(net.linear1(out))\r\n out = out.permute(dims=[0, 2, 1]) # out: [batch,embedding_size + hidden_size * num_bidirectional,L]\r\n out = net.globalmaxpool(out).squeeze(-1) # out: [batch,embedding_size + hidden_size * num_bidirectional]\r\n # print(out.shape)\r\n out = net.dropout(out)\r\n return out\r\n\r\nclass next(nn.Module):\r\n def __init__(self, output_size ):\r\n super(next, self).__init__()\r\n self.fc = nn.Linear(256, output_size)\r\n\r\n def forward(self,x):\r\n logit = self.fc(x)\r\n return logit\r\n\r\nrnn=TextRCNN(vocab_size=VOCAB_SIZE,embedding_dim=EMBEDDING_SIZE,hidden_size=64)\r\nrnn.load_state_dict(torch.load('./model-TextRCNN3.pkl'))\r\nrnnnext=next(2)\r\noptimizer = optim.Adam(rnnnext.parameters(), lr=LEARNING_RATE)\r\ncriteon = nn.CrossEntropyLoss()\r\n\r\ndef train(rnnnext, optimizer, criteon):\r\n\r\n global loss\r\n avg_acc = []\r\n rnnnext.train() #表示进入训练\r\n\r\n for x_batch, y_batch in get_batch(X_train,y_train):\r\n try:\r\n x_batch = torch.LongTensor(x_batch)\r\n y_batch = torch.LongTensor(y_batch.to_numpy())\r\n\r\n y_batch = y_batch.squeeze()\r\n x_batch = resnet_cifar(rnn, x_batch)\r\n pred = rnnnext(x_batch)\r\n acc = binary_acc(torch.max(pred, dim=1)[1], y_batch)\r\n avg_acc.append(acc)\r\n\r\n loss =criteon(pred, y_batch)\r\n\r\n optimizer.zero_grad()\r\n loss.backward()\r\n optimizer.step()\r\n except:\r\n pass\r\n\r\n avg_acc = np.array(avg_acc).mean()\r\n return avg_acc,loss\r\n\r\ndef evaluate(rnnnext, criteon):\r\n avg_acc = []\r\n rnnnext.eval() #表示进入测试模式\r\n\r\n with torch.no_grad():\r\n for x_batch, y_batch in get_batch(X_test, y_test):\r\n try:\r\n x_batch = torch.LongTensor(x_batch)\r\n y_batch = torch.LongTensor(y_batch.to_numpy())\r\n\r\n y_batch = y_batch.squeeze() #torch.Size([128])\r\n\r\n x_batch = resnet_cifar(rnn, x_batch)\r\n pred = rnnnext(x_batch) #torch.Size([128, 2])\r\n\r\n acc = binary_acc(torch.max(pred, dim=1)[1], y_batch)\r\n avg_acc.append(acc)\r\n except:\r\n pass\r\n\r\n avg_acc = np.array(avg_acc).mean()\r\n return avg_acc\r\n\r\ndef binary_acc(preds, y):\r\n correct = torch.eq(preds, y).float()\r\n acc = correct.sum() / len(correct)\r\n return acc\r\n\r\nfor epoch in range(15):\r\n\r\n train_acc,loss = train(rnnnext, optimizer, criteon)\r\n print('epoch={},训练准确率={},误判率 ={}'.format(epoch, train_acc,loss))\r\n test_acc = evaluate(rnnnext, criteon)\r\n print(\"epoch={},测试准确率={}\".format(epoch, test_acc))\r\n\r\n","sub_path":"TextRCNN_迁移.py","file_name":"TextRCNN_迁移.py","file_ext":"py","file_size_in_byte":8315,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"211811883","text":"# -*- coding: utf-8 -*-\n# change name of the folder(e.g. 0002,0007,0010,0011... to 0,1,2,3)\nimport os\nfrom shutil import copyfile\nimport argparse\n\n# Options\nparser = argparse.ArgumentParser(description='pytorch data path')\nparser.add_argument('--data_path', default='pytorch', type=str, help='the generated folder of pytorch data set')\nopt = parser.parse_args()\n\n\n# copy folder tree from source to destination\ndef copyfolder(src, dst):\n files = os.listdir(src)\n if not os.path.isdir(dst):\n os.mkdir(dst)\n for tt in files:\n copyfile(src + '/' + tt, dst + '/' + tt)\n\n\nif __name__ == '__main__':\n # original_path = '/home/gq123/guanqiao/deeplearning/reid/market/pytorch'\n original_path = opt.data_path\n\n data_dir = ['/train', '/val']\n\n for i in data_dir:\n train_save_path = original_path + i + '_new'\n data_path = original_path + i\n if not os.path.isdir(train_save_path):\n os.mkdir(train_save_path)\n\n reid_index = 0\n folders = os.listdir(data_path)\n for foldernames in folders:\n copyfolder(data_path + '/' + foldernames, train_save_path + '/' + str(reid_index).zfill(4))\n reid_index = reid_index + 1\n","sub_path":"src/main/python/dl/gan/Person-reid-GAN-pytorch/changeIndex.py","file_name":"changeIndex.py","file_ext":"py","file_size_in_byte":1209,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"387528466","text":"#!/usr/bin/env python2.7\n'''\nScript for container processes.\n'''\nimport os\nimport shlex\nfrom lib.scriptutil import *\n\n\ndef parseCommand(cmd) :\n args = shlex.split(cmd)\n exe = args.pop(0)\n return (exe, args)\n\n\ndef executeConf() :\n conf = \"/launch.conf\" \n\n with open(conf) as f:\n rawcmds = f.readlines()\n\n cmds = []\n for cmd in rawcmds :\n if not cmd :\n continue\n\n cmd = cmd.lstrip().rstrip()\n\n if cmd[0][0] == '#' :\n continue\n\n (cmd, args) = parseCommand(cmd)\n execute(cmd, args)\n\n\nif __name__ == \"__main__\":\n executeConf()","sub_path":"src/compose/src/scripts/launch.py","file_name":"launch.py","file_ext":"py","file_size_in_byte":609,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"569089910","text":"\"\"\"\nThis code defines a class, which in turn builds and compiles LaTeX code for\nBook 2 of this project.\n\"\"\"\n\n# Imports.\nimport os\n\n# Local imports.\nimport which_poems\nfrom utilities import compile_tex_from_string, get_contents\n\n##############\n# MAIN CLASS #\n##############\n\nclass Book2:\n \"\"\" The class in question. \"\"\"\n def __init__(self):\n self.tex = None\n self.base = get_contents(\"book2_base.tex\")\n self.package_code = get_contents(\"package_code.tex\")\n\n def build_tex(self):\n \"\"\" Add the poems to the .tex document. \"\"\"\n result = self.base\n result = result.replace(\"#PACKAGE_CODE\", self.package_code)\n the_poems = \"\"\n for filename in which_poems.book2:\n poem = Poem(filename)\n the_poems = the_poems+poem.printout+\"\\n\\n\"\n result = result.replace(\"#THE_POEMS\", the_poems)\n self.tex = result\n\n def build_pdf(self):\n \"\"\" Build the PDF using XeLaTeX. \"\"\"\n compile_tex_from_string(self.tex)\n os.rename(\"main.pdf\", \"book2.pdf\")\n\nclass Poem:\n \"\"\" A helper class, this handles the properties of a poem. \"\"\"\n def __init__(self, filename):\n self.filename = filename\n self.title = self.parse_title()\n self.body = get_contents(\"poems/book2/\"+filename)\n self.printout = self.get_printout()\n\n def parse_title(self):\n \"\"\" Converts a filename into a title. \"\"\"\n result = self.filename[:self.filename.index(\".tex\")]\n result = result.replace(\"_\", \" \")\n return result\n\n def get_printout(self):\n \"\"\" Generates a LaTeX printout from the other fields. \"\"\"\n result = \"\\\\chapter*{\"+self.title+\"}\\n\\n\"+self.body\n return result\n","sub_path":"book2.py","file_name":"book2.py","file_ext":"py","file_size_in_byte":1718,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"615125802","text":"from http.server import HTTPServer, BaseHTTPRequestHandler\n\nclass helloHandler(BaseHTTPRequestHandler):\n def do_GET(self):\n self.send_response(200)\n self.send_header('content-type', 'text/html')\n self.end_headers()\n # self.wfile.write('Hello Simon!'.encode())\n\ndef main():\n PORT = 8000\n server = HTTPServer(('', PORT), helloHandler)\n print('Server running on port %s' % PORT)\n server.serve_forever()\n\nif __name__ == '__main__':\n main()","sub_path":"webserver.py","file_name":"webserver.py","file_ext":"py","file_size_in_byte":481,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"343493821","text":"from tkinter import *\ndef intersection(lst1, lst2):\n lst3 = [value for value in lst1 if value in lst2]\n return lst3\ndef repeating():\n global used_buttons\n global b\n global player1\n global player2\n global player\n global winner\n lable_winning.configure(text=\"\")\n used_buttons=[]\n b = [[0,0,0],\n [0,0,0],\n [0,0,0]]\n winner=0\n player1=[]\n player2=[]\n player = ' X '\n for i in range(3):\n for j in range(3):\n b[i][j] = Button(font=( ' Verdana ' , 56), width=3,\n command = lambda n=i,m=j: click(n,m))\n b[i][j].grid(row = i, column = j)\ndef click(n,m):\n global player\n global player1\n global player2\n global winner\n global lable_winning\n if [n,m] not in used_buttons:\n if winner ==0:\n if player == ' X ' :\n b[n][m].configure(text = ' X ' )\n player1.append([n,m])\n player = ' O '\n turn_label.configure(text=player+\" plays\")\n else:\n b[n][m].configure(text = ' O ' )\n player2.append([n,m])\n player = ' X '\n turn_label.configure(text=player+\" plays\")\n for W in wining_list:\n if intersection(W,player1)== W :\n winner =\"X\"\n if intersection(W,player2)==W :\n winner =\"O\"\n if winner ==\"X\" or winner ==\"O\" :\n lable_winning.configure(text=winner+ \" is the winner\")\n lable_winning.grid(row=4, column=1)\n turn_label.configure(text=\"\")\n used_buttons.append([n,m])\nroot = Tk()\nroot.title( ' tic-toc-toe ' )\nb = [[0,0,0],\n[0,0,0],\n[0,0,0]]\nwinner=0\nplayer1=[]\nplayer2=[]\nused_buttons=[]\nfor i in range(3):\n for j in range(3):\n b[i][j] = Button(font=( ' Verdana ' , 56), width=3,\n command = lambda n=i,m=j: click(n,m))\n b[i][j].grid(row = i, column = j)\n\nwining_list=[ [[0,0],[0,1],[0,2]], [[1,0],[1,1],[1,2]],[[2,0],[2,1],[2,2]] ,\n [[0,0],[1,0],[2,0]] ,[[0,1],[1,1],[2,1]],[[0,2],[1,2],[2,2]] ,\n [ [0,0],[1,1],[2,2]] , [ [2,0],[1,1],[0,2]] ]\nlable_winning=Label(text= str(winner)+\" is the winner\")\nplayer = ' X '\nturn_label=Label(text=player+\" is turn\")\nturn_label.grid(row=4,column=2)\nplay_again=Button(text=\"play again\", command = repeating)\nplay_again.grid(row=4, column=0)\nmainloop()\n","sub_path":"tic-toc/tic-toc.py","file_name":"tic-toc.py","file_ext":"py","file_size_in_byte":2288,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"202054403","text":"# coding=utf-8\n# Copyleft 2019 project LXRT.\n\nimport os\nimport collections\nimport json\n\nimport torch\nimport torch.nn as nn\nfrom torch.utils.data.dataloader import DataLoader\nfrom tqdm import tqdm\n\nfrom param import args\nfrom pretrain.qa_answer_table import load_lxmert_qa\nfrom eval_matching.image_text_matching_model import ImageTextMatchingLXRTModel\nfrom eval_matching.image_text_matching_data import ImageTextMatchingDataset, ImageTextMatchingTorchDataset, ImageTextMatchingEvaluator\n# from lxrt.entry import LXRTEncoder, set_visual_config\nfrom lxrt.modeling import VisualConfig, BertConfig\n\nDataTuple = collections.namedtuple(\"DataTuple\", 'dataset loader evaluator')\n\n_DEBUG = False\n\ndef get_tuple(splits: str, bs:int, shuffle=False, drop_last=False) -> DataTuple:\n dset = ImageTextMatchingDataset(splits)\n tset = ImageTextMatchingTorchDataset(dset)\n evaluator = ImageTextMatchingEvaluator(dset)\n data_loader = DataLoader(\n tset, batch_size=bs,\n shuffle=shuffle, num_workers=args.num_workers,\n drop_last=drop_last, pin_memory=True\n )\n\n return DataTuple(dataset=dset, loader=data_loader, evaluator=evaluator)\n\n\nclass ImageTextMatching:\n def __init__(self):\n self.train_tuple = get_tuple(\n args.train, bs=args.batch_size, shuffle=True, drop_last=True\n )\n if args.valid != \"\":\n valid_bsize = 2048 if args.multiGPU else 512\n self.valid_tuple = get_tuple(\n args.valid, bs=valid_bsize,\n shuffle=False, drop_last=False\n )\n else:\n self.valid_tuple = None\n\n #self.model = LXRTEncoder(args, max_seq_length=20, mode='xlr')\n bert_config = BertConfig(vocab_size_or_config_json_file='./model/bert-base-uncased/bert_config.json')\n self.model = ImageTextMatchingLXRTModel(bert_config, args)\n\n # Load pre-trained weights\n if args.load_lxmert is not None:\n self.model.load(args.load_lxmert)\n\n # GPU options\n if args.multiGPU:\n self.model.multi_gpu()\n self.model = self.model.cuda()\n\n # Losses and optimizer\n self.mce_loss = nn.CrossEntropyLoss(ignore_index=-1)\n if 'bert' in args.optim:\n batch_per_epoch = len(self.train_tuple.loader)\n t_total = int(batch_per_epoch * args.epochs)\n print(\"Total Iters: %d\" % t_total)\n from lxrt.optimization import BertAdam\n self.optim = BertAdam(list(self.model.parameters()),\n lr=args.lr,\n warmup=0.1,\n t_total=t_total)\n else:\n self.optim = args.optimizer(list(self.model.parameters()), args.lr)\n\n self.output = args.output\n os.makedirs(self.output, exist_ok=True)\n\n def train(self, train_tuple, eval_tuple):\n dset, loader, evaluator = train_tuple\n iter_wrapper = (lambda x: tqdm(x, total=len(loader))) if args.tqdm else (lambda x: x)\n\n best_valid = 0.\n for epoch in range(args.epochs):\n quesid2ans = {}\n for i, (ques_id, feats, boxes, sent, label) in iter_wrapper(enumerate(loader)):\n self.model.train()\n\n self.optim.zero_grad()\n feats, boxes, label = feats.cuda(), boxes.cuda(), label.cuda()\n logit = self.model(feats, boxes, sent)\n\n loss = self.mce_loss(logit, label)\n\n loss.backward()\n nn.utils.clip_grad_norm_(self.model.parameters(), 5.)\n self.optim.step()\n\n score, predict = logit.max(1)\n for qid, l in zip(ques_id, predict.cpu().numpy()):\n quesid2ans[qid] = l\n\n log_str = \"\\nEpoch %d: Train %0.2f\\n\" % (epoch, evaluator.evaluate(quesid2ans) * 100.)\n\n if self.valid_tuple is not None: # Do Validation\n valid_score = self.evaluate(eval_tuple)\n if valid_score > best_valid:\n best_valid = valid_score\n self.save(\"BEST\")\n\n log_str += \"Epoch %d: Valid %0.2f\\n\" % (epoch, valid_score * 100.) + \\\n \"Epoch %d: Best %0.2f\\n\" % (epoch, best_valid * 100.)\n\n print(log_str, end='')\n\n with open(self.output + \"/log.log\", 'a') as f:\n f.write(log_str)\n f.flush()\n\n self.save(\"LAST\")\n\n def predict(self, eval_tuple: DataTuple, dump=None):\n self.model.eval()\n dset, loader, evaluator = eval_tuple\n quesid2ans = {}\n\n for i, datum_tuple in enumerate(loader):\n #ques_id, feats, boxes, sent, _, _, img_ids = datum_tuple[:7] # avoid handling target\n ques_id, feats, boxes, sent, _, raw_target, img_ids, gounds = datum_tuple[:8] # avoid handling target\n # print (sent)\n \n with torch.no_grad():\n cross_relationship_score = self.model(sent, feats, boxes)\n if _DEBUG: print (\"cross_relationship_score=\", cross_relationship_score.shape) \n\n match_labels = torch.max(cross_relationship_score, dim=1)\n if _DEBUG: print (\"cos_score=\", match_labels)\n\n for q_id, i_id, sent_ele, roi_obj, gound, is_match in zip(ques_id.tolist(), img_ids, sent, raw_target, gounds, match_labels.indices.cpu().numpy()):\n # quesid2ans[qid] = \"True\" if l == 1 else \"False\"\n predict_label = \"True\" if is_match == 1 else \"False\"\n quesid2ans[q_id] = {\"answer\": predict_label, \"image_id\": i_id, \"sentence\": sent_ele, \"roi_obj\": json.loads(roi_obj), \"ground\": gound}\n if _DEBUG: print (quesid2ans)\n if dump is not None:\n evaluator.dump_result(quesid2ans, dump)\n return quesid2ans\n\n def evaluate(self, eval_tuple: DataTuple, dump=None):\n dset, loader, evaluator = eval_tuple\n quesid2ans = self.predict(eval_tuple, dump)\n return evaluator.evaluate_matching(quesid2ans)\n\n def save(self, name):\n torch.save(self.model.state_dict(),\n os.path.join(self.output, \"%s.pth\" % name))\n\n def load(self, path):\n print(\"Load model from %s\" % path)\n state_dict = torch.load(\"%s.pth\" % path)\n self.model.load_state_dict(state_dict)\n\n\nif __name__ == \"__main__\":\n # Build Class\n matching = ImageTextMatching()\n\n # Open debug mode\n if args.debug is True:\n _DEBUG = True\n\n # Load Model\n if args.load is not None:\n matching.load(args.load)\n\n # Test or Train\n if args.test is not None:\n args.fast = args.tiny = False # Always loading all data in test\n if 'test' in args.test:\n matching.predict(\n get_tuple(args.test, bs=950,\n shuffle=False, drop_last=False),\n dump=os.path.join(args.output, 'test_predict.json')\n )\n elif 'val' in args.test: \n # Since part of valididation data are used in pre-training/fine-tuning,\n # only validate on the minival set.\n result = matching.evaluate(\n #get_tuple('minival', bs=950,\n get_tuple(args.test, bs=950,\n shuffle=False, drop_last=False),\n dump=os.path.join(args.output, 'minival_predict.json')\n )\n print (result)\n else:\n assert False, \"No such test option for %s\" % args.test\n else:\n print('Splits in Train data:', matching.train_tuple.dataset.splits)\n if matching.valid_tuple is not None:\n print('Splits in Valid data:', matching.valid_tuple.dataset.splits)\n else:\n print(\"DO NOT USE VALIDATION\")\n matching.train(matching.train_tuple, matching.valid_tuple)\n\n\n","sub_path":"src/eval_matching/image_text_matching.py","file_name":"image_text_matching.py","file_ext":"py","file_size_in_byte":7887,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"251567769","text":" #!/usr/bin/env python\n# -*- coding: utf-8 -*-\n#\n# Basic example for a bot that uses inline keyboards.\n# This program is dedicated to the public domain under the CC0 license.\n\nimport logging\n\nfrom telegrambotservice import *\nfrom jobs import *\nfrom usermanagement import *\nfrom realangebote import *\nfrom telegram.ext import Updater, CommandHandler, CallbackQueryHandler, MessageHandler, Filters, Job\n\n\ndef start(bot, update):\n\tsetMessageString(\"Ich suche nach Angeboten! :)\")\n\tsendMessage(bot, update)\n\n\tsetMessageString(str(getUsers()))\n\tsendMessage(bot, update)\n\t\n\ndef search_products(name_list):\n\tangebote_all = getRealAngebote()\n\tangebote_found = []\n\toutputmsg = []\n\tclearMessages()\n\tfor name in name_list:\n\t\tfor angebot in angebote_all:\t\t\t\n\t\t\tif name in angebot[\"name\"] and not angebot in angebote_found:\n\t\t\t\tangebote_found.append(angebot)\n\n\tfor produkt in angebote_found:\n\t\tmessage = \"Angebot:\\n\\n\"\n\t\tmessage += \"Name: %s\\n\" % produkt[\"name\"]\n\t\tmessage += \"Preis: %s\\n\" % produkt[\"preis\"]\n\t\tmessage += \"Datum: %s\\n\\n\" % produkt[\"datum\"]\n\n\t\tmessage += \"%s\" % produkt[\"link\"]\n\n\t\toutputmsg.append(message)\n\n\n\t# Gebe Nachrichten zurück.\n\treturn outputmsg\n\n\ndef subscribe_products(bot, update, name_list):\n\tfor name in name_list:\n\t\tsubscribe(update.message.chat_id, name)\n\n\t# Sende Nachricht\n\tsetMessageString(str(getSubscribeList(update.message.chat_id)))\n\tsendMessage(bot, update)\n\ndef unsubscribe_products(bot, update, name_list):\n\tfor name in name_list:\n\t\tunsubscribe(update.message.chat_id, name)\n\n\t# Sende Nachricht\n\tsetMessageString(str(getSubscribeList(update.message.chat_id)))\n\tsendMessage(bot, update)\n\n\ndef error(bot, update, error):\n logging.warning('Update \"%s\" caused error \"%s\"' % (update, error))\n\ndef message_interpreter(bot, update):\n\tmsg_splitted = update.message.text.lower().split(\" \")\t\n\tcmd = msg_splitted[0]\n\tregisterUser(update.message.from_user, bot, update)\n\n\tif cmd == \"search\":\n\t\tsearch_list = []\n\t\tfor to_search in msg_splitted[1:]:\n\t\t\tsearch_list.append(to_search.encode(\"utf-8\"))\n\t\tmsglist = search_products(search_list)\n\t\t\n\t\tif msg_splitted:\n\t\t\tsetMessageList(msglist)\n\t\t\tsendMessage(bot, update)\n\t\telse:\n\t\t\tsetMessageString(\"Gegenwärtig keine Angebote.\")\n\t\t\tsendMessage(bot, update)\n\n\n\tif cmd == \"subscribe\":\n\t\tsubscribe_list = []\n\t\tfor to_subscribe in msg_splitted[1:]:\n\t\t\tsubscribe_list.append(to_subscribe.encode(\"utf-8\"))\n\t\tsubscribe_products(bot, update, subscribe_list)\n\n\n\tif cmd == \"unsubscribe\":\n\t\tunsubscribe_list = []\n\t\tfor to_unsubscribe in msg_splitted[1:]:\n\t\t\tunsubscribe_list.append(to_unsubscribe.encode(\"utf-8\"))\n\t\tunsubscribe_products(bot, update, unsubscribe_list)\n\n\ndef main():\n\n\tlogging.basicConfig(level=logging.DEBUG, format='%(asctime)s' +\n '- %(name)s - %(levelname)s - %(message)s')\n\tlogger = logging.getLogger(__name__)\n\n\t# Create the Updater and pass it your bot's token.\n\tupdater = Updater(\"291218007:AAEKDywDY5B2liyHQzsS480QlqYEbOpPRgE\")\n\n\tupdater.dispatcher.add_handler(CommandHandler('start', start))\n\tupdater.dispatcher.add_handler(CallbackQueryHandler(button))\n\tupdater.dispatcher.add_handler(MessageHandler([Filters.text], message_interpreter))\n\tupdater.dispatcher.add_error_handler(error)\n\n\tjobqueue = updater.job_queue\n\n\t# User datebase:\t\n\tloadusers()\n\n\t# Job: stündlich\n\tjob_hour = Job(callback_hour, 5)\n\tjobqueue.put(job_hour, next_t=0.0)\n\n\t# Start the Bot\n\tupdater.start_polling()\n\n\t# Run the bot until the user presses Ctrl-C or the process receives SIGINT,\n\t# SIGTERM or SIGABRT\n\tupdater.idle()\n\n# start Main Methode.\nif __name__ == '__main__':\n main()\n","sub_path":"CheapMunk/cheapmunk.py","file_name":"cheapmunk.py","file_ext":"py","file_size_in_byte":3566,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"337882857","text":"# uncompyle6 version 3.7.4\n# Python bytecode 3.7 (3394)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: build\\bdist.win32\\egg\\SimpleMathCalc\\Hex_conversion_decimal_binary.py\n# Compiled at: 2019-04-09 12:10:41\n# Size of source mod 2**32: 823 bytes\n\n\ndef dtb():\n b = [\n 0, 0, 0, 0, 0, 0, 0, 0]\n s = int(input('Please enter a decimal number(less than 255):'))\n for i in range(0, 8, 1):\n b[i] = int(s % 2)\n s = s // 2\n\n b.reverse()\n p = [str(i) for i in b]\n print('The binary number is:', ''.join(p), '\\n\\n\\n-----')\n\n\ndef btd():\n a = 0\n d = list(input('Please enter a binary number(less than eight places):'))\n d.reverse()\n for i in range(0, len(d), 1):\n if int(d[i]) == 1:\n a += pow(2, i)\n\n print('The decimal number is:', a, '\\n\\n\\n-----')\n\n\nwhile True:\n choose = int(input('Decimal to binary please input: 1 \\nBinary to decimal please input: 2 \\n\\ninput: '))\n if choose == 1:\n dtb()\n elif choose == 2:\n btd()\n else:\n break","sub_path":"pycfiles/SimpleMathCalc-0.1-py3.7/Hex_conversion_decimal_binary.cpython-37.py","file_name":"Hex_conversion_decimal_binary.cpython-37.py","file_ext":"py","file_size_in_byte":1085,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"294514125","text":"# -*- coding: utf-8 -*-\n__all__ = ['postprocess']\n\n_FUNCTION = ['家庭', '政府', '医疗', '科教', '媒体', '公益', '文化', '经济']\n\n\nclass Building(object):\n def __init__(self):\n self.id = 0\n self.func = ''\n self.result = {0.2: {'x': {}, 'y': {}},\n 0.3: {'x': {}, 'y': {}},\n 0.4: {'x': {}, 'y': {}}}\n\n\ndef postprocess(blgFuncPath, resultDir):\n blgs = []\n # 读取分类\n with open(blgFuncPath, 'r', encoding='utf-8') as f:\n f.readline()\n for line in f.readlines():\n temp = line.strip('\\n').split()\n blg = Building()\n try:\n blg.id = int(temp[0])\n except:\n print('建筑功能文件ID不正确!')\n try:\n blg.func = temp[1]\n except:\n blg.func = '家庭' # 缺省\n if blg.func not in _FUNCTION:\n print('建筑功能文件Function不正确!')\n blgs.append(blg)\n\n # 读取结果\n for pga in [0.2, 0.3, 0.4]:\n for direction in ['x', 'y']:\n try:\n with open(resultDir + '/' + str(pga) + '/' + direction + '/basic.txt', 'r', encoding='utf-8') as f:\n f.readline()\n for blg in blgs:\n temp = f.readline().strip('\\n').split()\n result = {}\n result['lossMedian'] = float(temp[2])\n result['lossP16'] = float(temp[5])\n result['lossP84'] = float(temp[6])\n result['downtimeMedian'] = float(temp[3])\n result['downtimeP16'] = float(temp[7])\n result['downtimeP84'] = float(temp[8])\n result['hurtMedian'] = float(temp[9])\n result['hurtP16'] = float(temp[10])\n result['hurtP84'] = float(temp[11])\n result['deathMedian'] = float(temp[12])\n result['deathP16'] = float(temp[13])\n result['deathP84'] = float(temp[14])\n blg.result[pga][direction]['loss'] = result\n\n with open(resultDir + '/' + str(pga) + '/' + direction + '/DamageState.txt', 'r',\n encoding='utf-8') as f:\n f.readline()\n numEQ = 1\n for blg in blgs:\n dsEQ = []\n for i in range(numEQ):\n temp = f.readline().strip('\\n').split()\n dsStory = [int(ds) for ds in temp[2:]]\n dsEQ.append(max(dsStory))\n ds = sorted(dsEQ)[int(numEQ * 0.84) - 1] # 各地震动84%保证率的破坏状态\n blg.result[pga][direction]['ds'] = ds\n except:\n print('读取结果失败')\n\n # 合并结果\n for blg in blgs:\n for pga in [0.2, 0.3, 0.4]:\n merge = {'loss': {}, 'ds': 0}\n resultx = blg.result[pga]['x']\n resulty = blg.result[pga]['y']\n merge['loss']['lossMedian'] = resultx['loss']['lossMedian'] + resulty['loss']['lossMedian']\n merge['loss']['lossP16'] = resultx['loss']['lossP16'] + resulty['loss']['lossP16']\n merge['loss']['lossP84'] = resultx['loss']['lossP84'] + resulty['loss']['lossP84']\n merge['loss']['downtimeMedian'] = max(resultx['loss']['downtimeMedian'], resulty['loss']['downtimeMedian'])\n merge['loss']['downtimeP16'] = max(resultx['loss']['downtimeP16'], resulty['loss']['downtimeP16'])\n merge['loss']['downtimeP84'] = max(resultx['loss']['downtimeP84'], resulty['loss']['downtimeP84'])\n merge['loss']['hurtMedian'] = max(resultx['loss']['hurtMedian'], resulty['loss']['hurtMedian'])\n merge['loss']['hurtP16'] = max(resultx['loss']['hurtP16'], resulty['loss']['hurtP16'])\n merge['loss']['hurtP84'] = max(resultx['loss']['hurtP84'], resulty['loss']['hurtP84'])\n merge['loss']['deathMedian'] = max(resultx['loss']['deathMedian'], resulty['loss']['deathMedian'])\n merge['loss']['deathP16'] = max(resultx['loss']['deathP16'], resulty['loss']['deathP16'])\n merge['loss']['deathP84'] = max(resultx['loss']['deathP84'], resulty['loss']['deathP84'])\n merge['ds'] = max(resultx['ds'], resulty['ds'])\n blg.result[pga]['merge'] = merge\n\n for pga in [0.2, 0.3, 0.4]:\n with open(resultDir + '/' + str(pga) + '/blg_result_merge_' + str(pga) + '.txt', 'w', encoding='utf-8') as f:\n f.write('ID\\t'\n 'lossMedian\\tlossP16\\tlossP84\\t'\n 'downtimeMedian\\tdowntimeP16\\tdowntimeP84\\t'\n 'hurtMedian\\thurtP16\\thurtP84\\t'\n 'deathMedian\\tdeathP16\\tdeathP84\\t'\n 'damageState\\n')\n for blg in blgs:\n f.write(str(blg.id))\n f.write('\\t')\n for key in blg.result[pga]['merge']['loss']:\n f.write(str(blg.result[pga]['merge']['loss'][key]))\n f.write('\\t')\n f.write(str(blg.result[pga]['merge']['ds']))\n f.write('\\n')\n\n # 韧性指标\n for pga in [0.2, 0.3, 0.4]:\n status = _cal_status(pga, blgs)\n with open(resultDir + '/' + str(pga) + '/blg2criteria_' + str(pga) + '.txt', 'w', encoding='utf-8') as f:\n for func in _FUNCTION:\n f.write(str(status[func]['level']))\n f.write('\\t')\n f.write(str(status[func]['downtime']))\n f.write('\\n')\n\n\ndef _cal_status(pga, blgs):\n status = {}\n for func in _FUNCTION:\n status[func] = {'total': 0,\n 'usable': 0,\n 'downtimes': [], }\n\n for blg in blgs:\n merge = blg.result[pga]['merge']\n status[blg.func]['total'] += 1\n if merge['ds'] in [0, 1, 2]:\n status[blg.func]['usable'] += 1\n status[blg.func]['downtimes'].append(merge['loss']['downtimeP84'])\n\n numBlg = 0\n for func in _FUNCTION:\n numBlg += status[func]['total']\n if status[func]['total'] != 0:\n status[func]['level'] = status[func]['usable'] / status[func]['total']\n else:\n status[func]['level'] = 1.0\n if status[func]['downtimes'] != []:\n status[func]['downtime'] = sorted(status[func]['downtimes'])[int(status[func]['total'] * 0.9) - 1]\n else:\n status[func]['downtime'] = 0.0\n if numBlg != len(blgs):\n print('建筑数量不对应!')\n\n return status\n\n\nif __name__ == '__main__':\n blgFuncPath = 'BlgFunction.txt'\n resultDir = '.'\n postprocess(blgFuncPath, resultDir)\n","sub_path":"building/script/blg_post_m.py","file_name":"blg_post_m.py","file_ext":"py","file_size_in_byte":6884,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"309649922","text":"from selenium import webdriver\nimport time\n\nclass DiscordBot:\n def __init__(self):\n self.message = str(input('Digite a mensagem: '))\n self.contact = str(input('Digite o contato: '))\n options = webdriver.ChromeOptions()\n options.add_argument('lang=pt-br')\n self.driver = webdriver.Chrome(executable_path=r'./chromedriver.exe')\n \n \n def SendMessage(self):\n #TIRAR MUSICA\n #
\n #\n self.driver.get('https://discord.com/channels/@me')\n # for group in self.groups:\n for group in self.contact:\n time.sleep(10)\n group = self.driver.find_element_by_xpath(f'
{self.contact}
')\n time.sleep(3)\n group.click()\n chat_box = self.driver.find_element_by_class_name('DuUXI')\n time.sleep(3)\n chat_box.click()\n n = 0\n while n < 10:\n chat_box.send_keys(self.message)\n send_button = self.driver.find_element_by_xpath(\n '//span[@data-icon=\"send\"]')\n time.sleep(3)\n send_button.click()\n time.sleep(3)\n n += 1\n\nbot = DiscordBot()\nbot.SendMessage()\n","sub_path":"discord-bot.py","file_name":"discord-bot.py","file_ext":"py","file_size_in_byte":1481,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"34818631","text":"# -*- coding: utf-8 -*-\n\nfile = \"data/test.txt\"\n\nf = open(file, 'r', encoding='utf8')\nprops = []\nlines = f.readlines()\npropset = set()\nfor l in lines:\n ls = l.strip().split(' ')\n int_ls = []\n for i in ls:\n int_ls.append(int(i))\n props.append(int_ls)\n for p in ls:\n propset.add(p)\n\n\ndef get_prop():\n print(propset)\n return props, len(propset)\n","sub_path":"Property_Embedding/trans/input_prop.py","file_name":"input_prop.py","file_ext":"py","file_size_in_byte":377,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"614554716","text":"import pygame as pg\npg.init()\nfrom GUI_elements import*\nimport clr, traceback\nfrom random import choice, randint\nfrom help import*\n\n##############################################################################################################################################################################################\n\nclass Grid():\n def __init__(self, size, x = 0, y = 0, col = clr.black):\n self.box_size = size//3\n self.size = size\n self.coord = (x, y)\n self.col = col\n i = j = 0\n self.boxlist = [[((i*self.box_size+x), (j*self.box_size+y)) for i in range(3)] for j in range(3)]\n self.rectlist = []\n self.box_used = [False for i in range(9)]\n self.flag = False\n for lst in self.boxlist:\n for point in lst:\n self.rectlist.append(pg.Rect(point, (self.box_size, self.box_size)))\n def show(self, screen):\n pg.draw.line(screen, self.col, self.boxlist[1][0], (self.boxlist[1][0][0]+self.size, self.boxlist[1][0][1]), 5)\n pg.draw.line(screen, self.col, self.boxlist[2][0], (self.boxlist[2][0][0]+self.size, self.boxlist[2][0][1]), 5)\n pg.draw.line(screen, self.col, self.boxlist[0][1], (self.boxlist[0][1][0], self.boxlist[0][1][1]+self.size), 5)\n pg.draw.line(screen, self.col, self.boxlist[0][2], (self.boxlist[0][2][0], self.boxlist[0][2][1]+self.size), 5)\n def get_click(self, turn, screen, screenCol):\n pos = pg.mouse.get_pos()\n for i in range(len(self.rectlist)):\n temp = self.rectlist[i].collidepoint(pos) and pg.mouse.get_pressed()[0]\n if temp and not self.flag and not self.box_used[i]:\n if turn%2 == 0:\n self.box_used[i] = 1\n else:\n self.box_used[i] = 2\n self.mark(i, turn, screen, screenCol)\n self.flag = True\n return True\n if self.flag and not temp:\n self.flag = False\n return False\n def mark(self, i, turn, screen, screenCol):\n #print(self.rectlist[i][0])\n #print(self.rectlist[i][1])\n surfsize = self.box_size//2\n surf = pg.Surface((surfsize, surfsize))\n surf.fill(screenCol)\n if self.box_used[i] == 1:\n pg.draw.line(surf, clr.red, (0, 0), (surfsize, surfsize), 5)\n pg.draw.line(surf, clr.red, (0, surfsize), (surfsize, 0), 5)\n elif self.box_used[i] == 2:\n r = surfsize//2\n pg.draw.circle(surf, clr.blue, (r, r), r, 5)\n #print(self.box_used)\n screen.blit(surf, ((self.rectlist[i][0] + surfsize//2), (self.rectlist[i][1] + surfsize//2)))\n\n\ndef ai(boxes, hardness):\n #winning\n for i in range(0, 9, 3):\n if boxes[i] == boxes[i + 1] == 2 and boxes[i + 2] == False:\n return i + 2\n if boxes[i] == boxes[i + 2] == 2 and boxes[i + 1] == False:\n return i + 1\n if boxes[i + 2] == boxes[i + 1] == 2 and boxes[i] == False:\n return i\n \n for i in range(3):\n if boxes[i] == boxes[i + 3] == 2 and boxes[i + 6] == False:\n return i + 6\n if boxes[i] == boxes[i + 6] == 2 and boxes[i + 3] == False:\n return i + 3\n if boxes[i + 6] == boxes[i + 3] == 2 and boxes[i] == False:\n return i\n \n if boxes[0] == boxes[4] == 2 and boxes[8] == False:\n return 8\n if boxes[0] == boxes[8] == 2 and boxes[4] == False:\n return 4\n if boxes[4] == boxes[8] == 2 and boxes[0] == False:\n return 0\n\n if boxes[2] == boxes[4] == 2 and boxes[6] == False:\n return 6\n if boxes[2] == boxes[6] == 2 and boxes[4] == False:\n return 4\n if boxes[4] == boxes[6] == 2 and boxes[2] == False:\n return 2\n\n #preventing player from winning\n for i in range(0, 9, 3):\n if boxes[i] == boxes[i + 1] == 1 and boxes[i + 2] == False:\n return i + 2\n if boxes[i] == boxes[i + 2] == 1 and boxes[i + 1] == False:\n return i + 1\n if boxes[i + 2] == boxes[i + 1] == 1 and boxes[i] == False:\n return i\n \n for i in range(3):\n if boxes[i] == boxes[i + 3] == 1 and boxes[i + 6] == False:\n return i + 6\n if boxes[i] == boxes[i + 6] == 1 and boxes[i + 3] == False:\n return i + 3\n if boxes[i + 6] == boxes[i + 3] == 1 and boxes[i] == False:\n return i\n \n if boxes[0] == boxes[4] == 1 and boxes[8] == False:\n return 8\n if boxes[0] == boxes[8] == 1 and boxes[4] == False:\n return 4\n if boxes[4] == boxes[8] == 1 and boxes[0] == False:\n return 0\n \n if boxes[2] == boxes[4] == 1 and boxes[6] == False:\n return 6\n if boxes[2] == boxes[6] == 1 and boxes[4] == False:\n return 4\n if boxes[4] == boxes[6] == 1 and boxes[2] == False:\n return 2\n \n edge_list = []\n corner_list = []\n\n if boxes[4] == False:\n return 4\n\n for i in range(1, 8, 2):\n if boxes[i] == False:\n edge_list.append(i)\n for i in [0, 2, 6, 8]:\n if boxes[i] == False:\n corner_list.append(i)\n\n rand = randint(0, 99)\n rand %= 2\n\n if (hardness == 2 and rand == 1) or hardness == 3:\n if ((boxes[1] == boxes[6] == 1) or (boxes[2] == boxes[3] == 1)) and boxes[0] == False:\n return 0\n if ((boxes[0] == boxes[5] == 1) or (boxes[1] == boxes[8] == 1)) and boxes[2] == False:\n return 2\n if ((boxes[0] == boxes[7] == 1) or (boxes[5] == boxes[8] == 1)) and boxes[6] == False:\n return 6\n if ((boxes[2] == boxes[7] == 1) or (boxes[5] == boxes[6] == 1)) and boxes[8] == False:\n return 8\n\n if (hardness == 2 and rand == 0) or hardness == 3:\n if (boxes[1] == boxes[3] == 1) and boxes[0] == False:\n return 0\n if (boxes[1] == boxes[5] == 1) and boxes[2] == False:\n return 2\n if (boxes[3] == boxes[7] == 1) and boxes[6] == False:\n return 6\n if (boxes[5] == boxes[7] == 1) and boxes[8] == False:\n return 8\n\n if boxes[4] != 1:\n if len(edge_list):\n return choice(edge_list)\n if len(corner_list):\n return choice(corner_list)\n else:\n if len(corner_list):\n return choice(corner_list)\n if len(edge_list):\n return choice(edge_list)\n\n \ndef new(grid, screen, screenCol, turn):\n for i in range(len(grid.box_used)):\n grid.box_used[i] = False\n screen.fill(screenCol)\n grid.show(screen)\n turn = 0\n return turn\n\ndef mainLoop(screenCol, textCol, prev_screen, rect_pos):\n start = True\n pg.display.set_caption('Tic-Tac-Toe')\n screenWd, screenHt = 1120, 630\n screen = pg.display.set_mode((screenWd, screenHt))\n clock = pg.time.Clock()\n FPS = 25\n turn = 0\n current_mode = 1\n difficulty = 2\n won = False\n screenCenter = (screenWd//2, screenHt//2)\n grid = Grid(screenHt, 245, col = textCol)\n exit_button = Button(1050, 600, 50, 30, \"Exit\", textHeight = 30, textColour = textCol, opaque = False)\n new_button = Button(1000, 300, 50, 30, \"New Game\", textHeight = 30, textColour = textCol, opaque = False)\n butt_mode = Button(1075, 15, 20, 20)\n butt_mainMenu = Button(940, 600, 100, 30, \"Main Menu\", textHeight = 30, textColour = textCol, opaque = False)\n play2_butt = Button(50, 200, 150, 100, \"2 player\", textColour = textCol)\n play1_butt = Button(50, 400, 150, 100, \"1 player\", textColour = textCol)\n easy = Button(60, 550, 40, 40, 'easy', textHeight = 15, textColour = textCol, value = 1, enabled_selected = True, outline = True)\n medium = Button(110, 550, 40, 40, 'medium', textHeight = 15, textColour = textCol, value = 2, enabled_selected = True, outline = True)\n hard = Button(160, 550, 40, 40, 'hard', textHeight = 15, textColour = textCol, value = 3, enabled_selected = True, outline = True)\n\n diff_list = [easy, medium, hard]\n #print(grid.boxlist)\n #print(grid.rectlist)i]\n \n screen.fill(screenCol)\n grid.show(screen)\n\n key_check = [pg.K_1, pg.K_2, pg.K_3, pg.K_4, pg.K_5, pg.K_6, pg.K_7, pg.K_8, pg.K_9]\n \n while True:\n for event in pg.event.get():\n if event.type == pg.QUIT:\n Quit(screen)\n if event.type == pg.KEYDOWN:\n if event.key == pg.K_ESCAPE:\n fade(screen, True, col = screenCol)\n return screenCol, textCol\n if event.key == pg.K_n:\n turn = new(grid, screen, screenCol, turn)\n won = False\n elif event.key == pg.K_m:\n if screenCol == clr.black:\n textCol = clr.black\n screenCol = clr.white\n else:\n textCol = clr.white\n screenCol = clr.black\n exit_button.textColour = textCol\n new_button.textColour = textCol\n butt_mainMenu.textColour = textCol\n grid.col = textCol\n elif event.key == pg.K_h:\n fade(screen, True, col = screenCol)\n help_screen(TICTACTOE, screenCol, textCol)\n elif won == False:\n for i in range(len(key_check)):\n if event.key == key_check[i] and grid.box_used[i] == False:\n grid.mark(i, turn, screen, screenCol)\n if turn%2 == 0:\n grid.box_used[i] = 1\n else:\n grid.box_used[i] = 2\n turn += 1\n\n\n if exit_button.get_click():\n Quit(screen)\n if new_button.get_click():\n turn = new(grid, screen, screenCol, turn)\n won = False\n elif won == False and grid.get_click(turn, screen, screenCol):\n turn += 1\n elif butt_mode.get_click():\n if screenCol == clr.black:\n textCol = clr.black\n screenCol = clr.white\n else:\n textCol = clr.white\n screenCol = clr.black\n exit_button.textColour = textCol\n new_button.textColour = textCol\n butt_mainMenu.textColour = textCol\n grid.col = textCol\n elif butt_mainMenu.get_click():\n fade(screen, True, col = screenCol)\n return screenCol, textCol\n elif play2_butt.get_click() and current_mode == 1:\n turn = new(grid, screen, screenCol, turn)\n current_mode = 2\n won = False\n elif play1_butt.get_click() and current_mode == 2:\n turn = new(grid, screen, screenCol, turn)\n current_mode = 1\n won = False\n\n screen.fill(screenCol)\n grid.show(screen)\n\n for i in range(len(grid.box_used)):\n if grid.box_used[i]:\n grid.mark(i, turn, screen, screenCol)\n\n if ((grid.box_used[0] == grid.box_used[1] == grid.box_used[2] == 1) or (grid.box_used[3] == grid.box_used[4] == grid.box_used[5] == 1)\n or (grid.box_used[6] == grid.box_used[7] == grid.box_used[8] == 1) or (grid.box_used[0] == grid.box_used[4] == grid.box_used[8] == 1)\n or (grid.box_used[2] == grid.box_used[4] == grid.box_used[6] == 1) or (grid.box_used[0] == grid.box_used[3] == grid.box_used[6] == 1)\n or (grid.box_used[1] == grid.box_used[4] == grid.box_used[7] == 1) or (grid.box_used[2] == grid.box_used[5] == grid.box_used[8] == 1)):\n text(screen, 0, 0, 80, 'Player 1 Wins!', textCol, screenCenter)\n won = True\n #print(won)\n if ((grid.box_used[0] == grid.box_used[1] == grid.box_used[2] == 2) or (grid.box_used[3] == grid.box_used[4] == grid.box_used[5] == 2)\n or (grid.box_used[6] == grid.box_used[7] == grid.box_used[8] == 2) or (grid.box_used[0] == grid.box_used[4] == grid.box_used[8] == 2)\n or (grid.box_used[2] == grid.box_used[4] == grid.box_used[6] == 2) or (grid.box_used[0] == grid.box_used[3] == grid.box_used[6] == 2)\n or (grid.box_used[1] == grid.box_used[4] == grid.box_used[7] == 2) or (grid.box_used[2] == grid.box_used[5] == grid.box_used[8] == 2)):\n text(screen, 0, 0, 80, 'Player 2 Wins!', textCol, screenCenter)\n won = True\n #print(won)\n\n text(screen, 100, 340, 20, (str(current_mode)+\" Player\"), textCol)\n\n if turn%2 == 1 and current_mode == 1 and turn <=7 and won == False:\n move = ai(grid.box_used, difficulty)\n grid.mark(move, turn, screen, screenCol)\n grid.box_used[move] = 2\n turn += 1\n\n if current_mode == 1:\n for diff in diff_list:\n diff.show(screen)\n if diff.value == difficulty:\n diff.selected = True\n else:\n diff.selected = False\n if diff.get_click():\n turn = new(grid, screen, screenCol, turn)\n difficulty = diff.value\n\n if screenCol == clr.black:\n sun(screen)\n else:\n moon(screen)\n \n if turn >= 9 and won == False:\n text(screen, 0, 0, 80, 'draw', textCol, screenCenter)\n exit_button.show(screen)\n new_button.show(screen)\n butt_mainMenu.show(screen)\n play2_butt.show(screen)\n play1_butt.show(screen)\n \n if start:\n expand(screen, screen.copy(), [rect_pos[0], rect_pos[1]+90, 200, 113], prev_screen)\n start = False\n else:\n pg.display.update()\n \n clock.tick(FPS)\n\n\n##try:\n## mainLoop(clr.white, clr.black)\n##except:\n## traceback.print_exc()\n##finally:\n## pg.quit()\n \n \n","sub_path":"modules/tictactoe.py","file_name":"tictactoe.py","file_ext":"py","file_size_in_byte":13887,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"143118832","text":"\"\"\"\n A Sample program to get you started\n Laney Colleg Fall 2014\n Written by KaChiLau \"\"\"\n\"\"\"\n\ny is given as 3 times x squared, plus 6 times x,plus 9.\nWhat is the value of y when x equals 333?\n\nA Quadratic Formula: y = ax^2 + bx + c\n\n y = 3x^2 + 6x + 9\n\nCalculate y in python and paste the experssion and the answer in the notes.\"\"\"\n\n\"\"\"x = int(input(\"Please input the x: \"))\"\"\"\n\nx = 333\n\n\"\"\" print(\"y = \", 3 * x ** 2 + 6 * x + 9)\"\"\"\n\npoly1 = x ** 2\n\nprint(\"y = \", 3 * poly1 + 6 * x + 9)\n\n\n\"\"\"\n>>> ================================ RESTART ================================\n>>> \ny = 334674\n>>> \n\"\"\"\n","sub_path":"CIS 61 python/Labs/Section 1/1/1-1-A Quadratic Expression.py","file_name":"1-1-A Quadratic Expression.py","file_ext":"py","file_size_in_byte":634,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"551140523","text":"import Pyro4\nimport string\nimport settings\nfrom lib import Error\nfrom lib.Function import *\n\nclass AiScheduler(object):\n daemon = Pyro4.Daemon(settings.hostName)\n ns = Pyro4.locateNS(settings.nameServer,settings.nameServerPort)\n def getExecutorName(self):\n aiList = self.ns.list().keys()\n aiList = list(filter (lambda a: a.find('aiExecutor')!=-1, aiList))\n for each in aiList:\n print(\"Try: \"+each)\n uri = self.ns.lookup(each)\n aiExecutor = Pyro4.Proxy(uri)\n try:\n if not aiExecutor.busy():\n print(\"Get: \",each)\n return each\n except Pyro4.errors.PyroError:\n self.ns.remove(each)\n raise Error.NoAiExecutorError()\n\nif __name__=='__main__':\n aiScheduler = AiScheduler()\n uri = aiScheduler.daemon.register(aiScheduler)\n autoReregister('ai9.aiScheduler',uri,settings.nameServer,settings.nameServerPort)\n\n aiScheduler.daemon.requestLoop()\n\n","sub_path":"Platform/AiScheduler/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1009,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"637787625","text":"import json\nfrom time import sleep\nimport io\nfrom newspaper import Article\nfrom newspaper.article import ArticleException, ArticleDownloadState\n\n\ndef read_file(path):\n \"\"\"\n :param path: the path of the file containing the urls\n :return: list of the urls to be scraped\n \"\"\"\n url_list = []\n category_list = []\n for line in open(path, 'r'):\n json_entry = (json.loads(line))\n url_list.append(json_entry['link'])\n category_list.append(json_entry['category'])\n\n return category_list, url_list\n\n\ndef scrape_url(category_list, url_list):\n \"\"\"\n :param url_list: list of urls to scrape from the web\n :return: nothing, just create a text file containing article text of each url\n \"\"\"\n\n for i in range(0, len(url_list)):\n article_huff = Article(url_list[i]) # iterate through each article link\n slept = 0\n article_huff.download()\n while article_huff.download_state == ArticleDownloadState.NOT_STARTED:\n # Raise exception if article download state does not change after 12 seconds\n if slept > 13:\n raise ArticleException('Download never started')\n sleep(1)\n slept += 1\n\n article_huff.parse()\n article_info_huff = {\"category\": category_list[i], \"title\": article_huff.title, \"text\": article_huff.text}\n file_name = \"../huffpostarticles/huffpost\" + str(i) + \".json\"\n with io.open(file_name, \"w\", encoding=\"utf-8\") as f:\n f.write(json.dumps(article_info_huff))\n\n\ndef __main__():\n category_list, urls = read_file(\"../huffpost/News_Category_Dataset_v2.json\")\n scrape_url(category_list, urls)\n\n\n__main__()\n\n\n# We can write each of the following properties if required for classification or summarization\n# article_info_huff = {'title': article_huff.title,\n# 'description': article_huff.meta_description,\n# 'text': article_huff.text,\n# 'publisher': 'huff'}\n","sub_path":"util/scraper.py","file_name":"scraper.py","file_ext":"py","file_size_in_byte":1984,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"460164168","text":"#!/usr/bin/env python3\n\n\n\n###### Your paths go here\nfrom doTNR import *\n\n# mainTNR\n# ------------------------\n# by Glen Evenbly\n#\n# Script file for initializing a partition function (here the classical\n# Ising model) before passing to a Tensor Network Renormalization (TNR)\n# coarse-graining routine. The magnetization, free energy and internal\n# energy are then computed and compared against the exact results. Produces\n# a binary MERA defined from disentanglers 'upC' and isometries 'wC' for\n# the ground state of the transverse field quantum Ising model.\n\n##### Set bond dimensions and options\nchiM = 6\nchiS = 4\nchiU = 4\nchiH = 6\nchiV = 6\n\nallchi = [chiM,chiS,chiU,chiH,chiV]\n\nrelTemp = 0.995 # temp relative to the crit temp, in [0,inf]\nnumlevels = 12 # number of coarse-grainings\n\nO_dtol = 1e-10\nO_disiter = 2000\nO_miniter = 200\nO_dispon = True\nO_convtol = 0.01\nO_disweight = 0\n\nprint('relTemp=',relTemp)\n\n###### Define partition function (classical Ising)\nTc = (2/np.log(1+np.sqrt(2)))\nTval = relTemp*Tc\nbetaval = 1./Tval\nJtemp = np.zeros((2,2,2))\nJtemp[0,0,0]=1\nJtemp[1,1,1]=1\nEtemp = np.array([[np.exp(betaval), np.exp(-betaval)], [np.exp(-betaval),np.exp(betaval)]])\n\nAinit = np.einsum(Jtemp,[21,8,1],Jtemp,[22,2,3],Jtemp,[23,4,5],Jtemp,[24,6,7],Etemp,[1,2],Etemp,[3,4],Etemp,[5,6],Etemp,[7,8])\nXloc = (1/np.sqrt(2))*np.array([[1,1],[1,-1]])\nAinit = np.einsum(Ainit,[1,2,3,4],Xloc,[1,21],Xloc,[2,22],Xloc,[3,23],Xloc,[4,24])\nAtemp = np.einsum(Ainit,[12,13,3,1],Ainit,[3,14,15,2],Ainit,[11,1,4,18],Ainit,[4,2,16,17]).reshape(4,4,4,4)\nAnorm = [0]*(numlevels+1)\nAnorm[0]=np.linalg.norm(Atemp)\nA = [np.nan]*(numlevels+1)\nA[0]=Atemp/Anorm[0]\n\nSPerrs = [0]*numlevels\nqC = [np.nan]*numlevels\nsC = [np.nan]*numlevels\nuC = [np.nan]*numlevels\nyC = [np.nan]*numlevels\nvC = [np.nan]*numlevels\nwC = [np.nan]*numlevels\n\n###### Do iterations of TNR\nfor k in range(numlevels):\n A[k+1], qC[k], sC[k], uC[k], yC[k], vC[k], wC[k], Anorm[k+1], SPerrs[k] = doTNR(A[k], [chiM,chiS,chiU,chiH,chiV], dtol = O_dtol, disiter = O_disiter, miniter = O_miniter, dispon = O_dispon, convtol = O_convtol)\n\n print(\"RGstep: %d , Truncation Errors: %.6g, %.6g, %.6g, %.6g\"%(k,*SPerrs[k]))\n\n##### Change gauge on disentanglers 'u'\ngaugeX = np.eye(4).reshape(2,2,2,2).transpose(1,0,2,3).reshape(4,4)\nupC = [np.nan]*numlevels\nupC[0]=np.einsum(uC[0],[21,1,23,24],gaugeX,[1,22])\n\nfor k in range(1,numlevels):\n U, S, Vh = np.linalg.svd(np.einsum(wC[k-1],[1,2,21],wC[k-1],[2,1,22]))\n gaugeX = U@Vh\n upC[k]=np.einsum(uC[k],[21,1,23,24],gaugeX,[1,22])\n\n##### Magnetization\nsXcg = ((1/4)*(np.kron(np.eye(8),sX) + np.kron(np.eye(4),np.kron(sX,np.eye(2))) + np.kron(np.eye(2),np.kron(sX,np.eye(4))) + np.kron(sX,np.eye(8)))).reshape(4,4,4,4)\nfor k in range(numlevels):\n sXcg = np.einsum(sXcg,[3,4,1,2],upC[k],[1,2,6,9],upC[k],[3,4,7,10],wC[k],[5,6,21],wC[k],[9,8,22],wC[k],[5,7,23],wC[k],[10,8,24])\nw,v = np.linalg.eigh(sXcg.reshape(sXcg.shape[0]**2,sXcg.shape[2]**2))\nExpectX = np.max(w)\n\nprint(\"Magnetization: \",ExpectX)\n\nprint(\"##############################################\")\n# sXcg = reshape((1/4)*(kron(eye(8),sX) + kron(eye(4),kron(sX,eye(2))) +\n# kron(eye(2),kron(sX,eye(4))) + kron(sX,eye(8))),4,4,4,4);\n# for k = 1:numlevels\n# sXcg = ncon(Any[sXcg,upC[k],upC[k],wC[k],wC[k],wC[k],wC[k]],\n# Any[[3,4,1,2],[1,2,6,9],[3,4,7,10],[5,6,-1],[9,8,-2],[5,7,-3],[10,8,-4]]);\n# end\n# F = eigfact(reshape(sXcg,size(sXcg,1)^2,size(sXcg,3)^2));\n# ExpectX = maximum(F[:values]); # magnetization\n\n","sub_path":"mainTNR.py","file_name":"mainTNR.py","file_ext":"py","file_size_in_byte":3489,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"637385888","text":"'''\nex06_insert.py\n\n사용자가 입력을 받아서 데이터 베이스에 insert\n'''\n\nimport cx_Oracle\nimport lec08_database.oracle_config as cfg\n\nwith cx_Oracle.connect(cfg.user, cfg.pwd, cfg.dsn) as connection:\n with connection.cursor() as cursor :\n deptno = int(input('부서번호 입력>> '))\n dname = input('부서 이름 입력>> ')\n loc = input('부서 위치 입력>> ')\n\n sql_insert = f\"insert into dept2 values({deptno}, '{dname}', '{loc}')\"\n # 사용자가 입력한 문자열에 따옴표(')가 포함되어 있는 경우\n # SQL 에러가 발생할 수 있음. 권장하지 않는 방법.\n # -> data binding 방법을 권장.\n cursor.execute(sql_insert)\n connection.commit","sub_path":"lec08_database/ex06_insert.py","file_name":"ex06_insert.py","file_ext":"py","file_size_in_byte":753,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"106211953","text":"\"\"\"\nbatchAnalysis.py \n\nCode to anlayse batch sim results\n\nContributors: salvadordura@gmail.com\n\"\"\"\n\nimport utils\nimport json, pickle\nimport numpy as np\nfrom matplotlib import pyplot as plt\nimport pandas as pd\nimport seaborn as sb\nimport os\nfrom batchAnalysisPlotCombined import dfPopRates\nimport IPython as ipy\nplt.style.use('seaborn-whitegrid')\n\n# ---------------------------------------------------------------------------------\n# Support funcs\n# ---------------------------------------------------------------------------------\n\ndef filterRates(df, condlist=['rates', 'I>E', 'E5>E6>E2', 'PV>SOM'], copyFolder=None, dataFolder=None, batchLabel=None, skipDepol=True):\n from os.path import isfile, join\n from glob import glob\n\n rangesE = {}\n rangesI = {}\n\n Erange = [0.01,200]\n Epops = ['IT2', 'IT3', 'ITP4', 'ITS4', 'IT5A', 'CT5A', 'IT5B', 'CT5B', 'PT5B', 'IT6','CT6'] # , 'IT5A', 'CT5A', 'IT5B', 'CT5B', 'PT5B', 'IT6', 'CT6'] # all layers\n#'ITS4',\n for pop in Epops:\n rangesE[pop] = Erange\n\n Irange = [0.01,200]\n #Ipops = ['PV2']\n\n Ipops = ['NGF1', # L1\n 'PV2', 'SOM2', 'VIP2', 'NGF2', # L2\n 'PV3', 'SOM3', 'VIP3', 'NGF3', # L3\n 'PV4', 'SOM4', 'VIP4', 'NGF4', # L4\n 'PV5A', 'SOM5A', 'VIP5A', 'NGF5A', # L5A \n 'PV5B', 'SOM5B', 'VIP5B', 'NGF5B', # L5B\n 'PV6', 'SOM6', 'VIP6', 'NGF6'] # L6 \n\n for pop in Ipops:\n rangesI[pop] = Irange\n\n conds = []\n\n # check pop rate ranges\n if 'rates' in condlist:\n for k,v in rangesE.items(): conds.append(str(v[0]) + '<=' + k + '<=' + str(v[1]))\n \n # check I > E in each layer\n if 'I>E' in condlist:\n conds.append('PV2 > IT2 and SOM2 > IT2')\n conds.append('PV5A > IT5A and SOM5A > IT5A')\n conds.append('PV5B > IT5B and SOM5B > IT5B')\n conds.append('PV6 > IT6 and SOM6 > IT6')\n\n # check E L5 > L6 > L2\n if 'E5>E6>E2' in condlist:\n #conds.append('(IT5A+IT5B+PT5B)/3 > (IT6+CT6)/2 > IT2')\n conds.append('(IT5A+IT5B+PT5B)/3 > (IT6+CT6)/2')\n conds.append('(IT6+CT6)/2 > IT2')\n conds.append('(IT5A+IT5B+PT5B)/3 > IT2')\n \n # check PV > SOM in each layer\n if 'PV>SOM' in condlist:\n conds.append('PV2 > IT2')\n conds.append('PV5A > SOM5A')\n conds.append('PV5B > SOM5B')\n conds.append('PV6 > SOM6')\n\n # construct query and apply\n condStr = ''.join([''.join(str(cond) + ' and ') for cond in conds])[:-4]\n \n\n #import IPython; IPython.embed()\n\n dfcond = df.query(condStr)\n\n conds = []\n if 'rates' in condlist:\n for k, v in rangesI.items(): conds.append(str(v[0]) + '<=' + k + '<=' + str(v[1]))\n condStr = ''.join([''.join(str(cond) + ' and ') for cond in conds])[:-4]\n\n dfcond = dfcond.query(condStr)\n \n print('\\n Filtering based on: ' + str(condlist) + '\\n' + condStr)\n print(dfcond)\n print(len(dfcond))\n\n\n\n # \n if copyFolder:\n targetFolder = dataFolder+batchLabel+'/'+copyFolder\n try: \n os.mkdir(targetFolder)\n except:\n pass\n \n for i,row in dfcond.iterrows(): \n if skipDepol:\n sourceFile1 = dataFolder+batchLabel+'/noDepol/'+batchLabel+row['simLabel']+'*.png' \n else:\n sourceFile1 = dataFolder+batchLabel+'/'+batchLabel+row['simLabel']+'*.png' \n #sourceFile2 = dataFolder+batchLabel+'/'+batchLabel+row['simLabel']+'.json'\n if len(glob(sourceFile1))>0:\n cpcmd = 'cp ' + sourceFile1 + ' ' + targetFolder + '/.'\n #cpcmd = cpcmd + '; cp ' + sourceFile2 + ' ' + targetFolder + '/.'\n os.system(cpcmd) \n print(cpcmd)\n\n\n return dfcond\n\ndef detectDepolBlock(volt, minSamples=200, vRange=[-50, -10]):\n cumm = 0\n for v in volt:\n if v >= vRange[0] and v<= vRange[1]:\n cumm += 1\n if cumm > minSamples:\n return 1\n else:\n cumm = 0\n\n return 0 \n\n\n# ---------------------------------------------------------------------------------\n# Wrapper funcs\n# ---------------------------------------------------------------------------------\n \n\ndef applyFilterRates(dataFolder, batchLabel, loadAll, skipDepol=True):\n # load data \n var = [('simData','popRates')]\n params, data = utils.readBatchData(dataFolder, batchLabel, loadAll=loadAll, saveAll=1-loadAll, vars=var, maxCombs=None)\n \n #pipy.embed()\n\n # convert to pandas and add pop Rates\n df1 = utils.toPandas(params, data)\n dfpop = dfPopRates(df1)\n\n # filter based on pop rates\n condLists = [['rates']]#,\n # ['rates','I>E'],\n # ['rates', 'E5>E6>E2'],\n # ['rates', 'PV>SOM']]\n\n # [['I>E', 'E5>E6>E2', 'PV>SOM'],\n # ['I>E'],\n # ['E5>E6>E2'],\n # ['PV>SOM'],\n # ['rates']]\n # ['E5>E6>E2'],\n # ['PV>SOM']]\n\n\n for i,condList in enumerate(condLists):\n print(len(filterRates(dfpop, condlist=condList, copyFolder='selected_'+str(i), dataFolder=dataFolder, batchLabel=batchLabel, skipDepol=skipDepol)))\n \n return dfpop\n\n\ndef filterStimRates(dataFolder, batchLabel, simLabel=None, load=False, subset=''):\n from os import listdir\n from os.path import isfile, join\n\n # from mpi4py import MPI\n # comm = MPI.COMM_WORLD\n # rank = comm.Get_rank()\n # mode = MPI.MODE_CREATE | MPI.MODE_WRONLY \n\n ihlevels = [0,1,2]\n ihmax = 3\n\n for ihlevel in ihlevels:\n jsonFolder = batchLabel \n path = dataFolder+batchLabel #+'/noDepol'\n #onlyFiles = [f for f in listdir(path) if isfile(join(path, f)) and not f.endswith('batch.json') and not f.endswith('cfg.json')]\n onlyFiles = [f.replace('_raster.png', '.json') for f in listdir(path) if isfile(join(path, f)) and f.endswith('raster.png')]\n\n if type(simLabel) is list:\n outfiles = [f for f in onlyFiles if f in simLabel] #any([f.endswith(sl+'.json') for sl in simLabel])] \n elif type(simLabel) is '':\n outfiles = [f for f in onlyFiles if f.endswith(simLabel+'.json')]\n else:\n outfiles = [f for f in onlyFiles if f.endswith('_%d.json'%(ihlevel))] \n\n include = {}\n include['rates'] = ['IT5A', 'PT5B', 'IT2']\n\n targetFolder = dataFolder+batchLabel+'/stimRates'\n try: \n os.mkdir(targetFolder)\n except:\n pass\n\n if load:\n filename = dataFolder+jsonFolder+'/'+'stimRatesData'+subset+'%d.json'%(ihlevel)\n with open(filename, 'r') as fileObj: loadData = json.load(fileObj)\n\n with open('../sim/cells/popColors.pkl', 'r') as fileObj: popColors = pickle.load(fileObj)['popColors']\n saveData = []\n counter=0\n copied = 0\n for ifile, outfile in enumerate(outfiles):\n if 1: #rank == ifile: \n try: \n filename = dataFolder+jsonFolder+'/'+outfile\n #print filename \n\n if load:\n filename = filename.replace('_%d.json'%(ihlevel), '_%d.json'%(ihmax))\n found=0\n for d in loadData:\n if str(d[0]) == str(filename):\n filename, avgsPT5Bzd, peaksPT5Bzd, avgsPT5Bih, peaksPT5Bih, avgsIT5Azd, peaksIT5Azd, avgsIT5Aih, peaksIT5Aih, \\\n avgsIT2zd, peaksIT2zd, avgsIT2ih, peaksIT2ih = d\n found=1\n counter=counter+1\n if not found: continue\n\n else:\n sim,data,out=utils.plotsFromFile(filename, raster=0, stats=0, rates=1, syncs=0, hist=0, psd=0, traces=0, grang=0, plotAll=0, \n timeRange=[500,1500], include=include, textTop='', popColors=popColors, orderBy='gid')\n\n avgsIT5Azd, avgsPT5Bzd, avgsIT2zd = [out[2][0][0],out[2][1][0]], [out[2][0][1],out[2][1][1]], [out[2][0][2],out[2][1][2]]\n peaksIT5Azd, peaksPT5Bzd, peaksIT2zd = [out[3][0][0],out[3][1][0]], [out[3][0][1],out[3][1][1]], [out[3][0][2],out[3][1][2]]\n\n # ih = 1.0 (ends with 1)\n filename = dataFolder+jsonFolder+'/'+outfile.replace('_%d.json'%(ihlevel), '_%d.json'%(ihmax))\n print(filename) \n\n sim,data,out=utils.plotsFromFile(filename, raster=0, stats=0, rates=1, syncs=0, hist=0, psd=0, traces=0, grang=0, plotAll=0, \n timeRange=[500,1500], include=include, textTop='', popColors=popColors, orderBy='gid')\n\n avgsIT5Aih, avgsPT5Bih, avgsIT2ih = [out[2][0][0],out[2][1][0]], [out[2][0][1],out[2][1][1]], [out[2][0][2],out[2][1][2]]\n peaksIT5Aih, peaksPT5Bih, peaksIT2ih = [out[3][0][0],out[3][1][0]], [out[3][0][1],out[3][1][1]], [out[3][0][2],out[3][1][2]]\n\n saveData.append([filename, avgsPT5Bzd, peaksPT5Bzd, avgsPT5Bih, peaksPT5Bih, avgsIT5Azd, peaksIT5Azd, avgsIT5Aih, peaksIT5Aih, \n avgsIT2zd, peaksIT2zd, avgsIT2ih, peaksIT2ih])\n\n # conditions to select \n avgsPT5BzdInc = (avgsPT5Bzd[1] - avgsPT5Bzd[0]) / avgsPT5Bzd[0] if avgsPT5Bzd[0]>0 else 0 # % inc\n avgsPT5BihInc = (avgsPT5Bih[1] - avgsPT5Bih[0]) / avgsPT5Bih[0] if avgsPT5Bih[0]>0 else 0# % inc\n\n peaksPT5BzdInc = (peaksPT5Bzd[1] - peaksPT5Bzd[0]) / peaksPT5Bzd[0] if peaksPT5Bzd[0]>0 else 0# % inc\n peaksPT5BihInc = (peaksPT5Bih[1] - peaksPT5Bih[0]) / peaksPT5Bih[0] if peaksPT5Bih[0]>0 else 0 #% inc\n\n\n # peaks PT5B\n if (peaksPT5Bzd[1] > 1.0*peaksPT5Bih[1] and\n # peaksPT5BzdInc > 1.0*peaksPT5BihInc and\n peaksPT5BzdInc > 0 and\n \n # peaks IT2\n # peaksIT2zd[0] < 250.0 and\n # peaksIT2ih[0] < 250 and\n # peaksIT2zd[1] < 250.0 and\n # peaksIT2ih[1] < 250 and\n abs(peaksPT5BihInc) < 1.5 and \n\n #avgs PT5B\n avgsPT5Bzd[1] > 1.0*avgsPT5Bih[1] and # 1.5\n # avgsPT5BzdInc > 1.0*avgsPT5BihInc and # 1.25\n avgsPT5BzdInc > 0 and \n avgsPT5Bih[0] > 0. and\n # abs(avgsPT5BihInc) < 1.5 and\n \n # avgs IT2\n avgsIT2zd[0] > 0.05 and\n avgsIT2ih[0] > 0.05 and\n avgsIT2zd[1] > 0.05 and\n avgsIT2ih[1] > 0.05): #and\n\n copied += 1\n # print avgsPT5Bzd, avgsPT5BzdInc\n # print peaksPT5Bzd, peaksPT5BzdInc\n\n # print avgsPT5Bih, avgsPT5BihInc\n # print peaksPT5Bih, peaksPT5BihInc\n\n sourceFiles = []\n sourceFiles.append(filename)\n sourceFiles.append(filename.split('.json')[0]+'_raster.png')\n sourceFiles.append(filename.split('.json')[0]+'_spikeHist.png')\n sourceFiles.append(filename.split('.json')[0]+'_avgRates.png')\n sourceFiles.append(filename.split('.json')[0]+'_peakRates.png')\n filename2 = filename.replace('_%d.json'%(ihmax), '_%d.json'%(ihlevel))\n sourceFiles.append(filename2)\n sourceFiles.append(filename2.split('.json')[0]+'_raster.png')\n sourceFiles.append(filename2.split('.json')[0]+'_spikeHist.png')\n sourceFiles.append(filename2.split('.json')[0]+'_avgRates.png')\n sourceFiles.append(filename2.split('.json')[0]+'_peakRates.png')\n\n for sf in sourceFiles:\n cpcmd = 'cp ' + sf + ' ' + targetFolder + '/.'\n try:\n os.system(cpcmd) \n #print cpcmd\n except:\n pass\n else: \n pass\n #print 'not copied'\n\n if not load:\n filename = dataFolder+jsonFolder+'/'+'stimRatesData'+subset+'%d.json'%(ihlevel)\n with open(filename, 'w') as fileObj: json.dump(saveData, fileObj)\n\n # filename2 = dataFolder+jsonFolder+'/'+'stimRatesData_mpi'+subset+'.json'\n # fh = MPI.File.Open(comm, filename2, mode) \n # line1 = str(saveData) + '\\n' \n # fh.Write_ordered(line1) \n # fh.Close() \n\n except:\n pass\n\n print('Total: ', counter)\n print('Copied: ', copied)\n\n\ndef filterDepolBlock(dataFolder, batchLabel, loadAll, gids=None): \n if gids: # e.g. gids = [3136, 5198])\n var = [('simData')]\n params, data = utils.readBatchData(dataFolder, batchLabel, loadAll=loadAll, saveAll=1-loadAll, vars=var, maxCombs=None)\n df = utils.toPandas(params, data)\n\n copyFolder = 'noDepol'\n targetFolder = dataFolder+batchLabel+'/'+copyFolder\n try: \n os.mkdir(targetFolder)\n except:\n pass\n \n for i,row in df.iterrows():\n block = False\n for gid in gids:\n if detectDepolBlock(row.V_soma['cell_'+str(gid)]): block = True\n\n if not block:\n sourceFile1 = dataFolder+batchLabel+'/'+batchLabel+row['simLabel']+'_*.png'\n #sourceFile2 = dataFolder+batchLabel+'/'+batchLabel+row['simLabel']+'.json'\n cpcmd = 'cp ' + sourceFile1 + ' ' + targetFolder + '/.'\n #cpcmd = cpcmd + '; cp ' + sourceFile2 + ' ' + targetFolder + '/.'\n os.system(cpcmd) \n print(cpcmd)\n\n return df\n\n else:\n var = [('simData', 'V_soma', 'cell_5198'), ('simData', 'simLabel')]\n params, data = utils.readBatchData(dataFolder, batchLabel, loadAll=loadAll, saveAll=1-loadAll, vars=var, maxCombs=None)\n df = utils.toPandas(params, data)\n\n copyFolder = 'noDepol'\n targetFolder = dataFolder+batchLabel+'/'+copyFolder\n try: \n os.mkdir(targetFolder)\n except:\n pass\n \n for i,row in df.iterrows():\n block = False\n if detectDepolBlock(row.V_soma): block = True\n\n if not block:\n sourceFile1 = dataFolder+batchLabel+'/'+batchLabel+row.simLabel+'_*.png'\n sourceFile2 = dataFolder+batchLabel+'/'+batchLabel+row['simLabel']+'.json'\n cpcmd = 'cp ' + sourceFile1 + ' ' + targetFolder + '/.'\n cpcmd = cpcmd + '; cp ' + sourceFile2 + ' ' + targetFolder + '/.'\n os.system(cpcmd) \n print(cpcmd)\n \n return df\n\n\n\ndef addFitness(dataFolder, batchLabel, loadAll, tranges=[[1500, 1750], [1750,2000], [2000,2250], [2250,2500]], Epops=None, Ipops=None):\n \n params, data = utils.readBatchData(dataFolder, batchLabel, loadAll=loadAll, saveAll=1-loadAll)\n df = utils.toPandas(params, data)\n\n # calculate fitness value for each row\n fitnessFuncArgs = {}\n pops = {}\n\n ## Exc pops\n if not Epops:\n Epops = ['IT2', 'IT3', 'ITP4', 'ITS4', 'IT5A', 'CT5A', 'IT5B', 'PT5B', 'CT5B', 'IT6', 'CT6', 'TC', 'TCM', 'HTC'] # all layers + thal + IC\n\n Etune = {'target': 5, 'width': 5, 'min': 0.5}\n \n for pop in Epops:\n pops[pop] = Etune\n \n ## Inh pops \n if not Ipops:\n Ipops = ['NGF1', # L1\n 'PV2', 'SOM2', 'VIP2', 'NGF2', # L2\n 'PV3', 'SOM3', 'VIP3', 'NGF3', # L3\n 'PV4', 'SOM4', 'VIP4', 'NGF4', # L4\n 'PV5A', 'SOM5A', 'VIP5A', 'NGF5A', # L5A \n 'PV5B', 'SOM5B', 'VIP5B', 'NGF5B', # L5B\n 'PV6', 'SOM6', 'VIP6', 'NGF6', # L6\n 'IRE', 'IREM', 'TI'] # Thal \n\n\n Itune = {'target': 10, 'width': 15, 'min': 0.5}\n\n for pop in Ipops:\n pops[pop] = Itune\n \n fitnessFuncArgs['pops'] = pops\n fitnessFuncArgs['maxFitness'] = 1000\n fitnessFuncArgs['tranges'] = tranges\n\n def fitnessFunc(simData, **kwargs):\n import numpy as np\n pops = kwargs['pops']\n maxFitness = kwargs['maxFitness']\n tranges = kwargs['tranges']\n\n popFitnessAll = []\n\n for trange in tranges:\n popFitnessAll.append([min(np.exp(abs(v['target'] - simData['popRates'][k]['%d_%d'%(trange[0], trange[1])])/v['width']), maxFitness) \n if simData['popRates'][k]['%d_%d'%(trange[0], trange[1])] >= v['min'] else maxFitness for k, v in pops.items()])\n \n popFitness = np.mean(np.array(popFitnessAll), axis=0)\n \n fitness = np.mean(popFitness)\n return fitness\n\n df['fitness'] = [fitnessFunc(simData=row, **fitnessFuncArgs) for index, row in df.iterrows()]\n\n # add also avg rates \n for k in df.iloc[0]['popRates'].keys():\n df[k] = [np.mean([float(x) for x in r['popRates'][k].values()]) for i,r in df.iterrows()]\n\n return df","sub_path":"analysis/batchAnalysisFilter.py","file_name":"batchAnalysisFilter.py","file_ext":"py","file_size_in_byte":17628,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"185922342","text":"#!/usr/bin/env python3\n\n\"\"\"\nFor each Torch optimizer, we create a wrapper pydantic dataclass around it.\nWe also add this class to our Optimizer registry.\n\nUsage:\n\nWhenever you want to use this Optimizer__Union, specify it as the type.\nE.g.\nclass Parameters:\n rl: RLParameters = field(default_factory=RLParameters)\n minibatch_size: int = 64\n optimizer: Optimizer__Union = field(default_factory=Optimizer__Union.default)\n\nTo instantiate it, specify desired optimzier in YAML file.\nE.g.\nrl:\n ...\nminibatch: 64\noptimizer:\n Adam:\n lr: 0.001\n eps: 1e-08\n lr_schedulers:\n - OneCycleLR:\n ...\n\nSince we don't know which network parameters we want to optimize,\nOptimizer__Union will be a factory for the optimizer it contains.\n\nFollowing the above example, we create an optimizer as follows:\n\nclass Trainer:\n def __init__(self, network, params):\n self.optimizer = params.optimizer.make_optimizer(network.parameters())\n\n def train(self, data):\n ...\n loss.backward()\n # steps both optimizer and chained lr_schedulers\n self.optimizer.step()\n\"\"\"\nimport inspect\nfrom typing import List\n\nimport torch\nfrom reagent.core.dataclasses import dataclass, field\nfrom reagent.core.registry_meta import RegistryMeta\n\nfrom .scheduler import LearningRateSchedulerConfig\nfrom .utils import is_torch_optimizer\n\n\n@dataclass(frozen=True)\nclass Optimizer:\n # This is the wrapper for optimizer + scheduler\n optimizer: torch.optim.Optimizer\n lr_schedulers: List[torch.optim.lr_scheduler._LRScheduler]\n\n def step(self, closure=None):\n self.optimizer.step(closure=closure)\n for lr_scheduler in self.lr_schedulers:\n lr_scheduler.step()\n\n def __getattr__(self, attr):\n return getattr(self.optimizer, attr)\n\n\n@dataclass(frozen=True)\nclass OptimizerConfig(metaclass=RegistryMeta):\n # optional config if you want to use (potentially chained) lr scheduler\n lr_schedulers: List[LearningRateSchedulerConfig] = field(default_factory=list)\n\n def make_optimizer(self, params) -> Optimizer:\n # Assuming the classname is the same as the torch class name\n torch_optimizer_class = getattr(torch.optim, type(self).__name__)\n assert is_torch_optimizer(\n torch_optimizer_class\n ), f\"{torch_optimizer_class} is not an optimizer.\"\n filtered_args = {\n k: getattr(self, k)\n for k in inspect.signature(torch_optimizer_class).parameters\n if k != \"params\"\n }\n optimizer = torch_optimizer_class(params=params, **filtered_args)\n lr_schedulers = [\n lr_scheduler.make_from_optimizer(optimizer)\n for lr_scheduler in self.lr_schedulers\n ]\n return Optimizer(optimizer=optimizer, lr_schedulers=lr_schedulers)\n","sub_path":"reagent/optimizer/optimizer.py","file_name":"optimizer.py","file_ext":"py","file_size_in_byte":2811,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"33776391","text":"from sklearn.cluster import OPTICS, cluster_optics_dbscan\nimport matplotlib.gridspec as gridspec\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom Dataset import loadCSV\n\nX = loadCSV()\n\nclust = OPTICS(min_samples=11, metric='euclidean', cluster_method='dbscan', min_cluster_size=.05).fit(X)\n\n\n\nspace = np.arange(len(X))\nreachability = clust.reachability_[clust.ordering_]\nlabels = clust.labels_[clust.ordering_]\n\nplt.figure(figsize=(10, 7))\nG = gridspec.GridSpec(2, 3)\nax1 = plt.subplot(G[0, :])\n# ax2 = plt.subplot(G[1, 0])\n# ax3 = plt.subplot(G[1, 1])\n# ax4 = plt.subplot(G[1, 2])\n\n# Reachability plot\nprint(labels)\ncolors = ['g.', 'r.', 'b.', 'y.', 'c.']\nfor klass, color in zip(range(0, 5), colors):\n Xk = space[labels == klass]\n Rk = reachability[labels == klass]\n ax1.plot(Xk, Rk, color, alpha=0.3)\nax1.plot(space[labels == -1], reachability[labels == -1], 'k.', alpha=0.3)\n# ax1.plot(space, np.full_like(space, 2., dtype=float), 'k-', alpha=0.5)\n# ax1.plot(space, np.full_like(space, 0.5, dtype=float), 'k-.', alpha=0.5)\nax1.set_ylabel('Reachability (epsilon distance)')\nax1.set_title('Reachability Plot')\n\n# # OPTICS\n# colors = ['g.', 'r.', 'b.', 'y.', 'c.']\n# for klass, color in zip(range(0, 5), colors):\n# Xk = X[clust.labels_ == klass]\n# ax2.plot(Xk[:, 0], Xk[:, 1], color, alpha=0.3)\n# ax2.plot(X[clust.labels_ == -1, 0], X[clust.labels_ == -1, 1], 'k+', alpha=0.1)\n# ax2.set_title('Automatic Clustering\\nOPTICS')\n#\n# # DBSCAN at 0.5\n# colors = ['g', 'greenyellow', 'olive', 'r', 'b', 'c']\n# for klass, color in zip(range(0, 6), colors):\n# Xk = X[labels_050 == klass]\n# ax3.plot(Xk[:, 0], Xk[:, 1], color, alpha=0.3, marker='.')\n# ax3.plot(X[labels_050 == -1, 0], X[labels_050 == -1, 1], 'k+', alpha=0.1)\n# ax3.set_title('Clustering at 0.5 epsilon cut\\nDBSCAN')\n#\n# # DBSCAN at 2.\n# colors = ['g.', 'm.', 'y.', 'c.']\n# for klass, color in zip(range(0, 4), colors):\n# Xk = X[labels_200 == klass]\n# ax4.plot(Xk[:, 0], Xk[:, 1], color, alpha=0.3)\n# ax4.plot(X[labels_200 == -1, 0], X[labels_200 == -1, 1], 'k+', alpha=0.1)\n# ax4.set_title('Clustering at 2.0 epsilon cut\\nDBSCAN')\n\nplt.tight_layout()\nplt.show()","sub_path":"src/OPTICS.py","file_name":"OPTICS.py","file_ext":"py","file_size_in_byte":2159,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"448681906","text":"import pygame\nfrom pygame.locals import *\nimport time\nimport random\nfrom tkinter import messagebox\n\nSIZE = 40\nINITIAL_LENGTH = 1\n\n\nclass Game:\n\tdef __init__(self):\n\t\tpygame.init()\n\t\tpygame.mixer.init()\n\n\t\t# Create a Screen\n\t\tself.surface = pygame.display.set_mode((1000, 800))\n\t\tpygame.display.set_caption(\"Snake Game\")\n\n\t\t# Set Screen Icon\n\t\ticon_game = pygame.image.load(\"resources/22285snake_98774.ico\").convert()\n\t\tpygame.display.set_icon(icon_game)\n\n\t\t# Create a Snake Instance\n\t\tself.snake = Snake(self.surface, INITIAL_LENGTH)\n\t\tself.snake.draw()\n\n\t\tself.time_stamp = 0.03\n\n\t\t# Create an Apple Instance\n\t\tself.apple = Apple(self.surface)\n\t\tself.apple.draw()\n\n\t\t# Play Background Music\n\t\tself.play_background_music()\n\n\tdef play(self):\n\t\tself.render_background_image()\n\n\t\tself.snake.walk()\n\t\tself.apple.draw()\n\t\tself.display_score()\n\t\tpygame.display.flip()\n\n\t\t# Collision of Snake with Apple\n\t\tfor i in range(self.snake.length):\n\t\t\tif self.collide(self.snake.x[i], self.snake.y[i], self.apple.x, self.apple.y):\n\t\t\t\tself.play_sound(\"resources/ding.mp3\")\n\n\t\t\t\tself.snake.increase_length()\n\t\t\t\tself.apple.move()\n\n\t\t# Snake Colliding with itself\n\t\tfor i in range(2, self.snake.length):\n\t\t\tif self.collide(self.snake.x[0], self.snake.y[0], self.snake.x[i], self.snake.y[i]):\n\t\t\t\tself.play_sound(\"resources/crash.mp3\")\n\t\t\t\traise Exception(\"An Error occurred\")\n\n\t\t# Collision of snake with window boundaries\n\t\tif not (0 <= self.snake.x[0] <= 1000 and 0 <= self.snake.y[0] <= 800):\n\t\t\tself.play_sound(\"resources/crash.mp3\")\n\t\t\traise Exception(\"Snake hit the Wall\")\n\n\t@staticmethod\n\tdef collide(x_1, y_1, x_2, y_2):\n\t\tif x_1 >= x_2 and x_1 < x_2 + SIZE:\n\t\t\tif y_1 >= y_2 and y_1 < y_2 + SIZE:\n\t\t\t\treturn True\n\t\t\telse:\n\t\t\t\treturn False\n\t\telse:\n\t\t\treturn False\n\n\tdef display_score(self):\n\t\tfont = pygame.font.SysFont('arial', 30)\n\t\tscore = font.render(f'Score: {self.snake.length - INITIAL_LENGTH}', True, (255, 255, 255))\n\t\tl_block = font.render(\"Level 2\", True, (255, 255, 255))\n\t\tself.surface.blit(score, (850, 10))\n\t\tself.surface.blit(l_block, (650, 10))\n\n\tdef show_game_over(self):\n\t\t# self.render_background_image()\n\t\tself.surface.fill('black')\n\t\tpygame.display.update()\n\n\t\tfont = pygame.font.SysFont('Ink Free', 30)\n\t\tfont_score = pygame.font.SysFont(\"Ink Free\", 50)\n\n\t\tscore = self.snake.length - INITIAL_LENGTH\n\n\t\ttext = \"\"\n\t\tr = 0\n\t\tg = 0\n\t\tb = 0\n\n\t\tif score <= 10:\n\t\t\tr = 255\n\t\t\tg = 255\n\t\t\tb = 0\n\t\t\ttext = \"Well Tried! Just Keep Practising\"\n\t\telif score > 10 and score <= 20:\n\t\t\tr = 255\n\t\t\tg = 165\n\t\t\tb = 0\n\t\t\ttext = \"Good! But snake is still hungry\"\n\t\telif score > 20 and score <= 40:\n\t\t\tr = 0\n\t\t\tg = 0\n\t\t\tb = 255\n\t\t\ttext = \"Excellent! Just a little more to go\"\n\t\telif score > 40 and score <= 50:\n\t\t\tr = 0\n\t\t\tg = 100\n\t\t\tb = 0\n\t\t\ttext = \"Fabulous!!! Now, Snake is well-fed\"\n\t\telif score > 50 and score <= 60:\n\t\t\tr = 0\n\t\t\tg = 255\n\t\t\tb = 0\n\t\t\ttext = \"Just put your snake on diet!\"\n\t\telse:\n\t\t\tr = 128\n\t\t\tg = 0\n\t\t\tb = 128\n\t\t\ttext = \"Haha... Snakes are loving you!!\"\n\n\t\tline3 = font_score.render(f'{text}', True, (r, g, b))\n\t\tself.surface.blit(line3, (170, 200))\n\n\t\tline1 = font_score.render(f'Game Over! Your Score is: {self.snake.length - INITIAL_LENGTH}', True, (255, 0, 0))\n\t\tself.surface.blit(line1, (200, 300))\n\n\t\tline2 = font.render(\"To play Again, press ENTER. To exit, press ESC\", True, (255, 255, 255))\n\t\tself.surface.blit(line2, (180, 400))\n\n\t\tpygame.display.flip()\n\n\t\t# Stop the Background Music\n\t\tpygame.mixer.music.pause()\n\n\tdef game_reset(self):\n\t\tself.snake = Snake(self.surface, INITIAL_LENGTH)\n\t\tself.apple = Apple(self.surface)\n\n\t@staticmethod\n\tdef play_sound(sound):\n\t\tsound_to_be_played = pygame.mixer.Sound(sound)\n\t\tpygame.mixer.Sound.play(sound_to_be_played)\n\n\t@staticmethod\n\tdef play_background_music():\n\t\tpygame.mixer.music.load(\"resources/bg_music_1.mp3\")\n\t\tpygame.mixer.music.play(-1, 0)\n\n\tdef render_background_image(self):\n\t\tbackground_image = pygame.image.load(\"resources/aisvri-mkGZtYl2a9M-unsplash.jpg\")\n\t\tself.surface.blit(background_image, (0, 0))\n\n\tdef run(self):\n\t\t# Show the window\n\t\tpygame.display.flip()\n\n\t\t# Create mainloop\n\t\ttime.sleep(2)\n\t\trunning = True\n\t\tpause = False\n\t\twhile running:\n\t\t\tfor event in pygame.event.get():\n\t\t\t\tif event.type == QUIT:\n\t\t\t\t\trunning = False\n\t\t\t\t\tpygame.quit()\n\t\t\t\t\tpygame.display.quit()\n\t\t\t\t\tbreak\n\t\t\t\telif event.type == KEYDOWN:\n\t\t\t\t\tif event.key == K_ESCAPE:\n\t\t\t\t\t\trunning = False\n\t\t\t\t\t\tpygame.quit()\n\t\t\t\t\t\tpygame.display.quit()\n\t\t\t\t\t\tbreak\n\t\t\t\t\telif event.key == K_RETURN:\n\t\t\t\t\t\t# Re-run the background Music\n\t\t\t\t\t\tpygame.mixer.music.unpause()\n\n\t\t\t\t\t\tpause = False\n\t\t\t\t\telif event.key == K_SPACE:\n\t\t\t\t\t\tif pause:\n\t\t\t\t\t\t\tpause = False\n\t\t\t\t\t\t\tpygame.mixer.music.unpause()\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tpause = True\n\t\t\t\t\t\t\tpygame.mixer.music.pause()\n\t\t\t\t\t\t\tfont = pygame.font.SysFont('arial', 30)\n\t\t\t\t\t\t\tline1 = font.render('Paused', True, (255, 255, 255))\n\t\t\t\t\t\t\tself.surface.blit(line1, (450, 10))\n\t\t\t\t\t\t\tpygame.display.flip()\n\t\t\t\t\telif not pause:\n\t\t\t\t\t\tif event.key == K_DOWN:\n\t\t\t\t\t\t\tself.snake.move_down()\n\t\t\t\t\t\telif event.key == K_UP:\n\t\t\t\t\t\t\tself.snake.move_up()\n\t\t\t\t\t\telif event.key == K_LEFT:\n\t\t\t\t\t\t\tself.snake.move_left()\n\t\t\t\t\t\telif event.key == K_RIGHT:\n\t\t\t\t\t\t\tself.snake.move_right()\n\t\t\ttry:\n\t\t\t\tif not pause:\n\t\t\t\t\tself.play()\n\t\t\texcept Exception as e:\n\t\t\t\tself.show_game_over()\n\t\t\t\tpause = True\n\t\t\t\tself.game_reset()\n\n\t\t\t# This is will make the snake walk after every .2 seconds\n\t\t\ttime.sleep(self.time_stamp)\n\n\nclass Snake:\n\tdef __init__(self, parent_screen, length):\n\t\tself.parent_screen = parent_screen\n\n\t\t# Get The Block Image\n\t\tself.block = pygame.image.load(\"resources/second_tail.png\").convert()\n\t\tself.head = pygame.image.load(\"resources/head.png\").convert()\n\t\tself.tail = pygame.image.load(\"resources/tail.png\").convert()\n\n\t\t# This parameter will check the length of box\n\t\tself.length = length\n\t\t# Initialize default block properties\n\t\tself.x = [SIZE] * length\n\t\tself.y = [SIZE] * length\n\n\t\t# Define the default direction in which box moves\n\t\tself.direction = \"down\"\n\n\tdef draw(self):\n\t\t# Change block position\n\t\tfor i in range(self.length):\n\t\t\tif i == 0:\n\t\t\t\tself.parent_screen.blit(self.head, (self.x[0], self.y[0]))\n\t\t\telif i == self.length-1:\n\t\t\t\tself.parent_screen.blit(self.block, (self.x[i], self.y[i]))\n\t\t\telse:\n\t\t\t\tself.parent_screen.blit(self.tail, (self.x[i], self.y[i]))\n\t\tpygame.display.flip()\n\n\tdef walk(self):\n\t\tfor i in range(self.length - 1, 0, -1):\n\t\t\tself.x[i] = self.x[i - 1]\n\t\t\tself.y[i] = self.y[i - 1]\n\n\t\tif self.direction == 'down':\n\t\t\tself.y[0] += SIZE\n\t\telif self.direction == 'up':\n\t\t\tself.y[0] -= SIZE\n\t\telif self.direction == 'left':\n\t\t\tself.x[0] -= SIZE\n\t\telse:\n\t\t\tself.x[0] += SIZE\n\t\tself.draw()\n\n\tdef increase_length(self):\n\t\tself.length += 2\n\t\tself.x.append(-1)\n\t\tself.x.append(-1)\n\t\tself.y.append(-1)\n\t\tself.y.append(-1)\n\n\tdef move_up(self):\n\t\tif self.direction == 'down':\n\t\t\tself.direction = 'down'\n\t\telse:\n\t\t\tself.direction = \"up\"\n\n\tdef move_down(self):\n\t\tif self.direction == 'up':\n\t\t\tself.direction = 'up'\n\t\telse:\n\t\t\tself.direction = \"down\"\n\n\tdef move_left(self):\n\t\tif self.direction == 'right':\n\t\t\tself.direction = 'right'\n\t\telse:\n\t\t\tself.direction = \"left\"\n\n\tdef move_right(self):\n\t\tif self.direction == 'left':\n\t\t\tself.direction = 'left'\n\t\telse:\n\t\t\tself.direction = \"right\"\n\n\nclass Apple:\n\tdef __init__(self, parent_screen):\n\t\tself.parent_screen = parent_screen\n\t\tself.apple_image = pygame.image.load(\"resources/apple.jpg\").convert()\n\t\tself.x = SIZE * 3\n\t\tself.y = SIZE * 3\n\n\tdef draw(self):\n\t\tself.parent_screen.blit(self.apple_image, (self.x, self.y))\n\t\tpygame.display.flip()\n\n\tdef move(self):\n\t\tself.x = random.randint(1, 23) * SIZE\n\t\tself.y = random.randint(1, 19) * SIZE\n\n","sub_path":"prompt/level_2.py","file_name":"level_2.py","file_ext":"py","file_size_in_byte":7600,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"209355924","text":"import pytest\nimport os\nimport pathlib\nfrom LocalStorage.localStore import LocalSore\nimport jsonlines\n\nKEY_DESCRIPTOR = '&^@#'\n\n\ndef test_store_creation():\n \"\"\"Test for checking store is created at the default location\n \"\"\"\n store = LocalSore()\n file_path = store.file_path\n file = file_path.name\n parent_path = file_path.parent\n files = os.listdir(parent_path)\n\n assert file in files, 'Store Not Created'\n assert 'keys.json' in files, 'Keys file not created'\n\n store.delete_store()\n\n\ndef test_store_creation_user_path():\n \"\"\"Test to checking store is created at the user location\n \"\"\"\n store = LocalSore('store.json')\n file_path = store.file_path\n file = file_path.name\n parent_path = file_path.parent\n files = os.listdir(parent_path)\n print(file_path)\n\n assert file in files, 'Store Not Created'\n assert 'keys.json' in files, 'Keys file not created'\n\n store.delete_store()\n\n\ndef test_write_to_store__key_error():\n \"\"\"Test for checking if the write method raises KeyError Exception if same key is entered\n \"\"\"\n store = LocalSore()\n with pytest.raises(KeyError) as exec_info:\n store.write(\"key1\", 'adasdfadsf')\n store.write(\"key1\", 'adasdfadsf')\n print(exec_info)\n store.delete_store()\n\n\ndef test_write_to_store__type_error():\n \"\"\"Test for checking if write method raises if the type of key is not string\n \"\"\"\n store = LocalSore()\n with pytest.raises(TypeError) as exec_info:\n print(exec_info)\n store.write(1, 'adasdfadsf')\n store.delete_store()\n\n\ndef test_write_to_file():\n \"\"\"Test for checking if the record is written properly to the file\n \"\"\"\n store = LocalSore()\n store.write(\"key1\", 'adasdfadsf')\n\n with jsonlines.open(store.file_path) as fp:\n for line in fp.iter():\n assert line == {f'key1{KEY_DESCRIPTOR}': {'data': 'adasdfadsf'}\n }, 'Record is not same'\n store.delete_store()\n\n\ndef test_write_to_store_multiple_records():\n \"\"\"Test for checking if multiple items are written properly to the file\n \"\"\"\n store = LocalSore()\n store.write('key1', 'asdfadfasdf')\n store.write('key2', 'asdfadfasdf')\n entries = [\n {f'key1{KEY_DESCRIPTOR}': {'data': 'asdfadfasdf'}},\n {f'key2{KEY_DESCRIPTOR}': {'data': 'asdfadfasdf'}},\n ]\n\n with jsonlines.open(store.file_path) as fp:\n for line, test in zip(fp.iter(), entries):\n assert line == test, 'records not same'\n\n store.delete_store()\n\n\ndef test_read_from_file__type_error():\n \"\"\"Test for checking if read method raises if the type of key is not string\n \"\"\"\n store = LocalSore()\n with pytest.raises(TypeError) as exec_info:\n store.read(1)\n store.delete_store()\n\n\ndef test_read_from_file__key_error():\n \"\"\"Test for checking if the read method raises KeyError Exception if same key is entered\n \"\"\"\n store = LocalSore()\n store.write('key1', \"asdasdad\")\n with pytest.raises(KeyError) as exec_info:\n store.read('key2')\n store.delete_store()\n\n\ndef test_read_from_store():\n \"\"\"Test for checking if the data is read properly\n \"\"\"\n store = LocalSore('abc/store.ndjson')\n store.write('key1', 'asdasd')\n data = store.read('key1')\n assert data == {'data': 'asdasd'}, 'data is not same'\n store.delete_store()\n\n\ndef test_delete_from_store__type_error():\n \"\"\"Test for checking if delete method raises if the type of key is not string\n \"\"\"\n store = LocalSore()\n with pytest.raises(TypeError) as exec_info:\n store.delete(1)\n store.delete_store()\n\n\ndef test_delete_from_store__key_error():\n \"\"\"Test for checking if the delete method raises KeyError Exception if same key is entered\n \"\"\"\n store = LocalSore()\n store.write('key1', 'asdfadsfadsf')\n with pytest.raises(KeyError) as exec_info:\n assert store.delete('key2')\n store.delete_store()\n\n\ndef test_delete_from_store():\n \"\"\"Test for Checking if the record is deleted properly\n \"\"\"\n store = LocalSore()\n store.write('key1', 'asdfadsfadsf')\n store.write('key2', 'asdfadsfadsf')\n store.delete('key1')\n\n with jsonlines.open(store.file_path) as fp:\n for line in fp.iter():\n assert line == {f'key2{KEY_DESCRIPTOR}': {\n 'data': 'asdfadsfadsf'}}, 'Record deleted is different'\n\n store.delete_store()\n","sub_path":"LocalStorage/tests/test_localStore.py","file_name":"test_localStore.py","file_ext":"py","file_size_in_byte":4391,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"582902341","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models\n\nfrom undp_auth.models import UndpUser\n\n# Create your models here.\n\n\nPREFERRED_INDUSTRIES_CHOICES = (\n ('agriculture', \"Agriculture\"),\n ('manufacturing', \"Manufacturing and Assembly\"),\n ('financial', \"Financial Services\"),\n ('renewable', \"Renewable Energy\"),\n ('information security', \"Information Security\"),\n ('education', \"Education\"),\n ('health', \"Healthcare & Services\"),\n ('infrastructure', \"Infrastructure\"),\n ('transport', \"Transport\"),\n)\n\nINVESTMENT_STAGE_CHOICES = (\n (\"Concept Stage\", \"Concept stage\"),\n (\"Seed stage (finding product market fit)\",\n \"Seed stage (finding product market fit)\"),\n (\"Venture captial (growth)\", \"Venture captial (growth)\"),\n (\"Private Equity (scaling and expansion)\",\n \"Private Equity (scaling and expansion)\")\n)\n\n\nclass InvestmentCompany(models.Model):\n user = models.OneToOneField(UndpUser, on_delete=models.CASCADE)\n investor_focus = models.TextField(blank=True, default=\"\")\n preferred_industries = models.CharField(\n max_length=200, blank=True, choices=PREFERRED_INDUSTRIES_CHOICES)\n other_industries = models.CharField(max_length=100, blank=True)\n investment_stage = models.CharField(\n max_length=200, blank=True, choices=INVESTMENT_STAGE_CHOICES)\n ticket_size = models.CharField(max_length=200, blank=True, default=\"0\")\n url = models.CharField(max_length=200, blank=True, default=\"\")\n logo = models.ImageField(blank=True, null=True)\n organisation_name = models.CharField(\n max_length=200, blank=True, null=False)\n published = models.BooleanField(default=False)\n\n def get_logo(self):\n if self.logo:\n return self.logo.url\n elif self.picture:\n return self.picture.url\n else:\n return \"/\"\n\n def __unicode__(self):\n return self.organisation_name\n\n def __str__(self):\n return self.organisation_name\n\n\nclass CommunityHub(models.Model):\n user = models.OneToOneField(UndpUser, on_delete=models.CASCADE)\n organisation_name = models.CharField(max_length=200, blank=True)\n hub_focus = models.TextField(blank=True)\n preferred_industries = models.CharField(max_length=200, blank=True)\n investment_stage = models.CharField(max_length=200, blank=True)\n support_type = models.CharField(max_length=255, blank=True)\n url = models.CharField(max_length=200, blank=True)\n logo = models.ImageField(blank=True, null=True)\n\n def __unicode__(self):\n return self.organisation_name\n\n\nclass Innovation(models.Model):\n user = models.OneToOneField(UndpUser, on_delete=models.CASCADE)\n stage = models.CharField(max_length=30, blank=True)\n name = models.CharField(max_length=50, blank=True)\n description = models.TextField(blank=True)\n url = models.CharField(max_length=200, blank=True, default=\"\")\n service_pic = models.ImageField(blank=True, null=True)\n service_videos = models.TextField(blank=True, null=True)\n sectors = models.TextField(blank=True, default=\"\")\n other_sectors = models.CharField(max_length=30, blank=True, default=\"\")\n challenge_to_solve = models.TextField(blank=True, default=\"\")\n challenge_faced = models.TextField(blank=True, default=\"\")\n other_challenges = models.TextField(blank=True, default=\"\")\n logo = models.ImageField(blank=True, default=\"\")\n\n target_customers = models.TextField(blank=True, default=\"\")\n market_size = models.TextField(blank=True, default=\"\")\n customer_lessons = models.TextField(blank=True, default=\"\")\n acquisition_plan = models.TextField(blank=True, default=\"\")\n potential_competitors = models.TextField(blank=True, default=\"\")\n competitive_advantage = models.TextField(blank=True, default=\"\")\n business_differentiator = models.TextField(blank=True, default=\"\")\n major_wrongs = models.TextField(blank=True, default=\"\")\n\n revenue = models.TextField(blank=True, default=\"\")\n monthly_costs = models.FileField(blank=True, null=True)\n annual_costs = models.FileField(blank=True, null=True)\n\n growth_ambitions = models.TextField(blank=True, default=\"\")\n milestones = models.TextField(blank=True, default=\"\")\n\n do_you_have_audited_books = models.BooleanField(\n max_length=50, blank=True, default=False)\n total_sales = models.CharField(max_length=50, blank=True, default=\"\")\n total_capital = models.CharField(max_length=50, blank=True, default=\"\")\n expected_capital = models.CharField(max_length=50, blank=True, default=\"\")\n capital_type = models.CharField(max_length=50, blank=True, default=\"\")\n capital_use = models.CharField(max_length=50, blank=True, default=\"\")\n\n test_plan = models.TextField(blank=True, default=\"\")\n impact_measure_plan = models.TextField(blank=True, default=\"\")\n show_success_plan = models.TextField(blank=True, default=\"\")\n\n costs = models.TextField(max_length=50, blank=True, default=\"\")\n\n yr_1_projected_earnings = models.CharField(max_length=50, default=\"\")\n yr_2_projected_earnings = models.CharField(max_length=50, default=\"\")\n yr_3_projected_earnings = models.CharField(max_length=50, default=\"\")\n\n do_really_well = models.TextField(blank=True, default=\"\")\n key_resources = models.TextField(blank=True, default=\"\")\n key_partners = models.TextField(blank=True, default=\"\")\n\n problem_change = models.TextField(blank=True, default=\"\")\n customer_change = models.TextField(blank=True, default=\"\")\n planned_acquisition_plan = models.TextField(blank=True)\n performance = models.TextField(blank=True, default=\"\")\n test_learnings = models.TextField(blank=True, default=\"\")\n\n monthly_cashflow = models.FileField(blank=True, null=True)\n income_statement = models.FileField(blank=True, null=True)\n published = models.BooleanField(default=False)\n\n def get_annual_costs(self):\n try:\n return self.annual_costs.url\n except BaseException:\n return \"/\"\n\n def get_monthly_costs(self):\n try:\n return self.monthly_costs.url\n except BaseException:\n return \"/\"\n\n def get_logo(self):\n try:\n return self.logo.url\n except BaseException:\n return \"/\"\n\n def audited_books(self):\n try:\n vals = [\"No\", \"Yes\"]\n return vals[int(self.do_you_have_auditedbooks)]\n except BaseException:\n return \"No\"\n\n def type_of_capital_sought(self):\n try:\n vals = [\"\", \"Equity\", \"Grants\", \"Convertible Debt\",\n \"Commercial Debt (Banks)\", \"Soft Debt (Friends)\"]\n return vals[int(self.capital_type)]\n except BaseException:\n return \"\"\n\n # Override the __unicode__() method to return out something meaningful!\n def __unicode__(self):\n return self.name\n\n @property\n def __str__(self):\n return self.name\n","sub_path":"projects/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":6955,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"638586575","text":"#!/usr/bin/python3\nfrom datetime import datetime\nimport uuid\nimport models\n\ntime = \"%Y-%m-%dT%H:%M:%S.%f\"\n\n\nclass BaseModel:\n \"\"\" Class Base \"\"\"\n\n def __init__(self, *args, **kwargs):\n self.id = str(uuid.uuid4())\n self.created_at = datetime.today()\n self.updated_at = datetime.today()\n if len(kwargs) != 0:\n for key, value in kwargs.items():\n if key == \"updated_at\" or key == \"created_at\":\n self.__dict__[key] = datetime.strptime(value, time)\n else:\n self.__dict__[key] = value\n else:\n self.id = str(uuid.uuid4())\n self.created_at = datetime.now()\n self.updated_at = self.created_at\n models.storage.new(self)\n models.storage.save()\n\n def __str__(self):\n \"\"\" Returns the string representation \"\"\"\n return \"[{}] ({}) {} \".format(self.__class__.__name__,\n self.id,\n self.__dict__)\n\n def save(self):\n \"\"\" Update the updatet_at attribute \"\"\"\n self.updated_at = datetime.now()\n models.storage.save()\n\n def to_dict(self):\n \"\"\" Return the dictionary representation of the attributes \"\"\"\n my_dict = self.__dict__.copy()\n if \"created_at\" in my_dict:\n my_dict[\"created_at\"] = self.created_at.strftime(time)\n if \"updated_at\" in my_dict:\n my_dict[\"updated_at\"] = self.updated_at.strftime(time)\n my_dict[\"__class__\"] = self.__class__.__name__\n return my_dict\n","sub_path":"models/base_model.py","file_name":"base_model.py","file_ext":"py","file_size_in_byte":1602,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"611407356","text":"#!/usr/bin/env python\n#\n# License: BSD\n# https://raw.github.com/stonier/py_trees_suite/license/LICENSE\n#\n##############################################################################\n# Documentation\n##############################################################################\n\n\"\"\"\n.. module:: trees\n :platform: Unix\n :synopsis: Managing a behaviour tree.\n\nThis module creates tools for managing your entire behaviour tree.\n\n----\n\n\"\"\"\n\n##############################################################################\n# Imports\n##############################################################################\n\nimport time\n\nfrom . import composites\nfrom . import logging\n\nfrom .behaviours import Behaviour\n\nCONTINUOUS_TICK_TOCK = -1\n\n##############################################################################\n# Visitors\n##############################################################################\n\n\nclass VisitorBase(object):\n \"\"\"Base object for visitors.\n \"\"\"\n def __init__(self, full=False):\n \"\"\"Initialises the base object for the visitor.\n\n :param bool full: if true, this visitor will visit all nodes in the tree\n every tick. If false, it only visits nodes that are parents of nodes\n that are running, as well as those running nodes.\n\n \"\"\"\n self.full = full\n\n\nclass DebugVisitor(VisitorBase):\n def __init__(self):\n super(DebugVisitor, self).__init__(full=False)\n self.logger = logging.get_logger(\"Visitor\")\n\n def initialise(self):\n pass\n\n def run(self, behaviour):\n if behaviour.feedback_message:\n self.logger.debug(\" %s [visited][%s][%s]\" % (behaviour.name, behaviour.status, behaviour.feedback_message))\n else:\n self.logger.debug(\" %s [visited][%s]\" % (behaviour.name, behaviour.status))\n\n\n##############################################################################\n# Trees\n##############################################################################\n\n\nclass BehaviourTree(object):\n \"\"\"\n Grow, water, prune your behaviour tree.\n\n :ivar int count: number of times the tree has been ticked.\n :ivar root: root node of the tree.\n :vartype root: instance or descendant of :class:`Behaviour `\n :ivar visitors: list of entities that visit the iterated parts of the tree when it ticks.\n :vartype visitors: list of classes that implement an initialise() and run(py_trees.Behaviour) method.\n :ivar pre_tick_handlers: methods that run before the entire tree is ticked\n :vartype pre_tick_handlers: list of methods that take this instance as an arg\n :ivar post_tick_handlers: methods that run after the entire tree is ticked\n :vartype post_tick_handlers: list of methods that take this instance as an arg\n :ivar interrupt_tick_tocking: interrupt tick-tock if it is a tick-tocking.\n :vartype interrupt_tick_tocking: bool\n \"\"\"\n def __init__(self, root):\n \"\"\"\n Initialise the tree with a root.\n\n :param root: root node of the tree.\n :type root: instance or descendant of :class:`Behaviour `\n :raises AssertionError: if incoming root variable is not the correct type.\n \"\"\"\n self.count = 0\n assert root is not None, \"root node must not be 'None'\"\n assert isinstance(root, Behaviour), \"root node must be an instance of or descendant of pytrees.Behaviour\"\n self.root = root\n self.visitors = []\n self.pre_tick_handlers = []\n self.post_tick_handlers = []\n self.interrupt_tick_tocking = False\n self.tree_update_handler = None # child classes can utilise this one\n\n def add_pre_tick_handler(self, handler):\n self.pre_tick_handlers.append(handler)\n\n def add_post_tick_handler(self, handler):\n self.post_tick_handlers.append(handler)\n\n def prune_subtree(self, unique_id):\n \"\"\"\n :param uuid.UUID unique_id: unique id of the subtree root\n :raises AssertionError: if unique id is the behaviour tree's root node id\n :return: success or failure of the pruning\n :rtype: bool\n \"\"\"\n assert self.root.id != unique_id, \"may not prune the root node\"\n for child in self.root.iterate():\n if child.id == unique_id:\n parent = child.parent\n if parent is not None:\n parent.remove_child(child)\n if self.tree_update_handler is not None:\n self.tree_update_handler(self.root)\n return True\n return False\n\n def insert_subtree(self, child, unique_id, index):\n \"\"\"\n Insert subtree as a child of the specified parent.\n\n :param uuid.UUID unique_id: id of the parent container (usually Selector or Sequence)\n :param int index: insert the child at this index, pushing all children after it back one.\n :return: False if parent node was not found, True if inserted\n\n .. todo::\n\n Could use better, more informative error handling here. Especially if the insertion\n has its own error handling (e.g. index out of range).\n\n Could also use a different api that relies on the id\n of the sibling node it should be inserted before/after.\n \"\"\"\n for node in self.root.iterate():\n if node.id == unique_id:\n assert isinstance(node, composites.Composite), \"parent must be a Composite behaviour.\"\n node.insert_child(child, index)\n if self.tree_update_handler is not None:\n self.tree_update_handler(self.root)\n return True\n return False\n\n def replace_subtree(self, unique_id, subtree):\n \"\"\"\n Replace the subtree with the specified id for the new subtree.\n\n This is a common pattern where we'd like to swap out a whole sub-behaviour for another one.\n\n :param uuid.UUID unique_id: unique id of the subtree root\n :param subtree: incoming subtree to replace the old one\n :type subtree: instance or descendant of :class:`Behaviour `\n :raises AssertionError: if unique id is the behaviour tree's root node id\n :return: success or failure of the replacement\n :rtype: bool\n \"\"\"\n assert self.root.id != unique_id, \"may not replace the root node\"\n for child in self.root.iterate():\n if child.id == unique_id:\n parent = child.parent\n if parent is not None:\n parent.replace_child(child, subtree)\n if self.tree_update_handler is not None:\n self.tree_update_handler(self.root)\n return True\n return False\n\n def setup(self, timeout):\n \"\"\"\n Calls setup on the root of the tree. This should then percolate down into the tree itself\n via the :py:meth:`~py_trees.composites.Composite.setup` function in each composited behaviour.\n\n :returns: success or failure of the setup operation\n \"\"\"\n return self.root.setup(timeout)\n\n def tick(self, pre_tick_handler=None, post_tick_handler=None):\n \"\"\"\n Tick over the tree just once.\n\n :param pre_tick_visitor: visitor that runs on this class instance before the tick\n :type pre_tick_visitor: any class with a run(py_trees.BehaviourTree) method\n :param post_tick_visitor: visitor that runs on this class instance before the tick\n :type post_tick_visitor: any class with a run(py_trees.BehaviourTree) method\n \"\"\"\n # pre\n for handler in self.pre_tick_handlers:\n handler(self)\n if pre_tick_handler is not None:\n pre_tick_handler(self)\n for visitor in self.visitors:\n visitor.initialise()\n # tick\n for node in self.root.tick():\n for visitor in [visitor for visitor in self.visitors if not visitor.full]:\n node.visit(visitor)\n\n for node in self.root.iterate():\n for visitor in [visitor for visitor in self.visitors if visitor.full]:\n node.visit(visitor)\n\n # post\n for handler in self.post_tick_handlers:\n handler(self)\n if post_tick_handler is not None:\n post_tick_handler(self)\n self.count += 1\n\n def tick_tock(self, sleep_ms, number_of_iterations=CONTINUOUS_TICK_TOCK, pre_tick_handler=None, post_tick_handler=None):\n \"\"\"\n Tick continuously with a sleep interval as specified.\n\n :param float sleep_ms: sleep this much between ticks.\n :param int number_of_iterations: number of tick-tocks (-1 for infinite)\n :param pre_tick_handler: visitor that runs on this class instance before the tick\n :type pre_tick_handler: any function or class with a __call__ method taking a py_trees.BehaviourTree arg\n :param post_tick_handler: visitor that runs on this class instance before the tick\n :type post_tick_handler: any function or class with a __call__ method taking a py_trees.BehaviourTree arg\n \"\"\"\n tick_tocks = 0\n while not self.interrupt_tick_tocking and (tick_tocks < number_of_iterations or number_of_iterations == CONTINUOUS_TICK_TOCK):\n self.tick(pre_tick_handler, post_tick_handler)\n try:\n time.sleep(sleep_ms / 1000.0)\n except KeyboardInterrupt:\n break\n tick_tocks += 1\n self.interrupt_tick_tocking = False\n\n def interrupt(self):\n \"\"\"\n Interrupt tick-tock if it is tick-tocking.\n \"\"\"\n self.interrupt_tick_tocking = True\n\n def destroy(self):\n \"\"\"\n Destroy the tree by stopping the root node\n \"\"\"\n self.root.stop()\n","sub_path":"py_trees/src/py_trees/trees.py","file_name":"trees.py","file_ext":"py","file_size_in_byte":9871,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"49877264","text":"# -*- coding: utf-8 -*-\nimport os\n\nimport click\n\nfrom lark.exceptions import UnexpectedCharacters, UnexpectedToken\n\nfrom pytest import fixture, mark\n\nfrom storyscript.ErrorCodes import ErrorCodes\nfrom storyscript.Intention import Intention\nfrom storyscript.exceptions import CompilerError, StoryError\n\n\n@fixture\ndef error(magic):\n return magic()\n\n\n@fixture\ndef storyerror(error):\n return StoryError(error, 'story')\n\n\ndef test_storyerror_init(storyerror, error):\n assert storyerror.error == error\n assert storyerror.story == 'story'\n assert storyerror.path is None\n assert storyerror.error_tuple is None\n assert issubclass(StoryError, SyntaxError)\n\n\ndef test_storyerror_init_path():\n storyerror = StoryError('error', 'story', path='hello.story')\n assert storyerror.path == 'hello.story'\n\n\ndef test_storyerror_name(storyerror):\n assert storyerror.name() == 'story'\n\n\ndef test_storyerror_name_path(patch, storyerror):\n patch.object(os, 'getcwd', return_value='/abspath')\n storyerror.path = 'hello.story'\n assert storyerror.name() == 'hello.story'\n\n\ndef test_storyerror_name_reduce_path(patch, storyerror):\n \"\"\"\n Ensures that paths are simplified for stories in the current working\n directory.\n \"\"\"\n patch.object(os, 'getcwd', return_value='/abspath')\n storyerror.path = '/abspath/hello.story'\n assert storyerror.name() == 'hello.story'\n\n\ndef test_storyerror_get_line(patch, storyerror, error):\n \"\"\"\n Ensures get_line returns the error line\n \"\"\"\n error.line = '1'\n storyerror.story = 'x = 0\\ny = 1'\n assert storyerror.get_line() == 'x = 0'\n\n\ndef test_storyerror_header(patch, storyerror, error):\n \"\"\"\n Ensures StoryError.header returns the correct text.\n \"\"\"\n patch.object(click, 'style')\n patch.object(StoryError, 'name')\n template = 'Error: syntax error in {} at line {}, column {}'\n result = storyerror.header()\n click.style.assert_called_with(StoryError.name(), bold=True)\n assert result == template.format(click.style(), error.line, error.column)\n\n\ndef test_storyerror_symbols(patch, storyerror, error):\n \"\"\"\n Ensures StoryError.symbols creates one symbol when there is no end column.\n \"\"\"\n patch.object(click, 'style')\n del error.end_column\n error.column = '1'\n result = storyerror.symbols()\n click.style.assert_called_with('^', fg='red')\n assert result == click.style()\n\n\ndef test_story_error_symbols_end_column(patch, storyerror, error):\n \"\"\"\n Ensures StoryError.symbols creates many symbols when there is an end\n column.\n \"\"\"\n patch.object(click, 'style')\n error.end_column = '4'\n error.column = '1'\n result = storyerror.symbols()\n click.style.assert_called_with('^^^', fg='red')\n assert result == click.style()\n storyerror.with_color = False\n result = storyerror.symbols()\n assert result == '^^^'\n\n\ndef test_storyerror_highlight(patch, storyerror, error):\n \"\"\"\n Ensures StoryError.highlight produces the correct text.\n \"\"\"\n patch.many(StoryError, ['get_line', 'symbols'])\n error.column = '1'\n result = storyerror.highlight()\n highlight = '{}{}'.format(' ' * 6, StoryError.symbols())\n args = (error.line, StoryError.get_line(), highlight)\n assert result == '{}| {}\\n{}'.format(*args)\n\n\ndef test_storyerror_error_code(storyerror):\n storyerror.error_tuple = ('code', 'hint')\n assert storyerror.error_code() == 'code'\n\n\ndef test_storyerror_hint(storyerror):\n storyerror.error_tuple = ('code', 'hint')\n assert storyerror.hint() == 'hint'\n\n\ndef test_storyerror_identify(storyerror):\n storyerror.error.error = 'none'\n assert storyerror.identify() == ErrorCodes.unidentified_error\n\n\n@mark.parametrize('name', [\n 'service_name', 'arguments_noservice', 'return_outside',\n 'variables_backslash', 'variables_dash'\n])\ndef test_storyerror_identify_codes(storyerror, error, name):\n error.error = name\n assert storyerror.identify() == getattr(ErrorCodes, name)\n\n\ndef test_storyerror_identify_unexpected_token(patch, storyerror):\n patch.init(Intention)\n patch.object(Intention, 'assignment', return_value=True)\n patch.object(StoryError, 'get_line')\n storyerror.error = UnexpectedToken('token', 'expected')\n assert storyerror.identify() == ErrorCodes.assignment_incomplete\n\n\ndef test_storyerror_identify_unexpected_characters(patch, storyerror):\n patch.init(UnexpectedCharacters)\n patch.init(Intention)\n patch.object(Intention, 'is_function', return_value=True)\n patch.object(StoryError, 'get_line')\n storyerror.error = UnexpectedCharacters('seq', 'lex', 0, 0)\n assert storyerror.identify() == ErrorCodes.function_misspell\n\n\ndef test_storyerror_process(patch, storyerror):\n patch.object(StoryError, 'identify')\n storyerror.process()\n assert storyerror.error_tuple == storyerror.identify()\n\n\ndef test_storyerror_message(patch, storyerror):\n patch.many(StoryError,\n ['process', 'header', 'highlight', 'error_code', 'hint'])\n result = storyerror.message()\n assert storyerror.process.call_count == 1\n args = (storyerror.header(), storyerror.highlight(),\n storyerror.error_code(), storyerror.hint())\n assert result == '{}\\n\\n{}\\n\\n{}: {}'.format(*args)\n\n\ndef test_storyerror_echo(patch, storyerror):\n \"\"\"\n Ensures StoryError.echo prints StoryError.message\n \"\"\"\n patch.object(click, 'echo')\n patch.object(StoryError, 'message')\n storyerror.echo()\n click.echo.assert_called_with(StoryError.message())\n\n\ndef test_storyerror_internal(patch):\n \"\"\"\n Ensures that an internal error gets properly constructed\n \"\"\"\n patch.object(StoryError, 'unnamed_error')\n e = StoryError.internal_error(Exception('ICE happened'))\n msg = (\n 'Internal error occured: ICE happened\\n'\n 'Please report at https://github.com/storyscript/storyscript/issues')\n StoryError.unnamed_error.assert_called_with(msg)\n assert e == StoryError.internal_error(msg)\n\n\ndef test_storyerror_unnamed_error(patch):\n patch.init(StoryError)\n patch.init(CompilerError)\n e = StoryError.unnamed_error('Unknown error happened')\n assert isinstance(e, StoryError)\n assert CompilerError.__init__.call_count == 1\n assert isinstance(StoryError.__init__.call_args[0][0], CompilerError)\n assert StoryError.__init__.call_args[0][1] is None\n","sub_path":"tests/unittests/exceptions/StoryError.py","file_name":"StoryError.py","file_ext":"py","file_size_in_byte":6354,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"456038810","text":"def word_count(s):\n # Your code here\n word_dict = {}\n\n special_chars = ['\"', ':', ';', ',', '.', '-', '+', '=', '/', '\\\\', '|', '[', ']', '{', '}', '(', ')', '*', '^', '&']\n s2 = ''.join(c.lower() for c in s if not c in special_chars)\n word_list = s2.split()\n\n for word in word_list:\n if word == \" \":\n continue\n elif word in word_dict:\n word_dict[word] += 1\n else:\n word_dict[word] = 1\n return word_dict\n\n\nif __name__ == \"__main__\":\n print(word_count(\"\"))\n print(word_count(\"Hello\"))\n print(word_count('Hello, my cat. And my cat doesn\\'t say \"hello\" back.'))\n print(word_count('This is a test of the emergency broadcast network. This is only a test.'))","sub_path":"applications/word_count/word_count.py","file_name":"word_count.py","file_ext":"py","file_size_in_byte":739,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"550494431","text":"import unittest\ndef product(x,y):\n n=len(\"%d\"%x)\n if n==1:\n return x*y\n else:\n m=10**(n/2)\n b=x%m\n a=(x-b)/m\n d=y%m\n c=(y-d)/m\n first=product(a,c)\n second=product(b,d)\n third=product(a+b,c+d)-first-second\n return m*m*first+second+m*third\n\nclass product_test(unittest.TestCase):\n def test(self):\n print(product(12354,5678))\n\nif __name__=='__main__':\n unittest.main()\n","sub_path":"Karatsuba.py","file_name":"Karatsuba.py","file_ext":"py","file_size_in_byte":458,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"516322202","text":"import pygame\nfrom pygame import *\nfrom systemState import systemState\nfrom systemState import gameObject\nfrom level import level\n\n\nclass gameWorldState(object):\n\n\n def __init__(self, joystickList, screenSize, systemState):\n self.font1 = pygame.font.SysFont(\"arial\", 50)\n self.joystickList = joystickList\n self.screenSize = screenSize\n self.systemState = systemState\n\n self.gameNodesList = []\n self.createNodes()\n\n self.playerSprite = pygame.sprite.Sprite()\n self.playerSprite.image = pygame.image.load(\"still//fire01.png\").convert_alpha()\n self.playerSprite.image = pygame.transform.scale(self.playerSprite.image, (50,50))\n self.playerPos = self.gameNodesList[0]\n \n self.moving = False\n self.deltaX = 0\n self.deltaY = 0\n\n # Update a las variables relevantes\n def update(self, elapsedTime):\n\n # Parametros de iteracion\n playerInNode = self.playerInNode()\n temporalXDirection = 0\n temporalYDirection = 0\n \n # Botones de eleccion\n if len(self.joystickList) == 2:\n levelSelectionButton = self.joystickList[1].get_button(0) or self.joystickList[0].get_button(0)\n goBackButton = self.joystickList[1].get_button(1) or self.joystickList[0].get_button(1)\n else:\n levelSelectionButton = self.joystickList[0].get_button(0)\n goBackButton = self.joystickList[0].get_button(1)\n if levelSelectionButton and not self.moving:\n self.systemState.changeState(\"playState\") \n if self.playerPos == self.gameNodesList[0]:\n actualPath = \"levels//test.txt\"\n self.systemState.currentState.currentLevel = level(self.joystickList, self.screenSize, actualPath)\n self.systemState.currentState.actualPath = \"levels//test.txt\"\n if self.playerPos == self.gameNodesList[1]:\n actualPath = \"levels//ex1.txt\"\n self.systemState.currentState.currentLevel = level(self.joystickList, self.screenSize, actualPath)\n self.systemState.currentState.actualPath = \"levels//ex1.txt\"\n if self.playerPos == self.gameNodesList[2]:\n actualPath = \"levels//castle2.txt\"\n self.systemState.currentState.currentLevel = level(self.joystickList, self.screenSize, actualPath)\n self.systemState.currentState.actualPath = \"levels//castle2.txt\"\n if self.playerPos == self.gameNodesList[3]:\n actualPath = \"levels//level1.txt\"\n self.systemState.currentState.currentLevel = level(self.joystickList, self.screenSize, actualPath)\n self.systemState.currentState.actualPath = \"levels//level1.txt\"\n if self.playerPos == self.gameNodesList[4]:\n actualPath = \"levels//level3.txt\"\n self.systemState.currentState.currentLevel = level(self.joystickList, self.screenSize, actualPath)\n self.systemState.currentState.actualPath = \"levels//level3.txt\"\n if self.playerPos == self.gameNodesList[5]: \n actualPath = \"levels//castle.txt\"\n self.systemState.currentState.currentLevel = level(self.joystickList, self.screenSize, actualPath)\n self.systemState.currentState.actualPath = \"levels//castle.txt\"\n elif goBackButton:\n self.systemState.changeState(\"titleState\")\n\n # Obtiene si player apreto boton para desplazarse\n if abs(self.joystickList[0].get_axis(0)) > 0.3 and not self.moving and playerInNode:##\n temporalXDirection = self.joystickList[0].get_axis(0)##\n elif abs(self.joystickList[0].get_axis(1)) > 0.3 and not self.moving and playerInNode:##\n temporalYDirection = self.joystickList[0].get_axis(1)##\n\n # Se encarga de los desplazamientos\n if temporalXDirection > 0 and self.playerPos[0] != self.gameNodesList[2][0]:\n self.startMoving(self.playerPos, (self.playerPos[0] + 300, self.playerPos[1]))\n elif temporalXDirection < 0 and self.playerPos[0] != self.gameNodesList[0][0]:\n self.startMoving(self.playerPos, (self.playerPos[0] - 300, self.playerPos[1] + 1))\n\n if temporalYDirection < 0 and self.playerPos[1] != self.gameNodesList[0][1]:\n self.startMoving(self.playerPos, (self.playerPos[0], self.playerPos[1] - 200))\n elif temporalYDirection > 0 and self.playerPos[1] != self.gameNodesList[5][1]:\n self.startMoving(self.playerPos, (self.playerPos[0], self.playerPos[1] + 200))\n\n # Si se esta moviendo de un nodo a otro\n if self.moving:\n self.updateMovement()\n\n\n # Dibuja sprite\n def render(self):\n screen = pygame.display.get_surface()\n screen.fill((244, 164, 69))\n \n textSurf = self.font1.render(\"GAME WORLD\" , True,(0, 0, 0))\n screen.blit(textSurf, (self.screenSize[0] / 2 - 150, 50))\n\n pygame.draw.circle(screen, (0,0,255), self.gameNodesList[0], 20)\n pygame.draw.circle(screen, (0,0,255), self.gameNodesList[1], 20)\n pygame.draw.circle(screen, (0,0,255), self.gameNodesList[2], 20)\n pygame.draw.circle(screen, (0,0,255), self.gameNodesList[3], 20)\n pygame.draw.circle(screen, (0,0,255), self.gameNodesList[4], 20)\n pygame.draw.circle(screen, (0,0,255), self.gameNodesList[5], 20)\n\n screen.blit(self.playerSprite.image, self.playerPos)\n \n # Nodos donde se ubicaran visualmente los iconos a seleccionar\n def createNodes(self): \n self.gameNodesList = [(200, 300), (500, 300), (800, 300), (800, 500), (500, 500), (200, 500)]\n\n def playerInNode(self):\n if self.playerPos == self.gameNodesList[0] or self.playerPos == self.gameNodesList[1] or self.playerPos == self.gameNodesList[2] or self.playerPos == self.gameNodesList[3] or self.playerPos == self.gameNodesList[4] or self.playerPos == self.gameNodesList[5]:\n return True\n return False\n\n def startMoving(self, initialNode, finalNode):\n self.moving = True\n if finalNode[0] != initialNode[0]:\n self.deltaX = (finalNode[0] - initialNode[0]) / 10\n elif finalNode[1] != initialNode[1]:\n self.deltaY = (finalNode[1] - initialNode[1]) / 10\n\n def updateMovement(self):\n\n self.playerPos = (self.playerPos[0] + self.deltaX, self.playerPos[1] + self.deltaY)\n \n if self.playerInNode():\n self.deltaX = 0\n self.deltaY = 0\n self.moving = False\n\n \n\n","sub_path":"backup/gameWorldState.py","file_name":"gameWorldState.py","file_ext":"py","file_size_in_byte":6582,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"617940914","text":"import sys\r\nimport numpy as np\r\nimport cv2\r\n\r\n\r\n# 영상 불러오기\r\nsrc1 = cv2.imread('graf1.png', cv2.IMREAD_GRAYSCALE)\r\nsrc2 = cv2.imread('graf3.png', cv2.IMREAD_GRAYSCALE)\r\n\r\nif src1 is None or src2 is None:\r\n print('Image load failed!')\r\n sys.exit()\r\n\r\n# 특징점 알고리즘 객체 생성 (KAZE, AKAZE, ORB 등)\r\nfeature = cv2.KAZE_create()\r\n#feature = cv2.AKAZE_create()\r\n#feature = cv2.ORB_create()\r\n\r\n# 특징점 검출 및 기술자 계산\r\nkp1, desc1 = feature.detectAndCompute(src1, None)\r\nkp2, desc2 = feature.detectAndCompute(src2, None)\r\n\r\n# 특징점 매칭\r\nmatcher = cv2.BFMatcher_create()\r\n#matcher = cv2.BFMatcher_create(cv2.NORM_HAMMING)\r\nmatches = matcher.knnMatch(desc1, desc2, 2)\r\n\r\n# 좋은 매칭 결과 선별\r\ngood_matches = []\r\nfor m in matches:\r\n if m[0].distance / m[1].distance < 0.7:\r\n good_matches.append(m[0])\r\n\r\nprint('# of kp1:', len(kp1))\r\nprint('# of kp2:', len(kp2))\r\nprint('# of matches:', len(matches))\r\nprint('# of good_matches:', len(good_matches))\r\n\r\n# 특징점 매칭 결과 영상 생성\r\ndst = cv2.drawMatches(src1, kp1, src2, kp2, good_matches, None)\r\n\r\ncv2.imshow('dst', dst)\r\ncv2.waitKey()\r\ncv2.destroyAllWindows()\r\n","sub_path":"good_match2.py","file_name":"good_match2.py","file_ext":"py","file_size_in_byte":1188,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"297887267","text":"# Copyright ClusterHQ Inc. See LICENSE file for details.\n# -*- test-case-name: flocker.control.test.test_diffing -*-\n\n\"\"\"\nCode to calculate the difference between objects. This is particularly useful\nfor computing the difference between deeply pyrsisistent objects such as the\nflocker configuration or the flocker state.\n\"\"\"\n\nfrom pyrsistent import (\n PClass,\n PMap,\n PSet,\n field,\n pvector,\n pvector_field,\n)\n\nfrom zope.interface import Interface, implementer\n\n\nclass _IDiffChange(Interface):\n \"\"\"\n Interface for a diff change.\n\n This is simply something that can be applied to an object to create a new\n object.\n\n This interface is created as documentation rather than for any of the\n actual zope.interface mechanisms.\n \"\"\"\n\n def apply(obj):\n \"\"\"\n Apply this diff change to the passed in object and return a new object\n that is obj with the ``self`` diff applied.\n\n :param object obj: The object to apply the diff to.\n\n :returns: A new object that is the passed in object with the diff\n applied.\n \"\"\"\n\n\n@implementer(_IDiffChange)\nclass _Remove(PClass):\n \"\"\"\n A ``_IDiffChange`` that removes an object from a ``PSet`` or a key from a\n ``PMap`` inside a nested object tree.\n\n :ivar path: The path in the nested object tree of the object to be removed\n from the import set.\n\n :ivar item: The item to be removed from the set or the key to be removed\n from the mapping.\n \"\"\"\n path = pvector_field(object)\n item = field()\n\n def apply(self, obj):\n return obj.transform(self.path, lambda o: o.remove(self.item))\n\n\n@implementer(_IDiffChange)\nclass _Set(PClass):\n \"\"\"\n A ``_IDiffChange`` that sets a field in a ``PClass`` or sets a key in a\n ``PMap``.\n\n :ivar path: The path in the nested object to the field/key to be set to a\n new value.\n\n :ivar value: The value to set the field/key to.\n \"\"\"\n path = pvector_field(object)\n value = field()\n\n def apply(self, obj):\n return obj.transform(self.path, self.value)\n\n\n@implementer(_IDiffChange)\nclass _Add(PClass):\n \"\"\"\n A ``_IDiffChange`` that adds an item to a ``PSet``.\n\n :ivar path: The path to the set to which the item will be added.\n\n :ivar item: The item to be added to the set.\n \"\"\"\n path = pvector_field(object)\n item = field()\n\n def apply(self, obj):\n return obj.transform(self.path, lambda x: x.add(self.item))\n\n\n@implementer(_IDiffChange)\nclass Diff(PClass):\n \"\"\"\n A ``_IDiffChange`` that is simply the serial application of other diff\n changes.\n\n This is the object that external modules get and use to apply diffs to\n objects.\n\n :ivar changes: A vector of ``_IDiffChange`` s that represent a diff between\n two objects.\n \"\"\"\n\n changes = pvector_field(object)\n\n def apply(self, obj):\n for c in self.changes:\n obj = c.apply(obj)\n return obj\n\n\ndef _create_diffs_for_sets(current_path, set_a, set_b):\n \"\"\"\n Computes a series of ``_IDiffChange`` s to turn ``set_a`` into ``set_b``\n assuming that these sets are at ``current_path`` inside a nested pyrsistent\n object.\n\n :param current_path: An iterable of pyrsistent object describing the path\n inside the root pyrsistent object where the other arguments are\n located. See ``PMap.transform`` for the format of this sort of path.\n\n :param set_a: The desired input set.\n\n :param set_b: The desired output set.\n\n :returns: An iterable of ``_IDiffChange`` s that will turn ``set_a`` into\n ``set_b``.\n \"\"\"\n resulting_diffs = pvector([]).evolver()\n for item in set_a.difference(set_b):\n resulting_diffs.append(\n _Remove(path=current_path, item=item)\n )\n for item in set_b.difference(set_a):\n resulting_diffs.append(\n _Add(path=current_path, item=item)\n )\n return resulting_diffs.persistent()\n\n\ndef _create_diffs_for_mappings(current_path, mapping_a, mapping_b):\n \"\"\"\n Computes a series of ``_IDiffChange`` s to turn ``mapping_a`` into\n ``mapping_b`` assuming that these mappings are at ``current_path`` inside a\n nested pyrsistent object.\n\n :param current_path: An iterable of pyrsistent object describing the path\n inside the root pyrsistent object where the other arguments are\n located. See ``PMap.transform`` for the format of this sort of path.\n\n :param mapping_a: The desired input mapping.\n\n :param mapping_b: The desired output mapping.\n\n :returns: An iterable of ``_IDiffChange`` s that will turn ``mapping_a``\n into ``mapping_b``.\n \"\"\"\n resulting_diffs = pvector([]).evolver()\n a_keys = frozenset(mapping_a.keys())\n b_keys = frozenset(mapping_b.keys())\n for key in a_keys.intersection(b_keys):\n if mapping_a[key] != mapping_b[key]:\n resulting_diffs.extend(\n _create_diffs_for(\n current_path.append(key),\n mapping_a[key],\n mapping_b[key]\n )\n )\n for key in b_keys.difference(a_keys):\n resulting_diffs.append(\n _Set(path=current_path.append(key), value=mapping_b[key])\n )\n for key in a_keys.difference(b_keys):\n resulting_diffs.append(\n _Remove(path=current_path, item=key)\n )\n return resulting_diffs.persistent()\n\n\ndef _create_diffs_for(current_path, subobj_a, subobj_b):\n \"\"\"\n Computes a series of ``_IDiffChange`` s to turn ``subobj_a`` into\n ``subobj_b`` assuming that these subobjs are at ``current_path`` inside a\n nested pyrsistent object.\n\n :param current_path: An iterable of pyrsistent object describing the path\n inside the root pyrsistent object where the other arguments are\n located. See ``PMap.transform`` for the format of this sort of path.\n\n :param subobj_a: The desired input sub object.\n\n :param subobj_b: The desired output sub object.\n\n :returns: An iterable of ``_IDiffChange`` s that will turn ``subobj_a``\n into ``subobj_b``.\n \"\"\"\n if subobj_a == subobj_b:\n return pvector([])\n elif type(subobj_a) != type(subobj_b):\n return pvector([_Set(path=current_path, value=subobj_b)])\n elif isinstance(subobj_a, PClass) and isinstance(subobj_b, PClass):\n a_dict = subobj_a._to_dict()\n b_dict = subobj_b._to_dict()\n return _create_diffs_for_mappings(current_path, a_dict, b_dict)\n elif isinstance(subobj_a, PMap) and isinstance(subobj_b, PMap):\n return _create_diffs_for_mappings(\n current_path, subobj_a, subobj_b)\n elif isinstance(subobj_a, PSet) and isinstance(subobj_b, PSet):\n return _create_diffs_for_sets(\n current_path, subobj_a, subobj_b)\n # If the objects are not equal, and there is no intelligent way to recurse\n # inside the objects to make a smaller diff, simply set the current path\n # to the object in b.\n return pvector([_Set(path=current_path, value=subobj_b)])\n\n\ndef create_diff(object_a, object_b):\n \"\"\"\n Constructs a diff from ``object_a`` to ``object_b``\n\n :param object_a: The desired input object.\n\n :param object_b: The desired output object.\n\n :returns: A ``Diff`` that will convert ``object_a`` into ``object_b``\n when applied.\n \"\"\"\n changes = _create_diffs_for(pvector([]), object_a, object_b)\n return Diff(changes=changes)\n\n\ndef compose_diffs(iterable_of_diffs):\n \"\"\"\n Compose multiple ``Diff`` objects into a single diff.\n\n Assuming you have 3 objects, A, B, and C and you compute diff AB and BC.\n If you pass [AB, BC] into this function it will return AC, a diff that when\n applied to object A, will return C.\n\n :param iterable_of_diffs: An iterable of diffs to be composed.\n\n :returns: A new diff such that applying this diff is equivalent to applying\n each of the input diffs in serial.\n \"\"\"\n return Diff(\n changes=reduce(\n lambda x, y: x.extend(y.changes),\n iterable_of_diffs,\n pvector().evolver()\n ).persistent()\n )\n\n\n# Ensure that the representation of a ``Diff`` is entirely serializable:\nDIFF_SERIALIZABLE_CLASSES = [\n _Set, _Remove, _Add, Diff\n]\n","sub_path":"flocker/control/_diffing.py","file_name":"_diffing.py","file_ext":"py","file_size_in_byte":8284,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"210415763","text":"import random # 난수 생성\r\nimport math # 수학 함수(sqrt)\r\n\r\n\r\ndef monte_carlo(n):\r\n \"\"\"\r\n Monte Carlo 시뮬레이션을 통해서 1/4 원의 면적을 확률적으로 계산하고,\r\n pi의 근사값을 리턴.\r\n\r\n :param n: int. 시행 횟수\r\n :return: pi 근사값\r\n \"\"\"\r\n hit = 0 # 난수로 생성한 점이 원 안에 있게 될 확률을 계산하기 위한 변수.\r\n for _ in range(n):\r\n # 0 <= x, y < 1 난수를 생성\r\n x, y = random.random(), random.random()\r\n if math.sqrt(x ** 2 + y ** 2) <= 1:\r\n # (x, y)가 반지름 1인 원의 내부에 속한다면,\r\n hit += 1 # hit의 개수를 1 증가시킴.\r\n\r\n # hit는 1/4원 안에 있는 점들의 개수이므로, pi의 근사값은 x4를 함.\r\n return 4 * (hit / n)\r\n\r\n\r\nif __name__ == '__main__':\r\n for n in range(1, 7):\r\n pi = monte_carlo(10 ** n)\r\n print(f'n = {10 ** n}, pi = {pi}')\r\n","sub_path":"lab-python/py03_function/function05.py","file_name":"function05.py","file_ext":"py","file_size_in_byte":953,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"571664965","text":"# Um professor quer sortear um dos seus quatro alunos para apagar o quadro. \n# Faça um programa que ajude ele, lendo o nome dos alunos e escrevendo na tela o nome do escolhido.\n\nfrom random import choice\n\nlista = [\"Lucas\", \"Raquel\", \"Camila\", \"Marcela\", \"Jacqueline\", \"Esmeraldino\"]\n\nsorteio = choice(lista)\n\nprint(\"\\n______________________{}______________________\\n\".format(sorteio))","sub_path":"b-usandoModulos/ex-019.py","file_name":"ex-019.py","file_ext":"py","file_size_in_byte":385,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"340238022","text":"# -*- coding: utf-8 -*-\n\nfrom spider36kr.items import Spider36KrItem\nimport re\nimport logging\nimport pymongo\nimport pymysql\nimport redis\nfrom scrapy.exceptions import DropItem\n\n\nclass Spider36KrPipeline(object):\n def __init__(self):\n self.logger = logging.getLogger(__name__)\n\n def process_item(self, item, spider):\n if isinstance(item, Spider36KrItem):\n if item.get('article_tags'):\n item['article_tags'] = self.parse_tags(item.get('article_tags'))\n if item.get('article_content'):\n item['article_content'] = self.parse_content(item.get('article_content'))\n if item.get('article_summary'):\n item['article_summary'] = item.get('article_summary').replace(' ', '')\n if item.get('article_title'):\n item['article_title'] = item.get('article_title').replace(' ', '')\n if item.get('writer_role') == '读者':\n item['writer_role'] = ''\n return item\n\n def parse_tags(self, origin_tags):\n tag = re.sub(r'\\d+\\],?|\\[|\\]|\\\"', '', origin_tags).rstrip(',')\n tags = eval(\"u\" + \"\\'\" + tag + \"\\'\")\n return tags\n\n def parse_content(self, origin_content):\n article_content = re.sub(r'|||

.*?

|

|

||\\n|\\t|\\s', '',\n origin_content)\n return article_content\n\n\nclass MongoPipeline(object):\n def __init__(self, mongo_uri, mongo_db):\n self.logger = logging.getLogger(__name__)\n self.mongo_uri = mongo_uri\n self.mongo_db = mongo_db\n\n @classmethod\n def from_crawler(cls, crawler):\n return cls(\n mongo_uri=crawler.settings.get('MONGO_URI'),\n mongo_db=crawler.settings.get('MONGO_DB')\n )\n\n def open_spider(self, spider):\n self.client = pymongo.MongoClient(self.mongo_uri)\n self.db = self.client[self.mongo_db]\n\n def process_item(self, item, spider):\n if isinstance(item, Spider36KrItem):\n self.db[item.collection].update({'article_id': item.get('article_id')}, {'$set': dict(item)}, True)\n self.logger.info('ID: %s 的新闻已经插入到mogondb中' % item.get('article_id'))\n return item\n\n def close_spider(self, spider):\n self.client.close()\n\n\nclass RedisPipeline(object):\n def __init__(self, host, port, db):\n self.host = host\n self.port = port\n self.db = db\n\n @classmethod\n def from_crawler(cls, crawler):\n return cls(\n host=crawler.settings.get('REDIS_HOST'),\n port=crawler.settings.get('REDIS_PORT'),\n db=crawler.settings.get('REDIS_DB')\n )\n\n def open_spider(self, spider):\n self.redis_db = redis.StrictRedis(self.host, self.port, self.db, decode_responses=True)\n\n def process_item(self, item, spider):\n redis_data_url = {'36kr': 'url'}\n if self.redis_db.hexists(redis_data_url, item.get('article_url')):\n raise DropItem(\"Duplicate item found:%s\" % item.get('article_url'))\n else:\n self.redis_db.hset(redis_data_url, item.get('article_url'), 0)\n return item\n","sub_path":"spider36kr/spider36kr/pipelines.py","file_name":"pipelines.py","file_ext":"py","file_size_in_byte":3193,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"487917874","text":"\"\"\"\nhttps://leetcode.com/problems/summary-ranges/description/\n\"\"\"\nclass Solution(object):\n def summaryRanges(self, nums):\n return summary(nums)\n\ndef summary(nums):\n if not nums:\n return []\n result = []\n prev = nums[0]\n start=prev\n for x in nums[1:]:\n if x!=prev+1:\n result.append(make(start, prev))\n start = x\n prev = x\n result.append(make(start, prev))\n return result\n\ndef make(x, y):\n if x==y:\n return str(x)\n return str(x) + \"->\" + str(y)","sub_path":"sumary_range.py","file_name":"sumary_range.py","file_ext":"py","file_size_in_byte":528,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"126006069","text":"import zope.interface\nimport zope.component\n\nimport grok\n\nimport martian\nfrom martian.error import GrokError\nfrom martian import util\n\nimport mars.adapter\n\nclass AdapterFactoryGrokker(martian.ClassGrokker):\n component_class = mars.adapter.AdapterFactory\n\n def grok(self, name, factory, module_info, config, *kws):\n name = util.class_annotation(factory, 'grok.name', '')\n adapter_factory = util.class_annotation(\n factory, 'mars.adapter.factory', None)\n provides = zope.component.registry._getAdapterProvided(adapter_factory)\n adapter_context = zope.component.registry._getAdapterRequired(\n adapter_factory, None)\n\n #print '\\n',name,'\\n',adapter_factory,'\\n',provides,'\\n',adapter_context\n\n if adapter_factory is None:\n raise GrokError(\n \"mars.adapter.factory must be provided for AdapterFactory\"\n )\n else:\n config.action( \n discriminator=('adapter', adapter_context[0], provides, name),\n callable=zope.component.provideAdapter,\n args=(adapter_factory, adapter_context, provides, name),\n )\n\n return True\n","sub_path":"Sandbox/darrylcousins/tfws.website/mars.adapter/mars/adapter/meta.py","file_name":"meta.py","file_ext":"py","file_size_in_byte":1255,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"585236524","text":"# Autor: Jonathan Sanabria Rocha, A01746763\n# Descripcion: Problema de auto con formula v=d/t , uso de format.\n\n# Escribe tu programa después de esta línea.\nvelocidad= float(input(\"Dame la velocidad del auto en km/h:\"))\ntiempo= float(input(\"Dame el tiempo de recorrido del auto en horas:\"))\ndistancia=(float(velocidad)/float(tiempo))\ntiempo1= input(\"Dame el tiempo de recorrido del auto en horas: \")\ndistancia1=(float(velocidad)/float(tiempo1))\ndistancia2=input(\"Dame la distancia que recorrera el auto: \")\ntiempo2=(float(distancia2)/float(velocidad))\nprint(\"Velocidad del auto en km/h= \",format(velocidad,\".1f\")+\" km/h\")\nprint(\"Distancia recorrida en \"+str(float(tiempo))+\" hrs:=\",format(distancia,\".1f\")+\" km\")\nprint(\"Distancia recorrida en \"+str(float(tiempo1))+\" hrs:=\",format(distancia1,\".1f\")+\" km\")\nprint(\"Tiempo para recorrer \"+str(float(distancia2))+\" km:=\",format(tiempo2,\".1f\")+\" hrs\")\n","sub_path":"auto.py","file_name":"auto.py","file_ext":"py","file_size_in_byte":899,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"80085451","text":"\"\"\"Clears the screen, and displays the header.\"\"\"\n\nimport os\n\n\ndef clear_host():\n \"\"\"Clear the screen.\"\"\"\n if os.name == 'nt': # For windows systems.\n _ = os.system('cls')\n else: # For Mac & Linux.\n _ = os.system('clear')\n\n print(\" ---------------------------------------\")\n print(\" Substituts alimentaires \")\n print(\" ---------------------------------------\\n\\n\")\n","sub_path":"app/view/clear_host.py","file_name":"clear_host.py","file_ext":"py","file_size_in_byte":435,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"474688925","text":"from random import random\n\n\nclass MapGraph:\n def __init__(self, room): # populate what is known in connections\n self.cxn, self.cxn[room.id] = {}, {}\n for out in sorted(room.getExits(), key=lambda _: random()):\n self.cxn[room.id][out] = '?'\n\n def populate_known_areas(self, room, move, previous_room):\n if room.id not in self.cxn:\n self.cxn[room.id] = {} # create new room in connections\n for out in sorted(room.getExits(), key=lambda _: random()):\n if out not in self.cxn[room.id].keys():\n self.cxn[room.id][out] = '?' # find and populate unknown exits\n for out in previous_room.getExits():\n if out == move: # replace '?' with known numbers if we moved from there\n self.cxn[previous_room.id][out] = room.id\n self.cxn[room.id][{'n': 's', 's': 'n', 'e': 'w', 'w': 'e'}[\n move]] = previous_room.id # add reverse direction to previous room\n\n def path_to_next_q(self, room): # Path like ['n', 'n'] to the closest ?\n visited, arr = [], [[{room.id: None}]]\n while arr:\n path = arr.pop(0) # BFS only searching\n address = list(path[-1].keys())[0]\n if address not in visited:\n for news in self.cxn[address]:\n new_path = list(path)\n new_path.append({self.cxn[address][news]: news})\n arr.append(new_path)\n if self.cxn[address][news] == '?':\n return [list(step.values())[0] for step in new_path[1:]]\n visited.append(address)\n return False # no '?'s left\n\n\ndef traverse_all(player):\n path, rooms = [], MapGraph(player.currentRoom)\n s_path = rooms.path_to_next_q(player.currentRoom)\n while s_path: # Master app loop, while ? exist\n for step in s_path:\n previous_room = player.currentRoom\n player.travel(step)\n rooms.populate_known_areas(player.currentRoom, step, previous_room)\n path = path + s_path\n s_path = rooms.path_to_next_q(player.currentRoom)\n return path\n","sub_path":"projects/adventure/findpath.py","file_name":"findpath.py","file_ext":"py","file_size_in_byte":2159,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"139744288","text":"#standart ağ\nfrom keras.layers import Dense,Dropout,Conv3D,Input,MaxPool3D,Flatten,Activation,ZeroPadding3D,AveragePooling3D\nfrom keras.regularizers import l2\nfrom keras.models import Model\nimport random\nimport numpy as np\nimport cv2\nimport os\nfrom keras.optimizers import SGD, Adam, Adagrad\nfrom keras.utils import np_utils\nimport matplotlib\nmatplotlib.use('AGG')\nimport matplotlib.pyplot as plt\nfrom keras.layers import LeakyReLU\nfrom keras.layers import add\nimport keras.backend as K\nfrom keras.callbacks import Callback, ModelCheckpoint\nimport yaml\nimport h5py\nimport numpy as np\nimport keras.backend as K\nfrom keras.callbacks import Callback, ModelCheckpoint\nimport yaml\nimport h5py\nimport numpy as np\n\nclass Step(Callback):\n\n def __init__(self, steps, learning_rates, verbose=0):\n self.steps = steps\n self.lr = learning_rates\n self.verbose = verbose\n\n def change_lr(self, new_lr):\n old_lr = K.get_value(self.model.optimizer.lr)\n K.set_value(self.model.optimizer.lr, new_lr)\n if self.verbose == 1:\n print('Learning rate is %g' %new_lr)\n\n def on_epoch_begin(self, epoch, logs={}):\n for i, step in enumerate(self.steps):\n if epoch < step:\n self.change_lr(self.lr[i])\n return\n self.change_lr(self.lr[i+1])\n\n def get_config(self):\n config = {'class': type(self).__name__,\n 'steps': self.steps,\n 'learning_rates': self.lr,\n 'verbose': self.verbose}\n return config\n\n @classmethod\n def from_config(cls, config):\n offset = config.get('epoch_offset', 0)\n steps = [step - offset for step in config['steps']]\n return cls(steps, config['learning_rates'],\n verbose=config.get('verbose', 0))\n\ndef plot_history(history, result_dir):\n plt.plot(history.history['accuracy'], marker='.')\n plt.plot(history.history['val_accuracy'], marker='.')\n plt.title('model accuracy')\n plt.xlabel('epoch')\n plt.ylabel('accuracy')\n plt.grid()\n plt.legend(['acc', 'val_accuracy'], loc='lower right')\n plt.savefig(os.path.join(result_dir, 'model_accuracy.png'))\n plt.close()\n\n plt.plot(history.history['loss'], marker='.')\n plt.plot(history.history['val_loss'], marker='.')\n plt.title('model loss')\n plt.xlabel('epoch')\n plt.ylabel('loss')\n plt.grid()\n plt.legend(['loss', 'val_loss'], loc='upper right')\n plt.savefig(os.path.join(result_dir, 'model_loss.png'))\n plt.close()\n\n\ndef save_history(history, result_dir):\n loss = history.history['loss']\n acc = history.history['accuracy']\n val_loss = history.history['val_loss']\n val_acc = history.history['val_accuracy']\n nb_epoch = len(acc)\n\n with open(os.path.join(result_dir, 'result.txt'), 'w') as fp:\n fp.write('epoch\\tloss\\tacc\\tval_loss\\tval_acc\\n')\n for i in range(nb_epoch):\n fp.write('{}\\t{}\\t{}\\t{}\\t{}\\n'.format(\n i, loss[i], acc[i], val_loss[i], val_acc[i]))\n fp.close()\n\ndef c3d_model():\n input_shape = (112, 112, 20, 3)\n weight_decay = 0.005\n nb_classes = 101\n\n inputs = Input(input_shape)\n x = Conv3D(64, (3, 3, 3), strides=(1, 1, 1), padding='same',\n activation='relu', kernel_regularizer=l2(weight_decay))(inputs)\n x = MaxPool3D((2, 2, 1), strides=(2, 2, 1), padding='same')(x)\n\n x = Conv3D(128, (3, 3, 3), strides=(1, 1, 1), padding='same',\n activation='relu', kernel_regularizer=l2(weight_decay))(x)\n x = MaxPool3D((2, 2, 2), strides=(2, 2, 2), padding='same')(x)\n\n x = Conv3D(128, (3, 3, 3), strides=(1, 1, 1), padding='same',\n activation='relu', kernel_regularizer=l2(weight_decay))(x)\n x = MaxPool3D((2, 2, 2), strides=(2, 2, 2), padding='same')(x)\n\n x = Conv3D(256, (3, 3, 3), strides=(1, 1, 1), padding='same',\n activation='relu', kernel_regularizer=l2(weight_decay))(x)\n x = MaxPool3D((2, 2, 2), strides=(2, 2, 2), padding='same')(x)\n\n x = Conv3D(256, (3, 3, 3), strides=(1, 1, 1), padding='same',\n activation='relu', kernel_regularizer=l2(weight_decay))(x)\n x = MaxPool3D((2, 2, 2), strides=(2, 2, 2), padding='same')(x)\n\n\n x = Flatten()(x)\n x = Dense(512, input_dim=4096, kernel_initializer='glorot_normal', kernel_regularizer=l2(0.001), activation='relu')(x)\n x = Dropout(0.6)(x)\n x = Dense(32, kernel_initializer='glorot_normal', kernel_regularizer=l2(0.001))(x)\n x = Dropout(0.6)(x)\n x = Dense(4, kernel_initializer='glorot_normal', kernel_regularizer=l2(0.001), activation='softmax')(x)\n\n model = Model(inputs, x)\n return model\ndef generator_train_batch(train_txt, batch_size, img_path):\n ff = open(train_txt, 'r')\n lines = ff.readlines()\n num = len(lines)\n while True:\n new_line = []\n index = [n for n in range(num)]\n random.shuffle(index)\n for m in range(num):\n new_line.append(lines[index[m]])\n for i in range(int(num / batch_size)):\n a = i * batch_size\n b = (i + 1) * batch_size\n x_train, x_labels = process_batch(new_line[a:b], img_path)\n\n x = preprocess(x_train)\n x = np.transpose(x, (0, 2, 3, 1, 4))\n y = np_utils.to_categorical(np.array(x_labels), 4)\n yield x, y\n\ndef generator_val_batch(val_txt, batch_size, img_path):\n f = open(val_txt, 'r')\n lines = f.readlines()\n num = len(lines)\n while True:\n new_line = []\n index = [n for n in range(num)]\n random.shuffle(index)\n for m in range(num):\n new_line.append(lines[index[m]])\n for i in range(int(num / batch_size)):\n a = i * batch_size\n b = (i + 1) * batch_size\n y_test, y_labels = process_batch(new_line[a:b], img_path)\n\n x = preprocess(y_test)\n x = np.transpose(x, (0, 2, 3, 1, 4))\n y = np_utils.to_categorical(np.array(y_labels), 4)\n yield x, y\n\n\ndef process_batch(lines, img_path):\n num = len(lines)\n batch = np.zeros((num, 20, 112, 112, 3), dtype='float32')\n labels = np.zeros(num, dtype='int')\n for i in range(num): # num -- 16\n path = lines[i].split(' ')[0]\n label = lines[i].split(' ')[-1]\n label = label.strip('\\n')\n label = int(label)\n frameNumber = int(lines[i].split(' ')[1])\n for j in range(20):\n try:\n image = cv2.imread(img_path + 'frames/' + path + '/frame' + str((frameNumber)+j) + '.jpg')\n image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)\n image = cv2.resize(image, (171, 128))\n batch[i][j][:][:][:] = image[8:120, 30:142, :]\n except Exception as e:\n print(\"hata\\n\")\n print(img_path + 'Explosion/' + path + '/frame' + str((frameNumber) + j) + '.jpg')\n labels[i] = label\n return batch, labels\ndef preprocess(inputs):\n inputs[..., 0] -= 99.9\n inputs[..., 1] -= 92.1\n inputs[..., 2] -= 82.6\n inputs[..., 0] /= 65.8\n inputs[..., 1] /= 62.3\n inputs[..., 2] /= 60.3\n # inputs /=255.\n # inputs -= 0.5\n # inputs *=2.\n return inputs\n\ndef onetenth_4_8_12(lr):\n steps = [4, 8,12]\n lrs = [lr, lr/10, lr/100,lr/1000]\n return Step(steps, lrs)\n\nimg_path = 'C:/Users/onure/PycharmProjects/ImageClassification/'\n\ntrain_file = 'C:/Users/onure/PycharmProjects/ImageClassification/4-1ButunVideolar20-15frameTrain.txt'\ntest_file = 'C:/Users/onure/PycharmProjects/ImageClassification/4-1ButunVideolar20-15frameTest.txt'\n\nf1 = open(train_file, 'r')\nf2 = open(test_file, 'r')\nlines = f1.readlines()\nf1.close()\ntrain_samples = len(lines)\nlines = f2.readlines()\nf2.close()\nval_samples = len(lines)\n\nbatch_size = 2\nepochs = 50\nlearning_rate = 0.001\n\nmodel = c3d_model()\n\nsgd = SGD(lr=learning_rate, momentum=0.9, nesterov=True)\nmodel.compile(optimizer=sgd, loss=\"categorical_crossentropy\",metrics=['accuracy'])\nmodel.summary()\n\nhistory = model.fit_generator(generator_train_batch(train_file, batch_size, img_path),\n steps_per_epoch=train_samples // batch_size,\n epochs=epochs,\n callbacks=[onetenth_4_8_12(learning_rate)],\n validation_data=generator_val_batch(test_file,\n batch_size, img_path),\n validation_steps=val_samples // batch_size,\n verbose=1)\n\n\nmodel.save_weights('C:/Users/onure/PycharmProjects/ImageClassification/4-1Videolar-20-15framellbos.h5')\nplot_history(history, 'C:/Users/onure/PycharmProjects/ImageClassification/')\nsave_history(history, 'C:/Users/onure/PycharmProjects/ImageClassification/')\n\n\n","sub_path":"Bitirme Python Kodları/Ag Denemeleri/Standart ag.py","file_name":"Standart ag.py","file_ext":"py","file_size_in_byte":8772,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"150146461","text":"# leetcode 494--target sum\n\nclass Solution:\n def findTargetSumWays(self, nums: List[int], S: int) -> int:\n # at each step, there are two options:\n # inserting either a plus or a minus sign\n # keep the results that sum up to the target\n # can do this through recursion.\n # can be optimized via memoization\n count = 0\n memo = {}\n \n def helper(idx, nums, curSum, memo):\n # base case\n if (curSum, idx) in memo:\n return memo[(curSum, idx)]\n \n if curSum==S:\n if idx==len(nums):\n return 1\n elif idx>=len(nums):\n return 0\n \n # total count + counts from idx, either adding the next or subtracting the next integer. Keep track of the count from the current idx with current sum.\n count = helper(idx+1, nums, curSum+nums[idx], memo)+helper(idx+1, nums, curSum-nums[idx], memo)\n memo[(curSum,idx)] = count\n \n return count\n \n return helper(0, nums, 0, memo)\n","sub_path":"10-22-20.py","file_name":"10-22-20.py","file_ext":"py","file_size_in_byte":1110,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"13606807","text":"import webapp2, logging\r\nfrom database import get_feed_source_by_name, store_feed_source, \\\r\n get_feed_source_by_url, change_feed_source_url\r\n\r\nclass AddHandler(webapp2.RequestHandler):\r\n def post(self):\r\n from database import FeedSource\r\n name = self.request.get('name')\r\n url = self.request.get('url')\r\n frequency_ms = self.request.get('frequency_ms')\r\n should_update = self.request.get('should_update')\r\n should_be_added = True\r\n existing_source = get_feed_source_by_url(url)\r\n if existing_source:\r\n should_be_added = False\r\n self.response.write( \\\r\n 'The URL (' + url + ') already exists (name - ' + \\\r\n existing_source.name + ').
')\r\n self.response.write('Forgot you added it already? :O')\r\n else:\r\n existing_source = get_feed_source_by_name(name)\r\n if existing_source:\r\n if should_update:\r\n should_be_added = False\r\n change_feed_source_url(existing_source, url)\r\n self.response.write('Updated.')\r\n else:\r\n should_be_added = False\r\n self.response.write('The name (' + name + ') already exists.
')\r\n self.response.write( \\\r\n 'Go back and choose a different name, or tick \"Update?\".
')\r\n \r\n if should_be_added and store_feed_source(name, url, int(frequency_ms)):\r\n self.response.write('Added.');\r\n \r\n def get(self):\r\n from database import FeedSource\r\n self.response.write(\"\"\"Add Feed\r\n
\r\n Name -
\r\n URL -
\r\n Frequency (milliseconds) -\r\n
\r\n \r\n \r\n
\"\"\")","sub_path":"add_handler.py","file_name":"add_handler.py","file_ext":"py","file_size_in_byte":1694,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"311881866","text":"from tkinter import *\r\nimport random\r\n\r\nt = Tk()\r\nt.title(\"Wybierz przycisk\")\r\nt.geometry(\"250x300\")\r\n\r\n\r\ndef wstaw_przyciski():\r\n ile_przyciskow = 8\r\n global przyciski\r\n przyciski = []\r\n dobry = random.randint(0, ile_przyciskow - 1)\r\n for i in range(ile_przyciskow):\r\n if i == dobry:\r\n przyciski.append(Button(t, text=\"trafiony\", command=trafiony))\r\n else:\r\n przyciski.append(Button(t, text=\"pudlo\", command=pudlo))\r\n for i in przyciski:\r\n i.pack(fill=BOTH, expand=YES)\r\n\r\n\r\ndef trafiony():\r\n for i in przyciski:\r\n i.destroy()\r\n global etykieta\r\n etykieta = Label(t, text=\"Trafiłeś dobry przycisk\")\r\n etykieta.pack(fill=BOTH, expand=YES)\r\n t.after(1000, restart)\r\n\r\n\r\ndef pudlo():\r\n for i in przyciski:\r\n i.destroy()\r\n global etykieta\r\n etykieta = Label(t, text=\"Trafiłeś zły przycisk\")\r\n etykieta.pack(fill=BOTH, expand=YES)\r\n t.after(500, restart)\r\n\r\n\r\nwstaw_przyciski()\r\n\r\n\r\ndef restart():\r\n etykieta.destroy()\r\n wstaw_przyciski()\r\n\r\n\r\nt.mainloop()\r\n","sub_path":"gra losowa.py","file_name":"gra losowa.py","file_ext":"py","file_size_in_byte":1070,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"434729576","text":"import pandas as pd\nimport re\n\nuniqueplacement = []\nkeywordallunique = []\nkey = []\nkeywordval = []\nsplitkey = []\nsplitkey1 = []\n\ndf = pd.read_csv('C:\\myfiles\\QA\\grepserpython\\generalscripts_python\\\\flywheel\\\\201906271204-Amazon-com-SOV-Base-2019-06-27.csv', encoding='latin')\n\ndf1 = df['Placement']\ndf2 = df['Keyword']\n\nfor val_plac in df1:\n uniqueplacement.append(val_plac)\n\nunique_plac_grp = df1.groupby(uniqueplacement).size().reset_index(name='count').sort_values(['count'], ascending=False)\nplacindex = unique_plac_grp['index']\nplacindex_len = len(placindex)\n\n\nfor valplacement, valkeyword in zip(df1, df2):\n keywordallunique.append(valkeyword)\n\n for plac_val in range(1, placindex_len):\n if valplacement in placindex[plac_val]:\n key.append((valplacement, valkeyword))\nabc = set(key)\nfor valls in abc:\n splitkey.append(valls)\ndfnew = pd.DataFrame(splitkey)\nkeyw = dfnew[0]\nplac = dfnew[1]\nunique_placement = dfnew.groupby(keyw).size().reset_index(name='count').sort_values(['count'], ascending=False)\n# unique_keyword = dfnew.groupby(plac).size().reset_index(name='count').sort_values(['count'], ascending=False)\nprint(unique_placement)\n\n","sub_path":"generalscripts_python/flywheel/keywordsample.py","file_name":"keywordsample.py","file_ext":"py","file_size_in_byte":1173,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"286763375","text":"import urllib.request\nfrom bs4 import BeautifulSoup\nimport pymysql.cursors\nfrom pyfcm import FCMNotification\n\n\n\n# file에서 최근 값을 불러오기(db에서 불러오는 걸로 바꿔도 될 듯)\nf = open(\"khu_ce_file.txt\", mode =\"rt\", encoding=\"utf-8\")\nRECENT_POST_NUMBER = f.read()\nf.close()\n\nRESULT_POST_NUMBER = RECENT_POST_NUMBER\n\n# url로 html 문서 받아오기 \nwith urllib.request.urlopen(\"http://ce.khu.ac.kr/index.php?hCode=BOARD&bo_idx=2\") as r :\n soup = BeautifulSoup(r, \"html.parser\")\n\n # 안에 게시물 데이터가 담기므로 그 안에서 데이터 추출\n for post in soup.body.table.find_all(\"tr\")[1:] :\n ID = post.contents[1].get_text()\n if ID > RECENT_POST_NUMBER :\n NAME = post.contents[3].get_text()\n DATE = post.contents[9].get_text()\n URL = \"http://ce.khu.ac.kr/index.php\" + post.find(\"a\")[\"href\"]\n # db(mysql)와 연결\n connection = pymysql.connect(host = 'localhost', port = 3306, user='root', passwd='1879', db = 'khu_alarm', charset='utf8')\n \n # 파일에 쓸 가장 최근 업로드된 데이터를 저장 \n if RESULT_POST_NUMBER < ID:\n RESULT_POST_NUMBER = ID\n \n # 데이터 미리보기\n print(ID) #번호\n print(NAME) #게시물이름\n print(DATE) #게시일\n print(URL) #링크\n # db에 데이터 저장\n try :\n with connection.cursor() as cursor :\n # 게시물 삽입\n sql = \"INSERT INTO `khu_ce_notice` (`id`, `name`, `date`, `url`) VALUES (%s,%s,%s,%s)\"\n cursor.execute(sql,(ID, NAME, DATE, URL))\n connection.commit()\n \n # 게시물 100개 이상이면 삭제\n sql = \"DELETE FROM `khu_ce_notice` WHERE `id` = %s\"\n cursor.execute(sql, str(int(RESULT_POST_NUMBER) - 100))\n connection.commit()\n\n push_service = FCMNotification(api_key=\"AAAAoGJSySI:APA91bHRE9XHGAkjrCtoiZJPhbXxs7C0dgjbMzWZmZWLnRLYk3j9ZFr80whPyhrPWWYZV4-vQe3nzIw2RlltlyU__GXshnmTLx4b6ZcpPM94VAN_vllU_cLlnrHG2neXyi5n1rswaiDN\")\n sql = \"SELECT * from `push`\"\n cursor.execute(sql)\n rows = cursor.fetchall()\n registration_ids = []\n for row in rows :\n registration_ids.append(row[0])\n print(registration_ids)\n message_title = \"klaser\"\n message_body = NAME\n result = push_service.notify_multiple_devices(registration_ids=registration_ids, message_title=message_title, message_body=message_body)\n print(result)\n finally:\n connection.close()\n \n \n\n\n# 변경점이 없을 경우\nif RESULT_POST_NUMBER == RECENT_POST_NUMBER :\n print(\"NOT Chaged\")\n\n\nf = open(\"khu_ce_file.txt\", mode =\"wt\", encoding =\"utf-8\")\nf.write(RESULT_POST_NUMBER)\nf.close()\n","sub_path":"crawler/khu_ce_crawler.py","file_name":"khu_ce_crawler.py","file_ext":"py","file_size_in_byte":3131,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"537159449","text":"\"\"\"\n================================\nCompute ICA components on epochs\n================================\n\nICA is fit to MEG raw data.\nWe assume that the non-stationary EOG artifacts have already been removed.\nThe sources matching the ECG are automatically found and displayed.\n\n.. note:: This example does quite a bit of processing, so even on a\n fast machine it can take about a minute to complete.\n\"\"\"\n\n# Authors: Denis Engemann \n#\n# License: BSD (3-clause)\n\nimport mne\nfrom mne.preprocessing import ICA, create_ecg_epochs\nfrom mne.datasets import sample\n\nprint(__doc__)\n\n###############################################################################\n# Read and preprocess the data. Preprocessing consists of:\n#\n# - MEG channel selection\n# - 1-30 Hz band-pass filter\n# - epoching -0.2 to 0.5 seconds with respect to events\n# - rejection based on peak-to-peak amplitude\n\ndata_path = sample.data_path()\nraw_fname = data_path + '/MEG/sample/sample_audvis_filt-0-40_raw.fif'\n\nraw = mne.io.read_raw_fif(raw_fname)\nraw.pick_types(meg=True, eeg=False, exclude='bads', stim=True).load_data()\nraw.filter(1, 30, fir_design='firwin')\n\n# peak-to-peak amplitude rejection parameters\nreject = dict(grad=4000e-13, mag=4e-12)\n# longer + more epochs for more artifact exposure\nevents = mne.find_events(raw, stim_channel='STI 014')\nepochs = mne.Epochs(raw, events, event_id=None, tmin=-0.2, tmax=0.5,\n reject=reject)\n\n###############################################################################\n# Fit ICA model using the FastICA algorithm, detect and plot components\n# explaining ECG artifacts.\n\nica = ICA(n_components=0.95, method='fastica').fit(epochs)\n\necg_epochs = create_ecg_epochs(raw, tmin=-.5, tmax=.5)\necg_inds, scores = ica.find_bads_ecg(ecg_epochs, threshold='auto')\n\nica.plot_components(ecg_inds)\n\n###############################################################################\n# Plot properties of ECG components:\nica.plot_properties(epochs, picks=ecg_inds)\n\n###############################################################################\n# Plot the estimated source of detected ECG related components\nica.plot_sources(raw, picks=ecg_inds)\n","sub_path":"0.21/_downloads/524f91808231279d1382039c40dca610/plot_run_ica.py","file_name":"plot_run_ica.py","file_ext":"py","file_size_in_byte":2193,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"183414018","text":"import requests\r\nimport pymongo\r\nfrom pymongo import MongoClient\r\nimport datetime\r\nimport pytz\r\nfrom datetime import date\r\nfrom dotenv import load_dotenv\r\nimport os\r\nload_dotenv()\r\n\r\nfrom telegram import ReplyKeyboardMarkup, ReplyKeyboardRemove, Update\r\nfrom telegram.ext import (\r\n Updater,\r\n CommandHandler,\r\n MessageHandler,\r\n Filters,\r\n ConversationHandler,\r\n CallbackContext,\r\n)\r\n\r\nFOOD = range(1)\r\nDELETEITEM,CONFIRMDELETE = range(2)\r\n\r\napi_key = os.getenv(\"API_KEY\")\r\n\r\ncluster_url = os.getenv(\"CLUSTER_URL\")\r\ncluster = MongoClient(cluster_url)\r\ndb = cluster[\"Careloriebot\"]\r\ncollection = db[\"Calories\"]\r\n\r\ndef calories(update: Update, _: CallbackContext) -> None:\r\n update.message.reply_text(\r\n 'What food/drink did you eat?\\n\\n'\r\n 'For more accurate results, specify:\\n'\r\n 'Eg: 1 bowl Laksa\\n'\r\n '(quantity) (measurement) (food/drink)\\n'\r\n )\r\n return FOOD\r\n\r\ndef get_calorie(update: Update, _: CallbackContext) -> int:\r\n global food_input\r\n global calorie\r\n global protein\r\n global carbohydrates\r\n global fat\r\n global sugar\r\n food_input = str(update.message.text)\r\n endpoint = 'https://api.calorieninjas.com/v1/nutrition?query='\r\n query = food_input\r\n response = requests.get(endpoint + query, headers={'X-Api-Key': api_key}) #input own api key\r\n if not response.json()[\"items\"]:\r\n update.message.reply_text(\r\n 'Sorry ' + food_input + ' is not in our database\\n'\r\n 'Please be more specific\\n'\r\n )\r\n return FOOD\r\n else:\r\n calorie = str(response.json()[\"items\"][0][\"calories\"])\r\n protein = str(response.json()[\"items\"][0][\"protein_g\"])\r\n carbohydrates = str(response.json()[\"items\"][0][\"carbohydrates_total_g\"])\r\n fat = str(response.json()[\"items\"][0][\"fat_total_g\"])\r\n sugar = str(response.json()[\"items\"][0][\"sugar_g\"])\r\n update.message.reply_text(\r\n 'Item name: ' + food_input + '\\n\\n'\r\n 'Calories(kcal): ' + calorie + '\\n'\r\n 'Protein(g): ' + protein + '\\n'\r\n 'Carbohydates(g): ' + carbohydrates + '\\n'\r\n 'Sugar(g): ' + sugar + '\\n'\r\n 'Fats(g): ' + fat + '\\n\\n'\r\n 'Press /add to add it to your diary\\n'\r\n 'Press /cancel to finish\\n'\r\n )\r\n\r\n return FOOD\r\n\r\ndef add_entry(update, context):\r\n update.message.reply_text(food_input + \" has been added!\")\r\n \r\n today = datetime.datetime.today()\r\n today = today.strftime(f\"%d/%m/%Y\")\r\n log = collection.find_one_and_update(\r\n {\"user\": update.message.chat_id , \"date\": today}, #query\r\n {'$push': {\"item\" : {\"name\":food_input, \"calories\": float(calorie), \"protein\": float(protein), \"fat\": float(fat), \"sugar\": float(sugar)}}}, #what to add to db\r\n upsert = True) #if theres an existing entry, add it in, else create new entry\r\n\r\n return FOOD\r\n\r\ndef diary(update, context):\r\n try: \r\n dates = str(context.args[0])\r\n calories = 0\r\n text = \"\"\r\n find = collection.find({\"user\" : update.message.chat_id, \"date\":dates})\r\n for x in find:\r\n for y in x[\"item\"]:\r\n calories += y[\"calories\"]\r\n text += y[\"name\"] + '\\n'\r\n\r\n calories_str = \"{:.1f}\".format(calories)\r\n update.message.reply_text(\r\n dates + '\\n\\n' + text + '\\n' + 'Total calories: ' + str(calories_str) +'kcal'\r\n )\r\n except (IndexError, ValueError):\r\n update.message.reply_text(\r\n 'Please type command in this format\\n' +\r\n 'For eg: /diary 23/06/2021'\r\n )\r\n\r\ndef delete(update: Update, context: CallbackContext) -> None:\r\n global delete_date\r\n try: \r\n delete_date = str(context.args[0])\r\n update.message.reply_text(\r\n 'What food/drink would you like to remove?\\n\\n'\r\n 'Please specify full name:\\n'\r\n 'Eg: 1 bowl Laksa\\n\\n'\r\n 'Press /cancel to finish\\n'\r\n )\r\n text = \"\"\r\n find = collection.find({\"user\" : update.message.chat_id, \"date\": delete_date})\r\n for x in find:\r\n for y in x[\"item\"]:\r\n text += y[\"name\"] + '\\n'\r\n update.message.reply_text(\r\n delete_date + ':' + '\\n\\n' + text\r\n )\r\n return DELETEITEM\r\n except (IndexError, ValueError):\r\n update.message.reply_text(\r\n 'Please type command in this format\\n' +\r\n 'For eg: /removeitem 23/06/2021'\r\n )\r\n return ConversationHandler.END\r\n\r\ndef deleting_item(update: Update, _: CallbackContext):\r\n global delete_item\r\n delete_item = str(update.message.text)\r\n update.message.reply_text(\r\n 'Are you sure to remove ' + delete_item + '?\\n\\n'\r\n 'Type Yes to remove, No to stop removing'\r\n )\r\n return CONFIRMDELETE\r\n\r\ndef confirm_delete(update: Update, _: CallbackContext):\r\n reply = str(update.message.text)\r\n if reply.lower() == \"yes\":\r\n log = collection.find_one_and_update(\r\n {\"user\": update.message.chat_id , \"date\": delete_date}, #query\r\n {'$pull': {\"item\" : {\"name\":delete_item}}}, #what to remove db\r\n upsert = True)\r\n if log:\r\n update.message.reply_text(\r\n 'Item has successfully been removed!!'\r\n )\r\n return ConversationHandler.END\r\n else:\r\n update.message.reply_text(\r\n 'Item was not found, please double check if your input is correct'\r\n )\r\n return DELETEITEM\r\n else:\r\n update.message.reply_text(\r\n 'What would you like to do next?'\r\n )\r\n return ConversationHandler.END\r\n","sub_path":"functions/caloriefunc.py","file_name":"caloriefunc.py","file_ext":"py","file_size_in_byte":5687,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"176734243","text":"import os\r\nimport warnings\r\nfrom datetime import datetime\r\n\r\nimport astropy\r\nimport numpy as np\r\nfrom astropy import units as u\r\nfrom astropy.modeling.fitting import LevMarLSQFitter\r\nfrom astropy.modeling import Parameter\r\nfrom astropy.modeling.models import Gaussian1D\r\nfrom astropy.time import Time\r\nfrom glue.core.message import SubsetUpdateMessage\r\nfrom ipywidgets import widget_serialization\r\nfrom packaging.version import Version\r\nfrom photutils.aperture import (ApertureStats, CircularAperture, EllipticalAperture,\r\n RectangularAperture)\r\nfrom traitlets import Any, Bool, Integer, List, Unicode, observe\r\n\r\nfrom jdaviz.core.events import SnackbarMessage, LinkUpdatedMessage\r\nfrom jdaviz.core.region_translators import regions2aperture, _get_region_from_spatial_subset\r\nfrom jdaviz.core.registries import tray_registry\r\nfrom jdaviz.core.template_mixin import (PluginTemplateMixin, DatasetSelectMixin,\r\n SubsetSelect, TableMixin, PlotMixin)\r\nfrom jdaviz.utils import PRIHDR_KEY\r\n\r\n__all__ = ['SimpleAperturePhotometry']\r\n\r\nASTROPY_LT_5_2 = Version(astropy.__version__) < Version('5.2')\r\n\r\n\r\n@tray_registry('imviz-aper-phot-simple', label=\"Imviz Simple Aperture Photometry\")\r\nclass SimpleAperturePhotometry(PluginTemplateMixin, DatasetSelectMixin, TableMixin, PlotMixin):\r\n template_file = __file__, \"aper_phot_simple.vue\"\r\n subset_items = List([]).tag(sync=True)\r\n subset_selected = Unicode(\"\").tag(sync=True)\r\n subset_area = Integer().tag(sync=True)\r\n bg_subset_items = List().tag(sync=True)\r\n bg_subset_selected = Unicode(\"\").tag(sync=True)\r\n background_value = Any(0).tag(sync=True)\r\n pixel_area = Any(0).tag(sync=True)\r\n counts_factor = Any(0).tag(sync=True)\r\n flux_scaling = Any(0).tag(sync=True)\r\n result_available = Bool(False).tag(sync=True)\r\n result_failed_msg = Unicode(\"\").tag(sync=True)\r\n results = List().tag(sync=True)\r\n plot_types = List([]).tag(sync=True)\r\n current_plot_type = Unicode().tag(sync=True)\r\n plot_available = Bool(False).tag(sync=True)\r\n radial_plot = Any('').tag(sync=True, **widget_serialization)\r\n fit_radial_profile = Bool(False).tag(sync=True)\r\n fit_results = List().tag(sync=True)\r\n\r\n def __init__(self, *args, **kwargs):\r\n super().__init__(*args, **kwargs)\r\n\r\n self.subset = SubsetSelect(self,\r\n 'subset_items',\r\n 'subset_selected',\r\n default_text=None,\r\n filters=['is_spatial', 'is_not_composite', 'is_not_annulus'])\r\n\r\n self.bg_subset = SubsetSelect(self,\r\n 'bg_subset_items',\r\n 'bg_subset_selected',\r\n default_text='Manual',\r\n manual_options=['Manual'],\r\n filters=['is_spatial', 'is_not_composite'])\r\n\r\n headers = ['xcenter', 'ycenter', 'sky_center',\r\n 'sum', 'sum_aper_area',\r\n 'aperture_sum_counts', 'aperture_sum_counts_err',\r\n 'aperture_sum_mag',\r\n 'min', 'max', 'mean', 'median', 'mode', 'std', 'mad_std', 'var',\r\n 'biweight_location', 'biweight_midvariance', 'fwhm',\r\n 'semimajor_sigma', 'semiminor_sigma', 'orientation', 'eccentricity',\r\n 'data_label', 'subset_label']\r\n self.table.headers_avail = headers\r\n self.table.headers_visible = headers\r\n\r\n self._selected_data = None\r\n self._selected_subset = None\r\n self.plot_types = [\"Curve of Growth\", \"Radial Profile\", \"Radial Profile (Raw)\"]\r\n self.current_plot_type = self.plot_types[0]\r\n self._fitted_model_name = 'phot_radial_profile'\r\n\r\n self.plot.add_line('line', color='gray', marker_size=32)\r\n self.plot.add_scatter('scatter', color='gray', default_size=1)\r\n self.plot.add_line('fit_line', color='magenta', line_style='dashed')\r\n\r\n self.session.hub.subscribe(self, SubsetUpdateMessage, handler=self._on_subset_update)\r\n self.session.hub.subscribe(self, LinkUpdatedMessage, handler=self._on_link_update)\r\n\r\n @observe('dataset_selected')\r\n def _dataset_selected_changed(self, event={}):\r\n try:\r\n self._selected_data = self.dataset.selected_dc_item\r\n if self._selected_data is None:\r\n return\r\n self.counts_factor = 0\r\n self.pixel_area = 0\r\n self.flux_scaling = 0\r\n\r\n # Extract telescope specific unit conversion factors, if applicable.\r\n meta = self._selected_data.meta.copy()\r\n if PRIHDR_KEY in meta:\r\n meta.update(meta[PRIHDR_KEY])\r\n del meta[PRIHDR_KEY]\r\n if 'telescope' in meta:\r\n telescope = meta['telescope']\r\n else:\r\n telescope = meta.get('TELESCOP', '')\r\n if telescope == 'JWST':\r\n if 'photometry' in meta and 'pixelarea_arcsecsq' in meta['photometry']:\r\n self.pixel_area = meta['photometry']['pixelarea_arcsecsq']\r\n if 'bunit_data' in meta and meta['bunit_data'] == u.Unit(\"MJy/sr\"):\r\n # Hardcode the flux conversion factor from MJy to ABmag\r\n self.flux_scaling = 0.003631\r\n elif telescope == 'HST':\r\n # TODO: Add more HST support, as needed.\r\n # HST pixel scales are from instrument handbooks.\r\n # This is really not used because HST data does not have sr in unit.\r\n # This is only for completeness.\r\n # For counts conversion, PHOTFLAM is used to convert \"counts\" to flux manually,\r\n # which is the opposite of JWST, so we just do not do it here.\r\n instrument = meta.get('INSTRUME', '').lower()\r\n detector = meta.get('DETECTOR', '').lower()\r\n if instrument == 'acs':\r\n if detector == 'wfc':\r\n self.pixel_area = 0.05 * 0.05\r\n elif detector == 'hrc': # pragma: no cover\r\n self.pixel_area = 0.028 * 0.025\r\n elif detector == 'sbc': # pragma: no cover\r\n self.pixel_area = 0.034 * 0.03\r\n elif instrument == 'wfc3' and detector == 'uvis': # pragma: no cover\r\n self.pixel_area = 0.04 * 0.04\r\n\r\n except Exception as e:\r\n self._selected_data = None\r\n self.hub.broadcast(SnackbarMessage(\r\n f\"Failed to extract {self.dataset_selected}: {repr(e)}\",\r\n color='error', sender=self))\r\n\r\n # Update self._selected_subset with the new self._selected_data\r\n # and auto-populate background, if applicable.\r\n self._subset_selected_changed()\r\n\r\n def _on_subset_update(self, msg):\r\n if self.dataset_selected == '' or self.subset_selected == '':\r\n return\r\n\r\n sbst = msg.subset\r\n if sbst.label == self.subset_selected and sbst.data.label == self.dataset_selected:\r\n self._subset_selected_changed()\r\n elif sbst.label == self.bg_subset_selected and sbst.data.label == self.dataset_selected:\r\n self._bg_subset_selected_changed()\r\n\r\n def _on_link_update(self, msg):\r\n if self.dataset_selected == '' or self.subset_selected == '':\r\n return\r\n\r\n # Force background auto-calculation to update when linking has changed.\r\n self._subset_selected_changed()\r\n\r\n @observe('subset_selected')\r\n def _subset_selected_changed(self, event={}):\r\n subset_selected = event.get('new', self.subset_selected)\r\n if self._selected_data is None or subset_selected == '':\r\n return\r\n\r\n try:\r\n self._selected_subset = _get_region_from_spatial_subset(\r\n self, self.subset.selected_subset_state)\r\n self._selected_subset.meta['label'] = subset_selected\r\n\r\n # Sky subset does not have area. Not worth it to calculate just for a warning.\r\n if hasattr(self._selected_subset, 'area'):\r\n self.subset_area = int(np.ceil(self._selected_subset.area))\r\n else:\r\n self.subset_area = 0\r\n\r\n except Exception as e:\r\n self._selected_subset = None\r\n self.hub.broadcast(SnackbarMessage(\r\n f\"Failed to extract {subset_selected}: {repr(e)}\", color='error', sender=self))\r\n\r\n else:\r\n self._bg_subset_selected_changed()\r\n\r\n def _calc_bg_subset_median(self, reg):\r\n # Basically same way image stats are calculated in vue_do_aper_phot()\r\n # except here we only care about one stat for the background.\r\n data = self._selected_data\r\n comp = data.get_component(data.main_components[0])\r\n if hasattr(reg, 'to_pixel'):\r\n reg = reg.to_pixel(data.coords)\r\n aper_mask_stat = reg.to_mask(mode='center')\r\n img_stat = aper_mask_stat.get_values(comp.data, mask=None)\r\n\r\n # photutils/background/_utils.py --> nanmedian()\r\n return np.nanmedian(img_stat) # Naturally in data unit\r\n\r\n @observe('bg_subset_selected')\r\n def _bg_subset_selected_changed(self, event={}):\r\n bg_subset_selected = event.get('new', self.bg_subset_selected)\r\n if bg_subset_selected == 'Manual':\r\n # we'll later access the user's self.background_value directly\r\n return\r\n\r\n try:\r\n reg = _get_region_from_spatial_subset(self, self.bg_subset.selected_subset_state)\r\n self.background_value = self._calc_bg_subset_median(reg)\r\n except Exception as e:\r\n self.background_value = 0\r\n self.hub.broadcast(SnackbarMessage(\r\n f\"Failed to extract {bg_subset_selected}: {repr(e)}\", color='error', sender=self))\r\n\r\n def vue_do_aper_phot(self, *args, **kwargs):\r\n if self._selected_data is None or self._selected_subset is None:\r\n self.hub.broadcast(SnackbarMessage(\r\n \"No data for aperture photometry\", color='error', sender=self))\r\n return\r\n\r\n data = self._selected_data\r\n reg = self._selected_subset\r\n\r\n # Reset last fitted model\r\n fit_model = None\r\n if self._fitted_model_name in self.app.fitted_models:\r\n del self.app.fitted_models[self._fitted_model_name]\r\n\r\n try:\r\n comp = data.get_component(data.main_components[0])\r\n try:\r\n bg = float(self.background_value)\r\n except ValueError: # Clearer error message\r\n raise ValueError('Missing or invalid background value')\r\n\r\n if hasattr(reg, 'to_pixel'):\r\n sky_center = reg.center\r\n xcenter, ycenter = data.coords.world_to_pixel(sky_center)\r\n else:\r\n xcenter = reg.center.x\r\n ycenter = reg.center.y\r\n if data.coords is not None:\r\n sky_center = data.coords.pixel_to_world(xcenter, ycenter)\r\n else:\r\n sky_center = None\r\n\r\n aperture = regions2aperture(reg)\r\n include_pixarea_fac = False\r\n include_counts_fac = False\r\n include_flux_scale = False\r\n comp_data = comp.data\r\n if comp.units:\r\n img_unit = u.Unit(comp.units)\r\n bg = bg * img_unit\r\n comp_data = comp_data << img_unit\r\n\r\n if u.sr in img_unit.bases: # TODO: Better way to detect surface brightness unit?\r\n try:\r\n pixarea = float(self.pixel_area)\r\n except ValueError: # Clearer error message\r\n raise ValueError('Missing or invalid pixel area')\r\n if not np.allclose(pixarea, 0):\r\n include_pixarea_fac = True\r\n if img_unit != u.count:\r\n try:\r\n ctfac = float(self.counts_factor)\r\n except ValueError: # Clearer error message\r\n raise ValueError('Missing or invalid counts conversion factor')\r\n if not np.allclose(ctfac, 0):\r\n include_counts_fac = True\r\n try:\r\n flux_scale = float(self.flux_scaling)\r\n except ValueError: # Clearer error message\r\n raise ValueError('Missing or invalid flux scaling')\r\n if not np.allclose(flux_scale, 0):\r\n include_flux_scale = True\r\n phot_aperstats = ApertureStats(comp_data, aperture, wcs=data.coords, local_bkg=bg)\r\n phot_table = phot_aperstats.to_table(columns=(\r\n 'id', 'sum', 'sum_aper_area',\r\n 'min', 'max', 'mean', 'median', 'mode', 'std', 'mad_std', 'var',\r\n 'biweight_location', 'biweight_midvariance', 'fwhm', 'semimajor_sigma',\r\n 'semiminor_sigma', 'orientation', 'eccentricity')) # Some cols excluded, add back as needed. # noqa\r\n rawsum = phot_table['sum'][0]\r\n\r\n if include_pixarea_fac:\r\n pixarea = pixarea * (u.arcsec * u.arcsec / (u.pix * u.pix))\r\n # NOTE: Sum already has npix value encoded, so we simply apply the npix unit here.\r\n pixarea_fac = (u.pix * u.pix) * pixarea.to(u.sr / (u.pix * u.pix))\r\n phot_table['sum'] = [rawsum * pixarea_fac]\r\n else:\r\n pixarea_fac = None\r\n\r\n if include_counts_fac:\r\n ctfac = ctfac * (rawsum.unit / u.count)\r\n sum_ct = rawsum / ctfac\r\n sum_ct_err = np.sqrt(sum_ct.value) * sum_ct.unit\r\n else:\r\n ctfac = None\r\n sum_ct = None\r\n sum_ct_err = None\r\n\r\n if include_flux_scale:\r\n flux_scale = flux_scale * phot_table['sum'][0].unit\r\n sum_mag = -2.5 * np.log10(phot_table['sum'][0] / flux_scale) * u.mag\r\n else:\r\n flux_scale = None\r\n sum_mag = None\r\n\r\n # Extra info beyond photutils.\r\n phot_table.add_columns(\r\n [xcenter * u.pix, ycenter * u.pix, sky_center,\r\n bg, pixarea_fac, sum_ct, sum_ct_err, ctfac, sum_mag, flux_scale, data.label,\r\n reg.meta.get('label', ''), Time(datetime.utcnow())],\r\n names=['xcenter', 'ycenter', 'sky_center', 'background', 'pixarea_tot',\r\n 'aperture_sum_counts', 'aperture_sum_counts_err', 'counts_fac',\r\n 'aperture_sum_mag', 'flux_scaling',\r\n 'data_label', 'subset_label', 'timestamp'],\r\n indexes=[1, 1, 1, 1, 3, 3, 3, 3, 3, 3, 18, 18, 18])\r\n\r\n try:\r\n phot_table['id'][0] = self.table._qtable['id'].max() + 1\r\n self.table.add_item(phot_table)\r\n except Exception: # Discard incompatible QTable\r\n self.table.clear_table()\r\n phot_table['id'][0] = 1\r\n self.table.add_item(phot_table)\r\n\r\n # Plots.\r\n line = self.plot.marks['line']\r\n sc = self.plot.marks['scatter']\r\n fit_line = self.plot.marks['fit_line']\r\n\r\n if self.current_plot_type == \"Curve of Growth\":\r\n self.plot.figure.title = 'Curve of growth from aperture center'\r\n x_arr, sum_arr, x_label, y_label = _curve_of_growth(\r\n comp_data, (xcenter, ycenter), aperture, phot_table['sum'][0],\r\n wcs=data.coords, background=bg, pixarea_fac=pixarea_fac)\r\n line.x, line.y = x_arr, sum_arr\r\n self.plot.clear_marks('scatter', 'fit_line')\r\n self.plot.figure.axes[0].label = x_label\r\n self.plot.figure.axes[1].label = y_label\r\n\r\n else: # Radial profile\r\n self.plot.figure.axes[0].label = 'pix'\r\n self.plot.figure.axes[1].label = comp.units or 'Value'\r\n\r\n if self.current_plot_type == \"Radial Profile\":\r\n self.plot.figure.title = 'Radial profile from aperture center'\r\n x_data, y_data = _radial_profile(\r\n phot_aperstats.data_cutout, phot_aperstats.bbox, (xcenter, ycenter),\r\n raw=False)\r\n line.x, line.y = x_data, y_data\r\n self.plot.clear_marks('scatter')\r\n\r\n else: # Radial Profile (Raw)\r\n self.plot.figure.title = 'Raw radial profile from aperture center'\r\n x_data, y_data = _radial_profile(\r\n phot_aperstats.data_cutout, phot_aperstats.bbox, (xcenter, ycenter),\r\n raw=True)\r\n\r\n sc.x, sc.y = x_data, y_data\r\n self.plot.clear_marks('line')\r\n\r\n # Fit Gaussian1D to radial profile data.\r\n if self.fit_radial_profile:\r\n fitter = LevMarLSQFitter()\r\n y_max = y_data.max()\r\n x_mean = x_data[np.where(y_data == y_max)].mean()\r\n std = 0.5 * (phot_table['semimajor_sigma'][0] +\r\n phot_table['semiminor_sigma'][0])\r\n if isinstance(std, u.Quantity):\r\n std = std.value\r\n gs = Gaussian1D(amplitude=y_max, mean=x_mean, stddev=std,\r\n fixed={'amplitude': True},\r\n bounds={'amplitude': (y_max * 0.5, y_max)})\r\n if ASTROPY_LT_5_2:\r\n fitter_kw = {}\r\n else:\r\n fitter_kw = {'filter_non_finite': True}\r\n with warnings.catch_warnings(record=True) as warns:\r\n fit_model = fitter(gs, x_data, y_data, **fitter_kw)\r\n if len(warns) > 0:\r\n msg = os.linesep.join([str(w.message) for w in warns])\r\n self.hub.broadcast(SnackbarMessage(\r\n f\"Radial profile fitting: {msg}\", color='warning', sender=self))\r\n y_fit = fit_model(x_data)\r\n self.app.fitted_models[self._fitted_model_name] = fit_model\r\n fit_line.x, fit_line.y = x_data, y_fit\r\n else:\r\n self.plot.clear_marks('fit_line')\r\n\r\n except Exception as e: # pragma: no cover\r\n self.plot.clear_all_marks()\r\n msg = f\"Aperture photometry failed: {repr(e)}\"\r\n self.hub.broadcast(SnackbarMessage(msg, color='error', sender=self))\r\n self.result_failed_msg = msg\r\n else:\r\n self.result_failed_msg = ''\r\n\r\n # Parse results for GUI.\r\n tmp = []\r\n for key in phot_table.colnames:\r\n if key in ('id', 'data_label', 'subset_label', 'background', 'pixarea_tot',\r\n 'counts_fac', 'aperture_sum_counts_err', 'flux_scaling', 'timestamp'):\r\n continue\r\n x = phot_table[key][0]\r\n if (isinstance(x, (int, float, u.Quantity)) and\r\n key not in ('xcenter', 'ycenter', 'sky_center', 'sum_aper_area',\r\n 'aperture_sum_counts', 'aperture_sum_mag')):\r\n tmp.append({'function': key, 'result': f'{x:.4e}'})\r\n elif key == 'sky_center' and x is not None:\r\n tmp.append({'function': 'RA center', 'result': f'{x.ra.deg:.6f} deg'})\r\n tmp.append({'function': 'Dec center', 'result': f'{x.dec.deg:.6f} deg'})\r\n elif key in ('xcenter', 'ycenter', 'sum_aper_area'):\r\n tmp.append({'function': key, 'result': f'{x:.1f}'})\r\n elif key == 'aperture_sum_counts' and x is not None:\r\n tmp.append({'function': key, 'result':\r\n f'{x:.4e} ({phot_table[\"aperture_sum_counts_err\"][0]:.4e})'})\r\n elif key == 'aperture_sum_mag' and x is not None:\r\n tmp.append({'function': key, 'result': f'{x:.3f}'})\r\n else:\r\n tmp.append({'function': key, 'result': str(x)})\r\n\r\n # Also display fit results\r\n fit_tmp = []\r\n if fit_model is not None and isinstance(fit_model, Gaussian1D):\r\n for param in ('mean', 'fwhm', 'amplitude'):\r\n p_val = getattr(fit_model, param)\r\n if isinstance(p_val, Parameter):\r\n p_val = p_val.value\r\n fit_tmp.append({'function': param, 'result': f'{p_val:.4e}'})\r\n\r\n self.results = tmp\r\n self.fit_results = fit_tmp\r\n self.result_available = True\r\n self.plot_available = True\r\n\r\n\r\n# NOTE: These are hidden because the APIs are for internal use only\r\n# but we need them as a separate functions for unit testing.\r\n\r\ndef _radial_profile(radial_cutout, reg_bb, centroid, raw=False):\r\n \"\"\"Calculate radial profile.\r\n\r\n Parameters\r\n ----------\r\n radial_cutout : ndarray\r\n Cutout image from ``ApertureStats``.\r\n\r\n reg_bb : obj\r\n Bounding box from ``ApertureStats``.\r\n\r\n centroid : tuple of int\r\n ``ApertureStats`` centroid or desired center in ``(x, y)``.\r\n\r\n raw : bool\r\n If `True`, returns raw data points for scatter plot.\r\n Otherwise, use ``imexam`` algorithm for a clean plot.\r\n\r\n \"\"\"\r\n reg_ogrid = np.ogrid[reg_bb.iymin:reg_bb.iymax, reg_bb.ixmin:reg_bb.ixmax]\r\n radial_dx = reg_ogrid[1] - centroid[0]\r\n radial_dy = reg_ogrid[0] - centroid[1]\r\n radial_r = np.hypot(radial_dx, radial_dy)\r\n\r\n # Sometimes the mask is smaller than radial_r\r\n if radial_cutout.shape != reg_bb.shape:\r\n radial_r = radial_r[:radial_cutout.shape[0], :radial_cutout.shape[1]]\r\n\r\n radial_r = radial_r[~radial_cutout.mask].ravel() # pix\r\n radial_img = radial_cutout.compressed() # data unit\r\n\r\n if raw:\r\n i_arr = np.argsort(radial_r)\r\n x_arr = radial_r[i_arr]\r\n y_arr = radial_img[i_arr]\r\n else:\r\n # This algorithm is from the imexam package,\r\n # see licenses/IMEXAM_LICENSE.txt for more details\r\n radial_r = np.rint(radial_r).astype(int)\r\n y_arr = np.bincount(radial_r, radial_img) / np.bincount(radial_r)\r\n x_arr = np.arange(y_arr.size)\r\n\r\n return x_arr, y_arr\r\n\r\n\r\ndef _curve_of_growth(data, centroid, aperture, final_sum, wcs=None, background=0, n_datapoints=10,\r\n pixarea_fac=None):\r\n \"\"\"Calculate curve of growth for aperture photometry.\r\n\r\n Parameters\r\n ----------\r\n data : ndarray or `~astropy.units.Quantity`\r\n Data for the calculation.\r\n\r\n centroid : tuple of int\r\n ``ApertureStats`` centroid or desired center in ``(x, y)``.\r\n\r\n aperture : obj\r\n ``photutils`` aperture to use, except its center will be\r\n changed to the given ``centroid``. This is because the aperture\r\n might be hand-drawn and a more accurate centroid has been\r\n recalculated separately.\r\n\r\n final_sum : float or `~astropy.units.Quantity`\r\n Aperture sum that is already calculated in the\r\n main plugin above.\r\n\r\n wcs : obj or `None`\r\n Supported WCS objects or `None`.\r\n\r\n background : float or `~astropy.units.Quantity`\r\n Background to subtract, if any. Unit must match ``data``.\r\n\r\n n_datapoints : int\r\n Number of data points in the curve.\r\n\r\n pixarea_fac : float or `None`\r\n For ``flux_unit/sr`` to ``flux_unit`` conversion.\r\n\r\n Returns\r\n -------\r\n x_arr : ndarray\r\n Data for X-axis of the curve.\r\n\r\n sum_arr : ndarray or `~astropy.units.Quantity`\r\n Data for Y-axis of the curve.\r\n\r\n x_label, y_label : str\r\n X- and Y-axis labels, respectively.\r\n\r\n Raises\r\n ------\r\n TypeError\r\n Unsupported aperture.\r\n\r\n \"\"\"\r\n n_datapoints += 1 # n + 1\r\n\r\n if hasattr(aperture, 'to_pixel'):\r\n aperture = aperture.to_pixel(wcs)\r\n\r\n if isinstance(aperture, CircularAperture):\r\n x_label = 'Radius (pix)'\r\n x_arr = np.linspace(0, aperture.r, num=n_datapoints)[1:]\r\n aper_list = [CircularAperture(centroid, cur_r) for cur_r in x_arr[:-1]]\r\n elif isinstance(aperture, EllipticalAperture):\r\n x_label = 'Semimajor axis (pix)'\r\n x_arr = np.linspace(0, aperture.a, num=n_datapoints)[1:]\r\n a_arr = x_arr[:-1]\r\n b_arr = aperture.b * a_arr / aperture.a\r\n aper_list = [EllipticalAperture(centroid, cur_a, cur_b, theta=aperture.theta)\r\n for (cur_a, cur_b) in zip(a_arr, b_arr)]\r\n elif isinstance(aperture, RectangularAperture):\r\n x_label = 'Width (pix)'\r\n x_arr = np.linspace(0, aperture.w, num=n_datapoints)[1:]\r\n w_arr = x_arr[:-1]\r\n h_arr = aperture.h * w_arr / aperture.w\r\n aper_list = [RectangularAperture(centroid, cur_w, cur_h, theta=aperture.theta)\r\n for (cur_w, cur_h) in zip(w_arr, h_arr)]\r\n else:\r\n raise TypeError(f'Unsupported aperture: {aperture}')\r\n\r\n sum_arr = [ApertureStats(data, cur_aper, wcs=wcs, local_bkg=background).sum\r\n for cur_aper in aper_list]\r\n if isinstance(sum_arr[0], u.Quantity):\r\n sum_arr = u.Quantity(sum_arr)\r\n else:\r\n sum_arr = np.array(sum_arr)\r\n if pixarea_fac is not None:\r\n sum_arr = sum_arr * pixarea_fac\r\n sum_arr = np.append(sum_arr, final_sum)\r\n\r\n if isinstance(sum_arr, u.Quantity):\r\n y_label = sum_arr.unit.to_string()\r\n sum_arr = sum_arr.value # bqplot does not like Quantity\r\n else:\r\n y_label = 'Value'\r\n\r\n return x_arr, sum_arr, x_label, y_label\r\n","sub_path":"jdaviz/configs/imviz/plugins/aper_phot_simple/aper_phot_simple.py","file_name":"aper_phot_simple.py","file_ext":"py","file_size_in_byte":26171,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"479764272","text":"# Title: Probability Theory (with Python)\n# Date: Feb/19/2016, Friday\n# Author: Minwoo Bae (minubae.nyc@gmail.com)\n\n# Ex 01:\n# There are N people in room.\n# Find N people such that the probability that two were born on the same date is greater than 0.5.\n\n# Sample Space: N-tuples of birthdays in alphabetical order (Each person has 365 possibilities for the birthday)\n# The number of Sample Space: 365^N\n# An Event (E): N-tuples which have a repetition (= common birthdays)\n# Complement of an Event (E^c): N-tuples without repetition\n# The number of Complement of an Event: P_{365, N}\n# P(E) = 1 - P(E^c) = 1- P_{365, N} / 365^N\n\nimport math\n\ndef two_born_same_date(N):\n\n permutation = 1\n probability = 0\n\n for i in range(N):\n\n permutation = permutation*(365-i)\n probability = 1 - permutation/365**(i+1)\n\n print('probability: ', probability)\n \n if probability > 0.5:\n n = i+1\n print('N: ', n)\n return n\n","sub_path":"two_born_same_date.py","file_name":"two_born_same_date.py","file_ext":"py","file_size_in_byte":980,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"39055906","text":"from Activity import Activity\r\nimport datetime\r\nfrom Time import Time\r\n\r\nclass FixedActivity(Activity):\r\n\t\"\"\"docstring for FixedActivity\"\"\"\r\n\tdef __init__(self, name, startTime, endTime):\r\n\t\tsuper(FixedActivity, self).__init__(name)\r\n\t\tself.startTime = startTime\t#Delta Time from datetime\r\n\t\tself.endTime = endTime - Time(0,30)\t\t#Delta time from datetime\r\n\r\n\t#This method is irrelevent for this subclass\r\n\tdef addDay(self, day):\r\n\t\traise AttributeError( self.__class__.__name__ + \" object has no attrdibute 'addDay' use 'setDay instead'\")\r\n\r\n\tdef setDay(self, day):\r\n\t\tday = day.lower()\r\n\t\tif not day in self.week:\r\n\t\t\traise KeyError(\"'%s' is not a day of the week. O_o Wtf were you thinking?\"%(day))\r\n\t\tfor key in self.week:\r\n\t\t\tif(key != day):\r\n\t\t\t\tself.week[key] = False\r\n\t\t\telse:\r\n\t\t\t\tself.week[day] = True\r\n\r\n\tdef getDay(self):\r\n\t\ti = 0\r\n\t\tfor day in self.week:\r\n\t\t\tif(self.week[day]):\r\n\t\t\t\treturn i \r\n\t\t\ti = i+1\r\n\r\n\r\n\tdef setDuration(self, startTime, endTime):\r\n\t\t#startTime and endTime are supposed to be datetime.time\r\n\t\tself.startTime = startTime\r\n\t\tself.endTime = endTime\r\n\t\tsuper(FixedActivity, self).setDuration(startTime - endTime)\r\n\r\n\tdef getDuration(self):\r\n\t\t return self.endTime - self.startTime\r\n\r\ndef main():\r\n\tpass\r\n\r\nif __name__ == '__main__':\r\n\tmain()","sub_path":"FixedActivity.py","file_name":"FixedActivity.py","file_ext":"py","file_size_in_byte":1275,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"465923963","text":"import json\nimport plotly\nimport pandas as pd\n\nfrom nltk.stem import WordNetLemmatizer\nfrom nltk.tokenize import word_tokenize\n\nfrom flask import Flask\nfrom flask import render_template, request, jsonify\n\nfrom plotly import graph_objs as go\nfrom plotly.graph_objs import Bar, Box, Figure, Violin, Line\nfrom sklearn.externals import joblib\nfrom sqlalchemy import create_engine\n\nimport numpy as np\n\napp = Flask(__name__)\n\ndef tokenize(text):\n tokens = word_tokenize(text)\n lemmatizer = WordNetLemmatizer()\n\n clean_tokens = []\n for tok in tokens:\n clean_tok = lemmatizer.lemmatize(tok).lower().strip()\n clean_tokens.append(clean_tok)\n\n return clean_tokens\n\n# load data\nengine = create_engine('sqlite:///./../data/DisasterResponse.db')\ndf = pd.read_sql_table('InsertTableName', engine)\n\n# load model\nmodel = joblib.load(\"./../models/classifier.pkl\")\n\n\ndef create_chart_genre(df):\n \"\"\"\n Create a chart based on pre-selected information flow\n \n Args: \n df: pd.DataFrame()\n \n Returns:\n BarChart\n \n \"\"\"\n \n df_group = df.groupby('genre').count()['message'].reindex([\"direct\", \"social\", \"news\"])\n genre_counts = (df_group) #.sort_values(ascending=False)\n genre_names = list(genre_counts.index)\n genre_chart = {\n 'data': [\n Bar(\n x=genre_names,\n y=genre_counts\n )\n ],\n\n 'layout': {\n 'title': 'Distribution of Message Genres',\n 'yaxis': {\n 'title': \"Count\"\n },\n 'xaxis': {\n 'title': \"Genre\"\n }\n }\n }\n \n \n return genre_chart\n\n\ndef create_chart_message_boxplot(df):\n \"\"\"\n Create a boxplot chart based on pre-selected information flow\n \n Args: \n df: pd.DataFrame()\n \n Returns:\n boxplot chart\n \n \"\"\"\n df['message_len'] = df['message'].str.len()\n \n x_data = list(df['genre'].unique())\n \n y0 = df[df['genre'] == x_data[0]]['message_len'].astype(np.int)\n y1 = df[df['genre'] == x_data[1]]['message_len'].astype(np.int)\n y2 = df[df['genre'] == x_data[2]]['message_len'].astype(np.int)\n \n y_data = [y0, y1, y2]\n\n colors = ['rgba(93, 164, 214, 0.5)', 'rgba(255, 144, 14, 0.5)', 'rgba(44, 160, 101, 0.5)',\n\n ]\n\n fig = Figure()\n for xd, yd, cls in zip(x_data, y_data, colors):\n fig.add_trace(Box(\n y=yd,\n name=xd,\n boxpoints=False, #'suspectedoutliers', #'all' False\n jitter=0,\n whiskerwidth=0.2,\n fillcolor=cls,\n# marker_size=2,\n line_width=1)\n )\n \n fig.update_layout(\n title='BoxPlot Message Lenght by Genre',\n yaxis=dict(\n# autorange=True,\n showgrid=True,\n zeroline=True,\n# dtick=5,\n gridcolor='rgb(255, 255, 255)',\n# gridwidth=1,\n zerolinecolor='rgb(255, 255, 255)',\n zerolinewidth=2,\n title= \"Message Lenght\"\n ),\n margin=dict(\n l=40,\n r=30,\n b=80,\n t=100,\n ),\n paper_bgcolor='rgba(0,0,0,0)',\n plot_bgcolor='rgba(0,0,0,0)',\n showlegend=False\n )\n return fig\n\ndef plot_violin_chart_message_length_by_genre(df):\n \n \"\"\"\n Create a Violin chart of Genre Message Lenght based on pre-selected information flow\n \n Args: \n df: pd.DataFrame()\n \n Returns:\n ViolinChart\n \n \"\"\"\n \n df['message_len'] = df['message'].str.len()\n \n x_data = list(df['genre'].unique())\n \n colors = ['rgba(93, 164, 214, 0.5)', 'rgba(255, 144, 14, 0.5)', 'rgba(44, 160, 101, 0.5)',\n\n ]\n \n fig = Figure()\n \n for genre in x_data:\n fig.add_trace(\n Violin(x=df['genre'][df['genre'] == genre],\n y=df['message_len'][df['genre'] == genre],\n name=genre,\n box_visible=True,\n meanline_visible=True))\n fig.update_layout(\n title='ViolinPlot Message Lenght by Genre',\n paper_bgcolor='rgba(0,0,0,0)',\n plot_bgcolor='rgba(0,0,0,0)',\n yaxis=dict(title= \"Message Lenght\"),\n xaxis=dict(title= \"Genre\")\n )\n return fig\n\ndef create_chart_message_lenght(df):\n \"\"\"\n Create a Line chart Median Length of Message by genre, based on pre-selected information flow\n \n Args: \n df: pd.DataFrame()\n \n Returns:\n LineChart\n \n \"\"\"\n \n df['message_len'] = df['message'].str.len()\n \n mean_msg_len = df.groupby('genre').mean()['message_len'].reindex([\"direct\", \"social\" , \"news\"])\n mean_msg_x = list(mean_msg_len.index)\n msg_len_chart = {\n 'data': [\n Line(\n x=mean_msg_x,\n y=mean_msg_len\n )\n ],\n\n 'layout': {\n 'title': 'Median Message Length by Genres',\n 'yaxis': {\n 'title': \"Median Message Length\"\n },\n 'xaxis': {\n 'title': \"Genre\"\n },\n 'paper_bgcolor':'rgba(0,0,0,0)',\n 'plot_bgcolor':'rgba(0,0,0,0)'\n }\n }\n \n \n return msg_len_chart\n\ndef plot_violin_chart_message_by_classification_length_and_genre(df):\n \"\"\"\n Create a Violin chart of Message Lenght by classification and Genre based on pre-selected information flow\n \n Args: \n df: pd.DataFrame()\n \n Returns:\n ViolinChart\n \n \"\"\"\n \n \n yparams = [i for i in df.columns if i not in ['id', 'message', 'original', 'genre','categories']]\n df = df.copy()\n df['message_len'] = df['message'].str.len()\n \n y_data=[]\n x_data=[]\n for i in range(len(yparams)):\n y_data.append(df[df[yparams[i]]>0]['message_len'].astype(np.int))\n x_data.append(df[df[yparams[i]]>0]['genre'])\n \n fig = Figure()\n \n for xval, yval, name in zip(x_data,y_data,yparams):\n fig.add_trace(\n Violin(\n x=xval\n , y=yval\n , name=name\n , box_visible=True\n , meanline_visible=True\n )\n )\n fig.update_layout(\n title='Message distributions and lenght',\n paper_bgcolor='rgba(0,0,0,0)',\n plot_bgcolor='rgba(0,0,0,0)',\n yaxis=dict(title= \"Message Lenght\"),\n xaxis=dict(title= \"Genre\")\n )\n return fig\n\ndef generate_charts(df):\n \"\"\"\n Render all the information in a html page\n \n Args: \n df: pd.DataFrame()\n \n Returns:\n HTML page\n \n \"\"\"\n \n genre_chart = create_chart_genre(df)\n msg_length_chart = create_chart_message_lenght(df) \n fig = create_chart_message_boxplot(df)\n \n \n violin_chart_message_length_by_genre = plot_violin_chart_message_length_by_genre(df)\n violin_chart_message_by_classification_length_and_genre = plot_violin_chart_message_by_classification_length_and_genre(df)\n # create visuals\n # TODO: Below is an example - modify to create your own visuals\n graphs = [\n genre_chart\n , msg_length_chart \n , fig\n , violin_chart_message_length_by_genre\n , violin_chart_message_by_classification_length_and_genre\n ]\n \n # encode plotly graphs in JSON\n ids = [\"graph-{}\".format(i) for i, _ in enumerate(graphs)]\n graphJSON = json.dumps(graphs, cls=plotly.utils.PlotlyJSONEncoder)\n return ids, graphJSON\n\n# index webpage displays cool visuals and receives user input text for model\n@app.route('/')\n@app.route('/index')\ndef index():\n\n ids, graphJSON = generate_charts(df)\n \n # render web page with plotly graphs\n return render_template('master.html', ids=ids, graphJSON=graphJSON)\n\n\n# web page that handles user query and displays model results\n@app.route('/go')\ndef go():\n # save user input in query\n query = request.args.get('query', '') \n\n # use model to predict classification for query\n classification_labels = model.predict([query])[0]\n classification_results = dict(zip(df.columns[4:], classification_labels))\n\n # This will render the go.html Please see that file. \n return render_template(\n 'go.html',\n query=query,\n classification_result=classification_results\n )\n\n\ndef main():\n app.run(host='0.0.0.0', port=3001, debug=True)\n\n\nif __name__ == '__main__':\n main()","sub_path":"DS/Task_02/app/run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":8826,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"70611160","text":"# Sample Input\n\n# 3\n# 12\n# 5\n# 7\n\n# Sample Output\n\n# Not prime\n# Prime\n# Prime\n\nimport math\n\nn = int(input())\n\nfor x in range(n):\n t = int(input())\n prime = True\n \n if t == 1 or (t > 2 and t % 2 == 0):\n prime = False\n \n else:\n for i in range(1, int(math.sqrt(t)/2) + 1):\n j = i * 2 + 1\n if t % j == 0:\n prime = False\n break;\n if prime:\n print('Prime')\n else:\n print('No prime')","sub_path":"30 Days of Code/Day 25 - Running Time and Complexity.py","file_name":"Day 25 - Running Time and Complexity.py","file_ext":"py","file_size_in_byte":481,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"374377176","text":"from ...types import serializable, Timestamp\nfrom .contributor import Contributor\n#import pyximport; pyximport.install()\nfrom .util import consume_tags\nimport datetime\nimport mw.xml_dump.element_iterator\n\nTAG_MAP = {\n 'id': lambda e: int(e.text),\n 'timestamp': lambda e: e.text, # Timestamp(e.text),\n 'contributor': lambda e: Contributor.from_element(e),\n 'minor': lambda e: True,\n 'comment': lambda e: e.text, # Comment.from_element(e)\n}\n\nclass Revision():\n \"\"\"\n Revision meta data.\n \"\"\"\n __slots__ = ('id', 'timestamp', 'contributor', 'minor', 'comment',\n 'reverted_by', 'reverts_till', 'cancelled_by', 'cancels', 'reverts_last')\n\n\n\n def __init__(self, id, timestamp, contributor=None, minor=None,\n comment=None):\n self.id = id #none_or(id, int)\n \"\"\"\n Revision ID : `int`\n \"\"\"\n\n if timestamp is not None:\n self.timestamp = datetime.datetime(\n int(timestamp[0:4]),\n int(timestamp[5:7]),\n int(timestamp[8:10]),\n int(timestamp[11:13]),\n int(timestamp[14:16]),\n int(timestamp[17:19]),\n 0,\n datetime.timezone.utc\n ) # type: datetime.datetime\n else:\n self.timestamp = None # type: datetime.datetime\n\n self.contributor = None or contributor #none_or(contributor, Contributor.deserialize)\n \"\"\"\n Contributor meta data : :class:`~mw.xml_dump.Contributor` | `None`\n \"\"\"\n\n self.minor = minor #none_or(minor, bool)\n \"\"\"\n Is revision a minor change? : `bool`\n \"\"\"\n\n self.comment = comment #none_or(comment, Comment)\n \"\"\"\n Comment left with revision : :class:`~mw.xml_dump.Comment` (behaves like `str`, with additional members)\n \"\"\"\n\n self.reverted_by = None\n self.reverts_till = None\n self.reverts_last = None\n self.cancelled_by = None\n self.cancels = None\n\n @classmethod\n def from_element(cls, element):\n values = consume_tags(TAG_MAP, element)\n\n obj = cls(\n values.get('id'),\n values.get('timestamp'),\n values.get('contributor'),\n values.get('minor') is not None,\n values.get('comment'),\n )\n element.clear()\n return obj","sub_path":"mw/xml_dump/iteration/revision.py","file_name":"revision.py","file_ext":"py","file_size_in_byte":2383,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"314930229","text":"import time \nimport RPi.GPIO as GPIO\n\nGPIO.cleanup()\nGPIO.setmode(GPIO.BCM)\n\nPIN_SWITCHER_MOTOR = 26\n\nPIN_MOTORS_LEFT_FORWARD = 17 \nPIN_MOTORS_LEFT_BACK = 4\nPIN_MOTORS_RIGHT_FORWARD = 22\nPIN_MOTORS_RIGHT_BACK = 27\n\ndisablePins = [PIN_MOTORS_LEFT_FORWARD, PIN_MOTORS_LEFT_BACK, PIN_MOTORS_RIGHT_FORWARD, PIN_MOTORS_RIGHT_BACK, PIN_SWITCHER_MOTOR]\nfor pin in disablePins:\n GPIO.setup(pin, GPIO.OUT) \n\nfor pin in disablePins:\n GPIO.output(pin, GPIO.LOW) \n\ndef switchMotors(x): \n GPIO.output(PIN_SWITCHER_MOTOR, x)\n\ndef enablePinsForTime(pins, sec):\n for pin in pins: \n GPIO.output(pin, GPIO.HIGH) \n time.sleep(sec) \n for pin in pins: \n GPIO.output(pin, GPIO.LOW) \n time.sleep(0.5) \n\ndef nazad(x):\n enablePinsForTime([PIN_MOTORS_LEFT_BACK, PIN_MOTORS_RIGHT_BACK], x)\n \ndef vpered(x): \n enablePinsForTime([PIN_MOTORS_LEFT_FORWARD, PIN_MOTORS_RIGHT_FORWARD], x) \n\ndef vlevo(x): \n enablePinsForTime([PIN_MOTORS_RIGHT_BACK, PIN_MOTORS_LEFT_FORWARD], x) \n \ndef vpravo(x): \n enablePinsForTime([PIN_MOTORS_LEFT_BACK, PIN_MOTORS_RIGHT_FORWARD], x) \n \nswitchMotors(1)\nvpered(0.2)\nnazad(0.2)\nvlevo(1)\nvpravo(1)\nswitchMotors(0) \n","sub_path":"run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":1168,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"61513211","text":"from __future__ import print_function\nimport os, sys\n\ndef unpacktar(fname):\n print(\"Unpacking %s into _testdir...\" % fname, end=\"\")\n if (not os.path.isfile(fname)):\n print(\"%s not found\" % fname)\n print(\"\\n!!! TEST FAILED !!!\\n\")\n sys.exit()\n\n os.system(\"rm -rf _testdir\")\n os.system(\"mkdir _testdir\")\n os.system(\"cp %s ./_testdir\" % fname)\n os.chdir(\"_testdir\")\n os.system(\"tar -xzf %s\" % fname)\n\n print(\"done\\n\")\n\ndef make(target):\n\n print(\"Running 'make %s'\" % target)\n if (os.system('make %s' % target) != 0):\n print(\"\\n!!! TEST FAILED !!!\\n\")\n sys.exit()\n print(\"\")\n\n\ndef compile(fname,flags=\"\",cflags= '-std=c++11 -Wall -fopenmp'):\n\n compileString = 'c++ ' + cflags + ' ' + flags + ' -c ' + fname + ' -o ' + fname[0:fname.find('cpp')-1] + '.o'\n print(\"Running '%s'\" % compileString)\n if (os.system(compileString) != 0):\n print(\"\\n!!! TEST FAILED !!!\\n\")\n sys.exit()\n print(\"\")\n\ndef link(objNames,executable,lflags='-fopenmp'):\n\n linkString = 'c++ ' + lflags + ' '\n for name in objNames:\n linkString += name + ' '\n linkString += '-o ' + executable\n\n print(\"Running '%s'\" % linkString)\n if (os.system(linkString) != 0):\n print(\"\\n!!! TEST FAILED !!!\\n\")\n sys.exit()\n print(\"\")\n\ndef runWithArguments(executable, arguments):\n print(\"\\n----------\")\n print(\"Running '%s %s'\\n\" % (executable, arguments))\n print(\"your program output is\\n\")\n val = os.system(\"./%s %s\" % (executable, arguments))\n print(\"----------\\n\")\n\ndef runWithInput(executable,inputString):\n print('\\n----------')\n print(\"Running '%s'\\n\" % executable)\n print(\"For input\\n\\n%s\\n\" % inputString)\n print(\"your program output is\\n\")\n val = os.system(\"echo '%s' | ./%s\" % (inputString,executable))\n print('----------\\n')\n\ndef test3p1():\n print(\"\\n****************************\")\n print(\"*** TESTING Exercise 3.1 ***\")\n print(\"****************************\\n\")\n\n make('Vector.o')\n\n codestring = \\\n\"\"\"#include \n#include \"Vector.hpp\"\n\nusing std::cout;\nusing std::endl;\n\nint main()\n{\n cout << \"Setting Vector x = [1, 2]^T\" << endl;\n Vector x(2);\n x(0) = 1.0;\n x(1) = 2.0;\n\n cout << endl << \"Calling ompTwoNorm(x): \";\n cout << ompTwoNorm(x) << endl;\n\n return 0;\n\n}\"\"\"\n print(\"Creating driver that tests ompTwoNorm... \",end=\"\")\n if (os.system(\"echo '%s' > ompTwoNorm_driver.cpp\" % codestring) != 0):\n print(\"\\n!!! TEST FAILED !!!\\n\")\n sys.exit()\n print(\"done\")\n\n compile('ompTwoNorm_driver.cpp')\n link(['Vector.o','ompTwoNorm_driver.o'], 'ompTwoNorm_driver')\n runWithArguments(\"ompTwoNorm_driver\", \"\")\n\n make('pt2n_driver')\n runWithArguments('pt2n_driver', '10000 1000')\n\ndef test3p2():\n print(\"\\n****************************\")\n print(\"*** TESTING Exercise 3.2 ***\")\n print(\"****************************\\n\")\n\n make('Vector.o')\n make('COO.o')\n\n codestring = \\\n\"\"\"#include \n#include \"COO.hpp\"\n\nusing std::cout;\nusing std::endl;\n\nint main()\n{\n cout << \"Setting Matrix A such that A(0,0) = 1, A(0,1) = 2, A(1,0) = 3, A(1,1) = 0\" << endl;\n\n COOMatrix A(2,2);\n A.push_back(0,0,1.0);\n A.push_back(0,1,2.0);\n A.push_back(1,0,3.0);\n\n cout << \"Setting Vector x = [1, 2]^T\" << endl;\n Vector x(2);\n x(0) = 1.0;\n x(1) = 2.0;\n\n Vector y(2);\n zeroize(y);\n cout << endl << \"Calling ompMatvec(A,x,y)\" << endl;\n ompMatvec(A,x,y);\n cout << \"Result y is\" << endl;\n\n for (unsigned int i=0; i < y.numRows(); i++)\n {\n cout << y(i) << endl;\n }\n\n return 0;\n\n}\"\"\"\n print(\"Creating driver that tests ompMatvec... \",end=\"\")\n if (os.system(\"echo '%s' > ompMatvec_driver.cpp\" % codestring) != 0):\n print(\"\\n!!! TEST FAILED !!!\\n\")\n sys.exit()\n print(\"done\")\n\n compile('ompMatvec_driver.cpp')\n link(['Vector.o','COO.o','ompMatvec_driver.o'], 'ompMatvec_driver')\n runWithArguments(\"ompMatvec_driver\", \"\")\n\n make('coo_driver')\n runWithArguments('coo_driver', '10000')\n\n\ndef test3p3():\n print(\"\\n****************************\")\n print(\"*** TESTING Exercise 3.3 ***\")\n print(\"****************************\\n\")\n\n make('Vector.o')\n make('CSR.o')\n\n codestring = \\\n\"\"\"#include \n#include \"CSR.hpp\"\n\nusing std::cout;\nusing std::endl;\n\nint main()\n{\n cout << \"Setting Matrix A such that A(0,0) = 1, A(0,1) = 2, A(1,0) = 3, A(1,1) = 0\" << endl;\n\n CSRMatrix A(2,2);\n A.openForPushBack();\n A.push_back(0,0,1.0);\n A.push_back(0,1,2.0);\n A.push_back(1,0,3.0);\n A.closeForPushBack();\n\n cout << \"Setting Vector x = [1, 2]^T\" << endl;\n Vector x(2);\n x(0) = 1.0;\n x(1) = 2.0;\n\n Vector y(2);\n zeroize(y);\n cout << endl << \"Calling ompMatvec(A,x,y)\" << endl;\n ompMatvec(A,x,y);\n cout << \"Result y is\" << endl;\n\n for (unsigned int i=0; i < y.numRows(); i++)\n {\n cout << y(i) << endl;\n }\n\n return 0;\n\n}\"\"\"\n print(\"Creating driver that tests ompMatvec... \",end=\"\")\n if (os.system(\"echo '%s' > ompMatvec_driver2.cpp\" % codestring) != 0):\n print(\"\\n!!! TEST FAILED !!!\\n\")\n sys.exit()\n print(\"done\")\n\n compile('ompMatvec_driver2.cpp')\n link(['Vector.o','CSR.o','ompMatvec_driver2.o'], 'ompMatvec_driver2')\n runWithArguments(\"ompMatvec_driver2\", \"\")\n\n make('csr_driver')\n runWithArguments('csr_driver', '10000')\n\n###############################################################################\nif __name__ == \"__main__\":\n\n script = \\\n\"\"\"Select Test to Run\n\n0) All\n1) Exercise 3.1\n2) Exercise 3.2\n3) Exercise 3.3 (583 Only)\n\n... (q to quit):\n\"\"\"\n\n unpacktar(\"ps6.tgz\")\n response = raw_input(script)\n while (response != \"q\"):\n if (response == \"1\" or response == \"0\"):\n test3p1()\n if (response == \"2\" or response == \"0\"):\n test3p2()\n if (response == \"3\" or response == \"0\"):\n test3p3()\n response = raw_input(script)\n","sub_path":"hw6_openMP/test_ps6.py","file_name":"test_ps6.py","file_ext":"py","file_size_in_byte":5890,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"650845299","text":"# Given two arrays, write a function to compute their intersection.\n\n# Notice\n\n# Each element in the result must be unique.\n# The result can be in any order.\n\n# Example\n# Given nums1 = [1, 2, 2, 1], nums2 = [2, 2], return [2].\n\nclass Solution:\n # @param {int[]} nums1 an integer array\n # @param {int[]} nums2 an integer array\n # @return {int[]} an integer array\n def intersection(self, nums1, nums2):\n # method 1\n if nums1 is None or nums2 is None:\n return None\n res=[]\n nums1.sort()\n nums2.sort()\n i,j=0,0\n while inums2[j]:\n j+=1\n else:\n i+=1\n return res\n \n \n #method 2\n nums1=set(nums1)\n nums2=set(nums2)\n \n res=[]\n for j in nums2:\n if j in nums1:\n res.append(j)\n \n return res\n","sub_path":"intersection_of_two_arrays.py","file_name":"intersection_of_two_arrays.py","file_ext":"py","file_size_in_byte":1129,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"582709079","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\nbalance = 320000\nannualInterestRate = 0.2\n\ndef payingDept(balance, annualInterestRate, payment):\n \"\"\"\n input:\n balance - the outstanding balance on the credit card\n annualInterestRate - annual interest rate as a decimal\n payment - int > 0\n return: Remaining balance at the end of the year\n \"\"\"\n for month in range(12):\n unpaidBalance = balance - payment\n balance = unpaidBalance + annualInterestRate / 12 * unpaidBalance\n\n return balance\n\ndef getMinPayment(balance, annualInterestRate):\n \"\"\"\n input:\n balance - the outstanding balance on the credit card\n annualInterestRate - annual interest rate as a decimal\n return: minimum fixed monthly payment needed\n in order pay off a credit card balance within 12 months\n \"\"\"\n start = balance / 12\n end = start + start * annualInterestRate\n while True:\n payment = (end - start) / 2 + start\n print(payment)\n rest = payingDept(balance,annualInterestRate, payment)\n if abs(rest) < 1:\n return round(payment, 2)\n elif rest < 0:\n end = payment\n elif rest > 0:\n start = payment\n \nprint('Lowest Payment: ', getMinPayment(balance, annualInterestRate)) \n ","sub_path":"payingDept2.py","file_name":"payingDept2.py","file_ext":"py","file_size_in_byte":1317,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"536916343","text":"import re\nfrom typing import Callable, List\n\nfrom demisto_sdk.commands.common.tools import run_command\n\n\ndef git_path() -> str:\n git_path = run_command('git rev-parse --show-toplevel')\n return git_path.replace('\\n', '')\n\n\ndef get_current_working_branch() -> str:\n branches = run_command('git branch')\n branch_name_reg = re.search(r'\\* (.*)', branches)\n if branch_name_reg:\n return branch_name_reg.group(1)\n\n return ''\n\n\ndef get_changed_files(from_branch: str = 'master', filter_results: Callable = None):\n temp_files = run_command(f'git diff --name-status {from_branch}').split('\\n')\n files: List = []\n for file in temp_files:\n if file:\n temp_file_data = {\n 'status': file[0]\n }\n if file.lower().startswith('r'):\n file = file.split('\\t')\n temp_file_data['name'] = file[2]\n else:\n temp_file_data['name'] = file[2:]\n files.append(temp_file_data)\n\n if filter_results:\n filter(filter_results, files)\n\n return files\n","sub_path":"demisto_sdk/commands/common/git_tools.py","file_name":"git_tools.py","file_ext":"py","file_size_in_byte":1080,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"491023767","text":"from flask import Flask, request, render_template, redirect, url_for, flash\nfrom newsClasses.Bing import Bing_Search\nfrom newsClasses.Google import Google_Search\nfrom constants.news_sites_constants import *\n\napp = Flask(__name__)\napp.config\n\n\n@app.route('/', methods=['GET', 'POST'])\n@app.route('/home', methods=['GET', 'POST'])\ndef home():\n return render_template('home.html', results=Bing_Search(BING_VERTICAL_TOP_STORIES, \"\"))\n\n\n@app.route('/results', methods=['POST', 'GET'])\ndef search_results():\n if request.method == 'POST':\n print(request.form)\n if request.form.get('search') == None:\n search_string = request.form.get('group3')\n return render_template(\"results.html\", search_results=Bing_Search(BING_SEARCH_SPECIFIC, search_string))\n else:\n search_string = request.form.get('search')\n return render_template(\"results.html\", search_results=Google_Search(GOOGLE_SEARCH_SPECIFIC, search_string, 5))\n return \"Please search\"\n\n\nif __name__ == \"__main__\":\n app.run(debug=True)\n","sub_path":"my_flask_app.py","file_name":"my_flask_app.py","file_ext":"py","file_size_in_byte":1056,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"153214178","text":"#!/usr/bin/python3\n\nimport sys\n\nsys.setrecursionlimit(1000000)\n\nbeta = \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\"\n\nfrom functools import partial\nfrom operator import add\n\nflip = lambda f: lambda x, y: f(y, x)\nrev = partial(reduce, flip(add))\n\ndef recurse(start, last, bits, nxt):\n n = nxt[-1]\n i = beta.index(n)\n if len(nxt) == 1:\n if i >= last:\n return bits + n\n else:\n return n + bits\n\n elif i >= last:\n bits = recurse(start, i, bits + n, nxt[:-1])\n else:\n bits = recurse(i, last, n + bits, nxt[:-1])\n\n return bits\n\nT = int(input())\nfor _ in range(T):\n s = rev(input()[:-1])\n i = beta.index(s[-1])\n if len(s) == 1:\n print(\"Case #\" + str(_+1) + \": \" + s)\n else:\n print(\"Case #\" + str(_+1) + \": \" + rev(recurse(i,i,s[-1],s[:-1])))\n\n\"\"\"\ndef determine(meta, times):\n pass\n\nT = int(input())\nfor _ in range(T):\n obj = (lambda x: {'N':int(x[0]),'K':int(x[1])})(input().split(' '))\n print(determine(obj, [int(x) for x in input().split(' ')]))\n\n# Data structures from input\n# Array\n[int(x) for x in input().split(' ')]\n# Dict\n(lambda x: {'N':int(x[0]),'K':int(x[1])})(input().split(' '))\n# Class\nclass X:\n def __init__(self, attrs):\n puts = [int(x) for x in input().split(' ')]\n i = 0\n for attr in attrs:\n setattr(self,attr,puts[i])\n i += 1\n\"\"\"","sub_path":"codes/CodeJamCrawler/CJ_16_1/16_1_1_dmad___init__.py","file_name":"16_1_1_dmad___init__.py","file_ext":"py","file_size_in_byte":1372,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"22606750","text":"#154. tally match project...??\n\n\nn = int(input(\"enter the entries:\"))\narr=[]\nname_arr=[]\ncls_arr=[]\nmob_arr=[]\naddress_arr=[]\nsalary_arr=[]\nfor i in range(0,n):\n name = input(\"enter the name:\")\n if len(name)<=15:\n print(name)\n else:\n print(\"maximum limit of charters.\")\n cls = int(input(\"enter the class:\"))\n if (cls>0 or cls<=12):\n print(cls)\n else:\n print(\"not found class.\")\n mob = int(input(\"enter the mob.:\"))\n if len(str(mob))<=10:\n print(mob)\n else:\n print(\"maximum no of mob.\")\n address = input(\"enter the address:\")\n if len(address)<=20:\n print(address)\n else:\n print(\"address lenght is not fully space.\")\n salary = int(input(\"enter the salary:\"))\n name_arr.append(name)\n cls_arr.append(cls)\n mob_arr.append(mob)\n address_arr.append(address)\n salary_arr.append(salary)\nfile = open(\"ram.txt\",\"w\")\nfile.write('NAME\\tCLASS\\tMOB\\tADD\\tSAL\\n')\nfor j in range(n):\n file.write(name_arr[j]+ \"\\t\" + str(cls_arr[j])+ \"\\t\" + str(mob_arr[j])+ \"\\t\" + address_arr[j]+ \"\\t\" + str(salary_arr[j])+ \"\\n\")\n # integer change in string then add the print statement ..??\n # print(name_arr[j],cls_arr[j],mob_arr[j],address_arr[j],salary_arr[j])\nfile.close()\nfile = open(\"ram.txt\",\"r\")\nfile1 = open(\"shyam.txt\",\"w\")\nwhile True:\n line= file.readline()\n if len(line)==0:\n break\n f=line.split('\\t')\n a=','.join(f)\n file1.write(a)\nfile.close()\nfile1.close()\nz= input(\"enter the search name:\")\nfile1= open(\"shyam.txt\",\"r\")\nwhile True:\n line= file1.readline()\n if len(line)==0:\n break\n x= line.split(',')\n if x[0]==z:\n print(x[0],x[1],x[2],x[3],x[4])\n break\n\nfile1.close()\n","sub_path":"PythonPrograms/python_program/TALLY_MATCH_PROJECT.py","file_name":"TALLY_MATCH_PROJECT.py","file_ext":"py","file_size_in_byte":1727,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"651812985","text":"# Manipulation of a JSON objects as nested dictionaries\n\ndef expand_key (key, separator = '.'):\n\t\"\"\" Expand a dot-notation key into a list\n\t\"\"\"\n\tkey_t = type(key)\n\n\tif (key_t == list):\n\t\tkey = tuple(key)\n\n\telif (key_t == str) or (key_t == unicode):\n\t\tkey = tuple(key.split(separator))\n\n\telif (key_t != tuple):\n\t\traise ValueError(\"Malformed key: '%s'\" % key)\n\n\tif (len(key) == 0):\n\t\traise ValueError(\"Empty key\")\n\n\tfor i, subkey in enumerate(key):\n\t\tif (subkey.startswith('$')) and (i+1 < len(key)):\n\t\t\traise ValueError(\"Malformed key '%s': special keys ('%s'?) must be last\" % (separator.join(key), subkey))\n\n\treturn key\n\ndef set (dictionary, key, value):\n\t\"\"\" Insert a nested key into a dictionary\n\n\tParameters:\n\t\t- **dictionary**: dictionary to populate\n\t\t- **key**: nested key, as a list\n\t\t- **value**: value to set\n\n\tExample:\n\t\t> m = {}\n\t\t> set(m, ('a', 'b', 'c'), 1)\n\t\t> print m\n\t\t{'a': {'b': {'c': 1}}}\n\t\"\"\"\n\tis_leaf, root = (len(key) == 1), key[0]\n\n\tif (is_leaf):\n\t\tdictionary[root] = value\n\telse:\n\t\tif (not root in dictionary):\n\t\t\tdictionary[root] = {}\n\n\t\tset(dictionary[root], key[1:], value)\n\ndef get (dictionary, key):\n\t\"\"\" Query a nested key from a dictionary\n\n\tParameters:\n\t\t- **dictionary**: dictionary to query\n\t\t- **key**: nested key, as a list\n\t\"\"\"\n\tis_leaf, root = (len(key) == 1), key[0]\n\n\tif (is_leaf):\n\t\treturn dictionary[root]\n\telse:\n\t\treturn get(dictionary[root], key[1:])\n\ndef delete (dictionary, key):\n\t\"\"\" Delete a nested key from a dictionary\n\n\tParameters:\n\t\t- **dictionary**: dictionary to modify\n\t\t- **key**: nested key to delete, as a list\n\t\"\"\"\n\tis_leaf, root = (len(key) == 1), key[0]\n\n\tif (type(dictionary) != dict):\n\t\traise KeyError(root)\n\n\tif (is_leaf):\n\t\tdel dictionary[root]\n\n\telse:\n\t\tdelete(dictionary[root], key[1:])\n\t\tif (len(dictionary[root]) == 0):\n\t\t\tdel dictionary[root]\n\ndef contains (dictionary, key):\n\t\"\"\" Test if a dictionary contains a nested key\n\t\n\tParameters:\n\t\t- **dictionary**: dictionary to evaluate\n\t\t- **key**: nested key to test, as a list\n\t\"\"\"\n\tis_leaf, root = (len(key) == 1), key[0]\n\n\tif (root in dictionary):\n\t\tif (is_leaf):\n\t\t\treturn True\n\n\t\tif (type(dictionary[root]) != dict):\n\t\t\treturn False\n\n\t\treturn contains(dictionary[root], key[1:])\n\n\treturn False\n\ndef items (dictionary):\n\t\"\"\" Iterate through a nested dictionary and return all\n\tkeys (as lists) and values\n\n\tParameters:\n\t\t- **dictionary**: dictionary to browse\n\n\tExample:\n\t\t> m = {'a': {'b': {'c': 1}, 'd': 2}}\n\t\t> print items(m)\n\t\t[(('a', 'b', 'c'), 1), (('a', 'd'), 2)]\n\t\"\"\"\n\tdef walk (node, b = []):\n\t\titems = []\n\n\t\tfor key in node:\n\t\t\tbranch, value = b + list(expand_key(key)), node[key]\n\n\t\t\tif (type(value) == dict):\n\t\t\t\titems.extend(walk(value, branch))\n\t\t\telse:\n\t\t\t\titems.append((tuple(branch), value))\n\n\t\treturn items\n\n\treturn walk(dictionary)\n\ndef expand (dictionary, separator = '.'):\n\t\"\"\" Transform a dictionary with dot-notation keys into a nested dictionary\n\n\tParameters:\n\t\t- **dictionary**: dictionary to transform\n\n\tExample:\n\t\t> m = {\"a.b.c\": 1}\n\t\t> print expand(m)\n\t\t{\"a\": {\"b\": {\"c\": 1}}}\n\t\"\"\"\n\td = {}\n\tfor key, value in dictionary.iteritems():\n\t\tset(d, expand_key(key, separator), value)\n\n\treturn d\n\ndef flatten (dictionary, separator = '.'):\n\t\"\"\" Transform a nested dictionary into a dictionary with dot-notations\n\n\tParameters:\n\t\t- **dictionary**: dictionary to transform\n\n\tExample:\n\t\t> m = {\"a\": {\"b\": {\"c\": 1}}}\n\t\t> print flatten(m)\n\t\t{\"a.b.c\": 1}\n\t\"\"\"\n\td = {}\n\tfor (key, value) in items(dictionary):\n\t\t# hack: we don't want to flatten special MongoDB\n\t\t# keys (everything starting with a '$')\n\t\tif (key[-1].startswith('$')):\n\t\t\td[separator.join(key[:-1])] = {key[-1]: value}\n\t\telse:\n\t\t\td[separator.join(key)] = value\n\n\treturn d\n\ndef traverse (dictionary, selector = lambda x: False, key_modifier = lambda x: x, value_modifier = lambda x: x):\n\t\"\"\" Traverse a nested dictionary and modify keys or values\n\n\tParameters:\n\t\t- **dictionary**: dictionary to transform\n\t\t- **selector**: boolean function receiving each key and sub-key; if\n\t\t returns True, then this key and its value will be modified\n\t\t- **key_modifier**: function receiving a key to modify; its return is\n\t\t used as the new key value\n\t\t- **value_modifier**: function receiving a value to modify; its return\n\t\t is used as the new value\n\t\"\"\"\n\ttree = {}\n\n\tfor key in dictionary:\n\t\tvalue = dictionary[key]\n\t\tselected = selector(key)\n\n\t\tif (selected):\n\t\t\tkey = key_modifier(key)\n\n\t\tif (type(value) == dict):\n\t\t\ttree[key] = traverse(value, selector, key_modifier, value_modifier)\n\n\t\telif (selected):\n\t\t\ttree[key] = value_modifier(value)\n\n\t\telse:\n\t\t\ttree[key] = value\n\n\treturn tree\n","sub_path":"lib/MetagenomeDB/utils/tree.py","file_name":"tree.py","file_ext":"py","file_size_in_byte":4579,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"289723124","text":"\nfrom pyecharts import Bar\nimport json\nfrom config import *\nimport pymongo\nclient=pymongo.MongoClient(MONGO_URL)\ndb=client[MONGO_DB]\ntable=db[MONGO_TABLE]\n\ncomments=table.find()\n\n\ndef get_Count():\n Count_js=[]\n Count_qw=[]\n Count_xjb=[]\n with open('js_qw_xjb_new.txt','a',encoding='utf8')as f:\n\n for comment in comments:\n f.write(json.dumps(comment['score'],ensure_ascii=False)+'\\n')\n if len(comment['score'])==13:\n Count_js.append(comment['score'][0:4])\n Count_qw.append(comment['score'][4:8])\n Count_xjb.append(comment['score'][8:13])\n f.close()\n\n setCount_js = set(Count_js)\n setCount_qw = set(Count_qw)\n setCount_xjb = set(Count_xjb)\n\n #print(setCount_js)\n #print(setCount_qw)\n #print(setCount_xjb)\n\n\n dic_count1={}\n dic_count2={}\n dic_count3={}\n for item1,item2,item3 in zip(setCount_js,setCount_qw,setCount_xjb):\n dic_count1.update({item1:Count_js.count(item1)})\n dic_count2.update({item2:Count_qw.count(item2)})\n dic_count3.update({item3:Count_xjb.count(item3)})\n count1=sorted(dic_count1.items(), reverse=True,key=lambda x: x[0])\n count2=sorted(dic_count2.items(), reverse=True,key=lambda x: x[0])\n count3=sorted(dic_count3.items(), reverse=True,key=lambda x: x[0])\n print(count1)\n print(count2)\n print(count3)\n COUNT1=[]\n COUNT2=[]\n COUNT3=[]\n for count_1,count_2,count_3 in zip(count1,count2,count3):\n COUNT1.append(count_1[1])\n COUNT2.append(count_2[1])\n COUNT3.append(count_3[1])\n\n #print(count2)\n #print(count3)\n x=[\"很好(5分)\",\"较好(4分)\",\"一般(3分)\",\"较差(2分)\",\"很差(1分)\"]\n bar = Bar(title=\"田子坊综合评分统计\",subtitle=\"满分5分\")\n bar.add(\"景色\",x,COUNT1,label_color=[\"#8F8F8F\"],xaxis_name='满意度',xaxis_name_pos='end',yaxis_name_pos=\"end\",yaxis_name=\"数量\",yaxis_name_gap=5,xaxis_name_gap=5)\n bar.add(\"趣味\",x,COUNT2,label_color=[\"#4F4F4F\"],xaxis_name='满意度',xaxis_name_pos='end',yaxis_name_pos=\"end\",yaxis_name=\"数量\",yaxis_name_gap=5,xaxis_name_gap=5)\n bar.add(\"性价比\",x,COUNT3,label_color=[\"#080808\"],xaxis_name='满意度',xaxis_name_pos='end',yaxis_name_pos=\"end\",yaxis_name=\"数量\",yaxis_name_gap=5,xaxis_name_gap=5)\n bar.show_config()\n bar.render()\n\n\nif __name__==\"__main__\":\n get_Count()\n","sub_path":"tianzifang/js_qw_xjb.py","file_name":"js_qw_xjb.py","file_ext":"py","file_size_in_byte":2401,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"455209541","text":"# -*- coding:utf-8 -*-\n\"\"\"\nModule Description: JWT认证\nDate:\nAuthor: Yfh\n\"\"\"\n\nimport time\nimport base64\nimport json\nfrom itsdangerous import TimedJSONWebSignatureSerializer as Serializer\nfrom itsdangerous import SignatureExpired, BadSignature, BadData\nfrom config.global_variable import TOKEN_SECRET_KEY, ACCESS_TOKEN_EXPIRATION, REFRESH_TOKEN_EXPIRATION\nfrom base.db.redis_manager import RedisManager\nfrom config.global_variable import MESSAGE, CODE\nfrom base.log.log_manager import LogManager as Log\n\n\ndef base64_decode(s):\n \"\"\"Add missing padding to string and return the decoded base64 string.\"\"\"\n s = str(s).strip()\n try:\n return base64.b64decode(s)\n except TypeError:\n padding = len(s) % 4\n if padding == 1:\n Log.logger.error(\"Invalid base64 string: {}\".format(s))\n return ''\n elif padding == 2:\n s += b'=='\n elif padding == 3:\n s += b'='\n return base64.b64decode(s)\n\n\ndef pack_token_key(user_id, token_type):\n \"\"\"\n 组装角色token信息的键\n :param user_id:\n :param token_type:\n :return:\n \"\"\"\n return \"access:token:\" + str(user_id) if token_type == \"access\" else \"refresh:token:\" + str(user_id)\n\n\ndef generate_token(user_id, token_type):\n \"\"\"\n 生成Token\n :param user_id:\n :param token_type:\n :return:\n \"\"\"\n payload = {'user_id': user_id, 'iat': time.time()}\n expire_time = ACCESS_TOKEN_EXPIRATION if token_type == 'access' else REFRESH_TOKEN_EXPIRATION\n # 生成token\n s = Serializer(secret_key=TOKEN_SECRET_KEY, expires_in=expire_time)\n token = s.dumps(payload).encode('utf-8')\n role_token_key = pack_token_key(user_id, token_type)\n RedisManager.cache_set(role_token_key, token, expire=expire_time)\n return token\n\n\ndef verify_token(token, token_type='access'):\n \"\"\"\n 验证Token\n :param token:\n :param token_type:\n :return:\n \"\"\"\n user_id = get_token_user_id(token)\n Log.logger.info('verify token user_id is {}, token is {}'.format(user_id, token))\n token_info = RedisManager.get_cache(pack_token_key(user_id, token_type))\n if not token_info:\n return {'status': CODE['TOKEN_ERROR'], 'data': {}, 'message': MESSAGE.get(CODE['TOKEN_ERROR'])}\n s = Serializer(secret_key=TOKEN_SECRET_KEY)\n try:\n s.loads(token, return_header=True)\n except SignatureExpired:\n return {'status': CODE['TOKEN_EXPIRED'], 'data': {}, 'message': MESSAGE.get(CODE['TOKEN_EXPIRED'])}\n except BadSignature as e:\n encoded_payload = e.payload\n if encoded_payload:\n try:\n s.load_payload(encoded_payload)\n except BadData:\n return {'status': CODE['TOKEN_ERROR'], 'data': {}, 'message': MESSAGE.get(CODE['TOKEN_ERROR'])}\n return {'status': CODE['TOKEN_ERROR'], 'data': {}, 'message': MESSAGE.get(CODE['TOKEN_ERROR'])}\n except Exception as e:\n Log.logger.error(\"check token error is {}\".format(e))\n return {'status': CODE['TOKEN_ERROR'], 'data': {}, 'message': MESSAGE.get(CODE['TOKEN_ERROR'])}\n if token != token_info:\n return {'status': CODE['TOKEN_ERROR'], 'data': {},\n 'message': MESSAGE.get(CODE['TOKEN_ERROR'])}\n return {'status': 0, 'data': {'user_id': user_id}}\n\n\ndef get_header(token):\n \"\"\"\n 获取header\n :param token:\n :return:\n \"\"\"\n s = Serializer(TOKEN_SECRET_KEY)\n return s.loads(token, return_header=True)[1]\n\n\ndef get_token_user_id(token):\n \"\"\"\n 获取token的角色id\n :param token:\n :return:\n \"\"\"\n second_part_token = token.split('.')[1]\n Log.logger.info('second part token is:{}'.format(second_part_token))\n token_data = base64_decode(second_part_token)\n token_data = json.loads(token_data)\n user_id = token_data.get('user_id')\n return user_id\n\n\n\n\n\n","sub_path":"base/authentication/authentication.py","file_name":"authentication.py","file_ext":"py","file_size_in_byte":3841,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"53405838","text":"from Stacks import StackArray\n# Clay Rosenthal\n\n\n# infix to postfix converter and postfix calculator\ndef infix_to_postfix(infix_expr):\n\t# converts infix expression to a postfix expression\n \"\"\" Method to convert infix expressions into postix\n Infix expression should have operations and operands seperated by spaces\n postfix expression will be formatted that way\"\"\"\n expression = infix_expr.split(\" \")\n # operands = StackArray(len(expression)//2)\n operands = StackArray(30)\n to_process = []\n for part in expression:\n # part = expression[i]\n if not check_num(part):\n if (part == ')'):\n while (operands.peek() != '('):\n to_process.append(str(operands.pop()))\n operands.pop()\n # print(\"Operand: \" + part);\n else:\n while (not operandOnTop(part, operands)):\n to_process.append(str(operands.pop()))\n operands.push(part);\n # print(\"Operand: \" + part);\n else:\n if check_float(part):\n to_process.append(float(part))\n else:\n to_process.append(int(part))\n while (not operands.is_empty()):\n to_process.append(str(operands.pop()))\n postfix_expr = \" \".join(str(thing) for thing in to_process)\n # print(\"Postfix Expression Ready: \" + postfix_expr)\n return postfix_expr\n\n\ndef postfix_eval(postfix_expr):\n\t# evaluates a postfix expression\n \"\"\" Evaluates a postfix expression and returns the answer \"\"\"\n to_process = postfix_expr.split(\" \")\n num_nums = postfix_valid(postfix_expr)\n if not num_nums:\n raise ValueError\n nums = StackArray(num_nums)\n while to_process:\n if (check_num(to_process[0])):\n nums.push(float(to_process[0]))\n del to_process[0]\n # print(\"Number: \" + str(nums.peek()));\n else:\n # print(\"Operation: \"+ to_process[0]);\n if to_process[0] in [\"+\", \"-\", \"*\", \"/\", \"^\"]:\n nums.push(do_math(nums.pop(), nums.pop(), to_process[0]))\n del to_process[0]\n else:\n del to_process[0]\n # print(\"Calculation complete: \" + str(nums.peek()))\n return nums.pop()\n\ndef operandOnTop(operand, operands):\n\t# returns true if the operand should be inserted, false if others should be popped\n \"\"\" sees if the operand being passed in should be put on the stack or have other operands pushed\"\"\"\n if (operands.is_empty()):\n return True\n top = operands.peek()\n if (operand=='('):\n return True\n elif (operand=='^' and top =='^'):\n return True\n elif ((operand=='*'or operand=='/') and not (top=='^'or top=='*'or top=='/')):\n return True\n elif ((operand=='-' or operand=='+') and not(top=='^' or top=='*' or top=='/' or top=='-' or top=='+')):\n return True\n return False\n\ndef do_math(num1, num2, operand):\n\t# calculates the operation done on two operands\n \"\"\" takes in a set of numbers and the operand to compute them with\"\"\"\n if (operand == '^'):\n if num1 == 0 and num2 == 0:\n raise ValueError\n return num2 ** num1\n elif (operand == '*'):\n return (num2 * num1)\n elif (operand == '/'):\n if num1 == 0:\n raise ValueError\n return (num2 / num1)\n elif (operand == '-'):\n return num2 - num1\n return num2 + num1\n\ndef check_num(num):\n\t# \"\" sees if a string is a valid number \"\"\"\n \"\"\" sees if a string is a valid number \"\"\"\n if num == \"-\":\n return False\n isNum = True\n decimal = False\n for ch in num:\n if ch not in [\"0\", \"1\", \"2\", \"3\", \"4\", \"5\", \"6\", \"7\", \"8\", \"9\", \"-\", \".\"]:\n return False\n elif ch == \".\":\n if not decimal:\n decimal = True\n else:\n return False\n return isNum\n\ndef check_float(num):\n\t# \"\" Checks if a number is a decimal or an integer\"\"\"\n \"\"\" Checks if a number is a decimal or an integer\"\"\"\n return \".\" in num\n\ndef postfix_valid(postfix_expr):\n\t# \"\" checks if a postfix expression is valid, returns None if it is false\n \"\"\" checks if a postfix expression is valid, returns None if it is false\n returns the number of numbers in the expression if it is valid\"\"\"\n to_process = postfix_expr.split(\" \")\n if len(to_process) == 0:\n return None\n num_nums = 0\n num_operations = 0\n first = True\n second = False\n for token in to_process:\n if first:\n if second:\n if check_num(token):\n first = False\n else:\n return None\n elif check_num(token):\n second = True\n else:\n return None\n if check_num(token):\n num_nums += 1\n elif token in [\"+\",\"-\",\"*\",\"/\",\"^\"]:\n num_operations += 1\n else:\n continue\n if check_num(to_process[len(to_process)-1]):\n if len(to_process) == 1:\n pass\n else:\n return None\n if num_operations != (num_nums - 1):\n return None\n return num_nums","sub_path":"exp_eval.py","file_name":"exp_eval.py","file_ext":"py","file_size_in_byte":5186,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"89239633","text":"## Author: Jasper Ting\n## Date Started: 5/20/2014\n## Reading puzzles from a file and putting all the lines in a list\n\nlevel = []\n\nlevel = [line.strip() for line in open('level_1.txt','r')]\n\n#for line in levelfile:\n# level.append(levelfile.readline().rstrip('\\n'))\n\nprint (level)\n","sub_path":"readfile.py","file_name":"readfile.py","file_ext":"py","file_size_in_byte":282,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"642842532","text":"import numpy as np \nimport math\n\ndef rpyxyz2H(rpy,xyz):\n\tHt=[[1,0,0,xyz[0]],\n\t [0,1,0,xyz[1]],\n [0,0,1,xyz[2]],\n [0,0,0,1]]\n\n\tHx=[[1,0,0,0],\n\t [0,math.cos(rpy[0]),-math.sin(rpy[0]),0],\n [0,math.sin(rpy[0]),math.cos(rpy[0]),0],\n [0,0,0,1]]\n\n\tHy=[[math.cos(rpy[1]),0,math.sin(rpy[1]),0],\n [0,1,0,0],\n [-math.sin(rpy[1]),0,math.cos(rpy[1]),0],\n [0,0,0,1]]\n\n\tHz=[[math.cos(rpy[2]),-math.sin(rpy[2]),0,0],\n [math.sin(rpy[2]),math.cos(rpy[2]),0,0],\n [0,0,1,0],\n [0,0,0,1]]\n\n\tH=np.matmul(np.matmul(np.matmul(Ht,Hz),Hy),Hx)\n\n\treturn H\n\ndef R2axisang(R):\n\tang = math.acos(( R[0,0] + R[1,1] + R[2,2] - 1)/2)\n\tZ = np.linalg.norm([R[2,1] - R[1,2], R[0,2] - R[2,0], R[1,0] - R[0,1]])\n\tif Z==0:\n\t\treturn[1,0,0], 0.\n\tx = (R[2,1] - R[1,2])/Z\n\ty = (R[0,2] - R[2,0])/Z\n\tz = (R[1,0] - R[0,1])/Z \t\n\n\treturn[x, y, z], ang\n\n\ndef BlockDesc2Points(H, Dim):\n\tcenter = H[0:3,3]\n\taxes=[ H[0:3,0],H[0:3,1],H[0:3,2]]\t\n\n\tcorners=[\n\t\tcenter,\n\t\tcenter+(axes[0]*Dim[0]/2.)+(axes[1]*Dim[1]/2.)+(axes[2]*Dim[2]/2.),\n\t\tcenter+(axes[0]*Dim[0]/2.)+(axes[1]*Dim[1]/2.)-(axes[2]*Dim[2]/2.),\n\t\tcenter+(axes[0]*Dim[0]/2.)-(axes[1]*Dim[1]/2.)+(axes[2]*Dim[2]/2.),\n\t\tcenter+(axes[0]*Dim[0]/2.)-(axes[1]*Dim[1]/2.)-(axes[2]*Dim[2]/2.),\n\t\tcenter-(axes[0]*Dim[0]/2.)+(axes[1]*Dim[1]/2.)+(axes[2]*Dim[2]/2.),\n\t\tcenter-(axes[0]*Dim[0]/2.)+(axes[1]*Dim[1]/2.)-(axes[2]*Dim[2]/2.),\n\t\tcenter-(axes[0]*Dim[0]/2.)-(axes[1]*Dim[1]/2.)+(axes[2]*Dim[2]/2.),\n\t\tcenter-(axes[0]*Dim[0]/2.)-(axes[1]*Dim[1]/2.)-(axes[2]*Dim[2]/2.)\n\t\t]\t\n\t# returns corners of BB and axes\n\treturn corners, axes\n\n\n\ndef CheckPointOverlap(pointsA,pointsB,axis):\t\n\t# TODO: check if sets of points projected on axis are overlapping\n\tprojPointsA = np.matmul(axis, np.transpose(pointsA))\n\tprojPointsB = np.matmul(axis, np.transpose(pointsB))\n\t#check overlap\n\tminA = np.min(projPointsA)\n\tmaxA = np.max(projPointsA)\n\tminB = np.min(projPointsB)\n\tmaxB = np.max(projPointsB)\n\tif maxB >= maxA >= minB:\n\t\treturn True\n\tif maxB >= minA >= minB:\n\t\treturn True\n\tif maxA >= maxB >= minA:\n\t\treturn True\n\tif maxA >= minB >= minA:\n\t\treturn True\n\treturn False\n\n\n\ndef CheckBoxBoxCollision(pointsA,axesA,pointsB,axesB):\t\n\t#Sphere check\n\tif np.linalg.norm(pointsA[0]-pointsB[0]) > (np.linalg.norm(pointsA[0]-pointsA[1])+np.linalg.norm(pointsB[0]-pointsB[1])):\n\t\treturn False\n\n\t#TODO - SAT cuboid-cuboid collision check\n\tfor i in range(3):\n\t\tif not CheckPointOverlap(pointsA, pointsB, axesA[i]):\n\t\t\treturn False\n\tfor i in range(3):\n\t\tif not CheckPointOverlap(pointsA, pointsB, axesB[i]):\n\t\t\treturn False\n\t#edge edge check\n\tfor i in range(3):\n\t\tfor j in range(3):\n\t\t\tif not CheckPointOverlap(pointsA, pointsB, np.cross(axesA[i], axesB[j])):\n\t\t\t\treturn False\n\n\treturn True\n\t\n\n\n","sub_path":"lab2/RobotUtil.py","file_name":"RobotUtil.py","file_ext":"py","file_size_in_byte":2784,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"289992052","text":"import os\nfrom setuptools import setup\nimport shaker\n\n# Utility function to read the README file.\ndef read(fname):\n return open(os.path.join(os.path.dirname(__file__), fname)).read()\n\nsetup(\n name = \"shaker\",\n packages = [\"shaker\"],\n version = shaker.__version__,\n description = \"EC2 Salt Minion Launcher\",\n author = \"Jeff Bauer\",\n author_email = \"jbauer@rubic.com\",\n url = \"https://github.com/rubic/shaker\",\n keywords = [\"salt\", \"ec2\", \"aws\"],\n classifiers = [\n \"Programming Language :: Python\",\n \"Programming Language :: Python :: 2.6\",\n \"Programming Language :: Python :: 2.7\",\n \"Development Status :: 3 - Alpha\",\n \"Environment :: Console\",\n \"Intended Audience :: Developers\",\n \"License :: OSI Approved :: BSD License\",\n \"Operating System :: POSIX\",\n \"Topic :: System :: Distributed Computing\",\n \"Topic :: System :: Systems Administration\",\n ],\n long_description = read('README.rst'),\n scripts=['scripts/shaker',\n 'scripts/shaker-terminate',\n ],\n)\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1084,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"105106994","text":"from scipy.io import loadmat\nimport os\nimport numpy as np\nimport xlrd\n\nNUM_OF_FRAME = 1200\n\n\ndef multi_window_feature(path, ground_truth, window_size=10):\n minu_queue = list()\n\n files = os.listdir(path)\n features = None\n\n index = 0\n # ==========get each minutes data from a matrix file.=========\n for file in files:\n file_path = path + \"/\" + file\n data = loadmat(file_path).get(\"savedata1\")\n\n # all of those information stored in data_all format [distance_x, distance_y, speed, snr]\n all_data = []\n dataSeg = [] # stores one frame data between two `999`\n hasInfo = False\n non_empty_frame_cnt = 0\n for j in data:\n if j[0] == 999:\n if hasInfo:\n hasInfo = False\n non_empty_frame_cnt += 1\n res = process_frame(dataSeg)\n all_data.append(res)\n else: # the state has been hasInfo, just add info to it\n dataSeg.append(j)\n hasInfo = True\n\n minu_feature = []\n\n if all_data:\n all_data_array = np.asarray(all_data)\n max_data = all_data_array.max(0)\n # minu_feature.append(max_data[0]) # max speed\n minu_feature.append(max_data[2]) # max snr\n\n var_data = all_data_array.var(0)\n minu_feature.append(var_data[0]) # var speed\n minu_feature.append(var_data[1]) # var snr\n minu_feature.append(var_data[2]) # var x\n minu_feature.append(var_data[3]) # var y\n\n mean_data = all_data_array.mean(0)\n minu_feature.append(mean_data[0]) # mean speed\n minu_feature.append(mean_data[1]) # mean snr\n # minu_feature.append(mean_data[2]) # mean x\n # minu_feature.append(mean_data[3]) # mean y\n minu_feature.append(mean_data[4]) # mean activity intensity\n\n minu_feature.append(len(data) / NUM_OF_FRAME) # [non-empty frame number]\n\n minu_queue.append(minu_feature)\n\n if features is None:\n features = np.zeros((len(files) - window_size + 1, len(minu_feature) + 1))\n\n if len(minu_queue) == window_size:\n data_to_store = np.asarray(minu_queue).max(0)\n minu_queue.pop(0)\n for i, d in enumerate(data_to_store):\n features[index][i] = d\n features[index][-1] = ground_truth[index]\n index += 1\n\n return features\n\n\ndef process_frame(dataSeg: list):\n \"\"\"\n :param dataSeg: the data between 2 `999`, represent one frame's information\n :return: res[Speed_max, Snr_max, x_mean, y_mean, 活动强烈等级]\n \"\"\"\n dataSeg_array = np.abs(dataSeg)\n dataSeg_bak = np.asarray(dataSeg)\n res = []\n for d in dataSeg_array.max(0)[2:]:\n res.append(d)\n res.append(sum(dataSeg_bak[:, 0]) / len(dataSeg)) # get x mean position\n res.append(sum(dataSeg_bak[:, 1]) / len(dataSeg)) # get y mean position\n # res.append(len(dataSeg)) # 活动部位数\n res.append(0)\n\n res[-1] += res[0] // 1\n res[-1] += res[1] // 200\n # if res[0] > 1 or res[1] > 100:\n # res[-1] += 1\n # if res[0] > 2 or res[1] > 400:\n # res[-1] += 1\n dataSeg.clear()\n return res\n\n\ndef transfer(root_path):\n for path in os.listdir(root_path):\n data = np.load(root_path + path)\n # with open(\"paksvm/pak/csv/\" + path, 'w') as fin:\n # for i in data:\n # fin.write(\"%d \" % i[-1])\n # for index, j in enumerate(i[0:-1], 1):\n # fin.write(\"%d:%f \" % (index, j))\n # fin.write(\"\\n\")\n np.savetxt(\"paksvm/pak/csv/\" + path, data, delimiter=' ')\n\n\nif __name__ == '__main__':\n # feature_path = \"window_feature/\"\n #\n # transfer(feature_path)\n\n # ==========get ground truth from xiao_mi ring=========\n f = xlrd.open_workbook(\"../Radar_Sleep_pointCloud/Xiaomi.xlsx\")\n\n # the path store point cloud data\n pathRoot = \"/media/hya/resource/ProjectWorkSpace/Sleep-Stage-Analyse/Radar_Sleep_pointCloud\"\n\n folders = {\n '20190128': '28th Jan',\n '20190130': '30th Jan',\n '20190131': '31th Jan',\n '20190203': '3nd Feb',\n '20190204': '4th Feb',\n '20190207': '7th Feb',\n '20190209': '9th Feb',\n '20190210': '10th Feb',\n '20190211': '11th Feb',\n '20190212': '12th Feb',\n '20190213': '13th Feb',\n '20190214': '14th Feb',\n '20190215': '15th Feb',\n '20190412': '12th April',\n '20190413': '13th April',\n '20190417': '17th April',\n '20190520': '20th May'\n }\n\n window_size = 10\n\n for path in folders.keys(): # k is a folder which contains all data in one night\n path_fur = pathRoot + \"/\" + path\n ground_truth = f.sheet_by_name(folders[path]).col_values(1)\n ground_truth_new = []\n\n window = 0\n state = [0, 0, 0]\n for i, truth in enumerate(ground_truth):\n window += 1\n state[int(truth)] += 1\n if window == window_size:\n window -= 1\n if state[2] >= state[1] and state[2] >= state[0]:\n ground_truth_new.append(2)\n elif state[1] > state[0]:\n ground_truth_new.append(1)\n else:\n ground_truth_new.append(0)\n state[int(ground_truth[i - window_size + 1])] -= 1\n\n features = multi_window_feature(path_fur, ground_truth_new, window_size=window_size)\n\n np.save(\"pure_feature/\" + path, features)\n print(\"C\", path)\n","sub_path":"hya/windowFeature.py","file_name":"windowFeature.py","file_ext":"py","file_size_in_byte":5644,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"500046992","text":"from __future__ import division, print_function\r\n\r\nimport json\r\nimport matplotlib.pyplot as plt\r\nimport numpy as np\r\nfrom os.path import abspath, exists\r\nimport pandas as pd\r\nfrom sklearn.base import clone\r\nfrom sklearn.model_selection import KFold\r\nfrom sklearn.preprocessing import StandardScaler\r\nfrom sklearn.svm import SVR\r\nimport sys\r\nimport time\r\n\r\n# Custom imports\r\nfrom regression_experiment import load_data\r\n\r\n# Add path to avoid relative imports\r\nPATH = abspath(__file__).split('experiments')[0]\r\nif PATH not in sys.path: sys.path.append(PATH)\r\nfrom scorers import pcor\r\n\r\n# Constants\r\nRANDOM_STATE = 1718\r\n\r\n\r\ndef create_params_key(method, params):\r\n \"\"\"Creates unique key based on hyperparameters.\r\n\r\n Parameters\r\n ----------\r\n method : str\r\n Name of method\r\n\r\n params : dict\r\n Dictionary of parameters\r\n\r\n Returns\r\n -------\r\n key : str\r\n Unique key\r\n \"\"\"\r\n if method in ['lasso', 'ridge']:\r\n key = '_alpha_' + str(params['alpha'])\r\n else:\r\n key = '_es_' + str(int(params['early_stopping'])) + \\\r\n '_vm_' + str(int(params['muting'])) + \\\r\n '_alpha_' + str(params['alpha']) + \\\r\n '_select_' + str(params['selector'])\r\n return key\r\n\r\n\r\ndef full_cv(X, y, model, k, cv, ranks):\r\n \"\"\"Runs cross-validation for different number of features and evaluates\r\n performance using MSE and R^2.\r\n\r\n Parameters\r\n ----------\r\n X : 2d array-like\r\n Features\r\n\r\n y : 1d array-like\r\n Labels\r\n\r\n model : object with fit() and predict() methods\r\n Regression model\r\n\r\n k : int\r\n Number of folds for cross-validation\r\n\r\n cv : object that returns indices for splits\r\n Cross-validation object to generate indices\r\n\r\n ranks : 1d array-like\r\n Sorted array containing indices of most important features in X\r\n\r\n Returns\r\n -------\r\n ADD HERE\r\n\r\n ADD HERE\r\n \"\"\"\r\n # Determine number of columns to use\r\n if X.shape[1] >= 100:\r\n cols_to_keep = np.arange(5, 105, 5)\r\n else:\r\n cols_to_keep = np.arange(0, X.shape[1])+1\r\n\r\n # CV scores\r\n mse, r2 = np.zeros(len(cols_to_keep)), np.zeros(len(cols_to_keep))\r\n for i, col in enumerate(cols_to_keep):\r\n\r\n # Subset X\r\n X_ = X[:, ranks[:col]].reshape(-1, col)\r\n assert X_.shape[1] == col, \"Number of subsetted features is incorrect\"\r\n\r\n print(\"[CV] Running CV with top %d features\" % X_.shape[1])\r\n scores_mse, scores_r2 = single_cv(X_, y, model, k, cv)\r\n\r\n print(\"\\tMSE = %.4f\" % scores_mse.mean())\r\n print(\"\\tR^2 = %.4f\" % scores_r2.mean())\r\n\r\n # Append results\r\n mse[i] = scores_mse.mean()\r\n r2[i] = scores_r2.mean()\r\n\r\n return mse, r2, cols_to_keep\r\n\r\n\r\ndef single_cv(X, y, model, k, cv, verbose=False):\r\n \"\"\"ADD\r\n\r\n Parameters\r\n ----------\r\n\r\n Returns\r\n -------\r\n \"\"\"\r\n scores_mse, scores_r2, fold = np.zeros(k), np.zeros(k), 0\r\n for train_idx, test_idx in cv.split(X):\r\n\r\n # Split into train and test data\r\n X_train, X_test = X[train_idx], X[test_idx]\r\n y_train, y_test = y[train_idx], y[test_idx]\r\n\r\n # Standardize data based on training\r\n scaler = StandardScaler().fit(X_train)\r\n X_train, X_test = scaler.transform(X_train), scaler.transform(X_test)\r\n\r\n # Train model and make predictions\r\n clf = clone(model).fit(X_train, y_train)\r\n y_hat = clf.predict(X_test)\r\n\r\n # Calculate MSE\r\n try:\r\n scores_mse[fold] = np.mean((y_test-y_hat)*(y_test-y_hat))\r\n except Exception as e:\r\n print(\"[ERROR] Exception raised computing MSE because %s\" % e)\r\n pass\r\n\r\n # Calculate R^2\r\n try:\r\n scores_r2[fold] = pcor(y_test, y_hat)**2\r\n except Exception as e:\r\n print(\"[ERROR] Exception raised computing R^2 because %s\" % e)\r\n pass\r\n\r\n # Next fold\r\n if verbose:\r\n print(\"[CV] Fold %d\" % (fold+1))\r\n print(\"\\tMSE = %.4f\" % scores_mse[fold])\r\n print(\"\\tR^2 = %.4f\" % scores_r2[fold])\r\n fold += 1\r\n\r\n # Overall metrics\r\n if verbose:\r\n print(\"[CV] Overall\")\r\n print(\"\\tMSE = %.4f +/- %.4f\" % (scores_mse.mean(), scores_mse.std()))\r\n print(\"\\tR^2 = %.4f +/- %.4f\" % (scores_r2.mean(), scores_r2.std()))\r\n\r\n return scores_mse, scores_r2\r\n\r\n\r\ndef split(string):\r\n string = string.replace('\\n', '').replace('\\r', '').replace('\\\\', '')[1:]\r\n string = [s.replace('r', '').strip().replace('(','').replace(')', '').replace('[', '').replace(']', '') for s in string.split('array') if s]\r\n mse = map(float, [s.strip() for s in string[0].strip().split(',') if s])\r\n r2 = map(float, [s.strip() for s in string[1].strip().split(',') if s])\r\n try:\r\n cols = map(int, [s.strip() for s in string[2].strip().split(',') if s])\r\n except:\r\n string[2] = string[2].replace('dtype=int64', '')\r\n cols = map(int, [s.strip() for s in string[2].strip().split(',') if s])\r\n return mse, r2, cols\r\n\r\n\r\ndef calculate_metrics():\r\n \"\"\"Runs SVM on baseline data sets to compare feature importance results\r\n across methods\r\n\r\n Parameters\r\n ----------\r\n None\r\n\r\n Returns\r\n -------\r\n df : pandas DataFrame\r\n Dataframe with metrics on baseline datasets\r\n \"\"\"\r\n\r\n # Cross-validation and model objects\r\n k = 5\r\n cv = KFold(n_splits=k, random_state=RANDOM_STATE)\r\n model = SVR()\r\n\r\n # Prepare data structures to hold cv data\r\n cv_results, start = [], time.time()\r\n\r\n # Load feature importance results\r\n results = pd.DataFrame(\r\n [json.loads(line) for line in open('regression.json', 'r')]\r\n )\r\n\r\n # Loop over each data set\r\n for name in results['data'].unique():\r\n\r\n # Load data and split into features and labels\r\n X, y = load_data(name)\r\n print(\"\\n\\n-- Data set %s with %d samples and %d features --\" % \\\r\n (name, X.shape[0], X.shape[1]))\r\n\r\n # Grab results for current data set in iteration\r\n df = results[results['data'] == name]['results']\r\n\r\n # Iterate over individual methods\r\n for method in df.apply(lambda x: x['method']).unique():\r\n\r\n sub = df[df.apply(lambda x: x['method'])==method]\r\n\r\n # Iterate over each set of parameters for current method\r\n if sub.shape[0] > 1:\r\n all_params = sub.apply(lambda x: x['params'])\r\n all_ranks = sub.apply(lambda x: x['ranks']).values\r\n for idx, params in enumerate(all_params):\r\n ranks = all_ranks[idx]\r\n key = create_params_key(method, params)\r\n print(\"\\n* Method = %s *\" % (method+key))\r\n mse, r2, cols = full_cv(X, y, model, k, cv, ranks)\r\n for k in range(mse.shape[0]):\r\n cv_results.append([name, method+key, mse[k], r2[k], cols[k]])\r\n else:\r\n ranks = sub.apply(lambda x: x['ranks']).values[0]\r\n print(\"\\n* Method = %s *\" % method)\r\n mse, r2, cols = full_cv(X, y, model, k, cv, ranks)\r\n for k in range(mse.shape[0]):\r\n cv_results.append([name, method, mse[k], r2[k], cols[k]])\r\n\r\n # Convert to dataframe and save to disk\r\n df = pd.DataFrame(cv_results, columns=['Data', 'Method', 'MSE', 'R2', 'N_Feats'])\r\n df.to_csv('regression_metrics.csv', index=False)\r\n\r\n return df\r\n\r\n\r\ndef main():\r\n \"\"\"Calculates metrics on data sets and analyzes results\"\"\"\r\n\r\n # Load or calculate metrics\r\n if exists(\"regression_metrics.csv\"):\r\n df = pd.read_csv(\"regression_metrics.csv\")\r\n else:\r\n df = calculate_metrics()\r\n\r\n # Calculate summary statistics\r\n for name in df['Data'].unique():\r\n sub = df[df['Data'] == name]\r\n for method in sub['Method'].unique():\r\n if 'rf' in method or 'cf' in method:\r\n pattern = '-o' if 'cf' in method else '--'\r\n lw = 1.0 if 'ct' in method else 5.0\r\n plt.plot(sub[sub['Method']==method]['Feats'],\r\n sub[sub['Method']==method]['R2'], pattern,\r\n linewidth=lw,\r\n label=method)\r\n plt.title(\"Data = %s\" % name)\r\n # plt.legend()\r\n plt.show()\r\n\r\n # tmp = sub[sub['Method'].apply(lambda x: 'cf' in x or 'ct' in x)]\r\n # tmp['Method'] = tmp['Method'].str.split('_')\r\n # tmp['selector'] = tmp['Method'].apply(lambda x: x[-1]). \\\r\n # map({'pearson': 0, 'distance': 1, 'hybrid': 2})\r\n # tmp['model'] = tmp['Method'].apply(lambda x: x[0]). \\\r\n # map({'ct': 0, 'cf': 1})\r\n # tmp['es'] = tmp['Method'].apply(lambda x: int(x[2]))\r\n # tmp['vm'] = tmp['Method'].apply(lambda x: int(x[4]))\r\n # tmp['alpha'] = tmp['Method'].apply(lambda x: float(x[6])). \\\r\n # map({.01: 0, .05: 1, .95: 2})\r\n # from statsmodels.stats.anova import anova_lm\r\n # from statsmodels.formula.api import ols\r\n # from statsmodels.graphics.api import interaction_plot\r\n # lm = ols(\"R2 ~ C(alpha) + C(model) + C(es) + C(vm) + Feats\", tmp).fit()\r\n # print(ols(\"R2 ~ C(selector) + C(alpha) + C(selector)*C(alpha)\", tmp).fit().summary())\r\n # import pdb; pdb.set_trace()\r\n #\r\n # interaction_plot(tmp['selector'].values, tmp['vm'].values, tmp['R2'].fillna(0).values)\r\n # print(ols(\"R2 ~ C(selector) + C(alpha) + C(model) + C(es) + C(vm) + Feats\", tmp).fit().summary())\r\n\r\n # interaction_plot(tmp['selector'], tmp['vm'], tmp['R2'])\r\n # plt.show()\r\n\r\nif __name__ == \"__main__\":\r\n main()\r\n","sub_path":"citrees/experiments/regression/scripts/regression_analysis.py","file_name":"regression_analysis.py","file_ext":"py","file_size_in_byte":9872,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"298561097","text":"import sys\r\nsys.path.append(r\"C:\\Users\\user\\OneDrive\\桌面\\python模組\\mymodule.zip\")\r\n\r\nimport isprime\r\ndef nextPrime(n):\r\n while not isprime.prime(n + 1):\r\n n += 1\r\n return n + 1\r\ndef main():\r\n a = eval(input('Enter an integer: '))\r\n print(f'{nextPrime(a)} is the first prime number larger than {a}')\r\nmain()","sub_path":"093.py","file_name":"093.py","file_ext":"py","file_size_in_byte":333,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"527582634","text":"#cursos/urls.py\nfrom django.conf.urls import url, re_path\nfrom django.urls import path,include\nfrom cursos import views\n\nurlpatterns = [\n url(r'^$',views.HomePageView.as_view(),name=\"index\"),\n url(r'cursos/',views.HomeCursosView.as_view(),name=\"cursos\"),\n url(r'curso/',views.HomeCursoView.as_view(),name=\"curso\"), #para iterarlo\n re_path(r'^curso/(?P[A-Z]{3})/$', views.DetalleCursoView.as_view(),name=\"detalle\"),\n re_path(r'^cama/(?P[1-9]{1})/$', views.DetallesCamaView.as_view(),name=\"detalles\"),\n path('accounts/' , include('accounts.urls')),\n path('accounts/' , include('django.contrib.auth.urls')),\n]\n","sub_path":"semestre_1/Hito3/App-Django-estático/GestionDeCamas/cursos/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":640,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"383141551","text":"from transporte import Transporte\n\n\nclass TransporteAereo(Transporte):\n def __init__(self):\n self.envergadura = None\n self.autonomia = None\n\n def add(self, nome: str, altura: float, comprimento: float,\n carga: float, velocidade: float, autonomia: float, envergadura: float):\n self.nome = nome\n self.altura = altura\n self.comprimento = comprimento\n self.carga = carga\n self.velocidade = velocidade\n self.autonomia = autonomia\n self.envergadura = envergadura\n\n def mostra(self):\n print(f\"\"\"\n nome: {self.nome}\n altura: {self.altura} m\n comprimento: {self.comprimento} m\n carga: {self.carga} t\n velocidade: {self.velocidade} km/h\n autonomia: {self.autonomia} km\n envergadura: {self.envergadura} m\n \"\"\")\n","sub_path":"exPolimorf19/transporteAereo.py","file_name":"transporteAereo.py","file_ext":"py","file_size_in_byte":818,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"114290131","text":"from flask_restful import Resource\nimport logging as logger\nfrom app import mysql\nfrom flask import request, jsonify\n\nclass SelectedTable(Resource):\n\n def TableInfo(self, getValues):\n table = getValues['table']\n cur = getValues['cursor']\n returnValue = []\n \n queryForRecords = 'SELECT COUNT(*) FROM '+table\n cur.execute(queryForRecords)\n noOfRecords = cur.fetchall()\n\n query = 'SHOW COLUMNS FROM '+table\n resultValue = cur.execute(query)\n columns = cur.fetchall()\n\n columnList = []\n for c in columns:\n col = {\n 'name': c[0],\n 'type': c[1]\n }\n columnList.append(col)\n value = {\n 'noOfRecords' : noOfRecords[0][0],\n 'columns' : columnList,\n 'table' : table\n }\n return value\n \n\n def get(self, tableName):\n logger.debug('selected table ',tableName)\n cur = mysql.connection.cursor()\n getValues = {\n 'cursor' : cur,\n 'table' : tableName,\n 'from' : 'SelectedTable'\n }\n \n returnValue = self.TableInfo(getValues)\n cur.close()\n return jsonify(returnValue)","sub_path":"kerpow/api/selectedTable.py","file_name":"selectedTable.py","file_ext":"py","file_size_in_byte":1273,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"499880008","text":"import unittest\nimport pandas as pd, numpy as np\nfrom utils import *\n\nclass TestUtils(unittest.TestCase):\n\n def test_random_split(self):\n df = pd.DataFrame({'A':range(10), 'B':range(10)})\n train, test = random_split(df, 0.7)\n print(train.index.values, test.index.values)\n self.assertEqual(set(test.index.values).intersection(set(train.index.values)), set())\n\n\n\nif __name__ == '__main__':\n\n unittest.main()","sub_path":"AdhocClassifier/NN/test_utils.py","file_name":"test_utils.py","file_ext":"py","file_size_in_byte":439,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"124164824","text":"import unittest\nimport math\nfrom Lab2_folder.vector import Nvector\n\nV1 = [1, 2, 3, 4]\nV1_LEN = 5.48\nNV1 = Nvector(V1)\nV2 = [5, 6, 7, 8]\nV2_LEN = 13.19\nNV2 = Nvector(V2)\nV3 = [9, 10]\nNV3 = Nvector(V3)\nA = 3\nV1_SUM_V2 = [6, 8, 10, 12]\nV1_SUB_V2 = [-4, -4, -4, -4]\nV1_MUL_A = [3, 6, 9, 12]\nV1_MUL_V2 = [5, 12, 21, 32]\nALPHA = math.pi / 3\n\n\nclass TestVectorMethods(unittest.TestCase):\n def test_add(self):\n self.assertEqual(NV1 + NV2, V1_SUM_V2)\n with self.assertRaises(Exception):\n NV1 + NV3\n with self.assertRaises(TypeError):\n NV1 + 3\n\n def test_sub(self):\n self.assertEqual(NV1 - NV2, V1_SUB_V2)\n with self.assertRaises(Exception):\n NV1 - NV3\n with self.assertRaises(TypeError):\n NV1 - 3\n\n def test_mul(self):\n self.assertEqual(NV1 * NV2, V1_MUL_V2)\n self.assertEqual(NV1 * A, V1_MUL_A)\n with self.assertRaises(TypeError):\n NV1 * \"[1,2,3]\"\n\n def test_eq(self):\n self.assertEqual(NV1 == NV2, False)\n self.assertEqual(NV1 == NV1, True)\n with self.assertRaises(TypeError):\n NV1 == 15\n with self.assertRaises(Exception):\n NV1 == NV3\n\n def test_len(self):\n self.assertAlmostEqual(NV1.__len__(), V1_LEN, delta=0.02)\n\n def test_get(self):\n self.assertEqual(NV1.get(1), 2)\n with self.assertRaises(IndexError):\n NV1.get(10)\n\n def test_scalar_product(self):\n self.assertAlmostEqual(NV1.scalar_product(NV2, ALPHA), V1_LEN * V2_LEN * math.cos(ALPHA), delta=0.02)\n with self.assertRaises(TypeError):\n NV1.scalar_product(2, ALPHA)\n\n def test_str(self):\n self.assertEqual(NV1.__str__(), \"1 2 3 4\")\n\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"Solutions/Task2/853503_Галиева_Элеонора/MyLab2-0.1/Lab2/vector_tests.py","file_name":"vector_tests.py","file_ext":"py","file_size_in_byte":1788,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"68638944","text":"from bs4 import BeautifulSoup\nfrom urllib.request import urlretrieve\nimport requests\nimport json\nimport sys\nimport os\nimport re\n\nclass LinkedInScraper(object):\n \"\"\"Web scraper for LinkedIn public company pages\"\"\"\n\n def __init__(self, url):\n self.url = url\n self.media_prefix = \"https://media.licdn.com/media/\"\n self.company = {}\n\n def get_source(self):\n \"\"\"Retrieves the HTML source of the page\"\"\"\n headers = {\"User-Agent\": \"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.90 Safari/537.36\"}\n response = requests.get(self.url, headers=headers)\n html = response.content.decode(\"utf-8\")\n return html\n\n def parse_html(self):\n \"\"\"Parses HTML source for the JSON section\"\"\"\n source = self.get_source()\n soup = BeautifulSoup(source, \"html.parser\")\n soup.encode(\"utf-8\")\n result = soup.find_all(\"code\", {\"id\":\"stream-feed-embed-id-content\"})\n return result\n\n def convert_json(self):\n \"\"\"Prepares the raw HTML source for JSON encoding with\n string and regular expression replacements\n \"\"\"\n parsed_html = self.parse_html()\n if len(parsed_html) != 0:\n raw_html = str(parsed_html[0])\n\n raw_html = raw_html.replace(\"\", \"\")\n raw_html = re.sub(\"()\", \"\", raw_html)\n raw_html = re.sub(\"()\", \"\", raw_html)\n\n for char in raw_html:\n if char == \"\\n\" or char == \"\\r\":\n raw_html = raw_html.replace(char, \"\")\n elif char == \"’\":\n raw_html = raw_html.replace(char, \"'\")\n\n return json.loads(raw_html)\n return None\n\n def get_company_data(self, key):\n \"\"\"Retrieves JSON information from the HTML source and\n populates the company JSON object accordingly\n \"\"\"\n json = self.convert_json()\n if json != None:\n try:\n self.company[\"name\"] = json[\"companyName\"]\n except KeyError:\n self.company[\"name\"] = \"\"\n\n try:\n self.company[\"description\"] = json[\"description\"]\n except KeyError:\n self.company[\"description\"] = \"\"\n\n try:\n self.company[\"legacyLogo\"] = json[\"legacySquareLogo\"]\n if \"description\" in self.company.keys():\n legacy_url = self.media_prefix + self.company[\"legacyLogo\"]\n urlretrieve(legacy_url, \"legacyLogo-%s.png\" % key)\n except KeyError:\n self.company[\"legacyLogo\"] = \"\"\n\n try:\n self.company[\"heroImage\"] = json[\"heroImage\"]\n if \"description\" in self.company.keys():\n hero_image_url = self.media_prefix + self.company[\"heroImage\"]\n urlretrieve(hero_image_url, \"heroImage-%s.png\" % key)\n except KeyError:\n self.company[\"heroImage\"] = \"\"\n\n try:\n self.company[\"url\"] = self.url\n except KeyError:\n self.company[\"url\"] = \"\"\n\n try:\n self.company[\"key\"] = key\n except KeyError:\n self.company[\"key\"] = \"\"\n\n return self.company\n return None\n\nif __name__ == \"__main__\":\n # 10 length alphanumerical key\n fname = sys.argv[1]\n os.chdir(\"../../public/uploads\")\n if fname in os.listdir():\n # run the scraper\n with open(fname) as json_raw:\n temp = json.load(json_raw)\n url = temp[\"url\"]\n scraper = LinkedInScraper(url)\n\n # extract the key\n key = fname.replace(\"temp-\", \"\")\n key = key.replace(\".json\", \"\")\n\n data = scraper.get_company_data(key)\n\n # clean up\n os.remove(fname)\n print(json.dumps(data))\n else:\n pass\n","sub_path":"ajax/scraper/linkedin.py","file_name":"linkedin.py","file_ext":"py","file_size_in_byte":3965,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"634932546","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\"\"\"\n# CODE NAME HERE\n\n# CODE DESCRIPTION HERE\n\nCreated on 2019-06-05 at 09:05\n\n@author: cook\n\"\"\"\nfrom __future__ import division\nimport numpy as np\nfrom astropy.time import Time, TimeDelta\nfrom astropy import units as uu\nimport os\n\nfrom SpirouDRS import spirouConfig\nfrom SpirouDRS import spirouCore\nfrom SpirouDRS import spirouStartup\n\nfrom SpirouDRS.spirouImage import spirouBERV\nfrom SpirouDRS.spirouImage import spirouImage\nfrom SpirouDRS.spirouImage import spirouFITS\n\n# =============================================================================\n# Define variables\n# =============================================================================\n# Name of program\n__NAME__ = 'cal_extract_RAW_spirou.py'\n# Get version and author\n__version__ = spirouConfig.Constants.VERSION()\n__author__ = spirouConfig.Constants.AUTHORS()\n__date__ = spirouConfig.Constants.LATEST_EDIT()\n__release__ = spirouConfig.Constants.RELEASE()\n# Get the parameter dictionary class\nParamDict = spirouConfig.ParamDict\n# Get Logging function\nWLOG = spirouCore.wlog\n# Get plotting functions\nsPlt = spirouCore.sPlt\n# debug (skip ic_ff_extract_type = ic_extract_type)\nDEBUG = False\n# define ll extract types\nEXTRACT_LL_TYPES = ['3c', '3d', '4a', '4b', '5a', '5b']\nEXTRACT_SHAPE_TYPES = ['4a', '4b', '5a', '5b']\n\n\ndef etiennes_code(ra, dec, epoch, lat, longi, alt, pmra, pmdec, px, rv, mjdate):\n\n from barycorrpy import get_BC_vel\n from barycorrpy import utc_tdb\n\n obsname = ''\n zmeas = 0.0\n ephemeris = 'https://naif.jpl.nasa.gov/pub/naif/generic_kernels/spk/planets/a_old_versions/de405.bsp'\n\n JDUTC = Time(mjdate, format='mjd', scale='utc')\n\n bjd = utc_tdb.JDUTC_to_BJDTDB(JDUTC, ra=ra, dec=dec, obsname=obsname,\n lat=lat, longi=longi, alt=alt, pmra=pmra,\n pmdec=pmdec, px=px, rv=rv, epoch=epoch,\n ephemeris=ephemeris, leap_update=True)\n\n results = get_BC_vel(JDUTC=JDUTC, ra=ra, dec=dec, obsname=obsname, lat=lat,\n longi=longi, alt=alt, pmra=pmra, pmdec=pmdec, px=px,\n rv=rv, zmeas=zmeas, epoch=epoch, ephemeris=ephemeris,\n leap_update=True)\n\n return results[0][0]/1000, bjd[0][0], np.nan\n\n# =============================================================================\n# Start of code\n# =============================================================================\n# Main code here\nif __name__ == \"__main__\":\n\n path = '/Data/projects/spirou/data_dev/reduced'\n\n night_name = 'TEST1/20180805'\n files = ['2295545o_pp.fits']\n\n night_name = '2019-01-17'\n files = ['2368959o_pp.fits']\n\n night_name = 'TEST2/20180805'\n files = ['2295547o_pp_e2dsff_AB.fits']\n\n filename = os.path.join(path, night_name, files[0])\n filename = os.path.join(path, 'TEST4/20180527/2279540o_pp_e2dsff_AB.fits')\n\n filename = ('/Data/projects/spirou/data_dev/reduced/from_ea/'\n '2294341o_pp_e2dsff_AB_tellu_corrected.fits')\n\n # ----------------------------------------------------------------------\n # Set up\n # ----------------------------------------------------------------------\n p = spirouStartup.Begin(recipe=__NAME__)\n p = spirouStartup.LoadArguments(p, night_name, None,\n require_night_name=False)\n\n # ----------------------------------------------------------------------\n # Read image file\n # ----------------------------------------------------------------------\n # read the image data\n data, hdr, _, _ = spirouFITS.read_raw_data(p, filename)\n # ----------------------------------------------------------------------\n # Read star parameters\n # ----------------------------------------------------------------------\n p = spirouImage.get_sigdet(p, hdr, name='sigdet')\n p = spirouImage.get_exptime(p, hdr, name='exptime')\n p = spirouImage.get_gain(p, hdr, name='gain')\n p = spirouImage.get_param(p, hdr, 'KW_OBSTYPE', dtype=str)\n p = spirouImage.get_param(p, hdr, 'KW_OBJRA', dtype=str)\n p = spirouImage.get_param(p, hdr, 'KW_OBJDEC', dtype=str)\n p = spirouImage.get_param(p, hdr, 'KW_OBJEQUIN')\n p = spirouImage.get_param(p, hdr, 'KW_OBJRAPM')\n p = spirouImage.get_param(p, hdr, 'KW_OBJDECPM')\n p = spirouImage.get_param(p, hdr, 'KW_DATE_OBS', dtype=str)\n p = spirouImage.get_param(p, hdr, 'KW_UTC_OBS', dtype=str)\n p = spirouImage.get_param(p, hdr, 'KW_ACQTIME', dtype=float)\n\n # ----------------------------------------------------------------------\n # Get berv parameters\n # ----------------------------------------------------------------------\n # get the observation date\n obs_year = int(p['DATE-OBS'][0:4])\n obs_month = int(p['DATE-OBS'][5:7])\n obs_day = int(p['DATE-OBS'][8:10])\n # get the UTC observation time\n utc = p['UTC-OBS'].split(':')\n # convert to hours\n hourpart = float(utc[0])\n minpart = float(utc[1]) / 60.\n secondpart = float(utc[2]) / 3600.\n exptimehours = (p['EXPTIME'] / 3600.) / 2.\n obs_hour = hourpart + minpart + secondpart + exptimehours\n\n # get the RA in hours\n objra = p['OBJRA'].split(':')\n ra_hour = float(objra[0])\n ra_min = float(objra[1]) / 60.\n ra_second = float(objra[2]) / 3600.\n target_alpha = (ra_hour + ra_min + ra_second) * 15\n # get the DEC in degrees\n objdec = p['OBJDEC'].split(':')\n dec_hour = float(objdec[0])\n dec_min = np.sign(float(objdec[0])) * float(objdec[1]) / 60.\n dec_second = np.sign(float(objdec[0])) * float(objdec[2]) / 3600.\n target_delta = dec_hour + dec_min + dec_second\n # set the proper motion and equinox\n target_pmra = p['OBJRAPM'] * 1000\n target_pmde = p['OBJDECPM'] * 1000\n target_equinox = Time(float(p['OBJEQUIN']), format='decimalyear').jd\n\n target_plxs = np.arange(0, 1000, 10.0)\n\n # calculate JD time (as Astropy.Time object)\n tstr = '{0} {1}'.format(p['DATE-OBS'], p['UTC-OBS'])\n t = Time(tstr, scale='utc')\n tdelta = TimeDelta(((p['EXPTIME']) / 2.) * uu.s)\n t1 = t + tdelta\n\n # ----------------------------------------------------------------------\n # BERV TEST\n # ----------------------------------------------------------------------\n bervs1, bjds1 = [], []\n bervs2, bjds2 = [], []\n bervs3, bjds3 = [], []\n\n for target_plx in target_plxs:\n\n\n kwargs = dict(ra=target_alpha, dec=target_delta, epoch=target_equinox,\n pmra=target_pmra, pmde=target_pmde, plx=target_plx,\n lat=p['IC_LATIT_OBS'], long=p['IC_LONGIT_OBS'],\n alt=p['IC_ALTIT_OBS'])\n\n results2 = spirouBERV.use_barycorrpy(p, t1, **kwargs)\n\n results1 = spirouBERV.use_berv_est(p, t1, **kwargs)\n\n results3 = etiennes_code(target_alpha, target_delta, target_equinox,\n p['IC_LATIT_OBS'], p['IC_LONGIT_OBS'],\n p['IC_ALTIT_OBS'],\n target_pmra, target_pmde, target_plx,\n 0.0, t1.mjd)\n\n # append to arrays\n bervs1.append(results1[0])\n bjds1.append(results1[1])\n bervs2.append(results2[0])\n bjds2.append(results2[1])\n bervs3.append(results3[0])\n bjds3.append(results3[1])\n\n # print out\n print('OBJECT = {0}'.format(hdr['OBJECT']))\n\n print('ra={0} dec={1}'.format(target_alpha, target_delta))\n print('pmra={0} pmde={1}'.format(target_pmra, target_pmde))\n print('plx={0}'.format(target_plx))\n\n print('{0:25s}'.format('ESTIMATE (PYASL)'), results1)\n print('{0:25s}'.format('SPIROU DRS (BARYCORRPY)'), results2)\n print('{0:25s}'.format('ETIENNE (BARYCORRPY)'), results3)\n\n print('{0:25s}'.format('HEADER'), (hdr['BERV'], hdr['BJD'], hdr['BERVMAX']))\n\n\n # plot\n import matplotlib.pyplot as plt\n fig, frame = plt.subplots(ncols=1, nrows=1)\n frame.plot(target_plxs, bervs1, marker='o', label='estimate')\n frame.plot(target_plxs, bervs2, marker='+', label='spirou drs barcorrpy')\n frame.plot(target_plxs, bervs3, marker='x', label='etienne barycorrpy')\n\n frame.legend(loc=0)\n frame.set(xlabel='parallax', ylabel='BERV [km/s]')\n # sort out ylabels\n yticks = frame.get_yticks()\n yticklabels = ['{0:.5f}'.format(i) for i in yticks]\n frame.set_yticklabels(yticklabels)\n\n\n# =============================================================================\n# End of code\n# =============================================================================\n","sub_path":"old_code/INTROOT/misc/berv_error_test.py","file_name":"berv_error_test.py","file_ext":"py","file_size_in_byte":8609,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"402294510","text":"import json\nimport numpy as np\nimport ds_format as ds\n\ndef meta(*args, **opts):\n\tinput_ = args\n\tfor filename in input_:\n\t\td = ds.read(filename, [], full=True)\n\t\tinfo = d['.']\n\t\tj = json.dumps(info, sort_keys=True, indent=4, cls=ds.cmd.NumpyEncoder)\n\t\tprint(j)\n","sub_path":"ds_format/cmd/meta.py","file_name":"meta.py","file_ext":"py","file_size_in_byte":260,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"282573759","text":"\"\"\"Protocols\"\"\"\n\nimport random, threading, time\nfrom .PEEPTransport import MyProtocolTransport\nfrom .PEEPPackets import PEEPPacket\nfrom playground.network.common import StackingProtocol\n\n\nclass resendThread(threading.Thread):\n def __init__(self, threadID, name, func):\n threading.Thread.__init__(self)\n self.threadID = threadID\n self.name = name\n self.func = func\n\n def run(self):\n print(\"Starting \" + self.name)\n self.func()\n print(\"Exiting \" + self.name)\n\n\nclass PEEPProtocol(StackingProtocol):\n def __init__(self):\n self.deserializer = PEEPPacket.Deserializer()\n self.state = 0\n self.counter = 5\n random.seed()\n self.valid_sent = random.randrange(0, 4294967295)\n self.valid_received = 0\n self.handshake_to_send = []\n self.ackReceived = []\n self.pktReceived = []\n super().__init__()\n\n def handshake_resend(self):\n while self.state == 1:\n # print(\"self.counter: \", self.counter)\n if self.counter <= 0:\n # print(\"It has been a while, restart handshake\")\n # print(\"length of to_send: \", len(self.handshake_to_send))\n assert(len(self.handshake_to_send) == 1)\n self.transport.write(self.handshake_to_send[0].__serialize__())\n # print(\"PEEP: Sending PEEP packet.\", self.handshake_to_send[0].to_string())\n self.counter = 0.3\n else:\n self.counter = self.counter - 0.1\n time.sleep(0.1)\n\n def sortPacketBySeqNum(self):\n self.pktReceived.sort(key=lambda pkt: pkt.SequenceNumber, reverse=False)\n\n def addAck2Queue(self, ack):\n if ack in self.higherProtocol().transport.expected_ack:\n self.ackReceived.append(ack)\n\n def ack_shift(self, packet):\n exp_ack = self.higherProtocol().transport.expected_ack\n if len(exp_ack) < 1:\n return 0\n shift = -1\n while(shift + 1 < len(exp_ack) and packet.Acknowledgement >= exp_ack[shift+1]):\n shift = shift + 1\n if shift != -1:\n self.valid_sent = packet.Acknowledgement\n return shift+1\n\n\n def connection_lost(self, exc):\n #print(\"PEEP: Lost connection to client. Cleaning up.\")\n if self.transport != None:\n self.transport.close()\n if self.higherProtocol():\n self.higherProtocol().connection_lost(None)\n\n def data_received(self, data):\n self.counter = 5\n self.deserializer.update(data)\n for pkt in self.deserializer.nextPackets():\n if isinstance(pkt, PEEPPacket) and pkt.validate_checksum():\n # print(\"PEEP: Received PEEP packet.\", pkt.to_string())\n # print(\"PEEP: Received PEEP packet.\", pkt.get_type_string())\n # print(\"check: \", pkt.get_type_string() == \"DATA\" and self.state == 2)\n # print(\"check: \", pkt.get_type_string() == \"DATA\")\n # print(\"check: \", self.state)\n self.packet_processing(pkt)\n\n def packet_processing(self, pkt):\n if pkt.Type == 0 and self.state == 0:\n self.state = 1\n self.valid_received = pkt.SequenceNumber + 1\n packet_response = PEEPPacket.set_synack(self.valid_sent, pkt.SequenceNumber + 1)\n packet_response_bytes = packet_response.__serialize__()\n self.valid_sent = self.valid_sent + 1\n #print(\"PEEP: Sending PEEP packet.\", packet_response.to_string())\n self.transport.write(packet_response_bytes)\n self.handshake_to_send.append(packet_response)\n thread1 = resendThread(1, \"handshakeresendThread\", self.handshake_resend)\n thread1.start()\n elif pkt.Type == 1 and self.state == 1:\n self.valid_received = pkt.SequenceNumber + 1\n packet_response = PEEPPacket.set_ack(pkt.SequenceNumber + 1)\n response_bytes = packet_response.__serialize__()\n self.expecting_receive = pkt.SequenceNumber + 1\n self.valid_sent = pkt.Acknowledgement\n #print(\"PEEP: Sending PEEP packet.\", packet_response.to_string())\n self.transport.write(response_bytes)\n self.state = 2\n # Only when handshake is completed should we call higher protocol's connection_made\n # print(\"PEEP: Handshake is completed.\")\n higher_transport = MyProtocolTransport(self.transport)\n higher_transport.seq_start(self.valid_sent)\n higher_transport.reset_all()\n self.higherProtocol().connection_made(higher_transport)\n\n elif pkt.Type == 2 and self.state == 1:\n self.state = 2\n # Only when handshake is completed should we call higher protocol's connection_made\n # print(\"PEEP: Handshake is completed.\")\n self.ackReceived.append(pkt.Acknowledgement)\n higher_transport = MyProtocolTransport(self.transport)\n higher_transport.seq_start(self.valid_sent)\n higher_transport.reset_all()\n self.higherProtocol().connection_made(higher_transport)\n elif pkt.Type == 5 and self.state == 2:\n # print(\"incoming seq: \", pkt.SequenceNumber, \"current valid received: \", self.valid_received)\n # print(\"data length : \", len(pkt.Data))\n if pkt.SequenceNumber == self.valid_received:\n assert(pkt.SequenceNumber == self.valid_received)\n self.valid_received = self.valid_received + len(pkt.Data)\n self.higherProtocol().data_received(pkt.Data)\n # print(\"PEEP: Data is passed up\")\n while(len(self.pktReceived) > 0 and self.pktReceived[0].SequenceNumber <= self.valid_received):\n if self.pktReceived[0].SequenceNumber < self.valid_received:\n self.pktReceived.pop(0)\n else:\n self.valid_received = self.valid_received + len(self.pktReceived[0].Data)\n self.higherProtocol().data_received(self.pktReceived[0].Data)\n self.pktReceived.pop(0)\n # print(\"PEEP: Data is passed up\")\n # print(\"updated valid received: \", self.valid_received)\n packet_response = PEEPPacket.set_ack(self.valid_received)\n packet_response_bytes = packet_response.__serialize__()\n self.transport.write(packet_response_bytes)\n # print(\"PEEP: Sending PEEP packet.\", packet_response.to_string())\n elif pkt.SequenceNumber > self.valid_received:\n self.pktReceived.append(pkt)\n self.sortPacketBySeqNum()\n else:\n packet_response = PEEPPacket.set_ack(self.valid_received)\n packet_response_bytes = packet_response.__serialize__()\n self.transport.write(packet_response_bytes)\n # print(\"PEEP: Sending PEEP packet.\", packet_response.to_string())\n\n elif pkt.Type == 2 and self.state == 2:\n self.addAck2Queue(pkt.Acknowledgement)\n # print(\"Expected Acknowledgement: \", self.higherProtocol().transport.expected_ack)\n # print(\"Shift: \", self.ack_shift(pkt))\n self.higherProtocol().transport.mvwindow(self.ack_shift(pkt))\n\n elif pkt.Type == 3:\n #print(pkt.SequenceNumber, self.valid_received)\n if pkt.SequenceNumber == self.valid_received:\n # print(\" Receive a RIP\")\n packet_response = PEEPPacket.set_ripack(pkt.SequenceNumber + 1)\n # print(\" Receive a RIP line 1\")\n packet_response_bytes = packet_response.__serialize__()\n # print(\" Receive a RIP line 2\")\n if self.transport != None:\n self.transport.write(packet_response_bytes)\n #print(\" Receive a valid RIP \")\n self.state = 5\n\n elif pkt.Type == 4:\n #print(\"It's RIP-ACK!!!\")\n #print(\"Expected Acknowledgement: \", self.higherProtocol().transport.expected_ack)\n #print(\"Shift: \", self.ack_shift(pkt))\n self.higherProtocol().transport.mvwindow(self.ack_shift(pkt))\n self.transport.close()\n\nclass PEEPServerProtocol(PEEPProtocol):\n\n def connection_made(self, transport):\n # print(\"PEEPServer: Received a connection from {}\".format(transport.get_extra_info(\"peername\")))\n self.transport = transport\n\n\n\nclass PEEPClientProtocol(PEEPProtocol):\n\n def connection_made(self, transport):\n # print(\"PEEPClient: Connection established with server\")\n self.transport = transport\n self.handshake()\n\n\n\n def handshake(self):\n packet_response = PEEPPacket.set_syn(self.valid_sent)\n response_bytes = packet_response.__serialize__()\n # print(\"PEEP: Starting handshake. Sending PEEP packet.\", packet_response.to_string())\n self.transport.write(response_bytes)\n self.state = 1\n self.handshake_to_send.append(packet_response)\n thread1 = resendThread(1, \"handshakeresendThread\", self.handshake_resend)\n thread1.start()\n","sub_path":"lab3/src/lab3_protocol/PEEPProtocols.py","file_name":"PEEPProtocols.py","file_ext":"py","file_size_in_byte":9252,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"414378475","text":"from Methods.uninformed_search_method import UninformedSearchMethod\nfrom Utils.utils import get_unique_string_from_words, get_list_from_word_and_mapping\n\n\nclass CryptoDfs(UninformedSearchMethod):\n\n def __init__(self, words, operator, result_word, base=16):\n self.words = words\n self.operator = operator\n self.result_word = result_word\n self.base = base\n\n if self.operator == \"-\":\n aux = self.words[0]\n self.words[0] = self.result_word\n self.result_word = aux\n self.operator = \"+\"\n\n self.full_string = get_unique_string_from_words(self.words+[self.result_word])\n self.solution = None\n self.different_letters = len(self.full_string)\n self.usage = [0] * self.base\n self.mapping = dict() # letter : hexa_number\n\n def run(self):\n self.dfs(0)\n return self.solution\n\n def dfs(self, level):\n \"\"\"\n Generates Hexadecimal numbers for the given level (letter position in full_string)\n :param level: between 0 and number of different letters\n :return: None, completes self.solution variable\n \"\"\"\n if level == self.different_letters:\n self.solution = self.mapping\n return\n for number in range(len(self.usage)):\n if self.usage[number] == 0: # number not used\n self.mapping[self.full_string[level]] = number\n self.usage[number] = 1\n if self.valid():\n self.dfs(level+1)\n if self.solution:\n return\n self.mapping.pop(self.full_string[level])\n self.usage[number] = 0\n\n def valid(self):\n \"\"\"\n Checks wether the current mapping is valid mathematically\n :return: True/False\n \"\"\"\n mapped_words = [get_list_from_word_and_mapping(word, self.mapping) for word in self.words]\n mapped_result_word = get_list_from_word_and_mapping(self.result_word, self.mapping)\n # print(\"Checking validity for {} and result {}\".format(mapped_words, mapped_result_word))\n\n for word in mapped_words + [mapped_result_word]:\n if len(word) != 1 and word[-1] == 0: # numbers can not start with 0\n return False\n\n max_len = len(mapped_result_word)\n\n # bringing all numbers to the same size\n for word in mapped_words:\n while len(word) < max_len:\n word += [0]\n\n transport = 0\n for index in range(max_len):\n local_sum = 0\n if type(mapped_result_word[index]) is not int:\n return True\n for word in mapped_words:\n if type(word[index]) is not int:\n return True # there is nothing left to check at this point, so the mapping is currently valid\n local_sum += word[index]\n\n if (local_sum + transport) % self.base != mapped_result_word[index]:\n return False\n\n transport = (local_sum + transport) // self.base\n\n if transport !=0:\n return False\n return True\n","sub_path":"ai_lab1/Methods/crypto_dfs.py","file_name":"crypto_dfs.py","file_ext":"py","file_size_in_byte":3156,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"467292339","text":"#!/usr/bin/env python\n# encoding: utf-8\n# author: 余泉\n# version: python3.6\n# file: readyaml.py\n# time: 2018\\6\\14 0014 11:15\nimport yaml\nimport os\n\n\nclass ReadYaml:\n def __init__(self, path):\n self.path = path\n\n def getyamls(self, selector):\n try:\n with open(self.path,\"r\",encoding='utf-8') as f:\n y = yaml.load(f)\n except FileNotFoundError:\n print(\"==用例文件不存在==\")\n return y.get(selector).get('value'), y.get(selector).get('name')\n\n def getyaml(self, selector):\n try:\n with open(self.path, \"r\", encoding='utf-8') as f:\n y = yaml.load(f)\n except FileNotFoundError:\n print(\"==用例文件不存在==\")\n return y.get(selector)\n\n\nif __name__ == '__main__':\n r = ReadYaml(r'.\\config.yaml')\n print(r.getyaml('Email').get('mail_pass'))\n print(r.getyamls('test')[0])\n print(r.getyaml('test'))","sub_path":"Selenium/until/readyaml.py","file_name":"readyaml.py","file_ext":"py","file_size_in_byte":943,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"416804732","text":"from django.db import models\nfrom operator import itemgetter\n\n\n# Create your models here.\nclass Team(models.Model):\n name = models.CharField(max_length=30, verbose_name='Name')\n responsible = models.CharField(max_length=40, verbose_name='Team Responsible')\n image = models.ImageField(blank=True, upload_to='teams/')\n street = models.CharField(max_length=100, verbose_name='Street + Nr.')\n city = models.CharField(max_length=40, verbose_name='City')\n telephone = models.CharField(max_length=15, verbose_name='Telephone Nr.')\n\n def __str__(self):\n return self.name\n\n\nclass Player(models.Model):\n firstname = models.CharField(max_length=50, verbose_name='First Name')\n lastname = models.CharField(max_length=50, verbose_name='Last Name')\n number = models.IntegerField(verbose_name='Number')\n team = models.ForeignKey(Team, verbose_name=\"Team\")\n\n class Meta:\n ordering = ['team', 'number']\n\n def __str__(self):\n return '%s %s' % (self.firstname, self.lastname)\n\n\nclass Location(models.Model):\n name = models.CharField(max_length=50, verbose_name='Location')\n\n def __str__(self):\n return self.name\n\n\nclass Group(models.Model):\n code = models.CharField(max_length=3, verbose_name='Group name')\n\n def get_standing(self):\n teams = []\n games = Game.objects.filter(group_id=self.id, finished=True)\n for game in games:\n if game.team_away not in teams:\n teams.append(game.team_away)\n if game.team_home not in teams:\n teams.append(game.team_home)\n\n standings = []\n for team in teams:\n team_values = {\n 'team': team,\n 'games_played': 0,\n 'games_won': 0,\n 'games_lost': 0,\n 'games_draw': 0,\n 'goals_made': 0,\n 'goals_against': 0,\n 'goals_ratio': 0,\n 'total_points': 0,\n }\n for game in games:\n if game.team_away == team:\n team_score = game.amount_away\n opponent_score = game.amount_home\n elif game.team_home == team:\n team_score = game.amount_home\n opponent_score = game.amount_away\n else:\n continue\n\n if team_score > opponent_score:\n team_values.update({\n 'games_won': team_values['games_won'] + 1,\n 'total_points': team_values['total_points'] + 3\n })\n elif team_score < opponent_score:\n team_values.update({\n 'games_lost': team_values['games_lost'] + 1\n })\n else:\n team_values.update({\n 'games_draw': team_values['games_draw'] + 1,\n 'total_points': team_values['total_points'] + 1\n })\n\n team_values.update({\n 'games_played': team_values['games_played'] + 1,\n 'goals_made': team_values['goals_made'] + team_score,\n 'goals_against': team_values['goals_against'] + opponent_score,\n 'goals_ratio': team_values['goals_ratio'] + team_score - opponent_score\n })\n\n standings.append(team_values)\n\n sorted_standings = sorted(standings, key=itemgetter('total_points', 'games_won', 'goals_ratio'), reverse=True)\n return sorted_standings\n\n def __str__(self):\n return '%s %s' % ('Group', self.code)\n\n\nclass Game(models.Model):\n team_home = models.ForeignKey(Team, related_name='team_home')\n team_away = models.ForeignKey(Team, related_name='team_away')\n amount_home = models.IntegerField(verbose_name='Score Home')\n amount_away = models.IntegerField(verbose_name='Score Away')\n group = models.ForeignKey(Group, verbose_name='Group')\n location = models.ForeignKey(Location, verbose_name='Location', blank=True, null=True)\n date = models.DateTimeField(verbose_name='Date', blank=True)\n finished = models.BooleanField(verbose_name='Finished')\n\n def __str__(self):\n return '%s, %s - %s' % (self.group, self.team_home, self.team_away)\n\n class Meta:\n ordering = ['date', 'group']\n\n\nclass Goal(models.Model):\n player = models.ForeignKey(Player, verbose_name='Player')\n game = models.ForeignKey(Game, verbose_name='Game')\n amount = models.IntegerField()\n\n def __str__(self):\n return '%s, %d goals' % (self.player, self.amount)\n\n\nclass FairPlay(models.Model):\n team = models.ForeignKey(Team, verbose_name='Team')\n game = models.ForeignKey(Game, verbose_name='Game')\n amount = models.IntegerField()\n\n def __str__(self):\n return '%s, %d/10' % (self.team, self.amount)\n","sub_path":"tournament7h/tournament/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":4900,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"211143828","text":"from pymongo import MongoClient\nfrom c3po.db.common.base import session_factory\nfrom c3po.db.dao import user, link\nfrom c3po.db.common.db_config import MONGO_URI\n\nMC = MongoClient(MONGO_URI).get_database()\n\n\ndef post(data):\n # Create new session\n session = session_factory()\n\n lttkgp_user = user.User(\n \"Default user\",\n \"1637563079601213\",\n \"https://user-images.githubusercontent.com/10023615/77320178-19fe9e00-6d36-11ea-9c0c-45f652a6da78.png\",\n )\n song_link = link.Link(data[\"link\"], 0)\n session.add(lttkgp_user)\n session.commit()\n\n\ndef first_time_init():\n posts = MC[\"posts\"]\n latest = posts.find_one()\n print(latest)\n post(latest)\n\n\nif __name__ == \"__main__\":\n first_time_init()\n","sub_path":"c3po/job/utils/lttkgp_db.py","file_name":"lttkgp_db.py","file_ext":"py","file_size_in_byte":739,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"304606163","text":"\"\"\"\n1139. Largest 1-Bordered Square (Medium)\n\nGiven a 2D grid of 0s and 1s, return the number of elements in the largest square subgrid that has all 1s on its border, or 0 if such a subgrid doesn't exist in the grid.\n\nExample 1:\n\nInput: grid = [[1,1,1],[1,0,1],[1,1,1]]\nOutput: 9\nExample 2:\n\nInput: grid = [[1,1,0,0]]\nOutput: 1\n \n\nConstraints:\n\n1 <= grid.length <= 100\n1 <= grid[0].length <= 100\ngrid[i][j] is 0 or 1\n\"\"\"\n\nclass Solution(object):\n def largest1BorderedSquare(self, grid):\n \"\"\"\n :type grid: List[List[int]]\n :rtype: int\n \"\"\"\n m = len(grid)\n if m == 0: return 0\n n = len(grid[0])\n if n == 0: return 0\n\n rows = []\n cols = []\n for i in range(m):\n rows.append([0] * n)\n cols.append([0] * n)\n\n for i in range(m):\n for j in range(n):\n if grid[i][j] == 1:\n if j == 0:\n rows[i][j] = 1\n else:\n rows[i][j] = rows[i][j-1] + 1\n if i == 0:\n cols[i][j] = 1\n else:\n cols[i][j] = cols[i-1][j] + 1\n print(rows)\n print(cols)\n\n res = 0\n for i in range(m):\n for j in range(n):\n top = min(i+1, j+1)\n side = top\n while side >= res + 1:\n if rows[i][j] >= side and cols[i][j] >= side and rows[i-side+1][j] >= side and cols[i][j-side+1] >= side:\n res = side\n break\n side -= 1\n return res ** 2\n\nif __name__ == \"__main__\":\n a = Solution()\n print(a.largest1BorderedSquare([[1,1,1],[1,0,1],[1,1,1]]))\n print(a.largest1BorderedSquare([[1,1,0,0]]))","sub_path":"python/leetcode/array/1139_largest_1_square.py","file_name":"1139_largest_1_square.py","file_ext":"py","file_size_in_byte":1818,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"117954348","text":"import serial\nimport requests\nimport time\n\nclass IOT():\n def __init__(self):\n COM_PORT = 'COM3'\n BAUD_RATES = '115200'\n self.ser = serial.Serial(COM_PORT, BAUD_RATES)\n\n def send(self, sended):\n sended = sended.encode()\n self.ser.write(sended)\n print(sended, 'sended!')\n\n def req(self, index):\n res = requests.get('http://140.113.68.171:35000/replyiot?id={}'.format(index))\n self.send(res.text)\n\niot = IOT()\nwhile True:\n iot.req(0)\n time.sleep(2)\n iot.req(1)\n time.sleep(2)\n","sub_path":"LED/IOT2.py","file_name":"IOT2.py","file_ext":"py","file_size_in_byte":550,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"543394711","text":"#!/usr/bin/env python3\n\nimport time\nimport signal\nimport urllib.request\nimport requests\nimport logging\nimport influxdb\nfrom configparser import ConfigParser\n\n# Global vars.\n# CONFIG_FILE_PATH = './mh-data-acquisition.conf' # For dev\nCONFIG_FILE_PATH = '/etc/mh-data-acquisition.conf'\ndb_client = None\nrunning = True\n\n# Initialise config.\nconfig = ConfigParser()\nconfig.read(CONFIG_FILE_PATH)\n\n# Read and assign config\napi_url = config.get(\"default\", 'api_url')\nlog_file_path = config.get(\"default\", 'log_file_path')\nlog_level = config.get(\"default\", \"log_level\")\nlog_status_period = config.getfloat(\"default\", 'log_status_period')\napi_http_port = config.getint(\"default\", 'api_http_port')\napi_fetch_period = config.getfloat(\"default\", 'api_fetch_period')\ndb_host = config.get(\"default\", 'db_host')\ndb_port = config.getint(\"default\", 'db_port')\ndb_name = config.get(\"default\", 'db_name')\nendpoints_list = [i for i in config.get(\"default\", 'endpoints').split(\"\\n\")]\n# Pythonic creation of a dict of endpoints.\n# Keys are endpoint names, values are initialised to None.\nendpoints = dict(zip(endpoints_list[::1], [None for l in endpoints_list]))\n\n# Initialise and setup logger\nlog = logging.getLogger('mh-logger')\nlog.setLevel(log_level)\nhandler = logging.FileHandler(log_file_path)\nlog.addHandler(handler)\n# Create and add logging format\nformatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s')\nhandler.setFormatter(formatter)\n\n# Dump config\nlog.info(\"loaded config:\\n\" \\\n \"\\t'log file path' : '%s'\\n\" \\\n \"\\t'log status period' : '%s'\\n\" \\\n \"\\t'api url' : '%s'\\n\" \\\n \"\\t'api http port' : '%s'\\n\" \\\n \"\\t'api fetch period' : '%s'\\n\" \\\n \"\\t'db host' : '%s'\\n\" \\\n \"\\t'db port' : '%s'\\n\" \\\n \"\\t'db name' : '%s'\\n\" \\\n \"\\t'endpoints' : '%s'\" \\\n % (log_file_path, log_status_period, api_url, api_http_port, api_fetch_period,\n db_host, db_port, db_name, endpoints_list)\n )\n\n\n# Signal handler.\ndef handler(a, b): # define the handler\n log.info(\"Caught SIGTERM signal. Exiting\")\n global running\n running = False\n\n\n# Connect to InfluxDB\ndef db_connect():\n global db_client\n db_connected = False\n # TODO - make hardcoded values configurable items\n retry_wait_secs = 10\n max_retries = 5\n retry_counter = max_retries\n\n while not db_connected and retry_counter > 0:\n try:\n db_client = influxdb.InfluxDBClient(host=db_host, port=db_port)\n if db_name not in [v['name'] for v in db_client.get_list_database()]:\n db_client.create_database(db_name)\n log.debug(\"Database: %s created on host %s\" % (db_name, db_host))\n db_client.switch_database(db_name)\n\n except requests.exceptions.ConnectionError as e:\n log.error(\"ConnectionError exception connecting to DB ... still starting up?\")\n retry_counter -= 1\n\n # Too many retry attempts, exit\n if retry_counter <= 0:\n log.warning(\"DB connection retries (%d) exceeded, giving up\" % max_retries)\n raise e\n\n # We're probably just starting up, so wait a while ...\n time.sleep(retry_wait_secs)\n\n except Exception as e:\n log.error(\"Unhandled Exception connecting to DB.\")\n log.exception(e)\n raise e\n else:\n db_connected = True\n log.info(\"Connected to DB OK\")\n\n\n# Main run loop\ndef main():\n global running\n\n json_body = [{\n \"measurement\": \"fast_data\",\n \"fields\": {}\n }]\n\n # Timer used for periodic log output only.\n now = time.time() - log_status_period\n counter = 0\n\n try:\n db_connect()\n while running:\n\n #\n # Fetch data from all endpoints.\n #\n for endpoint in endpoints.keys():\n try:\n f = urllib.request.urlopen(\"%s:%s/%s\" % (api_url, api_http_port, endpoint))\n except ConnectionError as e:\n log.error(\"Exception connecting to API.\")\n log.error(\"e: %s\" % str(e))\n raise e\n endpoints[endpoint] = float(f.read())\n\n counter = counter + 1\n\n #\n # Format data for db.\n #\n json_body[0]['fields'] = endpoints\n # log.info(\"json_body[fields]: %s\" % json_body[0]['fields'])\n\n #\n # Insert data into db\n #\n try:\n # pprint.pprint(json_body)\n db_client.write_points(json_body)\n except (requests.exceptions.ConnectionError, influxdb.exceptions.InfluxDBServerError) as e:\n log.error(\"ConnectionError or InfluxDBServerError exception writing data to DB\")\n raise e\n except Exception as e:\n log.error(\"Unhandled Exception writing data to DB.\")\n log.exception(e)\n raise e\n\n # Log (sparingly) for reassurance.\n if time.time() - now > log_status_period:\n log.info(\"stored %s records\" % counter)\n now = time.time()\n\n # Wait for the next time ...\n time.sleep(api_fetch_period)\n\n except Exception as e:\n log.error(\"Caught Exception, Exiting\")\n running = False\n\n finally:\n if type(db_client) is influxdb.client.InfluxDBClient:\n log.info(\"Closing db client connection\")\n db_client.close()\n\n\nif __name__ == \"__main__\":\n log.info(\"Started\")\n signal.signal(signal.SIGTERM, handler) # assign the handler to the signal SIGTERM\n main()\n log.info(\"Exited\\n\\n\")\n","sub_path":"raspi/tracerbn/daq/mh-data-acquisition.py","file_name":"mh-data-acquisition.py","file_ext":"py","file_size_in_byte":5774,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"275118840","text":"## 4. Ejercicio al Formulario del Ejercicio 3 , agrege los siguientes botones 1- un botón Alta \n## que inicia otra venta donde puedo ingresar una ciudad y su código postal .\n## 2 – un botón Baja que borra del listad de ciudades la ciudad que esta selecionada en Treeview .\n## 3 – un botón Modificar . Todos los cambios se deben ver reflejados en la lista que se muestra . \n\n\nimport tkinter as tk\nfrom tkinter import ttk\n\n\n\nclass Application(ttk.Frame):\n\n def __init__(self, main_window):\n super().__init__(main_window)\n main_window.title(\"Formulario\")\n\n self.treeview = ttk.Treeview(self)\n item = self.treeview.insert(\"\", tk.END, text=\"Rosario\")\n self.treeview.insert(item, tk.END, text=\"2000\")\n item = self.treeview.insert(\"\", tk.END, text=\"Roldan\")\n self.treeview.insert(item, tk.END, text=\"2134\")\n item = self.treeview.insert(\"\", tk.END, text=\"Funes\")\n self.treeview.insert(item, tk.END, text=\"2132\")\n item = self.treeview.insert(\"\", tk.END, text=\"San Lorenzo\")\n self.treeview.insert(item, tk.END, text=\"2200\")\n item = self.treeview.insert(\"\", tk.END, text=\"Villa Gobernador Gálvez\")\n self.treeview.insert(item, tk.END, text=\"2124\")\n self.treeview.pack()\n\n self.pack()\n\n\nmain_window = tk.Tk()\napp = Application(main_window) #instancio\n\n#Inicio alta\ndef form_alta():\n otra_ventana = tk.Toplevel(main_window) #creo una nueva ventana\n main_window.iconify() #minimizo la principal\n txt_ciudad = tk.StringVar() #instancio las variables para los entry\n txt_CP = tk.StringVar()\n label = tk.Label(otra_ventana, text=\"Ciudad: \")\n label2 = tk.Label(otra_ventana, text=\"Código Postal: \")\n label.grid(column=1, row=1, padx=(50,50), pady=(10,10))\n label2.grid(column=2, row=1, padx=(40,40), pady=(10,5))\n\n #tuve que separar la definicion del grid porque si no no asiganba la variable.\n Ciudad = tk.Entry(otra_ventana,textvariable=txt_ciudad)\n Ciudad.grid(column=1, row=2, padx=(5,5), pady=(10,5))\n CP = tk.Entry(otra_ventana,textvariable=txt_CP)\n CP.grid(column=2, row=2, padx=(5,5), pady=(10,5))\n\n btn_alta = tk.Button(otra_ventana, text=\"Agregar\")\n btn_alta.grid(column=3, row=2, padx=(50,50), pady=(10,10))\n def alta(event):\n print(Ciudad.get())\n item = app.treeview.insert(\"\", tk.END, text=Ciudad.get())\n app.treeview.insert(item, tk.END, text=CP.get())\n main_window.deiconify()\n\n btn_alta.bind(\"\", alta)\n\nbtn_frm_alta = tk.Button(main_window, text=\"Dar de alta una Ciudad\", command=form_alta)\nbtn_frm_alta.pack()\n#Fin alta\n\n#Inicio Baja\ndef baja():\n curItem = app.treeview.focus() #trae el elemento que está seleccionado\n app.treeview.delete(curItem)\nbtn_baja = tk.Button(main_window, text=\"Baja\", command=baja)\nbtn_baja.pack()\n#Fin Baja\n\n#Inicio Modificacion\ndef form_modificacion():\n otra_ventana = tk.Toplevel(main_window) #creo una nueva ventana\n main_window.iconify() #minimizo la principal\n elem = app.treeview.focus()\n elem_child = app.treeview.get_children(elem) #app.treeview.selection()[0]\n print (app.treeview.item(elem_child))\n txt_ciudad = tk.StringVar(otra_ventana, value=app.treeview.item(elem)['text']) #instancio las variables para los entry\n\n txt_CP = tk.StringVar(otra_ventana, value=app.treeview.item(elem_child)['text'])\n label = tk.Label(otra_ventana, text=\"Ciudad: \")\n label2 = tk.Label(otra_ventana, text=\"Código Postal: \")\n label.grid(column=1, row=1, padx=(50,50), pady=(10,10))\n label2.grid(column=2, row=1, padx=(40,40), pady=(10,5))\n\n #tuve que separar la definicion del grid porque si no no asiganba la variable.\n Ciudad = tk.Entry(otra_ventana,textvariable=txt_ciudad)\n Ciudad.grid(column=1, row=2, padx=(5,5), pady=(10,5))\n CP = tk.Entry(otra_ventana,textvariable=txt_CP)\n CP.grid(column=2, row=2, padx=(5,5), pady=(10,5))\n\n btn_alta = tk.Button(otra_ventana, text=\"Modificar\")\n btn_alta.grid(column=3, row=2, padx=(50,50), pady=(10,10))\n def modificacion(event):\n print(Ciudad.get(),CP.get())\n app.treeview.item(elem,text=Ciudad.get()) #.update(Ciudad.get())\n app.treeview.item(elem_child,text=CP.get())\n main_window.deiconify()\n\n btn_alta.bind(\"\", modificacion)\n\nbtn_frm_alta = tk.Button(main_window, text=\"Modificar\", command=form_modificacion)\nbtn_frm_alta.pack()\n#Fin Modificacion\napp.mainloop()\n","sub_path":"practico_04/ejercicio04.py","file_name":"ejercicio04.py","file_ext":"py","file_size_in_byte":4445,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"529535568","text":"# Jonathan Kaufmann\n# CSC 280\n# 9/14/16\n# Assignment 3\n\n'''\nConvert temperature from c to f and back\nUse input to collect temperature and degree type from user\n'''\n\ndef tempConvC(temp):\n # Converts c temp to f temp, takes temperature as argument\n new_temp = temp * (9/5) + 32\n temp_string = str(temp) + \" degrees celsius is \" + str(new_temp) + \" degrees farenheit.\"\n return temp_string\n\n\ndef tempConvF(temp):\n # Converts f temp to c temp, takes temperature as argument\n new_temp = (temp - 32) * (5/9)\n temp_string = str(temp) + \" degrees farenheit is \" + str(new_temp) + \" degrees celsius.\"\n return temp_string\n\n\ndef input_function():\n # Gets input for tempConverter and calls it. Prints returned value.\n # Get temperature\n print(\"This program converts celsius to farenheit and vice versa.\")\n temperature = float(input(\"Please input a temperature to convert: \"))\n # Get unit type\n print(\"Is your temperature expressed in celsius or farenheit?\")\n unit = input(\"Input c for celsius or f for farenheit: \")\n unit = unit.lower()\n # Get conversion\n\n # Call farenheit conversion if farenheit\n if unit == 'f':\n result =tempConvF(temperature)\n\n # Call celsius conversion if celsius\n if unit == 'c':\n result = tempConvC(temperature)\n \n # Print result\n print(result)\n\n\n# Call input_function\ninput_function()\n","sub_path":"9841_Assignment3.py","file_name":"9841_Assignment3.py","file_ext":"py","file_size_in_byte":1387,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"198624400","text":"#! /usr/bin/env python3.4\n#\n#$Author: ee364e07 $\n#$Date: 2015-10-18 15:41:17 -0400 (Sun, 18 Oct 2015) $\n#$HeadURL: svn+ssh://ece364sv@ecegrid/home/ecegrid/a/ece364sv/svn/F15/students/ee364e07/Prelab07/points.py $\n#$Revision: 82701 $\n\nclass PointND:\n\n def __init__(self, *args):\n if len(args) == 0:\n raise ValueError(\"Please enter at least one argument.\")\n\n for num in args:\n if type(num) is not float:\n raise ValueError(\"Cannot instantiate an object with non-float values.\")\n\n self.t = tuple(args)\n self.n = len(args)\n\n def __str__(self):\n rstr = '('\n for ind,item in enumerate(self.t):\n if ind == len(self.t)-1:\n rstr += '{0:.2f}'.format(item)\n else:\n rstr += '{0:.2f}, '.format(item)\n rstr += ')'\n return rstr\n\n def __hash__(self):\n return hash(self.t)\n\n def distanceFrom(self,other):\n if other.n != self.n:\n raise ValueError(\"Cannot calculate distance between points of different cardinality.\")\n\n dist = 0\n for ind,item in enumerate(self.t):\n dist += (item - other.t[ind])**2\n\n dist = (dist)**0.5\n return dist\n\n def nearestPoint(self,points):\n if len(points) == 0:\n raise ValueError(\"Input cannot be empty.\")\n\n dist = self.distanceFrom(points[0])\n repnt = points[0]\n\n for item in points:\n newdist = self.distanceFrom(item)\n\n if(newdist < dist):\n dist = newdist\n repnt = item\n\n return repnt\n\n def clone(self):\n q = PointND(0.0)\n q.t = self.t\n return q\n\n def __add__(self, other):\n if type(other) == float:\n newcords = []\n rpoint = PointND(0.0)\n for item in self.t:\n newcords.append(item+other)\n\n rpoint.t = tuple(newcords)\n rpoint.n = len(rpoint.t)\n return rpoint\n\n else:\n if other.n != self.n:\n raise ValueError(\"Cannot operate on points with different cardinalities\")\n newcords = []\n rpoint = PointND(0.0)\n for ind,item in enumerate(self.t):\n newcords.append(item+other.t[ind])\n\n\n rpoint.t = tuple(newcords)\n rpoint.n = len(rpoint.t)\n return rpoint\n\n __radd__ = __add__\n\n def __sub__(self, other):\n if type(other) == float:\n newcords = []\n rpoint = PointND(0.0)\n for item in self.t:\n newcords.append(item-other)\n\n rpoint.t = tuple(newcords)\n rpoint.n = len(rpoint.t)\n return rpoint\n\n else:\n if other.n != self.n:\n raise ValueError(\"Cannot operate on points with different cardinalities\")\n newcords = []\n rpoint = PointND(0.0)\n for ind,item in enumerate(self.t):\n newcords.append(item-other.t[ind])\n\n rpoint.t = tuple(newcords)\n rpoint.n = len(rpoint.t)\n return rpoint\n\n def __mul__(self, other):\n newcords = []\n rpoint = PointND(0.0)\n for item in self.t:\n newcords.append(item*other)\n\n rpoint.t = tuple(newcords)\n rpoint.n = len(rpoint.t)\n return rpoint\n\n __rmul__ = __mul__\n\n def __truediv__(self, other):\n newcords = []\n rpoint = PointND(0.0)\n for item in self.t:\n newcords.append(item/other)\n\n rpoint.t = tuple(newcords)\n rpoint.n = len(rpoint.t)\n return rpoint\n\n def __neg__(self):\n newcords = []\n rpoint = PointND(0.0)\n for item in self.t:\n newcords.append(-item)\n\n rpoint.t = tuple(newcords)\n rpoint.n = len(rpoint.t)\n return rpoint\n\n def __getitem__(self, item):\n return self.t[item]\n\n def __eq__(self, other):\n if other.n != self.n:\n raise ValueError(\"Cannot compare points with different cardinalities.\")\n\n for ind,item in enumerate(self.t):\n if not (item == other.t[ind]):\n return False\n\n return True\n\n def __ne__(self, other):\n if other.n != self.n:\n raise ValueError(\"Cannot compare points with different cardinalities.\")\n\n for ind,item in enumerate(self.t):\n if not (item != other.t[ind]):\n return False\n\n return True\n\n def __gt__(self, other):\n if other.n != self.n:\n raise ValueError(\"Cannot compare points with different cardinalities.\")\n org = PointND(0.0)\n zeros = [0.0]*self.n\n org.t = tuple(zeros)\n org.n = self.n\n\n dist1 = self.distanceFrom(org)\n dist2 = other.distanceFrom(org)\n\n if dist1 > dist2:\n return True\n\n else:\n return False\n\n def __ge__(self, other):\n if other.n != self.n:\n raise ValueError(\"Cannot compare points with different cardinalities.\")\n org = PointND(0.0)\n zeros = [0.0]*self.n\n org.t = tuple(zeros)\n org.n = self.n\n\n dist1 = self.distanceFrom(org)\n dist2 = other.distanceFrom(org)\n\n if dist1 >= dist2:\n return True\n\n else:\n return False\n\n def __lt__(self, other):\n if other.n != self.n:\n raise ValueError(\"Cannot compare points with different cardinalities.\")\n org = PointND(0.0)\n zeros = [0.0]*self.n\n org.t = tuple(zeros)\n org.n = self.n\n\n dist1 = self.distanceFrom(org)\n dist2 = other.distanceFrom(org)\n\n if dist1 < dist2:\n return True\n\n else:\n return False\n\n def __le__(self, other):\n if other.n != self.n:\n raise ValueError(\"Cannot compare points with different cardinalities.\")\n org = PointND(0.0)\n zeros = [0.0]*self.n\n org.t = tuple(zeros)\n org.n = self.n\n\n dist1 = self.distanceFrom(org)\n dist2 = other.distanceFrom(org)\n\n if dist1 >= dist2:\n return True\n\n else:\n return False\n\nclass Point3D(PointND):\n\n def __init__(self,x=0.0,y=0.0,z=0.0):\n PointND.__init__(self,x,y,z)\n self.x = x\n self.y = y\n self.z = z\n\n\nclass PointSet():\n\n def __init__(self, **kwargs):\n if len(kwargs) == 0:\n self.points = set()\n self.n = 0\n\n for key in kwargs:\n if key == 'pointList':\n templist = kwargs['pointList']\n\n if len(templist) == 0:\n raise ValueError(\"\\'pointList\\' input parameter cannot be empty.\")\n\n self.n = templist[0].n\n for item in templist:\n if item.n != self.n:\n raise ValueError(\"Expecting a point with cardinality {}.\".format(self.n))\n\n self.points = set(templist)\n\n else:\n raise KeyError(\"\\'pointList\\' input parameter not found.\")\n\n def addPoint(self,p):\n if p.n != self.n:\n raise ValueError(\"Expecting a point with cardinality {}.\".format(self.n))\n\n self.points.add(p)\n\n def count(self):\n return len(self.points)\n\n def computeBoundingHyperCube(self):\n tempts = list(self.points)\n minpts = list(tempts[0].t)\n maxpts = list(tempts[0].t)\n\n i = 0\n for point in self.points:\n for ind,cord in enumerate(point.t):\n if cord < minpts[ind]:\n minpts[ind] = cord\n\n if cord > maxpts[ind]:\n maxpts[ind] = cord\n\n rmin = PointND(0.0)\n rmax = PointND(0.0)\n\n rmin.t = tuple(minpts)\n rmin.n = self.n\n rmax.t = tuple(maxpts)\n rmax.n = self.n\n\n return (rmin,rmax)\n\n def computeNearestNeighbors(self,otherPointSet):\n if self.n != otherPointSet.n:\n raise ValueError(\"Expecting a point with cardinality {}.\".format(self.n))\n rlist = []\n for point in self.points:\n close = point.nearestPoint(list(otherPointSet.points))\n app = (point,close)\n app = tuple(app)\n rlist.append(app)\n\n rlist = sorted(rlist)\n print(rlist)\n return rlist\n\n\n def __add__(self, other):\n if other.n != self.n:\n raise ValueError(\"Expecting a point with cardinality {}.\".format(self.n))\n\n self.points.add(other)\n\n return(self)\n\n def __sub__(self, other):\n if other.n != self.n:\n raise ValueError(\"Expecting a point with cardinality {}.\".format(self.n))\n\n if other in self.points:\n self.points.remove(other)\n return(self)\n\n else:\n return(self)\n\n\n def __contains__(self, item):\n if item in self.points:\n return True\n else:\n return False\n\n\n\n\nif __name__ == \"__main__\":\n pass\n\n\n\n","sub_path":"Prelab07/points.py","file_name":"points.py","file_ext":"py","file_size_in_byte":9030,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"516788686","text":"import imp\n\nclass Plugin(object):\n def __init__(self, name, alias=None):\n self.name = name.title()\n self.filename = name.lower()\n self.alias = name if not alias else alias\n self.fp = None\n \n try:\n self.fp, self.path, self.desc = imp.find_module(self.filename)\n except ImportError as e:\n print('No recognized plugin [ %s ]' %name)\n\n def load(self, parent):\n if self.fp:\n self.module = imp.load_module(self.alias, self.fp, \n self.path, self.desc)\n cls = getattr(self.module, self.name.title())\n setattr(parent, self.alias, cls())\n","sub_path":"plugin.py","file_name":"plugin.py","file_ext":"py","file_size_in_byte":660,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"284067537","text":"from canny2 import updEdge\nfrom canny3 import extractEdges\nfrom artUtils import *\n\nimport networkx as nx\nimport itertools\nimport pandas as pd\nfrom scipy.optimize import linear_sum_assignment\nfrom scipy.spatial import distance_matrix\nfrom scipy.ndimage import convolve\nimport matplotlib.pyplot as plt\nfrom matplotlib.widgets import Slider, TextBox, CheckButtons\nimport numpy as np\nimport sys\nimport os\nfrom PIL import Image\n\nprint(sys.argv)\nprint(len(sys.argv) > 1)\ninteractive = (len(sys.argv) > 1)\n# interactive = True\n\n# Binning and hatching parameters\nints = np.array([30, 30, 60, 90, 255]) # Brightness cutoffs\nspacing = np.array([7, 7, 13, 15, 20]) # Corresponding line densities\norientation = np.array([-1, 1, -1, 1, -1]) # Direction (not all the same way)\noffset = np.array([0, 0, 0, 0, 100000]) # Any offsets\n\nedgethr = [100, 200]\n\n# Pull the image\nfolder = '/Users/Ben/Desktop/Etch/'\njpgname = 'Stiller'\nim_path = os.path.join(folder, jpgname+'.jpg')\nIm = np.array(Image.open(im_path).convert('RGB'))\nIg = rgb2gray(Im)\n\nblurred = []\nbinIm = []\nsI = []\nedIm = np.zeros(Ig.shape)\ncanedges = []\nalledges = [[] for i in ints]\nhatchedgim = [[] for i in ints]\n\n\ndef main():\n global Ig, blurred, thresh # TODO Find a better way than global vars\n\n blurred = blur(Ig) # Smooth out any small specks\n # Build up a matrix from various bins and operations\n sumImage = Update(0, 0, 0, 0, 1) # Edge detection\n sumImage = Update(1, 0, 0, 0, 0) # Set up bin images\n for i in range(0, len(ints)):\n sumImage = Update(0, i+1, 0, 0, 0) # Hatch the bin images\n\n SliderFigure(sumImage)\n # plt.imshow(1-sumImage, cmap='gray', vmin=0, vmax=1)\n # plt.show()\n print('Start graph work')\n G, stops = genGraph(alledges)\n\n print('Write to file')\n np.set_printoptions(threshold=sys.maxsize)\n stopstring = 'asd'\n stopstring = np.array2string(stops, separator=',')\n # print(stopstring)\n file1 = open('../rPi/public/art/'+jpgname+'.json', \"w\")\n file1.write(FormatFile(stopstring))\n file1.close()\n # Checks\n # print(list(G.degree()))\n # print(len(nOdeg(G)))\n # print(nx.is_eulerian(G))\n\n\ndef FormatFile(stopstring):\n pretext = '{\"name\":\"'+jpgname+'\",\"pxSpeed\":50,\"pxPerRev\":200,\"points\":'\n return pretext+stopstring+'}'\n\n\ndef SliderFigure(sumImage):\n global ints, spacing, threshhold\n\n # if not interactive:\n # return\n\n fig = plt.figure(figsize=(12, 7))\n ax = fig.add_subplot(111)\n fig.subplots_adjust(left=0.45, bottom=0.35)\n ax.imshow(1-sumImage, cmap='gray', vmin=0, vmax=1)\n\n sax1 = fig.add_axes([0.15, 0.05, 0.5, 0.03])\n sax2 = fig.add_axes([0.15, 0.10, 0.5, 0.03])\n sax3 = fig.add_axes([0.15, 0.15, 0.5, 0.03])\n sax4 = fig.add_axes([0.15, 0.20, 0.5, 0.03])\n sax5 = fig.add_axes([0.15, 0.25, 0.5, 0.03])\n s1 = Slider(sax1, 'Int1', 0, 255, valfmt='%0.0f', valinit=ints[0])\n s2 = Slider(sax2, 'Int2', 0, 255, valfmt='%0.0f', valinit=ints[1])\n s3 = Slider(sax3, 'Int3', 0, 255, valfmt='%0.0f', valinit=ints[2])\n s4 = Slider(sax4, 'Int4', 0, 255, valfmt='%0.0f', valinit=ints[3])\n s5 = Slider(sax5, 'Int5', 0, 255, valfmt='%0.0f', valinit=ints[4])\n s1.on_changed(lambda x: slid(1, x))\n s2.on_changed(lambda x: slid(2, x))\n s3.on_changed(lambda x: slid(3, x))\n s4.on_changed(lambda x: slid(4, x))\n s5.on_changed(lambda x: slid(5, x))\n tax1 = fig.add_axes([0.7, 0.05, 0.05, 0.03])\n tax2 = fig.add_axes([0.7, 0.10, 0.05, 0.03])\n tax3 = fig.add_axes([0.7, 0.15, 0.05, 0.03])\n tax4 = fig.add_axes([0.7, 0.20, 0.05, 0.03])\n tax5 = fig.add_axes([0.7, 0.25, 0.05, 0.03])\n t1 = TextBox(tax1, '', initial=str(spacing[0]))\n t2 = TextBox(tax2, '', initial=str(spacing[1]))\n t3 = TextBox(tax3, '', initial=str(spacing[2]))\n t4 = TextBox(tax4, '', initial=str(spacing[3]))\n t5 = TextBox(tax5, '', initial=str(spacing[4]))\n t1.on_submit(lambda x: space(1, x))\n t2.on_submit(lambda x: space(2, x))\n t3.on_submit(lambda x: space(3, x))\n t4.on_submit(lambda x: space(4, x))\n t5.on_submit(lambda x: space(5, x))\n\n eax1 = fig.add_axes([0.15, 0.5, 0.2, 0.03])\n eax2 = fig.add_axes([0.15, 0.55, 0.2, 0.03])\n e1 = Slider(eax1, 'Thr1', 0, 1000, valfmt='%0.0f', valinit=edgethr[0])\n e2 = Slider(eax2, 'Thr0', 0, 1000, valfmt='%0.0f', valinit=edgethr[1])\n e1.on_changed(lambda x: thresh(1, x))\n e2.on_changed(lambda x: thresh(2, x))\n\n def slid(ind, val):\n global ints, spacing, threshhold\n ints[ind-1] = int(round(val))\n sumImage = Update(1, 0, 0, 0, 0) # Set up bin images\n sumImage = Update(0, ind, 0, 0, 0)\n # sumImage = Update(0, 2, 0, 0, 0)\n # sumImage = Update(0, 3, 0, 0, 0)\n # sumImage = Update(0, 4, 0, 0, 0)\n # sumImage = Update(0, 5, 0, 0, 0)\n ax.imshow(1-sumImage, cmap='gray', vmin=0, vmax=1)\n fig.canvas.draw()\n\n def space(ind, val):\n global ints, spacing, threshhold\n spacing[ind-1] = int(val)\n sumImage = Update(0, ind, 0, 0, 0)\n ax.imshow(1-sumImage, cmap='gray', vmin=0, vmax=1)\n fig.canvas.draw()\n\n def thresh(ind, val):\n global edgethr\n edgethr[ind-1] = val\n sumImage = Update(0, 0, 0, 0, 1) # Set up bin images\n ax.imshow(1-sumImage, cmap='gray', vmin=0, vmax=1)\n fig.canvas.draw()\n\n plt.show()\n plt.close()\n print(edgethr)\n print(ints)\n\ndef Update(nint, sp, ori, off, edge):\n if edge:\n print('Run edge detection')\n global edIm, canedges\n edIm = extractEdges(im_path, edgethr[0], edgethr[1])\n # edIm = updEdge(Ig, 100000)\n print('Link edge detection')\n canedges = ConnectCanny(edIm)\n\n if nint:\n print('Bin images')\n global binIm\n binIm = bin(blurred, ints)\n\n if sp or ori or off:\n print('Build hatch', sp, ori, off)\n global alledges, hatchedgim\n valid = (int(sp == 0) + int(ori == 0) + int(off == 0))\n if valid != 2:\n print('hmmm')\n # Which bin are we hatching?\n s = sp + ori + off - 1\n # Build the full matrix hatch\n h = buildHatch(binIm.shape, orientation[s], spacing[s], offset[s])\n # Boolean mask with bin matrix\n mh = (h & (binIm <= ints[s]))\n # plt.imshow(1-mh, cmap='gray', vmin=0, vmax=1)\n # plt.show()\n # Add edges to the graph\n alledges[s] = createDiagEdges(mh, orientation[s])\n hatchedgim[s] = mh > 0\n\n hIm = np.zeros(Ig.shape)\n for hI in hatchedgim:\n if (len(hI) != 0):\n hIm = (hIm + hI) > 0\n sumImage = edIm + hIm\n sumImage = despeck(sumImage)\n\n return sumImage\n\n\n# Link up adjacent points returned from edge detection\ndef ConnectCanny(cIm):\n # plt.imshow(1-cIm, cmap='gray', vmin=0, vmax=1)\n # plt.show()\n cpts = getCities(cIm)\n print('ConnectCanny', len(cpts))\n G = nx.Graph()\n\n G = NeiEdge(G, cIm, 2)\n G = NeiEdge(G, cIm, 4)\n G = NeiEdge(G, cIm, 1)\n G = NeiEdge(G, cIm, 3)\n return list(G.edges())\n\n\n# Create evenly-spaced lines in a matrix\n# shape: size of matrix\n# direction: (1 or -1) * 45 deg\n# spacing: # of pixels between lines\n# offset: shift left or right (so hatches don't overlap each other)\ndef buildHatch(shape, direction, spacing, offset):\n a = np.zeros(shape)\n m = np.arange(0, shape[0])\n n = np.arange(0, shape[1])\n A, B = np.meshgrid(m, n)\n\n return np.transpose(abs(A + B * direction) % (spacing + 1) == offset)\n\n\n# Given lines from buildHatch, turn matrix points into long edges\ndef createDiagEdges(mask, ori):\n G = NeiEdge(nx.Graph(), mask, (2+ori))\n\n # Each component is a long edge\n edges = []\n subs = (list(nx.connected_components(G)))\n # Extract the endpoints (degree == 1)\n # for s in subs:\n # n1 = [v for v, d2 in G.degree(list(s)) if d2 == 1]\n # edges.append(n1)\n edges = list(map(lambda s: [v for v, d2 in G.degree(list(s)) if d2 == 1], subs))\n return edges\n\n\n# Connect separate subgraphs into one big subgraph with optimal new edges\ndef ConnectSubgraphs(G, nnodes, dnodes):\n sub_graphs = list(nx.connected_components(G))\n all_coord = [dnodes[x] for x in list(G.nodes())]\n A = NodeMap(all_coord)\n\n\n # TODO: rewrite: shift up and left, connect if include other, repeat if not\n\n\n # For each subgraph, connect it to the closest node in a different subgraph\n # Repeat until there's only one\n while len(sub_graphs) > 1:\n\n for i, sg in enumerate(sub_graphs):\n print(i)\n if i == len(sub_graphs) - 1:\n continue\n sg = nx.node_connected_component(G, list(sg)[0])\n sg_node_num = list(sg) # Get all nodes in the subgraph\n sg_node_coord = [dnodes[x] for x in sg_node_num]\n\n newedge = GrowBorder(A, sg_node_coord)\n if newedge != None:\n G.add_edge(nnodes[newedge[0]], nnodes[newedge[1]], weight=newedge[2])\n\n sub_graphs = list(nx.connected_components(G))\n\n return G\n\n\n# Add a parallel edge to any degee 1 node with an odd node as a neighbor\ndef EasyLinkOne(G):\n n1 = n1deg(G)\n # Get the neighbor for each d1 node (and the neighbors degree)\n n1nei = list(map(lambda e: list(G.neighbors(e))[0], n1))\n neideg = list(map(lambda e: G.degree(e) % 2 == 1, n1nei))\n # Get only d1 nodes with an odd degree neighbor (and get that neighbor)\n filtern1 = [i for indx, i in enumerate(n1) if neideg[indx] is True]\n filterne = [i for indx, i in enumerate(n1nei) if neideg[indx] is True]\n # Add parallel edges\n for n1, ne in zip(filtern1, filterne):\n if G.degree(n1) != 1:\n continue\n G.add_edge(n1, ne, weight=G.get_edge_data(n1, ne)[0]['weight'])\n return G\n\n\n# Add a parallel edge to any odd node with an odd node as a neighbor\ndef EasyLinkOdd(G):\n nO = nOdeg(G)\n nOnei = list(map(lambda e: list(G.neighbors(e))[0], nO))\n neideg = list(map(lambda e: G.degree(e) % 2 == 1, nOnei))\n\n filternO = [i for indx, i in enumerate(nO) if neideg[indx] is True]\n filterne = [i for indx, i in enumerate(nOnei) if neideg[indx] is True]\n\n for nO, ne in zip(filternO, filterne):\n if G.degree(nO) % 2 != 1:\n continue\n G.add_edge(nO, ne, weight=G.get_edge_data(nO, ne)[0]['weight'])\n\n return G\n\n\ndef LinkDegOne(G, nnodes, dnodes):\n nodes_one_degree = n1deg(G)\n one_coord = [dnodes[p] for p in nodes_one_degree]\n\n nodes_all_degree = list(G.nodes())\n all_coord = [dnodes[p] for p in nodes_all_degree]\n\n # TODO change to lin sum assignment?\n\n for i, p in enumerate(one_coord):\n if G.degree(nnodes[p]) != 1:\n continue\n\n # print(i)\n ld = distance_matrix([p], all_coord)\n ld[0, nnodes[p]] = 100000\n nei = ld.argmin()\n G.add_edge(nnodes[p], nnodes[all_coord[nei]], weight=ld[0, nei])\n # newedge = GrowBorder(A, [p])\n # if newedge is not None:\n # G.add_edge(nnodes[newedge[0]], nnodes[newedge[1]], weight=newedge[2])\n\n return G\n\n\n# Link odd nodes together but only if they are each other's best odd\ndef LinkDegOdd(G, nnodes, dnodes):\n nodes_odd_degree = nOdeg(G)\n odd_coord = [dnodes[p] for p in nodes_odd_degree]\n\n for i, p in enumerate(odd_coord):\n if G.degree(nnodes[p]) % 2 != 1:\n continue\n\n # print(i)\n ld = distance_matrix([p], odd_coord)\n ld[0, i] = 100000\n nei = ld.argmin()\n if ld[0, nei] < 30:\n G.add_edge(nnodes[p], nnodes[odd_coord[nei]], weight=ld[0, nei])\n\n return G\n\n\n# Link remaining odd nodes by adding parallel paths between them\n# Try to find minimum weight matching\n# https://brooksandrew.github.io/simpleblog/articles/intro-to-graph-optimization-solving-cpp/\ndef PathFinder(G, dnodes):\n nO = nOdeg(G)\n A = np.zeros((len(list(G.nodes())), len(list(G.nodes()))))\n # Get path lengths from all odd nodes to all nodes\n # Populate a matrix\n print('Get all path lengths')\n for t in nO:\n length = nx.single_source_dijkstra_path_length(G, t)\n lk = list(length.keys())\n lv = list(length.values())\n A[t, lk] = lv\n\n # Only look at odd to odd paths\n np.fill_diagonal(A, 1000000) # No self loops\n A2 = A[nO, :]\n A2 = A2[:, nO]\n\n # Get all combinations of two odd nodes\n odd_node_pairs = list(itertools.combinations(nO, 2))\n print('Num pairs', len(odd_node_pairs))\n # Construct a temp complete graph of odd nodes\n # edge weights = path lengths (negative for max weight matching)\n OddComplete = nx.Graph()\n for op in odd_node_pairs:\n OddComplete.add_edge(op[0], op[1], weight=-A[op[0], op[1]])\n\n # This gets optimal matching, probably can do near-optimal matching\n print('Begin matching')\n odd_matching_dupes = nx.algorithms.max_weight_matching(OddComplete, True)\n print('End matching')\n if type(odd_matching_dupes) is set:\n odd_matching = list(pd.unique([tuple(sorted([k, v])) for k, v in list(odd_matching_dupes)]))\n else:\n odd_matching = list(pd.unique([tuple(sorted([k, v])) for k, v in odd_matching_dupes.items()]))\n\n # For each match that is created\n print('Add parallel paths')\n for a in odd_matching:\n # Get the full path between the two\n p = nx.dijkstra_path(G, a[0], a[1])\n # Add parallel edges from the path\n for i in range(0, len(p) - 1):\n w = pythag(dnodes[p[i]], dnodes[p[i+1]])\n G.add_edge(p[i], p[i+1], weight=w)\n\n return G\n\n\ndef PlotGraph(G, ndnodes):\n if not interactive:\n return\n nx.draw_networkx_edges(G, ndnodes, node_size=0.01, width=.2)\n nx.draw_networkx_nodes(G, ndnodes, nodelist=nOdeg(G), node_size=0.02)\n plt.axis('scaled')\n plt.show() \n\n\n# Do the graph theory work\ndef genGraph(es):\n G = nx.MultiGraph()\n # Collect all edges from all operations\n alledges = [item for sublist in es for item in sublist] + canedges\n # Add weights to them based on pythag distance\n wedges = list(map(lambda e: (e[0], e[1], pythag(e[0], e[1])), alledges))\n\n # Get all unique nodes in all edges\n allnodes = list(map(lambda e: [e[0], e[1]], alledges))\n allnodes = [item for sublist in allnodes for item in sublist]\n allnodes = list(set(allnodes))\n negnodes = [(n[0], -n[1]) for n in allnodes]\n # Create dicts that can translate between node # and node coord\n nnodes = {v: k for k, v in enumerate(allnodes)}\n dnodes = {k: v for k, v in enumerate(allnodes)}\n ndnodes = {k: v for k, v in enumerate(negnodes)}\n # Add the edges with node #'s instead of coords (makes things easier)\n nwedges = list(map(lambda e: (nnodes[e[0]], nnodes[e[1]], e[2]), wedges))\n G.add_weighted_edges_from(nwedges)\n\n # Need an eulerian circuit\n # One component, no odd degree nodes\n # Where do we stand\n print(\"Num Odd\", len(nOdeg(G))) # Number of odd degree nodes\n print(\"Num One\", len(n1deg(G))) # Number of degree one nodes\n print(\"Num components\", len(list(nx.connected_components(G))))\n PlotGraph(G, ndnodes)\n\n # Connect any separate subgraphs into one\n # Will add edges\n print('Connect Subgraphs')\n G = ConnectSubgraphs(G, nnodes, dnodes)\n print(\"Num Odd\", len(nOdeg(G))) # Number of odd degree nodes\n print(\"Num One\", len(n1deg(G))) # Number of degree one nodes\n print(\"Num components\", len(list(nx.connected_components(G))))\n PlotGraph(G, ndnodes)\n\n # Add a parallel edge to any d1 node with an odd node as a neighbor\n print('EasyLinkOne')\n G = EasyLinkOne(G)\n print(\"Num Odd\", len(nOdeg(G))) # Number of odd degree nodes\n print(\"Num One\", len(n1deg(G))) # Number of degree one nodes\n\n # # Link remaining d1 nodes to a good neighbor\n # # This may create new edges\n print('LinkDegOne')\n G = LinkDegOne(G, nnodes, dnodes)\n print(\"Num Odd\", len(nOdeg(G))) # Number of odd degree nodes\n print(\"Num One\", len(n1deg(G))) # Number of degree one nodes\n PlotGraph(G, ndnodes)\n \n # Add a parallel edge to any odd node with an odd node as a neighbor\n print('EasyLinkOdd')\n G = EasyLinkOdd(G)\n print(\"Num Odd\", len(nOdeg(G))) # Number of odd degree nodes\n print(\"Num One\", len(n1deg(G))) # Number of degree one nodes\n PlotGraph(G, ndnodes)\n \n # Link odd nodes together but only if they are each other's best odd\n # This may create new edges\n print('LinkDegOdd')\n G = LinkDegOdd(G, nnodes, dnodes)\n print(\"Num Odd\", len(nOdeg(G))) # Number of odd degree nodes\n print(\"Num One\", len(n1deg(G))) # Number of degree one nodes\n while len(nOdeg(G)) > 600:\n print('LinkDegOdd 2')\n G = LinkDegOdd(G, nnodes, dnodes)\n print(\"Num Odd\", len(nOdeg(G))) # Number of odd degree nodes\n print(\"Num One\", len(n1deg(G))) # Number of degree one nodes\n \n PlotGraph(G, ndnodes)\n\n # Match remaining odd nodes with longer parallel paths\n print('FinalOdd')\n G = PathFinder(G, dnodes)\n print(\"Num Odd\", len(nOdeg(G))) # Number of odd degree nodes\n print(\"Num One\", len(n1deg(G))) # Number of degree one nodes\n # nx.draw_networkx_edges(G, ndnodes, node_size=0.01, width=.2)\n # nx.draw_networkx_nodes(G, ndnodes, nodelist=nOdeg(G), node_size=0.02)\n # plt.axis('scaled')\n # plt.show()\n\n print('Begin Eulerian')\n stops = [list(dnodes[u]) for u, v in nx.eulerian_circuit(G)]\n stops = np.array(stops)\n return G, stops\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"Art/ImageGen.py","file_name":"ImageGen.py","file_ext":"py","file_size_in_byte":17446,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"138241557","text":"# when you skip a call to a function, all its callers should INHERIT its\n# dependencies as though it wasn't skipped\n\nimport time\n\n# reads 'five_lines.txt' and writes 'tmp_out.txt'\ndef bar():\n time.sleep(0.2)\n of = open('tmp_out.txt', 'w')\n for line in open('five_lines.txt'):\n of.write(line)\n of.close()\n\n# skips call to bar; foo should inherit bar's dependencies on five_lines.txt and tmp_out.txt\ndef foo():\n time.sleep(0.2)\n return bar()\n\nbar() # memoized, so that when foo calls it, it will be skipped\nfoo()\n","sub_path":"skip_and_inherit_deps_2/1.py","file_name":"1.py","file_ext":"py","file_size_in_byte":520,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"207054840","text":"import tempfile\nimport os\n\nfrom PIL import Image\n\nfrom django.contrib.auth import get_user_model\nfrom django.urls import reverse\nfrom django.test import TestCase\n\nfrom rest_framework import status\nfrom rest_framework.test import APIClient\n\nfrom core.models import Recipe, Tag, Ingredient\n\nfrom recipe.serializers import RecipeSerializer, RecipeDetailSerializer\n\nRECIPE_URL = reverse('recipe:recipe-list')\n\n\ndef image_upload_url(recipe_id):\n \"\"\"Return URL for recipe image upload\"\"\"\n return reverse('recipe:recipe-upload-image', args=[recipe_id])\n\n\ndef detail_url(recipe_id):\n \"\"\"Return recipe detail url\"\"\"\n return reverse('recipe:recipe-detail', args=[recipe_id])\n\n\ndef sample_tag(user, name='Dessert'):\n \"\"\"Create and return sample tag\"\"\"\n return Tag.objects.create(user=user, name=name)\n\n\ndef sample_ingredient(user, name='Jalapeno'):\n \"\"\"Create and return sample ingredient\"\"\"\n return Ingredient.objects.create(user=user, name=name)\n\n\ndef sample_recipe(user, **params):\n \"\"\"Create and return sample recipe\"\"\"\n defaults = {\n 'title': 'test recipe',\n 'time_minutes': 10,\n 'price': 5.00\n }\n defaults.update(params)\n\n return Recipe.objects.create(user=user, **defaults)\n\n\nclass PublicRecipeApiTests(TestCase):\n \"\"\"Test public recipe api\"\"\"\n\n def setUp(self):\n self.client_class = APIClient()\n\n def test_login_required(self):\n \"\"\"Test that login is required\"\"\"\n res = self.client.get(RECIPE_URL)\n\n self.assertEqual(res.status_code, status.HTTP_401_UNAUTHORIZED)\n\n\nclass PrivateRecipeApiTests(TestCase):\n \"\"\"Test recipe api for authorized user\"\"\"\n\n def setUp(self):\n self.client = APIClient()\n self.user = get_user_model().objects.create_user(\n 'test@email.com',\n 'testpass123'\n )\n self.client.force_authenticate(self.user)\n\n def test_get_recipe(self):\n \"\"\"Test recipe retrieval for authorized user\"\"\"\n sample_recipe(user=self.user)\n sample_recipe(user=self.user)\n\n res = self.client.get(RECIPE_URL)\n\n recipes = Recipe.objects.all().order_by('-id')\n serializer = RecipeSerializer(recipes, many=True)\n\n self.assertEqual(res.status_code, status.HTTP_200_OK)\n self.assertEqual(res.data, serializer.data)\n\n def test_user_limited_recipes(self):\n \"\"\"Test users can only access their recipes\"\"\"\n user2 = get_user_model().objects.create_user(\n 'test2',\n 'testpass123'\n )\n sample_recipe(user=user2)\n sample_recipe(user=self.user)\n\n res = self.client.get(RECIPE_URL)\n recipes = Recipe.objects.filter(user=self.user)\n serializer = RecipeSerializer(recipes, many=True)\n\n self.assertEqual(res.status_code, status.HTTP_200_OK)\n self.assertEqual(len(res.data), 1)\n self.assertEqual(res.data, serializer.data)\n\n def test_detail_view(self):\n \"\"\"Test recipe detail view\"\"\"\n recipe = sample_recipe(user=self.user)\n recipe.tags.add(sample_tag(user=self.user))\n recipe.ingredients.add(sample_ingredient(user=self.user))\n\n url = detail_url(recipe.id)\n res = self.client.get(url)\n\n serializer = RecipeDetailSerializer(recipe)\n self.assertEqual(res.data, serializer.data)\n\n def test_create_recipe(self):\n \"\"\"Test creating recipe\"\"\"\n payload = {\n 'title': 'Tacos',\n 'time_minutes': 15,\n 'price': 10.00\n }\n res = self.client.post(RECIPE_URL, payload)\n\n self.assertEqual(res.status_code, status.HTTP_201_CREATED)\n recipe = Recipe.objects.get(id=res.data['id'])\n for key in payload.keys():\n self.assertEqual(payload[key], getattr(recipe, key))\n\n def test_create_recipe_with_tags(self):\n \"\"\"Test creating a recipe with tags\"\"\"\n tag1 = sample_tag(user=self.user, name='Appetizer')\n tag2 = sample_tag(user=self.user, name='Fried')\n payload = {\n 'title': 'Mozzerella Sticks',\n 'tags': [tag1.id, tag2.id],\n 'time_minutes': 60,\n 'price': 6.00\n }\n res = self.client.post(RECIPE_URL, payload)\n\n self.assertEqual(res.status_code, status.HTTP_201_CREATED)\n recipe = Recipe.objects.get(id=res.data['id'])\n tags = recipe.tags.all()\n self.assertEqual(tags.count(), 2)\n self.assertIn(tag1, tags)\n self.assertIn(tag2, tags)\n\n def test_create_recipe_with_ingredients(self):\n \"\"\"Test Creating recipe with ingredients\"\"\"\n ingredient1 = sample_ingredient(user=self.user, name='Beef')\n ingredient2 = sample_ingredient(user=self.user, name='Onions')\n payload = {\n 'title': 'Shepard Pie',\n 'ingredients': [ingredient1.id, ingredient2.id],\n 'time_minutes': 90,\n 'price': 12\n }\n res = self.client.post(RECIPE_URL, payload)\n\n self.assertEqual(res.status_code, status.HTTP_201_CREATED)\n recipe = Recipe.objects.get(id=res.data['id'])\n ingredients = recipe.ingredients.all()\n self.assertEqual(ingredients.count(), 2)\n self.assertIn(ingredient1, ingredients)\n self.assertIn(ingredient2, ingredients)\n\n def test_partial_update_recipe(self):\n \"\"\"Test updating recipe with patch\"\"\"\n recipe = sample_recipe(user=self.user)\n recipe.tags.add(sample_tag(user=self.user))\n new_tag = sample_tag(user=self.user, name='Indian')\n\n payload = {'title': 'Samosas', 'tags': [new_tag.id]}\n url = detail_url(recipe.id)\n self.client.patch(url, payload)\n\n recipe.refresh_from_db()\n self.assertEqual(recipe.title, payload['title'])\n tags = recipe.tags.all()\n self.assertEqual(len(tags), 1)\n self.assertIn(new_tag, tags)\n\n def test_full_update(self):\n \"\"\"Test updating object with put\"\"\"\n recipe = sample_recipe(user=self.user)\n recipe.tags.add(sample_tag(user=self.user))\n\n payload = {'title': 'Samosas',\n 'time_minutes': 25,\n 'price': 5.00\n }\n url = detail_url(recipe.id)\n self.client.put(url, payload)\n\n recipe.refresh_from_db()\n self.assertEqual(recipe.title, payload['title'])\n self.assertEqual(recipe.time_minutes, payload['time_minutes'])\n self.assertEqual(recipe.price, payload['price'])\n tags = recipe.tags.all()\n self.assertEqual(len(tags), 0)\n\n\nclass RecipeImageUploadTests(TestCase):\n\n def setUp(self):\n self.client = APIClient()\n self.user = get_user_model().objects.create_user('user@email.com',\n 'testpass123')\n self.client.force_authenticate(self.user)\n self.recipe = sample_recipe(user=self.user)\n\n def tearDown(self):\n self.recipe.image.delete()\n\n def test_image_upload(self):\n \"\"\"Test Recipe image upload\"\"\"\n url = image_upload_url(self.recipe.id)\n with tempfile.NamedTemporaryFile(suffix='.jpg') as ntf:\n img = Image.new('RGB', (10, 10))\n img.save(ntf, format='JPEG')\n ntf.seek(0)\n res = self.client.post(url, {'image': ntf}, format('multipart'))\n\n self.recipe.refresh_from_db()\n self.assertEqual(res.status_code, status.HTTP_200_OK)\n self.assertIn('image', res.data)\n self.assertTrue(os.path.exists(self.recipe.image.path))\n\n def test_img_upload_bad_req(self):\n \"\"\"Tests invalid image uplaod fails\"\"\"\n url = image_upload_url(self.recipe.id)\n res = self.client.post(url, {'image': 'notimage'}, format='multipart')\n\n self.assertEqual(res.status_code, status.HTTP_400_BAD_REQUEST)\n\n def test_filter_by_tags(self):\n \"\"\"Test returning recipes with a specific tag\"\"\"\n recipe1 = sample_recipe(user=self.user, title='Hamburger')\n recipe2 = sample_recipe(user=self.user, title='Pizza')\n tag1 = sample_tag(user=self.user, name='American')\n tag2 = sample_tag(user=self.user, name='Italian')\n recipe1.tags.add(tag1)\n recipe2.tags.add(tag2)\n recipe3 = sample_recipe(user=self.user, title='Chicken Tikka Masala')\n\n res = self.client.get(\n RECIPE_URL,\n {'tags': f'{tag1.id},{tag2.id}'}\n )\n\n serializer1 = RecipeSerializer(recipe1)\n serializer2 = RecipeSerializer(recipe2)\n serializer3 = RecipeSerializer(recipe3)\n self.assertIn(serializer1.data, res.data)\n self.assertIn(serializer2.data, res.data)\n self.assertNotIn(serializer3.data, res.data)\n\n def test_filter_by_ingredients(self):\n \"\"\"Test returning recipes with specific ingredients\"\"\"\n recipe1 = sample_recipe(user=self.user, title='Chicken Pot Pie')\n recipe2 = sample_recipe(user=self.user, title='Spaghetti & Meatballs')\n ingredient1 = sample_ingredient(user=self.user, name='Carrots')\n ingredient2 = sample_ingredient(user=self.user, name='Tomato Sauce')\n recipe1.ingredients.add(ingredient1)\n recipe2.ingredients.add(ingredient2)\n recipe3 = sample_recipe(user=self.user, title=\"Tacos\")\n\n res = self.client.get(\n RECIPE_URL,\n {'ingredients': f'{ingredient1.id},{ingredient2.id}'}\n )\n\n serializer1 = RecipeSerializer(recipe1)\n serializer2 = RecipeSerializer(recipe2)\n serializer3 = RecipeSerializer(recipe3)\n self.assertIn(serializer1.data, res.data)\n self.assertIn(serializer2.data, res.data)\n self.assertNotIn(serializer3.data, res.data)\n","sub_path":"app/recipe/tests/test_recipe_api.py","file_name":"test_recipe_api.py","file_ext":"py","file_size_in_byte":9681,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"575860076","text":"#!/usr/bin/env python\n# \n# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n# \n# Michael A.G. Aivazis\n# California Institute of Technology\n# (C) 1998-2007 All Rights Reserved\n# \n# \n# \n# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n# \n\nfrom pyre.weaver.mills.HTMLMill import HTMLMill\n\n\nclass HtmlPickler(HTMLMill):\n\n\n def __init__(self):\n HTMLMill.__init__(self)\n self.__html = None;\n self.__body = None;\n self.__head = None;\n return\n\n def _html(self):\n if not self.__html:\n self._write('')\n self.__html = 1;\n else:\n self._write('')\n self.__html = None;\n\n\n def _head(self):\n if not self.__head:\n self._write('')\n self.__head = 1;\n else:\n self._write('')\n self.__head = None;\n\n def _body(self):\n if not self.__body:\n self._write('')\n self.__body = 1;\n else:\n self._write('')\n self.__body = None;\n\n def _style(self):\n import style\n self._write( style.string() )\n\n def _speciesScript(self):\n import speciesScript\n self._write( speciesScript.string() )\n\n def _renderDocument(self, mechanism, options=None):\n\n self._rep += ['']\n\n self._html()\n self._head()\n self._style()\n self._speciesScript() \n self._head()\n self._body()\n self._indent()\n\n self._renderElements(mechanism)\n self._renderSpecies(mechanism)\n self._renderReactions(mechanism)\n self._outdent()\n \n self._body()\n self._html()\n self._rep += ['']\n\n return\n\n\n def _renderElements(self, mechanism):\n self._write(self.line('elements'))\n\n self._write( '

Element Section

' )\n\n self._write('')\n for element in mechanism.element():\n symbol = element.symbol\n id = element.id+1\n self._indent()\n self._write('') \n self._indent()\n self._write('' % id) \n self._write('' % symbol) \n self._outdent()\n self._write('') \n self._outdent()\n\n self._write('
%d %s
')\n self._rep.append('')\n \n return\n\n\n def _speciesEvent(self, species):\n \"\"\" Only for NASA polynomials with tlow, tmid, thigh \"\"\"\n\n str = ''\n str += 'onClick=speciesWin(\"%s\",' % species.symbol\n for element, coefficient in species.composition:\n str += '\"%s\",%d,' % (element, coefficient)\n \n thermo = species.thermo\n if thermo:\n for model in thermo:\n for p in model.parameters:\n str += '%g,' % p\n str += '%g,%g,' % (model.lowT, model.highT)\n\n \n str = str[:-1] + \")\"\n return str\n\n def _renderSpecies(self, mechanism):\n nColumns = 6;\n self._write(self.line('species'))\n\n self._write( '

Species Section

' )\n \n self._write('')\n for dum in range(0,nColumns):\n self._write('')\n self._write('')\n\n col = 1\n for species in mechanism.species():\n symbol = species.symbol\n phase = species.phase\n id = species.id+1\n\n if col == 1:\n self._write('')\n\n self._indent()\n event = self._speciesEvent(species)\n self._write('' % (event, symbol) )\n self._outdent()\n \n if col == 6:\n self._write('')\n col = 1\n else:\n col = col+1\n\n self._write('
')\n self._write('%d' % id)\n self._write('

%s

')\n\n\n def _renderReactions(self, mechanism):\n self._write(self.line('reactions'))\n\n self._write( '

Reactions Section

' )\n \n self._write('')\n \n i = 0\n for reaction in mechanism.reaction():\n\n i += 1\n self._indent()\n self._write('')\n self._indent()\n self._write('' % i)\n self._write('' % reaction.equation())\n self._outdent()\n self._write('')\n self._outdent()\n \n self._write('
%d%s
') \n\n return\n\n def _br(self):\n self_write('
')\n \n \n# End of file \n","sub_path":"packages/fuego/fuego/serialization/html/HtmlPickler.py","file_name":"HtmlPickler.py","file_ext":"py","file_size_in_byte":5161,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"474842311","text":"# coding: utf-8\n\nimport sys\n\n\nif len(sys.argv) != 2:\n print(\"ファイル名が指定されていません。\")\n sys.exit()\n\nfile_name = sys.argv[1]\n\nf = open(file_name, \"r\")\nlines = f.readlines()\nf.close()\n\nf2 = open(\"export_\"+ file_name, \"w\")\n\n\nfor line in lines:\n line = line.replace(\"\\n\", \"\")\n\n index = line.index(\",\")\n #print(\"track_type: \", line[:index])\n #print(\"title: \", line[index+1:])\n track_type = line[:index]\n title = line[index+1:]\n\n line_out = \"\"\n if track_type == \"-\":\n #print(\"- \"+ title +\" -\")\n line_out = \"- \"+ title +\" -\"\n elif track_type == \"=\":\n #print(\"==== \"+ title +\" ====\")\n line_out = \"==== \"+ title +\" ====\"\n else:\n #print(\"[\"+ title +\"]\")\n if len(track_type) == 1:\n track_type = \"0\" + track_type\n line_out = track_type +\". [\"+ title +\"]\"\n\n line_out = \"[*** \" + line_out + \"]\\n\"\n print(line_out)\n f2.write(line_out + \"\\n\")\n\nf2.close()","sub_path":"setlist-into-scrapbox.py","file_name":"setlist-into-scrapbox.py","file_ext":"py","file_size_in_byte":968,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"126203616","text":"## ex_chaco_myTP.title_01.py\n\n# standard imports\nimport os, inspect\nimport numpy as np\n\n# Enthought imports\nfrom enable.api import Component, ComponentEditor\nfrom traits.api import HasTraits\nfrom traitsui.api import Item, Group, View\nfrom chaco.api import Plot, ArrayPlotData\n\n# defines\nwindowSize = (800,600)\n\n# window title is file name\nwindowTitle = os.path.split(__file__)[1]\n\nclass TraitedPlot( HasTraits ):\n\n numPoints = 100\n extent = 2.0 * np.pi\n phaseA = np.linspace( -extent,extent,numPoints )\n amplitudeA = np.sin( phaseA ) * np.exp(-abs( phaseA ))\n\n myTADP = ArrayPlotData()\n myTADP.set_data( 'X',phaseA )\n myTADP.set_data( 'Y',amplitudeA )\n\n myTP = Plot( myTADP )\n myTP.plot(\n (\"X\", \"Y\"),\n type = 'line',\n )\n\n myTP.padding = 50 # pixels twixt plot and window edge.\n\n # most title attributes delegate to the underlying _title attribute, which\n # is a PlotLabel object.\n myTP.title = 'My Plot Title' # title appearing on plot\n myTP.title_angle = 0 # angle of the title in degrees\n myTP.title_color = 'blue' # title color. see colorspec\n myTP.title_font = \"swiss 16\" # title font. see fontspec\n myTP.title_position = 'top' # top, bottom, left, right\n myTP.title_spacing = 'auto' # spacing between the axis line and the title\n\n myTP._title.hjustify = 'center' # left, right or cener\n myTP._title.vjustify = 'center' # top, bottom or center\n\n mySize = (800,600)\n myTitle = 'myPlot'\n traits_view = View(\n Group(\n Item(\n 'myTP',\n editor = ComponentEditor(size = windowSize),\n show_label = False,\n ),\n orientation = \"vertical\",\n ),\n resizable = True,\n title = windowTitle,\n )\n\nif __name__ == \"__main__\":\n\n tp = TraitedPlot()\n tp.configure_traits()\n\n print( type(tp.myTP._title) )\n\n # print only the public members of the list\n membersList = inspect.getmembers( tp.myTP._title )\n publicList = [thisItem for thisItem in membersList if thisItem[0][0] != '_']\n print( publicList )\n\n tp.myTP._title.print_traits()\n","sub_path":"docs/FAQ/source/myTP.title/ex_chaco_myTP.title_01.py","file_name":"ex_chaco_myTP.title_01.py","file_ext":"py","file_size_in_byte":2087,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"606572","text":"import nltk\nfor dependency in (\"punkt\", \"stopwords\", \"brown\", \"names\", \"wordnet\", \"averaged_perceptron_tagger\", \"universal_tagset\"):\n nltk.download(dependency)\nfrom nltk.tokenize import word_tokenize\nfrom nltk.stem import WordNetLemmatizer\nfrom normalise import normalise\n\ndef token_pipeline(line):\n tokens = word_tokenize(line.lower())\n tokens= [x for x in tokens if x.isalnum()]\n nltk_stop_words = nltk.corpus.stopwords.words('english')\n tokens = [x for x in tokens if x not in nltk_stop_words]\n tokens = normalise(tokens, variety=\"AmE\", verbose = False)\n tokens = [WordNetLemmatizer().lemmatize(word, pos='v') for word in tokens]\n tokens = [WordNetLemmatizer().lemmatize(word, pos='n') for word in tokens]\n return tokens\n","sub_path":"mp_functions.py","file_name":"mp_functions.py","file_ext":"py","file_size_in_byte":751,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"121251638","text":"from math import trunc\nimport numpy as np\nimport pandas as pd\nfrom collections import Counter\n\n\ndef fast_hist(arr, bins):\n histed = [0 for x in range(bins)]\n if len(arr) == 0:\n return histed\n if isinstance(arr, tuple) and all([len(e)==0 for e in arr]):\n return histed\n\n mx = max(arr)\n mn = min(arr)\n step = (mx-mn)/bins\n\n if mx == mn:\n norm = 1 / (mx-mn + 1)\n else:\n norm = 1 / (mx-mn)\n nx = bins\n\n for elem in arr:\n try:\n ix = trunc((elem - mn) * norm * nx)\n if ix == bins:\n ix -=1\n histed[ix] += 1\n except:\n pass#rint('-->','el', elem, 'min max', mn, mx)\n\n return np.array(histed)\n\n\ndef raw_data_to_features(df):\n print(df)\n materials = df['Материал'].copy()\n\n material_categories = set()\n material_categories.add('too_rare')\n material_freqs = Counter()\n\n for ix, cat in materials.apply(lambda s: s.split()[0].lower()).iteritems():\n material_categories.add(cat)\n material_freqs[cat] += 1\n\n # set -> dict\n material_categories = {cat: i for i, cat in enumerate(list(material_categories))}\n print(material_freqs)\n\n details = df['Номенклатура'].copy()\n\n details_categories = set()\n details_categories.add('too_rare')\n details_freqs = Counter()\n\n for ix, cat in details.apply(lambda s: s.split()[0].lower()).iteritems():\n details_categories.add(cat)\n details_freqs[cat] += 1\n\n # set -> dict\n details_categories = {cat: i for i, cat in enumerate(list(material_categories))}\n print(details_freqs)\n\n def filter_correct_dims(dims):\n dims_ = []\n for d in dims:\n try:\n dims_.append(float(d))\n except ValueError:\n pass\n return dims_\n\n df = df[df['Размер'].apply(lambda s: len(filter_correct_dims(s.lower().split('х'))) == 3)]\n\n mul = lambda arr: arr[0] * mul(arr[1:]) if len(arr) > 1 else arr[0]\n calc_vol = lambda params: mul([float(x) for x in filter_correct_dims(params.lower().split('х'))])\n calc_dims = lambda s: np.array([float(x) for x in filter_correct_dims(s.lower().split('х'))])\n\n def get_material(s):\n mat = s.split()[0].lower()\n if material_freqs[mat] < 70:\n mat = 'too_rare'\n return mat\n\n def get_detail(s):\n if len(s.split()) == 0:\n return 'too_rare'\n det = s.split()[0].lower()\n if details_freqs[det] < 50:\n det = 'too_rare'\n return det\n\n def get_price_category(price, price_levels=5):\n if price < 10:\n return 0\n elif price < 200:\n return 1\n elif price < 2000:\n return 2\n elif price < 4000:\n return 3\n else:\n return 4\n\n ndf = pd.DataFrame()\n # raw features\n ndf['size1'] = df['Размер'].apply(calc_dims).apply(lambda v: sorted(v)[0])\n ndf['size2'] = df['Размер'].apply(calc_dims).apply(lambda v: sorted(v)[1])\n ndf['size3'] = df['Размер'].apply(calc_dims).apply(lambda v: sorted(v)[2])\n ndf['volume'] = (list(map(calc_vol, df['Размер'])))\n ndf['mass'] = (df['Масса заготовки'].astype(float))\n\n # mass features\n # ndf['userful_mass_perc'] = (df['Масса ДЕС'] / df['Масса заготовки']).astype(float)\n # ndf['sqr_trash_mass'] = np.square((df['Масса заготовки'] - df['Масса ДЕС']).astype(float))\n ndf['log_mass'] = np.log1p(ndf.mass)\n ndf['sqrt_mass'] = np.sqrt(ndf.mass)\n\n # volume features\n ndf['log_volume'] = np.log1p(ndf.volume)\n\n # other features\n ndf['log_density'] = np.log(1000 * ndf['mass'] / ndf['volume'])\n ndf['material_category'] = df['Материал'].apply(lambda mat: get_material(mat))\n ndf['detail_category'] = df['Номенклатура'].apply(lambda det: get_detail(det))\n ndf['price_category'] = df['Цена'].apply(get_price_category)\n\n ndf['log_price'] = np.log(df['Цена'].astype(float))\n\n # Drop outliers\n ndf = ndf[ndf.volume > 10]\n\n # Drop unneccessary\n # ndf = ndf.drop(['size%d'% i for i in [1]],axis=1)\n # ndf = ndf.drop('mass volume'.split(), axis=1)\n # ndf = ndf[ (ndf.log_price > 2)]\n\n # indexed = ndf.copy()\n # indexed['detail_name'] = df['Номенклатура']\n # indexed.to_csv('featured_details_mape014.csv', index=False)\n\n return ndf","sub_path":"service/models/text_recog/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":4476,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"89860773","text":"from typing import List, Tuple\n\nfrom romhacking.bytepair import bytepairCompress # noqa\n\n\ndef encode_12bit(strings: List[List[int]]) -> Tuple[List[int], List[int]]:\n indexes: List[int] = []\n output: List[int] = []\n\n index = len(strings) * 2 * 8\n shifted = False\n\n for string in strings:\n assert index <= 0xFFFF\n indexes.append(index)\n\n for c in string:\n assert c <= 0xFFF\n if shifted:\n output[-1] |= (c >> 8)\n output.append((c & 0xFF))\n else:\n output.append((c >> 4))\n output.append((c & 0xF) << 4)\n shifted = not shifted\n index += 12\n\n return indexes, output\n","sub_path":"romhacking/compression.py","file_name":"compression.py","file_ext":"py","file_size_in_byte":715,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"565164899","text":"import numpy as np\nfrom .tools import *\nfrom copy import deepcopy\nimport imageio\nimport matplotlib.pyplot as plt\nimport matplotlib.ticker as mticker\nfrom matplotlib.gridspec import GridSpec\nfrom matplotlib.patches import FancyArrowPatch\n\n# global pyplot settings\nplt.style.use(['seaborn-bright'])\nplt.rcParams.update({'font.size' : 26,\n 'figure.dpi' : 200,\n 'legend.shadow' : True,\n 'legend.handlelength' : 2})\n\n\n####################\n# HELPER FUNCTIONS #\n####################\n\ndef identity(ax):\n \"\"\" Plot the identity map y=x \"\"\"\n x = np.array(ax.get_xlim())\n y = x \n ax.plot(x, y, c='r', lw=3, alpha=0.5)\n\ndef suptitle(fig, title, pad=0):\n \"\"\" Adds title above subplots \"\"\"\n fig.add_subplot(111, frame_on=False)\n plt.tick_params(labelcolor='none', bottom=False, left=False)\n plt.title(title, pad=pad)\n\ndef show():\n \"\"\" \n Plot methods don't show by default, \n so call this in network plot methods \n \"\"\"\n plt.show()\n plt.close()\n\n############\n# SAVE MP4 #\n############\n\ndef save_frame(frame_num, frame_path, frame_plot):\n \"\"\" Used at the end of any method that plots a frame to be saved \"\"\"\n # frame plot\n frame_plot()\n plt.savefig(frame_path + str(frame_num) + '.png')\n plt.close()\n\ndef save_mp4(frame_saver, settings):\n \"\"\"\n Creates mp4 from collection of frames.\n frame_saver - function that saves frame to frame_path\n settings - dictionary containing:\n mp4_path - path (including file name) to the mp4\n frame_path - path to directory containing frames\n num_frames - number of frames to make\n duration - length of video (in seconds)\n \"\"\"\n # unpack dictionary\n mp4_path = settings['mp4_path']\n frame_path = settings['frame_path']\n num_frames = settings['num_frames']\n duration = settings['duration']\n\n # make video\n fps = int(num_frames / duration)\n with imageio.get_writer(mp4_path, mode='I', fps=fps) as writer:\n for frame in range(num_frames):\n frame_saver(frame)\n writer.append_data(\n imageio.imread(\n frame_path + str(frame) + '.png'\n )\n )\n\n#############\n# SOLUTIONS #\n#############\n\ndef solution(domain, solution, theta):\n \"\"\"\n Plots solution(s) given domain, solution and theta\n Solution and theta should have shapes (num_plots, soln_shape)\n and (num_plots, theta_shape) respectively.\n \"\"\"\n num_plots = len(solution)\n commas = [', ', ', ', r'$)$']\n fig, ax = plt.subplots(1, num_plots, figsize=(20,10))\n for i in range(num_plots):\n title = r'$\\theta = ($'\n for j in range(theta.shape[1]):\n #title += '%s' % name\n title += r'$%.2f$' % theta[i,j] \n title += commas[j]\n ax[i].plot(domain, solution[i], linewidth=3)\n ax[i].set_xlabel(r'$x$', fontsize=30)\n ax[i].set_xticks([0,1])\n ax[i].set_title(title, fontsize=28)\n ax[0].set_ylabel(r'$u_\\theta = u(x)$', fontsize=30)\n\n#############\n# MODEL FIT # \n#############\n\ndef theta_fit(Phi, theta_Phi, theta, \n sigma=0, \n transform=True, \n verbose=True):\n \"\"\"\n General plotting function to plot latent space theta vs theta_Phi,\n Inputs:\n Phi - the test set data\n theta_Phi - the test set theta\n theta - latent theta values\n sigma - standard deviation for normally distributed noise\n transorm - plot theta components on common scale\n verbose - prints mean square errors\n \"\"\"\n if verbose:\n # evaluate, predict, and plot with trained model\n theta_mse = np.mean((theta - theta_Phi) ** 2, axis=0)\n print('theta MSE:', theta_mse)\n\n # initialize axes\n plot_cols = 1\n theta_len = theta_Phi.shape[1]\n fig, ax = plt.subplots(theta_len, 1,\n sharey=transform,\n sharex=transform,\n figsize=(20,20))\n\n # plot transformed thetas\n if transform:\n theta_Phi, theta = rescale_thetas(theta_Phi, theta)\n \n if verbose:\n # evaluate, predict, and plot with trained model\n theta_tform_mse = np.mean((theta - theta_Phi) ** 2, axis=0)\n print('transformed theta MSE:', theta_tform_mse)\n\n subplot_theta_fit(fig, ax, theta_Phi, theta)\n\ndef subplot_theta_fit(fig, ax, theta_Phi, theta=None, resids=None):\n \"\"\"\n Plots theta vs theta_Phi\n Agnostic to data transformation\n \"\"\"\n theta_names = ['$c$', '$b_0$', '$b_1$']\n num_plots = len(ax)\n\n # scientific notation for residuals\n formatter = mticker.ScalarFormatter(useMathText=True)\n formatter.set_scientific(True)\n formatter.set_powerlimits((0,0))\n\n # compute residuals if not given\n if resids is None:\n resids = theta - theta_Phi\n ymin = np.min(resids) * 1.25\n ymax = np.max(resids) * 1.25\n for i in range(num_plots):\n residuals = resids[:,i]\n xmin = 1.1 * np.min(theta_Phi[:,i])\n xmax = 1.1 * np.max(theta_Phi[:,i])\n ax[i].set_ylim(ymin, ymax)\n ax[i].scatter(theta_Phi[:,i], residuals,\n alpha=0.7, label=theta_names[i] + ' predictions')\n ax[i].plot([xmin, xmax], [0,0], lw=3, c='k', ls='dashed')\n ax[i].yaxis.set_major_formatter(formatter)\n ax[i].legend(loc='upper left', fontsize=20)\n suptitle(fig, '')\n plt.xlabel('Truth', fontsize=26)\n plt.ylabel('Residuals', fontsize=26, labelpad=40.0)\n\ndef solution_fit(Phi, noise, theta_Phi, theta, u_theta, \n sigma=0, \n seed=23, \n ylims=None,\n verbose=True):\n \"\"\"\n General plotting function to plot Phi, Phi+noise (for nonzero sigma),\n and the reconstructed Phi u_theta\n Inputs:\n Phi - the test set data\n theta_Phi - the test set theta\n theta_from_Phi - function that gets latent theta from Phi\n u_from_Phi - function that reconstructs Phi given Phi\n sigma - standard deviation for normally distributed noise\n seed - random seed for reprodicibility\n ylims - ylim for each subplot\n verbose - print mean square errors\n \"\"\"\n domain = np.linspace(0, 1, Phi.shape[1])\n theta_names = ['$c$', '$b_0$', '$b_1$']\n\n if verbose:\n # compute mean square errors\n theta_mse = np.mean((theta - theta_Phi) ** 2, axis=0)\n Phi_mse = np.mean((u_theta - Phi) ** 2)\n print('Latent theta MSE:', theta_mse)\n print('Reconstructed Phi MSE:', Phi_mse)\n\n num_plots = len(Phi)\n idx = np.array([x for x in range(num_plots)]).reshape(3, 3)\n fig, ax = plt.subplots(nrows=3, ncols=3,\n sharex=True,\n figsize=(20,20))\n labs = [r'$u_\\theta$', r'$\\Phi$', r'$\\Phi +$noise']\n for i in np.ndindex(3, 3):\n # plot reconstructed Phi\n ax[i].plot(domain, u_theta[idx[i]], label=labs[0], lw=3)\n # plot noiseless Phi\n ax[i].plot(domain, Phi[idx[i]] - noise[idx[i]],\n label=labs[1],\n lw=3,\n ls='dashed',\n c='k')\n # plot noisy Phi\n if sigma != 0: \n ax[i].plot(domain, Phi[idx[i]],\n label=labs[2],\n lw=3,\n alpha=0.2,\n c='k')\n if i[0] == 2:\n ax[i].set_xlabel(r'$x$', fontsize=26)\n ax[i].set_xticks([0, 1])\n if ylims is not None:\n ax[i].set_ylim(ylims[idx[i]])\n labs = ['' for lab in labs] # don't label other plots\n cols = 3 if sigma != 0 else 2\n fig.legend(fontsize=26, loc='upper center', ncol=cols)\n\n suptitle(fig, 'Test set sample', pad=20)\n\n#################\n# BOOTSTRAPPING #\n#################\n\ndef theta_boot(test, boot_data, sigmas, se='bootstrap', verbose=False):\n \"\"\" Plot bootstrap results in parameter space, resids vs truth \"\"\"\n # compute bootstrap means and confidence bounds\n test_theta = deepcopy(test[1]) # ground truth test theta\n stats = boot_stats(boot_data, test_theta)\n theta_Phi = stats['rescaled_true_theta']\n param = ['$c$', '$b_0$', '$b_1$']\n if verbose:\n print('%d intervals' % len(test_theta))\n\n # errorbar plots\n fig, ax = plt.subplots(3,1, figsize=(20,20), sharex=True, sharey=True)\n for i in range(3):\n # plot bootstrap means\n resids_means = stats['means'][:,i]\n\n # errors\n if se == 'bootstrap':\n errs = 2. * stats['SE'][:,i]\n upper = resids_means + errs \n lower = resids_means - errs\n elif se == 'quantile':\n errs = stats['credint95'][i]\n upper = stats['upper95'][:,i]\n lower = stats['lower95'][:,i]\n\n # count intervals containing zero\n below = (upper < 0)\n above = (lower > 0)\n outside = below + above\n num_outside = np.sum(outside, axis=0)\n percent_outside = 100. * num_outside / len(test_theta)\n if verbose:\n msg = '%d ' % num_outside\n msg += r'' + param[i] + ' intervals (%.2f%%) ' % percent_outside\n msg += 'do not contain 0'\n print(msg)\n colors = ['r' if out else 'C0' for out in outside]\n \n ax[i].scatter(theta_Phi[:,i], resids_means, \n label=param[i] + ' boot means', c=colors, alpha=0.7)\n # plot bootstrap credible regions\n ax[i].errorbar(theta_Phi[:,i], resids_means, \n yerr=errs,\n ecolor=colors,\n alpha=0.25,\n fmt='|',\n label='95% credible region')\n # y=0\n xmin = np.min(theta_Phi[:,i])\n xmax = np.max(theta_Phi[:,i])\n ax[i].plot([xmin, xmax], [0,0], \n c='k', \n lw=3, \n ls='dashed')\n ax[i].set_ylabel('Residuals')\n ax[i].legend(loc='upper left', fontsize=20)\n ax[2].set_xlabel('Truth')\n train_sigma, test_sigma = sigmas\n title = noise_title(train_sigma, test_sigma)\n suptitle(fig, title, pad=20)\n\ndef solution_boot(test, boot_data, u_from_theta, sigmas, se='bootstrap'):\n \"\"\"\n Plot bootstrap results for a sample of 9 solutions\n For each Phi in the sample, plots:\n denoised and noisy Phi\n bootstrap mean\n credible regions\n Credible regions are quantiles from theta bootstrap results\n \"\"\"\n # make title and add noise to Phi\n train_sigma, test_sigma = sigmas \n title = noise_title(train_sigma, test_sigma)\n Phi, theta_Phi = deepcopy(test)\n Phi, noise = add_noise(Phi, test_sigma) # noisy test inputs\n\n # get bootstrap statistics\n num_boots = len(boot_data)\n stats = boot_stats(boot_data)\n\n # generate sample\n num_plots = 9\n sample_idx = np.random.randint(0, len(Phi)-1, num_plots)\n Phi = Phi[sample_idx]\n noise = noise[sample_idx]\n theta_means = stats['means'][sample_idx]\n means = u_from_theta(theta_means)\n if se == 'bootstrap':\n up95 = theta_means + 2. * stats['SE_boot'][sample_idx]\n lo95 = theta_means - 2. * stats['SE_boot'][sample_idx]\n upper95 = u_from_theta(up95)\n lower95 = u_from_theta(lo95)\n up68 = theta_means + stats['SE_boot'][sample_idx]\n lo68 = theta_means - stats['SE_boot'][sample_idx]\n upper68 = u_from_theta(up68)\n lower68 = u_from_theta(lo68)\n else:\n upper95 = u_from_theta(stats['upper95'][sample_idx])\n lower95 = u_from_theta(stats['lower95'][sample_idx])\n upper68 = u_from_theta(stats['upper68'][sample_idx])\n lower68 = u_from_theta(stats['lower68'][sample_idx])\n\n # for indexing plot grid\n idx = np.array([x for x in range(num_plots)]).reshape(3, 3)\n\n fig, ax = plt.subplots(nrows=3, ncols=3,\n sharex=True,\n figsize=(20,20))\n labs = [r'$u_\\theta$ boot mean', \n '95% credible region', \n '68% credible region',\n r'$\\Phi$', \n r'$\\Phi +$noise']\n domain = np.linspace(0, 1, Phi.shape[1])\n\n for i in np.ndindex(3, 3):\n # u\n ax[i].plot(domain, means[idx[i]], label=labs[0], lw=3)\n\n # credible intervals\n ax[i].fill_between(domain, lower95[idx[i]], upper95[idx[i]], \n color='C0', \n alpha=0.12,\n label=labs[1])\n ax[i].fill_between(domain, lower68[idx[i]], upper68[idx[i]], \n color='C0', \n alpha=0.25,\n label=labs[2])\n\n # denoised Phi\n ax[i].plot(domain, Phi[idx[i]] - noise[idx[i]],\n label=labs[3],\n lw=3,\n ls='dashed',\n alpha=1.0,\n c='k')\n # noisy Phi\n if test_sigma != 0: \n ax[i].plot(domain, Phi[idx[i]],\n label=labs[4],\n lw=3,\n alpha=0.2,\n c='k')\n\n # label x axes\n if i[0] == 2:\n ax[i].set_xlabel(r'$x$', fontsize=26)\n ax[i].set_xticks([0, 1])\n labs = ['' for lab in labs] # don't label other plots\n\n # title\n suptitle(fig, title, pad=20)\n \n # legend in proper order\n handles, labels = ax[0,0].get_legend_handles_labels()\n if test_sigma != 0:\n new_order = [0,3,4,1,2]\n else:\n new_order = [0,2,3,1]\n handles = [handles[i] for i in new_order]\n labels = [labels[i] for i in new_order]\n fig.legend(handles, labels, \n fontsize=26, \n loc='upper center', \n ncol = len(new_order))\n\n\n############################\n# ADJOINT GRADIENT DESCENT #\n############################\n\nclass AdjointPlotter:\n \"\"\"\n Plotter class for adjoint equation gradient descent.\n Last line of AdjClass.descend() should be\n self.plt = plotter.AdjointDescent(AdjClass)\n \"\"\"\n\n def __init__(self, adjoint):\n # initialized with adjoint eq grad descent class\n self.adjoint = adjoint\n self.theta_names = [r'$c$', r'$b_0$', r'$b_1$']\n self.theta_Phi_names = [r'$\\kappa$', r'$\\beta_0$', r'$\\beta_1$']\n\n\n ####################\n # BOUNDARY CONTROL #\n ####################\n\n def grad_descent_bc(self):\n \"\"\" Plots boundary control gradient descent results \"\"\"\n # get parameters\n c, kappa = (self.adjoint.thetas[:,0], self.adjoint.theta_true[0])\n b0, beta0 = (self.adjoint.thetas[:,1], self.adjoint.theta_true[1])\n b1, beta1 = (self.adjoint.thetas[:,2], self.adjoint.theta_true[2])\n\n # 2x2 grid (b0, b1, \\\\ c, u)\n fig, ax = plt.subplots(2, 2, figsize=(18,15))\n\n # plot c, b0, b1\n self.subplot_theta_descent(ax[1,0], c, 0)\n self.subplot_theta_descent(ax[0,0], b0, 1)\n self.subplot_theta_descent(ax[0,1], b1, 2)\n\n # plot solutions\n self.subplot_solution_descent(ax[1,1])\n\n # make title\n title = r'%d iterations ' % max(self.adjoint.iterations)\n title += 'at learning rate $\\gamma = %.1f$' % self.adjoint.lr\n suptitle(fig, title)\n\n plt.show()\n plt.close()\n\n def subplot_theta_descent(self, ax, theta, idx):\n \"\"\"\n Plots parameter convergence during gradient descent\n Inputs:\n ax - axis object for plotting\n param - parameter to plot vs iterations\n idx - index for true parameter (0:kappa, 1:beta0, 2:beta1)\n \"\"\"\n theta_Phi = self.adjoint.theta_true[idx]\n iterations = self.adjoint.iterations\n\n # plot theta converging to theta_Phi\n ax.plot(iterations, theta, color='g', lw=3)\n ax.hlines(theta_Phi, \n xmin=0, \n xmax=max(iterations), \n lw=3, \n ls='dashed', \n color='k')\n\n ax.set_xlabel('iterations')\n ax.legend([self.theta_names[idx], self.theta_Phi_names[idx]])\n\n def subplot_solution_descent(self, ax, title=''):\n \"\"\" Plots gradient descent in solution space \"\"\"\n\n # plot solution convergence\n u_lab = r'$u$'\n for i, u in enumerate(self.adjoint.solutions):\n alpha_i = 1./(i+1)\n ax.plot(self.adjoint.x, u, \n label=u_lab, \n lw=3, \n c='C0', \n alpha=alpha_i)\n u_lab = ''\n\n # plot Phi without noise\n Phi = self.adjoint.Phi - self.adjoint.noise\n ax.plot(self.adjoint.x, Phi, \n label=r'$\\Phi$',\n lw=3, \n c='k',\n ls='dashed')\n\n # plot Phi with noise if exists\n if self.adjoint.sigma != 0:\n ax.plot(self.adjoint.x, self.adjoint.Phi, \n label=r'$\\Phi + $noise',\n lw=3, \n c='0.5', \n ls='dashed')\n \n ax.set_xlabel(r'$\\Omega$')\n ax.set_title(title)\n ax.legend()\n\n def curve_convergence(self):\n \"\"\" Plots descent in solution space \"\"\"\n fig, ax = plt.subplots(1, 1, figsize=(20,15)) \n\n title = r'%d iterations ' % max(self.adjoint.iterations)\n title += 'at learning rate $\\gamma = %.1f$' % self.adjoint.lr\n self.subplot_solution_descent(ax, title)\n ax.legend(loc='upper center', ncol=2)\n\n plt.show()\n plt.close()\n\n def biplot_descent_bc(self):\n \"\"\" Plots boundary control descent in parameter space \"\"\"\n fig, ax = plt.subplots(self.adjoint.theta_dim, 1, figsize=(18,18))\n\n for i in range(self.adjoint.theta_dim):\n j = (i + 1) % 3\n thetas = [self.adjoint.thetas[:,i], self.adjoint.thetas[:,j]]\n idxs = [i, j]\n self.biplot_theta(ax[i], thetas, idxs)\n\n title = '%d iterations to convergence, ' % max(self.adjoint.iterations)\n title += r'$\\gamma = %.1f$' % self.adjoint.lr\n suptitle(fig, title)\n\n plt.show()\n plt.close()\n\n def biplot_theta(self, ax, thetas, idxs, title='', color='g'):\n \"\"\"\n Plots gradient descent in parameter space with param_y vs param_x\n Inputs:\n ax - the axis plotting object\n thetas - list or tuple of parameter data [param_x, param_y]\n idxs - list or tuple of parameter indices from theta_true\n (0:kappa, 1:beta0, 2:beta1)\n \"\"\"\n # make names and get true parameter\n theta_x, theta_y = thetas\n x, y = idxs\n\n # make ordered pairs for legend\n ordered_pair = lambda x, y : '(' + x + ', ' + y + ')'\n curve = ordered_pair(self.theta_names[x], self.theta_names[y])\n optim = ordered_pair(self.theta_Phi_names[x], self.theta_Phi_names[y])\n\n # make the plot\n ax.plot(theta_x, theta_y, \n label=curve, \n lw=3, \n c=color)\n ax.scatter(self.adjoint.theta_true[x], self.adjoint.theta_true[y], \n label=optim, \n s=12 ** 2, \n c='k')\n ax.legend()\n ax.set_title(title)\n\n def learning_rates(self, data, max_its):\n \"\"\"\n Plots number of iterations to convergence\n as a function of learning rate given by lr_bounds\n \"\"\"\n # get plotting data\n lr, counts = zip(*data.items())\n lr_opt = lr[np.argmin(counts)]\n\n # plot\n fig, ax = plt.subplots(1, 1, figsize=(18,10))\n ax.plot(lr, counts, linewidth=5, color='C1')\n ax.set_xlabel('Learning Rate ' + r'$\\gamma$')\n ax.set_ylabel('iterations to convergence (%d max)' % max_its)\n ax.set_title(r'%d iterations at $\\gamma = %.2f$' \n % (np.min(counts), lr_opt))\n plt.show()\n plt.close()\n\n\n #########################\n # LEFT BOUNDARY CONTROL #\n #########################\n\n def grad_descent_lbc(self, c, kappa, b0, beta0):\n \"\"\" Plots left boundary control gradient descent \"\"\"\n fig, ax = plt.subplots(2, 2, figsize=(15, 15), dpi=200)\n fig.subplots_adjust(hspace=0.25)\n\n # c, b0 convergence top row\n self.subplot_theta_descent(ax[0,0], c, 0)\n self.subplot_theta_descent(ax[0,1], b0, 1)\n \n # solution convergence bottom row\n for ax in ax[1,:]: ax.remove()\n gs = GridSpec(2,2)\n soln_ax = fig.add_subplot(gs[1,:])\n self.subplot_solution_descent(soln_ax)\n\n # make title\n title = r'%d iterations ' % max(self.adjoint.iterations)\n title += 'at learning rate $\\gamma = %.1f$' % self.adjoint.lr\n suptitle(fig, title)\n\n plt.show()\n plt.close()\n\n def biplot_descent_lbc(self):\n \"\"\" Theta biplot of left boundary control grad descent \"\"\"\n fig, ax = plt.subplots(1, 1, figsize=(18,15))\n\n # make plot\n thetas = [self.adjoint.thetas[:,0], self.adjoint.thetas[:,1]]\n idxs = [0, 1]\n self.biplot_theta(ax, thetas, idxs)\n\n # make title\n title = '%d iterations to convergence, ' % max(self.adjoint.iterations)\n title += r'$\\gamma = %.1f$' % self.adjoint.lr\n ax.set_title(title)\n\n plt.show()\n plt.close()\n\n def loss_contour(self, c, b0, log_losses):\n \"\"\"\n Plots the -log(loss) contour as a function of c and b0\n with the gradient descent path overlayed on top\n \"\"\"\n c_min, c_max, b0_min, b0_max = self.adjoint.ranges\n lines = np.linspace(np.min(log_losses), np.max(log_losses), 20)\n grad = self.adjoint.get_grad([c[-1], b0[-1], self.adjoint.b1])\n\n fig, ax = plt.subplots(1, 1, figsize=(18,10))\n\n # make contour plot\n cont = ax.contourf(self.adjoint.c_tensor, \n self.adjoint.b0_tensor, \n log_losses, \n lines)\n cbar = fig.colorbar(cont)\n cbar.set_label(r'$-\\log(\\mathcal{J})$', rotation=90)\n\n # make theta biplot\n title = r'$\\frac{d\\mathcal{J}}{d\\theta} = '\n title += '(%.7f, %.7f)$' % (grad[0,0], grad[0,1])\n self.biplot_theta(ax, [c, b0], [0, 1], title, color='r')\n\n # make optimum point\n ax.scatter(c[-1], b0[-1], c='r', s=10**2)\n\n ax.set_xlim([c_min, c_max])\n ax.set_ylim([b0_min, b0_max])\n ax.set_xlabel(r'$c$')\n ax.set_ylabel(r'$b_0$')\n\n #######################\n # NO BOUNDARY CONTROL #\n #######################\n\n def grad_descent(self, c, kappa):\n \"\"\" Plots no boundary control grad descent results \"\"\"\n fig, ax = plt.subplots(2, 1, figsize=(15, 15))\n fig.subplots_adjust(hspace=0.25)\n self.subplot_theta_descent(ax[0], c, 0)\n self.subplot_solution_descent(ax[1])\n\n # make title\n title = r'%d iterations ' % max(self.adjoint.iterations)\n title += 'at learning rate $\\gamma = %.1f$' % self.adjoint.lr\n suptitle(fig, title)\n\n plt.show()\n plt.close()\n\n def loss(self, c_init, c_range, grad_line, Jc, dJdc):\n \"\"\" Plots loss J as a function of force parameter c \"\"\"\n fig, ax = plt.subplots(1, 1, figsize=(18, 15), dpi=200)\n\n # plot tangent line\n ax.plot(c_range, grad_line,\n label=r'$gradient -\\gamma \\frac{d\\mathcal{J}}{dc}$',\n linewidth=5, \n c='r',\n alpha=0.5)\n\n # plot (c, J(c))\n ax.scatter(c_init, Jc, \n label=r'descending parameter $(c, \\mathcal{J}(c))$',\n s=12**2, \n c='g',\n zorder=2.5)\n\n # plot gradient vector\n dc = -self.adjoint.lr * dJdc \n ax.arrow(x=c_init, y=Jc, dx=dc, dy=0, \n #length_includes_head=True,\n head_length=0.05,\n color='r',\n alpha=0.5)\n\n # compute and plot loss\n loss = np.zeros(c_range.shape)\n for i, c in enumerate(c_range):\n theta = [c, self.adjoint.b0, self.adjoint.b1]\n loss[i] = self.adjoint.get_loss(theta)\n loss_plot = ax.plot(c_range, loss, \n label=r'loss $\\mathcal{J}(c)$',\n linewidth=5, \n c='mediumblue')\n\n # set labels and title\n title = r'$\\frac{d\\mathcal{J}}{dc} = %.7f$' % dJdc\n title += r', $\\gamma = %.2f$' % self.adjoint.lr\n ax.set_title(title)\n ax.set_xlabel(r'force parameter $c$')\n ax.set_ylabel(r'Loss Functional $\\mathcal{J}$')\n ax.set_ylim(bottom=-0.01)\n ax.legend(loc='lower left')\n # make kappa a tick label\n ax.xaxis.set_major_formatter(mticker.FuncFormatter(\n lambda x, pos : r'$\\kappa$' if x == self.adjoint.kappa else x))\n\n","sub_path":"semantic_autoencoder/utilities/plotter.py","file_name":"plotter.py","file_ext":"py","file_size_in_byte":24620,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"587252585","text":"#Created by: Aaron Rose, Security Architect @ Check Point Software Technologies\n#Version 1.4\n#This script is provided \"as is\" and without warranty of any kind, you are solely responsible for any compromise or loss of data that may result from using this Script.\n# import modules\nfrom os import path\nimport urllib2\nimport os.path\nimport os\nimport getpass\nimport json\nimport ssl\n# SSL context to provide a CA Bundle for server verification. Download the CA Bundle here before running https://curl.haxx.se/ca/cacert.pem & make sure the path below is correct or SSL Validation will fail\nctx = ssl.create_default_context(cafile=\"/home/admin/cacert.pem\")\n# Define variables -- change object name, category, url to domain list, etc. as needed\nsuspiciousDomainsURL = 'https://raw.githubusercontent.com/aaronroseio/autoupdateurls/master/suspiciousdomains.txt'\nnewfile = 'suspiciousdomains.txt'\nobjectName = 'CUSTOM-SUSPICIOUS-DOMAINS'\nobjectCategory = 'Custom_Application_Site'\napiKey = 'API-KEY-HERE' # only needed for unattended use\ndomain = 'DOMAIN-NAME-HERE' # MDM Domain\npolicyPackage = 'Standard' # policy-package-name-here\ninstallTargets = 'R8040GWDEVTEST' # policy-install-targets-here\n# retrieve latest file from github\n\n\ndef retrieveLatest():\n filedata = urllib2.urlopen(\n suspiciousDomainsURL, context=ctx)\n datatowrite = filedata.read()\n\n with open('suspiciousdomains.txt', 'wb') as f:\n f.write(datatowrite)\n\n# function for login to mgmt api and retrieve sid-- this can be used with username & password for testing, as well as with the api key\n\n\ndef apiLogin(logincommand):\n stream = os.popen(logincommand)\n loginOutput = stream.read()\n jsonLoginOutput = json.loads(loginOutput)\n return jsonLoginOutput[\"sid\"]\n\n\n# function to publish changes using sid from login\n\n\ndef apiPublish(sid):\n stream = os.popen(\"mgmt_cli publish --session-id \" + sid)\n publishOutput = stream.read()\n print (publishOutput)\n\n# function to logout after publish using sid from login\n\n\ndef apiLogout(sid):\n stream = os.popen(\"mgmt_cli logout --session-id \" + sid)\n logoutOutput = stream.read()\n print (logoutOutput)\n\n\n# function to install policy after publish using sid from login\n\n\ndef apiInstall(sid, policyPackage, installTargets):\n installPolicyCommand = 'mgmt_cli install-policy policy-package \"{}\" access true threat-prevention false targets \"{}\" --session-id {} '.format(\n policyPackage, installTargets, sid)\n stream = os.popen(installPolicyCommand)\n installOutput = stream.read()\n print (installOutput)\n\n# this function is for the first time run using the add application-site command\n\n\ndef addApplicationSite(newfile, sid, objectName, objectCategory):\n with open(newfile, 'r') as fp:\n line = fp.readline()\n cnt = 1\n addApplicationCommand = 'mgmt_cli add application-site name {} primary-category {} --format json'.format(\n objectName, objectCategory)\n while line:\n if not line.startswith('#'):\n addApplicationCommand += ' url-list.{} \"{}\"'.format(\n cnt, line.strip())\n line = fp.readline()\n cnt += 1\n addApplicationCommand += \" --session-id \" + sid\n os.system(addApplicationCommand)\n\n# this function is for the first time run using the set application-site command with url.list.add argument, although it adds all urls in the txt file, only the changes are processed by the mgmt api server\n\n\ndef editApplicationSite(newfile, sid, objectName):\n with open(newfile, 'r') as fp:\n line = fp.readline()\n cnt = 1\n editApplicationCommand = 'mgmt_cli set application-site name {} --format json'.format(\n objectName)\n while line:\n if not line.startswith('#'):\n editApplicationCommand += ' url-list.add.{} \"{}\"'.format(\n cnt, line.strip())\n line = fp.readline()\n cnt += 1\n editApplicationCommand += \" --session-id \" + sid\n os.system(editApplicationCommand)\n\n\n# prompt user for login credentials to mgmt api server, then build the login command as a variable to pass to login function - this can be adapted to use an api key to allow for unattended use (cron)\nusername = raw_input(\"API Username:\")\npassword = getpass.getpass(\"Password for \" + username + \":\")\nlogincommand = \"mgmt_cli login user \" + username + \\\n \" password \" + password + \" --format json\"\n\n# uncomment the variable below and comment out the lines above to use the apikey\n# logincommand = 'mgmt_cli login api-key \"{}\" domain \"{}\" --format json'.format(apiKey,domain)\n\n\nsid = apiLogin(logincommand)\n\n# check to see if file exists --- uncomment #apiInstall lines if you want the script to install policy each time or create a separate script to run at the desired interval with the functions login, install & logout\nif path.exists('suspiciousdomains.txt'):\n retrieveLatest()\n editApplicationSite(newfile, sid, objectName)\n apiPublish(sid)\n #apiInstall(sid, policyPackage, installTargets)\n apiLogout(sid)\nelse:\n retrieveLatest()\n addApplicationSite(newfile, sid, objectName, objectCategory)\n apiPublish(sid)\n #apiInstall(sid, policyPackage, installTargets)\n apiLogout(sid)\n","sub_path":"updatesiteURLs.py","file_name":"updatesiteURLs.py","file_ext":"py","file_size_in_byte":5265,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"569590626","text":"import random\nimport string\nimport socket\nimport pickle\n\n\nclass Frame:\n def __init__(self, seqno, data):\n self.seqno = seqno\n self.data = data\n self.md5data\n self.frame_string = str(self.seqno) + \" \" + str(self.data)\n\n def display_frame(self):\n print(self.frame_string)\n print(\"\\n\")\n\n\nport = 8080\nserver = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\nserver.bind(('127.0.0.1', port))\nserver.listen(1)\nprint ('The server is ready to receive')\n\nconnect, address = server.accept()\n\nisEnd = 0\nlast_sequence = -1\n\nwhile isEnd == 0:\n # listen for data from client\n frame = connect.recv(1024)\n # load bytes object back into frame object using pickle\n # f = open('frame.pkl', 'rb')\n recv_frame = pickle.loads(frame)\n # f.close()\n\n # Print the string of the entire packet\n Frame.display_frame(recv_frame)\n\n if(recv_frame.sequence_number == last_sequence+1) or (len(recv_frame.data) != 8):\n connect.send(str(last_sequence+1).encode())\n else:\n # send an acknowledgement\n connect.send(b\"1\")\n print(\"Ack has send \\n\")\n if recv_frame.sequence_number == -1:\n isEnded = 1\n\nconnect.close()","sub_path":"Networks Programming/Socket-in-Pyphon/Socket Programming with protocal Idle RQ/secondary.py","file_name":"secondary.py","file_ext":"py","file_size_in_byte":1202,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"488897062","text":"# Create your views here.\nfrom annoying.decorators import ajax_request, render_to\nfrom django.core.urlresolvers import reverse\nfrom django.shortcuts import get_object_or_404\nfrom django.views.decorators.csrf import csrf_exempt\nfrom forms import PhotoUploadForm\nfrom photos.models import Photo\n\n\n@csrf_exempt\n@ajax_request\ndef upload(request):\n form = PhotoUploadForm(request.POST or None, request.FILES or None)\n if form.is_valid():\n photo = form.save()\n return {\n 'url': reverse('photo', kwargs={'id': photo.id})\n }\n return {\n 'error': form.errors\n }\n\n\n@render_to('photos/photo.haml')\ndef photo(request, id):\n photo = get_object_or_404(Photo, id=id)\n return {\n 'photo': photo\n }","sub_path":"apps/photos/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":746,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"120838596","text":"# Copyright (c) 2022 PaddlePaddle Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport unittest\n\nimport numpy as np\nfrom test_imperative_base import new_program_scope\nfrom utils import DyGraphProgramDescTracerTestHelper\n\nimport paddle\nfrom paddle import fluid\nfrom paddle.fluid import core\nfrom paddle.fluid.dygraph.base import to_variable\n\n\nclass SimpleNet(paddle.nn.Layer):\n def __init__(\n self,\n hidden_size,\n vocab_size,\n num_steps=20,\n init_scale=0.1,\n is_sparse=False,\n dtype='float32',\n ):\n super().__init__()\n self.hidden_size = hidden_size\n self.vocab_size = vocab_size\n self.init_scale = init_scale\n self.num_steps = num_steps\n paddle.set_default_dtype(dtype)\n self.embedding = paddle.nn.Embedding(\n vocab_size,\n hidden_size,\n sparse=is_sparse,\n weight_attr=fluid.ParamAttr(\n name='embedding_para',\n initializer=paddle.nn.initializer.Uniform(\n low=-init_scale, high=init_scale\n ),\n ),\n )\n self.softmax_bias = self.create_parameter(\n attr=fluid.ParamAttr(),\n shape=[self.vocab_size],\n dtype=dtype,\n default_initializer=paddle.nn.initializer.Uniform(\n low=-self.init_scale, high=self.init_scale\n ),\n )\n\n def forward(self, input, label):\n x_emb = self.embedding(input)\n projection = paddle.matmul(\n x_emb, paddle.transpose(self.embedding.weight, perm=[1, 0])\n )\n projection = paddle.add(projection, self.softmax_bias)\n projection = paddle.reshape(projection, shape=[-1, self.vocab_size])\n loss = paddle.nn.functional.softmax_with_cross_entropy(\n logits=projection, label=label, soft_label=False\n )\n loss = paddle.reshape(loss, shape=[-1, self.num_steps])\n loss = paddle.mean(loss, axis=[0])\n loss = paddle.sum(loss)\n\n return loss\n\n\nclass TestDygraphSimpleNet(unittest.TestCase):\n def test_simple_net(self):\n for is_sparse in [True, False]:\n dtype_list = [\"float32\"]\n if not core.is_compiled_with_rocm():\n dtype_list.append(\"float64\")\n for dtype in dtype_list:\n self.simple_net_float32(is_sparse, dtype)\n\n def simple_net_float32(self, is_sparse, dtype):\n places = [fluid.CPUPlace()]\n if core.is_compiled_with_cuda():\n places.append(fluid.CUDAPlace(0))\n\n for place in places:\n seed = 90\n hidden_size = 10\n vocab_size = 1000\n num_steps = 3\n init_scale = 0.1\n batch_size = 4\n batch_num = 200\n\n for is_sort_sum_gradient in [True, False]:\n with fluid.dygraph.guard(place):\n paddle.seed(seed)\n paddle.framework.random._manual_program_seed(seed)\n\n simple_net = SimpleNet(\n hidden_size=hidden_size,\n vocab_size=vocab_size,\n num_steps=num_steps,\n init_scale=init_scale,\n is_sparse=is_sparse,\n dtype=dtype,\n )\n\n sgd = paddle.optimizer.SGD(\n learning_rate=1e-3,\n parameters=simple_net.parameters(),\n )\n dy_param_updated = {}\n dy_param_init = {}\n dy_loss = None\n\n helper = DyGraphProgramDescTracerTestHelper(self)\n fluid.set_flags(\n {'FLAGS_sort_sum_gradient': is_sort_sum_gradient}\n )\n\n for i in range(batch_num):\n x_data = np.arange(12).reshape(4, 3).astype('int64')\n y_data = np.arange(1, 13).reshape(4, 3).astype('int64')\n x_data = x_data.reshape((-1, num_steps))\n y_data = y_data.reshape((-1, 1))\n\n x = to_variable(x_data)\n y = to_variable(y_data)\n outs = simple_net(x, y)\n dy_loss = outs\n if i == 0:\n for param in simple_net.parameters():\n dy_param_init[param.name] = param.numpy()\n dy_loss.backward()\n sgd.minimize(dy_loss)\n sgd.clear_gradients()\n if i == batch_num - 1:\n for param in simple_net.parameters():\n dy_param_updated[param.name] = param.numpy()\n dy_loss_value = dy_loss.numpy()\n\n with new_program_scope():\n paddle.seed(seed)\n paddle.framework.random._manual_program_seed(seed)\n\n simple_net = SimpleNet(\n hidden_size=hidden_size,\n vocab_size=vocab_size,\n num_steps=num_steps,\n is_sparse=is_sparse,\n dtype=dtype,\n )\n\n exe = fluid.Executor(place)\n sgd = paddle.optimizer.SGD(learning_rate=1e-3)\n x = paddle.static.data(\n name=\"x\", shape=[-1, num_steps], dtype='int64'\n )\n x.desc.set_need_check_feed(False)\n y = paddle.static.data(name=\"y\", shape=[-1, 1], dtype=dtype)\n y.desc.set_need_check_feed(False)\n static_loss = simple_net(x, y)\n sgd.minimize(static_loss)\n static_param_updated = {}\n static_param_init = {}\n static_param_name_list = []\n for param in simple_net.parameters():\n static_param_name_list.append(param.name)\n\n out = exe.run(\n fluid.default_startup_program(),\n fetch_list=static_param_name_list,\n )\n for i in range(len(static_param_name_list)):\n static_param_init[static_param_name_list[i]] = out[i]\n static_loss_value = None\n for i in range(batch_num):\n x_data = np.arange(12).reshape(4, 3).astype('int64')\n y_data = np.arange(1, 13).reshape(4, 3).astype('int64')\n x_data = x_data.reshape((-1, num_steps))\n y_data = y_data.reshape((-1, 1))\n fetch_list = [static_loss]\n fetch_list.extend(static_param_name_list)\n out = exe.run(\n fluid.default_main_program(),\n feed={\"x\": x_data, \"y\": y_data},\n fetch_list=fetch_list,\n )\n static_loss_value = out[0]\n\n if i == batch_num - 1:\n for k in range(3, len(out)):\n static_param_updated[\n static_param_name_list[k - 1]\n ] = out[k]\n\n np.testing.assert_allclose(\n static_loss_value, dy_loss_value, rtol=0.001\n )\n for key, value in static_param_init.items():\n np.testing.assert_array_equal(value, dy_param_init[key])\n for key, value in static_param_updated.items():\n np.testing.assert_array_equal(value, dy_param_updated[key])\n\n\nif __name__ == '__main__':\n paddle.enable_static()\n unittest.main()\n","sub_path":"test/legacy_test/test_imperative_lod_tensor_to_selected_rows.py","file_name":"test_imperative_lod_tensor_to_selected_rows.py","file_ext":"py","file_size_in_byte":8525,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"41855963","text":"import subprocess\nimport argparse\nimport shlex\n\nparser = argparse.ArgumentParser(description='Program to Run Carla Servers in Docker')\nparser.add_argument('--starting_port', type=int, help='starting port', default='2000')\nparser.add_argument('--ids-gpus', type=str, help='string containing the gpu ids', default=\"0\")\nparser.add_argument('--server_image-name', type=str, help='docker image name', default='carla-rl-server:1.0.0')\nparser.add_argument('--client_image-name', type=str, help='docker image name', default='carla-rl-client:1.0.0')\nparser.add_argument('--num-servers', type=int, help='number of servers', default=1)\nparser.add_argument('--client-config-file', type=str, help='number of servers', default='client/config/base.yaml')\nparser.add_argument('--client_save-dir', type=str, default='./outputs', help='directory to save models, logs and videos')\nargs = parser.parse_args()\n\nfor i in range(args.num_servers):\n gpu_id = args.ids_gpus[i % len(args.ids_gpus)]\n port = args.starting_port + i*3\n cmd_run_server = \"docker run --runtime=nvidia --rm -e NVIDIA_VISIBLE_DEVICES={} -p {}-{}:2000-2002 {} /bin/bash -c \\\"sed -i '5i sync' ./CarlaUE4.sh; ./CarlaUE4.sh /Game/Maps/Town01 -carla-server -benchmark -fps=10 -carla-settings=\\\"CarlaSettings.ini\\\"\\\"\".format(gpu_id, port, port+2, args.server_image_name)\n cmd_run_client = \"docker run --runtime=nvidia --rm -d --network=host -v $PWD:/app {} python client/train.py --starting-port {} --save-dir {} --config {}\".format(args.client_image_name, port, args.client_save_dir, args.client_config_file)\n print(i, cmd_run_server)\n print(i, cmd_run_client)\n subprocess.Popen(shlex.split(cmd_run_server), stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n subprocess.Popen(shlex.split(cmd_run_client), stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n\n","sub_path":"run_servers.py","file_name":"run_servers.py","file_ext":"py","file_size_in_byte":1820,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"62757685","text":"from EffFinal import *\nfrom getCircle import *\nimport matplotlib.pyplot as plt\nimport Processing\nimport matplotlib as mpl\nimport sys\nplt.switch_backend('agg')\n\npi = 3.1415926\n\ndatadir = savedir\n#datadir = '/home/yujq/users/caijie/epoch2d/txt/MassLimit/new_a3_w9.1_n0.2/y50x300/318.0$mu m$TimeSequence.npy'\nField = Processing.Field\n\nsavedir = const.figdir + 'R' +str(int(R/1e-6)) + 'x' + str(int(point[0]/1e-6)) + Field\n\nprint(datadir,savedir)\n#data = np.load(datadir)\n#data = np.array(data)\n\nR = 350e-6\nif len(sys.argv) > 2:\n R = sys.argv[2]\n R = float(R)\nmaxY = (const.y_max - const.y_min)/2\nif R > maxY:\n thetaMax = np.arcsin(maxY/R)\nelse:\n thetaMax = pi/2\n\ndef plotField(Theta,Time,data,savedir):\n Theta , Time = Theta*180/3.14 , Time/1e-15\n #plt.pcolormesh(theta,time,data,cmap = plt.cm.bwr)\n plt.pcolormesh(Theta[:,::10],Time[:,::10],data[:,::10],cmap = plt.cm.bwr)\n \n plt.colorbar()\n plt.title(savedir + 'Field.jpg')\n plt.savefig(savedir + 'Field.jpg',dpi=160)\n plt.close('all')\n\n######\ndef getFreqs(data,theta):\n '''\n XF = np.fft.rfft(data,axis=0)\n\n freq = np.fft.rfftfreq(data.shape[0],d = dt)\n\n theta = np.linspace(-3.14/2,3.14/2,NTheta)\n\n Theta,Freq = np.meshgrid(theta,freq)\n ######\n #Theta , Freq = Theta*180/3.14 , Freq/1e12\n\n data = data[:,int(NTheta/4):int(-NTheta/4)]\n '''\n XF = np.fft.rfft(data,axis=0)\n\n freq = np.fft.rfftfreq(data.shape[0],d = dt)\n\n #theta = np.linspace(-thetaMax,thetaMax,NTheta)\n\n Theta,Freq = np.meshgrid(theta,freq)\n\n\n return Theta , Freq , XF\n\ndef plotFreqs(Theta,Freq,XF,savedir):\n Theta , Freq = Theta*180/3.14 , Freq/1e12\n #tmin = int(NTheta*75/90)\n #XF[Theta > 75] = 0\n #XF[Theta < -75] = 0\n #Freq[Theta > 75] = 0\n #Freq[Theta < -75] = 0\n #Theta[Theta < -75] = -0\n #Theta[Theta > 75] = 0\n\n #XF[np.abs(Freq)<5]=0\n #plt.pcolormesh(Theta,Freq,np.abs(XF),cmap = plt.cm.jet)\n XF[Freq>30] = 0\n plt.pcolormesh(Theta[:,::10],Freq[:,::10],np.abs(XF)[:,::10],cmap = plt.cm.jet)\n \n plt.colorbar()\n plt.xlabel('Theta')\n plt.ylabel('Freqncey[THz]')\n plt.ylim([0,30])\n plt.title(savedir + 'Freqs.jpg')\n #plt.xlim([-75,75])\n #plt.clim([0,50000])\n plt.savefig(savedir + 'Freqs.jpg',dpi=160)\n plt.close('all')\n\n######\ndef THzFilter(Theta , Freq , XF):\n XF[np.abs(Freq)>10e12]=0\n XF[np.abs(Freq)<0.1e12]=0\n\n XF[np.abs(Freq) > 2e12]=0\n\n Bz = np.fft.irfft(XF,axis = 0)\n Bz = Bz.real\n return Bz\n\ndef plotTHz(Theta,Time,data,savedir):\n Theta , Time = Theta*180/3.14 , Time/1e-15\n plt.pcolormesh(Theta[:,::10],Time[:,::10],data[:,::10],cmap = plt.cm.bwr)\n plt.colorbar()\n plt.title(savedir + 'THz.jpg')\n plt.savefig(savedir + 'THz.jpg',dpi=160)\n plt.close('all')\n\n\ndef main():\n ####\n time = np.load(const.txtdir + 'Sequencetime.npy')\n #theta = np.linspace(-thetaMax,thetaMax,NTheta)\n #Theta , Time = np.meshgrid(theta,time)\n\n ####\n data = np.load(datadir)\n data = np.array(data)\n ###\n x0 = point[0]\n y0 = point[1]\n ###\n iterateY = np.arange(data.shape[1])\n\n \n indexY = iterateY[np.abs(iterateY * const.delta_y + const.y_min - y0) < R ]\n y = indexY * const.delta_y + const.y_min\n x = np.sqrt(R **2 - (y-y0)**2) + x0\n #indexX = int((np.sqrt(R **2 - (y-y0)**2) + x0)/delta_x)\n #y = indexY * const.delta_y + const.y_min - y0 < R\n theta = np.arctan((y-y0)/(x-x0))\n \n #Theta , Time = np.meshgrid(theta,time)\n\n data = data[:,np.abs(iterateY * const.delta_y + const.y_min - y0) < R]\n\n #Ttime = 1780e-15 \n \n #data = data[time < Ttime,:]\n #time = time[time < Ttime]\n #savedir = const.figdir + str(Ttime) + 'R' +str(int(R/1e-6)) + 'x' + str(int(point[0]/1e-6)) + Field\n \n \n\n Theta , Time = np.meshgrid(theta,time)\n\n iterateY = iterateY[np.abs(iterateY * const.delta_y + const.y_min - y0) < R ]\n\n\n #data = data[:,int(NTheta/4+1/2):int(-NTheta/4)]\n plotField(Theta,Time,data,savedir) \n Theta , Freq , XF = getFreqs(data,theta)\n plotFreqs(Theta,Freq,XF,savedir)\n Bz = THzFilter(Theta , Freq , XF)\n\n Theta , Time = np.meshgrid(theta,time)\n plotTHz(Theta,Time,Bz,savedir)\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"plotFilter.py","file_name":"plotFilter.py","file_ext":"py","file_size_in_byte":4217,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"124024805","text":"import numpy as np\r\nfrom brain.network import Network\r\nimport dataLoader\r\nfrom dataInterface import DataInterface\r\nfrom ganGame import GanGame, WGanGame\r\nfrom ganPlot import GanPlot\r\n# import matplotlib.pyplot as plt\r\n# import os\r\n\r\n\r\n# Récupération des paramètres du config.ini\r\ndata_interface = DataInterface()\r\n\r\nparam_liste = data_interface.read_conf('config.ini',\r\n 'GanMnist') # Lecture du fichier de config dans la\r\n# session [GanMnist]\r\nparam_desc_disc_liste = data_interface.read_conf('config_algo_descente.ini',\r\n 'Param de desc du disc')\r\nparam_desc_gen_liste = data_interface.read_conf('config_algo_descente.ini',\r\n 'Param de desc du gen')\r\n\r\n\r\n# Initialisation des données pour l'apprentissage\r\ntraining_images, training_labels, _, _ = dataLoader.load_data(param_liste['file'][0],\r\n param_liste['dataset'][0])\r\n\r\nnumber_exp = param_liste['number_exp'][0]\r\n\r\nfor exp in range(number_exp):\r\n\r\n print(\"Lancement de l'experience n°\", exp)\r\n\r\n param = data_interface.extract_param(param_liste, exp)\r\n\r\n param_desc_disc = data_interface.extract_param(param_desc_disc_liste, exp)\r\n param_desc_gen = data_interface.extract_param(param_desc_gen_liste, exp)\r\n numbers_to_draw = param['numbers_to_draw']\r\n\r\n# On ne conserve dans le set que les 'numbers_to_draw' du config\r\n not_right_nb = []\r\n for i in range(len(training_images)):\r\n if training_labels[i] not in numbers_to_draw:\r\n not_right_nb += [i]\r\n training_images_exp = np.delete(training_images, not_right_nb, axis=0) # A proprifier plus\r\n # tard, c'est pas opti le delete\r\n\r\n batch_size = param[\"batch_size\"]\r\n\r\n# Initialisation du dossier de sauvegarde\r\n save_folder = param['save_folder']\r\n data_interface = DataInterface(save_folder)\r\n\r\n# Initialisation de l'interface d'affichage et de sauvegarde des données des résultat du GAN\r\n gan_plot = GanPlot(save_folder, numbers_to_draw)\r\n\r\n# Initialisation du discriminator\r\n disc_layers_params = param['disc_network_layers']\r\n disc_error_fun = param['disc_error_fun']\r\n disc_error_fun.vectorize()\r\n gen_error_fun = param['gen_error_fun']\r\n gen_error_fun.vectorize()\r\n \r\n\r\n critic = Network(layers_parameters=disc_layers_params,\r\n error_function=disc_error_fun,\r\n error_gen=gen_error_fun,\r\n param_desc='Param de desc du disc',\r\n learning_batch_size=batch_size,\r\n nb_exp=exp\r\n )\r\n\r\n critic_learning_ratio = param['disc_learning_ratio'] # Pour chaque partie, nombre\r\n # d'apprentissage du discriminant sur image réelle\r\n disc_fake_learning_ratio = param['disc_fake_learning_ratio'] # Pour chaque partie,\r\n # nombre d'apprentissage du discriminant sur image fausse, !!! sans apprentissage du\r\n # génerateur !!!\r\n\r\n# Initialisation du generator\r\n gen_layers_params = param['generator_network_layers']\r\n\r\n generator = Network(layers_parameters=gen_layers_params,\r\n error_function=disc_error_fun,\r\n param_desc='Param de desc du gen',\r\n learning_batch_size=batch_size,\r\n nb_exp=exp\r\n )\r\n\r\n gen_learning_ratio = param['gen_learning_ratio'] # Pour chaque partie, nombre d'apprentissage\r\n # du discriminant sur image réelle\r\n gen_learning_ratio_alone = param['gen_learning_ratio_alone']\r\n\r\n# Initialisation de la partie\r\n training_fun = param['training_fun'] # Function donnant la réponse à une vrai image attendu\r\n # (1 par défaut)\r\n\r\n ganGame = WGanGame(critic=critic,\r\n learning_set=training_images_exp,\r\n learning_fun=training_fun,\r\n generator=generator,\r\n critic_learning_ratio=critic_learning_ratio,\r\n gen_learning_ratio=gen_learning_ratio,\r\n batch_size=batch_size)\r\n\r\n play_number = param['play_number'] # Nombre de partie (Une partie = i fois apprentissage\r\n # discriminateur sur vrai image, j fois apprentissage génerateur+ discriminateur et\r\n # potentiellement k fois discriminateur avec fausse image\r\n\r\n# Préparation de la sauvegarde des scores du discriminateur pour des vrais images et des images de\r\n# synthèses\r\n score = []\r\n score_std = []\r\n\r\n# Initialisation des paramètres\r\n nb_images_during_learning = param['nb_images_during_learning']\r\n nb_images_par_sortie_during_learning = param['nb_images_par_sortie_during_learning']\r\n test_period = param['test_period']\r\n lissage_test = param['lissage_test']\r\n final_images = param['final_images']\r\n # a, b, c, d = ganGame.testDiscriminatorLearning(10) # Valeur pour le réseau vierge\r\n # discriminator_real_score.append(a)\r\n # discriminator_fake_score.append(b)\r\n # real_std.append(c)\r\n # fake_std.append(d)\r\n\r\n image_evolution_number = play_number//nb_images_during_learning\r\n\r\n try:\r\n for i in range(play_number):\r\n if i % 10 == 0:\r\n print(\"Progress : \", i)\r\n if i % test_period == 0:\r\n print(\"i\", i)\r\n a, b = ganGame.test_critic_learning(lissage_test) # effectue n test et\r\n # renvoie la moyenne des scores\r\n score.append(a)\r\n print(\"Score : \", a)\r\n score_std.append(b)\r\n if i % image_evolution_number == 0:\r\n a, b, c, d = ganGame.test_discriminator_learning(lissage_test)\r\n images_evolution = ganGame.generate_image_test()\r\n gan_plot.save_multiple_output(images_evolution, str(numbers_to_draw) +\r\n \"_au_rang_\" + str(i), str(i), a, b)\r\n learn = ganGame.play_and_learn()\r\n except KeyboardInterrupt:\r\n pass\r\n\r\n images_finales = [[]]*final_images\r\n for i in range(final_images):\r\n image_test, associate_noise = ganGame.generate_image() # génération d'une image à la fin de\r\n # l'apprentissage\r\n images_finales[i] = image_test\r\n if final_images > 0:\r\n gan_plot.save_multiple_output(images_finales, str(numbers_to_draw) + str(play_number),\r\n str(play_number), score[-1],\r\n score_std[-1])\r\n\r\n conf = data_interface.save_conf('config.ini', 'GanMnist') # récupération de la\r\n # configuration pour la sauvegarde dans les fichiers\r\n data_interface.save(score, 'score', conf) # Sauvegarde\r\n # des courbes de score\r\n data_interface.save(score_std, 'score_std', conf)\r\n\r\n gan_plot.save_courbes(param, param_desc_gen, param_desc_disc,\r\n score, score_std)\r\n\r\n state = generator.save_state()\r\n gan_plot.save_plot_network_state(state)\r\n # if os.name == 'nt': # pour exécuter l'affichage uniquement sur nos ordis, et pas la vm\r\n # state = generator.save_state()\r\n # gan_plot.plot_network_state(state)\r\n\r\n # gan_plot.plot_courbes(param, discriminator_real_score, discriminator_fake_score)\r\n","sub_path":"WGanMnistMain.py","file_name":"WGanMnistMain.py","file_ext":"py","file_size_in_byte":7384,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"309769920","text":"\"\"\"\nGums' sumptious recipes.\n\nAuthor: @PKG_AUTHOR@ \n\nLicense: @PKG_LICENSE@\n\"\"\"\n\nAbout = \"\"\"\\\nGums has lived a very long life. 29 Snow Moons young. She is a member of the\nClan of the Cave Cricket. Over the years, Gums has curated a long list of\nrecipes that have provided her clan an enhanced quality of life. Well, at least,\nfood that didn't kill.\"\"\"\n\nclass GumsRecipe:\n \"\"\" Recipe class \"\"\"\n def __init__(self, ingredients=[], instructions=[]):\n \"\"\"\n Initializer.\n\n Parameters:\n ingredients List of things tossed into the food.\n instrcutions The step-by-step manual.\n \"\"\"\n self.ingredients = ingredients\n self.instructions = instructions\n","sub_path":"templates/ws/src/python/pkg_name/whatever/gums_recipes.py","file_name":"gums_recipes.py","file_ext":"py","file_size_in_byte":673,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"246902838","text":"from jogo.Player import Player\r\nfrom pygame import transform\r\nfrom PPlay.mouse import Mouse\r\nfrom PPlay.window import Window\r\nfrom PPlay.gameimage import GameImage\r\nfrom jogo.Territorio import Territorio\r\nfrom jogo.Continente import Continente\r\nfrom constant import *\r\n\r\nclass ControladorMapa:\r\n\r\n caminho_img_mapa = \"assets/imagem/mapa/\"\r\n img_mapa = \"mapa_war_conexoes.png\"\r\n img_fundo = \"fundo.jpg\"\r\n img_colisao = \"mouse_colisao.jpg\"\r\n lista_territorios = [] # Lista de todos os territorios do jogo\r\n lista_continentes = []\r\n #Instancias da classe Continentes\r\n africa = None\r\n america_do_norte = None\r\n america_do_sul = None\r\n asia = None\r\n europa = None\r\n oceania = None\r\n territorios_selecionados = [] # primeira posicao armazenara o territorio que recebera tropa na etapa 1,\r\n # atacante na etapa 2, ou territorio que tera sua tropa movida na etapa 3\r\n # a segunda posicao armazenara o territorio desensor na etapa 2 ou o territorio que recebera tropa\r\n # movida de outro territorio na etapa 3\r\n\r\n\r\n def __init__(self, janela: Window):\r\n self.pode_desenhar = True\r\n self.clicou_inicial = False\r\n self.clicou_vizinho = False\r\n self.colisao_mouse = GameImage(self.caminho_img_mapa+self.img_colisao)\r\n self.janela = janela\r\n self.fundo = GameImage(self.caminho_img_mapa+self.img_fundo)\r\n self.mapa = GameImage(self.caminho_img_mapa+self.img_mapa)\r\n #self.inicia_territorios()\r\n #self.inicia_continentes()\r\n self.primeira_vez = True\r\n #Redimensionando as imagens, eh necessario usar .image pois eh classe do Pygame\r\n self.fundo.image = transform.scale(self.fundo.image, (janela.width, janela.height))\r\n self.mapa.image = transform.scale(self.mapa.image, (int(PERCT_MAPA*LARGURA_PADRAO), int(PERCT_MAPA*ALTURA_PADRAO)))\r\n for territorio in self.lista_territorios:\r\n territorio.muda_escala(int(PERCT_MAPA*LARGURA_PADRAO), int(PERCT_MAPA*ALTURA_PADRAO))\r\n #territorio.img.image = transform.scale(territorio.img.image, (int(PERCT_MAPA*LARGURA_PADRAO), int(PERCT_MAPA*ALTURA_PADRAO)))\r\n #territorio.img_select.image = transform.scale(territorio.img_select.image, (int(PERCT_MAPA*LARGURA_PADRAO), int(PERCT_MAPA*ALTURA_PADRAO)))\r\n \r\n \r\n def selecionar_territorio(self, mouse:Mouse, jogador:Player, etapa:int) -> None:\r\n if etapa > 1:\r\n return\r\n if mouse.is_button_pressed(1):\r\n self.clicou_inicial = True\r\n\r\n if self.clicou_inicial and not mouse.is_button_pressed(1):\r\n x, y = mouse.get_position()\r\n self.clicou_inicial = False\r\n self.colisao_mouse.set_position(x, y)\r\n self.colisao_mouse.draw()\r\n self.pode_desenhar = True\r\n for territorio in jogador.territorios:\r\n if self.colisao_mouse.collided_perfect(territorio.img):\r\n # durante a etapa de combate, nao posso selecionar um territorio atacante com um exercito\r\n if(etapa == 2 and territorio.quantidade_tropas <= 1):\r\n break\r\n if len(self.territorios_selecionados) == 1:\r\n self.limpa_territorios_selecionados()\r\n territorio.selecionado = True\r\n self.territorios_selecionados.append(territorio)\r\n break\r\n\r\n def selecionar_inicial(self, mouse:Mouse, jogador:Player, etapa:int):\r\n if etapa < 2:\r\n return\r\n if mouse.is_button_pressed(1):\r\n self.clicou_inicial = True\r\n\r\n if self.clicou_inicial and not mouse.is_button_pressed(1):\r\n self.clicou_inicial = False\r\n x, y = mouse.get_position()\r\n self.colisao_mouse.set_position(x, y)\r\n self.colisao_mouse.draw()\r\n self.pode_desenhar = True\r\n for territorio in jogador.territorios:\r\n if self.colisao_mouse.collided_perfect(territorio.img):\r\n # durante a etapa de combate, nao posso selecionar um territorio atacante com um exercito\r\n if (etapa == 2 and territorio.quantidade_tropas <= 1) or len(self.territorios_selecionados) > 0:\r\n break\r\n self.territorios_selecionados.append(territorio)\r\n\r\n def selecionar_vizinho(self, mouse:Mouse, jogador:Player, etapa:int): # argumento 'etapa' indica em que etapa o turno esta\r\n if mouse.is_button_pressed(1) and len(self.territorios_selecionados) >= 1:\r\n self.clicou_vizinho = True\r\n\r\n if self.clicou_vizinho and not mouse.is_button_pressed(1):\r\n self.clicou_vizinho = False\r\n x, y = mouse.get_position()\r\n self.colisao_mouse.set_position(x, y)\r\n self.colisao_mouse.draw()\r\n self.pode_desenhar = True\r\n for territorio in self.lista_territorios:\r\n if (\r\n self.colisao_mouse.collided_perfect(territorio.img) and \r\n territorio != self.territorios_selecionados[0] and\r\n territorio.eh_vizinho(self.territorios_selecionados[0])\r\n ):\r\n\r\n if( \r\n (etapa == 2 and territorio.cor_tropas != self.territorios_selecionados[0].cor_tropas) or \r\n (etapa == 3 and territorio.cor_tropas == self.territorios_selecionados[0].cor_tropas)\r\n ):\r\n if len(self.territorios_selecionados) == 1:\r\n territorio.selecionado = True\r\n self.territorios_selecionados.append(territorio)\r\n elif len(self.territorios_selecionados) == 2:\r\n self.territorios_selecionados[1].selecionado = False\r\n territorio.selecionado = True\r\n self.territorios_selecionados[1] = territorio\r\n #print(\"primario {} {}, secundario {} {}\".format(self.territorios_selecionados[0].nome, self.territorios_selecionados[0].id, territorio.nome, territorio.id))\r\n break # Para nao percorrer toda a lista de territorios\r\n \r\n def render(self, etapa):\r\n \r\n if (self.pode_desenhar):\r\n self.pode_desenhar = False\r\n \r\n self.fundo.draw()\r\n self.mapa.draw()\r\n for territorio in self.lista_territorios:\r\n territorio.img.draw()\r\n for territorio in self.lista_territorios:\r\n for territorio_selecionado in self.territorios_selecionados:\r\n if (\r\n territorio.eh_vizinho(self.territorios_selecionados[0]) and\r\n ( \r\n (etapa == 2 and territorio.cor_tropas != self.territorios_selecionados[0].cor_tropas) or\r\n (etapa == 3 and territorio.cor_tropas == self.territorios_selecionados[0].cor_tropas)\r\n )\r\n ):\r\n territorio.img_highlight.draw()\r\n if territorio_selecionado == territorio:\r\n territorio.img_select.draw()\r\n\r\n self.desenha_quantidade_tropas(territorio)\r\n ''' \r\n tamanho_texto = 18\r\n cor_texto = (255,0,127)\r\n self.janela.draw_text(str(territorio.quantidade_tropas),\r\n territorio.pos_texto_x, \r\n territorio.pos_texto_y, \r\n tamanho_texto, \r\n cor_texto\r\n )\r\n '''\r\n def desenha_quantidade_tropas(self, territorio:Territorio):\r\n '''\r\n tamanho_texto = 28\r\n cor_texto = (255,255,255)\r\n self.janela.draw_text(\r\n str(territorio.quantidade_tropas),\r\n territorio.pos_texto_x-3, \r\n territorio.pos_texto_y-3, \r\n tamanho_texto, \r\n cor_texto\r\n )\r\n '''\r\n tamanho_texto = 24\r\n #cor_texto = (255,0,127)\r\n #cor_texto = (255, 95, 31)\r\n cor_texto = (106,106,106)\r\n self.janela.draw_text(\r\n str(territorio.quantidade_tropas),\r\n territorio.pos_texto_x, \r\n territorio.pos_texto_y, \r\n tamanho_texto, \r\n cor_texto,\r\n bold=True\r\n )\r\n \r\n\r\n def carrega_imagens_dos_territorios(self):\r\n\r\n for territorio in self.lista_territorios:\r\n territorio.carrega_imagem()\r\n\r\n def set_lista_continentes(self, lista_continentes):\r\n\r\n for continente in lista_continentes:\r\n \r\n if continente.nome == \"Africa\":\r\n self.africa = continente\r\n elif continente.nome == \"America do Norte\":\r\n self.america_do_norte = continente\r\n elif continente.nome == \"America do Sul\":\r\n self.america_do_sul = continente\r\n elif continente.nome == \"Asia\":\r\n self.asia = continente\r\n elif continente.nome == \"Europa\":\r\n self.europa = continente\r\n elif continente.nome == \"Oceania\":\r\n self.oceania = continente\r\n \r\n self.lista_continentes = lista_continentes\r\n \r\n def limpa_territorios_selecionados(self):\r\n for territorio in self.territorios_selecionados:\r\n territorio.selecionado = False\r\n self.territorios_selecionados = []\r\n\r\n def fim_de_turno(self,jogador:Player):\r\n for territorio in jogador.territorios:\r\n territorio.fim_de_turno()","sub_path":"WAR/jogo/ControladorMapa.py","file_name":"ControladorMapa.py","file_ext":"py","file_size_in_byte":9864,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"131986349","text":"\"\"\"\n '_auth': {\n 'type': 'dict',\n 'schema': {\n '_auth_username': {'type': 'string'},\n '_auth_password': {'type': 'string'},\n '_auth_club': {'type': 'integer'}\n }\n },\n '_auth_username': {'type': 'string'},\n '_auth_password': {'type': 'string'},\n '_auth_club': {'type': 'integer'},\n 'ActiveClubs': {'type': 'list'},\n 'ActiveFunctions': {'type': 'list'},\n 'Clubs': {'type': 'list'},\n 'ExtraAddresses': {'type': 'list'},\n 'Functions': {'type': 'list'},\n 'HomeAddress': {'type': 'dict'},\n 'MyProfileSettings': {'type': 'dict'},\n 'Id': {'type': 'integer', 'required': True},\n 'IsPersonInfoLocked': {'type': 'boolean'},\n 'LastChangedDate': {'type': 'datetime'},\n 'LastName': {'type': 'string'},\n 'Nationality': {'type': 'integer'},\n 'PersonGender': {'type': 'string'},\n 'PersonId': {'type': 'integer'},\n 'RestrictedAddress': {'type': 'boolean'},\n 'SportNo': {'type': 'string'},\n 'UserId': {'type': 'integer'},\n 'Username': {'type': 'string'},\n 'FirstName': {'type': 'string'},\n 'FullName': {'type': 'string'},\n 'ApproveMarketing': {'type': 'boolean'},\n 'ApprovePublishing': {'type': 'boolean'},\n 'AutomaticDataCleansingReservation': {'type': 'boolean'},\n 'BirthDate': {'type': 'datetime'},\n \"\"\"\n_schema = {\n\n 'active_clubs': {'type': 'list'},\n 'active_functions': {'type': 'list'},\n 'functions': {'type': 'list'},\n 'clubs': {'type': 'list'},\n 'club_id': {'type': 'integer', 'required': True, 'unique': True},\n 'id': {'type': 'integer', 'required': True},\n 'first_name': {'type': 'string'},\n 'full_name': {'type': 'string'},\n 'login': {'type': 'string'},\n 'password': {'type': 'string'},\n 'person_id': {'type': 'integer'},\n 'user_id': {'type': 'integer'},\n 'username': {'type': 'string'},\n 'modified': {'type': 'datetime'}\n}\n\ndefinition = {\n 'item_title': 'integration',\n 'datasource': {'source': 'integration',\n },\n 'additional_lookup': {\n 'url': 'regex(\"[\\d{1,20}]+\")',\n 'field': 'club_id',\n },\n 'extra_response_fields': ['club_id'],\n 'versioning': False,\n 'resource_methods': ['GET', 'POST'],\n 'item_methods': ['GET', 'PATCH', 'PUT'],\n\n 'schema': _schema\n}\n","sub_path":"domain/integration.py","file_name":"integration.py","file_ext":"py","file_size_in_byte":2297,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"526257790","text":"#!/bin/python3\n\nimport tensorflow as tf\nimport data\nimport model\nfrom glob import glob\nimport sys\n\nbatch_size = 56\ninput_max_length = 28\noutput_max_length = 24\nlearning_rate = 4e-4\ncheckpoint = \"ckpts/model101.ckpt\"\nlogdir = \"logdir/train101\"\nstart = 0\n\ndef main():\n reader = data.Reader('.', data='data',\n batch_size=batch_size,\n in_maxlen=input_max_length,\n out_maxlen=output_max_length)\n\n m = model.Model(input_size=reader.input_size, output_size=reader.output_size)\n m.train(batch_size, learning_rate, out_help=False, time_discount=True, sampling_probability=0.2)\n\n summaries = tf.summary.merge_all()\n\n init = tf.global_variables_initializer()\n\n sum_accuracy = 0.0\n count = 0\n\n saver = tf.train.Saver()\n\n with tf.Session() as sess:\n summary_writer = tf.summary.FileWriter(logdir, sess.graph)\n\n if len(glob(checkpoint + \"*\")) > 0:\n saver.restore(sess, checkpoint)\n print(\"Model restored!\")\n else:\n sess.run(init)\n print(\"Fresh variables!\")\n\n for i in range(start, 1000000):\n input_ids, input_len, output_ids, output_len = reader.next_batch()\n\n if input_ids is None:\n print(\"No more data!\")\n break\n\n feed = { m.input_data: input_ids,\n m.input_lengths: input_len,\n m.output_data: output_ids,\n m.output_lengths: output_len }\n summary_out, _ = sess.run([summaries, m.train_step], feed_dict=feed)\n\n if (i+1) % 100 == 0:\n summary_writer.add_summary(summary_out, (i+1)/50)\n train_accuracy = sess.run(m.accuracy, feed_dict=feed)\n sum_accuracy += train_accuracy\n count += 1\n print(\"step {0}, training accuracy {1}\".format(i+1, train_accuracy))\n\n if (i+1) % 2000 == 0:\n avg_accuracy = sum_accuracy/count\n print(\"Average accuracy:\", avg_accuracy)\n sum_accuracy = 0.0\n count = 0\n\n summary_writer.flush()\n save_path = saver.save(sess, checkpoint)\n print(\"Model saved in file:\", save_path)\n\n if (i+1) % 500 == 0:\n sys.stdout.flush()\n\n summary_writer.close()\n\nmain()\n","sub_path":"train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":2410,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"161746676","text":"\"\"\"Test the parse module\n\nWriten by Lea \"\"\"\n\nimport pytest\nfrom names import Names\nfrom scanner import Scanner\nfrom error import SyntaxError , SemanticError , ValueError, UnclassedError\n\n'''Test the scanner module'\n\nlist of functions to test:\nget_symbol\nerror\n'''\n\n@pytest.fixture\ndef new_names():\n names = Names()\n return names\n\n\n@pytest.fixture\ndef new_symbol():\n symbol = Symbol()\n return symbol\n\n\n@pytest.fixture\ndef new_scanner():\n data = (\" device7, 12 has \")\n other_names = Names()\n scan = Scanner(data, other_names, True)\n return scan\n\n\n@pytest.fixture\ndef no_spaces():\n return [\"d\" , \"e\" , \"v\" , \"i\" , \"c\" , \"e\" , \"7\" , \",\" , \"1\", \"2\" , \"h\" , \"a\" , \"s\" ]\n\n\ndef test_new_scanned_item_functionality(new_names):\n with pytest.raises(FileNotFoundError):\n Scanner(\"fakefile.txt\", new_names, False)\n\n\ndef test_skip_spaces(new_scanner, new_names, expected_out = \"d\"):\n new_scanner.skip_spaces()\n assert new_scanner.current_character == expected_out\n\n\ndef test_advance(new_scanner, no_spaces):\n i=0\n while i <= len(no_spaces)-1:\n expected = no_spaces[i]\n new_scanner.skip_spaces()\n assert new_scanner.current_character == expected\n new_scanner.advance()\n i += 1\n\n\ndef test_get_name_and_num(new_scanner, new_names):\n \"\"\"check that the get_name function gives out a valid name and the next character,\n check that the name is an alphanumerical string\"\"\"\n new_scanner.skip_spaces()\n name = new_scanner.get_name()\n assert name[0] == \"device7\"\n assert name [1] == \",\"\n assert name[0].isalnum()\n new_scanner.advance()\n new_scanner.advance()\n number = new_scanner.get_number()\n assert number[0] == \"12\"\n assert number[1] == \" \"\n\n@pytest.mark.parametrize(\"data, expected_output_type, expected_output_id\", [(\"DEVICES\",\n0,\"ignore\"),(\"NAND\",3, \"ignore\"),(\"device\", 1, \"ignore\"),\n(\"A12J\", 3, \"ignore\"), (\";\", 8,\"ignore\"),(\"12\", 2, \"ignore\")])\ndef test_get_symbol(new_names, data, expected_output_type, expected_output_id):\n \"\"\"Test that names, numbers, symbols and keywords are all\n initialised and stored in the right sections\"\"\"\n test_scan = Scanner(data, new_names, True)\n val = test_scan.get_symbol()\n assert val.type == expected_output_type\n\n\ndef test_arrow_recognition(new_names):\n \"\"\"Tests the recognition of an arrow symbol \"\"\"\n test_scan = Scanner(\"=>\", new_names, True)\n val = test_scan.get_symbol()\n assert val.type == 5\n\n\ndef test_get_symbol_ignore():\n empty_names= Names()\n \"\"\"check that the words in the scanner.ignore list are not appended to the name class\"\"\"\n test_strings = ('gates', 'gate', 'initially', ' initially')\n before = len(empty_names.names)\n for word in test_strings:\n test_scan = Scanner(word, empty_names, True)\n # this will make symbols for all 11 defined symbols, but none for the ignored strings inputed\n val = test_scan.get_symbol()\n assert val is None\n after_num = len(empty_names.names)\n assert before + 11 == after_num\n assert empty_names.names == [\"devices\", \"connections\", \"monitor\",\"are\", \"is\", \"have\", \"has\",\n \"set\", \"to\", \"cycle\",\"device\"]\n\n\ndef test_wordcount(new_names):\n \"\"\"test to see whether the names in the input string are added\n correctly and that the wordcount is counting well too\"\"\"\n Scanner(\"\", new_names, True)\n before = []\n after = []\n before.append(len(new_names.names))\n before.append(0)\n test_scan = Scanner(\"A1 to A2.I4\", new_names, True)\n i = 0\n while i <= 4:\n test_scan.get_symbol()\n i += 1\n after.append(len(new_names.names))\n after.append(test_scan.word_number)\n assert after[0] == before[0] + 3\n assert after[1] == before[1] + 5\n\n\ndef test_non_valid_symbol(new_names):\n with pytest.raises(SyntaxError):\n Scanner(\" +\", new_names, True).get_symbol() # + is not a valid symbol\n Scanner(\" 4fjd\", new_names, True).get_symbol() #\n","sub_path":"literature/reports/GF2 - Software - Interim report 2/GF2_lmhg2_files2/main_project/test_scanner.py","file_name":"test_scanner.py","file_ext":"py","file_size_in_byte":3985,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"554814364","text":"list1 = ['1.Jost do It', '2.一切皆有可能', '3.让编程改变世界', '4.Impossible is Nothing']\nlist2 = ['4.阿迪达斯', '2.李宁', '3.鱼C工作室', '1.耐克']\nlist2.sort()\n#list2.sort(reverse=True)#倒序\n\n\n\nlist3= [(x, y) for x in range(10) for y in range(10) if x%2==0 if y%2!=0]\nprint(list3)\n\nprint('----------------------------------')\n\nlist4= [x+\":\"+y[2:] for x in list2 for y in list1 if x[0] == y[0]]\nfor x in list4:\n\tprint(x)","sub_path":"fishc/013_homework.py","file_name":"013_homework.py","file_ext":"py","file_size_in_byte":447,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"618316131","text":"# Copyright (c) 2019 PaddlePaddle Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\"\"\"BERT model.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport six\nimport json\nimport logging\nimport numpy as np\nimport paddle.fluid as fluid\nfrom model.transformer_encoder import encoder, pre_process_layer\n\nlogging.basicConfig(format = '%(asctime)s - %(levelname)s - %(name)s - %(message)s', \n datefmt = '%m/%d/%Y %H:%M:%S',\n level = logging.INFO)\nlogging.getLogger().setLevel(logging.INFO) \nlogger = logging.getLogger(__name__)\n\nclass BertConfig(object):\n def __init__(self, config_path):\n self._config_dict = self._parse(config_path)\n\n def _parse(self, config_path):\n try:\n with open(config_path) as json_file:\n config_dict = json.load(json_file)\n except Exception:\n raise IOError(\"Error in parsing bert model config file '%s'\" %\n config_path)\n else:\n return config_dict\n\n def __getitem__(self, key):\n return self._config_dict[key]\n\n def print_config(self):\n for arg, value in sorted(six.iteritems(self._config_dict)):\n logger.info('%s: %s' % (arg, value))\n logger.info('------------------------------------------------')\n\n\nclass BertModel(object):\n def __init__(self,\n src_ids,\n position_ids,\n sentence_ids,\n input_mask,\n config,\n weight_sharing=True,\n use_fp16=False):\n\n self._emb_size = config['hidden_size']\n self._n_layer = config['num_hidden_layers']\n self._n_head = config['num_attention_heads']\n self._voc_size = config['vocab_size']\n self._max_position_seq_len = config['max_position_embeddings']\n self._sent_types = config['type_vocab_size']\n self._hidden_act = config['hidden_act']\n self._prepostprocess_dropout = config['hidden_dropout_prob']\n self._attention_dropout = config['attention_probs_dropout_prob']\n self._weight_sharing = weight_sharing\n\n self._word_emb_name = \"word_embedding\"\n self._pos_emb_name = \"pos_embedding\"\n self._sent_emb_name = \"sent_embedding\"\n self._dtype = \"float16\" if use_fp16 else \"float32\"\n\n # Initialize all weigths by truncated normal initializer, and all biases \n # will be initialized by constant zero by default.\n self._param_initializer = fluid.initializer.TruncatedNormal(\n scale=config['initializer_range'])\n\n self._build_model(src_ids, position_ids, sentence_ids, input_mask)\n\n def _build_model(self, src_ids, position_ids, sentence_ids, input_mask):\n # padding id in vocabulary must be set to 0\n emb_out = fluid.layers.embedding(\n input=src_ids,\n size=[self._voc_size, self._emb_size],\n dtype=self._dtype,\n param_attr=fluid.ParamAttr(\n name=self._word_emb_name, initializer=self._param_initializer),\n is_sparse=False)\n position_emb_out = fluid.layers.embedding(\n input=position_ids,\n size=[self._max_position_seq_len, self._emb_size],\n dtype=self._dtype,\n param_attr=fluid.ParamAttr(\n name=self._pos_emb_name, initializer=self._param_initializer))\n\n sent_emb_out = fluid.layers.embedding(\n sentence_ids,\n size=[self._sent_types, self._emb_size],\n dtype=self._dtype,\n param_attr=fluid.ParamAttr(\n name=self._sent_emb_name, initializer=self._param_initializer))\n\n emb_out = emb_out + position_emb_out\n emb_out = emb_out + sent_emb_out\n\n emb_out = pre_process_layer(\n emb_out, 'nd', self._prepostprocess_dropout, name='pre_encoder')\n\n if self._dtype == \"float16\":\n input_mask = fluid.layers.cast(x=input_mask, dtype=self._dtype)\n\n # self_attn_mask = fluid.layers.matmul(\n # x=input_mask, y=input_mask, transpose_y=True)\n self_attn_mask = fluid.layers.expand(fluid.layers.transpose(input_mask, [0, 2, 1]), [1, 384, 1]) \n self_attn_mask = fluid.layers.scale(\n x=self_attn_mask, scale=10000.0, bias=-1.0, bias_after_scale=False)\n n_head_self_attn_mask = fluid.layers.stack(\n x=[self_attn_mask] * self._n_head, axis=1)\n n_head_self_attn_mask.stop_gradient = True\n\n self._enc_out = encoder(\n enc_input=emb_out,\n attn_bias=n_head_self_attn_mask,\n n_layer=self._n_layer,\n n_head=self._n_head,\n d_key=self._emb_size // self._n_head,\n d_value=self._emb_size // self._n_head,\n d_model=self._emb_size,\n d_inner_hid=self._emb_size * 4,\n prepostprocess_dropout=self._prepostprocess_dropout,\n attention_dropout=self._attention_dropout,\n relu_dropout=0,\n hidden_act=self._hidden_act,\n preprocess_cmd=\"\",\n postprocess_cmd=\"dan\",\n param_initializer=self._param_initializer,\n name='encoder')\n\n def get_sequence_output(self):\n return self._enc_out\n\n def get_pooled_output(self):\n \"\"\"Get the first feature of each sequence for classification\"\"\"\n\n next_sent_feat = fluid.layers.slice(\n input=self._enc_out, axes=[1], starts=[0], ends=[1])\n next_sent_feat = fluid.layers.fc(\n input=next_sent_feat,\n size=self._emb_size,\n act=\"tanh\",\n param_attr=fluid.ParamAttr(\n name=\"pooled_fc.w_0\", initializer=self._param_initializer),\n bias_attr=\"pooled_fc.b_0\")\n return next_sent_feat\n\n def get_pretraining_output(self, mask_label, mask_pos, labels):\n \"\"\"Get the loss & accuracy for pretraining\"\"\"\n\n mask_pos = fluid.layers.cast(x=mask_pos, dtype='int32')\n\n # extract the first token feature in each sentence\n next_sent_feat = self.get_pooled_output()\n reshaped_emb_out = fluid.layers.reshape(\n x=self._enc_out, shape=[-1, self._emb_size])\n # extract masked tokens' feature\n mask_feat = fluid.layers.gather(input=reshaped_emb_out, index=mask_pos)\n\n # transform: fc\n mask_trans_feat = fluid.layers.fc(\n input=mask_feat,\n size=self._emb_size,\n act=self._hidden_act,\n param_attr=fluid.ParamAttr(\n name='mask_lm_trans_fc.w_0',\n initializer=self._param_initializer),\n bias_attr=fluid.ParamAttr(name='mask_lm_trans_fc.b_0'))\n # transform: layer norm \n mask_trans_feat = pre_process_layer(\n mask_trans_feat, 'n', name='mask_lm_trans')\n\n mask_lm_out_bias_attr = fluid.ParamAttr(\n name=\"mask_lm_out_fc.b_0\",\n initializer=fluid.initializer.Constant(value=0.0))\n if self._weight_sharing:\n fc_out = fluid.layers.matmul(\n x=mask_trans_feat,\n y=fluid.default_main_program().global_block().var(\n self._word_emb_name),\n transpose_y=True)\n fc_out += fluid.layers.create_parameter(\n shape=[self._voc_size],\n dtype=self._dtype,\n attr=mask_lm_out_bias_attr,\n is_bias=True)\n\n else:\n fc_out = fluid.layers.fc(input=mask_trans_feat,\n size=self._voc_size,\n param_attr=fluid.ParamAttr(\n name=\"mask_lm_out_fc.w_0\",\n initializer=self._param_initializer),\n bias_attr=mask_lm_out_bias_attr)\n\n mask_lm_loss = fluid.layers.softmax_with_cross_entropy(\n logits=fc_out, label=mask_label)\n mean_mask_lm_loss = fluid.layers.mean(mask_lm_loss)\n\n next_sent_fc_out = fluid.layers.fc(\n input=next_sent_feat,\n size=2,\n param_attr=fluid.ParamAttr(\n name=\"next_sent_fc.w_0\", initializer=self._param_initializer),\n bias_attr=\"next_sent_fc.b_0\")\n\n next_sent_loss, next_sent_softmax = fluid.layers.softmax_with_cross_entropy(\n logits=next_sent_fc_out, label=labels, return_softmax=True)\n\n next_sent_acc = fluid.layers.accuracy(\n input=next_sent_softmax, label=labels)\n\n mean_next_sent_loss = fluid.layers.mean(next_sent_loss)\n\n loss = mean_next_sent_loss + mean_mask_lm_loss\n return next_sent_acc, mean_mask_lm_loss, loss\n","sub_path":"ACL2019-KTNET/reading_comprehension/src/model/bert.py","file_name":"bert.py","file_ext":"py","file_size_in_byte":9301,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"478441395","text":"#!/usr/bin/python\nimport sys\nimport csv\n\nnet = 0.0\nnet_amount = 0\ntransactions = 0\n\n\nif len(sys.argv) > 1:\n market = sys.argv[1].upper()\nelse:\n market = 'BTC-TRTL'\n\nif len(sys.argv) > 2:\n file_name = sys.argv[2]\nelse:\n file_name = 'export_trades.csv'\n\nbuy = True\nprice = 0.0\namount = 0\nunits = ['BTC', 'Satoshis']\n\nwith open(file_name) as csv_file:\n csv_reader = csv.reader(csv_file, delimiter=',')\n \n for row in csv_reader:\n \n #skip unrelated transactions\n if row[1] != market:\n continue\n \n transactions += 1\n\n #figure out buy or sell\n if row[0].lower() == 'buy':\n buy = True\n else:\n buy = False\n\n #set price and amount\n price = float(row[4])\n amount = float(row[3])\n\n #update net\n if buy:\n net -= price * amount\n net_amount += amount\n else:\n net += price * amount\n net_amount -= amount\n\nif market[:3] == 'LTC':\n units = ['LTC', 'Litoshis']\n \nif net_amount > 0:\n print('%f net units bought' % net_amount)\n \nif net_amount < 0:\n print('%f net units sold' % -net_amount)\n\nif net_amount != 0:\n print('average unit price: %f %s' % ((-net / float(net_amount) * 100000000), units[1]))\n\nif transactions > 0:\n print('%s %s net gain over %d transactions' % (str(net)[:10], units[0], transactions))\nelse:\n print('no transactions found for %s' % market)\n\n","sub_path":"TradeOgreCalc.py","file_name":"TradeOgreCalc.py","file_ext":"py","file_size_in_byte":1461,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"21564672","text":"__author__ = 'Daniel'\n\nimport unittest\nimport json\n\nfrom HuePyPi.Schedules import Schedules\n\nresponse = {\n \"1\": {\n \"name\": \"Timer\",\n \"description\": \"\",\n \"command\": {\n \"address\": \"/api/s95jtYH8HUVWNkCO/groups/0/action\",\n \"body\": {\n \"scene\": \"02b12e930-off-0\"\n },\n \"method\": \"PUT\"\n },\n \"time\": \"PT00:01:00\",\n \"created\": \"2014-06-23T13:39:16\",\n \"status\": \"disabled\",\n \"autodelete\": False,\n \"starttime\": \"2014-06-23T13:39:16\"\n },\n \"2\": {\n \"name\": \"Alarm\",\n \"description\": \"\",\n \"command\": {\n \"address\": \"/api/s95jtYH8HUVWNkCO/groups/0/action\",\n \"body\": {\n \"scene\": \"02b12e930-off-0\"\n },\n \"method\": \"PUT\"\n },\n \"localtime\": \"2014-06-23T19:52:00\",\n \"time\": \"2014-06-23T13:52:00\",\n \"created\": \"2014-06-23T13:38:57\",\n \"status\": \"disabled\",\n \"autodelete\": False\n }\n}\n\nclass Response(object):\n def __init__(self, content):\n self.content = content\n\n\nclass FakeRequests(object):\n def __init__(self):\n self.error = False\n\n def get(self, url):\n if not self.error:\n return Response(json.dumps(response))\n\n\nclass TestSchedules(unittest.TestCase):\n def setUp(self):\n self.schedule = Schedules(\"192.168.1.33\", \"danielllewellyn\")\n\n def test_cstr(self):\n self.schedule = Schedules(\"192.168.1.33\", \"danielllewellyn\")\n assert self.schedule.ip == \"192.168.1.33\"\n assert self.schedule.username == \"danielllewellyn\"\n\n def test_get_all_schedules(self):\n self.schedule.requests = FakeRequests()\n self.schedule.get_all_schedules()\n assert self.schedule.schedules[0].id == \"1\"\n assert self.schedule.schedules[0].name == \"Timer\"\n assert not self.schedule.schedules[0].autodelete\n assert self.schedule.schedules[1].time == \"2014-06-23T13:52:00\"\n assert self.schedule.schedules[0].status == \"disabled\"","sub_path":"tests/test_schedules.py","file_name":"test_schedules.py","file_ext":"py","file_size_in_byte":2050,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"43482683","text":"import random\r\nfrom turtle import Turtle\r\n\r\ndef recursive_lines(turtle, angle_start, angle, turn, line_max, iterations=0):\r\n colors = [\"red\", \"orange\", \"brown\", \"green\", \"blue\", \"purple\"]\r\n turtle.setheading(angle)\r\n color = random.randint(0, len(colors)-1)\r\n turtle.color(colors[color])\r\n\r\n x = turtle.xcor()\r\n y = turtle.ycor()\r\n\r\n line_len = random.randint(line_max / 2, line_max)\r\n turtle.forward(line_len)\r\n turtle.setheading(angle + 180)\r\n turtle.penup()\r\n turtle.setpos(x, y)\r\n turtle.pendown()\r\n\r\n new_angle = angle + turn\r\n\r\n if iterations <= 1440 / turn:\r\n recursive_lines(turtle, angle_start, new_angle, turn, line_max, (iterations+1))\r\n\r\ndef main():\r\n ANIMATION_SPEED = 0\r\n billy_bob = Turtle()\r\n billy_bob.speed(ANIMATION_SPEED)\r\n line_len = random.randrange(100, 2000, 2)\r\n turn = random.randint(10, 30)\r\n recursive_lines(billy_bob, 0, 0, turn, 300)\r\n\r\nmain()\r\n","sub_path":"Python/RecursiveTurtle/recursiveturtle.py","file_name":"recursiveturtle.py","file_ext":"py","file_size_in_byte":943,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"332034801","text":"import os \nimport cv2 \nfrom PIL import Image \nfrom mutagen.mp3 import MP3\nimport math\nimport multiprocessing\n\ndef createClip(imgFileName, audioFileName, videoFileName): \n frame = cv2.imread(imgFileName) \n\n # setting the frame width, height width \n # the width, height of first image \n height, width, layers = frame.shape \n\n video = cv2.VideoWriter(videoFileName, 0, 10, (width, height)) \n\n audioLength = MP3(audioFileName).info.length\n numSeconds = math.ceil(audioLength) * 10\n # print(audioLength)\n for i in range(numSeconds):\n # print(i)\n video.write(frame) \n \n # Deallocating memories taken for window creation \n cv2.destroyAllWindows() \n video.release() # releasing the video generated \n # add audio\n cmd = \"ffmpeg -y -i \" + videoFileName + \" -i \" + audioFileName + \" -codec copy \" + videoFileName\n os.system(cmd)\n\n\ndef createClips(data, directoryName, subId): \n # make sure directory exists\n if not os.path.exists(directoryName):\n os.makedirs(directoryName)\n \n currDir = os.getcwd()\n\n # for submission\n imgFileName = \"./\" + directoryName + \"/submission\" + \".jpg\"\n audioFileName = \"./\" + directoryName + \"/submission\" + \".mp3\"\n videoFileName = \"./\" + directoryName + \"/submission\" + \".avi\"\n createClip(imgFileName, audioFileName, videoFileName)\n\n concatFiles = \"file '\" + currDir + \"/\" + directoryName + \"/submission\" + \".avi\" + \"'\"\n # for comments\n com=data[\"commentsData\"]\n jobs = []\n for i in range(len(com)):\n if com[i][\"isChecked\"]:\n imgFileName = \"./\" + directoryName + \"/\" + str(i) + \".jpg\"\n audioFileName = \"./\" + directoryName + \"/\" + str(i) + \".mp3\"\n videoFileName = \"./\" + directoryName + \"/\" + str(i) + \".avi\"\n # createClip(imgFileName, audioFileName, videoFileName)\n concatFiles += (\"\\nfile '\" + currDir + \"/\" + directoryName + \"/\" + str(i) + \".avi\" + \"'\")\n p = multiprocessing.Process(target=createClip, args=(imgFileName, audioFileName, videoFileName))\n jobs.append(p)\n p.start()\n # make sure all the jobs finish before going on to the next task\n for job in jobs:\n job.join()\n \n # concatenate clips together\n toConcatFile = directoryName + \"/toConcat.txt\"\n f = open(toConcatFile, \"w\")\n f.write(concatFiles)\n f.close()\n finalName = \"./final_videos/\" + subId + \".avi\"\n concatCMD = \"ffmpeg -y -f concat -safe 0 -i \" + toConcatFile + \" -c copy \" + finalName\n # concatCMD = \"ffmpeg -y -f concat -safe 0 -i \" + toConcatFile + \" -c copy \" + finalName\n os.system(concatCMD)\n print(concatCMD)","sub_path":"WindowsMakeVideoFull/generateClipsMulti.py","file_name":"generateClipsMulti.py","file_ext":"py","file_size_in_byte":2654,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"136603294","text":"import time\nimport requests\nimport base64\nimport json\nimport pprint\nimport pandas as pd\nimport numpy as np\nimport datetime\n\napp_token = \"a7e64ebe-0998-3dcd-afa8-88b5594440c9\"\nconsumer_key = \"ebxARAhZKo2_4abI3vroPlkUOTEa\"\nconsumer_secret = \"TuefeH8yl8rhzjXnBg1spQD4qmsa\"\nstubhub_username = \"haotianyu1104@gmail.com\"\nstubhub_password = \"Dududai1104\"\ncombo = consumer_key + ':' + consumer_secret\nbasic_authorization_token = base64.b64encode(combo.encode('utf-8'))\nheaders = {\n 'Content-Type':'application/x-www-form-urlencoded',\n 'Authorization':'Basic '+basic_authorization_token.decode('utf-8'),}\nbody = {\n 'grant_type':'password',\n 'username':stubhub_username,\n 'password':stubhub_password,\n 'scope':'PRODUCTION'}\nurl = 'https://api.stubhub.com/login'\nr = requests.post(url, headers=headers, data=body)\ntoken_respoonse = r.json()\naccess_token = token_respoonse['access_token']\nuser_GUID = r.headers['X-StubHub-User-GUID']\ninventory_url = 'https://api.stubhub.com/search/inventory/v2'\n\nheaders['Authorization'] = 'Bearer ' + access_token\nheaders['Accept'] = 'application/json'\nheaders['Accept-Encoding'] = 'application/json'\n\n\neventid = '9742147'\nlisting_df=pd.DataFrame()\nfor i in np.arange(0,1000,10):\n data = {'eventid':eventid,'rows':1000,'pricemin':i,'pricemax':i+10}\n inventory = requests.get(inventory_url, headers=headers, params=data)\n inv = inventory.json()\n if 'listing' in inv :\n listing_df = listing_df.append(pd.DataFrame(inv['listing']))\n else:\n continue\nt=str(time.ctime())\nz=t.replace(':','')\nz=z.replace(' ','')\n \nlisting_df[z+'amount'] = listing_df.apply(lambda x: x['currentPrice']['amount'], axis=1)\n \n \nlisting_df.to_csv('tickets_listing.csv', index=False)\n \n \ninfo_url = 'https://api.stubhub.com/catalog/events/v2/' + eventid\ninfo = requests.get(info_url, headers=headers)\n \n \ninfo_dict = info.json()\nevent_date = datetime.datetime.strptime(info_dict['eventDateLocal'][:10], '%Y-%m-%d')\n \nevent_name = info_dict['title']\nevent_date = info_dict['eventDateLocal'][:10]\nvenue = info_dict['venue']['name']\n \n \n \nlisting_df['eventName'] = event_name\nlisting_df['eventDate'] = event_date\nlisting_df['venue'] = venue\n \n\n\nmy_col = ['currentPrice','deliveryMethodList', 'deliveryTypeList', 'dirtyTicketInd', 'faceValue',\n 'listingAttributeList', 'listingId','listingPrice','sectionId','sellerOwnInd','sellerSectionName','splitOption','splitVector','ticketSplit','zoneId','zoneName']\n \n \n \nlast_df=pd.read_csv(\"C:/project/stubhub scraping/NYL.csv\")\nlisting_df.drop(my_col,axis=1).to_csv(\"now.csv\", index=False)\nnow_df=pd.read_csv(\"C:/project/stubhub scraping/now.csv\")\n\nnew_df=pd.merge(last_df,now_df,how=\"outer\") \n\nnew_df.to_csv(\"NYL.csv\", index=False)\n","sub_path":"thao/NYL_local.py","file_name":"NYL_local.py","file_ext":"py","file_size_in_byte":2798,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"190314603","text":"import tensorflow as tf\nimport tflearn as tfl\n\n# TODO: Doesn't work properly\n\nclass VAE:\n\n def __init__(self, in_dim, z_dim, lr):\n self.in_dim = in_dim\n self.z_dim = z_dim\n self.lr = lr\n\n self.g = tf.Graph()\n with self.g.as_default():\n self.lr_ph = tf.placeholder(tf.float32)\n self.z_rnd_ph = tf.placeholder(tf.float32, shape=(None, self.z_dim))\n self._encoder()\n self.trn_recon = self._decoder(self.z, reuse=False)\n self.tst_recon = self._decoder(self.z_rnd_ph, reuse=True)\n self._objective()\n self._init_op = tf.global_variables_initializer()\n\n config = tf.ConfigProto(device_count={'GPU': 1})\n self.sess = tf.Session(graph=self.g, config=config)\n self.sess.run(self._init_op)\n\n\n def _encoder(self):\n self.X = tf.placeholder(tf.float32, [None] + self.in_dim, 'X')\n w_init = tfl.initializations.xavier()\n l1 = tfl.conv_2d(self.X, 32, (3,3), (1,1), 'same', activation='tanh', weights_init=w_init)\n l1 = tfl.max_pool_2d(l1, [2, 2], strides=2)\n l2 = tfl.conv_2d(l1, 32, (3, 3), (1, 1), 'same', activation='tanh', weights_init=w_init)\n l2 = tfl.max_pool_2d(l2, [2, 2], strides=2)\n l3 = tfl.conv_2d(l2, 32, (3, 3), (1, 1), 'same', activation='tanh', weights_init=w_init)\n l3 = tfl.max_pool_2d(l3, [2, 2], strides=2)\n flattened = tfl.flatten(l3, 'flattened')\n\n self.mu = tfl.fully_connected(flattened, self.z_dim, weights_init=w_init)\n self.log_sig_sq = tfl.fully_connected(flattened, self.z_dim, weights_init=w_init)\n\n eps = tf.random_normal(tf.shape(self.log_sig_sq), mean=0, stddev=1, name='epsilon')\n self.z = self.mu + tf.multiply(tf.exp(0.5 * self.log_sig_sq), eps)\n\n\n def _decoder(self, z, reuse=False):\n flat_conv = tf.reshape(z, (-1, 1, 1, self.z_dim))\n with tf.variable_scope('decoder', reuse=reuse):\n w_init = tf.contrib.layers.xavier_initializer()\n deconv_1 = tf.layers.conv2d_transpose(inputs=flat_conv,\n filters=128,\n kernel_size=[7,7],\n strides=(1, 1),\n padding='valid',\n activation=tf.nn.relu,\n kernel_initializer=w_init)\n\n deconv_2 = tf.layers.conv2d_transpose(inputs=deconv_1,\n filters=32,\n kernel_size=[3, 3],\n strides=(2, 2),\n padding='same',\n activation=tf.nn.relu,\n kernel_initializer=w_init)\n\n deconv_3 = tf.layers.conv2d_transpose(inputs=deconv_2,\n filters=1,\n kernel_size=[3, 3],\n strides=(2, 2),\n padding='same',\n activation=tf.nn.relu,\n kernel_initializer=w_init)\n\n return deconv_3\n\n\n def _objective(self):\n self.latent_loss = -.5 * tf.reduce_sum(1 + self.log_sig_sq\n - tf.square(self.mu)\n - tf.exp(self.log_sig_sq), 1)\n\n self.reconstruction_loss = tfl.mean_square(self.trn_recon, self.X)\n total_loss = tf.reduce_mean(self.reconstruction_loss + self.latent_loss)\n self.optim = tf.train.AdamOptimizer(self.lr).minimize(total_loss)\n\n\n def train(self, X):\n fetches = [self.optim, self.reconstruction_loss, self.latent_loss]\n _, mse, kl_loss = self.sess.run(fetches, feed_dict={self.X : X})\n\n return mse, kl_loss\n\n\n def embed(self, X):\n return self.sess.run(self.z, feed_dict={self.X : X})\n\n\n def reconstruct(self, X):\n return self.sess.run(self.trn_recon, feed_dict={self.X : X})\n\n\n def sample(self, z):\n return self.sess.run(self.tst_recon,\n feed_dict={self.z_rnd_ph : z})","sub_path":"Machinelearning/VAE/vae_network.py","file_name":"vae_network.py","file_ext":"py","file_size_in_byte":4469,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"415492148","text":"from __future__ import print_function\nimport httplib2\nimport os\n\nfrom apiclient import discovery\nfrom oauth2client import client\nfrom oauth2client import tools\nfrom oauth2client.file import Storage\n\n# try:\n# import argparse\n# flags = argparse.ArgumentParser(parents=[tools.argparser]).parse_args()\n# except ImportError:\n# flags = None\n\n# If modifying these scopes, delete your previously saved credentials\n# at ~/.credentials/sheets.googleapis.com-python-quickstart.json\nSCOPES = 'https://www.googleapis.com/auth/spreadsheets.readonly'\nCLIENT_SECRET_FILE = 'client_secret.json'\nAPPLICATION_NAME = 'Google Sheets API Python Quickstart'\nCOHORTS = ['Jan 2017', 'Feb 2017', 'March 2017', 'April 2017', 'May 2017',\n 'June 2017', 'June2 2017', 'July 2017', 'August 2017', 'August2 2017']\nresults = []\n\n\ndef get_credentials():\n \"\"\"Gets valid user credentials from storage.\n\n If nothing has been stored, or if the stored credentials are invalid,\n the OAuth2 flow is completed to obtain the new credentials.\n\n Returns:\n Credentials, the obtained credential.\n \"\"\"\n home_dir = os.path.expanduser('~')\n credential_dir = os.path.join(home_dir, '.credentials')\n if not os.path.exists(credential_dir):\n os.makedirs(credential_dir)\n credential_path = os.path.join(credential_dir,\n 'sheets.googleapis.com-python-quickstart.json')\n\n store = Storage(credential_path)\n credentials = store.get()\n # if not credentials or credentials.invalid:\n # flow = client.flow_from_clientsecrets(CLIENT_SECRET_FILE, SCOPES)\n # flow.user_agent = APPLICATION_NAME\n # if not flags:\n # credentials = tools.run_flow(flow, store, flags)\n # else: # Needed only for compatibility with Python 2.6\n # credentials = tools.run(flow, store)\n # print('Storing credentials to ' + credential_path)\n return credentials\n\ncredentials = get_credentials()\nhttp = credentials.authorize(httplib2.Http())\ndiscoveryUrl = ('https://sheets.googleapis.com/$discovery/rest?'\n 'version=v4')\nservice = discovery.build('sheets', 'v4', http=http,\n discoveryServiceUrl=discoveryUrl)\n\nspreadsheetId = '1RRBsu9-3Pyb_0IepSQ0tfsUvAuHnchY7e867Tsj92hQ'\nfor cohort in COHORTS:\n cohort_row = []\n rangeName = cohort + '!A5:C'\n cohort_no = cohort + '!A4'\n result = service.spreadsheets().values().get(\n spreadsheetId=spreadsheetId, range=rangeName).execute()\n result2 = service.spreadsheets().values().get(\n spreadsheetId=spreadsheetId, range=cohort_no).execute()\n values = result.get('values')\n values.extend(result2.get('values'))\n\n if not values:\n print('No data found.')\n else:\n for row in values:\n cohort_row.append(row)\n results.append(cohort_row)\n cohort_row = []\n\ndef get_emails():\n emails = []\n for cohort in results:\n cohort_no = cohort[-1]\n for fellow in cohort:\n if fellow[0] != cohort_no[0]:\n emails.append([fellow[0], cohort_no[0]])\n\n return emails\n\ndef get_interests():\n interests = []\n for cohort in results:\n for fellow in cohort[:-1]:\n if fellow[1]:\n interests.append(fellow[1])\n else:\n interests.append(\"Nill\")\n return interests\n\ndef get_hobbies():\n hobbies = []\n for cohort in results:\n for fellow in cohort[:-1]:\n if fellow[2]:\n hobbies.append(fellow[2])\n else:\n hobbies.append(\"Nill\")\n return hobbies\n","sub_path":"app/google_api.py","file_name":"google_api.py","file_ext":"py","file_size_in_byte":3610,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"132363025","text":"import boto3\n\n#Change The Below 4 Variables\n#The Script Will Find The Running Server And Back It Up To An AMI Image\n#This Script Will First Delete Any AMI Backups That Match The AMIName Selected So They Can Be Overwritten\n#This Can Be Used In A Lambda Function For Backing Up An EC2 E.g. Runnng This Every Hour Using CloudWatch\n#This Only Works Where There's One Running Server In The Region; The Script Can Easily Be Adjusted To Work With Multiple Servers\n\nSecretAccessKey = \"\" #Obtain this from IAM users\nAccessKeyID = \"\" #Obtain this from IAM users\nRegionName = \"us-east-1\" #Region name with the ec2 instance to back up\nAMIName = \"\" #AMI name for the generated backup\n\nEC = boto3.client( 'ec2', \n aws_access_key_id= AccessKeyID,\n aws_secret_access_key= SecretAccessKey,\n region_name= RegionName)\n\nfor i in EC.describe_instances()[\"Reservations\"]:\n if i[\"Instances\"][0][\"State\"][\"Name\"] == \"running\":\n \n \n ec2 = boto3.client( 'ec2', \n aws_access_key_id= AccessKeyID,\n aws_secret_access_key= SecretAccessKey,\n region_name= RegionName)\n\n ImageNames = ec2.describe_images(Owners=['self'])\n \n for i in ImageNames[\"Images\"]:\n if i[\"Name\"] == AMIName:\n ImageId = i[\"ImageId\"]\n \n ec2.deregister_image(ImageId = ImageId, DryRun = False)\n \n session = boto3.Session(\n aws_access_key_id= AccessKeyID,\n aws_secret_access_key= SecretAccessKey,\n region_name= RegionName\n )\n \n Ec2Session = session.client(\"ec2\")\n \n for i in Ec2Session.describe_instances()[\"Reservations\"]:\n if i[\"Instances\"][0][\"State\"][\"Name\"] == \"running\":\n InstanceId = i[\"Instances\"][0][\"InstanceId\"]\n \n ec2 = boto3.resource(\n 'ec2',\n aws_access_key_id= AccessKeyID,\n aws_secret_access_key= SecretAccessKey,\n region_name= RegionName)\n \n instance = ec2.Instance(InstanceId)\n for i in instance.volumes.all():\n VolumeID = i\n DevName = instance.block_device_mappings[0][\"DeviceName\"]\n \n instance.block_device_mappings\n instance.create_image(\n InstanceId = InstanceId,\n Name = AMIName,\n Description = \"Backup\",\n NoReboot = True,\n BlockDeviceMappings = [{\"DeviceName\" : DevName,\n \"Ebs\" : {\n \"DeleteOnTermination\" : False\n }}],\n DryRun = False)","sub_path":"AutoBackupEC2.py","file_name":"AutoBackupEC2.py","file_ext":"py","file_size_in_byte":2692,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"366507243","text":"\"\"\"\n 1. splitting the Amazon data into train and test sets\n 2. extracting bigrams from the split datasets\n\"\"\"\nimport xml.etree.ElementTree as ET\nimport random\nimport string\nimport numpy as np\nfrom nltk.tokenize import RegexpTokenizer\nfrom sklearn.feature_extraction.text import CountVectorizer\nimport pickle\nimport os\n\n\ndef XML2arrayRAW(neg_path, pos_path):\n \"\"\"\n the raw data is in pseudo XML format\n ---------\n the following code extracts data from the XML framework accordingly\n \"\"\"\n reviews = []\n negReviews = []\n posReviews = []\n\n neg_tree = ET.parse(neg_path)\n neg_root = neg_tree.getroot()\n for rev in neg_root.iter('review'):\n reviews.append(rev.text)\n negReviews.append(rev.text)\n\n pos_tree = ET.parse(pos_path)\n pos_root = pos_tree.getroot()\n\n for rev in pos_root.iter('review'):\n reviews.append(rev.text)\n posReviews.append(rev.text)\n\n #\n return clean_data(reviews), clean_data(negReviews), clean_data(posReviews)\n\n\ndef split_data_balanced(reviews, dataSize, testSize):\n \"\"\"\n passed in from `extract_and_split` dataSize=1000, testSize=200\n \"\"\"\n test_data_neg = random.sample(range(0, dataSize), testSize)\n \"\"\"\n . randomly choose 200 data from (0, 1000) negatives\n . randomly choose 200 data from (1000, 2000) postives\n . the rest 800 + 800 will be used as training data\n \"\"\"\n test_data_pos = random.sample(range(dataSize, 2*dataSize), testSize)\n random_array = np.concatenate((test_data_neg, test_data_pos))\n train = []\n test = []\n test_label = []\n train_label = []\n for i in range(0, 2*dataSize): # dataSize*2 == 2000\n if i in random_array:\n test.append(reviews[i])\n label = 0 if i < dataSize else 1\n test_label.append(label)\n else:\n train.append(reviews[i])\n label = 0 if i < dataSize else 1\n train_label.append(label)\n\n \"\"\" train=1600, test=400 \"\"\"\n return train, train_label, test, test_label\n\n\ndef extract_and_split(neg_path, pos_path):\n reviews, n, p = XML2arrayRAW(neg_path, pos_path)\n train, train_label, test, test_label = split_data_balanced(reviews, 1000, 200)\n return train, train_label, test, test_label\n\n\ndef clean_data(raw_docs):\n \"\"\"\n a data cleaning function, which does:\n 1. remove numbers\n 2. tokenize\n 3. remove punctuation\n 4. remove stopwords (optional)\n ---------\n input: a list of strings, each string is a document\n \"\"\"\n # 1. remove numbers\n docs = []\n for x in raw_docs:\n s = []\n for char in x:\n if not char.isdigit():\n s.append(char)\n s = ''.join(s)\n docs.append(s)\n\n # 2. remove punct, tokenize\n tokenizer = RegexpTokenizer(r'\\w+')\n preprocessed_docs = []\n for doc in docs:\n translator = str.maketrans('', '', string.punctuation)\n doc = doc.translate(translator).lower()\n tokens = tokenizer.tokenize(doc)\n stop_words = [] # TODO:\n filtered_words = [w for w in tokens if w not in stop_words]\n preprocessed_docs.append(' '.join(filtered_words))\n\n # a list of cleaned docs\n return preprocessed_docs\n\n\ndef load_data(source, target):\n \"\"\"\n load raw data from the given paths\n create the directory for train/test split datsets if the director was\n not there; if the directory exists, read the data from specified directory\n \"\"\"\n filename = source + \"_to_\" + target + \"/split/\"\n if not os.path.exists(os.path.dirname(filename)):\n source_train, source_train_label, source_test, source_test_label = extract_and_split(\"data/\"+source+\"/negative.parsed\", \"data/\"+source+\"/positive.parsed\")\n os.makedirs(os.path.dirname(filename))\n with open(source + \"_to_\" + target + \"/split/train\", 'wb') as f:\n pickle.dump(source_train, f)\n with open(source + \"_to_\" + target + \"/split/test\", 'wb') as f:\n pickle.dump(source_test, f)\n with open(source + \"_to_\" + target + \"/split/train_label\", 'wb') as f:\n pickle.dump(source_train_label, f)\n with open(source + \"_to_\" + target + \"/split/test_label\", 'wb') as f:\n pickle.dump(source_test_label, f)\n\n else:\n with open(source + \"_to_\" + target + \"/split/train\", 'rb') as f:\n source_train = pickle.load(f)\n with open(source + \"_to_\" + target + \"/split/test\", 'rb') as f:\n source_test = pickle.load(f)\n with open(source + \"_to_\" + target + \"/split/train_label\", 'rb') as f:\n source_train_label = pickle.load(f)\n with open(source + \"_to_\" + target + \"/split/test_label\", 'rb') as f:\n source_test_label = pickle.load(f)\n #\n return source_train, source_train_label, source_test, source_test_label\n\n\ndef bigram_feature_mtx(source, target):\n \"\"\"\n extracting unigrams & bigrams from raw data.\n ---------\n return:\n . source_train_bigram: bigram matrix of labelled source training data\n . source_mix_bigram: bigram matrix of ALL source training data\n . target_mix_bigram: bigram matrix of UNLABELLED target training data\n . all_mix_bigram: bigram matrix of ALL data from above\n ---------\n also return:\n . all corresponding vectorizers from above\n \"\"\"\n source_train, source_train_label, source_test, source_test_label = load_data(source, target)\n _, source_unlabel, target_unlabel = XML2arrayRAW(\"data/\"+source+\"/\"+source+\"UN.txt\",\"data/\"+target+\"/\"+target+\"UN.txt\")\n\n \"\"\" otherwise original unlabeled too big and unbalanced \"\"\"\n source_unlabel = list(np.random.choice(source_unlabel, 4000))\n target_unlabel = list(np.random.choice(target_unlabel, 5600))\n\n source_mix = source_train + source_unlabel\n target_mix = target_unlabel\n all_mix = source_mix + target_mix\n\n filename = source + \"_to_\" + target + \"/mix/\"\n if not os.path.exists(os.path.dirname(filename)):\n os.makedirs(os.path.dirname(filename))\n with open(source + \"_to_\" + target + \"/mix/source_mix\", 'wb') as f:\n pickle.dump(source_mix, f)\n with open(source + \"_to_\" + target + \"/mix/target_mix\", 'wb') as f:\n pickle.dump(target_mix, f)\n with open(source + \"_to_\" + target + \"/mix/all_mix\", 'wb') as f:\n pickle.dump(all_mix, f)\n\n else:\n with open(source + \"_to_\" + target + \"/mix/source_mix\", 'rb') as f:\n source_mix = pickle.load(f)\n with open(source + \"_to_\" + target + \"/mix/target_mix\", 'rb') as f:\n target_mix = pickle.load(f)\n with open(source + \"_to_\" + target + \"/mix/all_mix\", 'rb') as f:\n all_mix = pickle.load(f)\n\n \"\"\" all parameters are kept the same \"\"\"\n # source train bigram mtx\n vectorizer_source_train = CountVectorizer(ngram_range=(1, 2), token_pattern=r'\\b\\w+\\b', min_df=5, binary=True)\n source_train_bigram = vectorizer_source_train.fit_transform(source_train).toarray()\n\n # source mix bigram mtx\n vectorizer_source_mix = CountVectorizer(ngram_range=(1, 2), token_pattern=r'\\b\\w+\\b', min_df=5, binary=True)\n source_mix_bigram = vectorizer_source_mix.fit_transform(source_mix).toarray()\n\n # target mix bigram mtx\n vectorizer_target_mix = CountVectorizer(ngram_range=(1, 2), token_pattern=r'\\b\\w+\\b', min_df=5, binary=True)\n target_mix_bigram = vectorizer_target_mix.fit_transform(target_mix).toarray()\n\n # all mix bigram mtx\n vectorizer_all_mix = CountVectorizer(ngram_range=(1, 2), token_pattern=r'\\b\\w+\\b', min_df=5, binary=True)\n all_mix_bigram = vectorizer_all_mix.fit_transform(all_mix).toarray()\n\n print('source_train_bigram.shape =', source_train_bigram.shape)\n print('source_mix_bigram.shape =', source_mix_bigram.shape)\n print('target_mix_bigram.shape =', target_mix_bigram.shape)\n print('all_mix_bigram.shape =', all_mix_bigram.shape)\n\n #\n return source_train_bigram, source_mix_bigram, target_mix_bigram, all_mix_bigram, \\\n vectorizer_source_train, vectorizer_source_mix, vectorizer_target_mix, vectorizer_all_mix\n\n\nif __name__ == '__main__':\n \"\"\" specify the domains here: \"\"\"\n source = 'dvd'\n target = 'books'\n source_train_bigram, source_mix_bigram, target_mix_bigram, all_mix_bigram, \\\n vectorizer_source_train, vectorizer_source_mix, vectorizer_target_mix, vectorizer_all_mix = bigram_feature_mtx(source, target)\n","sub_path":"get_bigrams.py","file_name":"get_bigrams.py","file_ext":"py","file_size_in_byte":8514,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"424203739","text":"'''\nThis script calls the optimization routines in order to estimate the desired\ncoefficients.\n\nIn Part 1, we have no transfers so transfers = \"F\". In Part 2, we add transfers\nin order to indentify target specific characteristics, so transfers = \"T\"\n'''\n\n\n# Part 1: No Transfers\ntransfers = \"F\"\n\nB = np.array((300, -2)) # initial guess for Nelder-Mead\n\n# Nelder-Mead method\n\nresult_NM_NT = opt.minimize(score_func, B,\n args=(transfers), method='Nelder-Mead')\n\n\nbounds = [(0, 400), (-5, 5)] #Bounds for differential_evolution\n\n# differential_evolution method\n\nresult_DE_NT = differential_evolution(score_func, bounds, args=(transfers))\n\nprint(result_NM_NT)\n\nprint(result_DE_NT)\n\n# Part 2 : Transfers\ntransfers = \"T\" # So that our function use correct specification\n\n# bounds for the differential_evolution method\n\nbounds = [(-1000, 1000), (0, 1000), (-1000, 0), (-1000, 0)]\n\n#differential_evolution method\n\nresult_DE_T = differential_evolution(score_func, bounds, args=(transfers))\n\nprint(result_DE_T)\n\nend = time.time()\n\nprint(end - start)\n","sub_path":"Problem Sets/Problem Set 4_matrix/optimization.py","file_name":"optimization.py","file_ext":"py","file_size_in_byte":1070,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"527042927","text":"## Script (Python) \"mandato_valida_coligacao_pysc\"\n##bind container=container\n##bind context=context\n##bind namespace=\n##bind script=script\n##bind subpath=traverse_subpath\n##parameters=lst_num_legislatura=\"\" lst_cod_coligacao=\"\"\n##title=\n##\n'''Esse script tem como finalidade validar coligacao indicada na inclusao de mandato''' \n\nif (lst_cod_coligacao==\"\"):\n return true\n\nn=int(lst_num_legislatura.split('ª')[0])\ntry:\n nc=zsql.coligacao_obter_zsql(num_legislatura=n, cod_coligacao=lst_cod_coligacao)[0].nom_coligacao\n return true\nexcept:\n return false\n","sub_path":"branches/2.6/skins/sk_sapl/pysc/mandato_valida_coligacao_pysc.py","file_name":"mandato_valida_coligacao_pysc.py","file_ext":"py","file_size_in_byte":559,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"357740826","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport os\nimport logging\nimport sys\nimport re\n\nlog = logging.getLogger(__name__)\n\ndef _getFileList(dir,pattern):\n \"\"\"\n 输入:dir string 目录;pattern 文件后缀名。\n 输出:fileList list \n 用途:把目录中以pattern为后缀名的文件的绝对路径,写入到一个fileList\n \"\"\"\n fileList = []\n print (pattern)\n for root,dirs,files in os.walk(dir):\n for fileObj in files:\n print (fileObj)\n if fileObj.endswith(pattern):\n fileList.append(os.path.join(root, fileObj))\n return fileList\n \ndef allPath(dir, params, pattern=('xml','properties','json','conf')):\n \"\"\"\n 输入:dir string 目录;params dict,需要替换的参数字典;pattern tuple,需要替换的文件后缀名\n 输出:ret 替换的日志。\n 用途:用于把dir目录中以pattern里变量结尾的文件内容进行替换。\n \n \"\"\"\n fileList = _getFileList(dir,pattern)\n print (type(pattern))\n print (params)\n print (type(params))\n print (fileList)\n params = dict(params) if params else {}\n print (params)\n \"\"\"\n 合并params 中value也是字典的项。\n \"\"\"\n for key in params:\n if isinstance(params[key],dict):\n params = dict(params, **dict(params[key]))\n del params[key]\n ret = {}\n print (params)\n for file in fileList:\n print (file)\n with open(file, 'r') as f:\n flag = False\n for line in f.readlines():\n if not flag:\n for key in params:\n key_tmp = '@' + key + '@'\n print (key_tmp)\n if key_tmp in line:\n flag = True\n break\n else:\n ret1 = managed(file, params)\n print (ret1)\n ret[file] = ret1 \n break\n return ret\n\ndef managed(name,params):\n \"\"\"\n 输入:name string,绝对路径。\n params dict\n 输出:ret 记录本次操作的日志。\n 用途:寻找name中有关params的@key@记录,替换成对应的value。\n \"\"\"\n print (name)\n if not name:\n log.error('Please type a file name for managed')\n if not os.path.isabs(name):\n log.error('please type a full path of this file')\n ret = {\n 'name': name,\n 'comment': '',\n 'result': False,\n 'changes': {}\n }\n ret['changes']['data']=[]\n try:\n f = open(name, 'r+')\n all_lines = f.readlines()\n f.seek(0)\n f.truncate()\n for line in all_lines:\n for key in params:\n key_tmp = '@' + key + '@'\n if key_tmp in line:\n ret['changes']['data'].append('-'+line)\n line = line.replace(key_tmp, str(params[key]))\n ret['changes']['data'].append('+'+line)\n f.write(line)\n f.close()\n ret['result']=True\n except Exception as e:\n print (e)\n type(e)\n ret['comment'] = 'Please check error' + ''.join(e)\n return ret\n return ret\n\nif __name__ == '__main__':\n allPath(sys.argv[1],{'TOMCAT_SHUTDOWN_PORT':'8999','base_url':'1'})\n","sub_path":"salt/file_modify.py","file_name":"file_modify.py","file_ext":"py","file_size_in_byte":3316,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"422839942","text":"from bottle import *\r\n\r\nimport sympy as sym\r\nimport numpy as np\r\n\r\nimport factor2 as fact\r\nimport solver as solv\r\nimport riemann as riem\r\nimport integral as inte\r\nimport derivative as diff\r\nimport tangent as tan\r\nimport maxmin as mm\r\nimport intersection as inter\r\nimport arclen as arc\r\nimport graph_general as graph\r\n\r\n@route('/')\r\ndef main():\r\n return template('homePage.tpl')\r\n\r\n@route('/factor/')\r\ndef factor():\r\n title = 'Factor'\r\n answer = '0'\r\n number = request.query.number\r\n expression = request.query.expression\r\n mode = request.query.mode\r\n number = number.encode(\"utf8\")\r\n expression = expression.encode(\"utf8\")\r\n mode = mode.encode(\"utf8\")\r\n\r\n if number == \"\":\r\n number = '0'\r\n if expression == \"\":\r\n expression = '0'\r\n \r\n if mode == \"number\":\r\n if '.' in number:\r\n number = float(number)\r\n else:\r\n number = int(number)\r\n answer = fact.factorx(number)\r\n else:\r\n answer = fact.factorx(expression)\r\n return template('factorPage.tpl', title = title, answer = answer)\r\n\r\n@route('/solve/')\r\ndef solve():\r\n title = 'Solve'\r\n answer = '0'\r\n exp1 = request.query.exp1\r\n exp2 = request.query.exp2\r\n exp1 = exp1.encode('utf8')\r\n exp2 = exp2.encode('utf8')\r\n if exp1 == '':\r\n exp1 = 'x'\r\n if exp2 == '':\r\n exp2 = '0'\r\n answer = solv.solve(exp1,exp2)\r\n return template('solvePage.tpl', title = title, answer = answer)\r\n\r\n@route('/simplify/')\r\ndef simplify():\r\n x = sym.Symbol('x')\r\n y = sym.Symbol('y')\r\n z = sym.Symbol('z')\r\n title = 'Simplify'\r\n answer = '0'\r\n exp = request.query.expression\r\n exp = exp.encode('utf8')\r\n if exp == '':\r\n exp = '0'\r\n answer = sym.simplify(exp)\r\n return template('simplifyPage.tpl', title = title, answer = answer)\r\n\r\n@route('/arclen/')\r\ndef arclen():\r\n title = 'Arc Length'\r\n answer = '0'\r\n function = request.query.function\r\n start = request.query.start\r\n end = request.query.end\r\n\r\n function = function.encode('utf8')\r\n start = start.encode('utf8')\r\n end = end.encode('utf8')\r\n\r\n if function and start and end != '':\r\n answer = arc.arclen(function, start, end) \r\n else:\r\n answer = 'Please fill in all fields.'\r\n\r\n return template('arclenPage.tpl', title=title, answer=answer)\r\n\r\n@route('/derivative/')\r\ndef derivative():\r\n title = 'Derivative'\r\n answer = '0'\r\n function = request.query.function\r\n mode = request.query.mode\r\n xcoor = request.query.xcoor\r\n \r\n function = function.encode('utf8')\r\n mode = mode.encode('utf8')\r\n xcoor = xcoor.encode('utf8')\r\n\r\n if function and mode != '':\r\n if mode == 'general':\r\n answer = diff.diffgeneral(function)\r\n if mode == 'point' and xcoor != '':\r\n answer = diff.diffpt(function,xcoor)\r\n else:\r\n answer = 'Please fill in all fields.'\r\n\r\n return template('derivativePage.tpl', title = title, answer = answer)\r\n\r\n@route('/integral/')\r\ndef integral():\r\n title = 'Integration'\r\n answer = '0'\r\n function = request.query.function\r\n mode = request.query.mode\r\n start = request.query.start\r\n end = request.query.end\r\n \r\n function = function.encode('utf8')\r\n mode = mode.encode('utf8')\r\n start = start.encode('utf8')\r\n end = end.encode('utf8')\r\n \r\n if function and mode != '':\r\n if mode == 'indefinite':\r\n answer = inte.indefinite(function)\r\n if mode == 'definite' and start and end != '':\r\n answer = inte.definite(function,start,end)\r\n else:\r\n answer = 'Please fill in all fields.'\r\n\r\n return template('integralPage.tpl', title=title, answer=answer)\r\n\r\n@route('/maxmin/')\r\ndef maxmin():\r\n title = 'Maximum/Minimum'\r\n answer = '0'\r\n function = request.query.function\r\n start = request.query.start\r\n end = request.query.end\r\n \r\n function = function.encode('utf8')\r\n start = start.encode('utf8')\r\n end = end.encode('utf8')\r\n\r\n if function and start and end != '':\r\n answer = mm.max_min(function, start, end) \r\n else:\r\n answer = 'Please fill in all fields.'\r\n\r\n return template('maxminPage.tpl', title=title, answer=answer)\r\n\r\n@route('/riemann/')\r\ndef riemann():\r\n title = 'Riemann Sums'\r\n answer = '0'\r\n function = request.query.function\r\n start = request.query.start\r\n end = request.query.end\r\n rekt = request.query.rekt\r\n mode = request.query.mode\r\n function = function.encode('utf8')\r\n start = start.encode('utf8')\r\n end = end.encode('utf8')\r\n rekt = rekt.encode('utf8')\r\n mode = mode.encode('utf8')\r\n f = lambda x: eval(function)\r\n\r\n if function and start and end and rekt and mode != '':\r\n if mode == 'trapezoid':\r\n answer = riem.trapezoid(start, end, rekt, f)\r\n else:\r\n answer = riem.riemann(start, end, rekt, mode, f)\r\n else:\r\n answer = 'Please fill in all fields.'\r\n\r\n return template('riemannPage.tpl', title = title, answer = answer)\r\n\r\n@route('/tangent/')\r\ndef tangent():\r\n title = 'Tangent Line'\r\n answer = '0'\r\n function = request.query.function\r\n xcoor = request.query.xcoor\r\n \r\n function = function.encode('utf8')\r\n xcoor = xcoor.encode('utf8')\r\n\r\n if function and xcoor != '':\r\n answer = tan.tangentLine(function, xcoor) \r\n else:\r\n answer = 'Please fill in all fields.'\r\n\r\n return template('tangentPage.tpl', title = title, answer = answer)\r\n\r\n@route('/2d/')\r\ndef twod():\r\n title = '2D Graphing'\r\n mode = request.query.function\r\n function = request.query.function\r\n\r\n mode = mode.encode('utf8')\r\n function = function.encode('utf8')\r\n\r\n if mode == 'graph':\r\n if function != '':\r\n answer = 'Graphed'\r\n graph.graph_general(function, -50, 50, name = '2d.png')\r\n else:\r\n answer = 'Please fill in all fields.' \r\n else:\r\n answer = 'Cleared'\r\n \r\n return template('2dPage.tpl', title = title, answer = answer)\r\n\r\n@route('/holes/')\r\ndef holes():\r\n title = 'Discontinuities'\r\n answer = '0'\r\n expression = request.query.expression\r\n start = request.query.start\r\n end = request.query.end\r\n\r\n expression = expression.encode('utf8')\r\n start = start.encode('utf8')\r\n end = end.encode('utf8')\r\n\r\n if expression and start and end != '':\r\n answer = graph.find_holes(expression, start, end) \r\n else:\r\n answer = 'Please fill in all fields.'\r\n\r\n return template('holesPage.tpl', title=title, answer=answer)\r\n\r\n@route('/intersection/')\r\ndef intersection():\r\n title = 'Intersection'\r\n answer = '0'\r\n function1 = request.query.function1\r\n function2 = request.query.function2\r\n \r\n function1 = function1.encode('utf8')\r\n function2 = function2.encode('utf8')\r\n\r\n if function1 and function2 != '':\r\n answer = inter.intersection(function1, function2) \r\n else:\r\n answer = 'Please fill in all fields.'\r\n\r\n return template('intersectionPage.tpl', title=title, answer=answer)\r\n \r\n@route('/static/')\r\ndef server_static(filename):\r\n return static_file(filename, root = 'C:/Users/Blain/Documents/CSE-Software-Design-Project-master/website')\r\n\r\nrun(host='localhost', port=8080, debug=True, reloader=True)\r\n#browser url http://localhost:8080/\r\n","sub_path":"website/finished programs/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":7387,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"605744004","text":"import os\nbasedir = os.path.abspath(os.path.dirname(__file__))\n\nif os.environ.get('DATABASE_URL') is None:\n SQLALCHEMY_DATABASE_URI = 'sqlite:///' + os.path.join(basedir, 'app.db')\nelse:\n SQLALCHEMY_DATABASE_URI = os.environ['DATABASE_URL']\nSQLALCHEMY_MIGRATE_REPO = os.path.join(basedir, 'db_repository')\n\nDEBUG = False\nSQLALCHEMY_ECHO = False\nSQLALCHEMY_TRACK_MODIFICATIONS = True\n\n# Constant to set interval of requests:\nREQUEST_INTERVAL = 10\n\n# Time in seconds while data is valuable:\nEXPIRATION_INTERVAL = 1800\n","sub_path":"config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":522,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"479986835","text":"import torch\n\ndtype = torch.float\ndevice = torch.device(\"cpu\")\n# device = torch.device(\"cuda:0\") # Uncomment this to run on GPU\n\n# N:batcH size(样本数量)\n# D_in:输入层神经元数量(特征维数)\n# H:隐藏层神经元数量\n# D_out:输出层神经元数量\nN, D_in, H, D_out = 64, 1000, 100, 10\n\n'''requires_grad=False/True表示不需要/需要计算梯度'''\n\n# 输入特征矩阵\nx = torch.randn(N, D_in, device=device, dtype=dtype)\n# 输出结果矩阵\ny = torch.randn(N, D_out, device=device, dtype=dtype)\n\n# 第0层到第1层的权重矩阵\nw1 = torch.randn(D_in, H, device=device, dtype=dtype, requires_grad=True)\n# 第1层到第2层的权重矩阵\nw2 = torch.randn(H, D_out, device=device, dtype=dtype, requires_grad=True)\n\n# 学习率\nlearning_rate = 1e-6\nfor t in range(500):\n '''前向计算,不需要保留中间值'''\n # 输出层的输出\n y_pred = x.mm(w1).clamp(min=0).mm(w2)\n\n '''平方误差损失函数'''\n loss = (y_pred - y).pow(2).sum()\n if t % 100 == 99:\n print(t, loss.item())\n\n '''反向传播计算损失关于权重的梯度'''\n loss.backward()\n\n '''更新权重'''\n with torch.no_grad():\n w1 -= learning_rate * w1.grad\n w2 -= learning_rate * w2.grad\n\n # 更新权重后将梯度置零\n w1.grad.zero_()\n w2.grad.zero_()","sub_path":"深度学习/Pytorch示例/code/3.py","file_name":"3.py","file_ext":"py","file_size_in_byte":1337,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"588907667","text":"from collections import deque\r\n\r\nH,W=map(int,input().split())\r\nc=[]\r\nfor i in range(H):\r\n ci=input()\r\n c.append(ci)\r\n\r\nreached=[[-1 for i in range(W)] for j in range(H)]\r\nqueue=deque()\r\n\r\nfor j in range(H):\r\n for i in range(W):\r\n if c[j][i]==\"s\":\r\n sy=j\r\n sx=i\r\n elif c[j][i]==\"g\":\r\n gy=j\r\n gx=i\r\n\r\nqueue.append([sy,sx])\r\nreached[sy][sx]=0\r\ndx=[1,-1,0,0]\r\ndy=[0,0,1,-1]\r\nwhile(queue):\r\n p=queue.pop()\r\n for i in range(4):\r\n y=p[0]+dy[i]\r\n x=p[1]+dx[i]\r\n if y==gy and x==gx:\r\n reached[y][x]=reached[p[0]][p[1]]\r\n queue=[]\r\n break\r\n if x<0 or x>=W or y<0 or y>=H:\r\n continue\r\n if not(reached[y][x]==-1):\r\n continue\r\n \r\n if c[y][x]==\"#\":\r\n if reached[p[0]][p[1]]==2:\r\n continue\r\n queue.appendleft([y,x])\r\n reached[y][x]=reached[p[0]][p[1]]+1\r\n else:\r\n queue.append([y,x])\r\n reached[y][x]=reached[p[0]][p[1]]\r\n\r\n\r\nif reached[gy][gx]==-1:\r\n print(\"NO\")\r\nelse:\r\n print(\"YES\")","sub_path":"Source Codes/AtCoder/arc005/C/4498231.py","file_name":"4498231.py","file_ext":"py","file_size_in_byte":1134,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"210448996","text":"# uncompyle6 version 3.7.4\n# Python bytecode 3.6 (3379)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: build/bdist.linux-x86_64/egg/test/bibliopixel/project/types/ledtype_test.py\n# Compiled at: 2019-08-11 12:22:47\n# Size of source mod 2**32: 439 bytes\nfrom bibliopixel.drivers.ledtype import LEDTYPE\nfrom .base import TypesBaseTest\n\nclass LEDTYPETypesTest(TypesBaseTest):\n\n def test_some(self):\n self.make('ledtype', 'LPD8806')\n self.make('ledtype', 'GENERIC')\n self.make('ledtype', LEDTYPE.NEOPIXEL)\n with self.assertRaises(ValueError):\n self.make('ledtype', 2)\n with self.assertRaises(KeyError):\n self.make('ledtype', 'NONE')","sub_path":"pycfiles/BiblioPixel-3.4.45-py3.6/ledtype_test.cpython-36.py","file_name":"ledtype_test.cpython-36.py","file_ext":"py","file_size_in_byte":742,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"354702022","text":"import io,sys\nimport sys\nsys.stdout=io.TextIOWrapper(sys.stdout.buffer,encoding='utf8')\n\nimport pandas as pd\nimport numpy as np\n\nnames=['CountryId', 'CountryName', 'CountryEname','ContinentId']\n# dtype={'CountryId':np.int64,'CountryName':object,'CountryEname':object,'ContinentId':np.int32}\n# df=pd.read_csv(fsrc,encoding='utf_8_sig',sep='\\t',na_fvalues=['NULL'],na_values=['NULL'],keep_default_na=False,names=names,dtype=dtype,header=0)\n\ndf=pd.read_csv(fsrc,encoding='utf_8_sig',sep='\\t',na_values=['NULL'],keep_default_na=False, names=names,header=0)\n\n# 查看类型\nprint(df.dtypes)\nprint(df.head())\nprint(df.describe())\nprint(df[df.CountryId==171])\nprint(df.count())\n\n# 查看唯一值\nprint(df['AreaName'].unique())\ndf=df.drop('AreaName',axis=1)\n\n# 填充缺失值\ndf['ContinentId'] = df['ContinentId'].fillna(0)\n# 转化类型\ndf[['ContinentId']] = df[['ContinentId']].astype(np.uint8)\n\ndf[['CityId']] = df[['CityId']].astype(np.uint32)\n\ndf[9:11]\ndf[df['CityId']=='9766']\n\nfrom sqlalchemy import create_engine\n# engine = create_engine('sqlite:///:memory:')\nengine = create_engine('sqlite:///dim.db')\n\nwith engine.connect() as conn, conn.begin():\n df.to_sql('country', engine,index=False)\n\n\na=[1,2,3,4,5,6,7]\nb=['亚洲','欧洲','大洋洲','北美洲','南美洲','非洲','南极洲']\n\ndf_continue=pd.DataFrame({'ContinentId':a,'ContinentName':b})\n\nwith engine.connect() as conn, conn.begin():\n df_continue.to_sql('continent', engine,index=False)\n\n\n# pandas \n\n# dataframe描述\ndf.describe()\ndf.info()\ndf.index\ndf.columns\ndf.dtypes\n\n# null值\nisnull,notnull,dropna,fillna\n\n# 排序\norder,rank\n\n# 函数\napply\n\n# 列操作\ninsert,pop\n\n# 统计\ndf['CityID'].hist()\n\n# sql\n\n# pip install sqlalchemy\n# pip install SQLAlchemy-1.1.6.tar.gz\nfrom sqlalchemy import create_engine\n# engine = create_engine('sqlite:///:memory:')\nengine = create_engine('sqlite:///dim.db')\n\ndata2 = pd.read_sql_table('city', engine)\n\nwith engine.connect() as conn, conn.begin():\n data = pd.read_sql_table('city', conn)\n\nprint(data.head())\n\n\n# 通过这个engine对象可以直接execute 进行查询,例如 engine.execute(\"SELECT * FROM user\") 也可以通过 engine 获取连接在查询,例如 conn = engine.connect() 通过 conn.execute()方法进行查询。两者有什么差别呢?\n\n# 直接使用engine的execute执行sql的方式, 叫做connnectionless执行,\n# 借助 engine.connect()获取conn, 然后通过conn执行sql, 叫做connection执行\n# 主要差别在于是否使用transaction模式, 如果不涉及transaction, 两种方法效果是一样的. 官网推荐使用后者。\n\n\n","sub_path":"python/tests/test_pandas.py","file_name":"test_pandas.py","file_ext":"py","file_size_in_byte":2602,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"5573668","text":"import logging\r\nimport os\r\nimport sys\r\nimport warnings\r\nfrom urllib.parse import urlparse\r\n\r\nimport mlflow\r\nimport mlflow.sklearn\r\nimport numpy as np\r\nimport pandas as pd\r\nfrom sklearn.linear_model import ElasticNet\r\nfrom sklearn.metrics import mean_absolute_error, mean_squared_error, r2_score\r\nfrom sklearn.model_selection import train_test_split\r\n\r\nlogging.basicConfig(level=logging.WARN)\r\nlogger = logging.getLogger(__name__)\r\n\r\ndata = pd.read_csv(\"wine-quality.csv\")\r\n\r\n\r\ndef eval_metrics(actual, pred):\r\n rmse = np.sqrt(mean_squared_error(actual, pred))\r\n mae = mean_absolute_error(actual, pred)\r\n r2 = r2_score(actual, pred)\r\n return rmse, mae, r2\r\n\r\n\r\n# Split the data into training and test sets. (0.75, 0.25) split.\r\ntrain, test = train_test_split(data)\r\n\r\n# The predicted column is \"quality\" which is a scalar from [3, 9]\r\ntrain_x = train.drop([\"quality\"], axis=1)\r\ntest_x = test.drop([\"quality\"], axis=1)\r\ntrain_y = train[[\"quality\"]]\r\ntest_y = test[[\"quality\"]]\r\n\r\nalpha = float(sys.argv[1]) if len(sys.argv) > 1 else 0.5\r\nl1_ratio = float(sys.argv[2]) if len(sys.argv) > 2 else 0.5\r\n\r\nwith mlflow.start_run():\r\n lr = ElasticNet(alpha=alpha, l1_ratio=l1_ratio, random_state=42)\r\n lr.fit(train_x, train_y)\r\n\r\n predicted_qualities = lr.predict(test_x)\r\n\r\n (rmse, mae, r2) = eval_metrics(test_y, predicted_qualities)\r\n\r\n print(\"Elasticnet model (alpha=%f, l1_ratio=%f):\" % (alpha, l1_ratio))\r\n print(\" RMSE: %s\" % rmse)\r\n print(\" MAE: %s\" % mae)\r\n print(\" R2: %s\" % r2)\r\n\r\n mlflow.log_param(\"alpha\", alpha)\r\n mlflow.log_param(\"l1_ratio\", l1_ratio)\r\n mlflow.log_metric(\"rmse\", rmse)\r\n mlflow.log_metric(\"r2\", r2)\r\n mlflow.log_metric(\"mae\", mae)\r\n\r\n tracking_url_type_store = urlparse(mlflow.get_tracking_uri()).scheme\r\n\r\n if tracking_url_type_store != \"file\":\r\n mlflow.sklearn.log_model(lr, \"model\", registered_model_name=\"ElasticnetWineModel\")\r\n else:\r\n mlflow.sklearn.log_model(lr, \"model\")\r\n","sub_path":"ml_flow.py","file_name":"ml_flow.py","file_ext":"py","file_size_in_byte":1980,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"7284707","text":"'''\nQ-learning approach for different RL problems\nas part of the basic series on reinforcement learning @\nhttps://github.com/vmayoral/basic_reinforcement_learning\n \nInspired by https://gym.openai.com/evaluations/eval_kWknKOkPQ7izrixdhriurA\n \n @author: Victor Mayoral Vilches \n'''\nimport random\n\nclass QLearn:\n def __init__(self, actions, epsilon, alpha, gamma):\n self.q = {}\n self.epsilon = epsilon # exploration constant\n self.alpha = alpha # discount constant\n self.gamma = gamma # discount factor\n self.actions = actions\n\n def getQ(self, state, action):\n return self.q.get((state, action), 0.0)\n\n def learnQ(self, state, action, reward, value):\n '''\n Q-learning:\n Q(s, a) += alpha * (reward(s,a) + max(Q(s') - Q(s,a)) \n '''\n oldv = self.q.get((state, action), None)\n if oldv is None:\n self.q[(state, action)] = reward\n else:\n self.q[(state, action)] = oldv + self.alpha * (value - oldv)\n\n def chooseAction(self, state, return_q=False):\n q = [self.getQ(state, a) for a in self.actions]\n maxQ = max(q)\n\n if random.random() < self.epsilon:\n minQ = min(q); mag = max(abs(minQ), abs(maxQ))\n # add random values to all the actions, recalculate maxQ\n q = [q[i] + random.random() * mag - .5 * mag for i in range(len(self.actions))] \n maxQ = max(q)\n\n count = q.count(maxQ)\n # In case there're several state-action max values \n # we select a random one among them\n if count > 1:\n best = [i for i in range(len(self.actions)) if q[i] == maxQ]\n i = random.choice(best)\n else:\n i = q.index(maxQ)\n\n action = self.actions[i] \n if return_q: # if they want it, give it!\n return action, q\n return action\n\n def learn(self, state1, action1, reward, state2):\n maxqnew = max([self.getQ(state2, a) for a in self.actions])\n self.learnQ(state1, action1, reward, reward + self.gamma*maxqnew)\n","sub_path":"my_deepsoccer_training/src/qlearn.py","file_name":"qlearn.py","file_ext":"py","file_size_in_byte":2140,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"174986009","text":"from collections import OrderedDict\n\nfrom .thepiratebay import Finder\n\n_modules = {\n 'thepiratebay': Finder\n}\n\n\nclass FindManager(object):\n\n def __init__(self):\n self._searchers = {}\n for k, searcher_class in _modules.items():\n self._searchers[k] = searcher_class()\n\n def find(self, s, t):\n res = OrderedDict()\n for k, searcher in self._searchers.items():\n res[k] = searcher.perform(s, t)\n return res\n\nfind_manager = FindManager()\n","sub_path":"rasmus_mediaweb/findmedia/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":497,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"33814664","text":"from numpy import *\nfrom numpy import linalg as la\n\ndef loadExData2():\n return [[0, 0, 0, 0, 0, 4, 0, 0, 0, 0, 5],\n [0, 0, 0, 3, 0, 4, 0, 0, 0, 0, 3],\n [0, 0, 0, 0, 4, 0, 0, 1, 0, 4, 0],\n [3, 3, 4, 0, 0, 0, 0, 2, 2, 0, 0],\n [5, 4, 5, 0, 0, 0, 0, 5, 5, 0, 0],\n [0, 0, 0, 0, 5, 0, 1, 0, 0, 5, 0],\n [4, 3, 4, 0, 0, 0, 0, 5, 5, 0, 1],\n [0, 0, 0, 4, 0, 4, 0, 0, 0, 0, 4],\n [0, 0, 0, 2, 0, 2, 5, 0, 0, 1, 2],\n [0, 0, 0, 0, 5, 0, 0, 0, 0, 4, 0],\n [1, 0, 0, 0, 0, 0, 0, 1, 2, 0, 0]]\n\n# 利用不同的方法计算相似度\ndef eulidSim(inA, inB):\n return 1.0/(1.0+la.norm(inA - inB))#根据欧式距离计算相似度\n\ndef pearsSim(inA, inB):\n if len(inA)<3:\n return 1.0\n else:\n return 0.5+0.5*corrcoef(inA, inB, rowvar = 0)[0][1]\n\ndef cosSim(inA, inB):\n num = float(inA.T*inB) #向量inA和向量inB点乘,得cos分子\n denom = la.norm(inA)*la.norm(inB) #向量inA,inB各自范式相乘,得cos分母\n return 0.5+0.5*(num/denom) #从-1到+1归一化到[0,1]\n\n\ndef standEst(dataMat,user,simMeas,item):\n \"\"\"\n 计算在给定相似度计算方法的前提下,用户对物品的估计评分值\n :param dataMat: 数据矩阵\n :param user: 用户编号\n :param simMeas: 相似性度量方法\n :param item: 物品编号\n :return:\n \"\"\"\n #数据中行为用于,列为物品,n即为物品数目\n n=shape(dataMat)[1]\n simTotal=0.0\n ratSimTotal=0.0\n #用户的第j个物品\n for j in range(n):\n userRating=dataMat[user,j]\n if userRating==0:\n continue\n #寻找两个用户都评级的物品\n overLap=nonzero(logical_and(dataMat[:,item].A>0,dataMat[:,j].A>0))[0]\n\n if len(overLap)==0:\n similarity=0\n else:\n similarity=simMeas(dataMat[overLap,item],dataMat[overLap,j])\n\n simTotal+=similarity\n ratSimTotal+=simTotal*userRating\n\n if simTotal==0:\n return 0\n else:\n return ratSimTotal/simTotal\n\ndef recommend(dataMat,user,N=3,simMeas=cosSim,estMethod=standEst):\n \"\"\"\n 推荐引擎,会调用standEst()函数\n :param dataMat: 数据矩阵\n :param user: 用户编号\n :param N:前N个未评级物品预测评分值\n :param simMeas:\n :param estMethod:\n :return:\n \"\"\"\n #寻找未评级的物品,nonzeros()[1]返回参数的某些为0的列的编号,dataMat中用户对某个商品的评价为0的列\n #矩阵名.A:将矩阵转化为array数组类型\n #nonzeros(a):返回数组a中不为0的元素的下标\n unratedItems=nonzero(dataMat[user,:].A==0)[1]\n if len(unratedItems)==0:\n return 'you rated everything!'\n itemScores=[]\n for item in unratedItems:\n estimatedScore=estMethod(dataMat,user,simMeas,item)\n itemScores.append((item,estimatedScore))\n return sorted(itemScores,key=lambda jj:jj[1],reverse=True)[:N]\n\n#======================基于SVD的评分估计==========================\ndef SVDEst(dataMat, user, simMeas, item):\n n = shape(dataMat)[1]\n simTotal = 0.0\n ratSimTotal = 0.0\n U, Sigma, VT = la.svd(dataMat)\n Sig4 = mat(eye(4)*Sigma[:4]) #化为对角阵,或者用linalg.diag()函数可破\n xformedItems = dataMat.T*U[:,:4]*Sig4.I#构造转换后的物品\n for j in range(n):\n userRating = dataMat[user,j]\n if userRating == 0 or j == item:\n continue\n similarity = simMeas(xformedItems[item,:].T, xformedItems[j, :].T)\n print(\"the %d and %d similarity is: %f\" %(item,j,similarity))\n simTotal += similarity\n ratSimTotal += similarity*userRating\n if simTotal ==0 :\n return 0\n else:\n return ratSimTotal/simTotal\n\nmyMat = mat(loadExData2())\nprint(recommend(myMat, 1, estMethod = SVDEst))\nprint(recommend(myMat, 1, estMethod = SVDEst, simMeas = pearsSim))\n","sub_path":"My Code/chap 14/svdEst.py","file_name":"svdEst.py","file_ext":"py","file_size_in_byte":3936,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"6026737","text":"import sys\nimport unittest\nimport json\nfrom . import unittestsetup\nfrom .unittestsetup import environment as environment\nimport requests_mock\n\n\ntry:\n from nose_parameterized import parameterized\nexcept:\n print(\"*** Please install 'nose_parameterized' to run these tests ***\")\n exit(0)\n\nimport oandapyV20\nfrom oandapyV20 import API\nfrom oandapyV20.exceptions import V20Error\nimport oandapyV20.endpoints.accounts as accounts\nfrom oandapyV20.endpoints.accounts import responses\nfrom oandapyV20.endpoints.definitions import primitives\n\naccess_token = None\naccountID = None\naccount_cur = None\napi = None\n\n\nclass TestAccounts(unittest.TestCase):\n \"\"\"Tests regarding the accounts endpoints.\"\"\"\n\n def setUp(self):\n \"\"\"setup for all tests.\"\"\"\n global access_token\n global accountID\n global account_cur\n global api\n # self.maxDiff = None\n try:\n accountID, account_cur, access_token = unittestsetup.auth()\n setattr(sys.modules[\"oandapyV20.oandapyV20\"],\n \"TRADING_ENVIRONMENTS\",\n {\"practice\": {\n \"stream\": \"https://test.com\",\n \"api\": \"https://test.com\",\n }})\n api = API(environment=environment,\n access_token=access_token,\n headers={\"Content-Type\": \"application/json\"})\n api.api_url = 'https://test.com'\n except Exception as e:\n print(\"%s\" % e)\n exit(0)\n\n @requests_mock.Mocker()\n def test__get_accounts(self, mock_get):\n \"\"\"get the list of accounts.\"\"\"\n text = json.dumps(responses[\"_v3_accounts\"]['response'])\n mock_get.register_uri('GET',\n 'https://test.com/v3/accounts',\n text=text)\n r = accounts.AccountList()\n result = api.request(r)\n count = len(result['accounts'])\n self.assertGreaterEqual(count, 1)\n\n @requests_mock.Mocker()\n def test__get_account(self, mock_get):\n \"\"\"get the details of specified account.\"\"\"\n uri = 'https://test.com/v3/accounts/{}'.format(accountID)\n text = json.dumps(responses[\"_v3_account_by_accountID\"]['response'])\n mock_get.register_uri('GET', uri, text=text)\n r = accounts.AccountDetails(accountID=accountID)\n result = api.request(r)\n s_result = json.dumps(result)\n self.assertTrue(accountID in s_result)\n\n @parameterized.expand([\n (None, 200),\n (\"X\", 404, \"Account does not exist\"),\n ])\n @requests_mock.Mocker(kw='mock')\n def test__get_account_summary(self, accID, status_code,\n fail=None, **kwargs):\n \"\"\"get the summary of specified account.\"\"\"\n if not fail:\n uri = 'https://test.com/v3/accounts/{}/summary'.format(accountID)\n resp = responses[\"_v3_account_by_accountID_summary\"]['response']\n text = json.dumps(resp)\n else:\n uri = 'https://test.com/v3/accounts/{}/summary'.format(accID)\n text = fail\n\n kwargs['mock'].register_uri('GET',\n uri,\n text=text,\n status_code=status_code)\n\n if not accID:\n # hack to use the global accountID\n accID = accountID\n r = accounts.AccountSummary(accountID=accID)\n if fail:\n # The test should raise an exception with code == fail\n oErr = None\n s = None\n with self.assertRaises(V20Error) as oErr:\n result = api.request(r)\n\n self.assertTrue(fail in \"{}\".format(oErr.exception))\n else:\n result = api.request(r)\n self.assertTrue(result[\"account\"][\"id\"] == accountID and\n result[\"account\"][\"currency\"] == account_cur)\n\n @requests_mock.Mocker()\n def test__get_instruments(self, mock_get):\n \"\"\"get the instruments of specified account.\"\"\"\n uri = 'https://test.com/v3/accounts/{}/instruments'.format(accountID)\n respKey = \"_v3_account_by_accountID_instruments\"\n text = json.dumps(responses[respKey]['response'])\n mock_get.register_uri('GET', uri, text=text)\n r = accounts.AccountInstruments(accountID=accountID)\n result = api.request(r)\n dax = None\n for instr in result[\"instruments\"]:\n if instr[\"name\"] == \"DE30_EUR\":\n dax = instr\n break\n\n s_result = json.dumps(result)\n primDev = primitives.definitions[\"InstrumentType\"][dax[\"type\"]]\n self.assertTrue(\n dax is not None and\n dax[\"type\"] == \"CFD\" and\n primDev == \"Contract For Difference\" and\n \"EUR_AUD\" not in s_result)\n\n def test__get_instruments_data_exception(self):\n \"\"\"check for data parameter exception.\"\"\"\n with self.assertRaises(TypeError) as oErr:\n r = accounts.AccountInstruments(accountID=accountID, data={})\n\n self.assertEqual(\"__init__() got an unexpected keyword argument 'data'\", \"{}\".format(oErr.exception))\n\n def test__get_instruments_params_exception(self):\n \"\"\"check for params parameter exception.\"\"\"\n with self.assertRaises(TypeError) as oErr:\n r = accounts.AccountConfiguration(accountID=accountID, params={})\n\n self.assertEqual(\"__init__() got an unexpected keyword argument 'params'\", \"{}\".format(oErr.exception))\n\nif __name__ == \"__main__\":\n\n unittest.main()\n","sub_path":"tests/test_accounts.py","file_name":"test_accounts.py","file_ext":"py","file_size_in_byte":5653,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"279878236","text":"\"\"\"\r\n Merge two linked list\r\n head could be None as well for empty list\r\n Node is defined as\r\n \r\n class Node(object):\r\n \r\n def __init__(self, data=None, next_node=None):\r\n self.data = data\r\n self.next = next_node\r\n\r\n return back the head of the linked list in the below method.\r\n\"\"\"\r\n\r\ndef CompareLists(headA, headB):\r\n #It will carry out comparing as long as both are different than none\r\n while headA != None and headB != None:\r\n if headA.data != headB.data:\r\n return 0\r\n headA=headA.next\r\n headB=headB.next\r\n #In case a list was longer than the other\r\n if headA != None or headB!=None:\r\n return 0\r\n return 1\r\n ","sub_path":"Datastructures/Linked-lists/compare-two.py","file_name":"compare-two.py","file_ext":"py","file_size_in_byte":684,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"65260711","text":"#------------------#\n# Analytics Report #\n#------------------#\n\nfrom CaseSheet import *\nfrom DataStore import *\nfrom AutoEmail import *\nimport time\n\ngoogle_spreadsheet = 'Cross-Divisional Spreadsheet'\n\ndef report_generator():\n start_time = time.time()\n c = CaseSheet(google_spreadsheet)\n a = Analytics(c)\n new_table()\n insert_data(c)\n send_mail(c)\n end_time = time.time()\n time_elapsed = end_time - start_time\n print('Report Generated and Distributed in {0} seconds'.format(round(time_elapsed, 2)))\n\nif __name__ == \"__main__\":\n report_generator()\n","sub_path":"AnalyticsReport.py","file_name":"AnalyticsReport.py","file_ext":"py","file_size_in_byte":577,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"93007484","text":"# -*- coding: utf-8 -*-\n\nimport scrapy\nimport re\nfrom soufang.items import SoufangItem\n\nclass SoufangSpider(scrapy.Spider):\n name = \"soufang\"\n districts = {'chaoyang':'1', 'haidian':'0', 'fengtai':'6',\n 'dongcheng':'2', 'xicheng':3, 'shijingshan':7,\n 'changping':'12', 'daxing':585, 'tongzhou':10,\n 'shunyi':'11', 'fangshan':'8', 'miyun':'13',\n 'mentougou':'9', 'huairou':'14', 'yanqing':15,\n 'pinggu':'16', 'yanjiao':'987', 'beijingzhoubian':'11817'}\n start_urls = [\"http://esf.fang.com/housing/%s__%s_0_0_0_1_0_0\" % (y, n) for (x,y) in districts.items() for n in ['1','2']]\n\n def parse(self, response):\n next_a_text = response.xpath('//div[@class=\"fanye gray6\"]/a[last()-1]/text()').extract_first()\n if next_a_text == '下一页':\n next_a_href = response.xpath('//div[@class=\"fanye gray6\"]/a[last()-1]/@href').extract_first()\n next_url = \"http://esf.fang.com\" + next_a_href\n yield scrapy.Request(url=next_url, callback=self.parse)\n\n for a_href in response.xpath('//div[@class=\"list rel\"]/dl/dd/p[1]/a/@href'):\n url = a_href.extract()\n if url:\n yield scrapy.Request(url=url, callback=self.parse_little)\n\n def parse_little(self, response):\n item = SoufangItem()\n item[\"property\"]= response.xpath('//li/strong[text()=\"物业公司:\"]/../text()').extract_first()\n item[\"total_buildings\"] = response.xpath('//li/strong[text()=\"楼栋总数:\"]/../text()').extract_first()\n src = response.xpath('//div[@class=\"con_left\"]/div[2]/iframe/@src').extract_first()\n code = src.split('/')[5].split('?')[1].split('&')[0].split('=')[1]\n item[\"internal_id\"] = code\n request = scrapy.Request(url=(response.url + \"xiangqing/\"), callback=self.parse_info)\n request.meta['item'] = item\n return request\n\n def parse_info(self, response):\n item = response.meta['item']\n item[\"source\"] = \"soufang\"\n item[\"title\"] = response.xpath('//h1/a/text()').extract_first()[0:-3]\n item[\"district\"] = response.xpath('//dd/strong[text()=\"所属区域:\"]/../text()').extract_first().split(\" \")[0]\n item[\"address\"] = response.xpath('//dd/strong[text()=\"小区地址:\"]/../text()').extract_first()\n item[\"unit_price\"] = response.xpath('//dl/dt[text()=\"本月均价\"]/../dd/span/text()').extract_first()\n item[\"build_time\"] = response.xpath('//dd/strong[text()=\"竣工时间:\"]/../text()').extract_first()\n item[\"build_type\"] = response.xpath('//dd/strong[text()=\"建筑类别:\"]/../text()').extract_first()\n item[\"property_fee\"] = response.xpath('//dd/strong[text()=\"物 业 费:\"]/../text()').extract_first()\n item[\"developer\"] = response.xpath('//dd/strong[text()=\"开 发 商:\"]/../text()').extract_first()\n item[\"total_houses\"] = response.xpath('//dd/strong[text()=\"总 户 数:\"]/../text()').extract_first()\n item[\"plot_rate\"] = response.xpath('//dd/strong[text()=\"容 积 率:\"]/../text()').extract_first()\n item[\"green_rate\"] = response.xpath('//dd/strong[text()=\"绿 化 率:\"]/../text()').extract_first()\n item[\"parking_num\"] = response.xpath('//dt/strong[text()=\"停 车 位:\"]/../text()').extract_first()\n url = \"http://fangjia.fang.com/pinggu/ajax/ChartAjaxContainMax.aspx?dataType=proj&city=%%u5317%%u4EAC&KeyWord=%s&year=1\" % item[\"internal_id\"]\n request = scrapy.Request(url=url, callback=self.parse_price)\n request.meta['item'] = item\n return request\n\n def parse_price(self, response):\n item = response.meta['item']\n b = response.body\n s = str(b)\n data = s.split('&')[0].split(\"'\")[1]\n pattern = re.compile(',([0-9]+)]')\n match = pattern.findall(data)\n months = ['201512','201601','201602','201603','201604','201605','201606','201607','201608','201609','201610','201611']\n if match:\n length = len(match)\n prices = {}\n for x in range(0, length):\n prices[months[12-length+x]] = match[x]\n item[\"prices\"] = prices\n return item\n","sub_path":"soufang/spiders/soufang_spider.py","file_name":"soufang_spider.py","file_ext":"py","file_size_in_byte":4180,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"122953448","text":"import threading\r\nimport time\r\nimport cv2\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\nimport sys\r\n\r\ncap = cv2.VideoCapture(0)\r\nframe = []\r\n#frame = cv2.imread('tree.jpg') #test\r\nymax = 7500\r\nlock = threading.Lock()\r\nr = []\r\nb = []\r\ng = []\r\nl = []\r\nfor i in range(256):\r\n\r\n b.append(0)\r\n g.append(0)\r\n r.append(0)\r\n l.append(i)\r\n\r\ndef getpix():\r\n global r\r\n global b\r\n global g\r\n while True:\r\n\r\n time.sleep(1)\r\n with lock:\r\n for i in range(256):\r\n\r\n b[i] = 0\r\n g[i] = 0\r\n r[i] = 0\r\n for pixx in frame:\r\n for pix in pixx:\r\n b[pix[0]] += 1\r\n g[pix[1]] += 1\r\n r[pix[2]] += 1\r\n\r\n\r\ndef draww():\r\n fig = plt.figure()\r\n axes = plt.gca()\r\n axes.set_ylim([0,ymax])\r\n ax = fig.add_subplot(111)\r\n line1, = ax.plot(l,b,'b-')\r\n\r\n fig = plt.figure()\r\n axes = plt.gca()\r\n axes.set_ylim([0,ymax])\r\n ax = fig.add_subplot(111)\r\n line2, = ax.plot(l,g,'g-')\r\n\r\n fig = plt.figure()\r\n axes = plt.gca()\r\n axes.set_ylim([0,ymax])\r\n ax = fig.add_subplot(111)\r\n line3, = ax.plot(l,r,'r-')\r\n\r\n while True:\r\n with lock:\r\n line1.set_ydata(b)\r\n line2.set_ydata(g)\r\n line3.set_ydata(r)\r\n fig.canvas.draw()\r\n #plt.draw()\r\n plt.pause(0.01)\r\n\r\n'''\r\ndef draww():\r\n while True:\r\n plt.plot(l,b)\r\n plt.draw()\r\n plt.pause(0.03)'''\r\n\r\ndef videoshow():\r\n global frame\r\n while True:\r\n _, img = cap.read()\r\n frame = img\r\n cv2.imshow('frame',frame)\r\n k = cv2.waitKey(25) & 0xff\r\n if k == 27:\r\n break\r\n cap.release()\r\n cv2.destroyAllWindows()\r\n sys.exit()\r\n\r\n\r\n\r\ndef main():\r\n t1 = threading.Thread(target = videoshow)\r\n t2 = threading.Thread(target = draww)\r\n t3 = threading.Thread(target = getpix)\r\n #t2b = threading.Thread(target = drawone, args = (b, '-b'))\r\n #t2g = threading.Thread(target = drawone, args = (g, '-g'))\r\n #t2r = threading.Thread(target = drawone, args = (r, '-r'))\r\n\r\n t2.daemon = True\r\n t3.daemon = True\r\n #t2b.daemon = True\r\n #t2g.daemon = True\r\n #t2r.daemon = True\r\n\r\n t1.start()\r\n t2.start()\r\n #t2b.start()\r\n #t2g.start()\r\n #t2r.start()\r\n t3.start()\r\n\r\n\r\nif __name__ == \"__main__\":\r\n main()\r\n","sub_path":"__OLD_CODE_STORAGE/BGR_graph/3graphs.py","file_name":"3graphs.py","file_ext":"py","file_size_in_byte":2418,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"417578364","text":"from VFX.smoked import VideoEffect\n\nfrom Engine.config import MAT_TYPE, CHANNEL\nfrom Engine.geometry import Vec2d, angular_distance\nfrom Engine.loading import load_model, cast_model, load_sound\nfrom Engine.physics import BaseProjectile\n\nimport pymunk\n\nNAME = __name__.split('.')[-1]\nMODEL = load_model('Projectiles\\\\Models\\\\%s' % (NAME,))\n\nCS = Vec2d(107, 43)\n\n\nclass Explosion(BaseProjectile):\n hit_damage = 15\n size_inc = .4\n mat = MAT_TYPE.ENERGY\n\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n\n self.body = pymunk.Body()\n self.shape = pymunk.Circle(self.body, self.RADIUS)\n self.shape.mass = 1000\n self._image.fps = 20\n self._image.que_end(self.kill)\n\n def update(self):\n self.shape.unsafe_set_radius(self.R_LIST[self._image.n])\n\n @classmethod\n def init_class(cls):\n cls._frames, cls.IMAGE_SHIFT = cast_model(\n load_model('Projectiles\\\\Models\\\\explosion_frag'),\n None, cls.size_inc)\n cls.precalculate_shape()\n cls.calculate_poly_shape()\n\n @classmethod\n def precalculate_shape(cls):\n radius = 5\n rs = (30, 75, 85, 100, 125, 150, 175, 200, 225, 125, 125, 100, 50, 1, 1)\n\n cls.RADIUS = radius * cls.size_inc\n cls.R_LIST = [e * cls.size_inc for e in rs]\n\n @classmethod\n def calculate_poly_shape(cls):\n img_poly_left = []\n poly_left = [tuple(e[n] - CS[n] for n in range(2)) for e in img_poly_left]\n poly_right = [(e[0], -e[1]) for e in poly_left[::-1]]\n cls.POLY_SHAPE = [(e[0] * cls.size_inc, e[1] * cls.size_inc) for e in poly_left + poly_right]\n\n\nExplosion.init_class()\n\n\nclass Projectile(BaseProjectile):\n size_inc = 1\n damping = 0\n max_health = 10\n lifetime = 3000\n hit_damage = 15\n sound = {\n 'launch': [load_sound('Projectiles\\\\Models\\\\mini_launch', ext='wav', volume=.5),\n {'channel': CHANNEL.MINI_LAUNCH}]\n }\n death_effect = VideoEffect\n\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n\n self.body = pymunk.Body()\n self.shape = pymunk.Poly(self.body, self.POLY_SHAPE)\n self.shape.density = 1\n\n self.target = None\n self.boost = False\n\n def effect(self, obj, arbiter, first=True):\n if self.boost:\n obj.damage(self.hit_damage)\n self.death()\n\n def death(self):\n if self.health > 0 and not self.boost:\n self.emit_death_effect()\n else:\n v = Explosion()\n v.add(*self.groups())\n v.position = self.position\n v.set_parent(self)\n self.kill()\n\n def update(self):\n if self.boost:\n self.body.apply_force_at_local_point((5000000, 0), (0, 0))\n if self.target is not None:\n if hasattr(self.target, '__call__'):\n tp = self.target()\n else:\n tp = list(self.target)\n da = angular_distance(self.angle, (Vec2d(tp) - self.position).angle)\n self.angle += da * .1\n\n def launch(self):\n self.play_sound('launch')\n self.boost = True\n self.damping = 0\n self._image.fps = 10\n\n @classmethod\n def init_class(cls):\n cls._frames, cls.IMAGE_SHIFT = cast_model(MODEL, CS, cls.size_inc)\n cls.precalculate_shape()\n cls.calculate_poly_shape()\n\n @classmethod\n def precalculate_shape(cls):\n radius = 15\n\n cls.RADIUS = radius * cls.size_inc\n\n @classmethod\n def calculate_poly_shape(cls):\n img_poly_left = [(75, 31), (146, 33)]\n poly_left = [tuple(e[n] - CS[n] for n in range(2)) for e in img_poly_left]\n poly_right = [(e[0], -e[1]) for e in poly_left[::-1]]\n cls.POLY_SHAPE = [(e[0] * cls.size_inc, e[1] * cls.size_inc) for e in poly_left + poly_right]\n\n\nProjectile.init_class()\n","sub_path":"Projectiles/missile.py","file_name":"missile.py","file_ext":"py","file_size_in_byte":3924,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"498314250","text":"\"\"\"\nSearch by full sequence scanning\n\nComplexity: O(n)\nMemory complexity: O(1)\n\"\"\"\n\nunordered_elements = [12, 43, 1, 3, 44, 21, 18, 15, 19, 33, 45, 22, 2]\n\n\ndef search(element, elements):\n for index, candidate in enumerate(elements):\n if candidate == element:\n return index\n return -1\n\n\nprint(search(21, unordered_elements))\n","sub_path":"home_work_5_2/search.py","file_name":"search.py","file_ext":"py","file_size_in_byte":349,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"636282404","text":"#!/usr/bin/env python3\n\n# Title: The Seven Deadly Sins in Social Media Case Study in Victoria Cities\n# Team Name: Team 14\n# Team Members:\n# Dading Zainal Gusti (1001261)\n# David Setyanugraha (867585)\n# Ghawady Ehmaid (983899)\n# Indah Permatasari (929578)\n# Try Ajitiono (990633)\n\n# Tips:\n# We can run this harvest.py in the background, use this command:\n# nohup python3 ./harvest.py &\n# To save output to file, use this command:\n# nohup python3 ./harvest.py &> harvestlog.log &\n#\n# Notes: Don't forget add '&' in the end of command to make sure it run in background\n# To check background process\n# ps aux | grep harvest.py\n\nimport tweepy\nimport requests\nimport json\nimport time, os\nfrom queue import Queue\nfrom threading import Thread\n\n# Listener to catch all stream from Twitter API\nclass MyStreamListener(tweepy.StreamListener):\n def __init__(self, q = Queue()):\n self.last_report_time = time.time()\n self.success_insert = 0\n self.error = 0\n self.duplicate_error = 0\n # Below added to resolve the \"Connection broken: IncompleteRead\" exception that kept occuring from time to time\n # based on online search disconnect could be due to network issues or a client reading too slowly, to avoid\n # the slow processing/not keeping up with the stream following the suggested answer in below thread\n # https://stackoverflow.com/questions/48034725/tweepy-connection-broken-incompleteread-best-way-to-handle-exception-or-can\n self.q = q\n super(MyStreamListener, self).__init__()\n for i in range(4):\n t = Thread(target=self.process_q)\n t.daemon = True\n t.start()\n\n def process_q(self):\n while True:\n self.q.get()\n self.q.task_done()\n\n\n def on_status(self, status):\n self.insertDB(status)\n if (time.time() - self.last_report_time) > 600:\n print(time.strftime(\"%a, %d %b %Y %H:%M:%S +0000\")+\" Statistics from last report time: \"\n + str(self.success_insert)+\" Tweets Added, \"+str(self.duplicate_error)+\" Reject Duplicate, \"\n + str(self.error)+\" Rejected due to error.\")\n # Resit counters\n self.last_report_time = time.time()\n self.success_insert = 0\n self.error = 0\n self.duplicate_error = 0\n\n def insertDB(self, status):\n data = json.dumps(status._json)\n\n # Insert Document to Tweets database\n url = BASE_URL + '/'+DATABASENAME+'/\\\"' + str(status.id) + '\\\"'\n response = db.put(url, data)\n\n # Catch the error from DB response\n if (response.status_code != 201):\n print(time.strftime(\"%a, %d %b %Y %H:%M:%S +0000\") + \" Error in insertDB (\" + str(response.status_code) + \") \" +\n str(response.json()) + \"[\" + str(status.id) + \"]\")\n if (response.status_code == 409):\n self.duplicate_error += 1\n else:\n self.error += 1\n else:\n self.success_insert += 1\n #print(time.strftime(\"%a, %d %b %Y %H:%M:%S +0000\") + \" Insert tweet in insertDB (\" + str(response.status_code) + \") \" +\n # str(response.json()) + \"[\" + str(status.id) + \"]\")\n\n def on_error(self, status_code):\n print(time.strftime(\"%a, %d %b %Y %H:%M:%S +0000\") + \" on_error message triggered (\" + str(status_code) + \")\",\n self)\n if status_code == 420:\n return False\n\n def on_limit(self, track):\n print(time.strftime(\"%a, %d %b %Y %H:%M:%S +0000\") + \" Twitter Limit reached! track:\", track)\n return False\n\n\n# read absulte path as required in ansible\nharvestconfigfilepath = os.path.join(os.path.dirname(os.path.realpath(__file__)), \"harvestconfig.json\")\n\nwith open(harvestconfigfilepath, \"r\") as read_file:\n harvestconfig = json.load(read_file)\n\n# Database Connection Configuration\n#BASE_URL = 'http://172.26.38.57:5984'\nBASE_URL = harvestconfig[\"couchdb\"][\"baseurl\"]\nUSERNAME = harvestconfig[\"couchdb\"][\"user\"]\nPASSWORD = harvestconfig[\"couchdb\"][\"password\"]\nDATABASENAME = harvestconfig[\"couchdb\"][\"databasename\"]\ndb = requests.Session()\ndb.auth = (USERNAME, PASSWORD)\n\n# API Twitter Configuration\nconsumer_key = harvestconfig[\"twitterapi\"][\"consumer_key\"]\nconsumer_secret = harvestconfig[\"twitterapi\"][\"consumer_secret\"]\naccess_token = harvestconfig[\"twitterapi\"][\"access_token\"]\naccess_token_secret = harvestconfig[\"twitterapi\"][\"access_token_secret\"]\n\n# Tweepy Initialization\nauth = tweepy.OAuthHandler(consumer_key, consumer_secret)\nauth.set_access_token(access_token, access_token_secret)\napi = tweepy.API(auth)\nmyStream = tweepy.Stream(api.auth, MyStreamListener())\n\n# Run Streaming tweet code for certain GEOBOX\nGEOBOX = harvestconfig[\"twitterapi\"][\"geobox_coordinates\"]\n#[\n# 140.96190162, -39.19848673,\n# 150.03328204, -33.98079743,\n#]\n\n# Run the Streaming continuously and reattempt incase of exception\nwhile True:\n try:\n myStream.filter(locations=GEOBOX)\n except Exception as ex:\n print(time.strftime(\"%a, %d %b %Y %H:%M:%S +0000\") + \" Exception in stream filter, retrying\")\n print(ex)\n #there will be some missing tweets between recornnect, but this is not critical for this implementation\n time.sleep(100)\n continue\n","sub_path":"harvest/harvest.py","file_name":"harvest.py","file_ext":"py","file_size_in_byte":5313,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"378452038","text":"import os\r\n\r\nfrom paypalcheckoutsdk.core import PayPalHttpClient, SandboxEnvironment\r\n\r\n\r\nclass PayPalClient:\r\n def __init__(self):\r\n self.client_id = os.environ.get('CLIENT_ID')\r\n self.client_secret = os.environ.get('CLIENT_SECRET')\r\n self.environment = SandboxEnvironment(client_id=self.client_id, client_secret=self.client_secret)\r\n self.client = PayPalHttpClient(self.environment)\r\n","sub_path":"ARStore/apps/checkout/paypal.py","file_name":"paypal.py","file_ext":"py","file_size_in_byte":417,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"6081362","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nsquare_digits.py\r\nSamuel Li\r\n9/30/2018\r\n\r\nI understand and have adhered to all the tenets of the Duke Community Standard \r\nin creating this code.\r\nSigned: sbl28\r\n\"\"\"\r\n\r\nfor i in range(1,4):\r\n for j in [0,1,5,6]:\r\n num = int(str(i)+str(j))\r\n if num>31:\r\n break;\r\n if int(str(num**2)[-2:]) == num:\r\n print(\"{}**2 is {}\".format(num,num**2))","sub_path":"lab4/square_digits.py","file_name":"square_digits.py","file_ext":"py","file_size_in_byte":413,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"145089657","text":"#import pdb\nfrom glob import glob\nfrom os import path\nfrom datetime import date, datetime, timezone, timedelta\nfrom scipy.io import loadmat\nfrom collections import defaultdict\nfrom Matlab_Helpers import datenum, read_arm_netcdf_files, read_text_file\nimport numpy as np\n\n#from parse import parse\nfrom MODF_Spec import MODF_Spec \nclass MODF_Utqiagvik(MODF_Spec): # extend the MODF spec class and implement Utqiagvik's version here\n\n # class variables, anything put here has to be accessed via self.variable_of_interest\n base_path = './Data'\n #base_path = 'W:/MODF/Data' # Windows\n\n # change me to fit your period\n start_year = 2018\n start_month = 7\n start_day = 1\n end_year = 2018\n end_month = 10\n end_day = 1\n period_start = datenum(datetime(start_year, start_month, start_day))\n period_end = datenum(datetime(end_year, end_month, end_day))\n\n # set desired global attributes and change dimensions to match Utqiagvik measurements\n def site_init(self): \n # super().set_var_dims() ## call parent method of same name, does some logic\n global_atts = {\n \"creator_name\" : \"Michael Gallagher\",\n \"creator_email\" : \"michael.r.gallagher@noaa.gov\",\n \"title\" : \"MODF for Utqiagvik, Alaska, US during YOPP SOP1 (utqiagvik_obs_sop1.nc)\",\n \"institution\" : \"NOAA/ESRL/PSD\",\n \"contact\" : \"esrl.psd.data@noaa.gov\",\n \"project\" : \"YOPPsiteMIP\",\n \"source\" : \"multiple: see variable attributes\",\n \"references\" : \"under development\",\n \"acknowledgement\" : \"\",\n \"license\" : \"\",\n \"comment\" : \"\",\n \"standard_name_vocabulary\" : \"CF Standard Name v64\",\n \"keywords\" : \"YOPP: Polar: Arctic: Supersite: Observations\",\n \"location\" : \"Utqiagvik, AK, USA\",\n \"time_coverage_start\" : \"2018-02-01 00:00:00\",\n \"time_coverage_end\" : \"2018-03-31 23:59:00\",\n \"this_shouldnt_work\" : \"This doesnt go in\",\n }\n\n self.add_global_atts(global_atts) # \n self.change_dim(\"height\", 111) # These could/should be pulled in from the data file \n self.change_dim(\"depth\", 10) # ... don't hardcode things...\n #print(self.__dict__.keys())\n\n # ################################################################################################\n # here are the functions that pull in the data for the MODF spec, they don't have to be defined\n # in any particular order, or called in any particular order....\n # override default spec function for data\n def read_sonde(self):\n print(\"-------------------------------------------------------------------------------------\")\n print(\"We've overridden read_sonde ...!\")\n print(\"-------------------------------------------------------------------------------------\")\n #print(\"This is going to be the first test of pulling in data!\")\n\n # here we go!\n def read_soil(self):\n print(\"... reading ARM soil data...\")\n\n soil_data = self.base_path+\"/GMD2018/\"\n soil = defaultdict(list) # does this need to be a default dict?? maybe?\n files = glob(\"{}gradobs*\".format(soil_data)) # get all files with title gradobs in soil_data dir\n for f in files: # loop over files\n data = read_text_file(f, starting_column=1)\n\n # Parse the third hour:min column into hours and minutes e.g. 1234 becomes 12:34, 59 -> 0:59, etc.\n years = data[:,1].astype(int)\n days = data[:,2].astype(int)\n hours = [int(hourmin[0:-2] or '0') for hourmin in data[:,3]]\n minutes = [int(hourmin[-2:]) for hourmin in data[:,3]]\n\n # Uses timedelta to convert raw day of year into month/day.\n time = [datenum(datetime(y, 1, 1, h, m) + timedelta(days=int(d-1))) for y, d, h, m in zip(years, days, hours, minutes)]\n\n soil['time'].append(time)\n soil['depth'].append(data[:,23])\n soil['temp'].append(data[:,24:34])\n\n soil = { key: np.concatenate(values) for key, values in soil.items() }\n\n # apply matlab QC files \n depth_qc = loadmat(\"{}/SnDepth_qc.mat\".format(soil_data))\n temp_qc = loadmat(\"{}/SoilTemp_qc.mat\".format(soil_data))\n\n soil['depth'][depth_qc['qc_SD'][:, 1] > 0] = np.nan\n soil['temp'][temp_qc['qc_soil'][:, 1:11] > 0] = np.nan\n\n # narrow data down to specific period.x\n period = np.logical_and(self.period_start <= soil['time'], soil['time'] < self.period_end)\n for s in ['time', 'depth', 'temp']:\n soil[s] = soil[s][period]\n\n # unit conversions\n time_soil = soil['time']\n snd = 3.6576 - (soil['depth'].astype(float) / 1000)\n tsl = soil['temp'].astype(float) + 273.15\n\n new_soil_att = { \n \"tsl\" : {\"test_att_one\" : \"here is a test of adding an attribute to a spec var\",\n \"test_att_two\" : \"here is another additional attribute to a spec var\",\n \"test_att_three\" : \"here is a final attribute added to a spec var\",},\n }\n\n self.add_var_att(new_soil_att)\n self.add_var_citation(\"tsl\", \"this data taken from ARM soil monitors, this is a cite test\")\n self.add_var_data(\"tsl\", tsl)\n self.add_coordinate_data(\"time\", time_soil)\n print((np.nanmax(time_soil)-np.nanmin(time_soil)))\n \n # implement these!\n def read_ozone(self):\n print(\"... reading GMD ozone data...\")\n\n # Ozone\n data = read_text_file(path.join(self.base_path, 'Ozone/brw_2018_all_minute.dat'), starting_column=16)\n\n # Determine timeline\n time_o = np.array([datenum(datetime(y, mo, d, h, m)) for y, mo, d, h, m in data[:,1:6].astype(int)])\n o3 = data[:,6].astype(float)\n\n # Apply quality control and narrow down to specific period.\n period = np.logical_and(self.period_start <= time_o, time_o < self.period_end)\n qc = o3 != 9999.99\n filters = np.logical_and(period, qc)\n\n time_o = time_o[filters]\n o3 = o3[filters]\n\n time_o, indices = np.unique(time_o, return_index=True)\n o3 = o3[indices]\n\n\n def read_prsn(self): \n print(\"... reading PSD snowflux data...\")\n\n # TODO: Put on timeline\n # ARM eddy covariance fluxes\n arm_ec = read_arm_netcdf_files(path.join(self.base_path, 'ARM2018/nsa30ecorE10*'), [\n 'h',\n 'lv_e'\n ], self.period_start, self.period_end)\n\n time_ec = arm_ec['time']\n hs = arm_ec['h']\n hl = arm_ec['lv_e']\n\n def read_ec(self): \n print(\"... reading ARM eddy covariance flux data...\")\n\n # TODO: Put on timeline\n # ARM eddy covariance fluxes\n arm_ec = read_arm_netcdf_files(path.join(self.base_path, 'ARM2018/nsa30ecorE10*'), [\n 'h',\n 'lv_e'\n ], self.period_start, self.period_end)\n\n time_ec = arm_ec['time']\n hs = arm_ec['h']\n hl = arm_ec['lv_e']\n\n def read_ghf(self): \n print(\"... reading ground heat flux data...\")\n\n arm_ground = read_arm_netcdf_files(path.join(self.base_path, 'ARM2018/nsasebsE10.b1.*'), [\n 'surface_soil_heat_flux_avg'\n ], self.period_start, self.period_end)\n\n time_ghf = arm_ground['time']\n ghf = arm_ground['surface_soil_heat_flux_avg']\n\n def read_rad(self): \n print(\"... reading radiation data...\")\n\n arm_rad = read_arm_netcdf_files(path.join(self.base_path, 'ARM2018/nsaqcrad1longC1*'), [\n 'BestEstimate_down_short_hemisp',\n 'down_long_hemisp',\n 'up_short_hemisp', \n 'up_long_hemisp',\n 'precip',\n 'press'\n ], self.period_start, self.period_end)\n\n time_rad = arm_rad['time']\n rsds = arm_rad['BestEstimate_down_short_hemisp']\n rlds = arm_rad['down_long_hemisp']\n rsus = arm_rad['up_short_hemisp']\n rlus = arm_rad['up_long_hemisp']\n pr = arm_rad['precip']\n ps = arm_rad['press'] * 1000\n\n def read_twr(self): \n print(\"... reading tower data...\")\n\n # ARM tower data\n arm_tower = read_arm_netcdf_files(path.join(self.base_path, 'ARM2018/nsatwr*'), [\n 'temp_mean',\n 'rh_mean',\n 'dew_point_mean',\n 'wspd_vec_mean',\n 'wdir_vec_mean'\n ], self.period_start, self.period_end)\n\n time = arm_tower['time']\n hurs = arm_tower['rh_mean']\n # Convert to K\n tdps = arm_tower['dew_point_mean'] + 273.15\n tas = arm_tower['temp_mean'] + 273.15\n # Convert to... something else\n uas = arm_tower['wspd_vec_mean'] * np.sin(arm_tower['wdir_vec_mean'] * np.pi / 180)\n vas = arm_tower['wspd_vec_mean'] * np.cos(arm_tower['wdir_vec_mean'] * np.pi / 180)\n\n def read_igra(self): \n print(\"... reading IGRA data...\")\n\n def read_tskin(self): \n print(\"... reading NCDC skin temperature data...\")\n\n # NCDC skin temperature\n data = read_text_file(path.join(self.base_path, 'NCDC2018/CRNS0101-05-2018-AK_Utqiagvik_formerly_Barrow_4_ENE.txt'))\n\n # learn to debug bbetter\n print() # you need to learn how to actually print info about numpy arrays, etc\n\n # Determine timeline\n time_orig = np.array([d + t for d, t in data[:,1:3]])\n time_tskin = np.array([datenum(datetime.strptime(d + t, '%Y%m%d%H%M')) for d, t in data[:,1:3]])\n\n # Apply quality control\n qc = data[:,14].astype(int)\n tskin = data[:,12].astype(float) + 273.15\n tskin[qc > 0] = np.nan\n\n # Narrow down to specific period.\n period = np.logical_and(self.period_start <= time_tskin, time_tskin < self.period_end)\n\n time_tskin = time_tskin[period]\n tskin = tskin[period]\n\n def read_bulk(self): \n print(\"... reading PSD bulk turbulent flux data...\")\n\n def read_SR(self): \n print(\"... reading data...\") \n\n def read_GMD(self):\n print(\"... reading data...\") \n\n\n # # Bulk\n # data = loadmat(path.join(self.base_path, 'YOPP_BRW_ARM_flux_data_2018_avg_10_min.mat'))\n\n # # Determine timeline\n # time_bulk = datenum(datetime(2017, 12, 31)) + data['yd_blk'].astype(float)\n # period = np.logical_and(self.period_start <= time_bulk, time_bulk < self.period_end)\n\n # time_bulk = time_bulk[period]\n # for s in ['z0b', 'z0tb', 'taub3n', 'taub3e', 'hsb3', 'hlb3']:\n # data[s] = data[s][period]\n\n # z0b = data['z0b'].astype(float)\n # z0tb = data['z0tb'].astype(float)\n # taub3n = data['taub3n'].astype(float)\n # taub3e = data['taub3e'].astype(float)\n # hsb3 = data['hsb3'].astype(float)\n # hlb3 = data['hlb3'].astype(float)\n\n # # PRSN\n # psrn = defaultdict(list)\n\n # files = glob.glob(path.join(self.base_path, f'SR/*/kazr*'))\n # for f in files:\n # data = read_text_file(f, starting_column=2)\n\n # # Date is taken from the filename\n # filename = f[f.rfind('\\\\') + 1:]\n # base_date = datetime.strptime(filename[4:12], '%Y%m%d')\n\n # # Time is in the form of hours past base date\n # hours = np.unique(data[:,0].astype(float))\n # height = np.unique(data[:,1].astype(float))\n # sr = data[:,4].astype(float)\n\n # # Remove duplicate values from time and height\n # time = np.array([datenum(base_date + timedelta(hours=h)) for h in hours])\n\n # # QC\n # sr[sr == -9.9] = np.nan\n # sr = sr/60/60\n\n # psrn['time'].append(time)\n # psrn['height'].append(height)\n # psrn['sr'].append(sr)\n\n # psrn = { key: np.concatenate(values) for key, values in psrn.items() }\n\n # time_psrn = psrn['time']\n # height = np.unique(psrn['height'])\n # sr = psrn['sr'].reshape(time_psrn.size, height.size)\n\n # # TODO: Put on timeline?\n\n # # TODO: Finish Sonde and add to timeline\n # # Sonde\n # sonde = read_arm_netcdf_files(path.join(self.base_path, 'ARM2018/nsasonde*'), [\n # 'pres',\n # 'tdry',\n # 'dp', \n # 'wspd',\n # 'deg',\n # 'rh',\n # 'u_wind',\n # 'lat',\n # 'lon',\n # 'alt'\n # ], self.period_start, self.period_end).clear\n\n # # TODO: Finish IGRA and add to timeline\n # # IGRA\n # igra = defaultdict(list)\n\n # with open(path.join(self.base_path, 'IGRA/USM00070026-data.txt')) as f:\n # lines = f.readlines()\n # headers = [(index, line) for index, line in enumerate(lines) if line[0] == '#']\n\n # for index, header in headers:\n # head = parse('#{_} {year:d} {month:d} {day:d} {hour:d} {_:2d}{_:2d} {num:d} {_} {_} {_:d} {_:d}', header)\n # section = lines[index, index + head.num]\n # data = np.array([line.replace('B', '').replace('A', '').split() for line in section])\n\n # base_time = datetime(int(head.year), int(head.month), int(head.day), int(head.hour))\n\n # hours = [int(hourmin[0:-2] or '0') for hourmin in data[:,1]]\n # minutes = [int(hourmin[-2:]) for hourmin in data[:,1]]\n\n # time = [base_time + timedelta(hours=h, minutes=m) for h, m in zip(hours, minutes)]\n\n # igra['base_time'].extend([base_time] * len(data))\n # igra['time'].extend(time)\n # igra['pres'].extend(data[:3] / 100)\n # igra['zg'].extend(data[:,4])\n # igra['tdry'].extend(data[:,5] / 10)\n # igra['dp'].extend(data[:,5] - (data[:,7] / 10))\n # igra['wspd'].extend(data[:,9] / 10)\n # igra['deg'].extend(data[:,8])\n # igra['rh'].extend(data[:,6] / 10)\n\n # # TODO: Save data in NetCDF file\n","sub_path":"MODF_Spec_Utqiagvik.py","file_name":"MODF_Spec_Utqiagvik.py","file_ext":"py","file_size_in_byte":14172,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"122099520","text":"from sqlitedict import SqliteDict\nimport pickle\n\ntall = []\nc = 0\nc_tall = 0\nmydict = SqliteDict(\"/../../../../../scratch/manoelribeiro/helpers/authors_dict.sqlite\", tablename=\"authors\", flag=\"r\")\n\nfor _, value in mydict.iteritems():\n if (c % 100000) == 0:\n print(f\"c = {c}, c_all = {c_tall}\")\n c += 1\n if c >= 11400000:\n break\n\n diff_comm = set()\n for comm in value:\n cat = comm[\"category\"]\n if cat == \"Alt-right\" or cat == \"Alt-lite\" or cat == \"Intellectual Dark Web\":\n diff_comm.add(cat)\n else:\n diff_comm.add(\"control\")\n\n if len(diff_comm) > 1:\n continue\n\n tall.append(value)\n c_tall += 1\n\nwith open(\"authors_engagement.pickle\", \"wb\") as fp:\n pickle.dump(tall, fp, protocol=pickle.HIGHEST_PROTOCOL)\n","sub_path":"scripts/engagement/split_engagement.py","file_name":"split_engagement.py","file_ext":"py","file_size_in_byte":793,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"582548266","text":"\"\"\"hello URL Configuration\n\nThe `urlpatterns` list routes URLs to views. For more information please see:\n https://docs.djangoproject.com/en/3.0/topics/http/urls/\nExamples:\nFunction views\n 1. Add an import: from my_app import views\n 2. Add a URL to urlpatterns: path('', views.home, name='home')\nClass-based views\n 1. Add an import: from other_app.views import Home\n 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')\nIncluding another URLconf\n 1. Import the include() function: from django.urls import include, path\n 2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))\n\"\"\"\nfrom django.contrib import admin\nfrom django.urls import path,re_path,include\nfrom firstapp import views\n\nurlpatterns = [\n re_path(r\"^$\",views.Home.as_view()),\n path('admin/', admin.site.urls),\n re_path(r'^public/(?P\\w+)/(?P\\w+)',views.Files.as_view()),\n re_path(r\"^signup\",views.SignUp.as_view(),name=\"signup\"),\n re_path(r'^logout',views.logOut),\n re_path(r'^login',views.Login.as_view()),\n \n re_path(r\"^auth/dash/(?P\\d+)\",views.Dash.as_view()),\n re_path(r\"^delete_user/(?P\\d+)\",views.DeleteUser.as_view()),\n re_path(r\"^addnewuser\",views.AddUser.as_view()),\n re_path(r\"^product/(?P\\d+)\",views.Product.as_view(),name=\"product\"),\n re_path(r\"^order/(?P\\d+)\",views.Order.as_view()),\n re_path(r'^data',views.DataNews.as_view()),\n re_path(r'^categories/(?P\\w+)/(?P

\\d+)',views.ShowCategory.as_view()),\n re_path(r'^find$',views.Cat.as_view()),\n\n re_path(r\"\",views.findFile),\n\n\n]\n","sub_path":"hello/hello/hello/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1595,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"533162800","text":"import json\r\n\r\nfrom database import Subreddit\r\nfrom datetime import datetime, timedelta\r\nimport time\r\n\r\n\r\ndef save_subreddit_vars(subreddit, key, var=None):\r\n if var == None: ## Fuck you named variables for not recalculating on each call\r\n var = datetime.now()\r\n if time.localtime().tm_isdst:\r\n var += timedelta(hours=1)\r\n var = var.timestamp()\r\n sub = Subreddit.get(Subreddit.subreddit == subreddit)\r\n variables = json.loads(sub.vars)\r\n variables[key] = var\r\n sub.vars = json.dumps(variables)\r\n sub.save()\r\n\r\n\r\ndef get_subreddit_vars(subreddit):\r\n v = Subreddit.get(Subreddit.subreddit == subreddit)\r\n if v.vars == None:\r\n v.vars = json.dumps({})\r\n v.save()\r\n return json.loads(v.vars)\r\n","sub_path":"subreddit_vars.py","file_name":"subreddit_vars.py","file_ext":"py","file_size_in_byte":761,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"14383427","text":"import pytest\nfrom crown import *\nimport datetime\nDATABASENAME = 'taos_test'\nHOST = 'localhost'\ndb = TdEngineDatabase('taos_test',host=HOST)\n\n# test all field \nclass AllFields(SuperModel):\n name_float = FloatField(column_name='n_float')\n name_double = DoubleField()\n name_bigint = BigIntegerField()\n name_int = IntegerField()\n name_smallint = SmallIntegerField()\n name_tinyint = TinyIntegerField()\n name_nchar = NCharField(max_length=59,)\n name_binary = BinaryField(max_length=3)\n name_ = BooleanField()\n dd = PrimaryKeyField()\n birthday = DateTimeField()\n class Meta:\n database = db\n db_table = 'all_field'\n location = BinaryField(max_length=30)\n groupid = IntegerField(db_column='gid')\nAllField1 = AllFields.create_son_table('d3',location='beijing',groupid=3)\nclass Meters(SuperModel):\n cur = FloatField(db_column='c1')\n curInt = IntegerField(db_column='c2')\n curDouble = DoubleField(db_column='c3')\n desc = BinaryField(db_column='des')\n class Meta:\n order_by= ['-ts']\n database = db\n db_table = 'meters'\n location = BinaryField(max_length=30)\n groupid = IntegerField(db_column='gid')\nTableT = Meters.create_son_table('d3',location='beijing',groupid=3)\n\ndef test_create_drop_stable():\n assert Meters.create_table()\n print(db.get_supertables())\n assert Meters.supertable_exists()\n assert Meters.drop_table()\n assert not Meters.supertable_exists()\n\ndef test_create_drop_sontable():\n son = Meters.create_son_table('d1',location='beijing',groupid=3)\n print(db.get_tables())\n assert son.table_exists()\n assert son.drop_table()\n assert not son.table_exists()\n\n\n@pytest.fixture()\ndef insertData():\n for i in range(1,11):\n # time.sleep(30)\n m = TableT(cur = 1/i,curInt=i,curDouble=1/i+10,desc='g1',ts= datetime.datetime.now() - datetime.timedelta(hours=(12-i)))\n m.save()\n for i in range(1,21):\n # time.sleep(30)\n m = TableT(cur = 1/i,curInt=i,curDouble=1/i+10,desc='g2',ts= datetime.datetime.now() - datetime.timedelta(hours=(21-i)))\n m.save()\n yield\n\n TableT.drop_table()\n\n\n\n\n\n","sub_path":"test_taos_supermodel.py","file_name":"test_taos_supermodel.py","file_ext":"py","file_size_in_byte":2275,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"234602807","text":"import logging\nimport os\nfrom glob import glob\nfrom zipfile import ZipFile\n\nfrom pywps import Process\nfrom pywps import ComplexInput, LiteralInput, ComplexOutput, Format\nfrom pywps.validator.mode import MODE\n\nimport fiona\nimport rasterio\nimport rasterio.mask\n\nclass SpatialSubsetGeotiff(Process):\n def __init__(self):\n inputs = [\n ComplexInput('datafile', 'GeoTIFF datafile',\n supported_formats=[Format('image/tiff')],\n min_occurs=1, max_occurs=1,\n # NOTE: Can't validate GeoTIFFs at the moment\n mode=MODE.NONE),\n ComplexInput('shapefile', '.zip file representing ESRI Shapefile of geometry to use for subset',\n supported_formats=[Format('application/zip')],\n min_occurs=1, max_occurs=1,\n # NOTE: No validator for ZIP files\n mode=MODE.NONE),\n ]\n\n outputs = [\n ComplexOutput('output', 'Output data',\n as_reference=True,\n supported_formats=[Format('text/plain')]),\n ]\n\n super(SpatialSubsetGeotiff, self).__init__(\n self._handler,\n identifier='spatial_subset_geotiff',\n title='GeoTIFF data spatial subset',\n abstract=\"Subsets a given GeoTIFF file with given spatial data/geometry\",\n version='1',\n metadata=[],\n inputs=inputs,\n outputs=outputs,\n store_supported=True,\n status_supported=True)\n\n def _handler(self, request, response):\n # Get the GeoTIFF file\n # Note that all input parameters require index access\n file_input = request.inputs['file'][0]\n\n # Subset geometry\n geometry_zip_input = request.inputs['shapefile'][0]\n geometry_zip = ZipFile(geometry_zip_input.file)\n\n # Extract to subdirectory, pick out the SHP file\n geometry_dir = os.path.join(self.workdir, '_geometry')\n geometry_zip.extractall(path=geometry_dir)\n\n geometry_shp_file = glob(os.path.join(geometry_dir, '*.shp'))[0]\n\n # Use shapefile to mask (subset) GeoTIFF file\n # Most of this is from https://rasterio.readthedocs.io/en/latest/topics/masking-by-shapefile.html\n with fiona.open(geometry_shp_file, \"r\") as shapefile:\n features = [feature[\"geometry\"] for feature in shapefile]\n \n with rasterio.open(file_input.file) as src:\n out_image, out_transform = rasterio.mask.mask(src, features, crop=True)\n out_meta = src.meta.copy()\n\n # Adjust metadata accordingly\n out_meta.update({\n \"driver\": \"GTiff\",\n \"height\": out_image.shape[1],\n \"width\": out_image.shape[2],\n \"transform\": out_transform,\n })\n\n # Write output GeoTIFF file\n output_path = os.path.join(self.workdir, \"subset.tif\")\n\n with rasterio.open(output_path, \"w\", **out_meta) as dest:\n dest.write(out_image)\n\n # Finish up by providing the path to the subsetted file\n response.outputs['output'].file = output_path\n\n return response\n","sub_path":"src/ecocloud_wps_demo/processes/spatial_subset_geotiff.py","file_name":"spatial_subset_geotiff.py","file_ext":"py","file_size_in_byte":3236,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"618694126","text":"import unicodedata\n\nimport arrow\nfrom pdl.models import Proyecto\nfrom pdl.models import Expedientes\nfrom pdl.utils import convert_string_to_time\n\n\ndef get_proyecto_from_short_url(short_url):\n \"\"\"\n :param short_url:\n :return: item for Proyecto\n \"\"\"\n item = Proyecto.objects.get(short_url=short_url)\n if item.iniciativas_agrupadas is not None and \\\n item.iniciativas_agrupadas != '' and '{' in \\\n item.iniciativas_agrupadas:\n iniciativas = item.iniciativas_agrupadas.replace(\"{\", \"\")\n iniciativas = iniciativas.replace(\"}\", \"\")\n item.iniciativas_agrupadas = iniciativas.split(\",\")\n item.congresistas_with_links = hiperlink_congre(item.congresistas)\n item.fecha_presentacion = convert_string_to_time(item.fecha_presentacion)\n item.fecha_presentacion_human = arrow.get(item.fecha_presentacion).format('DD MMMM, YYYY', locale='es_es')\n item.numero_congresistas = len(item.congresistas.split(\";\"))\n return item\n\n\ndef get_events_from_expediente(id):\n \"\"\"\n Uses the `proyecto_id` to obtain a list of events from the `expediente`\n page.\n\n :param id: proyecto_id as in table pdl_proyecto\n :return: list of events, which are key=>value dictionaries\n \"\"\"\n events = Expedientes.objects.all().filter(proyecto=id).order_by('-fecha')\n\n events_with_human_date = []\n append = events_with_human_date.append\n for i in events:\n i.fecha = arrow.get(i.fecha).format('DD MMM, YYYY', locale='es_es')\n append(i)\n return events_with_human_date\n\n\ndef hiperlink_congre(congresistas):\n # tries to make a hiperlink for each congresista name to its own webpage\n if congresistas == '':\n return None\n\n for name in congresistas.split(\"; \"):\n link = \"\"\n link += name + \"\"\n congresistas = congresistas.replace(name, link)\n congresistas = congresistas.replace(\"; \", \";\\n\")\n return congresistas\n\n\ndef convert_name_to_slug(name):\n \"\"\"Takes a congresista name and returns its slug.\"\"\"\n name = name.strip()\n name = name.replace(\",\", \"\").lower()\n name = name.split(\" \")\n\n if len(name) > 2:\n i = 0\n slug = \"\"\n while i < 3:\n slug += name[i]\n if i < 2:\n slug += \"_\"\n i += 1\n slug = unicodedata.normalize('NFKD', slug).encode('ascii', 'ignore')\n slug = str(slug, encoding=\"utf-8\")\n return slug + \"/\"\n","sub_path":"proyectos_de_ley/seguimientos/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":2551,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"638619240","text":"#Step 1.\n#Take a video frame placed in \\road_survey_vid\\upload_folder. it strips the video into frames\nimport cv2\nimport os\nRoot_dir = os.path.abspath(\".\")\n\n\nupload_folder_dir = os.path.join(Root_dir, r\"road_survey_vid\\upload_folder\" )\n\nvid_list= os.listdir(upload_folder_dir)\nprint(vid_list)\nupload_vid_loc = os.path.join(upload_folder_dir, vid_list[0])\nprint(upload_vid_loc)\nvidcap = cv2.VideoCapture(upload_vid_loc)\nsuccess,image = vidcap.read()\ncount = 0\npath = os.path.join(Root_dir, r\"frames\")\n# code below will extract one frame after every 0.1 sec, but will change the frequency of picking frame laatter when tuning\n#seconds = 100\nfps = vidcap.get(cv2.CAP_PROP_FPS) # Gets the frames per second\nprint(fps)\n\nframe_no = 0\nwhile success:\n frame_no += 1\n cv2.imwrite(os.path.join(path, \"{}_frame{}.jpg\".format(vid_list[0],count)), image) # save frame as JPEG file\n print(\"{}_frame{}.jpg\".format(vid_list[0],count))\n success,image = vidcap.read()\n count += 1 # this stes the frequency of capturing frames\n print('Read a new frame at ', count, \" :\", success)\n\n","sub_path":"vid_to_frame.py","file_name":"vid_to_frame.py","file_ext":"py","file_size_in_byte":1072,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"449475941","text":"# coding=utf-8\n# Copyright 2022 The Google Research Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\"Test for quantized aware ds_tc_resnet model in session mode.\"\"\"\nimport numpy as np\nfrom kws_streaming.layers import test_utils\nfrom kws_streaming.layers.compat import tf\nfrom kws_streaming.layers.compat import tf1\nfrom kws_streaming.layers.modes import Modes\nfrom kws_streaming.models import utils\nimport kws_streaming.models.ds_tc_resnet as ds_tc_resnet\nfrom kws_streaming.train import inference\n\n\nclass DsTcResnetQatTest(tf.test.TestCase):\n \"\"\"Test ds_tc_resnet model in non streaming and streaming modes.\"\"\"\n\n def setUp(self):\n super(DsTcResnetQatTest, self).setUp()\n\n config = tf1.ConfigProto()\n config.gpu_options.allow_growth = True\n self.sess = tf1.Session(config=config)\n tf1.keras.backend.set_session(self.sess)\n tf.keras.backend.set_learning_phase(0)\n\n test_utils.set_seed(123)\n self.params = utils.ds_tc_resnet_model_params(True)\n self.params.quantize = 1\n\n self.model = ds_tc_resnet.model(self.params)\n self.model.summary()\n\n self.input_data = np.random.rand(self.params.batch_size,\n self.params.desired_samples)\n\n # run non streaming inference\n self.non_stream_out = self.model.predict(self.input_data)\n\n def test_ds_tc_resnet_stream(self):\n \"\"\"Test for tf streaming with internal state.\"\"\"\n # prepare tf streaming model\n model_stream = utils.to_streaming_inference(\n self.model, self.params, Modes.STREAM_INTERNAL_STATE_INFERENCE)\n model_stream.summary()\n\n # run streaming inference\n stream_out = inference.run_stream_inference_classification(\n self.params, model_stream, self.input_data)\n self.assertAllClose(stream_out, self.non_stream_out, atol=1e-5)\n\n def test_ds_tc_resnet_stream_tflite(self):\n \"\"\"Test for tflite streaming with external state.\"\"\"\n tflite_streaming_model = utils.model_to_tflite(\n self.sess, self.model, self.params,\n Modes.STREAM_EXTERNAL_STATE_INFERENCE)\n\n interpreter = tf.lite.Interpreter(model_content=tflite_streaming_model)\n interpreter.allocate_tensors()\n\n # before processing new test sequence we reset model state\n inputs = []\n for detail in interpreter.get_input_details():\n inputs.append(np.zeros(detail['shape'], dtype=np.float32))\n\n stream_out = inference.run_stream_inference_classification_tflite(\n self.params, interpreter, self.input_data, inputs)\n\n self.assertAllClose(stream_out, self.non_stream_out, atol=1e-5)\n\n\nif __name__ == '__main__':\n tf1.disable_eager_execution()\n tf.test.main()\n","sub_path":"kws_streaming/models/ds_tc_resnet_qat_test.py","file_name":"ds_tc_resnet_qat_test.py","file_ext":"py","file_size_in_byte":3127,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"5855368","text":"\"\"\"\nYou can ask me to \"show the cash pool\" if you would like to see your debts. You\ncan also ask me to \"show the cash pool history\", if you'd prefer.\nAlternatively, you may inform me that \"Tom sent $42 to Dick\" or that \"Tom paid\n$333 for Tom, Dick, and Harry\".\n\"\"\"\nfrom collections import defaultdict\nimport cPickle as pickle\nimport re\n\n\noutputs = []\n\n\nSENT = re.compile(r'jarvis.* (\\w+) sent \\$([\\d\\.]+) to (\\w+)')\nPAID = re.compile(r'jarvis.* (\\w+) paid \\$([\\d\\.]+) for ([ \\w]+)')\n\n\nPICKLE_FILE = 'cash_pool.pickle'\ntry:\n pool = pickle.load(open(PICKLE_FILE, 'rb'))\nexcept IOError:\n pool = defaultdict(int)\n\nPICKLE_HISTORY_FILE = 'cash_pool_history.pickle'\ntry:\n history = pickle.load(open(PICKLE_HISTORY_FILE, 'rb'))\nexcept IOError:\n history = list()\n\n\ndef show_history(channel, recent=None):\n if history:\n outputs.append([channel,\n 'Very good, sir, displaying your history now:'])\n else:\n outputs.append([channel, 'I have no record of a cash pool, sir.'])\n\n for line in history[recent:]:\n # TODO: better history sanitization\n outputs.append([channel, line.replace('jarvis, ', '')])\n\n return\n\n\ndef show_pool(channel):\n outputs.append([channel, \"I've analyzed your cash pool.\"])\n for person, value in sorted(pool.iteritems()):\n outputs.append([channel,\n '%s %s $%s' % (person.title(),\n 'owes' if value > 0 else 'is owed',\n abs(value) / 100.)])\n\n\n if not pool:\n outputs.append([channel, 'All appears to be settled.'])\n\n\ndef process_message(data):\n if 'explain the cash pool' in data['text']:\n outputs.append([data['channel'], 'Very well, sir.'])\n outputs.append([data['channel'], __doc__.replace('\\n', ' ')])\n return\n\n if 'show the cash pool' in data['text']:\n if 'history' in data['text']:\n if 'entire' in data['text']:\n show_history(data['channel'])\n return\n\n show_history(data['channel'], recent=-10)\n return\n\n show_pool(data['channel'])\n return\n\n did_send = SENT.match(data['text'])\n if did_send:\n sender, value, sendee = did_send.groups()\n value = int(float(value) * 100)\n\n pool[sender] -= value\n if not pool[sender]:\n del pool[sender]\n\n pool[sendee] += value\n if not pool[sendee]:\n del pool[sendee]\n\n history.append(data['text'])\n\n pickle.dump(history, open(PICKLE_HISTORY_FILE, 'wb'))\n pickle.dump(pool, open(PICKLE_FILE, 'wb'))\n\n outputs.append([data['channel'], 'Very good, sir.'])\n return\n\n did_pay = PAID.match(data['text'])\n if did_pay:\n payer, value, payees = did_pay.groups()\n payees = payees.split(' and ')\n value = int(float(value) * 100)\n\n pool[payer] -= value\n if not pool[payer]:\n del pool[payer]\n\n for payee in payees:\n pool[payee] += int(round(value / len(payees)))\n if not pool[payee]:\n del pool[payee]\n\n history.append(data['text'])\n\n pickle.dump(history, open(PICKLE_HISTORY_FILE, 'wb'))\n pickle.dump(pool, open(PICKLE_FILE, 'wb'))\n\n outputs.append([data['channel'], 'Very good, sir.'])\n return\n","sub_path":"plugins/cash_pool.py","file_name":"cash_pool.py","file_ext":"py","file_size_in_byte":3364,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"305348422","text":"\nimport iris\nfrom cube_tools import box_constraint\nimport matplotlib.pyplot as plt\nimport iris.plot as iplt\nfrom general_tools import haversine_d\nimport datetime\nfrom storm_tools import *\nfrom locate_centre import *\nimport numpy as np\nimport cartopy.crs as ccrs\nfrom plotting_tools import *\nfrom test_metrics import *\nfrom calculus import *\nfrom convert_coords import *\nimport cmaps\n\ndef main():\n em=0\n save_loc = '../data/calculated_terms/'\n tendency_df = save_loc + \"pv_tendency.nc\"\n vertadv_df = save_loc + \"ver_adv.nc\"\n horiadv_df = save_loc + \"hor_adv.nc\"\n dpvdp_df = save_loc + \"dpvdp.nc\"\n omega_df = save_loc + \"omega.nc\"\n dh_df = save_loc + \"dh.nc\"\n cmap = cmaps.temp_19lev\n locs_loc = '/nfs/a319/scjea/pv_tendency/storm_locs/'\n df = locs_loc + 'em{0:02d}_{1}.npz'.format(em,'4p4')\n data = np.load(df)\n lats = data['lats']; lons = data['lons']\n levels = np.arange(-5e-9,5.5e-9,0.5e-9)\n dpvdt = iris.load_cube(tendency_df)\n hor_adv = iris.load_cube(horiadv_df)\n vert_adv = iris.load_cube(vertadv_df)\n j=0\n for dpvdt_slc, horadv_slc, vertadv_slc in zip (\n dpvdt.slices(['pressure','latitude','longitude']),\n hor_adv.slices(['pressure','latitude','longitude']),\n vert_adv.slices(['pressure','latitude','longitude']),\n ):\n cube = dpvdt_slc\n time_units = cube.coord('time').units\n hr = time_units.num2date(cube.coord('time').points)[0].hour\n dd = time_units.num2date(cube.coord('time').points)[0].day\n mth = time_units.num2date(cube.coord('time').points)[0].month\n yr = time_units.num2date(cube.coord('time').points)[0].year\n\n for i in np.arange(11):\n # plot_terms(dpv_slc[i],'tendency')\n p = dpvdt_slc[i].coord('pressure').points[0]\n\n veradv_cy = cylindrical(vertadv_slc[i],lats[j,i],lons[j,i])\n lat0 = lats[j,i]; lon0 = lons[j,i]\n lat1 = lats[j+1,i]; lon1 = lons[j+1,i]\n dlon = lon1 - lon0\n dlat = lat1 - lat0\n theta = np.arctan2(dlat,dlon)\n rs = veradv_cy.coord('r').points\n phis = veradv_cy.coord('phi').points\n levels = np.arange(-5e-9,5.5e-9,0.5e-9)\n\n awn0,awn1, awn2 = wave_number(veradv_cy)\n\n\n fig = plt.figure()\n ax = fig.add_subplot(221,projection='polar')\n plot = ax.contourf(phis,rs,veradv_cy.data,levels=levels,cmap=cmap,extend='both')\n ax.plot([theta,theta],[0,200])\n ax.annotate('VerAdv',xy=(0.03,0.97), xycoords='axes fraction',horizontalalignment='left',verticalalignment='top',color='k',fontsize=20)\n\n ax = fig.add_subplot(222,projection='polar')\n plot = ax.contourf(phis,rs,awn1.data,levels=levels,cmap=cmap,extend='both')\n ax.plot([theta,theta],[0,200])\n ax.annotate('WN1',xy=(0.03,0.97), xycoords='axes fraction',horizontalalignment='left',verticalalignment='top',color='k',fontsize=20)\n\n ax = fig.add_subplot(223,projection='polar')\n plot = ax.contourf(phis,rs,awn0.data,levels=levels,cmap=cmap,extend='both')\n ax.plot([theta,theta],[0,200])\n ax.annotate('WN0',xy=(0.03,0.97), xycoords='axes fraction',horizontalalignment='left',verticalalignment='top',color='k',fontsize=20)\n\n ax = fig.add_subplot(224,projection='polar')\n plot = ax.contourf(phis,rs,awn2.data,levels=levels,cmap=cmap,extend='both')\n ax.plot([theta,theta],[0,200])\n ax.annotate('WN2',xy=(0.03,0.97), xycoords='axes fraction',horizontalalignment='left',verticalalignment='top',color='k',fontsize=20)\n\n plt.gcf().subplots_adjust(hspace=0.025,wspace=0.025)\n w, h = plt.gcf().get_size_inches()\n plt.gcf().set_size_inches(w * 2, h * 2)\n cbar = plt.colorbar(plot,ax=plt.gcf().get_axes(), orientation='vertical',fraction=0.046, pad=0.09,extend='both')\n cbar.ax.tick_params(labelsize=18)\n plt.suptitle('plev = {0}hPa'.format(p))\n plt.savefig('../plots/wavenumber_analysis/ver_adv/{3}_{0:02d}_{1:02d}Z_{2}hPa.png'.format(dd,hr,int(p),'horadv'),dpi=100,bbox_inches='tight')\n plt.close()\n# plt.show()\n j+=1\n\nif __name__=='__main__':\n main()\n","sub_path":"plot_wavenumber_components.py","file_name":"plot_wavenumber_components.py","file_ext":"py","file_size_in_byte":4315,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"441824490","text":"# uncompyle6 version 3.7.4\n# Python bytecode 3.5 (3351)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: E:\\2.3BranchA\\ToolBox\\PythonToolBox\\atquant\\run_mode\\trader_run_back_test.py\n# Compiled at: 2018-08-27 20:45:24\n# Size of source mod 2**32: 46031 bytes\nimport datetime, os, traceback, types, scipy.io as sio, atquant.at_algorithm.core_algorithm as CORE_ALGO, atquant.socket_ctrl.tool_box_command as tb_command\nfrom atquant import api\nfrom atquant.account.account_checker import AccountChecker\nfrom atquant.socket_ctrl import base_socket\nfrom atquant.trade.back_test_trade import *\nfrom atquant.utils.arg_checker import ArgumnetChecker, ATInvalidArgument\nfrom atquant.utils.arg_checker import verify_that, apply_rule\nfrom atquant.utils.datetime_func import change_to_y_M_D_H_m_s\nfrom atquant.utils.datetime_func import check_begindate_enddate\nfrom atquant.utils.datetime_func import matlab_float_time_to_str_date, matlab_float_time_to_datetime\nfrom atquant.utils.internal_exception import ToolBoxErrors\nfrom atquant.utils.internal_util import SimpleTimer\nfrom atquant.utils.internal_util import append_or_assign_2d_array_axis0\nfrom atquant.utils.internal_util import trace_time\nfrom atquant.utils.logger import write_syslog, write_userlog\nfrom atquant.utils.user_class import dotdict\n\n@apply_rule(verify_that('StrategyName').is_instance_of(str), verify_that('TradeFun').is_instance_of(types.FunctionType), verify_that('varFunParameter').is_instance_of(tuple), verify_that('AccountList').is_instance_of(list).is_empty_or_not(empty=False), verify_that('TargetList').is_instance_of(list).is_empty_or_not(empty=False), verify_that('KFrequency').is_valid_frequency(), verify_that('KFreNum').is_instance_of(int).is_greater_or_equal_than(1), verify_that('BeginDate').is_valid_date(), verify_that('EndDate').is_valid_date(), verify_that('FQ').is_valid_fq())\ndef traderRunBacktestV2(StrategyName, TradeFun, varFunParameter, AccountList, TargetList, KFrequency, KFreNum, BeginDate, EndDate, FQ, *args):\n \"\"\"\n 主回测函数\n \"\"\"\n try:\n try:\n write_syslog('Begin Prepare traderRunBacktestV2', level='info', trace_debug=True)\n TradeFun = trace_time(TradeFun)\n if GVAR.g_ATraderRegisterRealK:\n ToolBoxErrors.not_support_error(const_da.Enum_Const.ERROR_NOTSUPPORT_WHEN_REALMODE.value)\n if len(AccountList) > 1:\n raise ValueError(const_da.Enum_Const.ERROR_NOTSUPPORT_MULTI_ACCOUNT_BACKTESTMODE.value)\n ArgumnetChecker.is_algorithm_func_and_args(traderRunBacktestV2.__name__, *args)\n check_begindate_enddate(BeginDate, EndDate)\n AccountChecker.check_run_back_test_account(AccountList)\n TargetList = GVAR.atRemoveInvalidTarget(TargetList)\n GVAR.g_ATraderAccountOrderMode = 0\n GVAR.atResetAlgorithmTradeMode()\n GVAR.rm_root_sub_dir('record')\n if len(args) > 0:\n raise Exception('TODO it')\n GVAR.generatingStrategyName(StrategyName)\n base_socket.atClearAllTCPIP()\n mode = tb_command.atSendCmdGetCurMode()\n ToolBoxErrors.at_mode_error(mode, 'backtest')\n api.traderSetMarketOrderHoldingType(False)\n except ATInvalidArgument as e:\n write_userlog(traceback.format_exc(), level='error', console=traceback.format_exc())\n return\n except Exception as e:\n write_syslog(traceback.format_exc(), level='error', console=traceback.format_exc())\n return\n\n finally:\n write_syslog('End Prepare traderRunBacktestV2', level='info', trace_debug=True)\n\n try:\n try:\n use_time = SimpleTimer('traderRunBacktestV2', 'sec')\n GVAR.atResetRealMode()\n GVAR.atResetBackTestMode()\n GVAR.atResetAlgoOrderSignal()\n GVAR.atResetAlgorithmTradeMode()\n GVAR.atResetDailyCloseTimeSetting()\n GVAR.atResetOrderMode()\n GVAR.atSetBackTestFinished(True)\n tb_command.at_send_ATraderStartBackTest(TargetList, KFrequency, KFreNum, BeginDate, EndDate, GVAR.g_ATraderStrategyName)\n write_syslog('Begin StraRunInitV2', level='info', trace_debug=True)\n atStraRunInitV2(AccountList, TargetList, KFrequency, KFreNum, BeginDate, EndDate, FQ)\n write_syslog('End StraRunInitV2', level='info', trace_debug=True)\n write_syslog('Begin TradeFunInit', level='info', trace_debug=True)\n TradeFun(True, False, varFunParameter)\n write_syslog('End TradeFunInit', level='info', trace_debug=True)\n GVAR.atEnterBackTestMode()\n GVAR.atEnterDataFreshMode()\n write_syslog('Begin BackTestLoopV2', level='info', trace_debug=True)\n atBackTestLoopV2(TradeFun, varFunParameter)\n write_syslog('Begin BackTestLoopV2', level='info', trace_debug=True)\n except Exception as e:\n write_syslog(traceback.format_exc(), level='error', console=traceback.format_exc())\n\n finally:\n print('回测完毕, 正在处理绩效报告, 请稍等...')\n write_syslog('Begin Clean', level='info', trace_debug=True)\n clear_up()\n write_syslog('End Clean', level='info', trace_debug=True)\n msg = '回测总耗时 %d 秒' % use_time.total()\n write_userlog(msg, level='info', console=None)\n print(msg)\n\n\ndef atBackTestLoopV2(TradeFun, varFunParameter):\n curSimDay = 0\n for timeLineNum in range(GVAR.g_ATraderDataValueFresh.shape[1]):\n GVAR.atSetATraderSimCurBarFresh(timeLineNum)\n curFreshBartime = GVAR.g_ATraderDataValueFresh[(GACV.KMatrixPos_TimeLine, GVAR.g_ATraderSimCurBarFresh)]\n cD = int(np.floor(curFreshBartime))\n if curSimDay != cD:\n Log = 'Test day:%s' % datetime.datetime.fromordinal(cD - 366).strftime('%Y-%m-%d')\n tb_command.at_send_cmd_TraderPutLog(GVAR.g_ATraderAccountHandleArray[0], GVAR.g_ATraderStrategyName, Log)\n curSimDay = cD\n if GVAR.g_ATraderStraInputInfo.KFrequencyI <= GACV.KFreq_Min:\n if timeLineNum == 0:\n bDayBegin = True\n clearUnfilledOrder = True\n else:\n preBar = int(GVAR.g_ATraderKDatas[0].CurrentBar[(timeLineNum - 1)])\n curBar = int(GVAR.g_ATraderKDatas[0].CurrentBar[timeLineNum])\n _r = np.where(GVAR.g_ATraderKDatas[0].Matrix[GACV.KMatrixPos_DayPos, preBar + 1:curBar + 1] == 1)[0]\n _t = True if _r.size > 0 else False\n bDayBegin = _t\n clearUnfilledOrder = _t\n else:\n bDayBegin = True\n clearUnfilledOrder = False\n if timeLineNum > 0 and (GVAR.atBeInDirectOrderMode() or GVAR.atBeInUnsetOrderMode()):\n if clearUnfilledOrder:\n ClearUnfilledOrder()\n else:\n DealTrade()\n TradeFun(False, bDayBegin, varFunParameter)\n if GVAR.atBeInConfigurationOrderMode():\n DealTradeConfig()\n\n\ndef clear_up():\n \"\"\"\n 退出函数:如果遇异常可以保证AT不挂死,如果正常退出则返回交易结果 \n \"\"\"\n normalFinished = GVAR.atIsBackTestNormalFinished()\n if normalFinished:\n try:\n if GVAR.atBeInDirectOrderMode() or GVAR.atBeInUnsetOrderMode():\n OrderTrans2()\n elif GVAR.atBeInConfigurationOrderMode():\n ConfigTrans()\n except Exception as e:\n write_syslog(traceback.format_exc(), level='error', console=str(e))\n\n try:\n tb_command.at_send_cmd_ATraderStopBackTest(normalFinished)\n GVAR.atResetBackTestMode()\n GVAR.atResetAlgorithmTradeMode()\n GVAR.atResetBackTestSetting()\n GVAR.atResetAlgoOrderSignal()\n GVAR.atResetDailyCloseTimeSetting()\n GVAR.g_ATraderOrderNum = 0\n GVAR.g_ATraderStopOrderNum = 0\n GVAR.g_ATraderAlgoOrderNum = 0\n GVAR.g_ATraderStopMode = 0\n GVAR.g_ATraderSimStopOrders = np.array([])\n GVAR.g_ATraderSimStopOrdersHolding = np.array([])\n GVAR.g_ATraderCurTickInfo = np.array([])\n GVAR.g_ATraderSimTrades = np.array([])\n GVAR.g_ATraderSimKDataValue = np.array([])\n GVAR.g_ATraderSimKDataKey = np.array([])\n GVAR.g_ATraderStraInputInfo.TargetList = []\n GVAR.g_ATraderDataValueFreshUserD = np.array([])\n except Exception as e:\n write_syslog(traceback.format_exc(), level='error', console=str(e))\n\n\ndef atStraRunInitV2(AccountList, TargetList, KFrequency, KFreNum, BeginDate, EndDate, FQ):\n \"\"\"\n 回测时初始化基础数据的主入口\n \"\"\"\n const_da.atDefineConst()\n GVAR.g_ATraderStraInputInfo.TargetList = TargetList\n GVAR.g_ATraderStraInputInfo.KFrequency = KFrequency\n GVAR.g_ATraderStraInputInfo.KFreNum = KFreNum\n GVAR.g_ATraderStraInputInfo.BeginDate = BeginDate\n GVAR.g_ATraderStraInputInfo.EndDate = EndDate\n GVAR.g_ATraderStraInputInfo.FQ = FQ\n GVAR.g_ATraderStraInputInfo.KFrequencyI = const_da.atStringToConst('KBaseFreq', KFrequency)\n if GVAR.atExistBackTestSetting():\n InitialCash = GVAR.g_AtraderSetInfo.InitialCash\n Costfee = GVAR.g_AtraderSetInfo.Costfee\n GVAR.g_ATraderSlidePrice = GVAR.g_AtraderSetInfo.SlidePrice\n GVAR.g_ATraderPriceLoc = GVAR.g_AtraderSetInfo.PriceLoc\n GVAR.g_ATraderLimitType = GVAR.g_AtraderSetInfo.LimitType\n else:\n InitialCash = 10000000.0\n Costfee = float('nan')\n GVAR.g_ATraderSlidePrice = 0\n GVAR.g_ATraderLimitType = 0\n GVAR.g_ATraderPriceLoc = 1\n GVAR.g_ATraderStraInputInfo.FreshMatrixIdx = 0 if KFreNum == 1 else 1\n api.traderAppendKDataScope(KFrequency, 0, True)\n base0_matrix = GVAR.g_ATraderKDatas[0].Matrix\n if KFreNum == 1:\n _t = GACV.KMatrixPos_TimeLine\n GVAR.g_ATraderDataValueFresh = append_or_assign_2d_array_axis0(GVAR.g_ATraderDataValueFresh, base0_matrix[_t], _t)\n base0_matrix = append_or_assign_2d_array_axis0(base0_matrix, np.array([[1] * len(base0_matrix[_t])]), GACV.KMatrixPos_FreshIdx)\n GVAR.g_ATraderKDatas[0].CurrentBar = CORE_ALGO.atFillKMatrixFreshBar(GVAR.atGetBaseMx(0))\n GVAR.g_ATraderKDatas[0].Matrix = base0_matrix\n else:\n idxFreshArray = CORE_ALGO.atCalculateReshIdxArray(base0_matrix, KFreNum)\n GVAR.g_ATraderDataValueFresh = append_or_assign_2d_array_axis0(GVAR.g_ATraderDataValueFresh, base0_matrix[(GACV.KMatrixPos_TimeLine, idxFreshArray)], GACV.KMatrixPos_TimeLine)\n base0_matrix = append_or_assign_2d_array_axis0(base0_matrix, idxFreshArray.astype(np.int), GACV.KMatrixPos_FreshIdx)\n GVAR.g_ATraderKDatas[0].CurrentBar = CORE_ALGO.atFillKMatrixFreshBar(GVAR.atGetBaseMx(0))\n GVAR.g_ATraderKDatas[0].Matrix = base0_matrix\n api.traderRegKData(KFrequency, KFreNum)\n api.init_set.atInitTargetInfo(Costfee)\n GVAR.g_ATraderAccountMatrix = np.zeros((len(GVAR.g_ATraderAccountHandleArray),\n len(GVAR.g_ATraderStraInputInfo.TargetList) + 1,\n GVAR.atACItemsLen()))\n GVAR.g_ATraderAccountMatrix[:, 0, GACV.ACMatrix_ValidCash] = InitialCash\n GVAR.g_ATraderAccountMatrix[:, 0, GACV.ACMatrix_OrderFrozen] = 0\n GVAR.g_ATraderAccountMatrix[:, 0, GACV.ACMatrix_MarginFrozen] = 0\n GVAR.g_ATraderAccountConfigMatrix = np.zeros((len(GVAR.g_ATraderAccountHandleArray),\n len(GVAR.g_ATraderStraInputInfo.TargetList),\n len(GVAR.g_ATraderDataValueFresh[GACV.KMatrixPos_TimeLine])))\n\n\ndef OrderTrans2():\n \"\"\"\n 将所有的下单记录,以及成交记录,止盈止损单记录,存贮在本地文件中,提供给AT进行分析\n \"\"\"\n record_dir = GVAR.cls_root_sub_dir('record')\n\n def _MC(index):\n return (\n GVAR.g_ATraderStraInputInfo.TargetList[index]['Market'],\n GVAR.g_ATraderStraInputInfo.TargetList[index]['Code'])\n\n def _PATH(index, suffix):\n market, code = _MC(index)\n _t = '%s_%s_%s.mat' % (market, code, suffix)\n _path = os.path.join(record_dir, _t)\n return _path\n\n temp_dict = dotdict({'allmxOrderTargetIdx': np.array([]), \n 'allmxOrderID': np.array([]), \n 'allmxOrderStatus': np.array([]), \n 'allmxOrderTime': np.array([]), \n 'allmxOrderFilledTime': np.array([]), \n 'allmxOrderContract': np.array([]), \n 'allmxOrderPrice': np.array([]), \n 'allmxOrderCtg': np.array([]), \n 'allmxOrderAct': np.array([]), \n 'allmxOrderOffsetFlag': np.array([])})\n if GVAR.g_ATraderSimOrders.size > 0:\n temp_dict.allmxOrderTargetIdx = GVAR.g_ATraderSimOrders[GACV.SimOrder_TargetIdx]\n temp_dict.allmxOrderID = GVAR.g_ATraderSimOrders[GACV.SimOrder_OrderID] + 1\n temp_dict.allmxOrderStatus = GVAR.g_ATraderSimOrders[GACV.SimOrder_Status]\n temp_dict.allmxOrderTime = change_inttime_to_y_M_D_H_m_s(GVAR.g_ATraderSimOrders[GACV.SimOrder_OrderTime])\n temp_dict.allmxOrderFilledTime = change_inttime_to_y_M_D_H_m_s(GVAR.g_ATraderSimOrders[GACV.SimOrder_FilledTime])\n temp_dict.allmxOrderContract = GVAR.g_ATraderSimOrders[GACV.SimOrder_Contracts]\n temp_dict.allmxOrderPrice = GVAR.g_ATraderSimOrders[GACV.SimOrder_Price]\n temp_dict.allmxOrderCtg = GVAR.g_ATraderSimOrders[GACV.SimOrder_OrderCtg]\n temp_dict.allmxOrderAct = GVAR.g_ATraderSimOrders[GACV.SimOrder_OrderAct]\n temp_dict.allmxOrderOffsetFlag = GVAR.g_ATraderSimOrders[GACV.SimOrder_OffsetFlag]\n file_name = os.path.join(record_dir, 'orders.mat')\n sio.savemat(file_name, temp_dict)\n temp_dict = dotdict({'allmxTradeTargetIdx': np.array([]), \n 'allmxTradeID': np.array([]), \n 'allmxTradeTime': np.array([]), \n 'allmxTradeContract': np.array([]), \n 'allmxTradePrice': np.array([]), \n 'allmxTradeCtg': np.array([]), \n 'allmxTradeAct': np.array([]), \n 'allmxTradeOffsetFlag': np.array([])})\n if GVAR.g_ATraderSimTrades.size > 0:\n temp_dict.allmxTradeTargetIdx = GVAR.g_ATraderSimTrades[GACV.SimTrade_TargetIdx]\n temp_dict.allmxTradeID = GVAR.g_ATraderSimTrades[GACV.SimTrade_OrderID] + 1\n temp_dict.allmxTradeTime = change_inttime_to_y_M_D_H_m_s(GVAR.g_ATraderSimTrades[GACV.SimTrade_FilledTime])\n temp_dict.allmxTradeContract = GVAR.g_ATraderSimTrades[GACV.SimTrade_Contracts]\n temp_dict.allmxTradePrice = GVAR.g_ATraderSimTrades[GACV.SimTrade_Price]\n temp_dict.allmxTradeCtg = GVAR.g_ATraderSimTrades[GACV.SimTrade_OrderCtg]\n temp_dict.allmxTradeAct = GVAR.g_ATraderSimTrades[GACV.SimTrade_OrderAct]\n temp_dict.allmxTradeOffsetFlag = GVAR.g_ATraderSimTrades[GACV.SimTrade_OffsetFlag]\n file_name = os.path.join(record_dir, 'trades.mat')\n sio.savemat(file_name, temp_dict)\n temp_dict = dotdict({'allmxSOTargetIdx': np.array([]), \n 'allmxSOStatus': np.array([]), \n 'allmxSOStopOrderType': np.array([]), \n 'allmxSOStopType': np.array([]), \n 'allmxSOTrailingType': np.array([]), \n 'allmxSOOrderAct': np.array([]), \n 'allmxSOOrderCtg': np.array([]), \n 'allmxSOTargetID': np.array([]), \n 'allmxSOClientID': np.array([]), \n 'allmxSOTargetPrice': np.array([]), \n 'allmxSOTrailingHigh': np.array([]), \n 'allmxSOTrailingLow': np.array([]), \n 'allmxSOEntryTime': np.array([]), \n 'allmxSOFireTime': np.array([]), \n 'allmxSOStopGap': np.array([]), \n 'allmxSOTrailingGap': np.array([]), \n 'allmxSOContracts': np.array([]), \n 'allmxSOBeginTrailingPrice': np.array([]), \n 'allmxSOStopTrailingPrice': np.array([]), \n 'allmxSOMPrice': np.array([])})\n if GVAR.g_ATraderSimStopOrders.size > 0:\n temp_dict.allmxSOTargetIdx = GVAR.g_ATraderSimStopOrders[GACV.SimStopOrder_TargetIdx]\n temp_dict.allmxSOStatus = GVAR.g_ATraderSimStopOrders[GACV.SimStopOrder_Status]\n temp_dict.allmxSOStopOrderType = GVAR.g_ATraderSimStopOrders[GACV.SimStopOrder_StopOrderType]\n temp_dict.allmxSOStopType = GVAR.g_ATraderSimStopOrders[GACV.SimStopOrder_StopGapType]\n temp_dict.allmxSOTrailingType = GVAR.g_ATraderSimStopOrders[GACV.SimStopOrder_TrailingType]\n temp_dict.allmxSOOrderAct = GVAR.g_ATraderSimStopOrders[GACV.SimStopOrder_OrderAct]\n temp_dict.allmxSOOrderCtg = GVAR.g_ATraderSimStopOrders[GACV.SimStopOrder_OrderCtg]\n temp_dict.allmxSOClientID = GVAR.g_ATraderSimStopOrders[GACV.SimStopOrder_ClientID]\n temp_dict.allmxSOTargetID = GVAR.g_ATraderSimStopOrders[GACV.SimStopOrder_TargetOrderID]\n temp_dict.allmxSOTargetPrice = GVAR.g_ATraderSimStopOrders[GACV.SimStopOrder_TargetPrice]\n temp_dict.allmxSOTrailingHigh = GVAR.g_ATraderSimStopOrders[GACV.SimStopOrder_TrailingHigh]\n temp_dict.allmxSOTrailingLow = GVAR.g_ATraderSimStopOrders[GACV.SimStopOrder_TrailingLow]\n temp_dict.allmxSOEntryTime = change_inttime_to_y_M_D_H_m_s(GVAR.g_ATraderSimStopOrders[GACV.SimStopOrder_EntryTime])\n temp_dict.allmxSOFireTime = change_inttime_to_y_M_D_H_m_s(GVAR.g_ATraderSimStopOrders[GACV.SimStopOrder_FireTime])\n temp_dict.allmxSOStopGap = GVAR.g_ATraderSimStopOrders[GACV.SimStopOrder_StopGap]\n temp_dict.allmxSOTrailingGap = GVAR.g_ATraderSimStopOrders[GACV.SimStopOrder_TrailingGap]\n temp_dict.allmxSOContracts = GVAR.g_ATraderSimStopOrders[GACV.SimStopOrder_Contracts]\n temp_dict.allmxSOBeginTrailingPrice = GVAR.g_ATraderSimStopOrders[GACV.SimStopOrder_BeginTrailingPrice]\n temp_dict.allmxSOStopTrailingPrice = GVAR.g_ATraderSimStopOrders[GACV.SimStopOrder_StopTrailingPrice]\n temp_dict.allmxSOMPrice = GVAR.g_ATraderSimStopOrders[GACV.SimStopOrder_MPrice]\n file_name = os.path.join(record_dir, 'stoporders.mat')\n sio.savemat(file_name, temp_dict)\n df = api.traderGetTargetInfoV2(0)\n temp_dict = dotdict({'Margin': np.array([]), \n 'Multiple': np.array([]), \n 'InitialCash': np.array([]), \n 'Costfee': np.array([]), \n 'Rate': np.array([]), \n 'SlidePrice': np.array([]), \n 'InitialCash': GVAR.g_AtraderSetInfo.get('InitialCash', 10000000.0) + 0.0, \n 'Costfee': GVAR.g_AtraderSetInfo.get('Costfee', df.loc[('TradingFeeOpen', 0)]), \n 'Rate': GVAR.g_AtraderSetInfo.get('Rate', 0.02), \n 'SlidePrice': GVAR.g_AtraderSetInfo.get('SlidePrice', 0), \n 'Margin': df.loc[('LongMargin', 0)], \n 'Multiple': df.loc[('Multiple', 0)]})\n file_name = os.path.join(record_dir, 'Info.mat')\n sio.savemat(file_name, temp_dict)\n\n\ndef ConfigTrans():\n \"\"\"记录配置下单矩阵传回给at\"\"\"\n GVAR.cls_root_sub_dir('record')\n record_dir = GVAR.root_sub_dir('record')\n mxTimeLine = change_inttime_to_y_M_D_H_m_s(GVAR.g_ATraderDataValueFresh[GACV.KMatrixPos_TimeLine])\n temp_dict = {'mxTimeLine': mxTimeLine}\n file_name = os.path.join(record_dir, 'config_timeline.mat')\n sio.savemat(file_name, temp_dict)\n targetsLen = len(GVAR.g_ATraderStraInputInfo.TargetList)\n _matrix = GVAR.g_ATraderKDatas[GVAR.g_ATraderStraInputInfo.FreshMatrixIdx].Matrix\n temp_dict = dotdict({'mxTarget': np.empty((targetsLen,), dtype=np.object), \n 'mxConfig': np.empty((targetsLen,), dtype=np.object), \n 'mxOpen': np.empty((targetsLen,), dtype=np.object), \n 'mxHigh': np.empty((targetsLen,), dtype=np.object), \n 'mxLow': np.empty((targetsLen,), dtype=np.object), \n 'mxClose': np.empty((targetsLen,), dtype=np.object)})\n for i in range(targetsLen):\n temp_dict.mxTarget[i] = '%s_%s' % (GVAR.g_ATraderStraInputInfo.TargetList[i]['Market'],\n GVAR.g_ATraderStraInputInfo.TargetList[i]['Code'])\n temp_dict.mxConfig[i] = np.array(GVAR.g_ATraderAccountConfigMatrix[0, i, :]).reshape(1, -1)\n temp_dict.mxOpen[i] = _matrix[GVAR.atKMatixBarItemPos(GACV.KMatrix_Open, i, contain_head=True)]\n temp_dict.mxHigh[i] = _matrix[GVAR.atKMatixBarItemPos(GACV.KMatrix_High, i, contain_head=True)]\n temp_dict.mxLow[i] = _matrix[GVAR.atKMatixBarItemPos(GACV.KMatrix_Low, i, contain_head=True)]\n temp_dict.mxClose[i] = _matrix[GVAR.atKMatixBarItemPos(GACV.KMatrix_Close, i, contain_head=True)]\n\n file_name = os.path.join(record_dir, 'configs.mat')\n sio.savemat(file_name, temp_dict)\n if GVAR.g_AtraderSetInfo:\n InitialCash = GVAR.g_AtraderSetInfo['InitialCash']\n Rate = GVAR.g_AtraderSetInfo['Rate']\n SlidePrice = GVAR.g_AtraderSetInfo['SlidePrice']\n else:\n InitialCash = 100000000\n Rate = 0.02\n SlidePrice = 0\n file_name = os.path.join(record_dir, 'Info.mat')\n sio.savemat(file_name, {'InitialCash': InitialCash, 'Rate': Rate, 'SlidePrice': SlidePrice})\n\n\ndef DealTradeConfig():\n \"\"\"处理配置交易的逻辑\"\"\"\n if GVAR.g_ATraderAccountConfigMatrix.size > 0 and GVAR.g_ATraderSimCurBarFresh > 0:\n GVAR.g_ATraderAccountConfigMatrix[:, :, GVAR.g_ATraderSimCurBarFresh] = GVAR.g_ATraderAccountConfigMatrix[:, :, GVAR.g_ATraderSimCurBarFresh - 1]\n if len(GVAR.g_ATraderAccountConfigBarOper) > 0:\n temp_bar_fresh = GVAR.g_ATraderSimCurBarFresh\n global_config_operation = GVAR.g_ATraderAccountConfigBarOper\n for i in range(len(GVAR.g_ATraderAccountConfigBarOper)):\n setTarget = GVAR.g_ATraderAccountConfigBarOper[i]['TargetIdx'] == 1\n if np.sum(setTarget) == 0:\n continue\n temp_handle = GVAR.g_ATraderAccountConfigBarOper[i]['HandleIdx']\n GVAR.g_ATraderAccountConfigMatrix[(temp_handle, setTarget, temp_bar_fresh)] = global_config_operation[i]['Config'][setTarget]\n\n GVAR.g_ATraderAccountConfigBarOper = []\n\n\ndef JudgeStopOrdersByBar(barHigh, barLow, Position, sameTargetStopOrdersPos):\n \"\"\"\n :param barHigh: \n :param barLow: \n :param Position: float,持仓量\n :param sameTargetStopOrdersPos: numpy.ndarray\n :return: \n \"\"\"\n mayFirePos = np.array([], dtype=np.int)\n mustTickCheckPos = np.array([], dtype=np.int)\n cancelledStopOrderPos = []\n for stopOrderPos in sameTargetStopOrdersPos:\n stopOrderPos = int(stopOrderPos)\n if GVAR.g_ATraderSimUnfiredStopOrders[(GACV.SimStopOrder_Status, stopOrderPos)] == GACV.StopOrderStatus_PreHolding:\n pass\n elif Position == 0:\n GVAR.g_ATraderSimUnfiredStopOrders[(GACV.SimStopOrder_Status, stopOrderPos)] = GACV.StopOrderStatus_Cancelled\n _t = GVAR.g_ATraderSimUnfiredStopOrders[:, stopOrderPos].reshape((-1, 1))\n GVAR.g_ATraderSimStopOrders = UTILS_UTIL.append_or_assign_2d_array_axis1(GVAR.g_ATraderSimStopOrders, _t, GVAR.g_ApendEnoughConstNum)\n cancelledStopOrderPos.append(stopOrderPos)\n continue\n orderAct = int(GVAR.g_ATraderSimUnfiredStopOrders[(GACV.SimStopOrder_OrderAct, stopOrderPos)])\n _type = int(GVAR.g_ATraderSimUnfiredStopOrders[(GACV.SimStopOrder_StopOrderType, stopOrderPos)])\n if _type == GACV.StopOrderType_Loss:\n if GVAR.g_ATraderSimUnfiredStopOrders[(GACV.SimStopOrder_OrderAct, stopOrderPos)] == GACV.OrderAct_Buy:\n if barLow <= GVAR.g_ATraderSimUnfiredStopOrders[(GACV.SimStopOrder_MPrice, stopOrderPos)]:\n mayFirePos = np.append(mayFirePos, [stopOrderPos], axis=0)\n elif GVAR.g_ATraderSimUnfiredStopOrders[(GACV.SimStopOrder_OrderAct, stopOrderPos)] == GACV.OrderAct_Sell and barHigh >= GVAR.g_ATraderSimUnfiredStopOrders[(GACV.SimStopOrder_MPrice, stopOrderPos)]:\n mayFirePos = np.append(mayFirePos, [stopOrderPos], axis=0)\n else:\n if _type == GACV.StopOrderType_Profit:\n if GVAR.g_ATraderSimUnfiredStopOrders[(GACV.SimStopOrder_OrderAct, stopOrderPos)] == GACV.OrderAct_Buy:\n if barHigh >= GVAR.g_ATraderSimUnfiredStopOrders[(GACV.SimStopOrder_MPrice, stopOrderPos)]:\n mayFirePos = np.append(mayFirePos, [stopOrderPos], axis=0)\n elif GVAR.g_ATraderSimUnfiredStopOrders[(GACV.SimStopOrder_OrderAct, stopOrderPos)] == GACV.OrderAct_Sell and barLow <= GVAR.g_ATraderSimUnfiredStopOrders[(GACV.SimStopOrder_MPrice, stopOrderPos)]:\n mayFirePos = np.append(mayFirePos, [stopOrderPos], axis=0)\n elif _type == GACV.StopOrderType_Trailing:\n beginTrailingPrice = GVAR.g_ATraderSimUnfiredStopOrders[(GACV.SimStopOrder_BeginTrailingPrice, stopOrderPos)]\n stopGapType = GVAR.g_ATraderSimUnfiredStopOrders[(GACV.SimStopOrder_StopGapType, stopOrderPos)]\n stopGap = GVAR.g_ATraderSimUnfiredStopOrders[(GACV.SimStopOrder_StopGap, stopOrderPos)]\n targetPrice = GVAR.g_ATraderSimUnfiredStopOrders[(GACV.SimStopOrder_TargetPrice, stopOrderPos)]\n if GVAR.g_ATraderSimUnfiredStopOrders[(GACV.SimStopOrder_IsBeginTrailing, stopOrderPos)] == 0:\n if orderAct == GACV.OrderAct_Buy and barHigh >= beginTrailingPrice or orderAct == GACV.OrderAct_Sell and barLow <= beginTrailingPrice:\n if GVAR.g_ATraderSimUnfiredStopOrders[(GACV.SimStopOrder_InBarBegin, stopOrderPos)] == 0:\n mustTickCheckPos = np.append(mustTickCheckPos, [stopOrderPos], axis=0)\n continue\n GVAR.g_ATraderSimUnfiredStopOrders[(GACV.SimStopOrder_IsBeginTrailing, stopOrderPos)] = True\n GVAR.g_ATraderSimUnfiredStopOrders[(GACV.SimStopOrder_InBeginTrailingBar, stopOrderPos)] = True\n GVAR.g_ATraderSimUnfiredStopOrders[(GACV.SimStopOrder_TrailingHigh, stopOrderPos)] = beginTrailingPrice\n GVAR.g_ATraderSimUnfiredStopOrders[(GACV.SimStopOrder_TrailingLow, stopOrderPos)] = beginTrailingPrice\n if orderAct == GACV.OrderAct_Buy:\n basePrice = GVAR.g_ATraderSimUnfiredStopOrders[(GACV.SimStopOrder_TrailingHigh, stopOrderPos)]\n stopGapDirection = -1\n else:\n if orderAct == GACV.OrderAct_Sell:\n basePrice = GVAR.g_ATraderSimUnfiredStopOrders[(GACV.SimStopOrder_TrailingLow, stopOrderPos)]\n stopGapDirection = 1\n elif not False:\n raise AssertionError\n if stopGapType == GACV.StopGapType_Point:\n GVAR.g_ATraderSimUnfiredStopOrders[(GACV.SimStopOrder_StopTrailingPrice, stopOrderPos)] = basePrice + stopGapDirection * stopGap\n else:\n if stopGapType == GACV.StopGapType_Percent:\n temp_stopGap = stopGap / 100.0\n GVAR.g_ATraderSimUnfiredStopOrders[(GACV.SimStopOrder_StopTrailingPrice, stopOrderPos)] = (1 - temp_stopGap) * basePrice + temp_stopGap * targetPrice\n elif not False:\n raise AssertionError\n else:\n continue\n if orderAct == GACV.OrderAct_Buy:\n if barHigh > GVAR.g_ATraderSimUnfiredStopOrders[(GACV.SimStopOrder_TrailingHigh, stopOrderPos)]:\n if stopGapType == GACV.StopGapType_Point:\n tempStopTrailingPrice = barHigh - stopGap\n else:\n if stopGapType == GACV.StopGapType_Percent:\n tempStopTrailingPrice = barHigh - (barHigh - targetPrice) * stopGap / 100.0\n elif not False:\n raise AssertionError\n if barLow <= tempStopTrailingPrice:\n mustTickCheckPos = np.append(mustTickCheckPos, [stopOrderPos], axis=0)\n continue\n else:\n GVAR.g_ATraderSimUnfiredStopOrders[(GACV.SimStopOrder_TrailingHigh, stopOrderPos)] = barHigh\n GVAR.g_ATraderSimUnfiredStopOrders[(GACV.SimStopOrder_StopTrailingPrice, stopOrderPos)] = tempStopTrailingPrice\n else:\n if barLow <= GVAR.g_ATraderSimUnfiredStopOrders[(GACV.SimStopOrder_StopTrailingPrice, stopOrderPos)]:\n if bool(GVAR.g_ATraderSimUnfiredStopOrders[(GACV.SimStopOrder_InBeginTrailingBar, stopOrderPos)]):\n mustTickCheckPos = np.append(mustTickCheckPos, [stopOrderPos], axis=0)\n else:\n GVAR.g_ATraderSimUnfiredStopOrders[(GACV.SimStopOrder_TrailingLow, stopOrderPos)] = min(GVAR.g_ATraderSimUnfiredStopOrders[(GACV.SimStopOrder_TrailingLow, stopOrderPos)], GVAR.g_ATraderSimUnfiredStopOrders[(GACV.SimStopOrder_StopTrailingPrice, stopOrderPos)])\n mayFirePos = np.append(mayFirePos, [stopOrderPos], axis=0)\n continue\n if barLow < GVAR.g_ATraderSimUnfiredStopOrders[(GACV.SimStopOrder_TrailingLow, stopOrderPos)]:\n GVAR.g_ATraderSimUnfiredStopOrders[(GACV.SimStopOrder_TrailingLow, stopOrderPos)] = barLow\n else:\n if orderAct == GACV.OrderAct_Sell:\n if barLow < GVAR.g_ATraderSimUnfiredStopOrders[(GACV.SimStopOrder_TrailingLow, stopOrderPos)]:\n if stopGapType == GACV.StopGapType_Point:\n tempStopTrailingPrice = barLow + stopGap\n else:\n if stopGapType == GACV.StopGapType_Percent:\n tempStopTrailingPrice = barLow + (targetPrice - barLow) * stopGap / 100.0\n elif not False:\n raise AssertionError\n if barHigh >= tempStopTrailingPrice:\n mustTickCheckPos = np.append(mustTickCheckPos, [stopOrderPos], axis=0)\n continue\n else:\n GVAR.g_ATraderSimUnfiredStopOrders[(GACV.SimStopOrder_TrailingLow, stopOrderPos)] = barHigh\n GVAR.g_ATraderSimUnfiredStopOrders[(GACV.SimStopOrder_StopTrailingPrice, stopOrderPos)] = tempStopTrailingPrice\n else:\n if barHigh >= GVAR.g_ATraderSimUnfiredStopOrders[(GACV.SimStopOrder_StopTrailingPrice, stopOrderPos)]:\n if bool(GVAR.g_ATraderSimUnfiredStopOrders[(GACV.SimStopOrder_InBeginTrailingBar, stopOrderPos)]):\n mustTickCheckPos = np.append(mustTickCheckPos, [stopOrderPos], axis=0)\n else:\n GVAR.g_ATraderSimUnfiredStopOrders[(GACV.SimStopOrder_TrailingHigh, stopOrderPos)] = max(GVAR.g_ATraderSimUnfiredStopOrders[(GACV.SimStopOrder_TrailingHigh, stopOrderPos)], GVAR.g_ATraderSimUnfiredStopOrders[(GACV.SimStopOrder_StopTrailingPrice, stopOrderPos)])\n mayFirePos = np.append(mayFirePos, [stopOrderPos], axis=0)\n continue\n if barHigh > GVAR.g_ATraderSimUnfiredStopOrders[(GACV.SimStopOrder_TrailingHigh, stopOrderPos)]:\n GVAR.g_ATraderSimUnfiredStopOrders[(GACV.SimStopOrder_TrailingHigh, stopOrderPos)] = barHigh\n elif not False:\n raise AssertionError\n else:\n if not False:\n raise AssertionError\n\n GVAR.g_ATraderSimUnfiredStopOrders = np.delete(GVAR.g_ATraderSimUnfiredStopOrders, np.asarray(cancelledStopOrderPos, dtype=np.int), axis=1)\n return (mayFirePos, mustTickCheckPos)\n\n\ndef JudgeStopOrdersByTick(stopOrdersPos):\n \"\"\"\n :param stopOrdersPos: 包含多个止盈止损的订单索引\n :return: theFireOnePos(N,), tickBarOpen(N,), tickBarHigh(N,), tickBarLow(N,), tickBarVol(N,)\n \"\"\"\n theFireOnePos = np.array([])\n tickBarOpen = np.array([])\n tickBarHigh = np.array([])\n tickBarLow = np.array([])\n tickBarVol = np.array([])\n _idx = GVAR.g_ATraderStraInputInfo.FreshMatrixIdx\n curbarfresh = GVAR.g_ATraderKDatas[_idx].CurrentBar[GVAR.g_ATraderSimCurBarFresh]\n curBarTime = GVAR.g_ATraderKDatas[_idx].Matrix[(GACV.KMatrixPos_TimeLine, curbarfresh)]\n preBarTime = GVAR.g_ATraderKDatas[_idx].Matrix[(GACV.KMatrixPos_TimeLine, curbarfresh - 1)]\n if matlab_float_time_to_datetime(curBarTime).hour >= 21:\n realBarDate = tb_command.atSendCmdTransTradeTimeToTradeDate(curBarTime)\n tickDay = int(realBarDate)\n else:\n tickDay = int(matlab_float_time_to_str_date(curBarTime))\n if GVAR.g_ATraderSimUnfiredStopOrders.size < 1 or len(GVAR.g_ATraderSimUnfiredStopOrders.shape) != 2:\n GVAR.g_ATraderSimUnfiredStopOrders = GVAR.g_ATraderSimUnfiredStopOrders.reshape((-1,\n 1))\n P = int(GVAR.g_ATraderSimUnfiredStopOrders[(GACV.SimStopOrder_TargetIdx, stopOrdersPos[0])])\n info = tb_command.atLoadTickDataFromPro(GVAR.g_ATraderStraInputInfo.TargetList[P]['Market'], GVAR.g_ATraderStraInputInfo.TargetList[P]['Code'], tickDay, 'NA')\n ticktime, tickprice, volumetick = info.Time.reshape((-1, 1)), info.Price.reshape((-1,\n 1)), info.VolumeTick.reshape((-1,\n 1))\n _t1 = np.where(ticktime > preBarTime)[0]\n _t2 = np.where(ticktime < curBarTime)[0]\n if len(_t1) > 0 and len(_t2) > 0:\n TickBeginNum = _t1[0]\n TickEndNum = _t2[(-1)]\n for tickNum in range(TickBeginNum, TickEndNum + 1):\n for sOrderPos in stopOrdersPos:\n sOrderPos = int(sOrderPos)\n orderAct = int(GVAR.g_ATraderSimUnfiredStopOrders[(GACV.SimStopOrder_OrderAct, sOrderPos)])\n targetPrice = GVAR.g_ATraderSimUnfiredStopOrders[(GACV.SimStopOrder_TargetPrice, sOrderPos)]\n curTickPrice = tickprice[(tickNum, 0)]\n if not bool(GVAR.g_ATraderSimUnfiredStopOrders[(GACV.SimStopOrder_InBarBegin, sOrderPos)]):\n if orderAct == GACV.OrderAct_Buy and curTickPrice <= targetPrice or orderAct == GACV.OrderAct_Sell and curTickPrice >= targetPrice:\n GVAR.g_ATraderSimUnfiredStopOrders[(GACV.SimStopOrder_InBarBegin, sOrderPos)] = True\n else:\n continue\n order_type = int(GVAR.g_ATraderSimUnfiredStopOrders[(GACV.SimStopOrder_StopOrderType, sOrderPos)])\n if order_type == GACV.StopOrderType_Loss:\n mPrice = GVAR.g_ATraderSimUnfiredStopOrders[(GACV.SimStopOrder_MPrice, sOrderPos)]\n if orderAct == GACV.OrderAct_Buy and curTickPrice <= mPrice or orderAct == GACV.OrderAct_Sell and curTickPrice >= mPrice:\n GVAR.g_ATraderSimUnfiredStopOrders[(GACV.SimStopOrder_MPrice, sOrderPos)] = curTickPrice\n GVAR.g_ATraderSimUnfiredStopOrders[(GACV.SimStopOrder_FireTime, sOrderPos)] = ticktime[tickNum]\n tickBarOpen = np.array([curTickPrice]).ravel()\n tickBarHigh = np.array([np.max(tickprice[tickNum:TickEndNum + 1])]).ravel()\n tickBarLow = np.array([np.min(tickprice[tickNum:TickEndNum + 1])]).ravel()\n tickBarVol = np.array([np.sum(volumetick[tickNum:TickEndNum + 1])]).ravel()\n theFireOnePos = np.array([sOrderPos])\n if order_type == GACV.StopOrderType_Profit:\n mPrice = GVAR.g_ATraderSimUnfiredStopOrders[(GACV.SimStopOrder_MPrice, sOrderPos)]\n if orderAct == GACV.OrderAct_Buy and curTickPrice >= mPrice or orderAct == GACV.OrderAct_Sell and curTickPrice <= mPrice:\n GVAR.g_ATraderSimUnfiredStopOrders[(GACV.SimStopOrder_MPrice, sOrderPos)] = curTickPrice\n GVAR.g_ATraderSimUnfiredStopOrders[(GACV.SimStopOrder_FireTime, sOrderPos)] = ticktime[tickNum]\n tickBarOpen = np.array([curTickPrice]).ravel()\n tickBarHigh = np.array([np.max(tickprice[tickNum:TickEndNum + 1])]).ravel()\n tickBarLow = np.array([np.min(tickprice[tickNum:TickEndNum + 1])]).ravel()\n tickBarVol = np.array([np.sum(volumetick[tickNum:TickEndNum + 1])]).ravel()\n theFireOnePos = np.array([sOrderPos])\n elif order_type == GACV.StopOrderType_Trailing:\n stopGapType = int(GVAR.g_ATraderSimUnfiredStopOrders[(GACV.SimStopOrder_StopGapType, sOrderPos)])\n stopGap = GVAR.g_ATraderSimUnfiredStopOrders[(GACV.SimStopOrder_StopGap, sOrderPos)]\n beginTrailingPrice = GVAR.g_ATraderSimUnfiredStopOrders[(GACV.SimStopOrder_BeginTrailingPrice, sOrderPos)]\n if not GVAR.g_ATraderSimUnfiredStopOrders[(GACV.SimStopOrder_IsBeginTrailing, sOrderPos)]:\n if orderAct == GACV.OrderAct_Buy and curTickPrice >= beginTrailingPrice or orderAct == GACV.OrderAct_Sell and curTickPrice <= beginTrailingPrice:\n pass\n GVAR.g_ATraderSimUnfiredStopOrders[(GACV.SimStopOrder_IsBeginTrailing, sOrderPos)] = True\n GVAR.g_ATraderSimUnfiredStopOrders[(GACV.SimStopOrder_InBeginTrailingBar, sOrderPos)] = False\n GVAR.g_ATraderSimUnfiredStopOrders[(GACV.SimStopOrder_TrailingHigh, sOrderPos)] = beginTrailingPrice\n GVAR.g_ATraderSimUnfiredStopOrders[(GACV.SimStopOrder_TrailingLow, sOrderPos)] = beginTrailingPrice\n if orderAct == GACV.OrderAct_Buy:\n if stopGapType == GACV.StopGapType_Point:\n GVAR.g_ATraderSimUnfiredStopOrders[(GACV.SimStopOrder_StopTrailingPrice, sOrderPos)] = beginTrailingPrice - stopGap\n else:\n if stopGapType == GACV.StopGapType_Percent:\n GVAR.g_ATraderSimUnfiredStopOrders[(GACV.SimStopOrder_StopTrailingPrice, sOrderPos)] = beginTrailingPrice - (beginTrailingPrice - targetPrice) * stopGap / 100.0\n elif not False:\n raise AssertionError\n if orderAct == GACV.OrderAct_Sell:\n if stopGapType == GACV.StopGapType_Point:\n GVAR.g_ATraderSimUnfiredStopOrders[(GACV.SimStopOrder_StopTrailingPrice, sOrderPos)] = beginTrailingPrice + stopGap\n else:\n if stopGapType == GACV.StopGapType_Percent:\n GVAR.g_ATraderSimUnfiredStopOrders[(GACV.SimStopOrder_StopTrailingPrice, sOrderPos)] = beginTrailingPrice + (targetPrice - beginTrailingPrice) * stopGap / 100.0\n elif not False:\n raise AssertionError\n else:\n continue\n if bool(GVAR.g_ATraderSimUnfiredStopOrders[(GACV.SimStopOrder_InBeginTrailingBar, sOrderPos)]):\n if orderAct == GACV.OrderAct_Buy and curTickPrice >= beginTrailingPrice or orderAct == GACV.OrderAct_Sell and curTickPrice <= beginTrailingPrice:\n GVAR.g_ATraderSimUnfiredStopOrders[(GACV.SimStopOrder_IsBeginTrailing, sOrderPos)] = True\n GVAR.g_ATraderSimUnfiredStopOrders[(GACV.SimStopOrder_InBeginTrailingBar, sOrderPos)] = False\n GVAR.g_ATraderSimUnfiredStopOrders[(GACV.SimStopOrder_TrailingHigh, sOrderPos)] = beginTrailingPrice\n GVAR.g_ATraderSimUnfiredStopOrders[(GACV.SimStopOrder_TrailingLow, sOrderPos)] = beginTrailingPrice\n else:\n continue\n stopTrailingPrice = GVAR.g_ATraderSimUnfiredStopOrders[(GACV.SimStopOrder_StopTrailingPrice, sOrderPos)]\n trailingHigh = GVAR.g_ATraderSimUnfiredStopOrders[(GACV.SimStopOrder_TrailingHigh, sOrderPos)]\n trailingLow = GVAR.g_ATraderSimUnfiredStopOrders[(GACV.SimStopOrder_TrailingLow, sOrderPos)]\n if orderAct == GACV.OrderAct_Buy and stopTrailingPrice >= curTickPrice or orderAct == GACV.OrderAct_Sell and curTickPrice >= stopTrailingPrice:\n GVAR.g_ATraderSimUnfiredStopOrders[(GACV.SimStopOrder_TrailingHigh, sOrderPos)] = max(trailingHigh, curTickPrice)\n GVAR.g_ATraderSimUnfiredStopOrders[(GACV.SimStopOrder_TrailingLow, sOrderPos)] = min(trailingLow, curTickPrice)\n GVAR.g_ATraderSimUnfiredStopOrders[(GACV.SimStopOrder_FireTime, sOrderPos)] = ticktime[tickNum]\n GVAR.g_ATraderSimUnfiredStopOrders[(GACV.SimStopOrder_StopTrailingPrice, sOrderPos)] = curTickPrice\n tickBarOpen = np.array([curTickPrice]).ravel()\n tickBarHigh = np.array([np.max(tickprice[tickNum:TickEndNum + 1])]).ravel()\n tickBarLow = np.array([np.min(tickprice[tickNum:TickEndNum + 1])]).ravel()\n tickBarVol = np.array([np.sum(volumetick[tickNum:TickEndNum + 1])]).ravel()\n theFireOnePos = np.array([sOrderPos])\n else:\n if curTickPrice > trailingHigh:\n GVAR.g_ATraderSimUnfiredStopOrders[(GACV.SimStopOrder_TrailingHigh, sOrderPos)] = curTickPrice\n if orderAct == GACV.OrderAct_Buy:\n if stopGapType == GACV.StopGapType_Point:\n GVAR.g_ATraderSimUnfiredStopOrders[(GACV.SimStopOrder_StopTrailingPrice, sOrderPos)] = curTickPrice - stopGap\n elif stopGapType == GACV.StopGapType_Percent:\n GVAR.g_ATraderSimUnfiredStopOrders[(GACV.SimStopOrder_StopTrailingPrice, sOrderPos)] = curTickPrice - (curTickPrice - targetPrice) * stopGap / 100.0\n elif not False:\n raise AssertionError\n if curTickPrice < trailingLow:\n GVAR.g_ATraderSimUnfiredStopOrders[(GACV.SimStopOrder_TrailingLow, sOrderPos)] = curTickPrice\n if orderAct == GACV.OrderAct_Sell:\n if stopGapType == GACV.StopGapType_Point:\n GVAR.g_ATraderSimUnfiredStopOrders[(GACV.SimStopOrder_StopTrailingPrice, sOrderPos)] = curTickPrice + stopGap\n else:\n if stopGapType == GACV.StopGapType_Percent:\n GVAR.g_ATraderSimUnfiredStopOrders[(GACV.SimStopOrder_StopTrailingPrice, sOrderPos)] = curTickPrice + (targetPrice - curTickPrice) * stopGap / 100.0\n elif not False:\n raise AssertionError\n else:\n assert False, 'not support stoporder type'\n if theFireOnePos.size > 0:\n break\n\n if theFireOnePos.size > 0:\n break\n\n return (\n theFireOnePos, tickBarOpen, tickBarHigh, tickBarLow, tickBarVol)\n\n\ndef change_inttime_to_y_M_D_H_m_s(test_array):\n \"\"\"将int型日期切割为由年,月,日,小时,分钟,秒组成的np.array()\"\"\"\n istick = GVAR.g_ATraderStraInputInfo['KFrequency'] == 'tick'\n return change_to_y_M_D_H_m_s(test_array, istick)","sub_path":"pycfiles/atquant-2.3.846-py3-none-any/trader_run_back_test.py","file_name":"trader_run_back_test.py","file_ext":"py","file_size_in_byte":44469,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"231655189","text":"from __future__ import absolute_import, unicode_literals\nimport os\nfrom flask import Flask, request, abort, render_template, redirect\n\nfrom message import message\nfrom sqlite_helper import SQLiteHelper\nfrom hwk_helper import HomeworkHelper\nfrom time_helpter import timestamp2date\nimport sys\n# set token or get from environments\nfrom util import *\n\napp = Flask(__name__)\n\n\n@app.route('/')\ndef index():\n host = request.url_root\n return render_template('index.html', host=host)\n # return \"hello world\"\n\n@app.route('/name/')\ndef showname(name):\n return \"hello\" + name\n\n@app.route('/showhomework/')\ndef showhomework(date):\n hwker = HomeworkHelper(date)\n user_d, user_d_rev = get_userlist()\n homework = {user_d[uid]:hwker.get(uid) for uid in range(501,518)}\n unsubmit = 0;\n submit = len(homework)\n for data in homework.values():\n if(len(data)==0):\n unsubmit+=1\n submit-=1\n return render_template(\"/mobile/show_dict.html\",date=date, result=homework,submit=submit,unsubmit=unsubmit)\n\n@app.route('/homework/')\ndef homeworkform():\n return render_template('/mobile/form.html',date=\"20180501\")\n\n@app.route('/homework/',methods=['POST'])\ndef homework():\n text = request.form['text'] \n if(\"hito\" in request.form.keys()):\n return redirect('/showcheckresult/'+text,code=302)\n if(\"keka\" in request.form.keys()):\n return redirect('/showhomework/'+text,code=302)\n\n@app.route('/showcheckresult/')\ndef showcheckresult(date):\n hwker = HomeworkHelper(date)\n user_d, user_d_rev = get_userlist()\n delayed = hwker.checkunsubmit(user_d.keys())\n name = [user_d[id] for id in delayed]\n return render_template(\"/mobile/show_list.html\", data=name,date=date)\n\n@app.route('/checkwork/')\ndef checkworkform():\n return render_template('my-form.html')\n\n@app.route('/checkwork/',methods=['POST'])\ndef checkwork():\n text = request.form['text'] \n return redirect('/showcheckresult/'+text,code=302)\n\nif __name__ == '__main__':\n app.run('127.0.0.1', 5000, debug=True)\n","sub_path":"local.py","file_name":"local.py","file_ext":"py","file_size_in_byte":2058,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"319557433","text":"from sklearn.feature_extraction.text import TfidfVectorizer\nfrom sklearn import metrics\nfrom sklearn.cluster import KMeans, AffinityPropagation\nfrom collections import defaultdict\nimport re\nfrom utils import Globals as glob\nfrom utils.ECBWrapper import ECBWrapper\nimport sys\n\n\nargs = glob.parser.parse_args()\ntopics = args.topics.split(' ')\nnum_labels = args.num_labels\ndamp = args.damping\n\necb_wrapper = ECBWrapper(glob.ECBPLUS_DIR, topics=None, lemmatize=False)\ndocs, targets, f_names = ecb_wrapper.make_data_for_clustering(option='text',\n topics=topics,\n sub_topics=True, filter=True)\n\nvectorizer = TfidfVectorizer(max_df=0.5, min_df=3, ngram_range=(1,3), stop_words='english',max_features=500)\nX = vectorizer.fit_transform(docs)\n\nif num_labels:\n clustering_obj = KMeans(n_clusters=num_labels, init='k-means++', max_iter=200,\n n_init=20, random_state=665,\n n_jobs=20, algorithm='auto').fit(X)\nelse:\n clustering_obj = AffinityPropagation(damping=damp).fit(X)\nclusters = defaultdict(list)\nfor k,v in zip(clustering_obj.labels_, f_names):\n clusters[k].append(v)\nclusters = {k:' '.join(v) for k,v in clusters.items()}\nhcv = metrics.homogeneity_completeness_v_measure(targets, clustering_obj.labels_)\nari = metrics.adjusted_rand_score(targets, clustering_obj.labels_)\nres = {'homogeneity': round(hcv[0], 4),\n 'completeness': round(hcv[1],4),\n 'v-measure': round(hcv[2],4),\n 'ari': round(ari,4)}\npattern = re.compile('{|}')\nsys.stdout.write(pattern.sub('', str(clusters)))\nsys.stdout.write('BREAK')\nsys.stdout.write(pattern.sub('', str(res)))","sub_path":"python_assets/doc_clustering/cluster_documents.py","file_name":"cluster_documents.py","file_ext":"py","file_size_in_byte":1724,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"390347036","text":"from typing import List\n\nimport numpy as np\n\nfrom fedot.core.data.supplementary_data import SupplementaryData\nfrom fedot.core.repository.dataset_types import DataTypesEnum\n\n\nclass DataMerger:\n \"\"\"\n Class for merging data, when it comes from different nodes and there is a\n need to merge it into next level node\n\n :param outputs: list with OutputData from parent nodes\n \"\"\"\n\n def __init__(self, outputs: list):\n self.outputs = outputs\n\n def merge(self):\n \"\"\" Method automatically determine which merge function should be\n applied \"\"\"\n\n if len(self.outputs) == 1 and self.outputs[0].data_type in [DataTypesEnum.image, DataTypesEnum.text]:\n # TODO implement correct merge\n idx = self.outputs[0].idx\n features = self.outputs[0].features\n target = self.outputs[0].target\n task = self.outputs[0].task\n data_type = self.outputs[0].data_type\n updated_info = SupplementaryData(is_main_target=True)\n updated_info.calculate_data_flow_len(self.outputs)\n return idx, features, target, task, data_type, updated_info\n\n merge_function_by_type = {DataTypesEnum.ts: self.combine_datasets_ts,\n DataTypesEnum.table: self.combine_datasets_table,\n DataTypesEnum.text: self.combine_datasets_table}\n\n output_data_types = [output.data_type for output in self.outputs]\n first_data_type = output_data_types[0]\n\n # Check is all data types can be merged or not\n if len(set(output_data_types)) > 1:\n raise ValueError(\"There is no ability to merge different data types\")\n\n # Define appropriate strategy\n merge_func = merge_function_by_type.get(first_data_type)\n if merge_func is None:\n message = f\"For data type '{first_data_type}' doesn't exist merge function\"\n raise NotImplementedError(message)\n else:\n idx, features, target, is_main_target, task = merge_func()\n\n updated_info = SupplementaryData(is_main_target=is_main_target)\n # Calculate amount of visited nodes for data\n updated_info.calculate_data_flow_len(self.outputs)\n # Prepare mask with predict from different parent nodes\n if first_data_type == DataTypesEnum.table and len(self.outputs) > 1:\n updated_info.prepare_parent_mask(self.outputs)\n\n return idx, features, target, task, first_data_type, updated_info\n\n def combine_datasets_table(self):\n \"\"\" Function for combining datasets from parents to make features to\n another node. Features are tabular data.\n\n :return idx: updated indices\n :return features: new features obtained from predictions at previous level\n :return target: updated target\n \"\"\"\n are_lengths_equal, idx_list = self._check_size_equality(self.outputs)\n\n if are_lengths_equal:\n idx, features, target, is_main_target, task = self._merge_equal_outputs(self.outputs)\n else:\n idx, features, target, is_main_target, task = self._merge_non_equal_outputs(self.outputs,\n idx_list)\n\n return idx, features, target, is_main_target, task\n\n def combine_datasets_ts(self):\n \"\"\" Function for combining datasets from parents to make features to\n another node. Features are time series data.\n\n :return idx: updated indices\n :return features: new features obtained from predictions at previous level\n :return target: updated target\n \"\"\"\n are_lengths_equal, idx_list = self._check_size_equality(self.outputs)\n\n if are_lengths_equal:\n idx, features, target, is_main_target, task = self._merge_equal_outputs(self.outputs)\n else:\n idx, features, target, is_main_target, task = self._merge_non_equal_outputs(self.outputs,\n idx_list)\n\n features = np.ravel(np.array(features))\n target = np.ravel(np.array(target))\n return idx, features, target, is_main_target, task\n\n @staticmethod\n def _merge_equal_outputs(outputs: list):\n \"\"\" Method merge datasets with equal amount of rows \"\"\"\n\n features = []\n for elem in outputs:\n if len(elem.predict.shape) == 1:\n features.append(elem.predict)\n else:\n # If the model prediction is multivariate\n number_of_variables_in_prediction = elem.predict.shape[1]\n for i in range(number_of_variables_in_prediction):\n features.append(elem.predict[:, i])\n\n features = np.array(features).T\n idx = outputs[0].idx\n\n # Update target from multiple parents\n target, is_main_target, task = TaskTargetMerger(outputs).obtain_equal_target()\n\n return idx, features, target, is_main_target, task\n\n @staticmethod\n def _merge_non_equal_outputs(outputs: list, idx_list: List):\n \"\"\" Method merge datasets with different amount of rows by idx field \"\"\"\n\n # Search overlapping indices in data\n for i, idx in enumerate(idx_list):\n idx = set(idx)\n if i == 0:\n common_idx = idx\n else:\n common_idx = common_idx & idx\n\n # Convert to list\n common_idx = np.array(list(common_idx))\n if len(common_idx) == 0:\n raise ValueError(f'There are no common indices for outputs')\n\n idx_list = [list(output.idx) for output in outputs]\n predicts = [output.predict for output in outputs]\n\n # Generate feature table with overlapping ids\n features = tables_mapping(idx_list, predicts, common_idx)\n # Link tables with features into one table - rotate array\n features = np.hstack(features)\n\n # Merge tasks and targets\n t_merger = TaskTargetMerger(outputs)\n filtered_target, is_main_target, task = t_merger.obtain_non_equal_target(common_idx)\n return common_idx, features, filtered_target, is_main_target, task\n\n @staticmethod\n def _check_size_equality(outputs: list):\n \"\"\" Function check the size of combining datasets \"\"\"\n idx_lengths = []\n idx_list = []\n for elem in outputs:\n idx_lengths.append(len(elem.idx))\n idx_list.append(elem.idx)\n\n # Check amount of unique lengths of datasets\n if len(set(idx_lengths)) == 1:\n are_lengths_equal = True\n else:\n are_lengths_equal = False\n\n return are_lengths_equal, idx_list\n\n\nclass TaskTargetMerger:\n \"\"\" Class for merging target and tasks \"\"\"\n\n def __init__(self, outputs):\n self.outputs = outputs\n\n def obtain_equal_target(self):\n \"\"\" Method can merge different targets if the amount of objects in the\n training sample are equal\n \"\"\"\n # If there is only one parent\n if len(self.outputs) == 1:\n target = self.outputs[0].target\n is_main_target = self.outputs[0].supplementary_data.is_main_target\n task = self.outputs[0].task\n return target, is_main_target, task\n\n # Get target flags, targets and tasks\n t_flags, targets, tasks = self._disintegrate_outputs()\n\n # If all t_flags are True - there is no need to merge targets\n if all(flag is True for flag in t_flags):\n target = self.outputs[0].target\n task = self.outputs[0].task\n is_main_target = True\n return target, is_main_target, task\n # If there is an \"ignore\" (False) flag - need to apply intelligent merge\n elif any(flag is False for flag in t_flags):\n target, is_main_target, task = self.ignored_merge(targets, t_flags, tasks)\n return target, is_main_target, task\n\n def obtain_non_equal_target(self, common_idx):\n \"\"\" Method for merging targets which have different amount of objects\n (amount of rows)\n\n :param common_idx: array with indices of common objects\n \"\"\"\n\n t_flags, targets, tasks = self._disintegrate_outputs()\n\n if targets[0] is None:\n mapped_targets = [None]\n else:\n # Match targets - make them equal\n idx_list = [output.idx for output in self.outputs]\n mapped_targets = tables_mapping(idx_list, targets, common_idx)\n\n # If all t_flags are True - there is no need to merge targets\n if all(flag is True for flag in t_flags):\n # Just applying merge operation for common_idx\n filtered_target = mapped_targets[0]\n\n task = tasks[0]\n is_main_target = True\n return filtered_target, is_main_target, task\n elif any(flag is False for flag in t_flags):\n\n filtered_target, is_main_target, task = self.ignored_merge(mapped_targets,\n t_flags,\n tasks)\n return filtered_target, is_main_target, task\n\n def _disintegrate_outputs(self):\n \"\"\"\n Method extract target flags, targets and tasks from list with OutputData\n \"\"\"\n t_flags = [output.supplementary_data.is_main_target for output in self.outputs]\n targets = [output.target for output in self.outputs]\n tasks = [output.task for output in self.outputs]\n\n return t_flags, targets, tasks\n\n @staticmethod\n def ignored_merge(targets, t_flags, tasks):\n \"\"\" Method merge targets with False labels. False - means that such\n branch target must be ignored \"\"\"\n # PEP8 fix through converting boolean into string\n t_flags = np.array(t_flags, dtype=str)\n main_ids = np.ravel(np.argwhere(t_flags == 'True'))\n tasks = np.array(tasks)\n\n # Is there is pipeline predict stage without target at all\n if targets[0] is None:\n target = None\n is_main_target = True\n # If there are several known targets\n else:\n # Take first non-ignored target\n main_id = main_ids[0]\n target = targets[main_id]\n if len(target.shape) == 1:\n target = target.reshape((-1, 1))\n is_main_target = True\n\n task = tasks[main_ids]\n task = task[0]\n return target, is_main_target, task\n\n\ndef tables_mapping(idx_list, object_list, common_idx):\n \"\"\" The function maps tables by matching object indices\n\n :param idx_list: list with indices for mapping\n :param object_list: list with tables (with features, targets or predictions)\n for mapping\n :param common_idx: list with common indices\n\n :return : list with matched tables\n \"\"\"\n\n common_tables = []\n for number in range(len(idx_list)):\n # Create mask where True - appropriate objects\n current_idx = idx_list[number]\n mask = np.in1d(np.array(current_idx), common_idx)\n\n current_object = object_list[number]\n if len(current_object.shape) == 1:\n filtered_predict = current_object[mask]\n filtered_predict = filtered_predict.reshape((-1, 1))\n common_tables.append(filtered_predict)\n else:\n # If the table object has many columns\n number_of_variables_in_prediction = current_object.shape[1]\n for i in range(number_of_variables_in_prediction):\n predict = current_object[:, i]\n filtered_predict = predict[mask]\n\n # Convert to column\n filtered_predict = filtered_predict.reshape((-1, 1))\n if i == 0:\n filtered_table = filtered_predict\n else:\n filtered_table = np.hstack((filtered_table, filtered_predict))\n common_tables.append(filtered_table)\n return common_tables\n","sub_path":"fedot/core/data/merge.py","file_name":"merge.py","file_ext":"py","file_size_in_byte":12078,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"429081633","text":"from pyselenium import Pyse, TestCase, TestRunner\nfrom page import BaiduPage\n\nclass BaiduTest(TestCase):\n ''' Baidu serach test case'''\n\n @classmethod\n def setUpClass(cls):\n cls.driver = Pyse(\"chrome\")\n\n def test_case(self):\n ''' baidu search key : pyse '''\n bd = BaiduPage(self.driver)\n bd.open()\n bd.search_input(\"pyse\")\n bd.search_button()\n self.assertTitle(\"pyse_百度搜索\")\n\n\nif __name__ == '__main__':\n runner = TestRunner('./', '百度测试用例', '测试环境:Firefox')\n runner.debug()\n","sub_path":"build/lib/testCase/test_baidu.py","file_name":"test_baidu.py","file_ext":"py","file_size_in_byte":569,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"28477317","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('Forum', '0009_forumuser_scratchverify'),\n ]\n\n operations = [\n migrations.AddField(\n model_name='forumuser',\n name='infolocation',\n field=models.CharField(max_length=100, default='No location set'),\n preserve_default=False,\n ),\n migrations.AddField(\n model_name='forumuser',\n name='infowebsitename',\n field=models.CharField(max_length=100, default='No website set'),\n preserve_default=False,\n ),\n migrations.AddField(\n model_name='forumuser',\n name='infowebsiteurl',\n field=models.CharField(max_length=500, default='#'),\n preserve_default=False,\n ),\n ]\n","sub_path":"migrations/0010_auto_20151106_2202.py","file_name":"0010_auto_20151106_2202.py","file_ext":"py","file_size_in_byte":914,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"71543256","text":"from django_filters.rest_framework import DjangoFilterBackend\nfrom drf_yasg.utils import swagger_auto_schema\nfrom rest_framework import viewsets, mixins\nfrom rest_framework.decorators import action\nfrom rest_framework.permissions import IsAuthenticated\nfrom rest_framework.response import Response\nfrom rest_framework_csv.renderers import CSVRenderer\n\nfrom spendings.serializers import SpendingSerializer, SpendingCategorySerializer\nfrom spendings.models import Spending, SpendingCategory\nfrom spendings.filters import SpendingFilter\n\n\n@swagger_auto_schema()\nclass SpendingsViewSet(viewsets.ModelViewSet):\n \"\"\"\n Takes JWT token for authorization.\n list:\n Get the list of all spendings for a specific user\n retrieve:\n Get the spending by its id\n create:\n Takes a set of spending details: amount, category, description.\n Returns a created spending\n update:\n Update the spending by its id\n Takes a set of spending details: amount, category, description.\n partial_update:\n Update the spending by its id\n Takes a set of spending details: amount or category or description.\n delete:\n Delete the spending by its id\n \"\"\"\n permission_classes = (IsAuthenticated,)\n serializer_class = SpendingSerializer\n filter_backends = (DjangoFilterBackend,)\n filterset_class = SpendingFilter\n\n def get_queryset(self):\n return Spending.objects.filter(user=self.request.user)\n\n def perform_create(self, serializer):\n serializer.save(user=self.request.user)\n\n def perform_update(self, serializer):\n serializer.save(user=self.request.user)\n\n\nclass SpendingCategoryViewSet(viewsets.ModelViewSet):\n \"\"\"\n Takes JWT token for authorization.\n list:\n Get the list of all categories for a specific user\n retrieve:\n Get the spending category by its id\n create:\n Takes the category name (unique name for a specific user)\n Returns a created category\n update:\n Update the spending category by its id\n Takes a new category name\n partial_update:\n Update the spending category by its id\n Takes a new category name\n delete:\n Delete the spending category by its id\n \"\"\"\n permission_classes = (IsAuthenticated,)\n serializer_class = SpendingCategorySerializer\n\n def get_queryset(self):\n return SpendingCategory.objects.filter(user=self.request.user)\n\n def perform_create(self, serializer):\n serializer.save(user=self.request.user)\n\n\nclass ExportViewSet(viewsets.GenericViewSet):\n \"\"\"\n Takes JWT token for authorization.\n Returns file .csv with all user's spendings\n \"\"\"\n permission_classes = (IsAuthenticated,)\n serializer_class = SpendingSerializer\n\n def get_queryset(self):\n return Spending.objects.filter(user=self.request.user)\n\n class SpendingRenderer(CSVRenderer):\n header = ['Amount', 'User', 'Category', 'Description', 'Created at']\n\n renderer_classes = (SpendingRenderer,)\n\n @action(methods=['GET'], detail=False, url_path='export-csv', url_name='export-csv')\n def export_csv(self, request):\n spendings = Spending.objects.filter(user=self.request.user)\n content = [{\n 'Amount': spending.amount,\n 'Category': spending.category.name,\n 'Description': spending.description,\n 'User': spending.user.email,\n 'Created at': spending.created_at.strftime('%d, %b %Y - %Hh %Mm')\n } for spending in spendings]\n return Response(content)\n","sub_path":"spendings/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3493,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"520564801","text":"assignments = []\nrows = 'ABCDEFGHI'\ncols = '123456789'\n\ndef cross(A, B):\n \"Cross product of elements in A and elements in B.\"\n return [s + t for s in A for t in B]\n\nboxes = cross(rows, cols)\nrow_units = [cross(r, cols) for r in rows]\ncolumn_units = [cross(rows, c) for c in cols]\nsquare_units = [cross(rs, cs) for rs in ('ABC', 'DEF', 'GHI')\n for cs in ('123', '456', '789')]\ndiagonal_left_right = [''.join(t) for t in list((zip(rows, cols)))]\ndiagonal_right_left = [''.join(t) for t in list((zip(rows, reversed(cols))))]\ndiagonal_units = [diagonal_left_right, diagonal_right_left]\nunitlist = row_units + column_units + square_units + diagonal_units\nunits = dict((s, [u for u in unitlist if s in u]) for s in boxes)\npeers = dict((s, set(sum(units[s], [])) - set([s])) for s in boxes)\n\ndef assign_value(values, box, value):\n \"\"\"\n Please use this function to update your values dictionary!\n Assigns a value to a given box. If it updates the board record it.\n \"\"\"\n values[box] = value\n if len(value) == 1:\n assignments.append(values.copy())\n return values\n\n\ndef naked_twins(values):\n \"\"\"Eliminate values using the naked twins strategy.\n Args:\n values(dict): a dictionary of the form {'box_name': '123456789', ...}\n\n Returns:\n the values dictionary with the naked twins eliminated from peers.\n \"\"\"\n # unitlist = column_units\n # display(values)\n for unit in unitlist:\n two_digit_values = [values[box] for box in unit if len(values[box]) == 2]\n twin_values = set()\n # Find all instances of naked twins\n for v in two_digit_values:\n if two_digit_values.count(v) > 1:\n a, b = list(v)\n twin_values.add(a)\n twin_values.add(b)\n # Eliminate the naked twins as possibilities for their peers \n for box in unit:\n for tv in twin_values:\n if tv in values[box] and len(values[box]) > 2:\n values[box] = values[box].replace(tv, '')\n return values\n \ndef grid_values(grid):\n chars = []\n digits = '123456789'\n for c in grid:\n if c in digits:\n chars.append(c)\n if c == '.':\n chars.append(digits)\n assert len(chars) == 81\n return dict(zip(boxes, chars))\n\n\ndef display(values):\n \"\"\"\n Display the values as a 2-D grid.\n Args:\n values(dict): The sudoku in dictionary form\n \"\"\"\n width = 1 + max(len(values[s]) for s in boxes)\n line = '+'.join(['-' * (width * 3)] * 3)\n for r in rows:\n print(''.join(values[r + c].center(width) + ('|' if c in '36' else '')\n for c in cols))\n if r in 'CF':\n print(line)\n return\n\n\ndef eliminate(values):\n \"\"\"\n Go through all the boxes, and whenever there is a box with a value, eliminate this value from the values of all its peers.\n Input: A sudoku in dictionary form.\n Output: The resulting sudoku in dictionary form.\n \"\"\"\n solved_values = [box for box in values.keys() if len(values[box]) == 1]\n for box in solved_values:\n digit = values[box]\n for peer in peers[box]:\n values[peer] = values[peer].replace(digit, '')\n return values\n\n\ndef only_choice(values):\n \"\"\"\n Go through all the units, and whenever there is a unit with a value that only fits in one box, assign the value to this box.\n Input: A sudoku in dictionary form.\n Output: The resulting sudoku in dictionary form.\n \"\"\"\n for unit in unitlist:\n for digit in '123456789':\n dplaces = [box for box in unit if digit in values[box]]\n if len(dplaces) == 1:\n values[dplaces[0]] = digit\n return values\n\n\ndef reduce_puzzle(values):\n \"\"\"\n Iterate eliminate() and only_choice(). If at some point, there is a box with no available values, return False.\n If the sudoku is solved, return the sudoku.\n If after an iteration of both functions, the sudoku remains the same, return the sudoku.\n Input: A sudoku in dictionary form.\n Output: The resulting sudoku in dictionary form.\n \"\"\"\n solved_values = [box for box in values.keys() if len(values[box]) == 1]\n stalled = False\n while not stalled:\n # Check how many boxes have a determined value\n solved_values_before = len(\n [box for box in values.keys() if len(values[box]) == 1])\n # Use the Eliminate Strategy\n values = eliminate(values)\n # Use the Only Choice Strategy\n values = only_choice(values)\n # Check how many boxes have a determined value, to compare\n solved_values_after = len(\n [box for box in values.keys() if len(values[box]) == 1])\n # If no new values were added, stop the loop.\n stalled = solved_values_before == solved_values_after\n # Sanity check, return False if there is a box with zero available\n # values:\n if len([box for box in values.keys() if len(values[box]) == 0]):\n return False\n return values\n\n\ndef search(values):\n # Using depth-first search and propagation, try all possible values.\n # First, reduce the puzzle using the previous function\n # print(values)\n values = reduce_puzzle(values)\n if values is False:\n return False # Failed earlier\n if all(len(values[s]) == 1 for s in boxes):\n return values # Solved!\n # Choose one of the unfilled squares with the fewest possibilities\n n, s = min((len(values[s]), s) for s in boxes if len(values[s]) > 1)\n # Now use recurrence to solve each one of the resulting sudokus, and\n for value in values[s]:\n new_sudoku = values.copy()\n new_sudoku[s] = value\n attempt = search(new_sudoku)\n if attempt:\n return attempt\n\n\ndef solve(grid):\n \"\"\"\n Find the solution to a Sudoku grid.\n Args:\n grid(string): a string representing a sudoku grid.\n Example: '2.............62....1....7...6..8...3...9...7...6..4...4....8....52.............3'\n Returns:\n The dictionary representation of the final sudoku grid. False if no solution exists.\n \"\"\"\n values = grid_values(grid)\n display(values)\n result = search(values)\n return result\n\nif __name__ == '__main__':\n diag_sudoku_grid = '2.............62....1....7...6..8...3...9...7...6..4...4....8....52.............3'\n # display(solve(diag_sudoku_grid))\n values = {'I6': '4', 'H9': '3', 'I2': '6', 'E8': '1', 'H3': '5', 'H7': '8', 'I7': '1', 'I4': '8',\n 'H5': '6', 'F9': '7', 'G7': '6', 'G6': '3', 'G5': '2', 'E1': '8', 'G3': '1', 'G2': '8',\n 'G1': '7', 'I1': '23', 'C8': '5', 'I3': '23', 'E5': '347', 'I5': '5', 'C9': '1', 'G9': '5',\n 'G8': '4', 'A1': '1', 'A3': '4', 'A2': '237', 'A5': '9', 'A4': '2357', 'A7': '27',\n 'A6': '257', 'C3': '8', 'C2': '237', 'C1': '23', 'E6': '579', 'C7': '9', 'C6': '6',\n 'C5': '37', 'C4': '4', 'I9': '9', 'D8': '8', 'I8': '7', 'E4': '6', 'D9': '6', 'H8': '2',\n 'F6': '125', 'A9': '8', 'G4': '9', 'A8': '6', 'E7': '345', 'E3': '379', 'F1': '6',\n 'F2': '4', 'F3': '23', 'F4': '1235', 'F5': '8', 'E2': '37', 'F7': '35', 'F8': '9',\n 'D2': '1', 'H1': '4', 'H6': '17', 'H2': '9', 'H4': '17', 'D3': '2379', 'B4': '27',\n 'B5': '1', 'B6': '8', 'B7': '27', 'E9': '2', 'B1': '9', 'B2': '5', 'B3': '6', 'D6': '279',\n 'D7': '34', 'D4': '237', 'D5': '347', 'B8': '3', 'B9': '4', 'D1': '5'}\n values1 = {'A1': '23', 'A2': '4', 'A3': '7', 'A4': '6', 'A5': '8', 'A6': '5', 'A7': '23', 'A8': '9',\n 'A9': '1', 'B1': '6', 'B2': '9', 'B3': '8', 'B4': '4', 'B5': '37', 'B6': '1', 'B7': '237',\n 'B8': '5', 'B9': '237', 'C1': '23', 'C2': '5', 'C3': '1', 'C4': '23', 'C5': '379',\n 'C6': '2379', 'C7': '8', 'C8': '6', 'C9': '4', 'D1': '8', 'D2': '17', 'D3': '9',\n 'D4': '1235', 'D5': '6', 'D6': '237', 'D7': '4', 'D8': '27', 'D9': '2357', 'E1': '5',\n 'E2': '6', 'E3': '2', 'E4': '8', 'E5': '347', 'E6': '347', 'E7': '37', 'E8': '1', 'E9': '9',\n 'F1': '4', 'F2': '17', 'F3': '3', 'F4': '125', 'F5': '579', 'F6': '279', 'F7': '6',\n 'F8': '8', 'F9': '257', 'G1': '1', 'G2': '8', 'G3': '6', 'G4': '35', 'G5': '345',\n 'G6': '34', 'G7': '9', 'G8': '27', 'G9': '27', 'H1': '7', 'H2': '2', 'H3': '4', 'H4': '9',\n 'H5': '1', 'H6': '8', 'H7': '5', 'H8': '3', 'H9': '6', 'I1': '9', 'I2': '3', 'I3': '5',\n 'I4': '7', 'I5': '2', 'I6': '6', 'I7': '1', 'I8': '4', 'I9': '8'}\n naked_twins(values)\n # display(solve(diag_sudoku_grid))\n # try:\n # from visualize import visualize_assignments\n # visualize_assignments(assignments)\n\n # except SystemExit:\n # pass\n # except:\n # print('We could not visualize your board due to a pygame issue. Not a problem! It is not a requirement.')\n","sub_path":"solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":8972,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"273751667","text":"from scrapy import Selector, Spider, Request\nfrom urllib.parse import urljoin\nfrom crawl.items.wsl_36KR import wsl_36KR\nimport json\n\nclass KRspider(Spider):\n name = '36KR'\n start_urls = [\n 'https://36kr.com/pp/api/aggregation-entity?type=web_latest_article&per_page=30'\n ]\n def parse(self, response):\n result = json.loads(response.text)\n for i in result['data']['items']:\n entity_id = i.get('entity_id')\n detauil_url = urljoin('https://36kr.com/p/', str(entity_id))\n yield Request(url=detauil_url, callback=self.content)\n\n\n def content(self, response):\n sel = Selector(response)\n item = wsl_36KR()\n item['title'] = sel.css('h1::text').extract_first()\n item['author'] = sel.xpath('//div[@class=\"article-title-icon common-width margin-bottom-40\"]/a/text()').extract_first()\n item['text'] = ''.join(sel.xpath('//p//text()').extract()).strip()\n item['time'] = ''.join(sel.xpath('//span[@class=\"title-icon-item item-time\"]/text()').re(r'\\d+\\w+'))\n yield item","sub_path":"crawl/spiders/wangshilong/36KR.py","file_name":"36KR.py","file_ext":"py","file_size_in_byte":1071,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"287598541","text":"import pygame\nimport sys\n\npygame.init()\nwin = pygame.display.set_mode((1050, 500))\npygame.display.set_caption('Pygame template')\nclock = pygame.time.Clock()\n\n\nwhile True:\n for e in pygame.event.get():\n if e.type == pygame.QUIT:\n pygame.quit()\n sys.exit()\n\n win.fill((30, 30, 80))\n\n pygame.display.update()\n clock.tick(30)\n","sub_path":"pygame_template.py","file_name":"pygame_template.py","file_ext":"py","file_size_in_byte":363,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"88416402","text":"class Solution(object):\n def numIslands(self, grid):\n \"\"\"\n :type grid: List[List[str]]\n :rtype: int\n \"\"\"\n res = 0\n if not grid: return res\n def dfs(i, j):\n if not(0<=i None:\n loaded_reviews = []\n\n for review_file_path in glob(os.path.join('reviews-old', '*.md')):\n with open(review_file_path, 'r') as review_file:\n review_file_content = review_file.read()\n _, fm, review_content = FM_REGEX.split(review_file_content, 2)\n front_matter = yaml.safe_load(fm)\n\n with db.connect() as connection:\n cursor = connection.cursor()\n row = cursor.execute(\n f'SELECT title, year FROM movies WHERE imdb_id=\"{front_matter[\":imdb_id\"]}\";'\n ).fetchone()\n year = row['year']\n title = row['title']\n\n loaded_reviews.append({\n 'imdb_id': front_matter[':imdb_id'],\n 'sequence': front_matter[':sequence'],\n 'title': title,\n 'year': year,\n 'date': front_matter[':date'],\n 'content': review_content,\n })\n\n loaded_reviews.sort(key=lambda d: d['sequence'])\n\n for review in loaded_reviews:\n new_review = reviews.add(\n imdb_id=review['imdb_id'],\n year=review['year'],\n title=review['title'],\n review_date=review['date'],\n )\n\n new_review.review_content = review['content']\n new_review.save()\n\n\nif __name__ == '__main__':\n # main.prompt()\n fix_reviews()\n","sub_path":"bin/moviedb.py","file_name":"moviedb.py","file_ext":"py","file_size_in_byte":1597,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"150590720","text":"# -*- coding: utf-8 -*-\nfrom django.core.urlresolvers import reverse\nfrom django.utils.translation import ugettext as _\nfrom django.template.loader import get_template\nfrom django.template import Context\nfrom coop_cms.settings import get_article_class\nfrom django.conf import settings\nfrom coop_bar.utils import make_link\n\ndef can_do(perm, object_names):\n def inner_decorator(func):\n def wrapper(request, context):\n editable = context.get('editable')\n if not editable:\n return\n for object_name in object_names:\n object = context.get(object_name)\n if object and request.user.has_perm(perm+\"_\"+object_name, object):\n yes_we_can = func(request, context)\n if yes_we_can:\n return yes_we_can\n return\n return wrapper\n return inner_decorator\n\ncan_edit_article = can_do('can_edit', ['article'])\ncan_publish_article = can_do('can_publish', ['article'])\ncan_edit_newsletter = can_do('can_edit', ['newsletter'])\ncan_edit = can_do('can_edit', ['article', 'newsletter'])\n\ndef django_admin(request, context):\n if request.user.is_staff:\n return make_link(reverse(\"admin:index\"), _(u'Administration'), 'fugue/lock.png',\n classes=['icon', 'alert_on_click'])\n\ndef django_admin_add_article(request, context):\n if request.user.is_staff:\n article_class = get_article_class()\n view_name = 'admin:%s_%s_add' % (article_class._meta.app_label, article_class._meta.module_name)\n return make_link(reverse(view_name), _(u'Add article'), 'fugue/document--plus.png',\n classes=['icon', 'alert_on_click'])\n \ndef django_admin_edit_article(request, context):\n if request.user.is_staff and 'article' in context:\n article_class = get_article_class()\n article = context['article']\n view_name = 'admin:%s_%s_change' % (article_class._meta.app_label, article_class._meta.module_name)\n return make_link(reverse(view_name, args=[article.id]), _(u'Article settings'), 'fugue/gear.png',\n classes=['icon', 'alert_on_click'])\n\n@can_edit\ndef cms_media_library(request, context):\n if context.get('edit_mode'):\n return make_link(reverse('coop_cms_media_images'), _(u'Media library'), 'fugue/images-stack.png',\n 'coopbar_medialibrary', ['icon', 'slide'])\n\n@can_edit\ndef cms_upload_image(request, context):\n if context.get('edit_mode'):\n return make_link(reverse('coop_cms_upload_image'), _(u'Add image'), 'fugue/image--plus.png',\n classes=['coopbar_addfile', 'colorbox-form', 'icon'])\n\n@can_edit\ndef cms_upload_doc(request, context):\n if context.get('edit_mode'):\n return make_link(reverse('coop_cms_upload_doc'), _(u'Add document'), 'fugue/document--plus.png',\n classes=['coopbar_addfile', 'colorbox-form', 'icon'])\n\n@can_edit_article \ndef cms_change_template(request, context):\n if context.get('edit_mode'):\n article = context['article']\n url = reverse('coop_cms_change_template', args=[article.id])\n return make_link(url, _(u'Template'), 'fugue/application-blog.png',\n classes=['alert_on_click', 'colorbox-form', 'icon'])\n\n@can_edit_article\ndef cms_save(request, context):\n if context.get('edit_mode'):\n #No link, will be managed by catching the js click event\n return make_link('', _(u'Save'), 'fugue/disk-black.png', id=\"coopbar_save\",\n classes=['show-dirty', 'icon'])\n\n@can_edit_article\ndef cms_view(request, context):\n if context.get('edit_mode'):\n article = context['article']\n return make_link(article.get_cancel_url(), _(u'View'), 'fugue/eye--arrow.png',\n classes=['alert_on_click', 'icon', 'show-clean'])\n\n@can_edit_article\ndef cms_cancel(request, context):\n if context.get('edit_mode'):\n article = context['article']\n return make_link(article.get_cancel_url(), _(u'Cancel'), 'fugue/cross.png',\n classes=['alert_on_click', 'icon', 'show-dirty'])\n\n@can_edit_article\ndef cms_edit(request, context):\n if not context.get('edit_mode'):\n article = context['article']\n return make_link(article.get_edit_url(), _(u'Edit'), 'fugue/document--pencil.png',\n classes=['icon'])\n\n@can_publish_article\ndef cms_publish(request, context):\n if context['draft']:\n article = context['article']\n return make_link(article.get_publish_url(), _(u'Publish'), 'fugue/newspaper--arrow.png',\n classes=['publish', 'colorbox-form', 'icon'])\n\ndef cms_extra_js(request, context):\n try:\n editable = context['editable']\n t = get_template(\"coop_cms/_coop_bar_js.html\")\n return t.render(context)\n except KeyError:\n return None\n\ndef log_out(request, context):\n if request.user.is_authenticated():\n return make_link(reverse(\"django.contrib.auth.views.logout\"), _(u'Log out'), 'fugue/control-power.png',\n classes=['alert_on_click', 'icon'])\n\n@can_edit_newsletter\ndef edit_newsletter(request, context):\n if not context.get('edit_mode'):\n newsletter = context.get('newsletter')\n return make_link(newsletter.get_edit_url(), _(u'Edit'), 'fugue/document--pencil.png', classes=['icon'])\n\n@can_edit_newsletter\ndef cancel_edit_newsletter(request, context):\n if context.get('edit_mode'):\n newsletter = context.get('newsletter')\n return make_link(newsletter.get_absolute_url(), _(u'Cancel'), 'fugue/cross.png', classes=['icon'])\n\n@can_edit_newsletter\ndef save_newsletter(request, context):\n newsletter = context.get('newsletter')\n post_url = context.get('post_url')\n if context.get('edit_mode') and post_url:\n return make_link(post_url, _(u'Save'), 'fugue/disk-black.png',\n classes=['icon', 'post-form'])\n\n@can_edit_newsletter\ndef change_newsletter_settings(request, context):\n if context.get('edit_mode'):\n newsletter = context.get('newsletter')\n view_name = 'admin:coop_cms_newsletter_change'\n return make_link(reverse(view_name, args=[newsletter.id]), _(u'Newsletter settings'), 'fugue/gear.png',\n classes=['icon', 'alert_on_click'])\n\n@can_edit_newsletter\ndef change_newsletter_template(request, context):\n if context.get('edit_mode'):\n newsletter = context.get('newsletter')\n url = reverse('coop_cms_change_newsletter_template', args=[newsletter.id])\n return make_link(url, _(u'Newsletter template'), 'fugue/application-blog.png',\n classes=['alert_on_click', 'colorbox-form', 'icon'])\n\n@can_edit_newsletter\ndef test_newsletter(request, context):\n newsletter = context.get('newsletter')\n url = reverse('coop_cms_test_newsletter', args=[newsletter.id])\n return make_link(url, _(u'Send test'), 'fugue/mail-at-sign.png',\n classes=['alert_on_click', 'colorbox-form', 'icon'])\n\n@can_edit_newsletter\ndef schedule_newsletter(request, context):\n if not context.get('edit_mode'):\n newsletter = context.get('newsletter')\n url = reverse('coop_cms_schedule_newsletter_sending', args=[newsletter.id])\n return make_link(url, _(u'Schedule sending'), 'fugue/alarm-clock--arrow.png',\n classes=['alert_on_click', 'colorbox-form', 'icon'])\n\ndef load_commands(coop_bar):\n \n coop_bar.register([\n [django_admin, django_admin_add_article, django_admin_edit_article],\n [edit_newsletter, cancel_edit_newsletter, save_newsletter,\n change_newsletter_settings, change_newsletter_template,\n test_newsletter, schedule_newsletter],\n [cms_media_library, cms_upload_image, cms_upload_doc],\n [cms_edit],\n [cms_change_template],\n [cms_save, cms_publish, cms_cancel, cms_view],\n [log_out]\n ])\n \n coop_bar.register_header(cms_extra_js)\n","sub_path":"coop_cms/coop_bar_cfg.py","file_name":"coop_bar_cfg.py","file_ext":"py","file_size_in_byte":7854,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"318680539","text":"from TagHandler import *\nfrom properties import *\nimport discord\nclass TagLeague(Tag_Handler):\n async def run(client, payload):\n if payload.message_id == REACT_MSG and payload.emoji.name == '♌':\n member = client.get_guild(GUILD).get_member(payload.user_id)\n for role in member.roles:\n if role.name == 'Member':\n role = discord.utils.get(client.get_guild(GUILD).roles, name=\"[League Of Legends]\")\n try:\n await member.add_roles(role)\n except:\n print(\"Member rank too high!\")\n finally:\n break","sub_path":"TagLeague.py","file_name":"TagLeague.py","file_ext":"py","file_size_in_byte":683,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"426687559","text":"# -*- coding: utf-8 -*-\n\"\"\"\nreV module for calculating economies of scale where larger power plants will\nhave reduced capital cost.\n\"\"\"\nimport logging\nimport copy\nimport re\nimport numpy as np # pylint: disable=unused-import\nimport pandas as pd\n\nfrom reV.econ.utilities import lcoe_fcr\nfrom rex.utilities.utilities import check_eval_str\n\nlogger = logging.getLogger(__name__)\n\n\nclass EconomiesOfScale:\n \"\"\"Class to calculate economies of scale where power plant capital cost is\n reduced for larger power plants.\n\n Units\n -----\n capacity_factor : unitless\n capacity : kW\n annual_energy_production : kWh\n fixed_charge_rate : unitless\n fixed_operating_cost : $ (per year)\n variable_operating_cost : $/kWh\n lcoe : $/MWh\n \"\"\"\n\n def __init__(self, eqn, data):\n \"\"\"\n Parameters\n ----------\n eqn : str\n LCOE scaling equation to implement \"economies of scale\".\n Equation must be in python string format and return a scalar\n value to multiply the capital cost by. Independent variables in\n the equation should match the keys in the data input arg. This\n equation may use numpy functions with the package prefix \"np\".\n data : dict | pd.DataFrame\n Namespace of econ data to use to calculate economies of scale. Keys\n in dict or column labels in dataframe should match the Independent\n variables in the eqn input. Should also include variables required\n to calculate LCOE.\n \"\"\"\n self._eqn = eqn\n self._data = data\n self._preflight()\n\n def _preflight(self):\n \"\"\"Run checks to validate EconomiesOfScale equation and input data.\"\"\"\n\n if self._eqn is not None:\n check_eval_str(str(self._eqn))\n\n if isinstance(self._data, pd.DataFrame):\n self._data = {k: self._data[k].values.flatten()\n for k in self._data.columns}\n\n if not isinstance(self._data, dict):\n e = ('Cannot evaluate EconomiesOfScale with data input of type: {}'\n .format(type(self._data)))\n logger.error(e)\n raise TypeError(e)\n\n missing = []\n for name in self.vars:\n if name not in self._data:\n missing.append(name)\n\n if any(missing):\n e = ('Cannot evaluate EconomiesOfScale, missing data for variables'\n ': {} for equation: {}'.format(missing, self._eqn))\n logger.error(e)\n raise KeyError(e)\n\n @staticmethod\n def is_num(s):\n \"\"\"Check if a string is a number\"\"\"\n try:\n float(s)\n except ValueError:\n return False\n else:\n return True\n\n @staticmethod\n def is_method(s):\n \"\"\"Check if a string is a numpy/pandas or python builtin method\"\"\"\n return bool(s.startswith(('np.', 'pd.')) or s in dir(__builtins__))\n\n @property\n def vars(self):\n \"\"\"Get a list of variable names that the EconomiesOfScale equation\n uses as input.\n\n Returns\n -------\n vars : list\n List of strings representing variable names that were parsed from\n the equation string. This will return an empty list if the equation\n has no variables.\n \"\"\"\n var_names = []\n if self._eqn is not None:\n delimiters = ('*', '/', '+', '-', ' ', '(', ')', '[', ']', ',')\n regex_pattern = '|'.join(map(re.escape, delimiters))\n var_names = []\n for sub in re.split(regex_pattern, str(self._eqn)):\n if sub:\n if not self.is_num(sub) and not self.is_method(sub):\n var_names.append(sub)\n var_names = sorted(list(set(var_names)))\n\n return var_names\n\n def _evaluate(self):\n \"\"\"Evaluate the EconomiesOfScale equation with Independent variables\n parsed into a kwargs dictionary input.\n\n Returns\n -------\n out : float | np.ndarray\n Evaluated output of the EconomiesOfScale equation. Should be\n numeric scalars to apply directly to the capital cost.\n \"\"\"\n out = 1\n if self._eqn is not None:\n kwargs = {k: self._data[k] for k in self.vars}\n # pylint: disable=eval-used\n out = eval(str(self._eqn), globals(), kwargs)\n\n return out\n\n @staticmethod\n def _get_prioritized_keys(input_dict, key_list):\n \"\"\"Get data from an input dictionary based on an ordered (prioritized)\n list of retrieval keys. If no keys are found in the input_dict, an\n error will be raised.\n\n Parameters\n ----------\n input_dict : dict\n Dictionary of data\n key_list : list | tuple\n Ordered (prioritized) list of retrieval keys.\n\n Returns\n -------\n out : object\n Data retrieved from input_dict using the first key in key_list\n found in the input_dict.\n \"\"\"\n\n out = None\n for key in key_list:\n if key in input_dict:\n out = input_dict[key]\n break\n\n if out is None:\n e = ('Could not find requested key list ({}) in the input '\n 'dictionary keys: {}'\n .format(key_list, list(input_dict.keys())))\n logger.error(e)\n raise KeyError(e)\n\n return out\n\n @property\n def capital_cost_scalar(self):\n \"\"\"Evaluated output of the EconomiesOfScale equation. Should be\n numeric scalars to apply directly to the capital cost.\n\n Returns\n -------\n out : float | np.ndarray\n Evaluated output of the EconomiesOfScale equation. Should be\n numeric scalars to apply directly to the capital cost.\n \"\"\"\n return self._evaluate()\n\n @property\n def raw_capital_cost(self):\n \"\"\"Unscaled (raw) capital cost found in the data input arg.\n\n Returns\n -------\n out : float | np.ndarray\n Unscaled (raw) capital_cost found in the data input arg.\n \"\"\"\n key_list = ['capital_cost', 'mean_capital_cost']\n return self._get_prioritized_keys(self._data, key_list)\n\n @property\n def scaled_capital_cost(self):\n \"\"\"Capital cost found in the data input arg scaled by the evaluated\n EconomiesOfScale input equation.\n\n Returns\n -------\n out : float | np.ndarray\n Capital cost found in the data input arg scaled by the evaluated\n EconomiesOfScale equation.\n \"\"\"\n cc = copy.deepcopy(self.raw_capital_cost)\n cc *= self.capital_cost_scalar\n return cc\n\n @property\n def system_capacity(self):\n \"\"\"Get the system capacity in kW (SAM input, not the reV supply\n curve capacity).\n\n Returns\n -------\n out : float | np.ndarray\n \"\"\"\n key_list = ['system_capacity', 'mean_system_capacity']\n return self._get_prioritized_keys(self._data, key_list)\n\n @property\n def fcr(self):\n \"\"\"Fixed charge rate from input data arg\n\n Returns\n -------\n out : float | np.ndarray\n Fixed charge rate from input data arg\n \"\"\"\n key_list = ['fixed_charge_rate', 'mean_fixed_charge_rate',\n 'fcr', 'mean_fcr']\n return self._get_prioritized_keys(self._data, key_list)\n\n @property\n def foc(self):\n \"\"\"Fixed operating cost from input data arg\n\n Returns\n -------\n out : float | np.ndarray\n Fixed operating cost from input data arg\n \"\"\"\n key_list = ['fixed_operating_cost', 'mean_fixed_operating_cost',\n 'foc', 'mean_foc']\n return self._get_prioritized_keys(self._data, key_list)\n\n @property\n def voc(self):\n \"\"\"Variable operating cost from input data arg\n\n Returns\n -------\n out : float | np.ndarray\n Variable operating cost from input data arg\n \"\"\"\n key_list = ['variable_operating_cost', 'mean_variable_operating_cost',\n 'voc', 'mean_voc']\n return self._get_prioritized_keys(self._data, key_list)\n\n @property\n def aep(self):\n \"\"\"Annual energy production back-calculated from the raw LCOE:\n\n AEP = (fcr * raw_cap_cost + foc) / raw_lcoe\n\n Returns\n -------\n out : float | np.ndarray\n \"\"\"\n\n aep = (self.fcr * self.raw_capital_cost + self.foc) / self.raw_lcoe\n aep *= 1000 # convert MWh to KWh\n return aep\n\n @property\n def raw_lcoe(self):\n \"\"\"Raw LCOE taken from the input data\n\n Returns\n -------\n lcoe : float | np.ndarray\n \"\"\"\n key_list = ['raw_lcoe', 'mean_lcoe']\n return copy.deepcopy(self._get_prioritized_keys(self._data, key_list))\n\n @property\n def scaled_lcoe(self):\n \"\"\"LCOE calculated with the scaled capital cost based on the\n EconomiesOfScale input equation.\n\n LCOE = (FCR * scaled_capital_cost + FOC) / AEP + VOC\n\n Returns\n -------\n lcoe : float | np.ndarray\n LCOE calculated with the scaled capital cost based on the\n EconomiesOfScale input equation.\n \"\"\"\n return lcoe_fcr(self.fcr, self.scaled_capital_cost, self.foc,\n self.aep, self.voc)\n","sub_path":"reV/econ/economies_of_scale.py","file_name":"economies_of_scale.py","file_ext":"py","file_size_in_byte":9485,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"502037932","text":"import time\nimport threading\n\ndef fun():\n print(\"fun函数开头\")\n time.sleep(2)\n print(\"睡醒了的fun\")\n\nprint(\"程序的入口\")\nt = threading.Thread(target=fun,args=())\n#守护线程的方法,必须在start之前设置,否则无效\nt.daemon=True\n#t.setDaemon(True)\nt.start()\ntime.sleep(1)\nprint(\"程序的结束口\")#执行这句话主线程就结束了,但是子线程却还在执行","sub_path":"多线程/05.py","file_name":"05.py","file_ext":"py","file_size_in_byte":405,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"650127546","text":"from django.urls import path\nfrom . import views\nfrom .views import (\n\tPost_ListView, \n\tPost_DetailView, \n\tPost_CreateView,\n\tPost_DeleteView,\n\tuserPost_ListView,\n LikeView\n)\n\nurlpatterns = [\n #path('', views.home, name='blog-home'), \n path('', Post_ListView.as_view(), name='blog-home'),\n path('user//', userPost_ListView.as_view(), name='blog-user_post'),\n path('post//', Post_DetailView.as_view(), name='post-detail'),\n path('post//delete/', Post_DeleteView.as_view(), name='post-delete'), # model_confirm_delete\n path('post/create/', Post_CreateView.as_view(), name='post-create'), # template is 'model_form.html'\n path('about/', views.about, name='blog-about'),\n path('post/', LikeView, name='like_post'),\n]","sub_path":"myblog/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":776,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"639199398","text":"from django.shortcuts import redirect\nfrom django.urls import reverse # ? Permite obtener url apartir del nombre\nfrom users.models import Profile\n\n\nclass ProfileCompletionMiddleware:\n \"\"\" Ensure that the new user create profile\n to use the application\n \"\"\"\n\n def __init__(self, get_response):\n self.get_response = get_response\n\n def __call__(self, request):\n if not request.user.is_anonymous:\n # ? en el caso de que no tenga el usuario un perfil se crea uno\n try:\n profile = request.user.profile\n except:\n profile = Profile.objects.create(user=request.user)\n profile.save()\n if not request.user.is_staff:\n if not profile.pictureUser or not profile.biography:\n # ? verifica que el path sea diferente a update_profile y logout\n if request.path not in [reverse('users:update_profile'), reverse('users:logout')]:\n return redirect('users:update_profile')\n\n response = self.get_response(request)\n return response\n","sub_path":"platzigram/middleware.py","file_name":"middleware.py","file_ext":"py","file_size_in_byte":1116,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"314335385","text":"from __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\n\nclass Node(object):\n \"\"\"Node class for Trie class.\"\"\"\n def __init__(self):\n # Each node has a children dict of char->node.\n self.children = {}\n self.word = None\n\n\nclass Trie(object):\n \"\"\"Trie class.\n\n Methods:\n - insert()\n - search()\n - delete()\n - search_prefix()\n - have_prefix()\n \"\"\"\n def __init__(self):\n self.root = Node()\n\n def insert(self, word):\n \"\"\"Insert a word.\n\n Time complexity: O(k), where k is the word length.\n Space complexity: O(k).\n \"\"\"\n current = self.root\n\n # Go through each char in word, check it exists or not in children.\n # If char exist, visit it's child; if not, create child node.\n for c in word:\n if c in current.children:\n current = current.children[c]\n else:\n current.children[c] = Node()\n current = current.children[c]\n\n current.word = word\n\n def search(self, word):\n \"\"\"Search a word.\n\n Time complexity: O(k), where k is the word length.\n Space complexity: O(1).\n \"\"\"\n current = self.root\n\n # Go through each char in word and check its existence in children.\n # Finally arrive at the word node.\n for c in word:\n if c in current.children:\n current = current.children[c]\n else:\n return False\n\n # Check the word exists or not.\n if current.word == word:\n return True\n else:\n return False\n\n def delete(self, word):\n \"\"\"Delete a word.\n\n Time complexity: O(k), where k is the word length. \n Space complexity: O(k).\n \"\"\"\n current = self.root\n\n # Use stack to track all visiting chars.\n stack = [current]\n\n # Go through each char in word and check its existence in children.\n # Finally arrive at the word node.\n for c in word:\n if c in current.children:\n current = current.children[c]\n stack.append(current)\n else:\n # The word does not exist.\n return None\n\n if current.children:\n # If word node has any children, just remove its payload.\n current.word = None\n return None\n else:\n # If no children, check char in reversed order.\n # Further, if char has no children, pop it from children dict.\n stack.pop()\n\n for c in word[::-1]:\n if not current.children:\n # Backtrack to the previous char.\n current = stack.pop()\n current.children.pop(c)\n else:\n break\n\n def search_prefix(self, prefix):\n \"\"\"Search a prefix.\n\n Time complexity: O(k), where k is the prefix length.\n Space complexity: O(1).\n \"\"\"\n current = self.root\n\n # Go through each char in prefix and check its existence in children.\n # Finally arrive at the prefix node.\n for c in prefix:\n if c in current.children:\n current = current.children[c]\n else:\n return False\n\n return True\n\n def have_prefix(self, prefix):\n \"\"\"Get words starting with prefix.\n\n Time complexity: O(l*m), where \n - l is the average word lenght,\n - m is the average number of connected words for each word.\n Space complexity: O(l*m).\n \"\"\"\n current = self.root\n\n words = []\n\n # Go through each char in prefix and check its existence in children.\n # Finally arrive at the prefix node.\n for c in prefix:\n if c in current.children:\n current = current.children[c]\n else:\n # The prefix does not exits.\n return None\n \n # Check whether prefix is a word, if yes, append it first.\n if current.word:\n words.append(current.word)\n\n # Run BFS with queue to collect the following words with prefix.\n queue = [current]\n\n while queue:\n node = queue.pop()\n for c, c_node in node.children.items():\n queue.insert(0, c_node)\n if c_node.word:\n words.append(c_node.word)\n\n return words\n\n\ndef main():\n trie = Trie()\n\n # Trie example: https://www.youtube.com/watch?v=AXjmTQ8LEoI\n trie.insert('abc')\n print('{}'.format(trie.root\n .children['a'].children['b']\n .children['c'].word))\n\n trie.insert('abgl')\n trie.insert('cdf')\n trie.insert('abcd')\n trie.insert('lmn')\n trie.insert('lmnz')\n\n print('Prefix \"ab\": {}'.format(trie.root\n .children['a'].children['b']\n .children.keys()))\n\n print('Search word \"abgl\" (True): {}'.format(trie.search('abgl')))\n print('Search word \"cdf\" (True): {}'.format(trie.search('cdf')))\n print('Search word \"abcd\" (True): {}'.format(trie.search('abcd')))\n print('Search word \"lmn\" (True): {}'.format(trie.search('lmn')))\n\n print('Search prefix \"ab\" (True): {}'.format(trie.search_prefix('ab')))\n print('Search prefix \"lo\" (False): {}'.format(trie.search_prefix('lo')))\n\n print('Start with prefix \"ab\": (abc, abgl, abcd): {}'\n .format(trie.have_prefix('ab')))\n print('Start with prefix \"abc\": (abc, abcd): {}'\n .format(trie.have_prefix('abc')))\n print('Start with prefix \"cd\": (cdf): {}'\n .format(trie.have_prefix('cd')))\n\n print('Search word \"lmn\" (True): {}'.format(trie.search('lmn')))\n print('Search word \"ab\" (False): {}'.format(trie.search('ab')))\n print('Search word \"cdf\" (True): {}'.format(trie.search('cdf')))\n print('Search word \"ghi\" (False): {}'.format(trie.search('ghi')))\n\n print('Delete word \"abc\":')\n trie.delete('abc')\n print('Search word \"abc\" (False): {}'.format(trie.search('abc')))\n print('Show keys with prefix \"ab\": {}'.format(\n trie.root\n .children['a'].children['b']\n .children.keys()))\n\n print('Delete word \"abgl\":')\n trie.delete('abgl')\n print('Search word \"abgl\" (False): {}'.format(trie.search('abgl')))\n print('Show children with prefix \"ab\": {}'.format(\n trie.root\n .children['a'].children['b']\n .children.keys()))\n print('Show children with prefix \"abc\": {}'.format(\n trie.root\n .children['a'].children['b']\n .children['c'].children.keys()))\n\n print('Delete word \"abcd\":')\n trie.delete('abcd')\n print('Search word \"abcd\" (False): {}'.format(trie.search('abcd')))\n print('Show root\\'s children: {}'.format(trie.root.children.keys()))\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"ds_trie.py","file_name":"ds_trie.py","file_ext":"py","file_size_in_byte":6908,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"60493988","text":"\"\"\"\n\ndjsupervisor.config: config loading and merging code for djsupervisor\n----------------------------------------------------------------------\n\nThe code in this module is responsible for finding the supervisord.conf\nfiles from all installed apps, merging them together with the config\nfiles from your project and any options specified on the command-line,\nand producing a final config file to control supervisord/supervisorctl.\n\n\"\"\"\n\nimport sys\nimport os\nimport hashlib\n\ntry:\n from cStringIO import StringIO\nexcept ImportError:\n from StringIO import StringIO\n\nfrom ConfigParser import RawConfigParser, NoSectionError, NoOptionError\n\nfrom django import template\nfrom django.conf import settings\nfrom django.utils.importlib import import_module\n \n\nCONFIG_FILE_NAME = \"supervisord.conf\"\n\n\ndef get_merged_config(**options):\n \"\"\"Get the final merged configuration for supvervisord, as a string.\n\n This is the top-level function exported by this module. It collects\n the various config files from installed applications and the main project,\n combines them together based on priority, and returns the resulting\n configuration as a string.\n \"\"\"\n # Find and load the containing project module.\n # This is assumed to be the top-level package containing settings module.\n # If it doesn't contain a manage.py script, we're in trouble.\n projname = settings.SETTINGS_MODULE.split(\".\",1)[0]\n projmod = import_module(projname)\n projdir = os.path.dirname(projmod.__file__)\n if not os.path.isfile(os.path.join(projdir,\"manage.py\")):\n msg = \"Project %s doesn't have a ./manage.py\" % (projname,)\n raise RuntimeError(msg)\n # Build the default template context variables.\n # This is mostly useful information about the project and environment.\n ctx = {\n \"PROJECT_DIR\": projdir,\n \"PYTHON\": os.path.realpath(os.path.abspath(sys.executable)),\n \"SUPERVISOR_OPTIONS\": rerender_options(options),\n \"settings\": settings,\n \"environ\": os.environ,\n }\n # Initialise the ConfigParser.\n # Fortunately for us, ConfigParser has merge-multiple-config-files\n # functionality built into it. You just read each file in turn, and\n # values from later files overwrite values from former.\n cfg = RawConfigParser()\n # Start from the default configuration options.\n data = render_config(DEFAULT_CONFIG,ctx)\n cfg.readfp(StringIO(data))\n # Add in each app-specific file in turn.\n for data in find_app_configs(ctx,projmod):\n cfg.readfp(StringIO(data))\n # Add in the project-specific config file.\n projcfg = os.path.join(projdir,CONFIG_FILE_NAME)\n if os.path.isfile(projcfg):\n with open(projcfg,\"r\") as f:\n data = render_config(f.read(),ctx)\n cfg.readfp(StringIO(data))\n # Add in the options specified on the command-line.\n cfg.readfp(StringIO(get_config_from_options(**options)))\n # Add options from [program:__defaults__] to each program section\n # if it happens to be missing that option.\n PROG_DEFAULTS = \"program:__defaults__\"\n if cfg.has_section(PROG_DEFAULTS):\n for option in cfg.options(PROG_DEFAULTS):\n default = cfg.get(PROG_DEFAULTS,option)\n for section in cfg.sections():\n if section.startswith(\"program:\"):\n if not cfg.has_option(section,option):\n cfg.set(section,option,default)\n cfg.remove_section(PROG_DEFAULTS)\n # Add options from [program:__overrides__] to each program section\n # regardless of whether they already have that option.\n PROG_OVERRIDES = \"program:__overrides__\"\n if cfg.has_section(PROG_OVERRIDES):\n for option in cfg.options(PROG_OVERRIDES):\n override = cfg.get(PROG_OVERRIDES,option)\n for section in cfg.sections():\n if section.startswith(\"program:\"):\n cfg.set(section,option,override)\n cfg.remove_section(PROG_OVERRIDES)\n # Make sure we've got a port configured for supervisorctl to\n # talk to supervisord. It's passworded based on secret key.\n # If they have configured a unix socket then use that, otherwise\n # use an inet server on localhost at fixed-but-randomish port.\n username = hashlib.md5(settings.SECRET_KEY).hexdigest()[:7]\n password = hashlib.md5(username).hexdigest()\n if cfg.has_section(\"unix_http_server\"):\n set_if_missing(cfg,\"unix_http_server\",\"username\",username)\n set_if_missing(cfg,\"unix_http_server\",\"password\",password)\n serverurl = \"unix://\" + cfg.get(\"unix_http_server\",\"file\")\n else:\n # This picks a \"random\" port in the 9000 range to listen on.\n # It's derived from the secret key, so it's stable for a given\n # project but multiple projects are unlikely to collide.\n port = int(hashlib.md5(password).hexdigest()[:3],16) % 1000\n addr = \"127.0.0.1:9%03d\" % (port,)\n set_if_missing(cfg,\"inet_http_server\",\"port\",addr)\n set_if_missing(cfg,\"inet_http_server\",\"username\",username)\n set_if_missing(cfg,\"inet_http_server\",\"password\",password)\n serverurl = \"http://\" + cfg.get(\"inet_http_server\",\"port\")\n set_if_missing(cfg,\"supervisorctl\",\"serverurl\",serverurl)\n set_if_missing(cfg,\"supervisorctl\",\"username\",username)\n set_if_missing(cfg,\"supervisorctl\",\"password\",password)\n set_if_missing(cfg,\"rpcinterface:supervisor\",\n \"supervisor.rpcinterface_factory\",\n \"supervisor.rpcinterface:make_main_rpcinterface\")\n # Remove any [program:] sections with exclude=true\n for section in cfg.sections():\n try:\n if cfg.getboolean(section,\"exclude\"):\n cfg.remove_section(section)\n except NoOptionError:\n pass\n # Sanity-check to give better error messages.\n for section in cfg.sections():\n if section.startswith(\"program:\"):\n if not cfg.has_option(section,\"command\"):\n msg = \"Process name '%s' has no command configured\"\n raise ValueError(msg % (section.split(\":\",1)[-1]))\n # Write it out to a StringIO and return the data\n s = StringIO()\n cfg.write(s)\n return s.getvalue()\n\n\ndef render_config(data,ctx):\n \"\"\"Render the given config data using Django's template system.\n\n This function takes a config data string and a dict of context variables,\n renders the data through Django's template system, and returns the result.\n \"\"\"\n t = template.Template(data)\n c = template.Context(ctx)\n return t.render(c).encode(\"ascii\")\n\n\ndef find_app_configs(ctx,projmod):\n \"\"\"Generator yielding app-provided config file data.\n\n This function searches for supervisord config files within each of the\n installed apps, in the order they are listed in INSTALLED_APPS. Each\n file found is rendered and the resulting contents yielded as a string.\n\n If the app ships with a management/supervisord.conf file, then that file\n is used. Otherwise, we look for one under the djsupervisor \"contrib\"\n directory. Only one of the two files is used, to prevent us from \n clobbering settings specified by app authors.\n \"\"\"\n contrib_dir = os.path.join(os.path.dirname(__file__),\"contrib\")\n for appname in settings.INSTALLED_APPS:\n appfile = None\n # Look first in the application directory.\n appmod = import_module(appname)\n try:\n appdir = os.path.dirname(appmod.__file__)\n except AttributeError:\n pass\n else:\n appfile = os.path.join(appdir,\"management\",CONFIG_FILE_NAME)\n if not os.path.isfile(appfile):\n appfile = None\n # If that didn't work, try the djsupervisor contrib directory\n if appfile is None:\n appdir = os.path.join(contrib_dir,appname.replace(\".\",os.sep))\n appfile = os.path.join(appdir,CONFIG_FILE_NAME)\n if not os.path.isfile(appfile):\n appfile = None\n # If we found one, render and yield it.\n if appfile is not None:\n # Add extra context info about the application.\n app_ctx = {\n \"APP_DIR\": os.path.dirname(appmod.__file__),\n }\n app_ctx.update(ctx)\n with open(appfile,\"r\") as f:\n yield render_config(f.read(),app_ctx)\n\n\ndef get_config_from_options(**options):\n \"\"\"Get config file fragment reflecting command-line options.\"\"\"\n data = []\n # Set whether or not to daemonize.\n # Unlike supervisord, our default is to stay in the foreground.\n if options.get(\"daemonize\",False):\n data.append(\"[supervisord]\\nnodaemon=false\\n\")\n else:\n data.append(\"[supervisord]\\nnodaemon=true\\n\")\n # Set which programs to launch automatically on startup.\n for progname in options.get(\"launch\",None) or []:\n data.append(\"[program:%s]\\nautostart=true\\n\" % (progname,))\n for progname in options.get(\"nolaunch\",None) or []:\n data.append(\"[program:%s]\\nautostart=false\\n\" % (progname,))\n # Set which programs to include/exclude from the config\n for progname in options.get(\"include\",None) or []:\n data.append(\"[program:%s]\\nexclude=false\\n\" % (progname,))\n for progname in options.get(\"exclude\",None) or []:\n data.append(\"[program:%s]\\nexclude=true\\n\" % (progname,))\n # Set which programs to autoreload when code changes.\n # When this option is specified, the default for all other\n # programs becomes autoreload=false.\n if options.get(\"autoreload\",None):\n data.append(\"[program:autoreload]\\nexclude=false\\nautostart=true\\n\")\n data.append(\"[program:__defaults__]\\nautoreload=false\\n\")\n for progname in options[\"autoreload\"]:\n data.append(\"[program:%s]\\nautoreload=true\\n\" % (progname,))\n # Set whether to use the autoreloader at all.\n if options.get(\"noreload\",False):\n data.append(\"[program:autoreload]\\nexclude=true\\n\")\n return \"\".join(data)\n\n\ndef set_if_missing(cfg,section,option,value):\n \"\"\"If the given option is missing, set to the given value.\"\"\"\n try:\n cfg.get(section,option)\n except NoSectionError:\n cfg.add_section(section)\n cfg.set(section,option,value)\n except NoOptionError:\n cfg.set(section,option,value)\n\n\ndef rerender_options(options):\n \"\"\"Helper function to re-render command-line options.\n\n This assumes that command-line options use the same name as their\n key in the options dictionary.\n \"\"\"\n args = []\n for name,value in options.iteritems():\n if value is None:\n pass\n elif isinstance(value,bool):\n if value:\n args.append(\"--%s\" % (name,))\n elif isinstance(value,list):\n for item in value:\n args.append(\"--%s=%s\" % (name,item))\n else:\n args.append(\"--%s=%s\" % (name,value))\n return \" \".join(args)\n\n\n# These are the default configuration options provided by djsupervisor.\n#\nDEFAULT_CONFIG = \"\"\"\n\n; We always provide the 'runserver' process to run the dev server.\n[program:runserver]\ncommand={{ PYTHON }} {{ PROJECT_DIR }}/manage.py runserver --noreload\n\n; In debug mode, we watch for changes in the project directory and inside\n; any installed apps. When something changes, restart all processes.\n[program:autoreload]\ncommand={{ PYTHON }} {{ PROJECT_DIR }}/manage.py supervisor {{ SUPERVISOR_OPTIONS }} autoreload\nautoreload=true\n{% if not settings.DEBUG %}\nexclude=true\n{% endif %}\n\n; All programs are auto-reloaded by default.\n[program:__defaults__]\nautoreload=true\nredirect_stderr=true\n\n[supervisord]\n{% if settings.DEBUG %}\nloglevel=debug\n{% endif %}\n\n\n\"\"\"\n\n","sub_path":"djsupervisor/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":11756,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"317345279","text":"import unittest\n\nfrom hand import Hand\nfrom knife import Knife\nfrom knight import Knight\n\n\nclass KnightTest(unittest.TestCase):\n\n def test_attack_by_hand(self):\n # setup\n knight = self.create_knight() # delegated setup\n\n # exercise\n pain = knight.attack_power()\n\n # verify\n self.assertEqual(pain, Hand().attack_power())\n\n def test_attack_by_knife(self):\n # setup\n knight = self.create_knight_with_knife() # delegated setup\n\n # exercise\n pain = knight.attack_power()\n\n # verify\n self.assertEqual(pain, Knife().attack_power())\n\n def create_knight_with_knife(self):\n knight = self.create_knight()\n knight.arms = Knife()\n return knight\n\n @classmethod\n def create_knight(cls) -> Knight:\n return Knight(100)\n\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"2020/04/20200402_Delegated_Setup/test_knight.py","file_name":"test_knight.py","file_ext":"py","file_size_in_byte":880,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"520303986","text":"from django.conf.urls import patterns, include, url\nfrom django.contrib import admin\n\n# Uncomment the next two lines to enable the admin:\n# from django.contrib import admin\nadmin.autodiscover()\n\nurlpatterns = patterns('rbac.views',\n # Examples:\n url(r'^$', 'home'),\n # url(r'^accounts/login/$', 'login'),\n url(r'^register$', 'register'),\n url(r'^Employee/create$', 'createEmployee', name='createEmployee'),\n url(r'^Role/(?P\\d+)/edit$', 'editRole', name='editRole'),\n url(r'^(?P\\w+)/(?P\\d+)/edit$', 'edit', name='edit'),\n url(r'^(?P\\w+)/(?P\\d+)/del$', 'delete', name='delete'),\n url(r'^(?P[A-Z]{1}\\w+)/view$', 'view', name='view'),\n url(r'^(?P[A-Z]{1}\\w+)/create$', 'create', name='create'),\n \n url(r'^role/new$', 'role'),\n url(r'^tabela/$', 'tabs'),\n\n url(r'^accounts/profile/$', 'rolechoose', name='rolechoose'),\n url(r'^register/$', 'register', name='register'),\n url(r'^logout/$', 'logoutHandler', name='logout'),\n # url(r'^bsk/', include('bsk.foo.urls')),\n\n # Uncomment the admin/doc line below to enable admin documentation:\n # url(r'^admin/doc/', include('django.contrib.admindocs.urls')),\n\n # Uncomment the next line to enable the admin:\n url(r'^admin/', include(admin.site.urls)),\n)\nurlpatterns += patterns('',\n url(r'^accounts/login/$', 'django.contrib.auth.views.login', name='login'),\n)\nhandler404 = 'rbac.views.fourzerofour'\n","sub_path":"bsk/bsk/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1444,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"528640669","text":"import asyncio\nimport inspect\nimport functools\n\nfrom aiocache.log import logger\nfrom aiocache import SimpleMemoryCache, caches\nfrom aiocache.serializers import JsonSerializer\n\n\nclass cached:\n \"\"\"\n Caches the functions return value into a key generated with module_name, function_name and args.\n\n In some cases you will need to send more args to configure the cache object.\n An example would be endpoint and port for the RedisCache. You can send those args as\n kwargs and they will be propagated accordingly.\n\n Each call will use the same connection through all the cache calls. If you expect high\n concurrency for the function you are decorating, it will be safer if you set high pool sizes\n (in case of using memcached or redis).\n\n :param ttl: int seconds to store the function call. Default is None which means no expiration.\n :param key: str value to set as key for the function return. Takes precedence over\n key_from_attr param. If key and key_from_attr are not passed, it will use module_name\n + function_name + args + kwargs\n :param key_from_attr: str arg or kwarg name from the function to use as a key.\n :param cache: cache class to use when calling the ``set``/``get`` operations.\n Default is ``aiocache.SimpleMemoryCache``.\n :param serializer: serializer instance to use when calling the ``dumps``/``loads``.\n Default is JsonSerializer.\n :param plugins: list plugins to use when calling the cmd hooks\n Default is pulled from the cache class being used.\n :param alias: str specifying the alias to load the config from. If alias is passed, other config\n parameters are ignored. New cache is created every time.\n :param noself: bool if you are decorating a class function, by default self is also used to\n generate the key. This will result in same function calls done by different class instances\n to use different cache keys. Use noself=True if you want to ignore it.\n \"\"\"\n\n def __init__(\n self, ttl=None, key=None, key_from_attr=None, cache=SimpleMemoryCache,\n serializer=JsonSerializer, plugins=None, alias=None, noself=False, **kwargs):\n self.ttl = ttl\n self.key = key\n self.key_from_attr = key_from_attr\n self.noself = noself\n self.alias = alias\n self.cache = None\n self._conn = None\n\n self._cache = cache\n self._serializer = serializer\n self._plugins = plugins\n self._kwargs = kwargs\n\n @property\n def conn(self):\n return self._conn\n\n def __call__(self, f):\n\n if self.alias:\n self.cache = caches.create(self.alias)\n else:\n self.cache = _get_cache(\n cache=self._cache, serializer=self._serializer,\n plugins=self._plugins, **self._kwargs)\n\n @functools.wraps(f)\n async def wrapper(*args, **kwargs):\n return await self.decorator(f, *args, **kwargs)\n return wrapper\n\n async def decorator(self, f, *args, **kwargs):\n self._conn = self.cache.get_connection()\n\n async with self._conn:\n key = self.get_cache_key(f, args, kwargs)\n\n value = await self.get_from_cache(key)\n if value is not None:\n return value\n\n result = await f(*args, **kwargs)\n\n await self.set_in_cache(key, result)\n\n return result\n\n def get_cache_key(self, f, args, kwargs):\n if self.key:\n return self.key\n\n args_dict = _get_args_dict(f, args, kwargs)\n cache_key = args_dict.get(\n self.key_from_attr, self._key_from_args(f, args, kwargs))\n return cache_key\n\n def _key_from_args(self, func, args, kwargs):\n ordered_kwargs = sorted(kwargs.items())\n return (func.__module__ or '') + func.__name__ + str(\n args[1:] if self.noself else args) + str(ordered_kwargs)\n\n async def get_from_cache(self, key):\n try:\n value = await self.conn.get(key)\n if value is not None:\n asyncio.ensure_future(self.cache.close())\n return value\n except Exception:\n logger.exception(\"Couldn't retrieve %s, unexpected error\", key)\n\n async def set_in_cache(self, key, value):\n try:\n await self.conn.set(key, value, ttl=self.ttl)\n except Exception:\n logger.exception(\"Couldn't set %s in key %s, unexpected error\", value, key)\n\n\nclass cached_stampede(cached):\n \"\"\"\n Caches the functions return value into a key generated with module_name, function_name and args\n while avoids for cache stampede effects.\n\n In some cases you will need to send more args to configure the cache object.\n An example would be endpoint and port for the RedisCache. You can send those args as\n kwargs and they will be propagated accordingly.\n\n This decorator doesn't reuse connections because it would lock the connection while its\n locked waiting for the first call to finish calculating and this is counterproductive.\n\n :param lease: int seconds to lock function call to avoid cache stampede effects.\n If 0 or None, no locking happens (default is 2). redis and memory backends support\n float ttls\n :param ttl: int seconds to store the function call. Default is None which means no expiration.\n :param key: str value to set as key for the function return. Takes precedence over\n key_from_attr param. If key and key_from_attr are not passed, it will use module_name\n + function_name + args + kwargs\n :param key_from_attr: str arg or kwarg name from the function to use as a key.\n :param cache: cache class to use when calling the ``set``/``get`` operations.\n Default is ``aiocache.SimpleMemoryCache``.\n :param serializer: serializer instance to use when calling the ``dumps``/``loads``.\n Default is JsonSerializer.\n :param plugins: list plugins to use when calling the cmd hooks\n Default is pulled from the cache class being used.\n :param alias: str specifying the alias to load the config from. If alias is passed, other config\n parameters are ignored. New cache is created every time.\n :param noself: bool if you are decorating a class function, by default self is also used to\n generate the key. This will result in same function calls done by different class instances\n to use different cache keys. Use noself=True if you want to ignore it.\n \"\"\"\n def __init__(\n self, lease=2, **kwargs):\n super().__init__(**kwargs)\n self.lease = lease\n\n @property\n def conn(self):\n return self.cache\n\n async def decorator(self, f, *args, **kwargs):\n key = self.get_cache_key(f, args, kwargs)\n\n value = await self.get_from_cache(key)\n if value is not None:\n return value\n\n async with self.conn._redlock(key, self.lease):\n value = await self.get_from_cache(key)\n if value is not None:\n return value\n\n result = await f(*args, **kwargs)\n\n await self.set_in_cache(key, result)\n\n return result\n\n\ndef _get_cache(\n cache=SimpleMemoryCache, serializer=None, plugins=None, **cache_kwargs):\n return cache(serializer=serializer, plugins=plugins, **cache_kwargs)\n\n\ndef _get_args_dict(func, args, kwargs):\n defaults = {\n arg_name: arg.default for arg_name, arg in inspect.signature(func).parameters.items()\n if arg.default is not inspect._empty\n }\n args_names = func.__code__.co_varnames[:func.__code__.co_argcount]\n return {**defaults, **dict(zip(args_names, args)), **kwargs}\n\n\nclass multi_cached:\n \"\"\"\n Only supports functions that return dict-like structures. This decorator caches each key/value\n of the dict-like object returned by the function.\n\n If key_builder is passed, before storing the key, it will be transformed according to the output\n of the function.\n\n If the attribute specified to be the key is an empty list, the cache will be ignored and\n the function will be called as expected.\n\n Each call will use the same connection through all the cache calls. If you expect high\n concurrency for the function you are decorating, it will be safer if you set high pool sizes\n (in case of using memcached or redis).\n\n :param keys_from_attr: arg or kwarg name from the function containing an iterable to use\n as keys to index in the cache.\n :param key_builder: Callable that allows to change the format of the keys before storing.\n Receives a dict with all the args of the function.\n :param ttl: int seconds to store the keys. Default is 0 which means no expiration.\n :param cache: cache class to use when calling the ``multi_set``/``multi_get`` operations.\n Default is ``aiocache.SimpleMemoryCache``.\n :param serializer: serializer instance to use when calling the ``dumps``/``loads``.\n Default is JsonSerializer.\n :param plugins: plugins to use when calling the cmd hooks\n Default is pulled from the cache class being used.\n :param alias: str specifying the alias to load the config from. If alias is passed, other config\n parameters are ignored. New cache is created every time.\n \"\"\"\n\n def __init__(\n self, keys_from_attr, key_builder=None, ttl=0, cache=SimpleMemoryCache,\n serializer=JsonSerializer, plugins=None, alias=None, **kwargs):\n self.keys_from_attr = keys_from_attr\n self.key_builder = key_builder\n self.ttl = ttl\n self.alias = alias\n self.cache = None\n self._conn = None\n\n self._cache = cache\n self._serializer = serializer\n self._plugins = plugins\n self._kwargs = kwargs\n self._key_builder = key_builder or (lambda x, args_dict: x)\n\n def __call__(self, f):\n if self.alias:\n self.cache = caches.create(self.alias)\n else:\n self.cache = _get_cache(\n cache=self._cache, serializer=self._serializer,\n plugins=self._plugins, **self._kwargs)\n\n @functools.wraps(f)\n async def wrapper(*args, **kwargs):\n return await self.decorator(f, *args, **kwargs)\n return wrapper\n\n async def decorator(self, f, *args, **kwargs):\n self._conn = self.cache.get_connection()\n async with self._conn:\n missing_keys = []\n partial = {}\n keys = self.get_cache_keys(f, args, kwargs)\n\n values = await self.get_from_cache(*keys)\n for key, value in zip(keys, values):\n if value is None:\n missing_keys.append(key)\n else:\n partial[key] = value\n kwargs[self.keys_from_attr] = missing_keys\n if values and None not in values:\n return partial\n\n result = await f(*args, **kwargs)\n result.update(partial)\n\n await self.set_in_cache(result)\n\n return result\n\n def get_cache_keys(self, f, args, kwargs):\n args_dict = _get_args_dict(f, args, kwargs)\n keys = args_dict[self.keys_from_attr]\n return [self._key_builder(key, args_dict) for key in keys]\n\n async def get_from_cache(self, *keys):\n if not keys:\n return []\n try:\n values = await self._conn.multi_get(keys)\n if None not in values:\n asyncio.ensure_future(self.cache.close())\n return values\n except Exception:\n logger.exception(\"Couldn't retrieve %s, unexpected error\", keys)\n return [None] * len(keys)\n\n async def set_in_cache(self, result):\n try:\n await self._conn.multi_set([(k, v) for k, v in result.items()], ttl=self.ttl)\n except Exception:\n logger.exception(\"Couldn't set %s, unexpected error\", result)\n","sub_path":"aiocache/decorators.py","file_name":"decorators.py","file_ext":"py","file_size_in_byte":11937,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"629806240","text":"#!/usr/bin/env python\n\n# Copyright (C) 2006-2011 Open Data (\"Open Data\" refers to\n# one or more of the following companies: Open Data Partners LLC,\n# Open Data Research LLC, or Open Data Capital LLC.)\n#\n# This file is part of Augustus.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\"ChangeDetectionModel\n\n\"\"\"\n\nimport itertools as it\nfrom base import corelib, Test, EquivUnary, EquivBinary, as_num_array\nlog = corelib.log\n\n########################################################################\n\nclass ChangeDetect(EquivBinary):\n '''Change Detection Model\n\n '''\n name = 'change_detect'\n ranking = ('fast',)\n\n @staticmethod\n def fast(arg1,arg2,reset_value=0.0,out=None):\n arg1 = as_num_array(arg1)\n arg2 = as_num_array(arg2)\n if not out:\n out = arg1.new()\n cusum_func = CusumReset().iterfunc\n log_odds = log(arg2/arg1)\n cusum_func(log_odds,reset_value=reset_value,out=out)\n return out\n \n\n########################################################################\n\nclass CusumReset(EquivUnary):\n '''CUSUM with reset algorithm\n\n >>> func = CusumReset().iterfunc\n >>> assert func([1,-3,6,7,-7,-9]).tolist() == [1,0,6,13,6,0]\n\n '''\n name = 'cusum_reset'\n ranking = ('iterfunc',)\n #ranking = ('iterfunc','iterloop')\n\n tests = (\n Test([1,-3,6,7,-7,-9]) == [1,0,6,13,6,0],\n )\n\n @staticmethod\n def iterfunc(arg,reset_value=0.0,out=None):\n def gen_cusum(data,reset_value=0.0):\n # no obvious way to vectorize this\n out = 0.0\n for value in data:\n out = max(reset_value,out+value)\n yield out\n\n arg = as_num_array(arg)\n if out is None:\n out = arg.new()\n out[:] = list(gen_cusum(arg,reset_value))\n return out\n\n\n @staticmethod\n def iterloop(arg,reset_value=0.0,out=None):\n arg = as_num_array(arg)\n if not out:\n out = arg.new()\n last = 0.0\n for i,value in it.izip(it.count(),arg):\n out[i] = max(reset_value,last+value)\n return out\n \n\n########################################################################\n\nif __name__ == \"__main__\":\n from base import tester\n tester.testmod()\n\n########################################################################\n","sub_path":"tags/augustus-0.5.2.0/augustus-scoringengine/augustus/kernel/unitable/veclib/pmml_models.py","file_name":"pmml_models.py","file_ext":"py","file_size_in_byte":2671,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"95502627","text":"__author__ = 'vlad'\nimport numpy\nimport numpy.linalg\nimport Substance\nimport itertools\nimport Substance_db\nimport math\n\n\ndef check_data_availability(substances, temperature):\n ok = True\n for substance in substances:\n if not substance.has_data(temperature):\n ok = False\n return ok\n\n\ndef generate_reactions(substances):\n \"\"\"\n Computes possible reactions for given list of substances.\n @param substance_list:\n \"\"\"\n elements = Substance_db.extract_elements(substances)\n\n M = stochiometry_matrix(elements, substances)\n A = null_space(M)\n\n return A\n\n\ndef clear_to_eps(vector):\n eps = 1e-6\n return [x if abs(x) > eps else 0 for x in vector]\n\n\ndef normalize(vector):\n vector_absolute = numpy.array([abs(x) for x in vector])\n min_abs = numpy.max(vector_absolute)\n for x in vector_absolute:\n if 0 < abs(x) < min_abs:\n min_abs = abs(x)\n return vector / min_abs\n\n\ndef are_parallel(vector1, vector2):\n eps = 1e-5\n vector1 = numpy.array(vector1)\n vector2 = numpy.array(vector2)\n length12 = math.sqrt(sum(vector1 * vector1))\n length22 = math.sqrt(sum(vector2 * vector2))\n if abs(1 - abs(sum(vector1 * vector2) / (length12 * length22))) < eps:\n return True\n else:\n return False\n\n\ndef choose_nonparallel(vector_list):\n \"\"\"\n\n @param vector_list:\n @return:\n \"\"\"\n nonparallels = []\n for tested in vector_list:\n is_unique = True\n for chosen in nonparallels:\n if are_parallel(tested, chosen):\n is_unique = False\n if is_unique:\n nonparallels.append(tested)\n return nonparallels\n\n\ndef all_possible_reactions(substances):\n \"\"\"\n\n @rtype : object\n \"\"\"\n all_reactions = []\n number_of_substances = len(substances)\n index = range(number_of_substances)\n\n combinations = []\n for r in range(2, number_of_substances + 1):\n combinations_r = itertools.combinations(index, r)\n for c in combinations_r:\n combinations.append(c)\n\n for combination in combinations:\n combination_substances = []\n for i in combination:\n combination_substances.append(substances[i])\n\n reactions = generate_reactions(combination_substances)\n reactions_obtained = reactions.shape[0]\n for i in range(reactions_obtained):\n new_reaction = numpy.zeros(number_of_substances)\n for j in range(len(combination)):\n new_reaction[combination[j]] = reactions[i, j]\n all_reactions.append(normalize(clear_to_eps(new_reaction)))\n\n return choose_nonparallel(all_reactions)\n\n\ndef align_to_square(matrix):\n \"\"\"\n Приводит прямоугольную матрицу к квадрадной форме, дополняя нулевыми строками или столбцами\n @param matrix: Rectangular 2d array with dimensions m x n\n @return: Square array with dimensions k x k where k = max(m,n)\n \"\"\"\n matrix = numpy.matrix(matrix)\n m = matrix.shape[0]\n n = matrix.shape[1]\n max_dim = max(matrix.shape)\n matrix_aligned = numpy.zeros((max_dim, max_dim))\n matrix_aligned[0:m, 0:n] += matrix\n return matrix_aligned\n\n\ndef null_space(M):\n \"\"\"\n Calculates the null space of matrix M using Singular Value Decomposition\n\n http://stackoverflow.com/questions/5889142/python-numpy-scipy-finding-the-null-space-of-a-matrix\n http://en.wikipedia.org/wiki/Kernel_%28matrix%29#Numerical_computation_of_null_space\n @param M:\n @return:\n \"\"\"\n M_aligned = align_to_square(M)\n u, s, vh = numpy.linalg.svd(M_aligned)\n eps = 1e-6\n null_space_vectors = numpy.compress(s <= eps, vh, axis=0)\n return null_space_vectors\n\n\ndef stochiometry_matrix(elements, substances):\n \"\"\"\n\n @param elements:\n @param substances:\n @return:\n \"\"\"\n m = len(elements)\n n = len(substances)\n M = numpy.zeros((m, n))\n for i in range(m):\n for j in range(n):\n M[i, j] = substances[j].get_element(elements[i])\n return M","sub_path":"ReactionGenerator.py","file_name":"ReactionGenerator.py","file_ext":"py","file_size_in_byte":4066,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"50397465","text":"#!/bin/python3\r\n\r\nimport math\r\nimport os\r\nimport random\r\nimport re\r\nimport sys\r\nfrom collections import Counter\r\n\r\n# Complete the repeatedString function below.\r\n\r\n\r\ndef repeatedString(s, n):\r\n if s == \"a\":\r\n return n\r\n\r\n new = s\r\n\r\n while len(new) < n:\r\n new += s\r\n\r\n c = Counter(new[:n])\r\n k = c['a']\r\n return k\r\n\r\n\r\nif __name__ == '__main__':\r\n # fptr = open(os.environ['OUTPUT_PATH'], 'w')\r\n\r\n s = input()\r\n\r\n n = int(input())\r\n\r\n result = repeatedString(s, n)\r\n\r\n # fptr.write(str(result) + '\\n')\r\n\r\n # fptr.close()\r\n print(result)\r\n","sub_path":"practice/Interview Preparation Kit/Warm-up Challenges/Repeated Strings/Repeated_String.py","file_name":"Repeated_String.py","file_ext":"py","file_size_in_byte":591,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"158130481","text":"# -*- coding: utf-8 -*-\nimport os, sys\nimport time, datetime\n\nreload(sys)\nsys.setdefaultencoding(\"utf-8\")\nsys.path.append(os.path.join(os.path.split(os.path.realpath(__file__))[0], '../util'))\nimport loghelper\nimport db\n\n#logger\nloghelper.init_logger(\"user_abnormal_log\", stream=True)\nlogger = loghelper.get_logger(\"user_abnormal_log\")\n\nblock_ips = [\"139.196.82.224\",\n \"218.4.167.70\",\n \"39.155.188.22\"]\n\ndef aggregate(minutes, quota):\n # urls = [\"/api-company/api/company/list\",\n # \"/api-company/api/company/collection/company/list\",\n # \"/api-company/api/company/basic\",\n # \"/api-company/api/company/track/getByTag\"]\n urls = [\"/api-company/api/company/basic\",\n \"/api-company/api/company/list\",\n \"/xiniudata-api/api2/service/company/basic\",\n \"/api2/service/company/basic\",\n \"/xiniudata-api/api2/service/gongshang/list_by_corporate\",\n \"/api2/service/gongshang/list_by_corporate\",\n \"/xiniudata-api/api2/service/company/list\",\n \"/api2/service/company/list\"]\n\n mongo = db.connect_mongo()\n items = list(mongo.log.user_log.aggregate([\n {\n \"$match\": {\n \"code\": 0,\n \"time\": {\"$gte\": datetime.datetime.utcnow() - datetime.timedelta(minutes=minutes)},\n \"requestURL\": {\"$in\": urls}\n }\n },\n {\n \"$group\": {\n \"_id\": \"$userId\",\n \"cnt\": {\"$sum\": 1}\n }\n },\n {\n \"$match\": {\n \"cnt\": {\"$gte\": quota}\n }\n },\n {\n \"$sort\": {\n \"cnt\": -1\n }\n }\n ]))\n mongo.close()\n return items\n\n\ndef aggregate_all(minutes, quota):\n mongo = db.connect_mongo()\n items = list(mongo.log.user_log.aggregate([\n {\n \"$match\": {\n \"code\": 0,\n \"time\": {\"$gte\": datetime.datetime.utcnow() - datetime.timedelta(minutes=minutes)}\n }\n },\n {\n \"$group\": {\n \"_id\": \"$userId\",\n \"cnt\": {\"$sum\": 1}\n }\n },\n {\n \"$match\": {\n \"cnt\": {\"$gte\": quota}\n }\n },\n {\n \"$sort\": {\n \"cnt\": -1\n }\n }\n ]))\n mongo.close()\n return items\n\n\ndef run():\n # 一分钟\n logger.info(\"*** 1m ***\")\n items = aggregate(1, 15)\n mongo = db.connect_mongo()\n for item in items:\n logger.info(item)\n if should_block(item[\"_id\"]):\n # if item[\"cnt\"] >= 20:\n # block_user(item[\"_id\"])\n log = mongo.log.user_abnormal_log.find_one({\"userId\":item[\"_id\"], \"processed\":\"N\"})\n if log is None:\n mongo.log.user_abnormal_log.insert({\n \"userId\": item[\"_id\"],\n \"type\": \"1m\",\n \"visit_times\": item[\"cnt\"],\n \"createTime\": datetime.datetime.utcnow(),\n \"modifyTime\": datetime.datetime.utcnow(),\n \"processed\": \"N\"\n })\n mongo.close()\n\n # 一小时\n logger.info(\"*** 60m ***\")\n items = aggregate(60, 100)\n mongo = db.connect_mongo()\n for item in items:\n logger.info(item)\n if should_block(item[\"_id\"]):\n if item[\"cnt\"] >= 150:\n block_user(item[\"_id\"])\n log = mongo.log.user_abnormal_log.find_one({\"userId\": item[\"_id\"], \"processed\": \"N\"})\n if log is None:\n log = mongo.log.user_abnormal_log.find_one({\"userId\": item[\"_id\"], \"processed\": \"Y\"}, sort=[(\"_id\", -1)])\n if log is None or log[\"modifyTime\"] < datetime.datetime.utcnow() - datetime.timedelta(minutes=10):\n mongo.log.user_abnormal_log.insert({\n \"userId\": item[\"_id\"],\n \"type\": \"60m\",\n \"visit_times\": item[\"cnt\"],\n \"createTime\": datetime.datetime.utcnow(),\n \"modifyTime\": datetime.datetime.utcnow(),\n \"processed\": \"N\"\n })\n mongo.close()\n\n\n # 一天\n logger.info(\"*** 1day ***\")\n items = aggregate(60*24, 300)\n mongo = db.connect_mongo()\n for item in items:\n logger.info(item)\n if should_block(item[\"_id\"]):\n if item[\"cnt\"] >= 400:\n block_user(item[\"_id\"])\n log = mongo.log.user_abnormal_log.find_one({\"userId\": item[\"_id\"], \"processed\": \"N\"})\n if log is None:\n log = mongo.log.user_abnormal_log.find_one({\"userId\": item[\"_id\"], \"processed\": \"Y\"}, sort=[(\"_id\", -1)])\n if log is None or log[\"modifyTime\"] < datetime.datetime.utcnow() - datetime.timedelta(minutes=10):\n mongo.log.user_abnormal_log.insert({\n \"userId\": item[\"_id\"],\n \"type\": \"1day\",\n \"visit_times\": item[\"cnt\"],\n \"createTime\": datetime.datetime.utcnow(),\n \"modifyTime\": datetime.datetime.utcnow(),\n \"processed\": \"N\"\n })\n mongo.close()\n\n\ndef should_block(user_id):\n conn = db.connect_torndb()\n rel = conn.get(\"select * from user_organization_rel where userId=%s and (active is null or active='Y')\", user_id)\n organization_id = rel[\"organizationId\"]\n if organization_id in [7, 51]:\n conn.close()\n return False\n org = conn.get(\"select * from organization where id=%s\", organization_id)\n if org[\"type\"] == 17020:\n conn.close()\n return False\n return True\n\n\ndef block_user(user_id):\n #return\n if user_id is None:\n return\n\n conn = db.connect_torndb()\n rel = conn.get(\"select * from user_organization_rel where userId=%s and (active is null or active='Y')\", user_id)\n organization_id = rel[\"organizationId\"]\n if organization_id in [7,51]:\n conn.close()\n return\n org = conn.get(\"select * from organization where id=%s\", organization_id)\n if org[\"type\"] == 17020:\n conn.close()\n return\n\n user = conn.get(\"select * from user where id=%s\", user_id)\n if user[\"active\"] != 'D' and user[\"verifiedInvestor\"] != 'Y':\n logger.info(\"Block: %s, %s, %s, %s\", user_id, user[\"username\"], user[\"phone\"], user[\"loginIP\"])\n conn.update(\"update user set active='D', modifyTime=now() where id=%s\", user_id)\n logger.info(\"\")\n\n conn.close()\n\n\ndef block_by_ips():\n conn = db.connect_torndb()\n users = conn.query(\"select * from user where active is null or active !='D' order by id desc\")\n for user in users:\n ip = user[\"loginIP\"]\n if ip in block_ips:\n logger.info(\"Block ip!\")\n logger.info(user)\n conn.update(\"update user set active='D', modifyTime=now() where id=%s\", user[\"id\"])\n\n conn.close()\n\n\ndef calc_ips_cnt(logs):\n ips = {}\n for log in logs:\n ip = log[\"ip\"]\n if ips.has_key(ip):\n ips[ip] += 1\n else:\n ips[ip] = 1\n return len(ips.keys())\n\n\ndef block_by_ip_statistic():\n items = aggregate_all(60, 10)\n mongo = db.connect_mongo()\n for item in items:\n if item[\"_id\"] is None:\n continue\n logs = list(mongo.log.user_log.find({\"userId\":item[\"_id\"],\n \"time\": {\"$gte\": datetime.datetime.utcnow() - datetime.timedelta(minutes=60)}}))\n logs_cnt = len(logs)\n ips_cnt = calc_ips_cnt(logs)\n if ips_cnt>5:\n logger.info(\"userId: %s, logs count: %s, ip count: %s\", item[\"_id\"], logs_cnt, ips_cnt)\n block_user(item[\"_id\"])\n mongo.close()\n\n\nif __name__ == '__main__':\n while True:\n logger.info(\"Begin...\")\n run()\n block_by_ips()\n block_by_ip_statistic()\n logger.info(\"End.\")\n time.sleep(60)\n","sub_path":"data/monitor/user_abnormal_log.py","file_name":"user_abnormal_log.py","file_ext":"py","file_size_in_byte":7987,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"453934881","text":"from time import time\r\ndef mergeSort(arr):\r\n length = len(arr)\r\n if length<2:\r\n return arr\r\n mid = length//2\r\n left = arr[:mid]\r\n right = arr[mid:]\r\n left = mergeSort(left)\r\n right = mergeSort(right)\r\n arr = merge(left,right,arr)\r\n return arr\r\n\r\ndef merge(left , right , arr):\r\n arr = []\r\n i , j = 0 , 0\r\n nL = len(left)\r\n nR = len(right)\r\n while i maxVal: maxVal = data[j][i]\n\t\tfor j in range(len(data)):\n\t\t\tif maxVal != 0: dataTmp[j][i] = data[j][i]/maxVal\n\treturn dataTmp\n\nif __name__ == '__main__':\n\tdata = []\n\tlabel = []\n\tnum = 0\n\t#print('name of the dataset: ')\n\t#dataSet = input()\n\tdataList = ['iris','soybean','fert','ionosphere','movement','wdbc','bank','bcw','semeion','waveform','pendigits']\n\tfor dataSet in dataList:\n\t\tdataTmp, label = loadData(dataSet)\n\t\tprint(dataSet)\n\t\ttmp = set(label)\n\t\tnum = len(tmp)\n\t\tdata = scalarTmp(dataTmp)\n\t\t#print('Enter dc: ')\n\t\t#dc = float(input())\n\t\t#print('enter lasso: ')\n\t\t#lasso = float(input())\n\t\tdc = 0.1\n\t\tlasso = 0.1\n\t\tinst = dpOrig()\n\t\tstart = timeit.default_timer()\n\t\tdlabel, valid, dcenters = inst.eval(dc, num, 'nl', data)\n\t\tstop = timeit.default_timer()\n\t\tprint('dpc takes' + str(stop-start))\n\n\t\tprint('running density peak merge clustering......')\n\t\tinst = dphm()\n\t\tstart = timeit.default_timer()\n\t\tcnt = inst.eval(dc, lasso, 'nl', data)\n\t\tstop = timeit.default_timer()\n\t\tprint('dpmc takes' + str(stop-start))\n\n\t\tprint('running density peak hausdorff clustering......')\n\t\tinst = huasdorffHier()\n\t\tstart = timeit.default_timer()\n\t\tarsTmp, amiTmp, centers, clusters = inst.eval(dc, 'nl', data, label, 1000000)\n\t\tstop = timeit.default_timer()\n\t\tprint('dphc takes' + str(stop-start))\n\n\t\tprint('running dbscan clustering......')\n\t\tinst = ddbscan()\n\t\tstart = timeit.default_timer()\n\t\tinst.eval(0.1, 2, 0, data, True)\n\t\t#eps, minSp, lasso, dataVecs, ifNormal\n\t\tstop = timeit.default_timer()\n\t\tprint('dbscan takes' + str(stop-start))\n\n\n\tprint(\"End of Test!\")\n\n","sub_path":"testtime.py","file_name":"testtime.py","file_ext":"py","file_size_in_byte":2047,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"511756635","text":"import sys\n\ncases = sys.stdin.readlines()\n\nfor t in range(1, len(cases)):\n A, B = cases[t].split()\n recycled = 0\n length = len(A)\n A = int(A)\n B = int(B)\n # range [A, B) is nor a mistake since n < m\n for n in range(A, B):\n used = {}\n for d in range(1, length):\n mul = 10**d\n shift = n % mul\n new = n // mul + shift * 10**(length - d)\n if A <= new and n < new and new <= B and not new in used:\n used[new] = True\n recycled += 1\n print('Case #', t, ': ', recycled, sep='')\n","sub_path":"solutions_1483488_0/Python/dbaltrus/recycled-numbers.py","file_name":"recycled-numbers.py","file_ext":"py","file_size_in_byte":582,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"586875384","text":"from setuptools import setup\n\npackage_name = 'crabe_localization'\n\nsetup(\n name=package_name,\n version='0.0.0',\n packages=[package_name],\n data_files=[\n ('share/ament_index/resource_index/packages',\n ['resource/' + package_name]),\n ('share/' + package_name, ['package.xml']),\n ('share/' + package_name, ['launch/calibration.launch.py']),\n ('share/' + package_name, ['launch/localization.launch.py']),\n ],\n install_requires=['setuptools'],\n zip_safe=True,\n maintainer='user',\n maintainer_email='corentin.lemoine@ensta-bretagne.org',\n description='TODO: Package description',\n license='TODO: License declaration',\n tests_require=['pytest'],\n entry_points={\n 'console_scripts': [\n \"localizer = crabe_localization.localization:main\",\n \"calibration = crabe_localization.calibration:main\",\n ],\n },\n)\n","sub_path":"crabe_localization/setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":911,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"473594505","text":"import requests\nimport time\nimport pandas as pd\nfrom bs4 import BeautifulSoup\ntitles = []\ncategories = []\ntags = []\nreplies = []\nposts = []\ncomments = []\n# You can add categories manually as we are already sorting by categories\ncats = 'Get Help,Git'\n# Find the number of pages in categories to determine the range\nfor i in range(0, 15):\n # Add the URL to the category page you have to scrape\n URL = 'https://discuss.codecademy.com/c/get-help/git/1813'+'?page='+str(i)\n page = requests.get(URL)\n soup = BeautifulSoup(page.content, 'html.parser')\n results = soup.find_all(class_='topic-list-item')\n for result in results:\n topic = result.find('a', class_='title')\n url1 = topic['href']\n page1 = requests.get(url1)\n soup1 = BeautifulSoup(page1.content, 'html.parser')\n result1 = soup1.find_all(class_='post')\n comment = ''\n for i in result1[1:]:\n comment += i.text\n tagg = result.find_all('a', class_='discourse-tag')\n tagss = ''\n for t in tagg:\n tagss += t.text+','\n tagss = tagss.rstrip(',')\n reps = result.find('td', class_='replies')\n titles.append(topic.text)\n categories.append(cats)\n tags.append(tagss)\n replies.append(reps.span.text)\n posts.append(result1[0].text)\n comments.append(comment)\n # To prevent DDoS\n time.sleep(3)\n\ngetcsv = pd.DataFrame({'Title': titles,\n 'Categories': categories,\n 'Tags': tags,\n 'Replies': replies,\n 'Post': posts,\n 'Comment': comments,\n })\n\nprint(getcsv.info())\n\ngetcsv.to_csv('output.csv')\n","sub_path":"Web scraping_codecademy.py","file_name":"Web scraping_codecademy.py","file_ext":"py","file_size_in_byte":1731,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"633697146","text":"import unittest\nimport unittest.mock as mock\nimport tempfile\nimport shutil\nimport os\nimport yaml\nfrom lmctl.ctl.config import Ctl, ConfigRewriter, Config, ConfigParser, ConfigParserError, ConfigError, CtlConfigFinder\nfrom lmctl.environment.group import EnvironmentGroup, EnvironmentGroup\nfrom lmctl.environment.lmenv import LmEnvironment\nfrom lmctl.environment.armenv import ArmEnvironment\n\n\nOLD_CONFIG = \"\"\"\\\ntest:\n alm:\n ip_address: '127.0.0.1'\n secure_port: True\n auth_address: 127.0.0.2\n\"\"\"\nNEW_CONFIG = \"\"\"\\\n## Lmctl has updated this file with the latest schema changes. A backup of your existing config file has been placed in the same directory with a .bak extension\nenvironments:\n test:\n alm:\n host: 127.0.0.1\n protocol: https\n auth_host: 127.0.0.2\n secure: false\n\"\"\"\nOLD_CONFIG_NON_SECURE_PORT = \"\"\"\\\ntest:\n alm:\n secure_port: false\n\"\"\"\nNEW_CONFIG_NON_SECURE_PORT = \"\"\"\\\n## Lmctl has updated this file with the latest schema changes. A backup of your existing config file has been placed in the same directory with a .bak extension\nenvironments:\n test:\n alm:\n protocol: http\n secure: false\n\"\"\"\nOLD_CONFIG_KEEP_OTHER_PROPS = \"\"\"\\\ntest:\n alm:\n ip_address: '127.0.0.1'\n port: 7654\n username: jack\n secure_port: True\n auth_port: 4643\n auth_address: 127.0.0.2\n password: secret\n\"\"\"\nNEW_CONFIG_KEEP_OTHER_PROPS = \"\"\"\\\n## Lmctl has updated this file with the latest schema changes. A backup of your existing config file has been placed in the same directory with a .bak extension\nenvironments:\n test:\n alm:\n host: 127.0.0.1\n port: 7654\n username: jack\n protocol: https\n auth_port: 4643\n auth_host: 127.0.0.2\n password: secret\n secure: true\n\"\"\"\n\nOLD_ARM_CONFIG = \"\"\"\\\ntest:\n arm:\n first:\n ip_address: '127.0.0.1'\n port: 1111\n secure_port: True\n onboarding_addr: http://127.0.0.1\n second:\n ip_address: '127.0.0.2'\n port: 2222\n secure_port: False\n onboarding_addr: http://127.0.0.2\n\"\"\"\nNEW_ARM_CONFIG = \"\"\"\\\n## Lmctl has updated this file with the latest schema changes. A backup of your existing config file has been placed in the same directory with a .bak extension\nenvironments:\n test:\n arm:\n first:\n host: 127.0.0.1\n port: 1111\n protocol: https\n second:\n host: 127.0.0.2\n port: 2222\n protocol: http\n\"\"\"\nclass TestConfigRewriter(unittest.TestCase):\n\n def setUp(self):\n self.tmp_dir = tempfile.mkdtemp()\n\n def tearDown(self):\n if self.tmp_dir and os.path.exists(self.tmp_dir):\n shutil.rmtree(self.tmp_dir)\n\n def test_rewrite_lm(self):\n file_path = os.path.join(self.tmp_dir, 'rewrite.yml')\n with open(file_path, 'w') as f:\n f.write(OLD_CONFIG)\n old_config_dict = yaml.safe_load(OLD_CONFIG)\n new_config_dict = ConfigRewriter(file_path, old_config_dict).rewrite()\n expected_new_config_dict = {\n 'environments': {\n 'test': {\n 'alm': {\n 'host': '127.0.0.1',\n 'protocol': 'https',\n 'auth_host': '127.0.0.2',\n 'secure': False\n }\n }\n }\n }\n self.assertDictEqual(new_config_dict, expected_new_config_dict)\n backup_path = os.path.join(self.tmp_dir, 'rewrite.yml.bak')\n self.assertTrue(os.path.exists(backup_path))\n with open(backup_path, 'r') as f:\n backup_config = f.read()\n self.assertEqual(backup_config, OLD_CONFIG)\n with open(file_path, 'r') as f:\n new_config = f.read()\n self.assertEqual(new_config, NEW_CONFIG)\n\n def test_rewrite_non_secure_port_lm(self):\n file_path = os.path.join(self.tmp_dir, 'rewrite.yml')\n with open(file_path, 'w') as f:\n f.write(OLD_CONFIG_NON_SECURE_PORT)\n old_config_dict = yaml.safe_load(OLD_CONFIG_NON_SECURE_PORT)\n new_config_dict = ConfigRewriter(file_path, old_config_dict).rewrite()\n expected_new_config_dict = {\n 'environments': {\n 'test': {\n 'alm': {\n 'protocol': 'http',\n 'secure': False\n }\n }\n }\n }\n self.assertDictEqual(new_config_dict, expected_new_config_dict)\n backup_path = os.path.join(self.tmp_dir, 'rewrite.yml.bak')\n self.assertTrue(os.path.exists(backup_path))\n with open(backup_path, 'r') as f:\n backup_config = f.read()\n self.assertEqual(backup_config, OLD_CONFIG_NON_SECURE_PORT)\n with open(file_path, 'r') as f:\n new_config = f.read()\n self.assertEqual(new_config, NEW_CONFIG_NON_SECURE_PORT)\n\n def test_rewrite_lm_keep_other_properties(self):\n file_path = os.path.join(self.tmp_dir, 'rewrite.yml')\n with open(file_path, 'w') as f:\n f.write(OLD_CONFIG_KEEP_OTHER_PROPS)\n old_config_dict = yaml.safe_load(OLD_CONFIG_KEEP_OTHER_PROPS)\n new_config_dict = ConfigRewriter(file_path, old_config_dict).rewrite()\n expected_new_config_dict = {\n 'environments': {\n 'test': {\n 'alm': {\n 'host': '127.0.0.1',\n 'protocol': 'https',\n 'auth_host': '127.0.0.2',\n 'port': 7654,\n 'username': 'jack',\n 'auth_port': 4643,\n 'password': 'secret',\n 'secure': True\n }\n }\n }\n }\n self.assertDictEqual(new_config_dict, expected_new_config_dict)\n backup_path = os.path.join(self.tmp_dir, 'rewrite.yml.bak')\n self.assertTrue(os.path.exists(backup_path))\n with open(backup_path, 'r') as f:\n backup_config = f.read()\n self.assertEqual(backup_config, OLD_CONFIG_KEEP_OTHER_PROPS)\n with open(file_path, 'r') as f:\n new_config = f.read()\n self.assertEqual(new_config, NEW_CONFIG_KEEP_OTHER_PROPS)\n\n def test_rewrite_arm(self):\n file_path = os.path.join(self.tmp_dir, 'rewrite.yml')\n with open(file_path, 'w') as f:\n f.write(OLD_ARM_CONFIG)\n old_config_dict = yaml.safe_load(OLD_ARM_CONFIG)\n new_config_dict = ConfigRewriter(file_path, old_config_dict).rewrite()\n expected_new_config_dict = {\n 'environments': {\n 'test': {\n 'arm': {\n 'first': {\n 'host': '127.0.0.1',\n 'protocol': 'https',\n 'port': 1111\n },\n 'second': {\n 'host': '127.0.0.2',\n 'protocol': 'http',\n 'port': 2222\n }\n }\n }\n }\n }\n self.assertDictEqual(new_config_dict, expected_new_config_dict)\n backup_path = os.path.join(self.tmp_dir, 'rewrite.yml.bak')\n self.assertTrue(os.path.exists(backup_path))\n with open(backup_path, 'r') as f:\n backup_config = f.read()\n self.assertEqual(backup_config, OLD_ARM_CONFIG)\n with open(file_path, 'r') as f:\n new_config = f.read()\n self.assertEqual(new_config, NEW_ARM_CONFIG)\n\n\nPARSER_TEST_CONFIG = \"\"\"\\\nenvironments:\n test:\n alm:\n host: 127.0.0.1\n port: 1111\n protocol: https\n auth_host: auth\n auth_port: 4643\n auth_protocol: http\n username: jack\n password: secret\n arm:\n default:\n host: default\n test2:\n arm:\n first:\n host: first\n second: \n host: second\n\"\"\"\n\nOLD_PARSER_TEST_CONFIG = \"\"\"\\\ntestlm:\n alm: \n ip_address: 127.0.0.1\n secure_port: True\n username: jack\n auth_address: 127.0.0.2\ntestarm:\n arm:\n default:\n ip_address: 127.0.0.3\n secure_port: False\n\"\"\"\n\nclass TestConfigParser(unittest.TestCase):\n\n def setUp(self):\n self.tmp_dir = tempfile.mkdtemp()\n\n def tearDown(self):\n if self.tmp_dir and os.path.exists(self.tmp_dir):\n shutil.rmtree(self.tmp_dir)\n\n def __write_file(self, file_path, content):\n with open(file_path, 'w') as f:\n f.write(content)\n\n def test_from_file(self):\n config_file_path = os.path.join(self.tmp_dir, 'config.yaml')\n self.__write_file(config_file_path, PARSER_TEST_CONFIG)\n config = ConfigParser().from_file(config_file_path)\n self.assertIsNotNone(config)\n self.assertIsInstance(config, Config)\n self.assertEqual(len(config.environments), 2)\n self.assertIn('test', config.environments)\n test_env = config.environments['test']\n self.assertIsInstance(test_env, EnvironmentGroup)\n self.assertIsInstance(test_env.lm, LmEnvironment)\n self.assertEqual(test_env.lm.host, '127.0.0.1')\n self.assertEqual(test_env.lm.port, 1111)\n self.assertEqual(test_env.lm.protocol, 'https')\n self.assertEqual(test_env.lm.auth_host, 'auth')\n self.assertEqual(test_env.lm.auth_port, 4643)\n self.assertEqual(test_env.lm.username, 'jack')\n self.assertEqual(test_env.lm.password, 'secret')\n self.assertEqual(test_env.lm.auth_protocol, 'http')\n arms_config = test_env.arms\n self.assertEqual(len(arms_config), 1)\n default_arm_config = arms_config['default']\n self.assertIsInstance(default_arm_config, ArmEnvironment)\n self.assertEqual(default_arm_config.host, 'default')\n self.assertIn('test2', config.environments)\n test2_env = config.environments['test2']\n arms_config = test2_env.arms\n self.assertEqual(len(arms_config), 2)\n self.assertIn('first', arms_config)\n self.assertIn('second', arms_config)\n \n def test_from_file_rewrites_old_config(self):\n config_file_path = os.path.join(self.tmp_dir, 'config.yaml')\n self.__write_file(config_file_path, OLD_PARSER_TEST_CONFIG)\n config = ConfigParser().from_file(config_file_path)\n self.assertEqual(len(config.environments), 2)\n testlm_env = config.environments['testlm']\n self.assertEqual(testlm_env.lm.host, '127.0.0.1')\n self.assertEqual(testlm_env.lm.protocol, 'https')\n self.assertEqual(testlm_env.lm.auth_host, '127.0.0.2')\n self.assertEqual(testlm_env.lm.secure, True)\n self.assertEqual(testlm_env.lm.username, 'jack')\n testarm_env = config.environments['testarm']\n self.assertEqual(testarm_env.arms['default'].host, '127.0.0.3')\n self.assertEqual(testarm_env.arms['default'].protocol, 'http')\n\n @mock.patch('lmctl.ctl.config.ConfigRewriter.rewrite')\n def test_rewrite_fails(self, mock_rewrite):\n config_file_path = os.path.join(self.tmp_dir, 'config.yaml')\n self.__write_file(config_file_path, OLD_PARSER_TEST_CONFIG)\n mock_rewrite.side_effect = ValueError('Mocked error')\n with self.assertRaises(ConfigParserError) as context:\n ConfigParser().from_file(config_file_path)\n self.assertEqual(str(context.exception), 'The configuration file provided ({0}) appears to be a 2.0.X file. \\\n Lmctl attempted to rewrite the file with updated syntax for 2.1.X but failed with the following error: Mocked error'.format(config_file_path))\n\nclass TestCtlConfigFinder(unittest.TestCase):\n\n def setUp(self):\n self.tmp_dir = tempfile.mkdtemp()\n\n def tearDown(self):\n if self.tmp_dir and os.path.exists(self.tmp_dir):\n shutil.rmtree(self.tmp_dir)\n\n def __write_file(self, file_path, content):\n with open(file_path, 'w') as f:\n f.write(content)\n\n def test_find_by_path(self):\n config_file_path = os.path.join(self.tmp_dir, 'config.yaml')\n self.__write_file(config_file_path, 'test')\n finder = CtlConfigFinder(config_file_path)\n self.assertEqual(config_file_path, finder.find())\n \n def test_fail_path_not_found(self):\n config_file_path = os.path.join(self.tmp_dir, 'config.yaml')\n with self.assertRaises(ConfigError) as context:\n CtlConfigFinder(config_file_path).find()\n self.assertEqual(str(context.exception), 'Path provided to load control config does not exist: {0}'.format(config_file_path))\n \n def test_find_by_env_var(self):\n config_file_path = os.path.join(self.tmp_dir, 'config.yaml')\n self.__write_file(config_file_path, 'test')\n os.environ['LMCONFIG'] = config_file_path\n try:\n finder = CtlConfigFinder(None, 'LMCONFIG')\n self.assertEqual(config_file_path, finder.find())\n finally:\n del os.environ['LMCONFIG']\n \n def test_fail_env_var_path_not_found(self):\n config_file_path = os.path.join(self.tmp_dir, 'config.yaml')\n os.environ['LMCONFIG'] = config_file_path\n try:\n with self.assertRaises(ConfigError) as context:\n CtlConfigFinder(None, 'LMCONFIG').find()\n self.assertEqual(str(context.exception), 'Config environment variable LMCONFIG path does not exist: {0}'.format(config_file_path))\n finally:\n del os.environ['LMCONFIG']\n\n def test_fail_env_var_not_set(self):\n config_file_path = os.path.join(self.tmp_dir, 'config.yaml')\n self.__write_file(config_file_path, 'test')\n if os.environ.get('LMCONFIG') != None:\n del os.environ['LMCONFIG']\n with self.assertRaises(ConfigError) as context:\n CtlConfigFinder(None, 'LMCONFIG').find()\n self.assertEqual(str(context.exception), 'Config environment variable LMCONFIG is not set'.format(config_file_path))\n\n def test_find_by_path_not_env_var(self):\n config_file_path = os.path.join(self.tmp_dir, 'config.yaml')\n config_env_file_path = os.path.join(self.tmp_dir, 'env_config.yaml')\n self.__write_file(config_file_path, 'test')\n self.__write_file(config_env_file_path, 'test')\n os.environ['LMCONFIG'] = config_env_file_path\n try:\n finder = CtlConfigFinder(config_file_path, 'LMCONFIG')\n self.assertEqual(config_file_path, finder.find())\n finally:\n del os.environ['LMCONFIG']\n \n\nclass TestCtl(unittest.TestCase):\n\n def test_init(self):\n environments = {\n 'groupA': EnvironmentGroup('groupA', '', LmEnvironment('alm', 'host'), {'defaultrm': ArmEnvironment('defaultrm', 'host')}),\n 'groupB': EnvironmentGroup('groupB', '', LmEnvironment('alm', 'hostB'), {'defaultrm': ArmEnvironment('defaultrm', 'hostB')})\n }\n config = Config(environments)\n ctl = Ctl(config)\n self.assertEqual(len(ctl.environments), 2)\n groupA_env = ctl.environment_group_named('groupA')\n self.assertIsNotNone(groupA_env)\n self.assertIsInstance(groupA_env, EnvironmentGroup)\n groupB_env = ctl.environment_group_named('groupB')\n self.assertIsNotNone(groupB_env)\n self.assertIsInstance(groupB_env, EnvironmentGroup)\n\n def test_environment_group_named_fails_when_not_found(self):\n config = Config({})\n ctl = Ctl(config)\n with self.assertRaises(ConfigError) as context:\n ctl.environment_group_named('groupA')\n self.assertEqual(str(context.exception), 'No environment group with name: groupA')","sub_path":"tests/unit/ctl/test_config.py","file_name":"test_config.py","file_ext":"py","file_size_in_byte":15661,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"638302107","text":"#!/usr/local/bin/python3\nfrom classes.character import Character\nimport random\n\ncharacternames = [\"Frasier\", \"Niles\", \"Roz\"]\nlines = 10\n\ncharacters = []\nfor c in characternames:\n characters.append(Character(c,\"transcripts/parsed_by_character/\"+c+\".txt\",1))\n\nprevC = c = 0 \nprevLine = line = None\n\nfor i in range(0,lines):\n # Choose a new respondent\n while c == prevC: \n c = random.randint(0,len(characternames)-1)\n\n # Generate line\n while line==None:\n # First sentence\n if prevLine==None:\n line = characters[c].say()\n # Else, potentially say something new\n elif random.random() < 0.3:\n line = characters[c].say()\n # Else, respond to the previous line\n else:\n line = characters[c].respond(prevLine)\n\n # Print line\n lineFormat = \"%8s: %s\" % (characters[c].Name(), line)\n print(lineFormat)\n\n # Keep track of who spoke last\n prevC = c\n prevLine = line\n line = None\n","sub_path":"make_scene.py","file_name":"make_scene.py","file_ext":"py","file_size_in_byte":979,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"603204840","text":"import pygame\r\nimport time\r\npygame.init()\r\n\r\nyellow=[255,255,0]\r\nwhite=[255,255,255]\r\nred=[255,0,0]\r\n\r\ndiswidth=800\r\ndisheight=800\r\ndis=pygame.display.set_mode((diswidth,disheight))\r\n\r\npygame.display.set_caption(\"The Snake game\")\r\n\r\nclock=pygame.time.Clock()\r\nsnakespeed=30\r\nsnakeblock=10\r\n\r\ngame_over = False\r\n\r\nx1=diswidth/2\r\ny1=disheight/2\r\nx1_change=0\r\ny1_change=0\r\n\r\nwhile not game_over:\r\n for event in pygame.event.get():\r\n print(event)\r\n if event.type==pygame.QUIT:\r\n game_over=True\r\n if event.type==pygame.KEYDOWN:\r\n if event.key==pygame.K_LEFT:\r\n x1_change=-10\r\n y1_change=0\r\n elif event.key==pygame.K_RIGHT:\r\n x1_change=10\r\n y1_change=0\r\n elif event.key==pygame.K_UP:\r\n x1_change=0\r\n y1_change=-10\r\n elif event.key==pygame.K_DOWN:\r\n x1_change=0\r\n y1_change=10\r\n\r\n if x1>=diswidth or x1<0 or y1>=disheight or y1<0:\r\n game_over=True\r\n\r\n x1 += x1_change\r\n y1 += y1_change\r\n\r\n dis.fill(yellow)\r\n\r\n pygame.draw.rect(dis,white,[x1,y1,snakeblock,snakeblock])\r\n pygame.display.update()\r\n\r\n clock.tick(snakespeed)\r\n\r\nmsg=\"You Lost\"\r\nfont_style = pygame.font.SysFont(None, 50)\r\nmessage = font_style.render(msg, True, red)\r\ndis.blit(message, [diswidth/2, disheight/2])\r\npygame.display.update()\r\n\r\ntime.sleep(2)\r\npygame.quit()\r\nquit()","sub_path":"snakegame.py","file_name":"snakegame.py","file_ext":"py","file_size_in_byte":1459,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"370430223","text":"# Utilities for authn/z\nimport base64\nimport json\nimport os\nimport re\n\nfrom Crypto.Signature import PKCS1_v1_5\nfrom Crypto.PublicKey import RSA\nfrom Crypto.Hash import SHA256\nfrom flask import g, request, abort\nfrom flask_restful import Resource\nimport jwt\n\nfrom agaveflask.auth import authn_and_authz as agaveflask_az\nfrom agaveflask.logs import get_logger\nlogger = get_logger(__name__)\n\nfrom agaveflask.utils import ok, RequestParser\n\nfrom config import Config\nimport codes\nfrom errors import PermissionsException\nfrom models import Actor, get_permissions\n\nfrom stores import actors_store, permissions_store\n\n\n\njwt.verify_methods['SHA256WITHRSA'] = (\n lambda msg, key, sig: PKCS1_v1_5.new(key).verify(SHA256.new(msg), sig))\njwt.prepare_key_methods['SHA256WITHRSA'] = jwt.prepare_RS_key\n\n\ndef get_pub_key():\n pub_key = Config.get('web', 'apim_public_key')\n return RSA.importKey(base64.b64decode(pub_key))\n\n\nPUB_KEY = get_pub_key()\n\nTOKEN_RE = re.compile('Bearer (.+)')\n\nWORLD_USER = 'world'\n\ndef get_pub_key():\n pub_key = Config.get('web', 'apim_public_key')\n return RSA.importKey(base64.b64decode(pub_key))\n\n\ndef authn_and_authz():\n \"\"\"All-in-one convenience function for implementing the basic abaco authentication\n and authorization on a flask app. Use as follows:\n\n import auth\n\n my_app = Flask(__name__)\n @my_app.before_request\n def authnz_for_my_app():\n auth.authn_and_authz()\n\n \"\"\"\n # we use the agaveflask authn_and_authz function, passing in our authorization callback.\n agaveflask_az(authorization)\n\ndef authorization():\n \"\"\"Entry point for authorization. Use as follows:\n\n import auth\n\n my_app = Flask(__name__)\n @my_app.before_request\n def authz_for_my_app():\n auth.authorization()\n\n \"\"\"\n g.admin = False\n if request.method == 'OPTIONS':\n # allow all users to make OPTIONS requests\n logger.info(\"Allowing request because of OPTIONS method.\")\n return True\n\n # the 'ALL' role is a role set by agaveflask in case the access_control_type is none\n if codes.ALL_ROLE in g.roles:\n g.admin = True\n logger.info(\"Allowing request because of ALL role.\")\n return True\n\n # the admin role when JWT auth is configured:\n if codes.ADMIN_ROLE in g.roles:\n g.admin = True\n logger.info(\"Allowing request because of ADMIN_ROLE.\")\n return True\n\n # all other requests require some kind of abaco role:\n if set(g.roles).isdisjoint(codes.roles):\n logger.info(\"NOT allowing request - user has no abaco role.\")\n raise PermissionsException(\"Not authorized -- missing required role.\")\n else:\n logger.debug(\"User has an abaco role.\")\n logger.debug(\"URL rule: {}\".format(request.url_rule.rule or 'actors/'))\n logger.debug(\"request.path: {}\".format(request.path))\n # there are special rules on the root collection:\n if '/actors' == request.url_rule.rule or '/actors/' == request.url_rule.rule:\n logger.debug(\"Checking permissions on root collection.\")\n # first, only admins can create/update actors to be privileged, so check that:\n if request.method == 'POST':\n check_privileged()\n # if we are here, it is either a GET or a new actor, so the request is allowed:\n logger.debug(\"new actor or GET on root connection. allowing request.\")\n return True\n\n # all other checks are based on actor-id:\n db_id = get_db_id()\n logger.debug(\"db_id: {}\".format(db_id))\n if request.method == 'GET':\n # GET requests require READ access\n has_pem = check_permissions(user=g.user, actor_id=db_id, level=codes.READ)\n elif request.method == 'DELETE':\n has_pem = check_permissions(user=g.user, actor_id=db_id, level=codes.UPDATE)\n else:\n logger.debug(\"URL rule in request: {}\".format(request.url_rule.rule))\n # first, only admins can create/update actors to be privileged, so check that:\n if request.method == 'POST' or request.method == 'PUT':\n check_privileged()\n # only admins have access to the workers endpoint, and if we are here, the user is not an admin:\n if 'workers' in request.url_rule.rule:\n raise PermissionsException(\"Not authorized -- only admins are authorized to update workers.\")\n if request.method == 'POST':\n # POST to the messages endpoint requires EXECUTE\n if 'messages' in request.url_rule.rule:\n has_pem = check_permissions(user=g.user, actor_id=db_id, level=codes.EXECUTE)\n # otherwise, we require UPDATE\n else:\n has_pem = check_permissions(user=g.user, actor_id=db_id, level=codes.UPDATE)\n if not has_pem:\n logger.info(\"NOT allowing request.\")\n raise PermissionsException(\"Not authorized -- you do not have access to this actor.\")\n\ndef check_privileged():\n \"\"\"Check if request is trying to make an actor privileged.\"\"\"\n logger.debug(\"top of check_privileged\")\n # admins have access to all actors:\n if g.admin:\n return True\n data = request.get_json()\n if not data:\n data = request.form\n if data.get('privileged'):\n logger.debug(\"User is trying to set privileged\")\n # if we're here, user isn't an admin so must have privileged role:\n if not codes.PRIVILEGED_ROLE in g.roles:\n logger.info(\"User does not have privileged role.\")\n raise PermissionsException(\"Not authorized -- only admins and privileged users can make privileged actors.\")\n else:\n logger.debug(\"user allowed to set privileged.\")\n return True\n else:\n logger.debug(\"not trying to set privileged.\")\n return True\n\ndef check_permissions(user, actor_id, level):\n \"\"\"Check the permissions store for user and level\"\"\"\n logger.debug(\"Checking user: {} permissions for actor id: {}\".format(user, actor_id))\n # get all permissions for this actor\n permissions = get_permissions(actor_id)\n for pem in permissions:\n # if the actor has been shared with the WORLD_USER anyone can use it\n if user == WORLD_USER:\n logger.info(\"Allowing request - actor has been shared with the WORLD_USER.\")\n return True\n # otherwise, check if the permission belongs to this user and has the necessary level\n if pem['user'] == user:\n if pem['level'] >= level:\n logger.info(\"Allowing request - user has appropriate permission with the actor.\")\n return True\n return False\n\ndef get_db_id():\n \"\"\"Get the db_id from the request path.\"\"\"\n path_split = request.path.split(\"/\")\n if len(path_split) < 3:\n logger.error(\"Unrecognized request -- could not find the actor id. path_split: {}\".format(path_split))\n raise PermissionsException(\"Not authorized.\")\n actor_id = path_split[2]\n logger.debug(\"actor_id: {}\".format(actor_id))\n return Actor.get_dbid(g.tenant, actor_id)\n","sub_path":"actors/auth.py","file_name":"auth.py","file_ext":"py","file_size_in_byte":6993,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"173390437","text":"import os\nimport json\n\ndef get_json_file_path():\n return os.path.abspath(os.path.join(__file__, \"../../config.json\"))\n\ndef load_data(failed=None):\n try:\n json_path = get_json_file_path()\n with open(json_path, \"r\") as json_file:\n data = json.load(json_file)\n return data\n except:\n # When logging is implemented, catch the exception and log it to the file\n if failed is not None:\n print(failed)\n return False\n\ndef get_database_path():\n data = load_data()\n file_name = data[\"database\"][\"database_name\"]\n absolute_path = os.path.abspath(os.path.join(__file__, f\"../../storage/{file_name}\"))\n return absolute_path\n\ndef database_exists():\n return os.path.exists(get_database_path())\n \ndef update_data(data):\n try:\n json_path = get_json_file_path()\n with open(json_path, \"w\") as json_file:\n json.dump(data, json_file)\n except:\n print(\"[!] Can't write to file\")\n","sub_path":"tools/configuration.py","file_name":"configuration.py","file_ext":"py","file_size_in_byte":987,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"544703912","text":"\"\"\"\nGiven an array A of strings made only from lowercase letters, return a list of all characters\nthat show up in all strings within the list (including duplicates).\nFor example, if a character occurs 3 times in all strings but not 4 times,\nyou need to include that character three times in the final answer.\n\nYou may return the answer in any order.\n\"\"\"\nclass Solution(object):\n def commonChars(self, A):\n \"\"\"\n :type A: List[str]\n :rtype: List[str]\n \"\"\"\n import collections\n res = collections.Counter(A[0])\n for a in A:\n res &= collections.Counter(a) # & return min count of key, | return max count\n return list(res.elements())\n\n def commonChars2(self, A):\n cnt = [float('inf')] * 26\n for s in A:\n cnt1 = [0] * 26\n for c in s:\n cnt1[ord(c) - ord('a')] += 1\n for i in range(26):\n cnt[i] = min(cnt[i], cnt1[i])\n\n res = []\n for i in range(26):\n if cnt[i]:\n tmp = chr(i + ord('a'))\n res.extend(tmp* cnt[i])\n return res\n\n\n\n# A = [\"bella\",\"label\",\"roller\"]\nA = [\"cool\",\"lock\",\"cook\"]\nprint(Solution().commonChars2(A))","sub_path":"1002FindCommonCh.py","file_name":"1002FindCommonCh.py","file_ext":"py","file_size_in_byte":1223,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"81224096","text":"#-*- encoding: UTF-8 -*-\n#---------------------------------import------------------------------------\nimport scrapy\nimport re\nfrom tutorial.items import CqgpNoticesDetailsItem\nfrom scrapy import Request\nfrom scrapy.selector import Selector \nimport json,time\nimport os, os.path \n\n#---------------------------------------------------------------------------\n#重庆采购公告\nclass cqgpNoticesSpider(scrapy.Spider):\n\tname = \"cqgpNotices\"\n\tallowed_domains = [\"cqgp.gov.cn\"]\n\t\n\tdef getlist():\n\t\tseq = []\n\t\tfor i in range(7832,12954):\n\t\t\tseq.append(\"https://www.cqgp.gov.cn/gwebsite/api/v1/notices/stable?pi=\"+str(i)+\"&ps=20×tamp=\" + str(int(time.time())) +\",\")\n\t\treturn seq;\n\t\t\n\tstart_urls = getlist()\n\t\n\tdef parse(self,response):\n\t\tprint(response.url)\n\t\treq = []\n\t\tsites = json.loads(response.body_as_unicode()) \n\n\t\tfor site in sites['notices']: \n\t\t\tnext_url = \"https://www.cqgp.gov.cn/gwebsite/api/v1/notices/stable/\"+site[\"id\"]+\"?timestamp=\" + str(int(time.time()))\n\t\t\tr = Request(next_url, self.parse_details)\n\t\t\treq.append(r)\n\t\t\t\n\t\treturn req\n\t\t\n\tdef parse_details(self,response):\n\t\t\"\"\"获取详情页面\"\"\"\n\t\tsites = json.loads(response.body_as_unicode()) \n\t\thtml = sites[\"html\"].replace('//n//r','').replace('//t','')\n\t\t\n\t\tfilepath = sites[\"notice\"][\"title\"] + '.html'\n\t\topath = os.path.abspath(\"./重庆采购公告/\" + filepath) \n\t\tbasedir = os.path.dirname(opath) \n\t\tif not os.path.exists(basedir): \n\t\t\tos.makedirs(basedir) \n\t\t#print(opath)\n\t\twith open(opath, 'w',encoding='utf-8') as f: \n\t\t\tf.write(html)\n\t\t\t\n\t\titem = CqgpNoticesDetailsItem()\n\t\titem[\"title\"] = sites[\"notice\"][\"title\"]\n\t\titem[\"projectPurchaseWay\"] = sites[\"notice\"][\"projectPurchaseWay\"]\n\t\titem[\"issueTime\"] = sites[\"notice\"][\"issueTime\"]\n\t\titem[\"noticeType\"] = sites[\"notice\"][\"noticeType\"]\n\t\tyield item\n\t\t\t\n\t\t\t\n\t\t\n\t\t\n\t\t\n\t\t\n\t\t\n\t\t\n\t\t\n\t\t\n\t\t\n\t\t\n\t\t\n\t\t\n\t\t\n\t\t\n\t\t\n\t\t\n\t\t\n\t\t\n\t\t\n\t\t\n\t\t\n\t\n","sub_path":"爬虫练习/scrapy_jingdong-master/tutorial/spiders/cqgp_notices.py","file_name":"cqgp_notices.py","file_ext":"py","file_size_in_byte":1862,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"258634371","text":"import pymc3 as pm\nimport numpy as np\n\nclass TT_PYMC3:\n\n def __init__(self, ThetaI, meanThetaInit, kappaInitMinusTwo, zz, N):\n self.Nsubj = len(N)\n\n with pm.Model() as model:\n omega = pm.Beta('omega', 1, 1, testval=meanThetaInit)\n kappaMinusTwo = pm.Gamma('kappa', 0.01, 0.01, testval=kappaInitMinusTwo)\n\n kappa = kappaMinusTwo + 2\n\n theta = pm.Beta('theta', omega * (kappa - 2) + 1, (1 - omega) * (kappa - 2) + 1, shape=self.Nsubj,\n testval=np.array(ThetaI))\n\n self.z = pm.Binomial('z', p=theta, n=np.array(N), observed=np.array(zz))\n\n self.samples = pm.sample(draws=133333, step=pm.NUTS(), cores=3, tune=1000, random_seed=-1, progressbar=False)\n","sub_path":"src/TherapeuticTouch/PYMC3.py","file_name":"PYMC3.py","file_ext":"py","file_size_in_byte":757,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"498650208","text":"from typing import List\n\nclass AutocompleteSystem:\n def __init__(self, sentences: List[str], times: List[int]):\n self.tree = {}\n self.current = []\n for sentence, count in zip(sentences, times):\n self.add(sentence, count)\n\n def add(self, sentence: str, count: int):\n node = self.tree\n for c in sentence:\n if not c in node:\n node[c] = {}\n node = node[c]\n if not \"count\" in node: node[\"count\"] = 0\n node[\"count\"] -= count\n\n def search(self, node: map, input_chars: List[str], result: List[str]) -> List[str]:\n if not node: return []\n for chara, next_node in node.items():\n if chara != \"count\":\n input_chars.append(chara)\n self.search(next_node, input_chars, result)\n input_chars.pop()\n else:\n result.append((next_node, \"\".join(input_chars)))\n return result\n\n def input(self, c: str) -> List[str]:\n if c == \"#\":\n self.add(\"\".join(self.current), 1)\n self.current.clear()\n return []\n else:\n self.current.append(c)\n node = self.tree\n for c in self.current:\n if node:\n node = node.get(c)\n res = self.search(node, self.current, [])\n res.sort()\n return list(map(lambda x: x[1], res))[:3]\n\n\n# acs = AutocompleteSystem([\"i love you\",\"island\",\"iroman\",\"i love leetcode\"], [5,3,2,2])\n# print(acs.tree)\n# print(acs.input(\"i\"))\n# print(acs.input(\" \"))\n# print(acs.input(\"a\"))\n# print(acs.input(\"#\"))\n# print(acs.input(\"i\"))\n# print(acs.input(\" \"))","sub_path":"0642.py","file_name":"0642.py","file_ext":"py","file_size_in_byte":1690,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"595800838","text":"import shortuuid\nfrom django.views.decorators.csrf import csrf_exempt\nfrom django.shortcuts import HttpResponseRedirect, render, reverse\nfrom submission.models import Submission\nfrom account.models import User\nfrom contest.models import Contest\nfrom dispatcher.tasks import submit_code_for_contest, submit_code\n\n\n@csrf_exempt\ndef test_view(request):\n if request.method == 'POST':\n username = request.POST['username']\n rstring = shortuuid.ShortUUID().random(6)\n email = '%s@%s.%s' % (rstring, rstring, rstring)\n user, _ = User.objects.get_or_create(username=username, defaults={'username': username,\n 'email': email})\n submission = Submission()\n submission.lang = request.POST['lang']\n submission.code = request.POST['code']\n problem = request.POST['problem']\n submit_code(submission, user, problem)\n return render(request, 'blank.jinja2')\n\n\n@csrf_exempt\ndef test_contest_view(request):\n if request.method == 'POST':\n username = request.POST['username']\n rstring = shortuuid.ShortUUID().random(6)\n email = '%s@%s.%s' % (rstring, rstring, rstring)\n user, _ = User.objects.get_or_create(username=username, defaults={'username': username,\n 'email': email})\n submission = Submission()\n submission.lang = request.POST['lang']\n submission.code = request.POST['code']\n contest = Contest.objects.get(pk=request.POST['contest'])\n problem = request.POST['problem']\n submit_code_for_contest(submission, user, problem, contest)\n return render(request, 'blank.jinja2')\n","sub_path":"tests/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1754,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"458665735","text":"import csv\nimport os\nimport sys\nimport time\nimport pymongo\nimport pickle\nfrom bson.binary import Binary\nimport json\nimport pandas as pd\nimport numpy as np\nfrom matplotlib import cm\n# import matplotlib.pyplot as plt\nfrom sklearn.cluster import DBSCAN\nfrom sklearn.cluster import KMeans\nfrom kmodes.kmodes import KModes\nfrom sklearn.cluster import MeanShift\nfrom sklearn.cluster import AgglomerativeClustering\nfrom sklearn.cluster import Birch\nfrom sklearn.cluster import SpectralClustering\nfrom sklearn.cluster import estimate_bandwidth\n\nfrom sklearn.metrics import silhouette_samples\nfrom sklearn.metrics import adjusted_rand_score\n# from sklearn.metrics import calinski_harabaz_score\n\nfrom sklearn.decomposition import PCA\nfrom sklearn.neighbors import LocalOutlierFactor\n\n# from sklearn.grid_search import GridSearchCV\n\nclass Bunch(dict):\n def __init__(self, **kwargs):\n dict.__init__(self, kwargs)\n\n def __setattr__(self, key, value):\n self[key] = value\n\n def __getattr__(self, key):\n try:\n return self[key]\n except KeyError:\n raise AttributeError(key)\n\n def __getstate__(self):\n return self.__dict__\n\n#链接MongoDB数据库\ndef Connectdatabase():\n conn=pymongo.MongoClient(host=\"localhost\",port=27017)\n db=conn.MongoDB_Data\n return db\n\n#读取文档操作。返回值:sample-数据个数;feature-特征个数;data-数据值;target-最后一列值-该iris数据集中表示花的种类;\n# feature_names-数据特征的名称;\ndef load_data(filename):\n with open(filename) as f:\n data_file=csv.reader(f)\n data=[]\n target=[]\n temp=next(data_file)\n feature_names=np.array(temp)\n for i, d in enumerate(data_file):\n temp = []\n for j in d:\n if j == '':\n j = 0\n temp.append(j)\n data.append(np.asarray(temp[:-1], dtype=np.float))\n target.append(np.asarray(d[-1], dtype=np.float))\n data = np.array(data)\n target = np.array(target)\n n_samples = data.shape[0]\n n_features = data.shape[1]\n return Bunch(sample=n_samples, features=n_features, data=data, target=target,\n feature_names=feature_names)\n\n\n\n#其中一种聚类质量的定量分析方法——轮廓分析法,用于度量簇中样本聚集的密集程度\n#内聚度a:某一样本x与簇内其他点之间的平均距离\n#分离度b:样本与其最近簇中所有点之间的平均距离看作是与下一最近簇的分离度\n#轮廓系数是(b-a)/max{b,a}\n#该函数画出了轮廓系数图返回轮廓系数均值,这里暂时主要是用于评价DBSCAN的聚类质量\ndef silhouette(data,labels):\n cluster_labels=np.unique(labels)\n n_cluster=cluster_labels.shape[0]\n silhouette_vals=silhouette_samples(data,labels,metric='euclidean')\n y_ax_lower,y_ax_upper=0,0\n yticks=[]\n for i,c in enumerate(cluster_labels):\n c_silhouette_vals=silhouette_vals[labels==c]\n c_silhouette_vals.sort()\n y_ax_upper += len(c_silhouette_vals)\n color=cm.jet(i/n_cluster)\n # plt.barh(range(y_ax_lower,y_ax_upper),\n # c_silhouette_vals,\n # height=1.0,\n # edgecolor='none',\n # color=color)\n yticks.append((y_ax_lower+y_ax_upper)/2)\n y_ax_lower+=len(c_silhouette_vals)\n silhouette_avg=np.mean(silhouette_vals)\n # plt.axvline(silhouette_avg,\n # color=\"red\",\n # linestyle=\"--\")\n # plt.yticks(yticks,cluster_labels+1)\n # plt.ylabel('Cluster')\n # plt.xlabel('Silhouette coefficient')\n # plt.show()\n return silhouette_avg\n\n#该函数使用的是Adjusted Rand index 指标评价聚类的好坏\n#主要是根据真实类别与预测类别用一定方法分析得到预测的正确值\n#详情见sklearn.cluster中的最后一节的第一个方法\ndef accuracy(labels,right_labels):\n accuracy=adjusted_rand_score(labels,right_labels)\n return accuracy\n\n#返回descan预测的值,由自己输入半径和簇类最小数目\ndef dbscan_labels(data,eps,min_samples):\n model=DBSCAN(eps=eps,min_samples=min_samples)\n labels=model.fit_predict(data)\n return labels\n\n#该函数是为了计算dbscan算法性能指标最好的半径值,指定的k值是簇类最小个体数目\n#详细原理见http://shiyanjun.cn/archives/1288.html\n#k值使用的是经验值4,目前觉得还没有必要对k值进行最佳值判断\ndef select_best_eps(data,k):\n distance=[]\n k_distance=[]\n row,col=data.shape[0],data.shape[1]\n for i in range(row):\n dis = []\n for j in range(row):\n dist=np.linalg.norm(data[i]-data[j])\n dis.append(dist)\n dis.sort()\n k_distance.append(dis[k])\n distance.append(dis)\n k_distance=np.array(k_distance)\n k_distance.sort()\n n_list=list(range(k_distance.shape[0]))\n delta=[]\n for i in range(k_distance.shape[0]):\n if(i==0):\n temp=0\n else:\n temp=k_distance[i]-k_distance[i-1]\n delta.append(temp)\n delta_distance=dict(zip(n_list,delta))\n delta_distance=sorted(delta_distance.items(),key=lambda d:d[1],reverse=True)\n return k_distance[delta_distance[0][0]]\n\n#dbscan的函数\n#显示两种性能指标,其中adjusted rand index目前是用于所有聚类算法的性能评价,average silhouette目前只是用于dbscan\ndef dbscan(data,right_labels):\n best_eps=select_best_eps(data,4)\n labels=dbscan_labels(data,best_eps,4)\n adjusted_rand_score=accuracy(labels,right_labels)\n return labels,adjusted_rand_score\n\n#KMEANS、KMODES、KPROTOTYPE\n#Kmeans:度量的是数值型数据,使用的是欧氏距离\n#Kmodes:度量的是非数值属性数据,比较的是属性之间相同数目的大小,不同D加1,越大越不相似。更新modes使用最代表的属性\n#Kprototype:使用混合属性,D=P1+a*P2,P1 kmeans,P2 kmodes\n\n#kmeans函数,直接调用sklearn的函数,由于k的值是由专家决定,所以这里不用函数选取最佳的k值\n#如有需要,可以使用肘方法确定簇的最佳数量。\ndef kmeans(data,k,right_labels):\n model=KMeans(n_clusters=k,init='k-means++')\n labels=model.fit_predict(data)\n adjusted_rand_score = accuracy(labels, right_labels)\n return labels,adjusted_rand_score\n\n#kmodes函数,使用的是kmodes库中的函数\n#GitHub链接:https://github.com/nicodv/kmodes\n#参数有n_clusters、max_iter、cat_dissim:function used for categorical variabels default:matching_dissim matching,找的是不同的\n#init:Huang、Cao、random,default:Cao,初始化方法,具体目前不了解\n#n_init,verbose\ndef kmodes(data,k,right_labels):\n model=KModes(n_clusters=k)\n labels=model.fit_predict(data)\n adjusted_rand_score=accuracy(labels,right_labels)\n return labels, adjusted_rand_score\n\n#MeanShift函数,使用的是sklearn库\n#评判标准是簇类点到中心点的向量之和为零\n#bandwidth高斯核函数的带宽\n#seeds初始化质心得到的方式,bin_seeding在没有设置seeds时使用,none表示全部点都为质心\n#min_bin_freq设置最少质心数目\n#cluster_all,True表示所有点都会被聚类,False表示孤立点类标签为-1\n#n_jobs多线程,-1所有cpu,1不使用,-2只有一块不被使用,-3有两块\ndef meanshift(data,k,right_labels):\n bandwidth=estimate_bandwidth(data)\n model=MeanShift(bandwidth=bandwidth,bin_seeding=True,min_bin_freq=k,n_jobs=-1)\n labels=model.fit_predict(data)\n adjusted_rand_score = accuracy(labels, right_labels)\n return labels, adjusted_rand_score\n\n#agglomerativeClustering的三种模式\n#两类之间某两个样本之间的距离\n#ward_linkage ward minimizes the variance of the clusters being merged.离差平方和\n#complete_linkage最大距离\n#average_linkage平均距离\ndef agglomerative(data,k,link,right_labels):\n if link not in ['ward','complete','average']:\n link='ward'\n model=AgglomerativeClustering(n_clusters=k,affinity='euclidean',linkage=link)\n labels = model.fit_predict(data)\n adjusted_rand_score = accuracy(labels, right_labels)\n return labels, adjusted_rand_score\n\n#birch聚类\n# def birch(data,th,br,right_labels):\ndef birch(data,k,right_labels):\n model=Birch(n_clusters=k)\n # model=Birch(threshold=th,branching_factor=br,n_clusters=None)\n labels=model.fit_predict(data)\n adjusted_rand_score = accuracy(labels, right_labels)\n return labels,adjusted_rand_score\n\n#SpectralClustering谱聚类\n#n_clusters:簇的个数;affinity:相似矩阵建立方法,nearest_neighbors,precomputed:自定义,全连接法,自定义核函数,默认rbf高斯核函数;\n#gamma:核函数参数,默认1.0,gamma\n#degree:核函数参数,d\n#coef0:核函数参数,r\ndef spectralclustering(data,k,right_labels):\n best_gamma_score={}\n for index,gamma in enumerate((0.01,0.1,1,10)):\n model=SpectralClustering(n_clusters=k,gamma=gamma)\n labels=model.fit_predict(data)\n accuracy_gamma=accuracy(labels,right_labels)\n best_gamma_score[gamma]=accuracy_gamma\n best_gamma_score=sorted(best_gamma_score.items(),key=lambda d:d[1],reverse=True)\n model_best = SpectralClustering(n_clusters=k, gamma=best_gamma_score[0][0])\n labels = model_best.fit_predict(data)\n adjusted_rand_score=accuracy(labels,right_labels)\n return labels, adjusted_rand_score\n\n#通过PCA降维将数据维度降成二维数据,从而在坐标系中显示数据,完成可视化功能\ndef visualization(data):\n print('Starting PCA')\n pca=PCA(n_components=2)\n # pca.fit(data)\n X=pca.fit_transform(data)\n print(X)\n print('End PCA')\n return X\n\n#利用LOF算法去检测是否有离群点,返回lof_label,false则没有离群点,True则有离群点\ndef LOF(data):\n model=LocalOutlierFactor()\n labels=model.fit_predict(data)\n lof_label=False\n for i in range(len(labels)):\n if(labels[i]==-1):\n lof_label=True\n break\n return lof_label\n\n#算法汇总选择\n#策略,K,数值型混合型标记,可解释标记,数据文件名编码,样本数目,特征数目,数据,分类标签,特征的名字,用户名\n\n#非自动化算法\n\ndef NonAuto_Cluster(Algorithm,K,filename,sample,features,data,target,feature_names,username):\n #正确分类标签\n right_labels=target\n K=int(K)\n #五个标签\n mix_label='undefined'\n explain_label='undefined'\n dimension_label='undefined'\n number_label='undefined'\n noise_label='undefined'\n\n print(\"sample_number is\",sample)\n XY=visualization(data)\n print('Starting Cluster')\n if(Algorithm=='KMeans'):\n print('KMeans:')\n labels,score=kmeans(data,K,right_labels)\n elif(Algorithm=='KModes'):\n print('KModes:')\n labels,score = kmodes(data, K,right_labels)\n elif(Algorithm=='MeanShift'):\n print('MeanShift:')\n labels,score = meanshift(data, K,right_labels)\n elif(Algorithm=='Agglomerative'):\n print('Agglomerative:')\n labels,score = agglomerative(data, K,'ward',right_labels)\n elif(Algorithm=='Birch'):\n print('Birch')\n labels,score = birch(data,K,right_labels)\n elif(Algorithm=='DBSCAN'):\n print('DBSCAN:')\n labels,score=dbscan(data,right_labels)\n elif(Algorithm=='Spectral Clustering'):\n print('Spectral Clustering:')\n labels,score = spectralclustering(data, K,right_labels)\n insert(username, filename, Algorithm, K, mix_label, explain_label, dimension_label, number_label,noise_label,\n sample, data, features, feature_names, target, labels, score, XY)\n return\n#自动化算法\n#KMeans,KModes,MeanShift,Agglomerative,Birch,DBSCAN,Spectral Clustering\ndef Auto_Cluster(K,mix_label,explain_label,filename,sample,features,data,target,feature_names,username):\n right_labels = target\n K = int(K)\n print(\"sample_number is\", sample)\n XY = visualization(data)\n print('Starting Cluster')\n dimension=len(feature_names)-1\n number=sample\n\n # 数值型:0,混合型:1,可解释:1,不可解释:0\n # 五个标签\n # mix_label = 'undefined'\n # explain_label = 'undefined'\n dimension_label = 'undefined'\n number_label = 'undefined'\n noise_label = LOF(data)\n if(mix_label==1):\n labels,score=kmodes(data,K,right_labels)\n insert(username, filename, 'FreeSelect_KModes', K, mix_label, explain_label, dimension_label, number_label, noise_label,\n sample, data, features, feature_names, target, labels, score, XY)\n else:\n #\n if(dimension/number>1):\n dimension_label=True\n labels,score=spectralclustering(data, K,right_labels)\n insert(username, filename, 'FreeSelect_Spectral Clustering', K, mix_label, explain_label, dimension_label, number_label,\n noise_label,\n sample, data, features, feature_names, target, labels, score, XY)\n else:\n dimension_label=False\n #检测使用算法,将样本数的是否走向调换了\n if(number/dimension<1):\n number_label=True\n if(noise_label==True):\n labels, score = spectralclustering(data, K, right_labels)\n insert(username, filename, 'FreeSelect_Spectral Clustering', K, mix_label, explain_label, dimension_label, number_label,noise_label,\n sample, data, features, feature_names, target, labels, score, XY)\n else:\n if(explain_label==1):\n #GMM\n birch_labels,birch_score=birch(data,K,right_labels)\n insert(username, filename, 'Birch', K, mix_label, explain_label, dimension_label,\n number_label, noise_label,\n sample, data, features, feature_names, target, birch_labels, birch_score, XY)\n else:\n kmeans_labels,kmeans_score=kmeans(data,K,right_labels)\n insert(username, filename, 'KMeans', K, mix_label, explain_label, dimension_label,\n number_label, noise_label,\n sample, data, features, feature_names, target, kmeans_labels, kmeans_score, XY)\n meanshift_labels,meanshift_score=meanshift(data,K,right_labels)\n insert(username, filename, 'MeanShift', K, mix_label, explain_label, dimension_label,\n number_label, noise_label,\n sample, data, features, feature_names, target, meanshift_labels, meanshift_score, XY)\n if(kmeans_score>=meanshift_score):\n insert(username, filename, 'FreeSelect_KMeans', K, mix_label, explain_label, dimension_label,\n number_label, noise_label,\n sample, data, features, feature_names, target, kmeans_labels, kmeans_score, XY)\n else:\n insert(username, filename, 'FreeSelect_MeanShift', K, mix_label, explain_label, dimension_label,\n number_label, noise_label,\n sample, data, features, feature_names, target, meanshift_labels, meanshift_score, XY)\n else:\n number_label=False\n if(noise_label==True):\n dbscan_labels, dbscan_score = dbscan(data,right_labels)\n insert(username, filename, 'DBSCAN', K, mix_label, explain_label, dimension_label,\n number_label, noise_label,\n sample, data, features, feature_names, target, dbscan_labels, dbscan_score, XY)\n spectral_labels, spectral_score = spectralclustering(data, K, right_labels)\n insert(username, filename, 'Spectral Clustering', K, mix_label, explain_label, dimension_label,\n number_label, noise_label,\n sample, data, features, feature_names, target, spectral_labels, spectral_score, XY)\n if (dbscan_score >= spectral_score):\n insert(username, filename, 'FreeSelect_DBSCAN', K, mix_label, explain_label, dimension_label,\n number_label, noise_label,\n sample, data, features, feature_names, target, dbscan_labels, dbscan_score, XY)\n else:\n insert(username, filename, 'FreeSelect_Spectral Clustering', K, mix_label, explain_label, dimension_label,\n number_label, noise_label,\n sample, data, features, feature_names, target, spectral_labels, spectral_score, XY)\n else:\n if(explain_label==1):\n birch_labels, birch_score = birch(data, K, right_labels)\n insert(username, filename, 'Birch', K, mix_label, explain_label, dimension_label,\n number_label, noise_label,\n sample, data, features, feature_names, target, birch_labels, birch_score, XY)\n #GMM\n agglomerative_labels,agglomerative_score=agglomerative(data, K,'ward',right_labels)\n insert(username, filename, 'Agglomerative', K, mix_label, explain_label, dimension_label,\n number_label, noise_label,\n sample, data, features, feature_names, target, agglomerative_labels, agglomerative_score, XY)\n\n max_score=max(birch_score,agglomerative_score)\n if(max_score==birch_score):\n insert(username, filename, 'FreeSelect_Birch', K, mix_label, explain_label, dimension_label,\n number_label, noise_label,\n sample, data, features, feature_names, target, birch_labels, birch_score, XY)\n elif(max_score==agglomerative_score):\n insert(username, filename, 'FreeSelect_Agglomerative', K, mix_label, explain_label, dimension_label,\n number_label, noise_label,\n sample, data, features, feature_names, target, agglomerative_labels,\n agglomerative_score, XY)\n else:\n kmeans_labels, kmeans_score = kmeans(data, K, right_labels)\n insert(username, filename, 'KMeans', K, mix_label, explain_label, dimension_label,\n number_label, noise_label,\n sample, data, features, feature_names, target, kmeans_labels, kmeans_score, XY)\n meanshift_labels, meanshift_score = meanshift(data, K, right_labels)\n insert(username, filename, 'MeanShift', K, mix_label, explain_label, dimension_label,\n number_label, noise_label,\n sample, data, features, feature_names, target, meanshift_labels, meanshift_score, XY)\n if (kmeans_score >= meanshift_score):\n insert(username, filename, 'FreeSelect_KMeans', K, mix_label, explain_label,\n dimension_label,\n number_label, noise_label,\n sample, data, features, feature_names, target, kmeans_labels, kmeans_score, XY)\n else:\n insert(username, filename, 'FreeSelect_MeanShift', K, mix_label, explain_label,\n dimension_label,\n number_label, noise_label,\n sample, data, features, feature_names, target, meanshift_labels, meanshift_score, XY)\n\n return\n\n#KMeans,KModes,MeanShift,Agglomerative,Birch,DBSCAN,Spectral Clustering\n#插入MongoDB数据库\ndef insert(username,filename,Algorithm,K,mix_label,explain_label,dimension_label,number_label,noise_label,sample,data,features,feature_names,target,labels,score,XY):\n print('The score of ' + Algorithm + ' is:', score)\n print('Insert DataBase:')\n db = Connectdatabase()\n db.clusterModel.insert({\n \"date\": time.strftime(\"%Y-%m-%d %H:%M:%S\", time.localtime()),\n \"type\": \"Cluster\",\n \"username\": username,\n \"data_name\": filename,\n \"algorithm\": Algorithm,\n \"k_NUM\": K,\n \"mix_label\": mix_label,\n \"explain_label\": explain_label,\n \"dimension_label\": dimension_label,\n \"number_label\": number_label,\n \"noise_label\": noise_label,\n \"sample_count\": sample,\n \"data\": data.astype(np.float64).tolist(),\n \"features_count\": features,\n \"features_names\": feature_names.astype('object').tolist(),\n \"right_labels\": target.astype('object').tolist(),\n \"result_labels\": labels.astype(np.float64).tolist(),\n \"score\": float(score),\n \"xy\": XY.astype(np.float64).tolist()\n })\n print('End Insert')\n # print('The result_labels of ' + Algorithm + ' is:')\n # print(labels)\n\n# python /superalloy/python/cluster/Cluster.py KMeans 3 0 0 glass.csv /superalloy/data/piki/glass.csv piki\nif __name__ == '__main__':\n\n #python 算法文件路径 算法名称0 K1 数值型混合型标记2 可解释标记3 数据文件名编码4 调用文件路径5 用户名6\n #算法路径\n # Algorithm_path='/编程文件/高温合金机器学习平台/聚类算法/Cluster.py'\n # #算法名称 0duedue\n # Algorithm='kmeans'\n # #K1\n # K=4\n # #数据地址 2\n # Data_path='/编程文件/高温合金机器学习平台/聚类算法/iris_data.csv'\n # #user 3\n # user_name='piki'\n # iris=load_data('iris_data.csv')\n # LOF(iris.data)\n length_argv=len(sys.argv)\n print(length_argv)\n\n parameterlist = []\n for i in range(1, len(sys.argv)):\n para = sys.argv[i]\n parameterlist.append(para)\n print(parameterlist)\n\n #自动化\n if(length_argv==7):\n inputdata = load_data(parameterlist[4])\n print('inputdata is:')\n print(inputdata.data)\n Auto_Cluster(parameterlist[0],parameterlist[1],parameterlist[2],parameterlist[3],inputdata.sample,inputdata.features,inputdata.data,inputdata.target,inputdata.feature_names,parameterlist[5])\n elif(length_argv==6):\n inputdata = load_data(parameterlist[3])\n print('inputdata is:')\n print(inputdata.data)\n NonAuto_Cluster(parameterlist[0],parameterlist[1],parameterlist[2],inputdata.sample,inputdata.features,inputdata.data,inputdata.target,inputdata.feature_names,parameterlist[4])\n\n\n\n\n\n\n# def Cluster(Algorithm,K,mix_label,explain_label,filename,sample,features,data,target,feature_names,username):\n","sub_path":"superlloy/python/nonautoclusterselection/Cluster.py","file_name":"Cluster.py","file_ext":"py","file_size_in_byte":23168,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"607741107","text":"import requests, json\nfrom flask import Flask, render_template, redirect, jsonify\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nfrom sqlalchemy.ext.automap import automap_base\nfrom sqlalchemy.orm import Session\nfrom sqlalchemy import create_engine, func\nfrom flask_sqlalchemy import SQLAlchemy\nfrom flask_migrate import Migrate \n\n# response = requests.get(\"https://data.lacity.org/resource/d5tf-ez2w.json\").json()\n# print(response[0].keys())\n\nengine = create_engine(\"sqlite:///sqlite_traffic_weather.db\")\n\nBase = automap_base()\nBase.prepare(engine, reflect=True)\nBase.classes.keys()\n\nTraffic = Base.classes.traffic_data_clean_final\n# Weather = Base.classes.national-weather-service\n\nsession = Session(engine)\n\napp = Flask(__name__)\n\n\n@app.route(\"/\")\ndef welcome():\n return (\n f\"Available Routes:
\"\n f\"/api/v1.0/home
\"\n f\"/api/v1.0/dates
\"\n f\"/api/v1.0/locations
\"\n f\"/api/v1.0/addresses
\"\n f\"/api/v1.0/victimsexes
\"\n )\n\n@app.route(\"/api/v1.0/home\")\ndef index():\n print(\"home\")\n return render_template(\"index.html\")\n\n\n@app.route(\"/api/v1.0/dates\")\ndef dates():\n # Create our session (link) from Python to the DB\n session = Session(engine)\n\n # Query all accidents to return list of dates\n results = session.query(Traffic.Date).all()\n session.close()\n\n # Convert list of tuples into normal list\n all_dates = list(np.ravel(results))\n return jsonify(all_dates)\n\n@app.route(\"/api/v1.0/locations\")\ndef locations():\n # Create our session (link) from Python to the DB\n session = Session(engine)\n\n # Query all accidents to return list of genders\n results = session.query(Traffic.Location).all()\n session.close()\n\n # Convert list of tuples into normal list\n locations = list(np.ravel(results))\n return jsonify(locations)\n\n\n@app.route(\"/api/v1.0/addresses\")\ndef addresses():\n # Create our session (link) from Python to the DB\n session = Session(engine)\n\n # Query all accidents to return list of addresses\n results = session.query(Traffic.Address).all()\n session.close()\n\n # Convert list of tuples into normal list\n all_addresses = list(np.ravel(results))\n return jsonify(all_addresses)\n\n\n@app.route(\"/api/v1.0/victimsexes\")\ndef victimsexes():\n # Create our session (link) from Python to the DB\n session = Session(engine)\n\n # Query all accidents to return list of genders\n results = session.query(Traffic.Victim_Sex).all()\n session.close()\n\n # Convert list of tuples into normal list\n victimsexes = list(np.ravel(results))\n return jsonify(victimsexes)\n\n\nif __name__ == \"__main__\":\n app.run(debug=True)\n","sub_path":"Tan/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":2691,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"342935354","text":"#!/usr/bin/env python3\n\n# Config.py\n# ~~~~~~~~\n# This file holds the configuration for the bot,\n# not including passwords and secrets - those are\n# in Secrets.py which is a gitignored file\n\nimport re\nimport sys\nimport praw\n\ntry:\n from PokeFacts import Secrets\nexcept ImportError:\n import Secrets\n\n# APPLICATION AUTH\n# ----------------\n\nUSERNAME = \"PokeFacts\" # case matters!\nPASSWORD = Secrets.PASSWORD\nAPP_ID = \"9RiijpOogYO53A\"\nAPP_SECRET = Secrets.APP_SECRET\n\n# APPLICATION META INFO\n# ---------------------\n\nDEVELOPERS = \"/u/kwwxis, /u/Haruka-sama\"\nVERSION = \"1.0.1\"\nDESCRIPTION = \"Responds to specific text in pokemon subreddits with a response\"\nUSERAGENT = USERNAME + \":\" + DESCRIPTION + \" v\" + VERSION + \" by \" + DEVELOPERS\nDSN = \"https://103153c555104b6695bc06dc10252c62:ffa3fc21a9ed48aaad63b3109f329fec@sentry.io/1197206\"\n\n# OPERATOR CONFIG\n# ---------------\n\nOPERATORS = [\"kwwxis\", \"Haruka-sama\", \"bigslothonmyface\", \"technophonix1\", \"D0cR3d\", \"thirdegree\"]\n\n# RESPONDER CONFIG\n# ----------------\n\n# list of subreddits the bot is allowed to operate on (case matters!)\nSUBREDDITS = [\"pokemon\", \"PokemonMods\"]\n\n# should check comments?\nRESPONDER_CHECK_COMMENTS = True\n\n# should check submissions?\nRESPONDER_CHECK_SUBMISSIONS = True\n\n# if true, check comments that have been edited on subreddits the bot has 'posts' perms on\nRESPONDER_CHECK_EDITED = True\n\n# should check mentions\nRESPONDER_CHECK_MENTIONS = True\n\n# should respond to mentions in subreddits outside of SUBREDDITS?\nRESPONDER_CHECK_MENTIONS_OTHER_SUBREDDITS = True\n\n# IDENTIFIER CONFIG\n# -----------------\n\nIDENTIFIER_TO_LOWER = True\nIDENTIFIER_NO_ACCENTS = True\nIDENTIFIER_SANITIZE = r\"[^A-Za-z0-9 ]\"\n\n# DATAPULLS CONFIG\n# ----------------\n\nDATA_FILES = ['/data/pokemon.json', '/data/items.json', '/data/moves.json', '/data/abilities.json'] # list of json files for responder to search with\nDATA_SYNONYM_FILES = ['/data/synonyms.json']\nDATA_CONF = {\n # defines which item property to use for the 'type' field\n # if this property is not set, then all items will have\n # no type (i.e. `None`)\n \"type_property\": \"type\",\n\n # defines which item property to use for the item terms\n \"term_property\": \"term\",\n\n # search a specific type for a given prefix (works for both pair and standalone)\n # - use `None` to search items that do not have a type\n # - use a list for searching multiple types\n # - set to `True` to search over all types including items without types\n # If this property is not set, then all prefixes will search over all types\n \"type_for_prefix\": {\n \"{\": True,\n \"<\": True,\n \"!\": True,\n }\n}\nDATA_USE_SYMSPELL = True\n\n# RESPONSE CONFIG\n# ---------------\n\nREPLY_TEMPLATE_FILE = \"/data/response.txt\"\nREPLY_SHOULD_STICKY = False # should sticky comment if reply is top level?\nREPLY_SHOULD_DISTINGUISH = False # should distinguish comment?\n\n# MATCH STRING\n# ------------\n\n# Valid matches (for the current configuration)\n# {POKEMON_NAME}, , or !POKEMON_NAME\n# exclamation mark notation does not accept pokemon names containing spaces\n\n# prefixes and suffixes should be same length arrays\n# the prefixes and suffixes items of the same index should be pairs\n# e.g. ['{', '<'] and ['}', '>']\n# not ['{', '<'] and ['>', '}']\n\n# you can change these\nMATCH_PAIR_PREFIXES = ['{', '<']\nMATCH_PAIR_SUFFIXES = ['}', '>']\nMATCH_PAIR_VALUE = r\"[A-Za-zÀ-ÿ0-9\\'\\-\\. ]+\"\nMATCH_STANDALONE_PREFIXES = ['!']\nMATCH_STANDALONE_VALUE = r\"[A-Za-zÀ-ÿ0-9\\'\\-]+\"\n\n# DO NOT CHANGE ANYTHING BELOW THIS LINE\n# --------------------------------------\nMATCH_STRING = ''\nMATCH_STRING += '(' + '|'.join(re.escape(item) for item in MATCH_PAIR_PREFIXES) + ')'\nMATCH_STRING += MATCH_PAIR_VALUE\nMATCH_STRING += '(' + '|'.join(re.escape(item) for item in MATCH_PAIR_SUFFIXES) + ')'\nMATCH_STRING += '|'\nMATCH_STRING += r\"(?:^|\\s+)\"\nMATCH_STRING += '(' + '|'.join(re.escape(item) for item in MATCH_STANDALONE_PREFIXES) + ')'\nMATCH_STRING += MATCH_STANDALONE_VALUE\nif not type(SUBREDDITS) == list or len(SUBREDDITS) == 0 or \"all\" in SUBREDDITS:\n print(\"Invalid Configuration!\")\n sys.exit(0)\nREDDIT = None\ndef reddit():\n global REDDIT\n if REDDIT is None:\n REDDIT = praw.Reddit(user_agent = USERAGENT,\n client_id = APP_ID,\n client_secret = APP_SECRET,\n username = USERNAME,\n password = PASSWORD)\n return REDDIT","sub_path":"PokeFacts/Config.py","file_name":"Config.py","file_ext":"py","file_size_in_byte":4601,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"113144767","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\nimport json\nimport argparse\nimport multiprocessing\n\nparser = argparse.ArgumentParser(description='Adjusts number of parallel executions')\nparser.add_argument('--config', dest='config')\nparser.add_argument('--workers', dest='workers', type=int, default=None,\n help='Number of parallel workers to use')\nargs = parser.parse_args()\n\nargs.config = args.config or '/rtt_backend/rtt_execution/rtt-settings.json'\nargs.workers = args.workers or max(1, multiprocessing.cpu_count() - 1)\n\njs = None\nwith open(args.config) as fh:\n js = json.load(fh)\n js['toolkit-settings']['execution']['max-parallel-tests'] = args.workers\n\nwith open(args.config, 'w') as fh:\n json.dump(js, fh, indent=2)\n\n","sub_path":"files/adjust_workers.py","file_name":"adjust_workers.py","file_ext":"py","file_size_in_byte":753,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"315057243","text":"import math\n\n# approximate radius of earth in km\nR = 6373.0\n\ndef get(lat1, lon1, lat2, lon2):\n\n radius = 6371 # km\n\n dlat = math.radians(lat2 - lat1)\n dlon = math.radians(lon2 - lon1)\n a = (math.sin(dlat / 2) * math.sin(dlat / 2) +\n math.cos(math.radians(lat1)) * math.cos(math.radians(lat2)) *\n math.sin(dlon / 2) * math.sin(dlon / 2))\n c = 2 * math.atan2(math.sqrt(a), math.sqrt(1 - a))\n d = radius * c\n\n return d\n","sub_path":"distance.py","file_name":"distance.py","file_ext":"py","file_size_in_byte":454,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"277558153","text":"import pandas as pd\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\nimport calculate_light\r\n\r\ndirac = ['_dirac_1', '_dirac_2', '_dirac_3']\r\nh264 = ['_h264_1', '_h264_2', '_h264_3', '_h264_4']\r\nip = ['_ip_1', '_ip_2', '_ip_3','_ip_4']\r\nmpeg2 = ['_mpeg2_1', '_mpeg2_2', '_mpeg2_3']\r\ndname = [dirac, h264, mpeg2, ip]\r\ndname_r = ['dirac', 'h264', 'mpeg2','ip']\r\nsname = ['laser']\r\nmetric_group = ['PSNR','SSIM','VMAF','PSNRHVS','VIFP','PSNRHVSM']\r\npsnr_group =[]\r\nvmaf_group =[]\r\nssim_group =[]\r\npsnrhvs_group =[]\r\nvifp_group = []\r\npsnrhvsm_group =[]\r\nmetric_result_group =[psnr_group,ssim_group,vmaf_group,psnrhvs_group,vifp_group,psnrhvsm_group]\r\ns_score_group =[]\r\nmarkers = ['o','v','^','<','>','d','s','p','h']\r\n\r\ndef plot(mindex,metric):\r\n df = pd.read_csv(metric+'_light.csv')\r\n sample_list = df.loc[:, 'Name']\r\n for sample_name in sname:\r\n df_sample = pd.DataFrame()\r\n count = 0\r\n count_1 = 0\r\n for samples in sample_list:\r\n if samples.find(sample_name) != -1:\r\n df_sample.insert(count, samples, [df.loc[count_1, metric], ])\r\n count += 1\r\n count_1 += 1\r\n metric_result_group[mindex].append(df_sample)\r\n # plot starts\r\n plt.xlim((-20, 120))\r\n if metric == 'PSNR':\r\n y_axi = (24, 42)\r\n y_linespace = [24, 42, 9]\r\n elif metric == 'SSIM':\r\n y_axi = (0.75,1.05)\r\n y_linespace = [0.75, 1.05, 9]\r\n elif metric == 'VMAF':\r\n y_axi = (30,110)\r\n y_linespace = [30, 110, 9]\r\n elif metric == 'PSNRHVS':\r\n y_axi = (24, 42)\r\n y_linespace = [24, 42, 9]\r\n elif metric == 'VIFP':\r\n y_axi = (0.3,0.9)\r\n y_linespace = [0.3, 0.9, 9]\r\n elif metric == 'PSNRHVSM':\r\n y_axi = (24, 42)\r\n y_linespace = [24, 42, 9]\r\n plt.ylim(y_axi)\r\n x_ax = np.linspace(-20, 120, 8)\r\n y_ax = np.linspace(y_linespace[0], y_linespace[1], y_linespace[2])\r\n plt.xticks(x_ax)\r\n plt.yticks(y_ax)\r\n x_set_total = []\r\n y_set_total = []\r\n index = 0\r\n for sample_metric in metric_result_group[mindex]:\r\n y_dirac_set = []\r\n y_h264_set = []\r\n y_mpeg2_set = []\r\n y_ip_set = []\r\n for i in range(4):\r\n y_ip_set.append(sample_metric.iloc[0, i + 10])\r\n y_h264_set.append(sample_metric.iloc[0, i + 3])\r\n for i in range(3):\r\n y_dirac_set.append(sample_metric.iloc[0, i])\r\n y_mpeg2_set.append(sample_metric.iloc[0, i + 7])\r\n y_set = y_dirac_set + y_h264_set + y_mpeg2_set + y_ip_set\r\n for i in y_set:\r\n y_set[y_set.index(i)] = float(i)\r\n x_set = []\r\n for i in range(14):\r\n x_set.append(s_score_group[index].iloc[0, i])\r\n plt.xlabel(\"DMOS\")\r\n plt.ylabel(metric)\r\n marker = markers[index]\r\n P1 = plt.scatter(x_set[0:3], y_set[0:3], s = 13, c='r', marker=marker)\r\n P2 = plt.scatter(x_set[3:7], y_set[3:7], s = 13, c='g', marker=marker)\r\n P3 = plt.scatter(x_set[7:10], y_set[7:10], s = 13, c='b', marker=marker)\r\n P4 = plt.scatter(x_set[10:14], y_set[10:14], s = 13, c='orange', marker=marker)\r\n x_set_total += x_set\r\n y_set_total += y_set\r\n index += 1\r\n plt.title(metric)\r\n plt.grid(ls='--')\r\n np_x = np.array(x_set_total)\r\n np_y = np.array(y_set_total)\r\n std_x = np_x.std(ddof=1)\r\n std_y = np_y.std(ddof=1)\r\n cov_xy_m = np.cov(np_x, np_y)\r\n cov_xy = cov_xy_m[0, 1]\r\n PCC = cov_xy / (std_x * std_y)\r\n PCC = str(PCC)\r\n np_x_sorted = np.sort(np_x, axis=None)\r\n np_y_sorted = np.sort(np_y, axis=None)\r\n np_x_order = []\r\n np_y_order = []\r\n for x in np_x:\r\n for i in range(np_x_sorted.shape[0]):\r\n if (np_x_sorted[i] == x).all():\r\n np_x_order.append(i + 1)\r\n break\r\n for y in np_y:\r\n for i in range(np_y_sorted.shape[0]):\r\n if (np_y_sorted[i] == y).all():\r\n np_y_order.append(i + 1)\r\n break\r\n d_order = [np_y_order[i] - np_x_order[i] for i in range(len(np_y_order))]\r\n d_order_square = [d_order[i] * d_order[i] for i in range(len(d_order))]\r\n d_order_square_sum = 0\r\n for item in d_order_square:\r\n d_order_square_sum += item\r\n SRCC = 1 - 6 * d_order_square_sum / ((len(d_order)) ** 3 - len(d_order))\r\n SRCC = str(SRCC)\r\n xy_couple = []\r\n xy_couple_group = []\r\n C = 0\r\n D = 0\r\n for item in range(len(np_x_order)):\r\n xy_couple.append(np_x_order[item])\r\n xy_couple.append(np_y_order[item])\r\n xy_couple_group.append(xy_couple)\r\n xy_couple = []\r\n for item in range(len(xy_couple_group)):\r\n for item_1 in range(item + 1, len(xy_couple_group)):\r\n if xy_couple_group[item][0] > xy_couple_group[item_1][0] and xy_couple_group[item][1] > \\\r\n xy_couple_group[item_1][1]:\r\n C += 1\r\n elif xy_couple_group[item][0] < xy_couple_group[item_1][0] and xy_couple_group[item][1] < \\\r\n xy_couple_group[item_1][1]:\r\n C += 1\r\n else:\r\n D += 1\r\n KRCC = (C - D) / (0.5 * len(np_x_order) * (len(np_x_order) - 1))\r\n KRCC = str(KRCC)\r\n if metric == 'PSNR':\r\n p_text = [0, 39]\r\n elif metric == 'SSIM':\r\n p_text = [0, 1]\r\n elif metric == 'VMAF':\r\n p_text = [0, 97]\r\n elif metric == 'PSNRHVS':\r\n p_text = [0, 39]\r\n elif metric == 'VIFP':\r\n p_text = [0, 0.800]\r\n elif metric == 'PSNRHVSM':\r\n p_text = [0, 39]\r\n plt.legend([P1, P2, P3, P4], ['Dirac', 'h264', 'mpeg2', 'packet loss'], loc='lower right', scatterpoints=1)\r\n plt.text(p_text[0], p_text[1], 'PCC:' + PCC + '\\n' + 'SRCC:' + SRCC + '\\n' + 'KRCC:' + KRCC, fontdict={'size': 13, 'color': 'r'})\r\n plt.savefig('./'+metric+'_light_.png')\r\n plt.show()\r\n\r\ndef import_dmos():\r\n df_score = pd.read_csv('subjective_score_all.csv')\r\n sample_list = df_score.loc[:, 'Name']\r\n for sample_name in sname:\r\n df_sample_score = pd.DataFrame()\r\n count = 0\r\n count_1 = 0\r\n for samples in sample_list:\r\n if samples.find(sample_name) != -1:\r\n df_sample_score.insert(count, samples, [df_score.loc[count_1, 'DMOS'], ])\r\n count += 1\r\n count_1 += 1\r\n s_score_group.append(df_sample_score)\r\n for df_sample_score in s_score_group:\r\n for i in range(14):\r\n df_sample_score.iloc[0, i] = (1 - df_sample_score.iloc[0, i] / 5) * 100\r\n\r\ndef plotting():\r\n for mindex in range(len(metric_group)):\r\n plot(mindex,metric_group[mindex])\r\n\r\nif __name__ == '__main__':\r\n calculate_light.calculation()\r\n import_dmos()\r\n plotting()\r\n","sub_path":"plot_light.py","file_name":"plot_light.py","file_ext":"py","file_size_in_byte":6741,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"225372934","text":"#-------------------STARTUP-BOX--------------------------#\n#-----Group-Task-On-Image-Processing---------------------#\n#-----Group-Members--------------------------------------#\n#------------------Krishna Prasad K----------------------#\n#------------------Amal Dethan---------------------------#\n#------------------Deepu SP------------------------------#\n#------------------Manu Karthikeyan----------------------#\n#---------------[Govt. RIT, Kottayam]--------------------#\n\nimport gtk\nfrom PIL import Image,ImageChops\nimport math\nimport urllib\n\nclass comparison:\n def __init__(self):\n def message(msg):\n dialog=gtk.MessageDialog(win,type=gtk.MESSAGE_ERROR,buttons=gtk.BUTTONS_OK)\n dialog.set_title(\"Error\")\n dialog.set_markup(msg)\n response=dialog.run()\n dialog.destroy()\n\n\n\n def result(res,data):\n dialog=gtk.MessageDialog(win,type=gtk.MESSAGE_INFO,buttons=gtk.BUTTONS_OK)\n dialog.set_title(\"Result\")\n calc=str(100-float(res))\n if float(res)>100:\n d='0'\n else:\n d=str(100-(float(res)))\n\n dialog.set_markup(''+\"Similarity: \"+d+'')\n\n response=dialog.run()\n dialog.destroy()\n\n\n\n def compare(self):\n try:\n url1=entry1.get_text()\n url2=entry2.get_text()\n new_file_type1=url1[-4:]\n new_file_type2=url2[-4:]\n if new_file_type1=='.jpe' or new_file_type2=='.jpe':\n new_file_type1='.jpeg'\n new_file_type2='.jpeg'\n\n urllib.urlretrieve(url1,'image1'+new_file_type1)\n urllib.urlretrieve(url2,'image2'+new_file_type2)\n\n image1=Image.open('image1'+new_file_type1)\n image2=Image.open('image2'+new_file_type2)\n image_height=image1.size[0]\n image_width=image1.size[1]\n\n mode='RGB'\n difference=ImageChops.difference(image1.convert(mode),image1.convert(mode))\n histo=difference.histogram()\n squares=(j*(i**2) for i, j in enumerate(histo))\n sum_of_squares=sum(squares)\n rms=math.sqrt(sum_of_squares/float(image_height * image_width))\n default_value=rms\n\n\n difference=ImageChops.difference(image1.convert(mode),image2.convert(mode))\n histo=difference.histogram()\n squares=(j*(i**2) for i, j in enumerate(histo))\n sum_of_squares=sum(squares)\n rms=math.sqrt(sum_of_squares/float(image_height * image_width))\n current_value=rms\n\n\n res=str(math.floor(abs(default_value-current_value)))\n result(res,default_value)\n\n except Exception as e:\n message(str(e))\n\n\n\n\n frame=gtk.Frame()\n hbox=gtk.HBox()\n vbox=gtk.VBox()\n label1=gtk.Label(\"Enter the first image url\")\n label2=gtk.Label(\"Enter the second image url\")\n entry1=gtk.Entry()\n entry2=gtk.Entry()\n button=gtk.Button(\"Compare\")\n button.connect(\"clicked\",compare)\n fixed=gtk.Fixed()\n fixed.put(label1,20,100)\n fixed.put(entry1,200,100)\n fixed.put(label2,20,150)\n fixed.put(entry2,200,150)\n fixed.put(button,170,200)\n frame.add(fixed)\n heading=gtk.Label()\n heading.set_markup('Image Comparison')\n about=gtk.Label('''A Startup Box group task done by Krishna Prasad K, Manu Karthikeyan,\n Amal Dethan and Deepu SP.''')\n fixed.put(heading,100,30)\n fixed.put(about,10,260)\n win=gtk.Window()\n win.add(frame)\n win.set_size_request(400,300)\n win.connect('delete_event',gtk.main_quit)\n win.set_title('Image Comparison')\n win.set_position(gtk.WIN_POS_CENTER_ALWAYS)\n win.show_all()\n\nif __name__=='__main__':\n comparison()\n gtk.main()\n\n","sub_path":"thewatsongroup/comparison.py","file_name":"comparison.py","file_ext":"py","file_size_in_byte":3969,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"581718035","text":"import logging\nimport sys\nimport socketserver\nimport uuid\nimport socket\nimport threading\nimport requests\n\nlogging.basicConfig(filename=\"env_logs.log\", level=logging.DEBUG, format='%(name)s: %(message)s', )\n\n\nclass EchoRequestHandler(socketserver.BaseRequestHandler):\n\n def handle(self):\n # Echo the back to the client\n data = self.request.recv(1024)\n self.request.sendall(data)\n\n return\n\n\nclass EchoServer(socketserver.ThreadingMixIn, socketserver.TCPServer):\n\n def __init__(self, server_address: tuple):\n # socketserver.TCPServer.__init__(self, server_address, handler_class)\n\n super().__init__(server_address, EchoRequestHandler)\n self.server_id = uuid.uuid4()\n self.logger = logging.getLogger(f'EchoServer({self.server_id})')\n self.logger.debug(f'server created ip={self.server_address[0]} port={self.server_address[1]}')\n self.connection_history = []\n self.is_running = False\n\n def finish_request(self, request, client_address):\n print(f'Server handled request from {client_address}')\n self.logger.debug(f'request handled')\n return super().finish_request(request, client_address)\n\n def run_me(self):\n \"\"\"Run server to handle each request on a diferent thread.\"\"\"\n t = threading.Thread(target=self.serve_forever)\n t.daemon = True # don't hang on exit\n t.start()\n self.is_running = True\n\n def stop_me(self):\n self.logger.debug('closing server')\n self.shutdown()\n self.server_close()\n\n def message_peer(self, message, peer):\n \"\"\"Send message to a peer server\"\"\"\n try:\n self.logger.debug(f'sending message to peer={peer.server_id}, message=\\\"{message}\\\"')\n\n self.connection_history.append(peer.server_id.__str__())\n\n ip, port = peer.server_address\n sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n sock.connect((ip, port))\n sock.sendall(bytes(message, 'ascii'))\n print(f'Server({self.server_id}): {message}')\n response = str(sock.recv(1024), 'ascii')\n sock.close()\n self.logger.debug(f'recieved response from peer={peer.server_id}, response={response}')\n except:\n print(f'Unable to send message to {peer}')\n\n def send_external(self, external_address):\n self.logger.debug(f'connecting to {external_address}')\n req = requests.get(url=external_address)\n self.connection_history.append(external_address)\n print(f'Response from {external_address}: {req.status_code}')\n\n def __repr__(self):\n ip, port = self.server_address\n return f'EchoServer'","sub_path":"serverAndClient/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":2806,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"525394222","text":"# make a program which allows the user to pick between sandwiches, return their order and value\r\n# sub divide cheeze selection and allow a meat and vegan option\r\n\r\ndef sandwich_shoppe(user_option): # This will convert the user input into something our program understands\r\n if user_option.isalpha() == False:\r\n print(\"NO!\")\r\n return False\r\n else:\r\n if user_option.lower() == \"c\": # cheese logic\r\n cheese_type = input(\"(C)heddar, (A)merican, or (S)wiss? \")\r\n if cheese_type.lower() == \"c\":\r\n output = \"Cheddar Cheese coming up!\"\r\n elif cheese_type.lower() == \"a\":\r\n output = \"American Classic coming up!\"\r\n elif cheese_type.lower() == \"s\":\r\n output = \"The Exotic Swiss!\"\r\n else:\r\n output = \"Umm...not sure what went wrong...\"\r\n return output\r\n\r\n if user_option.lower() == \"m\": # meat logic\r\n meat_type = input(\"(H)am, (B)eef, or (T)urkey? \")\r\n if meat_type.lower() == \"h\":\r\n output = \"HHHHHHAAAAAMMMMMY Samy!\"\r\n return output\r\n elif meat_type.lower() == \"b\":\r\n output = \"Where's the beef? In your hot little hands!\"\r\n return output\r\n elif meat_type.lower() == \"t\":\r\n output = \"Gobble Gobble, motherfuckers\"\r\n return output\r\n else:\r\n output = \"Yeah, no\"\r\n return output\r\n if user_option.lower() == \"v\": # logical logic\r\n output = \"Soylent Green is peop...wait, vegan,coming up.\"\r\n return output\r\n\r\n\r\nnew_order = input(\"You going (m)eat, (c)heese, or (v)egan\")\r\nnew_order.lower()\r\nprint(sandwich_shoppe(new_order))\r\n\r\n\r\n\r\n\r\n# (C)heese:\r\n# (C)heddar\r\n# (A)merican\r\n# (S)wiss\r\n# (M)eat:\r\n# (H)am\r\n# (B)eef\r\n# (T)urkey\r\n# (V)egan:\r\n# (V)egan","sub_path":"Sandwich_Shoppe.py","file_name":"Sandwich_Shoppe.py","file_ext":"py","file_size_in_byte":1931,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"404895581","text":"import base64\nimport json\nimport os\n\nimport libtorrent as lt\n\n\ndef gen_state(h, state):\n state_str = ['queued', 'checking', 'downloading metadata',\n 'downloading', 'finished', 'seeding', 'allocating',\n 'checking fastresume']\n if h.is_paused():\n return \"paused\"\n return state_str[state]\n\n\ndef torrent_to_dict(h, full=False):\n s = h.status()\n ret = {\"name\": h.name(),\n \"hash\": str(h.info_hash()),\n \"peers\": s.num_peers,\n \"seeds\": s.num_seeds,\n \"progress\": s.progress,\n \"downRate\": s.download_rate,\n \"upRate\": s.upload_rate,\n \"size\": s.total_wanted,\n \"size_down\": s.total_wanted_done,\n \"size_up\": s.all_time_upload,\n \"state\": gen_state(h, s.state),\n \"position\": s.queue_position}\n\n if not full:\n return ret\n\n ret[\"path\"] = h.save_path() + h.name()\n ret[\"files\"] = []\n files = h.get_torrent_info().files()\n for i in range(0, files.num_files()):\n ret[\"files\"].append((i, files.file_path(i), h.file_priority(i)))\n\n return ret\n\n\nclass TorrentManager:\n def __init__(self, download_path=\"downloads\", fast_resume_config=\"fast_resume.json\"):\n self.ses = lt.session()\n self.ses.listen_on(6881, 689)\n self.download_path = download_path\n self.fast_resume_config = fast_resume_config\n self.torrents = []\n self.fast_resume()\n\n def fast_resume(self):\n if not os.path.exists(self.fast_resume_config):\n return\n with open(self.fast_resume_config, \"r\") as f:\n infos = json.load(f)\n for info in infos:\n print(info[\"name\"])\n h = self.ses.add_torrent({'resume_data': base64.b64decode(info[\"data\"]),\n 'save_path': info[\"path\"]})\n if h.is_valid():\n self.torrents.append(h)\n else:\n print(\"error\")\n\n def add_torrent_file(self, path, paused=False, auto_managed=False):\n info = lt.torrent_info(path)\n h = self.ses.add_torrent({'ti': info,\n 'save_path': self.download_path,\n 'storage_mode': lt.storage_mode_t(2),\n 'paused': paused,\n 'auto_managed': auto_managed,\n 'duplicate_is_error': True})\n\n if h.is_valid():\n self.torrents.append(h)\n\n def get(self, info_hash):\n for h in self.torrents:\n if info_hash == str(h.info_hash()):\n return h\n\n def get_info(self, info_hash=None, full=False):\n ret = []\n for h in self.torrents:\n if not info_hash or info_hash == str(h.info_hash()):\n ret.append(torrent_to_dict(h, full=full))\n return ret\n\n def pause(self, info_hash=None):\n for h in self.torrents:\n if not info_hash or info_hash == str(h.info_hash()):\n if h.is_paused():\n h.resume()\n else:\n h.pause()\n\n def files(self, info_hash):\n ret = []\n h = self.get(info_hash)\n files = h.get_torrent_info().files()\n for i in range(0, files.num_files()):\n ret.append(files.file_path(i))\n return ret\n\n def path(self, info_hash):\n h = self.get(info_hash)\n return h.save_path()+\"/\"+h.name()\n\n def remove(self, info_hash):\n h = self.get(info_hash)\n self.ses.remove_torrent(h)\n self.torrents.remove(h)\n\n def test(self):\n for torrent in self.torrents:\n files = torrent.get_torrent_info().files()\n print(files.name())\n for i in range(0, files.num_files()):\n print(files.file_path(i))\n return {\"result\": None}\n\n def close(self):\n count = 0\n self.ses.pause()\n for torrent in self.torrents:\n torrent.save_resume_data(lt.save_resume_flags_t.flush_disk_cache | lt.save_resume_flags_t.save_info_dict)\n count += 1\n\n data_to_save = []\n while count > 0:\n alert = self.ses.pop_alert()\n if type(alert) == lt.save_resume_data_alert:\n h = alert.handle\n data = lt.bencode(alert.resume_data)\n data_to_save.append({\"name\": h.get_torrent_info().name(),\n \"data\": base64.b64encode(data).decode(),\n \"path\": h.save_path()})\n count -= 1\n\n with open(self.fast_resume_config, \"w\") as f:\n json.dump(data_to_save, f)\n","sub_path":"torrent.py","file_name":"torrent.py","file_ext":"py","file_size_in_byte":4694,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"142259626","text":"import numpy as np\nimport scipy.stats as stats\n\nfrom UQpy.SampleMethods.LHS import LHS\n########################################################################################################################\n########################################################################################################################\n# Adaptive Kriging-Monte Carlo Simulation (AK-MCS)\n########################################################################################################################\n\nclass AKMCS:\n \"\"\"\n Adaptively sample for construction of a Kriging surrogate for different objectives including reliability,\n optimization, and global fit.\n\n\n **Inputs:**\n\n * **dist_object** ((list of) ``Distribution`` object(s)):\n List of ``Distribution`` objects corresponding to each random variable.\n\n * **runmodel_object** (``RunModel`` object):\n A ``RunModel`` object, which is used to evaluate the model.\n\n * **samples** (`ndarray`):\n The initial samples at which to evaluate the model.\n\n Either `samples` or `nstart` must be provided.\n\n * **krig_object** (`class` object):\n A Kriging surrogate model, this object must have ``fit`` and ``predict`` methods.\n\n May be an object of the ``UQpy`` ``Kriging`` class or an object of the ``scikit-learn``\n ``GaussianProcessRegressor``\n\n * **nsamples** (`int`):\n Total number of samples to be drawn (including the initial samples).\n\n If `nsamples` and `samples` are provided when instantiating the class, the ``run`` method will automatically be\n called. If either `nsamples` or `samples` is not provided, ``AKMCS`` can be executed by invoking the ``run``\n method and passing `nsamples`.\n\n * **nlearn** (`int`):\n Number of samples generated for evaluation of the learning function. Samples for the learning set are drawn\n using ``LHS``.\n\n * **qoi_name** (`dict`):\n Name of the quantity of interest. If the quantity of interest is a dictionary, this is used to convert it to\n a list\n\n * **learning_function** (`str` or `function`):\n Learning function used as the selection criteria to identify new samples.\n\n Built-in options:\n 1. 'U' - U-function \\n\n 2. 'EFF' - Expected Feasibility Function \\n\n 3. 'Weighted-U' - Weighted-U function \\n\n 4. 'EIF' - Expected Improvement Function \\n\n 5. 'EGIF' - Expected Global Improvement Fit \\n\n\n `learning_function` may also be passed as a user-defined callable function. This function must accept a Kriging\n surrogate model object with ``fit`` and ``predict`` methods, the set of learning points at which to evaluate the\n learning function, and it may also take an arbitrary number of additional parameters that are passed to\n ``AKMCS`` as `**kwargs`.\n\n * **n_add** (`int`):\n Number of samples to be added per iteration.\n\n Default: 1.\n\n * **random_state** (None or `int` or ``numpy.random.RandomState`` object):\n Random seed used to initialize the pseudo-random number generator. Default is None.\n\n If an integer is provided, this sets the seed for an object of ``numpy.random.RandomState``. Otherwise, the\n object itself can be passed directly.\n\n * **verbose** (`Boolean`):\n A boolean declaring whether to write text to the terminal.\n\n Default value: False.\n\n * **kwargs**\n Used to pass parameters to `learning_function`.\n\n For built-in `learning_functions`, see the requisite inputs in the method list below.\n\n For user-defined `learning_functions`, these will be defined by the requisite inputs to the user-defined method.\n\n\n **Attributes:**\n\n * **samples** (`ndarray`):\n `ndarray` containing the samples at which the model is evaluated.\n\n * **lf_values** (`list`)\n The learning function evaluated at new sample points.\n\n\n **Methods:**\n\n \"\"\"\n\n def __init__(self, dist_object, runmodel_object, krig_object, samples=None, nsamples=None, nlearn=None,\n qoi_name=None, learning_function='U', n_add=1, random_state=None, verbose=False, **kwargs):\n\n # Initialize the internal variables of the class.\n self.runmodel_object = runmodel_object\n self.samples = np.array(samples)\n self.nlearn = nlearn\n self.nstart = None\n self.verbose = verbose\n self.qoi_name = qoi_name\n\n self.learning_function = learning_function\n self.learning_set = None\n self.dist_object = dist_object\n self.nsamples = nsamples\n\n self.moments = None\n self.n_add = n_add\n self.indicator = False\n self.pf = []\n self.cov_pf = []\n self.dimension = 0\n self.qoi = None\n self.krig_model = None\n self.kwargs = kwargs\n\n # Initialize and run preliminary error checks.\n self.dimension = len(dist_object)\n\n if samples is not None:\n if self.dimension != self.samples.shape[1]:\n raise NotImplementedError(\"UQpy Error: Dimension of samples and distribution are inconsistent.\")\n\n if self.learning_function not in ['EFF', 'U', 'Weighted-U', 'EIF', 'EIGF']:\n raise NotImplementedError(\"UQpy Error: The provided learning function is not recognized.\")\n elif self.learning_function == 'EIGF':\n self.learning_function = self.eigf\n elif self.learning_function == 'EIF':\n if 'eif_stop' not in self.kwargs:\n self.kwargs['eif_stop'] = 0.01\n self.learning_function = self.eif\n elif self.learning_function == 'U':\n if 'u_stop' not in self.kwargs:\n self.kwargs['u_stop'] = 2\n self.learning_function = self.u\n elif self.learning_function == 'Weighted-U':\n if 'u_stop' not in self.kwargs:\n self.kwargs['u_stop'] = 2\n self.learning_function = self.weighted_u\n else:\n if 'a' not in self.kwargs:\n self.kwargs['a'] = 0\n if 'epsilon' not in self.kwargs:\n self.kwargs['epsilon'] = 2\n if 'eff_stop' not in self.kwargs:\n self.kwargs['u_stop'] = 0.001\n self.learning_function = self.eff\n\n from UQpy.Distributions import DistributionContinuous1D, JointInd\n\n if isinstance(dist_object, list):\n for i in range(len(dist_object)):\n if not isinstance(dist_object[i], DistributionContinuous1D):\n raise TypeError('UQpy: A DistributionContinuous1D object must be provided.')\n else:\n if not isinstance(dist_object, (DistributionContinuous1D, JointInd)):\n raise TypeError('UQpy: A DistributionContinuous1D or JointInd object must be provided.')\n\n self.random_state = random_state\n if isinstance(self.random_state, int):\n self.random_state = np.random.RandomState(self.random_state)\n elif not isinstance(self.random_state, (type(None), np.random.RandomState)):\n raise TypeError('UQpy: random_state must be None, an int or an np.random.RandomState object.')\n\n if hasattr(krig_object, 'fit') and hasattr(krig_object, 'predict'):\n self.krig_object = krig_object\n else:\n raise NotImplementedError(\"UQpy: krig_object must have 'fit' and 'predict' methods.\")\n\n if self.verbose:\n print('UQpy: AKMCS - Running the initial sample set using RunModel.')\n\n # Evaluate model at the training points\n if len(self.runmodel_object.qoi_list) == 0 and samples is not None:\n self.runmodel_object.run(samples=self.samples, append_samples=False)\n if samples is not None:\n if len(self.runmodel_object.qoi_list) != self.samples.shape[0]:\n raise NotImplementedError(\"UQpy: There should be no model evaluation or Number of samples and model \"\n \"evaluation in RunModel object should be same.\")\n\n if self.nsamples is not None:\n if self.nsamples <= 0 or type(self.nsamples).__name__ != 'int':\n raise NotImplementedError(\"UQpy: Number of samples to be generated 'nsamples' should be a positive \"\n \"integer.\")\n\n if samples is not None:\n self.run(nsamples=self.nsamples)\n\n def run(self, nsamples, samples=None, append_samples=True, nstart=None):\n \"\"\"\n Execute the ``AKMCS`` learning iterations.\n\n The ``run`` method is the function that performs iterations in the ``AKMCS`` class. If `nsamples` is\n provided when defining the ``AKMCS`` object, the ``run`` method is automatically called. The user may also\n call the ``run`` method directly to generate samples. The ``run`` method of the ``AKMCS`` class can be invoked\n many times.\n\n **Inputs:**\n\n * **nsamples** (`int`):\n Total number of samples to be drawn (including the initial samples).\n\n * **samples** (`ndarray`):\n Samples at which to evaluate the model.\n\n * **nstart** (`int`):\n Number of initial samples, randomly generated using ``LHS`` class.\n\n Either `samples` or `nstart` must be provided.\n\n * **append_samples** (`boolean`)\n Append new samples and model evaluations to the existing samples and model evaluations.\n\n If ``append_samples = False``, all previous samples and the corresponding quantities of interest from their\n model evaluations are deleted.\n\n If ``append_samples = True``, samples and their resulting quantities of interest are appended to the\n existing ones.\n\n **Output/Returns:**\n\n The ``run`` method has no returns, although it creates and/or appends the `samples` attribute of the\n ``AKMCS`` class.\n\n \"\"\"\n\n self.nsamples = nsamples\n self.nstart = nstart\n\n if samples is not None:\n # New samples are appended to existing samples, if append_samples is TRUE\n if append_samples:\n if len(self.samples.shape) == 0:\n self.samples = np.array(samples)\n else:\n self.samples = np.vstack([self.samples, np.array(samples)])\n else:\n self.samples = np.array(samples)\n self.runmodel_object.qoi_list = []\n\n if self.verbose:\n print('UQpy: AKMCS - Evaluating the model at the sample set using RunModel.')\n\n self.runmodel_object.run(samples=samples, append_samples=append_samples)\n else:\n if len(self.samples.shape) == 0:\n if self.nstart is None:\n raise NotImplementedError(\"UQpy: User should provide either 'samples' or 'nstart' value.\")\n if self.verbose:\n print('UQpy: AKMCS - Generating the initial sample set using Latin hypercube sampling.')\n self.samples = LHS(dist_object=self.dist_object, nsamples=self.nstart,\n random_state=self.random_state).samples\n self.runmodel_object.run(samples=self.samples)\n\n if self.verbose:\n print('UQpy: Performing AK-MCS design...')\n\n # If the quantity of interest is a dictionary, convert it to a list\n self.qoi = [None] * len(self.runmodel_object.qoi_list)\n if type(self.runmodel_object.qoi_list[0]) is dict:\n for j in range(len(self.runmodel_object.qoi_list)):\n self.qoi[j] = self.runmodel_object.qoi_list[j][self.qoi_name]\n else:\n self.qoi = self.runmodel_object.qoi_list\n\n # Train the initial Kriging model.\n self.krig_object.fit(self.samples, self.qoi)\n self.krig_model = self.krig_object.predict\n\n # kwargs = {\"n_add\": self.n_add, \"parameters\": self.kwargs, \"samples\": self.samples, \"qoi\": self.qoi,\n # \"dist_object\": self.dist_object}\n\n # ---------------------------------------------\n # Primary loop for learning and adding samples.\n # ---------------------------------------------\n\n for i in range(self.samples.shape[0], self.nsamples):\n # Initialize the population of samples at which to evaluate the learning function and from which to draw\n # in the sampling.\n\n lhs = LHS(dist_object=self.dist_object, nsamples=self.nlearn, random_state=self.random_state)\n self.learning_set = lhs.samples.copy()\n\n # Find all of the points in the population that have not already been integrated into the training set\n rest_pop = np.array([x for x in self.learning_set.tolist() if x not in self.samples.tolist()])\n\n # Apply the learning function to identify the new point to run the model.\n\n # new_point, lf, ind = self.learning_function(self.krig_model, rest_pop, **kwargs)\n new_point, lf, ind = self.learning_function(self.krig_model, rest_pop, n_add=self.n_add,\n parameters=self.kwargs, samples=self.samples, qoi=self.qoi,\n dist_object=self.dist_object)\n\n # Add the new points to the training set and to the sample set.\n self.samples = np.vstack([self.samples, np.atleast_2d(new_point)])\n\n # Run the model at the new points\n self.runmodel_object.run(samples=new_point, append_samples=True)\n\n # If the quantity of interest is a dictionary, convert it to a list\n self.qoi = [None] * len(self.runmodel_object.qoi_list)\n if type(self.runmodel_object.qoi_list[0]) is dict:\n for j in range(len(self.runmodel_object.qoi_list)):\n self.qoi[j] = self.runmodel_object.qoi_list[j][self.qoi_name]\n else:\n self.qoi = self.runmodel_object.qoi_list\n\n # Retrain the surrogate model\n self.krig_object.fit(self.samples, self.qoi, nopt=1)\n self.krig_model = self.krig_object.predict\n\n # Exit the loop, if error criteria is satisfied\n if ind:\n print(\"UQpy: Learning stops at iteration: \", i)\n break\n\n if self.verbose:\n print(\"Iteration:\", i)\n\n if self.verbose:\n print('UQpy: AKMCS complete')\n\n # ------------------\n # LEARNING FUNCTIONS\n # ------------------\n @staticmethod\n def eigf(surr, pop, **kwargs):\n \"\"\"\n Expected Improvement for Global Fit (EIGF) learning function. See [7]_ for a detailed explanation.\n\n\n **Inputs:**\n\n * **surr** (`class` object):\n A Kriging surrogate model, this object must have a ``predict`` method as defined in `krig_object` parameter.\n\n * **pop** (`ndarray`):\n An array of samples defining the learning set at which points the EIGF is evaluated\n\n * **n_add** (`int`):\n Number of samples to be added per iteration.\n\n Default: 1.\n\n * **parameters** (`dictionary`)\n Dictionary containing all necessary parameters and the stopping criterion for the learning function. For\n ``EIGF``, this dictionary is empty as no stopping criterion is specified.\n\n * **samples** (`ndarray`):\n The initial samples at which to evaluate the model.\n\n * **qoi** (`list`):\n A list, which contaains the model evaluations.\n\n * **dist_object** ((list of) ``Distribution`` object(s)):\n List of ``Distribution`` objects corresponding to each random variable.\n\n\n **Output/Returns:**\n\n * **new_samples** (`ndarray`):\n Samples selected for model evaluation.\n\n * **indicator** (`boolean`):\n Indicator for stopping criteria.\n\n `indicator = True` specifies that the stopping criterion has been met and the AKMCS.run method stops.\n\n * **eigf_lf** (`ndarray`)\n EIGF learning function evaluated at the new sample points.\n\n \"\"\"\n samples = kwargs['samples']\n qoi = kwargs['qoi']\n n_add = kwargs['n_add']\n\n g, sig = surr(pop, True)\n\n # Remove the inconsistency in the shape of 'g' and 'sig' array\n g = g.reshape([pop.shape[0], 1])\n sig = sig.reshape([pop.shape[0], 1])\n\n # Evaluation of the learning function\n # First, find the nearest neighbor in the training set for each point in the population.\n from sklearn.neighbors import NearestNeighbors\n knn = NearestNeighbors(n_neighbors=1)\n knn.fit(np.atleast_2d(samples))\n neighbors = knn.kneighbors(np.atleast_2d(pop), return_distance=False)\n\n # noinspection PyTypeChecker\n qoi_array = np.array([qoi[x] for x in np.squeeze(neighbors)])\n\n # Compute the learning function at every point in the population.\n u = np.square(g - qoi_array) + np.square(sig)\n rows = u[:, 0].argsort()[(np.size(g) - n_add):]\n\n indicator = False\n new_samples = pop[rows, :]\n eigf_lf = u[rows, :]\n\n return new_samples, eigf_lf, indicator\n\n @staticmethod\n def u(surr, pop, **kwargs):\n \"\"\"\n U-function for reliability analysis. See [3] for a detailed explanation.\n\n\n **Inputs:**\n\n * **surr** (`class` object):\n A Kriging surrogate model, this object must have a ``predict`` method as defined in `krig_object` parameter.\n\n * **pop** (`ndarray`):\n An array of samples defining the learning set at which points the U-function is evaluated\n\n * **n_add** (`int`):\n Number of samples to be added per iteration.\n\n Default: 1.\n\n * **parameters** (`dictionary`)\n Dictionary containing all necessary parameters and the stopping criterion for the learning function. Here\n this includes the parameter `u_stop`.\n\n * **samples** (`ndarray`):\n The initial samples at which to evaluate the model.\n\n * **qoi** (`list`):\n A list, which contaains the model evaluations.\n\n * **dist_object** ((list of) ``Distribution`` object(s)):\n List of ``Distribution`` objects corresponding to each random variable.\n\n\n **Output/Returns:**\n\n * **new_samples** (`ndarray`):\n Samples selected for model evaluation.\n\n * **indicator** (`boolean`):\n Indicator for stopping criteria.\n\n `indicator = True` specifies that the stopping criterion has been met and the AKMCS.run method stops.\n\n * **u_lf** (`ndarray`)\n U learning function evaluated at the new sample points.\n\n \"\"\"\n n_add = kwargs['n_add']\n parameters = kwargs['parameters']\n\n g, sig = surr(pop, True)\n\n # Remove the inconsistency in the shape of 'g' and 'sig' array\n g = g.reshape([pop.shape[0], 1])\n sig = sig.reshape([pop.shape[0], 1])\n\n u = abs(g) / sig\n rows = u[:, 0].argsort()[:n_add]\n\n indicator = False\n if min(u[:, 0]) >= parameters['u_stop']:\n indicator = True\n\n new_samples = pop[rows, :]\n u_lf = u[rows, 0]\n return new_samples, u_lf, indicator\n\n @staticmethod\n def weighted_u(surr, pop, **kwargs):\n \"\"\"\n Probability Weighted U-function for reliability analysis. See [5]_ for a detailed explanation.\n\n\n **Inputs:**\n\n * **surr** (`class` object):\n A Kriging surrogate model, this object must have a ``predict`` method as defined in `krig_object` parameter.\n\n * **pop** (`ndarray`):\n An array of samples defining the learning set at which points the weighted U-function is evaluated\n\n * **n_add** (`int`):\n Number of samples to be added per iteration.\n\n Default: 1.\n\n * **parameters** (`dictionary`)\n Dictionary containing all necessary parameters and the stopping criterion for the learning function. Here\n this includes the parameter `u_stop`.\n\n * **samples** (`ndarray`):\n The initial samples at which to evaluate the model.\n\n * **qoi** (`list`):\n A list, which contaains the model evaluations.\n\n * **dist_object** ((list of) ``Distribution`` object(s)):\n List of ``Distribution`` objects corresponding to each random variable.\n\n **Output/Returns:**\n\n * **new_samples** (`ndarray`):\n Samples selected for model evaluation.\n\n * **w_lf** (`ndarray`)\n Weighted U learning function evaluated at the new sample points.\n\n * **indicator** (`boolean`):\n Indicator for stopping criteria.\n\n `indicator = True` specifies that the stopping criterion has been met and the AKMCS.run method stops.\n\n \"\"\"\n n_add = kwargs['n_add']\n parameters = kwargs['parameters']\n samples = kwargs['samples']\n dist_object = kwargs['dist_object']\n\n g, sig = surr(pop, True)\n\n # Remove the inconsistency in the shape of 'g' and 'sig' array\n g = g.reshape([pop.shape[0], 1])\n sig = sig.reshape([pop.shape[0], 1])\n\n u = abs(g) / sig\n p1, p2 = np.ones([pop.shape[0], pop.shape[1]]), np.ones([samples.shape[0], pop.shape[1]])\n for j in range(samples.shape[1]):\n p1[:, j] = dist_object[j].pdf(np.atleast_2d(pop[:, j]).T)\n p2[:, j] = dist_object[j].pdf(np.atleast_2d(samples[:, j]).T)\n\n p1 = p1.prod(1).reshape(u.size, 1)\n max_p = max(p2.prod(1))\n u_ = u * ((max_p - p1) / max_p)\n rows = u_[:, 0].argsort()[:n_add]\n\n indicator = False\n if min(u[:, 0]) >= parameters['weighted_u_stop']:\n indicator = True\n\n new_samples = pop[rows, :]\n w_lf = u_[rows, :]\n return new_samples, w_lf, indicator\n\n @staticmethod\n def eff(surr, pop, **kwargs):\n \"\"\"\n Expected Feasibility Function (EFF) for reliability analysis, see [6]_ for a detailed explanation.\n\n\n **Inputs:**\n\n * **surr** (`class` object):\n A Kriging surrogate model, this object must have a ``predict`` method as defined in `krig_object` parameter.\n\n * **pop** (`ndarray`):\n An array of samples defining the learning set at which points the EFF is evaluated\n\n * **n_add** (`int`):\n Number of samples to be added per iteration.\n\n Default: 1.\n\n * **parameters** (`dictionary`)\n Dictionary containing all necessary parameters and the stopping criterion for the learning function. Here\n these include `a`, `epsilon`, and `eff_stop`.\n\n * **samples** (`ndarray`):\n The initial samples at which to evaluate the model.\n\n * **qoi** (`list`):\n A list, which contaains the model evaluations.\n\n * **dist_object** ((list of) ``Distribution`` object(s)):\n List of ``Distribution`` objects corresponding to each random variable.\n\n\n **Output/Returns:**\n\n * **new_samples** (`ndarray`):\n Samples selected for model evaluation.\n\n * **indicator** (`boolean`):\n Indicator for stopping criteria.\n\n `indicator = True` specifies that the stopping criterion has been met and the AKMCS.run method stops.\n\n * **eff_lf** (`ndarray`)\n EFF learning function evaluated at the new sample points.\n\n \"\"\"\n n_add = kwargs['n_add']\n parameters = kwargs['parameters']\n\n g, sig = surr(pop, True)\n\n # Remove the inconsistency in the shape of 'g' and 'sig' array\n g = g.reshape([pop.shape[0], 1])\n sig = sig.reshape([pop.shape[0], 1])\n # Reliability threshold: a_ = 0\n # EGRA method: epsilon = 2*sigma(x)\n a_, ep = parameters['eff_a'], parameters['eff_epsilon']*sig\n t1 = (a_ - g) / sig\n t2 = (a_ - ep - g) / sig\n t3 = (a_ + ep - g) / sig\n eff = (g - a_) * (2 * stats.norm.cdf(t1) - stats.norm.cdf(t2) - stats.norm.cdf(t3))\n eff += -sig * (2 * stats.norm.pdf(t1) - stats.norm.pdf(t2) - stats.norm.pdf(t3))\n eff += ep * (stats.norm.cdf(t3) - stats.norm.cdf(t2))\n rows = eff[:, 0].argsort()[-n_add:]\n\n indicator = False\n if max(eff[:, 0]) <= parameters['eff_stop']:\n indicator = True\n\n new_samples = pop[rows, :]\n eff_lf = eff[rows, :]\n return new_samples, eff_lf, indicator\n\n @staticmethod\n def eif(surr, pop, **kwargs):\n \"\"\"\n Expected Improvement Function (EIF) for Efficient Global Optimization (EFO). See [4]_ for a detailed\n explanation.\n\n\n **Inputs:**\n\n * **surr** (`class` object):\n A Kriging surrogate model, this object must have a ``predict`` method as defined in `krig_object` parameter.\n\n * **pop** (`ndarray`):\n An array of samples defining the learning set at which points the EIF is evaluated\n\n * **n_add** (`int`):\n Number of samples to be added per iteration.\n\n Default: 1.\n\n * **parameters** (`dictionary`)\n Dictionary containing all necessary parameters and the stopping criterion for the learning function. Here\n this includes the parameter `eif_stop`.\n\n * **samples** (`ndarray`):\n The initial samples at which to evaluate the model.\n\n * **qoi** (`list`):\n A list, which contaains the model evaluations.\n\n * **dist_object** ((list of) ``Distribution`` object(s)):\n List of ``Distribution`` objects corresponding to each random variable.\n\n\n **Output/Returns:**\n\n * **new_samples** (`ndarray`):\n Samples selected for model evaluation.\n\n * **indicator** (`boolean`):\n Indicator for stopping criteria.\n\n `indicator = True` specifies that the stopping criterion has been met and the AKMCS.run method stops.\n\n * **eif_lf** (`ndarray`)\n EIF learning function evaluated at the new sample points.\n \"\"\"\n n_add = kwargs['n_add']\n parameters = kwargs['parameters']\n qoi = kwargs['qoi']\n\n g, sig = surr(pop, True)\n\n # Remove the inconsistency in the shape of 'g' and 'sig' array\n g = g.reshape([pop.shape[0], 1])\n sig = sig.reshape([pop.shape[0], 1])\n\n fm = min(qoi)\n eif = (fm - g) * stats.norm.cdf((fm - g) / sig) + sig * stats.norm.pdf((fm - g) / sig)\n rows = eif[:, 0].argsort()[(np.size(g) - n_add):]\n\n indicator = False\n if max(eif[:, 0]) / abs(fm) <= parameters['eif_stop']:\n indicator = True\n\n new_samples = pop[rows, :]\n eif_lf = eif[rows, :]\n return new_samples, eif_lf, indicator","sub_path":"src/UQpy/SampleMethods/AKMCS.py","file_name":"AKMCS.py","file_ext":"py","file_size_in_byte":27006,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"267931472","text":"n = int(input())\na=list(map(int,input().split()))\n#print(a)\nd=[0]*(n)\nd[0]=1\nfor i in range(1,n):\n for j in range(0,i):\n if a[i]= 4:\n return 4*_el\n elif category == LITTLE_STRAIGHT:\n dice.sort()\n if dice == LITTLE_STRAIGHT:\n return 30\n elif category == BIG_STRAIGHT:\n dice.sort()\n if dice == BIG_STRAIGHT:\n return 30\n elif category == CHOICE:\n return sum(dice)\n return 0\n","sub_path":"yacht/yacht.py","file_name":"yacht.py","file_ext":"py","file_size_in_byte":1341,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"637272227","text":"import dearpygui.core as dpg\nimport dearpygui.contexts as cxt\nfrom math import sin, cos\n\ndef _help(message):\n \"\"\" Simple Helper \"\"\"\n dpg.add_same_line()\n helper = dpg.add_text(color=[150, 150, 150], default_value=\"(?)\")\n with cxt.tooltip(parent=helper):\n dpg.add_text(default_value=message)\n\ndef _log(sender, data):\n dpg.log_debug(f\"Sender was {sender}.\", logger=\"Demo Logger\")\n dpg.log_debug(f\"Data was {data}.\", logger=\"Demo Logger\")\n\ndef _config(sender, data):\n\n widget_type = dpg.get_item_info(sender)[\"type\"]\n items = data\n value = dpg.get_value(sender)\n\n if widget_type == \"mvAppItemType::mvCheckbox\":\n keyword = dpg.get_item_configuration(sender)[\"label\"]\n\n elif widget_type == \"mvAppItemType::mvRadioButton\":\n keyword = dpg.get_item_configuration(sender)[\"items\"][value]\n\n if isinstance(data, list):\n for item in items:\n dpg.configure_item(item, **{keyword: value})\n else:\n dpg.configure_item(items, **{keyword: value})\n\ndef _hsv_to_rgb(h, s, v):\n if s == 0.0: return (v, v, v)\n i = int(h*6.) # XXX assume int() truncates!\n f = (h*6.)-i; p,q,t = v*(1.-s), v*(1.-s*f), v*(1.-s*(1.-f)); i%=6\n if i == 0: return (255*v, 255*t, 255*p)\n if i == 1: return (255*q, 255*v, 255*p)\n if i == 2: return (255*p, 255*v, 255*t)\n if i == 3: return (255*p, 255*q, 255*v)\n if i == 4: return (255*t, 255*p, 255*v)\n if i == 5: return (255*v, 255*p, 255*q)","sub_path":"DearPyGui/dearpygui/common.py","file_name":"common.py","file_ext":"py","file_size_in_byte":1455,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"418900301","text":"\"\"\"\nUtilities to deal with IONEX files\nAdopted from https://github.com/UPennEoR/radionopy\n\"\"\"\n\nimport numpy as np\n\n\ndef parse_IONEX_file(IONEX_file):\n '''\n parse data from IONEX file\n Parameters\n ----------\n IONEX_file | str: IONEX filename\n Returns\n -------\n tuple:\n list[str]: IONEX file data without header\n list: RMS IONEX file data without header\n int: number of maps\n float: ionospheric height\n float: first latitude\n float: last latitude\n float: latitude step\n float: first longitude\n float: last longitude\n float: step longitude\n '''\n # Opening and reading the IONEX file into memory\n with open(IONEX_file, 'r') as read_file:\n linestring = read_file.read()\n IONEX_list = linestring.split('\\n')\n # this is the IONEX file in a python list\n\n add = False\n rms_add = False\n base_IONEX_list = []\n RMS_IONEX_list = []\n for file_data in IONEX_list[:-1]:\n if not file_data:\n continue\n if file_data.split()[-2:] == ['RMS', 'MAP']:\n add = False\n rms_add = True\n elif file_data.split()[-2:] == ['IN', 'FILE']:\n number_of_maps = int(float(file_data.split()[0]))\n\n if file_data.split()[0] == 'END' and file_data.split()[2] == 'HEADER':\n add = True\n\n if rms_add:\n RMS_IONEX_list.append(file_data)\n if add:\n base_IONEX_list.append(file_data)\n\n if file_data.split()[-1] == 'DHGT':\n ion_h = float(file_data.split()[0])\n elif file_data.split()[-1] == 'DLAT':\n start_lat, end_lat, step_lat = [\n float(data_item) for data_item in file_data.split()[:3]]\n elif file_data.split()[-1] == 'DLON':\n start_lon, end_lon, step_lon = [\n float(data_item) for data_item in file_data.split()[:3]]\n\n return base_IONEX_list, RMS_IONEX_list, number_of_maps, \\\n ion_h, start_lat, end_lat, step_lat, start_lon, end_lon, step_lon\n\n\ndef get_IONEX_data(filename, verbose=False):\n '''\n Generate information from IONEX file to be used in further calculations\n Parameters\n ----------\n filename | str: name of IONEX file\n verbose | Optional[bool]: whether to print values or not\n Returns\n -------\n tuple:\n dict: TEC values\n dict: RMS TEC values\n tuple:\n float: first latitude\n float: last latitude\n int: amount of latitude points\n float: first longitude\n float: last longitude\n int: amount of longitude points\n int: number of maps\n array: TEC array\n array: RMS TEC array\n float: ionosphere height in meters\n '''\n # Reading and storing only the TEC values of 1 day\n # (13 maps) into a 3D array\n\n # IONEX_list = pull_IONEX_file(filename)\n\n # creating a new array without the header and only\n # with the TEC maps\n base_IONEX_list, RMS_IONEX_list, number_of_maps, ion_h,\\\n start_lat, end_lat, step_lat,\\\n start_lon, end_lon, step_lon = parse_IONEX_file(filename)\n\n # Variables that indicate the number of points in Lat. and Lon.\n points_lat = int(((end_lat - start_lat) / step_lat) + 1)\n points_lon = int(((end_lon - start_lon) / step_lon) + 1)\n if verbose:\n print(start_lat, end_lat, step_lat)\n print(start_lon, end_lon, step_lon)\n print(points_lat, points_lon)\n\n # What are the Lat/Lon coords?\n latitude = np.linspace(start_lat, end_lat, num=points_lat)\n longitude = np.linspace(start_lon, end_lon, num=points_lon)\n\n TEC_list = []\n # Selecting only the TEC values to store in the 3-D array\n for new_IONEX_list in (base_IONEX_list, RMS_IONEX_list):\n # 3D array that will contain TEC values only\n a = np.zeros((number_of_maps, points_lat, points_lon))\n\n counter_maps = 1\n for i in range(len(new_IONEX_list)):\n # Pointing to first map (out of 13 maps)\n # then by changing 'counter_maps' the other\n # maps are selected\n if (new_IONEX_list[i].split()[0] == str(counter_maps) and\n new_IONEX_list[i].split()[-4] == 'START'):\n # pointing the starting latitude\n # then by changing 'counter_lat' we select\n # TEC data at other latitudes within\n # the selected map\n counter_lat = 0\n new_start_lat = float(str(start_lat))\n for item_lat in range(int(points_lat)):\n cond1 = new_IONEX_list[i + 2 + counter_lat].split()[0].split('-')[0] == str(new_start_lat)\n cond2 = ('-' + new_IONEX_list[i + 2 + counter_lat].split()[0].split('-')[1]) == str(new_start_lat)\n if cond1 or cond2:\n # Adding to array 'a' a line of latitude TEC data\n # we account for the TEC values at negative latitudes\n counter_lon = 0\n for count_num in range(3, 8):\n list_index = i + count_num + counter_lat\n tmp_IONEX = new_IONEX_list[list_index].split()\n for new_IONEX_item in tmp_IONEX:\n a[counter_maps - 1, item_lat,\n counter_lon] = new_IONEX_item\n counter_lon = counter_lon + 1\n counter_lat = counter_lat + 6\n new_start_lat = new_start_lat + step_lat\n counter_maps = counter_maps + 1\n\n TEC_list.append({'TEC': np.array(a), 'a': a})\n\n tec_a = TEC_list[0]['a']\n rms_a = TEC_list[1]['a']\n TEC = {'TEC': TEC_list[0]['TEC'], 'lat': latitude, 'lon': longitude}\n RMS_TEC = {'TEC': TEC_list[1]['TEC'], 'lat': latitude, 'lon': longitude}\n\n return TEC, RMS_TEC, (start_lat, step_lat, points_lat,\n start_lon, step_lon, points_lon,\n number_of_maps, tec_a, rms_a, ion_h * 1000.0)\n","sub_path":"ionex.py","file_name":"ionex.py","file_ext":"py","file_size_in_byte":6127,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"272762303","text":"'''\r\nCreated on 2019年3月3日\r\n\r\n@author: rocky\r\n'''\r\nfrom __future__ import print_function\r\nimport pickle\r\nimport os.path\r\nfrom googleapiclient.discovery import build\r\nfrom google_auth_oauthlib.flow import InstalledAppFlow\r\nfrom google.auth.transport.requests import Request\r\nimport requests\r\nimport json\r\nimport base64\r\n\r\n# If modifying these scopes, delete the file token.pickle.\r\nSCOPES = ['https://www.googleapis.com/auth/gmail.readonly']\r\n\r\ndef main():\r\n creds = pickle.load(open('token.pickle', 'rb'))\r\n service = build('gmail', 'v1', credentials=creds)\r\n\r\n response = service.users().messages().list(userId='me', labelIds='INBOX').execute()\r\n cnt = 0\r\n for msg in response[\"messages\"]:\r\n cnt = cnt + 1\r\n print(cnt, msg)\r\n \r\n message = service.users().messages().get(userId='me', id=msg[\"id\"]).execute()\r\n\r\n subject = \"\"\r\n for header in message[\"payload\"][\"headers\"]:\r\n if header[\"name\"] == 'Subject':\r\n subject = header['value']\r\n \r\n snippet = message[\"snippet\"]\r\n \r\n print(\"主旨:\", subject) \r\n if subject.startswith(\"預���取書到館通知\"):\r\n snippet = message[\"snippet\"]\r\n snippet = snippet[snippet.index(\"保留日期\")+5:]\r\n print(snippet)\r\n\r\nif __name__ == '__main__':\r\n main()","sub_path":"mail00/readGmail.py","file_name":"readGmail.py","file_ext":"py","file_size_in_byte":1362,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"481915761","text":"#!/usr/bin/python\n\nimport hashlib\nimport os\nimport os.path\nimport shutil\n\nGENDIR = 'gen'\nNOCACHE_JS = 'nocache.js'\n\ndef cleanGenDir():\n try:\n shutil.rmtree(GENDIR)\n except OSError:\n pass\n os.makedirs(GENDIR)\n\n\ndef makeVersionedJs():\n sourceJsNames = getJsFileNamesInPath('js')\n versionedJsName = concatenateJsIntoFingerprintFile(sourceJsNames);\n return versionedJsName\n\n\ndef getJsFileNamesInPath(startPath):\n fileNames = []\n for root, dirs, files in os.walk(startPath):\n for fname in files:\n if (fname[-3:] == '.js'):\n fileNames.append(os.path.join(root, fname))\n return fileNames\n\n\ndef concatenateJsIntoFingerprintFile(sourcePaths):\n texts = [];\n for p in sourcePaths:\n f = open(p, 'r')\n texts.append(f.read())\n f.close();\n text = '\\n'.join(texts)\n outName = hashlib.sha224(text).hexdigest() + '.js'\n outFile = open(os.path.join(GENDIR, outName), 'w')\n outFile.write(text)\n outFile.close()\n return outName\n\n\ndef makeNocacheJs(versionedJsFilename):\n outFile = open(os.path.join(GENDIR, NOCACHE_JS), 'w')\n versionedJsHttpPath = '/'.join([GENDIR, versionedJsFilename])\n outFile.write(\"\"\"(function() {\n var e = document.createElement('script');\n e.setAttribute('type', 'text/javascript');\n e.setAttribute('src', '\"\"\" + versionedJsHttpPath + \"\"\"');\n document.querySelector('head').appendChild(e);\n})();\"\"\")\n\n\ndef main():\n cleanGenDir()\n versionedJsName = makeVersionedJs()\n makeNocacheJs(versionedJsName)\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"first/make.py","file_name":"make.py","file_ext":"py","file_size_in_byte":1496,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"320705493","text":"##########################################################################################\n#\n# Desc: implementation of filters which may be used in this project \n#\n###########################################################################################\nimport numpy as np\n\nGuassian_Kernel = np.array([0.00598,0.060626,0.241843,0.383103,0.241843,0.060626,0.00598])\n\ndef MediumFilter(image, k_size=3):\n width = k_size // 2\n kernel = np.zeros([k_size, k_size])\n kernel[:, 1:] = image[:k_size, :k_size - 1]\n result = np.array(image)\n for i in range(width, image.shape[0] - width - 1):\n for j in range(width, image.shape[1] - width - 1):\n next_list = np.array([image[i - width:i + width + 1, j + width + 1]]).T\n kernel = np.concatenate((kernel[:, 1:], next_list), axis=1)\n sorted_list = kernel.flatten()\n sorted_list.sort()\n result[i, j] = sorted_list[k_size**2 // 2]\n del sorted_list\n return result\n\ndef LineDetection(img):\n new = np.zeros_like(img)\n I_x = np.zeros_like(new)\n I_y = np.zeros_like(new)\n I_x[1:-1, 1:-1] = (img[1:-1, 2:] - img[1:-1, :-2]) / 2.0\n I_x[1:-1, 1:-1] = (I_x[1:-1, 2:] - I_x[1:-1, :-2]) / 2.0\n for i in range(1, img.shape[0]-1):\n for j in range(1, img.shape[1]-1):\n if (img[i, j-1] < img[i, j]) and (img[i, j] > img[i, j+1]):\n new[i, j] = img[i, j]\n\n I_y[1:-1, 1:-1] = (img[2:, 1:-1] - img[:-2, 1:-1]) / 2.0\n I_y[1:-1, 1:-1] = (I_y[2:, 1:-1] - I_y[:-2, 1:-1]) / 2.0\n for i in range(1, img.shape[0]-1):\n for j in range(1, img.shape[1]-1):\n if (img[i-1, j] < img[i, j]) and (img[i, j] > img[i+1, j]):\n new[i, j] = img[i, j]\n\n return new\n\ndef LinearFilter(image, Kernel):\n k = len(Kernel)\n h, w = image.shape\n newImage = np.zeros_like(image)\n for i in range(0, h):\n for j in range(0, w):\n if(image[i, j] != 0):\n if j < k // 2 or w - j - 1 < k // 2:\n newImage[i, j] = 0\n else:\n count = 0\n for n in range(0, k):\n count += image[i][j + k // 2 - n] * Kernel[n]\n newImage[i][j] = count\n image = newImage\n for j in range(0, w):\n for i in range(0, h):\n if(image[i, j] != 0):\n if i < k // 2 or h - i - 1 < k // 2: \n newImage[i][j] = 0\n else:\n count = 0\n for n in range(0, k):\n count += image[i + k // 2 - n][j] * Kernel[n]\n newImage[i][j] = count\n return newImage\n\ndef filtler2D(image, Kernel):\n k = len(Kernel)\n h, w = image.shape\n newImage = np.zeros_like(image)\n for i in range(0, h):\n for j in range(0, w):\n if(image[i, j] != 0):\n if j < k // 2 or w - j - 1 < k // 2:\n newImage[i, j] = 0\n else:\n count = 0\n for n in range(0, k):\n for m in range(0, k):\n count += image[i][j + k // 2 - n] * Kernel[n, m]\n newImage[i][j] = count\n return newImage\n\ndef GuassianBlur(img):\n return filter2D(img, Guassian_Kernel)","sub_path":"Functions.py","file_name":"Functions.py","file_ext":"py","file_size_in_byte":3316,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"45953718","text":"#!/usr/bin/python\n# -*-coding:utf-8 -*-\nu\"\"\"\n:创建时间: 2020/5/18 23:57\n:作者: 苍之幻灵\n:我的主页: https://cpcgskill.com\n:QQ: 2921251087\n:爱发电: https://afdian.net/@Phantom_of_the_Cang\n:aboutcg: https://www.aboutcg.org/teacher/54335\n:bilibili: https://space.bilibili.com/351598127\nCPMel.cmds 脚本模块\n\"\"\"\nfrom collections import Iterable\n\nfrom collections import Iterable\nimport maya.cmds as mc\n\nfrom ...api import OpenMaya\nfrom ... import core as cmcore\nfrom . import basedata\nfrom . import nodedata\nfrom . import nodetypes\nfrom ...tool import decode\n\nfrom .basedata import *\nfrom .nodedata import *\nfrom .nodetypes import *\nfrom .nodedata import newObject\n\n__all__ = [\"CPMelToCmds\", \"cmdsToCPMel\", \"commandWrap\"]\n\n# __ToTuple__ = {OpenMaya.MVector, OpenMaya.MFloatVector, OpenMaya.MPoint, OpenMaya.MFloatPoint, OpenMaya.MFloatArray,\n# OpenMaya.MDoubleArray, OpenMaya.MIntArray, OpenMaya.MInt64Array}\n\n__ToTuple__ = (list, tuple)\n\n\n# __RecursiveToList__ = {list, tuple, OpenMaya.MPointArray, OpenMaya.MFloatPointArray, OpenMaya.MVectorArray,\n# OpenMaya.MFloatVector}\n\n# CreateObjectType = nodedata.CreateObjectType()\n\n\ndef CPMelToCmds(val):\n u\"\"\"\n 用于将CPMel的对象转化为cmds可以理解的值的函数\n\n :param val:\tCmds模块输入参数列表中的元素\n :return: 转化完成的对象\n \"\"\"\n if isinstance(val, BaseData):\n return val.compile()\n if isinstance(val, CPObject):\n return val.compile()\n # 检查参数是否为需要递归转化为列表的值\n for i in __ToTuple__:\n if isinstance(val, i):\n return tuple((CPMelToCmds(t) for t in val))\n return val\n\n\ndef cmdsToCPMel(val):\n u\"\"\"\n 将cmds的返回值转化为CPMel使用的对象的函数\n\n :param val: Cmds模块返回参数列表中的元素\n :return: 转化完成的对象\n \"\"\"\n if isinstance(val, tuple):\n if len(val) == 3:\n try:\n return basedata.Double3(val)\n except Exception:\n return val\n return val\n if isinstance(val, basestring):\n try:\n return newObject(val)\n except Exception:\n return val\n # return val\n if isinstance(val, list):\n return [cmdsToCPMel(i) for i in val]\n return val\n\n\ndef inCommandWrap(fn):\n u\"\"\"\n 命令包裹函数\n\n :param fn:\n :return:\n \"\"\"\n\n def test(*args, **kwargs):\n args = tuple((CPMelToCmds(i) for i in args))\n kwargs = {i: CPMelToCmds(kwargs[i]) for i in kwargs}\n try:\n return fn(*args, **kwargs)\n except Exception as ex:\n raise cmcore.CPMelError(u\"Command error >> \" + u\"\\n\".join([decode(i) for i in ex.args]))\n\n test.__name__ = fn.__name__\n test.__doc__ = fn.__doc__\n return test\n\n\ndef runCommandWrap(fn):\n u\"\"\"\n 命令返回包裹函数\n\n :param fn:\n :return:\n \"\"\"\n\n def test(*args, **kwargs):\n try:\n out_args = fn(*args, **kwargs)\n except Exception as ex:\n raise cmcore.CPMelError(u\"Command error >> \" + u\"\\n\".join([decode(i) for i in ex.args]))\n if isinstance(out_args, Iterable) and (not isinstance(out_args, basestring)):\n return type(out_args)((cmdsToCPMel(i) for i in out_args))\n return cmdsToCPMel(out_args)\n\n test.__name__ = fn.__name__\n test.__doc__ = fn.__doc__\n return test\n\n\ndef runUiCommandWrap(fn):\n u\"\"\"\n gui命令返回值包裹函数\n :param fn:\n :return: fn\n \"\"\"\n\n def test(*args, **kwargs):\n try:\n out_args = fn(*args, **kwargs)\n except Exception as ex:\n raise cmcore.CPMelError(u\"Command error >> \" + u\"\\n\".join([decode(i) for i in ex.args]))\n if (not 'q' in kwargs) and (not 'query' in kwargs) and isinstance(out_args, basestring):\n return nodedata.UIObject(out_args)\n else:\n return out_args\n\n test.__name__ = fn.__name__\n test.__doc__ = fn.__doc__\n return test\n\n\ndef commandWrap(fn):\n u\"\"\"\n 命令包裹函数\n\n :param fn:\n :return:\n \"\"\"\n\n def test(*args, **kwargs):\n args = tuple((CPMelToCmds(i) for i in args))\n kwargs = {i: CPMelToCmds(kwargs[i]) for i in kwargs}\n try:\n out_args = fn(*args, **kwargs)\n except Exception as ex:\n raise cmcore.CPMelError(u\"Command error >> \" + u\"\\n\".join([decode(i) for i in ex.args]))\n\n if isinstance(out_args, Iterable) and (not isinstance(out_args, basestring)):\n return type(out_args)((cmdsToCPMel(i) for i in out_args))\n return cmdsToCPMel(out_args)\n\n test.__name__ = fn.__name__\n test.__doc__ = fn.__doc__\n return test\n\n\ndef uiCommandWrap(fn):\n u\"\"\"\n gui命令包裹函数\n :param fn:\n :return: fn\n \"\"\"\n\n def test(*args, **kwargs):\n args = tuple((CPMelToCmds(i) for i in args))\n kwargs = {i: CPMelToCmds(kwargs[i]) for i in kwargs}\n try:\n out_args = fn(*args, **kwargs)\n except Exception as ex:\n raise cmcore.CPMelError(u\"Command error >> \" + u\"\\n\".join([decode(i) for i in ex.args]))\n if (not 'q' in kwargs) and (not 'query' in kwargs) and isinstance(out_args, basestring):\n return nodedata.UIObject(out_args)\n else:\n return out_args\n\n test.__name__ = fn.__name__\n test.__doc__ = fn.__doc__\n return test\n\n# def getCmdInfoBasic(command):\n# typemap = {\n# 'string': unicode,\n# 'length': float,\n# 'float': float,\n# 'angle': float,\n# 'int': int,\n# 'unsignedint': int,\n# 'on|off': bool,\n# 'script': callable,\n# 'name': 'PyNode'\n# }\n# flags = {}\n# shortFlags = {}\n# removedFlags = {}\n# try:\n# lines = cmds.help(command).split('\\n')\n# except RuntimeError:\n# pass\n# else:\n# synopsis = lines.pop(0)\n# # certain commands on certain platforms have an empty first line\n# if not synopsis:\n# synopsis = lines.pop(0)\n# #_logger.debug(synopsis)\n# if lines:\n# lines.pop(0) # 'Flags'\n# #_logger.debug(lines)\n#\n# for line in lines:\n# line = line.replace('(Query Arg Mandatory)', '')\n# line = line.replace('(Query Arg Optional)', '')\n# tokens = line.split()\n#\n# try:\n# tokens.remove('(multi-use)')\n# multiuse = True\n# except ValueError:\n# multiuse = False\n# #_logger.debug(tokens)\n# if len(tokens) > 1 and tokens[0].startswith('-'):\n#\n# args = [typemap.get(x.lower(), util.uncapitalize(x)) for x in tokens[2:]]\n# numArgs = len(args)\n#\n# # lags with no args in mel require a boolean val in python\n# if numArgs == 0:\n# args = bool\n# # numArgs will stay at 0, which is the number of mel arguments.\n# # this flag should be renamed to numMelArgs\n# #numArgs = 1\n# elif numArgs == 1:\n# args = args[0]\n#\n# longname = str(tokens[1][1:])\n# shortname = str(tokens[0][1:])\n#\n# if longname in keyword.kwlist:\n# removedFlags[longname] = shortname\n# longname = shortname\n# elif shortname in keyword.kwlist:\n# removedFlags[shortname] = longname\n# shortname = longname\n# # sometimes the longname is empty, so we'll use the shortname for both\n# elif longname == '':\n# longname = shortname\n#\n# flags[longname] = {'longname': longname, 'shortname': shortname, 'args': args, 'numArgs': numArgs, 'docstring': ''}\n# if multiuse:\n# flags[longname].setdefault('modes', []).append('multiuse')\n# shortFlags[shortname] = longname\n#\n# # except:\n# # pass\n# #_logger.debug(\"could not retrieve command info for\", command)\n# res = {'flags': flags, 'shortFlags': shortFlags, 'description': '', 'example': '', 'type': 'other'}\n# if removedFlags:\n# res['removedFlags'] = removedFlags\n# return res\n","sub_path":"test/src/CPMel/cmds/node/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":8523,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"319136587","text":"# this is my wrangle module for the mall customers clustering exercises\n\nimport pandas as pd\nimport numpy as np\nimport os\nfrom env import host, username, password\n\n\n\nimport matplotlib.pyplot as plt\nimport scipy.stats as stats\nimport seaborn as sns\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.preprocessing import MinMaxScaler\n\n# general framework / template\ndef get_connection(db, user=username, host=host, password=password):\n '''\n This function uses my env file to create a connection url to access\n the Codeup database.\n '''\n return f'mysql+pymysql://{user}:{password}@{host}/{db}'\n\ndef get_mallcustomer_data():\n df = pd.read_sql('SELECT * FROM customers;', get_connection('mall_customers'))\n return df.set_index('customer_id')\n\ndef nulls_by_col(df):\n num_missing = df.isnull().sum()\n rows = df.shape[0]\n prcnt_miss = num_missing / rows * 100\n cols_missing = pd.DataFrame({'num_rows_missing': num_missing, 'percent_rows_missing': prcnt_miss})\n return cols_missing\n\ndef nulls_by_row(df):\n num_missing = df.isnull().sum(axis=1)\n prcnt_miss = num_missing / df.shape[1] * 100\n rows_missing = pd.DataFrame({'num_cols_missing': num_missing, 'percent_cols_missing': prcnt_miss})\\\n .reset_index()\\\n .groupby(['num_cols_missing', 'percent_cols_missing']).count()\\\n .rename(index=str, columns={'index': 'num_rows'}).reset_index()\n return rows_missing\n\ndef summarize(df):\n '''\n This function will take in a single argument (pandas DF)\n and output to console various statistics on said DF, including:\n # .head()\n # .info()\n # .describe()\n # value_counts()\n # observe null values\n '''\n print('----------------------------------------------------')\n print('DataFrame Head')\n print(df.head(3))\n print('----------------------------------------------------')\n print('DataFrame Info')\n print(df.info())\n print('----------------------------------------------------')\n print('DataFrame Description')\n print(df.describe())\n num_cols = [col for col in df.columns if df[col].dtype != 'O']\n cat_cols = [col for col in df.columns if col not in num_cols]\n print('----------------------------------------------------')\n print('DataFrame Value Counts: ')\n for col in df.columns:\n if col in cat_cols:\n print(df[col].value_counts())\n print('--------------------------------------------')\n print('')\n else:\n print(df[col].value_counts(bins=10, sort=False))\n print('--------------------------------------------')\n print('')\n print('----------------------------------------------------')\n print('Nulls in DataFrame by Column: ')\n print(nulls_by_col(df))\n print('----------------------------------------------------')\n print('Nulls in DataFrame by Rows: ')\n print(nulls_by_row(df))\n print('----------------------------------------------------')\n df.hist()\n plt.tight_layout()\n return plt.show()\n\ndef get_upper_outliers(s, k=1.5):\n q1, q3 = s.quantile([0.25, 0.75])\n iqr = q3 - q1\n upper_bound = q3 + k * iqr\n return s.apply(lambda x: max([x - upper_bound, 0]))\n\ndef add_upper_outlier_columns(df, k=1.5):\n for col in df.select_dtypes('number'):\n df[col + '_upper_outliers'] = get_upper_outliers(df[col], k)\n return df\n\ndef get_lower_outliers(s, k=1.5):\n q1, q3 = s.quantile([0.25, 0.75])\n iqr = q3 - q1\n lower_bound = q1 - k * iqr\n return s.apply(lambda x:max([x - lower_bound, 0]))\n\ndef add_lower_outlier_columns(df, k=1.5):\n for col in df.select_dtypes('number'):\n df[col + '_lower_outliers'] = get_lower_outliers(df[col], k)\n return df\n\ndef outlier_describe(df):\n outlier_cols = [col for col in df.columns if col.endswith('_outliers')]\n for col in outlier_cols:\n print(col, ': ')\n subset = df[col][df[col] > 0]\n print(subset.describe())\n\ndef drop_outliers(df, col_list, k=1.5):\n '''\n This function takes in a dataframe and removes outliers that are k * the IQR\n '''\n \n for col in col_list:\n\n q_25, q_75 = df[col].quantile([0.25, 0.75])\n q_iqr = q_75 - q_25\n q_upper = q_75 + (k * q_iqr)\n q_lower = q_25 - (k * q_iqr)\n df = df[df[col] > q_lower]\n df = df[df[col] < q_upper]\n# these bottome two lines are only necessary if previous functions have been callled\n# if this function is run BEFORE add_upper/lower, then these columns need to be commented out\n outlier_cols = [col for col in df.columns if col.endswith('_outliers')]\n df = df.drop(columns=outlier_cols)\n \n return df \n\ndef mall_encoder(df, col):\n df = pd.get_dummies(df, columns=col, drop_first=True)\n return df\n \ndef split_data(df):\n '''\n take in a DataFrame and return train, validate, and test DataFrames; stratify on survived.\n return train, validate, test DataFrames.\n '''\n train_validate, test = train_test_split(df, test_size=.2, random_state=1221)\n train, validate = train_test_split(train_validate, \n test_size=.3, \n random_state=1221)\n return train, validate, test\n\ndef min_max_scale(train, validate, test, numeric_cols):\n \"\"\"\n this function takes in 3 dataframes with the same columns,\n a list of numeric column names (because the scaler can only work with numeric columns),\n and fits a min-max scaler to the first dataframe and transforms all\n 3 dataframes using that scaler.\n it returns 3 dataframes with the same column names and scaled values.\n \"\"\"\n # create the scaler object and fit it to X_train (i.e. identify min and max)\n # if copy = false, inplace row normalization happens and avoids a copy (if the input is already a numpy array).\n\n scaler = MinMaxScaler(copy=True).fit(train[numeric_cols])\n\n # scale X_train, X_validate, X_test using the mins and maxes stored in the scaler derived from X_train.\n #\n train_scaled_array = scaler.transform(train[numeric_cols])\n validate_scaled_array = scaler.transform(validate[numeric_cols])\n test_scaled_array = scaler.transform(test[numeric_cols])\n\n # convert arrays to dataframes\n train_scaled = pd.DataFrame(train_scaled_array, columns=numeric_cols).set_index(\n [train.index.values]\n )\n\n validate_scaled = pd.DataFrame(\n validate_scaled_array, columns=numeric_cols\n ).set_index([validate.index.values])\n\n test_scaled = pd.DataFrame(test_scaled_array, columns=numeric_cols).set_index(\n [test.index.values]\n )\n\n return train_scaled, validate_scaled, test_scaled\n\ndef wrangle_mall_data():\n col_list = ['age', 'annual_income', 'spending_score']\n # let's acquire our data...\n df = get_mallcustomer_data()\n # summarize the data\n print(summarize(df))\n # add upper outlier columns\n df = add_upper_outlier_columns(df)\n # add lower outlier columns\n df = add_lower_outlier_columns(df)\n # describe the outliers\n print(outlier_describe(df))\n # drop outliers\n df = drop_outliers(df, col_list)\n # split the data\n train, validate, test = split_data(df)\n # drop missing values from train\n train = train.dropna()\n # scale the data\n train_scaled, \\\n validate_scaled, \\\n test_scaled = min_max_scale(train, validate, test, col_list)\n print(f' train shape: {train.shape}')\n print(f' validate shape: {validate.shape}')\n print(f' test shape: {test.shape}')\n print(f' train_scaled shape: {train_scaled.shape}')\n print(f'validate_scaled shape: {validate_scaled.shape}')\n print(f' test_scaled shape: {test_scaled.shape}')","sub_path":"wrangle_mall.py","file_name":"wrangle_mall.py","file_ext":"py","file_size_in_byte":7727,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"514104026","text":"class Solution:\n # @return an integer\n def atoi(self, s):\n symbols = {'+', '-', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9'}\n numbers = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9'}\n INT_MAX = 2147483647\n INT_MIN = -2147483648\n\n def get_char(s):\n s_len = len(s)\n if len(s) > 0:\n c = s[0]\n s = s[1:]\n return c, s, s_len\n else:\n return None, None, 0\n\n is_negative = False\n sign_parsed = False\n\n # Strip string first\n s = s.strip()\n\n # Get first char\n first_char, s, s_len = get_char(s)\n\n if first_char not in symbols:\n return 0\n\n res = 0\n c = first_char\n while c != None:\n if c in numbers:\n res += int(c) * (10 ** (s_len - 1))\n elif sign_parsed == False and c == '-':\n is_negative = True\n sign_parsed = True\n elif sign_parsed == False and c == '+':\n is_negative = False\n sign_parsed = True\n else:\n res /= 10 ** s_len\n break\n c, s, s_len = get_char(s)\n\n if is_negative:\n res = -res\n\n if res > INT_MAX:\n return INT_MAX\n elif res < INT_MIN:\n return INT_MIN\n\n return res\n\n","sub_path":"atoi.py","file_name":"atoi.py","file_ext":"py","file_size_in_byte":1412,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"375512111","text":"import numpy as np\nimport os\n\nfrom utils import *\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom keras.preprocessing import image\nfrom model import Deeplabv3\nimport keras\nfrom tensorflow.python.keras.layers import *\nfrom tensorflow.python.keras.layers.convolutional import Deconvolution2D\nfrom numpy import random\nfrom random import seed, sample, randrange\n\nfrom tensorflow.python.keras.callbacks import ReduceLROnPlateau, ModelCheckpoint, CSVLogger\nfrom tensorflow.python.keras.optimizers import Adam\n\n\n######## Train Model on ISIC\nEPOCHS = 10\nBS = 2\nrunnr = randrange(1, 10000)\nprint(\"RUNNUMBER\", runnr)\n\ndeeplab_model = Deeplabv3(input_shape=(256, 256, 3), classes=2)\ntest_percentage = 0.1\n\nfile_list = recursive_glob(\n \"/home/bijan/Workspace/Python/keras-deeplab-v3-plus/data/ISIC2018_Task1-2_Training_Input\",\n \".jpg\"\n)\n\nseed(123)\ntest_indices = sample(range(0, 2594), int(2594 * test_percentage))\n\ntest = [sorted(file_list)[k] for k in test_indices]\ntrain = sorted([k for k in file_list if k not in test])\n\nfile_list = recursive_glob(\n \"/home/bijan/Workspace/Python/keras-deeplab-v3-plus/data/ISIC2018_Task1_Training_GroundTruth/\",\n \".png\"\n)\n\ntest_labels = [sorted(file_list)[k] for k in test_indices]\ntrain_labels = sorted(list(set(file_list) - set(test_labels)))\n\n\naug = ImageDataGenerator(zoom_range=0.15,\n width_shift_range=0.2,\n height_shift_range=0.2,\n shear_range=0.15,\n horizontal_flip=True,\n fill_mode=\"nearest\")\n\ncsv_logger = CSVLogger('./runs/'+str(runnr)+'_log.csv', append=True, separator=';')\nreduce_lr = ReduceLROnPlateau(monitor='val_loss', factor=0.2, patience=3, min_lr=0.001)\ncheckpointer = ModelCheckpoint(filepath='./runs/'+str(runnr)+'_model.hdf5',\n verbose=1,\n save_weights_only=True,\n save_best_only=True)\n\n\ndeeplab_model.compile(optimizer=Adam(lr=0.0001), loss=keras.losses.binary_crossentropy, metrics=['binary_accuracy'])\n\nH = deeplab_model.fit_generator(isic_generator(train, train_labels, batch_size=BS),\n\t validation_data=isic_generator(test, test_labels, batch_size=BS),\n validation_steps=len(test_labels),\n steps_per_epoch=len(train) // BS,\n\t epochs=EPOCHS,\n max_queue_size=3,\n callbacks=[checkpointer, csv_logger, reduce_lr])\n\nmodel_json = deeplab_model.to_json()\nwith open(\"./runs/\"+str(runnr)+\"_model.json\", \"w\") as json_file:\n json_file.write(model_json)\nprint(H.history)\n","sub_path":"train_isic18.py","file_name":"train_isic18.py","file_ext":"py","file_size_in_byte":2731,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"476245623","text":"from __future__ import print_function\nfrom threading import Semaphore, Lock, Thread\nfrom random import random, randint\nfrom time import sleep\nimport sys\nimport random\nfrom timeit import Timer\n\nclass Lightswitch:\n def __init__(self):\n self.mutex = Lock()\n self.count = 0\n\n def lock(self, sem):\n with self.mutex:\n self.count += 1\n if self.count == 1:\n sem.acquire()\n\n def unlock(self, sem):\n with self.mutex:\n self.count -= 1\n if self.count == 0:\n sem.release()\n\nclass BaboonCrossing:\n def __init__(self,max_in_rope):\n self.rope = Lock()\n self.turnstile = Lock()\n self.switches = [Lightswitch(), Lightswitch()]\n self.multiplex = Semaphore(max_in_rope)\n\n def act_as_baboon(self,my_id, init_side, max_crossings):\n side = init_side\n crossings_cnt = max_crossings\n while True:\n# with self.turnstile:\n self.switches[side].lock(self.rope)\n with self.multiplex:\n print('baboon', my_id, 'crossing from', side_names[side], 'cnt',crossings_cnt )\n sleep(self.generate_random_int(my_id,15)) # simulate crossing\n crossings_cnt -=1\n self.switches[side].unlock(self.rope)\n side = 1 - side\n if crossings_cnt == 0:\n break\n sleep(self.generate_random_int(my_id,3))\n\n def generate_random_int (self,seed,factor):\n rng = random.Random()\n rng.seed(seed)\n # random_val = rng.randint(1,10)\n random_val = rng.random()\n # print ('random',random_val)\n return random_val*factor\n\n def simulate(self,num_baboons, tot_crossings):\n bthreads = []\n for i in range(num_baboons):\n bid, bside = i, randint(0, 1)\n bthreads.append(Thread(target=self.act_as_baboon, args=[bid, bside, tot_crossings]))\n for t in bthreads:\n t.start()\n for t in bthreads:\n t.join()\n\nside_names = ['west', 'east']\nROPE_MAX = 3\nNUM_BABOONS = 20\nMAX_NUM_OF_CROSSINGS = 2\n\ndef totime():\n bsim = BaboonCrossing(ROPE_MAX)\n bsim.simulate(NUM_BABOONS, MAX_NUM_OF_CROSSINGS)\n print('Simulation Over')\n\nif __name__ == '__main__':\n timer = Timer(totime)\n print(\"Average Time for 10 test: {:0.3f}s\".format(timer.timeit(10)/10))\n print('Test Repeat(5,1):',timer.repeat(5, 1))\n","sub_path":"det_baboons_improved.py","file_name":"det_baboons_improved.py","file_ext":"py","file_size_in_byte":2454,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"57305258","text":"import numpy as np\r\nimport pandas as pd\r\nimport sys\r\n\r\nin_to_reg_filename = r'in_to_reg.rpt'\r\nreg_to_out_filename = r'reg_to_out.rpt'\r\nreg_to_reg_filename = r'reg_to_reg.rpt'\r\n\r\npattern1 = r'End-point'\r\npattern2 = r'Start-point'\r\npattern3 = r'instances_hier'\r\nfeature_list = ['Rin', 'Rout', 'RRin', 'RRout', 'loop', 'length', 'hier_level', 'size']\r\n\r\n\r\ndef get_name(line, name_lists):\r\n lptr = line.index(r':') + 2\r\n if '[' in line:\r\n rptr = len(line) - 1\r\n while line[rptr] != r'[':\r\n rptr -= 1\r\n elif r'/' in line:\r\n rptr = len(line) - 1\r\n while line[rptr] != r'/':\r\n rptr -= 1\r\n else:\r\n rptr = len(line)\r\n signal_name = line[lptr:rptr]\r\n if signal_name not in name_lists:\r\n print('Unknown reg name: %s, please check!' % signal_name)\r\n return signal_name\r\n\r\n\r\nif __name__ == '__main__':\r\n if len(sys.argv) < 2:\r\n csv_filename = 'res_lcd.csv'\r\n else:\r\n csv_filename = sys.argv[1]\r\n\r\n df = pd.read_csv(csv_filename)\r\n df = df[df['type'].isin([3])]\r\n df = df.reset_index()\r\n for i in range(len(df.loc[:, 'signal_name'])):\r\n temp = df.loc[i, 'signal_name'].split('/')\r\n temp2 = []\r\n for j, item in enumerate(temp):\r\n if item == pattern3:\r\n temp2.append(temp[j + 1])\r\n temp2.append(temp[-1])\r\n df.loc[i, 'signal_name'] = '/'.join(temp2)\r\n\r\n df = df.set_index(['signal_name'])\r\n df = df.reindex(columns=feature_list, fill_value=0)\r\n signal_names = np.array(df.index)\r\n\r\n for line in open(in_to_reg_filename, 'r'):\r\n if pattern1 in line:\r\n signal_name = get_name(line, signal_names)\r\n df.loc[signal_name, 'Rin'] += 1\r\n\r\n for line in open(reg_to_out_filename, 'r'):\r\n if pattern2 in line:\r\n signal_name = get_name(line, signal_names)\r\n df.loc[signal_name, 'Rout'] += 1\r\n\r\n reg_to_reg_file = []\r\n for line in open(reg_to_reg_filename, 'r'):\r\n reg_to_reg_file.append(line)\r\n\r\n for index, line in enumerate(reg_to_reg_file):\r\n if pattern2 in line:\r\n signal_name1 = get_name(line, signal_names)\r\n signal_name2 = get_name(reg_to_reg_file[index + 1], signal_names)\r\n df.loc[signal_name1, 'RRout'] += 1\r\n df.loc[signal_name2, 'RRin'] += 1\r\n if signal_name1 == signal_name2:\r\n df.loc[signal_name1, 'loop'] = 1\r\n\r\n pos = csv_filename.index('.')\r\n output_filename = csv_filename[:pos] + '_reg' + csv_filename[pos:]\r\n df.to_csv(output_filename)\r\n print('Data transfer finished!')\r\n\r\n","sub_path":"designs/rocket/data_transfer2.py","file_name":"data_transfer2.py","file_ext":"py","file_size_in_byte":2622,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"62210735","text":"import re\nfrom django.conf import settings\nfrom django.http import HttpResponseRedirect\nfrom django.contrib.auth.views import auth_login\nfrom django.shortcuts import render_to_response\nfrom django.template.context import RequestContext\n\nfrom cms.views import details\n\nfrom empcom.util.general import undecorate\nfrom wdyt.auth.forms import WdytAuthenticationForm\n\n\n# Extract the decorated details cms function for use without it's wrapper \nprepare_cms_page = undecorate(details)\n\ndef show_cms_page(request, url, additional_context):\n (template_name, context) = prepare_cms_page(request, slug=url)\n for key, val in additional_context.items():\n context[key] = val\n\n return render_to_response(template_name, context, context_instance=RequestContext(request))\n\n\ndef handle_login(request):\n context = {}\n form = WdytAuthenticationForm(request)\n\n if request.method == \"POST\":\n form = WdytAuthenticationForm(data=request.POST)\n context['next'] = request.REQUEST.get('next', '')\n if form.is_valid():\n return _login_and_redirect(request, context['next'], form)\n else:\n context['next'] = request.path_info\n\n context['form'] = form\n request.session.set_test_cookie()\n return show_cms_page(request, '/home/login-intervention', context)\n\ndef _login_and_redirect(request, redirect_to, login_form):\n # Light security check -- make sure redirect_to isn't garbage.\n if not redirect_to or ' ' in redirect_to:\n redirect_to = settings.LOGIN_REDIRECT_URL\n\n # Heavier security check -- redirects to http://example.com should\n # not be allowed, but things like /view/?param=http://example.com\n # should be allowed. This regex checks if there is a '//' *before* a\n # question mark.\n elif '//' in redirect_to and re.match(r'[^\\?]*//', redirect_to):\n redirect_to = settings.LOGIN_REDIRECT_URL\n # Okay, security checks complete. Log the user in.\n auth_login(request, login_form.get_user())\n\n if request.session.test_cookie_worked():\n request.session.delete_test_cookie()\n\n return HttpResponseRedirect(redirect_to)\n\n\n\n","sub_path":"apps/efocms/redirect.py","file_name":"redirect.py","file_ext":"py","file_size_in_byte":2119,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"630235099","text":"#Shane's Button\n#User can select what day of the week it is and the button will tell you what percent brainer we're at\n\nimport tkinter as tk\nfrom tkinter import W, E\n\n#weekList\nweekList = [\"Monday\", \"Tuesday\", \"Wednesday\", \"Thursday\", \"Friday\"]\n\n#definitions\ndef run():\n\tday = master.listbox.get(tk.ACTIVE)\n\tif day == weekList[0]:#Monday\n\t\tbrainer = 100\n\tif day == weekList[1]:#Tuesday\n\t\tbrainer = 75\n\tif day == weekList[2]:#Wednesday\n\t\tbrainer = 50\n\tif day == weekList[3]:#Thursday\n\t\tbrainer = 25\n\tif day == weekList[4]:#Friday\n\t\tbrainer = 0\n\t\n\tbeerA = beer.get()\n\tif beerA == 0:\n\t\tbeerer = \"No Beer was had.\"\n\tif beerA ==1:\n\t\tbeerer = \"Beer was had!!\"\n\n\thockeyA = hockey.get()\n\tif hockeyA == 0:\n\t\thockeyer = \"No hockey was played.\"\n\tif hockeyA ==1:\n\t\thockeyer = \"Hockey was played!!\"\n\ttext.insert(tk.INSERT, \"We are at {}% Brainer! {} {}\\n\".format(brainer, beerer, hockeyer))\n\n#GUI\nmaster = tk.Tk()\nmaster.title(\"Shaner's Button\")\nmaster.configure(background = '#ccf2ff')\n\n#week day list\ntk.Label(master, text=\"Select the day of the week and hit run:\", anchor=E, background = '#ccf2ff').grid(row=0, column=0)\nmaster.listbox = tk.Listbox(master)\nmaster.listbox.grid(row=2, column=0, sticky='NS')\nfor item in weekList: #adding run names to the list in the main window\n\tmaster.listbox.insert(tk.END, item)\n\nbeer = tk.IntVar()\ntk.Checkbutton(master, text=\"Beer\", variable=beer).grid(row=1, column=0, sticky=W)\nhockey = tk.IntVar()\ntk.Checkbutton(master, text=\"Hockey\", variable=hockey).grid(row=1, column=1, sticky=W)\n\ntext = tk.Text(master)\ntext.grid(row=2, column=3)\ntext.insert(tk.INSERT, \">>>\")\n\ntk.Button(master, text='Run', command=run).grid(row=0, column=1, sticky=W, pady=4)\ntk.Button(master, text='Quit', command=master.quit).grid(row=3, column=4, sticky=W, pady=4)\n\ntk.mainloop( )\n","sub_path":"HelloVisualStudioPython/ShanersButton.py","file_name":"ShanersButton.py","file_ext":"py","file_size_in_byte":1789,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"200162534","text":"#!/usr/bin/env python\n# coding: utf-8\n# Libraries\nimport pandas as pd\nimport matplotlib.pyplot as plt\n\nfrom Josie17_Functions import Calc_average_profile, Calc_average_profile_Pair\nfrom Josie17_Functions import Plot_compare_4profile_plots_updated\nfrom Josie17_Functions import Calc_RDif, Calc_ADif, Plot_compare_4profile_plots_pair\nfrom Josie17_Functions import Plot_6profile_plots\nfrom rdif_calibration_functions import correctedPlot_PerCategory, correctedPlot_AllCategory, correct_Rdif, plot_2difPlots\n\n# df = pd.read_csv(\"/home/poyraden/Josie17/Files/Josie17_DataAll.csv\")\n\n# df = pd.read_csv(\"/home/poyraden/Josie17/Files/Josie1718_Data.csv\")\ndf = pd.read_csv(\"/home/poyraden/Josie17/Files/Josie1718_datacorrectedPO3_timecut18.csv\", low_memory=False)\n\n\nresol = 200\n# dimension for Rdif: ymax/resolution\n\nytitle = 'Pressure (hPa)'\nytitlet = 'Time (sec.)'\n\n# remove the bad simulations and use dfcleaned\n# here there are two cleaning one from Roeland which has Sim 179 and team 4, Sim 172 and Team 1 and the other is just 175\n# second new cleaning 01/02 is to remove profiles that have a and b:these are 171-a, 172-b, 180-b, 185-b\n\n# keep all profiles df = df.drop(df[((df.Sim == 171) | (df.Sim == 172) | (df.Sim == 180) | (df.Sim == 185))].index) # for b and c profiles\ndf = df.drop(df[(df.Sim == 179) & (df.Team == 4)].index)\ndf = df.drop(df[(df.Sim == 172) & (df.Team == 1)].index)\ndf = df[(df.PO3 > 0) & (df.PO3_OPM > 0)]\n# df = df.drop(df[(df.Tsim > 7000)].index)\n\ndf = df.drop(df[(df.Sim == 178) & (df.Team == 3)].index)\ndfcleaned = df.drop(df[(df.Sim == 175)].index)\n\n###############################################\n# Filters for Sonde, Solution, Buffer selection\n# 1, 0.1 ENSCI vs SPC\nfiltEN = dfcleaned.ENSCI == 1\nfiltSP = dfcleaned.ENSCI == 0\n\nfiltS10 = dfcleaned.Sol == 1\nfiltS05 = dfcleaned.Sol == 0.5\nfiltS20 = dfcleaned.Sol == 2\n\nfiltB01 = dfcleaned.Buf == 0.1\nfiltB10 = dfcleaned.Buf == 1.0\nfiltB05 = dfcleaned.Buf == 0.5\n\nfilterEN0505 = (filtEN & filtS05 & filtB05)\nfilterEN1001 = (filtEN & filtS10 & filtB01)\nfilterEN2001 = (filtEN & filtS20 & filtB01)\nprofEN0505 = dfcleaned.loc[filterEN0505]\nprofEN1001 = dfcleaned.loc[filterEN1001]\nprofEN2001 = dfcleaned.loc[filterEN2001]\nprofEN0505_nodup = profEN0505.drop_duplicates(['Sim', 'Team'])\nprofEN1001_nodup = profEN1001.drop_duplicates(['Sim', 'Team'])\nprofEN2001_nodup = profEN2001.drop_duplicates(['Sim', 'Team'])\ntotO3_EN0505 = profEN0505_nodup.frac.mean()\ntotO3_EN1001 = profEN1001_nodup.frac.mean()\ntotO3_EN2001 = profEN2001_nodup.frac.mean()\n\n\nfilterSP1010 = (filtSP & filtS10 & filtB10)\nfilterSP1001 = (filtSP & filtS10 & filtB01)\nfilterSP2001 = (filtSP & filtS20 & filtB01)\n\nprofSP1010 = dfcleaned.loc[filterSP1010]\nprofSP1001 = dfcleaned.loc[filterSP1001]\nprofSP2001 = dfcleaned.loc[filterSP2001]\nprofSP1010_nodup = profSP1010.drop_duplicates(['Sim', 'Team'])\nprofSP1001_nodup = profSP1001.drop_duplicates(['Sim', 'Team'])\nprofSP2001_nodup = profSP2001.drop_duplicates(['Sim', 'Team'])\ntotO3_SP1010 = profSP1010_nodup.frac.mean()\ntotO3_SP1001 = profSP1001_nodup.frac.mean()\ntotO3_SP2001 = profSP2001_nodup.frac.mean()\n\n\navgprofEN0505_X, avgprofEN0505_Xerr, Y1 = Calc_average_profile_Pair(profEN0505, 'ADif_PO3S')\navgprofEN1001_X, avgprofEN1001_Xerr, Y1 = Calc_average_profile_Pair(profEN1001, 'ADif_PO3S')\navgprofEN2001_X, avgprofEN2001_Xerr, Y1 = Calc_average_profile_Pair(profEN2001, 'ADif_PO3S')\n\navgprofSP1010_X, avgprofSP1010_Xerr, Y1 = Calc_average_profile_Pair(profSP1010, 'ADif_PO3S')\navgprofSP1001_X, avgprofSP1001_Xerr, Y1 = Calc_average_profile_Pair(profSP1001, 'ADif_PO3S')\navgprofSP2001_X, avgprofSP2001_Xerr, Y1 = Calc_average_profile_Pair(profSP2001, 'ADif_PO3S')\n\n\navgprofEN0505_O3S_X, avgprofEN0505_O3S_Xerr, Y = Calc_average_profile_Pair(profEN0505, 'PO3')\navgprofEN1001_O3S_X, avgprofEN1001_O3S_Xerr, Y = Calc_average_profile_Pair(profEN1001, 'PO3')\navgprofEN2001_O3S_X, avgprofEN2001_O3S_Xerr, Y = Calc_average_profile_Pair(profEN2001, 'PO3')\n\navgprofSP1010_O3S_X, avgprofSP1010_O3S_Xerr, Y = Calc_average_profile_Pair(profSP1010, 'PO3')\navgprofSP1001_O3S_X, avgprofSP1001_O3S_Xerr, Y = Calc_average_profile_Pair(profSP1001, 'PO3')\navgprofSP2001_O3S_X, avgprofSP2001_O3S_Xerr, Y = Calc_average_profile_Pair(profSP2001, 'PO3')\n\navgprofEN0505_OPM_X, avgprofEN0505_OPM_Xerr, Y = Calc_average_profile_Pair(profEN0505, 'PO3_OPM')\navgprofEN1001_OPM_X, avgprofEN1001_OPM_Xerr, Y = Calc_average_profile_Pair(profEN1001, 'PO3_OPM')\navgprofEN2001_OPM_X, avgprofEN2001_OPM_Xerr, Y = Calc_average_profile_Pair(profEN2001, 'PO3_OPM')\n\navgprofSP1010_OPM_X, avgprofSP1010_OPM_Xerr, Y = Calc_average_profile_Pair(profSP1010, 'PO3_OPM')\navgprofSP1001_OPM_X, avgprofSP1001_OPM_Xerr, Y = Calc_average_profile_Pair(profSP1001, 'PO3_OPM')\navgprofSP2001_OPM_X, avgprofSP2001_OPM_Xerr, Y = Calc_average_profile_Pair(profSP2001, 'PO3_OPM')\n\ndimension = len(Y)\n\n# piece of code special for Relative difference calculation\nrEN0505, rENerr0505 = Calc_RDif(avgprofEN0505_O3S_X, avgprofEN0505_OPM_X, avgprofEN0505_Xerr, dimension)\nrEN1001, rENerr1001 = Calc_RDif(avgprofEN1001_O3S_X, avgprofEN1001_OPM_X, avgprofEN1001_Xerr, dimension)\nrEN2001, rENerr2001 = Calc_RDif(avgprofEN2001_O3S_X, avgprofEN2001_OPM_X, avgprofEN2001_Xerr, dimension)\n\nrSP2001, rSPerr2001 = Calc_RDif(avgprofSP2001_O3S_X, avgprofSP2001_OPM_X, avgprofSP2001_Xerr, dimension)\nrSP1010, rSPerr1010 = Calc_RDif(avgprofSP1010_O3S_X, avgprofSP1010_OPM_X, avgprofSP1010_Xerr, dimension)\nrSP1001, rSPerr1001 = Calc_RDif(avgprofSP1001_O3S_X, avgprofSP1001_OPM_X, avgprofSP1001_Xerr, dimension)\n\nPlot_compare_4profile_plots_pair(\n avgprofEN0505_X, avgprofEN0505_Xerr, avgprofEN1001_X, avgprofEN1001_Xerr, avgprofSP1010_X, avgprofSP1010_Xerr,\n avgprofSP1001_X, avgprofSP1001_Xerr, Y, [-3, 3], ' ', 'Sonde - OPM Difference (mPa)', ytitle, 'EN 0.5%-0.5B',\n 'EN 1.0%-0.1B', 'SP 1.0%-1.0B', 'SP 1.0%-0.1B', totO3_EN0505, totO3_EN1001, totO3_SP1010, totO3_SP1001,\n profEN0505.drop_duplicates(['Sim', 'Team']), profEN1001.drop_duplicates(['Sim', 'Team']), profSP1010_nodup,\n profSP1001_nodup, 'ADif_Pair_calibration_allprofiles')\nPlot_compare_4profile_plots_pair(\n rEN0505, rENerr0505, rEN1001, rENerr1001, rSP1010, rSPerr1010, rSP1001, rSPerr1001, Y, [-40, 40], ' ',\n 'Sonde - OPM Difference (%)',\n ytitle, 'EN 0.5%-0.5B', 'EN 1.0%-0.1B', 'SP 1.0%-1.0B', 'SP 1.0%-0.1B', totO3_EN0505, totO3_EN1001, totO3_SP1010,\n totO3_SP1001,\n profEN0505.drop_duplicates(['Sim', 'Team']), profEN1001.drop_duplicates(['Sim', 'Team']), profSP1010_nodup,\n profSP1001_nodup, 'RDif_Pair_calibration_allprofiles')\n\n# Plot_6profile_plots(\n# avgprofEN0505_X, avgprofEN0505_Xerr, avgprofEN1001_X, avgprofEN1001_Xerr, avgprofEN2001_X, avgprofEN2001_Xerr,\n# avgprofSP1010_X, avgprofSP1010_Xerr, avgprofSP1001_X, avgprofSP1001_Xerr, avgprofSP2001_X, avgprofSP2001_Xerr,\n# Y, [-3, 3], ' ', 'Sonde - OPM Difference (mPa)', ytitle, 'EN 0.5%-0.5B','EN 1.0%-0.1B', 'EN 2.0%-0.1B',\n# 'SP 1.0%-1.0B', 'SP 1.0%-0.1B', 'SP 2.0%-0.1B', totO3_EN0505, totO3_EN1001, totO3_EN2001, totO3_SP1010, totO3_SP1001,\n# totO3_SP2001,\n# profEN0505.drop_duplicates(['Sim', 'Team']), profEN1001.drop_duplicates(['Sim', 'Team']), profEN2001_nodup,\n# profSP1010_nodup, profSP1001_nodup, profSP2001_nodup, 'ADif_Pair_calibration_allprofiles')\n# Plot_6profile_plots(\n# rEN0505, rENerr0505, rEN1001, rENerr1001, rEN2001, rENerr2001, rSP1010, rSPerr1010, rSP1001, rSPerr1001, rSP2001,\n# rSPerr2001, Y, [-40, 40], ' ', 'Sonde - OPM Difference (%)', ytitle, 'EN 0.5%-0.5B', 'EN 1.0%-0.1B', 'EN 2.0%-0.1B',\n# 'SP 1.0%-1.0B', 'SP 1.0%-0.1B', 'SP 2.0%-0.1B', totO3_EN0505, totO3_EN1001, totO3_EN2001, totO3_SP1010,\n# totO3_SP1001, totO3_SP2001, profEN0505.drop_duplicates(['Sim', 'Team']), profEN1001.drop_duplicates(['Sim', 'Team']),\n# profEN2001_nodup, profSP1010_nodup, profSP1001_nodup, profSP2001_nodup,'RDif_Pair_calibration_allprofiles')\n\n\n# # now make plots asaf of time to see the behaviour\n#\n# avgprofTimeEN0505_X, avgprofTimeEN0505_Xerr, Yt1 = Calc_average_profile(profEN0505, resol, 'ADif_PO3S')\n# avgprofTimeEN1001_X, avgprofTimeEN1001_Xerr, Yt1 = Calc_average_profile(profEN1001, resol, 'ADif_PO3S')\n# avgprofTimeSP1010_X, avgprofTimeSP1010_Xerr, Yt1 = Calc_average_profile(profSP1010, resol, 'ADif_PO3S')\n# avgprofTimeSP1001_X, avgprofTimeSP1001_Xerr, Yt1 = Calc_average_profile(profSP1001, resol, 'ADif_PO3S')\n#\n# avgprofTimeEN0505_O3S_X, avgprofTimeEN0505_O3S_Xerr, Yt = Calc_average_profile(profEN0505, resol, 'PO3')\n# avgprofTimeEN1001_O3S_X, avgprofTimeEN1001_O3S_Xerr, Yt = Calc_average_profile(profEN1001, resol, 'PO3')\n# avgprofTimeSP1010_O3S_X, avgprofTimeSP1010_O3S_Xerr, Yt = Calc_average_profile(profSP1010, resol, 'PO3')\n# avgprofTimeSP1001_O3S_X, avgprofTimeSP1001_O3S_Xerr, Yt = Calc_average_profile(profSP1001, resol, 'PO3')\n#\n# avgprofTimeEN0505_OPM_X, avgprofTimeEN0505_OPM_Xerr, Yt = Calc_average_profile(profEN0505, resol, 'PO3_OPM')\n# avgprofTimeEN1001_OPM_X, avgprofTimeEN1001_OPM_Xerr, Yt = Calc_average_profile(profEN1001, resol, 'PO3_OPM')\n# avgprofTimeSP1010_OPM_X, avgprofTimeSP1010_OPM_Xerr, Yt = Calc_average_profile(profSP1010, resol, 'PO3_OPM')\n# avgprofTimeSP1001_OPM_X, avgprofTimeSP1001_OPM_Xerr, Yt = Calc_average_profile(profSP1001, resol, 'PO3_OPM')\n#\n# dimension = len(Yt)\n#\n# # resol = 200\n# # dimension = int(7000/resol)\n#\n#\n# # piece of code special for Relative difference calculation\n# rTimeEN0505, rTimeENerr0505 = Calc_RDif(avgprofTimeEN0505_O3S_X, avgprofTimeEN0505_OPM_X, avgprofTimeEN0505_Xerr,\n# dimension)\n# rTimeEN1001, rTimeENerr1001 = Calc_RDif(avgprofTimeEN1001_O3S_X, avgprofTimeEN1001_OPM_X, avgprofTimeEN1001_Xerr,\n# dimension)\n#\n# rTimeSP1001, rTimeSPerr1001 = Calc_RDif(avgprofTimeSP1001_O3S_X, avgprofTimeSP1001_OPM_X, avgprofTimeSP1001_Xerr,\n# dimension)\n# rTimeSP1010, rTimeSPerr1010 = Calc_RDif(avgprofTimeSP1010_O3S_X, avgprofTimeSP1010_OPM_X, avgprofTimeSP1010_Xerr,\n# dimension)\n#\n# Plot_compare_4profile_plots_updated(\n# avgprofTimeEN0505_X, avgprofTimeEN0505_Xerr, avgprofTimeEN1001_X, avgprofTimeEN1001_Xerr, avgprofTimeSP1010_X,\n# avgprofTimeSP1010_Xerr,\n# avgprofTimeSP1001_X, avgprofTimeSP1001_Xerr, Yt, [-3, 3], ' ', 'Sonde - OPM Difference (mPa)', ytitlet,\n# 'EN 0.5%-0.5B', 'EN 1.0%-0.1B', 'SP 1.0%-1.0B', 'SP 1.0%-0.1B', totO3_EN0505, totO3_EN1001, totO3_SP1010,\n# totO3_SP1001,\n# profEN0505.drop_duplicates(['Sim', 'Team']), profEN1001.drop_duplicates(['Sim', 'Team']), profSP1010_nodup,\n# profSP1001_nodup, 'ADif_Time_calibration')\n#\n# Plot_compare_4profile_plots_updated(\n# rTimeEN0505, rTimeENerr0505, rTimeEN1001, rTimeENerr1001, rTimeSP1010, rTimeSPerr1010, rTimeSP1001, rTimeSPerr1001,\n# Yt, [-40, 40], ' ', 'Sonde - OPM Difference (%)', ytitlet, 'EN 0.5%-0.5B', 'EN 1.0%-0.1B', 'SP 1.0%-1.0B',\n# 'SP 1.0%-0.1B',\n# totO3_EN0505, totO3_EN1001, totO3_SP1010, totO3_SP1001, profEN0505.drop_duplicates(['Sim', 'Team']),\n# profEN1001.drop_duplicates(['Sim', 'Team']), profSP1010_nodup, profSP1001_nodup, 'RDif_Time_calibration')\n#\n# yref = [1000, 950, 900, 850, 800, 750, 700, 650, 600, 550, 500, 450, 400, 350, 325, 300, 275, 250, 225, 200, 175, 150,\n# 135, 120, 105, 90, 85, 80, 75, 70, 65, 60, 55, 50, 45, 40, 35, 30, 28, 26, 24, 22, 20, 18, 16, 14, 12, 10, 8, 6]\n#\n# profSP1010['PO3_corr'] = profSP1010.apply(correct_Rdif, Rdif=rSP1010, Ys=yref, axis=1)\n# profSP1001['PO3_corr'] = profSP1001.apply(correct_Rdif, Rdif=rSP1001, Ys=yref, axis=1)\n# profEN1001['PO3_corr'] = profEN1001.apply(correct_Rdif, Rdif=rEN1001, Ys=yref, axis=1)\n# profEN0505['PO3_corr'] = profEN0505.apply(correct_Rdif, Rdif=rEN0505, Ys=yref, axis=1)\n#\n# avgprofcorrSP1010_O3S_X, avgprofcorrSP1010_O3S_Xerr, Y = Calc_average_profile_Pair(profSP1010, 'PO3_corr')\n# avgprofcorrSP1001_O3S_X, avgprofcorrSP1001_O3S_Xerr, Y = Calc_average_profile_Pair(profSP1001, 'PO3_corr')\n# avgprofcorrEN1001_O3S_X, avgprofcorrEN1001_O3S_Xerr, Y = Calc_average_profile_Pair(profEN1001, 'PO3_corr')\n# avgprofcorrEN0505_O3S_X, avgprofcorrEN0505_O3S_Xerr, Y = Calc_average_profile_Pair(profEN0505, 'PO3_corr')\n#\n# correctedPlot_PerCategory(avgprofSP1010_OPM_X, avgprofSP1010_O3S_X, avgprofcorrSP1010_O3S_X, Y, 'SP 1.0%-1.0B',\n# 'testSP1010')\n# correctedPlot_PerCategory(avgprofSP1001_OPM_X, avgprofSP1001_O3S_X, avgprofcorrSP1001_O3S_X, Y, 'SP 1.0%-0.1B',\n# 'testSP1001')\n# correctedPlot_PerCategory(avgprofEN1001_OPM_X, avgprofEN1001_O3S_X, avgprofcorrEN1001_O3S_X, Y, 'EN 1.0%-0.1B',\n# 'testEN1001')\n# correctedPlot_PerCategory(avgprofEN0505_OPM_X, avgprofEN0505_O3S_X, avgprofcorrEN0505_O3S_X, Y, 'EN 0.5%-0.5B',\n# 'testEN0505')\n#\n# correctedPlot_AllCategory(avgprofSP1010_O3S_X, avgprofSP1001_O3S_X, avgprofEN1001_O3S_X, avgprofEN0505_O3S_X,\n# avgprofcorrSP1010_O3S_X, avgprofcorrSP1001_O3S_X, avgprofcorrEN1001_O3S_X,\n# avgprofcorrEN0505_O3S_X,\n# Y, '', 'testall')\n#\n# # now plot Rdif Sonde1-OPM and Sonde1-Sonde2 with corrected values:\n# # w.r.t. OPM\n# dimension = len(Y)\n# # rcorr1, rerrcorr1 = Calc_RDif(profcorrX1, OPMX1, profcorrXerr1, dimension )\n# rcorrSP1010, rcorrSPerr1010 = Calc_RDif(avgprofcorrSP1010_O3S_X, avgprofSP1010_OPM_X, avgprofcorrSP1010_O3S_Xerr,\n# dimension)\n# rcorrSP1001, rcorrSPerr1001 = Calc_RDif(avgprofcorrSP1001_O3S_X, avgprofSP1001_OPM_X, avgprofcorrSP1001_O3S_Xerr,\n# dimension)\n# rcorrEN1001, rcorrENerr1001 = Calc_RDif(avgprofcorrEN1001_O3S_X, avgprofEN1001_OPM_X, avgprofcorrEN1001_O3S_Xerr,\n# dimension)\n# rcorrEN0505, rcorrENerr0505 = Calc_RDif(avgprofcorrEN0505_O3S_X, avgprofEN0505_OPM_X, avgprofcorrEN0505_O3S_Xerr,\n# dimension)\n#\n# acorrSP1010, acorrSPerr1010 = Calc_RDif(avgprofcorrSP1010_O3S_X, avgprofSP1010_OPM_X, avgprofcorrSP1010_O3S_Xerr,\n# dimension)\n# acorrSP1001, acorrSPerr1001 = Calc_RDif(avgprofcorrSP1001_O3S_X, avgprofSP1001_OPM_X, avgprofcorrSP1001_O3S_Xerr,\n# dimension)\n# acorrEN1001, acorrENerr1001 = Calc_RDif(avgprofcorrEN1001_O3S_X, avgprofEN1001_OPM_X, avgprofcorrEN1001_O3S_Xerr,\n# dimension)\n# acorrEN0505, acorrENerr0505 = Calc_RDif(avgprofcorrEN0505_O3S_X, avgprofEN0505_OPM_X, avgprofcorrEN0505_O3S_Xerr,\n# dimension)\n#\n# fig, ax2 = plt.subplots()\n# plt.xlim(-20, 20)\n# plt.ylim(1000, 5)\n# plt.title('Corrected')\n# plt.xlabel('Sonde - OPM (%)')\n# plt.ylabel(r'Pair (mPa)')\n# ax2.set_yscale('log')\n#\n# ax2.errorbar(rcorrSP1010, Y, xerr=rcorrSPerr1010, label='SP 1.0%-1.0B', linewidth=1, elinewidth=0.5, capsize=1,\n# capthick=0.5)\n# ax2.errorbar(rcorrSP1001, Y, xerr=rcorrSPerr1001, label='SP 1.0%-0.1B', linewidth=1, elinewidth=0.5, capsize=1,\n# capthick=0.5)\n# ax2.errorbar(rcorrEN1001, Y, xerr=rcorrENerr1001, label='EN 1.0%-0.1B', linewidth=1, elinewidth=0.5, capsize=1,\n# capthick=0.5)\n# ax2.errorbar(rcorrEN0505, Y, xerr=rcorrENerr0505, label='EN 0.5%-0.5B', linewidth=1, elinewidth=0.5, capsize=1,\n# capthick=0.5)\n# ax2.legend(loc='upper right', frameon=True, fontsize='small')\n#\n# plt.savefig('/home/poyraden/Josie17/Plots/Calibration_1718/RDifCorrected_RDif.pdf')\n# plt.savefig('/home/poyraden/Josie17/Plots/Calibration_1718/RDifCorrected_RDif.eps')\n#\n# fig, ax3 = plt.subplots()\n# plt.xlim(-20, 20)\n# plt.ylim(1000, 5)\n# plt.title('Corrected')\n# plt.xlabel('Sonde - OPM (%)')\n# plt.ylabel(r'Pair (mPa)')\n# ax3.set_yscale('log')\n#\n# ax3.errorbar(rcorrSP1010, Y, xerr=rcorrSPerr1010, label='SP 1.0%-1.0B', linewidth=1, elinewidth=0.5, capsize=1,\n# capthick=0.5)\n# ax3.errorbar(rcorrSP1001, Y, xerr=rcorrSPerr1001, label='SP 1.0%-0.1B', linewidth=1, elinewidth=0.5, capsize=1,\n# capthick=0.5)\n# ax3.errorbar(rcorrEN1001, Y, xerr=rcorrENerr1001, label='EN 1.0%-0.1B', linewidth=1, elinewidth=0.5, capsize=1,\n# capthick=0.5)\n# ax3.errorbar(rcorrEN0505, Y, xerr=rcorrENerr0505, label='EN 0.5%-0.5B', linewidth=1, elinewidth=0.5, capsize=1,\n# capthick=0.5)\n# ax3.legend(loc='upper right', frameon=True, fontsize='small')\n#\n# plt.savefig('/home/poyraden/Josie17/Plots/Calibration_1718/RDifCorrected_ADif.pdf')\n# plt.savefig('/home/poyraden/Josie17/Plots/Calibration_1718/RDifCorrected_ADif.eps')\n#\n# # now make a plot:\n# # Rdif of two sondes before and after correction applied:\n#\n# aSP1010_SP1001, aSPerr1010_SP1001 = Calc_ADif(avgprofSP1010_O3S_X, avgprofSP1001_O3S_X, avgprofSP1010_O3S_Xerr,\n# dimension)\n# acorrSP1010_SP1001, acorrSPerr1010_SP1001 = Calc_ADif(avgprofcorrSP1010_O3S_X, avgprofcorrSP1001_O3S_X,\n# avgprofcorrSP1010_O3S_Xerr, dimension)\n#\n# rSP1010_SP1001, rSPerr1010_SP1001 = Calc_RDif(avgprofSP1010_O3S_X, avgprofSP1001_O3S_X, avgprofSP1010_O3S_Xerr,\n# dimension)\n# rcorrSP1010_SP1001, rcorrSPerr1010_SP1001 = Calc_RDif(avgprofcorrSP1010_O3S_X, avgprofcorrSP1001_O3S_X,\n# avgprofcorrSP1010_O3S_Xerr, dimension)\n#\n# plot_2difPlots(rSP1010_SP1001, rSPerr1010_SP1001, rcorrSP1010_SP1001, rcorrSPerr1010_SP1001,\n# aSP1010_SP1001, aSPerr1010_SP1001, acorrSP1010_SP1001, acorrSPerr1010_SP1001, Y,\n# 'SP 1.0%-1.0B vs SP 1.0%-0.1B', 'SP1010_1001')\n#\n# aSP1010_EN1001, aSPerr1010_EN1001 = Calc_ADif(avgprofSP1010_O3S_X, avgprofEN1001_O3S_X, avgprofSP1010_O3S_Xerr,\n# dimension)\n# acorrSP1010_EN1001, acorrSPerr1010_EN1001 = Calc_ADif(avgprofcorrSP1010_O3S_X, avgprofcorrEN1001_O3S_X,\n# avgprofcorrSP1010_O3S_Xerr, dimension)\n#\n# rSP1010_EN1001, rSPerr1010_EN1001 = Calc_RDif(avgprofSP1010_O3S_X, avgprofEN1001_O3S_X, avgprofSP1010_O3S_Xerr,\n# dimension)\n# rcorrSP1010_EN1001, rcorrSPerr1010_EN1001 = Calc_RDif(avgprofcorrSP1010_O3S_X, avgprofcorrEN1001_O3S_X,\n# avgprofcorrSP1010_O3S_Xerr, dimension)\n#\n# plot_2difPlots(rSP1010_EN1001, rSPerr1010_EN1001, rcorrSP1010_SP1001, rcorrSPerr1010_EN1001,\n# aSP1010_EN1001, aSPerr1010_EN1001, acorrSP1010_EN1001, acorrSPerr1010_EN1001, Y,\n# 'SP 1.0%-1.0B vs EN 1.0%-0.1B', 'SP1010_EN1001')\n#\n# aSP1010_EN0505, aSPerr1010_EN0505 = Calc_ADif(avgprofSP1010_O3S_X, avgprofEN0505_O3S_X, avgprofSP1010_O3S_Xerr,\n# dimension)\n# acorrSP1010_EN0505, acorrSPerr1010_EN0505 = Calc_ADif(avgprofcorrSP1010_O3S_X, avgprofcorrEN0505_O3S_X,\n# avgprofcorrSP1010_O3S_Xerr, dimension)\n#\n# rSP1010_EN0505, rSPerr1010_EN0505 = Calc_RDif(avgprofSP1010_O3S_X, avgprofEN0505_O3S_X, avgprofSP1010_O3S_Xerr,\n# dimension)\n# rcorrSP1010_EN0505, rcorrSPerr1010_EN0505 = Calc_RDif(avgprofcorrSP1010_O3S_X, avgprofcorrEN0505_O3S_X,\n# avgprofcorrSP1010_O3S_Xerr, dimension)\n#\n# plot_2difPlots(rSP1010_EN0505, rSPerr1010_EN0505, rcorrSP1010_EN0505, rcorrSPerr1010_EN0505,\n# aSP1010_EN0505, aSPerr1010_EN0505, acorrSP1010_EN0505, acorrSPerr1010_EN0505, Y,\n# 'SP 1.0%-1.0B vs EN 0.5%-0.5B', 'SP1010_EN0505')\n#\n# aSP1001_EN1001, aSPerr1001_EN1001 = Calc_ADif(avgprofSP1001_O3S_X, avgprofEN1001_O3S_X, avgprofSP1001_O3S_Xerr,\n# dimension)\n# acorrSP1001_EN1001, acorrSPerr1001_EN1001 = Calc_ADif(avgprofcorrSP1001_O3S_X, avgprofcorrEN1001_O3S_X,\n# avgprofcorrSP1001_O3S_Xerr, dimension)\n#\n# rSP1001_EN1001, rSPerr1001_EN1001 = Calc_RDif(avgprofSP1001_O3S_X, avgprofEN1001_O3S_X, avgprofSP1001_O3S_Xerr,\n# dimension)\n# rcorrSP1001_EN1001, rcorrSPerr1001_EN1001 = Calc_RDif(avgprofcorrSP1001_O3S_X, avgprofcorrEN1001_O3S_X,\n# avgprofcorrSP1001_O3S_Xerr, dimension)\n#\n# plot_2difPlots(rSP1001_EN1001, rSPerr1001_EN1001, rcorrSP1001_EN1001, rcorrSPerr1001_EN1001,\n# aSP1001_EN1001, aSPerr1001_EN1001, acorrSP1001_EN1001, acorrSPerr1001_EN1001, Y,\n# 'SP 1.0%-0.1B vs EN 1.0%-0.1B', 'SP1001_EN1001')\n#\n# aSP1001_EN0505, aSPerr1001_EN0505 = Calc_ADif(avgprofSP1001_O3S_X, avgprofEN0505_O3S_X, avgprofSP1001_O3S_Xerr,\n# dimension)\n# acorrSP1001_EN0505, acorrSPerr1001_EN0505 = Calc_ADif(avgprofcorrSP1001_O3S_X, avgprofcorrEN0505_O3S_X,\n# avgprofcorrSP1001_O3S_Xerr, dimension)\n#\n# rSP1001_EN0505, rSPerr1001_EN0505 = Calc_RDif(avgprofSP1001_O3S_X, avgprofEN0505_O3S_X, avgprofSP1001_O3S_Xerr,\n# dimension)\n# rcorrSP1001_EN0505, rcorrSPerr1001_EN0505 = Calc_RDif(avgprofcorrSP1001_O3S_X, avgprofcorrEN0505_O3S_X,\n# avgprofcorrSP1001_O3S_Xerr, dimension)\n#\n# plot_2difPlots(rSP1001_EN0505, rSPerr1001_EN0505, rcorrSP1001_EN0505, rcorrSPerr1001_EN0505,\n# aSP1001_EN0505, aSPerr1001_EN0505, acorrSP1001_EN0505, acorrSPerr1001_EN0505, Y,\n# 'SP 1.0%-0.1B vs EN 0.5%-0.5B', 'SP1001_EN0505')\n#\n# aEN1001_EN0505, aENerr1001_EN0505 = Calc_ADif(avgprofEN1001_O3S_X, avgprofEN0505_O3S_X, avgprofEN1001_O3S_Xerr,\n# dimension)\n# acorrEN1001_EN0505, acorrENerr1001_EN0505 = Calc_ADif(avgprofcorrEN1001_O3S_X, avgprofcorrEN0505_O3S_X,\n# avgprofcorrEN1001_O3S_Xerr, dimension)\n#\n# rEN1001_EN0505, rENerr1001_EN0505 = Calc_RDif(avgprofEN1001_O3S_X, avgprofEN0505_O3S_X, avgprofEN1001_O3S_Xerr,\n# dimension)\n# rcorrEN1001_EN0505, rcorrENerr1001_EN0505 = Calc_RDif(avgprofcorrEN1001_O3S_X, avgprofcorrEN0505_O3S_X,\n# avgprofcorrEN1001_O3S_Xerr, dimension)\n#\n# plot_2difPlots(rEN1001_EN0505, rENerr1001_EN0505, rcorrEN1001_EN0505, rcorrENerr1001_EN0505,\n# aEN1001_EN0505, aENerr1001_EN0505, acorrEN1001_EN0505, acorrENerr1001_EN0505, Y,\n# 'EN 1.0%-0.1B vs EN 0.5%-0.5B', 'EN1001_EN0505')\n#\n# # rSP1010_SP1001, rSPerr1010_SP1001 = Calc_RDif(avgprofSP1010_O3S_X, avgprofSP1001_O3S_X, avgprofSP1010_O3S_Xerr, dimension )\n# # rcorrSP1010_SP1001, rcorrSPerr1010_SP1001 = Calc_RDif(avgprofcorrSP1010_O3S_X, avgprofcorrSP1001_O3S_X, avgprofcorrSP1010_O3S_Xerr, dimension )\n# # # rcorrSP1001, rcorrSPerr1001 = Calc_RDif(avgprofcorrSP1001_O3S_X, avgprofSP1001_OPM_X, avgprofcorrSP1001_O3S_Xerr, dimension )\n# # # rcorrEN1001, rcorrENerr1001 = Calc_RDif(avgprofcorrEN1001_O3S_X, avgprofEN1001_OPM_X, avgprofcorrEN1001_O3S_Xerr, dimension )\n# # # rcorrEN0505, rcorrENerr0505 = Calc_RDif(avgprofcorrEN0505_O3S_X, avgprofEN0505_OPM_X, avgprofcorrEN0505_O3S_Xerr, dimension )\n# #\n# # fig,ax3 = plt.subplots()\n# # plt.xlim(-20,20)\n# # plt.ylim(1000,5)\n# # plt.title('SP 1.0%-1.0B vs SP 1.0%-0.1B')\n# # plt.xlabel('PO3 (hPa)')\n# # plt.ylabel(r'Sonde1 - Sonde2 (%)')\n# # ax3.set_yscale('log')\n# #\n# # ax3.errorbar(rSP1010_SP1001, Y, xerr = rSPerr1010_SP1001, label = 'No Correction', linewidth = 1, elinewidth = 0.5, capsize = 1, capthick=0.5)\n# # ax3.errorbar(rcorrSP1010_SP1001, Y, xerr = rcorrSPerr1010_SP1001, label = 'Correction', linewidth = 1, elinewidth = 0.5, capsize = 1, capthick=0.5)\n# # #ax3.errorbar(rcorrEN1001, Y, xerr = rcorrENerr1001, label = 'EN 1.0%-0.1B', linewidth = 1, elinewidth = 0.5, capsize = 1, capthick=0.5)\n# # #ax3.errorbar(rcorrEN0505, Y, xerr = rcorrENerr0505, label = 'EN 0.5%-0.5B', linewidth = 1, elinewidth = 0.5, capsize = 1, capthick=0.5)\n# #\n# # ax3.legend(loc='upper right', frameon=True, fontsize = 'small')\n# #\n# #\n# # plt.savefig('/home/poyraden/Josie17/Plots/Calibration_1718/Corrected_RDif_SP1010_1001.pdf')\n# # plt.savefig('/home/poyraden/Josie17/Plots/Calibration_1718/Corrected_RDif_SP1010_1001.eps')\n","sub_path":"RDif_Calibration.py","file_name":"RDif_Calibration.py","file_ext":"py","file_size_in_byte":24604,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"315046217","text":"import numpy as np \n\nimport matplotlib.pyplot as plot \n\nimport tensorflow as tf \n\nx=np.random.normal(0,1,[10000,1])\n\ny=2*x +1 +np.random.rand(1,0.1,[10000,1])\n\n# plot.scatter(x,y)\n# plot.show()\n\n\nx_in = tf.placeholder(tf.float64,[5,1])\ny_in =tf.placeholder(tf.float64,[5,1])\n\nw=tf.Variable(np.random.rand([1, 1]))\nb=tf.Variable(np.random.rand([1]))\ny_out =tf.matmul(x_in,w) +b\n\nloss =tf.reduce_mean(tf.square(y_in -y_out)) \nstep = tf.train.GradientDescentOptimizer(0.1).minimize(loss)\nsess = tf.Session()\n\nsess.run(tf.global_variables_initializer())\nfor iter in range(300):\n idx=np.random.randint(0,1000,5)\n sess.run(step,feed_dict={x_in:[x[idx]],y_in:[y[idx]]})\n if itr%10 == 0:\n print(sess.run([loss,w.value(),b.value()],feed_dict={x_in:x[idx],y_in:y[idx]}))\n","sub_path":"1.14_courses/practise/failed_test.py","file_name":"failed_test.py","file_ext":"py","file_size_in_byte":778,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"317904170","text":"#!/usr/bin/env python3\n# -*- encoding: utf-8 -*-\n\n\"\"\"\nExercise 11.8\n--------------\nExponentiation of large integers is the basis of common algorithms for public-key encryption.\nRead the Wikipedia page on the RSA algorithm (http://en.wikipedia.org/wiki/RSA_(algorithm))\nand write functions to encode and decode messages.\n\"\"\"\n\nimport random\n\nrsa = {}\n\ndef gcd(a, b):\n \"\"\"\n This function computes the greatest common divisor of two numbers.\n \"\"\"\n while b != 0:\n a, b = b, a % b\n return a\n\ndef is_prime(a):\n \"\"\"\n This function checks whether a given number is prime or not.\n \"\"\"\n if a < 2 or a%2 == 0:\n return False\n if a == 2:\n return True\n for n in range(3, a//2, 2):\n if a % n == 0:\n return False\n return True\n\ndef generate_prime_pair():\n \"\"\"\n This function generates a pair of random prime numbers.\n \"\"\"\n while True:\n a = random.randint(2, 100)\n b = random.randint(2, 100)\n if is_prime(a) and is_prime(b) and a != b:\n return a, b\n\ndef rsa_algorithm(message):\n \"\"\"\n This function process the RSA algorithm\n \"\"\"\n p, q = generate_prime_pair() # generate a pair of prime numbers p and q.\n print('p = ', p,' q = ', q)\n n = p * q\n print('n = p * q = ', n)\n phi = (p-1) * (q-1)\n print('phi = (p-1) * (q-1) = ', phi)\n while True:\n e = random.randint(1, phi)\n if gcd(n, e) == 1 and is_prime(e):\n break\n print('e = ', e)\n while True:\n d = random.randint(1, phi)\n if (d * e) % phi == 1 and is_prime(d):\n break\n print('d = ', d)\n rsa[e, n] = d, n\n c = (message**e) % n\n m = (c**d) % n\n print('At the encrypting end ({0} ^ {1}) mod {2} = {3}'.format(message, e, n, c))\n print('At the decrypting end ({0} ^ {1}) mod {2} = {3}'.format(c, d, n, m))\n\nif __name__ == '__main__':\n mes = int(input('Enter message code : '))\n rsa_algorithm(mes)\n","sub_path":"chapter11/exercise_11_8.py","file_name":"exercise_11_8.py","file_ext":"py","file_size_in_byte":1964,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"630041842","text":"\"\"\"\nThis module contains step definitions for unit.feature.\nIt uses the default 'parse' for step parameters:\nhttp://behave.readthedocs.io/en/latest/tutorial.html#step-parameters\n\"\"\"\n\n\nfrom behave import *\nfrom cucumbers import CucumberBasket\n\n\n# Givens\n\n@given('the basket has \"{initial:d}\" cucumber')\n@given('the basket has \"{initial:d}\" cucumbers')\ndef step_impl(context, initial):\n context.basket = CucumberBasket(initial_count=initial)\n\n\n@given('the basket is empty')\ndef step_impl(context):\n context.basket = CucumberBasket()\n\n\n@given('the basket is full')\ndef step_impl(context):\n context.basket = CucumberBasket(initial_count=10)\n\n\n# Whens\n\n@when('\"{some:d}\" more cucumbers are added to the basket')\n@when('\"{some:d}\" cucumbers are added to the basket')\ndef step_impl(context, some):\n context.basket.add(some)\n\n\n@when('\"{some:d}\" cucumbers are removed from the basket')\ndef step_impl(context, some):\n context.basket.remove(some)\n\n\n# Thens\n\n@then('the basket contains \"{total:d}\" cucumbers')\ndef step_impl(context, total):\n assert context.basket.count == total\n\n\n@then('the basket is empty')\ndef step_impl(context):\n assert context.basket.empty\n\n\n@then('the basket is full')\ndef step_impl(context):\n assert context.basket.full\n\n\n@then('\"{some:d}\" cucumbers cannot be added to the basket')\ndef step_impl(context, some):\n count = context.basket.count\n try:\n context.basket.add(some)\n except ValueError as e:\n assert str(e) == \"Attempted to add too many cucumbers\"\n assert count == context.basket.count, \"Cucumber count changed despite overflow\"\n except:\n assert False, \"Exception raised for basket overflow was not a ValueError\"\n else:\n assert False, \"ValueError was not raised for basket overflow\"\n\n\n@then('\"{some:d}\" cucumbers cannot be removed from the basket')\ndef step_impl(context, some):\n count = context.basket.count\n try:\n context.basket.remove(some)\n except ValueError as e:\n assert str(e) == \"Attempted to remove too many cucumbers\"\n assert count == context.basket.count, \"Cucumber count changed despite overdraw\"\n except:\n assert False, \"Exception raised for basket overdraw was not a ValueError\"\n else:\n assert False, \"ValueError was not raised for basket overdraw\"\n","sub_path":"behave/features/steps/unit.py","file_name":"unit.py","file_ext":"py","file_size_in_byte":2307,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"202941261","text":"import math, quat\n\nclass Camera():\n def __init__(self, v, u, p, f, d, ax, ay):\n # pull variables in\n if u == 'spherical':\n temp = []\n temp.append(u[0] * math.sin(u[1]) * math.cos(u[2]))\n temp.append(u[0] * math.sin(u[1]) * math.sin(u[2]))\n temp.append(u[0] * math.cos(u[1]))\n self.v = temp\n elif u == 'vector': self.v = v\n self.p,self.f,self.d = p,f,d\n self.sx,self.sy = f*math.tan(ax*math.pi/180.0),f*math.tan(ay*math.pi/180.0)\n self.mag = math.sqrt(self.v[0]**2+self.v[1]**2+self.v[2]**2)\n self.phi = math.asin(float(self.v[2])/self.mag)\n if float(self.v[0])/(self.mag*math.cos(self.phi)) > 1.0: self.theta = 0.0\n else: self.theta = math.acos(float(self.v[0])/(self.mag*math.cos(self.phi)))\n if self.v[1] < 0: self.theta = -self.theta\n self.y_hat_prime = [-self.v[1],self.v[0],0]\n self.gtl_rot1 = quat.axisangle_to_q([0,0,1],-self.theta)\n self.ltg_rot1 = quat.axisangle_to_q([0,0,1],self.theta)\n if self.y_hat_prime != [0,0,0]:\n self.gtl_rot2 = quat.axisangle_to_q(self.y_hat_prime,self.phi)\n self.ltg_rot2 = quat.axisangle_to_q(self.y_hat_prime,-self.phi)\n else:\n self.gtl_rot2 = quat.axisangle_to_q([-1,0,0],self.phi)\n self.ltg_rot2 = quat.axisangle_to_q([-1,0,0],-self.phi)\n def gtl(self,gv):\n v = quat.qv_mult(self.gtl_rot2,gv)\n # print(v)\n v = quat.qv_mult(self.gtl_rot1,v)\n # print(v)\n return v\n def ltg(self,lv):\n v = quat.qv_mult(self.ltg_rot1,lv)\n # print(v)\n v = quat.qv_mult(self.ltg_rot2,v)\n # print(v)\n for i in range(3): v[i] += self.p[i]\n # print(v)\n return v\n def unit_vector_to_plane(self, u):\n mag = math.sqrt(u[0]**2+u[1]**2+u[2]**2)\n for i in range(3): u[i] /= mag\n if u[2] < 0:\n x = u[0] / u[2] * -self.p[2] + self.p[0]\n if x > 10000.0: x = 10000.0\n elif x < -10000.0: x = -10000.0\n y = u[1] / u[2] * -self.p[2] + self.p[1]\n if y > 10000.0: y = 10000.0\n elif y < -10000.0: y = -10000.0\n else:\n if u[0] * -self.p[2] < 0: x = 10000.0\n else: x = -10000.0\n if u[1] * -self.p[2] < 0: y = 10000.0\n else: y = -10000.0\n x = round(x,4)\n y = round(y,4)\n return [x,y]\n def pixel_to_world(self, pixel):\n xp = -(pixel[0]-self.d[0]/2.0)/(self.d[0]/2.0)*self.sx\n yp = -(pixel[1]-self.d[1]/2.0)/(self.d[1]/2.0)*self.sy\n # print(\"xp,yp\")\n # print(xp,yp)\n lx = self.f\n ly = xp\n lz = yp\n # print(\"lx,ly,lz\")\n # print(lx,ly,lz)\n mag = math.sqrt(lx**2+ly**2+lz**2)\n lx /= mag\n ly /= mag\n lz /= mag\n # print(\"lx,ly,lz normalized\")\n # print(lx,ly,lz)\n # v = np.dot(self.ltg_rotation_matrix,[lx,ly,lz])\n v = self.ltg([lx,ly,lz])\n # print(v)\n for i in range(3): v[i] -= self.p[i]\n # print(\"gv\")\n # print(v)\n return self.unit_vector_to_plane(v)\n def get_corners(self):\n self.top_left = self.pixel_to_world([0,0])\n self.top_right = self.pixel_to_world([self.d[0],0])\n self.bottom_right = self.pixel_to_world([self.d[0],self.d[1]])\n self.bottom_left = self.pixel_to_world([0,self.d[1]])\n return [self.top_left,self.top_right,self.bottom_right,self.bottom_left]\n\n# i = [1, 0, 0] # initial global camera facing vector\n# v = [0, 1, -1] # final global camera facing vector\n# p = [0, 0, 1] # global camera position vector\n# f = 0.035 # focal length in meters\n# ax = 45.0 # total angle of view in degrees\n# ay = 45.0\n# d = [1920,1080] # [horizontal,vertical] dimensions in pixels\n#\n# camera1 = Camera(v,'vector',p,f,d,ax,ay)\n# print(camera1.get_corners())\n# print(camera1.pixel_to_world([1920/2,1080/2]))","sub_path":"camera.py","file_name":"camera.py","file_ext":"py","file_size_in_byte":3947,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"498573473","text":"# #importando la funcion power del modulo draw\n# from draw import power\n# print(\"Hola mundo!\")\n# power(10,2)\n#\n# def shut_down(s):\n# if s == \"yes\":\n#\n# print (\"She shut me down BANG BANG!\")\n# elif s == \"no\":\n#\n# print (\"My baby shut me down..\")\n# else:\n# return \"Sorry\"\n#\n#\n# shut_down(\"yes\")\n#\n# #COSTOS VACACIONES\n#\n# def hotel_cost(nights):\n# return 140 * nights\n#\n# def plane_ride_cost(city):\n# if city == \"Cordoba\":\n# return 183\n# elif city == \"San Luis\":\n# return 220\n# elif city == \"Salta\":\n# return 222\n# elif city == \"Bariloche\":\n# return 475\n#\n# def rental_car_cost(days):\n# rental_car = days * 40\n# if days >= 7:\n# rental_car -= 50\n# elif days >= 3 and days <= 6:\n# rental_car -= 20\n# return rental_car\n#\n#\n# def trip_cost(city, days, extra_money):\n# print (rental_car_cost(days) + hotel_cost(days - 1) + plane_ride_cost(city) + extra_money)\n#\n# print trip_cost(\"Bariloche\", 5, 1000)\n\n\n#SCRIPT PROMEDIO\n\n\n\nlloyd = {\n \"nombre\": \"Lloyd\",\n \"tarea\": [90.0, 97.0, 75.0, 92.0],\n \"preguntas\": [88.0, 40.0, 94.0],\n \"pruebas\": [75.0, 90.0]\n}\nalice = {\n \"nombre\": \"Alice\",\n \"tarea\": [100.0, 92.0, 98.0, 100.0],\n \"preguntas\": [82.0, 83.0, 91.0],\n \"pruebas\": [89.0, 97.0]\n}\ntyler = {\n \"nombre\": \"Tyler\",\n \"tarea\": [0.0, 87.0, 75.0, 22.0],\n \"preguntas\": [0.0, 75.0, 78.0],\n \"pruebas\": [100.0, 100.0]\n}\n\nestudiantes = [lloyd, alice , tyler]\n\nfor estudiante in estudiantes:\n print (estudiante[\"nombre\"])\n print (estudiante[\"tarea\"])\n print (estudiante[\"preguntas\"])\n print (estudiante[\"pruebas\"])\n","sub_path":"hola.py","file_name":"hola.py","file_ext":"py","file_size_in_byte":1634,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"595423458","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[1]:\n\n\nget_ipython().system('pip3 install python-docx')\n\n\n# In[2]:\n\n\nimport docx\n\n\n# In[3]:\n\n\ndef getTextWord(wordFileName): # getTextWord 함수\n doc = docx.Document(wordFileName)\n fullText = []\n for para in doc.paragraphs: # paragraphs \n fullText.append(para.text)\n return '\\n'.join(fullText)\n\n\n# In[ ]:\n\n\n\n\n","sub_path":"week03/word.py","file_name":"word.py","file_ext":"py","file_size_in_byte":372,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"41022451","text":"# ############################################################################################################# #\n# MAP Geoprocessing with python #\n# (c)Simon Spengler Humboldt-Universität zu Berlin #\n# Tested on Windows 10 1909, Python 3.7.4, gdal 3.0.2, sklearn 0.22.1\n# ####################################### LOAD REQUIRED LIBRARIES ############################################# #\nimport time\nimport os\nimport re\nfrom osgeo import ogr, osr\nimport gdal\nimport pandas as pd\nimport numpy as np\nfrom sklearn import metrics\nfrom sklearn.ensemble import RandomForestRegressor\nfrom sklearn.model_selection import GridSearchCV\nfrom joblib import Parallel, delayed\n\n# ####################################### SET TIME-COUNT ###################################################### #\nstarttime = time.strftime(\"%a, %d %b %Y %H:%M:%S\", time.localtime())\nprint(\"--------------------------------------------------------\")\nprint(\"Starting process, time: \" + starttime)\nprint(\"\")\n# ####################################### FOLDER PATHS & global variables ##################################### #\n# Define path to data folder and change directory\npath = \"C:/Users/Simon Spengler/PycharmProjects/GeoPy/Week15 - MAP/\"\nos.chdir(path)\n\n# check if output directory already exists. If not create output directory\nif not os.path.exists('SPENGLER_SIMON_MAP-WS-1920_RF-predictions'):\n os.makedirs('SPENGLER_SIMON_MAP-WS-1920_RF-predictions')\n\nout = os.path.join(path, 'SPENGLER_SIMON_MAP-WS-1920_RF-predictions/')\n\n# detect number of available cpu cores for parallel processing\nn_cores = os.cpu_count()\n# define no data value\nnodata = -9999\n\n\n# ####################################### FUNCTIONS ########################################################### #\n\ndef list_files(path, ftype, full=True):\n \"\"\"\n function that returns a list of files of a specific file format in a folder\n :param path: Path to folder\n :param ftype: file format ending\n :param full: If true full path will be returned, if not only the filename\n :return: list of file names\n \"\"\"\n # add all files to list with the ending of the specified file format\n list = [f for f in os.listdir(path) if re.match('^.*\\\\.' + ftype + '$$', f)]\n\n if full:\n # paste file name and path\n list = [os.path.join(path, f) for f in list]\n return list\n\n\ndef get_extent(inp_raster):\n \"\"\"\n function that returns the extent of a list of raster files (see assignment 4)\n :param inp_raster: list of raster file names\n :return: polygon with common extent of all rasters given\n \"\"\"\n # initialize extent coordinates\n ext_ulx, ext_uly = float('-inf'), float('inf')\n ext_lrx, ext_lry = float('inf'), float('-inf')\n\n # loop through all raster files\n for raster in inp_raster:\n\n raster = gdal.Open(raster, gdal.GA_ReadOnly)\n gt = raster.GetGeoTransform()\n ulx = gt[0] # upper left x coordinate\n uly = gt[3] # upper left y coordinate\n lrx = ulx + (gt[1] * raster.RasterXSize) # upper left x coordinate + number of pixels * pixel size\n lry = uly + (gt[5] * raster.RasterYSize) # upper left y coordinate + number of pixels * pixel size\n\n if ulx > ext_ulx:\n ext_ulx = ulx\n if uly < ext_uly:\n ext_uly = uly\n if lrx < ext_lrx:\n ext_lrx = lrx\n if lry > ext_lry:\n ext_lry = lry\n ext = [ext_ulx, ext_uly, ext_lrx, ext_lry]\n\n # create new geometry from extent coordinates\n ring = ogr.Geometry(ogr.wkbLinearRing)\n poly = ogr.Geometry(ogr.wkbPolygon)\n\n ring.AddPoint(ext[0], ext[1])\n ring.AddPoint(ext[2], ext[1])\n ring.AddPoint(ext[2], ext[3])\n ring.AddPoint(ext[0], ext[3])\n ring.AddPoint(ext[0], ext[1])\n\n poly.AddGeometry(ring)\n return poly\n\n\ndef extract(ras, points, attr=None):\n '''\n function that returns raster values from points layer (see assignment 10)\n :param ras: file of raster, where values are extracted from\n :param points: point geometry layer\n :param attr: attribute field that should be added from vector layer\n :return: list of extracted values\n '''\n\n ras = gdal.Open(ras)\n gt = img.GetGeoTransform()\n #initialize list for extrated values\n values = []\n #loop through all point in laer\n for feat in points:\n geom = feat.GetGeometryRef().Clone()\n #get coordinates from point\n x, y = geom.GetX(), geom.GetY()\n #transform into image coordinates\n px = int((x - gt[0]) / gt[1]) # x pixel\n py = int((y - gt[3]) / gt[5]) # y pixel\n\n # read raster values from image coordinates and append to list\n if attr:\n attr_val = feat.GetField(attr)\n values.append([attr_val] + ras.ReadAsArray(px, py, 1, 1).flatten().tolist())\n else:\n values.append(ras.ReadAsArray(px, py, 1, 1).flatten().tolist())\n # de-initialise\n del geom\n points.ResetReading()\n\n return values\n\n\ndef predict_RF(img):\n '''\n function for predicting random forest regression model on raster file (see assignment 12)\n :param img: file of raster file that should be predicted on\n :return:\n '''\n ds = gdal.Open(img)\n #read only non-corrupted raster bands\n ds_array = ds.ReadAsArray()[:12, :, :]\n\n # Take full image and reshape into long 2d array (nrow * ncol, nband) for classification\n n_bands, n_rows, n_cols = ds_array.shape\n flatImg = ds_array.reshape((n_bands, n_rows * n_cols))\n flatImg = np.transpose(flatImg)\n\n # Now predict for each pixel\n class_prediction = rf_model.predict(flatImg)\n\n # Reshape classification map\n lcImg = class_prediction.reshape(ds_array[0, :, :].shape)\n lcImg = lcImg.astype('int16')\n\n # write\n drv = gdal.GetDriverByName('GTiff')\n fname = os.path.basename(img.replace(\".tif\", \"_RF-regression.tif\"))\n dst_ds = drv.Create(out + fname, n_cols, n_rows, 1, gdal.GDT_Int16, [])\n dst_band = dst_ds.GetRasterBand(1)\n # write the data\n dst_band.WriteArray(lcImg, 0, 0)\n\n # flush data to disk, set the geo-references\n dst_band.FlushCache()\n dst_ds.SetGeoTransform(ds.GetGeoTransform())\n dst_ds.SetProjection(ds.GetProjectionRef())\n dst_ds = None\n\n\ndef image_offsets(img, coordinates):\n '''\n Translating real world coordinates in image coordinates (see Assignment 9)\n :param img: gdal raster image\n :param coordinates: list of real world coordinates\n :return:\n '''\n gt = img.GetGeoTransform()\n #Invert Geotransform\n inv_gt = gdal.InvGeoTransform(gt)\n offsets_ul = list(map(int, gdal.ApplyGeoTransform(inv_gt, coordinates[0], coordinates[1])))\n offsets_lr = list(map(int, gdal.ApplyGeoTransform(inv_gt, coordinates[2], coordinates[3])))\n\n return offsets_ul + offsets_lr\n\n\n# ####################################### PROCESSING ########################################################## #\n\n#############################################PART 1##############################################################\n\n\n\n########### 1)Extractthe response variable fromthe attribute table of the shapefile.\n########### 2)Extract the Landsat metrics at the locationof the points.\n########### Be aware, not all points are overlapping with the extent of the raster files,and\n########### some points have NA values in the response variables. Omit these points!\n\n# get list of raster files\ntile_list = list_files('datasets/RasterFiles', 'tif')\n\n# open random points vector file\nrnd_pts_f = ogr.Open('datasets/RandomPoint_Dataset/RandomPoints.shp')\nrnd_pnts = rnd_pts_f.GetLayer()\n\n# loop through all raster tiles\nfor i, tile in enumerate(tile_list):\n\n #get extent of raster tile\n tile_extent = get_extent([tile])\n\n #filter all point in current tile\n rnd_pnts.SetSpatialFilter(tile_extent)\n\n #extract raster values at points\n extr_data = extract(tile, rnd_pnts, 'TC')\n\n #create data frame in first loop\n if i == 0:\n df = pd.DataFrame.from_records(extr_data)\n else:\n #concat new values\n df = pd.concat((df, pd.DataFrame.from_records(extr_data)))\n #reset filter and reading for next tile\n rnd_pnts.SetSpatialFilter(None)\n rnd_pnts.ResetReading()\n\n#exclude no data values\ndf = df[df[0] != nodata]\n\n#select response variable\ny = df[0]\n\n#select predictor variable\nX = df.drop([0], axis=1)\n#exclude data from corrupt bands\nX = X.iloc[:, 0:12]\n\n\n\n\n########### 3)Parameterizea random forest regressionmodel.\n########### To describe the model goodness-of-fit and prediction error, print the following statistics to the console:\n########### 1)the root-mean-squared error of the out-of-bag predicted tree cover versus the observedtreecover,\n########### 2) the coefficient of determination R^2.\n\n\nprint('Fitting Random Forest Regressor')\nprint(\"--------------------------------------------------------\")\nrf_reg = RandomForestRegressor(oob_score=True)\n\n# define parameter grid for cross validation\nparam_grid = {\n \"n_estimators\": [10, 100, 250, 500],\n \"max_features\": [\"auto\", \"sqrt\", \"log2\"],\n \"min_samples_split\": [2, 4, 8, 16],\n}\n\n#find best parameters by cross-validation\ngrid = GridSearchCV(rf_reg, param_grid, cv=3)\n\n#fit regressor to extracted data\ngrid.fit(X, y)\n\nprint('Random Forest parameterization:')\nprint(grid.best_params_)\nprint(\"--------------------------------------------------------\")\n\nrf_model = grid.best_estimator_\n\n#Assess model fit\nr2 = metrics.r2_score(y, rf_model.oob_prediction_)\nrmse = metrics.mean_squared_error(y, rf_model.oob_prediction_, squared=False)\nprint('R2:' + str(round(r2, 3)))\nprint('RMSE: ' + str(round(rmse, 3)))\nprint(\"--------------------------------------------------------\")\n\n\n\n########### 4) Take the resulting model and predict fractional tree cover foreach pixel and tile.\n########### For each tile, write the fractional tree cover map as a GeoTiFFfile.\n########### The name of the output file(s) should have the suffix “_RF-regression.tif”\n\n\nprint('Run Random Forest Prediction')\nprint(\"--------------------------------------------------------\")\n#run random forest prediction looping through all tiles in parallel\nif __name__ == '__main__':\n Parallel(n_jobs=n_cores - 1)(delayed(predict_RF)(i) for i in tile_list)\n\n\n\n\n########### 5) From the individual fractional tree cover tiles (task 4),\n########### createa mosaic for the entire study area as\n########### 1) a virtual raster file (VRT), and\n########### 2) a GeoTIFF file.\n########### The name of the files should be 1)“SURNAME_NAME_MAP-WS-1920_RF-prediction.vrt”,and\n########### 2) “SURNAME_NAME_MAP-WS-1920_RF-prediction.tif”.\n########### 6) All files should be stored in a newly generated folder named “SURNAME_NAME_MAP-WS-1920_RF-predictions”\n\n\n#get list of file names of predictes raster tiles\nreg_list = list_files(out, 'tif')\n\nprint('Build image mosaics')\nprint(\"--------------------------------------------------------\")\n#build Virtual Raster from raster tiles\nvrt = gdal.BuildVRT(out + 'SPENGLER_SIMON_MAP-WS-1920_RF-prediction.vrt', reg_list, VRTNodata=-nodata)\n#convert Virtual Raster to GeoTiff\ntif = gdal.Translate(out + 'SPENGLER_SIMON_MAP-WS-1920_RF-prediction.tif', vrt)\n#close connection for writing to disk\nvrt = tif = None\n\n# open vrt and tif in read only mode for writing the overview pyramids\nvrt = gdal.Open(out + 'SPENGLER_SIMON_MAP-WS-1920_RF-prediction.vrt', 0)\ntif = gdal.Open(out + 'SPENGLER_SIMON_MAP-WS-1920_RF-prediction.tif', 0)\n\n#set compression parameters\ngdal.SetConfigOption('COMPRESS_OVERVIEW', 'DEFLATE')\n#build pyramids with nearest neigbor resampling\nvrt.BuildOverviews(\"NEAREST\", [2, 4, 8, 16, 32, 64])\ntif.BuildOverviews(\"NEAREST\", [2, 4, 8, 16, 32, 64])\nvrt = tif = None\n\n\n\n#############################################PART 2##############################################################\n\n########### 1) Calculate the tree cover statistics foreach features (polygon) in the shapefile.\n########### In case that the raster extent is smaller than the polygon shapefile, the dataset should report ‘NA’\n########### 2) Write a csv-file to the drive in which the first column contains the unique identifier,\n########### followed by the description of “OT_class”(this attribute you’ll need to extract from the shapefile),\n########### and the area of the feature in km2 (rounded to 3 digits).\n########### Following these three columns, please create individual columns for each of the summary statistics.\n########### The first row of the dataset should contain the variable names, the separator should be a “,”\n########### and should not contain row names\n########### 3) Name the output-file as SURNAME_NAME_MAP-WS-1920_summaryStats.csv\n\n\n#opem image mosaic of predictions\nimg = gdal.Open(out + 'SPENGLER_SIMON_MAP-WS-1920_RF-prediction.vrt')\n\n# open shape file with zone polygons and get layer\nzones_f = ogr.Open('Datasets/Zonal_Dataset/FL_Areas_ChacoRegion.shp')\nzones_lyr = zones_f.GetLayer()\n\n# define memory driver for temp. shape files\noutDriver = ogr.GetDriverByName(\"Memory\")\n\n#get coordinates reference system of image and shape file\ncrs_zones = zones_lyr.GetSpatialRef()\ncrs_img = img.GetSpatialRef()\n# set order of coordinate return\ncrs_zones.SetAxisMappingStrategy(osr.OAMS_TRADITIONAL_GIS_ORDER)\ncrs_img.SetAxisMappingStrategy(osr.OAMS_TRADITIONAL_GIS_ORDER)\n#build transformer object for on-the-fly conversion of zone geometries\ntransformer = osr.CoordinateTransformation(crs_zones, crs_img)\n\n#get pixel size and extent of raster file\ngt = img.GetGeoTransform()\npixel_size = gt[1]\nextent = get_extent([out + 'SPENGLER_SIMON_MAP-WS-1920_RF-prediction.vrt'])\n\n#initialize dataframe for statistics\nsummary = pd.DataFrame(columns={'UniqueID': [],\n 'OT_class': [],\n 'area': [],\n 'mean': [],\n 'std': [],\n 'min': [],\n 'max': [],\n '10th_percentile': [],\n '90th_percentile': []\n })\n\nprint('Calculating zonal statistics')\n\n#loop through all zone polygons\nfor zone in zones_lyr:\n #extract attributes from feature\n id = zone.GetField('UniqueID')\n OT_class = zone.GetField('OT_class')\n\n #copy geometry of feature\n geom = zone.GetGeometryRef().Clone()\n #Get area of feature and convert to square kilometres\n area = geom.GetArea() * 1e-6\n\n #transform geometry to image crs\n geom.Transform(transformer)\n\n #check if zone lies in raster extent\n if geom.Within(extent):\n # create temporary shape file with the current feature only\n outDataSource = outDriver.CreateDataSource('')\n outLayer = outDataSource.CreateLayer('', crs_img, geom_type=ogr.wkbPolygon)\n featureDefn = outLayer.GetLayerDefn()\n # create feature\n feat = ogr.Feature(featureDefn)\n feat.SetGeometry(geom)\n outLayer.CreateFeature(feat)\n\n #Get envelope coordinate of zone feature\n x_min, x_max, y_min, y_max = geom.GetEnvelope()\n # get array indices for subsetting the image raster\n img_offsets = image_offsets(img, (x_min, y_max, x_max, y_min))\n # snap upperleft coordinates to next image pixel\n new_x, new_y = gdal.ApplyGeoTransform(gt, img_offsets[0], img_offsets[1])\n\n # Get resolution of vectorized raster\n x_res = int((x_max - x_min) / pixel_size)\n # if the zone is smaller than 1 pixel, 1 pixel will be created\n if x_res == 0:\n x_res = 1\n y_res = int((y_max - y_min) / pixel_size)\n if y_res == 0:\n y_res = 1\n # create temporary gdal raster\n target_ds = gdal.GetDriverByName('MEM').Create('', x_res, y_res, gdal.GDT_Byte)\n target_ds.SetGeoTransform((new_x, pixel_size, 0, new_y, 0, -pixel_size))\n band = target_ds.GetRasterBand(1)\n band.SetNoDataValue(255)\n\n # Rasterize zone\n # if zone is too small cross the center of a pixel, all touched pixels will be rasterized\n if (x_res == 1 or y_res == 1):\n gdal.RasterizeLayer(target_ds, [1], outLayer, burn_values=[1], options=['ALL_TOUCHED=TRUE'])\n\n gdal.RasterizeLayer(target_ds, [1], outLayer, burn_values=[1])\n feat = None\n outDataSource = outLayer = None\n # read mask\n mask = band.ReadAsArray()\n # subset image mosaic\n img_sub = img.ReadAsArray(img_offsets[0], img_offsets[1], mask.shape[1], mask.shape[0])\n img_sub = np.where(img_sub == nodata, np.NaN, img_sub)\n\n # apply mask and calc stats\n tc_mean = np.nanmean(np.where(mask == 1, img_sub, np.NaN))\n tc_std = np.nanstd(np.where(mask == 1, img_sub, np.NaN))\n tc_min = np.nanmin(np.where(mask == 1, img_sub, np.NaN))\n tc_max = np.nanmax(np.where(mask == 1, img_sub, np.NaN))\n tc_10 = np.nanpercentile(np.where(mask == 1, img_sub, np.NaN), 10)\n tc_90 = np.nanpercentile(np.where(mask == 1, img_sub, np.NaN), 90)\n\n #append stats to data frame\n summary = summary.append({'UniqueID': id,\n 'OT_class': OT_class,\n 'area': area,\n 'mean': tc_mean,\n 'std': tc_std,\n 'min': tc_min,\n 'max': tc_max,\n '10th_percentile': tc_10,\n '90th_percentile': tc_90}, ignore_index=True)\n else:\n #if zone does not lie in raster extent NAs for the stats will be returned\n summary = summary.append({'UniqueID': id,\n 'OT_class': OT_class,\n 'area': area,\n 'mean': np.nan,\n 'std': np.nan,\n 'min': np.nan,\n 'max': np.nan,\n '10th_percentile': np.nan,\n '90th_percentile': np.nan}, ignore_index=True)\n\n#cast id and class as integer\nsummary = summary.astype({'UniqueID': 'uint32', 'OT_class': 'int8'})\n\n#write statistics to csv file\nsummary.to_csv(out + \"SPENGLER_SIMON_MAP-WS-1920_summaryStats.csv\", sep=\",\", na_rep=\"NA\", float_format='%.3f',\n index=False, encoding='utf-8-sig')\n\n# ####################################### END TIME-COUNT AND PRINT TIME STATS################################## #\nprint(\"\")\nendtime = time.strftime(\"%a, %d %b %Y %H:%M:%S\", time.localtime())\nprint(\"--------------------------------------------------------\")\nprint(\"start: \" + starttime)\nprint(\"end: \" + endtime)\nprint(\"\")\n","sub_path":"MAP.py","file_name":"MAP.py","file_ext":"py","file_size_in_byte":18930,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"607019582","text":"#-*- encoding: utf-8 -*-\nimport sys\nr=sys.stdin.readline\n\nN = int(r()) # N: 숫자의 개수\npermu = list(map(int, r().split())) # 주어진 순열\n\nis_minus = 1\nfor i in range(1, N+1):\n if permu[i-1] != i:\n is_minus = 0\n\nif is_minus: # 내림차순으로 이루어진 수열일 경우\n print(-1)\n exit()\n\n\nind = 0\nfor i in range(N): # 나머지의 경우 뒷자리의 숫자보다 앞자리의 숫자가 큰 경우를 탐색\n if permu[N-i-1] < permu[N-i-2]:\n ind = N-i-2\n break\n\nfor i in range(ind):\n print(permu[i], end=' ')\n\ntemp = sorted(permu[ind:], reverse = True)\nt = temp.index(permu[ind]) + 1\n\nprint(temp[t], end=' ')\n\ntemp.pop(t)\n\nfor i in temp:\n print(i, end=' ')\n","sub_path":"Algorithm/Baekjoon/10973 이전 순열/10973.py","file_name":"10973.py","file_ext":"py","file_size_in_byte":747,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"478695727","text":"# A simple implementation of a stack\n# using a array\n\nclass stack:\n __s = [None] * 10\n __len = 0\n \n def __init__(self):\n __s = []\n __len = 0\n\n def push(self, data):\n self.__s[self.__len] = data\n self.__len += 1\n \n def pop(self):\n data = self.__s[self.__len-1]\n self.__len -= 1\n self.__s[self.__len] = None\n return data\n \n def isEmpty(self):\n return not (self.__len > 0)\n \n def peek(self):\n return self.__s[self.__len-1]\n\n def __str__(self):\n return(str(self.__s))\n\ns = stack()\ns.push(10)\ns.push(20)\ns.push(60)\ns.push(40)\ns.push(50)\nprint(s)\n\nprint(s.pop())\nprint(s)\nprint(s.pop())\nprint(s)\nprint(s.pop())\nprint(s)\nprint(s.pop())\nprint(s)\nprint(s.peek())\nprint(s)\n","sub_path":"private/dev/ChallengePy/stack.py","file_name":"stack.py","file_ext":"py","file_size_in_byte":780,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"213709947","text":"\"\"\"\nWord2Vec 사용\ngensim : word2vec을 구현한 pypthon module\n\"\"\"\n\nimport pandas as pd\n\ntrain = pd.read_csv('DATA/labeledTrainData.tsv', header = 0, delimiter='\\t', quoting =3)\ntest = pd.read_csv('DATA/testData.tsv', header = 0, delimiter='\\t', quoting =3)\nunlabeled_train = pd.read_csv('DATA/unlabeledTrainData.tsv', header = 0, delimiter='\\t', quoting=3)\n\nfrom KaggleWord2VecUtility import KaggleWord2VecUtility\n\n\nsentences = []\nfor review in train['reivew'] :\n sentences += KaggleWord2VecUtility.review_to_sentences(review, remove_stopwords=False)\n\nfor review in unlabeled_train['review']:\n sentences += KaggleWord2VecUtility.review_to_sentences(review, remove_stopwords=False)\n\n\nimport logging\nlogging.basicConfig(\n format = '%(asctime)s : %(levelname)s : %(message)s',\n level = logging.INFO\n)\n\nnum_features = 300\nmin_word_count = 40\nnum_workers = 4\ncontext = 10\ndownsampling = 1e-3\n\n\nfrom gensim.models import word2vec\n\n# word2vec 모델 만들어서 학습.\nmodel = word2vec.WordVec(sentences,\n workers = num_workers,\n size = num_features,\n min_count = min_word_count,\n window = context,\n sample = downsampling)\n\n\n# 학습 완료 후 필요없는 memory unload.\nmodel.init_sims(replace=True)\n\nmodel_name = '300features_40minwords_10text'\nmodel.save(model_name)\n\n\n# 학습된 모델 결과 탐색\n\n# 유사도 없는 단어 추출\nprint(model.wv.dosent_match('man woman child kitchen'.spilt())) # kitchen만 사람이 아님.\nprint(model.wv.dosent_match('france england germany berlin'.split())) # belin만 나라이름이 아님.\n\n# 가장 유사한 단어 추출\nprint(model.wv.most_similar('man'))\n\nprint(model.wv.most_similar('queen'))\n\n\n\n# Word2Vec 벡터화한 단어를 t-SNE로 시각화하기\n\nfrom sklearn.manifold import TSNE\nimport matplotlib as mpl\nimport matplotlib\n\n\n\n\n\n","sub_path":"NLP_TUTO2.py","file_name":"NLP_TUTO2.py","file_ext":"py","file_size_in_byte":1928,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"650397231","text":"import matplotlib.pyplot as pl\nimport numpy as np\n\nx=np.linspace(-3,20,100) #spaziatura lineare dati\nx=np.random.normal(loc=x,scale=0.25,size=len(x)) #aggiungi qualche errore\ny=1.2*x**2-0.3*x+2.8\ny=np.random.normal(loc=y,scale=1.5,size=len(y)) #aggiungi errori\n\npl.plot(x,y,'or')\n\npl.show()\n\ncc=np.polyfit(x,y,deg=2) #misura polinomio secondo grado\n\nxx=np.linspace(-3,21) #crea x-data per tracciare la misura\nyy=np.polyval(cc,xx) #calcola valori utilizzando cc\npl.plot(xx,yy,'-b')\ncc,cov= np.polyfit(x,y,deg=2,cov=True) #matrice convarianza\nnp.sqrt(cov.diagonal())\n\npl.show()\n","sub_path":"Lezione3/Linear_fit.py","file_name":"Linear_fit.py","file_ext":"py","file_size_in_byte":579,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"154345092","text":"import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom torch.distributions import Normal\n\ndef identity(x):\n \"\"\"Return input without any change.\"\"\"\n return x\n\n\nclass MLP(nn.Module):\n def __init__(self, \n input_size, \n output_size, \n hidden_sizes=(256,256,256), \n activation=F.relu,\n output_activation=identity,\n use_output_layer=True,\n ):\n super(MLP, self).__init__()\n\n self.input_size = input_size\n self.output_size = output_size\n self.hidden_sizes = hidden_sizes\n self.activation = activation\n self.output_activation = output_activation\n self.use_output_layer = use_output_layer\n\n # Set hidden layers\n self.hidden_layers = nn.ModuleList()\n in_size = self.input_size\n for next_size in self.hidden_sizes:\n fc = nn.Linear(in_size, next_size)\n in_size = next_size\n self.hidden_layers.append(fc)\n\n # Set output layers\n if self.use_output_layer:\n self.output_layer = nn.Linear(in_size, self.output_size)\n else:\n self.output_layer = identity\n\n def forward(self, x):\n for hidden_layer in self.hidden_layers:\n x = self.activation(hidden_layer(x))\n x = self.output_activation(self.output_layer(x))\n return x\n\n\nclass FlattenMLP(MLP):\n def forward(self, x, a):\n q = torch.cat([x,a], dim=-1)\n return super(FlattenMLP, self).forward(q)\n\n\nLOG_STD_MAX = 2\nLOG_STD_MIN = -20\n\nclass GaussianPolicy(MLP):\n def __init__(self, \n input_size, \n output_size, \n hidden_sizes=(128,128),\n activation=F.relu,\n ):\n super(GaussianPolicy, self).__init__(\n input_size=input_size,\n output_size=output_size,\n hidden_sizes=hidden_sizes,\n activation=activation,\n use_output_layer=False,\n )\n\n in_size = hidden_sizes[-1]\n\n # Set output layers\n self.mu_layer = nn.Linear(in_size, output_size)\n self.log_std_layer = nn.Linear(in_size, output_size)\n\n def clip_but_pass_gradient(self, x, l=-1., u=1.):\n clip_up = (x > u).float()\n clip_low = (x < l).float()\n clip_value = (u - x)*clip_up + (l - x)*clip_low\n return x + clip_value.detach()\n\n def apply_squashing_func(self, mu, pi, log_pi):\n mu = torch.tanh(mu)\n pi = torch.tanh(pi)\n # To avoid evil machine precision error, strictly clip 1-pi**2 to [0,1] range.\n log_pi -= torch.sum(torch.log(self.clip_but_pass_gradient(1 - pi.pow(2), l=0., u=1.) + 1e-6), dim=-1)\n return mu, pi, log_pi\n\n def forward(self, x):\n x = super(GaussianPolicy, self).forward(x)\n \n mu = self.mu_layer(x)\n log_std = torch.tanh(self.log_std_layer(x))\n log_std = LOG_STD_MIN + 0.5 * (LOG_STD_MAX - LOG_STD_MIN) * (log_std + 1)\n std = torch.exp(log_std)\n \n # https://pytorch.org/docs/stable/distributions.html#normal\n dist = Normal(mu, std)\n pi = dist.rsample()\n log_pi = dist.log_prob(pi).sum(dim=-1)\n mu, pi, log_pi = self.apply_squashing_func(mu, pi, log_pi)\n \n return mu, pi, log_pi","sub_path":"2-Intermediate/5_ML-Agents/sac_Unity/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":3329,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"544253944","text":"import sqlite3\n\ndef calendartable():\n #Set up the connection to the database and the cursor\n conn = sqlite3.connect('calendar.db')\n c = conn.cursor()\n\n #Creating the table for the ABT\n c.execute('CREATE TABLE IF NOT EXISTS calendarevents (id INT, title TEXT, start TEXT, end TEXT)')\n\n # # Write ABT into the Database\n # c.executemany('INSERT INTO first_abt (theDate, Day, Time, Module, Room, Capacity, Type, Registered, Over3,'\\\n # 'Authenticated, Associated, TARGET) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)', csv)\n # conn.commit()\n\ndef event_writting(id, title, start, end):\n #Set up the connection.\n conn = sqlite3.connect('calendar.db')\n c = conn.cursor()\n #Consolidate into an array\n theevent = [id, title, start, end]\n # Write ABT into the Database\n c.execute('INSERT INTO calendarevents (id, title, start, end)'\\\n 'VALUES (?, ?, ?, ?)', theevent)\n conn.commit()\n\n\ndef events():\n #Set up the connection to the database and the cursor\n conn = sqlite3.connect('occupancy.db')\n c = conn.cursor()\n\n #Creating the table for the ABT\n c.execute('CREATE TABLE IF NOT EXISTS eventsx'\\\n ' (Datey TEXT, Hour TEXT, Room TEXT, Event TEXT, description TEXT)')\n\n\ndef delete_relevent():\n #Set up the connection to the database and the cursor\n conn = sqlite3.connect('occupancy.db')\n c = conn.cursor()\n\n #Reset\n c.execute(\"DELETE FROM eventsx;\")\n\n#abt()\n\n#events()\n\n# calendartable()\n# event_writting(9, 'paulsimon', '2016-11-29T12:30:00', '2016-11-3T12:40:00')\n\n# conn = sqlite3.connect('calendar.db')\n# c = conn.cursor()\n# c.execute('ALTER TABLE calendarevents ADD COLUMN category string;')\n\n\n","sub_path":"database.py","file_name":"database.py","file_ext":"py","file_size_in_byte":1704,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"183825710","text":"import sys\nimport os\n\nimport igraph as ig\n\nfrom biomap import BioMap\nfrom deregnet.core import SubgraphFinder\nfrom utils import *\n\ndef main(argv):\n dataset = argv[1]\n graph_path = 'graphs/kegg_hsa_paper.graphml'\n if len(argv) > 2:\n graph_path = argv[2]\n graph = ig.Graph.Read_GraphML(graph_path)\n finder = SubgraphFinder(graph)\n #\n id_mapper = BioMap.get_mapper('hgnc')\n mutation_data = list(get_mutation_matrix(dataset))\n mutation_data[1] = id_mapper.map(mutation_data[1], FROM='ensembl', TO='entrez')\n patients = mutation_data[2]\n failed = []\n base_path = os.path.join('mode2', dataset)\n os.makedirs(base_path)\n for patient_id in patients:\n score = get_somatic_mutation_score(patient_id, mutation_data)\n result = finder.run_average_deregnet(score, min_size=10, time_limit=1200)\n path = os.path.join(base_path, patient_id)\n os.makedirs(path)\n try:\n result.to_graphml(path)\n except:\n failed.append(patient_id)\n with open(os.path.join(base_path, 'failed.txt'), 'w') as fp:\n for fail in failed:\n fp.write(fail+'\\n')\n\nif __name__ == '__main__':\n main(sys.argv)\n","sub_path":"old/mode2.py","file_name":"mode2.py","file_ext":"py","file_size_in_byte":1195,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"396149931","text":"import logging\n\nfrom flask import Flask, render_template\nfrom flask_ask import Ask, request, session, question, statement\n\nimport time\n\n\napp = Flask(__name__)\nask = Ask(app, \"/\")\nlogging.getLogger('flask_ask').setLevel(logging.DEBUG)\n\n@ask.launch\ndef launch():\n return get_new_fact()\n\n@ask.intent('GetNewFactIntent', mapping={'website': 'website'})\ndef get_new_fact():\n today = time.strftime('%B-%-d').lower()\n template = '{0}'.format(today)\n\n fact_text = render_template(template)\n return statement(fact_text).simple_card('Hoops History', fact_text)\n\n@ask.intent('AMAZON.HelpIntent')\ndef help():\n speech_text = 'You can ask me about what happened today in basketball history.'\n return question(speech_text).reprompt(speech_text).simple_card('Livy', speech_text)\n\n@ask.intent('AMAZON.StopIntent')\ndef stop():\n speech_text = 'Goodbye.'\n return statement(speech_text).simple_card('Hoops History', speech_text) \n\n@ask.intent('AMAZON.CancelIntent')\ndef cancel():\n speech_text = 'Goodbye.'\n return statement(speech_text).simple_card('Hoops History', speech_text) \n\n@ask.session_ended\ndef session_ended():\n return \"\", 200\n\n\nif __name__ == '__main__':\n app.run(debug=True)","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1180,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"165734549","text":"# -*- coding: utf-8 -*-\nimport scrapy\nfrom nba.items import zbb_vieoOrnews\nfrom urllib import parse\n\n\n# spider\n# 爬取直播吧 新闻 以及视频 只有地址\n# 长期更新类爬虫\n\n# web\n# 新闻展示页(多)\nclass TxVideoSpider(scrapy.Spider):\n name = 'zbb_news'\n allowed_domains = ['www.zhibo8.cc/nba/more.htm']\n start_urls = ['https://www.zhibo8.cc/nba/more.htm']\n\n\n start_urls_one = \"https://www.zhibo8.cc/nba/more.htm?label={0}\"\n team_list = [\n '勇士',\n '湖人',\n '火箭',\n '雷霆',\n '凯尔特人',\n '马刺',\n '尼克斯',\n '猛龙',\n '独行侠',\n '热火',\n '鹈鹕',\n '森林狼',\n '开拓者',\n '76人',\n '奇才',\n '老鹰',\n '其他']\n custom_settings = {\n \"ITEM_PIPELINES\": {\n 'nba.pipelines.MysqlTwistedPipeline': 50,\n # 'nba.pipelines.DuplicatesPipeline': 1\n },\n }\n\n def start_requests(self):\n for i in self.team_list:\n yield scrapy.Request(url=self.start_urls_one.format(i), callback=self.parse, meta={\"team_name\": i})\n\n def parse(self, response):\n item = zbb_vieoOrnews()\n zone = response.css('.dataList ul.articleList li ')\n for i in zone:\n detail_url = i.css(' span a::attr(href)').extract()[0]\n detail_url = parse.urljoin(response.url, detail_url)\n item['detail_url'] = detail_url\n item['title'] = i.css(' span a::text').extract()[0]\n item['title_time'] = i.css(' span.postTime::text').extract()[0]\n item['team_name'] = response.meta.get(\"team_name\", \"\")\n\n yield item\n","sub_path":"篮球NBA全站爬取测试/nba/build/lib/nba/spiders/zbb_news.py","file_name":"zbb_news.py","file_ext":"py","file_size_in_byte":1701,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"254640052","text":"#!/usr/bin/env python3\n\nimport pygame\n\nblack = (0, 0, 0)\nwhite = ( 255, 255, 255)\n\nclass Player(pygame.sprite.Sprite):\n\n\tdef __init__(self):\n\t\tsuper().__init__()\n\n\t\twidth = 20\n\t\theight = 15\n\n\t\tself.image = pygame.Surface([width, height])\n\t\tself.image.fill(black)\n\n\t\tself.rect = self.image.get_rect()\n\n\t\tself.rect.x = 100\n\t\tself.rect.y = 100\n\n\t\tself.joystick_count = pygame.joystick.get_count()\n\t\tif (self.joystick_count == 0):\n\t\t\tprint (\"Error, I didn't find any joysticks.\")\n\t\telse:\n\t\t\tself.my_joystick = pygame.joystick.Joystick(0)\n\t\t\tself.my_joystick.init()\n\n\tdef update(self):\n\t\tif (self.joystick_count != 0):\n\t\t\thoriz_axis_pos = self.my_joystick.get_axis(0)\n\t\t\tvert_size_pos = self.my_joystick.get_axis(1)\n\n\t\t\tself.rect.x = self.rect.x + horiz_axis_pos * 10 \n\t\t\tself.rect.y = self.recty.y + vert_axis_pos * 10\n\npygame.init()\nwindow_size = [700, 500]\nscreen = pygame.display.set_mode(window_size)\n\ndone = False\n\nclock = pygame.time.Clock()\n\nall_sprites_list = pygame.sprite.Group()\n\nplayer = Player()\n\nall_sprites_list.add(player)\n\nwhile not done:\n\tfor event in pygame.event.get():\n\t\tif (event.type == pygame.QUIT):\n\t\t\tdone = True\n\n\tscreen.fill(white)\n\tall_sprites_list.update()\n\tall_sprites_list.draw(screen)\n\n\tclock.tick(60)\n\n\tpygame.display.flip()\n\npygame.quit()","sub_path":"Sprites/move_sprite_game_controller.py","file_name":"move_sprite_game_controller.py","file_ext":"py","file_size_in_byte":1269,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"65932672","text":"from urllib.request import urlopen\nfrom bs4 import BeautifulSoup\ntry:\n html=urlopen(\"http://pythonscraping.com/pages/page1.html\")\n obj=BeautifulSoup(html.read(),\"lxml\")\n b_content=obj.nonExistingTag.anotherTag\nexcept AttributeError as e:\n print(\"Tag was not found\")\nelse:\n if b_content==None:\n print(\"Tag was not found\")\n else:\n print(b_content) ","sub_path":"web_scrapping/pseudo_err.py","file_name":"pseudo_err.py","file_ext":"py","file_size_in_byte":385,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"136869096","text":"# BSD 2-Clause License\n#\n# Copyright (c) 2021, Hewlett Packard Enterprise\n# All rights reserved.\n#\n# Redistribution and use in source and binary forms, with or without\n# modification, are permitted provided that the following conditions are met:\n#\n# 1. Redistributions of source code must retain the above copyright notice, this\n# list of conditions and the following disclaimer.\n#\n# 2. Redistributions in binary form must reproduce the above copyright notice,\n# this list of conditions and the following disclaimer in the documentation\n# and/or other materials provided with the distribution.\n#\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\n# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\nfrom os import path\n\nfrom ..error import SSConfigError\n\n\nclass EntityFiles:\n \"\"\"EntityFiles are the files a user wishes to have available to\n models and nodes within SmartSim. Each entity has a method\n `entity.attach_generator_files()` that creates one of these\n objects such that at generation time, each file type will be\n present within the generated model or node directory.\n\n Tagged files are the configuration files for a model that\n can be searched through and edited by the ModelWriter.\n\n Copy files are files that a user wants to copy into the\n model or node directory without searching through and\n editing them for tags.\n\n Lastly, symlink can be used for big datasets or input\n files that a user just wants to have present in the directory\n without necessary having to copy the entire file.\n \"\"\"\n\n def __init__(self, tagged, copy, symlink):\n \"\"\"Initialize an EntityFiles instance\n\n :param tagged: tagged files for model configuration\n :type tagged: list of str\n :param copy: files or directories to copy into model\n or node directories\n :type copy: list of str\n :param symlink: files to symlink into model or node\n directories\n :type symlink: list of str\n \"\"\"\n self.tagged = tagged\n self.copy = copy\n self.link = symlink\n self._check_files()\n\n def _check_files(self):\n \"\"\"Ensure the files provided by the user are of the correct\n type and actually exist somewhere on the filesystem.\n\n :raises SSConfigError: If a user provides a directory within\n the tagged files.\n \"\"\"\n\n # type check all files provided by user\n self.tagged = self._type_check_files(self.tagged, \"Tagged\")\n self.copy = self._type_check_files(self.copy, \"Copyable\")\n self.link = self._type_check_files(self.link, \"Symlink\")\n\n # check the paths provided by the user and ensure\n # that no directories were provided as tagged files\n for i in range(len(self.tagged)):\n self.tagged[i] = self._check_path(self.tagged[i])\n if path.isdir(self.tagged[i]):\n raise SSConfigError(\"Directories cannot be listed in tagged files\")\n\n for i in range(len(self.copy)):\n self.copy[i] = self._check_path(self.copy[i])\n for i in range(len(self.link)):\n self.link[i] = self._check_path(self.link[i])\n\n def _type_check_files(self, file_list, file_type):\n \"\"\"Check the type of the files provided by the user.\n\n :param file_list: either tagged, copy, or symlink files\n :type file_list: list of str\n :param file_type: name of the file type e.g. \"tagged\"\n :type file_type: str\n :raises TypeError: if incorrect type is provided by user\n :return: file list provided\n :rtype: list of str\n \"\"\"\n if file_list:\n if not isinstance(file_list, list):\n if isinstance(file_list, str):\n file_list = [file_list]\n else:\n raise TypeError(\n f\"{file_type} files given were not of type list or str\"\n )\n else:\n if not all(isinstance(f, str) for f in file_list):\n raise TypeError(f\"Not all {file_type} files were of type str\")\n return file_list\n\n def _check_path(self, file_path):\n \"\"\"Given a user provided path-like str, find the actual path to\n the directory or file and create a full path.\n\n :param file_path: path to a specific file or directory\n :type file_path: str\n :raises SSConfigError: if file or directory does not exist\n :return: full path to file or directory\n :rtype: str\n \"\"\"\n full_path = path.abspath(file_path)\n if path.isfile(full_path):\n return full_path\n if path.isdir(full_path):\n return full_path\n raise SSConfigError(f\"File or Directory {file_path} not found\")\n","sub_path":"smartsim/entity/files.py","file_name":"files.py","file_ext":"py","file_size_in_byte":5511,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"313117932","text":"import komand\nfrom .schema import SubmitUrlForScanInput, SubmitUrlForScanOutput, Input, Output, Component\n# Custom imports below\nfrom komand.exceptions import PluginException\nimport requests\nimport json\n\n\nclass SubmitUrlForScan(komand.Action):\n\n def __init__(self):\n super(self.__class__, self).__init__(\n name='submit_url_for_scan',\n description=Component.DESCRIPTION,\n input=SubmitUrlForScanInput(),\n output=SubmitUrlForScanOutput())\n\n def run(self, params=None):\n if params is None:\n params = {}\n body = {'url': params[Input.URL]}\n if params[Input.PUBLIC]:\n body['public'] = 'on'\n\n response = requests.post(f'{self.connection.server}/scan', headers=self.connection.headers, data=body)\n\n try:\n out = response.json()\n except json.decoder.JSONDecodeError:\n raise PluginException(cause=\"Received an unexpected response from the Urlscan API. \",\n assistance=f\"(non-JSON or no response was received). Response was: {response.text}\")\n\n if 'uuid' in out:\n return {Output.SCAN_ID: out['uuid']}\n\n if 'status' in out:\n if out['status'] == 401:\n # {'message': \"No API key supplied. Send the key using the 'API-Key' header\", 'status': 401}\n raise PluginException(preset=PluginException.Preset.API_KEY)\n\n # {\n # \"message\": \"Missing URL properties\",\n # \"description\": \"The URL supplied was not OK, please specify it including the protocol, host and path (e.g. http://example.com/bar)\",\n # \"status\": 400\n # }\n\n if ('message' in out) and ('description' in out):\n raise PluginException(cause=f\"{out['message']}. \", assistance=f\"{out['description']}.\")\n\n raise PluginException(cause=\"Received an unexpected response from the Urlscan API. \",\n assistance=f\"If the problem persists, please contact support. Response was: {response.text}\")\n","sub_path":"urlscan/komand_urlscan/actions/submit_url_for_scan/action.py","file_name":"action.py","file_ext":"py","file_size_in_byte":2053,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"355462886","text":"from rest_framework.views import APIView\nfrom django.http import HttpRequest\nfrom rest_framework.request import Request\nfrom rest_framework.response import Response\nfrom db.service import DB\nfrom db.service import RedisCache\nfrom json import dumps, loads\nimport redis\nimport os\n\n\nDEFAULT_SETTINGS = ['localhost', 6379, 1]\nDOCKER_SETTINGS = [os.environ.get('REDIS_HOST'), os.environ.get('REDIS_PORT'), os.environ.get('REDIS_DB')]\ncache = redis.Redis(host=DEFAULT_SETTINGS[0], port=DEFAULT_SETTINGS[1], db=DEFAULT_SETTINGS[2])\n\nclass ScheduleView(APIView):\n def __init__(self):\n super().__init__()\n self.database = DB()\n self.cache = RedisCache(cache)\n\n def get(self, request: Request):\n id = request.query_params.get('id', None)\n if id:\n match = self.cache.get(id)\n if match:\n return Response(dumps(match), status=200)\n match = self.database.match_id(id)\n return Response(dumps(match), status=200)\n try:\n team_name = request.query_params.get('team_name', None)\n if team_name:\n match = self.database.match_schedule_team(team_name)\n return Response(dumps(match), status=200)\n else:\n match = self.database.match_schedule()\n return Response(dumps(match), status=200)\n except:\n return Response(status=400)\n\n def post(self, request: HttpRequest):\n data = loads(request.body)\n try:\n self.database.match_update(data)\n self.cache.delete(data['id'])\n return Response(status=200)\n except:\n return Response(status=400)\n\n def put(self, request: HttpRequest):\n data = loads(request.body)\n try:\n self.database.match_create(data)\n return Response(status=200)\n except:\n return Response(status=400)\n\n def delete(self, request: HttpRequest):\n data = loads(request.body)\n try:\n self.database.match_delete(data)\n self.cache.delete(data['id'])\n return Response(status=200)\n except:\n return Response(status=400)\n\n","sub_path":"schedule/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2200,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"164137471","text":"n_name = int(input('Enter number of names : '))\nlen_name = []\ninitial_list = []\nsort_list = []\nfor i in range(n_name):\n initial_name = ''\n fullname = input('Enter name : ')\n split_name = fullname.split()\n for word in split_name:\n if word[0].isupper() == True:\n initial_name += word[0]\n if initial_name != '':\n initial_list.append(initial_name)\nfor i in sorted(sorted(initial_list), key = len, reverse = True):\n print(i)\n\n","sub_path":"TheInternship2020/SortingAcronyms.py","file_name":"SortingAcronyms.py","file_ext":"py","file_size_in_byte":464,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"418693839","text":"import urllib.request as urllib2\n\ndef download(url, num_retries=2):\n\tprint ('Downloading:',url)\n\ttry:\n\t\thtml = urllib2.urlopen(url).read().decode('utf-8')\n\texcept urllib2.URLError as e:\n\t\tprint ('Download error:', e.reason)\n\t\thtml = None\n\t\tif num_retries > 0:\n\t\t\tif hasattr(e, 'code') and 500 <= e.code < 600:\n\t\t\t\t#recursively retry 5xx HTTP errors\n\t\t\t\treturn download(url, num_retries-1)\n\treturn html\n\t\nprint(download('http://example.webscraping.com/'))","sub_path":"chapter 1/use of urllib2.py","file_name":"use of urllib2.py","file_ext":"py","file_size_in_byte":454,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"601905107","text":"import sys\n\nimport numpy as np\nnp.random.seed(5)\nnp.set_printoptions(threshold=sys.maxsize)\nfrom sklearn.model_selection import train_test_split\n\nimport pandas as pd\n\nimport argparse\n\nparser = argparse.ArgumentParser(description='Read csv file to run RFR')\nparser.add_argument('csv_file', metavar='csv_filename', type=str, help='csv data file path')\nargs = parser.parse_args()\n\n# Read data file \nchoi_df = pd.read_csv(args.csv_file,encoding = \"ISO-8859-1\")\nchoi_df = choi_df.fillna(0.0)\ndata = np.asarray(choi_df.values.tolist())\n\n# Record list of variables\nvariables = choi_df.columns.tolist()[:-1]\n\n# Ready to do operations\nindependent_vars = data[:,:-1].astype('double') # Last column is dependent\ndependent_vars = data[:,-1].astype('double')\n\nnum_rows = np.shape(independent_vars)[0]\nnum_vars = np.shape(independent_vars)[1]\n\n# Do some randomization\nidx = np.random.choice(np.arange(num_vars), num_vars, replace=False)\nshuffled_vars = independent_vars[:,idx].astype('double') # Last column is dependent\n\n# Shuffling variable names\nnew_variables = []\nfor i in range(len(variables)):\n id_val = idx[i]\n new_variables.append(variables[id_val])\n\n# Make 40 folds\n# Split the data into training and testing sets\n\nnum_folds = 40\nfor fold in range(num_folds):\n shuffled_vars_train, shuffled_vars_test, dependent_vars_train, dependent_vars_test = train_test_split(shuffled_vars, dependent_vars.reshape(-1,1), train_size=0.8, random_state=fold)\n\n train_data = np.concatenate((shuffled_vars_train,dependent_vars_train),axis=-1)\n test_data = np.concatenate((shuffled_vars_test,dependent_vars_test),axis=-1)\n\n # Save the file\n np.savetxt('folds/train_'+f'{fold:02}'+'.csv',train_data,delimiter=',')\n np.savetxt('folds/test_'+f'{fold:02}'+'.csv',test_data,delimiter=',')\n \n ","sub_path":"Method_Comparison/policy4/make_folds.py","file_name":"make_folds.py","file_ext":"py","file_size_in_byte":1793,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"71032593","text":"from app.platform.appium.android.TAapt import *\n\nfrom app.platform.core.CaseObject import *\n\n'''\n# 基础案例对象\n# 页面元素步骤\n'''\n\n__author__ = 'banketree'\n\n\n# android 测试用例\nclass CaseObjectIOS(CaseObject):\n logger = None\n apkPath = None\n\n def __init__(self, dirPath, apkPath):\n self.logger = TLog(dirPath, \"\" + time.strftime('%Y%m%d%H%M%S', time.localtime()))\n self.apkPath = apkPath\n super().__init__(self.logger)\n\n def __del__(self):\n super().__del__()\n if (self.logger != None):\n del self.logger\n\n def getExecutor(self, ip=\"localhost\", port=\"4723\"):\n try:\n self.logger.info(u\"开始初始化appium client ip:\" + ip + \" port:\" + port)\n appiumDesktop = TAppiumDesktop(self.getDesiredCaps(), ip, port); # 设备连接属性\n return appiumDesktop\n except Exception as e:\n self.logger.error(u\"appium client error:\" + str(e))\n return None\n\n def getDesiredCaps(self):\n desiredCaps = {}\n adb = None;\n aapk = None\n\n try:\n adb = TAdb();\n aapk = TAapk(self.apkPath)\n\n devices = adb.getAttachedDevices()\n if (len(devices) <= 0):\n raise Exception(\"未检测到设备\")\n device = devices[0]\n # for device in devices: //暂时第一台\n appPackage = aapk.getApkPackageName();\n appActivity = aapk.getApkActivity().strip();\n apkVersionName = aapk.getApkVersionName();\n appVersionName = adb.getAppVersionName(appPackage);\n\n phoneInfo = adb.getPhoneInfo(device)\n desiredCaps['platformName'] = 'Android'\n desiredCaps['platformVersion'] = phoneInfo['system-realease'] # '7.1.1'\n desiredCaps['deviceName'] = phoneInfo['device'] # 'Test26'\n desiredCaps['app'] = self.apkPath\n desiredCaps['appPackage'] = appPackage\n desiredCaps['appActivity'] = appActivity\n desiredCaps['resetKeyboard'] = True # 将键盘给隐藏起来9\n desiredCaps['noReset'] = True # 不重新安装\n desiredCaps['udid'] = device # 应用app进程标识\n # desiredCaps['wdaLocalPort'] = \"8001\" # 默认端口转发 8100\n if (apkVersionName != appVersionName):\n desiredCaps['noReset'] = False # 重新安装\n except Exception as ex:\n print(ex);\n finally:\n if (adb != None):\n del adb;\n if (aapk != None):\n del aapk;\n return desiredCaps;\n\n\ndef getLogName(self):\n return self.logger.getFileName()\n\n\nif __name__ == '__main__':\n pass\n","sub_path":"app/platform/appium/ios/CaseObjectIOS.py","file_name":"CaseObjectIOS.py","file_ext":"py","file_size_in_byte":2727,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"591954868","text":"\"\"\"\nLanguage detector implementation starter\n\"\"\"\n\n\nfrom lab_3.main import tokenize_by_sentence\nfrom lab_3.main import encode_corpus\nfrom lab_3.main import NGramTrie\nfrom lab_3.main import LetterStorage\nfrom lab_3.main import LanguageDetector\n\nif __name__ == '__main__':\n unknown_file = open('lab_3/unknown_Arthur_Conan_Doyle.txt', encoding='utf-8')\n german_file = open('lab_3/Thomas_Mann.txt', encoding='utf-8')\n english_file = open('lab_3/Frank_Baum.txt', encoding='utf-8')\n\n text_unk = tokenize_by_sentence(unknown_file.read())\n text_ger = tokenize_by_sentence(german_file.read())\n text_eng = tokenize_by_sentence(english_file.read())\n english_file.close()\n german_file.close()\n unknown_file.close()\n\n letter_storage = LetterStorage()\n letter_storage.update(text_eng)\n letter_storage.update(text_ger)\n letter_storage.update(text_unk)\n\n eng_encoded = encode_corpus(letter_storage, text_eng)\n unk_encoded = encode_corpus(letter_storage, text_unk)\n ger_encoded = encode_corpus(letter_storage, text_ger)\n\n language_detector = LanguageDetector((3, 4, 5), 1000)\n language_detector.new_language(eng_encoded, 'english')\n language_detector.new_language(ger_encoded, 'german')\n\n ngram_unknown = NGramTrie(4)\n ngram_unknown.fill_n_grams(unk_encoded)\n\n language_log_probability_dict = language_detector.detect_language(ngram_unknown.n_grams)\n\n if language_log_probability_dict['german'] >\\\nlanguage_log_probability_dict['english']:\n RESULT = 'english'\n else:\n RESULT = 'german'\n\n print('this is a {} text.'.format(RESULT))\n\n # DO NOT REMOVE NEXT LINE - KEEP IT INTENTIONALLY LAST\n assert RESULT == 'german', 'Not working'\n","sub_path":"lab_3/start.py","file_name":"start.py","file_ext":"py","file_size_in_byte":1707,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"202772356","text":"#import timeit\n\n#setup = '''\nimport numpy as np\nimport pandas as pd\nfrom sklearn.ensemble import AdaBoostClassifier\nfrom sklearn import metrics\nimport matplotlib.pyplot as plt\nfrom sklearn.preprocessing import StandardScaler\n\n\nD_tr = pd.read_csv(\"training-steel.csv\", header = None)\nD_te = pd.read_csv(\"testing-steel.csv\", header = None)\nD_tr = D_tr.to_numpy()\nD_te = D_te.to_numpy()\nx_tr = D_tr[:,0:27]\ny_tr = D_tr[:,27]\nx_te = D_te[:,0:27]\ny_te = D_te[:,27]\n\nstdev = np.std(D_tr, axis=0)\nprint(stdev)\n\n#scaler = StandardScaler()\n#scaler.fit(x_tr)\n#x_tr = scaler.transform(x_tr)\n#x_te = scaler.transform(x_te)\n#print(np.std(x_tr, axis=0))\n\n#training\nadaboost = AdaBoostClassifier(n_estimators=50, learning_rate=0.1, random_state = 0)\nadaboost.fit(x_tr, y_tr)\n\n#'''\n#my_code = '''\n\n#testing\ny_pred = adaboost.predict(x_te)\nerr = sum(abs(y_pred-y_te))\n\nfpr, tpr, thresholds = metrics.roc_curve(y_te, adaboost.decision_function(x_te))\nfpr1, tpr1, thresholds1 = metrics.roc_curve(y_tr, adaboost.decision_function(x_tr))\n\n#confusion matrix\nCM=np.zeros((2,2))\nfor n in range(275):\n if y_pred[n]==1:\n if y_te[n]==1:\n CM[0,0]=CM[0,0]+1\n else:\n CM[0,1]=CM[0,1]+1\n else:\n if y_te[n]==1:\n CM[1,0]=CM[1,0]+1\n else:\n CM[1,1]=CM[1,1]+1\n#'''\n#print (timeit.timeit(setup = setup, stmt = my_code, number = 1))\n \nplt.plot(fpr, tpr)\nplt.plot(fpr1, tpr1)\nplt.legend(['test', 'train'])\nplt.xlabel('FPR')\nplt.ylabel('TPR')\nplt.grid()\nplt.show()\nprint(CM)","sub_path":"adaboost-training-testing.py","file_name":"adaboost-training-testing.py","file_ext":"py","file_size_in_byte":1542,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"254676486","text":"# a program which asks the user to enter their age in years \n# (Assume that the user always enters an integer) and based on\n# the following conditions, prints the output exactly as in the\n# following format (as highlighted in yellow):\n\n# When age is less than or equal to 0, your program should print\n# UNBORN\n\n# When age is greater than 0 and less than or equal to 150, \n# your program should print\n# ALIVE\n\n# When age is greater than 150, your program should print\n# VAMPIRE\n\n# Type your code here\nyour_year = input(\"please enter your year:\" )\nyour_year = int(your_year)\nif your_year <= 0:\n print(\"UNBORN\")\nelif your_year > 0 and your_year <= 150:\n print(\"ALIVE\")\nelse:\n print(\"VAMPIRE\")\n","sub_path":"04 - Exam 2/Part3.py","file_name":"Part3.py","file_ext":"py","file_size_in_byte":699,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"310806144","text":"import settings\r\n\r\ndef scrapeAlbum(setting, albumURL):\r\n from imgurpython import ImgurClient\r\n from image_scraping import saveImage\r\n from database_tools import getImgurAlbums, addImgurAlbum\r\n\r\n start = albumURL.find('''/a/''')\r\n\r\n if (start == -1):\r\n return \"This was not an album.\"\r\n\r\n if ('#' in albumURL):\r\n end = albumURL.find('#')\r\n else:\r\n end = len(albumURL)\r\n\r\n album_id = albumURL[start+3:end]\r\n\r\n if (album_id in getImgurAlbums()):\r\n return \"That album was scraped already.\"\r\n\r\n client_id, client_secret = settings.getImgurToken().split(',')\r\n\r\n client = ImgurClient(client_id, client_secret)\r\n\r\n try:\r\n images = client.get_album_images(album_id)\r\n except:\r\n return \"That album does not exist.\"\r\n\r\n addImgurAlbum(album_id)\r\n\r\n count = 0\r\n\r\n for image in images:\r\n lol = saveImage(setting, image.link)\r\n count += 1\r\n\r\n return count\r\n\r\ndef scrapeAlbumMessage(setting, albumURL):\r\n try:\r\n bufferMsg = scrapeAlbum(setting, albumURL)\r\n count = int(bufferMsg)\r\n return \"I saved *{}* new images in the folder `{}`.\".format(count, setting)\r\n except ValueError:\r\n return bufferMsg","sub_path":"tools/imgur.py","file_name":"imgur.py","file_ext":"py","file_size_in_byte":1223,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"291888384","text":"# -*- coding: utf-8 -*-\nimport base64\nfrom pydesx.pydes import *\nimport requests\nfrom xml.dom import minidom\nimport sys\nfrom workflow import Workflow3\nimport subprocess\nimport threading\nimport Queue\nimport re\nimport pickle\n\nreload(sys)\nsys.setdefaultencoding( \"utf-8\" )\n\n\nclass Ping(threading.Thread):\n\n def __init__(self, queue):\n threading.Thread.__init__(self)\n self.__queue = queue\n self.__result = None\n\n def __execute_cmd(self, cmd):\n p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)\n out, _ = p.communicate()\n out_list = out.splitlines()\n return out_list\n\n def get_result(self):\n return self.__result\n\n def run(self):\n while True:\n ip = self.__queue.get()\n cmd = \"./sudo.sh ./bin/fping -e -t300 %s\" % ip\n self.__result = self.__execute_cmd(cmd)\n self.__queue.task_done()\n\nclass VPNServer:\n\n def __init__(self):\n pass\n self.__des_key = \"A2U7vzy9\"\n self.__update_server_url = \"https://www.189host.com/123/en.list\"\n \n def __execute_cmd(self, cmd):\n p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)\n out, _ = p.communicate()\n out_list = out.splitlines()\n return out_list\n\n def __decode(self, s):\n k = des(self.__des_key, ECB, None, pad=None, padmode=None)\n org_data = base64.b64decode(s)\n out_data = k.decrypt(org_data)\n return out_data.decode(\"utf-8\")\n\n def __check_cache(self):\n try:\n with open(\"server_cache.txt\", \"r\") as f:\n data = f.read()\n if data and data != \"\":\n return data\n else :\n return None\n except:\n return None\n \n def get_connectioned_server(self):\n cmd = \"ps aux | grep obfuscated-ssh\"\n out_list = self.__execute_cmd(cmd)\n if None or len(out_list) == 0 :\n return None\n res = \"(\\d+\\.\\d+\\.\\d+\\.\\d+)\"\n for out in out_list:\n m = re.search(res, out)\n if None != m:\n return unicode(m.group(1), \"utf-8\")\n return None\n\n def get_time_delay(self, server_list):\n self.__execute_cmd(\"./sudo.sh\")\n queue = Queue.Queue()\n t_list = []\n for i in range(len(server_list)):\n t = Ping(queue)\n t.setDaemon(True)\n t.start()\n t_list.append(t)\n\n for server_ip in server_list.keys():\n queue.put(server_ip)\n queue.join()\n\n res = \"(\\d+\\.\\d+\\.\\d+\\.\\d+)\\sis\\salive\\s\\((.*)\\sms\\)\"\n new_server_list = {}\n for t in t_list:\n ret = t.get_result()\n if None != ret and 0 < len(ret):\n m = re.search(res, ret[0])\n if m:\n ip = unicode(m.group(1), \"utf-8\")\n delay = unicode(m.group(2), \"utf-8\")\n new_server_list[ip] = (server_list[ip][0],\n server_list[ip][1],\n server_list[ip][2],\n server_list[ip][3],\n server_list[ip][4],\n server_list[ip][5],\n delay)\n return new_server_list\n\n def get_server_list(self):\n data = self.__check_cache()\n if None == data:\n s = requests.session()\n r = s.get(self.__update_server_url, verify=False)\n data = r.text\n try:\n with open(\"server_cache.txt\", \"w\") as f:\n f.write(data)\n except:\n pass\n\n decode_data = self.__decode(data)\n xml_text = decode_data.replace(\"\", \"\").rstrip('\\0')\n\n tree = minidom.parseString(xml_text)\n root = tree.documentElement\n server_list = {}\n for row_node in root.getElementsByTagName(\"Row\"):\n server_name = row_node.getElementsByTagName(u\"服务器\")[0].childNodes[0].data.strip()\n server_ip = row_node.getElementsByTagName(u\"服务器地址\")[0].childNodes[0].data.strip()\n server_ssh_port = row_node.getElementsByTagName(u\"SSH端口\")[0].childNodes[0].data.strip()\n server_tcp_port = row_node.getElementsByTagName(u\"TCP端口\")[0].childNodes[0].data.strip()\n server_udp_port = row_node.getElementsByTagName(u\"UDP端口\")[0].childNodes[0].data.strip()\n server_ssh_type = row_node.getElementsByTagName(u\"SSH类型\")[0].childNodes[0].data.strip()\n server_des = row_node.getElementsByTagName(u\"描述\")[0].childNodes[0].data.strip()\n server_list[server_ip] = (server_name, server_ssh_port, server_tcp_port, server_udp_port, server_ssh_type, server_des)\n return server_list\n\n\ndef dump(obj):\n try:\n dump_data = pickle.dumps(obj)\n with open(\"serverlist.dump\", \"wb\") as f:\n f.write(dump_data)\n except:\n return False\n return True\ndef dump_load():\n obj = None\n try:\n with open(\"serverlist.dump\", \"rb\") as f:\n dump_data = f.read()\n obj = pickle.loads(dump_data)\n except:\n return None\n return obj\n\ndef load_user():\n out = None\n try:\n with open(\"pass.txt\", \"r\") as f:\n data = f.read()\n out = data.split('|')\n except :\n return None\n return out\n\nSERVER_NAME = 0\nSERVER_SSH_PORT = 1\nSERVER_TCP_PORT = 2\nSERVER_UDP_PORT = 3\nSERVER_SSH_TYPE = 4\nSERVER_DES = 5\nDELAY = 6\n\n\ndef main(wf):\n \n userinfo = load_user()\n vpn_server = VPNServer()\n \n if None == userinfo or 3!=len(userinfo):\n wf.add_item(title=\"请设置VPN账号信息\",\n subtitle=\"使用vpnset命令设置,例:vpnset 用户名|密码|SSH监听端口\",\n valid=True,\n largetext=\"test4\",\n icon=\"vpn.ico\")\n wf.send_feedback()\n else:\n if 2 == len(sys.argv):\n is_re = False\n if \"r\" == sys.argv[1]:\n is_re = True\n server_list = dump_load()\n if is_re or None == server_list:\n server_list = vpn_server.get_server_list()\n server_list = vpn_server.get_time_delay(server_list)\n dump(server_list)\n connectioned_server = vpn_server.get_connectioned_server()\n ctitle = \"当前没有连接服务器\"\n csubtitle = \"请选择服务器连接\"\n if None != connectioned_server:\n ctitle = \"当前连接服务器[%s]\" % server_list[connectioned_server][SERVER_NAME]\n csubtitle = connectioned_server\n wf.add_item(title=ctitle,\n subtitle=csubtitle,\n valid=False,\n uid=u\"0\",\n largetext=\"0\",\n icon=\"vpn.ico\")\n for server_ip, server_info in server_list.items():\n sub_title = \"IP: %s\\t(%s ms)\" % (server_ip, server_info[DELAY])\n arg = \"%s|%s|%s|%s|%s\" % (server_ip, server_info[SERVER_SSH_PORT], userinfo[0], userinfo[1], userinfo[2])\n wf.add_item(title=server_info[0],\n subtitle=sub_title,\n arg=arg,\n uid=server_info[DELAY],\n valid=True,\n largetext=\"test4\",\n icon=\"vpn.ico\")\n wf.send_feedback()\n\nif __name__ == '__main__':\n wf = Workflow3()\n log = wf.logger\n sys.exit(wf.run(main))","sub_path":"vpn2.py","file_name":"vpn2.py","file_ext":"py","file_size_in_byte":7833,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"45638395","text":"# CP template Version 1.006\nimport os\nimport sys\nimport itertools\nimport collections\n# not for python < 3.9\n# from functools import cmp_to_key, reduce, partial, cache\nfrom functools import cmp_to_key, reduce, partial\nfrom itertools import product\nfrom collections import deque, Counter, defaultdict as dd\nfrom math import log, log2, ceil, floor, gcd, sqrt\nimport math\nfrom heapq import heappush, heappop\nfrom bisect import bisect_left as bl, bisect_right as br\nDEBUG = False\n\n\ndef main(f=None):\n init(f)\n # sys.setrecursionlimit(10**9)\n # ####################################\n # ######## INPUT AREA BEGIN ##########\n\n x, y = map(int, input().split())\n y *= 100\n\n # ######## INPUT AREA END ############\n # ####################################\n\n #wrap = Wrap(1000000000, 999999999)\n #print(wrap[0])\n #print(wrap[000])\n #idx = br(wrap, wrap[0], 0, 2000000001)\n #print(idx)\n\n q, r = divmod(y, x)\n\n nume = y - q*x - x\n deno = q - 99\n\n if deno == 0:\n print(-1)\n return\n\n n = nume / deno\n\n if n > 0:\n print(math.ceil(n))\n else:\n print(-1)\n\nclass Wrap:\n def __init__(s, X, Y):\n s.X = X\n s.Y = Y\n pass\n\n def __getitem__(s, n):\n return (s.Y + n) * 100 // (s.X + n)\n\n\n# #############################################################################\n# #############################################################################\n# ############################## TEMPLATE AREA ################################\n# #############################################################################\n# #############################################################################\n\nenu = enumerate\n\n\ndef argmax(arr):\n return max(enumerate(arr), key=lambda x: x[1])\n\n\ndef argmin(arr):\n return min(enumerate(arr), key=lambda x: x[1])\n\n\ndef For(*args):\n return itertools.product(*map(range, args))\n\n\ndef copy2d(mat):\n return [row[:] for row in mat]\n\n\ndef Mat(h, w, default=None):\n return [[default for _ in range(w)] for _ in range(h)]\n\n\ndef nDim(*args, default=None):\n if len(args) == 1:\n return [default for _ in range(args[0])]\n else:\n return [nDim(*args[1:], default=default) for _ in range(args[0])]\n\n\ndef setStdin(f):\n global DEBUG, input\n DEBUG = True\n sys.stdin = open(f)\n input = sys.stdin.readline\n\n\ndef init(f=None):\n global input\n input = sys.stdin.readline # by default\n if os.path.exists(\"o\"):\n sys.stdout = open(\"o\", \"w\")\n if f is not None:\n setStdin(f)\n else:\n if len(sys.argv) == 1:\n if os.path.isfile(\"in/i\"):\n setStdin(\"in/i\")\n elif os.path.isfile(\"i\"):\n setStdin(\"i\")\n elif len(sys.argv) == 2:\n setStdin(sys.argv[1])\n else:\n assert False, \"Too many sys.argv: %d\" % len(sys.argv)\n\n\n# Mod #\nclass Mod:\n MOD = 10**9 + 7\n maxN = 5\n FACT = [0] * maxN\n INV_FACT = [0] * maxN\n\n @staticmethod\n def setMOD(n): Mod.MOD = n\n\n @staticmethod\n def add(x, y): return (x+y) % Mod.MOD\n\n @staticmethod\n def multiply(x, y): return (x*y) % Mod.MOD\n\n @staticmethod\n def power(x, y):\n if y == 0:\n return 1\n elif y % 2:\n return Mod.multiply(x, Mod.power(x, y-1))\n else:\n a = Mod.power(x, y//2)\n return Mod.multiply(a, a)\n\n @staticmethod\n def inverse(x):\n return Mod.power(x, Mod.MOD-2)\n\n @staticmethod\n def divide(x, y):\n return Mod.multiply(x, Mod.inverse(y))\n\n @staticmethod\n def allFactorials():\n Mod.FACT[0] = 1\n for i in range(1, Mod.maxN):\n Mod.FACT[i] = Mod.multiply(i, Mod.FACT[i-1])\n\n @staticmethod\n def inverseFactorials():\n n = len(Mod.INV_FACT)\n Mod.INV_FACT[n-1] = Mod.inverse(Mod.FACT[n-1])\n for i in range(n-2, -1, -1):\n Mod.INV_FACT[i] = Mod.multiply(Mod.INV_FACT[i+1], i+1)\n\n @staticmethod\n def coeffBinom(n, k):\n if n < k:\n return 0\n return Mod.multiply(Mod.FACT[n],\n Mod.multiply(Mod.INV_FACT[k], Mod.INV_FACT[n-k]))\n\n @staticmethod\n def sum(it):\n res = 0\n for i in it:\n res = Mod.add(res, i)\n return res\n# END Mod #\n\n\ndef dprint(*args):\n if DEBUG:\n print(*args)\n\n\ndef pfast(*args, end=\"\\n\", sep=' '):\n sys.stdout.write(sep.join(map(str, args)) + end)\n\n\ndef parr(arr):\n for i in arr:\n print(i)\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"binarySearch/1072_게임.py","file_name":"1072_게임.py","file_ext":"py","file_size_in_byte":4532,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"353851323","text":"def my_sort(*args):\n try:\n for item in args:\n if isinstance(item, str):\n raise ValueError\n except ValueError as e:\n print(\"This is error \", e)\n else:\n print(args)\n return sorted(args)\n\n\nprint(my_sort(*[1, 4, 2, 465, 9, 15, 'hi']))\n","sub_path":"l3/z2l3.py","file_name":"z2l3.py","file_ext":"py","file_size_in_byte":294,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"372514390","text":"#!/usr/bin/python3\r\n#ConvertXLSXtoCSV.py\r\n#Created by Jeff Weltman\r\n#https://github.com/jeffweltman/python_scripts\r\n#v1.1 11/02/2017\r\n#Requires openpyxl package\r\n\r\ndef main():\r\n import os\r\n import openpyxl\r\n import csv\r\n target_dir = ('Documents') # set target directory\r\n for file in os.listdir(target_dir):\r\n filename = os.fsdecode(file)\r\n if filename.endswith('.xlsx'): #looking only at Excel xlsx docs\r\n book = filename.rstrip('.xlsx') # this strips the extension\r\n fullpath = target_dir + \"/\" + filename\r\n success = '{} converted to CSV.'.format(book)\r\n from openpyxl import load_workbook\r\n wb = load_workbook(fullpath)\r\n sh = wb.get_active_sheet()\r\n with open(fullpath.rstrip('.xlsx') + '.csv', 'w') as f:\r\n c = csv.writer(f)\r\n for r in sh.rows: \r\n c.writerow([cell.value for cell in r])\r\n print(success) # prints successful conversions to console for each file \r\n f.close()\r\n\r\nif __name__ == \"__main__\": main()\r\n","sub_path":"ConvertXLSXtoCSV.py","file_name":"ConvertXLSXtoCSV.py","file_ext":"py","file_size_in_byte":1121,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"299556260","text":"try:\n import sys\n import time\n from selenium import webdriver\n from selenium.webdriver.common.by import By\n from selenium.common.exceptions import TimeoutException\n from selenium.webdriver.support.ui import WebDriverWait\n from selenium.webdriver.support import expected_conditions as EC\n from common import SECTION, OPTIONS, print_log_msg, Log, configs\nexcept ImportError as exception:\n print(\"%s - Please install the necessary libraries.\" % exception)\n sys.exit(1)\n\n\ndef get_betstars_content(url, country, tournament):\n \"\"\"\n Open each URL and get necessary tables with given credentials.\n Args:\n url - betstars url from config file\n country - country name from config file\n tournament - tournament type from config file\n Returns:\n web_page_and_scores - dictionary with web page name and scores\n \"\"\"\n content = ''\n web_page_and_scores = {}\n try:\n browser = webdriver.Firefox()\n\n # makes sure slower connections work as well\n browser.implicitly_wait(10)\n\n print_log_msg('Open %s url for searching content' % url, Log.DEBUG.value)\n browser.get(url + '#/soccer/competitions')\n\n timeout = 1\n try:\n element_present = EC.presence_of_element_located((By.ID, 'main'))\n WebDriverWait(browser, timeout).until(element_present)\n except TimeoutException:\n print(\"Timed out waiting for page to load\")\n finally:\n print(\"Page loaded\")\n\n browser.find_element_by_xpath(\"//div[@id='sideAZRegions']\").click()\n\n print_log_msg('Open all countries section for clicking on current country(given from config)', Log.DEBUG.value)\n all_countires = browser.find_elements_by_xpath(\"//div[@class='competitionListItem listItem']\")\n for country_name in all_countires:\n if country_name.text == country.upper():\n country_name.click()\n found_country = country_name\n\n print_log_msg('Open all tournaments section for clicking on current tournament(given from config)',\n Log.DEBUG.value)\n time.sleep(1)\n\n for li_tag in found_country.find_elements_by_tag_name('li'):\n if li_tag.text == country + ' - ' + tournament:\n score_url = li_tag.find_element_by_tag_name('a').get_attribute('href')\n\n print_log_msg('Get page content', Log.DEBUG.value)\n browser.get(score_url)\n\n timeout = 1\n try:\n element_present = EC.presence_of_element_located((By.ID, 'main'))\n WebDriverWait(browser, timeout).until(element_present)\n except TimeoutException:\n print(\"Timed out waiting for page to load\")\n finally:\n print(\"Page loaded\")\n\n score_table = browser.find_element_by_xpath(\"//div[@class='market-content']\")\n content = [item.text for item in score_table.find_elements_by_tag_name('li')]\n except Exception as exception:\n print (exception)\n\n finally:\n browser.delete_all_cookies()\n browser.close()\n\n\n if content:\n web_page_and_scores = create_scores_dict(url, content)\n else:\n print_log_msg('%s url ERROR while parsing' % url, Log.ERROR.value)\n return web_page_and_scores\n\ndef create_scores_dict(url, content):\n \"\"\"\n Parse content and get scores information, dump to the dict.\n Args:\n url - web page current url.\n content - url parsed content with all information.\n Returns:\n betstars_scores_dict - dictionary with all scores fro given options.\n \"\"\"\n print_log_msg('Create betstars dictionary with all teams and scores', Log.DEBUG.value)\n betstars_scores_dict = {}\n for each_row in content:\n scores = []\n row = each_row.split('\\n')\n if len(row) > 10:\n teams = row[4].lower() + ' - ' + row[5].lower()\n scores = {url : row[6:9]}\n else:\n teams = row[0].lower() + ' - ' + row[1].lower()\n scores = {url : row[2:5]}\n betstars_scores_dict[teams] = scores\n\n return betstars_scores_dict\n","sub_path":"betstars.py","file_name":"betstars.py","file_ext":"py","file_size_in_byte":4116,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"394987185","text":"from django.contrib import auth\nfrom django.http import Http404, HttpResponseNotAllowed\nfrom django.contrib.auth.decorators import login_required\nfrom django.shortcuts import render, redirect, get_object_or_404\nfrom django.views import View\nfrom django.utils import timezone\nfrom django.core.paginator import Paginator, EmptyPage, PageNotAnInteger\nfrom .models import Post\nfrom .forms import PostForm\n\n\nclass ShowHomeView(View):\n \"\"\"\n Default view for displaying home page\n\n \"\"\"\n template = 'news/news_list.html'\n\n def get(self, request):\n return redirect('/news/')\n\n\nclass NewsListView(View):\n \"\"\"\n Default view for displaying list of posts\n\n \"\"\"\n template = 'news/news_list.html'\n\n def get(self, request):\n post_list = Post.objects.filter(state=\"P\")\n paginator = Paginator(post_list, 3)\n page = request.GET.get('page')\n\n try:\n posts = paginator.page(page)\n except PageNotAnInteger:\n posts = paginator.page(1)\n except EmptyPage:\n posts = paginator.page(paginator.num_pages)\n\n context = {'post_list': posts}\n\n return render(request, self.template, context)\n\n def post(self, request):\n if not request.session or not request.session.session_key:\n request.session.save()\n return render(request, self.template)\n\n\nclass NewsPremoderationListView(View):\n \"\"\"\n View for displaying posts that require premoderation\n\n \"\"\"\n template = 'news/news_list.html'\n\n def get(self, request):\n post_list = Post.objects.filter(state=\"NP\")\n paginator = Paginator(post_list, 3)\n page = request.GET.get('page')\n print(\"PING!\", page)\n\n try:\n posts = paginator.page(page)\n except PageNotAnInteger:\n posts = paginator.page(1)\n except EmptyPage:\n posts = paginator.page(paginator.num_pages)\n\n context = {'post_list': posts}\n return render(request, self.template, context)\n\n\nclass NewsDetailView(View):\n model = Post\n template = \"news/news_post.html\"\n\n def get(self, request, pk, *args, **kwargs):\n post = Post.objects.filter(pk=pk)\n if not post.exists():\n raise Http404('Post with this ID does not exist')\n\n post = post.first()\n return render(request, self.template, {'post': post})\n\n\nclass NewsAddView(View):\n form = PostForm()\n model = Post\n template = \"news/news_edit.html\"\n\n def get(self, request, *args, **kwargs):\n return render(request, self.template, {'form': self.form})\n\n def post(self, request):\n form = PostForm(request.POST)\n user = request.user\n if form.is_valid():\n post = form.save(commit=False)\n post.author = user\n post.created = timezone.now()\n if 'base_ui.no_moderation_required' in user.get_all_permissions() or user.is_superuser or user.is_staff:\n post.state = 'P'\n else:\n post.state = 'NP'\n post.save()\n return redirect(\"news_detail\", pk=post.pk)\n\n\nclass NewsEditView(View):\n model = Post\n template = \"news/news_edit.html\"\n\n def get(self, request, pk, *args, **kwargs):\n post = get_object_or_404(Post, pk=pk)\n form = PostForm(instance=post)\n if post.author.pk == request.user.pk or request.user.is_superuser or request.user.is_staff:\n return render(request, self.template, {'form': form})\n else:\n return HttpResponseNotAllowed(\"ASDF\")\n\n def post(self, request, pk):\n post = get_object_or_404(Post, pk=pk)\n form = PostForm(request.POST, instance=post)\n user = request.user\n if form.is_valid():\n post = form.save(commit=False)\n post.author = user\n post.updated = timezone.now()\n post.save()\n return redirect(\"news_detail\", pk=post.pk)\n\n\n@login_required\ndef logout(request):\n auth.logout(request)\n return redirect(\"/\")\n","sub_path":"base_ui/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4025,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"173458593","text":"from servidor_de_impressora import ServidorDeImpressora\n\nclass Impressora(object):\n\n impressoras = []\n\n @classmethod\n def adicionar_impressora(classe, impressora):\n \tclasse.impressoras.append(impressora)\n\n def __init__(self, codigo_patrimonio, descricao, velocidade):\n self.codigo_patrimonio = codigo_patrimonio\n self.descricao = descricao\n self.velocidade = velocidade\n self.status = 'pronta'\n self.servidor = 0\n self.fila_de_espera = []\n Impressora.adicionar_impressora(self)\n\n\n def imprimir(self):\n return 'Impressao realizada com sucesso'","sub_path":"impressora.py","file_name":"impressora.py","file_ext":"py","file_size_in_byte":616,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"90349273","text":"__author__ = 'bhiwalakhil'\n\nimport json\nimport base64\n\nfrom flask import request, jsonify\nfrom webserver import app\nfrom database_access import db_utils\nfrom webserver.login import login_required\n\n\n@app.route('//friends', methods=['POST'])\n# @login_required\ndef friends():\n \"\"\"\n Request Body: {phone_numbers: [user1_phone, user2_phone, user3_phone]}\n :return: [{user_id: 234, nickname\" : \"abc\" , \"\"location_tag\" : \"work\", \"photoBLOB\" : IMAGE}, {user_id: 234, nickname\" : \"abc\" , \"\"location_tag\" : \"work\", \"photoBLOB\" : IMAGE}]\n \"\"\"\n response_list = []\n if request.method == 'POST':\n request_data = json.loads(request.data)\n phone_numbers = request_data['phone_numbers']\n for phone in phone_numbers:\n user_info = db_utils.get_user_from_phone(phone)\n if user_info:\n response = {\n 'user_id': user_info.user_id,\n 'nickname': user_info.name,\n 'location_tag': user_info.location_tag\n }\n if user_info.img:\n response['photoBLOB'] = base64.b64encode(user_info.img)\n response_list.append(response)\n return jsonify(response_list)","sub_path":"backend/webserver/user_id/friends.py","file_name":"friends.py","file_ext":"py","file_size_in_byte":1227,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"506838375","text":"import os\nimport pandas as pd\nimport numpy as np\nimport matplotlib\nmatplotlib.use('agg')\nimport functools\n\nimport tensorflow as tf\nfrom tensorflow import keras\nimport tensorflow.keras.backend as K\nfrom tensorflow.keras import Model\nfrom tensorflow.keras.layers import Layer, TimeDistributed, LSTM, GRU, Reshape, Conv1D, Concatenate, Dense, Embedding, Lambda, Flatten, BatchNormalization\n# from keras.callbacks import CSVLogger, Callback\n\nfrom data import Data\nfrom evaluation import *\nfrom tensorflow2_0.params import FLAGS\n\n\"\"\"\n* Filename: aaai19drsa.py\n* Implemented by Sundong Kim (sundong.kim@kaist.ac.kr) \n* Summary: Implementation of the State-of-the-art method DRSA [AAAI'19]. \n This performance of this baseline should be comparable to our method on first-time visitor testing set, \n whereas the performance on train_censored test set should be worse than our method. \n We implemented it again from the scratch, to guarantee same training input and same evaluation technique. \n* Reference: Deep Recurrent Survival Analysis [AAAI'19] by Kan Ren et al. \n* Dependency: \n * data.py (for some data preprocessing)\n * evaluation.py (for evaluation)\n * params.py (for parameters)\n * Data directory: ../data/indoor/ or ../data_samples/indoor/ depending on the parameter FLAGS.all_data\n* HowTo: This script can be executed independently or via main.py.\n\n* ToDo: Everything, Remove dependency for independent open-source. \n* Issues: \n\"\"\"\n\n\nclass AAAI19Data(Data):\n \"\"\"Data for AAAI19\"\"\"\n def __init__(self, store_id):\n super(AAAI19Data, self).__init__(store_id)\n\n def train_data_generator_AAAI19(self):\n \"\"\" Train data generator for AAAI'19 DRSA.\n Consider: Using each visit separately for training, histories are not considered.\n \"\"\"\n def __gen__():\n while True:\n # Only retain the last visits which includes all previous visits (Retain the last visit for each customer)\n idxs = list(self.df_train.visit_id)\n # np.random.shuffle(idxs)\n df_train = self.df_train.set_index('visit_id')\n train_visits = self.train_visits.set_index('visit_id')\n for idx in idxs:\n visit = train_visits.loc[idx]\n label = df_train.loc[idx]\n yield visit['visit_indices'], visit['area_indices'], \\\n [visit[ft] for ft in self.handcrafted_features], \\\n [label[ft] for ft in ['revisit_intention', 'suppress_time']]\n\n gen = __gen__()\n\n while True:\n batch = [np.stack(x) for x in zip(*(next(gen) for _ in range(FLAGS.batch_size)))]\n self.moke_data_train = np.hstack((batch[0].reshape(-1, 1), batch[1], batch[2])), batch[-1]\n yield self.moke_data_train\n\n def test_data_generator_AAAI19(self):\n \"\"\" Train data generator for AAAI'19 DRSA.\n Similar to train_data_generator_AAAI19()\n \"\"\"\n def __gen__():\n while True:\n idxs = list(self.df_test.visit_id)\n df_all = pd.concat([self.df_train, self.df_test]).set_index('visit_id')\n visits = self.visits.set_index('visit_id')\n for idx in idxs:\n visit = visits.loc[idx]\n label = df_all.loc[idx]\n yield visit['visit_indices'], visit['area_indices'], \\\n [visit[ft] for ft in self.handcrafted_features], \\\n [label[ft] for ft in ['revisit_intention', 'suppress_time']]\n\n gen = __gen__()\n\n while True:\n batch = [np.stack(x) for x in zip(*(next(gen) for _ in range(len(self.test_visits))))]\n self.moke_data_test = np.hstack((batch[0].reshape(-1, 1), batch[1], batch[2])), batch[-1]\n yield self.moke_data_test\n\n def train_censored_data_generator_AAAI19(self):\n \"\"\" Train_censored data generator for AAAI'19 DRSA.\n Similar to train_data_generator_AAAI19()\n \"\"\"\n def __gen__():\n while True:\n idxs = list(self.df_train_censored.visit_id)\n df_train = self.df_train.set_index('visit_id')\n train_visits = self.train_visits.set_index('visit_id')\n for idx in idxs:\n visit = train_visits.loc[idx]\n label = df_train.loc[idx]\n yield visit['visit_indices'], visit['area_indices'], \\\n [visit[ft] for ft in self.handcrafted_features], \\\n [label[ft] for ft in ['revisit_intention', 'suppress_time']]\n gen = __gen__()\n\n while True:\n batch = [np.stack(x) for x in zip(*(next(gen) for _ in range(len(self.censored_visit_id))))]\n self.moke_data_train_censored = np.hstack((batch[0].reshape(-1, 1), batch[1], batch[2])), batch[-1]\n yield self.moke_data_train_censored\n\n\nclass AAAI19Loss():\n \"\"\"Loss for AAAI19\"\"\"\n def __init__(self):\n self.y_true = None\n self.y_pred = None\n self.d_interval = {'date': {'left': -0.5, 'right': 0.5},\n 'week': {'left': -3.5, 'right': 3.5},\n 'month': {'left': -15, 'right': 15},\n 'season': {'left': -45, 'right': 45}}\n\n def initialize_data(self, y_true, y_pred):\n \"\"\" For initializing intermediate results for calculating losses later.\"\"\"\n self.y_true = y_true\n self.y_pred = y_pred\n\n def cal_expected_interval_for_loss(self, y_pred):\n \"\"\" For calculating MSE loss for censored data, we have to get the predict revisit interval.\"\"\"\n zeros = K.zeros(shape=(FLAGS.batch_size, 1))\n tmp_concat = K.concatenate([zeros, y_pred], axis=1)\n surv_rate = K.ones_like(tmp_concat) - tmp_concat\n surv_prob = K.cumprod(surv_rate, axis=1)\n revisit_prob = surv_prob[:, :-1] * y_pred\n rint = K.variable(np.stack([np.array(range(365)) + 0.5 for _ in range(FLAGS.batch_size)], axis=0))\n pred_revisit_probability = K.sum(revisit_prob, axis=1)\n pred_revisit_interval = K.sum(rint * revisit_prob, axis=1)\n return pred_revisit_interval\n\n @staticmethod\n def calculate_proba(x, interval):\n \"\"\" For calculating negative log likelihood losses for censored data.\"\"\"\n rvbin_label = x[-2] # revisit binary label\n supp_time = x[-1] # revisit suppress time # supp_time = K.cast(K.round(supp_time), dtype='int32')\n kvar_ones = K.ones_like(x[:-2])\n y = keras.layers.Subtract()([kvar_ones, x[:-2]]) # y = non-revisit rate (1-hazard rate)\n\n left_bin = K.maximum(supp_time + interval['left'], K.ones_like(\n supp_time)) # reason: y[0:x] cannot be calculated when x < 1, therefore set x as 1 so that y[0:1] = 1\n right_bin = K.minimum(supp_time + interval['right'], K.ones_like(\n supp_time) * 365) # reason: y[0:x] cannot be calculated when x > 365\n\n left_bin = K.cast(K.round(left_bin), dtype='int32')\n right_bin = K.cast(K.round(right_bin), dtype='int32')\n supp_time_int = K.cast(K.round(supp_time), dtype='int32')\n\n p_survive_until_linterval = K.prod(y[0:left_bin]) # The instance has to survive for every time step until t\n p_survive_until_rinterval = K.prod(y[0:right_bin])\n p_survive_until_supp_time = K.prod(y[0:supp_time_int])\n\n result = K.stack(\n [p_survive_until_linterval, p_survive_until_rinterval, p_survive_until_supp_time, rvbin_label])\n return result\n\n def uc_loss_nll(self, uc_loss_nll_option='date'):\n \"\"\"Wrapper function for all negative log-likelihood loss\"\"\"\n probs_survive = K.map_fn(functools.partial(self.calculate_proba, interval=self.d_interval[uc_loss_nll_option]),\n elems=self.tmp_tensor)\n prob_revisit_at_z = tf.transpose(probs_survive)[0] - tf.transpose(probs_survive)[1]\n # If censored -> multiply by 0 -> thus ignored\n prob_revisit_at_z_uncensored = tf.add(tf.multiply(prob_revisit_at_z, tf.transpose(probs_survive)[-1]), 1e-20)\n return -tf.reduce_sum(K.log(prob_revisit_at_z_uncensored)) # / num_revisitors_in_batch\n\n def uc_c_loss_ce(self):\n \"\"\" Cross entropy loss (Both uncensored and censored data) \"\"\"\n probs_survive = K.map_fn(functools.partial(self.calculate_proba, interval=self.d_interval['date']),\n elems=self.tmp_tensor, name='survive_rates')\n final_survive_prob = tf.transpose(probs_survive)[2]\n final_revisit_prob = tf.subtract(tf.constant(1.0, dtype=tf.float32), final_survive_prob)\n survive_revisit_prob = tf.transpose(tf.stack([final_survive_prob, final_revisit_prob]), name=\"predict\")\n\n actual_survive_bin = tf.subtract(tf.constant(1.0, dtype=tf.float32), self.y_true[:, -2])\n actual_revisit_bin = self.y_true[:, -2]\n revisit_binary_categorical = tf.transpose(tf.stack([actual_survive_bin, actual_revisit_bin]))\n\n return -tf.reduce_sum(\n revisit_binary_categorical * tf.log(tf.clip_by_value(survive_revisit_prob, 1e-10, 1.0)))\n\n def aaai19_loss(self):\n \"\"\"AAAI'19 loss, written as L_z, L_censored, L_uncensored in the paper\"\"\"\n self.tmp_tensor = K.concatenate([self.y_pred, self.y_true], axis=-1)\n print(self.y_true)\n print(self.y_pred)\n\n # First Loss (L_z): Negative Log Likelihood of true event time over the uncensored logs\n loss_z = self.uc_loss_nll(uc_loss_nll_option='date')\n\n # Second Loss (L_censored, L_uncensored): Cross Entropy\n loss_ce = self.uc_c_loss_ce()\n\n loss = loss_z + loss_ce\n # loss = loss_ce\n # loss = K.sum(K.mean(y_pred, axis=-1) - y_true[:, -1], axis=-1)\n return loss\n\n def rmse_loss(self):\n \"\"\"Implementation of RMSE loss for additional testing\"\"\"\n pred_revisit_interval = self.cal_expected_interval_for_loss(self.y_pred)\n squared_error_all = K.square(keras.layers.Subtract()([pred_revisit_interval, self.y_true[:, -1]]))\n squared_error_uc = tf.multiply(squared_error_all, self.y_true[:, -2]) # y_true[-2] is a binary revisit label.\n num_revisitors_in_batch = K.sum(self.y_true[:, -2])\n loss = K.sqrt(K.sum(squared_error_uc) / num_revisitors_in_batch)\n return loss\n\nclass AAAI19():\n def __init__(self, store_id, GPU_id):\n self.store_id = store_id\n self.GPU_id = GPU_id\n self.data = None\n\n def setup(self):\n pass\n # os.environ[\"CUDA_DEVICE_ORDER\"] = \"PCI_BUS_ID\"\n # os.environ[\"CUDA_VISIBLE_DEVICES\"] = self.GPU_id\n # config = tf.ConfigProto(allow_soft_placement=True)\n # config.gpu_options.per_process_gpu_memory_fraction = 0.9\n # config.gpu_options.allow_growth = True\n # sess = tf.Session(config=config)\n # K.set_session(sess)\n\n def generate_LSTM_model(self):\n \"\"\"Preliminary implementation of AAAI19 model, only having LSTM layer \"\"\"\n single_input = keras.Input((1 + self.max_num_areas + len(self.data.handcrafted_features),))\n\n # Generate a Model\n visit_embedding_layer = Embedding(\n input_dim=len(self.data.visit_embedding),\n output_dim=FLAGS.embedding_dim,\n weights=[np.array(list(self.data.visit_embedding.values()))],\n input_length=1,\n trainable=False)\n\n # x=[g;d;a;u], g=Gap,d=Time,a=Areas(Actions),u=Wifi_id\n gap_input = Lambda(lambda x: x[:, -1:])(single_input)\n time_idx = -len(self.data.handcrafted_features)+list(self.data.handcrafted_features).index('day_hour_comb')\n time_input = Lambda(lambda x: x[:, time_idx:time_idx+1])(single_input)\n area_input = Lambda(lambda x: x[:, 1:-len(self.data.handcrafted_features)])(single_input)\n visit_input = Lambda(lambda x: x[:, 0:1])(single_input)\n\n gap_input = Reshape((-1,))(gap_input)\n time_input = Reshape((-1,))(time_input)\n area_input = Reshape((-1,))(area_input)\n visit_input = Reshape((-1,))(visit_input)\n\n # with handcrafted features\n concat = Concatenate()([gap_input, time_input, area_input, visit_input])\n concat = Dense(40, activation=keras.activations.softmax)(concat)\n # concat = BatchNormalization()(concat)\n print('concat: ', K.int_shape(concat))\n low_level_model = keras.Model(inputs=single_input, outputs=concat)\n encoder = TimeDistributed(low_level_model)\n\n if FLAGS.dynamic_RNN:\n multiple_inputs = keras.Input((None, 1 + self.max_num_areas + len(self.data.handcrafted_features)))\n else:\n multiple_inputs = keras.Input((FLAGS.max_num_histories, 1 + self.max_num_areas + len(self.data.handcrafted_features)))\n\n all_areas_rslt = encoder(inputs=multiple_inputs)\n print('all_areas_rslt: ', K.int_shape(all_areas_rslt))\n all_areas_lstm = LSTM(64, return_sequences=True)(all_areas_rslt)\n\n logits = Dense(365, activation='softmax')(all_areas_lstm)\n\n self.model = keras.Model(inputs=multiple_inputs, outputs=logits)\n print(self.model.summary())\n\n def generate_model(self):\n \"\"\"AAAI19 model - Same implementation with DRSA Github repo.\n Covariate 'x' are copied for each cell and used as inputs for LSTM layer.\"\"\"\n\n # Define some embedding layers\n user_embedding_layer = Embedding(\n input_dim=len(self.data.visit_embedding),\n output_dim=FLAGS.embedding_dim,\n weights=[np.array(list(self.data.visit_embedding.values()))],\n input_length=1,\n trainable=False)\n\n area_embedding_layer = Embedding(\n input_dim=len(self.data.area_embedding),\n output_dim=FLAGS.embedding_dim,\n weights=[np.array(list(self.data.area_embedding.values()))],\n input_length=self.max_num_areas,\n trainable=False)\n\n # Data feeding\n single_input = keras.Input((1 + self.max_num_areas + len(self.data.handcrafted_features),))\n user_input = Lambda(lambda x: x[:, 0:1])(single_input)\n area_input = Lambda(lambda x: x[:, 1:-len(self.data.handcrafted_features)])(single_input)\n visit_features_input = Lambda(lambda x: x[:, -len(self.data.handcrafted_features):])(single_input)\n\n user_input = user_embedding_layer(user_input)\n area_input = area_embedding_layer(area_input) # Dimension becomes too large?\n\n user_input = Reshape((-1,))(user_input)\n area_input = Reshape((-1,))(area_input)\n\n print(user_input)\n print(area_input)\n print(visit_features_input)\n\n concat = Concatenate()([user_input, area_input, visit_features_input]) # [u;a;v]\n # concat = Dense(20, activation=keras.activations.softmax)(concat)\n # concat = BatchNormalization()(concat)\n\n print(concat.shape)\n expinp = Lambda(lambda x: K.repeat(x, 365))(concat)\n\n class AddTimeAscInputLayer(Layer):\n \"\"\"These set of computation did not work without defining this layer\"\"\"\n def __init__(self, **kwargs):\n super(AddTimeAscInputLayer, self).__init__(**kwargs)\n\n def build(self, input_shape):\n super(AddTimeAscInputLayer, self).build(input_shape)\n\n def call(self, x):\n ones = K.ones_like(x[:, :1, :1])\n yseq = K.variable(np.expand_dims(np.array(range(365)) + 0.5, 0))\n yseq = K.dot(ones, yseq)\n yseqd = Lambda(lambda y: K.permute_dimensions(y, (0, 2, 1)))(yseq)\n concat2 = Concatenate()([x, yseqd])\n return concat2\n\n def compute_output_shape(self, input_shape):\n return (input_shape[0], input_shape[1], input_shape[2]+1)\n\n concat2 = AddTimeAscInputLayer()(expinp)\n\n # LSTM\n all_areas_lstm = GRU(64, return_sequences=True)(concat2)\n logits = Dense(1, activation='softmax')(all_areas_lstm)\n logits = Lambda(lambda x: K.squeeze(x, axis=-1))(logits)\n self.model = keras.Model(inputs=single_input, outputs=logits)\n print(self.model.summary())\n\n def train_test(self):\n \"\"\"Using training/testing set & generated model, do learning & prediction\"\"\"\n\n # Data generation\n self.data = AAAI19Data(self.store_id)\n self.data.run()\n\n print('Number of areas: {}'.format(len(self.data.area_embedding)))\n self.max_num_areas = np.max(self.data.train_visits.areas.apply(len))\n\n # Generate a model\n self.generate_model()\n\n train_data_size = len(self.data.train_visits)\n test_data_size = len(self.data.test_visits)\n train_censored_data_size = len(self.data.train_censored_visits)\n\n self.train_data = self.data.train_data_generator_AAAI19()\n self.test_data = self.data.test_data_generator_AAAI19()\n self.train_censored_data = self.data.train_censored_data_generator_AAAI19()\n\n # import code\n # code.interact(local=locals())\n\n myloss = AAAI19Loss()\n\n def aaai19_loss(y_true, y_pred):\n \"\"\"Wrapper function to get combined loss by feeding data\"\"\"\n myloss.initialize_data(y_true, y_pred)\n return myloss.aaai19_loss()\n\n # def aaai19_loss2():\n #\n # def losses(y_true, y_pred):\n # a = 0.2\n # loss1 = rmse_loss(y_true, preprocess1(y_pred))\n # loss2 = ce_loss(y_true, preprocess2(y_pred))\n # loss = 0.2*loss1 + 0.8*loss2\n # return loss\n #\n # def aaai19_lossds(self):\n # \"\"\"AAAI'19 loss, written as L_z, L_censored, L_uncensored in the paper\"\"\"\n # self.tmp_tensor = K.concatenate([self.y_pred, self.y_true], axis=-1)\n # print(self.y_true)\n # print(self.y_pred)\n #\n # # First Loss (L_z): Negative Log Likelihood of true event time over the uncensored logs\n # loss_z = self.uc_loss_nll(uc_loss_nll_option='date')\n #\n # # Second Loss (L_censored, L_uncensored): Cross Entropy\n # loss_ce = self.uc_c_loss_ce()\n # print(K.eval(loss_ce))\n #\n # # loss = loss_z + loss_ce\n # loss = loss_ce\n # # loss = K.sum(K.mean(y_pred, axis=-1) - y_true[:, -1], axis=-1)\n # return loss\n\n def rmse_loss(y_true, y_pred):\n \"\"\"Wrapper function to get combined loss by feeding data\"\"\"\n myloss.initialize_data(y_true, y_pred)\n return myloss.rmse_loss()\n\n\n # Compile model\n self.model.compile(optimizer=keras.optimizers.Adam(0.01),\n loss=aaai19_loss # rmse_loss\n )\n\n if FLAGS.all_data: # Check more often since the whole data is much big\n steps_per_epoch = train_data_size // (10 * FLAGS.batch_size)\n else:\n steps_per_epoch = train_data_size // FLAGS.batch_size\n\n self.history = self.model.fit_generator(\n generator=self.train_data,\n steps_per_epoch=steps_per_epoch,\n epochs=FLAGS.train_epochs,\n )\n\n self.result = self.model.predict_generator(\n generator=self.test_data,\n steps=1\n )\n\n print(self.result)\n\n self.result_train_censored = self.model.predict_generator(\n generator=self.train_censored_data,\n steps=1\n )\n\n print(self.result_train_censored)\n\n eval = Evaluation()\n\n # Run other baselines for performance comparison\n eval.naive_baseline(self.data)\n eval.naive_baseline_for_train_censored(self.data)\n eval.poisson_process_baseline(self.data)\n eval.hawkes_process_baseline(self.data)\n eval.icdm_baseline(self.data)\n eval.icdm_baseline_for_train_censored(self.data)\n eval.traditional_survival_analysis_baseline(self.data)\n eval.traditional_survival_analysis_baseline_for_train_censored(self.data)\n\n # Evaluate the AAAI19 method\n eval.evaluate(self.data, self.result)\n eval.evaluate_train_censored(self.data, self.result_train_censored)\n print(\"The results of AAAI'19 model are listed as \\\"Our Model\\\" from the above log.\")\n\n def run(self):\n self.setup()\n self.train_test()\n\n\nif __name__ == \"__main__\":\n print(\"-----------------------------------------\")\n print(\" Running AAAI'19 code directly \")\n print(\"-----------------------------------------\")\n # gpu_id = input(\"Choose one GPU slot to run (ex. 0, 1, 2, 3, 4, 5, 6, 7 for DGX server)\")\n gpu_id = \"0\"\n aaai19 = AAAI19(store_id=FLAGS.store_id, GPU_id=gpu_id)\n aaai19.run()\n","sub_path":"survival-revisit-code/tensorflow2_0/aaai19drsa.py","file_name":"aaai19drsa.py","file_ext":"py","file_size_in_byte":20942,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"498102475","text":"\"\"\"Named-entity recognition with SpaCy\"\"\"\n\nfrom collections import defaultdict\nimport sys\n\nimport spacy\nfrom spacy.lang.fr.examples import sentences \n\nnlp = spacy.load('fr_core_news_md')\n\ndef test():\n \"\"\"Basic test on sample sentences\"\"\"\n for sent in sentences:\n doc = nlp(sent)\n entities = []\n for ent in doc.ents:\n entities.append(f\"{ent.text} ({ent.label_})\")\n if entities:\n print(f\"'{doc.text}' contains the following entities: {', '.join(entities)}\")\n else:\n print(f\"'{doc.text}' contains no entities\")\n\ndef search():\n text = open(\"data/all.txt\").read()[:100000]\n doc = nlp(text)\n people = defaultdict(int)\n for ent in doc.ents:\n if ent.label_ == \"PER\" and len(ent.text) > 3:\n people[ent.text] += 1\n sorted_people = sorted(people.items(), key=lambda kv: kv[1], reverse=True)\n for person, freq in sorted_people[:10]:\n print(f\"{person} appears {freq} times in the corpus\")\n\nif __name__ == \"__main__\":\n try:\n if sys.argv[1] == \"test\":\n test()\n elif sys.argv[1] == \"search\":\n search()\n else:\n print(\"Unknown option, please use either 'test' or 'search'\")\n except IndexError:\n print(\"No option, please specify either 'test' or 'search'\")\n","sub_path":"module3/raw_scripts/s3_ner.py","file_name":"s3_ner.py","file_ext":"py","file_size_in_byte":1322,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"240606205","text":"'''\n Copyright (C) 2019 Maged Mokhtar petasan.org>\n Copyright (C) 2019 PetaSAN www.petasan.org\n\n\n This program is free software; you can redistribute it and/or\n modify it under the terms of the GNU Affero General Public License\n as published by the Free Software Foundation\n\n This program is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU Affero General Public License for more details.\n'''\n\nfrom flask import json\n\n\nclass CephVolumeInfo(object):\n def __init__(self):\n self.devices = []\n self.linked_journal = \"\"\n self.linked_journal_part_num = -1\n self.osd_id = -1\n self.osd_uuid = \"\"\n self.linked_cache = []\n self.linked_cache_part_num = []\n self.lv_name = \"\"\n self.vg_name = \"\"\n\n\n\n def load_json(self, j):\n self.__dict__ = json.loads(j)\n\n def write_json(self):\n j = json.dumps(self, default=lambda o: o.__dict__,\n sort_keys=True, indent=4)\n return j\n\n def get_dict(self):\n return self.__dict__","sub_path":"storage-appliance/usr/lib/python2.7/dist-packages/PetaSAN/core/entity/ceph_volume.py","file_name":"ceph_volume.py","file_ext":"py","file_size_in_byte":1169,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"118815151","text":"from django.conf.urls import include, url\nfrom django.conf.urls.static import static\nfrom WebApp import settings\n\n\nfrom . import views\n\n\nurlpatterns = [\n url(r'^index/$', views.index, name='index'),\n url(r'^accounts/teacher/auth$', 'myapp.views.teacher_auth_view'),\n url(r'^accounts/teacher/loggedin/$', 'myapp.views.teacher_logged_in'),\n url(r'^accounts/student/auth$', 'myapp.views.student_auth_view'),\n url(r'^accounts/student/loggedin/$', 'myapp.views.student_logged_in'),\n url(r'^accounts/logout/$', 'myapp.views.logout'),\n url(r'^accounts/invalid/$', 'myapp.views.invalid_login'),\n url(r'^accounts/register$', 'myapp.views.register_user'),\n url(r'^accounts/register_success$', 'myapp.views.register_success'),\n\n]+static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)\n","sub_path":"myapp/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":810,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"242877631","text":"import numpy as np\nimport cv2\nimport os\nimport glob\nimport pickle\nfrom sklearn import svm\nfrom sklearn.externals import joblib\n\nW = 40\nH = 64\n\nhog = cv2.HOGDescriptor((W, H), (16, 16), (8,8), (8,8), 9)\ncurr_path = os.getcwd()\n\npos_dir_path = curr_path+'/data/INRIAPerson/train_64x128_H96/pos'\nneg_dir_path = curr_path+'/data/indoor'\n\npos_img_path = glob.glob(pos_dir_path+'/*.png')\nneg_img_path = glob.glob(neg_dir_path+'/*.png')\nneg_img_path += glob.glob(neg_dir_path+'/*.jpg')\nimg = cv2.imread(pos_img_path[1], 2)\n\ntrain_data = []\ntrain_label = []\n\nfor i in range(len(pos_img_path)):\n img = cv2.imread(pos_img_path[i], 2)\n # cv2.imshow('a', img)\n # cv2.waitKey()\n img2 = img[30:30+H, 30:30+W]\n # cv2.imshow('a', img2)\n # cv2.waitKey()\n vec = hog.compute(img2)\n train_data.append(vec.flatten())\n train_label.append(1)\n print(\"{}: {}\".format(i, len(vec)))\n\nwith open('POS_data', 'wb') as fp:\n pickle.dump((train_data, train_label), fp)\n\ntrain_data = []\ntrain_label = []\n\nTest_data = []\nTest_label = []\n\npadding = 30\n\nfor i in range(len(neg_img_path)):\n img = cv2.imread(neg_img_path[i], 2)\n if img==None:\n continue\n h2, w2 = img.shape\n h2, w2 = int((h2-H)/padding), int((w2-W)/padding)\n for j in range(h2):\n if j%2==0:\n continue\n for k in range(w2):\n if k%2==0:\n continue\n x = j*padding\n y = k*padding\n img2 = img[x:x+H, y:y+W]\n vec = hog.compute(img2)\n Test_data.append(vec.flatten())\n Test_label.append(0)\n print(\"{}.{}.{}: {}\".format(i, j, k, len(vec)))\n\nwith open('NEG_data', 'wb') as fp:\n pickle.dump((Test_data, Test_label), fp)\n","sub_path":"saveToDiffDir.py","file_name":"saveToDiffDir.py","file_ext":"py","file_size_in_byte":1721,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"78406450","text":"# -*- coding:utf-8 -*-\n# Description: ---\n# Author: Lynn\n# Email: lgang219@gmail.com\n# Create: 2018-07-20 00:59:50\n# Last Modified: 2018-09-02 14:11:27\n#\n\nfrom django.urls import path\nfrom . import views\n\nurlpatterns = [\n path('', views.book_index, name='book_index'),\n path('pages//', views.index_by_page, name='book_index_by_page'),\n path('/', views.book_detail, name='book_detail'),\n path('category/', views.book_category, name='book_category'),\n # 通过构造 URL 实现搜索\n # path('search/', views.movie_search, name='movie_search'),\n # navbar 中的 Form 搜索\n path('search/', views.book_search_navbar, name='book_search_navbar'),\n # 热搜榜\n path('resou/', views.book_resou, name='book_resou'),\n # 热搜榜 json format\n path('resou_json/', views.book_resou_json, name='book_resou_json'),\n # 八百里加急 立即催\n path('babaili_jiaji/', views.babaili_jiaji, name='babaili_jiaji'),\n path('invalid_url_report/', views.invalid_url_report, name='invalid_url_report'),\n]\n","sub_path":"pandy/books/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1098,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"508292248","text":"from django.shortcuts import render\nfrom django.http import HttpResponse,JsonResponse\nfrom django.views.decorators.csrf import csrf_exempt\n\nfrom rest_framework.parsers import JSONParser\nfrom rest_framework.decorators import api_view\nfrom rest_framework import status\nfrom rest_framework.response import Response\n\nfrom .models import Snippet\n\nfrom .serializers import SnippetSerializer\n\n\n\n\n@api_view(['GET','POST'])\ndef snippet_list(request,format=None):\n \"\"\"\n\n :param request:\n :return:\n \"\"\"\n if request.method == 'GET':\n \n snippets = Snippet.objects.all()\n serializer = SnippetSerializer(snippets,many=True)\n return Response(serializer.data)\n \n elif request.method == 'POST':\n serializer = SnippetSerializer(data=request.data)\n if serializer.is_valid():\n serializer.save()\n return Response(serializer.data,status=status.HTTP_201_CREATED)\n return Response(serializer.errors,status=status.HTTP_400_BAD_REQUEST)\n\n\n@api_view(['GET','PUT','DELETE'])\ndef snippet_detail(request,pk,format=None):\n try:\n snippet = Snippet.objects.get(pk=pk)\n except Snippet.DoesNotExist:\n return Response(status=status.HTTP_404_NOT_FOUND)\n \n if request.method == 'GET':\n serializer = SnippetSerializer(snippet)\n return Response(serializer.data)\n if request.method == 'PUT':\n # request.data可自动处理传入的json请求\n serializer = SnippetSerializer(snippet,data=request.data)\n if serializer.is_valid():\n return Response(serializer.data)\n return Response(serializer.errors,status=status.HTTP_404_NOT_FOUND)\n if request.method == 'DELETE':\n snippet.delete()\n return Response(status=status.HTTP_204_NO_CONTENT)\n\n\n\n\n\n\n\n\n\n\n","sub_path":"Growing/Rest_framework/02请求和响应/snippets/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1790,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"91637488","text":"from MySQLdb import _mysql\nfrom Trivia.forms import RegisterForm, LoginForm, RankingForm\nfrom django.contrib.auth.models import User\nfrom django.contrib.auth import authenticate, login\nfrom django.db import models\nfrom django.db.models import Count\nfrom Trivia.models import Config_Partida, Pregunta, Respuesta, Ranking\nimport random\n\n\n#Consultas del juego----------------------------------\ndef questions():\n #consulta todas las preguntas\n p_queryset = Pregunta.objects.all().values()\n r = Respuesta.objects.all().values()\n c = Config_Partida.objects.all().values()\n\n p = []\n for question in p_queryset:\n p.append(question)\n # r = Respuesta.objects.all().filter(pregunta_id=21)['respuesta']\n questions_list = {}\n for i in range(len(p_queryset)):\n #numero al azar segun cantidad de preguntas totales\n randNum = random.randint(0,len(p)-1)\n #se guardan todas las preguntas en orden aleatorio en questions_list \n questions_list['question_' + str(i+1)] = {\n \"id\": p[randNum]['id'],\n \"formula\": p[randNum]['formula'],\n \"categoría\": c[p[randNum]['trivia_id']-1]['nombre'],\n \"respuestas\": []\n }\n #según las preguntas al azar tomadas se filtran las respectivas respuestas y se agregan a questions_list\n resp_cont = 0\n for respuesta in r:\n if respuesta['pregunta_id'] == questions_list['question_' + str(i+1)]['id']:\n resp_cont = resp_cont + 1\n questions_list['question_' + str(i+1)]['respuestas'].append({'respuesta_' + str(resp_cont): {\n \"formula\": respuesta['formula'],\n \"correcta\": respuesta['correcta']\n }})\n del p[randNum]\n randNum+1\n return questions_list\n\n#registrar usuario----------------------------------\ndef register_post(request):\n # create a form instance and populate it with data from the request:\n form = RegisterForm(request.POST)\n # check whether it's valid:\n if form.is_valid():\n form_data = form.cleaned_data\n try:\n check = User.objects.get(username=form_data['name'])\n except:\n user = User.objects.create_user(form_data['name'], form_data['email'], form_data['password'])\n msg = [True, \"Usuario creado de forma exitosa!\"]\n return msg\n msg = [False, \"Usuario ya existente, ingrese otro nombre de usuario.\"]\n return msg\n \n#registrar partida---------------------------------- \ndef ranking_post(request):\n form = RankingForm(request.POST)\n if form.is_valid():\n form_data = form.cleaned_data\n user = User.objects.get(id=request.user.id)\n result = Ranking(usuario=user, aciertos=form_data['result'], pregunta=form_data['pregunta'], correcta=form_data['correcta'], incorrecta=form_data['incorrecta'])\n result.save()\n #CAMBIAR CODIGO POR CONSULTA AL IMPLEMENTAR EL RESULT\n part = Ranking.objects.latest('id')\n partida_id = part.id\n return partida_id\n \n#loguear usuario---------------------------------- \ndef user_login(request):\n form = LoginForm(request.POST)\n #si el formulario esta completo se autentifica con los datos ingresados\n if form.is_valid():\n form_data = form.cleaned_data\n user = authenticate(request, username=form_data['name'], password=form_data['password'])\n if user is not None:\n #aqui se deja abierta la sesión\n login(request, user)\n \n \n#obtener ranking---------------------------------- \ndef ranking_get():\n #se obtiene la lista completa de partidas y se ordena por puntaje, y se filtra para solo ver una por usuario\n rank = Ranking.objects.raw('SELECT id, MAX(aciertos) as maximo, usuario_id, fecha, pregunta, correcta, incorrecta FROM trivia_ranking GROUP BY usuario_id ORDER BY maximo DESC;')\n return rank\n\n#obtener ranking---------------------------------- \ndef own_historial_get(request):\n #se obtiene la lista completa de partidas propias y se ordena por fecha\n sql = str(f'SELECT * from informatorio.trivia_ranking WHERE usuario_id={request.user.id} ORDER BY fecha DESC;')\n historial = Ranking.objects.raw(sql)\n return historial\n\n#obtener partidas del ranking para mostrar url de partidas espec{---------------------------------- \ndef historial_get(partida_id):\n #se obtiene la partida a partir de la id ingresada\n part = Ranking.objects.filter(id=partida_id)\n partida = list(part)\n usuario = User.objects.filter(id=partida[0].usuario_id)\n result = {'points': partida[0].aciertos, 'pregunta': partida[0].pregunta, 'correcta': partida[0].correcta, 'incorrecta': partida[0].incorrecta, 'fecha': partida[0].fecha, 'usuario': usuario[0]}\n return result","sub_path":"Info/db.py","file_name":"db.py","file_ext":"py","file_size_in_byte":4829,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"440287328","text":"\"\"\"\nRun a created state machine with some inputs\n\"\"\"\n\nimport boto3\nimport json\n\naccount_num = 'xxx'\nARN = f\"arn:aws:states:ap-northeast-1:{account_num}:stateMachine:test\"\n\n\ndef main():\n command = {\n 'task1_cmd': ['-a', '100'],\n 'task2_cmd': ['-b', '110'],\n 'task1_foo': ['-a', '100'],\n 'task2_foo': ['-b', '110'],\n 'task1_xx': ['-a', '100'],\n 'task2_xx': ['-b', '110'],\n }\n state_input = json.dumps({'command': command}, indent=2, sort_keys=True)\n response = boto3.client('stepfunctions').start_execution(\n stateMachineArn=ARN,\n input=state_input\n )\n execution_arn = response['executionArn']\n print(\n 'See progress in :',\n ('https://ap-northeast-1.console.aws.amazon.com/states/home?'\n f'region=ap-northeast-1#/executions/details/{execution_arn}')\n )\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"aws/sfn/run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":893,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"391301625","text":"#!/usr/bin/env python\n\"\"\"This service implements a simple RESTful service that\ndemonstrates how tor-async-lcp is intended to be used.\n\"\"\"\n\nimport httplib\nimport logging\nimport optparse\nimport time\n\nimport tornado.httpserver\nimport tornado.web\n\nfrom tor_async_lcp.async_lcp_actions import AsyncLCPHealthCheck\n\n_logger = logging.getLogger(__name__)\n\n\nclass RequestHandler(tornado.web.RequestHandler):\n\n account_id = None\n mac_algo = None\n mac_key_identifier = None\n mac_key = None\n\n url_spec = r\"/v1.0/_health\"\n\n @tornado.web.asynchronous\n def get(self):\n alcphc = AsyncLCPHealthCheck(\n self.account_id,\n self.mac_algo,\n self.mac_key_identifier,\n self.mac_key)\n alcphc.check(self._on_alcphc_check_done)\n\n def _on_alcphc_check_done(self, is_ok, alcphc):\n response_body = {\n \"status\": \"green\" if is_ok else \"red\",\n }\n self.write(response_body)\n self.set_status(httplib.OK)\n self.finish()\n\n\nclass CommandLineParser(optparse.OptionParser):\n\n def __init__(self):\n description = (\n \"This service implements a simple RESTful service that \"\n \"demonstrates how tor-async-lcp is intended to be used.\"\n )\n optparse.OptionParser.__init__(\n self,\n \"usage: %prog [options]\",\n description=description)\n\n default = 8445\n help = \"port - default = %s\" % default\n self.add_option(\n \"--port\",\n action=\"store\",\n dest=\"port\",\n default=default,\n type=\"int\",\n help=help)\n\n default = \"127.0.0.1\"\n help = \"ip - default = %s\" % default\n self.add_option(\n \"--ip\",\n action=\"store\",\n dest=\"ip\",\n default=default,\n type=\"string\",\n help=help)\n\n default = None\n help = \"LCP account id - default = %s\" % default\n self.add_option(\n \"--account_id\",\n action=\"store\",\n dest=\"account_id\",\n default=default,\n type=\"string\",\n help=help)\n\n default = None\n help = \"LCP mac algo - default = %s\" % default\n self.add_option(\n \"--mac_algo\",\n action=\"store\",\n dest=\"mac_algo\",\n default=default,\n type=\"string\",\n help=help)\n\n default = None\n help = \"LCP mac key identifier - default = %s\" % default\n self.add_option(\n \"--mac_key_identifier\",\n action=\"store\",\n dest=\"mac_key_identifier\",\n default=default,\n type=\"string\",\n help=help)\n\n default = None\n help = \"LCP mac key - default = %s\" % default\n self.add_option(\n \"--mac_key\",\n action=\"store\",\n dest=\"mac_key\",\n default=default,\n type=\"string\",\n help=help)\n\n help = \"use simple async client - default enabled\"\n self.add_option(\n \"--use_simple\",\n action=\"store_true\",\n dest=\"use_simple\",\n help=help)\n\n def parse_args(self, *args, **kwargs):\n (clo, cla) = optparse.OptionParser.parse_args(self, *args, **kwargs)\n if not clo.account_id:\n self.error(\"'--account_id' is required\")\n if not clo.mac_algo:\n self.error(\"'--mac_algo' is required\")\n if not clo.mac_key_identifier:\n self.error(\"'--mac_key_identifier' is required\")\n if not clo.mac_key:\n self.error(\"'--mac_key' is required\")\n return (clo, cla)\n\n\nif __name__ == \"__main__\":\n clp = CommandLineParser()\n (clo, cla) = clp.parse_args()\n\n logging.Formatter.converter = time.gmtime # remember gmt = utc\n logging.basicConfig(\n level=logging.INFO,\n datefmt=\"%Y-%m-%dT%H:%M:%S\",\n format=\"%(asctime)s.%(msecs)03d+00:00 %(levelname)s %(module)s %(message)s\")\n\n handlers = [\n (\n RequestHandler.url_spec,\n RequestHandler\n ),\n ]\n\n RequestHandler.account_id = clo.account_id\n RequestHandler.mac_algo = clo.mac_algo\n RequestHandler.mac_key_identifier = clo.mac_key_identifier\n RequestHandler.mac_key = clo.mac_key\n\n if not clo.use_simple:\n # curl client req'd to get detailed timing info on requests to LCP\n client = \"tornado.curl_httpclient.CurlAsyncHTTPClient\"\n tornado.httpclient.AsyncHTTPClient.configure(client)\n\n settings = {\n }\n\n app = tornado.web.Application(handlers=handlers, **settings)\n\n http_server = tornado.httpserver.HTTPServer(app, xheaders=True)\n http_server.listen(port=clo.port, address=clo.ip)\n\n _logger.info(\n \"service started and listening on http://%s:%d\",\n clo.ip,\n clo.port)\n\n tornado.ioloop.IOLoop.instance().start()\n","sub_path":"samples/service.py","file_name":"service.py","file_ext":"py","file_size_in_byte":4914,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"395402985","text":"import math\n\nimport torch\nimport torch.nn as nn\n\nfrom ..registry import BACKBONES\nimport math\n\nimport torch\nimport torch.nn as nn\n\ndef conv_1x1_bn(input_depth, output_depth):\n return nn.Sequential(\n nn.Conv2d(input_depth, output_depth, 1, 1, 0, bias=False),\n nn.BatchNorm2d(output_depth),\n nn.ReLU6(inplace=True)\n )\n\nclass ConvBNRelu(nn.Sequential):\n def __init__(self, \n input_depth,\n output_depth,\n kernel,\n stride,\n pad,\n activation=\"relu\",\n group=1,\n *args,\n **kwargs):\n\n super(ConvBNRelu, self).__init__()\n\n assert activation in [\"hswish\", \"relu\", None]\n assert stride in [1, 2, 4]\n\n self.add_module(\"conv\", nn.Conv2d(input_depth, output_depth, kernel, stride, pad, groups=group, bias=False))\n self.add_module(\"bn\", nn.BatchNorm2d(output_depth))\n\n if activation == \"relu\":\n self.add_module(\"relu\", nn.ReLU6(inplace=True))\n elif activation == \"hswish\":\n self.add_module(\"hswish\", HSwish())\n\nclass SEModule(nn.Module):\n reduction = 4\n def __init__(self, C):\n super(SEModule, self).__init__()\n mid = max(C // self.reduction, 8)\n conv1 = nn.Conv2d(C, mid, 1, 1, 0)\n conv2 = nn.Conv2d(mid, C, 1, 1, 0)\n\n self.operation = nn.Sequential(\n nn.AdaptiveAvgPool2d(1), conv1, nn.ReLU(inplace=True), conv2, nn.Sigmoid() \n )\n\n def forward(self, x):\n return x * self.operation(x)\n\nclass MBConv(nn.Module):\n def __init__(self,\n input_depth,\n output_depth,\n expansion,\n kernel,\n stride,\n activation,\n group=1,\n se=False,\n *args,\n **kwargs):\n super(MBConv, self).__init__()\n self.use_res_connect = True if (stride==1 and input_depth == output_depth) else False\n mid_depth = int(input_depth * expansion)\n\n self.group = group\n\n if input_depth == mid_depth:\n self.point_wise = nn.Sequential()\n else:\n self.point_wise = ConvBNRelu(input_depth,\n mid_depth,\n kernel=1,\n stride=1,\n pad=0,\n activation=activation,\n group=group,\n )\n\n self.depthwise = ConvBNRelu(mid_depth,\n mid_depth,\n kernel=kernel,\n stride=stride,\n pad=(kernel//2),\n activation=activation,\n group=mid_depth,\n )\n\n self.point_wise_1 = ConvBNRelu(mid_depth,\n output_depth,\n kernel=1,\n stride=1,\n pad=0,\n activation=None,\n group=group,\n )\n self.se = SEModule(mid_depth) if se else None\n\n def forward(self, x):\n y = self.point_wise(x)\n y = self.depthwise(y)\n\n y = self.se(y) if self.se is not None else y\n y = self.point_wise_1(y)\n\n y = y + x if self.use_res_connect else y\n return y\n\n\n\nclass POBlock(nn.Module):\n def __init__(self, \n input_depth,\n output_depth,\n kernel,\n stride,\n activation=\"relu\",\n block_type=\"MB\",\n expansion=1,\n group=1,\n se=False):\n\n super(POBlock, self).__init__()\n\n self.block = MBConv(input_depth,\n output_depth,\n expansion,\n kernel,\n stride,\n activation,\n group,\n se) \n\n\n def forward(self, x):\n y = self.block(x)\n return y\n\n\n@BACKBONES.register_module\nclass PONASC(nn.Module):\n def __init__(self, classes=1000):\n super(PONASC, self).__init__()\n\n\n\n model_cfg = [\n [6, 5, False, 2, 32], \n [3, 5, False, 1, 32], \n [3, 7, True, 2, 40], \n [3, 5, True, 1, 40], \n [3, 5, False, 1, 40], \n [3, 7, False, 1, 40], \n [6, 7, True, 2, 80], \n [3, 5, True, 1, 80], \n [3, 5, True, 1, 80], \n [3, 5, True, 1, 80], \n [3, 5, False, 1, 96], \n [3, 7, False, 1, 96], \n [3, 7, False, 1, 96], \n [3, 7, True, 1, 96], \n [6, 7, True, 2, 192], \n [3, 7, True, 1, 192], \n [3, 5, False, 1, 192], \n [3, 7, True, 1, 192], \n [6, 5, True, 1, 320]]\n\n\n\n self.first = ConvBNRelu(input_depth=3, output_depth=32, kernel=3, stride=2, pad=3//2, activation=\"relu\")\n\n self.stages = nn.ModuleList()\n self.stages.append(POBlock(32, 16, 3, 1))\n input_depth = 16\n for i, cfg in enumerate(model_cfg):\n e, k, se, s, output_depth = cfg\n\n self.stages.append(POBlock(input_depth=input_depth, \n output_depth=output_depth,\n kernel=k,\n stride=s,\n expansion=e,\n se=se))\n input_depth = output_depth\n\n\n self.stages.add_module(\"last\", conv_1x1_bn(input_depth, 1280))\n self.classifier = nn.Sequential(\n nn.Dropout(0.2),\n nn.Linear(1280, classes)\n )\n \n# self._initialize_weights()\n\n def forward(self, x):\n y = self.first(x)\n out = []\n for i, l in enumerate(self.stages):\n y = l(y)\n if i in [2, 6, 14, 18]:\n out.append(y)\n# y = self.stages(y)\n y = y.mean(3).mean(2)\n y = self.classifier(y)\n return tuple(out)\n\n def _initialize_weights(self):\n for m in self.modules():\n if isinstance(m, nn.Conv2d):\n n = m.kernel_size[0] * m.kernel_size[1] * m.out_channels\n m.weight.data.normal_(0, math.sqrt(2. / n))\n if m.bias is not None:\n m.bias.data.zero_()\n elif isinstance(m, nn.BatchNorm2d):\n m.weight.data.fill_(1)\n m.bias.data.zero_()\n elif isinstance(m, nn.Linear):\n n = m.weight.size(1)\n m.weight.data.normal_(0, 0.01)\n m.bias.data.zero_()\n\n def init_weights(self, pretrained=False):\n self.load_state_dict(torch.load(\"/home/jovyan/mmdetection/mmdet/models/backbones/PONAS_A.pth\"))","sub_path":"mmdet/models/backbones/ponas.py","file_name":"ponas.py","file_ext":"py","file_size_in_byte":7475,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"11406319","text":"import urllib.request, urllib.error, urllib.parse\nimport json\nimport datetime\nimport time\nimport pytz\nimport re\nimport pandas as pd\nfrom pandas import DataFrame\n\ntimestring = lambda t: time.mktime(t.timetuple())\nstart = timestring(datetime.datetime(2013,1,1,0,0,0,0))\nend = timestring(datetime.datetime(2014,1,1,0,0,0,0))\n\niterations = 306\ndf = DataFrame()\nhitsPerPage = 1000\nrequested_keys = [\"objectID\",\"title\",\"url\",\"points\",\"num_comments\",\"author\",\"created_at_i\"]\n\nfor i in range(iterations):\n try:\n prefix = 'https://hn.algolia.com/api/v1/'\n query = 'search_by_date?tags=story&hitsPerPage=%s&numericFilters=created_at_i>%d,created_at_i<%d' % (hitsPerPage, start, end)\n url = prefix + query\n req = urllib.request.Request(url)\n response = urllib.request.urlopen(req)\n data = json.loads(response.read().decode(\"utf-8\"))\n data = DataFrame(data[\"hits\"])[requested_keys]\n df = df.append(data,ignore_index=True)\n end = data.created_at_i.min()\n print(i)\n time.sleep(3.6)\n\n except Exception as e:\n print(e)\n\ndf[\"title\"] = df[\"title\"].map(lambda x: x.replace(',','').replace('\"',\"'\"))\ndf[\"created_at\"] = df[\"created_at_i\"].map(lambda x: datetime.datetime.fromtimestamp(int(x), tz=pytz.timezone('America/New_York')).strftime('%Y-%m-%d %H:%M:%S'))\ndf[\"url-domain\"] = df[\"url\"].map(lambda x: urllib.parse.urlparse(x).hostname)\n\nordered_df = df[[\"objectID\",\"title\",\"url-domain\",\"points\",\"num_comments\",\"author\",\"created_at\"]]\nordered_df.to_csv(\"hacker_news_stories.csv\", encoding='utf-8', index=False)\n","sub_path":"download-stories.py","file_name":"download-stories.py","file_ext":"py","file_size_in_byte":1557,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"72720514","text":"\"\"\"MPI-supported kernels for computing advection flux in 2D.\"\"\"\nfrom sopht.numeric.eulerian_grid_ops.stencil_ops_2d import (\n gen_advection_flux_conservative_eno3_pyst_kernel_2d,\n)\nfrom sopht_mpi.utils.mpi_utils import check_valid_ghost_size_and_kernel_support\n\n\ndef gen_advection_flux_conservative_eno3_pyst_mpi_kernel_2d(\n real_t, mpi_construct, ghost_exchange_communicator\n):\n advection_flux_pyst_kernel = gen_advection_flux_conservative_eno3_pyst_kernel_2d(\n real_t=real_t\n )\n kernel_support = 2\n # define this here so that ghost size and kernel support is checked during\n # generation phase itself\n gen_advection_flux_conservative_eno3_pyst_mpi_kernel_2d.kernel_support = (\n kernel_support\n )\n check_valid_ghost_size_and_kernel_support(\n ghost_size=ghost_exchange_communicator.ghost_size,\n kernel_support=gen_advection_flux_conservative_eno3_pyst_mpi_kernel_2d.kernel_support,\n )\n\n def advection_flux_conservative_eno3_pyst_mpi_kernel_2d(\n advection_flux, field, velocity, inv_dx\n ):\n # define kernel support for kernel\n advection_flux_conservative_eno3_pyst_mpi_kernel_2d.kernel_support = (\n gen_advection_flux_conservative_eno3_pyst_mpi_kernel_2d.kernel_support\n )\n # define variable for use later\n ghost_size = ghost_exchange_communicator.ghost_size\n # begin ghost comm.\n ghost_exchange_communicator.exchange_scalar_field_init(field)\n ghost_exchange_communicator.exchange_vector_field_init(velocity)\n\n # crunch interior stencil\n advection_flux_pyst_kernel(\n advection_flux=advection_flux[\n ghost_size:-ghost_size, ghost_size:-ghost_size\n ],\n field=field[ghost_size:-ghost_size, ghost_size:-ghost_size],\n velocity=velocity[:, ghost_size:-ghost_size, ghost_size:-ghost_size],\n inv_dx=inv_dx,\n )\n # finalise ghost comm.\n ghost_exchange_communicator.exchange_finalise()\n\n # crunch boundary numbers\n # NOTE: we pass in arrays of width 3 * kernel support size because the\n # interior stencil computation leaves out a width of kernel_support.\n # Since the support needed by the kernel is kernel_support on each side,\n # we need to pass an array of width 3 * kernel_support, starting from\n # index +/-(ghost_size - kernel_support) on the lower and upper end.\n # Pystencils then automatically sets the kernel comp. bounds and\n # crunches numbers in the kernel_support thickness zone at the boundary.\n # Start of Y axis\n advection_flux_pyst_kernel(\n advection_flux=advection_flux[\n ghost_size - kernel_support : ghost_size + 2 * kernel_support,\n ghost_size:-ghost_size,\n ],\n field=field[\n ghost_size - kernel_support : ghost_size + 2 * kernel_support,\n ghost_size:-ghost_size,\n ],\n velocity=velocity[\n :,\n ghost_size - kernel_support : ghost_size + 2 * kernel_support,\n ghost_size:-ghost_size,\n ],\n inv_dx=inv_dx,\n )\n # End of Y axis\n advection_flux_pyst_kernel(\n advection_flux=advection_flux[\n -(ghost_size + 2 * kernel_support) : field.shape[0]\n - (ghost_size - kernel_support),\n ghost_size:-ghost_size,\n ],\n field=field[\n -(ghost_size + 2 * kernel_support) : field.shape[0]\n - (ghost_size - kernel_support),\n ghost_size:-ghost_size,\n ],\n velocity=velocity[\n :,\n -(ghost_size + 2 * kernel_support) : field.shape[0]\n - (ghost_size - kernel_support),\n ghost_size:-ghost_size,\n ],\n inv_dx=inv_dx,\n )\n # Start of X axis\n advection_flux_pyst_kernel(\n advection_flux=advection_flux[\n :,\n ghost_size - kernel_support : ghost_size + 2 * kernel_support,\n ],\n field=field[\n :,\n ghost_size - kernel_support : ghost_size + 2 * kernel_support,\n ],\n velocity=velocity[\n :,\n :,\n ghost_size - kernel_support : ghost_size + 2 * kernel_support,\n ],\n inv_dx=inv_dx,\n )\n # End of X axis\n advection_flux_pyst_kernel(\n advection_flux=advection_flux[\n :,\n -(ghost_size + 2 * kernel_support) : field.shape[1]\n - (ghost_size - kernel_support),\n ],\n field=field[\n :,\n -(ghost_size + 2 * kernel_support) : field.shape[1]\n - (ghost_size - kernel_support),\n ],\n velocity=velocity[\n :,\n :,\n -(ghost_size + 2 * kernel_support) : field.shape[1]\n - (ghost_size - kernel_support),\n ],\n inv_dx=inv_dx,\n )\n\n return advection_flux_conservative_eno3_pyst_mpi_kernel_2d\n","sub_path":"sopht_mpi/numeric/eulerian_grid_ops/stencil_ops_2d/advection_flux_mpi_2d.py","file_name":"advection_flux_mpi_2d.py","file_ext":"py","file_size_in_byte":5239,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"264301395","text":"#!/usr/bin/env python\n\nimport logging\nfrom argparse import ArgumentParser\nimport copy\n\nimport theano\nfrom theano import tensor\nfrom blocks.algorithms import GradientDescent, Momentum\nfrom blocks.model import Model\nfrom blocks.extensions import FinishAfter, Timing, Printing\nfrom blocks.extensions.monitoring import (DataStreamMonitoring,\n TrainingDataMonitoring)\nfrom blocks.main_loop import MainLoop\nfrom fuel.streams import DataStream\nfrom fuel.schemes import SequentialScheme\nfrom fuel.transformers import Mapping, ForceFloatX\n\nfrom dl_tutorials.blocks.extensions.plot import (\n PlotManager, Plotter, Display2DData\n)\nfrom dl_tutorials.part_2_mlp.neural_network import NeuralNetwork\nfrom dl_tutorials.utils.build_2d_datasets import build_2d_datasets\n\n\n# Getting around having tuples as argument and output\nclass TupleMapping(object):\n def __init__(self, fn):\n self.fn = fn\n\n def __call__(self, args):\n return (self.fn(args[0]), )\n\n\ndef main(dataset_name='sklearn', num_epochs=100):\n x = tensor.matrix('features')\n y = tensor.lmatrix('targets')\n\n neural_net = NeuralNetwork(input_dim=2, n_hidden=[20])\n probs = neural_net.get_probs(features=x)\n params = neural_net.get_params()\n cost = neural_net.get_cost(probs=probs, targets=y).mean()\n cost.name = 'cost'\n misclassification = neural_net.get_misclassification(\n probs=probs, targets=y\n ).mean()\n misclassification.name = 'misclassification'\n\n train_dataset, test_dataset = build_2d_datasets(dataset_name=dataset_name)\n\n algorithm = GradientDescent(\n cost=cost,\n params=params,\n step_rule=Momentum(learning_rate=0.1,\n momentum=0.1))\n\n train_data_stream = DataStream(\n dataset=train_dataset,\n iteration_scheme=SequentialScheme(\n examples=train_dataset.num_examples,\n batch_size=40,\n )\n )\n valid_data_stream = ForceFloatX(\n data_stream=DataStream(\n dataset=test_dataset,\n iteration_scheme=SequentialScheme(\n examples=range(10) + range(200, 210),\n batch_size=400,\n )\n )\n )\n test_data_stream = ForceFloatX(\n data_stream=DataStream(\n dataset=test_dataset,\n iteration_scheme=SequentialScheme(\n examples=test_dataset.num_examples,\n batch_size=400,\n )\n )\n )\n\n model = Model(cost)\n\n extensions = []\n extensions.append(Timing())\n extensions.append(FinishAfter(after_n_epochs=num_epochs))\n extensions.append(DataStreamMonitoring(\n [cost, misclassification],\n test_data_stream,\n prefix='test'))\n extensions.append(DataStreamMonitoring(\n [cost, misclassification],\n valid_data_stream,\n prefix='valid'))\n extensions.append(TrainingDataMonitoring(\n [cost, misclassification],\n prefix='train',\n after_epoch=True))\n\n scoring_function = theano.function([x], probs)\n\n plotters = []\n plotters.append(Plotter(\n channels=[['test_cost', 'test_misclassification',\n 'train_cost', 'train_misclassification']],\n titles=['Costs']))\n score_train_stream = Mapping(data_stream=copy.deepcopy(train_data_stream),\n mapping=TupleMapping(scoring_function),\n add_sources=('scores',))\n score_test_stream = Mapping(data_stream=copy.deepcopy(test_data_stream),\n mapping=TupleMapping(scoring_function),\n add_sources=('scores',))\n plotters.append(Display2DData(\n data_streams=[score_train_stream, copy.deepcopy(train_data_stream),\n score_test_stream, copy.deepcopy(test_data_stream)],\n radius=0.01\n ))\n\n extensions.append(PlotManager('2D examples', plotters=plotters,\n after_epoch=False,\n every_n_epochs=50,\n after_training=True))\n extensions.append(Printing())\n main_loop = MainLoop(model=model,\n data_stream=train_data_stream,\n algorithm=algorithm,\n extensions=extensions)\n\n main_loop.run()\n\n\nif __name__ == \"__main__\":\n logging.basicConfig(level=logging.INFO)\n parser = ArgumentParser(\"An example of training an MLP on\"\n \" a 2D dataset.\")\n parser.add_argument(\"--num-epochs\", type=int, default=100,\n help=\"Number of training epochs to do.\")\n parser.add_argument(\"--dataset\", default=\"sklearn\", nargs=\"?\",\n help=(\"Dataset to use.\"))\n args = parser.parse_args()\n main(dataset_name=args.dataset, num_epochs=args.num_epochs)\n","sub_path":"part_2_mlp/nn_main.py","file_name":"nn_main.py","file_ext":"py","file_size_in_byte":4874,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"281120623","text":"import sys\nimport socket\nimport threading\nimport time\ntry:\n s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n # 防止socket server重启后端口被占用(socket.error: [Errno 98] Address already in use)\n s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\n s.bind(('127.0.0.1', 6666))\n s.listen(10)\nexcept socket.error as msg:\n print(msg)\n sys.exit(1)\nprint('Waiting connection...')\n\n\n\ndef deal_data(conn, addr):\n print('Accept new connection from {0}'.format(addr))\n conn.send(('Hi, Welcome to the server!').encode())#send内容形式一\n while True:\n data = conn.recv(1024)\n print('{0} client send data is {1}'.format(addr, data.decode()))\n # time.sleep(1)\n # if data == 'exit' or not data:\n # print('{0} connection close'.format(addr))\n # conn.send(bytes('Connection closed!'),'UTF-8')#send内容形式二\n # break\n # conn.send(bytes('Hello, {0}'.format(data),\"UTF-8\"))\n # conn.close()\n\nwhile True:\n conn, addr = s.accept()\n t = threading.Thread(target=deal_data, args=(conn, addr))\n t.start()","sub_path":"Tornado/25.WebSocket聊天室/face501/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":1123,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"546496853","text":"import tkinter as tk \nfrom tkinter import Frame, Button, PanedWindow, Text\nfrom tkinter import X, Y, BOTH\n\nimport numpy as np \nfrom matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2TkAgg\nfrom matplotlib import pyplot as plt\nfrom matplotlib.figure import Figure\n\nfrom tone_curve import CurveBrowser\n\n\"\"\"\nnote\nif you will distribute others to whom you want not disclose this scripts\ntry to use 'pyinstaller' module\nUsage Part 1.\ninstall python 3.4 (many developer say it does not work well on python 3.5 )\nso please make vertual environments\n> conda create -n installenv python=3.4 numpy matplotlib scipy\nUsage Part 2.\nthen activate installenv\n> activate installenv\nUsage Part 3.\nbuild python code into .exe form\n(installenv) > pip install pyinstaller\n(installenv) > pyinstaller plot_win.py --onefile --noconsole\n\nRemark\nwhen run plot_win.exe I can't initialize this app and occur error\n'fail to run script plot_win'\nI had some experiments and found that image reading library disturbs \ninitializing this app e.g.\nfrom scipy.misc import imread\nfrom PIL import Image\nbut opencv library cv2 works!!!!!!\n\"\"\"\nfrom scipy.misc import imread\n\nclass ImageViewer(object):\n def __init__(self,root):\n self.root=root\n self.fig,self.ax=plt.subplots()\n self.img=imread('test1.bmp',0)\n self.draw_zone=self.ax.imshow(self.img,'gray')\n plot_frame=Frame(self.root)\n self.root.add(plot_frame)\n canvas=FigureCanvasTkAgg(self.fig,master=plot_frame)\n toolbar = NavigationToolbar2TkAgg(canvas, plot_frame)\n toolbar.update()\n self.canvas=canvas \n\nclass ToneCurve(CurveBrowser):\n def __init__(self,fig,ax,listener):\n super(ToneCurve, self).__init__(fig,ax)\n self.listener=listener\n\n def notify(self):\n tone_curve=self.tone_curve\n toned=tone_curve(self.listener.img)\n self.listener.draw_zone.set_data(toned)\n self.listener.fig.canvas.draw()\n\n\nclass ToneCurveViewer(object):\n def __init__(self,root,listener=None):\n self.root=root\n fig,ax=plt.subplots(figsize=(6,6))\n self.ax=ax\n self.ax.set_xlim([0,255])\n self.ax.set_ylim([0,255])\n browser=ToneCurve(fig,self.ax,listener)\n\n plot_frame=Frame(self.root)\n self.root.add(plot_frame)\n canvas=FigureCanvasTkAgg(fig,master=plot_frame)\n \n canvas.mpl_connect('pick_event',browser.onpick)\n canvas.mpl_connect('motion_notify_event',browser.on_motion)\n #both bind is very important for release event but I do not know why\n canvas._tkcanvas.bind('button_release_event',browser.on_release)\n canvas.mpl_connect('button_release_event', browser.on_release)\n\n toolbar = NavigationToolbar2TkAgg(canvas, plot_frame)\n toolbar.update()\n self.canvas=canvas \n self.canvas._tkcanvas.pack(side=tk.TOP, fill=tk.BOTH, expand=1)\n\ndef main():\n root=tk.Tk()\n pack_windows(root)\n root.protocol(\"WM_DELETE_WINDOW\")\n root.mainloop()\n\ndef pack_windows(root):\n main_paned_window = PanedWindow(root)\n main_paned_window.pack(fill=BOTH, expand=True)\n\n tone_paned_window=PanedWindow(relief=tk.GROOVE,bd=3,orient=tk.VERTICAL)\n main_paned_window.add(tone_paned_window)\n \n sub_tone_paned_window=PanedWindow(tone_paned_window)\n tone_paned_window.add(sub_tone_paned_window)\n \n plot_window=PanedWindow()\n main_paned_window.add(plot_window)\n plot_window=ImageViewer(plot_window)\n plot_window.canvas.get_tk_widget().pack(fill=tk.BOTH,expand=True)\n\n tone_window=ToneCurveViewer(sub_tone_paned_window,plot_window)\n tone_window.canvas.get_tk_widget().pack(fill=tk.BOTH,expand=True)\n space_frame=Frame()\n tone_paned_window.add(space_frame)\n \n button=Button(space_frame,text=\"something\")\n button.pack()\n\n def quit_app():\n root.quit()\n root.destroy()\n\n quitbutton=Button(space_frame,text=\"exit\",command=quit_app)\n quitbutton.pack()\n\nif __name__ == '__main__':\n main()","sub_path":"tkinter/appExer/toneCurve/plot_win.py","file_name":"plot_win.py","file_ext":"py","file_size_in_byte":4032,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"279880513","text":"# Adapted from https://gitlab.com/cheminfIBB/tfbio/-/blob/master/tfbio/data.py\n\nimport pickle\nimport numpy as np\nfrom openbabel import pybel\n\nclass Featurizer():\n \"\"\"Calcaulates atomic features for molecules. Features can encode atom type,\n native pybel properties or any property defined with SMARTS patterns\n\n Attributes\n ----------\n FEATURE_NAMES: list of strings\n Labels for features (in the same order as features)\n NUM_ATOM_CLASSES: int\n Number of atom codes\n ATOM_CODES: dict\n Dictionary mapping atomic numbers to codes\n NAMED_PROPS: list of string\n Names of atomic properties to retrieve from pybel.Atom object\n CALLABLES: list of callables\n Callables used to calculcate custom atomic properties\n SMARTS: list of SMARTS strings\n SMARTS patterns defining additional atomic properties\n \"\"\"\n\n def __init__(self, atom_codes=None, atom_labels=None,\n named_properties=None, save_molecule_codes=True,\n custom_properties=None, smarts_properties=None,\n smarts_labels=None):\n\n \"\"\"Creates Featurizer with specified types of features. Elements of a\n feature vector will be in a following order: atom type encoding\n (defined by atom_codes), Pybel atomic properties (defined by\n named_properties), molecule code (if present), custom atomic properties\n (defined `custom_properties`), and additional properties defined with\n SMARTS (defined with `smarts_properties`).\n\n Parameters\n ----------\n atom_codes: dict, optional\n Dictionary mapping atomic numbers to codes. It will be used for\n one-hot encoging therefore if n different types are used, codes\n shpuld be from 0 to n-1. Multiple atoms can have the same code,\n e.g. you can use {6: 0, 7: 1, 8: 1} to encode carbons with [1, 0]\n and nitrogens and oxygens with [0, 1] vectors. If not provided,\n default encoding is used.\n atom_labels: list of strings, optional\n Labels for atoms codes. It should have the same length as the\n number of used codes, e.g. for `atom_codes={6: 0, 7: 1, 8: 1}` you\n should provide something like ['C', 'O or N']. If not specified\n labels 'atom0', 'atom1' etc are used. If `atom_codes` is not\n specified this argument is ignored.\n named_properties: list of strings, optional\n Names of atomic properties to retrieve from pybel.Atom object. If\n not specified ['hyb', 'heavyvalence', 'heterovalence',\n 'partialcharge'] is used.\n save_molecule_codes: bool, optional (default True)\n If set to True, there will be an additional feature to save\n molecule code. It is usefeul when saving molecular complex in a\n single array.\n custom_properties: list of callables, optional\n Custom functions to calculate atomic properties. Each element of\n this list should be a callable that takes pybel.Atom object and\n returns a float. If callable has `__name__` property it is used as\n feature label. Otherwise labels 'func' etc are used, where i is\n the index in `custom_properties` list.\n smarts_properties: list of strings, optional\n Additional atomic properties defined with SMARTS patterns. These\n patterns should match a single atom. If not specified, deafult\n patterns are used.\n smarts_labels: list of strings, optional\n Labels for properties defined with SMARTS. Should have the same\n length as `smarts_properties`. If not specified labels 'smarts0',\n 'smarts1' etc are used. If `smarts_properties` is not specified\n this argument is ignored.\n \"\"\"\n\n # Remember namse of all features in the correct order\n self.FEATURE_NAMES = []\n\n if atom_codes is not None:\n if not isinstance(atom_codes, dict):\n raise TypeError('Atom codes should be dict, got %s instead'\n % type(atom_codes))\n codes = set(atom_codes.values())\n for i in range(len(codes)):\n if i not in codes:\n raise ValueError('Incorrect atom code %s' % i)\n\n self.NUM_ATOM_CLASSES = len(codes)\n self.ATOM_CODES = atom_codes\n if atom_labels is not None:\n if len(atom_labels) != self.NUM_ATOM_CLASSES:\n raise ValueError('Incorrect number of atom labels: '\n '%s instead of %s'\n % (len(atom_labels), self.NUM_ATOM_CLASSES))\n else:\n atom_labels = ['atom%s' % i for i in range(self.NUM_ATOM_CLASSES)]\n self.FEATURE_NAMES += atom_labels\n else:\n self.ATOM_CODES = {}\n\n metals = ([3, 4, 11, 12, 13] + list(range(19, 32))\n + list(range(37, 51)) + list(range(55, 84))\n + list(range(87, 104)))\n\n # List of tuples (atomic_num, class_name) with atom types to encode.\n atom_classes = [\n (5, 'B'),\n (6, 'C'),\n (7, 'N'),\n (8, 'O'),\n (15, 'P'),\n (16, 'S'),\n (34, 'Se'),\n ([9, 17, 35, 53], 'halogen'),\n (metals, 'metal')\n ]\n\n for code, (atom, name) in enumerate(atom_classes):\n if type(atom) is list:\n for a in atom:\n self.ATOM_CODES[a] = code\n else:\n self.ATOM_CODES[atom] = code\n self.FEATURE_NAMES.append(name)\n\n self.NUM_ATOM_CLASSES = len(atom_classes)\n\n if named_properties is not None:\n if not isinstance(named_properties, (list, tuple, np.ndarray)):\n raise TypeError('named_properties must be a list')\n allowed_props = [prop for prop in dir(pybel.Atom)\n if not prop.startswith('__')]\n for prop_id, prop in enumerate(named_properties):\n if prop not in allowed_props:\n raise ValueError(\n 'named_properties must be in pybel.Atom attributes,'\n ' %s was given at position %s' % (prop_id, prop)\n )\n self.NAMED_PROPS = named_properties\n else:\n # pybel.Atom properties to save\n self.NAMED_PROPS = ['hyb', 'heavydegree', 'heterodegree',\n 'partialcharge']\n self.FEATURE_NAMES += self.NAMED_PROPS\n\n if not isinstance(save_molecule_codes, bool):\n raise TypeError('save_molecule_codes should be bool, got %s '\n 'instead' % type(save_molecule_codes))\n self.save_molecule_codes = save_molecule_codes\n if save_molecule_codes:\n # Remember if an atom belongs to the ligand or to the protein\n self.FEATURE_NAMES.append('molcode')\n\n self.CALLABLES = []\n if custom_properties is not None:\n for i, func in enumerate(custom_properties):\n if not callable(func):\n raise TypeError('custom_properties should be list of'\n ' callables, got %s instead' % type(func))\n name = getattr(func, '__name__', '')\n if name == '':\n name = 'func%s' % i\n self.CALLABLES.append(func)\n self.FEATURE_NAMES.append(name)\n\n if smarts_properties is None:\n # SMARTS definition for other properties\n self.SMARTS = [\n '[#6+0!$(*~[#7,#8,F]),SH0+0v2,s+0,S^3,Cl+0,Br+0,I+0]',\n '[a]',\n '[!$([#1,#6,F,Cl,Br,I,o,s,nX3,#7v5,#15v5,#16v4,#16v6,*+1,*+2,*+3])]',\n '[!$([#6,H0,-,-2,-3]),$([!H0;#7,#8,#9])]',\n '[r]'\n ]\n smarts_labels = ['hydrophobic', 'aromatic', 'acceptor', 'donor',\n 'ring']\n elif not isinstance(smarts_properties, (list, tuple, np.ndarray)):\n raise TypeError('smarts_properties must be a list')\n else:\n self.SMARTS = smarts_properties\n\n if smarts_labels is not None:\n if len(smarts_labels) != len(self.SMARTS):\n raise ValueError('Incorrect number of SMARTS labels: %s'\n ' instead of %s'\n % (len(smarts_labels), len(self.SMARTS)))\n else:\n smarts_labels = ['smarts%s' % i for i in range(len(self.SMARTS))]\n\n # Compile patterns\n self.compile_smarts()\n self.FEATURE_NAMES += smarts_labels\n\n def compile_smarts(self):\n self.__PATTERNS = []\n for smarts in self.SMARTS:\n self.__PATTERNS.append(pybel.Smarts(smarts))\n\n def encode_num(self, atomic_num):\n \"\"\"Encode atom type with a binary vector. If atom type is not included in\n the `atom_classes`, its encoding is an all-zeros vector.\n\n Parameters\n ----------\n atomic_num: int\n Atomic number\n\n Returns\n -------\n encoding: np.ndarray\n Binary vector encoding atom type (one-hot or null).\n \"\"\"\n\n if not isinstance(atomic_num, int):\n raise TypeError('Atomic number must be int, %s was given'\n % type(atomic_num))\n\n encoding = np.zeros(self.NUM_ATOM_CLASSES)\n try:\n encoding[self.ATOM_CODES[atomic_num]] = 1.0\n except:\n pass\n return encoding\n\n def find_smarts(self, molecule):\n \"\"\"Find atoms that match SMARTS patterns.\n\n Parameters\n ----------\n molecule: pybel.Molecule\n\n Returns\n -------\n features: np.ndarray\n NxM binary array, where N is the number of atoms in the `molecule`\n and M is the number of patterns. `features[i, j]` == 1.0 if i'th\n atom has j'th property\n \"\"\"\n\n if not isinstance(molecule, pybel.Molecule):\n raise TypeError('molecule must be pybel.Molecule object, %s was given'\n % type(molecule))\n\n features = np.zeros((len(molecule.atoms), len(self.__PATTERNS)))\n\n for (pattern_id, pattern) in enumerate(self.__PATTERNS):\n atoms_with_prop = np.array(list(*zip(*pattern.findall(molecule))),\n dtype=int) - 1\n features[atoms_with_prop, pattern_id] = 1.0\n return features\n\n def get_features(self, molecule, molcode=None):\n \"\"\"Get coordinates and features for all heavy atoms in the molecule.\n\n Parameters\n ----------\n molecule: pybel.Molecule\n molcode: float, optional\n Molecule type. You can use it to encode whether an atom belongs to\n the ligand (1.0) or to the protein (-1.0) etc.\n\n Returns\n -------\n coords: np.ndarray, shape = (N, 3)\n Coordinates of all heavy atoms in the `molecule`.\n features: np.ndarray, shape = (N, F)\n Features of all heavy atoms in the `molecule`: atom type\n (one-hot encoding), pybel.Atom attributes, type of a molecule\n (e.g protein/ligand distinction), and other properties defined with\n SMARTS patterns\n \"\"\"\n\n if not isinstance(molecule, pybel.Molecule):\n raise TypeError('molecule must be pybel.Molecule object,'\n ' %s was given' % type(molecule))\n if molcode is None:\n if self.save_molecule_codes is True:\n raise ValueError('save_molecule_codes is set to True,'\n ' you must specify code for the molecule')\n elif not isinstance(molcode, (float, int)):\n raise TypeError('motlype must be float, %s was given'\n % type(molcode))\n\n coords = []\n features = []\n heavy_atoms = []\n\n for i, atom in enumerate(molecule):\n # ignore hydrogens and dummy atoms (they have atomicnum set to 0)\n if atom.atomicnum > 1:\n heavy_atoms.append(i)\n coords.append(atom.coords)\n\n features.append(np.concatenate((\n self.encode_num(atom.atomicnum),\n [atom.__getattribute__(prop) for prop in self.NAMED_PROPS],\n [func(atom) for func in self.CALLABLES],\n )))\n\n coords = np.array(coords, dtype=np.float32)\n features = np.array(features, dtype=np.float32)\n if self.save_molecule_codes:\n features = np.hstack((features,\n molcode * np.ones((len(features), 1))))\n features = np.hstack([features,\n self.find_smarts(molecule)[heavy_atoms]])\n\n if np.isnan(features).any():\n raise RuntimeError('Got NaN when calculating features')\n\n return coords, features\n\n def to_pickle(self, fname='featurizer.pkl'):\n \"\"\"Save featurizer in a given file. Featurizer can be restored with\n `from_pickle` method.\n\n Parameters\n ----------\n fname: str, optional\n Path to file in which featurizer will be saved\n \"\"\"\n\n # patterns can't be pickled, we need to temporarily remove them\n patterns = self.__PATTERNS[:]\n del self.__PATTERNS\n try:\n with open(fname, 'wb') as f:\n pickle.dump(self, f)\n finally:\n self.__PATTERNS = patterns[:]\n\n @staticmethod\n def from_pickle(fname):\n \"\"\"Load pickled featurizer from a given file\n\n Parameters\n ----------\n fname: str, optional\n Path to file with saved featurizer\n\n Returns\n -------\n featurizer: Featurizer object\n Loaded featurizer\n \"\"\"\n with open(fname, 'rb') as f:\n featurizer = pickle.load(f)\n featurizer.compile_smarts()\n return featurizer","sub_path":"apps/drug_target_interaction/giant/featurizer.py","file_name":"featurizer.py","file_ext":"py","file_size_in_byte":14311,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"140497669","text":"import os, shutil\nimport wget, zipfile\nimport cv2\nimport warnings\nimport random\nimport string\nimport csv\nimport re\nimport numpy as np\nimport paddle\nimport paddle.fluid as fluid\nfrom lime.lime_text import LimeTextExplainer\nfrom collections import OrderedDict \nimport matplotlib.pyplot as plt\n\n# Download and unzip data\n\nprint('downloading...')\nurl = \"https://archive.ics.uci.edu/ml/machine-learning-databases/00461/drugLib_raw.zip\"\nwget.download(url, './drugLibTest_raw.zip')\n\nprint('unziping...')\nwith zipfile.ZipFile('./drugLibTest_raw.zip', 'r') as zip_ref:\n zip_ref.extractall('./data')\n\n# Read dataset\n\ntext = [] # This is our text\ny_train = [] # And these are ratings given by customers\n\n# Select only rating and text from the whole dataset\nwith open(\"./data/drugLibTest_raw.tsv\") as df:\n rd = csv.reader(df, delimiter=\"\\t\", quotechar='\"')\n for i, row in enumerate(rd):\n if i > 0:\n if int(row[2]) >= 8:\n rating = 0\n else:\n rating = 1\n text.append(row[6])\n y_train.append([rating])\ny_train = np.array(y_train).astype('int64')\n\n# text_tokenizer helps us to turn each word into integers. By selecting maximum number of features\n# we also keep the most frequent words. Additionally, by default, all punctuation is removed.\n\ndef text_tokenizer(text, max_words):\n freq = dict()\n remove_punc = text.translate(str.maketrans('', '', string.punctuation))\n words = re.findall(r\"[\\w']+\", remove_punc)\n for word in words:\n if isinstance(word, str):\n word_low = word.lower()\n if word_low in freq:\n freq[word_low] += 1\n else:\n freq[word_low] = 1\n\n freq_sorted = sorted(freq.items(), key=lambda kv:(kv[1], kv[0]), reverse=True)\n\n word2idx, idx2word = dict(), dict()\n count = 0\n for key, value in freq_sorted: \n if count < max_words:\n word2idx[key] = count\n idx2word[count] = key\n count += 1\n\n return word2idx, idx2word\n\n# Then, we need to fit the tokenizer object to our text data\n\nmax_features = 1000\nw2i, i2w = text_tokenizer(' '.join(text), max_features)\n\n# Via tokenizer object you can check word indices, word counts and other interesting properties.\n\n# print(w2i)\n\n# Finally, we can replace words in dataset with integers\n\ndef text_to_sequence(text, w2i):\n remove_punc = text.translate(str.maketrans('', '', string.punctuation))\n words = re.findall(r\"[\\w']+\", remove_punc)\n text_ids = []\n for word in words:\n if isinstance(word, str):\n word_low = word.lower()\n if word_low in w2i:\n text_ids.append(int(w2i[word_low]))\n else:\n continue\n return text_ids\n\ndef texts_to_sequences(texts, w2i):\n texts_ids = []\n for text in texts:\n texts_ids.append(text_to_sequence(text, w2i))\n return texts_ids\n\ntext_seqs = texts_to_sequences(text, w2i)\n\n# Define the parameters of the keras model\n\nmaxlen = 30\nbatch_size = 32\nembedding_dims = 50\nfilters = 64\nkernel_size = 3\nhidden_dims = 50\nepochs = 15\n\n# As a final step, restrict the maximum length of all sequences and create a matrix as input for model\n\ndef cut(texts, maxlen):\n ret_texts = []\n for text in texts:\n if len(text) > maxlen:\n ret_texts.append(text[:15])\n else:\n ret_texts.append(text)\n return ret_texts\n\ndef to_lodtensor(data, place = fluid.CPUPlace()):\n seq_lens = [len(seq) for seq in data]\n cur_len = 0\n lod = [cur_len]\n for l in seq_lens:\n cur_len += l\n lod.append(cur_len)\n flattened_data = np.concatenate(data, axis=0).astype(\"int64\")\n flattened_data = flattened_data.reshape([len(flattened_data), 1])\n\n res = fluid.LoDTensor()\n res.set(flattened_data, place)\n res.set_lod([lod])\n return res\n\nx_train = cut(text_seqs, maxlen)\n\n# Lets print the first 2 rows and see that max length of first 2 sequences equals to 15\n\n# print(x_train[0:2])\n\n# Create a model\n\nx = fluid.layers.data(name=\"x\", shape=[1], dtype='int64', lod_level=1)\ny = fluid.layers.data(name=\"y\", shape=[1], dtype='int64')\n\nh_emb = fluid.layers.embedding(x, size=[max_features, embedding_dims])\nh_drop1 = fluid.layers.dropout(h_emb, dropout_prob=0.2)\nh_conv = fluid.layers.sequence_conv(h_drop1, num_filters=filters, \n filter_size=kernel_size, act='relu')\nh_pool = fluid.layers.sequence_pool(h_conv, pool_type='max')\nh_fc1 = fluid.layers.fc(h_pool, hidden_dims)\nh_drop2 = fluid.layers.dropout(h_fc1, dropout_prob=0.2)\nh_act1 = fluid.layers.relu(h_drop2)\npred = fluid.layers.fc(h_act1, 2)\n\npred_out = fluid.layers.softmax(pred)\n\ntest_program = fluid.default_main_program().clone(for_test=True)\n\ncost = fluid.layers.softmax_with_cross_entropy(pred, y)\nloss = fluid.layers.reduce_mean(cost)\nacc = fluid.layers.accuracy(pred, y)\n\noptimizer = fluid.optimizer.Adam(learning_rate=0.001)\noptimizer.minimize(loss)\n\nplace = fluid.CPUPlace()\nexe = fluid.Executor(place)\nexe.run(fluid.default_startup_program())\n\n# define data reader\ndef batch_creator(x_data, y_data, batch_size, drop_last=False):\n def batch_generator():\n batch_x, batch_y = [], []\n data = zip(x_data, y_data)\n for x, y in data:\n batch_x.append(x)\n batch_y.append(y)\n if len(batch_x) >= batch_size:\n yield to_lodtensor(batch_x), np.array(batch_y)\n batch_x, batch_y = [], []\n if batch_x and not drop_last:\n yield to_lodtensor(batch_x), np.array(batch_y)\n return batch_generator\n\ntrain_dataset = batch_creator(x_train, y_train, batch_size)\n\nfor epoch in range(epochs):\n print(\"epoch \", epoch)\n mean_loss, mean_acc = [], []\n for batch_x, batch_y in train_dataset():\n out = exe.run(\n feed={'x' : batch_x, 'y' : batch_y}, \n fetch_list=[loss.name, acc.name])\n mean_loss.append(float(out[0]))\n mean_acc.append(float(out[1]))\n mean_loss = np.array(mean_loss).mean()\n mean_acc = np.array(mean_acc).mean()\n print(\"train loss: %.6f, acc: %.4f\" % (mean_loss, mean_acc))\n\n# Understanding lime for Keras Embedding Layers\n\n# In order to explain a text with LIME, we should write a preprocess function\n# which will help to turn words into integers. Therefore, above mentioned steps \n# (how to encode a text) should be repeated BUT within a function. \n# As we already have had a tokenizer object, we can apply the same object to train/test or a new text.\n\ndef inference(x_batch):\n return exe.run(\n program = test_program,\n feed={'x' : to_lodtensor(x_batch)}, \n fetch_list=[pred_out.name])[0]\n\ndef get_embedding_explanation(input_text, w2i):\n text_to_seq = texts_to_sequences(input_text, w2i)\n cut_seq = cut(text_to_seq, maxlen)\n return cut_seq\n\ndef classifer(input_text):\n data = get_embedding_explanation(input_text, w2i)\n pred = inference(data)\n return pred\n\n# Lets choose some text to explain\nsentence_to_explain = text[1]\nprint('\\n' + sentence_to_explain + '\\n')\n\nexplainer = LimeTextExplainer(class_names=['high rating', 'low rating'])\nexplanation = explainer.explain_instance(\n sentence_to_explain, \n classifer,\n num_features=10,\n num_samples=10000)\n\nexplanation.show_in_notebook(text=True)\nexplanation.save_to_file('./explanation.html')\n","sub_path":"part4 easy tutorials/text_explanation_lime/run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":7349,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"427870807","text":"import pandas as pd\nimport numpy as np\nfrom marginal import marginal\nimport urllib\nimport json\nfrom typing import Dict, List\n\n\nALL_ITEMS = pd.read_json(\"http://localhost:9000/users/1/evaluated_hotels_charge\")\nDEFAULT_SCORE_TYPE_LIST = ['chargeScore', 'distanceScore', 'serviceScore', 'locationScore', 'roomScore',\n 'bathScore', 'equipmentScore', 'mealScore']\nNORM_DICT = {x:marginal.Norm(ALL_ITEMS[x]) for x in DEFAULT_SCORE_TYPE_LIST}\n\n\ndef kl_divergence_between_population_and_users(users_model: marginal.Norm, score_type: str) -> float:\n if score_type not in DEFAULT_SCORE_TYPE_LIST:\n raise ValueError\n population = NORM_DICT[score_type]\n mean1 = population.mean\n mean2 = users_model.mean\n var1 = population.sd ** 2\n var2 = users_model.sd ** 2\n return (np.log(var2/var1) + (var1/var2) + (((mean1 - mean2) ** 2) / var2) - 1) / 2\n\n\ndef list_of_users_axis_has_weight(user_id: int) -> List[str]:\n preference = get_users_preferences(user_id)\n return [k for k, v in preference.items() if not v == 0]\n\n\ndef get_users_preferences(user_id: int) -> Dict[str, float]:\n response = urllib.request.urlopen('http://localhost:9000/users/' + str(user_id) + '/preferences')\n data = response.read().decode('utf8')\n return json.loads(data)\n\n\ndef get_users_main_axis(user_id: int) -> Dict[str, float]:\n preference = get_users_preferences(user_id)\n sorted_pr = [k for k, v in sorted(preference.items(), key=lambda x: x[1])]\n return sorted_pr[-1]\n\n\n","sub_path":"out/production/research/service/data_service.py","file_name":"data_service.py","file_ext":"py","file_size_in_byte":1507,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"357506005","text":"#!/usr/bin/env python3\nimport os\nfrom setuptools import find_packages, setup\nfrom pathlib import Path\n\nPACKAGE_NAME = \"cnocr\"\n\nhere = Path(__file__).parent\n\nlong_description = (here / \"README.md\").read_text(encoding=\"utf-8\")\n\nabout = {}\nexec(\n (here / PACKAGE_NAME.replace('.', os.path.sep) / \"__version__.py\").read_text(\n encoding=\"utf-8\"\n ),\n about,\n)\n\nrequired = [\n 'numpy>=1.14.0,<1.20.0',\n 'pillow>=5.3.0',\n 'mxnet-cu100>=1.5.0,<1.7.0',\n 'gluoncv>=0.3.0,<0.7.0',\n]\nextras_require = {\n \"dev\": [\"pip-tools\", \"pytest\", \"python-Levenshtein\"],\n}\n\nsetup(\n name=PACKAGE_NAME,\n version=about['__version__'],\n description=\"Simple package for Chinese OCR, with small pretrained models\",\n long_description=long_description,\n long_description_content_type=\"text/markdown\",\n author='breezedeus',\n author_email='breezedeus@163.com',\n license='Apache 2.0',\n url='https://github.com/breezedeus/cnocr',\n platforms=[\"Mac\", \"Linux\", \"Windows\"],\n packages=find_packages(),\n include_package_data=True,\n install_requires=required,\n extras_require=extras_require,\n zip_safe=False,\n classifiers=[\n 'Development Status :: 4 - Beta',\n 'Operating System :: OS Independent',\n 'Intended Audience :: Developers',\n 'License :: OSI Approved :: Apache Software License',\n 'Programming Language :: Python',\n 'Programming Language :: Python :: Implementation',\n 'Programming Language :: Python :: 3',\n 'Programming Language :: Python :: 3.4',\n 'Programming Language :: Python :: 3.5',\n 'Programming Language :: Python :: 3.6',\n 'Topic :: Software Development :: Libraries'\n ],\n)\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1708,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"410868069","text":"# 0922~\n# 완전통과\ndef jaccard(s1, s2):\n if len(s1)==0 and len(s2)==0:\n return 1\n\n set1 = list(set(s1))\n set2 = list(set(s2))\n\n OR = list(set(s1)&set(s2))\n AND = list(set(s1)|set(s2))\n\n # OR = [1,2]\n # AND = [1,2,3,4]\n c,d=0,0\n for i in OR:\n c+=min(s1.count(i),s2.count(i))\n print(c)\n for j in AND:\n if j in OR:\n d+=max(s1.count(j),s2.count(j))\n else:\n if j in set1:\n d+=s1.count(j)\n else:\n d+=s2.count(j)\n print(d)\n return float(c)/d\n\nstr1 = input().lower()\nstr2 = input().lower()\n\nchar = \"`1234567890-=~!@#$%^&*()_+[]\\;',./{}|:\\\"<>? \"\n\nstr1 = list(str1)\nstr2 = list(str2)\n\nllist1 = []\ni=0\nwhile(i 0:\n return min(timestamps), max(timestamps)\n else:\n return None, None\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"eksitools/db.py","file_name":"db.py","file_ext":"py","file_size_in_byte":2176,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"286274299","text":"#!/usr/bin/env python3\nimport csv\nimport json\nimport pprint\nimport sys\nfrom collections import Counter\nfrom urllib.parse import urlparse, parse_qsl\n\n\nFIELD_NAMES = [\n \"scheme\",\n \"netloc\",\n \"path\",\n \"params\",\n \"query\",\n \"fragment\",\n]\n\n\ndef main(argv):\n writer = csv.writer(sys.stdout, dialect=\"excel-tab\", lineterminator=\"\\n\")\n\n added_field_counter = Counter()\n for json_file in argv[1:]:\n with open(json_file, \"r\", encoding=\"utf8\") as fd:\n nav_data = json.load(fd)\n\n # distinct_clicked_urls = {record[\"clickedUrl\"] for record in nav_data}\n # print(\n # f\"{json_file}\\t{len(nav_data)}\\t{len(distinct_clicked_urls)}\",\n # file=sys.stderr,\n # )\n\n if nav_data:\n seed_url = nav_data[0][\"clickedUrl\"]\n seed_bits = urlparse(seed_url)\n\n distinct_document_origins = {\n urlparse(record[\"documentUrl\"]).netloc\n for record in nav_data\n if record[\"documentUrl\"] != \"START\"\n }\n distinct_document_origins.add(seed_bits.netloc)\n for origin in distinct_document_origins:\n print(f\"{json_file}\\t{origin}\", file=sys.stderr)\n\n for record in nav_data[1:]:\n click_url = record[\"clickedUrl\"]\n click_bits = urlparse(click_url)\n doc_url = record[\"documentUrl\"]\n doc_bits = urlparse(doc_url)\n for tab_id, nav_url_list in record[\"tabNavigations\"].items():\n if nav_url_list:\n nav_url = nav_url_list[0]\n nav_bits = urlparse(nav_url)\n\n differing_fields = [\n name\n for i, name in enumerate(FIELD_NAMES)\n if (click_bits[i] != nav_bits[i])\n ] or [\"=\"]\n\n click_qsl = set(parse_qsl(click_bits.query)) | set(\n parse_qsl(click_bits.fragment)\n )\n nav_qsl = set(parse_qsl(nav_bits.query)) | set(\n parse_qsl(nav_bits.fragment)\n )\n new_fields = nav_qsl - click_qsl\n new_field_score = sum(\n 10 + len(value) for _, value in new_fields\n )\n\n added_field_counter += Counter(k for k, _ in new_fields)\n\n writer.writerow(\n (\n \"/\".join(differing_fields),\n new_field_score,\n seed_bits.netloc,\n doc_bits.netloc,\n click_url,\n \"same-tab\" if tab_id == \"clicked-tab\" else \"new-tab\",\n len(record[\"tabNavigations\"]),\n nav_url,\n json_file,\n # json.dumps(new_fields),\n # len(nav_url_list),\n # *nav_url_list,\n )\n )\n # print(json.dumps(added_field_counter), file=sys.stderr)\n\n\nif __name__ == \"__main__\":\n main(sys.argv)\n","sub_path":"analyze.py","file_name":"analyze.py","file_ext":"py","file_size_in_byte":3395,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"601202279","text":"import xgboost as xgb\nfrom hyperopt import fmin, tpe, hp, STATUS_OK, Trials\nimport pandas as pd\nfrom sklearn import metrics\n\nparameters={}\n# space of hyperopt parameters\nspace = {'max_depth': hp.choice('max_depth', list(range(3,10,1))),\n 'min_child_weight': hp.choice('min_child_weight', list(range(1,6,1))),\n 'gamma': hp.choice('gamma', [i/50.0 for i in range(10)]),\n 'reg_lambda':hp.choice('reg_lambda', [1e-5, 1e-2, 0.1, 1]),\n 'reg_alpha':hp.choice('reg_alpha', [1e-5, 1e-2, 0.1, 1]),\n 'lr':hp.choice('lr', [0.01, 0.05, 0.001, 0.005]),\n 'n_estimators':hp.choice('n_estimators', list(range(100, 300, 20))),\n 'colsample_bytree':hp.choice('colsample_bytree',[i/100.0 for i in range(75,90,5)]),\n 'subsample': hp.choice('subsample', [i/100.0 for i in range(75,90,5)]),\n }\n\ntask_list = ['Acute oral toxicity (LD50)', 'LC50DM', 'BCF', 'LC50', 'IGC50']\nresult_xgb = pd.DataFrame(columns=task_list)\nfor xgb_graph_feats_task in task_list:\n print('***************************************************************************************************')\n print(xgb_graph_feats_task)\n print('***************************************************************************************************')\n args = {}\n training_set = pd.read_csv(xgb_graph_feats_task+'_graph_feats_training.csv', index_col=None)\n valid_set = pd.read_csv(xgb_graph_feats_task+'_graph_feats_valid.csv', index_col=None)\n test_set = pd.read_csv(xgb_graph_feats_task+'_graph_feats_test.csv', index_col=None)\n x_colunms = [x for x in training_set.columns if x not in ['smiles', 'labels']]\n label_columns = ['labels']\n train_x = training_set[x_colunms]\n train_y = training_set[label_columns].values.ravel()\n valid_x = valid_set[x_colunms]\n valid_y = valid_set[label_columns].values.ravel()\n test_x = test_set[x_colunms]\n test_y = test_set[label_columns].values.ravel()\n\n\n def hyperopt_my_xgb(parameter):\n model = xgb.XGBRegressor(learning_rate=parameter['lr'], max_depth=parameter['max_depth'],\n min_child_weight=parameter['min_child_weight'], gamma=parameter['gamma'],\n reg_alpha=parameter['reg_alpha'], reg_lambda=parameter['reg_lambda'],\n subsample=parameter['subsample'], colsample_bytree=parameter['colsample_bytree'],\n n_estimators=parameter['n_estimators'], random_state=2020, n_jobs=6)\n model.fit(train_x, train_y)\n\n # valid set\n valid_prediction = model.predict(valid_x)\n r2 = metrics.r2_score(valid_y, valid_prediction)\n return {'loss':-r2, 'status':STATUS_OK, 'model':model}\n\n\n # hyper parameter optimization\n trials = Trials()\n best = fmin(hyperopt_my_xgb, space, algo=tpe.suggest, trials=trials, max_evals=50)\n print(best)\n\n # load the best model parameters\n args['max_depth'] = list(range(3,10,1))[best['max_depth']]\n args['min_child_weight'] = list(range(1,6,1))[best['min_child_weight']]\n args['gamma'] = [i/50 for i in range(10)][best['gamma']]\n args['reg_lambda'] = [1e-5, 1e-2, 0.1, 1][best['reg_lambda']]\n args['reg_alpha'] = [1e-5, 1e-2, 0.1, 1][best['reg_alpha']]\n args['lr'] = [0.01, 0.05, 0.001, 0.005][best['lr']]\n args['n_estimators'] = list(range(100, 300, 20))[best['n_estimators']]\n args['colsample_bytree'] = [i / 100.0 for i in range(75, 90, 5)][best['colsample_bytree']]\n args['subsample'] = [i / 100.0 for i in range(75, 90, 5)][best['subsample']]\n\n result = []\n for i in range(10):\n model = xgb.XGBRegressor(learning_rate=args['lr'], max_depth=args['max_depth'],\n min_child_weight=args['min_child_weight'], gamma=args['gamma'],\n reg_alpha=args['reg_alpha'], reg_lambda=args['reg_lambda'],\n subsample=args['subsample'], colsample_bytree=args['colsample_bytree'],\n n_estimators=args['n_estimators'], seed=2020+i, n_jobs=6)\n model.fit(train_x, train_y)\n test_prediction = model.predict(test_x)\n r2 = metrics.r2_score(test_y, test_prediction)\n result.append(r2)\n result_xgb[xgb_graph_feats_task] = result\n result_pd = pd.DataFrame(result)\n result_pd.to_csv(xgb_graph_feats_task+'_graph_feats_result.csv', index=False)\n parameters[str(xgb_graph_feats_task)]=args\nresult_xgb.to_csv('XGB_graph_feats_result_regression.csv', index=False)\nfilename = open('xgb_graph_feats_parameters_regression.txt', 'w')\nfor k,v in parameters.items():\n filename.write(k + ':' + str(v))\n filename.write('\\n')\nfilename.close()\n\n\n","sub_path":"experiment/XGBoost_Graph_feats_regression.py","file_name":"XGBoost_Graph_feats_regression.py","file_ext":"py","file_size_in_byte":4705,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"28564493","text":"def mayor():\n try:\n print(\"\\n¡Hola Usuario!\")\n x = int(input(\"Digite el Primer Número: \"))\n y = int(input(\"Digite el Segundo Número: \"))\n if x == y:\n print(\"Ambos números son iguales...\")\n mayor()\n elif x > y:\n print(x, \"es mayor que\", y )\n mayor()\n elif x < y:\n print(y, \"es mayor que\", x)\n mayor()\n except:\n print(\"Datos erroneos...\")\n mayor()\nmayor()","sub_path":"Desarrollo Examen/#3.py","file_name":"#3.py","file_ext":"py","file_size_in_byte":485,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"238818106","text":"import os\nfrom flask import Flask,current_app,g\nfrom flask.cli import with_appcontext\n\n\ndef create_app(test_config=None):\n #create and configure the app\n app=Flask(__name__, instance_relative_config=True)\n app.config.from_mapping(\n SECRET_KEY='dev',\n )\n\n if test_config is None:\n #Load the instance config, if it exists, when not testing\n app.config.from_pyfile('config.py',silent=True)\n else:\n #Load the test config if passed \n aqpp.config.from_mapping(test_config)\n\n #ensure the instance folder exists\n try:\n os.makedirs(app.instance_path)\n except OSError:\n pass\n\n #a simple page that says hello\n @app.route('/hello')\n def hello():\n return 'Hello, World!'\n\n from . import db\n db.init_app(app)\n\n from . import auth\n app.register_blueprint(auth.bp)\n\n from . import application\n app.register_blueprint(application.bp)\n app.add_url_rule('/',endpoint='index')\n\n return app\n","sub_path":"flask-archive/flaskr/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":986,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"360808317","text":"import unittest\nimport unittest.mock as mock\nimport tempfile\nimport shutil\nimport os\nimport yaml\nfrom lmctl.config import Config, ConfigParser, ConfigParserError\nfrom lmctl.environment.group import EnvironmentGroup, EnvironmentGroup\nfrom lmctl.environment.lmenv import LmEnvironment\nfrom lmctl.environment.armenv import ArmEnvironment\n\n\nPARSER_TEST_CONFIG_PARTS = \"\"\"\\\nenvironments:\n test:\n alm:\n host: 127.0.0.1\n port: 1111\n protocol: https\n auth_host: auth\n auth_port: 4643\n auth_protocol: http\n username: jack\n password: secret\n kami_port: 34567\n kami_protocol: https\n arm:\n default:\n host: default\n port: 8765\n protocol: http\n test2:\n arm:\n first:\n host: first\n second: \n host: second\n\"\"\"\n\nOLD_PARSER_TEST_CONFIG = \"\"\"\\\ntestlm:\n alm: \n ip_address: 127.0.0.1\n secure_port: True\n username: jack\n auth_address: 127.0.0.2\ntestarm:\n arm:\n default:\n ip_address: 127.0.0.3\n secure_port: False\n\"\"\"\n\nADDRESS_BASED_CONFIG = \"\"\"\\\nenvironments:\n test:\n lm:\n address: http://some.lm.example.com\n arm:\n default:\n address: http://some.arm.example.com\n\"\"\"\nclass TestConfigParser(unittest.TestCase):\n\n def setUp(self):\n self.tmp_dir = tempfile.mkdtemp()\n\n def tearDown(self):\n if self.tmp_dir and os.path.exists(self.tmp_dir):\n shutil.rmtree(self.tmp_dir)\n\n def __write_file(self, file_path, content):\n with open(file_path, 'w') as f:\n f.write(content)\n\n def test_from_file(self):\n config_file_path = os.path.join(self.tmp_dir, 'config.yaml')\n self.__write_file(config_file_path, PARSER_TEST_CONFIG_PARTS)\n config = ConfigParser().from_file(config_file_path)\n self.assertIsNotNone(config)\n self.assertIsInstance(config, Config)\n self.assertEqual(len(config.environments), 2)\n self.assertIn('test', config.environments)\n test_env = config.environments['test']\n self.assertIsInstance(test_env, EnvironmentGroup)\n self.assertIsInstance(test_env.lm, LmEnvironment)\n self.assertEqual(test_env.lm.address, 'https://127.0.0.1:1111')\n self.assertEqual(test_env.lm.auth_address, 'http://auth:4643')\n self.assertEqual(test_env.lm.username, 'jack')\n self.assertEqual(test_env.lm.password, 'secret')\n self.assertEqual(test_env.lm.kami_address, 'https://127.0.0.1:34567')\n arms_config = test_env.arms\n self.assertEqual(len(arms_config), 1)\n default_arm_config = arms_config['default']\n self.assertIsInstance(default_arm_config, ArmEnvironment)\n self.assertEqual(default_arm_config.address, 'http://default:8765')\n self.assertIn('test2', config.environments)\n test2_env = config.environments['test2']\n arms_config = test2_env.arms\n self.assertEqual(len(arms_config), 2)\n self.assertIn('first', arms_config)\n self.assertIn('second', arms_config)\n \n def test_from_file_rewrites_old_config(self):\n config_file_path = os.path.join(self.tmp_dir, 'config.yaml')\n self.__write_file(config_file_path, OLD_PARSER_TEST_CONFIG)\n config = ConfigParser().from_file(config_file_path)\n self.assertEqual(len(config.environments), 2)\n testlm_env = config.environments['testlm']\n self.assertEqual(testlm_env.lm.address, 'https://127.0.0.1')\n self.assertEqual(testlm_env.lm.secure, True)\n self.assertEqual(testlm_env.lm.username, 'jack')\n testarm_env = config.environments['testarm']\n self.assertEqual(testarm_env.arms['default'].address, 'http://127.0.0.3')\n\n @mock.patch('lmctl.ctl.config.ConfigRewriter.rewrite')\n def test_rewrite_fails(self, mock_rewrite):\n config_file_path = os.path.join(self.tmp_dir, 'config.yaml')\n self.__write_file(config_file_path, OLD_PARSER_TEST_CONFIG)\n mock_rewrite.side_effect = ValueError('Mocked error')\n with self.assertRaises(ConfigParserError) as context:\n ConfigParser().from_file(config_file_path)\n self.assertEqual(str(context.exception), 'The configuration file provided ({0}) appears to be a 2.0.X file. \\\n Lmctl attempted to rewrite the file with updated syntax for 2.1.X but failed with the following error: Mocked error'.format(config_file_path))\n","sub_path":"tests/unit/config/test_parser.py","file_name":"test_parser.py","file_ext":"py","file_size_in_byte":4389,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"580500354","text":"\"\"\"flashcards URL Configuration\n\nThe `urlpatterns` list routes URLs to views. For more information please see:\n https://docs.djangoproject.com/en/2.2/topics/http/urls/\nExamples:\nFunction views\n 1. Add an import: from my_app import views\n 2. Add a URL to urlpatterns: path('', views.home, name='home')\nClass-based views\n 1. Add an import: from other_app.views import Home\n 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')\nIncluding another URLconf\n 1. Import the include() function: from django.urls import include, path\n 2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))\n\"\"\"\nfrom django.conf import settings\nfrom django.contrib import admin\nfrom django.urls import path, include\nfrom django.views.generic import RedirectView\nfrom core import views as core_views\nfrom core import json_views\nfrom vocab import views as vocab_views\n\nurlpatterns = [\n path('', RedirectView.as_view(url='/stacks/')),\n path('stacks/', core_views.StackListView.as_view(), name='stack-list'),\n path('stacks//',\n core_views.StackDetailView.as_view(),\n name='stack-detail'),\n path('stacks//create_card/',\n core_views.card_create,\n name='card-create'),\n path('stacks//cards/',\n core_views.stack_all_cards,\n name='stack-all-cards'),\n path('stacks//quiz/',\n core_views.stack_quiz,\n name='stack-quiz'),\n path('card-results//',\n core_views.card_results,\n name='card-results'),\n path('admin/', admin.site.urls),\n path('accounts/', include('registration.backends.default.urls')),\n path('json/stacks//random-card/',\n json_views.random_card,\n name=\"json_random_card\"),\n path('json/card-results//',\n json_views.post_card_results,\n name=\"json_post_card_results\"),\n path('vocab/', vocab_views.vocab_quiz, name=\"vocab-quiz\"),\n path('json/vocab/word/',\n vocab_views.random_word_json,\n name=\"json_random_word\"),\n]\n\nif settings.DEBUG:\n import debug_toolbar\n urlpatterns = [\n path('__debug__/', include(debug_toolbar.urls)),\n\n # For django versions before 2.0:\n # url(r'^__debug__/', include(debug_toolbar.urls)),\n ] + urlpatterns\n","sub_path":"flashcards/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":2333,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"495786481","text":"# enter bunch of words, get hashtags with those words\n\ndef get_hashtags():\n\n words = input('Введи слова через пробел, чтобы получить хештеги. \\nЖми Enter, чтобы закончить ввод и получить результат.\\t > ')\n words = words.split(' ')\n words = ['#'+ word for word in words]\n words = \" \".join(tag for tag in words)\n print(words)\n\nget_hashtags()","sub_path":"automate-the-boring-stuff/get-hashtags.py","file_name":"get-hashtags.py","file_ext":"py","file_size_in_byte":434,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"531034652","text":"import sys\nimport os\nos.environ.setdefault(\"DJANGO_SETTINGS_MODULE\", \"mysite.settings\")\n\nfrom django.contrib.auth.models import User\n\n\ndef dropUser(username):\n '''\n Example usage of this script is as follows.\n ipython mediaviewer/dropUser.py username\n\n Be sure to set the PYTHONPATH env var to the folder\n containing the mediaviewer folder\n '''\n user = User.objects.get(username=username)\n if user:\n user.delete()\n\nif __name__ == '__main__':\n if len(sys.argv) == 2:\n dropUser(sys.argv[1])\n else:\n print('Invalid number of arguments')\n\n","sub_path":"mediaviewer/dropUser.py","file_name":"dropUser.py","file_ext":"py","file_size_in_byte":602,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"592743804","text":"import datetime\nimport json\n\nfrom app import db\nfrom app.models import ResultDetails\nfrom flask import flash, render_template, request, Blueprint, redirect, url_for\n\n\nresultdetails = Blueprint('resultdetails', __name__)\n\n\n@resultdetails.route(\"/resultdetails\", methods=['GET'])\ndef main():\n details = dict()\n details['data'] = []\n data = db.session.query(ResultDetails).order_by(ResultDetails.result_details_id.desc())\n for _data in data:\n details['data'].append({\n 'result_details_id': _data.result_details_id,\n 'sub_task_id': _data.sub_task_id,\n 'result_id': _data.result_id,\n 'model_id': _data.model_id,\n 'prediction_count': _data.prediction_count,\n 'prediction_insert_date': _data.prediction_insert_date,\n 'accuracy_score': _data.accuracy_score,\n 'error_score': _data.error_score,\n 'accuracy_error_score_date': _data.accuracy_error_score_date,\n 'source': _data.source,\n 'prediction_start_time': _data.prediction_start_time,\n 'prediction_end_time': _data.prediction_end_time,\n 'prediction_hour': _data.prediction_hour,\n 'prediction_time': _data.prediction_time,\n })\n\n return json.dumps(details, indent=4, sort_keys=True, default=str)\n\n\n@resultdetails.route(\"/resultdetails/delete\", methods=['GET'])\ndef delete():\n try:\n num_rows_deleted = db.session.query(ResultDetails).delete()\n db.session.commit()\n except:\n db.session.rollback()\n\n return \"Deleted\"\n\n\n@resultdetails.route(\"/api/v1/resultdetails/add\", methods=['POST'])\ndef add():\n message = ''\n status = ''\n print(request.form)\n try:\n result_details = ResultDetails(\n result_id=request.form.get('result_id'),\n sub_task_id=request.form.get('sub_task_id'),\n model_id=request.form.get('model_id'),\n prediction_count=request.form.get('prediction_count'),\n prediction_insert_date=datetime.datetime.strptime(request.form.get('prediction_insert_date'),\n '%Y-%m-%d %H:%M:%S.%f'),\n prediction_hour=request.form.get('prediction_hour'),\n source=request.form.get('source'),\n prediction_start_time=datetime.datetime.strptime(request.form.get('prediction_start_time'),\n '%Y-%m-%d %H:%M:%S.%f'),\n prediction_end_time=datetime.datetime.strptime(request.form.get('prediction_end_time'),\n '%Y-%m-%d %H:%M:%S.%f'),\n prediction_time=request.form.get('prediction_time')\n )\n db.session.add(result_details)\n db.session.commit()\n message = 'ResultDetails Successfully Added'\n status = \"success\"\n except Exception as e:\n db.session.rollback()\n status = \"error\"\n message = e\n finally:\n db.session.close()\n\n\n\n print(message)\n print(status)\n return \"test\"\n","sub_path":"app/api/result_details.py","file_name":"result_details.py","file_ext":"py","file_size_in_byte":3083,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"1196526","text":"import json\n\nimport requests\n\nfrom Common import config\nfrom Common.config import domain, code\n\n\ndef check_serial_number(pc_code, serial_number):\n result = False\n data = {'code': serial_number, 'pcCode': pc_code}\n req = requests.post(config.domain + \"store/api/check\", data)\n req_text = req.text\n try:\n req_text = json.loads(req_text)\n if req_text.get(\"data\"):\n result = req_text.get(\"data\")\n except Exception as e:\n print(e)\n result = req_text\n\n return result\n\n\ndef update_store_pc_info(register_id, address, store_phone):\n url = domain + 'store/api/update'\n data = {\n \"pcAddress\": address,\n \"pcSign\": register_id,\n \"pcPhone\": store_phone,\n \"code\": code\n }\n req = requests.post(url, data=data)\n req = json.loads(req.text)\n if req.get(\"code\") == 200:\n return True\n else:\n return False\n\n\ndef get_store_info():\n url = domain + \"store/api/list?code={}\".format(code)\n req = requests.get(url=url)\n result = json.loads(req.text)\n print(result)\n return result\n\n\n# 验证注册码\ndef check_register_code(pc_code, code):\n result = False\n data = {'code': code, 'pcCode': pc_code}\n req = requests.post(config.domain + \"store/api/check\", data)\n req_text = req.text\n try:\n req_text = json.loads(req_text)\n if req_text.get(\"data\"):\n result = req_text.get(\"data\")\n except Exception as e:\n print(e)\n result = req_text\n\n return result\n\n\ndef get_store_detail():\n url = domain + \"store/api/detail?code={}\".format(code)\n try:\n req = requests.get(url)\n json_data = req.text\n data = json.loads(json_data)\n except Exception as e:\n print(e)\n data = None\n\n return data\n","sub_path":"remote/store_pc_info.py","file_name":"store_pc_info.py","file_ext":"py","file_size_in_byte":1790,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"570447120","text":"from tinychain.chain import Chain, Sync\nfrom tinychain.cluster import Cluster\nfrom tinychain.collection import Column\nfrom tinychain.collection.table import Table\nfrom tinychain.collection.tensor import einsum, Sparse\nfrom tinychain.error import BadRequest\nfrom tinychain.decorators import closure, get_op, post_op, put_op, delete_op\nfrom tinychain.ref import After, Get, If, MethodSubject, While, With\nfrom tinychain.state import Map, Tuple\nfrom tinychain.util import uri, Context, URI\nfrom tinychain.value import Bool, Nil, I64, U64, String\n\nfrom .edge import Edge, ForeignKey\n\nERR_DELETE = \"cannot delete {{column}} {{id}} because it still has edges in the Graph\"\n\n\nclass Schema(object):\n \"\"\"A :class:`Graph` schema which comprises a set of :class:`Table` s and edges between :class:`Table` columns.\"\"\"\n\n def __init__(self, chain):\n if not issubclass(chain, Chain):\n raise ValueError(f\"default Chain type must be a subclass of Chain, not {chain}\")\n\n self.chain = chain\n self.tables = {}\n self.edges = {}\n\n def create_table(self, name, schema):\n \"\"\"Add a :class:`Table` to this `Graph`.\"\"\"\n\n self.tables[name] = schema\n return self\n\n def create_edge(self, name, edge):\n \"\"\"Add an :class:`Edge` between tables in this `Graph`.\"\"\"\n\n assert edge.from_table in self.tables\n from_table = self.tables[edge.from_table]\n\n assert edge.to_table in self.tables\n to_table = self.tables[edge.to_table]\n\n if from_table.key != [Column(edge.column, U64)]:\n raise ValueError(f\"invalid foreign key column: {edge.from_table}.{edge.column} (key is {from_table.key})\")\n\n [pk] = [col for col in from_table.key if col.name == edge.column]\n\n if edge.from_table != edge.to_table:\n if len(to_table.key) != 1:\n raise ValueError(\"the primary key of a Graph node type must be a single U64 column, not\", to_table.key)\n\n [fk] = [col for col in to_table.values if col.name == edge.column]\n if pk != fk:\n raise ValueError(\n f\"primary key {edge.from_table}.{pk.name} does not match foreign key {edge.to_table}.{fk.name}\")\n\n has_index = False\n for (_name, columns) in to_table.indices:\n if columns and columns[0] == edge.column:\n has_index = True\n\n if not has_index:\n raise ValueError(f\"there is no index on {edge.to_table} to support the foreign key on {edge.column}\")\n elif to_table.key != [pk]:\n raise ValueError(f\"Graph node {edge.to_table} self-reference must be to the primary key, not {edge.column}\")\n\n self.edges[name] = edge\n return self\n\n\nclass Graph(Cluster):\n \"\"\"\n A graph database consisting of a set of :class:`Table` s with :class:`U64` primary keys which serve as node IDs.\n\n Relationships are stored in 2D `Sparse` tensors whose coordinates take the form `[from_id, to_id]`.\n The two types of relationships are `Edge` and `ForeignKey`. These are distinguished by the graph schema--\n a table column which has an edge to itself is an `Edge`, otherwise it's a `ForeignKey`. `ForeignKey` relationships\n are automatically updated when a `Table` is updated, but `Edge` relationships require explicit management\n with the `add_edge` and `remove_edge` methods.\n \"\"\"\n\n def _configure(self):\n schema = self._schema()\n\n if schema.tables:\n assert schema.chain is not None\n\n for (label, edge) in schema.edges.items():\n if edge.from_table == edge.to_table:\n setattr(self, label, schema.chain(Edge.zeros([I64.max(), I64.max()], Bool)))\n else:\n setattr(self, label, schema.chain(ForeignKey.zeros([I64.max(), I64.max()], Bool)))\n\n for name in schema.tables:\n if hasattr(self, name):\n raise ValueError(f\"Graph already has an entry called {name}\")\n\n setattr(self, name, schema.chain(graph_table(self, schema, name)))\n\n def _schema(self):\n return Schema(Sync)\n\n def add_edge(self, label, from_node, to_node):\n \"\"\"Mark `from_node` -> `to_node` as `True` in the edge :class:`Tensor` with the given `label`.\"\"\"\n\n edge = Sparse(Get(uri(self), label))\n return edge.write([from_node, to_node], True)\n\n def remove_edge(self, label, from_node, to_node):\n \"\"\"Mark `from_node` -> `to_node` as `False` in the edge :class:`Tensor` with the given `label`.\"\"\"\n\n edge = Sparse(Get(uri(self), label))\n return edge.write([from_node, to_node], False)\n\n\ndef graph_table(graph, schema, table_name):\n table_schema = schema.tables[table_name]\n\n if len(table_schema.key) != 1:\n raise ValueError(\"Graph table key must be a single column of type U64, not\", table_schema.key)\n\n [key_col] = table_schema.key\n if key_col.dtype != U64:\n raise ValueError(\"Graph table key must be type U64, not\", key_col.dtype)\n\n def delete_row(edge, adjacent, row):\n delete_from = adjacent.write([row[edge.column]], False)\n\n to_table = Table(URI(f\"$self/{edge.to_table}\"))\n if edge.cascade:\n delete_to = (\n to_table.delete({edge.column: row[edge.column]}),\n adjacent.write([slice(None), row[edge.column]], False))\n else:\n delete_to = If(\n adjacent[:, row[edge.column]].any(),\n BadRequest(ERR_DELETE, column=edge.column, id=row[edge.column]))\n\n if edge.from_table == table_name and edge.to_table == table_name:\n return delete_from, delete_to\n elif edge.from_table == table_name:\n return delete_from\n elif edge.to_table == table_name:\n return delete_to\n\n def maybe_update_row(edge, adjacent, row, cond, new_id):\n to_table = Table(URI(f\"$self/{edge.to_table}\"))\n\n args = closure(get_op(lambda row: [new_id, Tuple(row)[0]]))\n\n # assumes row[0] is always the key\n add = closure(put_op(lambda new_id, key: adjacent.write([new_id, key], True)))\n add = to_table.where({edge.column: new_id}).rows().map(args).for_each(add)\n\n return After(If(cond, delete_row(edge, adjacent, row)), add)\n\n class GraphTable(Table):\n def delete_row(self, key):\n row = self[key]\n deletes = []\n for label, edge in schema.edges.items():\n if table_name not in [edge.from_table, edge.to_table]:\n continue\n\n adjacent = Sparse(uri(graph).append(label))\n deletes.append(delete_row(edge, adjacent, row))\n\n return If(row.is_some(), After(deletes, Table.delete_row(self, key)))\n\n def max_id(self):\n \"\"\"Return the maximum ID present in this :class:`Table`.\"\"\"\n\n row = Tuple(self.order_by([key_col.name], True).select([key_col.name]).rows().first())\n return U64(If(row.is_none(), 0, row[0]))\n\n def read_vector(self, node_ids):\n \"\"\"Given a vector of `node_ids`, return a :class:`Stream` of :class:`Table` rows matching those IDs.\"\"\"\n\n @closure\n @get_op\n def read_node(row: Tuple):\n return self[row[0]]\n\n return Sparse(uri(node_ids)).elements().map(read_node)\n\n def update_row(self, key, values):\n row = self[key]\n updates = []\n for label, edge in schema.edges.items():\n if table_name not in [edge.from_table, edge.to_table]:\n continue\n\n if any(col.name == edge.column for col in table_schema.values):\n adjacent = Sparse(uri(graph).append(label))\n old_id = row[edge.column]\n new_id = values[edge.column]\n update = maybe_update_row(edge, adjacent, values.contains(edge.column), old_id, new_id)\n updates.append(update)\n else:\n # the edge is on the primary key, so it's not being updated\n pass\n\n return After(Table.update_row(self, key, values), updates)\n\n def upsert(self, key, values):\n row = self[key]\n updates = []\n for label, edge in schema.edges.items():\n if table_name not in [edge.from_table, edge.to_table]:\n continue\n\n adjacent = Sparse(uri(graph).append(label))\n\n if any(col.name == edge.column for col in table_schema.values):\n value_index = [col.name for col in table_schema.values].index(edge.column)\n new_id = values[value_index]\n else:\n new_id = key[0]\n\n update = maybe_update_row(edge, adjacent, row, row.is_some(), new_id)\n updates.append(update)\n\n return After(Table.upsert(self, key, values), updates)\n\n return GraphTable(table_schema)\n","sub_path":"client/tinychain/graph/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":9016,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"452685636","text":"import os\nfrom PIL import Image\n\nfiles = os.listdir('./infer_testB')\nfor f in files:\n### oldfile = './gt/'+f\n### Image.open(oldfile).convert('RGB').save('./gt_rgb/'+f)\n oldname = './infer_testB/'+f\n newname = './infer_testB/'+f.replace('fake_','')\n os.rename(oldname, newname)\n","sub_path":"gan/change_name.py","file_name":"change_name.py","file_ext":"py","file_size_in_byte":284,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"475052924","text":"from django.conf.urls import url\n\nfrom . import views\n\napp_name = 'admin'\n\nurlpatterns = [\n url(r'^$', views.UserEmailsFormView.as_view(), name='search'),\n url(r'^search/name/(?P.*)/$', views.UserEmailsSearchList.as_view(), name='search_list'),\n url(r'^search/guid/(?P[a-z0-9]+)/$', views.UserEmailsSearchList.as_view(), name='search_list_guid'),\n url(r'^(?P[a-z0-9]+)/$', views.UserEmailsView.as_view(), name='user'),\n url(r'^(?P[a-z0-9]+)/primary/$', views.UserPrimaryEmail.as_view(), name='primary'),\n]\n","sub_path":"admin/user_emails/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":545,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"517651617","text":"import csv\nfrom grafo import *\nimport sys\nimport random\nimport collections\nfrom collections import deque as Deque\nimport operator\n \ndef cargar_grafo(nombre_archivo):\n grafo = Grafo()\n with open(nombre_archivo) as delincuentes:\n delincuentes_tsv = csv.reader(delincuentes, delimiter=\"\\t\")\n for linea in delincuentes_tsv:\n grafo.agregar_vertice(int(linea[0]))\n grafo.agregar_vertice(int(linea[1]))\n grafo.agregar_arista(int(linea[0]), int(linea[1])) \n return grafo\n\ndef max_freq(lista):\n resultado = collections.Counter(lista)\n etiqueta_que_mas_se_repite = -1\n cant_veces = -1\n for clave,valor in resultado.items():\n if valor > cant_veces:\n cant_veces = valor\n etiqueta_que_mas_se_repite = clave\n if etiqueta_que_mas_se_repite == -1: return None\n return etiqueta_que_mas_se_repite\n\ndef dfs_cfc(grafo, vertice, visitados, orden, lista1, pila2, cfcs, en_cfs):\n visitados.add(vertice)\n lista1.append(vertice)\n pila2.append(vertice)\n for adyacente in grafo.adyacentes(vertice):\n if adyacente not in visitados:\n orden[adyacente] = orden[vertice] + 1\n dfs_cfc(grafo, adyacente, visitados, orden, lista1, pila2, cfcs, en_cfs)\n elif adyacente not in en_cfs:\n while orden[lista1[-1]] > orden[adyacente]:\n lista1.pop()\n\n if lista1[-1] == vertice:\n lista1.pop()\n aux = None\n nueva_cfc = []\n while aux != vertice:\n aux = pila2.pop()\n en_cfs.add(aux)\n nueva_cfc.append(aux)\n cfcs.append(nueva_cfc)\n\ndef random_walks(grafo, origen, largo):\n recorrido = {}\n v = origen\n for i in range(largo):\n if not v in recorrido:\n recorrido[v] = 1\n else: \n recorrido[v] += 1\n adyacentes = grafo.adyacentes(v)\n if len(adyacentes) > 0:\n v = random.choice(adyacentes)\n else:\n break\n return recorrido\n \ndef bfs_min_seguimiento(grafo, vertice_inicial, destino):\n visitados = set()\n distancia = {}\n padres = {}\n q = Deque()\n q.append(vertice_inicial)\n padres[vertice_inicial] = None\n visitados.add(vertice_inicial)\n distancia[vertice_inicial] = 0\n\n while q:\n v = q.popleft()\n if v == destino: break\n for w in grafo.adyacentes(v):\n if w not in visitados:\n visitados.add(w)\n distancia[w] = distancia[v] + 1\n padres[w] = v\n q.append(w)\n return distancia, padres\n\ndef bfs_divulgar(grafo, vertice_inicial, n):\n visitados = set()\n distancia = {}\n padres = {}\n q = Deque()\n q.append(vertice_inicial)\n padres[vertice_inicial] = None\n visitados.add(vertice_inicial)\n distancia[vertice_inicial] = 0\n while q:\n v = q.popleft()\n if distancia[v] == n: break\n for w in grafo.adyacentes(v):\n if w not in visitados:\n visitados.add(w)\n distancia[w] = distancia[v] + 1\n padres[w] = v\n q.append(w)\n return distancia, padres\n\ndef ciclo_n(grafo, origen, largo):\n visitados = set()\n respuesta = Deque()\n respuesta.append(origen)\n visitados.add(origen)\n if _ciclo_n(grafo, origen, largo, visitados, respuesta, origen, 1):return respuesta\n respuesta.pop()\n return respuesta\n\ndef _ciclo_n(grafo, v, largo, visitados, respuesta, principio, cantidad): \n #if len(respuesta)-1 > largo: return False\n if cantidad-1 > largo: return False\n adyacentes = grafo.adyacentes(v)\n if cantidad == largo:\n if principio in adyacentes:\n respuesta.append(principio)\n return respuesta\n return False\n for w in adyacentes:\n if w in visitados:continue\n respuesta.append(w)\n visitados.add(w)\n cantidad += 1\n #print(respuesta)\n if _ciclo_n(grafo, w, largo, visitados, respuesta, principio, cantidad): return respuesta\n respuesta.pop()\n cantidad -= 1\n #visitados.remove(w)\n #else:\n # if v == principio and len(respuesta)-1 == largo: return respuesta\n return False\n\n ","sub_path":"tp3/biblioteca.py","file_name":"biblioteca.py","file_ext":"py","file_size_in_byte":4242,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"112607550","text":"import pytest\nfrom fastjsonschema.exceptions import JsonSchemaException\n\nfrom core.GraphQLColumn import GraphQLColumn\nfrom core.GraphQLForeignKey import GraphQLForeignKey\nfrom core.GraphQLTable import GraphQLTable\nfrom static.config import METADATA_TABLE\n\n\nclass TestGraphQLTable:\n def test_graph_ql_table_object(self):\n _col_data = [\n {\"field_type\": \"str\", \"field_name\": \"contract_ref_number\"},\n {\"field_type\": \"str\", \"field_name\": \"inco_term\"},\n ]\n\n _graph_ql_columns = [GraphQLColumn(**col) for col in _col_data]\n\n _table_data = {\"table_name\": \"contract_header\", \"columns\": _graph_ql_columns}\n _graph_ql_table = GraphQLTable(**_table_data)\n\n assert len(_graph_ql_table.columns) == len(_col_data)\n\n def test_foreign_key(self):\n _col_data = [\n {\"field_type\": \"str\", \"field_name\": \"contract_ref_number\"},\n {\"field_type\": \"str\", \"field_name\": \"inco_term\"},\n ]\n\n _graph_ql_columns = [GraphQLColumn(**col) for col in _col_data]\n\n _table_data = {\"table_name\": \"contract_header\", \"columns\": _graph_ql_columns}\n _graph_ql_table = GraphQLTable(**_table_data)\n\n assert _graph_ql_table.foreignKeyDicts is None\n\n _foreign_key_data = {\n \"parent_table_name\": \"department\",\n \"self_columns\": [\"department_id\"],\n \"parent_columns\": [\"id\"]\n }\n _foreign_key = [GraphQLForeignKey(**_foreign_key_data)]\n\n _table_data = {\"table_name\": \"contract_header\", \"columns\": _graph_ql_columns, \"foreign_key_fields\": _foreign_key}\n _graph_ql_table = GraphQLTable(**_table_data)\n\n assert _graph_ql_table.foreignKeyDicts is not None\n\n def test_graph_ql_table_from_json(self):\n _table_json = {\n \"table_name\": \"contract_header\",\n \"columns\": [\n {\"field_type\": \"str\", \"field_name\": \"contract_ref_number\"},\n {\"field_type\": \"str\", \"field_name\": \"inco_term\"},\n ],\n \"primary_key_fields\": [\"contract_ref_number\"]\n }\n\n _graph_ql_table = GraphQLTable.from_json(_table_json)\n\n assert len(_graph_ql_table.columns) == len(_table_json[\"columns\"])\n\n print(_graph_ql_table.__dict__)\n\n def test_metadata_json(self):\n _table_json_invalid = {}\n with pytest.raises(JsonSchemaException):\n assert METADATA_TABLE(_table_json_invalid)\n","sub_path":"test_graphql_table.py","file_name":"test_graphql_table.py","file_ext":"py","file_size_in_byte":2425,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"122252094","text":"rows = []\ndef init():\n global rows\n import formsdatabase\n #formsdatabase.pullNewRows()\n rows = formsdatabase.getAllRows()\ndef getCounts(rowNum):\n D = {}\n for row in rows:\n if row[rowNum] in D:\n D[row[rowNum]]+=1\n else:\n D[row[rowNum]] = 1\n return D\ndef getNumberList(rowNum):\n numList = []\n for row in rows:\n if row[rowNum] == '':\n continue\n try:\n numList.append(float(row[rowNum]))\n except:\n return None\n return numList\ndef average(numList):\n return sum(numList)/len(numList)\ndef stdev(numList):\n ans = 0.0\n mu = average(numList)\n for n in numList:\n ans += (n-mu)**2\n ans /= len(numList)\n return ans**0.5\ndef getAvg(rowNum):\n L = getNumberList(rowNum)\n if L:\n return average(L)\n return None\ndef getNumEntries(rowNum):\n L = getNumberList(rowNum)\n if L:\n return len(L)\n else:\n return 0\ndef getSD(rowNum):\n L = getNumberList(rowNum)\n if L:\n return stdev(L)\n return None\ndef getRating(row):\n L = [6,7,8,28,29,35,36]\n k = 0.0\n tot = 0.0\n for n in L:\n try:\n d = float(row[n])\n k += 1.0\n tot += d\n except:\n pass\n return tot/k\n \n \n","sub_path":"statanalyzer.py","file_name":"statanalyzer.py","file_ext":"py","file_size_in_byte":1303,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"390350149","text":"# Copyright (c) Microsoft Corporation.\n# Licensed under the MIT license.\n\nimport numpy as np\n\nPRECISION = 8 # in signs after dot\n\ndef objective_file_name(output_prefix, input_basename, module_basename):\n return output_prefix + input_basename + \"_F_\" + module_basename + \".txt\"\n\ndef jacobian_file_name(output_prefix, input_basename, module_basename):\n return output_prefix + input_basename + \"_J_\" + module_basename + \".txt\"\n\n\n\ndef time_to_string(objective_time, derivative_time):\n obj_time_str = np.format_float_scientific(\n objective_time,\n unique=False,\n precision=PRECISION\n )\n\n der_time_str = np.format_float_scientific(\n derivative_time,\n unique=False,\n precision=PRECISION\n )\n\n return f\"{obj_time_str}\\n{der_time_str}\"\n\ndef save_time_to_file(filepath, objective_time, derivative_time):\n # open file in write mode or create new one if it does not exist\n out = open(filepath,\"w\")\n out.write(time_to_string(objective_time, derivative_time))\n out.close()\n \n\n\ndef value_to_string(value):\n return np.format_float_scientific(value, unique=False, precision=PRECISION)\n\ndef save_value_to_file(filepath, value):\n out = open(filepath,\"w\")\n out.write(value_to_string(value))\n out.close()\n\ndef save_vector_to_file(filepath, gradient):\n out = open(filepath,\"w\")\n\n for value in gradient:\n out.write(value_to_string(value) + '\\n')\n\n out.close()\n\ndef save_jacobian_to_file(filepath, jacobian):\n out = open(filepath,\"w\")\n\n # output row-major matrix\n for row in jacobian:\n out.write(value_to_string(row[0]))\n for value in row[1:]:\n out.write('\\t' + value_to_string(value))\n out.write('\\n')\n\n out.close()\n\ndef save_errors_to_file(filepath, reprojection_error, zach_weight_error):\n out = open(filepath,\"w\")\n\n out.write(\"Reprojection error:\\n\")\n for value in reprojection_error:\n out.write(value_to_string(value) + '\\n')\n\n out.write(\"Zach weight error:\\n\")\n for value in zach_weight_error:\n out.write(value_to_string(value) + '\\n')\n\n out.close()\n\ndef save_sparse_j_to_file(filepath, J):\n out = open(filepath,\"w\")\n\n out.write(f\"{J.nrows} {J.ncols}\\n\")\n\n out.write(f\"{len(J.rows)}\\n\")\n for row in J.rows:\n out.write(f\"{row} \")\n out.write('\\n')\n \n out.write(f\"{len(J.cols)}\\n\")\n for column in J.cols:\n out.write(f\"{column} \")\n out.write('\\n')\n\n for value in J.vals:\n out.write(value_to_string(value) + ' ')\n\n out.close()","sub_path":"src/python/shared/output_utils.py","file_name":"output_utils.py","file_ext":"py","file_size_in_byte":2539,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"163765590","text":"\n\n\n\n\n\n\n# -*- coding: utf-8 -*-\n\n# 读取页面文本\n# 按照标题,保存整个文本\n\n\nimport csv\nimport datetime\n\nimport os\nimport re\nimport time\nimport sys\n\ntype = sys.getfilesystemencoding()\nimport pymysql\nimport xlrd\nimport requests\nfrom requests.exceptions import RequestException\nfrom lxml import etree\n\n\ndef call_page(url):\n try:\n response = requests.get(url)\n response.encoding = 'utf-8' #\n if response.status_code == 200:\n return response.text\n return None\n except RequestException:\n return None\n\n\ndef removeDot(item):\n f_l = []\n for it in item:\n f_str = \"\".join(it.split(\",\"))\n f_l.append(f_str)\n\n return f_l\n\n\ndef remove_block(items):\n new_items = []\n for it in items:\n f = \"\".join(it.split())\n new_items.append(f)\n return new_items\n\n\n\n\n\ndef read_xlrd(excelFile):\n data = xlrd.open_workbook(excelFile)\n table = data.sheet_by_index(0)\n dataFile = []\n for rowNum in range(table.nrows):\n dataFile.append(table.row_values(rowNum))\n\n # # if 去掉表头\n # if rowNum > 0:\n\n return dataFile\n\n\n\n\n\n\ndef getOneText(url):\n html = call_page(url)\n selector = etree.HTML(str(html))\n title = selector.xpath('//*[@id=\"content\"]/div/div[2]/article/div/ul/li/a/text()')\n content = selector.xpath('//*[@id=\"content\"]/div/div[2]/article/div/ul/text()')\n f_content = remove_block(content)\n half_url = selector.xpath('//*[@id=\"content\"]/div/div[2]/article/div/ul/li/a/@href')\n f_url = []\n for item in half_url:\n f_url.append(\"https://perldoc.perl.org/5.32.0/\"+item)\n for i1,i2,i3 in zip(title,f_content[1:],f_url):\n big_l.append((i1, i2,i3))\n\n\n\n\n\n\ndef text_save(filename, data):#filename为写入CSV文件的路径,data为要写入数据列表.\n file = open(filename,'a')\n for i in range(len(data)):\n s = str(data[i]).replace('[','').replace(']','')#去除[],这两行按数据不同,可以选择\n s = s.replace(\"'\",'').replace(',','') +'\\n' #去除单引号,逗号,每行末尾追加换行符\n file.write(s)\n file.close()\n print(\"保存文件成功\")\n\n\n\ndef writerDt_csv(headers, rowsdata):\n # rowsdata列表中的数据元组,也可以是字典数据\n with open('core_m.csv', 'w', newline='') as f:\n f_csv = csv.writer(f)\n f_csv.writerow(headers)\n f_csv.writerows(rowsdata)\n print(\"保存完成\")\n\nif __name__ == '__main__':\n big_l =[]\n\n\n for item in range(64,91):\n url = 'https://perldoc.perl.org/5.32.0/index-modules-{0}.html'.format(chr(item))\n\n getOneText(str(url))\n\n headers =[\"title\",\"content\",\"url\"]\n writerDt_csv(headers,big_l)\n\n","sub_path":"core mdules/core_modules.py","file_name":"core_modules.py","file_ext":"py","file_size_in_byte":2704,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"328564156","text":"#-*- coding: utf-8 -*-\n\nfrom selenium import webdriver\nfrom selenium.webdriver.chrome.options import Options\nimport os\nimport datetime\n\npypath = os.path.dirname(os.path.abspath(__file__))\nprint(pypath)\n\nchromepath = 'chromedriver'\n\ndrvpath_filepath = f'{pypath}/../drvpath.txt'\n\nhtmlpath = f'{pypath}/html_bluehouse'\nif not os.path.exists(htmlpath):\n os.makedirs(htmlpath)\n\nif not os.path.isfile(drvpath_filepath):\n print(drvpath_filepath + \" not found!\")\n quit();\n\nwith open(drvpath_filepath, 'r') as myfile:\n chromepath = myfile.read()\n\noptions = Options()\noptions.add_argument('--headless')\nbrowser = webdriver.Chrome(chromepath, chrome_options=options)\n\ndatetime_onstart =datetime.datetime.now().strftime(\"%Y%m%d_%H%M%S\")\n\nfor page in range(1,4):\n url = f\"https://www1.president.go.kr/petitions?order=best&page={page}\"\n print(f\"page : {page} {url}\")\n browser.get(url)\n print(browser.title)\n f = open(f\"{htmlpath}/{datetime_onstart}_{page}.htm\", encoding='utf-8', mode = 'w')\n f.write(browser.page_source)\n f.close()\n\nbrowser.quit()","sub_path":"bluehousebest.py","file_name":"bluehousebest.py","file_ext":"py","file_size_in_byte":1070,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"399604408","text":"#!/usr/bin/python3\n\nclass BFExecutionError(Exception):\n\tdef __init__(self, msg):\n\t\tself.msg = msg\n\n\tdef __str__(self):\n\t\treturn self.msg\n\nclass BFInterpreter():\n\t'''A simple brainfuck interpreter.\n\n\tParameters:\n\t\tmem_size: Amount of cells.\n\t\tring_memory: The field of cells works like a ring.\n\t\t\t\t\t\t Otherwise the memory size will grow dynamically.\n\t\tbuffering_input: Input is buffered and read one character\n\t\t\t\t\t\t time.\n\t'''\n\tdef __init__(self, mem_size=30000, ring_memory=False, buffering_input=True):\n\t\t# Memory\n\t\tself.cells = [0] * mem_size\n\t\tself.mem_inc_size = mem_size\n\t\tself.ring_mem = ring_memory\n\t\tself.ptr = 0\n\n\t\t# Input buffer\n\t\tself.buffering = buffering_input\n\t\tself.input_buf = ''\n\n\tdef get_cur_cell(self):\n\t\t'''Return current cell.'''\n\t\treturn self.get_cell(self.ptr)\n\n\tdef get_cell(self, i):\n\t\t'''Return i-th cell'''\n\t\treturn (i, self.cells[i])\n\n\tdef get_cells(self, n, m):\n\t\t'''Return all cells from n to m.'''\n\t\treturn [self.get_cell(i) for i in range(n,m+1)]\n\n\tdef __handle_ptr__(self):\n\t\t'''Changes the pointer or memory according to the current pointer value.'''\n\t\t# Pointer points outside the field\n\t\tif self.ptr >= len(self.cells):\n\t\t\tif not self.ring_mem:\n\t\t\t\t# Dynamic memory allocation\n\t\t\t\tself.cells += [0] * self.mem_inc_size\n\t\t\telse:\n\t\t\t\tself.ptr = 0\n\n\t\t# Pointer points into negative space\n\t\tif self.ptr < 0:\n\t\t\tif not self.ring_mem:\n\t\t\t\traise BFExecutionError('Trying to access a negative cell.')\n\t\t\telse:\n\t\t\t\tself.ptr = len(self.cells) - 1\n\n\tdef __handle_cell__(self):\n\t\t'''Restricts the current cell to 8 bit.'''\n\t\tif self.cells[self.ptr] > 255:\n\t\t\tself.cells[self.ptr] = 0\n\n\t\tif self.cells[self.ptr] < 0:\n\t\t\tself.cells[self.ptr] = 255\n\n\tdef __handle_input__(self):\n\t\tif not self.buffering:\n\t\t\t# Read current input\n\t\t\tval = input('')\n\t\t\tif len(val) < 1:\n\t\t\t\tval = '\\n'\n\t\t\tself.cells[self.ptr] = ord(val[0])\n\t\telse:\n\t\t\t# If the buffer is empty, read new input\n\t\t\tif len(self.input_buf) == 0:\n\t\t\t\tself.input_buf = input('')\n\t\t\t\t# Read input is still empty so add the newline\n\t\t\t\tif len(self.input_buf) == 0:\n\t\t\t\t\tself.input_buf = '\\n'\n\n\t\t\t# Get next value from buffer\n\t\t\tval = ord(self.input_buf[0])\n\t\t\tself.input_buf = self.input_buf[1:]\n\t\t\tself.cells[self.ptr] = val\n\n\tdef execute(self, code, verbose=False):\n\t\t'''Executes brainfuck code.\n\t\t\n\t\tVerbose output takes much longer.\n\t\t'''\n\t\tdef __print__(txt):\n\t\t\tprint(txt)\n\n\t\tdef __pass__(x):\n\t\t\tpass\n\n\t\tif not verbose:\n\t\t\t__print__ = __pass__\n\t\t\n\t\t# Program counter and stack for loop parenthesis\n\t\tpc = 0\n\t\tparan_stack = []\n\t\twhile True:\n\t\t\tif pc >= len(code):\n\t\t\t\t# Ending\n\t\t\t\treturn\n\t\t\t\t\n\t\t\tc = code[pc]\n\t\t\t__print__('PC: {}'.format(pc))\n\n\t\t\t# Memory\n\t\t\tif c == '>':\n\t\t\t\t__print__('PTR INC')\n\t\t\t\tself.ptr += 1\n\t\t\t\tself.__handle_ptr__()\n\t\t\tif c == '<':\n\t\t\t\t__print__('PTR DEC')\n\t\t\t\tself.ptr -= 1\n\t\t\t\tself.__handle_ptr__()\n\t\t\tif c == '+':\n\t\t\t\t__print__('CLL INC')\n\t\t\t\tself.cells[self.ptr] += 1\n\t\t\t\tself.__handle_cell__()\n\t\t\tif c == '-':\n\t\t\t\t__print__('CLL INC')\n\t\t\t\tself.cells[self.ptr] -= 1\n\t\t\t\tself.__handle_cell__()\n\n\t\t\t# Print current cell\n\t\t\t__print__(\"[{}] = {}\".format(self.ptr, self.cells[self.ptr]))\n \n\t\t\t# IO \n\t\t\tif c == '.':\n\t\t\t\tprint(chr(self.cells[self.ptr]), end=\"\")\n\t\t\tif c == ',':\n\t\t\t\t__print__('INPUT')\n\t\t\t\tself.__handle_input__()\n\n\t\t\t# Paranthesis\n\t\t\tif c == '[':\n\t\t\t\t__print__('PAR OPEN')\n\t\t\t\tif self.cells[self.ptr] != 0:\n\t\t\t\t\t# We enter the loop and safe the position of the start\n\t\t\t\t\tparan_stack.append(pc)\n\t\t\t\telse:\n\t\t\t\t\t# We skip the whole loop\n\t\t\t\t\tskip_ctr = 0 # Counter for loops inside the skipped loop\n\t\t\t\t\tfor j in range(pc, len(code)):\n\t\t\t\t\t\tif code[j] == '[':\n\t\t\t\t\t\t\tskip_ctr += 1\n\t\t\t\t\t\tif code[j] == ']':\n\t\t\t\t\t\t\tskip_ctr -= 1\n\t\t\t\t\t\t\tif skip_ctr == 0:\n\t\t\t\t\t\t\t\t__print__('JMP > {}'.format(j))\n\t\t\t\t\t\t\t\tpc = j; break\n\t\t\tif c == ']':\n\t\t\t\t__print__('PAR CLOSE')\n\t\t\t\t# Pop last loop entered and jump there\n\t\t\t\told = paran_stack.pop() - 1\n\t\t\t\tif self.cells[self.ptr] != 0:\n\t\t\t\t\tpc = old\n\t\t\t\t\t__print__('JMP < {}'.format(pc))\n \n\t\t\t# Increment programm counter \n\t\t\tpc += 1\n\t\t\t\n","sub_path":"src/brainint.py","file_name":"brainint.py","file_ext":"py","file_size_in_byte":4059,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"329913511","text":"# This is a Python framework to compliment \"Peek-a-Boo, I Still See You: Why Efficient Traffic Analysis Countermeasures Fail\".\n# Copyright (C) 2012 Kevin P. Dyer (kpdyer.com)\n# See LICENSE for more details.\n\nimport random\n\nfrom Trace import Trace\nfrom Packet import Packet\n\n# This doesn't allow a Burst to have more than bsize packets. \n# But allows all Bursts less than bsize to stay the same size.\n\nclass BurstClient2Server:\n @staticmethod\n def applyCountermeasure(trace):\n bsize = random.choice(range(3, 4, 1))\n dsize = random.choice(range(3, 4, 1))\n newTrace = Trace(trace.getId())\n rand = random.choice(range(8,256,8))\n count = 0\n curDir = 0\n for packet in trace.getPackets():\n direction = packet.getDirection()\n length = packet.getLength()\n newlength = min(length + rand, Packet.MTU) \n time = packet.getTime()\n newPacket = Packet(direction,\n time,\n newlength )\n \n if ((direction == 1 and curDir == 1) and count < bsize):\n count +=1\n newTrace.addPacket(newPacket)\n elif ((direction == 1 and curDir == 1) and count == bsize):\n BurstClient2Server.makeDummy(newTrace, length, time, curDir, dsize)\n newTrace.addPacket(newPacket)\n count = 1\n elif ((direction == 1 and curDir == 0)):\n newTrace.addPacket(newPacket)\n curDir = 1\n count = 1\n elif ((direction == 0 and curDir == 1)):\n newTrace.addPacket(newPacket)\n curDir = 0\n count = 1\n elif (direction == 0 and curDir == 0):\n newTrace.addPacket(newPacket)\n count = 1\n return newTrace\n\n @staticmethod \n def makeDummy(newTrace, length, time, curDir, dsize):\n# templength = min(length+random.choice(range(8,256,8)), Packet.MTU )\n # dummyPacket = Packet(0, time, 638)\n # newTrace.addPacket(dummyPacket)\n for val in range(0, dsize):\n newlength = random.choice(range(638,912,8))\n# newlength = 638\n dummyPacket = Packet(0, time, newlength)\n newTrace.addPacket(dummyPacket)\n","sub_path":"BurstClient2Server.py","file_name":"BurstClient2Server.py","file_ext":"py","file_size_in_byte":2365,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"90555553","text":"#!/usr/bin/env python\nfrom channel_tinker import diff_images\nfrom PIL import Image\nfrom channel_tinker import error\n\ndef diff_images_by_path(base_path, head_path, diff_path=None):\n \"\"\"\n Compare two images.\n\n Keyword arguments:\n diff_path -- If not None, then save a graphical representation of\n the difference: black is same, closer to white differs (if images\n are different sizes, red is deleted, green is added).\n \"\"\"\n base = Image.open(base_path)\n head = Image.open(head_path)\n w = max(base.size[0], head.size[0])\n h = max(base.size[1], head.size[1])\n diff_size = w, h\n diff = None\n # draw = None\n nochange_color = (0, 0, 0, 255)\n if diff_path is not None:\n diff = Image.new('RGBA', diff_size, nochange_color)\n # error(\"* generated diff image in memory\")\n # draw = ImageDraw.Draw(diff)\n error(\"Checking {} zone...\".format(diff_size))\n result = diff_images(base, head, diff_size, diff=diff,\n nochange_color=nochange_color)\n if diff_path is not None:\n diff.save(diff_path)\n error(\"* saved {}\".format(diff_path))\n return result\n\n\n","sub_path":"channel_tinker_pil.py","file_name":"channel_tinker_pil.py","file_ext":"py","file_size_in_byte":1150,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"459047570","text":"from itertools import combinations\n\n\ndef solution(relation):\n answer = 0\n\n tupleLength = len(relation)\n columnLength = len(relation[0])\n\n # 컬럼 번호로 만들 수 있는 모든 조합을 생성\n columnList = [i for i in range(columnLength)]\n columnCombinationList = []\n for selectedColumn in range(1, columnLength+1):\n columnCombinationList.extend(combinations(columnList, selectedColumn))\n\n superkey = []\n for columns in columnCombinationList:\n temp = [tuple([item[column] for column in columns])\n for item in relation]\n if len(set(temp)) == tupleLength:\n superkey.append(columns)\n\n check = [True] * len(superkey)\n for i in range(len(superkey)):\n for j in range(i+1, len(superkey)):\n if set(superkey[i]) - set(superkey[j]) == set():\n check[j] = False\n\n for value in check:\n if value:\n answer += 1\n\n return answer\n\n# relation = [\n# [\"100\",\"ryan\",\"music\",\"2\"],\n# [\"200\",\"apeach\",\"math\",\"2\"],\n# [\"300\",\"tube\",\"computer\",\"3\"],\n# [\"400\",\"con\",\"computer\",\"4\"],\n# [\"500\",\"muzi\",\"music\",\"3\"],\n# [\"600\",\"apeach\",\"music\",\"2\"]\n# ]\n","sub_path":"coding_test/KAKAO/후보키.py","file_name":"후보키.py","file_ext":"py","file_size_in_byte":1187,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"383933843","text":"import pyupbit\r\nimport numpy as np\r\n\r\n#OHLCV =(open, high, low, close, volume)로 당일 시가, 고가, 저가, 종가, 거래량에 대한 데이터\r\ndf = pyupbit.get_ohlcv(\"KRW-BTC\",count=7) # count = 7일동안의 데이터\r\n\r\n# 변동폭 *k 계산, (고가, 저가)*k값\r\ndf['range'] = (df['high'] - df['low']) * 0.5\r\n# target(매수가), range 컬럼을 한칸씩 밑으로 내림(.shift(1))\r\ndf['target'] = df['open'] + df['range'].shift(1)\r\n\r\n#ror (수익율), np.where\r\ndf['ror'] = np.where(df['high'] > df['target'],\r\n df['close'] / df['target'] ,\r\n 1)\r\n#누적 수익률\r\ndf['hpr'] = df['ror'].cumprod()\r\ndf['dd'] = (df['hpr'].cummax() - df['hpr']) / df['hpr'].cummax() * 100\r\nprint(\"MDD(%): \", df['dd'].max())\r\n#엑셀로 출력\r\ndf.to_excel(\"dd.xlsx\")\r\n","sub_path":"bitcoinautotrade_test/backtest.py","file_name":"backtest.py","file_ext":"py","file_size_in_byte":806,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"29083908","text":"# -*- coding: utf-8 -*-\n\nimport tensorflow as tf\nimport os\nimport numpy as np\nimport json\nfrom gensim.models import word2vec\nimport config_\nimport lstm\nimport bilstm\nimport lstmCRF\nimport bilstmCRF\nimport argparse\nimport string\n \ndef POStagger(sess, config, tagger, flag, data_dir):\n with open(data_dir+'posdt.json','r') as f:\n posdt = json.load(f)\n inv_map = dict(zip(posdt.values(), posdt.keys()))\n \n log = open(os.path.join(data_dir,file_to_save_model,'output.txt'),'a',encoding='utf-8')\n \n n_hidden_units = config.n_hidden_units # neurons in hidden layer\n n_classes = config.n_classes\n n_inputs = config.n_inputs\n max_step = config.max_step # max_time_step\n \n ## word segementation\n while True:\n try:\n inputsentence = input('write down sentences and see the POS tags: (exit: enter \"z\")\\n')\n except:\n continue\n if inputsentence == 'z':\n break\n for c in string.punctuation:\n \tinputsentence=inputsentence.replace(c,' '+c)\n seg_list = inputsentence.split(' ')\n\n sentence = [word for word in seg_list]\n model_ted = word2vec.Word2Vec.load(data_dir+\"fasttext.model\") \n sentence_vector = []\n for word in sentence:\n try:\n sentence_vector.append(model_ted.wv[word].tolist())\n except:\n sentence_vector.append([0]*n_inputs)\n inputs=[]\n seq_length=[]\n for data in [sentence_vector] : \n inputs.append(model.padding(data,n_inputs,max_step))\n seq_length.append(min(len(data),max_step)) \n \n pred = sess.run(tagger.prediction,feed_dict={tagger.x: inputs, tagger.length: seq_length, tagger.dropout: 0.0})\n if flag == '1' or flag == '2':\n tag_ls = np.argmax(pred,axis=1) #if use model LSTM/BLSTM, pred return a onehot encoding vector\n elif flag == '3' or flag == '4':\n tag_ls = pred #if use model combine CRF, pred return a label\n\n result=''\n for i in range(len(tag_ls)):\n result = result + sentence[i] + '_' + inv_map[tag_ls[i]] + ' '\n print(result)\n log.write(result+'\\n');log.flush()\n log.close()\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser(allow_abbrev=False)\n parser.add_argument(\"--data_path\", type=str, default='../data/', dest=\"data_dir\", help=\"specify your data directory\")\n parser.add_argument(\"--model_path\", type=str, default='lstmcrf0621', dest=\"file_to_save_model\",help=\"name the file to save your model\")\n parser.add_argument(\"--model_type\", type=str, default='3', dest=\"flag\", help=\"the model to be trained \\n1: LSTM \\n2: BiLSTM \\n3: LSTM+CRF \\n4: BLSTM+CRF \\n\")\n arg=parser.parse_args()\n data_dir = arg.data_dir\n file_to_save_model = arg.file_to_save_model\n flag = arg.flag\n\n config = config_.Config()\n\n if flag =='1':\n tagger = lstm.Tagger(config=config)\n elif flag =='2': \n tagger = bilstm.biRNNTagger(config=config)\n elif flag =='3':\n tagger = lstmCRF.CRFTagger(config=config)\n elif flag =='4':\n \ttagger = bilstmCRF.CRFTagger(config=config)\n else:\n print(\"No such model\")\n exit()\n\n init = tf.global_variables_initializer()\n sess_config = tf.ConfigProto()\n sess_config.gpu_options.allow_growth = True\n saver = tf.train.Saver()\n\n with tf.Session(config=sess_config) as sess:\n sess.run(init)\n saver.restore(sess, tf.train.latest_checkpoint(os.path.join(data_dir,file_to_save_model)))\n POStagger(sess, config, tagger,flag, data_dir)","sub_path":"argv.py","file_name":"argv.py","file_ext":"py","file_size_in_byte":3606,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"232437939","text":"import numpy as np \nimport pandas as pd \nimport tensorflow as tf \nfrom tensorflow import keras\nfrom sklearn.model_selection import train_test_split\nimport matplotlib.pyplot as plt\nfrom sklearn.model_selection import train_test_split\n\nclass MLPNN:\n def __init__(self):\n print(\"Running Neural Network\")\n def graph(self):\n print()\n def predictModel(self, path, dataArray):\n\n predictionLabels=[\"eyesOpen\", \"eyesCLosed\", \"Opposite Side\", \"Same Side\", \"Seizure\"]\n model=keras.models.load_model(path)\n seizureAmount=0\n for rows in range(dataArray.shape[0]):\n \n newdf=dataArray.iloc[rows:rows+1]\n prediction_features = model.predict(newdf)\n print(prediction_features)\n if predictionLabels[np.argmax(prediction_features[0])] ==\"Seizure\":\n seizureAmount+=1\n \n return seizureAmount\n\n \n def runModel(self, training_df, testing_df):\n #preprocessing for ml\n #training\n labels_train=training_df['Output']\n features_train=training_df.drop(columns=['Output'])\n features_train = features_train.values.astype('float32')\n labels_train = labels_train.values.astype('float32')\n #testing\n labels_test=testing_df['Output']\n features_test=testing_df.drop(columns=['Output'])\n features_test = features_test.values.astype('float32')\n labels_test = labels_test.values.astype('float32')\n #trainging, validation, and testing \n \"\"\"\n features_train, features_test, labels_train, labels_test = train_test_split(features, labels, test_size=0.2)\n features_train, features_validation, labels_train, labels_validation = train_test_split(features_train, labels_train, test_size=0.4)\n \"\"\"\n features_train, features_validation, labels_train, labels_validation = train_test_split(features_train, labels_train, test_size=0.3)\n #setting up the neural network\n model = keras.Sequential([keras.layers.Dense(128, input_shape=(5,)),\n keras.layers.Dense(128, activation=tf.nn.relu),\n keras.layers.Dense(48, activation='linear'),\n keras.layers.Dense(2,activation='softmax')])\n model.compile(optimizer='Adadelta',\n loss='sparse_categorical_crossentropy',\n metrics=['acc'])\n #running the actual Model\n \n history = model.fit(features_train, labels_train, epochs=100, validation_data=(features_validation, labels_validation))\n prediction_features = model.predict(features_test)\n performance = model.evaluate(features_test, labels_test)\n print(performance)\n history_dict = history.history\n #checking for overfitting\n acc = history_dict['acc']\n val_acc = history_dict['val_acc']\n loss = history_dict['loss']\n val_loss = history_dict['val_loss']\n epochs = range(1, len(acc) + 1)\n #plotting the data\n plt.plot(epochs, val_loss, 'b', label='Validation loss')\n plt.title('Training and validation loss')\n plt.xlabel('Epochs')\n plt.ylabel('Loss')\n plt.legend()\n plt.show()\n #model.save(\"my_model.h5\")\n return history\n ","sub_path":"Code/MachineLearning/src/StatML/mlpnn.py","file_name":"mlpnn.py","file_ext":"py","file_size_in_byte":3320,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"370468601","text":"import pytest\nimport json\n\n\n@pytest.mark.test_extensions_import_module1\ndef test_extensions_import_module1(parse):\n\n # import sys\n # import importlib\n\n # from pathlib import Path\n\n extensions = parse(\"extensions\")\n assert extensions.success, extensions.message\n\n sys_import = extensions.imports(\"sys\")\n assert sys_import, \"Are you importing `sys`?\"\n\n importlib_import = extensions.imports(\"importlib\")\n assert importlib_import, \"Are you importing `importlib`?\"\n\n path_import = extensions.from_imports(\"pathlib\", \"Path\")\n assert path_import, \"Are you importing `Path` from `pathlib`?\"\n\n\n@pytest.mark.test_extensions_sys_path_module1\ndef test_extensions_sys_path_module1(parse):\n\n # def load_module(directory, name):\n # sys.path.insert(0, directory)\n\n extensions = parse(\"extensions\")\n assert extensions.success, extensions.message\n\n load_module = extensions.defines(\"load_module\")\n load_module_exists = load_module.exists()\n\n assert load_module_exists, \"Are you defining a function called `load_module`?\"\n\n load_module.has_arg(\"directory\")\n arguments_exist = load_module.has_arg(\"directory\") and load_module.has_arg(\n \"name\", 1\n )\n assert (\n arguments_exist\n ), \"Does the `load_module` function have the correct arguments?\"\n\n insert_call_exists = (\n load_module.calls()\n .match(\n {\n \"value_func_value_value_id\": \"sys\",\n \"value_func_value_attr\": \"path\",\n \"value_func_attr\": \"insert\",\n \"value_args_0_value\": 0,\n \"value_args_1_id\": \"directory\",\n }\n )\n .exists()\n )\n\n assert (\n insert_call_exists\n ), \"Are you calling `sys.path.insert` and passing the correct parameters?\"\n\n\n@pytest.mark.test_extensions_import_pop_module1\ndef test_extensions_import_pop_module1(parse):\n\n # importlib.import_module(name)\n # sys.path.pop(0)\n\n extensions = parse(\"extensions\")\n assert extensions.success, extensions.message\n\n load_module = extensions.defines(\"load_module\")\n load_module_exists = load_module.exists()\n\n assert load_module_exists, \"Are you defining a function called `load_module`?\"\n\n import_module_call_exists = (\n load_module.calls()\n .match(\n {\n \"value_func_value_id\": \"importlib\",\n \"value_func_attr\": \"import_module\",\n \"value_args_0_id\": \"name\",\n }\n )\n .exists()\n )\n\n assert (\n import_module_call_exists\n ), \"Are you calling `importlib.import_module` and passing the correct parameters?\"\n\n pop_call_exists = (\n load_module.calls()\n .match(\n {\n \"value_func_value_value_id\": \"sys\",\n \"value_func_value_attr\": \"path\",\n \"value_func_attr\": \"pop\",\n \"value_args_0_value\": 0,\n }\n )\n .exists()\n )\n\n assert (\n pop_call_exists\n ), \"Are you calling `sys.path.pop` and passing the correct parameters?\"\n\n\n@pytest.mark.test_extensions_load_directory_module1\ndef test_extensions_load_directory_module1(parse):\n\n # def load_directory(directory):\n # for path in directory.rglob(\"*.py\"):\n # load_module(directory.as_posix(), path.stem)\n\n extensions = parse(\"extensions\")\n assert extensions.success, extensions.message\n\n load_directory = extensions.defines(\"load_directory\")\n load_directory_exists = load_directory.exists()\n\n assert load_directory_exists, \"Are you defining a function called `load_directory`?\"\n\n arguments_exist = load_directory.has_arg(\"directory\")\n assert (\n arguments_exist\n ), \"Does the `load_directory` function have the correct arguments?\"\n\n for_exists = (\n load_directory.for_()\n .match(\n {\n \"target_id\": \"path\",\n \"iter_type\": \"Call\",\n \"iter_func_value_id\": \"directory\",\n \"iter_func_attr\": \"rglob\",\n \"iter_args_0_value\": \"*.py\",\n }\n )\n .exists()\n )\n\n assert (\n for_exists\n ), \"Do you have a `for` loop that uses `rglob` to loop through `.py` files in `directory`?\"\n\n load_module_call_exists = (\n load_directory.for_()\n .match(\n {\n \"0_value_type\": \"Call\",\n \"0_value_func_id\": \"load_module\",\n \"0_value_args_0_type\": \"Call\",\n \"0_value_args_0_func_value_id\": \"directory\",\n \"0_value_args_0_func_attr\": \"as_posix\",\n \"0_value_args_1_value_id\": \"path\",\n \"0_value_args_1_attr\": \"stem\",\n }\n )\n .exists()\n )\n\n assert (\n load_module_call_exists\n ), \"Are you calling `load_module` and passing the correct parameters?\"\n\n\n@pytest.mark.test_extensions_load_bundled_module1\ndef test_extensions_load_bundled_module1(parse):\n\n # def load_bundled():\n # directory = Path(__file__).parent / \"extensions\"\n # load_directory(directory)\n\n extensions = parse(\"extensions\")\n assert extensions.success, extensions.message\n\n load_bundled = extensions.defines(\"load_bundled\")\n load_bundled_exists = load_bundled.exists()\n\n assert load_bundled_exists, \"Are you defining a function called `load_bundled`?\"\n\n load_bundled_assign_exists = load_bundled.assign_to().match(\n {\n \"targets_0_id\": \"directory\",\n \"value_type\": \"BinOp\",\n \"value_left_value_type\": \"Call\",\n \"value_left_value_func_id\": \"Path\",\n \"value_left_value_args_0_id\": \"__file__\",\n \"value_left_attr\": \"parent\",\n \"value_op_type\": \"Div\",\n \"value_right_type\": \"Constant\",\n \"value_right_value\": \"extensions\",\n }\n )\n\n assert (\n load_bundled_assign_exists\n ), \"Are you calling `load_directory` and passing the correct parameters?\"\n\n load_bundled_call_exists = (\n load_bundled.calls()\n .match({\"value_func_id\": \"load_directory\", \"value_args_0_id\": \"directory\"})\n .exists()\n )\n\n assert (\n load_bundled_call_exists\n ), \"Are you calling `load_directory` and passing the correct parameters?\"\n\n\n@pytest.mark.test_site_load_bundled_module1\ndef test_site_load_bundled_module1(parse):\n\n # from ssg import extensions\n # extensions.load_bundled()\n\n site = parse(\"site\")\n assert site.success, site.message\n\n extensions_import = site.from_imports(\"ssg\", \"extensions\")\n assert extensions_import, \"Are you importing `extensions` from `ssg`?\"\n\n build = site.method(\"build\")\n\n load_bundled_call_exists = (\n build.calls()\n .match(\n {\n \"type\": \"Expr\",\n \"value_type\": \"Call\",\n \"value_func_value_id\": \"extensions\",\n \"value_func_attr\": \"load_bundled\",\n }\n )\n .exists()\n )\n\n assert (\n load_bundled_call_exists\n ), \"Are you calling `extensions.load_bundled()` in the `build` method?\"\n","sub_path":"tests/test_module1.py","file_name":"test_module1.py","file_ext":"py","file_size_in_byte":7105,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"125512999","text":"\"\"\"\n Script to aggregate the results from an experiment.\n\n Input: source folder path, e.g.\n python3 evaluate.py blazer_login_unsafe/fuzzer-out-\n\n\"\"\"\nimport sys\nimport csv\nimport statistics\nimport math\nimport numpy\n\n# do not change this parameters\nSTART_INDEX = 1\n\nif __name__ == '__main__':\n\n if len(sys.argv) != 5:\n raise Exception(\"usage: fuzzer-out-dir n timeout stepsize\")\n\n fuzzerOutDir = sys.argv[1]\n NUMBER_OF_EXPERIMENTS = int(sys.argv[2])\n EXPERIMENT_TIMEOUT = int(sys.argv[3])\n STEP_SIZE = int(sys.argv[4])\n\n # Read data\n collected_partition_data = []\n collected_delta_for_max_partition_data = []\n collected_delta_data = []\n time_partition_greater_one = {}\n\n for i in range(START_INDEX, NUMBER_OF_EXPERIMENTS+1):\n experimentFolderPath = fuzzerOutDir + str(i)\n #print(\"run \" + str(i))\n\n partition_data = {}\n delta_data = {}\n dataFile = experimentFolderPath + \"/afl/path_costs.csv\"\n with open(dataFile,'r') as csvfile:\n csvreader = csv.reader(csvfile, delimiter=';')\n timeBucket = STEP_SIZE\n next(csvreader) # skip first row\n\n # seed input\n row = next(csvreader)\n previousHighscorePartition = int(row[2])\n previousHighscoreDelta = float(row[3])\n currentHighscorePartition = int(row[2])\n currentHighscoreDelta = float(row[3])\n\n if currentHighscorePartition > 1:\n time_partition_greater_one[i] = int(row[0])\n\n for row in csvreader:\n currentTime = int(row[0])\n fileName = row[1]\n\n containsBetterPartition = \"+partition\" in fileName\n containsBetterDelta = \"+delta\" in fileName\n\n currentPartition = int(row[2])\n currentDelta = float(row[3])\n\n if i not in time_partition_greater_one and currentPartition > 1:\n time_partition_greater_one[i] = currentTime\n\n if containsBetterPartition:\n currentHighscorePartition = currentPartition\n\n if containsBetterDelta:\n currentHighscoreDelta = currentDelta\n\n while (currentTime > timeBucket):\n partition_data[timeBucket] = previousHighscorePartition\n delta_data[timeBucket] = previousHighscoreDelta\n timeBucket += STEP_SIZE\n\n previousHighscorePartition = currentHighscorePartition\n previousHighscoreDelta = currentHighscoreDelta\n\n if timeBucket > EXPERIMENT_TIMEOUT:\n break\n\n # fill data with last known value if not enough information\n while timeBucket <= EXPERIMENT_TIMEOUT:\n partition_data[timeBucket] = previousHighscorePartition\n delta_data[timeBucket] = previousHighscoreDelta\n timeBucket += STEP_SIZE\n\n collected_partition_data.append(partition_data)\n collected_delta_data.append(delta_data)\n\n if i not in time_partition_greater_one:\n time_partition_greater_one[i] = EXPERIMENT_TIMEOUT\n\n # Aggregate data for partitions\n mean_values_partition = {}\n error_values_partition = {}\n max_values_partition = {}\n partition_values = {}\n for i in range(STEP_SIZE, EXPERIMENT_TIMEOUT+1, STEP_SIZE):\n partition_values[i] = []\n for j in range(START_INDEX-1, NUMBER_OF_EXPERIMENTS):\n partition_values[i].append(collected_partition_data[j][i])\n mean_values_partition[i] = \"{0:.2f}\".format(sum(partition_values[i])/float(NUMBER_OF_EXPERIMENTS))\n error_values_partition[i] = \"{0:.2f}\".format(1.960 * numpy.std(partition_values[i])/float(math.sqrt(NUMBER_OF_EXPERIMENTS)))\n max_values_partition[i] = max(partition_values[i])\n\n mean_values_delta = {}\n error_values_delta = {}\n max_values_delta = {}\n delta_values = {}\n for i in range(STEP_SIZE, EXPERIMENT_TIMEOUT+1, STEP_SIZE):\n delta_values[i] = []\n for j in range(START_INDEX-1, NUMBER_OF_EXPERIMENTS):\n delta_values[i].append(collected_delta_data[j][i])\n mean_values_delta[i] = \"{0:.2f}\".format(sum(delta_values[i])/float(NUMBER_OF_EXPERIMENTS))\n error_values_delta[i] = \"{0:.2f}\".format(1.960 * numpy.std(delta_values[i])/float(math.sqrt(NUMBER_OF_EXPERIMENTS)))\n max_values_delta[i] = max(delta_values[i])\n\n\n # Calculate maximum delta for maximum number of partitions.\n absolute_max_partition = max_values_partition[EXPERIMENT_TIMEOUT]\n absolute_max_delta = 0\n for j in range(START_INDEX-1, NUMBER_OF_EXPERIMENTS):\n if collected_partition_data[j][EXPERIMENT_TIMEOUT] == absolute_max_partition:\n if collected_delta_data[j][EXPERIMENT_TIMEOUT] > absolute_max_delta:\n absolute_max_delta = collected_delta_data[j][EXPERIMENT_TIMEOUT]\n\n # Retrieve time to max partition.\n absolut_max_partition = max_values_partition[EXPERIMENT_TIMEOUT]\n times_local_maximum = []\n times_absolute_maximum = []\n min_time_absolute_max = EXPERIMENT_TIMEOUT\n for j in range(START_INDEX-1, NUMBER_OF_EXPERIMENTS):\n current_max_partition = partition_values[EXPERIMENT_TIMEOUT][j]\n current_time_max_partition = EXPERIMENT_TIMEOUT\n for i in range(EXPERIMENT_TIMEOUT, STEP_SIZE-1, (-1)*STEP_SIZE):\n if partition_values[i][j] != current_max_partition:\n break\n current_time_max_partition = i\n times_local_maximum.append(current_time_max_partition)\n\n if current_max_partition == absolut_max_partition and min_time_absolute_max > current_time_max_partition:\n min_time_absolute_max = current_time_max_partition\n\n if current_max_partition == absolut_max_partition:\n times_absolute_maximum.append(current_time_max_partition)\n else:\n times_absolute_maximum.append(EXPERIMENT_TIMEOUT)\n\n # Write collected data\n headers = ['seconds', 'c_avg_highscore', 'c_ci', 'c_max', 'd_avg_highscore', 'd_ci', 'd_max']\n outputFileName = fuzzerOutDir + \"results-n=\" + str(NUMBER_OF_EXPERIMENTS) + \"-t=\" + str(EXPERIMENT_TIMEOUT) + \"-s=\" + str(STEP_SIZE) + \".csv\"\n print (outputFileName)\n with open(outputFileName, \"w\") as csv_file:\n writer = csv.DictWriter(csv_file, fieldnames=headers)\n writer.writeheader()\n for timeBucket in range(STEP_SIZE, EXPERIMENT_TIMEOUT+1, STEP_SIZE):\n values = {'seconds' : int(timeBucket)}\n values['c_avg_highscore'] = mean_values_partition[timeBucket]\n values['c_ci'] = error_values_partition[timeBucket]\n values['c_max'] = max_values_partition[timeBucket]\n values['d_avg_highscore'] = mean_values_delta[timeBucket]\n values['d_ci'] = error_values_delta[timeBucket]\n values['d_max'] = max_values_delta[timeBucket]\n writer.writerow(values)\n","sub_path":"evaluation/scripts/evaluate_plain.py","file_name":"evaluate_plain.py","file_ext":"py","file_size_in_byte":6980,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"437667046","text":"from multiprocessing import Pool\nfrom tqdm import tqdm\nfrom collections import defaultdict\nimport re\nimport time\nimport random\nimport copy\nimport networkx as nx\nfrom colorama import Fore\n\nclass CorpusManager():\n corpus = []\n vocab = {}\n word_occurrence_index = {}\n concept_entities_unique = {}\n all_entities_tokens = set()\n joined_corpus = [] \n\n def __init__(self):\n self.corpus = []\n self.vocab = set()\n self.word_occurrence_index = {}\n self.concept_entities_unique = {}\n self.all_entities_tokens = set()\n self.joined_corpus = [] \n\n def read_corpus(self, PATH, length = 5000000):\n \"\"\"\n read the corpus at PATH for the first length lines\n for each line the '\\n' is removed, multiple withespaces are compressed to one\n save in the self.corpus a list for each line ('this is a sentence' become ['this', 'is', 'a', 'sentence'])\n save in the self.joined corpus the line\n create the vocab at self.vocab by adding each unique word\n :param \n PATH: the path to the corpus\n length: the number of lines that are to read\n \"\"\"\n self.corpus = []\n with open(PATH, 'r') as inp:\n print('read input corpus')\n ll = inp.readlines()\n for l in tqdm(ll[:length]):\n l = l.replace('\\n', '')\n l = re.sub(r'[ ]+',' ', l)\n if len(l) > 0:\n splitted = l.split(' ')\n self.corpus.append(splitted)\n self.joined_corpus.append(l)\n for s in splitted:\n self.vocab.add(s)\n\n def create_all_entities(self, entity_dict, concepts = None):\n \"\"\"\n create a list of all entities names about concepts in the concepts variable\n if concept is None, create all entities names about all concepts\n :param \n entity_dict: the entity dict returned from the method self.entities_from_types\n concepts: a list of concepts\n \"\"\"\n if not concepts:\n concepts = list(entity_dict.keys())\n\n self.all_entities_tokens = set()\n\n for _, entities in entity_dict.items():\n for e in entities:\n splitted = e.split(' ')\n if len(splitted) == 1:\n self.all_entities_tokens.add(e)\n else:\n for s in splitted:\n self.all_entities_tokens.add(s) \n self.entities_token_in_corpus = self.all_entities_tokens.intersection(self.vocab)\n self.all_entities_tokens = list(self.all_entities_tokens)\n\n print('{} words in vocab'.format(len(self.vocab)))\n print('{} entities'.format(len(self.all_entities_tokens)))\n print('{} entity-tokens in vocab'.format(len(self.entities_token_in_corpus)))\n random.shuffle(self.all_entities_tokens)\n\n def parallel_find(self, n_proc, n_entities = None):\n \"\"\"\n takes a fraction of entities in self.entity_token_in_corpus and for each call the function self.entities_token_in_corpus\n this method (and the involved one) are thought to work in parallel, so after the calling a reduce is applied\n :param \n n_proc: the number of process used to make the computation\n n_entities: the fraction of entities to find\n \"\"\"\n\n if not n_entities:\n n_entities = 1 \n\n p = Pool(n_proc)\n\n print('start indexing')\n frac = int(n_entities * len(self.entities_token_in_corpus))\n es = random.sample(list(self.entities_token_in_corpus), frac)\n \n t = time.time()\n\n index_list = p.map(self.create_word_occurrence_index, es)\n\n t = time.time() - t\n\n index_list_dict = {k:v for elem in index_list for k, v in elem.items() if v}\n p.close()\n return index_list_dict, n_proc, frac, len(self.corpus), t\n \n def create_word_occurrence_index(self, word):\n \"\"\"\n loop on all the corpus, call self.find_in_sentence to find occurrences of word in each sentence, returns a dict\n :param \n word: the word to find\n :return: a dict with the structure: {entity_name: list of tuples (row: [occurrences in row])}\n \"\"\"\n key = word\n returning_list = []\n for row_index, splitted_sentence in enumerate(self.corpus):\n if word in splitted_sentence:\n indices = self.find_in_sentence(word = word, sentence = splitted_sentence)\n if indices:\n returning_list.append((row_index, indices))\n return {key: returning_list}\n\n def find_in_sentence(self, word, sentence):\n \"\"\"\n returns the indexes in which the word appear in a sentence\n :params\n word: the word to find\n sentence: the sentence in which find the word\n :return: a list of indices\n \"\"\"\n\n indices = [i for i, x in enumerate(sentence) if x == word]\n return indices\n\n def clean_occurrences(self, list_of_indexes):\n return [{k:v} for L in list_of_indexes for k,v in L.items() if v]\n\n def avoid_multilabeling(self, entity_dict, G, file):\n \"\"\"\n entity dict is a dict which format is : {concept: [list of entities], ...}, the same entity name can appear in more than one list\n this method remove the repetitions:\n first check which entities are repeated, then for each repeated entities select the concept which is more deeper in the graph,\n if the most deepere concept is not unique, a casual concept (between the deepest) is taken \n :param \n entity_dict: the entity dict returned from the method self.entities_from_types\n G: the graph which contains the concepts\n file: path to the log file\n :return: an entity_dict without repeated entities\n \"\"\"\n reverse_dict = defaultdict(list)\n\n for k, words in entity_dict.items():\n for w in words:\n reverse_dict[w].append(k)\n i = 0\n for r in reverse_dict.values():\n if len(set(r)) > 1 :\n i += 1\n \n print('Multilabel alerts: {}'.format(i))\n\n with open(file, 'w') as out:\n out.write('Multilabel alerts: {}\\n'.format(i))\n\n for k, v in reverse_dict.items():\n if len(set(v)) > 1:\n min_dist = 100\n for clas in v:\n d = nx.shortest_path_length(G, 'Thing', clas)\n if d < min_dist:\n min_dist = d\n min_k = clas\n if d == min_dist:\n x = random.random()\n if x > 0.5:\n min_dist = d\n min_k = clas\n for clas in v:\n if clas != min_k:\n with open(file, 'a') as out:\n out.write('remove {} from {}\\n'.format(k, clas))\n entity_dict[clas].remove(k)\n\n reverse_dataset = {}\n for k, words in entity_dict.items():\n for w in words:\n try:\n reverse_dataset[w].append(k)\n except:\n reverse_dataset[w] = [k]\n i = 0\n for r in reverse_dataset.values():\n if len(set(r)) > 1:\n i += 1\n\n print('Multilabel alerts: {}'.format(i))\n \n with open(file, 'a') as out:\n out.write('Multilabel alerts: {}'.format(i)) \n return entity_dict\n\n def check_composite_words(self, word_indexes, entity_dict, verbose = False):\n \"\"\"\n starting from indexes of useful words in corpus (word_indexes) and the entity to find (entity_dict) \n returns the occurrences of the entities in entity dict.\n :param \n word_indexes: the first return of parallel find, contain a couple (row, index) for each word that is in entities names\n entity_dict: the entity dict returned from the method self.entities_from_types\n verbose: if True some (a very high number of) prints are showed\n :return: a dict like word_indexes but with ALL AND ONLY the entities names in corpus, with row indexes and occurrence indexes\n \"\"\"\n\n j = 0\n found = defaultdict(list)\n\n self.word_indexes = word_indexes\n\n all_entities = []\n for _, v in entity_dict.items():\n all_entities.extend(v)\n all_entities = set(all_entities)\n\n keys = set(word_indexes.keys())\n\n # bar = tqdm(total = len(all_entities))\n \n for entity in tqdm(all_entities):\n splitted = entity.split(' ')\n if set(splitted) <= keys:\n # all words in this entity are in the corpus\n i = 0\n rows = self.extract_rows(splitted[i])\n while rows and i + 1 < len(splitted):\n i += 1\n new_rows = set(self.extract_rows(splitted[i]))\n rows = list(set(rows).intersection(new_rows))\n if rows and len(splitted) > 1:\n for r in rows:\n b = self.check_entity_in_row(ENTITY=entity, ROW=r, verbose = verbose)\n if b:\n if verbose:\n print('entity found at index(es): {}'.format(' '.join([str(v) for v in b])))\n found[entity].append((r, b))\n j +=1\n elif rows:\n found[entity] = word_indexes[entity]\n if not verbose:\n pass\n # bar.update(1)\n return found\n\n\n def extract_rows(self, word):\n \"\"\"\n extract the row index from each tuple in word_indexes[word]\n :param\n word: a key in self.word_indexes\n :return: a list of indexes which are the row in which word appear\n \"\"\"\n return [t[0] for t in self.word_indexes[word]] #extract the row index from each tuple\n\n def check_entity_in_row(self, ENTITY, ROW, verbose = False):\n \"\"\"\n returns the indexes of all occurrences of an entity name (ENTITY) in a sentence (ROW)\n :param \n ENTITY: an entity name (e.g., 'London', 'New York')\n ROW: a row IN WHICH THE ENTITY OCCURS\n verbose: if True some (a very high number of) prints are showed\n :return: a list of indices which are the occurrence of ENTITY in the row ROW of the corpus\n \"\"\"\n\n a = self.extract_rows_occurrency(ENTITY.split(' '), ROW)\n\n if verbose:\n print('row: {}'.format(ROW))\n print('entity: {}'.format(ENTITY))\n print('indexes of each word: {}'.format([(w, o) for w, o in zip(ENTITY.split(' '), a)]))\n print(' '.join([Fore.WHITE + c_w if c_w not in ENTITY.split(' ') else Fore.CYAN + c_w for c_w in self.corpus[ROW]]))\n print(Fore.WHITE + '--------')\n values = []\n for value in a[0]:\n occ = [(value, 0)]\n i = 1\n while i < len(a) and value + i in a[i]:\n occ.append(((value + i), i))\n i += 1\n if i == len(a):\n if verbose:\n print(Fore.WHITE + 'entity present in this sentence at the index {}'.format(value))\n values.append(value)\n else:\n if verbose:\n print(Fore.WHITE + 'entity not present in this sentence at the index {}'.format(value))\n if verbose:\n print(Fore.WHITE + '--------')\n if values:\n return values\n\n\n def extract_rows_occurrency(self, word_phrase, row):\n \"\"\"\n extract the occurrency indexes of each token in the word_phrase for a row in the corpus\n :param\n word_prase: a list of token which compose an entity name (e.g., ['new', 'york'])\n row: a row index of the corpus\n :return: a list of indexes which are occurency indexes of the tokens\n \"\"\"\n return [t[1] for s in word_phrase for t in self.word_indexes[s] if t[0] == row]","sub_path":"preprocessing/CorpusManager.py","file_name":"CorpusManager.py","file_ext":"py","file_size_in_byte":12315,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"171312374","text":"from typing import Dict\n\nfrom exasol_integration_test_docker_environment.lib.base.flavor_task import FlavorsBaseTask\nfrom exasol_integration_test_docker_environment.lib.docker.images.save.save_task_creator_for_build_tasks import \\\n SaveTaskCreatorFromBuildTasks\n\nfrom exaslct_src.exaslct.lib.tasks.build.docker_flavor_build_base import DockerFlavorBuildBase\nfrom exaslct_src.exaslct.lib.tasks.save.docker_save_parameter import DockerSaveParameter\n\n\nclass DockerSave(FlavorsBaseTask, DockerSaveParameter):\n def register_required(self):\n tasks = self.create_tasks_for_flavors_with_common_params(\n DockerFlavorSave) # type: Dict[str,DockerFlavorSave]\n self.image_info_futures = self.register_dependencies(tasks)\n\n def run_task(self):\n image_infos = self.get_values_from_futures(self.image_info_futures)\n self.return_object(image_infos)\n\n\nclass DockerFlavorSave(DockerFlavorBuildBase, DockerSaveParameter):\n\n def get_goals(self):\n return self.goals\n\n def run_task(self):\n build_tasks = self.create_build_tasks(shortcut_build=not self.save_all)\n save_task_creator = SaveTaskCreatorFromBuildTasks(self)\n save_tasks = save_task_creator.create_tasks_for_build_tasks(build_tasks)\n image_info_furtures = yield from self.run_dependencies(save_tasks)\n image_infos = self.get_values_from_futures(image_info_furtures)\n self.return_object(image_infos)\n","sub_path":"exaslct_src/exaslct/lib/tasks/save/docker_save.py","file_name":"docker_save.py","file_ext":"py","file_size_in_byte":1441,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"249785246","text":"import math\n\nnum_inputs = int(input())\n\ninputs_list = []\nfor x in range(num_inputs):\n inputs_list.append(int(input()))\n\nprimes = set()\nprimes.add(2)\ncomposites = set()\ncomposites.add(1)\n\n\n\ndef find_primes(target):\n checked = {}\n\n\n\n for i in primes:\n if i not in checked:\n checked[target - i] = i\n else: \n print(checked[i] ,i)\n return() \n \n for i in range(max(primes),target):\n isPrime = True\n for x in range(2, math.ceil(math.sqrt(i)) + 1):\n\n if i % x == 0:\n isPrime = False\n break\n\n if isPrime == True:\n primes.add(i)\n #print(i)\n if i not in checked:\n checked[target - i] = i\n\n tempcheck = target-i\n\n for p in range(2,math.ceil(math.sqrt(tempcheck)) + 1):\n if (tempcheck % p) == 0:\n break\n\n else:\n print(i, tempcheck)\n return()\n\n else: \n print(checked[i] ,i)\n #print(primes)\n return()\n else:\n composites.add(i)\n\n\n\nfor i in range(len(inputs_list)):\n find_primes(inputs_list[i]*2)\n\n\n\n\n\n","sub_path":"2019/S2/CCC 2019 S2.py","file_name":"CCC 2019 S2.py","file_ext":"py","file_size_in_byte":1260,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"58181366","text":"Cversion = '2.0.0'\nfrom DNA.libont import bytearray_reverse, hexstring2bytes\nfrom DNA.interop.System.App import RegisterAppCall, DynamicAppCall\nfrom DNA.interop.System.Runtime import Notify\nfrom DNA.interop.System.Storage import GetContext, Get, Put, Delete\n\nName = 'Router'\n\ndef Main(operation, args):\n if operation == 'name':\n return name()\n if operation == 'setContract':\n assert (len(args) == 2)\n name = args[0]\n address = args[1]\n return setContract(name, address)\n if operation == 'callContract':\n assert (len(args) == 3)\n name = args[0]\n operation = args[1]\n params = args[2]\n return callContract(name, operation, params)\n return False\n\ndef name():\n return Name\n\ndef setContract(name, address):\n assert(len(address) == 40)\n reversedContractAddress = bytearray_reverse(hexstring2bytes(address))\n Put(GetContext(), name, reversedContractAddress)\n Notify([Name, \"setContract\", name, address])\n return True\n\ndef callContract(name, operation, params):\n reversedContractAddress = Get(GetContext(), name)\n res = DynamicAppCall(reversedContractAddress, operation, params)\n Notify([Name, \"callContract\", name, operation])\n return res","sub_path":"contracts/Router.py","file_name":"Router.py","file_ext":"py","file_size_in_byte":1243,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"450259597","text":"## Reverse Word Order\r\n\r\n# Input a sentence of words and will output the words in reverse order.\r\ndef reverse_sentence(sentence:str):\r\n \r\n sentence = 'My name is Fahim'\r\n words = sentence.split()\r\n result = \" \".join(words[::-1])\r\n print(result)\r\n \r\n \r\n ## Other way to do it\r\n ## Backward indexing using [::-1] is easier tho\r\n \r\n #list_words = []\r\n \r\n #for i in range(len(words)):\r\n # list_words.append(words[len(words)-i-1])\r\n\r\n #result = \" \".join(list_words)\r\n \r\n \r\n","sub_path":"ReverseWordOrder.py","file_name":"ReverseWordOrder.py","file_ext":"py","file_size_in_byte":522,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"247673949","text":"from model.ORM import get_session, CompanyEntity, CompanyWatcherEntity\n\n\nclass CompanyDao:\n def list(self):\n s = get_session()\n try:\n return s.query(CompanyEntity) \\\n .all()\n finally:\n s.close()\n\n def list_watcher(self, company_id):\n s = get_session()\n try:\n return s.query(CompanyWatcherEntity.watcher_id) \\\n .filter(CompanyWatcherEntity.company_id == company_id) \\\n .all()\n finally:\n s.close()\n\n def get(self, company_id):\n s = get_session()\n try:\n return s.query(CompanyEntity) \\\n .filter(CompanyEntity.company_id == company_id).one()\n finally:\n s.close()\n\n def add(self, company):\n s = get_session()\n try:\n s.add(CompanyEntity(company_id=company.company_id,\n name=company.name, address=company.address))\n s.commit()\n except BaseException as e:\n print(str(e))\n finally:\n s.close()\n\n def update(self, company):\n s = get_session()\n try:\n q = s.query(CompanyEntity) \\\n .filter(CompanyEntity.company_id == company.company_id).one()\n q.company_id = company.company_id\n q.name = company.name\n q.address = company.address\n s.commit()\n except BaseException as e:\n print(str(e))\n finally:\n s.close()\n\n def delete(self, company_id):\n s = get_session()\n try:\n q = s.query(CompanyEntity) \\\n .filter(CompanyEntity.company_id == company_id).one()\n s.delete(q)\n s.commit()\n finally:\n s.close()\n\n","sub_path":"dao/CompanyDAO.py","file_name":"CompanyDAO.py","file_ext":"py","file_size_in_byte":1801,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"437343214","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models\n\n# Create your models here.\n\nclass User(models.Model):\n\t#User Table\n\tid = models.AutoField(primary_key=True)\n\tfirst_name = models.CharField(max_length=200)\n\tlast_name = models.CharField(max_length=200)\n\temail = models.EmailField()\n\tphone = models.BigIntegerField()\n\tpassword = models.CharField(max_length=200)\n\tdate_joined = models.DateField(auto_now_add=True)\n\nclass UserAddress(models.Model):\n\t#Saved User Addresses\n\tid = models.AutoField(primary_key=True)\n\tuser_id = models.ForeignKey('User',on_delete=models.CASCADE,)\n\thouse = models.CharField(max_length=200)\n\tstreet_1 = models.CharField(max_length=200)\n\thouse_2 = models.CharField(max_length=200)\n\tcity = models.CharField(max_length=200)\n\tstate = models.CharField(max_length=200)\n\tpincode = models.PositiveSmallIntegerField()\n\nclass Cart(models.Model):\n\t#User Cart\n\tid = models.AutoField(primary_key=True)\n\tuser_id = models.ForeignKey('User',on_delete=models.CASCADE,)\n\tpayment = models.NullBooleanField()\n\tdate = models.DateField(auto_now_add=True)\n\tpayment_date = models.DateField(null=True)\n\n\nclass CartBook(models.Model):\n\t#List of books in a cart\n\tid = models.AutoField(primary_key=True)\n\tcart_id = models.ForeignKey('Cart',on_delete=models.CASCADE,)\n\tpage_count = models.PositiveSmallIntegerField()\n\tpage_size = models.ForeignKey('Page',on_delete=models.PROTECT,)\n\tpage_quality = models.ForeignKey('PageQuality',on_delete=models.PROTECT,)\n\tink_type = models.ForeignKey('InkType',on_delete=models.PROTECT,)\n\tcover_id = models.ForeignKey('Cover',on_delete=models.PROTECT,)\n\tbinding = models.ForeignKey('CoverBinding',on_delete=models.PROTECT,)\n\tprice = models.DecimalField(max_digits=5, decimal_places=2)\n\nclass OrderMapping(models.Model):\n\t#Order map for each book\n\tid = models.AutoField(primary_key=True)\n\tcart_book_id = models.OneToOneField(CartBook,on_delete = models.CASCADE)\n\tdate = models.DateField(auto_now_add=True)\n\tprovider_id = models.ForeignKey('Provider',on_delete=models.PROTECT,)\n\nclass OrderStatus(models.Model):\n\t#Status Logs of each order\n\tid = models.AutoField(primary_key=True)\n\torder_mapping_id = models.ForeignKey('OrderMapping',on_delete=models.CASCADE,)\n\tstatus_code = models.CharField(max_length=200)\n\tdescription = models.CharField(max_length=200)\n\tdate = models.DateField(auto_now_add=True)\n\nclass Provider(models.Model):\n\t#Print Service Provider Details\n\tid = models.AutoField(primary_key=True)\n\tbusiness_name = models.CharField(max_length=200)\n\temail = models.CharField(max_length=200)\n\tphone = models.BigIntegerField()\n\tpassword = models.CharField(max_length=200)\n\taddress_line_1 = models.CharField(max_length=200)\n\taddress_line_2 = models.CharField(max_length=200)\n\tstate = models.CharField(max_length=200)\n\tcity = models.CharField(max_length=200)\n\tpincode = models.CharField(max_length=200)\n\nclass ProviderVerification(models.Model):\n\t#Provider Verification Documents\n\tid = models.AutoField(primary_key=True)\n\tprovider_id = models.ForeignKey('Provider',on_delete=models.CASCADE,)\n\nclass ProviderPickupAddress(models.Model):\n\t#Provider Wherehouse Location\n\tid = models.AutoField(primary_key=True)\n\tprovider_id = models.ForeignKey('Provider',on_delete=models.CASCADE,)\n\nclass Cover(models.Model):\n\t#Available Covers\n\tid = models.AutoField(primary_key=True)\n\tcover_type = models.CharField(max_length=200)\n\tcost = models.DecimalField(max_digits=5, decimal_places=2)\n\t\nclass CoverBinding(models.Model):\n\t#Available Binding Types\n\tid = models.AutoField(primary_key=True)\n\tcost = models.DecimalField(max_digits=5, decimal_places=2)\n\tcover_id = models.ForeignKey('Cover',on_delete=models.PROTECT,)\n\nclass Page(models.Model):\n\t#Page types\n\tid = models.AutoField(primary_key=True)\n\tcovers = models.ForeignKey('Cover',on_delete=models.PROTECT,)\n\tsize = models.CharField(max_length=200)\n\tcost = models.DecimalField(max_digits=5, decimal_places=2)\n\nclass PageQuality(models.Model):\n\t#Page quality\n\tid = models.AutoField(primary_key=True)\n\tpage_id = models.ForeignKey('Page',on_delete=models.PROTECT,)\n\nclass InkType(models.Model):\n\t#ink to be used\n\tid = models.AutoField(primary_key=True)\n\tpage_id = models.ForeignKey('Page',on_delete=models.PROTECT,)","sub_path":"copyloftserver/models/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":4225,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"553171674","text":"# Copyright 2018 RedHat Inc.\n# All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\n\nimport mock\nfrom oslo_concurrency import processutils\nfrom oslo_config import cfg\nfrom oslo_utils import units\nimport six\n\nimport glance_store as store\nfrom glance_store._drivers import sheepdog\nfrom glance_store import exceptions\nfrom glance_store import location\nfrom glance_store.tests import base\nfrom glance_store.tests.unit import test_store_capabilities as test_cap\n\n\nclass TestSheepdogMultiStore(base.MultiStoreBaseTest,\n test_cap.TestStoreCapabilitiesChecking):\n\n # NOTE(flaper87): temporary until we\n # can move to a fully-local lib.\n # (Swift store's fault)\n _CONF = cfg.ConfigOpts()\n\n def setUp(self):\n \"\"\"Establish a clean test environment.\"\"\"\n super(TestSheepdogMultiStore, self).setUp()\n enabled_backends = {\n \"sheepdog1\": \"sheepdog\",\n \"sheepdog2\": \"sheepdog\",\n }\n self.conf = self._CONF\n self.conf(args=[])\n self.conf.register_opt(cfg.DictOpt('enabled_backends'))\n self.config(enabled_backends=enabled_backends)\n store.register_store_opts(self.conf)\n self.config(default_backend='sheepdog1', group='glance_store')\n\n # mock sheepdog commands\n def _fake_execute(*cmd, **kwargs):\n pass\n\n execute = mock.patch.object(processutils, 'execute').start()\n execute.side_effect = _fake_execute\n self.addCleanup(execute.stop)\n\n # Ensure stores + locations cleared\n location.SCHEME_TO_CLS_BACKEND_MAP = {}\n\n store.create_multi_stores(self.conf)\n self.addCleanup(setattr, location, 'SCHEME_TO_CLS_BACKEND_MAP',\n dict())\n self.addCleanup(self.conf.reset)\n\n self.store = sheepdog.Store(self.conf, backend='sheepdog1')\n self.store.configure()\n self.store_specs = {'image': '6bd59e6e-c410-11e5-ab67-0a73f1fda51b',\n 'addr': '127.0.0.1',\n 'port': 7000}\n\n @mock.patch.object(sheepdog.SheepdogImage, 'write')\n @mock.patch.object(sheepdog.SheepdogImage, 'create')\n @mock.patch.object(sheepdog.SheepdogImage, 'exist')\n def test_add_image(self, mock_exist, mock_create, mock_write):\n data = six.BytesIO(b'xx')\n mock_exist.return_value = False\n\n (uri, size, checksum, loc) = self.store.add('fake_image_id', data, 2)\n self.assertEqual(\"sheepdog1\", loc[\"backend\"])\n\n mock_exist.assert_called_once_with()\n mock_create.assert_called_once_with(2)\n mock_write.assert_called_once_with(b'xx', 0, 2)\n\n @mock.patch.object(sheepdog.SheepdogImage, 'write')\n @mock.patch.object(sheepdog.SheepdogImage, 'create')\n @mock.patch.object(sheepdog.SheepdogImage, 'exist')\n def test_add_image_to_different_backend(self, mock_exist,\n mock_create, mock_write):\n self.store = sheepdog.Store(self.conf, backend='sheepdog2')\n self.store.configure()\n\n data = six.BytesIO(b'xx')\n mock_exist.return_value = False\n\n (uri, size, checksum, loc) = self.store.add('fake_image_id', data, 2)\n self.assertEqual(\"sheepdog2\", loc[\"backend\"])\n\n mock_exist.assert_called_once_with()\n mock_create.assert_called_once_with(2)\n mock_write.assert_called_once_with(b'xx', 0, 2)\n\n @mock.patch.object(sheepdog.SheepdogImage, 'write')\n @mock.patch.object(sheepdog.SheepdogImage, 'exist')\n def test_add_bad_size_with_image(self, mock_exist, mock_write):\n data = six.BytesIO(b'xx')\n mock_exist.return_value = False\n\n self.assertRaises(exceptions.Forbidden, self.store.add,\n 'fake_image_id', data, 'test')\n\n mock_exist.assert_called_once_with()\n self.assertEqual(mock_write.call_count, 0)\n\n @mock.patch.object(sheepdog.SheepdogImage, 'delete')\n @mock.patch.object(sheepdog.SheepdogImage, 'write')\n @mock.patch.object(sheepdog.SheepdogImage, 'create')\n @mock.patch.object(sheepdog.SheepdogImage, 'exist')\n def test_cleanup_when_add_image_exception(self, mock_exist, mock_create,\n mock_write, mock_delete):\n data = six.BytesIO(b'xx')\n mock_exist.return_value = False\n mock_write.side_effect = exceptions.BackendException\n\n self.assertRaises(exceptions.BackendException, self.store.add,\n 'fake_image_id', data, 2)\n\n mock_exist.assert_called_once_with()\n mock_create.assert_called_once_with(2)\n mock_write.assert_called_once_with(b'xx', 0, 2)\n mock_delete.assert_called_once_with()\n\n def test_add_duplicate_image(self):\n def _fake_run_command(command, data, *params):\n if command == \"list -r\":\n return \"= fake_volume 0 1000\"\n\n with mock.patch.object(sheepdog.SheepdogImage, '_run_command') as cmd:\n cmd.side_effect = _fake_run_command\n data = six.BytesIO(b'xx')\n self.assertRaises(exceptions.Duplicate, self.store.add,\n 'fake_image_id', data, 2)\n\n def test_get(self):\n def _fake_run_command(command, data, *params):\n if command == \"list -r\":\n return \"= fake_volume 0 1000\"\n\n with mock.patch.object(sheepdog.SheepdogImage, '_run_command') as cmd:\n cmd.side_effect = _fake_run_command\n loc = location.Location('test_sheepdog_store',\n sheepdog.StoreLocation,\n self.conf, store_specs=self.store_specs,\n backend='sheepdog1')\n ret = self.store.get(loc)\n self.assertEqual(1000, ret[1])\n\n def test_partial_get(self):\n loc = location.Location('test_sheepdog_store', sheepdog.StoreLocation,\n self.conf, store_specs=self.store_specs,\n backend='sheepdog1')\n self.assertRaises(exceptions.StoreRandomGetNotSupported,\n self.store.get, loc, chunk_size=1)\n\n def test_get_size(self):\n def _fake_run_command(command, data, *params):\n if command == \"list -r\":\n return \"= fake_volume 0 1000\"\n\n with mock.patch.object(sheepdog.SheepdogImage, '_run_command') as cmd:\n cmd.side_effect = _fake_run_command\n loc = location.Location('test_sheepdog_store',\n sheepdog.StoreLocation,\n self.conf, store_specs=self.store_specs,\n backend='sheepdog1')\n ret = self.store.get_size(loc)\n self.assertEqual(1000, ret)\n\n def test_delete(self):\n called_commands = []\n\n def _fake_run_command(command, data, *params):\n called_commands.append(command)\n if command == \"list -r\":\n return \"= fake_volume 0 1000\"\n\n with mock.patch.object(sheepdog.SheepdogImage, '_run_command') as cmd:\n cmd.side_effect = _fake_run_command\n loc = location.Location('test_sheepdog_store',\n sheepdog.StoreLocation,\n self.conf, store_specs=self.store_specs,\n backend='sheepdog1')\n self.store.delete(loc)\n self.assertEqual(['list -r', 'delete'], called_commands)\n\n def test_add_with_verifier(self):\n \"\"\"Test that 'verifier.update' is called when verifier is provided.\"\"\"\n verifier = mock.MagicMock(name='mock_verifier')\n self.store.chunk_size = units.Ki\n image_id = 'fake_image_id'\n file_size = units.Ki # 1K\n file_contents = b\"*\" * file_size\n image_file = six.BytesIO(file_contents)\n\n def _fake_run_command(command, data, *params):\n pass\n\n with mock.patch.object(sheepdog.SheepdogImage, '_run_command') as cmd:\n cmd.side_effect = _fake_run_command\n (uri, size, checksum, loc) = self.store.add(\n image_id, image_file, file_size, verifier=verifier)\n self.assertEqual(\"sheepdog1\", loc[\"backend\"])\n\n verifier.update.assert_called_with(file_contents)\n","sub_path":"glance_store/tests/unit/test_multistore_sheepdog.py","file_name":"test_multistore_sheepdog.py","file_ext":"py","file_size_in_byte":8877,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"171081695","text":"import os\nimport requests\nimport json\nimport time\nimport random\nimport sys\nimport substring\nfrom colorama import init,Fore\nfrom datetime import datetime\nfrom multiprocessing.dummy import Pool as ThreadPool\nfrom threading import Thread, Lock\nfrom fake_useragent import UserAgent\nfrom bs4 import BeautifulSoup\n\nclass Main:\n def clear(self):\n if os.name == 'posix':\n os.system('clear')\n elif os.name in ('ce', 'nt', 'dos'):\n os.system('cls')\n else:\n print(\"\\n\") * 120\n\n def SetTitle(self,title_name:str):\n os.system(\"title {0}\".format(title_name))\n\n def ReadFile(self,filename,method):\n with open(filename,method) as f:\n content = [line.strip('\\n') for line in f]\n return content\n\n def __init__(self):\n self.SetTitle('One Man Builds TikTok Video Downloader Tool')\n self.clear()\n init(convert=True)\n title = Fore.YELLOW+\"\"\"\n ___ _ _ _ ___ ____ _ _ _ _ _ ___ ____ ____ \n | | |_/ | | | |_/ | | | | \\ |___ | | \n | | | \\_ | |__| | \\_ \\/ | |__/ |___ |__| \n \n ___ ____ _ _ _ _ _ _ ____ ____ ___ ____ ____ \n | \\ | | | | | |\\ | | | | |__| | \\ |___ |__/ \n |__/ |__| |_|_| | \\| |___ |__| | | |__/ |___ | \\ \n \n \"\"\"\n print(title)\n self.ua = UserAgent()\n self.use_proxy = int(input(Fore.YELLOW+'['+Fore.WHITE+'>'+Fore.YELLOW+'] Would you like to use proxies [1] yes [0] no: '))\n self.method = int(input(Fore.YELLOW+'['+Fore.WHITE+'>'+Fore.YELLOW+'] [1] Download 1 video [2] Download multiple videos from txt: '))\n print('')\n self.videos = self.ReadFile('videos.txt','r')\n self.header = headers = {'User-Agent':'okhttp','referer':'https://www.tiktok.com/'}\n\n def GetRandomProxy(self):\n proxies_file = self.ReadFile('proxies.txt','r')\n proxies = {\n \"http\":\"http://{0}\".format(random.choice(proxies_file)),\n \"https\":\"https://{0}\".format(random.choice(proxies_file))\n }\n return proxies\n\n def DownloadVideo(self):\n download_url = str(input(Fore.YELLOW+'['+Fore.WHITE+'>'+Fore.YELLOW+'] TikTok Video URL: '))\n\n if 'https://' not in download_url:\n download_url = 'https://{0}'.format(download_url)\n\n response = requests.get(download_url,headers=self.header).text\n\n soup = BeautifulSoup(response,'html.parser')\n script = soup.find('script',{'id':'__NEXT_DATA__'})\n\n while script == None:\n try:\n if self.use_proxy == 1:\n response = requests.get(download_url,headers=self.header,proxies=self.GetRandomProxy()).text\n soup = BeautifulSoup(response,'html.parser')\n script = soup.find('script',{'id':'__NEXT_DATA__'})\n else:\n response = requests.get(download_url,headers=self.header).text\n soup = BeautifulSoup(response,'html.parser')\n script = soup.find('script',{'id':'__NEXT_DATA__'})\n \n time.sleep(2)\n except:\n pass\n \n json_data = json.loads(script.string)\n full_url = json_data['props']['pageProps']['videoData']['itemInfos']['video']['urls'][0]\n\n download_req = requests.get(full_url,headers=self.header)\n filename = substring.substringByChar(download_url,'@','/')\n filename = filename.replace('/','')\n \n with open('Downloads/{0}'.format(filename+''.join(random.choice('0123456789') for _ in range(6))+'.mp4'), 'wb') as f:\n f.write(download_req.content)\n print('')\n print(Fore.GREEN+'['+Fore.WHITE+'!'+Fore.GREEN+'] DOWNLOADED | {0} | {1}'.format(filename,download_url))\n\n def DownloadVideos(self,videos):\n\n if 'https://' not in videos:\n videos = 'https://{0}'.format(videos)\n\n response = requests.get(videos,headers=self.header).text\n\n soup = BeautifulSoup(response,'html.parser')\n script = soup.find('script',{'id':'__NEXT_DATA__'})\n\n while script == None:\n try:\n if self.use_proxy == 1:\n response = requests.get(videos,headers=self.header,proxies=self.GetRandomProxy()).text\n soup = BeautifulSoup(response,'html.parser')\n script = soup.find('script',{'id':'__NEXT_DATA__'})\n else:\n response = requests.get(videos,headers=self.header).text\n soup = BeautifulSoup(response,'html.parser')\n script = soup.find('script',{'id':'__NEXT_DATA__'})\n except:\n pass\n \n json_data = json.loads(script.string)\n full_url = json_data['props']['pageProps']['videoData']['itemInfos']['video']['urls'][0]\n\n download_req = requests.get(full_url,headers=self.header)\n filename = substring.substringByChar(videos,'@','/')\n filename = filename.replace('/','')\n \n with open('Downloads/{0}'.format(filename+''.join(random.choice('0123456789') for _ in range(6))+'.mp4'), 'wb') as f:\n f.write(download_req.content)\n print(Fore.GREEN+'['+Fore.WHITE+'!'+Fore.GREEN+'] DOWNLOADED | {0} | {1}'.format(filename,videos))\n\n def Start(self):\n if self.method == 2:\n pool = ThreadPool()\n results = pool.map(self.DownloadVideos,self.videos)\n pool.close()\n pool.join()\n else:\n self.DownloadVideo()\n\n \nif __name__ == \"__main__\":\n main = Main()\n main.Start()\n ","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":5954,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"113540885","text":"#!/usr/bin/env python3\n# -*- coding:utf-8 -*-\n# Author: kerlomz \n\nimport socket\nimport uuid\n\n\nclass Variable:\n import os\n import sys\n EXEC_PATH = os.path.realpath(sys.argv[0])\n MAC_ADDRESS = \":\".join([(uuid.UUID(int=uuid.getnode()).hex[-12:])[e:e + 2] for e in range(0, 11, 2)]).upper()\n HOST_NAME = socket.gethostname()\n\n\nclass RequestException:\n\n def __init__(self):\n # SIGN\n self.INVALID_PUBLIC_PARAMS = dict(message='Invalid Public Params', code=40001)\n self.UNKNOWN_SERVER_ERROR = dict(message='Unknown Server Error', code=40002)\n self.INVALID_VERSION = dict(message='Invalid Version', code=40003)\n self.INVALID_TIMESTAMP = dict(message='Invalid Timestamp', code=40004)\n self.INVALID_ACCESS_KEY = dict(message='Invalid Access Key', code=40005)\n self.INVALID_QUERY_STRING = dict(message='Invalid Query String', code=40006)\n\n # FLASK\n self.PARAMETER_MISSING = dict(message='Parameter Missing', code=40007)\n self.DATABASE_CONNECTION_ERROR = dict(message='Database Connection Error', code=40008)\n self.USER_OR_MODEL_DOES_NOT_EXIST = dict(message='User or Model doesn\\'t Exist', code=40009)\n self.INSUFFICIENT_BALANCE = dict(message='Insufficient Balance', code=40010)\n self.USER_DOES_NOT_EXIST_OR_BE_BANNED = dict(message='User doesn\\'t Exist or be Banned', code=40011)\n self.ORDER_DOES_NOT_EXIST_OR_INVALID = dict(message='Order doesn\\'t Exist or Invalid', code=40012)\n\n # G-RPC\n self.INVALID_IMAGE_FORMAT = dict(message='Invalid Image Format', code=50001)\n self.INVALID_BASE64_STRING = dict(message='Invalid Base64 String', code=50002)\n self.IMAGE_DAMAGE = dict(message='Image Damage', code=50003)\n\n\n def find(self, _code):\n e = [value for value in vars(self).values()]\n _t = [i['message'] for i in e if i['code'] == _code]\n return _t[0] if _t else None\n","sub_path":"constants.py","file_name":"constants.py","file_ext":"py","file_size_in_byte":1944,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"636748073","text":"# -*- encoding: utf-8 -*-\n##############################################################################\n# \n# OpenERP, Open Source Management Solution\n# Copyright (C) 2013 Savoir-faire Linux ().\n#\n# This program is free software: you can redistribute it and/or modify\n# it under the terms of the GNU Affero General Public License as\n# published by the Free Software Foundation, either version 3 of the\n# License, or (at your option) any later version.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU Affero General Public License for more details.\n#\n# You should have received a copy of the GNU Affero General Public License\n# along with this program. If not, see . \n#\n##############################################################################\nfrom openerp.osv import fields, orm\nfrom datetime import *\n\nclass document_page_history_wkfl(orm.Model):\n _inherit = 'document.page.history'\n \n def page_approval_draft(self, cr, uid, ids):\n self.write(cr, uid, ids, { 'state' : 'draft' })\n \n template_id = self.pool.get('ir.model.data').get_object_reference(cr, uid, \n 'document_page_approval', 'email_template_new_draft_need_approval')[1]\n for page in self.browse(cr, uid, ids):\n if page.is_parent_approval_required:\n self.pool.get('email.template').send_mail(cr, uid, template_id,\n page.id, force_send=True)\n\n return True\n \n def page_approval_approved(self, cr, uid, ids):\n self.write(cr, uid, ids, { 'state' : 'approved',\n 'approved_date' : datetime.now().strftime('%Y-%m-%d %H:%M:%S'),\n 'approved_uid': uid\n })\n return True\n \n def can_user_approve_page(self, cr, uid, ids, name, args, context=None):\n user = self.pool.get('res.users').browse(cr,uid,uid)\n res = {}\n for page in self.browse(cr, uid, ids, context=context):\n res[page.id]= self.can_user_approve_this_page(page.page_id, user)\n \n return res\n \n def can_user_approve_this_page(self, page, user):\n if page:\n res = page.approver_gid in user.groups_id\n res = res or self.can_user_approve_this_page(page.parent_id, user)\n else:\n res=False\n \n return res\n \n def get_approvers_guids(self, cr, uid, ids, name, args, context=None):\n res = {}\n for page in self.browse(cr, uid, ids, context=context):\n res[page.id]= self.get_approvers_guids_for_page(page.page_id)\n \n return res\n \n def get_approvers_guids_for_page(self, page):\n if page:\n if page.approver_gid:\n res = [page.approver_gid.id]\n else:\n res=[]\n res.extend(self.get_approvers_guids_for_page(page.parent_id))\n else:\n res=[]\n \n return res\n \n def get_approvers_email(self, cr, uid, ids, name, args, context):\n res = {}\n for id in ids:\n emails = ''\n guids = self.get_approvers_guids(cr, uid, ids, name, args, context=context)\n uids = self.pool.get('res.users').search(cr, uid, [('groups_id','in',guids[id])])\n users = self.pool.get('res.users').browse(cr, uid, uids)\n\n for user in users:\n if user.email:\n emails += user.email\n emails += ','\n else:\n empl_id = self.pool.get('hr.employee').search(cr, uid,\n [('login','=',user.login)])[0]\n empl = self.pool.get('hr.employee').browse(cr, uid, empl_id)\n if empl.work_email:\n emails += empl.work_email\n emails += ','\n\n emails = emails[:-1]\n res[id] = emails\n return res\n \n def get_page_url(self, cr, uid, ids, name, args, context):\n res = {}\n for id in ids:\n base_url = self.pool.get('ir.config_parameter').get_param(cr, uid, \n 'web.base.url', default='http://localhost:8069', context=context)\n \n res[id] = base_url + '/#db=%s&id=%s&view_type=form&model=document.page.history' % (cr.dbname, id);\n \n return res\n\n _columns = {\n 'state': fields.selection([\n ('draft','Draft'),\n ('approved','Approved')], 'Status', readonly=True),\n 'approved_date': fields.datetime(\"Approved Date\"),\n 'approved_uid': fields.many2one('res.users', \"Approved By\"),\n 'is_parent_approval_required': fields.related('page_id', 'is_parent_approval_required', \n string=\"parent approval\", type='boolean', store=False),\n 'can_user_approve_page': fields.function(can_user_approve_page, \n string=\"can user approve this page\", type='boolean', store=False),\n 'get_approvers_email': fields.function(get_approvers_email, \n string=\"get all approvers email\", type='text', store=False),\n 'get_page_url': fields.function(get_page_url, string=\"URL\", type='text',\n store=False),\n }\n \nclass document_page_approval(orm.Model):\n _inherit = 'document.page'\n def _get_display_content(self, cr, uid, ids, name, args, context=None):\n res = {}\n for page in self.browse(cr, uid, ids, context=context):\n content=\"\"\n if page.type == \"category\":\n content = self._get_page_index(cr, uid, page, link=False)\n else:\n history = self.pool.get('document.page.history')\n if self.is_approval_required(page):\n history_ids = history.search(cr, uid,[('page_id', '=', page.id), \n ('state', '=', 'approved')], limit=1, order='create_date DESC')\n for h in history.browse(cr, uid, history_ids):\n content = h.content\n else:\n content = page.content\n res[page.id] = content\n return res\n \n def _get_approved_date(self, cr, uid, ids, name, args, context=None):\n res = {}\n for page in self.browse(cr, uid, ids, context=context):\n if self.is_approval_required(page):\n history = self.pool.get('document.page.history')\n history_ids = history.search(cr, uid,[('page_id', '=', page.id), \n ('state', '=', 'approved')], limit=1, order='create_date DESC')\n approved_date = False\n for h in history.browse(cr, uid, history_ids):\n approved_date = h.approved_date\n res[page.id] = approved_date\n else:\n res[page.id] = \"\"\n \n return res\n \n def _get_approved_uid(self, cr, uid, ids, name, args, context=None):\n res = {}\n for page in self.browse(cr, uid, ids, context=context):\n if self.is_approval_required(page):\n history = self.pool.get('document.page.history')\n history_ids = history.search(cr, uid,[('page_id', '=', page.id), \n ('state', '=', 'approved')], limit=1, order='create_date DESC')\n approved_uid = False\n for h in history.browse(cr, uid, history_ids):\n approved_uid = h.approved_uid.id\n res[page.id] = approved_uid\n else:\n res[page.id] = \"\"\n \n return res\n \n def _is_parent_approval_required(self, cr, uid, ids, name, args, context=None):\n res = {}\n for page in self.browse(cr, uid, ids, context=context):\n res[page.id]= self.is_approval_required(page)\n \n return res\n \n def is_approval_required(self, page):\n if page:\n res = page.approval_required\n res = res or self.is_approval_required(page.parent_id)\n else:\n res=False\n \n return res\n \n _columns = {\n 'display_content': fields.function(_get_display_content, \n string='Displayed Content', type='text'),\n 'approved_date': fields.function(_get_approved_date, string=\"Approved Date\", \n type='datetime'),\n 'approved_uid': fields.function(_get_approved_uid, string=\"Approved By\", \n type='many2one', obj='res.users'),\n 'approval_required': fields.boolean(\"Require approval\"),\n 'is_parent_approval_required': fields.function(_is_parent_approval_required, \n string=\"parent approval\", type='boolean'),\n 'approver_gid': fields.many2one(\"res.groups\", \"Approver group\"),\n }\n# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:\n","sub_path":"document_page_approval.py","file_name":"document_page_approval.py","file_ext":"py","file_size_in_byte":9071,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"38588286","text":"#\n# @lc app=leetcode.cn id=347 lang=python3\n#\n# [347] 前 K 个高频元素\n#\n\n# @lc code=start\nclass Solution:\n def topKFrequent(self, nums: List[int], k: int) -> List[int]:\n count = {}\n for num in nums:\n if num not in count:\n count[num] = 1\n else:\n count[num] += 1\n count_sorted = sorted(count.items(), key=lambda x: x[1], reverse=True)\n return [item[0] for item in count_sorted[:k]]\n \n# @lc code=end\n\n","sub_path":"Week_02/五毒神掌第一掌/347.前-k-个高频元素.py","file_name":"347.前-k-个高频元素.py","file_ext":"py","file_size_in_byte":494,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"616000313","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri May 10 21:26:55 2019\n\n@author: jean\n\"\"\"\n''' import dataset'''\n\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport matplotlib.pyplot as plt\nimport pandas as pd\nimport numpy as np\n\n# data loading and transforming\nfrom torch.utils.data import DataLoader\n\nimport os\nimport sys\n\nsys.path.append(\"..\")\npwd = os.path.abspath('.') \n\nfrom GetThreeChannel import TTdataset,ToTensor\nfrom torch.utils.data.sampler import SubsetRandomSampler\n## Define a transform to read the data in as a tensor\ndata_transform = ToTensor()\n\n'''\npred_interval : 'no_normal_5min': traveltime without normalization\n '5min': traveltime with Z-score normalization\n 'uniform_5min': traveltime with uniform normalization to 0-1\n'''\npred_interval = 'no_normal_5min'\ncsv_file1=pwd+'/TravelTime/{}/train_data/combined_flow.csv'.format(pred_interval)\ncsv_file2=pwd+'/TravelTime/{}/train_data/combined_occupancy.csv'.format(pred_interval)\ncsv_file3=pwd+'/TravelTime/{}/train_data/combined_observation.csv'.format(pred_interval)\n\ntest_csv_file1=pwd+'/TravelTime/{}/test_data/combined_flow.csv'.format(pred_interval)\ntest_csv_file2=pwd+'/TravelTime/{}/test_data/combined_occupancy.csv'.format(pred_interval)\ntest_csv_file3=pwd+'/TravelTime/{}/test_data/combined_observation.csv'.format(pred_interval)\n\n\nroot_dir1 = pwd+'/Pics/flow'\nroot_dir2 = pwd+'/Pics/occupancy'\nroot_dir3 = pwd+'/Pics/observation'\ntrain_data = TTdataset(csv_file1, csv_file2, csv_file3, root_dir1, root_dir2, root_dir3, transform=data_transform)\ntest_data = TTdataset(test_csv_file1, test_csv_file2, test_csv_file3, root_dir1, root_dir2, root_dir3, transform=data_transform)\n\ndef create_datasets(batch_size, train_set, test_set):\n\n # percentage of training set to use as validation\n valid_size = 0.3\n\n # choose the training and test datasets\n train_data = train_set\n\n test_data = test_set\n\n # obtain training indices that will be used for validation\n num_train = len(train_data)\n indices = list(range(num_train))\n np.random.shuffle(indices)\n split = int(np.floor(valid_size * num_train))\n train_idx, valid_idx = indices[split:], indices[:split]\n \n # define samplers for obtaining training and validation batches\n train_sampler = SubsetRandomSampler(train_idx)\n valid_sampler = SubsetRandomSampler(valid_idx)\n \n # load training data in batches\n train_loader = torch.utils.data.DataLoader(train_data,\n batch_size=batch_size,\n sampler=train_sampler,\n num_workers=0)\n \n # load validation data in batches\n valid_loader = torch.utils.data.DataLoader(train_data,\n batch_size=batch_size,\n sampler=valid_sampler,\n num_workers=0)\n \n # load test data in batches\n test_loader = torch.utils.data.DataLoader(test_data,\n batch_size=batch_size,\n num_workers=0)\n \n return train_loader, test_loader, valid_loader\n \n''' Define a CNN '''\nclass Net(nn.Module):\n\n def __init__(self):\n super(Net, self).__init__()\n \n # 3 input image channels (speed, flow, occupancy), 10 output channels/feature maps\n # 3x3 square convolution kernel\n ## output size = (W-F+2*P)/S +1 = (15-3)/1 +1 = 13\n # W: input width, F: kernel_size P: padding S: stride\n # the output Tensor for one image, will have the dimensions: (10, 13, 13)\n self.conv1 = nn.Conv2d(3, 10, 3)\n self.conv1_bn = nn.BatchNorm2d(10)\n # maxpool layer\n # pool with kernel_size=2, stride=2\n self.pool = nn.MaxPool2d(2, 2)\n \n # second conv layer: 10 inputs, 20 outputs, 3x3 conv\n ## output size = (W-F)/S +1 = (13-3)/1 +1 = 11\n # the output tensor will have dimensions: (20, 11, 11)\n # after another pool layer this becomes (20, 5, 5); 5.5 is rounded down\n self.conv2 = nn.Conv2d(10, 20, 3)\n self.conv2_bn = nn.BatchNorm2d(20)\n # 20 outputs * the 5*5 filtered/pooled map size\n self.fc1 = nn.Linear(20*5*5, 256)\n self.fc1_bn = nn.BatchNorm1d(256)\n # finally, create 1 output channel \n self.fc2 = nn.Linear(256, 128)\n self.fc2_bn = nn.BatchNorm1d(128)\n self.fc3 = nn.Linear(128, 64)\n self.fc3_bn = nn.BatchNorm1d(64)\n self.fc4 = nn.Linear(64, 32)\n self.fc4_bn = nn.BatchNorm1d(32)\n self.fc5 = nn.Linear(32,16)\n self.fc5_bn = nn.BatchNorm1d(16)\n self.fc6 = nn.Linear(16,8)\n self.fc7 = nn.Linear(8,1)\n \n \n # dropout with p=0.5\n self.fc_drop = nn.Dropout(p=0.5)\n \n # define the feedforward behavior\n def forward(self, x):\n # two conv/relu + pool layers\n x = x.float()\n x = F.relu(self.conv1(x))\n x = self.conv1_bn(x)\n x = F.relu(self.conv2(x))\n x = self.conv2_bn(x)\n x = self.pool(x)\n \n # prep for linear layer\n # flatten the inputs into a vector\n x = x.view(x.size(0), -1)\n \n # 4 linear layers with dropout in between\n x = F.relu(self.fc1(x))\n x = self.fc_drop(x)\n #x = self.fc1_bn(x)\n \n x = F.relu(self.fc2(x))\n #x = self.fc_drop(x)\n #x = self.fc2_bn(x)\n x = F.relu(self.fc3(x))\n\n #x = self.fc3_bn(x)\n x = F.relu(self.fc4(x))\n\n #x = self.fc4_bn(x)\n x = F.relu(self.fc5(x))\n\n #x = self.fc5_bn(x)\n x = F.relu(self.fc6(x))\n x = self.fc7(x)\n # final output\n\n return x\n\n \n# instantiate the Net\nnet = Net().float()\n\nimport torch.optim as optim\n# stochastic gradient descent with a small learning rate\nlearning_rate = 0.002\noptimizer = optim.Adam(net.parameters(), lr=learning_rate)\ncriterion = nn.MSELoss()\n\n# print it out!\nfrom pytorchtools import EarlyStopping\n\n''' Train the CNN'''\n'''\nBelow, we've defined a `train` function that takes in a number of epochs to train for. \n* The number of epochs is how many times a network will cycle through the entire training dataset. \n* Inside the epoch loop, we loop over the training dataset in batches; recording the loss every 50 batches.\n\nHere are the steps that this training function performs as it iterates over the training dataset:\n\n1. Zero's the gradients to prepare for a forward pass\n2. Passes the input through the network (forward pass)\n3. Computes the loss (how far is the predicted classes are from the correct labels)\n4. Propagates gradients back into the network’s parameters (backward pass)\n5. Updates the weights (parameter update)\n6. Prints out the calculated loss\n\n'''\n\ndef train_model(model, batch_size, patience, n_epochs):\n \n # to track the training loss as the model trains\n train_losses = []\n # to track the validation loss as the model trains\n valid_losses = []\n\n # to track the average training loss per epoch as the model trains\n avg_train_losses = []\n # to track the average validation loss per epoch as the model trains\n avg_valid_losses = [] \n \n # initialize the early_stopping object\n early_stopping = EarlyStopping(patience=patience, verbose=True)\n \n for epoch in range(1, n_epochs + 1):\n\n ###################\n # train the model #\n ###################\n model.train() # prep model for training\n for batch, data in enumerate(train_loader):\n inputs, labels = data\n # clear the gradients of all optimized variables\n optimizer.zero_grad()\n # forward pass: compute predicted outputs by passing inputs to the model\n outputs = model(inputs)\n # calculate the loss\n outputs = outputs.reshape(-1)\n loss = criterion(outputs, labels)\n # backward pass: compute gradient of the loss with respect to model parameters\n loss.backward()\n # perform a single optimization step (parameter update)\n optimizer.step()\n # record training loss\n train_losses.append(loss.item())\n\n ###################### \n # validate the model #\n ######################\n model.eval() # prep model for evaluation\n for inputs, labels in valid_loader:\n # forward pass: compute predicted outputs by passing inputs to the model\n outputs = model(inputs)\n # calculate the loss\n outputs = outputs.reshape(-1)\n loss = criterion(outputs, labels)\n # record validation loss\n valid_losses.append(loss.item())\n\n # print training/validation statistics \n # calculate average loss over an epoch\n train_loss = np.average(train_losses)\n valid_loss = np.average(valid_losses)\n avg_train_losses.append(train_loss)\n avg_valid_losses.append(valid_loss)\n \n epoch_len = len(str(n_epochs))\n \n print_msg = (\"epoch:{}/{} \\n\".format(epoch,n_epochs)+\n \"train_loss: {} \".format(train_loss)+\n \"valid_loss: {}\".format(valid_loss))\n \n print(print_msg)\n \n # clear lists to track next epoch\n train_losses = []\n valid_losses = []\n \n # early_stopping needs the validation loss to check if it has decresed, \n # and if it has, it will make a checkpoint of the current model\n '''\n early_stopping(valid_loss, model)\n \n if early_stopping.early_stop:\n print(\"Early stopping\")\n break\n \n # load the last checkpoint with the best model\n model.load_state_dict(torch.load('checkpoint.pt'))\n '''\n torch.save(model.state_dict(), 'checkpoint.pt')\n return(model, avg_train_losses, avg_valid_losses)\n\nbatch_size = 20\nn_epochs = 500\n\ntrain_loader, test_loader, valid_loader = create_datasets(batch_size,train_data,test_data)\n\n# early stopping patience; how long to wait after last time validation loss improved.\npatience = 200\n\nmodel, train_loss, valid_loss = train_model(net, batch_size, patience, n_epochs)\n\n\n\n","sub_path":"CNN_3channel.py","file_name":"CNN_3channel.py","file_ext":"py","file_size_in_byte":10376,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"400868494","text":"import json\nfrom django.http import HttpResponse, JsonResponse\nfrom django.shortcuts import render, redirect\nfrom django.contrib.auth import authenticate, login, logout\nfrom django.contrib.auth.models import User\nfrom django.contrib.auth.password_validation import validate_password\nfrom django.contrib.auth.decorators import login_required\nfrom django.core.exceptions import ValidationError\nfrom .forms import UserRegisterForm, UserAuthenticationForm\nfrom django.views.decorators.csrf import csrf_exempt\n\ndef login_view(request):\n form = UserAuthenticationForm(request.POST or None)\n if request.method == 'POST':\n try:\n username = request.POST['username']\n pw = request.POST['password']\n user = authenticate(request, username=username, password=pw)\n if user is not None:\n login(request, user)\n return redirect('Dashboard')\n else:\n form.error = True\n except:\n form.error = True\n return render(request, 'auth/login.html', {'form':form})\n\ndef logout_view(request):\n logout(request)\n return redirect('Signup')\n\ndef signup(request):\n if request.method == 'POST':\n form = UserRegisterForm(request.POST)\n if form.is_valid():\n user = form.save()\n login(request, user)\n return redirect('Dashboard')\n else:\n return render(request, 'auth/signup.html', {'form': form})\n else:\n if request.user.is_authenticated:\n return redirect('Dashboard')\n else:\n form = UserRegisterForm()\n return render(request, 'auth/signup.html', {'form': form})\n\n@login_required\ndef user_dashboard(request):\n return render(request, 'auth/dashboard.html')\n\n@csrf_exempt\ndef validate_username(request):\n if request.method == 'POST':\n #get the username from the request\n body_unicode = request.body.decode('utf-8')\n body = json.loads(body_unicode)\n username = body['username']\n #return does the username exist?\n if User.objects.filter(username=username).exists():\n return JsonResponse({'exists': 'true'}) \n else:\n return JsonResponse({'exists': 'false'})\n else:\n return redirect('Signup')\n\n@csrf_exempt\ndef validate_email(request):\n valid_types = ['POST', 'OPTIONS']\n if request.method in valid_types:\n body_unicode = request.body.decode('utf-8')\n body = json.loads(body_unicode)\n email = body['email']\n if User.objects.filter(email=email).exists():\n return JsonResponse({'exists': 'true'})\n else:\n return JsonResponse({'exists': 'false'})\n else:\n return redirect('Signup')\n\n@csrf_exempt\ndef validate_pw(request):\n if request.method == 'POST':\n body_unicode = request.body.decode('utf-8')\n body = json.loads(body_unicode)\n pw = body['pw']\n try:\n validate_password(pw)\n return JsonResponse({'invalid': 'false'})\n except ValidationError as e:\n return JsonResponse({'invalid': 'true'})\n else:\n return redirect('Signup')\n \n","sub_path":"auth_app/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3195,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"474457131","text":"from django.contrib import admin\nfrom django.urls import path\nfrom . import views\n\nurlpatterns = [\n path('admin/', admin.site.urls),\n path('lap',views.lap),\n path('lists',views.lists),\n path('edit/', views.edit), \n path('update/', views.update), \n path('delete/', views.destroy), \n]\n","sub_path":"MyCrudTry/CrudTry1/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":327,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"129055869","text":"from django.core.management import call_command\nfrom nose.tools import eq_\n\nfrom kitsune.questions.models import Question, QuestionMappingType\nfrom kitsune.questions.tests import QuestionFactory, QuestionVoteFactory, TestCaseBase\nfrom kitsune.search.tests.test_es import ElasticTestCase\n\n\nclass TestVotes(TestCaseBase):\n \"\"\"Test QuestionVote counting and cron job.\"\"\"\n\n def test_vote_updates_count(self):\n q = QuestionFactory()\n eq_(0, q.num_votes_past_week)\n\n QuestionVoteFactory(question=q, anonymous_id='abc123')\n\n q = Question.objects.get(id=q.id)\n eq_(1, q.num_votes_past_week)\n\n def test_cron_updates_counts(self):\n q = QuestionFactory()\n eq_(0, q.num_votes_past_week)\n\n QuestionVoteFactory(question=q, anonymous_id='abc123')\n\n q.num_votes_past_week = 0\n q.save()\n\n call_command('update_weekly_votes')\n\n q = Question.objects.get(pk=q.pk)\n eq_(1, q.num_votes_past_week)\n\n\nclass TestVotesWithElasticSearch(ElasticTestCase):\n def test_cron_updates_counts(self):\n q = QuestionFactory()\n self.refresh()\n\n eq_(q.num_votes_past_week, 0)\n # NB: Need to call .values_dict() here and later otherwise we\n # get a Question object which has data from the database and\n # not the index.\n document = (QuestionMappingType.search()\n .filter(id=q.id))[0]\n\n eq_(document['question_num_votes_past_week'], 0)\n\n QuestionVoteFactory(question=q, anonymous_id='abc123')\n q.num_votes_past_week = 0\n q.save()\n\n call_command('update_weekly_votes')\n self.refresh()\n\n q = Question.objects.get(pk=q.pk)\n eq_(1, q.num_votes_past_week)\n\n document = (QuestionMappingType.search()\n .filter(id=q.id))[0]\n\n eq_(document['question_num_votes_past_week'], 1)\n","sub_path":"kitsune/questions/tests/test_votes.py","file_name":"test_votes.py","file_ext":"py","file_size_in_byte":1885,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"207237575","text":"\"\"\"\n@title\n@description\n\"\"\"\nimport hashlib\nimport os\nimport time\nfrom collections import namedtuple\n\nimport pandas as pd\nfrom Andrutil.Misc import select_skip_generator\nfrom Andrutil.ObserverObservable import Observable\n\nfrom SystemControl import DATA_DIR\n\n\ndef build_entry_id(data_list):\n id_str = ''\n sep = ''\n for data_val in data_list:\n id_str += f'{sep}{data_val}'\n sep = ':'\n id_bytes = id_str.encode('utf-8')\n entry_hash = hashlib.sha3_256(id_bytes).hexdigest()\n return entry_hash\n\n\nTrialInfoEntry = namedtuple('TrialInfoEntry', 'entry_id source subject trial_type trial_name')\nTrialDataEntry = namedtuple('TrialDataEntry', 'entry_id idx timestamp label C3 Cz C4')\n\n\nclass DataSource(Observable):\n\n def __init__(self, log_level: str = 'WARNING', save_method: str = 'h5'):\n Observable.__init__(self)\n self._log_level = log_level\n self.save_method = save_method\n\n self.name = ''\n self.sample_freq = -1\n self.subject_names = []\n self.trial_types = []\n self.event_names = []\n self.ascended_being = ''\n self.selected_trial_type = ''\n\n self.trial_info_df = None\n self.trial_data_df = None\n\n self.coi = ['C3', 'Cz', 'C4']\n return\n\n def __iter__(self):\n trial_samples_list = self.get_trial_samples()\n for trial_samples in trial_samples_list:\n for index, sample in trial_samples.iterrows():\n yield sample\n return\n\n def __str__(self):\n return f'{self.name}'\n\n def __repr__(self):\n return self.__str__()\n\n @property\n def dataset_directory(self):\n return os.path.join(DATA_DIR, self.name)\n\n @property\n def trial_info_file(self):\n path = {\n 'csv': os.path.join(self.dataset_directory, f'trial_info.csv'),\n 'h5': os.path.join(self.dataset_directory, f'trial_info.h5')\n }\n return path\n\n @property\n def trial_data_file(self):\n path = {\n 'csv': os.path.join(self.dataset_directory, f'trial_data.csv'),\n 'h5': os.path.join(self.dataset_directory, f'trial_data.h5')\n }\n return path\n\n def downsample_generator(self, skip_amount: int = 2):\n base_iter = self.__iter__()\n downsampled = select_skip_generator(base_iter, select=1, skip=skip_amount - 1)\n for sample in downsampled:\n yield sample\n\n def window_generator(self, window_length: float, window_overlap: float):\n trial_samples_list = self.get_trial_samples()\n for trial_samples in trial_samples_list:\n start_time = trial_samples['timestamp'].min()\n last_time = trial_samples['timestamp'].max()\n\n window_start = start_time\n window_end = window_start + window_length\n window_offset = (1 - window_overlap) * window_length\n\n while window_end < last_time:\n next_window = trial_samples.loc[\n (trial_samples['timestamp'] >= window_start) &\n (trial_samples['timestamp'] <= window_end)\n ]\n window_start += window_offset\n window_end += window_offset\n yield next_window\n return\n\n def get_num_samples(self):\n total_count = 0\n subject_entry_list = self.get_trial_samples()\n for subject_entry in subject_entry_list:\n sample_list = subject_entry[\"samples\"]\n last_sample = sample_list[-1]\n last_sample_idx = last_sample[\"idx\"]\n total_count += last_sample_idx + 1\n return total_count\n\n def get_trial_samples(self) -> list:\n current_trials = self.trial_info_df.loc[\n (self.trial_info_df['subject'] == self.ascended_being) &\n (self.trial_info_df['trial_type'] == self.selected_trial_type)\n ]\n trial_samples = []\n for index, row in current_trials.iterrows():\n row_id = row['entry_id']\n id_samples = self.trial_data_df.loc[self.trial_data_df['entry_id'] == row_id]\n trial_samples.append(id_samples)\n return trial_samples\n\n def load_data(self):\n print('Loading dataset')\n if not os.path.isfile(self.trial_info_file['csv']) and not os.path.isfile(self.trial_info_file['h5']):\n print(f'Unable to locate trial info file:\\n'\n f'\\t{self.trial_info_file[\"csv\"]}\\n'\n f'\\t{self.trial_info_file[\"h5\"]}')\n self.trial_info_df = pd.DataFrame(columns=TrialInfoEntry._fields)\n self.trial_data_df = pd.DataFrame(columns=TrialDataEntry._fields)\n return\n if not os.path.isfile(self.trial_data_file['csv']) and not os.path.isfile(self.trial_data_file['h5']):\n print(f'Unable to locate trial data file:\\n'\n f'\\t{self.trial_data_file[\"csv\"]}\\n'\n f'\\t{self.trial_data_file[\"h5\"]}')\n self.trial_info_df = pd.DataFrame(columns=TrialInfoEntry._fields)\n self.trial_data_df = pd.DataFrame(columns=TrialDataEntry._fields)\n return\n\n time_start = time.time()\n if os.path.isfile(self.trial_info_file['h5']):\n print(f'Loading info file: {self.trial_info_file[\"h5\"]}')\n self.trial_info_df = pd.read_hdf(self.trial_info_file['h5'], key='physio_trial_info')\n elif os.path.isfile(self.trial_info_file['csv']):\n print(f'Loading info file: {self.trial_info_file[\"csv\"]}')\n self.trial_info_df = pd.read_csv(self.trial_info_file['csv'])\n\n if os.path.isfile(self.trial_data_file['h5']):\n print(f'Loading info file: {self.trial_data_file[\"h5\"]}')\n self.trial_data_df = pd.read_hdf(self.trial_data_file['h5'], key='physio_trial_data')\n elif os.path.isfile(self.trial_data_file['csv']):\n print(f'Loading info file: {self.trial_data_file[\"csv\"]}')\n self.trial_data_df = pd.read_csv(self.trial_data_file['csv'])\n time_end = time.time()\n print(f'Time to load info and data: {time_end - time_start:.4f} seconds')\n return\n\n def set_subject(self, subject: str):\n if subject not in self.subject_names:\n raise ValueError(f'Designated subject is not a valid subject: {subject}')\n\n self.ascended_being = subject\n return\n\n def set_trial_type(self, trial_type: str):\n if trial_type not in self.trial_types:\n raise ValueError(f'Designated trial is not a valid trial type: {trial_type}')\n\n self.selected_trial_type = trial_type\n return\n\n def save_data(self, start_time: float = 0.0, end_time: float = -1):\n if not os.path.isdir(self.dataset_directory):\n os.makedirs(self.dataset_directory)\n\n info_ids = pd.unique(self.trial_info_df['entry_id'])\n data_ids = pd.unique(self.trial_data_df['entry_id'])\n print(f'Saving {len(info_ids)} info trial ids using method: {self.save_method}')\n print(f'Saving {len(data_ids)} data trial ids using method: {self.save_method}')\n\n save_data_df = self.trial_data_df\n if start_time >= 0:\n save_data_df = save_data_df.loc[save_data_df['timestamp'] >= start_time]\n if end_time >= 0:\n save_data_df = save_data_df[save_data_df['timestamp'] <= end_time]\n\n time_start = time.time()\n ############################################################\n self.trial_info_df.to_hdf(self.trial_info_file['h5'], key='physio_trial_info')\n save_data_df.to_hdf(self.trial_data_file['h5'], key='physio_trial_data')\n ############################################################\n self.trial_info_df.to_csv(self.trial_info_file['csv'], index=False)\n save_data_df.to_csv(self.trial_data_file['csv'], index=False)\n ############################################################\n time_end = time.time()\n print(f'Time to save info and data: {time_end - time_start:.4f} seconds')\n return\n","sub_path":"SystemControl/DataSource/DataSource.py","file_name":"DataSource.py","file_ext":"py","file_size_in_byte":8035,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"86914522","text":"import pandas as pd\n\ndef loadInvestments(filename):\n investOptions = []\n metro = pd.read_csv(filename)\n for i in range(1,5):\n name = metro.iloc[i][1]\n price = metro.iloc[i][-1]\n dif = metro.iloc[i][-1] - metro.iloc[i][-13]\n investOptions.append( (name,price,dif))\n return investOptions\n\n#price in jan(option at 1) is our kg, dif(option at 2) is our profit\ndef optimizeInvestments(ops,money,inc):\n rows = (money//inc)+1\n cols = len(ops)+1\n mat = [[0 for i in range(rows)] for i in range(cols)]\n traceback = [[0 for i in range(rows)] for i in range(cols)]\n for i in range(cols):\n for j in range(rows):\n if i==0 or j==0:\n mat[i][j] = 0\n traceback[i][j] = None\n elif ops[i-1][1] <= j*inc:\n max = mat[i-1][j]\n val = ops[i-1][2]+mat[i-1][(j*inc-ops[i-1][1])//inc]\n if val > max:\n mat[i][j] = val\n if traceback[i-1][(j*inc-ops[i-1][1])//inc] != None:\n traceback[i][j] = ops[i-1][0] + ' and ' + traceback[i-1][(j*inc-ops[i-1][1])//inc]\n else:\n traceback[i][j] = ops[i-1][0]\n else:\n mat[i][j] = max\n if traceback[i-1][j] != None:\n traceback[i][j] = traceback[i-1][j] +' and '+ ops[i-1][0]\n else:\n traceback[i][j] = ops[i-1][0]\n\n\n else:\n mat[i][j] = mat[i-1][j]\n traceback[i][j] = traceback[i-1][j]\n\n res = (mat[cols-1][rows-1], traceback[cols-1][rows-1])\n return res\n\nprint(optimizeInvestments(loadInvestments('Metro.csv'),1000000,1000))\n","sub_path":"DynamicProgramming/DynamicProgramming.py","file_name":"DynamicProgramming.py","file_ext":"py","file_size_in_byte":1760,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"311676000","text":"\nclass Solution(object):\n def numTimesAllBlue(self, light):\n res = 0\n max_idx = 0\n for i,b in enumerate(light):\n max_idx = max(max_idx, b)\n if i + 1 == max_idx:\n res += 1\n return res\n\n\nlight =[2,1,3,5,4]\nres = Solution().numTimesAllBlue(light)\nprint(res)","sub_path":"array/1375_bulb_switcher_iii/1375_bulb_switcher_iii.py","file_name":"1375_bulb_switcher_iii.py","file_ext":"py","file_size_in_byte":322,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"69187652","text":"# --------------------------------------------------------\n# Fast R-CNN\n# Copyright (c) 2015 Microsoft\n# Licensed under The MIT License [see LICENSE for details]\n# Written by Ross Girshick\n# --------------------------------------------------------\n#from __future__ import absolute_import\nfrom .nms.gpu_nms import gpu_nms\nfrom .nms.cpu_nms import cpu_nms\n\ndef nms(dets, thresh, force_cpu=False):\n \"\"\"Dispatch to either CPU or GPU NMS implementations.\"\"\"\n\n if dets.shape[0] == 0:\n return []\n if not force_cpu:\n device_id = 0\n return gpu_nms(dets, thresh, device_id=device_id)\n else:\n return cpu_nms(dets, thresh)","sub_path":"lib/rbgirshick/nms/nms_wrapper.py","file_name":"nms_wrapper.py","file_ext":"py","file_size_in_byte":650,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"217167654","text":"# -*- coding: utf-8 -*-\nimport json\nimport csv\nimport os\nimport pymysql as db\nimport multiprocessing\n\n\nconfig_json = open('config.json')\nconfig = json.load(config_json)\n\nconn = db.connect(host=config['db']['host'], port=3306, user=config['db']['user'], passwd=config['db']['pass'],\n db=config['db']['name'], charset='utf8')\n\ncur = conn.cursor()\nqueryFile = './output/query.sql'\n\ndef doConversion(row):\n id = row[0]\n region = row[1]\n lastModified = row[2]\n fileHash = row[3];\n filePath = './data/' + fileHash + '.json'\n outputPath = u\"./output/%s_%s.csv\" % (region, id)\n\n fullPath = os.path.abspath(outputPath)\n mysqlFullPath = fullPath.replace('\\\\', '\\\\\\\\')\n\n jsonData = open(filePath).read()\n data = json.loads(jsonData)\n\n allianceAuctions = data['alliance']['auctions']\n hordeAuctions = data['horde']['auctions']\n\n with open(outputPath.encode('utf-8'), 'wb+') as outputFile:\n\n writer = csv.writer(outputFile, delimiter=',', quoting=csv.QUOTE_NONNUMERIC)\n\n for auction in allianceAuctions:\n try:\n petSpeciesId = auction['petSpeciesId']\n petBreedId = auction['petBreedId']\n petLevel = auction['petLevel']\n petQualityId = auction['petQualityId']\n except KeyError:\n auction['petSpeciesId'] = '0'\n auction['petBreedId'] = '0'\n auction['petLevel'] = '0'\n auction['petQualityId'] = '0'\n writer.writerow([auction['auc'],\n '1', auction['item'],\n auction['owner'].encode('utf8'),\n auction['ownerRealm'].encode('utf8'),\n auction['bid'], auction['buyout'],\n auction['quantity'],\n auction['timeLeft'].encode('utf8'),\n auction['rand'], auction['seed'],\n auction['petSpeciesId'],\n auction['petBreedId'],\n auction['petLevel'],\n auction['petQualityId']])\n for auction in hordeAuctions:\n try:\n petSpeciesId = auction['petSpeciesId']\n petBreedId = auction['petBreedId']\n petLevel = auction['petLevel']\n petQualityId = auction['petQualityId']\n except KeyError:\n auction['petSpeciesId'] = '0'\n auction['petBreedId'] = '0'\n auction['petLevel'] = '0'\n auction['petQualityId'] = '0'\n writer.writerow([auction['auc'],\n '2', auction['item'],\n auction['owner'].encode('utf8'),\n auction['ownerRealm'].encode('utf8'),\n auction['bid'], auction['buyout'],\n auction['quantity'],\n auction['timeLeft'].encode('utf8'),\n auction['rand'], auction['seed'],\n auction['petSpeciesId'],\n auction['petBreedId'],\n auction['petLevel'],\n auction['petQualityId']])\n loadDataStr = \"CREATE TABLE `realm_{0}_data_tmp` LIKE realm_{1}_data;\\n\" \\\n \"LOAD DATA INFILE '{2}'\" \\\n \" INTO TABLE `realm_{3}_data_tmp`\" \\\n \" FIELDS TERMINATED BY ',' ENCLOSED BY '\\\"';\\n\" \\\n \"RENAME TABLE `realm_{4}_data` TO `realm_{5}_data_old`, `realm_{6}_data_tmp` TO `realm_{7}_data`;\\n\" \\\n \"DROP TABLE `realm_{8}_data_old`;\\n\".format(id,id,mysqlFullPath,id,id,id,id,id,id)\n\n with open(queryFile, 'a+') as f:\n f.write(loadDataStr.encode('utf-8'))\n f.close()\n print(\"Successfully converted Realm #\" + str(id) + \"-\" + region.upper() + \" data...\")\n\ndef convertData():\n # Set a global variable with the region so we can use it in other functions\n global region\n region = \"\"\n print(\"Beginning conversion of \" + region.upper() + \" data...\")\n cur.execute(\"SELECT id, region, last_modified, latest_hash \" \\\n \"FROM realms_lastmodified \" \\\n \"WHERE latest_hash IS NOT NULL \" \\\n \"ORDER BY id ASC\")\n\n result = cur.fetchall()\n\n pool = multiprocessing.Pool(2)\n pool.map(doConversion, result)\n\n print(\"Successfully converted \" + str(cur.rowcount) + \" files for \" + region.upper() + \" region.\")\n print\n pool.terminate()\n pool = None","sub_path":"convert.py","file_name":"convert.py","file_ext":"py","file_size_in_byte":4661,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"588470483","text":"#Code to find frequent short DNA fragments in genomes\n#in search of DnaA-boxes in bacteria\n#applied to the Salmonella enterica genome\n#as part of Bioinformatic algorithms course\n\nimport matplotlib.pyplot as plt\n\n#find the G:C skew along a DNA string\n#output is a list\ndef skew_along(dna):\n count = 0\n out = [0]\n for t in dna:\n if t == 'C': \n count = count - 1\n if t == 'G':\n count = count + 1\n out.append(count)\n return out\n \n#find the position(s) where the G:C skew is at its minimum\n#output is a string with spaces\ndef min_skew(dna):\n skew = skew_along(dna)\n m = min(skew)\n out = []\n for i in range(len(skew)):\n if skew[i] == m: out.append(i)\n return(' '.join(str(x) for x in out))\n \n#calculates the number of nucleotides between two DNA strings\n#output is an integer\ndef Hamming_distance(p,q):\n hd = 0\n for i in range(len(p)):\n if p[i] != q[i]: hd += 1\n return hd\n \n#finds the number of times a DNA word and its neighbors occur in a DNA string\n#a neighbor deviates max d nucleotides from the DNA word\n#output is an integer\ndef pattern_matching(text, pattern, d):\n #d is the max number of mismatches\n positions = []\n for i in range(len(text) - len(pattern)+1):\n if Hamming_distance(text[i:i+len(pattern)], pattern) <= d:\n positions.append(str(i))\n return(len(positions))\n #return (' '.join(positions))\n \n#produces a list of DNA strings that deviate max d nucleotides from input DNA string\n#RECURSIVE\n#output is a list\ndef neighbors(pattern,d):\n if d == 0: return pattern\n if len(pattern) == 1: return ['A','C','G','T']\n neighborhood = []\n suffix_neighbors = neighbors(pattern[1:],d)\n for t in suffix_neighbors:\n if Hamming_distance(pattern[1:],t) < d:\n for n in ['A','C','G','T']:\n neighborhood.append(n + t)\n else: neighborhood.append(pattern[0] + t)\n return neighborhood\n \n#algorithm to turn a DNA string into a number RECURSIVE\n#output is a number\ndef pattern_to_number(pattern):\n if pattern == '':\n return(0)\n symbol = pattern[-1]\n prefix = pattern[0:-1]\n return(4*pattern_to_number(prefix)+symbol_to_number(symbol))\n \n#algorithm to turn a nucleotide into a number <4\n#output is an integer\ndef symbol_to_number(letter):\n letters = {'A':0,'C':1,'G':2,'T':3}\n return letters[letter]\n\n#turns a number <4 into a nucleotide\n#returns a single letter string\ndef number_to_symbol(r):\n letters = {0:'A',1:'C',2:'G',3:'T'}\n return letters[r]\n\n#algorithm to turn number into a DNA string RECURSIVE\n#output is a string \ndef number_to_pattern(index,k):\n if k == 1:\n return number_to_symbol(index)\n remainder = index%4\n prefix_index = (index - remainder)/4\n symbol = number_to_symbol(remainder)\n prefix_pattern = number_to_pattern(prefix_index,k-1)\n return (prefix_pattern + symbol)\n \n#returns reverse complement of a DNA string\n#output is a string\ndef rc(string):\n base_complement = {'A':'T','T':'A','G':'C','C':'G'}\n string_rc = ''\n for i in range(len(string)):\n string_rc = string_rc + base_complement[string[i]]\n return(string_rc[::-1])\n \n#algorithm to find frequent k-mer words in DNA with max d mismatches\n#output is a string with spaces\ndef frequent_words_with_mismatches(text, k, d):\n frequent_patterns = []\n close = []\n frequency_array = []\n for i in range(pow(4,k)):\n close.append(0)\n frequency_array.append(0)\n for i in range(len(text)-k+1):\n neighborhood = neighbors(text[i:i+k],d)\n for t in neighborhood:\n index = pattern_to_number(t)\n close[index] = 1\n for i in range(pow(4,k)):\n if close[i] == 1:\n pattern = number_to_pattern(i,k)\n frequency_array[i] = pattern_matching(text,pattern,d)\n maxCount = max(frequency_array)\n for i in range(pow(4,k)):\n if frequency_array[i] == maxCount:\n pattern = number_to_pattern(i,k)\n frequent_patterns.append(pattern)\n return ' '.join(frequent_patterns)\n \n#algorithm to find frequent k-mer words in DNA with max d mismatches\n#also reverse complement of k-mer is searches for\n#output is a string with spaces\ndef frequent_words_with_mismatches_and_rc(text, k, d):\n frequent_patterns = []\n close = []\n frequency_array = []\n for i in range(pow(4,k)):\n close.append(0)\n frequency_array.append(0)\n for i in range(len(text)-k+1):\n neighborhood = neighbors(text[i:i+k],d)\n #neighborhood.extend(neighbors(rc(text[i:i+k]),d))\n for t in neighborhood:\n index = pattern_to_number(t)\n close[index] = 1\n for i in range(pow(4,k)):\n if close[i] == 1:\n pattern = number_to_pattern(i,k)\n frequency_array[i] = pattern_matching(text,pattern,d) + pattern_matching(text,rc(pattern),d)\n maxCount = max(frequency_array)\n for i in range(pow(4,k)):\n if frequency_array[i] == maxCount:\n pattern = number_to_pattern(i,k)\n frequent_patterns.append(pattern)\n return ' '.join(frequent_patterns)\n\n#faster algorithm to find frequent k-mer words in DNA with max d mismatches\n#output is a list of words\ndef frequent_words_with_mismatches_by_sorting(text, k, d):\n frequent_patterns = []\n neighborhoods = []\n index = []\n count = []\n for i in range(len(text)-k+1):\n neighborhoods.extend(neighbors(text[i:i+k],d))\n #neighborhoods_set = list(set(neighborhoods))\n for i in range(len(neighborhoods)):\n pattern = neighborhoods[i]\n index.append(pattern_to_number(pattern))\n count.append(1)\n index.sort()\n for i in range(len(neighborhoods)-1):\n if index[i] == index[i+1]:\n count[i+1] = count[i] + 1\n max_count = max(count)\n for i in range(len(neighborhoods)):\n if count[i] == max_count:\n pattern = number_to_pattern(index[i],k)\n frequent_patterns.append(pattern)\n return frequent_patterns\n\n#read the genome from text file into a single long string\nSenterica_genome = ''\nwith open('Salmonella_enterica.txt') as f:\n data = f.readlines()[1:]\nf.close()\nfor l in data:\n Senterica_genome = Senterica_genome + l.strip('\\n')\nprint(len(Senterica_genome)) #total genome length\n\n#plot the G:C skew along the genome\ny = skew_along(Senterica_genome)\nx = []\nfor i in range(len(y)):\n x.append(i)\nplt.scatter(x,y)\nplt.show()\nprint(min_skew(Senterica_genome)) #find the minimum\n#answer: 3764856 3764858\n\n#find frequent 9-mers in the 1000 bp region around the G:C minimum\nsuspect_region = Senterica_genome[(3764856-500):(3764858+500)]\nprint(frequent_words_with_mismatches_by_sorting(suspect_region,9,1))\n#answer: ['TCCAAATAA', 'TGAAAATCA', 'TTATCCACA']\n\n#find the positions of TTATCCACA along the genome\nanswer = []\nfor i in range(len(Senterica_genome)-9+1):\n if Senterica_genome[i:i+9] == 'TTATCCACA':\n answer.append(i)\nprint(answer)\nprint(len(answer)) #how many times is it in the genome?\n#answer: 24\n\n#plot the occurrences of the reverse complement of TTATCCACA along the genome\nanswer2 = []\nfor i in range(len(Senterica_genome)-9+1):\n if Senterica_genome[i:i+9] == rc('TTATCCACA'):\n answer2.append(i)\nprint(answer2)\nprint(len(answer2))\nplt.scatter(answer2,range(len(answer2)))\nplt.show()","sub_path":"CH01_frequent_DNA_fragments.py","file_name":"CH01_frequent_DNA_fragments.py","file_ext":"py","file_size_in_byte":7373,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"555880784","text":"import select\nfrom subprocess import Popen, PIPE\nfrom steve import format_exc\n\nblock_size = 4096\n\ndef commanderx (command, cwd, env, timeout, callback, cbdata):\n callback(cbdata, \"init\")\n try:\n with Popen(command, cwd=cwd, env=env,\n stdin=PIPE, stdout=PIPE, stderr=PIPE,\n bufsize=0, shell=False) as p:\n callback(cbdata, \"start\", p.pid)\n streams = {\n p.stdout: \"stdout\",\n p.stderr: \"stderr\",\n }\n p.stdin.close()\n callback(cbdata, \"stdin\", b\"\")\n while streams:\n rlist = select.select(list(streams.keys()),[],[],timeout)[0]\n if not rlist:\n callback(cbdata, \"timeout\")\n continue\n for stream in rlist:\n event_name = streams[stream]\n block = stream.read(block_size)\n if not block:\n del streams[stream]\n stream.close()\n callback(cbdata, event_name, block)\n callback(cbdata, \"finish\")\n code = p.returncode\n except Exception:\n callback(cbdata, \"unexpected\", format_exc())\n code = None\n callback(cbdata, \"done\", code)\n","sub_path":"lib/commanderx.py","file_name":"commanderx.py","file_ext":"py","file_size_in_byte":1296,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"490725251","text":"import sys, os, timeit\nsys.path.append(os.getcwd())\nfrom util.intcode import IntCode\n\ndef main():\n with open(\"dec9/input.txt\", \"r\") as file:\n memory = list(map(int, file.read().split(\",\")))\n\n ic = IntCode(memory, inp=[2])\n ic.start()\n return ic.out[0]\n\nprint(main())\nprint(timeit.timeit(main, number=1))\n","sub_path":"dec9/puzzle2.py","file_name":"puzzle2.py","file_ext":"py","file_size_in_byte":323,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"109045601","text":"from treelib import Tree\nimport time\n#\n# def duplicate_node_path_check(tree, node):\n# check_node = tree.get_node(node)\n# current_node = check_node\n#\n#\n# while not current_node.is_root():\n# current_node = tree.parent(current_node.identifier)\n# if check_node.tag == current_node.tag:\n# return True\n# return False\ndef dupilcate_node_path_check(tree,node,tag):\n\n current_node = node\n\n\n while not current_node.is_root():\n current_node = tree.parent(current_node.identifier)\n if current_node.tag == tag:\n #print(\"z funkcji node.tag\",node.tag)\n return True\n return False\n\ndef reachable_states(state):\n if state == \"Gdansk\":\n return [[\"Gdynia\",24],[\"Koscierzyna\",58],[\"Tczew\",33],[\"Elblag\",63]]\n\n if state == \"Gdynia\":\n return [[\"Gdansk\",24],[\"Lebork\",60],[\"Wladyslawowo\",33]]\n\n if state == \"Koscierzyna\":\n return [[\"Chojnice\", 70], [\"Bytów\", 40], [\"Lebork\", 58], [\"Gdansk\", 58], [\"Tczew\", 59]]\n\n if state == \"Tczew\":\n return [[\"Elblag\", 53], [\"Gdansk\", 33], [\"Koscierzyna\", 59]]\n\n if state == \"Elblag\":\n return [[\"Tczew\", 53], [\"Gdansk\", 63]]\n\n if state == \"Hel\":\n return [[\"Wladyslawowo\", 35]]\n\n if state == \"Wladyslawowo\":\n return [[\"Gdynia\", 42], [\"Leba\", 63]]\n\n if state == \"Leba\":\n return [[\"Ustka\", 64], [\"Lebork\", 29], [\"Wladyslawowo\", 66]]\n\n if state == \"Lebork\":\n return [[\"Leba\", 29], [\"Slupsk\", 55], [\"Koscierzyna\", 58], [\"Gdynia\", 60]]\n\n if state == \"Ustka\":\n return [[\"Slupsk\", 21], [\"Gdansk\", 64]]\n\n if state == \"Slupsk\":\n return [[\"Ustka\", 21], [\"Lebork\", 55], [\"Bytow\", 70]]\n\n if state == \"Bytow\":\n return [[\"Chojnice\", 65], [\"Koscierzyna\", 40], [\"Slupsk\", 70]]\n\n if state == \"Chojnice\":\n return [[\"Bytow\", 65], [\"Koscierzyna\", 70]]\n return []\n\n\n\ndef uniform_cost_search(start_state,target_state):\n#do budowy drzewa potrzebujemy dla kazdego wierzcholka id\n#bedziemy je pozniej inkrementowac\n\n id = 0\n\n #wrzucenie stanu startowego do drzewa (korzen) i kolejki\n\n tree = Tree()\n current_node = tree.create_node(start_state,id,data = 0)\n fifo_queue = []\n fifo_queue.append(current_node)\n\n\n #petla szukajaca sciezki do stnau koncowego\n #robimy ograniczenie na max wierzcholkow (id<200000)\n\n while id<200000:\n #jesli kolejka pusta to znaczy ze nie da sie dojsc do stanu koncowego\n #drukowanie kolejki: print(fifo_queue)\n if len(fifo_queue) == 0:\n tree.show()\n print(\"failed to reach the target state\")\n return 1\n\n #jesli kolejka niepusta to wez pierwszy stan z kolejki\n fifo_queue = sorted(fifo_queue, key=lambda x: x.data)\n current_node = fifo_queue[0]\n #jesli ten stan jest koncowy to zakoncz program z sukcesem\n if current_node.tag == target_state:\n tree.show()\n print(\"the target state \"+str(current_node.tag)+\" with id =\"+str(current_node.identifier)+\" has been reached after \"+str(current_node.data)+\" kms!\")\n return 0\n\n #jesli stan niekoncowy to usun go z kolejki\n del(fifo_queue[0])\n #a nastepnie dodaj stany osiagalne z niego\n #na koniec kolejki i do drzewa\n\n for elem in reachable_states(current_node.tag):\n if dupilcate_node_path_check(tree,current_node,elem[0]) == False:\n id += 1\n new_elem = tree.create_node(elem[0], id, parent=current_node.identifier)\n new_elem.data = current_node.data + elem[1]\n fifo_queue.append(new_elem)\n print(\"time limit exceeded\")\n\n\n#print(breadth_first_search(\"Tczew\",\"Gdansk\"))\n\nstart = time.time()\nuniform_cost_search(\"Gdansk\",\"Ustka\")\nend = time.time()\nprint(end - start)\n\n# IF\n# the target state Gdynia with id = 6 has been reached!\n# 0.0006566047668457031\n# Switch\n","sub_path":"python zajecia AI/zaj2/zad4.py","file_name":"zad4.py","file_ext":"py","file_size_in_byte":3907,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"376817456","text":"import typing\nimport math\n\nclass LossyCountTriple(object):\n def __init__(self, item, estimated_frequency:float, max_error:float):\n self.item = item\n self.estimated_frequency = estimated_frequency\n self.max_error = max_error\n\n def increment(self):\n self.estimated_frequency += 1\n\n def can_purge(self,threshold):\n return (self.estimated_frequency + self.max_error <= threshold)\n\n\nclass LossyCounter(object):\n def __init__(self, epsilon):\n self.epsilon = epsilon\n self.width = math.ceil(1 / math.floor(epsilon))\n self._n = 0\n self._bucket_generation = 1\n self._triples = {}\n\n def purge(self):\n if self._n % self.width:\n purgeable = []\n\n #Need to check if I can delete while enumerating\n for k, triple in self._triples.values():\n if triple.can_purge():\n purgeable.append(k)\n for p in purgeable:\n del self._triples[p]\n\n def observe(self, item):\n self._n +=1\n if item in self.triples:\n self._triples[item].increment()\n else:\n self._triples[item] = LossyCountTriple(item, 1, self._bucket_generation - 1,)\n\n def freqeunt(self, support):\n threshold = (support - self.epsilon) * self._n\n\n result = []\n for triple in self._triples:\n if triple.estimated_frequency >= threshold:\n result.append(triple)\n\n return result\n\n\n\n","sub_path":"counting/lossy_counter.py","file_name":"lossy_counter.py","file_ext":"py","file_size_in_byte":1496,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"627784600","text":"from tkinter import *\r\nimport time\r\nfrom contents.keeper import *\r\nclass Player_def:\r\n def __init__(self,canvas,team,num,ball):\r\n self.canvas=canvas\r\n self.ball=ball\r\n self.num=num\r\n self.team=team\r\n self.canvas_height=self.canvas.winfo_height()\r\n self.canvas_width=self.canvas.winfo_width()\r\n self.c=0\r\n self.c2=0\r\n self.c_turn=0\r\n self.offence=1\r\n self.b_hold=0\r\n self.movestart=False\r\n self.current_image=0\r\n self.next_image=0\r\n self.current_image1=2\r\n self.next_image1=2\r\n \r\n self.last_time=time.time()\r\n\r\n self.images_t=[\r\n PhotoImage(file=\"gif/t_player1.gif\"),\r\n PhotoImage(file=\"gif/t_player2.gif\"),\r\n PhotoImage(file=\"gif/t_player3.gif\"),\r\n PhotoImage(file=\"gif/t_player4.gif\")\r\n ]\r\n self.images_f=[\r\n PhotoImage(file=\"gif/f_player1.gif\"),\r\n PhotoImage(file=\"gif/f_player2.gif\"),\r\n PhotoImage(file=\"gif/f_player3.gif\"),\r\n PhotoImage(file=\"gif/f_player4.gif\")\r\n ]\r\n \r\n if team==True:\r\n #color='blue'\r\n each_image=self.images_t[0]\r\n x=300\r\n if num==self.b_hold:\r\n self.x=0\r\n self.y=0\r\n else:\r\n self.x=0\r\n self.y=0\r\n self.movestart=True\r\n else:\r\n each_image=self.images_f[0]\r\n x=1130\r\n self_y=[6,-6]\r\n self.y=self_y[num]\r\n #color='red'\r\n self.x=0\r\n starts_y=[200,600]\r\n self.image=canvas.create_image(x,starts_y[num],\\\r\n image=each_image,anchor='nw')\r\n pos_p=self.coords()\r\n \r\n def coords(self):\r\n xy=self.canvas.coords(self.image)\r\n pos_p=[]\r\n pos_p.append(xy[0])\r\n pos_p.append(xy[1])\r\n pos_p.append(xy[0]+100)\r\n pos_p.append(xy[1]+111)\r\n return pos_p\r\n\r\n def judge_hit(self,pos): #当たり判定\r\n pos_b=self.canvas.coords(self.ball.id)\r\n if pos_b[2]>=pos[0] and pos_b[0]<=pos[2]:\r\n if pos_b[3]>=pos[1] and pos_b[3] <= pos[3]:\r\n return True\r\n return False\r\n\r\n def calc_move_x(self,pos):\r\n self.expect_x=(pos[0]+pos[2])/2+self.x*(self.c_turn-10)\r\n return self.expect_x\r\n\r\n def calc_move_y(self,pos):\r\n self.expect_y=(pos[1]+pos[3])/2+self.y*(self.c_turn-10)\r\n return self.expect_y\r\n \r\n def move_ball_x(self,pos):\r\n pos_b=self.canvas.coords(self.ball.id)\r\n self.ball.x=(self.calc_move_x(pos)-((pos_b[0]+pos_b[2])/2))/(self.c_turn-10)\r\n return self.ball.x\r\n\r\n def move_ball_y(self,pos):\r\n pos_b=self.canvas.coords(self.ball.id)\r\n self.ball.y=(self.calc_move_y(pos)-((pos_b[1]+pos_b[3])/2))/(self.c_turn-10)\r\n return self.ball.y\r\n\r\n def move_ball_xd(self):\r\n self.ball.x=self.x\r\n return self.ball.x\r\n\r\n def move_ball_yd(self):\r\n self.ball.y=self.y\r\n return self.ball.y\r\n \r\n def shoot_ball_x(self,team):\r\n pos_b=self.canvas.coords(self.ball.id)\r\n if team:\r\n self.ball.x=(1475-(pos_b[0]+pos_b[2])/2)/10\r\n else:\r\n self.ball.x=(25-(pos_b[0]+pos_b[2])/2)/10\r\n return self.ball.x\r\n\r\n def shoot_ball_y(self):\r\n pos_b=self.canvas.coords(self.ball.id)\r\n self.ball.y=(450-(pos_b[1]+pos_b[3])/2)/10\r\n return self.ball.y\r\n\r\n def keeper_ball_x(self,pos,team):\r\n if not team:\r\n self.ball.x=((pos[0]+pos[2])/2-1475)/10\r\n else:\r\n self.ball.x=((pos[0]+pos[2])/2-25)/10\r\n return self.ball.x\r\n\r\n def keeper_ball_y(self,pos):\r\n self.ball.y=((pos[1]+pos[3])/2-450)/10+self.y\r\n return self.ball.y\r\n\r\n def def_y(self,pos_p,sx):\r\n if pos_p[1]>sx:\r\n self.y=-(abs((pos_p[1]+pos_p[3])/2-sx)/100)\r\n else:\r\n self.y=abs((pos_p[1]+pos_p[3])/2-sx)/100\r\n\r\n def bounce(self,pos):\r\n if pos[1]<=0:\r\n self.y=6\r\n if pos[3]>=self.canvas_height: \r\n self.y=-6\r\n if pos[0]<=0:\r\n self.x=6\r\n if pos[2]>=self.canvas_width:\r\n self.x=-6\r\n\r\n def animate(self,team,con):\r\n if time.time()-self.last_time>0.1:\r\n self.last_time=time.time()\r\n self.current_image=self.next_image\r\n if self.current_image==0:\r\n self.next_image=1\r\n elif self.current_image==1:\r\n self.next_image=0\r\n\r\n\r\n if team==True:\r\n if con==True:\r\n self.canvas.itemconfig(self.image,\\\r\n image=self.images_t[self.next_image])\r\n else:\r\n self.current_image1=self.next_image1\r\n if self.current_image1==2:\r\n self.next_image1=3\r\n elif self.current_image1==3:\r\n self.next_image1=2\r\n self.canvas.itemconfig(self.image,\\\r\n image=self.images_t[self.next_image1])\r\n \r\n else:\r\n if con==True:\r\n self.canvas.itemconfig(self.image,\\\r\n image=self.images_f[self.next_image])\r\n else:\r\n self.current_image1=self.next_image1\r\n if self.current_image1==2:\r\n self.next_image1=3\r\n elif self.current_image1==3:\r\n self.next_image1=2\r\n self.canvas.itemconfig(self.image,\\\r\n image=self.images_f[self.next_image1])\r\n\r\n\r\n\r\n\r\n","sub_path":"contents/player_def.py","file_name":"player_def.py","file_ext":"py","file_size_in_byte":5572,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"644667190","text":"__author__ = 'ayaseen'\n\nfrom distutils.core import setup\n\nsetup(\n name= 'nestModule',\n version='1.3.0',\n py_modules=['nestModule'],\n author='ayaseen',\n author_email='amjad.a.yaseen@gmail.com',\n description='A simple nester module of nested lists',\n)\n","sub_path":"chapter2/setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":268,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"53880921","text":"from datetime import datetime\nfrom flask import abort, Flask, request, redirect, render_template, Response, send_file\nfrom flask_cors import CORS, cross_origin\nimport pandas as pd\nimport os\n\nimport prometheus_client\nfrom prometheus_flask_exporter import PrometheusMetrics\nimport sqlite3 as sql\nimport urllib.request\nimport json\nimport jsonschema\nimport uuid\nimport zipfile\nimport io\n\nfrom InowasFlopyAdapter.ReadBudget import ReadBudget\nfrom InowasFlopyAdapter.ReadConcentration import ReadConcentration\nfrom InowasFlopyAdapter.ReadDrawdown import ReadDrawdown\nfrom InowasFlopyAdapter.ReadHead import ReadHead\n\nDB_LOCATION = '/db/modflow.db'\nMODFLOW_FOLDER = '/modflow'\nUPLOAD_FOLDER = './uploads'\nSCHEMA_SERVER_URL = 'https://schema.inowas.com'\n\napp = Flask(__name__)\nCORS(app)\nmetrics = PrometheusMetrics(app)\n\ng_0 = prometheus_client.Gauge('number_of_calculated_models_0', 'Calculations in queue')\ng_100 = prometheus_client.Gauge('number_of_calculated_models_100', 'Calculations in progress')\ng_200 = prometheus_client.Gauge('number_of_calculated_models_200', 'Calculations finished with success')\ng_400 = prometheus_client.Gauge('number_of_calculated_models_400', 'Calculations finished with error')\n\n\ndef db_init():\n conn = db_connect()\n\n sql_command = \"\"\"\n CREATE TABLE IF NOT EXISTS calculations (\n id INTEGER PRIMARY KEY AUTOINCREMENT, \n calculation_id STRING, \n state INTEGER, \n message TEXT, \n created_at DATE, \n updated_at DATE\n )\n \"\"\"\n conn.execute(sql_command)\n\n\ndef db_connect():\n return sql.connect(DB_LOCATION)\n\n\n# noinspection SqlResolve\ndef get_calculation_by_id(calculation_id):\n conn = db_connect()\n conn.row_factory = sql.Row\n cursor = conn.cursor()\n\n cursor.execute(\n 'SELECT calculation_id, state, message FROM calculations WHERE calculation_id = ?', (calculation_id,)\n )\n return cursor.fetchone()\n\n\ndef get_number_of_calculations(state=200):\n conn = db_connect()\n cursor = conn.cursor()\n\n cursor.execute(\n 'SELECT Count() FROM calculations WHERE state = ?', (state,)\n )\n\n return cursor.fetchone()[0]\n\n\ndef get_calculation_details_json(calculation_id, data, path):\n calculation = get_calculation_by_id(calculation_id)\n heads = ReadHead(path)\n budget_times = ReadBudget(path).read_times()\n concentration_times = ReadConcentration(path).read_times()\n drawdown_times = ReadDrawdown(path).read_times()\n\n total_times = [float(totim) for totim in heads.read_times()]\n\n times = {\n 'start_date_time': data['dis']['start_datetime'],\n 'time_unit': data['dis']['itmuni'],\n 'total_times': total_times\n }\n\n layer_values = []\n number_of_layers = data['dis']['nlay']\n\n lv = ['head']\n if len(budget_times) > 0:\n lv.append('budget')\n\n if len(concentration_times) > 0:\n lv.append('concentration')\n\n if len(drawdown_times) > 0:\n lv.append('drawdown')\n\n for i in range(0, number_of_layers):\n layer_values.append(lv)\n\n target_directory = os.path.join(app.config['MODFLOW_FOLDER'], calculation_id)\n\n return json.dumps({\n 'calculation_id': calculation_id,\n 'state': calculation['state'],\n 'message': calculation['message'],\n 'files': os.listdir(target_directory),\n 'times': times,\n 'layer_values': layer_values\n })\n\n\ndef valid_json_file(file):\n with open(file) as filedata:\n try:\n json.loads(filedata.read())\n except ValueError:\n return False\n return True\n\n\ndef read_json(file):\n with open(file) as filedata:\n data = json.loads(filedata.read())\n return data\n\n\ndef is_valid(content):\n try:\n data = content.get('data')\n mf = data.get('mf')\n mt = data.get('mt')\n except AttributeError:\n return False\n\n try:\n mf_schema_data = urllib.request.urlopen('{}/modflow/packages/mfPackages.json'.format(SCHEMA_SERVER_URL))\n mf_schema = json.loads(mf_schema_data.read())\n jsonschema.validate(instance=mf, schema=mf_schema)\n except jsonschema.exceptions.ValidationError:\n return False\n\n if mt:\n try:\n mt_schema_data = urllib.request.urlopen('{}/modflow/packages/mtPackages.json'.format(SCHEMA_SERVER_URL))\n mt_schema = json.loads(mt_schema_data.read())\n jsonschema.validate(instance=mt, schema=mt_schema)\n except jsonschema.exceptions.ValidationError:\n return False\n\n return True\n\n\n# noinspection SqlResolve\ndef insert_new_calculation(calculation_id):\n with db_connect() as con:\n cur = con.cursor()\n cur.execute('INSERT INTO calculations (calculation_id, state, created_at, updated_at) VALUES ( ?, ?, ?, ?)',\n (calculation_id, 0, datetime.now(), datetime.now()))\n\n\ndef is_binary(filename):\n \"\"\"\n Return true if the given filename appears to be binary.\n File is considered to be binary if it contains a NULL byte.\n FIXME: This approach incorrectly reports UTF-16 as binary.\n \"\"\"\n with open(filename, 'rb') as f:\n for block in f:\n if b'\\0' in block:\n return True\n return False\n\n\n@app.route('/', methods=['GET', 'POST'])\n@cross_origin()\ndef upload_file():\n if request.method == 'POST':\n\n if 'multipart/form-data' in request.content_type:\n # check if the post request has the file part\n if 'file' not in request.files:\n abort(415, 'No file uploaded')\n\n uploaded_file = request.files['file']\n if uploaded_file.filename == '':\n abort(415, 'No selected file')\n\n temp_filename = str(uuid.uuid4()) + '.json'\n temp_file = os.path.join(app.config['UPLOAD_FOLDER'], temp_filename)\n uploaded_file.save(temp_file)\n\n content = read_json(temp_file)\n\n if not is_valid(content):\n os.remove(temp_file)\n abort(422, 'This JSON file does not match with the MODFLOW JSON Schema')\n\n calculation_id = content.get(\"calculation_id\")\n target_directory = os.path.join(app.config['MODFLOW_FOLDER'], calculation_id)\n modflow_file = os.path.join(target_directory, 'configuration.json')\n\n if os.path.exists(modflow_file):\n abort(422, 'Model with calculationId: {} already exits.'.format(calculation_id))\n\n os.makedirs(target_directory)\n with open(modflow_file, 'w') as outfile:\n json.dump(content, outfile)\n\n insert_new_calculation(calculation_id)\n\n return redirect('/' + calculation_id)\n\n if 'application/json' in request.content_type:\n content = request.get_json(force=True)\n\n if not is_valid(content):\n abort(422, 'Content is not valid.')\n\n calculation_id = content.get('calculation_id')\n target_directory = os.path.join(app.config['MODFLOW_FOLDER'], calculation_id)\n modflow_file = os.path.join(target_directory, 'configuration.json')\n\n if not os.path.exists(modflow_file):\n os.makedirs(target_directory)\n with open(modflow_file, 'w') as outfile:\n json.dump(content, outfile)\n\n insert_new_calculation(calculation_id)\n\n return json.dumps({\n 'status': 200,\n 'calculation_id': calculation_id,\n 'link': '/' + calculation_id\n })\n\n if request.method == 'GET':\n return render_template('upload.html')\n\n\n@app.route('/', methods=['GET'])\n@cross_origin()\ndef calculation_details(calculation_id):\n modflow_file = os.path.join(app.config['MODFLOW_FOLDER'], calculation_id, 'configuration.json')\n if not os.path.exists(modflow_file):\n abort(404, 'Calculation with id: {} not found.'.format(calculation_id))\n\n data = read_json(modflow_file).get('data').get('mf')\n path = os.path.join(app.config['MODFLOW_FOLDER'], calculation_id)\n\n if request.content_type and 'application/json' in request.content_type:\n return get_calculation_details_json(calculation_id, data, path)\n\n return render_template('details.html', id=str(calculation_id), data=data, path=path)\n\n\n@app.route('//files/', methods=['GET'])\n@cross_origin()\ndef get_file(calculation_id, file_name):\n target_file = os.path.join(app.config['MODFLOW_FOLDER'], calculation_id, file_name)\n\n if not os.path.exists(target_file):\n abort(404, {'message': 'File with name {} not found.'.format(file_name)})\n\n if is_binary(target_file):\n return json.dumps({\n 'name': file_name,\n 'content': 'This file is a binary file and cannot be shown as text'\n })\n\n with open(target_file) as f:\n file_content = f.read()\n return json.dumps({\n 'name': file_name,\n 'content': file_content\n })\n\n\n@app.route('//results/types//layers//totims/', methods=['GET'])\n@cross_origin()\ndef get_results_head_drawdown(calculation_id, type, layer, totim):\n target_folder = os.path.join(app.config['MODFLOW_FOLDER'], calculation_id)\n modflow_file = os.path.join(target_folder, 'configuration.json')\n\n if not os.path.exists(modflow_file):\n abort(404, 'Calculation with id: {} not found.'.format(calculation_id))\n\n permitted_types = ['head', 'drawdown']\n\n totim = float(totim)\n layer = int(layer)\n\n if type not in permitted_types:\n abort(404,\n 'Type: {} not in the list of permitted types. \\\n Permitted types are: {}.'.format(type, \", \".join(permitted_types))\n )\n\n if type == 'head':\n heads = ReadHead(target_folder)\n times = heads.read_times()\n\n if totim not in times:\n abort(404, 'Totim: {} not available. Available totims are: {}'.format(totim, \", \".join(map(str, times))))\n\n nlay = heads.read_number_of_layers()\n if layer >= nlay:\n abort(404, 'Layer must be less then the overall number of layers ({}).'.format(nlay))\n\n return json.dumps(heads.read_layer(totim, layer))\n\n if type == 'drawdown':\n drawdown = ReadDrawdown(target_folder)\n times = drawdown.read_times()\n if totim not in times:\n abort(404, 'Totim: {} not available. Available totims are: {}'.format(totim, \", \".join(map(str, times))))\n\n nlay = drawdown.read_number_of_layers()\n if layer >= nlay:\n abort(404, 'Layer must be less then the overall number of layers ({}).'.format(nlay))\n\n return json.dumps(drawdown.read_layer(totim, layer))\n\n\n@app.route('//timeseries/types//layers//rows//columns/', methods=['GET'])\n@cross_origin()\ndef get_results_time_series(calculation_id, type, layer, row, column):\n target_folder = os.path.join(app.config['MODFLOW_FOLDER'], calculation_id)\n modflow_file = os.path.join(target_folder, 'configuration.json')\n\n if not os.path.exists(modflow_file):\n abort(404, 'Calculation with id: {} not found.'.format(calculation_id))\n\n permitted_types = ['head', 'drawdown']\n\n layer = int(layer)\n row = int(row)\n col = int(column)\n\n if type not in permitted_types:\n abort(404,\n 'Type: {} not in the list of permitted types. \\\n Permitted types are: {}.'.format(type, \", \".join(permitted_types))\n )\n\n if type == 'head':\n heads = ReadHead(target_folder)\n return json.dumps(heads.read_ts(layer, row, col))\n\n if type == 'drawdown':\n drawdown = ReadDrawdown(target_folder)\n return json.dumps(drawdown.read_ts(layer, row, col))\n\n\n@app.route('//results/types/budget/totims/', methods=['GET'])\n@cross_origin()\ndef get_results_budget(calculation_id, totim):\n target_folder = os.path.join(app.config['MODFLOW_FOLDER'], calculation_id)\n modflow_file = os.path.join(target_folder, 'configuration.json')\n\n if not os.path.exists(modflow_file):\n abort(404, 'Calculation with id: {} not found.'.format(calculation_id))\n\n totim = float(totim)\n\n budget = ReadBudget(target_folder)\n times = budget.read_times()\n if totim not in times:\n abort(404, 'Totim: {} not available. Available totims are: {}'.format(totim, \", \".join(map(str, times))))\n\n return json.dumps({\n 'cumulative': budget.read_cumulative_budget(totim),\n 'incremental': budget.read_incremental_budget(totim)\n })\n\n\n@app.route(\n '//results/types/concentration/substance//layers//totims/',\n methods=['GET'])\n@cross_origin()\ndef get_results_concentration(calculation_id, substance, layer, totim):\n target_folder = os.path.join(app.config['MODFLOW_FOLDER'], calculation_id)\n modflow_file = os.path.join(target_folder, 'configuration.json')\n\n if not os.path.exists(modflow_file):\n abort(404, 'Calculation with id: {} not found.'.format(calculation_id))\n\n layer = int(layer)\n substance = int(substance)\n totim = float(totim)\n\n concentrations = ReadConcentration(target_folder)\n\n nsub = concentrations.read_number_of_substances()\n if substance >= nsub:\n abort(404, 'Substance: {} not available. Number of substances: {}.'.format(substance, nsub))\n\n times = concentrations.read_times()\n if totim not in times:\n abort(404, 'Totim: {} not available. Available totims are: {}'.format(totim, \", \".join(map(str, times))))\n\n nlay = concentrations.read_number_of_layers()\n if layer >= nlay:\n abort(404, 'Layer must be less then the overall number of layers ({}).'.format(nlay))\n\n return json.dumps(concentrations.read_layer(substance, totim, layer))\n\n\n@app.route('//results/types/observations', methods=['GET'])\n@cross_origin()\ndef get_results_observations(calculation_id):\n target_folder = os.path.join(app.config['MODFLOW_FOLDER'], calculation_id)\n hob_out_file = os.path.join(target_folder, 'mf.hob.out')\n\n if not os.path.exists(hob_out_file):\n abort(404, 'Head observations from calculation with id: {} not found.'.format(calculation_id))\n\n try:\n df = pd.read_csv(hob_out_file, delim_whitespace=True, header=0, names=['simulated', 'observed', 'name'])\n return df.to_json(orient='records')\n except:\n abort(500, 'Error converting head observation output file.')\n\n\n@app.route('//download', methods=['GET'])\n@cross_origin()\ndef get_download_model(calculation_id):\n os.chdir(os.path.join(app.config['MODFLOW_FOLDER'], calculation_id))\n data = io.BytesIO()\n with zipfile.ZipFile(data, mode='w') as z:\n for root, dirs, files in os.walk(\".\"):\n for filename in files:\n if not filename.endswith('.json'):\n z.write(filename)\n\n data.seek(0)\n return send_file(\n data,\n mimetype='application/zip',\n as_attachment=True,\n attachment_filename='model-calculation-{}.zip'.format(calculation_id)\n )\n\n\n# noinspection SqlResolve\n@app.route('/list')\ndef list():\n con = db_connect()\n con.row_factory = sql.Row\n\n cur = con.cursor()\n cur.execute('select * from calculations')\n\n rows = cur.fetchall()\n return render_template(\"list.html\", rows=rows)\n\n\n@app.route('/metrics')\ndef metrics():\n g_0.set(get_number_of_calculations(0))\n g_100.set(get_number_of_calculations(100))\n g_200.set(get_number_of_calculations(200))\n g_400.set(get_number_of_calculations(400))\n CONTENT_TYPE_LATEST = str('text/plain; version=0.0.4; charset=utf-8')\n return Response(prometheus_client.generate_latest(), mimetype=CONTENT_TYPE_LATEST)\n\n\nif __name__ == '__main__':\n if not os.path.exists(UPLOAD_FOLDER):\n os.makedirs(UPLOAD_FOLDER)\n\n app.secret_key = '2349978342978342907889709154089438989043049835890'\n app.config['SESSION_TYPE'] = 'filesystem'\n app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER\n app.config['MODFLOW_FOLDER'] = MODFLOW_FOLDER\n\n db_init()\n app.run(debug=True, host='0.0.0.0')\n","sub_path":"app/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":16197,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"290492738","text":"import csv\n\ninfo = []\n\n# passa as informações do arquivo csv para uma lista\nfor year in range(1990, 2020): \n diretorio = \"DB/\" + str(year) + \"-\" + str(year+1) + \".csv\"\n file = open(diretorio)\n\n lines = csv.reader(file)\n\n for line in lines:\n info.append(line)\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":280,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"444705041","text":"import argparse\n\nimport torch\n\n\ndef get_args():\n parser = argparse.ArgumentParser(description='RL')\n # parser.add_argument('--algo', default='a2c',\n # help='algorithm to use: a2c, ppo, evo')\n\n # environment hyperparameters\n parser.add_argument('--true-environment', action='store_true', default=False,\n help='triggers the baseline methods')\n parser.add_argument('--frameskip', type=int, default=1,\n help='number of frames to skip (default: 1 (no skipping))')\n # # optimization hyperparameters\n parser.add_argument('--lr', type=float, default=7e-4,\n help='learning rate (default: 1e-6)')\n parser.add_argument('--eps', type=float, default=1e-5,\n help='RMSprop/Adam optimizer epsilon (default: 1e-5)')\n parser.add_argument('--alpha', type=float, default=0.99,\n help='RMSprop optimizer apha (default: 0.99)')\n parser.add_argument('--betas', type=float, nargs=2, default=(0.9, 0.999),\n help='Adam optimizer betas (default: (0.9, 0.999))')\n parser.add_argument('--weight-decay', type=float, default=0.00,\n help='Adam optimizer l2 norm constant (default: 0.01)')\n parser.add_argument('--gamma', type=float, default=0.99,\n help='discount factor for rewards (default: 0.99)')\n # cost function hyperparameters\n parser.add_argument('--return-form', default='true',\n help='determines what return equation to use. true is true returns, gae is gae (not implemented), value uses the value function')\n parser.add_argument('--tau', type=float, default=0.95,\n help='gae parameter (default: 0.95)')\n parser.add_argument('--entropy-coef', type=float, default=1e-2,\n help='entropy loss term coefficient (default: 1e-7)')\n parser.add_argument('--high-entropy', type=float, default=0,\n help='high entropy (for low frequency) term coefficient (default: 1)')\n parser.add_argument('--value-loss-coef', type=float, default=0.5,\n help='value loss coefficient (default: 0.5)')\n parser.add_argument('--max-grad-norm', type=float, default=0.5,\n help='value loss coefficient (default: 0.5)')\n # model hyperparameters\n parser.add_argument('--num-layers', type=int, default=1,\n help='number of layers for network. When using basis functions, defines independence relations (see ReinforcementLearning.basis_models.py)')\n parser.add_argument('--factor', type=int, default=4,\n help='decides width of the network')\n parser.add_argument('--optim', default=\"Adam\",\n help='optimizer to use: Adam, RMSprop, Evol')\n parser.add_argument('--activation', default=\"relu\",\n help='activation function for hidden layers: relu, sin, tanh, sigmoid')\n parser.add_argument('--init-form', default=\"uni\",\n help='initialization to use: uni, xnorm, xuni, eye')\n parser.add_argument('--model-form', default=\"\",\n help='choose the model form, which is defined in Models.models')\n # state hyperparameters\n parser.add_argument('--normalize', action='store_true', default=False,\n help='Normalized inputs for the neural network/function approximator')\n parser.add_argument('--num-stack', type=int, default=4,\n help='number of frames to stack (default: 4)')\n # target hypothesis\n parser.add_argument('--target-tau', type=float, default=0.5,\n help='mixture value for target network (default: 0.5)')\n # distributional RL parameters\n parser.add_argument('--value-bounds', type=float, nargs=2, default=(0, 10),\n help='bounds for the possible value of a state (default: (0, 10))')\n parser.add_argument('--num-value-atoms', type=int, default=51,\n help='number of atoms in distributional RL (default: 51)')\n # distributional regularization parameters\n parser.add_argument('--dist-interval', type=int, default=-1,\n help='decides how often distributional interval is computed')\n parser.add_argument('--exp-beta', type=float, default=0.1,\n help='beta value in exponential distribution')\n parser.add_argument('--dist-coef', type=float, default=1e-5,\n help='the coefficient used for determining the loss value of the distribution')\n parser.add_argument('--correlate-steps', type=int, default=-1,\n help='decides how many steps are used to compute correlate diversity enforcement (default -1)')\n parser.add_argument('--diversity-interval', type=int, default=2,\n help='decides how often correlate diversity error is computed')\n\n # novelty search hyperparameters\n parser.add_argument('--novelty-decay', type=int, default=5000,\n help='number of updates after which novelty rewards are halved')\n parser.add_argument('--novelty-wrappers', default=[], nargs='+',\n help='the different novelty definitions, which are defined in RewardFunctions.novelty_wrappers, empty uses no wrappers (default)')\n parser.add_argument('--visitation-magnitude', type=float, default=.01,\n help='the highest magnitude reward from novelty') # TODO: if multiple, don't share parameters\n parser.add_argument('--visitation-lambda', type=float, default=1,\n help='laplace regularization of novelty decay term')\n parser.add_argument('--novelty-hash-order', type=int, default=20,\n help='the number of possible values for tiles. Uses initial min max values, which might not be great (default: 20)')\n # offline learning parameters\n parser.add_argument('--grad-epoch', type=int, default=1,\n help='number of gradient epochs in offline learning (default: 1, 4 good)')\n\n #PPO parameters\n parser.add_argument('--clip-param', type=float, default=0.2,\n help='ppo clip parameter (default: 0.2)')\n\n # Evolution parameters \n parser.add_argument('--base-form', default=\"\",\n help='base network form for population model')\n parser.add_argument('--select-ratio', type=float, default=0.25,\n help='percentage of population selected in evolution(default: 0.25)')\n parser.add_argument('--num-population', type=int, default=20,\n help='size of the population (default: 20)')\n parser.add_argument('--sample-duration', type=int, default=-1,\n help='number of time steps to evaluate a subject of the population (default: -1)')\n parser.add_argument('--sample-schedule', type=int, default=-1,\n help='number of updates to increase the duration by a factor of duration (default: 10)')\n parser.add_argument('--retest-schedule', type=int, default=-1,\n help='if nonnegative, increases every n steps (default: -1)')\n parser.add_argument('--elitism', action='store_true', default=False,\n help='keep the best performing networks')\n parser.add_argument('--evo-gradient', type=float, default=-1,\n help='take a step towards the weighted mean, with weight as given, (default -1, not used)')\n parser.add_argument('--variance-lr', type=float, default=-1,\n help='adjusts the learning rate based on the variance of the weights, (default -1, not used)')\n parser.add_argument('--reassess-num', type=int, default=-1,\n help='number of best sampled networks, (default -1, not used)')\n parser.add_argument('--reentry-rate', type=float, default=0.0,\n help='rate of randomly re-entering a best network, to update the performance, (default 0.0)')\n parser.add_argument('--retest', type=int, default=1,\n help='number of times a network is sampled, (default 1)')\n parser.add_argument('--reward-stopping', action='store_true', default=False,\n help='if getting a reward causes a stopping behavior, (default False)')\n parser.add_argument('--OoO-eval', action='store_true', default=False,\n help='out of order execution of networks, (default False)')\n parser.add_argument('--weight-sharing', type=int, default=-1,\n help='uses the best networks for weight sharing for n steps, (default -1 for not used)')\n # Evolution Gradient parameters\n parser.add_argument('--sample-steps', type=int, default=2000,\n help='number of time steps to run to evaluate full population (default: 2000)')\n parser.add_argument('--base-learner', default=\"\",\n help='base learning algorithm for running the gradient component')\n parser.add_argument('--evo-lr', type=float, default=.05,\n help='the learning rate for the evolutionary steps (default .05, not used)')\n parser.add_argument('--init-var', type=float, default=1.0,\n help='the initial variance (default 1.0)')\n # Stein Variational policy gradient hyperparameters\n parser.add_argument('--stein-alpha', type=float, default=.05,\n help='the learning rate for the stein steps (default .05, not used)')\n parser.add_argument('--kernel-form', default=\"\",\n help='name of kernel function used (defined in ReinforcementLearning.kernels')\n # option time determination\n parser.add_argument('--swap-form', default=\"dense\",\n help='choose how often to check for new actions, where dense is every time step, and \"reward\" is when the proxy environment gets reward')\n\n # basis function parameters\n parser.add_argument('--period', type=float, default=1,\n help='length of period over which fourier basis is applied')\n parser.add_argument('--scale', type=float, default=1,\n help='scaling term for magnitudes, which can be useful in multilayer to exacerbate differences')\n parser.add_argument('--order', type=int, default=40,\n help='decides order of the basis functions (related to number of basis functions)')\n parser.add_argument('--connectivity', type=int, default=1,\n help='decides the amount the basis functions are connected (1, 2, 12, 22, 3)')\n # Transformer Network parameters\n parser.add_argument('--key-dim', type=int, default=1,\n help='decides the amount the basis functions are connected (1, 2, 12, 22, 3)')\n parser.add_argument('--value-dim', type=int, default=1,\n help='decides the amount the basis functions are connected (1, 2, 12, 22, 3)')\n parser.add_argument('--post-transform-form', default='none',\n help='has the same inputs as model-form, the model after the transform. (default: none for none)')\n parser.add_argument('--num-heads', type=int, default=1,\n help='number of heads for multiheaded attention (or multiple copies of any network) (default: 1)')\n parser.add_argument('--attention-form', default='vector',\n help='has the same inputs as model-form, the model after the transform. (default: none for none)')\n # Adjustment model variables\n parser.add_argument('--adjustment-form', default='none',\n help='has the same inputs as model-form, the model for the base')\n parser.add_argument('--correction-form', default='none',\n help='how the adjustment form relates to the base: none, linear, inbiaspost, inbiaspre, biaspost, biaspre')\n parser.add_argument('--freeze-initial', action ='store_true', default=False,\n help='freeze the weights of the loaded network, do not use with no-adjustment')\n parser.add_argument('--keep-initial-output', action ='store_true', default=False,\n help='use the output parameters from the loaded network (requires that dimensions of hidden layer match')\n\n # Behavior policy parameters\n parser.add_argument('--greedy-epsilon', type=float, default=0.1,\n help='percentage of random actions in epsilon greedy')\n parser.add_argument('--min-greedy-epsilon', type=float, default=0.1,\n help='minimum percentage of random actions in epsilon greedy (if decaying)')\n parser.add_argument('--greedy-epsilon-decay', type=float, default=-1,\n help='greedy epsilon decays by half every n updates (-1 is for no use)')\n parser.add_argument('--behavior-policy', default='',\n help='defines the behavior policy, as defined in BehaviorPolicies.behavior_policies')\n\n # pretraining arguments TODO: not implemented\n parser.add_argument('--pretrain-iterations', type=int, default=-1,\n help='number of time steps to run the pretrainer using PPO on optimal demonstration data, -1 means not used (default: -1)')\n parser.add_argument('--pretrain-target', type=int, default=0,\n help='pretrain either with actions (0) or outputs (1) (default: -1)')\n # Reinforcement model settings\n parser.add_argument('--optimizer-form', default=\"\",\n help='choose the optimizer form, which is defined in ReinforcementLearning.learning_algorithms')\n parser.add_argument('--state-forms', default=[\"\"], nargs='+',\n help='the different relational functions, which are defined in Environment.state_definition')\n parser.add_argument('--state-names', default=[\"\"], nargs='+',\n help='should match the number of elements in state-forms, contains the names of nodes used')\n # Hindsight learning parameter\n parser.add_argument('--base-optimizer', default=\"\",\n help='choose the optimizer form, which is defined in ReinforcementLearning.learning_algorithms')\n # Learning settings\n parser.add_argument('--seed', type=int, default=1,\n help='random seed (default: 1)')\n parser.add_argument('--num-processes', type=int, default=1,\n help='how many training CPU processes to use (default: 16)')\n parser.add_argument('--lag-num', type=int, default=2,\n help='lag between states executed and those used for learning, to delay for reward computation TODO: 1 is the minimum for reasons... (default: 1)')\n parser.add_argument('--num-steps', type=int, default=1,\n help='number of reward checks before update (default: 1)')\n parser.add_argument('--num-grad-states', type=int, default=-1,\n help='number of forward steps used to compute gradient, -1 for not used (default: -1)')\n parser.add_argument('--reward-check', type=int, default=5,\n help='steps between a check for reward, (default 1)')\n parser.add_argument('--num-update-model', type=int, default=1,\n help='number of gradient steps before switching options (default: 3)')\n parser.add_argument('--changepoint-queue-len', type=int, default=30,\n help='number of steps in the queue for computing the changepoints')\n parser.add_argument('--num-iters', type=int, default=int(2e3),\n help='number of iterations for training (default: 2e3)')\n parser.add_argument('--no-cuda', action='store_true', default=False,\n help='disables CUDA training')\n parser.add_argument('--warm-up', type=int, default=10,\n help='num updates before changing model (default: 200 (1000 timesteps))')\n parser.add_argument('--reward-swapping', action='store_true', default=False,\n help='if getting a reward only causes a change in policy, (default False)')\n parser.add_argument('--done-swapping', type=int, default=9999999999,\n help='after n updates, the episode is determined by the episode from the true environment, (default 99999)')\n\n # Replay buffer settings\n parser.add_argument('--match-option', action='store_true', default=False,\n help='use data only from the option currently learning (default False')\n parser.add_argument('--buffer-steps', type=int, default=-1,\n help='number of buffered steps in the record buffer, -1 implies it is not used (default: -1)')\n parser.add_argument('--buffer-clip', type=int, default=20,\n help='backwards return computation (strong effect on runtime')\n parser.add_argument('--weighting-lambda', type=float, default=1e-2,\n help='lambda for the sample weighting in prioritized replay (default = 1e-2)')\n parser.add_argument('--prioritized-replay', default=\"\",\n help='different prioritized replay schemes, (TD (Q TD error), return, recent, \"\"), default: \"\"')\n # Trace settings\n parser.add_argument('--trace-len', type=int, default=-1,\n help='number of states in a trace trajectory (default -1)')\n parser.add_argument('--trace-queue-len', type=int, default=-1,\n help='number of trace trajectories in the trace queue (default -1)')\n # dilated settings\n parser.add_argument('--dilated-stack', type=int, default=4,\n help='number of states to keep when one dilated index is added (default 4)')\n parser.add_argument('--dilated-queue-len', type=int, default=-1,\n help='number of states in the dilation index queue (multiply with dilated-stack) (default -1 not used)')\n parser.add_argument('--target-stack', type=int, default=10,\n help='states to keep around the pretrain-target (default 10)')\n\n # logging settings\n parser.add_argument('--log-interval', type=int, default=10,\n help='log interval, one log per n updates (default: 10)')\n parser.add_argument('--save-interval', type=int, default=100,\n help='save interval, one save per n updates (default: 10)')\n parser.add_argument('--save-dir', default='',\n help='directory to save data when adding edges')\n parser.add_argument('--save-graph', default='graph',\n help='directory to save graph data. Use \"graph\" to let the graph specify target dir, empty does not train')\n parser.add_argument('--save-recycle', type=int, default=-1,\n help='only saves the last n timesteps (-1 if not used)')\n parser.add_argument('--record-rollouts', default=\"\",\n help='path to where rollouts are recorded (when adding edges, where data was recorded to compute min/max)')\n parser.add_argument('--changepoint-dir', default='./data/optgraph/',\n help='directory to save/load option chain')\n parser.add_argument('--unique-id', default=\"0\",\n help='a differentiator for the save path for this network')\n parser.add_argument('--save-past', type=int, default=-1,\n help='save past, saves a new net at the interval, -1 disables, must be a multiple of save-interval (default: -1)')\n parser.add_argument('--save-models', action ='store_true', default=False,\n help='Saves environment and models to option chain directory if true')\n parser.add_argument('--display-focus', action ='store_true', default=False,\n help='shows an image with the focus at each timestep like a video')\n parser.add_argument('--single-save-dir', default=\"\",\n help='saves all images to a single directory with name all')\n # Option Chain Parameters\n parser.add_argument('--base-node', default=\"Action\",\n help='The name of the lowest node in the option chain (generally should be Action)')\n\n # changepoint parameters\n parser.add_argument('--past-data-dir', default='',\n help='directory to load data for computing minmax')\n parser.add_argument('--segment', action='store_true', default=False,\n help='if true, the reward function gives reward for a full segment, while if false, will apply a single sparse reward')\n parser.add_argument('--remove-outliers', type=int, default=-1,\n help='removes outliers prior to clustering, that is, removes |x| > remove value, -1 is not used')\n parser.add_argument('--transforms', default=[''], nargs='+',\n help='Different transforms to be used to reduce a segment or window to a single value. Options are in RewardFunctions.dataTransforms.py')\n parser.add_argument('--train-edge', default='',\n help='the edge to be trained, of the form Object->Object, for changepoints, just Object')\n parser.add_argument('--determiner', default='',\n help='defines the determiner to use, using strings as defined in RewardFunctions.changepointDeterminers')\n parser.add_argument('--reward-form', default='',\n help='defines the kind of reward function to use, as defined in RewardFunctions.changepointReward, also: dense, x, bounce, dir, move_dir[0,1,2,3,4, all] for different cardinal directions')\n parser.add_argument('--changepoint-name', default='changepoint',\n help='name to save changepoint related values')\n parser.add_argument('--champ-parameters', default=[\"Paddle\"], nargs='+',\n help='parameters for champ in the order len_mean, len_sigma, min_seg_len, max_particles, model_sigma, dynamics model enum (0 is position, 1 is velocity, 2 is displacement). Pre built Paddle and Ball can be input as \"paddle\", \"ball\"')\n parser.add_argument('--window', type=int, default=3,\n help='A window over which to compute changepoint statistics')\n parser.add_argument('--min-cluster', type=int, default=15,\n help='A number defining the number of elements in a cluster')\n parser.add_argument('--focus-dumps-name', default='object_dumps.txt',\n help='the name of the dump file used for CHAMP')\n\n # environmental variables\n parser.add_argument('--gpu', type=int, default=0,\n help='gpu number to use (default: 0)')\n parser.add_argument('--num-frames', type=int, default=10e4,\n help='number of frames to use for the training set (default: 10e6)')\n parser.add_argument('--env', default='SelfBreakout',\n help='environment to train on (default: SelfBreakout)')\n parser.add_argument('--train', action ='store_true', default=False,\n help='trains the algorithm if set to true')\n # load variables\n parser.add_argument('--load-weights', action ='store_true', default=False,\n help='load the options for the existing network')\n # parametrized options parameters\n parser.add_argument('--parameterized-option', type=int, default=0,\n help='parametrization enumerator,as defined in multioption, default no parametrization (default: 0)')\n parser.add_argument('--parameterized-form', default='basic',\n help='has the same inputs as model-form, the model for the base')\n\n # parser.add_argument('--load-networks', default=[], nargs='+',\n # help='load weights from the network')\n # DP-GMM parameters\n parser.add_argument('--cluster-model', default=\"DPGMM\",\n help='Which clustering model to use, current DPGMM or Filtered DPGMM')\n parser.add_argument('--dp-gmm', default=[\"default\"], nargs='+',\n help='parameters for dirichlet process gaussian mixture model, in order number of components, maximum iteration number, prior, covariance type and covariance prior')\n \n # testing parameters\n parser.add_argument('--visualize', action='store_true', default=False,\n help='show an image of the output')\n\n\n args = parser.parse_args()\n if args.dp_gmm[0] == 'default':\n args.dp_gmm = [10, 6000, 100, 'diag', 1e-10]\n elif args.dp_gmm[0] == 'ataripaddle':\n args.dp_gmm = [10, 6000, 100, 'diag', 1e-10]\n elif args.dp_gmm[0] == 'block':\n args.dp_gmm = [10, 6000, 1, 'diag', 10]\n elif args.dp_gmm[0] == 'atariball':\n args.dp_gmm = [10, 6000, 1e-10, 'diag', 20]\n elif args.dp_gmm[0] == 'far':\n args.dp_gmm = [10, 6000, 1e-10, 'diag', 20]\n elif args.dp_gmm[0] == 'further':\n args.dp_gmm = [10, 6000, 1e-30, 'diag', 20]\n if args.champ_parameters[0] == \"Paddle\":\n args.champ_parameters = [3, 5, 1, 100, 100, 2, 1e-2, 3]\n elif args.champ_parameters[0] == \"PaddleLong\":\n args.champ_parameters = [3, 30, 1, 100, 100, 2, 1e-2, 3]\n elif args.champ_parameters[0] == \"Block\":\n args.champ_parameters = [3, 30, 1, 100, 100, 2, 1, 3]\n elif args.champ_parameters[0] == \"PaddleAtari\":\n args.champ_parameters = [3, 5, 1, 100, 100, 2, 1, 3]\n elif args.champ_parameters[0] == \"Ball\": \n args.champ_parameters = [15, 10, 1, 100, 100, 2, 1e-2, 3] \n elif args.champ_parameters[0] == \"BallAtari\":\n args.champ_parameters = [15, 7, 1, 100, 100, 2, .5, 3]\n else:\n args.champ_parameters = [float(p) for p in args.champ_parameters]\n if len(args.behavior_policy) == 0:\n print(args.optimizer_form in [\"DQN\", \"SARSA\", \"TabQ\", \"Dist\", \"DDPG\"])\n if args.optimizer_form in [\"DQN\", \"SARSA\", \"TabQ\", \"Dist\", \"DDPG\"]:\n args.behavior_policy = \"egq\"\n elif args.optimizer_form in [\"PPO\", \"A2C\", \"PG\", \"Evo\", \"GradEvo\", \"CMAES\", \"SVPG\", \"Hind\", \"SAC\", \"\"]:\n args.behavior_policy = \"esp\"\n\n\n args.cuda = not args.no_cuda and torch.cuda.is_available()\n\n return args\n\ndef get_edge(edge):\n head = edge.split(\"->\")[0]\n tail = edge.split(\"->\")[1]\n head = head.split(\",\")\n return head, tail[0]\n","sub_path":"arguments.py","file_name":"arguments.py","file_ext":"py","file_size_in_byte":26358,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"152869327","text":"\nfrom torchvision.datasets import VisionDataset\n\nfrom PIL import Image\n\nimport os\nimport os.path\nimport sys\n\ndef pil_loader(path):\n # open path as file to avoid ResourceWarning (https://github.com/python-pillow/Pillow/issues/835)\n with open(path, 'rb') as f:\n img = Image.open(f)\n return img.convert('RGB')\n \nclass Caltech(VisionDataset):\n def __init__(self, root, split='train', transform=None, target_transform=None):\n super(Caltech, self).__init__(root, transform=transform, target_transform=target_transform)\n\n self.split = split # This defines the split you are going to use\n # (split files are called 'train.txt' and 'test.txt')\n\n #Generate a list containing all the classes available in the dataset and a list of index for the classes\n classes = self._find_classes(self.root + \"/101_ObjectCategories\")\n\n self.classes = classes\n self.classes.remove('BACKGROUND_Google') \n\n #Open and read the file containing all the elements of the split set\n pathsplit = root + \"/\" + split + \".txt\"\n f = open(pathsplit, 'r')\n lines = f.readlines()\n\n items = []\n items_as_string = []\n #Generate a list of elements name\n for line in lines:\n ln = line.replace('\\n','')\n if(ln.split(\"/\")[0] != \"BACKGROUND_Google\") :\n items_as_string.append(ln)\n items.append(pil_loader( root + \"/101_ObjectCategories/\" + ln))\n f.close()\n \n self.items = items\n self.items_as_string = items_as_string\n \n\n def _find_classes(self, dir):\n classes = [d.name for d in os.scandir(dir) if d.is_dir()]\n classes.sort()\n return classes\n\n def __getitem__(self, index):\n '''\n __getitem__ should access an element through its index\n Args:\n index (int): Index\n Returns:\n tuple: (sample, target) where target is class_index of the target class.\n '''\n #Find the string (label + img_name) corrispondent to index passed as input\n item = self.items_as_string[index]\n \n #Divide the item into label (that is the class) and image name\n label, image_name = item.split(\"/\") \n\n #By the index, access directly the img file\n image = self.items[index] \n\n # Applies preprocessing when accessing the image\n if self.transform is not None:\n image = self.transform(image)\n\n #By the label, return the index of the class in the list of all the classes for the dataset\n target = self.classes.index(label)\n\n return image, target\n\n def __len__(self):\n '''\n The __len__ method returns the length of the dataset\n It is mandatory, as this is used by several other components\n '''\n length = len(self.items)\n return length\n\n def __getSubsets__(self, percentage):\n import random\n percentage = percentage/100\n first_split = []\n second_split = []\n for _class_ in self.classes:\n elements = [key for key, val in enumerate(self.items_as_string) if val.startswith(_class_)]\n tmp_split1 = random.sample(range(min(elements), max(elements)), int(len(elements)*percentage) )\n tmp_split1.sort()\n tmp_split2 = set(elements) - set(tmp_split1)\n first_split.extend(tmp_split1)\n second_split.extend(tmp_split2)\n return first_split, second_split\n\n","sub_path":"caltech_dataset.py","file_name":"caltech_dataset.py","file_ext":"py","file_size_in_byte":3520,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"479862239","text":"# coding=utf-8\n\"\"\"\n多线程爬虫:\npage_queue: 页码队列(page页码)\ndata_queue: 采集队列(html源码)\nCrawlThread: 采集线程\nParseThread: 解析线程\n\nqueue部分:\n1、Queue(maxsize): 创建一个队列并指定大小(Create a queue object with a given maximum size)\n2、queue.put(self, item, block=True, timeout=None): 往队列中添加一个元素(Put an item into the queue)\n3、queue.get(self, block=True, timeout=None): 从队列中移除并返回一个元素(Remove and return an item from the queue)\n block=True(默认): 如果对��为空,线程不会结束而是进入阻塞状态,直到队列有新的数据\n block=False: 如果队列为空,就弹出queue.Empty异常\n\nthread部分:\n\"\"\"\n\nfrom threading import Thread, Lock\nfrom queue import Queue\nimport requests\nfrom lxml import etree\nimport json\nimport time\n\n# 采集线程类\nclass CrawlThread(Thread):\n\n def __init__(self, crawl_name, page_queue, data_queue):\n \"\"\"\n :param crawl:\n :param page_queue:\n :param data_queue:\n \"\"\"\n\n # 调用父类初始化方法\n super(CrawlThread, self).__init__()\n\n # 线程名\n self.crawl_name = crawl_name\n # 页码队列\n self.page_queue = page_queue\n # 数据队列\n self.data_queue = data_queue\n\n # 请求头\n self.headers = {\"User-Agent\": \"Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0;\"}\n\n # 重写run方法\n def run(self):\n print(\"%s 已启动\" % self.crawl_name)\n\n while not crawl_exit:\n try:\n # url前缀\n url = \"https://www.qiushibaike.com/8hr/page/\"\n # 从page_queue取出一个page\n page = self.page_queue.get(False)\n # 拼接完整url\n full_url = url + str(page)\n print(full_url)\n\n # 发送get请求\n response = requests.get(full_url, headers=self.headers)\n # 获取html源码\n text = response.text\n # 休眠线程\n time.sleep(1)\n # 将html源码放入data_queue\n self.data_queue.put(text)\n except:\n pass\n print(\"%s 已结束\" % self.crawl_name)\n\n\n# 解析线程类\nclass ParseThread(Thread):\n\n def __init__(self, parse_name, data_queue, filename, lock):\n \"\"\"\n :param parse_name:\n :param data_queue:\n :param filename:\n :param lock:\n \"\"\"\n\n # 调用父类初始化方法\n super(ParseThread, self).__init__()\n\n # 线程名\n self.parse_name = parse_name\n # 数据队列\n self.data_queue = data_queue\n # 文件名\n self.filename = filename\n # 锁对象\n self.lock = lock\n\n # 重写run方法\n def run(self):\n print(\"%s 已启动\" % self.parse_name)\n\n while not parse_exit:\n try:\n # 从date_queue队列取数据\n text = self.data_queue.get(False)\n # 调用解析方法\n self.parse(text)\n except:\n pass\n\n print(\"%s 已结束\" % self.parse_name)\n\n def parse(self, text):\n \"\"\"\n xpath表达式解析html源代码\n :param text:\n :return:\n \"\"\"\n\n # 解析HTML文档为HTML DOM(XML)模型\n html = etree.HTML(text)\n # 返回所有段子的节点位置,contains()模糊查询: 第一个参数是要匹配的标签,第二个参数是标签名的部分内容\n node_list = html.xpath('//div[contains(@id, \"qiushi_tag\")]')\n print(node_list)\n # print(type(node_list)) # \n # 遍历列表\n for node in node_list:\n # 用户头像链接(xpath表达式返回的是list,根据索引取数据)\n imgurl = node.xpath('.//div[@class=\"author clearfix\"]//img/@src')[0]\n # print(imgurl)\n # 用户姓名\n username = node.xpath('.//div[@class=\"author clearfix\"]//h2')[0].text.replace('\\n', '')\n # print(username)\n # 段子内容\n content = node.xpath('.//div[@class=\"content\"]/span')[0].text.replace('\\n', '')\n # print(content)\n # 点赞次数\n vote = node.xpath('.//span[@class=\"stats-vote\"]/i')[0].text\n # print(vote)\n # 评论次数\n comments = node.xpath('.//span[@class=\"stats-comments\"]//i')[0].text\n # print(comments)\n # 往字典添加数据\n items = {\n \"imgurl\": imgurl,\n \"username\": username,\n \"content\": content,\n \"vote\": vote,\n \"comments\": comments\n }\n # 将Python对象序列化成Json字符串\n data = json.dumps(items, ensure_ascii=False)\n # 写入本地文件\n with self.lock:\n self.filename.write(data + \"\\n\")\n\ncrawl_exit = False\nparse_exit = False\n\ndef main():\n # 页码队列(限定20页)\n page_queue = Queue(maxsize=20)\n # 往队列添加元素\n for i in range(1, 21):\n page_queue.put(i)\n # 采集队列(页面的html源码,参数为空表示不限制大小)\n data_queue = Queue()\n\n # 创建锁对象\n lock = Lock()\n # 创建存json数据的文件\n filename = open('C://Users/Public/Downloads/qiubai.json', 'a', encoding='utf-8')\n\n # 采集线程名称\n crawl_list = ['carwl-1', 'carwl-2', 'carwl-3']\n # 存放采集线程对象的列表\n crawl_thread = []\n # 遍历名称\n for crawl_name in crawl_list:\n # 创建采集线程对象\n thread = CrawlThread(crawl_name, page_queue, data_queue)\n # 启动线程\n thread.start()\n # 往列表添加线程对象\n crawl_thread.append(thread)\n\n # 解析线程名称\n parse_list = ['parse-1', 'parse-2', 'parse-3']\n # 存放解析线程对象的列表\n parse_thread = []\n # 遍历名称\n for parse_name in parse_list:\n # 创建解析线程对象\n thread = ParseThread(parse_name, data_queue, filename, lock)\n # 启动线程\n thread.start()\n # 往列表添加线程对象\n parse_thread.append(thread)\n\n # 判断page_queue是否为空\n while not page_queue.empty():\n # 不为空就跳过\n pass\n\n # 如果page_queue为空,采集线程退出循环\n global crawl_exit\n crawl_exit = True\n print(\"page_queue为空\")\n\n # 给线程加入阻塞\n for thread in crawl_thread:\n thread.join()\n print('1')\n\n # 判断data_queue是否为空\n while not data_queue.empty():\n # 不为空就跳过\n pass\n\n # 如果data_queue为空,采集线程退出循环\n global parse_exit\n parse_exit = True\n print(\"data_queue为空\")\n\n # 给线程加入阻塞\n for thread in parse_thread:\n thread.join()\n print('2')\n\n with lock:\n # 关闭文件\n filename.close()\n print(\"thanks for use!\")\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"crawl/17_多线程爬虫案例1.py","file_name":"17_多线程爬虫案例1.py","file_ext":"py","file_size_in_byte":7113,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"72265233","text":"import time\nfrom qcfractal.interface.models.records import ResultRecord\nfrom qcfractal.interface.models import KeywordSet, TaskRecord\nimport qcfractal\nimport qcfractal.interface as ptl\nimport numpy as np\nimport qcelemental as qcel\nimport random\n\nprint(\"Building and clearing the database...\\n\")\ndb_name = \"molecule_tests\"\nstorage = qcfractal.storage_socket_factory(f\"postgresql://localhost:5432/{db_name}\")\n# storage._delete_DB_data(db_name)\n\nINSERTION_QUERY_FLAG = 0\n\nCOUNTER_MOL = 0\n\n\ndef create_unique_task(status=\"WAITING\", number=1, num_tags=1, num_programs=1):\n global COUNTER_MOL\n global starting_res_id\n tasks = []\n\n for i in range(number):\n mol = qcel.models.Molecule(symbols=[\"He\", \"He\"], geometry=np.random.rand(2, 3) + COUNTER_MOL, validated=True)\n ret = storage.add_molecules([mol])[\"data\"]\n COUNTER_MOL += 1\n result = ResultRecord(\n version=\"1\", driver=\"energy\", program=\"games\", molecule=ret[0], method=\"test\", basis=\"6-31g\"\n )\n res = storage.add_results([result])[\"data\"]\n tags = [\"tag\" + str(i + 1) for i in range(num_tags)]\n programs = [\"p\" + str(i + 1) for i in range(num_programs)]\n program = random.choice(programs)\n tag = random.choice(tags)\n task = ptl.models.TaskRecord(\n **{\n # \"hash_index\": idx, # not used anymore\n \"spec\": {\"function\": \"qcengine.compute_procedure\", \"args\": [{\"json_blob\": \"data\"}], \"kwargs\": {}},\n \"tag\": tag,\n \"program\": program,\n \"status\": status,\n \"parser\": \"\",\n \"base_result\": res[0],\n }\n )\n tasks.append(task)\n return tasks\n\n\nif INSERTION_QUERY_FLAG == 1:\n\n print(\"starting insertion!!!\")\n num_tasks = int(1e4)\n number = 2000\n for i in range(1):\n then = time.time()\n tasks = create_unique_task(status=\"WAITING\", number=number, num_tags=2, num_programs=1)\n now = time.time()\n print(f\"{number} tasks created in { (now - then) } seconds\")\n then = time.time()\n ret = storage.queue_submit(tasks)\n now = time.time()\n print(f\"Inserted {len(ret['data'])} tasks in { (now - then) } seconds\")\n\n for i in range(10):\n tasks = create_unique_task(status=\"ERROR\", number=num_tasks, num_tags=3, num_programs=3)\n ret = storage.queue_submit(tasks)\n print(f\"Inserted #{i} {len(ret['data'])} tasks.\")\nelse:\n print(\"Running the query!\")\n then = time.time()\n storage.queue_get_next(\n manager=None, available_programs=\"p1\", available_procedures=[], tag=[\"tag1\", \"tag2\"], limit=1000\n )\n now = time.time()\n print(f\"Get time {now - then } second\")\n","sub_path":"benchmarks/bench_task_get_next.py","file_name":"bench_task_get_next.py","file_ext":"py","file_size_in_byte":2734,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"125678140","text":"import numpy as np\nimport pandas as pd\nimport seaborn as sns\nimport matplotlib.pyplot as plt\n\ndata = pd.read_csv(\"data_original.csv\", encoding=\"utf-8\")\ndata[\"structure\"] = list(map(int,list(map(lambda x:x[0]+x[2],data[\"structure\"].values))))\ndata[\"size\"] = list(map(int,list(map(lambda x:x[:-3],data[\"size\"].values))))\ndata[\"price\"] = list(map(int,list(map(lambda x:x[:-4], data[\"price\"].values))))\n\ndata.drop(\"position\",axis=1,inplace=True)\ndata.drop(\"title\",axis=1,inplace=True)\n\nsns.set(style=\"ticks\")\nsns.lmplot(x=\"size\", y=\"price\", col=\"structure\", hue=\"structure\", data=data,\n col_wrap=3, order=1, ci=None, palette=\"muted\", size=4,\n scatter_kws={\"s\": 50, \"alpha\": 1})\nsns.plt.show()\nsns.lmplot(x=\"size\", y=\"price\", data=data)\nsns.plt.show()\n","sub_path":"estimator.py","file_name":"estimator.py","file_ext":"py","file_size_in_byte":767,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"27205013","text":"'''This script demonstrates how to build a variational autoencoder with Keras.\n\n #Reference\n\n - Auto-Encoding Variational Bayes\n https://arxiv.org/abs/1312.6114\n'''\nfrom __future__ import print_function\nimport os\n#os.environ['KERAS_BACKEND'] = 'tensorflow'\nimport numpy as np \nimport matplotlib.pyplot as plt\nfrom scipy.stats import norm \nimport keras\nfrom keras.layers import Input, Dense, Lambda ,Conv2D,MaxPooling2D,Flatten, Reshape, UpSampling2D\nfrom keras.models import Model\nfrom keras import backend as K\nfrom keras import metrics \nfrom keras.datasets import mnist\nfrom keras.layers import Concatenate\n\ndef VAE(original_dim = (224,224,3), latent_dim = 2048, epsilon_std = 1.0, lr = 0.0001, is_sum = True): \n img = Input(shape=original_dim) \n # Block 1\n x = Conv2D(64, (3, 3), activation='relu', padding='same', name='block1_conv1')(img)\n x = Conv2D(64, (3, 3), activation='relu', padding='same', name='block1_conv2',strides = 2)(x)\n #x = MaxPooling2D((2, 2), strides=(2, 2), name='block1_pool')(x)\n\n # Block 2\n x = Conv2D(128, (3, 3), activation='relu', padding='same', name='block2_conv1')(x)\n x = Conv2D(128, (3, 3), activation='relu', padding='same', name='block2_conv2',strides = 2)(x)\n #x = MaxPooling2D((2, 2), strides=(2, 2), name='block2_pool')(x)\n\n # Block 3\n x = Conv2D(256, (3, 3), activation='relu', padding='same', name='block3_conv1')(x)\n x = Conv2D(256, (3, 3), activation='relu', padding='same', name='block3_conv2')(x)\n x = Conv2D(256, (3, 3), activation='relu', padding='same', name='block3_conv3', strides =2)(x)\n #x = MaxPooling2D((2, 2), strides=(2, 2), name='block3_pool')(x)\n\n # Block 4\n x = Conv2D(512, (3, 3), activation='relu', padding='same', name='block4_conv1')(x)\n x = Conv2D(512, (3, 3), activation='relu', padding='same', name='block4_conv2')(x)\n x = Conv2D(512, (3, 3), activation='relu', padding='same', name='block4_conv3', strides = 2)(x)\n #x = MaxPooling2D((2, 2), strides=(2, 2), name='block4_pool')(x)\n\n # Block 5\n x = Conv2D(512, (3, 3), activation='relu', padding='same', name='block5_conv1')(x)\n x = Conv2D(512, (3, 3), activation='relu', padding='same', name='block5_conv2')(x)\n x = Conv2D(512, (3, 3), activation='relu', padding='same', name='block5_conv3')(x)\n #x = MaxPooling2D((2, 2), strides=(2, 2), name='block5_pool')(x) \n\n z_mean = Conv2D(512,(1,1), activation='linear',padding='same',name='z_mean')(x)\n z_log_var = Conv2D(512,(1,1),activation='linear',padding = 'same',name='z_log_var')(x)\n z_mean_var = Concatenate(axis=-1)([z_mean,z_log_var])\n \n def sampling(args): \n z_mean, z_log_var = args \n epsilon = K.random_normal(shape=(K.shape(z_mean)[0],K.shape(z_mean)[1],14,14), mean=0., \n stddev=epsilon_std) \n return z_mean + K.exp(z_log_var / 2) * epsilon \n \n z = Lambda(sampling, output_shape = (512,14,14,),name='sampling')([z_mean,z_log_var])\n\n \n '''\n flat = Flatten()(x) \n \n z_mean = Dense(latent_dim)(flat) \n z_log_var = Dense(latent_dim)(flat) \n z_mean_var = Concatenate(axis = -1)([z_mean,z_log_var])\n\n def sampling(args): \n z_mean, z_log_var = args \n epsilon = K.random_normal(shape=(K.shape(z_mean)[0], latent_dim), mean=0., \n stddev=epsilon_std) \n return z_mean + K.exp(z_log_var / 2) * epsilon \n \n # note that \"output_shape\" isn't necessary with the TensorFlow backend \n z = Lambda(sampling, output_shape=(latent_dim,),name='sampling')([z_mean, z_log_var]) \n \n # we instantiate these layers separately so as to reuse them later \n decoder_h = Dense(7*7*512, activation='relu',name='decode_dense1')(z) \n if K.image_data_format() == 'channels_last':\n reshape_h = Reshape((7,7,512),name='decode_reshape')(decoder_h) \n else:\n reshape_h = Reshape((512,7,7),name='decode_reshape')(decoder_h)\n '''\n\n #up1 = UpSampling2D(size=(2, 2),name='decode_upsample_1')(z) \n decode_conv2_1 = Conv2D(256, (3, 3),padding='same', activation='relu',name='decode_conv1')(z) \n\n up2 = UpSampling2D(size=(2, 2),name='decode_upsample_2')(decode_conv2_1) \n decode_conv2_2 = Conv2D(128, (3, 3), padding='same',activation='relu',name='decode_conv2')(up2) \n\n up3 = UpSampling2D(size=(2, 2),name='decode_upsample_3')(decode_conv2_2) \n decode_conv2_3 = Conv2D(64, (3, 3), padding='same',activation='relu',name='decode_conv3')(up3) \n \n\n up4 = UpSampling2D(size=(2, 2),name='decode_upsample_4')(decode_conv2_3) \n decode_conv2_4 = Conv2D(32, (3, 3),padding='same', activation='relu',name='decode_conv4')(up4) \n \n up5 = UpSampling2D(size=(2, 2),name='decode_upsample_5')(decode_conv2_4)\n decode_conv2_5 = Conv2D(3, (3, 3),padding='same', activation='tanh',name = 'decode_conv5')(up5)\n\n \n # instantiate VAE model \n #vae = Model(img, decode_conv2_5) \n vae = Model(img, [decode_conv2_5,z_mean_var]) \n\n def l2_loss(img, decode_x):\n if is_sum == True: \n l2_loss = K.sum(K.square(img- decode_x), axis = (1,2,3)) \n else: \n l2_loss = K.mean(K.square(img- decode_x), axis = (1,2,3)) \n return l2_loss\n '''\n def kl_loss(img,pred):\n dim = pred.shape[-1]\n z_mean = pred[:,0:dim/2]\n z_logvar = pred[:,dim/2:]\n if is_sum == True:\n kl_loss = - 0.5 * K.sum(1 + z_logvar - K.square(z_mean) - K.exp(z_logvar), axis=-1) \n else:\n kl_loss = - 0.5 * K.mean(1 + z_logvar - K.square(z_mean) - K.exp(z_logvar), axis=-1) \n return kl_loss\n '''\n def kl_loss(img,pred):\n dim = pred.shape[-1]\n z_mean = pred[:,:,:,:dim/2]\n z_logvar = pred[:,:,:,dim/2:]\n if is_sum == True:\n kl_loss = - 0.5 * K.sum(1 + z_logvar - K.square(z_mean) - K.exp(z_logvar), axis=(1,2,3)) \n else:\n kl_loss = - 0.5 * K.mean(1 + z_logvar - K.square(z_mean) - K.exp(z_logvar), axis=(1,2,3)) \n return kl_loss\n # Compute VAE loss \n #vae.add_loss(vae_loss) \n rmsprop = keras.optimizers.RMSprop(lr=lr, rho=0.9, decay=0.0)\n vae.compile(optimizer=rmsprop,loss=[l2_loss, kl_loss]) \n #vae.summary()\n \n return vae\n","sub_path":"conv14/vae_conv14.py","file_name":"vae_conv14.py","file_ext":"py","file_size_in_byte":7233,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"113536627","text":"# Copyright (c) 2018 Uber Technologies, Inc.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nfrom __future__ import absolute_import\n\nimport os\nimport tempfile\nimport unittest\nfrom os.path import join\n\nimport mock\nimport testfixtures.popen\nfrom testfixtures.popen import MockPopen, PopenBehaviour\n\nfrom uberpoet.genproj import GenProjCommandLine\nfrom uberpoet.multisuite import CommandLineMultisuite\n\nfrom .utils import integration_test, read_file\n\n\nclass TestIntegration(unittest.TestCase):\n\n def verify_genproj(self, lib_name, mod_count, app_path):\n main_path = join(app_path, 'App')\n lib_path = join(app_path, lib_name, 'Sources')\n\n # Top level dir\n contents = os.listdir(app_path)\n self.assertGreater(len(contents), 0)\n self.assertEqual(len(contents), mod_count)\n\n # App dir\n self.assertIn('App', contents)\n app_contents = os.listdir(main_path)\n self.assertGreater(len(app_contents), 0)\n for file_name in ['BUCK', 'main.swift', 'Info.plist']:\n self.assertIn(file_name, app_contents)\n with open(join(main_path, file_name), 'r') as f:\n self.assertGreater(len(f.read()), 0)\n # TODO actually verify generated code?\n\n # Lib dir\n self.assertIn(lib_name, contents)\n lib_contents = os.listdir(lib_path)\n self.assertGreater(len(lib_contents), 0)\n self.assertIn('File0.swift', lib_contents)\n with open(join(lib_path, 'File0.swift'), 'r') as f:\n self.assertGreater(len(f.read()), 0)\n # TODO actually verify generated code?\n\n @integration_test\n def test_flat_genproj(self):\n app_path = join(tempfile.gettempdir(), 'apps', 'mockapp')\n args = [\n \"--output_directory\", app_path, \"--buck_module_path\", \"/apps/mockapp\", \"--gen_type\", \"flat\",\n \"--lines_of_code\", \"150000\"\n ]\n command = GenProjCommandLine()\n command.main(args)\n\n self.verify_genproj('MockLib53', 101, app_path)\n\n @integration_test\n def test_dot_genproj(self):\n app_path = join(tempfile.gettempdir(), 'apps', 'mockapp')\n\n test_fixture_path = os.path.join(os.path.dirname(__file__), 'fixtures', 'test_dot.gv')\n args = [\n \"--output_directory\", app_path, \"--buck_module_path\", \"/apps/mockapp\", \"--gen_type\", \"dot\",\n \"--lines_of_code\", \"150000\", \"--dot_file\", test_fixture_path, \"--dot_root\", \"DotReaderMainModule\"\n ]\n command = GenProjCommandLine()\n command.main(args)\n\n self.verify_genproj('DotReaderLib17', 338, app_path)\n\n @integration_test\n def test_flat_multisuite(self):\n root_path = join(tempfile.gettempdir(), 'multisuite_test')\n app_path = join(root_path, 'apps', 'mockapp')\n log_path = join(root_path, 'logs')\n args = [\"--log_dir\", log_path, \"--app_gen_output_dir\", root_path, \"--test_build_only\", \"--skip_xcode_build\"]\n command = CommandLineMultisuite()\n command.main(args)\n self.assertGreater(os.listdir(app_path), 0)\n self.verify_genproj('MockLib53', 101, app_path)\n\n @integration_test\n def test_flat_multisuite_mocking_calls(self):\n test_cloc_out_path = os.path.join(os.path.dirname(__file__), 'fixtures', 'cloc_out.json')\n cloc_out = read_file(test_cloc_out_path)\n root_path = join(tempfile.gettempdir(), 'multisuite_test')\n app_path = join(root_path, 'apps', 'mockapp')\n log_path = join(root_path, 'logs')\n args = [\n \"--log_dir\", log_path, \"--app_gen_output_dir\", root_path, \"--test_build_only\", \"--switch_xcode_versions\",\n \"--full_clean\"\n ]\n\n # we need the unused named variable for mocking purposes\n # noinspection PyUnusedLocal\n def command_callable(command, stdin):\n if 'cloc' in command:\n return PopenBehaviour(stdout=cloc_out)\n elif 'xcodebuild -version' in command:\n return PopenBehaviour(stdout=b'Xcode 10.0\\nBuild version 10A255\\n')\n return PopenBehaviour(stdout=b'test_out', stderr=b'test_error')\n\n with testfixtures.Replacer() as rep:\n mock_popen = MockPopen()\n rep.replace('subprocess.Popen', mock_popen)\n mock_popen.set_default(behaviour=command_callable)\n\n with mock.patch('distutils.spawn.find_executable') as mock_find:\n mock_find.return_value = '/bin/ls' # A non empty return value basically means \"I found that executable\"\n CommandLineMultisuite().main(args)\n self.assertGreater(os.listdir(app_path), 0)\n self.verify_genproj('MockLib53', 101, app_path)\n\n @integration_test\n def test_dot_multisuite(self):\n test_fixture_path = os.path.join(os.path.dirname(__file__), 'fixtures', 'test_dot.gv')\n root_path = join(tempfile.gettempdir(), 'multisuite_test')\n app_path = join(root_path, 'apps', 'mockapp')\n log_path = join(root_path, 'logs')\n args = [\n \"--log_dir\", log_path, \"--app_gen_output_dir\", root_path, \"--dot_file\", test_fixture_path, \"--dot_root\",\n \"DotReaderMainModule\", \"--skip_xcode_build\", \"--test_build_only\"\n ]\n command = CommandLineMultisuite()\n command.main(args)\n self.assertGreater(os.listdir(app_path), 0)\n self.verify_genproj('DotReaderLib17', 338, app_path)\n\n @integration_test\n def test_all_multisuite(self):\n test_fixture_path = os.path.join(os.path.dirname(__file__), 'fixtures', 'test_dot.gv')\n root_path = join(tempfile.gettempdir(), 'multisuite_test')\n app_path = join(root_path, 'apps', 'mockapp')\n log_path = join(root_path, 'logs')\n args = [\n \"--log_dir\", log_path, \"--app_gen_output_dir\", root_path, \"--dot_file\", test_fixture_path, \"--dot_root\",\n \"DotReaderMainModule\", \"--skip_xcode_build\", \"--lines_of_code\", \"150000\"\n ]\n command = CommandLineMultisuite()\n command.main(args)\n self.assertGreater(os.listdir(app_path), 0)\n\n # Note we are assuming that the last project to be generated is the dot project.\n # If you change the order of project generation, make this match whatever is the new 'last project'\n # It's a bit fragile, but it's better than not verifying anything currently\n self.verify_genproj('DotReaderLib17', 338, app_path)\n","sub_path":"tests/test_integration.py","file_name":"test_integration.py","file_ext":"py","file_size_in_byte":6942,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"243500222","text":"import bisect\r\n\r\nN = 10 ** 5\r\nprimes = [True] * (N + 1)\r\nprimes[0] = primes[1] = False\r\nfor i in range(2, int(len(primes) ** 0.5 + 1)):\r\n for j in range(i + i, len(primes), i):\r\n primes[j] = False\r\nprimes = [i for i in range(len(primes)) if primes[i]]\r\ntargets = [x for x in primes if (x + 1) // 2 in primes]\r\n\r\nq = int(input())\r\nfor i in range(q):\r\n l, r = map(int, input().split())\r\n x = bisect.bisect_left(targets, l)\r\n y = bisect.bisect_right(targets, r)\r\n print(y - x)","sub_path":"abc084/d.py","file_name":"d.py","file_ext":"py","file_size_in_byte":495,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"118741613","text":"from sklearn.neighbors import KNeighborsClassifier\nfrom sklearn import datasets\nfrom sklearn.metrics import accuracy_score\nimport numpy as np\nimport datetime\n\ndigits_data = datasets.load_digits()\n\n\nclass Knn(object):\n def __init__(self, X_train, X_test, y_train, y_test, start_state=0, n_neighbors=3):\n self.X_train = X_train\n self.X_test = X_test\n self.y_train = y_train\n self.y_test = y_test\n self.start_state = start_state\n self.n = n_neighbors\n self.accuracy = 0.0\n\n def fit(self):\n self.knn = KNeighborsClassifier(n_neighbors=self.n)\n self.knn.fit(self.X_train, self.y_train)\n\n def predict(self):\n y_pred = self.knn.predict(self.X_test)\n miss_classified = (y_pred != self.y_test).sum()\n score = self.knn.score(self.X_test, self.y_test, sample_weight=None)\n errors = len(np.nonzero(self.y_test - y_pred))\n self.accuracy = accuracy_score(y_pred, self.y_test)\n # print(\"MissClassified: \", miss_classified)\n # print('Accuracy : % .2f' % self.accuracy)\n\n def main(self):\n start = datetime.datetime.now()\n self.fit()\n end = datetime.datetime.now()\n self.predict()\n return [self.accuracy, (end - start).total_seconds()]\n","sub_path":"Proj3/KNearsNeighbour.py","file_name":"KNearsNeighbour.py","file_ext":"py","file_size_in_byte":1277,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"432178076","text":"# 题目:输入一个复杂链表(每个节点中有节点值,以及两个指针,一个指向下一个节点,另一个特殊指针指向任意一个节点),\n# 返回结果为复制后复杂链表的head。(注意,输出结果中请不要返回参数中的节点引用,否则判题程序会直接返回空)\n# 思路:第一步:在每个原始节点后面复制这个节点,并用next将这2n个节点串起来\n# 第二步:复制random指针,指向原始random指针所指向的后一个节点\n# 第三步:拆分原始链表和复制链表\n\n\nclass RandomListNode(object):\n def __init__(self, data):\n self.label = data\n self.next = None\n self.random = None\n\n\nclass Solution:\n # 返回 RandomListNode\n def Clone(self, pHead):\n # write code here\n if pHead is None:\n return None\n\n self.CloneNodes(pHead)\n self.CloneRandomNodes(pHead)\n return self.ReconnextedNodes(pHead)\n\n def CloneNodes(self, pHead):\n pNode = pHead\n while pNode:\n pClone = RandomListNode(0)\n pClone.label = pNode.label\n pClone.next = pNode.next\n pClone.random = pNode.random\n pNode.next = pClone\n pNode = pClone.next\n\n def CloneRandomNodes(self, pHead):\n pNode = pHead\n while pNode:\n pClone = pNode.next\n if pNode.random is not None:\n pClone.random = pNode.random.next\n pNode = pClone.next\n\n def ReconnextedNodes(self, pHead):\n pNode = pHead\n pCloneHead = pCloneNode = pNode.next\n pNode.next = pCloneNode.next\n pNode = pNode.next\n\n while pNode:\n pCloneNode.next = pNode.next\n pCloneNode = pCloneNode.next\n pNode.next = pCloneNode.next\n pNode = pNode.next\n return pCloneHead\n\n\nnode1 = RandomListNode(1)\nnode2 = RandomListNode(3)\nnode3 = RandomListNode(5)\nnode1.next = node2\nnode2.next = node3\nnode1.random = node3\n\nS = Solution()\nclonedNode = S.Clone(node1)\nprint(clonedNode.random.label)\n","sub_path":"35_01复杂链表的复制.py","file_name":"35_01复杂链表的复制.py","file_ext":"py","file_size_in_byte":2114,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"81043158","text":"\"\"\" First part of the problem.\n\"\"\"\n\n# lista = [\"\"]\n# counter = 0\n# valido = 0\n# questions = 0\n# with open ('YourFilePath/Desktop/AdventOfCode2020/Puzzle6.txt') as f:\n# for line in f: #adding all the responses in to a list item\n# if line.strip():\n# line = line.rstrip(\"\\n\")\n# lista[counter] = lista[counter] + ' ' + line\n# lista[counter].replace(\" \", \"\")\n# else:\n# lista.append(\"\") # if the line is a blank line, we increment the counter\n# counter += 1 # so we have the next item on a different list entry\n\n# for i in lista:\n# i = i.replace(' ', '')\n# questions += len(set(i))\n# print(questions)\n \n\"\"\"Second part of the problem.\n\"\"\"\nlista = [\"\"]\ngroups = {}\ncounter = 0\nvalido = 0\nquestions = 0\ngroups[\"grupo0\"] = [] #initializing the dictionary for the answers (values) of every participant\nwith open ('YourFilePath/Desktop/AdventOfCode2020/Puzzle6.txt') as f:\n for line in f: #adding all the responses in to a dict item\n if line.strip():\n line = line.rstrip(\"\\n\")\n groups[\"grupo\" + str(counter)].append(line) #if we don't have a blank space, we add the value to the dictionary key (groupx)\n else:\n counter += 1 # so we have the next item on a different group entry, so we initialize the dictionary key to empty\n groups[\"grupo\" + str(counter)] = []\n\n\nfor k in groups.keys(): #iterating over the groups \n if len(groups[k]) == 1: #if ther eis only 1 person in the group, all the answers are valid\n questions = questions + len(groups[k][0])\n else:\n d = {} #initializing a dict to count repeated answers\n for i in groups[k]:\n if len(i) > 1: # if the strings are formed for more than 1 letter, we split them and count how many times the letter appears\n for j in i:\n if j in d:\n d[j] +=1\n else:\n d[j] = 1\n else: # if the letter only appears one, we check if it's on the dict already, and add it if not.\n if i in d:\n d[i] +=1\n else:\n d[i] = 1\n for value in d: #for the values of the letters, if it's equal to the number of people in the group,it's correct.\n if d[value] == len(groups[k]):\n questions = questions + 1 \n\nprint(questions)\n","sub_path":"Puzzle6.py","file_name":"Puzzle6.py","file_ext":"py","file_size_in_byte":2458,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"76636223","text":"import numpy as np\nimport networkx as nx\nimport node2vec\nfrom gensim.models import Word2Vec\nimport time\nimport pandas as pd\n\n\nclass Node2VecFeatureLearning(object):\n\n def __init__(self, nxG=None):\n self.nxG = nxG\n self.G = None\n self.model = None\n\n #\n # learn_embeddings() and fit() are based on the learn_embeddings() and main() functions in main.py of the\n # reference implementation.\n #\n def learn_embeddings(self, walks, d, k):\n '''\n Learn embeddings by optimizing the Skipgram objective using SGD.\n '''\n walks = [map(str, walk) for walk in walks]\n self.model = Word2Vec(walks, size=d, window=k, min_count=0, sg=1, workers=2,\n iter=1)\n self.model.wv.save_word2vec_format(r'..\\data\\model.txt')\n\n return\n\n def fit(self, p=1, q=1, d=128, r=10, l=80, k=10 ):\n '''\n Pipeline for representational learning for all nodes in a graph.\n '''\n start_time_fit = time.time()\n self.G = node2vec.Graph(self.nxG, False, p, q)\n self.G.preprocess_transition_probs()\n walks = self.G.simulate_walks(r, l)\n #print(\"Time up to learn_embeddings()\", time.time()-start_time_fit, \"seconds\")\n self.learn_embeddings(walks, d, k)\n print(\"Total time for fit()\", time.time()-start_time_fit, \"seconds\")\n\n\n def from_file(self, filename):\n '''\n Helper function for loading a node2vec model from disk so that I can run experiments fast without having to\n wait for node2vec to finish.\n :param filename: The filename storing the model\n :return: None\n '''\n self.model = pd.read_csv(filename, delimiter=' ', skiprows=1, header=None)\n self.model.iloc[:, 0] = self.model.iloc[:, 0].astype(str) # this is so that indexing works the same as having\n # trained the model with self.fit()\n self.model.index = self.model.iloc[:, 0]\n self.model = self.model.drop([0],1)\n print(self.model.head(2))\n\n def select_operator_from_str(self, binary_operator):\n if binary_operator == 'l1':\n return self.operator_l1\n elif binary_operator == 'l2':\n return self.operator_l2\n elif binary_operator == 'avg':\n return self.operator_avg\n elif binary_operator == 'h': #hadamard\n return self.operator_hadamard\n\n print(\"CAUTION: Operator\"+binary_operator+\"is invalid. Returning Hadamard operator.\")\n return self.operator_hadamard # default in case binary operator is not a valid value\n\n def operator_hadamard(self, u, v):\n return u*v\n\n def operator_avg(self, u, v):\n return (u+v)/2.0\n\n def operator_l2(self, u, v):\n return (u-v)**2\n\n def operator_l1(self, u, v):\n return np.abs(u-v)\n\n def transform(self, data_edge, binary_operator = 'h'):\n '''\n It calculates edge features for the given binary operator applied to the node features in data_edge\n :param data_edge: It is a list of pairs of nodes that make an edge in the graph\n :param binary_operator: The binary operator to apply to the node features to calculate an edge feature\n :return: Features in X (Nxd array where N is the number of edges and d is the dimensionality of the edge\n features that is the same as the dimensionality of the node features) and edge labels in y (0 for no edge\n and 1 for edge).\n '''\n X = [] # data matrix, each row is a d-dimensional feature of an edge\n y = [] # is label 0,1 for no-edge and edge respectively\n\n func_bin_operator = self.select_operator_from_str(binary_operator)\n\n for row in data_edge:\n y.append(row[-1]) # the label, 0 or 1\n u_str = str(row[0])\n v_str = str(row[1])\n if type(self.model) is Word2Vec:\n X.append(func_bin_operator(self.model[u_str], self.model[v_str]))\n else: # Pandas Dataframe\n X.append(func_bin_operator(self.model.loc[u_str],self.model.loc[v_str]))\n\n return np.array(X), np.array(y)","sub_path":"src/Node2VecFeatureLearning.py","file_name":"Node2VecFeatureLearning.py","file_ext":"py","file_size_in_byte":4126,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"486659685","text":"#!/usr/bin/env python3\n\nfrom datetime import datetime, timedelta\nfrom django.db.models import Max\nfrom django.shortcuts import render, HttpResponseRedirect\nfrom devnet2019.forms import AddDevice, AddDeviceType, EditDeviceType, EditDevice\nfrom devnet2019.models import Devicedb, Devicetype, DeviceSNMP, SNMPtype\nfrom modules.devnet_0_cpumem_interval import cpu_max_interval, mem_max_interval\n\n\ndef add_device_type(request):\n if request.method == 'POST':\n form = AddDeviceType(request.POST)\n if form.is_valid():\n device_type_name = request.POST.get('device_type_name')\n\n oid_list = []\n cpu_usage = request.POST.get('cpu_usage')\n oid_list.append(['cpu_usage', cpu_usage])\n mem_usage = request.POST.get('mem_usage')\n oid_list.append(['mem_usage', mem_usage])\n mem_free = request.POST.get('mem_free')\n oid_list.append(['mem_free', mem_free])\n if_name = request.POST.get('if_name')\n oid_list.append(['if_name', if_name])\n if_speed = request.POST.get('if_speed')\n oid_list.append(['if_speed', if_speed])\n if_state = request.POST.get('if_state')\n oid_list.append(['if_state', if_state])\n if_in_bytes = request.POST.get('if_in_bytes')\n oid_list.append(['if_in_bytes', if_in_bytes])\n if_out_bytes = request.POST.get('if_out_bytes')\n oid_list.append(['if_out_bytes', if_out_bytes])\n\n # 设备类型表指保存设备name\n d = Devicetype(type_name=device_type_name)\n d.save()\n\n # 提取OID列表分别写入\n for x in oid_list:\n # 第一次添加设备类型前将下面2行恢复,否则snmptype表无数据\n # f = SNMPtype(snmp_type=x[0])\n # f.save()\n ds = DeviceSNMP(device_type=d,\n snmp_type=SNMPtype.objects.get(snmp_type=x[0]),\n oid=x[1])\n ds.save()\n successmessage = '设备类型添加成功!'\n return render(request, 'devnet_add_device_type.html', locals())\n else:\n return render(request, 'devnet_add_device_type.html', locals())\n else:\n form = AddDeviceType()\n return render(request, 'devnet_add_device_type.html', locals())\n\n\ndef show_device_type(request):\n device_type_list = []\n for devicetype in Devicetype.objects.all().order_by('id'):\n device_type_dict = {'id_delete': '/device_mgmt/deletedevicetype/' + str(devicetype.id),\n 'id_edit': '/device_mgmt/editdevicetype/' + str(devicetype.id),\n 'name': devicetype.type_name}\n device_type_list.append(device_type_dict)\n return render(request, 'devnet_show_device_type.html', locals())\n\n\ndef edit_device_type(request, device_type_id):\n if request.method == 'POST':\n form = EditDeviceType(request.POST)\n if form.is_valid():\n if request.user.has_perm('devnet2019.change_devicedb'):\n device_id = request.POST.get('device_id')\n device_type_name = request.POST.get('device_type_name')\n\n # 修改设备类型名称\n d1 = Devicetype(id=request.POST.get('device_id'),\n type_name=request.POST.get('device_type_name'))\n d1.save()\n\n # 存储OID列表,包含OID_name和OID\n oid_list = []\n cpu_usage = request.POST.get('cpu_usage')\n oid_list.append(['cpu_usage', cpu_usage])\n mem_usage = request.POST.get('mem_usage')\n oid_list.append(['mem_usage', mem_usage])\n mem_free = request.POST.get('mem_free')\n oid_list.append(['mem_free', mem_free])\n if_name = request.POST.get('if_name')\n oid_list.append(['if_name', if_name])\n if_speed = request.POST.get('if_speed')\n oid_list.append(['if_speed', if_speed])\n if_state = request.POST.get('if_state')\n oid_list.append(['if_state', if_state])\n if_in_bytes = request.POST.get('if_in_bytes')\n oid_list.append(['if_in_bytes', if_in_bytes])\n if_out_bytes = request.POST.get('if_out_bytes')\n oid_list.append(['if_out_bytes', if_out_bytes])\n\n d = Devicetype.objects.get(id=device_id)\n\n for x in oid_list:\n device_snmp_oid = d.devicesnmp.get(snmp_type__snmp_type=x[0])\n device_snmp_oid.oid = x[1]\n device_snmp_oid.save()\n else:\n err = '没有权限'\n return render(request, '404.html', locals())\n successmessage = '设备类型编辑成功!'\n return render(request, 'devnet_edit_device_type.html', locals())\n\n else:\n return render(request, 'devnet_edit_device_type.html', locals())\n else:\n dt = Devicetype.objects.get(id=device_type_id)\n # django数据库双下划线操作。\n # django数据库中没有连表的操作,没有sqlalchemy中的join操作,它使用了一种更简洁的操作‘__’, 双下划线。\n # 使用双下划线可以完成连表操作,可以正向查询,也可以反向查询。\n form = EditDeviceType(initial={'device_id': device_type_id,\n 'device_type_name': dt.type_name,\n 'cpu_usage': dt.devicesnmp.get(snmp_type__snmp_type='cpu_usage').oid,\n 'mem_usage': dt.devicesnmp.get(snmp_type__snmp_type='mem_usage').oid,\n 'mem_free': dt.devicesnmp.get(snmp_type__snmp_type='mem_free').oid,\n 'if_name': dt.devicesnmp.get(snmp_type__snmp_type='if_name').oid,\n 'if_speed': dt.devicesnmp.get(snmp_type__snmp_type='if_speed').oid,\n 'if_state': dt.devicesnmp.get(snmp_type__snmp_type='if_state').oid,\n 'if_in_bytes': dt.devicesnmp.get(snmp_type__snmp_type='if_in_bytes').oid,\n 'if_out_bytes': dt.devicesnmp.get(snmp_type__snmp_type='if_out_bytes').oid,\n })\n return render(request, 'devnet_edit_device_type.html', locals())\n\n\ndef delete_device_type(request, device_type_id):\n if request.user.has_perm('devnet2019.delete_devicetype'):\n d = Devicetype.objects.get(id=device_type_id)\n d.delete()\n else:\n err = '没有权限'\n return render(request, '404.html', locals())\n return HttpResponseRedirect('/device_mgmt/show_device_type/')\n\n\ndef add_device(request):\n if request.method == 'POST':\n form = AddDevice(request.POST)\n if form.is_valid():\n # 把设备信息写入Devicedb数据库\n d1 = Devicedb(name=request.POST.get('name'),\n ip=request.POST.get('ip'),\n description=request.POST.get('description'),\n type=Devicetype.objects.get(id=int(request.POST.get('type'))),\n snmp_enable=request.POST.get('snmp_enable'),\n snmp_ro_community=request.POST.get('snmp_ro_community'),\n snmp_rw_community=request.POST.get('snmp_rw_community'),\n ssh_username=request.POST.get('ssh_username'),\n ssh_password=request.POST.get('ssh_password'),\n enable_password=request.POST.get('enable_password'), )\n d1.save()\n successmessage = '设备添加成功!'\n # locls()返回一个包含当前作用域里面的所有变量和它们的值的字典。\n return render(request, 'devnet_add_device.html', locals())\n else:\n return render(request, 'devnet_add_device.html', locals())\n else:\n form = AddDevice()\n return render(request, 'devnet_add_device.html', locals())\n\n\ndef show_device(request):\n # 查询整个Devicedb信息\n result = Devicedb.objects.all()\n devices_list = []\n # 获取每个设备信息\n for x in result:\n # 产生设备信息的字典\n devices_dict = {'id_delete': \"/device_mgmt/deletedevice/\" + str(x.id), # 删除设备URL\n 'id_edit': \"/device_mgmt/editdevice/\" + str(x.id), # 编辑设备URL\n 'name': x.name, # 设备名称\n 'ip': x.ip} # 设备IP地址\n try:\n # 取最新的SNMP和SSH可达信息\n reachable_info = x.reachable.all().order_by('-id')[0]\n devices_dict['snmp_reachable'] = reachable_info.snmp_reachable\n devices_dict['ssh_reachable'] = reachable_info.ssh_reachable\n except IndexError:\n devices_dict['snmp_reachable'] = False\n devices_dict['ssh_reachable'] = False\n\n try:\n # 取CPU最大利用率。\n # record_datetime__gt表示数据库记录时间record_datetime大于上一次告警时间\n # timedelta代表两个datetime之间的时间。\n # datetime.now() - timedelta(hours=cpu_max_interval)是当前时间减去告警周期(默认一个小时)\n # Max获取指定对象的最大值\n devices_dict['cpu_max'] = x.cpu_usage.filter(\n record_datetime__gt=datetime.now() - timedelta(hours=cpu_max_interval)).aggregate(Max('cpu_usage')).get('cpu_usage__max')\n # 取当前CPU利用率\n devices_dict['cpu_current'] = x.cpu_usage.filter(record_datetime__gt=datetime.now() - timedelta(minutes=1)).order_by('-id')[0].cpu_usage\n except IndexError:\n devices_dict['cpu_max'] = 'None'\n devices_dict['cpu_current'] = 'None'\n\n try:\n # 取内存最大利用率。\n # record_datetime__gt表示数据库记录时间record_datetime大于上一次告警时间\n # timedelta代表两个datetime之间的时间。\n # datetime.now() - timedelta(hours=cpu_max_interval)是当前时间减去告警周期(默认一个小时)\n # Max获取指定对象的最大值\n devices_dict['mem_max'] = x.mem_usage.filter(\n record_datetime__gt=datetime.now() - timedelta(hours=mem_max_interval)).aggregate(Max('mem_usage')).get('mem_usage__max')\n # 取当前内存利用率\n devices_dict['mem_current'] = x.mem_usage.filter(record_datetime__gt=datetime.now() - timedelta(minutes=1)).order_by('-id')[0].mem_usage\n except IndexError:\n devices_dict['mem_max'] = 'None'\n devices_dict['mem_current'] = 'None'\n\n if_count = 0\n for if_info in x.interface.all():\n try:\n # 如果再1分钟内接口状态为UP并且接口双向bytes不为空,则将接口数量加1\n if if_info.interface_state.filter(record_datetime__gt=datetime.now() - timedelta(minutes=1)).order_by('-id')[0].state and \\\n if_info.interface_in_bytes.filter(record_datetime__gt=datetime.now() - timedelta(minutes=1)).order_by('-id')[0].in_bytes and \\\n if_info.interface_out_bytes.filter(record_datetime__gt=datetime.now() - timedelta(minutes=1)).order_by('-id')[0].out_bytes:\n if_count += 1\n except IndexError:\n if_count = 0\n\n devices_dict['ifs'] = if_count\n # 把设备信息添加到字典,再添加到devices_list清单\n devices_list.append(devices_dict)\n return render(request, 'devnet_show_devices.html', locals())\n\n\ndef edit_device(request, device_id):\n if request.method == 'POST':\n form = EditDevice(request.POST)\n type = Devicetype.objects.get(id=int(request.POST.get('type')))\n if form.is_valid():\n # 判断用户是否有变更该表的权限\n if request.user.has_perm('devnet2019.change_devicedb'):\n d1 = Devicedb(id=request.POST.get('id'),\n name=request.POST.get('name'),\n ip=request.POST.get('ip'),\n description=request.POST.get('description'),\n type=Devicetype.objects.get(id=int(request.POST.get('type'))),\n snmp_enable=request.POST.get('snmp_enable'),\n snmp_ro_community=request.POST.get('snmp_ro_community'),\n snmp_rw_community=request.POST.get('snmp_rw_community'),\n ssh_username=request.POST.get('ssh_username'),\n ssh_password=request.POST.get('ssh_password'),\n enable_password=request.POST.get('enable_password'), )\n d1.save()\n successmessage = '设备修改成功!'\n else:\n err = '没有权限'\n return render(request, '404.html', locals())\n\n # locls()返回一个包含当前作用域里面的所有变量和它们的值的字典。\n return render(request, 'devnet_add_device.html', locals())\n else:\n return render(request, 'devnet_add_device.html', locals())\n else:\n d = Devicedb.objects.get(id=device_id)\n form = EditDevice(initial={'id': d.id,\n 'name': d.name,\n 'ip': d.ip,\n 'description': d.description,\n 'type': d.type.id,\n 'snmp_enable': d.snmp_enable,\n 'snmp_ro_community': d.snmp_ro_community,\n 'snmp_rw_community': d.snmp_rw_community,\n 'ssh_username': d.ssh_username,\n 'ssh_password': d.ssh_password,\n 'enable_password': d.enable_password\n })\n return render(request, 'devnet_add_device.html', locals())\n\n\ndef delete_device(request, device_id):\n d = Devicedb.objects.get(id=device_id)\n d.delete()\n return HttpResponseRedirect('/device_mgmt/show_device/')\n","sub_path":"devnet2019/views/devnet_device_mgmt.py","file_name":"devnet_device_mgmt.py","file_ext":"py","file_size_in_byte":14619,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"502440335","text":"from __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\n\n#import seaborn as sns\n#sns.set(style='white')\nimport urllib.request\nimport numpy as np\nimport os\nimport glob\nimport pandas as pd\nimport importlib\n'''\nimport matplotlib\n\nmatplotlib.use('Agg') # fixes issue if no GUI provided\nimport matplotlib.pyplot as plt\n\nimport keras\nfrom keras import backend as K\nimport config\nimport math\nimport itertools\nfrom scipy import ndimage as ndi\nfrom skimage import morphology\nfrom skimage import filters\nfrom skimage.color import rgb2gray\nfrom skimage.transform import resize\n'''\nimport argparse\nimport sys\nimport time\nimport validators\nimport tensorflow as tf\n\n\n\n\n\ndef resize_image(img, height=224, width=224):\n im = resize(img, (height, width, 3))\n im_arr = im.reshape((height, width, 3))\n return im_arr\n #return im_arr\n\ndef remove_background(img):\n grayscaled = rgb2gray(img)\n img = grayscaled\n print(\"Initial shape: \" + str(grayscaled.shape))\n sobel = filters.sobel(img)\n blurred = filters.gaussian(sobel, sigma=2.0)\n # Create Light Spots\n light_spots = np.array((img > 245).nonzero()).T\n\n # Create dark spots\n dark_spots = np.array((img < 3).nonzero()).T\n\n bool_mask = np.zeros(img.shape, dtype=np.bool)\n bool_mask[tuple(light_spots.T)] = True\n bool_mask[tuple(dark_spots.T)] = True\n seed_mask, num_seeds = ndi.label(bool_mask)\n ws = morphology.watershed(blurred, seed_mask)\n background = max(set(ws.ravel()), key=lambda g: np.sum(ws == g))\n background_mask = (ws == background)\n cleaned = img * ~background_mask\n return cleaned\n\ndef save_history(history, prefix):\n if 'acc' not in history.history:\n return\n\n if not os.path.exists(config.plots_dir):\n os.mkdir(config.plots_dir)\n\n img_path = os.path.join(config.plots_dir, '{}-%s.jpg'.format(prefix))\n\n # summarize history for accuracy\n plt.plot(history.history['acc'])\n plt.plot(history.history['val_acc'])\n plt.title('model accuracy')\n plt.ylabel('accuracy')\n plt.xlabel('epoch')\n plt.legend(['train', 'test'], loc='upper left')\n plt.savefig(img_path % 'accuracy')\n plt.close()\n\n # summarize history for loss\n plt.plot(history.history['loss'])\n plt.plot(history.history['val_loss'])\n plt.title('model loss')\n plt.ylabel('loss')\n plt.xlabel('epoch')\n plt.legend(['train', 'test'], loc='upper right')\n plt.savefig(img_path % 'loss')\n plt.close()\n\n\n#def plot_confusion_matrix(cm, classes, normalize=False, title='Confusion matrix', cmap=plt.cm.Blues):\ndef plot_confusion_matrix(cm, classes, normalize=False, title='Confusion matrix'):\n \"\"\"\n This function prints and plots the confusion matrix.\n Normalization can be applied by setting `normalize=True`.\n \"\"\"\n confusion_matrix_dir = './confusion_matrix_plots'\n if not os.path.exists(confusion_matrix_dir):\n os.mkdir(confusion_matrix_dir)\n\n plt.cla()\n plt.figure()\n plt.imshow(cm, interpolation='nearest', cmap=cmap)\n plt.title(title)\n plt.colorbar()\n tick_marks = np.arange(len(classes))\n plt.xticks(tick_marks, classes, rotation=45)\n plt.yticks(tick_marks, classes)\n\n if normalize:\n cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis]\n print(\"Normalized confusion matrix\")\n else:\n print('Confusion matrix, without normalization')\n\n print(cm)\n\n thresh = cm.max() / 2.\n for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])):\n plt.text(j, i, cm[i, j],\n horizontalalignment=\"center\",\n color=\"#BFD1D4\" if cm[i, j] > thresh else \"black\")\n\n plt.tight_layout()\n plt.ylabel('True label')\n plt.xlabel('Predicted label')\n\n if normalize:\n plt.savefig(os.path.join(confusion_matrix_dir, 'normalized.jpg'))\n else:\n plt.savefig(os.path.join(confusion_matrix_dir, 'without_normalization.jpg'))\n\n\ndef get_dir_imgs_number(dir_path):\n allowed_extensions = ['*.png', '*.jpg', '*.jpeg', '*.bmp']\n number = 0\n for e in allowed_extensions:\n number += len(glob.glob(os.path.join(dir_path, e)))\n return number\n\n\ndef set_samples_info():\n \"\"\"Walks through the train and valid directories\n and returns number of images\"\"\"\n white_list_formats = {'png', 'jpg', 'jpeg', 'bmp'}\n dirs_info = {config.train_dir: 0, config.validation_dir: 0}\n for d in dirs_info:\n iglob_iter = glob.iglob(d + '**/*.*')\n for i in iglob_iter:\n filename, file_extension = os.path.splitext(i)\n if file_extension[1:] in white_list_formats:\n dirs_info[d] += 1\n\n config.nb_train_samples = dirs_info[config.train_dir]\n config.nb_validation_samples = dirs_info[config.validation_dir]\n\n\ndef get_class_weight(d):\n white_list_formats = {'png', 'jpg', 'jpeg', 'bmp'}\n class_number = dict()\n dirs = sorted([o for o in os.listdir(d) if os.path.isdir(os.path.join(d, o))])\n k = 0\n for class_name in dirs:\n class_number[k] = 0\n iglob_iter = glob.iglob(os.path.join(d, class_name, '*.*'))\n for i in iglob_iter:\n _, ext = os.path.splitext(i)\n if ext[1:] in white_list_formats:\n class_number[k] += 1\n k += 1\n\n total = np.sum(list(class_number.values()))\n max_samples = np.max(list(class_number.values()))\n mu = 1. / (total / float(max_samples))\n keys = class_number.keys()\n class_weight = dict()\n for key in keys:\n score = math.log(mu * total / float(class_number[key]))\n class_weight[key] = score if score > 1. else 1.\n\n return class_weight\n\n\ndef set_classes_from_train_dir():\n \"\"\"Returns classes based on directories in train directory\"\"\"\n d = config.train_dir\n config.classes = sorted([o for o in os.listdir(d) if os.path.isdir(os.path.join(d, o))])\n\n\ndef override_keras_directory_iterator_next():\n \"\"\"Overrides .next method of DirectoryIterator in Keras\n to reorder color channels for images from RGB to BGR\"\"\"\n from keras.preprocessing.image import DirectoryIterator\n\n original_next = DirectoryIterator.next\n\n # do not allow to override one more time\n if 'custom_next' in str(original_next):\n return\n\n def custom_next(self):\n batch_x, batch_y = original_next(self)\n batch_x = batch_x[:, ::-1, :, :]\n return batch_x, batch_y\n\n DirectoryIterator.next = custom_next\n\n\ndef get_classes_in_keras_format():\n if config.classes:\n return dict(zip(config.classes, range(len(config.classes))))\n return None\n\n\ndef get_model_class_instance(*args, **kwargs):\n module = importlib.import_module(\"models.{}\".format(config.model))\n return module.inst_class(*args, **kwargs)\n\n\ndef get_activation_function(m, layer):\n x = [m.layers[0].input, K.learning_phase()]\n y = [m.get_layer(layer).output]\n return K.function(x, y)\n\n\ndef get_activations(activation_function, X_batch):\n activations = activation_function([X_batch, 0])\n return activations[0][0]\n\n\ndef save_activations(model, inputs, files, layer, batch_number):\n all_activations = []\n ids = []\n af = get_activation_function(model, layer)\n for i in range(len(inputs)):\n acts = get_activations(af, [inputs[i]])\n all_activations.append(acts)\n ids.append(files[i].split('/')[-2])\n\n submission = pd.DataFrame(all_activations)\n submission.insert(0, 'class', ids)\n submission.reset_index()\n if batch_number > 0:\n submission.to_csv(config.activations_path, index=False, mode='a', header=False)\n else:\n submission.to_csv(config.activations_path, index=False)\n\n\ndef lock():\n if os.path.exists(config.lock_file):\n exit('Previous process is not yet finished.')\n\n with open(config.lock_file, 'w') as lock_file:\n lock_file.write(str(os.getpid()))\n\n\ndef unlock():\n if os.path.exists(config.lock_file):\n os.remove(config.lock_file)\n\n\ndef is_keras2():\n return keras.__version__.startswith('2')\n\n\ndef get_keras_backend_name():\n try:\n return K.backend()\n except AttributeError:\n return K._BACKEND\n\n\ndef set_img_format():\n try:\n if K.backend() == 'theano':\n K.set_image_data_format('channels_first')\n else:\n K.set_image_data_format('channels_last')\n except AttributeError:\n if K._BACKEND == 'theano':\n K.set_image_dim_ordering('th')\n else:\n K.set_image_dim_ordering('tf')\n\ndef load_graph(model_file):\n graph = tf.Graph()\n graph_def = tf.GraphDef()\n\n with open(model_file, \"rb\") as f:\n graph_def.ParseFromString(f.read())\n with graph.as_default():\n tf.import_graph_def(graph_def)\n\n return graph\n\ndef read_tensor_from_image_file(file_name, input_height=299, input_width=299, input_mean=0, input_std=255):\n\n input_name = \"file_reader\"\n output_name = \"normalized\"\n filename = None\n\n if validators.url(file_name):\n filename = './models/mobilenet/tmp/' + file_name.split('/')[-1]\n urllib.request.urlretrieve(file_name, filename)\n file_name = filename\n\n file_reader = tf.read_file(file_name, input_name)\n\n if file_name.endswith(\".png\"):\n image_reader = tf.image.decode_png(file_reader, channels = 3, name='png_reader')\n elif file_name.endswith(\".gif\"):\n image_reader = tf.squeeze(tf.image.decode_gif(file_reader, name='gif_reader'))\n elif file_name.endswith(\".bmp\"):\n image_reader = tf.image.decode_bmp(file_reader, name='bmp_reader')\n else:\n image_reader = tf.image.decode_jpeg(file_reader, channels = 3, name='jpeg_reader')\n\n float_caster = tf.cast(image_reader, tf.float32)\n dims_expander = tf.expand_dims(float_caster, 0);\n resized = tf.image.resize_bilinear(dims_expander, [input_height, input_width])\n normalized = tf.divide(tf.subtract(resized, [input_mean]), [input_std])\n sess = tf.Session()\n result = sess.run(normalized)\n\n\n\n # Remove tmp file\n if filename != None:\n if os.path.exists(filename):\n os.remove(filename)\n\n return result\n\ndef load_labels(label_file):\n label = []\n proto_as_ascii_lines = tf.gfile.GFile(label_file).readlines()\n for l in proto_as_ascii_lines:\n label.append(l.rstrip())\n return label\n","sub_path":"util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":10195,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"393734036","text":"import logging\n\nfrom PyQt5 import QtCore, QtWidgets\n\nfrom .projectsetup_ui import Ui_Form\nfrom ...core.mixins import ToolWindow\nfrom ....core.instrument.privileges import PRIV_PROJECTMAN\nfrom ....core.services.accounting import Accounting\nfrom ....core.utils.inhibitor import Inhibitor\n\nlogger = logging.getLogger(__name__)\nlogger.setLevel(logging.DEBUG)\n\n\nclass ProjectSetup(QtWidgets.QWidget, Ui_Form, ToolWindow):\n required_privilege = PRIV_PROJECTMAN\n\n def __init__(self, *args, **kwargs):\n credo = kwargs.pop('credo')\n QtWidgets.QWidget.__init__(self, *args, **kwargs)\n self.setupToolWindow(credo=credo)\n self._updating_ui = Inhibitor(max_inhibit=1)\n self._acc_connections = []\n self.setupUi(self)\n\n def setupUi(self, Form):\n Ui_Form.setupUi(self, Form)\n acc = self.credo.services['accounting']\n assert isinstance(acc, Accounting)\n self.listWidget.addItems(sorted(acc.get_projectids()))\n self.listWidget.item(0).setSelected(True)\n self.addPushButton.clicked.connect(self.onAddProject)\n self.removePushButton.clicked.connect(self.onRemoveProject)\n self.renamePushButton.clicked.connect(self.onRenameProject)\n self._acc_connections = [acc.connect('project-changed', self.onProjectChanged)]\n self.listWidget.itemSelectionChanged.connect(self.onProjectSelected)\n self.updatePushButton.clicked.connect(self.onUpdateProject)\n self.projectIDLineEdit.textChanged.connect(self.onProjectIDChanged)\n self.proposerLineEdit.textChanged.connect(self.onProposerNameChanged)\n self.projectTitleLineEdit.textChanged.connect(self.onProjectTitleChanged)\n self.addPushButton.setEnabled(True)\n self.removePushButton.setEnabled(False)\n self.updatePushButton.setEnabled(False)\n self.renamePushButton.setEnabled(False)\n self.onProjectSelected()\n\n def onProjectIDChanged(self):\n acc = self.credo.services['accounting']\n assert isinstance(acc, Accounting)\n self.renamePushButton.setEnabled(True)\n\n def onProjectTitleChanged(self):\n if not self._updating_ui:\n self.updatePushButton.setEnabled(True)\n\n def onProposerNameChanged(self):\n if not self._updating_ui:\n self.updatePushButton.setEnabled(True)\n\n def onUpdateProject(self):\n logger.debug('Updating project')\n acc = self.credo.services['accounting']\n assert isinstance(acc, Accounting)\n acc.update_project(self.selectedProjectName(),\n self.projectTitleLineEdit.text(),\n self.proposerLineEdit.text())\n self.updatePushButton.setEnabled(False)\n\n def cleanup(self):\n for c in self._acc_connections:\n self.credo.services['accounting'].disconnect(c)\n self._acc_connections = []\n super().cleanup()\n\n def onAddProject(self):\n acc = self.credo.services['accounting']\n assert isinstance(acc, Accounting)\n index = 0\n projectname=None\n while True:\n index += 1\n projectname = 'Untitled {:d}'.format(index)\n if projectname not in acc.get_projectids():\n break\n acc.new_project(projectname, '', '')\n # the previous command emits the project-changed signal.\n self.selectProject(projectname)\n\n def onRemoveProject(self):\n acc = self.credo.services['accounting']\n assert isinstance(acc, Accounting)\n try:\n acc.delete_project(self.selectedProjectName())\n except ValueError as ve:\n QtWidgets.QMessageBox.critical(self, 'Error while removing project', ve.args[0])\n self.onProjectChanged(acc)\n self.onProjectSelected()\n\n def onRenameProject(self):\n logger.debug('onRenameProject()')\n self.renamePushButton.setEnabled(False)\n acc = self.credo.services['accounting']\n assert isinstance(acc, Accounting)\n selected = self.selectedProjectName()\n newname = self.projectIDLineEdit.text()\n try:\n acc.rename_project(selected, newname)\n except ValueError as ve:\n QtWidgets.QMessageBox.critical(self, 'Cannot rename project',\n 'Cannot rename project: {}'.format(ve.args[0]))\n return\n self.selectProject(newname)\n\n def selectProject(self, projectid):\n item=self.listWidget.findItems(projectid, QtCore.Qt.MatchExactly)[0]\n item.setSelected(True)\n self.listWidget.scrollToItem(item)\n\n def onProjectChanged(self, acc: Accounting):\n \"\"\"Callback function, called when the project list is changed: either a project is modified\n or one is added or removed\"\"\"\n logger.debug('onProjectChanged()')\n with self._updating_ui:\n try:\n selected = self.selectedProjectName() # try to keep the currently selected project\n # update the project name list in the list widget\n self.listWidget.clear()\n self.listWidget.addItems(sorted(acc.get_projectids()))\n except IndexError:\n return\n try:\n self.selectProject(selected)\n except IndexError:\n # if the project has been removed, select the first one.\n self.listWidget.setCurrentRow(0)\n return\n\n def selectedProjectName(self):\n return self.listWidget.selectedItems()[0].data(QtCore.Qt.DisplayRole)\n\n def selectedProject(self):\n return self.credo.services['accounting'].get_project(self.selectedProjectName())\n\n def onProjectSelected(self):\n if self._updating_ui.inhibited:\n logger.debug('Already inhibited')\n return\n with self._updating_ui:\n try:\n self.updatePushButton.setEnabled(False)\n name = self.selectedProjectName()\n acc = self.credo.services['accounting']\n assert isinstance(acc, Accounting)\n prj = acc.get_project(name)\n self.projectIDLineEdit.setText(prj.projectid)\n self.projectTitleLineEdit.setText(prj.projectname)\n self.proposerLineEdit.setText(prj.proposer)\n self.removePushButton.setEnabled(True)\n except IndexError:\n self.projectIDLineEdit.setText('')\n self.projectTitleLineEdit.setText('')\n self.proposerLineEdit.setText('')\n self.removePushButton.setEnabled(True)\n","sub_path":"cct/qtgui/setup/project/projectsetup.py","file_name":"projectsetup.py","file_ext":"py","file_size_in_byte":6581,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"211726414","text":"import socket\nimport sys\n\nPORT = 3000\n\ninfos = socket.getaddrinfo('127.0.0.1', PORT)\n\nstream_info = [i for i in infos if i[1] == socket.SOCK_STREAM][0]\n# for sock_data in infos:\n# if sock_data[1] == socket.SOCK_STREAM:\n# stream_info = sock_data # 5-tuple repr of socket\n\n# 5-tuple => (Family, Kind, Protocol, '', Endpoint)\n\nclient = socket.socket(*stream_info[:3])\n# client = socket.socket(\n# stream_info[0], # Family\n# stream_info[1], # Kind\n# stream_info[2], # Protocol\n# )\n\n\nclient.connect(stream_info[-1]) # ('127.0.0.1', 3000)\n\nmessage = sys.argv[1]\n\nclient.sendall(message.encode('utf8'))\n\nbuffer_length = 8\n\nmessage_complete = False\n\nserver_msg = b''\nwhile not message_complete:\n part = client.recv(buffer_length)\n server_msg += part\n if len(part) < buffer_length:\n break\n\nserver_msg = server_msg.decode('utf8')\nprint(server_msg)\n\nclient.close()\n","sub_path":"12-protocols-http/demos/00-code-review/client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":898,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"463820666","text":"import sagemaker as sage\n\n\ndef train_and_deploy():\n\n # AmazonSageMaker ExecutionRole\n role = \"arn:aws:iam:\"\n\n sess = sage.Session()\n account = sess.boto_session.client('sts').get_caller_identity()['Account']\n\n # path to the s3 location to store the models\n bucket_path = \"s3://mdb-sagemaker/models/\"\n region = sess.boto_session.region_name\n\n # location of the mindsdb container\n image = '{}.dkr.ecr.{}.amazonaws.com/mindsdb_lts:latest'.format(account, region)\n\n # note that to_predict is required in hyperparameters\n mindsdb_impl = sage.estimator.Estimator(image,\n role, 1, 'ml.m4.xlarge',\n output_path=bucket_path,\n sagemaker_session=sess,\n base_job_name=\"mindsdb-lts-sdk\",\n hyperparameters={\"to_predict\": \"Class\"})\n\n # read data from \n dataset_location = 's3://mdb-sagemaker/diabetes.csv'\n mindsdb_impl.fit(dataset_location)\n print('DONE')\n\n # deploy container\n predictor = mindsdb_impl.deploy(1, 'ml.m4.xlarge', endpoint_name='mindsdb-impl')\n\n with open('test_data/diabetes-test.csv', 'r') as reader:\n when_data = reader.read()\n result = predictor.predict(when_data).decode('utf-8')\n print(\"Result: \", result)\n return result\n\n\nif __name__ == \"__main__\":\n train_and_deploy()","sub_path":"local_test/sage_sdk.py","file_name":"sage_sdk.py","file_ext":"py","file_size_in_byte":1384,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"207274252","text":"#!/usr/bin/env python3\nfrom gpiozero import OutputDevice\nfrom time import sleep\n\n#chip pull up\nch_pd = OutputDevice(4, True)\n# reset on pin 3, active low\nrst = OutputDevice(3, False)\n# flash mode select on pin 0, active low\nflash = OutputDevice(0, False)\n\nch_pd.on()\nflash.on()\nsleep(0.5)\nrst.on()\nsleep(0.5)\nrst.off()\nsleep(0.5)\nflash.off()\nrst.close()\nflash.close()\n","sub_path":"src/main/python/flash.py","file_name":"flash.py","file_ext":"py","file_size_in_byte":368,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"590713332","text":"# Copyright 2019 The Chromium OS Authors. All rights reserved.\n# Use of this source code is governed by a BSD-style license that can be\n# found in the LICENSE file.\n\"\"\"Ensure servo v4 manufacturing script is robust.\"\"\"\n\n\nimport unittest\n\nimport mfg_servo_v4 as mfg\n\nclass TestMfgServoV4(unittest.TestCase):\n\n\n def setUp(self):\n \"\"\"Set up serialname stubs.\"\"\"\n unittest.TestCase.setUp(self)\n # G is one of the valid prefixes i.e. known manufacteurer.\n self.supplier = 'G'\n # A valid suffix is purely digits for example.\n self.suffix = '9999'\n # These three attributes are valid parts of the YYMMDD component.\n self.year = '19'\n self.month = '09'\n self.day = '17'\n\n def buildSerial(self):\n \"\"\"Return serialname from components.\"\"\"\n return self.supplier + self.year + self.month + self.day + self.suffix\n\n def test_SerialNumberRegexSupplierInvalid(self):\n \"\"\"Ensure regex rejects unknown supplier.\"\"\"\n self.supplier = 'Z'\n assert not mfg.RE_SERIALNO.match(self.buildSerial())\n\n def test_SerialNumberRegexDatesValid(self):\n \"\"\"Ensure date-checking portion of regex WAI.\"\"\"\n assert mfg.RE_SERIALNO.match(self.buildSerial())\n\n def test_SerialNumberRegexDatesInvalidDay(self):\n \"\"\"Ensure date-checking portion of regex rejects invalid day.\"\"\"\n # Check invalid day\n self.day = '00'\n assert not mfg.RE_SERIALNO.match(self.buildSerial())\n # Check non-existant 2-digit day.\n self.day = '32'\n assert not mfg.RE_SERIALNO.match(self.buildSerial())\n # Check ensure 3-digit day is rejected.\n self.day = '111'\n assert not mfg.RE_SERIALNO.match(self.buildSerial())\n\n def test_SerialNumberRegexDatesInvalidMonth(self):\n \"\"\"Ensure date-checking portion of regex rejects invalid month.\"\"\"\n # Check invalid month\n self.month = '00'\n assert not mfg.RE_SERIALNO.match(self.buildSerial())\n # Check non-existant 2-digit month.\n self.month = '13'\n assert not mfg.RE_SERIALNO.match(self.buildSerial())\n # Check ensure 3-digit month is rejected.\n self.month = '111'\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"servo/scripts/servo_mfg/mfg_servo_v4_unittest.py","file_name":"mfg_servo_v4_unittest.py","file_ext":"py","file_size_in_byte":2097,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"588548344","text":"\"\"\"\nA VGG16 implementation.\n\"\"\"\nimport tensorflow as tf\nimport numpy as np\n\nfrom models.nn import NN\n\n\nclass VGG16(NN):\n \"\"\"\n A CNN model consisting of 16 layers.\n\n This model takes a 224x224 image of 3 channels [224x224x3] as an input and\n produces an output vector of 1000 dimensions.\n \"\"\"\n @staticmethod\n def create_variables(from_file=None, trainable=True):\n \"\"\"\n Create all variables for VGG16.\n\n Args:\n from_file: A file that stores weights.\n Returns:\n A dictionary of variables.\n \"\"\"\n def _create_new_variables():\n def _weight_variable(shape):\n init = tf.truncated_normal(shape, stddev=0.1)\n return tf.Variable(init)\n\n def _bias_variable(shape):\n init = tf.constant(0.1, shape=shape)\n return tf.Variable(init)\n\n return _weight_variable, _bias_variable\n\n def _load_variables():\n data = np.load(from_file)\n class Local:\n keys = sorted(data.keys())\n idx = 0\n\n def _weight_variable(shape):\n init = tf.constant(data[Local.keys[Local.idx]])\n Local.idx += 1\n return tf.Variable(init, trainable=trainable)\n\n def _bias_variable(shape):\n init = tf.constant(data[Local.keys[Local.idx]])\n Local.idx += 1\n return tf.Variable(init, trainable=trainable)\n\n return _weight_variable, _bias_variable\n\n\n variables = {}\n\n if from_file == None:\n _weight_variable, _bias_variable = _create_new_variables()\n else:\n _weight_variable, _bias_variable = _load_variables()\n\n # First group: conv + relu, conv + relu, pooling\n variables[\"11K\"] = _weight_variable([3, 3, 3, 64])\n variables[\"11b\"] = _bias_variable([64])\n variables[\"12K\"] = _weight_variable([3, 3, 64, 64])\n variables[\"12b\"] = _bias_variable([64])\n\n # Second group: conv + relu, conv + relu, pooling\n variables[\"21K\"] = _weight_variable([3, 3, 64, 128])\n variables[\"21b\"] = _bias_variable([128])\n variables[\"22K\"] = _weight_variable([3, 3, 128, 128])\n variables[\"22b\"] = _bias_variable([128])\n\n # Third group: conv + relu, conv + relu, conv + relu, pooling\n variables[\"31K\"] = _weight_variable([3, 3, 128, 256])\n variables[\"31b\"] = _bias_variable([256])\n variables[\"32K\"] = _weight_variable([3, 3, 256, 256])\n variables[\"32b\"] = _bias_variable([256])\n variables[\"33K\"] = _weight_variable([3, 3, 256, 256])\n variables[\"33b\"] = _bias_variable([256])\n\n # Forth group: conv + relu, conv + relu, conv + relu, pooling\n variables[\"41K\"] = _weight_variable([3, 3, 256, 512])\n variables[\"41b\"] = _bias_variable([512])\n variables[\"42K\"] = _weight_variable([3, 3, 512, 512])\n variables[\"42b\"] = _bias_variable([512])\n variables[\"43K\"] = _weight_variable([3, 3, 512, 512])\n variables[\"43b\"] = _bias_variable([512])\n\n # Fifth group : conv + relu, conv + relu, conv + relu, pooling\n variables[\"51K\"] = _weight_variable([3, 3, 512, 512])\n variables[\"51b\"] = _bias_variable([512])\n variables[\"52K\"] = _weight_variable([3, 3, 512, 512])\n variables[\"52b\"] = _bias_variable([512])\n variables[\"53K\"] = _weight_variable([3, 3, 512, 512])\n variables[\"53b\"] = _bias_variable([512])\n\n # 3 fully connected\n variables[\"6W\"] = _weight_variable([7 * 7 * 512, 4096])\n variables[\"6b\"] = _bias_variable([4096])\n variables[\"7W\"] = _weight_variable([4096, 4096])\n variables[\"7b\"] = _bias_variable([4096])\n variables[\"8W\"] = _weight_variable([4096, 1000])\n variables[\"8b\"] = _weight_variable([1000])\n\n return variables\n\n\n @staticmethod\n def create_model(variables=create_variables.__func__(), name=\"\"):\n \"\"\"\n Create an instance of VGG16.\n\n Params:\n variables (dict): A dictionary of variables.\n Returns:\n An instance of VGG16.\n \"\"\"\n return VGG16(variables, name)\n\n\n def forward(self, inputs):\n \"\"\"\n Get an output tensor corresponding to the input tensor.\n\n Params:\n inputs: An image of 224x224x3 or an equivalent tensor.\n Returns:\n A tensor of [1000].\n \"\"\"\n def _apply_convolution(inputs, kernel, bias):\n return tf.nn.relu(\n tf.nn.conv2d(\n inputs,\n kernel,\n strides=[1, 1, 1, 1],\n padding=\"SAME\") + bias)\n\n def _apply_pooling(inputs):\n return tf.nn.max_pool(\n inputs,\n ksize=[1, 2, 2, 1],\n strides=[1, 2, 2, 1],\n padding=\"SAME\")\n\n def _apply_fc_relu(inputs, weight, bias):\n return tf.nn.relu(tf.matmul(inputs, weight) + bias)\n\n def _get_variable(name):\n return self._variables[name]\n\n conv11 = _apply_convolution(inputs, \n _get_variable(\"11K\"),\n _get_variable(\"11b\")) \n conv12 = _apply_convolution(conv11,\n _get_variable(\"12K\"),\n _get_variable(\"12b\"))\n pool1 = _apply_pooling(conv12)\n\n conv21 = _apply_convolution(pool1,\n _get_variable(\"21K\"),\n _get_variable(\"21b\"))\n conv22 = _apply_convolution(conv21,\n _get_variable(\"22K\"),\n _get_variable(\"22b\"))\n pool2 = _apply_pooling(conv22)\n\n conv31 = _apply_convolution(pool2,\n _get_variable(\"31K\"),\n _get_variable(\"31b\"))\n conv32 = _apply_convolution(conv31,\n _get_variable(\"32K\"),\n _get_variable(\"32b\"))\n conv33 = _apply_convolution(conv32,\n _get_variable(\"33K\"),\n _get_variable(\"33b\"))\n pool3 = _apply_pooling(conv33)\n\n conv41 = _apply_convolution(pool3,\n _get_variable(\"41K\"),\n _get_variable(\"41b\"))\n conv42 = _apply_convolution(conv41,\n _get_variable(\"42K\"),\n _get_variable(\"42b\"))\n conv43 = _apply_convolution(conv42,\n _get_variable(\"43K\"),\n _get_variable(\"43b\"))\n pool4 = _apply_pooling(conv43)\n\n conv51 = _apply_convolution(pool4,\n _get_variable(\"51K\"),\n _get_variable(\"51b\"))\n conv52 = _apply_convolution(conv51,\n _get_variable(\"52K\"),\n _get_variable(\"52b\"))\n conv53 = _apply_convolution(conv52,\n _get_variable(\"53K\"),\n _get_variable(\"53b\"))\n pool5 = _apply_pooling(conv53)\n\n flat = tf.reshape(pool5, [-1, 7 * 7 * 512])\n\n fc1 = _apply_fc_relu(flat,\n _get_variable(\"6W\"),\n _get_variable(\"6b\"))\n fc2 = _apply_fc_relu(fc1,\n _get_variable(\"7W\"),\n _get_variable(\"7b\"))\n fc3 = _apply_fc_relu(fc2,\n _get_variable(\"8W\"),\n _get_variable(\"8b\"))\n\n return fc3\n","sub_path":"mvcnn/models/vgg16_1000.py","file_name":"vgg16_1000.py","file_ext":"py","file_size_in_byte":7874,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"70531506","text":"import pytest\n\nfrom robot_server.service.session.models.command import \\\n CalibrationCommand, BasicSessionCommand\nfrom robot_server.service.session.models.common import EmptyModel, \\\n JogPosition\nfrom robot_server.service.session.models.session import BasicSession\n\n\ndef test_command_type_validation_jog():\n c = BasicSessionCommand(**{'command': CalibrationCommand.jog,\n 'data': {'vector': [1, 2, 3]}})\n assert c.data == JogPosition(vector=(1, 2, 3,))\n\n\ndef test_command_type_validation_jog_fail():\n with pytest.raises(ValueError):\n BasicSessionCommand(**{'command': CalibrationCommand.jog,\n 'data': {}})\n\n\ndef test_command_type_empty():\n \"\"\"Test that we create command correctly for\n commands that have no added data.\"\"\"\n c = BasicSessionCommand(\n **{'command': CalibrationCommand.load_labware,\n 'data': {}})\n assert c.data == EmptyModel()\n\n\n@pytest.mark.parametrize(argnames=\"create_params\",\n argvalues=[\n {'createParams': None},\n {'createParams': {}},\n {}\n ])\ndef test_basic_session_type_validation_no_create_params(create_params):\n \"\"\"Test that when create params have no mandatory members we accept null,\n and {}\"\"\"\n body = {\n \"sessionType\": \"null\",\n }\n body.update(create_params)\n\n session = BasicSession(**body)\n assert session.createParams == create_params.get('createParams')\n\n\n@pytest.mark.parametrize(argnames=\"create_params\",\n argvalues=[\n {'createParams': None},\n {'createParams': {}},\n {}\n ])\ndef test_basic_session_type_validation_with_create_params(create_params):\n \"\"\"Test that when create params have mandatory members we reject invalid\n createParams\"\"\"\n body = {\n \"sessionType\": \"protocol\",\n }\n body.update(create_params)\n\n with pytest.raises(ValueError):\n BasicSession(**body)\n","sub_path":"robot-server/tests/service/session/test_models.py","file_name":"test_models.py","file_ext":"py","file_size_in_byte":2127,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"347003206","text":"\"\"\"Test for letsencrypt_plesk.api_client.\"\"\"\nimport unittest\nimport mock\nimport pkg_resources\nimport os\n\nfrom letsencrypt import errors\nfrom letsencrypt_plesk import api_client\n\n\nclass PleskApiClientTest(unittest.TestCase):\n TEST_DATA_PATH = pkg_resources.resource_filename(\n \"letsencrypt_plesk.tests\", \"testdata\")\n\n def setUp(self):\n super(PleskApiClientTest, self).setUp()\n self.api_client = api_client.PleskApiClient()\n self.api_client.PSA_PATH = os.path.join(\n self.TEST_DATA_PATH, 'psa')\n self.api_client.CLI_PATH = os.path.join(\n self.TEST_DATA_PATH, 'psa', 'bin')\n\n def test_ssl_port_found(self):\n uri = self.api_client.get_api_uri(\n os.path.join(self.TEST_DATA_PATH, 'conf/plesk.ssl.conf.txt'))\n self.assertEqual(uri, \"https://127.0.0.1:1234/enterprise/control/agent.php\")\n\n def test_ssl_port_priority(self):\n uri = self.api_client.get_api_uri(\n os.path.join(self.TEST_DATA_PATH, 'conf/plesk.ssl-priority.conf.txt'))\n self.assertEqual(uri, \"https://127.0.0.1:1234/enterprise/control/agent.php\")\n\n def test_non_ssl_port_found(self):\n uri = self.api_client.get_api_uri(\n os.path.join(self.TEST_DATA_PATH, 'conf/plesk.conf.txt'))\n self.assertEqual(uri, \"http://127.0.0.1:5678/enterprise/control/agent.php\")\n\n def test_no_config_found(self):\n uri = self.api_client.get_api_uri(\n os.path.join(self.TEST_DATA_PATH, 'conf/plesk.empty.conf.txt'))\n self.assertEqual(uri, \"https://127.0.0.1:8443/enterprise/control/agent.php\")\n\n def test_no_config_file_found_leads_to_default_port(self):\n uri = self.api_client.get_api_uri(\n os.path.join(self.TEST_DATA_PATH, 'conf/plesk.non-existing.conf.txt'))\n self.assertEqual(uri, \"https://127.0.0.1:8443/enterprise/control/agent.php\")\n\n def test_check_version_supported(self):\n self.api_client.check_version()\n\n def test_check_version_not_supported(self):\n self.api_client.PSA_PATH = os.path.join(\n self.TEST_DATA_PATH, 'psa8')\n self.assertRaises(errors.NotSupportedError,\n self.api_client.check_version)\n\n def test_check_version_not_installed(self):\n self.api_client.PSA_PATH = os.path.join(\n self.TEST_DATA_PATH, 'not_exists')\n self.assertRaises(errors.NoInstallationError,\n self.api_client.check_version)\n\n def test_check_version_with_secret_key(self):\n self.api_client.PSA_PATH = 'unreachable'\n self.api_client.secret_key = '3c4941c1-890b-5690-0c44f037ed1c'\n self.api_client.check_version()\n\n def test_get_secret_key(self):\n self.api_client.secret_key = None\n self.assertEqual('3c4941c1-890b-5690-0c44f037ed1c',\n self.api_client.get_secret_key())\n self.assertTrue(self.api_client.secret_key_created)\n\n def test_get_secret_key_existing(self):\n self.api_client.execute = mock.MagicMock()\n self.api_client.secret_key = '3c4941c1-890b-5690-0c44f037ed1c'\n self.assertEqual('3c4941c1-890b-5690-0c44f037ed1c',\n self.api_client.get_secret_key())\n self.assertFalse(self.api_client.secret_key_created)\n self.api_client.execute.assert_not_called()\n\n def test_execute(self):\n self.api_client.execute(\n os.path.join(self.api_client.CLI_PATH, 'secret_key'), arguments=['--help'])\n\n def test_execute_error(self):\n self.assertRaises(api_client.PleskApiException, self.api_client.execute,\n os.path.join(self.api_client.CLI_PATH, 'secret_key'),\n arguments=['--invalid-argument'])\n\n def test_cleanup(self):\n self.api_client.secret_key = '3c4941c1-890b-5690-0c44f037ed1c'\n self.api_client.secret_key_created = True\n self.api_client.cleanup()\n self.assertEquals(None, self.api_client.secret_key)\n self.assertFalse(self.api_client.secret_key_created)\n\n def test_cleanup_error(self):\n self.api_client.secret_key = '3c4941c1-890b-5690-0c44f037ed1c'\n self.api_client.secret_key_created = True\n self.api_client.execute = mock.MagicMock(side_effect=api_client.PleskApiException)\n self.api_client.cleanup()\n\n @mock.patch('requests.post')\n def test_request(self, post_mock):\n self.api_client.secret_key = '3c4941c1-890b-5690-0c44f037ed1c'\n self.api_client.get_api_uri = mock.MagicMock(return_value='https://plesk/api')\n post_mock.return_value = mock.MagicMock(text='ok')\n request = {'packet': 'test'}\n expected_request = 'test'\n response = self.api_client.request(request)\n self.assertEqual('ok', response['packet'])\n post_mock.assert_called_once_with('https://plesk/api', data=expected_request,\n headers=mock.ANY, verify=mock.ANY)\n\n def test_dict_to_xml(self):\n request = {'packet': {'test': [{'a': '123'}, {'b': '456'}, {'c': None}]}}\n expected_request = '' \\\n '123456'\n self.assertEqual(expected_request, api_client.DictToXml(request).__str__())\n\n def test_xml_to_dict(self):\n response = \"\"\"\n \n \n error\n \n \n 1\n 2\n 3\n \n \n \"\"\"\n actual_response = api_client.XmlToDict(response)\n self.assertEqual('error', actual_response['packet']['result']['status'])\n self.assertEqual({}, actual_response['packet']['result']['code'])\n self.assertTrue(actual_response['packet']['result']['error'].find('1'))\n self.assertTrue(actual_response['packet']['result']['error'].find('2'))\n self.assertTrue(actual_response['packet']['result']['error'].find('3'))\n\n\nif __name__ == \"__main__\":\n unittest.main() # pragma: no cover\n","sub_path":"letsencrypt_plesk/tests/api_client_test.py","file_name":"api_client_test.py","file_ext":"py","file_size_in_byte":6223,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"565317468","text":"from datetime import datetime\nimport logging\n\nLOGGER = logging.getLogger(\"ai\")\n\n\ndef map_to_objects(rows, constructor):\n return [constructor(**row) for row in rows]\n\n\ndef map_to_object(row, constructor):\n if row is None:\n return None\n\n return constructor(**row)\n\n\nclass Drone:\n\n def __init__(self, id: str = None, drone_id: str = None, optimized: bool = None, glitched: bool = None, trusted_users: str = None, last_activity: datetime = None):\n self.id = id\n self.drone_id = drone_id\n self.optimized = optimized\n self.glitched = glitched\n self.trusted_users = trusted_users\n self.last_activity = last_activity\n\n\nclass Storage:\n\n def __init__(self, id: str, stored_by: str, target_id: str, purpose: str, roles: str, release_time: datetime):\n self.id = id\n self.stored_by = stored_by\n self.target_id = target_id\n self.purpose = purpose\n self.roles = roles\n self.release_time = release_time\n\n\nclass DroneOrder:\n\n def __init__(self, id: str = None, drone_id: str = None, protocol: str = None, finish_time: datetime = None):\n self.id = id\n self.drone_id = drone_id\n self.protocol = protocol\n self.finish_time = finish_time\n","sub_path":"db/data_objects.py","file_name":"data_objects.py","file_ext":"py","file_size_in_byte":1254,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"644930897","text":"\"\"\"\nService class\n------------------\nService object for interfacing with the Pipelines Service API.\n\nThis class instance is used to communicate with a RESTFul service. The `post_job` method\ncreates a new job on the server and `find_job` and `get_jobs` allow you to inspect running\nand past workflow jobs.\n\nNote: This service has not been fully integrated into the SDK and access is still quite raw. \n\n\"\"\"\nimport time\nimport os\n\nfrom typing import Optional, List, Union, Dict\nfrom ...services import BaseService\nfrom ...client import Client\nfrom ...exceptions import NotFound\nfrom .job import PipelineJob\nfrom .exceptions import JobError\nfrom ...packagelocal import package_and_upload\n\nimport logging\n\nSERVICE_PATH = \"pipelines-service\"\n\n\nlog = logging.getLogger(__name__)\n\n\nclass Service(BaseService):\n \"\"\"\n A connection to the pipelines service API server\n \"\"\"\n\n def __init__(self, client: Client, *args, **kwargs) -> None:\n super(Service, self).__init__(client, SERVICE_PATH, *args, **kwargs)\n\n def get_pipelines(self) -> List:\n \"\"\"\n Returns the pipelines available on the current server\n\n Refer to the API documentation for the Pipelines service to see formatting of data.\n\n :return: List of pipelines\n \"\"\"\n resp = self.session.get(self.session.url_from_endpoint(\"pipelines\"))\n pipelines = resp.json()[\"pipelines\"]\n return pipelines\n\n def get_projects(self) -> List:\n \"\"\"\n Returns the projects that have been created on the current server\n\n Refer to the API documentation for the Pipelines service to see formatting of data.\n\n :return: List of projects\n \"\"\"\n resp = self.session.get(self.session.url_from_endpoint(\"projects\"))\n projects = resp.json()[\"projects\"]\n return projects\n\n def find_job(self, job_id: Union[int, str]) -> PipelineJob:\n \"\"\"\n Return a job proxy object\n \"\"\"\n jobs_endpoint = self.session.url_from_endpoint(\"jobs\")\n\n data: Dict = {\"limit\": 1}\n if job_id == \"latest\":\n data[\"user_name\"] = self.current_user.get(\"email\")\n else:\n try:\n data[\"job_id\"] = int(job_id)\n except ValueError:\n raise NotFound(\n \"job_id must be an integer or 'latest', not '%s'\" % job_id\n )\n resp = self.session.get(jobs_endpoint, json=data)\n jobs = resp.json()[\"jobs\"]\n if not jobs:\n raise NotFound(\"Job not found\")\n\n job = jobs[0]\n return PipelineJob(self.session, job[\"job_id\"], job)\n\n def get_jobs(\n self,\n user_name: Optional[str] = None,\n status: Optional[str] = None,\n project: Optional[str] = None,\n pipeline: Optional[str] = None,\n limit: Optional[int] = 50,\n ) -> List[PipelineJob]:\n \"\"\"\n Get a list of jobs satisfying the supplied criteria\n\n :param user_name: The user who created the job\n :param status: Current status of jobs\n :param project: Filter by project\n :param pipeline: Filter by pipeline name\n :param limit: Maximum number of jobs to return\n \"\"\"\n data: Dict = {\"limit\": limit}\n if user_name:\n data[\"user_name\"] = user_name\n if status:\n data[\"status\"] = status\n if project:\n data[\"project_name\"] = project\n if pipeline:\n data[\"pipeline_name\"] = pipeline\n st = time.time()\n resp = self.session.get(self.session.url_from_endpoint(\"jobs\"), json=data)\n jobs = resp.json()[\"jobs\"]\n log.info(\"Retrieved %s jobs in %.2f sec\", len(jobs), time.time() - st)\n ret = []\n for job in jobs:\n ret.append(PipelineJob(self.session, job[\"job_id\"], job))\n return ret\n","sub_path":"nextcode/services/pipelines/service.py","file_name":"service.py","file_ext":"py","file_size_in_byte":3838,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"157205746","text":"import sys\n\ns = input(\"Input the desired size: \")\ntry:\n size = int(s)\nexcept ValueError:\n print(\"Invalid value, giving up...\")\n sys.exit()\nif size <= 0:\n print(\"Invalid value, giving up...\")\n sys.exit()\ntriangle = [None] * (size + 3)\nfor i in range(size + 3):\n triangle[i] = [0] * (size + 1)\ntriangle[1][0] = 1\nfor y in range(1, size + 1):\n for x in range(y + 1):\n triangle[x + 1][y] = triangle[x][y - 1] + triangle[x + 2][y - 1]\n triangle[0][y] = triangle[2][y]\nlines = list()\nlines.append(r'\\documentclass[10pt]{article}' + '\\n')\nlines.append(r'\\usepackage{tikz}' + '\\n')\nlines.append(r'\\pagestyle{empty}' + '\\n')\nlines.append(r'\\begin{document}' + '\\n')\nlines.append(r'\\vspace*{\\fill}' + '\\n')\nlines.append(r'\\begin{center}' + '\\n')\nlines.append(r'\\begin{tikzpicture}[scale=0.047]' + '\\n')\nfor y in range(size + 1):\n for x in range(1, y + 2):\n if triangle[x][y] == 0:\n print(' ', end='')\n else:\n print(triangle[x][y], end='')\n print()\n\nfor y in range(size + 1):\n for x in range(1, y + 2):\n if triangle[x][y] & 1 == 1:\n lines.append(f\"\\\\fill({x-1},{-y * 2}) rectangle({x+1},{2-y * 2});\\n\")\n if x != 1:\n lines.append(f\"\\\\fill({1-x},{-y * 2}) rectangle({3-x},{2-y * 2});\\n\")\nwith open(\"Sierpinski_triangle.tex\", 'w') as f:\n f.writelines(lines)\n","sub_path":"COMP9021/Lab_5/sierpinski_triangle.py","file_name":"sierpinski_triangle.py","file_ext":"py","file_size_in_byte":1367,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"577091419","text":"# https://www.practicepython.org/exercise/2016/03/27/28-max-of-three.html\ndef max_of_three(num1, num2, num3):\n max_num = num1\n \n if num2 > max_num: max_num = num2\n if num3 > max_num: max_num = num3\n \n return f'\\nMax: {max_num}'\n\n\nhow_many_numbers = 3\nnumbers = []\n\nprint('\\nMax of Three!')\n\nfor i in range(how_many_numbers):\n while True:\n try:\n numbers.append(float(input(f'\\nNumber {i+1}: ')))\n break\n except ValueError: print(f'\\nInvalid input! Number {i+1} is not a number')\n\nprint(max_of_three(numbers[0],numbers[2],numbers[2]))","sub_path":"Max_Of_Three.py","file_name":"Max_Of_Three.py","file_ext":"py","file_size_in_byte":589,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"406853384","text":"from . import FixtureTest\n\n\nclass Funicular(FixtureTest):\n def test_funicular(self):\n self.load_fixtures(['https://www.openstreetmap.org/way/393550019'])\n\n self.assert_has_feature(\n 16, 10481, 25345, 'roads',\n {'kind': 'rail', 'kind_detail': 'funicular'})\n","sub_path":"integration-test/510-funicular.py","file_name":"510-funicular.py","file_ext":"py","file_size_in_byte":295,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"109338850","text":"from django.shortcuts import render, redirect, get_object_or_404\nfrom .models import Review, Comment\nfrom .forms import ReviewForm, CommentForm\nfrom django.views.decorators.http import require_safe, require_http_methods, require_POST\nfrom django.contrib.auth.decorators import login_required\n\n@require_safe\ndef index(request):\n\treviews = Review.objects.order_by('-pk')\n\tcontext = {\n\t\t'reviews' : reviews,\n\t}\t\n\treturn render(request, 'community/index.html', context)\n\n@require_safe\ndef detail(request, review_pk):\n\treview = get_object_or_404(Review, pk=review_pk)\n\tcomment_form = CommentForm()\n\tcomments = review.comment_set.all()\n\tcontext = {\n\t\t'review' : review,\n\t\t'comment_form' : comment_form,\n\t\t'comments' : comments,\n\t}\n\treturn render(request, 'community/detail.html', context)\n\n@login_required\n@require_http_methods(['GET', 'POST'])\ndef create(request):\n\tif request.method == 'POST':\n\t\tform = ReviewForm(request.POST)\n\t\tif form.is_valid():\n\t\t\treview = form.save(commit=False)\n\t\t\treview.user = request.user\n\t\t\treview.save()\n\t\t\treturn redirect('community:detail', review.pk)\n\telse:\n\t\tform = ReviewForm()\n\tcontext = {\n\t\t'form' : form,\n\t}\n\treturn render(request, 'community/create.html', context)\n\n\n@require_POST\ndef comments_create(request, review_pk):\n\tif request.user.is_authenticated:\n\t\treview = get_object_or_404(Review, pk=review_pk)\n\t\tcomment_form = CommentForm(request.POST)\n\t\tif comment_form.is_valid():\n\t\t\tcomment = comment_form.save(commit=False)\n\t\t\tcomment.review = review\n\t\t\tcomment.save()\n\t\t\treturn redirect('community:detail', review.pk)\n\t\tcontext = {\n\t\t\t'comment_form': comment_form,\n\t\t\t'review' : review,\n\t\t}\n\t\treturn render(request, 'community/detail.html', context)\n\treturn redirect('accounts:login')\n\n\t\n","sub_path":"pjt/pjt06/pjt06/community/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1725,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"57325951","text":"def shorting(a):\n for i in range (len(a)-1,0,-1):\n print (\"Proses ke \",len(a)-i,\"Jumlah Iterasi =\",i)\n for j in range (i):\n if a[j] > a[j+1]:\n a[j],a[j+1] = a[j+1],a[j]\n print (a)\n tes = True\n for j in range (i):\n if a[j]<=a[j+1]:\n tes = tes and True\n else:\n tes = tes and False\n if tes:\n print (\"Data terurut =\",a)\n return a\n \n \nshorting([100,34,1,7,2,4,6,77,4,54])\n\n","sub_path":"Buble short/ascending(bener).py","file_name":"ascending(bener).py","file_ext":"py","file_size_in_byte":543,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"69252045","text":"import boto3\nimport configparser\nimport os\nimport pyspark.sql.functions as F\nfrom pyspark.sql import types as T\nfrom pyspark.sql import SparkSession\nfrom pyspark.sql.functions import udf, col\n\nconfig = configparser.ConfigParser()\nconfig.read('/home/workspace/dwh.cfg')\nos.environ[\"AWS_ACCESS_KEY_ID\"] = config.get(\"AWS_CREDENTIALS\", \"AWS_ACCESS_KEY_ID\")\nos.environ[\"AWS_SECRET_ACCESS_KEY\"] = config.get(\"AWS_CREDENTIALS\", \"AWS_SECRET_ACCESS_KEY\")\nos.environ[\"s3_bucket\"] = config.get(\"S3\", \"s3_bucket\")\n\ndef check(path, table,spark,SQL):\n \n print (\"======================================\")\n checkvar=path + table\n print(\"Check Activated : \" , checkvar)\n print(\"SQL Query : \" , SQL)\n \n temp_table = spark.read.parquet(checkvar)\n temp_table.createOrReplaceTempView(\"temp_table\")\n \n temp_table = spark.sql(SQL).first()\n print(table ,\" count :\",temp_table[0])\n if (temp_table[0] > 0):\n print (\"PASSED\")\n else:\n print (\"FAILED\")\n \n print (\"======================================\")\n print (\"\")\n \ndef create_spark_session():\n \"\"\"\n Create spark session for processing\n \"\"\"\n print(\"Create Spark Session\")\n spark = SparkSession \\\n .builder \\\n .config(\"spark.jars.packages\",\"org.apache.hadoop:hadoop-aws:2.7.0\") \\\n .getOrCreate()\n return spark\n\ndef main():\n \"\"\"\n Main Function to load data to S3 using spark.\n \"\"\" \n \n #Print S3 bucket location\n s3_bucket=os.environ[\"s3_bucket\"]\n s3_bucket = s3_bucket.replace(\"'\", \"\")\n \n print (s3_bucket)\n\n spark = create_spark_session()\n print(\"Spark Session Created\")\n\n #Invoke Functions to check data \n check(s3_bucket + \"datalake/\", \"country_table\",spark,\"SELECT count(code_2digit) total_country FROM temp_table\")\n check(s3_bucket + \"datalake/\", \"airport_table\",spark,\"SELECT count(iata_code) total_airport FROM temp_table\")\n\n\nif __name__ == \"__main__\":\n main()","sub_path":"Capstone/Data_Build_Load/analytics_quality_check.py","file_name":"analytics_quality_check.py","file_ext":"py","file_size_in_byte":1954,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"87630333","text":"from turtle import Turtle, Screen\nimport random\n\nturt = Turtle()\nscreen = Screen()\n\nturt.shape(\"turtle\")\nscreen.colormode(255);\n\ndef random_rgb():\n r = random.randint(0,255)\n g = random.randint(0,255)\n b = random.randint(0,255)\n\n return (r,g,b)\n\n\n############################################################\n# 1) Draws shapes from triangle to decagon\n############################################################\n\n\ndef draw_shape(num_sides):\n angle = 360 / num_sides\n for _ in range(num_sides):\n rgb = random_rgb()\n turt.pencolorr(rgb)\n turt.forward(100)\n turt.right(angle)\n\n# for sides in range(3, 100):\n# draw_shape(sides)\n\n\n############################################################\n# 2) Turtle Random Walk\n############################################################\n\ndef left():\n turt.left(90)\n turt.forward(20)\n\ndef right():\n turt.right(90)\n turt.forward(20)\n\ndef forward():\n turt.forward(20)\n\ndef backward():\n turt.backward(20)\n\ndirections = [left, right, forward, backward]\n# turt.pensize(15)\n\n# for _ in range(100):\n# rgb = random_rgb()\n# turt.pencolor(rgb)\n# random.choice(directions)()\n\n\n############################################################\n# 3) Draw a spirograph\n############################################################\n\n# turt.speed(\"fastest\")\n#\n# tilt = 10\n# for i in range(450):\n# rgb = random_rgb()\n# turt.pencolor(rgb)\n#\n# turt.circle(100)\n# turt.right(tilt)\n# if i % 100 == 0:\n# tilt -= 2\n\n\n\nscreen.exitonclick()\n","sub_path":"patterns.py","file_name":"patterns.py","file_ext":"py","file_size_in_byte":1552,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"208858912","text":"__author__ = \"Sean Grogan\"\n__credits__ = [\"Sean Grogan\"]\n__license__ = \"Attribution-NonCommercial-ShareAlike 4.0 International\"\n__version__ = \"1.0\"\n__maintainer__ = \"Sean Grogan\"\n__email__ = \"sean.grogan@gmail.com\"\n__status__ = \"Production\"\nfrom PokerHandTester import *\nfrom Hand import *\nfrom DeckOfCards import *\n\n\ndef master_hand_tester(hand_class):\n \"\"\"This is a function that takes a pool of cards and will return the\n highest 5 card hand in a given pool of cards. hand_class must be a Hand()\n from Hand.py\n \"\"\"\n pool = hand_class.pool\n # tests the Straight Flush ------------------------------------------------\n h = straight_flush(pool.copy())\n if h is not False:\n v = 10 + h[0].value/100\n hand_class.set_value(v)\n hand_class.set_best_hand(h)\n return h\n # tests the Four of a Kind ------------------------------------------------\n h = four_of_a_kind(pool.copy())\n if h is not False:\n v = 9 + h[0].value/100 + h[4].value/10000\n hand_class.set_value(v)\n hand_class.set_best_hand(h)\n return h\n # tests the Full House ----------------------------------------------------\n h = full_house(pool.copy())\n if h is not False:\n v = 8 + h[0].value/100 + h[3].value/10000\n hand_class.set_value(v)\n hand_class.set_best_hand(h)\n return h\n # Tests the Flush ---------------------------------------------------------\n h = flush(pool.copy())\n if h is not False:\n v = 7\n e = 1\n for c in h:\n v += c.value/(100**e)\n e += 1\n hand_class.set_value(v)\n hand_class.set_best_hand(h)\n return h\n # Tests the Straight ------------------------------------------------------\n h = straight(pool.copy())\n if h is not False:\n v = 6 + h[0].value/100\n hand_class.set_value(v)\n hand_class.set_best_hand(h)\n return h\n # Tests the 3 of a Kind ---------------------------------------------------\n h = three_of_a_kind(pool.copy())\n if h is not False:\n v = 5\n e = 1\n for c in h:\n v += c.value/(100**e)\n e += 1\n hand_class.set_value(v)\n hand_class.set_best_hand(h)\n return h\n # Tests the Two Pair ------------------------------------------------------\n h = two_pair(pool.copy())\n if h is not False:\n v = 4\n e = 1\n for c in h:\n v += c.key/(100**e)\n e += 1\n hand_class.set_value(v)\n hand_class.set_best_hand(h)\n return h\n # Tests the Pair ----------------------------------------------------------\n h = pair(pool.copy())\n if h is not False:\n v = 3\n e = 1\n for c in h:\n v += c.value/(100**e)\n e += 1\n hand_class.set_value(v)\n hand_class.set_best_hand(h)\n return h\n # Returns the high card ---------------------------------------------------\n h = sorted_high_card(pool.copy())\n if h is not False:\n v = 1\n e = 1\n for c in h:\n v += c.value/(100**e)\n e += 1\n hand_class.set_value(v)\n hand_class.set_best_hand(h)\n return h\n return h\n\n'''\ndef main_test(iterations=1):\n maxi = 0\n mini = 99\n for i in range(iterations):\n h = Hand()\n d = DeckOfCards()\n d.shuffle()\n h.add_card(d.draw_card())\n h.add_card(d.draw_card())\n h.add_pool([d.draw_card(), d.draw_card(), d.draw_card(), d.draw_card(), d.draw_card()])\n master_hand_tester(h)\n print('run: ', i+1)\n p = ''\n b = ''\n for i in h.pool:\n p += str(i) + ','\n print(p)\n for i in h.best_hand:\n b += str(i) + ','\n print(b)\n if h.value > maxi:\n maxi = h.value\n if h.value < mini:\n mini = h.value\n print(h.value)\n print(maxi)\n print(mini)\n\nmain_test(1000000000)'''\n","sub_path":"MasterHandTester.py","file_name":"MasterHandTester.py","file_ext":"py","file_size_in_byte":3977,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"233733858","text":"import pandas as pd\nimport sys\nfrom six import BytesIO\nfrom jqdata import *\n\n\ndatabase_path = './db/'\n\n\ndef H_V_H(arr):\n ''' historic_valuation_height: 计算历史估值高度\n\n 参数\n ====\n arr : ndarry类型,此时是一维的估值数据\n\n 返回值\n ======\n 返回“小于最后一天估值数据的天数”占“总的天数”的百分比\n '''\n low = arr[arr < arr[-1]]\n return(low.shape[0] / arr.shape[0])\n\n\ndef get_valuation_status(quantile):\n ''' 获取估值状态\n\n 参数\n ====\n quantile : 估值所处的百分位\n\n 返回值\n ======\n assessment : 估值状态\n '''\n assessment = ''\n if 0 <= quantile < 0.1:\n assessment = '超低估'\n elif 0.1 < quantile < 0.3:\n assessment = '低估'\n elif 0.3 < quantile < 0.4:\n assessment = '适中偏低'\n elif 0.4 < quantile < 0.6:\n assessment = '适中'\n elif 0.6 < quantile < 0.7:\n assessment = '适中偏高'\n elif 0.7 < quantile < 0.9:\n assessment = '高估'\n elif 0.9 < quantile <= 1:\n assessment = '超高估'\n\n return assessment\n\n\ndef calc_index_valuation(index_code, start_date, end_date=datetime.datetime.now().date() - datetime.timedelta(days=1)):\n '''计算指数的估值数据。\n\n 参数\n ====\n index_code: 指数代码\n start_date:起始日期\n end_date : 结束日期(默认为今天)\n\n 返回值\n ======\n df: DataFrame,包含了指定日期区间每天的pe, pb数据\n '''\n if (isinstance(start_date, pd.Timestamp)):\n start_date = start_date.date()\n if (start_date <= end_date):\n print('\\t计算{}自{}到{}的估值数据...'.format(index_code, start_date, end_date))\n else:\n print('\\t没有新的数据需要获取。')\n\n def iter_pe_pb(): # 这是一个生成器函数\n trade_date = get_trade_days(start_date=start_date, end_date=end_date)\n\n for date in trade_date:\n stocks = get_index_stocks(index_code, date)\n q = query(valuation.pe_ratio,\n valuation.pb_ratio\n ).filter(\n valuation.pe_ratio != None,\n valuation.pb_ratio != None,\n valuation.code.in_(stocks))\n df = get_fundamentals(q, date)\n if (len(df.index) == 0):\n return pd.DataFrame()\n quantile = df.quantile([0.25, 0.75])\n df_pe = df.pe_ratio[(df.pe_ratio > quantile.pe_ratio.values[0]) &\\\n (df.pe_ratio < quantile.pe_ratio.values[1])]\n df_pb = df.pb_ratio[(df.pb_ratio > quantile.pb_ratio.values[0]) &\\\n (df.pb_ratio < quantile.pb_ratio.values[1])]\n\n yield date, df_pe.median(), df_pb.median()\n\n dict_result = [{'date': value[0], 'pe': value[1], 'pb':value[2]} for value in iter_pe_pb()]\n print('\\t计算完成。')\n if (len(dict_result) == 0):\n return pd.DataFrame()\n else:\n df = pd.DataFrame(dict_result)\n df.set_index('date', inplace=True)\n return df\n\n\ndef load_local_db(index_code):\n '''从本地导入之前保存在./database目录中的估值数据。\n\n 参数\n ====\n index_code: 指数代码\n\n 返回值\n ======\n df : DataFrame,从本地保存的csv里面导入的估值数据\n '''\n file_name = database_path + get_security_info(index_code).display_name + '_pe_pb.csv'\n try:\n df_loc_pe_pb = pd.read_csv(BytesIO(read_file(file_name)), index_col='date', parse_dates=True)\n print(\"\\t找到了本地缓存文件 %s\" % (file_name))\n return df_loc_pe_pb\n except:\n print(\"\\t没有找到本地缓存文件 %s\" % (file_name))\n return pd.DataFrame()\n\n\ndef save_to_db(index_code, new, old=pd.DataFrame()):\n '''将计算得到的估值数据保存到./database目录中的估值数据,提高数据查询效率。\n\n 参数\n ====\n index_code: 指数代码\n new : 计算得到的最新一段时间的估值数据\n old : 获取之前保存在本地的估值数据\n '''\n file_name = database_path + get_security_info(index_code).display_name + '_pe_pb.csv'\n if len(old) <= 0:\n write_file(file_name, new.to_csv(), append=False)\n else:\n df = old.append(new)\n write_file(file_name, df.to_csv(), append=False)\n\n\ndef get_pe_pb(index_code, start_date):\n '''获取从某个日期开始的估值pe/pb。\n\n 参数\n ====\n index_code: 指数代码\n start_date: 起始日期\n '''\n print('开始获取{}的估值数据:'.format(index_code))\n df_old = load_local_db(index_code)\n if len(df_old) <= 0:\n start_date = start_date # 本地没有保存估值数据,从指定的日期开始获取\n print('\\t本地无缓存,需要计算从{}开始的估值数据。'.format(start_date))\n else:\n start_date = df_old.index[-1] + datetime.timedelta(days=1) # 否则,将本地存储估值数据的最后一个日期做为新的起始日期\n print('\\t本地有缓存从{}至{}的数据。'.format(df_old.index[0], df_old.index[-1]))\n df_new = calc_index_valuation(index_code, start_date=start_date)\n save_to_db(index_code, new=df_new, old=df_old)\n return load_local_db(index_code)\n","sub_path":"Finance/聚宽量化/学习笔记/2005/全网指数估值v1.0/valuationlib.py","file_name":"valuationlib.py","file_ext":"py","file_size_in_byte":5336,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"149305570","text":"#_*_ coding:utf-8 _*_\n\nimport scrapy\nfrom scrapy.http import Request\nfrom dota2.items import Dota2Item\n\n# global id_temp\n# id_temp = 0\n\nclass Dota2Spider(scrapy.Spider):\n name = \"dota2\"\n start_urls = [\n # \"http://dota2.sgamer.com/hero/\",\n \"http://db.sgamer.com/dota2/hero\"\n # \"http://www.qiushibaike.com/hot\"\n ]\n url_head = \"http://db.sgamer.com\"\n th_url_list = []\n yy_url_list = []\n\n hero_id = 0 # 初始化英雄ID\n hero_ID_db = []\n hero_name_en_db = []\n attribute_power_db = []\n attribute_agile_db = []\n attribute_intelligence_db = []\n initial_attack_db = []\n initial_armor_db = []\n initial_speed_db = []\n vision_field_db = []\n attack_field_db = []\n attack_speed_db = []\n skill_db = []\n co_hero_db = []\n similar_hero_db = []\n equip_db = [\"N/A\"] # 装备暂时获取不到\n\n# 通过response获得爬取的信息\n def parse(self, response):\n item = Dota2Item()\n selector = scrapy.selector.Selector(response)\n infos_th = selector.xpath('//*[@class=\"heros_main\"]/div[@class=\"th_box\"]') # 天辉\n infos_yy = selector.xpath('//*[@class=\"heros_main\"]/div[@class=\"ym_box\"]') # 夜魇\n\n # 天辉英雄\n th_hero = infos_th.xpath('div[@class=\"heros_list_con cf\"]/ul/li/a/@href').extract()\n for each_hero in th_hero:\n each_th_url = self.url_head + each_hero\n\n hero_name_en = each_th_url.split(\"/\")[-1] # 英雄名(英)\n del self.hero_name_en_db[:]\n self.hero_name_en_db.append(hero_name_en)\n # item[\"hero_name_en\"] = self.hero_name_en_db\n\n self.th_url_list.append(each_th_url)\n yield Request(each_th_url,callback=self.parseDetail)\n\n # break\n\n\n # 夜魇英雄\n yy_hero = infos_yy.xpath('div[@class=\"heros_list_con cf\"]/ul/li/a/@href').extract()\n for each_hero in yy_hero:\n each_yy_url = self.url_head + each_hero\n\n hero_name_en = each_yy_url.split(\"/\")[-1] # 英雄名(英)\n self.hero_name_en_db.append(hero_name_en)\n # item[\"hero_name_en\"] = self.hero_name_en_db\n\n self.yy_url_list.append(each_yy_url)\n yield Request(each_yy_url,callback=self.parseDetail)\n\n # break\n\n # url = \"http://db.sgamer.com/dota2/hero/invoker\"\n # yield Request(url, callback=self.parseDetail)\n\n # yield item\n\n\n # 爬取英雄详细信息页面\n def parseDetail(self,response):\n item = Dota2Item()\n selector = scrapy.selector.Selector(response)\n infos_hero_left = selector.xpath('//div[@class=\"db_main cf id_div\"]/div[@class=\"db_left fl\"]')\n infos_hero_right = selector.xpath('//div[@class=\"db_main cf id_div\"]/div[@class=\"db_right fr\"]')\n\n # 英雄ID\n hero_id_temp = []\n self.hero_id += 1\n hero_id_temp.append(self.hero_id)\n del self.hero_ID_db[:]\n self.hero_ID_db.extend(hero_id_temp)\n\n # global id_temp\n # id_temp += 1\n # hero_id_temp.append(id_temp)\n # del self.hero_ID_db[:]\n # self.hero_ID_db.extend(hero_id_temp)\n # print(\"!!!\" * 20)\n # print(id_temp)\n # print(self.hero_ID_db[0])\n # print(\"!!!\" * 20)\n\n\n # Block-Left(英雄基本信息,英雄属性)\n # 英雄基本信息\n block_left_infos = infos_hero_left.xpath('div[@class=\"hero_infos\"]')\n hero_img = block_left_infos.xpath('img/@src').extract() # 英雄头像\n hero_small_img = block_left_infos.xpath('h3/img/@src').extract() # 英雄小头像\n hero_name_cn = block_left_infos.xpath('h3/text()').extract() # 英雄名(中)\n attack_type = block_left_infos.xpath('ul/li[1]/p/text()').extract() # 攻击类型\n role = block_left_infos.xpath('ul/li[2]/p/text()').extract() # 角色(英雄定位)\n camp = block_left_infos.xpath('ul/li[3]/p/text()').extract() # 阵营\n other_name = block_left_infos.xpath('ul/li[4]/p/text()').extract() # 别名\n\n # log文件处理\n try:\n with open(\"log.txt\",\"a\") as log:\n # log.write(\"***\" * 20 + \"\\n\")\n log.write(str(self.hero_ID_db[0]) + \"\\n\")\n log.write(hero_name_cn[0].encode(\"utf8\") + \"\\n\")\n # log.write(\"@@@\" * 20 + \"\\n\")\n except IOError as err:\n print(\"File Error :\" + str(err))\n\n\n # 英雄属性\n block_left_attribute = infos_hero_left.xpath('div[@class=\"property_box\"]')\n\n # 力量属性\n attribute_power = block_left_attribute.xpath('ul/li[1]/text()').extract()\n self.attribute_power_db = self.deleteSpace(attribute_power)\n\n # 敏捷属性\n attribute_agile = block_left_attribute.xpath('ul/li[2]/text()').extract()\n self.attribute_agile_db = self.deleteSpace(attribute_agile)\n\n # 智力属性\n attribute_intelligence = block_left_attribute.xpath('ul/li[3]/text()').extract()\n self.attribute_intelligence_db = self.deleteSpace(attribute_intelligence)\n\n # 初始攻击\n initial_attack = block_left_attribute.xpath('ul/li[4]/text()').extract()\n self.initial_attack_db = self.deleteSpace(initial_attack)\n\n # 初始护甲\n initial_armor = block_left_attribute.xpath('ul/li[5]/text()').extract()\n self.initial_armor_db = self.deleteSpace(initial_armor)\n\n # 初始移速\n initial_speed = block_left_attribute.xpath('ul/li[6]/text()').extract()\n self.initial_speed_db = self.deleteSpace(initial_speed)\n\n # 视野范围\n vision_field = block_left_attribute.xpath('div[@class=\"area_box cf\"]/span[1]/font/text()').extract()\n self.vision_field_db = self.deleteSpace(vision_field)\n\n # 攻击范围\n attack_field = block_left_attribute.xpath('div[@class=\"area_box cf\"]/span[2]/font/text()').extract()\n self.attack_field_db = self.deleteSpace(attack_field)\n\n # 初始攻击速度\n attack_speed = block_left_attribute.xpath('div[@class=\"area_box cf\"]/span[3]/font/text()').extract()\n self.attack_speed_db = self.deleteSpace(attack_speed)\n\n\n # Block-Right(故事背景)\n # 故事背景\n block_right_story = infos_hero_right.xpath('div[@class=\"story_main pb30\"]')\n background = block_right_story.xpath('div/p/text()').extract()\n\n # 技能介绍\n block_right_skill = infos_hero_right.xpath('div[@class=\"skill_main pb30\"]')\n skill_type_1 = block_right_skill.xpath('div[@class=\"skill_box\"]/div[1]/div/span/font/text()').extract()\n skill_type_2 = block_right_skill.xpath('div[@class=\"skill_box\"]/div[1]/div/span/text()').extract()\n skill_1 = self.deleteSpace(skill_type_1)\n skill_2 = self.deleteSpace(skill_type_2)\n del self.skill_db[:]\n self.skill_db.append(skill_1[0] + skill_2[0])\n\n # 技能详细信息\n # 转换为能给item传值的list格式\n skill_story_list = []\n skill_name_list = []\n skill_describe_list = []\n skill_tip_list = []\n skill_magic_list = []\n skill_CD_list = []\n skill_infos_list = []\n\n skill_detail = block_right_skill.xpath('div[@class=\"skill_box\"]/div[2]/div')\n for each_skill in skill_detail:\n skill_story = each_skill.xpath('div[2]/text()').extract()\n if len(skill_story) == 0:\n skill_story = [\" \"]\n skill_name = each_skill.xpath('div[1]/div/p[1]/span/text()').extract() # 技能名称\n skill_describe = each_skill.xpath('div[1]/div/p[1]/text()').extract() # 技能描述\n skill_tip = each_skill.xpath('div[1]/div/p[2]/text()').extract() # 技能提示\n if len(skill_tip) == 0: # 处理列表为空的情况\n skill_tip = [\" \"]\n elif len(skill_tip) > 1: # 处理列表字段大于1的情况\n skill_tip_temp = \"\"\n for i in range(len(skill_tip)):\n skill_tip_temp += skill_tip[i]\n del skill_tip[:] # 清空列表,将字符串赋值到列表中\n skill_tip.append(skill_tip_temp)\n skill_magic = each_skill.xpath('div[1]/div/div/div[1]/text()').extract() # 技能消耗\n skill_CD = each_skill.xpath('div[1]/div/div/div[2]/text()').extract() # 技能CD\n # skill_infos = each_skill.xpath('div[1]/div/ul/li/text()').extract() # 技能详细信息\n skill_infos = each_skill.xpath('div[1]/div/ul/li')\n skill_infos_record = []\n for each_infos in skill_infos: # for循环中将两个标签的内容整合为一条\n title = each_infos.xpath('span/text()').extract()\n title = self.deleteSpace(title)\n content = each_infos.xpath('text()').extract()\n content = self.deleteSpace(content)\n infos = title[0] + content[0]\n skill_infos_record.append(infos)\n if len(skill_infos_record) > 1: # if语句中将多个列表字段整合为一个列表字段\n skill_infos_temp = \"\"\n for i in range(len(skill_infos_record)):\n skill_infos_temp += skill_infos_record[i]\n del skill_infos_record[:]\n skill_infos_record.append(skill_infos_temp)\n\n skill_story_list.append(skill_story)\n skill_name_list.append(skill_name)\n skill_describe_list.append(skill_describe)\n skill_tip_list.append(skill_tip)\n skill_magic_list.append(skill_magic)\n skill_CD_list.append(skill_CD)\n skill_infos_list.append(skill_infos_record)\n\n # 处理列表长度不满14的情况\n self.addSpace(skill_name_list)\n self.addSpace(skill_describe_list)\n self.addSpace(skill_tip_list)\n self.addSpace(skill_magic_list)\n self.addSpace(skill_CD_list)\n self.addSpace(skill_infos_list)\n self.addSpace(skill_story_list)\n\n\n\n # 给item传值\n item[\"skill_name_1\"] = skill_name_list[0]\n item[\"skill_name_2\"] = skill_name_list[1]\n item[\"skill_name_3\"] = skill_name_list[2]\n item[\"skill_name_4\"] = skill_name_list[3]\n item[\"skill_name_5\"] = skill_name_list[4]\n item[\"skill_name_6\"] = skill_name_list[5]\n item[\"skill_name_7\"] = skill_name_list[6]\n item[\"skill_name_8\"] = skill_name_list[7]\n item[\"skill_name_9\"] = skill_name_list[8]\n item[\"skill_name_10\"] = skill_name_list[9]\n item[\"skill_name_11\"] = skill_name_list[10]\n item[\"skill_name_12\"] = skill_name_list[11]\n item[\"skill_name_13\"] = skill_name_list[12]\n item[\"skill_name_14\"] = skill_name_list[13]\n\n item[\"skill_describe_1\"] = skill_describe_list[0]\n item[\"skill_describe_2\"] = skill_describe_list[1]\n item[\"skill_describe_3\"] = skill_describe_list[2]\n item[\"skill_describe_4\"] = skill_describe_list[3]\n item[\"skill_describe_5\"] = skill_describe_list[4]\n item[\"skill_describe_6\"] = skill_describe_list[5]\n item[\"skill_describe_7\"] = skill_describe_list[6]\n item[\"skill_describe_8\"] = skill_describe_list[7]\n item[\"skill_describe_9\"] = skill_describe_list[8]\n item[\"skill_describe_10\"] = skill_describe_list[9]\n item[\"skill_describe_11\"] = skill_describe_list[10]\n item[\"skill_describe_12\"] = skill_describe_list[11]\n item[\"skill_describe_13\"] = skill_describe_list[12]\n item[\"skill_describe_14\"] = skill_describe_list[13]\n\n item[\"skill_tip_1\"] = skill_tip_list[0]\n item[\"skill_tip_2\"] = skill_tip_list[1]\n item[\"skill_tip_3\"] = skill_tip_list[2]\n item[\"skill_tip_4\"] = skill_tip_list[3]\n item[\"skill_tip_5\"] = skill_tip_list[4]\n item[\"skill_tip_6\"] = skill_tip_list[5]\n item[\"skill_tip_7\"] = skill_tip_list[6]\n item[\"skill_tip_8\"] = skill_tip_list[7]\n item[\"skill_tip_9\"] = skill_tip_list[8]\n item[\"skill_tip_10\"] = skill_tip_list[9]\n item[\"skill_tip_11\"] = skill_tip_list[10]\n item[\"skill_tip_12\"] = skill_tip_list[11]\n item[\"skill_tip_13\"] = skill_tip_list[12]\n item[\"skill_tip_14\"] = skill_tip_list[13]\n\n item[\"skill_magic_1\"] = skill_magic_list[0]\n item[\"skill_magic_2\"] = skill_magic_list[1]\n item[\"skill_magic_3\"] = skill_magic_list[2]\n item[\"skill_magic_4\"] = skill_magic_list[3]\n item[\"skill_magic_5\"] = skill_magic_list[4]\n item[\"skill_magic_6\"] = skill_magic_list[5]\n item[\"skill_magic_7\"] = skill_magic_list[6]\n item[\"skill_magic_8\"] = skill_magic_list[7]\n item[\"skill_magic_9\"] = skill_magic_list[8]\n item[\"skill_magic_10\"] = skill_magic_list[9]\n item[\"skill_magic_11\"] = skill_magic_list[10]\n item[\"skill_magic_12\"] = skill_magic_list[11]\n item[\"skill_magic_13\"] = skill_magic_list[12]\n item[\"skill_magic_14\"] = skill_magic_list[13]\n\n item[\"skill_CD_1\"] = skill_CD_list[0]\n item[\"skill_CD_2\"] = skill_CD_list[1]\n item[\"skill_CD_3\"] = skill_CD_list[2]\n item[\"skill_CD_4\"] = skill_CD_list[3]\n item[\"skill_CD_5\"] = skill_CD_list[4]\n item[\"skill_CD_6\"] = skill_CD_list[5]\n item[\"skill_CD_7\"] = skill_CD_list[6]\n item[\"skill_CD_8\"] = skill_CD_list[7]\n item[\"skill_CD_9\"] = skill_CD_list[8]\n item[\"skill_CD_10\"] = skill_CD_list[9]\n item[\"skill_CD_11\"] = skill_CD_list[10]\n item[\"skill_CD_12\"] = skill_CD_list[11]\n item[\"skill_CD_13\"] = skill_CD_list[12]\n item[\"skill_CD_14\"] = skill_CD_list[13]\n\n item[\"skill_infos_1\"] = skill_infos_list[0]\n item[\"skill_infos_2\"] = skill_infos_list[1]\n item[\"skill_infos_3\"] = skill_infos_list[2]\n item[\"skill_infos_4\"] = skill_infos_list[3]\n item[\"skill_infos_5\"] = skill_infos_list[4]\n item[\"skill_infos_6\"] = skill_infos_list[5]\n item[\"skill_infos_7\"] = skill_infos_list[6]\n item[\"skill_infos_8\"] = skill_infos_list[7]\n item[\"skill_infos_9\"] = skill_infos_list[8]\n item[\"skill_infos_10\"] = skill_infos_list[9]\n item[\"skill_infos_11\"] = skill_infos_list[10]\n item[\"skill_infos_12\"] = skill_infos_list[11]\n item[\"skill_infos_13\"] = skill_infos_list[12]\n item[\"skill_infos_14\"] = skill_infos_list[13]\n\n item[\"skill_story_1\"] = skill_story_list[0]\n item[\"skill_story_2\"] = skill_story_list[1]\n item[\"skill_story_3\"] = skill_story_list[2]\n item[\"skill_story_4\"] = skill_story_list[3]\n item[\"skill_story_5\"] = skill_story_list[4]\n item[\"skill_story_6\"] = skill_story_list[5]\n item[\"skill_story_7\"] = skill_story_list[6]\n item[\"skill_story_8\"] = skill_story_list[7]\n item[\"skill_story_9\"] = skill_story_list[8]\n item[\"skill_story_10\"] = skill_story_list[9]\n item[\"skill_story_11\"] = skill_story_list[10]\n item[\"skill_story_12\"] = skill_story_list[11]\n item[\"skill_story_13\"] = skill_story_list[12]\n item[\"skill_story_14\"] = skill_story_list[13]\n\n # self.transItem(skill_name_list,\"skill_name\") #技能名称\n # self.transItem(skill_describe_list,\"skill_describe\") #技能描述\n # self.transItem(skill_tip_list,\"skill_tip\") #技能技巧\n # self.transItem(skill_magic_list,\"skill_magic\") #技能耗蓝\n # self.transItem(skill_CD_list,\"skill_CD\") #技能CD\n # self.transItem(skill_infos_list,\"skill_infos\") #技能详细信息\n # self.transItem(skill_story_list,\"skill_story\") #技能背景\n\n # print(\"---\" * 20)\n # print(item[\"skill_name_1\"][0])\n # print(\"---\" * 20)\n\n # 装备选择\n block_right_equip = infos_hero_right.xpath('div[@class=\"equip_main pb30\"]')\n pass # 动态获取,暂时无法获取\n\n # 英雄适配\n block_right_hero = infos_hero_right.xpath('div[@class=\"match_main\"]/div')\n\n # 配合英雄\n co_hero = \"\"\n co_hero_info = block_right_hero.xpath('ul[1]/li/a/@href').extract()\n for each_co_hero_info in co_hero_info:\n each_co_hero_name = each_co_hero_info.split(\"/\")[-1]\n co_hero = co_hero + each_co_hero_name + \" \"\n del self.co_hero_db[:]\n self.co_hero_db.append(co_hero)\n\n # 同类英雄\n similar_hero = \"\"\n similar_hero_info = block_right_hero.xpath('ul[2]/li/a/@href').extract()\n for each_similar_hero_info in similar_hero_info:\n each_hero_name = each_similar_hero_info.split(\"/\")[-1]\n similar_hero = similar_hero + each_hero_name + \" \"\n del self.similar_hero_db[:]\n self.similar_hero_db.append(similar_hero)\n\n item[\"hero_ID\"] = self.hero_ID_db # 英雄ID\n\n\n item[\"hero_name_cn\"] = hero_name_cn\n item[\"hero_name_en\"] = self.hero_name_en_db\n item[\"attack_type\"] = attack_type\n item[\"role\"] = role\n item[\"camp\"] = camp\n item[\"other_name\"] = other_name\n item[\"attribute_power\"] = self.attribute_power_db\n item[\"attribute_agile\"] = self.attribute_agile_db\n item[\"attribute_intelligence\"] = self.attribute_intelligence_db\n item[\"initial_attack\"] = self.initial_attack_db\n item[\"initial_armor\"] = self.initial_armor_db\n item[\"initial_speed\"] = self.initial_speed_db\n item[\"vision_field\"] = self.vision_field_db\n item[\"attack_field\"] = self.attack_field_db\n item[\"attack_speed\"] = self.attack_speed_db\n item[\"background\"] = background\n item[\"skill\"] = self.skill_db\n item[\"co_hero\"] = self.co_hero_db\n item[\"similar_hero\"] = self.similar_hero_db\n\n item[\"initial_equip\"] = self.equip_db\n item[\"early_equip\"] = self.equip_db\n item[\"core_equip\"] = self.equip_db\n item[\"god_equip\"] = self.equip_db\n\n yield item\n\n\n\n # 删除列表中的空值\n def deleteSpace(self,init_list):\n temp_str = \"\"\n temp_list = []\n for i in range(len(init_list)):\n if len(init_list[i].strip()) == 0:\n temp_str += init_list[i].strip()\n else:\n temp_str = temp_str + init_list[i].strip() + \" \"\n temp_list.append(temp_str)\n return temp_list\n\n\n\n # 处理列表长度不满14的清空\n def addSpace(self,add_list):\n add_temp = [\" \"]\n add_len = len(add_list)\n if add_len < 14:\n dif = 14 - add_len\n for i in range(dif):\n add_list.append(add_temp)\n return(add_list)\n\n\n\n # 利用循环给item传值\n # def transItem(self,trans_list,trans_str):\n # item = Dota2Item()\n # print(\"???\" * 20)\n # for i in range(1,len(trans_list) + 1):\n # # print(len(trans_list))\n # item_skill_left = trans_str + \"_\" + str(i)\n # item_skill_right = trans_list[i - 1]\n # # print(\"item[%s] = %s\" % (item_skill_left,item_skill_right))\n # # print(item_skill_left)\n # item[item_skill_left] = item_skill_right\n #\n # print(\"---\" * 20)\n # print(type(item_skill_left))\n # print(item_skill_left)\n # print(\"---\" * 20)\n #\n # # yield item","sub_path":"dota2/spiders/dota2_spider.py","file_name":"dota2_spider.py","file_ext":"py","file_size_in_byte":19394,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"143071432","text":"class Combat:\n \"\"\"\n Combat handler\n Alchemist (player) vs bosses\n \"\"\"\n def __init__(self, alchemist, boss):\n self.alchemist = alchemist\n self.boss = boss\n\n def fight(self):\n \"\"\"\n Begins main fight\n :return: bool: Boss killed?\n \"\"\"\n is_victorious = False\n self.boss.begin_combat()\n\n print(\"WIP\")\n\n if is_victorious:\n return True\n return False\n","sub_path":"Combat.py","file_name":"Combat.py","file_ext":"py","file_size_in_byte":448,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"46071092","text":"# python3 -m pupil_localizer.viola_jones.detectors.msgbts.tracker\nimport cv2\nimport numpy as np\nfrom . import detector\n\n\nFACE_HAARCASCADES = (\"/usr/local/Cellar/opencv/4.1.0_2/share/opencv4/\"\n \"haarcascades/haarcascade_frontalface_default.xml\")\nEYE_HAARCASCADES = (\"/usr/local/Cellar/opencv/4.1.0_2/share/opencv4/\"\n \"haarcascades/haarcascade_eye_tree_eyeglasses.xml\")\n\n\ndef get_two_eyes(eyes):\n le_index = 0\n re_index = 0\n x_le = eyes[0][0]\n x_re = eyes[0][0]\n\n for index, (x, y, w, h) in enumerate(eyes):\n if x > x_le:\n x_le = x\n le_index = index\n if x < x_re:\n x_re = x\n re_index = index\n\n return (eyes[le_index], eyes[re_index])\n\n\ndef mark_pupil_centers(le, re, face, img, gray):\n # Establish the first bounding box.\n x_le, y_le, w_le, h_le = le\n x_re, y_re, w_re, h_re = re\n x, y, w, h = face\n\n x_tl_le = x_le + x\n x_br_le = x_le + w_le + x\n y_tl_le = y_le + y\n y_br_le = y_le + h_le + y\n\n x_tl_re = x_re + x\n x_br_re = x_re + w_re + x\n y_tl_re = y_re + y\n y_br_re = y_re + h_re + y\n\n le = np.array([x_tl_le, y_tl_le, x_br_le, y_br_le])\n re = np.array([x_tl_re, y_tl_re, x_br_re, y_br_re])\n\n # Perform the detection.\n pupil_x_l, pupil_y_l, boxes_le = detector.detect_le(le, gray)\n pupil_x_r, pupil_y_r, boxes_re = detector.detect_re(re, gray)\n\n cv2.rectangle(img, (x_tl_le, y_tl_le), (x_br_le, y_br_le),\n (0, 255, 0), 1)\n cv2.rectangle(img, (x_tl_re, y_tl_re), (x_br_re, y_br_re),\n (0, 255, 0), 1)\n\n # Draw the rest bounding boxes.\n for le in boxes_le:\n x_tl_le, y_tl_le, x_br_le, y_br_le = le\n cv2.rectangle(img, (x_tl_le, y_tl_le), (x_br_le, y_br_le),\n (0, 255, 0), 1)\n\n for re in boxes_re:\n x_tl_re, y_tl_re, x_br_re, y_br_re = re\n cv2.rectangle(img, (x_tl_re, y_tl_re), (x_br_re, y_br_re),\n (0, 255, 0), 1)\n\n cv2.circle(img, (pupil_x_l, pupil_y_l), 2, (255, 255, 255), -1)\n cv2.circle(img, (pupil_x_r, pupil_y_r), 2, (255, 255, 255), -1)\n\n\ndef start_tracking():\n detector.initialize()\n\n captured_video = cv2.VideoCapture(0) # 0 for capturing from the cam\n\n captured_video.set(cv2.CAP_PROP_FRAME_WIDTH, 640)\n captured_video.set(cv2.CAP_PROP_FRAME_HEIGHT, 480)\n\n face_cascade = cv2.CascadeClassifier(FACE_HAARCASCADES)\n eye_cascade = cv2.CascadeClassifier(EYE_HAARCASCADES)\n\n while captured_video.isOpened():\n # Capture frame-by-frame.\n did_read_frame, img = captured_video.read()\n\n if did_read_frame:\n # Our operations on the frame come here.\n gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n else:\n break\n\n faces = face_cascade.detectMultiScale(gray, 1.1, 3)\n\n for face in faces:\n x, y, w, h = face\n\n face_roi_gray = gray[y:y+h, x:x+w]\n\n eyes = eye_cascade.detectMultiScale(face_roi_gray, 1.1, 3)\n\n try:\n le, re = get_two_eyes(eyes)\n except IndexError:\n continue\n else:\n mark_pupil_centers(le, re, face, img, gray)\n\n cv2.rectangle(img, (x, y), (x+w, y+h), (255, 0, 0), 2)\n\n # Display the resulting frame.\n cv2.imshow(\"frame\", img)\n if cv2.waitKey(1) & 0xFF == ord(\"q\"):\n break\n\n # When everything done, release the capture.\n captured_video.release()\n cv2.destroyAllWindows()\n\n detector.terminate()\n\n\ndef main():\n start_tracking()\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"viola_jones/detectors/msgbts/tracker.py","file_name":"tracker.py","file_ext":"py","file_size_in_byte":3632,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"477922362","text":"# -*- coding: utf-8 -*-\n# Copyright 2020 The PsiZ Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ============================================================================\n\"\"\"Test GateMulti.\"\"\"\n\nimport numpy as np\nimport pytest\nimport tensorflow as tf\n\nfrom psiz.keras.layers import DistanceBased\nfrom psiz.keras.layers import ExponentialSimilarity\nfrom psiz.keras.layers import GateMulti\nfrom psiz.keras.layers import Minkowski\nfrom psiz.keras.layers import MinkowskiStochastic\nfrom psiz.keras.layers import MinkowskiVariational\n\n\ndef build_vi_kernel(similarity, n_dim, kl_weight):\n \"\"\"Build kernel for single group.\"\"\"\n mink_prior = MinkowskiStochastic(\n rho_loc_trainable=False, rho_scale_trainable=True,\n w_loc_trainable=False, w_scale_trainable=False,\n w_scale_initializer=tf.keras.initializers.Constant(.1)\n )\n\n mink_posterior = MinkowskiStochastic(\n rho_loc_trainable=False, rho_scale_trainable=True,\n w_loc_trainable=True, w_scale_trainable=True,\n w_scale_initializer=tf.keras.initializers.Constant(.1)\n )\n\n mink = MinkowskiVariational(\n prior=mink_prior, posterior=mink_posterior,\n kl_weight=kl_weight, kl_n_sample=30\n )\n\n kernel = DistanceBased(\n distance=mink,\n similarity=similarity\n )\n return kernel\n\n\n@pytest.fixture\ndef kernel_subnets():\n \"\"\"A list of subnets\"\"\"\n pw_0 = DistanceBased(\n distance=Minkowski(\n rho_initializer=tf.keras.initializers.Constant(2.),\n w_initializer=tf.keras.initializers.Constant(1.),\n trainable=False\n ),\n similarity=ExponentialSimilarity(\n fit_tau=False, fit_gamma=False, fit_beta=False,\n tau_initializer=tf.keras.initializers.Constant(1.),\n gamma_initializer=tf.keras.initializers.Constant(0.0),\n beta_initializer=tf.keras.initializers.Constant(.1),\n )\n )\n pw_1 = DistanceBased(\n distance=Minkowski(\n rho_initializer=tf.keras.initializers.Constant(2.),\n w_initializer=tf.keras.initializers.Constant(1.),\n trainable=False\n ),\n similarity=ExponentialSimilarity(\n fit_tau=False, fit_gamma=False, fit_beta=False,\n tau_initializer=tf.keras.initializers.Constant(1.),\n gamma_initializer=tf.keras.initializers.Constant(0.0),\n beta_initializer=tf.keras.initializers.Constant(.1),\n )\n )\n\n pw_2 = DistanceBased(\n distance=Minkowski(\n rho_initializer=tf.keras.initializers.Constant(2.),\n w_initializer=tf.keras.initializers.Constant(1.),\n trainable=False\n ),\n similarity=ExponentialSimilarity(\n fit_tau=False, fit_gamma=False, fit_beta=False,\n tau_initializer=tf.keras.initializers.Constant(1.),\n gamma_initializer=tf.keras.initializers.Constant(0.0),\n beta_initializer=tf.keras.initializers.Constant(.1),\n )\n )\n\n subnets = [pw_0, pw_1, pw_2]\n return subnets\n\n\ndef test_subnet_method(kernel_subnets):\n group_layer = GateMulti(subnets=kernel_subnets, group_col=0)\n group_layer.build([[None, 3], [None, 3], [None, 3]])\n\n subnet_0 = group_layer.subnets[0]\n subnet_1 = group_layer.subnets[1]\n subnet_2 = group_layer.subnets[2]\n\n tf.debugging.assert_equal(\n subnet_0.distance.rho, kernel_subnets[0].distance.rho\n )\n tf.debugging.assert_equal(\n subnet_0.distance.w, kernel_subnets[0].distance.w\n )\n\n tf.debugging.assert_equal(\n subnet_1.distance.rho, kernel_subnets[1].distance.rho\n )\n tf.debugging.assert_equal(\n subnet_1.distance.w, kernel_subnets[1].distance.w\n )\n\n tf.debugging.assert_equal(\n subnet_2.distance.rho, kernel_subnets[2].distance.rho\n )\n tf.debugging.assert_equal(\n subnet_2.distance.w, kernel_subnets[2].distance.w\n )\n\n\ndef test_kernel_call(kernel_subnets, paired_inputs_v0, group_v0):\n group_layer = GateMulti(subnets=kernel_subnets, group_col=0)\n outputs = group_layer(\n [paired_inputs_v0[0], paired_inputs_v0[1], group_v0]\n )\n\n # x = np.exp(-.1 * np.sqrt(3*(5**2)))\n desired_outputs = np.array([\n 0.4206200260541147,\n 0.4206200260541147,\n 0.4206200260541147,\n 0.4206200260541147,\n 0.4206200260541147\n ])\n\n np.testing.assert_array_almost_equal(desired_outputs, outputs.numpy())\n\n\ndef test_call_kernel_empty_branch(paired_inputs_v0, group_3g_empty_v0):\n \"\"\"Test call with empty branch.\n\n This test does not have an explicit assert, but tests that such a\n call does not raise a runtime error.\n\n \"\"\"\n n_dim = 3\n kl_weight = .1\n\n shared_similarity = ExponentialSimilarity(\n beta_initializer=tf.keras.initializers.Constant(10.),\n tau_initializer=tf.keras.initializers.Constant(1.),\n gamma_initializer=tf.keras.initializers.Constant(0.),\n trainable=False\n )\n\n # Define group-specific kernels.\n kernel_0 = build_vi_kernel(shared_similarity, n_dim, kl_weight)\n kernel_1 = build_vi_kernel(shared_similarity, n_dim, kl_weight)\n kernel_2 = build_vi_kernel(shared_similarity, n_dim, kl_weight)\n kernel_group = GateMulti(\n subnets=[kernel_0, kernel_1, kernel_2], group_col=0\n )\n\n _ = kernel_group(\n [paired_inputs_v0[0], paired_inputs_v0[1], group_3g_empty_v0]\n )\n\n\ndef test_kernel_output_shape(kernel_subnets, paired_inputs_v0, group_v0):\n \"\"\"Test output_shape method.\"\"\"\n group_layer = GateMulti(subnets=kernel_subnets, group_col=0)\n\n input_shape = [\n tf.TensorShape(tf.shape(paired_inputs_v0[0])),\n tf.TensorShape(tf.shape(paired_inputs_v0[1])),\n tf.TensorShape(tf.shape(group_v0))\n ]\n output_shape = group_layer.compute_output_shape(input_shape)\n desired_output_shape = tf.TensorShape([5])\n tf.debugging.assert_equal(output_shape, desired_output_shape)\n\n\ndef test_serialization(kernel_subnets, paired_inputs_v0, group_v0):\n \"\"\"Test serialization.\"\"\"\n group_layer_0 = GateMulti(subnets=kernel_subnets, group_col=0)\n outputs_0 = group_layer_0(\n [paired_inputs_v0[0], paired_inputs_v0[1], group_v0]\n )\n config = group_layer_0.get_config()\n assert config['group_col'] == 0\n\n group_layer_1 = GateMulti.from_config(config)\n outputs_1 = group_layer_1(\n [paired_inputs_v0[0], paired_inputs_v0[1], group_v0]\n )\n\n tf.debugging.assert_equal(outputs_0, outputs_1)\n","sub_path":"tests/keras/layers/test_gate_multi.py","file_name":"test_gate_multi.py","file_ext":"py","file_size_in_byte":6997,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"188560061","text":"# -*- coding:utf-8 _*- \n\"\"\" \n@author:Administrator\n@file: plot_test.py\n@time: 2018/9/5\n\"\"\"\n\nimport matplotlib.pyplot as plt\n\nx = [x for x in range(10)]\n\nplt.hist(x)\nplt.show()","sub_path":"buildingTypeId_no_reducing_demensions/first_process/plot_test.py","file_name":"plot_test.py","file_ext":"py","file_size_in_byte":176,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"580189301","text":"import pandas as pd \nimport numpy as np \nfrom pathlib import Path \n\n\n\n#Importing the file \nlocation = \"C:/Users/flyhi/OneDrive/Desktop/india/Covid19_India_datasets-main/combined.csv\"\nnew = Path(location)\ndf = pd.read_csv(location)\n\n\n\n#Dropping col's\ndf = df.drop(['Unnamed: 0', 'Unnamed: 0.1'], axis=1)\ndf['Time'] = pd.to_datetime(df['Time'])\n\n\n#Getting cases \nmissing_set = df[df['New Cases'].notnull()]\ncases = list(missing_set['New Cases'])\nprint(missing_set['State'].unique())\n\nlist_of_cases = []\nfor i in list(missing_set['State'].unique()):\n new_state = missing_set[missing_set['State'] == i]\n z = new_state[(new_state['New Cases'] == 1276.0)]\n print(z)\n \n# series_cases = list(new_state['New Cases'])\n# for z in range(len(series_cases)):\n# list_of_cases.append(series_cases[z])\n\n\n# for i in list_of_cases:\n# if i == 1276.0:\n# print('yay')","sub_path":"Covid19_India_datasets-main/case_check.py","file_name":"case_check.py","file_ext":"py","file_size_in_byte":885,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"30534771","text":"\"\"\"\nThis module provides some basic metricsprovider and metric classes and functionalities,\nwhich are used in the E2E tests to ease the execution flow.\nFunctions include creation, read, update and deletion commands as well as receiving of\nother useful information like corresponding metrics and providers.\n\nThe following classes can be found:\n MetricsProviderType (Enum):\n Enum class for all metrics provider types.\n\n BaseMetricsProviderDefinition (ResourceDefinition, ABC):\n Base class for both namespaced and global metrics provider\n resource definitions.\n\n BaseKafkaMetricsProviderDefinition (BaseMetricsProviderDefinition):\n Base class for all kafka metrics provider resource definitions.\n\n BasePrometheusMetricsProviderDefinition (BaseMetricsProviderDefinition):\n Base class for all prometheus metrics provider resource definitions.\n\n BaseStaticMetricsProviderDefinition (BaseMetricsProviderDefinition):\n Base class for all static metrics provider resource definitions.\n\n BaseMetricDefinition (ResourceDefinition, ABC):\n Base class for namespaced and global metrics.\n\n NonExistentMetric (BaseMetricDefinition):\n Used by tests which require a metric that is not in the database.\n\n WrappedMetric (ABC):\n A wrapper around a BaseMetricDefinition object with kind\n ResourceKind.Metric or ResourceKind.GlobalMetric.\n\n ValuedMetric (WrappedMetric, ABC):\n A wrapper around a BaseMetricDefinition object and a value.\n\n StaticMetric (ValuedMetric):\n Used by the static metrics providers.\n\n PrometheusMetric (ValuedMetric):\n Used by the prometheus metrics providers.\n\n WeightedMetric (ValuedMetric):\n A wrapper around a BaseMetricDefinition object and a weight.\n\n ResourceProvider (Singleton):\n Resource provider class, which contains data for the resource provider as well\n as useful functions.\n\nSome of these classes are inherited from abstract base classes, which function as a\nvirtual parent class (import ABC).\n\"\"\"\n\nfrom abc import ABC, abstractmethod\nfrom enum import Enum\nimport random\nimport uuid\n\nfrom functionals.utils import Singleton, check_resource_exists\nfrom functionals.utils import DEFAULT_NAMESPACE as NAMESPACE\nfrom functionals.resource_definitions import ResourceKind, ResourceDefinition\n\n\nclass MetricsProviderType(Enum):\n PROMETHEUS = \"prometheus\"\n STATIC = \"static\"\n KAFKA = \"kafka\"\n\n\nclass BaseMetricsProviderDefinition(ResourceDefinition, ABC):\n \"\"\"Base class for both namespaced and global metrics provider\n resource definitions.\n\n Attributes:\n name (str): name of the metrics provider\n kind (ResourceKind): kind of metrics provider. Must be either\n ResourceKind.METRICSPROVIDER or ResourceKind.GLOBALMETRICSPROVIDER\n namespace (str, optional): the namespace of the metrics provider.\n None if kind == ResourceKind.GLOBALMETRICSPROVIDER\n mp_type (functionals.resource_provider.MetricsProviderType): type of\n metrics provider\n _base_metrics (list[BaseMetricDefinition]): list of metric resource definitions\n that this provider provides.\n\n Raises:\n ValueError: if kind is incorrect or does not match the namespace\n \"\"\"\n\n def __init__(self, name, kind, namespace, mp_type):\n if kind not in [\n ResourceKind.METRICSPROVIDER,\n ResourceKind.GLOBALMETRICSPROVIDER,\n ]:\n raise ValueError(f\"Unexpected metrics provider kind: {kind}\")\n super().__init__(name, kind, namespace=namespace)\n self.type = mp_type\n self._valued_metrics = []\n\n @abstractmethod\n def _get_mutable_attributes(self):\n raise NotImplementedError(\"Not yet implemented\")\n\n def _get_default_values(self):\n return dict.fromkeys(self._mutable_attributes, None)\n\n def _get_actual_mutable_attribute_values(self):\n metrics_provider = self.get_resource()\n return {\n attr: metrics_provider[\"spec\"][self.type.value][attr]\n for attr in self._mutable_attributes\n }\n\n @abstractmethod\n def creation_command(self, wait):\n raise NotImplementedError(\"Not yet implemented\")\n\n def creation_acceptance_criteria(self, error_message=None, expected_state=None):\n if not error_message:\n error_message = (\n f\"The {self.kind.value} {self.name} was not properly created.\"\n )\n return check_resource_exists(error_message=error_message)\n\n def delete_command(self, wait):\n return f\"rok core {self.kind.value} delete {self.name}\".split()\n\n def get_command(self):\n return f\"rok core {self.kind.value} get {self.name} -o json\".split()\n\n @abstractmethod\n def update_command(self, **kwargs):\n raise NotImplementedError()\n\n @abstractmethod\n def read_metrics(self):\n \"\"\"Read the metrics the actual resource provides\n\n Returns:\n dict[str, float]: dictionary with the metric names and values as\n keys and values.\n Raises:\n NotImplementedError: if the metrics are not found\n \"\"\"\n raise NotImplementedError()\n\n def get_valued_metrics(self):\n \"\"\"Retrieve the valued metrics of this metrics provider resource definition.\n\n Returns:\n list(ValuedMetric): list of the metrics this metrics provider provides,\n together with their values.\n \"\"\"\n return self._valued_metrics\n\n def set_valued_metrics(self, metrics):\n \"\"\"Set the valued metrics of this metrics provider\n\n Of the krake metrics provider resources, only the static metrics provider\n keeps the values of the metrics it provides. However, during the tests\n we need to be able to 'predict' which values a metrics provider will provide\n during the tests. Therefore, we provide the valued metrics to all types of\n metrics providers using this method.\n The values are however never used and can only be retrieved using the\n get_valued_metrics() method.\n\n For metrics providers of type MetricsProviderType.STATIC, calling this\n method changes the metrics which the metrics providers resource definition\n uses, without updating the actual database resource associated with it.\n This is useful when the provider needs to be set with a correct value already\n at creation of the actual database resource.\n (Otherwise, the initial values of the provider resource definition would be used\n when an application is scheduled to a cluster at the entry of an\n environment.Environment, which could contain incorrect information.)\n\n Args:\n metrics (list[ValuedMetric]):\n list of metrics that this metrics provider provides\n \"\"\"\n self._validate_metrics(metrics)\n self._valued_metrics = metrics\n\n def _validate_metrics(self, metrics):\n \"\"\"Validate the metrics list based on their namespaces.\n\n Args:\n metrics (list(StaticMetric)): metrics to validate\n\n Raises:\n ValueError:\n if metrics are no list or if metrics and metricsprovider do not match\n \"\"\"\n if metrics is None:\n raise ValueError(\"Expected metrics to be a list. Was None.\")\n if any([self.namespace != m.metric.namespace for m in metrics]):\n raise ValueError(\n f\"Metrics ({metrics}) and metrics provider namespace \"\n f\"{self.namespace} do not match.\"\n )\n\n\nclass BaseKafkaMetricsProviderDefinition(BaseMetricsProviderDefinition):\n \"\"\"Base class for all kafka metrics provider resource definitions.\n\n Args:\n name (str): name of the metrics provider\n kind (ResourceKind): kind of metrics provider. Valid values are\n ResourceKind.METRICSPROVIDER and ResourceKind.GLOBALMETRICSPROVIDER\n namespace (str, optional): the namespace of the metrics provider.\n None if kind == ResourceKind.GLOBALMETRICSPROVIDER\n url (str): url at which this metrics provider provides.\n table (str): name of the ksql table.\n comparison_column (str): Name of the column whose value will be compared\n to the metric name when selecting a metric.\n value_column (str): Name of the column where the value of a metric is stored.\n\n Raises:\n ValueError: if kind is incorrect or does not match the namespace\n \"\"\"\n\n def __init__(\n self, name, kind, namespace, url, table, comparison_column, value_column\n ):\n super().__init__(name, kind, namespace, mp_type=MetricsProviderType.KAFKA)\n self.url = url\n self.table = table\n self.comparison_column = comparison_column\n self.value_column = value_column\n\n def _get_mutable_attributes(self):\n return [\"url\", \"table\", \"comparison_column\", \"value_column\"]\n\n def creation_command(self, wait):\n return (\n f\"rok core {self.kind.value} create --type {self.type.value} \"\n f\"--url {self.url} --comparison-column {self.comparison_column} \"\n f\"--value-column {self.value_column} --table {self.table} \"\n f\"{self.name}\".split()\n )\n\n def update_command(\n self, url=None, table=None, comparison_column=None, value_column=None\n ):\n cmd = f\"rok core {self.kind.value} update {self.name}\".split()\n if url:\n cmd += [\"--url\", url]\n if table:\n cmd += [\"--table\", table]\n if comparison_column:\n cmd += [\"--comparison-column\", comparison_column]\n if value_column:\n cmd += [\"--value-column\", value_column]\n return cmd\n\n def read_metrics(self):\n raise NotImplementedError()\n\n\nclass BasePrometheusMetricsProviderDefinition(BaseMetricsProviderDefinition):\n \"\"\"Base class for all prometheus metrics provider resource definitions.\n\n Args:\n name (str): name of the metrics provider\n kind (ResourceKind): kind of metrics provider. Valid values are\n ResourceKind.METRICSPROVIDER and ResourceKind.GLOBALMETRICSPROVIDER\n namespace (str, optional): the namespace of the metrics provider.\n None iff kind == ResourceKind.GLOBALMETRICSPROVIDER\n url (str): url at which this metrics provider provides.\n\n Raises:\n ValueError: if kind is incorrect or does not match the namespace\n \"\"\"\n\n def __init__(self, name, kind, namespace, url):\n super().__init__(name, kind, namespace, mp_type=MetricsProviderType.PROMETHEUS)\n self.url = url\n\n def _get_mutable_attributes(self):\n return [\"url\"]\n\n def creation_command(self, wait):\n return (\n f\"rok core {self.kind.value} create --type {self.type.value} \"\n f\"--url {self.url} {self.name}\".split()\n )\n\n def update_command(self, url=None):\n return f\"rok core {self.kind.value} update --url {url} {self.name}\".split()\n\n def read_metrics(self):\n raise NotImplementedError()\n\n\nclass BaseStaticMetricsProviderDefinition(BaseMetricsProviderDefinition):\n \"\"\"Base class for all static metrics provider resource definitions.\n\n Attributes:\n name (str): name of the metrics provider\n kind (ResourceKind): kind of metrics provider. Valid values are\n ResourceKind.METRICSPROVIDER and ResourceKind.GLOBALMETRICSPROVIDER\n namespace (str, optional): the namespace of the metrics provider.\n None iff kind == ResourceKind.GLOBALMETRICSPROVIDER\n metrics (list[StaticMetric]): list of static metrics that this\n metrics provider provides.\n\n Raises:\n ValueError: if kind is incorrect or does not match the namespace\n \"\"\"\n\n def __init__(self, name, kind, namespace, metrics=None):\n super().__init__(name, kind, namespace, mp_type=MetricsProviderType.STATIC)\n if metrics is None:\n metrics = []\n self.set_valued_metrics(metrics)\n\n def _get_mutable_attributes(self):\n return [\"metrics\"]\n\n def creation_command(self, wait):\n cmd = (\n f\"rok core {self.kind.value} create --type {self.type.value} \"\n f\"{self.name}\".split()\n )\n cmd += self._get_metrics_options(self.metrics)\n return cmd\n\n def update_command(self, metrics=None):\n cmd = f\"rok core {self.kind.value} update {self.name}\".split()\n cmd += self._get_metrics_options(metrics)\n return cmd\n\n @staticmethod\n def _get_metrics_options(metrics):\n \"\"\"Convenience method for generating metric lists for rok cli commands.\n\n Example:\n If provided the argument metrics=\n [StaticMetric(\"metric_name1\", True, 1.0),\n StaticMetric(\"metric_name2\", False, 2.0)],\n this method will return the list\n [\"-m\", \"metric_name1\", \"1.0\", \"-m\", \"metric_name2\", \"2.0\"],\n which can be used when constructing a cli command like\n rok kube cluster register -m metric_name1 1.0 -m metric_name2 2.0 ...\n\n Args:\n metrics (list[StaticMetric], optional): list of metrics with values.\n\n Returns:\n list[str]:\n ['-m', 'key_1', 'value_1', '-m', 'key_2', 'value_2', ...,\n '-m', 'key_n', 'value_n']\n for all n key, value pairs in metrics.\n \"\"\"\n metrics_options = []\n if metrics is None:\n metrics = []\n for static_metric in metrics:\n metrics_options += [\n \"-m\",\n static_metric.metric.mp_metric_name,\n str(static_metric.value),\n ]\n return metrics_options\n\n def set_valued_metrics(self, metrics):\n super().set_valued_metrics(metrics)\n self.metrics = metrics\n\n def attribute_is_equal(self, attr_name, expected, observed):\n \"\"\"Overriding attribute_is_equal() of the ResourceDefinition class,\n since the metrics attribute needs to be compared differently.\n\n Args:\n attr_name (str): the name of the attribute for which this comparison\n is taking place\n expected (list[StaticMetric]): the expected attribute value\n observed (dict[str, float]): the observed attribute value\n\n Returns:\n bool: indicating whether expected == observed, given that they are\n the values of the attr_name attribute of this ResourceDefintion object.\n \"\"\"\n if attr_name != \"metrics\":\n return super().attribute_is_equal(attr_name, expected, observed)\n\n expected_names = [m.metric.mp_metric_name for m in expected]\n return (\n len(expected) == len(observed)\n and all(name in expected_names for name in observed)\n and all(m.value == observed.get(m.metric.mp_metric_name) for m in expected)\n )\n\n def read_metrics(self):\n actual_mutable_attrs = self._get_actual_mutable_attribute_values()\n return actual_mutable_attrs[\"metrics\"]\n\n\nclass BaseMetricDefinition(ResourceDefinition, ABC):\n \"\"\"Base class for namespaced and global metrics.\n\n Args:\n name (str): name of the metric\n kind (ResourceKind): kind of the metric. Must be either\n ResourceKind.METRIC or ResourceKind.GLOBALMETRIC\n namespace (str, optional): namespace of the metric.\n None iff kind == ResourceKind.GLOBALMETRIC\n allowed_values (List(int)): List of possible values of this metric\n min (float): minimum value of this metric\n max (float): maximum value of this metric\n mp_name (str): name of the metrics provider which privides this metric.\n mp_metric_name (str, optional): metric name for a specific metrics provider\n\n Raises:\n ValueError: if kind is incorrect or does not match the namespace\n \"\"\"\n\n def __init__(\n self, name, kind, namespace, allowed_values, min, max, mp_name, mp_metric_name\n ):\n\n super().__init__(name, kind, namespace)\n if kind not in [ResourceKind.METRIC, ResourceKind.GLOBALMETRIC]:\n raise ValueError(f\"Unexpected type of metric: {kind}\")\n self.kind = kind\n self.allowed_values = allowed_values\n self.min = min\n self.max = max\n self.mp_name = mp_name\n self.mp_metric_name = mp_metric_name if mp_metric_name else name\n self._mp_name_param = (\n \"--mp-name\" if kind == ResourceKind.METRIC else \"--gmp-name\"\n )\n\n def _get_mutable_attributes(self):\n return [\"allowed_values\", \"min\", \"max\", \"mp_name\", \"mp_metric_name\"]\n\n def _get_default_values(self):\n default_values = dict.fromkeys(self._mutable_attributes, None)\n default_values[\"mp_metric_name\"] = self.name\n return default_values\n\n def _get_actual_mutable_attribute_values(self):\n metric = self.get_resource()\n return {\n \"allowed_values\": metric[\"spec\"][\"allowed_values\"],\n \"min\": metric[\"spec\"][\"min\"],\n \"max\": metric[\"spec\"][\"max\"],\n \"mp_name\": metric[\"spec\"][\"provider\"][\"name\"],\n \"mp_metric_name\": metric[\"spec\"][\"provider\"][\"metric\"],\n }\n\n def creation_command(self, wait):\n cmd = (\n f\"rok core {self.kind.value} create --min {self.min} --max {self.max} \"\n f\"{self._mp_name_param} {self.mp_name} --metric-name {self.mp_metric_name} \"\n f\"{self.name}\".split()\n )\n\n if self.allowed_values:\n cmd += f\"--allowed-values {' '.join(self.allowed_values)} \"\n\n if self.mp_metric_name:\n cmd += [\"--metric-name\", self.mp_metric_name]\n return cmd\n\n def creation_acceptance_criteria(self, error_message=None, expected_state=None):\n if not error_message:\n error_message = (\n f\"The {self.kind.value} {self.name} was not properly created.\"\n )\n return check_resource_exists(error_message=error_message)\n\n def delete_command(self, wait):\n return f\"rok core {self.kind.value} delete {self.name}\".split()\n\n def get_command(self):\n return f\"rok core {self.kind.value} get {self.name} -o json\".split()\n\n def update_command(\n self, allowed_values=None, min=None, max=None, mp_name=None, mp_metric_name=None\n ):\n cmd = f\"rok core {self.kind.value} update {self.name}\".split()\n if allowed_values:\n cmd += [\"allowed-values\", allowed_values]\n if min:\n cmd += [\"--min\", min]\n if max:\n cmd += [\"--max\", max]\n if mp_name:\n cmd += [self._mp_name_param, mp_name]\n if mp_metric_name:\n cmd += [\"--metric-name\", self.mp_metric_name]\n return cmd\n\n def get_metrics_provider(self):\n \"\"\"\n Returns:\n BaseMetricsProviderDefinition:\n The resource definition of the metrics proivder which provides\n this metric\n \"\"\"\n return provider.get_metrics_provider(self)\n\n\nclass NonExistentMetric(BaseMetricDefinition):\n \"\"\"Used by tests which require a metric that is not in the database.\n\n Raises:\n ValueError: whenever one tries to access the metric.\n Only create_resource(), check_created(), delete_resource() and\n check_deleted() will silently fail, since these will be called\n whenever entering and exiting an Environment.\n \"\"\"\n\n def __init__(self):\n suffix = str(uuid.uuid4())\n name = \"non-existent-metric-\" + suffix\n mp_name = \"non-existent-metrics-provider-\" + suffix\n super().__init__(\n name,\n ResourceKind.GLOBALMETRIC,\n None,\n allowed_values=[],\n min=0,\n max=1,\n mp_name=mp_name,\n mp_metric_name=name,\n )\n\n def _get_mutable_attributes(self):\n return []\n\n def _get_default_values(self):\n raise ValueError(\"This metric does not exist and has no default values.\")\n\n def _get_actual_mutable_attribute_values(self):\n raise ValueError(\"This metric does not exist and has no mutable attributes.\")\n\n def create_resource(self, ignore_verification=False):\n pass\n\n def check_created(self, delay=10):\n pass\n\n def creation_command(self, wait):\n raise ValueError(\"This metric does not exist and cannot be created.\")\n\n def creation_acceptance_criteria(self, error_message=None, expected_state=None):\n msg = (\n f\"This metric does not exist and cannot be created. \"\n f\"error_message = {error_message}\"\n )\n raise ValueError(msg)\n\n def delete_resource(self):\n pass\n\n def delete_command(self, wait):\n raise ValueError(\"This metric does not exist and cannot be deleted.\")\n\n def check_deleted(self, delay=10):\n pass\n\n def get_command(self):\n raise ValueError(\"This metric does not exist and cannot be retrieved.\")\n\n def update_command(self, min=None, max=None, mp_name=None, mp_metric_name=None):\n raise ValueError(\"This metric does not exist and cannot be updated.\")\n\n def get_metrics_provider(self):\n return None\n\n\nclass WrappedMetric(ABC):\n \"\"\"A wrapper around a BaseMetricDefinition object with kind\n ResourceKind.Metric or ResourceKind.GlobalMetric.\n\n Args:\n metric (BaseMetricDefinition): metric resource definition\n \"\"\"\n\n def __init__(self, metric):\n super().__init__()\n self.metric = metric\n\n def __repr__(self):\n return self.metric.name + f\"(provider '{self.metric.mp_name}')\"\n\n def get_metrics_provider(self):\n return self.metric.get_metrics_provider()\n\n\nclass ValuedMetric(WrappedMetric, ABC):\n \"\"\"A wrapper around a BaseMetricDefinition object and a value.\n\n Used by metrics providers.\n\n Args:\n metric (BaseMetricDefinition): metric resource definition\n value (float): value of the metric.\n \"\"\"\n\n def __init__(self, metric, value):\n super().__init__(metric)\n self.value = value\n\n def __repr__(self):\n super_repr = super().__repr__()\n return super_repr + \" = \" + str(self.value)\n\n\nclass StaticMetric(ValuedMetric):\n \"\"\"Used by the static metrics providers.\"\"\"\n\n pass\n\n\nclass PrometheusMetric(ValuedMetric):\n \"\"\"Used by the prometheus metrics providers.\"\"\"\n\n pass\n\n\nclass WeightedMetric(WrappedMetric):\n \"\"\"A wrapper around a BaseMetricDefinition object and a weight.\n\n Used by clusters.\n\n Args:\n metric (BaseMetricDefinition): metric resource definition\n weight (float): a cluster's weight of the metric.\n \"\"\"\n\n def __init__(self, metric, weight):\n super().__init__(metric)\n self.weight = weight\n\n def __repr__(self):\n super_repr = super().__repr__()\n return super_repr + \" = \" + str(self.weight)\n\n\nclass ResourceProvider(Singleton):\n \"\"\"Resource provider class, which contains data for the resource provider as well\n as useful functions.\n\n \"\"\"\n\n def __init__(self):\n self._metric_to_metrics_provider = {}\n prometheus_metrics_providers = {\n None: self._init_metrics_providers(MetricsProviderType.PROMETHEUS, None),\n }\n static_metrics_providers = {\n NAMESPACE: self._init_metrics_providers(\n MetricsProviderType.STATIC, NAMESPACE\n ),\n None: self._init_metrics_providers(MetricsProviderType.STATIC, None),\n }\n self.metrics_providers = {\n MetricsProviderType.STATIC: static_metrics_providers,\n MetricsProviderType.PROMETHEUS: prometheus_metrics_providers,\n }\n\n self.unreachable_metrics_providers = {\n MetricsProviderType.PROMETHEUS: {\n None: self._init_metrics_providers(\n MetricsProviderType.PROMETHEUS, None, unreachable=True\n )\n },\n }\n\n static_metrics = {\n NAMESPACE: self._init_metrics(MetricsProviderType.STATIC, NAMESPACE),\n None: self._init_metrics(MetricsProviderType.STATIC, None),\n }\n prometheus_metrics = {\n None: self._init_metrics(MetricsProviderType.PROMETHEUS, None),\n }\n self.metrics = {\n MetricsProviderType.STATIC: static_metrics,\n MetricsProviderType.PROMETHEUS: prometheus_metrics,\n }\n\n self.unreachable_metrics = {\n MetricsProviderType.PROMETHEUS: {\n None: self._init_metrics(\n MetricsProviderType.PROMETHEUS, None, unreachable=True\n )\n }\n }\n\n # Metrics providers\n _METRICS_PROVIDER_INFO = {\n MetricsProviderType.STATIC: {\n # Namespace name\n None: {\n \"providers\": [\n {\n \"name\": \"static_provider\",\n \"provided_metrics\": [\n # (metric name at mp, metric value)\n (\"electricity_cost_1\", 0.9),\n (\"green_energy_ratio_1\", 0.1),\n ],\n },\n ],\n \"metrics\": [\n {\n \"name\": \"electricity_cost_1\",\n \"mp_name\": \"static_provider\",\n \"allowed_values\": [],\n \"min\": 0,\n \"max\": 1,\n },\n {\n \"name\": \"green_energy_ratio_1\",\n \"mp_name\": \"static_provider\",\n \"allowed_values\": [],\n \"min\": 0,\n \"max\": 1,\n },\n ],\n },\n NAMESPACE: {\n \"providers\": [\n {\n \"name\": \"static_provider_w_namespace\",\n \"provided_metrics\": [\n # (metric name at mp, metric value)\n (\"existing_nsed_metric\", 0.9),\n ],\n },\n ],\n \"metrics\": [\n {\n \"name\": \"existing_namespaced_metric\",\n \"mp_name\": \"static_provider_w_namespace\",\n # metric name at mp\n \"mp_metric_name\": \"existing_nsed_metric\",\n \"allowed_values\": [],\n \"min\": 0,\n \"max\": 1,\n },\n ],\n },\n },\n MetricsProviderType.PROMETHEUS: {\n # Namespace name\n None: {\n \"providers\": [\n {\n \"name\": \"prometheus\",\n \"provided_metrics\": [\n # (metric name at mp, metric value)\n (\"heat_demand_zone_1\", 1),\n (\"heat_demand_zone_2\", 2),\n (\"heat_demand_zone_3\", 3),\n (\"heat_demand_zone_4\", 4),\n (\"heat_demand_zone_5\", 5),\n ],\n \"url\": \"http://prometheus:9090\",\n },\n {\n \"name\": \"prometheus-unreachable\",\n \"provided_metrics\": [\n (\"heat_demand_zone_unreachable\", None),\n ],\n \"url\": \"1.2.3.4:9090\",\n },\n ],\n \"metrics\": [\n {\n \"name\": \"heat_demand_zone_1\",\n \"mp_name\": \"prometheus\",\n \"allowed_values\": [],\n \"min\": 0,\n \"max\": 5,\n },\n {\n \"name\": \"heat_demand_zone_2\",\n \"mp_name\": \"prometheus\",\n \"allowed_values\": [],\n \"min\": 0,\n \"max\": 5,\n },\n {\n \"name\": \"heat_demand_zone_3\",\n \"mp_name\": \"prometheus\",\n \"allowed_values\": [],\n \"min\": 0,\n \"max\": 5,\n },\n {\n \"name\": \"heat_demand_zone_4\",\n \"mp_name\": \"prometheus\",\n \"allowed_values\": [],\n \"min\": 0,\n \"max\": 5,\n },\n {\n \"name\": \"heat_demand_zone_5\",\n \"mp_name\": \"prometheus\",\n \"allowed_values\": [],\n \"min\": 0,\n \"max\": 5,\n },\n {\n \"name\": \"heat_demand_zone_unreachable\",\n \"mp_name\": \"prometheus-unreachable\",\n \"allowed_values\": [],\n \"min\": 0,\n \"max\": 5,\n },\n ],\n },\n },\n MetricsProviderType.KAFKA: {},\n }\n\n @classmethod\n def _add_metrics_to_metrics_provider(cls, mp, metrics):\n \"\"\"\n Add valued metrics to the metrics provider.\n\n Although only static metrics providers resources know about the values of the\n metrics they provide, we need to add valued metrics to metrics providers\n of all types, since they also need to be able to 'predict' which behaviour\n the actual metrics provider will have during the tests.\n\n Args:\n mp (BaseMetricsProviderDefinition): the metrics provider\n metrics (list[BaseMetricDefinition): the metrics\n\n Raises:\n NotImplementedError: if the MetricsProviderType is not set\n \"\"\"\n providers_info = cls._METRICS_PROVIDER_INFO[mp.type][mp.namespace][\"providers\"]\n provided_metrics = next(\n provider_info[\"provided_metrics\"]\n for provider_info in providers_info\n if provider_info[\"name\"] == mp.name\n )\n\n # Check if the provided metrics are equal to the metrics\n num_metrics = len(metrics)\n if len(provided_metrics) != num_metrics:\n raise ValueError(\n f\"Found {len(provided_metrics)} metrics for metrics provider \"\n f\"{mp.name}. Expected {num_metrics}.\"\n )\n\n # Check what type of provider is used at the moment\n if mp.type == MetricsProviderType.STATIC:\n valued_metric_class = StaticMetric\n elif mp.type == MetricsProviderType.PROMETHEUS:\n valued_metric_class = PrometheusMetric\n else:\n raise NotImplementedError()\n # Iterate through the provided metrics\n valued_metrics = []\n for i, (metric_name, metric_value) in enumerate(provided_metrics):\n metric = metrics[i]\n if metric.mp_metric_name != metric_name:\n msg = (\n f\"Unexpected name {metric.mp_metric_name}. Expected: {metric_name}.\"\n )\n raise ValueError(msg)\n valued_metric = valued_metric_class(metric, metric_value)\n valued_metrics.append(valued_metric)\n mp.set_valued_metrics(valued_metrics)\n\n @classmethod\n def _init_metrics_providers(cls, mp_type, namespace, unreachable=False):\n \"\"\"\n Create and return the metrics provider resource definition which\n matches the type and namespace parameters given.\n\n Args:\n mp_type (MetricsProviderType): the type of metrics provider to create.\n namespace (str, optional): the namespace of the metrics provider to create.\n unreachable (bool): flag indicating whether the metrics provider should be\n unreachable\n\n Returns:\n BaseMetricsProviderDefinition:\n The resource definition created.\n\n Raises:\n NotImplementedError: if the MetricsProviderType is not set\n \"\"\"\n kind = (\n ResourceKind.METRICSPROVIDER\n if namespace\n else ResourceKind.GLOBALMETRICSPROVIDER\n )\n providers_info = (\n cls._METRICS_PROVIDER_INFO.get(mp_type, {})\n .get(namespace, {})\n .get(\"providers\", [])\n )\n mps = []\n for provider_info in providers_info:\n provider_is_unreachable = any(\n metric_value is None\n for (metric_name, metric_value) in provider_info[\"provided_metrics\"]\n )\n if unreachable == provider_is_unreachable:\n mp_name = provider_info[\"name\"]\n if mp_type == MetricsProviderType.STATIC:\n # We do not add the metrics here since we need the metric resource\n # definitions for that, and they are not yet instantiated.\n # They are added later by calling _add_metrics_to_metrics_provider()\n # in _init_metrics().\n mps.append(\n BaseStaticMetricsProviderDefinition(mp_name, kind, namespace)\n )\n elif mp_type == MetricsProviderType.PROMETHEUS:\n url = provider_info[\"url\"]\n mps.append(\n BasePrometheusMetricsProviderDefinition(\n mp_name, kind, namespace, url\n )\n )\n else:\n raise NotImplementedError()\n return mps\n\n def _init_metrics(self, mp_type, namespace, unreachable=False):\n \"\"\"\n Create and return the metric resource definitions which\n matches the type and namespace parameters given.\n\n Args:\n mp_type (MetricsProviderType): the type of the metrics provider providing\n the metrics to create\n namespace (str, optional): the namespace of the metrics to create.\n unreachable (bool): flag indicating whether the metrics provider providing\n these metrics is unreachable\n\n Returns:\n list(BaseMetricDefinition):\n list of the created metric resource definitions\n\n Raises:\n ValueError: if ResourceProvider.metrics_providers has not been initialized.\n \"\"\"\n kind = ResourceKind.METRIC if namespace else ResourceKind.GLOBALMETRIC\n metrics_info = (\n self._METRICS_PROVIDER_INFO.get(mp_type, {})\n .get(namespace, {})\n .get(\"metrics\", [])\n )\n\n # We will collect metrics from all metrics providers of the correct type\n # and in the correct namespace in the metrics list.\n metrics = []\n\n # all metrics providers of the correct type in the correct namespace\n if unreachable:\n mps_list = self.unreachable_metrics_providers\n else:\n mps_list = self.metrics_providers\n mps = mps_list.get(mp_type, {}).get(namespace, {})\n\n # Mapping from metrics provider resource definition to its metrics.\n # Initially empty.\n metrics_for_mp = dict.fromkeys([mp for mp in mps], [])\n for metric_info in metrics_info:\n # check if metric has the correct reachability. Skip if not.\n mp_name = metric_info[\"mp_name\"]\n reachability_matches = True if mp_name in [mp.name for mp in mps] else False\n if reachability_matches:\n # Create and collect the metric\n metric_name = metric_info[\"name\"]\n mp_metric_name = metric_info.get(\"mp_metric_name\", None)\n metric = BaseMetricDefinition(\n metric_name,\n kind,\n namespace,\n metric_info[\"allowed_values\"],\n metric_info[\"min\"],\n metric_info[\"max\"],\n mp_name,\n mp_metric_name=mp_metric_name,\n )\n metrics.append(metric)\n\n # remember its metrics provider for performance reasons\n mps_w_correct_name = [mp for mp in mps if mp.name == mp_name]\n if len(mps_w_correct_name) != 1:\n msg = (\n f\"Expected 1 metrics provider with the name {mp_name}. \"\n f\"Found {len(mps_w_correct_name)}.\"\n )\n raise ValueError(msg)\n mp = mps_w_correct_name[0]\n self._metric_to_metrics_provider[metric] = mp\n\n # save this metric to the metrics provider so it can be added later.\n metrics_for_mp[mp].append(metric)\n\n # The metrics providers need their metrics, so we add them here - also for\n # non-static metrics providers, since information about the metrics they\n # provide is needed in the tests.\n sanity_check_number_of_metrics = 0\n for mp, mp_metrics in metrics_for_mp.items():\n sanity_check_number_of_metrics += len(mp_metrics)\n self._add_metrics_to_metrics_provider(mp, mp_metrics)\n if len(metrics) != sanity_check_number_of_metrics:\n msg = (\n f\"Expected {len(metrics)} and {sanity_check_number_of_metrics} \"\n f\"to be equal.\"\n )\n raise ValueError(msg)\n\n return metrics\n\n def get_metrics_provider(self, metric):\n \"\"\"\n Return the metrics provider resource definition which\n matches the type and namespace parameters given.\n\n Args:\n metric (BaseMetricDefinition): the resource definition of the metric\n which metrics provider is sought\n\n Returns:\n BaseMetricsProviderDefinition:\n The metrics provider resource definition.\n \"\"\"\n return self._metric_to_metrics_provider[metric]\n\n def get_metrics_in_namespace(\n self, sample_size, namespace, mp_type, unreachable=False\n ):\n \"\"\"\n Return list of sample_size random metrics provided by a metrics provider\n of the given type.\n\n Args:\n sample_size (int): the number of metrics\n namespace (str, optional): the namespace of the desired metrics\n mp_type (MetricsProviderType): the type of the metrics provider that\n should be providing the metrics\n unreachable (bool): flag indicating whether the metrics should be\n unreachable\n\n Returns:\n list(BaseMetricDefinition):\n list of sample_size randomly selected metric resource definitions.\n\n Raises:\n ValueError:\n if fewer than sample_size metrics were found\n \"\"\"\n metrics = list(self.metrics.get(mp_type, {}).get(namespace, {}))\n desired_metrics = [\n m for m in metrics if unreachable == self._is_unreachable(m, mp_type)\n ]\n if len(desired_metrics) < sample_size:\n unreachable_str = \"unreachable\" if unreachable else \"reachable\"\n msg = (\n f\"There are not enough {unreachable_str} metrics. Needed \"\n f\"{sample_size}, found {len(desired_metrics)}: {desired_metrics}.\"\n )\n raise ValueError(msg)\n return random.sample(desired_metrics, sample_size)\n\n def get_metrics(\n self,\n sample_size,\n namespaced=False,\n mp_type=MetricsProviderType.STATIC,\n unreachable=False,\n ):\n \"\"\"\n Return list of sample_size random metrics provided by a metrics provider\n of the given type.\n\n Args:\n sample_size (int): the number of metrics\n namespaced (bool): flag indicating whether the metrics should be\n namespaced\n mp_type (MetricsProviderType): the type of the metrics provider that\n should be providing the metrics\n unreachable (bool): flag indicating whether unreachable metrics\n should be included\n\n Returns:\n list(BaseMetricDefinition):\n list of sample_size randomly selected metric resource definitions.\n\n Raises:\n ValueError:\n if fewer than sample_size metrics were found\n \"\"\"\n namespace = NAMESPACE if namespaced else None\n return self.get_metrics_in_namespace(\n namespace, sample_size, mp_type, unreachable\n )\n\n def _is_unreachable(self, m, mp_type):\n return m in self.unreachable_metrics.get(mp_type, {}).get(m.namespace, {})\n\n def get_global_static_metrics_provider(self):\n mps = self.metrics_providers[MetricsProviderType.STATIC][None]\n if len(mps) != 1:\n raise ValueError(\n f\"Expected 1 global static metrics provider. \" f\"Found {len(mps)}.\"\n )\n return mps[0]\n\n def get_namespaced_static_metrics_provider(self):\n mps = self.metrics_providers[MetricsProviderType.STATIC][NAMESPACE]\n if len(mps) != 1:\n raise ValueError(\n f\"Expected 1 namespaced static metrics provider. \" f\"Found {len(mps)}.\"\n )\n return mps[0]\n\n def get_global_prometheus_metrics_provider(self, reachable=True):\n if reachable:\n mps = self.metrics_providers[MetricsProviderType.PROMETHEUS][None]\n else:\n mps = self.unreachable_metrics_providers[MetricsProviderType.PROMETHEUS][\n None\n ]\n if len(mps) != 1:\n raise ValueError(\n f\"Expected 1 global prometheus metrics provider \"\n f\"(reachable={reachable}). Found {len(mps)}.\"\n )\n return mps[0]\n\n\nprovider = ResourceProvider()\n","sub_path":"rak/functionals/resource_provider.py","file_name":"resource_provider.py","file_ext":"py","file_size_in_byte":42199,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"630113322","text":"import collections\nimport os\nimport pickle as pkl\nfrom itertools import chain\nfrom pathlib import Path\nfrom typing import *\n\nimport cv2\nimport imgaug as ia\nimport imgaug.augmenters as iaa\nimport imutils\nimport numpy as np\nimport tensorflow as tf\nfrom sklearn.preprocessing import LabelEncoder\n\nfrom classifier.data_utils import rebalance_by_path\nfrom common import CLASSIFIER_INPUT_HEIGHT, CLASSIFIER_INPUT_WIDTH\n\nnp.random.seed(0)\n\n\nclass Merger:\n def __init__(self, input_class: str, output_class: str):\n self._input_class = input_class\n self._output_class = output_class\n\n def _merge_if_list(self, instance: Iterable, label_encoder: Optional[LabelEncoder]) -> Iterable:\n new_classes = []\n for cls in instance:\n if isinstance(cls, int):\n transformed = label_encoder.inverse_transform([instance])[0]\n if transformed == self._input_class:\n if self._output_class in new_classes:\n continue\n else:\n new_classes.append(label_encoder.transform([self._output_class])[0])\n else:\n if cls == self._input_class:\n if self._output_class in new_classes:\n continue\n else:\n new_classes.append(self._output_class)\n if cls not in new_classes:\n new_classes.append(cls)\n\n return new_classes\n\n def _merge_if_single(self, instance: Union[str, int], label_encoder: Optional[LabelEncoder]) -> Union[str, int]:\n if isinstance(instance, int) or type(instance) in [np.int32, np.int64]:\n transformed = label_encoder.inverse_transform([instance])[0]\n if transformed == self._input_class:\n return label_encoder.transform([self._output_class])[0]\n else:\n if instance == self._input_class:\n return self._output_class\n return instance\n\n def merge(self, instance: Union[str, collections.Iterable]) -> Union[str, collections.Iterable]:\n if isinstance(instance, collections.Iterable) or isinstance(instance, np.ndarray):\n return self._merge_if_list(instance, None)\n elif isinstance(instance, str):\n return self._merge_if_single(instance, None)\n else:\n raise TypeError(\"Unknown type\")\n\n def merge_using_label_encoder(self, instance: Union[int, collections.Iterable],\n label_encoder: LabelEncoder) -> Union[int, collections.Iterable]:\n if isinstance(instance, collections.Iterable) or isinstance(instance, np.ndarray):\n return self._merge_if_list(instance, label_encoder)\n elif isinstance(instance, str) or isinstance(instance, int) or type(instance) in [np.int32, np.int64]:\n return self._merge_if_single(instance, label_encoder)\n else:\n raise TypeError(\"Unknown type %s\" % type(instance))\n\n\nclass CompoundMerger(Merger):\n def __init__(self, mergers: collections.Iterable):\n super().__init__(\"\", \"\")\n self._mergers = mergers\n\n def merge(self, instance: Union[str, collections.Iterable]) -> Union[str, collections.Iterable]:\n result = instance\n for merg in self._mergers:\n result = merg.merge(result)\n return result\n\n def merge_using_label_encoder(self, instance: Union[int, collections.Iterable],\n label_encoder: LabelEncoder):\n result = instance\n for merg in self._mergers:\n result = merg.merge_using_label_encoder(result, label_encoder)\n return result\n\n\ncommon_class_merger = CompoundMerger([\n Merger(\"warning_pedestrians\", \"pedestrian_crossing\")\n])\n\n\ndef get_images(data_path: Path) -> Iterable[Path]:\n return chain(\n data_path.rglob(\"*.png\"),\n data_path.rglob(\"*.jpg\"),\n data_path.rglob(\"*.tiff\"),\n data_path.rglob(\"*.jpeg\"),\n )\n\n\ndef get_augmenters() -> iaa.Sequential:\n return iaa.Sequential(children=[\n # iaa.JpegCompression((20, 90)),\n iaa.Add((-20, 20)),\n iaa.Multiply((0.8, 1.2)),\n iaa.AdditiveGaussianNoise(0, 0.1),\n iaa.Invert(p=0.5),\n iaa.AdditivePoissonNoise(lam=(0, 12)),\n iaa.Affine(\n # scale=(0.8, 1.2),\n translate_percent=(-0.1, 0.1),\n # rotate=(-15, 15),\n mode=ia.ALL\n )], random_order=True\n )\n\n\nclass DataLoader:\n def __init__(self, data_path: str, is_training: bool):\n self._data_path = Path(data_path)\n self._is_training = is_training\n\n self.all_classes = self.get_classes_from_data_path()\n tf.logging.info(\"Loaded {} classes\".format(self.all_classes))\n\n self.num_classes = len(self.all_classes)\n self.label_encoder = LabelEncoder()\n self.label_encoder.fit(self.all_classes)\n self.indexed_classes = self.label_encoder.transform(self.all_classes)\n\n self._augmenters = get_augmenters() if is_training else None\n self._one_hot_class_helper = np.eye(self.num_classes)\n\n self._x_paths = list(get_images(self._data_path))\n if self._is_training:\n self._x_paths = rebalance_by_path(self._x_paths, fraction_of_most_counted_class=0.6)\n\n self._x_paths = np.asarray(self._x_paths)\n np.random.shuffle(self._x_paths)\n self._x_paths = np.asarray([str(x.as_posix()).encode('utf-8') for x in self._x_paths])\n\n def get_classes_from_data_path(self) -> List[str]:\n paths = self._data_path.iterdir()\n return [p.name for p in paths]\n\n def save_label_encoder(self, path: str):\n with open(path, 'wb') as f:\n pkl.dump(self.label_encoder, f, protocol=pkl.HIGHEST_PROTOCOL)\n\n def input_fn(self, batch_size: int = 32, buffer_size: int = 2048):\n def _f():\n return self._input_fn(batch_size, buffer_size)\n\n return _f\n\n def _prepare_single_record(self, path: bytes):\n img_path = path.decode('utf-8')\n img = cv2.imread(img_path)\n height, width = img.shape[:2]\n if height > width:\n img = imutils.resize(img, height=CLASSIFIER_INPUT_HEIGHT)\n to_pad_from_left = (32 - img.shape[1]) // 2\n to_pad_from_right = (32 - img.shape[1] - to_pad_from_left)\n padding = [[0, 0], [to_pad_from_left, to_pad_from_right], [0, 0]]\n else:\n img = imutils.resize(img, width=CLASSIFIER_INPUT_WIDTH)\n to_pad_from_top = (32 - img.shape[0]) // 2\n to_pad_from_bottom = (32 - img.shape[0] - to_pad_from_top)\n padding = [[to_pad_from_top, to_pad_from_bottom], [0, 0], [0, 0]]\n img = np.pad(img, padding, mode=\"constant\", constant_values=0)\n if self._is_training:\n img = self._augmenters.augment_image(img)\n\n class_name = os.path.basename(os.path.dirname(img_path))\n a_class = self.label_encoder.transform([class_name])[0]\n img = cv2.cvtColor(cv2.cvtColor(img, cv2.COLOR_BGR2GRAY), cv2.COLOR_GRAY2BGR)\n img = img.astype(np.float32)\n a_class = a_class.astype(np.int32)\n return img, a_class\n\n def _process_input_tensor(self, input_tensor: tf.Tensor):\n img, a_class_one_hot = tf.py_func(self._prepare_single_record, inp=[input_tensor],\n Tout=[tf.float32, tf.int32])\n img.set_shape([None, None, 3])\n a_class_one_hot.set_shape([])\n return img, a_class_one_hot\n\n def _input_fn(self, batch_size: int, buffer_size: int = 2048) -> Iterable[Dict[str, tf.Tensor]]:\n dataset = tf.data.Dataset.from_tensor_slices(self._x_paths)\n if self._is_training:\n dataset = dataset.shuffle(buffer_size)\n dataset = dataset.map(self._process_input_tensor, num_parallel_calls=8)\n dataset.repeat(1)\n dataset = dataset.batch(batch_size)\n dataset = dataset.prefetch(buffer_size)\n\n iterator = dataset.make_one_shot_iterator()\n images_batch, labels_batch = iterator.get_next()\n\n x = {\n \"image\": images_batch\n }\n y = {\n \"label\": labels_batch,\n }\n return x, y\n","sub_path":"src/classifier/data.py","file_name":"data.py","file_ext":"py","file_size_in_byte":8224,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"387732782","text":"# ps2\nimport os\nimport numpy as np\nimport cv2\nimport time\n\nfrom disparity_ssd import disparity_ssd\nfrom disparity_ncorr import disparity_ncorr\n\ndef scale(image):\n return ((image - np.min(image)) * (255.0/np.max(image)) ).astype(np.uint8)\n\n## 1-a\n# Read images\nL = cv2.imread(os.path.join('input', 'pair2-L.png'), 0) * (1.0 / 255.0) # grayscale, [0, 1]\nR = cv2.imread(os.path.join('input', 'pair2-R.png'), 0) * (1.0 / 255.0)\n\nD_L = scale(disparity_ssd(L, R))\nD_R = scale(disparity_ssd(R, L))\n\nC_L = scale(disparity_ncorr(L, R))\nC_R = scale(disparity_ncorr(R, L))\ncv2.imwrite(\"part5-original-ssd-L.png\", D_L)\ncv2.imwrite(\"part5-original-ssd-R.png\", D_R)\ncv2.imwrite(\"part5-original-ncorr-L.png\", C_L)\ncv2.imwrite(\"part5-original-ncorr-R.png\", C_R)\n# Compute disparity (using method disparity_ssd defined in disparity_ssd.py)\nfor i in range(3, 16, 2):\n for j in [1, 5, 10]:\n if j < i: \n # Blur\n Lb = cv2.GaussianBlur(L, (i,i), j)\n Rb = cv2.GaussianBlur(R, (i,i), j)\n D_L = scale(disparity_ssd(Lb, Rb))\n D_R = scale(disparity_ssd(Rb, Lb))\n\n C_L = scale(disparity_ncorr(Lb, Rb))\n C_R = scale(disparity_ncorr(Rb, Lb))\n cv2.imwrite(\"part5-%d-%d-blurred-ssd-L.png\" % (i,j), D_L)\n cv2.imwrite(\"part5-%d-%d-blurred-ssd-R.png\" % (i,j), D_R)\n cv2.imwrite(\"part5-%d-%d-blurred-ncorr-L.png\" % (i,j), C_L)\n cv2.imwrite(\"part5-%d-%d-blurred-ncorr-R.png\" % (i,j), C_R)\n # Sharpen\n Ls = 1.5*L - 0.5*Lb\n Rs = 1.5*R - 0.5*Rb\n D_L = scale(disparity_ssd(Ls, Rs))\n D_R = scale(disparity_ssd(Rs, Ls))\n\n C_L = scale(disparity_ncorr(Ls, Rs))\n C_R = scale(disparity_ncorr(Rs, Ls))\n cv2.imwrite(\"part5-%d-%d-sharpened-ssd-L.png\" % (i,j), D_L)\n cv2.imwrite(\"part5-%d-%d-sharpened-ssd-R.png\" % (i,j), D_R)\n cv2.imwrite(\"part5-%d-%d-sharpened-ncorr-L.png\" % (i,j), C_L)\n cv2.imwrite(\"part5-%d-%d-sharpened-ncorr-R.png\" % (i,j), C_R)\n\n","sub_path":"omscs/vision-4495/ps2/ps2-5.py","file_name":"ps2-5.py","file_ext":"py","file_size_in_byte":1969,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"403742073","text":"# Kaggle training\n# This is a slightly different version of the wrapper to use with the RAY RLlib training\nfrom collections import Counter\nfrom math import sqrt\nimport gym\nimport kaggle_environments as kaggle\nimport numpy as np\n\nimport logging\n\n\n\nfrom gym.spaces import Discrete, Box\n\nfrom ray.rllib.env.multi_agent_env import MultiAgentEnv\n\nclass HungryGeeseKaggle(MultiAgentEnv):\n \"\"\"A class to contain environments, so that a learning algorithm can just access the observation space and actions pace\n I wouldn't have bothered but kaggle environments need some additional processing around the observation space\n And I might as well create this in case I decide to make some environments in future...\"\"\"\n def __init__(self, config):\n \n self.env = kaggle.make(\"hungry_geese\")\n self.num_agents = 4\n self.env.reset(self.num_agents)\n self.rows = self.env.configuration.rows\n self.columns = self.env.configuration.columns\n #self.observation_space = np.array((self.rows, self.columns, 3))\n self.observation_space = Box(low=-100, high=1000, shape=(self.rows, self.columns, 3), dtype=np.float32)\n # self.observation_space = self.rows * self.columns\n self.action_space = Discrete(4)\n self.discrete = True\n self.actions = ['NORTH','SOUTH','WEST','EAST', '']\n self.prev_head_locations = [0,0,0,0]\n self.food_history = [0,0,0,0]\n self.names = ['geese1','geese2','geese3','geese4']\n logging.basicConfig(filename='logging2.log', level=logging.DEBUG)\n\n \n def reset(self):\n self.env.reset(num_agents=self.num_agents)\n states = {}\n for i in range(0, self.num_agents):\n states[self.names[i]] = self.get_geese_observation(i, self.env.state)\n logging.debug(f'initial states: {states}')\n return states\n \n '''\n def step(self, action, agent=0):\n\n status = self.env.step([self.actions[action]])\n state = self.get_geese_observation(agent, self.env.state)\n reward = status[agent]['reward']\n if status[agent]['status']=='DONE':\n done = True\n else:\n done = False\n return state, reward, done, 1\n ''' \n \n def step(self, action_dict):\n \"\"\"Useful if the environment accepts multiple actions simultaneously\"\"\"\n\n action1 = action_dict.get('geese1', 0)\n action2 = action_dict.get('geese2', 0)\n action3 = action_dict.get('geese3', 0)\n action4 = action_dict.get('geese4', 0)\n\n actions = [action1, action2, action3, action4]\n\n \n done = False\n prev_status = self.env.state\n for i in range(0, self.num_agents):\n old_board = self.get_geese_observation(i, prev_status)\n old_geese_loc = self.get_geese_coord(old_board)\n\n if len(old_geese_loc) > 0:\n self.prev_head_locations[i] = old_geese_loc[0]\n\n\n status = self.env.step([self.actions[action] for action in actions])\n \n running = False\n next_states = {}\n rewards = {}\n dones = {}\n for i in range(0, self.num_agents):\n\n next_states[self.names[i]] = self.get_geese_observation(i, self.env.state)\n reward = self.reward_geese(prev_status, status, i)\n #rewards.append(status[i]['reward'])\n rewards[self.names[i]] = reward\n if status[i]['status']=='DONE':\n dones[self.names[i]] = True\n else:\n dones[self.names[i]] = False\n if status[i]['status']=='ACTIVE':\n running = True\n\n '''\n if False not in dones:\n done = True\n else:\n done = False\n '''\n if running == False:\n dones['__all__'] = True\n else:\n dones['__all__'] = False\n\n logging.debug(f'Rewards: {rewards}')\n return next_states, rewards, dones, {}\n \n def reward_geese(self, prev_status, status, geese):\n\n step = status[0].observation.step\n reward = status[geese]['reward']\n step_reward = 0\n old_length = len(prev_status[0].observation.geese[geese])\n new_length = len(status[0].observation.geese[geese])\n\n old_board = self.get_geese_observation(geese, prev_status)\n board = self.get_geese_observation(geese, self.env.state)\n\n\n old_geese_loc = self.get_geese_coord(old_board)\n geese_loc = self.get_geese_coord(board)\n\n old_food_loc = self.get_food_coord(old_board)\n food_loc = self.get_food_coord(board)\n\n enemy_geese_loc = self.get_enemy_geese_head_coord(board)\n # print('testing')\n # print(f'old food: {old_food_loc}, new_food: {food_loc}, old geese: {old_geese_loc}, new geese: {geese_loc}')\n # print(f'enemy geese: {enemy_geese_loc}')\n\n\n old_distances = []\n new_distances = []\n move_reward = 0\n # Measure the distance to old food only - as new food pops up when eaten\n if (len(geese_loc) > 0) & (len(old_food_loc) > 0):\n old_distances = [self.get_distance_toroidal(old_geese_loc[0], food) for food in old_food_loc]\n new_distances = [self.get_distance_toroidal(geese_loc[0], food) for food in food_loc]\n #print(f'testing: old_distances: {old_distances}, new_distances: {new_distances}')\n\n old_min_distance = min(old_distances)\n new_min_distance = min(new_distances)\n if old_min_distance > new_min_distance:\n # Moved closer to a food\n move_reward = 100 / (new_min_distance + 1)\n #print('rewarded')\n else:\n #moved away\n move_reward = -20\n #print('punished')\n\n length_reward = 0\n food_reward = 0\n punish = 0\n\n # If the move kills the geese, then punish accordingly\n #if new_length == 0:\n # punish = -20\n\n # Food reward is based on how quickly food was obtained\n if new_length > old_length:\n food_reward = 200 - 2*self.food_history[geese]\n self.food_history[geese] = 0\n else:\n self.food_history[geese] += 1\n \n #print(self.food_history)\n # Check whether the geese was adjacent to food and missed it\n\n #print(f'reward calc: reward: {reward}, step_reward {step_reward}, length {length_reward}')\n return step_reward + length_reward + food_reward + punish + move_reward\n \n\n def get_geese_coord(self, board):\n return self.get_coord_from_np_grid(board, 101)\n \n def get_food_coord(self, board):\n return self.get_coord_from_np_grid(board, 1000)\n \n def get_enemy_geese_head_coord(self, board):\n return self.get_coord_from_np_grid(board, -99)\n \n \n def get_coord_from_np_grid(self, grid, value):\n coords = []\n for i in range(0, len(np.where(grid==value)[0])):\n coords.append((np.where(grid==value)[0][i], np.where(grid==value)[1][i]))\n return coords\n \n\n def get_distance_toroidal(self, coord1, coord2):\n x1, y1 = coord1[0], coord1[1]\n x2, y2 = coord2[0], coord2[1]\n\n dx = abs(x2 - x1)\n dy = abs(y2 - y1)\n\n if dx > 0.5*self.rows:\n dx = self.rows - dx\n \n if dy > 0.5*self.columns:\n dy = self.columns - dy\n\n return sqrt(dx*dx + dy*dy)\n\n \n def coordinates_adjacent_check(self, coord1, coord2):\n x1, y1 = coord1\n x2, y2 = coord2\n if x1==x2:\n if abs(y1 - y2) == 1:\n return True\n else:\n return False\n elif y2 == y1:\n if abs(x1 - x2) == 1:\n return True\n else:\n return False\n else:\n return False\n\n def get_coordinate(self, item, columns):\n (x, y) = divmod(item+1, columns)\n x = x\n y = y - 1\n return (x, y)\n \n \n def get_state(self, agent=0):\n if self.env_type=='gym':\n if self.env_name=='AirRaid-v0':\n return self.env.ale.getScreenRGB2()\n\n else:\n return self.env.state\n elif self.env_type=='kaggle':\n return self.get_geese_observation(agent, self.env.state) \n \n def get_geese_observation(self, agent, state):\n \"\"\"\n Given a particular geese, does some processing and returns a geese specific observation. \n Unfortunately specific to the geese environment for now.\n Encoding as follows: \n 2: enemy snake head\n 1: enemy snake body\n 11: own head\n 12: own body\n 100: food\n \"\"\"\n\n game_board_self = np.zeros(self.rows*self.columns, None)\n game_board_enemy = np.zeros(self.rows*self.columns, None)\n game_board_food = np.zeros(self.rows*self.columns, None)\n\n\n for i, geese in enumerate(state[0].observation.geese):\n identify=0\n if i==agent:\n identify=100\n for j, cell in enumerate(geese):\n if j == 0:\n game_board_self[cell] = identify+1\n else:\n game_board_self[cell] = identify+2\n else:\n identify=-100\n for j, cell in enumerate(geese):\n if j == 0:\n game_board_enemy[cell] = identify+1\n else:\n game_board_enemy[cell] = identify+2\n \n for food in state[0].observation.food:\n game_board_food[food] = 1000\n game_board_self = game_board_self.reshape([self.rows, self.columns])\n game_board_enemy = game_board_enemy.reshape([self.rows, self.columns])\n game_board_food = game_board_food.reshape([self.rows, self.columns])\n\n head = self.get_geese_coord(game_board_self)\n\n if len(head)==0:\n head = self.prev_head_locations[agent]\n else:\n head = head[0]\n game_board_self = np.roll(game_board_self, 5-head[1], axis=1)\n game_board_self = np.roll(game_board_self, 3-head[0], axis=0)\n game_board_enemy = np.roll(game_board_enemy, 5-head[1], axis=1)\n game_board_enemy = np.roll(game_board_enemy, 3-head[0], axis=0)\n game_board_food = np.roll(game_board_food, 5-head[1], axis=1)\n game_board_food = np.roll(game_board_food, 3-head[0], axis=0)\n\n #game_board = game_board.reshape((game_board.shape[0], game_board.shape[1], 1))\n game_board = np.dstack((game_board_self, game_board_enemy, game_board_food))\n return game_board\n \n\n\n\n\n ","sub_path":"EnvWrapperRay.py","file_name":"EnvWrapperRay.py","file_ext":"py","file_size_in_byte":10717,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"} +{"seq_id":"211987011","text":"from django.urls import path\nfrom . import views,views_extra\nfrom django.conf.urls import url\nfrom django.conf import settings\nfrom django.conf.urls.static import static\n\nhandler404 = views.handler404\nurlpatterns = [\n path('', views.index, name='index'),\n path('arama', views.arama, name='arama'),\n path('giriskalite', views.giriskalite, name='giriskalite'),\n path('uretimkontrol', views.uretimkontrol, name='uretimkontrol'),\n path('isemri', views.isemri, name='isemri'),\n path('yetkilendirme', views.yetkilendirme, name='yetkilendirme'),\n path('performans', views.performans, name='performans'),\n path('yazdir', views.yazdir, name='yazdir'),\n path('login/', views.ulogin, name='ulogin'),\n path('logout/', views.ulogout, name='ulogout'),\n path('pdf/', views.pdf, name='pdf'),\n #hata sayfaları\n path('403', views._403, name='403'),\n #fonksiyonlar\n url(r'^kullanicijson',views.kullanicijson),\n url(r'^kullanicisil',views.kullanicisil),\n url(r'^kullaniciduzelt',views.kullaniciduzelt),\n url(r'^passwordreset',views.passwordreset),\n url(r'^bildirim',views.bildirim),\n url(r'^dashboard',views.dashboard),\n url(r'^uretimdurum',views.uretimdurum),\n url(r'^personeldurum',views.personeldurum),\n url(r'^acikisemirleri',views.acikisemirleri),\n url(r'^tupTuru',views.tupTuru),\n url(r'^kontrolEt',views.kontrolEt),\n url(r'^is_emri_valfleri',views_extra.is_emri_valfleri), \n url(r'^valf_parti_no_ata',views_extra.valf_parti_no_ata), \n url(r'^kurlenmeKontrol',views.kurlenmeKontrol),\n url(r'^newVSN',views.newVSN),\n url(r'^getEmirNo',views.getEmirNo),\n url(r'^hardreset',views.hardreset),\n url(r'^valf_test_kayıt',views_extra.valf_test_kayıt),\n url(r'^pdf_yukle', views_extra.upload_pdf_rapor),\n url(r'valf_montaj_kurlenme_tablo',views_extra.montajKurlenme),\n url(r'valf_govde_save',views_extra.valf_govde_save),\n url(r'GovdekontrolEt',views_extra.GovdekontrolEt),\n url(r'kurlenmegovde',views_extra.kurlenme_govde),\n url(r'valf_govde_parti_no_ata',views_extra.valf_govde_parti_no_ata),\n url(r'govdektarih',views_extra.govdemontajKurlenme),\n url(r'fm200kurlenme',views_extra.FM200kontrolEt),\n url(r'fm200save',views_extra.fm200_save),\n url(r'kurlenmefm200',views_extra.kurlenme_fm200),\n url(r'valf_fm200_parti_no_ata',views_extra.valf_fm200_parti_no_ata),\n url(r'fm200tarih',views_extra.fm200Kurlenme),\n url(r'fm200deger',views_extra.fm200deger),\n url(r'havuztestsave',views_extra.havuztestsave),\n url(r'havuztestcontrol',views_extra.havuztestcontrol),\n url(r'finalmontajcontrol',views_extra.finalmontajcontrol),\n url(r'finalmontajsave',views_extra.finalmontajsave),\n url(r'yazdirtest',views_extra.yazdirtest),\n url(r'isemridurumdegistir',views_extra.isemridurumdegistir),\n \n\n\n] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)\n","sub_path":"ysib/base/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":2887,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"13"}