diff --git "a/6450.jsonl" "b/6450.jsonl"
new file mode 100644--- /dev/null
+++ "b/6450.jsonl"
@@ -0,0 +1,122 @@
+{"seq_id":"230079412","text":"# coding=utf-8\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom sklearn import datasets, linear_model\nimport ipdb\n\ndiabetes = datasets.load_diabetes() # 加载数据\ndiabetes_X = diabetes.data[:,np.newaxis,2]\n\ndiabetes_X_train = diabetes_X[:-20] # 训练数据(前20个)\ndiabetes_X_test = diabetes_X[-20:] # 检验数据(后20个)\ndiabetes_y_train = diabetes.target[:-20] # 训练数据\ndiabetes_y_test = diabetes.target[-20:]\nipdb.set_trace()\n\nregr = linear_model.LinearRegression() # 初始化线性模型\nregr.fit(diabetes_X_train, diabetes_y_train) #这里就是在训练模型了\n\nprint('Coefficients: \\n', regr.coef_) #这就是w0,常数项\nprint(\"Residual sum of squares: %.2f\" % np.mean((regr.predict(diabetes_X_test) - diabetes_y_test) ** 2)) #这个是预测与真实的差\nprint('Variance score: %.2f' % regr.score(diabetes_X_test, diabetes_y_test)) #这里就是得分,1为拟合最好,0最差\n\nplt.scatter(diabetes_X_test, diabetes_y_test, color = 'black')\nplt.plot(diabetes_X_test,regr.predict(diabetes_X_test), color='blue',linewidth=3)\nplt.xticks(())\nplt.yticks(())\n\nplt.show()\n","sub_path":"sklearn/simple_liner_test.py","file_name":"simple_liner_test.py","file_ext":"py","file_size_in_byte":1108,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"}
+{"seq_id":"457377585","text":"from googleapiclient.discovery import build\nimport json\nimport re\nimport pprint\nimport pandas as pd\nfrom pytrends.request import TrendReq\nimport pytrends\n\n\nyt_risingQueriesVAR = []\nyt_topQueriesVAR = []\n\n\ndef youtube_api(input):\n api_key = 'AIzaSyCZrRnFzZxJ3szNYvLVHLoUq1qbdMLVk40'\n youtubeVideoLink = 'https://www.youtube.com/watch?v='\n youtubeChannelLink = 'https://www.youtube.com/channel/'\n youtubePlaylistLink = 'https://www.youtube.com/results?search_query='\n channelList = []\n titleList = []\n thumbnailList = []\n itemList = []\n linkList = []\n\n APIdata = {'Channel Name:' : [], 'Title:' : [], 'Thumbnail:' : [], 'Link:' : [] }\n\n\n youtube = build(serviceName='youtube', version='v3', developerKey=api_key)\n\n request = youtube.search().list(\n part = 'snippet',\n q = input,\n maxResults = 50\n )\n\n response = request.execute()\n\n for item in response['items']:\n channelList.append(item['snippet']['channelTitle'])\n titleList.append(item['snippet']['title'])\n thumbnailList.append(item['snippet']['thumbnails']['high']['url'])\n if item['id']['kind'] == 'youtube#video':\n linkList.append(youtubeVideoLink + item['id']['videoId'])\n elif item['id']['kind'] == 'youtube#playlist':\n linkList.append(youtubePlaylistLink + item['id']['playlistId'])\n else:\n linkList.append(youtubeChannelLink + item['id']['channelId'])\n\n\n for item in channelList:\n APIdata['Channel Name:'].append(item)\n\n for item in titleList:\n APIdata['Title:'].append(item)\n\n for item in thumbnailList:\n APIdata['Thumbnail:'].append(item)\n\n for item in linkList:\n APIdata['Link:'].append(item)\n\n data = APIdata\n\n df = pd.DataFrame.from_dict(data)\n df.to_csv('CSV Files/youtubeData.csv')\n\n\ndef yt_risingQueries(input):\n\n pytrends = TrendReq()\n\n pytrends.build_payload(kw_list=[input], geo='US', gprop='youtube')\n\n\n related_queries = pytrends.related_queries()\n\n dg = related_queries.get(input).get('rising')\n\n df = pd.DataFrame(dg)\n df.to_csv('CSV Files/youtube_RisingKeywords.csv')\n\n for item in dg['query']:\n yt_risingQueriesVAR.append(item)\n\n\n\ndef yt_topQueries(input):\n\n pytrends = TrendReq()\n\n pytrends.build_payload(kw_list=[input], geo='US', gprop='youtube')\n\n\n related_queries = pytrends.related_queries()\n\n dg = related_queries.get(input).get('top')\n\n df = pd.DataFrame(dg)\n df.to_csv('CSV Files/youtube_topKeywords.csv')\n\n for item in dg['query']:\n yt_topQueriesVAR.append(item)\n\n","sub_path":"youtubeData.py","file_name":"youtubeData.py","file_ext":"py","file_size_in_byte":2601,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"}
+{"seq_id":"228073409","text":"#!/usr/bin/env python\n\n# ------------------------------\n# projects/xml/RunXML.py\n# Copyright (C) 2013\n# Glenn P. Downing\n# -------------------------------\n\n# -------\n# imports\n# -------\n\nimport sys\nimport os\n\nfrom XML import solve\n\n# ----\n# main\n# ----\nfor r,d,f in os.walk ( \".\\Tests\" ):\n with open ( \"RunXML.out\", \"w\" ) as output:\n for file in f:\n if file.endswith(\".in\"):\n with open ( \".\\Tests\\\\\" + file, \"r\" ) as input:\n solve(input, output)\n output.write ( \"\\n\\n\\n\\n\" )","sub_path":"XML/XML/RunXMLAll.py","file_name":"RunXMLAll.py","file_ext":"py","file_size_in_byte":560,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"}
+{"seq_id":"560290435","text":"from django.shortcuts import render\nfrom django.http import JsonResponse\n\nfrom rest_framework.decorators import api_view\nfrom rest_framework.response import Response\nfrom .serializers import MedicamentSerializer\n\nfrom .models import Medicament\n\n# Create your views here.\n\n@api_view(['GET'])\ndef Med(request):\n\tapi_urls = {\n\t\t'ListMedicament':'/Medicament-list/',\n\t\t'Create':'/Medicament-create/',\n\t\t'Update':'/Medicament-update/',\n\t}\n\treturn Response(api_urls)\n\n\n\n@api_view(['GET'])\ndef MedList(request):\n\tMeds = Medicament.objects.all().order_by('-id')\n\tMedserializer = MedicamentSerializer(Meds, many=True)\n\treturn Response(Medserializer.data)\n\n\n@api_view(['POST'])\ndef MedCreate(request):\n\tMedserializer = MedicamentSerializer(data=request.data)\n\n\tif Medserializer.is_valid():\n\t\tMedserializer.save()\n\n\treturn Response(Medserializer.data)\n\n@api_view(['POST'])\ndef MedUpdate(request, pk):\n\tMed = Medicament.objects.get(id=pk)\n\tMedserializer = MedicamentSerializer(instance=Med, data=request.data)\n\tif Medserializer.is_valid():\n\t\tMedserializer.save()\n\treturn Response(Medserializer.data)\n\n","sub_path":"rest/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1089,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"}
+{"seq_id":"214791273","text":"import numpy as np\nimport matplotlib.pyplot as plt\nimport time, sys\nsys.path.append(\"/Users/azofeifa/Lab/\")\nsys.path.append(\"/Users/joazofeifa/Lab/\")\n\nfrom interval_searcher import intervals, node\n\ndef simulate(L1=10, L2=100, N1=100, N2=100, N3=100, D=1000000 , sigma=1 ):\n\txe, xm \t\t= 0,0\n\tmotif, eRNA = list(),list()\n\tmotif, eRNA = np.random.uniform(0, D, N1 ),np.random.uniform(0, D, N2 )\n\tmotif, eRNA = [(x-L1, x+L1) for x in motif],[(x-L2, x+L2) for x in eRNA]\n\tcoocur_pts \t= np.random.uniform(0,D, N3 )\n\tcoocur_pts \t= [(x, x+np.random.normal(0, sigma)) for x in coocur_pts]\n\tmotif, eRNA = motif + [(y - L1, y+ L1) for x,y in coocur_pts], eRNA + [(x - L2, x+ L2) for x,y in coocur_pts]\n\t\n\treturn motif, eRNA\n\ndef compute_overlaps(x,y,OUT=\"\"):\n\ty.sort()\n\tT \t= node.tree(y)\n\tj,N,O \t= 0,len(y),list()\n\t#FHW.open(OUT,\"w\")\n\tfor start, stop in x:\n\t\tFINDS \t= T.searchInterval((start, stop))\n\t\tcx \t\t= (stop+start) / 2.\n\t\tfor st,sp in FINDS:\n\t\t\tcy = (sp+st) / 2.\n\t\t\tO.append((cx-cy))\n\treturn O\ndef show():\n\tF \t= plt.figure(figsize=(15,10))\n\tax1 = F.add_subplot(2,2,1)\n\tax2 = F.add_subplot(2,2,2)\n\tax3 = F.add_subplot(2,2,3)\n\tax4 = F.add_subplot(2,2,4)\n\t\n\tN1,N2,N3,sigma \t= 5000,5000,0,1\t\n\tax1.set_title(\"N1: \"+ str(N1) + \", N2: \"+ str(N2)+ \", N3: \"+ str(N3) + \", sigma: \" + str(sigma))\n\tarrivals_motif,arrivals_eRNA \t= simulate(L1=10, L2=10, N1=N1,N2=N2,N3=N3, sigma=sigma)\n\tD \t= compute_overlaps(arrivals_motif, arrivals_eRNA)\n\tax1.hist(D, bins=100)\n\tax1.grid()\n\n\tN1,N2,N3,sigma \t= 100,1000,100,1\t\n\tax2.set_title(\"N1: \"+ str(N1) + \", N2: \"+ str(N2)+ \", N3: \"+ str(N3) + \", sigma: \" + str(sigma))\n\tarrivals_motif,arrivals_eRNA \t= simulate(L1=10, L2=10, N1=N1,N2=N2,N3=N3, sigma=sigma)\n\tD \t= compute_overlaps(arrivals_motif, arrivals_eRNA)\n\tax2.hist(D, bins=100)\n\tax2.grid()\n\t\n\tN1,N2,N3,sigma \t= 10000,1000,10000,5\n\tax3.set_title(\"N1: \"+ str(N1) + \", N2: \"+ str(N2)+ \", N3: \"+ str(N3) + \", sigma: \" + str(sigma))\n\tarrivals_motif,arrivals_eRNA \t= simulate(L1=10, L2=10, N1=N1,N2=N2,N3=N3, sigma=sigma)\n\tD \t= compute_overlaps(arrivals_motif, arrivals_eRNA)\n\tax3.hist(D, bins=100)\n\tax3.grid()\n\n\tN1,N2,N3,sigma \t= 10,1000,100,1\t\n\tax4.set_title(\"N1: \"+ str(N1) + \", N2: \"+ str(N2)+ \", N3: \"+ str(N3) + \", sigma: \" + str(sigma))\n\tarrivals_motif,arrivals_eRNA \t= simulate(L1=10, L2=10, N1=N1,N2=N2,N3=N3, sigma=sigma)\n\tD \t= compute_overlaps(arrivals_motif, arrivals_eRNA)\n\tax4.hist(D, bins=100)\n\tax4.grid()\n\t\n\tplt.show()\n\t\n\nshow()","sub_path":"analysis/co_ocurrence_simulator.py","file_name":"co_ocurrence_simulator.py","file_ext":"py","file_size_in_byte":2420,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"}
+{"seq_id":"499070904","text":"from django.shortcuts import render\nfrom RecordingExperiment.models import *\nfrom django.http import HttpResponse, HttpResponseRedirect\nimport uuid\nfrom django.views.decorators.csrf import csrf_exempt\n\n\n@csrf_exempt\ndef home(request):\n # create uuid\n userid = str(uuid.uuid4()).split(\"-\")[0]\n method = ''\n\n no_training = False\n if no_training:\n # add the user to the trainedusers model\n method = 'expert'\n new_tuser = TrainedUsers.objects.create(user=userid, training=method)\n new_tuser.save()\n\n # redirect directly to the transcribe page\n return HttpResponseRedirect('/transcribe/'+userid)\n\n else:\n # serve based on training counts\n methods = TrainingCounts.objects.all()\n if methods[0].type is 'example':\n example = methods[0]\n interactive = methods[1]\n else:\n example = methods[1]\n interactive = methods[0]\n\n if int(example.count) <= int(interactive.count):\n method = 'example'\n example.count = int(example.count) + 1\n example.save()\n\n elif int(example.count) > int(interactive.count):\n method = 'interactive'\n interactive.count = int(interactive.count) + 1\n interactive.save()\n\n method = 'interactive'\n\n # add the user to the trainedusers model\n new_tuser = TrainedUsers.objects.create(user=userid, training=method)\n new_tuser.save()\n\n return render(request, 'home.html', {'userid': userid, 'method': method})\n\n\n@csrf_exempt\ndef transcribe(request, user_id):\n # define the image list\n img_set = [\"303.jpg\", \"304.jpg\", \"137.jpg\", \"1896.jpg\", \"2426.jpg\"]\n\n # check the user's training method\n user = TrainedUsers.objects.get(user=user_id)\n method = user.training\n\n # how many classifications has the user submitted?\n set_count = int(Classifications.objects.filter(user=user_id).count())\n\n if set_count < 5:\n image_name = img_set[set_count]\n\n return render(request, 'transcribe.html', {'userid': user_id, 'method': method, 'image_name': image_name})\n else:\n # redirect to the google doc form\n return HttpResponseRedirect('https://docs.google.com/forms/d/1mox7IhuComxR6nGcXafOHALBdxmYoyluhNqn2VcEEx0/viewform?usp=send_form')\n\n\n@csrf_exempt\ndef save_classifications(request):\n if request.POST:\n classifications = str(request.POST['classifications'])\n image = str(request.POST['img_name'])\n user = str(request.POST['user_id'])\n duration = int(request.POST['duration'])\n\n # create a new classification set for the image\n new_set = Classifications.objects.create(user=user, fragment=image, duration=duration)\n new_set.save()\n\n\n # add the classifications\n for classification in classifications.split(\";\"):\n if classification != '':\n splt = classification.split(\",\")\n x = int(splt[0])\n y = int(splt[1])\n letter = str(splt[2])\n\n new_set.classification_set.create(x=x, y=y, letter=letter)\n new_set.save()\n\n\n return HttpResponse(200)\n\n\n@csrf_exempt\ndef interactive(request):\n # create uuid\n userid = str(uuid.uuid4()).split(\"-\")[0]\n method = 'interactive'\n\n # add the user to the trainedusers model\n new_tuser = TrainedUsers.objects.create(user=userid, training=method)\n new_tuser.save()\n\n return render(request, 'home.html', {'userid': userid, 'method': method})\n\n@csrf_exempt\ndef example(request):\n # create uuid\n userid = str(uuid.uuid4()).split(\"-\")[0]\n method = 'example'\n\n # add the user to the trainedusers model\n new_tuser = TrainedUsers.objects.create(user=userid, training=method)\n new_tuser.save()\n\n return render(request, 'home.html', {'userid': userid, 'method': method})","sub_path":"RecordingExperiment/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3881,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"}
+{"seq_id":"607516298","text":"#!/usr/bin/env python3\n# -*- coding:utf-8 -*-\n\nimport requests as rq\nimport os\nimport pathlib\nimport logging\nimport datetime\nimport gzip\nimport json\nimport hashlib\nimport pandas as pd\nfrom bs4 import BeautifulSoup as soup\nfrom fake_useragent import UserAgent, FakeUserAgentError\n\n_BASE = 'https://web.archive.org/web/{0}/'\n_OBJ = ''\n_CHOICE = [\n 'http://grad-schools.usnews.rankingsandreviews.com:80/best-graduate-schools/{0}/rankings',\n 'http://grad-schools.usnews.rankingsandreviews.com/best-graduate-schools/{0}/rankings',\n 'http://grad-schools.usnews.rankingsandreviews.com:80/best-graduate-schools/{0}/{1}',\n 'http://grad-schools.usnews.rankingsandreviews.com/best-graduate-schools/{0}/{1}',\n 'https://www.usnews.com:80/best-graduate-schools/{0}/{1}',\n 'https://www.usnews.com/best-graduate-schools/{0}/{1}',\n]\n_SPARK = 'https://web.archive.org/__wb/sparkline'\n_CAPYEAR = 'https://web.archive.org/__wb/calendarcaptures'\n_SUBJECTS = {\n 'top-education-schools': 'edu-rankings',\n 'top-business-schools': 'mba-rankings',\n}\n_IGNORE = [\n b'301 Moved Permanently',\n b'found capture at',\n]\n_ROOT = pathlib.Path(os.path.dirname(os.path.realpath(__file__)))\n_OUTPUT = _ROOT/'rank_output'\n_LOG = _OUTPUT / 'log'\n_UA = None\ntry:\n _UA = UserAgent()\nexcept FakeUserAgentError:\n pass\n\n\nclass RankError(Exception):\n pass\n\n\nclass Page(object):\n def __init__(self, obj, ts, init_page):\n self._obj = obj\n self._ts = ts\n ha = hashlib.md5(_OBJ.encode('ascii')).hexdigest()\n self._ts_dir = _OUTPUT / (obj+ha)/ts\n self._ts_dir.mkdir(exist_ok=True)\n self._tasks = {init_page}\n\n def run(self):\n while len(self._tasks) > 0:\n task = self._tasks.pop()\n try:\n self._download(task)\n except RankError:\n f_name = self._ts_dir/'{0}.html.gz'.format(task)\n with gzip.open(f_name, 'wb') as f:\n f.write(b'')\n continue\n except Exception as e:\n logging.error(\"%s Down Page %d for '%s' in %s\",\n e, task, self._obj, self._ts)\n continue\n self._extraction(task)\n self._merge()\n\n def _merge(self):\n f_name = self._ts_dir/'merge.csv.gz'\n if f_name.exists():\n f_name.unlink()\n ret = pd.DataFrame()\n for idx in self._ts_dir.glob('*.df.gz'):\n df = pd.read_pickle(idx)\n ret = ret.append(df)\n if ret.shape[0] == 0:\n return\n ret.to_csv(f_name, na_rep='N/A', index=False, compression='gzip')\n logging.info(\"Merge '%s' in %s\", self._obj, self._ts)\n\n def _download(self, page):\n assert page > 0\n f_name = self._ts_dir/'{0}.html.gz'.format(page)\n if f_name.exists():\n return\n url = _BASE.format(self._ts)+_OBJ.format(self._obj,\n _SUBJECTS[self._obj])\n if page > 1:\n url += '/page+{0}'.format(page)\n logging.debug('Try URL %s', url)\n try:\n response = rq.get(url=url, headers={\n 'User-Agent': _UA.random}, allow_redirects=False)\n except AttributeError:\n logging.info(\"Page %d missing for '%s' in %s\",\n page, self._obj, self._ts)\n raise RankError\n if response.status_code == 403:\n raise RankError\n response.raise_for_status()\n with gzip.open(f_name, 'wb') as f:\n f.write(response.content)\n logging.info(\"Down Page %d for '%s' in %s\", page, self._obj, self._ts)\n\n def _extraction(self, page):\n assert page > 0\n f_name = self._ts_dir/'{0}.html.gz'.format(page)\n assert f_name.exists()\n with gzip.open(f_name) as f:\n content = f.read()\n for idx in _IGNORE:\n if idx in content:\n return\n sp = soup(content, 'lxml')\n f_name = self._ts_dir/'{0}.df.gz'.format(page)\n\n tab = sp.find('table', class_='stickyHeader')\n if tab is not None:\n if not f_name.exists():\n df = self._ex_sticky_header(tab)\n df.to_pickle(f_name)\n logging.info(\"Extract %d for '%s' in %s\",\n page, self._obj, self._ts)\n return\n\n tab = sp.find('table', class_='ranking-data')\n if tab is not None:\n if not f_name.exists():\n df = self._ex_ranking_data(tab)\n df.to_pickle(f_name)\n logging.info(\"Extract %d for '%s' in %s\",\n page, self._obj, self._ts)\n return\n\n url = _BASE.format(self._ts)+_OBJ.format(self._obj,\n _SUBJECTS[self._obj])\n if page > 1:\n url += '/page+{0}'.format(page)\n logging.error(\"Unknown Pattern %s\", url)\n\n def _ex_ranking_data(self, tab):\n s_data = tab.find_all('tr', valign=\"top\")\n ret = []\n for idx in s_data:\n sch = idx.find_all('td')\n assert len(sch) > 4\n if sch[0].span is None:\n sch = sch[1:]\n rank = sch[0].span.span.get_text(strip=True).replace('#', '')\n name = sch[1].a.get_text(strip=True).replace(u'\\u200b', '')\n addr = sch[1].p.get_text(strip=True)\n score = 'N/A'\n tuition = sch[2].contents[0]\n enroll = sch[3].contents[0]\n data = tuple(idx.strip()\n for idx in (rank, name, addr, score, tuition, enroll))\n ret.append(data)\n df = pd.DataFrame(ret, columns=(\n 'rank', 'name', 'addr', 'score', 'tuition', 'enroll'))\n return df\n\n def _ex_sticky_header(self, tab):\n s_data = tab.find_all('tr', class_='school-data')\n s_titl = tab.find_all('tr', class_='school-title')\n assert len(s_data) == len(s_titl)\n ret = []\n for idx in zip(s_data, s_titl):\n sch_d = idx[1].find_all('td')\n rank = sch_d[0].contents[1] if len(sch_d) == 2 else 'N/A'\n name = sch_d[-1].a.get_text(strip=True)\n addr = sch_d[-1].address.get_text(strip=True)\n score = idx[0].find_all('td')[0].get_text(strip=True)\n tuition = idx[0].find_all('td')[1].get_text(strip=True)\n enroll = idx[0].find_all('td')[2].em.get_text(strip=True)\n data = tuple(idx.strip()\n for idx in (rank, name, addr, score, tuition, enroll))\n ret.append(data)\n df = pd.DataFrame(ret, columns=(\n 'rank', 'name', 'addr', 'score', 'tuition', 'enroll'))\n return df\n\n\nclass Calender(object):\n def __init__(self, obj):\n _OUTPUT.mkdir(exist_ok=True)\n self._obj = obj\n ha = hashlib.md5(_OBJ.encode('ascii')).hexdigest()\n self._obj_dir = _OUTPUT / (obj+ha)\n self._obj_dir.mkdir(exist_ok=True)\n self._ts = []\n\n def _down_calender(self, page):\n f_name = self._obj_dir/'calender_{0}.json.gz'.format(page)\n if f_name.exists():\n with gzip.open(f_name) as f:\n return json.loads(f.read())\n\n url = _OBJ.format(self._obj, _SUBJECTS[self._obj])\n if page > 1:\n url += '/page+{0}'.format(page)\n logging.debug('Try URL %s', url)\n response = rq.get(url=_SPARK, params={\n 'url': url,\n 'collection': 'web',\n 'output': 'json'\n })\n response.raise_for_status()\n with gzip.open(f_name, 'w') as f:\n f.write(response.content)\n return response.json()\n\n def search_calender(self, page):\n page += 1\n response = self._down_calender(page)\n if response['first_ts'] is None:\n return False\n self._first = int(response['first_ts'][:4])\n self._last = int(response['last_ts'][:4])\n logging.info(\"Find Time Range %d ~ %d for '%s'\",\n self._first, self._last, self._obj)\n\n for idx in range(self._first, self._last+1):\n self._search_one_year(idx, page)\n\n for idx in self._ts:\n p = Page(self._obj, *idx)\n p.run()\n\n ret = pd.DataFrame()\n for idx in self._obj_dir.glob('**/merge.csv.gz'):\n if os.stat(idx).st_size == 0:\n continue\n ts = idx.parent.name\n df = pd.read_csv(idx)\n df['ts'] = ts\n ret = ret.append(df)\n ha = hashlib.md5(_OBJ.encode('ascii')).hexdigest()\n ret.to_csv(_OUTPUT/'collect_{0}_{1}.csv'.format(self._obj, ha),\n na_rep='N/A', index=False)\n logging.info(\"Collect '%s'\", self._obj)\n return True\n\n def _down_year(self, year, page):\n f_name = self._obj_dir/'year_{0}_{1}.json.gz'.format(year, page)\n if f_name.exists():\n with gzip.open(f_name) as f:\n return json.loads(f.read())\n\n url = _OBJ.format(self._obj, _SUBJECTS[self._obj])\n if page > 1:\n url += '/page+{0}'.format(page)\n logging.debug('Try URL %s', url)\n response = rq.get(url=_CAPYEAR, params={\n 'url': url,\n 'selected_year': year\n })\n response.raise_for_status()\n with gzip.open(f_name, 'w') as f:\n f.write(response.content)\n return response.json()\n\n def _search_one_year(self, year, page):\n response = self._down_year(year, page)\n for month in response:\n for week in month:\n for day in week:\n if day is None:\n continue\n ts = day.get('ts')\n if ts is None:\n continue\n for idx in ts:\n self._ts.append((str(idx), page))\n logging.info(\"Find page %d ts %s for '%s'\",\n page, idx, self._obj)\n\n\ndef init_log():\n _OUTPUT.mkdir(exist_ok=True)\n _LOG.mkdir(exist_ok=True)\n root = logging.getLogger()\n root.setLevel(logging.DEBUG)\n\n time_name = datetime.datetime.now().strftime('%Y-%m-%d-%H-%M-%S.%f')\n log_file = _LOG/(time_name + '-info.log')\n ch = logging.FileHandler(str(log_file), encoding='UTF-8')\n ch.setLevel(logging.DEBUG) # INFO and DEBUG\n ch.setFormatter(logging.Formatter(\n '%(asctime)s - %(levelname)-5s - %(message)s'))\n root.addHandler(ch)\n\n\nif __name__ == '__main__':\n init_log()\n for _OBJ in _CHOICE:\n for idx in _SUBJECTS.keys():\n page = 0\n run = True\n while run:\n cal = Calender(idx)\n run = cal.search_calender(page)\n page += 1\n","sub_path":"zl/ranking.py","file_name":"ranking.py","file_ext":"py","file_size_in_byte":10818,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"}
+{"seq_id":"20264653","text":"# -*- coding: utf-8 -*-\nimport scrapy\nfrom scrapy.http import Request\n\nfrom news_sites.items import CTItem\n\n\nclass CtodaySpider(scrapy.Spider):\n name = \"ctoday\"\n allowed_domains = [\"ceylontoday.lk\"]\n start_urls = ['http://www.ceylontoday.lk/category.php?id=1']\n\n def parse(self, response):\n items = []\n # panel panel-default panel-latestst\n i = 0\n for news in response.css('div.article-big'):\n title = news.css(\n 'div.article-content h2 ::attr(title)').extract_first()\n tmpurl = news.css(\n 'div.article-content h2 ::attr(href)').extract_first()\n url = 'http://www.ceylontoday.lk/' + tmpurl\n\n item = CTItem()\n item['news_headline'] = title\n item['link'] = url\n r = Request(url=url, callback=self.parse_1)\n r.meta['item'] = item\n yield r\n items.append(item)\n yield {\"data\": items}\n\n next_urls = response.css(\n 'div.block-content div.pagination div.pagination ::attr(href)').extract()\n tmp_next = next_urls[len(next_urls) - 1]\n real_next = 'http://www.ceylontoday.lk/' + tmp_next\n yield scrapy.Request(real_next, callback=self.parse)\n\n def parse_1(self, response):\n path = response.css('div.shortcode-content')\n path = path.css('::text').extract()\n path = [i.strip() for i in path]\n path = list(filter(None, path))\n s = ' '.join(path)\n item = response.meta['item']\n item['data'] = s\n yield item\n","sub_path":"Crawlers/news_sites/spiders/ctoday.py","file_name":"ctoday.py","file_ext":"py","file_size_in_byte":1577,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"}
+{"seq_id":"19255057","text":"#encoding=utf8\nimport re\nimport os\nimport numpy as np\nimport pandas as pd\nimport tensorflow as tf\nimport data_read as readData\nimport bi_lstm_model as modelDef\nfrom tensorflow.contrib import crf\n\n\nclass BiLSTMTest(object):\n def __init__(self, data=None, model_path='.\\ckpt\\pos',test_file='.\\\\test\\\\seg_result.txt', test_result='.\\\\test\\pos_result.txt'):\n self.data = data\n self.model_path = model_path\n self.test_file = test_file\n self.test_result = test_result\n self.sess = tf.Session()\n self.isload = self.loadModel(self.sess)\n self.seq_len = 200 # 神经网络输入大小\n\n # 读取测试文件并且写入测试文件\n def testfile(self): \n pos = pd.read_csv('./pos.csv') # 读取词性标签以及对应id\n id2tag = {ii: label for ii, label in enumerate(list(pos['POS']),1)}\n id2tag[0]=''\n \n isFile = os.path.isfile(self.test_file)\n if isFile:\n with open(self.test_result, \"w\", encoding='utf-8') as out: # 读写文件默认都是UTF-8编码的\n with open(self.test_file, \"r\", encoding='utf-8') as fp:\n for line in fp.readlines(): # line为段\n \n words_ints = []\n word_ints = [] \n line = line.strip()\n line = line.replace('/ ','').replace('/Date ','').replace('/','')\n line = line.strip()\n word_ = line.split(' ')\n for word in word_:\n if word in self.data.word2id: \n word_ints.append(self.data.word2id[word]) # 文字转id\n else:\n word_ints.append('126') # 未登录词处理\n words_ints.append(word_ints)\n \n features_ = np.zeros((len(words_ints), self.seq_len), dtype=int)\n for i, row in enumerate(words_ints):\n features_[i, :len(row)] = np.array(row)[:self.seq_len]\n \n X_batch = features_ \n \n fetches = [self.model.scores, self.model.length, self.model.transition_params]\n feed_dict = {self.model.X_inputs: X_batch, self.model.lr: 1.0, self.model.batch_size: 1,\n self.model.keep_prob: 1.0}\n test_score, test_length, transition_params = self.sess.run(fetches, feed_dict)\n tags, _ = crf.viterbi_decode(test_score[0][:test_length[0]], transition_params)\n\n tags = [id2tag[i] for i in tags]\n \n result = ''\n for i in range(len(word_)):\n result = result + word_[i] + '/' +tags[i] + ' '\n print(result)\n out.write(\"%s\\n\" % (result))\n\n # 加载还原模型\n def loadModel(self, sess=None):\n isload = False\n\n self.model = modelDef.BiLSTMModel(vocab_size=self.data.word2id.__len__(), class_num=self.data.tag2id.__len__())\n ckpt = tf.train.latest_checkpoint(self.model_path)\n print(ckpt)\n saver = tf.train.Saver()\n if ckpt:\n saver.restore(sess, ckpt)\n isload = True\n return isload\n\n\nif __name__ == '__main__':\n\n data = readData.DataHandler(save_path = 'data/POS_training_data.pkl')\n data.loadData()\n print('加载字典(词性标注)完成')\n\n test = BiLSTMTest(data)\n if test.isload:\n test.testfile()\n","sub_path":"pos_model_test.py","file_name":"pos_model_test.py","file_ext":"py","file_size_in_byte":3730,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"}
+{"seq_id":"428097042","text":"from django.contrib import admin\nfrom django.urls import path, include\n#from django.contrib.auth.views import Login\n\nfrom . import views\n\nurlpatterns = [\n\tpath('', views.LoadsPage.as_view()),\n\t\n\tpath('newplan/', views.AddPlan.as_view()),\n\tpath('newload/', views.AddDiciplineLoad.as_view()),\n\n\tpath('newlectorload/', views.AddDistributed.as_view()),\n\tpath('newlectorload/confirm/', views.ConfirmDistributed.as_view()),\n\n\tpath('newactivity/', views.AddActivity.as_view())\n\n]\n","sub_path":"loads/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":473,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"}
+{"seq_id":"456299798","text":"from autode.wrappers.NWChem import NWChem, ecp_block, get_keywords\nfrom autode.point_charges import PointCharge\nfrom autode.calculation import Calculation, CalculationInput\nfrom autode.exceptions import CouldNotGetProperty, CalculationException\nfrom autode.species.molecule import Molecule\nfrom autode.wrappers.keywords import OptKeywords, MaxOptCycles, SinglePointKeywords\nfrom autode.wrappers.basis_sets import def2svp\nfrom autode.wrappers.wf import hf\nfrom autode.wrappers.functionals import pbe0\nfrom autode.atoms import Atom\nfrom . import testutils\nimport numpy as np\nimport pytest\nimport os\n\nhere = os.path.dirname(os.path.abspath(__file__))\ntest_mol = Molecule(name='methane', smiles='C')\nmethod = NWChem()\n\nopt_keywords = OptKeywords(['driver\\n gmax 0.002\\n grms 0.0005\\n'\n ' xmax 0.01\\n xrms 0.007\\n eprec 0.00003\\nend',\n 'basis\\n * library Def2-SVP\\nend',\n 'dft\\n xc xpbe96 cpbe96\\nend',\n 'task dft optimize'])\n\n\n@testutils.work_in_zipped_dir(os.path.join(here, 'data', 'nwchem.zip'))\ndef test_opt_calc():\n\n calc = Calculation(name='opt', molecule=test_mol, method=method,\n keywords=opt_keywords)\n calc.run()\n\n assert os.path.exists('opt_nwchem.nw')\n assert os.path.exists('opt_nwchem.out')\n\n final_atoms = calc.get_final_atoms()\n assert len(final_atoms) == 5\n assert type(final_atoms[0]) is Atom\n assert -40.4165 < calc.get_energy() < -40.4164\n assert calc.output.exists\n assert calc.output.file_lines is not None\n assert calc.input.filename == 'opt_nwchem.nw'\n assert calc.output.filename == 'opt_nwchem.out'\n assert calc.terminated_normally\n assert calc.optimisation_converged()\n assert calc.optimisation_nearly_converged() is False\n\n # No Hessian is computed for an optimisation calculation\n with pytest.raises(CouldNotGetProperty):\n _ = calc.get_hessian()\n\n charges = calc.get_atomic_charges()\n assert len(charges) == 5\n assert all(-1.0 < c < 1.0 for c in charges)\n\n # Optimisation should result in small gradients\n gradients = calc.get_gradients()\n assert len(gradients) == 5\n assert all(-0.1 < np.linalg.norm(g) < 0.1 for g in gradients)\n\n\ndef test_opt_single_atom():\n\n h = Molecule(name='H', smiles='[H]')\n calc = Calculation(name='opt_h', molecule=h, method=method,\n keywords=opt_keywords)\n calc.generate_input()\n\n # Can't do an optimisation of a hydrogen atom..\n assert os.path.exists('opt_h_nwchem.nw')\n input_lines = open('opt_h_nwchem.nw', 'r').readlines()\n assert 'opt' not in [keyword.lower() for keyword in input_lines[0].split()]\n\n os.remove('opt_h_nwchem.nw')\n\n\ndef test_exception_wf_solvent_calculation():\n\n solvated_mol = Molecule(name='methane', smiles='C',\n solvent_name='water')\n\n calc = Calculation(name='opt',\n molecule=solvated_mol,\n method=method,\n keywords=SinglePointKeywords([hf, def2svp]))\n\n # Cannot have solvent with a non-DFT calculation(?)\n with pytest.raises(CalculationException):\n calc.generate_input()\n\n\n@testutils.work_in_zipped_dir(os.path.join(here, 'data', 'nwchem.zip'))\ndef test_ecp_calc():\n\n # Should have no ECP block for molecule with only light elements\n water_ecp_block = ecp_block(Molecule(smiles='O'),\n keywords=method.keywords.sp)\n assert water_ecp_block == ''\n\n # Should have no ECP block if the keywords do not define an ECP\n pd_ecp_block = ecp_block(Molecule(smiles='[Pd]'), keywords=OptKeywords([]))\n assert pd_ecp_block == ''\n\n pdh2 = Molecule(smiles='[H][Pd][H]', name='H2Pd')\n pdh2.single_point(method=method)\n\n assert os.path.exists('H2Pd_sp_nwchem.nw')\n input_lines = open('H2Pd_sp_nwchem.nw', 'r').readlines()\n assert any('ecp' in line for line in input_lines)\n\n assert pdh2.energy is not None\n\n\n@testutils.work_in_zipped_dir(os.path.join(here, 'data', 'nwchem.zip'))\ndef test_opt_hf_constraints():\n\n keywords = OptKeywords(['driver\\n gmax 0.002\\n grms 0.0005\\n'\n ' xmax 0.01\\n xrms 0.007\\n eprec 0.00003\\nend',\n 'basis\\n * library Def2-SVP\\nend',\n 'task scf optimize'])\n\n h2o = Molecule(name='water', smiles='O')\n calc = Calculation(name='opt_water', molecule=h2o, method=method,\n keywords=keywords,\n cartesian_constraints=[0],\n distance_constraints={(0, 1): 0.95})\n calc.run()\n h2o.atoms = calc.get_final_atoms()\n assert 0.94 < h2o.distance(0, 1) < 0.96\n\n\ndef test_get_keywords_max_opt_cyles():\n\n opt_block = ('driver\\n'\n ' gmax 0.0003\\n'\n ' maxiter 100\\n'\n 'end')\n\n # Defining the maximum number of optimisation cycles should override the\n # value set in the driver\n kwds = OptKeywords([opt_block, def2svp, pbe0, MaxOptCycles(10),\n 'task dft optimize',\n 'task dft property'])\n\n calc_input = CalculationInput(keywords=kwds)\n\n # Should only have a single instance of the maxiter declaration\n str_keywords = get_keywords(calc_input, molecule=test_mol)\n modified_opt_block = str_keywords[0].split('\\n')\n\n assert sum('maxiter' in line for line in modified_opt_block) == 1\n\n # and should be 10 not 100\n assert sum('maxiter 100' in line for line in modified_opt_block) == 0\n assert sum('maxiter 10' in line for line in modified_opt_block) == 1\n\n # Also if the maxiter is not defined already\n\n kwds = OptKeywords([('driver\\n gmax 0.0003\\nend'), def2svp, pbe0, MaxOptCycles(10)])\n calc_input = CalculationInput(keywords=kwds)\n modified_opt_block2 = get_keywords(calc_input, molecule=test_mol)[0].split('\\n')\n\n assert sum('maxiter 10' in line for line in modified_opt_block2) == 1\n\n\n@testutils.work_in_zipped_dir(os.path.join(here, 'data', 'nwchem.zip'))\ndef test_hessian_extract_ts():\n\n atoms = [Atom('F', 0.00000, 0.00000, 2.50357),\n Atom('Cl', -0.00000, 0.00000, -1.62454),\n Atom('C', 0.00000, 0.00000, 0.50698),\n Atom('H', 1.05017, 0.24818, 0.60979),\n Atom('H', -0.74001, 0.78538, 0.60979),\n Atom('H', -0.31016, -1.03356, 0.60979)]\n\n calc = Calculation(name='sn2_hess',\n molecule=Molecule(name='ts', atoms=atoms),\n keywords=method.keywords.hess,\n method=method)\n calc.output.filename = 'sn2_hess_nwchem.out'\n\n hess = calc.get_hessian()\n assert hess.shape == (3*len(atoms), 3*len(atoms))\n\n\n@testutils.work_in_zipped_dir(os.path.join(here, 'data', 'nwchem.zip'))\ndef test_hessian_extract_butane():\n\n calc = Calculation(name='butane',\n molecule=Molecule('butane.xyz'),\n keywords=method.keywords.hess,\n method=method)\n calc.output.filename = 'butane_hess_nwchem.out'\n\n hess = calc.get_hessian()\n\n # bottom right corner element should be positive\n assert hess[-1, -1] > 0\n assert np.isclose(hess.frequencies[0].to('cm-1'),\n -2385.13,\n atol=3.0)\n\n assert np.isclose(hess.frequencies[-1].to('cm-1'),\n 3500.27,\n atol=3.0)\n\n calc = Calculation(name='butane',\n molecule=Molecule('butane.xyz'),\n keywords=method.keywords.hess,\n method=method)\n calc.output.filename = 'broken_hessian.out'\n\n with pytest.raises(CalculationException):\n _ = calc.get_hessian()\n\n\n@testutils.work_in_zipped_dir(os.path.join(here, 'data', 'nwchem.zip'))\ndef test_hf_calculation():\n\n\n h2o = Molecule(smiles='O', name='H2O')\n hf_kwds = SinglePointKeywords([def2svp, 'task scf'])\n\n h2o.single_point(method=method,\n keywords=hf_kwds)\n\n assert h2o.energy is not None\n\n # Solvation is unavalible with HF in v <7.0.2\n h2o_in_water = Molecule(smiles='O', name='H2O_solv', solvent_name='water')\n \n with pytest.raises(CalculationException): \n h2o_in_water.single_point(method=method,\n keywords=hf_kwds)\n\n # Open-shell calculations should be okay\n \n h = Molecule(smiles='[H]', name='H')\n h.single_point(method=method, keywords=hf_kwds)\n\n assert np.isclose(h.energy, -0.5, atol=0.001)\n\n # Should also support other arguments in the SCF block\n hf_kwds = SinglePointKeywords([def2svp, 'scf\\n maxiter 100\\nend', 'task scf'])\n h.single_point(method=method, keywords=hf_kwds)\n\n assert h.energy is not None\n\n\n@testutils.work_in_zipped_dir(os.path.join(here, 'data', 'nwchem.zip'))\ndef test_point_charge_calculation():\n\n h = Molecule(smiles='[H]')\n\n calc = Calculation(name='h', \n molecule=h,\n method=method, \n keywords=SinglePointKeywords([def2svp, 'task scf']),\n point_charges=[PointCharge(1.0, 0.0, 0.0, 1.0)])\n calc.run() \n\n assert calc.get_energy() is not None\n \n # H atom energy with a point charge should be different from the \n # isolated atoms HF energy\n assert not np.isclose(calc.get_energy(), -0.5, atol=0.001)\n\n","sub_path":"tests/test_nwchem.py","file_name":"test_nwchem.py","file_ext":"py","file_size_in_byte":9438,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"}
+{"seq_id":"235523567","text":"import platform\n\n\nos = platform.system()\n\ngolbal_os = ('Windows', 'Linux') # List of OSs we are supporting now\n\nPATH_WITH_DRIVER = '' # Default PATH of chrome driver\n\ndef init_path():\n \"\"\"\n This is the function that will work to select driver based on OS ('Windows', 'Linux')\n We are only supporting only 'Windows', 'Linux'. Hope next we will support OSX\n :return: True if chrome driver found\n :Exception: otherwise\n \"\"\"\n global PATH_WITH_DRIVER\n global os\n if os is 'Windows':\n PATH_WITH_DRIVER = 'C:\\chromedriver.exe'\n elif os is 'Linux':\n PATH_WITH_DRIVER = ''\n\n import os.path\n is_consist = os.path.exists(PATH_WITH_DRIVER)\n\n if is_consist is True:\n return True\n else:\n raise Exception('No chromedriver found at {0}.\\nPlease be sure you have configure PATH_WITH_DRIVER'.format(PATH_WITH_DRIVER))\n\n\n\nif __name__ == \"__main__\":\n\n print(init_path())\n print(os)","sub_path":"config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":938,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"}
+{"seq_id":"25662102","text":"#! python3\n\ndef func(n):\n\n if len(str(n)) == 1:\n return n\n return str(n)[-1:] + str(func(str(n)[:-1]))\n\nif __name__ =='__main__':\n n = int(input('enter n: '))\n res = func(n)\n print (res)\n\n","sub_path":"Python/python_fromLiaoXuefeng/Recursion/revers_num.py","file_name":"revers_num.py","file_ext":"py","file_size_in_byte":210,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"}
+{"seq_id":"39778632","text":"\"\"\"\nFor efficiency, if a video already exists, this script will\nskip over it. So if you wish to update a video, delete it \nfirst, and then run this script.\n\nusage:\nin the base results directory (i.e. you should be able to see directories 1,\n2, ... etc) execute:\n\npython animate_results_save.py path_to_your_data.fits [N_MAX_COMPS] [dim1] [dim2]\n\nThe order of the arguments is important. An example would be:\npython animate_results_save.py star_data.fits 8 X U\n\nAnd the script will generate a video for each EM run, (1, 2A, 3A, 3B, 4A, 4B, 4C, ... 8A, 8B ... 8G),\nplotted in X and U. It can take quite a while, since so many plots must be generated.\n\"\"\"\n\nimport os\nimport sys\nimport numpy as np\nimport matplotlib\nimport matplotlib.pyplot as plt\nimport matplotlib.animation as animation\n\nfrom chronostar.component import SphereComponent\nfrom chronostar import tabletool\n\nN_MAX_COMPS=20\nN_MAX_ITERS=200\nLABELS='XYZUVW'\nUNITS=3*['pc'] + 3*['km/s']\n\ndim1 = 0\ndim2 = 3\n\ndef animate(i):\n COLOURS = ['blue', 'red', 'orange', 'purple', 'brown', 'green', 'black']\n iterdir = base_dir + 'iter{:02}/'.format(i)\n print('[animate]: In ', iterdir)\n comps = SphereComponent.load_raw_components(iterdir + 'best_comps.npy')\n membs = np.load(iterdir + 'membership.npy')\n\n plt.clf()\n plt.title('Iter {}'.format(i))\n plt.xlabel('{} [{}]'.format(LABELS[dim1], UNITS[dim1]))\n plt.ylabel('{} [{}]'.format(LABELS[dim2], UNITS[dim2]))\n\n comp_assignment = np.argmax(membs, axis=1)\n\n # Plot color coded component members\n for comp_ix in range(len(comps)):\n memb_mask = np.where(comp_assignment == comp_ix)\n plt.plot(data['means'][memb_mask,dim1], data['means'][memb_mask,dim2], '.',\n color=COLOURS[comp_ix%len(COLOURS)], alpha=0.6, markersize=10)\n\n # Plot background stars\n bg_mask = np.where(comp_assignment == len(comps))\n plt.plot(data['means'][bg_mask,dim1], data['means'][bg_mask,dim2], '.',\n color='grey', alpha=0.3, markersize=2)\n\n [c.plot(dim1, dim2, color=COLOURS[comp_ix%len(COLOURS)]) for comp_ix, c in enumerate(comps)]\n # [c.plot(dim1, dim2) for c in comps]\n\n\nWriter = animation.writers['ffmpeg']\nwriter = Writer(fps=20, metadata=dict(artist='Me'), bitrate=1800)\n\nif len(sys.argv) < 2:\n print('USAGE: python animate_results_save.py datafile.fits [max_comps]')\n sys.exit()\ndatafile = sys.argv[1]\nif len(sys.argv) > 2:\n N_MAX_COMPS = int(sys.argv[2])\nif len(sys.argv) > 4:\n dim1 = sys.argv[3]\n dim2 = sys.argv[4]\n try:\n dim1 = int(dim1)\n except ValueError:\n dim1 = ord(dim1.upper()) - ord('X')\n try:\n dim2 = int(dim2)\n except ValueError:\n dim2 = ord(dim2.upper()) - ord('X')\n\ntry:\n data = tabletool.build_data_dict_from_table(datafile)\nexcept:\n data = tabletool.build_data_dict_from_table(datafile, historical=True)\n\nfig = plt.figure(figsize=(10,6))\n\nani = matplotlib.animation.FuncAnimation(fig, animate, frames=N_MAX_ITERS, repeat=True)\n\nfor i in range(1,N_MAX_COMPS+1):\n if i == 1:\n base_dir = '1/'\n save_filename = '1_{}{}.mp4'.format(LABELS[dim1],LABELS[dim2])\n if os.path.isdir(base_dir) and not os.path.isfile(save_filename):\n print('Going into ', base_dir)\n try:\n ani.save(save_filename, writer=writer)\n except: # FileNotFoundError: # Python2 consistent\n pass\n else:\n subdirs = [f.name for f in os.scandir(str(i)) if f.is_dir()] \n print('Subdirs: ', subdirs)\n for subdir in subdirs:\n # char = chr(ord('A')+j)\n # base_dir = '{}/{}/'.format(i,char)\n\n base_dir = '{}/{}/'.format(i,subdir)\n save_filename = '{}_{}_{}{}.mp4'.format(i,subdir,LABELS[dim1],LABELS[dim2])\n if os.path.isdir(base_dir) and not os.path.isfile(save_filename):\n print('Going into ', base_dir)\n try:\n ani.save(save_filename, writer=writer)\n except: # FileNotFoundError: # Python2 consistent\n pass\n\n\n","sub_path":"scripts/utils/animate_results_save.py","file_name":"animate_results_save.py","file_ext":"py","file_size_in_byte":4061,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"}
+{"seq_id":"118104539","text":"from binascii import hexlify\nimport pickle\nimport os\nimport sys\n\nHELP_TEXT = \"\\n\\nBienvenu dans le programme de décompression \\n\" \\\n \"Ce programme nécessite python 3 pour fonctionner\" \\\n \"\\nPour utiliser ce programme: python .\\huffman_decoding.py \" \\\n \" \\nExemple d'utilisation: \" \\\n \"python .\\huffman_decoding.py test_compressed.huffman test_uncompressed.txt\" \\\n \"\\n\\n\"\n\nif len(sys.argv) > 1:\n if sys.argv[1] == \"-h\":\n print(HELP_TEXT)\n sys.exit()\n\nif len(sys.argv) < 3:\n print(\"usage: \")\n sys.exit()\n\nINPUT_COMPRESSED = sys.argv[1]\nOUTPUT_UNCOMPRESSED = sys.argv[2]\nDICT_TMP = 'dict.tmp'\n\n# code taken from http://stackoverflow.com/questions/1035340/reading-binary-file-in-python-and-looping-over-each-byte\n# read the compressed file byte by byte\ntext = \"\"\nwith open(INPUT_COMPRESSED, \"rb\") as f:\n byte = f.read(1)\n while byte:\n text += str(hexlify(byte))[2:][:-1]\n byte = f.read(1)\n f.close()\n\n# format the string to remove useless hexadecimal encoding at the beginning\nbits = bin(int(text, 16))[2:]\nbits = str(bits)\n\n# remove the special encoding at the end\nwhile bits.endswith('0'):\n bits = bits[:-1]\nbits = bits[:-1]\n\n# get the dict of huffman codes\nwith open(DICT_TMP, 'rb') as input_file:\n codes = pickle.load(input_file)\n input_file.close()\nos.remove(DICT_TMP)\ntext = \"\"\ncode = \"\"\n\n# reverse dict for convenience\ncodes = {v: k for k, v in codes.items()}\n\n# use the dict to translate the bits into text\nwhile len(bits) > 0:\n code += bits[0]\n bits = bits[1:]\n if code in codes.keys():\n text += codes[code]\n code = \"\"\n\n# write text to a file\nwith open(OUTPUT_UNCOMPRESSED, \"w\") as f:\n f.write(text)\n f.close()\n","sub_path":"huffman_decoding.py","file_name":"huffman_decoding.py","file_ext":"py","file_size_in_byte":1849,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"}
+{"seq_id":"93464833","text":"import pyautogui\r\nimport time\r\n\r\n\r\ndef Check(img):\r\n try:\r\n a, b, c, d = pyautogui.locateOnScreen(\r\n f'images/{img}.png',\r\n region=(1568, 926, 236, 81),\r\n grayscale=True,\r\n confidence=0.9)\r\n except:\r\n print(f'{img} not found')\r\n else:\r\n print(f'{img} found')\r\n\r\n\r\nprint('checking in 5 seconds')\r\ntime.sleep(5)\r\n\r\nCheck('retry_button')\r\nCheck('retry_button_dark')","sub_path":"test_scripts/retry_test.py","file_name":"retry_test.py","file_ext":"py","file_size_in_byte":436,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"}
+{"seq_id":"261912981","text":"import unittest\r\nimport torch\r\nfrom pg_travel.deeprm.env_simu_sigle.environment import Env\r\nfrom pg_travel.deeprm.hparams import HyperParams as hp\r\nfrom pg_travel.deeprm.utils import utils\r\n\r\n\r\nclass TestUtils(unittest.TestCase):\r\n def test_get_action(self):\r\n action = utils.get_action(torch.Tensor([1, 2, 3, 4]))\r\n print(action.dtype, torch.LongTensor([0, 1, 2, 3]).dtype)\r\n action in torch.LongTensor([0, 1, 2, 3])\r\n # self.assertTrue(action in torch.Tensor([0, 1, 2, 3]))\r\n\r\n\r\nclass TestEnv(unittest.TestCase):\r\n def test_backlog(self):\r\n pa = hp()\r\n pa.num_nw = 5\r\n pa.simu_len = 50\r\n pa.num_ex = 10\r\n pa.new_job_rate = 1\r\n pa.compute_dependent_parameters()\r\n\r\n env = Env(pa)\r\n\r\n env.step(5)\r\n env.step(5)\r\n env.step(5)\r\n env.step(5)\r\n env.step(5)\r\n env.step(5)\r\n\r\n self.assertTrue(env.job_backlog.backlog[0] is not None)\r\n self.assertTrue(env.job_backlog.backlog[1] is None)\r\n\r\n print(\"New job is backlogged\")\r\n\r\n env.step(5)\r\n env.step(5)\r\n env.step(5)\r\n env.step(5)\r\n\r\n job = env.job_backlog.backlog[0]\r\n env.step(0)\r\n self.assertEqual(env.job_slot.slot[0], job)\r\n\r\n job = env.job_backlog.backlog[0]\r\n env.step(0)\r\n self.assertEqual(env.job_slot.slot[0], job)\r\n\r\n job = env.job_backlog.backlog[0]\r\n env.step(1)\r\n self.assertEqual(env.job_slot.slot[1], job)\r\n\r\n job = env.job_backlog.backlog[0]\r\n env.step(1)\r\n self.assertEqual(env.job_slot.slot[1], job)\r\n\r\n env.step(5)\r\n\r\n job = env.job_backlog.backlog[0]\r\n env.step(3)\r\n self.assertEqual(env.job_slot.slot[3], job)\r\n\r\n print(\"- Backlog test passed -\")\r\n\r\n\r\nif __name__ == '__main__':\r\n unittest.main()\r\n","sub_path":"test_deeprm.py","file_name":"test_deeprm.py","file_ext":"py","file_size_in_byte":1859,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"}
+{"seq_id":"575572233","text":"\"\"\"\nreport_types.py\n\nClasses for describing different report formats.\n\n\"\"\"\n\nimport logging\nimport csv\nfrom application import settings\nfrom google.appengine.ext import deferred\nfrom datetime import datetime, date\nfrom dateutil.relativedelta import relativedelta\nfrom ft import FT\nfrom flask import Response, abort, request\nfrom StringIO import StringIO\nfrom models import FustionTablesNames, StatsStore\n\n\nclass ReportType(object):\n\n zone = None\n\n def init(self, zone):\n self.f.truncate(0)\n self.zone = zone\n \n def set_zone(self):\n self.zone = zone\n \n def write_row(self, report, table=None, kml=None):\n raise NotImplementedError\n\n def write_header(self):\n raise NotImplementedError\n\n def write_footer(self):\n raise NotImplementedError\n\n def value(self):\n raise NotImplementedError\n\n def response(self, file_name):\n raise NotImplementedError\n\n def get_stats(self, report, table):\n report_id = str(report.key())\n st = StatsStore.get_for_report(report_id)\n if not st:\n logging.error(\"no cached stats for %s\" % report_id)\n abort(404)\n\n if self.zone:\n stats = st.table_accum(table, self.zone)\n if not stats:\n logging.error(\"no stats for %s\" % report_id)\n abort(404)\n else:\n stats = st.for_table(table)\n if not stats:\n logging.error(\"no stats for %s\" % report_id)\n abort(404)\n return stats\n\n def get_polygon_name(self, table, id):\n all_table_names = FustionTablesNames.all()\n filtered_table_names = all_table_names.filter('table_id =', table)\n table_names=filtered_table_names.fetch(1)[0].as_dict()\n name = table_names.get(id, id)\n return name\n \n @staticmethod\n def factory(format):\n if (format == \"kml\"):\n return KMLReportType()\n else:\n return CSVReportType()\n \n \n\nclass CSVReportType(ReportType):\n\n f = StringIO()\n csv_file = csv.writer(f)\n\n def write_header(self):\n if self.zone:\n self.csv_file.writerow(('report_id', 'start_date', 'end_date', \n 'deforested', 'degraded'))\n else:\n self.csv_file.writerow(('report_id', 'start_date', 'end_date', \n 'zone_id', 'deforested', 'degraded'))\n\n def write_footer(self):\n pass \n\n def write_row(self, report, stats, table=None, kml=None):\n name = None\n\n if table and not self.zone:\n name = self.get_polygon_name(table, stats['id'])\n \n if name:\n self.csv_file.writerow((str(report.key().id()),\n report.start.isoformat(),\n report.end.isoformat(),\n name,\n stats['def'],\n stats['deg']))\n else:\n self.csv_file.writerow((str(report.key().id()),\n report.start.isoformat(),\n report.end.isoformat(),\n stats['def'],\n stats['deg']))\n \n\n def value(self):\n return self.f.getvalue()\n\n def response(self, file_name):\n result = self.value()\n self.f.truncate(0)\n return Response(result, \n headers={\n \"Content-Disposition\": \"attachment; filename=\\\"\" + file_name + \n \".csv\\\"\"\n },\n mimetype='text/csv')\n\nclass KMLReportType(ReportType):\n\n f = StringIO()\n\n def write_header(self):\n self.f.write(\"\")\n self.f.write(\"\")\n self.f.write(\"\")\n self.f.write(\"\")\n\n def write_footer(self):\n self.f.write(\"\")\n self.f.write(\"\")\n\n def write_row(self, report, stats, table=None, kml=None):\n name = None\n\n if table:\n name = self.get_polygon_name(table, stats['id'])\n kml = self.kml(table, stats['id'])\n else:\n name = \"Custom Polygon\"\n\n description = self.description(name, stats)\n\n self.f.write(\"\")\n self.f.write(\"#transGreenPoly\")\n if (name):\n self.f.write(\"\" + name + \"\")\n self.f.write(\"\" + description + \"\")\n self.f.write(kml)\n self.f.write(\"\")\n\n def value(self):\n return self.f.getvalue()\n\n def response(self, file_name):\n result = self.value()\n self.f.truncate(0)\n return Response(result, \n headers={\n \"Content-Disposition\": \"attachment; filename=\\\"\" + file_name + \n \".kml\\\"\"\n },\n mimetype='text/kml')\n\n def kml(self, table, row_id):\n cl = FT(settings.FT_CONSUMER_KEY,\n settings.FT_CONSUMER_SECRET,\n settings.FT_TOKEN,\n settings.FT_SECRET)\n\n #TODO: do this better\n if (table == 1568452):\n id = 'ex_area'\n else:\n id = 'name'\n\n info = cl.sql(\"select geometry from %s where %s = %s\" % \n (table, id, row_id))\n polygon = info.split('\\n')[1]\n polygon = polygon.replace(\"\\\"\", \"\")\n return polygon\n\n def description(self, name, stats):\n desc = \"\" \n if (name):\n desc += name\n desc += \" | |
\"\n desc += \"| Deforestation: | \" \n desc += str(stats['def']) + \"km2 |
\" \n desc += \"| Degradation: | \" + str(stats['deg']) \n desc += \"km2 |
]]>\"\n return desc\n\n\n \n \n\n","sub_path":"src/application/report_types.py","file_name":"report_types.py","file_ext":"py","file_size_in_byte":6117,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"}
+{"seq_id":"202269002","text":"#-------------------------------------------------------------------------------\n# Copyright 2008-2012 Istituto Nazionale di Fisica Nucleare (INFN)\n# \n# Licensed under the EUPL, Version 1.1 only (the \"Licence\").\n# You may not use this work except in compliance with the Licence. \n# You may obtain a copy of the Licence at:\n# \n# http://joinup.ec.europa.eu/system/files/EN/EUPL%20v.1.1%20-%20Licence.pdf\n# \n# Unless required by applicable law or agreed to in \n# writing, software distributed under the Licence is \n# distributed on an \"AS IS\" basis, \n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,\n# either express or implied. \n# See the Licence for the specific language governing \n# permissions and limitations under the Licence.\n#-------------------------------------------------------------------------------\n'''\nCreated on Feb 24, 2011\n\n@author: aleita\n'''\nimport commands\nimport os\nfrom wnodes.utils import utils as utils\n\ndef mount(SSH_KEY_FILE, LSF_CLIENT, SRC, LOCAL_MOUNT):\n \n \n CMD_MOUNT = 'ssh -i %s -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no -q %s \"mkdir -p %s; mount %s %s\"' % (SSH_KEY_FILE, LSF_CLIENT, LOCAL_MOUNT, SRC, LOCAL_MOUNT)\n CMD_MOUNT_OUTPUT = utils.runCommand(CMD_MOUNT, 12)\n return CMD_MOUNT_OUTPUT\n\ndef unmount(SSH_KEY_FILE, LSF_CLIENT, LOCAL_MOUNT):\n \n CMD_UNMOUNT = 'ssh -i %s -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no -q %s \"umount %s\"' % (SSH_KEY_FILE, LSF_CLIENT, LOCAL_MOUNT)\n CMD_UNMOUNT_OUTPUT = utils.runCommand(CMD_UNMOUNT, 12)\n return CMD_UNMOUNT_OUTPUT\n\ndef handlePlugin(SSH_KEY_FILE, LSF_CLIENT, CONFIG):\n \n for MOUNT_POINT in CONFIG.keys():\n \n MOUNT_POINT_ID, MOUNT_POINT_OP = MOUNT_POINT.split('-')\n \n if MOUNT_POINT_OP.upper() == 'MOUNT':\n SRC, LOCAL_MOUNT = CONFIG[MOUNT_POINT].split()\n output = mount(SSH_KEY_FILE, LSF_CLIENT, SRC, LOCAL_MOUNT)\n \n if MOUNT_POINT_OP.upper() == 'UNMOUNT':\n output = unmount(SSH_KEY_FILE, LSF_CLIENT, CONFIG[MOUNT_POINT])\n \n return output\n","sub_path":"packages/wnodes_utils/sources/utils/plugin_mount.py","file_name":"plugin_mount.py","file_ext":"py","file_size_in_byte":2071,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"}
+{"seq_id":"159723937","text":"import nltk\n#nltk.download('punkt')\n#nltk.download('stopwords')\nnltk.download('wordnet')\nfrom nltk.tokenize import word_tokenize\nfrom nltk.corpus import stopwords\nfrom autocorrect import Speller\nimport re\nfrom nltk.stem import PorterStemmer\nfrom nltk.tokenize import sent_tokenize\nfrom nltk.stem import WordNetLemmatizer\nfrom sklearn.feature_extraction.text import TfidfTransformer\nimport csv\nimport json \n\nps = PorterStemmer()\nspel = Speller(lang='en',threshold=0.7)\nlemmatizer = WordNetLemmatizer()\n\ndef text_cleaner(text):\n\trules = [\n\t\t{r'>\\s+': u'>'}, # remove spaces after a tag opens or closes\n\t\t{r'\\s+': u' '}, # replace consecutive spaces\n\t\t{r'\\s*
\\s*': u'\\n'}, # newline after a
\n\t\t{r'(div)\\s*>\\s*': u'\\n'}, # newline after
and and ...\n\t\t{r'(p|h\\d)\\s*>\\s*': u'\\n\\n'}, # newline after and and ...\n\t\t{r'.*<\\s*(/head|body)[^>]*>': u''}, # remove to \n\t\t{r']*>.*': r'\\1'}, # show links instead of texts\n\t\t{r'[ \\t]*<[^<]*?/?>': u''}, # remove remaining tags\n\t\t{r'^\\s+': u''} # remove spaces at the beginning\n\t]\n\tfor rule in rules:\n\t\tfor (k, v) in rule.items():\n\t\t\tregex = re.compile(k)\n\t\t\ttext = regex.sub(v, text)\n\ttext = text.rstrip()\n\treturn text.lower()\n\ndef spell(text):\n\tfor i in range(0,len(text)):\n\t\ttext[i]=spel.autocorrect_word(text[i])\n\treturn text\ndef steam(words):\n\tfor i in range(0,len(words)):\n\t\twords[i]=ps.stem(words[i])\t\n\treturn words\n\t\ndef lemitzr(words):\n\tfor i in range(0,len(words)):\n\t\twords[i]=lemmatizer.lemmatize(words[i])\t\n\treturn words\n\n\n#from parse import *\n#print(\"original string: \",text)\n\nclasses=[\"World\",\"Sports\",\"Business\",\"Sci_Tech\"]\n\nfor file in classes:\n\topen(file,\"w\").write(\"{}\")\nfo=open(\"data/train.csv\",\"r\")\ncsv_reader = csv.reader(fo, delimiter=',')\ntrain_count=0\nfor row in csv_reader:\n\ttrain_count+=1\n\tprint(\"train_no_\",train_count)\n\tClass=int(row[0])-1\n\ttext=(row[1]+row[2]).lower()\n\t#print(\"cleaned string: \",text)\n\tstop_words = set(stopwords.words('english'))\n\n\tword_tokens = word_tokenize(text)\n\t#print(\"tokens: \",word_tokens)\n\tprint(\"original_token_count: \",len(word_tokens))\n\n\tunique_words = list(set(word_tokens))\n\tprint(\"unique_token_count: \",len(unique_words))\n\n\tspelled_words=spell(unique_words)\n\t#print(\"spell words: \",spelled_words)\n\n\tfiltered_sentence = [w for w in word_tokens if not w in stop_words]\n\tfiltered_sentence = []\n\tfor w in spelled_words:\n\t\tif w not in stop_words:\n\t\t\tfiltered_sentence.append(w)\n\t#print(\"filtered_words: \",filtered_sentence)\t\n\n\t#stm=steam(filtered_sentence)\n\t#print(\"steamed_words: \",stm)#not to accurate only remove er ing ed from each word\t\n\n\tlmtz=lemitzr(filtered_sentence)\n\tprint(\"lamitized_words: \",lmtz)\n\n\n\tprint(\"stpwords count: \",len(word_tokens)-len(filtered_sentence))\n\tprint(\"dataset of word decreses from \",len(word_tokens), \"to\", len(filtered_sentence))\n\tprint(\"eliminated word \",len(word_tokens)-len(filtered_sentence),\" \", 100-(len(filtered_sentence)/(len(word_tokens)))*100 ,\"%\")\n\t\n\t\n\t\n\ttemp_word_list=json.loads(open(classes[Class],\"r\").read())\n\t#print(\"old_word_count\",temp_word_list)\n\t\n\tfor word in list(set(filtered_sentence)):\n\t\tif word in temp_word_list.keys(): \t\n\t\t\ttemp_word_list[word]+=filtered_sentence.count(word)\n\t\telse:\n\t\t\ttemp_word_list[word]=filtered_sentence.count(word)\n\t#print(\"new \",temp_word_list)\n\topen(classes[Class],\"w\").write(json.dumps(temp_word_list))","sub_path":"bs4/a_classifier.py","file_name":"a_classifier.py","file_ext":"py","file_size_in_byte":3389,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"}
+{"seq_id":"627162820","text":"from linear_algebra.gauss_elimination import gauss_elim\nimport numpy as np\n\n\ndef gram_schmidt(S):\n trace = []\n\n def proj(e, a):\n s = np.divide(np.dot(e, a), np.dot(e, e))\n return np.dot(s, e)\n\n for v in S.T:\n u = v.copy()\n for _u in trace:\n u -= proj(_u, v)\n trace.append(u)\n\n for u in trace:\n u /= np.linalg.norm(u)\n\n return np.array(trace).T\n\n\n# \"Now without loops\"\n# ref(AA^T | A) split and normalized\ngram_schmidt_unsafe = lambda s: list(map(\n lambda v: np.divide(v[len(s):], np.linalg.norm(v[len(s):])),\n gauss_elim(np.append(np.matmul(s, np.transpose(s)), s, 1))))\n\n\nif __name__ == '__main__':\n v1 = np.array([1, 3], np.float64)\n v2 = np.array([2, 2], np.float64)\n base = np.array([v1, v2])\n print(gram_schmidt_unsafe(base))\n","sub_path":"linear_algebra/gram_schmidt.py","file_name":"gram_schmidt.py","file_ext":"py","file_size_in_byte":817,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"}
+{"seq_id":"550186403","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Thu Nov 8 13:21:39 2018\r\n\r\n@author: mtomic\r\n\"\"\"\r\n\r\nclass File:\r\n def __init__(self, naziv, velicina, roditelj=None):\r\n if not isinstance(naziv, str):\r\n raise TypeError('Pogresan tip argumenta naziv:' + type(naziv).__name__)\r\n\r\n if not isinstance(velicina, int):\r\n raise TypeError('Pogresan tip argumenta velicina:' + type(velicina).__name__)\r\n\r\n if roditelj and not isinstance(roditelj, Folder):\r\n raise TypeError('Pogresan tip argumenta roditelj:' + type(roditelj).__name__)\r\n \r\n self.naziv = naziv\r\n self.velicina = velicina\r\n self.roditelj = roditelj\r\n if roditelj is not None:\r\n # dodati fajl u kolekciju roditelja\r\n roditelj.kolekcija.append(self)\r\n \r\n def __len__(self):\r\n return self.velicina\r\n \r\n def __str__(self):\r\n return self.naziv\r\n \r\n __repr__ = __str__\r\n \r\n def ls(self, *args):\r\n if not 'f' in args:\r\n yield self\r\n\r\nclass Folder(File):\r\n def __init__(self, naziv, roditelj=None):\r\n super().__init__(naziv, 4, roditelj)\r\n self.kolekcija = []\r\n \r\n def __len__(self):\r\n z = self.velicina\r\n# for f in self.kolekcija:\r\n# z += len(f)\r\n z += sum((len(f) for f in self.kolekcija))\r\n return z\r\n \r\n def __contains__(self, fajl):\r\n if fajl in self.kolekcija:\r\n return True\r\n else:\r\n return any((fajl in f for f in self.kolekcija if isinstance(f, Folder)))\r\n# for f in self.kolekcija:\r\n# if isinstance(f, Folder) and fajl in f:\r\n# return True\r\n# return False\r\n \r\n def ls(self, *args):\r\n key = None\r\n for arg in args:\r\n if arg in ('n', 'v'):\r\n key = arg\r\n rev = 'r' in args\r\n rek = 'R' in args\r\n fo = 'f' in args\r\n \r\n kljucevi = {\r\n 'n': lambda x: x.naziv,\r\n 'v': lambda x: -len(x)\r\n }\r\n \r\n if key is not None:\r\n kol = sorted(self.kolekcija, key=kljucevi[key], reverse=rev)\r\n else:\r\n kol = self.kolekcija\r\n \r\n yield self\r\n for f in kol:\r\n if rek:\r\n for f2 in f.ls(*args):\r\n yield f2\r\n elif (fo and isinstance(f, Folder)) or not fo:\r\n yield f\r\n \r\nclass Disk:\r\n def __init__(self, naziv, kapacitet, root):\r\n if not isinstance(naziv, str):\r\n raise TypeError('Pogresan tip argumenta naziv:' + type(naziv).__name__)\r\n\r\n if not isinstance(kapacitet, int):\r\n raise TypeError('Pogresan tip argumenta kapacitet:' + type(kapacitet).__name__)\r\n\r\n if not isinstance(root, Folder):\r\n raise TypeError('Pogresan tip argumenta root:' + type(root).__name__)\r\n\r\n if len(root) > kapacitet:\r\n raise ValueError('Velicina root foldera prevazilazi kapacitet diska')\r\n \r\n self.naziv = naziv\r\n self.kapacitet = kapacitet\r\n self.root = root\r\n \r\n def dodaj_fajl(self, folder, fajl):\r\n if not isinstance(folder, Folder):\r\n raise TypeError('Pogresan tip argumenta folder:' + type(folder).__name__)\r\n \r\n if not isinstance(fajl, File):\r\n raise TypeError('Pogresan tip argumenta fajl:' + type(fajl).__name__)\r\n \r\n # da li je folder na disku\r\n if folder != self.root and folder not in self.root:\r\n raise ValueError('Folder se ne nalazi na disku')\r\n # da li fajl nije na disku\r\n if fajl in self.root:\r\n raise ValueError('Fajl je vec na disku')\r\n # preostali prostor na disku ne sme biti prekoracen velicinom fajla\r\n if self.kapacitet - len(self.root) < len(fajl):\r\n raise ValueError('Velicina fajla prevazilazi preostali kapacitet diska')\r\n \r\n folder.kolekcija.append(fajl)\r\n fajl.roditelj = folder\r\n \r\n def ls(self, putanja, *args):\r\n print(f'{self.naziv} {self.kapacitet}')\r\n # nadji putanju\r\n delovi = putanja.split('/')\r\n f = self.root\r\n indeks = 1\r\n while indeks < len(delovi) and delovi[indeks] != '':\r\n for p in f.kolekcija:\r\n if p.naziv == delovi[indeks]:\r\n f = p\r\n indeks += 1\r\n break\r\n else:\r\n raise IndexError('Nepostojeca putanja \"%s\"' % putanja)\r\n # ispisuj sa te putanje\r\n for fajl in f.ls(*args):\r\n print(f'{str(fajl)} ({len(fajl)}{\"f\" if isinstance(fajl, Folder) else \"\"})')\r\n \r\nif __name__ == '__main__':\r\n root = Folder('/')\r\n fs = Disk('test', 8000, root)\r\n fo1 = Folder('folder1')\r\n fo2 = Folder('folder2')\r\n fs.dodaj_fajl(root, fo1)\r\n fs.dodaj_fajl(root, fo2)\r\n fs.dodaj_fajl(root, File('file4', 180))\r\n fs.dodaj_fajl(root, File('file6', 881))\r\n fs.dodaj_fajl(root, File('file7', 412))\r\n fs.dodaj_fajl(fo1, File('file1', 20))\r\n fs.dodaj_fajl(fo1, Folder('folder3'))\r\n fs.dodaj_fajl(fo1, File('file5', 4000))\r\n fs.dodaj_fajl(fo1, File('file2', 433))\r\n fs.dodaj_fajl(fo2, File('file3', 70))\r\n \r\n print('-'*10)\r\n fs.ls('/', 'R')\r\n print('-'*10)\r\n fs.ls('/folder1', 'n', 'R', 'r')\r\n print('-'*10)\r\n fs.ls('/', 'f', 'v')\r\n \r\n ","sub_path":"SkriptJezici/Termin 06/cas6_20181108.py","file_name":"cas6_20181108.py","file_ext":"py","file_size_in_byte":5444,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"}
+{"seq_id":"549510049","text":"# -*- coding: utf-8 -*-\n\n\n#importing important libraries\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport seaborn as sns\n\n\n\n#reading the dataset\ndf = pd.read_csv('Data/Real Data/Real_Combine.csv')\n\n##check for null values\ndf.isnull().sum()\n\n#another way to look for null values is heatmaps\nsns.heatmap(df.isnull(),yticklabels=False,cbar=True,cmap='viridis')\n\n\n#only missing value is in PM2.5,since only one null value we can drop it\ndf = df.dropna()\n\n#division into dependent and independent features\nx= df.iloc[:,:-1]#independent features\ny = df.iloc[:,-1]#dependent features\n\ny.isnull().sum()\n\n#univariate analysis 1.Using pairplot 2.correlation 3.Heatmap\n#1.\nsns.pairplot(df)\n\n#2.\ndf.corr()\n\n\n#3.\n#get correlation of each feature in the dataset\ncorrmat = df.corr()\ntop_corr_features = corrmat.index\nplt.figure(figsize=(20,20))\n#plot the heatmap\ng = sns.heatmap(df[top_corr_features].corr(),annot=True,cmap='RdYlGn')\n\n\n#Feature selection\nfrom sklearn.ensemble import ExtraTreesRegressor\nmodel = ExtraTreesRegressor()\nmodel.fit(x,y)\n\nprint(model.feature_importances_)\n\n\n#now look at the target variable\nsns.distplot(y)\n\n#it is right skewed\n\n#train test split\nfrom sklearn.model_selection import train_test_split\n\nx_train,x_test,y_train,y_test = train_test_split(x,y,test_size=0.3,random_state=42)\n\n\n#linear regression\nfrom sklearn.linear_model import LinearRegression\nlr = LinearRegression()\nlr.fit(x_train,y_train)\n\n#score = r^2\nlr.score(x_train,y_train)\n\n\n#cross val score\nfrom sklearn.model_selection import cross_val_score\nscore = cross_val_score(lr,x,y,cv=5)\n\n\nscore.mean()\n\n#prediction\nprediction = lr.predict(x_test)\n\nsns.distplot(y_test-prediction)\n\n\n#Pickle for deployment\nimport pickle\nfile = open('regression_model.pkl','wb')\n\n#dump info to that file\npickle.dump(lr,file)\n","sub_path":"linear_regression.py","file_name":"linear_regression.py","file_ext":"py","file_size_in_byte":1814,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"}
+{"seq_id":"6866157","text":"legL = [ ('la','lk'), ('lk','lh'), ('lh','ne') ]\nlegR = [ ('ra','rk'), ('rk','rh'), ('rh','ne') ]\n\narmL = [ ('lw','le'), ('le','ls'), ('ls','ne') ]\narmR = [ ('rw','re'), ('re','rs'), ('rs','ne') ]\n\nhead = [ ('ne','he') ]\n\nedgeComp = legL + legR + armL + armR + head\n\nedgeData = []\nedgeRaw = []\n\nfor e in edgeComp:\n\n\n\tinit = joints[e[0]][:,:2]\n\tfinal = joints[e[1]][:,:2]\n\n\tedgeRaw.append( (init,final) )\n\n\tdelta = init - final\n\n\tmag, ang = cart2pol( delta[:,0], delta[:,1] )\n\n\tangm = meanAngle( ang )\n\tangcent = np.mod( ang - angm + np.pi, 2*np.pi )\n\n\tedgeData.append( (angcent,mag) )\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"ver0/pairwise/EdgeSetup.py","file_name":"EdgeSetup.py","file_ext":"py","file_size_in_byte":596,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"}
+{"seq_id":"354785687","text":"# Copyright 2018 Google. 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\n\"\"\"Efficient implementation of topk_mask for TPUs.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport tensorflow as tf\n\n\ndef topk_mask(score, k):\n \"\"\"Efficient implementation of topk_mask for TPUs.\n\n This is a more efficient implementation of the following snippet with support\n for higher rank tensors. It has the limitation that it only supports float32\n as element type. The mask only contains k elements even if other elements\n have the same value as the kth largest.\n\n def topk_mask(score, k):\n _, indices = tf.nn.top_k(score, k=k)\n return tf.scatter_nd(tf.expand_dims(indices, -1), tf.ones(k),\n tf.squeeze(score).shape.as_list())\n\n The implementation binary searches for the kth value along each row of the\n input and once the kth value is found it creates the mask via a single select\n instruction. This approach is more than 100x faster on TPUs for large inputs\n compared with the above snippet.\n\n Args:\n score: 1-D or higher Tensor with last dimension at least k.\n k: Number of top elements to look for along the last dimension (along each\n row for matrices).\n \"\"\"\n last_dim_size = score.get_shape().as_list()[-1]\n\n # Choose top k+epsilon where epsilon is the number of times the k'th largest i\n # element is present in the input.\n topk_mask_with_duplicate = topk_mask_internal(score, k)\n # Calculate the number of redudant duplicate values to discard.\n select_num = tf.cast(\n tf.reduce_sum(topk_mask_with_duplicate, axis=-1, keepdims=True), tf.int32)\n redudant_num = select_num - k\n\n # softmax cross entropy value range [0, 1].\n # k's largest value is the smallest value being selected.\n k_th_value = tf.reduce_min(\n tf.where(\n tf.cast(topk_mask_with_duplicate, tf.bool), score,\n tf.ones_like(score) * 2.0),\n axis=-1,\n keepdims=True)\n # Mask to indicate if score equals k th largest value.\n equal_k_th_value = tf.equal(score, k_th_value)\n # Creates a tensor wherer the value is 1 if the value is equal to kth largest\n # value, otherwise, 0.\n k_th_value = tf.where(equal_k_th_value, tf.ones_like(score, dtype=tf.int32),\n tf.zeros_like(score, dtype=tf.int32))\n index = tf.range(last_dim_size)\n\n k_th_value_index = tf.multiply(k_th_value, index)\n\n duplicate_mask = topk_mask_internal(\n tf.cast(k_th_value_index, tf.float32), redudant_num)\n\n return tf.where(\n tf.cast(duplicate_mask, tf.bool), tf.zeros_like(topk_mask_with_duplicate),\n topk_mask_with_duplicate)\n\n\ndef topk_mask_internal(score, k):\n \"\"\"Efficient implementation of topk_mask for TPUs.\n\n This is a more efficient implementation of the following snippet with support\n for higher rank tensors. It has the limitation that it only supports float32\n as element type. The mask may contain more than k elements if other elements\n have the same value as the kth largest.\n\n The implementation binary searches for the kth value along each row of the\n input and once the kth value is found it creates the mask via a single select\n instruction. This approach is more than 100x faster on TPUs for large inputs\n compared with the above snippet.\n\n Args:\n score: 1-D or higher Tensor with last dimension at least k.\n k: Number of top elements to look for along the last dimension (along each\n row for matrices).\n \"\"\"\n\n def larger_count(data, limit):\n \"\"\"Number of elements larger than limit along the most minor dimension.\n\n Args:\n data: Rn tensor with the data to compare.\n limit: Rn tensor with last dimension being 1 and rest of the dimensions\n being same as for data.\n\n Returns:\n Rn tensor with same shape as limit and int32 as element type containing\n the number of elements larger then limit inside data.\n \"\"\"\n return tf.reduce_sum(\n tf.cast(data > tf.broadcast_to(limit, data.shape), tf.int32),\n axis=-1, keepdims=True)\n\n # Predicate specifying if the kth value is negative or positive.\n kth_negative = (larger_count(score, 0.0) < k)\n\n # Value of the sign bit for each row.\n limit_sign = tf.where(kth_negative,\n tf.broadcast_to(1, kth_negative.shape),\n tf.broadcast_to(0, kth_negative.shape))\n\n # Initial value for the binary search with the sign bit set.\n next_value = tf.bitwise.left_shift(limit_sign, 31)\n\n def cond(bit_index, _):\n return bit_index >= 0\n\n def body(bit_index, value):\n \"\"\"Body for the while loop executing the binary search.\n\n Args:\n bit_index: Index of the bit to be updated next.\n value: Current value of the binary search separator. Stored as an int32\n but bitcasted to a float32 for comparison.\n Returns:\n The updated value of bit_index and value\n \"\"\"\n\n # Calculate new value via `new_value = value | (1 << bit_index)`\n new_value = tf.bitwise.bitwise_or(\n value, tf.bitwise.left_shift(1, bit_index))\n\n # Calculate number of values larger than new_value\n larger = larger_count(score, tf.bitcast(new_value, tf.float32))\n\n # Update next_value based on new_value. For positive numbers new_value is\n # larger than value while for negative numbers it is the other way around.\n next_value = tf.where(tf.logical_xor(larger >= k, kth_negative),\n new_value, value)\n return bit_index - 1, next_value\n\n # Executes a binary search for the value of the limits. We run the loop 31\n # times to calculate the 31 bits of the float32 value (the sign is calculated\n # separately).\n _, limit = tf.while_loop(cond, body, (30, next_value))\n\n # Create a mask by comparing the individual values to the kth value and then\n # selecting zero or one accordingly.\n return tf.where(\n score >= tf.broadcast_to(tf.bitcast(limit, tf.float32), score.shape),\n tf.ones(score.shape), tf.zeros(score.shape))\n","sub_path":"Google/benchmarks/ssd/implementations/tpu-v3-32-ssd/ssd/topk_mask.py","file_name":"topk_mask.py","file_ext":"py","file_size_in_byte":6592,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"}
+{"seq_id":"375313289","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\nfrom django.views.generic import TemplateView\nfrom usuarios.models import Preferencias\nfrom geojson import loads, Feature, FeatureCollection\nfrom django.db import connection\nfrom django.http import JsonResponse\n\n# Vistas.\nfrom django.http import HttpResponse\n\nclass Paginaprincipal(TemplateView):\n\ttemplate_name = 'PaginaPrincipal.html'\n\nclass Visor_Cartografia(TemplateView):\n\ttemplate_name = 'Visor_Cartografia.html'\n\nclass Visor_Sencillo(TemplateView):\n\ttemplate_name = 'Visor_Sencillo.html'\n\n# Cálculo del índice para cartografia calidad residencial:\ndef calculo_indice(request):\n\tif request.method == 'GET' or request.method == 'POST':\n\t\tusuario = request.user\n\t\tdatos = Preferencias.objects.get(username_id=usuario)\n\t\tsuma = datos.valzv + datos.valc + datos.vals + datos.valcult + datos.valtransp\n\t\tpondvz = float(datos.valzv) / float(suma)\n\t\tpondvc = float(datos.valc) / float(suma)\n\t\tpondvs = float(datos.vals) / float(suma)\n\t\tpondvcu = float(datos.valcult) / float(suma)\n\t\tpondvt = float(datos.valtransp) / float(suma)\n\t\t\n\t\t# seleccion de los datos de la capa de las manzanas mediante conulta SQL\n\t\tcur = connection.cursor()\n\t\tconsulta = ''' SELECT val_zv, val_educ, val_salud, val_cult, val_transp, dist_zv, dist_salud, dist_eei, dist_ceip, dist_ies, dist_cult, dist_bus, dist_metro, dist_cerca, ST_AsGeoJSON(geom) as geoj FROM public.icru_CR '''\n\t\tcur.execute(consulta)\n\t\tpoligonos_consulta = cur.fetchall()\n\t\tresultado = []\n\t\tfor pol in poligonos_consulta:\n\t\t\t# atributos de la capa, recuperacion de la consulta para cada poligono\n\t\t\tvaloracion = ((pol[0] * pondvz) + (pol[1] * pondvc) + (pol[2] * pondvs) + (pol[3] * pondvcu) + (pol[4] * pondvt))\n\t\t\tdistzv = pol[5]\n\t\t\tdists = pol[6]\n\t\t\tdisteei = pol[7]\n\t\t\tdistceip = pol[8]\n\t\t\tdisties = pol[9]\n\t\t\tdistcult = pol[10]\n\t\t\tdistbus = pol[11]\n\t\t\tdistmetro = pol[12]\n\t\t\tdistcerc = pol[13]\n\t\t\tgeojs = pol[14]\n\t\t\t# Datos a capa en formato GeoJson\n\t\t\tgeojs_geom = loads(geojs)\n\t\t\tgeojs_feat = Feature(geometry=geojs_geom, properties={'valor':valoracion, 'dist_zv':distzv, 'dist_s':dists, 'dist_EEI':disteei, 'dist_CEIP':distceip, 'dist_IES':disties, 'dist_cult':distcult, 'dist_bus':distbus, 'dist_metro':distmetro, 'dist_cerca':distcerc})\n\t\t\tresultado.append(geojs_feat)\n\t\tgeojs_fc = FeatureCollection(resultado)\n\t\t# Devolver los datos en formato json\n\t\treturn JsonResponse(geojs_fc)\n\t\t","sub_path":"icru/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2407,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"}
+{"seq_id":"629195832","text":"import setuptools\n\n\nwith open(\"README.md\", \"r\") as fh:\n long_description = fh.read()\n\n\nsetuptools.setup(\n name=\"tfdeterminism\",\n version=\"0.0.1\",\n author=\"Anatoly Potapov (forked from NVIDIA)\",\n author_email=\"anatolii.s.potapov@gmail.com\",\n description=\"Make tensorflow reproducible\",\n long_description=long_description,\n long_description_content_type=\"text/markdown\",\n url=\"https://github.com/AnatoliiPotapov/tensorflow-determinism\",\n packages=setuptools.find_packages(),\n classifiers=[\n \"Programming Language :: Python :: 3\",\n \"License :: OSI Approved :: Apache 2.0\",\n \"Operating System :: OS Independent\",\n ],\n python_requires='>=3.6',\n)","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":700,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"}
+{"seq_id":"548334299","text":"# Copyright 2018 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# https://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\ntry:\n from unittest import mock\nexcept ImportError: # pragma: NO PY3 COVER\n import mock\n\nimport pytest\nimport redis as redis_module\n\nfrom google.cloud.ndb import global_cache\n\n\nclass TestGlobalCache:\n def make_one(self):\n class MockImpl(global_cache.GlobalCache):\n def get(self, keys):\n return super(MockImpl, self).get(keys)\n\n def set(self, items, expires=None):\n return super(MockImpl, self).set(items, expires=expires)\n\n def delete(self, keys):\n return super(MockImpl, self).delete(keys)\n\n def watch(self, keys):\n return super(MockImpl, self).watch(keys)\n\n def compare_and_swap(self, items, expires=None):\n return super(MockImpl, self).compare_and_swap(\n items, expires=expires\n )\n\n return MockImpl()\n\n def test_get(self):\n cache = self.make_one()\n with pytest.raises(NotImplementedError):\n cache.get(b\"foo\")\n\n def test_set(self):\n cache = self.make_one()\n with pytest.raises(NotImplementedError):\n cache.set({b\"foo\": \"bar\"})\n\n def test_delete(self):\n cache = self.make_one()\n with pytest.raises(NotImplementedError):\n cache.delete(b\"foo\")\n\n def test_watch(self):\n cache = self.make_one()\n with pytest.raises(NotImplementedError):\n cache.watch(b\"foo\")\n\n def test_compare_and_swap(self):\n cache = self.make_one()\n with pytest.raises(NotImplementedError):\n cache.compare_and_swap({b\"foo\": \"bar\"})\n\n\nclass TestInProcessGlobalCache:\n @staticmethod\n def test_set_get_delete():\n cache = global_cache._InProcessGlobalCache()\n result = cache.set({b\"one\": b\"foo\", b\"two\": b\"bar\", b\"three\": b\"baz\"})\n assert result is None\n\n result = cache.get([b\"two\", b\"three\", b\"one\"])\n assert result == [b\"bar\", b\"baz\", b\"foo\"]\n\n cache = global_cache._InProcessGlobalCache()\n result = cache.get([b\"two\", b\"three\", b\"one\"])\n assert result == [b\"bar\", b\"baz\", b\"foo\"]\n\n result = cache.delete([b\"one\", b\"two\", b\"three\"])\n assert result is None\n\n result = cache.get([b\"two\", b\"three\", b\"one\"])\n assert result == [None, None, None]\n\n @staticmethod\n @mock.patch(\"google.cloud.ndb.global_cache.time\")\n def test_set_get_delete_w_expires(time):\n time.time.return_value = 0\n\n cache = global_cache._InProcessGlobalCache()\n result = cache.set(\n {b\"one\": b\"foo\", b\"two\": b\"bar\", b\"three\": b\"baz\"}, expires=5\n )\n assert result is None\n\n result = cache.get([b\"two\", b\"three\", b\"one\"])\n assert result == [b\"bar\", b\"baz\", b\"foo\"]\n\n time.time.return_value = 10\n result = cache.get([b\"two\", b\"three\", b\"one\"])\n assert result == [None, None, None]\n\n @staticmethod\n def test_watch_compare_and_swap():\n cache = global_cache._InProcessGlobalCache()\n result = cache.watch([b\"one\", b\"two\", b\"three\"])\n assert result is None\n\n cache.cache[b\"two\"] = (b\"hamburgers\", None)\n\n result = cache.compare_and_swap(\n {b\"one\": b\"foo\", b\"two\": b\"bar\", b\"three\": b\"baz\"}\n )\n assert result is None\n\n result = cache.get([b\"one\", b\"two\", b\"three\"])\n assert result == [b\"foo\", b\"hamburgers\", b\"baz\"]\n\n @staticmethod\n @mock.patch(\"google.cloud.ndb.global_cache.time\")\n def test_watch_compare_and_swap_with_expires(time):\n time.time.return_value = 0\n\n cache = global_cache._InProcessGlobalCache()\n result = cache.watch([b\"one\", b\"two\", b\"three\"])\n assert result is None\n\n cache.cache[b\"two\"] = (b\"hamburgers\", None)\n\n result = cache.compare_and_swap(\n {b\"one\": b\"foo\", b\"two\": b\"bar\", b\"three\": b\"baz\"}, expires=5\n )\n assert result is None\n\n result = cache.get([b\"one\", b\"two\", b\"three\"])\n assert result == [b\"foo\", b\"hamburgers\", b\"baz\"]\n\n time.time.return_value = 10\n\n result = cache.get([b\"one\", b\"two\", b\"three\"])\n assert result == [None, b\"hamburgers\", None]\n\n\nclass TestRedisCache:\n @staticmethod\n def test_constructor():\n redis = object()\n cache = global_cache.RedisCache(redis)\n assert cache.redis is redis\n\n @staticmethod\n @mock.patch(\"google.cloud.ndb.global_cache.redis_module\")\n def test_from_environment(redis_module):\n redis = redis_module.Redis.from_url.return_value\n with mock.patch.dict(\"os.environ\", {\"REDIS_CACHE_URL\": \"some://url\"}):\n cache = global_cache.RedisCache.from_environment()\n assert cache.redis is redis\n redis_module.Redis.from_url.assert_called_once_with(\"some://url\")\n\n @staticmethod\n def test_from_environment_not_configured():\n with mock.patch.dict(\"os.environ\", {\"REDIS_CACHE_URL\": \"\"}):\n cache = global_cache.RedisCache.from_environment()\n assert cache is None\n\n @staticmethod\n def test_get():\n redis = mock.Mock(spec=(\"mget\",))\n cache_keys = [object(), object()]\n cache_value = redis.mget.return_value\n cache = global_cache.RedisCache(redis)\n assert cache.get(cache_keys) is cache_value\n redis.mget.assert_called_once_with(cache_keys)\n\n @staticmethod\n def test_set():\n redis = mock.Mock(spec=(\"mset\",))\n cache_items = {\"a\": \"foo\", \"b\": \"bar\"}\n cache = global_cache.RedisCache(redis)\n cache.set(cache_items)\n redis.mset.assert_called_once_with(cache_items)\n\n @staticmethod\n def test_set_w_expires():\n expired = {}\n\n def mock_expire(key, expires):\n expired[key] = expires\n\n redis = mock.Mock(expire=mock_expire, spec=(\"mset\", \"expire\"))\n cache_items = {\"a\": \"foo\", \"b\": \"bar\"}\n cache = global_cache.RedisCache(redis)\n cache.set(cache_items, expires=32)\n redis.mset.assert_called_once_with(cache_items)\n assert expired == {\"a\": 32, \"b\": 32}\n\n @staticmethod\n def test_delete():\n redis = mock.Mock(spec=(\"delete\",))\n cache_keys = [object(), object()]\n cache = global_cache.RedisCache(redis)\n cache.delete(cache_keys)\n redis.delete.assert_called_once_with(*cache_keys)\n\n @staticmethod\n @mock.patch(\"google.cloud.ndb.global_cache.uuid\")\n def test_watch(uuid):\n uuid.uuid4.return_value = \"abc123\"\n redis = mock.Mock(\n pipeline=mock.Mock(spec=(\"watch\",)), spec=(\"pipeline\",)\n )\n pipe = redis.pipeline.return_value\n keys = [\"foo\", \"bar\"]\n cache = global_cache.RedisCache(redis)\n cache.watch(keys)\n\n pipe.watch.assert_called_once_with(\"foo\", \"bar\")\n assert cache.pipes == {\n \"foo\": global_cache._Pipeline(pipe, \"abc123\"),\n \"bar\": global_cache._Pipeline(pipe, \"abc123\"),\n }\n\n @staticmethod\n def test_compare_and_swap():\n redis = mock.Mock(spec=())\n cache = global_cache.RedisCache(redis)\n pipe1 = mock.Mock(spec=(\"multi\", \"mset\", \"execute\", \"reset\"))\n pipe2 = mock.Mock(spec=(\"multi\", \"mset\", \"execute\", \"reset\"))\n cache._pipes.pipes = {\n \"ay\": global_cache._Pipeline(pipe1, \"abc123\"),\n \"be\": global_cache._Pipeline(pipe1, \"abc123\"),\n \"see\": global_cache._Pipeline(pipe2, \"def456\"),\n \"dee\": global_cache._Pipeline(pipe2, \"def456\"),\n \"whatevs\": global_cache._Pipeline(None, \"himom!\"),\n }\n pipe2.execute.side_effect = redis_module.exceptions.WatchError\n\n items = {\"ay\": \"foo\", \"be\": \"bar\", \"see\": \"baz\", \"wut\": \"huh?\"}\n cache.compare_and_swap(items)\n\n pipe1.multi.assert_called_once_with()\n pipe2.multi.assert_called_once_with()\n pipe1.mset.assert_called_once_with({\"ay\": \"foo\", \"be\": \"bar\"})\n pipe2.mset.assert_called_once_with({\"see\": \"baz\"})\n pipe1.execute.assert_called_once_with()\n pipe2.execute.assert_called_once_with()\n pipe1.reset.assert_called_once_with()\n pipe2.reset.assert_called_once_with()\n\n assert cache.pipes == {\n \"whatevs\": global_cache._Pipeline(None, \"himom!\")\n }\n\n @staticmethod\n def test_compare_and_swap_w_expires():\n expired = {}\n\n def mock_expire(key, expires):\n expired[key] = expires\n\n redis = mock.Mock(spec=())\n cache = global_cache.RedisCache(redis)\n pipe1 = mock.Mock(\n expire=mock_expire,\n spec=(\"multi\", \"mset\", \"execute\", \"expire\", \"reset\"),\n )\n pipe2 = mock.Mock(\n expire=mock_expire,\n spec=(\"multi\", \"mset\", \"execute\", \"expire\", \"reset\"),\n )\n cache._pipes.pipes = {\n \"ay\": global_cache._Pipeline(pipe1, \"abc123\"),\n \"be\": global_cache._Pipeline(pipe1, \"abc123\"),\n \"see\": global_cache._Pipeline(pipe2, \"def456\"),\n \"dee\": global_cache._Pipeline(pipe2, \"def456\"),\n \"whatevs\": global_cache._Pipeline(None, \"himom!\"),\n }\n pipe2.execute.side_effect = redis_module.exceptions.WatchError\n\n items = {\"ay\": \"foo\", \"be\": \"bar\", \"see\": \"baz\", \"wut\": \"huh?\"}\n cache.compare_and_swap(items, expires=32)\n\n pipe1.multi.assert_called_once_with()\n pipe2.multi.assert_called_once_with()\n pipe1.mset.assert_called_once_with({\"ay\": \"foo\", \"be\": \"bar\"})\n pipe2.mset.assert_called_once_with({\"see\": \"baz\"})\n pipe1.execute.assert_called_once_with()\n pipe2.execute.assert_called_once_with()\n pipe1.reset.assert_called_once_with()\n pipe2.reset.assert_called_once_with()\n\n assert cache.pipes == {\n \"whatevs\": global_cache._Pipeline(None, \"himom!\")\n }\n assert expired == {\"ay\": 32, \"be\": 32, \"see\": 32}\n","sub_path":"tests/unit/test_global_cache.py","file_name":"test_global_cache.py","file_ext":"py","file_size_in_byte":10479,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"}
+{"seq_id":"496139556","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Mar 7 15:21:51 2017\n@author: Cesar Alvarez\nSurprisingly there are only three numbers that can be written as the sum of \nfourth powers of their digits:\n\n1634 = 14 + 64 + 34 + 44\n8208 = 84 + 24 + 04 + 84\n9474 = 94 + 44 + 74 + 44\nAs 1 = 14 is not a sum it is not included.\n\nThe sum of these numbers is 1634 + 8208 + 9474 = 19316.\n\nFind the sum of all the numbers that can be written as the sum of fifth powers \nof their digits.\n\n\"\"\"\nN=int(input())\n\nLimit=(N)*(9**N)\nif N==6:\n Limit=550000\nstart=10\nacum=0\nfor j in range(start,Limit):\n a=list(str(j))\n b=[int(i)**N for i in a]\n \n if sum(b) == j:\n acum+=j\nprint(acum)","sub_path":"p30DigitFifthPowersHackerRank.py","file_name":"p30DigitFifthPowersHackerRank.py","file_ext":"py","file_size_in_byte":678,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"}
+{"seq_id":"407256661","text":"#!/usr/bin/python\nimport sys\nimport string\n\ndigs = string.digits + string.letters\ndef base36(x):\n if x == 0: return digs[0]\n digits = []\n while x:\n digits.append(digs[x % 36].upper())\n x /= 36\n digits.reverse()\n return ''.join(digits)\n\ndef main():\n z = int(sys.argv[1])\n g = ''\n for i in range(z):\n for j in range(i+1,z):\n if (i%2==0 and j%2!=0) or (i%2!=0 and j%2==0):\n g+='+xe'+base36(i+1)+base36(j+1)\n print(g)\n\n\nif __name__ == '__main__':\n main()","sub_path":"build_graph.py","file_name":"build_graph.py","file_ext":"py","file_size_in_byte":507,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"}
+{"seq_id":"190309395","text":"#!/usr/bin/env python\nimport json\nimport re\n# TODO: Replase urllib to requests\nfrom urllib.request import Request, urlopen, HTTPError, URLError\nfrom typing import Dict, Iterator, List\n\nDEFAULT_SOLR_URL = 'http://localhost:8983/solr'\n# s/( -?)9\\d\\.\\d{2,}/\\190.0/g\nREGEX_OUTER_LATITUDE = re.compile(r\"(?P -?)9\\d\\.\\d{2,}\")\n# s/([\\(,]-?)18\\d\\.\\d{2,}/\\1180.0/g\nREGEX_OUTER_LONGITUDE = re.compile(r\"(?P[\\(,]-?)18\\d\\.\\d{2,}\")\n\n\nclass SolrClient:\n def __init__(self, core: str, base_url: str = DEFAULT_SOLR_URL):\n self.base_url = base_url\n self.core = core\n\n def upsert_field_types(self, field_types: Iterator[Dict]) -> List:\n return [self.__upsert_field_type(field_type) for field_type in field_types]\n\n def __upsert_field_type(self, field_type: Dict):\n url = self.__build_url(suffix=\"schema\")\n upsert_key = self.__switch_upsert_field_type_key(name=field_type['name'])\n data = {upsert_key: field_type}\n headers = {\"Content-type\": \"application/json\"}\n req = Request(url, json.dumps(data).encode(), headers)\n try:\n with urlopen(req) as res:\n return res\n except HTTPError as err:\n print(f\"Failed to upsert field. {field_type}\")\n print(err.code)\n print(err.reason)\n raise err\n except URLError as err:\n print(f\"Failed to upsert field. {field_type}\")\n print(err.reason)\n raise err\n\n def __switch_upsert_field_type_key(self, name: str) -> str:\n if self.__exists_field_type(name):\n return \"replace-field-type\"\n else:\n return \"add-field-type\"\n\n def __exists_field_type(self, name: str) -> bool:\n url = self.__build_url(suffix=f\"schema/fieldtypes/{name}\")\n try:\n with urlopen(Request(url)) as _:\n return True\n except HTTPError as err:\n if err.code == 404:\n return False\n raise err\n except URLError as err:\n raise err\n\n def __build_url(self, suffix: str) -> str:\n return f\"{self.base_url}/{self.core}/{suffix}\"\n\n def upsert_fields(self, fields: Iterator) -> List:\n return [self.__upsert_field(field) for field in fields]\n\n def __upsert_field(self, field: Dict):\n url = self.__build_url(suffix=\"schema\")\n upsert_key = self.__switch_upsert_field_key(name=field['name'])\n data = {upsert_key: field}\n headers = {\"Content-type\": \"application/json\"}\n req = Request(url, json.dumps(data).encode(), headers)\n try:\n with urlopen(req) as res:\n _ = res.read\n except HTTPError as err:\n print(f\"Failed to upsert field: {field['name']}\")\n print(err.code)\n print(err.reason)\n raise err\n except URLError as err:\n print(f\"Failed to upsert field: {field['name']}\")\n print(err.reason)\n raise err\n\n def __switch_upsert_field_key(self, name: str) -> str:\n if self.__exists_field(name):\n return \"replace-field\"\n else:\n return \"add-field\"\n\n def __exists_field(self, name: str) -> bool:\n url = self.__build_url(suffix=f\"schema/fields/{name}\")\n try:\n with urlopen(Request(url)) as _:\n return True\n except HTTPError as err:\n if err.code == 404:\n return False\n raise err\n\n def index(self, documents: Iterator[Dict]):\n return [self.__index_document(document) for document in documents]\n\n def __index_document(self, document: Dict):\n document[\"WKT\"] = rearrange_out_of_range_point(document[\"WKT\"])\n\n url = self.__build_url(suffix=\"update/json/docs\")\n headers = {\"Content-type\": \"application/json\"}\n req = Request(url, json.dumps(document).encode(), headers, method=\"POST\")\n try:\n with urlopen(req) as res:\n _ = res.read()\n except HTTPError as err:\n print(err.code)\n print(err.reason)\n if err.code == 400:\n print(f\"[ERROR]: Skipped to index {document['places']}\")\n print(err.msg)\n print(json.dumps(document).encode())\n return\n raise err\n except URLError as err:\n print(err.reason)\n raise err\n \n\n def commit(self):\n url = self.__build_url(suffix=\"update?commit=true\")\n try:\n with urlopen(Request(url)) as res:\n return res\n except HTTPError as err:\n raise err\n except URLError as err:\n raise err\n\n def delete_all_index(self):\n url = self.__build_url(suffix=\"update?commit=true\")\n headers = {\"Content-type\": \"application/json\"}\n data = {\"delete\": {\"query\": \"*:*\"}}\n req = Request(url, json.dumps(data).encode(), headers)\n try:\n with urlopen(req) as res:\n _ = res.read()\n except HTTPError as err:\n print(err.code)\n print(err.reason)\n raise err\n except URLError as err:\n print(err.reason)\n raise err\n\n\ndef rearrange_out_of_range_point(wkt: str) -> str:\n r\"\"\"\n Flatten out of range point to on border.\n latitude: [-90.0, 90.0]; longitude: [-180.0, 180.0]\n\n latitude: 's/( -?)9\\d\\.\\d{2,}/\\190.0/g'\n longitude: 's/([\\(,]-?)18\\d\\.\\d{2,}/\\1180.0/g'\n \"\"\"\n wkt = REGEX_OUTER_LATITUDE.sub(r\"\\g90.0\", wkt)\n wkt = REGEX_OUTER_LONGITUDE.sub(r\"\\g180.0\", wkt)\n return wkt\n","sub_path":"converter/solr.py","file_name":"solr.py","file_ext":"py","file_size_in_byte":5627,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"}
+{"seq_id":"265347653","text":"#!usr/bin/env python\n#-*- encoding: utf-8 -*-\n\n\nimport gzip\nimport itertools\n\n\ndef is_header(line):\n return line[0] == '>'\n\ndef parse_multi_fasta_file(filename):\n \"\"\"Yields the name(ID) and a sequence as a tuple\n arg = a fasta file that can be compressed as a gzip file\n or a non compressed fasta file.\n \"\"\"\n print('Starting reading the fasta file' + '\\n')\n if filename.endswith('.gz'):\n opener = lambda filename: gzip.open(filename, 'rt')\n else:\n opener = lambda filename: open(filename, 'r')\n\n with opener(filename) as f:\n fasta_iter = (it[1] for it in itertools.groupby(f, is_header))\n for name in fasta_iter:\n name = next(name)\n sequences = ''.join(seq.strip() for seq in next(fasta_iter))\n yield name.strip()[1:], sequences\n\n\ndef str_punctuation_strip(word):\n \"\"\"It strip all the punctuation and other characters in a string.\"\"\"\n punctuation = '!\"#$%&\\'()*+,-/:;<=>?@[\\\\]^`{|}~'\n for char in word:\n for p in punctuation:\n word = word.replace(p, ' ')\n return word.strip().split()\n\n\n# filename = 'genomes/refseq/test/GCF_000005825.2/GCF_000005825.2_ASM582v2_cds_from_genomic.fna.gz'\n# filename = 'genomes/refseq/test/fastaFile.fa'\n# for name, seq in parse_multi_fasta_file(filename):\n# name = '/'.join(str_punctuation_strip(name)[1:4:2])\n# print(name)\n# print(seq)\n\n","sub_path":"fasta_reader.py","file_name":"fasta_reader.py","file_ext":"py","file_size_in_byte":1399,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"}
+{"seq_id":"221014308","text":"vote = 0\r\nana = 0\r\nbruno = 0\r\ncarlos = 0\r\nwhite = 0\r\ninvalid = 0\r\n\r\nwhile (True):\r\n print('--- Elections ---')\r\n print('0 - to vote white')\r\n print('1 - to vote in Ana')\r\n print('2 - to vote in Bruno')\r\n print('3 - to vote in Carlos')\r\n print('9 - to see results')\r\n vote = int(input('Enter: '))\r\n if vote == 0:\r\n white +=1\r\n elif vote == 1:\r\n ana += 1\r\n elif vote == 2:\r\n bruno += 1\r\n elif vote == 3:\r\n carlos += 1\r\n elif vote == 9:\r\n break\r\n else:\r\n invalid += 1\r\n\r\nprint('--- Results ---')\r\nprint('Ana had {} votes'.format(ana))\r\nprint('Bruno had {} votes'.format(bruno))\r\nprint('Carlos had {} votes'.format(carlos))\r\nprint('There ware {} whites votes'.format(white))\r\nprint(('There ware {} null votes'.format(invalid)))\r\n","sub_path":"Lista de exercicios 2/Q10.py","file_name":"Q10.py","file_ext":"py","file_size_in_byte":806,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"}
+{"seq_id":"549486244","text":"# Built-in\nimport logging\nimport os\nimport shutil\nimport subprocess\nfrom tempfile import TemporaryDirectory\nfrom io import StringIO\nfrom pkg_resources import resource_filename\n\n# This app\nfrom app_deployer.core.ansible import run_playbook\nfrom app_deployer.core.apps import get_app\n\n\nlogger = logging.getLogger(__name__)\n\n\ndef deploy(app_name, env, user=None, host=None, deploy_path=None, repo=None,\n record=None, **kwargs):\n \"\"\"\n Deploys an application\n\n Parameters\n ----------\n app_name : str\n Name of the application to deploy\n env : str\n Environment to deploy the app to - either dev, staging|qa, or prod|ops\n user : str, optional\n Name of the user to deploy the app as - this is the username on the host - if None then\n get the user from the App dict\n host : str, optional\n Host to deploy the app to - if None then get the host from the App dict by combining\n `environment` with the string `-host` (eg. staging-host), and getting the value of that\n key in the App dict\n deploy_path : str, optional\n Path to deploy the app to - if None then deploy_path will be set automatically by Ansible\n repo : str, optional\n Version control repo URL to deploy from - if None then get the repo from the App dict\n record : bool, optional\n Whether to record information about the deployment\n **kwargs\n Additional keyword arguments\n \"\"\"\n # Get the current dir so we can return there once finished\n orig_dir = os.getcwd()\n\n # Setup logging to a string to return\n if 'verbose' in kwargs and kwargs['verbose']:\n logger.setLevel('DEBUG')\n else:\n logger.setLevel('INFO')\n console = logging.StreamHandler(StringIO())\n logger.addHandler(console)\n\n # Load app_deployer.db.run_deployment only if the record option is True, otherwise no need to\n # import it. Plus, if the user is using the --no-record argument, they may not have setup a\n # secrets.yml file with `make recordsdb`\n if record:\n from app_deployer.core.recording import record_deployment\n\n # Get app properties\n app = get_app(app_name)\n repo = app['repo'] if repo is None else repo\n host = app[f'{env}-host'] if host is None else host\n user = app[f'{env}-user'] if user is None else user\n deploy_path = f'$HOME/apps/{app_name}' if deploy_path is None else deploy_path\n\n logger.debug(\n f'Deploying {app_name} to the {env} env ({user}@{host}:{deploy_path})...'\n )\n\n # Set some info to record this deployment in the DB\n record_info = {\n 'app-name': app_name,\n 'host': host,\n 'host-user': user,\n 'deploy-path': deploy_path,\n 'repo-url': repo,\n 'env': env\n }\n\n # Get path to ansible files\n ansible_files_path = resource_filename(__name__, '../ansible-files')\n\n # Create a temporary directory (as a context manager)\n with TemporaryDirectory(prefix='app-deployer-') as temp_dir:\n\n # Copy ansible files into temp_dir\n shutil.copytree(ansible_files_path, f'{temp_dir}/ansible-files')\n\n # Change into the temp ansible files dir\n os.chdir(f'{temp_dir}/ansible-files')\n\n # Run the deploy.yml playbook\n try:\n output = run_playbook('deploy.yml', app_name=app_name, host=host, user=user, repo=repo,\n deploy_path=deploy_path)\n except subprocess.CalledProcessError as e:\n os.chdir(orig_dir)\n logger.critical(f'Couldn\\'t deploy the app: {e.output.decode()}')\n # Record the deployment, specifying success as False\n if record:\n record_info['success'] = False\n record_deployment(record_info)\n # Return result and return code of 2\n results = console.stream.getvalue()\n console.flush()\n console.close()\n logger.removeHandler(console)\n\n return results, 2\n\n logger.debug(\nf\"\"\"\n=========================================================================================\nAnsible output\n\n{output}\n\"\"\"\n )\n\n # Record the deployment, specifying success as True\n if record:\n record_info['success'] = True\n record_deployment(record_info)\n\n # Change back into the original dir\n os.chdir(orig_dir)\n\n # Return result and return code of 0\n results = console.stream.getvalue()\n console.flush()\n console.close()\n logger.removeHandler(console)\n\n return results, 0\n","sub_path":"app_deployer/core/deploy.py","file_name":"deploy.py","file_ext":"py","file_size_in_byte":4528,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"}
+{"seq_id":"179516651","text":"import cv2\nimport numpy as np\nimport operator\nimport os\nimport pytesseract\nimport argparse\n\nMIN_CONTOUR_AREA = 100\n\nRESIZED_IMAGE_WIDTH = 20\nRESIZED_IMAGE_HEIGHT = 30\n\n\nclass ContourWithData():\n # member variables ############################################################################\n npaContour = None # contour\n boundingRect = None # bounding rect for contour\n intRectX = 0 # bounding rect top left corner x location\n intRectY = 0 # bounding rect top left corner y location\n intRectWidth = 0 # bounding rect width\n intRectHeight = 0 # bounding rect height\n fltArea = 0.0 # area of contour\n\n # calculate bounding rect info\n def calculateRectTopLeftPointAndWidthAndHeight(self):\n [intX, intY, intWidth, intHeight] = self.boundingRect\n self.intRectX = intX\n self.intRectY = intY\n self.intRectWidth = intWidth\n self.intRectHeight = intHeight\n\n # this is oversimplified, for a production grade program\n def checkIfContourIsValid(self):\n if self.fltArea < MIN_CONTOUR_AREA:\n return False # much better validity checking would be necessary\n return True\n\n\ndef main(args):\n # read in testing numbers image\n img = cv2.imread(args[\"image\"])\n\n config = (\n \"-l eng --psm 7 --oem 0 -c tessedit_char_whitelist=0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ\")\n text = pytesseract.image_to_string(img, config=config)\n\n print('text: '+text)\n\n # write text to the image\n cv2.putText(img, text, (5, 35),\n cv2.FONT_HERSHEY_SIMPLEX, 0.8, (0, 0, 255), 2)\n\n cv2.imshow(\"img\", img)\n ext = args[\"image\"].split(\".\")[-1]\n cv2.imwrite(args[\"image\"].split(\".\"+ext)[0]+\"_detected.jpg\", img)\n\n cv2.waitKey(0)\n cv2.destroyAllWindows()\n\n return\n\n\nif __name__ == \"__main__\":\n ap = argparse.ArgumentParser()\n ap.add_argument(\"-i\", \"--image\", type=str,\n help=\"path to input image\")\n ap.add_argument(\"-east\", \"--east\", type=str,\n help=\"path to input EAST text detector\", default=\"frozen_east_text_detection.pb\")\n ap.add_argument(\"-c\", \"--min-confidence\", type=float, default=0.5,\n help=\"minimum probability required to inspect a region\")\n ap.add_argument(\"-w\", \"--width\", type=int, default=320,\n help=\"nearest multiple of 32 for resized width\")\n ap.add_argument(\"-e\", \"--height\", type=int, default=320,\n help=\"nearest multiple of 32 for resized height\")\n ap.add_argument(\"-p\", \"--padding\", type=float, default=0.0,\n help=\"amount of padding to add to each border of ROI\")\n args = vars(ap.parse_args())\n\n main(args)\n","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":2763,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"}
+{"seq_id":"16996264","text":"import os\n\nfrom fab_deploy.base import gunicorn as base_gunicorn\n\nfrom fabric.api import run, sudo, env\nfrom fabric.tasks import Task\n\nclass GunicornControl(base_gunicorn.Control):\n\n def start(self):\n run('svcadm enable %s' % self.get_name())\n\n def stop(self):\n run('svcadm disable %s' % self.get_name())\n\n def restart(self):\n run('svcadm restart %s' % self.get_name())\n\nclass GunicornInstall(base_gunicorn.GunicornInstall):\n \"\"\"\n Install gunicorn and set it up with svcadm.\n \"\"\"\n\n def _setup_service(self, env_value=None):\n path = os.path.join(env.git_working_dir, 'deploy',\n 'gunicorn',\n '%s.xml' % self.gunicorn_name)\n\n run('svccfg import %s' % path)\n if env_value:\n run('svccfg -s %s setenv %s %s' % (self.gunicorn_name,\n env.project_env_var,\n env_value))\n\n def _setup_rotate(self, path):\n sudo('logadm -C 3 -p1d -c -w %s -z 1' % path)\n\n\nsetup = GunicornInstall()\ncontrol = GunicornControl()\n","sub_path":"fab_deploy/joyent/gunicorn.py","file_name":"gunicorn.py","file_ext":"py","file_size_in_byte":1126,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"}
+{"seq_id":"82586240","text":"# %load q05_runs/build.py\n# Default Imports\nfrom greyatomlib.python_getting_started.q01_read_data.build import read_data\ndata = read_data()\n\n\n# Your Solution\ndef BC_runs(data):\n\n # Write your code here\n runs=0\n run_by_McCullum=0\n l1 = data.get('innings')[0].get('1st innings').get('deliveries')\n for s in l1:\n for key, value in s.items():\n myval = value\n name=str(myval.get('batsman')) \n if(name=='BB McCullum'):\n run_by_McCullum=myval.get('runs').get('batsman')\n runs = runs+run_by_McCullum\n\n return(runs)\n\nBC_runs(data)\n\n\n","sub_path":"q05_runs/build.py","file_name":"build.py","file_ext":"py","file_size_in_byte":620,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"}
+{"seq_id":"384442957","text":"names=[]\r\nscores=[]\r\nhighest=0\r\nlowest=100\r\navg=0\r\ntotal=0\r\nx=input('輸入全班人數:')\r\nx=int(x)\r\ndef abc(x,total):\r\n avg = total/x\r\n return avg \r\nfor i in range(x):\r\n names.insert(i,input('輸入你的名字:'))\r\n scores.insert(i,int(input('輸入你的分數:')))\r\n total=total+scores[i]\r\navg = abc(x,total)\r\nprint('班平均:',avg)\r\n#def awd():\r\n# awd=\r\n\r\n\r\nfor y in range(x):\r\n num=int(scores[y])\r\n if int(num)>int(highest):\r\n highest=scores[y]\r\n else:\r\n highest=int(highest)\r\nprint(y) \r\n#print('班上最高分:',highest,'分')\r\n#for w in range(x):\r\n# num=int(scores[w])\r\n# if int(num)\n# BSD 2-clause (see LICENSE or https://opensource.org/licenses/BSD-2-Clause)\n\nfrom __future__ import absolute_import, division, print_function\nimport os\nimport json\nimport hashlib\n\nfrom ansible.module_utils.basic import AnsibleModule\n\n__metaclass__ = type\n\nANSIBLE_METADATA = {\n 'metadata_version': '0.1',\n 'status': ['preview'],\n 'supported_by': 'community'\n}\n\n# ---------------------------------------------------------------------------------------\n\n\nclass KnotZoneConfig(object):\n \"\"\"\n Main Class to implement the Icinga2 API Client\n \"\"\"\n module = None\n\n def __init__(self, module):\n \"\"\"\n Initialize all needed Variables\n \"\"\"\n self.module = module\n\n self.state = module.params.get(\"state\")\n #\n self.zone = module.params.get(\"zone\")\n self.zone_ttl = module.params.get(\"zone_ttl\")\n self.zone_soa = module.params.get(\"zone_soa\")\n self.name_servers = module.params.get(\"name_servers\")\n self.records = module.params.get(\"records\")\n\n self.database_path = module.params.get(\"database_path\")\n self.owner = module.params.get(\"owner\")\n self.group = module.params.get(\"group\")\n self.mode = module.params.get(\"mode\")\n\n self.zone_path = \"{0}\".format(self.database_path) # , self.zone)\n self.config_file = \"{0}/{1}.zone\".format(self.zone_path, self.zone)\n self.config_checksum = \"{0}/.{1}.checksum\".format(self.zone_path, self.zone)\n self.config_serial = \"{0}/.{1}.serial\".format(self.zone_path, self.zone)\n\n # self.module.log(msg=\"---------------------------------------------\")\n # self.module.log(msg=\"zone_path : {}\".format(self.zone_path))\n # self.module.log(msg=\"config_file : {}\".format(self.config_file))\n # self.module.log(msg=\"config_checksum: {}\".format(self.config_checksum))\n # self.module.log(msg=\"config_serial : {}\".format(self.config_serial))\n # self.module.log(msg=\"---------------------------------------------\")\n\n def run(self):\n \"\"\"\n run\n \"\"\"\n if self.state == 'absent':\n \"\"\"\n remove created zone directory\n \"\"\"\n _changed = False\n for f in [self.config_file, self.config_checksum, self.config_serial]:\n # self.module.log(msg=\"remove file : {}\".format(f))\n if(os.path.isdir(f)):\n _changed = True\n os.remove(f)\n\n return dict(\n changed = _changed,\n failed = False,\n msg = \"zone removed\"\n )\n\n if not os.path.isdir(self.zone_path):\n try:\n # Create Directory\n os.mkdir(self.zone_path)\n except FileExistsError:\n pass\n\n _checksum = ''\n _old_checksum = ''\n _data_changed = False\n\n data = dict()\n data[\"zone\"] = self.zone\n data[\"zone_ttl\"] = self.zone_ttl\n data[\"soa\"] = self.zone_soa\n data[\"name_servers\"] = self.name_servers\n data[\"records\"] = self.records\n\n # self.module.log(msg=\"---------------------------------------------\")\n # self.module.log(msg=\"data : {}\".format(json.dumps(data, sort_keys=True)))\n # self.module.log(msg=\"---------------------------------------------\")\n\n _checksum = self.__checksum(json.dumps(data, sort_keys=True))\n\n if os.path.isfile(self.config_checksum):\n with open(self.config_checksum, \"r\") as fp:\n _old_checksum = fp.readlines()[0]\n\n # self.module.log(msg=\"checksum current config: {}\".format(_checksum))\n # self.module.log(msg=\"old checksum : {}\".format(_old_checksum))\n\n if _old_checksum == _checksum:\n return dict(\n changed = False,\n failed = False,\n msg = \"no changes\"\n )\n\n # compare both checksums\n if _old_checksum != _checksum:\n soa_serial = self.__zone_serial()\n data[\"soa\"][\"serial\"] = soa_serial\n\n self.__write_template(self.config_file, data)\n\n with open(self.config_serial, \"w\") as fp:\n fp.write(soa_serial)\n\n with open(self.config_checksum, \"w\") as fp:\n fp.write(_checksum)\n\n return dict(\n changed = _data_changed,\n failed = False,\n msg = \"config created\"\n )\n\n def __zone_serial(self):\n \"\"\"\n\n \"\"\"\n from datetime import datetime\n\n now = datetime.now().strftime(\"%Y%m%d\")\n id = \"01\"\n\n if os.path.isfile(self.config_serial):\n with open(self.config_serial, 'r') as fp:\n _serial = fp.read()\n\n # self.module.log(msg=\"serial : {}\".format(_serial))\n # self.module.log(msg=\"date : {}\".format(_serial[:-2]))\n # self.module.log(msg=\"number : {}\".format(_serial[8:]))\n\n if now == _serial[:-2]:\n id = int(_serial[8:])\n # id = id + 1\n id = \"{0:02d}\".format(id + 1)\n\n _serial = \"{0}{1}\".format(\n now,\n id\n )\n\n # self.module.log(msg=\"serial : {}\".format(_serial))\n\n return _serial\n\n def __checksum(self, plaintext):\n \"\"\"\n create checksum from string\n \"\"\"\n password_bytes = plaintext.encode('utf-8')\n password_hash = hashlib.sha256(password_bytes)\n checksum = password_hash.hexdigest()\n\n return checksum\n\n def __write_template(self, file_name, data):\n \"\"\"\n\n \"\"\"\n tpl = \"\"\"\n$ORIGIN {{ item.zone }}.\n$TTL {{ item.zone_ttl }}\n\n@ SOA {{ item.soa.primary_dns }}. {{ item.soa.hostmaster }}. (\n {{ item.soa.serial }} ; serial\n {{ item.soa.refresh | default('6h') }} ; refresh\n {{ item.soa.retry | default('1h') }} ; retry\n {{ item.soa.expire | default('1w') }} ; expire\n {{ item.soa.minimum | default('1d') }} ) ; minimum\n\n{% if item.name_servers | count > 0 %}\n{%- for k, v in item.name_servers.items() %}\n{{ (v.ttl | default('3600')).ljust(10).rjust(42) }} {{ \"NS\".ljust(19) }} {{ (k + '.') }}\n{{ (k + '.').ljust(30) }} {{ (v.ttl | default('3600')).ljust(10) }} {{ \"A\".ljust(19) }} {{ v.ip }}\n{%- endfor -%}\n{%- endif %}\n\n{% if item.records | count > 0 %}\n{%- for k, v in item.records.items() %}\n{%- if v.description is defined and v.description | length != 0 %}\n;; {{ v.description }}\n{%- endif %}\n{%- if k == '@' %}\n{% set source = item.zone %}\n{%- else %}\n{% set source = v %}\n{%- endif -%}\n{%- if v.type == 'A' -%}\n{{ (k + '.').ljust(30) }} {{ (v.ttl | default('3600')).ljust(10) }} {{ v.type.ljust(20) }} {{ v.ip }}\n{%- if v.aliases is defined and v.aliases | count > 0 -%}\n{%- for a in v.aliases -%}\n{% set _source = a + '.' + item.zone %}\n{% set _type = 'CNAME' -%}\n{{ (_source + '.').ljust(30) }} {{ (v.ttl | default(item.zone_ttl) | string).ljust(10) }} {{ _type.ljust(20) }} {{ (k + '.') }}\n{%- endfor -%}\n{%- endif %}\n{%- endif %}\n{%- if v.type == 'CNAME' -%}\n{{ (k + '.').ljust(30) }} {{ (v.ttl | default('3600')).ljust(10) }} {{ v.type.ljust(20) }} {{ v.target }}.\n{%- endif %}\n{%- if v.type == 'TXT' -%}\n{{ (source + '.').ljust(30) }} {{ (v.ttl | default('3600')).ljust(10) }} {{ v.type.ljust(20) }} \"{{ v.text }}\"\n{%- endif %}\n{%- if v.type == 'SRV' -%}\n{{ (k + '.').ljust(30) }} {{ (v.ttl | default('3600')).ljust(10) }} {{ v.type.ljust(20) }} {{ v.priority }} {{ v.weight }} {{ v.port }} {{ v.target }}.\n{%- endif %}\n{%- endfor %}\n{%- endif %}\n\n\"\"\"\n from jinja2 import Template\n\n tm = Template(tpl)\n d = tm.render(item=data)\n\n with open(file_name, \"w\") as fp:\n fp.write(d)\n\n return True\n\n\n# ---------------------------------------------------------------------------------------\n# Module execution.\n#\n\ndef main():\n \"\"\"\n \"\"\"\n module = AnsibleModule(\n argument_spec = dict(\n state = dict(default=\"present\", choices=[\"absent\", \"present\"]),\n #\n zone = dict(required=True, type='str'),\n zone_ttl = dict(required=True, type='int'),\n zone_soa = dict(required=True, type='dict'),\n name_servers = dict(required=True, type='dict'),\n records = dict(required=True, type='dict'),\n debug = dict(required=False, type=\"bool\", default=False),\n\n database_path = dict(required=True, type='str'),\n owner = dict(required=False, type='str'),\n group = dict(required=False, type='str'),\n mode = dict(required=False, type='str', default=\"0666\"),\n ),\n supports_check_mode = True,\n )\n\n c = KnotZoneConfig(module)\n result = c.run()\n\n module.exit_json(**result)\n\n\n# import module snippets\nif __name__ == '__main__':\n main()\n","sub_path":"library/knot_zone.py","file_name":"knot_zone.py","file_ext":"py","file_size_in_byte":9110,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"}
+{"seq_id":"158604399","text":"#!/usr/bin/python3\n\"\"\" Unittest for FileStorage class\n\"\"\"\nimport unittest\nimport os\nimport models\nfrom models.engine.file_storage import FileStorage\nfrom models.base_model import BaseModel\n\n\nclass TestFileStorage(unittest.TestCase):\n \"\"\"Utilizes unittest to evaluate possible outcomes of\n creating instances of FileStorage class\n \"\"\"\n\n def setUp(self):\n \"\"\"sets up testing environment so previous file storage\n is not affected\"\"\"\n file_path = models.storage._FileStorage__file_path\n self.my_path = models.storage._FileStorage__file_path\n if os.path.exists(file_path):\n os.rename(file_path, 'test_storage')\n self.testcase = FileStorage()\n\n def tearDown(self):\n \"\"\" Removes JSON file after test cases run \"\"\"\n file_path = models.storage._FileStorage__file_path\n if os.path.exists(file_path):\n os.remove(file_path)\n if os.path.exists('test_storage'):\n os.rename('test_storage', file_path)\n self.testcase = None\n\n def test_save_1(self):\n \"\"\"testing if save saves new instance properly\n \"\"\"\n my_model = BaseModel()\n my_storage = FileStorage()\n my_storage.new(my_model)\n my_storage.save()\n file_existence = os.path.exists(self.my_path)\n self.assertEqual(True, file_existence)\n\n def test_save_2(self):\n \"\"\"tests if updating attributes saves properly\"\"\"\n my_model = BaseModel()\n my_storage = FileStorage()\n my_model.my_number = 89\n my_storage.save()\n self.assertEqual(my_model.my_number, 89)\n\n def test_save_3(self):\n \"\"\"tests if file contains correct id after saving\"\"\"\n my_model = BaseModel()\n my_storage = FileStorage()\n my_storage.save()\n desired_str = 'BaseModel.' + my_model.id\n with open(self.my_path, \"r\", encoding=\"utf-8\") as f:\n if desired_str in f.read():\n result = True\n else:\n result = False\n self.assertEqual(result, True)\n\n def test_file_path(self):\n \"\"\"testing if file saves as correct file path name\"\"\"\n my_storage = FileStorage()\n my_storage.save()\n expected_name = self.my_path\n self.assertEqual(expected_name, my_storage._FileStorage__file_path)\n\n def test_file_empty(self):\n \"\"\"testing if file saves properly, and doesn't return an\n empty file\"\"\"\n my_model = BaseModel()\n my_storage = FileStorage()\n my_storage.new(my_model)\n my_storage.save()\n self.assertEqual(os.stat(self.my_path).st_size == 0, False)\n\n def test_file_storage_file_path_exists(self):\n \"\"\"Tests if __file_path is created correctly\"\"\"\n self.assertEqual(type(self.testcase._FileStorage__file_path), str)\n\n def test_file_storage_objects_exists(self):\n \"\"\"Test if __objects is created correctly\"\"\"\n self.assertEqual(type(self.testcase._FileStorage__objects), dict)\n\n def test_file_storage_all_method(self):\n \"\"\"Test all method\"\"\"\n my_model = BaseModel()\n my_storage = FileStorage()\n my_dict = my_storage.all()\n self.assertEqual(my_dict, my_storage._FileStorage__objects)\n\n def test_file_storage_new_method(self):\n \"\"\"Test new method\"\"\"\n my_model = BaseModel()\n my_storage = FileStorage()\n my_storage.new(my_model)\n my_storage.save()\n desired_key = my_model.__class__.__name__ + '.' + my_model.id\n for key in my_storage._FileStorage__objects:\n if key == desired_key:\n self.assertEqual(desired_key, key)\n","sub_path":"tests/test_models/test_engine/test_file_storage.py","file_name":"test_file_storage.py","file_ext":"py","file_size_in_byte":3652,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"}
+{"seq_id":"568381120","text":"import os\n\nfrom flask import Flask, request\nfrom flask_cors import CORS\nfrom flask_sqlalchemy import SQLAlchemy\n\nimport uuid\n\nimport boto3\n\n# local config import\nfrom instance.config import app_config\n\ndb = SQLAlchemy()\n\ns3 = boto3.client('s3')\n\n\n# noinspection PyTypeChecker\ndef create_api(flask_app):\n from flask_rest_jsonapi import Api\n\n from app.schemas.garden import GardenList, GardenDetail, GardenBedList, GardenBedDetail, GardenPlantList, \\\n GardenPlantDetail\n\n from app.schemas.bed import BedList, BedDetail, BedPlantList, BedPlantDetail, BedPlantCalendarList, \\\n BedPlantCalendarDetail, BedPlantCalendarHarvestList, BedPlantCalendarHarvestDetail, BedPlantCalendarNoteList, \\\n BedPlantCalendarNoteDetail, BedPlantCalendarBloomingList, BedPlantCalendarBloomingDetail, \\\n BedPlantCalendarPruningList, BedPlantCalendarPruningDetail, BedPlantCalendarHarvestNoteList, \\\n BedPlantCalendarHarvestNoteDetail, BedPlantCalendarBloomingNoteList, BedPlantCalendarBloomingNoteDetail, \\\n BedPlantCalendarPruningNoteList, BedPlantCalendarPruningNoteDetail, BedPlantNoteList, BedPlantNoteDetail, \\\n BedNoteList, BedNoteDetail\n\n from app.schemas.plant import PlantList, PlantDetail\n from app.schemas.plant import PlantNoteList, PlantNoteDetail\n from app.schemas.plant import PlantLightRequirementList, PlantLightRequirementDetail\n from app.schemas.plant import PlantLightRequirementNoteList, PlantLightRequirementNoteDetail\n from app.schemas.plant import PlantWaterRequirementList, PlantWaterRequirementDetail\n from app.schemas.plant import PlantWaterRequirementNoteList, PlantWaterRequirementNoteDetail\n from app.schemas.plant import PlantUseList, PlantUseDetail\n from app.schemas.plant import PlantSeasonList, PlantSeasonDetail\n from app.schemas.plant import PlantPropagationList, PlantPropagationDetail\n from app.schemas.plant import PlantHarvestList, PlantHarvestDetail\n from app.schemas.plant import PlantBloomingList, PlantBloomingDetail\n from app.schemas.plant import PlantPruningList, PlantPruningDetail\n\n from app.schemas.lifespan import LifespanList, LifespanDetail\n from app.schemas.soil import SoilList, SoilDetail\n from app.schemas.family import FamilyList, FamilyDetail\n from app.schemas.genus import GenusList, GenusDetail\n from app.schemas.species import SpeciesList, SpeciesDetail\n from app.schemas.category import CategoryList, CategoryDetail\n from app.schemas.measurement_unit import MeasurementUnitList, MeasurementUnitDetail\n from app.schemas.soil_fertility import SoilFertilityList, SoilFertilityDetail\n from app.schemas.growth_habit import GrowthHabitList, GrowthHabitDetail\n from app.schemas.light_requirement import LightRequirementList, LightRequirementDetail\n from app.schemas.water_requirement import WaterRequirementList, WaterRequirementDetail\n from app.schemas.season import SeasonList, SeasonDetail\n from app.schemas.use import UseList, UseDetail\n from app.schemas.note import NoteList, NoteDetail\n from app.schemas.month import MonthList, MonthDetail\n\n api = Api(flask_app)\n\n # MONTH ROUTES\n api.route(MonthList, 'month_list', '/months')\n api.route(MonthDetail, 'month_detail', '/months/')\n\n api.route(GardenList, 'garden_list', '/gardens')\n api.route(GardenDetail, 'garden_detail', '/gardens/')\n\n api.route(BedList, 'bed_list', '/beds')\n api.route(BedDetail, 'bed_detail', '/beds/')\n\n api.route(LifespanList, 'lifespan_list', '/lifespans')\n api.route(LifespanDetail, 'lifespan_detail', '/lifespans/')\n\n api.route(SoilList, 'soil_list', '/soils')\n api.route(SoilDetail, 'soil_detail', '/soils/')\n\n api.route(FamilyList, 'family_list', '/families')\n api.route(FamilyDetail, 'family_detail', '/families/')\n\n api.route(GenusList, 'genus_list', '/genera')\n api.route(GenusDetail, 'genus_detail', '/genera/')\n\n api.route(SpeciesList, 'species_list', '/species')\n api.route(SpeciesDetail, 'species_detail', '/species/')\n\n api.route(CategoryList, 'category_list', '/categories')\n api.route(CategoryDetail, 'category_detail', '/categories/')\n\n api.route(MeasurementUnitList, 'measurement_unit_list', '/measurement_units')\n api.route(MeasurementUnitDetail, 'measurement_unit_detail', '/measurement_units/')\n\n api.route(SoilFertilityList, 'soil_fertility_list', '/soil_fertility')\n api.route(SoilFertilityDetail, 'soil_fertility_detail', '/soil_fertility/')\n\n api.route(GrowthHabitList, 'growth_habit_list', '/growth_habits')\n api.route(GrowthHabitDetail, 'growth_habit_detail', '/growth_habits/')\n\n api.route(LightRequirementList, 'light_requirement_list', '/light_requirements')\n api.route(LightRequirementDetail, 'light_requirement_detail', '/light_requirements/')\n\n api.route(WaterRequirementList, 'water_requirement_list', '/water_requirements')\n api.route(WaterRequirementDetail, 'water_requirement_detail', '/water_requirements/')\n\n api.route(SeasonList, 'season_list', '/seasons')\n api.route(SeasonDetail, 'season_detail', '/seasons/')\n\n api.route(UseList, 'use_list', '/uses')\n api.route(UseDetail, 'use_detail', '/uses/')\n\n api.route(NoteList, 'note_list', '/notes')\n api.route(NoteDetail, 'note_detail', '/notes/')\n\n api.route(PlantList, 'plant_list', '/plants')\n api.route(PlantDetail, 'plant_detail', '/plants/')\n\n api.route(PlantNoteList, 'plant_note_list', '/plant_notes')\n api.route(PlantNoteDetail, 'plant_note_detail', '/plant_notes/')\n\n api.route(PlantUseList, 'plant_use_list', '/plant_uses')\n api.route(PlantUseDetail, 'plant_use_detail', '/plant_uses/')\n\n api.route(PlantSeasonList, 'plant_season_list', '/plant_seasons')\n api.route(PlantSeasonDetail, 'plant_season_detail', '/plant_seasons/')\n\n api.route(PlantPropagationList, 'plant_propagation_list', '/plant_propagations')\n api.route(PlantPropagationDetail, 'plant_propagation_detail', '/plant_propagations/')\n\n api.route(PlantHarvestList, 'plant_harvest_list', '/plant_harvests')\n api.route(PlantHarvestDetail, 'plant_harvest_detail', '/plant_harvests/')\n\n api.route(PlantBloomingList, 'plant_blooming_list', '/plant_bloomings')\n api.route(PlantBloomingDetail, 'plant_blooming_detail', '/plant_bloomings/')\n\n api.route(PlantPruningList, 'plant_pruning_list', '/plant_prunings')\n api.route(PlantPruningDetail, 'plant_pruning_detail', '/plant_prunings/')\n\n api.route(PlantLightRequirementList, 'plant_light_requirement_list', '/plant_light_requirements')\n api.route(PlantLightRequirementDetail, 'plant_light_requirement_detail', '/plant_light_requirements/')\n\n api.route(PlantLightRequirementNoteList, 'plant_light_requirement_note_list', '/plant_light_requirement_notes')\n api.route(PlantLightRequirementNoteDetail,\n 'plant_light_requirement_note_detail', '/plant_light_requirement_notes/')\n\n api.route(PlantWaterRequirementList, 'plant_water_requirement_list', '/plant_water_requirements')\n api.route(PlantWaterRequirementDetail, 'plant_water_requirement_detail', '/plant_water_requirements/')\n\n api.route(PlantWaterRequirementNoteList, 'plant_water_requirement_note_list', '/plant_water_requirement_notes')\n api.route(PlantWaterRequirementNoteDetail,\n 'plant_water_requirement_note_detail', '/plant_water_requirement_notes/')\n\n api.route(GardenBedList, 'garden_bed_list', '/garden_beds')\n api.route(GardenBedDetail, 'garden_bed_detail', '/garden_beds/')\n\n api.route(GardenPlantList, 'garden_plant_list', '/garden_plants')\n api.route(GardenPlantDetail, 'garden_plant_detail', '/garden_plants/')\n\n api.route(BedPlantList, 'bed_plant_list', '/bed_plants')\n api.route(BedPlantDetail, 'bed_plant_detail', '/bed_plants/')\n\n api.route(BedNoteList, 'bed_note_list', '/bed_notes')\n api.route(BedNoteDetail, 'bed_note_detail', '/bed_notes/')\n\n api.route(BedPlantNoteList, 'bed_plant_note_list', '/bed_plant_notes')\n api.route(BedPlantNoteDetail, 'bed_plant_note_detail', '/bed_plant_notes/')\n\n api.route(BedPlantCalendarList, 'bed_plant_calendar_list', '/bed_plant_calendars')\n api.route(BedPlantCalendarDetail, 'bed_plant_calendar_detail', '/bed_plant_calendars/')\n\n api.route(BedPlantCalendarHarvestList, 'bed_plant_calendar_harvest_list', '/bed_plant_calendar_harvests')\n api.route(BedPlantCalendarHarvestDetail,\n 'bed_plant_calendar_harvest_detail', '/bed_plant_calendar_harvests/')\n\n api.route(BedPlantCalendarBloomingList, 'bed_plant_calendar_blooming_list', '/bed_plant_calendar_bloomings')\n api.route(BedPlantCalendarBloomingDetail,\n 'bed_plant_calendar_blooming_detail', '/bed_plant_calendar_bloomings/')\n\n api.route(BedPlantCalendarPruningList, 'bed_plant_calendar_pruning_list', '/bed_plant_calendar_prunings')\n api.route(BedPlantCalendarPruningDetail,\n 'bed_plant_calendar_pruning_detail', '/bed_plant_calendar_prunings/')\n\n api.route(BedPlantCalendarNoteList, 'bed_plant_calendar_note_list', '/bed_plant_calendar_notes')\n api.route(BedPlantCalendarNoteDetail, 'bed_plant_calendar_note_detail', '/bed_plant_calendar_notes/')\n\n api.route(BedPlantCalendarHarvestNoteList,\n 'bed_plant_calendar_harvest_note_list', '/bed_plant_calendar_harvest_notes')\n api.route(BedPlantCalendarHarvestNoteDetail,\n 'bed_plant_calendar_harvest_note_detail', '/bed_plant_calendar_harvest_notes/')\n\n api.route(BedPlantCalendarBloomingNoteList,\n 'bed_plant_calendar_blooming_note_list', '/bed_plant_calendar_blooming_notes')\n api.route(BedPlantCalendarBloomingNoteDetail,\n 'bed_plant_calendar_blooming_note_detail', '/bed_plant_calendar_blooming_notes/')\n\n api.route(BedPlantCalendarPruningNoteList,\n 'bed_plant_calendar_pruning_note_list', '/bed_plant_calendar_pruning_notes')\n api.route(BedPlantCalendarPruningNoteDetail,\n 'bed_plant_calendar_pruning_note_detail', '/bed_plant_calendar_pruning_notes/')\n\n\ndef create_flask_app(environment_config):\n flask_app = Flask(__name__)\n flask_app.config.from_object(app_config[environment_config])\n flask_app.config.from_pyfile('../instance/config.py')\n flask_app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False\n\n CORS(flask_app)\n\n return flask_app\n\n\ndef create_app(environment_config):\n app = create_flask_app(environment_config)\n create_api(app)\n db.init_app(app)\n\n return app\n\nconfig_name = os.getenv('APP_SETTINGS')\napplication = create_app(config_name)\n\ns3_plants_bucket = os.getenv('S3_PLANTS_BUCKET')\ns3_beds_bucket = os.getenv('S3_BEDS_BUCKET')\ns3_gardens_bucket = os.getenv('S3_GARDENS_BUCKET')\n\n\n@application.route(\"/upload_plant_image\", methods=['POST', 'GET'])\ndef upload_plant_image():\n s3_filename = str(uuid.uuid4())\n\n file = request.files['image']\n\n s3.upload_fileobj(file, s3_plants_bucket, s3_filename, ExtraArgs={'ACL': 'public-read', 'ContentType': file.content_type})\n\n endpoint = 'https://s3.amazonaws.com/' + s3_plants_bucket + '/' + s3_filename\n\n return endpoint\n\n\n@application.route(\"/upload_bed_image\", methods=['POST', 'GET'])\ndef upload_bed_image():\n s3_filename = str(uuid.uuid4())\n\n file = request.files['image']\n\n s3.upload_fileobj(file, s3_beds_bucket, s3_filename, ExtraArgs={'ACL': 'public-read', 'ContentType': file.content_type})\n\n endpoint = 'https://s3.us-east-2.amazonaws.com/' + s3_beds_bucket + '/' + s3_filename\n\n return endpoint\n\n\n@application.route(\"/upload_garden_image\", methods=['POST', 'GET'])\ndef upload_garden_image():\n s3_filename = str(uuid.uuid4())\n\n file = request.files['image']\n\n s3.upload_fileobj(file, s3_gardens_bucket, s3_filename, ExtraArgs={'ACL': 'public-read', 'ContentType': file.content_type})\n\n endpoint = 'https://s3.us-east-2.amazonaws.com/' + s3_gardens_bucket + '/' + s3_filename\n\n return endpoint\n","sub_path":"app/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":12234,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"}
+{"seq_id":"209756223","text":"\"\"\"\nYou are given coins of different denominations and a total amount of money amount.\nWrite a function to compute the fewest number of coins that you need to make up that amount.\nIf that amount of money cannot be made up by any combination of the coins, return -1.\n\"\"\"\n\nclass Solution(object):\n def coinChange(self, coins, amount):\n if amount < 0:\n return 0\n\n def fewest(coins, rem, count):\n if rem < 0: return -1\n if rem == 0: return 0\n if count[rem-1] != 0:\n return count[rem - 1]\n\n min = float('inf')\n for coin in coins:\n res = fewest(coins, rem-coin, count)\n if res >= 0 and res < min:\n min = 1 + res\n count[rem - 1] = -1 if min == float('inf') else min\n return count[rem - 1]\n\n return fewest(coins, amount, [0]*amount)\n\n # Amount outer loop\n def coinChange2(self, coins, amount):\n f = [amount + 1] * (amount + 1)\n f[0] = 0\n for i in range(1, amount + 1):\n for coin in coins:\n if coin <= i:\n f[i] = min(f[i], f[i - coin] + 1)\n\n if f[amount] > amount:\n return -1\n else:\n return f[amount]\n\n # coins outer loop\n def coinChange3(self, coins, amount):\n f = [amount + 1] * (amount + 1)\n f[0] = 0\n for coin in coins:\n for i in range(coin, amount + 1):\n f[i] = min(f[i], f[i-coin] + 1)\n return f[amount] if f[amount] <= amount else -1\n\n\n\n# coins = [1,2,5] # 3\n# amount = 11\n# coins = [2] # -1\n# amount = 3\ncoins = [2,5,10,1] # 4\namount = 27\n# coins = [186,419,83,408] # expect 20\n# amount = 6249\n\nprint(Solution().coinChange3(coins, amount))","sub_path":"322CoinChange.py","file_name":"322CoinChange.py","file_ext":"py","file_size_in_byte":1782,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"}
+{"seq_id":"168336059","text":"#!/usr/bin/env python3\nimport json\nimport sys\nfrom os.path import join, dirname, isfile\nfrom os import makedirs, remove, environ\nfrom dotenv import load_dotenv\nfrom . import log\nfrom . import util\n\nthis = sys.modules[__name__]\nthis.is_validation_checked = False\n\nlogger = log.get_logger()\n\ndef check_validation(dir_path):\n if not this.is_validation_checked:\n dotenv_path = join(dir_path, \".env\")\n if not isfile(dotenv_path):\n logger.error(\".env file not exists\")\n return False\n \n jceks_path = join(dir_path, \"jwt.jceks\")\n if not isfile(jceks_path):\n logger.error(\"jwt.jceks file not exists\")\n return False\n \n logback_path = join(dir_path, \"logback.xml\")\n if not isfile(logback_path):\n logger.error(\"logback.xml file not exists\")\n return False\n\n load_dotenv(dotenv_path)\n this.is_validation_checked = True\n\n return True\n\ndef saveJsonConfig(dir_path, file_name, json_dict):\n json_content = json.dumps(json_dict)\n dest_file_name = join(dir_path, file_name)\n\n try:\n makedirs(dir_path)\n except:\n pass\n\n try:\n remove(dest_file_name)\n except:\n pass\n\n with open(dest_file_name, \"w\") as conf_json:\n conf_json.write(json_content)\n\ndef generate_frontend_config(dir_path):\n if not check_validation(dir_path):\n exit()\n\n # config file for nodejs web app\n frontend_dic = {\n \"cookieDomain\": environ[\"FR_CONF_COOKIE_DOMAIN\"],\n \"tokenCookieName\": environ[\"FR_CONF_TOKEN_COOKIE_NAME\"],\n \"apiRootUrl\": environ[\"FR_CONF_API_ROOT_URL\"],\n \"loginRootUrl\": environ[\"FR_CONF_LOGIN_ROOT_URL\"],\n \"siteUrl\": environ[\"BE_CONF_SITE_URL\"],\n \"gaCode\": environ[\"FR_CONF_GA_CODE\"]\n }\n frontend_dir_path = join(dir_path, \"frontend\", \"src\")\n frontend_file_name = \"conf.json\"\n saveJsonConfig(frontend_dir_path, frontend_file_name, frontend_dic)\n\n logger.info(\"Save frontend config file: %s/%s\", frontend_dir_path, frontend_file_name)\n\ndef generate_backend_config(dir_path):\n logger.info(\"Begin to generate backend config file\")\n\n if not check_validation(dir_path):\n exit()\n\n mysqlUrl = \"jdbc:mysql://{}:{}/{}?serverTimezone=UTC&characterEncoding=UTF-8&useSSL={}\".format(\n environ[\"DB_HOST\"],\n environ[\"DB_PORT\"],\n environ[\"DB_DATABASE\"],\n environ[\"DB_SSLENABLED\"]\n )\n\n backend_dic = {\n \"http.port\": int(environ[\"BE_CONF_HTTP_PORT\"]),\n \"site.url\": environ[\"BE_CONF_SITE_URL\"],\n \"restApi.url\": environ[\"BE_CONF_REST_API_URL\"],\n \"restApi.domain\": environ[\"BE_CONF_REST_API_DOMAIN\"],\n \"datasource\": {\n \"driverClassName\": environ[\"DB_DRIVERCLASS\"],\n \"username\": environ[\"DB_USER\"],\n \"password\": environ[\"DB_PASSWORD\"],\n \"url\": mysqlUrl\n },\n \"oauth\": {\n \"github\": {\n \"clientId\": environ[\"OAUTH_GITHUB_CLIENTID\"],\n \"clientSecret\": environ[\"OAUTH_GITHUB_CLIENTSECRET\"],\n \"callbackUrl\": environ[\"OAUTH_GITHUB_CALLBACK_URL\"]\n }\n },\n \"jwt\": {\n \"file\": environ[\"JWT_FILE\"],\n \"password\": environ[\"JWT_PASSWORD\"],\n \"algorithm\": environ[\"JWT_ALGORITHM\"],\n \"cookieName\": environ[\"JWT_COOKIENAME\"],\n \"cookieDomain\": environ[\"JWT_COOKIEDOMAIN\"],\n \"expiration\": int(environ[\"JWT_EXPIRATION\"])\n }\n }\n\n backend_dir_path = join(dir_path, \"backend\", \"build\", \"libs\")\n backend_file_name = \"conf.json\"\n saveJsonConfig(backend_dir_path, backend_file_name, backend_dic)\n\n logger.info(\"Save backend config file: %s\", join(backend_dir_path, backend_file_name))\n\ndef copy_backend_logback_config_files(dir_path):\n logback_file_name = \"logback.xml\"\n dst_path = join(dir_path, \"backend\", \"build\", \"generated\", \"resources\")\n util.copy_file(dir_path, dst_path, logback_file_name)\n logger.info(\"Save logback.xml file: %s\", join(dst_path, logback_file_name))\n\ndef copy_backend_jwt_jceks_files(dir_path):\n jceks_file_name = \"jwt.jceks\"\n dst_path = join(dir_path, \"backend\", \"build\", \"generated\", \"resources\")\n util.copy_file(dir_path, dst_path, jceks_file_name)\n logger.info(\"Save logback.xml file: %s\", join(dst_path, jceks_file_name))\n\n","sub_path":"scripts/conf.py","file_name":"conf.py","file_ext":"py","file_size_in_byte":4019,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"}
+{"seq_id":"621191738","text":"# The same to Q102, but reverse sub_res every 2 appending\nfrom typing import *\nfrom utils import TreeNode, build_tree, drawtree\nimport random\n\nclass Solution:\n def zigzagLevelOrder(self, root: Optional[TreeNode]) -> List[List[int]]:\n if root is None:\n return []\n res = []\n q = [(root, 0)]\n sub_res = []\n reverse = False\n last_depth = 0\n while len(q) > 0:\n node, depth = q[0]\n if depth != last_depth:\n last_depth = depth\n res.append(sub_res if not reverse else sub_res[::-1])\n sub_res = []\n reverse = not reverse\n sub_res.append(node.val)\n if node.left is not None:\n q.append((node.left, depth + 1))\n if node.right is not None:\n q.append((node.right, depth + 1))\n q = q[1:]\n if len(sub_res) > 0:\n res.append(sub_res if not reverse else sub_res[::-1])\n return res\n\nif __name__ == '__main__':\n sol = Solution()\n # inp_lst = [str(random.randint(-1000, 1000)) for _ in range(2000)]\n # inp = '[' + ','.join(inp_lst) + ']'\n inp = '[3,9,20,null,null,15,7]'\n root = TreeNode.build_by_str(inp)\n # root.draw()\n print(sol.zigzagLevelOrder(root))","sub_path":"source code/103. Binary Tree Zigzag Level Order Traversal.py","file_name":"103. Binary Tree Zigzag Level Order Traversal.py","file_ext":"py","file_size_in_byte":1298,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"}
+{"seq_id":"231340069","text":"from autoit_unpack import unpack_ea05, unpack_ea06\nfrom typing import Optional\nimport sys\nimport argparse\nimport logging\n\nlogging.basicConfig()\nlog = logging.getLogger()\n\n\ndef main() -> int:\n parser = argparse.ArgumentParser()\n parser.add_argument(\"file\", help=\"input binary\")\n parser.add_argument(\"--verbose\", \"-v\", action=\"store_true\")\n parser.add_argument(\n \"--ea\",\n default=\"guess\",\n choices=[\"EA05\", \"EA06\", \"guess\"],\n help=\"extract a specific version of AutoIt script (default: %(default)s)\",\n )\n\n args = parser.parse_args()\n if args.verbose:\n log.setLevel(logging.DEBUG)\n else:\n log.setLevel(logging.WARNING)\n\n if args.ea in (\"EA05\", \"guess\"):\n data = unpack_ea05(args.file)\n if data:\n print(data)\n if args.ea in (\"EA06\", \"guess\"):\n data = unpack_ea06(args.file)\n if data:\n print(data)\n\n\nif __name__ == \"__main__\":\n sys.exit(main())\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":965,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"}
+{"seq_id":"543554546","text":"\n## MADlib Tests for logistic regression\n## For learning tinc\n\nfrom madlib.src.template.madlib_test import MADlibTestCase\nfrom madlib.src.test_utils.utils import unique_string\nfrom madlib.src.test_utils.utils import string_to_array\nfrom madlib.src.test_utils.utils import relative_mean_squared_error\nfrom madlib.src.test_utils.utils import relative_l_inf_error\nfrom madlib.src.test_utils.utils import read_sql_result\nfrom madlib.src.test_utils.utils import parse_all_R_output\nfrom madlib.src.test_utils.utils import parse_single_SQL_output\nfrom madlib.src.test_utils.utils import _get_argument_expansion\nfrom madlib.src.test_utils.get_dbsettings import get_schema_testing\nimport os\nimport re\nimport sys\n\n# ------------------------------------------------------------------------\n# ------------------------------------------------------------------------\n# ------------------------------------------------------------------------\n\nclass clustered_variancemlogregrOutputTestCase (MADlibTestCase):\n \"\"\"\n Run templated SQL tests\n \"\"\"\n run_sql = \"\"\"\n set client_min_messages to error;\n drop table if exists {output_table};\n drop table if exists {output_table}_summary;\n select {schema_madlib}.clustered_variance_mlogregr(\n '{schema_testing}.{dataset}',\n '{output_table}',\n '{depvar}',\n '{indepvar}',\n '{clustvar}',\n 0,\n NULL, -- grouping col placeholder\n '{opt_params}',\n false);\n select category, coef, std_err, z_stats, p_values from {output_table};\n \"\"\"\n ans_dir = \"expected_output\"\n template_method = \"RobustMlogregr_{dataset}\"\n template_doc = \"This is for output tests of robust multinomial logistic regression.\"\n\n template_vars = {\n 'dataset': ['cl_mlogr_testdata_wi_with_nulls', 'cl_mlogr_testdata_wi'],\n 'output_table': unique_string(),\n 'depvar': 'y',\n 'indepvar': 'x',\n 'clustvar': 'cl',\n 'opt_params': 'max_iter=20,optimizer=irls,precision=0.0001'}\n\n template = run_sql\n MADlibTestCase.db_settings_[\"psql_options\"] = \"-x\"\n\n def validate(self, sql_resultfile, r_answerfile):\n keys = [\"category\", \"coef\",\n \"std_err\", \"z_stats\", \"p_values\"]\n return self.compare_outputs(sql_resultfile, r_answerfile, keys,\n grouping=[\"category\"], threshold=1e-4)\n\n\n# ------------------------------------------------------------------------\n# ------------------------------------------------------------------------\n# ------------------------------------------------------------------------\n# SQL Run for input test cases\ninput_test_sql = \"\"\"\n drop table if exists {tbl_output};\n select {schema_madlib}.clustered_variance_mlogregr(\n '{dataset}',\n '{tbl_output}',\n {y},\n {x},\n {clvar},\n {ref},\n NULL,\n {optimizer_params},\n {verbose}\n );\n \"\"\"\n\n# Add your datasets here\nALL_DATASETS = [\"cl_mlogr_testdata_wi\"]\n\nINPUT_TEST_DATASETS = \"cl_mlogr_testdata_wi\"\n# Maintain a dictionary of number of clustered variables per dataset\nNUM_CLUSTERED_VARIABLES = {\"cl_mlogr_testdata_wi\": 1}\n# Example\n# NUM_CLUSTERD_VARIABLES['dataset1'] = 1\n\n\n# ------------------------------------------------------------------------\n# ------------------------------------------------------------------------\n# ------------------------------------------------------------------------\n\nclass clustered_variancemlogregrInputTestCase (MADlibTestCase):\n \"\"\"\n Run input tests\n \"\"\"\n ans_dir = \"expected_input\"\n # use a different name convention from the above example\n template_method = \"clustered_mlogregr_input_{incr_}\"\n # doc does not seem to be important\n template_doc = \"This is for input tests of multinomial logistic clustered_variance regression \"\n schema_testing = get_schema_testing()\n arg_dict = {'tbl_output': [],\n 'dataset': [\"NULL\", \"''\", \"non_existing_input_table\",\n \"{0}.cl_mlogr_test_wi_category_0_null\".format(schema_testing),\n \"{0}.cl_mlogr_test_wi_category_1_null\".format(schema_testing),\n \"{0}.cl_mlogr_test_wi_category_3_null\".format(schema_testing)],\n 'x': [\"'wrong_dep_col_name'\", \"NULL\", \"''\"],\n 'y': [\"'wrong_indep_col_name'\", \"NULL\", \"''\"],\n 'clvar': [\"'wrong_clvar_col_name'\", \"''\"],\n 'ref': [\"NULL\", 2000, -1],\n 'optimizer_params': [\n \"'max_iter=0, optimizer=irls, tolerance=0.0001'\",\n \"'max_iter=-1, optimizer=irls, tolerance=0.0001'\",\n \"'max_iter=20, optimizer=unknown, tolerance=0.0001'\",\n \"'max_iter=20, optimizer=irls, tolerance=-1'\",\n \"'max_iter=20, optimizer=irls, tolerance=-1e-4'\"]\n }\n default_arg_dict = dict(\n tbl_output=unique_string(),\n dataset=schema_testing + \".cl_mlogr_testdata_wi\",\n x=\"'x'\",\n y=\"'y'\",\n clvar=\"'cl'\",\n ref=\"0\",\n optimizer_params=\"'max_iter=20, optimizer=irls, tolerance=0.0001'\",\n verbose=False\n )\n template_vars = _get_argument_expansion(arg_dict, default_arg_dict)\n template = input_test_sql\n","sub_path":"tests/clustered_mlogregr/clustered_mlogregrTest.py","file_name":"clustered_mlogregrTest.py","file_ext":"py","file_size_in_byte":5442,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"}
+{"seq_id":"29406183","text":"\"\"\"Tests for the quotes app.\"\"\"\n\nimport pytest\nfrom django.urls import reverse\n\nfrom modularhistory.constants.misc import ResponseCodes\n\nEXPECTED_N_SQL_QUERIES = 15\n\n\n@pytest.mark.django_db\ndef test_quotes(django_app, django_assert_max_num_queries):\n \"\"\"Test that the quotes page loads successfully.\"\"\"\n page = django_app.get(reverse('quotes:index'))\n assert page.status_code == ResponseCodes.SUCCESS\n page.mustcontain('')\n assert 'form' in page\n with django_assert_max_num_queries(EXPECTED_N_SQL_QUERIES):\n django_app.get(reverse('quotes:index'))\n","sub_path":"quotes/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":579,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"}
+{"seq_id":"16829928","text":"from django import forms\nfrom app_api.models import *\n\nclass PhotoForm(forms.ModelForm):\n\n class Meta:\n model = PostPhotos\n fields = '__all__'\n labels = {\n 'post_id': \"帖子id\",\n }\n widgets = {\n 'pic': forms.ClearableFileInput(attrs={'multiple': True}),\n }\n # img = forms.ImageField(widget=forms.ClearableFileInput(attrs={'multiple': True}))\n\nclass CommentForm(forms.ModelForm):\n\n class Meta:\n model = FloorComments\n exclude = ['replied_comment']\n error_messages = {\n '__all__': {'required': \"不能为空\"},\n 'create_time': {'invalid': \"格式错误\"},\n }\n\n\n replied_comment = forms.ChoiceField(label=\"回复\", help_text=\"0为1级评论, 填对应id表示回复对应评论\")\n\n def __init__(self, *args, **kwargs):\n super(CommentForm, self).__init__(*args, **kwargs)\n self.fields['replied_comment'].choices = tuple([(str(x), x) for x in FloorComments.objects.filter(display_status=True).values_list('id',flat=True)]+[(0,0)])\n self.initial['replied_comment'] = [0]\n\n def clean_replied_comment(self):\n reply_id = self.cleaned_data['replied_comment'] # 回复的id\n comment = self.cleaned_data['reply'] # 回复的楼层\n if int(reply_id) != 0:\n floor_comment = FloorComments.objects.get(id=reply_id)\n if floor_comment.reply != comment:\n raise forms.ValidationError(\"请保持回复的楼层一致\")\n return reply_id\n\n\nclass UserForm(forms.ModelForm):\n\n class Meta:\n model = UserAll\n fields = '__all__'\n error_messages = {\n 'email': {'invalid': \"格式错误\"},\n 'username': {'max_length': \"过长\", 'required': \"不能为空\"},\n 'password': {'max_length': \"过长\", 'required': \"不能为空\"},\n }\n\n\n def clean_username(self):\n raw_name = self.cleaned_data['username']\n if UserAll.objects.filter(username=raw_name):\n raise forms.ValidationError(\"用户名不能重复\")\n else:\n return raw_name","sub_path":"app_api/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":2121,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"}
+{"seq_id":"607563390","text":"'''\nCreated on 13-Oct-2017\n\n@author: netset\n'''\nfrom __future__ import unicode_literals\n\nfrom django.shortcuts import render, render_to_response\n\nfrom django.http import HttpResponse\n\nfrom django.contrib.auth import authenticate\n\nfrom appadmin.models import UserDetails, Category, Service, Deal, DealItem, RelBusinessService, UserImage, Commission, ForgetPasswordLog, Feedback\nfrom appadmin.serializers import UserDetailsSerializer, CategorySerializer, ServiceSerializer, DealSerializer, \\\n DealItemSerializer, RelBusinessServiceSerializer, UserImageSerializer, CommissionSerializer, ForgetPasswordLogSerializer, FeedbackSerializer\n\nfrom appadmin.serializers import UserSerializer\nfrom django.contrib.auth.models import Group, Permission, User\nfrom django.db.models import Avg\n\nimport datetime\nfrom rest_framework.views import APIView\nfrom rest_framework.decorators import api_view, schema, renderer_classes\nfrom django.db import transaction\nfrom django.views.decorators.csrf import ensure_csrf_cookie, csrf_exempt\nfrom rest_framework.response import Response\nimport pdb\nfrom django.contrib.auth import login, logout\nfrom django.http import HttpResponseRedirect\nfrom rest_framework.authtoken.models import Token\nimport json\nfrom django.shortcuts import redirect\nfrom datetime import datetime, timedelta\nimport base64, random, pytz\nfrom django.core.serializers.json import DjangoJSONEncoder\nfrom django.template.context import RequestContext\nfrom django.utils.http import urlsafe_base64_encode, urlsafe_base64_decode\nfrom django.conf import settings\nimport stripe\n\n\ndef index(request):\n try:\n token = request.session['token']\n request.session['token'] = token\n token1 = Token.objects.get(key=token)\n user = token1.user\n checkGroup = user.groups.filter(name='SuperAdmin').exists()\n if checkGroup:\n return render(request, \"superadmin/dashboard.html\", {\"token\":token})\n else:\n return redirect(\"setSessionNullForSuperAdmin\")\n except:\n return render(request, \"general/login.html\")\n\n\ndef Dashboard(request):\n token = request.POST['token']\n request.session['token'] = token\n token1 = Token.objects.get(key=token)\n user = token1.user\n checkGroup = user.groups.filter(name='SuperAdmin').exists()\n if checkGroup:\n return render(request, \"superadmin/dashboard.html\", {\"token\":token})\n else:\n return redirect(\"setSessionNullForSuperAdmin\")\n\n\ndef GetSuperAdminProfile(request):\n token = request.session['token']\n if checkAuthentication(token):\n token1 = Token.objects.get(key=token)\n userId = token1.user_id\n superAdminUser = UserDetails.objects.get(user_auth_id=userId)\n serializer = UserDetailsSerializer(superAdminUser)\n return render(request, \"superadmin/myProfile.html\", {'obj':json.dumps(serializer.data)})\n else:\n return redirect(\"setSessionNullForSuperAdmin\")\n \n\ndef EditAdminProfile(request):\n token = request.session['token']\n if checkAuthentication(token):\n token1 = Token.objects.get(key=token)\n userId = token1.user_id\n superAdminUser = UserDetails.objects.get(user_auth_id=userId)\n serializer = UserDetailsSerializer(superAdminUser)\n return render(request, \"superadmin/editProfile.html\", {'obj':json.dumps(serializer.data)})\n else:\n return redirect(\"setSessionNullForSuperAdmin\")\n\n\ndef MerchantsTemplate(request):\n token = request.session['token']\n if checkAuthentication(token):\n token1 = Token.objects.get(key=token)\n userId = token1.user_id\n \n return render(request, \"superadmin/merchants.html\", {})\n else:\n return redirect(\"setSessionNullForSuperAdmin\")\n\n\ndef ViewBusinessById(request):\n token = request.session['token']\n if checkAuthentication(token):\n businessObj = request.POST['viewBusinessId']\n businessDetails = json.loads(businessObj)\n return render(request, \"superadmin/viewBusiness.html\", {'businessId':businessDetails['id']})\n else:\n return redirect(\"setSessionNullForSuperAdmin\")\n\n\ndef SuperAdminDeals(request):\n token = request.session['token']\n if checkAuthentication(token):\n merchantUsers = UserDetails.objects.filter(role=2).filter(status=1).filter(isAccountVerified=1).values('id', 'firstName', 'email').order_by('-id')\n return render(request, \"superadmin/deals.html\", {'businessList':json.dumps(list(merchantUsers), cls=DjangoJSONEncoder)})\n else:\n return redirect(\"setSessionNullForSuperAdmin\")\n\n\ndef ViewBusinessDeal(request):\n token = request.session['token']\n if checkAuthentication(token):\n dealObj = request.POST['viewDealId']\n dealDetails = json.loads(dealObj) \n return render(request, \"superadmin/viewDeal.html\", {'dealId':dealDetails['id']})\n else:\n return redirect(\"setSessionNullForSuperAdmin\")\n\n\ndef BusinessReviewsAdmin(request):\n token = request.session['token']\n if checkAuthentication(token):\n token1 = Token.objects.get(key=token)\n userId = token1.user_id\n merchantUsers = UserDetails.objects.filter(role=2).values('id', 'firstName').order_by('-id')\n return render(request, \"superadmin/businessReviews.html\", {'businesses':json.dumps(list(merchantUsers), cls=DjangoJSONEncoder)})\n else:\n return redirect(\"setSessionNullForSuperAdmin\")\n\n\ndef Commissions(request):\n token = request.session['token']\n if checkAuthentication(token):\n ZDfeeObj = Commission.objects.latest('lastUpdated') \n serializerCommissions = CommissionSerializer(ZDfeeObj)\n jsonCommissions = json.dumps(serializerCommissions.data, cls=DjangoJSONEncoder)\n return render(request, \"superadmin/commissions.html\", {\"commissions\":jsonCommissions})\n else:\n return redirect(\"setSessionNullForSuperAdmin\")\n \n \ndef AddCardZipDeal(request):\n token = request.session['token']\n if checkAuthentication(token):\n \n return render(request, \"superadmin/adminCard.html\")\n else:\n return redirect(\"setSessionNullForSuperAdmin\")\n \n\ndef PaymentTransactions(request):\n token = request.session['token']\n if checkAuthentication(token):\n businesses = UserDetails.objects.filter(status=1).filter(role=2).filter(status=1).filter(isAccountVerified=1).values('id', 'firstName')\n jsonBusinesses = json.dumps(list(businesses))\n return render(request, \"superadmin/paymentTransactions.html\", {\"businesses\":jsonBusinesses})\n else:\n return redirect(\"setSessionNullForSuperAdmin\")\n\n\nfrom django.utils import timezone\n\n\ndef ValidateAdmin(request):\n receivedUid = request.GET['token']\n b64UserId = request.GET['uid']\n b64UserDId = urlsafe_base64_decode(b64UserId)\n userObj1 = UserDetails.objects.get(user_auth_id=b64UserDId)\n # result = default_token_generator.check_token(userObj1, receivedUid)\n # print str(result), \"result\"\n try:\n tokenValid = ForgetPasswordLog.objects.filter(code=receivedUid).filter(user_id=userObj1.id).latest(\n 'createdTime')\n nowTime = timezone.now().replace(microsecond=0)\n tokenExpiryTime = tokenValid.createdTime + timedelta(minutes=10)\n except Exception as e1:\n tokenValid = None\n if tokenValid is not None and tokenExpiryTime >= nowTime and tokenValid.codeUsed == 0:\n context = {'validlink': True, 'userId': b64UserId}\n return render(request, 'passwordReset/forgetPassword.html', context)\n\n else:\n context = {'validlink': False}\n return render(request, 'passwordReset/forgetPassword.html', context)\n\n\ndef checkAuthentication(token):\n try:\n token1 = Token.objects.get(key=token)\n user = token1.user\n checkGroup = user.groups.filter(name='SuperAdmin').exists()\n if checkGroup:\n return True\n else:\n return False\n except Exception as e:\n return False\n\n\ndef Logout(request):\n token = request.session['token']\n if checkAuthentication(token):\n token1 = Token.objects.get(key=token) \n user = token1.user \n if user is not None: \n user.auth_token.delete()\n \n del request.session['token']\n \n return HttpResponseRedirect(\"/appadmin/index/\")\n else:\n return redirect(\"setSessionNullForSuperAdmin\")\n \n\ndef SetSessionNullForSuperAdmin(request):\n if request.session.get('token', False):\n del request.session['token']\n return redirect(\"/appadmin/index\")\n\n","sub_path":"appadmin/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":8531,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"}
+{"seq_id":"398793141","text":"# Hint: You may not need all of these. Remove the unused functions.\nclass Ticket:\n def __init__(self, source, destination):\n self.source = source\n self.destination = destination\n\n\ndef reconstruct_trip(tickets, length):\n \"\"\"\n YOUR CODE HERE\n \"\"\"\n # route= starting_ticket(source= none)--middle_tickets---ending_ticket(destination= None)\n # Check which ticket is starting ticket( source should be None)\n\n\n cache = {}\n starting_ticket = None\n\n #Itereate through the length of the tickets findout which ticket is starting ticket\n # for ticket in tickets:\n for i in range(length):\n ticket = tickets[i]\n if ticket.source == \"NONE\":\n starting_ticket = ticket\n else:\n # ticket.source is not none, store them in cache to create the route\n cache[ticket.source]= ticket\n\n route = [None]* length\n i= 0\n\n while starting_ticket is not None: \n # if i ==length:\n # route.append(starting_ticket)\n if i< length: \n route[i] = starting_ticket.destination\n # repeat\n starting_ticket = cache.get(starting_ticket.destination)\n i +=1\n \n return route\n\n","sub_path":"hashtables/ex2/ex2.py","file_name":"ex2.py","file_ext":"py","file_size_in_byte":1245,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"}
+{"seq_id":"307153512","text":"import os\n\nfrom gaze_detection.definitions import PATH_UPLOADS\n\n\nclass Initializer:\n\n @staticmethod\n def initialize_db():\n pass\n\n @staticmethod\n def initialize_files():\n \"\"\"\n Ensure that all required files (eg. log files, data files) are there\n :return:\n \"\"\"\n required_file_paths = []\n\n # create files, if required\n for path_file in required_file_paths:\n if not os.path.exists(path_file):\n path_dir = os.path.dirname(path_file)\n if not os.path.isdir(path_dir):\n os.makedirs(path_dir)\n os.mknod(path_file)\n\n\n @staticmethod\n def initialize_folders():\n \"\"\"\n Ensure that all required folders are there\n :return:\n \"\"\"\n required_folder_paths = [PATH_UPLOADS]\n\n # create files, if required\n for path_folder in required_folder_paths:\n if not os.path.isdir(path_folder):\n os.makedirs(path_folder)\n\n\nif __name__ == '__main__':\n Initializer.initialize_db()\n Initializer.initialize_folders()\n Initializer.initialize_files()\n","sub_path":"gaze_detection/initializer.py","file_name":"initializer.py","file_ext":"py","file_size_in_byte":1145,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"}
+{"seq_id":"455914969","text":"from Models.NPSOM.Connections_Models import *\nfrom Parameters import *\n\n\ndef kohonen():\n connexion_matrix = np.empty((neuron_nbr, neuron_nbr, 5, 5))\n for y in range(neuron_nbr):\n for x in range(neuron_nbr):\n connexion_matrix[x, y] = kohonen_matrix\n return connexion_matrix\n\n\ndef small_worlds():\n connexion_matrix = np.empty((neuron_nbr, neuron_nbr, 5, 5))\n pattern = [[top_left, top_highway, top_right],\n [left_highway, kohonen_matrix, right_highway],\n [bottom_left, bottom_highway, bottom_right]]\n for y in range(neuron_nbr):\n for x in range(neuron_nbr):\n connexion_matrix[x, y] = pattern[y % 3][x % 3]\n return connexion_matrix\n\n\ndef acentric_small_worlds():\n connexion_matrix = np.empty((neuron_nbr, neuron_nbr, 5, 5))\n pattern = [[top_left, kohonen_matrix, top_right],\n [kohonen_matrix, kohonen_matrix, kohonen_matrix],\n [bottom_left, kohonen_matrix, bottom_right]]\n for y in range(neuron_nbr):\n for x in range(neuron_nbr):\n connexion_matrix[x, y] = pattern[y % 3][x % 3]\n return connexion_matrix\n\n\ndef fully_connected_small_worlds():\n connexion_matrix = np.empty((neuron_nbr, neuron_nbr, 5, 5))\n pattern = [[fc_top_left, fc_top, fc_top_right],\n [fc_left, fc, fc_right],\n [fc_bottom_left, fc_bottom, fc_bottom_right]]\n for y in range(neuron_nbr):\n for x in range(neuron_nbr):\n connexion_matrix[x, y] = pattern[y % 3][x % 3]\n return connexion_matrix\n\n\ndef star():\n connexion_matrix = np.empty((neuron_nbr, neuron_nbr, 5, 5))\n pattern = [[star_corner_left, star_top, star_corner_right],\n [star_left, kohonen_matrix, star_right],\n [star_corner_left, star_bottom, star_corner_right]]\n for y in range(neuron_nbr):\n for x in range(neuron_nbr):\n connexion_matrix[x, y] = pattern[y % 3][x % 3]\n return connexion_matrix\n\n\ndef random():\n connexion_matrix = np.empty((neuron_nbr, neuron_nbr, 5, 5))\n for y in range(neuron_nbr):\n for x in range(neuron_nbr):\n matrix = np.zeros((5, 5), dtype=int)\n for i in range(5):\n for j in range(5):\n if i == j:\n matrix[i, j] = 0\n elif i == 4 or j == 4:\n matrix[i, j] = 1 if np.random.random() < probability_neural_link else 0\n else:\n matrix[i, j] = 1 if np.random.random() < probability_link else 0\n connexion_matrix[x, y] = matrix\n return connexion_matrix\n","sub_path":"Models/NPSOM/Connections.py","file_name":"Connections.py","file_ext":"py","file_size_in_byte":2634,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"}
+{"seq_id":"238569095","text":"#!/usr/bin/env python3\n# ECB wrapper skeleton file for 50.042 FCS\n# 1003474\n# Alex W\n\nfrom present import *\nimport argparse\nimport math\nfrom tqdm import tqdm\n\nnokeybits = 80\nblocksize = 64\n\n\ndef get_block_binary_from_bytes(bytes_in):\n block_binary = ''\n for byte in bytes_in:\n block_binary += f\"{bin(byte).lstrip('0b'):0>8}\"\n\n return block_binary\n\n\ndef get_bytes_from_block_binary_int(binary_in):\n\n return binary_in.to_bytes(8, byteorder='big')\n\n\ndef ecb(infile, outfile, keyfile, mode):\n key = -1\n with open(keyfile, 'r') as f:\n key = get_hex_int(f.read())\n print(key)\n\n fin = open(infile, mode='rb')\n fout = open(outfile, mode='wb')\n\n infile_hex = fin.read()\n\n encrypted_blocks = b''\n\n if mode == 'e':\n\n for i in tqdm(range(math.ceil(len(infile_hex) / 8))):\n\n block_bytes = infile_hex[i * 8:i * 8 + 8]\n\n if len(block_bytes) < 8:\n block_bytes = block_bytes.ljust(8, b'0')\n\n block_binary_string = get_block_binary_from_bytes(block_bytes)\n block_binary_int = get_bin_int(block_binary_string)\n encrypted_block_int = present(block_binary_int, key)\n encrypted_block_bytes = get_bytes_from_block_binary_int(\n encrypted_block_int)\n\n encrypted_blocks += encrypted_block_bytes\n\n elif mode == 'd':\n\n for i in tqdm(range(math.ceil(len(infile_hex) / 8))):\n\n block_bytes = infile_hex[i * 8:i * 8 + 8]\n block_binary_string = get_block_binary_from_bytes(block_bytes)\n block_binary_int = get_bin_int(block_binary_string)\n encrypted_block_int = present_inv(block_binary_int, key)\n encrypted_block_bytes = get_bytes_from_block_binary_int(\n encrypted_block_int)\n\n if i == len(infile_hex) // 8 - 1:\n encrypted_block_bytes = encrypted_block_bytes.rstrip(b'0')\n\n encrypted_blocks += encrypted_block_bytes\n\n fout.write(encrypted_blocks)\n\n fin.close()\n fout.close()\n\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser(\n description='Block cipher using ECB mode.')\n parser.add_argument('-i', dest='infile', help='input file')\n parser.add_argument('-o', dest='outfile', help='output file')\n parser.add_argument('-k', dest='keyfile', help='key file')\n parser.add_argument('-m',\n dest='mode',\n help='mode, e for encryption, d for decryption')\n\n args = parser.parse_args()\n infile = args.infile\n outfile = args.outfile\n keyfile = args.keyfile\n mode = args.mode\n\n ecb(infile, outfile, keyfile, mode)\n","sub_path":"lab6/ecb.py","file_name":"ecb.py","file_ext":"py","file_size_in_byte":2662,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"}
+{"seq_id":"145975505","text":"__author__ = 'KoicsD'\n\n\n# Write a function translate() that will translate a text into \"rovarsprlket\" (Swedish for \"robber's language\").\n# That is, double every consonant and place an occurrence of \"o\" in between. For example, translate(\"this is fun\")\n# should return the string \"tothohisos isos fofunon\".\n\n\nalphabet = \"abcdefghijklmnopqrstuvwxyz\"\nvowels = \"aeiou\"\nconsonants = [l for l in alphabet if l not in vowels]\n\n\ndef translate(text: str):\n translation = \"\"\n for c in text:\n translation += c\n if c.lower() in consonants:\n if c.islower():\n translation += 'o' + c\n else:\n translation += 'O' + c\n return translation\n\n\nif __name__ == '__main__':\n assert translate(\"this is fun\") == \"tothohisos isos fofunon\"\n","sub_path":"Week5B/robbers_language.py","file_name":"robbers_language.py","file_ext":"py","file_size_in_byte":789,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"}
+{"seq_id":"18818812","text":"from django import forms\n#from django.contrib.auth.models import User\nfrom handouts.models import Section,SubSection,TextBlock,Proof,Theorem,Handout\nfrom randomtest.utils import newtexcode\n\n\nTHEOREMS = (\n ('Theorem','Theorem'),\n ('Corollary','Corollary'),\n ('Proposition','Proposition'),\n ('Lemma','Lemma'),\n ('Definition','Definition'),\n ('Example','Example'),\n ('Exercise','Exercise'),\n )\n\nPROOFS = (\n ('Proof','Proof'),\n ('Solution','Solution'),\n )\n\nclass HandoutForm(forms.ModelForm):\n class Meta:\n model = Handout\n fields = ('name',)\n widgets = {\n 'name': forms.TextInput(attrs={'class':'form-control'}),\n }\nclass SectionForm(forms.ModelForm):\n class Meta:\n model = Section\n fields = ('name',)\n widgets = {\n 'name': forms.TextInput(attrs={'class':'form-control'}),\n }\nclass SubsectionForm(forms.ModelForm):\n class Meta:\n model = SubSection\n fields = ('name',)\n widgets = {\n 'name': forms.TextInput(attrs={'class':'form-control'}),\n }\nclass TextBlockForm(forms.ModelForm):\n class Meta:\n model = TextBlock\n fields = ('text_code',)\n widgets = {\n 'text_code': forms.Textarea(attrs={'style':'min-width: 100%', 'rows': 15,'id' : 'codetext'}),\n }\n def __init__(self, *args, **kwargs):\n super(TextBlockForm, self).__init__(*args, **kwargs)\n def save(self,commit=True):\n instance = super(TextBlockForm, self).save(commit=False)\n instance.text_display = newtexcode(instance.text_code,'textblock_'+str(instance.pk),\"\")\n if commit:\n instance.save()\n return instance\n\nclass TheoremForm(forms.ModelForm):\n class Meta:\n model = Theorem\n fields = ('prefix','name','theorem_code',)\n widgets = {\n 'theorem_code': forms.Textarea(attrs={'style':'min-width: 100%', 'rows': 15,'id' : 'codetext'}),\n 'prefix': forms.Select(choices=THEOREMS, attrs={'class':'form-control'}),\n 'name': forms.TextInput(attrs={'class':'form-control'}),\n }\n def __init__(self, *args, **kwargs):\n super(TheoremForm, self).__init__(*args, **kwargs)\n self.fields['name'].required=False\n def save(self,commit=True):\n instance = super(TheoremForm, self).save(commit=False)\n instance.theorem_display = newtexcode(instance.theorem_code,'theoremblock_'+str(instance.pk),\"\")\n if commit:\n instance.save()\n return instance\n\nclass ProofForm(forms.ModelForm):\n class Meta:\n model = Proof\n fields = ('prefix','proof_code',)\n widgets = {\n 'proof_code': forms.Textarea(attrs={'style':'min-width: 100%', 'rows': 15,'id' : 'codetext'}),\n 'prefix': forms.Select(choices=PROOFS,attrs={'class':'form-control'})\n }\n def __init__(self, *args, **kwargs):\n super(ProofForm, self).__init__(*args, **kwargs)\n def save(self,commit=True):\n instance = super(ProofForm, self).save(commit=False)\n instance.proof_display = newtexcode(instance.proof_code,'proofblock_'+str(instance.pk),\"\")\n if commit:\n instance.save()\n return instance\n\nclass ImageForm(forms.Form):\n image = forms.ImageField()\n\n\n","sub_path":"handouts/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":3330,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"}
+{"seq_id":"644925557","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 ]\n\n operations = [\n migrations.CreateModel(\n name='StudentTool',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, primary_key=True, auto_created=True)),\n ('rating', models.IntegerField(verbose_name='Rating', max_length=1, default=1, choices=[(1, 'Theoretical'), (2, 'Basics'), (3, 'Familiar'), (4, 'Experienced'), (5, 'Professional'), (6, 'Specialist')])),\n ('status', models.CharField(verbose_name='Status', max_length=25, default='new', choices=[('new', 'New'), ('confirmed_interview', 'Confirmed in Interview'), ('confirmed_project', 'Confirmed in Project')])),\n ],\n options={\n 'verbose_name': 'Student Tool',\n 'verbose_name_plural': 'Student Tools',\n 'db_table': 'student_tool',\n },\n bases=(models.Model,),\n ),\n migrations.CreateModel(\n name='Tool',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, primary_key=True, auto_created=True)),\n ('name', models.CharField(verbose_name='Name', max_length=255, unique=True)),\n ('user_created', models.BooleanField(verbose_name='Created by a student', default=False)),\n ('created', models.DateTimeField(verbose_name='Created at', auto_now_add=True)),\n ],\n options={\n 'verbose_name': 'Tool',\n 'verbose_name_plural': 'Tools',\n 'db_table': 'tool',\n },\n bases=(models.Model,),\n ),\n migrations.CreateModel(\n name='ToolCategory',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, primary_key=True, auto_created=True)),\n ('name', models.CharField(max_length=100, unique=True)),\n ],\n options={\n 'verbose_name': 'Tool Category',\n 'verbose_name_plural': 'Tool Categories',\n 'db_table': 'tool_category',\n },\n bases=(models.Model,),\n ),\n migrations.AddField(\n model_name='tool',\n name='category',\n field=models.ForeignKey(blank=True, null=True, to='motius_tool.ToolCategory'),\n preserve_default=True,\n ),\n ]\n","sub_path":"motius_tool/migrations/0001_initial.py","file_name":"0001_initial.py","file_ext":"py","file_size_in_byte":2552,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"}
+{"seq_id":"445922501","text":"# bot.py\nimport socket, select, string, sys\nimport os\nimport threading\nimport time\nimport re\nimport asyncio, concurrent.futures\n\nimport discord\nfrom dotenv import load_dotenv\n\nload_dotenv()\ntoken = os.getenv('DISCORD_TOKEN')\ndiscord_channel = int(os.getenv('DISCORD_CHANNEL'))\nmud_username = os.getenv('MUD_USERNAME')\nmud_password = os.getenv('MUD_PASSWORD')\nmud_host = os.getenv('MUD_HOST')\nmud_port = int(os.getenv('MUD_PORT'))\nooc_command = os.getenv('OOC_COMMAND')\n\nlogged_in = False\ngetting_who = False\n\n#for passing messages from mud -> discord\nmessage_queue = asyncio.Queue()\n\nclient = discord.Client()\ns = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n\ndef telnet(client):\n global s\n pool = concurrent.futures.ThreadPoolExecutor()\n channel = None\n global getting_who, logged_in\n s.settimeout(2)\n\n # connect to remote host\n try :\n s.connect((mud_host, mud_port))\n except :\n print('Unable to connect')\n os._exit()\n\n print('Connected to remote host')\n\n reconnect = False\n while 1:\n time.sleep(1)\n if reconnect:\n logged_in = False\n print(\"Reconnecting\")\n # connect to remote host\n try :\n s.connect((mud_host, mud_port))\n except :\n print('Unable to connect')\n s.close()\n s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n continue\n reconnect = False\n\n socket_list = [sys.stdin, s]\n \n # Get the list sockets which are readable\n read_sockets, write_sockets, error_sockets = select.select(socket_list , [], [])\n who_text = \"\"\n for sock in read_sockets:\n #incoming message from remote server\n if sock == s:\n data = sock.recv(4096)\n if not data:\n print('Connection closed')\n reconnect = True\n s.close()\n break\n else:\n data = data.decode('utf-8', 'backslashreplace')\n\n if getting_who:\n print(\"Getting who in loop\")\n print(data.strip())\n who_text = data.strip()\n if \"displayed.\" in data or \"[--]>\" in data or \"end>>\" in data:\n print(\"found end of who\")\n message_queue.put_nowait(\"```\" + who_text.replace(\"end>>\", \"\") + \"```\")\n who_text = \"\"\n getting_who = False\n continue\n if \"/ooc\" in data:\n data = data.strip()\n user = data.split('[0m ')[1].split(']')[0]\n if user.lower() != mud_username.lower():\n send_text = \"**\" + user + \"**: \" + data[data.find(':')+2:].split('\\n')[0]\n print(\"sending to discord: \" + send_text)\n message_queue.put_nowait(send_text)\n if \"(OOC)\" in data:\n data = data.strip()\n user = data[1:].split(']')[0]\n if user.lower() != mud_username.lower():\n send_text = \"**\" + user + \"**: \" + data[data.find('\"')+1:-1]\n print(\"sending to discord: \" + send_text)\n message_queue.put_nowait(send_text)\n elif \"has entered the game\" in data:\n data = data.strip()\n user = data.split('[ ')[1].split(' has entered')[0]\n send_text = \"**\" + user + \"** has connected\"\n print(\"Connection: \" + send_text)\n message_queue.put_nowait(send_text)\n elif \"CONNLOG\" in data and \"has connected\" in data:\n data = data.strip()\n user = data.split(']')[1].split('[')[0][1:-1]\n send_text = \"**\" + user + \"** has connected\"\n print(\"Connection: \" + send_text)\n message_queue.put_nowait(send_text)\n elif not logged_in and (\"your handle\" in data or \"Enter your character\" in data):\n print(\"your handle\")\n s.send((mud_username + \"\\n\").encode())\n elif not logged_in and (\"Welcome back. Enter your password\" in data or \"Password:\" in data):\n s.send((mud_password + \"\\n\").encode())\n logged_in = True\n elif \"PRESS RETURN\" in data or \"Press ENTER\" in data:\n s.send(\"\\n\".encode())\n elif \"Enter the game\" in data:\n s.send(\"1\\n\".encode())\n\n@client.event\nasync def on_message(message):\n global getting_who, s\n if message.author == client.user:\n return\n if message.channel.id != discord_channel:\n return\n if \"!who\" in message.content:\n getting_who = True\n print(\"Getting who list\")\n s.send(\"who\\n\".encode())\n return\n send_text = ooc_command + \" Discord: \" + message.author.display_name + \" says \" + message.content + \"\\n\"\n print(\"sending to mud: \" + send_text)\n s.send(send_text.encode())\n\n@client.event\nasync def on_ready():\n print(f'{client.user} has connected to Discord!')\n channel = client.get_channel(discord_channel)\n for guild in client.guilds:\n print(\n f'{client.user} is connected to the following guild:\\n'\n f'{guild.name}(id: {guild.id})'\n )\n while True:\n await asyncio.sleep(1)\n try:\n message = message_queue.get_nowait()\n except asyncio.QueueEmpty:\n continue\n\n print(f\"Sending message to Discord: '{message}'\")\n await channel.send(message)\n\nx = threading.Thread(target=telnet, args=(client,))\nx.start()\n\nclient.run(token)\n\n","sub_path":"discordbot/bot.py","file_name":"bot.py","file_ext":"py","file_size_in_byte":6058,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"}
+{"seq_id":"644676635","text":"import numpy as np\nfrom functools import partial\nimport scipy.optimize\nfrom scipy.optimize.nonlin import NoConvergence\nfrom mpl_toolkits.mplot3d import Axes3D\nfrom matplotlib.patches import FancyArrowPatch\nfrom mpl_toolkits.mplot3d import proj3d\n\nclass Arrow3D(FancyArrowPatch):\n def __init__(self, xs, ys, zs, *args, **kwargs):\n FancyArrowPatch.__init__(self, (0,0), (0,0), *args, **kwargs)\n self._verts3d = xs, ys, zs\n\n def draw(self, renderer):\n xs3d, ys3d, zs3d = self._verts3d\n xs, ys, zs = proj3d.proj_transform(xs3d, ys3d, zs3d, renderer.M)\n self.set_positions((xs[0],ys[0]),(xs[1],ys[1]))\n FancyArrowPatch.draw(self, renderer)\n \n\ndef xv(phi,d0,phi0,theta,qoverp,z0):\n\treturn d0*np.cos(phi0+np.pi/2.0)+(np.sin(theta)/(2.0*qoverp*0.299792))*(np.cos(phi+np.pi/2.0)-np.cos(phi0+np.pi/2.0))\n\ndef yv(phi,d0,phi0,theta,qoverp,z0):\n\treturn d0*np.sin(phi0+np.pi/2.0)+(np.sin(theta)/(2.0*qoverp*0.299792))*(np.sin(phi+np.pi/2.0)-np.sin(phi0+np.pi/2.0))\n\ndef zv(phi,d0,phi0,theta,qoverp,z0):\n\treturn z0-(np.cos(theta)/(2.0*qoverp*0.299792))*(phi-phi0)\n\n\n\n\ndef rotationMatrix(jet_axis,des_directon):\n\n\tnorm_des_dir = des_directon/np.linalg.norm(des_directon)\n\n\taxis = np.cross(jet_axis,norm_des_dir)\n\n\tdotprod = np.dot(jet_axis,norm_des_dir)\n\n\tangle = np.arccos(min([dotprod,1.0]))\n\n\tr = np.zeros((3,3))\n\n\n\tif angle < 0.00001:\n\t\tr[0][0] = 1.0\n\t\tr[1][1] = 1.0\n\t\tr[2][2] = 1.0\n\n\t\treturn np.array(r)\n\n\tca = np.cos(angle)\n\tsa = np.sin(angle)\n\taxislength = np.sqrt(axis[0]**2+axis[1]**2+axis[2]**2)\n\tdx = axis[0]/axislength\n\tdy = axis[1]/axislength\n\tdz = axis[2]/axislength\n\n\n\tr[0][0] = ca+(1-ca)*dx*dx\n\tr[0][1] = (1-ca)*dx*dy-sa*dz\n\tr[0][2] = (1-ca)*dx*dz+sa*dy\n\n\tr[1][0] = (1-ca)*dy*dx+sa*dz\n\tr[1][1] = ca+(1-ca)*dy*dy\n\tr[1][2] = (1-ca)*dy*dz-sa*dx\n\n\tr[2][0] = (1-ca)*dz*dx-sa*dy\n\tr[2][1] = (1-ca)*dz*dy+sa*dx\n\tr[2][2] = ca+(1-ca)*dz*dz\n\n\treturn np.array(r)\n\ndef build_track_trajectory(track,true_range=300):\n\tphi0,theta,d0,z0,qoverp = track\n\t\n\t\n\tphiV = (phi0-1.0*np.sign(qoverp)*np.pi/320.0)\n\txv_end = xv(phiV,d0,phi0,theta,qoverp,z0)\n\tyv_end = yv(phiV,d0,phi0,theta,qoverp,z0)\n\tzv_end = zv(phiV,d0,phi0,theta,qoverp,z0)\n\n\tdistance = np.linalg.norm([xv_end,yv_end,zv_end])\n\n\n\tfraction_to_target = (float(2.0*true_range)/distance)\n\n\tphiFinal = (phi0-1.0*np.sign(qoverp)*fraction_to_target*(np.pi/320.0))\n\n\tnpoints = 800\n\n\ttrack_trajectory = []\n\t\n\tfor phiV in np.linspace(phi0,phiFinal,npoints):\n\t\txV = xv(phiV,d0,phi0,theta,qoverp,z0)\n\t\tyV = yv(phiV,d0,phi0,theta,qoverp,z0)\n\t\tzV = zv(phiV,d0,phi0,theta,qoverp,z0)\n\t\t\n\t\ttrack_trajectory.append([xV,yV,zV])\n\t\t\n\treturn np.array(track_trajectory)\n\ndef plot_track(ax, track,rotMatrix,track_color):\n\t\n\trotated_track = np.array( [np.dot(rotMatrix,[x,y,z]) for x,y,z in track] )\n\t\n\tlinestyle='--'\n\n\tax.plot(rotated_track[:,0],rotated_track[:,1],c=track_color,linestyle=linestyle)\n\n\ndef G(data, phi):\n\td0, z0 , phi0,theta,qoverp, rotMatrix, z_target = data\n\t\n\txV = xv(phi,d0,phi0,theta,qoverp,z0)\n\tyV = yv(phi,d0,phi0,theta,qoverp,z0)\n\tzV = zv(phi,d0,phi0,theta,qoverp,z0)\n\tx,y,z = np.dot(rotMatrix,[xV,yV,zV])\n\t\n\treturn abs(z-z_target)\n\n\ndef get_phi(target_z,track,rotMatrix):\n\td0, z0 , phi0,theta,qoverp = track\n\t\n\tdata = (d0, z0 , phi0,theta,qoverp,rotMatrix,target_z)\n\tG_partial = partial(G, data)\n\t\n\ttry:\n\t\tphi_z = scipy.optimize.broyden1(G_partial,phi0, f_tol=1e-3)\n\texcept NoConvergence as e:\n\t\tphi_z = e.args[0]\n\n\treturn float(phi_z)\n\ndef get_xy_p(phi,track,rotMatrix):\n\td0, z0 , phi0,theta,qoverp = track\n\n\tp3 = abs(1.0/qoverp)\n\n\txV = xv(phi,d0,phi0,theta,qoverp,z0)\n\tyV = yv(phi,d0,phi0,theta,qoverp,z0)\n\tzV = zv(phi,d0,phi0,theta,qoverp,z0)\n\t\n\tpVx = xV+np.cos(phi)*np.sin(theta)\n\tpVy = yV+np.sin(phi)*np.sin(theta)\n\tpVz = zV+np.cos(theta)\n\t\n\tx,y,z = np.dot(rotMatrix,[xV,yV,zV])\n\tpx,py,pz = np.dot(rotMatrix,[pVx,pVy,pVz])\n\n\tpx,py,pz = px-x,py-y,pz-z\n\n\treturn (x,y),(px,py,pz),p3\n\n","sub_path":"helper_functions/track_trajectory_functions.py","file_name":"track_trajectory_functions.py","file_ext":"py","file_size_in_byte":3883,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"}
+{"seq_id":"14257594","text":"\"\"\"\nNaive implementation of Dijkstra's shortest-path algorithm. This implementation\nserves as a \"conversation starter\" to justify the need for using a min-heap, as\nwell as a more structured approach to capturing and representing a graph.\n leo@cs.luc.edu\n\"\"\"\n\n# The graph is modeled as a dict of dicts. The outer dict's key-value pairs\n# are the graph vertices and their adjacency lists. The adjacency lists are\n# dicts too, whose key-value pairs are the adjacent vertices and the length\n# of the edge to them. For example, the key-value pair:\n# 'A': { 'B':1, 'C':3 },\n# means that vertex A has two adjacent vertices (B and C) and the lengths\n# of the edges are 1 and 3 for A-B and A-C respectively.\n\ngraph = {\n 'A': { 'B':1, 'C':3 },\n 'B': { 'D':3},\n 'C': { 'D':1, 'F':8},\n 'D': { 'E':1},\n 'E': { 'F':2},\n 'F': {}\n}\n# TRY a different graph of your own. In the dict above, each line represents a vertex and\n# its adjacency list:\n# 'A': { 'B':1, 'C':3 }\n# --- ----------------\n# | |\n# | +----------> Node B is adjacent to A and the edge A->B has length 1\n# This node Node C is adjacent to A and the edge A->C has length 3\n# has an\n# adjacency\n# list described =======================================================\n# by dict: | You may add another vertex adjacent to A; let's say |\n# { 'B':1, 'C':3 } | that you want to add a vertex called K with an edge |\n# This adjacency | from A->K of length 5. The dict entry for A will |\n# dict (ok, list) | become: |\n# describes all the | 'A': { 'B':1, 'C':3, 'K':5 } |\n# outgoing edges | ^^^^^ |\n# emanating from | You will also need to add an entry for node K in |\n# vertex A. | the adjacency dict: |\n# | 'K': {} |\n# | This says that vertex K has no outgoing edges. You |\n# | may add outgoing edges for K if you wish, as long |\n# | you pay attention to not create a cyclical graph. |\n# =======================================================\n\n\n\n# Algorithm input: a graph in the dict-of-dicts representation and a starting vertex\n# Algorithm output: a dict called distance, showing the distance of each vertex from the starting vertex.\n\nstarting_vertex = 'C' # This can be any vertex in the graph. *** TRY A DIFFERENT VALUE AND SEE WHAT HAPPENS.\n\nunvisited = set() # A set to contain all unvisited vertices\ndistance = {} # This will be the final product, listing distances from the starting vertex\n\nimport sys # we need this to access the value of the largest integer available in python\ninfinity = sys.maxsize; # The largest number available to represent infinity\n\n# At the beginning we need to mark all vertices as not visited. We add them to the set unvisited.\n# Also, we need to assign a distance value to them: 0 for the starting vertex, infinity for the rest.\nfor vertex in graph.keys():\n unvisited.add(vertex)\n if vertex == starting_vertex:\n distance[vertex] = 0;\n else:\n distance[vertex] = infinity\n\n# Set up the main loop of the algorithm\ncurrent_vertex = starting_vertex\ncontinue_loop = True\n\n# The main loop\nwhile continue_loop:\n neighbors = graph[current_vertex] # Find the adjacent vertices of the current vertex\n for neighbor in neighbors: # Look at each adjacent vertex\n if neighbor in unvisited: # If it has not been visited before\n # find its distance from the starting vertex through the current vertex\n new_distance = distance[current_vertex] + neighbors[neighbor]\n # ------------------------ -------------------\n # distance of current # length of edge\n # vertex from the # from current vertex\n # starting vertex # to its adjacent vertex\n if new_distance < distance[neighbor]: # If computed distance less than what's stored\n distance[neighbor] = new_distance # Store newly computed distance for this adjacent node\n unvisited.remove(current_vertex) # Remove current vertex from unvisited.\n # select the next current vertex\n min = infinity\n for vertex in unvisited: # Searc through every vertex in unvisited\n if distance[vertex] < min: # Looking of the one with the smallest distance from the starting vertex\n current_vertex = vertex # Make it the current vertex\n min = distance[vertex] # And update the value of the shortest distance\n # At this point we have either a new current vertex (to continue the while loop) or\n # the set of unvisited vertices is empty, or if there are still vertices in it, they\n # remain at infinite distance from the starting vertex.\n if len(unvisited)==0 or min==infinity: # If no more unvisited vertices, or remaining ones at infinite distance\n continue_loop = False # Cause while loop to end\n\n# Display results\nprint(\"\\nDistances from starting point\",starting_vertex)\nfor vertex in distance.keys():\n print(\"\\tTo vertex\", vertex,\": \", end='')\n if distance[vertex] == infinity:\n print(u'\\u221E') # Unicode for infinity symbol 221E\n else:\n print(distance[vertex])","sub_path":"Dijkstra shortest-path/naive_dijkstra.py","file_name":"naive_dijkstra.py","file_ext":"py","file_size_in_byte":5697,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"}
+{"seq_id":"179847579","text":"class Block():\n\n\tdef __init__(self, prev, timestamp, owner):\n\t\tself.prev = prev\n\t\tself.timestamp = timestamp\n\t\tself.owner = owner\n\t\t# self.data = data \t\t# Assume there's no data for simplicity\n\t\tself.ID = 0\t\t\t # Attributes assigned by the chain upon committing\n\t\tself.height = 0\n\t\tself.score = 0\n\t\t# self.nonce = 0\t\t# Assume the proof of work is always valid for simplicity\n\t\t# self.hash = \"\"","sub_path":"old/old_model_2/block.py","file_name":"block.py","file_ext":"py","file_size_in_byte":395,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"}
+{"seq_id":"334583571","text":"#!usr/bin/env python\nimport unittest\nfrom typing import Optional\n\n\nclass Node(object):\n def __init__(self, node: int, next_node=None):\n self.data = node\n self._next = next_node\n\n def __repr__(self):\n return str(self.data)\n\n\nclass SingleLinkList(object):\n def __init__(self):\n self.head = None\n\n def find_by_value(self, value):\n node = self.head\n while node._next and node.data != value:\n node = node._next\n if value == node.data:\n return node\n\n def find_by_index(self, index: int) -> Optional[Node]:\n pointer = self.head\n position = 0\n while position < index and pointer:\n pointer = pointer._next\n position += 1\n return pointer\n\n def insert_value_to_head(self, value):\n node = Node(value)\n self.insert_node_to_head(node)\n\n def insert_node_to_head(self, node: Node):\n node._next = self.head\n self.head = node\n\n def insert_value_after(self, node: Node, value: int):\n new_node = Node(value)\n self.insert_node_after(new_node, node)\n\n def insert_node_after(self, new_node: Node, node: Node):\n new_node._next = node._next\n node._next = new_node\n\n def insert_value_before(self, node: Node, value: int):\n new_node = Node(value)\n self.insert_node_before(node, new_node)\n\n def insert_node_before(self, node: Node, new_node: Node):\n if not self.head or not node or not new_node:\n return\n if self.head == node:\n self.insert_node_to_head(new_node)\n current = self.head\n while current._next != node:\n current = current._next\n if not current._next:\n return\n new_node._next = node\n current._next = new_node\n\n def delete_by_node(self, node: Node):\n if not self.head or not node:\n return\n if node is self.head:\n self.head = self.head._next\n return\n pro_node = current = self.head\n while current != node:\n pro_node = current\n current = current._next\n if pro_node._next == node:\n pro_node._next = pro_node._next._next\n\n def __repr__(self) -> str:\n values = []\n current = self.head\n while current:\n values.append(current.data)\n current = current._next\n return ' -> '.join(str(value) for value in values)\n\n def __iter__(self):\n node = self.head\n while node:\n yield node.data\n node = node._next\n\n\nclass TestDict(unittest.TestCase):\n\n def setUp(self) -> None:\n self.link = SingleLinkList()\n for i in range(20):\n self.link.insert_value_to_head(i)\n\n def test_init(self):\n self.assertEqual(str(self.link),\n '19 -> 18 -> 17 -> 16 -> 15 -> 14 -> 13 -> 12 -> 11 -> '\n '10 -> 9 -> 8 -> 7 -> 6 -> 5 -> 4 -> 3 -> 2 -> 1 -> 0')\n\n def test_find_by_value(self):\n node5 = self.link.find_by_value(5)\n self.assertEqual(node5.data, 5)\n\n def test_find_last_by_value(self):\n node0 = self.link.find_by_value(0)\n self.assertEqual(node0.data, 0)\n\n def test_find_by_index(self):\n node18 = self.link.find_by_index(1)\n self.assertEqual(18, node18.data)\n node0 = self.link.find_by_index(19)\n self.assertEqual(0, node0.data)\n node_none = self.link.find_by_index(20)\n self.assertIsNone(node_none)\n\n def test_delete_node(self):\n node10 = self.link.find_by_value(10)\n self.link.delete_by_node(node10)\n self.assertEqual(str(self.link),\n '19 -> 18 -> 17 -> 16 -> 15 -> 14 -> 13 -> 12 -> 11 -> '\n '9 -> 8 -> 7 -> 6 -> 5 -> 4 -> 3 -> 2 -> 1 -> 0')\n\n def test_delete_head_node(self):\n self.link.delete_by_node(self.link.head)\n self.assertEqual(str(self.link),\n '18 -> 17 -> 16 -> 15 -> 14 -> 13 -> 12 -> 11 -> '\n '10 -> 9 -> 8 -> 7 -> 6 -> 5 -> 4 -> 3 -> 2 -> 1 -> 0')\n\n def test_delete_last_node(self):\n last_node = self.link.find_by_value(0)\n self.link.delete_by_node(last_node)\n self.assertEqual(str(self.link),\n '19 -> 18 -> 17 -> 16 -> 15 -> 14 -> 13 -> 12 -> 11 -> '\n '10 -> 9 -> 8 -> 7 -> 6 -> 5 -> 4 -> 3 -> 2 -> 1')\n\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"algorithm/python/single_link_list.py","file_name":"single_link_list.py","file_ext":"py","file_size_in_byte":4503,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"}
+{"seq_id":"606531529","text":"\n\n#calss header\nclass _PREQUEL():\n\tdef __init__(self,): \n\t\tself.name = \"PREQUEL\"\n\t\tself.definitions = [u'a film, book, or play that develops the story of an earlier film, etc. by telling you what happened before the events in the first film, etc.: ']\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/_prequel.py","file_name":"_prequel.py","file_ext":"py","file_size_in_byte":425,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"}
+{"seq_id":"634943372","text":"# -*- coding: utf-8 -*-\n\"\"\"\nin-situ TEM Toolbox - Data process \n\nAssembles of functions related to movie input output\n\nExample:\n \n import insitu_DP as DP\n IO.f2tif(path,1)\n\nCreated on Tue Jun 11 10:25:25 2019\n@author: Mona\n\"\"\"\nimport numpy as np\n\ndef readcsvCol(path,col):\n \"\"\"\n Function to read csv rol into array \n Inputs: file path; col number\n Output: 1D np array\n \n Example: \n x = readcsvCol(path,1)\n \"\"\"\n import csv\n x=[]\n with open(path,'r') as csvfile:\n plots = csv.reader(csvfile, delimiter=',')\n for row in plots:\n if row[col]=='':\n x.append(np.nan)\n else:\n x.append(float(row[col]))\n# plt.plot(x,y) #to check if the read result is correct\n return x\ndef readcsv(path,col_list):\n \"\"\"\n Function to read csv rol into array \n Inputs: file path; col number list\n Output: 1D np array\n \n Example: \n x = readcsv(path,[0:3])\n \"\"\"\n# w= len(col_list)\n x=readcsvCol(path,col_list[0])\n# l = len(x)\n D=np.zeros((len(x),len(col_list)))\n i=0\n for col in col_list:\n \n x=readcsvCol(path,col)\n D[:,i]=x\n i=i+1\n# D = [D, x]\n return D\n\n \ndef writeCSV(pathout,data):\n# import csv\n import numpy as np\n# (length,width)=np.shape(data)\n# np.savetxt(pathout, data, fmt='%1.4d', delimiter=\",\") \n np.savetxt(pathout, data, fmt='%.4f', delimiter=\",\") \n \ndef plot2ani(x,y,outpath,label,w=800,h=600,fps=10,dpi=72,tl_size=20,c='r'):\n \"\"\"\n Function to make plot into animation \n Inputs: \n data: x y; \n Movie setting: size: w,h ;\n fps; savepath\n label: ['xlabel','ylabel'] str array\n tl_size: title font size\n c: color of the plot line\n dpi: dpi for screen : 72 for 4k screen, 96 for 1080p screen\n Output: mp4 movie\n \n Example: \n plot2ani(x,y,w,h,fps,outpath,dpi,tl_size,'r')\n\n \"\"\"\n \n import matplotlib.pyplot as plt\n import matplotlib.animation as animation\n interV=1000/fps #time interval for each frame: ms\n# w_in=w/dpi\n# h_in=h/dpi\n fig, ax = plt.subplots(figsize=(w/dpi, h/dpi))#figsize unit: inch\n plt.rcParams.update({'font.size': tl_size})\n plt.xlabel(label[0])#Change xy label if needed\n plt.ylabel(label[1])\n l=plt.plot(x,y,'grey') #For inital plot\n redLine, = plt.plot(x[:0],y[:0],color=c, lw=3)\n time_text = ax.text(5,7,str(y[0])+'°',fontsize=20)\n# plt.text(5, 7, str(y[0],fontsize=20))\n def animate(i):\n redLine.set_data(x[:i], y[:i])\n# plt.text(5, 7, str(y[i])+'°',fontsize=20) # Text is overlapping with previous frames\n time_text.set_text(str(round(y[i],1))+'°') \n# print(str(i)/len(x))\n return tuple([redLine,]) + tuple([time_text])\n \n plt.tight_layout() #To avoid boarder\n # create animation using the animate() function\n ani = animation.FuncAnimation(fig, animate, frames=len(x), \\\n interval=interV, blit=True, repeat=True)\n ani.save(outpath)\n plt.show()\n \ndef getintensity(x,y,disk,img):\n \"\"\"\n Function to get intensity of a disk region at point (x,y) \n Inputs:\n x,y: coordinates of the detection point\n disk: size of pixels for detection region\n img: 2D grayscale image\n \"\"\"\n x_l=int(x-disk)\n x_r=int(x+disk)\n y_l=int(y-disk)\n y_r=int(y+disk)\n intensity=int(np.mean(img[y_l:y_r,x_l:x_r]))\n return intensity\n \n\ndef findconnectingpoints(points,startpoint,r,level):\n \"\"\"\n FUnction for find all surrounding points within distance r betwwen each other from startpoint\n return: index of all connected points\n \"\"\"\n from scipy import spatial\n tree = spatial.cKDTree(points, leafsize=30)\n idx =tree.query_ball_point(startpoint,r)\n i=0\n while i Generator[Sequence, None, None]:\n \"\"\"Yield successive n-sized chunks from l.\"\"\"\n for i in range(0, len(my_list), chuck_size):\n yield my_list[i : i + chuck_size]\n\n\ndef aws_get_object(\n bucket: str,\n key: str,\n request_pays: bool = False,\n client: boto3_session.client = None,\n) -> bytes:\n \"\"\"AWS s3 get object content.\"\"\"\n if not client:\n session = boto3_session()\n endpoint_url = os.environ.get(\"AWS_S3_ENDPOINT\", None)\n client = session.client(\"s3\", endpoint_url=endpoint_url)\n\n params = {\"Bucket\": bucket, \"Key\": key}\n if request_pays or os.environ.get(\"AWS_REQUEST_PAYER\", \"\").lower() == \"requester\":\n params[\"RequestPayer\"] = \"requester\"\n\n response = client.get_object(**params)\n return response[\"Body\"].read()\n\n\ndef _stats(\n arr: numpy.ma.array, percentiles: Tuple[float, float] = (2, 98), **kwargs: Any\n) -> Dict:\n \"\"\"Calculate array statistics.\n\n Args:\n arr (numpy.ndarray): Input array data to get the stats from.\n percentiles (tuple, optional): Min/Max percentiles to compute. Defaults to `(2, 98)`.\n kwargs (optional): Options to forward to numpy.histogram function.\n\n Returns:\n dict: numpy array statistics (percentiles, min, max, stdev, histogram, valid_percent).\n\n Examples:\n >>> {\n 'percentiles': [38, 147],\n 'min': 20,\n 'max': 180,\n 'std': 28.123562304138662,\n 'histogram': [\n [1625, 219241, 28344, 15808, 12325, 10687, 8535, 7348, 4656, 1208],\n [20.0, 36.0, 52.0, 68.0, 84.0, 100.0, 116.0, 132.0, 148.0, 164.0, 180.0]\n ],\n 'valid_percent': 0.5\n }\n\n \"\"\"\n sample, edges = numpy.histogram(arr[~arr.mask], **kwargs)\n return dict(\n percentiles=numpy.percentile(arr[~arr.mask], percentiles)\n .astype(arr.dtype)\n .tolist(),\n min=arr.min().item(),\n max=arr.max().item(),\n std=arr.std().item(),\n histogram=[sample.tolist(), edges.tolist()],\n valid_percent=((numpy.count_nonzero(~arr.mask)) / float(arr.data.size)) * 100,\n )\n\n\n# https://github.com/OSGeo/gdal/blob/b1c9c12ad373e40b955162b45d704070d4ebf7b0/gdal/frmts/ingr/IngrTypes.cpp#L191\ndef _div_round_up(a: int, b: int) -> int:\n return (a // b) if (a % b) == 0 else (a // b) + 1\n\n\ndef get_overview_level(\n src_dst: Union[DatasetReader, DatasetWriter, WarpedVRT],\n bounds: BBox,\n height: int,\n width: int,\n dst_crs: CRS = WEB_MERCATOR_CRS,\n) -> int:\n \"\"\"Return the overview level corresponding to the tile resolution.\n\n Freely adapted from https://github.com/OSGeo/gdal/blob/41993f127e6e1669fbd9e944744b7c9b2bd6c400/gdal/apps/gdalwarp_lib.cpp#L2293-L2362\n\n Args:\n src_dst (rasterio.io.DatasetReader or rasterio.io.DatasetWriter or rasterio.vrt.WarpedVRT): Rasterio dataset.\n bounds (tuple): Bounding box coordinates in target crs (**dst_crs**).\n height (int): Desired output height of the array for the input bounds.\n width (int): Desired output width of the array for the input bounds.\n dst_crs (rasterio.crs.CRS, optional): Target Coordinate Reference System. Defaults to `epsg:3857`.\n\n Returns:\n int: Overview level.\n\n \"\"\"\n dst_transform, _, _ = calculate_default_transform(\n src_dst.crs, dst_crs, src_dst.width, src_dst.height, *src_dst.bounds\n )\n src_res = dst_transform.a\n\n # Compute what the \"natural\" output resolution\n # (in pixels) would be for this input dataset\n vrt_transform = from_bounds(*bounds, width, height)\n target_res = vrt_transform.a\n\n ovr_idx = -1\n if target_res > src_res:\n res = [src_res * decim for decim in src_dst.overviews(1)]\n\n for ovr_idx in range(ovr_idx, len(res) - 1):\n ovrRes = src_res if ovr_idx < 0 else res[ovr_idx]\n nextRes = res[ovr_idx + 1]\n if (ovrRes < target_res) and (nextRes > target_res):\n break\n if abs(ovrRes - target_res) < 1e-1:\n break\n else:\n ovr_idx = len(res) - 1\n\n return ovr_idx\n\n\ndef get_vrt_transform(\n src_dst: Union[DatasetReader, DatasetWriter, WarpedVRT],\n bounds: BBox,\n height: Optional[int] = None,\n width: Optional[int] = None,\n dst_crs: CRS = WEB_MERCATOR_CRS,\n window_precision: int = 6,\n) -> Tuple[Affine, int, int]:\n \"\"\"Calculate VRT transform.\n\n Args:\n src_dst (rasterio.io.DatasetReader or rasterio.io.DatasetWriter or rasterio.vrt.WarpedVRT): Rasterio dataset.\n bounds (tuple): Bounding box coordinates in target crs (**dst_crs**).\n height (int, optional): Desired output height of the array for the input bounds.\n width (int, optional): Desired output width of the array for the input bounds.\n dst_crs (rasterio.crs.CRS, optional): Target Coordinate Reference System. Defaults to `epsg:3857`.\n\n Returns:\n tuple: VRT transform (affine.Affine), width (int) and height (int)\n\n \"\"\"\n dst_transform, _, _ = calculate_default_transform(\n src_dst.crs, dst_crs, src_dst.width, src_dst.height, *src_dst.bounds\n )\n\n # If bounds window is aligned with the dataset internal tile we align the bounds with the pixels.\n # This is to limit the number of internal block fetched.\n if _requested_tile_aligned_with_internal_tile(\n src_dst, bounds, height, width, dst_crs\n ):\n col_off, row_off, w, h = windows.from_bounds(\n *bounds, transform=src_dst.transform, width=width, height=height,\n ).flatten()\n\n w = windows.Window(\n round(col_off, window_precision),\n round(row_off, window_precision),\n round(w, window_precision),\n round(h, window_precision),\n )\n bounds = src_dst.window_bounds(w)\n\n w, s, e, n = bounds\n\n # TODO: Explain\n if not height or not width:\n vrt_width = max(1, round((e - w) / dst_transform.a))\n vrt_height = max(1, round((s - n) / dst_transform.e))\n vrt_transform = from_bounds(w, s, e, n, vrt_width, vrt_height)\n return vrt_transform, vrt_width, vrt_height\n\n # TODO: Explain\n tile_transform = from_bounds(w, s, e, n, width, height)\n w_res = (\n tile_transform.a\n if abs(tile_transform.a) < abs(dst_transform.a)\n else dst_transform.a\n )\n h_res = (\n tile_transform.e\n if abs(tile_transform.e) < abs(dst_transform.e)\n else dst_transform.e\n )\n\n # TODO: Explain\n vrt_width = max(1, round((e - w) / w_res))\n vrt_height = max(1, round((s - n) / h_res))\n vrt_transform = from_bounds(w, s, e, n, vrt_width, vrt_height)\n\n return vrt_transform, vrt_width, vrt_height\n\n\ndef has_alpha_band(src_dst: Union[DatasetReader, DatasetWriter, WarpedVRT]) -> bool:\n \"\"\"Check for alpha band or mask in source.\"\"\"\n if (\n any([MaskFlags.alpha in flags for flags in src_dst.mask_flag_enums])\n or ColorInterp.alpha in src_dst.colorinterp\n ):\n return True\n return False\n\n\ndef has_mask_band(src_dst: Union[DatasetReader, DatasetWriter, WarpedVRT]) -> bool:\n \"\"\"Check for mask band in source.\"\"\"\n if any(\n [\n (MaskFlags.per_dataset in flags and MaskFlags.alpha not in flags)\n for flags in src_dst.mask_flag_enums\n ]\n ):\n return True\n return False\n\n\ndef non_alpha_indexes(src_dst: Union[DatasetReader, DatasetWriter, WarpedVRT]) -> Tuple:\n \"\"\"Return indexes of non-alpha bands.\"\"\"\n return tuple(\n b\n for ix, b in enumerate(src_dst.indexes)\n if (\n src_dst.mask_flag_enums[ix] is not MaskFlags.alpha\n and src_dst.colorinterp[ix] is not ColorInterp.alpha\n )\n )\n\n\ndef linear_rescale(\n image: numpy.ndarray,\n in_range: Tuple[NumType, NumType],\n out_range: Tuple[NumType, NumType] = (0, 255),\n) -> numpy.ndarray:\n \"\"\"Apply linear rescaling to a numpy array.\n\n Args:\n image (numpy.ndarray): array to rescale.\n in_range (tuple): array min/max value to rescale from.\n out_range (tuple, optional): output min/max bounds to rescale to. Defaults to `(0, 255)`.\n\n Returns:\n numpy.ndarray: linear rescaled array.\n\n \"\"\"\n imin, imax = in_range\n omin, omax = out_range\n image = numpy.clip(image, imin, imax) - imin\n image = image / numpy.float64(imax - imin)\n return image * (omax - omin) + omin\n\n\ndef _requested_tile_aligned_with_internal_tile(\n src_dst: Union[DatasetReader, DatasetWriter, WarpedVRT],\n bounds: BBox,\n height: Optional[int] = None,\n width: Optional[int] = None,\n bounds_crs: CRS = WEB_MERCATOR_CRS,\n) -> bool:\n \"\"\"Check if tile is aligned with internal tiles.\"\"\"\n if not src_dst.is_tiled:\n return False\n\n if src_dst.crs != bounds_crs:\n return False\n\n col_off, row_off, w, h = windows.from_bounds(\n *bounds, transform=src_dst.transform, height=height, width=width\n ).flatten()\n\n if round(w) % 64 and round(h) % 64:\n return False\n\n if (src_dst.width - round(col_off)) % 64:\n return False\n\n if (src_dst.height - round(row_off)) % 64:\n return False\n\n return True\n\n\ndef render(\n data: numpy.ndarray,\n mask: Optional[numpy.ndarray] = None,\n img_format: str = \"PNG\",\n colormap: Optional[Dict] = None,\n **creation_options: Any,\n) -> bytes:\n \"\"\"Translate numpy.ndarray to image bytes.\n\n Args:\n data (numpy.ndarray): Image array to encode.\n mask (numpy.ndarray, optional): Mask array.\n img_format (str, optional): Image format. See: for the list of supported format by GDAL: https://www.gdal.org/formats_list.html. Defaults to `PNG`.\n colormap (dict, optional): GDAL RGBA Color Table dictionary.\n creation_options (optional): Image driver creation options to forward to GDAL.\n\n Returns\n bytes: image body.\n\n Examples:\n >>> with COGReader(\"my_tif.tif\") as cog:\n img = cog.preview()\n with open('test.jpg', 'wb') as f:\n f.write(render(img.data, img.mask, img_format=\"jpeg\"))\n\n\n \"\"\"\n img_format = img_format.upper()\n\n if len(data.shape) < 3:\n data = numpy.expand_dims(data, axis=0)\n\n if colormap:\n data, alpha = apply_cmap(data, colormap)\n if mask is not None:\n mask = (\n mask * alpha * 255\n ) # This is a special case when we want to mask some valid data\n\n # WEBP doesn't support 1band dataset so we must hack to create a RGB dataset\n if img_format == \"WEBP\" and data.shape[0] == 1:\n data = numpy.repeat(data, 3, axis=0)\n\n if img_format == \"PNG\" and data.dtype == \"uint16\" and mask is not None:\n mask = linear_rescale(mask, (0, 255), (0, 65535)).astype(\"uint16\")\n\n elif img_format == \"JPEG\":\n mask = None\n\n elif img_format == \"NPY\":\n # If mask is not None we add it as the last band\n if mask is not None:\n mask = numpy.expand_dims(mask, axis=0)\n data = numpy.concatenate((data, mask))\n\n bio = BytesIO()\n numpy.save(bio, data)\n bio.seek(0)\n return bio.getvalue()\n\n elif img_format == \"NPZ\":\n bio = BytesIO()\n if mask is not None:\n numpy.savez_compressed(bio, data=data, mask=mask)\n else:\n numpy.savez_compressed(bio, data=data)\n bio.seek(0)\n return bio.getvalue()\n\n count, height, width = data.shape\n\n output_profile = dict(\n driver=img_format,\n dtype=data.dtype,\n count=count + 1 if mask is not None else count,\n height=height,\n width=width,\n )\n output_profile.update(creation_options)\n\n with MemoryFile() as memfile:\n with memfile.open(**output_profile) as dst:\n dst.write(data, indexes=list(range(1, count + 1)))\n # Use Mask as an alpha band\n if mask is not None:\n dst.write(mask.astype(data.dtype), indexes=count + 1)\n\n return memfile.read()\n\n\ndef mapzen_elevation_rgb(data: numpy.ndarray) -> numpy.ndarray:\n \"\"\"Encode elevation value to RGB values compatible with Mapzen tangram.\n\n Args:\n data (numpy.ndarray): Image array to encode.\n\n Returns\n numpy.ndarray: Elevation encoded in a RGB array.\n\n \"\"\"\n data = numpy.clip(data + 32768.0, 0.0, 65535.0)\n r = data / 256\n g = data % 256\n b = (data * 256) % 256\n return numpy.stack([r, g, b]).astype(numpy.uint8)\n\n\ndef pansharpening_brovey(\n rgb: numpy.ndarray, pan: numpy.ndarray, weight: float, pan_dtype: str\n) -> numpy.ndarray:\n \"\"\"Apply Brovey pansharpening method.\n\n Brovey Method: Each resampled, multispectral pixel is\n multiplied by the ratio of the corresponding\n panchromatic pixel intensity to the sum of all the\n multispectral intensities.\n\n Original code from https://github.com/mapbox/rio-pansharpen\n\n \"\"\"\n\n def _calculateRatio(\n rgb: numpy.ndarray, pan: numpy.ndarray, weight: float\n ) -> numpy.ndarray:\n return pan / ((rgb[0] + rgb[1] + rgb[2] * weight) / (2 + weight))\n\n with numpy.errstate(invalid=\"ignore\", divide=\"ignore\"):\n ratio = _calculateRatio(rgb, pan, weight)\n return numpy.clip(ratio * rgb, 0, numpy.iinfo(pan_dtype).max).astype(pan_dtype)\n\n\ndef create_cutline(\n src_dst: Union[DatasetReader, DatasetWriter, WarpedVRT],\n geometry: Dict,\n geometry_crs: CRS = None,\n) -> str:\n \"\"\"\n Create WKT Polygon Cutline for GDALWarpOptions.\n\n Ref: https://gdal.org/api/gdalwarp_cpp.html?highlight=vrt#_CPPv415GDALWarpOptions\n\n Args:\n src_dst (rasterio.io.DatasetReader or rasterio.io.DatasetWriter or rasterio.vrt.WarpedVRT): Rasterio dataset.\n geometry (dict): GeoJSON feature or GeoJSON geometry. By default the cordinates are considered to be in the dataset CRS. Use `geometry_crs` to set a specific CRS.\n geometry_crs (rasterio.crs.CRS, optional): Input geometry Coordinate Reference System\n Returns:\n str: WKT geometry in form of `POLYGON ((x y, x y, ...)))\n\n \"\"\"\n if \"geometry\" in geometry:\n geometry = geometry[\"geometry\"]\n\n if not is_valid_geom(geometry):\n raise RioTilerError(\"Invalid geometry\")\n\n geom_type = geometry[\"type\"]\n if geom_type not in [\"Polygon\", \"MultiPolygon\"]:\n raise RioTilerError(\n \"Invalid geometry type: {geom_type}. Should be Polygon or MultiPolygon\"\n )\n\n if geometry_crs:\n geometry = transform_geom(geometry_crs, src_dst.crs, geometry)\n\n polys = []\n geom = (\n [geometry[\"coordinates\"]] if geom_type == \"Polygon\" else geometry[\"coordinates\"]\n )\n for p in geom:\n xs, ys = zip(*coords(p))\n src_y, src_x = rowcol(src_dst.transform, xs, ys)\n src_x = [max(0, min(src_dst.width, x)) for x in src_x]\n src_y = [max(0, min(src_dst.height, y)) for y in src_y]\n poly = \", \".join([f\"{x} {y}\" for x, y in list(zip(src_x, src_y))])\n polys.append(f\"(({poly}))\")\n\n str_poly = \",\".join(polys)\n\n return (\n f\"POLYGON {str_poly}\"\n if geom_type == \"Polygon\"\n else f\"MULTIPOLYGON ({str_poly})\"\n )\n","sub_path":"rio_tiler/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":15974,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"}
+{"seq_id":"78440504","text":"import numpy as np\n\nfrom pymoo.algorithms.genetic_algorithm import GeneticAlgorithm\nfrom pymoo.docs import parse_doc_string\nfrom pymoo.model.survival import Survival\nfrom pymoo.operators.crossover.simulated_binary_crossover import SimulatedBinaryCrossover\nfrom pymoo.operators.default_operators import set_if_none\nfrom pymoo.operators.mutation.polynomial_mutation import PolynomialMutation\nfrom pymoo.operators.sampling.random_sampling import RandomSampling\nfrom pymoo.operators.selection.tournament_selection import TournamentSelection, compare\nfrom pymoo.util.display import disp_single_objective\nfrom pymoo.util.non_dominated_sorting import NonDominatedSorting\nfrom pymoo.util.normalization import normalize\n\n\n# =========================================================================================================\n# Implementation\n# =========================================================================================================\n\n\nclass SingleObjectiveGeneticAlgorithm(GeneticAlgorithm):\n\n def __init__(self, **kwargs):\n set_if_none(kwargs, 'pop_size', 100)\n set_if_none(kwargs, 'sampling', RandomSampling())\n set_if_none(kwargs, 'selection', TournamentSelection(func_comp=comp_by_cv_and_fitness))\n set_if_none(kwargs, 'crossover', SimulatedBinaryCrossover(prob_cross=0.9, eta_cross=3))\n set_if_none(kwargs, 'mutation', PolynomialMutation(prob_mut=None, eta_mut=5))\n set_if_none(kwargs, 'survival', FitnessSurvival())\n set_if_none(kwargs, 'eliminate_duplicates', True)\n\n super().__init__(**kwargs)\n self.func_display_attrs = disp_single_objective\n\n\nclass FitnessSurvival(Survival):\n\n def __init__(self) -> None:\n super().__init__(True)\n\n def _do(self, pop, n_survive, out=None, **kwargs):\n F = pop.get(\"F\")\n\n if F.shape[1] != 1:\n raise ValueError(\"FitnessSurvival can only used for single objective problems!\")\n\n return pop[np.argsort(F[:, 0])[:n_survive]]\n\n\nclass ConstraintHandlingSurvival(Survival):\n\n def __init__(self, method=\"parameter_less\", **kwargs) -> None:\n super().__init__(False)\n self.method = method\n self.params = kwargs\n\n self.min_constraints = None\n self.max_constraints = None\n\n def calc_normalized_constraints(self, G):\n\n # update the ideal point for constraints\n if self.min_constraints is None:\n self.min_constraints = np.full(G.shape[1], np.inf)\n self.min_constraints = np.min(np.vstack((self.min_constraints, G)), axis=0)\n\n # update the nadir point for constraints\n non_dominated = NonDominatedSorting().do(G, return_rank=True, only_non_dominated_front=True)\n\n if self.max_constraints is None:\n self.max_constraints = np.full(G.shape[1], np.inf)\n self.max_constraints = np.min(np.vstack((self.max_constraints, np.max(G[non_dominated, :], axis=0))), axis=0)\n\n return normalize(G, self.min_constraints, self.max_constraints)\n\n def _do(self, pop, n_survive, out=None, **kwargs):\n\n # check if it is a population with a single objective\n F, G = pop.get(\"F\", \"G\")\n if F.shape[1] != 1:\n raise ValueError(\"FitnessSurvival can only used for single objective problems!\")\n\n # default parameters if not provided to the algorithm\n DEFAULT_PARAMS = {\n \"parameter_less\": {},\n \"epsilon_constrained\": {\"epsilon\": 1e-2},\n \"penalty\": {\"weight\": 0.1},\n \"stochastic_ranking\": {\"weight\": 0.45},\n }\n\n # check if the method is known\n if self.method not in DEFAULT_PARAMS.keys():\n raise Exception(\"Unknown constraint handling method %s\" % self.method)\n\n # set the default parameter if not provided\n for key, value in DEFAULT_PARAMS[self.method].items():\n set_if_none(self.params, key, value)\n\n # make the lowest possible constraint violation 0 - if not violated in that constraint\n G = G * (G > 0).astype(np.float)\n\n # find value to normalize to sum of for CV\n for j in range(G.shape[1]):\n\n N = np.median(G[:, j])\n if N == 0:\n N = np.max(G[:, j])\n\n if N > 0:\n pass\n # G[:, j] /= N\n\n # add the constraint violation and divide by normalization factor\n CV = np.sum(G, axis=1)\n\n if self.method == \"parameter_less\":\n\n # if infeasible add the constraint violation to worst F value\n _F = np.max(F, axis=0) + CV\n infeasible = CV > 0\n\n F[infeasible, 0] = _F[infeasible]\n\n # do fitness survival as done before with modified f\n return pop[np.argsort(F[:, 0])[:n_survive]]\n\n elif self.method == \"epsilon_constrained\":\n\n _F = np.max(F, axis=0) + CV\n infeasible = CV > self.params[\"epsilon\"]\n F[infeasible, 0] = _F[infeasible]\n\n # do fitness survival as done before with modified f\n return pop[np.argsort(F[:, 0])[:n_survive]]\n\n elif self.method == \"penalty\":\n\n _F = normalize(F)\n\n # add for each constraint violation a penalty\n _F[:, 0] = _F[:, 0] + self.params[\"weight\"] * CV\n return pop[np.argsort(_F[:, 0])[:n_survive]]\n\n elif self.method == \"stochastic_ranking\":\n\n # first shuffle the population randomly - to be sorted again\n I = np.random.permutation(len(pop))\n pop, F, CV = pop[I], F[I], CV[I]\n\n # func = load_function(\"stochastic_ranking\", \"stochastic_ranking\")\n\n from stochastic_ranking import stochastic_ranking\n func = stochastic_ranking\n\n index = func(F[:, 0], CV, self.params[\"prob\"])\n\n return pop[index[:n_survive]]\n\n\ndef comp_by_cv_and_fitness(pop, P, **kwargs):\n S = np.full(P.shape[0], np.nan)\n\n for i in range(P.shape[0]):\n a, b = P[i, 0], P[i, 1]\n\n # if at least one solution is infeasible\n if pop[a].CV > 0.0 or pop[b].CV > 0.0:\n S[i] = compare(a, pop[a].CV, b, pop[b].CV, method='smaller_is_better', return_random_if_equal=True)\n\n # both solutions are feasible just set random\n else:\n S[i] = compare(a, pop[a].F, b, pop[b].F, method='smaller_is_better', return_random_if_equal=True)\n\n return S[:, None].astype(np.int)\n\n\n# =========================================================================================================\n# Interface\n# =========================================================================================================\n\n\ndef ga(\n pop_size=100,\n sampling=RandomSampling(),\n selection=TournamentSelection(func_comp=comp_by_cv_and_fitness),\n crossover=SimulatedBinaryCrossover(prob_cross=0.9, eta_cross=3),\n mutation=PolynomialMutation(prob_mut=None, eta_mut=5),\n eliminate_duplicates=True,\n n_offsprings=None,\n **kwargs):\n \"\"\"\n\n Parameters\n ----------\n pop_size : {pop_size}\n sampling : {sampling}\n selection : {selection}\n crossover : {crossover}\n mutation : {mutation}\n eliminate_duplicates : {eliminate_duplicates}\n n_offsprings : {n_offsprings}\n\n Returns\n -------\n ga : :class:`~pymoo.model.algorithm.Algorithm`\n Returns an SingleObjectiveGeneticAlgorithm algorithm object.\n\n\n \"\"\"\n\n return SingleObjectiveGeneticAlgorithm(pop_size=pop_size,\n sampling=sampling,\n selection=selection,\n crossover=crossover,\n mutation=mutation,\n survival=FitnessSurvival(),\n eliminate_duplicates=eliminate_duplicates,\n n_offsprings=n_offsprings,\n **kwargs)\n\n\nparse_doc_string(ga)\n","sub_path":"pymoo/algorithms/so_genetic_algorithm.py","file_name":"so_genetic_algorithm.py","file_ext":"py","file_size_in_byte":8006,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"}
+{"seq_id":"117898101","text":"# The purpose of this class is to test the\n# performance of flask-based sockets in\n# apache + gunicorn environment.\n# also, this mini-project serves as a template for future flask projects\n\nfrom flask import Flask, request, abort, jsonify\nimport json\nfrom flask import render_template\nfrom flask_socketio import SocketIO, send, emit\nimport sys, os\nfrom .chatbot.calculate import Calculator\n\n\nsys.path.insert(0, os.path.realpath(os.path.dirname(__file__)))\nsys.path.append('/source')\n\n\napp = Flask(__name__)\nsocketio = SocketIO(app)\n\n@app.route('/index')\ndef render_index():\n return render_template('index_socket_test.html')\n\n\n@socketio.on('message')\ndef handle_message(message):\n print('message:', message['message'])\n cal.run()\n emit('response', json.dumps({'response': 'Hello'}))\n\n# def get_square():\n# if not request.json or 'number' not in request.json:\n# abort(400)\n# num = request.json['number']\n#\n# return jsonify({'answer': num ** 2})\n\ncal = Calculator(socketio)\n\n\nif __name__ == '__main__':\n app.run(host='127.0.0.1', port=8080, debug=True)\n socketio.run(app)","sub_path":"JPS_Chatbot/EnvironmentTest/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1110,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"}
+{"seq_id":"535367644","text":"\nfrom src.mobilenet_v2_tsm import MobileNetV2\nimport os\nimport torch\nimport torchvision\n\ndef load_model():\n torch_module = MobileNetV2(n_class=27)\n # checkpoint not downloaded\n if not os.path.exists(\"mobilenetv2_jester_online.pth.tar\"):\n print('Downloading PyTorch checkpoint...')\n import urllib.request\n url = 'https://hanlab.mit.edu/projects/tsm/models/mobilenetv2_jester_online.pth.tar'\n urllib.request.urlretrieve(url, './mobilenetv2_jester_online.pth.tar')\n torch_module.load_state_dict(torch.load(\n \"mobilenetv2_jester_online.pth.tar\"))\n\n return torch_module\n\n\ndef init_buffer():\n return [torch.zeros([1, 3, 56, 56]),\n torch.zeros([1, 4, 28, 28]),\n torch.zeros([1, 4, 28, 28]),\n torch.zeros([1, 8, 14, 14]),\n torch.zeros([1, 8, 14, 14]), \n torch.zeros([1, 8, 14, 14]), \n torch.zeros([1, 12, 14, 14]), \n torch.zeros([1, 12, 14, 14]), \n torch.zeros([1, 20, 7, 7]), \n torch.zeros([1, 20, 7, 7])]\n\n","sub_path":"src/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":1052,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"}
+{"seq_id":"232714179","text":"import numpy as np\nfrom abc import ABCMeta, abstractmethod\n\nclass Classifier:\n\t__metaclass__ = ABCMeta\n\t\t\n\t@abstractmethod\n\tdef classify(self, x):\n\t\tpass\n\t\n\t\nclass PerceptronClassifier(Classifier):\n\tdef __init__(self, w_vector):\n\t\tself.w = w_vector\n\t\n\tdef _calculate_y_from_dot_product_calculated(self, y_calculated):\n\t\tif y_calculated < 0:\n\t\t\treturn 0\n\t\telse: \n\t\t\treturn 1\n\t\n\tdef classify(self, x):\n\t\tx_append_1 = [1.0, x]\t\t\n\t\ty_calculated = np.dot(x_append_1, self.w)\n\t\t\n\t\treturn self._calculate_y_from_dot_product_calculated(y_calculated)\n\t\n\nclass PerceptronGenerator:\t\n\tdef _init_training_data(self, training_data):\n\t\tpla_training_data = []\n\t\tfor item in training_data:\n\t\t\txs = [1, item[0]]\n\t\t\ty = item[1]\n\t\t\tpla_training_data.append([xs, y]) \n\n\t\treturn pla_training_data\n\n\tdef _calculate_y_from_dot_product_calculated(self, value):\n\t\tif value < 0:\n\t\t\treturn 0\n\t\treturn 1\n\n\tdef _is_misclassified(self, test, actual_value):\n\t\tcalculated_y = self._calculate_y_from_dot_product_calculated(test)\n\t\tactual_y = self._calculate_y_from_dot_product_calculated(actual_value)\n\t\t\n\t\tif calculated_y == actual_y:\n\t\t\treturn False\n\n\t\treturn True\n\n\tdef _calculate_error(self, input_vec ,w):\n\t\tnumber_of_samples = len(input_vec)\n\t\tmisclassified_points_count = 0\n\n\t\tfor p in input_vec:\n\t\t\tcalculated_y = np.dot(p[0], w)\n\t\t\tif self._is_misclassified(calculated_y, p[1]):\n\t\t\t\tmisclassified_points_count += 1\n\n\t\treturn float(misclassified_points_count) / number_of_samples\n\n\tdef _pick_a_misclassified_point(self, input_vec, w):\n\t\tfor p in input_vec:\n\t\t\tcalculated_y = np.dot(p[0], w)\n\t\t\tif self._is_misclassified(calculated_y, p[1]):\n\t\t\t\treturn p\n\n\t\treturn None\n\n\tdef generate(self, training_data):\n\t\tw = np.zeros(2)\n\t\titeration_count = 0\n\t\t\n\t\tpla_training_data = self._init_training_data(training_data)\n\t\t\n\t\twhile self._calculate_error(pla_training_data ,w) > 0.0:\t\t\t\n\t\t\titeration_count += 1\n\t\t\tp = self._pick_a_misclassified_point(pla_training_data, w)\n\t\t\tfactor = [p[1] * x for x in p[0]]\n\t\t\t\n\t\t\tw += factor\n\n\t\t\t#print(\"factor = w = \" + str(p) + \"itr = \" + str(iteration_count))\n\t\t\t#input()\n\n\t\treturn PerceptronClassifier(w)\n","sub_path":"problem6/Perceptron.py","file_name":"Perceptron.py","file_ext":"py","file_size_in_byte":2110,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"}
+{"seq_id":"358830","text":"#!/usr/bin/env python\nfrom databases import data_to_mysql\nimport numpy as np\n\n\ndef emaTotalWhenDay(whenDay):\n cur = data_to_mysql.select_one_storm_before_limit(\"bigdog\", whenDay, 4)\n a = np.array(cur.fetchall())\n c = np.array(a[:, 10])\n if len(c) < 4:\n return\n w = 2 / (3 + 1)\n emaT3 = (c[0] +\n (1 - w) ** 1 * c[1] +\n (1 - w) ** 2 * c[2] +\n (1 - w) ** 3 * c[3]) / (1 + (1 - w) + (1 - w) ** 2 + (1 - w) ** 3)\n\n data_to_mysql.update_total_ema3(whenDay, round(emaT3, 3))\n return emaT3\n","sub_path":"rule/ema_total.py","file_name":"ema_total.py","file_ext":"py","file_size_in_byte":549,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"}
+{"seq_id":"485308710","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.macosx-10.15-x86_64/egg/samcli/commands/init/init_generator.py\n# Compiled at: 2020-03-21 12:32:11\n# Size of source mod 2**32: 630 bytes\n\"\"\"\nCookiecutter-based generation logic for project templates.\n\"\"\"\nfrom samcli.commands.exceptions import UserException\nfrom samcli.lib.init import generate_project\nfrom samcli.lib.init.exceptions import GenerateProjectFailedError, ArbitraryProjectDownloadFailed\n\ndef do_generate(location, runtime, dependency_manager, output_dir, name, no_input, extra_context):\n try:\n generate_project(location, runtime, dependency_manager, output_dir, name, no_input, extra_context)\n except (GenerateProjectFailedError, ArbitraryProjectDownloadFailed) as e:\n try:\n raise UserException((str(e)), wrapped_from=(e.__class__.__name__))\n finally:\n e = None\n del e","sub_path":"pycfiles/aws_sam_cli_without_docker-0.48.0-py3.7/init_generator.cpython-37.py","file_name":"init_generator.cpython-37.py","file_ext":"py","file_size_in_byte":1010,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"}
+{"seq_id":"623402656","text":"import asyncio\nimport ParseCity\n\nfrom pyppeteer.errors import ElementHandleError\nfrom pyppeteer import launch\n\neventid = []\n\n\nasync def main():\n browser = await launch()\n page = await browser.newPage()\n with open(\"maindata.txt\", \"w\", errors=\"ignore\", encoding=\"UTF-8\") as file:\n for event_number in eventid:\n print(event_number)\n await page.goto('https://2event.com/uk/events/' + event_number)\n await page.waitForSelector(\".event-address-street\")\n\n # місце\n element = await page.querySelector('p.event-address-street')\n title = await page.evaluate('(element) => element.textContent',\n element)\n file.write(title.strip() + \"@@\")\n\n # назва\n element = await page.querySelector('h1.location-title')\n title = await page.evaluate('(element) => element.textContent',\n element)\n file.write(title.strip() + \"@@\")\n\n # категорія\n element = await page.querySelector('p.location-category')\n title = await page.evaluate('(element) => element.textContent',\n element)\n file.write(title.strip() + \"@@\")\n\n # ссилка в фейсбук\n try:\n element = await page.querySelector('a.fb')\n title = await page.evaluate(\n '(element) => element.getAttribute(\\'href\\')', element)\n file.write(title.strip() + \"@@\")\n except ElementHandleError:\n title = \"\"\n file.write(title + \"@@\")\n\n # дата\n element = await page.querySelector('div.event-date')\n title = await page.evaluate('(element) => element.textContent',\n element)\n title = title.strip().split(\" \")\n file.write(title[0].strip() + \"@@\" + title[1] + \"@@\")\n\n # опис\n element = await page.querySelector('div.text-description-content')\n title = await page.evaluate('(element) => element.textContent',\n element)\n file.write(title.strip() + \"####\")\n\n await browser.close()\n\ndef start():\n global eventid\n eventid=ParseCity.main()\n asyncio.get_event_loop().run_until_complete(main())","sub_path":"Parser.py","file_name":"Parser.py","file_ext":"py","file_size_in_byte":2477,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"}
+{"seq_id":"194576967","text":"import subprocess\nimport sys\nimport argparse\n\n'''\nNote:\nIn the below representation pcd is abbreviated as point_cloud\nThe try..finally block performs the libraries check and installs necessary dependencies\n'''\ntry:\n import open3d as o3d\n import numpy as np\n import matplotlib.pyplot as plt\nexcept ModuleNotFoundError:\n subprocess.call([sys.executable, \"-m\", \"pip3\", \"install\", 'open3d'])\n subprocess.call([sys.executable, \"-m\", \"pip3\", \"install\", 'numpy'])\n subprocess.call([sys.executable, \"-m\", \"pip3\", \"install\", 'matplotlib'])\nfinally:\n import open3d as o3d\n import matplotlib.pyplot as plt\n import numpy as np\n\n## Argument Parser for command line args\nap = argparse.ArgumentParser()\nap.add_argument(\"filename\")\nap.add_argument(\"voxelsize\")\nargs = ap.parse_args()\n\n## Function read_from_file reads an input point cloud as a file and returns the object\ndef read_from_file(filename):\n pcd = o3d.io.read_point_cloud(filename)\n # print(pcd) # Uncomment to see the points number\n return pcd\n\n## Function downsample_pcd performs downsampling w.r.t voxel size and returns output\ndef downsample_pcd(pcd, voxel_size):\n downpcd = pcd.voxel_down_sample(voxel_size) # Downsample the point cloud with voxel size\n #print(downpcd) # Uncomment to see the points number\n return downpcd\n\n## Function visualize_pcd displays the output pcd\ndef visualize_pcd(pcd):\n o3d.visualization.draw_geometries([pcd])\n\n## Function write_to_file performs a write operation to output ASCII File\ndef write_to_file(filename):\n o3d.io.write_point_cloud(\"downsampled_point_cloud.xyz\", filename, write_ascii=True)\n print(\"Written into downsampled_point_cloud.xyz\")\n\ndef main():\n filename = args.filename\n voxel_size = float(args.voxelsize)\n input_pcd = read_from_file(filename)\n downsampled_pcd = downsample_pcd(input_pcd, voxel_size)\n visualize_pcd(downsampled_pcd)\n write_to_file(downsampled_pcd)\n \n\nif __name__ == \"__main__\":\n main()\n\n\n","sub_path":"pointcloud_downsampling/down_sampler.py","file_name":"down_sampler.py","file_ext":"py","file_size_in_byte":1983,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"}
+{"seq_id":"282831098","text":"import numpy as np\nimport tensorflow as tf\ninput_data=tf.Variable(np.random.rand(10,9,9,3),dtype=np.float32)\n\nfilter_data=tf.Variable(np.random.rand(2,2,3,2),dtype=np.float32)\n\ny=tf.nn.conv2d(input_data,filter_data,strides=[1,1,1,1],padding='SAME')\n\nwith tf.Session() as sess:\n tf.global_variables_initializer().run()\n print(sess.run(tf.shape(y)))","sub_path":"conv2d函数.py","file_name":"conv2d函数.py","file_ext":"py","file_size_in_byte":353,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"}
+{"seq_id":"147075085","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 ('website', '0038_auto_20150920_0756'),\n ]\n\n operations = [\n migrations.RenameField(\n model_name='comment',\n old_name='money',\n new_name='total_price',\n ),\n migrations.AddField(\n model_name='comment',\n name='count',\n field=models.IntegerField(null=True, blank=True),\n preserve_default=True,\n ),\n migrations.AddField(\n model_name='comment',\n name='goods',\n field=models.TextField(null=True, blank=True),\n preserve_default=True,\n ),\n migrations.AddField(\n model_name='comment',\n name='unit_price',\n field=models.IntegerField(null=True, blank=True),\n preserve_default=True,\n ),\n ]\n","sub_path":"website/migrations/0039_auto_20150920_0825.py","file_name":"0039_auto_20150920_0825.py","file_ext":"py","file_size_in_byte":985,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"}
+{"seq_id":"554603343","text":"class Budget:\n def __init__(self, category):\n self.category = category\n self.amount = 1000\n\n def deposit(self, amount):\n self.amount += amount\n return self.amount\n\n def __check_balance(self, amount):\n return True if self.amount > amount else False\n\n def withdraw(self, amount):\n if self.__check_balance(amount) == True:\n self.amount -= amount\n return self.amount\n else:\n return 'You do not have sufficient funds'\n\n def transfer(self, amount, category):\n print(self.amount, amount)\n if self.__check_balance(amount) == True:\n self.amount -= amount\n category.amount += amount\n return f\"You have transferred {amount} to {category.category} category\"\n else:\n return 'You do not have sufficient funds'\n\n\n\ncategory_1 = Budget(\"clothing\")\nprint(\"This is deposit for clothing\", category_1.deposit(1000))\nprint(\"This is withdrawal for clothing\", category_1.withdraw(300))\n\ncategory_2 = Budget(\"food\")\nprint(category_1.transfer(500, category_2))\n\ncategory_3 = Budget(\"entertainment\")","sub_path":"classes.py","file_name":"classes.py","file_ext":"py","file_size_in_byte":1133,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"}
+{"seq_id":"608647153","text":"from statiskit import stl\n\nimport unittest\nfrom nose.plugins.attrib import attr\n\n@attr(linux=True, \n osx=True,\n win=True,\n level=1)\nclass TestVector(unittest.TestCase):\n\n def test___initialization(self):\n \"\"\"Test vector initialization\"\"\"\n\n v = stl.VectorIndex()\n self.assertEqual(len(v), 0)\n\n def test__equal(self):\n \"\"\"Test vectors equality\"\"\"\n\n v1 = stl.VectorIndex()\n v1.push_back(3)\n v1.push_back(1)\n v1.push_back(2)\n v2 = stl.VectorIndex()\n v2.push_back(3)\n v2.push_back(1)\n v2.push_back(2)\n self.assertEqual(v1, v2)\n v3 = stl.VectorString()\n v3.push_back('A')\n v3.push_back('B')\n v3.push_back('C')\n v4 = stl.VectorString()\n v4.push_back('A')\n v4.push_back('B')\n v4.push_back('C')\n self.assertEqual(v3, v4)","sub_path":"test/test_vector.py","file_name":"test_vector.py","file_ext":"py","file_size_in_byte":886,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"}
+{"seq_id":"296992086","text":"# -*- coding: utf-8 -*-\n# Tests for psj_basedoc module.\n#\n# XXX: FSD-related tests (including author attr) are missing.\n# These are blocked by difficulties installing FSD in tests.\n#\nimport os\nimport shutil\nimport tempfile\nimport unittest\nfrom base64 import b64encode\nfrom plone.app.testing import (\n TEST_USER_ID, SITE_OWNER_NAME, SITE_OWNER_PASSWORD, setRoles,\n )\nfrom plone.app.textfield.value import RichTextValue\nfrom plone.dexterity.interfaces import IDexterityFTI\nfrom plone.testing.z2 import Browser\nfrom zope.component import queryUtility, createObject, getGlobalSiteManager\nfrom zope.event import notify\nfrom zope.interface import verify\nfrom zope.lifecycleevent import ObjectModifiedEvent\nfrom zope.schema.interfaces import IVocabularyFactory\nfrom psj.content.interfaces import IExternalVocabConfig\nfrom psj.content.psj_basedoc import (\n IBaseDoc, BaseDoc,\n )\nfrom psj.content.testing import INTEGRATION_TESTING, FUNCTIONAL_TESTING\n\n\nVOCABS = [\n (u'psj.content.Institutes', 'Institute'),\n (u'psj.content.Licenses', 'License')\n ]\n\nRICH_TEXT_VALUE1 = RichTextValue(\n u\"My Richtext Value\\n\",\n 'text/plain', 'text/x-html-safe', 'utf-8')\n\nRICH_TEXT_VALUE2 = RichTextValue(\n u\"Other Richtext Value\\n\",\n 'text/plain', 'text/x-html-safe', 'utf-8')\n\n\nclass BaseDocUnitTests(unittest.TestCase):\n\n def test_iface(self):\n # make sure we fullfill all interface contracts\n obj = BaseDoc()\n verify.verifyClass(IBaseDoc, BaseDoc)\n verify.verifyObject(IBaseDoc, obj)\n\n\nclass BaseDocIntegrationTests(unittest.TestCase):\n\n layer = INTEGRATION_TESTING\n\n def create_external_vocab(self, name, readable=None):\n # create a working external vocab and register it\n readable = readable or name\n gsm = getGlobalSiteManager()\n path = os.path.join(self.workdir, 'sample_vocab-%s.csv' % name)\n entries = u'First %s Entry\\nOther %s Entry\\nÜmlautEntry\\n' % (\n readable, readable)\n open(path, 'w').write(entries.encode('utf-8'))\n conf = {'path': path, 'name': name}\n gsm.registerUtility(conf, provided=IExternalVocabConfig, name=name)\n\n def setup_vocabs(self):\n for name, readable in VOCABS:\n self.create_external_vocab(name, readable)\n\n def teardown_vocabs(self):\n gsm = getGlobalSiteManager()\n for entry in VOCABS:\n gsm.unregisterUtility(name=entry[0], provided=IVocabularyFactory)\n\n def setUp(self):\n self.workdir = tempfile.mkdtemp()\n self.portal = self.layer['portal']\n setRoles(self.portal, TEST_USER_ID, ['Manager'])\n self.portal.invokeFactory('Folder', 'test-folder')\n setRoles(self.portal, TEST_USER_ID, ['Member'])\n self.folder = self.portal['test-folder']\n self.setup_vocabs()\n return\n\n def tearDown(self):\n self.teardown_vocabs()\n shutil.rmtree(self.workdir)\n\n def test_adding(self):\n # we can add BaseDoc instances\n self.folder.invokeFactory(\n 'psj.content.basedoc', 'doc1',\n title=u'My Doc', description=u'My description.',\n psj_title=u'My Title', psj_subtitle=u'My Subtitle',\n psj_institute=[u'First Institute Entry'],\n psj_license=u'First License Entry',\n psj_abstract=RICH_TEXT_VALUE1,\n psj_doi=u'My Identifier',\n )\n d1 = self.folder['doc1']\n self.assertTrue(IBaseDoc.providedBy(d1))\n self.assertEqual(d1.title, u'My Doc')\n self.assertEqual(d1.description, u'My description.')\n # additional attributes were set\n self.assertEqual(d1.psj_title, u'My Title')\n self.assertEqual(d1.psj_subtitle, u'My Subtitle')\n self.assertEqual(d1.psj_institute, [u'First Institute Entry', ])\n self.assertEqual(d1.psj_license, u'First License Entry')\n self.assertEqual(d1.psj_abstract.output,\n u'My Richtext Value
')\n self.assertEqual(d1.psj_doi, u'My Identifier')\n\n def test_editing(self):\n # we can modify BaseDocs. Changes are reflected.\n self.folder.invokeFactory(\n 'psj.content.basedoc', 'doc1',\n title=u'My doc', description=u'My description.',\n psj_title=u'My title', psj_subtitle=u'My Subtitle',\n psj_institute=[u'First Institute Entry', ],\n psj_license=u'First License Entry',\n psj_abstract=RICH_TEXT_VALUE1,\n psj_doi=u'My Identifier',\n )\n d1 = self.folder['doc1']\n d1.title = u'My changed title'\n d1.description = u'My changed description'\n d1.psj_title = u'My changed title'\n d1.psj_subtitle = u'My changed subtitle'\n d1.psj_institute = [u'Other Institute Entry', ]\n d1.psj_license = u'Other License Entry'\n d1.psj_abstract = RICH_TEXT_VALUE2\n d1.psj_doi = u'My changed identifier'\n # we have to fire an event here\n notify(ObjectModifiedEvent(d1))\n self.assertEqual(d1.title, u'My changed title')\n self.assertEqual(d1.description, u'My changed description')\n self.assertEqual(d1.psj_title, u'My changed title')\n self.assertEqual(d1.psj_subtitle, u'My changed subtitle')\n self.assertEqual(d1.psj_institute, [u'Other Institute Entry', ])\n self.assertEqual(d1.psj_license, u'Other License Entry')\n self.assertEqual(d1.psj_abstract.output,\n u'Other Richtext Value
')\n self.assertEqual(d1.psj_doi, u'My changed identifier')\n\n def test_fti(self):\n # we can get factory type infos for base docs\n fti = queryUtility(IDexterityFTI, name='psj.content.basedoc')\n assert fti is not None\n\n def test_schema(self):\n # our fti provides the correct schema\n fti = queryUtility(IDexterityFTI, name='psj.content.basedoc')\n schema = fti.lookupSchema()\n self.assertEqual(IBaseDoc, schema)\n\n def test_factory(self):\n # our fti provides a factory for BaseDoc instances\n fti = queryUtility(IDexterityFTI, name='psj.content.basedoc')\n factory = fti.factory\n new_obj = createObject(factory)\n self.assertTrue(IBaseDoc.providedBy(new_obj))\n\n def test_views(self):\n # we can get a regular and a special view for added basedocs\n self.folder.invokeFactory(\n 'psj.content.basedoc', 'doc1',)\n d1 = self.folder['doc1']\n view = d1.restrictedTraverse('@@view')\n assert view is not None\n\n def test_searchable_text(self):\n # searchableText contains the base doc content\n self.folder.invokeFactory(\n 'psj.content.basedoc', 'doc1',\n title=u'Foo Doc', description=u'My Description',\n psj_title=u'Baz', psj_subtitle=u'Furor', psj_doi=u'Bar',\n psj_abstract=RICH_TEXT_VALUE1,\n )\n d1 = self.folder['doc1']\n self.assertEqual(\n 'Foo Doc My Description Baz Furor My Richtext Value',\n d1.SearchableText())\n\n def test_searchable_text_indexed(self):\n # searchableText is indexed properly\n self.folder.invokeFactory(\n 'psj.content.basedoc', 'doc1',\n title=u'Foo Doc', description=u'My Description',\n psj_title=u'Baz', psj_subtitle=u'Furor', psj_doi=u'Bar',\n )\n d1 = self.folder['doc1']\n d1.reindexObject()\n result = self.portal.portal_catalog(SearchableText=\"Foo\")\n self.assertEqual(1, len(result))\n self.assertEqual(result[0].getURL(), d1.absolute_url())\n\n def test_title_indexed(self):\n # titles of basedocs are indexed (also after change)\n self.folder.invokeFactory(\n 'psj.content.basedoc', 'doc1', title=u'My DocTitle',\n psj_doi=u'Bar',)\n d1 = self.folder['doc1']\n result = self.portal.portal_catalog(Title='DocTitle')\n self.assertEqual(1, len(result))\n # title changes are reflected in catalog\n d1.setTitle(u'My Othertitle')\n notify(ObjectModifiedEvent(d1))\n result = self.portal.portal_catalog(Title='Doctitle')\n self.assertEqual(0, len(result)) # old content gone\n result = self.portal.portal_catalog(Title='Othertitle')\n self.assertEqual(1, len(result)) # new content found\n\n def test_description_indexed(self):\n # descriptions of basedocs are indexed (also after change)\n self.folder.invokeFactory(\n 'psj.content.basedoc', 'doc1',\n description=u'My DocDescription', psj_doi=u'Bar')\n d1 = self.folder['doc1']\n result = self.portal.portal_catalog(Description='DocDescription')\n self.assertEqual(1, len(result))\n # description changes are reflected in catalog\n d1.setDescription(u'My ChangedDescription')\n notify(ObjectModifiedEvent(d1))\n result = self.portal.portal_catalog(Description='DocDescription')\n self.assertEqual(0, len(result)) # old content gone\n result = self.portal.portal_catalog(Description='ChangedDescription')\n self.assertEqual(1, len(result)) # new content found\n\n\nclass BasedocBrowserTests(unittest.TestCase):\n\n layer = FUNCTIONAL_TESTING\n\n def create_doc(self):\n portal = self.layer['portal']\n portal.invokeFactory(\n 'psj.content.basedoc', 'myeditdoc',\n title=u'My Edit Doc', description=u'My description.',\n psj_title=u'My Title', psj_subtitle=u'My Subtitle',\n psj_institute=[u'First Institute Entry', ],\n psj_license=u'First License Entry',\n psj_abstract=RICH_TEXT_VALUE1,\n psj_doi=u'My identifier',\n )\n import transaction\n transaction.commit()\n\n def create_external_vocab(self, name, readable=None):\n # create a working external vocab and register it\n readable = readable or name\n gsm = getGlobalSiteManager()\n path = os.path.join(self.workdir, 'sample_vocab-%s.csv' % name)\n entries = u'First %s Entry\\nOther %s Entry\\nÜmlautEntry\\n' % (\n readable, readable)\n open(path, 'w').write(entries.encode('utf-8'))\n conf = {'path': path, 'name': name}\n gsm.registerUtility(conf, provided=IExternalVocabConfig, name=name)\n\n def setup_vocabs(self):\n for name, readable in VOCABS:\n self.create_external_vocab(name, readable)\n\n def teardown_vocabs(self):\n gsm = getGlobalSiteManager()\n for name in VOCABS:\n gsm.unregisterUtility(name=name[0], provided=IVocabularyFactory)\n\n def setUp(self):\n self.portal = self.layer['portal']\n setRoles(self.portal, TEST_USER_ID, ['Member', 'Manager'])\n self.portal_url = self.portal.absolute_url()\n self.browser = Browser(self.layer['app'])\n self.workdir = tempfile.mkdtemp()\n self.setup_vocabs()\n\n def tearDown(self):\n self.teardown_vocabs()\n shutil.rmtree(self.workdir)\n\n def do_login(self, browser):\n browser.open(self.portal_url + '/login')\n browser.getControl(label='Login Name').value = SITE_OWNER_NAME\n browser.getControl(label='Password').value = SITE_OWNER_PASSWORD\n browser.getControl(\"Log in\").click()\n\n def test_add(self):\n # we can add base docs.\n self.do_login(self.browser)\n self.browser.open(self.portal_url)\n # find add link and click it\n add_link = self.browser.getLink('PSJ Base Document')\n self.assertEqual('psj-content-basedoc', add_link.attrs['id'])\n add_link.click()\n\n # fill form\n self.browser.getControl(label='Title').value = 'My Title'\n self.browser.getControl(label='Summary').value = 'My Description'\n self.browser.getControl(label='Titel').value = 'My Book Title'\n self.browser.getControl(label='Untertitel').value = 'My Subtitle'\n # XXX: Disabled; too hard to test JS-driven forms\n #self.browser.getControl(label='Institut').displayValue = [\n # 'First Institute Entry', ]\n self.browser.getControl(label='Lizenz').displayValue = [\n 'First License Entry', ]\n self.browser.getControl(\n name='form.widgets.psj_abstract').value = 'My Abstract\\n'\n self.browser.getControl(label='DOI').value = 'My Identifier'\n self.browser.getControl(\"Save\").click()\n\n assert 'My Title' in self.browser.contents\n assert 'My Description' in self.browser.contents\n assert 'My Book Title' in self.browser.contents\n assert 'My Subtitle' in self.browser.contents\n # XXX: Disabled; too hard to test JS-driven forms\n #assert 'First Institute Entry' in self.browser.contents\n assert 'First License Entry' in self.browser.contents\n assert 'My Abstract' in self.browser.contents\n assert 'My Identifier' in self.browser.contents\n\n def test_edit(self):\n # we can edit base docs\n self.do_login(self.browser)\n self.create_doc()\n self.browser.open(self.portal_url + '/myeditdoc')\n edit_link = self.browser.getLink('Edit', index=1)\n edit_link.click()\n\n # set new values\n self.browser.getControl(label='Title').value = 'Other Title'\n self.browser.getControl(label='Summary').value = 'My Other Descr.'\n self.browser.getControl(label='Titel').value = 'Other Book Title'\n self.browser.getControl(label='Untertitel').value = 'Other Subtitle'\n # XXX: Disabled; too hard to test JS-driven forms\n #self.browser.getControl(label='Institut').value = [\n # b64encode('Other Institute Entry'), ]\n self.browser.getControl(label='Lizenz').value = [\n b64encode('Other License Entry'), ]\n self.browser.getControl(\n name='form.widgets.psj_abstract').value = 'Other Abstract\\n'\n self.browser.getControl(label='DOI').value = 'Other Identifier'\n self.browser.getControl(\"Save\").click()\n\n assert 'Other Title' in self.browser.contents\n assert 'My Title' not in self.browser.contents\n assert 'My Other Descr.' in self.browser.contents\n assert 'My Description' not in self.browser.contents\n assert 'Other Book Title' in self.browser.contents\n assert 'My Book Title' not in self.browser.contents\n assert 'Other Subtitle' in self.browser.contents\n assert 'My Subtitle' not in self.browser.contents\n # XXX: Disabled; too hard to test JS-driven forms\n #assert 'Other Institute Entry' in self.browser.contents\n #assert 'First Institute Entry' not in self.browser.contents\n assert 'Other License Entry' in self.browser.contents\n assert 'First License Entry' not in self.browser.contents\n assert 'Other Abstract' in self.browser.contents\n assert 'My Abstract' not in self.browser.contents\n assert 'Other Identifier' in self.browser.contents\n assert 'My Identifier' not in self.browser.contents\n","sub_path":"psj/content/tests/test_psj_basedoc.py","file_name":"test_psj_basedoc.py","file_ext":"py","file_size_in_byte":14991,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"}
+{"seq_id":"597716740","text":"from collections import Counter\n\nwith open('input.txt', 'rt') as fin:\n data = [d.strip() for d in fin]\n\ncode = list(' ' * len(data[0]))\nprint(code)\n\n\nfor i in range(len(code)):\n letters = []\n for d in data:\n letter = d[i]\n letters.append(letter)\n counted = Counter(letters)\n most_common = counted.most_common()[-1][0]\n code[i] = most_common\n\nprint(\"\".join(code))\n","sub_path":"day06/day06part2.py","file_name":"day06part2.py","file_ext":"py","file_size_in_byte":395,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"}
+{"seq_id":"390127254","text":"# Copyright (c) 2016, DjaoDjin inc.\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,\n# this list of conditions and the following disclaimer.\n# 2. Redistributions in binary form must reproduce the above copyright\n# notice, this list of conditions and the following disclaimer in the\n# documentation and/or other materials provided with the distribution.\n#\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n# \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED\n# TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\n# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR\n# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\n# EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;\n# OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n# WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR\n# OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF\n# ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\nimport json\nimport datetime\n\nfrom django.core.urlresolvers import reverse\nfrom django.views.generic import (View, TemplateView)\n\nfrom django.http import HttpResponse\nimport django.db.models.manager\nimport django.db.models.query\nimport django.contrib.auth.models\nfrom django.apps import apps as django_apps\n\nfrom ..compat import csrf\nfrom ..models import (Question,\n Response,\n Answer,\n Portfolio,\n SurveyModel,\n QuestionCategory,\n PortfolioPredicate,\n QuestionCategoryPredicate)\nfrom ..mixins import QuestionMixin, SurveyModelMixin\nfrom ..settings import ACCOUNT_MODEL\nfrom ..compat import csrf\n\nclass MatrixView(TemplateView):\n template_name = \"survey/matrix.html\"\n\n def get_context_data(self):\n return {\n 'portfolio_api' :reverse('portfolio_api'),\n 'questioncategory_api': reverse('questioncategory_api'),\n }\n\ndef select_keys(obj, ks):\n d = {}\n for k in ks:\n d[k] = getattr(obj, k)\n return d\n\n\ndef encode_json(obj):\n\n if isinstance(obj, django.contrib.auth.models.User):\n d = select_keys(obj, [\n 'first_name',\n 'last_name',\n 'email',\n 'username',\n ])\n d.update({\n 'id': obj.email\n })\n return d\n if isinstance(obj, Response):\n return select_keys(obj, [\n 'survey',\n 'answers',\n 'user',\n ])\n elif isinstance(obj, Answer):\n return select_keys(obj, [\n 'created_at',\n 'updated_at',\n 'question',\n 'index',\n 'body',\n ])\n elif isinstance(obj, SurveyModel):\n return select_keys(obj, [\n 'start_date',\n 'end_date',\n 'title',\n 'description',\n 'published',\n 'quizz_mode',\n 'one_response_only',\n 'questions',\n ])\n elif isinstance(obj, Question):\n d = select_keys(obj, [\n 'text',\n 'question_type',\n 'has_other',\n 'choices',\n 'order',\n 'correct_answer',\n 'required',\n ])\n d.update({\n 'id': ':'.join([obj.survey.slug, str(obj.order)])\n })\n return d\n\n\n elif isinstance(obj, Portfolio):\n d = select_keys(obj, [\n 'title',\n 'slug',\n ])\n d.update({\n 'predicates': obj.predicates.order_by('order')\n })\n return d\n elif isinstance(obj, QuestionCategory):\n d = select_keys(obj, [\n 'title',\n 'slug',\n ])\n d.update({\n 'predicates': obj.predicates.order_by('order')\n })\n return d\n elif isinstance(obj, PortfolioPredicate):\n return select_keys(obj, [\n 'operator',\n 'operand',\n 'property',\n 'filterType',\n ])\n elif isinstance(obj, QuestionCategoryPredicate):\n return select_keys(obj, [\n 'operator',\n 'operand',\n 'property',\n 'filterType',\n ])\n\n elif isinstance(obj, datetime.datetime):\n return obj.isoformat()\n elif isinstance(obj, django.db.models.manager.Manager):\n return obj.all()\n elif isinstance(obj, django.db.models.query.QuerySet):\n return list(obj)\n else:\n return obj\n\ndef pretty_json(obj, *args, **kw):\n return json.dumps(obj, sort_keys=True, indent=4, separators=(',', ': '), *args, **kw)\n\nclass MatrixApi(View):\n def get(self, request):\n responses = Response.objects.all()\n\n return HttpResponse(pretty_json(responses, default=encode_json),\n content_type='application/json')\n\n\nclass PortfolioView(TemplateView):\n template_name = \"survey/categorize.html\"\n\n def get_context_data(self, *args, **kwargs):\n context = super(PortfolioView, self).get_context_data(\n *args, **kwargs)\n context.update(csrf(self.request))\n context.update({\n 'category_api': reverse('portfolio_api'),\n })\n return context\n\nclass QuestionCategoryView(TemplateView):\n template_name = \"survey/categorize.html\"\n\n def get_context_data(self, *args, **kwargs):\n context = super(QuestionCategoryView, self).get_context_data(\n *args, **kwargs)\n context.update(csrf(self.request))\n context.update({\n 'category_api': reverse('questioncategory_api'),\n })\n return context\n\n\n\ndef get_account_model():\n \"\"\"\n Returns the ``Account`` model that is active in this project.\n \"\"\"\n try:\n return django_apps.get_model(ACCOUNT_MODEL)\n except ValueError:\n raise ImproperlyConfigured(\n \"ACCOUNT_MODEL must be of the form 'app_label.model_name'\")\n except LookupError:\n raise ImproperlyConfigured(\"ACCOUNT_MODEL refers to model '%s'\"\\\n\" that has not been installed\" % ACCOUNT_MODEL)\n\nclass CategoryApi(View):\n # override in subclasses\n categoryModel = None\n predicateModel = None\n objectModel = None\n\n def get(self, request):\n\n categories = list(self.categoryModel.objects.all())\n # accounts = get_account_model().objects.all()\n objects = self.objectModel.objects.all()\n\n data = {\n 'categories': categories,\n 'objects': objects,\n }\n\n return HttpResponse(pretty_json(data, default=encode_json),\n content_type='application/json')\n\n\n def post(self, request):\n category = json.loads(request.body)\n\n if category['slug'] is None:\n # create\n c = self.categoryModel(title=category['title'])\n c.save()\n else:\n # update\n c = self.categoryModel.objects.get(slug=category['slug'])\n c.title = category['title']\n c.save()\n\n\n # always update predicates\n c.predicates.all().delete()\n for i, predicateData in enumerate(category['predicates']):\n predicate = self.predicateModel(operator=predicateData['operator'],\n operand=predicateData['operand'],\n property=predicateData['property'],\n filterType=predicateData['filterType'],\n order=i,\n category=c)\n predicate.save()\n\n\n return HttpResponse(pretty_json(c, default=encode_json), content_type='application/json')\n\nclass PortfolioApi(CategoryApi):\n categoryModel = Portfolio\n predicateModel = PortfolioPredicate\n objectModel = get_account_model()\n\nclass QuestionCategoryApi(CategoryApi):\n categoryModel = QuestionCategory\n predicateModel = QuestionCategoryPredicate\n objectModel = Question\n\n\n","sub_path":"survey/views/matrix.py","file_name":"matrix.py","file_ext":"py","file_size_in_byte":8358,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"}
+{"seq_id":"91756677","text":"N=int(input())\nd={}\nans=0\nfor n in range(N):\n S=input()\n if S in d:\n d[S]+=1\n else:\n d[S]=1\nM=int(input())\nfor m in range(M):\n T=input()\n if T in d:\n d[T]-=1\n else:\n d[T]=1\nfor k in d:\n if d[k]>ans:\n ans=d[k]\nprint(ans)\n","sub_path":"ABC/ABC_091/abc091b.py","file_name":"abc091b.py","file_ext":"py","file_size_in_byte":276,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"}
+{"seq_id":"606474067","text":"# Copyright (c) 2001-2015, Canal TP and/or its affiliates. All rights reserved.\n#\n# This file is part of Navitia,\n# the software to build cool stuff with public transport.\n#\n# powered by Canal TP (www.canaltp.fr).\n# Help us simplify mobility and open public transport:\n# a non ending quest to the responsive locomotion way of traveling!\n#\n# LICENCE: 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 published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU 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# Stay tuned using\n# twitter @navitia\n# IRC #navitia on freenode\n# https://groups.google.com/d/forum/navitia\n# www.navitia.io\nimport json\nimport os\nimport urllib.request\nfrom time import sleep\n\nimport requests\n\nfrom tests.utils import (\n assert_in_memory_zip_equals_ref_zip_file,\n assert_in_memory_zip_contains_expected_files,\n _get_file_fixture_full_path,\n assert_files_equals,\n)\n\n\nclass AbstractRequestClient:\n def get_url(self):\n return \"http://{host}\".format(host=os.getenv(\"TARTARE_WS_HOST\"))\n\n def get_test_relative_path(self, relative_path):\n return \"{}/{}\".format(os.path.dirname(os.path.dirname(__file__)), relative_path)\n\n def get_functional_relative_path(self, relative_path):\n return self.get_test_relative_path(os.path.join(\"functional\", relative_path))\n\n def get_fixtures_relative_path(self, relative_path):\n return self.get_test_relative_path(os.path.join(\"fixtures\", relative_path))\n\n def get(self, uri):\n return requests.get(self.get_url() + uri)\n\n def delete(self, uri):\n return requests.delete(self.get_url() + uri)\n\n def post(self, uri, payload=None, files=None, headers=None):\n return requests.post(self.get_url() + uri, json=payload, files=files, headers=headers)\n\n def put(self, uri, payload=None, headers=None):\n headers = headers if headers else {\"Content-Type\": \"application/json\"}\n return requests.put(self.get_url() + uri, json=payload, headers=headers)\n\n def get_json_from_dict(self, dict):\n return json.dumps(dict)\n\n def get_dict_from_response(self, response):\n return json.loads(response.content)\n\n def reset_api(self):\n for resource in [\"/contributors\", \"/coverages\"]:\n raw = self.get(resource)\n contributors = self.get_dict_from_response(raw)[resource]\n\n for contributor in contributors:\n raw = self.delete(resource + \"/\" + contributor[\"id\"])\n self.assert_sucessful_call(raw, 204)\n\n def get_file_stream(self, contributor_id, data_source_id, expected_filename=None, resource=\"contributors\"):\n contributor_or_coverage = self.get_dict_from_response(self.get(\"/{}/{}\".format(resource, contributor_id)))[\n resource\n ][0]\n gridfs_id = next(\n data_source[\"data_sets\"][0][\"gridfs_id\"]\n for data_source in contributor_or_coverage[\"data_sources\"]\n if data_source[\"id\"] == data_source_id\n )\n\n # get export file\n raw = self.get(\"/files/{gridfs_id}/download\".format(gridfs_id=gridfs_id))\n if expected_filename:\n import re\n\n d = raw.headers[\"Content-Disposition\"]\n fname = re.findall(\"filename=(.+)\", d)\n assert fname[0] == expected_filename, print(fname[0])\n\n return raw.content\n\n def assert_export_zip_file_equals_ref_file(\n self,\n contributor_or_coverage_id,\n data_source_id,\n ref_file,\n expected_filename=None,\n resource=\"contributors\",\n work_dir=None,\n skip_files=None,\n only_files=None,\n ):\n skip_files = skip_files if skip_files else []\n only_files = only_files if only_files else []\n file_stream = self.get_file_stream(contributor_or_coverage_id, data_source_id, expected_filename, resource)\n assert_in_memory_zip_equals_ref_zip_file(file_stream, ref_file, work_dir, skip_files, only_files)\n\n def assert_export_zip_file_contains_expected_files(\n self,\n contributor_or_coverage_id,\n data_source_id,\n expected_filename=None,\n expected_files=[],\n resource=\"contributors\",\n work_dir=None,\n ):\n file_stream = self.get_file_stream(contributor_or_coverage_id, data_source_id, expected_filename, resource)\n assert_in_memory_zip_contains_expected_files(file_stream, work_dir, expected_files)\n\n def assert_export_file_equals_ref_file(\n self, contributor_or_coverage_id, data_source_id, ref_file, expected_filename=None, resource=\"contributors\"\n ):\n file_stream = self.get_file_stream(contributor_or_coverage_id, data_source_id, expected_filename, resource)\n ref_file = _get_file_fixture_full_path(ref_file)\n assert_files_equals(file_stream, ref_file)\n\n def assert_export_file_is_present(\n self, contributor_or_coverage_id, data_source_id, expected_filename=None, resource=\"contributors\"\n ):\n # 'AssertionError' will be thrown by the method 'get_file_stream' if 'expected_filename' is not found\n self.get_file_stream(contributor_or_coverage_id, data_source_id, expected_filename, resource)\n\n def replace_servers_ip_in_fixture(\n self, fixture_path, server_ip_env_variable=\"HTTP_SERVER_IP\", tartare_ws_host=\"TARTARE_WS_HOST\"\n ):\n with open(self.get_fixtures_relative_path(fixture_path), \"rb\") as file:\n json_file = json.load(file)\n if \"data_sources\" in json_file:\n for data_source in json_file[\"data_sources\"]:\n if \"input\" in data_source and \"url\" in data_source[\"input\"]:\n data_source[\"input\"][\"url\"] = data_source[\"input\"][\"url\"].format(\n HTTP_SERVER_IP=os.getenv(server_ip_env_variable)\n )\n if \"processes\" in json_file:\n for process in json_file[\"processes\"]:\n if \"parameters\" in process and \"urls\" in process[\"parameters\"]:\n for i, url in enumerate(process[\"parameters\"][\"urls\"]):\n process[\"parameters\"][\"urls\"][i] = url.format(TARTARE_WS_HOST=os.getenv(tartare_ws_host))\n return json_file\n\n def wait_for_jobs_to_exist(self, action_type, number, nb_retries_max=20):\n retry = 0\n while retry < nb_retries_max:\n jobs = self.get_dict_from_response(self.get(\"/jobs\"))[\"jobs\"]\n jobs_matching = [job for job in jobs if job[\"action_type\"] == action_type]\n if len(jobs_matching) != number:\n sleep(1)\n retry += 1\n else:\n if number == 1:\n return jobs_matching[0]\n break\n assert retry < nb_retries_max, print(\"job {} reached max waiting time ({})\".format(action_type, nb_retries_max))\n\n def wait_for_all_jobs_to_be_done(self):\n sleep(3)\n raw = self.get(\"/jobs\")\n for job in self.get_dict_from_response(raw)[\"jobs\"]:\n self.wait_and_assert_for_job_to_be_done(job[\"id\"])\n\n def wait_and_assert_for_job_to_be_done(self, job_id, step=None, nb_retries_max=15, break_if=\"done\", sleep_time=1):\n retry = 0\n while retry < nb_retries_max:\n raw = self.get(\"/jobs/\" + job_id)\n job = self.get_dict_from_response(raw)[\"jobs\"][0]\n status = job[\"state\"]\n if status == break_if or status == \"failed\":\n break\n else:\n sleep(sleep_time)\n retry += 1\n\n raw = self.get(\"/jobs/\" + job_id)\n job = self.get_dict_from_response(raw)[\"jobs\"][0]\n assert job[\"state\"] == break_if, f\"state {job['state']} != {break_if}\"\n if step:\n assert job[\"step\"] == step, f\"step ${job['step']} != {step}\"\n\n def assert_status_is(self, raw, status):\n assert raw.status_code == status, print(self.get_dict_from_response(raw))\n\n def assert_sucessful_call(self, raw, code=200):\n self.assert_status_is(raw, code)\n\n def assert_sucessful_create(self, raw):\n self.assert_status_is(raw, 201)\n\n def full_export(self, contributor_id, coverage_id, current_date=None):\n resp = self.post(\"/contributors/{}/actions/export\".format(contributor_id))\n self.assert_sucessful_create(resp)\n job_id = self.get_dict_from_response(resp)[\"job\"][\"id\"]\n self.wait_and_assert_for_job_to_be_done(job_id, \"save_contributor_export\")\n date_option = \"?current_date=\" + current_date if current_date else \"\"\n resp = self.post(\"/coverages/{}/actions/export{}\".format(coverage_id, date_option))\n self.assert_sucessful_create(resp)\n job_id = self.get_dict_from_response(resp)[\"job\"][\"id\"]\n self.wait_and_assert_for_job_to_be_done(job_id, \"save_coverage_export\")\n return resp\n\n def init_contributor(self, fixture, server_ip_env_variable=\"HTTP_SERVER_IP\", tartare_ws_host=\"TARTARE_WS_HOST\"):\n json_file = self.replace_servers_ip_in_fixture(fixture, server_ip_env_variable, tartare_ws_host)\n raw = self.post(\"/contributors\", json_file)\n self.assert_sucessful_create(raw)\n\n return self.get_dict_from_response(raw)[\"contributors\"][0]\n\n def init_coverage(self, fixture, server_ip_env_variable=\"HTTP_SERVER_IP\", tartare_ws_host=\"TARTARE_WS_HOST\"):\n json_file = self.replace_servers_ip_in_fixture(fixture, server_ip_env_variable, tartare_ws_host)\n raw = self.post(\"/coverages\", json_file)\n self.assert_sucessful_create(raw)\n\n def export(self, contributor_or_coverage, model_id, current_date=None):\n raw = self.post(\n \"/{}/{}/actions/export{}\".format(\n contributor_or_coverage, model_id, \"\" if not current_date else \"?current_date=\" + current_date\n )\n )\n self.assert_sucessful_create(raw)\n return self.get_dict_from_response(raw)[\"job\"][\"id\"]\n\n def contributor_export(self, contributor_id, current_date=None):\n return self.export(\"contributors\", contributor_id, current_date)\n\n def coverage_export(self, coverage_id, current_date=None):\n return self.export(\"coverages\", coverage_id, current_date)\n\n def fetch_export_fixture(self, export_fixture):\n ref_file_url = \"http://{}/regression_tests/{}\".format(os.getenv(\"REGRESSION_TEST_WEBDAV\"), export_fixture)\n local_destination = export_fixture.split(os.sep)[1] if os.sep in export_fixture else export_fixture\n dest_full_file_name = _get_file_fixture_full_path(local_destination)\n urllib.request.urlretrieve(ref_file_url, dest_full_file_name)\n\n @staticmethod\n def assert_validity_period(object, data_source_id, validity_period_to_compare=None):\n data_set = next(\n data_source[\"data_sets\"][0] for data_source in object[\"data_sources\"] if data_source[\"id\"] == data_source_id\n )\n assert \"validity_period\" in data_set\n assert data_set[\"validity_period\"]\n if validity_period_to_compare:\n assert data_set[\"validity_period\"] == validity_period_to_compare, print(data_set[\"validity_period\"])\n","sub_path":"tests/functional/abstract_request_client.py","file_name":"abstract_request_client.py","file_ext":"py","file_size_in_byte":11650,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"}
+{"seq_id":"493342950","text":"class Customer:\n\n def __init__(self, first_name, last_name, age, street, city, state, zip):\n self.first_name = first_name\n self.last_name = last_name\n self.age = age\n self.street = street\n self.city = city\n self.state = state\n self.zip = zip\n\n def __str__(self):\n fmt = \"{} {}\\n{}\\n{}, {} {}\"\n return fmt.format(self.first_name, self.last_name, self.street,\n self.city, self.state, self.zip)\n","sub_path":"EXAMPLES/oodesign/exercises/customers.py","file_name":"customers.py","file_ext":"py","file_size_in_byte":486,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"}
+{"seq_id":"232823785","text":"def resolve():\n # 処理時間が足りない\n # n, k = map(int, input().split())\n # pl = list(map(int, input().split()))\n # pl_i = []\n # pl_max = 0\n # s = 0\n # for i in range(n):\n # for j in range(1, pl[i]+1):\n # s += j\n # pl_i.append(s / pl[i])\n # s = 0\n # for m in range(n - k + 1):\n # pl_max = max(pl_max, sum(pl_i[m:m + k]))\n # print(pl_max)\n\n n, k = map(int, input().split())\n p = list(map(int, input().split()))\n tmp = sum(p[:k])\n res = tmp\n for i in range(n - k):\n tmp -= p[i]\n tmp += p[i + k]\n res = max(res, tmp)\n print((res + k) / 2)\n\n\nimport sys\nfrom io import StringIO\nimport unittest\n\n\nclass TestClass(unittest.TestCase):\n def assertIO(self, input, output):\n stdout, stdin = sys.stdout, sys.stdin\n sys.stdout, sys.stdin = StringIO(), StringIO(input)\n resolve()\n sys.stdout.seek(0)\n out = sys.stdout.read()[:-1]\n sys.stdout, sys.stdin = stdout, stdin\n self.assertEqual(out, output)\n\n def test_入力例_1(self):\n input = \"\"\"5 3\n1 2 2 4 5\"\"\"\n output = \"\"\"7.000000000000\"\"\"\n self.assertIO(input, output)\n\n def test_入力例_2(self):\n input = \"\"\"4 1\n6 6 6 6\"\"\"\n output = \"\"\"3.500000000000\"\"\"\n self.assertIO(input, output)\n\n def test_入力例_3(self):\n input = \"\"\"10 4\n17 13 13 12 15 20 10 13 17 11\"\"\"\n output = \"\"\"32.000000000000\"\"\"\n self.assertIO(input, output)\n\n\nif __name__ == \"__main__\":\n unittest.main()\n","sub_path":"ABC-D/ABC154D.py","file_name":"ABC154D.py","file_ext":"py","file_size_in_byte":1553,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"}
+{"seq_id":"419271337","text":"\nfrom keras.engine import Layer, InputSpec\nfrom keras.layers.wrappers import Wrapper\nfrom keras import backend as K\n\n\n\nclass Recursive(Wrapper):\n \"\"\"This wrapper applies any model recursively\n\n Input (samples, nT0, nY, nX)\n Layer must map (samples, nT0, nY, nX) => (samples, nY, nX)\n Output (samples, nT, nY, nX)\n\n # Arguments\n layer: a layer instance.\n \"\"\"\n def __init__(self, layer, nT, **kwargs):\n self.supports_masking = True\n self.nT = nT\n self.return_sequences = True\n super(Recursive, self).__init__(layer, **kwargs)\n\n def build(self, input_shape):\n assert len(input_shape) >= 3\n self.input_spec = [InputSpec(shape=input_shape)]\n if K._BACKEND == 'tensorflow':\n raise Exception('Recursive Layer is not implemented for TensorFlow')\n if not self.layer.built:\n self.layer.build(input_shape)\n self.layer.built = True\n super(Recursive, self).build()\n\n def get_output_shape_for(self, input_shape):\n child_output_shape = self.layer.get_output_shape_for(input_shape)\n return (input_shape[0], self.nT) + child_output_shape[1:]\n\n def call(self, X, mask=None):\n\n input_shape = self.input_spec[0].shape\n nT0 = input_shape[1]\n\n input = K.zeros_like(X) # (samples, timesteps, input_dim)\n input = input[:,:1,:,:]\n input = K.repeat_elements(input, self.nT, 1)\n\n def step(x, states): # x = (samples,1,input_dims) - currently zeros\n prev = states[0] # s = (samples,nT0,input_dims)\n\n next_frame = self.layer.call(prev)\n next_state = K.concatenate([prev[:,1:,:,:],K.reshape(next_frame,(-1,1)+input_shape[2:])],axis=1)\n return next_frame, [next_state]\n\n last_output, outputs, states = K.rnn(step, input, initial_states=[X])\n\n if self.return_sequences:\n return outputs\n else:\n return last_output\n","sub_path":"src/predictAtari/cnnN_RecursiveLayer.py","file_name":"cnnN_RecursiveLayer.py","file_ext":"py","file_size_in_byte":1970,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"}
+{"seq_id":"310009344","text":"#------------------------------------------------------------------------------\n# Mach-8: The Virtual Machinery Playpen \n#\n# blackchip.org, Inspired by the Vintage Computer Club. \n# All rites reversed (K) 2011, Reprint what you like.\n#\n# $Id: test_stack.py 96 2011-12-12 22:29:35Z mcgann $\n#------------------------------------------------------------------------------\nfrom mach8.assembly import *\nfrom mach8_test import suite\nfrom mach8_test.harness import execution\n\nclass TestStack(execution.TestHarness):\n \n def test_pha(self):\n suite.banner(self.test_pha) \n a = self.a \n \n _; a(lda_imm, 0x11) \n _; a(pha) \n _; a(lda_imm, 0x22) \n _; a(pha) \n \n self.run_test() \n self.assertEquals(0x22, self.mem[0x01fe])\n self.assertEquals(0x11, self.mem[0x01ff])\n \n def test_pla(self):\n suite.banner(self.test_pla) \n a = self.a \n \n _; a(pha) \n _; a(pha) \n _; a(ldy_imm, 0x22) \n _; a(sty_abs, 0x1fe) \n _; a(ldy_imm, 0x11) \n _; a(sty_abs, 0x1ff) \n _; a(pla) \n _; a(pla) \n \n self.run_test() \n self.assertEquals(0x11, self.cpu.a) \n \n def test_pla_zero(self):\n suite.banner(self.test_pla_zero)\n a = self.a\n\n _; a(lda_imm, 0x00)\n _; a(pha)\n _; a(lda_imm, 0x22)\n _; a(pla)\n \n self.run_test() \n self.assertEquals(0, self.cpu.a)\n self.assertTrue(self.cpu.z and not self.cpu.n)\n \n def test_pla_negative(self):\n suite.banner(self.test_pla_negative) \n a = self.a \n\n _; a(lda_imm, 0x81) \n _; a(pha) \n _; a(lda_imm, 0x00)\n _; a(pla)\n \n self.run_test() \n self.assertEquals(0x81, self.cpu.a)\n self.assertTrue(not self.cpu.z and self.cpu.n)\n\n def test_phx(self):\n suite.banner(self.test_phx) \n a = self.a \n \n _; a(ldx_imm, 0x11) \n _; a(phx) \n _; a(ldx_imm, 0x22) \n _; a(phx) \n \n self.run_test() \n self.assertEquals(0x22, self.mem[0x01fe])\n self.assertEquals(0x11, self.mem[0x01ff])\n \n def test_plx(self):\n suite.banner(self.test_plx) \n a = self.a \n \n _; a(phx) \n _; a(phx) \n _; a(lda_imm, 0x22) \n _; a(sta_abs, 0x1fe) \n _; a(lda_imm, 0x11) \n _; a(sta_abs, 0x1ff) \n _; a(plx) \n _; a(plx) \n \n self.run_test() \n self.assertEquals(0x11, self.cpu.x) \n \n def test_plx_zero(self):\n suite.banner(self.test_plx_zero) \n a = self.a\n\n _; a(ldx_imm, 0x00)\n _; a(phx)\n _; a(ldx_imm, 0x22)\n _; a(plx)\n \n self.run_test() \n self.assertEquals(0, self.cpu.x)\n self.assertTrue(self.cpu.z and not self.cpu.n)\n\n def test_plx_negative(self):\n suite.banner(self.test_plx_negative) \n a = self.a\n\n _; a(ldx_imm, 0x81)\n _; a(phx) \n _; a(ldx_imm, 0x00)\n _; a(plx) \n \n self.run_test() \n self.assertEquals(0x81, self.cpu.x)\n self.assertTrue(not self.cpu.z and self.cpu.n)\n\n def test_phy(self):\n suite.banner(self.test_phy) \n a = self.a \n \n _; a(ldy_imm, 0x11) \n _; a(phy) \n _; a(ldy_imm, 0x22) \n _; a(phy) \n \n self.run_test() \n self.assertEquals(0x22, self.mem[0x01fe])\n self.assertEquals(0x11, self.mem[0x01ff])\n \n def test_ply(self):\n suite.banner(self.test_ply) \n a = self.a \n \n _; a(phy) \n _; a(phy) \n _; a(lda_imm, 0x22) \n _; a(sta_abs, 0x1fe) \n _; a(lda_imm, 0x11) \n _; a(sta_abs, 0x1ff) \n _; a(ply) \n _; a(ply) \n \n self.run_test() \n self.assertEquals(0x11, self.cpu.y) \n \n def test_ply_zero(self):\n suite.banner(self.test_ply_zero) \n a = self.a\n\n _; a(ldy_imm, 0x00)\n _; a(phy)\n _; a(ldy_imm, 0x22)\n _; a(ply) \n \n self.run_test() \n self.assertEquals(0, self.cpu.y)\n self.assertTrue(self.cpu.z and not self.cpu.n)\n\n def test_ply_negative(self):\n suite.banner(self.test_ply_negative) \n a = self.a\n\n _; a(ldy_imm, 0x81) \n _; a(phy) \n _; a(ldy_imm, 0x00)\n _; a(ply)\n \n self.run_test() \n self.assertEquals(0x81, self.cpu.y)\n self.assertTrue(not self.cpu.z and self.cpu.n)\n\n\n def test_php(self):\n suite.banner(self.test_php) \n a = self.a\n self.cpu.sr = 0b11101011\n \n _; a(php) \n \n self.run_test() \n self.assertEquals(0b11101011, self.mem[0x1ff])\n\n def test_plp(self):\n suite.banner(self.test_plp) \n a = self.a \n \n _; a(lda_imm, b8(0b11101011))\n _; a(pha) \n _; a(cmp_imm, 1)\n _; a(plp) \n \n self.run_test() \n # Include the break flag!\n self.assertEquals(0b11111011, self.cpu.sr) \n \n def test_txs(self):\n suite.banner(self.test_txs) \n a = self.a\n\n _; a(lda_imm, 0x11) \n _; a(pha) \n _; a(lda_imm, 0x22) \n _; a(pha) \n _; a(ldx_imm, 0xfe) \n _; a(txs)\n _; a(pla) \n \n self.run_test() \n self.assertEquals(0x11, self.cpu.a);\n \n def test_tsx(self):\n suite.banner(self.test_tsx) \n a = self.a \n \n _; a(pha)\n _; a(pha)\n _; a(pha) \n\n _; a(tsx) \n \n _; a(plp)\n _; a(plp) \n _; a(plp) \n \n self.run_test() \n self.assertEquals(0xfc, self.cpu.x)\n\n \n","sub_path":"tests/mach8_test/unit/instructions/test_stack.py","file_name":"test_stack.py","file_ext":"py","file_size_in_byte":6169,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"}
+{"seq_id":"449461251","text":"from django.shortcuts import render\nfrom .forms import ValidateForm\n# Create your views here.\n\ndef index(request):\n context_data = {}\n if request.method == 'POST':\n validateform = ValidateForm(request.POST, request.FILES)\n if validateform.is_valid():\n validate = validateform.save(commit=False)\n validate.save()\n context_data = {\n 'form': validateform,\n 'validated': validate.validate_card_file()\n }\n return render(request, 'index.html', context_data)\n else:\n validateform = ValidateForm()\n context_data = { 'form': validateform }\n return render(request, 'index.html', context_data)\n\ndef about(request):\n return render(request, 'about.html')\n","sub_path":"validate/credit_card/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":772,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"}
+{"seq_id":"541731623","text":"# coding:utf-8\nfrom django.shortcuts import render, redirect, get_object_or_404\nfrom django.http import HttpResponseNotAllowed\nfrom django.views.decorators.http import require_http_methods\nfrom django.contrib.auth import authenticate, login, logout\nfrom django.contrib.auth.models import User\nfrom django.contrib import messages\nfrom django.core.urlresolvers import reverse\nfrom django.core.paginator import Paginator, PageNotAnInteger, EmptyPage\n\nfrom account.forms import LoginForm, UserCreationForm\nfrom account.models import UserExtra\n\nfrom discuss.models import Topic, Reply\n\n\n@require_http_methods(['POST', 'GET'])\ndef member_login(request):\n _next = request.GET.get('next', reverse('index'))\n\n if request.user.is_authenticated():\n return redirect(_next)\n\n if request.method == 'POST':\n\n form = LoginForm(request.POST)\n if form.is_valid():\n user = authenticate(username=form.cleaned_data['username'],\n password=form.cleaned_data['password'])\n if user:\n login(request, user)\n messages.info(request, u'登录成功, 欢迎回来')\n return redirect(_next)\n else:\n form.add_error(None, u'用户名或密码错误')\n return render(request, 'account/login_form.html', {'form': form})\n else:\n return render(request, 'account/login_form.html', {'form': form})\n\n form = LoginForm()\n return render(request, 'account/login_form.html', {'form': form})\n\n\n@require_http_methods(['POST'])\ndef member_logout(request):\n _next = request.GET.get('next', reverse('index'))\n\n logout(request)\n messages.info(request, u'已登出')\n\n return redirect(_next)\n\n\n@require_http_methods(['POST', 'GET'])\ndef member_register(request):\n _next = request.GET.get('next', reverse('index'))\n\n if request.user.is_authenticated():\n return redirect(_next)\n\n if request.method == 'POST':\n form = UserCreationForm(request.POST)\n if form.is_valid():\n user = form.save()\n UserExtra.objects.create(user=user)\n # https://docs.djangoproject.com/en/1.7/topics/auth/default/#django.contrib.auth.login\n auth_user = authenticate(\n username=form.cleaned_data['username'],\n password=form.cleaned_data['password1']\n )\n login(request, auth_user)\n return redirect(_next)\n else:\n return render(request, 'account/register_form.html', {'form': form})\n\n form = UserCreationForm()\n return render(request, 'account/register_form.html', {'form': form})\n\n\ndef member_profile(request, user_id):\n user = get_object_or_404(User, id=user_id)\n\n topics = Topic.objects.filter(user=user).order_by('-created_at')\n replies = Reply.objects.filter(user=user).order_by('-created_at')\n\n return render(request, 'account/user_profile.html', {'member': user, 'topics': topics, 'replies': replies})\n\n\ndef member_topics(request, user_id):\n user = get_object_or_404(User, id=user_id)\n\n topic_list = Topic.objects.filter(user=user).order_by('-created_at')\n\n paginator = Paginator(topic_list, 25)\n page = request.GET.get('page')\n\n try:\n topics = paginator.page(page)\n except (PageNotAnInteger, EmptyPage):\n topics = paginator.page(1)\n\n return render(request, 'account/user_topics.html', {'member': user, 'topics': topics})\n\n\ndef member_replies(request, user_id):\n user = get_object_or_404(User, id=user_id)\n\n reply_list = Reply.objects.filter(user=user).order_by('-created_at')\n\n paginator = Paginator(reply_list, 25)\n page = request.GET.get('page')\n\n try:\n replies = paginator.page(page)\n except (PageNotAnInteger, EmptyPage):\n replies = paginator.page(1)\n\n\n return render(request, 'account/user_replies.html', {'member': user, 'replies': replies})\n\n","sub_path":"account/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3923,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"}
+{"seq_id":"440810707","text":"import time, os, os.path, importlib\nproblems = [int(f.split('.')[0][1:]) for f in os.listdir() if f[0]=='_' and f[1]!='_']\nproblems.sort()\nproblems = ['_' + str(f) for f in problems]\n\nstart_time = time.time()\nfor f in problems:\n pre = time.time()\n importlib.import_module(f)\n print(f[1:]+' time: ' + str(round(time.time()-pre, 6)))\nprint('Total time: ' + str(round(time.time()-start_time, 6)))\n","sub_path":"time_all.py","file_name":"time_all.py","file_ext":"py","file_size_in_byte":403,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"}
+{"seq_id":"244984368","text":"\"\"\"\nФункция вызывает окно удаления кортежа\nПолучает: -\nВозвращает: -\nАвтор: Матвеев В.Е., Демидов И.Д., Будин А.М.\n\"\"\"\nimport tkinter as tk\nimport tkinter.ttk as ttk\nimport pandas as pd\nimport numpy as np\nimport os, sys\nsys.path.insert(0, os.path.abspath(\"../Library\"))\nimport bd\nsys.path.insert(0, os.path.abspath(\"../Scripts\"))\nimport app as m\nfrom tkinter import messagebox as mb\n\n\nclass Delete(tk.Toplevel):\n def __init__(self, parent_):\n '''\n Функция вызывает окно удаления кортежа\n Получает: -\n Возвращает: -\n Автор: Демидов И.Д\n '''\n super().__init__(parent_)\n global parent\n parent = parent_\n self.title('Удаление смартфона')\n self.geometry('250x100+400+300')\n self.resizable(False, False)\n\n def delete_code():\n '''\n Функция удаляет выбранный кортеж\n Получает: -\n Возвращает: -\n Автор: Демидов И.Д\n '''\n global parent\n if(choice.get() == ''):\n mb.showerror(\"Ошибка\", \"Введите код продукта\")\n elif (m.mdf.loc[len(m.mdf)-1][\"Product Code\"] < int(choice.get())):\n mb.showerror(\"Ошибка\", \"Нет такого продукта\")\n else:\n m.mdf = m.mdf.drop(np.where(m.mdf['Product Code'] == int(choice.get()))[0])\n for widget in parent.winfo_children():\n widget.destroy()\n bd.Table(parent, m.mdf)\n self.destroy()\n\n\n label_choice = ttk.Label(self, text='''Введите код товара, который хотите удалить''')\n label_choice.grid(row=0, column=0, columnspan=2)\n choice = ttk.Entry(self)\n choice.grid(row=1, column=0, columnspan=2)\n cancel_but = ttk.Button(self, text='Отмена', command=self.destroy)\n cancel_but.grid(row=2, column=1)\n del_but = ttk.Button(self, text='Удалить', command=delete_code)\n del_but.grid(row=2, column=0)\n del_but.bind('')\n","sub_path":"Scripts/delete.py","file_name":"delete.py","file_ext":"py","file_size_in_byte":2331,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"}
+{"seq_id":"554676053","text":"# Neutron star thermal evolution\n# --------------------------------------\n# main.py\n# --------------------------------------\n# This is the main module of\n# the code. Use it to start\n# the simulation.\n\nimport matplotlib.pyplot as plt\nimport timeit\nimport time\n\nfrom data import loaddata\nfrom physics import tite_1e9\nfrom computation import PDEsolver\nfrom other import plot\nfrom control.manager import *\nfrom physics import tite\n\n\ndef data_init():\n\n print ('Simulation of neutron star cooling starts... \\n')\n\n loaddata.star_model_data_init()\n if(model_file):\n tite_1e9.init(log_rho_b,rho_star)\n else:\n tite.tite_init()\n loaddata.TiTe_data_init()\n loaddata.superfluid_data_init()\n loaddata.eff_mass_data_init()\n\n print ('All data files are loaded.\\n')\n\ndef config_reader():\n\n global left_boundary, right_boundary, power, duration\n\n config = numpy.loadtxt(source_cfg)\n\n left_boundary = config[:,0]\n right_boundary = config[:,1]\n power = config[:,2]\n duration = config[:,3]\n\ndef main():\n\n output_1, output_2 = loaddata.create_output_files()\n\n print ('Files for output data are created.\\n')\n print ('Generating C,Q,k tables...\\n')\n\n PDEsolver.TableCreator()\n PDEsolver.interpolation_on_tables()\n PDEsolver.init()\n PDEsolver.time_derivative_init()\n PDEsolver.time_derivative_iso_regime_init()\n\n if(source_trigger):\n\n print ('Heat source is turned on\\n')\n\n config_reader()\n number_of_simulations = len(power)\n\n print ('Number of simulations = %i\\n \\n' % (number_of_simulations))\n print ('Sources\\' properties:\\n')\n print ('Number Left Right Power Duration(Left and Right source boundaries in density units)')\n print ('-------------------------')\n\n for i in range(0,number_of_simulations):\n print ('%2i %1.2e %1.2e %1.2e %1.2e' % (i, left_boundary[i], right_boundary[i], power[i], duration[i]))\n print ('-------------------------\\n')\n\n for i in range(10,0,-1):\n print ('Simulation begins in %d sec...' % i)\n time.sleep(1)\n print (' ')\n\n start = timeit.default_timer()\n\n for simulation_number in range(0,number_of_simulations):\n\n if simulation_number != 0:\n PDEsolver.re_init()\n PDEsolver.source_initialization(duration[simulation_number],power[simulation_number],\n left_boundary[simulation_number],right_boundary[simulation_number])\n if(source_visualise):\n PDEsolver.source_visualisation(simulation_number)\n PDEsolver.solve_PDE_with_source(simulation_number,number_of_simulations)\n\n else:\n\n for i in range(10,0,-1):\n print ('Simulation begins in %d sec...' % i)\n time.sleep(1)\n print ('')\n\n start = timeit.default_timer()\n PDEsolver.solve_PDE(output_1, output_2)\n\n stop = timeit.default_timer()\n\n print (' ')\n print ('calculation time: %3.5f sec' % (stop - start))\n\n\ndef show_cooling_curves():\n\n temp_data_1 = numpy.loadtxt(output_file_1)\n temp_data_2 = numpy.loadtxt(output_file_2)\n\n plt.title('Cooling curves')\n labels = []\n for i in range (0,len(time_points)):\n labels.append(str(time_points[i]))\n\n line_styles = ['b-','y-','g-','r-','m-','c-','b--','y--','g--', 'r--', 'm--', 'c--']\n X = numpy.outer(temp_data_2[:,0],numpy.ones(len(time_points)))\n Y = temp_data_2[:,1:]\n\n plt.plot(numpy.log10(temp_data_1[:,1]) ,numpy.log10(temp_data_1[:,0]),'b--')\n plt.show()\n\n plot.multi_plot(numpy.log10(X), numpy.log10(Y),'$\\mathrm{Temperature profile}$', labels, 1,\n '$\\mathrm{log}_{10} \\\\thinspace \\\\rho \\\\thinspace \\mathrm{(g} \\\\thinspace \\mathrm{cm^{-3})}$', '$\\mathrm{log}_{10} \\\\thinspace \\mathrm{T}^{\\infty} \\mathrm{(K)}$', line_styles[0:len(time_points)], xslace = 'linear', yslace = 'linear')\n\n#config_reader()\n#config_reader_periodic()\n\ndata_init()\nmain()\nshow_cooling_curves()\n\n\n\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":4089,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"}
+{"seq_id":"368936236","text":"from .feature_engineer.fe_count import FeatureCount\nfrom .feature_engineer.fe_stat import FeatureStat\nfrom .feature_engineer.fe_rank import FeatureRank\nfrom .feature_engineer.fe_nlp import FeatureNlp\nfrom .feature_engineer.fe_time import FeatureTime\nfrom .feature_engineer.fe_cumsum import FeatureCumsum\nfrom .feature_engineer.fe_shift import FeatureShift\nfrom .feature_engineer.fe_diff import FeatureDiff\nfrom .file_io.read_data import read_data_from_path\nfrom .models.regressor import CrossLgbRegression, CrossXgbRegression, CrossTabnetRegression\nfrom .models.classifier import CrossLgbBiClassifier, CrossXgbBiClassifier, CrossTabnetBiClassifier\nfrom .process_data import feature_combination, train_test_divide, clip_label\nfrom .process_data import feature_filter, auto_label_encoder\nfrom .process_data.feature_type_recognition import Feature_type_recognition\nfrom .util import log, reduce_mem_usage\n\nclass AutoX():\n def __init__(self, target, train_name, test_name, path, metric='rmse', feature_type = {}, relations = [], id = [], task_type = 'regression', Debug = False):\n self.Debug = Debug\n self.info_ = {}\n self.info_['id'] = id\n self.info_['task_type'] = task_type\n self.info_['target'] = target\n self.info_['feature_type'] = feature_type\n self.info_['relations'] = relations\n self.info_['train_name'] = train_name\n self.info_['test_name'] = test_name\n self.info_['metric'] = metric\n self.dfs_ = read_data_from_path(path)\n if Debug:\n log(\"Debug mode, sample data\")\n self.dfs_[train_name] = self.dfs_[train_name].sample(5000)\n self.info_['max_target'] = self.dfs_[train_name][target].max()\n self.info_['min_target'] = self.dfs_[train_name][target].min()\n if feature_type == {}:\n for table_name in self.dfs_.keys():\n df = self.dfs_[table_name]\n feature_type_recognition = Feature_type_recognition()\n feature_type = feature_type_recognition.fit(df)\n self.info_['feature_type'][table_name] = feature_type\n self.join_simple_tables()\n self.concat_train_test()\n\n self.dfs_['FE_all'] = None\n self.sub = None\n\n # 识别任务类型\n if self.dfs_[self.info_['train_name']][self.info_['target']].nunique() == 2:\n self.info_['task_type'] = 'binary'\n else:\n self.info_['task_type'] = 'regression'\n\n def join_simple_tables(self):\n simple_relations = [x for x in self.info_['relations'] if x['type'] == '1-1' and x['related_to_main_table'] == 'true']\n for relation in simple_relations:\n left_table_name = relation['left_entity']\n right_table_name = relation['right_entity']\n left_on = relation['left_on']\n right_on = relation['right_on']\n if right_table_name in [self.info_['train_name'], self.info_['test_name']]:\n left_table_name, right_table_name = right_table_name, left_table_name\n left_on, right_on = right_on, left_on\n\n skip_name = right_on\n merge_table_name = right_table_name\n merge_table = self.dfs_[merge_table_name].copy()\n\n # rename\n merge_table.columns = [x if x in skip_name else merge_table_name + '__' + x for x in merge_table.columns]\n\n self.dfs_[left_table_name] = self.dfs_[left_table_name].merge(merge_table, left_on=left_on,\n right_on=right_on, how='left')\n del merge_table\n for key_ in self.info_['feature_type'][merge_table_name]:\n if key_ not in self.info_['feature_type'][left_table_name] and key_ not in skip_name:\n self.info_['feature_type'][left_table_name][merge_table_name + '__' + key_] = self.info_['feature_type'][merge_table_name][key_]\n\n def concat_train_test(self):\n self.info_['shape_of_train'] = len(self.dfs_[self.info_['train_name']])\n self.info_['shape_of_test'] = len(self.dfs_[self.info_['test_name']])\n self.dfs_['train_test'] = self.dfs_[self.info_['train_name']].append(self.dfs_[self.info_['test_name']])\n self.dfs_['train_test'].index = range(len(self.dfs_['train_test']))\n\n feature_type_train_test = {}\n for col in self.dfs_['train_test'].columns:\n if col in self.info_['feature_type'][self.info_['train_name']]:\n feature_type_train_test[col] = self.info_['feature_type'][self.info_['train_name']][col]\n else:\n feature_type_train_test[col] = self.info_['feature_type'][self.info_['test_name']][col]\n self.info_['feature_type']['train_test'] = feature_type_train_test\n\n def split_train_test(self):\n self.dfs_['FE_train'] = self.dfs_['FE_all'][:self.info_['shape_of_train']]\n self.dfs_['FE_test'] = self.dfs_['FE_all'][self.info_['shape_of_train']:]\n\n def get_submit(self):\n\n id_ = self.info_['id']\n target = self.info_['target']\n\n # 特征工程\n log(\"start feature engineer\")\n df = self.dfs_['train_test']\n feature_type = self.info_['feature_type']['train_test']\n\n # 时间特征\n log(\"feature engineer: time\")\n featureTime = FeatureTime()\n featureTime.fit(df, df_feature_type=feature_type, silence_cols=id_ + [target])\n log(f\"featureTime ops: {featureTime.get_ops()}\")\n self.dfs_['FE_time'] = featureTime.transform(df)\n\n\n # cumsum特征\n log(\"feature engineer: Cumsum\")\n featureCumsum = FeatureCumsum()\n featureCumsum.fit(df, df_feature_type=feature_type, silence_group_cols=id_ + [target],\n silence_agg_cols=id_ + [target], select_all=False)\n fe_cumsum_cnt = 0\n for key_ in featureCumsum.get_ops().keys():\n fe_cumsum_cnt += len(featureCumsum.get_ops()[key_])\n if fe_cumsum_cnt < 30:\n self.dfs_['FE_cumsum'] = featureCumsum.transform(df)\n log(f\"featureCumsum ops: {featureCumsum.get_ops()}\")\n else:\n self.dfs_['FE_cumsum'] = None\n log(\"ignore featureCumsum\")\n\n\n # shift特征\n log(\"feature engineer: Shift\")\n featureShift = FeatureShift()\n featureShift.fit(df, df_feature_type=feature_type, silence_group_cols=id_ + [target],\n silence_agg_cols=id_ + [target], select_all=False)\n fe_shift_cnt = 0\n for key_ in featureShift.get_ops().keys():\n fe_shift_cnt += len(featureShift.get_ops()[key_])\n if fe_shift_cnt < 30:\n self.dfs_['FE_shift'] = featureShift.transform(df)\n log(f\"featureShift ops: {featureShift.get_ops()}\")\n else:\n self.dfs_['FE_shift'] = None\n log(\"ignore featureShift\")\n\n\n # diff特征\n log(\"feature engineer: Diff\")\n featureDiff = FeatureDiff()\n featureDiff.fit(df, df_feature_type=feature_type, silence_group_cols=id_ + [target],\n silence_agg_cols=id_ + [target], select_all=False)\n fe_diff_cnt = 0\n for key_ in featureDiff.get_ops().keys():\n fe_diff_cnt += len(featureDiff.get_ops()[key_])\n if fe_diff_cnt < 30:\n self.dfs_['FE_diff'] = featureDiff.transform(df)\n log(f\"featureDiff ops: {featureDiff.get_ops()}\")\n else:\n self.dfs_['FE_diff'] = None\n log(\"ignore featureDiff\")\n\n\n # 统计特征\n log(\"feature engineer: Stat\")\n featureStat = FeatureStat()\n featureStat.fit(df, df_feature_type=feature_type, silence_group_cols= id_ + [target],\n silence_agg_cols= id_ + [target], select_all=False)\n\n fe_stat_cnt = 0\n for key_ in featureStat.get_ops().keys():\n fe_stat_cnt += len(featureStat.get_ops()[key_])\n if fe_stat_cnt < 1500:\n self.dfs_['FE_stat'] = featureStat.transform(df)\n log(f\"featureStat ops: {featureStat.get_ops()}\")\n else:\n self.dfs_['FE_stat'] = None\n log(\"ignore featureStat\")\n\n # nlp特征\n log(\"feature engineer: NLP\")\n featureNlp = FeatureNlp()\n featureNlp.fit(df, target, df_feature_type=feature_type, silence_cols=id_, select_all=False)\n self.dfs_['FE_nlp'] = featureNlp.transform(df)\n log(f\"featureNlp ops: {featureNlp.get_ops()}\")\n\n # count特征\n log(\"feature engineer: Count\")\n # degree自动调整\n featureCount = FeatureCount()\n featureCount.fit(df, degree=2, df_feature_type=feature_type, silence_cols= id_ + [target], select_all=False)\n if len(featureCount.get_ops()) > 500:\n featureCount = FeatureCount()\n featureCount.fit(df, degree=1, df_feature_type=feature_type, silence_cols=id_ + [target], select_all=False)\n self.dfs_['FE_count'] = featureCount.transform(df)\n log(f\"featureCount ops: {featureCount.get_ops()}\")\n\n\n # rank特征\n log(\"feature engineer: Rank\")\n featureRank = FeatureRank()\n featureRank.fit(df, df_feature_type=feature_type, select_all=False)\n fe_rank_cnt = 0\n for key_ in featureRank.get_ops().keys():\n fe_rank_cnt += len(featureRank.get_ops()[key_])\n if fe_rank_cnt < 500:\n self.dfs_['FE_rank'] = featureRank.transform(df)\n log(f\"featureRank ops: {featureRank.get_ops()}\")\n else:\n self.dfs_['FE_rank'] = None\n log(\"ignore featureRank\")\n\n # label_encoder\n df = auto_label_encoder(df, feature_type, silence_cols = id_ + [target])\n\n # 特征合并\n log(\"feature combination\")\n df_list = [df, self.dfs_['FE_nlp'], self.dfs_['FE_count'], self.dfs_['FE_stat'], self.dfs_['FE_rank'], self.dfs_['FE_shift'], self.dfs_['FE_diff'], self.dfs_['FE_cumsum']]\n self.dfs_['FE_all'] = feature_combination(df_list)\n\n # # 内存优化\n # self.dfs_['FE_all'] = reduce_mem_usage(self.dfs_['FE_all'])\n\n # train和test数据切分\n train_length = self.info_['shape_of_train']\n train, test = train_test_divide(self.dfs_['FE_all'], train_length)\n log(f\"shape of FE_all: {self.dfs_['FE_all'].shape}, shape of train: {train.shape}, shape of test: {test.shape}\")\n\n # 特征过滤\n log(\"feature filter\")\n used_features = feature_filter(train, test, id_, target)\n log(f\"used_features: {used_features}\")\n\n # 模型训练\n log(\"start training model\")\n if self.info_['task_type'] == 'regression':\n model_lgb = CrossLgbRegression(metric=self.info_['metric'])\n model_lgb.fit(train[used_features], train[target], tuning=False, Debug=self.Debug)\n\n model_xgb = CrossXgbRegression(metric=self.info_['metric'])\n model_xgb.fit(train[used_features], train[target], tuning=False, Debug=self.Debug)\n\n # model_tabnet = CrossTabnetRegression()\n # model_tabnet.fit(train[used_features], train[target], tuning=True, Debug=self.Debug)\n\n elif self.info_['task_type'] == 'binary':\n model_lgb = CrossLgbBiClassifier()\n model_lgb.fit(train[used_features], train[target], tuning=False, Debug=self.Debug)\n\n model_xgb = CrossXgbBiClassifier()\n model_xgb.fit(train[used_features], train[target], tuning=False, Debug=self.Debug)\n\n # model_tabnet = CrossTabnetBiClassifier()\n # model_tabnet.fit(train[used_features], train[target], tuning=True, Debug=self.Debug)\n\n # 特征重要性\n fimp = model_lgb.feature_importances_\n log(\"feature importance\")\n log(fimp)\n\n # 模型预测\n predict_lgb = model_lgb.predict(test[used_features])\n predict_xgb = model_xgb.predict(test[used_features])\n # predict_tabnet = model_tabnet.predict(test[used_features])\n predict = (predict_xgb + predict_lgb) / 2\n\n # 预测结果后处理\n min_ = self.info_['min_target']\n max_ = self.info_['max_target']\n predict = clip_label(predict, min_, max_)\n\n # 获得结果\n sub = test[id_]\n sub[target] = predict\n sub.index = range(len(sub))\n\n return sub\n","sub_path":"autox/autox.py","file_name":"autox.py","file_ext":"py","file_size_in_byte":12322,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"}
+{"seq_id":"332223857","text":"from unittest import TestCase\nfrom test_request import test_env\n\n\nclass TestApi(TestCase):\n\n data = {\n \"method\":\"get\",\n \"url\":\"http://testing-studio:9999/demo1.txt\",\n \"headers\":None\n }\n\n def test_send(self):\n ar = test_env.Api()\n print(ar.send(self.data))\n","sub_path":"test_request/test_api.py","file_name":"test_api.py","file_ext":"py","file_size_in_byte":300,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"}
+{"seq_id":"421373615","text":"__all__=['SCRFluenceSettings']\n\nfrom Util.misc import mergedDict\nfrom CRadSettings import CRadSettings, SettingsType\n\nclass SCRFluenceSettings(CRadSettings):\n '''This class stores the SCRFluence settings\n '''\n\n __key_name__='SCRFluence'\n\n __slots__ = ['on',\n 'time', # in years\n 'confidenceLvl', # range: 0.0 - 1.0\n ]\n\n def __init__(self, context={}, **kwargs):\n ctxt = mergedDict(context, kwargs)\n super(SCRFluenceSettings, self).__init__(context=ctxt)\n\n self.params = [\n ('setType', None, \"- Type of settings\"), # '-' means only used by unformated object\n ('tgtSig', None, \"Targrt's signature\"),\n ('time', None, \"Time\"),\n ('on', None, \"- Is open\"),\n ('confidenceLvl', None, \" Confidence level \")\n ]\n\n self.setParamDict(ctxt)\n if len(ctxt)>0: self.checkData()\n\n def checkData(self):\n def _logTypeError(paramName, val):\n self._log.error(self.checkData, \"TypeError: '%s' type is '%s'\"%(paramName, type(val)))\n\n def _logValueError(paramName, val):\n self._log.error(self.checkData, \"ValueError: '%s' value is '%s'\"%(paramName, val))\n\n if not isinstance(self.on, bool):\n self._logTypeError('on', bool)\n return False\n\n time = self.time\n if time is None:\n return False\n elif (not float(time)>0):\n self._logValueError('time', time);\n return False\n\n lvl = self.confidenceLvl\n if lvl is None:\n return False\n elif not isinstance(lvl, float) or lvl < 0 or lvl > 1:\n self._logValueError('confidenceLvl', lvl)\n return False\n\n return True\n\n def fromData(self, setsData, dataPath=None):\n self.setParamDict(setsData)\n ret = self.checkData()\n return (ret, \"\")\n\n def format(self):\n raise NotImplementedError\n","sub_path":"lib/CRad/Model/Settings/SCRFluenceSettings.py","file_name":"SCRFluenceSettings.py","file_ext":"py","file_size_in_byte":2048,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"}
+{"seq_id":"620880358","text":"import sys\r\nsys.path.append('/home/aistudio')\r\n\r\nimport paddle\r\nimport paddle.fluid as fluid\r\n\r\nfrom TPN.models.networks.backbone.resnet_3d import ResNet3D\r\nfrom TPN.models.networks.backbone.xception_3d import Xception\r\nfrom TPN.models.networks.tpn import TPN\r\nfrom TPN.models.networks.simple_spatial_temporal_module import SimpleSpatialTemporalModule\r\nfrom TPN.models.networks.simple_consensus import SimpleConsenus\r\nfrom TPN.models.networks.cls_head import ClsHead\r\n\r\n\r\nclass TPN3D(fluid.dygraph.Layer):\r\n\r\n def __init__(self, model_cfg):\r\n super(TPN3D, self).__init__()\r\n if model_cfg.backbone_name == 'resnet':\r\n self.backbone = ResNet3D(**model_cfg.backbone)\r\n else:\r\n self.backbone = Xception(**model_cfg.backbone)\r\n self.necks = TPN(**model_cfg.tpn)\r\n self.spatial_temporal_module = SimpleSpatialTemporalModule()\r\n self.segmental_consensus = SimpleConsenus()\r\n self.cls_head = ClsHead(**model_cfg.cls_head)\r\n\r\n \r\n def forward(self, img_group, gt_label, for_test=False):\r\n b, n, c, t, h, w = img_group.shape\r\n x = fluid.layers.reshape(img_group, (-1, c, t, h, w))\r\n label = fluid.layers.reshape(gt_label, (b * n, -1))\r\n\r\n x = self.backbone(x)\r\n x, aux_losses, aux_accuracy, aux_score = self.necks(x, label, for_test)\r\n x = self.spatial_temporal_module(x)\r\n x = fluid.layers.reshape(x, (b, n, x.shape[1], x.shape[2], x.shape[3], x.shape[4])) # (b, n, c, t, 1, 1)\r\n x = self.segmental_consensus(x) # (b, 1, c, t, 1, 1)\r\n x = fluid.layers.squeeze(x, [1]) # (b, c, t, 1, 1)\r\n losses, accuracy = dict(), dict()\r\n cls_score = self.cls_head(x)\r\n loss_cls = self.cls_head.loss(cls_score, gt_label[:, 0])\r\n losses.update(loss_cls)\r\n losses.update(aux_losses)\r\n accuracy.update(aux_accuracy)\r\n \r\n cls_score = fluid.layers.softmax(cls_score, 1)\r\n accuracy['cls_acc1'] = fluid.layers.accuracy(input=cls_score, label=gt_label[:,0], k=1)\r\n accuracy['cls_acc5'] = fluid.layers.accuracy(input=cls_score, label=gt_label[:,0], k=5)\r\n \r\n mix_score = (cls_score + aux_score) / 2\r\n accuracy['mix_acc1'] = fluid.layers.accuracy(input=mix_score, label=gt_label[:,0], k=1)\r\n accuracy['mix_acc5'] = fluid.layers.accuracy(input=mix_score, label=gt_label[:,0], k=5)\r\n\r\n return losses, accuracy\r\n\r\n\r\nif __name__ == '__main__':\r\n import sys\r\n sys.path.append('/home/aistudio/')\r\n import numpy as np\r\n from paddle.fluid.dygraph import to_variable\r\n from TPN.utils.config import cfg\r\n\r\n with fluid.dygraph.guard():\r\n img_group = to_variable(np.zeros((1, 1, 3, 32, 224, 224)).astype('float32'))\r\n gt_label = to_variable(np.zeros((1, 1, 1)).astype('int64'))\r\n\r\n model = TPN3D(cfg.models)\r\n\r\n losses, _ = model(img_group, gt_label)\r\n\r\n print(losses['loss_cls'].shape)\r\n print(losses['loss_aux'].shape)\r\n\r\n \r\n\r\n ","sub_path":"models/tsn3d.py","file_name":"tsn3d.py","file_ext":"py","file_size_in_byte":2997,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"}
+{"seq_id":"240543874","text":"# exceso de alumnos en un aula\n#declaracion\ninstitucion=\"\"\ngrado:\"\"\nseccion=\"\"\nnumero_alumnos=0\n\n#Input\ninstitucion=input(\"ingrese institucion:\")\ngrado=input(\"ingrese grado:\")\nseccion=input(\"ingrese acciones:\")\nnumero_alumnos=int(input(\"ingrese numero de alumnos:\"))\n\n#procesing\ntotal=(numero_alumnos)\nif(total>30):\n print(exceso_alumnos_en_aula)\n#fin_if\n","sub_path":"rojas_baturen/EJERCICIO07.py","file_name":"EJERCICIO07.py","file_ext":"py","file_size_in_byte":358,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"}
+{"seq_id":"52002146","text":"import random\nlower = int(input(\"Enter a lower limit : \"))\nupper = int(input(\"Enter a upper limit : \"))\n\nsamples = int(input(\"Enter how many sample number u want : \"))\n\noutput = []\nprint(output);\n\n\nfile = open('samples.csv','w')\nfor x in range(samples):\n\trandomsample = random.randint(lower,upper)\n\n\toutput.append(randomsample)\n\nwith open(\"samples.csv\", \"w\") as txt_file:\n for line in samples:\n txt_file.write(\" \".join(line) + \"\\n\") \n\nprint(output);\n\n\n\nfile.close()","sub_path":"rancaswes.py","file_name":"rancaswes.py","file_ext":"py","file_size_in_byte":476,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"}
+{"seq_id":"398158812","text":"\nfrom ncclient import manager\nimport xml.dom.minidom\nimport xmltodict\n\nHost = '192.168.0.200'\nPort = 830\nUser = 'cisco'\nPass = 'cisco'\n\nwith manager.connect(host = Host,\n port = Port,\n username=User,\n password=Pass,\n hostkey_verify=False,\n timeout= 200, \n allow_agent=False,\n look_for_keys=False,\n ) as m:\n\n\n MyFilter ='''\n \n \n\t\t\n\t\t\tTenGigabitEthernet1/0/1\n\t\t\n\t\t\n\t\t\tTenGigabitEthernet1/0/2\n\t\t\n\t\t\n\t\t\tTenGigabitEthernet1/0/3\n\t\t\n \n \n '''\n\n\n runningConfig = m.get(filter=MyFilter).data_xml\n dom = xml.dom.minidom.parseString(runningConfig) #or xml.dom.minidom.parse(c)\n pretty_xml_as_string = dom.toprettyxml()\n #print(pretty_xml_as_string)\n\n interfaceDic = xmltodict.parse(runningConfig)\n #print(interfaceDic)\n\n import json\n\n #print(json.dumps(interfaceDic,indent=2))\n\n interfaceStat = interfaceDic['data'][\"interfaces-state\"][\"interface\"]\n# print(interfaceStat)\n\n print(json.dumps(interfaceStat,indent=2))\n\n for i in interfaceStat:\n print(i[\"name\"]['#text'])\n","sub_path":"Section2_Netconf/GetInterfaceOutputs.py","file_name":"GetInterfaceOutputs.py","file_ext":"py","file_size_in_byte":1511,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"}
+{"seq_id":"464036093","text":"import requests\r\n\r\n\r\ndef f1(mdb_genome):\r\n bases = set()\r\n to_load = {}\r\n for doc in mdb_genome.find():\r\n k = doc['lineage'].split('; ')[0]\r\n if k == 'Archaea' or k == 'Bacteria':\r\n to_load[doc['_id']] = doc\r\n bases.add(k)\r\n return bases, to_load\r\n\r\n\r\ndef f2(mdb_genome):\r\n bases = set()\r\n code_to_genome = {}\r\n code_to_taxonomy_id = {}\r\n to_load = {}\r\n for genome_doc in mdb_genome.find():\r\n k = genome_doc['lineage'].split('; ')[0]\r\n # print(k)\r\n bases.add(k)\r\n if 'name' in genome_doc:\r\n code = genome_doc['name'].split(',')[0].strip().upper()\r\n\r\n if k == 'Archaea' or k == 'Bacteria':\r\n to_load[code] = genome_doc\r\n taxonomy = genome_doc['taxonomy']\r\n if 'TAX:' in taxonomy:\r\n taxonomy = taxonomy.split('TAX:')[1]\r\n\r\n code_to_genome[code] = genome_doc\r\n code_to_taxonomy_id[code] = taxonomy\r\n else:\r\n # print(k)\r\n pass\r\n return bases, code_to_genome, code_to_taxonomy_id, to_load\r\n\r\n\r\ndef map_genome(kbase_genome, kegg_gene_annotation):\r\n match_count = {'id': 0, 'locus_tag': 0, 'old_locus_tag': 0}\r\n mapping = {}\r\n unmapped = set()\r\n for f in kbase_genome.features:\r\n mapping[f.id] = {}\r\n if f.id in kegg_gene_annotation:\r\n match_count['id'] += 1\r\n mapping[f.id]['kegg'] = f.id\r\n for alias in f.data['aliases']:\r\n if alias[0] == 'locus_tag' and alias[1] in kegg_gene_annotation:\r\n match_count['locus_tag'] += 1\r\n mapping[f.id]['kegg'] = alias[1]\r\n if alias[0] == 'old_locus_tag' and alias[1] in kegg_gene_annotation:\r\n match_count['old_locus_tag'] += 1\r\n mapping[f.id]['kegg'] = alias[1]\r\n if 'kegg' in mapping[f.id]:\r\n mapping[f.id]['kegg_annotation'] = kegg_gene_annotation[mapping[f.id]['kegg']]\r\n else:\r\n unmapped.add(f.id)\r\n return mapping, match_count, unmapped\r\n\r\n\r\ndef ko(code_to_genome, to_load, ncbi_assembly, genome_ids, kbase, ws_id):\r\n all_mapping = {}\r\n for code in code_to_genome:\r\n if code in to_load or True:\r\n genome_doc = code_to_genome[code]\r\n data_source = genome_doc['data_source']\r\n if 'Assembly' in data_source:\r\n assembly = data_source.split('Assembly:')[1].split(')')[0]\r\n if assembly in ncbi_assembly:\r\n assembly_data = ncbi_assembly[assembly]\r\n if assembly_data is not None:\r\n gcf = assembly_data['lastmajorreleaseaccession']\r\n if gcf in genome_ids:\r\n t_id = code_to_genome[code]['_id']\r\n ss = \"{}\\t{}\\t{}\\t{}\\t{}\\t{}\\t{}\".format(t_id, code, assembly, gcf,\r\n assembly_data['synonym']['similarity'],\r\n assembly_data['assemblystatus'],\r\n code_to_genome[code]['lineage'])\r\n #print(ss)\r\n resp = requests.get('http://rest.kegg.jp/list/' + t_id)\r\n kegg_gene_annotation = {}\r\n for l in resp.text.split('\\n'):\r\n p = l.split('\\t')\r\n if len(p[0]) > 0:\r\n kegg_gene_annotation[p[0].split(':')[1]] = p[1]\r\n kbase_genome = kbase.get_from_ws(gcf, ws_id)\r\n mapping, match_count, unmapped = map_genome(kbase_genome, kegg_gene_annotation)\r\n all_mapping[gcf] = mapping\r\n\r\n return all_mapping\r\n\r\n\r\ndef get_code_to_gcf(code_to_genome, to_load, ncbi_assembly):\r\n code_to_gcf = {}\r\n for code in code_to_genome:\r\n if code in to_load:\r\n genome_doc = code_to_genome[code]\r\n data_source = genome_doc['data_source']\r\n if 'Assembly' in data_source:\r\n assembly = data_source.split('Assembly:')[1].split(')')[0]\r\n if assembly in ncbi_assembly:\r\n assembly_data = ncbi_assembly[assembly]\r\n if assembly_data is not None:\r\n gcf = assembly_data['lastmajorreleaseaccession']\r\n code_to_gcf[code] = gcf\r\n return code_to_gcf\r\n\r\n\r\ndef get_kegg_to_kbase(ko_mappings):\r\n kegg_to_kbase = {}\r\n for gcf in ko_mappings:\r\n kegg_to_kbase[gcf] = {}\r\n for kb_gene_id in ko_mappings[gcf]:\r\n if 'kegg' in ko_mappings[gcf][kb_gene_id]:\r\n kegg_gene_id = ko_mappings[gcf][kb_gene_id]['kegg']\r\n if kegg_gene_id not in kegg_to_kbase[gcf]:\r\n kegg_to_kbase[gcf][kegg_gene_id] = kb_gene_id\r\n else:\r\n print('!', kegg_gene_id)\r\n return kegg_to_kbase\r\n\r\n\r\ndef get_ko_gcf_genes(mdb_ko, code_to_gcf, ko_mappings, kegg_to_kbase):\r\n ko_gcf_genes = {}\r\n for doc in mdb_ko.find():\r\n gcf_genes = []\r\n for g in doc['genes_raw']:\r\n p = g.strip().split(': ')\r\n if len(p) == 2:\r\n code = p[0]\r\n b = p[1]\r\n genes = b.strip().split(' ')\r\n for s in genes:\r\n if '(' in s:\r\n s = s.split('(')[0]\r\n if code in code_to_gcf:\r\n gcf = code_to_gcf[code]\r\n if gcf in ko_mappings:\r\n if s in kegg_to_kbase[gcf]:\r\n gcf_genes.append([code_to_gcf[code], kegg_to_kbase[gcf][s]])\r\n else:\r\n print(doc['_id'], g)\r\n if len(gcf_genes) > 0:\r\n ko_gcf_genes[doc['_id']] = gcf_genes\r\n return ko_gcf_genes\r\n","sub_path":"modelseed_annotation/kegg_utils.py","file_name":"kegg_utils.py","file_ext":"py","file_size_in_byte":6027,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"}
+{"seq_id":"236799885","text":"# -*- coding: utf-8 -*-\r\n# @Time:2018.12.18 15:32\r\n# @Author:Zhang\r\n# @Desc :\r\n\r\n\r\nfrom django.urls import path\r\nfrom . import views\r\n\r\napp_name = 'movie'\r\nurlpatterns = [\r\n path('index/', views.index, name='index'),\r\n path('job/', views.job_view, name='job'),\r\n\r\n]","sub_path":"myClass/djangoDemo/apps/movie/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":272,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"}
+{"seq_id":"279834631","text":"from random import randint, random\nimport matplotlib.pyplot as plt\nimport matplotlib.colors as colors\nimport matplotlib.cm as cmx\n\n\nclass Sistema():\n def __init__(self, path):\n self.path = path\n self.paraderos = {}\n self.buses = []\n self.viaje_directo = []\n self.llegaron = []\n self.cargar_sistema(self.path)\n self.tiempo_simulacion = 4 # si no pueden volver a salir es obvio que todos los buses salen a las 7 y vuelven antes de las 11, por lo que poniendo 2 acá se resolvería sin volver a salir.\n\n def cargar_sistema(self, path):\n # Crear paraderos\n with open(path, 'r') as datos:\n self.datos = datos.readlines()\n self.paraderos = {}\n for k in range(len(self.datos) - 6):\n cord = (self.datos[k + 1].strip().split(' ')[:2])\n self.paraderos[k + 1] = Paradero(k + 1, int(cord[0]), int(cord[1]), self)\n\n cord = self.datos[-5].split(' ')\n self.base = Paradero(0, int(cord[0]), int(cord[1]), self) #base es paradero 0\n self.cantidad_buses = int(self.datos[-4].split(' ')[-1])\n self.capacidad_buses = int(self.datos[-3].split(' ')[-1])\n self.velocidad_buses = float(self.datos[-2].split(' ')[-1])\n self.ventana_tiempo = float(self.datos[-1].split(' ')[-1])\n\n # Meter pasajeros a los paraderos\n for k in range(len(self.datos) - 6):\n destinos = (self.datos[k + 1].strip().split(' ')[2:])\n for j in range(len(destinos)):\n if int(destinos[j]) != 0:\n nuevo_pasajero = Pasajero(self.paraderos[k + 1], self.paraderos[j + 1], int(destinos[j]), self)\n if nuevo_pasajero.tiempo_minimo_total > 2: #primer filtro\n self.viaje_directo.append(nuevo_pasajero)\n else:\n self.paraderos[k + 1].pasajeros.append(nuevo_pasajero)\n #crear buses\n for k in range(self.cantidad_buses):\n self.buses.append(Bus(k, self.capacidad_buses, self.velocidad_buses, self.ventana_tiempo, self))\n\n @property\n def pasajeros(self):\n pasajeros = self.viaje_directo + self.llegaron\n for k in list(self.paraderos.values()) + self.buses:\n pasajeros.extend(k.pasajeros)\n return pasajeros\n\n @property\n def pasajeros_en_paraderos(self):\n pasajeros = []\n for paradero in self.paraderos.values():\n pasajeros.extend(paradero.pasajeros)\n return pasajeros\n\n @property\n def numero_pasajeros(self):\n return sum(x.n for x in self.pasajeros)\n\n @property\n def tiempo_esperado_total(self):\n return sum(pasajero.tiempo_esperado * pasajero.n for pasajero in self.pasajeros)\n\n def mostrar_viajes_pasajeros(self):\n # colores http://stackoverflow.com/questions/11885060/how-to-shade-points-in-scatter-based-on-colormap-in-matplotlib\n cmap = plt.cm.jet\n cNorm = colors.Normalize(vmin=1, vmax=len(self.paraderos))\n scalarMap = cmx.ScalarMappable(norm=cNorm, cmap=cmap)\n plt.plot(50, 50, marker='o', color='w', ls='')\n for pasajero in self.pasajeros:\n #if pasajero not in self.viaje_directo:\n if True:\n colorVal = scalarMap.to_rgba(pasajero.origen.k)\n plt.scatter(pasajero.origen.x, pasajero.origen.y, s=20, alpha=1, color=colorVal)\n plt.arrow(pasajero.origen.x,\n pasajero.origen.y,\n pasajero.destino.x - pasajero.origen.x,\n pasajero.destino.y - pasajero.origen.y,\n shape='full', lw=.5 * pasajero.n, length_includes_head=True, head_width=4, color=colorVal,\n alpha=0.3)\n plt.show()\n\n\nclass Paradero():\n def __init__(self, k, x, y, sistema):\n self.k = k\n self.x = x\n self.y = y\n self.sistema = sistema\n self.pasajeros = []\n\n def distancia_paradero(self, paradero):\n return ((self.x - paradero.x) ** 2 + (self.y - paradero.y) ** 2) ** 0.5\n\n @property\n def numero_pasajeros(self):\n return sum(x.n for x in self.pasajeros)\n\n def __repr__(self):\n return 'Paradero ' + str(self.k)\n\n\nclass Bus():\n def __init__(self, k, capacidad, velocidad, ventana, sistema):\n self.k = k\n self.capacidad = capacidad\n self.pasajeros = []\n self.velocidad = velocidad\n self.tiempo_base = 0\n self.tiempo_operacion = ventana\n self.tiempo_total = 0\n self.sistema = sistema\n self.paradero_actual = self.sistema.base\n self.itinerario = []\n self.hora_pasada = []\n self.contador_base = 0\n self.suben = []\n self.bajan = []\n self.pasajeros_todos = []\n\n def ir_a_paradero(self, paradero):\n\n if not (len(self.itinerario) > 0 and self.itinerario[-1] == paradero):\n self.itinerario.append(paradero)\n\n self.tiempo_base += self.paradero_actual.distancia_paradero(paradero) / self.velocidad\n self.tiempo_total += self.paradero_actual.distancia_paradero(paradero) / self.velocidad\n self.hora_pasada.append([paradero, self.tiempo_total, self.contador_base])\n if paradero == self.sistema.base:\n self.tiempo_base = 0\n self.contador_base += 1\n self.paradero_actual = paradero\n self.sistema.llegaron.extend(list(filter(lambda x: x.destino == self.paradero_actual, self.pasajeros)))\n self.pasajeros = list(filter(lambda x: x.destino != self.paradero_actual, self.pasajeros))\n\n\n def subir_pasajero(self, pasajero, n = None):\n if not n:\n n = pasajero.n\n if pasajero.n == n:\n pasajero.tiempo_esperado = self.tiempo_total\n self.pasajeros.append(pasajero)\n self.pasajeros_todos.append(pasajero)\n pasajero.origen.pasajeros.remove(pasajero)\n\n elif n != 0:\n pasajero.n -= n\n nuevo_pasajero = pasajero.copy()\n nuevo_pasajero.n = n\n nuevo_pasajero.tiempo_esperado = self.tiempo_total\n self.pasajeros.append(nuevo_pasajero)\n\n\n @property\n def numero_pasajeros(self):\n return sum(x.n for x in self.pasajeros)\n\n # formula de diego\n def peso_pasajero(self, pasajero):\n return pasajero.n * (4 - (self.tiempo_base + self.paradero_actual.distancia_paradero(pasajero.origen)/self.velocidad))\n\n #formula de nano\n def peso_nano(self, pasajero):\n otros = []\n for bus in self.sistema.buses:\n if bus != self:\n otros.extend(bus.itinerario)\n if pasajero.origen in otros:\n return 0\n else:\n return pasajero.n * (4 - (self.tiempo_base + self.paradero_actual.distancia_paradero(pasajero.origen)/self.velocidad))\n\n @property\n def pasajeros_recogibles(self):\n return list(filter(lambda x: (self.paradero_actual.distancia_paradero(x.origen) + x.distancia_entre_nodos + self.sistema.base.distancia_paradero(x.destino)) /self.velocidad + self.tiempo_base <= self.tiempo_operacion and (self.paradero_actual.distancia_paradero(x.origen) + x.distancia_entre_nodos + self.sistema.base.distancia_paradero(x.destino)) /self.velocidad + self.tiempo_total <= self.sistema.tiempo_simulacion, self.sistema.pasajeros_en_paraderos))\n\n\n def __repr__(self):\n return 'Bus {} en {} con {} pasajeros'.format(self.k, self.paradero_actual, self.numero_pasajeros)\n\nclass Pasajero():\n def __init__(self, origen, destino, n, sistema):\n self.n = n\n self.tiempo_esperado = 4\n self.origen = origen\n self.destino = destino\n self.sistema = sistema\n\n @property\n def distancia_entre_nodos(self):\n return self.origen.distancia_paradero(self.destino)\n\n @property\n def tiempo_minimo_total(self):\n return (self.origen.distancia_paradero(self.destino) + self.origen.distancia_paradero(self.sistema.base) +\n self.destino.distancia_paradero(self.sistema.base)) / self.sistema.velocidad_buses\n\n def copy(self):\n return Pasajero(self.origen, self.destino, self.n, self.sistema)\n\n def __repr__(self):\n return '{} Pasajero(s) | Origen {} -> Destino {}|Distancia {}'.format(self.n,\n self.origen.k,\n self.destino.k,\n self.distancia_entre_nodos)\n","sub_path":"Pickup&delivery/Clases.py","file_name":"Clases.py","file_ext":"py","file_size_in_byte":8614,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"}
+{"seq_id":"589063098","text":"\"\"\"\nThis program to store book information for a book store for a customor to use.\n\nTitle, Author, Year, ISBN.\n\nUser can :\nView all records\nsearch an entry\nadd entry\nUpdate entry\nDelete\nClose\n\n\"\"\"\n\nfrom tkinter import *\nfrom BackEnd import Database\nfrom tkinter import ttk\nfrom pandas import DataFrame\nimport pandas as pd\nfrom tkinter import filedialog\ndatabase=Database(\"books.db\")\n\nclass Gui(object):\n def __init__(self, Root):\n self.FontStyle= (\"Times\", 10, \"bold\")\n self.Root = Root\n self.Root.wm_title(\"Book Store\")\n self.Root.configure(bg=\"#5D6D7E\")\n self.Root.minsize(600,400)\n self.Root.resizable(0, 0) #Don't allow resizing in the x or y direction\n # Frame for all of our labels and entries, check boxes.\n self.frame1=Frame(Root,height=50,width=250)\n self.frame1.pack(side=\"top\")\n # Frame for our list box and scroll bar. \n self.frame2=Frame(Root,height=150,width=500)\n self.frame2.pack(side=\"left\")\n # Frame for our buttons\n self.frame3=Frame(Root,height=150,width=100)\n self.frame3.pack(side=\"right\")\n\n\n # Here we are defining all the labels in our desgin\n self.Label1 = Label(self.frame1,text=\"Title :\",bg=\"#5D6D7E\",font=self.FontStyle,padx=5,pady=5, width=10)\n self.Label1.grid(row=0,column=0)\n\n self.Label2 = Label(self.frame1,text=\"Author :\",bg=\"#5D6D7E\",font=self.FontStyle,padx=5,pady=5, width=10)\n self.Label2.grid(row=0,column=2)\n\n self.Label3 = Label(self.frame1,text=\"Year :\",bg=\"#5D6D7E\",font=self.FontStyle,padx=5,pady=5, width=10)\n self.Label3.grid(row=1,column=0)\n\n self.Label4 = Label(self.frame1,text=\"ISBN :\",bg=\"#5D6D7E\",font=self.FontStyle,padx=5,pady=5, width=10)\n self.Label4.grid(row=1,column=2)\n\n\n # here we are defining all the entries.\n self.title_text= StringVar()\n self.Entry1 = Entry(self.frame1, textvariable=self.title_text,bd=5)\n self.Entry1.grid(row=0,column=1)\n\n self.author_text= StringVar()\n self.Entry2 = Entry(self.frame1, textvariable=self.author_text,bd=5)\n self.Entry2.grid(row=0,column=3)\n\n self.year_text= StringVar()\n self.Entry3 = Entry(self.frame1, textvariable=self.year_text,bd=5)\n self.Entry3.grid(row=1,column=1)\n\n self.isbn_text= StringVar()\n self.Entry4 = Entry(self.frame1, textvariable=self.isbn_text,bd=5)\n self.Entry4.grid(row=1,column=3)\n\n\n self.list1=Listbox(self.frame2, height=20, width=80,font=self.FontStyle,relief=\"raised\",bd=5)\n self.list1.grid(row=2,column=0, rowspan=6, columnspan=2)\n\n ScrollBar1 = Scrollbar(self.frame2,orient=VERTICAL)\n ScrollBar1.grid(row=2,column=2, rowspan = 6)\n\n self.list1.configure(yscrollcommand=ScrollBar1.set)\n ScrollBar1.configure(command=self.list1.yview)\n\n\n self.list1.bind('<>',self.get_selected_row)\n # defining all the buttons that should be functions on the right\n\n # We don't pass bracts to view command because we want to execute the function only\n b1 = Button(self.frame3, text=\"View all\", width=14, command=self.view_command,font=self.FontStyle,pady=2,padx=2,bd=5, bg='white',relief='raised')\n b1.grid(row=2,column=3)\n\n b2 = Button(self.frame3, text=\"Search Entry\", width=14, command=self.search_command,font=self.FontStyle,pady=2,padx=2,bd=5, bg='white',relief='raised')\n b2.grid(row=3,column=3)\n\n b3 = Button(self.frame3, text=\"Add entry\", width=14, command=self.add_command,font=self.FontStyle,pady=2,padx=2,bd=5, bg='white',relief='raised')\n b3.grid(row=4,column=3)\n\n b4 = Button(self.frame3, text=\"Update selected\", width=14, command=self.update_command,font=self.FontStyle,pady=2,padx=2,bd=5, bg='white',relief='raised')\n b4.grid(row=5,column=3)\n\n b5 = Button(self.frame3, text=\"Delete selected\", width=14, command=self.delete_command,font=self.FontStyle,pady=2,padx=2,bd=5, bg='white',relief='raised')\n b5.grid(row=6,column=3)\n b6 = Button(self.frame3, text=\"Export CSV\", width=14, command=self.export_csv,font=self.FontStyle,pady=2,padx=2,bd=5, bg='white',relief='raised')\n b6.grid(row=7,column=3)\n b7 = Button(self.frame3, text=\"Import CSV\", width=14, command=self.import_csv,font=self.FontStyle,pady=2,padx=2,bd=5, bg='white',relief='raised')\n b7.grid(row=8,column=3)\n b8 = Button(self.frame3, text=\"Close\", width=14, command=self.close_window,font=self.FontStyle,pady=2,padx=2,bd=5, bg='white',relief='raised')\n b8.grid(row=10,column=3)\n\n\n\n # this is a special method for the list box wedgit and we pass event to it and it return the selected object\n def get_selected_row(self,event):\n try:\n global selected_tuple\n # we return the curselection of the listbox method\n # [0] to get the item inside the tuble without the pretesses\n index = self.list1.curselection()[0]\n selected_tuple=self.list1.get(index)\n # To show the the information in entry wegit\n self.Entry1.delete(0,END)\n self.Entry1.insert(END,selected_tuple[1])\n self.Entry2.delete(0,END)\n self.Entry2.insert(END,selected_tuple[2])\n self.Entry3.delete(0,END)\n self.Entry3.insert(END,selected_tuple[3])\n self.Entry4.delete(0,END)\n self.Entry4.insert(END,selected_tuple[4])\n except IndexError:\n pass\n\n # Wrapper function to connect the back end to the front end\n def view_command(self):\n self.list1.delete(0,END)\n for row in database.view():\n self.list1.insert(END,row)\n\n def search_command(self):\n # first thing delete the list and empty it out for the new information\n self.list1.delete(0,END)\n # we need now to iterate through the list to find the keyword\n # we need here a .get method since we will get what the user type in the entry widget\n for row in database.search(self.title_text.get(),self.author_text.get(),self.year_text.get(), self.isbn_text.get()):\n self.list1.insert(END,row)\n\n def add_command(self):\n global selected_tuple\n index = self.list1.curselection()[0]\n selected_tuple=self.list1.get(index)\n\n self.list1.delete(0,END)\n database.insert(self.title_text.get(),self.author_text.get(),self.year_text.get(), self.isbn_text.get())\n\n def delete_command(self):\n database.delete(selected_tuple[0])\n\n def update_command(self):\n # the id is the index of 0 in the tuple the rest is changing\n database.update(selected_tuple[0],self.title_text.get(),self.author_text.get(),self.year_text.get(), self.isbn_text.get())\n #print(selected_tuple[0],selected_tuple[1],selected_tuple[2],selected_tuple[3],self.selected_tuple[4])\n\n def export_csv(self):\n global df\n # Creating pandas dataframe.\n df = DataFrame(columns=['index','Title',\"Year\",\"Author\",\"isbn\"])\n # Converting database data into a list.\n list1=list(database.view())\n # iterating through the list and passing each book details to a row in our pandas dataframe\n for item in range(0,len(list1)):\n # Passing each book details in our data base to a list\n df.loc[item] = list(list1[item])\n\n \"debug print\"\n print(df) \n #convert the dataframe to csv on click and show save as dialog\n export_file_path = filedialog.asksaveasfilename(defaultextension='.csv')\n df.to_csv (export_file_path, index = None, header=True)\n\n def import_csv(self):\n global df\n global selected_tuple\n global list1\n global tuple1\n \n df = DataFrame(columns=['index','Title',\"Year\",\"Author\",\"isbn\"])\n import_file_path = filedialog.askopenfilename(defaultextension='.csv')\n df=pd.read_csv(import_file_path)\n # Create a dynamic list with a size based on the data stored in the csv file\n list1=[None] * len(df)\n print(len(list1))\n # here we want to pass each row in our pandas data frame to a list then insert the values in our data frame.\n # the for loop will iterate through the dataframe based on the index which is len(df)\n for item in range(len(df)):\n list1[item]=list(df.loc[item])\n #Pop an item from a list of lists \" Debug print\"\n #print(type(list1[item][1]),type(list1[item][2]),type(int(list1[item][3])),type(str(list1[item][4])))\n # Since we are using pandas to import the data in our database\n # We need to make sure that we have the right data types so we cast them to the desire datatype\n # In this case str, str,int str\n database.insert(str(list1[item][1]),str(list1[item][2]),int(list1[item][3]),str(list1[item][4]) )\n\n\n\n def photo_gallery(self):\n pass\n\n def close_window(self):\n self.Root.destroy()\n\n\n\n\nif __name__ == '__main__':\n Root=Tk()\n Gui(Root)\n Root.mainloop()\n","sub_path":"FrontEnd.py","file_name":"FrontEnd.py","file_ext":"py","file_size_in_byte":9101,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"15"}
+{"seq_id":"40955133","text":"import Classes.Calculos\r\nimport Classes.Transformacoes\r\nimport Classes.UtilidadeLista\r\n\r\ncalRede = Classes.Calculos.CalculaRede\r\ncalBroadCast = Classes.Calculos.CalculaBroadCast\r\nutil = Classes.UtilidadeLista.MetodosListas\r\ntransformacao = Classes.Transformacoes.TransformarIP\r\n\r\n\r\nclass Conversor:\r\n\r\n # CONSTRUTOR\r\n def __init__(self, ip):\r\n self.ip = ip\r\n self.separar_valores_ip(Conversor, ip)\r\n\r\n # Verifica se existe ou não mascara no IP, direcionando a montagem correta\r\n def separar_valores_ip(self, ip):\r\n if (self.verificar_mascara(Conversor, ip)):\r\n self.separar_valores_ip_com_mascara(Conversor, ip)\r\n else:\r\n self.separar_valores_ip_sem_mascara(Conversor, ip)\r\n\r\n def separar_valores_ip_com_mascara(self, ip): # IP com mascara\r\n listaIP = self.adicionar_IP_lista(Conversor, ip, True)\r\n if (not listaIP == False or listaIP != None): # Verifica se a lista está vazia\r\n listaIPInteiro = transformacao.transformar_lista_para_int(transformacao, listaIP, True)\r\n if (not listaIPInteiro == False or listaIPInteiro != None):\r\n listaMascaraBinario = transformacao.transformar_mascara_para_binario(transformacao, listaIP[4])\r\n listaRedeNetwork = calRede.calcular_rede(calRede, listaIPInteiro, listaMascaraBinario)\r\n listaRedeNetwork = self.montar_print_ip(Conversor, listaRedeNetwork)\r\n listaIPBinario = self.montar_print_ip(Conversor, listaIPInteiro)\r\n listaMascaraBinario = self.montar_print_mascara(Conversor, listaIP)\r\n\r\n # listaBroadCast = [] AQUI VAI A LISTA COM A REDE BROADCAST\r\n print(\"BINARIO:\", listaIPBinario)\r\n print(\"MASCARA:\", listaMascaraBinario)\r\n print(\"REDE:\", listaRedeNetwork)\r\n\r\n def separar_valores_ip_sem_mascara(self, ip): # IP sem mascara\r\n listaIP = self.adicionar_IP_lista(Conversor, ip)\r\n if (not listaIP == False or listaIP != None): # Verifica se a lista está vazia\r\n listaIPInteiro = transformacao.transformar_lista_para_int(transformacao, listaIP)\r\n if (not listaIPInteiro == False or listaIPInteiro != None):\r\n print(\"BINARIO:\", self.montar_print_ip(Conversor, listaIPInteiro))\r\n\r\n def montar_print_ip(self, lista, binario=True):\r\n ipString = \"\"\r\n if (binario):\r\n for i in range(0, 32):\r\n if (i == 8 or i == 16 or i == 24): # aqui sao as posicoes onde coloca os pontos\r\n ipString += \".\"\r\n ipString += str(lista[i])\r\n else:\r\n for i in range(0, 4):\r\n if (i != 4 and i != 0):\r\n ipString += \".\"\r\n ipString += str(lista[i])\r\n return ipString\r\n\r\n def montar_print_mascara(self, lista):\r\n mascara = lista[4]\r\n listaMascaraBinario = transformacao.transformar_mascara_para_binario(transformacao, mascara)\r\n return util.transformar_lista_em_String(util, listaMascaraBinario)\r\n\r\n # Separa o IP em uma lista de Int\r\n def adicionar_IP_lista(self, ip, temMascara=False):\r\n lista = ip.split(\".\")\r\n lista1 = []\r\n if (temMascara):\r\n lista1 = ip.split(\"/\")\r\n lista.append(lista1[1])\r\n # A lista estara com sujeira do primeiro 'split', então isso eliminara o que restou\r\n for i in range(0, len(lista)):\r\n if (\"/\" in lista[i]): # compara se possui uma barra nos elementos da lista\r\n numero = lista[i] # ao excluir, eu perco um numero do IP, isso faz com que eu consiga resgata-lo\r\n for i in range(0, len(numero)):\r\n numero = numero.replace(\"/\", \"\")\r\n numero = numero[0: (len(numero) - 2)]\r\n del (lista[i - 1]) # deleto o elemento com a barra, SUJEIRA\r\n lista.insert(i - 1, numero) # insere o numero que foi eliminado junto com a sujeira\r\n break # paro a execucacao do FOR em funcao de não ter mais o que remover\r\n listaInt = []\r\n for i in range(0, len(lista)):\r\n listaInt.append(int(lista[i]))\r\n return listaInt\r\n\r\n # Busca se há alguma máscara imposta pelo usuario na entrada\r\n def verificar_mascara(self, ip):\r\n if (ip != None or ip != \"\"):\r\n if (ip[0:].find(\"/\") > -1 or ip[0:].find(\"\\\\\") > -1):\r\n return True # Achou a barra, simbolizando a mascara\r\n else:\r\n return False # Não achou a mascara\r\n\r\n\r\n","sub_path":"Classes/Classes/ConversorIP.py","file_name":"ConversorIP.py","file_ext":"py","file_size_in_byte":4625,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"}
+{"seq_id":"624743395","text":"#!/usr/bin/env python\nfrom __future__ import division\n\"\"\"\nClassical CV Server for StartGate\nLocalizes the gate by declaring the gate as METERS_AHEAD in the x dir\nAdjust the y position of the gate by taking the difference between the middle of the frame and middle of the gate\n\"\"\"\nimport rospy\nfrom sensor_msgs.msg import Image\nfrom darknet_ros_msgs.msg import BoundingBox, BoundingBoxes\nfrom localizer.srv import ClassicalBox2Pose\nfrom geometry_msgs.msg import Pose\n\nfrom pdb import set_trace\n\nPIXEL_2_METER_MOVEMENT = 80\nMETERS_AHEAD = 6\n\nclass GateMidpointServer():\n\n def __init__(self):\n self.server = rospy.Service(\"/localize_start_gate_pole\", ClassicalBox2Pose, self.localize)\n rospy.loginfo(\"Gate Midpoint Initialized\")\n\n def _orderBoxesLeft2Right(self, box1, box2):\n if box1[0] < box2[0]:\n return box1, box2\n else:\n return box2, box1\n\n def _getCenter(self, bounding_box):\n center_x = int( (bounding_box.xmax + bounding_box.xmin) / 2)\n center_y = int( (bounding_box.ymax + bounding_box.ymin) / 2)\n return (center_x, center_y)\n\n def localize(self, req):\n \"\"\"\n This function just finds how shifted to the right or left in front of the gate is, and says it's 5m ahead. Through this carrot in front of the sub technique we can center on the gate and go through it.\n \"\"\"\n # calculate image dims\n bounding_boxes = req.boxes\n image_dims = (req.image.height, req.image.width)\n\n\n \n x_pos = METERS_AHEAD # always send the sub 6m ahead, carrot out in front\n # rest of this function is moving the carrot side to side\n \n box1 = bounding_boxes[0]\n box2 = bounding_boxes[1]\n center1 = self._getCenter(box1) # NOTE WE SWITCH X (the column) to be the first element in the list here\n center2 = self._getCenter(box2)\n\n leftBoxCenter, rightBoxCenter = self._orderBoxesLeft2Right(center1, center2)\n \n gateMidpt_y = int( (leftBoxCenter[0] + rightBoxCenter[0]) / 2 )\n\n difference_y = int(image_dims[1] / 2) - gateMidpt_y\n\n y_pos = difference_y / PIXEL_2_METER_MOVEMENT\n\n gateMidpt_z = int( (leftBoxCenter[1] + rightBoxCenter[1]) / 2 )\n difference_z = int(image_dims[0] / 2) - gateMidpt_z\n z_pos = -difference_z / PIXEL_2_METER_MOVEMENT # let's go a meter deeper\n\n pose = Pose()\n pose.position.x = x_pos\n pose.position.y = y_pos\n pose.position.z = z_pos\n \n return pose\n\ndef main():\n rospy.init_node('gate_localizer')\n server = GateMidpointServer()\n rospy.spin()\n\ndef test1():\n g = GateLocalizer()\n image_dims = (480,752)\n # image is 480x752\n\n # does x go along the rows or columns??\n \n boxes = []\n boxLeft = BoundingBox()\n boxLeft.xmin = 607\n boxLeft.ymin = 154\n boxLeft.xmax = 629\n boxLeft.ymax = 410\n\n boxRight = BoundingBox()\n boxRight.xmin = 206\n boxRight.ymin = 171\n boxRight.xmax = 231\n boxRight.ymax = 391\n \n boxes.append(boxLeft)\n boxes.append(boxRight)\n print(g.midpoint(boxes, image_dims))\n\nif __name__ == \"__main__\":\n main()\n# test1()\n\n \n\n\n \n \n","sub_path":"cusub_perception/localizer/scripts/gate_servers/gate_midpoint_srv.py","file_name":"gate_midpoint_srv.py","file_ext":"py","file_size_in_byte":3200,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"}
+{"seq_id":"185333641","text":"from flask import Flask, request, abort\nfrom flask_restful import Resource, Api\nimport json\nimport tensorflow as tf\nimport sys\nimport azure_connection\nimport subprocess\nimport os\nimport requests\nfrom PIL import Image\nfrom io import BytesIO\nimport numpy as np\nimport lime\nfrom lime import lime_image\nfrom skimage.segmentation import mark_boundaries\nfrom tensorflow.keras.preprocessing import image\nimport tensorflow.keras.applications.imagenet_utils as imn\nimport matplotlib.pyplot as plt\nimport autokeras as ak\n\napp = Flask(__name__)\napi = Api(app)\nnum_classes = 10\nBLOBFUSE_MOUNT_SCRIPT = \"/app/mount-blobfuse.sh\"\n\ndef _request_key_required(d, request_key):\n try:\n request_value = d[request_key]\n except KeyError:\n app.logger.error(f\"'{request_key}' key not found in request body. Unable to explain classification.\")\n abort(400)\n return request_value\n\ndef _get_input_dimensions(model):\n model_input = model.layers[0].output\n #Remove shape from Tensor object context (if in one)\n if tf.is_tensor(model_input):\n if hasattr(model_input, 'shape'):\n model_input = model_input.shape\n else:\n app.logger.error(\"Unable to determine input shape of model.\")\n abort(400)\n #Remove tuple from list context (if in one)\n if isinstance(model_input, list):\n if len(model_input) == 1:\n model_input = model_input[0]\n app.logger.info(model_input)\n return model_input[1:3]\n\ndef _mount_blobfuse():\n #Mount Azure Blob Storage as a virtual file system in Docker Container\n try:\n if os.path.isfile(BLOBFUSE_MOUNT_SCRIPT):\n subprocess.call([BLOBFUSE_MOUNT_SCRIPT], shell=True)\n else:\n raise FileExistsError(f\"{BLOBFUSE_MOUNT_SCRIPT} not found.\")\n except Exception as e:\n app.logger.error(f\"Issue with running blobfuse mounting script {BLOBFUSE_MOUNT_SCRIPT}, please ensure that file exists \\\n and that sufficient priveledges are given to all for execution. {e}\")\n return(400)\n\n\n@app.route('/explainTest', methods=['POST'])\ndef explain_test():\n \"\"\"\n Given a request containing the model location, and image location in blob storage to explain, saves an image with the boundaries of \n top classification to the same image directory. \n \n Note, this is *image_location*, and not *image_url* like that of the test_model API. This corresponds to the image location in blob storage.\n\n Takes a POST request of the form:\n {\n \"model_location\": ${LOCATION_OF_BASELINE_MODEL},\n \"image_location\": ${LOCATION_OF_IMAGE_TO_EXPLAIN},\n }\n \"\"\"\n #Mount Azure Blob Storage as a virtual file system in Docker Container\n if not os.path.isdir('/mnt/blobfusetmp/'):\n if(_mount_blobfuse()) == 400: return json.dumps({'success':False}), 400, {'ContentType':'application/json'} \n\n d = request.get_json()\n\n model_location, image_location = _request_key_required(d, \"model_location\"), _request_key_required(d, \"image_location\")\n try:\n model = tf.keras.models.load_model(model_location,custom_objects=ak. CUSTOM_OBJECTS)\n input_dimensions = _get_input_dimensions(model)\n except Exception as e:\n app.logger.error(f\"Failed to load model. {e}\")\n return json.dumps({'success':False}), 400, {'ContentType':'application/json'} \n\n def transform_img_fn(path_list):\n out = []\n for img_path in path_list:\n img = image.load_img(img_path, target_size=input_dimensions)\n x = image.img_to_array(img)\n x = np.expand_dims(x, axis=0)\n x = imn.preprocess_input(x, mode=\"tf\")\n out.append(x)\n return np.vstack(out)\n\n def predict_func(images):\n prediction = model.predict(images)\n return np.squeeze(prediction)\n\n #Retrieve info about model and dataset from body\n if (os.path.isfile(model_location) and os.path.isfile(image_location)):\n try:\n images = transform_img_fn([image_location])\n # plt.imsave(save_location, images[0])\n explainer = lime_image.LimeImageExplainer()\n print(type(model.layers[-1]))\n if(type(model.layers[-1]) == ak.keras_layers.Sigmoid):\n explanation = explainer.explain_instance(images[0], model.predict, hide_color=0, num_samples=1000)\n else:\n explanation = explainer.explain_instance(images[0], predict_func, hide_color=0, num_samples=1000)\n temp, mask = explanation.get_image_and_mask(explanation.top_labels[0], positive_only=False, num_features=10, hide_rest=False)\n save_location = os.path.join(os.path.dirname(model_location), \"output.png\")\n plt.imsave(save_location, mark_boundaries(temp / 2 + 0.5, mask))\n return json.dumps({'success':True}), 200, {'ContentType':'application/json'} \n except Exception as e:\n raise(e)\n app.logger.error(f\"Failed to load model. {e}\")\n return json.dumps({'success':False}), 400, {'ContentType':'application/json'} \n else:\n app.logger.error(f\"Model or image cannot be found a specified location.\")\n return json.dumps({'success':False}), 400, {'ContentType':'application/json'} \n\nif __name__ == '__main__':\n app.run(debug=True, host='0.0.0.0')\n ","sub_path":"apis/explain_model/explain_model.py","file_name":"explain_model.py","file_ext":"py","file_size_in_byte":5317,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"}
+{"seq_id":"46841968","text":"#!/usr/bin/python\nimport requests\nfrom bs4 import BeautifulSoup\nimport json\nfrom datetime import datetime\nfrom frontera.utils.fingerprint import hostname_local_fingerprint, sha1\nfrom frontera.core.components import States\nfrom frontera.contrib.backends.hbase import *\nfrom frontera.utils.misc import get_crc32\nfrom frontera.contrib.middlewares.extract import EntityDetailsExtractMiddleware\nfrom frontera.contrib.middlewares.index import ElasticSearchIndexMiddleware\nfrom frontera.contrib.middlewares.domain import DomainMiddleware\nfrom binascii import unhexlify\nimport yaml\nimport happybase\nimport logging\nfrom elasticsearch_dsl.connections import connections\n\nlogfile = \"/home/cia/bitbucket/frontera/examples/ptinews/crawl.log\"\nconfigfile = \"/home/cia/bitbucket/frontera/examples/ptinews/config.yaml\"\n\nclass Manager:\n\n def __init__(self):\n self.settings = dict()\n self.settings = yaml.safe_load(open(configfile))\n self.test_mode = False\n\n\nclass Response:\n\n def __init__(self, url):\n self.url = url\n self.body = \"\"\n self.meta = dict()\n\n\nclass PTICrawler:\n\n def __init__(self):\n logging.basicConfig(filename=logfile, level=logging.INFO, format='%(asctime)s %(message)s')\n self.manager = Manager()\n hb_host = self.manager.settings.get(\"HBASE_THRIFT_HOST\")\n hb_port = int(self.manager.settings.get(\"HBASE_THRIFT_PORT\"))\n hb_timeout = int(self.manager.settings.get(\"HBASE_TIMEOUT\"))\n self.hb_connection = happybase.Connection(\n host=hb_host, port=hb_port, timeout=hb_timeout)\n self.hb_table = self.hb_connection.table(\"crawler:metadata\")\n\n self.feeds = []\n self.ede = EntityDetailsExtractMiddleware(None)\n self.esi = ElasticSearchIndexMiddleware(self.manager)\n self.de = DomainMiddleware(self.manager)\n self.es_client = connections.create_connection(\n hosts=self.manager.settings.get('ELASTICSEARCH_SERVER', [\"localhost\"]), timeout=30)\n\n\n def index_in_hbase(self, response):\n domain_fingerprint = sha1(response.meta[b\"domain\"][b\"name\"])\n obj = prepare_hbase_object(url=response.url,\n depth=0,\n created_at=utcnow_timestamp(),\n domain_fingerprint=domain_fingerprint,\n status_code=200,\n content=response.meta[b'html'],\n state=States.CRAWLED)\n self.hb_table.put(unhexlify(response.meta[b'fingerprint']), obj)\n\n def get_article_details(self, url):\n res = requests.get(url)\n html = res.text\n doc = BeautifulSoup(html)\n title = doc.find(\"div\", {\"id\": \"dvheadin\"}).get_text()\n published_date = doc.findAll(\"font\", {\"class\": \"fullstorytime\"})[\n 1].get_text()\n published_date = datetime.strptime(\n published_date, \"%m/%d/%Y %I:%M:%S %p\")\n body = doc.find(\"div\", {\"class\": \"fulstorytext\"}).get_text()\n l = body.split(\"\\r\\n\")\n if \"By\" in l[0]:\n text = \" \".join(l[1:])\n author = l[0].replace(\"By \", \"\")\n else:\n text = \" \".join(l)\n author = None\n return title, text, html, author, published_date\n\n def get_paginated_links(self, session, doc):\n page_link = doc.find(\"a\", {\"name\": \"hpaging\"})\n temp = page_link[\"onclick\"][15:-2]\n temp = temp.split(\",\")\n start_page = int(temp[0][1:-1])\n end_page = int(temp[1][1:-1])\n count = int(temp[2][1:-1])\n links = []\n for i in range(start_page + 1, end_page + 1):\n params = dict()\n params[\"chkids\"] = \"0\"\n params[\"count\"] = str(end_page)\n params[\"pagewidth\"] = str(count)\n params[\"pnum\"] = str(i)\n url = \"http://www.ptinews.com/news/newnewslisting.aspx/changeData\"\n res = session.post(url, data=json.dumps(params), headers={\n \"Referer\": \"http://www.ptinews.com/news/newnewslisting.aspx?btnid=subscription\", \"Host\": \"www.ptinews.com\", 'content-type': 'application/json'})\n html = json.loads(res.text).split(\"^\")[1]\n sub_doc = BeautifulSoup(html)\n news_tds = sub_doc.findAll(\"td\", {\"class\": \"news_head_download\"})\n for td in news_tds:\n temp = td[\"onclick\"][20:-2]\n temp = temp.split(\",\")\n url = \"http://www.ptinews.com/news/\"\n url += temp[0][1:-1] + \"__\" + \\\n temp[1][1:-1] + \"$\" + temp[2][1:-1]\n links.append(url)\n return links\n\n def get_news_links(self):\n url = \"http://www.ptinews.com/\"\n s = requests.session()\n r = s.get(url)\n doc = BeautifulSoup(r.text)\n req_elements = set([\"__EVENTTARGET\", \"__EVENTARGUMENT\", \"__VIEWSTATE\", \"__VIEWSTATEGENERATOR\",\n \"ctl00$txtusrname\", \"ctl00$txtpwd\", \"ctl00$txtuval\", \"ctl00$btnlogin\", \"ctl00$txtlogintop\"])\n input_elements = doc.findAll(\"input\")\n params = dict()\n for el in input_elements:\n if el.get(\"name\") in req_elements:\n params[el[\"name\"]] = el.get(\"value\")\n params[\"ctl00$txtusrname\"] = \"news@crediwatch.com\"\n params[\"ctl00$txtpwd\"] = \"news#69\"\n url2 = \"http://www.ptinews.com/home.aspx\"\n r = s.post(url2, params)\n url2 = \"http://www.ptinews.com/main.aspx\"\n r = s.get(url2)\n url3 = \"http://www.ptinews.com/news/newnewslisting.aspx?btnid=subscription\"\n r = s.get(url3)\n doc = BeautifulSoup(r.text)\n news_tds = doc.findAll(\"td\", {\"class\": \"news_head_download\"})\n links = []\n for td in news_tds:\n temp = td[\"onclick\"][20:-2]\n temp = temp.split(\",\")\n url = \"http://www.ptinews.com/news/\"\n url += temp[0][1:-1] + \"__\" + temp[1][1:-1] + \"$\" + temp[2][1:-1]\n links.append(url)\n return s, doc, links\n\n def logout(self, session, doc):\n url = \"http://www.ptinews.com/news/newnewslisting.aspx?btnid=subscription\"\n input_elements = doc.findAll(\"input\")\n req_elements = set([\"__EVENTTARGET\", \"__EVENTARGUMENT\", \"__VIEWSTATEGENERATOR\", \"ctl00$txtuval\", \"ctl00$btnlogout.x\", \"ctl00$btnlogout.y\",\n \"ctl00$ContentPlaceHolder1$engtxt\", \"ctl00$ContentPlaceHolder1$count_cat\", \"ctl00$ContentPlaceHolder1$count_date\", \"ctl00$ContentPlaceHolder1$count_src\"])\n params = dict()\n for el in input_elements:\n if el.get(\"name\") in req_elements:\n params[el[\"name\"]] = el.get(\"value\")\n r = session.post(url, params)\n\n def already_indexed(self, response):\n try:\n doc = self.es_client.get(id=response.meta[b\"fingerprint\"], index=\"news\")\n return True\n except:\n return False\n\n def process(self):\n logging.info(\"Logging in\")\n session, doc, links = self.get_news_links()\n try:\n logging.info(\"Logged in. Getting paginated links\")\n res = session.get(\"http://www.ptinews.com/updatesession.aspx\")\n links += self.get_paginated_links(session, doc)\n except Exception as e:\n logging.error(e)\n\n logging.info(\"Crawling and parsing articles. Found: %s\", str(len(links)))\n for url in links:\n logging.info(\"Crawling: %s\", url)\n try:\n res = Response(url)\n res = self.de.add_domain(res)\n res.meta[b\"fingerprint\"] = hostname_local_fingerprint(res.url)\n if self.already_indexed(res):\n continue\n\n title, text, html, author, published_date = self.get_article_details(\n url)\n res.meta[b\"text\"] = text\n res.meta[b\"content_hash\"] = get_crc32(text)\n res.meta[b\"title\"] = title\n res.meta[b\"html\"] = html\n res.meta[b\"published_date\"] = published_date\n res.meta[b\"crawled_date\"] = datetime.now()\n res.meta[b\"image\"] = None\n res.meta[b\"authors\"] = author\n res.meta[b\"location\"] = [\"india\"]\n res.meta[b\"language\"] = \"en\"\n res = self.ede.add_details(res)\n self.index_in_hbase(res)\n self.esi.add_to_index(res)\n logging.info(\"Published date: %s\", str(published_date))\n except Exception as e:\n logging.error(e)\n self.logout(session, doc)\n\nif __name__ == \"__main__\":\n p = PTICrawler()\n p.process()\n","sub_path":"examples/ptinews/crawl.py","file_name":"crawl.py","file_ext":"py","file_size_in_byte":8716,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"}
+{"seq_id":"491209665","text":"import six\nimport logging\n\nfrom requests.packages.urllib3 import disable_warnings\nimport requests\n\nfrom myapp.common.applogging import classproperty, get_object_namespace\n\ndisable_warnings()\n\n\ndef _safe_decode(text, incoming='utf-8', errors='replace'):\n if isinstance(text, six.text_type):\n return text\n\n return text.decode(incoming, errors)\n\n\ndef _log_transaction(func):\n def _wrapper(self, *args, **kwargs):\n level = 10\n logline = '{0} {1}'.format(args, kwargs)\n\n try:\n self._log.debug(_safe_decode(logline))\n except Exception as exception:\n self._log.info(\n 'Exception occured while logging signature of calling'\n 'method in http client')\n self._log.exception(exception)\n\n try:\n response = func(self, *args, **kwargs)\n except Exception as exception:\n self._log.critical('Call to Requests failed due to exception')\n self._log.exception(exception)\n raise exception\n\n request_body = ''\n if 'body' in dir(response.request):\n request_body = response.request.body\n elif 'data' in dir(response.request):\n request_body = response.request.data\n else:\n self._log.info(\n \"Unable to log request body, neither a 'data' nor a \"\n \"'body' object could be found\")\n\n request_params = ''\n request_url = response.request.url\n if 'params' in dir(response.request):\n request_params = response.request.params\n elif '?' in request_url:\n request_url, request_params = request_url.split('?', 1)\n\n logline = ''.join([\n '\\n{0}\\nREQUEST SENT\\n{0}\\n'.format('-' * 12),\n 'request method..: {0}\\n'.format(response.request.method),\n 'request url.....: {0}\\n'.format(request_url),\n 'request params..: {0}\\n'.format(request_params),\n 'request headers.: {0}\\n'.format(response.request.headers),\n 'request body....: {0}\\n'.format(request_body)])\n try:\n self._log.log(level, _safe_decode(logline))\n except Exception as exception:\n # Ignore all exceptions that happen in logging, then log them\n self._log.log(level, '\\n{0}\\nREQUEST INFO\\n{0}\\n'.format('-' * 12))\n self._log.exception(exception)\n\n logline = ''.join([\n '\\n{0}\\nRESPONSE RECEIVED\\n{0}\\n'.format('-' * 17),\n 'response status..: {0}\\n'.format(response),\n 'response time....: {0}\\n'.format(response.elapsed),\n 'response headers.: {0}\\n'.format(response.headers),\n 'response body....: {0}\\n'.format(response.content),\n '-' * 79])\n try:\n self._log.log(level, _safe_decode(logline))\n except Exception as exception:\n # Ignore all exceptions that happen in logging, then log them\n self._log.log(\n level, '\\n{0}\\nRESPONSE INFO\\n{0}\\n'.format('-' * 13))\n self._log.exception(exception)\n return response\n return _wrapper\n\n\nclass BaseHTTPClient(object):\n def __init__(self, url):\n self.headers = {}\n self.url = url\n\n @classproperty\n def _log(cls):\n return logging.getLogger(get_object_namespace(cls))\n\n @_log_transaction\n def request(self, method, url, **kwargs):\n headers = self.headers\n headers.update(kwargs.get(\"headers\", {}))\n kwargs.update({\"headers\": headers})\n kwargs.update({\"verify\": False})\n return requests.request(method, url, **kwargs)\n\n def put(self, url, **kwargs):\n return self.request('PUT', url, **kwargs)\n\n def copy(self, url, **kwargs):\n return self.request('COPY', url, **kwargs)\n\n def post(self, url, data=None, **kwargs):\n return self.request('POST', url, data=data, **kwargs)\n\n def get(self, url, **kwargs):\n return self.request('GET', url, **kwargs)\n\n def head(self, url, **kwargs):\n return self.request('HEAD', url, **kwargs)\n\n def delete(self, url, **kwargs):\n return self.request('DELETE', url, **kwargs)\n\n def options(self, url, **kwargs):\n return self.request('OPTIONS', url, **kwargs)\n\n def patch(self, url, **kwargs):\n return self.request('PATCH', url, **kwargs)\n\n\nclass BaseRaxClient(BaseHTTPClient):\n def __init__(self, url, auth_client):\n super(BaseRaxClient, self).__init__(url)\n self._auth = auth_client\n\n @property\n def token(self):\n self.token = self._auth.token\n return self.headers.get(\"X-Auth-Token\")\n\n @token.setter\n def token(self, value):\n self.headers[\"X-Auth-Token\"] = value\n\n def request(self, *args, **kwargs):\n self.token\n return super(BaseRaxClient, self).request(*args, **kwargs)\n","sub_path":"myapp/common/client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":4872,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"}
+{"seq_id":"230565649","text":"import xlrd\nimport datetime\nimport hashlib\nimport json\nimport decimal\nimport sys\nimport csv\nimport psycopg2\nfrom configparser import ConfigParser\n\nXL_CELL_EMPT = 0 # -- empty string\nXL_CELL_TEXT = 1 # -- a Unicode string\nXL_CELL_NUMBER = 2 # -- float\nXL_CELL_DATE = 3 # -- float\nXL_CELL_BOOLEAN = 4 # -- int; 1 means True, 0 means False\nXL_CELL_ERROR = 5 # -- int representing internal Excel codes;\n # -- for a text representation, refer to the supplied\n # -- dictionary error_text_from_code\nXL_CELL_BLANK = 6 # -- empty string. Note: this type will appear only\n # -- when open_workbook(..., formatting_info= True) is used.\n\nclass ImportException(Exception):\n def __init__(self, message):\n self.message = message\n\n\nclass FileReader:\n def __init__(self, map):\n self.map = map\n\n def read_data(self, file):\n data = [[]]\n\n if file.lower().endswith(\".xlsx\"):\n data = self.get_xlsx_data(file)\n elif file.lower().endswith(\".csv\"):\n data = self.get_csv_data(file)\n\n return data\n\n def get_xlsx_data(self, xlsx_file):\n book = xlrd.open_workbook(xlsx_file)\n sheet_name = self.map.get_xlsx_sheet_name()\n\n if sheet_name is not None:\n sheet = book.sheet_by_name(sheet_name)\n else:\n sheet = book.sheet_by_index(0)\n\n has_header = self.map.source_has_header()\n\n if self.map.has_intermediate_table():\n col_count = len(self.map.get_table_columns(\"intermediate\"))\n else:\n col_count = len(self.map.get_table_columns(\"target\"))\n\n data = []\n first_row = 0\n\n if has_header:\n first_row = 1\n\n for sheet_row in range(first_row, sheet.nrows - 1):\n data.append([])\n if not self.xlsx_is_empty_row(sheet, sheet_row):\n for col_index in range(0, col_count):\n cell = sheet.cell(sheet_row, col_index)\n data[len(data) - 1].append(str(self.xlsx_get_cell_value(book, cell)))\n\n return data\n\n def get_csv_data(self, csv_file):\n has_header = self.map.source_has_header()\n data = []\n row_number = 0\n\n with open(csv_file) as csv_ptr:\n csv_reader = csv.reader(csv_ptr)\n data.append([])\n for values in csv_reader:\n row_number = row_number + 1\n\n if has_header and row_number == 1:\n continue\n\n for value in values:\n data[len(data) - 1].append(value)\n\n return data\n\n def xlsx_get_cell_value(self, book, cell):\n if cell.ctype == XL_CELL_NUMBER:\n if str(cell.value).find(\"e+\") > 0:\n value = decimal.Decimal(cell.value)\n else:\n value = cell.value\n elif cell.ctype == XL_CELL_DATE:\n value = self.xlsx_to_date_string(book, cell)\n elif cell.ctype == XL_CELL_BOOLEAN:\n if cell.value == 0:\n value = False\n else:\n value = True\n elif cell.ctype == XL_CELL_ERROR:\n value = \"ERR\"\n else:\n value = cell.value.strip()\n\n return value\n\n def xlsx_is_empty_row(self, sheet, sheet_row):\n is_empty = True\n\n for sheet_col in range(0, sheet.ncols - 1):\n cell = sheet.cell(sheet_row, sheet_col)\n\n if cell.value != \"\":\n is_empty = False\n break\n\n return is_empty\n\n def xlsx_to_date_string(self, book, cell):\n return datetime.datetime(*xlrd.xldate_as_tuple(cell.value, book.datemode))\n\n\nclass Database:\n def get_connection_settings(self, filename='database.ini', section='postgresql'):\n # create a parser\n parser = ConfigParser()\n # read config file\n parser.read(filename)\n\n # get section, default to postgresql\n db = {}\n if parser.has_section(section):\n params = parser.items(section)\n for param in params:\n db[param[0]] = param[1]\n else:\n raise Exception('Section {0} not found in the {1} file'.format(section, filename))\n\n return db\n\n def get_connection(self):\n \"\"\" Connect to the PostgreSQL database server \"\"\"\n conn = None\n try:\n # read connection parameters\n params = self.get_connection_settings()\n\n # connect to the PostgreSQL server\n print('Connecting to the PostgreSQL database...')\n conn = psycopg2.connect(**params)\n\n # create a cursor\n cur = conn.cursor()\n\n # execute a statement\n print('PostgreSQL database version:')\n cur.execute('SELECT version()')\n\n # display the PostgreSQL database server version\n db_version = cur.fetchone()\n print(db_version)\n\n # close the communication with the PostgreSQL\n cur.close()\n\n return conn\n except (Exception, psycopg2.DatabaseError) as error:\n raise error\n\n def execute_command(self, conn, command):\n try:\n cur = conn.cursor()\n cur.execute(command)\n # close communication with the PostgreSQL database server\n cur.close()\n # commit the changes\n conn.commit()\n except (Exception, psycopg2.DatabaseError) as error:\n raise error\n\n\nclass ScriptGenerator:\n def __init__(self, map):\n self.map = map\n\n def generate_script(self, data):\n ddl = \"\"\n\n if self.map.has_intermediate_table():\n ddl = ddl + \" \" + self.generate_create_table(\"intermediate\")\n for row in data:\n ddl = ddl + \" \" + self.generate_insert(\"intermediate\", row)\n\n ddl = ddl + \" \" + self.generate_create_table(\"target\")\n\n if self.map.has_intermediate_table():\n ddl = ddl + \"\\n\" + self.map.get_intermediate_script()\n else:\n for row in data:\n ddl = ddl + \" \" + self.generate_insert(\"target\", row)\n\n if self.map.has_intermediate_table():\n ddl = ddl + \"\\nDROP TABLE \" + self.map.get_table_name(\"intermediate\") + \"\\n;\"\n\n return ddl\n\n def generate_create_table(self, type):\n table_name = self.map.get_table_name(type)\n sql = \"\"\n\n if table_name is not None:\n sql = \"DROP TABLE IF EXISTS %s\\n;\\n\" % table_name\n sql = \"%sCREATE TABLE %s (\\n\" % (sql, table_name)\n sql = \"%s\\tID CHAR(40) NOT NULL PRIMARY KEY,\\n\" % sql\n sql = \"%s\\tEFFECTIVE_DATE TIMESTAMP NOT NULL,\\n\" % sql\n\n for column_name in self.map.get_table_columns(type):\n sql = \"%s\\t%s VARCHAR(255) NULL,\\n\" % (sql, column_name.upper())\n\n sql = \"%s\\n)\\n;\\n\" % sql[0:len(sql) - 2]\n\n return sql\n\n def generate_insert(self, type, row):\n table_name = self.map.get_table_name(type)\n columns = []\n col_count = len(self.map.get_table_columns(type))\n insert_values = []\n\n for col_index in range(0, col_count):\n table_column = self.map.get_table_columns(type)[col_index]\n columns.append(table_column)\n\n for value in row:\n insert_values.append(self.format_insert(value))\n\n insert = \"INSERT INTO %s ( id, effective_date, %s )\\nVALUES ( %s, NOW(), %s )\\n;\\n\" % (\n table_name,\n self.to_csv(columns),\n self.to_quoted_string(self.get_primary_key(row)),\n self.to_csv(insert_values)\n )\n\n return insert\n\n def get_primary_key(self, row):\n key_value = \"\"\n col_count = len(row)\n\n for col_index in range(0, col_count):\n value = row[col_index].upper()\n key_value = \"%s %s\" % (key_value, value)\n\n return self.hash(key_value)\n\n def to_quoted_string(self, value):\n return \"'%s'\" % str(value).strip().replace(\"'\", \"''\")\n\n def format_insert(self, value): # (map, value):\n insert_value = value # apply_regex(map, value)\n db_type = \"varchar\" # map[\"table\"][\"type\"]\n\n if insert_value == \"N/A\" or insert_value == \"NA\" or insert_value == \"\":\n insert_value = \"NULL\"\n elif db_type.find(\"char\") != -1 or db_type == \"date\" or db_type == \"timestamp\":\n insert_value = self.to_quoted_string(insert_value)\n elif db_type == \"money\" or db_type.find(\"decimal\") != -1 or db_type == \"integer\":\n insert_value = self.to_quoted_string(insert_value)\n elif db_type == \"boolean\":\n insert_value = self.to_quoted_string(insert_value)\n else:\n raise Exception(\"Unknown type: \" + db_type)\n\n return insert_value\n\n @staticmethod\n def hash(value):\n return hashlib.sha1(value.encode(\"utf-8\")).hexdigest()\n\n @staticmethod\n def to_csv(arr):\n csv = \"\"\n\n for c in arr:\n csv = csv + str(c) + \", \"\n\n return csv[0:len(csv) - 2]\n\n\nclass MappingFile:\n def __init__(self, file):\n with open(file, \"r\") as f:\n self.json = \\\n json.load(f)\n\n def get_table_columns(self, type):\n columns = []\n\n if type in self.json:\n columns = self.json[type][\"columns\"]\n\n return columns\n\n def get_table_name(self, type):\n table_name = None\n\n if type in self.json:\n table_name = self.json[type][\"table\"]\n\n return table_name\n\n def get_intermediate_script(self):\n file = self.json[\"intermediate\"][\"script\"]\n sql = \"\"\n\n with open(file, \"r\") as f:\n for line in f:\n sql = sql + line\n\n return sql\n\n def get_target_table_name(self):\n return self.json[\"target\"][\"table\"]\n\n def source_has_header(self):\n return self.json[\"source\"][\"header\"]\n\n def has_intermediate_table(self):\n return \"intermediate\" in self.json\n\n def get_xlsx_sheet_name(self):\n sheet = None\n\n if \"sheet\" in self.json[\"source\"]:\n sheet = self.json[\"source\"][\"sheet\"]\n\n return sheet\n\ndef main():\n conn = None\n\n try:\n file = sys.argv[1]\n map_file = sys.argv[2]\n\n print(\"Loading mapping file...\")\n map = MappingFile(map_file)\n file_reader = FileReader(map)\n script_gen = ScriptGenerator(map)\n db = Database()\n\n conn = db.get_connection()\n\n print(\"Loading into %s...\" % map.get_target_table_name())\n\n data = file_reader.read_data(file)\n sql = script_gen.generate_script(data)\n db.execute_command(conn, sql)\n\n print(\"%s row(s) loaded.\" % len(data))\n print(\"Done.\")\n except ImportException as e:\n print(\"Error: %s\" % str(e))\n finally:\n if conn is not None:\n conn.close()\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"import-listings.py","file_name":"import-listings.py","file_ext":"py","file_size_in_byte":10953,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"}
+{"seq_id":"185118886","text":"\"\"\"\r\nUn supermercado maneja el catálogo de los productos que vende. \r\nDe cada producto se conoce su nombre, precio, y si el mismo es parte del programa Precios Cuidados o no. Por defecto, el producto no es parte del programa, a menos que se especifique lo contrario.\r\n\r\nPara ayudar a los clientes, el supermercado quiere realizar \r\ndescuentos en productos de Primera Necesidad. Es por eso que al calcular el precio de un producto de Primera Necesidad, se aplica un descuento del 10%. Es decir:\r\n\r\nprecioProductoPrimeraNecesidad = precioBaseDelProducto * 0.9\r\n\r\nEl supermercado, del cual se conoce el nombre y la dirección, desea conocer la \r\ncantidad total de productos que comercializa y la suma total de los precios de los mismos.\r\n\r\nImplementar un programa en Python que resuelva este requerimiento.\r\nSuponga ahora que el descuento a aplicar en cada producto de primera necesidad puede ser distinto y se debe poder definir al momento de crear el mismo. Por ejemplo, el arroz puede ser un producto de primera necesidad con un descuento del 8%, mientras que leche podría ser otro producto de primera necesidad con un decuento del 11%. Esto es sólo un ejemplo. El descuento a aplicar en cada producto de primera necesidad debe ser configurable al momento de crearlo.\r\n\r\nImplementar un programa en Python basado en el anterior que ahora incorpore este nuevo requerimiento.\"\"\"\r\n\r\n\r\n\r\nfrom clases import producto, Menu_productos, cliente\r\n\r\nwhile True:\r\n\r\n p1 = producto(nombre='cigarrillo', precio= 120)\r\n p2 = producto(nombre='shampoo', precio = 100, precios_cuidados= True)\r\n p3 = producto(nombre='cerveza', precio=120, productos_primera_necesidad=True)\r\n p4 = producto(nombre='frutilla', precio=120, descuento=0.2)\r\n Menu = Menu_productos(nombre='\"CAREFURE\"', direccion= 'av. Avalos N° 899', lista_productos=[p1, p2, p3, p4])\r\n clien = cliente(lista_precios= Menu.lista_precios)\r\n\r\n print('opciones:\\n\\t1. Ver menu de mercaderias \\n\\t2. Mostrar Listas de Precios:\\n\\t3. Mostrar precio total de la mercaderia del super \\n\\t4. Hacer compra \\n\\t5. salir')\r\n\r\n opcion = input('')\r\n if opcion == '1':\r\n Menu.ver_menu()\r\n elif opcion == '2':\r\n Menu.mostrar_listaPrecios()\r\n elif opcion == '3':\r\n Menu.mostrar_precio_total_mercaderia()\r\n\r\n elif opcion == '4':\r\n while True:\r\n opcion_cliente = input('Elegir opcion: \\n\\t1. Realizar compra\\n\\t2. Ver productos comprados\\n\\t3. Salir\\n')\r\n if opcion_cliente == '1':\r\n Menu.mostrar_listaPrecios()\r\n op = int(input('Elija Producto: '))\r\n clien.opcion = op-1\r\n clien.eleccion()\r\n elif opcion_cliente == '2':\r\n clien.compra_total()\r\n elif opcion_cliente == '3':\r\n break\r\n else: print('elija una opcion valida')\r\n elif opcion == '5':\r\n print('Gracias vuelva pronto')\r\n break\r\n else: print('Elija una opcion valida')\r\n\r\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2988,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"}
+{"seq_id":"342314488","text":"import sys\nsys.stdin = open('input1.txt','r')\n\nT = int(input())\nfor tc in range(T):\n N,K = map(int, input().split())\n fly = [list(map(int,input().split())) for i in range(N)]\n maxV = 0\n for i in range(0,N-K+1): #부분 영역의 왼쪽 위 모서리칸 좌표, i, j\n for j in range(0,N-K+1):\n s = 0\n for x in range(K):\n if x % 2 == 0:\n for b in range(K//2):\n s += fly[i+x][j+1+2*b]\n\n else:\n if K % 2 == 1:\n for b in range(K//2+1):\n s += fly[i+x][j+2*b]\n\n else:\n for b in range(K//2):\n s += fly[i+x][j+2*b]\n if maxV < s:\n maxV = s\n print(f'#{tc+1} {maxV}')","sub_path":"0822/모자이크.py","file_name":"모자이크.py","file_ext":"py","file_size_in_byte":835,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"}
+{"seq_id":"592339139","text":"# -*- coding: utf-8 -*-\n# @date 161003 - Added url patterns\n\"\"\"\nUrl patterns\n\"\"\"\nfrom django.conf.urls import url\n\nfrom product import views, api_views\n\n# Template\nurlpatterns = [\n url(r'^$', views.ProductManagement.as_view()),\n]\n\n# For APIs\nurlpatterns += [\n url(r'^api-product/$', api_views.ProductAPI.as_view()),\n]\n","sub_path":"website/product/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":328,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"}
+{"seq_id":"229433460","text":"import os\nimport time\nimport qrcode\nimport hmac\nimport hashlib\nimport json\nimport simplejson\nimport urllib\nfrom hashlib import md5\nfrom base64 import decodebytes, encodebytes\nimport base64\n\nfrom django.shortcuts import render, reverse\nfrom django.conf import settings\nfrom django.views.decorators.csrf import csrf_exempt\nfrom django.conf import settings\nfrom django.views.decorators.http import require_POST\nfrom django.http import JsonResponse\n\nfrom alipay import AliPay\n\n\nfrom .models import Course, CourseOrder\nfrom utils import restful\nfrom apps.xfzauth.decorators import xxz_login_required\n\n\ndef course_index(request):\n \"\"\"\n 获取课程列表页\n :param request:\n :return:\n \"\"\"\n courses = Course.objects.all()\n context = {\n 'courses': courses\n }\n return render(request, 'course/course_index.html', context=context)\n\n\ndef course_order_completed(request):\n return render(request, 'course/course_order_completed.html')\n\n\ndef course_detail(request, course_id):\n \"\"\"\n 获取某个具体的课程\n :param request: course_id\n :param course_id:\n :return:\n \"\"\"\n course = Course.objects.get(pk=course_id)\n order_exist = CourseOrder.objects.filter(course_id=course_id, buyer=request.user, status=2).exists()\n\n context = {\n 'course': course,\n 'order_exist': order_exist\n }\n\n return render(request, 'course/course_detail.html', context=context)\n\n\ndef course_token(request):\n \"\"\"\n 生成前端视频播放所需要的token\n :param request:\n :return: token\n \"\"\"\n file = request.GET.get('video') # 这里的file是一个完整的视频链接地址\n course_id = request.GET.get('course_id')\n exists = CourseOrder.objects.filter(course_id=course_id, buyer=request.user, status=2).exists() # 处理用户是否购买课程的逻辑\n if not exists:\n return restful.param_error(message='请先购买该课程!')\n\n expired_time = int(time.time()) + 2 * 60 * 60\n USER_ID = settings.BAIDU_CLOUD_USER_ID\n USER_KEY = settings.BAIDU_CLOUD_USER_KEY\n\n # 获取的file的地址url如下\n # file=http://hemvpc6ui1kef2g0dd2.exp.bcevod.com/mda-igjsr8g7z7zqwnav/mda-igjsr8g7z7zqwnav.m3u8\n # 1.获取地址url中的文件名的扩展名\n # 2.去除扩展名,获取文件名\n extension = os.path.splitext(file)[1] # 将文件名和扩展名分离: (filename, extension)\n media_id = file.split('/')[-1].replace(extension, '') # 获取二进制文件名: mda-igjsr8g7z7zqwnav\n\n # 将user_key编码成utf8格式\n key = USER_KEY.encode('utf-8')\n message = '/{0}/{1}'.format(media_id, expired_time).encode('utf-8')\n\n # 数字签名\n signature = hmac.new(key, message, digestmod=hashlib.sha256).hexdigest()\n token = '{0}_{1}_{2}'.format(signature, USER_ID, expired_time)\n\n return restful.result(data={'token': token})\n\n\ndef init_alipay_obj():\n \"\"\"\n 初始化alipay对象\n :return: alipay object\n \"\"\"\n alipay = AliPay(\n appid= settings.ALIPAY_APPID,\n app_notify_url= None,\n app_private_key_path=os.path.join(os.path.dirname(__file__), \"keys/app_private_key.pem\"),\n # 支付宝的公钥,验证支付宝回传消息使用,不是你自己的公钥,\n alipay_public_key_path=os.path.join(os.path.dirname(__file__), \"keys/alipay_public_key.pem\"),\n sign_type=\"RSA2\", # RSA 或者 RSA2\n debug=True # 默认False\n )\n\n return alipay\n\n\n@xxz_login_required\ndef get_qr_code(code_url):\n \"\"\"\n 根据支付宝返回的二维码链接生成二维码图像\n :param code_url:\n :return: code_img\n \"\"\"\n qr = qrcode.QRCode(\n version=1,\n error_correction=qrcode.constants.ERROR_CORRECT_H,\n box_size=10,\n border=1\n )\n\n qr.add_data(code_url)\n img = qr.make_image()\n img.save(os.path.join(settings.MEDIA_ROOT, 'zfb.png'))\n print('保存二维码图片成功!')\n\n\n# @xxz_login_required\n@require_POST\ndef create_pre_order(request):\n \"\"\"\n 创建预订单\n :param subject: 订单名\n :param out_trade_no: 支付宝交易号,固定\n :param total_amount: 订单金额,浮点数\n :return: 1.创建预订单失败 2.返回二维码code_url\n \"\"\"\n subject = request.POST.get('goodsname')\n out_trade_no = request.POST.get('orderid')\n total_amount = request.POST.get('price')\n\n result = init_alipay_obj().api_alipay_trade_precreate(\n subject=subject,\n out_trade_no=out_trade_no,\n total_amount=total_amount\n )\n print('返回值',result)\n\n code_url = result.get('qr_code')\n if not code_url:\n return restful.param_error(message='预付订单创建失败!')\n else:\n get_qr_code(code_url)\n # 等下在这里测试是否会生成二维码图片,如果生成则返回给前端\n\n\n@xxz_login_required\ndef create_order_request(request):\n \"\"\"向支付宝发起支付请求\"\"\"\n out_trade_no = request.POST.get('orderid')\n total_amount = request.POST.get('price')\n subject = request.POST.get('goodsname')\n\n alipay_client = init_alipay_obj()\n order_string = alipay_client.api_alipay_trade_page_pay(\n out_trade_no=out_trade_no,\n total_amount=total_amount,\n subject='课程订单%s' % subject,\n return_url='http://localhost:8000/course/course_order_completed/',\n notify_url=None\n )\n\n alipay_url = settings.ALIPAY_URL + order_string\n\n return JsonResponse({'alipay_url': alipay_url})\n\n\n@require_POST\ndef order_payment_result(request):\n \"\"\"\n 接受从支付宝返回的参数,提取其中的sign参数进行签名验证\n :param request:\n :return:\n \"\"\"\n alipay_data= request.POST.get('alipayData') # 这里返回一个字符串,需要将它改造成字典,再提取出sign的值\n print('源数据:%s'%alipay_data)\n alipay_dict = {}\n alipay_data_arr = alipay_data.split('&')\n print('alipay数组:%s' % alipay_data_arr)\n for value in range(1, len(alipay_data_arr)):\n value = alipay_data_arr[value]\n arr_val = value.split('=')\n alipay_dict[arr_val[0]] = arr_val[1]\n\n alipay_sign = alipay_dict.pop('sign')\n\n print('*' * 30)\n print('alipay_dict数据:%s' % alipay_dict)\n print('*' * 30)\n print('签名值是多少?:%s' % alipay_sign)\n\n alipay_client = init_alipay_obj()\n result = True\n if result:\n order_id = alipay_dict.get('out_trade_no')\n trade_no = alipay_dict.get('trade_no')\n CourseOrder.objects.filter(uid=order_id).update(trade_no=trade_no, status=2)\n # result = alipay_client.verify(alipay_dict, alipay_sign)\n return restful.ok()\n\n\n@xxz_login_required\ndef course_order(request, course_id):\n \"\"\"\n 课程订单购买页面,请求参数为某个课程的id\n :param request: course_id\n :return:order list 返回订单列表\n \"\"\"\n course = Course.objects.get(pk=course_id)\n order = CourseOrder.objects.create(course=course, buyer=request.user, amount=course.price, status=1)\n # notify_url = request.build_absolute_uri(reverse('course:notify_view'))\n # return_url = request.build_absolute_uri(reverse('course:course_detail', kwargs={'course_id': course.pk}))\n\n context = {\n 'course': course,\n 'order': order,\n # 'notify_url': notify_url,\n # 'return_url': return_url\n }\n\n return render(request, 'course/course_order.html', context=context)\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n# @xxz_login_required\n# def course_order_key(request):\n# \"\"\"\n# 获取课程key\n# :param request:\n# :return: key\n# \"\"\"\n# goodsname = request.POST.get('goodsname')\n# istype = request.POST.get('istype')\n# notify_url = request.POST.get('notify_url')\n# orderid = request.POST.get('orderid')\n# price = request.POST.get('price')\n# return_url = request.POST.get('return_url')\n#\n# token = 'e6110f92abcb11040ba153967847b7a6'\n# uid = '49dc532695baa99e16e01bc0'\n# orderuid = str(request.user.pk)\n# key = md5((goodsname + istype + notify_url + orderid + orderuid + price + return_url + token + uid).encode('utf-8')).hexdigest()\n#\n# return restful.ok(data={'key': key})\n\n\n# @csrf_exempt\n# def notify_view(request):\n# \"\"\"\n# 通知给自己服务器的视图函数\n# :param request:\n# :return:\n# \"\"\"\n# orderid = request.POST.get('orderid')\n# CourseOrder.objects.filter(pk=orderid).update(status=2)\n#\n# return restful.ok()","sub_path":"apps/course/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":8408,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"}
+{"seq_id":"467756170","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\n\nfrom django.conf.urls import patterns, url\n\n\nurlpatterns = patterns('settings.views',\n url(r'^$', 'home'),\n url(r'^submit/$', 'submit'),\n url(r'^success/$', 'success'),\n url(r'^error/$', 'error'),\n url(r'^groupes/$', 'groupes'),\n url(r'^ips/$', 'ips'),\n url(r'^ports/$', 'ports'),\n url(r'^ports/ajax/(?P.+)/(?P\\d+)/$', 'ajax_nmap'),\n)\n","sub_path":"src/settings/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":421,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"}
+{"seq_id":"548124813","text":"#!/usr/bin/env python3\n\nimport re\nimport urllib.request\nimport urllib.error\nimport shutil\nimport sys\n\npattern = 'kulla[-.0-9]+\\.jar'\nkulla_artifact_homepage = 'https://adopt-openjdk.ci.cloudbees.com/view/OpenJDK/job/' \\\n 'langtools-1.9-linux-x86_64-kulla-dev/lastSuccessfulBuild/artifact'\ntest_file = '/home/charles/etc/kulla/kulla-test-data.html'\ncacheFile = \"/home/charles/etc/kulla/kulla-version.log\"\n# kulla_file_name = 'kulla.jar'\n\n\ndef get_cached_version():\n with open(cacheFile, 'r') as cvf:\n version = cvf.read().strip()\n return version\n\n\ndef cache_version_file(version):\n with open(cacheFile, 'w') as cvf:\n cvf.write(version)\n\n\ndef is_same_version(version):\n try:\n if get_cached_version() == version:\n return True\n else:\n return False\n except FileNotFoundError as e:\n print(\"version cache file not found\")\n\n\ndef find_file_name(content):\n p = re.compile(pattern)\n result = p.search(content)\n if result:\n file_name = result.group()\n\n return file_name\n\n\ndef get_kulla_jar_file(file_name):\n kulla_artifact_url = kulla_artifact_homepage + '/' + file_name\n print(\"getting {}\".format(kulla_artifact_url))\n local_file_name, headers = urllib.request.urlretrieve(kulla_artifact_url)\n shutil.move(local_file_name, '/home/charles/kulla/' + file_name)\n\n\ndef get_test_file(file_name):\n tf = open(file_name, 'r')\n content = tf.readlines()\n\n return \"\".join(content)\n\n\ndef retrieve_page():\n req = urllib.request.Request(kulla_artifact_homepage)\n\n try:\n with urllib.request.urlopen(req) as page:\n content = page.read().decode(\"utf-8\")\n except urllib.error.HTTPError as e:\n print(\"http error: unable to retrieve page\")\n return\n except urllib.error.URLError as e:\n print(\"url error: unable to retrieve the page\")\n return\n\n return content\n\n\ndef update_kulla_script(file_name):\n p = re.compile('kulla[-.0-9]+\\.jar')\n\n with open('/home/charles/bin/kulla', 'r') as ifh:\n lines = ifh.readlines()\n\n for num, line in enumerate(lines):\n m = p.findall(line)\n if len(m) > 0:\n lines[num] = p.sub(file_name, line)\n\n with open('/home/charles/bin/kulla', 'w') as ofh:\n for line in lines:\n ofh.write(line)\n\n\ndef main(args):\n print(\"================================================\")\n print(\"Attempting to update kulla (aka JShell)\")\n\n print(\"retriving page...\", end=\"\")\n if len(args) > 1 and args[1] == 'test':\n content = get_test_file(test_file)\n else:\n content = retrieve_page()\n\n if content:\n print(\"ok\")\n\n print(\"searching for kulla version...\", end=\"\")\n latest_kulla_version = find_file_name(content)\n if latest_kulla_version:\n print(\"ok\")\n print(\" found file name {}\".format(latest_kulla_version))\n\n if not is_same_version(latest_kulla_version):\n print(\"new version of kulla available...\")\n print(\"retrieving new version...\")\n\n get_kulla_jar_file(latest_kulla_version)\n\n cache_version_file(latest_kulla_version)\n\n update_kulla_script(latest_kulla_version)\n else:\n print(\"a newer version is not currently available...\")\n else:\n print(\"did not find a file to download...\")\n\n print(\"================================================\")\n\n\nif __name__ == '__main__':\n main(sys.argv)\n","sub_path":"update-kulla.py","file_name":"update-kulla.py","file_ext":"py","file_size_in_byte":3533,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"}
+{"seq_id":"565901955","text":"from django.shortcuts import HttpResponse\nfrom django.http import HttpResponseRedirect\nfrom subprocess import Popen\nfrom explorer.models import Msite, Fsite, Keyword, Taccount\nimport sys, os, time, json\n\ndef command(request):\n if request.method == 'POST':\n if request.POST.get('acommand') == 'Run':\n path = os.path.dirname(os.path.realpath(__file__))\n Popen([\"python\", path + \"/../../src/executer.py\", \"article\", \"run\"], cwd=path)\n\n if request.POST.get('acommand') == 'Pause':\n path = os.path.dirname(os.path.realpath(__file__))\n Popen([\"python\", path + \"/../../src/executer.py\", \"article\", \"pause\"], cwd=path)\n\n if request.POST.get('acommand') == 'Stop':\n path = os.path.dirname(os.path.realpath(__file__))\n Popen([\"python\", path + \"/../../src/executer.py\", \"article\", \"stop\"], cwd=path)\n\n if request.POST.get('acommand') == '[F]Stop':\n path = os.path.dirname(os.path.realpath(__file__))\n Popen([\"python\", path + \"/../../src/executer.py\", \"article\", \"fstop\"], cwd=path)\n\n if request.POST.get('tcommand') == 'Run':\n path = os.path.dirname(os.path.realpath(__file__))\n Popen([\"python\", path + \"/../../src/executer.py\", \"twitter\", \"run\"], cwd=path)\n\n if request.POST.get('tcommand') == 'Pause':\n path = os.path.dirname(os.path.realpath(__file__))\n Popen([\"python\", path + \"/../../src/executer.py\", \"twitter\", \"pause\"], cwd=path)\n\n if request.POST.get('tcommand') == 'Stop':\n path = os.path.dirname(os.path.realpath(__file__))\n Popen([\"python\", path + \"/../../src/executer.py\", \"twitter\", \"stop\"], cwd=path)\n\n if request.POST.get('tcommand') == '[F]Stop':\n path = os.path.dirname(os.path.realpath(__file__))\n Popen([\"python\", path + \"/../../src/executer.py\", \"twitter\", \"fstop\"], cwd=path)\n\n\n return HttpResponseRedirect(\"/admin\")\n\ndef getJson(request):\n scope = {'monitoring_sites':{}, 'foreign_sites': {}, \n 'keywords': [], 'twitter_accounts': []}\n\n for site in Msite.objects.all():\n scope['monitoring_sites'][site.url] = {'name': site.name}\n\n for site in Fsite.objects.all():\n scope['foreign_sites'][site.url] = {'name': site.name}\n\n for key in Keyword.objects.all():\n scope['keywords'].append(key.keyword)\n\n for acc in Taccount.objects.all():\n scope['twitter_accounts'].append(acc.account)\n\n res = HttpResponse(json.dumps(scope, indent=2, sort_keys=True))\n res['Content-Disposition'] = format('attachment; filename=scope-%s.json' \n % time.strftime(\"%Y%m%d-%H%M%S\"))\n return res\n","sub_path":"Frontend/explorer/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2720,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"}
+{"seq_id":"364264752","text":"import os\r\n\r\n# Import the bill of materials (bom) file created as such:\r\n# Combined property string:\r\n# {Reference}\\t{Quantity}\\t{Value}\\t{Part number\\t{Manufacturer}\\t{Manufacturer part}\r\n# Header line doesn't matter.\r\n# Make sure \"each part on a separate line\" is checked\r\nbomname = \"../schematics/judybom.bom\"\r\n\r\n# The file srsparts.dat maps part numbers to plain text descriptions\r\npartfile = \"srsparts.dat\"\r\n\r\n#Parts not eligible for the pick and place\r\ndisfile = \"noplace.dat\"\r\n\r\n#Number of part reels on the machine. 15 reels x 8 parts = 120\r\nmaxparts = 120\r\n\r\n# pntrunc -- Truncate part numbers to get rid of the suffix\r\n# Usage: pntrunc()\r\n# Returns: Truncated part number as a string\r\n# Example:\r\n# pntrunc('5-00764-581') returns '5-00764'\r\ndef pntrunc(fullpn):\r\n\tpnsplit = fullpn.split('-')\r\n\tspn = pnsplit[0] + '-' + pnsplit[1]\r\n\treturn spn\r\n\r\n# ispn -- Check to see if this is a valid srs part number\r\n# Usage: ispn()\r\n# Returns: True (for a good part) or False\r\n# Example:\r\n# ispn('5-00764-581') returns True\r\ndef ispn(fullpn):\r\n return len(fullpn.split('-')) == 3\r\n\r\n# iscom -- Check to see if a line is commented out\r\n# Usage: iscom()\r\n# Returns: True (for a line beginning with #) or False\r\n# Example:\r\n# iscom('#Some comment') returns True\r\ndef iscom(line):\r\n return line.startswith('#')\r\n\r\n\r\n \r\n\r\n#Make a dictionary of descriptions\r\nfpf = open(partfile,'r')\r\nrawpf = fpf.read()\r\ndesc = {}\r\nfor line in rawpf.split(\"\\n\"):\r\n if line != '' and not iscom(line):\r\n fields = line.split()\r\n srspn = pntrunc(fields[0])\r\n blurb = fields[1]\r\n if len(fields) >= 3:\r\n for item in fields[2:]:\r\n blurb += ' ' + item\r\n desc[srspn] = blurb\r\n\r\n#Make a list of disqualified parts\r\nfdq = open(disfile,'r')\r\nrawdq = fdq.read()\r\ndqparts = []\r\nfor line in rawdq.split(\"\\n\"):\r\n if line != '' and not iscom(line):\r\n fields = line.split()\r\n srspn = pntrunc(fields[0])\r\n dqparts.append(srspn)\r\n\r\n\r\n#make a dictionary to hold part number and quantity\r\n#qty will hold part:qty\r\nfbm = open(bomname,'r')\r\nrawbom = fbm.read()\r\nqty = {}\r\ntotalnum = 0\r\nfor line in rawbom.split('\\n'):\r\n if line != '':\r\n fields = line.split('\\t')\r\n if (len(fields) == 6 and ispn(fields[3])):\r\n srspn = pntrunc(fields[3])\r\n totalnum += 1\r\n if srspn in qty:\r\n qty[srspn] += 1\r\n else:\r\n qty[srspn] = 1\r\n else:\r\n print('Skipping line --> ' +\r\n str(fields[0]))\r\n\r\n\r\n#Sort the parts by frequency in descending order\r\nqtylist = sorted(qty,key=lambda x: qty[x], reverse=True)\r\n\r\n\r\n\r\n\r\n\r\n#Now qty is a dictionary of srs part numbers and their quantities\r\nprint('\\n' + \"There are \" + str(totalnum) + \" total parts, with \" +\r\n str(len(qty)) + \" unique\")\r\n\r\n\r\n# Start the list of most-used parts, with parts disqualified for\r\n# pick and place enclosed in parenthesis\r\nprint('Machine-placeable parts ranked by frequency:')\r\ncount = 0\r\nfor part in qtylist:\r\n if part not in dqparts:\r\n count += 1\r\n if count > maxparts and count < (maxparts + 2):\r\n print('--------------------------------------------------')\r\n if part in desc:\r\n print(str(count) + \": \" + str(qty[part]) +\r\n \" \" + desc[part] + \"s\")\r\n else:\r\n print(str(count) + \": \" + str(qty[part]) + \" \" + part)\r\n else:\r\n if part in desc:\r\n print(\"(\" + str(qty[part]) + \" \" +\r\n desc[part] + \"s)\")\r\n else:\r\n print(\"(\" + str(qty[part]) + \" \" + part)\r\n#fpk.close()\r\n \r\n\r\n \r\n\r\n\r\n","sub_path":"python/partcount.py","file_name":"partcount.py","file_ext":"py","file_size_in_byte":3940,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"}
+{"seq_id":"52608915","text":"#67.Exercise 6 _ modify number guessing game - Python tutorial 64\r\n\r\n\r\nimport random\r\nwinning_num = random.randint(1,100)\r\n#winning_num = 45\r\ntrynum = 1\r\nguess_num = int(input(\"plaese guess a number between 1 and 100: \"))\r\nGameOver = False\r\nwhile not GameOver:\r\n if guess_num == winning_num:\r\n print(f\"cong.....! you guessed the right number in {trynum} times\")\r\n GameOver = True\r\n else:\r\n if guess_num > winning_num:\r\n print(\"too high\")\r\n else:\r\n print(\"too low\")\r\n\r\n trynum += 1\r\n guess_num = int(input(\"plaese again guess a number between 1 and 100: \"))","sub_path":"69.dry principal of coding.py","file_name":"69.dry principal of coding.py","file_ext":"py","file_size_in_byte":626,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"}
+{"seq_id":"142945994","text":"import json\nimport select\nimport socket\n\nBYTES_AMOUNT_REQUEST_SIZE = 20\n\n\nclass SocketDataReceiver:\n @staticmethod\n def receive_fixed_size(connection: socket.socket, size: int):\n buffer = \"\"\n\n while len(buffer) < size:\n try:\n ready_to_read, ready_to_write, in_error = select.select([connection], [], [])\n except select.error:\n raise TimeoutError\n buffer += connection.recv(size).decode('utf-8')\n if not buffer:\n raise TimeoutError\n\n return buffer\n\n @staticmethod\n def receive_json(connection: socket.socket):\n request_size = int(SocketDataReceiver.receive_fixed_size(connection, BYTES_AMOUNT_REQUEST_SIZE))\n data = SocketDataReceiver.receive_fixed_size(connection, request_size)\n # logging.info(\"Json received: {}\".format(data))\n # logging.info(\"Address: {}\".format(connection.getpeername()))\n\n return json.loads(data)\n","sub_path":"tp2_utils_package/tp2_utils/data_transfering_utils/socket_data_receiver.py","file_name":"socket_data_receiver.py","file_ext":"py","file_size_in_byte":976,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"}
+{"seq_id":"375105945","text":"import json\nimport os\nimport logger\nfrom flask import Flask, jsonify, request\nfrom PIL import Image\nfrom werkzeug.utils import secure_filename\n\nfrom config import app\nfrom models import database, Img, Task\n\n\ndef saves_the_checked_file_to_database(sent_file):\n \"\"\"Сохраняет проверенный файл в базу данных,\n парсит данные в json,\n дополнительно выполняя проверку имени файла,\n присваивает файлу уникальное имя и\n возвращает ответ в json формате\"\"\"\n\n sent_filename = sent_file.filename\n path_to_picture = os.path.join(app.config['UPLOAD_FOLDER'], sent_filename)\n picture_name = secure_filename(str(sent_filename))\n file_data = Img(picture_name=picture_name, path_to_picture=path_to_picture)\n try:\n database.session.add(file_data)\n database.session.commit()\n image_database = Img.query.order_by(Img.date).all()\n with open('parse database/image_database.json', 'w') as image_base_to_json:\n json.dump(str(image_database), image_base_to_json, indent=-2, ensure_ascii=False)\n response = jsonify({'result': 'success',\n 'filename': sent_filename,\n 'id': file_data.image_id,\n 'description': 'the file is saved and ready for processing'})\n return response, 202\n except Exception:\n response = jsonify({'result': 'error', 'description': 'error adding to database'})\n return response, 499\n\n\ndef save_task():\n \"\"\"Сохраняет задачу клиента в базу данных и парсит её в json\"\"\"\n sent_json = {\n 'id': request.json['id'],\n 'required_height': request.json['required_height'],\n 'required_width': request.json['required_width']\n }\n sent_id = sent_json['id']\n try:\n processed_file = Img.query.get(sent_id)\n task_name = processed_file.picture_name.rsplit('.', 1)[0]\n file_format = processed_file.picture_name.rsplit('.', 1)[1]\n required_image_height = sent_json['required_height']\n required_image_width = sent_json['required_width']\n task_path = processed_file.path_to_picture\n task = Task(task_name=task_name, file_format=file_format, required_height=required_image_height,\n required_width=required_image_width, task_path=task_path)\n database.session.add(task)\n database.session.commit()\n task_database = Task.query.order_by(Task.date).all()\n with open('parse database/tasks_database.json', 'w') as tasks_base_to_json:\n json.dump(str(task_database), tasks_base_to_json, indent=-2, ensure_ascii=False)\n return task.task_id, 201\n except ExceptionWhenAddingTaskToDatabase:\n response = jsonify({'result': 'error', 'description': 'when adding a task to the database, an unknown error '\n 'occurred (the connection to the server may have been '\n 'broken)'})\n return response, 499\n\n\ndef change_image(id):\n \"\"\"Изменяет изображение, согласно полученной задачи и сохраняет его на сервере\"\"\"\n from models import database, Task\n tasks_data = database.session.query(Task).filter_by(task_id=id).first()\n path_to_save_done_task = os.path.join(app.config['COMPLETED_FOLDER'])\n task_path = tasks_data.task_path\n processed_image = Image.open(task_path)\n image_height = tasks_data.required_height\n image_width = tasks_data.required_width\n resize_img = processed_image.resize((image_height, image_width), Image.ANTIALIAS)\n processed_img_name = f\"task_id={tasks_data.task_id}_{tasks_data.task_name}.\" \\\n f\"{tasks_data.file_format}\"\n file_path = os.path.join(path_to_save_done_task, processed_img_name)\n resize_img.save(file_path)\n tasks_data.is_it_done_now = True\n database.session.add(tasks_data)\n database.session.commit()\n processed_image.close()\n response = jsonify({'result': 'success',\n 'file_name': processed_img_name,\n 'id': tasks_data.task_id,\n 'done': tasks_data.is_it_done_now})\n logger.LOG.info(f'change image name: {processed_img_name}, path: {file_path} response 200, \"User-Agent\": {request.headers.get(\"User-Agent\")}')\n return response, 200\n","sub_path":"saver.py","file_name":"saver.py","file_ext":"py","file_size_in_byte":4576,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"}
+{"seq_id":"621721449","text":"'''\nName: Ryan Fernandes\nCisc 235, Assignment 1.2\n'''\nimport random #to use the random generator\nimport timeit #to use the timeit function\n\ndef linearSearch(array,keyVal):\n for i in range(0,len(array)):\n if array[i] == keyVal:\n return True\n return False\n\ndef algorithmA(array, targetArray): #function iterates through the target array and searches with the supplied array.\n for i in targetArray:\n linearSearch(array,i)\n\ndef mergeSort(array):\n i = j = k = 0\n if len(array) >1: #check if array is not empty\n middle = len(array)//2 #finding the middle of array\n #divide the array\n left = array[:middle]\n right = array[middle:]\n mergeSort(left)\n mergeSort(right)\n while i < len(left) and j < len(right):\n if left[i] < right [j]:\n array[k] = left[i]\n i+=1\n else:\n array[k] = right[i]\n j+=1\n k+=1\n # final check if any code was left out\n while j highIndex:\n return False\n else:\n midIndex = (lowIndex + highIndex) //2\n if target == array[midIndex]:\n return True\n elif target < array[midIndex]:\n return binSearch(array,target,lowIndex,midIndex-1)\n else:\n return binSearch(array,target,midIndex+1,highIndex)\n\n#Function runs Merge Sort function & Binary Search function\ndef algorithmB(array, targetArray):\n mergeSort(array)\n for i in targetArray:\n binSearch(array, i)\n\ndef createList(n):\n array = [] #empty list\n for i in range(0,n):\n nextInput = (random.randint(1,n+1)//2)*2 #creates a random number that is even\n array.append(nextInput) #adds the random number into the generated array\n return array\n\ndef targetList(k, array):\n targetArray = [] #empty list\n firstHalf = k//2\n secondHalf = k-firstHalf\n for i in range(0,firstHalf):\n nextInput = array[random.randint(0,len(array)-1)] #obtain a random number from the main list to be appended into the targetArray\n targetArray.append(nextInput)\n for i in range(0,secondHalf): #appends random odd number into half of the target array.\n nextInput = ((random.randint(1,len(array)+1)//2)*2)+1 #generates random ODD numbers to be appended into the target array.\n targetArray.append(nextInput)\n return targetArray\n\ndef main():\n global k, n # k and n are global variables\n setupA = '''from __main__ import algorithmA, createList, targetList, k, n\narray = createList(n)\ntargetArray = targetList(k, array)\n'''\n setupB = '''from __main__ import algorithmB, createList, targetList, k, n\narray = createList(n)\ntargetArray = targetList(k, array)\n'''\n stmtA = '''algorithmA(array, targetArray)\n'''\n stmtB = '''algorithmB(array, targetArray)\n'''\n\n i = 1000\n n = 1000\n print(\"N = 1000\")\n print(\"\")\n print(\"%-5s%-25s%-25s\" % ('k', 'Algorithm A Time (ms)', 'Algorithm B Time (ms)'))\n print(\"--------------------------------------------------\")\n for k in range(150,170):\n timeA = (timeit.timeit(stmt= stmtA, setup = setupA, number = i)) * 1000\n timeB = (timeit.timeit(stmt = stmtB, setup = setupB, number = i))* 1000\n print(\"%-7d%-25d%-25d\" % (k,timeA,timeB))\n print(\"\")\n\n n = 2000\n print(\"N = 2000:\")\n print(\"\")\n print (\"%-5s%-25s%-25s\" % ('k','Algorithm A Time (ms)','Algorithm B Time (ms)'))\n print(\"_____________________________________________________________\")\n for k in range(150,170):\n timeA = (timeit.timeit(stmt = stmtA, setup = setupA, number = i))*1000\n timeB = (timeit.timeit(stmt = stmtB, setup = setupB, number = i))*1000\n print(\"%-7d%-25d%-25d\" % (k,timeA,timeB))\n print(\"\")\n\n n = 5000\n print(\"N = 5000:\")\n print(\"\")\n print (\"%-5s%-25s%-25s\" % ('k','Algorithm A Time (ms)','Algorithm B Time (ms)'))\n print(\"_____________________________________________________________\")\n for k in range(150,170):\n timeA = (timeit.timeit(stmt = stmtA, setup = setupA, number = i))*1000\n timeB = (timeit.timeit(stmt = stmtB, setup = setupB, number = i))*1000\n print(\"%-7d%-25d%-25d\" % (k,timeA,timeB))\n print(\"\")\n\n n = 10000\n print(\"N = 10000:\")\n print(\"\")\n print (\"%-5s%-25s%-25s\" % ('k','Algorithm A Time (ms)','Algorithm B Time (ms)'))\n print(\"_____________________________________________________________\")\n for k in range(150,170):\n timeA = (timeit.timeit(stmt = stmtA, setup = setupA, number = i))*1000\n timeB = (timeit.timeit(stmt = stmtB, setup = setupB, number = i))*1000\n print(\"%-7d%-25d%-25d\" % (k,timeA,timeB))\n\n\nmain()\n","sub_path":"Assignment 1.2/assignment-1.2.py","file_name":"assignment-1.2.py","file_ext":"py","file_size_in_byte":5003,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"}
+{"seq_id":"62135118","text":"from math import cos, sin, pi, sqrt\nimport os\n\nfolder_name = \"fila_256\"\ntry: \n os.mkdir(folder_name)\nexcept OSError:\n print(f\"Directory {folder_name} already exists\")\nelse:\n print(f\"Created directory {folder_name}\")\n\ndef b10(num): # Decimal to Scientific Notation\n return \"{:.10e}\".format(num)\n\ndef circ(x, y, r, n): # Generates Circle coordinates\n return [(cos(2*pi/n*i)*r + x, sin(2*pi/n*i)*r + y)\n for i in range(0,n)]\n\n# Variables\nr1, (x1, y1) = 1, (2.5, 2) # Circle 1, Radius and Center\nr2, (x2, y2) = 1, (5, 2) # Circle 2, Radius and Center\nn = 64 # Number of Points\nspring_const = 5000 # Spring Constant\nrest_length = round(r1*sqrt(2-2*cos(2*pi/n)), 3) # Rest Length (recommended above)\nRigidity = 5000000 # Beam Rigidity\nr_sm = r1*(0.4) # Radius of Smaller Circles\nn_sm = n//2 # Number of Points on Smaller Circles\n# Generates small circles centered at pi/4 and -pi/4 radians\nsm_center = n//8 # Center Angle (pi/8 radians)\nsm_start = n_sm//8 # Small Circle offset Left/Right\nsm_half = n_sm//2 # Small Circle Arc length\ncirc_sm_rad = n//16 # Large Circle removing arc radius\n\n##########################################################################################\n#################################### Vertex Formation ####################################\n##########################################################################################\n\nfile_out = open(f\"./{folder_name}/fila_256.vertex\", \"w\")\n\n# 2 Circles, rough outline of cells\ncirc_1 = circ(x1,y1,r1,n)\ncirc_2 = circ(x2,y2,r2,n)\n\n####### SMALL CIRCLE 1 ######\n\n# Generates small circles centered at pi/4 and -pi/4 radians\nsm_circ_1 = circ(circ_1[sm_center][0], circ_1[sm_center][1], r_sm, n_sm)\nsm_circ_2 = circ(circ_1[n - sm_center][0], circ_1[n - sm_center][1], r_sm, n_sm)\n\n# Cuts small circles inside larger circle\nsm_circ_1 = sm_circ_1[n_sm - sm_start:] + sm_circ_1[:sm_half - sm_start + 1]\nsm_circ_2 = sm_circ_2[sm_half + sm_start:] + sm_circ_2[:sm_start + 1]\n\n# Replace overlap with cut small circle\ncirc_1[n - sm_center - circ_sm_rad : n - circ_sm_rad + 1] = sm_circ_2\ncirc_1[circ_sm_rad : sm_center + circ_sm_rad + 1] = sm_circ_1\n\nn_big = len(circ_1)\n\n# File output\nfile_out.write(f\"{n_big + n} # number of vertices in file\\n\")\n\nfor point in circ_1 + circ_2:\n file_out.write(f\"{b10(point[0])} {b10(point[1])}\\n\")\n\nfile_out.write(\"# x-coord, y-coord\\n\")\n\nprint(f\"Success: ~/{folder_name}/fila_256.vertex\")\nfile_out.close()\n\n##########################################################################################\n#################################### Spring Formation ####################################\n##########################################################################################\n\nfile_out = open(f\"./{folder_name}/fila_256.spring\", \"w\")\n\nfile_out.write(f\"{n_big + n + sm_center + 1} # INACCURATE number of springs in file\\n\")\n\nfor x in range(n_big):\n file_out.write(f\"{x%n_big} {(x+1)%n_big} {b10(spring_const)} {b10(rest_length)}\\n\")\n\nfor x in range(n):\n file_out.write(f\"{n_big + (x%n)} {n_big + (x+1)%n} {b10(spring_const)} {b10(rest_length)}\\n\")\n\n###### PULL BARS #####\n#for x in range(-1*n//16 ,n//16 + 1):\n# pullbar_len_formula = 0.5 - 0.02*abs(x) # <-- <-- <-- <-- <-- <-- <-- <-- <-- <-- <-- <-- \n# print(pullbar_len_formula)\n# file_out.write(f\"{n_big//2 - 4*x} {x%n_big} {b10(spring_const)} {b10(pullbar_len_formula)}\\n\")\n\n### CONNECTING BARS ###\n\n#for x in range(1,5*n_sm//16):\n# file_out.write(f\"{n//16 + x} {n_big + n//2 - x - n//9} {b10(spring_const)} {b10(0.1)}\\n\")\n#for x in range(1,5*n_sm//16):\n# file_out.write(f\"{(-n//16 - x)%n_big} {n_big + n//2 + x + n//9} {b10(spring_const)} {b10(0.1)}\\n\")\n\nfile_out.write(\"# idx1, idx2, spring constant, rest length\\n\")\nfile_out.close()\n\nprint(f\"Success: ~/{folder_name}/fila_256.spring\")\n\n##########################################################################################\n##################################### Beam Formation #####################################\n##########################################################################################\n\nfile_out = open(f\"./{folder_name}/fila_256.beam\", \"w\")\n\nfile_out.write(f\"{7*n_big//8+n-1} # INACCURATE number of beams in file\\n\")\n\nfor x in range(n_big):\n file_out.write(f\"{x%n_big} {(x+1)%n_big} {(x+2)%n_big} {b10(Rigidity)}\\n\")\n# \\/ is for the beamless center\n#for x in range(n_big//16 + 1, 15*n_big//16):\n# file_out.write(f\"{x%n_big} {(x+1)%n_big} {(x+2)%n_big} {b10(Rigidity)}\\n\")\nfor x in range(n):\n file_out.write(f\"{n_big+x%n} {n_big+(x+1)%n} {n_big+(x+2)%n} {b10(Rigidity*100)}\\n\")\n\nfile_out.write(\"# idx1, idx2, idx3, rigidity\\n\")\nfile_out.close()\n\nprint(f\"Success: ~/{folder_name}/fila_256.beam\")\n\n##################################################################################\n# More vertices ---> Doesn't help until 64, stops moving at 128 #\n# Spring2d Input2D ---> ... I forgot what I meant by this #\n# Changing Spring Constant ---> Doesn't change much #\n# Changing Beam Constant ---> Check #\n# Lower CFL or Timestep ---> Takes longer, doesn't do anything important #\n# Extending Spring Lengths ---> Deforms cells by making them fluff or crush #\n# #\n# Docker Container working in local server #\n# Alternate Springs code lost on Palmtree restart(?) #\n# Backup to GitHub or local server #\n# #\n# Goals #\n# - Fix ordering of sm circle vertices #\n# - Scale cleft springsw #\n# - Envelopment #\n##################################################################################\n# Removing intial self intersections\n# Spread out internal connections\n# Remove beams on inside of cleft\n# Testing out beams\n# Stability\n\n# . mass file (mass to points)\n# Add springs to inside so it doesn't just collapse on the other one\n # Massive spring constant\n\n# markdown tutorial\n# Docker cp\n# Add them as collab \n# Add docker link somehow???\n# Make the markdown file like a tutorial\n# Make movie recordings\n# Organize simulation files \n\n# Think about 3d?\n# Self intersection and permeability\n# Correct rho and mu\n# Increase resolution something funny freeeze lack of motion\n# Wrap around though?\n# Maybe no Mickey shape?\n# More variable dependant\n# Make script to launch vscode and terminal stuff","sub_path":"Python/CircleTest.py","file_name":"CircleTest.py","file_ext":"py","file_size_in_byte":7215,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"}
+{"seq_id":"273533782","text":"import sys\nimport string\n\ndigi = string.digits\nmath_sign = \"*/%^+-\"\n\n\ndef validate_input(s):\n if len(s) < 2:\n return False\n else:\n return True\n\n\ndef validate_first_char(e):\n if is_open_brac(e[0]) or is_digit(e[0]):\n return True\n else:\n return False\n\n\ndef validate_last_char(e):\n if is_close_brac(e[len(e) - 1]) or is_digit(e[len(e) - 1]):\n return True\n else:\n return False\n\n\ndef is_digit(a):\n if a in digi:\n return True\n else:\n return False\n\n\ndef is_open_brac(a):\n if a == \"(\":\n return True\n else:\n return False\n\n\ndef is_close_brac(a):\n if a == \")\":\n return True\n else:\n return False\n\n\ndef is_math_sign(a):\n if a in math_sign:\n return True\n else:\n return False\n\n\ndef validate_char(c):\n if is_digit(c) or \\\n is_open_brac(c) or \\\n is_close_brac(c) or \\\n is_math_sign(c):\n return True\n else:\n return False\n\n\ndef validate_expression(expression):\n math_sign = False\n prev_char = \"\"\n counter_open_brac = 0\n counter_close_brac = 0\n if validate_first_char(expression) and validate_last_char(expression):\n for j in range(len(expression)):\n i = expression[j]\n prev_char = expression[j - 1]\n if validate_char(i):\n if is_math_sign(i):\n if math_sign:\n return False # 2 math sings na elkaar\n else:\n math_sign = True\n else:\n math_sign = False\n if is_close_brac(i) and is_open_brac(prev_char):\n return False # empty bracket\n if is_open_brac(i):\n counter_open_brac += 1\n if is_close_brac(i):\n counter_close_brac += 1\n else:\n return False # char not valid of given options\n else:\n return False # first and last char not valid\n if counter_open_brac != counter_close_brac:\n return False\n\n return True\n\n\ndef process_input(s):\n wrong_exp_counter = 0\n if validate_input(s):\n for e in s[1:]:\n if not validate_expression(e):\n print(e)\n wrong_exp_counter += 1\n if wrong_exp_counter == 0:\n print(\"correct\")\n else:\n print(\"no input provided\")\n\n\nprocess_input(sys.argv)\n","sub_path":"Assignments/chalc.py","file_name":"chalc.py","file_ext":"py","file_size_in_byte":2459,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"}
+{"seq_id":"556912254","text":"import matplotlib.pyplot as plt\nimport numpy as np\nfrom ParticleTrackingGui.general.parameters import get_param_val\n\ndef colour_array(subset_df, f, parameters, method=None):\n cmap_type = parameters[method]['cmap_type']\n sz = np.shape(subset_df.index.values)\n if cmap_type == 'static':\n colour_val = parameters[method]['colour']\n colours = colour_val*np.ones((sz[0],3))\n elif cmap_type == 'continuous':\n cmap_column = parameters[method]['cmap_column']\n colour_data = subset_df[[cmap_column]].values\n cmap_max = get_param_val(parameters[method]['cmap_max']) / parameters[method]['cmap_scale']\n cmap_name = 'jet'\n colour_obj = plt.get_cmap(cmap_name, np.size(colour_data))\n colour_vals = 255 * colour_obj(colour_data / cmap_max)\n colours = []\n for colour in colour_vals:\n colours.append((colour[0,0], colour[0,1], colour[0,2]))\n colours = np.array(colours)\n return colours\n\n\ndef cmap_variables(data, f, parameters, method=None):\n '''\n Convenience method to extract the inputs necessary for building a colourmap\n\n :param data: DataStore\n :param f: frame number\n :param parameters: annotation parameters dictionary\n :param method: String of the method being used to annotate\n\n :return: Numpy array of data to be used in colour coding, type of colour map, maximum value to scale data.\n '''\n cmap_column = parameters[method]['cmap_column']\n if cmap_column is None:\n sz = np.shape(data.df.loc[f].index.values)\n colour_data = np.ones(sz)\n cmap_type='discrete'\n else:\n colour_data = data.get_info(f, cmap_column)\n cmap_type = parameters[method]['cmap_type']\n cmax_max = get_param_val(parameters[method]['cmap_max'])/10\n return colour_data, cmap_type, cmax_max\n\ndef colourmap(colour_data, cmap_type=None, cmax_max=None):\n '''\n cmap could have different use cases:\n 1: 'discrete' data is colour coded according to some classifier\n 2: 'continuous' data is colour coded according to continuous scale\n\n Colormap definitions: https://matplotlib.org/3.1.1/gallery/color/colormap_reference.html\n case 1 colourmap is Set1 of Matplotlibs Qualitative color maps\n case 2 colourmap is seismic from diverging colormaps\n\n\n :param data: Datastore object containing column upon which to perform the mapping\n :param f: integer specifying frame number\n :param col_name: string specifying column in dataframe of Datastore which supplies values for colour coding\n :param parameters: Dictionary specifying parameters\n\n :return: a\n '''\n\n if cmap_type == 'discrete':\n cmap_name = 'Set1'\n elif cmap_type == 'continuous':\n cmap_name='jet'\n else:\n cmap_name = cmap_type\n\n if cmax_max is None:\n cmax_max = np.max(colour_data)\n\n colour_obj = plt.get_cmap(cmap_name, np.size(colour_data))\n colour_vals = 255*colour_obj(colour_data/cmax_max)\n colours=[]\n for colour in colour_vals:\n colours.append((colour[0],colour[1],colour[2]))\n return np.array(colours)\n\n\n\n\nif __name__=='__main__':\n colour = plt.get_cmap('Set1',2)\n print(colour(np.array([0.01,0.1])))","sub_path":"general/cmap.py","file_name":"cmap.py","file_ext":"py","file_size_in_byte":3198,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"14"}