code
stringlengths
22
1.05M
apis
listlengths
1
3.31k
extract_api
stringlengths
75
3.25M
import unittest # time complexity O(n**2) # space complexity O(1) def selection_sort(arr): n = len(arr) while n >= 2: value_max = arr[0] index_max = 0 for i in range(1, n): if arr[i] > value_max: value_max = arr[i] index_max = i arr[n-1], arr[index_max] = arr[index_max], arr[n-1] n -= 1 return arr class Test(unittest.TestCase): def test_selection_sort(self): arr = [3,6,9,7,8,4,2,5,1,9,6] self.assertEqual(selection_sort(arr), [1,2,3,4,5,6,6,7,8,9,9]); if __name__ == "__main__": unittest.main()
[ "unittest.main" ]
[((608, 623), 'unittest.main', 'unittest.main', ([], {}), '()\n', (621, 623), False, 'import unittest\n')]
# !/usr/bin/python3 # -*- coding: utf-8 -*- # *****************************************************************************/ # * Authors: <NAME>, <NAME> # *****************************************************************************/ import os, datetime, traceback, optparse, shutil import PyInstaller.__main__ def main(): ############################################## # Main function, Options ############################################## parser = optparse.OptionParser() parser.add_option("--installer", dest='installer', action='store_true', default=False, help='Boolean to create installer executable. If false, GUI executable is created ' 'instead') (options, args) = parser.parse_args() if options.installer is True: print("Generating Installer...") pwd = os.getcwd() dirPath = os.path.join(pwd, 'data/installer') if os.path.exists(dirPath) and os.path.isdir(dirPath): print("Previous executable exists. Removing it before generating the new one") shutil.rmtree(dirPath) PyInstaller.__main__.run([ 'src/installer.py', '--onefile', '--clean', '--debug=all', # '--windowed', '--key=RAADEngineTesting123456', '--workpath=data/installer/temp', '--distpath=data/installer', '--specpath=data/installer' ]) else: print("Generating main GUI...") pwd = os.getcwd() dirPath = os.path.join(pwd, 'data/binary') if os.path.exists(dirPath) and os.path.isdir(dirPath): print("Previous executable exists. Removing it before generating the new one") shutil.rmtree(dirPath) logoLocation = '{0}/src/software/{1}'.format(os.getcwd(), 'Intel_IntelligentSystems.png') newLocation = '{0}/data/binary/software'.format(os.getcwd()) PyInstaller.__main__.run([ 'src/software/gui.py', '--onefile', '--clean', '--debug=all', # '--windowed', '--add-data=' + logoLocation + os.pathsep + ".", '--key=RAADEngineTesting123456', '--workpath=data/binary/temp', '--distpath=data/binary', '--specpath=data/binary', ]) os.mkdir(newLocation) shutil.copyfile(logoLocation, newLocation + '/Intel_IntelligentSystems.png') if __name__ == '__main__': """Performs execution delta of the process.""" pStart = datetime.datetime.now() try: main() except Exception as errorMain: print("Fail End Process: {0}".format(errorMain)) traceback.print_exc() qStop = datetime.datetime.now() print("Execution time: " + str(qStop - pStart))
[ "os.path.exists", "os.path.join", "optparse.OptionParser", "os.getcwd", "datetime.datetime.now", "shutil.copyfile", "os.path.isdir", "os.mkdir", "shutil.rmtree", "traceback.print_exc" ]
[((482, 505), 'optparse.OptionParser', 'optparse.OptionParser', ([], {}), '()\n', (503, 505), False, 'import os, datetime, traceback, optparse, shutil\n'), ((2649, 2672), 'datetime.datetime.now', 'datetime.datetime.now', ([], {}), '()\n', (2670, 2672), False, 'import os, datetime, traceback, optparse, shutil\n'), ((2837, 2860), 'datetime.datetime.now', 'datetime.datetime.now', ([], {}), '()\n', (2858, 2860), False, 'import os, datetime, traceback, optparse, shutil\n'), ((896, 907), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (905, 907), False, 'import os, datetime, traceback, optparse, shutil\n'), ((927, 962), 'os.path.join', 'os.path.join', (['pwd', '"""data/installer"""'], {}), "(pwd, 'data/installer')\n", (939, 962), False, 'import os, datetime, traceback, optparse, shutil\n'), ((1588, 1599), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (1597, 1599), False, 'import os, datetime, traceback, optparse, shutil\n'), ((1619, 1651), 'os.path.join', 'os.path.join', (['pwd', '"""data/binary"""'], {}), "(pwd, 'data/binary')\n", (1631, 1651), False, 'import os, datetime, traceback, optparse, shutil\n'), ((2443, 2464), 'os.mkdir', 'os.mkdir', (['newLocation'], {}), '(newLocation)\n', (2451, 2464), False, 'import os, datetime, traceback, optparse, shutil\n'), ((2474, 2550), 'shutil.copyfile', 'shutil.copyfile', (['logoLocation', "(newLocation + '/Intel_IntelligentSystems.png')"], {}), "(logoLocation, newLocation + '/Intel_IntelligentSystems.png')\n", (2489, 2550), False, 'import os, datetime, traceback, optparse, shutil\n'), ((975, 998), 'os.path.exists', 'os.path.exists', (['dirPath'], {}), '(dirPath)\n', (989, 998), False, 'import os, datetime, traceback, optparse, shutil\n'), ((1003, 1025), 'os.path.isdir', 'os.path.isdir', (['dirPath'], {}), '(dirPath)\n', (1016, 1025), False, 'import os, datetime, traceback, optparse, shutil\n'), ((1132, 1154), 'shutil.rmtree', 'shutil.rmtree', (['dirPath'], {}), '(dirPath)\n', (1145, 1154), False, 'import os, datetime, traceback, optparse, shutil\n'), ((1664, 1687), 'os.path.exists', 'os.path.exists', (['dirPath'], {}), '(dirPath)\n', (1678, 1687), False, 'import os, datetime, traceback, optparse, shutil\n'), ((1692, 1714), 'os.path.isdir', 'os.path.isdir', (['dirPath'], {}), '(dirPath)\n', (1705, 1714), False, 'import os, datetime, traceback, optparse, shutil\n'), ((1821, 1843), 'shutil.rmtree', 'shutil.rmtree', (['dirPath'], {}), '(dirPath)\n', (1834, 1843), False, 'import os, datetime, traceback, optparse, shutil\n'), ((1898, 1909), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (1907, 1909), False, 'import os, datetime, traceback, optparse, shutil\n'), ((2000, 2011), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (2009, 2011), False, 'import os, datetime, traceback, optparse, shutil\n'), ((2802, 2823), 'traceback.print_exc', 'traceback.print_exc', ([], {}), '()\n', (2821, 2823), False, 'import os, datetime, traceback, optparse, shutil\n')]
from .database import db_session, init_db from .models import User, Book, BookRental from sqlalchemy import func import datetime import logging init_db() def get_tables(db_table): """ @author : <NAME> :param db_table: database table in model.py :type db_table: database model Object :return type: list[list] """ entries = [] queries = db_session.query(db_table) for q in queries: s = str(q).split('|') entries.append(s) return entries def add_entry(entry): """ @author : <NAME> :param entry: database table in model.py :type entry: database model Object ex) User(param..), Book(params..) etc.. :return Returns True if the operation succeeds, False if it fails :usage user = User(id, name...) add_entry(user) """ try: db_session.add(entry) db_session.commit() except Exception as ex: print(ex) return False logging.info("Database : Add Entry Success") logging.info(str(entry).split('|')) return True def delete_entry(db_table, id): """ @author : <NAME> :param db_table: database table in model.py :type db_table: database model Object :param id: database model entry's id :type id: int :return Returns True if the operation succeeds, False if it fails :usage delete_entry(User, 100) """ try: db_session.query(db_table).filter(db_table.id == id).delete() db_session.commit() except Exception as ex: print(ex) return False logging.info("Database : Delete Entry Success") return True def search_entry(db_table, condition, keyword): """ @author : <NAME> :param db_table: database table in model.py :type db_table: database model Object :param condition: search condition. ex)User.name :type condition: db_table.column :param keyword: search keyword. ex)"Lee" :type keyword: str or int :return filtered table. :usage **if keyword is str** entry = search_entry(User, User.name, "yongjjang") **if keyword is int** entry = search_entry(User, User.id, 200) """ if type(keyword) is str: result = db_session.query(db_table).filter(condition.ilike('%' + keyword + "%")).first() entry = str(result).split('|') return entry elif type(keyword) is int: id = keyword result = db_session.query(db_table).filter(condition == id).first() entry = str(result).split('|') return entry def get_max_id(db_table): try: return int(db_session.query(func.max(db_table.id)).scalar()) except: return 1 def get_rent_date(): rental_date = datetime.date.today() return_date = rental_date + datetime.timedelta(days=14) return str(rental_date), str(return_date) def parse_row(row): return str(row).split('|') if __name__ == "__main__": tst = search_entry(User, User.birthday, "2020%") print(tst) rst = User.query.all() ra = Book.query.filter(Book.name.like("asdasdasd")).all() if not ra: print("HI") # user = User(101, 'yong', '1995-10-06', 'M', 'yongjjang<EMAIL>', '010-1234-1231', 'static/images/testImage', True) # add_entry(user) # # if delete_entry(User, 101): # logging.info("삭제 성공") # else: # logging.info("삭제 실패") # # max_id = db_session.query(func.max(User.id)).scalar() # print(type(max_id), max_id) # # print(search_entry(User, User.name, "bi")) # for q in db_session.query(User).filter(User.name.like('%' + "A" + "%")): # print(q) # print(type(q)) # # result = db_session.query(User).filter(User.id == 1).all() # # for r in result: # print(r) # print(r.column_list)
[ "datetime.date.today", "logging.info", "sqlalchemy.func.max", "datetime.timedelta" ]
[((996, 1040), 'logging.info', 'logging.info', (['"""Database : Add Entry Success"""'], {}), "('Database : Add Entry Success')\n", (1008, 1040), False, 'import logging\n'), ((1640, 1687), 'logging.info', 'logging.info', (['"""Database : Delete Entry Success"""'], {}), "('Database : Delete Entry Success')\n", (1652, 1687), False, 'import logging\n'), ((2853, 2874), 'datetime.date.today', 'datetime.date.today', ([], {}), '()\n', (2872, 2874), False, 'import datetime\n'), ((2907, 2934), 'datetime.timedelta', 'datetime.timedelta', ([], {'days': '(14)'}), '(days=14)\n', (2925, 2934), False, 'import datetime\n'), ((2748, 2769), 'sqlalchemy.func.max', 'func.max', (['db_table.id'], {}), '(db_table.id)\n', (2756, 2769), False, 'from sqlalchemy import func\n')]
# -*- coding:utf-8 -*- from django.db import models import django.utils.timezone as timezone # 用户登录信息表(服务器、虚拟机) class ConnectionInfo(models.Model): # 用户连接相关信息 ssh_username = models.CharField(max_length=10, default='', verbose_name=u'ssh用户名', null=True) ssh_userpasswd = models.CharField(max_length=40, default='', verbose_name=u'ssh用户密码', null=True) ssh_hostip = models.CharField(max_length=40, default='', verbose_name=u'ssh登录的ip', null=True) ssh_host_port = models.CharField(max_length=10, default='', verbose_name=u'ssh登录的端口', null=True) ssh_rsa = models.CharField(max_length=64, default='', verbose_name=u'ssh私钥') rsa_pass = models.CharField(max_length=64, default='', verbose_name=u'私钥的密钥') # 0-登录失败,1-登录成功 ssh_status = models.IntegerField(default=0, verbose_name=u'用户连接状态,0-登录失败,1-登录成功') # 1-rsa登录,2-dsa登录,3-普通用户_rsa登录,4-docker成功,5-docker无法登录 ssh_type = models.IntegerField(default=0, verbose_name=u'用户连接类型, 1-rsa登录,2-dsa登录,' u'3-ssh_rsa登录,4-docker成功,5-docker无法登录') # 唯一对象标示 sn_key = models.CharField(max_length=256, verbose_name=u"唯一设备ID", default="") class Meta: verbose_name = u'用户登录信息表' verbose_name_plural = verbose_name db_table = "connectioninfo" #用户登录信息表(交换机、网络设备) class NetConnectionInfo(models.Model): tel_username = models.CharField(max_length=10, default='', verbose_name=u'用户名', null=True) tel_userpasswd = models.CharField(max_length=40, default='', verbose_name=u'设备用户密码', null=True) tel_enpasswd = models.CharField(max_length=40, default='', verbose_name=u'设备超级用户密码', null=True) tel_host_port = models.CharField(max_length=10, default='', verbose_name=u'设备登录的端口', null=True) tel_hostip = models.CharField(max_length=40, default='', verbose_name=u'设备登录的ip', null=True) # 0-登录失败,1-登录成功 tel_status = models.IntegerField(default=0, verbose_name=u'用户连接状态,0-登录失败,1-登录成功') tel_type = models.IntegerField(default=0, verbose_name=u'用户连接类型, 1-普通用户可登录,2-超级用户可登录') # 唯一对象标示 sn_key = models.CharField(max_length=256, verbose_name=u"唯一设备ID", default="") dev_info = models.ForeignKey('NetWorkInfo') class Meta: verbose_name = u'网络设备用户登录信息' verbose_name_plural = verbose_name db_table = "netconnectioninfo" # 机柜的信息 class CabinetInfo(models.Model): cab_name = models.CharField(max_length=10, verbose_name=u'机柜编号') # 1-10分别代表1~10层 cab_lever = models.CharField(max_length=2, verbose_name=u'机器U数,1-10分别代表1~10层') class Meta: verbose_name = u'机柜信息表' verbose_name_plural = verbose_name db_table = "cabinetinfo" # 物理服务器信息 class PhysicalServerInfo(models.Model): # server_name = models.CharField(max_length=15, verbose_name=u'服务器名') server_ip = models.CharField(max_length=40, verbose_name=u'服务器IP') # 机器的类型 dell or other? machine_brand = models.CharField(max_length=60, default='--', verbose_name=u'服务器品牌') # 机器的类型 # machine_type = models.IntegerField(default=0, verbose_name=u'服务器,0-物理服务器,1-虚拟服务器,2-') system_ver = models.CharField(max_length=30, default='', verbose_name=u'操作系统版本') sys_hostname = models.CharField(max_length=15, verbose_name=u'操作系统主机名') mac = models.CharField(max_length=512, default='', verbose_name=u'MAC地址') sn = models.CharField(max_length=256, verbose_name=u'SN-主机的唯一标识', default='') vir_type = models.CharField(max_length=2, verbose_name=u'宿主机类型', default='') # 物理服务器关联的机柜 ser_cabin = models.ForeignKey('CabinetInfo') # 用户登录系统信息 conn_phy = models.ForeignKey('ConnectionInfo') class Meta: verbose_name = u'物理服务器信息表' verbose_name_plural = verbose_name db_table = "physicalserverinfo" # 虚拟设备信息 class VirtualServerInfo(models.Model): # server_name = models.CharField(max_length=15, verbose_name=u'服务器名') server_ip = models.CharField(max_length=40, verbose_name=u'服务器IP') # 机器的类型 0=kvm,2=虚拟资产,3=网络设备 0=其他类型(未知) server_type = models.CharField(max_length=80, default='', verbose_name=u'服务器类型:kvm,Vmware,Docker,others') system_ver = models.CharField(max_length=30, default='', verbose_name=u'操作系统版本') sys_hostname = models.CharField(max_length=15, verbose_name=u'操作系统主机名') mac = models.CharField(max_length=512, default='', verbose_name=u'MAC地址') sn = models.CharField(max_length=256, verbose_name=u'SN-主机的唯一标识', default='') # 虚拟设备关联的物理服务器 vir_phy = models.ForeignKey('PhysicalServerInfo') # 用户登录系统信息 conn_vir = models.ForeignKey('ConnectionInfo') class Meta: verbose_name = u'虚拟设备表' verbose_name_plural = verbose_name db_table = "virtualserverinfo" # 网络设备表 class NetWorkInfo(models.Model): host_ip = models.CharField(max_length=40, verbose_name=u'网络设备ip') host_name = models.CharField(max_length=10, verbose_name=u'网络设备名') sn = models.CharField(max_length=256, verbose_name=u"SN-设备的唯一标识", default="") # 网络设备所在的机柜 net_cab = models.ForeignKey('CabinetInfo') class Meta: verbose_name = u'网络设备表' verbose_name_plural = verbose_name db_table = "networkinfo" class OtherMachineInfo(models.Model): ip = models.CharField(max_length=40, verbose_name=u'设备ip') sn_key = models.CharField(max_length=256, verbose_name=u'设备的唯一标识') machine_name = models.CharField(max_length=20, verbose_name=u'设备名称') remark = models.TextField(default='', verbose_name=u'备注') reson_str = models.CharField(max_length=128,verbose_name=u"归纳原因",default='') # 关联的机柜 oth_cab = models.ForeignKey('CabinetInfo') class Meta: verbose_name = u'其它设备表' verbose_name_plural = verbose_name db_table = 'othermachineinfo' class StatisticsRecord(models.Model): datatime = models.DateTimeField(verbose_name=u"更新时间",default=timezone.now().strftime('%Y-%m-%d')) all_count = models.IntegerField(verbose_name=u"所有设备数量",default=0) pyh_count = models.IntegerField(verbose_name=u"物理设备数量",default=0) net_count = models.IntegerField(verbose_name=u"网络设备数量",default=0) other_count = models.IntegerField(verbose_name=u"其他设备数量",default=0) kvm_count = models.IntegerField(verbose_name=u"KVM设备数量",default=0) docker_count = models.IntegerField(verbose_name=u"Docker设备数量",default=0) vmx_count = models.IntegerField(verbose_name=u"VMX设备数量",default=0) class Meta: verbose_name = u'扫描后的汇总硬件统计信息' verbose_name_plural = verbose_name db_table = 'statisticsrecord'
[ "django.db.models.TextField", "django.db.models.ForeignKey", "django.db.models.IntegerField", "django.utils.timezone.now", "django.db.models.CharField" ]
[((184, 262), 'django.db.models.CharField', 'models.CharField', ([], {'max_length': '(10)', 'default': '""""""', 'verbose_name': 'u"""ssh用户名"""', 'null': '(True)'}), "(max_length=10, default='', verbose_name=u'ssh用户名', null=True)\n", (200, 262), False, 'from django.db import models\n'), ((284, 363), 'django.db.models.CharField', 'models.CharField', ([], {'max_length': '(40)', 'default': '""""""', 'verbose_name': 'u"""ssh用户密码"""', 'null': '(True)'}), "(max_length=40, default='', verbose_name=u'ssh用户密码', null=True)\n", (300, 363), False, 'from django.db import models\n'), ((381, 466), 'django.db.models.CharField', 'models.CharField', ([], {'max_length': '(40)', 'default': '""""""', 'verbose_name': 'u"""ssh登录的ip"""', 'null': '(True)'}), "(max_length=40, default='', verbose_name=u'ssh登录的ip', null=True\n )\n", (397, 466), False, 'from django.db import models\n'), ((482, 567), 'django.db.models.CharField', 'models.CharField', ([], {'max_length': '(10)', 'default': '""""""', 'verbose_name': 'u"""ssh登录的端口"""', 'null': '(True)'}), "(max_length=10, default='', verbose_name=u'ssh登录的端口', null=True\n )\n", (498, 567), False, 'from django.db import models\n'), ((577, 643), 'django.db.models.CharField', 'models.CharField', ([], {'max_length': '(64)', 'default': '""""""', 'verbose_name': 'u"""ssh私钥"""'}), "(max_length=64, default='', verbose_name=u'ssh私钥')\n", (593, 643), False, 'from django.db import models\n'), ((659, 725), 'django.db.models.CharField', 'models.CharField', ([], {'max_length': '(64)', 'default': '""""""', 'verbose_name': 'u"""私钥的密钥"""'}), "(max_length=64, default='', verbose_name=u'私钥的密钥')\n", (675, 725), False, 'from django.db import models\n'), ((763, 831), 'django.db.models.IntegerField', 'models.IntegerField', ([], {'default': '(0)', 'verbose_name': 'u"""用户连接状态,0-登录失败,1-登录成功"""'}), "(default=0, verbose_name=u'用户连接状态,0-登录失败,1-登录成功')\n", (782, 831), False, 'from django.db import models\n'), ((906, 1018), 'django.db.models.IntegerField', 'models.IntegerField', ([], {'default': '(0)', 'verbose_name': 'u"""用户连接类型, 1-rsa登录,2-dsa登录,3-ssh_rsa登录,4-docker成功,5-docker无法登录"""'}), "(default=0, verbose_name=\n u'用户连接类型, 1-rsa登录,2-dsa登录,3-ssh_rsa登录,4-docker成功,5-docker无法登录')\n", (925, 1018), False, 'from django.db import models\n'), ((1103, 1171), 'django.db.models.CharField', 'models.CharField', ([], {'max_length': '(256)', 'verbose_name': 'u"""唯一设备ID"""', 'default': '""""""'}), "(max_length=256, verbose_name=u'唯一设备ID', default='')\n", (1119, 1171), False, 'from django.db import models\n'), ((1380, 1455), 'django.db.models.CharField', 'models.CharField', ([], {'max_length': '(10)', 'default': '""""""', 'verbose_name': 'u"""用户名"""', 'null': '(True)'}), "(max_length=10, default='', verbose_name=u'用户名', null=True)\n", (1396, 1455), False, 'from django.db import models\n'), ((1477, 1555), 'django.db.models.CharField', 'models.CharField', ([], {'max_length': '(40)', 'default': '""""""', 'verbose_name': 'u"""设备用户密码"""', 'null': '(True)'}), "(max_length=40, default='', verbose_name=u'设备用户密码', null=True)\n", (1493, 1555), False, 'from django.db import models\n'), ((1575, 1660), 'django.db.models.CharField', 'models.CharField', ([], {'max_length': '(40)', 'default': '""""""', 'verbose_name': 'u"""设备超级用户密码"""', 'null': '(True)'}), "(max_length=40, default='', verbose_name=u'设备超级用户密码', null=True\n )\n", (1591, 1660), False, 'from django.db import models\n'), ((1676, 1755), 'django.db.models.CharField', 'models.CharField', ([], {'max_length': '(10)', 'default': '""""""', 'verbose_name': 'u"""设备登录的端口"""', 'null': '(True)'}), "(max_length=10, default='', verbose_name=u'设备登录的端口', null=True)\n", (1692, 1755), False, 'from django.db import models\n'), ((1773, 1852), 'django.db.models.CharField', 'models.CharField', ([], {'max_length': '(40)', 'default': '""""""', 'verbose_name': 'u"""设备登录的ip"""', 'null': '(True)'}), "(max_length=40, default='', verbose_name=u'设备登录的ip', null=True)\n", (1789, 1852), False, 'from django.db import models\n'), ((1891, 1959), 'django.db.models.IntegerField', 'models.IntegerField', ([], {'default': '(0)', 'verbose_name': 'u"""用户连接状态,0-登录失败,1-登录成功"""'}), "(default=0, verbose_name=u'用户连接状态,0-登录失败,1-登录成功')\n", (1910, 1959), False, 'from django.db import models\n'), ((1975, 2050), 'django.db.models.IntegerField', 'models.IntegerField', ([], {'default': '(0)', 'verbose_name': 'u"""用户连接类型, 1-普通用户可登录,2-超级用户可登录"""'}), "(default=0, verbose_name=u'用户连接类型, 1-普通用户可登录,2-超级用户可登录')\n", (1994, 2050), False, 'from django.db import models\n'), ((2077, 2145), 'django.db.models.CharField', 'models.CharField', ([], {'max_length': '(256)', 'verbose_name': 'u"""唯一设备ID"""', 'default': '""""""'}), "(max_length=256, verbose_name=u'唯一设备ID', default='')\n", (2093, 2145), False, 'from django.db import models\n'), ((2162, 2194), 'django.db.models.ForeignKey', 'models.ForeignKey', (['"""NetWorkInfo"""'], {}), "('NetWorkInfo')\n", (2179, 2194), False, 'from django.db import models\n'), ((2387, 2440), 'django.db.models.CharField', 'models.CharField', ([], {'max_length': '(10)', 'verbose_name': 'u"""机柜编号"""'}), "(max_length=10, verbose_name=u'机柜编号')\n", (2403, 2440), False, 'from django.db import models\n'), ((2477, 2543), 'django.db.models.CharField', 'models.CharField', ([], {'max_length': '(2)', 'verbose_name': 'u"""机器U数,1-10分别代表1~10层"""'}), "(max_length=2, verbose_name=u'机器U数,1-10分别代表1~10层')\n", (2493, 2543), False, 'from django.db import models\n'), ((2811, 2865), 'django.db.models.CharField', 'models.CharField', ([], {'max_length': '(40)', 'verbose_name': 'u"""服务器IP"""'}), "(max_length=40, verbose_name=u'服务器IP')\n", (2827, 2865), False, 'from django.db import models\n'), ((2913, 2981), 'django.db.models.CharField', 'models.CharField', ([], {'max_length': '(60)', 'default': '"""--"""', 'verbose_name': 'u"""服务器品牌"""'}), "(max_length=60, default='--', verbose_name=u'服务器品牌')\n", (2929, 2981), False, 'from django.db import models\n'), ((3103, 3170), 'django.db.models.CharField', 'models.CharField', ([], {'max_length': '(30)', 'default': '""""""', 'verbose_name': 'u"""操作系统版本"""'}), "(max_length=30, default='', verbose_name=u'操作系统版本')\n", (3119, 3170), False, 'from django.db import models\n'), ((3190, 3246), 'django.db.models.CharField', 'models.CharField', ([], {'max_length': '(15)', 'verbose_name': 'u"""操作系统主机名"""'}), "(max_length=15, verbose_name=u'操作系统主机名')\n", (3206, 3246), False, 'from django.db import models\n'), ((3257, 3324), 'django.db.models.CharField', 'models.CharField', ([], {'max_length': '(512)', 'default': '""""""', 'verbose_name': 'u"""MAC地址"""'}), "(max_length=512, default='', verbose_name=u'MAC地址')\n", (3273, 3324), False, 'from django.db import models\n'), ((3334, 3406), 'django.db.models.CharField', 'models.CharField', ([], {'max_length': '(256)', 'verbose_name': 'u"""SN-主机的唯一标识"""', 'default': '""""""'}), "(max_length=256, verbose_name=u'SN-主机的唯一标识', default='')\n", (3350, 3406), False, 'from django.db import models\n'), ((3422, 3487), 'django.db.models.CharField', 'models.CharField', ([], {'max_length': '(2)', 'verbose_name': 'u"""宿主机类型"""', 'default': '""""""'}), "(max_length=2, verbose_name=u'宿主机类型', default='')\n", (3438, 3487), False, 'from django.db import models\n'), ((3521, 3553), 'django.db.models.ForeignKey', 'models.ForeignKey', (['"""CabinetInfo"""'], {}), "('CabinetInfo')\n", (3538, 3553), False, 'from django.db import models\n'), ((3584, 3619), 'django.db.models.ForeignKey', 'models.ForeignKey', (['"""ConnectionInfo"""'], {}), "('ConnectionInfo')\n", (3601, 3619), False, 'from django.db import models\n'), ((3895, 3949), 'django.db.models.CharField', 'models.CharField', ([], {'max_length': '(40)', 'verbose_name': 'u"""服务器IP"""'}), "(max_length=40, verbose_name=u'服务器IP')\n", (3911, 3949), False, 'from django.db import models\n'), ((4011, 4107), 'django.db.models.CharField', 'models.CharField', ([], {'max_length': '(80)', 'default': '""""""', 'verbose_name': 'u"""服务器类型:kvm,Vmware,Docker,others"""'}), "(max_length=80, default='', verbose_name=\n u'服务器类型:kvm,Vmware,Docker,others')\n", (4027, 4107), False, 'from django.db import models\n'), ((4120, 4187), 'django.db.models.CharField', 'models.CharField', ([], {'max_length': '(30)', 'default': '""""""', 'verbose_name': 'u"""操作系统版本"""'}), "(max_length=30, default='', verbose_name=u'操作系统版本')\n", (4136, 4187), False, 'from django.db import models\n'), ((4207, 4263), 'django.db.models.CharField', 'models.CharField', ([], {'max_length': '(15)', 'verbose_name': 'u"""操作系统主机名"""'}), "(max_length=15, verbose_name=u'操作系统主机名')\n", (4223, 4263), False, 'from django.db import models\n'), ((4274, 4341), 'django.db.models.CharField', 'models.CharField', ([], {'max_length': '(512)', 'default': '""""""', 'verbose_name': 'u"""MAC地址"""'}), "(max_length=512, default='', verbose_name=u'MAC地址')\n", (4290, 4341), False, 'from django.db import models\n'), ((4351, 4423), 'django.db.models.CharField', 'models.CharField', ([], {'max_length': '(256)', 'verbose_name': 'u"""SN-主机的唯一标识"""', 'default': '""""""'}), "(max_length=256, verbose_name=u'SN-主机的唯一标识', default='')\n", (4367, 4423), False, 'from django.db import models\n'), ((4458, 4497), 'django.db.models.ForeignKey', 'models.ForeignKey', (['"""PhysicalServerInfo"""'], {}), "('PhysicalServerInfo')\n", (4475, 4497), False, 'from django.db import models\n'), ((4528, 4563), 'django.db.models.ForeignKey', 'models.ForeignKey', (['"""ConnectionInfo"""'], {}), "('ConnectionInfo')\n", (4545, 4563), False, 'from django.db import models\n'), ((4752, 4807), 'django.db.models.CharField', 'models.CharField', ([], {'max_length': '(40)', 'verbose_name': 'u"""网络设备ip"""'}), "(max_length=40, verbose_name=u'网络设备ip')\n", (4768, 4807), False, 'from django.db import models\n'), ((4824, 4878), 'django.db.models.CharField', 'models.CharField', ([], {'max_length': '(10)', 'verbose_name': 'u"""网络设备名"""'}), "(max_length=10, verbose_name=u'网络设备名')\n", (4840, 4878), False, 'from django.db import models\n'), ((4888, 4960), 'django.db.models.CharField', 'models.CharField', ([], {'max_length': '(256)', 'verbose_name': 'u"""SN-设备的唯一标识"""', 'default': '""""""'}), "(max_length=256, verbose_name=u'SN-设备的唯一标识', default='')\n", (4904, 4960), False, 'from django.db import models\n'), ((4992, 5024), 'django.db.models.ForeignKey', 'models.ForeignKey', (['"""CabinetInfo"""'], {}), "('CabinetInfo')\n", (5009, 5024), False, 'from django.db import models\n'), ((5200, 5253), 'django.db.models.CharField', 'models.CharField', ([], {'max_length': '(40)', 'verbose_name': 'u"""设备ip"""'}), "(max_length=40, verbose_name=u'设备ip')\n", (5216, 5253), False, 'from django.db import models\n'), ((5267, 5324), 'django.db.models.CharField', 'models.CharField', ([], {'max_length': '(256)', 'verbose_name': 'u"""设备的唯一标识"""'}), "(max_length=256, verbose_name=u'设备的唯一标识')\n", (5283, 5324), False, 'from django.db import models\n'), ((5344, 5397), 'django.db.models.CharField', 'models.CharField', ([], {'max_length': '(20)', 'verbose_name': 'u"""设备名称"""'}), "(max_length=20, verbose_name=u'设备名称')\n", (5360, 5397), False, 'from django.db import models\n'), ((5411, 5459), 'django.db.models.TextField', 'models.TextField', ([], {'default': '""""""', 'verbose_name': 'u"""备注"""'}), "(default='', verbose_name=u'备注')\n", (5427, 5459), False, 'from django.db import models\n'), ((5476, 5542), 'django.db.models.CharField', 'models.CharField', ([], {'max_length': '(128)', 'verbose_name': 'u"""归纳原因"""', 'default': '""""""'}), "(max_length=128, verbose_name=u'归纳原因', default='')\n", (5492, 5542), False, 'from django.db import models\n'), ((5567, 5599), 'django.db.models.ForeignKey', 'models.ForeignKey', (['"""CabinetInfo"""'], {}), "('CabinetInfo')\n", (5584, 5599), False, 'from django.db import models\n'), ((5888, 5942), 'django.db.models.IntegerField', 'models.IntegerField', ([], {'verbose_name': 'u"""所有设备数量"""', 'default': '(0)'}), "(verbose_name=u'所有设备数量', default=0)\n", (5907, 5942), False, 'from django.db import models\n'), ((5958, 6012), 'django.db.models.IntegerField', 'models.IntegerField', ([], {'verbose_name': 'u"""物理设备数量"""', 'default': '(0)'}), "(verbose_name=u'物理设备数量', default=0)\n", (5977, 6012), False, 'from django.db import models\n'), ((6028, 6082), 'django.db.models.IntegerField', 'models.IntegerField', ([], {'verbose_name': 'u"""网络设备数量"""', 'default': '(0)'}), "(verbose_name=u'网络设备数量', default=0)\n", (6047, 6082), False, 'from django.db import models\n'), ((6100, 6154), 'django.db.models.IntegerField', 'models.IntegerField', ([], {'verbose_name': 'u"""其他设备数量"""', 'default': '(0)'}), "(verbose_name=u'其他设备数量', default=0)\n", (6119, 6154), False, 'from django.db import models\n'), ((6170, 6225), 'django.db.models.IntegerField', 'models.IntegerField', ([], {'verbose_name': 'u"""KVM设备数量"""', 'default': '(0)'}), "(verbose_name=u'KVM设备数量', default=0)\n", (6189, 6225), False, 'from django.db import models\n'), ((6244, 6302), 'django.db.models.IntegerField', 'models.IntegerField', ([], {'verbose_name': 'u"""Docker设备数量"""', 'default': '(0)'}), "(verbose_name=u'Docker设备数量', default=0)\n", (6263, 6302), False, 'from django.db import models\n'), ((6318, 6373), 'django.db.models.IntegerField', 'models.IntegerField', ([], {'verbose_name': 'u"""VMX设备数量"""', 'default': '(0)'}), "(verbose_name=u'VMX设备数量', default=0)\n", (6337, 6373), False, 'from django.db import models\n'), ((5843, 5857), 'django.utils.timezone.now', 'timezone.now', ([], {}), '()\n', (5855, 5857), True, 'import django.utils.timezone as timezone\n')]
# -*- coding: utf-8 -*- """ Tencent is pleased to support the open source community by making BK-BASE 蓝鲸基础平台 available. Copyright (C) 2021 THL A29 Limited, a Tencent company. All rights reserved. BK-BASE 蓝鲸基础平台 is licensed under the MIT License. License for BK-BASE 蓝鲸基础平台: -------------------------------------------------------------------- Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. """ from django.utils.translation import ugettext_lazy as _ from dataflow.batch.exceptions.comp_execptions import BatchTimeCompareError, BatchUnsupportedOperationError from dataflow.batch.periodic.param_info.builder.periodic_batch_job_builder import PeriodicBatchJobBuilder from dataflow.batch.utils.time_util import BatchTimeTuple class ProcessingsValidator(object): def validate(self, periodic_batch_info_params_obj): """ :param periodic_batch_info_params_obj: :type periodic_batch_info_params_obj: dataflow.batch.periodic.param_info.periodic_batch_info_params.PeriodicBatchInfoParams """ self.validate_input(periodic_batch_info_params_obj) self.validate_output_data_offset(periodic_batch_info_params_obj) def validate_input(self, periodic_batch_info_params_obj): """ :param periodic_batch_info_params_obj: :type periodic_batch_info_params_obj: dataflow.batch.periodic.param_info.periodic_batch_info_params.PeriodicBatchInfoParams """ for input_table in periodic_batch_info_params_obj.input_result_tables: if ( input_table.window_type.lower() == "scroll" or input_table.window_type.lower() == "slide" or input_table.window_type.lower() == "accumulate" ): self.__check_greater_than_value(input_table.window_offset, "window_offset", "0H") if input_table.window_type.lower() == "slide" or input_table.window_type.lower() == "accumulate": self.__check_greater_than_value(input_table.window_size, "window_size", "0H") if input_table.window_type.lower() == "accumulate": self.__check_greater_than_value(input_table.window_start_offset, "window_start_offset", "0H") self.__check_greater_than_value(input_table.window_end_offset, "window_end_offset", "0H") self.__check_less_than_value( input_table.window_start_offset, "window_start_offset", input_table.window_size, ) self.__check_less_than_value( input_table.window_end_offset, "window_end_offset", input_table.window_size, ) self.__check_if_null(input_table.accumulate_start_time, "accumulate_start_time") def __check_greater_than_value(self, check_value, check_name, limit_value): self.__check_if_null(check_value, check_name) limit_time_tuple = BatchTimeTuple() limit_time_tuple.from_jobnavi_format(limit_value) check_value_tuple = BatchTimeTuple() check_value_tuple.from_jobnavi_format(check_value) if check_value_tuple < limit_time_tuple: raise BatchUnsupportedOperationError(_("{}数值必须大于{}".format(check_name, limit_value))) def __check_less_than_value(self, check_value, check_name, limit_value): self.__check_if_null(check_value, check_name) limit_time_tuple = BatchTimeTuple() limit_time_tuple.from_jobnavi_format(limit_value) check_value_tuple = BatchTimeTuple() check_value_tuple.from_jobnavi_format(check_value) if check_value_tuple > limit_time_tuple: raise BatchUnsupportedOperationError(_("{}数值必须小于{}".format(check_name, limit_value))) def __check_if_null(self, check_value, check_name): if check_value is None: raise BatchUnsupportedOperationError(_("{}数值不能是null".format(check_name))) def validate_output_data_offset(self, periodic_batch_info_params_obj): """ :param periodic_batch_info_params_obj: :type periodic_batch_info_params_obj: dataflow.batch.periodic.param_info.periodic_batch_info_params.PeriodicBatchInfoParams """ try: PeriodicBatchJobBuilder.calculate_output_offset( periodic_batch_info_params_obj.input_result_tables, periodic_batch_info_params_obj.output_result_tables[0], periodic_batch_info_params_obj.count_freq, periodic_batch_info_params_obj.schedule_period, ) except BatchTimeCompareError: raise BatchUnsupportedOperationError(_("当前配置无法算出默认存储分区,请激活自定义出库配置"))
[ "django.utils.translation.ugettext_lazy", "dataflow.batch.periodic.param_info.builder.periodic_batch_job_builder.PeriodicBatchJobBuilder.calculate_output_offset", "dataflow.batch.utils.time_util.BatchTimeTuple" ]
[((3964, 3980), 'dataflow.batch.utils.time_util.BatchTimeTuple', 'BatchTimeTuple', ([], {}), '()\n', (3978, 3980), False, 'from dataflow.batch.utils.time_util import BatchTimeTuple\n'), ((4067, 4083), 'dataflow.batch.utils.time_util.BatchTimeTuple', 'BatchTimeTuple', ([], {}), '()\n', (4081, 4083), False, 'from dataflow.batch.utils.time_util import BatchTimeTuple\n'), ((4449, 4465), 'dataflow.batch.utils.time_util.BatchTimeTuple', 'BatchTimeTuple', ([], {}), '()\n', (4463, 4465), False, 'from dataflow.batch.utils.time_util import BatchTimeTuple\n'), ((4552, 4568), 'dataflow.batch.utils.time_util.BatchTimeTuple', 'BatchTimeTuple', ([], {}), '()\n', (4566, 4568), False, 'from dataflow.batch.utils.time_util import BatchTimeTuple\n'), ((5262, 5522), 'dataflow.batch.periodic.param_info.builder.periodic_batch_job_builder.PeriodicBatchJobBuilder.calculate_output_offset', 'PeriodicBatchJobBuilder.calculate_output_offset', (['periodic_batch_info_params_obj.input_result_tables', 'periodic_batch_info_params_obj.output_result_tables[0]', 'periodic_batch_info_params_obj.count_freq', 'periodic_batch_info_params_obj.schedule_period'], {}), '(periodic_batch_info_params_obj\n .input_result_tables, periodic_batch_info_params_obj.\n output_result_tables[0], periodic_batch_info_params_obj.count_freq,\n periodic_batch_info_params_obj.schedule_period)\n', (5309, 5522), False, 'from dataflow.batch.periodic.param_info.builder.periodic_batch_job_builder import PeriodicBatchJobBuilder\n'), ((5675, 5705), 'django.utils.translation.ugettext_lazy', '_', (['"""当前配置无法算出默认存储分区,请激活自定义出库配置"""'], {}), "('当前配置无法算出默认存储分区,请激活自定义出库配置')\n", (5676, 5705), True, 'from django.utils.translation import ugettext_lazy as _\n')]
"""Test app.routes.build.""" import responses mock_product_data = { "bucket_name": "lsst-the-docs", "doc_repo": "https://github.com/lsst-sqre/test-059.git", "domain": "test-059.lsst.io", "fastly_domain": "n.global-ssl.fastly.net", "published_url": "https://test-059.lsst.io", "root_domain": "lsst.io", "root_fastly_domain": "n.global-ssl.fastly.net", "self_url": "https://keeper-staging.lsst.codes/products/test-059", "slug": "test-059", "surrogate_key": "235becbe0b8349aa88b7f6e086529d77", "title": "Test Technote Via Bot" } mock_editions_data = { "editions": [ "https://keeper-staging.lsst.codes/editions/388", "https://keeper-staging.lsst.codes/editions/390" ] } mock_edition_388_data = { "build_url": "https://keeper-staging.lsst.codes/builds/1322", "date_created": "2017-02-03T23:49:23Z", "date_ended": None, "date_rebuilt": "2017-02-03T23:51:21Z", "product_url": "https://keeper-staging.lsst.codes/products/test-059", "published_url": "https://test-059.lsst.io", "self_url": "https://keeper-staging.lsst.codes/editions/388", "slug": "main", "surrogate_key": "c1e29b6b1c97450c9d6d854ee3395ec9", "title": "Latest", "tracked_refs": [ "master" ] } mock_edition_390_data = { "build_url": "https://keeper-staging.lsst.codes/builds/1324", "date_created": "2017-02-09T23:40:57Z", "date_ended": None, "date_rebuilt": "2017-02-09T23:41:17Z", "product_url": "https://keeper-staging.lsst.codes/products/test-059", "published_url": "https://test-059.lsst.io/v/test-branch", "self_url": "https://keeper-staging.lsst.codes/editions/390", "slug": "test-branch", "surrogate_key": "99ab3d93b1b54a4ea49dbe1764b7ea6a", "title": "test-branch", "tracked_refs": [ "test-branch" ] } mock_builds_data = { "builds": [ "https://keeper-staging.lsst.codes/builds/1322", "https://keeper-staging.lsst.codes/builds/1324" ] } mock_build_1322_data = { "bucket_name": "lsst-the-docs", "bucket_root_dir": "test-059/builds/1", "date_created": "2017-02-03T23:51:08Z", "date_ended": None, "git_refs": [ "master" ], "github_requester": None, "product_url": "https://keeper-staging.lsst.codes/products/test-059", "published_url": "https://test-059.lsst.io/builds/1", "self_url": "https://keeper-staging.lsst.codes/builds/1322", "slug": "1", "surrogate_key": "006e34ec8f714aed956292645bb7e432", "uploaded": True } mock_build_1324_data = { "bucket_name": "lsst-the-docs", "bucket_root_dir": "test-059/builds/2", "date_created": "2017-02-09T23:40:57Z", "date_ended": None, "git_refs": [ "test-branch" ], "github_requester": None, "product_url": "https://keeper-staging.lsst.codes/products/test-059", "published_url": "https://test-059.lsst.io/builds/2", "self_url": "https://keeper-staging.lsst.codes/builds/1324", "slug": "2", "surrogate_key": "<KEY>", "uploaded": True } mock_bulk_data = { "product": mock_product_data, "editions": [ mock_edition_388_data, mock_edition_390_data ], "builds": [ mock_build_1322_data, mock_build_1324_data ] } @responses.activate def test_rebuild_dashboards(anon_client): """Test dashboard rebuilds with full client using new bulk metadata endpoint. """ responses.add( responses.GET, 'https://keeper-staging.lsst.codes/products/test-059/dashboard', json=mock_bulk_data, status=200, content_type='application/json') r = anon_client.post( '/build', { 'product_urls': ['https://keeper-staging.lsst.codes/' 'products/test-059'] } ) assert r.status == 202 @responses.activate def test_rebuild_dashboards_oldstyle(anon_client): """Test dashboard rebuilds with full client using original endpoints.""" responses.add( responses.GET, 'https://keeper-staging.lsst.codes/products/test-059/dashboard', json={}, status=404, content_type='application/json') responses.add( responses.GET, 'https://keeper-staging.lsst.codes/products/test-059', json=mock_product_data, status=200, content_type='application/json') responses.add( responses.GET, 'https://keeper-staging.lsst.codes/products/test-059/editions/', json=mock_editions_data, status=200, content_type='application/json') responses.add( responses.GET, 'https://keeper-staging.lsst.codes/editions/388', json=mock_edition_388_data, status=200, content_type='application/json') responses.add( responses.GET, 'https://keeper-staging.lsst.codes/editions/390', json=mock_edition_390_data, status=200, content_type='application/json') responses.add( responses.GET, 'https://keeper-staging.lsst.codes/products/test-059/builds/', json=mock_builds_data, status=200, content_type='application/json') responses.add( responses.GET, 'https://keeper-staging.lsst.codes/builds/1322', json=mock_build_1322_data, status=200, content_type='application/json') responses.add( responses.GET, 'https://keeper-staging.lsst.codes/builds/1324', json=mock_build_1324_data, status=200, content_type='application/json') r = anon_client.post( '/build', { 'product_urls': ['https://keeper-staging.lsst.codes/' 'products/test-059'] } ) assert r.status == 202
[ "responses.add" ]
[((3453, 3621), 'responses.add', 'responses.add', (['responses.GET', '"""https://keeper-staging.lsst.codes/products/test-059/dashboard"""'], {'json': 'mock_bulk_data', 'status': '(200)', 'content_type': '"""application/json"""'}), "(responses.GET,\n 'https://keeper-staging.lsst.codes/products/test-059/dashboard', json=\n mock_bulk_data, status=200, content_type='application/json')\n", (3466, 3621), False, 'import responses\n'), ((4022, 4178), 'responses.add', 'responses.add', (['responses.GET', '"""https://keeper-staging.lsst.codes/products/test-059/dashboard"""'], {'json': '{}', 'status': '(404)', 'content_type': '"""application/json"""'}), "(responses.GET,\n 'https://keeper-staging.lsst.codes/products/test-059/dashboard', json={\n }, status=404, content_type='application/json')\n", (4035, 4178), False, 'import responses\n'), ((4216, 4377), 'responses.add', 'responses.add', (['responses.GET', '"""https://keeper-staging.lsst.codes/products/test-059"""'], {'json': 'mock_product_data', 'status': '(200)', 'content_type': '"""application/json"""'}), "(responses.GET,\n 'https://keeper-staging.lsst.codes/products/test-059', json=\n mock_product_data, status=200, content_type='application/json')\n", (4229, 4377), False, 'import responses\n'), ((4415, 4587), 'responses.add', 'responses.add', (['responses.GET', '"""https://keeper-staging.lsst.codes/products/test-059/editions/"""'], {'json': 'mock_editions_data', 'status': '(200)', 'content_type': '"""application/json"""'}), "(responses.GET,\n 'https://keeper-staging.lsst.codes/products/test-059/editions/', json=\n mock_editions_data, status=200, content_type='application/json')\n", (4428, 4587), False, 'import responses\n'), ((4625, 4785), 'responses.add', 'responses.add', (['responses.GET', '"""https://keeper-staging.lsst.codes/editions/388"""'], {'json': 'mock_edition_388_data', 'status': '(200)', 'content_type': '"""application/json"""'}), "(responses.GET,\n 'https://keeper-staging.lsst.codes/editions/388', json=\n mock_edition_388_data, status=200, content_type='application/json')\n", (4638, 4785), False, 'import responses\n'), ((4823, 4983), 'responses.add', 'responses.add', (['responses.GET', '"""https://keeper-staging.lsst.codes/editions/390"""'], {'json': 'mock_edition_390_data', 'status': '(200)', 'content_type': '"""application/json"""'}), "(responses.GET,\n 'https://keeper-staging.lsst.codes/editions/390', json=\n mock_edition_390_data, status=200, content_type='application/json')\n", (4836, 4983), False, 'import responses\n'), ((5021, 5189), 'responses.add', 'responses.add', (['responses.GET', '"""https://keeper-staging.lsst.codes/products/test-059/builds/"""'], {'json': 'mock_builds_data', 'status': '(200)', 'content_type': '"""application/json"""'}), "(responses.GET,\n 'https://keeper-staging.lsst.codes/products/test-059/builds/', json=\n mock_builds_data, status=200, content_type='application/json')\n", (5034, 5189), False, 'import responses\n'), ((5227, 5385), 'responses.add', 'responses.add', (['responses.GET', '"""https://keeper-staging.lsst.codes/builds/1322"""'], {'json': 'mock_build_1322_data', 'status': '(200)', 'content_type': '"""application/json"""'}), "(responses.GET,\n 'https://keeper-staging.lsst.codes/builds/1322', json=\n mock_build_1322_data, status=200, content_type='application/json')\n", (5240, 5385), False, 'import responses\n'), ((5423, 5581), 'responses.add', 'responses.add', (['responses.GET', '"""https://keeper-staging.lsst.codes/builds/1324"""'], {'json': 'mock_build_1324_data', 'status': '(200)', 'content_type': '"""application/json"""'}), "(responses.GET,\n 'https://keeper-staging.lsst.codes/builds/1324', json=\n mock_build_1324_data, status=200, content_type='application/json')\n", (5436, 5581), False, 'import responses\n')]
from sklearn import tree from matplotlib import pyplot as plt from sklearn.model_selection import cross_val_score from sklearn.model_selection import train_test_split from sklearn import model_selection from sklearn import metrics import numpy as np import pandas as pd import seaborn as sns from sklearn.neighbors import KNeighborsClassifier from sklearn.linear_model import LogisticRegression from sklearn.naive_bayes import GaussianNB from sklearn.naive_bayes import MultinomialNB from sklearn.neighbors import KNeighborsClassifier from sklearn.model_selection import train_test_split from sklearn.preprocessing import MinMaxScaler from sklearn.preprocessing import StandardScaler from pandas import DataFrame data = pd.read_csv("heart.csv") # sns.set(style="ticks", color_codes=True) # plot=sns.pairplot(data) # plot.savefig("heart.png") # pd.crosstab(data.sex,data.target).plot(kind="bar",figsize=(15,6),color=['#1CA53B','#AA1111' ]) # plt.title('Heart Disease Frequency for Sex') # plt.xlabel('Sex (0 = Female, 1 = Male)') # plt.xticks(rotation=0) # plt.legend(["Haven't Disease", "Have Disease"]) # plt.ylabel('Frequency') # plt.savefig("heart1.png") # pd.crosstab(data.age,data.target).plot(kind="bar",figsize=(20,6)) # plt.title('Heart Disease Frequency for Ages') # plt.xlabel('Age') # plt.ylabel('Frequency') # plt.savefig('heartDiseaseAndAges.png') feature_names =["age","sex","cp","trestbps","chol" ,"fbs","restecg","thalach","exang","oldpeak","slope","ca","thal"] x = data[feature_names].values y = data["target"].values X_train, X_test, y_train, y_test = train_test_split(x, y, test_size=0.2, random_state=5,shuffle=True) feature_scaler = StandardScaler() X_train = feature_scaler.fit_transform(X_train) X_test = feature_scaler.transform(X_test) # Krange = range(1,30) # scores = {} # scores_list = [] # for k in Krange: # knn = KNeighborsClassifier(n_neighbors = k) # knn.fit(X_train,y_train) # y_pred = knn.predict(X_test) # scores[k] = metrics.accuracy_score(y_test,y_pred) # scores_list.append(metrics.accuracy_score(y_test,y_pred)) # plt.plot(Krange,scores_list) # plt.xlabel("Value of K") # plt.ylabel("Accuracy") # plt.savefig("k.png") # plt.show() model = KNeighborsClassifier(n_neighbors=7) model.fit(X_train,y_train) y_pred= model.predict(X_test) print("Accuracy KNN:",metrics.accuracy_score(y_test, y_pred)) X_train, X_test, y_train, y_test = train_test_split(x, y, test_size=0.2, random_state=5,shuffle=True) #Create a Gaussian Classifier gnb = GaussianNB() gnb.fit(X_train, y_train) y_pred = gnb.predict(X_test) print("Accuracy NB:",metrics.accuracy_score(y_test, y_pred))
[ "pandas.read_csv", "sklearn.model_selection.train_test_split", "sklearn.neighbors.KNeighborsClassifier", "sklearn.preprocessing.StandardScaler", "sklearn.naive_bayes.GaussianNB", "sklearn.metrics.accuracy_score" ]
[((725, 749), 'pandas.read_csv', 'pd.read_csv', (['"""heart.csv"""'], {}), "('heart.csv')\n", (736, 749), True, 'import pandas as pd\n'), ((1583, 1650), 'sklearn.model_selection.train_test_split', 'train_test_split', (['x', 'y'], {'test_size': '(0.2)', 'random_state': '(5)', 'shuffle': '(True)'}), '(x, y, test_size=0.2, random_state=5, shuffle=True)\n', (1599, 1650), False, 'from sklearn.model_selection import train_test_split\n'), ((1668, 1684), 'sklearn.preprocessing.StandardScaler', 'StandardScaler', ([], {}), '()\n', (1682, 1684), False, 'from sklearn.preprocessing import StandardScaler\n'), ((2221, 2256), 'sklearn.neighbors.KNeighborsClassifier', 'KNeighborsClassifier', ([], {'n_neighbors': '(7)'}), '(n_neighbors=7)\n', (2241, 2256), False, 'from sklearn.neighbors import KNeighborsClassifier\n'), ((2415, 2482), 'sklearn.model_selection.train_test_split', 'train_test_split', (['x', 'y'], {'test_size': '(0.2)', 'random_state': '(5)', 'shuffle': '(True)'}), '(x, y, test_size=0.2, random_state=5, shuffle=True)\n', (2431, 2482), False, 'from sklearn.model_selection import train_test_split\n'), ((2518, 2530), 'sklearn.naive_bayes.GaussianNB', 'GaussianNB', ([], {}), '()\n', (2528, 2530), False, 'from sklearn.naive_bayes import GaussianNB\n'), ((2338, 2376), 'sklearn.metrics.accuracy_score', 'metrics.accuracy_score', (['y_test', 'y_pred'], {}), '(y_test, y_pred)\n', (2360, 2376), False, 'from sklearn import metrics\n'), ((2608, 2646), 'sklearn.metrics.accuracy_score', 'metrics.accuracy_score', (['y_test', 'y_pred'], {}), '(y_test, y_pred)\n', (2630, 2646), False, 'from sklearn import metrics\n')]
# Generated by Django 3.2 on 2021-05-17 12:43 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('api', '0001_initial'), ] operations = [ migrations.CreateModel( name='Pavilhao', fields=[ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('numero', models.IntegerField()), ], ), migrations.AlterField( model_name='message', name='id', field=models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID'), ), migrations.CreateModel( name='Sentenciado', fields=[ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('nome', models.CharField(max_length=30)), ('matricula', models.CharField(max_length=50)), ('pavilhao', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='api.pavilhao')), ], ), ]
[ "django.db.models.ForeignKey", "django.db.models.CharField", "django.db.models.BigAutoField", "django.db.models.IntegerField" ]
[((626, 722), 'django.db.models.BigAutoField', 'models.BigAutoField', ([], {'auto_created': '(True)', 'primary_key': '(True)', 'serialize': '(False)', 'verbose_name': '"""ID"""'}), "(auto_created=True, primary_key=True, serialize=False,\n verbose_name='ID')\n", (645, 722), False, 'from django.db import migrations, models\n'), ((348, 444), 'django.db.models.BigAutoField', 'models.BigAutoField', ([], {'auto_created': '(True)', 'primary_key': '(True)', 'serialize': '(False)', 'verbose_name': '"""ID"""'}), "(auto_created=True, primary_key=True, serialize=False,\n verbose_name='ID')\n", (367, 444), False, 'from django.db import migrations, models\n'), ((470, 491), 'django.db.models.IntegerField', 'models.IntegerField', ([], {}), '()\n', (489, 491), False, 'from django.db import migrations, models\n'), ((839, 935), 'django.db.models.BigAutoField', 'models.BigAutoField', ([], {'auto_created': '(True)', 'primary_key': '(True)', 'serialize': '(False)', 'verbose_name': '"""ID"""'}), "(auto_created=True, primary_key=True, serialize=False,\n verbose_name='ID')\n", (858, 935), False, 'from django.db import migrations, models\n'), ((959, 990), 'django.db.models.CharField', 'models.CharField', ([], {'max_length': '(30)'}), '(max_length=30)\n', (975, 990), False, 'from django.db import migrations, models\n'), ((1023, 1054), 'django.db.models.CharField', 'models.CharField', ([], {'max_length': '(50)'}), '(max_length=50)\n', (1039, 1054), False, 'from django.db import migrations, models\n'), ((1086, 1172), 'django.db.models.ForeignKey', 'models.ForeignKey', ([], {'on_delete': 'django.db.models.deletion.CASCADE', 'to': '"""api.pavilhao"""'}), "(on_delete=django.db.models.deletion.CASCADE, to=\n 'api.pavilhao')\n", (1103, 1172), False, 'from django.db import migrations, models\n')]
import torch from torch import nn import torch.nn.functional as F #from helper_functions import process_image class DeepNetworkClassifier(nn.Module): def __init__(self, input_units, output_units, hidden_units,p_drop=0.2): ''' Builds a classifier for a pretrained deep neural network for the flower dataset Inputs ------ arch: string, model name from torchvision.models, determines the number of inputs in the classifier hidden_units: int, the number of hidden units in the hidden layer ''' super().__init__() # Create input layer with input units based on model architecture self.input = nn.Linear(input_units,hidden_units) # Create output layer with 102 outputs (for 102 flower classes) self.output = nn.Linear(hidden_units,output_units) # Define level of dropout self.dropout = nn.Dropout(p=p_drop) def forward(self, x): ''' Performs a forward pass through the network and returns the log probabilities x: layer in model ''' # Apply ReLU activation function and dropout to the input layer x = F.relu(self.input(x)) x = self.dropout(x) # Apply Log Softmax function to output layer x = self.output(x) x = F.log_softmax(x,dim=1) return x def train(model, trainloader, validloader, criterion, optimizer, epochs, device): ''' Train the model Inputs ------- model: torchvision model trainloader: PyTorch dataloader containing the training dataset validloader: PyTorch dataloader containing the validation dataset criterion: PyTorch criterion optimizer: PyTorch optimizer with learning rate epochs: int, number of passes of the training data through the network device: 'cuda' if GPU is specified, otherwise 'cpu' ''' # Initialize some counters steps = 0 running_loss = 0 print_every = 10 for epoch in range(epochs): for images, labels in trainloader: steps += 1 # Send the images and labels to the device images, labels = images.to(device), labels.to(device) # Zero gradients for this step optimizer.zero_grad() # Perform a forward pass on the models log_ps = model.forward(images) # Calculate loss loss = criterion(log_ps, labels) # Backpropagate error loss.backward() # Take next step optimizer.step() # Aggregate loss running_loss += loss.item() # Display results if steps % print_every == 0: # Set model to evaluate mode model.eval() # Initialize the validation loss and accuracy valid_loss = 0 valid_acc = 0 # Run validation dataset through the network with torch.no_grad(): for images, labels in validloader: # Send the images and labels to the device images_v, labels_v = images.to(device), labels.to(device) # Perform forward pass with validation images log_ps_valid = model.forward(images_v) # Calculate validation loss and aggregate loss = criterion(log_ps_valid, labels_v) valid_loss += loss # Calculate validation accuracy # Calculate the probabilities from the log_probabilities ps = torch.exp(log_ps_valid) # Determine the top probability top_p, top_class = ps.topk(1, dim=1) # Compare top_class to label valid_equality = top_class == labels_v.view(*top_class.shape) # Calculate accuracy by aggregating the equalities valid_acc += torch.mean(valid_equality.type(torch.FloatTensor)).item() # Print Results print(f"Epoch {epoch+1}/{epochs}.. " f"Training Loss: {running_loss/print_every:.3f}.. " f"Validation Loss: {valid_loss/len(validloader):.3f}.. " f"Validation Accuracy: {valid_acc/len(validloader):.3f}") # Reset counter running_loss = 0 # Return model to training mode to calculate grads model.train() def test(model, testloader, device): ''' Test the model on the test dataset Inputs ------- model: torchvision model testloader: PyTorch dataloader containing the testing dataset device: 'cuda' if GPU is specified, otherwise 'cpu' ''' # Set model to evaluate mode model.eval() # Initialize the testing accuracy test_acc = 0 # Run test dataset through the network with torch.no_grad(): for images, labels in testloader: # Send the images and labels to the device images_t, labels_t = images.to(device), labels.to(device) # Perform forward pass with validation images log_ps_test = model.forward(images_t) # Calculate test accuracy # Calculate the probabilities from the log_probabilities ps_test = torch.exp(log_ps_test) # Determine the top probability top_p, top_class = ps_test.topk(1, dim=1) # Compare top_class to label test_equality = top_class == labels_t.view(*top_class.shape) # Calculate accuracy by aggregating the equalities test_acc += torch.mean(test_equality.type(torch.FloatTensor)).item() # Print Results print("Test Accuracy: {:.3f}".format(test_acc/len(testloader))) # Return model to training mode to calculate grads model.train(); def predict(image, model, topk, device): ''' Predict the class (or classes) of an image using a trained deep learning model. Inputs ------ image: numpy array, processed for PyTorch (224x224, normalized, color dimension in 3rd channel) model: torchvision model topk: int, number of classes to output returns lists of the topk probabilities and the corresponding classes ''' # Convert image from a numpy array to a tensor image_tensor = torch.from_numpy(image) image_tensor = image_tensor.unsqueeze(0) # Run the test dataset through the model # Send the model to the device model.to(device) # Set model to evaluate mode model.to(torch.double) model.eval() # Run the image through the network with torch.no_grad(): # Send the image to the device image_tensor = image_tensor.to(device) # Perform a forward pass with the image log_ps = model.forward(image_tensor) # Calculate the probabilities from the log_probabilities ps = torch.exp(log_ps) # Determine the top k probabilities top_p, top_class = ps.topk(topk, dim=1) labels = [] for i in top_class.tolist()[0]: for cls, idx in model.class_to_idx.items(): if idx == i: labels.append(cls) # Return model to train mode model.train() return top_p.tolist()[0], labels
[ "torch.nn.Dropout", "torch.from_numpy", "torch.exp", "torch.nn.functional.log_softmax", "torch.nn.Linear", "torch.no_grad" ]
[((6466, 6489), 'torch.from_numpy', 'torch.from_numpy', (['image'], {}), '(image)\n', (6482, 6489), False, 'import torch\n'), ((674, 710), 'torch.nn.Linear', 'nn.Linear', (['input_units', 'hidden_units'], {}), '(input_units, hidden_units)\n', (683, 710), False, 'from torch import nn\n'), ((804, 841), 'torch.nn.Linear', 'nn.Linear', (['hidden_units', 'output_units'], {}), '(hidden_units, output_units)\n', (813, 841), False, 'from torch import nn\n'), ((898, 918), 'torch.nn.Dropout', 'nn.Dropout', ([], {'p': 'p_drop'}), '(p=p_drop)\n', (908, 918), False, 'from torch import nn\n'), ((1309, 1332), 'torch.nn.functional.log_softmax', 'F.log_softmax', (['x'], {'dim': '(1)'}), '(x, dim=1)\n', (1322, 1332), True, 'import torch.nn.functional as F\n'), ((5020, 5035), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (5033, 5035), False, 'import torch\n'), ((6763, 6778), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (6776, 6778), False, 'import torch\n'), ((7037, 7054), 'torch.exp', 'torch.exp', (['log_ps'], {}), '(log_ps)\n', (7046, 7054), False, 'import torch\n'), ((5441, 5463), 'torch.exp', 'torch.exp', (['log_ps_test'], {}), '(log_ps_test)\n', (5450, 5463), False, 'import torch\n'), ((2968, 2983), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (2981, 2983), False, 'import torch\n'), ((3662, 3685), 'torch.exp', 'torch.exp', (['log_ps_valid'], {}), '(log_ps_valid)\n', (3671, 3685), False, 'import torch\n')]
from flask import Blueprint, redirect, url_for, g from ..utils.utils import make_cache_key from ..internals.cache.redis import get_conn from ..internals.cache.flask_cache import cache from ..internals.database.database import get_cursor from ..lib.artist import get_artist, get_random_artist_keys from ..lib.post import get_post, get_random_posts_keys from ..lib.ab_test import get_ab_variant from ..utils.utils import get_value import random as rand random = Blueprint('random', __name__) @random.route('/posts/random') def random_post(): post = get_random_post() if post is None: return redirect('back') return redirect(url_for('post.get', service = post['service'], artist_id = post['user'], post_id = post['id'])) @random.route('/artists/random') def random_artist(): artist = get_random_artist() if artist is None: return redirect('back') return redirect(url_for('artists.get', service = artist['service'], artist_id = artist['id'])) def get_random_post(): post_keys = get_random_posts_keys(1000) if len(post_keys) == 0: return None return rand.choice(post_keys) def get_random_artist(): artists = get_random_artist_keys(1000) if len(artists) == 0: return None return rand.choice(artists)
[ "flask.redirect", "flask.Blueprint", "random.choice", "flask.url_for" ]
[((478, 507), 'flask.Blueprint', 'Blueprint', (['"""random"""', '__name__'], {}), "('random', __name__)\n", (487, 507), False, 'from flask import Blueprint, redirect, url_for, g\n'), ((1150, 1172), 'random.choice', 'rand.choice', (['post_keys'], {}), '(post_keys)\n', (1161, 1172), True, 'import random as rand\n'), ((1305, 1325), 'random.choice', 'rand.choice', (['artists'], {}), '(artists)\n', (1316, 1325), True, 'import random as rand\n'), ((630, 646), 'flask.redirect', 'redirect', (['"""back"""'], {}), "('back')\n", (638, 646), False, 'from flask import Blueprint, redirect, url_for, g\n'), ((670, 762), 'flask.url_for', 'url_for', (['"""post.get"""'], {'service': "post['service']", 'artist_id': "post['user']", 'post_id': "post['id']"}), "('post.get', service=post['service'], artist_id=post['user'],\n post_id=post['id'])\n", (677, 762), False, 'from flask import Blueprint, redirect, url_for, g\n'), ((898, 914), 'flask.redirect', 'redirect', (['"""back"""'], {}), "('back')\n", (906, 914), False, 'from flask import Blueprint, redirect, url_for, g\n'), ((938, 1011), 'flask.url_for', 'url_for', (['"""artists.get"""'], {'service': "artist['service']", 'artist_id': "artist['id']"}), "('artists.get', service=artist['service'], artist_id=artist['id'])\n", (945, 1011), False, 'from flask import Blueprint, redirect, url_for, g\n')]
# -*- coding: utf-8 -*- import scrapy class BitcointalkSpider(scrapy.Spider): name = 'bitcointalk' allowed_domains = ['bitcointalk.org'] start_urls = [ 'https://bitcointalk.org/index.php?board=1.0', ] def parse(self, response): topics = response.css('div.tborder table.bordercolor')[-1] if topics.css('table span a::attr(href)') is not None: for link in topics.css('span a::attr(href)'): url = link.extract() yield scrapy.Request(url, callback=self.parseTopic) prevnext = response.css('td#toppages span.prevnext')[-1] linkContent = prevnext.css('a::text').extract_first() link = prevnext.css('a::attr(href)') print(linkContent) if linkContent == '»': url = link.extract_first() yield scrapy.Request(url, callback=self.parse) def parseTopic(self, response): for post in response.css('form#quickModForm tr:first-of-type'): yield { 'author': post.css('td.poster_info b a::text').extract_first(), 'messageNumber': post.css('a.message_number::text').extract_first(), 'title': post.css('div.subject a::text').extract_first(), 'date': post.css('td.td_headerandpost div.smalltext::text').extract_first(), 'text': post.css('div.post::text').extract(), } prevnext = response.css('td.middletext span.prevnext') linkContent = prevnext.css('a::text').extract_first() link = prevnext.css('a::attr(href)') print(linkContent) if linkContent == '»': url = link.extract_first() yield scrapy.Request(url, callback=self.parseTopic)
[ "scrapy.Request" ]
[((844, 884), 'scrapy.Request', 'scrapy.Request', (['url'], {'callback': 'self.parse'}), '(url, callback=self.parse)\n', (858, 884), False, 'import scrapy\n'), ((1712, 1757), 'scrapy.Request', 'scrapy.Request', (['url'], {'callback': 'self.parseTopic'}), '(url, callback=self.parseTopic)\n', (1726, 1757), False, 'import scrapy\n'), ((507, 552), 'scrapy.Request', 'scrapy.Request', (['url'], {'callback': 'self.parseTopic'}), '(url, callback=self.parseTopic)\n', (521, 552), False, 'import scrapy\n')]
from typing import Any, Optional import pyarrow as pa from fugue.column.expressions import ( ColumnExpr, _FuncExpr, _to_col, function, ) from triad import Schema def coalesce(*args: Any) -> ColumnExpr: """SQL ``COALESCE`` function :param args: If a value is not :class:`~fugue.column.expressions.ColumnExpr` then it's converted to a literal column by :func:`~fugue.column.expressions.col` .. note:: this function can infer neither type nor alias .. admonition:: New Since :class: hint **0.6.0** .. admonition:: Examples .. code-block:: python import fugue.column.functions as f f.coalesce(col("a"), col("b")+col("c"), 1) """ return function("COALESCE", *[_to_col(x) for x in args]) def min(col: ColumnExpr) -> ColumnExpr: # pylint: disable=redefined-builtin """SQL ``MIN`` function (aggregation) :param col: the column to find min .. note:: * this function can infer type from ``col`` type * this function can infer alias from ``col``'s inferred alias .. admonition:: New Since :class: hint **0.6.0** .. admonition:: Examples .. code-block:: python import fugue.column.functions as f # assume col a has type double f.min(col("a")) # CAST(MIN(a) AS double) AS a f.min(-col("a")) # CAST(MIN(-a) AS double) AS a # neither type nor alias can be inferred in the following cases f.min(col("a")+1) f.min(col("a")+col("b")) # you can specify explicitly # CAST(MIN(a+b) AS int) AS x f.min(col("a")+col("b")).cast(int).alias("x") """ assert isinstance(col, ColumnExpr) return _SameTypeUnaryAggFuncExpr("MIN", col) def max(col: ColumnExpr) -> ColumnExpr: # pylint: disable=redefined-builtin """SQL ``MAX`` function (aggregation) :param col: the column to find max .. note:: * this function can infer type from ``col`` type * this function can infer alias from ``col``'s inferred alias .. admonition:: New Since :class: hint **0.6.0** .. admonition:: Examples .. code-block:: python import fugue.column.functions as f # assume col a has type double f.max(col("a")) # CAST(MAX(a) AS double) AS a f.max(-col("a")) # CAST(MAX(-a) AS double) AS a # neither type nor alias can be inferred in the following cases f.max(col("a")+1) f.max(col("a")+col("b")) # you can specify explicitly # CAST(MAX(a+b) AS int) AS x f.max(col("a")+col("b")).cast(int).alias("x") """ assert isinstance(col, ColumnExpr) return _SameTypeUnaryAggFuncExpr("MAX", col) def count(col: ColumnExpr) -> ColumnExpr: """SQL ``COUNT`` function (aggregation) :param col: the column to find count .. note:: * this function cannot infer type from ``col`` type * this function can infer alias from ``col``'s inferred alias .. admonition:: New Since :class: hint **0.6.0** .. admonition:: Examples .. code-block:: python import fugue.column.functions as f f.count(col("*")) # COUNT(*) f.count(col("a")) # COUNT(a) AS a # you can specify explicitly # CAST(COUNT(a) AS double) AS a f.count(col("a")).cast(float) """ assert isinstance(col, ColumnExpr) return _UnaryAggFuncExpr("COUNT", col) def count_distinct(col: ColumnExpr) -> ColumnExpr: """SQL ``COUNT DISTINCT`` function (aggregation) :param col: the column to find distinct element count .. note:: * this function cannot infer type from ``col`` type * this function can infer alias from ``col``'s inferred alias .. admonition:: New Since :class: hint **0.6.0** .. admonition:: Examples .. code-block:: python import fugue.column.functions as f f.count_distinct(col("*")) # COUNT(DISTINCT *) f.count_distinct(col("a")) # COUNT(DISTINCT a) AS a # you can specify explicitly # CAST(COUNT(DISTINCT a) AS double) AS a f.count_distinct(col("a")).cast(float) """ assert isinstance(col, ColumnExpr) return _UnaryAggFuncExpr("COUNT", col, arg_distinct=True) def avg(col: ColumnExpr) -> ColumnExpr: """SQL ``AVG`` function (aggregation) :param col: the column to find average .. note:: * this function cannot infer type from ``col`` type * this function can infer alias from ``col``'s inferred alias .. admonition:: New Since :class: hint **0.6.0** .. admonition:: Examples .. code-block:: python import fugue.column.functions as f f.avg(col("a")) # AVG(a) AS a # you can specify explicitly # CAST(AVG(a) AS double) AS a f.avg(col("a")).cast(float) """ assert isinstance(col, ColumnExpr) return _UnaryAggFuncExpr("AVG", col) def sum(col: ColumnExpr) -> ColumnExpr: # pylint: disable=redefined-builtin """SQL ``SUM`` function (aggregation) :param col: the column to find sum .. note:: * this function cannot infer type from ``col`` type * this function can infer alias from ``col``'s inferred alias .. admonition:: New Since :class: hint **0.6.0** .. admonition:: Examples .. code-block:: python import fugue.column.functions as f f.sum(col("a")) # SUM(a) AS a # you can specify explicitly # CAST(SUM(a) AS double) AS a f.sum(col("a")).cast(float) """ assert isinstance(col, ColumnExpr) return _UnaryAggFuncExpr("SUM", col) def first(col: ColumnExpr) -> ColumnExpr: """SQL ``FIRST`` function (aggregation) :param col: the column to find first .. note:: * this function can infer type from ``col`` type * this function can infer alias from ``col``'s inferred alias .. admonition:: New Since :class: hint **0.6.0** .. admonition:: Examples .. code-block:: python import fugue.column.functions as f # assume col a has type double f.first(col("a")) # CAST(FIRST(a) AS double) AS a f.first(-col("a")) # CAST(FIRST(-a) AS double) AS a # neither type nor alias can be inferred in the following cases f.first(col("a")+1) f.first(col("a")+col("b")) # you can specify explicitly # CAST(FIRST(a+b) AS int) AS x f.first(col("a")+col("b")).cast(int).alias("x") """ assert isinstance(col, ColumnExpr) return _SameTypeUnaryAggFuncExpr("FIRST", col) def last(col: ColumnExpr) -> ColumnExpr: """SQL ``LAST`` function (aggregation) :param col: the column to find last .. note:: * this function can infer type from ``col`` type * this function can infer alias from ``col``'s inferred alias .. admonition:: New Since :class: hint **0.6.0** .. admonition:: Examples .. code-block:: python import fugue.column.functions as f # assume col a has type double f.last(col("a")) # CAST(LAST(a) AS double) AS a f.last(-col("a")) # CAST(LAST(-a) AS double) AS a # neither type nor alias can be inferred in the following cases f.last(col("a")+1) f.last(col("a")+col("b")) # you can specify explicitly # CAST(LAST(a+b) AS int) AS x f.last(col("a")+col("b")).cast(int).alias("x") """ assert isinstance(col, ColumnExpr) return _SameTypeUnaryAggFuncExpr("LAST", col) def is_agg(column: Any) -> bool: """Check if a column contains aggregation operation :param col: the column to check :return: whether the column is :class:`~fugue.column.expressions.ColumnExpr` and contains aggregation operations .. admonition:: New Since :class: hint **0.6.0** .. admonition:: Examples .. code-block:: python import fugue.column.functions as f assert not f.is_agg(1) assert not f.is_agg(col("a")) assert not f.is_agg(col("a")+lit(1)) assert f.is_agg(f.max(col("a"))) assert f.is_agg(-f.max(col("a"))) assert f.is_agg(f.max(col("a")+1)) assert f.is_agg(f.max(col("a"))+f.min(col("a")))) """ if isinstance(column, _UnaryAggFuncExpr): return True if isinstance(column, _FuncExpr): return any(is_agg(x) for x in column.args) or any( is_agg(x) for x in column.kwargs.values() ) return False class _UnaryAggFuncExpr(_FuncExpr): def __init__(self, func: str, col: ColumnExpr, arg_distinct: bool = False): super().__init__(func, col, arg_distinct=arg_distinct) def infer_alias(self) -> ColumnExpr: return ( self if self.output_name != "" else self.alias(self.args[0].infer_alias().output_name) ) def _copy(self) -> _FuncExpr: return _UnaryAggFuncExpr(self.func, *self.args, **self.kwargs) class _SameTypeUnaryAggFuncExpr(_UnaryAggFuncExpr): def _copy(self) -> _FuncExpr: return _SameTypeUnaryAggFuncExpr(self.func, *self.args, **self.kwargs) def infer_type(self, schema: Schema) -> Optional[pa.DataType]: return self.as_type or self.args[0].infer_type(schema)
[ "fugue.column.expressions._to_col" ]
[((779, 789), 'fugue.column.expressions._to_col', '_to_col', (['x'], {}), '(x)\n', (786, 789), False, 'from fugue.column.expressions import ColumnExpr, _FuncExpr, _to_col, function\n')]
from functools import reduce from itertools import groupby from operator import add, itemgetter def merge_records_by(key, combine): return lambda first, second: { k: first[k] if k == key else combine(first[k], second[k]) for k in first } def merge_list_of_records_by(key, combine): keyprop = itemgetter(key) return lambda lst: [ reduce(merge_records_by(key, combine), records) for _, records in groupby(sorted(lst, key=keyprop), keyprop) ]
[ "operator.itemgetter" ]
[((325, 340), 'operator.itemgetter', 'itemgetter', (['key'], {}), '(key)\n', (335, 340), False, 'from operator import add, itemgetter\n')]
from selenium import webdriver from config import Config from db import cursor def get_venues(): driver = webdriver.Chrome() try: driver.get("https://tickets.edfringe.com/venues") while True: venues_container = driver.find_element_by_class_name("venues") for venue in venues_container.find_elements_by_class_name("venue-details"): name = venue.find_element_by_tag_name("h3").text lis = venue.find_elements_by_tag_name("li") address = lis[0].text number_text = lis[1].text.split()[-1] lat = lis[3].get_attribute("data-lat") long = lis[3].get_attribute("data-lng") yield (int(number_text), name, address, (float(lat), float(long))) next_links = driver.find_elements_by_link_text("Next »") if not next_links: break next_links[0].click() finally: driver.quit() venues = tuple(get_venues()) with cursor(Config.from_env()) as cur: cur.execute("SELECT edfringe_number FROM venues") existing = {row[0] for row in cur.fetchall()} for venue in sorted(venues): if venue[0] in existing: continue print( cur.mogrify( "INSERT INTO venues (edfringe_number, name, address, latlong) VALUES (%s, %s, %s, POINT%s)", venue, ).decode("utf-8"), end=";\n", )
[ "selenium.webdriver.Chrome", "config.Config.from_env" ]
[((113, 131), 'selenium.webdriver.Chrome', 'webdriver.Chrome', ([], {}), '()\n', (129, 131), False, 'from selenium import webdriver\n'), ((1030, 1047), 'config.Config.from_env', 'Config.from_env', ([], {}), '()\n', (1045, 1047), False, 'from config import Config\n')]
import unittest import logging import xml.etree.ElementTree as et import dscraper.utils as utils logger = logging.getLogger(__name__) class TestUtils(unittest.TestCase): XML_FILES = ( 'tests/resources/1.xml', ) def setUp(self): pass
[ "logging.getLogger" ]
[((108, 135), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (125, 135), False, 'import logging\n')]
import numpy as np import cv2 import glob from matplotlib import pyplot as plt class CameraCalibration(): def __init__(self): pass # =========================================================== # ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ @staticmethod def find_chess(frame_input, chess_size=(6, 6)): status = None print("chess...") # termination criteria criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 30, 0.001) # prepare object points, like (0,0,0), (1,0,0), (2,0,0) ....,(6,5,0) objp = np.zeros((chess_size[0]*chess_size[1], 3), np.float32) objp[:, :2] = np.mgrid[0:chess_size[0], 0:chess_size[1]].T.reshape(-1, 2) # Arrays to store object points and image points from all the images. objpoints = [] # 3d point in real world space imgpoints = [] # 2d points in image plane. frame_gray = cv2.cvtColor(frame_input, cv2.COLOR_BGR2GRAY) # Find the chess board corners ret, corners = cv2.findChessboardCorners(frame_gray, (chess_size[0], chess_size[1]), None) # If found, add object points, image points (after refining them) frame_output = None if ret == True: status = "checkmate!" print(status) objpoints.append(objp) corners2 = cv2.cornerSubPix(frame_gray, corners, (11, 11), (-1, -1), criteria) imgpoints.append(corners2) # Draw and display the corners frame_output = cv2.drawChessboardCorners(frame_input, (chess_size[0], chess_size[1]), corners2, ret) plt.imshow(frame_output) plt.show() if frame_output is None: frame_output = frame_input return frame_output, objpoints, imgpoints, status # =========================================================== # ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ @staticmethod def calibrateCoefficients(frame_input, objpoints, imgpoints): ret, mtx, dist, rvecs, tvecs = cv2.calibrateCamera(objpoints, imgpoints, frame_input.shape[::-1], None, None) tot_error = 0 mean_error = 0 for i in range(len(objpoints)): imgpoints2, _ = cv2.projectPoints(objpoints[i], rvecs[i], tvecs[i], mtx, dist) error = cv2.norm(imgpoints[i],imgpoints2, cv2.NORM_L2)/len(imgpoints2) tot_error += error print("total error: ", mean_error/len(objpoints)) return ret, mtx, dist, rvecs, tvecs # $$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$ # ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ @staticmethod def testbench(video_source=2): capture = cv2.VideoCapture(video_source) count_frame = 0 while 1: # ++++++++++++++++++++++++++++++++++++++++++++++++ print('calibrate state...') status = None while status is None: status = None ret, frame_input = capture.read() print(count_frame) count_frame += 1 frame_chess, objpoints, imgpoints, status = CameraCalibration.find_chess(frame_input) plt.imshow(frame_chess) plt.show() # ++++++++++++++++++++++++++++++++++++++++++++++++ frame_gray = cv2.cvtColor(frame_input, cv2.COLOR_BGR2GRAY) plt.imshow(frame_gray) plt.show() ret, mtx, dist, rvecs, tvecs = CameraCalibration.calibrateCoefficients(frame_gray, objpoints, imgpoints) h, w = frame_gray.shape[:2] newcameramtx, roi =cv2.getOptimalNewCameraMatrix(mtx, dist, (w, h), 1, (w, h)) # ++++++++++++++++++++++++++++++++++++++++++++++++ print('test state...') while 1: ret, frame_input = capture.read() frame_gray = cv2.cvtColor(frame_input,cv2.COLOR_BGR2GRAY) h, w = frame_gray.shape[:2] newcameramtx, roi =cv2.getOptimalNewCameraMatrix(mtx, dist, (w, h), 1, (w, h)) frame_undist = cv2.undistort(frame_input, mtx, dist, None, newcameramtx) x,y,w,h = roi print(x,y,w,h) # frame_undist = frame_undist[y:y+h, x:x+w] frame_concat = np.concatenate((frame_undist, frame_input), axis=1) plt.imshow(frame_concat) plt.show() # ---------------------------------------------------------- # Esc -> EXIT while # while 1: # k = cv2.waitKey(1) & 0xff # if k ==13 or k==27: # break # if k == 27: # break # ---------------------------------------------------------- capture.release() cv2.destroyAllWindows() # $$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$ # ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ @staticmethod def getPhoto(video_source=0): capture = cv2.VideoCapture(video_source) while 1: ret, frame_input = capture.read() frame_line = frame_input frame_output = cv2.line(frame_line, (0, frame_line.shape[0]//2), (frame_line.shape[1], frame_line.shape[0]//2), (255,0,0), 1) frame_output = cv2.line(frame_line, (frame_line.shape[1]//2, 0), (frame_line.shape[1]//2, frame_line.shape[0]), (255,0,0), 1) cv2.imshow("Video", frame_line) # ------------------------------------------------------------------------------------------------------------------ # Esc -> EXIT while k = cv2.waitKey(30) & 0xff if k == 27: break # ------------------------------------------------------------------------------------------------------------------ # ---------------------------------------------------------------------------------------------------------------------- ret, frame_input = capture.read() frame_input = cv2.cvtColor(frame_input, cv2.COLOR_BGR2RGB) plt.imshow(frame_input) plt.xticks([]) plt.yticks([]) plt.show() # ---------------------------------------------------------------------------------------------------------------------- capture.release() cv2.destroyAllWindows() # $$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$ # $$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$ # $$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$ # CameraCalibration.testbench(video_source=2)
[ "cv2.norm", "cv2.projectPoints", "cv2.imshow", "cv2.destroyAllWindows", "cv2.calibrateCamera", "cv2.findChessboardCorners", "cv2.cornerSubPix", "matplotlib.pyplot.imshow", "cv2.line", "cv2.undistort", "matplotlib.pyplot.yticks", "numpy.concatenate", "cv2.waitKey", "matplotlib.pyplot.xticks...
[((604, 660), 'numpy.zeros', 'np.zeros', (['(chess_size[0] * chess_size[1], 3)', 'np.float32'], {}), '((chess_size[0] * chess_size[1], 3), np.float32)\n', (612, 660), True, 'import numpy as np\n'), ((947, 992), 'cv2.cvtColor', 'cv2.cvtColor', (['frame_input', 'cv2.COLOR_BGR2GRAY'], {}), '(frame_input, cv2.COLOR_BGR2GRAY)\n', (959, 992), False, 'import cv2\n'), ((1056, 1131), 'cv2.findChessboardCorners', 'cv2.findChessboardCorners', (['frame_gray', '(chess_size[0], chess_size[1])', 'None'], {}), '(frame_gray, (chess_size[0], chess_size[1]), None)\n', (1081, 1131), False, 'import cv2\n'), ((2254, 2332), 'cv2.calibrateCamera', 'cv2.calibrateCamera', (['objpoints', 'imgpoints', 'frame_input.shape[::-1]', 'None', 'None'], {}), '(objpoints, imgpoints, frame_input.shape[::-1], None, None)\n', (2273, 2332), False, 'import cv2\n'), ((3171, 3201), 'cv2.VideoCapture', 'cv2.VideoCapture', (['video_source'], {}), '(video_source)\n', (3187, 3201), False, 'import cv2\n'), ((5364, 5387), 'cv2.destroyAllWindows', 'cv2.destroyAllWindows', ([], {}), '()\n', (5385, 5387), False, 'import cv2\n'), ((5591, 5621), 'cv2.VideoCapture', 'cv2.VideoCapture', (['video_source'], {}), '(video_source)\n', (5607, 5621), False, 'import cv2\n'), ((6905, 6949), 'cv2.cvtColor', 'cv2.cvtColor', (['frame_input', 'cv2.COLOR_BGR2RGB'], {}), '(frame_input, cv2.COLOR_BGR2RGB)\n', (6917, 6949), False, 'import cv2\n'), ((6967, 6990), 'matplotlib.pyplot.imshow', 'plt.imshow', (['frame_input'], {}), '(frame_input)\n', (6977, 6990), True, 'from matplotlib import pyplot as plt\n'), ((6999, 7013), 'matplotlib.pyplot.xticks', 'plt.xticks', (['[]'], {}), '([])\n', (7009, 7013), True, 'from matplotlib import pyplot as plt\n'), ((7022, 7036), 'matplotlib.pyplot.yticks', 'plt.yticks', (['[]'], {}), '([])\n', (7032, 7036), True, 'from matplotlib import pyplot as plt\n'), ((7045, 7055), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (7053, 7055), True, 'from matplotlib import pyplot as plt\n'), ((7220, 7243), 'cv2.destroyAllWindows', 'cv2.destroyAllWindows', ([], {}), '()\n', (7241, 7243), False, 'import cv2\n'), ((1378, 1445), 'cv2.cornerSubPix', 'cv2.cornerSubPix', (['frame_gray', 'corners', '(11, 11)', '(-1, -1)', 'criteria'], {}), '(frame_gray, corners, (11, 11), (-1, -1), criteria)\n', (1394, 1445), False, 'import cv2\n'), ((1720, 1809), 'cv2.drawChessboardCorners', 'cv2.drawChessboardCorners', (['frame_input', '(chess_size[0], chess_size[1])', 'corners2', 'ret'], {}), '(frame_input, (chess_size[0], chess_size[1]),\n corners2, ret)\n', (1745, 1809), False, 'import cv2\n'), ((1818, 1842), 'matplotlib.pyplot.imshow', 'plt.imshow', (['frame_output'], {}), '(frame_output)\n', (1828, 1842), True, 'from matplotlib import pyplot as plt\n'), ((1855, 1865), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (1863, 1865), True, 'from matplotlib import pyplot as plt\n'), ((2686, 2748), 'cv2.projectPoints', 'cv2.projectPoints', (['objpoints[i]', 'rvecs[i]', 'tvecs[i]', 'mtx', 'dist'], {}), '(objpoints[i], rvecs[i], tvecs[i], mtx, dist)\n', (2703, 2748), False, 'import cv2\n'), ((3817, 3862), 'cv2.cvtColor', 'cv2.cvtColor', (['frame_input', 'cv2.COLOR_BGR2GRAY'], {}), '(frame_input, cv2.COLOR_BGR2GRAY)\n', (3829, 3862), False, 'import cv2\n'), ((3875, 3897), 'matplotlib.pyplot.imshow', 'plt.imshow', (['frame_gray'], {}), '(frame_gray)\n', (3885, 3897), True, 'from matplotlib import pyplot as plt\n'), ((3910, 3920), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (3918, 3920), True, 'from matplotlib import pyplot as plt\n'), ((4112, 4171), 'cv2.getOptimalNewCameraMatrix', 'cv2.getOptimalNewCameraMatrix', (['mtx', 'dist', '(w, h)', '(1)', '(w, h)'], {}), '(mtx, dist, (w, h), 1, (w, h))\n', (4141, 4171), False, 'import cv2\n'), ((5752, 5873), 'cv2.line', 'cv2.line', (['frame_line', '(0, frame_line.shape[0] // 2)', '(frame_line.shape[1], frame_line.shape[0] // 2)', '(255, 0, 0)', '(1)'], {}), '(frame_line, (0, frame_line.shape[0] // 2), (frame_line.shape[1], \n frame_line.shape[0] // 2), (255, 0, 0), 1)\n', (5760, 5873), False, 'import cv2\n'), ((6035, 6155), 'cv2.line', 'cv2.line', (['frame_line', '(frame_line.shape[1] // 2, 0)', '(frame_line.shape[1] // 2, frame_line.shape[0])', '(255, 0, 0)', '(1)'], {}), '(frame_line, (frame_line.shape[1] // 2, 0), (frame_line.shape[1] //\n 2, frame_line.shape[0]), (255, 0, 0), 1)\n', (6043, 6155), False, 'import cv2\n'), ((6303, 6334), 'cv2.imshow', 'cv2.imshow', (['"""Video"""', 'frame_line'], {}), "('Video', frame_line)\n", (6313, 6334), False, 'import cv2\n'), ((2769, 2816), 'cv2.norm', 'cv2.norm', (['imgpoints[i]', 'imgpoints2', 'cv2.NORM_L2'], {}), '(imgpoints[i], imgpoints2, cv2.NORM_L2)\n', (2777, 2816), False, 'import cv2\n'), ((3676, 3699), 'matplotlib.pyplot.imshow', 'plt.imshow', (['frame_chess'], {}), '(frame_chess)\n', (3686, 3699), True, 'from matplotlib import pyplot as plt\n'), ((3716, 3726), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (3724, 3726), True, 'from matplotlib import pyplot as plt\n'), ((4373, 4418), 'cv2.cvtColor', 'cv2.cvtColor', (['frame_input', 'cv2.COLOR_BGR2GRAY'], {}), '(frame_input, cv2.COLOR_BGR2GRAY)\n', (4385, 4418), False, 'import cv2\n'), ((4498, 4557), 'cv2.getOptimalNewCameraMatrix', 'cv2.getOptimalNewCameraMatrix', (['mtx', 'dist', '(w, h)', '(1)', '(w, h)'], {}), '(mtx, dist, (w, h), 1, (w, h))\n', (4527, 4557), False, 'import cv2\n'), ((4590, 4647), 'cv2.undistort', 'cv2.undistort', (['frame_input', 'mtx', 'dist', 'None', 'newcameramtx'], {}), '(frame_input, mtx, dist, None, newcameramtx)\n', (4603, 4647), False, 'import cv2\n'), ((4801, 4852), 'numpy.concatenate', 'np.concatenate', (['(frame_undist, frame_input)'], {'axis': '(1)'}), '((frame_undist, frame_input), axis=1)\n', (4815, 4852), True, 'import numpy as np\n'), ((4870, 4894), 'matplotlib.pyplot.imshow', 'plt.imshow', (['frame_concat'], {}), '(frame_concat)\n', (4880, 4894), True, 'from matplotlib import pyplot as plt\n'), ((4911, 4921), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (4919, 4921), True, 'from matplotlib import pyplot as plt\n'), ((6513, 6528), 'cv2.waitKey', 'cv2.waitKey', (['(30)'], {}), '(30)\n', (6524, 6528), False, 'import cv2\n')]
#!/usr/bin/env python # -*- coding: utf-8 -*- # Copyright (c) 2014-2021 Megvii Inc. All rights reserved. import torch import torch.nn as nn from .sdc_darknet import SDCCSPDarknet # from .simo_darknet import SIMOCSPDarknet from .network_blocks import BaseConv, CSPLayer, DWConv from .network_blocks import get_activation class SIMOFPN(nn.Module): """ YOLOv3 model. Darknet 53 is the default backbone of this model. """ def __init__( self, depth=1.0, width=1.0, in_features=("dark5",), in_channels=[1024,], encode_channels=[256, 256, 256], out_channels=[256, 256, 256], depthwise=False, act="silu", ): super().__init__() self.backbone = SDCCSPDarknet(depth, width, depthwise=depthwise, act=act) # self.backbone = SIMOCSPDarknet(depth, width, depthwise=depthwise, act=act) self.in_features = in_features self.in_channels = in_channels self.out_channels = out_channels self.encode_channels = encode_channels Conv = DWConv if depthwise else BaseConv self.upsample = nn.Upsample(scale_factor=2, mode="nearest") self.align_layers = nn.ModuleList() for idx in range(len(self.in_channels)): self.align_layers.append( Conv(int(self.in_channels[idx] * width), int(self.encode_channels[idx] * width), 1, 1, act=act) ) # bottom-up conv self.level_conv2_layers = nn.ModuleList() for idx in range(len(self.out_channels)): self.level_conv2_layers.append( Conv(int(self.encode_channels[idx] * width), int(self.encode_channels[idx] * width), 3, 1, act=act) ) # extra layers self.extra_lvl_in_conv = ExtraConv( int(self.encode_channels[0] * width), int(self.encode_channels[0] * width), 3, 2, act=act ) self.top_down_blocks = ExtraConv( int(self.encode_channels[0] * width), int(self.encode_channels[0] * width), 3, 2, act=act ) def forward(self, input): """ Args: inputs: input images. Returns: Tuple[Tensor]: FPN feature. """ # backbone out_features = self.backbone(input) features = [align(out_features[f]) for f, align in zip(self.in_features, self.align_layers)] [C5] = features P5 = C5 P4 = self.upsample(P5) P3 = self.upsample(P4) P5 = self.level_conv2_layers[0](P5) P4 = self.level_conv2_layers[1](P4) P3 = self.level_conv2_layers[2](P3) # extra layers P6 = self.extra_lvl_in_conv(C5) + self.top_down_blocks(P5) outputs = (P3, P4, P5, P6) return outputs class ExtraConv(nn.Module): """A Conv2d -> Batchnorm -> silu/leaky relu block""" def __init__( self, in_channels, out_channels, ksize, stride, groups=1, bias=False, act="silu" ): super().__init__() pad = ksize // 2 self.conv = nn.Conv2d( in_channels, out_channels, kernel_size=ksize, stride=stride, padding=pad, groups=groups, bias=bias, ) self.bn = nn.BatchNorm2d(out_channels) self.act = get_activation(act, inplace=True) def forward(self, x): return self.act(self.bn(self.conv(x))) def fuseforward(self, x): return self.act(self.conv(x))
[ "torch.nn.ModuleList", "torch.nn.BatchNorm2d", "torch.nn.Upsample", "torch.nn.Conv2d" ]
[((1131, 1174), 'torch.nn.Upsample', 'nn.Upsample', ([], {'scale_factor': '(2)', 'mode': '"""nearest"""'}), "(scale_factor=2, mode='nearest')\n", (1142, 1174), True, 'import torch.nn as nn\n'), ((1203, 1218), 'torch.nn.ModuleList', 'nn.ModuleList', ([], {}), '()\n', (1216, 1218), True, 'import torch.nn as nn\n'), ((1492, 1507), 'torch.nn.ModuleList', 'nn.ModuleList', ([], {}), '()\n', (1505, 1507), True, 'import torch.nn as nn\n'), ((3052, 3165), 'torch.nn.Conv2d', 'nn.Conv2d', (['in_channels', 'out_channels'], {'kernel_size': 'ksize', 'stride': 'stride', 'padding': 'pad', 'groups': 'groups', 'bias': 'bias'}), '(in_channels, out_channels, kernel_size=ksize, stride=stride,\n padding=pad, groups=groups, bias=bias)\n', (3061, 3165), True, 'import torch.nn as nn\n'), ((3275, 3303), 'torch.nn.BatchNorm2d', 'nn.BatchNorm2d', (['out_channels'], {}), '(out_channels)\n', (3289, 3303), True, 'import torch.nn as nn\n')]
import unittest from minos.common import ( MinosException, ) from minos.networks import ( MinosNetworkException, ) class TestExceptions(unittest.TestCase): def test_type(self): self.assertTrue(issubclass(MinosNetworkException, MinosException)) if __name__ == "__main__": unittest.main()
[ "unittest.main" ]
[((300, 315), 'unittest.main', 'unittest.main', ([], {}), '()\n', (313, 315), False, 'import unittest\n')]
__author__ = 'Vincent' from protorpc import messages class CsvFile(messages.Message): file = messages.BytesField(1, required=True) name = messages.StringField(2, required=False)
[ "protorpc.messages.BytesField", "protorpc.messages.StringField" ]
[((99, 136), 'protorpc.messages.BytesField', 'messages.BytesField', (['(1)'], {'required': '(True)'}), '(1, required=True)\n', (118, 136), False, 'from protorpc import messages\n'), ((148, 187), 'protorpc.messages.StringField', 'messages.StringField', (['(2)'], {'required': '(False)'}), '(2, required=False)\n', (168, 187), False, 'from protorpc import messages\n')]
import os import numpy as np import tensorflow as tf from models.config import Config from models.memory_gan import MemoryGAN from models.test_generation import test_generation from models.train import train from utils import pp, visualize, to_json os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3' flags = tf.app.flags flags.DEFINE_integer("epoch", 1500, "Max epoch to train") flags.DEFINE_string("exp", 0, "Experiment number") flags.DEFINE_string("load_cp_dir", '', "cp path") flags.DEFINE_string("dataset", "fashion", "[fashion, affmnist, cifar10]") flags.DEFINE_string("loss", "jsd", "[jsd, alternative, reverse_kl, updown]") flags.DEFINE_boolean("lr_decay", False, "") flags.DEFINE_boolean("use_augmentation", False, "") flags.DEFINE_boolean("is_train", True, "True for training, False for testing [False]") flags.DEFINE_string("model", 'MemoryGAN', '') flags.DEFINE_string("generator", 'base_g', '') flags.DEFINE_string("discriminator", 'memory_d', '') FLAGS = flags.FLAGS def main(_): pp.pprint(flags.FLAGS.__flags) config = Config(FLAGS) config.print_config() config.make_dirs() config_proto = tf.ConfigProto(allow_soft_placement=FLAGS.is_train, log_device_placement=False) config_proto.gpu_options.allow_growth = True with tf.Session(config=config_proto) as sess: model = globals()[FLAGS.model](config) if not FLAGS.is_train: test_generation(model, sess) else: train(model, sess) if __name__ == '__main__': tf.app.run()
[ "models.config.Config", "tensorflow.Session", "utils.pp.pprint", "models.test_generation.test_generation", "tensorflow.ConfigProto", "models.train.train", "tensorflow.app.run" ]
[((992, 1022), 'utils.pp.pprint', 'pp.pprint', (['flags.FLAGS.__flags'], {}), '(flags.FLAGS.__flags)\n', (1001, 1022), False, 'from utils import pp, visualize, to_json\n'), ((1037, 1050), 'models.config.Config', 'Config', (['FLAGS'], {}), '(FLAGS)\n', (1043, 1050), False, 'from models.config import Config\n'), ((1120, 1199), 'tensorflow.ConfigProto', 'tf.ConfigProto', ([], {'allow_soft_placement': 'FLAGS.is_train', 'log_device_placement': '(False)'}), '(allow_soft_placement=FLAGS.is_train, log_device_placement=False)\n', (1134, 1199), True, 'import tensorflow as tf\n'), ((1497, 1509), 'tensorflow.app.run', 'tf.app.run', ([], {}), '()\n', (1507, 1509), True, 'import tensorflow as tf\n'), ((1259, 1290), 'tensorflow.Session', 'tf.Session', ([], {'config': 'config_proto'}), '(config=config_proto)\n', (1269, 1290), True, 'import tensorflow as tf\n'), ((1391, 1419), 'models.test_generation.test_generation', 'test_generation', (['model', 'sess'], {}), '(model, sess)\n', (1406, 1419), False, 'from models.test_generation import test_generation\n'), ((1446, 1464), 'models.train.train', 'train', (['model', 'sess'], {}), '(model, sess)\n', (1451, 1464), False, 'from models.train import train\n')]
from django.views import View from django.http import HttpResponseRedirect from add2cal import Add2Cal from pytz import timezone import datetime from django.http import ( JsonResponse, HttpResponse ) ADD2CAL_DATE_FORMAT = "%Y%m%dT%H%M%S" CALENDAR_CONTENT_TYPE = 'text/calendar' OUTLOOK_LINK_TYPE = 'outlook' GOOGLE_LINK_TYPE = 'google' YAHOO_LINK_TYPE = 'yahoo' ICAL_LINK_TYPE = 'ical' class CalendarReminderView(View): view_name = 'calendar_reminder_view' def get(self, request, *args, **kwargs): params = self.request.GET start = params.get('start', datetime.datetime.now().strftime( ADD2CAL_DATE_FORMAT)) end = params.get( 'end', datetime.datetime.now().strftime(ADD2CAL_DATE_FORMAT)) title = params.get('title', 'new reminder') description = params.get('description', '') location = params.get('location', 'MassChallenge') tz = params.get('timezone', timezone('UTC')) link_type = params.get('link_type', 'data') add2cal = Add2Cal( start=start, end=end, title=title, description=description, location=location, timezone=tz) calendar_data = add2cal.as_dict() if link_type == ICAL_LINK_TYPE: response = HttpResponse( calendar_data['ical_content'], content_type=CALENDAR_CONTENT_TYPE) attachment = 'attachment; filename={title}.ics'.format(title=title) response['Content-Type'] = CALENDAR_CONTENT_TYPE response['Content-Disposition'] = attachment elif link_type == OUTLOOK_LINK_TYPE: response = HttpResponseRedirect( redirect_to=calendar_data['outlook_link']) elif link_type == GOOGLE_LINK_TYPE: response = HttpResponseRedirect( redirect_to=calendar_data['gcal_link']) elif link_type == YAHOO_LINK_TYPE: response = HttpResponseRedirect( redirect_to=calendar_data['yahoo_link']) else: response = JsonResponse(add2cal.as_dict()) return response
[ "django.http.HttpResponseRedirect", "pytz.timezone", "django.http.HttpResponse", "add2cal.Add2Cal", "datetime.datetime.now" ]
[((1043, 1146), 'add2cal.Add2Cal', 'Add2Cal', ([], {'start': 'start', 'end': 'end', 'title': 'title', 'description': 'description', 'location': 'location', 'timezone': 'tz'}), '(start=start, end=end, title=title, description=description,\n location=location, timezone=tz)\n', (1050, 1146), False, 'from add2cal import Add2Cal\n'), ((956, 971), 'pytz.timezone', 'timezone', (['"""UTC"""'], {}), "('UTC')\n", (964, 971), False, 'from pytz import timezone\n'), ((1321, 1400), 'django.http.HttpResponse', 'HttpResponse', (["calendar_data['ical_content']"], {'content_type': 'CALENDAR_CONTENT_TYPE'}), "(calendar_data['ical_content'], content_type=CALENDAR_CONTENT_TYPE)\n", (1333, 1400), False, 'from django.http import JsonResponse, HttpResponse\n'), ((1700, 1763), 'django.http.HttpResponseRedirect', 'HttpResponseRedirect', ([], {'redirect_to': "calendar_data['outlook_link']"}), "(redirect_to=calendar_data['outlook_link'])\n", (1720, 1763), False, 'from django.http import HttpResponseRedirect\n'), ((589, 612), 'datetime.datetime.now', 'datetime.datetime.now', ([], {}), '()\n', (610, 612), False, 'import datetime\n'), ((702, 725), 'datetime.datetime.now', 'datetime.datetime.now', ([], {}), '()\n', (723, 725), False, 'import datetime\n'), ((1848, 1908), 'django.http.HttpResponseRedirect', 'HttpResponseRedirect', ([], {'redirect_to': "calendar_data['gcal_link']"}), "(redirect_to=calendar_data['gcal_link'])\n", (1868, 1908), False, 'from django.http import HttpResponseRedirect\n'), ((1992, 2053), 'django.http.HttpResponseRedirect', 'HttpResponseRedirect', ([], {'redirect_to': "calendar_data['yahoo_link']"}), "(redirect_to=calendar_data['yahoo_link'])\n", (2012, 2053), False, 'from django.http import HttpResponseRedirect\n')]
"""Traffic counts _jobs file.""" import pandas as pd import logging from subprocess import Popen, PIPE from trident.util import general conf = general.config fy = general.get_FY_year() def get_traffic_counts(out_fname='traffic_counts_file'): """Get traffic counts file from shared drive.""" logging.info(f'Retrieving data for FY {fy}.') command = "smbclient //ad.sannet.gov/dfs " \ + "--user={adname}%{adpass} -W ad -c " \ + "'cd \"TSW-TEO-Shared/TEO/" \ + "TEO-Transportation-Systems-and-Safety-Programs/" \ + "Traffic Data/{fy}/RECORD FINDER\";" \ + " ls; get Machine_Count_Index.xlsx {temp_dir}/{out_f}.xlsx;'" command = command.format(adname=conf['svc_acct_user'], adpass=conf['svc_acct_pass'], fy=fy, temp_dir=conf['temp_data_dir'], out_f=out_fname) p = Popen(command, shell=True, stdout=PIPE, stderr=PIPE) output, error = p.communicate() if p.returncode != 0: raise Exception(output) else: return 'Successfully retrieved {} data.'.format(fy) def clean_traffic_counts(src_fname='traffic_counts_file', out_fname='traffic_counts_raw_clean'): """Clean traffic counts data.""" xlsx_file = "{0}/{1}.xlsx"\ .format(conf['temp_data_dir'], src_fname) out_csv_file = "{0}/{1}.csv"\ .format(conf['temp_data_dir'], out_fname) names = ['street_name', 'limits', 'northbound_count', 'southbound_count', 'eastbound_count', 'westbound_count', 'total_count', 'file_no', 'date_count'] worksheet = pd.read_excel(xlsx_file, sheet_name='TRAFFIC', header=None, skiprows=[0, 1, 2, 3], usecols=[8, 9, 10, 11, 12, 13, 14, 15, 16], names=names) # Write temp csv general.pos_write_csv( worksheet, out_csv_file, date_format=conf['date_format_ymd_hms']) return "Successfully cleaned traffic counts data." def build_traffic_counts(src_fname='traffic_counts_raw_clean', out_fname='traffic_counts_datasd_v1'): """Build traffic counts production data.""" src_file = "{0}/{1}.csv"\ .format(conf['temp_data_dir'], src_fname) out_file = "{0}/{1}.csv"\ .format(conf['prod_data_dir'], out_fname) # read in csv from temp counts = pd.read_csv(src_file) # remove rows that are part of the main worksheet but empty for some reason counts = counts[counts['street_name'] != ' '] # date type counts['date_count'] = pd.to_datetime(counts['date_count'],errors='coerce') # create id field based on file id and street counts['id'] = counts.street_name.str.cat(counts.file_no, sep="")\ .str.replace(" ", "")\ .str.replace("-", "") # reorder columns cols = counts.columns.tolist() cols = cols[-1:] + cols[:-1] counts = counts[cols] # write to production file new_file_path = out_file general.pos_write_csv( counts, new_file_path, date_format=conf['date_format_ymd_hms']) return "Successfully built traffic counts production file."
[ "trident.util.general.get_FY_year", "pandas.read_csv", "subprocess.Popen", "pandas.read_excel", "trident.util.general.pos_write_csv", "logging.info", "pandas.to_datetime" ]
[((164, 185), 'trident.util.general.get_FY_year', 'general.get_FY_year', ([], {}), '()\n', (183, 185), False, 'from trident.util import general\n'), ((302, 347), 'logging.info', 'logging.info', (['f"""Retrieving data for FY {fy}."""'], {}), "(f'Retrieving data for FY {fy}.')\n", (314, 347), False, 'import logging\n'), ((940, 992), 'subprocess.Popen', 'Popen', (['command'], {'shell': '(True)', 'stdout': 'PIPE', 'stderr': 'PIPE'}), '(command, shell=True, stdout=PIPE, stderr=PIPE)\n', (945, 992), False, 'from subprocess import Popen, PIPE\n'), ((1767, 1910), 'pandas.read_excel', 'pd.read_excel', (['xlsx_file'], {'sheet_name': '"""TRAFFIC"""', 'header': 'None', 'skiprows': '[0, 1, 2, 3]', 'usecols': '[8, 9, 10, 11, 12, 13, 14, 15, 16]', 'names': 'names'}), "(xlsx_file, sheet_name='TRAFFIC', header=None, skiprows=[0, 1,\n 2, 3], usecols=[8, 9, 10, 11, 12, 13, 14, 15, 16], names=names)\n", (1780, 1910), True, 'import pandas as pd\n'), ((2083, 2175), 'trident.util.general.pos_write_csv', 'general.pos_write_csv', (['worksheet', 'out_csv_file'], {'date_format': "conf['date_format_ymd_hms']"}), "(worksheet, out_csv_file, date_format=conf[\n 'date_format_ymd_hms'])\n", (2104, 2175), False, 'from trident.util import general\n'), ((2632, 2653), 'pandas.read_csv', 'pd.read_csv', (['src_file'], {}), '(src_file)\n', (2643, 2653), True, 'import pandas as pd\n'), ((2829, 2882), 'pandas.to_datetime', 'pd.to_datetime', (["counts['date_count']"], {'errors': '"""coerce"""'}), "(counts['date_count'], errors='coerce')\n", (2843, 2882), True, 'import pandas as pd\n'), ((3282, 3372), 'trident.util.general.pos_write_csv', 'general.pos_write_csv', (['counts', 'new_file_path'], {'date_format': "conf['date_format_ymd_hms']"}), "(counts, new_file_path, date_format=conf[\n 'date_format_ymd_hms'])\n", (3303, 3372), False, 'from trident.util import general\n')]
import os import subprocess import json from metaquantome.util.utils import BASE_DIR from metaquantome.classes.SampleGroups import SampleGroups def run_viz(plottype, img, infile, strip=None, mode=None, meancol=None, nterms='5', target_rank=None, barcol=6, # barplot, stacked_bar textannot=None, fc_name=None, fc_corr_p=None, flip_fc=False, gosplit=False, # volcano sinfo=None, filter_to_sig=False, alpha='0.05', # heatmap calculate_sep=False, # pca whichway=None, name=None, id=None, target_onto=None, # ft_dist width='5', height='5', tabfile=None, feature_cluster_size=2, sample_cluster_size=2): """ Wrapper script for the command-line R visualizations The documentation for each of the arguments is in cli.py :return: None """ r_script_path = os.path.join(BASE_DIR, 'modules', 'viz.R') cmd = ['Rscript', '--vanilla', r_script_path, plottype, img, infile] if plottype == "bar": cmd += [mode, meancol, nterms, width, height, target_rank, target_onto, barcol, tabfile] elif plottype == "volcano": cmd += [str(textannot), fc_name, fc_corr_p, flip_fc, gosplit, width, height, tabfile] elif plottype == "heatmap": samp_grps = SampleGroups(sinfo) all_intcols_str = ','.join(samp_grps.all_intcols) json_dump = json.dumps(samp_grps.sample_names) cmd += [all_intcols_str, json_dump, filter_to_sig, alpha, width, height, strip, feature_cluster_size, sample_cluster_size, fc_corr_p] elif plottype == "pca": samp_grps = SampleGroups(sinfo) all_intcols_str = ','.join(samp_grps.all_intcols) json_dump = json.dumps(samp_grps.sample_names) cmd += [all_intcols_str, json_dump, calculate_sep, width, height, strip] elif plottype == "ft_dist": cmd += [whichway, name, id, meancol, nterms, width, height, target_rank, target_onto, barcol, tabfile] if plottype == "stacked_bar": samp_grps = SampleGroups(sinfo) all_intcols_str = ','.join(samp_grps.all_intcols) json_dump = json.dumps(samp_grps.sample_names) cmd += [all_intcols_str, json_dump, nterms, target_rank, width, height, tabfile] else: ValueError("Wrong plot type. Must be bar, volcano, heatmap, ft_dist, stacked_bar, or pca.") # ensure that all elements are strings (even booleans, etc) cmd_string = [str(elem) for elem in cmd] # run the visualizations, suppressing any output to stdout with open(os.devnull, 'w') as fnull: subprocess.run(cmd_string, stdout=fnull, check=True)
[ "metaquantome.classes.SampleGroups.SampleGroups", "subprocess.run", "json.dumps", "os.path.join" ]
[((849, 891), 'os.path.join', 'os.path.join', (['BASE_DIR', '"""modules"""', '"""viz.R"""'], {}), "(BASE_DIR, 'modules', 'viz.R')\n", (861, 891), False, 'import os\n'), ((2016, 2035), 'metaquantome.classes.SampleGroups.SampleGroups', 'SampleGroups', (['sinfo'], {}), '(sinfo)\n', (2028, 2035), False, 'from metaquantome.classes.SampleGroups import SampleGroups\n'), ((2114, 2148), 'json.dumps', 'json.dumps', (['samp_grps.sample_names'], {}), '(samp_grps.sample_names)\n', (2124, 2148), False, 'import json\n'), ((2570, 2622), 'subprocess.run', 'subprocess.run', (['cmd_string'], {'stdout': 'fnull', 'check': '(True)'}), '(cmd_string, stdout=fnull, check=True)\n', (2584, 2622), False, 'import subprocess\n'), ((1266, 1285), 'metaquantome.classes.SampleGroups.SampleGroups', 'SampleGroups', (['sinfo'], {}), '(sinfo)\n', (1278, 1285), False, 'from metaquantome.classes.SampleGroups import SampleGroups\n'), ((1364, 1398), 'json.dumps', 'json.dumps', (['samp_grps.sample_names'], {}), '(samp_grps.sample_names)\n', (1374, 1398), False, 'import json\n'), ((1589, 1608), 'metaquantome.classes.SampleGroups.SampleGroups', 'SampleGroups', (['sinfo'], {}), '(sinfo)\n', (1601, 1608), False, 'from metaquantome.classes.SampleGroups import SampleGroups\n'), ((1687, 1721), 'json.dumps', 'json.dumps', (['samp_grps.sample_names'], {}), '(samp_grps.sample_names)\n', (1697, 1721), False, 'import json\n')]
import json import multiprocessing import os import requests from requests_oauthlib import OAuth1 from time import sleep import tweepy def get_users_single(x,auth,output_folder): while(True): url=f"https://api.twitter.com/1.1/users/lookup.json?user_id={','.join([str(i) for i in x])}" if(type(auth)==str): headers = {"Authorization": "Bearer "+auth} r = requests.get(url = url,headers=headers) else: r = requests.get(url = url, auth=auth) if(r.status_code != 200): print("sleeping") url="https://api.twitter.com/1.1/application/rate_limit_status.json?resources=help,users,search,statuses" while(True): sleep(30) try: if(type(auth)==str): headers = {"Authorization": "Bearer "+auth} l = requests.get(url = url,headers=headers).json() else: l = requests.get(url = url, auth=auth).json() if(l["resources"]["users"]["/users/lookup"]["remaining"]!=0): break; except: pass; continue; else: l = r.json() return(l) break; def get_users_single_mp_aux(x,index,auths,output_folder): n=100 auth=auths[index] with open(f'{output_folder}/{index}.jsonl', 'w') as outfile: for i in range(0,len(x),n): json1=get_users_single(x[i:i+n],auth,output_folder) json.dump(json1, outfile) outfile.write('\n') def get_users(auths,user_ids,output_folder): if(not os.path.isdir(output_folder)): print(f"Not a directory: {output_folder}") return(None) if(len(auths)==0): return(None) if(type(auths[0])!=str): auths=[OAuth1(auths[i][0],auths[i][1],auths[i][2],auths[i][3]) for i in range(len(auths))] Process_jobs = [] k=len(auths) n=(1+len(user_ids)//k) index=0 for i in range(0,len(user_ids),n): p = multiprocessing.Process(target = get_users_single_mp_aux, args = (user_ids[i:i+n],index,auths,output_folder)) index+=1 Process_jobs.append(p) p.start() for p in Process_jobs: p.join() def get_timeline_single(auth,user_id=None,screen_name=None,count=200,trim_user=True,exclude_replies=False,include_rts=True,max_id=None): l=[1] ans=[] while(len(l)!=0): if(user_id is not None): url=f"https://api.twitter.com/1.1/statuses/user_timeline.json?user_id={user_id}&count={count}&trim_user={trim_user}&exclude_replies={exclude_replies}&include_rts={include_rts}" else: url=f"https://api.twitter.com/1.1/statuses/user_timeline.json?screen_name={screen_name}&count={count}&trim_user={trim_user}&exclude_replies={exclude_replies}&include_rts={include_rts}" url+="&tweet_mode=extended" if(max_id is not None): #print(max_id,"here") url+=f"&max_id={max_id}" #r = requests.get(url = url, auth=auth) if(type(auth)==str): headers = {"Authorization": "Bearer "+auth} r = requests.get(url = url,headers=headers) else: r = requests.get(url = url, auth=auth) #print(url) if(r.status_code == 401): break; if(r.status_code != 200): print("sleeping") url="https://api.twitter.com/1.1/application/rate_limit_status.json?resources=help,users,search,statuses" while(True): sleep(30) try: if(type(auth)==str): l=requests.get(url = url,headers=headers).json() else: l=requests.get(url = url, auth=auth).json() if(l["resources"]["statuses"]["/statuses/user_timeline"]["remaining"]!=0): break; except Exception as e: print(e) pass; continue; else: l = r.json() ans.extend(l) if(len(l)==0 or max_id==l[-1]["id_str"]): break; else: max_id=l[-1]["id_str"] return(ans) def get_timeline_single_mp_aux(index,auths,users,output_folder): auth=auths[index] with open(f'{output_folder}/{index}.jsonl', 'w') as outfile: for user_id in users: try: json1=get_timeline_single(auth=auth,user_id=user_id) except: sleep(30) continue; json.dump(json1, outfile) outfile.write('\n') def get_timelines(auths,users,output_folder): if(not os.path.isdir(output_folder)): print(f"Not a directory: {output_folder}") return(None) if(len(auths)==0): return(None) if(type(auths[0])!=str): auths=[OAuth1(auths[i][0],auths[i][1],auths[i][2],auths[i][3]) for i in range(len(auths))] Process_jobs = [] k=len(auths) n=(1+len(users)//k) index=-1 for i in range(0,len(users),n): p = multiprocessing.Process(target = get_timeline_single_mp_aux, args = (index,auths,users[i:i+n],output_folder)) index+=1 Process_jobs.append(p) p.start() for p in Process_jobs: p.join() def get_followers_aux(auth,screen_name_or_userid,cursor=-1,use_userid=False): url="https://api.twitter.com/1.1/followers/ids.json" params={"screen_name":screen_name_or_userid,"count":"5000","cursor":cursor} if(use_userid): params={"user_id":screen_name_or_userid,"count":"5000","cursor":cursor} if(type(auth)==str): headers = {"Authorization": "Bearer "+auth} temp=requests.get(url=url,headers=headers,params=params).json() else: temp=requests.get(url=url,auth=auth,params=params).json() if(len(temp["ids"])==0): return(temp["ids"],None) else: return(temp["ids"],temp["next_cursor"]) def get_followers(auths,screen_name_or_userid,max_num=-1,use_userid=False): cursor=-1 if(len(auths)==0): return(None) if(type(auths[0])!=str): auths=[OAuth1(auths[i][0],auths[i][1],auths[i][2],auths[i][3]) for i in range(len(auths))] res=[] index=0 auth=auths[index] flag=False while(cursor is not None and (max_num==-1 or max_num>len(res))): try: a,cursor=get_followers_aux(auth,screen_name_or_userid,cursor,use_userid) flag=False res.extend(a) print(len(res)) except Exception as e: print(e) print("done",len(res)) if(flag): sleep(30) else: flag=True index+=1 index%=len(auths) auth=auths[index] pass; return(res)
[ "multiprocessing.Process", "requests.get", "time.sleep", "os.path.isdir", "requests_oauthlib.OAuth1", "json.dump" ]
[((1714, 1742), 'os.path.isdir', 'os.path.isdir', (['output_folder'], {}), '(output_folder)\n', (1727, 1742), False, 'import os\n'), ((2118, 2232), 'multiprocessing.Process', 'multiprocessing.Process', ([], {'target': 'get_users_single_mp_aux', 'args': '(user_ids[i:i + n], index, auths, output_folder)'}), '(target=get_users_single_mp_aux, args=(user_ids[i:i +\n n], index, auths, output_folder))\n', (2141, 2232), False, 'import multiprocessing\n'), ((4907, 4935), 'os.path.isdir', 'os.path.isdir', (['output_folder'], {}), '(output_folder)\n', (4920, 4935), False, 'import os\n'), ((5315, 5429), 'multiprocessing.Process', 'multiprocessing.Process', ([], {'target': 'get_timeline_single_mp_aux', 'args': '(index, auths, users[i:i + n], output_folder)'}), '(target=get_timeline_single_mp_aux, args=(index,\n auths, users[i:i + n], output_folder))\n', (5338, 5429), False, 'import multiprocessing\n'), ((406, 444), 'requests.get', 'requests.get', ([], {'url': 'url', 'headers': 'headers'}), '(url=url, headers=headers)\n', (418, 444), False, 'import requests\n'), ((476, 508), 'requests.get', 'requests.get', ([], {'url': 'url', 'auth': 'auth'}), '(url=url, auth=auth)\n', (488, 508), False, 'import requests\n'), ((1577, 1602), 'json.dump', 'json.dump', (['json1', 'outfile'], {}), '(json1, outfile)\n', (1586, 1602), False, 'import json\n'), ((1905, 1963), 'requests_oauthlib.OAuth1', 'OAuth1', (['auths[i][0]', 'auths[i][1]', 'auths[i][2]', 'auths[i][3]'], {}), '(auths[i][0], auths[i][1], auths[i][2], auths[i][3])\n', (1911, 1963), False, 'from requests_oauthlib import OAuth1\n'), ((3258, 3296), 'requests.get', 'requests.get', ([], {'url': 'url', 'headers': 'headers'}), '(url=url, headers=headers)\n', (3270, 3296), False, 'import requests\n'), ((3328, 3360), 'requests.get', 'requests.get', ([], {'url': 'url', 'auth': 'auth'}), '(url=url, auth=auth)\n', (3340, 3360), False, 'import requests\n'), ((4774, 4799), 'json.dump', 'json.dump', (['json1', 'outfile'], {}), '(json1, outfile)\n', (4783, 4799), False, 'import json\n'), ((5098, 5156), 'requests_oauthlib.OAuth1', 'OAuth1', (['auths[i][0]', 'auths[i][1]', 'auths[i][2]', 'auths[i][3]'], {}), '(auths[i][0], auths[i][1], auths[i][2], auths[i][3])\n', (5104, 5156), False, 'from requests_oauthlib import OAuth1\n'), ((6400, 6458), 'requests_oauthlib.OAuth1', 'OAuth1', (['auths[i][0]', 'auths[i][1]', 'auths[i][2]', 'auths[i][3]'], {}), '(auths[i][0], auths[i][1], auths[i][2], auths[i][3])\n', (6406, 6458), False, 'from requests_oauthlib import OAuth1\n'), ((734, 743), 'time.sleep', 'sleep', (['(30)'], {}), '(30)\n', (739, 743), False, 'from time import sleep\n'), ((3659, 3668), 'time.sleep', 'sleep', (['(30)'], {}), '(30)\n', (3664, 3668), False, 'from time import sleep\n'), ((5952, 6005), 'requests.get', 'requests.get', ([], {'url': 'url', 'headers': 'headers', 'params': 'params'}), '(url=url, headers=headers, params=params)\n', (5964, 6005), False, 'import requests\n'), ((6034, 6081), 'requests.get', 'requests.get', ([], {'url': 'url', 'auth': 'auth', 'params': 'params'}), '(url=url, auth=auth, params=params)\n', (6046, 6081), False, 'import requests\n'), ((4726, 4735), 'time.sleep', 'sleep', (['(30)'], {}), '(30)\n', (4731, 4735), False, 'from time import sleep\n'), ((6953, 6962), 'time.sleep', 'sleep', (['(30)'], {}), '(30)\n', (6958, 6962), False, 'from time import sleep\n'), ((902, 940), 'requests.get', 'requests.get', ([], {'url': 'url', 'headers': 'headers'}), '(url=url, headers=headers)\n', (914, 940), False, 'import requests\n'), ((1003, 1035), 'requests.get', 'requests.get', ([], {'url': 'url', 'auth': 'auth'}), '(url=url, auth=auth)\n', (1015, 1035), False, 'import requests\n'), ((3774, 3812), 'requests.get', 'requests.get', ([], {'url': 'url', 'headers': 'headers'}), '(url=url, headers=headers)\n', (3786, 3812), False, 'import requests\n'), ((3873, 3905), 'requests.get', 'requests.get', ([], {'url': 'url', 'auth': 'auth'}), '(url=url, auth=auth)\n', (3885, 3905), False, 'import requests\n')]
# -*- coding: utf-8 -*- """ Utilities for reading and writing USID datasets that are highly model-dependent (with or without N-dimensional form) Created on Tue Nov 3 21:14:25 2015 @author: <NAME>, <NAME> """ from __future__ import division, print_function, absolute_import, unicode_literals from warnings import warn import sys import h5py import numpy as np from dask import array as da from sidpy.hdf.hdf_utils import get_attr, write_simple_attrs, is_editable_h5, \ copy_dataset, lazy_load_array from sidpy.base.num_utils import contains_integers from sidpy.base.dict_utils import flatten_dict from sidpy.base.string_utils import validate_single_string_arg, \ validate_list_of_strings, validate_string_args from sidpy.hdf.dtype_utils import validate_dtype from sidpy import sid from .base import write_book_keeping_attrs from .simple import link_as_main, check_if_main, write_ind_val_dsets, validate_dims_against_main, validate_anc_h5_dsets from ..dimension import Dimension, validate_dimensions from ..anc_build_utils import INDICES_DTYPE, make_indices_matrix if sys.version_info.major == 3: unicode = str def reshape_to_n_dims(h5_main, h5_pos=None, h5_spec=None, get_labels=False, verbose=False, sort_dims=False, lazy=False): """ Reshape the input 2D matrix to be N-dimensions based on the position and spectroscopic datasets. Parameters ---------- h5_main : HDF5 Dataset 2D data to be reshaped h5_pos : HDF5 Dataset, optional Position indices corresponding to rows in `h5_main` h5_spec : HDF5 Dataset, optional Spectroscopic indices corresponding to columns in `h5_main` get_labels : bool, optional Whether or not to return the dimension labels. Default False verbose : bool, optional Whether or not to print debugging statements sort_dims : bool If True, the data is sorted so that the dimensions are in order from slowest to fastest If False, the data is kept in the original order If `get_labels` is also True, the labels are sorted as well. lazy : bool, optional. Default = False If False, ds_Nd will be a numpy.ndarray object - this is suitable if the HDF5 dataset fits into memory If True, ds_Nd will be a dask.array object - This is suitable if the HDF5 dataset is too large to fit into memory. Note that this will bea lazy computation meaning that the returned object just contains the instructions . In order to get the actual value or content in numpy arrays, call ds_Nd.compute() Returns ------- ds_Nd : N-D numpy array or dask.array object N dimensional array arranged as [positions slowest to fastest, spectroscopic slowest to fastest] success : boolean or string True if full reshape was successful "Positions" if it was only possible to reshape by the position dimensions False if no reshape was possible ds_labels : list of str List of the labels of each dimension of `ds_Nd` Notes ----- If either `h5_pos` or `h5_spec` are not provided, the function will first attempt to find them as attributes of `h5_main`. If that fails, it will generate dummy values for them. """ # TODO: automatically switch on lazy if the data is larger than memory # TODO: sort_dims does not appear to do much. Functions as though it was always True if h5_pos is None and h5_spec is None: if not check_if_main(h5_main): raise ValueError('if h5_main is a h5py.Dataset it should be a Main dataset') else: if not isinstance(h5_main, (h5py.Dataset, np.ndarray, da.core.Array)): raise TypeError('h5_main should either be a h5py.Dataset or numpy array') if h5_pos is not None: if not isinstance(h5_pos, (h5py.Dataset, np.ndarray, da.core.Array)): raise TypeError('h5_pos should either be a h5py.Dataset or numpy array') if h5_pos.shape[0] != h5_main.shape[0]: raise ValueError('The size of h5_pos: {} does not match with h5_main: {}'.format(h5_pos.shape, h5_main.shape)) if h5_spec is not None: if not isinstance(h5_spec, (h5py.Dataset, np.ndarray, da.core.Array)): raise TypeError('h5_spec should either be a h5py.Dataset or numpy array') if h5_spec.shape[1] != h5_main.shape[1]: raise ValueError('The size of h5_spec: {} does not match with h5_main: {}'.format(h5_spec.shape, h5_main.shape)) pos_labs = np.array(['Positions']) spec_labs = np.array(['Spectral_Step']) if h5_pos is None: """ Get the Position datasets from the references if possible """ if isinstance(h5_main, h5py.Dataset): try: h5_pos = h5_main.file[h5_main.attrs['Position_Indices']] ds_pos = h5_pos[()] pos_labs = get_attr(h5_pos, 'labels') except KeyError: print('No position datasets found as attributes of {}'.format(h5_main.name)) if len(h5_main.shape) > 1: ds_pos = np.arange(h5_main.shape[0], dtype=INDICES_DTYPE).reshape(-1, 1) pos_labs = np.array(['Position Dimension {}'.format(ipos) for ipos in range(ds_pos.shape[1])]) else: ds_pos = np.array(0, dtype=INDICES_DTYPE).reshape(-1, 1) else: ds_pos = np.arange(h5_main.shape[0], dtype=INDICES_DTYPE).reshape(-1, 1) pos_labs = np.array(['Position Dimension {}'.format(ipos) for ipos in range(ds_pos.shape[1])]) elif isinstance(h5_pos, h5py.Dataset): """ Position Indices dataset was provided """ ds_pos = h5_pos[()] pos_labs = get_attr(h5_pos, 'labels') elif isinstance(h5_pos, (np.ndarray, da.core.Array)): ds_pos = np.atleast_2d(h5_pos) pos_labs = np.array(['Position Dimension {}'.format(ipos) for ipos in range(ds_pos.shape[1])]) else: raise TypeError('Position Indices must be either h5py.Dataset or None') if h5_spec is None: """ Get the Spectroscopic datasets from the references if possible """ if isinstance(h5_main, h5py.Dataset): try: h5_spec = h5_main.file[h5_main.attrs['Spectroscopic_Indices']] ds_spec = h5_spec[()] spec_labs = get_attr(h5_spec, 'labels') except KeyError: print('No spectroscopic datasets found as attributes of {}'.format(h5_main.name)) if len(h5_main.shape) > 1: ds_spec = np.arange(h5_main.shape[1], dtype=INDICES_DTYPE).reshape([1, -1]) spec_labs = np.array(['Spectral Dimension {}'.format(ispec) for ispec in range(ds_spec.shape[0])]) else: ds_spec = np.array(0, dtype=INDICES_DTYPE).reshape([1, 1]) else: ds_spec = np.arange(h5_main.shape[1], dtype=INDICES_DTYPE).reshape([1, -1]) spec_labs = np.array(['Spectral Dimension {}'.format(ispec) for ispec in range(ds_spec.shape[0])]) elif isinstance(h5_spec, h5py.Dataset): """ Spectroscopic Indices dataset was provided """ ds_spec = h5_spec[()] spec_labs = get_attr(h5_spec, 'labels') elif isinstance(h5_spec, (np.ndarray, da.core.Array)): ds_spec = h5_spec spec_labs = np.array(['Spectral Dimension {}'.format(ispec) for ispec in range(ds_spec.shape[0])]) else: raise TypeError('Spectroscopic Indices must be either h5py.Dataset or None') ''' Sort the indices from fastest to slowest ''' pos_sort = get_sort_order(np.transpose(ds_pos)) spec_sort = get_sort_order(ds_spec) if verbose: print('Position dimensions:', pos_labs) print('Position sort order:', pos_sort) print('Spectroscopic Dimensions:', spec_labs) print('Spectroscopic sort order:', spec_sort) ''' Get the size of each dimension in the sorted order ''' pos_dims = get_dimensionality(np.transpose(ds_pos), pos_sort) spec_dims = get_dimensionality(ds_spec, spec_sort) if np.prod(pos_dims) != h5_main.shape[0]: mesg = 'Product of position dimension sizes: {} = {} not matching ' \ 'with size of first axis of main dataset: {}. One or more ' \ 'dimensions are dependent dimensions and not marked as such' \ '.'.format(pos_dims, np.prod(pos_dims), h5_main.shape[0]) raise ValueError(mesg) if np.prod(spec_dims) != h5_main.shape[1]: mesg = 'Product of spectroscopic dimension sizes: {} = {} not matching ' \ 'with size of second axis of main dataset: {}. One or more ' \ 'dimensions are dependent dimensions and not marked as such' \ '.'.format(spec_dims, np.prod(spec_dims), h5_main.shape[1]) raise ValueError(mesg) if verbose: print('\nPosition dimensions (sort applied):', pos_labs[pos_sort]) print('Position dimensionality (sort applied):', pos_dims) print('Spectroscopic dimensions (sort applied):', spec_labs[spec_sort]) print('Spectroscopic dimensionality (sort applied):', spec_dims) if lazy: ds_main = lazy_load_array(h5_main) else: ds_main = h5_main[()] """ Now we reshape the dataset based on those dimensions numpy reshapes correctly when the dimensions are arranged from slowest to fastest. Since the sort orders we have are from fastest to slowest, we need to reverse the orders for both the position and spectroscopic dimensions """ if verbose: print('Will attempt to reshape main dataset from:\n{} to {}'.format(ds_main.shape, pos_dims[::-1] + spec_dims[::-1])) try: ds_Nd = ds_main.reshape(pos_dims[::-1] + spec_dims[::-1]) except ValueError: warn('Could not reshape dataset to full N-dimensional form. Attempting reshape based on position only.') try: ds_Nd = ds_main.reshape(pos_dims[::-1] + [-1]) except ValueError: warn('Reshape by position only also failed. Will keep dataset in 2d form.') if get_labels: return ds_main, False, ['Position', 'Spectral Step'] else: return ds_main, False # No exception else: if get_labels: return ds_Nd, 'Positions', ['Position'] + spec_labs else: return ds_Nd, 'Positions' all_labels = np.hstack((pos_labs[pos_sort][::-1], spec_labs[spec_sort][::-1])) if verbose: print('\nAfter reshaping, labels are', all_labels) print('Data shape is', ds_Nd.shape) """ At this point, the data is arranged from slowest to fastest dimension in both pos and spec """ if sort_dims: results = [ds_Nd, True] if get_labels: results.append(all_labels) return results if verbose: print('\nGoing to put dimensions back in the same order as in the file:') swap_axes = list() # Compare the original order of the pos / spec labels with where these dimensions occur in the sorted labels for lab in pos_labs: swap_axes.append(np.argwhere(all_labels == lab).squeeze()) for lab in spec_labs: swap_axes.append(np.argwhere(all_labels == lab).squeeze()) swap_axes = np.array(swap_axes) if verbose: print('Axes will permuted in this order:', swap_axes) print('New labels ordering:', all_labels[swap_axes]) ds_Nd = ds_Nd.transpose(tuple(swap_axes)) results = [ds_Nd, True] if verbose: print('Dataset now of shape:', ds_Nd.shape) if get_labels: ''' Get the labels in the proper order ''' results.append(all_labels[swap_axes]) return results def reshape_from_n_dims(data_n_dim, h5_pos=None, h5_spec=None, verbose=False): """ Reshape the input 2D matrix to be N-dimensions based on the position and spectroscopic datasets. Parameters ---------- data_n_dim : numpy.array or dask.array.core.Array N dimensional array arranged as [positions dimensions..., spectroscopic dimensions] If h5_pos and h5_spec are not provided, this function will have to assume that the dimensions are arranged as [positions slowest to fastest, spectroscopic slowest to fastest]. This restriction is removed if h5_pos and h5_spec are provided h5_pos : HDF5 Dataset, numpy.array or dask.array.core.Array Position indices corresponding to rows in the final 2d array The dimensions should be arranged in terms of rate of change corresponding to data_n_dim. In other words if data_n_dim had two position dimensions arranged as [pos_fast, pos_slow, spec_dim_1....], h5_pos should be arranged as [pos_fast, pos_slow] h5_spec : HDF5 Dataset, numpy. array or dask.array.core.Array Spectroscopic indices corresponding to columns in the final 2d array The dimensions should be arranged in terms of rate of change corresponding to data_n_dim. In other words if data_n_dim had two spectral dimensions arranged as [pos_dim_1,..., spec_fast, spec_slow], h5_spec should be arranged as [pos_slow, pos_fast] verbose : bool, optional. Default = False Whether or not to print log statements Returns ------- ds_2d : numpy.array 2 dimensional numpy array arranged as [positions, spectroscopic] success : boolean or string True if full reshape was successful "Positions" if it was only possible to reshape by the position dimensions False if no reshape was possible Notes ----- If either `h5_pos` or `h5_spec` are not provided, the function will assume the first dimension is position and the remaining are spectroscopic already in order from fastest to slowest. """ if not isinstance(data_n_dim, (np.ndarray, da.core.Array)): raise TypeError('data_n_dim is not a numpy or dask array') if h5_spec is None and h5_pos is None: raise ValueError('at least one of h5_pos or h5_spec must be specified for an attempt to reshape to 2D') if data_n_dim.ndim < 2: return data_n_dim, True if h5_pos is None: pass elif isinstance(h5_pos, h5py.Dataset): ''' Position Indices dataset was provided ''' ds_pos = h5_pos[()] elif isinstance(h5_pos, da.core.Array): ds_pos = h5_pos.compute() elif isinstance(h5_pos, np.ndarray): ds_pos = h5_pos else: raise TypeError('Position Indices must be either h5py.Dataset or None') if h5_spec is None: pass elif isinstance(h5_spec, h5py.Dataset): ''' Spectroscopic Indices dataset was provided ''' ds_spec = h5_spec[()] elif isinstance(h5_spec, da.core.Array): ds_spec = h5_spec.compute() elif isinstance(h5_spec, np.ndarray): ds_spec = h5_spec else: raise TypeError('Spectroscopic Indices must be either h5py.Dataset or None') if h5_spec is None and h5_pos is not None: if verbose: print('Spectral indices not provided but position indices provided.\n' 'Building spectral indices assuming that dimensions are arranged as slow -> fast') pos_dims = get_dimensionality(ds_pos, index_sort=get_sort_order(ds_pos)) if not np.all([x in data_n_dim.shape for x in pos_dims]): raise ValueError('Dimension sizes in pos_dims: {} do not exist in data_n_dim shape: ' '{}'.format(pos_dims, data_n_dim.shape)) spec_dims = [col for col in list(data_n_dim.shape[len(pos_dims):])] if verbose: print('data has dimensions: {}. Provided position indices had dimensions of size: {}. Spectral dimensions ' 'will built with dimensions: {}'.format(data_n_dim.shape, pos_dims, spec_dims)) ds_spec = make_indices_matrix(spec_dims, is_position=False) elif h5_pos is None and h5_spec is not None: if verbose: print('Position indices not provided but spectral indices provided.\n' 'Building position indices assuming that dimensions are arranged as slow -> fast') spec_dims = get_dimensionality(ds_spec, index_sort=get_sort_order(ds_spec)) if not np.all([x in data_n_dim.shape for x in spec_dims]): raise ValueError('Dimension sizes in spec_dims: {} do not exist in data_n_dim shape: ' '{}'.format(spec_dims, data_n_dim.shape)) pos_dims = [col for col in list(data_n_dim.shape[:data_n_dim.ndim-len(spec_dims)])] if verbose: print('data has dimensions: {}. Spectroscopic position indices had dimensions of size: {}. Position ' 'dimensions will built with dimensions: {}'.format(data_n_dim.shape, spec_dims, pos_dims)) ds_pos = make_indices_matrix(pos_dims, is_position=True) elif h5_spec is not None and h5_pos is not None: if ds_pos.shape[0] * ds_spec.shape[1] != np.product(data_n_dim.shape): raise ValueError('The product ({}) of the number of positions ({}) and spectroscopic ({}) observations is ' 'not equal to the product ({}) of the data shape ({})' '.'.format(ds_pos.shape[0] * ds_spec.shape[1], ds_pos.shape[0], ds_spec.shape[1], np.product(data_n_dim.shape), data_n_dim.shape)) if ds_pos.shape[1] + ds_spec.shape[0] != data_n_dim.ndim: # This may mean that the dummy position or spectroscopic axes has been squeezed out! # Dask does NOT allow singular dimensions apparently. So cannot do expand_dims. Handle later if ds_pos.size == 1 or ds_spec.size == 1: if verbose: print('ALL Position dimensions squeezed: {}. ALL Spectroscopic dimensions squeezed: {}' '.'.format(ds_pos.size == 1, ds_spec.size == 1)) else: raise ValueError('The number of position ({}) and spectroscopic ({}) dimensions do not match with the ' 'dimensionality of the N-dimensional dataset: {}' '.'.format(ds_pos.shape[1], ds_spec.shape[0], data_n_dim.ndim)) ''' Sort the indices from fastest to slowest ''' if ds_pos.size == 1: # Position dimension squeezed out: pos_sort = [] else: pos_sort = get_sort_order(np.transpose(ds_pos)) if ds_spec.size == 1: # Spectroscopic axis squeezed out: spec_sort = [] else: spec_sort = get_sort_order(ds_spec) if h5_spec is None: spec_sort = spec_sort[::-1] if h5_pos is None: pos_sort = pos_sort[::-1] if verbose: print('Position sort order: {}'.format(pos_sort)) print('Spectroscopic sort order: {}'.format(spec_sort)) ''' Now we transpose the axes associated with the spectroscopic dimensions so that they are in the same order as in the index array ''' swap_axes = np.uint16(np.append(pos_sort[::-1], spec_sort[::-1] + len(pos_sort))) if verbose: print('swap axes: {} to be applied to N dimensional data of shape {}'.format(swap_axes, data_n_dim.shape)) data_n_dim_2 = data_n_dim.transpose(tuple(swap_axes)) if verbose: print('N dimensional data shape after axes swap: {}'.format(data_n_dim_2.shape)) ''' Now we reshape the dataset based on those dimensions We must use the spectroscopic dimensions in reverse order ''' try: ds_2d = data_n_dim_2.reshape([ds_pos.shape[0], ds_spec.shape[1]]) except ValueError: raise ValueError('Could not reshape dataset to full N-dimensional form') return ds_2d, True def get_dimensionality(ds_index, index_sort=None): """ Get the size of each index dimension in a specified sort order Parameters ---------- ds_index : 2D HDF5 Dataset or numpy array Row matrix of indices index_sort : Iterable of unsigned integers (Optional) Sort that can be applied to dimensionality. For example - Order of rows sorted from fastest to slowest Returns ------- sorted_dims : list of unsigned integers Dimensionality of each row in ds_index. If index_sort is supplied, it will be in the sorted order """ if isinstance(ds_index, da.core.Array): ds_index = ds_index.compute() if not isinstance(ds_index, (np.ndarray, h5py.Dataset)): raise TypeError('ds_index should either be a numpy array or h5py.Dataset') if ds_index.shape[0] > ds_index.shape[1]: # must be spectroscopic like in shape (few rows, more cols) ds_index = np.transpose(ds_index) if index_sort is None: index_sort = np.arange(ds_index.shape[0]) else: if not contains_integers(index_sort, min_val=0): raise ValueError('index_sort should contain integers > 0') index_sort = np.array(index_sort) if index_sort.ndim != 1: raise ValueError('index_sort should be a 1D array') if len(np.unique(index_sort)) > ds_index.shape[0]: raise ValueError('length of index_sort ({}) should be smaller than number of dimensions in provided dataset' ' ({}'.format(len(np.unique(index_sort)), ds_index.shape[0])) if set(np.arange(ds_index.shape[0])) != set(index_sort): raise ValueError('Sort order of dimensions ({}) not matching with number of dimensions ({})' ''.format(index_sort, ds_index.shape[0])) sorted_dims = [len(np.unique(row)) for row in np.array(ds_index, ndmin=2)[index_sort]] return sorted_dims def get_sort_order(ds_spec): """ Find how quickly the spectroscopic values are changing in each row and the order of rows from fastest changing to slowest. Parameters ---------- ds_spec : 2D HDF5 dataset or numpy array Rows of indices to be sorted from fastest changing to slowest Returns ------- change_sort : List of unsigned integers Order of rows sorted from fastest changing to slowest """ if isinstance(ds_spec, da.core.Array): ds_spec = ds_spec.compute() if not isinstance(ds_spec, (np.ndarray, h5py.Dataset)): raise TypeError('ds_spec should either be a numpy array or h5py.Dataset') if ds_spec.shape[0] > ds_spec.shape[1]: # must be spectroscopic like in shape (few rows, more cols) ds_spec = np.transpose(ds_spec) change_count = [len(np.where([row[i] != row[i - 1] for i in range(len(row))])[0]) for row in ds_spec] change_sort = np.argsort(change_count)[::-1] return change_sort def get_unit_values(ds_inds, ds_vals, dim_names=None, all_dim_names=None, is_spec=None, verbose=False): """ Gets the unit arrays of values that describe the spectroscopic dimensions Parameters ---------- ds_inds : h5py.Dataset or numpy.ndarray Spectroscopic or Position Indices dataset ds_vals : h5py.Dataset or numpy.ndarray Spectroscopic or Position Values dataset dim_names : str, or list of str, Optional Names of the dimensions of interest. Default = all all_dim_names : list of str, Optional Names of all the dimensions in these datasets. Use this if supplying numpy arrays instead of h5py.Dataset objects for h5_inds, h5_vals since there is no other way of getting the dimension names. is_spec : bool, optional Whether or not the provided ancillary datasets are position or spectroscopic The user is recommended to supply this parameter whenever it is known By default, this function will attempt to recognize the answer based on the shape of the datasets. verbose : bool, optional Whether or not to print debugging statements. Default - off Note - this function can be extended / modified for ancillary position dimensions as well Returns ------- unit_values : dict Dictionary containing the unit array for each dimension. The name of the dimensions are the keys. """ if all_dim_names is None: allowed_types = h5py.Dataset else: all_dim_names = validate_list_of_strings(all_dim_names, 'all_dim_names') all_dim_names = np.array(all_dim_names) allowed_types = (h5py.Dataset, np.ndarray) for dset, dset_name in zip([ds_inds, ds_vals], ['ds_inds', 'ds_vals']): if not isinstance(dset, allowed_types): raise TypeError(dset_name + ' should be of type: {}'.format(allowed_types)) # For now, we will throw an error if even a single dimension is listed as an incomplete dimension: if isinstance(ds_inds, h5py.Dataset): if np.any(['incomplete_dimensions' in dset.attrs.keys() for dset in [ds_inds, ds_vals]]): try: incomp_dims_inds = get_attr(ds_inds, 'incomplete_dimensions') except KeyError: incomp_dims_inds = None try: incomp_dims_vals = get_attr(ds_vals, 'incomplete_dimensions') except KeyError: incomp_dims_vals = None if incomp_dims_inds is None and incomp_dims_vals is not None: incomp_dims = incomp_dims_vals elif incomp_dims_inds is not None and incomp_dims_vals is None: incomp_dims = incomp_dims_inds else: # ensure that both attributes are the same if incomp_dims_vals != incomp_dims_inds: raise ValueError('Provided indices ({}) and values ({}) datasets were marked with different values ' 'for incomplete_datasets.'.format(incomp_dims_inds, incomp_dims_vals)) incomp_dims = incomp_dims_vals all_dim_names = get_attr(ds_inds, 'labels') raise ValueError('Among all dimensions: {}, These dimensions were marked as incomplete dimensions: {}' '. You are recommended to find unit values manually'.format(all_dim_names, incomp_dims)) # Do we need to check that the provided inds and vals correspond to the same main dataset? if ds_inds.shape != ds_vals.shape: raise ValueError('h5_inds: {} and h5_vals: {} should have the same shapes'.format(ds_inds.shape, ds_vals.shape)) if all_dim_names is None: all_dim_names = get_attr(ds_inds, 'labels') if verbose: print('All dimensions: {}'.format(all_dim_names)) # First load to memory inds_mat = ds_inds[()] vals_mat = ds_vals[()] if is_spec is None: # Attempt to recognize the type automatically is_spec = False if inds_mat.shape[0] < inds_mat.shape[1]: is_spec = True else: if not isinstance(is_spec, bool): raise TypeError('is_spec should be a boolean. Provided object is of type: {}'.format(type(is_spec))) if verbose: print( 'Ancillary matrices of shape: {}, hence determined to be Spectroscopic:{}'.format(inds_mat.shape, is_spec)) if not is_spec: # Convert to spectral shape inds_mat = np.transpose(inds_mat) vals_mat = np.transpose(vals_mat) if len(all_dim_names) != inds_mat.shape[0]: raise ValueError('Length of dimension names list: {} not matching with shape of dataset: {}' '.'.format(len(all_dim_names), inds_mat.shape[0])) if dim_names is None: dim_names = all_dim_names if verbose: print('Going to return unit values for all dimensions: {}'.format(all_dim_names)) else: dim_names = validate_list_of_strings(dim_names, 'dim_names') if verbose: print('Checking to make sure that the target dimension names: {} exist in the datasets attributes: {}' '.'.format(dim_names, all_dim_names)) # check to make sure that the dimension names exist in the datasets: for dim_name in dim_names: if dim_name not in all_dim_names: raise KeyError('Dimension {} does not exist in the provided ancillary datasets'.format(dim_name)) unit_values = dict() for dim_name in all_dim_names: # Find the row in the spectroscopic indices that corresponds to the dimensions we want to slice: if verbose: print('Looking for dimension: {} in {}'.format(dim_name, dim_names)) desired_row_ind = np.where(all_dim_names == dim_name)[0][0] inds_for_dim = inds_mat[desired_row_ind] # Wherever this dimension goes to 0 - start of a new tile starts = np.where(inds_for_dim == np.min(inds_for_dim))[0] if starts[0] != 0: raise ValueError('Spectroscopic Indices for dimension: "{}" not ' 'starting with 0. Please fix this and try again' '.'.format(dim_name)) # There may be repetitions in addition to tiling. Find how the the positions increase. # 1 = repetition, > 1 = new tile step_sizes = np.hstack(([1], np.diff(starts))) # This array is of the same length as the full indices array # We should expect only two values of step sizes for a regular dimension (tiles of the same size): # 1 for same value repeating and a big jump in indices when the next tile starts # If the repeats / tiles are of different lengths, then this is not a regular dimension. # What does a Unit Values vector even mean in this case? Just raise an error for now if np.where(np.unique(step_sizes) - 1)[0].size > 1: raise ValueError('Non constant step sizes') # Finding Start of a new tile tile_starts = np.where(step_sizes > 1)[0] # converting these indices to correct indices that can be mapped straight to if len(tile_starts) < 1: # Dimension(s) with no tiling at all # Make it look as though the next tile starts at the end of the whole indices vector tile_starts = np.array([0, len(inds_for_dim)]) else: # Dimension with some form of repetition tile_starts = np.hstack(([0], starts[tile_starts])) # Verify that each tile is identical here # Last tile will not be checked unless we add the length of the indices vector as the start of next tile tile_starts = np.hstack((tile_starts, [len(inds_for_dim)])) subsections = [inds_for_dim[tile_starts[ind]: tile_starts[ind + 1]] for ind in range(len(tile_starts) - 1)] if np.max(np.diff(subsections, axis=0)) != 0: # Should get unit values for ALL dimensions regardless of expectations to catch such scenarios. raise ValueError('Values in each tile of dimension: {} are different'.format(dim_name)) # Now looking within the first tile: subsection = inds_for_dim[tile_starts[0]:tile_starts[1]] # remove all repetitions. ie - take indices only where jump == 1 step_inds = np.hstack(([0], np.where(np.hstack(([0], np.diff(subsection))))[0])) # Finally, use these indices to get the values if dim_name in dim_names: # Only add this dimension to dictionary if requwested. unit_values[dim_name] = vals_mat[desired_row_ind, step_inds] return unit_values def write_main_dataset(h5_parent_group, main_data, main_data_name, quantity, units, pos_dims, spec_dims, main_dset_attrs=None, h5_pos_inds=None, h5_pos_vals=None, h5_spec_inds=None, h5_spec_vals=None, aux_spec_prefix='Spectroscopic_', aux_pos_prefix='Position_', verbose=False, slow_to_fast=False, **kwargs): """ Writes the provided data as a 'Main' dataset with all appropriate linking. By default, the instructions for generating the ancillary datasets should be specified using the pos_dims and spec_dims arguments as dictionary objects. Alternatively, if both the indices and values datasets are already available for either/or the positions / spectroscopic, they can be specified using the keyword arguments. In this case, fresh datasets will not be generated. Parameters ---------- h5_parent_group : :class:`h5py.Group` Parent group under which the datasets will be created main_data : numpy.ndarray, dask.array.core.Array, list or tuple 2D matrix formatted as [position, spectral] or a list / tuple with the shape for an empty dataset. If creating an empty dataset - the dtype must be specified via a kwarg. main_data_name : String / Unicode Name to give to the main dataset. This cannot contain the '-' character. quantity : String / Unicode Name of the physical quantity stored in the dataset. Example - 'Current' units : String / Unicode Name of units for the quantity stored in the dataset. Example - 'A' for amperes pos_dims : Dimension or array-like of Dimension objects Sequence of Dimension objects that provides all necessary instructions for constructing the indices and values datasets Object specifying the instructions necessary for building the Position indices and values datasets spec_dims : Dimension or array-like of Dimension objects Sequence of Dimension objects that provides all necessary instructions for constructing the indices and values datasets Object specifying the instructions necessary for building the Spectroscopic indices and values datasets main_dset_attrs : dictionary, Optional Dictionary of parameters that will be written to the main dataset. Do NOT include region references here. h5_pos_inds : h5py.Dataset, Optional Dataset that will be linked with the name "Position_Indices" h5_pos_vals : h5py.Dataset, Optional Dataset that will be linked with the name "Position_Values" h5_spec_inds : h5py.Dataset, Optional Dataset that will be linked with the name "Spectroscopic_Indices" h5_spec_vals : h5py.Dataset, Optional Dataset that will be linked with the name "Spectroscopic_Values" aux_spec_prefix : str or unicode, Optional Default prefix for Spectroscopic datasets. Default = "Spectroscopic" aux_pos_prefix : str or unicode, Optional Default prefix for Position datasets. Default = "Position" verbose : bool, Optional, default=False If set to true - prints debugging logs slow_to_fast : bool, Optional. Default=False Set to True if the dimensions are arranged from slowest varying to fastest varying. Set to False otherwise. kwargs will be passed onto the creation of the dataset. Please pass chunking, compression, dtype, and other arguments this way Returns ------- h5_main : USIDataset Reference to the main dataset """ def __check_anc_before_creation(aux_prefix, dim_type='pos'): aux_prefix = validate_single_string_arg(aux_prefix, 'aux_' + dim_type + '_prefix') if not aux_prefix.endswith('_'): aux_prefix += '_' if '-' in aux_prefix: warn('aux_' + dim_type + ' should not contain the "-" character. Reformatted name from:{} to ' '{}'.format(aux_prefix, aux_prefix.replace('-', '_'))) aux_prefix = aux_prefix.replace('-', '_') for dset_name in [aux_prefix + 'Indices', aux_prefix + 'Values']: if dset_name in h5_parent_group.keys(): # TODO: What if the contained data was correct? raise KeyError('Dataset named: ' + dset_name + ' already exists in group: ' '{}. Consider passing these datasets using kwargs (if they are correct) instead of providing the pos_dims and spec_dims arguments'.format(h5_parent_group.name)) return aux_prefix def __ensure_anc_in_correct_file(h5_inds, h5_vals, prefix): if h5_inds.file != h5_vals.file: raise ValueError('Provided ' + prefix + ' datasets are present in different HDF5 files!') if h5_inds.file != h5_parent_group.file: # Need to copy over the anc datasets to the new group if verbose: print('Need to copy over ancillary datasets: {} and {} to ' 'destination group: {} which is in a different HDF5 ' 'file'.format(h5_inds, h5_vals, h5_parent_group)) ret_vals = [copy_dataset(x, h5_parent_group, verbose=verbose) for x in [h5_inds, h5_vals]] else: ret_vals = [h5_inds, h5_vals] return tuple(ret_vals) if not isinstance(h5_parent_group, (h5py.Group, h5py.File)): raise TypeError('h5_parent_group should be a h5py.File or h5py.Group object') if not is_editable_h5(h5_parent_group): raise ValueError('The provided file is not editable') if verbose: print('h5 group and file OK') quantity, units, main_data_name = validate_string_args([quantity, units, main_data_name], ['quantity', 'units', 'main_data_name']) if verbose: print('quantity, units, main_data_name all OK') quantity = quantity.strip() units = units.strip() main_data_name = main_data_name.strip() if '-' in main_data_name: warn('main_data_name should not contain the "-" character. Reformatted name from:{} to ' '{}'.format(main_data_name, main_data_name.replace('-', '_'))) main_data_name = main_data_name.replace('-', '_') if isinstance(main_data, (list, tuple)): if not contains_integers(main_data, min_val=1): raise ValueError('main_data if specified as a shape should be a list / tuple of integers >= 1') if len(main_data) != 2: raise ValueError('main_data if specified as a shape should contain 2 numbers') if 'dtype' not in kwargs: raise ValueError('dtype must be included as a kwarg when creating an empty dataset') _ = validate_dtype(kwargs.get('dtype')) main_shape = main_data if verbose: print('Selected empty dataset creation. OK so far') elif isinstance(main_data, (np.ndarray, da.core.Array)): if main_data.ndim != 2: raise ValueError('main_data should be a 2D array') main_shape = main_data.shape if verbose: print('Provided numpy or Dask array for main_data OK so far') else: raise TypeError('main_data should either be a numpy array or a tuple / list with the shape of the data') if h5_pos_inds is not None and h5_pos_vals is not None: # The provided datasets override fresh building instructions. validate_anc_h5_dsets(h5_pos_inds, h5_pos_vals, main_shape, is_spectroscopic=False) if verbose: print('The shapes of the provided h5 position indices and values are OK') h5_pos_inds, h5_pos_vals = __ensure_anc_in_correct_file(h5_pos_inds, h5_pos_vals, 'Position') else: aux_pos_prefix = __check_anc_before_creation(aux_pos_prefix, dim_type='pos') pos_dims = validate_dimensions(pos_dims, dim_type='Position') validate_dims_against_main(main_shape, pos_dims, is_spectroscopic=False) if verbose: print('Passed all pre-tests for creating position datasets') h5_pos_inds, h5_pos_vals = write_ind_val_dsets(h5_parent_group, pos_dims, is_spectral=False, verbose=verbose, slow_to_fast=slow_to_fast, base_name=aux_pos_prefix) if verbose: print('Created position datasets!') if h5_spec_inds is not None and h5_spec_vals is not None: # The provided datasets override fresh building instructions. validate_anc_h5_dsets(h5_spec_inds, h5_spec_vals, main_shape, is_spectroscopic=True) if verbose: print('The shapes of the provided h5 position indices and values ' 'are OK') h5_spec_inds, h5_spec_vals = __ensure_anc_in_correct_file(h5_spec_inds, h5_spec_vals, 'Spectroscopic') else: aux_spec_prefix = __check_anc_before_creation(aux_spec_prefix, dim_type='spec') spec_dims = validate_dimensions(spec_dims, dim_type='Spectroscopic') validate_dims_against_main(main_shape, spec_dims, is_spectroscopic=True) if verbose: print('Passed all pre-tests for creating spectroscopic datasets') h5_spec_inds, h5_spec_vals = write_ind_val_dsets(h5_parent_group, spec_dims, is_spectral=True, verbose=verbose, slow_to_fast=slow_to_fast, base_name=aux_spec_prefix) if verbose: print('Created Spectroscopic datasets') if h5_parent_group.file.driver == 'mpio': if kwargs.pop('compression', None) is not None: warn('This HDF5 file has been opened wth the "mpio" communicator. ' 'mpi4py does not allow creation of compressed datasets. Compression kwarg has been removed') if isinstance(main_data, np.ndarray): # Case 1 - simple small dataset h5_main = h5_parent_group.create_dataset(main_data_name, data=main_data, **kwargs) if verbose: print('Created main dataset with provided data') elif isinstance(main_data, da.core.Array): # Case 2 - Dask dataset # step 0 - get rid of any automated dtype specification: _ = kwargs.pop('dtype', None) # step 1 - create the empty dataset: h5_main = h5_parent_group.create_dataset(main_data_name, shape=main_data.shape, dtype=main_data.dtype, **kwargs) if verbose: print('Created empty dataset: {} for writing Dask dataset: {}'.format(h5_main, main_data)) print('Dask array will be written to HDF5 dataset: "{}" in file: "{}"'.format(h5_main.name, h5_main.file.filename)) # Step 2 - now ask Dask to dump data to disk da.to_hdf5(h5_main.file.filename, {h5_main.name: main_data}) # main_data.to_hdf5(h5_main.file.filename, h5_main.name) # Does not work with python 2 for some reason else: # Case 3 - large empty dataset h5_main = h5_parent_group.create_dataset(main_data_name, main_data, **kwargs) if verbose: print('Created empty dataset for Main') write_simple_attrs(h5_main, {'quantity': quantity, 'units': units}) if verbose: print('Wrote quantity and units attributes to main dataset') if isinstance(main_dset_attrs, dict): write_simple_attrs(h5_main, main_dset_attrs) if verbose: print('Wrote provided attributes to main dataset') write_book_keeping_attrs(h5_main) # make it main link_as_main(h5_main, h5_pos_inds, h5_pos_vals, h5_spec_inds, h5_spec_vals) if verbose: print('Successfully linked datasets - dataset should be main now') from ..usi_data import USIDataset return USIDataset(h5_main) def map_grid_to_cartesian(h5_main, grid_shape, mode='histogram', **kwargs): """ Map an incomplete measurement, such as a spiral scan, to a cartesian grid. Parameters ---------- h5_main : :class:`pyUSID.USIDataset` Dataset containing the sparse measurement grid_shape : int or [int, int] Shape of the output :class:`numpy.ndarray`. mode : str, optional. Default = 'histogram' Method used for building a cartesian grid. Available methods = 'histogram', 'linear', 'nearest', 'cubic' Use kwargs to pass onto each of the techniques Note ---- UNDER DEVELOPMENT! Currently only valid for 2 position dimensions @author: <NAME> Returns ------- :class:`numpy.ndarray` but could be a h5py.Dataset or dask.array.core.Array object """ try: from scipy.interpolate import griddata except ImportError as expn: griddata = None warn('map_grid_to_cartesian() requires scipy') raise expn from ..usi_data import USIDataset if not isinstance(h5_main, USIDataset): raise TypeError('Provided object is not a pyUSID.USIDataset object') if mode not in ['histogram', 'linear', 'nearest', 'cubic']: raise ValueError('mode must be a string among["histogram", "cubic"]') ds_main = h5_main[()].squeeze() ds_pos_vals = h5_main.h5_pos_vals[()] if ds_pos_vals.shape[1] != 2: raise TypeError("Only working for 2 position dimensions.") # Transform to row, col image format rotation = np.array([[0, 1], [-1, 0]]) ds_pos_vals = np.dot(ds_pos_vals, rotation) try: grid_n = len(grid_shape) except TypeError: grid_n = 1 if grid_n != 1 and grid_n != 2: raise ValueError("grid_shape must be of type int or [int, int].") if grid_n == 1: grid_shape = 2 * [grid_shape] def interpolate(points, values, grid_shape, method): grid_shape = list(map((1j).__mul__, grid_shape)) grid_x, grid_y = np.mgrid[ np.amin(points[:, 0]):np.amax(points[:, 0]):grid_shape[0], np.amin(points[:, 1]):np.amax(points[:, 1]):grid_shape[1] ] ndim_data = griddata(points, values, (grid_x, grid_y), method=method) return ndim_data if mode == "histogram": histogram_weighted, _, _ = np.histogram2d(*ds_pos_vals.T, bins=grid_shape, weights=ds_main) histogram, _, _ = np.histogram2d(*ds_pos_vals.T, bins=grid_shape) cart_data = np.divide(histogram_weighted, histogram) else: cart_data = interpolate(ds_pos_vals, ds_main, grid_shape, method=mode) return cart_data def write_sidpy_dataset(si_dset, h5_parent_group, verbose=False, **kwargs): """ Writes a sidpy.Dataset as a USID dataset in the provided HDF5 Group. Please see notes about dimension types Parameters ---------- si_dset: sidpy.Dataset Dataset to be written to HDF5 in NSID format h5_parent_group : class:`h5py.Group` Parent group under which the datasets will be created verbose : bool, Optional. Default = False Whether or not to write logs to standard out kwargs: dict additional keyword arguments passed on to h5py when writing data Returns ------ h5_main : USIDataset Reference to the main dataset Notes ----- USID only has two dimension types - Position and Spectroscopic. Consider changing the types of dimensions of all other dimensions to either "SPATIAL" or "SPECTRAL". """ if not isinstance(si_dset, sid.Dataset): raise TypeError('Data to write is not a sidpy dataset') if not isinstance(h5_parent_group, (h5py.File, h5py.Group)): raise TypeError('h5_parent_group is not a h5py.File or ' 'h5py.Group object') spatial_dims, spectral_dims, spatial_size, spectral_size = [], [], 1, 1 for dim_ind, dime in si_dset._axes.items(): if dime._dimension_type == sid.DimensionType.SPATIAL: spatial_dims.append(Dimension(dime._name, dime._units, dime.values, dime._quantity, dime._dimension_type)) spatial_size *= np.size(dime.values) else: if not dime._dimension_type == sid.DimensionType.SPECTRAL: warn('Will consider dimension: {} of type: {} as a ' 'spectroscopic dimension'.format(dime._name, dime._dimension_type)) spectral_dims.append(Dimension(dime._name, dime._units, dime.values, dime._quantity, dime._dimension_type)) spectral_size *= np.size(dime.values) main_dataset = da.reshape(si_dset, [spatial_size, spectral_size]) # TODO : Consider writing this out as a separate group main_dset_attr = {} for attr_name in dir(si_dset): attr_val = getattr(si_dset, attr_name) if isinstance(attr_val, dict): main_dset_attr.update(attr_val) h5_main = write_main_dataset(h5_parent_group=h5_parent_group, main_data=main_dataset, main_data_name=si_dset.name, quantity=si_dset.quantity, units=si_dset.units, pos_dims=spatial_dims, spec_dims=spectral_dims, main_dset_attrs=flatten_dict(main_dset_attr), slow_to_fast=True, verbose=verbose, **kwargs) return h5_main
[ "numpy.product", "numpy.prod", "sidpy.base.string_utils.validate_list_of_strings", "numpy.hstack", "numpy.argsort", "numpy.array", "numpy.divide", "numpy.arange", "numpy.atleast_2d", "dask.array.reshape", "sidpy.hdf.hdf_utils.copy_dataset", "numpy.where", "sidpy.hdf.hdf_utils.lazy_load_array...
[((4720, 4743), 'numpy.array', 'np.array', (["['Positions']"], {}), "(['Positions'])\n", (4728, 4743), True, 'import numpy as np\n'), ((4760, 4787), 'numpy.array', 'np.array', (["['Spectral_Step']"], {}), "(['Spectral_Step'])\n", (4768, 4787), True, 'import numpy as np\n'), ((10784, 10849), 'numpy.hstack', 'np.hstack', (['(pos_labs[pos_sort][::-1], spec_labs[spec_sort][::-1])'], {}), '((pos_labs[pos_sort][::-1], spec_labs[spec_sort][::-1]))\n', (10793, 10849), True, 'import numpy as np\n'), ((11683, 11702), 'numpy.array', 'np.array', (['swap_axes'], {}), '(swap_axes)\n', (11691, 11702), True, 'import numpy as np\n'), ((37647, 37747), 'sidpy.base.string_utils.validate_string_args', 'validate_string_args', (['[quantity, units, main_data_name]', "['quantity', 'units', 'main_data_name']"], {}), "([quantity, units, main_data_name], ['quantity',\n 'units', 'main_data_name'])\n", (37667, 37747), False, 'from sidpy.base.string_utils import validate_single_string_arg, validate_list_of_strings, validate_string_args\n'), ((43230, 43297), 'sidpy.hdf.hdf_utils.write_simple_attrs', 'write_simple_attrs', (['h5_main', "{'quantity': quantity, 'units': units}"], {}), "(h5_main, {'quantity': quantity, 'units': units})\n", (43248, 43297), False, 'from sidpy.hdf.hdf_utils import get_attr, write_simple_attrs, is_editable_h5, copy_dataset, lazy_load_array\n'), ((45420, 45447), 'numpy.array', 'np.array', (['[[0, 1], [-1, 0]]'], {}), '([[0, 1], [-1, 0]])\n', (45428, 45447), True, 'import numpy as np\n'), ((45466, 45495), 'numpy.dot', 'np.dot', (['ds_pos_vals', 'rotation'], {}), '(ds_pos_vals, rotation)\n', (45472, 45495), True, 'import numpy as np\n'), ((48943, 48993), 'dask.array.reshape', 'da.reshape', (['si_dset', '[spatial_size, spectral_size]'], {}), '(si_dset, [spatial_size, spectral_size])\n', (48953, 48993), True, 'from dask import array as da\n'), ((7906, 7926), 'numpy.transpose', 'np.transpose', (['ds_pos'], {}), '(ds_pos)\n', (7918, 7926), True, 'import numpy as np\n'), ((8295, 8315), 'numpy.transpose', 'np.transpose', (['ds_pos'], {}), '(ds_pos)\n', (8307, 8315), True, 'import numpy as np\n'), ((8390, 8407), 'numpy.prod', 'np.prod', (['pos_dims'], {}), '(pos_dims)\n', (8397, 8407), True, 'import numpy as np\n'), ((8773, 8791), 'numpy.prod', 'np.prod', (['spec_dims'], {}), '(spec_dims)\n', (8780, 8791), True, 'import numpy as np\n'), ((9502, 9526), 'sidpy.hdf.hdf_utils.lazy_load_array', 'lazy_load_array', (['h5_main'], {}), '(h5_main)\n', (9517, 9526), False, 'from sidpy.hdf.hdf_utils import get_attr, write_simple_attrs, is_editable_h5, copy_dataset, lazy_load_array\n'), ((21212, 21234), 'numpy.transpose', 'np.transpose', (['ds_index'], {}), '(ds_index)\n', (21224, 21234), True, 'import numpy as np\n'), ((21284, 21312), 'numpy.arange', 'np.arange', (['ds_index.shape[0]'], {}), '(ds_index.shape[0])\n', (21293, 21312), True, 'import numpy as np\n'), ((21472, 21492), 'numpy.array', 'np.array', (['index_sort'], {}), '(index_sort)\n', (21480, 21492), True, 'import numpy as np\n'), ((23028, 23049), 'numpy.transpose', 'np.transpose', (['ds_spec'], {}), '(ds_spec)\n', (23040, 23049), True, 'import numpy as np\n'), ((23175, 23199), 'numpy.argsort', 'np.argsort', (['change_count'], {}), '(change_count)\n', (23185, 23199), True, 'import numpy as np\n'), ((24753, 24809), 'sidpy.base.string_utils.validate_list_of_strings', 'validate_list_of_strings', (['all_dim_names', '"""all_dim_names"""'], {}), "(all_dim_names, 'all_dim_names')\n", (24777, 24809), False, 'from sidpy.base.string_utils import validate_single_string_arg, validate_list_of_strings, validate_string_args\n'), ((24834, 24857), 'numpy.array', 'np.array', (['all_dim_names'], {}), '(all_dim_names)\n', (24842, 24857), True, 'import numpy as np\n'), ((26949, 26976), 'sidpy.hdf.hdf_utils.get_attr', 'get_attr', (['ds_inds', '"""labels"""'], {}), "(ds_inds, 'labels')\n", (26957, 26976), False, 'from sidpy.hdf.hdf_utils import get_attr, write_simple_attrs, is_editable_h5, copy_dataset, lazy_load_array\n'), ((27706, 27728), 'numpy.transpose', 'np.transpose', (['inds_mat'], {}), '(inds_mat)\n', (27718, 27728), True, 'import numpy as np\n'), ((27748, 27770), 'numpy.transpose', 'np.transpose', (['vals_mat'], {}), '(vals_mat)\n', (27760, 27770), True, 'import numpy as np\n'), ((28202, 28250), 'sidpy.base.string_utils.validate_list_of_strings', 'validate_list_of_strings', (['dim_names', '"""dim_names"""'], {}), "(dim_names, 'dim_names')\n", (28226, 28250), False, 'from sidpy.base.string_utils import validate_single_string_arg, validate_list_of_strings, validate_string_args\n'), ((35582, 35651), 'sidpy.base.string_utils.validate_single_string_arg', 'validate_single_string_arg', (['aux_prefix', "('aux_' + dim_type + '_prefix')"], {}), "(aux_prefix, 'aux_' + dim_type + '_prefix')\n", (35608, 35651), False, 'from sidpy.base.string_utils import validate_single_string_arg, validate_list_of_strings, validate_string_args\n'), ((37459, 37490), 'sidpy.hdf.hdf_utils.is_editable_h5', 'is_editable_h5', (['h5_parent_group'], {}), '(h5_parent_group)\n', (37473, 37490), False, 'from sidpy.hdf.hdf_utils import get_attr, write_simple_attrs, is_editable_h5, copy_dataset, lazy_load_array\n'), ((43434, 43478), 'sidpy.hdf.hdf_utils.write_simple_attrs', 'write_simple_attrs', (['h5_main', 'main_dset_attrs'], {}), '(h5_main, main_dset_attrs)\n', (43452, 43478), False, 'from sidpy.hdf.hdf_utils import get_attr, write_simple_attrs, is_editable_h5, copy_dataset, lazy_load_array\n'), ((46071, 46128), 'scipy.interpolate.griddata', 'griddata', (['points', 'values', '(grid_x, grid_y)'], {'method': 'method'}), '(points, values, (grid_x, grid_y), method=method)\n', (46079, 46128), False, 'from scipy.interpolate import griddata\n'), ((46219, 46283), 'numpy.histogram2d', 'np.histogram2d', (['*ds_pos_vals.T'], {'bins': 'grid_shape', 'weights': 'ds_main'}), '(*ds_pos_vals.T, bins=grid_shape, weights=ds_main)\n', (46233, 46283), True, 'import numpy as np\n'), ((46310, 46357), 'numpy.histogram2d', 'np.histogram2d', (['*ds_pos_vals.T'], {'bins': 'grid_shape'}), '(*ds_pos_vals.T, bins=grid_shape)\n', (46324, 46357), True, 'import numpy as np\n'), ((46378, 46418), 'numpy.divide', 'np.divide', (['histogram_weighted', 'histogram'], {}), '(histogram_weighted, histogram)\n', (46387, 46418), True, 'import numpy as np\n'), ((5961, 5987), 'sidpy.hdf.hdf_utils.get_attr', 'get_attr', (['h5_pos', '"""labels"""'], {}), "(h5_pos, 'labels')\n", (5969, 5987), False, 'from sidpy.hdf.hdf_utils import get_attr, write_simple_attrs, is_editable_h5, copy_dataset, lazy_load_array\n'), ((7499, 7526), 'sidpy.hdf.hdf_utils.get_attr', 'get_attr', (['h5_spec', '"""labels"""'], {}), "(h5_spec, 'labels')\n", (7507, 7526), False, 'from sidpy.hdf.hdf_utils import get_attr, write_simple_attrs, is_editable_h5, copy_dataset, lazy_load_array\n'), ((8698, 8715), 'numpy.prod', 'np.prod', (['pos_dims'], {}), '(pos_dims)\n', (8705, 8715), True, 'import numpy as np\n'), ((9089, 9107), 'numpy.prod', 'np.prod', (['spec_dims'], {}), '(spec_dims)\n', (9096, 9107), True, 'import numpy as np\n'), ((10126, 10241), 'warnings.warn', 'warn', (['"""Could not reshape dataset to full N-dimensional form. Attempting reshape based on position only."""'], {}), "(\n 'Could not reshape dataset to full N-dimensional form. Attempting reshape based on position only.'\n )\n", (10130, 10241), False, 'from warnings import warn\n'), ((15784, 15835), 'numpy.all', 'np.all', (['[(x in data_n_dim.shape) for x in pos_dims]'], {}), '([(x in data_n_dim.shape) for x in pos_dims])\n', (15790, 15835), True, 'import numpy as np\n'), ((18946, 18966), 'numpy.transpose', 'np.transpose', (['ds_pos'], {}), '(ds_pos)\n', (18958, 18966), True, 'import numpy as np\n'), ((21338, 21378), 'sidpy.base.num_utils.contains_integers', 'contains_integers', (['index_sort'], {'min_val': '(0)'}), '(index_sort, min_val=0)\n', (21355, 21378), False, 'from sidpy.base.num_utils import contains_integers\n'), ((22129, 22143), 'numpy.unique', 'np.unique', (['row'], {}), '(row)\n', (22138, 22143), True, 'import numpy as np\n'), ((26377, 26404), 'sidpy.hdf.hdf_utils.get_attr', 'get_attr', (['ds_inds', '"""labels"""'], {}), "(ds_inds, 'labels')\n", (26385, 26404), False, 'from sidpy.hdf.hdf_utils import get_attr, write_simple_attrs, is_editable_h5, copy_dataset, lazy_load_array\n'), ((30293, 30317), 'numpy.where', 'np.where', (['(step_sizes > 1)'], {}), '(step_sizes > 1)\n', (30301, 30317), True, 'import numpy as np\n'), ((30738, 30775), 'numpy.hstack', 'np.hstack', (['([0], starts[tile_starts])'], {}), '(([0], starts[tile_starts]))\n', (30747, 30775), True, 'import numpy as np\n'), ((38296, 38335), 'sidpy.base.num_utils.contains_integers', 'contains_integers', (['main_data'], {'min_val': '(1)'}), '(main_data, min_val=1)\n', (38313, 38335), False, 'from sidpy.base.num_utils import contains_integers\n'), ((41613, 41780), 'warnings.warn', 'warn', (['"""This HDF5 file has been opened wth the "mpio" communicator. mpi4py does not allow creation of compressed datasets. Compression kwarg has been removed"""'], {}), '(\n \'This HDF5 file has been opened wth the "mpio" communicator. mpi4py does not allow creation of compressed datasets. Compression kwarg has been removed\'\n )\n', (41617, 41780), False, 'from warnings import warn\n'), ((42845, 42905), 'dask.array.to_hdf5', 'da.to_hdf5', (['h5_main.file.filename', '{h5_main.name: main_data}'], {}), '(h5_main.file.filename, {h5_main.name: main_data})\n', (42855, 42905), True, 'from dask import array as da\n'), ((44812, 44858), 'warnings.warn', 'warn', (['"""map_grid_to_cartesian() requires scipy"""'], {}), "('map_grid_to_cartesian() requires scipy')\n", (44816, 44858), False, 'from warnings import warn\n'), ((48253, 48273), 'numpy.size', 'np.size', (['dime.values'], {}), '(dime.values)\n', (48260, 48273), True, 'import numpy as np\n'), ((48902, 48922), 'numpy.size', 'np.size', (['dime.values'], {}), '(dime.values)\n', (48909, 48922), True, 'import numpy as np\n'), ((49706, 49734), 'sidpy.base.dict_utils.flatten_dict', 'flatten_dict', (['main_dset_attr'], {}), '(main_dset_attr)\n', (49718, 49734), False, 'from sidpy.base.dict_utils import flatten_dict\n'), ((5100, 5126), 'sidpy.hdf.hdf_utils.get_attr', 'get_attr', (['h5_pos', '"""labels"""'], {}), "(h5_pos, 'labels')\n", (5108, 5126), False, 'from sidpy.hdf.hdf_utils import get_attr, write_simple_attrs, is_editable_h5, copy_dataset, lazy_load_array\n'), ((6063, 6084), 'numpy.atleast_2d', 'np.atleast_2d', (['h5_pos'], {}), '(h5_pos)\n', (6076, 6084), True, 'import numpy as np\n'), ((6606, 6633), 'sidpy.hdf.hdf_utils.get_attr', 'get_attr', (['h5_spec', '"""labels"""'], {}), "(h5_spec, 'labels')\n", (6614, 6633), False, 'from sidpy.hdf.hdf_utils import get_attr, write_simple_attrs, is_editable_h5, copy_dataset, lazy_load_array\n'), ((16738, 16790), 'numpy.all', 'np.all', (['[(x in data_n_dim.shape) for x in spec_dims]'], {}), '([(x in data_n_dim.shape) for x in spec_dims])\n', (16744, 16790), True, 'import numpy as np\n'), ((21605, 21626), 'numpy.unique', 'np.unique', (['index_sort'], {}), '(index_sort)\n', (21614, 21626), True, 'import numpy as np\n'), ((21876, 21904), 'numpy.arange', 'np.arange', (['ds_index.shape[0]'], {}), '(ds_index.shape[0])\n', (21885, 21904), True, 'import numpy as np\n'), ((22156, 22183), 'numpy.array', 'np.array', (['ds_index'], {'ndmin': '(2)'}), '(ds_index, ndmin=2)\n', (22164, 22183), True, 'import numpy as np\n'), ((25418, 25460), 'sidpy.hdf.hdf_utils.get_attr', 'get_attr', (['ds_inds', '"""incomplete_dimensions"""'], {}), "(ds_inds, 'incomplete_dimensions')\n", (25426, 25460), False, 'from sidpy.hdf.hdf_utils import get_attr, write_simple_attrs, is_editable_h5, copy_dataset, lazy_load_array\n'), ((25582, 25624), 'sidpy.hdf.hdf_utils.get_attr', 'get_attr', (['ds_vals', '"""incomplete_dimensions"""'], {}), "(ds_vals, 'incomplete_dimensions')\n", (25590, 25624), False, 'from sidpy.hdf.hdf_utils import get_attr, write_simple_attrs, is_editable_h5, copy_dataset, lazy_load_array\n'), ((29009, 29044), 'numpy.where', 'np.where', (['(all_dim_names == dim_name)'], {}), '(all_dim_names == dim_name)\n', (29017, 29044), True, 'import numpy as np\n'), ((29642, 29657), 'numpy.diff', 'np.diff', (['starts'], {}), '(starts)\n', (29649, 29657), True, 'import numpy as np\n'), ((37130, 37179), 'sidpy.hdf.hdf_utils.copy_dataset', 'copy_dataset', (['x', 'h5_parent_group'], {'verbose': 'verbose'}), '(x, h5_parent_group, verbose=verbose)\n', (37142, 37179), False, 'from sidpy.hdf.hdf_utils import get_attr, write_simple_attrs, is_editable_h5, copy_dataset, lazy_load_array\n'), ((5634, 5682), 'numpy.arange', 'np.arange', (['h5_main.shape[0]'], {'dtype': 'INDICES_DTYPE'}), '(h5_main.shape[0], dtype=INDICES_DTYPE)\n', (5643, 5682), True, 'import numpy as np\n'), ((7156, 7204), 'numpy.arange', 'np.arange', (['h5_main.shape[1]'], {'dtype': 'INDICES_DTYPE'}), '(h5_main.shape[1], dtype=INDICES_DTYPE)\n', (7165, 7204), True, 'import numpy as np\n'), ((10344, 10420), 'warnings.warn', 'warn', (['"""Reshape by position only also failed. Will keep dataset in 2d form."""'], {}), "('Reshape by position only also failed. Will keep dataset in 2d form.')\n", (10348, 10420), False, 'from warnings import warn\n'), ((11531, 11561), 'numpy.argwhere', 'np.argwhere', (['(all_labels == lab)'], {}), '(all_labels == lab)\n', (11542, 11561), True, 'import numpy as np\n'), ((11624, 11654), 'numpy.argwhere', 'np.argwhere', (['(all_labels == lab)'], {}), '(all_labels == lab)\n', (11635, 11654), True, 'import numpy as np\n'), ((17463, 17491), 'numpy.product', 'np.product', (['data_n_dim.shape'], {}), '(data_n_dim.shape)\n', (17473, 17491), True, 'import numpy as np\n'), ((29209, 29229), 'numpy.min', 'np.min', (['inds_for_dim'], {}), '(inds_for_dim)\n', (29215, 29229), True, 'import numpy as np\n'), ((31162, 31190), 'numpy.diff', 'np.diff', (['subsections'], {'axis': '(0)'}), '(subsections, axis=0)\n', (31169, 31190), True, 'import numpy as np\n'), ((45912, 45933), 'numpy.amin', 'np.amin', (['points[:, 0]'], {}), '(points[:, 0])\n', (45919, 45933), True, 'import numpy as np\n'), ((45934, 45955), 'numpy.amax', 'np.amax', (['points[:, 0]'], {}), '(points[:, 0])\n', (45941, 45955), True, 'import numpy as np\n'), ((45983, 46004), 'numpy.amin', 'np.amin', (['points[:, 1]'], {}), '(points[:, 1])\n', (45990, 46004), True, 'import numpy as np\n'), ((46005, 46026), 'numpy.amax', 'np.amax', (['points[:, 1]'], {}), '(points[:, 1])\n', (46012, 46026), True, 'import numpy as np\n'), ((21817, 21838), 'numpy.unique', 'np.unique', (['index_sort'], {}), '(index_sort)\n', (21826, 21838), True, 'import numpy as np\n'), ((17848, 17876), 'numpy.product', 'np.product', (['data_n_dim.shape'], {}), '(data_n_dim.shape)\n', (17858, 17876), True, 'import numpy as np\n'), ((30136, 30157), 'numpy.unique', 'np.unique', (['step_sizes'], {}), '(step_sizes)\n', (30145, 30157), True, 'import numpy as np\n'), ((5321, 5369), 'numpy.arange', 'np.arange', (['h5_main.shape[0]'], {'dtype': 'INDICES_DTYPE'}), '(h5_main.shape[0], dtype=INDICES_DTYPE)\n', (5330, 5369), True, 'import numpy as np\n'), ((5551, 5583), 'numpy.array', 'np.array', (['(0)'], {'dtype': 'INDICES_DTYPE'}), '(0, dtype=INDICES_DTYPE)\n', (5559, 5583), True, 'import numpy as np\n'), ((6834, 6882), 'numpy.arange', 'np.arange', (['h5_main.shape[1]'], {'dtype': 'INDICES_DTYPE'}), '(h5_main.shape[1], dtype=INDICES_DTYPE)\n', (6843, 6882), True, 'import numpy as np\n'), ((7071, 7103), 'numpy.array', 'np.array', (['(0)'], {'dtype': 'INDICES_DTYPE'}), '(0, dtype=INDICES_DTYPE)\n', (7079, 7103), True, 'import numpy as np\n'), ((31659, 31678), 'numpy.diff', 'np.diff', (['subsection'], {}), '(subsection)\n', (31666, 31678), True, 'import numpy as np\n')]
from flask_wtf import Form from wtforms import TextField, PasswordField, validators, IntegerField, BooleanField, SelectField, SubmitField from wtforms.validators import Required, Length, Email, ValidationError, Regexp, EqualTo, NumberRange from wtforms.widgets import SubmitInput class SignUp(Form): username = TextField("Username", validators=[Required("Please provide a username without any spaces"), Length(min=4, max=20), Regexp(r'^[\w.@+-]+$', message="Please provide a username without any spaces")]) password = PasswordField("Password", validators=[Required("Please pick a secure password"), Regexp(r'^[\w.@+-]+$', message="Please provide a password without any spaces")]) email = TextField("Email", validators=[Required("Please provide a valid email address"), Length(min=6, max=35), Email(message="That is not a valid email address"), Regexp(r'^[\w.@+-]+$', message="Please provide an email without any spaces")]) firstname = TextField("First Name", validators=[Required("Please provide your first name"), Regexp(r'^[\w.@+-]+$', message="Please enter your first name without any spaces")]) lastname = TextField("Last Name", validators=[Required("Please provide your last name"), Regexp(r'^[\w.@+-]+$', message="Please enter your last name without any spaces")]) class Login(Form): username = TextField("Username", validators=[Required("Please provide a username without any spaces"), Length(min=4, max=20), Regexp(r'^[\w.@+-]+$', message="Please provide a username without any spaces")]) password = PasswordField("Password", validators=[Required("Please pick a secure password"), Regexp(r'^[\w.@+-]+$', message="Please provide a password without any spaces")]) class ForgotPassword(Form): email = TextField("Email", validators=[Required("Please provide a valid email address"), Length(min=6, max=35), Email(message="That is not a valid email address"), Regexp(r'^[\w.@+-]+$', message="Please provide an email without any spaces")]) class NewPassword(Form): password = PasswordField("Password", validators=[Required("Please pick a secure password"), Regexp(r'^[\w.@+-]+$', message="Please provide a password without any spaces")]) confirm_password = PasswordField("Confirm Password", validators=[Required("Required"), Regexp(r'^[\w.@+-]+$', message="Please provide a password without any spaces"), EqualTo("password", message="Passwords must match")]) class ChangePassword(Form): current_password = PasswordField("Current Password", validators=[Required("Please type in your current password"), Regexp(r'^[\w.@+-]+$', message="Please provide a password without any spaces")]) password = PasswordField("<PASSWORD>", validators=[Required("Please pick a secure password"), Regexp(r'^[\w.@+-]+$', message="Please provide a password without any spaces")]) confirm_password = PasswordField("Confirm Password", validators=[Required("Password must match with new password"), Regexp(r'^[\w.@+-]+$', message="Please provide a password without any spaces"), EqualTo("password", message="Password must match with new password")]) class CamSettings(Form): brightness = IntegerField("Brightness", default=50, validators=[Required("Please choose a number between 0 and 100"), NumberRange(min=0, max=100, message="Please choose a number between 0 and 100")]) resolution = SelectField("Video/Image Resolution: ", choices=[("320x240", "320 x 240"), ("640x480", "640 x 480"), ("800x600", "800 x 600")], default="640x480", validators=[(Required("Required"))]) hflip = BooleanField("Horizontal Flip: ", default=False) vflip = BooleanField("Vertical Flip: ", default=False) class Recording(Form): start = SubmitField("Start Recording") stop = SubmitField("Stop Recording") class LicensePlate(Form): license = TextField("License Plate", validators=[Required("Please provide a license plate without any spaces"), Length(min=4, max=10), Regexp(r'^[\w.@+-]+$', message="Please provide a license plate without any spaces")]) class ForceLock(Form): forcelock = SubmitField("Force Lock") class GarageDoor(Form): opengarage = SubmitField("Open Garage")
[ "wtforms.validators.NumberRange", "wtforms.validators.Email", "wtforms.BooleanField", "wtforms.SubmitField", "wtforms.validators.EqualTo", "wtforms.validators.Required", "wtforms.validators.Length", "wtforms.validators.Regexp" ]
[((3527, 3575), 'wtforms.BooleanField', 'BooleanField', (['"""Horizontal Flip: """'], {'default': '(False)'}), "('Horizontal Flip: ', default=False)\n", (3539, 3575), False, 'from wtforms import TextField, PasswordField, validators, IntegerField, BooleanField, SelectField, SubmitField\n'), ((3586, 3632), 'wtforms.BooleanField', 'BooleanField', (['"""Vertical Flip: """'], {'default': '(False)'}), "('Vertical Flip: ', default=False)\n", (3598, 3632), False, 'from wtforms import TextField, PasswordField, validators, IntegerField, BooleanField, SelectField, SubmitField\n'), ((3666, 3696), 'wtforms.SubmitField', 'SubmitField', (['"""Start Recording"""'], {}), "('Start Recording')\n", (3677, 3696), False, 'from wtforms import TextField, PasswordField, validators, IntegerField, BooleanField, SelectField, SubmitField\n'), ((3706, 3735), 'wtforms.SubmitField', 'SubmitField', (['"""Stop Recording"""'], {}), "('Stop Recording')\n", (3717, 3735), False, 'from wtforms import TextField, PasswordField, validators, IntegerField, BooleanField, SelectField, SubmitField\n'), ((4024, 4049), 'wtforms.SubmitField', 'SubmitField', (['"""Force Lock"""'], {}), "('Force Lock')\n", (4035, 4049), False, 'from wtforms import TextField, PasswordField, validators, IntegerField, BooleanField, SelectField, SubmitField\n'), ((4089, 4115), 'wtforms.SubmitField', 'SubmitField', (['"""Open Garage"""'], {}), "('Open Garage')\n", (4100, 4115), False, 'from wtforms import TextField, PasswordField, validators, IntegerField, BooleanField, SelectField, SubmitField\n'), ((347, 403), 'wtforms.validators.Required', 'Required', (['"""Please provide a username without any spaces"""'], {}), "('Please provide a username without any spaces')\n", (355, 403), False, 'from wtforms.validators import Required, Length, Email, ValidationError, Regexp, EqualTo, NumberRange\n'), ((407, 428), 'wtforms.validators.Length', 'Length', ([], {'min': '(4)', 'max': '(20)'}), '(min=4, max=20)\n', (413, 428), False, 'from wtforms.validators import Required, Length, Email, ValidationError, Regexp, EqualTo, NumberRange\n'), ((430, 508), 'wtforms.validators.Regexp', 'Regexp', (['"""^[\\\\w.@+-]+$"""'], {'message': '"""Please provide a username without any spaces"""'}), "('^[\\\\w.@+-]+$', message='Please provide a username without any spaces')\n", (436, 508), False, 'from wtforms.validators import Required, Length, Email, ValidationError, Regexp, EqualTo, NumberRange\n'), ((562, 603), 'wtforms.validators.Required', 'Required', (['"""Please pick a secure password"""'], {}), "('Please pick a secure password')\n", (570, 603), False, 'from wtforms.validators import Required, Length, Email, ValidationError, Regexp, EqualTo, NumberRange\n'), ((607, 685), 'wtforms.validators.Regexp', 'Regexp', (['"""^[\\\\w.@+-]+$"""'], {'message': '"""Please provide a password without any spaces"""'}), "('^[\\\\w.@+-]+$', message='Please provide a password without any spaces')\n", (613, 685), False, 'from wtforms.validators import Required, Length, Email, ValidationError, Regexp, EqualTo, NumberRange\n'), ((729, 777), 'wtforms.validators.Required', 'Required', (['"""Please provide a valid email address"""'], {}), "('Please provide a valid email address')\n", (737, 777), False, 'from wtforms.validators import Required, Length, Email, ValidationError, Regexp, EqualTo, NumberRange\n'), ((781, 802), 'wtforms.validators.Length', 'Length', ([], {'min': '(6)', 'max': '(35)'}), '(min=6, max=35)\n', (787, 802), False, 'from wtforms.validators import Required, Length, Email, ValidationError, Regexp, EqualTo, NumberRange\n'), ((804, 854), 'wtforms.validators.Email', 'Email', ([], {'message': '"""That is not a valid email address"""'}), "(message='That is not a valid email address')\n", (809, 854), False, 'from wtforms.validators import Required, Length, Email, ValidationError, Regexp, EqualTo, NumberRange\n'), ((858, 934), 'wtforms.validators.Regexp', 'Regexp', (['"""^[\\\\w.@+-]+$"""'], {'message': '"""Please provide an email without any spaces"""'}), "('^[\\\\w.@+-]+$', message='Please provide an email without any spaces')\n", (864, 934), False, 'from wtforms.validators import Required, Length, Email, ValidationError, Regexp, EqualTo, NumberRange\n'), ((987, 1029), 'wtforms.validators.Required', 'Required', (['"""Please provide your first name"""'], {}), "('Please provide your first name')\n", (995, 1029), False, 'from wtforms.validators import Required, Length, Email, ValidationError, Regexp, EqualTo, NumberRange\n'), ((1033, 1119), 'wtforms.validators.Regexp', 'Regexp', (['"""^[\\\\w.@+-]+$"""'], {'message': '"""Please enter your first name without any spaces"""'}), "('^[\\\\w.@+-]+$', message=\n 'Please enter your first name without any spaces')\n", (1039, 1119), False, 'from wtforms.validators import Required, Length, Email, ValidationError, Regexp, EqualTo, NumberRange\n'), ((1165, 1206), 'wtforms.validators.Required', 'Required', (['"""Please provide your last name"""'], {}), "('Please provide your last name')\n", (1173, 1206), False, 'from wtforms.validators import Required, Length, Email, ValidationError, Regexp, EqualTo, NumberRange\n'), ((1210, 1295), 'wtforms.validators.Regexp', 'Regexp', (['"""^[\\\\w.@+-]+$"""'], {'message': '"""Please enter your last name without any spaces"""'}), "('^[\\\\w.@+-]+$', message='Please enter your last name without any spaces'\n )\n", (1216, 1295), False, 'from wtforms.validators import Required, Length, Email, ValidationError, Regexp, EqualTo, NumberRange\n'), ((1359, 1415), 'wtforms.validators.Required', 'Required', (['"""Please provide a username without any spaces"""'], {}), "('Please provide a username without any spaces')\n", (1367, 1415), False, 'from wtforms.validators import Required, Length, Email, ValidationError, Regexp, EqualTo, NumberRange\n'), ((1419, 1440), 'wtforms.validators.Length', 'Length', ([], {'min': '(4)', 'max': '(20)'}), '(min=4, max=20)\n', (1425, 1440), False, 'from wtforms.validators import Required, Length, Email, ValidationError, Regexp, EqualTo, NumberRange\n'), ((1442, 1520), 'wtforms.validators.Regexp', 'Regexp', (['"""^[\\\\w.@+-]+$"""'], {'message': '"""Please provide a username without any spaces"""'}), "('^[\\\\w.@+-]+$', message='Please provide a username without any spaces')\n", (1448, 1520), False, 'from wtforms.validators import Required, Length, Email, ValidationError, Regexp, EqualTo, NumberRange\n'), ((1574, 1615), 'wtforms.validators.Required', 'Required', (['"""Please pick a secure password"""'], {}), "('Please pick a secure password')\n", (1582, 1615), False, 'from wtforms.validators import Required, Length, Email, ValidationError, Regexp, EqualTo, NumberRange\n'), ((1619, 1697), 'wtforms.validators.Regexp', 'Regexp', (['"""^[\\\\w.@+-]+$"""'], {'message': '"""Please provide a password without any spaces"""'}), "('^[\\\\w.@+-]+$', message='Please provide a password without any spaces')\n", (1625, 1697), False, 'from wtforms.validators import Required, Length, Email, ValidationError, Regexp, EqualTo, NumberRange\n'), ((1769, 1817), 'wtforms.validators.Required', 'Required', (['"""Please provide a valid email address"""'], {}), "('Please provide a valid email address')\n", (1777, 1817), False, 'from wtforms.validators import Required, Length, Email, ValidationError, Regexp, EqualTo, NumberRange\n'), ((1821, 1842), 'wtforms.validators.Length', 'Length', ([], {'min': '(6)', 'max': '(35)'}), '(min=6, max=35)\n', (1827, 1842), False, 'from wtforms.validators import Required, Length, Email, ValidationError, Regexp, EqualTo, NumberRange\n'), ((1844, 1894), 'wtforms.validators.Email', 'Email', ([], {'message': '"""That is not a valid email address"""'}), "(message='That is not a valid email address')\n", (1849, 1894), False, 'from wtforms.validators import Required, Length, Email, ValidationError, Regexp, EqualTo, NumberRange\n'), ((1898, 1974), 'wtforms.validators.Regexp', 'Regexp', (['"""^[\\\\w.@+-]+$"""'], {'message': '"""Please provide an email without any spaces"""'}), "('^[\\\\w.@+-]+$', message='Please provide an email without any spaces')\n", (1904, 1974), False, 'from wtforms.validators import Required, Length, Email, ValidationError, Regexp, EqualTo, NumberRange\n'), ((2053, 2094), 'wtforms.validators.Required', 'Required', (['"""Please pick a secure password"""'], {}), "('Please pick a secure password')\n", (2061, 2094), False, 'from wtforms.validators import Required, Length, Email, ValidationError, Regexp, EqualTo, NumberRange\n'), ((2098, 2176), 'wtforms.validators.Regexp', 'Regexp', (['"""^[\\\\w.@+-]+$"""'], {'message': '"""Please provide a password without any spaces"""'}), "('^[\\\\w.@+-]+$', message='Please provide a password without any spaces')\n", (2104, 2176), False, 'from wtforms.validators import Required, Length, Email, ValidationError, Regexp, EqualTo, NumberRange\n'), ((2246, 2266), 'wtforms.validators.Required', 'Required', (['"""Required"""'], {}), "('Required')\n", (2254, 2266), False, 'from wtforms.validators import Required, Length, Email, ValidationError, Regexp, EqualTo, NumberRange\n'), ((2270, 2348), 'wtforms.validators.Regexp', 'Regexp', (['"""^[\\\\w.@+-]+$"""'], {'message': '"""Please provide a password without any spaces"""'}), "('^[\\\\w.@+-]+$', message='Please provide a password without any spaces')\n", (2276, 2348), False, 'from wtforms.validators import Required, Length, Email, ValidationError, Regexp, EqualTo, NumberRange\n'), ((2352, 2403), 'wtforms.validators.EqualTo', 'EqualTo', (['"""password"""'], {'message': '"""Passwords must match"""'}), "('password', message='Passwords must match')\n", (2359, 2403), False, 'from wtforms.validators import Required, Length, Email, ValidationError, Regexp, EqualTo, NumberRange\n'), ((2501, 2549), 'wtforms.validators.Required', 'Required', (['"""Please type in your current password"""'], {}), "('Please type in your current password')\n", (2509, 2549), False, 'from wtforms.validators import Required, Length, Email, ValidationError, Regexp, EqualTo, NumberRange\n'), ((2553, 2631), 'wtforms.validators.Regexp', 'Regexp', (['"""^[\\\\w.@+-]+$"""'], {'message': '"""Please provide a password without any spaces"""'}), "('^[\\\\w.@+-]+$', message='Please provide a password without any spaces')\n", (2559, 2631), False, 'from wtforms.validators import Required, Length, Email, ValidationError, Regexp, EqualTo, NumberRange\n'), ((2687, 2728), 'wtforms.validators.Required', 'Required', (['"""Please pick a secure password"""'], {}), "('Please pick a secure password')\n", (2695, 2728), False, 'from wtforms.validators import Required, Length, Email, ValidationError, Regexp, EqualTo, NumberRange\n'), ((2732, 2810), 'wtforms.validators.Regexp', 'Regexp', (['"""^[\\\\w.@+-]+$"""'], {'message': '"""Please provide a password without any spaces"""'}), "('^[\\\\w.@+-]+$', message='Please provide a password without any spaces')\n", (2738, 2810), False, 'from wtforms.validators import Required, Length, Email, ValidationError, Regexp, EqualTo, NumberRange\n'), ((2880, 2929), 'wtforms.validators.Required', 'Required', (['"""Password must match with new password"""'], {}), "('Password must match with new password')\n", (2888, 2929), False, 'from wtforms.validators import Required, Length, Email, ValidationError, Regexp, EqualTo, NumberRange\n'), ((2933, 3011), 'wtforms.validators.Regexp', 'Regexp', (['"""^[\\\\w.@+-]+$"""'], {'message': '"""Please provide a password without any spaces"""'}), "('^[\\\\w.@+-]+$', message='Please provide a password without any spaces')\n", (2939, 3011), False, 'from wtforms.validators import Required, Length, Email, ValidationError, Regexp, EqualTo, NumberRange\n'), ((3015, 3083), 'wtforms.validators.EqualTo', 'EqualTo', (['"""password"""'], {'message': '"""Password must match with new password"""'}), "('password', message='Password must match with new password')\n", (3022, 3083), False, 'from wtforms.validators import Required, Length, Email, ValidationError, Regexp, EqualTo, NumberRange\n'), ((3177, 3229), 'wtforms.validators.Required', 'Required', (['"""Please choose a number between 0 and 100"""'], {}), "('Please choose a number between 0 and 100')\n", (3185, 3229), False, 'from wtforms.validators import Required, Length, Email, ValidationError, Regexp, EqualTo, NumberRange\n'), ((3233, 3312), 'wtforms.validators.NumberRange', 'NumberRange', ([], {'min': '(0)', 'max': '(100)', 'message': '"""Please choose a number between 0 and 100"""'}), "(min=0, max=100, message='Please choose a number between 0 and 100')\n", (3244, 3312), False, 'from wtforms.validators import Required, Length, Email, ValidationError, Regexp, EqualTo, NumberRange\n'), ((3493, 3513), 'wtforms.validators.Required', 'Required', (['"""Required"""'], {}), "('Required')\n", (3501, 3513), False, 'from wtforms.validators import Required, Length, Email, ValidationError, Regexp, EqualTo, NumberRange\n'), ((3813, 3874), 'wtforms.validators.Required', 'Required', (['"""Please provide a license plate without any spaces"""'], {}), "('Please provide a license plate without any spaces')\n", (3821, 3874), False, 'from wtforms.validators import Required, Length, Email, ValidationError, Regexp, EqualTo, NumberRange\n'), ((3878, 3899), 'wtforms.validators.Length', 'Length', ([], {'min': '(4)', 'max': '(10)'}), '(min=4, max=10)\n', (3884, 3899), False, 'from wtforms.validators import Required, Length, Email, ValidationError, Regexp, EqualTo, NumberRange\n'), ((3901, 3989), 'wtforms.validators.Regexp', 'Regexp', (['"""^[\\\\w.@+-]+$"""'], {'message': '"""Please provide a license plate without any spaces"""'}), "('^[\\\\w.@+-]+$', message=\n 'Please provide a license plate without any spaces')\n", (3907, 3989), False, 'from wtforms.validators import Required, Length, Email, ValidationError, Regexp, EqualTo, NumberRange\n')]
import torch from shape_utils import Shape, load_shape_pair, scatter_shape_pair from torch_geometric.nn import knn from param import * from arap_potential import arap_vert def load_multiscale_shapes(folder_path, file_name, scales, offset=0.5*torch.ones([3], device=device, dtype=torch.float32)): """Like 'load_shape_pair' but for shapes with different resolutions""" vert_x_array = [] triv_x_array = [] vert_y_array = [] triv_y_array = [] for i_scale in range(len(scales)): file_load = folder_path + "sub_" + str(scales[i_scale]) + "/" + file_name shape_x, shape_y = load_shape_pair(file_load, offset) vert_x_array.append(shape_x.vert) vert_y_array.append(shape_y.vert) triv_x_array.append(shape_x.triv) triv_y_array.append(shape_y.triv) shape_x = MultiscaleShape(vert_x_array, triv_x_array) shape_y = MultiscaleShape(vert_y_array, triv_y_array) return shape_x, shape_y class MultiscaleShape(Shape): """Class for shapes with multiple resolutions. Attributes beyond the base class 'Shape' are: vert_array: List of vertices with different resolutions triv_array: List of triangles with different resolutions scale_idx: The index describing the current resolution -- The current vertices are vert_array[scale_idx] ass_[array/vecs/weights]: attributes needed to apply an interpolation on scale 'scale_idx' to the next resolution '(scale_idx+1)' """ def __init__(self, vert_array, triv_array): super().__init__(vert_array[0], triv_array[0]) self.vert_array = vert_array self.triv_array = triv_array self.scale_idx = 0 self.scale_idx_len = len(vert_array) self.ass_array = None self.ass_vecs = None self.ass_weights = None self.init_upscale() def set_scale_idx(self, scale_idx): assert scale_idx >= 0 and scale_idx < self.scale_idx_len, "new index out of bounds" self.vert_array[self.scale_idx] = self.vert self.scale_idx = scale_idx self.vert = self.vert_array[scale_idx] self.triv = self.triv_array[scale_idx] self.samples = list(range(self.vert.shape[0])) self.neigh = None def increase_scale_idx(self): self.set_scale_idx(self.scale_idx+1) def next_resolution(self): return self.vert_array[self.scale_idx+1].shape def init_upscale(self, num_knn=3): self.ass_array = [] self.ass_vecs = [] self.ass_weights = [] for idx in range(self.scale_idx_len-1): vert_i = self.vert_array[idx].to(device_cpu) vert_ip1 = self.vert_array[idx+1].to(device_cpu) ass_curr = knn(vert_i, vert_ip1, num_knn) ass_curr = ass_curr[1, :].view(-1, num_knn) self.ass_array.append(ass_curr.to(device)) #[n_vert_tp1, num_knn] vec_curr = vert_ip1.unsqueeze(1) - vert_i[ass_curr, :] self.ass_vecs.append(vec_curr.to(device)) #[n_vert_tp1, num_knn, 3] weights_curr = 1/(torch.norm(vec_curr, dim=2, keepdim=True)+1e-5) weights_curr = weights_curr / torch.sum(weights_curr, dim=1, keepdim=True) self.ass_weights.append(weights_curr.to(device)) #[n_vert_tp1, num_knn, 1] def apply_upsampling(self, vert_t): R = arap_vert(vert_t, self.vert, self.get_neigh()) #[n_vert_tp1, 3, 3] ass_curr = self.ass_array[self.scale_idx] vec_curr = self.ass_vecs[self.scale_idx] weights_curr = self.ass_weights[self.scale_idx] vert_tp1 = vert_t[ass_curr, :] + torch.matmul(R[ass_curr], vec_curr.unsqueeze(3)).squeeze() #[n_vert_tp1, num_knn, 3] vert_tp1 = torch.sum(weights_curr * vert_tp1, dim=1) return vert_tp1 def rotate(self, R): for i in range(self.scale_idx_len): self.vert_array[i] = torch.mm(self.vert_array[i], R.transpose(0, 1)) self.vert = self.vert_array[self.scale_idx] self.init_upscale() def to_box(self, shape_y): scale_idx = self.scale_idx for i in range(self.scale_idx_len): self.set_scale_idx(i) shape_y.set_scale_idx(i) super().to_box(shape_y) self.set_scale_idx(scale_idx) shape_y.set_scale_idx(scale_idx) self.init_upscale() def scale(self, factor, shift=True): scale_idx = self.scale_idx for i in range(self.scale_idx_len): self.set_scale_idx(i) super().scale(factor, shift) self.set_scale_idx(scale_idx) self.init_upscale() if __name__ == "__main__": print("main of multiscale_shape.py")
[ "torch.norm", "torch_geometric.nn.knn", "torch.sum", "shape_utils.load_shape_pair", "torch.ones" ]
[((244, 295), 'torch.ones', 'torch.ones', (['[3]'], {'device': 'device', 'dtype': 'torch.float32'}), '([3], device=device, dtype=torch.float32)\n', (254, 295), False, 'import torch\n'), ((611, 645), 'shape_utils.load_shape_pair', 'load_shape_pair', (['file_load', 'offset'], {}), '(file_load, offset)\n', (626, 645), False, 'from shape_utils import Shape, load_shape_pair, scatter_shape_pair\n'), ((3695, 3736), 'torch.sum', 'torch.sum', (['(weights_curr * vert_tp1)'], {'dim': '(1)'}), '(weights_curr * vert_tp1, dim=1)\n', (3704, 3736), False, 'import torch\n'), ((2702, 2732), 'torch_geometric.nn.knn', 'knn', (['vert_i', 'vert_ip1', 'num_knn'], {}), '(vert_i, vert_ip1, num_knn)\n', (2705, 2732), False, 'from torch_geometric.nn import knn\n'), ((3138, 3182), 'torch.sum', 'torch.sum', (['weights_curr'], {'dim': '(1)', 'keepdim': '(True)'}), '(weights_curr, dim=1, keepdim=True)\n', (3147, 3182), False, 'import torch\n'), ((3048, 3089), 'torch.norm', 'torch.norm', (['vec_curr'], {'dim': '(2)', 'keepdim': '(True)'}), '(vec_curr, dim=2, keepdim=True)\n', (3058, 3089), False, 'import torch\n')]
import numpy as np import scipy import scipy.linalg as linalg import scipy.spatial import scipy.special import scipy.optimize import sklearn def bases(name): if name == 'linear': f = lambda x: x elif name == 'cubic': f = lambda x: x**3 elif name == 'multiquadric': f = lambda x, s: np.sqrt((1.0/s*x)**2 + 1) elif name == 'thin_plate': f = lambda x: scipy.special.xlogy(x**2, x) elif name == 'gaussian': f = lambda x, s: np.exp(-(1.0/s*x)**2) elif name == 'inverse_multiquadric': f = lambda x, s: 1.0/np.sqrt((1.0/s*x)**2 + 1) else: raise ValueError('Basis not recognised.') return f class RbfInterpolator: """ Standard RBF interpolation / kernel smoothing. Written to replace Scipy's Rbf class, which has a silly interface and is difficult to modify Also includes optional optimization of the "smooth" parameter Author: <NAME> -- 2018 """ def __init__(self, norm='euclidean', rbf=lambda r: r, smooth=0.0, optimize_smoothing=False): self.norm = norm self.rbf = rbf self.smooth = smooth self.optimize_smoothing = optimize_smoothing def _opt_smooth(self): # We're just using cross-validation and retraining the whole model. # Likely a lot of improvements possible def obj(x): ss = sklearn.model_selection.ShuffleSplit(n_splits=5, test_size=.3) for tri, tei in ss.split(self._X_train): K = scipy.spatial.distance.squareform(scipy.spatial.distance.pdist(self._X_train[tri,:], self.norm)) K = self.rbf(K) K -= np.eye(K.shape[0]) * x nodes = None rcond = 1/np.linalg.cond(K) if rcond > 1e-10: # If the matrix is not singular, (i.e. most of the time) try: nodes = linalg.solve(K, self._y_train[tri], sym_pos=True) except linalg.LinAlgError: pass if nodes is None: nodes = linalg.lstsq(K, self._y_train[tri])[0] K = scipy.spatial.distance.cdist(self._X_train[tei,:], self._X_train[tri,:], self.norm) K = self.rbf(K) return np.sum((self._y_train[tei] - np.dot(K, nodes))**2) opt_param = scipy.optimize.minimize_scalar(obj, bounds=[.0001,100], bracket=[0.0001,100]) self.smooth = opt_param.x def _make_kernel(self, new_X=None): if new_X is None: K = scipy.spatial.distance.squareform(scipy.spatial.distance.pdist(self._X_train, self.norm)) else: K = scipy.spatial.distance.cdist(new_X, self._X_train, self.norm) K = self.rbf(K) if new_X is None and self.smooth != 0: K -= np.eye(K.shape[0])*self.smooth return K def fit(self, X, y): self._X_train = X self._y_train = y if len(self._X_train.shape) == 1: self._X_train = self._X_train[:,np.newaxis] if self.optimize_smoothing: self._opt_smooth() self.K = self._make_kernel() nodes = None rcond = 1/np.linalg.cond(self.K) if rcond > 1e-10: try: self.nodes = linalg.solve(self.K, self._y_train, sym_pos=True) except linalg.LinAlgError: pass if nodes is None: self.nodes = linalg.lstsq(self.K, self._y_train)[0] def predict(self, X): if len(X.shape) == 1: X = X[:,np.newaxis] K = self._make_kernel(X) return np.dot(K, self.nodes) class RBFConsensus: def __init__(self, sample_frac=.6, subsample_rounds=32, radial_basis_function=lambda x:x, norm='euclidean', copy_data=True, categorical_features=None): self.sample_frac = sample_frac # What fraction of data to sample for each subsampling round self.subsample_rounds = subsample_rounds # How many rounds self.radial_basis_function = radial_basis_function # which interpolator ("linear" with euclidean norm is linear interpolation) self.norm = norm # Which distance function is appropriate? self.copy_data = copy_data # Should input data be copied, or refed? self.N = None self.trained_smooth_param = None self.categorical_features = categorical_features def _fit_one(self, X, y, optimize_smoothing=False): self.rbfis_by_dim = [] for dim in range(y.shape[1]): # Use previously optimized smoothing unless optimize_smoothing == True if self.trained_smooth_param is None: rbfi = RbfInterpolator(rbf=self.radial_basis_function, norm=self.norm, optimize_smoothing=optimize_smoothing) else: rbfi = RbfInterpolator(smooth=self.trained_smooth_param[dim], rbf=self.radial_basis_function, norm=self.norm, optimize_smoothing=optimize_smoothing) rbfi.fit(X,y[:,dim]) self.rbfis_by_dim.append(rbfi) if optimize_smoothing: # This means we have optimized params available self.trained_smooth_param = [self.rbfis_by_dim[dim].smooth for dim in range(y.shape[1])] return self def _predict_one(self, X): if len(X.shape) == 1: Xp = X[:,np.newaxis] else: Xp = X pred = np.empty([Xp.shape[0], self._y_train.shape[1]]) for dim in range(len(self.rbfis_by_dim)): pred[:,dim] = self.rbfis_by_dim[dim].predict(X).squeeze() return pred def fit(self, X, y): self._y_train = y.copy() if self.copy_data else y self._X_train = X.copy() if self.copy_data else X if len(self._y_train.shape) == 1: self._y_train = self._y_train[:,np.newaxis] if len(self._X_train.shape) == 1: self._X_train = self._X_train[:,np.newaxis] self.N = X.shape[0] def predict(self, X, return_std=False): if self.N is None: raise RuntimeError('`.fit` must be called before `.predict`') N_samp = int(np.ceil(self.N * self.sample_frac)) y_pred = np.empty([X.shape[0], self._y_train.shape[1], self.subsample_rounds]) # np.random.seed(7) for i in range(self.subsample_rounds): r = np.random.permutation(self.N)[:N_samp] y_sub = self._y_train[r,:] X_sub = self._X_train[r,:] self._fit_one(X_sub, y_sub) y_pred[:,:,i] = self._predict_one(X) y_out = y_pred.mean(axis=2) if return_std: y_std = np.sqrt(y_pred.var(axis=2).sum(axis=1)) return y_out, y_std else: return y_out def RBF_unit_test(): import matplotlib.pyplot as plt import time # Generate synthetic 1-d data N = 300 lo = -10.0 hi = 10.0 t = np.linspace(lo,hi,N) y = np.sin(t*.5) - .08*t**2 + np.random.randn(t.shape[0])*.05*(t-lo) # Messy fitting model = RBFConsensus(radial_basis_function=lambda x:bases('inverse_multiquadric')(x,.2)) t0 = time.time() model.fit(t,y) y_pred, y_std = model.predict(t, return_std=True) print(time.time()-t0) y_pred = y_pred.squeeze() y_std = y_std.squeeze() plt.fill_between(t, y_pred - 5*y_std, y_pred + 5*y_std, alpha=0.15, color='k') plt.scatter(t,y) plt.plot(t, y_pred, color='red') plt.show()
[ "scipy.special.xlogy", "numpy.sqrt", "numpy.linalg.cond", "matplotlib.pyplot.fill_between", "numpy.sin", "scipy.linalg.lstsq", "matplotlib.pyplot.plot", "sklearn.model_selection.ShuffleSplit", "numpy.exp", "numpy.linspace", "numpy.dot", "numpy.empty", "scipy.optimize.minimize_scalar", "mat...
[((7360, 7382), 'numpy.linspace', 'np.linspace', (['lo', 'hi', 'N'], {}), '(lo, hi, N)\n', (7371, 7382), True, 'import numpy as np\n'), ((7582, 7593), 'time.time', 'time.time', ([], {}), '()\n', (7591, 7593), False, 'import time\n'), ((7757, 7843), 'matplotlib.pyplot.fill_between', 'plt.fill_between', (['t', '(y_pred - 5 * y_std)', '(y_pred + 5 * y_std)'], {'alpha': '(0.15)', 'color': '"""k"""'}), "(t, y_pred - 5 * y_std, y_pred + 5 * y_std, alpha=0.15,\n color='k')\n", (7773, 7843), True, 'import matplotlib.pyplot as plt\n'), ((7840, 7857), 'matplotlib.pyplot.scatter', 'plt.scatter', (['t', 'y'], {}), '(t, y)\n', (7851, 7857), True, 'import matplotlib.pyplot as plt\n'), ((7861, 7893), 'matplotlib.pyplot.plot', 'plt.plot', (['t', 'y_pred'], {'color': '"""red"""'}), "(t, y_pred, color='red')\n", (7869, 7893), True, 'import matplotlib.pyplot as plt\n'), ((7899, 7909), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (7907, 7909), True, 'import matplotlib.pyplot as plt\n'), ((2392, 2477), 'scipy.optimize.minimize_scalar', 'scipy.optimize.minimize_scalar', (['obj'], {'bounds': '[0.0001, 100]', 'bracket': '[0.0001, 100]'}), '(obj, bounds=[0.0001, 100], bracket=[0.0001, 100]\n )\n', (2422, 2477), False, 'import scipy\n'), ((3729, 3750), 'numpy.dot', 'np.dot', (['K', 'self.nodes'], {}), '(K, self.nodes)\n', (3735, 3750), True, 'import numpy as np\n'), ((5721, 5768), 'numpy.empty', 'np.empty', (['[Xp.shape[0], self._y_train.shape[1]]'], {}), '([Xp.shape[0], self._y_train.shape[1]])\n', (5729, 5768), True, 'import numpy as np\n'), ((6582, 6651), 'numpy.empty', 'np.empty', (['[X.shape[0], self._y_train.shape[1], self.subsample_rounds]'], {}), '([X.shape[0], self._y_train.shape[1], self.subsample_rounds])\n', (6590, 6651), True, 'import numpy as np\n'), ((1385, 1448), 'sklearn.model_selection.ShuffleSplit', 'sklearn.model_selection.ShuffleSplit', ([], {'n_splits': '(5)', 'test_size': '(0.3)'}), '(n_splits=5, test_size=0.3)\n', (1421, 1448), False, 'import sklearn\n'), ((2711, 2772), 'scipy.spatial.distance.cdist', 'scipy.spatial.distance.cdist', (['new_X', 'self._X_train', 'self.norm'], {}), '(new_X, self._X_train, self.norm)\n', (2739, 2772), False, 'import scipy\n'), ((3295, 3317), 'numpy.linalg.cond', 'np.linalg.cond', (['self.K'], {}), '(self.K)\n', (3309, 3317), True, 'import numpy as np\n'), ((6528, 6562), 'numpy.ceil', 'np.ceil', (['(self.N * self.sample_frac)'], {}), '(self.N * self.sample_frac)\n', (6535, 6562), True, 'import numpy as np\n'), ((7389, 7404), 'numpy.sin', 'np.sin', (['(t * 0.5)'], {}), '(t * 0.5)\n', (7395, 7404), True, 'import numpy as np\n'), ((7677, 7688), 'time.time', 'time.time', ([], {}), '()\n', (7686, 7688), False, 'import time\n'), ((2172, 2261), 'scipy.spatial.distance.cdist', 'scipy.spatial.distance.cdist', (['self._X_train[tei, :]', 'self._X_train[tri, :]', 'self.norm'], {}), '(self._X_train[tei, :], self._X_train[tri, :],\n self.norm)\n', (2200, 2261), False, 'import scipy\n'), ((2625, 2679), 'scipy.spatial.distance.pdist', 'scipy.spatial.distance.pdist', (['self._X_train', 'self.norm'], {}), '(self._X_train, self.norm)\n', (2653, 2679), False, 'import scipy\n'), ((2883, 2901), 'numpy.eye', 'np.eye', (['K.shape[0]'], {}), '(K.shape[0])\n', (2889, 2901), True, 'import numpy as np\n'), ((3390, 3439), 'scipy.linalg.solve', 'linalg.solve', (['self.K', 'self._y_train'], {'sym_pos': '(True)'}), '(self.K, self._y_train, sym_pos=True)\n', (3402, 3439), True, 'import scipy.linalg as linalg\n'), ((3535, 3570), 'scipy.linalg.lstsq', 'linalg.lstsq', (['self.K', 'self._y_train'], {}), '(self.K, self._y_train)\n', (3547, 3570), True, 'import scipy.linalg as linalg\n'), ((6753, 6782), 'numpy.random.permutation', 'np.random.permutation', (['self.N'], {}), '(self.N)\n', (6774, 6782), True, 'import numpy as np\n'), ((7415, 7442), 'numpy.random.randn', 'np.random.randn', (['t.shape[0]'], {}), '(t.shape[0])\n', (7430, 7442), True, 'import numpy as np\n'), ((320, 351), 'numpy.sqrt', 'np.sqrt', (['((1.0 / s * x) ** 2 + 1)'], {}), '((1.0 / s * x) ** 2 + 1)\n', (327, 351), True, 'import numpy as np\n'), ((1555, 1617), 'scipy.spatial.distance.pdist', 'scipy.spatial.distance.pdist', (['self._X_train[tri, :]', 'self.norm'], {}), '(self._X_train[tri, :], self.norm)\n', (1583, 1617), False, 'import scipy\n'), ((1671, 1689), 'numpy.eye', 'np.eye', (['K.shape[0]'], {}), '(K.shape[0])\n', (1677, 1689), True, 'import numpy as np\n'), ((1766, 1783), 'numpy.linalg.cond', 'np.linalg.cond', (['K'], {}), '(K)\n', (1780, 1783), True, 'import numpy as np\n'), ((399, 429), 'scipy.special.xlogy', 'scipy.special.xlogy', (['(x ** 2)', 'x'], {}), '(x ** 2, x)\n', (418, 429), False, 'import scipy\n'), ((1932, 1981), 'scipy.linalg.solve', 'linalg.solve', (['K', 'self._y_train[tri]'], {'sym_pos': '(True)'}), '(K, self._y_train[tri], sym_pos=True)\n', (1944, 1981), True, 'import scipy.linalg as linalg\n'), ((2096, 2131), 'scipy.linalg.lstsq', 'linalg.lstsq', (['K', 'self._y_train[tri]'], {}), '(K, self._y_train[tri])\n', (2108, 2131), True, 'import scipy.linalg as linalg\n'), ((2341, 2357), 'numpy.dot', 'np.dot', (['K', 'nodes'], {}), '(K, nodes)\n', (2347, 2357), True, 'import numpy as np\n'), ((482, 509), 'numpy.exp', 'np.exp', (['(-(1.0 / s * x) ** 2)'], {}), '(-(1.0 / s * x) ** 2)\n', (488, 509), True, 'import numpy as np\n'), ((574, 605), 'numpy.sqrt', 'np.sqrt', (['((1.0 / s * x) ** 2 + 1)'], {}), '((1.0 / s * x) ** 2 + 1)\n', (581, 605), True, 'import numpy as np\n')]
from recipe_compiler.recipe import Recipe from recipe_compiler.recipe_category import RecipeCategory def test_recipe_slug(): # Given name = "<NAME>" residence = "Seattle, WA" category = RecipeCategory("dessert") recipe_name = '"Pie" Shell Script' quote = "Hello, World" ingredients = [""] instructions = [""] expected = "pie-shell-script" # When recipe = Recipe( name, residence, category, recipe_name, quote, ingredients, instructions ) # Then assert expected == recipe.slug
[ "recipe_compiler.recipe_category.RecipeCategory", "recipe_compiler.recipe.Recipe" ]
[((204, 229), 'recipe_compiler.recipe_category.RecipeCategory', 'RecipeCategory', (['"""dessert"""'], {}), "('dessert')\n", (218, 229), False, 'from recipe_compiler.recipe_category import RecipeCategory\n'), ((403, 488), 'recipe_compiler.recipe.Recipe', 'Recipe', (['name', 'residence', 'category', 'recipe_name', 'quote', 'ingredients', 'instructions'], {}), '(name, residence, category, recipe_name, quote, ingredients, instructions\n )\n', (409, 488), False, 'from recipe_compiler.recipe import Recipe\n')]
from flask_restplus import Namespace, fields class UserDataModel(object): """Represents the user data transfer object.""" api = Namespace( 'user', description='user authentication and signup resources' ) this_user = api.model('Register input data', { 'username': fields.String( required=True, description="username" ), 'first_name': fields.String( required=True, description="user's first name" ), 'last_name': fields.String( required=True, description="user's last name" ), 'national_id': fields.Integer( required=True, description="user's national ID" ), 'role': fields.String( required=True, description="user's role" ), 'date_joined': fields.String( required=True, description="Date joined timestamp" ), 'email': fields.String( required=True, description="user's email" ), 'phone_number': fields.String( required=True, description="user's last name" ), 'password': fields.String( required=True, description="<PASSWORD>" ), 'retype_password': fields.String( required=True, description="Retype password" ), 'officer_username': fields.String( required=False, description="Enter officer name" ), 'location': fields.String( required=False, description="Enter location" ), 'officer_info': fields.String( required=False, description="Add officer information" ), 'farmer_info': fields.String( required=False, description="Add farmer information" ), }) login_user = api.model('Login input data', { 'password': fields.String( required=True, description="Add your password" ), 'username': fields.String( required=False, description="Add your username" ), 'email': fields.String( required=False, description="Add you email" ) })
[ "flask_restplus.fields.String", "flask_restplus.Namespace", "flask_restplus.fields.Integer" ]
[((138, 211), 'flask_restplus.Namespace', 'Namespace', (['"""user"""'], {'description': '"""user authentication and signup resources"""'}), "('user', description='user authentication and signup resources')\n", (147, 211), False, 'from flask_restplus import Namespace, fields\n'), ((297, 349), 'flask_restplus.fields.String', 'fields.String', ([], {'required': '(True)', 'description': '"""username"""'}), "(required=True, description='username')\n", (310, 349), False, 'from flask_restplus import Namespace, fields\n'), ((395, 456), 'flask_restplus.fields.String', 'fields.String', ([], {'required': '(True)', 'description': '"""user\'s first name"""'}), '(required=True, description="user\'s first name")\n', (408, 456), False, 'from flask_restplus import Namespace, fields\n'), ((501, 561), 'flask_restplus.fields.String', 'fields.String', ([], {'required': '(True)', 'description': '"""user\'s last name"""'}), '(required=True, description="user\'s last name")\n', (514, 561), False, 'from flask_restplus import Namespace, fields\n'), ((608, 671), 'flask_restplus.fields.Integer', 'fields.Integer', ([], {'required': '(True)', 'description': '"""user\'s national ID"""'}), '(required=True, description="user\'s national ID")\n', (622, 671), False, 'from flask_restplus import Namespace, fields\n'), ((711, 766), 'flask_restplus.fields.String', 'fields.String', ([], {'required': '(True)', 'description': '"""user\'s role"""'}), '(required=True, description="user\'s role")\n', (724, 766), False, 'from flask_restplus import Namespace, fields\n'), ((813, 878), 'flask_restplus.fields.String', 'fields.String', ([], {'required': '(True)', 'description': '"""Date joined timestamp"""'}), "(required=True, description='Date joined timestamp')\n", (826, 878), False, 'from flask_restplus import Namespace, fields\n'), ((919, 975), 'flask_restplus.fields.String', 'fields.String', ([], {'required': '(True)', 'description': '"""user\'s email"""'}), '(required=True, description="user\'s email")\n', (932, 975), False, 'from flask_restplus import Namespace, fields\n'), ((1023, 1083), 'flask_restplus.fields.String', 'fields.String', ([], {'required': '(True)', 'description': '"""user\'s last name"""'}), '(required=True, description="user\'s last name")\n', (1036, 1083), False, 'from flask_restplus import Namespace, fields\n'), ((1127, 1181), 'flask_restplus.fields.String', 'fields.String', ([], {'required': '(True)', 'description': '"""<PASSWORD>"""'}), "(required=True, description='<PASSWORD>')\n", (1140, 1181), False, 'from flask_restplus import Namespace, fields\n'), ((1232, 1291), 'flask_restplus.fields.String', 'fields.String', ([], {'required': '(True)', 'description': '"""Retype password"""'}), "(required=True, description='Retype password')\n", (1245, 1291), False, 'from flask_restplus import Namespace, fields\n'), ((1343, 1406), 'flask_restplus.fields.String', 'fields.String', ([], {'required': '(False)', 'description': '"""Enter officer name"""'}), "(required=False, description='Enter officer name')\n", (1356, 1406), False, 'from flask_restplus import Namespace, fields\n'), ((1450, 1509), 'flask_restplus.fields.String', 'fields.String', ([], {'required': '(False)', 'description': '"""Enter location"""'}), "(required=False, description='Enter location')\n", (1463, 1509), False, 'from flask_restplus import Namespace, fields\n'), ((1557, 1625), 'flask_restplus.fields.String', 'fields.String', ([], {'required': '(False)', 'description': '"""Add officer information"""'}), "(required=False, description='Add officer information')\n", (1570, 1625), False, 'from flask_restplus import Namespace, fields\n'), ((1672, 1739), 'flask_restplus.fields.String', 'fields.String', ([], {'required': '(False)', 'description': '"""Add farmer information"""'}), "(required=False, description='Add farmer information')\n", (1685, 1739), False, 'from flask_restplus import Namespace, fields\n'), ((1839, 1900), 'flask_restplus.fields.String', 'fields.String', ([], {'required': '(True)', 'description': '"""Add your password"""'}), "(required=True, description='Add your password')\n", (1852, 1900), False, 'from flask_restplus import Namespace, fields\n'), ((1944, 2006), 'flask_restplus.fields.String', 'fields.String', ([], {'required': '(False)', 'description': '"""Add your username"""'}), "(required=False, description='Add your username')\n", (1957, 2006), False, 'from flask_restplus import Namespace, fields\n'), ((2047, 2105), 'flask_restplus.fields.String', 'fields.String', ([], {'required': '(False)', 'description': '"""Add you email"""'}), "(required=False, description='Add you email')\n", (2060, 2105), False, 'from flask_restplus import Namespace, fields\n')]
""" The script declares functions used in 'data_analysis.py' """ import os import yaml from logzero import logger import matplotlib.pyplot as plt import seaborn as sns from matplotlib.patches import Patch import plotly.graph_objects as go from utility import parse_config config_path = "config/config.yaml" config = parse_config(config_path) # read config file def dataset_balance(df_clean, col): fig, ax = plt.subplots() sns.countplot(x = col, data = df_clean, palette = 'viridis') plt.title('Deposit Distribution of Bank Customers', fontsize = 16) plt.xlabel('Deposit', fontsize = 14) plt.ylabel('Total Customers', fontsize = 14) plt.xticks(fontsize = 12) plt.savefig("dataset_balance.png") def box_plot(df_clean, col, plot_type): fig, ax = plt.subplots(1, 2, figsize=(15, 5)) fig.suptitle(config["data_analysis"][plot_type]["title"], size = 18, y=1.08) # Subplot 1 ax[0].hist(df_clean[df_clean["deposit"]=='no'][col], bins=30, alpha=0.5, color="green", label="Non-Depositors") ax[0].hist(df_clean[df_clean["deposit"]=='yes'][col], bins=30, alpha=0.5, color="blue", label="Depositors") ax[0].set_xlabel(config["data_analysis"][plot_type]["xlabel"], size = 14) ax[0].set_ylabel(config["data_analysis"][plot_type]["ylabel"], size = 14) ax[0].legend(fontsize = 11); # Subplot 2 sns.boxplot(x=col, y="deposit", data=df_clean, orient="h", palette={ 'no':"#80e880", 'yes':"#2626ff"}, ax = ax[1]) ax[1].get_yaxis().set_visible(False) ax[1].set_xlabel(config["data_analysis"][plot_type]["xlabel"], size = 14) color_patches = [ Patch(facecolor="#80e880", label="Non-Depositors"), Patch(facecolor="#2626ff", label="Depositors") ] ax[1].legend(handles=color_patches, fontsize=11); plt.savefig(plot_type) # saving figure def grouped_bar_plot(df_clean, col, plot_type): fig, ax = plt.subplots() sns.catplot(col, hue = 'deposit', data=df_clean, kind="count", palette={'no':"#80e880", 'yes':"#2626ff"}, legend = False) color_patches = [ Patch(facecolor="#80e880", label="Non-Depositors"), Patch(facecolor="#2626ff", label="Depositors") ] plt.title(config["data_analysis"][plot_type]["title"], size = 18, y=1.08) plt.xlabel(config["data_analysis"][plot_type]["xlabel"], size = 14) plt.ylabel(config["data_analysis"][plot_type]["ylabel"], size = 14) plt.xticks(size = 12, rotation = 'vertical') plt.legend(handles = color_patches, fontsize = 12, bbox_to_anchor=(1.4,1.05)) plt.savefig(plot_type) # saving figure plt.close(1)
[ "matplotlib.pyplot.savefig", "matplotlib.pyplot.xticks", "matplotlib.pyplot.ylabel", "matplotlib.pyplot.xlabel", "seaborn.catplot", "seaborn.boxplot", "matplotlib.pyplot.close", "utility.parse_config", "matplotlib.patches.Patch", "seaborn.countplot", "matplotlib.pyplot.title", "matplotlib.pypl...
[((326, 351), 'utility.parse_config', 'parse_config', (['config_path'], {}), '(config_path)\n', (338, 351), False, 'from utility import parse_config\n'), ((425, 439), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {}), '()\n', (437, 439), True, 'import matplotlib.pyplot as plt\n'), ((444, 498), 'seaborn.countplot', 'sns.countplot', ([], {'x': 'col', 'data': 'df_clean', 'palette': '"""viridis"""'}), "(x=col, data=df_clean, palette='viridis')\n", (457, 498), True, 'import seaborn as sns\n'), ((514, 578), 'matplotlib.pyplot.title', 'plt.title', (['"""Deposit Distribution of Bank Customers"""'], {'fontsize': '(16)'}), "('Deposit Distribution of Bank Customers', fontsize=16)\n", (523, 578), True, 'import matplotlib.pyplot as plt\n'), ((585, 619), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Deposit"""'], {'fontsize': '(14)'}), "('Deposit', fontsize=14)\n", (595, 619), True, 'import matplotlib.pyplot as plt\n'), ((626, 668), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Total Customers"""'], {'fontsize': '(14)'}), "('Total Customers', fontsize=14)\n", (636, 668), True, 'import matplotlib.pyplot as plt\n'), ((675, 698), 'matplotlib.pyplot.xticks', 'plt.xticks', ([], {'fontsize': '(12)'}), '(fontsize=12)\n', (685, 698), True, 'import matplotlib.pyplot as plt\n'), ((705, 739), 'matplotlib.pyplot.savefig', 'plt.savefig', (['"""dataset_balance.png"""'], {}), "('dataset_balance.png')\n", (716, 739), True, 'import matplotlib.pyplot as plt\n'), ((800, 835), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(1)', '(2)'], {'figsize': '(15, 5)'}), '(1, 2, figsize=(15, 5))\n', (812, 835), True, 'import matplotlib.pyplot as plt\n'), ((1385, 1502), 'seaborn.boxplot', 'sns.boxplot', ([], {'x': 'col', 'y': '"""deposit"""', 'data': 'df_clean', 'orient': '"""h"""', 'palette': "{'no': '#80e880', 'yes': '#2626ff'}", 'ax': 'ax[1]'}), "(x=col, y='deposit', data=df_clean, orient='h', palette={'no':\n '#80e880', 'yes': '#2626ff'}, ax=ax[1])\n", (1396, 1502), True, 'import seaborn as sns\n'), ((1828, 1850), 'matplotlib.pyplot.savefig', 'plt.savefig', (['plot_type'], {}), '(plot_type)\n', (1839, 1850), True, 'import matplotlib.pyplot as plt\n'), ((1941, 1955), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {}), '()\n', (1953, 1955), True, 'import matplotlib.pyplot as plt\n'), ((1961, 2084), 'seaborn.catplot', 'sns.catplot', (['col'], {'hue': '"""deposit"""', 'data': 'df_clean', 'kind': '"""count"""', 'palette': "{'no': '#80e880', 'yes': '#2626ff'}", 'legend': '(False)'}), "(col, hue='deposit', data=df_clean, kind='count', palette={'no':\n '#80e880', 'yes': '#2626ff'}, legend=False)\n", (1972, 2084), True, 'import seaborn as sns\n'), ((2240, 2311), 'matplotlib.pyplot.title', 'plt.title', (["config['data_analysis'][plot_type]['title']"], {'size': '(18)', 'y': '(1.08)'}), "(config['data_analysis'][plot_type]['title'], size=18, y=1.08)\n", (2249, 2311), True, 'import matplotlib.pyplot as plt\n'), ((2319, 2384), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (["config['data_analysis'][plot_type]['xlabel']"], {'size': '(14)'}), "(config['data_analysis'][plot_type]['xlabel'], size=14)\n", (2329, 2384), True, 'import matplotlib.pyplot as plt\n'), ((2391, 2456), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (["config['data_analysis'][plot_type]['ylabel']"], {'size': '(14)'}), "(config['data_analysis'][plot_type]['ylabel'], size=14)\n", (2401, 2456), True, 'import matplotlib.pyplot as plt\n'), ((2463, 2503), 'matplotlib.pyplot.xticks', 'plt.xticks', ([], {'size': '(12)', 'rotation': '"""vertical"""'}), "(size=12, rotation='vertical')\n", (2473, 2503), True, 'import matplotlib.pyplot as plt\n'), ((2512, 2586), 'matplotlib.pyplot.legend', 'plt.legend', ([], {'handles': 'color_patches', 'fontsize': '(12)', 'bbox_to_anchor': '(1.4, 1.05)'}), '(handles=color_patches, fontsize=12, bbox_to_anchor=(1.4, 1.05))\n', (2522, 2586), True, 'import matplotlib.pyplot as plt\n'), ((2600, 2622), 'matplotlib.pyplot.savefig', 'plt.savefig', (['plot_type'], {}), '(plot_type)\n', (2611, 2622), True, 'import matplotlib.pyplot as plt\n'), ((2644, 2656), 'matplotlib.pyplot.close', 'plt.close', (['(1)'], {}), '(1)\n', (2653, 2656), True, 'import matplotlib.pyplot as plt\n'), ((1654, 1704), 'matplotlib.patches.Patch', 'Patch', ([], {'facecolor': '"""#80e880"""', 'label': '"""Non-Depositors"""'}), "(facecolor='#80e880', label='Non-Depositors')\n", (1659, 1704), False, 'from matplotlib.patches import Patch\n'), ((1714, 1760), 'matplotlib.patches.Patch', 'Patch', ([], {'facecolor': '"""#2626ff"""', 'label': '"""Depositors"""'}), "(facecolor='#2626ff', label='Depositors')\n", (1719, 1760), False, 'from matplotlib.patches import Patch\n'), ((2118, 2168), 'matplotlib.patches.Patch', 'Patch', ([], {'facecolor': '"""#80e880"""', 'label': '"""Non-Depositors"""'}), "(facecolor='#80e880', label='Non-Depositors')\n", (2123, 2168), False, 'from matplotlib.patches import Patch\n'), ((2178, 2224), 'matplotlib.patches.Patch', 'Patch', ([], {'facecolor': '"""#2626ff"""', 'label': '"""Depositors"""'}), "(facecolor='#2626ff', label='Depositors')\n", (2183, 2224), False, 'from matplotlib.patches import Patch\n')]
#!/usr/bin/env python3 import isce from isceobj.Sensor import createSensor import shelve import argparse import os from isceobj.Util import Poly1D from isceobj.Planet.AstronomicalHandbook import Const from mroipac.dopiq.DopIQ import DopIQ import copy def cmdLineParse(): ''' Command line parser. ''' parser = argparse.ArgumentParser(description='Unpack RISAT raw data and store metadata in pickle file.') parser.add_argument('-i','--input', dest='indir', type=str, required=True, help='Input CSK frame') parser.add_argument('-o', '--output', dest='slc', type=str, required=True, help='Output SLC file') parser.add_argument('-p', '--polar', dest='polar', type=str, default='RH', help='Polarization to extract') return parser.parse_args() def unpack(hdf5, slcname, polar='RH'): ''' Unpack HDF5 to binary SLC file. ''' obj = createSensor('RISAT1') obj._imageFile = os.path.join(hdf5, 'scene_'+polar, 'dat_01.001') obj._leaderFile = os.path.join(hdf5, 'scene_'+polar,'lea_01.001') if not os.path.isdir(slcname): os.mkdir(slcname) date = os.path.basename(slcname) obj.output = os.path.join(slcname, date + '.raw') obj.extractImage() obj.frame.getImage().renderHdr() #####Estimate doppler dop = DopIQ() dop.configure() img = copy.deepcopy(obj.frame.getImage()) img.setAccessMode('READ') dop.wireInputPort('frame', object=obj.frame) dop.wireInputPort('instrument', object=obj.frame.instrument) dop.wireInputPort('image', object=img) dop.calculateDoppler() dop.fitDoppler() fit = dop.quadratic coef = [fit['a'], fit['b'], fit['c']] print(coef) obj.frame._dopplerVsPixel = [x*obj.frame.PRF for x in coef] pickName = os.path.join(slcname, 'raw') with shelve.open(pickName) as db: db['frame'] = obj.frame if __name__ == '__main__': ''' Main driver. ''' inps = cmdLineParse() unpack(inps.indir, inps.slc, polar=inps.polar)
[ "mroipac.dopiq.DopIQ.DopIQ", "argparse.ArgumentParser", "os.path.join", "os.path.isdir", "shelve.open", "os.path.basename", "os.mkdir", "isceobj.Sensor.createSensor" ]
[((329, 429), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""Unpack RISAT raw data and store metadata in pickle file."""'}), "(description=\n 'Unpack RISAT raw data and store metadata in pickle file.')\n", (352, 429), False, 'import argparse\n'), ((914, 936), 'isceobj.Sensor.createSensor', 'createSensor', (['"""RISAT1"""'], {}), "('RISAT1')\n", (926, 936), False, 'from isceobj.Sensor import createSensor\n'), ((958, 1008), 'os.path.join', 'os.path.join', (['hdf5', "('scene_' + polar)", '"""dat_01.001"""'], {}), "(hdf5, 'scene_' + polar, 'dat_01.001')\n", (970, 1008), False, 'import os\n'), ((1029, 1079), 'os.path.join', 'os.path.join', (['hdf5', "('scene_' + polar)", '"""lea_01.001"""'], {}), "(hdf5, 'scene_' + polar, 'lea_01.001')\n", (1041, 1079), False, 'import os\n'), ((1150, 1175), 'os.path.basename', 'os.path.basename', (['slcname'], {}), '(slcname)\n', (1166, 1175), False, 'import os\n'), ((1193, 1229), 'os.path.join', 'os.path.join', (['slcname', "(date + '.raw')"], {}), "(slcname, date + '.raw')\n", (1205, 1229), False, 'import os\n'), ((1329, 1336), 'mroipac.dopiq.DopIQ.DopIQ', 'DopIQ', ([], {}), '()\n', (1334, 1336), False, 'from mroipac.dopiq.DopIQ import DopIQ\n'), ((1803, 1831), 'os.path.join', 'os.path.join', (['slcname', '"""raw"""'], {}), "(slcname, 'raw')\n", (1815, 1831), False, 'import os\n'), ((1088, 1110), 'os.path.isdir', 'os.path.isdir', (['slcname'], {}), '(slcname)\n', (1101, 1110), False, 'import os\n'), ((1120, 1137), 'os.mkdir', 'os.mkdir', (['slcname'], {}), '(slcname)\n', (1128, 1137), False, 'import os\n'), ((1841, 1862), 'shelve.open', 'shelve.open', (['pickName'], {}), '(pickName)\n', (1852, 1862), False, 'import shelve\n')]
"""Tests for qr.py.""" from jax import lax import jax.numpy as jnp import numpy as np import pytest import tempfile from distla_core.linalg.utils import testutils from distla_core.linalg.qr import qr_ooc from distla_core.utils import pops DTYPE = jnp.float32 seeds = [0, 1] flags = [True, False] def _dephase_qr(R, Q=None): """ Maps the Q and R factor from an arbitrary QR decomposition to the unique with non-negative diagonal entries. """ phases_data = np.sign(np.diagonal(R)) m, n = R.shape if m > n: phases = np.ones(m) phases[:n] = phases_data else: phases = phases_data R = phases.conj()[:, None] * R if Q is not None: Q = Q * phases return Q, R @pytest.mark.parametrize("N", [8, 32, 128]) @pytest.mark.parametrize("aspect_ratio", [1, 2, 10]) @pytest.mark.parametrize("panel_size", [1, 2]) @pytest.mark.parametrize("seed", [0, 1]) def test_qr_ooc(N, aspect_ratio, panel_size, seed): dtype = np.float32 M = N * aspect_ratio np.random.seed(seed) A = np.random.randn(M, N).astype(dtype) _, expected = np.linalg.qr(A) _, expected = _dephase_qr(expected) with tempfile.NamedTemporaryFile(delete=False) as f: np.save(f, A) f.close() # Explicit close needed to open again as a memmap. # The file is still deleted when the context goes out of scope. result = qr_ooc.qr_ooc(f.name, caqr_panel_size=panel_size) result = pops.undistribute(result) _, result = _dephase_qr(result) atol = testutils.eps(lax.Precision.HIGHEST, dtype=dtype) atol *= np.linalg.norm(A) ** 2 testutils.assert_allclose(result, expected, atol=atol) @pytest.mark.parametrize("N", [8, 32, 128]) @pytest.mark.parametrize("aspect_ratio", [1, 2, 10]) @pytest.mark.parametrize("panel_size", [1, 2]) @pytest.mark.parametrize("seed", [0, 1]) def test_fake_cholesky(N, aspect_ratio, panel_size, seed): fname = "fake_cholesky_test_matrix" dtype = np.float32 M = N * aspect_ratio np.random.seed(seed) A = np.random.randn(M, N).astype(dtype) cond = np.linalg.cond(A) expected_gram = np.dot(A.T, A) expected_chol = np.linalg.cholesky(expected_gram).T _, expected_chol = _dephase_qr(expected_chol) np.save(fname, A) fread = fname + ".npy" chol_fname = "cholesky_transpose" gram_fname = "gram_matrix" qr_ooc.fake_cholesky(fread, caqr_panel_size=panel_size, chol_fname=chol_fname, gram_fname=gram_fname) result_gram = np.load(gram_fname + ".npy") result_chol = np.load(chol_fname + ".npy") _, result_chol = _dephase_qr(result_chol) atol = testutils.eps(lax.Precision.HIGHEST, dtype=dtype) atol *= cond * np.linalg.norm(expected_gram) ** 2 testutils.assert_allclose(result_chol, expected_chol, atol=10 * atol) testutils.assert_allclose(result_gram, expected_gram, atol=atol)
[ "distla_core.linalg.utils.testutils.eps", "distla_core.linalg.utils.testutils.assert_allclose", "numpy.diagonal", "numpy.linalg.qr", "numpy.ones", "distla_core.linalg.qr.qr_ooc.qr_ooc", "numpy.linalg.cond", "numpy.linalg.norm", "pytest.mark.parametrize", "distla_core.utils.pops.undistribute", "n...
[((697, 739), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""N"""', '[8, 32, 128]'], {}), "('N', [8, 32, 128])\n", (720, 739), False, 'import pytest\n'), ((741, 792), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""aspect_ratio"""', '[1, 2, 10]'], {}), "('aspect_ratio', [1, 2, 10])\n", (764, 792), False, 'import pytest\n'), ((794, 839), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""panel_size"""', '[1, 2]'], {}), "('panel_size', [1, 2])\n", (817, 839), False, 'import pytest\n'), ((841, 880), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""seed"""', '[0, 1]'], {}), "('seed', [0, 1])\n", (864, 880), False, 'import pytest\n'), ((1618, 1660), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""N"""', '[8, 32, 128]'], {}), "('N', [8, 32, 128])\n", (1641, 1660), False, 'import pytest\n'), ((1662, 1713), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""aspect_ratio"""', '[1, 2, 10]'], {}), "('aspect_ratio', [1, 2, 10])\n", (1685, 1713), False, 'import pytest\n'), ((1715, 1760), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""panel_size"""', '[1, 2]'], {}), "('panel_size', [1, 2])\n", (1738, 1760), False, 'import pytest\n'), ((1762, 1801), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""seed"""', '[0, 1]'], {}), "('seed', [0, 1])\n", (1785, 1801), False, 'import pytest\n'), ((979, 999), 'numpy.random.seed', 'np.random.seed', (['seed'], {}), '(seed)\n', (993, 999), True, 'import numpy as np\n'), ((1058, 1073), 'numpy.linalg.qr', 'np.linalg.qr', (['A'], {}), '(A)\n', (1070, 1073), True, 'import numpy as np\n'), ((1404, 1429), 'distla_core.utils.pops.undistribute', 'pops.undistribute', (['result'], {}), '(result)\n', (1421, 1429), False, 'from distla_core.utils import pops\n'), ((1474, 1523), 'distla_core.linalg.utils.testutils.eps', 'testutils.eps', (['lax.Precision.HIGHEST'], {'dtype': 'dtype'}), '(lax.Precision.HIGHEST, dtype=dtype)\n', (1487, 1523), False, 'from distla_core.linalg.utils import testutils\n'), ((1560, 1614), 'distla_core.linalg.utils.testutils.assert_allclose', 'testutils.assert_allclose', (['result', 'expected'], {'atol': 'atol'}), '(result, expected, atol=atol)\n', (1585, 1614), False, 'from distla_core.linalg.utils import testutils\n'), ((1945, 1965), 'numpy.random.seed', 'np.random.seed', (['seed'], {}), '(seed)\n', (1959, 1965), True, 'import numpy as np\n'), ((2017, 2034), 'numpy.linalg.cond', 'np.linalg.cond', (['A'], {}), '(A)\n', (2031, 2034), True, 'import numpy as np\n'), ((2053, 2067), 'numpy.dot', 'np.dot', (['A.T', 'A'], {}), '(A.T, A)\n', (2059, 2067), True, 'import numpy as np\n'), ((2173, 2190), 'numpy.save', 'np.save', (['fname', 'A'], {}), '(fname, A)\n', (2180, 2190), True, 'import numpy as np\n'), ((2284, 2390), 'distla_core.linalg.qr.qr_ooc.fake_cholesky', 'qr_ooc.fake_cholesky', (['fread'], {'caqr_panel_size': 'panel_size', 'chol_fname': 'chol_fname', 'gram_fname': 'gram_fname'}), '(fread, caqr_panel_size=panel_size, chol_fname=\n chol_fname, gram_fname=gram_fname)\n', (2304, 2390), False, 'from distla_core.linalg.qr import qr_ooc\n'), ((2425, 2453), 'numpy.load', 'np.load', (["(gram_fname + '.npy')"], {}), "(gram_fname + '.npy')\n", (2432, 2453), True, 'import numpy as np\n'), ((2470, 2498), 'numpy.load', 'np.load', (["(chol_fname + '.npy')"], {}), "(chol_fname + '.npy')\n", (2477, 2498), True, 'import numpy as np\n'), ((2553, 2602), 'distla_core.linalg.utils.testutils.eps', 'testutils.eps', (['lax.Precision.HIGHEST'], {'dtype': 'dtype'}), '(lax.Precision.HIGHEST, dtype=dtype)\n', (2566, 2602), False, 'from distla_core.linalg.utils import testutils\n'), ((2657, 2726), 'distla_core.linalg.utils.testutils.assert_allclose', 'testutils.assert_allclose', (['result_chol', 'expected_chol'], {'atol': '(10 * atol)'}), '(result_chol, expected_chol, atol=10 * atol)\n', (2682, 2726), False, 'from distla_core.linalg.utils import testutils\n'), ((2729, 2793), 'distla_core.linalg.utils.testutils.assert_allclose', 'testutils.assert_allclose', (['result_gram', 'expected_gram'], {'atol': 'atol'}), '(result_gram, expected_gram, atol=atol)\n', (2754, 2793), False, 'from distla_core.linalg.utils import testutils\n'), ((477, 491), 'numpy.diagonal', 'np.diagonal', (['R'], {}), '(R)\n', (488, 491), True, 'import numpy as np\n'), ((535, 545), 'numpy.ones', 'np.ones', (['m'], {}), '(m)\n', (542, 545), True, 'import numpy as np\n'), ((1119, 1160), 'tempfile.NamedTemporaryFile', 'tempfile.NamedTemporaryFile', ([], {'delete': '(False)'}), '(delete=False)\n', (1146, 1160), False, 'import tempfile\n'), ((1171, 1184), 'numpy.save', 'np.save', (['f', 'A'], {}), '(f, A)\n', (1178, 1184), True, 'import numpy as np\n'), ((1343, 1392), 'distla_core.linalg.qr.qr_ooc.qr_ooc', 'qr_ooc.qr_ooc', (['f.name'], {'caqr_panel_size': 'panel_size'}), '(f.name, caqr_panel_size=panel_size)\n', (1356, 1392), False, 'from distla_core.linalg.qr import qr_ooc\n'), ((1534, 1551), 'numpy.linalg.norm', 'np.linalg.norm', (['A'], {}), '(A)\n', (1548, 1551), True, 'import numpy as np\n'), ((2086, 2119), 'numpy.linalg.cholesky', 'np.linalg.cholesky', (['expected_gram'], {}), '(expected_gram)\n', (2104, 2119), True, 'import numpy as np\n'), ((1006, 1027), 'numpy.random.randn', 'np.random.randn', (['M', 'N'], {}), '(M, N)\n', (1021, 1027), True, 'import numpy as np\n'), ((1972, 1993), 'numpy.random.randn', 'np.random.randn', (['M', 'N'], {}), '(M, N)\n', (1987, 1993), True, 'import numpy as np\n'), ((2620, 2649), 'numpy.linalg.norm', 'np.linalg.norm', (['expected_gram'], {}), '(expected_gram)\n', (2634, 2649), True, 'import numpy as np\n')]
import wpilib import constants import swerve import lift import winch import sys from teleop import Teleop from autonomous.baseline_simple import Autonomous from sensors.imu import IMU def log(src, msg): try: full_msg = "[{:.3f}] [{}] {}".format( wpilib.Timer.getMatchTime(), str(src), str(msg) ) print(full_msg, file=sys.stderr) except: # noqa: E772 full_msg = "[{:.3f}] [log] Caught exception when logging: {} {}".format( # noqa: E501 wpilib.Timer.getMatchTime(), str(sys.exc_info()[0]), str(sys.exc_info()[1]) ) print(full_msg, file=sys.stderr) def log_exception(src, locstr): # i.e. caught {ValueError} {in my_method}: {could not cast X to Y} log(src, "Caught {} {}: {}".format( str(sys.exc_info()[0]), locstr, str(sys.exc_info()[1]) )) class Robot(wpilib.IterativeRobot): def robotInit(self): constants.load_control_config() wpilib.CameraServer.launch('driver_vision.py:main') self.autoPositionSelect = wpilib.SendableChooser() self.autoPositionSelect.addDefault('Middle-Baseline', 'Middle-Baseline') self.autoPositionSelect.addObject('Middle-Placement', 'Middle-Placement') # noqa: E501 self.autoPositionSelect.addObject('Left', 'Left') self.autoPositionSelect.addObject('Right', 'Right') wpilib.SmartDashboard.putData( 'Robot Starting Position', self.autoPositionSelect) self.drivetrain = swerve.SwerveDrive( constants.chassis_length, constants.chassis_width, constants.swerve_config ) self.drivetrain.load_config_values() self.lift = lift.ManualControlLift( constants.lift_ids['left'], constants.lift_ids['right'], constants.lift_limit_channel, constants.start_limit_channel ) self.winch = winch.Winch( constants.winch_id ) self.throttle = wpilib.Joystick(1) self.claw = lift.Claw( constants.claw_id, constants.claw_follower_id ) self.imu = IMU(wpilib.SPI.Port.kMXP) self.sd_update_timer = wpilib.Timer() self.sd_update_timer.reset() self.sd_update_timer.start() def disabledInit(self): pass def disabledPeriodic(self): try: self.lift.load_config_values() self.drivetrain.load_config_values() except: # noqa: E772 log_exception('disabled', 'when loading config') try: self.drivetrain.update_smart_dashboard() self.imu.update_smart_dashboard() self.lift.update_smart_dashboard() self.winch.update_smart_dashboard() wpilib.SmartDashboard.putNumber( "Throttle Pos", self.throttle.getRawAxis(constants.liftAxis) ) except: # noqa: E772 log_exception('disabled', 'when updating SmartDashboard') try: self.lift.checkLimitSwitch() pass except: # noqa: E772 log_exception('disabled', 'when checking lift limit switch') self.drivetrain.update_smart_dashboard() def autonomousInit(self): try: self.drivetrain.load_config_values() self.lift.load_config_values() except: # noqa: E772 log_exception('auto-init', 'when loading config') self.autoPos = None try: self.autoPos = self.autoPositionSelect.getSelected() except: # noqa: E772 self.autoPos = None log_exception('auto-init', 'when getting robot start position') try: if self.autoPos is not None and self.autoPos != 'None': self.auto = Autonomous(self, self.autoPos) else: log('auto-init', 'Disabling autonomous...') except: # noqa: E772 log_exception('auto-init', 'in Autonomous constructor') try: self.lift.checkLimitSwitch() pass except: # noqa: E772 log_exception('auto-init', 'when checking lift limit switch') def autonomousPeriodic(self): try: if self.sd_update_timer.hasPeriodPassed(0.5): self.auto.update_smart_dashboard() self.imu.update_smart_dashboard() self.drivetrain.update_smart_dashboard() self.lift.update_smart_dashboard() self.winch.update_smart_dashboard() except: # noqa: E772 log_exception('auto', 'when updating SmartDashboard') try: if self.autoPos is not None and self.autoPos != 'None': self.auto.periodic() except: # noqa: E772 # Stop everything. self.drivetrain.immediate_stop() self.lift.setLiftPower(0) self.claw.set_power(0) self.winch.stop() log_exception('auto', 'in auto :periodic()') try: self.lift.checkLimitSwitch() pass except: # noqa: E772 log_exception('auto', 'when checking lift limit switch') def teleopInit(self): try: self.teleop = Teleop(self) except: # noqa: E772 log_exception('teleop-init', 'in Teleop constructor') try: self.drivetrain.load_config_values() self.lift.load_config_values() constants.load_control_config() except: # noqa: E772 log_exception('teleop-init', 'when loading config') try: self.lift.checkLimitSwitch() pass except: # noqa: E772 log_exception('teleop-init', 'when checking lift limit switch') def teleopPeriodic(self): try: self.teleop.drive() except: # noqa: E772 log_exception('teleop', 'in drive control') self.drivetrain.immediate_stop() try: self.teleop.buttons() except: # noqa: E772 log_exception('teleop', 'in button handler') try: self.teleop.lift_control() except: # noqa: E772 log_exception('teleop', 'in lift_control') self.lift.setLiftPower(0) try: self.teleop.claw_control() except: # noqa: E772 log_exception('teleop', 'in claw_control') self.claw.set_power(0) try: self.teleop.winch_control() except: # noqa: E772 log_exception('teleop', 'in winch_control') self.winch.stop() try: self.lift.checkLimitSwitch() pass except: # noqa: E772 log_exception('teleop', 'in lift.checkLimitSwitch') if self.sd_update_timer.hasPeriodPassed(0.5): try: constants.load_control_config() self.drivetrain.load_config_values() self.lift.load_config_values() except: # noqa: E772 log_exception('teleop', 'when loading config') try: self.drivetrain.update_smart_dashboard() self.teleop.update_smart_dashboard() self.imu.update_smart_dashboard() self.lift.update_smart_dashboard() self.winch.update_smart_dashboard() except: # noqa: E772 log_exception('teleop', 'when updating SmartDashboard') # for module in self.drivetrain.modules: # module.set_steer_angle(0) if __name__ == "__main__": wpilib.run(Robot)
[ "autonomous.baseline_simple.Autonomous", "wpilib.Timer", "swerve.SwerveDrive", "lift.ManualControlLift", "teleop.Teleop", "wpilib.Timer.getMatchTime", "wpilib.run", "wpilib.Joystick", "sensors.imu.IMU", "sys.exc_info", "wpilib.SendableChooser", "wpilib.CameraServer.launch", "wpilib.SmartDash...
[((7717, 7734), 'wpilib.run', 'wpilib.run', (['Robot'], {}), '(Robot)\n', (7727, 7734), False, 'import wpilib\n'), ((944, 975), 'constants.load_control_config', 'constants.load_control_config', ([], {}), '()\n', (973, 975), False, 'import constants\n'), ((985, 1036), 'wpilib.CameraServer.launch', 'wpilib.CameraServer.launch', (['"""driver_vision.py:main"""'], {}), "('driver_vision.py:main')\n", (1011, 1036), False, 'import wpilib\n'), ((1072, 1096), 'wpilib.SendableChooser', 'wpilib.SendableChooser', ([], {}), '()\n', (1094, 1096), False, 'import wpilib\n'), ((1401, 1487), 'wpilib.SmartDashboard.putData', 'wpilib.SmartDashboard.putData', (['"""Robot Starting Position"""', 'self.autoPositionSelect'], {}), "('Robot Starting Position', self.\n autoPositionSelect)\n", (1430, 1487), False, 'import wpilib\n'), ((1535, 1633), 'swerve.SwerveDrive', 'swerve.SwerveDrive', (['constants.chassis_length', 'constants.chassis_width', 'constants.swerve_config'], {}), '(constants.chassis_length, constants.chassis_width,\n constants.swerve_config)\n', (1553, 1633), False, 'import swerve\n'), ((1742, 1887), 'lift.ManualControlLift', 'lift.ManualControlLift', (["constants.lift_ids['left']", "constants.lift_ids['right']", 'constants.lift_limit_channel', 'constants.start_limit_channel'], {}), "(constants.lift_ids['left'], constants.lift_ids[\n 'right'], constants.lift_limit_channel, constants.start_limit_channel)\n", (1764, 1887), False, 'import lift\n'), ((1963, 1994), 'winch.Winch', 'winch.Winch', (['constants.winch_id'], {}), '(constants.winch_id)\n', (1974, 1994), False, 'import winch\n'), ((2042, 2060), 'wpilib.Joystick', 'wpilib.Joystick', (['(1)'], {}), '(1)\n', (2057, 2060), False, 'import wpilib\n'), ((2082, 2138), 'lift.Claw', 'lift.Claw', (['constants.claw_id', 'constants.claw_follower_id'], {}), '(constants.claw_id, constants.claw_follower_id)\n', (2091, 2138), False, 'import lift\n'), ((2193, 2218), 'sensors.imu.IMU', 'IMU', (['wpilib.SPI.Port.kMXP'], {}), '(wpilib.SPI.Port.kMXP)\n', (2196, 2218), False, 'from sensors.imu import IMU\n'), ((2251, 2265), 'wpilib.Timer', 'wpilib.Timer', ([], {}), '()\n', (2263, 2265), False, 'import wpilib\n'), ((273, 300), 'wpilib.Timer.getMatchTime', 'wpilib.Timer.getMatchTime', ([], {}), '()\n', (298, 300), False, 'import wpilib\n'), ((5332, 5344), 'teleop.Teleop', 'Teleop', (['self'], {}), '(self)\n', (5338, 5344), False, 'from teleop import Teleop\n'), ((5559, 5590), 'constants.load_control_config', 'constants.load_control_config', ([], {}), '()\n', (5588, 5590), False, 'import constants\n'), ((506, 533), 'wpilib.Timer.getMatchTime', 'wpilib.Timer.getMatchTime', ([], {}), '()\n', (531, 533), False, 'import wpilib\n'), ((3864, 3894), 'autonomous.baseline_simple.Autonomous', 'Autonomous', (['self', 'self.autoPos'], {}), '(self, self.autoPos)\n', (3874, 3894), False, 'from autonomous.baseline_simple import Autonomous\n'), ((6978, 7009), 'constants.load_control_config', 'constants.load_control_config', ([], {}), '()\n', (7007, 7009), False, 'import constants\n'), ((815, 829), 'sys.exc_info', 'sys.exc_info', ([], {}), '()\n', (827, 829), False, 'import sys\n'), ((847, 861), 'sys.exc_info', 'sys.exc_info', ([], {}), '()\n', (859, 861), False, 'import sys\n'), ((551, 565), 'sys.exc_info', 'sys.exc_info', ([], {}), '()\n', (563, 565), False, 'import sys\n'), ((587, 601), 'sys.exc_info', 'sys.exc_info', ([], {}), '()\n', (599, 601), False, 'import sys\n')]
import requests text = "0123456789abcdefghijklmnopqrstuvwxyz_}" flag = "hsctf{" for _ in range(30): time = [0.1 for _ in range(38)] for _ in range(5): for i in range(38): payload = {"password": flag + text[i]} r = requests.post( "https://networked-password.web.chal.hsctf.com", data=payload ) response_time = r.elapsed.total_seconds() time[i] += response_time print(payload, " response time : ", response_time) flag += text[time.index(max(time))] print("flag is ", flag)
[ "requests.post" ]
[((259, 335), 'requests.post', 'requests.post', (['"""https://networked-password.web.chal.hsctf.com"""'], {'data': 'payload'}), "('https://networked-password.web.chal.hsctf.com', data=payload)\n", (272, 335), False, 'import requests\n')]
#!/usr/bin/env python try: from typing import Any, Dict, Union, Optional except: pass import time import string import boto3 import random import zstd import sys def rand_str(l): # type: (int) -> str return ''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(l)) def main(prefix): s3 = boto3.client('s3') with open('./eventlog.xml', 'rb') as b: body = b.readlines() body = [line for line in body] def chunker(seq, size): return [seq[pos:pos + size] for pos in range(0, len(seq), size)] for chunks in chunker(body, 50): c_body = zstd.compress(b"\n".join(chunks), 4) epoch = int(time.time()) s3.put_object( Body=c_body, Bucket="{}-sysmon-log-bucket".format(prefix), Key=str(epoch - (epoch % (24 * 60 * 60))) + "/sysmon/" + str(epoch) + rand_str(3) ) print(time.ctime()) if __name__ == '__main__': if len(sys.argv) != 2: raise Exception("Provide bucket prefix as first argument") else: main(sys.argv[1])
[ "time.ctime", "random.choice", "boto3.client", "time.time" ]
[((357, 375), 'boto3.client', 'boto3.client', (['"""s3"""'], {}), "('s3')\n", (369, 375), False, 'import boto3\n'), ((953, 965), 'time.ctime', 'time.ctime', ([], {}), '()\n', (963, 965), False, 'import time\n'), ((235, 288), 'random.choice', 'random.choice', (['(string.ascii_uppercase + string.digits)'], {}), '(string.ascii_uppercase + string.digits)\n', (248, 288), False, 'import random\n'), ((703, 714), 'time.time', 'time.time', ([], {}), '()\n', (712, 714), False, 'import time\n')]
from __future__ import absolute_import import argparse import logging import multiprocessing import os import sys import uuid from os.path import join, exists import yaml from phigaro.context import Context from phigaro.batch.runner import run_tasks_chain from phigaro.batch.task.path import sample_name from phigaro.batch.task.prodigal import ProdigalTask from phigaro.batch.task.hmmer import HmmerTask from phigaro.batch.task.dummy import DummyTask from phigaro.batch.task.preprocess import PreprocessTask from phigaro.batch.task.run_phigaro import RunPhigaroTask from phigaro._version import __version__ def parse_substitute_output(subs): subs = subs or [] res = {} for sub in subs: task_name, output = sub.split(":") res[task_name] = DummyTask(output, task_name) return res def create_task(substitutions, task_class, *args, **kwargs): # TODO: refactor to class Application task = task_class(*args, **kwargs) if task.task_name in substitutions: print( 'Substituting output for {}: {}'.format( task.task_name, substitutions[task.task_name].output() ) ) return substitutions[task.task_name] return task def clean_fold(): is_empty = True for root, dirs, files in os.walk('proc', topdown=False): for name in files: is_empty = False break if is_empty: for name in dirs: os.rmdir(os.path.join(root, name)) if is_empty: os.rmdir('proc') def main(): default_config_path = join(os.getenv('HOME'), '.phigaro', 'config.yml') parser = argparse.ArgumentParser( prog='phigaro', description='Phigaro is a scalable command-line tool for predictions phages and prophages ' 'from nucleid acid sequences', ) parser.add_argument( '-V', '--version', action='version', version='%(prog)s {version}'.format(version=__version__), ) parser.add_argument( '-f', '--fasta-file', help='Assembly scaffolds/contigs or full genomes, required', required=True, ) parser.add_argument( '-c', '--config', default=default_config_path, help='Path to the config file, not required. The deafult is %s'%default_config_path, ) parser.add_argument( '-v', '--verbose', action='store_true', help=argparse.SUPPRESS ) parser.add_argument( '-p', '--print-vogs', help='Print phage vogs for each region', action='store_true', ) parser.add_argument( '-e', '--extension', default=['html'], nargs='+', help='Type of the output: html, tsv, gff, bed or stdout. Default is html. You can specify several file formats with a space as a separator. Example: -e tsv html stdout.', ) parser.add_argument( '-o', '--output', default='', help='Output filename for html and txt outputs. Required by default, but not required for stdout only output.', ) parser.add_argument( '--not-open', help='Do not open html file automatically, if html output type is specified.', action='store_true', ) parser.add_argument( '-t', '--threads', type=int, default=multiprocessing.cpu_count(), help='Num of threads (' 'default is num of CPUs={})'.format(multiprocessing.cpu_count()), ) parser.add_argument( '--no-cleanup', action='store_true', help="Do not delete any temporary files that was generated by Phigaro (HMMER & Prodigal outputs and some others)." ) parser.add_argument( '-S', '--substitute-output', action='append', help='If you have precomputed prodigal and/or hmmer data you can provide paths to the files in the following format: program:address/to/the/file. In place of program you should write hmmer or prodigal. If you need to provide both files you should pass them separetely as two parametres.', ) parser.add_argument( '--save-fasta', action='store_true', help='Save all phage fasta sequences in a fasta file.', ) parser.add_argument( '-d', '--delete-shorts', action='store_true', help='Exclude sequences with length < 20000 automatically.', ) parser.add_argument( '-m', '--mode', default='basic', help='You can launch Phigaro at one of 3 modes: basic, abs, without_gc. Default is basic. Read more about modes at https://github.com/bobeobibo/phigaro/', ) parser.add_argument( '--wtp', action='store_true', help=argparse.SUPPRESS ) args = parser.parse_args() logging.basicConfig(level=logging.INFO if args.verbose else logging.WARN) logging.getLogger('sh.command').setLevel(logging.WARN) logger = logging.getLogger(__name__) if not exists(args.config): # TODO: pretty message print('Please, create config file using phigaro-setup script') exit(1) args.extension = [atype.lower() for atype in args.extension] for ext in args.extension: if ext not in ['html', 'gff', 'bed', 'tsv', 'stdout']: print( 'Error! The unknown output format in -e/--extensionn parameter: %s. Please, choose one or several from the list: html, gff, bed, tsv, stdout'%ext ) exit(1) if (args.output == '') and (args.extension != ['stdout']): print( 'Error! Argument -o/--output is required or change the type of the output to stdout.' ) exit(1) with open(args.config) as f: logger.info('Using config file: {}'.format(args.config)) config = yaml.load(f, Loader=yaml.FullLoader) config['phigaro']['wtp'] = args.wtp config['phigaro']['print_vogs'] = args.print_vogs config['phigaro']['filename'] = args.fasta_file config['phigaro']['no_html'] = ( True if 'html' not in args.extension else False ) config['phigaro']['not_open'] = args.not_open config['phigaro']['output'] = (args.output+'/'+os.path.splitext(os.path.basename(args.fasta_file))[0]+'.phigaro').replace('//', '/') config['phigaro']['uuid'] = uuid.uuid4().hex config['phigaro']['delete_shorts'] = args.delete_shorts config['phigaro']['gff'] = True if ('gff' in args.extension) else False config['phigaro']['bed'] = True if ('bed' in args.extension) else False config['phigaro']['mode'] = args.mode config['phigaro']['save_fasta'] = args.save_fasta filename = args.fasta_file sample = '{}-{}'.format(sample_name(filename), config['phigaro']['uuid']) if args.wtp: config['phigaro']['not_open'] = True config['phigaro']['gff'] = True config['phigaro']['bed'] = True args.extension.append('tsv') config['phigaro']['delete_shorts'] = True config['phigaro']['print_vogs'] = True config['phigaro']['output_wtp'] = args.output + '/phigaro.txt' config['phigaro']['output'] = args.output +'/phigaro/phigaro' config['phigaro']['save_fasta'] = True if config['phigaro']['output'] != '': fold = os.path.dirname(config['phigaro']['output']) if fold and not os.path.isdir(fold): os.makedirs(fold) if args.wtp: fold = os.path.dirname(config['phigaro']['output_wtp']) if fold and not os.path.isdir(fold): os.makedirs(fold) Context.initialize( sample=sample, config=config, threads=args.threads, ) substitutions = parse_substitute_output(args.substitute_output) preprocess_task = create_task(substitutions, PreprocessTask, filename) prodigal_task = create_task( substitutions, ProdigalTask, preprocess_task=preprocess_task ) hmmer_task = create_task( substitutions, HmmerTask, prodigal_task=prodigal_task ) run_phigaro_task = create_task( substitutions, RunPhigaroTask, prodigal_task=prodigal_task, hmmer_task=hmmer_task, ) tasks = [preprocess_task, prodigal_task, hmmer_task, run_phigaro_task] task_output_file = run_tasks_chain(tasks) if ('tsv' in args.extension) or ('stdout' in args.extension): with open(task_output_file) as f: f = list(f) if 'tsv' in args.extension: out_f = open(config['phigaro']['output'] + '.tsv', 'w') for line in f: out_f.write(line) if 'stdout' in args.extension: out_f = sys.stdout for line in f: out_f.write(line) out_f.close() if not args.no_cleanup: for t in tasks: t.clean() clean_fold() if __name__ == '__main__': main()
[ "logging.getLogger", "yaml.load", "multiprocessing.cpu_count", "phigaro.batch.runner.run_tasks_chain", "os.walk", "os.path.exists", "argparse.ArgumentParser", "phigaro.context.Context.initialize", "os.path.isdir", "uuid.uuid4", "os.path.dirname", "phigaro.batch.task.path.sample_name", "loggi...
[((1293, 1323), 'os.walk', 'os.walk', (['"""proc"""'], {'topdown': '(False)'}), "('proc', topdown=False)\n", (1300, 1323), False, 'import os\n'), ((1646, 1815), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'prog': '"""phigaro"""', 'description': '"""Phigaro is a scalable command-line tool for predictions phages and prophages from nucleid acid sequences"""'}), "(prog='phigaro', description=\n 'Phigaro is a scalable command-line tool for predictions phages and prophages from nucleid acid sequences'\n )\n", (1669, 1815), False, 'import argparse\n'), ((4808, 4881), 'logging.basicConfig', 'logging.basicConfig', ([], {'level': '(logging.INFO if args.verbose else logging.WARN)'}), '(level=logging.INFO if args.verbose else logging.WARN)\n', (4827, 4881), False, 'import logging\n'), ((4955, 4982), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (4972, 4982), False, 'import logging\n'), ((7579, 7649), 'phigaro.context.Context.initialize', 'Context.initialize', ([], {'sample': 'sample', 'config': 'config', 'threads': 'args.threads'}), '(sample=sample, config=config, threads=args.threads)\n', (7597, 7649), False, 'from phigaro.context import Context\n'), ((8274, 8296), 'phigaro.batch.runner.run_tasks_chain', 'run_tasks_chain', (['tasks'], {}), '(tasks)\n', (8289, 8296), False, 'from phigaro.batch.runner import run_tasks_chain\n'), ((771, 799), 'phigaro.batch.task.dummy.DummyTask', 'DummyTask', (['output', 'task_name'], {}), '(output, task_name)\n', (780, 799), False, 'from phigaro.batch.task.dummy import DummyTask\n'), ((1526, 1542), 'os.rmdir', 'os.rmdir', (['"""proc"""'], {}), "('proc')\n", (1534, 1542), False, 'import os\n'), ((1588, 1605), 'os.getenv', 'os.getenv', (['"""HOME"""'], {}), "('HOME')\n", (1597, 1605), False, 'import os\n'), ((4995, 5014), 'os.path.exists', 'exists', (['args.config'], {}), '(args.config)\n', (5001, 5014), False, 'from os.path import join, exists\n'), ((5819, 5855), 'yaml.load', 'yaml.load', (['f'], {'Loader': 'yaml.FullLoader'}), '(f, Loader=yaml.FullLoader)\n', (5828, 5855), False, 'import yaml\n'), ((6321, 6333), 'uuid.uuid4', 'uuid.uuid4', ([], {}), '()\n', (6331, 6333), False, 'import uuid\n'), ((6706, 6727), 'phigaro.batch.task.path.sample_name', 'sample_name', (['filename'], {}), '(filename)\n', (6717, 6727), False, 'from phigaro.batch.task.path import sample_name\n'), ((7280, 7324), 'os.path.dirname', 'os.path.dirname', (["config['phigaro']['output']"], {}), "(config['phigaro']['output'])\n", (7295, 7324), False, 'import os\n'), ((3364, 3391), 'multiprocessing.cpu_count', 'multiprocessing.cpu_count', ([], {}), '()\n', (3389, 3391), False, 'import multiprocessing\n'), ((4886, 4917), 'logging.getLogger', 'logging.getLogger', (['"""sh.command"""'], {}), "('sh.command')\n", (4903, 4917), False, 'import logging\n'), ((7382, 7399), 'os.makedirs', 'os.makedirs', (['fold'], {}), '(fold)\n', (7393, 7399), False, 'import os\n'), ((7440, 7488), 'os.path.dirname', 'os.path.dirname', (["config['phigaro']['output_wtp']"], {}), "(config['phigaro']['output_wtp'])\n", (7455, 7488), False, 'import os\n'), ((3469, 3496), 'multiprocessing.cpu_count', 'multiprocessing.cpu_count', ([], {}), '()\n', (3494, 3496), False, 'import multiprocessing\n'), ((7349, 7368), 'os.path.isdir', 'os.path.isdir', (['fold'], {}), '(fold)\n', (7362, 7368), False, 'import os\n'), ((7554, 7571), 'os.makedirs', 'os.makedirs', (['fold'], {}), '(fold)\n', (7565, 7571), False, 'import os\n'), ((1475, 1499), 'os.path.join', 'os.path.join', (['root', 'name'], {}), '(root, name)\n', (1487, 1499), False, 'import os\n'), ((7517, 7536), 'os.path.isdir', 'os.path.isdir', (['fold'], {}), '(fold)\n', (7530, 7536), False, 'import os\n'), ((6220, 6253), 'os.path.basename', 'os.path.basename', (['args.fasta_file'], {}), '(args.fasta_file)\n', (6236, 6253), False, 'import os\n')]
from conans import ConanFile, tools, AutoToolsBuildEnvironment from conans.errors import ConanInvalidConfiguration import os class LibmountConan(ConanFile): name = "libmount" description = "The libmount library is used to parse /etc/fstab, /etc/mtab and /proc/self/mountinfo files, manage the mtab file, evaluate mount options, etc" topics = ("conan", "mount", "libmount", "linux", "util-linux") url = "https://github.com/conan-io/conan-center-index" homepage = "https://git.kernel.org/pub/scm/utils/util-linux/util-linux.git" license = "GPL-2.0-or-later" settings = "os", "arch", "compiler", "build_type" options = {"shared": [True, False], "fPIC": [True, False]} default_options = {"shared": False, "fPIC": True} _source_subfolder = "source_subfolder" _autotools = None def configure(self): del self.settings.compiler.libcxx del self.settings.compiler.cppstd if self.settings.os != "Linux": raise ConanInvalidConfiguration("only Linux is supported") def source(self): tools.get(**self.conan_data["sources"][self.version]) extracted_dir = "util-linux-" + self.version os.rename(extracted_dir, self._source_subfolder) def _configure_autotools(self): if not self._autotools: args = ["--disable-all-programs", "--enable-libmount", "--enable-libblkid"] if self.options.shared: args.extend(["--disable-static", "--enable-shared"]) else: args.extend(["--disable-shared", "--enable-static"]) self._autotools = AutoToolsBuildEnvironment(self) self._autotools.configure(args=args) return self._autotools def build(self): with tools.chdir(self._source_subfolder): env_build = self._configure_autotools() env_build.make() def package(self): with tools.chdir(self._source_subfolder): env_build = self._configure_autotools() env_build.install() self.copy(pattern="COPYING", dst="licenses", src=self._source_subfolder) tools.rmdir(os.path.join(self.package_folder, "sbin")) tools.rmdir(os.path.join(self.package_folder, "share")) tools.rmdir(os.path.join(self.package_folder, "lib", "pkgconfig")) os.remove(os.path.join(self.package_folder, "lib", "libblkid.la")) os.remove(os.path.join(self.package_folder, "lib", "libmount.la")) def package_info(self): self.cpp_info.libs = ["mount", "blkid"] self.cpp_info.includedirs.append(os.path.join("include", "libmount"))
[ "conans.errors.ConanInvalidConfiguration", "os.rename", "os.path.join", "conans.tools.chdir", "conans.tools.get", "conans.AutoToolsBuildEnvironment" ]
[((1070, 1123), 'conans.tools.get', 'tools.get', ([], {}), "(**self.conan_data['sources'][self.version])\n", (1079, 1123), False, 'from conans import ConanFile, tools, AutoToolsBuildEnvironment\n'), ((1185, 1233), 'os.rename', 'os.rename', (['extracted_dir', 'self._source_subfolder'], {}), '(extracted_dir, self._source_subfolder)\n', (1194, 1233), False, 'import os\n'), ((986, 1038), 'conans.errors.ConanInvalidConfiguration', 'ConanInvalidConfiguration', (['"""only Linux is supported"""'], {}), "('only Linux is supported')\n", (1011, 1038), False, 'from conans.errors import ConanInvalidConfiguration\n'), ((1613, 1644), 'conans.AutoToolsBuildEnvironment', 'AutoToolsBuildEnvironment', (['self'], {}), '(self)\n', (1638, 1644), False, 'from conans import ConanFile, tools, AutoToolsBuildEnvironment\n'), ((1760, 1795), 'conans.tools.chdir', 'tools.chdir', (['self._source_subfolder'], {}), '(self._source_subfolder)\n', (1771, 1795), False, 'from conans import ConanFile, tools, AutoToolsBuildEnvironment\n'), ((1915, 1950), 'conans.tools.chdir', 'tools.chdir', (['self._source_subfolder'], {}), '(self._source_subfolder)\n', (1926, 1950), False, 'from conans import ConanFile, tools, AutoToolsBuildEnvironment\n'), ((2137, 2178), 'os.path.join', 'os.path.join', (['self.package_folder', '"""sbin"""'], {}), "(self.package_folder, 'sbin')\n", (2149, 2178), False, 'import os\n'), ((2200, 2242), 'os.path.join', 'os.path.join', (['self.package_folder', '"""share"""'], {}), "(self.package_folder, 'share')\n", (2212, 2242), False, 'import os\n'), ((2264, 2317), 'os.path.join', 'os.path.join', (['self.package_folder', '"""lib"""', '"""pkgconfig"""'], {}), "(self.package_folder, 'lib', 'pkgconfig')\n", (2276, 2317), False, 'import os\n'), ((2337, 2392), 'os.path.join', 'os.path.join', (['self.package_folder', '"""lib"""', '"""libblkid.la"""'], {}), "(self.package_folder, 'lib', 'libblkid.la')\n", (2349, 2392), False, 'import os\n'), ((2412, 2467), 'os.path.join', 'os.path.join', (['self.package_folder', '"""lib"""', '"""libmount.la"""'], {}), "(self.package_folder, 'lib', 'libmount.la')\n", (2424, 2467), False, 'import os\n'), ((2587, 2622), 'os.path.join', 'os.path.join', (['"""include"""', '"""libmount"""'], {}), "('include', 'libmount')\n", (2599, 2622), False, 'import os\n')]
BASE_URL="https://harpers.org/sections/readings/page/" N_ARTICLE_LINK_PAGES = 50 OUTPUT_FILE = 'harpers-later-urls.json' WORKER_THREADS = 32 import json import datetime import dateutil.parser from dataclasses import dataclass from dataclasses_json import dataclass_json from datetime import datetime from newspaper import Article from bs4 import BeautifulSoup from typing import List from queue import Queue from threading import Thread from requests import get from pathlib import Path import pandas as pd from urllib.request import Request, urlopen @dataclass_json @dataclass class HarperReadingArticleUrl: url: str title: str class WriteThread(Thread): def __init__(self, queue: Queue, *args, **kwargs): super().__init__(*args, **kwargs) self.queue = queue def run(self): existing_links = [] while True: article = self.queue.get() if article is None: output_file_path = Path(OUTPUT_FILE) check_df = pd.DataFrame(existing_links) check_df.drop_duplicates(subset="url", keep="first", inplace=True) check_df.to_json(output_file_path, orient="records") break current_article_json = article.to_dict() existing_links.insert(0,current_article_json) class ScrapeThread(Thread): def __init__(self, chunk, queue: Queue, *args, **kwargs): super().__init__(*args, **kwargs) self.chunk = chunk self.queue = queue def run(self): for i in self.chunk: try: print(f'Getting articles from list page {i}') url = f"{BASE_URL}{i}" req = Request(url , headers={'User-Agent': 'Mozilla/5.0'}) webpage = urlopen(req).read() soup = BeautifulSoup(webpage, "html5lib") articles = soup.find_all('div', {'class': 'card'}) for article in articles: dual_hrefs = article.find_all('a') link = dual_hrefs[1]['href'] title = dual_hrefs[1].find('h2', {'class': 'ac-title'}) if title is None or title.string is None or link is None or link is None: continue article_url = HarperReadingArticleUrl(url=link.strip(), title=str(title.string.strip()) or '') self.queue.put(article_url) except Exception as e: print(f'Something went wrong when scraping: {e}') print("------------------------------------------") if __name__ == '__main__': queue = Queue() write_thread = WriteThread(queue) write_thread.start() worker_threads = [] chunk_size = (N_ARTICLE_LINK_PAGES) // WORKER_THREADS for i in range(0, N_ARTICLE_LINK_PAGES+1, chunk_size): chunk = range(i,i+chunk_size) worker_threads.append(ScrapeThread(chunk, queue)) for thread in worker_threads: thread.start() for thread in worker_threads: thread.join() # Signal end of jobs to write thread queue.put(None) print('Done.') write_thread.join()
[ "pathlib.Path", "urllib.request.Request", "bs4.BeautifulSoup", "pandas.DataFrame", "queue.Queue", "urllib.request.urlopen" ]
[((2662, 2669), 'queue.Queue', 'Queue', ([], {}), '()\n', (2667, 2669), False, 'from queue import Queue\n'), ((981, 998), 'pathlib.Path', 'Path', (['OUTPUT_FILE'], {}), '(OUTPUT_FILE)\n', (985, 998), False, 'from pathlib import Path\n'), ((1026, 1054), 'pandas.DataFrame', 'pd.DataFrame', (['existing_links'], {}), '(existing_links)\n', (1038, 1054), True, 'import pandas as pd\n'), ((1717, 1768), 'urllib.request.Request', 'Request', (['url'], {'headers': "{'User-Agent': 'Mozilla/5.0'}"}), "(url, headers={'User-Agent': 'Mozilla/5.0'})\n", (1724, 1768), False, 'from urllib.request import Request, urlopen\n'), ((1839, 1873), 'bs4.BeautifulSoup', 'BeautifulSoup', (['webpage', '"""html5lib"""'], {}), "(webpage, 'html5lib')\n", (1852, 1873), False, 'from bs4 import BeautifulSoup\n'), ((1796, 1808), 'urllib.request.urlopen', 'urlopen', (['req'], {}), '(req)\n', (1803, 1808), False, 'from urllib.request import Request, urlopen\n')]
from typing import Dict import numpy as np import torch from torch.nn.functional import linear, log_softmax, embedding from torch.nn import Dropout, LogSoftmax, NLLLoss from allennlp.common import Params from allennlp.models.model import Model from allennlp.data.vocabulary import Vocabulary, DEFAULT_PADDING_TOKEN from allennlp.modules import TextFieldEmbedder, TimeDistributed, Seq2SeqEncoder from allennlp.modules.sampled_softmax_loss import SampledSoftmaxLoss from allennlp.modules.input_variational_dropout import InputVariationalDropout from allennlp.modules.token_embedders import Embedding, TokenEmbedder from allennlp.modules.token_embedders.embedding import _read_pretrained_embeddings_file from allennlp.nn.util import combine_initial_dims, uncombine_initial_dims class SoftmaxLoss(torch.nn.Module): def __init__(self, num_words: int, embedding_dim: int, padding_index: int = 0) -> None: super().__init__() self.softmax_w = torch.nn.Parameter(torch.Tensor(num_words, embedding_dim)) self.softmax_b = torch.nn.Parameter(torch.Tensor(num_words)) self._softmax_func = LogSoftmax(dim=-1) self._padding_index = padding_index self._reset_parameters() def _reset_parameters(self): stdv = 1. / np.sqrt(self.softmax_w.size(1)) self.softmax_w.data.uniform_(-stdv, stdv) self.softmax_b.data.uniform_(-stdv, stdv) def forward(self, embeddings: torch.Tensor, targets: torch.Tensor) -> torch.Tensor: logits = self._softmax_func(linear(embeddings, self.softmax_w, self.softmax_b)) criterion = NLLLoss(ignore_index=self._padding_index, reduction="sum") return criterion(logits, targets.long()) @TokenEmbedder.register("embedding_with_dropout") class EmbeddingWithDropout(Embedding): def __init__(self, num_embeddings: int, embedding_dim: int, dropout: float = None, projection_dim: int = None, weight: torch.FloatTensor = None, padding_index: int = None, trainable: bool = True, max_norm: float = None, norm_type: float = 2., scale_grad_by_freq: bool = False, sparse: bool = False) -> None: Embedding.__init__(self, num_embeddings=num_embeddings, embedding_dim=embedding_dim, projection_dim=projection_dim, weight=weight, padding_index=padding_index, trainable=trainable, max_norm=max_norm, norm_type=norm_type, scale_grad_by_freq=scale_grad_by_freq, sparse=sparse) self.dropout = dropout def forward(self, inputs): original_size = inputs.size() inputs = combine_initial_dims(inputs) if self.dropout and self.training: mask = self.weight.data.new().resize_((self.weight.size(0), 1)).bernoulli_(1 - self.dropout)\ .expand_as(self.weight) / (1 - self.dropout) masked_embed_weight = mask * self.weight else: masked_embed_weight = self.weight embedded = embedding(inputs, masked_embed_weight, max_norm=self.max_norm, norm_type=self.norm_type, scale_grad_by_freq=self.scale_grad_by_freq, sparse=self.sparse) embedded = uncombine_initial_dims(embedded, original_size) if self._projection: projection = self._projection for _ in range(embedded.dim() - 2): projection = TimeDistributed(projection) embedded = projection(embedded) return embedded @classmethod def from_params(cls, vocab: Vocabulary, params: Params) -> 'Embedding': num_embeddings = params.pop_int('num_embeddings', None) vocab_namespace = params.pop("vocab_namespace", "tokens") if num_embeddings is None: num_embeddings = vocab.get_vocab_size(vocab_namespace) embedding_dim = params.pop_int('embedding_dim') pretrained_file = params.pop("pretrained_file", None) projection_dim = params.pop_int("projection_dim", None) trainable = params.pop_bool("trainable", True) padding_index = params.pop_int('padding_index', None) max_norm = params.pop_float('max_norm', None) norm_type = params.pop_float('norm_type', 2.) scale_grad_by_freq = params.pop_bool('scale_grad_by_freq', False) sparse = params.pop_bool('sparse', False) dropout = params.pop_float('dropout', None) params.assert_empty(cls.__name__) weight = _read_pretrained_embeddings_file(pretrained_file, embedding_dim, vocab, vocab_namespace) if pretrained_file else None return cls(num_embeddings=num_embeddings, embedding_dim=embedding_dim, projection_dim=projection_dim, weight=weight, padding_index=padding_index, trainable=trainable, max_norm=max_norm, norm_type=norm_type, scale_grad_by_freq=scale_grad_by_freq, sparse=sparse, dropout=dropout) @Model.register("encoder_only") class EncoderOnlyLanguageModel(Model): def __init__(self, vocab: Vocabulary, embedder: TextFieldEmbedder, contextualizer: Seq2SeqEncoder, dropout: float = None, tie_embeddings: bool = True, num_samples: int = None, use_variational_dropout: bool = False): super().__init__(vocab) self._embedder = embedder self._contextualizer = contextualizer self._context_dim = contextualizer.get_output_dim() if use_variational_dropout: self._dropout = InputVariationalDropout(dropout) if dropout else lambda x: x else: self._dropout = Dropout(dropout) if dropout else lambda x: x vocab_size = self.vocab.get_vocab_size() padding_index = self.vocab.get_token_index(DEFAULT_PADDING_TOKEN) if num_samples: self._softmax_loss = SampledSoftmaxLoss(vocab_size, self._context_dim, num_samples) else: self._softmax_loss = SoftmaxLoss(vocab_size, self._context_dim, padding_index) self._tie_embeddings = tie_embeddings if self._tie_embeddings: embedder_children = dict(self._embedder.named_children()) word_embedder = embedder_children["token_embedder_tokens"] assert self._softmax_loss.softmax_w.size() == word_embedder.weight.size() self._softmax_loss.softmax_w = word_embedder.weight def forward(self, source_tokens: Dict[str, torch.Tensor], target_tokens: Dict[str, torch.Tensor]=None, **kwargs) -> Dict[str, torch.Tensor]: # Shape: (batch_size, max_length) source = source_tokens["tokens"] mask = source > 0 # Shape: (batch_size, max_length, embedding_size) embeddings = self._embedder(source_tokens) embeddings = self._dropout(embeddings) # Shape: (batch_size, max_length, context_dim) contextual_embeddings = self._contextualizer(embeddings, mask) contextual_embeddings = self._dropout(contextual_embeddings) result = dict() if target_tokens: targets = target_tokens["tokens"] targets = targets.view(-1) mask = targets > 0 masked_targets = targets.masked_select(mask) lined_embeddings = contextual_embeddings.view(-1, self._context_dim) masked_embeddings = lined_embeddings.masked_select(mask.unsqueeze(-1)) masked_embeddings = masked_embeddings.view(-1, self._context_dim) loss = self._softmax_loss(masked_embeddings, masked_targets) num_targets = torch.sum(mask.long()) result["loss"] = loss / num_targets.float() if not self.training: result["logits"] = self._get_logits(contextual_embeddings) return result def _get_logits(self, embeddings): linears = linear(embeddings, self._softmax_loss.softmax_w, self._softmax_loss.softmax_b) return log_softmax(linears, dim=-1)
[ "torch.nn.functional.linear", "torch.nn.Dropout", "allennlp.modules.TimeDistributed", "allennlp.nn.util.combine_initial_dims", "allennlp.modules.sampled_softmax_loss.SampledSoftmaxLoss", "allennlp.modules.token_embedders.TokenEmbedder.register", "allennlp.modules.input_variational_dropout.InputVariation...
[((1757, 1805), 'allennlp.modules.token_embedders.TokenEmbedder.register', 'TokenEmbedder.register', (['"""embedding_with_dropout"""'], {}), "('embedding_with_dropout')\n", (1779, 1805), False, 'from allennlp.modules.token_embedders import Embedding, TokenEmbedder\n'), ((5592, 5622), 'allennlp.models.model.Model.register', 'Model.register', (['"""encoder_only"""'], {}), "('encoder_only')\n", (5606, 5622), False, 'from allennlp.models.model import Model\n'), ((1167, 1185), 'torch.nn.LogSoftmax', 'LogSoftmax', ([], {'dim': '(-1)'}), '(dim=-1)\n', (1177, 1185), False, 'from torch.nn import Dropout, LogSoftmax, NLLLoss\n'), ((1646, 1704), 'torch.nn.NLLLoss', 'NLLLoss', ([], {'ignore_index': 'self._padding_index', 'reduction': '"""sum"""'}), "(ignore_index=self._padding_index, reduction='sum')\n", (1653, 1704), False, 'from torch.nn import Dropout, LogSoftmax, NLLLoss\n'), ((2352, 2639), 'allennlp.modules.token_embedders.Embedding.__init__', 'Embedding.__init__', (['self'], {'num_embeddings': 'num_embeddings', 'embedding_dim': 'embedding_dim', 'projection_dim': 'projection_dim', 'weight': 'weight', 'padding_index': 'padding_index', 'trainable': 'trainable', 'max_norm': 'max_norm', 'norm_type': 'norm_type', 'scale_grad_by_freq': 'scale_grad_by_freq', 'sparse': 'sparse'}), '(self, num_embeddings=num_embeddings, embedding_dim=\n embedding_dim, projection_dim=projection_dim, weight=weight,\n padding_index=padding_index, trainable=trainable, max_norm=max_norm,\n norm_type=norm_type, scale_grad_by_freq=scale_grad_by_freq, sparse=sparse)\n', (2370, 2639), False, 'from allennlp.modules.token_embedders import Embedding, TokenEmbedder\n'), ((3015, 3043), 'allennlp.nn.util.combine_initial_dims', 'combine_initial_dims', (['inputs'], {}), '(inputs)\n', (3035, 3043), False, 'from allennlp.nn.util import combine_initial_dims, uncombine_initial_dims\n'), ((3395, 3557), 'torch.nn.functional.embedding', 'embedding', (['inputs', 'masked_embed_weight'], {'max_norm': 'self.max_norm', 'norm_type': 'self.norm_type', 'scale_grad_by_freq': 'self.scale_grad_by_freq', 'sparse': 'self.sparse'}), '(inputs, masked_embed_weight, max_norm=self.max_norm, norm_type=\n self.norm_type, scale_grad_by_freq=self.scale_grad_by_freq, sparse=self\n .sparse)\n', (3404, 3557), False, 'from torch.nn.functional import linear, log_softmax, embedding\n'), ((3684, 3731), 'allennlp.nn.util.uncombine_initial_dims', 'uncombine_initial_dims', (['embedded', 'original_size'], {}), '(embedded, original_size)\n', (3706, 3731), False, 'from allennlp.nn.util import combine_initial_dims, uncombine_initial_dims\n'), ((8588, 8666), 'torch.nn.functional.linear', 'linear', (['embeddings', 'self._softmax_loss.softmax_w', 'self._softmax_loss.softmax_b'], {}), '(embeddings, self._softmax_loss.softmax_w, self._softmax_loss.softmax_b)\n', (8594, 8666), False, 'from torch.nn.functional import linear, log_softmax, embedding\n'), ((8682, 8710), 'torch.nn.functional.log_softmax', 'log_softmax', (['linears'], {'dim': '(-1)'}), '(linears, dim=-1)\n', (8693, 8710), False, 'from torch.nn.functional import linear, log_softmax, embedding\n'), ((1029, 1067), 'torch.Tensor', 'torch.Tensor', (['num_words', 'embedding_dim'], {}), '(num_words, embedding_dim)\n', (1041, 1067), False, 'import torch\n'), ((1113, 1136), 'torch.Tensor', 'torch.Tensor', (['num_words'], {}), '(num_words)\n', (1125, 1136), False, 'import torch\n'), ((1574, 1624), 'torch.nn.functional.linear', 'linear', (['embeddings', 'self.softmax_w', 'self.softmax_b'], {}), '(embeddings, self.softmax_w, self.softmax_b)\n', (1580, 1624), False, 'from torch.nn.functional import linear, log_softmax, embedding\n'), ((4945, 5037), 'allennlp.modules.token_embedders.embedding._read_pretrained_embeddings_file', '_read_pretrained_embeddings_file', (['pretrained_file', 'embedding_dim', 'vocab', 'vocab_namespace'], {}), '(pretrained_file, embedding_dim, vocab,\n vocab_namespace)\n', (4977, 5037), False, 'from allennlp.modules.token_embedders.embedding import _read_pretrained_embeddings_file\n'), ((6568, 6630), 'allennlp.modules.sampled_softmax_loss.SampledSoftmaxLoss', 'SampledSoftmaxLoss', (['vocab_size', 'self._context_dim', 'num_samples'], {}), '(vocab_size, self._context_dim, num_samples)\n', (6586, 6630), False, 'from allennlp.modules.sampled_softmax_loss import SampledSoftmaxLoss\n'), ((3881, 3908), 'allennlp.modules.TimeDistributed', 'TimeDistributed', (['projection'], {}), '(projection)\n', (3896, 3908), False, 'from allennlp.modules import TextFieldEmbedder, TimeDistributed, Seq2SeqEncoder\n'), ((6239, 6271), 'allennlp.modules.input_variational_dropout.InputVariationalDropout', 'InputVariationalDropout', (['dropout'], {}), '(dropout)\n', (6262, 6271), False, 'from allennlp.modules.input_variational_dropout import InputVariationalDropout\n'), ((6342, 6358), 'torch.nn.Dropout', 'Dropout', (['dropout'], {}), '(dropout)\n', (6349, 6358), False, 'from torch.nn import Dropout, LogSoftmax, NLLLoss\n')]
""" Created on 22 Feb 2019 @author: <NAME> (<EMAIL>) source repo: scs_analysis """ import optparse # -------------------------------------------------------------------------------------------------------------------- class CmdCSVJoin(object): """unix command line handler""" def __init__(self): """ Constructor """ self.__parser = optparse.OptionParser(usage="%prog [-t TYPE] [-i] [-v] -l PREFIX PK FILENAME " "-r PREFIX PK FILENAME", version="%prog 1.0") # compulsory... self.__parser.add_option("--left", "-l", type="string", nargs=3, action="store", dest="left", help="output path prefix, primary key and filename for left-hand set") self.__parser.add_option("--right", "-r", type="string", nargs=3, action="store", dest="right", help="output path prefix, primary key and filename for right-hand set") # optional... self.__parser.add_option("--type", "-t", type="string", nargs=1, action="store", dest="type", default='INNER', help="{ 'INNER' | 'LEFT' | 'RIGHT' | 'FULL' } (default 'INNER')") self.__parser.add_option("--iso8601", "-i", action="store_true", dest="iso8601", default=False, help="interpret the primary key as an ISO 8601 datetime") self.__parser.add_option("--verbose", "-v", action="store_true", dest="verbose", default=False, help="report narrative to stderr") self.__opts, self.__args = self.__parser.parse_args() # ---------------------------------------------------------------------------------------------------------------- def is_valid(self): if self.__opts.left is None or self.__opts.right is None: return False return True # ---------------------------------------------------------------------------------------------------------------- @property def type(self): return self.__opts.type @property def left_prefix(self): return None if self.__opts.left is None else self.__opts.left[0] @property def left_pk(self): return None if self.__opts.left is None else self.__opts.left[1] @property def left_filename(self): return None if self.__opts.left is None else self.__opts.left[2] @property def right_prefix(self): return None if self.__opts.right is None else self.__opts.right[0] @property def right_pk(self): return None if self.__opts.right is None else self.__opts.right[1] @property def right_filename(self): return None if self.__opts.right is None else self.__opts.right[2] @property def iso8601(self): return self.__opts.iso8601 @property def verbose(self): return self.__opts.verbose # ---------------------------------------------------------------------------------------------------------------- def print_help(self, file): self.__parser.print_help(file) def __str__(self, *args, **kwargs): return "CmdCSVJoin:{type:%s, left:%s, right:%s, iso8601:%s, verbose:%s}" % \ (self.type, self.__opts.left, self.__opts.right, self.iso8601, self.verbose)
[ "optparse.OptionParser" ]
[((379, 509), 'optparse.OptionParser', 'optparse.OptionParser', ([], {'usage': '"""%prog [-t TYPE] [-i] [-v] -l PREFIX PK FILENAME -r PREFIX PK FILENAME"""', 'version': '"""%prog 1.0"""'}), "(usage=\n '%prog [-t TYPE] [-i] [-v] -l PREFIX PK FILENAME -r PREFIX PK FILENAME',\n version='%prog 1.0')\n", (400, 509), False, 'import optparse\n')]
# Generated by Django 3.2.9 on 2022-01-10 12:39 from django.db import migrations, models import django.utils.timezone class Migration(migrations.Migration): dependencies = [ ('car', '0003_auto_20220110_1507'), ] operations = [ migrations.AddField( model_name='sale', name='cc', field=models.CharField(default=django.utils.timezone.now, max_length=100), preserve_default=False, ), ]
[ "django.db.models.CharField" ]
[((353, 420), 'django.db.models.CharField', 'models.CharField', ([], {'default': 'django.utils.timezone.now', 'max_length': '(100)'}), '(default=django.utils.timezone.now, max_length=100)\n', (369, 420), False, 'from django.db import migrations, models\n')]
import pandas as pd import pytask from src.config import BLD @pytask.mark.depends_on(BLD / "data" / "raw_time_series" / "reproduction_number.csv") @pytask.mark.produces(BLD / "data" / "processed_time_series" / "r_effective.pkl") def task_prepare_rki_r_effective_data(depends_on, produces): df = pd.read_csv(depends_on) df["date"] = pd.to_datetime(df["Datum"], yearfirst=True) df = df.set_index("date").sort_index() r_effective = df["PS_7_Tage_R_Wert"] r_effective.to_pickle(produces)
[ "pandas.to_datetime", "pytask.mark.depends_on", "pytask.mark.produces", "pandas.read_csv" ]
[((65, 153), 'pytask.mark.depends_on', 'pytask.mark.depends_on', (["(BLD / 'data' / 'raw_time_series' / 'reproduction_number.csv')"], {}), "(BLD / 'data' / 'raw_time_series' /\n 'reproduction_number.csv')\n", (87, 153), False, 'import pytask\n'), ((151, 236), 'pytask.mark.produces', 'pytask.mark.produces', (["(BLD / 'data' / 'processed_time_series' / 'r_effective.pkl')"], {}), "(BLD / 'data' / 'processed_time_series' / 'r_effective.pkl'\n )\n", (171, 236), False, 'import pytask\n'), ((302, 325), 'pandas.read_csv', 'pd.read_csv', (['depends_on'], {}), '(depends_on)\n', (313, 325), True, 'import pandas as pd\n'), ((344, 387), 'pandas.to_datetime', 'pd.to_datetime', (["df['Datum']"], {'yearfirst': '(True)'}), "(df['Datum'], yearfirst=True)\n", (358, 387), True, 'import pandas as pd\n')]
from collections import defaultdict import pytest from radical_translations.agents.models import Organisation, Person pytestmark = pytest.mark.django_db @pytest.mark.usefixtures("vocabulary") class TestOrganisation: def test_agent_type(self, title): obj = Person(name="<NAME>") obj.save() assert obj.agent_type == "person" obj = Organisation(name="organisation name") obj.save() assert obj.agent_type == "organisation" def test_from_gsx_entry(self): assert Organisation.from_gsx_entry(None) is None entry = defaultdict(defaultdict) entry["gsx$organisation"]["$t"] = "" assert Organisation.from_gsx_entry(entry) is None entry["gsx$organisation"]["$t"] = "Organisation 1" assert Organisation.from_gsx_entry(entry) is not None entry["gsx$type"]["$t"] = "Publisher" assert Organisation.from_gsx_entry(entry) is not None entry["gsx$location"]["$t"] = "0001: London [UK]" assert Organisation.from_gsx_entry(entry) is not None assert Organisation.objects.count() == 1 @pytest.mark.usefixtures("vocabulary") class TestPerson: def test_from_gsx_entry(self): assert Person.from_gsx_entry(None) is None entry = defaultdict(defaultdict) entry["gsx$name"]["$t"] = "" assert Person.from_gsx_entry(entry) is None entry["gsx$name"]["$t"] = "Person 1" assert Person.from_gsx_entry(entry) is not None entry["gsx$gender"]["$t"] = "f" p = Person.from_gsx_entry(entry) assert p is not None assert p.gender == "f" entry["gsx$birth"]["$t"] = "1790" p = Person.from_gsx_entry(entry) assert p is not None assert p.date_birth.date_display == "1790" entry["gsx$locationsresidence"]["$t"] = "0001: London [UK]; 0002: Paris [FR]" p = Person.from_gsx_entry(entry) assert p is not None assert "London" in p.based_near.first().address assert "Paris" in p.based_near.last().address entry["gsx$locationbirth"]["$t"] = "0001: London [UK]" p = Person.from_gsx_entry(entry) assert p is not None assert "London" in p.place_birth.address entry["gsx$locationdeath"]["$t"] = "0002: Paris [FR]" p = Person.from_gsx_entry(entry) assert p is not None assert "Paris" in p.place_death.address entry["gsx$occupations"]["$t"] = "tester" p = Person.from_gsx_entry(entry) assert p is not None assert "tester" in p.roles.first().label.lower() entry["gsx$organisations"]["$t"] = "Organisation 1" p = Person.from_gsx_entry(entry) assert p is not None entry["gsx$collaborators"]["$t"] = "Person 2; Person 3" p = Person.from_gsx_entry(entry) assert p is not None assert Person.objects.count() == 3
[ "radical_translations.agents.models.Person", "radical_translations.agents.models.Person.objects.count", "radical_translations.agents.models.Person.from_gsx_entry", "radical_translations.agents.models.Organisation", "pytest.mark.usefixtures", "collections.defaultdict", "radical_translations.agents.models...
[((159, 196), 'pytest.mark.usefixtures', 'pytest.mark.usefixtures', (['"""vocabulary"""'], {}), "('vocabulary')\n", (182, 196), False, 'import pytest\n'), ((1120, 1157), 'pytest.mark.usefixtures', 'pytest.mark.usefixtures', (['"""vocabulary"""'], {}), "('vocabulary')\n", (1143, 1157), False, 'import pytest\n'), ((273, 294), 'radical_translations.agents.models.Person', 'Person', ([], {'name': '"""<NAME>"""'}), "(name='<NAME>')\n", (279, 294), False, 'from radical_translations.agents.models import Organisation, Person\n'), ((371, 409), 'radical_translations.agents.models.Organisation', 'Organisation', ([], {'name': '"""organisation name"""'}), "(name='organisation name')\n", (383, 409), False, 'from radical_translations.agents.models import Organisation, Person\n'), ((587, 611), 'collections.defaultdict', 'defaultdict', (['defaultdict'], {}), '(defaultdict)\n', (598, 611), False, 'from collections import defaultdict\n'), ((1279, 1303), 'collections.defaultdict', 'defaultdict', (['defaultdict'], {}), '(defaultdict)\n', (1290, 1303), False, 'from collections import defaultdict\n'), ((1548, 1576), 'radical_translations.agents.models.Person.from_gsx_entry', 'Person.from_gsx_entry', (['entry'], {}), '(entry)\n', (1569, 1576), False, 'from radical_translations.agents.models import Organisation, Person\n'), ((1692, 1720), 'radical_translations.agents.models.Person.from_gsx_entry', 'Person.from_gsx_entry', (['entry'], {}), '(entry)\n', (1713, 1720), False, 'from radical_translations.agents.models import Organisation, Person\n'), ((1900, 1928), 'radical_translations.agents.models.Person.from_gsx_entry', 'Person.from_gsx_entry', (['entry'], {}), '(entry)\n', (1921, 1928), False, 'from radical_translations.agents.models import Organisation, Person\n'), ((2144, 2172), 'radical_translations.agents.models.Person.from_gsx_entry', 'Person.from_gsx_entry', (['entry'], {}), '(entry)\n', (2165, 2172), False, 'from radical_translations.agents.models import Organisation, Person\n'), ((2326, 2354), 'radical_translations.agents.models.Person.from_gsx_entry', 'Person.from_gsx_entry', (['entry'], {}), '(entry)\n', (2347, 2354), False, 'from radical_translations.agents.models import Organisation, Person\n'), ((2495, 2523), 'radical_translations.agents.models.Person.from_gsx_entry', 'Person.from_gsx_entry', (['entry'], {}), '(entry)\n', (2516, 2523), False, 'from radical_translations.agents.models import Organisation, Person\n'), ((2683, 2711), 'radical_translations.agents.models.Person.from_gsx_entry', 'Person.from_gsx_entry', (['entry'], {}), '(entry)\n', (2704, 2711), False, 'from radical_translations.agents.models import Organisation, Person\n'), ((2818, 2846), 'radical_translations.agents.models.Person.from_gsx_entry', 'Person.from_gsx_entry', (['entry'], {}), '(entry)\n', (2839, 2846), False, 'from radical_translations.agents.models import Organisation, Person\n'), ((528, 561), 'radical_translations.agents.models.Organisation.from_gsx_entry', 'Organisation.from_gsx_entry', (['None'], {}), '(None)\n', (555, 561), False, 'from radical_translations.agents.models import Organisation, Person\n'), ((672, 706), 'radical_translations.agents.models.Organisation.from_gsx_entry', 'Organisation.from_gsx_entry', (['entry'], {}), '(entry)\n', (699, 706), False, 'from radical_translations.agents.models import Organisation, Person\n'), ((790, 824), 'radical_translations.agents.models.Organisation.from_gsx_entry', 'Organisation.from_gsx_entry', (['entry'], {}), '(entry)\n', (817, 824), False, 'from radical_translations.agents.models import Organisation, Person\n'), ((899, 933), 'radical_translations.agents.models.Organisation.from_gsx_entry', 'Organisation.from_gsx_entry', (['entry'], {}), '(entry)\n', (926, 933), False, 'from radical_translations.agents.models import Organisation, Person\n'), ((1020, 1054), 'radical_translations.agents.models.Organisation.from_gsx_entry', 'Organisation.from_gsx_entry', (['entry'], {}), '(entry)\n', (1047, 1054), False, 'from radical_translations.agents.models import Organisation, Person\n'), ((1083, 1111), 'radical_translations.agents.models.Organisation.objects.count', 'Organisation.objects.count', ([], {}), '()\n', (1109, 1111), False, 'from radical_translations.agents.models import Organisation, Person\n'), ((1226, 1253), 'radical_translations.agents.models.Person.from_gsx_entry', 'Person.from_gsx_entry', (['None'], {}), '(None)\n', (1247, 1253), False, 'from radical_translations.agents.models import Organisation, Person\n'), ((1356, 1384), 'radical_translations.agents.models.Person.from_gsx_entry', 'Person.from_gsx_entry', (['entry'], {}), '(entry)\n', (1377, 1384), False, 'from radical_translations.agents.models import Organisation, Person\n'), ((1454, 1482), 'radical_translations.agents.models.Person.from_gsx_entry', 'Person.from_gsx_entry', (['entry'], {}), '(entry)\n', (1475, 1482), False, 'from radical_translations.agents.models import Organisation, Person\n'), ((2892, 2914), 'radical_translations.agents.models.Person.objects.count', 'Person.objects.count', ([], {}), '()\n', (2912, 2914), False, 'from radical_translations.agents.models import Organisation, Person\n')]
from go.apps.tests.view_helpers import AppViewsHelper from go.base.tests.helpers import GoDjangoTestCase class TestHttpApiViews(GoDjangoTestCase): def setUp(self): self.app_helper = self.add_helper(AppViewsHelper(u'http_api')) self.client = self.app_helper.get_client() def test_show_stopped(self): """ Test showing the conversation """ conv_helper = self.app_helper.create_conversation_helper( name=u"myconv") response = self.client.get(conv_helper.get_view_url('show')) self.assertContains(response, u"<h1>myconv</h1>") def test_show_running(self): """ Test showing the conversation """ conv_helper = self.app_helper.create_conversation_helper( name=u"myconv", started=True) response = self.client.get(conv_helper.get_view_url('show')) self.assertContains(response, u"<h1>myconv</h1>") def test_edit_view(self): conv_helper = self.app_helper.create_conversation_helper() conversation = conv_helper.get_conversation() self.assertEqual(conversation.config, {}) response = self.client.post(conv_helper.get_view_url('edit'), { 'http_api-api_tokens': 'token', 'http_api-push_message_url': 'http://messages/', 'http_api-push_event_url': 'http://events/', 'http_api-metric_store': 'foo_metric_store', }, follow=True) self.assertRedirects(response, conv_helper.get_view_url('show')) reloaded_conv = conv_helper.get_conversation() self.assertEqual(reloaded_conv.config, { 'http_api': { 'push_event_url': 'http://events/', 'push_message_url': 'http://messages/', 'api_tokens': ['token'], 'metric_store': 'foo_metric_store', 'ignore_events': False, 'ignore_messages': False, } }) def test_edit_view_no_event_url(self): conv_helper = self.app_helper.create_conversation_helper() conversation = conv_helper.get_conversation() self.assertEqual(conversation.config, {}) response = self.client.post(conv_helper.get_view_url('edit'), { 'http_api-api_tokens': 'token', 'http_api-push_message_url': 'http://messages/', 'http_api-push_event_url': '', 'http_api-metric_store': 'foo_metric_store', }) self.assertRedirects(response, conv_helper.get_view_url('show')) reloaded_conv = conv_helper.get_conversation() self.assertEqual(reloaded_conv.config, { 'http_api': { 'push_event_url': None, 'push_message_url': 'http://messages/', 'api_tokens': ['token'], 'metric_store': 'foo_metric_store', 'ignore_events': False, 'ignore_messages': False, } }) self.assertEqual(conversation.config, {}) response = self.client.get(conv_helper.get_view_url('edit')) self.assertContains(response, 'http://messages/') self.assertContains(response, 'foo_metric_store') self.assertEqual(response.status_code, 200) def test_edit_view_no_push_urls(self): conv_helper = self.app_helper.create_conversation_helper() conversation = conv_helper.get_conversation() self.assertEqual(conversation.config, {}) response = self.client.post(conv_helper.get_view_url('edit'), { 'http_api-api_tokens': 'token', 'http_api-push_message_url': '', 'http_api-push_event_url': '', 'http_api-metric_store': 'foo_metric_store', }) self.assertRedirects(response, conv_helper.get_view_url('show')) reloaded_conv = conv_helper.get_conversation() self.assertEqual(reloaded_conv.config, { 'http_api': { 'push_event_url': None, 'push_message_url': None, 'api_tokens': ['token'], 'metric_store': 'foo_metric_store', 'ignore_events': False, 'ignore_messages': False, } }) self.assertEqual(conversation.config, {}) response = self.client.get(conv_helper.get_view_url('edit')) self.assertContains(response, 'foo_metric_store') self.assertEqual(response.status_code, 200)
[ "go.apps.tests.view_helpers.AppViewsHelper" ]
[((213, 240), 'go.apps.tests.view_helpers.AppViewsHelper', 'AppViewsHelper', (['u"""http_api"""'], {}), "(u'http_api')\n", (227, 240), False, 'from go.apps.tests.view_helpers import AppViewsHelper\n')]
# -*- coding: utf-8 -*- # Copyright: (c) 2019-2021, Dell EMC """Helper module for PowerStore""" import logging from pkg_resources import parse_version provisioning_obj = None def set_provisioning_obj(val): global provisioning_obj provisioning_obj = val def prepare_querystring(*query_arguments, **kw_query_arguments): """Prepare a querystring dict containing all query_arguments and kw_query_arguments passed. :return: Querystring dict. :rtype: dict """ querystring = dict() for argument_dict in query_arguments: if isinstance(argument_dict, dict): querystring.update(argument_dict) querystring.update(kw_query_arguments) return querystring def get_logger(module_name, enable_log=False): """Return a logger with the specified name :param module_name: Name of the module :type module_name: str :param enable_log: (optional) Whether to enable log or not :type enable_log: bool :return: Logger object :rtype: logging.Logger """ LOG = logging.getLogger(module_name) LOG.setLevel(logging.DEBUG) if enable_log: LOG.disabled = False else: LOG.disabled = True return LOG def is_foot_hill_or_higher(): """Return a true if the array version is foot hill or higher. :return: True if foot hill or higher :rtype: bool """ foot_hill_version = '2.0.0.0' array_version = provisioning_obj.get_array_version() if array_version and ( parse_version(array_version) >= parse_version(foot_hill_version)): return True return False def filtered_details(filterable_keys, filter_dict, resource_list, resource_name): """ Get the filtered output. :filterable_keys: Keys on which filters are supported. :type filterable_keys: list :filter_dict: Dict containing the filters, operators and value. :type filter_dict: dict :resource_list: The response of the REST api call on which filter_dict is to be applied. :type resource_list: list :resource_name: Name of the resource :type resource_name: str :return: Dict, containing filtered values. :rtype: dict """ err_msg = "Entered key {0} is not supported for filtering. " \ "For {1}, filters can be applied only on {2}. " response = list() for resource in resource_list: count = 0 for key in filter_dict: # Check if the filters can be applied on the key or not if key not in filterable_keys: raise Exception(err_msg.format( key, resource_name, str(filterable_keys))) count = apply_operators(filter_dict, key, resource, count) if count == len(filter_dict): temp_dict = dict() temp_dict['id'] = resource['id'] # check if resource has 'name' parameter or not. if resource_name not in ["CHAP config", "service config"]: temp_dict['name'] = resource['name'] response.append(temp_dict) return response def apply_operators(filter_dict, key, resource, count): """ Returns the count for the filters applied on the keys """ split_list = filter_dict[key].split(".") if split_list[0] == 'eq' and str(resource[key]) == str(split_list[1]): count += 1 elif split_list[0] == 'neq' and str(resource[key]) != str(split_list[1]): count += 1 elif split_list[0] == 'ilike': if not isinstance(resource[key], str): raise Exception('like can be applied on string type' ' parameters only. Please enter a valid operator' ' and parameter combination') search_val = split_list[1].replace("*", "") value = resource[key] if split_list[1].startswith("*") and \ split_list[1].endswith("*") and \ value.count(search_val) > 0: count += 1 elif split_list[1].startswith("*") and \ value.endswith(search_val): count += 1 elif value.startswith(search_val): count += 1 elif split_list[0] == 'gt': if not isinstance(resource[key], (int, float)): raise Exception('greater can be applied on int type' ' parameters only. Please enter a valid operator' ' and parameter combination') if isinstance(resource[key], int) and\ int(split_list[1]) < resource[key]: count += 1 if isinstance(resource[key], float) and \ float(split_list[1]) < resource[key]: count += 1 elif split_list[0] == 'lt': if not isinstance(resource[key], (int, float)): raise Exception('lesser can be applied on int type' ' parameters only. Please enter a valid operator' ' and parameter combination') if isinstance(resource[key], int) and\ int(split_list[1]) > resource[key]: count += 1 if isinstance(resource[key], float) and \ float(split_list[1]) > resource[key]: count += 1 return count
[ "logging.getLogger", "pkg_resources.parse_version" ]
[((1041, 1071), 'logging.getLogger', 'logging.getLogger', (['module_name'], {}), '(module_name)\n', (1058, 1071), False, 'import logging\n'), ((1500, 1528), 'pkg_resources.parse_version', 'parse_version', (['array_version'], {}), '(array_version)\n', (1513, 1528), False, 'from pkg_resources import parse_version\n'), ((1532, 1564), 'pkg_resources.parse_version', 'parse_version', (['foot_hill_version'], {}), '(foot_hill_version)\n', (1545, 1564), False, 'from pkg_resources import parse_version\n')]
# -*- coding: utf-8 -*- # Copyright 2018, IBM. # # This source code is licensed under the Apache License, Version 2.0 found in # the LICENSE.txt file in the root directory of this source tree. # pylint: disable=redefined-builtin """Tests basic functionality of the transpile function""" from qiskit import QuantumRegister, QuantumCircuit from qiskit import compile, BasicAer from qiskit.transpiler import PassManager, transpile_dag, transpile from qiskit.tools.compiler import circuits_to_qobj from qiskit.converters import circuit_to_dag from ..common import QiskitTestCase class TestTranspile(QiskitTestCase): """Test transpile function.""" def test_pass_manager_empty(self): """Test passing an empty PassManager() to the transpiler. It should perform no transformations on the circuit. """ qr = QuantumRegister(2) circuit = QuantumCircuit(qr) circuit.h(qr[0]) circuit.h(qr[0]) circuit.cx(qr[0], qr[1]) circuit.cx(qr[0], qr[1]) circuit.cx(qr[0], qr[1]) circuit.cx(qr[0], qr[1]) dag_circuit = circuit_to_dag(circuit) resources_before = dag_circuit.count_ops() pass_manager = PassManager() dag_circuit = transpile_dag(dag_circuit, pass_manager=pass_manager) resources_after = dag_circuit.count_ops() self.assertDictEqual(resources_before, resources_after) def test_pass_manager_none(self): """Test passing the default (None) pass manager to the transpiler. It should perform the default qiskit flow: unroll, swap_mapper, cx_direction, cx_cancellation, optimize_1q_gates and should be equivalent to using tools.compile """ qr = QuantumRegister(2, 'qr') circuit = QuantumCircuit(qr) circuit.h(qr[0]) circuit.h(qr[0]) circuit.cx(qr[0], qr[1]) circuit.cx(qr[0], qr[1]) circuit.cx(qr[0], qr[1]) circuit.cx(qr[0], qr[1]) coupling_map = [[1, 0]] basis_gates = 'u1,u2,u3,cx,id' backend = BasicAer.get_backend('qasm_simulator') circuit2 = transpile(circuit, backend, coupling_map=coupling_map, basis_gates=basis_gates, pass_manager=None) qobj = compile(circuit, backend=backend, coupling_map=coupling_map, basis_gates=basis_gates) qobj2 = circuits_to_qobj(circuit2, backend.name(), basis_gates=basis_gates, coupling_map=coupling_map, qobj_id=qobj.qobj_id) self.assertEqual(qobj, qobj2)
[ "qiskit.transpiler.transpile_dag", "qiskit.transpiler.transpile", "qiskit.transpiler.PassManager", "qiskit.converters.circuit_to_dag", "qiskit.BasicAer.get_backend", "qiskit.QuantumCircuit", "qiskit.compile", "qiskit.QuantumRegister" ]
[((847, 865), 'qiskit.QuantumRegister', 'QuantumRegister', (['(2)'], {}), '(2)\n', (862, 865), False, 'from qiskit import QuantumRegister, QuantumCircuit\n'), ((884, 902), 'qiskit.QuantumCircuit', 'QuantumCircuit', (['qr'], {}), '(qr)\n', (898, 902), False, 'from qiskit import QuantumRegister, QuantumCircuit\n'), ((1107, 1130), 'qiskit.converters.circuit_to_dag', 'circuit_to_dag', (['circuit'], {}), '(circuit)\n', (1121, 1130), False, 'from qiskit.converters import circuit_to_dag\n'), ((1206, 1219), 'qiskit.transpiler.PassManager', 'PassManager', ([], {}), '()\n', (1217, 1219), False, 'from qiskit.transpiler import PassManager, transpile_dag, transpile\n'), ((1242, 1295), 'qiskit.transpiler.transpile_dag', 'transpile_dag', (['dag_circuit'], {'pass_manager': 'pass_manager'}), '(dag_circuit, pass_manager=pass_manager)\n', (1255, 1295), False, 'from qiskit.transpiler import PassManager, transpile_dag, transpile\n'), ((1736, 1760), 'qiskit.QuantumRegister', 'QuantumRegister', (['(2)', '"""qr"""'], {}), "(2, 'qr')\n", (1751, 1760), False, 'from qiskit import QuantumRegister, QuantumCircuit\n'), ((1779, 1797), 'qiskit.QuantumCircuit', 'QuantumCircuit', (['qr'], {}), '(qr)\n', (1793, 1797), False, 'from qiskit import QuantumRegister, QuantumCircuit\n'), ((2071, 2109), 'qiskit.BasicAer.get_backend', 'BasicAer.get_backend', (['"""qasm_simulator"""'], {}), "('qasm_simulator')\n", (2091, 2109), False, 'from qiskit import compile, BasicAer\n'), ((2129, 2232), 'qiskit.transpiler.transpile', 'transpile', (['circuit', 'backend'], {'coupling_map': 'coupling_map', 'basis_gates': 'basis_gates', 'pass_manager': 'None'}), '(circuit, backend, coupling_map=coupling_map, basis_gates=\n basis_gates, pass_manager=None)\n', (2138, 2232), False, 'from qiskit.transpiler import PassManager, transpile_dag, transpile\n'), ((2273, 2363), 'qiskit.compile', 'compile', (['circuit'], {'backend': 'backend', 'coupling_map': 'coupling_map', 'basis_gates': 'basis_gates'}), '(circuit, backend=backend, coupling_map=coupling_map, basis_gates=\n basis_gates)\n', (2280, 2363), False, 'from qiskit import compile, BasicAer\n')]
""" MIT License Copyright (c) 2020-present noaione Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. """ import shutil import sys from functools import partial from pathlib import Path from typing import Dict, Generator, List, NamedTuple, NoReturn, Optional, Tuple import vapoursynth as vs from vsutil import get_w, get_y from .utils import has_plugin_or_raise __all__ = ( "check_difference", "save_difference", "stack_compare", "interleave_compare", "compare", ) core = vs.core class FrameDiff(NamedTuple): frame: vs.VideoNode number: int difference: float def _pad_video_length(clip_a: vs.VideoNode, clip_b: vs.VideoNode) -> Tuple[vs.VideoNode, vs.VideoNode]: clip_a_length = clip_a.num_frames clip_b_length = clip_b.num_frames if clip_a_length == clip_b_length: return clip_a, clip_b elif clip_a_length > clip_b_length: src_add = clip_a_length - clip_b_length clip_b = clip_b + (clip_b[-1] * src_add) elif clip_b_length > clip_a_length: src_add = clip_b_length - clip_a_length clip_a = clip_a + (clip_a[-1] * src_add) return clip_a, clip_b def _preprocess_clips(clip_a: vs.VideoNode, clip_b: vs.VideoNode) -> Tuple[vs.VideoNode, vs.VideoNode]: if not isinstance(clip_a, vs.VideoNode): raise TypeError("clip_a must be a clip") if not isinstance(clip_b, vs.VideoNode): raise TypeError("clip_b must be a clip") has_plugin_or_raise("fmtc") clipa_cf = clip_a.format.color_family clipb_cf = clip_b.format.color_family clipa_bits = clip_a.format.bits_per_sample clipb_bits = clip_b.format.bits_per_sample clip_a, clip_b = _pad_video_length(clip_a, clip_b) if clipa_cf != vs.RGB: clip_a = clip_a.resize.Point(format=vs.RGBS, matrix_in_s="709") if clipb_cf != vs.RGB: clip_b = clip_b.resize.Point(format=vs.RGBS, matrix_in_s="709") if clipa_bits != 8: clip_a = clip_a.fmtc.bitdepth(bits=8) if clipb_bits != 8: clip_b = clip_b.fmtc.bitdepth(bits=8) return clip_a, clip_b def _frame_yielder( clip_a: vs.VideoNode, clip_b: vs.VideoNode, threshold: float = 0.1 ) -> Generator[Tuple[int, vs.RawFrame], None, None]: clip_a_gray = clip_a.std.ShufflePlanes(0, vs.GRAY) clip_b_gray = clip_b.std.ShufflePlanes(0, vs.GRAY) frame: vs.RawFrame for num, frame in enumerate(core.std.PlaneStats(clip_a_gray, clip_b_gray).frames()): # type: ignore if frame.props["PlaneStatsDiff"] >= threshold: # type: ignore yield num, frame def check_difference( clip_a: vs.VideoNode, clip_b: vs.VideoNode, threshold: float = 0.1, ) -> NoReturn: if not hasattr(sys, "argv"): # Simple check if script are opened via VSEdit raise Exception( "check_difference: please run this vpy script via command-line (ex: python3 ./script.vpy)" ) clip_a, clip_b = _preprocess_clips(clip_a, clip_b) last_known_diff = -1 known_diff = 0 try: for num, _ in _frame_yielder(clip_a, clip_b, threshold): if last_known_diff != num: print(f"check_difference: Frame {num} is different") known_diff += 1 last_known_diff = num + 1 except KeyboardInterrupt: print("check_difference: Process interrupted") exit(1) if known_diff == 0: print(f"check_difference: No difference found (threshold: {threshold})") exit(0) def save_difference( clip_a: vs.VideoNode, clip_b: vs.VideoNode, threshold: float = 0.1, output_filename: List[str] = ["src1", "src2"], ) -> NoReturn: if not hasattr(sys, "argv"): # Simple check if script are opened via VSEdit raise Exception( "save_difference: please run this vpy script via command-line (ex: python3 ./script.vpy)" ) if len(output_filename) != 2: raise Exception("save_difference: output_filename must be a tuple of two strings") has_plugin_or_raise("imwri") clip_a, clip_b = _preprocess_clips(clip_a, clip_b) fn_a, fn_b = output_filename # Get current directory of the file filename = Path(sys.argv[0]).resolve() current_dir = filename.parent only_fn = filename.name.split(".", 1)[0] target_dir = current_dir / f"{only_fn}_frame_difference" target_dir.mkdir(exist_ok=True) differences_data: Dict[str, FrameDiff] = {} known_diff = 0 last_known_diff = -1 try: for num, frame in _frame_yielder(clip_a, clip_b, threshold): if last_known_diff != num: differences_data[f"{known_diff}_{fn_a}"] = FrameDiff( frame=clip_a[num], number=num, difference=frame.props["PlaneStatsDiff"], # type: ignore ) differences_data[f"{known_diff}_{fn_b}"] = FrameDiff( frame=clip_b[num], number=num, difference=frame.props["PlaneStatsDiff"], # type: ignore ) known_diff += 1 last_known_diff = num + 1 except KeyboardInterrupt: print("save_difference: Process interrupted") exit(1) if known_diff == 0: print(f"check_difference: No difference found (threshold: {threshold})") shutil.rmtree(str(target_dir)) exit(0) print(f"save_difference: {known_diff} differences found, saving images...") try: for filename, frame_info in differences_data.items(): print(f"save_difference: saving frame: {frame_info.number} ({frame_info.difference})") actual_target = target_dir / f"{filename} (%05d).png" out: vs.VideoNode = core.imwri.Write( frame_info.frame, imgformat="PNG", filename=str(actual_target), firstnum=frame_info.number ) out.get_frame(0) except KeyboardInterrupt: print("save_difference: Process interrupted") exit(1) exit(0) def stack_compare( clips: List[vs.VideoNode], height: Optional[int] = None, identity: bool = False, max_vertical_stack: int = 2, interleave_only: bool = False, ): """ Stack/interleave compare multiple clips. Probably inspired by LightArrowsEXE ``stack_compare`` function. Clips are stacked like this: ------------- | A | C | E | ------------- | B | D | F | ------------- -- (For max_vertical_stack = 2) etc... If clips total are missing some, it'll add an extra BlankClip. Formula: `multiples_of_max_vertical_stack[i] <= clip_total <= multiples_of_max_vertical_stack[i + 1]` If one of the clips only have `Y` plane, all other clips will be changed to use only 1 plane The total vertical clips can be modified using `max_vertical_stack` Parameters ---------- clips: :class:`List[VideoNode]` A collection of clips or sources to compare. height: :class:`Optional[int]` Resize the stacked compare into a new height. If ``interleave_only`` is ``True``, this will be ignored. identity: :class:`bool` If ``True``, there will be numbering to identify each clips. If ``interleave_only`` is ``True``, this will be ignored. max_vertical_stack: :class:`int` The maximum number of clips to stack vertically. If ``interleave_only`` is ``True``, this will be ignored. interleave_only: :class:`bool` If ``True``, the output will be an interleaved comparision. Returns ------- :class:`VideoNode` A stacked/interleaved compare of the clips. """ the_string = "ABCDEFGHIJKLMNOPQRSTUVWXYZ123456789abcefghijklmnopqrstuvwxyz" if len(clips) < 2: raise ValueError("stack_compare: please provide 2 or more clips.") has_plugin_or_raise("sub") def _fallback_str(num: int) -> str: try: return the_string[num] except IndexError: return f"Extra{num + 1}" def _generate_ident(clip_index: int, src_w: int, src_h: int) -> str: gen = r"{\an7\b1\bord5\c&H00FFFF\pos" gen += "({w}, {h})".format(w=25 * (src_w / 1920), h=25 * (src_h / 1080)) gen += r"\fs" + "{0}".format(60 * (src_h / 1080)) + r"}" gen += "Clip {0}".format(_fallback_str(clip_index)) return gen # Check for luma only clip only_use_luma = False for clip in clips: if clip.format.num_planes == 1: only_use_luma = True break if interleave_only: if only_use_luma: clips = [get_y(clip) for clip in clips] # Set identity if identity: clips = [ clip.sub.Subtitle( _generate_ident( idx, clip.width, clip.height, ) ) for idx, clip in enumerate(clips) ] return core.std.Interleave(clips, mismatch=True) def _calculate_needed_clip(max_vert: int, clip_total: int) -> int: multiples_of = list(range(max_vert, (clip_total + 1) * max_vert, max_vert)) multiples_of_total = len(multiples_of) max_needed = 1 for i in range(multiples_of_total): if i + 1 == multiples_of_total - 1: break if multiples_of[i] <= clip_total <= multiples_of[i + 1]: max_needed = multiples_of[i + 1] break return max_needed # Set YUV video to Y video if only_use_luma. if only_use_luma: clips = [get_y(clip) for clip in clips] if identity: clips = [ clip.sub.Subtitle(_generate_ident(ind, clip.width, clip.height)) for ind, clip in enumerate(clips) ] # Find needed clip for current `max_vertical_stack`. if len(clips) != max_vertical_stack: needed_clip = _calculate_needed_clip(max_vertical_stack, len(clips)) f_clip = clips[0] for _ in range(needed_clip - len(clips)): clips.append( core.std.BlankClip(f_clip).sub.Subtitle( r"{\an5\fs120\b1\pos(" + "{},{}".format(f_clip.width / 2, f_clip.height / 2) + r")}BlankClip Pad\N(Ignore)" ) ) # Split into chunks of `max_vertical_stack` and StackVertical it. # Input: [A, B, C, D, E, F, G, H] # Output: [[A, B], [C, D], [E, F], [G, H]] clips = [ core.std.StackVertical(clips[i : i + max_vertical_stack]) for i in range(0, len(clips), max_vertical_stack) ] final_clip = core.std.StackHorizontal(clips) if len(clips) > 1 else clips[0] if height: if height != final_clip.height: ar = final_clip.width / final_clip.height final_clip = final_clip.resize.Bicubic( get_w(height, ar), height, ) return final_clip interleave_compare = partial(stack_compare, interleave_only=True) compare = stack_compare
[ "vsutil.get_y", "functools.partial", "vsutil.get_w", "pathlib.Path" ]
[((11970, 12014), 'functools.partial', 'partial', (['stack_compare'], {'interleave_only': '(True)'}), '(stack_compare, interleave_only=True)\n', (11977, 12014), False, 'from functools import partial\n'), ((5132, 5149), 'pathlib.Path', 'Path', (['sys.argv[0]'], {}), '(sys.argv[0])\n', (5136, 5149), False, 'from pathlib import Path\n'), ((10587, 10598), 'vsutil.get_y', 'get_y', (['clip'], {}), '(clip)\n', (10592, 10598), False, 'from vsutil import get_w, get_y\n'), ((9559, 9570), 'vsutil.get_y', 'get_y', (['clip'], {}), '(clip)\n', (9564, 9570), False, 'from vsutil import get_w, get_y\n'), ((11868, 11885), 'vsutil.get_w', 'get_w', (['height', 'ar'], {}), '(height, ar)\n', (11873, 11885), False, 'from vsutil import get_w, get_y\n')]
# This software is open source software available under the BSD-3 license. # # Copyright (c) 2020 Triad National Security, LLC. All rights reserved. # Copyright (c) 2020 Lawrence Livermore National Security, LLC. All rights # reserved. # Copyright (c) 2020 UT-Battelle, LLC. All rights reserved. # # Additional copyright and license information can be found in the LICENSE file # distributed with this code, or at # https://raw.githubusercontent.com/MPAS-Dev/MPAS-Analysis/master/LICENSE from __future__ import absolute_import, division, print_function, \ unicode_literals from mpas_analysis.shared import AnalysisTask from mpas_analysis.shared.plot import timeseries_analysis_plot, savefig from mpas_analysis.shared.time_series import combine_time_series_with_ncrcat from mpas_analysis.shared.io import open_mpas_dataset from mpas_analysis.shared.timekeeping.utility import date_to_days, \ days_to_datetime from mpas_analysis.shared.io.utility import build_config_full_path, \ make_directories, check_path_exists from mpas_analysis.shared.html import write_image_xml class TimeSeriesSST(AnalysisTask): """ Performs analysis of the time-series output of sea-surface temperature (SST). Attributes ---------- mpasTimeSeriesTask : ``MpasTimeSeriesTask`` The task that extracts the time series from MPAS monthly output controlConfig : ``MpasAnalysisConfigParser`` Configuration options for a control run (if any) """ # Authors # ------- # <NAME>, <NAME> def __init__(self, config, mpasTimeSeriesTask, controlConfig=None): # {{{ """ Construct the analysis task. Parameters ---------- config : ``MpasAnalysisConfigParser`` Configuration options mpasTimeSeriesTask : ``MpasTimeSeriesTask`` The task that extracts the time series from MPAS monthly output controlConfig : ``MpasAnalysisConfigParser``, optional Configuration options for a control run (if any) """ # Authors # ------- # <NAME> # first, call the constructor from the base class (AnalysisTask) super(TimeSeriesSST, self).__init__( config=config, taskName='timeSeriesSST', componentName='ocean', tags=['timeSeries', 'sst', 'publicObs']) self.mpasTimeSeriesTask = mpasTimeSeriesTask self.controlConfig = controlConfig self.run_after(mpasTimeSeriesTask) # }}} def setup_and_check(self): # {{{ """ Perform steps to set up the analysis and check for errors in the setup. Raises ------ OSError If files are not present """ # Authors # ------- # <NAME> # first, call setup_and_check from the base class (AnalysisTask), # which will perform some common setup, including storing: # self.inDirectory, self.plotsDirectory, self.namelist, self.streams # self.calendar super(TimeSeriesSST, self).setup_and_check() config = self.config self.startDate = self.config.get('timeSeries', 'startDate') self.endDate = self.config.get('timeSeries', 'endDate') self.variableList = \ ['timeMonthly_avg_avgValueWithinOceanRegion_avgSurfaceTemperature'] self.mpasTimeSeriesTask.add_variables(variableList=self.variableList) if config.get('runs', 'preprocessedReferenceRunName') != 'None': check_path_exists(config.get('oceanPreprocessedReference', 'baseDirectory')) self.inputFile = self.mpasTimeSeriesTask.outputFile mainRunName = config.get('runs', 'mainRunName') regions = config.getExpression('timeSeriesSST', 'regions') self.xmlFileNames = [] self.filePrefixes = {} for region in regions: filePrefix = 'sst_{}_{}'.format(region, mainRunName) self.xmlFileNames.append('{}/{}.xml'.format(self.plotsDirectory, filePrefix)) self.filePrefixes[region] = filePrefix return # }}} def run_task(self): # {{{ """ Performs analysis of the time-series output of sea-surface temperature (SST). """ # Authors # ------- # <NAME>, <NAME> self.logger.info("\nPlotting SST time series...") self.logger.info(' Load SST data...') config = self.config calendar = self.calendar mainRunName = config.get('runs', 'mainRunName') preprocessedReferenceRunName = \ config.get('runs', 'preprocessedReferenceRunName') preprocessedInputDirectory = config.get('oceanPreprocessedReference', 'baseDirectory') movingAveragePoints = config.getint('timeSeriesSST', 'movingAveragePoints') regions = config.getExpression('regions', 'regions') plotTitles = config.getExpression('regions', 'plotTitles') regionsToPlot = config.getExpression('timeSeriesSST', 'regions') regionIndicesToPlot = [regions.index(region) for region in regionsToPlot] outputDirectory = build_config_full_path(config, 'output', 'timeseriesSubdirectory') make_directories(outputDirectory) dsSST = open_mpas_dataset(fileName=self.inputFile, calendar=calendar, variableList=self.variableList, startDate=self.startDate, endDate=self.endDate) yearStart = days_to_datetime(dsSST.Time.min(), calendar=calendar).year yearEnd = days_to_datetime(dsSST.Time.max(), calendar=calendar).year timeStart = date_to_days(year=yearStart, month=1, day=1, calendar=calendar) timeEnd = date_to_days(year=yearEnd, month=12, day=31, calendar=calendar) if self.controlConfig is not None: baseDirectory = build_config_full_path( self.controlConfig, 'output', 'timeSeriesSubdirectory') controlFileName = '{}/{}.nc'.format( baseDirectory, self.mpasTimeSeriesTask.fullTaskName) controlStartYear = self.controlConfig.getint( 'timeSeries', 'startYear') controlEndYear = self.controlConfig.getint('timeSeries', 'endYear') controlStartDate = '{:04d}-01-01_00:00:00'.format(controlStartYear) controlEndDate = '{:04d}-12-31_23:59:59'.format(controlEndYear) dsRefSST = open_mpas_dataset( fileName=controlFileName, calendar=calendar, variableList=self.variableList, startDate=controlStartDate, endDate=controlEndDate) else: dsRefSST = None if preprocessedReferenceRunName != 'None': self.logger.info(' Load in SST for a preprocesses reference ' 'run...') inFilesPreprocessed = '{}/SST.{}.year*.nc'.format( preprocessedInputDirectory, preprocessedReferenceRunName) outFolder = '{}/preprocessed'.format(outputDirectory) make_directories(outFolder) outFileName = '{}/sst.nc'.format(outFolder) combine_time_series_with_ncrcat(inFilesPreprocessed, outFileName, logger=self.logger) dsPreprocessed = open_mpas_dataset(fileName=outFileName, calendar=calendar, timeVariableNames='xtime') yearEndPreprocessed = days_to_datetime(dsPreprocessed.Time.max(), calendar=calendar).year if yearStart <= yearEndPreprocessed: dsPreprocessedTimeSlice = \ dsPreprocessed.sel(Time=slice(timeStart, timeEnd)) else: self.logger.warning('Preprocessed time series ends before the ' 'timeSeries startYear and will not be ' 'plotted.') preprocessedReferenceRunName = 'None' self.logger.info(' Make plots...') for regionIndex in regionIndicesToPlot: region = regions[regionIndex] title = '{} SST'.format(plotTitles[regionIndex]) xLabel = 'Time [years]' yLabel = r'[$\degree$C]' varName = self.variableList[0] SST = dsSST[varName].isel(nOceanRegions=regionIndex) filePrefix = self.filePrefixes[region] outFileName = '{}/{}.png'.format(self.plotsDirectory, filePrefix) lineColors = ['k'] lineWidths = [3] fields = [SST] legendText = [mainRunName] if dsRefSST is not None: refSST = dsRefSST[varName].isel(nOceanRegions=regionIndex) fields.append(refSST) lineColors.append('r') lineWidths.append(1.5) controlRunName = self.controlConfig.get('runs', 'mainRunName') legendText.append(controlRunName) if preprocessedReferenceRunName != 'None': SST_v0 = dsPreprocessedTimeSlice.SST fields.append(SST_v0) lineColors.append('purple') lineWidths.append(1.5) legendText.append(preprocessedReferenceRunName) if config.has_option(self.taskName, 'firstYearXTicks'): firstYearXTicks = config.getint(self.taskName, 'firstYearXTicks') else: firstYearXTicks = None if config.has_option(self.taskName, 'yearStrideXTicks'): yearStrideXTicks = config.getint(self.taskName, 'yearStrideXTicks') else: yearStrideXTicks = None timeseries_analysis_plot(config, fields, calendar=calendar, title=title, xlabel=xLabel, ylabel=yLabel, movingAveragePoints=movingAveragePoints, lineColors=lineColors, lineWidths=lineWidths, legendText=legendText, firstYearXTicks=firstYearXTicks, yearStrideXTicks=yearStrideXTicks) savefig(outFileName) caption = 'Running Mean of {} Sea Surface Temperature'.format( region) write_image_xml( config=config, filePrefix=filePrefix, componentName='Ocean', componentSubdirectory='ocean', galleryGroup='Time Series', groupLink='timeseries', thumbnailDescription='{} SST'.format(region), imageDescription=caption, imageCaption=caption) # }}} # }}} # vim: foldmethod=marker ai ts=4 sts=4 et sw=4 ft=python
[ "mpas_analysis.shared.plot.savefig", "mpas_analysis.shared.io.open_mpas_dataset", "mpas_analysis.shared.io.utility.make_directories", "mpas_analysis.shared.timekeeping.utility.date_to_days", "mpas_analysis.shared.time_series.combine_time_series_with_ncrcat", "mpas_analysis.shared.plot.timeseries_analysis_...
[((5396, 5462), 'mpas_analysis.shared.io.utility.build_config_full_path', 'build_config_full_path', (['config', '"""output"""', '"""timeseriesSubdirectory"""'], {}), "(config, 'output', 'timeseriesSubdirectory')\n", (5418, 5462), False, 'from mpas_analysis.shared.io.utility import build_config_full_path, make_directories, check_path_exists\n'), ((5521, 5554), 'mpas_analysis.shared.io.utility.make_directories', 'make_directories', (['outputDirectory'], {}), '(outputDirectory)\n', (5537, 5554), False, 'from mpas_analysis.shared.io.utility import build_config_full_path, make_directories, check_path_exists\n'), ((5572, 5718), 'mpas_analysis.shared.io.open_mpas_dataset', 'open_mpas_dataset', ([], {'fileName': 'self.inputFile', 'calendar': 'calendar', 'variableList': 'self.variableList', 'startDate': 'self.startDate', 'endDate': 'self.endDate'}), '(fileName=self.inputFile, calendar=calendar, variableList=\n self.variableList, startDate=self.startDate, endDate=self.endDate)\n', (5589, 5718), False, 'from mpas_analysis.shared.io import open_mpas_dataset\n'), ((6027, 6090), 'mpas_analysis.shared.timekeeping.utility.date_to_days', 'date_to_days', ([], {'year': 'yearStart', 'month': '(1)', 'day': '(1)', 'calendar': 'calendar'}), '(year=yearStart, month=1, day=1, calendar=calendar)\n', (6039, 6090), False, 'from mpas_analysis.shared.timekeeping.utility import date_to_days, days_to_datetime\n'), ((6142, 6205), 'mpas_analysis.shared.timekeeping.utility.date_to_days', 'date_to_days', ([], {'year': 'yearEnd', 'month': '(12)', 'day': '(31)', 'calendar': 'calendar'}), '(year=yearEnd, month=12, day=31, calendar=calendar)\n', (6154, 6205), False, 'from mpas_analysis.shared.timekeeping.utility import date_to_days, days_to_datetime\n'), ((6309, 6387), 'mpas_analysis.shared.io.utility.build_config_full_path', 'build_config_full_path', (['self.controlConfig', '"""output"""', '"""timeSeriesSubdirectory"""'], {}), "(self.controlConfig, 'output', 'timeSeriesSubdirectory')\n", (6331, 6387), False, 'from mpas_analysis.shared.io.utility import build_config_full_path, make_directories, check_path_exists\n'), ((6886, 7037), 'mpas_analysis.shared.io.open_mpas_dataset', 'open_mpas_dataset', ([], {'fileName': 'controlFileName', 'calendar': 'calendar', 'variableList': 'self.variableList', 'startDate': 'controlStartDate', 'endDate': 'controlEndDate'}), '(fileName=controlFileName, calendar=calendar, variableList\n =self.variableList, startDate=controlStartDate, endDate=controlEndDate)\n', (6903, 7037), False, 'from mpas_analysis.shared.io import open_mpas_dataset\n'), ((7538, 7565), 'mpas_analysis.shared.io.utility.make_directories', 'make_directories', (['outFolder'], {}), '(outFolder)\n', (7554, 7565), False, 'from mpas_analysis.shared.io.utility import build_config_full_path, make_directories, check_path_exists\n'), ((7635, 7725), 'mpas_analysis.shared.time_series.combine_time_series_with_ncrcat', 'combine_time_series_with_ncrcat', (['inFilesPreprocessed', 'outFileName'], {'logger': 'self.logger'}), '(inFilesPreprocessed, outFileName, logger=\n self.logger)\n', (7666, 7725), False, 'from mpas_analysis.shared.time_series import combine_time_series_with_ncrcat\n'), ((7794, 7883), 'mpas_analysis.shared.io.open_mpas_dataset', 'open_mpas_dataset', ([], {'fileName': 'outFileName', 'calendar': 'calendar', 'timeVariableNames': '"""xtime"""'}), "(fileName=outFileName, calendar=calendar,\n timeVariableNames='xtime')\n", (7811, 7883), False, 'from mpas_analysis.shared.io import open_mpas_dataset\n'), ((10387, 10679), 'mpas_analysis.shared.plot.timeseries_analysis_plot', 'timeseries_analysis_plot', (['config', 'fields'], {'calendar': 'calendar', 'title': 'title', 'xlabel': 'xLabel', 'ylabel': 'yLabel', 'movingAveragePoints': 'movingAveragePoints', 'lineColors': 'lineColors', 'lineWidths': 'lineWidths', 'legendText': 'legendText', 'firstYearXTicks': 'firstYearXTicks', 'yearStrideXTicks': 'yearStrideXTicks'}), '(config, fields, calendar=calendar, title=title,\n xlabel=xLabel, ylabel=yLabel, movingAveragePoints=movingAveragePoints,\n lineColors=lineColors, lineWidths=lineWidths, legendText=legendText,\n firstYearXTicks=firstYearXTicks, yearStrideXTicks=yearStrideXTicks)\n', (10411, 10679), False, 'from mpas_analysis.shared.plot import timeseries_analysis_plot, savefig\n'), ((10940, 10960), 'mpas_analysis.shared.plot.savefig', 'savefig', (['outFileName'], {}), '(outFileName)\n', (10947, 10960), False, 'from mpas_analysis.shared.plot import timeseries_analysis_plot, savefig\n')]
import sys import os.path as osp import math import torchvision.utils sys.path.append(osp.dirname(osp.dirname(osp.abspath(__file__)))) from data import create_dataloader, create_dataset # noqa: E402 from utils import util # noqa: E402 def main(): dataset = 'REDS' # REDS | Vimeo90K | DIV2K800_sub opt = {} opt['dist'] = False opt['gpu_ids'] = [0] if dataset == 'REDS': opt['name'] = 'test_REDS' opt['dataroot_GT'] = '../../datasets/REDS/train_sharp_wval.lmdb' opt['dataroot_LQ'] = '../../datasets/REDS/train_sharp_bicubic_wval.lmdb' opt['mode'] = 'REDS' opt['N_frames'] = 5 opt['phase'] = 'train' opt['use_shuffle'] = True opt['n_workers'] = 8 opt['batch_size'] = 16 opt['GT_size'] = 256 opt['LQ_size'] = 64 opt['scale'] = 4 opt['use_flip'] = True opt['use_rot'] = True opt['interval_list'] = [1] opt['random_reverse'] = False opt['border_mode'] = False opt['cache_keys'] = None opt['data_type'] = 'lmdb' # img | lmdb | mc elif dataset == 'Vimeo90K': opt['name'] = 'test_Vimeo90K' opt['dataroot_GT'] = '../../datasets/vimeo90k/vimeo90k_train_GT.lmdb' opt['dataroot_LQ'] = '../../datasets/vimeo90k/vimeo90k_train_LR7frames.lmdb' opt['mode'] = 'Vimeo90K' opt['N_frames'] = 7 opt['phase'] = 'train' opt['use_shuffle'] = True opt['n_workers'] = 8 opt['batch_size'] = 16 opt['GT_size'] = 256 opt['LQ_size'] = 64 opt['scale'] = 4 opt['use_flip'] = True opt['use_rot'] = True opt['interval_list'] = [1] opt['random_reverse'] = False opt['border_mode'] = False opt['cache_keys'] = None opt['data_type'] = 'lmdb' # img | lmdb | mc elif dataset == 'DIV2K800_sub': opt['name'] = 'DIV2K800' opt['dataroot_GT'] = '../../datasets/DIV2K/DIV2K800_sub.lmdb' opt['dataroot_LQ'] = '../../datasets/DIV2K/DIV2K800_sub_bicLRx4.lmdb' opt['mode'] = 'LQGT' opt['phase'] = 'train' opt['use_shuffle'] = True opt['n_workers'] = 8 opt['batch_size'] = 16 opt['GT_size'] = 128 opt['scale'] = 4 opt['use_flip'] = True opt['use_rot'] = True opt['color'] = 'RGB' opt['data_type'] = 'lmdb' # img | lmdb else: raise ValueError('Please implement by yourself.') util.mkdir('tmp') train_set = create_dataset(opt) train_loader = create_dataloader(train_set, opt, opt, None) nrow = int(math.sqrt(opt['batch_size'])) padding = 2 if opt['phase'] == 'train' else 0 print('start...') for i, data in enumerate(train_loader): if i > 5: break print(i) if dataset == 'REDS' or dataset == 'Vimeo90K': LQs = data['LQs'] else: LQ = data['LQ'] GT = data['GT'] if dataset == 'REDS' or dataset == 'Vimeo90K': for j in range(LQs.size(1)): torchvision.utils.save_image(LQs[:, j, :, :, :], 'tmp/LQ_{:03d}_{}.png'.format(i, j), nrow=nrow, padding=padding, normalize=False) else: torchvision.utils.save_image(LQ, 'tmp/LQ_{:03d}.png'.format(i), nrow=nrow, padding=padding, normalize=False) torchvision.utils.save_image(GT, 'tmp/GT_{:03d}.png'.format(i), nrow=nrow, padding=padding, normalize=False) if __name__ == "__main__": main()
[ "data.create_dataset", "math.sqrt", "utils.util.mkdir", "os.path.abspath", "data.create_dataloader" ]
[((2494, 2511), 'utils.util.mkdir', 'util.mkdir', (['"""tmp"""'], {}), "('tmp')\n", (2504, 2511), False, 'from utils import util\n'), ((2528, 2547), 'data.create_dataset', 'create_dataset', (['opt'], {}), '(opt)\n', (2542, 2547), False, 'from data import create_dataloader, create_dataset\n'), ((2567, 2611), 'data.create_dataloader', 'create_dataloader', (['train_set', 'opt', 'opt', 'None'], {}), '(train_set, opt, opt, None)\n', (2584, 2611), False, 'from data import create_dataloader, create_dataset\n'), ((2627, 2655), 'math.sqrt', 'math.sqrt', (["opt['batch_size']"], {}), "(opt['batch_size'])\n", (2636, 2655), False, 'import math\n'), ((111, 132), 'os.path.abspath', 'osp.abspath', (['__file__'], {}), '(__file__)\n', (122, 132), True, 'import os.path as osp\n')]
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. import re from .bucket import Bucket from .dates import Dates from .identity import Identity from .timestamps import Timestamps from .truncate import Truncate from ..types import (TypeID) """ Factory methods for transforms. <p> Most users should create transforms using a {@link PartitionSpec.Builder#builderFor(Schema)} partition spec builder}. @see PartitionSpec#builderFor(Schema) The partition spec builder. """ class Transforms(object): HAS_WIDTH = re.compile("(\\w+)\\[(\\d+)\\]") def __init__(self): pass @staticmethod def from_string(type_var, transform): match = Transforms.HAS_WIDTH.match(transform) if match is not None: name = match.group(1) w = int(match.group(2)) if name.lower() == "truncate": return Truncate.get(type_var, w) elif name.lower() == "bucket": return Bucket.get(type_var, w) if transform.lower() == "identity": return Identity.get(type_var) elif type_var.type_id == TypeID.TIMESTAMP: return Timestamps(transform.lower(), transform.lower()) elif type_var.type_id == TypeID.DATE: return Dates(transform.lower(), transform.lower()) raise RuntimeError("Unknown transform: %s" % transform) @staticmethod def identity(type_var): return Identity.get(type_var) @staticmethod def year(type_var): if type_var.type_id == TypeID.DATE: return Dates("year", "year") elif type_var.type_id == TypeID.TIMESTAMP: return Timestamps("year", "year") else: raise RuntimeError("Cannot partition type %s by year" % type_var) @staticmethod def month(type_var): if type_var.type_id == TypeID.DATE: return Dates("month", "month") elif type_var.type_id == TypeID.TIMESTAMP: return Timestamps("month", "month") else: raise RuntimeError("Cannot partition type %s by month" % type_var) @staticmethod def day(type_var): if type_var.type_id == TypeID.DATE: return Dates("day", "day") elif type_var.type_id == TypeID.TIMESTAMP: return Timestamps("day", "day") else: raise RuntimeError("Cannot partition type %s by day" % type_var) @staticmethod def hour(type_var): if type_var.type_id == TypeID.DATE: return Dates("hour", "hour") elif type_var.type_id == TypeID.TIMESTAMP: return Timestamps("hour", "hour") else: raise RuntimeError("Cannot partition type %s by hour" % type_var) @staticmethod def bucket(type_var, num_buckets): return Bucket.get(type_var, num_buckets) @staticmethod def truncate(type_var, width): return Truncate.get(type_var, width)
[ "re.compile" ]
[((1255, 1287), 're.compile', 're.compile', (['"""(\\\\w+)\\\\[(\\\\d+)\\\\]"""'], {}), "('(\\\\w+)\\\\[(\\\\d+)\\\\]')\n", (1265, 1287), False, 'import re\n')]
# Copyright (c) Trainline Limited, 2016-2017. All rights reserved. See LICENSE.txt in the project root for license information. from os.path import join import unittest from mock import patch from agent.find_deployment import find_deployment_dir_win class Fake(object): def __init__(self, **kwargs): self.__dict__.update(kwargs) class TestFindDeployment(unittest.TestCase): def test_find_deployment_dir_win_finds_none_returns_none(self): with patch('agent.find_deployment.exists', return_value=False): expected = None actual = find_deployment_dir_win('/deployments', 'my_service', 'my_deployment_id') self.assertEqual(actual, expected) def test_find_deployment_dir_win_finds_both_returns_new(self): with patch('agent.find_deployment.exists', return_value=True): expected = join('/deployments', 'my_service', 'my_deployment_id') actual = find_deployment_dir_win('/deployments', 'my_service', 'my_deployment_id') self.assertEqual(actual, expected) def test_find_deployment_dir_win_finds_old_returns_old(self): expected = join('/deployments', 'my_deployment_id') with patch('agent.find_deployment.exists', lambda x: x == expected): actual = find_deployment_dir_win('/deployments', 'my_service', 'my_deployment_id') self.assertEqual(actual, expected)
[ "agent.find_deployment.find_deployment_dir_win", "mock.patch", "os.path.join" ]
[((1144, 1184), 'os.path.join', 'join', (['"""/deployments"""', '"""my_deployment_id"""'], {}), "('/deployments', 'my_deployment_id')\n", (1148, 1184), False, 'from os.path import join\n'), ((470, 527), 'mock.patch', 'patch', (['"""agent.find_deployment.exists"""'], {'return_value': '(False)'}), "('agent.find_deployment.exists', return_value=False)\n", (475, 527), False, 'from mock import patch\n'), ((578, 651), 'agent.find_deployment.find_deployment_dir_win', 'find_deployment_dir_win', (['"""/deployments"""', '"""my_service"""', '"""my_deployment_id"""'], {}), "('/deployments', 'my_service', 'my_deployment_id')\n", (601, 651), False, 'from agent.find_deployment import find_deployment_dir_win\n'), ((780, 836), 'mock.patch', 'patch', (['"""agent.find_deployment.exists"""'], {'return_value': '(True)'}), "('agent.find_deployment.exists', return_value=True)\n", (785, 836), False, 'from mock import patch\n'), ((861, 915), 'os.path.join', 'join', (['"""/deployments"""', '"""my_service"""', '"""my_deployment_id"""'], {}), "('/deployments', 'my_service', 'my_deployment_id')\n", (865, 915), False, 'from os.path import join\n'), ((937, 1010), 'agent.find_deployment.find_deployment_dir_win', 'find_deployment_dir_win', (['"""/deployments"""', '"""my_service"""', '"""my_deployment_id"""'], {}), "('/deployments', 'my_service', 'my_deployment_id')\n", (960, 1010), False, 'from agent.find_deployment import find_deployment_dir_win\n'), ((1198, 1260), 'mock.patch', 'patch', (['"""agent.find_deployment.exists"""', '(lambda x: x == expected)'], {}), "('agent.find_deployment.exists', lambda x: x == expected)\n", (1203, 1260), False, 'from mock import patch\n'), ((1283, 1356), 'agent.find_deployment.find_deployment_dir_win', 'find_deployment_dir_win', (['"""/deployments"""', '"""my_service"""', '"""my_deployment_id"""'], {}), "('/deployments', 'my_service', 'my_deployment_id')\n", (1306, 1356), False, 'from agent.find_deployment import find_deployment_dir_win\n')]
import os import logging import argparse import numpy as np import tensorflow as tf from keras_preprocessing.text import Tokenizer from tqdm import tqdm from data import DataLoader class EmbeddingsBuilder: def __init__(self, args): logging.info('initializing...') self.args = args self.dataset = DataLoader(self.args) self.embeddings_path = args.embeddings_path self.small_embeddings_path = os.path.splitext(self.embeddings_path)[0] + '_small.vec' logging.info('initializing...[ok]') def build_embedding(self, vocab_dict): """ Load embedding vectors from a .txt file. Optionally limit the vocabulary to save memory. `vocab` should be a set. """ num_words = len(vocab_dict) num_found = 0 with open(self.small_embeddings_path, 'w') as out_file: with tf.gfile.GFile(self.embeddings_path) as f: header =next(f) num_embeddings, embeddings_dim = header.split(' ') num_embeddings = int(num_embeddings) out_file.write(header) for _, line in tqdm(enumerate(f), 'loading embeddings', total=num_embeddings): tokens = line.rstrip().split(" ") word = tokens[0] if word in vocab_dict: num_found += 1 out_file.write(line) tf.logging.info("Found embeddings for {} out of {} words in vocabulary".format(num_found, num_words)) def run(self): self.dataset.load() X = self.dataset.X_train_labeled['moment'].values X = np.append(X, self.dataset.X_train_unlabeled['moment'].values, axis=0) X = np.append(X, self.dataset.X_test['moment'].values, axis=0) tokenizer = Tokenizer() tokenizer.fit_on_texts(X) self.build_embedding(tokenizer.word_index) if __name__ == '__main__': logging.basicConfig(format='%(asctime)s %(message)s', level=logging.DEBUG) logging.info('initializing task...') parser = argparse.ArgumentParser() parser.add_argument('--data-dir', default='data/claff-happydb') parser.add_argument('--embeddings-path', type=str, default=None) parser.add_argument('--num-unlabeled', type=int, default=1000) parser.add_argument('--use-allfeats', action='store_true', default=False) parser.add_argument('--predict', action='store_true', default=True) builder = EmbeddingsBuilder(args=parser.parse_args()) builder.run() logging.info('task finished...[ok]')
[ "logging.basicConfig", "keras_preprocessing.text.Tokenizer", "argparse.ArgumentParser", "os.path.splitext", "numpy.append", "tensorflow.gfile.GFile", "logging.info", "data.DataLoader" ]
[((1951, 2025), 'logging.basicConfig', 'logging.basicConfig', ([], {'format': '"""%(asctime)s %(message)s"""', 'level': 'logging.DEBUG'}), "(format='%(asctime)s %(message)s', level=logging.DEBUG)\n", (1970, 2025), False, 'import logging\n'), ((2030, 2066), 'logging.info', 'logging.info', (['"""initializing task..."""'], {}), "('initializing task...')\n", (2042, 2066), False, 'import logging\n'), ((2080, 2105), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (2103, 2105), False, 'import argparse\n'), ((2540, 2576), 'logging.info', 'logging.info', (['"""task finished...[ok]"""'], {}), "('task finished...[ok]')\n", (2552, 2576), False, 'import logging\n'), ((248, 279), 'logging.info', 'logging.info', (['"""initializing..."""'], {}), "('initializing...')\n", (260, 279), False, 'import logging\n'), ((328, 349), 'data.DataLoader', 'DataLoader', (['self.args'], {}), '(self.args)\n', (338, 349), False, 'from data import DataLoader\n'), ((504, 539), 'logging.info', 'logging.info', (['"""initializing...[ok]"""'], {}), "('initializing...[ok]')\n", (516, 539), False, 'import logging\n'), ((1655, 1724), 'numpy.append', 'np.append', (['X', "self.dataset.X_train_unlabeled['moment'].values"], {'axis': '(0)'}), "(X, self.dataset.X_train_unlabeled['moment'].values, axis=0)\n", (1664, 1724), True, 'import numpy as np\n'), ((1737, 1795), 'numpy.append', 'np.append', (['X', "self.dataset.X_test['moment'].values"], {'axis': '(0)'}), "(X, self.dataset.X_test['moment'].values, axis=0)\n", (1746, 1795), True, 'import numpy as np\n'), ((1817, 1828), 'keras_preprocessing.text.Tokenizer', 'Tokenizer', ([], {}), '()\n', (1826, 1828), False, 'from keras_preprocessing.text import Tokenizer\n'), ((439, 477), 'os.path.splitext', 'os.path.splitext', (['self.embeddings_path'], {}), '(self.embeddings_path)\n', (455, 477), False, 'import os\n'), ((878, 914), 'tensorflow.gfile.GFile', 'tf.gfile.GFile', (['self.embeddings_path'], {}), '(self.embeddings_path)\n', (892, 914), True, 'import tensorflow as tf\n')]
""" stanCode Breakout Project Adapted from <NAME>'s Breakout by <NAME>, <NAME>, <NAME>, and <NAME> File: breakoutgraphics.py Name: <NAME> ------------------------- This python file will create a class named BreakoutGraphics for the break out game. This class will contain the building block for creating that game. """ from campy.graphics.gwindow import GWindow from campy.graphics.gobjects import GOval, GRect, GLabel from campy.gui.events.mouse import onmouseclicked, onmousemoved import random BRICK_SPACING = 5 # Space between bricks (in pixels). This space is used for horizontal and vertical spacing. BRICK_WIDTH = 40 # Height of a brick (in pixels). BRICK_HEIGHT = 15 # Height of a brick (in pixels). BRICK_ROWS = 10 # Number of rows of bricks. BRICK_COLS = 10 # Number of columns of bricks. BRICK_OFFSET = 50 # Vertical offset of the topmost brick from the window top (in pixels). BALL_RADIUS = 10 # Radius of the ball (in pixels). PADDLE_WIDTH = 75 # Width of the paddle (in pixels). PADDLE_HEIGHT = 15 # Height of the paddle (in pixels). PADDLE_OFFSET = 50 # Vertical offset of the paddle from the window bottom (in pixels). INITIAL_Y_SPEED = 7 # Initial vertical speed for the ball. MAX_X_SPEED = 5 # Maximum initial horizontal speed for the ball. class BreakoutGraphics: def __init__(self, ball_radius = BALL_RADIUS, paddle_width = PADDLE_WIDTH, paddle_height = PADDLE_HEIGHT, paddle_offset = PADDLE_OFFSET, brick_rows = BRICK_ROWS, brick_cols = BRICK_COLS, brick_width = BRICK_WIDTH, brick_height = BRICK_HEIGHT, brick_offset = BRICK_OFFSET, brick_spacing = BRICK_SPACING, title='Breakout'): """ The basic parameters for building these breakout game. :param ball_radius: The radius of the ball. :param paddle_width: The width of the paddle. :param paddle_height: The height of the paddle. :param paddle_offset: The distance between paddle and the bottom of the window. :param brick_rows: The number of rows in bricks. :param brick_cols: The number of column in bricks. :param brick_width: The width of each brick. :param brick_height: The height of each brick. :param brick_offset: The distance between the first row of bricks and the top of the window. :param brick_spacing: The spacing between each brick. :param title: The name of this program. """ # Create a graphical window, with some extra space self.window_width = brick_cols * (brick_width + brick_spacing) - brick_spacing self.window_height = brick_offset + 3 * (brick_rows * (brick_height + brick_spacing) - brick_spacing) self.window = GWindow(width=self.window_width, height=self.window_height, title=title) # Create a paddle self.paddle = GRect(paddle_width, paddle_height, x=(self.window_width-paddle_width)/2, y=(self.window_height-paddle_offset)) self.paddle.filled = True self.paddle.color = 'black' self.paddle.fill_color = 'black' self.window.add(self.paddle) self.paddle_width = paddle_width self.paddle_height = paddle_height self.paddle_offset = paddle_offset # Center a filled ball in the graphical window self.ball = GOval(ball_radius*2, ball_radius*2, x=(self.window_width-ball_radius*2)/2, y=(self.window_height-ball_radius*2)/2) self.ball.filled = True self.ball.fill_color = 'black' self.window.add(self.ball) self.ball_radius = ball_radius # Default initial velocity for the ball self.__dx = 0 # self.__dx = random.randint(1, MAX_X_SPEED) self.__dy = 0 # self.__dy = INITIAL_Y_SPEED # if random.random() > 0.5: # self.__dx = -self.__dx # The above is the mistake I made during doing this homework. # Draw bricks for i in range(brick_cols): for j in range(brick_rows): # Crucial point! This can't be placed at the outside of for loop. brick = GRect(brick_width, brick_height) brick.x = (brick_width+brick_spacing)*i brick.y = brick_offset+(brick_height+brick_spacing)*j brick.filled = True if j < 2: brick.fill_color = 'red' elif j < 4: brick.fill_color = 'orange' elif j < 6: brick.fill_color = 'yellow' elif j < 8: brick.fill_color = 'green' elif j < 10: brick.fill_color = 'blue' elif j < 12: brick.fill_color = 'teal' elif j < 14: brick.fill_color = 'chocolate' self.window.add(brick) # Initialize our mouse listeners onmouseclicked(self.is_start_game) onmousemoved(self.moving_paddle) # Total bricks self.total_bricks = brick_cols * brick_rows def is_start_game(self, event): # Crucial point!!! Stuck here for three days! The initial velocity! """ The check point of the game start. :param event: The information of the mouse, including (x,y) of it. :return: Set the __dx and __dy of the ball. """ if event.x != -1 and event.y != -1 and self.__dx == 0 and self.__dy == 0: self.__dx = random.randint(1, MAX_X_SPEED) self.__dy = INITIAL_Y_SPEED if random.random() > 0.5: self.__dx = -self.__dx def check_for_collisions(self): """ Four check points of the ball to check the collision with objects. :return: boolean value. Build the information of object that the ball collide with. """ one = self.window.get_object_at(self.ball.x, self.ball.y) two = self.window.get_object_at(self.ball.x + 2*self.ball_radius, self.ball.y) three = self.window.get_object_at(self.ball.x, self.ball.y + 2*self.ball_radius) four = self.window.get_object_at(self.ball.x + 2*self.ball_radius, self.ball.y + 2*self.ball_radius) if one is not None: self.obj = self.window.get_object_at(self.ball.x, self.ball.y) return True elif two is not None: self.obj = self.window.get_object_at(self.ball.x + 2*self.ball_radius, self.ball.y) return True elif three is not None: self.obj = self.window.get_object_at(self.ball.x, self.ball.y + 2*self.ball_radius) return True elif four is not None: self.obj = self.window.get_object_at(self.ball.x + 2*self.ball_radius, self.ball.y + 2*self.ball_radius) return True def check_object_type(self): """ The objects above the half of the window height are bricks and the object below the half of the window height is paddle. :return: boolean value. Bricks return True and paddle returns False. """ if self.ball.y > self.window.height/2: return True else: return False def moving_ball(self): """ The method for moving ball. :return: The moving result of the ball. """ self.ball.move(self.__dx, self.__dy) def moving_paddle(self, event): """ The method for moving paddle. :param event: The information of the mouse, including (x,y) of it. :return: The moving result of the paddle. """ if event.x - self.paddle_width/2 >= 0 and event.x-self.paddle_width/2 <= self.window_width-self.paddle_width: self.paddle.x = event.x - self.paddle_width / 2 def reset_ball(self): """ As the ball falls below the paddle and the game hasn't overed, the ball will be reset to the original position. :return: The ball at the original position. """ self.ball = GOval(self.ball_radius * 2, self.ball_radius * 2, x=(self.window_width - self.ball_radius * 2) / 2, y=(self.window_height - self.ball_radius * 2) / 2) self.ball.filled = True self.ball.fill_color = 'black' self.window.add(self.ball) self.ball_radius = self.ball_radius self.__dx = 0 self.__dy = 0 def set_dx(self, new_dx): """ Set the new __dx. :param new_dx: The new dx. :return: __dx. """ self.__dx = new_dx def set_dy(self, new_dy): """ Set the new __dy. :param new_dy: The new dy. :return: __dy. """ self.__dy = new_dy def get_dx(self): """ Get the information of __dx from class BreakoutGraphics. :return: The __dx for the ball. """ return self.__dx def get_dy(self): """ Get the information of __dy from class BreakoutGraphics. :return: The __dy for the ball. """ return self.__dy def set_dx_collision(self, new_dx): """ Set the new __dx for ball after colliding with bricks. :param new_dx: The new dx. :return: __dx. """ if random.random() > 0.5: self.__dx = new_dx else: self.__dx = -new_dx def game_over(self): """ The label for game over. :return: The label for game over. """ label = GLabel('Game Over!!!') # The condition below is for 10*10 bricks. # If coder change the number of rows or columns, the size would probably not fit. label.font = '-40' self.window.add(label, x= self.window_width/2 - 100, y=self.window_height/2 + 100) def game_win(self): """ The label for game win. :return: The label for game win. """ label = GLabel('You Win!!!') # The condition below is for 10*10 bricks. # If coder change the number of rows or columns, the size would probably not fit. label.font = '-40' self.window.add(label, x=self.window_width / 2 - 100, y=self.window_height / 2 + 100)
[ "campy.graphics.gobjects.GLabel", "campy.gui.events.mouse.onmousemoved", "campy.graphics.gobjects.GRect", "campy.graphics.gwindow.GWindow", "campy.graphics.gobjects.GOval", "random.random", "random.randint", "campy.gui.events.mouse.onmouseclicked" ]
[((2814, 2886), 'campy.graphics.gwindow.GWindow', 'GWindow', ([], {'width': 'self.window_width', 'height': 'self.window_height', 'title': 'title'}), '(width=self.window_width, height=self.window_height, title=title)\n', (2821, 2886), False, 'from campy.graphics.gwindow import GWindow\n'), ((2936, 3054), 'campy.graphics.gobjects.GRect', 'GRect', (['paddle_width', 'paddle_height'], {'x': '((self.window_width - paddle_width) / 2)', 'y': '(self.window_height - paddle_offset)'}), '(paddle_width, paddle_height, x=(self.window_width - paddle_width) / 2,\n y=self.window_height - paddle_offset)\n', (2941, 3054), False, 'from campy.graphics.gobjects import GOval, GRect, GLabel\n'), ((3398, 3532), 'campy.graphics.gobjects.GOval', 'GOval', (['(ball_radius * 2)', '(ball_radius * 2)'], {'x': '((self.window_width - ball_radius * 2) / 2)', 'y': '((self.window_height - ball_radius * 2) / 2)'}), '(ball_radius * 2, ball_radius * 2, x=(self.window_width - ball_radius *\n 2) / 2, y=(self.window_height - ball_radius * 2) / 2)\n', (3403, 3532), False, 'from campy.graphics.gobjects import GOval, GRect, GLabel\n'), ((5058, 5092), 'campy.gui.events.mouse.onmouseclicked', 'onmouseclicked', (['self.is_start_game'], {}), '(self.is_start_game)\n', (5072, 5092), False, 'from campy.gui.events.mouse import onmouseclicked, onmousemoved\n'), ((5101, 5133), 'campy.gui.events.mouse.onmousemoved', 'onmousemoved', (['self.moving_paddle'], {}), '(self.moving_paddle)\n', (5113, 5133), False, 'from campy.gui.events.mouse import onmouseclicked, onmousemoved\n'), ((8150, 8310), 'campy.graphics.gobjects.GOval', 'GOval', (['(self.ball_radius * 2)', '(self.ball_radius * 2)'], {'x': '((self.window_width - self.ball_radius * 2) / 2)', 'y': '((self.window_height - self.ball_radius * 2) / 2)'}), '(self.ball_radius * 2, self.ball_radius * 2, x=(self.window_width - \n self.ball_radius * 2) / 2, y=(self.window_height - self.ball_radius * 2\n ) / 2)\n', (8155, 8310), False, 'from campy.graphics.gobjects import GOval, GRect, GLabel\n'), ((9651, 9673), 'campy.graphics.gobjects.GLabel', 'GLabel', (['"""Game Over!!!"""'], {}), "('Game Over!!!')\n", (9657, 9673), False, 'from campy.graphics.gobjects import GOval, GRect, GLabel\n'), ((10072, 10092), 'campy.graphics.gobjects.GLabel', 'GLabel', (['"""You Win!!!"""'], {}), "('You Win!!!')\n", (10078, 10092), False, 'from campy.graphics.gobjects import GOval, GRect, GLabel\n'), ((5617, 5647), 'random.randint', 'random.randint', (['(1)', 'MAX_X_SPEED'], {}), '(1, MAX_X_SPEED)\n', (5631, 5647), False, 'import random\n'), ((9409, 9424), 'random.random', 'random.random', ([], {}), '()\n', (9422, 9424), False, 'import random\n'), ((4246, 4278), 'campy.graphics.gobjects.GRect', 'GRect', (['brick_width', 'brick_height'], {}), '(brick_width, brick_height)\n', (4251, 4278), False, 'from campy.graphics.gobjects import GOval, GRect, GLabel\n'), ((5703, 5718), 'random.random', 'random.random', ([], {}), '()\n', (5716, 5718), False, 'import random\n')]
# flake8: noqa """ Copyright 2021 - Present Okta, Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. """ # AUTO-GENERATED! DO NOT EDIT FILE DIRECTLY # SEE CONTRIBUTOR DOCUMENTATION from okta.okta_object import OktaObject from okta.okta_collection import OktaCollection from okta.models import profile_enrollment_policy_rule_activation_requirement\ as profile_enrollment_policy_rule_activation_requirement from okta.models import pre_registration_inline_hook\ as pre_registration_inline_hook from okta.models import profile_enrollment_policy_rule_profile_attribute\ as profile_enrollment_policy_rule_profile_attribute class ProfileEnrollmentPolicyRuleAction( OktaObject ): """ A class for ProfileEnrollmentPolicyRuleAction objects. """ def __init__(self, config=None): super().__init__(config) if config: self.access = config["access"]\ if "access" in config else None if "activationRequirements" in config: if isinstance(config["activationRequirements"], profile_enrollment_policy_rule_activation_requirement.ProfileEnrollmentPolicyRuleActivationRequirement): self.activation_requirements = config["activationRequirements"] elif config["activationRequirements"] is not None: self.activation_requirements = profile_enrollment_policy_rule_activation_requirement.ProfileEnrollmentPolicyRuleActivationRequirement( config["activationRequirements"] ) else: self.activation_requirements = None else: self.activation_requirements = None self.pre_registration_inline_hooks = OktaCollection.form_list( config["preRegistrationInlineHooks"] if "preRegistrationInlineHooks"\ in config else [], pre_registration_inline_hook.PreRegistrationInlineHook ) self.profile_attributes = OktaCollection.form_list( config["profileAttributes"] if "profileAttributes"\ in config else [], profile_enrollment_policy_rule_profile_attribute.ProfileEnrollmentPolicyRuleProfileAttribute ) self.target_group_ids = OktaCollection.form_list( config["targetGroupIds"] if "targetGroupIds"\ in config else [], str ) self.unknown_user_action = config["unknownUserAction"]\ if "unknownUserAction" in config else None else: self.access = None self.activation_requirements = None self.pre_registration_inline_hooks = [] self.profile_attributes = [] self.target_group_ids = [] self.unknown_user_action = None def request_format(self): parent_req_format = super().request_format() current_obj_format = { "access": self.access, "activationRequirements": self.activation_requirements, "preRegistrationInlineHooks": self.pre_registration_inline_hooks, "profileAttributes": self.profile_attributes, "targetGroupIds": self.target_group_ids, "unknownUserAction": self.unknown_user_action } parent_req_format.update(current_obj_format) return parent_req_format
[ "okta.okta_collection.OktaCollection.form_list", "okta.models.profile_enrollment_policy_rule_activation_requirement.ProfileEnrollmentPolicyRuleActivationRequirement" ]
[((2256, 2433), 'okta.okta_collection.OktaCollection.form_list', 'OktaCollection.form_list', (["(config['preRegistrationInlineHooks'] if 'preRegistrationInlineHooks' in\n config else [])", 'pre_registration_inline_hook.PreRegistrationInlineHook'], {}), "(config['preRegistrationInlineHooks'] if \n 'preRegistrationInlineHooks' in config else [],\n pre_registration_inline_hook.PreRegistrationInlineHook)\n", (2280, 2433), False, 'from okta.okta_collection import OktaCollection\n'), ((2530, 2727), 'okta.okta_collection.OktaCollection.form_list', 'OktaCollection.form_list', (["(config['profileAttributes'] if 'profileAttributes' in config else [])", 'profile_enrollment_policy_rule_profile_attribute.ProfileEnrollmentPolicyRuleProfileAttribute'], {}), "(config['profileAttributes'] if 'profileAttributes' in\n config else [], profile_enrollment_policy_rule_profile_attribute.\n ProfileEnrollmentPolicyRuleProfileAttribute)\n", (2554, 2727), False, 'from okta.okta_collection import OktaCollection\n'), ((2822, 2919), 'okta.okta_collection.OktaCollection.form_list', 'OktaCollection.form_list', (["(config['targetGroupIds'] if 'targetGroupIds' in config else [])", 'str'], {}), "(config['targetGroupIds'] if 'targetGroupIds' in\n config else [], str)\n", (2846, 2919), False, 'from okta.okta_collection import OktaCollection\n'), ((1876, 2017), 'okta.models.profile_enrollment_policy_rule_activation_requirement.ProfileEnrollmentPolicyRuleActivationRequirement', 'profile_enrollment_policy_rule_activation_requirement.ProfileEnrollmentPolicyRuleActivationRequirement', (["config['activationRequirements']"], {}), "(\n config['activationRequirements'])\n", (1978, 2017), True, 'from okta.models import profile_enrollment_policy_rule_activation_requirement as profile_enrollment_policy_rule_activation_requirement\n')]
import datetime import unittest import luigi import numpy as np from netCDF4 import Dataset from iasi.compression import (CompressDataset, CompressDateRange, DecompressDataset) class TestCompression(unittest.TestCase): def test_dataset_compression(self): task = CompressDataset( file='test/resources/MOTIV-single-event.nc', dst='/tmp/iasi', force=True, threshold=0.01, log_file=False ) assert luigi.build([task], local_scheduler=True) with Dataset(task.output().path) as nc: state = nc['state'] subgroups = state.groups.keys() self.assertListEqual( list(subgroups), ['GHG', 'HNO3', 'Tatm', 'Tskin', 'WV']) def test_dataset_decompression(self): task = DecompressDataset( file='test/resources/MOTIV-single-event.nc', dst='/tmp/iasi', force=True, log_file=False, compress_upstream=True ) success = luigi.build([task], local_scheduler=True) self.assertTrue(success) class TestDateInterval(unittest.TestCase): def test_date_range(self): # end date is not inclusive interval = luigi.date_interval.Custom.parse('2016-06-01-2016-06-30') task = CompressDateRange(date_interval=interval, dst='/tmp/iasi', src='test/resources') luigi.build([task], local_scheduler=True)
[ "luigi.build", "luigi.date_interval.Custom.parse", "iasi.compression.CompressDateRange", "iasi.compression.CompressDataset", "iasi.compression.DecompressDataset" ]
[((309, 435), 'iasi.compression.CompressDataset', 'CompressDataset', ([], {'file': '"""test/resources/MOTIV-single-event.nc"""', 'dst': '"""/tmp/iasi"""', 'force': '(True)', 'threshold': '(0.01)', 'log_file': '(False)'}), "(file='test/resources/MOTIV-single-event.nc', dst=\n '/tmp/iasi', force=True, threshold=0.01, log_file=False)\n", (324, 435), False, 'from iasi.compression import CompressDataset, CompressDateRange, DecompressDataset\n'), ((516, 557), 'luigi.build', 'luigi.build', (['[task]'], {'local_scheduler': '(True)'}), '([task], local_scheduler=True)\n', (527, 557), False, 'import luigi\n'), ((847, 983), 'iasi.compression.DecompressDataset', 'DecompressDataset', ([], {'file': '"""test/resources/MOTIV-single-event.nc"""', 'dst': '"""/tmp/iasi"""', 'force': '(True)', 'log_file': '(False)', 'compress_upstream': '(True)'}), "(file='test/resources/MOTIV-single-event.nc', dst=\n '/tmp/iasi', force=True, log_file=False, compress_upstream=True)\n", (864, 983), False, 'from iasi.compression import CompressDataset, CompressDateRange, DecompressDataset\n'), ((1067, 1108), 'luigi.build', 'luigi.build', (['[task]'], {'local_scheduler': '(True)'}), '([task], local_scheduler=True)\n', (1078, 1108), False, 'import luigi\n'), ((1274, 1331), 'luigi.date_interval.Custom.parse', 'luigi.date_interval.Custom.parse', (['"""2016-06-01-2016-06-30"""'], {}), "('2016-06-01-2016-06-30')\n", (1306, 1331), False, 'import luigi\n'), ((1347, 1432), 'iasi.compression.CompressDateRange', 'CompressDateRange', ([], {'date_interval': 'interval', 'dst': '"""/tmp/iasi"""', 'src': '"""test/resources"""'}), "(date_interval=interval, dst='/tmp/iasi', src='test/resources'\n )\n", (1364, 1432), False, 'from iasi.compression import CompressDataset, CompressDateRange, DecompressDataset\n'), ((1436, 1477), 'luigi.build', 'luigi.build', (['[task]'], {'local_scheduler': '(True)'}), '([task], local_scheduler=True)\n', (1447, 1477), False, 'import luigi\n')]
# Copyright 2019 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. #!/usr/bin/python3 """ Coral Smart Bird Feeder Uses ClassificationEngine from the EdgeTPU API to analyze animals in camera frames. Sounds a deterrent if a squirrel is detected. Users define model, labels file, storage path, deterrent sound, and optionally can set this to training mode for collecting images for a custom model. """ import argparse import time import logging from PIL import Image from playsound import playsound from pycoral.utils.dataset import read_label_file from pycoral.utils.edgetpu import make_interpreter from pycoral.adapters import common from pycoral.adapters.classify import get_classes import gstreamer def save_data(image, results, path, ext='png'): """Saves camera frame and model inference results to user-defined storage directory.""" tag = '%010d' % int(time.monotonic()*1000) name = '%s/img-%s.%s' % (path, tag, ext) image.save(name) print('Frame saved as: %s' % name) logging.info('Image: %s Results: %s', tag, results) def print_results(start_time, last_time, end_time, results): """Print results to terminal for debugging.""" inference_rate = ((end_time - start_time) * 1000) fps = (1.0/(end_time - last_time)) print('\nInference: %.2f ms, FPS: %.2f fps' % (inference_rate, fps)) for label, score in results: print(' %s, score=%.2f' % (label, score)) def do_training(results, last_results, top_k): """Compares current model results to previous results and returns true if at least one label difference is detected. Used to collect images for training a custom model.""" new_labels = [label[0] for label in results] old_labels = [label[0] for label in last_results] shared_labels = set(new_labels).intersection(old_labels) if len(shared_labels) < top_k: print('Difference detected') return True return False def user_selections(): parser = argparse.ArgumentParser() parser.add_argument('--model', required=True, help='.tflite model path') parser.add_argument('--labels', required=True, help='label file path') parser.add_argument('--videosrc', help='Which video source to use', default='/dev/video0') parser.add_argument('--top_k', type=int, default=3, help='number of classes with highest score to display') parser.add_argument('--threshold', type=float, default=0.1, help='class score threshold') parser.add_argument('--storage', required=True, help='File path to store images and results') parser.add_argument('--sound', required=True, help='File path to deterrent sound') parser.add_argument('--print', default=False, required=False, help='Print inference results to terminal') parser.add_argument('--training', action='store_true', help='Training mode for image collection') args = parser.parse_args() return args def main(): """Creates camera pipeline, and pushes pipeline through ClassificationEngine model. Logs results to user-defined storage. Runs either in training mode to gather images for custom model creation or in deterrent mode that sounds an 'alarm' if a defined label is detected.""" args = user_selections() print("Loading %s with %s labels." % (args.model, args.labels)) interpreter = make_interpreter(args.model) interpreter.allocate_tensors() labels = read_label_file(args.labels) input_tensor_shape = interpreter.get_input_details()[0]['shape'] if (input_tensor_shape.size != 4 or input_tensor_shape[0] != 1): raise RuntimeError( 'Invalid input tensor shape! Expected: [1, height, width, channel]') output_tensors = len(interpreter.get_output_details()) if output_tensors != 1: raise ValueError( ('Classification model should have 1 output tensor only!' 'This model has {}.'.format(output_tensors))) storage_dir = args.storage # Initialize logging file logging.basicConfig(filename='%s/results.log' % storage_dir, format='%(asctime)s-%(message)s', level=logging.DEBUG) last_time = time.monotonic() last_results = [('label', 0)] def user_callback(image, svg_canvas): nonlocal last_time nonlocal last_results start_time = time.monotonic() common.set_resized_input( interpreter, image.size, lambda size: image.resize(size, Image.NEAREST)) interpreter.invoke() results = get_classes(interpreter, args.top_k, args.threshold) end_time = time.monotonic() play_sounds = [labels[i] for i, score in results] results = [(labels[i], score) for i, score in results] if args.print: print_results(start_time, last_time, end_time, results) if args.training: if do_training(results, last_results, args.top_k): save_data(image, results, storage_dir) else: # Custom model mode: # The labels can be modified to detect/deter user-selected items if len(results): if results[0][0] != 'background': save_data(image, results, storage_dir) if FOX_SQUIRREL_LABEL in play_sounds: playsound(args.sound) logging.info('Deterrent sounded') last_results = results last_time = end_time gstreamer.run_pipeline(user_callback, videosrc=args.videosrc) if __name__ == '__main__': FOX_SQUIRREL_LABEL = 'fox squirrel, eastern fox squirrel, Sciurus niger' main()
[ "logging.basicConfig", "pycoral.utils.dataset.read_label_file", "argparse.ArgumentParser", "pycoral.utils.edgetpu.make_interpreter", "time.monotonic", "playsound.playsound", "pycoral.adapters.classify.get_classes", "logging.info", "gstreamer.run_pipeline" ]
[((1518, 1569), 'logging.info', 'logging.info', (['"""Image: %s Results: %s"""', 'tag', 'results'], {}), "('Image: %s Results: %s', tag, results)\n", (1530, 1569), False, 'import logging\n'), ((2477, 2502), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (2500, 2502), False, 'import argparse\n'), ((4010, 4038), 'pycoral.utils.edgetpu.make_interpreter', 'make_interpreter', (['args.model'], {}), '(args.model)\n', (4026, 4038), False, 'from pycoral.utils.edgetpu import make_interpreter\n'), ((4087, 4115), 'pycoral.utils.dataset.read_label_file', 'read_label_file', (['args.labels'], {}), '(args.labels)\n', (4102, 4115), False, 'from pycoral.utils.dataset import read_label_file\n'), ((4683, 4803), 'logging.basicConfig', 'logging.basicConfig', ([], {'filename': "('%s/results.log' % storage_dir)", 'format': '"""%(asctime)s-%(message)s"""', 'level': 'logging.DEBUG'}), "(filename='%s/results.log' % storage_dir, format=\n '%(asctime)s-%(message)s', level=logging.DEBUG)\n", (4702, 4803), False, 'import logging\n'), ((4863, 4879), 'time.monotonic', 'time.monotonic', ([], {}), '()\n', (4877, 4879), False, 'import time\n'), ((6131, 6192), 'gstreamer.run_pipeline', 'gstreamer.run_pipeline', (['user_callback'], {'videosrc': 'args.videosrc'}), '(user_callback, videosrc=args.videosrc)\n', (6153, 6192), False, 'import gstreamer\n'), ((5035, 5051), 'time.monotonic', 'time.monotonic', ([], {}), '()\n', (5049, 5051), False, 'import time\n'), ((5218, 5270), 'pycoral.adapters.classify.get_classes', 'get_classes', (['interpreter', 'args.top_k', 'args.threshold'], {}), '(interpreter, args.top_k, args.threshold)\n', (5229, 5270), False, 'from pycoral.adapters.classify import get_classes\n'), ((5290, 5306), 'time.monotonic', 'time.monotonic', ([], {}), '()\n', (5304, 5306), False, 'import time\n'), ((1386, 1402), 'time.monotonic', 'time.monotonic', ([], {}), '()\n', (1400, 1402), False, 'import time\n'), ((5994, 6015), 'playsound.playsound', 'playsound', (['args.sound'], {}), '(args.sound)\n', (6003, 6015), False, 'from playsound import playsound\n'), ((6032, 6065), 'logging.info', 'logging.info', (['"""Deterrent sounded"""'], {}), "('Deterrent sounded')\n", (6044, 6065), False, 'import logging\n')]
import unittest import uuid from memory.client import MemoryClient from hailtop.aiocloud.aiogoogle import GoogleStorageAsyncFS from hailtop.config import get_user_config from hailtop.utils import async_to_blocking from gear.cloud_config import get_gcp_config PROJECT = get_gcp_config().project class BlockingMemoryClient: def __init__(self, gcs_project=None, fs=None, deploy_config=None, session=None, headers=None, _token=None): self._client = MemoryClient(gcs_project, fs, deploy_config, session, headers, _token) async_to_blocking(self._client.async_init()) def _get_file_if_exists(self, filename): return async_to_blocking(self._client._get_file_if_exists(filename)) def read_file(self, filename): return async_to_blocking(self._client.read_file(filename)) def write_file(self, filename, data): return async_to_blocking(self._client.write_file(filename, data)) def close(self): return async_to_blocking(self._client.close()) class Tests(unittest.TestCase): def setUp(self): bucket_name = get_user_config().get('batch', 'bucket') token = uuid.uuid4() self.test_path = f'gs://{bucket_name}/memory-tests/{token}' self.fs = GoogleStorageAsyncFS(project=PROJECT) self.client = BlockingMemoryClient(fs=self.fs) self.temp_files = set() def tearDown(self): async_to_blocking(self.fs.rmtree(None, self.test_path)) self.client.close() async def add_temp_file_from_string(self, name: str, str_value: bytes): handle = f'{self.test_path}/{name}' async with await self.fs.create(handle) as f: await f.write(str_value) return handle def test_non_existent(self): for _ in range(3): self.assertIsNone(self.client._get_file_if_exists(f'{self.test_path}/nonexistent')) def test_small_write_around(self): async def read(url): async with await self.fs.open(url) as f: return await f.read() cases = [('empty_file', b''), ('null', b'\0'), ('small', b'hello world')] for file, data in cases: handle = async_to_blocking(self.add_temp_file_from_string(file, data)) expected = async_to_blocking(read(handle)) self.assertEqual(expected, data) i = 0 cached = self.client._get_file_if_exists(handle) while cached is None and i < 10: cached = self.client._get_file_if_exists(handle) i += 1 self.assertEqual(cached, expected) def test_small_write_through(self): cases = [('empty_file2', b''), ('null2', b'\0'), ('small2', b'hello world')] for file, data in cases: filename = f'{self.test_path}/{file}' self.client.write_file(filename, data) cached = self.client._get_file_if_exists(filename) self.assertEqual(cached, data)
[ "memory.client.MemoryClient", "gear.cloud_config.get_gcp_config", "uuid.uuid4", "hailtop.aiocloud.aiogoogle.GoogleStorageAsyncFS", "hailtop.config.get_user_config" ]
[((272, 288), 'gear.cloud_config.get_gcp_config', 'get_gcp_config', ([], {}), '()\n', (286, 288), False, 'from gear.cloud_config import get_gcp_config\n'), ((462, 532), 'memory.client.MemoryClient', 'MemoryClient', (['gcs_project', 'fs', 'deploy_config', 'session', 'headers', '_token'], {}), '(gcs_project, fs, deploy_config, session, headers, _token)\n', (474, 532), False, 'from memory.client import MemoryClient\n'), ((1140, 1152), 'uuid.uuid4', 'uuid.uuid4', ([], {}), '()\n', (1150, 1152), False, 'import uuid\n'), ((1240, 1277), 'hailtop.aiocloud.aiogoogle.GoogleStorageAsyncFS', 'GoogleStorageAsyncFS', ([], {'project': 'PROJECT'}), '(project=PROJECT)\n', (1260, 1277), False, 'from hailtop.aiocloud.aiogoogle import GoogleStorageAsyncFS\n'), ((1083, 1100), 'hailtop.config.get_user_config', 'get_user_config', ([], {}), '()\n', (1098, 1100), False, 'from hailtop.config import get_user_config\n')]
import librosa import numpy as np from . import base from . import spectral class OnsetStrength(base.Computation): """ Compute a spectral flux onset strength envelope. Based on http://librosa.github.io/librosa/generated/librosa.onset.onset_strength.html Args: n_mels (int): Number of mel bands to generate. """ def __init__(self, n_mels=128, parent=None, name=None): super(OnsetStrength, self).__init__(left_context=1, right_context=0, parent=parent, name=name) self.n_mels = n_mels def compute(self, chunk, sampling_rate, corpus=None, utterance=None): # Compute mel-spetrogram power_spec = np.abs(spectral.stft_from_frames(chunk.data.T)) ** 2 mel = np.abs(librosa.feature.melspectrogram(S=power_spec, n_mels=self.n_mels, sr=sampling_rate)) mel_power = librosa.power_to_db(mel) # Compute onset strengths oenv = librosa.onset.onset_strength(S=mel_power, center=False) # Switch dimensions and add dimension to have frames oenv = oenv.T.reshape(oenv.shape[0], -1) # Remove context oenv = oenv[chunk.left_context:oenv.shape[0] - chunk.right_context] return oenv
[ "librosa.onset.onset_strength", "librosa.power_to_db", "librosa.feature.melspectrogram" ]
[((845, 869), 'librosa.power_to_db', 'librosa.power_to_db', (['mel'], {}), '(mel)\n', (864, 869), False, 'import librosa\n'), ((920, 975), 'librosa.onset.onset_strength', 'librosa.onset.onset_strength', ([], {'S': 'mel_power', 'center': '(False)'}), '(S=mel_power, center=False)\n', (948, 975), False, 'import librosa\n'), ((741, 828), 'librosa.feature.melspectrogram', 'librosa.feature.melspectrogram', ([], {'S': 'power_spec', 'n_mels': 'self.n_mels', 'sr': 'sampling_rate'}), '(S=power_spec, n_mels=self.n_mels, sr=\n sampling_rate)\n', (771, 828), False, 'import librosa\n')]
from PyQt5.QtWidgets import QMainWindow, QApplication, QFileDialog import sys from .readNanoscopeForceRamps import * import matplotlib.pyplot as plt from ..qt5_ui_files.ForceRampGUI import * from matplotlib.backends.backend_qt5agg import (NavigationToolbar2QT as NavigationToolbar) import os import math from ..qt5_ui_files.mplwidget1plot import mplwidget1plot class forceRampGUI(QMainWindow): signal1 = QtCore.pyqtSignal(float) signal2 = QtCore.pyqtSignal(float) def __init__(self): super().__init__() self.ui = Ui_ForceRampGUI() self.ui.setupUi(self) self.ui.pushButtonSendVi.clicked.connect(self.sendVi) self.ui.pushButtonSendVf.clicked.connect(self.sendVf) self.ui.pushButtonGetValue.clicked.connect(self.getValue) MplToolbar = NavigationToolbar(self.ui.widget.canvas, self) self.addToolBar(MplToolbar) filename = QFileDialog.getOpenFileNames( self, "Open File", os.getcwd(), "All Files (*)")[0][0] self.rampObject = NanoscopeRamp(filename) self.rampObject.readHeader() self.rampObject.readRamps() self.plotRamp() def getValue(self): x1,x2 = self.ui.widget.canvas.axes.get_xlim() condition = np.logical_and((self.rampObject.Ramp[0]['RawX']>x1),(self.rampObject.Ramp[0]['RawX']<x2)) if self.ui.radioButtonForward.isChecked() == True: yf = self.rampObject.Ramp[0]['RawY'][0][condition] self.ui.lineEditValue.setText(str(format(yf.mean(),'.3f'))) elif self.ui.radioButtonBackward.isChecked() == True: yb = self.rampObject.Ramp[0]['RawY'][1][condition] self.ui.lineEditValue.setText(str(format(yb.mean(),'.3f'))) else: yf = self.rampObject.Ramp[0]['RawY'][0][condition] yb = self.rampObject.Ramp[0]['RawY'][1][condition] y2 = (yf+yb)/2 self.ui.lineEditValue.setText(str(format(y2.mean(),'.3f'))) QtCore.pyqtSlot() def sendVi(self): value = float(self.ui.lineEditValue.text()) self.signal1.emit(value) QtCore.pyqtSlot() def sendVf(self): value = float(self.ui.lineEditValue.text()) self.signal2.emit(value) def plotRamp(self): self.ui.widget.canvas.axes.clear() self.ui.widget.canvas.axes.plot(self.rampObject.Ramp[0]['RawX'], self.rampObject.Ramp[0]['RawY'][0][:]) self.ui.widget.canvas.axes.plot(self.rampObject.Ramp[0]['RawX'], self.rampObject.Ramp[1]['RawY'][1][:]) self.ui.widget.canvas.axes.set_ylabel('Photodiode Vertical Signal (V)') self.ui.widget.canvas.axes.set_xlabel('Sample Displacement (nm)') self.ui.widget.canvas.figure.tight_layout() self.ui.widget.canvas.draw()
[ "matplotlib.backends.backend_qt5agg.NavigationToolbar2QT", "os.getcwd" ]
[((751, 797), 'matplotlib.backends.backend_qt5agg.NavigationToolbar2QT', 'NavigationToolbar', (['self.ui.widget.canvas', 'self'], {}), '(self.ui.widget.canvas, self)\n', (768, 797), True, 'from matplotlib.backends.backend_qt5agg import NavigationToolbar2QT as NavigationToolbar\n'), ((893, 904), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (902, 904), False, 'import os\n')]
"""Create your tests for the admin app here.""" import pytest from django.contrib.auth import get_user_model from django.urls import reverse pytestmark = pytest.mark.django_db User = get_user_model() class TestUserAdmin: """Test the admin interface.""" def test_changelist(self, admin_client): """Test the changelist view.""" url = reverse("admin:users_user_changelist") response = admin_client.get(url) assert response.status_code == 200 def test_search(self, admin_client): """Test the search functionality.""" url = reverse("admin:users_user_changelist") response = admin_client.get(url, data={"q": "test"}) assert response.status_code == 200 def test_add(self, admin_client): """Test the add user functionality.""" url = reverse("admin:users_user_add") response = admin_client.get(url) assert response.status_code == 200 def test_view_user(self, admin_client): """Test the view user functionality.""" user = User.objects.get(username="admin") url = reverse("admin:users_user_change", kwargs={"object_id": user.pk}) response = admin_client.get(url) assert response.status_code == 200
[ "django.contrib.auth.get_user_model", "django.urls.reverse" ]
[((184, 200), 'django.contrib.auth.get_user_model', 'get_user_model', ([], {}), '()\n', (198, 200), False, 'from django.contrib.auth import get_user_model\n'), ((360, 398), 'django.urls.reverse', 'reverse', (['"""admin:users_user_changelist"""'], {}), "('admin:users_user_changelist')\n", (367, 398), False, 'from django.urls import reverse\n'), ((584, 622), 'django.urls.reverse', 'reverse', (['"""admin:users_user_changelist"""'], {}), "('admin:users_user_changelist')\n", (591, 622), False, 'from django.urls import reverse\n'), ((827, 858), 'django.urls.reverse', 'reverse', (['"""admin:users_user_add"""'], {}), "('admin:users_user_add')\n", (834, 858), False, 'from django.urls import reverse\n'), ((1100, 1165), 'django.urls.reverse', 'reverse', (['"""admin:users_user_change"""'], {'kwargs': "{'object_id': user.pk}"}), "('admin:users_user_change', kwargs={'object_id': user.pk})\n", (1107, 1165), False, 'from django.urls import reverse\n')]
from flask_apispec import MethodResource, marshal_with, doc, use_kwargs from webargs import fields from ..models import Dataset from ..core import cache from .utils import first_or_404 from ..schemas.dataset import DatasetSchema class DatasetResource(MethodResource): @doc(tags=['dataset'], summary='Get dataset by id.') @cache.cached(60 * 60 * 24 * 300, query_string=True) @marshal_with(DatasetSchema) def get(self, dataset_id): return first_or_404(Dataset.query.filter_by(id=dataset_id)) class DatasetListResource(MethodResource): @doc(tags=['dataset'], summary='Returns list of datasets.') @use_kwargs({ 'active_only': fields.Boolean( missing=True, description="Return only active Datasets") }, location='query') @cache.cached(60 * 60 * 24 * 300, query_string=True) @marshal_with(DatasetSchema( many=True, exclude=['dataset_address', 'preproc_address', 'runs'])) def get(self, **kwargs): query = {} if kwargs.pop('active_only'): query['active'] = True return Dataset.query.filter_by(**query).all()
[ "flask_apispec.marshal_with", "flask_apispec.doc", "webargs.fields.Boolean" ]
[((275, 326), 'flask_apispec.doc', 'doc', ([], {'tags': "['dataset']", 'summary': '"""Get dataset by id."""'}), "(tags=['dataset'], summary='Get dataset by id.')\n", (278, 326), False, 'from flask_apispec import MethodResource, marshal_with, doc, use_kwargs\n'), ((389, 416), 'flask_apispec.marshal_with', 'marshal_with', (['DatasetSchema'], {}), '(DatasetSchema)\n', (401, 416), False, 'from flask_apispec import MethodResource, marshal_with, doc, use_kwargs\n'), ((566, 624), 'flask_apispec.doc', 'doc', ([], {'tags': "['dataset']", 'summary': '"""Returns list of datasets."""'}), "(tags=['dataset'], summary='Returns list of datasets.')\n", (569, 624), False, 'from flask_apispec import MethodResource, marshal_with, doc, use_kwargs\n'), ((666, 737), 'webargs.fields.Boolean', 'fields.Boolean', ([], {'missing': '(True)', 'description': '"""Return only active Datasets"""'}), "(missing=True, description='Return only active Datasets')\n", (680, 737), False, 'from webargs import fields\n')]
import numpy as np from graph_tiger.graphs import o4_graph, p4_graph, c4_graph, k4_1_graph, k4_2_graph from graph_tiger.graphs import two_c4_0_bridge, two_c4_1_bridge, two_c4_2_bridge, two_c4_3_bridge from graph_tiger.measures import run_measure def test_measures(): measure_ground_truth = { # graph order: o4, p4, c4, k4_1, c4_0, c4_1, c4_2, c4_3 'node_connectivity': [0, 1, 2, 2, 3, 0, 1, 1, 1], 'edge_connectivity': [0, 1, 2, 2, 3, 0, 1, 1, 1], 'diameter': [None, 3, 2, 2, 1, None, 5, 5, 5], 'average_distance': [None, 1.67, 1.33, 1.17, 1, None, 2.29, 2.29, 2.29], 'average_inverse_distance': [0, 0.72, 0.83, 0.92, 1.0, 0.36, 0.58, 0.58, 0.58], 'average_vertex_betweenness': [0, 4, 3.5, 3.25, 3, 3.5, 11.5, None, None], 'average_edge_betweenness': [0, 3.33, 2.0, 1.4, 1, 2, 7.11, 7.11, 7.11], 'average_clustering_coefficient': [0, 0, 0, 0.83, 1, 0, 0, None, None], 'largest_connected_component': [1, 4, 4, 4, 4, 4, 8, 8, 8], 'spectral_radius': [0, 1.62, 2, 2.56, 3, 2, 2.34, 2.9, 3.65], 'spectral_gap': [0, 1, 2, 2.56, 4, 0, 0.53, 1.19, 2], 'natural_connectivity': [0, 0.65, 0.87, 1.29, 1.67, 0.87, 0.97, 1.28, 1.81], 'spectral_scaling': [None, 7.18, 7.28, 0.17, 0.09, None, None, 7.04, 6.93], 'generalized_robustness_index': [None, 7.18, 7.28, 0.17, 0.09, None, None, 7.04, 6.93], 'algebraic_connectivity': [0, 0.59, 2, 2, 4, 0, 0.29, 0.4, 0.45], 'number_spanning_trees': [0, 1, 4, 8, 16, 0, 16, 32, 48], 'effective_resistance': [np.inf, 10, 5, 4, 3, np.inf, 46, 38, 35.33] } graphs = [o4_graph(), p4_graph(), c4_graph(), k4_1_graph(), k4_2_graph(), two_c4_0_bridge(), two_c4_1_bridge(), two_c4_2_bridge(), two_c4_3_bridge()] for measure_name, graph_values in measure_ground_truth.items(): for idx, graph in enumerate(graphs): value = run_measure(graph, measure_name) if value is not None: value = round(value, 2) # print(idx, measure_name, value) assert (value, graph_values[idx]) def main(): test_measures() if __name__ == '__main__': main()
[ "graph_tiger.graphs.two_c4_1_bridge", "graph_tiger.graphs.c4_graph", "graph_tiger.graphs.two_c4_2_bridge", "graph_tiger.graphs.two_c4_0_bridge", "graph_tiger.graphs.two_c4_3_bridge", "graph_tiger.graphs.k4_1_graph", "graph_tiger.graphs.k4_2_graph", "graph_tiger.measures.run_measure", "graph_tiger.gr...
[((1647, 1657), 'graph_tiger.graphs.o4_graph', 'o4_graph', ([], {}), '()\n', (1655, 1657), False, 'from graph_tiger.graphs import o4_graph, p4_graph, c4_graph, k4_1_graph, k4_2_graph\n'), ((1659, 1669), 'graph_tiger.graphs.p4_graph', 'p4_graph', ([], {}), '()\n', (1667, 1669), False, 'from graph_tiger.graphs import o4_graph, p4_graph, c4_graph, k4_1_graph, k4_2_graph\n'), ((1671, 1681), 'graph_tiger.graphs.c4_graph', 'c4_graph', ([], {}), '()\n', (1679, 1681), False, 'from graph_tiger.graphs import o4_graph, p4_graph, c4_graph, k4_1_graph, k4_2_graph\n'), ((1683, 1695), 'graph_tiger.graphs.k4_1_graph', 'k4_1_graph', ([], {}), '()\n', (1693, 1695), False, 'from graph_tiger.graphs import o4_graph, p4_graph, c4_graph, k4_1_graph, k4_2_graph\n'), ((1697, 1709), 'graph_tiger.graphs.k4_2_graph', 'k4_2_graph', ([], {}), '()\n', (1707, 1709), False, 'from graph_tiger.graphs import o4_graph, p4_graph, c4_graph, k4_1_graph, k4_2_graph\n'), ((1725, 1742), 'graph_tiger.graphs.two_c4_0_bridge', 'two_c4_0_bridge', ([], {}), '()\n', (1740, 1742), False, 'from graph_tiger.graphs import two_c4_0_bridge, two_c4_1_bridge, two_c4_2_bridge, two_c4_3_bridge\n'), ((1744, 1761), 'graph_tiger.graphs.two_c4_1_bridge', 'two_c4_1_bridge', ([], {}), '()\n', (1759, 1761), False, 'from graph_tiger.graphs import two_c4_0_bridge, two_c4_1_bridge, two_c4_2_bridge, two_c4_3_bridge\n'), ((1763, 1780), 'graph_tiger.graphs.two_c4_2_bridge', 'two_c4_2_bridge', ([], {}), '()\n', (1778, 1780), False, 'from graph_tiger.graphs import two_c4_0_bridge, two_c4_1_bridge, two_c4_2_bridge, two_c4_3_bridge\n'), ((1782, 1799), 'graph_tiger.graphs.two_c4_3_bridge', 'two_c4_3_bridge', ([], {}), '()\n', (1797, 1799), False, 'from graph_tiger.graphs import two_c4_0_bridge, two_c4_1_bridge, two_c4_2_bridge, two_c4_3_bridge\n'), ((1936, 1968), 'graph_tiger.measures.run_measure', 'run_measure', (['graph', 'measure_name'], {}), '(graph, measure_name)\n', (1947, 1968), False, 'from graph_tiger.measures import run_measure\n')]
"""Association mining -- apriori algo""" __author__ = 'thor' from numpy import * # Modified from: # <NAME> & <NAME> (https://github.com/cse40647/cse40647/blob/sp.14/10%20-%20Apriori.ipynb) # # Itself Modified from: # <NAME> (https://gist.github.com/marcelcaraciolo/1423287) # # Functions to compute and extract association rules from a given frequent # itemset generated by the Apriori algorithm. import pandas as pd from statsmodels.stats.proportion import samplesize_confint_proportion def choose_sample_size(min_confidence, alpha=0.05, half_length=None): if half_length is None: t = 0.20 * min_confidence if min_confidence < 0.5 else 0.20 * (1 - min_confidence) half_length = max(0.01, t) # choose half length to be a proportion (0.2) of min_confidence return samplesize_confint_proportion( proportion=min_confidence, half_length=half_length, alpha=alpha, method='normal') def association_rules(dataset, min_confidence=0.2, min_support=None, output='dataframe', verbose=False): assert min_confidence > 0 and min_confidence <= 1, "min_confidence must be between 0 and 1" if min_support is None: # if no min_support is given, choose it to be the sample size you need to get 95% conf in proportion estimate min_support = choose_sample_size(min_confidence, alpha=0.05, half_length=None) if min_support > 1: min_support /= float(len(dataset)) F, support_data = apriori(dataset, min_support=min_support, verbose=False) H = generate_rules(F, support_data, min_confidence=min_confidence, verbose=verbose) if output == 'triple': return H elif output == 'dataframe': def set_to_string(s): return str(", ".join(s)) support_df = pd.DataFrame({'condition': list(map(set_to_string, list(support_data.keys()))), 'condition_frequency': list(support_data.values())}) support_df['condition_count'] = len(dataset) * support_df['condition_frequency'] d = pd.DataFrame([{'condition': set_to_string(condition), 'effect': set_to_string(effect), 'effect_frequency': support} for condition, effect, support in H]) d = pd.merge(d, support_df, how='inner', on='condition') d['condition_and_effect_count'] = d['effect_frequency'] * d['condition_count'] d = d[['condition', 'effect', 'effect_frequency', 'condition_count', 'condition_and_effect_count', 'condition_frequency']] return d.sort('effect_frequency', ascending=False).reset_index(drop=True) def apriori(dataset, min_support=0.5, verbose=False): """Implements the Apriori algorithm. The Apriori algorithm will iteratively generate new candidate k-itemsets using the frequent (k-1)-itemsets found in the previous iteration. Parameters ---------- dataset : list The dataset (a list of transactions) from which to generate candidate itemsets. min_support : float The minimum support threshold. Defaults to 0.5. Returns ------- F : list The list of frequent itemsets. support_data : dict The support data for all candidate itemsets. References ---------- .. [1] <NAME>, <NAME>, "Fast Algorithms for Mining Association Rules", 1994. """ C1 = create_candidates(dataset) D = list(map(set, dataset)) F1, support_data = support_prune(D, C1, min_support, verbose=False) # prune candidate 1-itemsets F = [F1] # list of frequent itemsets; initialized to frequent 1-itemsets k = 2 # the itemset cardinality while (len(F[k - 2]) > 0): Ck = apriori_gen(F[k-2], k) # generate candidate itemsets Fk, supK = support_prune(D, Ck, min_support) # prune candidate itemsets support_data.update(supK) # update the support counts to reflect pruning F.append(Fk) # add the pruned candidate itemsets to the list of frequent itemsets k += 1 if verbose: # Print a list of all the frequent itemsets. for kset in F: for item in kset: print(("" \ + "{" \ + "".join(str(i) + ", " for i in iter(item)).rstrip(', ') \ + "}" \ + ": sup = " + str(round(support_data[item], 3)))) return F, support_data def create_candidates(dataset, verbose=False): """Creates a list of candidate 1-itemsets from a list of transactions. Parameters ---------- dataset : list The dataset (a list of transactions) from which to generate candidate itemsets. Returns ------- The list of candidate itemsets (c1) passed as a frozenset (a set that is immutable and hashable). """ c1 = [] # list of all items in the database of transactions for transaction in dataset: for item in transaction: if not [item] in c1: c1.append([item]) c1.sort() if verbose: # Print a list of all the candidate items. print(("" \ + "{" \ + "".join(str(i[0]) + ", " for i in iter(c1)).rstrip(', ') \ + "}")) # Map c1 to a frozenset because it will be the key of a dictionary. return list(map(frozenset, c1)) def support_prune(dataset, candidates, min_support, verbose=False): """Returns all candidate itemsets that meet a minimum support threshold. By the apriori principle, if an itemset is frequent, then all of its subsets must also be frequent. As a result, we can perform support-based pruning to systematically control the exponential growth of candidate itemsets. Thus, itemsets that do not meet the minimum support level are pruned from the input list of itemsets (dataset). Parameters ---------- dataset : list The dataset (a list of transactions) from which to generate candidate itemsets. candidates : frozenset The list of candidate itemsets. min_support : float The minimum support threshold. Returns ------- retlist : list The list of frequent itemsets. support_data : dict The support data for all candidate itemsets. """ sscnt = {} # set for support counts for tid in dataset: for can in candidates: if can.issubset(tid): sscnt.setdefault(can, 0) sscnt[can] += 1 num_items = float(len(dataset)) # total number of transactions in the dataset retlist = [] # array for unpruned itemsets support_data = {} # set for support data for corresponding itemsets for key in sscnt: # Calculate the support of itemset key. support = sscnt[key] / num_items if support >= min_support: retlist.insert(0, key) support_data[key] = support # Print a list of the pruned itemsets. if verbose: for kset in retlist: for item in kset: print(("{" + str(item) + "}")) print("") for key in sscnt: print(("" \ + "{" \ + "".join([str(i) + ", " for i in iter(key)]).rstrip(', ') \ + "}" \ + ": sup = " + str(support_data[key]))) return retlist, support_data def apriori_gen(freq_sets, k): """Generates candidate itemsets (via the F_k-1 x F_k-1 method). This operation generates new candidate k-itemsets based on the frequent (k-1)-itemsets found in the previous iteration. The candidate generation procedure merges a pair of frequent (k-1)-itemsets only if their first k-2 items are identical. Parameters ---------- freq_sets : list The list of frequent (k-1)-itemsets. k : integer The cardinality of the current itemsets being evaluated. Returns ------- retlist : list The list of merged frequent itemsets. """ retList = [] # list of merged frequent itemsets lenLk = len(freq_sets) # number of frequent itemsets for i in range(lenLk): for j in range(i+1, lenLk): a=list(freq_sets[i]) b=list(freq_sets[j]) a.sort() b.sort() F1 = a[:k-2] # first k-2 items of freq_sets[i] F2 = b[:k-2] # first k-2 items of freq_sets[j] if F1 == F2: # if the first k-2 items are identical # Merge the frequent itemsets. retList.append(freq_sets[i] | freq_sets[j]) return retList def rules_from_conseq(freq_set, H, support_data, rules, min_confidence=0.5, verbose=False): """Generates a set of candidate rules. Parameters ---------- freq_set : frozenset The complete list of frequent itemsets. H : list A list of frequent itemsets (of a particular length). support_data : dict The support data for all candidate itemsets. rules : list A potentially incomplete set of candidate rules above the minimum confidence threshold. min_confidence : float The minimum confidence threshold. Defaults to 0.5. """ m = len(H[0]) if m == 1: Hmp1 = calc_confidence(freq_set, H, support_data, rules, min_confidence, verbose) if (len(freq_set) > (m+1)): Hmp1 = apriori_gen(H, m+1) # generate candidate itemsets Hmp1 = calc_confidence(freq_set, Hmp1, support_data, rules, min_confidence, verbose) if len(Hmp1) > 1: # If there are candidate rules above the minimum confidence # threshold, recurse on the list of these candidate rules. rules_from_conseq(freq_set, Hmp1, support_data, rules, min_confidence, verbose) def calc_confidence(freq_set, H, support_data, rules, min_confidence=0.5, verbose=False): """Evaluates the generated rules. One measurement for quantifying the goodness of association rules is confidence. The confidence for a rule 'P implies H' (P -> H) is defined as the support for P and H divided by the support for P (support (P|H) / support(P)), where the | symbol denotes the set union (thus P|H means all the items in set P or in set H). To calculate the confidence, we iterate through the frequent itemsets and associated support data. For each frequent itemset, we divide the support of the itemset by the support of the antecedent (left-hand-side of the rule). Parameters ---------- freq_set : frozenset The complete list of frequent itemsets. H : list A list of frequent itemsets (of a particular length). min_support : float The minimum support threshold. rules : list A potentially incomplete set of candidate rules above the minimum confidence threshold. min_confidence : float The minimum confidence threshold. Defaults to 0.5. Returns ------- pruned_H : list The list of candidate rules above the minimum confidence threshold. """ pruned_H = [] # list of candidate rules above the minimum confidence threshold for conseq in H: # iterate over the frequent itemsets conf = support_data[freq_set] / support_data[freq_set - conseq] if conf >= min_confidence: rules.append((freq_set - conseq, conseq, conf)) pruned_H.append(conseq) if verbose: print(("" \ + "{" \ + "".join([str(i) + ", " for i in iter(freq_set-conseq)]).rstrip(', ') \ + "}" \ + " ---> " \ + "{" \ + "".join([str(i) + ", " for i in iter(conseq)]).rstrip(', ') \ + "}" \ + ": conf = " + str(round(conf, 3)) \ + ", sup = " + str(round(support_data[freq_set], 3)))) return pruned_H def generate_rules(F, support_data, min_confidence=0.5, verbose=True): """Generates a set of candidate rules from a list of frequent itemsets. For each frequent itemset, we calculate the confidence of using a particular item as the rule consequent (right-hand-side of the rule). By testing and merging the remaining rules, we recursively create a list of pruned rules. Parameters ---------- F : list A list of frequent itemsets. support_data : dict The corresponding support data for the frequent itemsets (L). min_confidence : float The minimum confidence threshold. Defaults to 0.5. Returns ------- rules : list The list of candidate rules above the minimum confidence threshold. """ rules = [] for i in range(1, len(F)): for freq_set in F[i]: H1 = [frozenset([itemset]) for itemset in freq_set] if (i > 1): rules_from_conseq(freq_set, H1, support_data, rules, min_confidence, verbose) else: calc_confidence(freq_set, H1, support_data, rules, min_confidence, verbose) return rules
[ "statsmodels.stats.proportion.samplesize_confint_proportion", "pandas.merge" ]
[((795, 911), 'statsmodels.stats.proportion.samplesize_confint_proportion', 'samplesize_confint_proportion', ([], {'proportion': 'min_confidence', 'half_length': 'half_length', 'alpha': 'alpha', 'method': '"""normal"""'}), "(proportion=min_confidence, half_length=\n half_length, alpha=alpha, method='normal')\n", (824, 911), False, 'from statsmodels.stats.proportion import samplesize_confint_proportion\n'), ((2300, 2352), 'pandas.merge', 'pd.merge', (['d', 'support_df'], {'how': '"""inner"""', 'on': '"""condition"""'}), "(d, support_df, how='inner', on='condition')\n", (2308, 2352), True, 'import pandas as pd\n')]
try: from setuptools import setup except ImportError: from distutils.core import setup setup( description='Tech@NYU API Python Client', author='TechatNYU', url='https://github.com/TechAtNYU/pytnyu', author_email='<EMAIL>', version='0.0.4', install_requires=['requests'], namespace_packages=['pytnyu'], packages=['pytnyu'], name='pytnyu', )
[ "distutils.core.setup" ]
[((96, 359), 'distutils.core.setup', 'setup', ([], {'description': '"""Tech@NYU API Python Client"""', 'author': '"""TechatNYU"""', 'url': '"""https://github.com/TechAtNYU/pytnyu"""', 'author_email': '"""<EMAIL>"""', 'version': '"""0.0.4"""', 'install_requires': "['requests']", 'namespace_packages': "['pytnyu']", 'packages': "['pytnyu']", 'name': '"""pytnyu"""'}), "(description='Tech@NYU API Python Client', author='TechatNYU', url=\n 'https://github.com/TechAtNYU/pytnyu', author_email='<EMAIL>', version=\n '0.0.4', install_requires=['requests'], namespace_packages=['pytnyu'],\n packages=['pytnyu'], name='pytnyu')\n", (101, 359), False, 'from distutils.core import setup\n')]
import spidev columns = [0x1,0x2,0x3,0x4,0x5,0x6,0x7,0x8] LEDOn = [0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF] LEDOff = [0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0] LEDEmoteSmile = [0x0,0x0,0x24,0x0,0x42,0x3C,0x0,0x0] LEDEmoteSad = [0x0,0x0,0x24,0x0,0x0,0x3C,0x42,0x0] LEDEmoteTongue = [0x0,0x0,0x24,0x0,0x42,0x3C,0xC,0x0] LEDEmoteSurprise = [0x0,0x0,0x24,0x0,0x18,0x24,0x24,0x18] spi = None def setup(robot_config): global LEDEmoteSmile global LEDEmoteSad global LEDEmoteTongue global LEDEmoteSuprise global module global spi #LED controlling spi = spidev.SpiDev() spi.open(0,0) #VCC -> RPi Pin 2 #GND -> RPi Pin 6 #DIN -> RPi Pin 19 #CLK -> RPi Pin 23 #CS -> RPi Pin 24 # decoding:BCD spi.writebytes([0x09]) spi.writebytes([0x00]) # Start with low brightness spi.writebytes([0x0a]) spi.writebytes([0x03]) # scanlimit; 8 LEDs spi.writebytes([0x0b]) spi.writebytes([0x07]) # Enter normal power-mode spi.writebytes([0x0c]) spi.writebytes([0x01]) # Activate display spi.writebytes([0x0f]) spi.writebytes([0x00]) rotate = robot_config.getint('max7219', 'ledrotate') if rotate == 180: LEDEmoteSmile = LEDEmoteSmile[::-1] LEDEmoteSad = LEDEmoteSad[::-1] LEDEmoteTongue = LEDEmoteTongue[::-1] LEDEmoteSurprise = LEDEmoteSurprise[::-1] SetLED_Off() def SetLED_On(): for i in range(len(columns)): spi.xfer([columns[i],LEDOn[i]]) def SetLED_Off(): for i in range(len(columns)): spi.xfer([columns[i],LEDOff[i]]) def SetLED_E_Smiley(): for i in range(len(columns)): spi.xfer([columns[i],LEDEmoteSmile[i]]) def SetLED_E_Sad(): for i in range(len(columns)): spi.xfer([columns[i],LEDEmoteSad[i]]) def SetLED_E_Tongue(): for i in range(len(columns)): spi.xfer([columns[i],LEDEmoteTongue[i]]) def SetLED_E_Surprised(): for i in range(len(columns)): spi.xfer([columns[i],LEDEmoteSurprise[i]]) def SetLED_Low(): # brightness MIN spi.writebytes([0x0a]) spi.writebytes([0x00]) def SetLED_Med(): #brightness MED spi.writebytes([0x0a]) spi.writebytes([0x06]) def SetLED_Full(): # brightness MAX spi.writebytes([0x0a]) spi.writebytes([0x0F]) def move(args): command = args['command'] if command == 'LED_OFF': SetLED_Off() if command == 'LED_FULL': SetLED_On() SetLED_Full() if command == 'LED_MED': SetLED_On() SetLED_Med() if command == 'LED_LOW': SetLED_On() SetLED_Low() if command == 'LED_E_SMILEY': SetLED_On() SetLED_E_Smiley() if command == 'LED_E_SAD': SetLED_On() SetLED_E_Sad() if command == 'LED_E_TONGUE': SetLED_On() SetLED_E_Tongue() if command == 'LED_E_SURPRISED': SetLED_On() SetLED_E_Suprised()
[ "spidev.SpiDev" ]
[((576, 591), 'spidev.SpiDev', 'spidev.SpiDev', ([], {}), '()\n', (589, 591), False, 'import spidev\n')]
#!/usr/bin/env python from datapackage_pipelines.wrapper import ingest, spew import logging, collections from pipeline_params import get_pipeline_param_rows from google.cloud import storage from contextlib import contextmanager from tempfile import mkdtemp import os import pywikibot import time from pywikibot.pagegenerators import GeneratorFactory import datetime from pywikibot.specialbots import UploadRobot from pywikibot.data.api import APIError import sys from datapackage import Package LICENSE_TEMPLATE = "PD-Israel" SUPPORTED_TEMPLATE = "Supported by Wikimedia Israel|year=2018" FILES_CATEGORY = "Files from JNF uploaded by Wikimedia Israel" FILES_CATEGORY_ID = "Files_from_JNF_uploaded_by_Wikimedia_Israel" DESCRIPTION_TEMPLATE=lambda description, datestring, source, author, jnfnum: """=={{int:filedesc}}== {{Information |description={{he|1=__DESCRIPTION__}} |date=__DATESTRING__ |source={{he|1=__SOURCE__}} |author={{he|1=__AUTHOR__}} |permission= |other versions= |other fields={{Information field|Name=JNF Number|Value=__JNFNUM__}} }} =={{int:license-header}}== {{__LICENSE__}} {{__SUPPORTED__}} [[Category:__FILESCAT__]]""".replace("__DATESTRING__", datestring) \ .replace("__SOURCE__", source) \ .replace("__AUTHOR__", author) \ .replace("__JNFNUM__", jnfnum) \ .replace("__DESCRIPTION__", description) \ .replace("__LICENSE__", LICENSE_TEMPLATE) \ .replace("__SUPPORTED__", SUPPORTED_TEMPLATE) \ .replace("__FILESCAT__", FILES_CATEGORY) \ @contextmanager def temp_dir(*args, **kwargs): dir = mkdtemp(*args, **kwargs) try: yield dir except Exception: if os.path.exists(dir): os.rmdir(dir) raise @contextmanager def temp_file(*args, **kwargs): with temp_dir(*args, **kwargs) as dir: file = os.path.join(dir, "temp") try: yield file except Exception: if os.path.exists(file): os.unlink(file) raise @contextmanager def throttle(delay_seconds=None): delay_seconds = int(os.environ.get("THROTTLE_SECONDS", "1")) if not delay_seconds else delay_seconds if hasattr(throttle, 'last_call'): seconds_since_last_call = (datetime.datetime.now() - throttle.last_call).seconds if seconds_since_last_call < delay_seconds: logging.info("throttling {} seconds...".format(delay_seconds - seconds_since_last_call)) time.sleep(delay_seconds - seconds_since_last_call) yield throttle.last_call = datetime.datetime.now() def delete_page(page): with throttle(): page.delete(reason="Deleting duplicated images created by bot", prompt=True, mark=True) def get_gcs_bucket(consts): logging.info("uploading from google storage bucket {}".format(consts["gcs_bucket"])) gcs = storage.Client.from_service_account_json(consts["gcs_secret_file"]) return gcs.get_bucket(consts["gcs_bucket"]) def init_stats(): stats = {} stats["num eligible for download"] = 0 stats["invalid resolution"] = 0 stats["invalid description"] = 0 stats["invalid source"] = 0 stats["invalid year"] = 0 stats["in skip list"] = 0 stats["skipped start at"] = 0 stats['invalid image_path'] = 0 return stats def get_donum_from_row(row): return row["image_path"].replace("/ArchiveTazlumim/TopSmlPathArc/Do", "").replace(".jpeg", "") def is_valid_row(row, stats): if row["width_px"] * row["height_px"] < 200 * 200: stats["invalid resolution"] += 1 logging.info('invalid resolution: {} X {}'.format(row["width_px"], row["height_px"])) return False elif len(row["description"]) < 3: stats["invalid description"] += 1 logging.info('invalid description: {}'.format(row["description"])) return False elif len(row["source"]) < 2: stats["invalid source"] += 1 logging.info('invalid source: {}'.format(row["source"])) return False elif row["date"].year > 1947: stats["invalid year"] += 1 logging.info('invalid year: {}'.format(row["date"])) return False elif 'mi:' in row['image_path']: stats['invalid image_path'] += 1 logging.info('invalid image path: {}'.format(row['image_path'])) return False else: stats["num eligible for download"] += 1 return True # def load_datapackage_resources(resources, stats): # logging.info("Loading datapackage resources...") # donums = {} # start_at_donum = False # reached_start_at = False # for resource in resources: # for row_num, row in enumerate(resource, start=1): # donum = get_donum_from_row(row) # if start_at_donum and not reached_start_at and donum != start_at_donum: # stats["skipped start at"] += 1 # elif is_valid_row(row, stats): # if start_at_donum and donum == start_at_donum: # reached_start_at = True # donums[donum] = row # stats["num eligible for download"] += 1 # return donums def upload(consts, parameters, row, donum, stats, retry_num=0): if is_valid_row(row, stats): if os.environ.get('WIKISCRAPER_DRY_RUN'): site = None else: site = pywikibot.Site() site.login() gcs_bucket = get_gcs_bucket(consts) blob = gcs_bucket.blob("data/kkl/images" + row["image_path"]) with temp_file() as filename: blob.download_to_filename(filename) logging.info(os.path.getsize(filename)) page_title = row["description"][:100] + "-JNF{}.jpeg".format(donum) logging.info("page_title={}".format(page_title)) if os.environ.get('WIKISCRAPER_DRY_RUN'): page = None else: page = pywikibot.FilePage(site, page_title) assert page.site.family == 'commons', 'invalid page site: {}'.format(page.site) page_text = DESCRIPTION_TEMPLATE(row["description"], str(row["date"]), 'ארכיון הצילומים של קק"ל', row["source"], donum) if os.environ.get('WIKISCRAPER_DRY_RUN'): logging.info(" -- {} -- \n{}".format(filename, page_text)) else: with throttle(): if not page.exists(): page.text = page_text if page.upload(filename, comment="uploaded by wmilbot", ignore_warnings=True): logging.info("uploaded successfully") else: raise Exception("Upload failed") else: page.get() page.text = page_text page.save(summary='update by wmilbot') return True, '' else: return True, 'invalid row' def ingest_spew(): raise NotImplementedError # parameters, datapackage, resources = ingest() # parameters = next(get_pipeline_param_rows(parameters["pipeline-id"], parameters["pipeline-parameters"])) # consts = next(get_pipeline_param_rows('constants', 'kkl-parameters.csv')) # gcs_bucket = get_gcs_bucket(consts) # stats = init_stats() # for donum, row in load_datapackage_resources(resources, stats).items(): # success, error = upload(gcs_bucket, parameters, row, donum) # assert success # spew(dict(datapackage, resources=[]), []) def cli_upload(consts, parameters, start_donum=None, upload_limit=1): reached_start_at = False if start_donum else True num_uploaded = 0 package = Package('final-data/kkl/extended-metadata/datapackage.json') stats = init_stats() for row in package.get_resource('kkl').iter(keyed=True): donum = get_donum_from_row(row) if reached_start_at or donum == start_donum: reached_start_at = True success, error = upload(consts, parameters, row, donum, stats) if success: num_uploaded += 1 if upload_limit > 0 and num_uploaded >= upload_limit: break stats['num processed'] = num_uploaded stats['last donum'] = donum print(stats) def cli(): parameters = next(get_pipeline_param_rows('kkl-wikicommons-upload', 'kkl-parameters.csv')) consts = next(get_pipeline_param_rows('constants', 'kkl-parameters.csv')) if len(sys.argv) > 2: if sys.argv[2] == 'upload': if len(sys.argv) > 3: if sys.argv[3] == 'all': cli_upload(consts, parameters, None, 0) else: cli_upload(consts, parameters, sys.argv[3]) else: cli_upload(consts, parameters) if sys.argv[2] == 'upload-after': cli_upload(consts, parameters, sys.argv[3], upload_limit=int(sys.argv[4]) if len(sys.argv) > 4 else 1) if len(sys.argv) > 1 and sys.argv[1] == '--cli': cli() else: ingest_spew()
[ "os.path.exists", "os.path.getsize", "pywikibot.Site", "google.cloud.storage.Client.from_service_account_json", "datapackage.Package", "pipeline_params.get_pipeline_param_rows", "pywikibot.FilePage", "os.path.join", "os.environ.get", "time.sleep", "datetime.datetime.now", "os.rmdir", "tempfi...
[((1717, 1741), 'tempfile.mkdtemp', 'mkdtemp', (['*args'], {}), '(*args, **kwargs)\n', (1724, 1741), False, 'from tempfile import mkdtemp\n'), ((2683, 2706), 'datetime.datetime.now', 'datetime.datetime.now', ([], {}), '()\n', (2704, 2706), False, 'import datetime\n'), ((2978, 3045), 'google.cloud.storage.Client.from_service_account_json', 'storage.Client.from_service_account_json', (["consts['gcs_secret_file']"], {}), "(consts['gcs_secret_file'])\n", (3018, 3045), False, 'from google.cloud import storage\n'), ((7849, 7909), 'datapackage.Package', 'Package', (['"""final-data/kkl/extended-metadata/datapackage.json"""'], {}), "('final-data/kkl/extended-metadata/datapackage.json')\n", (7856, 7909), False, 'from datapackage import Package\n'), ((1971, 1996), 'os.path.join', 'os.path.join', (['dir', '"""temp"""'], {}), "(dir, 'temp')\n", (1983, 1996), False, 'import os\n'), ((5373, 5410), 'os.environ.get', 'os.environ.get', (['"""WIKISCRAPER_DRY_RUN"""'], {}), "('WIKISCRAPER_DRY_RUN')\n", (5387, 5410), False, 'import os\n'), ((8472, 8543), 'pipeline_params.get_pipeline_param_rows', 'get_pipeline_param_rows', (['"""kkl-wikicommons-upload"""', '"""kkl-parameters.csv"""'], {}), "('kkl-wikicommons-upload', 'kkl-parameters.csv')\n", (8495, 8543), False, 'from pipeline_params import get_pipeline_param_rows\n'), ((8563, 8621), 'pipeline_params.get_pipeline_param_rows', 'get_pipeline_param_rows', (['"""constants"""', '"""kkl-parameters.csv"""'], {}), "('constants', 'kkl-parameters.csv')\n", (8586, 8621), False, 'from pipeline_params import get_pipeline_param_rows\n'), ((1802, 1821), 'os.path.exists', 'os.path.exists', (['dir'], {}), '(dir)\n', (1816, 1821), False, 'import os\n'), ((2222, 2261), 'os.environ.get', 'os.environ.get', (['"""THROTTLE_SECONDS"""', '"""1"""'], {}), "('THROTTLE_SECONDS', '1')\n", (2236, 2261), False, 'import os\n'), ((2596, 2647), 'time.sleep', 'time.sleep', (['(delay_seconds - seconds_since_last_call)'], {}), '(delay_seconds - seconds_since_last_call)\n', (2606, 2647), False, 'import time\n'), ((5469, 5485), 'pywikibot.Site', 'pywikibot.Site', ([], {}), '()\n', (5483, 5485), False, 'import pywikibot\n'), ((5919, 5956), 'os.environ.get', 'os.environ.get', (['"""WIKISCRAPER_DRY_RUN"""'], {}), "('WIKISCRAPER_DRY_RUN')\n", (5933, 5956), False, 'import os\n'), ((6352, 6389), 'os.environ.get', 'os.environ.get', (['"""WIKISCRAPER_DRY_RUN"""'], {}), "('WIKISCRAPER_DRY_RUN')\n", (6366, 6389), False, 'import os\n'), ((1835, 1848), 'os.rmdir', 'os.rmdir', (['dir'], {}), '(dir)\n', (1843, 1848), False, 'import os\n'), ((2074, 2094), 'os.path.exists', 'os.path.exists', (['file'], {}), '(file)\n', (2088, 2094), False, 'import os\n'), ((2377, 2400), 'datetime.datetime.now', 'datetime.datetime.now', ([], {}), '()\n', (2398, 2400), False, 'import datetime\n'), ((5736, 5761), 'os.path.getsize', 'os.path.getsize', (['filename'], {}), '(filename)\n', (5751, 5761), False, 'import os\n'), ((6027, 6063), 'pywikibot.FilePage', 'pywikibot.FilePage', (['site', 'page_title'], {}), '(site, page_title)\n', (6045, 6063), False, 'import pywikibot\n'), ((2112, 2127), 'os.unlink', 'os.unlink', (['file'], {}), '(file)\n', (2121, 2127), False, 'import os\n'), ((6736, 6773), 'logging.info', 'logging.info', (['"""uploaded successfully"""'], {}), "('uploaded successfully')\n", (6748, 6773), False, 'import logging, collections\n')]
#!/usr/bin/python # -*- coding: UTF-8 -* from db.it.db_it_mgr import it_mgr __all__ = {"itSingleton"} class itSingleton(): def get_cmd_sql(self, sql): return it_mgr.get_cmd_sql(sql) it_singleton = itSingleton()
[ "db.it.db_it_mgr.it_mgr.get_cmd_sql" ]
[((177, 200), 'db.it.db_it_mgr.it_mgr.get_cmd_sql', 'it_mgr.get_cmd_sql', (['sql'], {}), '(sql)\n', (195, 200), False, 'from db.it.db_it_mgr import it_mgr\n')]
#!/usr/bin/env python3 # Copyright (c) 2019, AT&T Intellectual Property. # All rights reserved. # # SPDX-License-Identifier: LGPL-2.1-only # """ Unit-tests for the qos_config.py module. """ from vyatta.res_grp.res_grp_config import ResGrpConfig TEST_DATA = { 'vyatta-resources-v1:resources': { 'vyatta-resources-group-misc-v1:group': { 'vyatta-resources-dscp-group-v1:dscp-group': [ { 'group-name': 'group-a', 'dscp': [ '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14', '15' ] }, { 'group-name': 'group-b', 'dscp': [ '16', '17', '18', '19', '20', '21', '22', '23', '24', '25', '26', '27', '28', '29', '30', '31' ] }, { 'group-name': 'group-c', 'dscp': [ '32', '33', '34', '35', '36', '37', '38', '39', '40', '41', '42', '43', '44', '45', '46', '47' ] }, { 'group-name': 'group-d', 'dscp': [ '48', '49', '50', '51', '52', '53', '54', '55', '56', '57', '58', '59', '60', '61', '62', '63' ] } ] } } } def test_rgconfig(): """ Simple unit-test for the ResGrpConfig class """ config = ResGrpConfig(TEST_DATA) assert config is not None assert len(config.dscp_groups) == 4 assert config.get_dscp_group("group-a") is not None assert config.get_dscp_group("group-b") is not None assert config.get_dscp_group("group-c") is not None assert config.get_dscp_group("group-d") is not None assert config.get_dscp_group("group-e") is None
[ "vyatta.res_grp.res_grp_config.ResGrpConfig" ]
[((1584, 1607), 'vyatta.res_grp.res_grp_config.ResGrpConfig', 'ResGrpConfig', (['TEST_DATA'], {}), '(TEST_DATA)\n', (1596, 1607), False, 'from vyatta.res_grp.res_grp_config import ResGrpConfig\n')]
import pytest import json import numpy as np @pytest.mark.parametrize("candidate, expected", [ (1.345, True), (-4.554, True), ('9999', True) ]) def test_number_please(candidate, expected): from hrm_code import number_please assert number_please(candidate) == expected def test_import_data(): from hrm_code import import_data [time, voltage] = import_data("test_data/test_data2.csv") assert time[0] == 0 assert voltage[0] == -0.345 def test_calc_duration(): from hrm_code import calc_duration fake_time = [0, 1, 2, 3, 4.3, 5, 6, 7.2] dur = calc_duration(fake_time) assert dur == 7.2 def test_find_min_max_volt(): from hrm_code import find_max_min_volt fake_voltage = [1.2, -0.3, 4.8, 0, -3] both = find_max_min_volt(fake_voltage) assert both == [-3, 4.8] def test_calc_freq(): from hrm_code import calc_sample_freq fake_time = [0, 0.5, 1, 1.5, 2] fs = calc_sample_freq(fake_time) assert fs == 2 def test_detect_peak(): from hrm_code import detect_peak # Peaks should occur every 60 sec fs = 60 t = np.arange(0, 5, 1/fs) wave = abs(np.sin(t*np.pi)**20) peaks = detect_peak(wave, fs, hrw=0.1) assert peaks == [27, 87, 147, 207, 267] def test_num_beat(): from hrm_code import num_beat fake_peaklist = [1, 3, 4] fake_time = [0, 0.5, 1, 1.5, 2, 2.5, 3] [num_beats, beats] = num_beat(fake_time, fake_peaklist) assert num_beats == 3 assert beats == [0.5, 1.5, 2] def test_calc_bpm(): from hrm_code import calc_bpm fake_num_beats = 20 fake_dur = 40 bpm = calc_bpm(fake_num_beats, fake_dur) assert bpm == 30 def test_create_metrics(): from hrm_code import create_metrics bpm = 70 both = [-1.4, 5.6] dur = 30 num_beats = 80 beats = [0.5, 0.75, 0.8] metrics = create_metrics(bpm, beats, both, dur, num_beats) assert metrics == { "mean_hr_bpm": 70, "voltage extremes": [-1.4, 5.6], "duration": 30, "num_beats": 80, "beats": [0.5, 0.75, 0.8] } def test_create_jason(): from hrm_code import create_jason metrics = {"Favorite Ice Cream Flavor": "Chocolate", "Favorite Book": "A Tree Grows in Brooklyn", "Favorite Number": 8} filename = "test_output.csv" create_jason(filename, metrics) read_file = json.load(open('test_output.json')) assert read_file == {"Favorite Ice Cream Flavor": "Chocolate", "Favorite Book": "A Tree Grows in Brooklyn", "Favorite Number": 8}
[ "hrm_code.num_beat", "hrm_code.detect_peak", "hrm_code.number_please", "pytest.mark.parametrize", "hrm_code.import_data", "hrm_code.calc_bpm", "hrm_code.create_jason", "hrm_code.find_max_min_volt", "hrm_code.calc_sample_freq", "numpy.sin", "hrm_code.create_metrics", "numpy.arange", "hrm_code...
[((48, 148), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""candidate, expected"""', "[(1.345, True), (-4.554, True), ('9999', True)]"], {}), "('candidate, expected', [(1.345, True), (-4.554, \n True), ('9999', True)])\n", (71, 148), False, 'import pytest\n'), ((375, 414), 'hrm_code.import_data', 'import_data', (['"""test_data/test_data2.csv"""'], {}), "('test_data/test_data2.csv')\n", (386, 414), False, 'from hrm_code import import_data\n'), ((593, 617), 'hrm_code.calc_duration', 'calc_duration', (['fake_time'], {}), '(fake_time)\n', (606, 617), False, 'from hrm_code import calc_duration\n'), ((769, 800), 'hrm_code.find_max_min_volt', 'find_max_min_volt', (['fake_voltage'], {}), '(fake_voltage)\n', (786, 800), False, 'from hrm_code import find_max_min_volt\n'), ((941, 968), 'hrm_code.calc_sample_freq', 'calc_sample_freq', (['fake_time'], {}), '(fake_time)\n', (957, 968), False, 'from hrm_code import calc_sample_freq\n'), ((1109, 1132), 'numpy.arange', 'np.arange', (['(0)', '(5)', '(1 / fs)'], {}), '(0, 5, 1 / fs)\n', (1118, 1132), True, 'import numpy as np\n'), ((1179, 1209), 'hrm_code.detect_peak', 'detect_peak', (['wave', 'fs'], {'hrw': '(0.1)'}), '(wave, fs, hrw=0.1)\n', (1190, 1209), False, 'from hrm_code import detect_peak\n'), ((1410, 1444), 'hrm_code.num_beat', 'num_beat', (['fake_time', 'fake_peaklist'], {}), '(fake_time, fake_peaklist)\n', (1418, 1444), False, 'from hrm_code import num_beat\n'), ((1614, 1648), 'hrm_code.calc_bpm', 'calc_bpm', (['fake_num_beats', 'fake_dur'], {}), '(fake_num_beats, fake_dur)\n', (1622, 1648), False, 'from hrm_code import calc_bpm\n'), ((1850, 1898), 'hrm_code.create_metrics', 'create_metrics', (['bpm', 'beats', 'both', 'dur', 'num_beats'], {}), '(bpm, beats, both, dur, num_beats)\n', (1864, 1898), False, 'from hrm_code import create_metrics\n'), ((2336, 2367), 'hrm_code.create_jason', 'create_jason', (['filename', 'metrics'], {}), '(filename, metrics)\n', (2348, 2367), False, 'from hrm_code import create_jason\n'), ((253, 277), 'hrm_code.number_please', 'number_please', (['candidate'], {}), '(candidate)\n', (266, 277), False, 'from hrm_code import number_please\n'), ((1146, 1163), 'numpy.sin', 'np.sin', (['(t * np.pi)'], {}), '(t * np.pi)\n', (1152, 1163), True, 'import numpy as np\n')]
# Generated by Django 2.1.7 on 2019-05-10 09:21 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('core', '0043_auto_20190424_1029'), ] operations = [ migrations.RemoveField( model_name='statetransition', name='state', ), migrations.AddField( model_name='statetransition', name='asset_state_from_report', field=models.CharField(choices=[('requires repair', 'requires repair'), ('requires external assessment', 'requires external assessment'), ('Damaged', 'Damaged')], default='requires repair', max_length=50), ), migrations.AddField( model_name='statetransition', name='incident_report_state', field=models.CharField(choices=[('newly reported', 'newly reported'), ('internal assessment', 'internal assessment'), ('external assessment', 'external assessment'), ('out for repair', 'out for repair')], default='newly reported', max_length=50), ), ]
[ "django.db.migrations.RemoveField", "django.db.models.CharField" ]
[((232, 298), 'django.db.migrations.RemoveField', 'migrations.RemoveField', ([], {'model_name': '"""statetransition"""', 'name': '"""state"""'}), "(model_name='statetransition', name='state')\n", (254, 298), False, 'from django.db import migrations, models\n'), ((468, 676), 'django.db.models.CharField', 'models.CharField', ([], {'choices': "[('requires repair', 'requires repair'), ('requires external assessment',\n 'requires external assessment'), ('Damaged', 'Damaged')]", 'default': '"""requires repair"""', 'max_length': '(50)'}), "(choices=[('requires repair', 'requires repair'), (\n 'requires external assessment', 'requires external assessment'), (\n 'Damaged', 'Damaged')], default='requires repair', max_length=50)\n", (484, 676), False, 'from django.db import migrations, models\n'), ((810, 1063), 'django.db.models.CharField', 'models.CharField', ([], {'choices': "[('newly reported', 'newly reported'), ('internal assessment',\n 'internal assessment'), ('external assessment', 'external assessment'),\n ('out for repair', 'out for repair')]", 'default': '"""newly reported"""', 'max_length': '(50)'}), "(choices=[('newly reported', 'newly reported'), (\n 'internal assessment', 'internal assessment'), ('external assessment',\n 'external assessment'), ('out for repair', 'out for repair')], default=\n 'newly reported', max_length=50)\n", (826, 1063), False, 'from django.db import migrations, models\n')]
from stk_sequence import * from stk_tcp_server import * from stk_tcp_client import * from stk_data_flow import * from stk_options import stk_clear_cb import time class stk_callback: def __init__(self): self._caller = None self._mapobj = None pass def add_callback_ref(self,caller): self._caller = caller def del_callback_ref(self,caller): if self._caller: self._caller.delCallback() def add_callback_map_obj(self,mapobj): self._mapobj = mapobj def map_obj(self): return self._mapobj def close(self): if self._caller: self.del_callback_ref(self._caller) self._caller = None def caller(self): return self._caller def fd_created(self,df,fd): pass def fd_destroyed(self,df,fd): pass class stk_dispatcher_cb(stk_dispatch_cb_class): def __init__(self,env,cbcls): self.dispatchclass = stk_dispatch_cb_class.__init__(self) self._cbcls = cbcls self._env = env def close(self): #del self.dispatchclass #self.dispatchclass = None #del self.__class__.obj_map[stk_get_service_group_id(self._svcgrp)] pass def finddf(self,dfptr): dfref = stk_ulong_df_to_df_ptr(dfptr) df = stk_data_flow.find(dfptr) if df == None: dftype = stk_data_flow.type(dfptr) if dftype == STK_TCP_ACCEPTED_FLOW or dftype == STK_TCP_SERVER_FLOW: df = stk_tcp_server(self._env,None,None,None,dfref) if dftype == STK_TCP_CLIENT_FLOW: df = stk_tcp_client(self._env,None,None,None,dfref) return df def process_data(self,dfptr,seqptr): seqref = stk_ulong_seq_to_seq_ptr(seqptr) seq = stk_sequence.find(seqptr) if seq == None: seq = stk_sequence(self._env,None,None,0,0,None,seqref) # the dfptr here is actually the C pointer converted to a ulong df = self.finddf(dfptr) self._cbcls.process_data(df,seq) seq.unmap() def process_name_response(self,dfptr,seqptr): seqref = stk_ulong_seq_to_seq_ptr(seqptr) seq = stk_sequence.find(seqptr) if seq == None: seq = stk_sequence(self._env,None,None,0,0,None,seqref) # the dfptr here is actually the C pointer converted to a ulong df = self.finddf(dfptr) self._cbcls.process_name_response(df,seq) seq.unmap() pass def process_monitoring_response(self,dfptr,seqptr): pass def fd_created(self,dfptr,fd): # the dfptr here is actually the C pointer converted to a ulong dfref = stk_ulong_df_to_df_ptr(dfptr) df = stk_data_flow.find(dfptr) if df == None: # This sucks.... dftype = stk_data_flow.type(dfptr) if dftype == STK_TCP_ACCEPTED_FLOW or dftype == STK_TCP_SERVER_FLOW: df = stk_tcp_server(self._env,None,None,None,dfref) # Err, UDP doesn't actually have connections so this really # isn't likely to be needed - why would the app care about udp creations? #elif dftype == STK_UDP_CLIENT_FLOW: #df = stk_udp_client(self._env,None,None,None,dfref) if df: self._cbcls.fd_created(df,fd) def fd_destroyed(self,dfptr,fd): # the dfptr here is actually the C pointer converted to a ulong dfref = stk_ulong_df_to_df_ptr(dfptr) df = stk_data_flow.find(dfptr) if df == None: dftype = stk_data_flow.type(dfptr) if dftype == STK_TCP_ACCEPTED_FLOW or dftype == STK_TCP_SERVER_FLOW: df = stk_tcp_server(self._env,None,None,None,dfref) if df: self._cbcls.fd_destroyed(df,fd) class stk_env: def __init__(self,envopts): self.caller = stk_dispatch_cb_caller() envopts.append_dispatcher(self.caller.get_dispatcher()) self._opts = envopts self._env = stk_create_env(envopts.ref()) self._dispatcher_stopped = False; def close(self): if self._env: if self._opts: stk_clear_cb(self._opts.ref(),"dispatcher") if self.caller: self.caller.detach_env(self._env) stk_destroy_env(self._env) if self.caller: self.caller.close() self.caller = None self._env = None def ref(self): return self._env def get_name_service(self): return stk_env_get_name_service(self.ref()) def dispatch_timer_pools(self,interval): stk_env_dispatch_timer_pools(self._env,interval) def listening_dispatcher(self,df,svcgrp,appcb): appcb.add_callback_ref(self.caller) self._dispatcher_stopped = False if self.caller.env_listening_dispatcher_add_fd(df.ref()) < 0: return while self._dispatcher_stopped == False: self.caller.env_listening_dispatcher(df.ref(),stk_dispatcher_cb(self,appcb).__disown__(),200) self.caller.env_listening_dispatcher_del_fd(df.ref()) def client_dispatcher_timed(self,appcb,timeout): if appcb: appcb.add_callback_ref(self.caller) self.caller.env_client_dispatcher_timed(self._env,timeout,stk_dispatcher_cb(self,appcb).__disown__()) else: self.caller.env_client_dispatcher_timed(self._env,timeout,None) def stop_dispatcher(self): self._dispatcher_stopped = True; self.caller.env_stop_dispatching(self._env) time.sleep(.2) def terminate_dispatcher(self): self.caller.env_terminate_dispatcher(self._env) @classmethod def append_name_server_dispatcher_cbs(cls,envopts,data_flow_group): nsopts = envopts.find_option("name_server_options") nsopts.update_ref(stk_append_name_server_fd_cbs(data_flow_group,nsopts.ref())) @classmethod def remove_name_server_dispatcher_cbs(cls,envopts,data_flow_group): dfopts = envopts.find_option(data_flow_group + "_options") if dfopts != None: dfopts.remove_dispatcher_fd_cbs() else: envopts.remove_dispatcher_fd_cbs() @classmethod def append_monitoring_dispatcher_cbs(cls,envopts,data_flow_group): envopts.update_ref(stk_append_monitoring_fd_cbs(data_flow_group,envopts.ref())) @classmethod def remove_monitoring_dispatcher_cbs(cls,envopts,data_flow_group): dfopts = envopts.find_option(data_flow_group + "_options") if dfopts != None: dfopts.remove_dispatcher_fd_cbs() @classmethod def log(cls,level,message): stk_log(level,message) @classmethod def debug(cls,component,message): stk_debug(component,message)
[ "time.sleep" ]
[((4749, 4764), 'time.sleep', 'time.sleep', (['(0.2)'], {}), '(0.2)\n', (4759, 4764), False, 'import time\n')]
from __future__ import print_function import pkgutil import stream_decoders # this module decodes stream based protocols. # and resolves retransmissions. decoders= [] # __path__ is used to find the location of all decoder submodules for impimp, name, ii in pkgutil.iter_modules(stream_decoders.__path__): impload= impimp.find_module(name) decoders.append(impload.load_module(name).toplevel) import math import time import struct def addrstring(*args): if len(args)==1 and type(args[0])==tuple: # from getaddr args= args[0] if len(args)==0: raise Exception("no addr") addr= args[0] if len(addr)==4: addr= ".".join(map(lambda x:str(x), struct.unpack("4B", addr))) elif len(addr)==16: addr= ":".join(map(lambda x:"%04x"%x if x else "", struct.unpack(">8H", addr))) else: raise Exception("invalid addr") if len(args)==1: return addr elif len(args)==2: return addr+"."+str(args[1]) else: raise Exception("addr: too many items") def getaddr(ctx, frm): # ipaddr if hasattr(ctx, frm): return getattr(ctx, frm) # ipaddr + portnum for proto in ("udp", "tcp"): if hasattr(ctx, proto): return getattr(ctx.ip, frm), getattr(getattr(ctx, proto), frm) # ipaddr return getattr(ctx.ip, frm) def pkttag(ip, p): if p.src < p.dst: return "%s:%s" % (addrstring(ip.dst, p.dst), addrstring(ip.src, p.src)) elif p.src > p.dst: return "%s:%s" % (addrstring(ip.src, p.src), addrstring(ip.dst, p.dst)) elif ip.src < ip.dst: return "%s:%s" % (addrstring(ip.dst, p.dst), addrstring(ip.src, p.src)) else: return "%s:%s" % (addrstring(ip.src, p.src), addrstring(ip.dst, p.dst)) def pktprefix(ip, p): if p.src < p.dst: return "%s < %s" % (addrstring(ip.dst, p.dst), addrstring(ip.src, p.src)) elif p.src > p.dst: return "%s > %s" % (addrstring(ip.src, p.src), addrstring(ip.dst, p.dst)) elif ip.src < ip.dst: return "%s < %s" % (addrstring(ip.dst, p.dst), addrstring(ip.src, p.src)) else: return "%s > %s" % (addrstring(ip.src, p.src), addrstring(ip.dst, p.dst)) def tsformat(ts): f, n= math.modf(ts) return time.strftime("%H:%M:%S", time.localtime(n))+("%.6f" % f)[1:] class StreamAutoDetect: def __init__(self): self.data= {} self.decoder= None # todo for 'src' pass: 'clt', 'svr' + clt+svr addr:ports def handle(self, src, data, ofs, last): if self.decoder: return self.decoder.handle(src, data, ofs, last) if src in self.data: data = self.data[src] + data[ofs:last] ofs, last= 0, len(data) # try to determine what decoder to use for cls in decoders: # todo: pass both svr+clt traffic to isvaliddata. if cls.isvaliddata(data, ofs, last): if src in self.data: del self.data[src] self.setdecoder(cls, src, data, ofs, last) return def setdecoder(self, cls, src, sdata, ofs, last): self.decoder= cls(self) # first forward older data for s, ddata in self.data.items(): o= self.decoder.handle(s, ddata, 0, len(ddata)) # todo: resulting ofs del self.data[s] if o<len(ddata): print("stream WARN: ddata remaining: %s" % (ddata[o:].encode("hex"))) # then forward this data ofs= self.decoder.handle(src, sdata, ofs, last) # todo: optionally clear data #self.data[src]= sdata if ofs<last: print("stream WARN: sdata remaining: %s" % (sdata[ofs:].encode("hex"))) def handlegap(self, src, size): pass #print("gap: %d" % size) class StreamDecoder: def __init__(self): self.seq= {} self.cur= {} self.protocol = StreamAutoDetect() self.totalgap = 0 self.seqmap= {} def __del__(self): if any(len(x) for x in self.seqmap.values()): #print("seq: ", self.seq) #print("cur: ", self.cur) #print("map: ", self.seqmap) pass @staticmethod def tcpflags(tcp): f= "" if tcp.URG: f+="U" if tcp.ACK: f+="A" if tcp.PSH: f+="P" if tcp.RST: f+="R" if tcp.SYN: f+="S" if tcp.FIN: f+="F" return f # handle without packet reordering # ... this is currently not used, see 'reorder' def handle(self, ctx): src= addrstring(getaddr(ctx, "src")) dst= addrstring(getaddr(ctx, "dst")) if not src in self.seq: self.seq[src]= ctx.tcp.seq if not dst in self.seq and ctx.tcp.ack: self.seq[dst]= ctx.tcp.ack f= self.tcpflags(ctx.tcp) skip= 0 extra= ctx.tcp.FIN or ctx.tcp.SYN endseq= ctx.tcp.seq + len(ctx.tcp.payload)+extra if not src in self.cur: self.cur[src]= ctx.tcp.seq elif self.cur[src] < ctx.tcp.seq: #print("GAP: %08x-%08x" % (self.cur[src], ctx.tcp.seq)) self.totalgap += ctx.tcp.seq-self.cur[src] elif self.cur[src] > ctx.tcp.seq: #print("OVERLAP: %08x-%08x" % (ctx.tcp.seq, self.cur[src])) # handle retransmit skip= self.cur[src] - ctx.tcp.seq if ctx.tcp.payload and self.totalgap: self.protocol.handlegap(src, self.totalgap) self.totalgap= 0 #seqnr= "[%08x]" % ctx.tcp.seq-self.seq[src] seqnr= "[%08x-%08x:%08x]" % (ctx.tcp.seq, endseq, ctx.tcp.ack) print("%s TCP %-45s %s%-2s %s" % (tsformat(ctx.pcap.ts), pktprefix(ctx.ip, ctx.tcp), seqnr, f, ctx.tcp.payload.encode("hex"))) if skip < len(ctx.tcp.payload): self.protocol.handle(src, ctx.tcp.payload, skip, len(ctx.tcp.payload)) elif len(ctx.tcp.payload): print("dropped") self.cur[src] = endseq # handle with packet reordering def reorder(self, ctx): src= addrstring(getaddr(ctx, "src")) dst= addrstring(getaddr(ctx, "dst")) # if any(len(x) for x in self.seqmap.values()): # print(self.seqmap) # save all pkts in seqmap if not src in self.seqmap: self.seqmap[src]= {} self.seqmap[src][ctx.tcp.seq]= ctx # then try to process pkts for k in sorted(self.seqmap[src].keys()): ctx= self.seqmap[src][k] if not src in self.seq: self.seq[src]= ctx.tcp.seq if not dst in self.seq and ctx.tcp.ack: self.seq[dst]= ctx.tcp.ack f= self.tcpflags(ctx.tcp) skip= 0 extra= ctx.tcp.FIN or ctx.tcp.SYN endseq= ctx.tcp.seq + len(ctx.tcp.payload)+extra if not src in self.cur: self.cur[src]= ctx.tcp.seq elif self.cur[src] < ctx.tcp.seq: # gap -> output later # todo: on FIN: do forward gapped data to protocol.handler. ##print("gap %d" % (ctx.tcp.seq-self.cur[src])) break elif self.cur[src] > ctx.tcp.seq: #print("OVERLAP: %08x-%08x" % (ctx.tcp.seq, self.cur[src])) # handle retransmit skip= self.cur[src] - ctx.tcp.seq ##print("retransmitted %d" % skip) # todo: detect server/client direction # client: SYN has ctx.tcp.ack==0 # server: SYN has ctx.tcp.ack!=0 #seqnr= "[%08x]" % ctx.tcp.seq-self.seq[src] seqnr= "[%08x-%08x %08x]" % (ctx.tcp.seq, endseq, ctx.tcp.ack) print("%s TCP %-45s %s%-2s" % (tsformat(ctx.pcap.ts), pktprefix(ctx.ip, ctx.tcp), seqnr, f)) if skip < len(ctx.tcp.payload): # todo: pass server/client flag + source/dest ports self.protocol.handle(src, ctx.tcp.payload, skip, len(ctx.tcp.payload)) self.cur[src] = endseq del self.seqmap[src][k] class StreamManager: def __init__(self): self.streams= {} def handle(self, ctx): tag= pkttag(ctx.ip, ctx.tcp) if not tag in self.streams: self.streams[tag]= StreamDecoder() self.streams[tag].reorder(ctx)
[ "math.modf", "time.localtime", "struct.unpack", "pkgutil.iter_modules" ]
[((259, 305), 'pkgutil.iter_modules', 'pkgutil.iter_modules', (['stream_decoders.__path__'], {}), '(stream_decoders.__path__)\n', (279, 305), False, 'import pkgutil\n'), ((2234, 2247), 'math.modf', 'math.modf', (['ts'], {}), '(ts)\n', (2243, 2247), False, 'import math\n'), ((2285, 2302), 'time.localtime', 'time.localtime', (['n'], {}), '(n)\n', (2299, 2302), False, 'import time\n'), ((695, 720), 'struct.unpack', 'struct.unpack', (['"""4B"""', 'addr'], {}), "('4B', addr)\n", (708, 720), False, 'import struct\n'), ((807, 833), 'struct.unpack', 'struct.unpack', (['""">8H"""', 'addr'], {}), "('>8H', addr)\n", (820, 833), False, 'import struct\n')]
import logging import aioredis from app.core.config import REDIS_DSN, REDIS_PASSWORD logger = logging.getLogger(__name__) async def get_redis_pool(): return await aioredis.create_redis(REDIS_DSN, encoding='utf-8', password=REDIS_PASSWORD)
[ "logging.getLogger", "aioredis.create_redis" ]
[((96, 123), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (113, 123), False, 'import logging\n'), ((171, 246), 'aioredis.create_redis', 'aioredis.create_redis', (['REDIS_DSN'], {'encoding': '"""utf-8"""', 'password': 'REDIS_PASSWORD'}), "(REDIS_DSN, encoding='utf-8', password=REDIS_PASSWORD)\n", (192, 246), False, 'import aioredis\n')]
import pathlib from typing import Any, Dict, List, Tuple from torchdata.datapipes.iter import IterDataPipe, Mapper, Filter from torchvision.prototype.datasets.utils import Dataset, DatasetConfig, DatasetInfo, HttpResource, OnlineResource from torchvision.prototype.datasets.utils._internal import path_comparator, hint_sharding, hint_shuffling from torchvision.prototype.features import EncodedImage, Label class Country211(Dataset): def _make_info(self) -> DatasetInfo: return DatasetInfo( "country211", homepage="https://github.com/openai/CLIP/blob/main/data/country211.md", valid_options=dict(split=("train", "val", "test")), ) def resources(self, config: DatasetConfig) -> List[OnlineResource]: return [ HttpResource( "https://openaipublic.azureedge.net/clip/data/country211.tgz", sha256="c011343cdc1296a8c31ff1d7129cf0b5e5b8605462cffd24f89266d6e6f4da3c", ) ] _SPLIT_NAME_MAPPER = { "train": "train", "val": "valid", "test": "test", } def _prepare_sample(self, data: Tuple[str, Any]) -> Dict[str, Any]: path, buffer = data category = pathlib.Path(path).parent.name return dict( label=Label.from_category(category, categories=self.categories), path=path, image=EncodedImage.from_file(buffer), ) def _filter_split(self, data: Tuple[str, Any], *, split: str) -> bool: return pathlib.Path(data[0]).parent.parent.name == split def _make_datapipe( self, resource_dps: List[IterDataPipe], *, config: DatasetConfig ) -> IterDataPipe[Dict[str, Any]]: dp = resource_dps[0] dp = Filter(dp, path_comparator("parent.parent.name", self._SPLIT_NAME_MAPPER[config.split])) dp = hint_shuffling(dp) dp = hint_sharding(dp) return Mapper(dp, self._prepare_sample) def _generate_categories(self, root: pathlib.Path) -> List[str]: resources = self.resources(self.default_config) dp = resources[0].load(root) return sorted({pathlib.Path(path).parent.name for path, _ in dp})
[ "torchdata.datapipes.iter.Mapper", "torchvision.prototype.features.EncodedImage.from_file", "torchvision.prototype.features.Label.from_category", "torchvision.prototype.datasets.utils._internal.hint_sharding", "pathlib.Path", "torchvision.prototype.datasets.utils._internal.path_comparator", "torchvision...
[((1862, 1880), 'torchvision.prototype.datasets.utils._internal.hint_shuffling', 'hint_shuffling', (['dp'], {}), '(dp)\n', (1876, 1880), False, 'from torchvision.prototype.datasets.utils._internal import path_comparator, hint_sharding, hint_shuffling\n'), ((1894, 1911), 'torchvision.prototype.datasets.utils._internal.hint_sharding', 'hint_sharding', (['dp'], {}), '(dp)\n', (1907, 1911), False, 'from torchvision.prototype.datasets.utils._internal import path_comparator, hint_sharding, hint_shuffling\n'), ((1927, 1959), 'torchdata.datapipes.iter.Mapper', 'Mapper', (['dp', 'self._prepare_sample'], {}), '(dp, self._prepare_sample)\n', (1933, 1959), False, 'from torchdata.datapipes.iter import IterDataPipe, Mapper, Filter\n'), ((792, 946), 'torchvision.prototype.datasets.utils.HttpResource', 'HttpResource', (['"""https://openaipublic.azureedge.net/clip/data/country211.tgz"""'], {'sha256': '"""c011343cdc1296a8c31ff1d7129cf0b5e5b8605462cffd24f89266d6e6f4da3c"""'}), "('https://openaipublic.azureedge.net/clip/data/country211.tgz',\n sha256='c011343cdc1296a8c31ff1d7129cf0b5e5b8605462cffd24f89266d6e6f4da3c')\n", (804, 946), False, 'from torchvision.prototype.datasets.utils import Dataset, DatasetConfig, DatasetInfo, HttpResource, OnlineResource\n'), ((1771, 1847), 'torchvision.prototype.datasets.utils._internal.path_comparator', 'path_comparator', (['"""parent.parent.name"""', 'self._SPLIT_NAME_MAPPER[config.split]'], {}), "('parent.parent.name', self._SPLIT_NAME_MAPPER[config.split])\n", (1786, 1847), False, 'from torchvision.prototype.datasets.utils._internal import path_comparator, hint_sharding, hint_shuffling\n'), ((1228, 1246), 'pathlib.Path', 'pathlib.Path', (['path'], {}), '(path)\n', (1240, 1246), False, 'import pathlib\n'), ((1298, 1355), 'torchvision.prototype.features.Label.from_category', 'Label.from_category', (['category'], {'categories': 'self.categories'}), '(category, categories=self.categories)\n', (1317, 1355), False, 'from torchvision.prototype.features import EncodedImage, Label\n'), ((1398, 1428), 'torchvision.prototype.features.EncodedImage.from_file', 'EncodedImage.from_file', (['buffer'], {}), '(buffer)\n', (1420, 1428), False, 'from torchvision.prototype.features import EncodedImage, Label\n'), ((1531, 1552), 'pathlib.Path', 'pathlib.Path', (['data[0]'], {}), '(data[0])\n', (1543, 1552), False, 'import pathlib\n'), ((2146, 2164), 'pathlib.Path', 'pathlib.Path', (['path'], {}), '(path)\n', (2158, 2164), False, 'import pathlib\n')]
import numpy as np from math import sqrt def robot_distance_incorrect(robot_actual_location, hexagon_pixel_values): distance_to_get_back = [] distances = [] pixel_distance = [] for i in range(0, len(hexagon_pixel_values)): dist = sqrt((robot_actual_location[0] - hexagon_pixel_values[i][0]) ** 2 + (robot_actual_location[1] - hexagon_pixel_values[i][1]) ** 2) distances += [dist] index_min = np.argmin(distances) correct_position = hexagon_pixel_values[index_min] # find the distance that needs to be traveled to get to the correct location pixel_distance = (correct_position[0] - robot_actual_location[0], correct_position[1]-robot_actual_location[1]) # print(correct_position, robot_actual_location, pixel_distance) # convert to actual distance distance_to_get_back = (pixel_distance[0]/1.79, pixel_distance[1]/1.749) return distance_to_get_back
[ "numpy.argmin", "math.sqrt" ]
[((450, 470), 'numpy.argmin', 'np.argmin', (['distances'], {}), '(distances)\n', (459, 470), True, 'import numpy as np\n'), ((256, 390), 'math.sqrt', 'sqrt', (['((robot_actual_location[0] - hexagon_pixel_values[i][0]) ** 2 + (\n robot_actual_location[1] - hexagon_pixel_values[i][1]) ** 2)'], {}), '((robot_actual_location[0] - hexagon_pixel_values[i][0]) ** 2 + (\n robot_actual_location[1] - hexagon_pixel_values[i][1]) ** 2)\n', (260, 390), False, 'from math import sqrt\n')]
import warnings from typing import List from fastapi import APIRouter, FastAPI from fastapi.routing import APIRoute from fastapi.testclient import TestClient from pydantic import BaseModel def custom_generate_unique_id(route: APIRoute): return f"foo_{route.name}" def custom_generate_unique_id2(route: APIRoute): return f"bar_{route.name}" def custom_generate_unique_id3(route: APIRoute): return f"baz_{route.name}" class Item(BaseModel): name: str price: float class Message(BaseModel): title: str description: str def test_top_level_generate_unique_id(): app = FastAPI(generate_unique_id_function=custom_generate_unique_id) router = APIRouter() @app.post("/", response_model=List[Item], responses={404: {"model": List[Message]}}) def post_root(item1: Item, item2: Item): return item1, item2 # pragma: nocover @router.post( "/router", response_model=List[Item], responses={404: {"model": List[Message]}} ) def post_router(item1: Item, item2: Item): return item1, item2 # pragma: nocover app.include_router(router) client = TestClient(app) response = client.get("/openapi.json") data = response.json() assert data == { "openapi": "3.0.2", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/": { "post": { "summary": "Post Root", "operationId": "foo_post_root", "requestBody": { "content": { "application/json": { "schema": { "$ref": "#/components/schemas/Body_foo_post_root" } } }, "required": True, }, "responses": { "200": { "description": "Successful Response", "content": { "application/json": { "schema": { "title": "Response Foo Post Root", "type": "array", "items": {"$ref": "#/components/schemas/Item"}, } } }, }, "404": { "description": "Not Found", "content": { "application/json": { "schema": { "title": "Response 404 Foo Post Root", "type": "array", "items": { "$ref": "#/components/schemas/Message" }, } } }, }, "422": { "description": "Validation Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError" } } }, }, }, } }, "/router": { "post": { "summary": "Post Router", "operationId": "foo_post_router", "requestBody": { "content": { "application/json": { "schema": { "$ref": "#/components/schemas/Body_foo_post_router" } } }, "required": True, }, "responses": { "200": { "description": "Successful Response", "content": { "application/json": { "schema": { "title": "Response Foo Post Router", "type": "array", "items": {"$ref": "#/components/schemas/Item"}, } } }, }, "404": { "description": "Not Found", "content": { "application/json": { "schema": { "title": "Response 404 Foo Post Router", "type": "array", "items": { "$ref": "#/components/schemas/Message" }, } } }, }, "422": { "description": "Validation Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError" } } }, }, }, } }, }, "components": { "schemas": { "Body_foo_post_root": { "title": "Body_foo_post_root", "required": ["item1", "item2"], "type": "object", "properties": { "item1": {"$ref": "#/components/schemas/Item"}, "item2": {"$ref": "#/components/schemas/Item"}, }, }, "Body_foo_post_router": { "title": "Body_foo_post_router", "required": ["item1", "item2"], "type": "object", "properties": { "item1": {"$ref": "#/components/schemas/Item"}, "item2": {"$ref": "#/components/schemas/Item"}, }, }, "HTTPValidationError": { "title": "HTTPValidationError", "type": "object", "properties": { "detail": { "title": "Detail", "type": "array", "items": {"$ref": "#/components/schemas/ValidationError"}, } }, }, "Item": { "title": "Item", "required": ["name", "price"], "type": "object", "properties": { "name": {"title": "Name", "type": "string"}, "price": {"title": "Price", "type": "number"}, }, }, "Message": { "title": "Message", "required": ["title", "description"], "type": "object", "properties": { "title": {"title": "Title", "type": "string"}, "description": {"title": "Description", "type": "string"}, }, }, "ValidationError": { "title": "ValidationError", "required": ["loc", "msg", "type"], "type": "object", "properties": { "loc": { "title": "Location", "type": "array", "items": { "anyOf": [{"type": "string"}, {"type": "integer"}] }, }, "msg": {"title": "Message", "type": "string"}, "type": {"title": "Error Type", "type": "string"}, }, }, } }, } def test_router_overrides_generate_unique_id(): app = FastAPI(generate_unique_id_function=custom_generate_unique_id) router = APIRouter(generate_unique_id_function=custom_generate_unique_id2) @app.post("/", response_model=List[Item], responses={404: {"model": List[Message]}}) def post_root(item1: Item, item2: Item): return item1, item2 # pragma: nocover @router.post( "/router", response_model=List[Item], responses={404: {"model": List[Message]}} ) def post_router(item1: Item, item2: Item): return item1, item2 # pragma: nocover app.include_router(router) client = TestClient(app) response = client.get("/openapi.json") data = response.json() assert data == { "openapi": "3.0.2", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/": { "post": { "summary": "Post Root", "operationId": "foo_post_root", "requestBody": { "content": { "application/json": { "schema": { "$ref": "#/components/schemas/Body_foo_post_root" } } }, "required": True, }, "responses": { "200": { "description": "Successful Response", "content": { "application/json": { "schema": { "title": "Response Foo Post Root", "type": "array", "items": {"$ref": "#/components/schemas/Item"}, } } }, }, "404": { "description": "Not Found", "content": { "application/json": { "schema": { "title": "Response 404 Foo Post Root", "type": "array", "items": { "$ref": "#/components/schemas/Message" }, } } }, }, "422": { "description": "Validation Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError" } } }, }, }, } }, "/router": { "post": { "summary": "Post Router", "operationId": "bar_post_router", "requestBody": { "content": { "application/json": { "schema": { "$ref": "#/components/schemas/Body_bar_post_router" } } }, "required": True, }, "responses": { "200": { "description": "Successful Response", "content": { "application/json": { "schema": { "title": "Response Bar Post Router", "type": "array", "items": {"$ref": "#/components/schemas/Item"}, } } }, }, "404": { "description": "Not Found", "content": { "application/json": { "schema": { "title": "Response 404 Bar Post Router", "type": "array", "items": { "$ref": "#/components/schemas/Message" }, } } }, }, "422": { "description": "Validation Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError" } } }, }, }, } }, }, "components": { "schemas": { "Body_bar_post_router": { "title": "Body_bar_post_router", "required": ["item1", "item2"], "type": "object", "properties": { "item1": {"$ref": "#/components/schemas/Item"}, "item2": {"$ref": "#/components/schemas/Item"}, }, }, "Body_foo_post_root": { "title": "Body_foo_post_root", "required": ["item1", "item2"], "type": "object", "properties": { "item1": {"$ref": "#/components/schemas/Item"}, "item2": {"$ref": "#/components/schemas/Item"}, }, }, "HTTPValidationError": { "title": "HTTPValidationError", "type": "object", "properties": { "detail": { "title": "Detail", "type": "array", "items": {"$ref": "#/components/schemas/ValidationError"}, } }, }, "Item": { "title": "Item", "required": ["name", "price"], "type": "object", "properties": { "name": {"title": "Name", "type": "string"}, "price": {"title": "Price", "type": "number"}, }, }, "Message": { "title": "Message", "required": ["title", "description"], "type": "object", "properties": { "title": {"title": "Title", "type": "string"}, "description": {"title": "Description", "type": "string"}, }, }, "ValidationError": { "title": "ValidationError", "required": ["loc", "msg", "type"], "type": "object", "properties": { "loc": { "title": "Location", "type": "array", "items": { "anyOf": [{"type": "string"}, {"type": "integer"}] }, }, "msg": {"title": "Message", "type": "string"}, "type": {"title": "Error Type", "type": "string"}, }, }, } }, } def test_router_include_overrides_generate_unique_id(): app = FastAPI(generate_unique_id_function=custom_generate_unique_id) router = APIRouter(generate_unique_id_function=custom_generate_unique_id2) @app.post("/", response_model=List[Item], responses={404: {"model": List[Message]}}) def post_root(item1: Item, item2: Item): return item1, item2 # pragma: nocover @router.post( "/router", response_model=List[Item], responses={404: {"model": List[Message]}} ) def post_router(item1: Item, item2: Item): return item1, item2 # pragma: nocover app.include_router(router, generate_unique_id_function=custom_generate_unique_id3) client = TestClient(app) response = client.get("/openapi.json") data = response.json() assert data == { "openapi": "3.0.2", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/": { "post": { "summary": "Post Root", "operationId": "foo_post_root", "requestBody": { "content": { "application/json": { "schema": { "$ref": "#/components/schemas/Body_foo_post_root" } } }, "required": True, }, "responses": { "200": { "description": "Successful Response", "content": { "application/json": { "schema": { "title": "Response Foo Post Root", "type": "array", "items": {"$ref": "#/components/schemas/Item"}, } } }, }, "404": { "description": "Not Found", "content": { "application/json": { "schema": { "title": "Response 404 Foo Post Root", "type": "array", "items": { "$ref": "#/components/schemas/Message" }, } } }, }, "422": { "description": "Validation Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError" } } }, }, }, } }, "/router": { "post": { "summary": "Post Router", "operationId": "bar_post_router", "requestBody": { "content": { "application/json": { "schema": { "$ref": "#/components/schemas/Body_bar_post_router" } } }, "required": True, }, "responses": { "200": { "description": "Successful Response", "content": { "application/json": { "schema": { "title": "Response Bar Post Router", "type": "array", "items": {"$ref": "#/components/schemas/Item"}, } } }, }, "404": { "description": "Not Found", "content": { "application/json": { "schema": { "title": "Response 404 Bar Post Router", "type": "array", "items": { "$ref": "#/components/schemas/Message" }, } } }, }, "422": { "description": "Validation Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError" } } }, }, }, } }, }, "components": { "schemas": { "Body_bar_post_router": { "title": "Body_bar_post_router", "required": ["item1", "item2"], "type": "object", "properties": { "item1": {"$ref": "#/components/schemas/Item"}, "item2": {"$ref": "#/components/schemas/Item"}, }, }, "Body_foo_post_root": { "title": "Body_foo_post_root", "required": ["item1", "item2"], "type": "object", "properties": { "item1": {"$ref": "#/components/schemas/Item"}, "item2": {"$ref": "#/components/schemas/Item"}, }, }, "HTTPValidationError": { "title": "HTTPValidationError", "type": "object", "properties": { "detail": { "title": "Detail", "type": "array", "items": {"$ref": "#/components/schemas/ValidationError"}, } }, }, "Item": { "title": "Item", "required": ["name", "price"], "type": "object", "properties": { "name": {"title": "Name", "type": "string"}, "price": {"title": "Price", "type": "number"}, }, }, "Message": { "title": "Message", "required": ["title", "description"], "type": "object", "properties": { "title": {"title": "Title", "type": "string"}, "description": {"title": "Description", "type": "string"}, }, }, "ValidationError": { "title": "ValidationError", "required": ["loc", "msg", "type"], "type": "object", "properties": { "loc": { "title": "Location", "type": "array", "items": { "anyOf": [{"type": "string"}, {"type": "integer"}] }, }, "msg": {"title": "Message", "type": "string"}, "type": {"title": "Error Type", "type": "string"}, }, }, } }, } def test_subrouter_top_level_include_overrides_generate_unique_id(): app = FastAPI(generate_unique_id_function=custom_generate_unique_id) router = APIRouter() sub_router = APIRouter(generate_unique_id_function=custom_generate_unique_id2) @app.post("/", response_model=List[Item], responses={404: {"model": List[Message]}}) def post_root(item1: Item, item2: Item): return item1, item2 # pragma: nocover @router.post( "/router", response_model=List[Item], responses={404: {"model": List[Message]}} ) def post_router(item1: Item, item2: Item): return item1, item2 # pragma: nocover @sub_router.post( "/subrouter", response_model=List[Item], responses={404: {"model": List[Message]}}, ) def post_subrouter(item1: Item, item2: Item): return item1, item2 # pragma: nocover router.include_router(sub_router) app.include_router(router, generate_unique_id_function=custom_generate_unique_id3) client = TestClient(app) response = client.get("/openapi.json") data = response.json() assert data == { "openapi": "3.0.2", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/": { "post": { "summary": "Post Root", "operationId": "foo_post_root", "requestBody": { "content": { "application/json": { "schema": { "$ref": "#/components/schemas/Body_foo_post_root" } } }, "required": True, }, "responses": { "200": { "description": "Successful Response", "content": { "application/json": { "schema": { "title": "Response Foo Post Root", "type": "array", "items": {"$ref": "#/components/schemas/Item"}, } } }, }, "404": { "description": "Not Found", "content": { "application/json": { "schema": { "title": "Response 404 Foo Post Root", "type": "array", "items": { "$ref": "#/components/schemas/Message" }, } } }, }, "422": { "description": "Validation Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError" } } }, }, }, } }, "/router": { "post": { "summary": "Post Router", "operationId": "baz_post_router", "requestBody": { "content": { "application/json": { "schema": { "$ref": "#/components/schemas/Body_baz_post_router" } } }, "required": True, }, "responses": { "200": { "description": "Successful Response", "content": { "application/json": { "schema": { "title": "Response Baz Post Router", "type": "array", "items": {"$ref": "#/components/schemas/Item"}, } } }, }, "404": { "description": "Not Found", "content": { "application/json": { "schema": { "title": "Response 404 Baz Post Router", "type": "array", "items": { "$ref": "#/components/schemas/Message" }, } } }, }, "422": { "description": "Validation Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError" } } }, }, }, } }, "/subrouter": { "post": { "summary": "Post Subrouter", "operationId": "bar_post_subrouter", "requestBody": { "content": { "application/json": { "schema": { "$ref": "#/components/schemas/Body_bar_post_subrouter" } } }, "required": True, }, "responses": { "200": { "description": "Successful Response", "content": { "application/json": { "schema": { "title": "Response Bar Post Subrouter", "type": "array", "items": {"$ref": "#/components/schemas/Item"}, } } }, }, "404": { "description": "Not Found", "content": { "application/json": { "schema": { "title": "Response 404 Bar Post Subrouter", "type": "array", "items": { "$ref": "#/components/schemas/Message" }, } } }, }, "422": { "description": "Validation Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError" } } }, }, }, } }, }, "components": { "schemas": { "Body_bar_post_subrouter": { "title": "Body_bar_post_subrouter", "required": ["item1", "item2"], "type": "object", "properties": { "item1": {"$ref": "#/components/schemas/Item"}, "item2": {"$ref": "#/components/schemas/Item"}, }, }, "Body_baz_post_router": { "title": "Body_baz_post_router", "required": ["item1", "item2"], "type": "object", "properties": { "item1": {"$ref": "#/components/schemas/Item"}, "item2": {"$ref": "#/components/schemas/Item"}, }, }, "Body_foo_post_root": { "title": "Body_foo_post_root", "required": ["item1", "item2"], "type": "object", "properties": { "item1": {"$ref": "#/components/schemas/Item"}, "item2": {"$ref": "#/components/schemas/Item"}, }, }, "HTTPValidationError": { "title": "HTTPValidationError", "type": "object", "properties": { "detail": { "title": "Detail", "type": "array", "items": {"$ref": "#/components/schemas/ValidationError"}, } }, }, "Item": { "title": "Item", "required": ["name", "price"], "type": "object", "properties": { "name": {"title": "Name", "type": "string"}, "price": {"title": "Price", "type": "number"}, }, }, "Message": { "title": "Message", "required": ["title", "description"], "type": "object", "properties": { "title": {"title": "Title", "type": "string"}, "description": {"title": "Description", "type": "string"}, }, }, "ValidationError": { "title": "ValidationError", "required": ["loc", "msg", "type"], "type": "object", "properties": { "loc": { "title": "Location", "type": "array", "items": { "anyOf": [{"type": "string"}, {"type": "integer"}] }, }, "msg": {"title": "Message", "type": "string"}, "type": {"title": "Error Type", "type": "string"}, }, }, } }, } def test_router_path_operation_overrides_generate_unique_id(): app = FastAPI(generate_unique_id_function=custom_generate_unique_id) router = APIRouter(generate_unique_id_function=custom_generate_unique_id2) @app.post("/", response_model=List[Item], responses={404: {"model": List[Message]}}) def post_root(item1: Item, item2: Item): return item1, item2 # pragma: nocover @router.post( "/router", response_model=List[Item], responses={404: {"model": List[Message]}}, generate_unique_id_function=custom_generate_unique_id3, ) def post_router(item1: Item, item2: Item): return item1, item2 # pragma: nocover app.include_router(router) client = TestClient(app) response = client.get("/openapi.json") data = response.json() assert data == { "openapi": "3.0.2", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/": { "post": { "summary": "Post Root", "operationId": "foo_post_root", "requestBody": { "content": { "application/json": { "schema": { "$ref": "#/components/schemas/Body_foo_post_root" } } }, "required": True, }, "responses": { "200": { "description": "Successful Response", "content": { "application/json": { "schema": { "title": "Response Foo Post Root", "type": "array", "items": {"$ref": "#/components/schemas/Item"}, } } }, }, "404": { "description": "Not Found", "content": { "application/json": { "schema": { "title": "Response 404 Foo Post Root", "type": "array", "items": { "$ref": "#/components/schemas/Message" }, } } }, }, "422": { "description": "Validation Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError" } } }, }, }, } }, "/router": { "post": { "summary": "Post Router", "operationId": "baz_post_router", "requestBody": { "content": { "application/json": { "schema": { "$ref": "#/components/schemas/Body_baz_post_router" } } }, "required": True, }, "responses": { "200": { "description": "Successful Response", "content": { "application/json": { "schema": { "title": "Response Baz Post Router", "type": "array", "items": {"$ref": "#/components/schemas/Item"}, } } }, }, "404": { "description": "Not Found", "content": { "application/json": { "schema": { "title": "Response 404 Baz Post Router", "type": "array", "items": { "$ref": "#/components/schemas/Message" }, } } }, }, "422": { "description": "Validation Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError" } } }, }, }, } }, }, "components": { "schemas": { "Body_baz_post_router": { "title": "Body_baz_post_router", "required": ["item1", "item2"], "type": "object", "properties": { "item1": {"$ref": "#/components/schemas/Item"}, "item2": {"$ref": "#/components/schemas/Item"}, }, }, "Body_foo_post_root": { "title": "Body_foo_post_root", "required": ["item1", "item2"], "type": "object", "properties": { "item1": {"$ref": "#/components/schemas/Item"}, "item2": {"$ref": "#/components/schemas/Item"}, }, }, "HTTPValidationError": { "title": "HTTPValidationError", "type": "object", "properties": { "detail": { "title": "Detail", "type": "array", "items": {"$ref": "#/components/schemas/ValidationError"}, } }, }, "Item": { "title": "Item", "required": ["name", "price"], "type": "object", "properties": { "name": {"title": "Name", "type": "string"}, "price": {"title": "Price", "type": "number"}, }, }, "Message": { "title": "Message", "required": ["title", "description"], "type": "object", "properties": { "title": {"title": "Title", "type": "string"}, "description": {"title": "Description", "type": "string"}, }, }, "ValidationError": { "title": "ValidationError", "required": ["loc", "msg", "type"], "type": "object", "properties": { "loc": { "title": "Location", "type": "array", "items": { "anyOf": [{"type": "string"}, {"type": "integer"}] }, }, "msg": {"title": "Message", "type": "string"}, "type": {"title": "Error Type", "type": "string"}, }, }, } }, } def test_app_path_operation_overrides_generate_unique_id(): app = FastAPI(generate_unique_id_function=custom_generate_unique_id) router = APIRouter(generate_unique_id_function=custom_generate_unique_id2) @app.post( "/", response_model=List[Item], responses={404: {"model": List[Message]}}, generate_unique_id_function=custom_generate_unique_id3, ) def post_root(item1: Item, item2: Item): return item1, item2 # pragma: nocover @router.post( "/router", response_model=List[Item], responses={404: {"model": List[Message]}}, ) def post_router(item1: Item, item2: Item): return item1, item2 # pragma: nocover app.include_router(router) client = TestClient(app) response = client.get("/openapi.json") data = response.json() assert data == { "openapi": "3.0.2", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/": { "post": { "summary": "Post Root", "operationId": "baz_post_root", "requestBody": { "content": { "application/json": { "schema": { "$ref": "#/components/schemas/Body_baz_post_root" } } }, "required": True, }, "responses": { "200": { "description": "Successful Response", "content": { "application/json": { "schema": { "title": "Response Baz Post Root", "type": "array", "items": {"$ref": "#/components/schemas/Item"}, } } }, }, "404": { "description": "Not Found", "content": { "application/json": { "schema": { "title": "Response 404 Baz Post Root", "type": "array", "items": { "$ref": "#/components/schemas/Message" }, } } }, }, "422": { "description": "Validation Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError" } } }, }, }, } }, "/router": { "post": { "summary": "Post Router", "operationId": "bar_post_router", "requestBody": { "content": { "application/json": { "schema": { "$ref": "#/components/schemas/Body_bar_post_router" } } }, "required": True, }, "responses": { "200": { "description": "Successful Response", "content": { "application/json": { "schema": { "title": "Response Bar Post Router", "type": "array", "items": {"$ref": "#/components/schemas/Item"}, } } }, }, "404": { "description": "Not Found", "content": { "application/json": { "schema": { "title": "Response 404 Bar Post Router", "type": "array", "items": { "$ref": "#/components/schemas/Message" }, } } }, }, "422": { "description": "Validation Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError" } } }, }, }, } }, }, "components": { "schemas": { "Body_bar_post_router": { "title": "Body_bar_post_router", "required": ["item1", "item2"], "type": "object", "properties": { "item1": {"$ref": "#/components/schemas/Item"}, "item2": {"$ref": "#/components/schemas/Item"}, }, }, "Body_baz_post_root": { "title": "Body_baz_post_root", "required": ["item1", "item2"], "type": "object", "properties": { "item1": {"$ref": "#/components/schemas/Item"}, "item2": {"$ref": "#/components/schemas/Item"}, }, }, "HTTPValidationError": { "title": "HTTPValidationError", "type": "object", "properties": { "detail": { "title": "Detail", "type": "array", "items": {"$ref": "#/components/schemas/ValidationError"}, } }, }, "Item": { "title": "Item", "required": ["name", "price"], "type": "object", "properties": { "name": {"title": "Name", "type": "string"}, "price": {"title": "Price", "type": "number"}, }, }, "Message": { "title": "Message", "required": ["title", "description"], "type": "object", "properties": { "title": {"title": "Title", "type": "string"}, "description": {"title": "Description", "type": "string"}, }, }, "ValidationError": { "title": "ValidationError", "required": ["loc", "msg", "type"], "type": "object", "properties": { "loc": { "title": "Location", "type": "array", "items": { "anyOf": [{"type": "string"}, {"type": "integer"}] }, }, "msg": {"title": "Message", "type": "string"}, "type": {"title": "Error Type", "type": "string"}, }, }, } }, } def test_callback_override_generate_unique_id(): app = FastAPI(generate_unique_id_function=custom_generate_unique_id) callback_router = APIRouter(generate_unique_id_function=custom_generate_unique_id2) @callback_router.post( "/post-callback", response_model=List[Item], responses={404: {"model": List[Message]}}, generate_unique_id_function=custom_generate_unique_id3, ) def post_callback(item1: Item, item2: Item): return item1, item2 # pragma: nocover @app.post( "/", response_model=List[Item], responses={404: {"model": List[Message]}}, generate_unique_id_function=custom_generate_unique_id3, callbacks=callback_router.routes, ) def post_root(item1: Item, item2: Item): return item1, item2 # pragma: nocover @app.post( "/tocallback", response_model=List[Item], responses={404: {"model": List[Message]}}, ) def post_with_callback(item1: Item, item2: Item): return item1, item2 # pragma: nocover client = TestClient(app) response = client.get("/openapi.json") data = response.json() assert data == { "openapi": "3.0.2", "info": {"title": "FastAPI", "version": "0.1.0"}, "paths": { "/": { "post": { "summary": "Post Root", "operationId": "baz_post_root", "requestBody": { "content": { "application/json": { "schema": { "$ref": "#/components/schemas/Body_baz_post_root" } } }, "required": True, }, "responses": { "200": { "description": "Successful Response", "content": { "application/json": { "schema": { "title": "Response Baz Post Root", "type": "array", "items": {"$ref": "#/components/schemas/Item"}, } } }, }, "404": { "description": "Not Found", "content": { "application/json": { "schema": { "title": "Response 404 Baz Post Root", "type": "array", "items": { "$ref": "#/components/schemas/Message" }, } } }, }, "422": { "description": "Validation Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError" } } }, }, }, "callbacks": { "post_callback": { "/post-callback": { "post": { "summary": "Post Callback", "operationId": "baz_post_callback", "requestBody": { "content": { "application/json": { "schema": { "$ref": "#/components/schemas/Body_baz_post_callback" } } }, "required": True, }, "responses": { "200": { "description": "Successful Response", "content": { "application/json": { "schema": { "title": "Response Baz Post Callback", "type": "array", "items": { "$ref": "#/components/schemas/Item" }, } } }, }, "404": { "description": "Not Found", "content": { "application/json": { "schema": { "title": "Response 404 Baz Post Callback", "type": "array", "items": { "$ref": "#/components/schemas/Message" }, } } }, }, "422": { "description": "Validation Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError" } } }, }, }, } } } }, } }, "/tocallback": { "post": { "summary": "Post With Callback", "operationId": "foo_post_with_callback", "requestBody": { "content": { "application/json": { "schema": { "$ref": "#/components/schemas/Body_foo_post_with_callback" } } }, "required": True, }, "responses": { "200": { "description": "Successful Response", "content": { "application/json": { "schema": { "title": "Response Foo Post With Callback", "type": "array", "items": {"$ref": "#/components/schemas/Item"}, } } }, }, "404": { "description": "Not Found", "content": { "application/json": { "schema": { "title": "Response 404 Foo Post With Callback", "type": "array", "items": { "$ref": "#/components/schemas/Message" }, } } }, }, "422": { "description": "Validation Error", "content": { "application/json": { "schema": { "$ref": "#/components/schemas/HTTPValidationError" } } }, }, }, } }, }, "components": { "schemas": { "Body_baz_post_callback": { "title": "Body_baz_post_callback", "required": ["item1", "item2"], "type": "object", "properties": { "item1": {"$ref": "#/components/schemas/Item"}, "item2": {"$ref": "#/components/schemas/Item"}, }, }, "Body_baz_post_root": { "title": "Body_baz_post_root", "required": ["item1", "item2"], "type": "object", "properties": { "item1": {"$ref": "#/components/schemas/Item"}, "item2": {"$ref": "#/components/schemas/Item"}, }, }, "Body_foo_post_with_callback": { "title": "Body_foo_post_with_callback", "required": ["item1", "item2"], "type": "object", "properties": { "item1": {"$ref": "#/components/schemas/Item"}, "item2": {"$ref": "#/components/schemas/Item"}, }, }, "HTTPValidationError": { "title": "HTTPValidationError", "type": "object", "properties": { "detail": { "title": "Detail", "type": "array", "items": {"$ref": "#/components/schemas/ValidationError"}, } }, }, "Item": { "title": "Item", "required": ["name", "price"], "type": "object", "properties": { "name": {"title": "Name", "type": "string"}, "price": {"title": "Price", "type": "number"}, }, }, "Message": { "title": "Message", "required": ["title", "description"], "type": "object", "properties": { "title": {"title": "Title", "type": "string"}, "description": {"title": "Description", "type": "string"}, }, }, "ValidationError": { "title": "ValidationError", "required": ["loc", "msg", "type"], "type": "object", "properties": { "loc": { "title": "Location", "type": "array", "items": { "anyOf": [{"type": "string"}, {"type": "integer"}] }, }, "msg": {"title": "Message", "type": "string"}, "type": {"title": "Error Type", "type": "string"}, }, }, } }, } def test_warn_duplicate_operation_id(): def broken_operation_id(route: APIRoute): return "foo" app = FastAPI(generate_unique_id_function=broken_operation_id) @app.post("/") def post_root(item1: Item): return item1 # pragma: nocover @app.post("/second") def post_second(item1: Item): return item1 # pragma: nocover @app.post("/third") def post_third(item1: Item): return item1 # pragma: nocover client = TestClient(app) with warnings.catch_warnings(record=True) as w: warnings.simplefilter("always") client.get("/openapi.json") assert len(w) == 2 assert issubclass(w[-1].category, UserWarning) assert "Duplicate Operation ID" in str(w[-1].message)
[ "fastapi.FastAPI", "fastapi.testclient.TestClient", "warnings.catch_warnings", "fastapi.APIRouter", "warnings.simplefilter" ]
[((608, 670), 'fastapi.FastAPI', 'FastAPI', ([], {'generate_unique_id_function': 'custom_generate_unique_id'}), '(generate_unique_id_function=custom_generate_unique_id)\n', (615, 670), False, 'from fastapi import APIRouter, FastAPI\n'), ((684, 695), 'fastapi.APIRouter', 'APIRouter', ([], {}), '()\n', (693, 695), False, 'from fastapi import APIRouter, FastAPI\n'), ((1130, 1145), 'fastapi.testclient.TestClient', 'TestClient', (['app'], {}), '(app)\n', (1140, 1145), False, 'from fastapi.testclient import TestClient\n'), ((8984, 9046), 'fastapi.FastAPI', 'FastAPI', ([], {'generate_unique_id_function': 'custom_generate_unique_id'}), '(generate_unique_id_function=custom_generate_unique_id)\n', (8991, 9046), False, 'from fastapi import APIRouter, FastAPI\n'), ((9060, 9125), 'fastapi.APIRouter', 'APIRouter', ([], {'generate_unique_id_function': 'custom_generate_unique_id2'}), '(generate_unique_id_function=custom_generate_unique_id2)\n', (9069, 9125), False, 'from fastapi import APIRouter, FastAPI\n'), ((9560, 9575), 'fastapi.testclient.TestClient', 'TestClient', (['app'], {}), '(app)\n', (9570, 9575), False, 'from fastapi.testclient import TestClient\n'), ((17422, 17484), 'fastapi.FastAPI', 'FastAPI', ([], {'generate_unique_id_function': 'custom_generate_unique_id'}), '(generate_unique_id_function=custom_generate_unique_id)\n', (17429, 17484), False, 'from fastapi import APIRouter, FastAPI\n'), ((17498, 17563), 'fastapi.APIRouter', 'APIRouter', ([], {'generate_unique_id_function': 'custom_generate_unique_id2'}), '(generate_unique_id_function=custom_generate_unique_id2)\n', (17507, 17563), False, 'from fastapi import APIRouter, FastAPI\n'), ((18054, 18069), 'fastapi.testclient.TestClient', 'TestClient', (['app'], {}), '(app)\n', (18064, 18069), False, 'from fastapi.testclient import TestClient\n'), ((25929, 25991), 'fastapi.FastAPI', 'FastAPI', ([], {'generate_unique_id_function': 'custom_generate_unique_id'}), '(generate_unique_id_function=custom_generate_unique_id)\n', (25936, 25991), False, 'from fastapi import APIRouter, FastAPI\n'), ((26005, 26016), 'fastapi.APIRouter', 'APIRouter', ([], {}), '()\n', (26014, 26016), False, 'from fastapi import APIRouter, FastAPI\n'), ((26034, 26099), 'fastapi.APIRouter', 'APIRouter', ([], {'generate_unique_id_function': 'custom_generate_unique_id2'}), '(generate_unique_id_function=custom_generate_unique_id2)\n', (26043, 26099), False, 'from fastapi import APIRouter, FastAPI\n'), ((26862, 26877), 'fastapi.testclient.TestClient', 'TestClient', (['app'], {}), '(app)\n', (26872, 26877), False, 'from fastapi.testclient import TestClient\n'), ((37547, 37609), 'fastapi.FastAPI', 'FastAPI', ([], {'generate_unique_id_function': 'custom_generate_unique_id'}), '(generate_unique_id_function=custom_generate_unique_id)\n', (37554, 37609), False, 'from fastapi import APIRouter, FastAPI\n'), ((37623, 37688), 'fastapi.APIRouter', 'APIRouter', ([], {'generate_unique_id_function': 'custom_generate_unique_id2'}), '(generate_unique_id_function=custom_generate_unique_id2)\n', (37632, 37688), False, 'from fastapi import APIRouter, FastAPI\n'), ((38204, 38219), 'fastapi.testclient.TestClient', 'TestClient', (['app'], {}), '(app)\n', (38214, 38219), False, 'from fastapi.testclient import TestClient\n'), ((46070, 46132), 'fastapi.FastAPI', 'FastAPI', ([], {'generate_unique_id_function': 'custom_generate_unique_id'}), '(generate_unique_id_function=custom_generate_unique_id)\n', (46077, 46132), False, 'from fastapi import APIRouter, FastAPI\n'), ((46146, 46211), 'fastapi.APIRouter', 'APIRouter', ([], {'generate_unique_id_function': 'custom_generate_unique_id2'}), '(generate_unique_id_function=custom_generate_unique_id2)\n', (46155, 46211), False, 'from fastapi import APIRouter, FastAPI\n'), ((46758, 46773), 'fastapi.testclient.TestClient', 'TestClient', (['app'], {}), '(app)\n', (46768, 46773), False, 'from fastapi.testclient import TestClient\n'), ((54613, 54675), 'fastapi.FastAPI', 'FastAPI', ([], {'generate_unique_id_function': 'custom_generate_unique_id'}), '(generate_unique_id_function=custom_generate_unique_id)\n', (54620, 54675), False, 'from fastapi import APIRouter, FastAPI\n'), ((54698, 54763), 'fastapi.APIRouter', 'APIRouter', ([], {'generate_unique_id_function': 'custom_generate_unique_id2'}), '(generate_unique_id_function=custom_generate_unique_id2)\n', (54707, 54763), False, 'from fastapi import APIRouter, FastAPI\n'), ((55635, 55650), 'fastapi.testclient.TestClient', 'TestClient', (['app'], {}), '(app)\n', (55645, 55650), False, 'from fastapi.testclient import TestClient\n'), ((67523, 67579), 'fastapi.FastAPI', 'FastAPI', ([], {'generate_unique_id_function': 'broken_operation_id'}), '(generate_unique_id_function=broken_operation_id)\n', (67530, 67579), False, 'from fastapi import APIRouter, FastAPI\n'), ((67884, 67899), 'fastapi.testclient.TestClient', 'TestClient', (['app'], {}), '(app)\n', (67894, 67899), False, 'from fastapi.testclient import TestClient\n'), ((67909, 67945), 'warnings.catch_warnings', 'warnings.catch_warnings', ([], {'record': '(True)'}), '(record=True)\n', (67932, 67945), False, 'import warnings\n'), ((67960, 67991), 'warnings.simplefilter', 'warnings.simplefilter', (['"""always"""'], {}), "('always')\n", (67981, 67991), False, 'import warnings\n')]
#!/usr/bin/env python # encoding: utf-8 #------------------------------------------------------------------------------ # Naked | A Python command line application framework # Copyright 2014 <NAME> # MIT License #------------------------------------------------------------------------------ #------------------------------------------------------------------------------------ # c.cmd = Primary command (<executable> <primary command>) # c.cmd2 = Secondary command (<executable> <primary command> <secondary command>) # # c.option(option_string, [bool argument_required]) = test for option with optional test for positional arg to the option # c.option_with_arg(option_string) = test for option and mandatory positional argument to option test # c.flag(flag_string) = test for presence of a "--option=argument" style flag # # c.arg(arg_string) = returns the next positional argument to the arg_string argument # c.flag_arg(flag_string) = returns the flag assignment for a "--option=argument" style flag #------------------------------------------------------------------------------------ # Application start def main(): import sys from Naked.commandline import Command #from Naked.toolshed.state import StateObject from Naked.toolshed.system import stderr #------------------------------------------------------------------------------------------ # [ Instantiate command line object ] # used for all subsequent conditional logic in the CLI application #------------------------------------------------------------------------------------------ c = Command(sys.argv[0], sys.argv[1:]) #------------------------------------------------------------------------------ # [ Instantiate state object ] #------------------------------------------------------------------------------ #state = StateObject() #------------------------------------------------------------------------------------------ # [ Command Suite Validation ] - early validation of appropriate command syntax # Test that user entered a primary command, print usage if not #------------------------------------------------------------------------------------------ if not c.command_suite_validates(): from Naked.commands.usage import Usage Usage().print_usage() sys.exit(1) #------------------------------------------------------------------------------------------ # [ PRIMARY COMMAND LOGIC ] # Test for primary commands and handle them #------------------------------------------------------------------------------------------ #------------------------------------------------------------------------------ # [ args ] - identify the parsed arguments for a command string (2)= help #------------------------------------------------------------------------------ if c.cmd == "args": if c.cmd2 == "help": from Naked.commands.args import help as args_help args_help() elif c.argc > 0: # there is an argument to where that is not help from Naked.commands.args import Args a = Args(c.arg_to_cmd) a.run() else: stderr("The args command requires an example command as an argument. Use 'naked args help' for more information.", 1) #------------------------------------------------------------------------------ # [ build ] - build the C code in the Naked library (2)= help #------------------------------------------------------------------------------ elif c.cmd == "build": if c.cmd2 == "help": from Naked.commands.build import help as build_help build_help() else: from Naked.commands.build import compile_c_code import os, inspect abs_dirpath = os.path.join(os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe()))), "toolshed", "c") compile_c_code(abs_dirpath) # function calls exit status code #------------------------------------------------------------------------------ # [ classify ] - search Python application classifiers and display to user (args)-search string #------------------------------------------------------------------------------ elif c.cmd == "classify": if c.cmd2 == "help": from Naked.commands.classifier import help as classifier_help classifier_help() else: if c.second: # if search string was given search_string = c.second else: search_string = "" # absence of search string detected in Classifier, defaults to the entire list instead of search from Naked.commands.classifier import Classifier c = Classifier(search_string) c.run() #------------------------------------------------------------------------------ # [ dist ] - distribute source files to PyPI (2)=register, sdist, swheel, wheel, win, all, help #------------------------------------------------------------------------------ elif c.cmd == "dist": if c.argc > 1: from Naked.commands.dist import Dist d = Dist() if c.cmd2 == "register": # python setup.py register d.run('register') elif c.cmd2 == "sdist": # python setup.py sdist upload d.run('sdist') elif c.cmd2 == "swheel": # python setup.py sdist bdist_wheel upload d.run('swheel') elif c.cmd2 == "wheel": # python setup.py bdist_wheel upload d.run('wheel') elif c.cmd2 == "win": # python setup.py bdist_wininst upload d.run('win') elif c.cmd2 == "all": # python setup.py sdist bdist_wheel bdist_wininst upload d.run('all') elif c.cmd2 == "help": # help for command from Naked.commands.dist import help as dist_help dist_help() else: stderr("The naked dist secondary command was not recognized. Use 'naked dist help' for more information.", 1) else: stderr("Please enter a secondary command", 1) #------------------------------------------------------------------------------ # [ locate ] - locate Naked project files (2)= main, settings, setup, help #------------------------------------------------------------------------------ elif c.cmd == "locate": from Naked.commands.locate import Locator if c.cmd2 == "help": from Naked.commands.locate import help as locate_help locate_help() elif c.cmd2 == "main": l = Locator('main') elif c.cmd2 == "settings": l = Locator('settings') elif c.cmd2 == "setup": l = Locator('setup') else: l = Locator('') #handles error report to user #------------------------------------------------------------------------------ # [ make ] - make a new Naked project (2)=help (args)=project name #------------------------------------------------------------------------------ elif c.cmd == "make": from Naked.commands.make import MakeController if c.cmd2 == "help": from Naked.commands.make import help as make_help make_help() if c.arg1: # arg1 is not help so use it as the argument to the make command m = MakeController(c.arg1) else: m = MakeController(None) m.run() #------------------------------------------------------------------------------ # [ profile ] - run the profiler.py file in the Naked project (2)=help #------------------------------------------------------------------------------ elif c.cmd == "profile": if c.cmd2 == "help": from Naked.commands.profile import help as profile_help profile_help() else: from Naked.commands.profile import Profiler p = Profiler() p.run() #------------------------------------------------------------------------------ # [ pyh ] - help for python built-in library modules, classes, methods, functions #------------------------------------------------------------------------------ elif c.cmd == "pyh": if c.cmd2 == "help": from Naked.commands.pyh import pyh_help pyh_help() else: if c.argc > 1: from Naked.commands.pyh import python_help python_help(c.arg1) else: stderr("Please enter a query term with the pyh command. Use 'naked pyh help' for more information.", 1) #------------------------------------------------------------------------------ # [ test ] - Run unit tests on the project (2)= help,nose,pytest,tox,unittest (see help for args) #------------------------------------------------------------------------------ elif c.cmd == "test": if c.argc > 1: if c.cmd2 == "help": from Naked.commands.test import help as tox_help tox_help() elif c.cmd2 == "nose": from Naked.commands.test import NoseTester n = NoseTester() n.run() elif c.cmd2 == "pytest": from Naked.commands.test import PyTester p = PyTester() p.run() elif c.cmd2 == "tox": from Naked.commands.test import ToxTester if c.arg2: #user specified a python version to run with one of the tox version defs t = ToxTester(c.arg2) #instantiate with the python version else: t = ToxTester() t.run() elif c.cmd2 == "unittest": from Naked.commands.test import UnitTester if c.arg2: t = UnitTester(c.arg2) t.run() else: stderr("Please include a unit test file path. Use 'naked test help' for more information.", 1) else: stderr("The secondary command was not recognized. Use 'naked test help' for more information.", 1) else: stderr("Please include a secondary command with the 'naked test' command. Use 'naked dist help' for more information.", 1) #------------------------------------------------------------------------------------------ # [ NAKED FRAMEWORK COMMANDS ] # Naked framework provides default help, usage, and version commands for all applications # --> settings for user messages are assigned in the lib/PROJECT/settings.py file #------------------------------------------------------------------------------------------ elif c.help(): # User requested naked help (help.py module in commands directory) from Naked.commands.help import Help Help().print_help() elif c.usage(): # user requested naked usage info (usage.py module in commands directory) from Naked.commands.usage import Usage Usage().print_usage() elif c.version(): # user requested naked version (version.py module in commands directory) from Naked.commands.version import Version Version().print_version() #------------------------------------------------------------------------------------------ # [ DEFAULT MESSAGE FOR MATCH FAILURE ] # Message to provide to the user when all above conditional logic fails to meet a true condition #------------------------------------------------------------------------------------------ else: print("Could not complete the command that you entered. Please try again.") sys.exit(1) #exit if __name__ == '__main__': main()
[ "Naked.commands.make.MakeController", "Naked.commands.profile.help", "Naked.commands.dist.Dist", "Naked.commandline.Command", "Naked.commands.classifier.Classifier", "sys.exit", "Naked.commands.profile.Profiler", "Naked.commands.test.help", "Naked.commands.pyh.python_help", "Naked.commands.classif...
[((1593, 1627), 'Naked.commandline.Command', 'Command', (['sys.argv[0]', 'sys.argv[1:]'], {}), '(sys.argv[0], sys.argv[1:])\n', (1600, 1627), False, 'from Naked.commandline import Command\n'), ((2327, 2338), 'sys.exit', 'sys.exit', (['(1)'], {}), '(1)\n', (2335, 2338), False, 'import sys\n'), ((2986, 2997), 'Naked.commands.args.help', 'args_help', ([], {}), '()\n', (2995, 2997), True, 'from Naked.commands.args import help as args_help\n'), ((2297, 2304), 'Naked.commands.usage.Usage', 'Usage', ([], {}), '()\n', (2302, 2304), False, 'from Naked.commands.usage import Usage\n'), ((3137, 3155), 'Naked.commands.args.Args', 'Args', (['c.arg_to_cmd'], {}), '(c.arg_to_cmd)\n', (3141, 3155), False, 'from Naked.commands.args import Args\n'), ((3202, 3329), 'Naked.toolshed.system.stderr', 'stderr', (['"""The args command requires an example command as an argument. Use \'naked args help\' for more information."""', '(1)'], {}), '(\n "The args command requires an example command as an argument. Use \'naked args help\' for more information."\n , 1)\n', (3208, 3329), False, 'from Naked.toolshed.system import stderr\n'), ((3686, 3698), 'Naked.commands.build.help', 'build_help', ([], {}), '()\n', (3696, 3698), True, 'from Naked.commands.build import help as build_help\n'), ((3947, 3974), 'Naked.commands.build.compile_c_code', 'compile_c_code', (['abs_dirpath'], {}), '(abs_dirpath)\n', (3961, 3974), False, 'from Naked.commands.build import compile_c_code\n'), ((4422, 4439), 'Naked.commands.classifier.help', 'classifier_help', ([], {}), '()\n', (4437, 4439), True, 'from Naked.commands.classifier import help as classifier_help\n'), ((4776, 4801), 'Naked.commands.classifier.Classifier', 'Classifier', (['search_string'], {}), '(search_string)\n', (4786, 4801), False, 'from Naked.commands.classifier import Classifier\n'), ((5204, 5210), 'Naked.commands.dist.Dist', 'Dist', ([], {}), '()\n', (5208, 5210), False, 'from Naked.commands.dist import Dist\n'), ((6173, 6218), 'Naked.toolshed.system.stderr', 'stderr', (['"""Please enter a secondary command"""', '(1)'], {}), "('Please enter a secondary command', 1)\n", (6179, 6218), False, 'from Naked.toolshed.system import stderr\n'), ((6651, 6664), 'Naked.commands.locate.help', 'locate_help', ([], {}), '()\n', (6662, 6664), True, 'from Naked.commands.locate import help as locate_help\n'), ((3891, 3913), 'inspect.currentframe', 'inspect.currentframe', ([], {}), '()\n', (3911, 3913), False, 'import os, inspect\n'), ((6712, 6727), 'Naked.commands.locate.Locator', 'Locator', (['"""main"""'], {}), "('main')\n", (6719, 6727), False, 'from Naked.commands.locate import Locator\n'), ((7359, 7370), 'Naked.commands.make.help', 'make_help', ([], {}), '()\n', (7368, 7370), True, 'from Naked.commands.make import help as make_help\n'), ((7471, 7493), 'Naked.commands.make.MakeController', 'MakeController', (['c.arg1'], {}), '(c.arg1)\n', (7485, 7493), False, 'from Naked.commands.make import MakeController\n'), ((7524, 7544), 'Naked.commands.make.MakeController', 'MakeController', (['None'], {}), '(None)\n', (7538, 7544), False, 'from Naked.commands.make import MakeController\n'), ((6779, 6798), 'Naked.commands.locate.Locator', 'Locator', (['"""settings"""'], {}), "('settings')\n", (6786, 6798), False, 'from Naked.commands.locate import Locator\n'), ((7942, 7956), 'Naked.commands.profile.help', 'profile_help', ([], {}), '()\n', (7954, 7956), True, 'from Naked.commands.profile import help as profile_help\n'), ((8043, 8053), 'Naked.commands.profile.Profiler', 'Profiler', ([], {}), '()\n', (8051, 8053), False, 'from Naked.commands.profile import Profiler\n'), ((6847, 6863), 'Naked.commands.locate.Locator', 'Locator', (['"""setup"""'], {}), "('setup')\n", (6854, 6863), False, 'from Naked.commands.locate import Locator\n'), ((6894, 6905), 'Naked.commands.locate.Locator', 'Locator', (['""""""'], {}), "('')\n", (6901, 6905), False, 'from Naked.commands.locate import Locator\n'), ((8447, 8457), 'Naked.commands.pyh.pyh_help', 'pyh_help', ([], {}), '()\n', (8455, 8457), False, 'from Naked.commands.pyh import pyh_help\n'), ((8574, 8593), 'Naked.commands.pyh.python_help', 'python_help', (['c.arg1'], {}), '(c.arg1)\n', (8585, 8593), False, 'from Naked.commands.pyh import python_help\n'), ((8628, 8741), 'Naked.toolshed.system.stderr', 'stderr', (['"""Please enter a query term with the pyh command. Use \'naked pyh help\' for more information."""', '(1)'], {}), '(\n "Please enter a query term with the pyh command. Use \'naked pyh help\' for more information."\n , 1)\n', (8634, 8741), False, 'from Naked.toolshed.system import stderr\n'), ((10323, 10456), 'Naked.toolshed.system.stderr', 'stderr', (['"""Please include a secondary command with the \'naked test\' command. Use \'naked dist help\' for more information."""', '(1)'], {}), '(\n "Please include a secondary command with the \'naked test\' command. Use \'naked dist help\' for more information."\n , 1)\n', (10329, 10456), False, 'from Naked.toolshed.system import stderr\n'), ((9166, 9176), 'Naked.commands.test.help', 'tox_help', ([], {}), '()\n', (9174, 9176), True, 'from Naked.commands.test import help as tox_help\n'), ((5991, 6002), 'Naked.commands.dist.help', 'dist_help', ([], {}), '()\n', (6000, 6002), True, 'from Naked.commands.dist import help as dist_help\n'), ((6037, 6156), 'Naked.toolshed.system.stderr', 'stderr', (['"""The naked dist secondary command was not recognized. Use \'naked dist help\' for more information."""', '(1)'], {}), '(\n "The naked dist secondary command was not recognized. Use \'naked dist help\' for more information."\n , 1)\n', (6043, 6156), False, 'from Naked.toolshed.system import stderr\n'), ((9291, 9303), 'Naked.commands.test.NoseTester', 'NoseTester', ([], {}), '()\n', (9301, 9303), False, 'from Naked.commands.test import NoseTester\n'), ((10997, 11003), 'Naked.commands.help.Help', 'Help', ([], {}), '()\n', (11001, 11003), False, 'from Naked.commands.help import Help\n'), ((11809, 11820), 'sys.exit', 'sys.exit', (['(1)'], {}), '(1)\n', (11817, 11820), False, 'import sys\n'), ((9442, 9452), 'Naked.commands.test.PyTester', 'PyTester', ([], {}), '()\n', (9450, 9452), False, 'from Naked.commands.test import PyTester\n'), ((11167, 11174), 'Naked.commands.usage.Usage', 'Usage', ([], {}), '()\n', (11172, 11174), False, 'from Naked.commands.usage import Usage\n'), ((11343, 11352), 'Naked.commands.version.Version', 'Version', ([], {}), '()\n', (11350, 11352), False, 'from Naked.commands.version import Version\n'), ((9693, 9710), 'Naked.commands.test.ToxTester', 'ToxTester', (['c.arg2'], {}), '(c.arg2)\n', (9702, 9710), False, 'from Naked.commands.test import ToxTester\n'), ((9794, 9805), 'Naked.commands.test.ToxTester', 'ToxTester', ([], {}), '()\n', (9803, 9805), False, 'from Naked.commands.test import ToxTester\n'), ((10198, 10306), 'Naked.toolshed.system.stderr', 'stderr', (['"""The secondary command was not recognized. Use \'naked test help\' for more information."""', '(1)'], {}), '(\n "The secondary command was not recognized. Use \'naked test help\' for more information."\n , 1)\n', (10204, 10306), False, 'from Naked.toolshed.system import stderr\n'), ((9979, 9997), 'Naked.commands.test.UnitTester', 'UnitTester', (['c.arg2'], {}), '(c.arg2)\n', (9989, 9997), False, 'from Naked.commands.test import UnitTester\n'), ((10068, 10173), 'Naked.toolshed.system.stderr', 'stderr', (['"""Please include a unit test file path. Use \'naked test help\' for more information."""', '(1)'], {}), '(\n "Please include a unit test file path. Use \'naked test help\' for more information."\n , 1)\n', (10074, 10173), False, 'from Naked.toolshed.system import stderr\n')]
import datetime import re import pytz from django.utils.timezone import make_aware, is_aware def seconds_resolution(dt): return dt - dt.microsecond * datetime.timedelta(0, 0, 1) def minutes_resolution(dt): return dt - dt.second * datetime.timedelta(0, 1, 0) - dt.microsecond * datetime.timedelta(0, 0, 1) def date_to_datetime(date, tzinfo=None): if tzinfo is None: tzinfo = pytz.UTC return datetime.datetime(*date.timetuple()[:6], tzinfo=tzinfo) def extract_date_or_datetime(dt): if isinstance(dt, datetime.datetime): return convert_dt_to_aware(dt) return dt def convert_dt_to_aware(dt): if not isinstance(dt, datetime.datetime): dt = date_to_datetime(dt) if not is_aware(dt): # we don't want to use get_current_timezone() because # settings.TIME_ZONE may be set something different than # UTC in the future return make_aware(dt, timezone=pytz.UTC) return dt def timedelta_nice_repr(timedelta, display='long', sep=', '): """ Turns a datetime.timedelta object into a nice string repr. 'display' can be 'minimal', 'short' or 'long' (default). Taken from bitbucket.org/schinckel/django-timedelta-field. 'sql' and 'iso8601' support have been removed. """ if not isinstance(timedelta, datetime.timedelta): raise TypeError('First argument must be a timedelta.') result = [] weeks = int(timedelta.days / 7) days = timedelta.days % 7 hours = int(timedelta.seconds / 3600) minutes = int((timedelta.seconds % 3600) / 60) seconds = timedelta.seconds % 60 if display == 'minimal': words = ['w', 'd', 'h', 'm', 's'] elif display == 'short': words = [' wks', ' days', ' hrs', ' min', ' sec'] elif display == 'long': words = [' weeks', ' days', ' hours', ' minutes', ' seconds'] else: # Use django template-style formatting. # Valid values are d, g, G, h, H, i, s. return re.sub(r'([dgGhHis])', lambda x: '%%(%s)s' % x.group(), display) % { 'd': days, 'g': hours, 'G': hours if hours > 9 else '0%s' % hours, 'h': hours, 'H': hours if hours > 9 else '0%s' % hours, 'i': minutes if minutes > 9 else '0%s' % minutes, 's': seconds if seconds > 9 else '0%s' % seconds } values = [weeks, days, hours, minutes, seconds] for i in range(len(values)): if values[i]: if values[i] == 1 and len(words[i]) > 1: result.append('%i%s' % (values[i], words[i].rstrip('s'))) else: result.append('%i%s' % (values[i], words[i])) # Values with less than one second, which are considered zeroes. if len(result) == 0: # Display as 0 of the smallest unit. result.append('0%s' % (words[-1])) return sep.join(result) def timedelta_parse(string): """ Parse a string into a timedelta object. Taken from bitbucket.org/schinckel/django-timedelta-field. """ string = string.strip() if not string: raise TypeError(f'{string!r} is not a valid time interval') # This is the format we get from sometimes PostgreSQL, sqlite, # and from serialization. d = re.match( r'^((?P<days>[-+]?\d+) days?,? )?(?P<sign>[-+]?)(?P<hours>\d+):' r'(?P<minutes>\d+)(:(?P<seconds>\d+(\.\d+)?))?$', string ) if d: d = d.groupdict(0) if d['sign'] == '-': for k in 'hours', 'minutes', 'seconds': d[k] = '-' + d[k] d.pop('sign', None) else: # This is the more flexible format. d = re.match( r'^((?P<weeks>-?((\d*\.\d+)|\d+))\W*w((ee)?(k(s)?)?)(,)?\W*)?' r'((?P<days>-?((\d*\.\d+)|\d+))\W*d(ay(s)?)?(,)?\W*)?' r'((?P<hours>-?((\d*\.\d+)|\d+))\W*h(ou)?(r(s)?)?(,)?\W*)?' r'((?P<minutes>-?((\d*\.\d+)|\d+))\W*m(in(ute)?(s)?)?(,)?\W*)?' r'((?P<seconds>-?((\d*\.\d+)|\d+))\W*s(ec(ond)?(s)?)?)?\W*$', string ) if not d: raise TypeError(f'{string!r} is not a valid time interval') d = d.groupdict(0) return datetime.timedelta(**{k: float(v) for k, v in d.items()})
[ "django.utils.timezone.is_aware", "datetime.timedelta", "re.match", "django.utils.timezone.make_aware" ]
[((3273, 3415), 're.match', 're.match', (['"""^((?P<days>[-+]?\\\\d+) days?,? )?(?P<sign>[-+]?)(?P<hours>\\\\d+):(?P<minutes>\\\\d+)(:(?P<seconds>\\\\d+(\\\\.\\\\d+)?))?$"""', 'string'], {}), "(\n '^((?P<days>[-+]?\\\\d+) days?,? )?(?P<sign>[-+]?)(?P<hours>\\\\d+):(?P<minutes>\\\\d+)(:(?P<seconds>\\\\d+(\\\\.\\\\d+)?))?$'\n , string)\n", (3281, 3415), False, 'import re\n'), ((731, 743), 'django.utils.timezone.is_aware', 'is_aware', (['dt'], {}), '(dt)\n', (739, 743), False, 'from django.utils.timezone import make_aware, is_aware\n'), ((915, 948), 'django.utils.timezone.make_aware', 'make_aware', (['dt'], {'timezone': 'pytz.UTC'}), '(dt, timezone=pytz.UTC)\n', (925, 948), False, 'from django.utils.timezone import make_aware, is_aware\n'), ((3681, 4024), 're.match', 're.match', (['"""^((?P<weeks>-?((\\\\d*\\\\.\\\\d+)|\\\\d+))\\\\W*w((ee)?(k(s)?)?)(,)?\\\\W*)?((?P<days>-?((\\\\d*\\\\.\\\\d+)|\\\\d+))\\\\W*d(ay(s)?)?(,)?\\\\W*)?((?P<hours>-?((\\\\d*\\\\.\\\\d+)|\\\\d+))\\\\W*h(ou)?(r(s)?)?(,)?\\\\W*)?((?P<minutes>-?((\\\\d*\\\\.\\\\d+)|\\\\d+))\\\\W*m(in(ute)?(s)?)?(,)?\\\\W*)?((?P<seconds>-?((\\\\d*\\\\.\\\\d+)|\\\\d+))\\\\W*s(ec(ond)?(s)?)?)?\\\\W*$"""', 'string'], {}), "(\n '^((?P<weeks>-?((\\\\d*\\\\.\\\\d+)|\\\\d+))\\\\W*w((ee)?(k(s)?)?)(,)?\\\\W*)?((?P<days>-?((\\\\d*\\\\.\\\\d+)|\\\\d+))\\\\W*d(ay(s)?)?(,)?\\\\W*)?((?P<hours>-?((\\\\d*\\\\.\\\\d+)|\\\\d+))\\\\W*h(ou)?(r(s)?)?(,)?\\\\W*)?((?P<minutes>-?((\\\\d*\\\\.\\\\d+)|\\\\d+))\\\\W*m(in(ute)?(s)?)?(,)?\\\\W*)?((?P<seconds>-?((\\\\d*\\\\.\\\\d+)|\\\\d+))\\\\W*s(ec(ond)?(s)?)?)?\\\\W*$'\n , string)\n", (3689, 4024), False, 'import re\n'), ((158, 185), 'datetime.timedelta', 'datetime.timedelta', (['(0)', '(0)', '(1)'], {}), '(0, 0, 1)\n', (176, 185), False, 'import datetime\n'), ((291, 318), 'datetime.timedelta', 'datetime.timedelta', (['(0)', '(0)', '(1)'], {}), '(0, 0, 1)\n', (309, 318), False, 'import datetime\n'), ((244, 271), 'datetime.timedelta', 'datetime.timedelta', (['(0)', '(1)', '(0)'], {}), '(0, 1, 0)\n', (262, 271), False, 'import datetime\n')]
import time import xappt @xappt.register_plugin class AutoAdvance(xappt.BaseTool): message = xappt.ParamString(options={"ui": "label"}) next_iteration_advance_mode = xappt.ParamInt(choices=("no auto advance", "auto advance")) def __init__(self, *, interface: xappt.BaseInterface, **kwargs): super(AutoAdvance, self).__init__(interface=interface, **kwargs) self.max_iterations = 5 self.auto_advance = bool(self.interface.tool_data.get('next_iteration_advance_mode', 0)) self.iteration = self.interface.tool_data.get("iteration", 1) if self.iteration == self.max_iterations: step = "last" self.next_iteration_advance_mode.hidden = True else: step = xappt.humanize_ordinal(self.iteration) self.message.value = f"This is the {step} of {self.max_iterations} iterations of this tool." @classmethod def name(cls) -> str: return 'auto-advance' @classmethod def help(cls) -> str: return ("When using a tool in the Qt interface, the default behavior is to leave the tool disabled " "after a successful execution. Clicking **Next** or **Close** will move to the next tool or " "close the interface.\n\nYou can set an attribute named `auto_advance`, and when it's set " "to `True` the next tool will be automatically loaded (or the interface wil be closed) after " "a successful execution.") def message_label_text(self) -> str: raise NotImplementedError @classmethod def collection(cls) -> str: return "Examples" def execute(self, **kwargs) -> int: self.interface.progress_start() for i in range(100): progress = (i + 1) / 100.0 self.interface.progress_update(f"Iteration: {i + 1}/100", progress) time.sleep(0.01) self.interface.progress_end() last_iteration = self.iteration == self.max_iterations if last_iteration: if self.auto_advance: self.interface.message("Auto Advance is enabled for this iteration.\n\nOnce you click OK " "on this message the interface will automatically exit.") else: self.interface.message("Auto Advance is disabled for this iteration.\n\nOnce you click OK " "on this message, click the Close button to exit this interface.") else: self.interface.add_tool(AutoAdvance) if self.auto_advance: self.interface.message("Auto Advance is enabled for this iteration.\n\nOnce you click OK " "on this message the next iteration will be automatically loaded.") else: self.interface.message("Auto Advance is disabled for this iteration.\n\nOnce you click OK " "on this message click the Next button to continue to the next " "iteration.") self.interface.tool_data['iteration'] = self.iteration + 1 self.interface.tool_data['next_iteration_advance_mode'] = self.next_iteration_advance_mode.value return 0
[ "xappt.ParamInt", "xappt.humanize_ordinal", "xappt.ParamString", "time.sleep" ]
[((100, 142), 'xappt.ParamString', 'xappt.ParamString', ([], {'options': "{'ui': 'label'}"}), "(options={'ui': 'label'})\n", (117, 142), False, 'import xappt\n'), ((177, 236), 'xappt.ParamInt', 'xappt.ParamInt', ([], {'choices': "('no auto advance', 'auto advance')"}), "(choices=('no auto advance', 'auto advance'))\n", (191, 236), False, 'import xappt\n'), ((749, 787), 'xappt.humanize_ordinal', 'xappt.humanize_ordinal', (['self.iteration'], {}), '(self.iteration)\n', (771, 787), False, 'import xappt\n'), ((1882, 1898), 'time.sleep', 'time.sleep', (['(0.01)'], {}), '(0.01)\n', (1892, 1898), False, 'import time\n')]
"""Largest prime factor The prime factors of 13195 are 5, 7, 13 and 29. What is the largest prime factor of the number 600851475143? """ import math import numpy as np def largest_prime_factor_naive(number): """ Let the given number be n and let k = 2, 3, 4, 5, ... . For each k, if it is a factor of n then we divide n by k and completely divide out each k before moving to the next k. It can be seen that when k is a factor it will necessarily be prime, as all smaller factors have been removed, and the final result of this process will be n = 1. """ factor = 2 factors = [] while number > 1: if number % factor == 0: factors.append(factor) number = number // factor # Remainder guarenteed to be zero while number % factor == 0: number = number // factor # Remainder guarenteed to be zero factor += 1 return factors def largest_prime_factor_even_optimized(number): """ We know that, excluding 2, there are no even prime numbers. So we can increase factor by 2 per iteration after having found the """ factors = [] factor = 2 if number % factor == 0: number = number // factor factors.append(factor) while number % factor == 0: number = number // factor factor = 3 while number > 1: if number % factor == 0: factors.append(factor) number = number // factor # Remainder guarenteed to be zero while number % factor == 0: number = number // factor # Remainder guarenteed to be zero factor += 2 return factors def largest_prime_factor_square_optimized(number): """ Every number n can at most have one prime factor greater than n. If we, after dividing out some prime factor, calculate the square root of the remaining number we can use that square root as upper limit for factor. If factor exceeds this square root we know the remaining number is prime. """ factors = [] factor = 2 if number % factor == 0: number = number // factor factors.append(factor) while number % factor == 0: number = number // factor factor = 3 max_factor = math.sqrt(number) while number > 1 and factor <= max_factor: if number % factor == 0: factors.append(factor) number = number // factor while number % factor == 0: number = number // factor max_factor = math.sqrt(number) factor += 2 return factors def idx_sieve(length): """Static length sieve-based prime generator""" primes = [] is_prime = np.array([True]*length) i = 2 while i < length: if is_prime[i]: is_prime[np.arange(i, length, i)] = False primes.append(i) else: i += 1 return primes def prime_factor(n, primes): i = 0 factors = [] while n != 1: while (n % primes[i]) != 0: i += 1 factors.append(primes[i]) n = n / primes[i] return factors if __name__ == '__main__': number = 600851475143 print(largest_prime_factor_naive(number)) print(largest_prime_factor_even_optimized(number)) print(largest_prime_factor_square_optimized(number)) number = 600851475143 primes = idx_sieve(20000) print(max(prime_factor(number, primes)))
[ "numpy.array", "math.sqrt", "numpy.arange" ]
[((2287, 2304), 'math.sqrt', 'math.sqrt', (['number'], {}), '(number)\n', (2296, 2304), False, 'import math\n'), ((2735, 2760), 'numpy.array', 'np.array', (['([True] * length)'], {}), '([True] * length)\n', (2743, 2760), True, 'import numpy as np\n'), ((2569, 2586), 'math.sqrt', 'math.sqrt', (['number'], {}), '(number)\n', (2578, 2586), False, 'import math\n'), ((2836, 2859), 'numpy.arange', 'np.arange', (['i', 'length', 'i'], {}), '(i, length, i)\n', (2845, 2859), True, 'import numpy as np\n')]
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Copyright (c) 2012 OpenStack, LLC. # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. """Tests for hook customization.""" import stevedore from nova import hooks from nova import test class SampleHookA(object): name = "a" def _add_called(self, op, kwargs): called = kwargs.get('called', None) if called is not None: called.append(op + self.name) def pre(self, *args, **kwargs): self._add_called("pre", kwargs) class SampleHookB(SampleHookA): name = "b" def post(self, rv, *args, **kwargs): self._add_called("post", kwargs) class MockEntryPoint(object): def __init__(self, cls): self.cls = cls def load(self): return self.cls class HookTestCase(test.TestCase): def _mock_load_plugins(self, iload, iargs, ikwargs): return [ stevedore.extension.Extension('test_hook', MockEntryPoint(SampleHookA), SampleHookA, SampleHookA()), stevedore.extension.Extension('test_hook', MockEntryPoint(SampleHookB), SampleHookB, SampleHookB()), ] def setUp(self): super(HookTestCase, self).setUp() hooks.reset() self.stubs.Set(stevedore.extension.ExtensionManager, '_load_plugins', self._mock_load_plugins) @hooks.add_hook('test_hook') def _hooked(self, a, b=1, c=2, called=None): return 42 def test_basic(self): self.assertEqual(42, self._hooked(1)) mgr = hooks._HOOKS['test_hook'] self.assertEqual(2, len(mgr.extensions)) self.assertEqual(SampleHookA, mgr.extensions[0].plugin) self.assertEqual(SampleHookB, mgr.extensions[1].plugin) def test_order_of_execution(self): called_order = [] self._hooked(42, called=called_order) self.assertEqual(['prea', 'preb', 'postb'], called_order)
[ "nova.hooks.add_hook", "nova.hooks.reset" ]
[((1920, 1947), 'nova.hooks.add_hook', 'hooks.add_hook', (['"""test_hook"""'], {}), "('test_hook')\n", (1934, 1947), False, 'from nova import hooks\n'), ((1773, 1786), 'nova.hooks.reset', 'hooks.reset', ([], {}), '()\n', (1784, 1786), False, 'from nova import hooks\n')]
""" This module defines the class QueryUniprot which connects to APIs at http://www.uniprot.org/uploadlists/, querying reactome pathways from uniprot id. * map_enzyme_commission_id_to_uniprot_ids(ec_id) Description: map enzyme commission id to UniProt ids Args: ec_id (str): enzyme commission id, e.g., "ec:1.4.1.17" Returns: ids (set): a set of the enzyme commission ids, or empty set if no UniProt id can be obtained or the response status code is not 200. """ __author__ = "" __copyright__ = "" __credits__ = [] __license__ = "" __version__ = "" __maintainer__ = "" __email__ = "" __status__ = "Prototype" # import requests # import requests_cache from cache_control_helper import CacheControlHelper import CachedMethods import sys import urllib.parse import xmltodict class QueryUniprot: API_BASE_URL = "http://www.uniprot.org/uploadlists/" TIMEOUT_SEC = 120 HANDLER_MAP = { 'map_enzyme_commission_id_to_uniprot_ids': 'uniprot/?query=({id})&format=tab&columns=id', 'get_protein': 'uniprot/{id}.xml' } @staticmethod @CachedMethods.register def uniprot_id_to_reactome_pathways(uniprot_id): """returns a ``set`` of reactome IDs of pathways associated with a given string uniprot ID :param uniprot_id: a ``str`` uniprot ID, like ``"P68871"`` :returns: a ``set`` of string Reactome IDs """ payload = { 'from': 'ACC', 'to': 'REACTOME_ID', 'format': 'tab', 'query': uniprot_id } contact = "<EMAIL>" header = {'User-Agent': 'Python %s' % contact} requests = CacheControlHelper() try: url =QueryUniprot.API_BASE_URL res = requests.post(QueryUniprot.API_BASE_URL, data=payload, headers=header) except requests.exceptions.Timeout: print(url, file=sys.stderr) print('Timeout in QueryUniprot for URL: ' + QueryUniprot.API_BASE_URL, file=sys.stderr) return None except KeyboardInterrupt: sys.exit(0) except BaseException as e: print(url, file=sys.stderr) print('%s received in QueryUniprot for URL: %s' % (e, url), file=sys.stderr) return None status_code = res.status_code if status_code != 200: print(QueryUniprot.API_BASE_URL, file=sys.stderr) print('Status code ' + str(status_code) + ' for url: ' + QueryUniprot.API_BASE_URL, file=sys.stderr) return None # assert 200 == res.status_code res_set = set() for line in res.text.splitlines(): field_str = line.split("\t")[1] if field_str != "To": res_set.add(field_str) return res_set @staticmethod def __access_api(handler): api_base_url = 'http://www.uniprot.org' url = api_base_url + '/' + handler #print(url) contact = "<EMAIL>" header = {'User-Agent': 'Python %s' % contact} requests = CacheControlHelper() try: res = requests.get(url, timeout=QueryUniprot.TIMEOUT_SEC, headers=header) except requests.exceptions.Timeout: print(url, file=sys.stderr) print('Timeout in QueryUniprot for URL: ' + url, file=sys.stderr) return None except requests.exceptions.ChunkedEncodingError: print(url, file=sys.stderr) print('ChunkedEncodingError for URL: ' + url, file=sys.stderr) return None except BaseException as e: print(url, file=sys.stderr) print('%s received in QueryUniprot for URL: %s' % (e, url), file=sys.stderr) return None status_code = res.status_code if status_code != 200: print(url, file=sys.stderr) print('Status code ' + str(status_code) + ' for url: ' + url, file=sys.stderr) return None return res.text @staticmethod def map_enzyme_commission_id_to_uniprot_ids(ec_id): res_set = set() if not isinstance(ec_id, str): return res_set ec_id_encoded = urllib.parse.quote_plus(ec_id) handler = QueryUniprot.HANDLER_MAP['map_enzyme_commission_id_to_uniprot_ids'].format(id=ec_id_encoded) res = QueryUniprot.__access_api(handler) if res is not None: res = res[res.find('\n')+1:] for line in res.splitlines(): res_set.add(line) return res_set @staticmethod def __get_entity(entity_type, entity_id): if entity_id[:10] == 'UniProtKB:': entity_id = entity_id[10:] handler = QueryUniprot.HANDLER_MAP[entity_type].format(id=entity_id) results = QueryUniprot.__access_api(handler) entity = None if results is not None: obj = xmltodict.parse(results) if 'uniprot' in obj.keys(): if 'entry' in obj['uniprot'].keys(): entity = obj['uniprot']['entry'] return entity @staticmethod def get_protein_gene_symbol(entity_id): ret_symbol = "None" if not isinstance(entity_id, str): return ret_symbol entity_obj = QueryUniprot.__get_entity("get_protein", entity_id) if entity_obj is not None: if 'gene' in entity_obj.keys(): if "name" in entity_obj["gene"].keys(): gene_name_obj = entity_obj["gene"]["name"] if not type(gene_name_obj) == list: gene_name_obj = [gene_name_obj] for name_dict in gene_name_obj: # print(name_dict) if "primary" in name_dict.values() and "#text" in name_dict.keys(): ret_symbol = name_dict["#text"] return ret_symbol @staticmethod def __get_name(entity_type, entity_id): entity_obj = QueryUniprot.__get_entity(entity_type, entity_id) name = "UNKNOWN" if entity_obj is not None: if 'protein' in entity_obj.keys(): if 'recommendedName' in entity_obj['protein'].keys(): if 'fullName' in entity_obj['protein']['recommendedName'].keys(): name = entity_obj['protein']['recommendedName']['fullName'] if isinstance(name, dict): name = name['#text'] return name @staticmethod def get_protein_name(protein_id): if not isinstance(protein_id, str): return "UNKNOWN" return QueryUniprot.__get_name("get_protein", protein_id) @staticmethod def get_citeable_accession_for_accession(accession_number): res_acc = None res_tab = QueryUniprot.__access_api("uniprot/" + accession_number + ".tab") if res_tab is None: return res_acc res_lines = res_tab.splitlines() if len(res_lines) > 1: res_acc = res_lines[1].split("\t")[0] return res_acc if __name__ == '__main__': print(QueryUniprot.get_citeable_accession_for_accession("P35354")) print(QueryUniprot.get_citeable_accession_for_accession("A8K802")) print(QueryUniprot.get_citeable_accession_for_accession("Q16876")) # print(QueryUniprot.uniprot_id_to_reactome_pathways("P68871")) # print(QueryUniprot.uniprot_id_to_reactome_pathways("Q16621")) # print(QueryUniprot.uniprot_id_to_reactome_pathways("P09601")) print(CachedMethods.cache_info()) print(QueryUniprot.map_enzyme_commission_id_to_uniprot_ids("ec:1.4.1.17")) # small results print(QueryUniprot.map_enzyme_commission_id_to_uniprot_ids("ec:1.3.1.110")) # empty result print(QueryUniprot.map_enzyme_commission_id_to_uniprot_ids("ec:1.2.1.22")) # large results print(QueryUniprot.map_enzyme_commission_id_to_uniprot_ids("ec:4.4.1.xx")) # fake id print(QueryUniprot.map_enzyme_commission_id_to_uniprot_ids("R-HSA-1912422")) # wrong id print(QueryUniprot.get_protein_gene_symbol('UniProtKB:P20848')) print(QueryUniprot.get_protein_gene_symbol("UniProtKB:P01358")) print(QueryUniprot.get_protein_gene_symbol("UniProtKB:Q96P88")) print(QueryUniprot.get_protein_name('UniProtKB:P01358')) print(QueryUniprot.get_protein_name('UniProtKB:P20848')) print(QueryUniprot.get_protein_name('UniProtKB:Q9Y471')) print(QueryUniprot.get_protein_name('UniProtKB:O60397')) print(QueryUniprot.get_protein_name('UniProtKB:Q8IZJ3')) print(QueryUniprot.get_protein_name('UniProtKB:Q7Z2Y8')) print(QueryUniprot.get_protein_name('UniProtKB:Q8IWN7')) print(QueryUniprot.get_protein_name('UniProtKB:Q156A1'))
[ "sys.exit", "cache_control_helper.CacheControlHelper", "CachedMethods.cache_info", "xmltodict.parse" ]
[((1700, 1720), 'cache_control_helper.CacheControlHelper', 'CacheControlHelper', ([], {}), '()\n', (1718, 1720), False, 'from cache_control_helper import CacheControlHelper\n'), ((3100, 3120), 'cache_control_helper.CacheControlHelper', 'CacheControlHelper', ([], {}), '()\n', (3118, 3120), False, 'from cache_control_helper import CacheControlHelper\n'), ((7613, 7639), 'CachedMethods.cache_info', 'CachedMethods.cache_info', ([], {}), '()\n', (7637, 7639), False, 'import CachedMethods\n'), ((4935, 4959), 'xmltodict.parse', 'xmltodict.parse', (['results'], {}), '(results)\n', (4950, 4959), False, 'import xmltodict\n'), ((2121, 2132), 'sys.exit', 'sys.exit', (['(0)'], {}), '(0)\n', (2129, 2132), False, 'import sys\n')]
import re from streamlink.plugin import Plugin from streamlink.plugin.api import validate from streamlink.stream import HTTPStream from streamlink import NoStreamsError class Tamago(Plugin): _url_re = re.compile(r"https?://(?:player\.)?tamago\.live/w/(?P<id>\d+)") _api_url_base = "https://player.tamago.live/api/rooms/{id}" _api_response_schema = validate.Schema({ u"status": 200, u"message": u"Success", u"data": { u"room_number": validate.text, u"stream": {validate.text: validate.url()} } }) _stream_qualities = { u"150": "144p", u"350": "360p", u"550": "540p", u"900": "720p", } @classmethod def can_handle_url(cls, url): return cls._url_re.match(url) is not None def _get_streams(self): user_id = self._url_re.match(self.url).group('id') try: api_response = self.session.http.get(self._api_url_base.format(id=user_id)) streams = self.session.http.json(api_response, schema=self._api_response_schema)['data']['stream'] except Exception: raise NoStreamsError(self.url) unique_stream_urls = [] for stream in streams.keys(): if streams[stream] not in unique_stream_urls: unique_stream_urls.append(streams[stream]) quality = self._stream_qualities[stream] if stream in self._stream_qualities.keys() else "720p+" yield quality, HTTPStream(self.session, streams[stream]) __plugin__ = Tamago
[ "streamlink.NoStreamsError", "streamlink.plugin.api.validate.url", "streamlink.stream.HTTPStream", "re.compile" ]
[((209, 274), 're.compile', 're.compile', (['"""https?://(?:player\\\\.)?tamago\\\\.live/w/(?P<id>\\\\d+)"""'], {}), "('https?://(?:player\\\\.)?tamago\\\\.live/w/(?P<id>\\\\d+)')\n", (219, 274), False, 'import re\n'), ((1150, 1174), 'streamlink.NoStreamsError', 'NoStreamsError', (['self.url'], {}), '(self.url)\n', (1164, 1174), False, 'from streamlink import NoStreamsError\n'), ((541, 555), 'streamlink.plugin.api.validate.url', 'validate.url', ([], {}), '()\n', (553, 555), False, 'from streamlink.plugin.api import validate\n'), ((1507, 1548), 'streamlink.stream.HTTPStream', 'HTTPStream', (['self.session', 'streams[stream]'], {}), '(self.session, streams[stream])\n', (1517, 1548), False, 'from streamlink.stream import HTTPStream\n')]
""" Name: modules.py Desc: This script defines some base module for building networks. """ from typing import Any import torch import torch.nn as nn import torch.nn.functional as F class UNet_down_block(nn.Module): def __init__(self, input_channel, output_channel, down_size=True): super(UNet_down_block, self).__init__() self.conv1 = nn.Conv2d(input_channel, output_channel, 3, padding=1) self.bn1 = nn.GroupNorm(8, output_channel) self.conv2 = nn.Conv2d(output_channel, output_channel, 3, padding=1) self.bn2 = nn.GroupNorm(8, output_channel) self.conv3 = nn.Conv2d(output_channel, output_channel, 3, padding=1) self.bn3 = nn.GroupNorm(8, output_channel) self.max_pool = nn.MaxPool2d(2, 2) self.relu = nn.ReLU() self.down_size = down_size def forward(self, x): x = self.relu(self.bn1(self.conv1(x))) x = self.relu(self.bn2(self.conv2(x))) x = self.relu(self.bn3(self.conv3(x))) if self.down_size: x = self.max_pool(x) return x class UNet_up_block(nn.Module): def __init__(self, prev_channel, input_channel, output_channel, up_sample=True): super(UNet_up_block, self).__init__() self.up_sampling = nn.Upsample(scale_factor=2, mode='bilinear', align_corners=False) self.conv1 = nn.Conv2d(prev_channel + input_channel, output_channel, 3, padding=1) self.bn1 = nn.GroupNorm(8, output_channel) self.conv2 = nn.Conv2d(output_channel, output_channel, 3, padding=1) self.bn2 = nn.GroupNorm(8, output_channel) self.conv3 = nn.Conv2d(output_channel, output_channel, 3, padding=1) self.bn3 = nn.GroupNorm(8, output_channel) self.relu = torch.nn.ReLU() self.up_sample = up_sample def forward(self, prev_feature_map, x): if self.up_sample: x = self.up_sampling(x) x = torch.cat((x, prev_feature_map), dim=1) x = self.relu(self.bn1(self.conv1(x))) x = self.relu(self.bn2(self.conv2(x))) x = self.relu(self.bn3(self.conv3(x))) return x class UNet(nn.Module): def __init__(self, downsample=6, in_channels=3, out_channels=3): super(UNet, self).__init__() self.in_channels, self.out_channels, self.downsample = in_channels, out_channels, downsample self.down1 = UNet_down_block(in_channels, 16, False) self.down_blocks = nn.ModuleList( [UNet_down_block(2**(4+i), 2**(5+i), True) for i in range(0, downsample)] ) bottleneck = 2**(4 + downsample) self.mid_conv1 = nn.Conv2d(bottleneck, bottleneck, 3, padding=1) self.bn1 = nn.GroupNorm(8, bottleneck) self.mid_conv2 = nn.Conv2d(bottleneck, bottleneck, 3, padding=1) self.bn2 = nn.GroupNorm(8, bottleneck) self.mid_conv3 = torch.nn.Conv2d(bottleneck, bottleneck, 3, padding=1) self.bn3 = nn.GroupNorm(8, bottleneck) self.up_blocks = nn.ModuleList( [UNet_up_block(2**(4+i), 2**(5+i), 2**(4+i)) for i in range(0, downsample)] ) self.last_conv1 = nn.Conv2d(16, 16, 3, padding=1) self.last_bn = nn.GroupNorm(8, 16) self.last_conv2 = nn.Conv2d(16, out_channels, 1, padding=0) self.relu = nn.ReLU() def forward(self, x): x = self.down1(x) xvals = [x] for i in range(0, self.downsample): x = self.down_blocks[i](x) xvals.append(x) x = self.relu(self.bn1(self.mid_conv1(x))) x = self.relu(self.bn2(self.mid_conv2(x))) x = self.relu(self.bn3(self.mid_conv3(x))) for i in range(0, self.downsample)[::-1]: x = self.up_blocks[i](xvals[i], x) x = self.relu(self.last_bn(self.last_conv1(x))) x = self.relu(self.last_conv2(x)) #x = self.last_conv2(x) return x ''' class UNetDepth(nn.Module): def __init__(self): super(UNetDepth, self).__init__() self.down_block1 = UNet_down_block(3, 16, False) self.down_block2 = UNet_down_block(16, 32, True) self.down_block3 = UNet_down_block(32, 64, True) self.down_block4 = UNet_down_block(64, 128, True) self.down_block5 = UNet_down_block(128, 256, True) self.down_block6 = UNet_down_block(256, 512, True) self.down_block7 = UNet_down_block(512, 1024, False) self.mid_conv1 = nn.Conv2d(1024, 1024, 3, padding=1) self.bn1 = nn.GroupNorm(8, 1024) self.mid_conv2 = nn.Conv2d(1024, 1024, 3, padding=1) self.bn2 = nn.GroupNorm(8, 1024) self.mid_conv3 = torch.nn.Conv2d(1024, 1024, 3, padding=1) self.bn3 = torch.nn.GroupNorm(8, 1024) self.up_block1 = UNet_up_block(512, 1024, 512, False) self.up_block2 = UNet_up_block(256, 512, 256, True) self.up_block3 = UNet_up_block(128, 256, 128, True) self.up_block4 = UNet_up_block(64, 128, 64, True) self.up_block5 = UNet_up_block(32, 64, 32, True) self.up_block6 = UNet_up_block(16, 32, 16, True) self.last_conv1 = nn.Conv2d(16, 16, 3, padding=1) self.last_bn = nn.GroupNorm(8, 16) self.last_conv2 = nn.Conv2d(16, 1, 1, padding=0) self.relu = nn.ReLU() def forward(self, x): x = self.x1 = self.down_block1(x) x = self.x2 = self.down_block2(self.x1) x = self.x3 = self.down_block3(self.x2) x = self.x4 = self.down_block4(self.x3) x = self.x5 = self.down_block5(self.x4) x = self.x6 = self.down_block6(self.x5) x = self.x7 = self.down_block7(self.x6) x = self.relu(self.bn1(self.mid_conv1(x))) x = self.relu(self.bn2(self.mid_conv2(x))) x = self.relu(self.bn3(self.mid_conv3(x))) x = self.up_block1(self.x6, x) x = self.up_block2(self.x5, x) x = self.up_block3(self.x4, x) x = self.up_block4(self.x3, x) x = self.up_block5(self.x2, x) x = self.up_block6(self.x1, x) x = self.relu(self.last_bn(self.last_conv1(x))) x = self.last_conv2(x) return x ''' class UNetDepth(nn.Module): def __init__(self): super(UNetDepth, self).__init__() self.down_block1 = UNet_down_block(3, 16, False) self.down_block2 = UNet_down_block(16, 32, True) self.down_block3 = UNet_down_block(32, 64, True) self.down_block4 = UNet_down_block(64, 128, True) self.down_block5 = UNet_down_block(128, 256, True) self.down_block6 = UNet_down_block(256, 512, False) self.mid_conv1 = nn.Conv2d(512, 512, 3, padding=1) self.bn1 = nn.GroupNorm(8, 512) self.mid_conv2 = nn.Conv2d(512, 512, 3, padding=1) self.bn2 = nn.GroupNorm(8, 512) self.mid_conv3 = torch.nn.Conv2d(512, 512, 3, padding=1) self.bn3 = torch.nn.GroupNorm(8, 512) self.up_block1 = UNet_up_block(256, 512, 256, False) self.up_block2 = UNet_up_block(128, 256, 128, True) self.up_block3 = UNet_up_block(64, 128, 64, True) self.up_block4 = UNet_up_block(32, 64, 32, True) self.up_block5 = UNet_up_block(16, 32, 16, True) self.last_conv1 = nn.Conv2d(16, 16, 3, padding=1) self.last_bn = nn.GroupNorm(8, 16) self.last_conv2 = nn.Conv2d(16, 1, 1, padding=0) self.relu = nn.ReLU() def forward(self, x): x = self.x1 = self.down_block1(x) x = self.x2 = self.down_block2(self.x1) x = self.x3 = self.down_block3(self.x2) x = self.x4 = self.down_block4(self.x3) x = self.x5 = self.down_block5(self.x4) x = self.x6 = self.down_block6(self.x5) x = self.relu(self.bn1(self.mid_conv1(x))) x = self.relu(self.bn2(self.mid_conv2(x))) x = self.relu(self.bn3(self.mid_conv3(x))) x = self.up_block1(self.x5, x) x = self.up_block2(self.x4, x) x = self.up_block3(self.x3, x) x = self.up_block4(self.x2, x) x = self.up_block5(self.x1, x) x = self.relu(self.last_bn(self.last_conv1(x))) x = self.last_conv2(x) return x class UNet_sim(nn.Module): def __init__(self, downsample=4, in_channels=3, out_channels=3): super(UNet_sim, self).__init__() self.downsample, self.in_channels, self.out_channels = downsample, in_channels, out_channels self.conv = ConvBlock(in_channels, 64) self.down_blocks = nn.ModuleList( [UNet_down_block(2 ** (6 + i), 2 ** (7 + i), True) for i in range(0, downsample)] ) bottleneck = 2 ** (6 + downsample) self.mid_conv1 = nn.Conv2d(bottleneck, bottleneck, 3, padding=1) self.bn1 = nn.GroupNorm(8, bottleneck) self.mid_conv2 = nn.Conv2d(bottleneck, bottleneck, 3, padding=1) self.bn2 = nn.GroupNorm(8, bottleneck) self.mid_conv3 = torch.nn.Conv2d(bottleneck, bottleneck, 3, padding=1) self.bn3 = nn.GroupNorm(8, bottleneck) self.up_blocks = nn.ModuleList( [UNet_up_block(2 ** (6 + i), 2 ** (7 + i), 2 ** (6 + i)) for i in range(0, downsample)] ) self.last_conv1 = nn.Conv2d(64, 64, 3, padding=1) self.last_bn = nn.GroupNorm(8, 64) self.last_conv2 = nn.Conv2d(64, out_channels, 1, padding=0) self.relu = nn.ReLU() def forward(self, x): x = self.conv(x) xvals = [x] for i in range(0, self.downsample): x = self.down_blocks[i](x) xvals.append(x) x = self.relu(self.bn1(self.mid_conv1(x))) x = self.relu(self.bn2(self.mid_conv2(x))) x = self.relu(self.bn3(self.mid_conv3(x))) for i in range(0, self.downsample)[::-1]: x = self.up_blocks[i](xvals[i], x) x = self.last_bn(self.last_conv1(x)) x = self.last_conv2(x) return x class Encoder(nn.Module): def __init__(self, downsample=6, in_channels=3): """:downsample the number of down blocks :in_channels the channel of input tensor """ super(Encoder, self).__init__() self.in_channels, self.downsample = in_channels, downsample self.down1 = UNet_down_block(in_channels, 16, False) self.down_blocks = nn.ModuleList( [UNet_down_block(2 ** (4 + i), 2 ** (5 + i), True) for i in range(0, downsample)] ) bottleneck = 2 ** (4 + downsample) self.mid_conv1 = nn.Conv2d(bottleneck, bottleneck, 3, padding=1) self.bn1 = nn.GroupNorm(8, bottleneck) self.mid_conv2 = nn.Conv2d(bottleneck, bottleneck, 3, padding=1) self.bn2 = nn.GroupNorm(8, bottleneck) self.mid_conv3 = torch.nn.Conv2d(bottleneck, bottleneck, 3, padding=1) self.bn3 = nn.GroupNorm(8, bottleneck) self.relu = nn.ReLU() def forward(self, x): x = self.down1(x) xvals = [x] for i in range(0, self.downsample): x = self.down_blocks[i](x) xvals.append(x) x = self.relu(self.bn1(self.mid_conv1(x))) x = self.relu(self.bn2(self.mid_conv2(x))) x = self.relu(self.bn3(self.mid_conv3(x))) return xvals, x class Decoder(nn.Module): def __init__(self, downsample, out_channels, combine_num=0): super(Decoder, self).__init__() self.out_channels, self.downsample = out_channels, downsample self.combine_num = combine_num self.up_blocks = nn.ModuleList( [UNet_up_block(2 ** (4 + i), 2 ** (5 + i), 2 ** (4 + i)) for i in range(0, self.downsample)]) self.last_conv1 = nn.Conv2d(16, 16, 3, padding=1) self.last_bn = nn.GroupNorm(8, 16) self.last_conv2 = nn.Conv2d(16, self.out_channels, 1, padding=0) self.up_sampling = nn.Upsample(scale_factor=2, mode='bilinear', align_corners=False) self.relu = nn.ReLU() def forward(self, xvals, x): devals = [] for i in range(0, self.downsample)[::-1]: x = self.up_blocks[i](xvals[i], x) if i < self.combine_num: devals.append(x) y = self.last_bn(self.last_conv1(x)) y = self.last_conv2(x) if len(devals) > 0: for j, decode in enumerate(devals): for _ in range(len(devals) - 1 - j): decode = self.up_sampling(decode) devals[j] = decode combine_x = torch.cat(devals[::-1], dim=1) return y, combine_x else: return y, x class Encoder_sim(nn.Module): def __init__(self, downsample=4, in_channels=3): super(Encoder_sim, self).__init__() self.downsample = downsample self.conv = ConvBlock(in_channels, 64) self.down_blocks = nn.ModuleList( [UNet_down_block(2 ** (6 + i), 2 ** (7 + i), True) for i in range(0, downsample)] ) bottleneck = 2 ** (6 + self.downsample) self.mid_conv1 = nn.Conv2d(bottleneck, bottleneck, 3, padding=1) self.bn1 = nn.GroupNorm(8, bottleneck) self.mid_conv2 = nn.Conv2d(bottleneck, bottleneck, 3, padding=1) self.bn2 = nn.GroupNorm(8, bottleneck) self.mid_conv3 = torch.nn.Conv2d(bottleneck, bottleneck, 3, padding=1) self.bn3 = nn.GroupNorm(8, bottleneck) self.relu = nn.ReLU() def forward(self, x): x = self.conv(x) xvals = [x] for i in range(0, self.downsample): x = self.down_blocks[i](x) xvals.append(x) x = self.relu(self.bn1(self.mid_conv1(x))) x = self.relu(self.bn2(self.mid_conv2(x))) x = self.relu(self.bn3(self.mid_conv3(x))) return xvals, x class Decoder_sim(nn.Module): def __init__(self, downsample, out_channels): super(Decoder_sim, self).__init__() self.downsample, self.out_channels = downsample, out_channels self.up_blocks = nn.ModuleList( [UNet_up_block(2 ** (6 + i), 2 ** (7 + i), 2 ** (6 + i)) for i in range(0, self.downsample)] ) self.last_conv1 = nn.Conv2d(64, 64, 3, padding=1) self.last_bn = nn.GroupNorm(8, 64) self.last_conv2 = nn.Conv2d(64, self.out_channels, 1, padding=0) self.relu = nn.ReLU() def forward(self, xvals, x): for i in range(0, self.downsample)[::-1]: x = self.up_blocks[i](xvals[i], x) y = self.last_bn(self.last_conv1(x)) y = self.last_conv2(y) return y, x class ThreeD2NorDepth(nn.Module): def __init__(self, downsample=3, use_simple=True): super(ThreeD2NorDepth, self).__init__() if use_simple: self.threeD_encoder = Encoder_sim(downsample=downsample, in_channels=3) self.normal_decoder = Decoder_sim(downsample=downsample, out_channels=3) self.depth_decoder = Decoder_sim(downsample=downsample, out_channels=1) else: self.threeD_encoder = Encoder(downsample=downsample, in_channels=3) self.normal_decoder = Decoder(downsample=downsample, out_channels=3, combine_num=0) self.depth_decoder = Decoder(downsample=downsample, out_channels=1, combine_num=0) def forward(self, x): xvals, x = self.threeD_encoder(x) nor, _ = self.normal_decoder(xvals, x) dep, _ = self.depth_decoder(xvals, x) return nor, dep class AlbedoDecoder_sim(nn.Module): def __init__(self, downsample=6, out_channels=1): super(AlbedoDecoder_sim, self).__init__() self.out_channels, self.downsample = out_channels, downsample self.up_blocks = nn.ModuleList( [UNet_up_block(2 ** (7 + i), 2 ** (8 + i), 2 ** (7 + i)) for i in range(0, self.downsample)]) self.last_conv1 = nn.Conv2d(128, 64, 3, padding=1) self.last_bn = nn.GroupNorm(8, 64) self.last_conv2 = nn.Conv2d(64, self.out_channels, 1, padding=0) self.relu = nn.ReLU() def forward(self, xvals, x): for i in range(0, self.downsample)[::-1]: x = self.up_blocks[i](xvals[i], x) y = self.last_bn(self.last_conv1(x)) y = self.last_conv2(y) return y, x class AlbedoDecoder(nn.Module): def __init__(self, downsample=6, out_channels=1): super(AlbedoDecoder, self).__init__() self.out_channels, self.downsample = out_channels, downsample self.up_blocks = nn.ModuleList( [UNet_up_block(2 ** (5 + i), 2 ** (6 + i), 2 ** (5 + i)) for i in range(0, self.downsample)]) self.last_conv1 = nn.Conv2d(32, 32, 3, padding=1) self.last_bn = nn.GroupNorm(8, 32) self.last_conv2 = nn.Conv2d(32, self.out_channels, 1, padding=0) self.relu = nn.ReLU() def forward(self, xvals, x): for i in range(0, self.downsample)[::-1]: x = self.up_blocks[i](xvals[i], x) y = self.last_bn(self.last_conv1(x)) y = self.last_conv2(y) return y, x class ConvBlock(nn.Module): def __init__(self, f1, f2, kernel_size=3, padding=1, use_groupnorm=False, groups=8, dilation=1, transpose=False): super(ConvBlock, self).__init__() self.transpose = transpose self.conv = nn.Conv2d(f1, f2, (kernel_size, kernel_size), dilation=dilation, padding=padding*dilation) if self.transpose: self.convt = nn.ConvTranspose2d( f1, f1, (3, 3), dilation=dilation, stride=2, padding=dilation, output_padding=1 ) if use_groupnorm: self.bn = nn.GroupNorm(groups, f1) else: self.bn = nn.BatchNorm2d(f1) def forward(self, x): # x = F.dropout(x, 0.04, self.training) x = self.bn(x) if self.transpose: # x = F.upsample(x, scale_factor=2, mode='bilinear') x = F.relu(self.convt(x)) # x = x[:, :, :-1, :-1] x = F.relu(self.conv(x)) return x
[ "torch.nn.GroupNorm", "torch.nn.ReLU", "torch.nn.BatchNorm2d", "torch.nn.Conv2d", "torch.nn.MaxPool2d", "torch.nn.Upsample", "torch.nn.ConvTranspose2d", "torch.cat" ]
[((359, 413), 'torch.nn.Conv2d', 'nn.Conv2d', (['input_channel', 'output_channel', '(3)'], {'padding': '(1)'}), '(input_channel, output_channel, 3, padding=1)\n', (368, 413), True, 'import torch.nn as nn\n'), ((433, 464), 'torch.nn.GroupNorm', 'nn.GroupNorm', (['(8)', 'output_channel'], {}), '(8, output_channel)\n', (445, 464), True, 'import torch.nn as nn\n'), ((486, 541), 'torch.nn.Conv2d', 'nn.Conv2d', (['output_channel', 'output_channel', '(3)'], {'padding': '(1)'}), '(output_channel, output_channel, 3, padding=1)\n', (495, 541), True, 'import torch.nn as nn\n'), ((561, 592), 'torch.nn.GroupNorm', 'nn.GroupNorm', (['(8)', 'output_channel'], {}), '(8, output_channel)\n', (573, 592), True, 'import torch.nn as nn\n'), ((614, 669), 'torch.nn.Conv2d', 'nn.Conv2d', (['output_channel', 'output_channel', '(3)'], {'padding': '(1)'}), '(output_channel, output_channel, 3, padding=1)\n', (623, 669), True, 'import torch.nn as nn\n'), ((689, 720), 'torch.nn.GroupNorm', 'nn.GroupNorm', (['(8)', 'output_channel'], {}), '(8, output_channel)\n', (701, 720), True, 'import torch.nn as nn\n'), ((745, 763), 'torch.nn.MaxPool2d', 'nn.MaxPool2d', (['(2)', '(2)'], {}), '(2, 2)\n', (757, 763), True, 'import torch.nn as nn\n'), ((784, 793), 'torch.nn.ReLU', 'nn.ReLU', ([], {}), '()\n', (791, 793), True, 'import torch.nn as nn\n'), ((1265, 1330), 'torch.nn.Upsample', 'nn.Upsample', ([], {'scale_factor': '(2)', 'mode': '"""bilinear"""', 'align_corners': '(False)'}), "(scale_factor=2, mode='bilinear', align_corners=False)\n", (1276, 1330), True, 'import torch.nn as nn\n'), ((1352, 1421), 'torch.nn.Conv2d', 'nn.Conv2d', (['(prev_channel + input_channel)', 'output_channel', '(3)'], {'padding': '(1)'}), '(prev_channel + input_channel, output_channel, 3, padding=1)\n', (1361, 1421), True, 'import torch.nn as nn\n'), ((1441, 1472), 'torch.nn.GroupNorm', 'nn.GroupNorm', (['(8)', 'output_channel'], {}), '(8, output_channel)\n', (1453, 1472), True, 'import torch.nn as nn\n'), ((1494, 1549), 'torch.nn.Conv2d', 'nn.Conv2d', (['output_channel', 'output_channel', '(3)'], {'padding': '(1)'}), '(output_channel, output_channel, 3, padding=1)\n', (1503, 1549), True, 'import torch.nn as nn\n'), ((1569, 1600), 'torch.nn.GroupNorm', 'nn.GroupNorm', (['(8)', 'output_channel'], {}), '(8, output_channel)\n', (1581, 1600), True, 'import torch.nn as nn\n'), ((1622, 1677), 'torch.nn.Conv2d', 'nn.Conv2d', (['output_channel', 'output_channel', '(3)'], {'padding': '(1)'}), '(output_channel, output_channel, 3, padding=1)\n', (1631, 1677), True, 'import torch.nn as nn\n'), ((1697, 1728), 'torch.nn.GroupNorm', 'nn.GroupNorm', (['(8)', 'output_channel'], {}), '(8, output_channel)\n', (1709, 1728), True, 'import torch.nn as nn\n'), ((1749, 1764), 'torch.nn.ReLU', 'torch.nn.ReLU', ([], {}), '()\n', (1762, 1764), False, 'import torch\n'), ((1920, 1959), 'torch.cat', 'torch.cat', (['(x, prev_feature_map)'], {'dim': '(1)'}), '((x, prev_feature_map), dim=1)\n', (1929, 1959), False, 'import torch\n'), ((2617, 2664), 'torch.nn.Conv2d', 'nn.Conv2d', (['bottleneck', 'bottleneck', '(3)'], {'padding': '(1)'}), '(bottleneck, bottleneck, 3, padding=1)\n', (2626, 2664), True, 'import torch.nn as nn\n'), ((2684, 2711), 'torch.nn.GroupNorm', 'nn.GroupNorm', (['(8)', 'bottleneck'], {}), '(8, bottleneck)\n', (2696, 2711), True, 'import torch.nn as nn\n'), ((2737, 2784), 'torch.nn.Conv2d', 'nn.Conv2d', (['bottleneck', 'bottleneck', '(3)'], {'padding': '(1)'}), '(bottleneck, bottleneck, 3, padding=1)\n', (2746, 2784), True, 'import torch.nn as nn\n'), ((2804, 2831), 'torch.nn.GroupNorm', 'nn.GroupNorm', (['(8)', 'bottleneck'], {}), '(8, bottleneck)\n', (2816, 2831), True, 'import torch.nn as nn\n'), ((2857, 2910), 'torch.nn.Conv2d', 'torch.nn.Conv2d', (['bottleneck', 'bottleneck', '(3)'], {'padding': '(1)'}), '(bottleneck, bottleneck, 3, padding=1)\n', (2872, 2910), False, 'import torch\n'), ((2930, 2957), 'torch.nn.GroupNorm', 'nn.GroupNorm', (['(8)', 'bottleneck'], {}), '(8, bottleneck)\n', (2942, 2957), True, 'import torch.nn as nn\n'), ((3124, 3155), 'torch.nn.Conv2d', 'nn.Conv2d', (['(16)', '(16)', '(3)'], {'padding': '(1)'}), '(16, 16, 3, padding=1)\n', (3133, 3155), True, 'import torch.nn as nn\n'), ((3179, 3198), 'torch.nn.GroupNorm', 'nn.GroupNorm', (['(8)', '(16)'], {}), '(8, 16)\n', (3191, 3198), True, 'import torch.nn as nn\n'), ((3225, 3266), 'torch.nn.Conv2d', 'nn.Conv2d', (['(16)', 'out_channels', '(1)'], {'padding': '(0)'}), '(16, out_channels, 1, padding=0)\n', (3234, 3266), True, 'import torch.nn as nn\n'), ((3287, 3296), 'torch.nn.ReLU', 'nn.ReLU', ([], {}), '()\n', (3294, 3296), True, 'import torch.nn as nn\n'), ((6576, 6609), 'torch.nn.Conv2d', 'nn.Conv2d', (['(512)', '(512)', '(3)'], {'padding': '(1)'}), '(512, 512, 3, padding=1)\n', (6585, 6609), True, 'import torch.nn as nn\n'), ((6629, 6649), 'torch.nn.GroupNorm', 'nn.GroupNorm', (['(8)', '(512)'], {}), '(8, 512)\n', (6641, 6649), True, 'import torch.nn as nn\n'), ((6675, 6708), 'torch.nn.Conv2d', 'nn.Conv2d', (['(512)', '(512)', '(3)'], {'padding': '(1)'}), '(512, 512, 3, padding=1)\n', (6684, 6708), True, 'import torch.nn as nn\n'), ((6728, 6748), 'torch.nn.GroupNorm', 'nn.GroupNorm', (['(8)', '(512)'], {}), '(8, 512)\n', (6740, 6748), True, 'import torch.nn as nn\n'), ((6774, 6813), 'torch.nn.Conv2d', 'torch.nn.Conv2d', (['(512)', '(512)', '(3)'], {'padding': '(1)'}), '(512, 512, 3, padding=1)\n', (6789, 6813), False, 'import torch\n'), ((6833, 6859), 'torch.nn.GroupNorm', 'torch.nn.GroupNorm', (['(8)', '(512)'], {}), '(8, 512)\n', (6851, 6859), False, 'import torch\n'), ((7181, 7212), 'torch.nn.Conv2d', 'nn.Conv2d', (['(16)', '(16)', '(3)'], {'padding': '(1)'}), '(16, 16, 3, padding=1)\n', (7190, 7212), True, 'import torch.nn as nn\n'), ((7236, 7255), 'torch.nn.GroupNorm', 'nn.GroupNorm', (['(8)', '(16)'], {}), '(8, 16)\n', (7248, 7255), True, 'import torch.nn as nn\n'), ((7282, 7312), 'torch.nn.Conv2d', 'nn.Conv2d', (['(16)', '(1)', '(1)'], {'padding': '(0)'}), '(16, 1, 1, padding=0)\n', (7291, 7312), True, 'import torch.nn as nn\n'), ((7333, 7342), 'torch.nn.ReLU', 'nn.ReLU', ([], {}), '()\n', (7340, 7342), True, 'import torch.nn as nn\n'), ((8606, 8653), 'torch.nn.Conv2d', 'nn.Conv2d', (['bottleneck', 'bottleneck', '(3)'], {'padding': '(1)'}), '(bottleneck, bottleneck, 3, padding=1)\n', (8615, 8653), True, 'import torch.nn as nn\n'), ((8673, 8700), 'torch.nn.GroupNorm', 'nn.GroupNorm', (['(8)', 'bottleneck'], {}), '(8, bottleneck)\n', (8685, 8700), True, 'import torch.nn as nn\n'), ((8726, 8773), 'torch.nn.Conv2d', 'nn.Conv2d', (['bottleneck', 'bottleneck', '(3)'], {'padding': '(1)'}), '(bottleneck, bottleneck, 3, padding=1)\n', (8735, 8773), True, 'import torch.nn as nn\n'), ((8793, 8820), 'torch.nn.GroupNorm', 'nn.GroupNorm', (['(8)', 'bottleneck'], {}), '(8, bottleneck)\n', (8805, 8820), True, 'import torch.nn as nn\n'), ((8846, 8899), 'torch.nn.Conv2d', 'torch.nn.Conv2d', (['bottleneck', 'bottleneck', '(3)'], {'padding': '(1)'}), '(bottleneck, bottleneck, 3, padding=1)\n', (8861, 8899), False, 'import torch\n'), ((8919, 8946), 'torch.nn.GroupNorm', 'nn.GroupNorm', (['(8)', 'bottleneck'], {}), '(8, bottleneck)\n', (8931, 8946), True, 'import torch.nn as nn\n'), ((9123, 9154), 'torch.nn.Conv2d', 'nn.Conv2d', (['(64)', '(64)', '(3)'], {'padding': '(1)'}), '(64, 64, 3, padding=1)\n', (9132, 9154), True, 'import torch.nn as nn\n'), ((9178, 9197), 'torch.nn.GroupNorm', 'nn.GroupNorm', (['(8)', '(64)'], {}), '(8, 64)\n', (9190, 9197), True, 'import torch.nn as nn\n'), ((9224, 9265), 'torch.nn.Conv2d', 'nn.Conv2d', (['(64)', 'out_channels', '(1)'], {'padding': '(0)'}), '(64, out_channels, 1, padding=0)\n', (9233, 9265), True, 'import torch.nn as nn\n'), ((9286, 9295), 'torch.nn.ReLU', 'nn.ReLU', ([], {}), '()\n', (9293, 9295), True, 'import torch.nn as nn\n'), ((10399, 10446), 'torch.nn.Conv2d', 'nn.Conv2d', (['bottleneck', 'bottleneck', '(3)'], {'padding': '(1)'}), '(bottleneck, bottleneck, 3, padding=1)\n', (10408, 10446), True, 'import torch.nn as nn\n'), ((10466, 10493), 'torch.nn.GroupNorm', 'nn.GroupNorm', (['(8)', 'bottleneck'], {}), '(8, bottleneck)\n', (10478, 10493), True, 'import torch.nn as nn\n'), ((10519, 10566), 'torch.nn.Conv2d', 'nn.Conv2d', (['bottleneck', 'bottleneck', '(3)'], {'padding': '(1)'}), '(bottleneck, bottleneck, 3, padding=1)\n', (10528, 10566), True, 'import torch.nn as nn\n'), ((10586, 10613), 'torch.nn.GroupNorm', 'nn.GroupNorm', (['(8)', 'bottleneck'], {}), '(8, bottleneck)\n', (10598, 10613), True, 'import torch.nn as nn\n'), ((10639, 10692), 'torch.nn.Conv2d', 'torch.nn.Conv2d', (['bottleneck', 'bottleneck', '(3)'], {'padding': '(1)'}), '(bottleneck, bottleneck, 3, padding=1)\n', (10654, 10692), False, 'import torch\n'), ((10712, 10739), 'torch.nn.GroupNorm', 'nn.GroupNorm', (['(8)', 'bottleneck'], {}), '(8, bottleneck)\n', (10724, 10739), True, 'import torch.nn as nn\n'), ((10760, 10769), 'torch.nn.ReLU', 'nn.ReLU', ([], {}), '()\n', (10767, 10769), True, 'import torch.nn as nn\n'), ((11544, 11575), 'torch.nn.Conv2d', 'nn.Conv2d', (['(16)', '(16)', '(3)'], {'padding': '(1)'}), '(16, 16, 3, padding=1)\n', (11553, 11575), True, 'import torch.nn as nn\n'), ((11599, 11618), 'torch.nn.GroupNorm', 'nn.GroupNorm', (['(8)', '(16)'], {}), '(8, 16)\n', (11611, 11618), True, 'import torch.nn as nn\n'), ((11645, 11691), 'torch.nn.Conv2d', 'nn.Conv2d', (['(16)', 'self.out_channels', '(1)'], {'padding': '(0)'}), '(16, self.out_channels, 1, padding=0)\n', (11654, 11691), True, 'import torch.nn as nn\n'), ((11719, 11784), 'torch.nn.Upsample', 'nn.Upsample', ([], {'scale_factor': '(2)', 'mode': '"""bilinear"""', 'align_corners': '(False)'}), "(scale_factor=2, mode='bilinear', align_corners=False)\n", (11730, 11784), True, 'import torch.nn as nn\n'), ((11805, 11814), 'torch.nn.ReLU', 'nn.ReLU', ([], {}), '()\n', (11812, 11814), True, 'import torch.nn as nn\n'), ((12887, 12934), 'torch.nn.Conv2d', 'nn.Conv2d', (['bottleneck', 'bottleneck', '(3)'], {'padding': '(1)'}), '(bottleneck, bottleneck, 3, padding=1)\n', (12896, 12934), True, 'import torch.nn as nn\n'), ((12954, 12981), 'torch.nn.GroupNorm', 'nn.GroupNorm', (['(8)', 'bottleneck'], {}), '(8, bottleneck)\n', (12966, 12981), True, 'import torch.nn as nn\n'), ((13007, 13054), 'torch.nn.Conv2d', 'nn.Conv2d', (['bottleneck', 'bottleneck', '(3)'], {'padding': '(1)'}), '(bottleneck, bottleneck, 3, padding=1)\n', (13016, 13054), True, 'import torch.nn as nn\n'), ((13074, 13101), 'torch.nn.GroupNorm', 'nn.GroupNorm', (['(8)', 'bottleneck'], {}), '(8, bottleneck)\n', (13086, 13101), True, 'import torch.nn as nn\n'), ((13127, 13180), 'torch.nn.Conv2d', 'torch.nn.Conv2d', (['bottleneck', 'bottleneck', '(3)'], {'padding': '(1)'}), '(bottleneck, bottleneck, 3, padding=1)\n', (13142, 13180), False, 'import torch\n'), ((13200, 13227), 'torch.nn.GroupNorm', 'nn.GroupNorm', (['(8)', 'bottleneck'], {}), '(8, bottleneck)\n', (13212, 13227), True, 'import torch.nn as nn\n'), ((13248, 13257), 'torch.nn.ReLU', 'nn.ReLU', ([], {}), '()\n', (13255, 13257), True, 'import torch.nn as nn\n'), ((13993, 14024), 'torch.nn.Conv2d', 'nn.Conv2d', (['(64)', '(64)', '(3)'], {'padding': '(1)'}), '(64, 64, 3, padding=1)\n', (14002, 14024), True, 'import torch.nn as nn\n'), ((14048, 14067), 'torch.nn.GroupNorm', 'nn.GroupNorm', (['(8)', '(64)'], {}), '(8, 64)\n', (14060, 14067), True, 'import torch.nn as nn\n'), ((14094, 14140), 'torch.nn.Conv2d', 'nn.Conv2d', (['(64)', 'self.out_channels', '(1)'], {'padding': '(0)'}), '(64, self.out_channels, 1, padding=0)\n', (14103, 14140), True, 'import torch.nn as nn\n'), ((14161, 14170), 'torch.nn.ReLU', 'nn.ReLU', ([], {}), '()\n', (14168, 14170), True, 'import torch.nn as nn\n'), ((15667, 15699), 'torch.nn.Conv2d', 'nn.Conv2d', (['(128)', '(64)', '(3)'], {'padding': '(1)'}), '(128, 64, 3, padding=1)\n', (15676, 15699), True, 'import torch.nn as nn\n'), ((15723, 15742), 'torch.nn.GroupNorm', 'nn.GroupNorm', (['(8)', '(64)'], {}), '(8, 64)\n', (15735, 15742), True, 'import torch.nn as nn\n'), ((15769, 15815), 'torch.nn.Conv2d', 'nn.Conv2d', (['(64)', 'self.out_channels', '(1)'], {'padding': '(0)'}), '(64, self.out_channels, 1, padding=0)\n', (15778, 15815), True, 'import torch.nn as nn\n'), ((15836, 15845), 'torch.nn.ReLU', 'nn.ReLU', ([], {}), '()\n', (15843, 15845), True, 'import torch.nn as nn\n'), ((16448, 16479), 'torch.nn.Conv2d', 'nn.Conv2d', (['(32)', '(32)', '(3)'], {'padding': '(1)'}), '(32, 32, 3, padding=1)\n', (16457, 16479), True, 'import torch.nn as nn\n'), ((16503, 16522), 'torch.nn.GroupNorm', 'nn.GroupNorm', (['(8)', '(32)'], {}), '(8, 32)\n', (16515, 16522), True, 'import torch.nn as nn\n'), ((16549, 16595), 'torch.nn.Conv2d', 'nn.Conv2d', (['(32)', 'self.out_channels', '(1)'], {'padding': '(0)'}), '(32, self.out_channels, 1, padding=0)\n', (16558, 16595), True, 'import torch.nn as nn\n'), ((16616, 16625), 'torch.nn.ReLU', 'nn.ReLU', ([], {}), '()\n', (16623, 16625), True, 'import torch.nn as nn\n'), ((17097, 17194), 'torch.nn.Conv2d', 'nn.Conv2d', (['f1', 'f2', '(kernel_size, kernel_size)'], {'dilation': 'dilation', 'padding': '(padding * dilation)'}), '(f1, f2, (kernel_size, kernel_size), dilation=dilation, padding=\n padding * dilation)\n', (17106, 17194), True, 'import torch.nn as nn\n'), ((12354, 12384), 'torch.cat', 'torch.cat', (['devals[::-1]'], {'dim': '(1)'}), '(devals[::-1], dim=1)\n', (12363, 12384), False, 'import torch\n'), ((17240, 17344), 'torch.nn.ConvTranspose2d', 'nn.ConvTranspose2d', (['f1', 'f1', '(3, 3)'], {'dilation': 'dilation', 'stride': '(2)', 'padding': 'dilation', 'output_padding': '(1)'}), '(f1, f1, (3, 3), dilation=dilation, stride=2, padding=\n dilation, output_padding=1)\n', (17258, 17344), True, 'import torch.nn as nn\n'), ((17418, 17442), 'torch.nn.GroupNorm', 'nn.GroupNorm', (['groups', 'f1'], {}), '(groups, f1)\n', (17430, 17442), True, 'import torch.nn as nn\n'), ((17479, 17497), 'torch.nn.BatchNorm2d', 'nn.BatchNorm2d', (['f1'], {}), '(f1)\n', (17493, 17497), True, 'import torch.nn as nn\n')]
import os from flask_unchained import AppConfig class Config(AppConfig): WEBPACK_MANIFEST_PATH = os.path.join( AppConfig.STATIC_FOLDER, 'assets', 'manifest.json') class ProdConfig: # use relative paths by default, ie, the same host as the backend WEBPACK_ASSETS_HOST = '' class StagingConfig(ProdConfig): pass
[ "os.path.join" ]
[((104, 168), 'os.path.join', 'os.path.join', (['AppConfig.STATIC_FOLDER', '"""assets"""', '"""manifest.json"""'], {}), "(AppConfig.STATIC_FOLDER, 'assets', 'manifest.json')\n", (116, 168), False, 'import os\n')]
import logging import torch import torch.nn as nn import torch.nn.functional as F from .... import extensions as E from . import accuracy as A logger = logging.getLogger('global') def _reduce(loss, reduction, **kwargs): if reduction == 'none': ret = loss elif reduction == 'mean': normalizer = loss.numel() if kwargs.get('normalizer', None): normalizer = kwargs['normalizer'] ret = loss.sum() / normalizer elif reduction == 'sum': ret = loss.sum() else: raise ValueError(reduction + ' is not valid') return ret def l1_loss(input, target, scale_type='linear', reduction='mean', normalizer=None): if scale_type == 'linear': input = input target = target elif scale_type == 'log': input = torch.log(input) target = torch.log(target) else: raise NotImplementedError loss = torch.abs(input - target) loss = _reduce(loss, reduction=reduction, normalizer=normalizer) return loss def balanced_l1_loss(input, target, sigma=1.0, alpha=0.5, gamma=1.5, reduction='mean', normalizer=None): beta = 1. / (sigma**2) diff = torch.abs(input - target) b = np.e**(gamma / alpha) - 1 loss = torch.where( diff < beta, alpha / b * (b * diff + 1) * torch.log(b * diff / beta + 1) - alpha * diff, gamma * diff + gamma / b - alpha * beta) loss = _reduce(loss, reduction, normalizer=normalizer) return loss def smooth_l1_loss(input, target, sigma, reduce=True, normalizer=1.0): beta = 1. / (sigma**2) diff = torch.abs(input - target) cond = diff < beta loss = torch.where(cond, 0.5 * diff**2 / beta, diff - 0.5 * beta) if reduce: return torch.sum(loss) / normalizer return torch.sum(loss, dim=1) / normalizer def cross_entropy_weight(input, target, sample_weight=None, cls_weight=None): if sample_weight is None: return F.cross_entropy(input, target, weight=cls_weight) sample_num = target.size()[0] log_input = F.log_softmax(input, 1) loss = F.nll_loss(log_input * sample_weight.reshape(sample_num, 1), target, cls_weight) return loss * sample_num / sample_weight.sum() # normal def ohem_loss(batch_size, cls_pred, cls_target, loc_pred, loc_target, cls_type='softmax', smooth_l1_sigma=1.0): """ Arguments: batch_size (int): number of sampled rois for bbox head training loc_pred (FloatTensor): [R, 4], location of positive rois loc_target (FloatTensor): [R, 4], location of positive rois pos_mask (FloatTensor): [R], binary mask for sampled positive rois cls_pred (FloatTensor): [R, C] cls_target (LongTensor): [R] Returns: cls_loss, loc_loss (FloatTensor) """ if cls_type == 'softmax': ohem_cls_loss = F.cross_entropy(cls_pred, cls_target, reduction='none', ignore_index=-1) else: ohem_cls_loss = F.binary_cross_entropy_with_logits(cls_pred, cls_target, reduction='none') if loc_pred is None: ohem_loc_loss = torch.zeros_like(ohem_cls_loss) else: ohem_loc_loss = smooth_l1_loss(loc_pred, loc_target, sigma=smooth_l1_sigma, reduce=False) loss = ohem_cls_loss + ohem_loc_loss sorted_ohem_loss, idx = torch.sort(loss, descending=True) keep_num = min(sorted_ohem_loss.size()[0], batch_size) if keep_num <= sorted_ohem_loss.size()[0]: keep_idx_cuda = idx[:keep_num] ohem_cls_loss = ohem_cls_loss[keep_idx_cuda] ohem_loc_loss = ohem_loc_loss[keep_idx_cuda] cls_loss = ohem_cls_loss.sum() / keep_num loc_loss = ohem_loc_loss.sum() / keep_num return cls_loss, loc_loss, keep_idx_cuda def get_rpn_cls_loss(cls_pred, cls_target, sample_cls_mask, loss_type): """ Arguments: cls_pred (FloatTensor): [B*K, C] cls_target (LongTensor): [B*K] sample_cls_mask (ByteTensor): [B, K], binary mask for sampled rois loss_type (str): sigmoid or softmax Returns: cls_loss, acc (FloatTensor) """ sample_cls_mask = sample_cls_mask.reshape(-1) if loss_type == "softmax": cls_pred = cls_pred.reshape(cls_target.numel(), -1) cls_target = cls_target.reshape(-1) cls_loss = F.cross_entropy(cls_pred, cls_target.long(), ignore_index=-1) acc = A.accuracy(cls_pred, cls_target)[0] elif loss_type == "sigmoid": cls_pred = cls_pred.reshape(-1) cls_target = cls_target.reshape(-1) normalizer = (sample_cls_mask > 0).float().sum() normalizer = max(1, normalizer.item()) cls_loss = F.binary_cross_entropy_with_logits(cls_pred, cls_target.float(), reduction='none') cls_loss = (cls_loss * sample_cls_mask.float()).sum() / normalizer # acc = torch.tensor([0]).cuda().float() # for sigmoid, there is a bug in A.accuracy acc = A.binary_accuracy(cls_pred, cls_target)[0] return cls_loss, acc def get_rpn_loc_loss(loc_pred, loc_target, sample_loc_mask, sigma, normalizer): """ Arguments: loc_pred (FloatTensor): [B*K, 4] loc_target (LongTensor): [B*K, 4] sample_loc_mask (ByteTensor): [B, K], binary mask for sampled poitive rois Returns: loc_loss (FloatTensor) """ sample_loc_mask = sample_loc_mask.reshape(-1) loc_target = loc_target.reshape(-1, 4)[sample_loc_mask] loc_pred = loc_pred.reshape(-1, 4)[sample_loc_mask] loc_loss = smooth_l1_loss(loc_pred, loc_target, sigma, normalizer=normalizer) return loc_loss def get_focal_loss(cls_pred, cls_target, normalizer, num_classes, cfg_loss): """ Arguments: cls_pred (FloatTensor): [B*K, C] cls_target (LongTensor): [B*K] cfg_loss: config for focal loss Returns: cls_loss, acc (FloatTensor) """ alpha = cfg_loss['alpha'] gamma = cfg_loss['gamma'] loss_type = cfg_loss['type'] C = {'sigmoid': -1, 'softmax': 0}[loss_type] + num_classes cls_pred = cls_pred.float().view(-1, C) cls_target = cls_target.int().view(-1) normalizer = torch.cuda.FloatTensor([normalizer]) loss_fn = {'sigmoid': E.SigmoidFocalLossFunction, 'softmax': E.SoftmaxFocalLossFunction}[loss_type] loss_fn = loss_fn(gamma, alpha, C) cls_loss = loss_fn(cls_pred, cls_target, normalizer) if loss_type == 'softmax': acc = A.accuracy(cls_pred, cls_target.long())[0] elif loss_type == 'sigmoid': acc = A.accuracy(cls_pred, cls_target.long() - 1, ignore_indices=[-1, -2])[0] else: raise NotImplementedError('{} is not supported for focal loss'.format(loss_type)) return cls_loss, acc class FocalLoss(nn.Module): def __init__(self, class_num, alpha=None, gamma=2, use_alpha=False, size_average=True): super(FocalLoss, self).__init__() self.class_num = class_num self.alpha = alpha self.gamma = gamma if use_alpha: self.alpha = torch.tensor(alpha).cuda() self.softmax = nn.Softmax(dim=1) self.use_alpha = use_alpha self.size_average = size_average def forward(self, pred, target): prob = self.softmax(pred.view(-1,self.class_num)) prob = prob.clamp(min=0.0001,max=1.0) target_ = torch.zeros(target.size(0),self.class_num).cuda() target_.scatter_(1, target.view(-1, 1).long(), 1.) if self.use_alpha: batch_loss = - self.alpha.double() * torch.pow(1-prob,self.gamma).double() * prob.log().double() * target_.double() else: batch_loss = - torch.pow(1-prob,self.gamma).double() * prob.log().double() * target_.double() batch_loss = batch_loss.sum(dim=1) if self.size_average: loss = batch_loss.mean() else: loss = batch_loss.sum() return loss class GHMCLoss(nn.Module): def __init__(self, bins=10, momentum=0, loss_weight=1.0): super(GHMCLoss, self).__init__() self.bins = bins self.momentum = momentum self.edges = [float(x) / bins for x in range(bins + 1)] self.edges[-1] += 1e-6 self.loss_weight = loss_weight if momentum > 0: self.acc_sum = [0.0 for _ in range(bins)] def binarize_target(self, input, target): """ convert target index to one-hot target Args: input: [B, A, C] target: [B, A] Returns: target: [B, A, C] mask: [B, A, C] """ binary_targets = torch.zeros_like(input) mask = torch.zeros_like(input) pos_inds = target > 0 cls_inds = target[pos_inds] - 1 binary_targets[pos_inds, cls_inds] = 1 mask[target > -1, :] = 1 return binary_targets, mask def forward(self, input, target, mlvl_shapes=None): """ Args: input [batch_num, anchor_num, C]: The direct prediction of classification fc layer. target [batch_num, anchor_num]: Binary target (0 or 1) for each sample each class. The value is -1 when the sample is ignored. """ target, mask = self.binarize_target(input, target) if mlvl_shapes is None: return self.forward_single(input, target, mask) mlvl_size = [_[-1] for _ in mlvl_shapes] assert input.ndimension() == 3 assert target.ndimension() == 3 assert mask.ndimension() == 3 inputs = input.split(mlvl_size, dim=1) targets = target.split(mlvl_size, dim=1) masks = mask.split(mlvl_size, dim=1) loss = 0 for i, t, m in zip(inputs, targets, masks): loss += self.forward_single(i, t, m) return loss def forward_single(self, input, target, mask): edges = self.edges mmt = self.momentum weights = torch.zeros_like(input) # gradient length g = torch.abs(input.sigmoid().detach() - target) valid = mask > 0 tot = max(valid.float().sum().item(), 1.0) n = 0 # n valid bins for i in range(self.bins): inds = (g >= edges[i]) & (g < edges[i + 1]) & valid num_in_bin = inds.sum().item() if num_in_bin > 0: if mmt > 0: self.acc_sum[i] = mmt * self.acc_sum[i] \ + (1 - mmt) * num_in_bin weights[inds] = tot / self.acc_sum[i] else: weights[inds] = tot / num_in_bin n += 1 if n > 0: weights = weights / n loss = F.binary_cross_entropy_with_logits(input, target, weights, reduction='sum') / tot return loss * self.loss_weight @classmethod def from_params(cls, params): bins = params['bins'] momentum = params['momentum'] loss_weight = params['loss_weight'] return cls(bins, momentum, loss_weight) class GHMRLoss(nn.Module): def __init__(self, mu=0.02, bins=10, momentum=0, loss_weight=1.0): super(GHMRLoss, self).__init__() self.mu = mu self.bins = bins self.edges = [float(x) / bins for x in range(bins + 1)] self.edges[-1] = 1e3 self.momentum = momentum self.loss_weight = loss_weight if momentum > 0: self.acc_sum = [0.0 for _ in range(bins)] def forward(self, input, target, mask, mlvl_shapes=None): """ Args: input [batch_num, anchor_num, 4]: The prediction of box regression layer. Channel number can be 4 or (4 * class_num) depending on whether it is class-agnostic. target [batch_num, anchor_num, 4]: The target regression values with the same size of input. mask [batch_num, anchor_num]: mask for each anchor """ # expand to each coordinate mask = mask.float().reshape(input.shape[0], input.shape[1], 1).repeat(1, 1, 4) if mlvl_shapes is None: return self.forward_single(input, target, mask) mlvl_size = [_[-1] for _ in mlvl_shapes] assert input.ndimension() == 3 assert target.ndimension() == 3 assert mask.ndimension() == 3 inputs = input.split(mlvl_size, dim=1) targets = target.split(mlvl_size, dim=1) masks = mask.split(mlvl_size, dim=1) loss = 0 for i, t, m in zip(inputs, targets, masks): loss += self.forward_single(i, t, m) return loss def forward_single(self, input, target, mask): mu = self.mu edges = self.edges mmt = self.momentum # ASL1 loss diff = input - target loss = torch.sqrt(diff * diff + mu * mu) - mu # gradient length g = torch.abs(diff / torch.sqrt(mu * mu + diff * diff)).detach() weights = torch.zeros_like(g) valid = mask > 0 tot = max(mask.float().sum().item(), 1.0) n = 0 # n: valid bins for i in range(self.bins): inds = (g >= edges[i]) & (g < edges[i + 1]) & valid num_in_bin = inds.sum().item() if num_in_bin > 0: n += 1 if mmt > 0: self.acc_sum[i] = mmt * self.acc_sum[i] \ + (1 - mmt) * num_in_bin weights[inds] = tot / self.acc_sum[i] else: weights[inds] = tot / num_in_bin if n > 0: weights /= n loss = loss * weights loss = loss.sum() / tot return loss * self.loss_weight @classmethod def from_params(cls, params): mu = params['mu'] bins = params['bins'] momentum = params['momentum'] loss_weight = params['loss_weight'] return cls(mu, bins, momentum, loss_weight)
[ "logging.getLogger", "torch.sort", "torch.abs", "torch.cuda.FloatTensor", "torch.log", "torch.nn.Softmax", "torch.sqrt", "torch.pow", "torch.tensor", "torch.sum", "torch.nn.functional.log_softmax", "torch.nn.functional.cross_entropy", "torch.zeros_like", "torch.nn.functional.binary_cross_e...
[((155, 182), 'logging.getLogger', 'logging.getLogger', (['"""global"""'], {}), "('global')\n", (172, 182), False, 'import logging\n'), ((912, 937), 'torch.abs', 'torch.abs', (['(input - target)'], {}), '(input - target)\n', (921, 937), False, 'import torch\n'), ((1168, 1193), 'torch.abs', 'torch.abs', (['(input - target)'], {}), '(input - target)\n', (1177, 1193), False, 'import torch\n'), ((1592, 1617), 'torch.abs', 'torch.abs', (['(input - target)'], {}), '(input - target)\n', (1601, 1617), False, 'import torch\n'), ((1652, 1712), 'torch.where', 'torch.where', (['cond', '(0.5 * diff ** 2 / beta)', '(diff - 0.5 * beta)'], {}), '(cond, 0.5 * diff ** 2 / beta, diff - 0.5 * beta)\n', (1663, 1712), False, 'import torch\n'), ((2041, 2064), 'torch.nn.functional.log_softmax', 'F.log_softmax', (['input', '(1)'], {}), '(input, 1)\n', (2054, 2064), True, 'import torch.nn.functional as F\n'), ((3285, 3318), 'torch.sort', 'torch.sort', (['loss'], {'descending': '(True)'}), '(loss, descending=True)\n', (3295, 3318), False, 'import torch\n'), ((6087, 6123), 'torch.cuda.FloatTensor', 'torch.cuda.FloatTensor', (['[normalizer]'], {}), '([normalizer])\n', (6109, 6123), False, 'import torch\n'), ((1781, 1803), 'torch.sum', 'torch.sum', (['loss'], {'dim': '(1)'}), '(loss, dim=1)\n', (1790, 1803), False, 'import torch\n'), ((1941, 1990), 'torch.nn.functional.cross_entropy', 'F.cross_entropy', (['input', 'target'], {'weight': 'cls_weight'}), '(input, target, weight=cls_weight)\n', (1956, 1990), True, 'import torch.nn.functional as F\n'), ((2844, 2916), 'torch.nn.functional.cross_entropy', 'F.cross_entropy', (['cls_pred', 'cls_target'], {'reduction': '"""none"""', 'ignore_index': '(-1)'}), "(cls_pred, cls_target, reduction='none', ignore_index=-1)\n", (2859, 2916), True, 'import torch.nn.functional as F\n'), ((2951, 3025), 'torch.nn.functional.binary_cross_entropy_with_logits', 'F.binary_cross_entropy_with_logits', (['cls_pred', 'cls_target'], {'reduction': '"""none"""'}), "(cls_pred, cls_target, reduction='none')\n", (2985, 3025), True, 'import torch.nn.functional as F\n'), ((3075, 3106), 'torch.zeros_like', 'torch.zeros_like', (['ohem_cls_loss'], {}), '(ohem_cls_loss)\n', (3091, 3106), False, 'import torch\n'), ((7010, 7027), 'torch.nn.Softmax', 'nn.Softmax', ([], {'dim': '(1)'}), '(dim=1)\n', (7020, 7027), True, 'import torch.nn as nn\n'), ((8515, 8538), 'torch.zeros_like', 'torch.zeros_like', (['input'], {}), '(input)\n', (8531, 8538), False, 'import torch\n'), ((8554, 8577), 'torch.zeros_like', 'torch.zeros_like', (['input'], {}), '(input)\n', (8570, 8577), False, 'import torch\n'), ((9839, 9862), 'torch.zeros_like', 'torch.zeros_like', (['input'], {}), '(input)\n', (9855, 9862), False, 'import torch\n'), ((12825, 12844), 'torch.zeros_like', 'torch.zeros_like', (['g'], {}), '(g)\n', (12841, 12844), False, 'import torch\n'), ((805, 821), 'torch.log', 'torch.log', (['input'], {}), '(input)\n', (814, 821), False, 'import torch\n'), ((839, 856), 'torch.log', 'torch.log', (['target'], {}), '(target)\n', (848, 856), False, 'import torch\n'), ((1741, 1756), 'torch.sum', 'torch.sum', (['loss'], {}), '(loss)\n', (1750, 1756), False, 'import torch\n'), ((10590, 10665), 'torch.nn.functional.binary_cross_entropy_with_logits', 'F.binary_cross_entropy_with_logits', (['input', 'target', 'weights'], {'reduction': '"""sum"""'}), "(input, target, weights, reduction='sum')\n", (10624, 10665), True, 'import torch.nn.functional as F\n'), ((12668, 12701), 'torch.sqrt', 'torch.sqrt', (['(diff * diff + mu * mu)'], {}), '(diff * diff + mu * mu)\n', (12678, 12701), False, 'import torch\n'), ((1310, 1340), 'torch.log', 'torch.log', (['(b * diff / beta + 1)'], {}), '(b * diff / beta + 1)\n', (1319, 1340), False, 'import torch\n'), ((6959, 6978), 'torch.tensor', 'torch.tensor', (['alpha'], {}), '(alpha)\n', (6971, 6978), False, 'import torch\n'), ((12763, 12796), 'torch.sqrt', 'torch.sqrt', (['(mu * mu + diff * diff)'], {}), '(mu * mu + diff * diff)\n', (12773, 12796), False, 'import torch\n'), ((7451, 7482), 'torch.pow', 'torch.pow', (['(1 - prob)', 'self.gamma'], {}), '(1 - prob, self.gamma)\n', (7460, 7482), False, 'import torch\n'), ((7571, 7602), 'torch.pow', 'torch.pow', (['(1 - prob)', 'self.gamma'], {}), '(1 - prob, self.gamma)\n', (7580, 7602), False, 'import torch\n')]
import inspect import os from collections import Callable from asyncorm.application.configure import get_model from asyncorm.exceptions import AsyncOrmFieldError, AsyncOrmModelDoesNotExist, AsyncOrmModelError from asyncorm.manager import ModelManager from asyncorm.models.fields import AutoField, Field, ForeignKey, ManyToManyField from asyncorm.serializers import ModelSerializer, SerializerMethod __all__ = ["Model", "ModelSerializer", "SerializerMethod"] class empty: pass class ModelMeta(type): def __new__(cls, clsname, bases, clsdict): base_class = super().__new__(cls, clsname, bases, clsdict) base_class.objects = type("{}Manager".format(base_class.__name__), (ModelManager,), {"model": base_class})( base_class ) # Meta manage defined_meta = clsdict.pop("Meta", None) base_class.ordering = None base_class.unique_together = [] base_class.table_name = "" base_class.DoesNotExist = AsyncOrmModelDoesNotExist base_class.meta_items = ("ordering", "unique_together", "table_name") if defined_meta: if hasattr(defined_meta, "ordering"): base_class.ordering = getattr(defined_meta, "ordering") if hasattr(defined_meta, "unique_together"): base_class.unique_together = getattr(defined_meta, "unique_together") if hasattr(defined_meta, "table_name"): base_class.table_name = getattr(defined_meta, "table_name") base_class.fields = base_class.get_fields() primary_keys = [f for f in base_class.fields.values() if isinstance(f, AutoField)] if not primary_keys: base_class.id = AutoField() base_class.fields["id"] = base_class.id base_class.db_pk = "id" base_class.orm_pk = "id" elif len(primary_keys) == 1: base_class.db_pk = primary_keys[0].db_column base_class.orm_pk = primary_keys[0].orm_field_name for f in base_class.fields.values(): if hasattr(f, "choices"): if f.choices: setattr(base_class, "{}_display".format(f.orm_field_name), "choices_placeholder") return base_class class BaseModel(object, metaclass=ModelMeta): table_name = "" objects = None deleted = False field_requirements = [] def __init__(self, **kwargs): self.dir_name = os.path.dirname(inspect.getmodule(self).__file__) self.app_name = self.dir_name.split(os.path.sep)[-1] self.table_name = "" self.objects.model = self.__class__ manager = getattr(self, "objects") manager.model = self.__class__ # resolve method for posible display methods for k, v in self.__class__.__dict__.items(): if v == "choices_placeholder": field_name = k.split("_display")[0] field = getattr(self.__class__, field_name) def new_func(field=field, field_name=field_name): value = getattr(self, field_name) for a, b in field.choices.items(): if a == value: return b setattr(self, k, new_func) self.validate_kwargs(kwargs) for field_name in self.fields.keys(): f_cls = getattr(self.__class__, field_name) if field_name in kwargs: setattr(self, field_name, kwargs[field_name]) elif hasattr(f_cls, "default"): d_value = f_cls.default setattr(self, field_name, d_value() if isinstance(d_value, Callable) else d_value) @classmethod def cls_tablename(cls): return cls.table_name or cls.__name__ @classmethod def set_reverse_foreignkey(cls, model_name, field_name): def fk_set(self): model = get_model(model_name) return model.objects.filter(**{field_name: getattr(self, self.orm_pk)}) setattr(cls, "{}_set".format(model_name.lower()), fk_set) @classmethod def set_many2many(cls, field, table_name, my_column, other_column, direct=False): other_model = get_model(other_column) queryset = ModelManager(other_model, field=field) queryset.set_orm(cls.objects.orm) def m2m_set(self): queryset.query = [ { "action": "_db__select_m2m", "select": "*", "m2m_tablename": table_name, "other_tablename": other_column, "otherdb_pk": other_model.db_pk, "id_data": "{}={}".format(my_column, getattr(self, self.orm_pk)), } ] return queryset method_name = direct and field.field_name or "{}_set".format(other_column.lower()) setattr(cls, method_name, m2m_set) @classmethod def set_orm(cls, orm): cls.objects.set_orm(orm) @property def data(self): d = {} created = bool(self.orm_pk) for orm, db in self.__class__.attr_names.items(): class__orm = getattr(self.__class__, orm) self__orm = getattr(self, orm) if self__orm is class__orm: continue has_pk = self.orm_pk == orm many2many = isinstance(class__orm, ManyToManyField) if not has_pk and not many2many: d[db] = self__orm is_default = self__orm == getattr(class__orm, "default", empty) # if value equal to default we set him with insert, # else we should always represent him if not created and is_default: d.pop(db) return d @property def m2m_data(self): d = {} for orm, db in self.__class__.attr_names.items(): class__orm = getattr(self.__class__, orm) if isinstance(class__orm, ManyToManyField): self__orm = getattr(self, orm) d[db] = self__orm default = self__orm == class__orm.default if bool(self.orm_pk) and default: d.pop(db) return d @classmethod def orm_attr_names(cls): return {v: k for k, v in cls.attr_names.items()} @classmethod def get_fields(cls): fields = {} cls.attr_names = {} for f_n, field in cls.__dict__.items(): if isinstance(field, Field): field.orm_field_name = f_n if not field.db_column: field.set_field_name(f_n) if not field.table_name: field.table_name = cls.cls_tablename() if isinstance(field, ManyToManyField): field.own_model = cls.cls_tablename() field.table_name = "{my_model}_{foreign_key}".format( my_model=cls.cls_tablename(), foreign_key=field.foreign_key ) if not isinstance(field.__class__, AutoField): cls.attr_names.update({f_n: field.db_column}) if hasattr(field, "field_requirement"): if field.field_requirement not in cls.field_requirements: cls.field_requirements.append(field.field_requirement) fields[f_n] = field if len(cls.attr_names) != len(set(cls.attr_names)): raise AsyncOrmModelError("Models should have unique attribute names and field_name if explicitly edited!") return fields @classmethod def get_db_columns(cls): db_columns = [] for f_n, field in cls.__dict__.items(): is_many2many = isinstance(field, ManyToManyField) is_field = isinstance(field, Field) if is_field and not is_many2many: db_columns.append(field.db_column and field.db_column or f_n) return db_columns def validate_kwargs(self, kwargs): """validate the kwargs on object instantiation only""" attr_errors = [k for k in kwargs.keys() if k not in self.fields.keys()] if attr_errors: err_string = '"{}" is not an attribute for {}' error_list = [err_string.format(k, self.__class__.__name__) for k in attr_errors] raise AsyncOrmModelError(error_list) for k, v in kwargs.items(): att_field = getattr(self.__class__, k) att_field.validate(v) if att_field.__class__ is AutoField and v: raise AsyncOrmFieldError("Models can not be generated with forced id") def migration_queries(self): migration_queries = [self.objects.create_table_builder()] for f in self.fields.values(): if isinstance(f, ForeignKey): migration_queries.append(self.objects.add_fk_field_builder(f)) for f in self.fields.values(): if isinstance(f, ManyToManyField): migration_queries.append(self.objects.add_m2m_columns_builder(f)) migration_queries.append(self.objects.unique_together_builder()) return migration_queries @classmethod def current_state(cls): from copy import deepcopy fields = deepcopy(cls.get_fields()) meta = {} for f_n, field in fields.items(): fields[f_n] = field.current_state() for m in cls.meta_items: meta[m] = getattr(cls, m) return {"fields": fields, "meta": meta} @classmethod def status_difference(cls, old_state): current_state = cls.current_state() news = {"fields": {}, "meta": {}} deleted = {"fields": [], "meta": []} updated = {"fields": {}, "meta": {}} if old_state != current_state: for subzone in ("fields", "meta"): if old_state[subzone] != current_state[subzone]: for f_n, f_v in old_state[subzone].items(): if current_state[subzone].get(f_n, False): if current_state[subzone][f_n] != f_v: updated[subzone][f_n] = current_state[subzone].get(f_n) else: deleted[subzone].append(f_n) for f_n, f_v in current_state[subzone].items(): if not old_state[subzone].get(f_n, False): news[subzone][f_n] = current_state[subzone].get(f_n) class Model(BaseModel): def construct(self, data, deleted=False, subitems=None): # populates the model with the data internal_objects = {} for k, v in data.items(): k_splitted = k.split("€$$€") if len(k_splitted) == 1: # check if its named different in the database than the orm if k not in self.__class__.attr_names.keys(): for orm, db in self.__class__.attr_names.items(): if k == db: k = orm break # get the recomposed value field_class = getattr(self.__class__, k, None) if field_class is None: continue v = field_class.recompose(v) if field_class in [ForeignKey, ManyToManyField]: pass setattr(self, k, v) else: # itself or empty dict internal_objects[k_splitted[0]] = internal_objects.get(k_splitted[0], {}) # update the new value internal_objects[k_splitted[0]].update({k_splitted[1]: v}) if internal_objects: for attr_name, data in internal_objects.items(): if hasattr(self, attr_name): if getattr(self, attr_name): field = getattr(self.__class__, attr_name) model = get_model(field.foreign_key) setattr(self, attr_name, model().construct(data)) else: for join in subitems[0]["fields"]: if join["right_table"] == attr_name: field = getattr(self.__class__, join["orm_fieldname"]) model = get_model(field.foreign_key) setattr(self, join["orm_fieldname"], model().construct(data)) break self.deleted = deleted return self async def save(self, **kwargs): # external save method if self.deleted: raise AsyncOrmModelError( "That {model_name} has already been deleted!".format(model_name=self.__class__.__name__) ) await self.objects.save(self) async def delete(self): # object delete method self.deleted = True return await self.objects.delete(self) def __str__(self): return "< {} object >".format(self.__class__.__name__) def __repr__(self): return self.__str__()
[ "inspect.getmodule", "asyncorm.models.fields.AutoField", "asyncorm.exceptions.AsyncOrmFieldError", "asyncorm.application.configure.get_model", "asyncorm.exceptions.AsyncOrmModelError", "asyncorm.manager.ModelManager" ]
[((4214, 4237), 'asyncorm.application.configure.get_model', 'get_model', (['other_column'], {}), '(other_column)\n', (4223, 4237), False, 'from asyncorm.application.configure import get_model\n'), ((4257, 4295), 'asyncorm.manager.ModelManager', 'ModelManager', (['other_model'], {'field': 'field'}), '(other_model, field=field)\n', (4269, 4295), False, 'from asyncorm.manager import ModelManager\n'), ((1715, 1726), 'asyncorm.models.fields.AutoField', 'AutoField', ([], {}), '()\n', (1724, 1726), False, 'from asyncorm.models.fields import AutoField, Field, ForeignKey, ManyToManyField\n'), ((3914, 3935), 'asyncorm.application.configure.get_model', 'get_model', (['model_name'], {}), '(model_name)\n', (3923, 3935), False, 'from asyncorm.application.configure import get_model\n'), ((7533, 7643), 'asyncorm.exceptions.AsyncOrmModelError', 'AsyncOrmModelError', (['"""Models should have unique attribute names and field_name if explicitly edited!"""'], {}), "(\n 'Models should have unique attribute names and field_name if explicitly edited!'\n )\n", (7551, 7643), False, 'from asyncorm.exceptions import AsyncOrmFieldError, AsyncOrmModelDoesNotExist, AsyncOrmModelError\n'), ((8418, 8448), 'asyncorm.exceptions.AsyncOrmModelError', 'AsyncOrmModelError', (['error_list'], {}), '(error_list)\n', (8436, 8448), False, 'from asyncorm.exceptions import AsyncOrmFieldError, AsyncOrmModelDoesNotExist, AsyncOrmModelError\n'), ((2463, 2486), 'inspect.getmodule', 'inspect.getmodule', (['self'], {}), '(self)\n', (2480, 2486), False, 'import inspect\n'), ((8649, 8713), 'asyncorm.exceptions.AsyncOrmFieldError', 'AsyncOrmFieldError', (['"""Models can not be generated with forced id"""'], {}), "('Models can not be generated with forced id')\n", (8667, 8713), False, 'from asyncorm.exceptions import AsyncOrmFieldError, AsyncOrmModelDoesNotExist, AsyncOrmModelError\n'), ((12064, 12092), 'asyncorm.application.configure.get_model', 'get_model', (['field.foreign_key'], {}), '(field.foreign_key)\n', (12073, 12092), False, 'from asyncorm.application.configure import get_model\n'), ((12425, 12453), 'asyncorm.application.configure.get_model', 'get_model', (['field.foreign_key'], {}), '(field.foreign_key)\n', (12434, 12453), False, 'from asyncorm.application.configure import get_model\n')]
# # Jasy - Web Tooling Framework # Copyright 2010-2012 Zynga Inc. # Copyright 2013-2014 <NAME> # import os import jasy import jasy.core.Console as Console from jasy.item.Script import ScriptError from jasy.item.Script import ScriptItem import jasy.script.Resolver as ScriptResolver from jasy.script.Resolver import Resolver import jasy.script.output.Optimization as ScriptOptimization import jasy.script.output.Formatting as ScriptFormatting class ScriptBuilder: # -------------------------------------------------------------------------------------------- # ESSENTIALS # -------------------------------------------------------------------------------------------- def __init__(self, profile): self.__profile = profile self.__session = profile.getSession() self.__assetManager = profile.getAssetManager() self.__fileManager = profile.getFileManager() self.__outputPath = os.path.join(profile.getDestinationPath(), profile.getJsOutputFolder()) self.__kernelScripts = [] self.__scriptOptimization = ScriptOptimization.Optimization() self.__scriptFormatting = ScriptFormatting.Formatting() compressionLevel = profile.getCompressionLevel() formattingLevel = profile.getFormattingLevel() self.__addDividers = formattingLevel > 0 if compressionLevel > 0: self.__scriptOptimization.enable("variables") self.__scriptOptimization.enable("declarations") if compressionLevel > 1: self.__scriptOptimization.enable("blocks") self.__scriptOptimization.enable("privates") if formattingLevel > 1: self.__scriptFormatting.enable("semicolon") self.__scriptFormatting.enable("comma") def __sortScriptItems(self, items, bootCode=None, filterBy=None, inlineTranslations=False): profile = self.__profile session = self.__session # 1. Add given set of items resolver = Resolver(profile) for item in items: resolver.add(item) # 2. Add optional boot code if bootCode: bootScriptItem = session.getVirtualItem("jasy.generated.BootCode", ScriptItem, "(function(){%s})();" % bootCode, ".js") resolver.add(bootScriptItem) # 3. Check for asset usage includedScripts = resolver.getIncluded() usesAssets = False for item in includedScripts: if item.getId() == "jasy.Asset": usesAssets = True break # 4. Add asset data if needed if usesAssets: assetData = self.__assetManager.exportToJson(includedScripts) if assetData: assetScriptItem = session.getVirtualItem("jasy.generated.AssetData", ScriptItem, "jasy.Asset.addData(%s);" % assetData, ".js") resolver.add(assetScriptItem, prepend=True) # 5. Add translation data if not inlineTranslations: translationBundle = session.getTranslationBundle(profile.getCurrentLocale()) if translationBundle: translationData = translationBundle.export(includedScripts) if translationData: translationScriptItem = session.getVirtualItem("jasy.generated.TranslationData", ScriptItem, "jasy.Translate.addData(%s);" % translationData, ".js") resolver.add(translationScriptItem, prepend=True) # 6. Sorting items sortedScripts = resolver.getSorted() # 7. Apply filter if filterBy: filteredScripts = [] for item in sortedScripts: if item not in filterBy: filteredScripts.append(item) sortedScripts = filteredScripts return sortedScripts def __compressScripts(self, items): try: profile = self.__profile session = self.__session result = [] for item in items: compressed = item.getCompressed(profile) if self.__addDividers: result.append("// FILE ID: %s\n%s\n\n" % (item.getId(), compressed)) else: result.append(compressed) except ScriptError as error: raise jasy.UserError("Error during script compression! %s" % error) return "".join(result) def __generateScriptLoader(self, items): # For loading items we require core.ui.Queue and core.io.Script # being available. If they are not part of the kernel, we have to # prepend them as compressed code into the resulting output. hasLoader = False hasQueue = False for item in self.__kernelScripts: itemId = item.getId() if itemId == "core.io.Queue": hasQueue = True elif itemId == "core.io.Script": hasLoader = True code = "" if not hasQueue or not hasLoader: compress = [] if not hasQueue: compress.append("core.io.Queue") if not hasLoader: compress.append("core.io.Script") compressedList = self.__sortScriptItems(compress, filterBy=self.__kernelScripts) code += self.__compressScripts(compressedList) main = self.__session.getMain() files = [] for item in items: # Ignore already compressed items if item.getId() in ("core.io.Script", "core.io.Queue"): continue path = item.getPath() # Support for multi path items # (typically in projects with custom layout/structure e.g. 3rd party) if isinstance(path, list): for singleFileName in path: files.append(main.toRelativeUrl(singleFileName)) else: files.append(main.toRelativeUrl(path)) if self.__addDividers: loaderList = '"%s"' % '",\n"'.join(files) else: loaderList = '"%s"' % '","'.join(files) code += 'core.io.Queue.load([%s], null, null, true);' % loaderList return code # -------------------------------------------------------------------------------------------- # PUBLIC API # -------------------------------------------------------------------------------------------- def getWorkingPath(self): # Locations inside scripts are always relative to the application root folder # aka the folder where HTML files are loaded from return self.__profile.getDestinationPath() def buildKernel(self, fileId): if not fileId: return self.__profile.setWorkingPath(self.getWorkingPath()) self.storeKernelScript("kernel.js", bootCode="%s.boot();" % fileId) def buildPart(self, partId, fileId): if not fileId: return Console.info("Generating script (%s)...", fileId) Console.indent() self.__profile.setWorkingPath(self.getWorkingPath()) ScriptItems = ScriptResolver.Resolver(self.__profile).add(fileId).getSorted() if self.__profile.getUseSource(): self.storeLoaderScript(ScriptItems, "%s-{{id}}.js" % partId, "new %s;" % fileId) else: self.storeCompressedScript(ScriptItems, "%s-{{id}}.js" % partId, "new %s;" % fileId) Console.outdent() def storeKernelScript(self, fileName, bootCode=""): Console.info("Generating kernel script...") Console.indent() # Export all profile data for the kernel items = self.__profile.getSetupScripts().values() # Transfer all hard-wired fields into a permutation self.__profile.setStaticPermutation() # Sort and compress sortedScripts = self.__sortScriptItems(items, bootCode, inlineTranslations=True) compressedCode = self.__compressScripts(sortedScripts) self.__fileManager.writeFile(os.path.join(self.__outputPath, fileName), compressedCode) self.__kernelScripts = sortedScripts Console.outdent() def storeLoaderScript(self, items, fileName, bootCode=""): Console.info("Generating loader script...") Console.indent() sortedScripts = self.__sortScriptItems(items, bootCode, filterBy=self.__kernelScripts) loaderCode = self.__generateScriptLoader(sortedScripts) self.__fileManager.writeFile(os.path.join(self.__outputPath, fileName), loaderCode) Console.outdent() def storeCompressedScript(self, items, fileName, bootCode=""): Console.info("Generating compressed script...") Console.indent() sortedScripts = self.__sortScriptItems(items, bootCode, filterBy=self.__kernelScripts, inlineTranslations=True) compressedCode = self.__compressScripts(sortedScripts) self.__fileManager.writeFile(os.path.join(self.__outputPath, fileName), compressedCode) Console.outdent()
[ "jasy.script.Resolver.Resolver", "jasy.script.output.Optimization.Optimization", "jasy.core.Console.indent", "jasy.core.Console.info", "os.path.join", "jasy.UserError", "jasy.script.output.Formatting.Formatting", "jasy.core.Console.outdent" ]
[((1086, 1119), 'jasy.script.output.Optimization.Optimization', 'ScriptOptimization.Optimization', ([], {}), '()\n', (1117, 1119), True, 'import jasy.script.output.Optimization as ScriptOptimization\n'), ((1154, 1183), 'jasy.script.output.Formatting.Formatting', 'ScriptFormatting.Formatting', ([], {}), '()\n', (1181, 1183), True, 'import jasy.script.output.Formatting as ScriptFormatting\n'), ((2010, 2027), 'jasy.script.Resolver.Resolver', 'Resolver', (['profile'], {}), '(profile)\n', (2018, 2027), False, 'from jasy.script.Resolver import Resolver\n'), ((6987, 7036), 'jasy.core.Console.info', 'Console.info', (['"""Generating script (%s)..."""', 'fileId'], {}), "('Generating script (%s)...', fileId)\n", (6999, 7036), True, 'import jasy.core.Console as Console\n'), ((7045, 7061), 'jasy.core.Console.indent', 'Console.indent', ([], {}), '()\n', (7059, 7061), True, 'import jasy.core.Console as Console\n'), ((7466, 7483), 'jasy.core.Console.outdent', 'Console.outdent', ([], {}), '()\n', (7481, 7483), True, 'import jasy.core.Console as Console\n'), ((7551, 7594), 'jasy.core.Console.info', 'Console.info', (['"""Generating kernel script..."""'], {}), "('Generating kernel script...')\n", (7563, 7594), True, 'import jasy.core.Console as Console\n'), ((7603, 7619), 'jasy.core.Console.indent', 'Console.indent', ([], {}), '()\n', (7617, 7619), True, 'import jasy.core.Console as Console\n'), ((8166, 8183), 'jasy.core.Console.outdent', 'Console.outdent', ([], {}), '()\n', (8181, 8183), True, 'import jasy.core.Console as Console\n'), ((8258, 8301), 'jasy.core.Console.info', 'Console.info', (['"""Generating loader script..."""'], {}), "('Generating loader script...')\n", (8270, 8301), True, 'import jasy.core.Console as Console\n'), ((8310, 8326), 'jasy.core.Console.indent', 'Console.indent', ([], {}), '()\n', (8324, 8326), True, 'import jasy.core.Console as Console\n'), ((8588, 8605), 'jasy.core.Console.outdent', 'Console.outdent', ([], {}), '()\n', (8603, 8605), True, 'import jasy.core.Console as Console\n'), ((8684, 8731), 'jasy.core.Console.info', 'Console.info', (['"""Generating compressed script..."""'], {}), "('Generating compressed script...')\n", (8696, 8731), True, 'import jasy.core.Console as Console\n'), ((8740, 8756), 'jasy.core.Console.indent', 'Console.indent', ([], {}), '()\n', (8754, 8756), True, 'import jasy.core.Console as Console\n'), ((9046, 9063), 'jasy.core.Console.outdent', 'Console.outdent', ([], {}), '()\n', (9061, 9063), True, 'import jasy.core.Console as Console\n'), ((8053, 8094), 'os.path.join', 'os.path.join', (['self.__outputPath', 'fileName'], {}), '(self.__outputPath, fileName)\n', (8065, 8094), False, 'import os\n'), ((8524, 8565), 'os.path.join', 'os.path.join', (['self.__outputPath', 'fileName'], {}), '(self.__outputPath, fileName)\n', (8536, 8565), False, 'import os\n'), ((8978, 9019), 'os.path.join', 'os.path.join', (['self.__outputPath', 'fileName'], {}), '(self.__outputPath, fileName)\n', (8990, 9019), False, 'import os\n'), ((4330, 4391), 'jasy.UserError', 'jasy.UserError', (["('Error during script compression! %s' % error)"], {}), "('Error during script compression! %s' % error)\n", (4344, 4391), False, 'import jasy\n'), ((7146, 7185), 'jasy.script.Resolver.Resolver', 'ScriptResolver.Resolver', (['self.__profile'], {}), '(self.__profile)\n', (7169, 7185), True, 'import jasy.script.Resolver as ScriptResolver\n')]
# coding=utf-8 # Copyright 2020 The Google Research Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Collapsed Amortized Variational Inference for SNLDS. This is a reasonable baseline model for switching non-linear dynamical system with the following architecture: 1. an inference network, with Bidirectional-RNN for input embedding, and a forward RNN to get the posterior distribution of `q(z[1:T] | x[1:T])`. 2. a continuous state transition network, `p(z[t] | z[t-1], s[t])`. 3. a discrete state transition network that conditioned on the input, `p(s[t] | s[t-1], x[t-1])`. 4. an emission network conditioned on the continuous hidden dynamics, `p(x[t] | z[t])`. It also contains a function, `create_model()`, to help to create the SNLDS model discribed in ``Collapsed Amortized Variational Inference for Switching Nonlinear Dynamical Systems``. 2019. https://arxiv.org/abs/1910.09588. All the networks are configurable through function arguments `network_*`. """ import collections import tensorflow as tf import tensorflow_probability as tfp from snlds import model_base from snlds import utils namedtuple = collections.namedtuple layers = tf.keras.layers tfd = tfp.distributions tfpl = tfp.layers RANDOM_SEED = 131 def construct_initial_state_distribution( latent_dim, num_categ, use_trainable_cov=False, use_triangular_cov=False, raw_sigma_bias=0.0, sigma_min=1e-5, sigma_scale=0.05, dtype=tf.float32, name="z0"): """Construct the initial state distribution, `p(z[0])`. Args: latent_dim: an `int` scalar for dimension of continuous hidden states, `z`. num_categ: an `int` scalar for number of discrete states, `s`. use_trainable_cov: a `bool` scalar indicating whether the scale of `p(z[0])` is trainable. Default to False. use_triangular_cov: a `bool` scalar indicating whether to use triangular covariance matrices and `tfp.distributions.MultivariateNormalTriL` for distribution. Otherwise, a diagonal covariance matrices and `tfp.distributions.MultivariateNormalDiag` will be used. raw_sigma_bias: a `float` scalar to be added to the raw sigma, which is standard deviation of the distribution. Default to `0.`. sigma_min: a `float` scalar for minimal level of sigma to prevent underflow. Default to `1e-5`. sigma_scale: a `float` scalar for scaling the sigma. Default to `0.05`. The above three arguments are used as `sigma_scale * max(softmax(raw_sigma + raw_sigma_bias), sigma_min))`. dtype: data type for variables within the scope. Default to `tf.float32`. name: a `str` to construct names of variables. Returns: return_dist: a `tfp.distributions` instance for the initial state distribution, `p(z[0])`. """ glorot_initializer = tf.keras.initializers.GlorotUniform() z0_mean = tf.Variable( initial_value=glorot_initializer(shape=[num_categ, latent_dim], dtype=dtype), name="{}_mean".format(name)) if use_triangular_cov: z0_scale = tfp.math.fill_triangular( tf.Variable( initial_value=glorot_initializer( shape=[int(latent_dim * (latent_dim + 1) / 2)], dtype=dtype), name="{}_scale".format(name), trainable=use_trainable_cov)) z0_scale = (tf.maximum(tf.nn.softmax(z0_scale + raw_sigma_bias), sigma_min) * sigma_scale) return_dist = tfd.Independent( distribution=tfd.MultivariateNormalTriL( loc=z0_mean, scale_tril=z0_scale), reinterpreted_batch_ndims=0) else: z0_scale = tf.Variable( initial_value=glorot_initializer( shape=[latent_dim], dtype=dtype), name="{}_scale".format(name), trainable=use_trainable_cov) z0_scale = (tf.maximum(tf.nn.softmax(z0_scale + raw_sigma_bias), sigma_min) * sigma_scale) return_dist = tfd.Independent( distribution=tfd.MultivariateNormalDiag( loc=z0_mean, scale_diag=z0_scale), reinterpreted_batch_ndims=0) return tfp.experimental.as_composite(return_dist) class ContinuousStateTransition(tf.keras.Model): """Transition for `p(z[t] | z[t-1], s[t])`.""" def __init__(self, transition_mean_networks, distribution_dim, num_categories=1, cov_mat=None, use_triangular_cov=False, use_trainable_cov=True, raw_sigma_bias=0.0, sigma_min=1e-5, sigma_scale=0.05, dtype=tf.float32, name="ContinuousStateTransition"): """Construct a `ContinuousStateTransition` instance. Args: transition_mean_networks: a list of `callable` networks, with the length of list same as `num_categories`. Each one of the networks will take previous step hidden state, `z[t-1]`, and returns the mean of transition distribution, `p(z[t] | z[t-1], s[t]=i)` for each discrete state `i`. distribution_dim: an `int` scalar for dimension of continuous hidden states, `z`. num_categories: an `int` scalar for number of discrete states, `s`. cov_mat: an optional `float` Tensor for predefined covariance matrix. Default to `None`, in which case, a `cov` variable will be created. use_triangular_cov: a `bool` scalar indicating whether to use triangular covariance matrices and `tfp.distributions.MultivariateNormalTriL` for distribution. Otherwise, a diagonal covariance matrices and `tfp.distributions.MultivariateNormalDiag` will be used. use_trainable_cov: a `bool` scalar indicating whether the scale of the distribution is trainable. Default to False. raw_sigma_bias: a `float` scalar to be added to the raw sigma, which is standard deviation of the distribution. Default to `0.`. sigma_min: a `float` scalar for minimal level of sigma to prevent underflow. Default to `1e-5`. sigma_scale: a `float` scalar for scaling the sigma. Default to `0.05`. The above three arguments are used as `sigma_scale * max(softmax(raw_sigma + raw_sigma_bias), sigma_min))`. dtype: data type for variables within the scope. Default to `tf.float32`. name: a `str` to construct names of variables. """ super(ContinuousStateTransition, self).__init__() assertion_str = ( "There has to be one transition mean networks for each discrete state") assert len(transition_mean_networks) == num_categories, assertion_str self.z_trans_networks = transition_mean_networks self.num_categ = num_categories self.use_triangular_cov = use_triangular_cov self.distribution_dim = distribution_dim if cov_mat: self.cov_mat = cov_mat elif self.use_triangular_cov: self.cov_mat = tfp.math.fill_triangular( tf.Variable( tf.random.uniform( shape=[ int(self.distribution_dim * (self.distribution_dim + 1) / 2)], minval=0., maxval=1., dtype=dtype), name="{}_cov".format(name), dtype=dtype, trainable=use_trainable_cov)) self.cov_mat = tf.maximum(tf.nn.softmax(self.cov_mat + raw_sigma_bias), sigma_min) * sigma_scale else: self.cov_mat = tf.Variable( tf.random.uniform(shape=[self.distribution_dim], minval=0.0, maxval=1., dtype=dtype), name="{}_cov".format(name), dtype=dtype, trainable=use_trainable_cov) self.cov_mat = tf.maximum(tf.nn.softmax(self.cov_mat + raw_sigma_bias), sigma_min) * sigma_scale def call(self, input_tensor, dtype=tf.float32): input_tensor = tf.convert_to_tensor(input_tensor, dtype_hint=dtype) batch_size, num_steps, distribution_dim = tf.unstack(tf.shape(input_tensor)) # The shape of the mean_tensor after tf.stack is [num_categ, batch_size, # num_steps, distribution_dim]., mean_tensor = tf.transpose( tf.stack([ z_net(input_tensor) for z_net in self.z_trans_networks]), [1, 2, 0, 3]) mean_tensor = tf.reshape(mean_tensor, [batch_size, num_steps, self.num_categ, distribution_dim]) if self.use_triangular_cov: output_dist = tfd.MultivariateNormalTriL( loc=mean_tensor, scale_tril=self.cov_mat) else: output_dist = tfd.MultivariateNormalDiag( loc=mean_tensor, scale_diag=self.cov_mat) return tfp.experimental.as_composite(output_dist) @property def output_event_dims(self): return self.distribution_dim class DiscreteStateTransition(tf.keras.Model): """Discrete state transition p(s[t] | s[t-1], x[t-1]).""" def __init__(self, transition_network, num_categories): """Construct a `DiscreteStateTransition` instance. Args: transition_network: a `callable` network taking batch conditional inputs, `x[t-1]`, and returning the discrete state transition matrices, `log p(s[t] |s[t-1], x[t-1])`. num_categories: an `int` scalar for number of discrete states, `s`. """ super(DiscreteStateTransition, self).__init__() self.dense_net = transition_network self.num_categ = num_categories def call(self, input_tensor, dtype=tf.float32): input_tensor = tf.convert_to_tensor(input_tensor, dtype_hint=dtype) batch_size, num_steps = tf.unstack(tf.shape(input_tensor)[:2]) transition_tensor = self.dense_net(input_tensor) transition_tensor = tf.reshape( transition_tensor, [batch_size, num_steps, self.num_categ, self.num_categ]) return transition_tensor @property def output_event_dims(self): return self.num_categ class GaussianDistributionFromMean(tf.keras.Model): """Emission model p(x[t] | z[t]).""" def __init__(self, emission_mean_network, observation_dim, cov_mat=None, use_triangular_cov=False, use_trainable_cov=True, raw_sigma_bias=0.0, sigma_min=1e-5, sigma_scale=0.05, dtype=tf.float32, name="GaussianDistributionFromMean"): """Construct a `GaussianDistributionFromMean` instance. Args: emission_mean_network: a `callable` network taking continuous hidden states, `z[t]`, and returning the mean of emission distribution, `p(x[t] | z[t])`. observation_dim: an `int` scalar for dimension of observations, `x`. cov_mat: an optional `float` Tensor for predefined covariance matrix. Default to `None`, in which case, a `cov` variable will be created. use_triangular_cov: a `bool` scalar indicating whether to use triangular covariance matrices and `tfp.distributions.MultivariateNormalTriL` for distribution. Otherwise, a diagonal covariance matrices and `tfp.distributions.MultivariateNormalDiag` will be used. use_trainable_cov: a `bool` scalar indicating whether the scale of the distribution is trainable. Default to False. raw_sigma_bias: a `float` scalar to be added to the raw sigma, which is standard deviation of the distribution. Default to `0.`. sigma_min: a `float` scalar for minimal level of sigma to prevent underflow. Default to `1e-5`. sigma_scale: a `float` scalar for scaling the sigma. Default to `0.05`. The above three arguments are used as `sigma_scale * max(softmax(raw_sigma + raw_sigma_bias), sigma_min))`. dtype: data type for variables within the scope. Default to `tf.float32`. name: a `str` to construct names of variables. """ super(GaussianDistributionFromMean, self).__init__() self.observation_dim = observation_dim self.x_emission_net = emission_mean_network self.use_triangular_cov = use_triangular_cov if cov_mat: self.cov_mat = cov_mat elif self.use_triangular_cov: local_variable = tf.Variable( tf.random.uniform( shape=[int(self.observation_dim*(self.observation_dim+1)/2)], minval=0., maxval=1., dtype=dtype), name="{}_cov".format(name), dtype=dtype, trainable=use_trainable_cov) self.cov_mat = tfp.math.fill_triangular( local_variable) self.cov_mat = tf.maximum(tf.nn.softmax(self.cov_mat + raw_sigma_bias), sigma_min) * sigma_scale else: self.cov_mat = tf.Variable( initial_value=tf.random.uniform(shape=[self.observation_dim], minval=0.0, maxval=1., dtype=dtype), name="{}_cov".format(name), dtype=dtype, trainable=use_trainable_cov) self.cov_mat = tf.maximum(tf.nn.softmax(self.cov_mat + raw_sigma_bias), sigma_min) * sigma_scale def call(self, input_tensor, dtype=tf.float32): input_tensor = tf.convert_to_tensor(input_tensor, dtype_hint=dtype) mean_tensor = self.x_emission_net(input_tensor) if self.use_triangular_cov: output_dist = tfd.MultivariateNormalTriL( loc=mean_tensor, scale_tril=self.cov_mat) else: output_dist = tfd.MultivariateNormalDiag( loc=mean_tensor, scale_diag=self.cov_mat) return tfp.experimental.as_composite(output_dist) @property def output_event_dims(self): return self.observation_dim class RnnInferenceNetwork(tf.keras.Model): """Inference network for posterior q(z[1:T] | x[1:T]).""" def __init__(self, posterior_rnn, posterior_dist, latent_dim, embedding_network=None): """Construct a `RnnInferenceNetwork` instance. Args: posterior_rnn: a RNN cell, `h[t]=f_RNN(h[t-1], z[t-1], input[t])`, which recursively takes previous step RNN states `h`, previous step sampled dynamical state `z[t-1]`, and conditioned input `input[t]`. posterior_dist: a distribution instance for `p(z[t] | h[t])`, where h[t] is the output of `posterior_rnn`. latent_dim: an `int` scalar for dimension of continuous hidden states, `z`. embedding_network: an optional network to embed the observations, `x[t]`. Default to `None`, in which case, no embedding is applied. """ super(RnnInferenceNetwork, self).__init__() self.latent_dim = latent_dim self.posterior_rnn = posterior_rnn self.posterior_dist = posterior_dist if embedding_network is None: self.embedding_network = lambda x: x self.embedding_network = embedding_network def call(self, inputs, num_samples=1, dtype=tf.float32, random_seed=RANDOM_SEED, parallel_iterations=10): """Recursively sample z[t] ~ q(z[t]|h[t]=f_RNN(h[t-1], z[t-1], h[t]^b)). Args: inputs: a float `Tensor` of size [batch_size, num_steps, obs_dim], where each observation should be flattened. num_samples: an `int` scalar for number of samples per time-step, for posterior inference networks, `z[i] ~ q(z[1:T] | x[1:T])`. dtype: The data type of input data. random_seed: an `Int` as the seed for random number generator. parallel_iterations: a positive `Int` indicates the number of iterations allowed to run in parallel in `tf.while_loop`, where `tf.while_loop` defaults it to be 10. Returns: sampled_z: a float 3-D `Tensor` of size [num_samples, batch_size, num_steps, latent_dim], which stores the z_t sampled from posterior. entropies: a float 2-D `Tensor` of size [num_samples, batch_size, num_steps], which stores the entropies of posterior distributions. log_probs: a float 2-D `Tensor` of size [num_samples. batch_size, num_steps], which stores the log posterior probabilities. """ inputs = tf.convert_to_tensor(inputs, dtype_hint=dtype) batch_size, num_steps = tf.unstack(tf.shape(inputs)[:2]) latent_dim = self.latent_dim ## passing through embedding_network, e.g. bidirectional RNN inputs = self.embedding_network(inputs) ## passing through forward RNN ta_names = ["rnn_states", "latent_states", "entropies", "log_probs"] tas = [tf.TensorArray(tf.float32, num_steps, name=n) for n in ta_names] t0 = tf.constant(0, tf.int32) loopstate = namedtuple("LoopState", "rnn_state latent_encoded") initial_rnn_state = self.posterior_rnn.get_initial_state( batch_size=batch_size * num_samples, dtype=dtype) if (isinstance(self.posterior_rnn, layers.GRUCell) or isinstance(self.posterior_rnn, layers.SimpleRNNCell)): initial_rnn_state = [initial_rnn_state] init_state = (t0, loopstate( rnn_state=initial_rnn_state, latent_encoded=tf.zeros( [batch_size * num_samples, latent_dim], dtype=tf.float32)), tas) def _cond(t, *unused_args): return t < num_steps def _step(t, loop_state, tas): """One step in tf.while_loop.""" prev_latent_state = loop_state.latent_encoded prev_rnn_state = loop_state.rnn_state current_input = inputs[:, t, :] # Duplicate current observation to sample multiple trajectories. current_input = tf.tile(current_input, [num_samples, 1]) rnn_input = tf.concat([current_input, prev_latent_state], axis=-1) # num_samples * BS, latent_dim+input_dim rnn_out, rnn_state = self.posterior_rnn( inputs=rnn_input, states=prev_rnn_state) dist = self.posterior_dist(rnn_out) latent_state = dist.sample(seed=random_seed) ## rnn_state is a list of [batch_size, rnn_hidden_dim], ## after TA.stack(), the dimension will be ## [num_steps, 1 for GRU/2 for LSTM, batch, rnn_dim] tas_updates = [rnn_state, latent_state, dist.entropy(), dist.log_prob(latent_state)] tas = utils.write_updates_to_tas(tas, t, tas_updates) return (t+1, loopstate(rnn_state=rnn_state, latent_encoded=latent_state), tas) ## end of _step function _, _, tas_final = tf.while_loop( _cond, _step, init_state, parallel_iterations=parallel_iterations) sampled_z, entropies, log_probs = [ utils.tensor_for_ta(ta, swap_batch_time=True) for ta in tas_final[1:] ] sampled_z = tf.reshape(sampled_z, [num_samples, batch_size, num_steps, latent_dim]) entropies = tf.reshape(entropies, [num_samples, batch_size, num_steps]) log_probs = tf.reshape(log_probs, [num_samples, batch_size, num_steps]) return sampled_z, entropies, log_probs def create_model(num_categ, hidden_dim, observation_dim, config_emission, config_inference, config_z_initial, config_z_transition, network_emission, network_input_embedding, network_posterior_rnn, network_s_transition, networks_z_transition, network_posterior_mlp=lambda x: x, name="snlds"): """Construct SNLDS model. Args: num_categ: an `int` scalar for number of discrete states, `s`. hidden_dim: an `int` scalar for dimension of continuous hidden states, `z`. observation_dim: an `int` scalar for dimension of observations, `x`. config_emission: a `dict` for configuring emission distribution, `p(x[t] | z[t])`. config_inference: a `dict` for configuring the posterior distribution, `q(z[t]|h[t]=f_RNN(h[t-1], z[t-1], h[t]^b))`. config_z_initial: a `dict` for configuring the initial distribution of continuous hidden state, `p(z[0])`. config_z_transition: a `dict` for configuring the transition distribution `p(z[t] | z[t-1], s[t])`. network_emission: a `callable` network taking continuous hidden states, `z[t]`, and returning the mean of emission distribution, `p(x[t] | z[t])`. network_input_embedding: a `callable` network to embed the observations, `x[t]`. E.g. a bidirectional RNN to embedding `x[1:T]`. network_posterior_rnn: a RNN cell, `h[t]=f_RNN(h[t-1], z[t-1], input[t])`, which recursively takes previous step RNN states `h`, previous step sampled dynamical state `z[t-1]`, and conditioned input `input[t]`. network_s_transition: a `callable` network taking batch conditional inputs, `x[t-1]`, and returning the discrete state transition matrices, `log p(s[t] |s[t-1], x[t-1])`. networks_z_transition: a list of `callable` networks, with the length of list same as `num_categories`. Each one of the networks will take previous step hidden state, `z[t-1]`, and returns the mean of transition distribution, `p(z[t] | z[t-1], s[t]=i)` for each discrete state `i`. network_posterior_mlp: an optional network to embedding the output of inference RNN networks, before passing into the distribution as mean, `q(z[t] | mlp( h[t] ))`. Default to identity mapping. name: a `str` to construct names of variables. Returns: An instance of instantiated `model_base.SwitchingNLDS` model. """ z_transition = ContinuousStateTransition( transition_mean_networks=networks_z_transition, distribution_dim=hidden_dim, num_categories=num_categ, cov_mat=config_z_transition.cov_mat, use_triangular_cov=config_z_transition.use_triangular_cov, use_trainable_cov=config_z_transition.use_trainable_cov, raw_sigma_bias=config_z_transition.raw_sigma_bias, sigma_min=config_z_transition.sigma_min, sigma_scale=config_z_transition.sigma_scale, name=name+"_z_trans") s_transition = DiscreteStateTransition( transition_network=network_s_transition, num_categories=num_categ) emission_network = GaussianDistributionFromMean( emission_mean_network=network_emission, observation_dim=observation_dim, cov_mat=config_emission.cov_mat, use_triangular_cov=config_emission.use_triangular_cov, use_trainable_cov=config_emission.use_trainable_cov, raw_sigma_bias=config_emission.raw_sigma_bias, sigma_min=config_emission.sigma_min, sigma_scale=config_emission.sigma_scale, name=name+"_x_emit") posterior_distribution = GaussianDistributionFromMean( emission_mean_network=network_posterior_mlp, observation_dim=hidden_dim, cov_mat=config_inference.cov_mat, use_triangular_cov=config_inference.use_triangular_cov, use_trainable_cov=config_inference.use_trainable_cov, raw_sigma_bias=config_inference.raw_sigma_bias, sigma_min=config_inference.sigma_min, sigma_scale=config_inference.sigma_scale, name=name+"_posterior") posterior_network = RnnInferenceNetwork( posterior_rnn=network_posterior_rnn, posterior_dist=posterior_distribution, latent_dim=hidden_dim, embedding_network=network_input_embedding) z_initial_distribution = construct_initial_state_distribution( latent_dim=hidden_dim, num_categ=num_categ, use_trainable_cov=config_z_initial.use_trainable_cov, use_triangular_cov=config_z_initial.use_triangular_cov, raw_sigma_bias=config_z_initial.raw_sigma_bias, sigma_min=config_z_initial.sigma_min, sigma_scale=config_z_initial.sigma_scale, name="init_dist") snlds_model = model_base.SwitchingNLDS( continuous_transition_network=z_transition, discrete_transition_network=s_transition, emission_network=emission_network, inference_network=posterior_network, initial_distribution=z_initial_distribution, continuous_state_dim=None, num_categories=None, discrete_state_prior=None) return snlds_model
[ "tensorflow.random.uniform", "tensorflow.tile", "tensorflow.shape", "tensorflow.TensorArray", "tensorflow.keras.initializers.GlorotUniform", "tensorflow_probability.experimental.as_composite", "snlds.utils.tensor_for_ta", "snlds.model_base.SwitchingNLDS", "tensorflow.concat", "snlds.utils.write_up...
[((3313, 3350), 'tensorflow.keras.initializers.GlorotUniform', 'tf.keras.initializers.GlorotUniform', ([], {}), '()\n', (3348, 3350), True, 'import tensorflow as tf\n'), ((4680, 4722), 'tensorflow_probability.experimental.as_composite', 'tfp.experimental.as_composite', (['return_dist'], {}), '(return_dist)\n', (4709, 4722), True, 'import tensorflow_probability as tfp\n'), ((24659, 24978), 'snlds.model_base.SwitchingNLDS', 'model_base.SwitchingNLDS', ([], {'continuous_transition_network': 'z_transition', 'discrete_transition_network': 's_transition', 'emission_network': 'emission_network', 'inference_network': 'posterior_network', 'initial_distribution': 'z_initial_distribution', 'continuous_state_dim': 'None', 'num_categories': 'None', 'discrete_state_prior': 'None'}), '(continuous_transition_network=z_transition,\n discrete_transition_network=s_transition, emission_network=\n emission_network, inference_network=posterior_network,\n initial_distribution=z_initial_distribution, continuous_state_dim=None,\n num_categories=None, discrete_state_prior=None)\n', (24683, 24978), False, 'from snlds import model_base\n'), ((8529, 8581), 'tensorflow.convert_to_tensor', 'tf.convert_to_tensor', (['input_tensor'], {'dtype_hint': 'dtype'}), '(input_tensor, dtype_hint=dtype)\n', (8549, 8581), True, 'import tensorflow as tf\n'), ((8939, 9025), 'tensorflow.reshape', 'tf.reshape', (['mean_tensor', '[batch_size, num_steps, self.num_categ, distribution_dim]'], {}), '(mean_tensor, [batch_size, num_steps, self.num_categ,\n distribution_dim])\n', (8949, 9025), True, 'import tensorflow as tf\n'), ((9356, 9398), 'tensorflow_probability.experimental.as_composite', 'tfp.experimental.as_composite', (['output_dist'], {}), '(output_dist)\n', (9385, 9398), True, 'import tensorflow_probability as tfp\n'), ((10212, 10264), 'tensorflow.convert_to_tensor', 'tf.convert_to_tensor', (['input_tensor'], {'dtype_hint': 'dtype'}), '(input_tensor, dtype_hint=dtype)\n', (10232, 10264), True, 'import tensorflow as tf\n'), ((10409, 10500), 'tensorflow.reshape', 'tf.reshape', (['transition_tensor', '[batch_size, num_steps, self.num_categ, self.num_categ]'], {}), '(transition_tensor, [batch_size, num_steps, self.num_categ, self.\n num_categ])\n', (10419, 10500), True, 'import tensorflow as tf\n'), ((13913, 13965), 'tensorflow.convert_to_tensor', 'tf.convert_to_tensor', (['input_tensor'], {'dtype_hint': 'dtype'}), '(input_tensor, dtype_hint=dtype)\n', (13933, 13965), True, 'import tensorflow as tf\n'), ((14294, 14336), 'tensorflow_probability.experimental.as_composite', 'tfp.experimental.as_composite', (['output_dist'], {}), '(output_dist)\n', (14323, 14336), True, 'import tensorflow_probability as tfp\n'), ((16887, 16933), 'tensorflow.convert_to_tensor', 'tf.convert_to_tensor', (['inputs'], {'dtype_hint': 'dtype'}), '(inputs, dtype_hint=dtype)\n', (16907, 16933), True, 'import tensorflow as tf\n'), ((17333, 17357), 'tensorflow.constant', 'tf.constant', (['(0)', 'tf.int32'], {}), '(0, tf.int32)\n', (17344, 17357), True, 'import tensorflow as tf\n'), ((19313, 19398), 'tensorflow.while_loop', 'tf.while_loop', (['_cond', '_step', 'init_state'], {'parallel_iterations': 'parallel_iterations'}), '(_cond, _step, init_state, parallel_iterations=parallel_iterations\n )\n', (19326, 19398), True, 'import tensorflow as tf\n'), ((19545, 19616), 'tensorflow.reshape', 'tf.reshape', (['sampled_z', '[num_samples, batch_size, num_steps, latent_dim]'], {}), '(sampled_z, [num_samples, batch_size, num_steps, latent_dim])\n', (19555, 19616), True, 'import tensorflow as tf\n'), ((19660, 19719), 'tensorflow.reshape', 'tf.reshape', (['entropies', '[num_samples, batch_size, num_steps]'], {}), '(entropies, [num_samples, batch_size, num_steps])\n', (19670, 19719), True, 'import tensorflow as tf\n'), ((19736, 19795), 'tensorflow.reshape', 'tf.reshape', (['log_probs', '[num_samples, batch_size, num_steps]'], {}), '(log_probs, [num_samples, batch_size, num_steps])\n', (19746, 19795), True, 'import tensorflow as tf\n'), ((8639, 8661), 'tensorflow.shape', 'tf.shape', (['input_tensor'], {}), '(input_tensor)\n', (8647, 8661), True, 'import tensorflow as tf\n'), ((17258, 17303), 'tensorflow.TensorArray', 'tf.TensorArray', (['tf.float32', 'num_steps'], {'name': 'n'}), '(tf.float32, num_steps, name=n)\n', (17272, 17303), True, 'import tensorflow as tf\n'), ((18352, 18392), 'tensorflow.tile', 'tf.tile', (['current_input', '[num_samples, 1]'], {}), '(current_input, [num_samples, 1])\n', (18359, 18392), True, 'import tensorflow as tf\n'), ((18412, 18466), 'tensorflow.concat', 'tf.concat', (['[current_input, prev_latent_state]'], {'axis': '(-1)'}), '([current_input, prev_latent_state], axis=-1)\n', (18421, 18466), True, 'import tensorflow as tf\n'), ((19075, 19122), 'snlds.utils.write_updates_to_tas', 'utils.write_updates_to_tas', (['tas', 't', 'tas_updates'], {}), '(tas, t, tas_updates)\n', (19101, 19122), False, 'from snlds import utils\n'), ((19452, 19497), 'snlds.utils.tensor_for_ta', 'utils.tensor_for_ta', (['ta'], {'swap_batch_time': '(True)'}), '(ta, swap_batch_time=True)\n', (19471, 19497), False, 'from snlds import utils\n'), ((3873, 3913), 'tensorflow.nn.softmax', 'tf.nn.softmax', (['(z0_scale + raw_sigma_bias)'], {}), '(z0_scale + raw_sigma_bias)\n', (3886, 3913), True, 'import tensorflow as tf\n'), ((4391, 4431), 'tensorflow.nn.softmax', 'tf.nn.softmax', (['(z0_scale + raw_sigma_bias)'], {}), '(z0_scale + raw_sigma_bias)\n', (4404, 4431), True, 'import tensorflow as tf\n'), ((10304, 10326), 'tensorflow.shape', 'tf.shape', (['input_tensor'], {}), '(input_tensor)\n', (10312, 10326), True, 'import tensorflow as tf\n'), ((13183, 13223), 'tensorflow_probability.math.fill_triangular', 'tfp.math.fill_triangular', (['local_variable'], {}), '(local_variable)\n', (13207, 13223), True, 'import tensorflow_probability as tfp\n'), ((16973, 16989), 'tensorflow.shape', 'tf.shape', (['inputs'], {}), '(inputs)\n', (16981, 16989), True, 'import tensorflow as tf\n'), ((8081, 8170), 'tensorflow.random.uniform', 'tf.random.uniform', ([], {'shape': '[self.distribution_dim]', 'minval': '(0.0)', 'maxval': '(1.0)', 'dtype': 'dtype'}), '(shape=[self.distribution_dim], minval=0.0, maxval=1.0,\n dtype=dtype)\n', (8098, 8170), True, 'import tensorflow as tf\n'), ((17862, 17928), 'tensorflow.zeros', 'tf.zeros', (['[batch_size * num_samples, latent_dim]'], {'dtype': 'tf.float32'}), '([batch_size * num_samples, latent_dim], dtype=tf.float32)\n', (17870, 17928), True, 'import tensorflow as tf\n'), ((7924, 7968), 'tensorflow.nn.softmax', 'tf.nn.softmax', (['(self.cov_mat + raw_sigma_bias)'], {}), '(self.cov_mat + raw_sigma_bias)\n', (7937, 7968), True, 'import tensorflow as tf\n'), ((8355, 8399), 'tensorflow.nn.softmax', 'tf.nn.softmax', (['(self.cov_mat + raw_sigma_bias)'], {}), '(self.cov_mat + raw_sigma_bias)\n', (8368, 8399), True, 'import tensorflow as tf\n'), ((13267, 13311), 'tensorflow.nn.softmax', 'tf.nn.softmax', (['(self.cov_mat + raw_sigma_bias)'], {}), '(self.cov_mat + raw_sigma_bias)\n', (13280, 13311), True, 'import tensorflow as tf\n'), ((13438, 13526), 'tensorflow.random.uniform', 'tf.random.uniform', ([], {'shape': '[self.observation_dim]', 'minval': '(0.0)', 'maxval': '(1.0)', 'dtype': 'dtype'}), '(shape=[self.observation_dim], minval=0.0, maxval=1.0,\n dtype=dtype)\n', (13455, 13526), True, 'import tensorflow as tf\n'), ((13739, 13783), 'tensorflow.nn.softmax', 'tf.nn.softmax', (['(self.cov_mat + raw_sigma_bias)'], {}), '(self.cov_mat + raw_sigma_bias)\n', (13752, 13783), True, 'import tensorflow as tf\n')]
import matplotlib.pyplt as plt from bermuda import ellipse, polygon, rectangle plt.plot([1,2,3], [2,3,4]) ax = plg.gca() # default choices for everything e = ellipse(ax) # custom position, genric interface for all shapes e = ellipse(ax, bbox = (x, y, w, h, theta)) e = ellipse(ax, cen=(x, y), width=w, height=h, theta=theta) # force square/circle? e = ellipse(ax, aspect_equal=True) # freeze properties? e = ellipse(ax, width=1, height=2, aspect_frozen = True) e = ellipse(ax, rotation_frozen=True) e = ellipse(ax, center_frozen=True) e = ellipse(ax, size_frozen=True) # all of these kwargs should be settable properties as well e.bbox = (x, y, w, h, theta) e.aspect_equal = True e.aspect_frozen = True
[ "bermuda.ellipse", "matplotlib.pyplt.plot" ]
[((82, 112), 'matplotlib.pyplt.plot', 'plt.plot', (['[1, 2, 3]', '[2, 3, 4]'], {}), '([1, 2, 3], [2, 3, 4])\n', (90, 112), True, 'import matplotlib.pyplt as plt\n'), ((162, 173), 'bermuda.ellipse', 'ellipse', (['ax'], {}), '(ax)\n', (169, 173), False, 'from bermuda import ellipse, polygon, rectangle\n'), ((230, 267), 'bermuda.ellipse', 'ellipse', (['ax'], {'bbox': '(x, y, w, h, theta)'}), '(ax, bbox=(x, y, w, h, theta))\n', (237, 267), False, 'from bermuda import ellipse, polygon, rectangle\n'), ((274, 329), 'bermuda.ellipse', 'ellipse', (['ax'], {'cen': '(x, y)', 'width': 'w', 'height': 'h', 'theta': 'theta'}), '(ax, cen=(x, y), width=w, height=h, theta=theta)\n', (281, 329), False, 'from bermuda import ellipse, polygon, rectangle\n'), ((358, 388), 'bermuda.ellipse', 'ellipse', (['ax'], {'aspect_equal': '(True)'}), '(ax, aspect_equal=True)\n', (365, 388), False, 'from bermuda import ellipse, polygon, rectangle\n'), ((415, 465), 'bermuda.ellipse', 'ellipse', (['ax'], {'width': '(1)', 'height': '(2)', 'aspect_frozen': '(True)'}), '(ax, width=1, height=2, aspect_frozen=True)\n', (422, 465), False, 'from bermuda import ellipse, polygon, rectangle\n'), ((472, 505), 'bermuda.ellipse', 'ellipse', (['ax'], {'rotation_frozen': '(True)'}), '(ax, rotation_frozen=True)\n', (479, 505), False, 'from bermuda import ellipse, polygon, rectangle\n'), ((510, 541), 'bermuda.ellipse', 'ellipse', (['ax'], {'center_frozen': '(True)'}), '(ax, center_frozen=True)\n', (517, 541), False, 'from bermuda import ellipse, polygon, rectangle\n'), ((546, 575), 'bermuda.ellipse', 'ellipse', (['ax'], {'size_frozen': '(True)'}), '(ax, size_frozen=True)\n', (553, 575), False, 'from bermuda import ellipse, polygon, rectangle\n')]
# Copyright 2022 MosaicML Composer authors # SPDX-License-Identifier: Apache-2.0 """BraTS (Brain Tumor Segmentation) dataset hyperparameters.""" from dataclasses import dataclass import torch import yahp as hp from composer.datasets.brats import PytTrain, PytVal, get_data_split from composer.datasets.dataset_hparams import DataLoaderHparams, DatasetHparams from composer.utils import dist def _my_collate(batch): """Custom collate function to handle images with different depths.""" data = [item[0] for item in batch] target = [item[1] for item in batch] return [torch.Tensor(data), torch.Tensor(target)] @dataclass class BratsDatasetHparams(DatasetHparams): """Defines an instance of the BraTS dataset for image segmentation. Args: oversampling (float): The oversampling ratio to use. Default: ``0.33``. """ oversampling: float = hp.optional("oversampling", default=0.33) def initialize_object(self, batch_size: int, dataloader_hparams: DataLoaderHparams): oversampling = self.oversampling if self.datadir is None: raise ValueError("datadir must be specified.") x_train, y_train, x_val, y_val = get_data_split(self.datadir) dataset = PytTrain(x_train, y_train, oversampling) if self.is_train else PytVal(x_val, y_val) collate_fn = None if self.is_train else _my_collate sampler = dist.get_sampler(dataset, drop_last=self.drop_last, shuffle=self.shuffle) return dataloader_hparams.initialize_object( dataset=dataset, batch_size=batch_size, sampler=sampler, drop_last=self.drop_last, collate_fn=collate_fn, )
[ "torch.Tensor", "yahp.optional", "composer.datasets.brats.get_data_split", "composer.datasets.brats.PytVal", "composer.datasets.brats.PytTrain", "composer.utils.dist.get_sampler" ]
[((884, 925), 'yahp.optional', 'hp.optional', (['"""oversampling"""'], {'default': '(0.33)'}), "('oversampling', default=0.33)\n", (895, 925), True, 'import yahp as hp\n'), ((588, 606), 'torch.Tensor', 'torch.Tensor', (['data'], {}), '(data)\n', (600, 606), False, 'import torch\n'), ((608, 628), 'torch.Tensor', 'torch.Tensor', (['target'], {}), '(target)\n', (620, 628), False, 'import torch\n'), ((1192, 1220), 'composer.datasets.brats.get_data_split', 'get_data_split', (['self.datadir'], {}), '(self.datadir)\n', (1206, 1220), False, 'from composer.datasets.brats import PytTrain, PytVal, get_data_split\n'), ((1401, 1474), 'composer.utils.dist.get_sampler', 'dist.get_sampler', (['dataset'], {'drop_last': 'self.drop_last', 'shuffle': 'self.shuffle'}), '(dataset, drop_last=self.drop_last, shuffle=self.shuffle)\n', (1417, 1474), False, 'from composer.utils import dist\n'), ((1239, 1279), 'composer.datasets.brats.PytTrain', 'PytTrain', (['x_train', 'y_train', 'oversampling'], {}), '(x_train, y_train, oversampling)\n', (1247, 1279), False, 'from composer.datasets.brats import PytTrain, PytVal, get_data_split\n'), ((1302, 1322), 'composer.datasets.brats.PytVal', 'PytVal', (['x_val', 'y_val'], {}), '(x_val, y_val)\n', (1308, 1322), False, 'from composer.datasets.brats import PytTrain, PytVal, get_data_split\n')]
from quo.getchar import getchar getchar()
[ "quo.getchar.getchar" ]
[((33, 42), 'quo.getchar.getchar', 'getchar', ([], {}), '()\n', (40, 42), False, 'from quo.getchar import getchar\n')]
from setuptools import setup, find_packages setup( name='syntaxerrors', version='0.0.1', description='Report better SyntaxErrors', author='<NAME>', author_email='<EMAIL>', packages=['syntaxerrors'], package_dir={'': 'src'}, include_package_data=True, )
[ "setuptools.setup" ]
[((45, 263), 'setuptools.setup', 'setup', ([], {'name': '"""syntaxerrors"""', 'version': '"""0.0.1"""', 'description': '"""Report better SyntaxErrors"""', 'author': '"""<NAME>"""', 'author_email': '"""<EMAIL>"""', 'packages': "['syntaxerrors']", 'package_dir': "{'': 'src'}", 'include_package_data': '(True)'}), "(name='syntaxerrors', version='0.0.1', description=\n 'Report better SyntaxErrors', author='<NAME>', author_email='<EMAIL>',\n packages=['syntaxerrors'], package_dir={'': 'src'},\n include_package_data=True)\n", (50, 263), False, 'from setuptools import setup, find_packages\n')]
import operator from amino.either import Left, Right from amino import Empty, Just, Maybe, List, Either, _ from amino.test.spec_spec import Spec from amino.list import Lists class EitherSpec(Spec): def map(self) -> None: a = 'a' b = 'b' Right(a).map(_ + b).value.should.equal(a + b) Left(a).map(_ + b).value.should.equal(a) def optional(self) -> None: a = 'a' b = 'b' Right(a).to_maybe.should.just_contain(a) Left(a).to_maybe.should.be.a(Empty) Right(a).to_either(b).should.equal(Right(a)) Left(a).to_either(b).should.equal(Left(a)) def ap2(self) -> None: a = 'a' b = 'b' Right(a).ap2(Right(b), operator.add).should.equal(Right(a + b)) def traverse(self) -> None: a = 'a' Right(Just(a)).sequence(Maybe).should.equal(Just(Right(a))) Left(Just(a)).sequence(Maybe).should.equal(Just(Left(Just(a)))) List(Right(a)).sequence(Either).should.equal(Right(List(a))) List(Right(a), Left(a)).sequence(Either).should.equal(Left(a)) def fold_m(self) -> None: def f(z: int, a: int) -> Either[str, int]: return Right(z + a) if a < 5 else Left('too large') Lists.range(5).fold_m(Right(8))(f).should.contain(18) Lists.range(6).fold_m(Right(8))(f).should.be.left def list_flat_map(self) -> None: (List(Right(1), Left(2), Right(3)).join).should.equal(List(1, 3)) __all__ = ('EitherSpec',)
[ "amino.either.Right", "amino.either.Left", "amino.List", "amino.list.Lists.range", "amino.Just" ]
[((565, 573), 'amino.either.Right', 'Right', (['a'], {}), '(a)\n', (570, 573), False, 'from amino.either import Left, Right\n'), ((617, 624), 'amino.either.Left', 'Left', (['a'], {}), '(a)\n', (621, 624), False, 'from amino.either import Left, Right\n'), ((744, 756), 'amino.either.Right', 'Right', (['(a + b)'], {}), '(a + b)\n', (749, 756), False, 'from amino.either import Left, Right\n'), ((1078, 1085), 'amino.either.Left', 'Left', (['a'], {}), '(a)\n', (1082, 1085), False, 'from amino.either import Left, Right\n'), ((1453, 1463), 'amino.List', 'List', (['(1)', '(3)'], {}), '(1, 3)\n', (1457, 1463), False, 'from amino import Empty, Just, Maybe, List, Either, _\n'), ((864, 872), 'amino.either.Right', 'Right', (['a'], {}), '(a)\n', (869, 872), False, 'from amino.either import Left, Right\n'), ((1006, 1013), 'amino.List', 'List', (['a'], {}), '(a)\n', (1010, 1013), False, 'from amino import Empty, Just, Maybe, List, Either, _\n'), ((1188, 1200), 'amino.either.Right', 'Right', (['(z + a)'], {}), '(z + a)\n', (1193, 1200), False, 'from amino.either import Left, Right\n'), ((1215, 1232), 'amino.either.Left', 'Left', (['"""too large"""'], {}), "('too large')\n", (1219, 1232), False, 'from amino.either import Left, Right\n'), ((936, 943), 'amino.Just', 'Just', (['a'], {}), '(a)\n', (940, 943), False, 'from amino import Empty, Just, Maybe, List, Either, _\n'), ((437, 445), 'amino.either.Right', 'Right', (['a'], {}), '(a)\n', (442, 445), False, 'from amino.either import Left, Right\n'), ((707, 715), 'amino.either.Right', 'Right', (['b'], {}), '(b)\n', (712, 715), False, 'from amino.either import Left, Right\n'), ((486, 493), 'amino.either.Left', 'Left', (['a'], {}), '(a)\n', (490, 493), False, 'from amino.either import Left, Right\n'), ((530, 538), 'amino.either.Right', 'Right', (['a'], {}), '(a)\n', (535, 538), False, 'from amino.either import Left, Right\n'), ((583, 590), 'amino.either.Left', 'Left', (['a'], {}), '(a)\n', (587, 590), False, 'from amino.either import Left, Right\n'), ((694, 702), 'amino.either.Right', 'Right', (['a'], {}), '(a)\n', (699, 702), False, 'from amino.either import Left, Right\n'), ((1263, 1271), 'amino.either.Right', 'Right', (['(8)'], {}), '(8)\n', (1268, 1271), False, 'from amino.either import Left, Right\n'), ((1325, 1333), 'amino.either.Right', 'Right', (['(8)'], {}), '(8)\n', (1330, 1333), False, 'from amino.either import Left, Right\n'), ((1405, 1413), 'amino.either.Right', 'Right', (['(1)'], {}), '(1)\n', (1410, 1413), False, 'from amino.either import Left, Right\n'), ((1415, 1422), 'amino.either.Left', 'Left', (['(2)'], {}), '(2)\n', (1419, 1422), False, 'from amino.either import Left, Right\n'), ((1424, 1432), 'amino.either.Right', 'Right', (['(3)'], {}), '(3)\n', (1429, 1432), False, 'from amino.either import Left, Right\n'), ((269, 277), 'amino.either.Right', 'Right', (['a'], {}), '(a)\n', (274, 277), False, 'from amino.either import Left, Right\n'), ((323, 330), 'amino.either.Left', 'Left', (['a'], {}), '(a)\n', (327, 330), False, 'from amino.either import Left, Right\n'), ((821, 828), 'amino.Just', 'Just', (['a'], {}), '(a)\n', (825, 828), False, 'from amino import Empty, Just, Maybe, List, Either, _\n'), ((888, 895), 'amino.Just', 'Just', (['a'], {}), '(a)\n', (892, 895), False, 'from amino import Empty, Just, Maybe, List, Either, _\n'), ((960, 968), 'amino.either.Right', 'Right', (['a'], {}), '(a)\n', (965, 968), False, 'from amino.either import Left, Right\n'), ((1029, 1037), 'amino.either.Right', 'Right', (['a'], {}), '(a)\n', (1034, 1037), False, 'from amino.either import Left, Right\n'), ((1039, 1046), 'amino.either.Left', 'Left', (['a'], {}), '(a)\n', (1043, 1046), False, 'from amino.either import Left, Right\n'), ((1241, 1255), 'amino.list.Lists.range', 'Lists.range', (['(5)'], {}), '(5)\n', (1252, 1255), False, 'from amino.list import Lists\n'), ((1303, 1317), 'amino.list.Lists.range', 'Lists.range', (['(6)'], {}), '(6)\n', (1314, 1317), False, 'from amino.list import Lists\n')]
#!/usr/bin/env python2 # -*- coding: utf-8 -*- """******************************************************************************* * MIT License * Copyright (c) <NAME> 2021 * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * * Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. ********************************************************************************""" """ * @file explore.py * @author <NAME> * @date 12/14/2021 * @version 1.0 * * @brief Main source file * * @section DESCRIPTION * * file to let the bot explore to the target locations and sending confirmation flag when reached * """ #!/usr/bin/env python #importing Libraries import rospy import math import tf from geometry_msgs.msg import Twist, Point from sensor_msgs.msg import LaserScan from tf.transformations import euler_from_quaternion from enpm808x_inspection_robot.msg import location, flag_array, flag rospy.init_node("move_robot") pub = rospy.Publisher("cmd_vel", Twist, queue_size=1) # create another publisher for location # rospy.init_node('location_node') # loc_pub = rospy.Publisher('location', array, queue_size=1) loc_pub = rospy.Publisher('/flag', flag_array, queue_size=1) rate = rospy.Rate(1) velocity_msg = Twist() rate = rospy.Rate(4) tf_listener = tf.TransformListener() parent_frame = 'odom' child_frame = 'base_footprint' k_h_gain = 1 k_v_gain = 1 distance_to_goal = 0.0 # locations = location() flagged = flag() flagged_arrays = flag_array() flagged.check = "false" try: tf_listener.waitForTransform(parent_frame, child_frame, rospy.Time(), rospy.Duration(1.0)) except (tf.Exception, tf.ConnectivityException, tf.LookupException): rospy.loginfo("Cannot find transform between {p} and {c}".format(p=parent_frame, c=child_frame)) rospy.signal_shutdown("tf Exception") def get_odom_data(): # Get the current pose of the robot from the /odom topic try: (trans, rot) = tf_listener.lookupTransform(parent_frame, child_frame, rospy.Time(0)) rotation = euler_from_quaternion(rot) except (tf.Exception, tf.ConnectivityException, tf.LookupException): rospy.loginfo("TF Exception") return return Point(*trans), rotation[2] def compute_distance(x1, y1, x2, y2): return math.sqrt((x2 - x1)**2 + (y2 - y1)**2) def go_to_goal(goal_x, goal_y): global velocity_msg (position, rotation) = get_odom_data() last_rotation = 0 # locations.loc_x = position.x # locations.loc_y = position.y distance_to_goal = compute_distance(position.x, position.y, goal_x, goal_y) while distance_to_goal > 0.05: (position, rotation) = get_odom_data() x_start = position.x y_start = position.y rospy.loginfo("x = {0}, y = {1}".format(x_start, y_start)) angle_to_goal = math.atan2(goal_y - y_start, goal_x - x_start) if angle_to_goal < -math.pi / 4 or angle_to_goal > math.pi / 4: if 0 > goal_y > y_start: angle_to_goal = -2 * math.pi + angle_to_goal elif 0 <= goal_y < y_start: angle_to_goal = 2 * math.pi + angle_to_goal if last_rotation > math.pi - 0.1 and rotation <= 0: rotation = 2 * math.pi + rotation elif last_rotation < -math.pi + 0.1 and rotation > 0: rotation = -2 * math.pi + rotation velocity_msg.angular.z = k_v_gain * angle_to_goal - rotation distance_to_goal = compute_distance(position.x, position.y, goal_x, goal_y) velocity_msg.linear.x = min(k_h_gain * distance_to_goal, 0.2) if velocity_msg.angular.z > 0: velocity_msg.angular.z = min(velocity_msg.angular.z, 0.6) else: velocity_msg.angular.z = max(velocity_msg.angular.z, -0.6) last_rotation = rotation sub = rospy.Subscriber('scan', LaserScan, sensor_callback) pub = rospy.Publisher("cmd_vel", Twist, queue_size=1) pub.publish(velocity_msg) rate.sleep() velocity_msg.linear.x = 0.0 velocity_msg.angular.z = 0.0 pub.publish(velocity_msg) rate.sleep() def sensor_callback(msg): front = msg.ranges[0] left = msg.ranges[90] right = msg.ranges[270] def read_scan(): rospy.Subscriber("scan", LaserScan, sensor_callback) rospy.spin() # while not rospy.is_shutdown(): # loc_pub.publish(arrays.loc) if __name__ == "__main__": action = "" go_to_goal(-3, -1) flagged.check = 'true' print("The robot has reached the Chiller") print("Commencing the pressure Detection") # print("locations.loc_x = ", locations.loc_x) # print("locations.loc_y = ", locations.loc_y) flagged.check = 'false' go_to_goal(0, 3) print("The robot has reached the Boiler") print("Commencing the pressure Detection") # locations.loc_x = 0.0 # locations.loc_y = 3.0 # send message for boiler go_to_goal(1, 3) print("The robot has reached the Air Handling Units") print("Commencing the pressure Detection") # send message to AHU # arrays.id.insert(0,flag) while not rospy.is_shutdown(): loc_pub.publish(flagged_arrays.id) flagged_arrays.id.insert(0,flagged) rate.sleep() exit()
[ "tf.transformations.euler_from_quaternion", "rospy.Subscriber", "rospy.signal_shutdown", "rospy.is_shutdown", "geometry_msgs.msg.Twist", "rospy.init_node", "enpm808x_inspection_robot.msg.flag_array", "math.sqrt", "rospy.Time", "rospy.Rate", "tf.TransformListener", "rospy.spin", "geometry_msg...
[((2335, 2364), 'rospy.init_node', 'rospy.init_node', (['"""move_robot"""'], {}), "('move_robot')\n", (2350, 2364), False, 'import rospy\n'), ((2372, 2419), 'rospy.Publisher', 'rospy.Publisher', (['"""cmd_vel"""', 'Twist'], {'queue_size': '(1)'}), "('cmd_vel', Twist, queue_size=1)\n", (2387, 2419), False, 'import rospy\n'), ((2569, 2619), 'rospy.Publisher', 'rospy.Publisher', (['"""/flag"""', 'flag_array'], {'queue_size': '(1)'}), "('/flag', flag_array, queue_size=1)\n", (2584, 2619), False, 'import rospy\n'), ((2628, 2641), 'rospy.Rate', 'rospy.Rate', (['(1)'], {}), '(1)\n', (2638, 2641), False, 'import rospy\n'), ((2658, 2665), 'geometry_msgs.msg.Twist', 'Twist', ([], {}), '()\n', (2663, 2665), False, 'from geometry_msgs.msg import Twist, Point\n'), ((2673, 2686), 'rospy.Rate', 'rospy.Rate', (['(4)'], {}), '(4)\n', (2683, 2686), False, 'import rospy\n'), ((2701, 2723), 'tf.TransformListener', 'tf.TransformListener', ([], {}), '()\n', (2721, 2723), False, 'import tf\n'), ((2861, 2867), 'enpm808x_inspection_robot.msg.flag', 'flag', ([], {}), '()\n', (2865, 2867), False, 'from enpm808x_inspection_robot.msg import location, flag_array, flag\n'), ((2885, 2897), 'enpm808x_inspection_robot.msg.flag_array', 'flag_array', ([], {}), '()\n', (2895, 2897), False, 'from enpm808x_inspection_robot.msg import location, flag_array, flag\n'), ((3682, 3724), 'math.sqrt', 'math.sqrt', (['((x2 - x1) ** 2 + (y2 - y1) ** 2)'], {}), '((x2 - x1) ** 2 + (y2 - y1) ** 2)\n', (3691, 3724), False, 'import math\n'), ((5650, 5702), 'rospy.Subscriber', 'rospy.Subscriber', (['"""scan"""', 'LaserScan', 'sensor_callback'], {}), "('scan', LaserScan, sensor_callback)\n", (5666, 5702), False, 'import rospy\n'), ((5707, 5719), 'rospy.spin', 'rospy.spin', ([], {}), '()\n', (5717, 5719), False, 'import rospy\n'), ((2989, 3001), 'rospy.Time', 'rospy.Time', ([], {}), '()\n', (2999, 3001), False, 'import rospy\n'), ((3003, 3022), 'rospy.Duration', 'rospy.Duration', (['(1.0)'], {}), '(1.0)\n', (3017, 3022), False, 'import rospy\n'), ((3198, 3235), 'rospy.signal_shutdown', 'rospy.signal_shutdown', (['"""tf Exception"""'], {}), "('tf Exception')\n", (3219, 3235), False, 'import rospy\n'), ((3441, 3467), 'tf.transformations.euler_from_quaternion', 'euler_from_quaternion', (['rot'], {}), '(rot)\n', (3462, 3467), False, 'from tf.transformations import euler_from_quaternion\n'), ((3605, 3618), 'geometry_msgs.msg.Point', 'Point', (['*trans'], {}), '(*trans)\n', (3610, 3618), False, 'from geometry_msgs.msg import Twist, Point\n'), ((4229, 4275), 'math.atan2', 'math.atan2', (['(goal_y - y_start)', '(goal_x - x_start)'], {}), '(goal_y - y_start, goal_x - x_start)\n', (4239, 4275), False, 'import math\n'), ((5229, 5281), 'rospy.Subscriber', 'rospy.Subscriber', (['"""scan"""', 'LaserScan', 'sensor_callback'], {}), "('scan', LaserScan, sensor_callback)\n", (5245, 5281), False, 'import rospy\n'), ((5296, 5343), 'rospy.Publisher', 'rospy.Publisher', (['"""cmd_vel"""', 'Twist'], {'queue_size': '(1)'}), "('cmd_vel', Twist, queue_size=1)\n", (5311, 5343), False, 'import rospy\n'), ((6524, 6543), 'rospy.is_shutdown', 'rospy.is_shutdown', ([], {}), '()\n', (6541, 6543), False, 'import rospy\n'), ((3407, 3420), 'rospy.Time', 'rospy.Time', (['(0)'], {}), '(0)\n', (3417, 3420), False, 'import rospy\n'), ((3549, 3578), 'rospy.loginfo', 'rospy.loginfo', (['"""TF Exception"""'], {}), "('TF Exception')\n", (3562, 3578), False, 'import rospy\n')]
import pandas as pd class ProcessCSV: """ A general class to read in and process a csv format file using pandas. """ def __init__(self, filename, delim=',', header=None, usecols=None, dtype=None, ignore=False, *args): self._filename = filename self._args = args self._df = self._readFile(delim=delim, header=header, usecols=usecols, dtype=dtype, ignore=ignore) def _readFile(self, delim=',', header=None, usecols=None, dtype=None, ignore=False): df = pd.read_csv(self._filename, sep=delim, header=header, usecols=usecols, dtype=dtype) if ignore: df.dropna(how="all", inplace=True) return df.fillna(0) def getCoordinates(self): return self._df[['map X', 'map Y', 'map Z']] def getGene(self): return self._df.iloc[:, 8:] def getID(self): return self._df['Sample Name']
[ "pandas.read_csv" ]
[((506, 593), 'pandas.read_csv', 'pd.read_csv', (['self._filename'], {'sep': 'delim', 'header': 'header', 'usecols': 'usecols', 'dtype': 'dtype'}), '(self._filename, sep=delim, header=header, usecols=usecols,\n dtype=dtype)\n', (517, 593), True, 'import pandas as pd\n')]
from functools import lru_cache from itertools import product from pathlib import Path from typing import Optional, List, Tuple from pydantic import validate_arguments import pyhmmer import requests as r from yarl import URL from sadie.typing import Species, Chain, Source class G3: """API Wrapper with OpenAPI found here https://g3.jordanrwillis.com/docs""" # TODO: most likely make this an import data_folder = Path(__file__).parent.parent / "data" segments = {"V", "D", "J"} chains = {"H", "K", "L"} def __init__(self): self.base_url = URL("https://g3.jordanrwillis.com/api/v1") self.not_usable_species = [ "pig", "cow", "cat", # missing L "alpaca", # missing L and K "rhesus", # TODO: breaks tests; fix and fall back on numbering for now "dog", # TODO: viable but does not match. Need to check if diff species of dog from G3 ] self.alphabet = pyhmmer.easel.Alphabet.amino() self.builder = pyhmmer.plan7.Builder(self.alphabet, architecture="hand") self.background = pyhmmer.plan7.Background(self.alphabet) @property @lru_cache(maxsize=1) def sources(self): resp = r.get(self.base_url) resp.raise_for_status() return resp.json()["components"]["schemas"]["SourceName"]["enum"] @property @lru_cache(maxsize=1) def species(self): resp = r.get(self.base_url) resp.raise_for_status() species = resp.json()["components"]["schemas"]["CommonName"]["enum"] return [single_species for single_species in species if single_species not in self.not_usable_species] @lru_cache(maxsize=None) @validate_arguments def __get_gene_resp( self, source: Source = "imgt", species: Species = "human", segment: str = "V", limit: Optional[int] = None, ) -> str: segment = segment.upper() if segment not in self.segments: raise ValueError(f"{segment} is not a valid segment from {self.segments}") params = { "source": source, "common": species, "segment": segment, "limit": limit if limit else "-1", } resp = r.get(self.base_url / "genes", params=params) resp.raise_for_status() return resp @validate_arguments def get_gene( self, source: Source = "imgt", species: Species = "human", chain: Chain = "H", segment: str = "V", limit: Optional[int] = None, ) -> str: resp = self.__get_gene_resp(source=source, species=species, segment=segment, limit=limit) return [x for x in resp.json() if x["gene"][2].lower() == chain.lower()] def get_stockholm_pairs( self, source: Source = "imgt", chain: Chain = "H", species: Species = "human", limit: Optional[int] = None, ) -> List[Tuple[str, str]]: sub_v = self.get_gene(source=source, species=species, chain=chain, segment="V", limit=limit) sub_j = self.get_gene(source=source, species=species, chain=chain, segment="J", limit=limit) stockholm_pairs = [] for merge in product(sub_v, sub_j): v_seg = merge[0] j_seg = merge[1] if v_seg["receptor"] not in ["IG"]: continue functional = v_seg["imgt"]["imgt_functional"] v_part = v_seg["imgt"]["sequence_gapped_aa"].replace(".", "-")[:108].ljust(108).replace(" ", "-") # if v_part[0] == "-": # continue cdr3_part = j_seg["imgt"]["cdr3_aa"] fwr4_part = j_seg["imgt"]["fwr4_aa"] v_name = v_seg["gene"] j_name = j_seg["gene"] name = f"{species}_{v_name}_{j_name}" # why? if functional != "F": continue # H rules if chain.strip().lower() in "H": if len(cdr3_part[-3:] + fwr4_part) == 13: fwr4_part += "-" # K rules if chain.strip().lower() in "k": if len(cdr3_part[-3:] + fwr4_part) in [12, 13]: fwr4_part += "-" # # L rules if chain.strip().lower() == "l": if len(cdr3_part[-3:] + fwr4_part) == 12: fwr4_part += "-" # todo: alt fwr4_part based on it's size and who's askin multiplier = 128 - (len(v_part) + len(cdr3_part[-3:] + fwr4_part)) align = v_part + "-" * multiplier + cdr3_part[-3:] + fwr4_part # sanity check if chains rules are working assert len(align) == 128 stockholm_pairs.append((name, align)) return stockholm_pairs # def get_msa( # self, # source: Source = "imgt", # species: Species = "human", # chain: Chain = "H", # limit: Optional[int] = None, # ) -> str: # stockholm_pairs = self.get_stockholm_pairs(source=source, chain=chain, species=species, limit=limit) # sequences = [] # for name, align in stockholm_pairs: # sequence = pyhmmer.easel.TextSequence(name=name.encode(), sequence=align) # sequences.append(sequence) # if not sequences: # return None # return pyhmmer.easel.TextMSA(name=f"{species}_{chain}".encode(), sequences=sequences).digitize(self.alphabet) @lru_cache(maxsize=None) def build_stockholm( self, source: Source = "imgt", species: Species = "human", chain: Chain = "H", limit: Optional[int] = None, ) -> Path: """ Get a stockholm file in string format for the given species and chain. Parameters ---------- source : str, optional Source of gene data, by default "imgt" options: 'imgt' or 'custom' species : str, optional species selected from avaliabe, by default "human" chain : str, optional chain for seq, by default "H" options: 'H', 'k', 'l' -> heavy, kappa light Returns ------- str stockholm file in string format """ sto_path = self.data_folder / f"stockholms/{species}_{chain}.sto" sto_pairs = self.get_stockholm_pairs(source=source, chain=chain, species=species, limit=limit) if not sto_pairs: return head = f"# STOCKHOLM 1.0\n#=GF ID {species}_{chain}\n" body = "\n".join([f"{name}\t{ali}" for name, ali in sto_pairs]) tail = "\n#=GC RF" + "\t" + "x" * 128 + "\n//\n" # TODO: hand arch needs a parsed file -- will be refactored to handle digital directly with open(sto_path, "w") as outfile: outfile.write(head + body + tail) return sto_path @lru_cache(maxsize=None) def build_hmm( self, source: Source = "imgt", species: Species = "human", chain: Chain = "H", limit: Optional[int] = None, ) -> Path: sto_path = self.build_stockholm(source=source, chain=chain, species=species, limit=limit) if not sto_path: return hmm_path = self.data_folder / f"hmms/{species}_{chain}.hmm" with pyhmmer.easel.MSAFile(sto_path, digital=True, alphabet=self.alphabet, format="stockholm") as msa_file: msa = next(msa_file) hmm, _, _ = self.builder.build_msa(msa, self.background) with open(hmm_path, "wb") as output_file: hmm.write(output_file) return hmm_path @lru_cache(maxsize=None) def get_hmm( self, source: Source = "imgt", species: Species = "human", chain: Chain = "H", limit: Optional[int] = None, prioritize_cached_hmm: bool = False, ): hmm_path = self.data_folder / f"hmms/{species}_{chain}.hmm" if prioritize_cached_hmm is True: if hmm_path.is_file() is False: hmm_path = self.build_hmm(source=source, chain=chain, species=species, limit=limit) else: hmm_path = self.build_hmm(source=source, chain=chain, species=species, limit=limit) if not hmm_path: return with pyhmmer.plan7.HMMFile(hmm_path) as hmm_file: hmm = next(hmm_file) return hmm
[ "pyhmmer.plan7.Background", "pyhmmer.easel.MSAFile", "pyhmmer.easel.Alphabet.amino", "pyhmmer.plan7.Builder", "pathlib.Path", "itertools.product", "requests.get", "pyhmmer.plan7.HMMFile", "functools.lru_cache", "yarl.URL" ]
[((1183, 1203), 'functools.lru_cache', 'lru_cache', ([], {'maxsize': '(1)'}), '(maxsize=1)\n', (1192, 1203), False, 'from functools import lru_cache\n'), ((1389, 1409), 'functools.lru_cache', 'lru_cache', ([], {'maxsize': '(1)'}), '(maxsize=1)\n', (1398, 1409), False, 'from functools import lru_cache\n'), ((1695, 1718), 'functools.lru_cache', 'lru_cache', ([], {'maxsize': 'None'}), '(maxsize=None)\n', (1704, 1718), False, 'from functools import lru_cache\n'), ((5518, 5541), 'functools.lru_cache', 'lru_cache', ([], {'maxsize': 'None'}), '(maxsize=None)\n', (5527, 5541), False, 'from functools import lru_cache\n'), ((6940, 6963), 'functools.lru_cache', 'lru_cache', ([], {'maxsize': 'None'}), '(maxsize=None)\n', (6949, 6963), False, 'from functools import lru_cache\n'), ((7693, 7716), 'functools.lru_cache', 'lru_cache', ([], {'maxsize': 'None'}), '(maxsize=None)\n', (7702, 7716), False, 'from functools import lru_cache\n'), ((577, 619), 'yarl.URL', 'URL', (['"""https://g3.jordanrwillis.com/api/v1"""'], {}), "('https://g3.jordanrwillis.com/api/v1')\n", (580, 619), False, 'from yarl import URL\n'), ((985, 1015), 'pyhmmer.easel.Alphabet.amino', 'pyhmmer.easel.Alphabet.amino', ([], {}), '()\n', (1013, 1015), False, 'import pyhmmer\n'), ((1039, 1096), 'pyhmmer.plan7.Builder', 'pyhmmer.plan7.Builder', (['self.alphabet'], {'architecture': '"""hand"""'}), "(self.alphabet, architecture='hand')\n", (1060, 1096), False, 'import pyhmmer\n'), ((1123, 1162), 'pyhmmer.plan7.Background', 'pyhmmer.plan7.Background', (['self.alphabet'], {}), '(self.alphabet)\n', (1147, 1162), False, 'import pyhmmer\n'), ((1242, 1262), 'requests.get', 'r.get', (['self.base_url'], {}), '(self.base_url)\n', (1247, 1262), True, 'import requests as r\n'), ((1448, 1468), 'requests.get', 'r.get', (['self.base_url'], {}), '(self.base_url)\n', (1453, 1468), True, 'import requests as r\n'), ((2276, 2321), 'requests.get', 'r.get', (["(self.base_url / 'genes')"], {'params': 'params'}), "(self.base_url / 'genes', params=params)\n", (2281, 2321), True, 'import requests as r\n'), ((3250, 3271), 'itertools.product', 'product', (['sub_v', 'sub_j'], {}), '(sub_v, sub_j)\n', (3257, 3271), False, 'from itertools import product\n'), ((7371, 7464), 'pyhmmer.easel.MSAFile', 'pyhmmer.easel.MSAFile', (['sto_path'], {'digital': '(True)', 'alphabet': 'self.alphabet', 'format': '"""stockholm"""'}), "(sto_path, digital=True, alphabet=self.alphabet,\n format='stockholm')\n", (7392, 7464), False, 'import pyhmmer\n'), ((8358, 8389), 'pyhmmer.plan7.HMMFile', 'pyhmmer.plan7.HMMFile', (['hmm_path'], {}), '(hmm_path)\n', (8379, 8389), False, 'import pyhmmer\n'), ((430, 444), 'pathlib.Path', 'Path', (['__file__'], {}), '(__file__)\n', (434, 444), False, 'from pathlib import Path\n')]
# coding: utf-8 from nlp_components.content_items_processors import process_list_content_sentences from nlp_components.content_items_processors import process_list_content_sentences_real import dals.os_io.io_wrapper as dal import json # NO DRY!! def read_utf_txt_file(fname): sets = dal.get_utf8_template() sets['name'] = fname return dal.file2list(sets) def mapper(job): """ [node_name, index_word, [count_sent, summ_sent_len], url, lang]""" url_tmp_file = job[1] node_name = job[0] # Получем текст file_content = read_utf_txt_file(url_tmp_file) metadata = file_content[0] settings = json.loads(metadata) url = settings['url'] lang = settings['lang'] list_content_items = file_content[1:] # Теперь можно составлять индекс index, (count_sents, summ_sents_len) = process_list_content_sentences( list_content_items, lang) parallel_pkg = (node_name, index, [count_sents, summ_sents_len], (url, lang)) return parallel_pkg def mapper_real(job): """ [node_name, .., .., .., ]""" url = job[0] text_extractor = job[1] tokenizer = job[2] node_name = job[3] # Получем текст text = text_extractor(url) # Токенизация lits_content_items = [] if tokenizer: lits_content_items = tokenizer(text) else: lits_content_items = [text] # Теперь можно составлять индекс index, (count_sents, summ_sents_len) = \ process_list_content_sentences_real( lits_content_items, tokenizer) parallel_pkg = (node_name, index, [count_sents, summ_sents_len], url) return parallel_pkg
[ "json.loads", "dals.os_io.io_wrapper.file2list", "nlp_components.content_items_processors.process_list_content_sentences_real", "dals.os_io.io_wrapper.get_utf8_template", "nlp_components.content_items_processors.process_list_content_sentences" ]
[((290, 313), 'dals.os_io.io_wrapper.get_utf8_template', 'dal.get_utf8_template', ([], {}), '()\n', (311, 313), True, 'import dals.os_io.io_wrapper as dal\n'), ((350, 369), 'dals.os_io.io_wrapper.file2list', 'dal.file2list', (['sets'], {}), '(sets)\n', (363, 369), True, 'import dals.os_io.io_wrapper as dal\n'), ((631, 651), 'json.loads', 'json.loads', (['metadata'], {}), '(metadata)\n', (641, 651), False, 'import json\n'), ((833, 889), 'nlp_components.content_items_processors.process_list_content_sentences', 'process_list_content_sentences', (['list_content_items', 'lang'], {}), '(list_content_items, lang)\n', (863, 889), False, 'from nlp_components.content_items_processors import process_list_content_sentences\n'), ((1476, 1542), 'nlp_components.content_items_processors.process_list_content_sentences_real', 'process_list_content_sentences_real', (['lits_content_items', 'tokenizer'], {}), '(lits_content_items, tokenizer)\n', (1511, 1542), False, 'from nlp_components.content_items_processors import process_list_content_sentences_real\n')]
# -*- cpy-indent-level: 4; indent-tabs-mode: nil -*- # ex: set expandtab softtabstop=4 shiftwidth=4: # # Copyright (C) 2008,2009,2010,2011,2012,2013,2014,2015,2017 Contributor # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """List formatter.""" from operator import attrgetter from six import string_types from sqlalchemy.orm.collections import InstrumentedList from sqlalchemy.orm.query import Query from sqlalchemy.ext.associationproxy import _AssociationList from aquilon.worker.formats.formatters import ObjectFormatter class ListFormatter(ObjectFormatter): def format_raw(self, result, indent="", embedded=True, indirect_attrs=True): if hasattr(self, "template_raw"): return ObjectFormatter.format_raw(self, result, indent, embedded=embedded, indirect_attrs=indirect_attrs) return "\n".join(self.redirect_raw(item, indent, embedded=embedded, indirect_attrs=indirect_attrs) for item in result) def format_csv(self, result, writer): for item in result: self.redirect_csv(item, writer) def format_djb(self, result): return "\n".join(self.redirect_djb(item) for item in result) def format_proto(self, result, container, embedded=True, indirect_attrs=True): for item in result: skeleton = container.add() ObjectFormatter.redirect_proto(item, skeleton, embedded=embedded, indirect_attrs=indirect_attrs) ObjectFormatter.handlers[list] = ListFormatter() ObjectFormatter.handlers[Query] = ListFormatter() ObjectFormatter.handlers[InstrumentedList] = ListFormatter() ObjectFormatter.handlers[_AssociationList] = ListFormatter() class StringList(list): pass class StringListFormatter(ListFormatter): """ Format a list of object as strings, regardless of type """ def format_raw(self, objects, indent="", embedded=True, indirect_attrs=True): return "\n".join(indent + str(obj) for obj in objects) def format_csv(self, objects, writer): for obj in objects: writer.writerow((str(obj),)) ObjectFormatter.handlers[StringList] = StringListFormatter() class StringAttributeList(list): def __init__(self, items, attr): if isinstance(attr, string_types): self.getter = attrgetter(attr) else: self.getter = attr super(StringAttributeList, self).__init__(items) class StringAttributeListFormatter(ListFormatter): """ Format a single attribute of every object as a string """ def format_raw(self, objects, indent="", embedded=True, indirect_attrs=True): return "\n".join(indent + str(objects.getter(obj)) for obj in objects) def format_csv(self, objects, writer): for obj in objects: writer.writerow((str(objects.getter(obj)),)) def format_proto(self, objects, container, embedded=True, indirect_attrs=True): # This method always populates the first field of the protobuf message, # regardless of how that field is called. field_name = None for obj in objects: msg = container.add() if not field_name: field_name = msg.DESCRIPTOR.fields[0].name setattr(msg, field_name, str(objects.getter(obj))) # TODO: if obj is really the full DB object rather than just a # string, and it has other attributes already loaded, then we could # add those attributes to the protobuf message "for free". Let's see # if a usecase comes up. ObjectFormatter.handlers[StringAttributeList] = StringAttributeListFormatter()
[ "operator.attrgetter", "aquilon.worker.formats.formatters.ObjectFormatter.redirect_proto", "aquilon.worker.formats.formatters.ObjectFormatter.format_raw" ]
[((1228, 1330), 'aquilon.worker.formats.formatters.ObjectFormatter.format_raw', 'ObjectFormatter.format_raw', (['self', 'result', 'indent'], {'embedded': 'embedded', 'indirect_attrs': 'indirect_attrs'}), '(self, result, indent, embedded=embedded,\n indirect_attrs=indirect_attrs)\n', (1254, 1330), False, 'from aquilon.worker.formats.formatters import ObjectFormatter\n'), ((1996, 2096), 'aquilon.worker.formats.formatters.ObjectFormatter.redirect_proto', 'ObjectFormatter.redirect_proto', (['item', 'skeleton'], {'embedded': 'embedded', 'indirect_attrs': 'indirect_attrs'}), '(item, skeleton, embedded=embedded,\n indirect_attrs=indirect_attrs)\n', (2026, 2096), False, 'from aquilon.worker.formats.formatters import ObjectFormatter\n'), ((2966, 2982), 'operator.attrgetter', 'attrgetter', (['attr'], {}), '(attr)\n', (2976, 2982), False, 'from operator import attrgetter\n')]