content
stringlengths
0
894k
type
stringclasses
2 values
from bokeh.io import output_file, show from bokeh.models import ColumnDataSource, GMapOptions from bokeh.plotting import gmap output_file("gmap.html") map_options = GMapOptions(lat=30.2861, lng=-97.7394, map_type="roadmap", zoom=11) # For GMaps to function, Google requires you obtain and enable an API key: # # https://developers.google.com/maps/documentation/javascript/get-api-key # # Replace the value below with your personal API key: p = gmap("GOOGLE_API_KEY", map_options, title="Austin") source = ColumnDataSource( data=dict(lat=[ 30.29, 30.20, 30.29], lon=[-97.70, -97.74, -97.78]) ) p.circle(x="lon", y="lat", size=15, fill_color="blue", fill_alpha=0.8, source=source) show(p)
python
""" Common utility functions for NPP/SNPP """ import os import numpy as np from pathlib import Path # Country enumerations EN = "en" WA = "wa" SC = "sc" NI = "ni" # Aggregations EW = [EN, WA] GB = [EN, WA, SC] UK = [EN, WA, SC, NI] # ONS country codes CODES = { EN: "E92000001", WA: "W92000004", SC: "S92000003", NI: "N92000002" } def country(codes): """ Returns country from ONS LAD code or 2-letter country code (above) - simply looks at first letter, case insensitive """ if isinstance(codes, str): codes = [codes] lookup = {"E": EN, "W": WA, "S": SC, "N": NI} # return lookup[code[0].upper()] raw = set([code[0] in lookup and lookup[code[0]] for code in codes]) raw.discard(False) return sorted(list(raw)) # set([code[0] in lookup and lookup[code[0]].upper() for code in codes]).discard(False)) def split_by_country(codes): """ Splits a single array of LAD codes into separate arrays for each country """ return {EN: [code for code in codes if code.startswith("E")], WA: [code for code in codes if code.startswith("W")], SC: [code for code in codes if code.startswith("S")], NI: [code for code in codes if code.startswith("N")]} def default_cache_dir(): """ Default cache dir location, ensures the path exists (failing if it cannot create) This *should* work on all platforms """ cache_dir = str(Path.home() / ".ukpopulation/cache") if not os.path.exists(cache_dir): os.makedirs(cache_dir) return cache_dir def check_and_invert(categories): """ Takes a list of categories to aggregrate and removes them from all possible categories, creating a list of categories to preserve that can be used by groupby Will thow ValueError if one of supplied categories is not one of the column names below """ inverted = ['C_AGE', 'GENDER', 'GEOGRAPHY_CODE', 'PROJECTED_YEAR_NAME'] # first ensure list if isinstance(categories, str): categories = [categories] if "PROJECTED_YEAR_NAME" in categories: raise ValueError("It makes no sense to aggregate data over PROJECTED_YEAR_NAME") for cat in categories: inverted.remove(cat) return inverted def filter_by_age(data, age_range): return data[data.C_AGE.isin(age_range)] def aggregate(detail, categories): """ Aggregate OBS_VALUE over categories """ return detail.groupby(check_and_invert(categories))["OBS_VALUE"].sum().reset_index() def split_range(full_range, cutoff): """ Split a range of values into those within (<=) cutoff and those without (>) Returns a tuple containing 2 lists (which can be empty) """ if np.isscalar(full_range): full_range = [full_range] return ([x for x in full_range if x <= cutoff], [x for x in full_range if x > cutoff]) def trim_range(input_range, minval, maxval): """ Removes values < minval or > maxval from input_range If input_range is None, defaults to the inclusive range: range(minval, maxval + 1) """ if input_range is None: return range(minval, maxval + 1) if np.isscalar(input_range): input_range = [input_range] return [x for x in input_range if x >= minval and x <= maxval] def read_cell_range(worksheet, topleft, bottomright): data_rows = [] for row in worksheet[topleft:bottomright]: data_cols = [] for cell in row: data_cols.append(cell.value) data_rows.append(data_cols) return np.array(data_rows) def integerise(series): """ This duplicates functionality that exists in humanleague, rather than intorducing a package dependency solely for this function """ sumf = sum(series) sumi = round(sumf) # rescale series to nearest-integer sum series = series * sumi / sumf # get integer and fractional parts seriesi = np.floor(series) seriesf = series - seriesi # shortfall is integer sum less sum of integer values shortfall = int(sumi - sum(seriesi)) # select the n largest fractional parts where n=shortfall idx = np.argpartition(seriesf, -shortfall)[-shortfall:] # increment the values at these indices inc = np.zeros(len(series)) np.put(inc, idx, 1) return seriesi + inc
python
from __future__ import print_function from utensor_cgen.ir import uTensorGraph from utensor_cgen.ir.utils import graph_check from utensor_cgen.transformer import CMSIS_NN_Transformer def test_cmsisnn_trnasformer(fusion_graph_tuple): (ugraph, ugraph1) = fusion_graph_tuple transformer = CMSIS_NN_Transformer() test_graph = transformer.transform(ugraph1) graph_check(test_graph) print('cmsisnn test topo order: %s' % test_graph.topo_order)
python
import requests import json import execjs # 必须,需要先用pip 安装,用来执行js脚本 from urllib.parse import quote # 用来判断是否需要打印日志 debug = True class Py4Js: def __init__(self): self.ctx = execjs.compile(""" function TL(a) { var k = ""; var b = 406644; var b1 = 3293161072; var jd = "."; var $b = "+-a^+6"; var Zb = "+-3^+b+-f"; for (var e = [], f = 0, g = 0; g < a.length; g++) { var m = a.charCodeAt(g); 128 > m ? e[f++] = m : (2048 > m ? e[f++] = m >> 6 | 192 : (55296 == (m & 64512) && g + 1 < a.length && 56320 == (a.charCodeAt(g + 1) & 64512) ? (m = 65536 + ((m & 1023) << 10) + (a.charCodeAt(++g) & 1023), e[f++] = m >> 18 | 240, e[f++] = m >> 12 & 63 | 128) : e[f++] = m >> 12 | 224, e[f++] = m >> 6 & 63 | 128), e[f++] = m & 63 | 128) } a = b; for (f = 0; f < e.length; f++) a += e[f], a = RL(a, $b); a = RL(a, Zb); a ^= b1 || 0; 0 > a && (a = (a & 2147483647) + 2147483648); a %= 1E6; return a.toString() + jd + (a ^ b) }; function RL(a, b) { var t = "a"; var Yb = "+"; for (var c = 0; c < b.length - 2; c += 3) { var d = b.charAt(c + 2), d = d >= t ? d.charCodeAt(0) - 87 : Number(d), d = b.charAt(c + 1) == Yb ? a >>> d: a << d; a = b.charAt(c) == Yb ? a + d & 4294967295 : a ^ d } return a } """) def get_tk(self, text): return self.ctx.call("TL", text) def build_url(text, tk, tl='zh-CN'): """ 需要用转URLEncoder :param text: :param tk: :param tl: :return: """ return 'https://translate.google.cn/translate_a/single?client=webapp&sl=auto&tl=' + tl + '&hl=zh-CN&dt=at&dt=bd&dt=ex&dt=ld&dt=md&dt=qca&dt=rw&dt=rm&dt=ss&dt=t&source=btn&ssel=0&tsel=0&kc=0&tk=' \ + str(tk) + '&q=' + quote(text, encoding='utf-8') def translate(js, text, tl='zh-CN'): """ tl为要翻译的语言 de:德语 ja:日语 sv:瑞典语 nl:荷兰语 ar:阿拉伯语 ko:韩语 pt:葡萄牙语 zh-CN:中文简体 zh-TW:中文繁体 """ header = { 'authority': 'translate.google.cn', 'method': 'GET', 'path': '', 'scheme': 'https', 'accept': '*/*', 'accept-encoding': 'gzip, deflate, br', 'accept-language': 'zh-CN,zh;q=0.9,ja;q=0.8', # 'cookie': '_ga=GA1.3.110668007.1547438795; _gid=GA1.3.791931751.1548053917; 1P_JAR=2019-1-23-1; NID=156=biJbQQ3j2gPAJVBfdgBjWHjpC5m9vPqwJ6n6gxTvY8n1eyM8LY5tkYDRsYvacEnWNtMh3ux0-lUJr439QFquSoqEIByw7al6n_yrHqhFNnb5fKyIWMewmqoOJ2fyNaZWrCwl7MA8P_qqPDM5uRIm9SAc5ybSGZijsjalN8YDkxQ', 'cookie':'_ga=GA1.3.110668007.1547438795; _gid=GA1.3.1522575542.1548327032; 1P_JAR=2019-1-24-10; NID=156=ELGmtJHel1YG9Q3RxRI4HTgAc3l1n7Y6PAxGwvecTJDJ2ScgW2p-CXdvh88XFb9dTbYEBkoayWb-2vjJbB-Rhf6auRj-M-2QRUKdZG04lt7ybh8GgffGtepoA4oPN9OO9TeAoWDY0HJHDWCUwCpYzlaQK-gKCh5aVC4HVMeoppI', # 'cookie': '', 'user-agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.108 Safari/537.36', 'x-client-data': 'CKi1yQEIhrbJAQijtskBCMG2yQEIqZ3KAQioo8oBCL+nygEI7KfKAQjiqMoBGPmlygE=' } url = build_url(text, js.get_tk(text), tl) res = [] try: r = requests.get(url, headers=header) result = json.loads(r.text) r.encoding = "UTF-8" if debug: print(r.url) print(r.headers) print(r.request.headers) print(result) res = result[0] if res is None: if result[7] is not None: # 如果我们文本输错,提示你是不是要找xxx的话,那么重新把xxx正确的翻译之后返回 try: correct_text = result[7][0].replace('<b><i>', ' ').replace('</i></b>', '') if debug: print(correct_text) correct_url = build_url(correct_text, js.get_tk(correct_text), tl) correct_response = requests.get(correct_url) correct_result = json.loads(correct_response.text) res = correct_result[0] except Exception as e: if debug: print(e) res = [] except Exception as e: res = [] if debug: print(url) print("翻译" + text + "失败") print("错误信息:") print(e) finally: return res def get_translate(word, tl): js = Py4Js() translate_result = translate(js, word, tl) if debug: print("word== %s, tl== %s" % (word, tl)) print(translate_result) return translate_result if __name__ == '__main__': debug = True translate_text = '3.Hear voice prompt \"start configuration mode\". click \"reset successfully\" button\n' results = get_translate(translate_text, 'cs') translate_result = "" if "." in translate_text or "?" in translate_text: for result in results: translate_result += result[0] else: result_translate = results[0] if debug: print("translate_result:" + translate_result)
python
import torch import torch.nn as nn import torch.optim as optim import numpy as np import matplotlib.pylab as plt import random from celluloid import Camera class Energy(nn.Module): def __init__(self): super(Energy, self).__init__() self.sigma = nn.Parameter(torch.tensor([0.5])) self.mu = nn.Parameter(torch.tensor([10.0])) def forward(self, x): return self.sigma*(x - self.mu)*(x - self.mu) def energy_ans(x): return x*x if __name__=='__main__': num_epochs = 300 num_steps = 50 Ntrain = 100 mem_max = 20 batch_size = 16 x_train = np.random.randn(Ntrain) mem = [torch.rand(1) for i in range(batch_size)] energy = Energy() energy_optimizer = optim.Adam(energy.parameters(), lr=0.1) f = plt.figure(figsize=(12,6)) camera = Camera(f) ax = f.add_subplot(111) for i in range(num_epochs): x_batch = random.choices(mem, k=batch_size) x_batch = torch.stack(x_batch, dim=0) x_batch.requires_grad_() energy.eval() energy.mu.requires_grad = False energy.sigma.requires_grad = False langevin_optimizer = optim.Adam([x_batch], lr=0.1) x_traces = [[] for i in range(batch_size)] e_traces = [[] for i in range(batch_size)] for j in range(num_steps): langevin_optimizer.zero_grad() E = energy(x_batch) L = E.mean() L.backward() x_batch.grad += torch.randn(batch_size,1)*0.1 langevin_optimizer.step() for k in range(batch_size): x_traces[k].append(x_batch[k].item()) e_traces[k].append(E[k].item()) x_batch = x_batch.detach() for j in range(batch_size): mem.append(x_batch[j].clone()) if len(mem)>mem_max: mem.pop(0) # plt.cla() for k in range(batch_size): plt.plot(x_traces[k], e_traces[k], 'r-.') plt.scatter(x_batch.numpy(), energy(x_batch).detach().numpy(), marker='x', c='g') plt.scatter(x_train, energy_ans(x_train), marker='o', c='b') # plt.draw() # plt.pause(.01) energy.train() energy.mu.requires_grad = True energy.sigma.requires_grad = True energy_optimizer.zero_grad() train_batch = torch.from_numpy(np.random.choice(x_train, batch_size)) L = (energy(train_batch) - energy(x_batch)).mean() L.backward() energy_optimizer.step() print(L.item(), energy.mu.item(), energy.sigma.item()) camera.snap() animation = camera.animate() animation.save(f'test1d.mp4')
python
import scrapy from celery import Celery from scrapy.settings import Settings from scrapy.spiders import Spider from scrapyscript import Job, Processor, ScrapyScriptException from spiders import ItemSpider, TitleSpider app = Celery("hello", broker="amqp://guest@localhost//") @app.task def celery_job(url): job = Job(TitleSpider, url=url) return Processor().run(job) @app.task def celery_job_with_custom_settings(url, settings): job = Job(ItemSpider, url=url) return Processor(settings=settings).run(job) class TestScrapyScriptCelery: def test_celery_job(self): # for unit testing, call celery synchronously task = celery_job.s("https://www.python.org").apply() assert len(task.result[0]["data"]) > 0 def test_celery_job_with_settings(self): settings = Settings() settings["BOT_NAME"] = "alpha" task = celery_job_with_custom_settings.s( "https://www.python.org", settings ).apply() print(task.result[0]) assert task.result[0]["bot"] == "alpha"
python
from copy import copy from Cat.utils.collections_ import ChainedList from model.commands.argumentTypes import * from model.commands.command import CommandSchema, KeywordSchema, ArgumentSchema, TERMINAL, COMMANDS_ROOT, SwitchSchema from model.data.mcVersions import MCVersion def fillCommandsFor1_17(version: MCVersion) -> None: _BASIC_COMMAND_INFO_LIST = [ CommandSchema( name='?', description='An alias of /help. Provides help for commands.', opLevel=0, ), CommandSchema( name='advancement', description='Gives, removes, or checks player advancements.', opLevel=2, ), CommandSchema( name='attribute', description='Queries, adds, removes or sets an entity attribute.', opLevel=2, ), CommandSchema( name='ban', description='Adds player to banlist.', opLevel=3, availableInSP=False ), CommandSchema( name='ban-ip', description='Adds IP address to banlist.', opLevel=3, availableInSP=False ), CommandSchema( name='banlist', description='Displays banlist.', opLevel=3, availableInSP=False ), CommandSchema( name='bossbar', description='Creates and modifies bossbars.', opLevel=2, ), CommandSchema( name='clear', description='Clears items from player inventory.', opLevel=2, ), CommandSchema( name='clone', description='Copies blocks from one place to another.', opLevel=2, ), CommandSchema( name='data', description='Gets, merges, modifies and removes block entity and entity NBT data.', opLevel=2, ), CommandSchema( name='datapack', description='Controls loaded data packs.', opLevel=2, ), CommandSchema( name='debug', description='Starts or stops a debugging session.', opLevel=3, ), CommandSchema( name='defaultgamemode', description='Sets the default game mode.', opLevel=2, ), CommandSchema( name='deop', description='Revokes operator status from a player.', opLevel=3, availableInSP=False ), CommandSchema( name='difficulty', description='Sets the difficulty level.', opLevel=2, ), CommandSchema( name='effect', description='Add or remove status effects.', opLevel=2, ), CommandSchema( name='enchant', description="Adds an enchantment to a player's selected item.", opLevel=2, ), CommandSchema( name='execute', description='Executes another command.', opLevel=2, ), CommandSchema( name='experience', description='An alias of /xp. Adds or removes player experience.', opLevel=2, ), CommandSchema( name='fill', description='Fills a region with a specific block.', opLevel=2, ), CommandSchema( name='forceload', description='Forces chunks to constantly be loaded or not.', opLevel=2, ), CommandSchema( name='function', description='Runs a function.', opLevel=2, ), CommandSchema( name='gamemode', description="Sets a player's game mode.", opLevel=2, ), CommandSchema( name='gamerule', description='Sets or queries a game rule value.', opLevel=2, ), CommandSchema( name='give', description='Gives an item to a player.', opLevel=2, ), CommandSchema( name='help', description='An alias of /?. Provides help for commands.', opLevel=0, ), CommandSchema( name='item', description='Manipulates items in inventories.', opLevel=2, ), CommandSchema( name='kick', description='Kicks a player off a server.', opLevel=3, ), CommandSchema( name='kill', description='Kills entities (players, mobs, items, etc.).', opLevel=2, ), CommandSchema( name='list', description='Lists players on the server.', opLevel=0, ), CommandSchema( name='locate', description='Locates closest structure.', opLevel=2, ), CommandSchema( name='locatebiome', description='Locates closest biome.', opLevel=2, ), CommandSchema( name='loot', description='Drops items from an inventory slot onto the ground.', opLevel=2, ), CommandSchema( name='me', description='Displays a message about the sender.', opLevel=0, ), CommandSchema( name='msg', description='An alias of /tell and /w. Displays a private message to other players.', opLevel=0, ), CommandSchema( name='op', description='Grants operator status to a player.', opLevel=3, availableInSP=False ), CommandSchema( name='pardon', description='Removes entries from the banlist.', opLevel=3, availableInSP=False ), CommandSchema( name='pardon-ip', description='Removes entries from the banlist.', opLevel=3, availableInSP=False ), CommandSchema( name='particle', description='Creates particles.', opLevel=2, ), CommandSchema( name='perf', description='Captures info and metrics about the game for 10 seconds.', opLevel=4, availableInSP=False ), CommandSchema( name='playsound', description='Plays a sound.', opLevel=2, ), CommandSchema( name='publish', description='Opens single-player world to local network.', opLevel=4, availableInMP=False ), CommandSchema( name='recipe', description='Gives or takes player recipes.', opLevel=2, ), CommandSchema( name='reload', description='Reloads loot tables, advancements, and functions from disk.', opLevel=2, ), CommandSchema( name='replaceitem', description='Replaces items in inventories.', removed=True, removedVersion='1.17', removedComment='Replaced with `/item replace`', opLevel=2, ), CommandSchema( name='save-all', description='Saves the server to disk.', opLevel=4, availableInSP=False ), CommandSchema( name='save-off', description='Disables automatic server saves.', opLevel=4, availableInSP=False ), CommandSchema( name='save-on', description='Enables automatic server saves.', opLevel=4, availableInSP=False ), CommandSchema( name='say', description='Displays a message to multiple players.', opLevel=2, ), CommandSchema( name='schedule', description='Delays the execution of a function.', opLevel=2, ), CommandSchema( name='scoreboard', description='Manages scoreboard objectives and players.', opLevel=2, ), CommandSchema( name='seed', description='Displays the world seed.', opLevel='0 in singleplayer, 2 in multiplayer', ), CommandSchema( name='setblock', description='Changes a block to another block.', opLevel=2, ), CommandSchema( name='setidletimeout', description='Sets the time before idle players are kicked.', opLevel=3, availableInSP=False ), CommandSchema( name='setworldspawn', description='Sets the world spawn.', opLevel=2, ), CommandSchema( name='spawnpoint', description='Sets the spawn point for a player.', opLevel=2, ), CommandSchema( name='spectate', description='Make one player in spectator mode spectate an entity.', opLevel=2, ), CommandSchema( name='spreadplayers', description='Teleports entities to random locations.', opLevel=2, ), CommandSchema( name='stop', description='Stops a server.', opLevel=4, availableInSP=False ), CommandSchema( name='stopsound', description='Stops a sound.', opLevel=2, ), CommandSchema( name='summon', description='Summons an entity.', opLevel=2, ), CommandSchema( name='tag', description='Controls entity tags.', opLevel=2, ), CommandSchema( name='team', description='Controls teams.', opLevel=2, ), CommandSchema( name='teammsg', description='An alias of /tm. Specifies the message to send to team.', opLevel=0, ), CommandSchema( name='teleport', description='An alias of /tp. Teleports entities.', opLevel=2, ), CommandSchema( name='tell', description='An alias of /msg and /w. Displays a private message to other players.', opLevel=0, ), CommandSchema( name='tellraw', description='Displays a JSON message to players.', opLevel=2, ), CommandSchema( name='testfor', description='Counts entities matching specified conditions.', removed=True, removedVersion='1.13', removedComment='Use `/execute if` instead', # TODO: removedComment for '/testfor' command opLevel=2, ), CommandSchema( name='testforblock', description='Tests whether a block is in a location.', removed=True, removedVersion='1.13', removedComment='Use `/execute if block` instead', opLevel=2, ), CommandSchema( name='testforblocks', description='Tests whether the blocks in two regions match.', removed=True, removedVersion='1.13', removedComment='Use `/execute if` instead', opLevel=2, ), CommandSchema( name='time', description="Changes or queries the world's game time.", opLevel=2, ), CommandSchema( name='title', description='Manages screen titles.', opLevel=2, ), CommandSchema( name='tm', description='An alias of /teammsg. Specifies the message to send to team.', opLevel=0, ), # CommandSchema( # name='toggledownfall', # description='Toggles the weather.', # removed=True, # removedVersion='1.13', # removedComment='Use `/weather ...` instead', # opLevel=1, # ), CommandSchema( name='tp', description='An alias of /teleport. Teleports entities.', opLevel=2, ), CommandSchema( name='trigger', description='Sets a trigger to be activated.', opLevel=0, ), CommandSchema( name='w', description='An alias of /tell and /msg. Displays a private message to other players.', opLevel=0, ), CommandSchema( name='weather', description='Sets the weather.', opLevel=2, ), CommandSchema( name='whitelist', description='Manages server whitelist.', opLevel=3, availableInSP=False ), CommandSchema( name='worldborder', description='Manages the world border.', opLevel=2, ), CommandSchema( name='xp', description='An alias of /experience [Java Edition only]. Adds or removes player experience.', opLevel=2, ) ] BASIC_COMMAND_INFO: dict[str, CommandSchema] = {c.name: c for c in _BASIC_COMMAND_INFO_LIST} version.commands = BASIC_COMMAND_INFO BASIC_COMMAND_INFO['?'].next = [] BASIC_COMMAND_INFO['advancement'].next = [ ArgumentSchema( name='__action', type=makeLiteralsArgumentType(['grant', 'revoke']), next=[ ArgumentSchema( name='targets', type=MINECRAFT_ENTITY, next=[ KeywordSchema( name='everything', ), KeywordSchema( name='only', next=[ ArgumentSchema( name='advancement', type=DPE_ADVANCEMENT, next=[ TERMINAL, ArgumentSchema( name='criterion', type=BRIGADIER_STRING, ), ] ), ] ), KeywordSchema( name='from', next=[ ArgumentSchema( name='advancement', type=DPE_ADVANCEMENT, ), ] ), KeywordSchema( name='through', next=[ ArgumentSchema( name='advancement', type=DPE_ADVANCEMENT, ), ] ), KeywordSchema( name='until', next=[ ArgumentSchema( name='advancement', type=DPE_ADVANCEMENT, ), ] ), ], ), ], ), ] BASIC_COMMAND_INFO['attribute'].next = [ ArgumentSchema( name='target', type=MINECRAFT_ENTITY, next=[ ArgumentSchema( name='attribute', type=MINECRAFT_RESOURCE_LOCATION, next=[ KeywordSchema( name='get', next=[ TERMINAL, ArgumentSchema( name='scale', type=BRIGADIER_DOUBLE, ), ] ), KeywordSchema( name='base', next=[ KeywordSchema( name='get', next=[ TERMINAL, ArgumentSchema( name='scale', type=BRIGADIER_DOUBLE, ), ] ), KeywordSchema( name='set', next=[ ArgumentSchema( name='value', type=BRIGADIER_DOUBLE, ), ] ), ], ), KeywordSchema( name='modifier', next=[ KeywordSchema( name='add', next=[ ArgumentSchema( name='uuid', type=MINECRAFT_UUID, next=[ ArgumentSchema( name='name', type=BRIGADIER_STRING, next=[ ArgumentSchema( name='value', type=BRIGADIER_DOUBLE, next=[ ArgumentSchema( name='uuid', type=makeLiteralsArgumentType(['add', 'multiply', 'multiply_base']), ), ] ), ] ), ] ), ] ), KeywordSchema( name='remove', next=[ ArgumentSchema( name='uuid', type=MINECRAFT_UUID, ), ] ), KeywordSchema( name='value', next=[ KeywordSchema( name='get', next=[ ArgumentSchema( name='uuid', type=MINECRAFT_UUID, next=[ TERMINAL, ArgumentSchema( name='scale', type=BRIGADIER_DOUBLE, ), ] ), ] ), ] ), ], ), ], ), ], ), ] BASIC_COMMAND_INFO['ban'].next = [ ArgumentSchema( name='targets', type=MINECRAFT_GAME_PROFILE, next=[ TERMINAL, ArgumentSchema( name='reason', type=MINECRAFT_MESSAGE, ), ] ), ] BASIC_COMMAND_INFO['ban-ip'].next = [ ArgumentSchema( name='target', type=BRIGADIER_STRING, next=[ TERMINAL, ArgumentSchema( name='reason', type=MINECRAFT_MESSAGE, ), ] ), ] BASIC_COMMAND_INFO['banlist'].next = [ TERMINAL, KeywordSchema( name='ips', ), KeywordSchema( name='players', ), ] BASIC_COMMAND_INFO['bossbar'].next = [ KeywordSchema( name='add', next=[ ArgumentSchema( name='id', type=MINECRAFT_RESOURCE_LOCATION, next=[ ArgumentSchema( name='name', type=MINECRAFT_COMPONENT, ), ] ), ], ), KeywordSchema( name='get', next=[ ArgumentSchema( name='id', type=MINECRAFT_RESOURCE_LOCATION, next=[ ArgumentSchema( name='__setting', type=makeLiteralsArgumentType(['max', 'players', 'value', 'visible']), ), ] ), ], ), KeywordSchema( name='list', ), KeywordSchema( name='remove', next=[ ArgumentSchema( name='id', type=MINECRAFT_RESOURCE_LOCATION, ), ], ), KeywordSchema( name='set', next=[ ArgumentSchema( name='id', type=MINECRAFT_RESOURCE_LOCATION, next=[ KeywordSchema( name='color', next=[ ArgumentSchema( name='color', type=makeLiteralsArgumentType(['blue', 'green', 'pink', 'purple', 'red', 'white', 'yellow']), ), ], ), KeywordSchema( name='max', next=[ ArgumentSchema( name='max', type=BRIGADIER_INTEGER, ), ], ), KeywordSchema( name='name', next=[ ArgumentSchema( name='name', type=MINECRAFT_COMPONENT, ), ], ), KeywordSchema( name='players', next=[ TERMINAL, ArgumentSchema( name='targets', type=MINECRAFT_ENTITY, ), ], ), KeywordSchema( name='style', next=[ ArgumentSchema( name='style', type=makeLiteralsArgumentType(['notched_6', 'notched_10', 'notched_12', 'notched_20', 'progress']), ), ], ), KeywordSchema( name='value ', next=[ ArgumentSchema( name='value', type=BRIGADIER_INTEGER, ), ], ), KeywordSchema( name='visible', next=[ ArgumentSchema( name='visible', type=BRIGADIER_BOOL, ), ], ), ] ), ], ), ] BASIC_COMMAND_INFO['clear'].next = [ TERMINAL, ArgumentSchema( name='targets', type=MINECRAFT_ENTITY, next=[ TERMINAL, ArgumentSchema( name='item', type=MINECRAFT_ITEM_PREDICATE, next=[ TERMINAL, ArgumentSchema( name='maxCount', type=BRIGADIER_INTEGER, ), ], ), ], ), ] BASIC_COMMAND_INFO['clone'].next = [ ArgumentSchema( name='begin', type=MINECRAFT_BLOCK_POS, next=[ ArgumentSchema( name='end', type=MINECRAFT_BLOCK_POS, next=[ ArgumentSchema( name='destination', type=MINECRAFT_BLOCK_POS, next=[ TERMINAL, ArgumentSchema( name='maskMode', type=makeLiteralsArgumentType(['replace', 'masked']), next=[ TERMINAL, ArgumentSchema( name='cloneMode', type=makeLiteralsArgumentType(['force', 'move', 'normal']), ), ], ), KeywordSchema( name='filtered', next=[ ArgumentSchema( name='filter', type=MINECRAFT_BLOCK_PREDICATE, next=[ TERMINAL, ArgumentSchema( name='cloneMode', type=makeLiteralsArgumentType(['force', 'move', 'normal']), ), ], ), ], ), ], ), ], ), ], ), ] # data command: DATA_TARGET = [ KeywordSchema( name='block', next=[ ArgumentSchema( name='targetPos', type=MINECRAFT_BLOCK_POS, ), ] ), KeywordSchema( name='entity', next=[ ArgumentSchema( name='target', type=MINECRAFT_ENTITY, ), ] ), KeywordSchema( name='storage', next=[ ArgumentSchema( name='target', type=MINECRAFT_RESOURCE_LOCATION, ), ] ), ] DATA_MODIFICATION = [ KeywordSchema( name='append', ), KeywordSchema( name='insert', next=[ ArgumentSchema( name='index', type=BRIGADIER_INTEGER, ), ] ), KeywordSchema( name='merge', ), KeywordSchema( name='prepend', ), KeywordSchema( name='set', ), ] DATA_SOURCE = [ KeywordSchema( name='block', next=[ ArgumentSchema( name='sourcePos', type=MINECRAFT_BLOCK_POS, ), ] ), KeywordSchema( name='entity', next=[ ArgumentSchema( name='source', type=MINECRAFT_ENTITY, ), ] ), KeywordSchema( name='storage', next=[ ArgumentSchema( name='source', type=MINECRAFT_RESOURCE_LOCATION, ), ] ), ] BASIC_COMMAND_INFO['data'].next = [ KeywordSchema( name='get', next=[ SwitchSchema( name='TARGET', options=DATA_TARGET, next=[ TERMINAL, ArgumentSchema( name='path', type=MINECRAFT_NBT_PATH, next=[ TERMINAL, ArgumentSchema( name='scale', type=BRIGADIER_FLOAT, ), ] ), ] ), ] ), KeywordSchema( name='merge', next=[ SwitchSchema( name='TARGET', options=DATA_TARGET, next=[ ArgumentSchema( name='nbt', type=MINECRAFT_NBT_COMPOUND_TAG, ), ] ), ] ), KeywordSchema( name='modify', next=[ SwitchSchema( name='TARGET', options=DATA_TARGET, next=[ ArgumentSchema( name='targetPath', type=MINECRAFT_NBT_PATH, next=[ SwitchSchema( name='MODIFICATION', options=DATA_MODIFICATION, next=[ KeywordSchema( name='from', next=[ SwitchSchema( name='SOURCE', options=DATA_SOURCE, next=[ TERMINAL, ArgumentSchema( name='sourcePath', type=MINECRAFT_NBT_PATH, ), ] ), ] ), KeywordSchema( name='value', next=[ ArgumentSchema( name='value', type=MINECRAFT_NBT_TAG, ), ] ), ] ), ] ), ] ), ] ), # remove <TARGET> <path> KeywordSchema( name='remove', next=[ SwitchSchema( name='TARGET', options=DATA_TARGET, next=[ ArgumentSchema( name='path', type=MINECRAFT_NBT_PATH, ), ] ), ] ), ] BASIC_COMMAND_INFO['datapack'].next = [ KeywordSchema( name='disable', next=[ ArgumentSchema( name='name', type=BRIGADIER_STRING, subType=ST_DPE_DATAPACK, ), ], ), KeywordSchema( name='enable', next=[ ArgumentSchema( name='name', type=BRIGADIER_STRING, subType=ST_DPE_DATAPACK, next=[ TERMINAL, KeywordSchema( name='first', ), KeywordSchema( name='last', ), KeywordSchema( name='before', next=[ ArgumentSchema( name='name', type=BRIGADIER_STRING, subType=ST_DPE_DATAPACK, ), ], ), KeywordSchema( name='after', next=[ ArgumentSchema( name='name', type=BRIGADIER_STRING, subType=ST_DPE_DATAPACK, ), ], ), ] ), ], ), KeywordSchema( name='list', description="List all data packs, or list only the available/enabled ones. Hovering over the data packs in the chat output shows their description defined in their pack.mcmeta.", next=[ TERMINAL, KeywordSchema( name='available', next=[TERMINAL], ), KeywordSchema( name='enabled', next=[TERMINAL], ), ], ), ] BASIC_COMMAND_INFO['debug'].next = [ KeywordSchema( name='start', ), KeywordSchema( name='stop', ), KeywordSchema( name='function', next=[ ArgumentSchema( name='name', type=MINECRAFT_FUNCTION, ), ] ), ] BASIC_COMMAND_INFO['defaultgamemode'].next = [ ArgumentSchema( name='mode', type=makeLiteralsArgumentType(['survival', 'creative', 'adventure', 'spectator']), ), ] BASIC_COMMAND_INFO['deop'].next = [ ArgumentSchema( name='targets', type=MINECRAFT_GAME_PROFILE, ), ] BASIC_COMMAND_INFO['difficulty'].next = [ TERMINAL, ArgumentSchema( name='difficulty', type=makeLiteralsArgumentType(['peaceful', 'easy', 'normal', 'hard']), ), ] BASIC_COMMAND_INFO['effect'].next = [ KeywordSchema( name='give', next=[ ArgumentSchema( name='targets', type=MINECRAFT_ENTITY, next=[ ArgumentSchema( name='effect', type=MINECRAFT_MOB_EFFECT, next=[ TERMINAL, ArgumentSchema( name='seconds', type=BRIGADIER_INTEGER, args={'min': 0, 'max': 1000000}, next=[ TERMINAL, ArgumentSchema( name='amplifier', type=BRIGADIER_INTEGER, args={'min': 0, 'max': 255}, next=[ TERMINAL, ArgumentSchema( name='hideParticles', type=BRIGADIER_BOOL, ), ] ), ] ), ] ), ] ), ], ), KeywordSchema( name='clear', next=[ TERMINAL, ArgumentSchema( name='targets', type=MINECRAFT_ENTITY, next=[ TERMINAL, ArgumentSchema( name='effect', type=MINECRAFT_MOB_EFFECT, ), ] ), ], ), ] BASIC_COMMAND_INFO['enchant'].next = [ ArgumentSchema( name='targets', type=MINECRAFT_ENTITY, next=[ ArgumentSchema( name='enchantment', type=MINECRAFT_ITEM_ENCHANTMENT, next=[ TERMINAL, ArgumentSchema( name='level', type=BRIGADIER_INTEGER, ), ] ), ] ), ] # execute Command: EXECUTE_INSTRUCTIONS = [] EXECUTE_INSTRUCTIONS.append(KeywordSchema(name='align', next=[ ArgumentSchema( name='axes', type=MINECRAFT_SWIZZLE, next=EXECUTE_INSTRUCTIONS ), ], )) EXECUTE_INSTRUCTIONS.append(KeywordSchema(name='anchored', next=[ ArgumentSchema( name='anchor', type=MINECRAFT_ENTITY_ANCHOR, next=EXECUTE_INSTRUCTIONS ), ], )) EXECUTE_INSTRUCTIONS.append(KeywordSchema(name='as', next=[ ArgumentSchema( name='targets', type=MINECRAFT_ENTITY, next=EXECUTE_INSTRUCTIONS ), ], )) EXECUTE_INSTRUCTIONS.append(KeywordSchema(name='at', next=[ ArgumentSchema( name='targets', type=MINECRAFT_ENTITY, next=EXECUTE_INSTRUCTIONS ), ], )) EXECUTE_INSTRUCTIONS.append(KeywordSchema(name='facing', next=[ ArgumentSchema( name='pos', type=MINECRAFT_VEC3, next=EXECUTE_INSTRUCTIONS ), KeywordSchema( name='entity', next=[ ArgumentSchema( name='targets', type=MINECRAFT_ENTITY, next=[ ArgumentSchema( name='anchor', type=MINECRAFT_ENTITY_ANCHOR, next=EXECUTE_INSTRUCTIONS ), ] ), ], ) ], )) EXECUTE_INSTRUCTIONS.append(KeywordSchema(name='in', next=[ ArgumentSchema( name='dimension', type=MINECRAFT_DIMENSION, next=EXECUTE_INSTRUCTIONS ), ], )) EXECUTE_INSTRUCTIONS.append(KeywordSchema(name='positioned', next=[ ArgumentSchema( name='pos', type=MINECRAFT_VEC3, next=EXECUTE_INSTRUCTIONS ), KeywordSchema( name='as', next=[ ArgumentSchema( name='targets', type=MINECRAFT_ENTITY, next=EXECUTE_INSTRUCTIONS ), ], ) ], )) EXECUTE_INSTRUCTIONS.append(KeywordSchema(name='rotated', next=[ ArgumentSchema( name='rot', type=MINECRAFT_ROTATION, next=EXECUTE_INSTRUCTIONS ), KeywordSchema( name='as', next=[ ArgumentSchema( name='targets', type=MINECRAFT_ENTITY, next=EXECUTE_INSTRUCTIONS ), ], ) ], )) EXECUTE_IF_UNLESS_ARGUMENTS = [] TERMINAL_LIST = [TERMINAL] EXECUTE_IF_UNLESS_ARGUMENTS.append(KeywordSchema(name='block', next=[ ArgumentSchema( name='pos', type=MINECRAFT_BLOCK_POS, next=[ ArgumentSchema( name='block', type=MINECRAFT_BLOCK_PREDICATE, next=ChainedList(TERMINAL_LIST, EXECUTE_INSTRUCTIONS) ), ], ), ], )) EXECUTE_IF_UNLESS_ARGUMENTS.append(KeywordSchema(name='blocks', next=[ ArgumentSchema( name='start', type=MINECRAFT_BLOCK_POS, next=[ ArgumentSchema( name='end', type=MINECRAFT_BLOCK_POS, next=[ ArgumentSchema( name='destination', type=MINECRAFT_BLOCK_POS, next=[ KeywordSchema( name='all', next=ChainedList(TERMINAL_LIST, EXECUTE_INSTRUCTIONS), ), KeywordSchema( name='masked', next=ChainedList(TERMINAL_LIST, EXECUTE_INSTRUCTIONS), ), ], ), ], ), ], ), ], )) EXECUTE_IF_UNLESS_ARGUMENTS.append(KeywordSchema(name='data', next=[ KeywordSchema( name='block', next=[ ArgumentSchema( name='pos', type=MINECRAFT_BLOCK_POS, next=[ ArgumentSchema( name='path', type=MINECRAFT_NBT_PATH, next=ChainedList(TERMINAL_LIST, EXECUTE_INSTRUCTIONS), ), ], ), ], ), KeywordSchema( name='entity', next=[ ArgumentSchema( name='target', type=MINECRAFT_ENTITY, next=[ ArgumentSchema( name='path', type=MINECRAFT_NBT_PATH, next=ChainedList(TERMINAL_LIST, EXECUTE_INSTRUCTIONS), ), ], ), ], ), KeywordSchema( name='storage', next=[ ArgumentSchema( name='source', type=MINECRAFT_RESOURCE_LOCATION, next=[ ArgumentSchema( name='path', type=MINECRAFT_NBT_PATH, next=ChainedList(TERMINAL_LIST, EXECUTE_INSTRUCTIONS), ), ], ), ], ), ], )) EXECUTE_IF_UNLESS_ARGUMENTS.append(KeywordSchema(name='entity', next=[ ArgumentSchema( name='entities', type=MINECRAFT_ENTITY, next=ChainedList(TERMINAL_LIST, EXECUTE_INSTRUCTIONS), ), ], )) EXECUTE_IF_UNLESS_ARGUMENTS.append(KeywordSchema(name='predicate', next=[ ArgumentSchema( name='predicate', type=MINECRAFT_PREDICATE, next=ChainedList(TERMINAL_LIST, EXECUTE_INSTRUCTIONS), ), ], )) EXECUTE_IF_UNLESS_ARGUMENTS.append(KeywordSchema(name='score', next=[ ArgumentSchema( name='target', type=MINECRAFT_SCORE_HOLDER, next=[ ArgumentSchema( name='targetObjective', type=MINECRAFT_OBJECTIVE, next=[ KeywordSchema( name='matches', next=[ ArgumentSchema( name='range', type=MINECRAFT_INT_RANGE, next=ChainedList(TERMINAL_LIST, EXECUTE_INSTRUCTIONS), ), ] ), ArgumentSchema( name='__compare', type=makeLiteralsArgumentType(['<=', '<', '=', '>=', '>']), next=[ ArgumentSchema( name='source', type=MINECRAFT_SCORE_HOLDER, next=[ ArgumentSchema( name='sourceObjective', type=MINECRAFT_OBJECTIVE, next=ChainedList(TERMINAL_LIST, EXECUTE_INSTRUCTIONS), ), ], ), ], ), ], ), ], ), ], )) EXECUTE_INSTRUCTIONS.append(KeywordSchema(name='if', next=EXECUTE_IF_UNLESS_ARGUMENTS, )) EXECUTE_INSTRUCTIONS.append(KeywordSchema(name='unless', next=EXECUTE_IF_UNLESS_ARGUMENTS, )) EXECUTE_STORE_RESULT_SUCCESS_ARGUMENTS = [] EXECUTE_STORE_RESULT_SUCCESS_ARGUMENTS.append(KeywordSchema(name='block', next=[ ArgumentSchema( name='targetPos', type=MINECRAFT_BLOCK_POS, next=[ ArgumentSchema( name='path', type=MINECRAFT_NBT_PATH, next=[ ArgumentSchema( name='type', type=makeLiteralsArgumentType(['byte', 'short', 'int', 'long', 'float', 'double']), next=[ ArgumentSchema( name='scale', description="Multiplier to apply before storing value", type=BRIGADIER_DOUBLE, next=EXECUTE_INSTRUCTIONS ), ], ), ], ), ], ), ] )) EXECUTE_STORE_RESULT_SUCCESS_ARGUMENTS.append(KeywordSchema(name='bossbar', next=[ ArgumentSchema( name='id', type=MINECRAFT_RESOURCE_LOCATION, next=[ ArgumentSchema( name='value', type=makeLiteralsArgumentType(['value', 'max']), next=EXECUTE_INSTRUCTIONS, ), ], ), ] )) EXECUTE_STORE_RESULT_SUCCESS_ARGUMENTS.append(KeywordSchema(name='entity', next=[ ArgumentSchema( name='target', type=MINECRAFT_ENTITY, next=[ ArgumentSchema( name='path', type=MINECRAFT_NBT_PATH, next=[ ArgumentSchema( name='type', type=makeLiteralsArgumentType(['byte', 'short', 'int', 'long', 'float', 'double']), next=[ ArgumentSchema( name='scale', description="Multiplier to apply before storing value", type=BRIGADIER_DOUBLE, next=EXECUTE_INSTRUCTIONS ), ], ), ], ), ], ), ] )) EXECUTE_STORE_RESULT_SUCCESS_ARGUMENTS.append(KeywordSchema(name='score', next=[ ArgumentSchema( name='targets', description='Specifies score holder(s) whose score is to be overridden', type=MINECRAFT_SCORE_HOLDER, next=[ ArgumentSchema( name='objective', description='A scoreboard objective', type=MINECRAFT_OBJECTIVE, next=EXECUTE_INSTRUCTIONS, ), ], ), ] )) EXECUTE_STORE_RESULT_SUCCESS_ARGUMENTS.append(KeywordSchema(name='storage', next=[ ArgumentSchema( name='target', type=MINECRAFT_RESOURCE_LOCATION, next=[ ArgumentSchema( name='path', type=MINECRAFT_NBT_PATH, next=[ ArgumentSchema( name='type', type=makeLiteralsArgumentType(['byte', 'short', 'int', 'long', 'float', 'double']), next=[ ArgumentSchema( name='scale', description="Multiplier to apply before storing value", type=BRIGADIER_DOUBLE, next=EXECUTE_INSTRUCTIONS ), ], ), ], ), ], ), ] )) EXECUTE_INSTRUCTIONS.append(KeywordSchema(name='store', next=[ KeywordSchema( name='result', next=EXECUTE_STORE_RESULT_SUCCESS_ARGUMENTS, ), KeywordSchema( name='success', next=EXECUTE_STORE_RESULT_SUCCESS_ARGUMENTS, ), ] )) EXECUTE_INSTRUCTIONS.append(KeywordSchema(name='run', next=[COMMANDS_ROOT], )) BASIC_COMMAND_INFO['execute'].next = EXECUTE_INSTRUCTIONS BASIC_COMMAND_INFO['experience'].next = [ KeywordSchema( name='add', next=[ ArgumentSchema( name='targets', type=MINECRAFT_ENTITY, next=[ ArgumentSchema( name='amount', type=BRIGADIER_INTEGER, next=[ ArgumentSchema( name='__levels', type=makeLiteralsArgumentType(['levels', 'points']), ), ] ), ] ), ] ), KeywordSchema( name='set', next=[ ArgumentSchema( name='targets', type=MINECRAFT_ENTITY, next=[ ArgumentSchema( name='amount', type=BRIGADIER_INTEGER, next=[ ArgumentSchema( name='__levels', type=makeLiteralsArgumentType(['levels', 'points']), ), ] ), ] ), ], ), KeywordSchema( name='query', next=[ ArgumentSchema( name='targets', type=MINECRAFT_ENTITY, next=[ ArgumentSchema( name='__levels', type=makeLiteralsArgumentType(['levels', 'points']), ), ] ), ] ), ] # fill <from> <to> <block> [destroy|hollow|keep|outline] # fill <from> <to> <block> replace [<filter>] BASIC_COMMAND_INFO['fill'].next = [ ArgumentSchema( name='from', type=MINECRAFT_BLOCK_POS, next=[ ArgumentSchema( name='to', type=MINECRAFT_BLOCK_POS, next=[ ArgumentSchema( name='block', type=MINECRAFT_BLOCK_STATE, next=[ TERMINAL, ArgumentSchema( name='option', type=makeLiteralsArgumentType(['destroy', 'hollow', 'keep', 'outline']), ), KeywordSchema( name='replace', next=[ TERMINAL, ArgumentSchema( name='replace', type=MINECRAFT_BLOCK_PREDICATE ), ] ), ] ), ] ), ] ), ] FORCELOAD_RANGE_ARG = ArgumentSchema( name='from', type=MINECRAFT_COLUMN_POS, next=[ TERMINAL, ArgumentSchema( name='to', type=MINECRAFT_COLUMN_POS, ), ] ) BASIC_COMMAND_INFO['forceload'].next = [ KeywordSchema( name='add', next=[ FORCELOAD_RANGE_ARG, ] ), KeywordSchema( name='remove', next=[ KeywordSchema('all'), FORCELOAD_RANGE_ARG, ] ), KeywordSchema( name='query', next=[ TERMINAL, ArgumentSchema( name='pos', type=MINECRAFT_COLUMN_POS, ), ] ), ] BASIC_COMMAND_INFO['function'].next = [ ArgumentSchema( name='name', type=MINECRAFT_FUNCTION, ), ] BASIC_COMMAND_INFO['gamemode'].next = [ ArgumentSchema( name='gamemode', type=MINECRAFT_GAME_MODE, next=[ TERMINAL, ArgumentSchema( name='target', type=MINECRAFT_ENTITY, ) ] ), ] BASIC_COMMAND_INFO['gamerule'].next = [ KeywordSchema( name=gr.name, description=gr.description, next=[ TERMINAL, ArgumentSchema( name='value', type=gr.type, ), ] ) for gr in version.gamerules ] BASIC_COMMAND_INFO['give'].next = [ ArgumentSchema( name='target', type=MINECRAFT_ENTITY, next=[ ArgumentSchema( name='item', type=MINECRAFT_ITEM_STACK, next=[ TERMINAL, ArgumentSchema( name='count', type=BRIGADIER_INTEGER, ), ] ), ] ), ] BASIC_COMMAND_INFO['help'].next = [] ITEM_TARGET = [ KeywordSchema( name='block', next=[ ArgumentSchema( name='pos', type=MINECRAFT_BLOCK_POS, ), ] ), KeywordSchema( name='entity', next=[ ArgumentSchema( name='targets', type=MINECRAFT_ENTITY, ), ] ), ] ITEM_SOURCE = [ KeywordSchema( name='block', next=[ ArgumentSchema( name='sourcePos', type=MINECRAFT_BLOCK_POS, ), ] ), KeywordSchema( name='entity', next=[ ArgumentSchema( name='sourceTarget', type=MINECRAFT_ENTITY, ), ] ), ] ITEM_MODIFIER = [ ArgumentSchema( name='modifier', type=MINECRAFT_RESOURCE_LOCATION, ), ] BASIC_COMMAND_INFO['item'].next = [ KeywordSchema( name='modify', next=[ SwitchSchema( name='TARGET', options=ITEM_TARGET, next=[ ArgumentSchema( name='slot', type=MINECRAFT_NBT_PATH, next=[*ITEM_MODIFIER] ), ] ), ] ), KeywordSchema( name='replace', next=[ SwitchSchema( name='TARGET', options=ITEM_TARGET, next=[ ArgumentSchema( name='slot', type=MINECRAFT_NBT_PATH, next=[ KeywordSchema( name='with', next=[ ArgumentSchema( name='item', type=MINECRAFT_ITEM_STACK, next=[ TERMINAL, ArgumentSchema( name='count', type=BRIGADIER_INTEGER, args={'min': 1, 'max': 64}, ), ] ), ] ), KeywordSchema( name='from', next=[ SwitchSchema( name='SOURCE', options=ITEM_SOURCE, next=[ ArgumentSchema( name='sourceSlot', type=MINECRAFT_ITEM_SLOT, next=[ TERMINAL, *ITEM_MODIFIER, ] ), ] ), ] ), ] ), ] ), ] ), ] BASIC_COMMAND_INFO['kick'].next = [ ArgumentSchema( name='targets', type=MINECRAFT_GAME_PROFILE, next=[ TERMINAL, ArgumentSchema( name='reason', type=MINECRAFT_MESSAGE, ), ] ), ] BASIC_COMMAND_INFO['kill'].next = [ TERMINAL, # An entity is required to run the command without args ArgumentSchema( name='targets', type=MINECRAFT_ENTITY, ), ] BASIC_COMMAND_INFO['list'].next = [ TERMINAL, KeywordSchema('uuids'), ] BASIC_COMMAND_INFO['locate'].next = [ ArgumentSchema( name='StructureType', type=makeLiteralsArgumentType(list(version.structures)), ), ] BASIC_COMMAND_INFO['locatebiome'].next = [ ArgumentSchema( name='biome', type=DPE_BIOME_ID, ), ] LOOT_TARGETS = [ KeywordSchema( name='spawn', next=[ ArgumentSchema( name='targetPos', type=MINECRAFT_BLOCK_POS, args={'type': float} ), ] ), KeywordSchema( name='replace', next=[ SwitchSchema( name='REPLACE', options=[ KeywordSchema( name='entity', next=[ ArgumentSchema( name='entities', type=MINECRAFT_ENTITY, ), ] ), KeywordSchema( name='block', next=[ ArgumentSchema( name='targetPos', type=MINECRAFT_BLOCK_POS, ), ] ), ], next=[ ArgumentSchema( name='slot', type=MINECRAFT_ITEM_SLOT, next=[ TERMINAL, ArgumentSchema( name='count', type=BRIGADIER_INTEGER, ), ] ), ] ), ] ), KeywordSchema( name='give', next=[ ArgumentSchema( name='players', type=MINECRAFT_ENTITY, ), ] ), KeywordSchema( name='insert', next=[ ArgumentSchema( name='targetPos', type=MINECRAFT_BLOCK_POS, ), ] ), ] LOOT_SOURCES = [ KeywordSchema( name='fish', next=[ ArgumentSchema( name='loot_table', type=MINECRAFT_RESOURCE_LOCATION, next=[ ArgumentSchema( name='pos', type=MINECRAFT_BLOCK_POS, next=[ TERMINAL, ArgumentSchema( name='hand', type=makeLiteralsArgumentType(['mainhand', 'offhand']), ), ArgumentSchema( name='tool', type=MINECRAFT_ITEM_STACK, ), ] ), ] ), ] ), KeywordSchema( name='loot', next=[ ArgumentSchema( name='loot_table', type=MINECRAFT_RESOURCE_LOCATION, ), ] ), KeywordSchema( name='kill', next=[ ArgumentSchema( name='target', type=MINECRAFT_ENTITY, ), ] ), KeywordSchema( name='mine', next=[ ArgumentSchema( name='pos', type=MINECRAFT_BLOCK_POS, next=[ TERMINAL, ArgumentSchema( name='hand', type=makeLiteralsArgumentType(['mainhand', 'offhand']), ), ArgumentSchema( name='tool', type=MINECRAFT_ITEM_STACK, ), ] ), ] ), ] BASIC_COMMAND_INFO['loot'].next = [ SwitchSchema( name='TARGET', options=LOOT_TARGETS, next=[ SwitchSchema( name='SOURCE', options=LOOT_SOURCES, ), ] ), ] BASIC_COMMAND_INFO['me'].next = [ ArgumentSchema( name='action', type=MINECRAFT_MESSAGE, ) ] BASIC_COMMAND_INFO['msg'].next = [ ArgumentSchema( name='targets', type=MINECRAFT_ENTITY, next=[ ArgumentSchema( name='message', type=MINECRAFT_MESSAGE, ), ] ), ] BASIC_COMMAND_INFO['op'].next = [ ArgumentSchema( name='targets', type=MINECRAFT_GAME_PROFILE, ), ] BASIC_COMMAND_INFO['pardon'].next = [ ArgumentSchema( name='targets', type=MINECRAFT_GAME_PROFILE, ), ] BASIC_COMMAND_INFO['pardon-ip'].next = [ ArgumentSchema( name='target', type=BRIGADIER_STRING, ), ] # particle <name> [<pos>] [<delta> <speed> <count> [force|normal] [<viewers>]] PARTICLE_ARGUMENTS = [ TERMINAL, ArgumentSchema( name='pos', type=MINECRAFT_VEC3, next=[ TERMINAL, ArgumentSchema( name='delta', type=MINECRAFT_VEC3, next=[ ArgumentSchema( name='speed', type=BRIGADIER_FLOAT, next=[ ArgumentSchema( name='count', type=BRIGADIER_INTEGER, next=[ TERMINAL, ArgumentSchema( name='display_mode', type=makeLiteralsArgumentType(['force', 'normal']), next=[ TERMINAL, ArgumentSchema( name='viewers', type=MINECRAFT_ENTITY, next=[] ), ] ), ] ), ] ), ] ), ] ), ] _SPECIAL_PARTICLES_tmp = [ KeywordSchema( name='dust', next=[ ArgumentSchema( name='red', type=BRIGADIER_FLOAT, next=[ ArgumentSchema( name='green', type=BRIGADIER_FLOAT, next=[ ArgumentSchema( name='blue', type=BRIGADIER_FLOAT, next=[ ArgumentSchema( name='size', type=BRIGADIER_FLOAT, next=PARTICLE_ARGUMENTS ), ] ), ] ), ] ), ] ), KeywordSchema( name='dust_color_transition', next=[ ArgumentSchema( name='red', type=BRIGADIER_FLOAT, next=[ ArgumentSchema( name='green', type=BRIGADIER_FLOAT, next=[ ArgumentSchema( name='blue', type=BRIGADIER_FLOAT, next=[ ArgumentSchema( name='size', type=BRIGADIER_FLOAT, next=[ ArgumentSchema( name='red', type=BRIGADIER_FLOAT, next=[ ArgumentSchema( name='green', type=BRIGADIER_FLOAT, next=[ ArgumentSchema( name='blue', type=BRIGADIER_FLOAT, next=PARTICLE_ARGUMENTS ), ] ), ] ), ] ), ] ), ] ), ] ), ] ), KeywordSchema( name='block', next=[ ArgumentSchema( name='blockState', type=MINECRAFT_BLOCK_STATE, next=PARTICLE_ARGUMENTS ), ] ), KeywordSchema( name='falling_dust', next=[ ArgumentSchema( name='blockState', type=MINECRAFT_BLOCK_STATE, next=PARTICLE_ARGUMENTS ), ] ), KeywordSchema( name='item', next=[ ArgumentSchema( name='item', type=MINECRAFT_ITEM_STACK, next=PARTICLE_ARGUMENTS ), ] ), KeywordSchema( name='vibration', next=[ ArgumentSchema( name='x_start', type=BRIGADIER_DOUBLE, next=[ ArgumentSchema( name='y_start', type=BRIGADIER_DOUBLE, next=[ ArgumentSchema( name='z_start', type=BRIGADIER_DOUBLE, next=[ ArgumentSchema( name='x_end', type=BRIGADIER_DOUBLE, next=[ ArgumentSchema( name='y_end', type=BRIGADIER_DOUBLE, next=[ ArgumentSchema( name='z_end', type=BRIGADIER_DOUBLE, next=[ ArgumentSchema( name='duration', type=BRIGADIER_INTEGER, next=PARTICLE_ARGUMENTS ), ] ), ] ), ] ), ] ), ] ), ] ), ] ), ] _SPECIAL_PARTICLES = [] for particle in _SPECIAL_PARTICLES_tmp: _SPECIAL_PARTICLES.append(particle) particle = copy(particle) particle.name = f'minecraft:{particle.name}' _SPECIAL_PARTICLES.append(particle) del _SPECIAL_PARTICLES_tmp BASIC_COMMAND_INFO['particle'].next = [ *_SPECIAL_PARTICLES, ArgumentSchema( name='name', type=MINECRAFT_PARTICLE, next=PARTICLE_ARGUMENTS ), ] BASIC_COMMAND_INFO['perf'].next = [ KeywordSchema('start'), KeywordSchema('stop'), ] # playsound <sound> <source> <targets> [<pos>] [<volume>] [<pitch>] [<minVolume>] BASIC_COMMAND_INFO['playsound'].next = [ ArgumentSchema( name='sound', type=MINECRAFT_RESOURCE_LOCATION, next=[ ArgumentSchema( name='source', type=makeLiteralsArgumentType(['master', 'music', 'record', 'weather', 'block', 'hostile', 'neutral', 'player', 'ambient', 'voice']), next=[ ArgumentSchema( name='targets', type=MINECRAFT_ENTITY, next=[ TERMINAL, ArgumentSchema( name='pos', type=MINECRAFT_VEC3, next=[ TERMINAL, ArgumentSchema( name='volume', type=BRIGADIER_FLOAT, next=[ TERMINAL, ArgumentSchema( name='pitch', type=BRIGADIER_FLOAT, next=[ TERMINAL, ArgumentSchema( name='minVolume', type=BRIGADIER_FLOAT, ), ] ), ] ), ] ), ] ), ] ), ] ), ] BASIC_COMMAND_INFO['publish'].next = [ TERMINAL, ArgumentSchema( name='port', type=BRIGADIER_INTEGER, ), ] # recipe (give|take) <targets> (*|<recipe>) BASIC_COMMAND_INFO['recipe'].next = [ ArgumentSchema( name='action', type=makeLiteralsArgumentType(['give', 'take']), next=[ ArgumentSchema( name='target', type=MINECRAFT_ENTITY, next=[ KeywordSchema('*'), ArgumentSchema( name='recipe', type=MINECRAFT_RESOURCE_LOCATION, ), ] ), ] ), ] BASIC_COMMAND_INFO['reload'].next = [TERMINAL] # has no arguments! BASIC_COMMAND_INFO['replaceitem'].next = [ ArgumentSchema( name='OUTDATED!', type=MINECRAFT_MESSAGE, ), ] # This command was superseded by the /item command in Java Edition 1.17. BASIC_COMMAND_INFO['save-all'].next = [ TERMINAL, KeywordSchema('flush'), ] BASIC_COMMAND_INFO['save-off'].next = [TERMINAL] # has no arguments! BASIC_COMMAND_INFO['save-on'].next = [TERMINAL] # has no arguments! BASIC_COMMAND_INFO['say'].next = [ ArgumentSchema( name='message', type=MINECRAFT_MESSAGE, ), ] # schedule function <function> <time> [append|replace] # schedule clear <function> BASIC_COMMAND_INFO['schedule'].next = [ KeywordSchema( name='function', next=[ ArgumentSchema( name='function', type=MINECRAFT_FUNCTION, next=[ ArgumentSchema( name='time', type=MINECRAFT_TIME, next=[ TERMINAL, ArgumentSchema( name='replace_behaviour', type=makeLiteralsArgumentType(['append', 'replace']), ), ] ), ] ), ] ), KeywordSchema( name='clear', next=[ ArgumentSchema( name='function', type=MINECRAFT_FUNCTION, ), ] ), ] # scoreboard Command: SCOREBOARD_OBJECTIVES = [] SCOREBOARD_OBJECTIVES.append(KeywordSchema(name='list')) # scoreboard objectives add <objective> <criteria> [<displayName>] SCOREBOARD_OBJECTIVES.append(KeywordSchema(name='add', next=[ ArgumentSchema( name='objective', type=BRIGADIER_STRING, next=[ ArgumentSchema( name='criteria', type=MINECRAFT_OBJECTIVE_CRITERIA, next=[ TERMINAL, ArgumentSchema( name='displayName', type=MINECRAFT_COMPONENT, ), ] ), ] ), ] )) # scoreboard objectives remove <objective> SCOREBOARD_OBJECTIVES.append(KeywordSchema(name='remove', next=[ ArgumentSchema( name='objective', type=MINECRAFT_OBJECTIVE, ), ] )) # scoreboard objectives setdisplay <slot> [<objective>] SCOREBOARD_OBJECTIVES.append(KeywordSchema(name='setdisplay', next=[ ArgumentSchema( name='slot', type=MINECRAFT_SCOREBOARD_SLOT, next=[ TERMINAL, ArgumentSchema( name='objective', type=MINECRAFT_OBJECTIVE, ), ] ), ] )) # scoreboard objectives modify <objective> displayname <displayName> # scoreboard objectives modify <objective> rendertype (hearts|integer) SCOREBOARD_OBJECTIVES.append(KeywordSchema(name='modify', next=[ ArgumentSchema( name='objective', type=MINECRAFT_OBJECTIVE, next=[ KeywordSchema( name='displayname', next=[ ArgumentSchema( name='displayName', type=MINECRAFT_COMPONENT, ), ] ), KeywordSchema( name='rendertype', next=[ ArgumentSchema( name='rendertype', type=makeLiteralsArgumentType(['hearts', 'integer']), ), ] ), ] ), ] )) SCOREBOARD_PLAYERS = [] # scoreboard players list [<target>] SCOREBOARD_PLAYERS.append(KeywordSchema(name='list', next=[ TERMINAL, ArgumentSchema( name='target', type=MINECRAFT_SCORE_HOLDER, ), ] )) # scoreboard players get <target> <objective> SCOREBOARD_PLAYERS.append(KeywordSchema(name='get', next=[ ArgumentSchema( name='target', type=MINECRAFT_SCORE_HOLDER, next=[ ArgumentSchema( name='objective', type=MINECRAFT_OBJECTIVE, ), ] ), ] )) # scoreboard players set <targets> <objective> <score> SCOREBOARD_PLAYERS.append(KeywordSchema(name='set', next=[ ArgumentSchema( name='targets', type=MINECRAFT_SCORE_HOLDER, next=[ ArgumentSchema( name='objective', type=MINECRAFT_OBJECTIVE, next=[ ArgumentSchema( name='score', type=BRIGADIER_INTEGER, ), ] ), ] ), ] )) # scoreboard players add <targets> <objective> <score> SCOREBOARD_PLAYERS.append(KeywordSchema(name='add', next=[ ArgumentSchema( name='targets', type=MINECRAFT_SCORE_HOLDER, next=[ ArgumentSchema( name='objective', type=MINECRAFT_OBJECTIVE, next=[ ArgumentSchema( name='score', type=BRIGADIER_INTEGER, ), ] ), ] ), ] )) # scoreboard players remove <targets> <objective> <score> SCOREBOARD_PLAYERS.append(KeywordSchema(name='remove', next=[ ArgumentSchema( name='targets', type=MINECRAFT_SCORE_HOLDER, next=[ ArgumentSchema( name='objective', type=MINECRAFT_OBJECTIVE, next=[ ArgumentSchema( name='score', type=BRIGADIER_INTEGER, ), ] ), ] ), ] )) # scoreboard players reset <targets> [<objective>] SCOREBOARD_PLAYERS.append(KeywordSchema(name='reset', next=[ ArgumentSchema( name='targets', type=MINECRAFT_SCORE_HOLDER, next=[ TERMINAL, ArgumentSchema( name='objective', type=MINECRAFT_OBJECTIVE, ), ] ), ] )) # scoreboard players enable <targets> <objective> SCOREBOARD_PLAYERS.append(KeywordSchema(name='enable', next=[ ArgumentSchema( name='targets', type=MINECRAFT_SCORE_HOLDER, next=[ ArgumentSchema( name='objective', type=MINECRAFT_OBJECTIVE, ), ] ), ] )) # scoreboard players operation <targets> <targetObjective> <operation> <source> <sourceObjective> SCOREBOARD_PLAYERS.append(KeywordSchema(name='operation', next=[ ArgumentSchema( name='targets', type=MINECRAFT_SCORE_HOLDER, next=[ ArgumentSchema( name='targetObjective', type=MINECRAFT_OBJECTIVE, next=[ ArgumentSchema( name='operation', type=MINECRAFT_OPERATION, next=[ ArgumentSchema( name='source', type=MINECRAFT_SCORE_HOLDER, next=[ ArgumentSchema( name='sourceObjective', type=MINECRAFT_OBJECTIVE, ), ] ), ] ), ] ), ] ), ] )) BASIC_COMMAND_INFO['scoreboard'].next = [ KeywordSchema( name='objectives', next=SCOREBOARD_OBJECTIVES ), KeywordSchema( name='players', next=SCOREBOARD_PLAYERS ), ] BASIC_COMMAND_INFO['seed'].next = [TERMINAL] # has no arguments! # setblock <pos> <block> [destroy|keep|replace] BASIC_COMMAND_INFO['setblock'].next = [ ArgumentSchema( name='pos', type=MINECRAFT_BLOCK_POS, next=[ ArgumentSchema( name='block', type=MINECRAFT_BLOCK_STATE, next=[ TERMINAL, ArgumentSchema( name='operation', type=makeLiteralsArgumentType(['destroy', 'keep', 'replace']), ), ] ), ] ), ] BASIC_COMMAND_INFO['setidletimeout'].next = [ ArgumentSchema( name='minutes', type=BRIGADIER_INTEGER, ), ] # setworldspawn [<pos>] [<angle>] BASIC_COMMAND_INFO['setworldspawn'].next = [ TERMINAL, ArgumentSchema( name='pos', type=MINECRAFT_BLOCK_POS, next=[ TERMINAL, ArgumentSchema( name='angle', type=MINECRAFT_ANGLE, ), ] ), ] # spawnpoint [<targets>] [<pos>] [<angle>] BASIC_COMMAND_INFO['spawnpoint'].next = [ TERMINAL, ArgumentSchema( name='targets', type=MINECRAFT_ENTITY, next=[ TERMINAL, ArgumentSchema( name='pos', type=MINECRAFT_BLOCK_POS, next=[ TERMINAL, ArgumentSchema( name='angle', type=MINECRAFT_ANGLE, ), ] ), ] ), ] # spectate <target> [<player>] BASIC_COMMAND_INFO['spectate'].next = [ ArgumentSchema( name='target', type=MINECRAFT_ENTITY, next=[ TERMINAL, ArgumentSchema( name='player', type=MINECRAFT_ENTITY, ), ] ), ] # spreadplayers <center> <spreadDistance> <maxRange> <respectTeams> <targets> # spreadplayers <center> <spreadDistance> <maxRange> under <maxHeight> <respectTeams> <targets> SPREADPLAYERS_RESPECT_TEAMS = [ ArgumentSchema( name='respectTeams', type=BRIGADIER_BOOL, next=[ ArgumentSchema( name='targets', type=MINECRAFT_ENTITY, ), ] ), ] BASIC_COMMAND_INFO['spreadplayers'].next = [ ArgumentSchema( name='center', type=MINECRAFT_VEC2, next=[ ArgumentSchema( name='spreadDistance', type=BRIGADIER_FLOAT, next=[ ArgumentSchema( name='maxRange', type=BRIGADIER_FLOAT, next=[ KeywordSchema( name='under', next=[ ArgumentSchema( name='maxHeight', type=BRIGADIER_INTEGER, next=SPREADPLAYERS_RESPECT_TEAMS ), ] ), *SPREADPLAYERS_RESPECT_TEAMS ] ), ] ), ] ), ] BASIC_COMMAND_INFO['stop'].next = [TERMINAL] # has no arguments! # stopsound <targets> [<source>] [<sound>] BASIC_COMMAND_INFO['stopsound'].next = [ ArgumentSchema( name='targets', type=MINECRAFT_ENTITY, next=[ TERMINAL, ArgumentSchema( name='source', type=makeLiteralsArgumentType(['*', 'master', 'music', 'record', 'weather', 'block', 'hostile', 'neutral', 'player', 'ambient', 'voice']), next=[ TERMINAL, ArgumentSchema( name='sound', type=MINECRAFT_RESOURCE_LOCATION, description="Specifies the sound to stop. Must be a resource location. \n\nMust be a sound event defined in `sounds.json` (for example, `entity.pig.ambient`).", ), ] ), ] ), ] # summon <entity> [<pos>] [<nbt>] BASIC_COMMAND_INFO['summon'].next = [ ArgumentSchema( name='entity', type=MINECRAFT_ENTITY_SUMMON, next=[ TERMINAL, ArgumentSchema( name='pos', type=MINECRAFT_VEC3, next=[ TERMINAL, ArgumentSchema( name='nbt', type=MINECRAFT_NBT_COMPOUND_TAG, ), ] ), ] ), ] # tag <targets> add <name> # tag <targets> list # tag <targets> remove <name> BASIC_COMMAND_INFO['tag'].next = [ ArgumentSchema( name='targets', type=MINECRAFT_ENTITY, next=[ KeywordSchema( name='add', next=[ ArgumentSchema( name='name', type=BRIGADIER_STRING, ), ] ), KeywordSchema('list'), KeywordSchema( name='remove', next=[ ArgumentSchema( name='name', type=BRIGADIER_STRING, ), ] ), ] ), ] # team list [<team>] # Lists all teams, with their display names and the amount of entities in them. The optional <team> can be used to specify a particular team. # # team add <team> [<displayName>] # Creates a team with the given name and optional display name. <displayName> defaults to <objective> when unspecified. # # team remove <team> # Deletes the specified team. # # team empty <team> # Removes all members from the named team. # # team join <team> [<members>] # Assigns the specified entities to the specified team. If no entities is specified, makes the executor join the team. # # team leave <members> # Makes the specified entities leave their teams. # # team modify <team> <option> <value> # Modifies the options of the specified team. BASIC_COMMAND_INFO['team'].next = [ KeywordSchema( name='list', description="Lists all teams, with their display names and the amount of entities in them. The optional `<team>` can be used to specify a particular team.", next=[ TERMINAL, ArgumentSchema( name='team', type=MINECRAFT_TEAM, ), ] ), KeywordSchema( name='add', description="Creates a team with the given name and optional display name. `<displayName>` defaults to `<objective>` when unspecified.", next=[ ArgumentSchema( name='team', type=BRIGADIER_STRING, next=[ TERMINAL, ArgumentSchema( name='displayName', type=MINECRAFT_COMPONENT, ), ] ), ] ), KeywordSchema( name='remove', description="Deletes the specified team.", next=[ ArgumentSchema( name='team', type=MINECRAFT_TEAM, ), ] ), KeywordSchema( name='empty', description="Removes all members from the named team.", next=[ ArgumentSchema( name='team', type=MINECRAFT_TEAM, ), ] ), KeywordSchema( name='join', description="Assigns the specified entities to the specified team. If no entities is specified, makes the executor join the team.", next=[ ArgumentSchema( name='team', type=MINECRAFT_TEAM, next=[ TERMINAL, ArgumentSchema( name='members', type=MINECRAFT_SCORE_HOLDER, ), ] ), ] ), KeywordSchema( name='leave', description="Makes the specified entities leave their teams.", next=[ ArgumentSchema( name='members', type=MINECRAFT_SCORE_HOLDER, ), ] ), KeywordSchema( name='modify', description="Modifies the options of the specified team.", next=[ ArgumentSchema( name='team', type=MINECRAFT_TEAM, next=[ SwitchSchema( name='option', options=[ KeywordSchema( name='displayName', description="Set the display name of the team.", next=[ ArgumentSchema( name='displayName', type=MINECRAFT_COMPONENT, description="Specifies the team name to be displayed. Must be a raw JSON text.", ), ] ), KeywordSchema( name='color', description="Decide the color of the team and players in chat, above their head, on the Tab menu, and on the sidebar. Also changes the color of the outline of the entities caused by the Glowing effect.", next=[ ArgumentSchema( name='value', type=MINECRAFT_COLOR, description="Must be a color.\n\nDefaults to reset. If reset, names are shown in default color and formatting.", ), ] ), KeywordSchema( name='friendlyFire', description="Enable/Disable players inflicting damage on each other when on the same team. (Note: players can still inflict status effects on each other.) Does not affect some non-player entities in a team.", next=[ ArgumentSchema( name='allowed', type=BRIGADIER_BOOL, description=" - true - (Default) Enable players inflicting damage on each other when in the same team.\n - false - Disable players inflicting damage on each other when in the same team.", ), ] ), KeywordSchema( name='seeFriendlyInvisibles', description="Decide players can see invisible players on their team as whether semi-transparent or completely invisible.", next=[ ArgumentSchema( name='allowed', type=BRIGADIER_BOOL, description=" - true - (Default) Can see invisible players on the same team semi-transparently.\n - false - Cannot see invisible players on the same team.", ), ] ), KeywordSchema( name='nametagVisibility', description="Decide whose name tags above their heads can be seen.", next=[ KeywordSchema( name='never', description="Name above player's head cannot be seen by any players.", ), KeywordSchema( name='hideForOtherTeams', description="Name above player's head can be seen only by players in the same team.", ), KeywordSchema( name='hideForOwnTeam', description="Name above player's head cannot be seen by all the players in the same team.", ), KeywordSchema( name='always', description="(Default) Name above player's head can be seen by all the players.", ), ] ), KeywordSchema( name='deathMessageVisibility', description="Control the visibility of death messages for players.", next=[ KeywordSchema( name='never', description="Hide death message for all the players.", ), KeywordSchema( name='hideForOtherTeams', description="Hide death message to all the players who are not in the same team.", ), KeywordSchema( name='hideForOwnTeam', description="Hide death message to players in the same team.", ), KeywordSchema( name='always', description="(Default) Make death message visible to all the players.", ), ] ), KeywordSchema( name='collisionRule', description="Controls the way the entities on the team collide with other entities.", next=[ KeywordSchema( name='always', description="(Default) Normal collision.", ), KeywordSchema( name='never', description="No entities can push entities in this team.", ), KeywordSchema( name='pushOtherTeams', description="Entities in this team can be pushed only by other entities in the same team.", ), KeywordSchema( name='pushOwnTeam', description="Entities in this team cannot be pushed by another entity in this team.", ), ] ), KeywordSchema( name='prefix', description="Modifies the prefix that displays before players' names.", next=[ ArgumentSchema( name='prefix', type=MINECRAFT_COMPONENT, description="Specifies the prefix to display. Must be a raw JSON text.", ), ] ), KeywordSchema( name='suffix', description="Modifies the suffix that displays before players' names.", next=[ ArgumentSchema( name='suffix', type=MINECRAFT_COMPONENT, description="Specifies the suffix to display. Must be a raw JSON text.", ), ] ), ], ), ] ), ] ), ] BASIC_COMMAND_INFO['teammsg'].next = [ ArgumentSchema( name='message', type=MINECRAFT_MESSAGE, ), ] # teleport <destination> # teleport <location> # # teleport <targets> <destination> # teleport <targets> <location> # teleport <targets> <location> <rotation> # teleport <targets> <location> facing <facingLocation> # teleport <targets> <location> facing entity <facingEntity> [<facingAnchor>] BASIC_COMMAND_INFO['teleport'].next = [ # ArgumentSchema( # name='destination', # type=MINECRAFT_ENTITY, # ), ArgumentSchema( name='location', type=MINECRAFT_VEC3, ), ArgumentSchema( name='targets|destination', type=MINECRAFT_ENTITY, next=[ TERMINAL, ArgumentSchema( name='location', type=MINECRAFT_VEC3, next=[ TERMINAL, ArgumentSchema( name='rotation', type=MINECRAFT_ROTATION, ), KeywordSchema( name='facing', next=[ ArgumentSchema( name='facingLocation', type=MINECRAFT_VEC3, ), KeywordSchema( name='entity', next=[ ArgumentSchema( name='facingEntity', type=MINECRAFT_ENTITY, next=[ TERMINAL, ArgumentSchema( name='facingAnchor', type=MINECRAFT_ENTITY_ANCHOR, ), ] ), ] ), ] ), ] ), ArgumentSchema( name='destination', type=MINECRAFT_ENTITY, ), ] ), ] BASIC_COMMAND_INFO['tell'].next = BASIC_COMMAND_INFO['msg'].next # tellraw <targets> <message> BASIC_COMMAND_INFO['tellraw'].next = [ ArgumentSchema( name='targets', type=MINECRAFT_ENTITY, next=[ ArgumentSchema( name='message', type=MINECRAFT_COMPONENT, ), ] ), ] BASIC_COMMAND_INFO['testfor'].next = [] # This command has been removed BASIC_COMMAND_INFO['testforblock'].next = [] # This command has been removed BASIC_COMMAND_INFO['testforblocks'].next = [] # This command has been removed BASIC_COMMAND_INFO['time'].next = [ KeywordSchema( name='add', description="Adds `<time>` to the in-game daytime.", next=[ ArgumentSchema( name='time', type=MINECRAFT_TIME, ), ] ), KeywordSchema( name='query', description="Queries current time.", next=[ ArgumentSchema( name='daytime|gametime|day', type=makeLiteralsArgumentType(['daytime', 'gametime', 'day']), ), ] ), KeywordSchema( name='set', next=[ ArgumentSchema( name='timeSpec', type=makeLiteralsArgumentType(['day', 'night', 'noon', 'midnight']), ), ] ), KeywordSchema( name='set', next=[ ArgumentSchema( name='time', type=MINECRAFT_TIME, ), ] ), ] # title <targets> (clear|reset) # title <targets> (title|subtitle|actionbar) <title> # title <targets> times <fadeIn> <stay> <fadeOut> BASIC_COMMAND_INFO['title'].next = [ ArgumentSchema( name='targets', type=MINECRAFT_ENTITY, next=[ ArgumentSchema( name='clear|reset', type=makeLiteralsArgumentType(['clear', 'reset']), ), ArgumentSchema( name='title|subtitle|actionbar', type=makeLiteralsArgumentType(['title', 'subtitle', 'actionbar']), next=[ ArgumentSchema( name='title', type=MINECRAFT_COMPONENT, ), ] ), KeywordSchema( name='times', next=[ ArgumentSchema( name='fadeIn', type=BRIGADIER_INTEGER, next=[ ArgumentSchema( name='stay', type=BRIGADIER_INTEGER, next=[ ArgumentSchema( name='fadeOut', type=BRIGADIER_INTEGER, ), ] ), ] ), ] ), ] ), ] BASIC_COMMAND_INFO['tm'].next = BASIC_COMMAND_INFO['teammsg'].next # BASIC_COMMAND_INFO['toggledownfall'].next = [] has been removed BASIC_COMMAND_INFO['tp'].next = BASIC_COMMAND_INFO['teleport'].next # trigger <objective> # trigger <objective> add <value> # trigger <objective> set <value> BASIC_COMMAND_INFO['trigger'].next = [ ArgumentSchema( name='objective', type=MINECRAFT_OBJECTIVE, next=[ TERMINAL, KeywordSchema( name='add', next=[ ArgumentSchema( name='value', type=BRIGADIER_INTEGER, ), ] ), KeywordSchema( name='set', next=[ ArgumentSchema( name='value', type=BRIGADIER_INTEGER, ), ], ), ] ), ] BASIC_COMMAND_INFO['w'].next = BASIC_COMMAND_INFO['msg'].next # weather (clear|rain|thunder) [<duration>] BASIC_COMMAND_INFO['weather'].next = [ ArgumentSchema( name='objective', type=makeLiteralsArgumentType(['clear', 'rain', 'thunder']), next=[ TERMINAL, ArgumentSchema( name='duration', type=BRIGADIER_INTEGER, ), ] ), ] BASIC_COMMAND_INFO['whitelist'].next = [] # TODO: BASIC_COMMAND_INFO['whitelist'].next BASIC_COMMAND_INFO['worldborder'].next = [] # TODO: BASIC_COMMAND_INFO['worldborder'].next BASIC_COMMAND_INFO['xp'].next = BASIC_COMMAND_INFO['experience'].next
python
# -*- coding: utf-8 -*- # Port of the official ttgo library for the LilyGo TTGO T-Watch 2020. # Author: Nikita Selin (Anodev)[https://github.com/OPHoperHPO] import gc import _thread import axp202 import lvgl as lv import st7789_lvgl import ft6x36 from bma42x import BMA42X from pcf8563 import PCF8563 from machine import Pin, I2C, PWM class Watch: def __init__(self, fastboot=False): self.__i2c__ = I2C(1, scl=Pin(22), sda=Pin(21)) self.pmu = axp202.PMU(self.__i2c__) self.tft = self.__init_display__() self.touch = self.__init_touch__() self.motor = None self.rtc = None self.bma = None self.ticker = None self.__fastboot__ = fastboot if fastboot: _thread.start_new_thread(self.__init_prep__, ()) else: self.__init_prep__() def __init_prep__(self): self.init_power() self.motor = Motor() self.rtc = PCF8563(self.__i2c__) self.bma = self.__init_bma__() def __init_touch__(self): ft6x36.lvgl_touch_init() return ft6x36 def __init_bma__(self): # BMA423.init(self.__i2c__, irq=True) # return BMA423 bma423 = BMA42X(self.__i2c__) bma423.init() return bma423 def __init_display__(self): return Display(self.pmu) @staticmethod def pmu_attach_interrupt(callback): irq = Pin(35, mode=Pin.IN) irq.irq(handler=callback, trigger=Pin.IRQ_FALLING) return irq @staticmethod def bma_attach_interrupt(callback): irq = Pin(39, mode=Pin.IN) irq.irq(handler=callback, trigger=Pin.IRQ_RISING) return irq @staticmethod def rtc_attach_interrupt(rtc_callback): irq = Pin(37, mode=Pin.IN) irq.irq(handler=rtc_callback, trigger=Pin.IRQ_FALLING) return irq def enable_audio_power(self, en=True): self.pmu.setLDO3Mode(1) self.pmu.setPowerOutPut(axp202.AXP202_LDO3, en) def lvgl_begin(self): import lvesp32 lv.init() self.ticker = lvesp32 disp_buf1 = st7789_lvgl.lv_disp_buf_t() buf1_1 = bytes(240 * 10) disp_buf1.init(buf1_1, None, len(buf1_1) // 4) disp_drv = st7789_lvgl.lv_disp_drv_t() disp_drv.init() disp_drv.buffer = disp_buf1 disp_drv.flush_cb = st7789_lvgl.driver_flush disp_drv.hor_res = 240 disp_drv.ver_res = 240 disp_drv.register() indev_drv = ft6x36.lv_indev_drv_t() indev_drv.init() indev_drv.type = lv.INDEV_TYPE.POINTER indev_drv.read_cb = ft6x36.touch_driver_read indev_drv.register() def init_power(self): # Change the button boot time to 4 seconds self.pmu.setShutdownTime(axp202.AXP_POWER_OFF_TIME_4S) # Turn off the charging instructions, there should be no self.pmu.setChgLEDMode(axp202.AXP20X_LED_OFF) # Turn off external enable self.pmu.setPowerOutPut(axp202.AXP202_EXTEN, False) # axp202 allows maximum charging current of 1800mA, minimum 300mA self.pmu.setChargeControlCur(300) def power_off(self): self.pmu.setPowerOutPut(axp202.AXP202_EXTEN, False) self.pmu.setPowerOutPut(axp202.AXP202_LDO4, False) self.pmu.setPowerOutPut(axp202.AXP202_DCDC2, False) self.pmu.setPowerOutPut(axp202.AXP202_LDO3, False) self.pmu.setPowerOutPut(axp202.AXP202_LDO2, False) class Display: """Display wrapper""" def __init__(self, pmu): """Inits display""" # Init display tft = st7789_lvgl tft.lvgl_driver_init() self.tft = tft self.pmu = pmu self.set_backlight_level(0) # Turn backlight off self.backlight_level = 0 self.bl_pin = Pin(12, Pin.OUT) self.backlight(1) # Enable power on backlight def backlight_fade(self, val=100): if val > self.backlight_level: data = 0 for i in range(self.backlight_level, val): data = i self.set_backlight_level(i) self.backlight_level = data return True elif val < self.backlight_level: data = 0 for i in reversed(range(val, self.backlight_level)): data = i self.set_backlight_level(i) self.backlight_level = data return True def switch_scene(self): level = self.backlight_level self.backlight_fade(0) self.backlight_fade(level) def set_backlight_level(self, percent): if 0 <= percent <= 100: voltage = 800 * percent / 100 self.__set_lcd_backlight_voltage__(2400 + voltage) self.backlight_level = percent def display_off(self): self.tft.st7789_send_cmd(0x10) def display_sleep(self): self.tft.st7789_send_cmd(0x10) def display_wakeup(self): self.tft.st7789_send_cmd(0x11) def backlight(self, val): self.bl_pin.value(val) self.__turn_lcd_backlight__(val) def __turn_lcd_backlight__(self, val): if val == 1: self.pmu.setPowerOutPut(axp202.AXP202_LDO2, True) else: self.pmu.setPowerOutPut(axp202.AXP202_LDO2, False) def __set_lcd_backlight_voltage__(self, voltage=3200): if voltage >= 3200: self.pmu.setLDO2Voltage(3200) elif voltage <= 2400: self.pmu.setLDO2Voltage(2400) else: self.pmu.setLDO2Voltage(voltage) class Motor: def __init__(self): self.pwm = PWM(Pin(4, Pin.OUT), freq=1000, duty=0) def on(self): self.pwm.duty(5) def off(self): self.pwm.duty(0) def set_strength(self, strength): self.pwm.duty(5 * strength / 100) def set_freq(self, freq): self.pwm.freq(freq)
python
# https://leetcode.com/problems/longest-common-prefix/ class Solution: def longestCommonPrefix(self, strs: List[str]) -> str: if not strs: return '' # since list of string will be sorted and retrieved min max by alphebetic order s1, s2 = min(strs), max(strs) for i, c in enumerate(s1): if c != s2[i]: return s1[:i] # stop until hit the split index return s1
python
from django.apps import AppConfig class S3FileConfig(AppConfig): name = 'apps.s3file'
python
""" test_django-oci api ------------------- Tests for `django-oci` api. """ from django.urls import reverse from django.contrib.auth.models import User from django_oci import settings from rest_framework import status from rest_framework.test import APITestCase from django.test.utils import override_settings from time import sleep from unittest import skipIf import subprocess import requests import hashlib import base64 import json import os import re here = os.path.abspath(os.path.dirname(__file__)) # Boolean from environment that determines authentication required variable auth_regex = re.compile('(\w+)[:=] ?"?([^"]+)"?') # Important: user needs to be created globally to be seen user, _ = User.objects.get_or_create(username="dinosaur") token = str(user.auth_token) def calculate_digest(blob): """Given a blob (the body of a response) calculate the sha256 digest""" hasher = hashlib.sha256() hasher.update(blob) return hasher.hexdigest() def get_auth_header(username, password): """django oci requires the user token as the password to generate a longer auth token that will expire after some number of seconds """ auth_str = "%s:%s" % (username, password) auth_header = base64.b64encode(auth_str.encode("utf-8")) return {"Authorization": "Basic %s" % auth_header.decode("utf-8")} def get_authentication_headers(response): """Given a requests.Response, assert that it has status code 401 and provides the Www-Authenticate header that can be parsed for the request """ assert response.status_code == 401 assert "Www-Authenticate" in response.headers matches = dict(auth_regex.findall(response.headers["Www-Authenticate"])) for key in ["scope", "realm", "service"]: assert key in matches # Prepare authentication headers and get token headers = get_auth_header(user.username, token) url = "%s?service=%s&scope=%s" % ( matches["realm"], matches["service"], matches["scope"], ) # With proper headers should be 200 auth_response = requests.get(url, headers=headers) assert auth_response.status_code == 200 body = auth_response.json() # Make sure we have the expected fields for key in ["token", "expires_in", "issued_at"]: assert key in body # Formulate new auth header return {"Authorization": "Bearer %s" % body["token"]} def read_in_chunks(image, chunk_size=1024): """Helper function to read file in chunks, with default size 1k.""" while True: data = image.read(chunk_size) if not data: break yield data def get_manifest(config_digest, layer_digest): """A dummy image manifest with a config and single image layer""" return json.dumps( { "schemaVersion": 2, "config": { "mediaType": "application/vnd.oci.image.config.v1+json", "size": 7023, "digest": config_digest, }, "layers": [ { "mediaType": "application/vnd.oci.image.layer.v1.tar+gzip", "size": 32654, "digest": layer_digest, } ], "annotations": {"com.example.key1": "peas", "com.example.key2": "carrots"}, } ) class APIBaseTests(APITestCase): def setUp(self): self.process = subprocess.Popen(["python", "manage.py", "runserver"]) sleep(2) def tearDown(self): os.kill(self.process.pid, 9) def test_api_version_check(self): """ GET of /v2 should return a 200 response. """ url = reverse("django_oci:api_version_check") response = self.client.get(url, format="json") self.assertEqual(response.status_code, status.HTTP_200_OK) class APIPushTests(APITestCase): def push( self, digest, data, content_type="application/octet-stream", test_response=True, extra_headers={}, ): url = "http://127.0.0.1:8000%s?digest=%s" % ( reverse("django_oci:blob_upload", kwargs={"name": self.repository}), digest, ) print("Single Monolithic POST: %s" % url) headers = { "Content-Length": str(len(data)), "Content-Type": content_type, } headers.update(extra_headers) response = requests.post(url, data=data, headers=headers) if test_response: self.assertTrue( response.status_code in [status.HTTP_202_ACCEPTED, status.HTTP_201_CREATED] ) return response def test_push_post_then_put(self): """ POST /v2/<name>/blobs/uploads/ PUT /v2/<name>/blobs/uploads/ """ url = "http://127.0.0.1:8000%s" % ( reverse("django_oci:blob_upload", kwargs={"name": self.repository}) ) print("POST to request session: %s" % url) headers = {"Content-Type": "application/octet-stream"} response = requests.post(url, headers=headers) auth_headers = get_authentication_headers(response) headers.update(auth_headers) response = requests.post(url, headers=headers) # Location must be in response header self.assertEqual(response.status_code, status.HTTP_202_ACCEPTED) self.assertTrue("Location" in response.headers) blob_url = "http://127.0.0.1:8000%s?digest=%s" % ( response.headers["Location"], self.digest, ) # PUT to upload blob url headers = { "Content-Length": str(len(self.data)), "Content-Type": "application/octet-stream", } headers.update(auth_headers) print("PUT to upload: %s" % blob_url) response = requests.put(blob_url, data=self.data, headers=headers) # This should allow HTTP_202_ACCEPTED too self.assertEqual(response.status_code, status.HTTP_201_CREATED) self.assertTrue("Location" in response.headers) download_url = add_url_prefix(response.headers["Location"]) response = requests.get(download_url, headers=auth_headers) self.assertEqual(response.status_code, status.HTTP_200_OK) # Test upload request from another repository non_standard_name = "conformance-aedf05b6-6996-4dae-ad18-70a4db9e9061" url = "http://127.0.0.1:8000%s" % ( reverse("django_oci:blob_upload", kwargs={"name": non_standard_name}) ) url = "%s?mount=%s&from=%s" % (url, self.digest, self.repository) print("POST to request mount from another repository: %s" % url) headers = {"Content-Type": "application/octet-stream"} response = requests.post(url, headers=headers) auth_headers = get_authentication_headers(response) headers.update(auth_headers) response = requests.post(url, headers=headers) assert "Location" in response.headers assert non_standard_name in response.headers["Location"] download_url = add_url_prefix(response.headers["Location"]) response = requests.get(download_url, headers=auth_headers) self.assertEqual(response.status_code, status.HTTP_200_OK) def test_push_chunked(self): """ POST /v2/<name>/blobs/uploads/ PATCH <location> PUT /v2/<name>/blobs/uploads/ """ url = "http://127.0.0.1:8000%s" % ( reverse("django_oci:blob_upload", kwargs={"name": self.repository}) ) print("POST to request chunked session: %s" % url) headers = {"Content-Type": "application/octet-stream", "Content-Length": "0"} response = requests.post(url, headers=headers) auth_headers = get_authentication_headers(response) headers.update(auth_headers) response = requests.post(url, headers=headers) # Location must be in response header self.assertEqual(response.status_code, status.HTTP_202_ACCEPTED) self.assertTrue("Location" in response.headers) session_url = "http://127.0.0.1:8000%s" % response.headers["Location"] # Read the file in chunks, for each do a patch start = 0 with open(self.image, "rb") as fd: for chunk in read_in_chunks(fd): if not chunk: break end = start + len(chunk) - 1 content_range = "%s-%s" % (start, end) headers = { "Content-Range": content_range, "Content-Length": str(len(chunk)), "Content-Type": "application/octet-stream", } headers.update(auth_headers) start = end + 1 print("PATCH to upload content range: %s" % content_range) response = requests.patch(session_url, data=chunk, headers=headers) self.assertEqual(response.status_code, status.HTTP_202_ACCEPTED) self.assertTrue("Location" in response.headers) # Finally, issue a PUT request to close blob session_url = "%s?digest=%s" % (session_url, self.digest) response = requests.put(session_url, headers=auth_headers) # Location must be in response header self.assertEqual(response.status_code, status.HTTP_201_CREATED) self.assertTrue("Location" in response.headers) def test_push_view_delete_manifest(self): """ PUT /v2/<name>/manifests/<reference> DELETE /v2/<name>/manifests/<reference> """ url = "http://127.0.0.1:8000%s" % ( reverse( "django_oci:image_manifest", kwargs={"name": self.repository, "tag": "latest"}, ) ) print("PUT to create image manifest: %s" % url) # Calculate digest for config (yes, we haven't uploaded the blob, it's ok) with open(self.config, "r") as fd: content = fd.read() config_digest = calculate_digest(content.encode("utf-8")) # Prepare the manifest (already a text string) manifest = get_manifest(config_digest, self.digest) manifest_reference = "sha256:%s" % calculate_digest(manifest.encode("utf-8")) headers = { "Content-Type": "application/vnd.oci.image.manifest.v1+json", "Content-Length": str(len(manifest)), } response = requests.put(url, headers=headers, data=manifest) auth_headers = get_authentication_headers(response) headers.update(auth_headers) response = requests.put(url, headers=headers, data=manifest) # Location must be in response header self.assertEqual(response.status_code, status.HTTP_201_CREATED) self.assertTrue("Location" in response.headers) # test manifest download response = requests.get(url, headers=auth_headers).json() for key in ["schemaVersion", "config", "layers", "annotations"]: assert key in response # Retrieve newly created tag tags_url = "http://127.0.0.1:8000%s" % ( reverse("django_oci:image_tags", kwargs={"name": self.repository}) ) print("GET to list tags: %s" % tags_url) tags = requests.get(tags_url, headers=auth_headers) self.assertEqual(tags.status_code, status.HTTP_200_OK) tags = tags.json() for key in ["name", "tags"]: assert key in tags # First delete tag (we are allowed to have an untagged manifest) response = requests.delete(url, headers=auth_headers) self.assertEqual(response.status_code, status.HTTP_202_ACCEPTED) # Finally, delete the manifest url = "http://127.0.0.1:8000%s" % ( reverse( "django_oci:image_manifest", kwargs={"name": self.repository, "reference": manifest_reference}, ) ) response = requests.delete(url, headers=auth_headers) self.assertEqual(response.status_code, status.HTTP_202_ACCEPTED) def test_push_single_monolithic_post(self): """ POST /v2/<name>/blobs/uploads/ """ # Push the image blob, should return 401 without authentication response = self.push(digest=self.digest, data=self.data, test_response=False) headers = get_authentication_headers(response) response = self.push( digest=self.digest, data=self.data, test_response=False, extra_headers=headers, ) assert response.status_code == 201 assert "Location" in response.headers download_url = add_url_prefix(response.headers["Location"]) response = requests.get(download_url, headers=headers if headers else None) self.assertEqual(response.status_code, status.HTTP_200_OK) # Upload an image manifest with open(self.config, "r") as fd: content = fd.read().encode("utf-8") config_digest = calculate_digest(content) self.push(digest=config_digest, data=content, extra_headers=headers) def setUp(self): self.repository = "vanessa/container" self.image = os.path.abspath( os.path.join(here, "..", "examples", "singularity", "busybox_latest.sif") ) self.config = os.path.abspath( os.path.join(here, "..", "examples", "singularity", "config.json") ) # Read binary data and calculate sha256 digest with open(self.image, "rb") as fd: self.data = fd.read() self._digest = calculate_digest(self.data) self.digest = "sha256:%s" % self._digest def add_url_prefix(download_url): if not download_url.startswith("http"): download_url = "http://127.0.0.1:8000%s" % download_url return download_url
python
from _todefrost import package_md5sum md5 = None try: with open('/flash/package.md5') as f: md5 = f.read().strip() except Exception as e: pass if md5 != package_md5sum.md5sum: print("package md5 changed....defrosting...") from _todefrost import microwave microwave.defrost() import machine machine.reset()
python
#!/usr/bin/env python import pytest from clichain import cli, pipeline import click from click.testing import CliRunner import sys import ast import logging from difflib import SequenceMatcher def test_main_help(): tasks = cli.Tasks() args = ['--help'] result = cli.test(tasks, args) print('>> test_main_help #1:\n', result.output, file=sys.stderr) assert result.exit_code == 0 assert not result.exception ratio = SequenceMatcher(None, result.output, cli.usage()).ratio() assert ratio >= 0.8 def test_basic_single_task_help(): tasks = cli.Tasks() @tasks @click.command(name='compute') @click.option('--approximate', '-a', help='compute with approximation') @click.argument('y') def compute_task_cli(approximate, y): " divide data by 'y' " pass args = ['compute', '--help'] result = cli.test(tasks, args) print('>> test_basic_single_task_help #1:\n', result.output, file=sys.stderr) assert result.exit_code == 0 assert not result.exception usage = """\ Usage: _app compute [OPTIONS] Y divide data by 'y' Options: -a, --approximate TEXT compute with approximation --help Show this message and exit. """ ratio = SequenceMatcher(None, result.output, usage).ratio() assert ratio >= 0.8 def test_basic_single_sequence(): inputs = '1\n2\n3\n' tasks = cli.Tasks() @pipeline.task def compute_task(ctrl, y): with ctrl as push: while True: push((yield) / y) @pipeline.task def parse(ctrl): _parse = ast.literal_eval with ctrl as push: while True: try: push(_parse((yield))) except (SyntaxError, ValueError): pass @tasks @click.command(name='parse') def parse_cli(): " performs literal_eval on data " return parse() @tasks @click.command(name='compute') @click.option('--approximate', '-a', help='compute with approximation') @click.argument('y') def compute_task_cli(approximate, y): " divide data by 'y' " y = ast.literal_eval(y) if y == 0: raise click.BadParameter("can't devide by 0") if approximate: y = round(y) return compute_task(y) args = ['compute', '0'] result = cli.test(tasks, args, input=inputs, catch_exceptions=False) print('>> test_basic_single_sequence #1:\n', result.output, file=sys.stderr) usage = """\ Usage: _app compute [OPTIONS] Y Error: Invalid value: can't devide by 0 """ ratio = SequenceMatcher(None, result.output, usage).ratio() assert ratio >= 0.8 args = ['parse', 'compute', '10'] result = cli.test(tasks, args, input=inputs, catch_exceptions=False) print('>> test_basic_single_sequence #2:\n', result.output, file=sys.stderr) assert result.output == """\ 0.1 0.2 0.3 """ def _get_pipeline(args, inputs, err_msg=None): tasks = cli.Tasks() @pipeline.task def compute_task(ctrl, name, err): print(f'starting {name} (coroutine name: {ctrl.name})') with ctrl as push: while True: value = yield if isinstance(value, str) and '7' in value and err: raise RuntimeError(name if err_msg is None else err_msg) push(f'{value.strip()}->{name}') print(f'finished {name} (coroutine name: {ctrl.name})') @tasks @click.command(name='task') @click.argument('name') @click.option('--err', '-e', is_flag=True) def compute_task_cli(name, err): return compute_task(name, err) def test(): result = cli.test(tasks, args.split(), input=inputs, catch_exceptions=False) return result return test def test_pipeline_one_level_split_and_join(): """ +--> B --> C --+ inp >>> A--| +--> F >>> out +--> D --> E --+ =>> A [ B C , D E ] F """ inputs = '\n'.join('12345678') args = 'task A [ task B task C , task D task E ] task F' name = 'test_pipeline_one_level_split_and_join' test = _get_pipeline(args, inputs) result = test() output = result.output print(f'>> {name} #1:\n', output, file=sys.stderr) assert output == """\ starting F (coroutine name: 3) starting C (coroutine name: 1) starting E (coroutine name: 2) starting B (coroutine name: 1_0) starting D (coroutine name: 2_0) starting A (coroutine name: 0) 1->A->B->C->F 1->A->D->E->F 2->A->B->C->F 2->A->D->E->F 3->A->B->C->F 3->A->D->E->F 4->A->B->C->F 4->A->D->E->F 5->A->B->C->F 5->A->D->E->F 6->A->B->C->F 6->A->D->E->F 7->A->B->C->F 7->A->D->E->F 8->A->B->C->F 8->A->D->E->F finished A (coroutine name: 0) finished D (coroutine name: 2_0) finished B (coroutine name: 1_0) finished E (coroutine name: 2) finished C (coroutine name: 1) finished F (coroutine name: 3) """ def test_pipeline_two_levels_split_and_join(): """ +--> C1 --+ +--> B --| +-----+ | +--> C2 --+ | inp >>> A--| +--> F >>> out +--> D --> E ------------+ =>> A [ B [ C1 , C2 ] , D E ] F """ inputs = '\n'.join('12345678') args = 'task A [ task B [ task C1 , task C2 ] , task D task E ] task F' name = 'test_pipeline_two_levels_split_and_join' test = _get_pipeline(args, inputs) result = test() output = result.output print(f'>> {name} #1:\n', output, file=sys.stderr) assert output == """\ starting F (coroutine name: 5) starting C1 (coroutine name: 2) starting C2 (coroutine name: 3) starting E (coroutine name: 4) starting B (coroutine name: 1) starting D (coroutine name: 4_0) starting A (coroutine name: 0) 1->A->B->C1->F 1->A->B->C2->F 1->A->D->E->F 2->A->B->C1->F 2->A->B->C2->F 2->A->D->E->F 3->A->B->C1->F 3->A->B->C2->F 3->A->D->E->F 4->A->B->C1->F 4->A->B->C2->F 4->A->D->E->F 5->A->B->C1->F 5->A->B->C2->F 5->A->D->E->F 6->A->B->C1->F 6->A->B->C2->F 6->A->D->E->F 7->A->B->C1->F 7->A->B->C2->F 7->A->D->E->F 8->A->B->C1->F 8->A->B->C2->F 8->A->D->E->F finished A (coroutine name: 0) finished D (coroutine name: 4_0) finished B (coroutine name: 1) finished E (coroutine name: 4) finished C2 (coroutine name: 3) finished C1 (coroutine name: 2) finished F (coroutine name: 5) """ def test_pipeline_debug_name(caplog): """ +--> B --> C --+ inp >>> A--| +--> B >>> out +--> B --> D --+ #equivalent: =>> A { 'b1' [ B C , B D ] } B =>> A [ { 'b1' B C , B D } ] B =>> A [ { 'b1' B C , B D ] } B =>> A [ { 'b1' B C } , { 'b1' B D } ] B # =>> A [ { 'b1' B } C , { 'b1' B } D ] B #equivalent: =>> A { 'b1' [ B C , { 'b2' B } D ] } B =>> A [ { 'b1' B C } , { 'b2' B } { 'b1' D } ] B #no effect: =>> A [ { 'b1' } B , { 'b2' } B ] B """ inputs = '\n'.join('12345678') name = 'test_pipeline_debug_name' def _test(ex, i, args, stdout, err_name='{NAME}'): print('', file=sys.stderr) err_name = err_name.format(NAME=f'{ex}_{i}') args = args.format(NAME=f'{ex}_{i}') test = _get_pipeline(args, inputs, err_msg=err_name) result = test() # abort: assert isinstance(result.exception, SystemExit) assert result.exit_code == 1 print(f'\n>> {name}-{ex}#{i}: out:', file=sys.stderr) print(result.output, file=sys.stderr) assert result.output == stdout.format(NAME=f'{ex}_{i}') print(f'\n>> {name}-{ex}#{i}: logs:', file=sys.stderr) _logger = pipeline.logger.getChild(err_name) print(caplog.text, file=sys.stderr) assert any(map(lambda r: r.name == _logger.name and r.msg == "an exception occured:" and r.exc_info, caplog.records)) assert f"RuntimeError: {err_name}" in caplog.text # ---------------------------------------------------------------- # # equivalent: # =>> A { 'b1' [ B C , B D ] } B # =>> A [ { 'b1' B C , B D } ] B # =>> A [ { 'b1' B C , B D ] } B # =>> A [ { 'b1' B C } , { 'b1' B D } ] B # ---------------------------------------------------------------- # ex = 'ex_1' # ---------------------------------------------------------------- # args = [ 'task A {{ {NAME} [ task -e B task C , task B task D ] }} task B ', 'task A [ {{ {NAME} task -e B task C , task B task D }} ] task B', 'task A [ {{ {NAME} task -e B task C , task B task D ] }} task B', 'task A [ {{ {NAME} task -e B task C }} , {{ {NAME} task B task D }} ] task B', ] stdout = """\ starting B (coroutine name: 3) starting C (coroutine name: {NAME}) starting D (coroutine name: {NAME}) starting B (coroutine name: {NAME}) starting B (coroutine name: {NAME}) starting A (coroutine name: 0) 1->A->B->C->B 1->A->B->D->B 2->A->B->C->B 2->A->B->D->B 3->A->B->C->B 3->A->B->D->B 4->A->B->C->B 4->A->B->D->B 5->A->B->C->B 5->A->B->D->B 6->A->B->C->B 6->A->B->D->B finished B (coroutine name: {NAME}) finished D (coroutine name: {NAME}) finished C (coroutine name: {NAME}) finished B (coroutine name: 3) Aborted! """ for i, args in enumerate(args): _test(ex, i, args, stdout) # ---------------------------------------------------------------- # # =>> A [ { 'b1' B } C , { 'b1' B } D ] B # ---------------------------------------------------------------- # ex = 'ex_2' # ---------------------------------------------------------------- # args = [ 'task A [ {{ {NAME} task -e B }} task C , {{ {NAME} task B }} task D ] task B', ] stdout = """\ starting B (coroutine name: 3) starting C (coroutine name: 1) starting D (coroutine name: 2) starting B (coroutine name: {NAME}) starting B (coroutine name: {NAME}) starting A (coroutine name: 0) 1->A->B->C->B 1->A->B->D->B 2->A->B->C->B 2->A->B->D->B 3->A->B->C->B 3->A->B->D->B 4->A->B->C->B 4->A->B->D->B 5->A->B->C->B 5->A->B->D->B 6->A->B->C->B 6->A->B->D->B finished B (coroutine name: {NAME}) finished D (coroutine name: 2) finished C (coroutine name: 1) finished B (coroutine name: 3) Aborted! """ for i, args in enumerate(args): _test(ex, i, args, stdout) # ---------------------------------------------------------------- # # equivalent: # =>> A { 'b1' [ B C , { 'b2' B } D ] } B # =>> A [ { 'b1' B C } , { 'b2' B } { 'b1' D } ] B # ---------------------------------------------------------------- # ex = 'ex_3' # ---------------------------------------------------------------- # args = [ 'task A {{ {NAME} [ task -e B task C , {{ {NAME}_bis task B }} task D ] }} task B ', 'task A [ {{ {NAME} task -e B task C }} , {{ {NAME}_bis task B }} {{ {NAME} task D }} ] task B ', ] stdout = """\ starting B (coroutine name: 3) starting C (coroutine name: {NAME}) starting D (coroutine name: {NAME}) starting B (coroutine name: {NAME}) starting B (coroutine name: {NAME}_bis) starting A (coroutine name: 0) 1->A->B->C->B 1->A->B->D->B 2->A->B->C->B 2->A->B->D->B 3->A->B->C->B 3->A->B->D->B 4->A->B->C->B 4->A->B->D->B 5->A->B->C->B 5->A->B->D->B 6->A->B->C->B 6->A->B->D->B finished B (coroutine name: {NAME}_bis) finished D (coroutine name: {NAME}) finished C (coroutine name: {NAME}) finished B (coroutine name: 3) Aborted! """ for i, args in enumerate(args): _test(ex, i, args, stdout) # ---------------------------------------------------------------- # # =>> A [ { 'b1' } B , { 'b2' } B ] B # ---------------------------------------------------------------- # ex = 'ex_4' # ---------------------------------------------------------------- # args = [ 'task A [ {{ {NAME} }} task -e B , {{ {NAME} }} task B ] task B', ] stdout = """\ starting B (coroutine name: 3) starting B (coroutine name: 1) starting B (coroutine name: 2) starting A (coroutine name: 0) 1->A->B->B 1->A->B->B 2->A->B->B 2->A->B->B 3->A->B->B 3->A->B->B 4->A->B->B 4->A->B->B 5->A->B->B 5->A->B->B 6->A->B->B 6->A->B->B finished B (coroutine name: 2) finished B (coroutine name: 3) Aborted! """ for i, args in enumerate(args): _test(ex, i, args, stdout, err_name='1')
python
compiler = 'C:\\Users\\Public\\Documents\\Mikroelektronika\\mikroC PRO for PIC\\mikroCPIC1618.exe' settings = { 'cmdln0': '"{compiler}" -MSF -DBG -p{device} -GC -DL -O11111110 -fo{clock} -N"{project}" "{filename}"', 'cmdlnSP': '-SP"{path}"', 'cmdlnIP': '-IP"{path}"', 'cmdlnLIBS': '"__Lib_Math.mcl" "__Lib_MathDouble.mcl" "__Lib_System.mcl" "__Lib_Delays.mcl" "__Lib_CType.mcl" "__Lib_CString.mcl" "__Lib_CStdlib.mcl" "__Lib_CMath.mcl" "__Lib_MemManager.mcl" "__Lib_Conversions.mcl" "__Lib_Sprinti.mcl" "__Lib_Sprintl.mcl" "__Lib_Time.mcl" "__Lib_Trigonometry.mcl" "__Lib_Button.mcl" "__Lib_Keypad4x4.mcl" "__Lib_Manchester.mcl" "__Lib_OneWire.mcl" "__Lib_PS2.mcl" "__Lib_Sound.mcl" "__Lib_SoftI2C.mcl" "__Lib_SoftSPI.mcl" "__Lib_SoftUART.mcl" "__Lib_ADC_A_C.mcl" "__Lib_EEPROM.mcl" "__Lib_FLASH_RW.mcl" "__Lib_I2C_c34.mcl" "__Lib_PWM_c21.mcl" "__Lib_SPI_c345.mcl" "__Lib_UART_c67.mcl" "__Lib_PortExpander.mcl" "__Lib_CANSPI.mcl" "__Lib_CF.mcl" "__Lib_GlcdFonts.mcl" "__Lib_Glcd.mcl" "__Lib_LcdConsts.mcl" "__Lib_Lcd.mcl" "__Lib_RS485.mcl" "__Lib_S1D13700.mcl" "__Lib_T6963C.mcl" "__Lib_SPIGlcd.mcl" "__Lib_SPILcd.mcl" "__Lib_SPILcd8.mcl" "__Lib_SPIT6963C.mcl" "__Lib_EthEnc28j60.mcl" "__Lib_EthEnc24j600.mcl" "__Lib_TouchPanel.mcl"' }
python
from rest_framework import serializers from .models import Post, Category class BlogCategorySerializer(serializers.ModelSerializer): class Meta: model = Category fields = [ 'name', 'created_at', 'updated_at', ] class BlogPostSerializer(serializers.ModelSerializer): class Meta: model = Post fields = [ 'title', 'description', 'body', 'thumb', 'category', 'author', 'created_at', 'updated_at', 'published', ]
python
from dictpy.dict_search import DictSearch from dictpy.serializer import Serializer __all__ = ["DictSearch", "Serializer"]
python
import pandas as pd class TrainDataSampler: def name(self): raise NotImplementedError def sample(self, df): raise NotImplementedError class CompleteData(TrainDataSampler): def name(self): return 'complete_data' def sample(self, df): return df class BalancedExamplesSampler(TrainDataSampler): def __init__(self, label_name, positive_label, n, random_state): super().__init__() self.label_name = label_name self.positive_label = positive_label self.n = n self.random_state = random_state def name(self): return 'balanced_data_{}'.format(self.n) def sample(self, df): examples_per_class = int(self.n / 2) positive = df[df[self.label_name] == self.positive_label].sample(n=examples_per_class, random_state=self.random_state) negative = df[df[self.label_name] != self.positive_label].sample(n=examples_per_class, random_state=self.random_state) return pd.concat([positive, negative])
python
from unbillit_project import app if __name__ == '__main__': app.run(host='127.0.0.1', port=8000, debug=True) ############## set envirnment variable for secret key ############# # Add password strength validators later to user/form.py # work on putting everything together # implement password reset functionality with firebase # email verification with firebase # google OAuth # facebook OAuth # add contact us page to also send email to an admin # generate reqiurement.txt # flask admin functionality
python
import psycopg2 import pandas as pd import numpy as np import pickle import matplotlib.pyplot as plt from numpy import random from sklearn.preprocessing import StandardScaler import os os.chdir('/home/rafalb/work/molecules/chemicalSmilesSpace/src') from keras.layers import LSTM, TimeDistributed, concatenate, Input, Dense, RepeatVector, Lambda from keras.models import Model from keras.activations import relu, sigmoid, tanh from keras.callbacks import EarlyStopping, ModelCheckpoint from keras.optimizers import Adam, RMSprop import keras.backend as K from keras.utils import plot_model from keras import losses import numpy.random as rnd def sampling(args): z_mean, z_log_var = args batch = K.shape(z_mean)[0] dim = K.int_shape(z_mean)[1] # by default, random_normal has mean=0 and std=1.0 epsilon = K.random_normal(shape=(batch, dim)) return z_mean + K.exp(0.5 * z_log_var) * epsilon def prepare_model(static, dynamic, k, window, charsetLen, lr, lossFunction, showArch): input_dynamic = Input(shape=(window, charsetLen), name="input_dynamic") input_static = Input(shape=(static,), name="input_static") latent = Dense(k[0], activation=relu)(input_static) dense_h = Dense(k[0])(latent) dense_c = Dense(k[0])(latent) lstm_layer, state_h, state_c = LSTM(k[0], return_sequences=True, return_state=True)(input_dynamic, initial_state=[dense_h, dense_c]) for x in k[1:-1]: concat_h = concatenate([dense_h, state_h]) dense_h = Dense(x)(concat_h) concat_c = concatenate([dense_c, state_c]) dense_c = Dense(x)(concat_c) lstm_layer, state_h, state_c = LSTM(x, return_sequences=True, return_state=True)(lstm_layer, initial_state=[dense_h, dense_c]) x = k[-1] concat_h = concatenate([dense_h, state_h]) dense_h = Dense(x)(concat_h) concat_c = concatenate([dense_c, state_c]) dense_c = Dense(x)(concat_c) lstm_layer, state_h, state_c = LSTM(x, return_state=True)(lstm_layer, initial_state=[dense_h, dense_c]) concat = concatenate([lstm_layer, latent]) # autoencoder z_mean = Dense(x, name='z_mean')(concat) z_log_var = Dense(x, name='z_log_var')(concat) z = Lambda(sampling, output_shape=(x,), name='z')([z_mean, z_log_var]) state_h = Dense(k[-2], activation=relu)(z) dense_h = Dense(k[-2], activation=relu)(z) state_c = Dense(k[-2], activation=relu)(z) dense_c = Dense(k[-2], activation=relu)(z) lstm_layer = RepeatVector(window)(z) for x in np.flip(k[:-1]): concat_h = concatenate([dense_h, state_h]) dense_h = Dense(x)(concat_h) concat_c = concatenate([dense_c, state_c]) dense_c = Dense(x)(concat_c) lstm_layer, state_h, state_c = LSTM(x, return_sequences=True, return_state=True)(lstm_layer, initial_state=[dense_h, dense_c]) #result_series = TimeDistributed(Dense(charsetLen))(lstm_layer) result_series = LSTM(charsetLen, return_sequences=True, activation='softmax')(lstm_layer) concat = concatenate([state_h, state_c]) #result_sigmoid = Dense(static-3, activation=sigmoid)(concat) result_relu = Dense(static, activation=sigmoid)(concat) #model = Model(inputs=[input_dynamic, input_static], outputs=[result_series, result_sigmoid, result_relu]) model = Model(inputs=[input_dynamic, input_static], outputs=[result_series, result_relu]) optimizer = RMSprop(lr=lr) model.compile(optimizer=optimizer, loss=lossFunction, metrics=['binary_crossentropy', 'mean_absolute_error']) if (showArch): print(model.summary()) return model def prepareModelOnlyDynamic(dynamicDim, k, lr, lossFunction, showArch): input_dynamic = Input(shape=(dynamicDim[1], dynamicDim[2]), name="inputDynamic") lstm_layer, state_h, state_c = LSTM(k[0], return_sequences=True, return_state=True)(input_dynamic) for x in k[1:-1]: lstm_layer, state_h, state_c = LSTM(x, return_sequences=True, return_state=True)(lstm_layer) x = k[-1] lstm_layer, state_h, state_c = LSTM(x, return_state=True)(lstm_layer) # autoencoder z_mean = Dense(x, name='z_mean')(lstm_layer) z_log_var = Dense(x, name='z_log_var')(lstm_layer) z = Lambda(sampling, output_shape=(x,), name='z')([z_mean, z_log_var]) lstm_layer = RepeatVector(dynamicDim[1])(z) for x in np.flip(k[:-1]): lstm_layer, state_h, state_c = LSTM(x, return_sequences=True, return_state=True)(lstm_layer) #result_series = TimeDistributed(Dense(charsetLen))(lstm_layer) result_series = LSTM(dynamicDim[2], return_sequences=True, activation='softmax')(lstm_layer) #model = Model(inputs=[input_dynamic, input_static], outputs=[result_series, result_sigmoid, result_relu]) model = Model(inputs=[input_dynamic], outputs=[result_series]) optimizer = RMSprop(lr=lr) model.compile(optimizer=optimizer, loss=lossFunction, metrics=['binary_crossentropy', 'mean_absolute_error']) if (showArch): print(model.summary()) return model def prepareEncoder(nCharInSmiles, nCharSet, nStatic, k, lr, lossFunction, showArch): input_dynamic = Input(shape=(nCharInSmiles, nCharSet), name="inputDynamic") input_static = Input(shape=(nStatic,), name="inputStatic") latent = Dense(k[0], activation=relu)(input_static) dense_h = Dense(k[0])(latent) dense_c = Dense(k[0])(latent) encoder, state_h, state_c = LSTM(k[0], return_sequences=True, return_state=True)(input_dynamic, initial_state=[dense_h, dense_c]) for x in k[1:-1]: concat_h = concatenate([dense_h, state_h]) dense_h = Dense(x)(concat_h) concat_c = concatenate([dense_c, state_c]) dense_c = Dense(x)(concat_c) encoder, state_h, state_c = LSTM(x, return_sequences=True, return_state=True)(encoder, initial_state = [dense_h, dense_c]) x = k[-1] concat_h = concatenate([dense_h, state_h]) dense_h = Dense(x)(concat_h) concat_c = concatenate([dense_c, state_c]) dense_c = Dense(x)(concat_c) encoder, state_h, state_c = LSTM(x, return_state=True)(encoder, initial_state=[dense_h, dense_c]) concat = concatenate([encoder, latent]) # autoencoder z_mean = Dense(x, name='z_mean')(concat) z_log_var = Dense(x, name='z_log_var')(concat) z = Lambda(sampling, output_shape=(x,), name='encoderOutput')([z_mean, z_log_var]) #state_h = Dense(k[-2], activation=relu)(z) #dense_h = Dense(k[-2], activation=relu)(z) #state_c = Dense(k[-2], activation=relu)(z) #dense_c = Dense(k[-2], activation=relu)(z) #encoder = RepeatVector(dynamicDim[1])(z) model = Model(inputs=[input_dynamic, input_static], outputs=[z]) if (showArch): print(model.summary()) return model def prepareDecoder(nCharInSmiles, nCharSet, nStatic, k, lr, lossFunction, showArch): decoderInput = Input(shape=(k[-1],), name="decoderInput") state_h = Dense(k[-2], activation=relu, name='ini_state_h')(decoderInput) dense_h = Dense(k[-2], activation=relu, name='ini_dense_h')(decoderInput) state_c = Dense(k[-2], activation=relu, name='ini_state_c')(decoderInput) dense_c = Dense(k[-2], activation=relu, name='ini_dense_c')(decoderInput) decoder = RepeatVector(nCharInSmiles, name='repeat')(decoderInput) for x in np.flip(k[:-1]): concat_h = concatenate([dense_h, state_h]) dense_h = Dense(x)(concat_h) concat_c = concatenate([dense_c, state_c]) dense_c = Dense(x)(concat_c) decoder, state_h, state_c = LSTM(x, return_sequences=True, return_state=True)(decoder) #result_series = TimeDistributed(Dense(charsetLen))(lstm_layer) resultDynamic = LSTM(nCharSet, return_sequences=True, activation='softmax', name = 'outputDynamic')(decoder) concat = concatenate([state_h, state_c]) resultStatic = Dense(nStatic, activation=sigmoid, name = 'outputStatic')(concat) model = Model(inputs=[decoderInput], outputs=[resultDynamic, resultStatic]) if (showArch): print(model.summary()) return model #def prepareAutoencoder() # #model = Model(inputs=[input_dynamic, input_static], outputs=[result_series, result_sigmoid, result_relu]) # model = Model(inputs=[input_dynamic, input_static], outputs=[result_series, result_static]) # optimizer = RMSprop(lr=lr) # model.compile(optimizer=optimizer, loss=lossFunction, metrics=['binary_crossentropy', 'mean_absolute_error']) # if (showArch): # print(model.summary()) # return model def prepareModelDynamicStatic(dynamicDim, staticDim, k, lr, lossFunction, showArch): input_dynamic = Input(shape=(dynamicDim[1], dynamicDim[2]), name="inputDynamic") input_static = Input(shape=(staticDim[1],), name="inputStatic") latent = Dense(k[0], activation=relu)(input_static) dense_h = Dense(k[0])(latent) dense_c = Dense(k[0])(latent) lstm_layer, state_h, state_c = LSTM(k[0], return_sequences=True, return_state=True)(input_dynamic, initial_state=[dense_h, dense_c]) for x in k[1:-1]: concat_h = concatenate([dense_h, state_h]) dense_h = Dense(x)(concat_h) concat_c = concatenate([dense_c, state_c]) dense_c = Dense(x)(concat_c) lstm_layer, state_h, state_c = LSTM(x, return_sequences=True, return_state=True)(lstm_layer, initial_state = [dense_h, dense_c]) x = k[-1] concat_h = concatenate([dense_h, state_h]) dense_h = Dense(x)(concat_h) concat_c = concatenate([dense_c, state_c]) dense_c = Dense(x)(concat_c) lstm_layer, state_h, state_c = LSTM(x, return_state=True)(lstm_layer, initial_state=[dense_h, dense_c]) concat = concatenate([lstm_layer, latent]) #lstm_layer, state_h, state_c = LSTM(x, return_state=True)(lstm_layer) # autoencoder z_mean = Dense(x, name='z_mean')(concat) z_log_var = Dense(x, name='z_log_var')(concat) z = Lambda(sampling, output_shape=(x,), name='z')([z_mean, z_log_var]) state_h = Dense(k[-2], activation=relu)(z) dense_h = Dense(k[-2], activation=relu)(z) state_c = Dense(k[-2], activation=relu)(z) dense_c = Dense(k[-2], activation=relu)(z) lstm_layer = RepeatVector(dynamicDim[1])(z) for x in np.flip(k[:-1]): lstm_layer, state_h, state_c = LSTM(x, return_sequences=True, return_state=True)(lstm_layer) #result_series = TimeDistributed(Dense(charsetLen))(lstm_layer) result_series = LSTM(dynamicDim[2], return_sequences=True, activation='softmax', name = 'outputDynamic')(lstm_layer) concat = concatenate([state_h, state_c]) result_static = Dense(staticDim[1], activation=sigmoid, name = 'outputStatic')(concat) #model = Model(inputs=[input_dynamic, input_static], outputs=[result_series, result_sigmoid, result_relu]) model = Model(inputs=[input_dynamic, input_static], outputs=[result_series, result_static]) optimizer = RMSprop(lr=lr) model.compile(optimizer=optimizer, loss=lossFunction, metrics=['binary_crossentropy', 'mean_absolute_error']) if (showArch): print(model.summary()) return model def fit(staticFeatures, dynamicFeatures, model, step=1): #dynamic_data = np.empty((0, window, 1), np.float) #helper = [] #for d in dynamic: # new_data = rolling_window(d, window, step) # helper.append(len(new_data)) # dynamic_data = np.append(dynamic_data, new_data, axis=0) #print(len(helper)) #static_data = np.repeat(static, helper, axis=0) order = rnd.permutation(len(staticFeatures)) early_stopping = EarlyStopping(monitor='val_loss', patience=5) bst_model_path = 'autoencoder.h5' checkpoint = ModelCheckpoint(bst_model_path, save_best_only=True, save_weights_only=True, monitor='val_loss') size = int(staticFeaturesSta.shape[0] * 0.9) training_dynamic, training_static = dynamicFeatures[order[:size]], staticFeatures[order[:size]] testing_dynamic, testing_static = dynamicFeatures[order[size:]], staticFeatures[order[size:]] print(training_dynamic.shape, training_static.shape) print(testing_dynamic.shape, testing_static.shape) model.fit([training_dynamic, training_static], [training_dynamic, training_static], epochs=10, batch_size=64, callbacks=[early_stopping, checkpoint], validation_data=([testing_dynamic, testing_static], [testing_dynamic, testing_static])) def fitOnlyDynamic(dynamicFeatures, model, step=1): order = rnd.permutation(len(staticFeatures)) early_stopping = EarlyStopping(monitor='val_loss', patience=5) bst_model_path = 'autoencoder.h5' checkpoint = ModelCheckpoint(bst_model_path, save_best_only=True, save_weights_only=True, monitor='val_loss') size = int(dynamicFeatures.shape[0] * 0.9) training_dynamic = dynamicFeatures[order[:size]] testing_dynamic = dynamicFeatures[order[size:]] print(training_dynamic.shape) print(testing_dynamic.shape) model.fit(training_dynamic, training_dynamic, epochs=10, batch_size=64, callbacks=[early_stopping, checkpoint], validation_data=(testing_dynamic, testing_dynamic)) def fitDynamicStatic(dynamicFeatures, staticFeatures, model, modelFilePath, nEpoch, nBatch): order = rnd.permutation(len(staticFeatures)) early_stopping = EarlyStopping(monitor='val_loss', patience=3) checkpoint = ModelCheckpoint(modelFilePath, save_best_only=True, save_weights_only=True, monitor='val_loss') size = int(staticFeatures.shape[0] * 0.9) training_dynamic, training_static = dynamicFeatures[order[:size]], staticFeatures[order[:size]] testing_dynamic, testing_static = dynamicFeatures[order[size:]], staticFeatures[order[size:]] print(training_dynamic.shape, training_static.shape) print(testing_dynamic.shape, testing_static.shape) model.fit([training_dynamic, training_static], [training_dynamic, training_static], epochs=nEpoch, batch_size=nBatch, callbacks=[early_stopping, checkpoint], validation_data=([testing_dynamic, testing_static], [testing_dynamic, testing_static])) def pad_smile(string, max_len, padding='right'): if len(string) <= max_len: if padding == 'right': return string + " " * (max_len - len(string)) elif padding == 'left': return " " * (max_len - len(string)) + string elif padding == 'none': return string def prepareData(dataFile, nSample, doPlot = False): with open(dataFile, 'rb') as file: molDataGroupedChosen = pickle.load(file) #nSmilesCodes = 200000 nSmilesMore = np.min([molDataGroupedChosen.shape[0], int(1.2*nSample)]) mask = random.randint(0, molDataGroupedChosen.shape[0], size = nSmilesMore) #mask = random.randint(0, molDataGroupedChosen.shape[0], size=nSmilesCodes) mask = molDataGroupedChosen.index staticFeatures = pd.DataFrame() toBeAveraged = ['standard_value', 'alogp', 'hba', 'hbd', 'psa', 'rtb', 'full_mwt', 'qed_weighted'] for quantity in toBeAveraged: staticFeatures.loc[:, quantity] = (molDataGroupedChosen.loc[mask, (quantity, 'min')] + molDataGroupedChosen.loc[mask, (quantity, 'max')])/2 staticFeatures.loc[:, quantity].astype(float) toBeTaken = ['aromatic_rings', 'heavy_atoms'] for quantity in toBeTaken: staticFeatures.loc[:, quantity] = molDataGroupedChosen.loc[mask, (quantity, 'min')] staticFeatures.loc[:, quantity].astype(float) staticFeatures.loc[:, 'number_of_rings'] = molDataGroupedChosen.loc[mask, 'numberOfRings'].astype(float) staticFeatures['full_mwt'] = staticFeatures.full_mwt.astype(float) staticFeatures['qed_weighted'] = staticFeatures.qed_weighted.astype(float) staticFeatures['aromatic_rings'] = staticFeatures.aromatic_rings.astype(float) staticFeatures['smiles_length'] = molDataGroupedChosen.loc[staticFeatures.index, 'canonicalSmiles'].apply(lambda x: len(x)) # Remove rows with nans staticFeatures = staticFeatures.dropna() # Filter the smiles from given length range staticFeatures = staticFeatures[(staticFeatures['smiles_length'] >= 40) & (staticFeatures['smiles_length'] <= 60)] thres = 100000 print(staticFeatures[staticFeatures['standard_value'] < thres].shape[0] / staticFeatures['standard_value'].shape[0]) staticFeatures = staticFeatures[staticFeatures['standard_value'] < thres] staticFeatures = staticFeatures.sample(nSample) allDescriptors = ['standard_value', 'alogp', 'hba', 'hbd', 'psa', 'rtb', 'full_mwt', 'qed_weighted', 'aromatic_rings', 'heavy_atoms', 'number_of_rings', 'smiles_length'] if (doPlot): plotIdx = 1 nRows = np.ceil(len(allDescriptors) / 2) fig = plt.figure(figsize=(16, 16)) for quantity in allDescriptors: print(quantity) plt.subplot(nRows, 2, plotIdx) plt.hist(staticFeatures[~staticFeatures[quantity].isnull()][quantity], bins = 10) plt.title(quantity) plotIdx += 1 smilesCodes = molDataGroupedChosen.loc[staticFeatures.index, 'encodedSmiles'] maxlen = -1 for code in smilesCodes: if len(code) > maxlen: maxlen = len(code) maxlen minlen = 1e6 for code in smilesCodes: if len(code) < minlen: minlen = len(code) minlen # pad the codes to the longest code smilesCodes = smilesCodes.apply(lambda x: pad_smile(x, max_len=maxlen, padding='right')) chars = sorted(list(set(smilesCodes.str.cat(sep='')))) print('total chars:', len(chars)) print(chars) char2indices = dict((c, i) for i, c in enumerate(chars)) indices2char = dict((i, c) for i, c in enumerate(chars)) dynamicFeatures = np.zeros((len(smilesCodes), maxlen, len(chars)), dtype=np.float) print(dynamicFeatures.shape) for codeidx, code in enumerate(smilesCodes): for charidx, char in enumerate(code): dynamicFeatures[codeidx, charidx, char2indices[char]] = 1 if (doPlot): sums = [] for idx in range(dynamicFeatures.shape[0]): sums.append(np.sum(dynamicFeatures[idx, :, :])) plt.hist(sums) return staticFeatures, dynamicFeatures def scaleFeatures(staticFeatures): # Choose some subset of dynamicFeatures scaler = StandardScaler() scaler.fit(staticFeatures) return scaler.transform(staticFeatures, ), scaler def loadDecoder(nCharInSmiles, nCharSet, nStatic, modelFile): lr = 0.001 encoder = prepareEncoder(nCharInSmiles, nCharSet, nStatic, [64,64,64,64,32], lr, ['binary_crossentropy', 'mean_absolute_error'], True) decoder = prepareDecoder(nCharInSmiles, nCharSet, nStatic, [64,64,64,64,32], lr, ['binary_crossentropy', 'mean_absolute_error'], True) encoderOutput = encoder.get_layer('encoderOutput').output decoderOutput = decoder(encoderOutput) autoencoder = Model(inputs=encoder.input, outputs=decoderOutput) autoencoder.load_weights(modelFile) decoder.load_weights(modelFile, by_name=True) return decoder def predictStaticDynamic(decoder): latentVector = [random.random() for iii in range(32)] latentVector = np.array(latentVector).reshape(-1, 32) prediction = decoder.predict(latentVector) return(prediction) if __name__ == '__main__': import argparse #from tabulate import tabulate from pathlib import Path import predictiveModel parser = argparse.ArgumentParser( description='OpenMM simulation.', epilog='Examplary usage: python simulate.py -sys mysystem -msteps 500 -ssteps 5000 -ffreq 100 -nthreads 8', formatter_class=argparse.RawTextHelpFormatter ) parser.add_argument('-modelFile', action='store', dest='modelFile', required=False, type=str, help='Resulting model file') parser.add_argument('-modelMetaInformation', action='store', dest='modelMetaInformation', required=False, type=str, help='Resulting model file') parser.add_argument('-v', '--version', action='version', version='parseAutoDockFiles.py v. 1.0') args = parser.parse_args() predictiveModel = predictiveModel.unpicklePredictiveModel(args.modelMetaInformation) # with open('predictiveModel646432_20191027.pckl') as f: # predictiveModel = pickle.load(f) nCharInSmiles = predictiveModel['nCharSmiles'] nCharSet = predictiveModel['nCharSet'] nStatic = predictiveModel['nStatic'] decoder = loadDecoder(nCharInSmiles, nCharSet, nStatic, args.modelFile) prediction = predictStaticDynamic(decoder)
python
from django.db import models class Contact(models.Model): first_name = models.CharField(null=False, blank=False, max_length=50) last_name = models.CharField(null=False, blank=False, max_length=50) email = models.CharField(null=False, blank=False, max_length=50) ip = models.CharField(null=False, blank=False, max_length=50) lat = models.CharField(null=False, blank=False, max_length=50) lng = models.CharField(null=False, blank=False, max_length=50)
python
""" Provides animated GIF images of weather-radar imagery derived the Australian Bureau of Meteorology (http://www.bom.gov.au/australia/radar/). """ import datetime as dt import io import logging import os import re import time import PIL.Image import requests # Legend: # # NSW: http://www.bom.gov.au/australia/radar/nsw_radar_sites_table.shtml # NT: http://www.bom.gov.au/australia/radar/nt_radar_sites_table.shtml # QLD: http://www.bom.gov.au/australia/radar/qld_radar_sites_table.shtml # SA: http://www.bom.gov.au/australia/radar/sa_radar_sites_table.shtml # TAS: http://www.bom.gov.au/australia/radar/tas_radar_sites_table.shtml # VIC: http://www.bom.gov.au/australia/radar/vic_radar_sites_table.shtml # WA: http://www.bom.gov.au/australia/radar/wa_radar_sites_table.shtml # # res: 1 => 512km, 2 => 256km, 3 => 128km, 4 => 64km # fmt: off RADARS = { "Adelaide": {"id": "64", "res": (1, 2, 3, 4)}, # Adelaide (Buckland Park) [SA] "Albany": {"id": "31", "res": (1, 2, 3, 4)}, # Albany [WA] "AliceSprings": {"id": "25", "res": (1, 2, 3)}, # Alice Springs [NT] "Bairnsdale": {"id": "68", "res": (1, 2, 3)}, # Bairnsdale [VIC] "Bowen": {"id": "24", "res": (1, 2, 3)}, # Bowen [QLD] "Brisbane": {"id": "66", "res": (1, 2, 3, 4)}, # Brisbane (Mt Stapylton) [QLD] "Broome": {"id": "17", "res": (1, 2, 3)}, # Broome [WA] "Cairns": {"id": "19", "res": (1, 2, 3, 4)}, # Cairns [QLD] "Canberra": {"id": "40", "res": (1, 2, 3, 4)}, # Canberra (Captains Flat) [NSW] "Carnarvon": {"id": "05", "res": (1, 2, 3)}, # Carnarvon [WA] "Ceduna": {"id": "33", "res": (1, 2, 3)}, # Ceduna [SA] "Dampier": {"id": "15", "res": (1, 2, 3)}, # Dampier [WA] "Darwin": {"id": "63", "res": (1, 2, 3, 4)}, # Darwin (Berrimah) [NT] "Emerald": {"id": "72", "res": (1, 2, 3, 4)}, # Emerald [QLD] "Esperance": {"id": "32", "res": (1, 2, 3, 4)}, # Esperance [WA] "Geraldton": {"id": "06", "res": (1, 2, 3, 4)}, # Geraldton [WA] "Giles": {"id": "44", "res": (1, 2, 3)}, # Giles [WA] "Gladstone": {"id": "23", "res": (1, 2, 3)}, # Gladstone [QLD] "Gove": {"id": "09", "res": (1, 2, 3)}, # Gove [NT] "Grafton": {"id": "28", "res": (1, 2, 3)}, # Grafton [NSW] "Gympie": {"id": "08", "res": (1, 2, 3, 4)}, # Gympie (Mt Kanigan) [QLD] "HallsCreek": {"id": "39", "res": (1, 2, 3)}, # Halls Creek [WA] "Hobart": {"id": "76", "res": (1, 2, 3, 4)}, # Hobart (Mt Koonya) [TAS] "Kalgoorlie": {"id": "48", "res": (1, 2, 3, 4)}, # Kalgoorlie [WA] "Katherine": {"id": "42", "res": (1, 2, 3)}, # Katherine (Tindal) [NT] "Learmonth": {"id": "29", "res": (1, 2, 3)}, # Learmonth [WA] "Longreach": {"id": "56", "res": (1, 2, 3)}, # Longreach [QLD] "Mackay": {"id": "22", "res": (1, 2, 3)}, # Mackay [QLD] "Marburg": {"id": "50", "res": (1, 2, 3)}, # Brisbane (Marburg) [QLD] "Melbourne": {"id": "02", "res": (1, 2, 3, 4)}, # Melbourne [VIC] "Mildura": {"id": "30", "res": (1, 2, 3)}, # Mildura [VIC] "Moree": {"id": "53", "res": (1, 2, 3)}, # Moree [NSW] "MorningtonIs": {"id": "36", "res": (1, 2, 3)}, # Gulf of Carpentaria (Mornington Is) [QLD] "MountIsa": {"id": "75", "res": (1, 2, 3, 4)}, # Mount Isa [QLD] "MtGambier": {"id": "14", "res": (1, 2, 3)}, # Mt Gambier [SA] "Namoi": {"id": "69", "res": (1, 2, 3, 4)}, # Namoi (Blackjack Mountain) [NSW] "Newcastle": {"id": "04", "res": (1, 2, 3, 4)}, # Newcastle [NSW] "Newdegate": {"id": "38", "res": (1, 2, 3, 4)}, # Newdegate [WA] "NorfolkIs": {"id": "62", "res": (1, 2, 3)}, # Norfolk Island [ET] "NWTasmania": {"id": "52", "res": (1, 2, 3, 4)}, # N.W. Tasmania (West Takone) [TAS] "Perth": {"id": "70", "res": (1, 2, 3, 4)}, # Perth (Serpentine) [WA] "PortHedland": {"id": "16", "res": (1, 2, 3)}, # Pt Hedland [WA] "Rainbow": {"id": "95", "res": (1, 2, 3, 4)}, # Rainbow [VIC] "SellicksHill": {"id": "46", "res": (1, 2, 3)}, # Adelaide (Sellicks Hill) [SA] "SouthDoodlakine": {"id": "58", "res": (1, 2, 3, 4)}, # South Doodlakine [WA] "Sydney": {"id": "71", "res": (1, 2, 3, 4)}, # Sydney (Terrey Hills) [NSW] "Townsville": {"id": "73", "res": (1, 2, 3, 4)}, # Townsville (Hervey Range) [QLD] "WaggaWagga": {"id": "55", "res": (1, 2, 3)}, # Wagga Wagga [NSW] "Warrego": {"id": "67", "res": (1, 2, 3)}, # Warrego [QLD] "Warruwi": {"id": "77", "res": (1, 2, 3, 4)}, # Warruwi [NT] "Watheroo": {"id": "79", "res": (1, 2, 3, 4)}, # Watheroo [WA] "Weipa": {"id": "78", "res": (1, 2, 3, 4)}, # Weipa [QLD] "WillisIs": {"id": "41", "res": (1, 2, 3)}, # Willis Island [QLD] "Wollongong": {"id": "03", "res": (1, 2, 3, 4)}, # Wollongong (Appin) [NSW] "Woomera": {"id": "27", "res": (1, 2, 3)}, # Woomera [SA] "Wyndham": {"id": "07", "res": (1, 2, 3)}, # Wyndham [WA] "Yarrawonga": {"id": "49", "res": (1, 2, 3, 4)}, # Yarrawonga [VIC] } # fmt: on DEFAULT_RESOLUTION = "3" # Consider using http://reg.bom.gov.au/catalogue/data-feeds.shtml#radar HEADERS = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.169 Safari/537.36"} class BOMRadarLoop: """ The class to be instantiated by Home Assistant """ def __init__(self, location=None, radar_id=None, outfile=None, logger=None): self._log = logger or logging.getLogger(__name__) if isinstance(radar_id, int): radar_id = "%03d" % radar_id valids = ", ".join(sorted(RADARS.keys())) if not radar_id and location not in RADARS: location = "Sydney" self._log.error("Bad 'location' specified, using '%s' (valid locations are: %s)", location, valids) if radar_id: if location in RADARS: radar_id = None self._log.error("Valid 'location' specified, ignoring 'radar_id'") elif location: self._log.error("Bad 'location' specified, using ID %s (valid locations are: %s)", radar_id, valids) self._location = location or "ID %s" % radar_id self._radar_id = radar_id or "%s%s" % (RADARS[location]["id"], DEFAULT_RESOLUTION) self._outfile = outfile self._t0 = 0 self._current = self.current # Public methods @property def current(self): """ Return the current BOM radar-loop image. """ now = int(time.time()) t1 = now - (now % 300) # update every 5 minutes if t1 > self._t0: self._t0 = t1 self._current = self._loop return self._current # Private methods @property def _background(self): """ Fetch the background map, then the topography, locations (e.g. city names), and distance-from-radar range markings, and merge into a single image. """ self._log.debug("Getting background for %s at %s", self._location, self._t0) suffix = "products/radar_transparencies/IDR%s.background.png" url = self._url(suffix % self._radar_id) background = self._image(url) if background is None: return None for layer in ("topography", "locations", "range"): self._log.debug("Getting %s for %s at %s", layer, self._location, self._t0) suffix = "products/radar_transparencies/IDR%s.%s.png" % (self._radar_id, layer) url = self._url(suffix) image = self._image(url) if image is not None: try: background = PIL.Image.alpha_composite(background, image) except ValueError: pass return background @property def _frames(self): """ Fetch a radar image for each expected time, composite it with a common background image, then overlay on the legend to produce a frame. Collect and return the frames, ignoring any blanks. If no frames were produced, return None (the caller must expect this). """ self._log.debug("Getting frames for %s at %s", self._location, self._t0) bg = self._background legend = self._legend frames = [] if bg and legend: for image_name in self._image_names: fg = self._image(self._url(image_name)) if fg is not None: frames.append(legend.copy()) frames[-1].paste(PIL.Image.alpha_composite(bg, fg), (0, 0)) return frames def _image(self, url): """ Fetch an image from the BOM. """ self._log.debug("Getting image %s", url) response = requests.get(url, headers=HEADERS) if response.status_code == 200: log_level = self._log.level self._log.setLevel(logging.INFO) image = PIL.Image.open(io.BytesIO(response.content)) rgba_img = image.convert("RGBA") image.close() self._log.setLevel(log_level) return rgba_img return None @property def _image_names(self): """ Return the currently available frame images for the given radar, extracted from the BOM's HTML. """ url = self._url("products/IDR%s.loop.shtml" % self._radar_id) response = requests.get(url, headers=HEADERS) image_names = [] if response.status_code != 200: return image_names pattern = r'^theImageNames\[\d+\] = "/(radar/IDR\d{3}\.T\.\d{12}\.png)";$' for line in response.text.split("\n"): m = re.match(pattern, line) if m: image_names.append(m.groups()[0]) return sorted(image_names) @property def _legend(self): """ Fetch the BOM colorbar legend image. """ self._log.debug("Getting legend at %s", self._t0) url = self._url("products/radar_transparencies/IDR.legend.0.png") return self._image(url) @property def _loop(self): """ Return an animated GIF comprising a set of frames, where each frame includes a background, one or more supplemental layers, a colorbar legend, and a radar image. """ self._log.info("Getting loop for %s at %s", self._location, self._t0) loop = io.BytesIO() frames = self._frames if frames: self._log.debug("Got %s frames for %s at %s", len(frames), self._location, self._t0) frames[0].save( loop, append_images=frames[1:], duration=500, format="GIF", loop=0, save_all=True, ) else: self._log.warning("Got NO frames for %s at %s", self._location, self._t0) PIL.Image.new("RGB", (512, 557)).save(loop, format="GIF") if self._outfile: outdir = os.path.dirname(self._outfile) if not os.path.isdir(outdir): try: os.makedirs(outdir) except OSError: self._log.error("Could not create directory %s", outdir) try: with open(self._outfile, "wb") as outfile: outfile.write(loop.getvalue()) except IOError: self._log.error("Could not write image to %s", self._outfile) return loop.getvalue() def _url(self, path): """ Return a full URL to a resource on the BOM site. """ self._log.debug("Getting URL for path %s", path) return "http://www.bom.gov.au/%s" % path
python
from AttachmentFetcherGUI import runGUI runGUI()
python
from typing import Tuple import numpy as np import tensorflow as tf from absl import logging from xain.datasets import prep from xain.types import KerasHistory, KerasWeights, Metrics, VolumeByClass from . import ModelProvider class Participant: # pylint: disable-msg=too-many-arguments # pylint: disable=too-many-instance-attributes def __init__( self, cid: int, model_provider: ModelProvider, xy_train: Tuple[np.ndarray, np.ndarray], xy_val: Tuple[np.ndarray, np.ndarray], num_classes: int, batch_size: int, ) -> None: assert xy_train[0].shape[0] == xy_train[1].shape[0] assert xy_val[0].shape[0] == xy_val[1].shape[0] self.cid = cid self.model_provider = model_provider self.num_classes: int = num_classes self.batch_size: int = batch_size self.num_examples = xy_train[0].shape[0] # Training set self.xy_train = xy_train self.steps_train: int = int(xy_train[0].shape[0] / batch_size) # Validation set self.xy_val = xy_val self.steps_val: int = 1 def train_round( self, theta: KerasWeights, epochs: int, epoch_base: int ) -> Tuple[Tuple[KerasWeights, int], KerasHistory]: logging.info( f"Participant {self.cid}: train_round START (epoch_base: {epoch_base})" ) model = self.model_provider.init_model(epoch_base=epoch_base) # type:ignore model.set_weights(theta) hist: KerasHistory = self.fit(model, epochs) theta_prime = model.get_weights() logging.info("Participant {}: train_round FINISH".format(self.cid)) return (theta_prime, self.num_examples), hist def fit(self, model: tf.keras.Model, epochs: int) -> KerasHistory: ds_train = prep.init_ds_train(self.xy_train, self.num_classes, self.batch_size) ds_val = prep.init_ds_val(self.xy_val, self.num_classes) hist = model.fit( ds_train, epochs=epochs, validation_data=ds_val, callbacks=[LoggingCallback(str(self.cid), logging.info)], shuffle=False, # Shuffling is handled via tf.data.Dataset steps_per_epoch=self.steps_train, validation_steps=self.steps_val, verbose=0, ) return cast_to_float(hist.history) def evaluate( self, theta: KerasWeights, xy_test: Tuple[np.ndarray, np.ndarray] ) -> Tuple[float, float]: model = self.model_provider.init_model() model.set_weights(theta) ds_val = prep.init_ds_val(xy_test) # Assume the validation `tf.data.Dataset` to yield exactly one batch containing # all examples in the validation set loss, accuracy = model.evaluate(ds_val, steps=1, verbose=0) return loss, accuracy def metrics(self) -> Metrics: vol_by_class = xy_train_volume_by_class(self.num_classes, self.xy_train) return (self.cid, vol_by_class) def xy_train_volume_by_class(num_classes: int, xy_train) -> VolumeByClass: counts = [0] * num_classes _, y = xy_train classes, counts_actual = np.unique(y, return_counts=True) for c in classes: # Cast explicitly to int so its later JSON serializable # as other we will get a list of np objects of type int64 counts[c] = int(counts_actual[c]) return counts def cast_to_float(hist) -> KerasHistory: for key in hist: for index, number in enumerate(hist[key]): hist[key][index] = float(number) return hist class LoggingCallback(tf.keras.callbacks.Callback): def __init__(self, cid: str, print_fn): tf.keras.callbacks.Callback.__init__(self) self.cid = cid self.print_fn = print_fn def on_epoch_end(self, epoch, logs=None): msg = "CID {} epoch {}".format(self.cid, epoch) self.print_fn(msg)
python
#!/usr/bin/env python3 import sys import heapq # Generates gawk code. Run this manually and update hinter.awk if you don't like current alphabet or want to increase number of hints. # # This script builds prefix code for given number of hints using n-aray Huffman Coding. # We precompute hints for hinter.awk to make it fast (and to avoid implementing priority queue in awk). alphabet = list('sadfjklewcmvpghru') alphabet_size = len(alphabet) def generate_hints(num_hints_needed): def huffman_build_tree(num_hints_needed): heap = [(1, [i], []) for i in range(num_hints_needed)] heapq.heapify(heap) if num_hints_needed <= alphabet_size: first_step_num_children = num_hints_needed else: first_step_num_children = [m for m in range(2, num_hints_needed) if m % (alphabet_size - 1) == num_hints_needed % (alphabet_size - 1)][0] while len(heap) > 1: children = [] while len(heap) > 0 and len(children) < first_step_num_children: children.append(heapq.heappop(heap)) new_node = (sum(node[0] for node in children), sum([node[1] for node in children], []), [node for node in children]) heapq.heappush(heap, new_node) first_step_num_children = alphabet_size return heap[0] def generate_codes(tree, code): if len(tree[1]) == 1: yield code assert len(tree[2]) <= alphabet_size for child, char in zip(tree[2], alphabet): yield from generate_codes(child, code + char) tree = huffman_build_tree(num_hints_needed) yield from generate_codes(tree, code='') def generate_gawk_hints(): statement = '\nif' sizes = [alphabet_size, 30, 50, 80, 110, 150, 200, 300, 500, 1000] for num_hints_needed in sizes: hints_string = ' '.join(generate_hints(num_hints_needed)) if num_hints_needed == sizes[-1]: print(' else {') else: print('%s (num_hints_needed <= %d) {' % (statement, num_hints_needed)) print(' split("%s", HINTS]);' % (hints_string)) print('}', end='') statement = ' else if' print("") generate_gawk_hints()
python
#!/usr/bin/python2.7 # -*- coding=utf-8 -*- ################################################################## # WaterLevelTree Test # Goal: Test script for WaterLevelTree algorithm # Author: wenchieh # # Project: eaglemine # waterleveltree.py # Version: # Date: November 29 2017 # Main Contact: Wenchieh Feng ([email protected]) # # Copyright: # This software is free of charge under research purposes. # For commercial purposes, please contact the author. # # Created by @wenchieh on <11/30/2017> # ################################################################## __author__ = 'wenchieh' # sys import os import time import argparse # third-part lib import numpy as np # project from utils.loader import Loader from core.leveltree import LevelTree VERBOSE = False tiny_blobs = 'tiny_blob2cnt.out' contracttree = 'level_tree_contract.out' prunetree = 'level_tree_prune.out' refinetree = 'level_tree_refine.out' def waterleveltree(cel2cnt_arr, outpath): tsr_arr = np.asarray(cel2cnt_arr) values = np.log2(1.0 + tsr_arr[:, -1]) max_level = np.max(values) step = 0.2 tree = LevelTree() print("Construct raw-tree.") tree.build_level_tree(tsr_arr[:, :-1], values, 1.0, max_level, step, verbose=False, outfn=os.path.join(outpath, tiny_blobs)) print("Refine tree structure.") print("a). tree contract") tree.tree_contract(VERBOSE) tree.save_leveltree(os.path.join(outpath, contracttree)) print("b). tree pruned") tree.tree_prune(alpha=0.8, verbose=VERBOSE) tree.save_leveltree(os.path.join(outpath, prunetree)) print("c). tree node expand") tree.tree_node_expand(VERBOSE) tree.save_leveltree(os.path.join(outpath, refinetree)) tree.dump() if __name__ == '__main__': path = '../output/' histogram_infn = 'histogram.out' loader = Loader() print("load data") shape, ticks_vec, hist_arr = loader.load_multi_histogram(os.path.join(path, histogram_infn)) mode = len(shape) print("Info: mode:{} shape:{}".format(mode, shape)) waterleveltree(hist_arr, path) print("done!")
python
from restaurant import Restaurant rest1 = Restaurant('Alitas y Costillas', 'BBQ') print(rest1.describe_restaurant()) print(rest1.open_restaurant()) from user import Admin admin1 = Admin('Antonio', 'Perez', '25', 'Monterrey, Nuevo Leon') admin1.privileges = ['Edit', 'Delete', 'Ban'] print(admin1.describe_User()) admin1.show_privileges()
python
#!/usr/bin/env python3 """ See freq_response.md for details """ from dataclasses import dataclass import fractions import math from typing import Iterable, Optional, Tuple, Union import numpy as np from analysis import linearity, time_domain_response from utils import utils from unit_test import unit_test from processor import ProcessorBase from generation import signal_generation PI = math.pi HALF_PI = 0.5 * math.pi TWOPI = 2.0 * math.pi SQRT2 = math.sqrt(2.0) INV_SQRT2 = 1.0 / SQRT2 # Square wave has THD+N of sqrt(pi^2 / 8 - 1) ~= 0.483 ~= -6.32 dB # https://en.wikipedia.org/wiki/Total_harmonic_distortion#Examples SQUARE_THDN = utils.to_dB(math.sqrt((math.pi ** 2.) / 8 - 1)) _unit_tests_short = [] _unit_tests_full = [] @dataclass class FreqResponse: freqs: np.ndarray sample_rate: float amplitude: Optional[float] = None # Amplitude frequency response was performed at (relevant for nonlinear systems) mag: Optional[np.ndarray] = None # Magnitude rms: Optional[np.ndarray] = None # RMS response (only relevant for nonlinear system) phase: Optional[np.ndarray] = None # Phase response, in radians group_delay: Optional[np.ndarray] = None thdn: Optional[np.ndarray] = None # THD + Noise (linear, not dB) def dft_num_samples( freq: Union[int, float], sample_rate: Union[int, float], min_num_samples=0, max_num_samples: Optional[int]=None, maximize=False, round_up=False, ) -> int: """ Determine optimum DFT size at a given frequency and sample rate, in order to get an exact number of cycles at the frequency, or as close as possible. :param freq: frequency, in whatever units you want (must be same units as sample rate) :param sample_rate: sample rate (in same units as freq) :param min_num_samples: Minimum number of samples; default 0 (i.e. no minimum). Actual practical minimum will always be at least 1 cycle :param max_num_samples: Maximum number of samples; default is sample_rate or period at frequency, whichever is larger Must be > (sample_rate/freq). Must be specified if maximize :param maximize: By default, will come up with the minimum possible number of samples that satisfies the criteria sequence; if maximize, will come up with the longest instead. Must explicitly specify max_num_samples if maximize :param round_up: if True, will always round up instead of rounding to nearest """ if maximize and not max_num_samples: raise ValueError('Must provide max_num_samples if setting maximize') period = sample_rate / freq if min_num_samples < 0: raise ValueError('min_num_samples must be > 0') elif not isinstance(min_num_samples, int): raise ValueError('min_num_samples must be integer') if max_num_samples is None: max_num_samples = int(math.ceil(max(sample_rate, period))) elif not isinstance(max_num_samples, int): raise ValueError('max_num_samples must be integer') elif max_num_samples <= 0: raise ValueError('max_num_samples (%g) must be > 0' % max_num_samples) elif max_num_samples <= min_num_samples: raise ValueError('max_num_samples (%g) must be > min_num_samples (%g)' % (max_num_samples, min_num_samples)) eps = 1e-12 min_num_cycles = max(min_num_samples / period, 1.) min_num_cycles_int = int(math.ceil(min_num_cycles - eps)) max_num_cycles = max_num_samples / period max_num_cycles_int = int(math.floor(max_num_cycles + eps)) if max_num_cycles_int < 1: assert max_num_samples < period raise ValueError('max_num_samples (%u) must be >= period (%g)' % (max_num_samples, period)) assert min_num_cycles_int * (period + eps) >= min_num_samples assert max_num_cycles_int * (period - eps) <= max_num_samples if max_num_cycles_int == min_num_cycles_int: # Special case: only 1 possible number of periods n_samples = max_num_cycles_int * period n_samples = int(math.ceil(n_samples) if round_up else round(n_samples)) assert min_num_samples <= n_samples <= max_num_samples return n_samples elif max_num_cycles_int < min_num_cycles_int: # TODO: come up with good error message for this raise ValueError('freq %g, SR %g, min_num_cycles %f -> %u, max_num_cycles %f -> %u' % ( freq, sample_rate, min_num_cycles, min_num_cycles_int, max_num_cycles, max_num_cycles_int )) assert max_num_samples >= period # Should be guaranteed by above conditions freq = utils.integerize_if_int(freq) sample_rate = utils.integerize_if_int(sample_rate) if isinstance(freq, int) and isinstance(sample_rate, int): period_as_fraction = fractions.Fraction(sample_rate, freq) else: period_as_fraction = fractions.Fraction.from_float(period) period_as_fraction = period_as_fraction.limit_denominator(max_denominator=max_num_cycles_int) n_samples_ideal = period * period_as_fraction.denominator assert utils.approx_equal(period_as_fraction.numerator, n_samples_ideal, eps=0.5) if maximize: if 2*n_samples_ideal <= max_num_samples: """ What's the largest integer we can multiply n_samples_ideal by to still be <= max_num_samples? n * k <= max k <= max / n k = floor(max / n) """ n_samples_ideal *= math.floor(max_num_samples / n_samples_ideal) elif n_samples_ideal < min_num_samples: """ What's the smallest integer we can multiply n_samples_ideal by to be >= min_num_samples? n * k >= min k >= min / n k = ceil(min / n) """ n_samples_ideal *= math.ceil(min_num_samples / n_samples_ideal) n_samples = int(math.ceil(n_samples_ideal) if round_up else round(n_samples_ideal)) if not (min_num_samples <= n_samples <= max_num_samples): raise AssertionError('Check n_samples (%i, from %g, fraction %s) in range (%i, %i) failed!' % ( n_samples, n_samples_ideal, period_as_fraction, min_num_samples, max_num_samples)) return n_samples def _test_dft_num_samples(): from unit_test.unit_test import test_equal, test_threw """ Perfect divisors """ # 1 kHz @ 96 kHz # 1 period = 96 samples test_equal(dft_num_samples(1000, 96000), 96) test_equal(dft_num_samples(1000, 96000.), 96) test_equal(dft_num_samples(1000., 96000), 96) test_equal(dft_num_samples(1000., 96000.), 96) test_equal(dft_num_samples(1000., 96000., min_num_samples=100), 192) test_equal(dft_num_samples(1000., 96000., min_num_samples=384), 384) test_equal(dft_num_samples(1000., 96000., max_num_samples=400, maximize=True), 384) test_equal(dft_num_samples(1000., 96000., min_num_samples=380, max_num_samples=400), 384) test_threw(dft_num_samples, 1000., 96000., min_num_samples=398, max_num_samples=400) # 3.125 (25/8) @ 96 kHz # 1 period = 30,720 samples test_equal(dft_num_samples(3.125, 96000.), 30720) """ Rational numbers """ # 10 kHz @ 96 kHz # 1 period = 9.6 samples (48/5) test_equal(dft_num_samples(10000, 96000), 48) test_equal(dft_num_samples(10000, 96000, maximize=True, max_num_samples=96000), 96000) # 1 kHz @ 44.1 kHz # 1 period = 44.1 samples (441/10) test_equal(dft_num_samples(1000, 44100), 441) test_equal(dft_num_samples(1000, 44100, maximize=True, max_num_samples=44100), 44100) # 440 Hz @ 44.1 kHz # 1 period = 100.2272727 samples (2205/22) test_equal(dft_num_samples(440, 44100), 2205) test_equal(dft_num_samples(440, 44100, maximize=True, max_num_samples=44100), 44100) test_equal(dft_num_samples(440, 44100, max_num_samples=102), 100) test_equal(dft_num_samples(440, 44100, max_num_samples=102, round_up=True), 101) test_equal(dft_num_samples(440, 44100, max_num_samples=510, maximize=True), 401) test_equal(dft_num_samples(440, 44100, max_num_samples=510, round_up=True, maximize=True), 401) # 100.125 Hz @ 96 kHz # 1 period = 958.80 samples (256000/267) test_equal(dft_num_samples(100.125, 96000, max_num_samples=1000000), 256000) test_equal(dft_num_samples(100.125, 96000, max_num_samples=1000000, maximize=True), 768000) test_equal(dft_num_samples(100.125, 96000), 92045) # 3010 Hz @ 96 kHz # 1 period = 31.89 samples (9600/301) test_equal(dft_num_samples(3010, 96000), 9600) test_equal(dft_num_samples(3010, 96000, maximize=True, max_num_samples=96000), 96000) # 1001 Hz @ 96 kHz (coprime) # 1 period = 95.904 samples (96000/1001) test_equal(dft_num_samples(1001, 96000), 96000) test_equal(dft_num_samples(1001, 96000, maximize=True, max_num_samples=96000), 96000) # 1000.1 Hz @ 96 kHz # 1 period = 95.99 samples (960,000/10,001) test_equal(dft_num_samples(1000.1, 96000), 59994) test_equal(dft_num_samples(1000.1, 96000, maximize=True, max_num_samples=96000), 59994) """ Irrational numbers """ # 1000*pi Hz @ 96 kHz # 1 period = 30.5577 samples test_equal(dft_num_samples(1000*PI, 96000), 30955) """ Rational numbers expressed as ratio of 2 irrational numbers """ test_equal(dft_num_samples(1000*PI, 96000*PI), 96) _unit_tests_short.append(_test_dft_num_samples) _unit_tests_full.append(_test_dft_num_samples) def _single_freq_dft( x: np.ndarray, cos_sig: np.ndarray, sin_sig: np.ndarray, freq: Union[int, float], sample_rate: Union[int, float], mag=False, phase=False, adjust_num_samp=False, normalize=False): # TODO: use Goertzel algo instead # FIXME: properly deal with boundary conditions - i.e. extra samples at end that don't fit into a complete cycle # adjust_num_samp should mostly deal with that if adjust_num_samp: n_samp = dft_num_samples(freq, sample_rate, min_num_samples=(len(x) // 2), max_num_samples=len(x), maximize=True) else: n_samp = len(x) dft_mult = cos_sig[:n_samp] - 1j * sin_sig[:n_samp] xs = x[:n_samp] * dft_mult xs = np.mean(xs) if normalize else sum(xs) if mag and phase: return np.abs(xs), np.angle(xs) elif mag: return np.abs(xs) elif phase: return np.angle(xs) else: return xs def single_freq_dft( x: np.ndarray, freq: float, sample_rate=1.0, mag=True, phase=True, adjust_num_samp=False, normalize=False): """ Perform DFT at a single arbitrary frequency :param x: :param freq: :param sample_rate: :param mag: return magnitude :param phase: return phase :param adjust_num_samp: if True, will not perform DFT on entire signal; rather, will find optimal number of samples to get as close to a zero-crossing as possible (though guaranteed to use at least half the samples). Recommend calling dft_num_samples to determine sample size instead, in order to get the optimal DFT size of the signal in the first place. :param normalize: divide by number of samples, i.e. return average power per sample instead of sum :return: (mag, phase) if mag and phase; magnitude if mag only; phase if phase only; complex result if neither """ cos_sig, sin_sig = signal_generation.gen_cos_sine(freq / sample_rate, len(x)) return _single_freq_dft( x, cos_sig, sin_sig, freq, sample_rate, mag=mag, phase=phase, adjust_num_samp=adjust_num_samp, normalize=normalize) def phase_to_group_delay(freqs: np.ndarray, phases_rad: np.ndarray, sample_rate: float) -> np.ndarray: phases_rad_unwrapped = np.unwrap(phases_rad) freqs_cycles_per_sample = freqs / sample_rate freqs_rads_per_sample = freqs_cycles_per_sample * TWOPI np_version = [int(n) for n in np.__version__.split('.')] if np_version[0] <= 1 and np_version[1] < 13: delay_samples = -np.gradient(phases_rad_unwrapped) / np.gradient(freqs_rads_per_sample) else: delay_samples = -np.gradient(phases_rad_unwrapped, freqs_rads_per_sample) delay_seconds = delay_samples / sample_rate return delay_seconds def get_ir_freq_response( ir: np.ndarray, freqs: Iterable, sample_rate, mag=True, phase=True, group_delay=True) -> FreqResponse: """ Calculate frequency response based on impulse response :param ir: Impulse response :param freqs: frequencies to get response at. More frequencies will also lead to more precise group delay :param sample_rate: sample rate, in Hz :param mag: if False, does not calculate nor return magnitude :param rms: if False, does not calculate nor return RMS magnitude :param phase: if False, does not calculate nor return phase :param group_delay: if False, does not calculate nor return group delay :return: frequency response of system """ if group_delay and not phase: raise ValueError('Must calculate phase to calculate group delay!') freqs = np.array(freqs) freq_resp = FreqResponse(freqs=freqs, sample_rate=sample_rate) if mag: freq_resp.mag = np.zeros(len(freqs)) if phase: freq_resp.phase = np.zeros(len(freqs)) for n, f_norm in enumerate(freqs / sample_rate): ret = single_freq_dft(ir, f_norm, mag=mag, phase=phase, adjust_num_samp=True) if mag: freq_resp.mag[n] = ret[0] if phase: freq_resp.phase[n] = ret[-1] if group_delay: freq_resp.group_delay = phase_to_group_delay(freqs, freq_resp.phase, sample_rate) if phase: freq_resp.phase = ((freq_resp.phase + PI) % TWOPI) - PI return freq_resp def _calc_thdn(y, f_norm, mag, phase, debug_assert=False): # Subtract fundamental from signal phase01 = np.mod(phase / TWOPI, 1.0) fundamental = signal_generation.gen_sine(f_norm, n_samp=len(y), start_phase=phase01) * mag if debug_assert: debug_mag, debug_phase = single_freq_dft(fundamental, f_norm, mag=True, phase=True, normalize=True, adjust_num_samp=False) assert utils.approx_equal(debug_mag, mag, eps=0.001) assert utils.approx_equal(debug_phase, phase, eps=0.01) thdn_sig = y - fundamental return utils.rms(thdn_sig) * SQRT2 / mag def get_discrete_sine_sweep_freq_response( system: ProcessorBase, freqs: Iterable, sample_rate, n_cycles=40.0, n_samp_min: Optional[int]=None, n_samp=None, amplitude=1.0, mag=True, rms=True, phase=True, group_delay=None, thdn=None) -> FreqResponse: """ Calculate frequency response by passing sine waves at various frequencies through system Unlike impulse response analysis, this will work for nonlinear systems as well (Of course, the definition of "frequency response" is ill-defined for a nonlinear system - see freq_response.md) :param system: Processor to process :param freqs: frequencies to get response at. More frequencies will also lead to more precise group delay :param sample_rate: sample rate, in Hz :param n_cycles: how many cycles of waveform to calculate over :param n_samp_min: if using n_cycles, minimum n_samp :param n_samp: how many samples to calculate over - overrides n_cycles :param amplitude: amplitude of sine wave to pass in :param mag: if False, does not calculate nor return magnitude :param rms: if False, does not calculate nor return RMS magnitude :param phase: if False, does not calculate nor return phase :param group_delay: if False, does not calculate nor return group delay; default true if phase, else false :param thdn: if False, does not calculate THD+Noise; default true if mag & phase, else false :return: frequency response of system. mag, phase, and group delay are based on measurement of output at only that frequency. RMS is based on entire signal. So you can get a proxy for "how nonlinear" the system is by comparing difference between mag & RMS (if linear, output would be a sine wave, so RMS would be 1/sqrt(2) of magnitude) """ if group_delay is None: group_delay = phase elif group_delay and not phase: raise ValueError('Must calculate phase to calculate group delay!') if thdn is None: thdn = mag and phase elif thdn and (not mag or not phase): raise ValueError('Must calculate magnitude/phase to calculate THD+N') freqs = np.array(freqs) freq_resp = FreqResponse(freqs=freqs, sample_rate=sample_rate) if mag: freq_resp.mag = np.zeros(len(freqs)) if rms: freq_resp.rms = np.zeros(len(freqs)) if phase: freq_resp.phase = np.zeros(len(freqs)) if thdn: freq_resp.thdn = np.zeros(len(freqs)) debug_use_dft_of_input = True # FIXME: false is broken for n, freq in enumerate(freqs): f_norm = freq / sample_rate period = sample_rate / freq if n_samp is None: max_num_samples = int(math.ceil(max(n_cycles * period, sample_rate))) #n_samp_this_freq = max(math.ceil(n_cycles / f_norm), n_samp_min) n_samp_this_freq = dft_num_samples( freq, sample_rate, min_num_samples=n_samp_min if (n_samp_min is not None) else 0, max_num_samples=max_num_samples) else: n_samp_this_freq = n_samp scaling = 2.0 / n_samp_this_freq # Input is actually double the number of samples, but for output we only take the 2nd half # TODO: be smarter about this, actually watch the output and wait for the system to hit steady-state # TODO: Can we reach steady-state faster if we ramp up the amplitude? # (This would avoid the sudden impulse in 2nd, 3rd, etc derivatives) x_cos_full, x_sin_full = signal_generation.gen_cos_sine(f_norm, 2 * n_samp_this_freq) x_cos = x_cos_full[n_samp_this_freq:] x_sin = x_sin_full[n_samp_this_freq:] x_cos_dft_mag = x_cos_dft_phase = x_sin_dft_mag = x_sin_dft_phase = None if debug_use_dft_of_input: x_cos_dft_mag, x_cos_dft_phase = _single_freq_dft(x_cos, x_cos, x_sin, freq, sample_rate, mag=True, phase=True, adjust_num_samp=False) x_sin_dft_mag, x_sin_dft_phase = _single_freq_dft(x_sin, x_cos, x_sin, freq, sample_rate, mag=True, phase=True, adjust_num_samp=False) x_rms = utils.rms(x_sin) if rms else None else: x_cos_dft_mag = 1.0 x_cos_dft_phase = HALF_PI x_sin_dft_mag = 1.0 x_sin_dft_phase = 0 x_rms = INV_SQRT2 # TODO: remove y_cos once we know we don't need it anymore system.reset() y_cos = system.process_vector(x_cos_full * amplitude)[n_samp_this_freq:] / amplitude system.reset() y_sin = system.process_vector(x_sin_full * amplitude)[n_samp_this_freq:] / amplitude # TODO: use this? the results look really good - in some cases they look even better than impulse response results # (That doesn't really make sense though - IR should be perfect for linear?) #mag_sin_cos = np.sqrt(np.square(y_sin) + np.square(y_cos)) if mag or phase: ret = _single_freq_dft(y_sin, x_cos, x_sin, freq, sample_rate, mag=mag, phase=phase, adjust_num_samp=False) if mag: freq_resp.mag[n] = ret[0] if (mag and phase) else ret if x_sin_dft_mag is not None: freq_resp.mag[n] /= x_sin_dft_mag else: freq_resp.mag[n] *= scaling if phase: # TODO: figure out if should use both sin & cos # TODO: use x_sin_dft_phase freq_resp.phase[n] = (ret[1] if (mag and phase) else ret) + HALF_PI if rms: freq_resp.rms[n] = utils.rms(y_sin) / x_rms if thdn: freq_resp.thdn[n] = _calc_thdn( y=y_sin, f_norm=f_norm, mag=freq_resp.mag[n], phase=freq_resp.phase[n]) if group_delay: freq_resp.group_delay = phase_to_group_delay(freqs, freq_resp.phase, sample_rate) if phase: freq_resp.phase = ((freq_resp.phase + PI) % TWOPI) - PI return freq_resp def _test_thdn(): pass # TODO #_unit_tests_short.append(_test_thdn) #_unit_tests_full.append(_test_thdn) def get_white_noise_response( system: ProcessorBase, freqs: Iterable, sample_rate, n_samp: int, amplitude=1.0, gaussian=True, mag=True, phase=True, group_delay=True, relative_to_input=True) -> FreqResponse: freqs = np.array(freqs) freq_resp = FreqResponse(freqs=freqs, sample_rate=sample_rate) if not (mag or phase): return freq_resp if mag: freq_resp.mag = np.zeros(len(freqs)) if phase: freq_resp.phase = np.zeros(len(freqs)) x = signal_generation.gen_noise(n_samp, gaussian=gaussian, amp=amplitude) y = system.process_vector(x) for n, freq in enumerate(freqs): kwargs = dict( freq=freq, sample_rate=sample_rate, mag=mag, phase=phase, adjust_num_samp=True, normalize=(not relative_to_input)) x_ret = single_freq_dft(x, **kwargs) y_ret = single_freq_dft(y, **kwargs) if mag and phase: x_mag, x_phase = x_ret y_mag, y_phase = y_ret elif mag: x_mag = x_ret y_mag = y_ret else: assert phase x_phase = x_ret y_phase = y_ret if mag: freq_resp.mag[n] = (y_mag / x_mag) if relative_to_input else y_mag if phase: freq_resp.phase[n] = y_phase - x_phase if group_delay: freq_resp.group_delay = phase_to_group_delay(freqs, freq_resp.phase, sample_rate) return freq_resp def _test_sine_vs_noise(long: bool): from filters import one_pole from filters import biquad from overdrive import overdrive from processor import GainWrapper, CascadedProcessors, GainProcessor from utils.utils import to_dB sample_rate = 96000 cutoff = 1000 Q = 2.0 wc = cutoff / sample_rate if long: n_samp_min = 4096 n_samp_noise = 4 * sample_rate eps_dB = 3 freqs = [ 10, 30, 100, 300, 1000, 3000, 10000, 20000, ] phase_eps = 0.1 delay_eps = 0.1 else: n_samp_min = 1024 n_samp_noise = sample_rate eps_dB = 6 freqs = [ 10, 100, 1000, 10000, 20000, ] phase_eps = 0.1 delay_eps = 0.1 processors = [ ("pass-through processor", CascadedProcessors([])), ("Basic one pole", one_pole.BasicOnePole(wc=wc)), ("Trapz one pole", one_pole.TrapzOnePole(wc=wc)), ("Basic one pole highpass", one_pole.BasicOnePoleHighpass(wc=wc)), ("Biquad, Q=%g" % Q, biquad.BiquadLowpass(wc=wc, Q=Q)), ("tanh overdrive", overdrive.TanhProcessor()), ("tanh overdrive, 20 dB gain", GainWrapper(overdrive.TanhProcessor(), 10.)), ("tanh overdrive, -20 dB gain", GainWrapper(overdrive.TanhProcessor(), 0.1)), ("Squarizer", overdrive.Squarizer()), ("Squarizer -20 dB", CascadedProcessors([overdrive.Squarizer(), GainProcessor(0.1)])), ("One pole then tanh", CascadedProcessors([one_pole.BasicOnePole(wc=wc), overdrive.TanhProcessor(gain=2)])), ("tanh then one pole", CascadedProcessors([overdrive.TanhProcessor(gain=2), one_pole.BasicOnePole(wc=wc)])), ("Biquad, Q=%g, then hard clip at 1.1" % Q, CascadedProcessors([biquad.BiquadLowpass(wc=wc, Q=Q), overdrive.Clipper(gain=1.0/1.1)])), ("Biquad, Q=%g, then hard clip at 1" % Q, CascadedProcessors([biquad.BiquadLowpass(wc=wc, Q=Q), overdrive.Clipper()])), ("Rossum 92 Nonlinear Biquad, Q=%g, gain 10" % Q, GainWrapper(biquad.Rossum92Biquad(wc=wc, Q=Q), 10.)), ] for name, processor in processors: sine_resp = get_discrete_sine_sweep_freq_response( processor, freqs, sample_rate=sample_rate, rms=False, thdn=False, n_samp_min=n_samp_min) noise_resp = get_white_noise_response(processor, freqs=freqs, sample_rate=sample_rate, n_samp=n_samp_noise) assert np.array_equal(sine_resp.freqs, freqs) assert np.array_equal(noise_resp.freqs, freqs) if False: print(sine_resp.mag) print(to_dB(sine_resp.mag)) print(noise_resp.mag) print(to_dB(noise_resp.mag)) print(sine_resp.phase) print(to_dB(sine_resp.phase)) print(noise_resp.phase) print(to_dB(noise_resp.phase)) print(sine_resp.group_delay) print(to_dB(sine_resp.group_delay)) print(noise_resp.group_delay) print(to_dB(noise_resp.group_delay)) unit_test.test_approx_equal(to_dB(sine_resp.mag), to_dB(noise_resp.mag), eps_abs=eps_dB) unit_test.test_approx_equal(sine_resp.phase, noise_resp.phase, eps_abs=phase_eps) unit_test.test_approx_equal(sine_resp.group_delay, noise_resp.group_delay, eps_abs=delay_eps) _unit_tests_short.append(lambda: _test_sine_vs_noise(False)) _unit_tests_full.append(lambda: _test_sine_vs_noise(True)) def check_linear_and_get_freq_resp( system: ProcessorBase, freqs: Iterable, sample_rate, n_samp: Optional[int]=None, n_cycles=40.0, n_samp_min: Optional[int]=None, amplitude=1.0, eps=0.00001, mag=True, rms=True, phase=True, group_delay=True) -> Tuple[bool, FreqResponse]: """ Check if system is linear and calculate frequency response If linear, impulse response will be used If nonlinear, sine sweep will be used Linearity check is done by testing if impulse response is equal to derivative of step response :param system: Processor to process :param freqs: frequencies to get response at. More frequencies will also lead to more precise group delay :param sample_rate: sample rate, in Hz :param n_cycles: how many cycles of waveform to calculate over (if using impulse response, IR length will be based on lowest of freqs) :param n_samp_min: if using n_cycles, minimum n_samp :param n_samp: how many samples to calculate over - overrides n_cycles :param amplitude: amplitude of IR/step/sine wave :param eps: epsilon value for IR/step comparison :param mag: if False, does not calculate nor return magnitude :param rms: if False, does not calculate nor return RMS magnitude :param phase: if False, does not calculate nor return phase :param group_delay: if False, does not calculate nor return group delay :return: Tuple (True if linear, frequency response of system) """ if n_samp is None: lowest_freq = min(freqs) highest_period = sample_rate / lowest_freq n_samp = highest_period * n_cycles linear = linearity.check_linear(system, n_samp=n_samp, amplitude=amplitude, eps=eps) if linear: freq_resp = get_ir_freq_response( ir, freqs, sample_rate, mag=mag, phase=phase, group_delay=group_delay) else: freq_resp = get_discrete_sine_sweep_freq_response( system, freqs, sample_rate, n_cycles=n_cycles, n_samp=n_samp, n_samp_min=n_samp_min, amplitude=amplitude, mag=mag, rms=rms, phase=phase, group_delay=group_delay) return linear, freq_resp def _test_dft_trivial(): """ Test DFT using the same cos/sin signal as the DFT uses """ sample_rates = [32000., 44100., 96000., 192000.] freqs = [ 100., 100.125, 107., 440., 500., 1000., 1001., 2050., 3000., 3010., 5000., 10000., 20000., 1000 * PI, ] for sample_rate in sample_rates: for freq in freqs: if (2 * freq) > sample_rate: continue f_norm = freq / sample_rate period = sample_rate / freq max_num_samples = int(math.ceil(max(period, sample_rate))) n_samp = dft_num_samples( freq, sample_rate, max_num_samples=max_num_samples) n_cycles = n_samp / period cycle_err = abs(n_cycles - round(n_cycles)) # TODO: tighten up maximum clip values here eps_rel = utils.clip(cycle_err, (1e-12, 1e-5)) eps_zero = utils.clip(10*cycle_err, (1e-11, 1e-3)) x_cos, x_sin = signal_generation.gen_cos_sine(f_norm, n_samp) dft_cos = _single_freq_dft( x_cos, cos_sig=x_cos, sin_sig=x_sin, freq=freq, sample_rate=sample_rate, adjust_num_samp=False) dft_sin = _single_freq_dft( x_sin, cos_sig=x_cos, sin_sig=x_sin, freq=freq, sample_rate=sample_rate, adjust_num_samp=False) unit_test.test_approx_equal(np.real(dft_cos), 0.5*n_samp, eps=eps_rel, rel=True) unit_test.test_approx_equal(np.imag(dft_cos), 0., eps=eps_zero) unit_test.test_approx_equal(np.real(dft_sin), 0., eps=eps_zero) unit_test.test_approx_equal(np.imag(dft_sin), -0.5*n_samp, eps=eps_rel, rel=True) _unit_tests_short.append(_test_dft_trivial) _unit_tests_full.append(_test_dft_trivial) def _test_dft_against_fft(long=True): """ Test single_freq_dft against numpy fft Note that this is only possible at frequencies that perfectly fit into n samples """ eps = 1e-6 mags_short = [1.0, eps, PI, 100.1] mags_full = [1.0, 0.125, 0.1, eps, PI, 100., 100.1, 100 + eps] phases_short = [0, 0.1, 0.125, 0.24, 0.25, 0.9] phases_full = [0, eps, 0.1, 0.124, 0.125, 0.126, 0.25, 0.24, 0.26, 0.25 - eps, 0.25 + eps, 0.5, 0.75, 0.9, 1 - eps] tests = [ dict( n_samples=512, bin_nums=[0, 1, 10, 11, 100, 255, 256], eps_abs=1e-9, eps_rel=1e-12, mags=mags_full, phases=phases_full, ), dict( n_samples=4096, bin_nums=[0, 1, 10, 11, 100, 512, 1024, 2047, 2048], eps_abs=1e-9, eps_rel=1e-9, mags=mags_full, phases=phases_full, ), dict( n_samples=65536, bin_nums=( [0, 1, 10, 11, 100, 512, 1024, 2047, 2048, 4096, 8191, 8192, 32767, 32768] if long else [0, 1, 10, 11, 100, 2048, 4096, 32767, 32768] ), eps_abs=1e-9, eps_rel=1e-8, mags=(mags_full if long else mags_short), phases=(phases_full if long else phases_short), ), ] for test in tests: eps_abs = test['eps_abs'] eps_rel = test['eps_rel'] n_samples = test['n_samples'] bin_nums = test['bin_nums'] mags = test['mags'] phases = test['phases'] for bin_num in bin_nums: for mag in mags: for phase in phases: unit_test.log('n_samples %u, bin_num %u, mag %g, ph %g' % (n_samples, bin_num, mag, phase)) f_norm = bin_num / n_samples sig = mag * signal_generation.gen_sine(f_norm, n_samp=n_samples, start_phase=phase) dft_sig = single_freq_dft( sig, f_norm, sample_rate=1.0, mag=False, phase=False, adjust_num_samp=False, normalize=False) fft_sig = np.fft.fft(sig) fft_at_bin = fft_sig[bin_num] unit_test.test_approx_equal( np.real(dft_sig), np.real(fft_at_bin), abs_rel=True, eps_abs=eps_abs, eps_rel=eps_rel) unit_test.test_approx_equal( np.imag(dft_sig), np.imag(fft_at_bin), abs_rel=True, eps_abs=eps_abs, eps_rel=eps_rel) unit_test.test_approx_equal( np.abs(dft_sig), np.abs(fft_at_bin), abs_rel=True, eps_abs=eps_abs, eps_rel=eps_rel ) _unit_tests_short.append(lambda: _test_dft_against_fft(long=False)) _unit_tests_full.append(lambda: _test_dft_against_fft(long=True)) def _test_dft_sine(long=True): """ Test single_freq_dft with sine waves at arbitrary frequency, phase, amplitude """ # Similar to both _test_dft_trivial and _test_dft_against_fft but covers some ground those don't # (arbitrary frequency) eps = 1e-6 sample_rate = 96000. mags_short = [1.0, eps, PI, 100.1] mags_full = [1.0, 0.125, 0.1, eps, PI, 100., 100.1, 100 + eps] phases_short = [0, 0.1, 0.125, 0.24, 0.25, 0.9] phases_full = [0, eps, 0.1, 0.124, 0.125, 0.126, 0.25, 0.24, 0.26, 0.25 - eps, 0.25 + eps, 0.5, 0.75, 0.9, 1 - eps] simple_freqs = [ 20., 100., 1000., 10000., 20000., 32000., ] complex_freqs = [ 440., 440. + 0.1*PI, 1234., 5927., PI*10000., ] freqs = [ 20., 100., 440., 440. + 0.1*PI, 1000., 1234., 5927., 10000., 20000., PI*10000., 32000., ] for freq in freqs: #eps_abs = test['eps_abs'] #eps_rel = test['eps_rel'] #n_samples = test['n_samples'] #bin_nums = test['bin_nums'] #mags = test['mags'] #phases = test['phases'] pass # TODO: like _test_dft_trivial() but with with non-trivial phase & magnitude #_unit_tests_short.append(lambda: _test_dft_sine(long=False)) # TODO: enable when ready #_unit_tests_full.append(lambda: _test_dft_sine(long=True)) # TODO: enable when ready def _do_detail(): from matplotlib import pyplot as plt sample_rate = 96000 n_samp = None n_samp_min = 4096 n_cycles = 128.0 n_samp_plot = 128 freqs = [100., 107., 500., 1000., 2050., 3000., 3010., 5000., 10000., 20000.] fig = plt.figure() print('%6s %6s %8s %8s %10s %10s %10s %10s %12s' % ( 'freq', 'phase', 'num samp', 'num cyc', 'real err', 'imag err', 'mag err', 'ph err', 'max rec err',)) for n, freq in enumerate(freqs): f_norm = freq / sample_rate period = sample_rate / freq if n_samp is None: max_num_samples = int(math.ceil(max(n_cycles * period, sample_rate))) n_samp_this_freq = dft_num_samples( freq, sample_rate, min_num_samples=n_samp_min, max_num_samples=max_num_samples) else: n_samp_this_freq = n_samp n_cycles_this_freq = n_samp_this_freq * f_norm x_cos, x_sin = signal_generation.gen_cos_sine(f_norm, n_samp_this_freq) #mag_sin, phase_sin = _single_freq_dft(x_sin, x_cos, x_sin, freq, sample_rate, mag=True, phase=True) dft_cos = _single_freq_dft( x_cos, cos_sig=x_cos, sin_sig=x_sin, freq=freq, sample_rate=sample_rate, adjust_num_samp=False) dft_sin = _single_freq_dft( x_sin, cos_sig=x_cos, sin_sig=x_sin, freq=freq, sample_rate=sample_rate, adjust_num_samp=False) dft_cos /= (0.5*n_samp_this_freq) dft_sin /= (0.5*n_samp_this_freq) mag_cos = np.abs(dft_cos) mag_sin = np.abs(dft_sin) phase_cos = np.angle(dft_cos) phase_sin = np.angle(dft_sin) # gen_sine takes phase 0-1, relative to sine (not cos) phase_cos_01 = np.mod((phase_cos / TWOPI) + 0.25, 1.0) phase_sin_01 = np.mod((phase_sin / TWOPI) + 0.25, 1.0) idx = np.arange(n_samp_plot) reconstructed_cos = signal_generation.gen_sine(f_norm, n_samp=n_samp_this_freq, start_phase=phase_cos_01) * mag_cos reconstructed_sin = signal_generation.gen_sine(f_norm, n_samp=n_samp_this_freq, start_phase=phase_sin_01) * mag_sin cos_real_err = np.real(dft_cos) - 1.0 cos_imag_err = np.imag(dft_cos) sin_real_err = np.real(dft_sin) sin_imag_err = np.imag(dft_sin) + 1.0 cos_mag_err = mag_cos - 1 sin_mag_err = mag_sin - 1 cos_phase_err = phase_cos sin_phase_err = phase_sin + HALF_PI cos_rec_err = reconstructed_cos - x_cos sin_rec_err = reconstructed_sin - x_sin plt.subplot(len(freqs), 2, 2*n+1) if n == 0: plt.title('cos') plt.plot(idx, x_cos[:n_samp_plot], label='input') plt.plot(idx, x_cos[:n_samp_plot], label='output') plt.plot(idx, reconstructed_cos[:n_samp_plot], label='reconstructed') plt.plot(idx, cos_rec_err[:n_samp_plot], label='reconst err' % np.amax(np.abs(cos_rec_err))) plt.grid() plt.legend() plt.ylabel('%g Hz' % freq) plt.subplot(len(freqs), 2, 2*n+2) if n == 0: plt.title('sin') plt.plot(idx, x_sin[:n_samp_plot], label='input') plt.plot(idx, x_sin[:n_samp_plot], label='output') plt.plot(idx, reconstructed_sin[:n_samp_plot], label='reconstructed') plt.plot(idx, sin_rec_err[:n_samp_plot], label='reconst err' % np.amax(np.abs(sin_rec_err))) plt.grid() plt.legend() print() print('%6g %6s %8g %8g %10.2e %10.2e %10.2e %10.2e %12.2e' % ( freq, 'cos', n_samp_this_freq, n_cycles_this_freq, cos_real_err, cos_imag_err, cos_mag_err, cos_phase_err, np.amax(np.abs(cos_rec_err)))) print('%6g %6s %8g %8g %10.2e %10.2e %10.2e %10.2e %12.2e' % ( freq, 'sin', n_samp_this_freq, n_cycles_this_freq, sin_real_err, sin_imag_err, sin_mag_err, sin_phase_err, np.amax(np.abs(sin_rec_err)))) plt.show() def _do_main(trivial=True, linear=True, nonlin=True, do_noise=True): from matplotlib import pyplot as plt from filters import one_pole from filters import biquad from overdrive import overdrive from processor import GainWrapper, CascadedProcessors, GainProcessor from utils.utils import to_dB sample_rate = 96000 cutoff = 1000 Q = 2.0 n_samp_ir = 16384 n_samp_min = 4096 n_samp_noise = 4 * sample_rate wc = cutoff / sample_rate filters_trivial = [ ("pass-through processor", CascadedProcessors([]), None), ] filters_linear = [ ("Basic one pole", one_pole.BasicOnePole(wc=wc), None), ("Trapz one pole", one_pole.TrapzOnePole(wc=wc), None), ("Basic one pole highpass", one_pole.BasicOnePoleHighpass(wc=wc), None), ("Biquad, Q=%g" % Q, biquad.BiquadLowpass(wc=wc, Q=Q), None), ] filters_nonlin = [ ("tanh overdrive", overdrive.TanhProcessor(), None), ("tanh overdrive, 20 dB gain", GainWrapper(overdrive.TanhProcessor(), 10.), None), ("tanh overdrive, -20 dB gain", GainWrapper(overdrive.TanhProcessor(), 0.1), None), ("Squarizer", overdrive.Squarizer(), SQUARE_THDN), ("Squarizer -20 dB", CascadedProcessors([overdrive.Squarizer(), GainProcessor(0.1)]), SQUARE_THDN), ("One pole then tanh", CascadedProcessors([one_pole.BasicOnePole(wc=wc), overdrive.TanhProcessor(gain=2)]), None), ("tanh then one pole", CascadedProcessors([overdrive.TanhProcessor(gain=2), one_pole.BasicOnePole(wc=wc)]), None), ("Biquad, Q=%g, then hard clip at 1.1" % Q, CascadedProcessors([biquad.BiquadLowpass(wc=wc, Q=Q), overdrive.Clipper(gain=1.0/1.1)]), None), ("Biquad, Q=%g, then hard clip at 1" % Q, CascadedProcessors([biquad.BiquadLowpass(wc=wc, Q=Q), overdrive.Clipper()]), None), ("Rossum 92 Nonlinear Biquad, Q=%g, gain 10" % Q, GainWrapper(biquad.Rossum92Biquad(wc=wc, Q=Q), 10.), None), ] filters = [] if trivial: filters += filters_trivial if linear: filters += filters_linear if nonlin: filters += filters_nonlin freqs = np.array([ 10., 20., 30., 50., 100., 200., 300., 500., 700., 800., 900., 950., 1000., 1050., 1100., 1200., 1300., 1500., 2000., 3000., 5000., 10000., 11000., 13000., 15000., 20000., 25000., 30000., 40000.]) for filter_name, filter, expected_thdn_dB in filters: print('Processing filter "%s"' % filter_name) ir = time_domain_response.get_impulse_response(filter, n_samp_ir, amplitude=1.0, reset=True) ir_freq_resp = get_ir_freq_response( ir, freqs, sample_rate, mag=True, phase=True, group_delay=True) sweep_freq_resp = get_discrete_sine_sweep_freq_response( filter, freqs, sample_rate, n_cycles=128.0, n_samp=None, n_samp_min=n_samp_min, amplitude=1.0, mag=True, rms=True, phase=True, group_delay=True) mag_rms_err = np.abs(sweep_freq_resp.mag - sweep_freq_resp.rms) sweep_ir_err = np.abs(sweep_freq_resp.mag - ir_freq_resp.mag) if do_noise: uniform_noise_freq_resp = get_white_noise_response( filter, freqs, sample_rate, n_samp_noise, gaussian=False, mag=True, phase=True, group_delay=True) gaussian_noise_freq_resp = get_white_noise_response( filter, freqs, sample_rate, n_samp_noise, gaussian=True, mag=True, phase=True, group_delay=True) fft_bin_freqs = np.fft.fftfreq(n_samp_ir, 1.0 / sample_rate)[:n_samp_ir // 2] ir_fft = np.fft.fft(ir)[:n_samp_ir // 2] ir_fft_group_delay = phase_to_group_delay(fft_bin_freqs, np.angle(ir_fft), sample_rate) # # Plotting # fig = plt.figure() fig.suptitle(filter_name) plt.subplot(4, 1, 1) plt.semilogx(fft_bin_freqs, to_dB(np.abs(ir_fft)), label='IR magnitude from FFT') plt.semilogx(freqs, to_dB(ir_freq_resp.mag), label='IR magnitude') plt.semilogx(freqs, to_dB(sweep_freq_resp.mag), label='Sine sweep magnitude') plt.semilogx(freqs, to_dB(sweep_freq_resp.rms), label='Sine sweep RMS') if do_noise: plt.semilogx(freqs, to_dB(uniform_noise_freq_resp.mag), label='Uniform noise') plt.semilogx(freqs, to_dB(gaussian_noise_freq_resp.mag), label='Gaussian noise') plt.grid() plt.legend() plt.ylabel('dB') plt.subplot(4, 1, 2) if expected_thdn_dB is not None: plt.axhline(expected_thdn_dB, color='g', label='Expected THD + Noise') plt.semilogx(freqs, to_dB(sweep_freq_resp.thdn, min_dB=-120), label='Measured THD + Noise') plt.semilogx(freqs, to_dB(sweep_ir_err, min_dB=-120), label='sine vs IR error') plt.semilogx(freqs, to_dB(mag_rms_err, min_dB=-120), label='sine mag vs RMS error') plt.grid() plt.legend() plt.ylabel('dB') plt.subplot(4, 1, 3) plt.semilogx(fft_bin_freqs, np.rad2deg(np.angle(ir_fft)), label='IR phase from FFT') plt.semilogx(freqs, np.rad2deg(ir_freq_resp.phase), label='IR phase') plt.semilogx(freqs, np.rad2deg(sweep_freq_resp.phase), label='Sine sweep phase') if do_noise: plt.semilogx(freqs, np.rad2deg(uniform_noise_freq_resp.phase), label='Uniform noise') plt.semilogx(freqs, np.rad2deg(gaussian_noise_freq_resp.phase), label='Gaussian noise') plt.grid() plt.legend() plt.ylabel('Degrees') plt.subplot(4, 1, 4) plt.semilogx(fft_bin_freqs, ir_fft_group_delay, label='IR group delay from FFT') plt.semilogx(freqs, ir_freq_resp.group_delay, label='IR group delay') plt.semilogx(freqs, sweep_freq_resp.group_delay, label='Sine sweep group delay') if do_noise: plt.semilogx(freqs, uniform_noise_freq_resp.group_delay, label='Uniform noise') plt.semilogx(freqs, gaussian_noise_freq_resp.group_delay, label='Gaussian noise') plt.grid() plt.legend() plt.ylabel('Seconds') print('Showing plots') plt.show() def main(args): import argparse parser = argparse.ArgumentParser() grp = parser.add_argument_group('Standard analysis') grp.add_argument('--noise', action='store_true', help='Include noise analysis (slow)') grp.add_argument('--trivial', action='store_true', help='Process only trivial processors') grp.add_argument('--linear', action='store_true', help='Process only linear filters') grp.add_argument('--nonlin', action='store_true', help='Process only nonlinear processors') grp = parser.add_argument_group('Other functions') grp.add_argument('--detail', action='store_true') args = parser.parse_args(args) if args.detail: return _do_detail() num_args = sum([args.trivial, args.linear, args.nonlin, args.detail]) if num_args > 1: raise ValueError('Can only give max 1 of --trivial, --nonlin, --detail') elif not num_args: args.trivial = True args.linear = True args.nonlin = True trivial = (args.trivial or args.linear) linear = args.linear nonlin = args.nonlin return _do_main(trivial=trivial, linear=linear, nonlin=nonlin, do_noise=args.noise) def test(verbose=False, long=False): if long: return unit_test.run_unit_tests(_unit_tests_full, verbose=verbose) else: return unit_test.run_unit_tests(_unit_tests_short, verbose=verbose)
python
""" 2019/12/23 23:42 162.【正则表达式】开始结束和或语法 """ import re # TODO: 1. ^托字号: 表示以...开始 """ 如果是在中括号中,那么代表取反操作. """ text1 = 'hello' ret_text1 = re.match('^h', text1) print('^托字号: 表示以...开始...') print(ret_text1.group()) # TODO: 2.$ 表示以...结束 email = '[email protected]' ret_email = re.match('\w+@163\.com$', email) print('$ 表示以...结束...') print(ret_email.group()) # TODO: 3.| 匹配多个表达式或者字符串 url = 'https' ret_url = re.match('(http|https|ftp)$', url) print('| 匹配多个表达式或者字符串...') print(ret_url.group()) # TODO: 4.贪婪模式和非贪婪模式 """ 贪婪模式:正则表达式会匹配尽量多的字符。默认是贪婪模式。 非贪婪模式:正则表达式会尽量少的匹配字符。 """ text2 = '01234567' ret_text2 = re.match('\d+?', text2) print('贪婪模式和非贪婪模式...') print(ret_text2.group()) h1 = '<h1>标题</h1>' ret_h1 = re.match('<.*?>', h1) print('贪婪模式和非贪婪模式...') print(ret_h1.group()) # TODO: 5.匹配0-100之间的数字 # TODO: 可以出现的:1,2,3,10,100,99 # TODO: 有三种情况:1,99,100 # TODO: 不可以出现的:09,101 num = '1' ret_num = re.match('([1-9]?\d$|100$)', num) print('匹配0-100之间的数字...') print(ret_num.group())
python
import paddle import paddle.nn.functional as F import random import numpy as np import math from PIL import Image from ..registry import PIPELINES from collections.abc import Sequence import cv2 import random @PIPELINES.register() class Toskeleton(object): """ transpose (M,T,V,2) to (2,T,V,M) """ def __init__(self, label_expand=True): self.label_expand = label_expand def __call__(self, results): data = results['keypoint'] results['data'] = data.astype('float32').transpose(3,1,2,0) if 'label' in results and self.label_expand: label = results['label'] results['label'] = np.expand_dims(label, 0).astype('int64') return results @PIPELINES.register() class Norm: """ keys:data,label formal:(2,T,V,M) """ def __init__(self, label_expand=True,shape=[64,64],form='CTVM'): self.label_expand=label_expand self.h,self.w=shape[0],shape[1] self.form = form def __call__(self,results): if self.form=='CTVM': data = results['data'] data[0,:,:,:] =( data[0,:,:,:] - self.w/2)/(self.w/2+1e-6) data[1,:,:,:] =( data[1,:,:,:] - self.h/2)/(self.h/2+1e-6) # Centralization data[:,:,:,:] = data[:,:,:,:] - data[:, :, 8:9, :] results['data'] = data.astype('float32') elif self.form=='MTVC': data = results['keypoint'] print(data.max(),data.min()) data[:,:,:,0] =( data[:,:,:,0] - self.w/2)/(self.w/2+1e-6) data[:,:,:,1] =( data[:,:,:,1] - self.h/2)/(self.h/2+1e-6) print(data.max(),data.min()) # Centralization data[:,:,:,:] = data[:,:,:,:] - data[:, :, 8:9, :] print(data.max(),data.min()) results['keypoint'] = data else: assert False,'Wrong form !' return results # reference from paper "Revisiting Skeleton-based Action Recognition" # <https://arxiv.org/pdf/2104.13586v1.pdf> # @misc{2020mmaction2, # title={OpenMMLab's Next Generation Video Understanding Toolbox and Benchmark}, # author={MMAction2 Contributors}, # howpublished = {\url{https://github.com/open-mmlab/mmaction2}}, # year={2020} # } def downsample(data_numpy, step, random_sample=True): # input: C,T,V,M begin = np.random.randint(step) if random_sample else 0 return data_numpy[:, begin::step, :, :] def normalize(data): # V,T,H,W data = (data - data.min())/(data.max()-data.min()+1e-6) return data class RandomCrop: """Vanilla square random crop that specifics the output size. Required keys in results are "img_shape", "keypoint" (optional), "imgs" (optional), added or modified keys are "keypoint", "imgs", "lazy"; Required keys in "lazy" are "flip", "crop_bbox", added or modified key is "crop_bbox". Args: size (int): The output size of the images. lazy (bool): Determine whether to apply lazy operation. Default: False. """ def __init__(self, size, lazy=False): if not isinstance(size, int): raise TypeError(f'Size must be an int, but got {type(size)}') self.size = size self.lazy = lazy @staticmethod def _crop_kps(kps, crop_bbox): return kps - crop_bbox[:2] @staticmethod def _crop_imgs(imgs, crop_bbox): x1, y1, x2, y2 = crop_bbox return [img[y1:y2, x1:x2] for img in imgs] @staticmethod def _box_crop(box, crop_bbox): """Crop the bounding boxes according to the crop_bbox. Args: box (np.ndarray): The bounding boxes. crop_bbox(np.ndarray): The bbox used to crop the original image. """ x1, y1, x2, y2 = crop_bbox img_w, img_h = x2 - x1, y2 - y1 box_ = box.copy() box_[..., 0::2] = np.clip(box[..., 0::2] - x1, 0, img_w - 1) box_[..., 1::2] = np.clip(box[..., 1::2] - y1, 0, img_h - 1) return box_ def _all_box_crop(self, results, crop_bbox): """Crop the gt_bboxes and proposals in results according to crop_bbox. Args: results (dict): All information about the sample, which contain 'gt_bboxes' and 'proposals' (optional). crop_bbox(np.ndarray): The bbox used to crop the original image. """ results['gt_bboxes'] = self._box_crop(results['gt_bboxes'], crop_bbox) if 'proposals' in results and results['proposals'] is not None: assert results['proposals'].shape[1] == 4 results['proposals'] = self._box_crop(results['proposals'], crop_bbox) return results def __call__(self, results): """Performs the RandomCrop augmentation. Args: results (dict): The resulting dict to be modified and passed to the next transform in pipeline. """ _init_lazy_if_proper(results, self.lazy) if 'keypoint' in results: assert not self.lazy, ('Keypoint Augmentations are not compatible ' 'with lazy == True') img_h, img_w = results['img_shape'] assert self.size <= img_h and self.size <= img_w y_offset = 0 x_offset = 0 if img_h > self.size: y_offset = int(np.random.randint(0, img_h - self.size)) if img_w > self.size: x_offset = int(np.random.randint(0, img_w - self.size)) if 'crop_quadruple' not in results: results['crop_quadruple'] = np.array( [0, 0, 1, 1], # x, y, w, h dtype=np.float32) x_ratio, y_ratio = x_offset / img_w, y_offset / img_h w_ratio, h_ratio = self.size / img_w, self.size / img_h old_crop_quadruple = results['crop_quadruple'] old_x_ratio, old_y_ratio = old_crop_quadruple[0], old_crop_quadruple[1] old_w_ratio, old_h_ratio = old_crop_quadruple[2], old_crop_quadruple[3] new_crop_quadruple = [ old_x_ratio + x_ratio * old_w_ratio, old_y_ratio + y_ratio * old_h_ratio, w_ratio * old_w_ratio, h_ratio * old_h_ratio ] results['crop_quadruple'] = np.array( new_crop_quadruple, dtype=np.float32) new_h, new_w = self.size, self.size crop_bbox = np.array( [x_offset, y_offset, x_offset + new_w, y_offset + new_h]) results['crop_bbox'] = crop_bbox results['img_shape'] = (new_h, new_w) if not self.lazy: if 'keypoint' in results: results['keypoint'] = self._crop_kps(results['keypoint'], crop_bbox) if 'imgs' in results: results['imgs'] = self._crop_imgs(results['imgs'], crop_bbox) else: lazyop = results['lazy'] if lazyop['flip']: raise NotImplementedError('Put Flip at last for now') # record crop_bbox in lazyop dict to ensure only crop once in Fuse lazy_left, lazy_top, lazy_right, lazy_bottom = lazyop['crop_bbox'] left = x_offset * (lazy_right - lazy_left) / img_w right = (x_offset + new_w) * (lazy_right - lazy_left) / img_w top = y_offset * (lazy_bottom - lazy_top) / img_h bottom = (y_offset + new_h) * (lazy_bottom - lazy_top) / img_h lazyop['crop_bbox'] = np.array([(lazy_left + left), (lazy_top + top), (lazy_left + right), (lazy_top + bottom)], dtype=np.float32) # Process entity boxes if 'gt_bboxes' in results: assert not self.lazy results = self._all_box_crop(results, results['crop_bbox']) return results def __repr__(self): repr_str = (f'{self.__class__.__name__}(size={self.size}, ' f'lazy={self.lazy})') return repr_str @PIPELINES.register() class RandomResizedCrop(RandomCrop): """Random crop that specifics the area and height-weight ratio range. Required keys in results are "img_shape", "crop_bbox", "imgs" (optional), "keypoint" (optional), added or modified keys are "imgs", "keypoint", "crop_bbox" and "lazy"; Required keys in "lazy" are "flip", "crop_bbox", added or modified key is "crop_bbox". Args: area_range (Tuple[float]): The candidate area scales range of output cropped images. Default: (0.08, 1.0). aspect_ratio_range (Tuple[float]): The candidate aspect ratio range of output cropped images. Default: (3 / 4, 4 / 3). lazy (bool): Determine whether to apply lazy operation. Default: False. """ def __init__(self, area_range=(0.08, 1.0), aspect_ratio_range=(3 / 4, 4 / 3), lazy=False): area_range = tuple(area_range) self.area_range = area_range self.aspect_ratio_range = aspect_ratio_range self.lazy = lazy # if not mmcv.is_tuple_of(self.area_range, float): # raise TypeError(f'Area_range must be a tuple of float, ' # f'but got {type(area_range)}') # if not mmcv.is_tuple_of(self.aspect_ratio_range, float): # raise TypeError(f'Aspect_ratio_range must be a tuple of float, ' # f'but got {type(aspect_ratio_range)}') @staticmethod def get_crop_bbox(img_shape, area_range, aspect_ratio_range, max_attempts=10): """Get a crop bbox given the area range and aspect ratio range. Args: img_shape (Tuple[int]): Image shape area_range (Tuple[float]): The candidate area scales range of output cropped images. Default: (0.08, 1.0). aspect_ratio_range (Tuple[float]): The candidate aspect ratio range of output cropped images. Default: (3 / 4, 4 / 3). max_attempts (int): The maximum of attempts. Default: 10. max_attempts (int): Max attempts times to generate random candidate bounding box. If it doesn't qualified one, the center bounding box will be used. Returns: (list[int]) A random crop bbox within the area range and aspect ratio range. """ assert 0 < area_range[0] <= area_range[1] <= 1 assert 0 < aspect_ratio_range[0] <= aspect_ratio_range[1] img_h, img_w = img_shape area = img_h * img_w min_ar, max_ar = aspect_ratio_range aspect_ratios = np.exp( np.random.uniform( np.log(min_ar), np.log(max_ar), size=max_attempts)) target_areas = np.random.uniform(*area_range, size=max_attempts) * area candidate_crop_w = np.round(np.sqrt(target_areas * aspect_ratios)).astype(np.int32) candidate_crop_h = np.round(np.sqrt(target_areas / aspect_ratios)).astype(np.int32) for i in range(max_attempts): crop_w = candidate_crop_w[i] crop_h = candidate_crop_h[i] if crop_h <= img_h and crop_w <= img_w: x_offset = random.randint(0, img_w - crop_w) y_offset = random.randint(0, img_h - crop_h) return x_offset, y_offset, x_offset + crop_w, y_offset + crop_h # Fallback crop_size = min(img_h, img_w) x_offset = (img_w - crop_size) // 2 y_offset = (img_h - crop_size) // 2 return x_offset, y_offset, x_offset + crop_size, y_offset + crop_size def __call__(self, results): """Performs the RandomResizeCrop augmentation. Args: results (dict): The resulting dict to be modified and passed to the next transform in pipeline. """ _init_lazy_if_proper(results, self.lazy) if 'keypoint' in results: assert not self.lazy, ('Keypoint Augmentations are not compatible ' 'with lazy == True') img_h, img_w = results['img_shape'] left, top, right, bottom = self.get_crop_bbox( (img_h, img_w), self.area_range, self.aspect_ratio_range) new_h, new_w = bottom - top, right - left if 'crop_quadruple' not in results: results['crop_quadruple'] = np.array( [0, 0, 1, 1], # x, y, w, h dtype=np.float32) x_ratio, y_ratio = left / img_w, top / img_h w_ratio, h_ratio = new_w / img_w, new_h / img_h old_crop_quadruple = results['crop_quadruple'] old_x_ratio, old_y_ratio = old_crop_quadruple[0], old_crop_quadruple[1] old_w_ratio, old_h_ratio = old_crop_quadruple[2], old_crop_quadruple[3] new_crop_quadruple = [ old_x_ratio + x_ratio * old_w_ratio, old_y_ratio + y_ratio * old_h_ratio, w_ratio * old_w_ratio, h_ratio * old_h_ratio ] results['crop_quadruple'] = np.array( new_crop_quadruple, dtype=np.float32) crop_bbox = np.array([left, top, right, bottom]) results['crop_bbox'] = crop_bbox results['img_shape'] = (new_h, new_w) if not self.lazy: if 'keypoint' in results: results['keypoint'] = self._crop_kps(results['keypoint'], crop_bbox) if 'imgs' in results: results['imgs'] = self._crop_imgs(results['imgs'], crop_bbox) else: lazyop = results['lazy'] if lazyop['flip']: raise NotImplementedError('Put Flip at last for now') # record crop_bbox in lazyop dict to ensure only crop once in Fuse lazy_left, lazy_top, lazy_right, lazy_bottom = lazyop['crop_bbox'] left = left * (lazy_right - lazy_left) / img_w right = right * (lazy_right - lazy_left) / img_w top = top * (lazy_bottom - lazy_top) / img_h bottom = bottom * (lazy_bottom - lazy_top) / img_h lazyop['crop_bbox'] = np.array([(lazy_left + left), (lazy_top + top), (lazy_left + right), (lazy_top + bottom)], dtype=np.float32) if 'gt_bboxes' in results: assert not self.lazy results = self._all_box_crop(results, results['crop_bbox']) return results def __repr__(self): repr_str = (f'{self.__class__.__name__}(' f'area_range={self.area_range}, ' f'aspect_ratio_range={self.aspect_ratio_range}, ' f'lazy={self.lazy})') return repr_str @PIPELINES.register() class CenterCropkp(RandomCrop): """Crop the center area from images. Required keys are "img_shape", "imgs" (optional), "keypoint" (optional), added or modified keys are "imgs", "keypoint", "crop_bbox", "lazy" and "img_shape". Required keys in "lazy" is "crop_bbox", added or modified key is "crop_bbox". Args: crop_size (int | tuple[int]): (w, h) of crop size. lazy (bool): Determine whether to apply lazy operation. Default: False. """ def __init__(self, crop_size, lazy=False): self.crop_size = (crop_size,crop_size) self.lazy = lazy def __call__(self, results): """Performs the CenterCrop augmentation. Args: results (dict): The resulting dict to be modified and passed to the next transform in pipeline. """ _init_lazy_if_proper(results, self.lazy) if 'keypoint' in results: assert not self.lazy, ('Keypoint Augmentations are not compatible ' 'with lazy == True') img_h, img_w = results['img_shape'] crop_w, crop_h = self.crop_size left = (img_w - crop_w) // 2 top = (img_h - crop_h) // 2 right = left + crop_w bottom = top + crop_h new_h, new_w = bottom - top, right - left crop_bbox = np.array([left, top, right, bottom]) results['crop_bbox'] = crop_bbox results['img_shape'] = (new_h, new_w) if 'crop_quadruple' not in results: results['crop_quadruple'] = np.array( [0, 0, 1, 1], # x, y, w, h dtype=np.float32) x_ratio, y_ratio = left / img_w, top / img_h w_ratio, h_ratio = new_w / img_w, new_h / img_h old_crop_quadruple = results['crop_quadruple'] old_x_ratio, old_y_ratio = old_crop_quadruple[0], old_crop_quadruple[1] old_w_ratio, old_h_ratio = old_crop_quadruple[2], old_crop_quadruple[3] new_crop_quadruple = [ old_x_ratio + x_ratio * old_w_ratio, old_y_ratio + y_ratio * old_h_ratio, w_ratio * old_w_ratio, h_ratio * old_h_ratio ] results['crop_quadruple'] = np.array( new_crop_quadruple, dtype=np.float32) if not self.lazy: if 'keypoint' in results: results['keypoint'] = self._crop_kps(results['keypoint'], crop_bbox) if 'imgs' in results: results['imgs'] = self._crop_imgs(results['imgs'], crop_bbox) else: lazyop = results['lazy'] if lazyop['flip']: raise NotImplementedError('Put Flip at last for now') # record crop_bbox in lazyop dict to ensure only crop once in Fuse lazy_left, lazy_top, lazy_right, lazy_bottom = lazyop['crop_bbox'] left = left * (lazy_right - lazy_left) / img_w right = right * (lazy_right - lazy_left) / img_w top = top * (lazy_bottom - lazy_top) / img_h bottom = bottom * (lazy_bottom - lazy_top) / img_h lazyop['crop_bbox'] = np.array([(lazy_left + left), (lazy_top + top), (lazy_left + right), (lazy_top + bottom)], dtype=np.float32) if 'gt_bboxes' in results: assert not self.lazy results = self._all_box_crop(results, results['crop_bbox']) return results def __repr__(self): repr_str = (f'{self.__class__.__name__}(crop_size={self.crop_size}, ' f'lazy={self.lazy})') return repr_str def _combine_quadruple(a, b): return (a[0] + a[2] * b[0], a[1] + a[3] * b[1], a[2] * b[2], a[3] * b[3]) @PIPELINES.register() class PoseCompact: """Convert the coordinates of keypoints to make it more compact. Specifically, it first find a tight bounding box that surrounds all joints in each frame, then we expand the tight box by a given padding ratio. For example, if 'padding == 0.25', then the expanded box has unchanged center, and 1.25x width and height. Required keys in results are "img_shape", "keypoint", add or modified keys are "img_shape", "keypoint", "crop_quadruple". Args: padding (float): The padding size. Default: 0.25. threshold (int): The threshold for the tight bounding box. If the width or height of the tight bounding box is smaller than the threshold, we do not perform the compact operation. Default: 10. hw_ratio (float | tuple[float] | None): The hw_ratio of the expanded box. Float indicates the specific ratio and tuple indicates a ratio range. If set as None, it means there is no requirement on hw_ratio. Default: None. allow_imgpad (bool): Whether to allow expanding the box outside the image to meet the hw_ratio requirement. Default: True. Returns: type: Description of returned object. """ def __init__(self, padding=0.25, threshold=10, hw_ratio=None, allow_imgpad=True, step=3, label=True): self.padding = padding self.threshold = threshold self.step = step self.label = label if hw_ratio is not None: # hw_ratio = _pair(hw_ratio) hw_ratio = (hw_ratio,hw_ratio) self.hw_ratio = hw_ratio self.allow_imgpad = allow_imgpad assert self.padding >= 0 def __call__(self, results): results['data']=downsample(results['data'],step=self.step,random_sample=False) data = results['data'].transpose(3,1,2,0) # (C,T,V,M)-->(M,T,V,C) if self.label: label = results['label'] # print(data[:,:,:,2].max(),data[:,:,:,2].min()) data[:,:,:,1] = data[:,:,:,1]*1080/2. + 1080/2. # scale y data[:,:,:,0] = data[:,:,:,0]*720/2. + 720/2. # scale x all_kps = data[:,:,:,:2] #(M,T,V,2) # print(data[:,:,:,2].max(),data[:,:,:,2].min()) # results['keypoint_score'] = data[:,:,:,2] #(M,T,V) results=dict() results['keypoint'] = all_kps results['keypoint_score'] = data[:,:,:,2] results['img_shape'] = (1080,720) if self.label: results['label'] = label results['modality']='pose' img_shape = results['img_shape'] h, w = img_shape kp = results['keypoint'] # Make NaN zero kp[np.isnan(kp)] = 0. kp_x = kp[..., 0] kp_y = kp[..., 1] min_x = np.min(kp_x[kp_x != 0], initial=np.Inf) min_y = np.min(kp_y[kp_y != 0], initial=np.Inf) max_x = np.max(kp_x[kp_x != 0], initial=-np.Inf) max_y = np.max(kp_y[kp_y != 0], initial=-np.Inf) # The compact area is too small if max_x - min_x < self.threshold or max_y - min_y < self.threshold: return results center = ((max_x + min_x) / 2, (max_y + min_y) / 2) half_width = (max_x - min_x) / 2 * (1 + self.padding) half_height = (max_y - min_y) / 2 * (1 + self.padding) if self.hw_ratio is not None: half_height = max(self.hw_ratio[0] * half_width, half_height) half_width = max(1 / self.hw_ratio[1] * half_height, half_width) min_x, max_x = center[0] - half_width, center[0] + half_width min_y, max_y = center[1] - half_height, center[1] + half_height # hot update if not self.allow_imgpad: min_x, min_y = int(max(0, min_x)), int(max(0, min_y)) max_x, max_y = int(min(w, max_x)), int(min(h, max_y)) else: min_x, min_y = int(min_x), int(min_y) max_x, max_y = int(max_x), int(max_y) kp_x[kp_x != 0] -= min_x kp_y[kp_y != 0] -= min_y new_shape = (max_y - min_y, max_x - min_x) results['img_shape'] = new_shape # the order is x, y, w, h (in [0, 1]), a tuple crop_quadruple = results.get('crop_quadruple', (0., 0., 1., 1.)) new_crop_quadruple = (min_x / w, min_y / h, (max_x - min_x) / w, (max_y - min_y) / h) crop_quadruple = _combine_quadruple(crop_quadruple, new_crop_quadruple) results['crop_quadruple'] = crop_quadruple return results def __repr__(self): repr_str = (f'{self.__class__.__name__}(padding={self.padding}, ' f'threshold={self.threshold}, ' f'hw_ratio={self.hw_ratio}, ' f'allow_imgpad={self.allow_imgpad})') return repr_str def _init_lazy_if_proper(results, lazy): """Initialize lazy operation properly. Make sure that a lazy operation is properly initialized, and avoid a non-lazy operation accidentally getting mixed in. Required keys in results are "imgs" if "img_shape" not in results, otherwise, Required keys in results are "img_shape", add or modified keys are "img_shape", "lazy". Add or modified keys in "lazy" are "original_shape", "crop_bbox", "flip", "flip_direction", "interpolation". Args: results (dict): A dict stores data pipeline result. lazy (bool): Determine whether to apply lazy operation. Default: False. """ if 'img_shape' not in results: results['img_shape'] = results['imgs'][0].shape[:2] if lazy: if 'lazy' not in results: img_h, img_w = results['img_shape'] lazyop = dict() lazyop['original_shape'] = results['img_shape'] lazyop['crop_bbox'] = np.array([0, 0, img_w, img_h], dtype=np.float32) lazyop['flip'] = False lazyop['flip_direction'] = None lazyop['interpolation'] = None results['lazy'] = lazyop else: assert 'lazy' not in results, 'Use Fuse after lazy operations' def imresize(img, size, return_scale=False, interpolation='bilinear', out=None, backend=None): """Resize image to a given size. Args: img (ndarray): The input image. size (tuple[int]): Target size (w, h). return_scale (bool): Whether to return `w_scale` and `h_scale`. interpolation (str): Interpolation method, accepted values are "nearest", "bilinear", "bicubic", "area", "lanczos" for 'cv2' backend, "nearest", "bilinear" for 'pillow' backend. out (ndarray): The output destination. backend (str | None): The image resize backend type. Options are `cv2`, `pillow`, `None`. If backend is None, the global imread_backend specified by ``mmcv.use_backend()`` will be used. Default: None. Returns: tuple | ndarray: (`resized_img`, `w_scale`, `h_scale`) or `resized_img`. """ h, w = img.shape[:2] resized_img = cv2.resize( img, size, dst=None, interpolation=cv2.INTER_LINEAR) return resized_img def _scale_size(size, scale): """Rescale a size by a ratio. Args: size (tuple[int]): (w, h). scale (float | tuple(float)): Scaling factor. Returns: tuple[int]: scaled size. """ if isinstance(scale, (float, int)): scale = (scale, scale) w, h = size return int(w * float(scale[0]) + 0.5), int(h * float(scale[1]) + 0.5) def rescale_size(old_size, scale, return_scale=False): """Calculate the new size to be rescaled to. Args: old_size (tuple[int]): The old size (w, h) of image. scale (float | tuple[int]): The scaling factor or maximum size. If it is a float number, then the image will be rescaled by this factor, else if it is a tuple of 2 integers, then the image will be rescaled as large as possible within the scale. return_scale (bool): Whether to return the scaling factor besides the rescaled image size. Returns: tuple[int]: The new rescaled image size. """ w, h = old_size if isinstance(scale, (float, int)): if scale <= 0: raise ValueError(f'Invalid scale {scale}, must be positive.') scale_factor = scale elif isinstance(scale, tuple): max_long_edge = max(scale) max_short_edge = min(scale) scale_factor = min(max_long_edge / max(h, w), max_short_edge / min(h, w)) else: raise TypeError( f'Scale must be a number or tuple of int, but got {type(scale)}') new_size = _scale_size((w, h), scale_factor) if return_scale: return new_size, scale_factor else: return new_size @PIPELINES.register() class Resize: """Resize images to a specific size. Required keys are "img_shape", "modality", "imgs" (optional), "keypoint" (optional), added or modified keys are "imgs", "img_shape", "keep_ratio", "scale_factor", "lazy", "resize_size". Required keys in "lazy" is None, added or modified key is "interpolation". Args: scale (float | Tuple[int]): If keep_ratio is True, it serves as scaling factor or maximum size: If it is a float number, the image will be rescaled by this factor, else if it is a tuple of 2 integers, the image will be rescaled as large as possible within the scale. Otherwise, it serves as (w, h) of output size. keep_ratio (bool): If set to True, Images will be resized without changing the aspect ratio. Otherwise, it will resize images to a given size. Default: True. interpolation (str): Algorithm used for interpolation: "nearest" | "bilinear". Default: "bilinear". lazy (bool): Determine whether to apply lazy operation. Default: False. """ def __init__(self, scale, keep_ratio=True, interpolation='bilinear', lazy=False): scale = tuple(scale) if isinstance(scale, float): if scale <= 0: raise ValueError(f'Invalid scale {scale}, must be positive.') elif isinstance(scale, tuple): max_long_edge = max(scale) max_short_edge = min(scale) if max_short_edge == -1: # assign np.inf to long edge for rescaling short edge later. scale = (np.inf, max_long_edge) else: raise TypeError( f'Scale must be float or tuple of int, but got {type(scale)}') self.scale = scale self.keep_ratio = keep_ratio self.interpolation = interpolation self.lazy = lazy def _resize_imgs(self, imgs, new_w, new_h): return [ imresize( img, (new_w, new_h), interpolation=self.interpolation) for img in imgs ] @staticmethod def _resize_kps(kps, scale_factor): return kps * scale_factor @staticmethod def _box_resize(box, scale_factor): """Rescale the bounding boxes according to the scale_factor. Args: box (np.ndarray): The bounding boxes. scale_factor (np.ndarray): The scale factor used for rescaling. """ assert len(scale_factor) == 2 scale_factor = np.concatenate([scale_factor, scale_factor]) return box * scale_factor def __call__(self, results): """Performs the Resize augmentation. Args: results (dict): The resulting dict to be modified and passed to the next transform in pipeline. """ _init_lazy_if_proper(results, self.lazy) if 'keypoint' in results: assert not self.lazy, ('Keypoint Augmentations are not compatible ' 'with lazy == True') if 'scale_factor' not in results: results['scale_factor'] = np.array([1, 1], dtype=np.float32) img_h, img_w = results['img_shape'] if self.keep_ratio: new_w, new_h = rescale_size((img_w, img_h), self.scale) else: new_w, new_h = self.scale self.scale_factor = np.array([new_w / img_w, new_h / img_h], dtype=np.float32) results['img_shape'] = (new_h, new_w) results['keep_ratio'] = self.keep_ratio results['scale_factor'] = results['scale_factor'] * self.scale_factor if not self.lazy: if 'imgs' in results: results['imgs'] = self._resize_imgs(results['imgs'], new_w, new_h) if 'keypoint' in results: results['keypoint'] = self._resize_kps(results['keypoint'], self.scale_factor) else: lazyop = results['lazy'] if lazyop['flip']: raise NotImplementedError('Put Flip at last for now') lazyop['interpolation'] = self.interpolation if 'gt_bboxes' in results: assert not self.lazy results['gt_bboxes'] = self._box_resize(results['gt_bboxes'], self.scale_factor) if 'proposals' in results and results['proposals'] is not None: assert results['proposals'].shape[1] == 4 results['proposals'] = self._box_resize( results['proposals'], self.scale_factor) return results def __repr__(self): repr_str = (f'{self.__class__.__name__}(' f'scale={self.scale}, keep_ratio={self.keep_ratio}, ' f'interpolation={self.interpolation}, ' f'lazy={self.lazy})') return repr_str def imflip_(img, direction='horizontal'): """Inplace flip an image horizontally or vertically. Args: img (ndarray): Image to be flipped. direction (str): The flip direction, either "horizontal" or "vertical" or "diagonal". Returns: ndarray: The flipped image (inplace). """ assert direction in ['horizontal', 'vertical', 'diagonal'] if direction == 'horizontal': return cv2.flip(img, 1, img) elif direction == 'vertical': return cv2.flip(img, 0, img) else: return cv2.flip(img, -1, img) def iminvert(img): """Invert (negate) an image. Args: img (ndarray): Image to be inverted. Returns: ndarray: The inverted image. """ return np.full_like(img, 255) - img ###########keypoint################### left_kp=[2,3,4,9,10,11,15,17,22,23,24] right_kp = [5,6,7,12,13,14,16,18,19,20,21,] @PIPELINES.register() class Flip: """Flip the input images with a probability. Reverse the order of elements in the given imgs with a specific direction. The shape of the imgs is preserved, but the elements are reordered. Required keys are "img_shape", "modality", "imgs" (optional), "keypoint" (optional), added or modified keys are "imgs", "keypoint", "lazy" and "flip_direction". Required keys in "lazy" is None, added or modified key are "flip" and "flip_direction". The Flip augmentation should be placed after any cropping / reshaping augmentations, to make sure crop_quadruple is calculated properly. Args: flip_ratio (float): Probability of implementing flip. Default: 0.5. direction (str): Flip imgs horizontally or vertically. Options are "horizontal" | "vertical". Default: "horizontal". flip_label_map (Dict[int, int] | None): Transform the label of the flipped image with the specific label. Default: None. left_kp (list[int]): Indexes of left keypoints, used to flip keypoints. Default: None. right_kp (list[ind]): Indexes of right keypoints, used to flip keypoints. Default: None. lazy (bool): Determine whether to apply lazy operation. Default: False. """ _directions = ['horizontal', 'vertical'] def __init__(self, flip_ratio=0.5, direction='horizontal', flip_label_map=None, left_kp=left_kp, right_kp=right_kp, lazy=False): if direction not in self._directions: raise ValueError(f'Direction {direction} is not supported. ' f'Currently support ones are {self._directions}') self.flip_ratio = flip_ratio self.direction = direction self.flip_label_map = flip_label_map self.left_kp = left_kp self.right_kp = right_kp self.lazy = lazy def _flip_imgs(self, imgs, modality): _ = [imflip_(img, self.direction) for img in imgs] lt = len(imgs) if modality == 'Flow': # The 1st frame of each 2 frames is flow-x for i in range(0, lt, 2): imgs[i] = iminvert(imgs[i]) return imgs def _flip_kps(self, kps, kpscores, img_width): kp_x = kps[..., 0] kp_x[kp_x != 0] = img_width - kp_x[kp_x != 0] new_order = list(range(kps.shape[2])) if self.left_kp is not None and self.right_kp is not None: for left, right in zip(self.left_kp, self.right_kp): new_order[left] = right new_order[right] = left kps = kps[:, :, new_order] if kpscores is not None: kpscores = kpscores[:, :, new_order] return kps, kpscores @staticmethod def _box_flip(box, img_width): """Flip the bounding boxes given the width of the image. Args: box (np.ndarray): The bounding boxes. img_width (int): The img width. """ box_ = box.copy() box_[..., 0::4] = img_width - box[..., 2::4] box_[..., 2::4] = img_width - box[..., 0::4] return box_ def __call__(self, results): """Performs the Flip augmentation. Args: results (dict): The resulting dict to be modified and passed to the next transform in pipeline. """ _init_lazy_if_proper(results, self.lazy) if 'keypoint' in results: assert not self.lazy, ('Keypoint Augmentations are not compatible ' 'with lazy == True') assert self.direction == 'horizontal', ( 'Only horizontal flips are' 'supported for human keypoints') modality = results['modality'] if modality == 'Flow': assert self.direction == 'horizontal' flip = np.random.rand() < self.flip_ratio results['flip'] = flip results['flip_direction'] = self.direction img_width = results['img_shape'][1] if self.flip_label_map is not None and flip: results['label'] = self.flip_label_map.get(results['label'], results['label']) if not self.lazy: if flip: if 'imgs' in results: results['imgs'] = self._flip_imgs(results['imgs'], modality) if 'keypoint' in results: kp = results['keypoint'] kpscore = results.get('keypoint_score', None) kp, kpscore = self._flip_kps(kp, kpscore, img_width) results['keypoint'] = kp if 'keypoint_score' in results: results['keypoint_score'] = kpscore else: lazyop = results['lazy'] if lazyop['flip']: raise NotImplementedError('Use one Flip please') lazyop['flip'] = flip lazyop['flip_direction'] = self.direction if 'gt_bboxes' in results and flip: assert not self.lazy and self.direction == 'horizontal' width = results['img_shape'][1] results['gt_bboxes'] = self._box_flip(results['gt_bboxes'], width) if 'proposals' in results and results['proposals'] is not None: assert results['proposals'].shape[1] == 4 results['proposals'] = self._box_flip(results['proposals'], width) return results def __repr__(self): repr_str = ( f'{self.__class__.__name__}(' f'flip_ratio={self.flip_ratio}, direction={self.direction}, ' f'flip_label_map={self.flip_label_map}, lazy={self.lazy})') return repr_str @PIPELINES.register() class GeneratePoseTarget: """Generate pseudo heatmaps based on joint coordinates and confidence. Required keys are "keypoint", "img_shape", "keypoint_score" (optional), added or modified keys are "imgs". Args: sigma (float): The sigma of the generated gaussian map. Default: 0.6. use_score (bool): Use the confidence score of keypoints as the maximum of the gaussian maps. Default: True. with_kp (bool): Generate pseudo heatmaps for keypoints. Default: True. with_limb (bool): Generate pseudo heatmaps for limbs. At least one of 'with_kp' and 'with_limb' should be True. Default: False. skeletons (tuple[tuple]): The definition of human skeletons. Default: ((0, 1), (0, 2), (1, 3), (2, 4), (0, 5), (5, 7), (7, 9), (0, 6), (6, 8), (8, 10), (5, 11), (11, 13), (13, 15), (6, 12), (12, 14), (14, 16), (11, 12)), which is the definition of COCO-17p skeletons. double (bool): Output both original heatmaps and flipped heatmaps. Default: False. left_kp (tuple[int]): Indexes of left keypoints, which is used when flipping heatmaps. Default: (1, 3, 5, 7, 9, 11, 13, 15), which is left keypoints in COCO-17p. right_kp (tuple[int]): Indexes of right keypoints, which is used when flipping heatmaps. Default: (2, 4, 6, 8, 10, 12, 14, 16), which is right keypoints in COCO-17p. """ def __init__(self, sigma=0.6, use_score=True, with_kp=True, with_limb=False, skeletons=((1, 8), (0, 1), (15, 0), (17, 15), (16, 0), (18, 16), (5, 1), (6, 5), (7, 6), (2, 1), (3, 2), (4, 3), (9, 8), (10, 9), (11, 10), (24, 11), (22, 11), (23, 22), (12, 8), (13, 12), (14, 13), (21, 14), (19, 14), (20, 19)), double=False): self.sigma = sigma self.use_score = use_score self.with_kp = with_kp self.with_limb = with_limb self.double = double # an auxiliary const self.eps = 1e-4 assert self.with_kp or self.with_limb, ( 'At least one of "with_limb" ' 'and "with_kp" should be set as True.') self.left_kp = left_kp self.right_kp = right_kp self.skeletons = skeletons def generate_a_heatmap(self, img_h, img_w, centers, sigma, max_values): """Generate pseudo heatmap for one keypoint in one frame. Args: img_h (int): The height of the heatmap. img_w (int): The width of the heatmap. centers (np.ndarray): The coordinates of corresponding keypoints (of multiple persons). sigma (float): The sigma of generated gaussian. max_values (np.ndarray): The max values of each keypoint. Returns: np.ndarray: The generated pseudo heatmap. """ heatmap = np.zeros([img_h, img_w], dtype=np.float32) for center, max_value in zip(centers, max_values): mu_x, mu_y = center[0], center[1] if max_value < self.eps: continue st_x = max(int(mu_x - 3 * sigma), 0) ed_x = min(int(mu_x + 3 * sigma) + 1, img_w) st_y = max(int(mu_y - 3 * sigma), 0) ed_y = min(int(mu_y + 3 * sigma) + 1, img_h) x = np.arange(st_x, ed_x, 1, np.float32) y = np.arange(st_y, ed_y, 1, np.float32) # if the keypoint not in the heatmap coordinate system if not (len(x) and len(y)): continue y = y[:, None] patch = np.exp(-((x - mu_x)**2 + (y - mu_y)**2) / 2 / sigma**2) patch = patch * max_value heatmap[st_y:ed_y, st_x:ed_x] = np.maximum(heatmap[st_y:ed_y, st_x:ed_x], patch) return heatmap def generate_a_limb_heatmap(self, img_h, img_w, starts, ends, sigma, start_values, end_values): """Generate pseudo heatmap for one limb in one frame. Args: img_h (int): The height of the heatmap. img_w (int): The width of the heatmap. starts (np.ndarray): The coordinates of one keypoint in the corresponding limbs (of multiple persons). ends (np.ndarray): The coordinates of the other keypoint in the corresponding limbs (of multiple persons). sigma (float): The sigma of generated gaussian. start_values (np.ndarray): The max values of one keypoint in the corresponding limbs. end_values (np.ndarray): The max values of the other keypoint in the corresponding limbs. Returns: np.ndarray: The generated pseudo heatmap. """ heatmap = np.zeros([img_h, img_w], dtype=np.float32) for start, end, start_value, end_value in zip(starts, ends, start_values, end_values): value_coeff = min(start_value, end_value) if value_coeff < self.eps: continue min_x, max_x = min(start[0], end[0]), max(start[0], end[0]) min_y, max_y = min(start[1], end[1]), max(start[1], end[1]) min_x = max(int(min_x - 3 * sigma), 0) max_x = min(int(max_x + 3 * sigma) + 1, img_w) min_y = max(int(min_y - 3 * sigma), 0) max_y = min(int(max_y + 3 * sigma) + 1, img_h) x = np.arange(min_x, max_x, 1, np.float32) y = np.arange(min_y, max_y, 1, np.float32) if not (len(x) and len(y)): continue y = y[:, None] x_0 = np.zeros_like(x) y_0 = np.zeros_like(y) # distance to start keypoints d2_start = ((x - start[0])**2 + (y - start[1])**2) # distance to end keypoints d2_end = ((x - end[0])**2 + (y - end[1])**2) # the distance between start and end keypoints. d2_ab = ((start[0] - end[0])**2 + (start[1] - end[1])**2) if d2_ab < 1: full_map = self.generate_a_heatmap(img_h, img_w, [start], sigma, [start_value]) heatmap = np.maximum(heatmap, full_map) continue coeff = (d2_start - d2_end + d2_ab) / 2. / d2_ab a_dominate = coeff <= 0 b_dominate = coeff >= 1 seg_dominate = 1 - a_dominate - b_dominate position = np.stack([x + y_0, y + x_0], axis=-1) projection = start + np.stack([coeff, coeff], axis=-1) * ( end - start) d2_line = position - projection d2_line = d2_line[:, :, 0]**2 + d2_line[:, :, 1]**2 d2_seg = ( a_dominate * d2_start + b_dominate * d2_end + seg_dominate * d2_line) patch = np.exp(-d2_seg / 2. / sigma**2) patch = patch * value_coeff heatmap[min_y:max_y, min_x:max_x] = np.maximum( heatmap[min_y:max_y, min_x:max_x], patch) return heatmap def generate_heatmap(self, img_h, img_w, kps, sigma, max_values): """Generate pseudo heatmap for all keypoints and limbs in one frame (if needed). Args: img_h (int): The height of the heatmap. img_w (int): The width of the heatmap. kps (np.ndarray): The coordinates of keypoints in this frame. sigma (float): The sigma of generated gaussian. max_values (np.ndarray): The confidence score of each keypoint. Returns: np.ndarray: The generated pseudo heatmap. """ heatmaps = [] if self.with_kp: num_kp = kps.shape[1] for i in range(num_kp): heatmap = self.generate_a_heatmap(img_h, img_w, kps[:, i], sigma, max_values[:, i]) heatmaps.append(heatmap) if self.with_limb: for limb in self.skeletons: start_idx, end_idx = limb starts = kps[:, start_idx] ends = kps[:, end_idx] start_values = max_values[:, start_idx] end_values = max_values[:, end_idx] heatmap = self.generate_a_limb_heatmap(img_h, img_w, starts, ends, sigma, start_values, end_values) heatmaps.append(heatmap) return np.stack(heatmaps, axis=-1) def gen_an_aug(self, results): """Generate pseudo heatmaps for all frames. Args: results (dict): The dictionary that contains all info of a sample. Returns: list[np.ndarray]: The generated pseudo heatmaps. """ all_kps = results['keypoint'] kp_shape = all_kps.shape if 'keypoint_score' in results: all_kpscores = results['keypoint_score'] else: all_kpscores = np.ones(kp_shape[:-1], dtype=np.float32) img_h, img_w = results['img_shape'] num_frame = kp_shape[1] imgs = [] for i in range(num_frame): sigma = self.sigma kps = all_kps[:, i] kpscores = all_kpscores[:, i] max_values = np.ones(kpscores.shape, dtype=np.float32) if self.use_score: max_values = kpscores hmap = self.generate_heatmap(img_h, img_w, kps, sigma, max_values) imgs.append(hmap) return imgs def __call__(self, results): if not self.double: results['data'] = np.stack(self.gen_an_aug(results)).transpose(3,0,1,2)#(T,H,W,V)-->(V,T,H,W) results['data'] = normalize(results['data']) results['data'] = results['data'].astype('float32') if 'label' in results: label = results['label'] results['label'] = np.expand_dims(label, 0).astype('int64') return results
python
class RoundEdge: def __init__(self, r, obj): self.r = r self.obj = obj self.material = obj.material self.color = obj.color def signedDistance(self, point): return self.obj.signedDistance(point) - self.r def evalColorAtPoint(self, point): return self.obj.evalColorAtPoint(point)
python
# -*- coding: utf-8 -*- """ unistorage.adapters.amazon ~~~~~~~~~~~~~~~~~~~~~~~~~~ This module an adapter for Amazon Simple Storage Service (S3). :copyright: (c) 2012 by Janne Vanhala. :license: BSD, see LICENSE for more details. """ from datetime import datetime, timedelta from email.utils import parsedate_tz from unistorage.exceptions import FileNotFound from unistorage.interface import Adapter class AmazonS3(Adapter): """ An adapter for Amazon Simple Storage Service (S3). This adapter requires an boto_ library to be installed. You can install it by executing the following command in the terminal:: pip install boto .. _boto: https://github.com/boto/boto Constructor arguments are as follows: :type access_key: str :param access_key: your Amazon Web Services access key id :type secret_key: str :param secret_key: your Amazon Web Services secret access key :type bucket_name: str :param bucket_name: your Amazon S3 bucket name :type use_query_auth: bool :param use_query_auth: :method:`url` should use query string authentication to sign the URL. This is useful for enabling direct access to private Amazon S3 data without proxying the request. Defaults to ``True``. :type querystring_expires: int :param querystring_expires: The number of seconds a URL signed with query string authentication is valid before expiring. Defaults to 3600 (one hour). """ def __init__(self, access_key, secret_key, bucket_name, use_query_auth=True, querystring_expires=3600): boto = self._import_boto() self.connection = boto.connect_s3(access_key, secret_key) self.bucket_name = bucket_name self.use_query_auth = use_query_auth self.querystring_expires = querystring_expires @property def bucket(self): """ The :class:`boto.s3.Bucket` instance with the name :attr:`bucket_name`. """ if not hasattr(self, '_bucket'): self._bucket = self._get_or_create_bucket() return self._bucket def _get_or_create_bucket(self): """ Retrive the bucket with the name :attr:`bucket_name`, and create one if necessary. :return: a :class:`boto.s3.Bucket` instance """ from boto.exception import S3ResponseError try: bucket = self.connection.get_bucket(self.bucket_name) except S3ResponseError as exc: if exc.status != 404: raise bucket = self.connection.create_bucket(self.bucket_name) return bucket def _import_boto(self): """ Import and return :module:`boto`. If the module cannot be imported, for example due to it not being installed, a :exception:`RuntimeError` is raised. """ try: import boto except ImportError: raise RuntimeError( 'Could not import boto. Amazon S3 adapter requires boto ' 'library to be installed. You can install it by executing ' '``pip install boto`` in the terminal.' ) return boto def delete(self, name): self.bucket.delete_key(name) def exists(self, name): key = self.bucket.new_key(name) return key.exists() def write(self, name, content): key = self.bucket.new_key(name) key.set_contents_from_string(content) def read(self, name): key = self.bucket.get_key(name) if not key: raise FileNotFound(name) return key.get_contents_as_string() def size(self, name): key = self.bucket.get_key(name) if not key: raise FileNotFound(name) return key.size def list(self): for key in self.bucket.list(): yield key.name def modified(self, name): key = self.bucket.get_key(name) if not key: raise FileNotFound(name) t = parsedate_tz(key.last_modified) return datetime(*t[:7]) - timedelta(seconds=t[-1]) def url(self, name): return self.connection.generate_url( expires_in=self.querystring_expires, method='GET', bucket=self.bucket_name, key=name, query_auth=self.use_query_auth )
python
import numpy as np import time #Note, all modes should have a return to forward, to prevent stucks def forward_mode(Rover): # Calm the roll and pitch if (Rover.roll >= 1.5 and Rover.roll <= 358.5) or (Rover.pitch >= 1.5 and Rover.pitch <= 359): Rover.max_vel = 0.5 else: Rover.max_vel = 5 #Segment for follow only nearest left wall angles steer_angles = np.concatenate((Rover.nav_anglesA,Rover.nav_anglesB),axis=0) if len(steer_angles) <= 20: steer_angles = np.copy(Rover.nav_anglesC) #if you don't have enough at the left, turn right # Check the extent of navigable terrain if len(Rover.nav_angles) >= Rover.stop_forward: # If mode is forward, navigable terrain looks good # and velocity is below max, then throttle if Rover.vel < Rover.max_vel: # Set throttle value to throttle setting Rover.throttle = Rover.throttle_set else: # Else coast Rover.throttle = 0 Rover.brake = 0 # Set steering to average angle clipped to the range +/- 15 #Rover.steer = np.clip(np.mean(Rover.nav_angles * 180/np.pi), -15, 15) Rover.steer = np.clip(np.mean(steer_angles* 180/np.pi), -15, 15) #Using this eventually crash, not founded explain # If there's a lack of navigable terrain pixels then go to 'stop' mode elif len(Rover.nav_angles) < Rover.stop_forward: # Set mode to "stop" and hit the brakes! Rover.throttle = 0 # Set brake to stored brake value Rover.brake = Rover.brake_set Rover.steer = 0 Rover.mode = 'stop' # If rover have the six samples, and is near home, just stop. (Homing by chance xD) if Rover.samples_collected == 6: #if Rover.total_time >= 30: dist_to_home = np.sqrt((Rover.pos[0] - Rover.start_pos[0])**2+ (Rover.pos[1] - Rover.start_pos[1])**2) #print("dist_home",dist_to_home,"\n\n") #print("Have all the balls! \n \n \n \n \n \n \n") #print("Home position",Rover.pos,"\n\n") if dist_to_home <= 30.0: #print("Enter home_alone") Rover.mode='home_alone' ## Checking if stuck if Rover.vel <= 0.05: Rover.stuck +=1 else: Rover.stuck = 0 if Rover.stuck >=100: Rover.mode = 'stuck' Rover.stuck = 0 def stop_mode(Rover): # If we're in stop mode but still moving keep braking if Rover.vel > 0.2: Rover.throttle = 0 Rover.brake = Rover.brake_set Rover.steer = 0 # If we're not moving (vel < 0.2) then do something else elif Rover.vel <= 0.2: # Now we're stopped and we have vision data to see if there's a path forward if len(Rover.nav_angles) < Rover.go_forward: Rover.throttle = 0 # Release the brake to allow turning Rover.brake = 0 # Turn range is +/- 15 degrees, when stopped the next line will induce 4-wheel turning Rover.steer = -15 # Could be more clever here about which way to turn # If we're stopped but see sufficient navigable terrain in front then go! if len(Rover.nav_angles) >= Rover.go_forward: # Set throttle back to stored value Rover.throttle = Rover.throttle_set # Release the brake Rover.brake = 0 # Set steer to mean angle Rover.steer = np.clip(np.mean(Rover.nav_angles * 180/np.pi), -15, 15) Rover.mode = 'forward' def stuck_mode(Rover): # print("HEEEEYYYY ____------___--_--____\n \n \n \n ") # print(Rover.mode) if Rover.stuck == 0: Rover.stuck_time = time.time() Rover.stuck+=1 if time.time() <= Rover.stuck_time + 3: Rover.throttle = -1 elif time.time()>Rover.stuck_time + 3 and time.time()<=Rover.stuck_time + 6: Rover.throttle = 0 Rover.steer = -10 elif time.time()>Rover.stuck_time + 6: Rover.stuck=0 Rover.stuck_time=0 Rover.mode='forward' def home_alone(Rover): #this mode does not need a pass to another state, it is the end # If rover have the six samples, and is near home, just stop. (Homing by chance xD) Rover.brake = 10 Rover.steer = 10 Rover.throttle = 0 def rock_chasin(Rover): pass # This is where you can build a decision tree for determining throttle, brake and steer # commands based on the output of the perception_step() function def decision_step(Rover): #print(Rover.nav_anglesA.dtype) #print(Rover.nav_anglesA) #print(Rover.nav_anglesB) #print(steer_angles) # Implement conditionals to decide what to do given perception data # Here you're all set up with some basic functionality but you'll need to # improve on this decision tree to do a good job of navigating autonomously! print('this is the decision step') # Save starting position if Rover.start_pos==None: Rover.start_pos = Rover.pos # Example: # Check if we have vision data to make decisions with if Rover.nav_angles is not None: print('Rover.mode ==',Rover.mode,'\n') # Check for Rover.mode status #Note, Machine states reordered for clarity and easy of modification # forward mode is basically the default mode. Lot of main decision are made there. if Rover.mode == 'forward': forward_mode(Rover) # If we're already in "stop" mode then make different decisions elif Rover.mode == 'stop': stop_mode(Rover) elif Rover.mode == 'stuck': stuck_mode(Rover) elif Rover.mode == 'home_alone': home_alone(Rover) elif Rover.mode == 'rock_chasin': rock_chasin(Rover) # Just to make the rover do something # even if no modifications have been made to the code else: Rover.throttle = Rover.throttle_set Rover.steer = 0 Rover.brake = 0 # If in a state where want to pickup a rock send pickup command if Rover.near_sample and Rover.vel == 0 and not Rover.picking_up: Rover.send_pickup = True return Rover
python
# License: MIT License import typing import numpy as np class Trajectory(object): """ Abstracts the infos about a complete set of trajectories, represented as a numpy array of doubles (the time deltas) and a numpy matrix of ints (the changes of states). :param list_of_columns: the list containing the times array and values matrix :type list_of_columns: List :param original_cols_number: total number of cols in the data :type original_cols_number: int :_actual_trajectory: the trajectory containing also the duplicated/shifted values :_times: the array containing the time deltas """ def __init__(self, list_of_columns: typing.List, original_cols_number: int): """Constructor Method """ self._times = list_of_columns[0] self._actual_trajectory = list_of_columns[1] self._original_cols_number = original_cols_number @property def trajectory(self) -> np.ndarray: return self._actual_trajectory[:, :self._original_cols_number - 1] @property def complete_trajectory(self) -> np.ndarray: return self._actual_trajectory @property def times(self): return self._times def size(self): return self._actual_trajectory.shape[0] def __repr__(self): return "Complete Trajectory Rows: " + str(self.size()) + "\n" + self.complete_trajectory.__repr__() + \ "\nTimes Rows:" + str(self.times.size) + "\n" + self.times.__repr__()
python
# -*- coding: utf-8 -*- # Copyright 2016 Battelle Energy Alliance, 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 # # 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. from __future__ import unicode_literals, absolute_import from ci.tests import DBTester, utils import datetime from ci import EventsStatus, models class Tests(DBTester.DBTester): def create_events(self): self.set_counts() self.build_user = utils.create_user_with_token(name="moosebuild") self.owner = utils.create_user(name="idaholab") self.repo = utils.create_repo(name="civet", user=self.owner) self.branch = utils.create_branch(name="devel", repo=self.repo) pre = utils.create_recipe(name="Precheck", user=self.build_user, repo=self.repo) test = utils.create_recipe(name="Test", user=self.build_user, repo=self.repo) test1 = utils.create_recipe(name="Test1", user=self.build_user, repo=self.repo) test.depends_on.add(pre) test1.depends_on.add(pre) merge = utils.create_recipe(name="Merge", user=self.build_user, repo=self.repo) merge.depends_on.add(test) merge.depends_on.add(test1) pr = utils.create_pr(title="{a, b} & <c> … somereallylongwordthatshouldgettruncated", repo=self.repo) pr.username = 'pr_user' pr.save() for commit in ['1234', '2345', '3456']: e = utils.create_event(user=self.owner, commit1=commit, branch1=self.branch, branch2=self.branch) e.pull_request = pr e.description = "some description" e.save() j = utils.create_job(recipe=pre, event=e, user=self.build_user) j.seconds = datetime.timedelta(seconds=10) j.failed_step = 'failed step' j.running_step = '3/5' j.save() utils.create_job(recipe=test, event=e, user=self.build_user) utils.create_job(recipe=test1, event=e, user=self.build_user) utils.create_job(recipe=merge, event=e, user=self.build_user) self.compare_counts(recipes=4, deps=4, current=4, jobs=12, active=12, num_pr_recipes=4, events=3, users=2, repos=1, branches=1, commits=3, prs=1) def test_get_default_events_query(self): self.create_events() q = EventsStatus.get_default_events_query() with self.assertNumQueries(1): self.assertEqual(q.count(), 3) event_q = models.Event.objects.filter(head__sha="1234") q = EventsStatus.get_default_events_query(event_q=event_q) with self.assertNumQueries(1): self.assertEqual(q.count(), 1) event_q = models.Event.objects.filter(head__sha="invalid") q = EventsStatus.get_default_events_query(event_q=event_q) with self.assertNumQueries(1): self.assertEqual(q.count(), 0) def test_all_events_info(self): self.create_events() with self.assertNumQueries(4): info = EventsStatus.all_events_info() self.assertEqual(len(info), 3) # pre, blank, test, test1, blank, merge self.assertEqual(len(info[0]["jobs"]), 6) # make sure limit works with self.assertNumQueries(4): info = EventsStatus.all_events_info(limit=1) self.assertEqual(len(info), 1) self.assertEqual(len(info[0]["jobs"]), 6) last_modified = models.Event.objects.last().last_modified last_modified = last_modified + datetime.timedelta(0,10) # make sure last_modified works with self.assertNumQueries(4): info = EventsStatus.all_events_info(last_modified=last_modified) self.assertEqual(len(info), 0) def test_events_with_head(self): self.create_events() q = EventsStatus.events_with_head() with self.assertNumQueries(1): self.assertEqual(q.count(), 3) event_q = models.Event.objects.filter(head__sha="1234") q = EventsStatus.events_with_head(event_q=event_q) q = EventsStatus.get_default_events_query(event_q=event_q) with self.assertNumQueries(1): self.assertEqual(q.count(), 1) event_q = models.Event.objects.filter(head__sha="invalid") q = EventsStatus.events_with_head(event_q=event_q) with self.assertNumQueries(1): self.assertEqual(q.count(), 0) def test_events_info(self): self.create_events() ev = models.Event.objects.first() info = EventsStatus.events_info([ev]) self.assertEqual(len(info), 1) ev = models.Event.objects.all() info = EventsStatus.events_info(ev) self.assertEqual(len(info), 3) def test_multi_line(self): self.create_events() e = utils.create_event(user=self.owner, commit1='456', branch1=self.branch, branch2=self.branch, cause=models.Event.PUSH) e.description = "some description" e.save() event_q = EventsStatus.get_default_events_query()[:30] info = EventsStatus.multiline_events_info(event_q, max_jobs_per_line=100) self.assertEqual(len(info), 3) self.assertEqual(len(info[0]["jobs"]), 6) info = EventsStatus.multiline_events_info(event_q, max_jobs_per_line=1) self.assertEqual(len(info), 18) def test_get_single_event_for_open_prs(self): self.create_events() pr = models.PullRequest.objects.latest() latest_event = pr.events.latest() # 1. main PullRequest query # 2. latest() for each PullRequest # 3. jobs query below with self.assertNumQueries(3): info = EventsStatus.get_single_event_for_open_prs([pr.pk]) self.assertEqual(len(info), 1) # should only have the latest event self.assertEqual(info[0].pk, latest_event.pk) # pre, test, test1, merge self.assertEqual(info[0].jobs.count(), 4) last_modified = latest_event.last_modified + datetime.timedelta(0,10) with self.assertNumQueries(2): info = EventsStatus.get_single_event_for_open_prs([pr.pk], last_modified) self.assertEqual(len(info), 0) last_modified = latest_event.last_modified - datetime.timedelta(0,10) with self.assertNumQueries(2): info = EventsStatus.get_single_event_for_open_prs([pr.pk], last_modified) self.assertEqual(len(info), 1) self.assertEqual(info[0].pk, latest_event.pk)
python
# emacs: -*- mode: python-mode; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: """Conversions between formats.""" import numpy as np import pytest from .. import linear as _l from ..io import LinearTransformArray as LTA @pytest.mark.parametrize( "filename", [ "from-fsnative_to-bold_mode-image", "from-fsnative_to-scanner_mode-image", "from-scanner_to-bold_mode-image", "from-scanner_to-fsnative_mode-image", ], ) def test_lta2itk_conversions(data_path, filename): """Check conversions between formats.""" lta = _l.load(data_path / "regressions" / ".".join((filename, "lta")), fmt="lta") itk = _l.load(data_path / "regressions" / ".".join((filename, "tfm")), fmt="itk") assert np.allclose(lta.matrix, itk.matrix) @pytest.mark.parametrize( "filename,moving,reference", [ ("from-fsnative_to-bold_mode-image", "T1w_fsnative.nii.gz", "bold.nii.gz"), ( "from-fsnative_to-scanner_mode-image", "T1w_fsnative.nii.gz", "T1w_scanner.nii.gz", ), ("from-scanner_to-bold_mode-image", "T1w_scanner.nii.gz", "bold.nii.gz"), ( "from-scanner_to-fsnative_mode-image", "T1w_scanner.nii.gz", "T1w_fsnative.nii.gz", ), ], ) def test_itk2lta_conversions( data_path, testdata_path, tmp_path, filename, moving, reference ): """Check conversions between formats.""" itk = _l.load(data_path / "regressions" / "".join((filename, ".tfm")), fmt="itk") itk.reference = testdata_path / reference itk.to_filename(tmp_path / "test.lta", fmt="fs", moving=testdata_path / moving) converted_lta = LTA.from_filename(tmp_path / "test.lta") expected_fname = ( data_path / "regressions" / "".join((filename, "_type-ras2ras.lta")) ) if not expected_fname.exists(): expected_fname = data_path / "regressions" / "".join((filename, ".lta")) exp_lta = LTA.from_filename(expected_fname) assert np.allclose(converted_lta["xforms"][0]["m_L"], exp_lta["xforms"][0]["m_L"]) def test_concatenation(data_path): """Check replacement to lta_concat.""" lta0 = _l.load( data_path / "regressions" / "from-scanner_to-fsnative_mode-image.lta", fmt="lta" ) lta1 = _l.load( data_path / "regressions" / "from-fsnative_to-bold_mode-image.lta", fmt="lta" ) lta_combined = _l.load( data_path / "regressions" / "from-scanner_to-bold_mode-image.lta", fmt="lta" ) assert np.allclose(lta1.matrix.dot(lta0.matrix), lta_combined.matrix)
python
import sys import os class Configuration: ###################################### ###### Configuration parameters ###### ###################################### # Change them if required # path to the root of ExaHyPe from this file pathToExaHyPERoot = os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "..")) # path to the gemm generator from this file pathToLibxsmmGemmGenerator = os.path.abspath(os.path.join(pathToExaHyPERoot, "Submodules", "libxsmm", "bin", "libxsmm_gemm_generator")) # path to jinja2 pathToJinja2 = os.path.abspath(os.path.join(pathToExaHyPERoot, "Submodules", "jinja")) # path to markupsafe pathToMarkupsafe = os.path.abspath(os.path.join(pathToExaHyPERoot, "Submodules", "markupsafe", "src")) # simd size of the accepted architectures simdWidth = { "noarch" : 1, "wsm" : 2, "snb" : 4, "hsw" : 4, "knc" : 8, "knl" : 8, "skx" : 8 } # set to false to use standard loops instead of libxsmm useLibxsmm = True; # set to true to print models runtime runtimeDebug = False; @staticmethod def checkPythonVersion(): """check version. Python 3.3 required""" requiredVersion = (3,3) currentVersion = sys.version_info if(requiredVersion > currentVersion): sys.exit("Requires Python 3.3 or newer. Abort.") def checkDependencies(): """check all dependencies are reachable from the configuration path""" # Check jinja sys.path.insert(1, Configuration.pathToJinja2) sys.path.insert(1, Configuration.pathToMarkupsafe) import jinja2 # Remove added path sys.path.remove(Configuration.pathToJinja2) sys.path.remove(Configuration.pathToMarkupsafe)
python
from socket import socket, AF_INET, SOCK_STREAM from message_handler import MessageHandler from string_match import match from rsa_ops import init_rsa class Client: def __init__(self, server_adr, bsize=1024): self.server_adr = server_adr # a tuple self.bsize = bsize self.pubkey, self.privkey = init_rsa() def run(self): sock = socket(AF_INET, SOCK_STREAM) sock.connect(self.server_adr) print("Client started") mh = MessageHandler(sock, self.bsize, self.pubkey, self.privkey) print("Enter command after the PocketDB > prompt. Enter .exit to exit") while True: print("PocketDB > ", end='') command = input().strip() if command == ".q": mh.send_message("\n") break if command.startswith("filter"): mh.send_message("select") data = mh.receive_message() lines = data.split("\n") lines = lines[1:-1] words = [i.strip() for i in lines] target = command.split()[1:] target = ' '.join(target) rst = [] words.pop() for word in words: if match(target, word.split(',')[1].strip()): rst.append(word) print(">Matched results:") print(rst) continue mh.send_message(command) data = mh.receive_message() if data == "\n\n\n": break print(data) print("Database connection closed") if __name__ == '__main__': client = Client(('127.0.0.1', 9001)) client.run()
python
from django.db import models from datetime import date class CompletionDate(models.Model): """Store a task completion on a certain date""" completion_date = models.DateField(auto_now_add=True, primary_key=True) class Task(models.Model): """Daily task model and related functions""" task_id = models.AutoField(primary_key=True) task_name = models.CharField(max_length=50) task_completed = models.BooleanField(default="False") task_streak = models.IntegerField(default=0) task_maxstreak = models.IntegerField(default=0) # Relationship with CompletionDate objects this task was completed on completion_dates = models.ManyToManyField(CompletionDate) # Date maxstreak is completed on maxstreak_date = models.DateField(default=date.today) # Order tasks are displayed in order = models.IntegerField(blank=True) def save(self, *args, **kwargs): """Override save to set the order""" if self.order is None: self.order = Task.objects.count() super(Task, self).save(*args, **kwargs) def increment_streak(self): """Increase the current task streak and set max streak if necessary""" self.task_streak += 1 # Create a new completion date object, or return one for today today = date.today() date_obj, created = CompletionDate.objects.get_or_create( completion_date=today) self.completion_dates.add(date_obj) # Update max streak if necessary if self.task_maxstreak < self.task_streak: self.task_maxstreak = self.task_streak self.maxstreak_date = date.today() self.save() def decrement_streak(self): """Decrease the current task streak and set max streak if necessary""" # Do nothing if streak already at 0 if self.task_streak == 0: return self.task_streak -= 1 # Remove task from completion date relationship today = date.today() self.completion_dates.remove( CompletionDate.objects.get(completion_date=today)) # Update maxstreak if it was set today if self.maxstreak_date == date.today(): self.task_maxstreak = self.task_streak self.save()
python
#!/usr/bin/env python import keras import numpy as np from imgaug import augmenters as iaa from keras.applications.mobilenet import preprocess_input from keras.preprocessing.image import image class CustomDataGenerator(keras.utils.Sequence): """ Takes input of image paths and corresponding labels and generates batches of tensor image data with real-time data augmentation. The data will be looped over (in batches). """ def __init__(self, images_paths, labels, batch_size=64, image_dimensions=(224, 224, 3), shuffle=False, augment=False): self.images_paths = images_paths # array of image paths. self.labels = labels # array of labels self.batch_size = batch_size # batch size. self.dim = image_dimensions # image dimensions. self.shuffle = shuffle # shuffle Boolean (default False). self.augment = augment # augment Boolean (default False). self.on_epoch_end() def __len__(self): """Denotes the number of batches per epoch""" return int(np.floor(len(self.images_paths) / self.batch_size)) def on_epoch_end(self): """Updates indexes after each epoch""" self.indexes = np.arange(len(self.images_paths)) if self.shuffle: np.random.shuffle(self.indexes) def __getitem__(self, index): """Generate one batch of data""" # selects indices of data for next batch indexes = self.indexes[index * self.batch_size: (index + 1) * self.batch_size] # select data and load images labels = np.array([self.labels[k] for k in indexes]) images = [image.img_to_array(image.load_img(self.images_paths[k], target_size=(224, 224))) for k in indexes] # preprocess and augment data if self.augment: images = self.augmentor(images) images = np.array([preprocess_input(img) for img in images]) return images, labels def augmentor(self, images): """Apply data augmentation""" sometimes = lambda aug: iaa.Sometimes(1, aug) seq = iaa.Sequential( [ iaa.Fliplr(0.5), # horizontally flip 50% of images sometimes(iaa.Affine( translate_percent={"x": (-0.1, 0.1), "y": (-0.1, 0.1)}, # translate by -20 to +20 percent (per axis) rotate=(-10, 10), # rotate by -10 to +10 degrees )) ] ) return seq.augment_images(images)
python
# Generated by Django 3.2.7 on 2021-10-06 22:44 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('app', '0008_alter_review_reviewer'), ] operations = [ migrations.AlterField( model_name='watchlist', name='platforms', field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='watchlist', to='app.streamplatform'), ), ]
python
# # PySNMP MIB module APPACCELERATION-STATUS-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/APPACCELERATION-STATUS-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 17:07:44 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15) # appAccelerationMgmt, appAccelerationNotifications = mibBuilder.importSymbols("APPACCELERATION-SMI", "appAccelerationMgmt", "appAccelerationNotifications") AppAccelerationAlarmSeverity, AppAccelerationSeqNum, AppAccelerationYesNo, AppAccelerationDescription = mibBuilder.importSymbols("APPACCELERATION-TC", "AppAccelerationAlarmSeverity", "AppAccelerationSeqNum", "AppAccelerationYesNo", "AppAccelerationDescription") Integer, ObjectIdentifier, OctetString = mibBuilder.importSymbols("ASN1", "Integer", "ObjectIdentifier", "OctetString") NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues") ConstraintsIntersection, ValueSizeConstraint, SingleValueConstraint, ValueRangeConstraint, ConstraintsUnion = mibBuilder.importSymbols("ASN1-REFINEMENT", "ConstraintsIntersection", "ValueSizeConstraint", "SingleValueConstraint", "ValueRangeConstraint", "ConstraintsUnion") InetAddress, InetAddressType, InetAddressPrefixLength = mibBuilder.importSymbols("INET-ADDRESS-MIB", "InetAddress", "InetAddressType", "InetAddressPrefixLength") ObjectGroup, ModuleCompliance, NotificationGroup = mibBuilder.importSymbols("SNMPv2-CONF", "ObjectGroup", "ModuleCompliance", "NotificationGroup") NotificationType, Counter32, Gauge32, MibIdentifier, TimeTicks, Unsigned32, ModuleIdentity, Counter64, iso, Bits, Integer32, ObjectIdentity, MibScalar, MibTable, MibTableRow, MibTableColumn, IpAddress = mibBuilder.importSymbols("SNMPv2-SMI", "NotificationType", "Counter32", "Gauge32", "MibIdentifier", "TimeTicks", "Unsigned32", "ModuleIdentity", "Counter64", "iso", "Bits", "Integer32", "ObjectIdentity", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "IpAddress") DisplayString, TextualConvention = mibBuilder.importSymbols("SNMPv2-TC", "DisplayString", "TextualConvention") appAccelerationStatusMIB = ModuleIdentity((1, 3, 6, 1, 4, 1, 3845, 30, 4, 1)) if mibBuilder.loadTexts: appAccelerationStatusMIB.setLastUpdated('201310110000Z') if mibBuilder.loadTexts: appAccelerationStatusMIB.setOrganization('www.citrix.com') wsStatusMIBObjects = MibIdentifier((1, 3, 6, 1, 4, 1, 3845, 30, 4, 1, 1)) wsStatusMIBNotifications = MibIdentifier((1, 3, 6, 1, 4, 1, 3845, 30, 5, 1)) wsStatusMIBConformance = MibIdentifier((1, 3, 6, 1, 4, 1, 3845, 30, 4, 1, 2)) wsStatusMIBScalars = MibIdentifier((1, 3, 6, 1, 4, 1, 3845, 30, 4, 1, 1, 1)) wsOperStatus = MibScalar((1, 3, 6, 1, 4, 1, 3845, 30, 4, 1, 1, 1, 1), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 100, 101, 102, 103))).clone(namedValues=NamedValues(("active", 1), ("busy", 100), ("down", 101), ("licenseExpired", 102), ("bypassTraffic", 103)))).setMaxAccess("readonly") if mibBuilder.loadTexts: wsOperStatus.setStatus('current') wsLoad1Min = MibScalar((1, 3, 6, 1, 4, 1, 3845, 30, 4, 1, 1, 1, 2), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: wsLoad1Min.setStatus('deprecated') wsLoad5Min = MibScalar((1, 3, 6, 1, 4, 1, 3845, 30, 4, 1, 1, 1, 3), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: wsLoad5Min.setStatus('deprecated') wsLoad15Min = MibScalar((1, 3, 6, 1, 4, 1, 3845, 30, 4, 1, 1, 1, 4), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: wsLoad15Min.setStatus('deprecated') wsBypass = MibScalar((1, 3, 6, 1, 4, 1, 3845, 30, 4, 1, 1, 1, 5), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("normal", 1), ("bypass", 2)))).setMaxAccess("readonly") if mibBuilder.loadTexts: wsBypass.setStatus('current') wsLastAlarmSeqNum = MibScalar((1, 3, 6, 1, 4, 1, 3845, 30, 4, 1, 1, 1, 6), AppAccelerationSeqNum()).setMaxAccess("readonly") if mibBuilder.loadTexts: wsLastAlarmSeqNum.setStatus('current') wsBoostStatus = MibScalar((1, 3, 6, 1, 4, 1, 3845, 30, 4, 1, 1, 1, 7), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("hardboost", 1), ("softboost", 2)))).setMaxAccess("readonly") if mibBuilder.loadTexts: wsBoostStatus.setStatus('deprecated') wsBandwidthMode = MibScalar((1, 3, 6, 1, 4, 1, 3845, 30, 4, 1, 1, 1, 8), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("full", 1), ("partial", 2)))).setMaxAccess("readonly") if mibBuilder.loadTexts: wsBandwidthMode.setStatus('current') wsBandwidthLimit = MibScalar((1, 3, 6, 1, 4, 1, 3845, 30, 4, 1, 1, 1, 9), Integer32()).setUnits('K-Bits/sec').setMaxAccess("readonly") if mibBuilder.loadTexts: wsBandwidthLimit.setStatus('current') wsWanOutOctets = MibScalar((1, 3, 6, 1, 4, 1, 3845, 30, 4, 1, 1, 1, 10), Counter64()).setUnits('Octets').setMaxAccess("readonly") if mibBuilder.loadTexts: wsWanOutOctets.setStatus('current') wsWanInOctets = MibScalar((1, 3, 6, 1, 4, 1, 3845, 30, 4, 1, 1, 1, 11), Counter64()).setUnits('Octets').setMaxAccess("readonly") if mibBuilder.loadTexts: wsWanInOctets.setStatus('current') wsLanOutOctets = MibScalar((1, 3, 6, 1, 4, 1, 3845, 30, 4, 1, 1, 1, 12), Counter64()).setUnits('Octets').setMaxAccess("readonly") if mibBuilder.loadTexts: wsLanOutOctets.setStatus('current') wsLanInOctets = MibScalar((1, 3, 6, 1, 4, 1, 3845, 30, 4, 1, 1, 1, 13), Counter64()).setUnits('Octets').setMaxAccess("readonly") if mibBuilder.loadTexts: wsLanInOctets.setStatus('current') wsCompressionEffectiveBandwidth = MibScalar((1, 3, 6, 1, 4, 1, 3845, 30, 4, 1, 1, 1, 14), Integer32()).setUnits('K-Bits/sec').setMaxAccess("readonly") if mibBuilder.loadTexts: wsCompressionEffectiveBandwidth.setStatus('current') wsSendCompressionRatio = MibScalar((1, 3, 6, 1, 4, 1, 3845, 30, 4, 1, 1, 1, 15), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: wsSendCompressionRatio.setStatus('current') wsReceiveCompressionRatio = MibScalar((1, 3, 6, 1, 4, 1, 3845, 30, 4, 1, 1, 1, 16), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: wsReceiveCompressionRatio.setStatus('current') wsCompressionStatsCollectionTime = MibScalar((1, 3, 6, 1, 4, 1, 3845, 30, 4, 1, 1, 1, 17), TimeTicks()).setMaxAccess("readonly") if mibBuilder.loadTexts: wsCompressionStatsCollectionTime.setStatus('current') wsAcceleratedConnections = MibScalar((1, 3, 6, 1, 4, 1, 3845, 30, 4, 1, 1, 1, 18), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: wsAcceleratedConnections.setStatus('current') wsNonAcceleratedConnections = MibScalar((1, 3, 6, 1, 4, 1, 3845, 30, 4, 1, 1, 1, 19), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: wsNonAcceleratedConnections.setStatus('current') wsHaState = MibScalar((1, 3, 6, 1, 4, 1, 3845, 30, 4, 1, 1, 1, 20), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3, 4, 5))).clone(namedValues=NamedValues(("standalone", 0), ("primary", 1), ("secondary", 2), ("restarting", 3), ("starting", 4), ("invalid", 5)))).setMaxAccess("readonly") if mibBuilder.loadTexts: wsHaState.setStatus('current') wsHaVmIp = MibScalar((1, 3, 6, 1, 4, 1, 3845, 30, 4, 1, 1, 1, 21), IpAddress()).setMaxAccess("readonly") if mibBuilder.loadTexts: wsHaVmIp.setStatus('current') wsHaSecondaryIp = MibScalar((1, 3, 6, 1, 4, 1, 3845, 30, 4, 1, 1, 1, 22), IpAddress()).setMaxAccess("readonly") if mibBuilder.loadTexts: wsHaSecondaryIp.setStatus('current') wsPrimaryIp = MibScalar((1, 3, 6, 1, 4, 1, 3845, 30, 4, 1, 1, 1, 23), IpAddress()).setMaxAccess("readonly") if mibBuilder.loadTexts: wsPrimaryIp.setStatus('current') wsCpuUsage = MibScalar((1, 3, 6, 1, 4, 1, 3845, 30, 4, 1, 1, 1, 24), Integer32()).setUnits('%').setMaxAccess("readonly") if mibBuilder.loadTexts: wsCpuUsage.setStatus('current') wsConnectedPlugIns = MibScalar((1, 3, 6, 1, 4, 1, 3845, 30, 4, 1, 1, 1, 25), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: wsConnectedPlugIns.setStatus('current') wsMaxPlugIns = MibScalar((1, 3, 6, 1, 4, 1, 3845, 30, 4, 1, 1, 1, 26), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: wsMaxPlugIns.setStatus('current') wsQosStatsCollectionTime = MibScalar((1, 3, 6, 1, 4, 1, 3845, 30, 4, 1, 1, 1, 27), TimeTicks()).setMaxAccess("readonly") if mibBuilder.loadTexts: wsQosStatsCollectionTime.setStatus('current') wsUpTime = MibScalar((1, 3, 6, 1, 4, 1, 3845, 30, 4, 1, 1, 1, 28), TimeTicks()).setMaxAccess("readonly") if mibBuilder.loadTexts: wsUpTime.setStatus('current') wsSerialNumber = MibScalar((1, 3, 6, 1, 4, 1, 3845, 30, 4, 1, 1, 1, 29), DisplayString()).setMaxAccess("readonly") if mibBuilder.loadTexts: wsSerialNumber.setStatus('current') wsNonAcceleratedVolume = MibScalar((1, 3, 6, 1, 4, 1, 3845, 30, 4, 1, 1, 1, 30), Counter64()).setUnits('1000-Octets').setMaxAccess("readonly") if mibBuilder.loadTexts: wsNonAcceleratedVolume.setStatus('current') wsActiveConnections = MibScalar((1, 3, 6, 1, 4, 1, 3845, 30, 4, 1, 1, 1, 31), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: wsActiveConnections.setStatus('current') wsAccelerationStatus = MibScalar((1, 3, 6, 1, 4, 1, 3845, 30, 4, 1, 1, 1, 32), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2)))).setMaxAccess("readonly") if mibBuilder.loadTexts: wsAccelerationStatus.setStatus('current') wsTrafficShapingStatus = MibScalar((1, 3, 6, 1, 4, 1, 3845, 30, 4, 1, 1, 1, 33), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2)))).setMaxAccess("readonly") if mibBuilder.loadTexts: wsTrafficShapingStatus.setStatus('current') wsSystemLoad = MibScalar((1, 3, 6, 1, 4, 1, 3845, 30, 4, 1, 1, 1, 34), Integer32()).setUnits('%').setMaxAccess("readonly") if mibBuilder.loadTexts: wsSystemLoad.setStatus('current') wsWanSendRate = MibScalar((1, 3, 6, 1, 4, 1, 3845, 30, 4, 1, 1, 1, 35), Integer32()).setUnits('bps').setMaxAccess("readonly") if mibBuilder.loadTexts: wsWanSendRate.setStatus('current') wsWanReceiveRate = MibScalar((1, 3, 6, 1, 4, 1, 3845, 30, 4, 1, 1, 1, 36), Integer32()).setUnits('bps').setMaxAccess("readonly") if mibBuilder.loadTexts: wsWanReceiveRate.setStatus('current') wsLanSendRate = MibScalar((1, 3, 6, 1, 4, 1, 3845, 30, 4, 1, 1, 1, 37), Integer32()).setUnits('bps').setMaxAccess("readonly") if mibBuilder.loadTexts: wsLanSendRate.setStatus('current') wsLanReceiveRate = MibScalar((1, 3, 6, 1, 4, 1, 3845, 30, 4, 1, 1, 1, 38), Integer32()).setUnits('bps').setMaxAccess("readonly") if mibBuilder.loadTexts: wsLanReceiveRate.setStatus('current') wsNonAcceleratedRate = MibScalar((1, 3, 6, 1, 4, 1, 3845, 30, 4, 1, 1, 1, 39), Integer32()).setUnits('bps').setMaxAccess("readonly") if mibBuilder.loadTexts: wsNonAcceleratedRate.setStatus('current') wsModelNumber = MibScalar((1, 3, 6, 1, 4, 1, 3845, 30, 4, 1, 1, 1, 40), DisplayString()).setMaxAccess("readonly") if mibBuilder.loadTexts: wsModelNumber.setStatus('current') wsWccpStatus = MibScalar((1, 3, 6, 1, 4, 1, 3845, 30, 4, 1, 1, 1, 41), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2)))).setMaxAccess("readonly") if mibBuilder.loadTexts: wsWccpStatus.setStatus('current') wsStatusMIBTables = MibIdentifier((1, 3, 6, 1, 4, 1, 3845, 30, 4, 1, 1, 2)) wsActiveAlarmTable = MibTable((1, 3, 6, 1, 4, 1, 3845, 30, 4, 1, 1, 2, 1), ) if mibBuilder.loadTexts: wsActiveAlarmTable.setStatus('current') activeAlarmEntry = MibTableRow((1, 3, 6, 1, 4, 1, 3845, 30, 4, 1, 1, 2, 1, 1), ).setIndexNames((0, "APPACCELERATION-STATUS-MIB", "wsActiveAlarmIndex")) if mibBuilder.loadTexts: activeAlarmEntry.setStatus('current') wsActiveAlarmIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 3845, 30, 4, 1, 1, 2, 1, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 65535))).setMaxAccess("readonly") if mibBuilder.loadTexts: wsActiveAlarmIndex.setStatus('current') wsActiveAlarmSeqNum = MibTableColumn((1, 3, 6, 1, 4, 1, 3845, 30, 4, 1, 1, 2, 1, 1, 2), AppAccelerationSeqNum()).setMaxAccess("readonly") if mibBuilder.loadTexts: wsActiveAlarmSeqNum.setStatus('current') wsActiveAlarmID = MibTableColumn((1, 3, 6, 1, 4, 1, 3845, 30, 4, 1, 1, 2, 1, 1, 3), ObjectIdentifier()).setMaxAccess("readonly") if mibBuilder.loadTexts: wsActiveAlarmID.setStatus('current') wsActiveAlarmSeverity = MibTableColumn((1, 3, 6, 1, 4, 1, 3845, 30, 4, 1, 1, 2, 1, 1, 4), AppAccelerationAlarmSeverity()).setMaxAccess("readonly") if mibBuilder.loadTexts: wsActiveAlarmSeverity.setStatus('current') wsActiveAlarmLogTime = MibTableColumn((1, 3, 6, 1, 4, 1, 3845, 30, 4, 1, 1, 2, 1, 1, 5), TimeTicks()).setMaxAccess("readonly") if mibBuilder.loadTexts: wsActiveAlarmLogTime.setStatus('current') wsActiveAlarmDesc = MibTableColumn((1, 3, 6, 1, 4, 1, 3845, 30, 4, 1, 1, 2, 1, 1, 6), AppAccelerationDescription()).setMaxAccess("readonly") if mibBuilder.loadTexts: wsActiveAlarmDesc.setStatus('current') wsActiveAlarmAcked = MibTableColumn((1, 3, 6, 1, 4, 1, 3845, 30, 4, 1, 1, 2, 1, 1, 7), AppAccelerationYesNo()).setMaxAccess("readwrite") if mibBuilder.loadTexts: wsActiveAlarmAcked.setStatus('current') wsActiveAlarmServiceAffect = MibTableColumn((1, 3, 6, 1, 4, 1, 3845, 30, 4, 1, 1, 2, 1, 1, 8), AppAccelerationYesNo()).setMaxAccess("readonly") if mibBuilder.loadTexts: wsActiveAlarmServiceAffect.setStatus('current') wsServiceClassStatsTable = MibTable((1, 3, 6, 1, 4, 1, 3845, 30, 4, 1, 1, 2, 2), ) if mibBuilder.loadTexts: wsServiceClassStatsTable.setStatus('current') wsServiceClassStatsEntry = MibTableRow((1, 3, 6, 1, 4, 1, 3845, 30, 4, 1, 1, 2, 2, 1), ).setIndexNames((0, "APPACCELERATION-STATUS-MIB", "wsServiceClassIndex")) if mibBuilder.loadTexts: wsServiceClassStatsEntry.setStatus('current') wsServiceClassIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 3845, 30, 4, 1, 1, 2, 2, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 2147483647))).setMaxAccess("readonly") if mibBuilder.loadTexts: wsServiceClassIndex.setStatus('current') wsServiceClassName = MibTableColumn((1, 3, 6, 1, 4, 1, 3845, 30, 4, 1, 1, 2, 2, 1, 2), DisplayString()).setMaxAccess("readonly") if mibBuilder.loadTexts: wsServiceClassName.setStatus('current') wsScsCurrentAcceleratedConnections = MibTableColumn((1, 3, 6, 1, 4, 1, 3845, 30, 4, 1, 1, 2, 2, 1, 3), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: wsScsCurrentAcceleratedConnections.setStatus('current') wsScsTotalAcceleratedConnections = MibTableColumn((1, 3, 6, 1, 4, 1, 3845, 30, 4, 1, 1, 2, 2, 1, 4), Counter64()).setMaxAccess("readonly") if mibBuilder.loadTexts: wsScsTotalAcceleratedConnections.setStatus('current') wsScsTotalAcceleratedOctets = MibTableColumn((1, 3, 6, 1, 4, 1, 3845, 30, 4, 1, 1, 2, 2, 1, 5), Counter64()).setUnits('Octets').setMaxAccess("readonly") if mibBuilder.loadTexts: wsScsTotalAcceleratedOctets.setStatus('current') wsScsTotalNonAcceleratedConnections = MibTableColumn((1, 3, 6, 1, 4, 1, 3845, 30, 4, 1, 1, 2, 2, 1, 6), Counter64()).setMaxAccess("readonly") if mibBuilder.loadTexts: wsScsTotalNonAcceleratedConnections.setStatus('current') wsScsTotalNonAcceleratedOctets = MibTableColumn((1, 3, 6, 1, 4, 1, 3845, 30, 4, 1, 1, 2, 2, 1, 7), Counter64()).setUnits('Octets').setMaxAccess("readonly") if mibBuilder.loadTexts: wsScsTotalNonAcceleratedOctets.setStatus('current') wsScsTotalPreCompressionOctets = MibTableColumn((1, 3, 6, 1, 4, 1, 3845, 30, 4, 1, 1, 2, 2, 1, 8), Counter64()).setUnits('Octets').setMaxAccess("readonly") if mibBuilder.loadTexts: wsScsTotalPreCompressionOctets.setStatus('current') wsScsCompressSentOctets = MibTableColumn((1, 3, 6, 1, 4, 1, 3845, 30, 4, 1, 1, 2, 2, 1, 9), Counter64()).setUnits('Octets').setMaxAccess("readonly") if mibBuilder.loadTexts: wsScsCompressSentOctets.setStatus('current') wsScsCompressReceivedOctets = MibTableColumn((1, 3, 6, 1, 4, 1, 3845, 30, 4, 1, 1, 2, 2, 1, 10), Counter64()).setUnits('Octets').setMaxAccess("readonly") if mibBuilder.loadTexts: wsScsCompressReceivedOctets.setStatus('current') wsScsPreCompressSentOctets = MibTableColumn((1, 3, 6, 1, 4, 1, 3845, 30, 4, 1, 1, 2, 2, 1, 11), Counter64()).setUnits('Octets').setMaxAccess("readonly") if mibBuilder.loadTexts: wsScsPreCompressSentOctets.setStatus('current') wsScsPreCompressReceivedOctets = MibTableColumn((1, 3, 6, 1, 4, 1, 3845, 30, 4, 1, 1, 2, 2, 1, 12), Counter64()).setUnits('Octets').setMaxAccess("readonly") if mibBuilder.loadTexts: wsScsPreCompressReceivedOctets.setStatus('current') wsScsSendBWSavings = MibTableColumn((1, 3, 6, 1, 4, 1, 3845, 30, 4, 1, 1, 2, 2, 1, 13), Integer32()).setUnits('%').setMaxAccess("readonly") if mibBuilder.loadTexts: wsScsSendBWSavings.setStatus('current') wsScsRecvBWSavings = MibTableColumn((1, 3, 6, 1, 4, 1, 3845, 30, 4, 1, 1, 2, 2, 1, 14), Integer32()).setUnits('%').setMaxAccess("readonly") if mibBuilder.loadTexts: wsScsRecvBWSavings.setStatus('current') wsScsSendRecvBWSavings = MibTableColumn((1, 3, 6, 1, 4, 1, 3845, 30, 4, 1, 1, 2, 2, 1, 15), Integer32()).setUnits('%').setMaxAccess("readonly") if mibBuilder.loadTexts: wsScsSendRecvBWSavings.setStatus('current') wsScsSendCompressionRatio = MibTableColumn((1, 3, 6, 1, 4, 1, 3845, 30, 4, 1, 1, 2, 2, 1, 16), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: wsScsSendCompressionRatio.setStatus('current') wsScsRecvCompressionRatio = MibTableColumn((1, 3, 6, 1, 4, 1, 3845, 30, 4, 1, 1, 2, 2, 1, 17), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: wsScsRecvCompressionRatio.setStatus('current') wsScsSendRecvCompressionRatio = MibTableColumn((1, 3, 6, 1, 4, 1, 3845, 30, 4, 1, 1, 2, 2, 1, 18), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: wsScsSendRecvCompressionRatio.setStatus('current') wsQosTrafficClassStatsTable = MibTable((1, 3, 6, 1, 4, 1, 3845, 30, 4, 1, 1, 2, 3), ) if mibBuilder.loadTexts: wsQosTrafficClassStatsTable.setStatus('deprecated') wsQosTcStatsEntry = MibTableRow((1, 3, 6, 1, 4, 1, 3845, 30, 4, 1, 1, 2, 3, 1), ).setIndexNames((0, "APPACCELERATION-STATUS-MIB", "wsQosIndex")) if mibBuilder.loadTexts: wsQosTcStatsEntry.setStatus('deprecated') wsQosIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 3845, 30, 4, 1, 1, 2, 3, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 2147483647))).setMaxAccess("readonly") if mibBuilder.loadTexts: wsQosIndex.setStatus('deprecated') wsQosName = MibTableColumn((1, 3, 6, 1, 4, 1, 3845, 30, 4, 1, 1, 2, 3, 1, 2), DisplayString()).setMaxAccess("readonly") if mibBuilder.loadTexts: wsQosName.setStatus('deprecated') wsQosConfiguredSendRatio = MibTableColumn((1, 3, 6, 1, 4, 1, 3845, 30, 4, 1, 1, 2, 3, 1, 3), Integer32()).setUnits('%').setMaxAccess("readonly") if mibBuilder.loadTexts: wsQosConfiguredSendRatio.setStatus('deprecated') wsQosSentVolume = MibTableColumn((1, 3, 6, 1, 4, 1, 3845, 30, 4, 1, 1, 2, 3, 1, 4), Counter64()).setUnits('K-octets').setMaxAccess("readonly") if mibBuilder.loadTexts: wsQosSentVolume.setStatus('deprecated') wsQosActualSendRatio = MibTableColumn((1, 3, 6, 1, 4, 1, 3845, 30, 4, 1, 1, 2, 3, 1, 5), Integer32()).setUnits('%').setMaxAccess("readonly") if mibBuilder.loadTexts: wsQosActualSendRatio.setStatus('deprecated') wsIcaStatsTable = MibTable((1, 3, 6, 1, 4, 1, 3845, 30, 4, 1, 1, 2, 4), ) if mibBuilder.loadTexts: wsIcaStatsTable.setStatus('current') wsIcaStatsEntry = MibTableRow((1, 3, 6, 1, 4, 1, 3845, 30, 4, 1, 1, 2, 4, 1), ).setIndexNames((0, "APPACCELERATION-STATUS-MIB", "wsIcaIndex")) if mibBuilder.loadTexts: wsIcaStatsEntry.setStatus('current') wsIcaIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 3845, 30, 4, 1, 1, 2, 4, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 2147483647))).setMaxAccess("readonly") if mibBuilder.loadTexts: wsIcaIndex.setStatus('current') wsIcaServiceName = MibTableColumn((1, 3, 6, 1, 4, 1, 3845, 30, 4, 1, 1, 2, 4, 1, 2), DisplayString()).setMaxAccess("readonly") if mibBuilder.loadTexts: wsIcaServiceName.setStatus('current') wsIcaPriority = MibTableColumn((1, 3, 6, 1, 4, 1, 3845, 30, 4, 1, 1, 2, 4, 1, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3, 9999))).clone(namedValues=NamedValues(("high", 0), ("medium", 1), ("low", 2), ("background", 3), ("notApplicable", 9999)))).setMaxAccess("readonly") if mibBuilder.loadTexts: wsIcaPriority.setStatus('deprecated') wsIcaSentVolume = MibTableColumn((1, 3, 6, 1, 4, 1, 3845, 30, 4, 1, 1, 2, 4, 1, 4), Counter64()).setUnits('K-octets').setMaxAccess("readonly") if mibBuilder.loadTexts: wsIcaSentVolume.setStatus('current') wsIcaSentRatio = MibTableColumn((1, 3, 6, 1, 4, 1, 3845, 30, 4, 1, 1, 2, 4, 1, 5), Integer32()).setUnits('%').setMaxAccess("readonly") if mibBuilder.loadTexts: wsIcaSentRatio.setStatus('current') wsIcaReceivedVolume = MibTableColumn((1, 3, 6, 1, 4, 1, 3845, 30, 4, 1, 1, 2, 4, 1, 6), Counter64()).setUnits('K-octets').setMaxAccess("readonly") if mibBuilder.loadTexts: wsIcaReceivedVolume.setStatus('current') wsIcaReceivedRatio = MibTableColumn((1, 3, 6, 1, 4, 1, 3845, 30, 4, 1, 1, 2, 4, 1, 7), Integer32()).setUnits('%').setMaxAccess("readonly") if mibBuilder.loadTexts: wsIcaReceivedRatio.setStatus('current') wsIcaSendRate = MibTableColumn((1, 3, 6, 1, 4, 1, 3845, 30, 4, 1, 1, 2, 4, 1, 8), Integer32()).setUnits('bps').setMaxAccess("readonly") if mibBuilder.loadTexts: wsIcaSendRate.setStatus('current') wsIcaReceiveRate = MibTableColumn((1, 3, 6, 1, 4, 1, 3845, 30, 4, 1, 1, 2, 4, 1, 9), Integer32()).setUnits('bps').setMaxAccess("readonly") if mibBuilder.loadTexts: wsIcaReceiveRate.setStatus('current') wsAdapterTable = MibTable((1, 3, 6, 1, 4, 1, 3845, 30, 4, 1, 1, 2, 5), ) if mibBuilder.loadTexts: wsAdapterTable.setStatus('current') wsAdapterEntry = MibTableRow((1, 3, 6, 1, 4, 1, 3845, 30, 4, 1, 1, 2, 5, 1), ).setIndexNames((0, "APPACCELERATION-STATUS-MIB", "wsAdapterIndex")) if mibBuilder.loadTexts: wsAdapterEntry.setStatus('current') wsAdapterIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 3845, 30, 4, 1, 1, 2, 5, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 2147483647))).setMaxAccess("readonly") if mibBuilder.loadTexts: wsAdapterIndex.setStatus('current') wsAdapterName = MibTableColumn((1, 3, 6, 1, 4, 1, 3845, 30, 4, 1, 1, 2, 5, 1, 2), DisplayString()).setMaxAccess("readonly") if mibBuilder.loadTexts: wsAdapterName.setStatus('current') wsAdapterEnabled = MibTableColumn((1, 3, 6, 1, 4, 1, 3845, 30, 4, 1, 1, 2, 5, 1, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2)))).setMaxAccess("readonly") if mibBuilder.loadTexts: wsAdapterEnabled.setStatus('current') wsAdapterIp = MibTableColumn((1, 3, 6, 1, 4, 1, 3845, 30, 4, 1, 1, 2, 5, 1, 4), IpAddress()).setMaxAccess("readonly") if mibBuilder.loadTexts: wsAdapterIp.setStatus('current') wsAdapterNetmask = MibTableColumn((1, 3, 6, 1, 4, 1, 3845, 30, 4, 1, 1, 2, 5, 1, 5), IpAddress()).setMaxAccess("readonly") if mibBuilder.loadTexts: wsAdapterNetmask.setStatus('current') wsAdapterGateway = MibTableColumn((1, 3, 6, 1, 4, 1, 3845, 30, 4, 1, 1, 2, 5, 1, 6), IpAddress()).setMaxAccess("readonly") if mibBuilder.loadTexts: wsAdapterGateway.setStatus('current') wsAdapterVirtualIp = MibTableColumn((1, 3, 6, 1, 4, 1, 3845, 30, 4, 1, 1, 2, 5, 1, 7), IpAddress()).setMaxAccess("readonly") if mibBuilder.loadTexts: wsAdapterVirtualIp.setStatus('current') wsAdapterVLanEnabled = MibTableColumn((1, 3, 6, 1, 4, 1, 3845, 30, 4, 1, 1, 2, 5, 1, 8), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2)))).setMaxAccess("readonly") if mibBuilder.loadTexts: wsAdapterVLanEnabled.setStatus('current') wsAdapterVLanGroup = MibTableColumn((1, 3, 6, 1, 4, 1, 3845, 30, 4, 1, 1, 2, 5, 1, 9), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: wsAdapterVLanGroup.setStatus('current') wsLinkStatsTable = MibTable((1, 3, 6, 1, 4, 1, 3845, 30, 4, 1, 1, 2, 6), ) if mibBuilder.loadTexts: wsLinkStatsTable.setStatus('current') linkStatsEntry = MibTableRow((1, 3, 6, 1, 4, 1, 3845, 30, 4, 1, 1, 2, 6, 1), ).setIndexNames((0, "APPACCELERATION-STATUS-MIB", "linkIndex")) if mibBuilder.loadTexts: linkStatsEntry.setStatus('current') linkIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 3845, 30, 4, 1, 1, 2, 6, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 2147483647))).setMaxAccess("readonly") if mibBuilder.loadTexts: linkIndex.setStatus('current') linkName = MibTableColumn((1, 3, 6, 1, 4, 1, 3845, 30, 4, 1, 1, 2, 6, 1, 2), DisplayString()).setMaxAccess("readonly") if mibBuilder.loadTexts: linkName.setStatus('current') linkSentVolume = MibTableColumn((1, 3, 6, 1, 4, 1, 3845, 30, 4, 1, 1, 2, 6, 1, 3), Counter64()).setUnits('K-octets').setMaxAccess("readonly") if mibBuilder.loadTexts: linkSentVolume.setStatus('current') linkReceivedVolume = MibTableColumn((1, 3, 6, 1, 4, 1, 3845, 30, 4, 1, 1, 2, 6, 1, 4), Counter64()).setUnits('K-octets').setMaxAccess("readonly") if mibBuilder.loadTexts: linkReceivedVolume.setStatus('current') linkSentPackets = MibTableColumn((1, 3, 6, 1, 4, 1, 3845, 30, 4, 1, 1, 2, 6, 1, 5), Counter64()).setUnits('Packets').setMaxAccess("readonly") if mibBuilder.loadTexts: linkSentPackets.setStatus('current') linkReceivedPackets = MibTableColumn((1, 3, 6, 1, 4, 1, 3845, 30, 4, 1, 1, 2, 6, 1, 6), Counter64()).setUnits('Packets').setMaxAccess("readonly") if mibBuilder.loadTexts: linkReceivedPackets.setStatus('current') linkDroppedSentVolume = MibTableColumn((1, 3, 6, 1, 4, 1, 3845, 30, 4, 1, 1, 2, 6, 1, 7), Counter64()).setUnits('K-octets').setMaxAccess("readonly") if mibBuilder.loadTexts: linkDroppedSentVolume.setStatus('current') linkDroppedReceivedVolume = MibTableColumn((1, 3, 6, 1, 4, 1, 3845, 30, 4, 1, 1, 2, 6, 1, 8), Counter64()).setUnits('K-octets').setMaxAccess("readonly") if mibBuilder.loadTexts: linkDroppedReceivedVolume.setStatus('current') linkDroppedSentPackets = MibTableColumn((1, 3, 6, 1, 4, 1, 3845, 30, 4, 1, 1, 2, 6, 1, 9), Counter64()).setUnits('Packets').setMaxAccess("readonly") if mibBuilder.loadTexts: linkDroppedSentPackets.setStatus('current') linkDroppedReceivedPackets = MibTableColumn((1, 3, 6, 1, 4, 1, 3845, 30, 4, 1, 1, 2, 6, 1, 10), Counter64()).setUnits('Packets').setMaxAccess("readonly") if mibBuilder.loadTexts: linkDroppedReceivedPackets.setStatus('current') wsAppStatsTable = MibTable((1, 3, 6, 1, 4, 1, 3845, 30, 4, 1, 1, 2, 7), ) if mibBuilder.loadTexts: wsAppStatsTable.setStatus('current') appStatsEntry = MibTableRow((1, 3, 6, 1, 4, 1, 3845, 30, 4, 1, 1, 2, 7, 1), ).setIndexNames((0, "APPACCELERATION-STATUS-MIB", "appIndex")) if mibBuilder.loadTexts: appStatsEntry.setStatus('current') appIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 3845, 30, 4, 1, 1, 2, 7, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 2147483647))).setMaxAccess("readonly") if mibBuilder.loadTexts: appIndex.setStatus('current') appName = MibTableColumn((1, 3, 6, 1, 4, 1, 3845, 30, 4, 1, 1, 2, 7, 1, 2), DisplayString()).setMaxAccess("readonly") if mibBuilder.loadTexts: appName.setStatus('current') appId = MibTableColumn((1, 3, 6, 1, 4, 1, 3845, 30, 4, 1, 1, 2, 7, 1, 3), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: appId.setStatus('current') appParentId = MibTableColumn((1, 3, 6, 1, 4, 1, 3845, 30, 4, 1, 1, 2, 7, 1, 4), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: appParentId.setStatus('current') appGroupId = MibTableColumn((1, 3, 6, 1, 4, 1, 3845, 30, 4, 1, 1, 2, 7, 1, 5), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: appGroupId.setStatus('current') appSentVolume = MibTableColumn((1, 3, 6, 1, 4, 1, 3845, 30, 4, 1, 1, 2, 7, 1, 6), Counter64()).setUnits('K-octets').setMaxAccess("readonly") if mibBuilder.loadTexts: appSentVolume.setStatus('current') appReceivedVolume = MibTableColumn((1, 3, 6, 1, 4, 1, 3845, 30, 4, 1, 1, 2, 7, 1, 7), Counter64()).setUnits('K-octets').setMaxAccess("readonly") if mibBuilder.loadTexts: appReceivedVolume.setStatus('current') appSentPackets = MibTableColumn((1, 3, 6, 1, 4, 1, 3845, 30, 4, 1, 1, 2, 7, 1, 8), Counter64()).setUnits('Packets').setMaxAccess("readonly") if mibBuilder.loadTexts: appSentPackets.setStatus('current') appReceivedPackets = MibTableColumn((1, 3, 6, 1, 4, 1, 3845, 30, 4, 1, 1, 2, 7, 1, 9), Counter64()).setUnits('Packets').setMaxAccess("readonly") if mibBuilder.loadTexts: appReceivedPackets.setStatus('current') appDroppedSentVolume = MibTableColumn((1, 3, 6, 1, 4, 1, 3845, 30, 4, 1, 1, 2, 7, 1, 10), Counter64()).setUnits('K-octets').setMaxAccess("readonly") if mibBuilder.loadTexts: appDroppedSentVolume.setStatus('current') appDroppedReceiveVolume = MibTableColumn((1, 3, 6, 1, 4, 1, 3845, 30, 4, 1, 1, 2, 7, 1, 11), Counter64()).setUnits('K-octets').setMaxAccess("readonly") if mibBuilder.loadTexts: appDroppedReceiveVolume.setStatus('current') appDroppedSentPackets = MibTableColumn((1, 3, 6, 1, 4, 1, 3845, 30, 4, 1, 1, 2, 7, 1, 12), Counter64()).setUnits('Packets').setMaxAccess("readonly") if mibBuilder.loadTexts: appDroppedSentPackets.setStatus('current') appDroppedReceivedPackets = MibTableColumn((1, 3, 6, 1, 4, 1, 3845, 30, 4, 1, 1, 2, 7, 1, 13), Counter64()).setUnits('Packets').setMaxAccess("readonly") if mibBuilder.loadTexts: appDroppedReceivedPackets.setStatus('current') appSendRate = MibTableColumn((1, 3, 6, 1, 4, 1, 3845, 30, 4, 1, 1, 2, 7, 1, 14), Integer32()).setUnits('bps').setMaxAccess("readonly") if mibBuilder.loadTexts: appSendRate.setStatus('current') appReceiveRate = MibTableColumn((1, 3, 6, 1, 4, 1, 3845, 30, 4, 1, 1, 2, 7, 1, 15), Integer32()).setUnits('bps').setMaxAccess("readonly") if mibBuilder.loadTexts: appReceiveRate.setStatus('current') wsQosStatsTable = MibTable((1, 3, 6, 1, 4, 1, 3845, 30, 4, 1, 1, 2, 8), ) if mibBuilder.loadTexts: wsQosStatsTable.setStatus('current') qosStatsEntry = MibTableRow((1, 3, 6, 1, 4, 1, 3845, 30, 4, 1, 1, 2, 8, 1), ).setIndexNames((0, "APPACCELERATION-STATUS-MIB", "qosIndex")) if mibBuilder.loadTexts: qosStatsEntry.setStatus('current') qosIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 3845, 30, 4, 1, 1, 2, 8, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 2147483647))).setMaxAccess("readonly") if mibBuilder.loadTexts: qosIndex.setStatus('current') qosPolicyName = MibTableColumn((1, 3, 6, 1, 4, 1, 3845, 30, 4, 1, 1, 2, 8, 1, 2), DisplayString()).setMaxAccess("readonly") if mibBuilder.loadTexts: qosPolicyName.setStatus('current') qosLink = MibTableColumn((1, 3, 6, 1, 4, 1, 3845, 30, 4, 1, 1, 2, 8, 1, 3), DisplayString()).setMaxAccess("readonly") if mibBuilder.loadTexts: qosLink.setStatus('current') qosSentVolume = MibTableColumn((1, 3, 6, 1, 4, 1, 3845, 30, 4, 1, 1, 2, 8, 1, 4), Counter64()).setUnits('K-octets').setMaxAccess("readonly") if mibBuilder.loadTexts: qosSentVolume.setStatus('current') qosReceiveVolume = MibTableColumn((1, 3, 6, 1, 4, 1, 3845, 30, 4, 1, 1, 2, 8, 1, 5), Counter64()).setUnits('K-octets').setMaxAccess("readonly") if mibBuilder.loadTexts: qosReceiveVolume.setStatus('current') qosSentPackets = MibTableColumn((1, 3, 6, 1, 4, 1, 3845, 30, 4, 1, 1, 2, 8, 1, 6), Counter64()).setUnits('Packets').setMaxAccess("readonly") if mibBuilder.loadTexts: qosSentPackets.setStatus('current') qosReceivedPackets = MibTableColumn((1, 3, 6, 1, 4, 1, 3845, 30, 4, 1, 1, 2, 8, 1, 7), Counter64()).setUnits('Packets').setMaxAccess("readonly") if mibBuilder.loadTexts: qosReceivedPackets.setStatus('current') qosDroppedSentVolume = MibTableColumn((1, 3, 6, 1, 4, 1, 3845, 30, 4, 1, 1, 2, 8, 1, 8), Counter64()).setUnits('K-octets').setMaxAccess("readonly") if mibBuilder.loadTexts: qosDroppedSentVolume.setStatus('current') qosDroppedReceiveVolume = MibTableColumn((1, 3, 6, 1, 4, 1, 3845, 30, 4, 1, 1, 2, 8, 1, 9), Counter64()).setUnits('K-octets').setMaxAccess("readonly") if mibBuilder.loadTexts: qosDroppedReceiveVolume.setStatus('current') qosDroppedSentPackets = MibTableColumn((1, 3, 6, 1, 4, 1, 3845, 30, 4, 1, 1, 2, 8, 1, 10), Counter64()).setUnits('Packets').setMaxAccess("readonly") if mibBuilder.loadTexts: qosDroppedSentPackets.setStatus('current') qosDroppedReceivedPackets = MibTableColumn((1, 3, 6, 1, 4, 1, 3845, 30, 4, 1, 1, 2, 8, 1, 11), Counter64()).setUnits('Packets').setMaxAccess("readonly") if mibBuilder.loadTexts: qosDroppedReceivedPackets.setStatus('current') wsLscStatsTable = MibTable((1, 3, 6, 1, 4, 1, 3845, 30, 4, 1, 1, 2, 9), ) if mibBuilder.loadTexts: wsLscStatsTable.setStatus('current') lscStatsEntry = MibTableRow((1, 3, 6, 1, 4, 1, 3845, 30, 4, 1, 1, 2, 9, 1), ).setIndexNames((0, "APPACCELERATION-STATUS-MIB", "lscIndex")) if mibBuilder.loadTexts: lscStatsEntry.setStatus('current') lscIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 3845, 30, 4, 1, 1, 2, 9, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 2147483647))).setMaxAccess("readonly") if mibBuilder.loadTexts: lscIndex.setStatus('current') lscServiceClassName = MibTableColumn((1, 3, 6, 1, 4, 1, 3845, 30, 4, 1, 1, 2, 9, 1, 2), DisplayString()).setMaxAccess("readonly") if mibBuilder.loadTexts: lscServiceClassName.setStatus('current') lscLink = MibTableColumn((1, 3, 6, 1, 4, 1, 3845, 30, 4, 1, 1, 2, 9, 1, 3), DisplayString()).setMaxAccess("readonly") if mibBuilder.loadTexts: lscLink.setStatus('current') lscSentVolume = MibTableColumn((1, 3, 6, 1, 4, 1, 3845, 30, 4, 1, 1, 2, 9, 1, 4), Counter64()).setUnits('K-octets').setMaxAccess("readonly") if mibBuilder.loadTexts: lscSentVolume.setStatus('current') lscReceivedVolume = MibTableColumn((1, 3, 6, 1, 4, 1, 3845, 30, 4, 1, 1, 2, 9, 1, 5), Counter64()).setUnits('K-octets').setMaxAccess("readonly") if mibBuilder.loadTexts: lscReceivedVolume.setStatus('current') lscSentPackets = MibTableColumn((1, 3, 6, 1, 4, 1, 3845, 30, 4, 1, 1, 2, 9, 1, 6), Counter64()).setUnits('Packets').setMaxAccess("readonly") if mibBuilder.loadTexts: lscSentPackets.setStatus('current') lscReceivedPackets = MibTableColumn((1, 3, 6, 1, 4, 1, 3845, 30, 4, 1, 1, 2, 9, 1, 7), Counter64()).setUnits('Packets').setMaxAccess("readonly") if mibBuilder.loadTexts: lscReceivedPackets.setStatus('current') lscDroppedSentVolume = MibTableColumn((1, 3, 6, 1, 4, 1, 3845, 30, 4, 1, 1, 2, 9, 1, 8), Counter64()).setUnits('K-octets').setMaxAccess("readonly") if mibBuilder.loadTexts: lscDroppedSentVolume.setStatus('current') lscDroppedReceiveVolume = MibTableColumn((1, 3, 6, 1, 4, 1, 3845, 30, 4, 1, 1, 2, 9, 1, 9), Counter64()).setUnits('K-octets').setMaxAccess("readonly") if mibBuilder.loadTexts: lscDroppedReceiveVolume.setStatus('current') lscDroppedSentPackets = MibTableColumn((1, 3, 6, 1, 4, 1, 3845, 30, 4, 1, 1, 2, 9, 1, 10), Counter64()).setUnits('Packets').setMaxAccess("readonly") if mibBuilder.loadTexts: lscDroppedSentPackets.setStatus('current') lscDroppedReceivedPackets = MibTableColumn((1, 3, 6, 1, 4, 1, 3845, 30, 4, 1, 1, 2, 9, 1, 11), Counter64()).setUnits('Packets').setMaxAccess("readonly") if mibBuilder.loadTexts: lscDroppedReceivedPackets.setStatus('current') wsPartnerTable = MibTable((1, 3, 6, 1, 4, 1, 3845, 30, 4, 1, 1, 2, 10), ) if mibBuilder.loadTexts: wsPartnerTable.setStatus('current') partnerEntry = MibTableRow((1, 3, 6, 1, 4, 1, 3845, 30, 4, 1, 1, 2, 10, 1), ).setIndexNames((0, "APPACCELERATION-STATUS-MIB", "partnerAddrType"), (0, "APPACCELERATION-STATUS-MIB", "partnerAddr")) if mibBuilder.loadTexts: partnerEntry.setStatus('current') partnerAddrType = MibTableColumn((1, 3, 6, 1, 4, 1, 3845, 30, 4, 1, 1, 2, 10, 1, 1), InetAddressType()).setMaxAccess("readonly") if mibBuilder.loadTexts: partnerAddrType.setStatus('current') partnerAddr = MibTableColumn((1, 3, 6, 1, 4, 1, 3845, 30, 4, 1, 1, 2, 10, 1, 2), InetAddress()).setMaxAccess("readonly") if mibBuilder.loadTexts: partnerAddr.setStatus('current') partnerConnections = MibTableColumn((1, 3, 6, 1, 4, 1, 3845, 30, 4, 1, 1, 2, 10, 1, 3), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: partnerConnections.setStatus('current') partnerSendRate = MibTableColumn((1, 3, 6, 1, 4, 1, 3845, 30, 4, 1, 1, 2, 10, 1, 4), Integer32()).setUnits('bps').setMaxAccess("readonly") if mibBuilder.loadTexts: partnerSendRate.setStatus('current') partnerReceiveRate = MibTableColumn((1, 3, 6, 1, 4, 1, 3845, 30, 4, 1, 1, 2, 10, 1, 5), Integer32()).setUnits('bps').setMaxAccess("readonly") if mibBuilder.loadTexts: partnerReceiveRate.setStatus('current') partnerIdleTime = MibTableColumn((1, 3, 6, 1, 4, 1, 3845, 30, 4, 1, 1, 2, 10, 1, 6), TimeTicks()).setMaxAccess("readonly") if mibBuilder.loadTexts: partnerIdleTime.setStatus('current') wsHAMasterIpAddr = MibScalar((1, 3, 6, 1, 4, 1, 3845, 30, 4, 1, 1, 3), IpAddress()).setMaxAccess("accessiblefornotify") if mibBuilder.loadTexts: wsHAMasterIpAddr.setStatus('current') wsSourceIpAddr = MibScalar((1, 3, 6, 1, 4, 1, 3845, 30, 4, 1, 1, 5), IpAddress()).setMaxAccess("accessiblefornotify") if mibBuilder.loadTexts: wsSourceIpAddr.setStatus('current') wsStatusMIBAlertTables = MibIdentifier((1, 3, 6, 1, 4, 1, 3845, 30, 4, 1, 1, 4)) wsAlertAction = MibScalar((1, 3, 6, 1, 4, 1, 3845, 30, 4, 1, 1, 4, 1), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3))).clone(namedValues=NamedValues(("oneShot", 0), ("set", 1), ("reset", 2), ("expired", 3)))).setMaxAccess("readonly") if mibBuilder.loadTexts: wsAlertAction.setStatus('current') wsAlertClass = MibScalar((1, 3, 6, 1, 4, 1, 3845, 30, 4, 1, 1, 4, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75))).clone(namedValues=NamedValues(("slowLossRate", 0), ("fastLossRate", 1), ("connectionStalled", 2), ("connectionTimeout", 3), ("connectionInvalid", 4), ("nicHalfDuplex", 5), ("arpTimeout", 6), ("badLicense", 7), ("limitExceeded", 8), ("asymmetric", 9), ("badPackets", 10), ("lowOnCpu", 11), ("lowOnMemory", 12), ("internal", 13), ("restartRequired", 14), ("vridNotSet", 15), ("haConfigurationChanged", 16), ("haNoSecondary", 17), ("haPairCommError", 18), ("haNotCapable", 19), ("haPeerVersion", 20), ("compressionError", 21), ("bwTypeMismatch", 22), ("cpuPegged", 23), ("lowOnVm", 24), ("numSlowRtosExceeded", 25), ("numFastRtosExceeded", 26), ("numBootoutsExceeded", 27), ("numRewindsExceeded", 28), ("diskDriveFailing", 29), ("diskDriveDegraded", 30), ("diskDriveFailed", 31), ("groupModeError", 32), ("nicBypassEvent", 33), ("haMisMatchVmip", 34), ("diskFragmented", 35), ("redirectorModeSyn", 36), ("unreachable", 37), ("dnsLookup", 38), ("redirectorModeFailure", 39), ("applianceInTheMiddle", 40), ("internalCritical", 41), ("internalMajor", 42), ("internalMinor", 43), ("internalWarning", 44), ("wccpMajor", 45), ("wccpMinor", 46), ("wccpWarning", 47), ("driverHung", 48), ("signalingChannelError", 49), ("scpsError", 50), ("plugInNearLimit", 51), ("sslError", 52), ("haDispositionError", 53), ("haVIPNotSet", 54), ("vlanNotSupported", 55), ("tooManyBadTcpChecksum", 56), ("invalidGateway", 57), ("haPeerKeyStoreLocked", 58), ("sslProxyMajor", 59), ("sslProxyMinor", 60), ("sslProxyWarning", 61), ("sslTunnelMajor", 62), ("sslTunnelMinor", 63), ("sslTunnelWarning", 64), ("excessiveIpFragments", 65), ("userAccountLocked", 66), ("smb2AccelerationFailure", 67), ("invalidBridgeConfig", 68), ("invalidHttpCachingConfigFile", 69), ("qosEngineError", 70), ("mapiNtlmError", 71), ("ethernetCrcError", 72), ("qosLinkConfigError", 73), ("maxUnacceleratedConnectionsExceeded", 74), ("badHardware", 75)))).setMaxAccess("readonly") if mibBuilder.loadTexts: wsAlertClass.setStatus('current') wsAlertMsg = MibScalar((1, 3, 6, 1, 4, 1, 3845, 30, 4, 1, 1, 4, 3), AppAccelerationDescription()).setMaxAccess("readonly") if mibBuilder.loadTexts: wsAlertMsg.setStatus('current') wsNotifyStart = NotificationType((1, 3, 6, 1, 4, 1, 3845, 30, 5, 1, 1)).setObjects(("APPACCELERATION-STATUS-MIB", "wsActiveAlarmSeverity"), ("APPACCELERATION-STATUS-MIB", "wsActiveAlarmSeqNum"), ("APPACCELERATION-STATUS-MIB", "wsActiveAlarmDesc"), ("APPACCELERATION-STATUS-MIB", "wsActiveAlarmServiceAffect"), ("APPACCELERATION-STATUS-MIB", "wsPrimaryIp")) if mibBuilder.loadTexts: wsNotifyStart.setStatus('current') wsNotifyShutdown = NotificationType((1, 3, 6, 1, 4, 1, 3845, 30, 5, 1, 2)).setObjects(("APPACCELERATION-STATUS-MIB", "wsActiveAlarmSeverity"), ("APPACCELERATION-STATUS-MIB", "wsActiveAlarmSeqNum"), ("APPACCELERATION-STATUS-MIB", "wsActiveAlarmDesc"), ("APPACCELERATION-STATUS-MIB", "wsActiveAlarmServiceAffect"), ("APPACCELERATION-STATUS-MIB", "wsPrimaryIp")) if mibBuilder.loadTexts: wsNotifyShutdown.setStatus('current') wsNotifyRestart = NotificationType((1, 3, 6, 1, 4, 1, 3845, 30, 5, 1, 3)).setObjects(("APPACCELERATION-STATUS-MIB", "wsActiveAlarmSeverity"), ("APPACCELERATION-STATUS-MIB", "wsActiveAlarmSeqNum"), ("APPACCELERATION-STATUS-MIB", "wsActiveAlarmDesc"), ("APPACCELERATION-STATUS-MIB", "wsActiveAlarmServiceAffect")) if mibBuilder.loadTexts: wsNotifyRestart.setStatus('deprecated') wsHANotifyNewMaster = NotificationType((1, 3, 6, 1, 4, 1, 3845, 30, 5, 1, 4)).setObjects(("APPACCELERATION-STATUS-MIB", "wsActiveAlarmSeverity"), ("APPACCELERATION-STATUS-MIB", "wsActiveAlarmSeqNum"), ("APPACCELERATION-STATUS-MIB", "wsActiveAlarmDesc"), ("APPACCELERATION-STATUS-MIB", "wsActiveAlarmServiceAffect"), ("APPACCELERATION-STATUS-MIB", "wsHAMasterIpAddr"), ("APPACCELERATION-STATUS-MIB", "wsPrimaryIp")) if mibBuilder.loadTexts: wsHANotifyNewMaster.setStatus('current') wsNotifyAvailBWChange = NotificationType((1, 3, 6, 1, 4, 1, 3845, 30, 5, 1, 5)).setObjects(("APPACCELERATION-STATUS-MIB", "wsActiveAlarmSeverity"), ("APPACCELERATION-STATUS-MIB", "wsActiveAlarmSeqNum"), ("APPACCELERATION-STATUS-MIB", "wsActiveAlarmDesc"), ("APPACCELERATION-STATUS-MIB", "wsActiveAlarmServiceAffect")) if mibBuilder.loadTexts: wsNotifyAvailBWChange.setStatus('deprecated') wsNotifyUnexpectedRestart = NotificationType((1, 3, 6, 1, 4, 1, 3845, 30, 5, 1, 6)).setObjects(("APPACCELERATION-STATUS-MIB", "wsActiveAlarmSeverity"), ("APPACCELERATION-STATUS-MIB", "wsActiveAlarmSeqNum"), ("APPACCELERATION-STATUS-MIB", "wsActiveAlarmDesc"), ("APPACCELERATION-STATUS-MIB", "wsActiveAlarmServiceAffect"), ("APPACCELERATION-STATUS-MIB", "wsPrimaryIp")) if mibBuilder.loadTexts: wsNotifyUnexpectedRestart.setStatus('current') wsNotifyPersistentError = NotificationType((1, 3, 6, 1, 4, 1, 3845, 30, 5, 1, 7)).setObjects(("APPACCELERATION-STATUS-MIB", "wsActiveAlarmSeverity"), ("APPACCELERATION-STATUS-MIB", "wsActiveAlarmSeqNum"), ("APPACCELERATION-STATUS-MIB", "wsActiveAlarmDesc"), ("APPACCELERATION-STATUS-MIB", "wsActiveAlarmServiceAffect"), ("APPACCELERATION-STATUS-MIB", "wsPrimaryIp")) if mibBuilder.loadTexts: wsNotifyPersistentError.setStatus('current') wsNotifyAlert = NotificationType((1, 3, 6, 1, 4, 1, 3845, 30, 5, 1, 8)).setObjects(("APPACCELERATION-STATUS-MIB", "wsActiveAlarmSeverity"), ("APPACCELERATION-STATUS-MIB", "wsActiveAlarmSeqNum"), ("APPACCELERATION-STATUS-MIB", "wsActiveAlarmDesc"), ("APPACCELERATION-STATUS-MIB", "wsActiveAlarmServiceAffect"), ("APPACCELERATION-STATUS-MIB", "wsAlertAction"), ("APPACCELERATION-STATUS-MIB", "wsAlertClass"), ("APPACCELERATION-STATUS-MIB", "wsAlertMsg"), ("APPACCELERATION-STATUS-MIB", "wsPrimaryIp")) if mibBuilder.loadTexts: wsNotifyAlert.setStatus('current') wsNotifyConfigurationChanged = NotificationType((1, 3, 6, 1, 4, 1, 3845, 30, 5, 1, 9)).setObjects(("APPACCELERATION-STATUS-MIB", "wsActiveAlarmSeverity"), ("APPACCELERATION-STATUS-MIB", "wsActiveAlarmSeqNum"), ("APPACCELERATION-STATUS-MIB", "wsActiveAlarmDesc"), ("APPACCELERATION-STATUS-MIB", "wsActiveAlarmServiceAffect"), ("APPACCELERATION-STATUS-MIB", "wsPrimaryIp")) if mibBuilder.loadTexts: wsNotifyConfigurationChanged.setStatus('current') wsStatusMIBCompliances = MibIdentifier((1, 3, 6, 1, 4, 1, 3845, 30, 4, 1, 2, 1)) wsStatusMIBGroups = MibIdentifier((1, 3, 6, 1, 4, 1, 3845, 30, 4, 1, 2, 2)) wsStatusCompliance = ModuleCompliance((1, 3, 6, 1, 4, 1, 3845, 30, 4, 1, 2, 1, 1)).setObjects(("APPACCELERATION-STATUS-MIB", "wsStatusGroup"), ("APPACCELERATION-STATUS-MIB", "wsStatusTrapGroup"), ("APPACCELERATION-STATUS-MIB", "wsStatusNotifyGroup")) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): wsStatusCompliance = wsStatusCompliance.setStatus('current') wsStatusGroup = ObjectGroup((1, 3, 6, 1, 4, 1, 3845, 30, 4, 1, 2, 2, 1)).setObjects(("APPACCELERATION-STATUS-MIB", "wsOperStatus"), ("APPACCELERATION-STATUS-MIB", "wsLoad1Min"), ("APPACCELERATION-STATUS-MIB", "wsLoad5Min"), ("APPACCELERATION-STATUS-MIB", "wsLoad15Min"), ("APPACCELERATION-STATUS-MIB", "wsBypass"), ("APPACCELERATION-STATUS-MIB", "wsLastAlarmSeqNum"), ("APPACCELERATION-STATUS-MIB", "wsBoostStatus"), ("APPACCELERATION-STATUS-MIB", "wsBandwidthMode"), ("APPACCELERATION-STATUS-MIB", "wsBandwidthLimit"), ("APPACCELERATION-STATUS-MIB", "wsWanOutOctets"), ("APPACCELERATION-STATUS-MIB", "wsWanInOctets"), ("APPACCELERATION-STATUS-MIB", "wsLanOutOctets"), ("APPACCELERATION-STATUS-MIB", "wsLanInOctets"), ("APPACCELERATION-STATUS-MIB", "wsCompressionEffectiveBandwidth"), ("APPACCELERATION-STATUS-MIB", "wsSendCompressionRatio"), ("APPACCELERATION-STATUS-MIB", "wsReceiveCompressionRatio"), ("APPACCELERATION-STATUS-MIB", "wsCompressionStatsCollectionTime"), ("APPACCELERATION-STATUS-MIB", "wsAcceleratedConnections"), ("APPACCELERATION-STATUS-MIB", "wsNonAcceleratedConnections"), ("APPACCELERATION-STATUS-MIB", "wsHaState"), ("APPACCELERATION-STATUS-MIB", "wsHaVmIp"), ("APPACCELERATION-STATUS-MIB", "wsHaSecondaryIp"), ("APPACCELERATION-STATUS-MIB", "wsPrimaryIp"), ("APPACCELERATION-STATUS-MIB", "wsCpuUsage"), ("APPACCELERATION-STATUS-MIB", "wsConnectedPlugIns"), ("APPACCELERATION-STATUS-MIB", "wsMaxPlugIns"), ("APPACCELERATION-STATUS-MIB", "wsQosStatsCollectionTime"), ("APPACCELERATION-STATUS-MIB", "wsUpTime"), ("APPACCELERATION-STATUS-MIB", "wsSerialNumber"), ("APPACCELERATION-STATUS-MIB", "wsNonAcceleratedVolume"), ("APPACCELERATION-STATUS-MIB", "wsActiveConnections"), ("APPACCELERATION-STATUS-MIB", "wsAccelerationStatus"), ("APPACCELERATION-STATUS-MIB", "wsTrafficShapingStatus"), ("APPACCELERATION-STATUS-MIB", "wsSystemLoad"), ("APPACCELERATION-STATUS-MIB", "wsWanSendRate"), ("APPACCELERATION-STATUS-MIB", "wsWanReceiveRate"), ("APPACCELERATION-STATUS-MIB", "wsLanSendRate"), ("APPACCELERATION-STATUS-MIB", "wsLanReceiveRate"), ("APPACCELERATION-STATUS-MIB", "wsNonAcceleratedRate"), ("APPACCELERATION-STATUS-MIB", "wsModelNumber"), ("APPACCELERATION-STATUS-MIB", "wsWccpStatus"), ("APPACCELERATION-STATUS-MIB", "wsActiveAlarmIndex"), ("APPACCELERATION-STATUS-MIB", "wsActiveAlarmSeqNum"), ("APPACCELERATION-STATUS-MIB", "wsActiveAlarmID"), ("APPACCELERATION-STATUS-MIB", "wsActiveAlarmSeverity"), ("APPACCELERATION-STATUS-MIB", "wsActiveAlarmLogTime"), ("APPACCELERATION-STATUS-MIB", "wsActiveAlarmDesc"), ("APPACCELERATION-STATUS-MIB", "wsActiveAlarmAcked"), ("APPACCELERATION-STATUS-MIB", "wsActiveAlarmServiceAffect"), ("APPACCELERATION-STATUS-MIB", "wsServiceClassIndex"), ("APPACCELERATION-STATUS-MIB", "wsServiceClassName"), ("APPACCELERATION-STATUS-MIB", "wsScsCurrentAcceleratedConnections"), ("APPACCELERATION-STATUS-MIB", "wsScsTotalAcceleratedConnections"), ("APPACCELERATION-STATUS-MIB", "wsScsTotalAcceleratedOctets"), ("APPACCELERATION-STATUS-MIB", "wsScsTotalNonAcceleratedConnections"), ("APPACCELERATION-STATUS-MIB", "wsScsTotalNonAcceleratedOctets"), ("APPACCELERATION-STATUS-MIB", "wsScsTotalPreCompressionOctets"), ("APPACCELERATION-STATUS-MIB", "wsScsCompressSentOctets"), ("APPACCELERATION-STATUS-MIB", "wsScsCompressReceivedOctets"), ("APPACCELERATION-STATUS-MIB", "wsScsPreCompressSentOctets"), ("APPACCELERATION-STATUS-MIB", "wsScsPreCompressReceivedOctets"), ("APPACCELERATION-STATUS-MIB", "wsScsSendBWSavings"), ("APPACCELERATION-STATUS-MIB", "wsScsRecvBWSavings"), ("APPACCELERATION-STATUS-MIB", "wsScsSendRecvBWSavings"), ("APPACCELERATION-STATUS-MIB", "wsScsSendCompressionRatio"), ("APPACCELERATION-STATUS-MIB", "wsScsRecvCompressionRatio"), ("APPACCELERATION-STATUS-MIB", "wsScsSendRecvCompressionRatio"), ("APPACCELERATION-STATUS-MIB", "wsQosIndex"), ("APPACCELERATION-STATUS-MIB", "wsQosName"), ("APPACCELERATION-STATUS-MIB", "wsQosConfiguredSendRatio"), ("APPACCELERATION-STATUS-MIB", "wsQosSentVolume"), ("APPACCELERATION-STATUS-MIB", "wsQosActualSendRatio"), ("APPACCELERATION-STATUS-MIB", "wsIcaIndex"), ("APPACCELERATION-STATUS-MIB", "wsIcaServiceName"), ("APPACCELERATION-STATUS-MIB", "wsIcaPriority"), ("APPACCELERATION-STATUS-MIB", "wsIcaSentVolume"), ("APPACCELERATION-STATUS-MIB", "wsIcaSentRatio"), ("APPACCELERATION-STATUS-MIB", "wsIcaReceivedVolume"), ("APPACCELERATION-STATUS-MIB", "wsIcaReceivedRatio"), ("APPACCELERATION-STATUS-MIB", "wsIcaSendRate"), ("APPACCELERATION-STATUS-MIB", "wsIcaReceiveRate"), ("APPACCELERATION-STATUS-MIB", "wsAdapterIndex"), ("APPACCELERATION-STATUS-MIB", "wsAdapterName"), ("APPACCELERATION-STATUS-MIB", "wsAdapterEnabled"), ("APPACCELERATION-STATUS-MIB", "wsAdapterIp"), ("APPACCELERATION-STATUS-MIB", "wsAdapterNetmask"), ("APPACCELERATION-STATUS-MIB", "wsAdapterGateway"), ("APPACCELERATION-STATUS-MIB", "wsAdapterVirtualIp"), ("APPACCELERATION-STATUS-MIB", "wsAdapterVLanEnabled"), ("APPACCELERATION-STATUS-MIB", "wsAdapterVLanGroup"), ("APPACCELERATION-STATUS-MIB", "linkIndex"), ("APPACCELERATION-STATUS-MIB", "linkName"), ("APPACCELERATION-STATUS-MIB", "linkSentVolume"), ("APPACCELERATION-STATUS-MIB", "linkReceivedVolume"), ("APPACCELERATION-STATUS-MIB", "linkSentPackets"), ("APPACCELERATION-STATUS-MIB", "linkReceivedPackets"), ("APPACCELERATION-STATUS-MIB", "linkDroppedSentVolume"), ("APPACCELERATION-STATUS-MIB", "linkDroppedReceivedVolume"), ("APPACCELERATION-STATUS-MIB", "linkDroppedSentPackets"), ("APPACCELERATION-STATUS-MIB", "linkDroppedReceivedPackets"), ("APPACCELERATION-STATUS-MIB", "appIndex"), ("APPACCELERATION-STATUS-MIB", "appName"), ("APPACCELERATION-STATUS-MIB", "appId"), ("APPACCELERATION-STATUS-MIB", "appParentId"), ("APPACCELERATION-STATUS-MIB", "appGroupId"), ("APPACCELERATION-STATUS-MIB", "appSentVolume"), ("APPACCELERATION-STATUS-MIB", "appReceivedVolume"), ("APPACCELERATION-STATUS-MIB", "appSentPackets"), ("APPACCELERATION-STATUS-MIB", "appReceivedPackets"), ("APPACCELERATION-STATUS-MIB", "appDroppedSentVolume"), ("APPACCELERATION-STATUS-MIB", "appDroppedReceiveVolume"), ("APPACCELERATION-STATUS-MIB", "appDroppedSentPackets"), ("APPACCELERATION-STATUS-MIB", "appDroppedReceivedPackets"), ("APPACCELERATION-STATUS-MIB", "appSendRate"), ("APPACCELERATION-STATUS-MIB", "appReceiveRate"), ("APPACCELERATION-STATUS-MIB", "qosIndex"), ("APPACCELERATION-STATUS-MIB", "qosPolicyName"), ("APPACCELERATION-STATUS-MIB", "qosLink"), ("APPACCELERATION-STATUS-MIB", "qosSentVolume"), ("APPACCELERATION-STATUS-MIB", "qosReceiveVolume"), ("APPACCELERATION-STATUS-MIB", "qosSentPackets"), ("APPACCELERATION-STATUS-MIB", "qosReceivedPackets"), ("APPACCELERATION-STATUS-MIB", "qosDroppedSentVolume"), ("APPACCELERATION-STATUS-MIB", "qosDroppedReceiveVolume"), ("APPACCELERATION-STATUS-MIB", "qosDroppedSentPackets"), ("APPACCELERATION-STATUS-MIB", "qosDroppedReceivedPackets"), ("APPACCELERATION-STATUS-MIB", "lscIndex"), ("APPACCELERATION-STATUS-MIB", "lscServiceClassName"), ("APPACCELERATION-STATUS-MIB", "lscLink"), ("APPACCELERATION-STATUS-MIB", "lscSentVolume"), ("APPACCELERATION-STATUS-MIB", "lscReceivedVolume"), ("APPACCELERATION-STATUS-MIB", "lscSentPackets"), ("APPACCELERATION-STATUS-MIB", "lscReceivedPackets"), ("APPACCELERATION-STATUS-MIB", "lscDroppedSentVolume"), ("APPACCELERATION-STATUS-MIB", "lscDroppedReceiveVolume"), ("APPACCELERATION-STATUS-MIB", "lscDroppedSentPackets"), ("APPACCELERATION-STATUS-MIB", "lscDroppedReceivedPackets"), ("APPACCELERATION-STATUS-MIB", "partnerAddrType"), ("APPACCELERATION-STATUS-MIB", "partnerAddr"), ("APPACCELERATION-STATUS-MIB", "partnerConnections"), ("APPACCELERATION-STATUS-MIB", "partnerSendRate"), ("APPACCELERATION-STATUS-MIB", "partnerReceiveRate"), ("APPACCELERATION-STATUS-MIB", "partnerIdleTime")) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): wsStatusGroup = wsStatusGroup.setStatus('current') wsStatusTrapGroup = ObjectGroup((1, 3, 6, 1, 4, 1, 3845, 30, 4, 1, 2, 2, 2)).setObjects(("APPACCELERATION-STATUS-MIB", "wsHAMasterIpAddr"), ("APPACCELERATION-STATUS-MIB", "wsAlertAction"), ("APPACCELERATION-STATUS-MIB", "wsAlertClass"), ("APPACCELERATION-STATUS-MIB", "wsAlertMsg")) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): wsStatusTrapGroup = wsStatusTrapGroup.setStatus('current') wsStatusNotifyGroup = ObjectGroup((1, 3, 6, 1, 4, 1, 3845, 30, 4, 1, 2, 2, 3)).setObjects(("APPACCELERATION-STATUS-MIB", "wsNotifyStart"), ("APPACCELERATION-STATUS-MIB", "wsNotifyShutdown"), ("APPACCELERATION-STATUS-MIB", "wsNotifyRestart"), ("APPACCELERATION-STATUS-MIB", "wsHANotifyNewMaster"), ("APPACCELERATION-STATUS-MIB", "wsNotifyAvailBWChange"), ("APPACCELERATION-STATUS-MIB", "wsNotifyUnexpectedRestart"), ("APPACCELERATION-STATUS-MIB", "wsNotifyPersistentError"), ("APPACCELERATION-STATUS-MIB", "wsNotifyAlert")) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): wsStatusNotifyGroup = wsStatusNotifyGroup.setStatus('current') mibBuilder.exportSymbols("APPACCELERATION-STATUS-MIB", wsNotifyShutdown=wsNotifyShutdown, wsNotifyPersistentError=wsNotifyPersistentError, wsQosTrafficClassStatsTable=wsQosTrafficClassStatsTable, wsActiveAlarmAcked=wsActiveAlarmAcked, PYSNMP_MODULE_ID=appAccelerationStatusMIB, wsNotifyRestart=wsNotifyRestart, wsActiveConnections=wsActiveConnections, wsPrimaryIp=wsPrimaryIp, partnerConnections=partnerConnections, wsQosSentVolume=wsQosSentVolume, wsAdapterNetmask=wsAdapterNetmask, appId=appId, wsPartnerTable=wsPartnerTable, wsUpTime=wsUpTime, wsActiveAlarmIndex=wsActiveAlarmIndex, wsActiveAlarmSeverity=wsActiveAlarmSeverity, wsQosIndex=wsQosIndex, lscLink=lscLink, appParentId=appParentId, wsAdapterName=wsAdapterName, wsQosActualSendRatio=wsQosActualSendRatio, wsQosConfiguredSendRatio=wsQosConfiguredSendRatio, wsIcaStatsTable=wsIcaStatsTable, wsBypass=wsBypass, wsScsRecvBWSavings=wsScsRecvBWSavings, appDroppedReceiveVolume=appDroppedReceiveVolume, qosStatsEntry=qosStatsEntry, lscSentVolume=lscSentVolume, appGroupId=appGroupId, wsMaxPlugIns=wsMaxPlugIns, qosReceivedPackets=qosReceivedPackets, wsScsCompressReceivedOctets=wsScsCompressReceivedOctets, linkReceivedVolume=linkReceivedVolume, wsScsRecvCompressionRatio=wsScsRecvCompressionRatio, appSendRate=appSendRate, wsStatusNotifyGroup=wsStatusNotifyGroup, linkIndex=linkIndex, wsHaVmIp=wsHaVmIp, wsScsTotalNonAcceleratedOctets=wsScsTotalNonAcceleratedOctets, appReceivedPackets=appReceivedPackets, wsScsPreCompressSentOctets=wsScsPreCompressSentOctets, qosSentPackets=qosSentPackets, wsHaSecondaryIp=wsHaSecondaryIp, linkDroppedReceivedPackets=linkDroppedReceivedPackets, lscDroppedSentPackets=lscDroppedSentPackets, wsActiveAlarmServiceAffect=wsActiveAlarmServiceAffect, wsScsSendRecvCompressionRatio=wsScsSendRecvCompressionRatio, qosDroppedReceiveVolume=qosDroppedReceiveVolume, wsHAMasterIpAddr=wsHAMasterIpAddr, qosIndex=qosIndex, qosLink=qosLink, linkSentPackets=linkSentPackets, wsSendCompressionRatio=wsSendCompressionRatio, wsAlertAction=wsAlertAction, wsSystemLoad=wsSystemLoad, wsScsSendBWSavings=wsScsSendBWSavings, wsStatusMIBNotifications=wsStatusMIBNotifications, wsIcaServiceName=wsIcaServiceName, qosReceiveVolume=qosReceiveVolume, wsStatusMIBCompliances=wsStatusMIBCompliances, linkName=linkName, wsLoad5Min=wsLoad5Min, linkDroppedReceivedVolume=linkDroppedReceivedVolume, wsServiceClassIndex=wsServiceClassIndex, wsAdapterIndex=wsAdapterIndex, lscIndex=lscIndex, partnerReceiveRate=partnerReceiveRate, linkDroppedSentVolume=linkDroppedSentVolume, lscSentPackets=lscSentPackets, wsAcceleratedConnections=wsAcceleratedConnections, wsLscStatsTable=wsLscStatsTable, wsStatusMIBConformance=wsStatusMIBConformance, wsNonAcceleratedRate=wsNonAcceleratedRate, wsWccpStatus=wsWccpStatus, wsIcaIndex=wsIcaIndex, qosDroppedReceivedPackets=qosDroppedReceivedPackets, lscDroppedSentVolume=lscDroppedSentVolume, appSentVolume=appSentVolume, partnerEntry=partnerEntry, partnerAddr=partnerAddr, wsStatusMIBScalars=wsStatusMIBScalars, wsScsTotalNonAcceleratedConnections=wsScsTotalNonAcceleratedConnections, lscStatsEntry=lscStatsEntry, qosPolicyName=qosPolicyName, wsWanOutOctets=wsWanOutOctets, wsActiveAlarmLogTime=wsActiveAlarmLogTime, wsModelNumber=wsModelNumber, wsAlertMsg=wsAlertMsg, wsIcaReceiveRate=wsIcaReceiveRate, wsQosStatsCollectionTime=wsQosStatsCollectionTime, appStatsEntry=appStatsEntry, wsTrafficShapingStatus=wsTrafficShapingStatus, wsAdapterVirtualIp=wsAdapterVirtualIp, wsHaState=wsHaState, wsScsCompressSentOctets=wsScsCompressSentOctets, wsSerialNumber=wsSerialNumber, wsBoostStatus=wsBoostStatus, wsScsTotalAcceleratedOctets=wsScsTotalAcceleratedOctets, wsIcaStatsEntry=wsIcaStatsEntry, wsServiceClassStatsEntry=wsServiceClassStatsEntry, wsNotifyAlert=wsNotifyAlert, wsAppStatsTable=wsAppStatsTable, wsLoad1Min=wsLoad1Min, wsWanReceiveRate=wsWanReceiveRate, wsHANotifyNewMaster=wsHANotifyNewMaster, wsIcaSentRatio=wsIcaSentRatio, wsLanSendRate=wsLanSendRate, wsLanInOctets=wsLanInOctets, appDroppedSentVolume=appDroppedSentVolume, wsStatusMIBGroups=wsStatusMIBGroups, wsCompressionEffectiveBandwidth=wsCompressionEffectiveBandwidth, wsIcaReceivedVolume=wsIcaReceivedVolume, wsWanInOctets=wsWanInOctets, wsScsTotalPreCompressionOctets=wsScsTotalPreCompressionOctets, partnerIdleTime=partnerIdleTime, appDroppedReceivedPackets=appDroppedReceivedPackets, lscReceivedPackets=lscReceivedPackets, qosDroppedSentPackets=qosDroppedSentPackets, wsLastAlarmSeqNum=wsLastAlarmSeqNum, wsAdapterIp=wsAdapterIp, linkStatsEntry=linkStatsEntry, wsAdapterEnabled=wsAdapterEnabled, wsWanSendRate=wsWanSendRate, wsBandwidthMode=wsBandwidthMode, wsSourceIpAddr=wsSourceIpAddr, appSentPackets=appSentPackets, wsLanReceiveRate=wsLanReceiveRate, wsIcaSendRate=wsIcaSendRate, wsStatusMIBObjects=wsStatusMIBObjects, wsAlertClass=wsAlertClass, wsCompressionStatsCollectionTime=wsCompressionStatsCollectionTime, appIndex=appIndex, wsLinkStatsTable=wsLinkStatsTable, wsNonAcceleratedConnections=wsNonAcceleratedConnections, wsScsCurrentAcceleratedConnections=wsScsCurrentAcceleratedConnections, wsNonAcceleratedVolume=wsNonAcceleratedVolume, wsAdapterGateway=wsAdapterGateway, linkReceivedPackets=linkReceivedPackets, wsServiceClassStatsTable=wsServiceClassStatsTable, wsActiveAlarmID=wsActiveAlarmID, wsNotifyStart=wsNotifyStart, appName=appName, appReceiveRate=appReceiveRate, wsCpuUsage=wsCpuUsage, wsActiveAlarmSeqNum=wsActiveAlarmSeqNum, linkSentVolume=linkSentVolume, qosSentVolume=qosSentVolume, wsStatusTrapGroup=wsStatusTrapGroup, wsReceiveCompressionRatio=wsReceiveCompressionRatio, lscServiceClassName=lscServiceClassName, wsScsSendCompressionRatio=wsScsSendCompressionRatio, wsServiceClassName=wsServiceClassName, wsLoad15Min=wsLoad15Min, appReceivedVolume=appReceivedVolume, wsScsPreCompressReceivedOctets=wsScsPreCompressReceivedOctets, wsActiveAlarmDesc=wsActiveAlarmDesc, wsAdapterVLanEnabled=wsAdapterVLanEnabled, wsQosTcStatsEntry=wsQosTcStatsEntry, linkDroppedSentPackets=linkDroppedSentPackets, wsStatusMIBTables=wsStatusMIBTables, wsNotifyConfigurationChanged=wsNotifyConfigurationChanged, wsScsSendRecvBWSavings=wsScsSendRecvBWSavings, wsScsTotalAcceleratedConnections=wsScsTotalAcceleratedConnections, wsActiveAlarmTable=wsActiveAlarmTable, wsAdapterVLanGroup=wsAdapterVLanGroup, wsQosName=wsQosName, partnerAddrType=partnerAddrType, lscReceivedVolume=lscReceivedVolume, wsAccelerationStatus=wsAccelerationStatus, partnerSendRate=partnerSendRate, wsOperStatus=wsOperStatus, wsAdapterEntry=wsAdapterEntry, wsConnectedPlugIns=wsConnectedPlugIns, wsBandwidthLimit=wsBandwidthLimit, appDroppedSentPackets=appDroppedSentPackets, wsQosStatsTable=wsQosStatsTable, wsIcaSentVolume=wsIcaSentVolume, wsStatusGroup=wsStatusGroup, activeAlarmEntry=activeAlarmEntry, qosDroppedSentVolume=qosDroppedSentVolume, wsNotifyAvailBWChange=wsNotifyAvailBWChange, wsStatusMIBAlertTables=wsStatusMIBAlertTables, wsAdapterTable=wsAdapterTable, wsStatusCompliance=wsStatusCompliance, appAccelerationStatusMIB=appAccelerationStatusMIB, lscDroppedReceiveVolume=lscDroppedReceiveVolume, wsIcaPriority=wsIcaPriority, wsNotifyUnexpectedRestart=wsNotifyUnexpectedRestart, lscDroppedReceivedPackets=lscDroppedReceivedPackets, wsLanOutOctets=wsLanOutOctets, wsIcaReceivedRatio=wsIcaReceivedRatio)
python
# -*- coding: utf-8 -*- from __future__ import absolute_import from __future__ import print_function import os import sys if os.name == 'posix' and sys.version_info[0] < 3: import subprocess32 as subprocess else: import subprocess from . import common as cmn task_registry = {} def task(task_func): """ Decorate your tasks to register them. The name of the function is the public task name used to invoke it from the command line. """ task_registry[task_func.__name__] = task_func return task_func def s(command, verbose=False, fail_fast=True, interactive=False): """ Run a shell command. """ completed_process = None output = None if interactive: completed_process = subprocess.run( command, shell=True, stdin=sys.stdin, stdout=sys.stdout, stderr=sys.stderr, ) output = { "exit_code": completed_process.returncode, } else: completed_process = subprocess.run( command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, ) output = { "exit_code": completed_process.returncode, "out": completed_process.stdout.decode('utf-8'), "err": completed_process.stderr.decode('utf-8'), } result = None if completed_process.returncode == 0: result = cmn.OkResult(output) else: result = cmn.ErrorResult(output) fail = fail_fast and not result.ok if verbose or fail: cmn.logger.log( "Executed shell command '{command}'\n" "exit code was: {exit_code}\n".format( command=command, **result.value ) ) if (verbose or fail) and not interactive: cmn.logger.log( "stdout was:\n{out}\n" "stderr was:\n{err}".format( **result.value ) ) if fail: cmn.fail("Failed executing shell command '{command}'".format(command=command)) return result
python
#!/usr/bin/env python """Test for near equality """ import unittest class AlmostEqualTest(unittest.TestCase): def testNotAlmostEqual(self): self.failIfAlmostEqual(1.1, 3.3 - 2.0, places=1) def testAlmostEqual(self): self.failUnlessAlmostEqual(1.1, 3.3 - 2.0, places=0) if __name__ == '__main__': unittest.main()
python
import pytest from generalizer import generalize_label test_data = [ ('enter the email associated with your account', 'email'), ('zip code', 'ZIPcode'), ('postal code', 'ZIPcode'), ('first name', 'firstname'), ('last name', 'surname'), ('city', 'city'), ('reference name', 'name'), ('password', 'password'), ('username', 'username'), ('email', 'e-mail'), ('street', 'street'), ('street address', 'streetaddress'), ('state', 'state'), ('country', 'country'), ('zip', 'ZIPcode'), ('search', 'search'), ('apt. number', 'apt'), ('credit card number', 'number'), ('cvv', 'cvv'), ('expiration date', 'date'), ('birth date', 'date'), ('birthday', 'birthday'), ('date of birth', 'date'), ('account', 'report'), ('dependent', 'dependent'), ('job title', 'title'), ('title', 'title'), ('zip / postal code', 'ZIPcode'), ('state / province', 'state') ] @pytest.mark.parametrize("input_data,expected", test_data) def test_generalize_label(input_data, expected): assert generalize_label(input_data) == expected
python
# -*- coding: utf-8 -*- from __future__ import absolute_import, print_function, unicode_literals import sys from json import loads as json_loads from wolframclient.utils import six from wolframclient.utils.encoding import force_text # Python 3.4 and 3.5 json loads only accept str. if sys.version_info[0] == 3 and sys.version_info[1] <= 5: def loads(s, **kwargs): if isinstance(s, six.binary_type): s = force_text(s) return json_loads(s) else: loads = json_loads
python
from csc148_queue import Queue class Tree: """ A bare-bones Tree ADT that identifies the root with the entire tree. """ def __init__(self, value=None, children=None): """ Create Tree self with content value and 0 or more children @param Tree self: this tree @param object value: value contained in this tree @param list[Tree|None] children: possibly-empty list of children @rtype: None """ self.value = value # copy children if not None self.children = children.copy() if children else [] def __eq__(self, other): """ Return whether this Tree is equivalent to other. @param Tree self: this tree @param object|Tree other: object to compare to self @rtype: bool >>> t1 = Tree(5) >>> t2 = Tree(5, []) >>> t1 == t2 True >>> t3 = Tree(5, [t1]) >>> t2 == t3 False """ # print("{} == {}?".format(self.value, other.value)) return (type(self) == type(other) and self.value == other.value and self.children == other.children) def __str__(self, indent=0): """ Produce a user-friendly strindent=ing representation of Tree self, indenting each level as a visual clue. @param Tree self: this tree @param int indent: amount to indent each level of tree @rtype: str >>> t = Tree(17) >>> print(t) 17 >>> t1 = Tree(19, [t, Tree(23)]) >>> print(t1) 19 17 23 >>> t3 = Tree(29, [Tree(31), t1]) >>> print(t3) 29 31 19 17 23 """ root_str = indent * " " + str(self.value) return '\n'.join([root_str] + [c.__str__(indent + 3) for c in self.children]) def __contains__(self, v): """ Return whether Tree self contains v. @param Tree self: this tree @param object v: value to search this tree for # >>> t = Tree(17) # >>> t.__contains__(17) # True >>> t = descendants_from_list(Tree(19), [1, 2, 3, 4, 5, 6, 7], 3) >>> t.__contains__(5) True """ if not self.children: # self is a leaf return self.value == v else: # self is an interior node # this else block would probably also work for the base case! return ((self.value == v) or (any([v in child for child in self.children]))) # We can shorten the entire method: the lines from the else block are # sufficient (look closely to convince yourselves!): # return ((self.value == v) or # (any([v in child for child in self.children]))) # Any() stops early once it finds a True (no need to traverse the entire # list, *but* the list has to be fully generated first in memory. # We can avoid generating the entire list too, by turning the iterable # argument of any(), into a generator (just remove the []): # return ((self.value == v) or # (any(v in child for child in self.children))) def __repr__(self): """ Return representation of Tree (self) as string that can be evaluated into an equivalent Tree. @param Tree self: this tree @rtype: str >>> t1 = Tree(5) >>> t1 Tree(5) >>> t2 = Tree(7, [t1]) >>> t2 Tree(7, [Tree(5)]) """ # Our __repr__ is recursive, because it can also be called via repr...! return ('Tree({}, {})'.format(repr(self.value), repr(self.children)) if self.children else 'Tree({})'.format(repr(self.value))) # helpful helper function def descendants_from_list(t, list_, arity): """ Populate Tree t's descendants from list_, filling them in level order, with up to arity children per node. Then return t. @param Tree t: tree to populate from list_ @param list list_: list of values to populate from @param int arity: maximum branching factor @rtype: Tree # >>> descendants_from_list(Tree(0), [1, 2, 3, 4], 2) # Tree(0, [Tree(1, [Tree(3), Tree(4)]), Tree(2)]) """ q = Queue() q.add(t) list_ = list_.copy() while not q.is_empty(): # unlikely to happen new_t = q.remove() for i in range(0, arity): if len(list_) == 0: return t # our work here is done else: new_t_child = Tree(list_.pop(0)) new_t.children.append(new_t_child) q.add(new_t_child) return t def leaf_count(t): """ Return the number of leaves in Tree t. @param Tree t: tree to count the leaves of @rtype: int >>> t = Tree(7) >>> leaf_count(t) 1 >>> t = descendants_from_list(Tree(7), [0, 1, 3, 5, 7, 9, 11, 13], 3) >>> leaf_count(t) 6 """ return (sum([leaf_count(c) for c in t.children]) + (0 if t.children else 1)) def height(t): """ Return 1 + length of longest path of t. @param Tree t: tree to find height of @rtype: int >>> t = Tree(13) >>> height(t) 1 >>> t = descendants_from_list(Tree(13), [0, 1, 3, 5, 7, 9, 11, 13], 3) >>> height(t) 3 """ return 1 + max([height(c) for c in t.children]) if t.children else 1 def count(t): """ Return the number of nodes in Tree t. @param Tree t: tree to find number of nodes in @rtype: int >>> t = Tree(17) >>> count(t) 1 >>> t4 = descendants_from_list(Tree(17), [0, 2, 4, 6, 8, 10, 11], 4) >>> count(t4) 8 """ return 1 + sum([count(n) for n in t.children]) # helper function that may be useful for other tree functions def gather_lists(list_): """ Concatenate all the sublists of L and return the result. @param list[list[object]] list_: list of lists to concatenate @rtype: list[object] >>> gather_lists([[1, 2], [3, 4, 5]]) [1, 2, 3, 4, 5] >>> gather_lists([[6, 7], [8], [9, 10, 11]]) [6, 7, 8, 9, 10, 11] """ new_list = [] for l in list_: new_list += l return new_list def list_all(t): """ Return list of values in t. @param Tree t: tree to list values of @rtype: list[object] >>> t = Tree(0) >>> list_all(t) [0] >>> t = descendants_from_list(Tree(0), [1, 2, 3, 4, 5, 6, 7, 8], 3) >>> list_ = list_all(t) >>> list_.sort() >>> list_ [0, 1, 2, 3, 4, 5, 6, 7, 8] """ return [t.value] + gather_lists([list_all(c) for c in t.children]) def list_if(t, p): """ Return a list of values in Tree t that satisfy predicate p(value). @param Tree t: tree to list values that satisfy predicate p @param (object)->bool p: predicate to check values with @rtype: list[object] >>> def p(v): return v > 4 >>> t = descendants_from_list(Tree(0), [1, 2, 3, 4, 5, 6, 7, 8], 3) >>> list_ = list_if(t, p) >>> list_.sort() >>> list_ [5, 6, 7, 8] >>> def p(v): return v % 2 == 0 >>> list_ = list_if(t, p) >>> list_.sort() >>> list_ [0, 2, 4, 6, 8] """ # practice on your own! pass def list_leaves(t): """ Return list of values in leaves of t. @param Tree t: tree to list leaf values of @rtype: list[object] >>> t = Tree(0) >>> list_leaves(t) [0] >>> t = descendants_from_list(Tree(0), [1, 2, 3, 4, 5, 6, 7, 8], 3) >>> list_ = list_leaves(t) >>> list_.sort() # so list_ is predictable to compare >>> list_ [3, 4, 5, 6, 7, 8] """ # practice on your own! pass def preorder_visit(t, act): """ Visit each node of Tree t in preorder, and act on the nodes as they are visited. @param Tree t: tree to visit in preorder @param (Tree)->Any act: function to carry out on visited Tree node @rtype: None >>> t = descendants_from_list(Tree(0), [1, 2, 3, 4, 5, 6, 7], 3) >>> def act(node): print(node.value) >>> preorder_visit(t, act) 0 1 4 5 6 2 7 3 """ act(t) for child in t.children: preorder_visit(child, act) def postorder_visit(t, act): """ Visit each node of t in postorder, and act on it when it is visited. @param Tree t: tree to be visited in postorder @param (Tree)->Any act: function to do to each node @rtype: None >>> t = descendants_from_list(Tree(0), [1, 2, 3, 4, 5, 6, 7], 3) >>> def act(node): print(node.value) >>> postorder_visit(t, act) 4 5 6 1 7 2 3 0 """ for child in t.children: postorder_visit(child, act) act(t) def levelorder_visit(t, act): """ Visit every node in Tree t in level order and act on the node as you visit it. @param Tree t: tree to visit in level order @param (Tree)->Any act: function to execute during visit >>> t = descendants_from_list(Tree(0), [1, 2, 3, 4, 5, 6, 7], 3) >>> def act(node): print(node.value) >>> levelorder_visit(t, act) 0 1 2 3 4 5 6 7 """ nodes_to_be_processed = Queue() nodes_to_be_processed.add(t) while not nodes_to_be_processed.is_empty(): next_node = nodes_to_be_processed.remove() act(next_node) for c in next_node.children: nodes_to_be_processed.add(c) def visit_level(t, n, act): """ Visit nodes of t at level n, act on them, and return the number visited. @param Tree t: tree to visit level n of @param int n: level (depth) to visit @param (Tree)->object act: function to execute at level n @rtype: int >>> t = descendants_from_list(Tree(0), [1, 2, 3, 4, 5, 6, 7], 3) >>> def act(node): print(node.value) >>> visit_level(t, 1, act) 1 2 3 3 """ if n == 0: act(t) return 1 else: return sum([visit_level(c, n-1, act) for c in t.children]) def levelorder_visit2(t, act): """ Visit Tree t in level order and act on its nodes. @param Tree t: Tree to visit in level order @param (Tree)->object act: function to execute on visit @rtype: None >>> t = descendants_from_list(Tree(0), [1, 2, 3, 4, 5, 6, 7], 3) >>> def act(node): print(node.value) >>> levelorder_visit2(t, act) 0 1 2 3 4 5 6 7 """ visited = visit_level(t, 0, act) n = 0 while visited > 0: n += 1 visited = visit_level(t, n, act) if __name__ == '__main__': import doctest doctest.testmod() t3 = descendants_from_list(Tree(19), [1, 2, 3, 4, 5, 6, 7], 3) t4 = descendants_from_list(Tree(19), [1, 2, 3, 4, 5, 6, 7], 3) print(t3 == t4) # print(5 in t3) print("===========") print(str(t3)) print("===========") print(repr(t3)) t5 = eval(repr(t3)) print("===========") print(str(t5)) print(t5 == t3)
python
pythonic_machine_ages = [19, 22, 34, 26, 32, 30, 24, 24] def mean(dataset): return sum(dataset) / len(dataset) print(mean(pythonic_machine_ages)) print(sum(pythonic_machine_ages))
python
""" business days module """ from datetime import timedelta, date from collections.abc import Generator import holidays def business_days_list(sdate: date, edate: date) -> list[date]: """ get business days for start and end date inclusive """ days = [] us_holidays = holidays.UnitedStates() for num in range((edate - sdate).days + 1): the_date = sdate + timedelta(days=num) if (the_date.weekday() < 5) and (the_date not in us_holidays): days.append(the_date) return days def business_days(sdate: date, edate: date ) -> Generator[date, None, None]: """ get business days for start and end date inclusive """ us_holidays = holidays.UnitedStates() for num in range((edate - sdate).days + 1): the_date = sdate + timedelta(days=num) if (the_date.weekday() < 5) and (the_date not in us_holidays): yield the_date if __name__ == "__main__": start_date = date(2021, 1, 1) end_date = date(2021, 3, 31) for business_day in business_days(start_date, end_date): print("in the loop") print(business_day)
python
from random import randint from math import hypot, fabs, ceil class AudioSource: def __init__(self, pos, tile): self.pos = pos self.tile = tile def ValidatedMove(self, velocity, map): new_location = {'tile' : [self.tile.pos[0], self.tile.pos[1]], 'position' : [0, 0]} if velocity[1] < 0: if self.pos[1] + velocity[1] >= 0: new_location['position'][1] = self.pos[1] + velocity[1] elif self.tile.pos[1] > 0: new_location['position'][1] = (self.tile.height + velocity[1]) new_location['tile'][1] = self.tile.pos[1] - 1 else: return False elif velocity[1] > 0: if self.pos[1] + velocity[1] <= self.tile.height - 1: new_location['position'][1] = self.pos[1] + velocity[1] elif self.tile.pos[1] < map.height - 1: new_location['position'][1] = velocity[1] - 1 new_location['tile'][1] = self.tile.pos[1] + 1 else: return False elif velocity[1] == 0: new_location['position'][1] = self.pos[1] new_location['tile'][1] = self.tile.pos[1] if velocity[0] > 0: if self.pos[0] + velocity[0] <= self.tile.width - 1: new_location['position'][0] = self.pos[0] + velocity[0] elif self.tile.pos[0] < map.width - 1: new_location['position'][0] = velocity[0] - 1 new_location['tile'][0] = self.tile.pos[0] + 1 else: return False elif velocity[0] < 0: if self.pos[0] + velocity[0] >= 0: new_location['position'][0] = self.pos[0] + velocity[0] elif self.tile.pos[0] > 0: new_location['position'][0] = map.width + velocity[0] new_location['tile'][0] = self.tile.pos[0] - 1 else: return False elif velocity[0] == 0: new_location['position'][0] = self.pos[0] new_location['tile'][0] = self.tile.pos[0] print(new_location) for field in map.tiles[(new_location['tile'][0], new_location['tile'][1])].FieldsAtLocation(new_location['position']): if field.clipping == False: return False print('moving') self.pos = new_location['position'] self.tile = map.tiles[(new_location['tile'][0], new_location['tile'][1])] return True def Move(self, velocity): self.pos[0] = self.pos[0] + velocity[0] self.pos[1] = self.pos[1] + velocity[1] def DistanceFrom(self, coords): self.xdist = self.pos[0] - coords[0] self.ydist = self.pos[1] - coords[1] self.hdist = hypot(fabs(xdist), fabs(ydist)) return self.hdist class NamedSource(AudioSource): def __init__(self, pos, tile, name): AudioSource.__init__(self, pos, tile) self.name = name class Zombie(NamedSource): def __init__(self, pos, tile): NamedSource.__init__(self, pos, tile, 'zombie') self.state = "wander" def behave(self, target, map): if self.state == "wander": if self.sense(target): self.state = "follow" elif self.state == "follow": absolute_self_position = ((self.tile.pos[0]*self.tile.width + self.pos[0]), (self.tile.pos[1]*self.tile.height + self.pos[1])) absolute_target_position = ((target.tile.pos[0]*target.tile.width + target.pos[0]), (target.tile.pos[1]*target.tile.height + target.pos[1])) xdist = absolute_target_position[0] - absolute_self_position[0] ydist = absolute_target_position[1] - absolute_self_position[1] hdist = hypot(fabs(xdist), fabs(ydist)) try: velocity = (ceil(xdist/hdist), ceil(ydist/hdist)) except ZeroDivisionError: self.state = 'kill' else: if self.pos == target.pos: self.state = 'kill' else: self.ValidatedMove(velocity, map) if not self.sense(target): self.state = "lost" elif self.state == "lost": if self.sense(target): self.state = "follow" else: self.state = "wander" elif self.state == "kill": self.pos = target.pos self.tile = target.tile def sense(self, target): hdist = hypot(fabs(self.pos[0] - target.pos[0]), fabs(self.pos[1] - target.pos[1])) if hdist > 7: return False else: return True """ class Monster(Creature): def __init__(self, pos, aggression_sfx, sensory_sfx, footstep_sfx): Creature.__init__(self, pos) self.cries = {'aggression' : aggression_sfx, 'sensory' : sensory_sfx, 'footstep' : footstep_sfx} def aggress(self, listener_pos): sound_name = self.cries['aggression'] + str(randint(1, 3)) self.MakeNoise(sound_name, listener_pos) def sense(self, listener_pos): sound_name = self.cries['sensory'] + str(randint(1, 3)) self.MakeNoise(sound_name, listener_pos) def step(self, listener_pos, velocity): self.Move(velocity[0], velocity[1]) sound_name = self.cries['footstep'] + str(randint(1, 3)) self.MakeNoise(sound_name, listener_pos) """ class Player(AudioSource): def __init__(self, pos): AudioSource.__init__(self, pos)
python
* * * * * * * * * * * * * * * * * * PRINT TRIANGLE LOOK LIKE THIS =========================================== for row in range(7): for col in range(7): if(row-col==row)or(row==6)or(row==col): print("*",end=" ") else: print(" ",end=" ") print() #for next line or row
python
DEPARTMENTS_MAP = { "che": "Chemical", "che-idd": "Chemical IDD", "cer": "Ceramic", "cer-idd": "Ceramic IDD", "civ": "Civil", "civ-idd": "Civil IDD", "cse": "Computer Science", "cse-idd": "Computer Science IDD", "eee": "Electrical", "eee-idd": "Electrical IDD", "ece": "Electronics", "mat": "Mathematics", "mat-idd": "Mathematics IDD", "mec": "Mechanical", "mec-idd": "Mechanical IDD", "min": "Mining", "min-idd": "Mining IDD", "phe": "Pharma", "phe-idd": "Pharma IDD", "chy": "Chemistry", "chy-idd": "Chemistry IDD", "met": "Metallurgy", "met-idd": "Metallurgy IDD", "mst": "Material", "mst-idd": "Material IDD", "hss": "humanities", "phy": "Physics", "phy-idd": "Physics IDD", "bce": "Biotechnology", "bce-idd": "Biotechnology IDD", "bme": "Biomedical", "bme-idd": "Biomedical IDD", "all": "all" }
python
# -*- coding: utf-8 -*- __author__ = 'study_sun' from spider_base.downloader import * import sys reload(sys) sys.setdefaultencoding('utf-8') class IndexDownloader(SBDownloader): pass
python
INPUT_IMAGE_WIDTH = 1024
python
##### Imports ##### from datetime import date, datetime import json import dateutil.parser import babel from flask import ( Flask, render_template, request, Response, flash, redirect, url_for) from flask_moment import Moment from flask_sqlalchemy import SQLAlchemy from flask_migrate import Migrate from flask_wtf import Form import logging from logging import Formatter, FileHandler # Import other *.py files of the project from forms import * from models import db, Venue, Artist, Show ##### APP CONFIG ##### app = Flask(__name__) app.config.from_object('config') moment = Moment(app) db.init_app(app) # Activate Migration migrate = Migrate(app, db) ##### FILTERS ##### def format_datetime(value, format='medium'): date = dateutil.parser.parse(value) if format == 'full': format="EEEE MMMM, d, y 'at' h:mma" elif format == 'medium': format="EE MM, dd, y h:mma" return babel.dates.format_datetime(date, format) app.jinja_env.filters['datetime'] = format_datetime ##### CONTROLLERS ##### @app.route('/') def index(): return render_template('pages/home.html') ##### Artists ##### # 1.- Create Artist @app.route('/artists/create', methods=['GET']) def create_artist_form(): form = ArtistForm() return render_template('forms/new_artist.html', form=form) @app.route('/artists/create', methods=['POST']) def create_artist_submission(): form = ArtistForm(request.form, csrf_enabled=False) if form.validate(): try: # Using FlaskForm: artist = Artist( name = form.name.data, city = form.city.data, seeking_venue = form.seeking_venue.data, state = form.state.data, phone = form.phone.data, website = form.website.data, seeking_description = form.seeking_description.data, image_link = form.image_link.data, genres = form.genres.data, facebook_link = form.facebook_link.data, ) # Or: # artist = Artist() # form.populate_obj(artist) db.session.add(artist) db.session.commit() flash('Artist ' + form.name.data + ' was successfully listed!') except ValueError as e: print(e) flash('An error occurred. Artist ' + form.name.data + ' could not be listed.') db.session.rollback() finally: db.session.close() else: message = [] for field, err in form.errors.items(): message.append(field + ' ' + '|'.join(err)) flash('Errors ' + str(message)) return render_template('pages/home.html') # 2.- Get Artist @app.route('/artists') def artists(): return render_template('pages/artists.html', artists=Artist.query.all()) @app.route('/artists/<int:artist_id>') def show_artist(artist_id): artist = Artist.query.filter_by(id=artist_id).first_or_404() past_shows = db.session.query(Venue, Show).join(Show).join(Artist).\ filter( Show.venue_id == Venue.id, Show.artist_id == artist_id, Show.start_time < datetime.now() ).\ all() upcoming_shows = db.session.query(Venue, Show).join(Show).join(Artist).\ filter( Show.venue_id == Venue.id, Show.artist_id == artist_id, Show.start_time > datetime.now() ).\ all() data = { 'id': artist.id, 'name': artist.name, 'city': artist.city, 'state': artist.state, 'phone': artist.phone, 'website': artist.website, 'image_link': artist.image_link, 'genres': artist.genres, 'facebook_link': artist.facebook_link, 'seeking_venue': artist.seeking_venue, 'seeking_description': artist.seeking_description, 'past_shows': [{ 'venue_id': venue.id, 'venue_name': venue.name, 'venue_image_link': venue.image_link, 'start_time': show.start_time.strftime("%m/%d/%Y, %H:%M") } for venue, show in past_shows], 'upcoming_shows': [{ 'venue_id': venue.id, 'venue_name': venue.name, 'venue_image_link': venue.image_link, 'start_time': show.start_time.strftime("%m/%d/%Y, %H:%M") } for venue, show in upcoming_shows], 'past_shows_count': len(past_shows), 'upcoming_shows_count': len(upcoming_shows) } return render_template('pages/show_artist.html', artist=data) # 3.- Update Artist @app.route('/artists/<int:artist_id>/edit', methods=['GET']) def edit_artist(artist_id): # OR: # form = ArtistForm() # artist = Artist.query.get(artist_id) # return render_template('forms/edit_artist.html', form=form, artist=artist) artist = Artist.query.first_or_404(artist_id) form = ArtistForm(obj=artist) return render_template('forms/edit_artist.html', form=form, artist=artist) @app.route('/artists/<int:artist_id>/edit', methods=['POST']) def edit_artist_submission(artist_id): artist = Artist.query.get(artist_id) error = False form = ArtistForm(request.form, csrf_enabled=False) if form.validate(): try: # Using FlaskForm: artist.name = form.name.data artist.city = form.city.data artist.seeking_venue = form.seeking_venue.data artist.state = form.state.data artist.phone = form.phone.data artist.website = form.website.data artist.seeking_description = form.seeking_description.data artist.image_link = form.image_link.data artist.genres = form.genres.data artist.facebook_link = form.facebook_link.data db.session.add(artist) db.session.commit() flash('Artist ' + artist.name + ' was successfully updated!') except ValueError as e: print(e) flash('An error occurred. Artist ' + artist.name + ' could not be updated.') db.session.rollback() finally: db.session.close() return redirect(url_for('show_artist', artist_id=artist_id)) @app.route('/artists/search', methods=['POST']) def search_artists(): search_term = request.form.get('search_term') search_results = Artist.query.filter( Artist.name.ilike('%{}%'.format(search_term))).all() # search results by ilike matching partern to match every search term response = {} response['count'] = len(search_results) response['data'] = search_results return render_template('pages/search_artists.html', results=response, search_term=request.form.get('search_term', '')) ##### VENUES ##### # 1.- Create Venue: @app.route('/venues/create', methods=['GET']) def create_venue_form(): form = VenueForm() return render_template('forms/new_venue.html', form=form) @app.route('/venues/create', methods=['POST']) def create_venue_submission(): form = VenueForm(request.form, csrf_enabled=False) if form.validate(): try: # Using FlaskForm: venue = Venue( name = form.name.data, city = form.city.data, state = form.state.data, address = form.address.data, phone = form.phone.data, image_link = form.image_link.data, website = form.website.data, seeking_talent = form.seeking_talent.data, seeking_description = form.seeking_description.data, genres = form.genres.data, facebook_link = form.facebook_link.data, ) # Or: # venue = Venue() # form.populate_obj(venue) db.session.add(venue) db.session.commit() flash('Venue ' + form.name.data + ' was successfully listed!') except ValueError as e: print(e) flash('An error occured. Venue ' + form.name.data + ' Could not be listed!') db.session.rollback() finally: db.session.close() else: message = [] for field, err in form.errors.items(): message.append(field + ' ' + '|'.join(err)) flash('Errors ' + str(message)) return render_template('pages/home.html') # 2.- Get Venue: @app.route('/venues') def venues(): locals = [] venues = Venue.query.all() places = Venue.query.distinct(Venue.city, Venue.state).all() for place in places: locals.append({ 'city': place.city, 'state': place.state, 'venues': [{ 'id': venue.id, 'name': venue.name, 'num_upcoming_shows': len([show for show in venue.shows if show.start_time > datetime.now()]) } for venue in venues if venue.city == place.city and venue.state == place.state] }) print(locals[0]) return render_template('pages/venues.html', areas=locals) @app.route('/venues/search', methods=['POST']) def search_venues(): search_term = request.form.get('search_term') venues = Venue.query.filter( Venue.name.ilike('%{}%'.format(search_term))).all() data = [] for venue in venues: tmp = {} tmp['id'] = venue.id tmp['name'] = venue.name tmp['num_upcoming_shows'] = len(venue.shows) data.append(tmp) response = {} response['count'] = len(data) response['data'] = data return render_template('pages/search_venues.html', results=response, search_term=request.form.get('search_term', '')) @app.route('/venues/<int:venue_id>') def show_venue(venue_id): venue = Venue.query.filter_by(id=venue_id).first_or_404() past_shows = db.session.query(Artist, Show).join(Show).join(Venue).\ filter( Show.venue_id == venue_id, Show.artist_id == Artist.id, Show.start_time < datetime.now() ).\ all() upcoming_shows = db.session.query(Artist, Show).join(Show).join(Venue).\ filter( Show.venue_id == venue_id, Show.artist_id == Artist.id, Show.start_time > datetime.now() ).\ all() data = { 'id': venue.id, 'name': venue.name, 'city': venue.city, 'state': venue.state, 'address': venue.address, 'phone': venue.phone, 'image_link': venue.image_link, 'website': venue.website, 'seeking_talent': venue.seeking_talent, 'seeking_description': venue.seeking_description, 'genres': venue.genres, 'facebook_link': venue.facebook_link, 'past_shows': [{ 'artist_id': artist.id, "artist_name": artist.name, "artist_image_link": artist.image_link, "start_time": show.start_time.strftime("%m/%d/%Y, %H:%M") } for artist, show in past_shows], 'upcoming_shows': [{ 'artist_id': artist.id, 'artist_name': artist.name, 'artist_image_link': artist.image_link, 'start_time': show.start_time.strftime("%m/%d/%Y, %H:%M") } for artist, show in upcoming_shows], 'past_shows_count': len(past_shows), 'upcoming_shows_count': len(upcoming_shows) } print(venue.genres) return render_template('pages/show_venue.html', venue=data) # 3.- Update Venue: @app.route('/venues/<int:venue_id>/edit', methods=['GET']) def edit_venue(venue_id): # OR: # form = VenueForm() # venue = Venue.query.get(venue_id).to_dict() # return render_template('forms/edit_venue.html', form=form, venue=venue) venue = Venue.query.first_or_404(venue_id) form = VenueForm(obj=venue) return render_template('forms/edit_venue.html', form=form, venue=venue) @app.route('/venues/<int:venue_id>/edit', methods=['POST']) def edit_venue_submission(venue_id): venue = Venue.query.get(venue_id) error = False form = VenueForm(request.form, csrf_enabled=False) if form.validate(): try: venue.name = form.name.data venue.city = form.city.data venue.state = form.state.data venue.address = form.address.data venue.phone = form.phone.data venue.image_link = form.image_link.data venue.website = form.website.data venue.seeking_description = form.seeking_description.data venue.genres = form.genres.data # Revisar!!!!: # tmp_genres = request.form.getlist('genres') # venue.genres = ','.join(tmp_genres) # convert list to string venue.facebook_link = form.facebook_link.data db.session.add(venue) db.session.commit() flash('Venue ' + venue.name + ' was successfully updated!') except ValueError as e: print(e) flash('An error occurred. Venue ' + venue.name + ' could not be updated.') db.session.rollback() finally: db.session.close() return redirect(url_for('show_venue', venue_id=venue_id)) ##### SHOWS ##### @app.route('/shows') def shows(): shows = Show.query.all() data = [] for show in shows: data.append({ 'venue_id': show.venue.id, 'venue_name': show.venue.name, 'artist_id': show.artist.id, 'artist_name': show.artist.name, 'artist_image_link': show.artist.image_link, 'start_time': show.start_time.isoformat() }) return render_template('pages/shows.html', shows=data) @app.route('/shows/create') def create_shows(): # renders form. do not touch. form = ShowForm() return render_template('forms/new_show.html', form=form) @app.route('/shows/create', methods=['POST']) def create_show_submission(): error = False form = ShowForm(request.form, csrf_enabled=False) if form.validate(): try: # Using FlaskForm: show = Show( artist_id = form.artist_id.data, venue_id = form.venue_id.data, start_time = form.start_time.data, ) # Or: # show = Show() # form.populate_obj(show) db.session.add(show) db.session.commit() flash('Requested show was successfully listed') except ValueError as e: print(e) flash('An error occurred. Requested show could not be listed.') db.session.rollback() finally: db.session.close() else: message = [] for field, err in form.errors.items(): message.append(field + ' ' + '|'.join(err)) flash('Errors ' + str(message)) return render_template('pages/home.html') @app.errorhandler(404) def not_found_error(error): return render_template('errors/404.html'), 404 @app.errorhandler(500) def server_error(error): return render_template('errors/500.html'), 500 if not app.debug: file_handler = FileHandler('error.log') file_handler.setFormatter( Formatter( '%(asctime)s %(levelname)s: %(message)s [in %(pathname)s:%(lineno)d]') ) app.logger.setLevel(logging.INFO) file_handler.setLevel(logging.INFO) app.logger.addHandler(file_handler) app.logger.info('errors') ##### Launch ##### # Default port: if __name__ == '__main__': app.run()
python
#!/usr/bin/env python """ a collection of functions for reading EEG signals and applying basic filtering operations """ import os import scipy.io import numpy as np from scipy.signal import butter, lfilter def butter_lowpass(cutoff, fs, order=5): """ wrapper for calculating parameters of a lowpass filter Args: cutoff: cutoff frequency fs: sampling frequency order: order of butterworth filter Returns: parameters used in lowpass filtering """ nyq = 0.5 * fs normal_cutoff = cutoff / nyq b, a = butter(order, normal_cutoff, btype='low', analog=False) return b, a def butter_lowpass_filter(data, cutoff, fs, order=5): """ apply a lowpass filter Args: data: input signal cutoff: cutoff frequency fs: sampling frequency order: order of butterworth filter Returns: output signal """ b, a = butter_lowpass(cutoff, fs, order=order) y = lfilter(b, a, data) return y def butter_highpass(cutoff, fs, order=5): """ wrapper for calculating parameters of a highpass filter Args: cutoff: cutoff frequency fs: sampling frequency order: order of butterworth filter Returns: parameters used in highpass filtering """ nyq = 0.5 * fs normal_cutoff = cutoff / nyq b, a = butter(order, normal_cutoff, btype='high', analog=False) return b, a def butter_highpass_filter(data, cutoff, fs, order=5): """ apply a highpass filter Args: data: input signal cutoff: cutoff frequency fs: sampling frequency order: order of butterworth filter Returns: output signal """ b, a = butter_highpass(cutoff, fs, order=order) y = lfilter(b, a, data) return y def butter_bandpass(lowcut, highcut, fs, order=5): """ wrapper for calculating parameters of a bandpass filter Args: lowcut: cutoff frequency for lowpass highcut: cutoff frequency for highpass fs: sampling frequency order: order of butterworth filter Returns: parameters used in bandpass filtering """ nyq = 0.5 * fs low = lowcut / nyq high = highcut / nyq b, a = butter(order, [low, high], btype='band') return b, a
python
# -*- coding: utf-8 -*- from __future__ import unicode_literals import django.db.models.deletion from django.db import models, migrations import orchestra.models.fields from django.conf import settings class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] operations = [ migrations.CreateModel( name='Message', fields=[ ('id', models.AutoField(primary_key=True, serialize=False, auto_created=True, verbose_name='ID')), ('author_name', models.CharField(blank=True, max_length=256, verbose_name='author name')), ('content', models.TextField(verbose_name='content')), ('created_on', models.DateTimeField(auto_now_add=True, verbose_name='created on')), ('author', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='ticket_messages', to=settings.AUTH_USER_MODEL, verbose_name='author')), ], options={ 'get_latest_by': 'id', }, ), migrations.CreateModel( name='Queue', fields=[ ('id', models.AutoField(primary_key=True, serialize=False, auto_created=True, verbose_name='ID')), ('name', models.CharField(max_length=128, verbose_name='name', unique=True)), ('verbose_name', models.CharField(blank=True, max_length=128, verbose_name='verbose_name')), ('default', models.BooleanField(verbose_name='default', default=False)), ('notify', orchestra.models.fields.MultiSelectField(blank=True, max_length=256, help_text='Contacts to notify by email', verbose_name='notify', default=('SUPPORT', 'ADMIN', 'BILLING', 'TECH', 'ADDS', 'EMERGENCY'), choices=[('SUPPORT', 'Support tickets'), ('ADMIN', 'Administrative'), ('BILLING', 'Billing'), ('TECH', 'Technical'), ('ADDS', 'Announcements'), ('EMERGENCY', 'Emergency contact')])), ], ), migrations.CreateModel( name='Ticket', fields=[ ('id', models.AutoField(primary_key=True, serialize=False, auto_created=True, verbose_name='ID')), ('creator_name', models.CharField(blank=True, max_length=256, verbose_name='creator name')), ('subject', models.CharField(max_length=256, verbose_name='subject')), ('description', models.TextField(verbose_name='description')), ('priority', models.CharField(max_length=32, default='MEDIUM', verbose_name='priority', choices=[('HIGH', 'High'), ('MEDIUM', 'Medium'), ('LOW', 'Low')])), ('state', models.CharField(max_length=32, default='NEW', verbose_name='state', choices=[('NEW', 'New'), ('IN_PROGRESS', 'In Progress'), ('RESOLVED', 'Resolved'), ('FEEDBACK', 'Feedback'), ('REJECTED', 'Rejected'), ('CLOSED', 'Closed')])), ('created_at', models.DateTimeField(auto_now_add=True, verbose_name='created')), ('updated_at', models.DateTimeField(auto_now=True, verbose_name='modified')), ('cc', models.TextField(blank=True, help_text='emails to send a carbon copy to', verbose_name='CC')), ('creator', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='tickets_created', null=True, to=settings.AUTH_USER_MODEL, verbose_name='created by')), ('owner', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, blank=True, related_name='tickets_owned', null=True, to=settings.AUTH_USER_MODEL, verbose_name='assigned to')), ('queue', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, blank=True, related_name='tickets', null=True, to='issues.Queue')), ], options={ 'ordering': ['-updated_at'], }, ), migrations.CreateModel( name='TicketTracker', fields=[ ('id', models.AutoField(primary_key=True, serialize=False, auto_created=True, verbose_name='ID')), ('ticket', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='trackers', to='issues.Ticket', verbose_name='ticket')), ('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='ticket_trackers', to=settings.AUTH_USER_MODEL, verbose_name='user')), ], ), migrations.AddField( model_name='message', name='ticket', field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='messages', to='issues.Ticket', verbose_name='ticket'), ), migrations.AlterUniqueTogether( name='tickettracker', unique_together=set([('ticket', 'user')]), ), ]
python
raise ValueError("test failed! wrapper did not ignore polluted PWD. either the wrapper is faulty, or ooni is still unpatched (Tor bug #13581)")
python
"""empty message Revision ID: 879fe8a73df4 Revises: 8c3766231a8f Create Date: 2018-06-07 19:56:40.800424 """ from alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic. revision = '879fe8a73df4' down_revision = '8c3766231a8f' branch_labels = None depends_on = None def upgrade(): # ### commands auto generated by Alembic - please adjust! ### op.add_column('registrants', sa.Column('addr_lookup_complete', sa.Boolean(), nullable=True)) op.add_column('registrants', sa.Column('reg_lookup_complete', sa.Boolean(), nullable=True)) # ### end Alembic commands ### def downgrade(): # ### commands auto generated by Alembic - please adjust! ### op.drop_column('registrants', 'reg_lookup_complete') op.drop_column('registrants', 'addr_lookup_complete') # ### end Alembic commands ###
python
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('peacecorps', '0035_auto_20141202_2354'), ] operations = [ migrations.AddField( model_name='campaign', name='accountnew', field=models.ForeignKey(blank=True, to='peacecorps.Account', related_name='cam', null=True, unique=True, to_field='code'), preserve_default=True, ), migrations.AddField( model_name='project', name='accountnew', field=models.ForeignKey(blank=True, to='peacecorps.Account', related_name='proj', null=True, unique=True, to_field='code'), preserve_default=True, ), ]
python
import time from flask import request, jsonify, make_response from app import app from controllers.mock_data import request_method_list, get_mock_data @app.route('/mock/<path:path>', methods=request_method_list) def mock_call(path): try: if not path.startswith('/'): path = "/" + path method = request.method mock_data = get_mock_data(method, path) if mock_data: if 'delaySeconds' in mock_data and mock_data.get('delaySeconds') > 0: time.sleep(mock_data.get('delaySeconds')) return make_response(jsonify(mock_data.get('responseBody')), mock_data.get('responseCode')) else: return make_response(jsonify({ 'status': 'failed', 'msg': 'MockData不存在' }), 400) except BaseException as e: return make_response(jsonify({"error": str(e)}), 500)
python
# Hyppopy - A Hyper-Parameter Optimization Toolbox # # Copyright (c) German Cancer Research Center, # Division of Medical Image Computing. # All rights reserved. # # This software is distributed WITHOUT ANY WARRANTY; without # even the implied warranty of MERCHANTABILITY or FITNESS FOR # A PARTICULAR PURPOSE. # # See LICENSE import unittest from hyppopy.SolverPool import SolverPool from hyppopy.HyppopyProject import HyppopyProject from hyppopy.FunctionSimulator import FunctionSimulator from hyppopy.solvers.HyperoptSolver import HyperoptSolver from hyppopy.solvers.OptunitySolver import OptunitySolver from hyppopy.solvers.OptunaSolver import OptunaSolver from hyppopy.solvers.RandomsearchSolver import RandomsearchSolver from hyppopy.solvers.QuasiRandomsearchSolver import QuasiRandomsearchSolver from hyppopy.solvers.GridsearchSolver import GridsearchSolver class SolverPoolTestSuite(unittest.TestCase): def setUp(self): pass def test_PoolContent(self): names = SolverPool.get_solver_names() self.assertTrue("hyperopt" in names) self.assertTrue("optunity" in names) self.assertTrue("optuna" in names) self.assertTrue("randomsearch" in names) self.assertTrue("quasirandomsearch" in names) self.assertTrue("gridsearch" in names) def test_getHyperoptSolver(self): config = { "hyperparameter": { "axis_00": { "domain": "uniform", "data": [300, 700], "type": float }, "axis_01": { "domain": "uniform", "data": [0, 0.8], "type": float }, "axis_02": { "domain": "uniform", "data": [3.5, 6.5], "type": float } }, "max_iterations": 500 } project = HyppopyProject(config) solver = SolverPool.get("hyperopt", project) self.assertTrue(isinstance(solver, HyperoptSolver)) vfunc = FunctionSimulator() vfunc.load_default() solver.blackbox = vfunc solver.run(print_stats=False) df, best = solver.get_results() self.assertTrue(300 <= best['axis_00'] <= 700) self.assertTrue(0 <= best['axis_01'] <= 0.8) self.assertTrue(3.5 <= best['axis_02'] <= 6.5) for status in df['status']: self.assertTrue(status) for loss in df['losses']: self.assertTrue(isinstance(loss, float)) def test_getOptunitySolver(self): config = { "hyperparameter": { "axis_00": { "domain": "uniform", "data": [300, 800], "type": float }, "axis_01": { "domain": "uniform", "data": [-1, 1], "type": float }, "axis_02": { "domain": "uniform", "data": [0, 10], "type": float } }, "max_iterations": 100 } project = HyppopyProject(config) solver = SolverPool.get("optunity", project) self.assertTrue(isinstance(solver, OptunitySolver)) vfunc = FunctionSimulator() vfunc.load_default() solver.blackbox = vfunc solver.run(print_stats=False) df, best = solver.get_results() self.assertTrue(300 <= best['axis_00'] <= 800) self.assertTrue(-1 <= best['axis_01'] <= 1) self.assertTrue(0 <= best['axis_02'] <= 10) for status in df['status']: self.assertTrue(status) for loss in df['losses']: self.assertTrue(isinstance(loss, float)) def test_getOptunaSolver(self): config = { "hyperparameter": { "axis_00": { "domain": "uniform", "data": [300, 800], "type": float }, "axis_01": { "domain": "uniform", "data": [-1, 1], "type": float }, "axis_02": { "domain": "uniform", "data": [0, 10], "type": float } }, "max_iterations": 100 } project = HyppopyProject(config) solver = SolverPool.get("optuna", project) self.assertTrue(isinstance(solver, OptunaSolver)) vfunc = FunctionSimulator() vfunc.load_default() solver.blackbox = vfunc solver.run(print_stats=False) df, best = solver.get_results() self.assertTrue(300 <= best['axis_00'] <= 800) self.assertTrue(-1 <= best['axis_01'] <= 1) self.assertTrue(0 <= best['axis_02'] <= 10) for status in df['status']: self.assertTrue(status) for loss in df['losses']: self.assertTrue(isinstance(loss, float)) def test_getRandomsearchSolver(self): config = { "hyperparameter": { "axis_00": { "domain": "uniform", "data": [0, 800], "type": float }, "axis_01": { "domain": "uniform", "data": [-1, 1], "type": float }, "axis_02": { "domain": "uniform", "data": [0, 10], "type": float } }, "max_iterations": 300 } project = HyppopyProject(config) solver = SolverPool.get("randomsearch", project) self.assertTrue(isinstance(solver, RandomsearchSolver)) vfunc = FunctionSimulator() vfunc.load_default() solver.blackbox = vfunc solver.run(print_stats=False) df, best = solver.get_results() self.assertTrue(0 <= best['axis_00'] <= 800) self.assertTrue(-1 <= best['axis_01'] <= 1) self.assertTrue(0 <= best['axis_02'] <= 10) for status in df['status']: self.assertTrue(status) for loss in df['losses']: self.assertTrue(isinstance(loss, float)) def test_getQuasiRandomsearchSolver(self): config = { "hyperparameter": { "axis_00": { "domain": "uniform", "data": [0, 800], "type": float }, "axis_01": { "domain": "uniform", "data": [-1, 1], "type": float }, "axis_02": { "domain": "uniform", "data": [0, 10], "type": float } }, "max_iterations": 300 } project = HyppopyProject(config) solver = SolverPool.get("quasirandomsearch", project) self.assertTrue(isinstance(solver, QuasiRandomsearchSolver)) vfunc = FunctionSimulator() vfunc.load_default() solver.blackbox = vfunc solver.run(print_stats=False) df, best = solver.get_results() self.assertTrue(0 <= best['axis_00'] <= 800) self.assertTrue(-1 <= best['axis_01'] <= 1) self.assertTrue(0 <= best['axis_02'] <= 10) for status in df['status']: self.assertTrue(status) for loss in df['losses']: self.assertTrue(isinstance(loss, float)) def test_getGridsearchSolver(self): config = { "hyperparameter": { "value 1": { "domain": "uniform", "data": [0, 20], "type": int, "frequency": 11 }, "value 2": { "domain": "normal", "data": [0, 20.0], "type": float, "frequency": 11 }, "value 3": { "domain": "loguniform", "data": [1, 10000], "type": float, "frequency": 11 }, "categorical": { "domain": "categorical", "data": ["a", "b"], "type": str, "frequency": 1 } }} res_labels = ['value 1', 'value 2', 'value 3', 'categorical'] res_values = [[0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20], [0.0, 5.467452952462635, 8.663855974622837, 9.755510546899107, 9.973002039367397, 10.0, 10.026997960632603, 10.244489453100893, 11.336144025377163, 14.532547047537365, 20.0], [1.0, 2.51188643150958, 6.309573444801933, 15.848931924611136, 39.810717055349734, 100.00000000000004, 251.18864315095806, 630.9573444801938, 1584.8931924611143, 3981.071705534977, 10000.00000000001], ['a', 'b']] project = HyppopyProject(config) solver = SolverPool.get("gridsearch", project) self.assertTrue(isinstance(solver, GridsearchSolver)) searchspace = solver.convert_searchspace(config["hyperparameter"]) for n in range(len(res_labels)): self.assertEqual(res_labels[n], searchspace[0][n]) for i in range(3): self.assertAlmostEqual(res_values[i], searchspace[1][i]) self.assertEqual(res_values[3], searchspace[1][3]) def test_projectNone(self): solver = SolverPool.get("hyperopt") solver = SolverPool.get("optunity") solver = SolverPool.get("optuna") solver = SolverPool.get("randomsearch") solver = SolverPool.get("quasirandomsearch") solver = SolverPool.get("gridsearch") self.assertRaises(AssertionError, SolverPool.get, "foo")
python
"""Routines for performing spectral unmixing on earth engine images.""" import ee as _ee from tqdm import tqdm as _tqdm from .utils import selectSpectra as _selectSpectra # this function must be run before any of the specific unmixing routines are set def Initialize(sensor, n=30, bands=None): """Initializes sensor-specific global variables. Args: sensor: the name of the sensor (from earthlib.listSensors()). n: the number of iterations for unmixing. bands: a list of bands to select (from earthlib.getBands(sensor)). Returns: None: creates a series of global endmember variables. """ # get them as a python array pv_list = _selectSpectra("vegetation", sensor, n, bands) npv_list = _selectSpectra("npv", sensor, n, bands) soil_list = _selectSpectra("bare", sensor, n, bands) burn_list = _selectSpectra("burn", sensor, n, bands) urban_list = _selectSpectra("urban", sensor, n, bands) # create a series of global variables for later global pv global npv global soil global burn global urban # then convert them to ee lists pv = [_ee.List(pv_spectra.tolist()) for pv_spectra in pv_list] npv = [_ee.List(npv_spectra.tolist()) for npv_spectra in npv_list] soil = [_ee.List(soil_spectra.tolist()) for soil_spectra in soil_list] burn = [_ee.List(burn_spectra.tolist()) for burn_spectra in burn_list] urban = [_ee.List(urban_spectra.tolist()) for urban_spectra in urban_list] def fractionalCover( img, endmembers, endmember_names, shade_normalize=True, ): """Computes the percent cover of each endmember spectra. Args: img: the ee.Image to unmix. endmembers: lists of ee.List objects, each element corresponding to a sub. endmember_names: list of names for each endmember. must match the number of lists passed. shade_normalize: flag to apply shade normalization during unmixing. Returns: unmixed: a 3-band image file in order of (soil-veg-impervious). """ n_bands = len(list(img.bandNames().getInfo())) n_classes = len(endmembers) n_endmembers = len(endmembers[0]) band_numbers = list(range(n_classes)) shade = _ee.List([0] * n_bands) # create a list of images to append and later convert to an image collection unmixed = list() # loop through each iteration and unmix each for spectra in _tqdm(list(zip(*endmembers)), total=n_endmembers, desc="Unmixing"): if shade_normalize: spectra += (shade,) unmixed_iter = img.unmix(spectra, True, True).toFloat() # run the forward model to evaluate the fractional cover fit modeled_reflectance = computeModeledSpectra(spectra, unmixed_iter) rmse = computeSpectralRMSE(img, modeled_reflectance) # normalize by the observed shade fraction if shade_normalize: shade_fraction = unmixed_iter.select([n_classes]).subtract(1).abs() unmixed_iter = unmixed_iter.divide(shade_fraction) # rename the bands and append an rmse band unmixed.append( unmixed_iter.select(band_numbers, endmember_names).addBands(rmse) ) # use the sum of rmse to weight each estimate rmse_sum = _ee.Image( _ee.ImageCollection.fromImages(unmixed) .select(["RMSE"]) .sum() .select([0], ["SUM"]) .toFloat() ) unscaled = [computeWeight(fractions, rmse_sum) for fractions in unmixed] # use these weights to scale each unmixing estimate weight_sum = _ee.Image( _ee.ImageCollection.fromImages(unscaled).select(["weight"]).sum().toFloat() ) scaled = [weightedAverage(fractions, weight_sum) for fractions in unscaled] # reduce it to a single image and return unmixed = _ee.ImageCollection.fromImages(scaled).sum().toFloat() return unmixed def computeModeledSpectra(endmembers, fractions): """Constructs a modeled spectrum for each pixel based on endmember fractions. Args: endmembers: a list of _ee.List() items, each representing an endmember spectrum. fractions: ee.Image output from .unmix() with the same number of bands as items in `endmembers`. Returns: modeled_reflectance: an _ee.Image with n_bands equal to the number of endmember bands. """ # compute the number of endmember bands nb = int(endmembers[0].length().getInfo()) band_range = list(range(nb)) band_names = [f"M{band:02d}" for band in band_range] # create a list to store each reflectance fraction refl_fraction_images = list() # loop through each endmember and mulitply the fraction estimated by the reflectance value for i, endmember in enumerate(endmembers): fraction = fractions.select([i]) refl_fraction_list = [ fraction.multiply(_ee.Image(endmember.get(band).getInfo())) for band in band_range ] refl_fraction_images.append( _ee.ImageCollection.fromImages(refl_fraction_list) .toBands() .select(band_range, band_names) ) # convert these images to an image collection and sum them together to reconstruct the spectrum modeled_reflectance = ( _ee.ImageCollection.fromImages(refl_fraction_images) .sum() .toFloat() .select(band_range, band_names) ) return modeled_reflectance def computeSpectralRMSE(measured, modeled): """Computes root mean squared error between measured and modeled spectra. Args: measured: an ee.Image of measured reflectance. modeled: an ee.Image of modeled reflectance. Returns: rmse: a floating point _ee.Image with pixel-wise RMSE values. """ # harmonize band info to ensure element-wise computation band_names = list(measured.bandNames().getInfo()) band_range = list(range(len(band_names))) # compute rmse rmse = ( measured.select(band_range, band_names) .subtract(modeled.select(band_range, band_names)) .pow(2) .reduce(_ee.Reducer.sum()) .sqrt() .select([0], ["RMSE"]) .toFloat() ) return rmse def computeWeight(fractions, rmse_sum): """Computes the relative weight for an image's RMSE based on the sum of the global RMSE. Args: fractions: a multi-band ee.Image object with an 'RMSE' band. rmse_sum: a single-band ee.Image object with the global RMSE value. Returns: unweighted: appends the fractions Image with a 'weight' band. """ rmse = fractions.select(["RMSE"]) ratio = rmse.divide(rmse_sum).toFloat().select([0], ["ratio"]) weight = _ee.Image(1).subtract(ratio).select([0], ["weight"]) unweighted = fractions.addBands([weight, ratio]) return unweighted def weightedAverage(fractions, weight_sum): """Computes an RMSE-weighted fractional cover image. Args: fractions: a multi-band ee.Image object with a 'weight' band. weight_sum: a single-band _eeImage object with the global weight sum. Returns: weighted: scaled fractional cover Image. """ # harmonize band info band_names = list(fractions.bandNames().getInfo()) band_names.pop(band_names.index("weight")) band_range = list(range(len(band_names))) scaler = fractions.select(["weight"]).divide(weight_sum) weighted = fractions.select(band_range, band_names).multiply(scaler) return weighted def VIS(img, **normalization): """Unmixes according to the Vegetation-Impervious-Soil (VIS) approach. Args: img: the ee.Image to unmix. **normalization: keyword arguments to pass to fractionalCover(), like shade_normalize=True. Returns: unmixed: a 3-band image file in order of (soil-veg-impervious). """ endmembers = [soil, pv, urban] endmember_names = ["soil", "pv", "impervious"] unmixed = fractionalCover(img, endmembers, endmember_names, **normalization) return unmixed def SVN(img, **normalization): """Unmixes using Soil-Vegetation-NonphotosyntheticVegetation (SVN) endmembers. Args: img: the ee.Image to unmix. **normalization: keyword arguments to pass to fractionalCover(), like shade_normalize=True. Returns: unmixed: a 3-band image file in order of (soil-veg-npv). """ endmembers = [soil, pv, npv] endmember_names = ["soil", "pv", "npv"] unmixed = fractionalCover(img, endmembers, endmember_names, **normalization) return unmixed def BVN(img, **normalization): """Unmixes using Burned-Vegetation-NonphotosyntheticVegetation (BVN) endmembers. Args: img: the ee.Image to unmix. **normalization: keyword arguments to pass to fractionalCover(), like shade_normalize=True. Returns: unmixed: a 4-band image file in order of (burned-veg-npv-soil). """ endmembers = [burn, pv, npv] endmember_names = ["burned", "pv", "npv"] unmixed = fractionalCover(img, endmembers, endmember_names, **normalization) return unmixed
python
from builtins import * import numpy as np import scipy.linalg from scipy.special import gammaln, digamma from bnpy.suffstats import ParamBag, SuffStatBag from bnpy.util import LOGTWO, LOGPI, LOGTWOPI, EPS from bnpy.util import dotATA, dotATB, dotABT from bnpy.util import as1D, as2D, as3D, toCArray from bnpy.util import numpyToSharedMemArray, fillSharedMemArray from bnpy.util.SparseRespStatsUtil import calcSpRXXT from .AbstractObsModel import AbstractObsModel class GaussObsModel(AbstractObsModel): """ Full-covariance gaussian data generation model for real vectors. Attributes for Prior (Normal-Wishart) -------- nu : float degrees of freedom B : 2D array, size D x D scale parameters that set mean of parameter sigma m : 1D array, size D mean of the parameter mu kappa : float scalar precision on parameter mu Attributes for k-th component of EstParams (EM point estimates) --------- mu[k] : 1D array, size D Sigma[k] : 2D array, size DxD Attributes for k-th component of Post (VB parameter) --------- nu[k] : float B[k] : 1D array, size D m[k] : 1D array, size D kappa[k] : float """ def __init__(self, inferType='EM', D=0, min_covar=None, Data=None, **PriorArgs): ''' Initialize bare obsmodel with valid prior hyperparameters. Resulting object lacks either EstParams or Post, which must be created separately (see init_global_params). ''' if Data is not None: self.D = Data.dim else: self.D = int(D) self.K = 0 self.inferType = inferType self.min_covar = min_covar self.createPrior(Data, **PriorArgs) self.Cache = dict() def createPrior(self, Data, nu=0, B=None, m=None, kappa=None, MMat='zero', ECovMat=None, sF=1.0, **kwargs): ''' Initialize Prior ParamBag attribute. Post Condition ------ Prior expected covariance matrix set to match provided value. ''' D = self.D nu = np.maximum(nu, D + 2) if B is None: if ECovMat is None or isinstance(ECovMat, str): ECovMat = createECovMatFromUserInput(D, Data, ECovMat, sF) B = ECovMat * (nu - D - 1) if B.ndim == 1: B = np.asarray([B], dtype=np.float) elif B.ndim == 0: B = np.asarray([[B]], dtype=np.float) if m is None: if MMat == 'data': m = np.mean(Data.X, axis=0) else: m = np.zeros(D) elif m.ndim < 1: m = np.asarray([m], dtype=np.float) if kappa is None: kappa = 1e-8 else: kappa = np.maximum(kappa, 1e-8) self.Prior = ParamBag(K=0, D=D) self.Prior.setField('nu', nu, dims=None) self.Prior.setField('kappa', kappa, dims=None) self.Prior.setField('m', m, dims=('D')) self.Prior.setField('B', B, dims=('D', 'D')) def get_mean_for_comp(self, k=None): if hasattr(self, 'EstParams'): return self.EstParams.mu[k] elif k is None or k == 'prior': return self.Prior.m else: return self.Post.m[k] def get_covar_mat_for_comp(self, k=None): if hasattr(self, 'EstParams'): return self.EstParams.Sigma[k] elif k is None or k == 'prior': return self._E_CovMat() else: return self._E_CovMat(k) def get_name(self): return 'Gauss' def get_info_string(self): return 'Gaussian with full covariance.' def get_info_string_prior(self): msg = 'Gauss-Wishart on mean and covar of each cluster\n' if self.D > 2: sfx = ' ...' else: sfx = '' S = self._E_CovMat()[:2, :2] msg += 'E[ mean[k] ] = \n %s %s\n' % (str(self.Prior.m[:2]), sfx) msg += 'E[ covar[k] ] = \n' msg += str(S) + sfx msg = msg.replace('\n', '\n ') return msg def setEstParams(self, obsModel=None, SS=None, LP=None, Data=None, mu=None, Sigma=None, **kwargs): ''' Create EstParams ParamBag with fields mu, Sigma ''' self.ClearCache() if obsModel is not None: self.EstParams = obsModel.EstParams.copy() self.K = self.EstParams.K return if LP is not None and Data is not None: SS = self.calcSummaryStats(Data, None, LP) if SS is not None: self.updateEstParams(SS) else: Sigma = as3D(Sigma) K, D, D2 = Sigma.shape mu = as2D(mu) if mu.shape[0] != K: mu = mu.T assert mu.shape[0] == K assert mu.shape[1] == D self.EstParams = ParamBag(K=K, D=D) self.EstParams.setField('mu', mu, dims=('K', 'D')) self.EstParams.setField('Sigma', Sigma, dims=('K', 'D', 'D')) self.K = self.EstParams.K def setEstParamsFromPost(self, Post): ''' Convert from Post (nu, B, m, kappa) to EstParams (mu, Sigma), each EstParam is set to its posterior mean. ''' self.EstParams = ParamBag(K=Post.K, D=Post.D) mu = Post.m.copy() Sigma = Post.B / (Post.nu[:, np.newaxis, np.newaxis] - Post.D - 1) self.EstParams.setField('mu', mu, dims=('K', 'D')) self.EstParams.setField('Sigma', Sigma, dims=('K', 'D', 'D')) self.K = self.EstParams.K def setPostFactors(self, obsModel=None, SS=None, LP=None, Data=None, nu=0, B=0, m=0, kappa=0, **kwargs): ''' Set attribute Post to provided values. ''' self.ClearCache() if obsModel is not None: if hasattr(obsModel, 'Post'): self.Post = obsModel.Post.copy() self.K = self.Post.K else: self.setPostFromEstParams(obsModel.EstParams) return if LP is not None and Data is not None: SS = self.calcSummaryStats(Data, None, LP) if SS is not None: self.updatePost(SS) else: m = as2D(m) if m.shape[1] != self.D: m = m.T.copy() K, _ = m.shape self.Post = ParamBag(K=K, D=self.D) self.Post.setField('nu', as1D(nu), dims=('K')) self.Post.setField('B', B, dims=('K', 'D', 'D')) self.Post.setField('m', m, dims=('K', 'D')) self.Post.setField('kappa', as1D(kappa), dims=('K')) self.K = self.Post.K def setPostFromEstParams(self, EstParams, Data=None, N=None): ''' Set attribute Post based on values in EstParams. ''' K = EstParams.K D = EstParams.D if Data is not None: N = Data.nObsTotal N = np.asarray(N, dtype=np.float) if N.ndim == 0: N = N / K * np.ones(K) nu = self.Prior.nu + N B = np.zeros((K, D, D)) for k in range(K): B[k] = (nu[k] - D - 1) * EstParams.Sigma[k] m = EstParams.mu.copy() kappa = self.Prior.kappa + N self.Post = ParamBag(K=K, D=D) self.Post.setField('nu', nu, dims=('K')) self.Post.setField('B', B, dims=('K', 'D', 'D')) self.Post.setField('m', m, dims=('K', 'D')) self.Post.setField('kappa', kappa, dims=('K')) self.K = self.Post.K def calcSummaryStats(self, Data, SS, LP, **kwargs): ''' Calculate summary statistics for given dataset and local parameters Returns -------- SS : SuffStatBag object, with K components. ''' return calcSummaryStats(Data, SS, LP, **kwargs) def forceSSInBounds(self, SS): ''' Force count vector N to remain positive This avoids numerical problems due to incremental add/subtract ops which can cause computations like x = 10. x += 1e-15 x -= 10 x -= 1e-15 to be slightly different than zero instead of exactly zero. Returns ------- None. SS.N updated in-place. ''' np.maximum(SS.N, 0, out=SS.N) def incrementSS(self, SS, k, x): SS.x[k] += x SS.xxT[k] += np.outer(x, x) def decrementSS(self, SS, k, x): SS.x[k] -= x SS.xxT[k] -= np.outer(x, x) def calcSummaryStatsForContigBlock(self, Data, SS=None, a=0, b=0): ''' Calculate sufficient stats for a single contiguous block of data ''' if SS is None: SS = SuffStatBag(K=1, D=Data.dim) SS.setField('N', (b - a) * np.ones(1), dims='K') SS.setField( 'x', np.sum(Data.X[a:b], axis=0)[np.newaxis, :], dims=('K', 'D')) SS.setField( 'xxT', dotATA(Data.X[a:b])[np.newaxis, :, :], dims=('K', 'D', 'D')) return SS def calcLogSoftEvMatrix_FromEstParams(self, Data, **kwargs): ''' Compute log soft evidence matrix for Dataset under EstParams. Returns --------- L : 2D array, N x K ''' K = self.EstParams.K L = np.empty((Data.nObs, K)) for k in range(K): L[:, k] = - 0.5 * self.D * LOGTWOPI \ - 0.5 * self._logdetSigma(k) \ - 0.5 * self._mahalDist_EstParam(Data.X, k) return L def _mahalDist_EstParam(self, X, k): ''' Calc Mahalanobis distance from comp k to every row of X Args --------- X : 2D array, size N x D k : integer ID of comp Returns ---------- dist : 1D array, size N ''' Q = np.linalg.solve(self.GetCached('cholSigma', k), (X - self.EstParams.mu[k]).T) Q *= Q return np.sum(Q, axis=0) def _cholSigma(self, k): ''' Calculate lower cholesky decomposition of Sigma[k] Returns -------- L : 2D array, size D x D, lower triangular Sigma = np.dot(L, L.T) ''' return scipy.linalg.cholesky(self.EstParams.Sigma[k], lower=1) def _logdetSigma(self, k): ''' Calculate log determinant of EstParam.Sigma for comp k Returns --------- logdet : scalar real ''' return 2 * np.sum(np.log(np.diag(self.GetCached('cholSigma', k)))) def updateEstParams_MaxLik(self, SS): ''' Update attribute EstParams for all comps given suff stats. Update uses the maximum likelihood objective for point estimation. Post Condition --------- Attributes K and EstParams updated in-place. ''' self.ClearCache() if not hasattr(self, 'EstParams') or self.EstParams.K != SS.K: self.EstParams = ParamBag(K=SS.K, D=SS.D) mu = SS.x / SS.N[:, np.newaxis] minCovMat = self.min_covar * np.eye(SS.D) covMat = np.tile(minCovMat, (SS.K, 1, 1)) for k in range(SS.K): covMat[k] += SS.xxT[k] / SS.N[k] - np.outer(mu[k], mu[k]) self.EstParams.setField('mu', mu, dims=('K', 'D')) self.EstParams.setField('Sigma', covMat, dims=('K', 'D', 'D')) self.K = SS.K def updateEstParams_MAP(self, SS): ''' Update attribute EstParams for all comps given suff stats. Update uses the MAP objective for point estimation. Post Condition --------- Attributes K and EstParams updated in-place. ''' self.ClearCache() if not hasattr(self, 'EstParams') or self.EstParams.K != SS.K: self.EstParams = ParamBag(K=SS.K, D=SS.D) Prior = self.Prior nu = Prior.nu + SS.N kappa = Prior.kappa + SS.N PB = Prior.B + Prior.kappa * np.outer(Prior.m, Prior.m) m = np.empty((SS.K, SS.D)) B = np.empty((SS.K, SS.D, SS.D)) for k in range(SS.K): km_x = Prior.kappa * Prior.m + SS.x[k] m[k] = 1.0 / kappa[k] * km_x B[k] = PB + SS.xxT[k] - 1.0 / kappa[k] * np.outer(km_x, km_x) mu, Sigma = MAPEstParams_inplace(nu, B, m, kappa) self.EstParams.setField('mu', mu, dims=('K', 'D')) self.EstParams.setField('Sigma', Sigma, dims=('K', 'D', 'D')) self.K = SS.K def updatePost(self, SS): ''' Update attribute Post for all comps given suff stats. Update uses the variational objective. Post Condition --------- Attributes K and Post updated in-place. ''' self.ClearCache() if not hasattr(self, 'Post') or self.Post.K != SS.K: self.Post = ParamBag(K=SS.K, D=SS.D) nu, B, m, kappa = self.calcPostParams(SS) self.Post.setField('nu', nu, dims=('K')) self.Post.setField('kappa', kappa, dims=('K')) self.Post.setField('m', m, dims=('K', 'D')) self.Post.setField('B', B, dims=('K', 'D', 'D')) self.K = SS.K def calcPostParams(self, SS): ''' Calc updated params (nu, B, m, kappa) for all comps given suff stats These params define the common-form of the exponential family Normal-Wishart posterior distribution over mu, diag(Lambda) Returns -------- nu : 1D array, size K B : 3D array, size K x D x D, each B[k] is symmetric and pos. def. m : 2D array, size K x D kappa : 1D array, size K ''' Prior = self.Prior nu = Prior.nu + SS.N kappa = Prior.kappa + SS.N m = (Prior.kappa * Prior.m + SS.x) / kappa[:, np.newaxis] Bmm = Prior.B + Prior.kappa * np.outer(Prior.m, Prior.m) B = SS.xxT + Bmm[np.newaxis, :] for k in range(B.shape[0]): B[k] -= kappa[k] * np.outer(m[k], m[k]) return nu, B, m, kappa def calcPostParamsForComp(self, SS, kA=None, kB=None): ''' Calc params (nu, B, m, kappa) for specific comp, given suff stats These params define the common-form of the exponential family Normal-Wishart posterior distribution over mu[k], diag(Lambda)[k] Returns -------- nu : positive scalar B : 2D array, size D x D, symmetric and positive definite m : 1D array, size D kappa : positive scalar ''' if kB is None: SN = SS.N[kA] Sx = SS.x[kA] SxxT = SS.xxT[kA] else: SN = SS.N[kA] + SS.N[kB] Sx = SS.x[kA] + SS.x[kB] SxxT = SS.xxT[kA] + SS.xxT[kB] Prior = self.Prior nu = Prior.nu + SN kappa = Prior.kappa + SN m = (Prior.kappa * Prior.m + Sx) / kappa B = Prior.B + SxxT \ + Prior.kappa * np.outer(Prior.m, Prior.m) \ - kappa * np.outer(m, m) return nu, B, m, kappa def updatePost_stochastic(self, SS, rho): ''' Update attribute Post for all comps given suff stats Update uses the stochastic variational formula. Post Condition --------- Attributes K and Post updated in-place. ''' assert hasattr(self, 'Post') assert self.Post.K == SS.K self.ClearCache() self.convertPostToNatural() nu, Bnat, km, kappa = self.calcNaturalPostParams(SS) Post = self.Post Post.nu[:] = (1 - rho) * Post.nu + rho * nu Post.Bnat[:] = (1 - rho) * Post.Bnat + rho * Bnat Post.km[:] = (1 - rho) * Post.km + rho * km Post.kappa[:] = (1 - rho) * Post.kappa + rho * kappa self.convertPostToCommon() def calcNaturalPostParams(self, SS): ''' Calc natural posterior parameters given suff stats SS. Returns -------- nu : 1D array, size K Bnat : 3D array, size K x D x D km : 2D array, size K x D kappa : 1D array, size K ''' Prior = self.Prior nu = Prior.nu + SS.N kappa = Prior.kappa + SS.N km = Prior.kappa * Prior.m + SS.x Bnat = (Prior.B + Prior.kappa * np.outer(Prior.m, Prior.m)) + SS.xxT return nu, Bnat, km, kappa def convertPostToNatural(self): ''' Convert current posterior params from common to natural form ''' Post = self.Post assert hasattr(Post, 'nu') assert hasattr(Post, 'kappa') km = Post.m * Post.kappa[:, np.newaxis] Bnat = np.empty((self.K, self.D, self.D)) for k in range(self.K): Bnat[k] = Post.B[k] + np.outer(km[k], km[k]) / Post.kappa[k] Post.setField('km', km, dims=('K', 'D')) Post.setField('Bnat', Bnat, dims=('K', 'D', 'D')) def convertPostToCommon(self): ''' Convert current posterior params from natural to common form ''' Post = self.Post assert hasattr(Post, 'nu') assert hasattr(Post, 'kappa') if hasattr(Post, 'm'): Post.m[:] = Post.km / Post.kappa[:, np.newaxis] else: m = Post.km / Post.kappa[:, np.newaxis] Post.setField('m', m, dims=('K', 'D')) if hasattr(Post, 'B'): B = Post.B # update in place, no reallocation! else: B = np.empty((self.K, self.D, self.D)) for k in range(self.K): B[k] = Post.Bnat[k] - \ np.outer(Post.km[k], Post.km[k]) / Post.kappa[k] Post.setField('B', B, dims=('K', 'D', 'D')) def calcLogSoftEvMatrix_FromPost(self, Data, **kwargs): ''' Calculate expected log soft ev matrix under Post. Returns ------ L : 2D array, size N x K ''' K = self.Post.K L = np.zeros((Data.nObs, K)) for k in range(K): L[:, k] = - 0.5 * self.D * LOGTWOPI \ + 0.5 * self.GetCached('E_logdetL', k) \ - 0.5 * self._mahalDist_Post(Data.X, k) return L def _mahalDist_Post(self, X, k): ''' Calc expected mahalonobis distance from comp k to each data atom Returns -------- distvec : 1D array, size nObs distvec[n] gives E[ (x-\mu) \Lam (x-\mu) ] for comp k ''' Q = np.linalg.solve(self.GetCached('cholB', k), (X - self.Post.m[k]).T) Q *= Q return self.Post.nu[k] * np.sum(Q, axis=0) \ + self.D / self.Post.kappa[k] def calcELBO_Memoized(self, SS, returnVec=0, afterMStep=False, **kwargs): """ Calculate obsModel's objective using suff stats SS and Post. Args ------- SS : bnpy SuffStatBag afterMStep : boolean flag if 1, elbo calculated assuming M-step just completed Returns ------- obsELBO : scalar float Equal to E[ log p(x) + log p(phi) - log q(phi)] """ elbo = np.zeros(SS.K) Post = self.Post Prior = self.Prior for k in range(SS.K): elbo[k] = c_Diff(Prior.nu, self.GetCached('logdetB'), Prior.m, Prior.kappa, Post.nu[k], self.GetCached('logdetB', k), Post.m[k], Post.kappa[k], ) if not afterMStep: aDiff = SS.N[k] + Prior.nu - Post.nu[k] bDiff = SS.xxT[k] + Prior.B \ + Prior.kappa * np.outer(Prior.m, Prior.m) \ - Post.B[k] \ - Post.kappa[k] * np.outer(Post.m[k], Post.m[k]) cDiff = SS.x[k] + Prior.kappa * Prior.m \ - Post.kappa[k] * Post.m[k] dDiff = SS.N[k] + Prior.kappa - Post.kappa[k] elbo[k] += 0.5 * aDiff * self.GetCached('E_logdetL', k) \ - 0.5 * self._trace__E_L(bDiff, k) \ + np.inner(cDiff, self.GetCached('E_Lmu', k)) \ - 0.5 * dDiff * self.GetCached('E_muLmu', k) if returnVec: return elbo - (0.5 * SS.D * LOGTWOPI) * SS.N return elbo.sum() - 0.5 * np.sum(SS.N) * SS.D * LOGTWOPI def getDatasetScale(self, SS): ''' Get number of observed scalars in dataset from suff stats. Used for normalizing the ELBO so it has reasonable range. Returns --------- s : scalar positive integer ''' return SS.N.sum() * SS.D def calcHardMergeGap(self, SS, kA, kB): ''' Calculate change in ELBO after a hard merge applied to this model Returns --------- gap : scalar real, indicates change in ELBO after merge of kA, kB ''' Post = self.Post Prior = self.Prior cA = c_Func(Post.nu[kA], Post.B[kA], Post.m[kA], Post.kappa[kA]) cB = c_Func(Post.nu[kB], Post.B[kB], Post.m[kB], Post.kappa[kB]) cPrior = c_Func(Prior.nu, Prior.B, Prior.m, Prior.kappa) nu, B, m, kappa = self.calcPostParamsForComp(SS, kA, kB) cAB = c_Func(nu, B, m, kappa) return cA + cB - cPrior - cAB def calcHardMergeGap_AllPairs(self, SS): ''' Calculate change in ELBO for all candidate hard merge pairs Returns --------- Gap : 2D array, size K x K, upper-triangular entries non-zero Gap[j,k] : scalar change in ELBO after merge of k into j ''' Post = self.Post Prior = self.Prior cPrior = c_Func(Prior.nu, Prior.B, Prior.m, Prior.kappa) c = np.zeros(SS.K) for k in range(SS.K): c[k] = c_Func(Post.nu[k], Post.B[k], Post.m[k], Post.kappa[k]) Gap = np.zeros((SS.K, SS.K)) for j in range(SS.K): for k in range(j + 1, SS.K): nu, B, m, kappa = self.calcPostParamsForComp(SS, j, k) cjk = c_Func(nu, B, m, kappa) Gap[j, k] = c[j] + c[k] - cPrior - cjk return Gap def calcHardMergeGap_SpecificPairs(self, SS, PairList): ''' Calc change in ELBO for specific list of candidate hard merge pairs Returns --------- Gaps : 1D array, size L Gap[j] : scalar change in ELBO after merge of pair in PairList[j] ''' Gaps = np.zeros(len(PairList)) for ii, (kA, kB) in enumerate(PairList): Gaps[ii] = self.calcHardMergeGap(SS, kA, kB) return Gaps def calcHardMergeGap_SpecificPairSS(self, SS1, SS2): ''' Calc change in ELBO for merge of two K=1 suff stat bags. Returns ------- gap : scalar float ''' assert SS1.K == 1 assert SS2.K == 1 Prior = self.Prior cPrior = c_Func(Prior.nu, Prior.B, Prior.m, Prior.kappa) # Compute cumulants of individual states 1 and 2 nu1, B1, m1, kappa1 = self.calcPostParamsForComp(SS1, 0) nu2, B2, m2, kappa2 = self.calcPostParamsForComp(SS2, 0) c1 = c_Func(nu1, B1, m1, kappa1) c2 = c_Func(nu2, B2, m2, kappa2) # Compute cumulant of merged state 1&2 SS12 = SS1 + SS2 nu12, B12, m12, kappa12 = self.calcPostParamsForComp(SS12, 0) c12 = c_Func(nu12, B12, m12, kappa12) return c1 + c2 - cPrior - c12 def calcLogMargLikForComp(self, SS, kA, kB=None, **kwargs): ''' Calc log marginal likelihood of data assigned to given component Args ------- SS : bnpy suff stats object kA : integer ID of target component to compute likelihood for kB : (optional) integer ID of second component. If provided, we merge kA, kB into one component for calculation. Returns ------- logM : scalar real logM = log p( data assigned to comp kA ) computed up to an additive constant ''' nu, beta, m, kappa = self.calcPostParamsForComp(SS, kA, kB) return -1 * c_Func(nu, beta, m, kappa) def calcMargLik(self, SS): ''' Calc log marginal likelihood across all comps, given suff stats Returns -------- logM : scalar real logM = \sum_{k=1}^K log p( data assigned to comp k | Prior) ''' return self.calcMargLik_CFuncForLoop(SS) def calcMargLik_CFuncForLoop(self, SS): Prior = self.Prior logp = np.zeros(SS.K) for k in range(SS.K): nu, B, m, kappa = self.calcPostParamsForComp(SS, k) logp[k] = c_Diff(Prior.nu, Prior.B, Prior.m, Prior.kappa, nu, B, m, kappa) return np.sum(logp) - 0.5 * np.sum(SS.N) * LOGTWOPI def calcPredProbVec_Unnorm(self, SS, x): ''' Calculate predictive probability that each comp assigns to vector x Returns -------- p : 1D array, size K, all entries positive p[k] \propto p( x | SS for comp k) ''' return self._calcPredProbVec_Fast(SS, x) def _calcPredProbVec_cFunc(self, SS, x): nu, B, m, kappa = self.calcPostParams(SS) pSS = SS.copy() pSS.N += 1 pSS.x += x[np.newaxis, :] pSS.xxT += np.outer(x, x)[np.newaxis, :, :] pnu, pB, pm, pkappa = self.calcPostParams(pSS) logp = np.zeros(SS.K) for k in range(SS.K): logp[k] = c_Diff(nu[k], B[k], m[k], kappa[k], pnu[k], pB[k], pm[k], pkappa[k]) return np.exp(logp - np.max(logp)) def _calcPredProbVec_Fast(self, SS, x): nu, B, m, kappa = self.calcPostParams(SS) kB = B kB *= ((kappa + 1) / kappa)[:, np.newaxis, np.newaxis] logp = np.zeros(SS.K) p = logp # Rename so its not confusing what we're returning for k in range(SS.K): cholKB = scipy.linalg.cholesky(kB[k], lower=1) logdetKB = 2 * np.sum(np.log(np.diag(cholKB))) mVec = np.linalg.solve(cholKB, x - m[k]) mDist_k = np.inner(mVec, mVec) logp[k] = -0.5 * logdetKB - 0.5 * \ (nu[k] + 1) * np.log(1.0 + mDist_k) logp += gammaln(0.5 * (nu + 1)) - gammaln(0.5 * (nu + 1 - self.D)) logp -= np.max(logp) np.exp(logp, out=p) return p def _Verify_calcPredProbVec(self, SS, x): ''' Verify that the predictive prob vector is correct, by comparing very different implementations ''' pA = self._calcPredProbVec_Fast(SS, x) pC = self._calcPredProbVec_cFunc(SS, x) pA /= np.sum(pA) pC /= np.sum(pC) assert np.allclose(pA, pC) def _E_CovMat(self, k=None): if k is None: B = self.Prior.B nu = self.Prior.nu else: B = self.Post.B[k] nu = self.Post.nu[k] return B / (nu - self.D - 1) def _cholB(self, k=None): if k == 'all': retArr = np.zeros((self.K, self.D, self.D)) for kk in range(self.K): retArr[kk] = self.GetCached('cholB', kk) return retArr elif k is None: B = self.Prior.B else: # k is one of [0, 1, ... K-1] B = self.Post.B[k] return scipy.linalg.cholesky(B, lower=True) def _logdetB(self, k=None): cholB = self.GetCached('cholB', k) return 2 * np.sum(np.log(np.diag(cholB))) def _E_logdetL(self, k=None): dvec = np.arange(1, self.D + 1, dtype=np.float) if k == 'all': dvec = dvec[:, np.newaxis] retVec = self.D * LOGTWO * np.ones(self.K) for kk in range(self.K): retVec[kk] -= self.GetCached('logdetB', kk) nuT = self.Post.nu[np.newaxis, :] retVec += np.sum(digamma(0.5 * (nuT + 1 - dvec)), axis=0) return retVec elif k is None: nu = self.Prior.nu else: nu = self.Post.nu[k] return self.D * LOGTWO \ - self.GetCached('logdetB', k) \ + np.sum(digamma(0.5 * (nu + 1 - dvec))) def _trace__E_L(self, Smat, k=None): if k is None: nu = self.Prior.nu B = self.Prior.B else: nu = self.Post.nu[k] B = self.Post.B[k] return nu * np.trace(np.linalg.solve(B, Smat)) def _E_Lmu(self, k=None): if k is None: nu = self.Prior.nu B = self.Prior.B m = self.Prior.m else: nu = self.Post.nu[k] B = self.Post.B[k] m = self.Post.m[k] return nu * np.linalg.solve(B, m) def _E_muLmu(self, k=None): if k is None: nu = self.Prior.nu kappa = self.Prior.kappa m = self.Prior.m B = self.Prior.B else: nu = self.Post.nu[k] kappa = self.Post.kappa[k] m = self.Post.m[k] B = self.Post.B[k] Q = np.linalg.solve(self.GetCached('cholB', k), m.T) return self.D / kappa + nu * np.inner(Q, Q) def getSerializableParamsForLocalStep(self): """ Get compact dict of params for local step. Returns ------- Info : dict """ if self.inferType == 'EM': raise NotImplementedError('TODO') return dict(inferType=self.inferType, K=self.K, D=self.D, ) def fillSharedMemDictForLocalStep(self, ShMem=None): """ Get dict of shared mem arrays needed for parallel local step. Returns ------- ShMem : dict of RawArray objects """ if ShMem is None: ShMem = dict() if 'nu' in ShMem: fillSharedMemArray(ShMem['nu'], self.Post.nu) fillSharedMemArray(ShMem['kappa'], self.Post.kappa) fillSharedMemArray(ShMem['m'], self.Post.m) fillSharedMemArray(ShMem['cholB'], self._cholB('all')) fillSharedMemArray(ShMem['E_logdetL'], self._E_logdetL('all')) else: ShMem['nu'] = numpyToSharedMemArray(self.Post.nu) ShMem['kappa'] = numpyToSharedMemArray(self.Post.kappa) ShMem['m'] = numpyToSharedMemArray(self.Post.m.copy()) ShMem['cholB'] = numpyToSharedMemArray(self._cholB('all')) ShMem['E_logdetL'] = numpyToSharedMemArray(self._E_logdetL('all')) return ShMem def getLocalAndSummaryFunctionHandles(self): """ Get function handles for local step and summary step Useful for parallelized algorithms. Returns ------- calcLocalParams : f handle calcSummaryStats : f handle """ return calcLocalParams, calcSummaryStats def calcSmoothedMu(self, X, W=None): ''' Compute smoothed estimate of mean of statistic xxT. Args ---- X : 2D array, size N x D Returns ------- Mu_1 : 2D array, size D x D Expected value of Cov[ X[n] ] Mu_2 : 1D array, size D Expected value of Mean[ X[n] ] ''' if X is None: Mu1 = self.Prior.B / self.Prior.nu Mu2 = self.Prior.m return Mu1, Mu2 if X.ndim == 1: X = X[np.newaxis,:] N, D = X.shape # Compute suff stats if W is None: sum_wxxT = np.dot(X.T, X) sum_wx = np.sum(X, axis=0) sum_w = X.shape[0] else: W = as1D(W) sqrtWX = np.sqrt(W)[:,np.newaxis] * X sum_wxxT = np.dot(sqrtWX.T, sqrtWX) sum_wx = np.dot(W, X) sum_w = np.sum(W) kappa = self.Prior.kappa + sum_w m = (self.Prior.m * self.Prior.kappa + sum_wx) / kappa Mu_2 = m prior_kmmT = self.Prior.kappa * np.outer(self.Prior.m, self.Prior.m) post_kmmT = kappa * np.outer(m,m) B = sum_wxxT + self.Prior.B + prior_kmmT - post_kmmT Mu_1 = B / (self.Prior.nu + sum_w) assert Mu_1.ndim == 2 assert Mu_1.shape == (D, D,) assert Mu_2.shape == (D,) return Mu_1, Mu_2 def calcSmoothedBregDiv( self, X, Mu, W=None, eps=1e-10, smoothFrac=0.0, includeOnlyFastTerms=False, DivDataVec=None, returnDivDataVec=False, return1D=False, **kwargs): ''' Compute Bregman divergence between data X and clusters Mu. Smooth the data via update with prior parameters. Args ---- X : 2D array, size N x D Mu : list of size K, or tuple Returns ------- Div : 2D array, N x K Div[n,k] = smoothed distance between X[n] and Mu[k] ''' # Parse X if X.ndim < 2: X = X[np.newaxis,:] assert X.ndim == 2 N = X.shape[0] D = X.shape[1] # Parse Mu if isinstance(Mu, tuple): Mu = [Mu] assert isinstance(Mu, list) K = len(Mu) assert Mu[0][0].shape[0] == D assert Mu[0][0].shape[1] == D assert Mu[0][1].size == D prior_x = self.Prior.m prior_covx = self.Prior.B / (self.Prior.nu) CovX = eps * prior_covx Div = np.zeros((N, K)) for k in range(K): chol_CovMu_k = np.linalg.cholesky(Mu[k][0]) logdet_CovMu_k = 2.0 * np.sum(np.log(np.diag(chol_CovMu_k))) tr_InvMu_CovX_k = np.trace(np.linalg.solve( Mu[k][0], CovX)) XdiffMu_k = X - Mu[k][1] tr_InvMu_XdXdT_k = np.linalg.solve(chol_CovMu_k, XdiffMu_k.T) tr_InvMu_XdXdT_k *= tr_InvMu_XdXdT_k tr_InvMu_XdXdT_k = tr_InvMu_XdXdT_k.sum(axis=0) Div[:,k] = \ + 0.5 * logdet_CovMu_k \ + 0.5 * (tr_InvMu_CovX_k + tr_InvMu_XdXdT_k) if not includeOnlyFastTerms: if DivDataVec is None: # Compute DivDataVec : 1D array of size N # This is the per-row additive constant indep. of k. DivDataVec = -0.5 * D * np.ones(N) s, logdet = np.linalg.slogdet(CovX) logdet_CovX = s * logdet DivDataVec -= 0.5 * logdet_CovX Div += DivDataVec[:,np.newaxis] # Apply per-atom weights to divergences. if W is not None: assert W.ndim == 1 assert W.size == N Div *= W[:,np.newaxis] # Verify divergences are strictly non-negative if not includeOnlyFastTerms: minDiv = Div.min() if minDiv < 0: if minDiv < -1e-6: raise AssertionError( "Expected Div.min() to be positive or" + \ " indistinguishable from zero. Instead " + \ " minDiv=% .3e" % (minDiv)) np.maximum(Div, 0, out=Div) minDiv = Div.min() assert minDiv >= 0 if return1D: Div = Div[:,0] if returnDivDataVec: return Div, DivDataVec return Div def calcBregDivFromPrior(self, Mu, smoothFrac=0.0): ''' Compute Bregman divergence between Mu and prior mean. Returns ------- Div : 1D array, size K Div[k] = distance between Mu[k] and priorMu ''' assert isinstance(Mu, list) K = len(Mu) assert K >= 1 assert Mu[0][0].ndim == 2 assert Mu[0][1].ndim == 1 D = Mu[0][0].shape[0] assert D == Mu[0][0].shape[1] assert D == Mu[0][1].size priorCov = self.Prior.B / self.Prior.nu priorMu_2 = self.Prior.m priorN_ZMG = (1-smoothFrac) * self.Prior.nu priorN_FVG = (1-smoothFrac) * self.Prior.kappa Div_ZMG = np.zeros(K) # zero-mean gaussian Div_FVG = np.zeros(K) # fixed variance gaussian s, logdet = np.linalg.slogdet(priorCov) logdet_priorCov = s * logdet for k in range(K): Cov_k = Mu[k][0] s, logdet = np.linalg.slogdet(Cov_k) logdet_Cov_k = s * logdet Div_ZMG[k] = 0.5 * logdet_Cov_k + \ - 0.5 * logdet_priorCov \ + 0.5 * np.trace(np.linalg.solve(Cov_k, priorCov)) \ - 0.5 pmT = np.outer(priorMu_2 - Mu[k][1], priorMu_2 - Mu[k][1]) Div_FVG[k] = 0.5 * np.trace(np.linalg.solve(Cov_k, pmT)) return priorN_ZMG * Div_ZMG + priorN_FVG * Div_FVG # .... end class def MAPEstParams_inplace(nu, B, m, kappa=0): ''' MAP estimate parameters mu, Sigma given Normal-Wishart hyperparameters ''' D = m.size mu = m Sigma = B for k in range(B.shape[0]): Sigma[k] /= (nu[k] + D + 1) return mu, Sigma def c_Func(nu, logdetB, m, kappa): ''' Evaluate cumulant function at given params. Returns -------- c : scalar real value of cumulant function at provided args ''' if logdetB.ndim >= 2: logdetB = np.log(np.linalg.det(logdetB)) D = m.size dvec = np.arange(1, D + 1, dtype=np.float) return - 0.5 * D * LOGTWOPI \ - 0.25 * D * (D - 1) * LOGPI \ - 0.5 * D * LOGTWO * nu \ - np.sum(gammaln(0.5 * (nu + 1 - dvec))) \ + 0.5 * D * np.log(kappa) \ + 0.5 * nu * logdetB def c_Diff(nu1, logdetB1, m1, kappa1, nu2, logdetB2, m2, kappa2): ''' Evaluate difference of cumulant functions c(params1) - c(params2) May be more numerically stable than directly using c_Func to find the difference. Returns ------- diff : scalar real value of the difference in cumulant functions ''' if logdetB1.ndim >= 2: logdetB1 = np.log(np.linalg.det(logdetB1)) if logdetB2.ndim >= 2: logdetB2 = np.log(np.linalg.det(logdetB2)) D = m1.size dvec = np.arange(1, D + 1, dtype=np.float) return - 0.5 * D * LOGTWO * (nu1 - nu2) \ - np.sum(gammaln(0.5 * (nu1 + 1 - dvec))) \ + np.sum(gammaln(0.5 * (nu2 + 1 - dvec))) \ + 0.5 * D * (np.log(kappa1) - np.log(kappa2)) \ + 0.5 * (nu1 * logdetB1 - nu2 * logdetB2) def calcSummaryStats(Data, SS, LP, **kwargs): ''' Calculate summary statistics for given dataset and local parameters Returns -------- SS : SuffStatBag object, with K components. ''' X = Data.X if 'resp' in LP: resp = LP['resp'] K = resp.shape[1] # 1/2: Compute mean statistic S_x = dotATB(resp, X) # 2/2: Compute expected outer-product statistic S_xxT = np.zeros((K, Data.dim, Data.dim)) sqrtResp_k = np.sqrt(resp[:, 0]) sqrtRX_k = sqrtResp_k[:, np.newaxis] * Data.X S_xxT[0] = dotATA(sqrtRX_k) for k in range(1, K): np.sqrt(resp[:, k], out=sqrtResp_k) np.multiply(sqrtResp_k[:, np.newaxis], Data.X, out=sqrtRX_k) S_xxT[k] = dotATA(sqrtRX_k) else: spR = LP['spR'] K = spR.shape[1] # 1/2: Compute mean statistic S_x = spR.T * X # 2/2: Compute expected outer-product statistic S_xxT = calcSpRXXT(X=X, spR_csr=spR) if SS is None: SS = SuffStatBag(K=K, D=Data.dim) # Expected mean for each state k SS.setField('x', S_x, dims=('K', 'D')) # Expected outer-product for each state k SS.setField('xxT', S_xxT, dims=('K', 'D', 'D')) # Expected count for each k # Usually computed by allocmodel. But just in case... if not hasattr(SS, 'N'): if 'resp' in LP: SS.setField('N', LP['resp'].sum(axis=0), dims='K') else: SS.setField('N', as1D(toCArray(LP['spR'].sum(axis=0))), dims='K') return SS def calcLocalParams(Dslice, **kwargs): L = calcLogSoftEvMatrix_FromPost(Dslice, **kwargs) LP = dict(E_log_soft_ev=L) return LP def calcLogSoftEvMatrix_FromPost(Dslice, **kwargs): ''' Calculate expected log soft ev matrix for variational. Returns ------ L : 2D array, size N x K ''' K = kwargs['K'] L = np.zeros((Dslice.nObs, K)) for k in range(K): L[:, k] = - 0.5 * Dslice.dim * LOGTWOPI \ + 0.5 * kwargs['E_logdetL'][k] \ - 0.5 * _mahalDist_Post(Dslice.X, k, **kwargs) return L def _mahalDist_Post(X, k, D=None, cholB=None, m=None, nu=None, kappa=None, **kwargs): ''' Calc expected mahalonobis distance from comp k to each data atom Returns -------- distvec : 1D array, size N distvec[n] gives E[ (x-\mu) \Lam (x-\mu) ] for comp k ''' Q = np.linalg.solve(cholB[k], (X - m[k]).T) Q *= Q return nu[k] * np.sum(Q, axis=0) + D / kappa[k] def createECovMatFromUserInput(D=0, Data=None, ECovMat='eye', sF=1.0): ''' Create expected covariance matrix defining Wishart prior. The creation process follows user-specified criteria. Args -------- D : positive integer, size of each observation Data : [optional] dataset to use to make Sigma in data-driven way ECovMat : string name of the procedure to use to create Sigma 'eye' : make Sigma a multiple of the identity matrix 'covdata' : set Sigma to a multiple of the data covariance matrix 'fromtruelabels' : set Sigma to the empirical mean of the covariances for each true cluster in the dataset Returns -------- Sigma : 2D array, size D x D Symmetric and positive definite. ''' if Data is not None: assert D == Data.dim if ECovMat == 'eye': Sigma = sF * np.eye(D) elif ECovMat == 'covdata': Sigma = sF * np.cov(Data.X.T, bias=1) elif ECovMat == 'diagcovdata': CovMat = as2D(np.cov(Data.X.T, bias=1)) # as2D deals with case of D=1 Sigma = sF * np.diag(np.diag(CovMat)) elif ECovMat == 'covfirstdiff': if not hasattr(Data, 'Xprev'): raise ValueError( 'covfirstdiff only applies to auto-regressive datasets') Xdiff = Data.X - Data.Xprev Sigma = sF * np.cov(Xdiff.T, bias=1) elif ECovMat == 'diagcovfirstdiff': if not hasattr(Data, 'Xprev'): raise ValueError( 'covfirstdiff only applies to auto-regressive datasets') Xdiff = Data.X - Data.Xprev Sigma = sF * np.diag(np.diag(np.cov(Xdiff.T, bias=1))) elif ECovMat == 'fromtruelabels': ''' Set Cov Matrix Sigma using the true labels in empirical Bayes style Sigma = \sum_{c : class labels} w_c * SampleCov[ data from class c] ''' if hasattr(Data, 'TrueLabels'): Z = Data.TrueLabels else: Z = Data.TrueParams['Z'] Zvals = np.unique(Z) Kmax = len(Zvals) wHat = np.zeros(Kmax) SampleCov = np.zeros((Kmax, D, D)) for kLoc, kVal in enumerate(Zvals): mask = Z == kVal wHat[kLoc] = np.sum(mask) SampleCov[kLoc] = np.cov(Data.X[mask].T, bias=1) wHat = wHat / np.sum(wHat) Sigma = 1e-8 * np.eye(D) for k in range(Kmax): Sigma += wHat[k] * SampleCov[k] else: raise ValueError('Unrecognized ECovMat procedure %s' % (ECovMat)) return Sigma
python
import networkx as nx import operator import matplotlib.pyplot as plt g = nx.read_weighted_edgelist('data/edgelist24.csv') degree = nx.degree(g) numNodes = nx.number_of_nodes(g) numEdges = nx.number_of_edges(g) minDegree = min([item[1] for item in degree]) maxDegree = max([item[1] for item in degree]) print(degree) print(numNodes) print(numEdges) print(minDegree) print(maxDegree) degreeSorted = sorted(degree, key=operator.itemgetter(1), reverse=True) print(degreeSorted[0:9]) nx.draw(g) plt.show() plt.savefig('path.png')
python
# 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 # # 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 numpy as np import pickle import sys import os import argparse import traceback #my imports from pddm.utils.helper_funcs import visualize_rendering from pddm.utils.helper_funcs import create_env import pddm.envs ###import by hamada from gym import wrappers import matplotlib.pyplot as plt import time import re from pylab import rcParams rcParams['figure.figsize'] = 30,30 plt.rcParams["font.size"] = 18 def vis_iter_graph(args, load_dir0): ########################## ## load in data ########################## #params0 paramfile0 = open(load_dir0 + '/params.pkl', 'rb') params0 = pickle.load(paramfile0) env_name0 = params0.env_name #data to visualize if args.eval: with open(load_dir0 + '/saved_rollouts/rollouts_eval'+ str(args.iter_num) +'.pickle', 'rb') as handle: rollouts_info0 = pickle.load(handle) else: with open( load_dir0 + '/saved_rollouts/rollouts_info_' + str(args.iter_num) + '.pickle', 'rb') as handle0: rollouts_info0 = pickle.load(handle0) ########################## ## visualize ########################## #create env #use_env, dt_from_xml = create_env(env_name) ###added by hamada #use_env=wrappers.Monitor(use_env, args.save_dir, force=True) rewards = [] scores = [] #save_dir =load_dir0+"/{}_aftercal/".format(time.strftime("%Y-%m-%d")) save_dir = load_dir0 + "/aftercaleei/".format(time.strftime("%Y-%m-%d")) if not os.path.isdir(save_dir): os.makedirs(save_dir) if re.findall('i.?v', env_name0 ): agent_type="ip" elif re.findall('r.?a',env_name0): agent_type = "re" elif re.findall('c.?h',env_name0): agent_type = "hc" iter_num ="iter"+str(args.iter_num) print("env name {}".format(re.findall('r.?a',env_name0))) for vis_index in range(len(rollouts_info0)): print("\n\nROLLOUT NUMBER ", vis_index, " .... num steps loaded: ", rollouts_info0[vis_index]['actions'].shape[0]) #visualize rollouts from this iteration states0=rollouts_info0[vis_index]["observations"] actions0=rollouts_info0[vis_index]["actions"] if args.perturb: perturb0 = rollouts_info0[vis_index]["disturbances"].reshape([500,1]) if agent_type=="ip": state_index = [0,1,2,3] elif agent_type=="re": #state_index = [0, 1, 2, 3,4,5,6,7,8,9] state_index =[4,5,6,7,8,9 ] elif agent_type == "hc": state_index = [4, 5, 6, 7, 8, 9] fig = plt.figure() until_where = 200 speed = 0 energy = 0 energy2=0 error2=0 for ind in range(actions0.shape[0]): speed = speed + states0[ind,9] for i in range(actions0.shape[1]): delta_theta = np.abs(states0[ind+1,i]-states0[ind,i]) energy = energy + np.abs(actions0[ind,i]) * delta_theta EEI = speed/energy #EEI2 = 1/error/enrrgy2 #EEI3= 1/error2/energy print("EEI:{} Ene:{} Speed:{}".format(EEI,energy,speed)) #print("EEI2:{} Ene2:{} Error:{}".format(EEI2, energy2, error)) #print("EEI:{} Ene:{} Error:{}".format(EEI3, energy, error2)) if args.eval: np.save(save_dir + "/eval_eeis_{}.npy".format(args.iter_num), np.array(EEI)) np.save(save_dir + "/eval_ers_{}.npy".format(args.iter_num), np.array(speed)) np.save(save_dir + "/eval_enes_{}.npy".format(args.iter_num), np.array(energy)) #np.save(save_dir + "/eval_eeis2_{}.npy".format(args.iter_num), np.array(EEI2)) #np.save(save_dir + "/eval_ers2_{}.npy".format(args.iter_num), np.array(error2)) #np.save(save_dir + "/eval_enes2_{}.npy".format(args.iter_num), np.array(energy2)) #np.save(save_dir + "/eval_eeis3_{}.npy".format(args.iter_num), np.array(EEI3)) else: np.save(save_dir + "/eeis_{}.npy".format(args.iter_num), np.array(EEI)) np.save(save_dir + "/ers_{}.npy".format(args.iter_num), np.array(speed)) np.save(save_dir + "/enes_{}.npy".format(args.iter_num), np.array(energy)) #np.save(save_dir + "/eeis2_{}.npy".format(args.iter_num), np.array(EEI2)) #np.save(save_dir + "/ers2_{}.npy".format(args.iter_num), np.array(error2)) #np.save(save_dir + "/enes2_{}.npy".format(args.iter_num), np.array(energy2)) #np.save(save_dir + "/eeis3_{}.npy".format(args.iter_num), np.array(EEI3)) def main(): ########################## ## vars to specify ########################## parser = argparse.ArgumentParser() parser.add_argument('--job_path0', type=str) #address this path WRT your working directory #parser.add_argument('--job_path3', type=str) # address this path WRT your working directory parser.add_argument('--iter_num', type=int, default=1) #if eval is False, visualize rollouts from this iteration parser.add_argument('--eval', action="store_true") # if this is True, visualize rollouts from rollouts_eval.pickle ##added by hamadda parser.add_argument('--perturb', action="store_true") #parser.add_argument('--agent_type', type=str) args = parser.parse_args() ########################## ## do visualization ########################## #directory to load from load_dir0 = os.path.abspath(args.job_path0) print("LOADING FROM: ", load_dir0) assert os.path.isdir(load_dir0) try: vis_iter_graph(args, load_dir0) except (KeyboardInterrupt, SystemExit): print('Terminating...') sys.exit(0) except Exception as e: print('ERROR: Exception occured while running a job....') traceback.print_exc() if __name__ == '__main__': main()
python
import vcr from .common import * from keepassxc_pwned.cli import main_wrapper from keepassxc_pwned.parser import Database db_file_loc = os.path.join(db_files, "duplicate_entry.kdbx") db_pw = "duplicate_entry" @pytest.fixture() def database(): db: Database = Database(pathlib.Path(db_file_loc)) db._password = db_pw return db def test_entry_count(database): assert len(database.credentials) == 3 # pass -q flag @vcr.use_cassette("tests/vcr_cassettes/test_default.yaml") def test_default(capsys, caplog): os.environ["KEEPASSXC_PWNED_PASSWD"] = "duplicate_entry" main_wrapper(False, None, False, True, db_file_loc, None) captured = capsys.readouterr() captured_lines = captured.out.splitlines() for output, expected in zip( captured_lines, [ "Found 3 previously breached passwords:", "entry:5BAA61E4C9B93F3F0682250B6CF8331B7EE68FD8:3730471", "entry:5BAA61E4C9B93F3F0682250B6CF8331B7EE68FD8:3730471", "5BAA61E4C9B93F3F0682250B6CF8331B7EE68FD8:5BAA61E4C9B93F3F0682250B6CF8331B7EE68FD8:3730471", ], ): assert output == expected assert len(captured_lines) == 4
python
import sys import logging import random import numpy as np import os # from nltk.corpus import wordnet as wn import argparse import torch import pickle from transformers import GPT2Tokenizer, TransfoXLTokenizer from shutil import copyfile import collections from multiprocessing.pool import Pool import multiprocessing from functools import partial try: multiprocessing.set_start_method('spawn') except RuntimeError: pass logging.basicConfig(format='%(asctime)s - %(levelname)s - %(name)s - %(message)s', datefmt='%m/%d/%Y %H:%M:%S', level=logging.INFO) logger = logging.getLogger(__name__) parser = argparse.ArgumentParser() parser.add_argument("--input-data-file", type=str, default="./data/wikitext-103/wiki.test.tokens") parser.add_argument("--output-data-file", type=str, default="./data/wikitext-103/pos_tagged_test.txt") args = parser.parse_args() seed = 42 random.seed(seed) np.random.seed(seed) torch.manual_seed(seed) torch.cuda.manual_seed_all(seed) subword_models = ["gpt2-medium", "gpt2"] device = torch.device("cuda" if torch.cuda.is_available() else "cpu") n_gpu = torch.cuda.device_count() logger.info("device: {}, n_gpu {}".format(device, n_gpu)) punct_masks = ["#", "$", "''", "(", ")", ",", ".", ":", "``"] upper_pos_dir = { "NOUN": [ "FW", "NN", "NNS", "NNP", "NNPS"], "PRON": [ "PRP", "PRP$", "WP", "WP$", "EX"], "ADJ": [ "JJ", "JJR", "JJS"], "ADV": [ "RB", "RBR", "RBS", "RP", "WRB", "UH"], "VERB": [ "MD", "VB", "VBD", "VBG", "VBN", "VBP", "VBZ"], "NUM": ["CD"], "ART": ["DT", "PDT", "WDT"], "PREP": ["IN", "POS", "TO"], "CONJ": ["CC"], "SYM": ["SYM", "LS", "#", "$", "''", "(", ")", ",", ".", ":", "``"] } punct_marks = ["-", "--", "---", ",", ".", "?", ":", "'", '"', "!", "`", "$", "#", "...", "(", ")", "[", "]", "{", "}"] down_pos_to_up = {down_pos:up_pos for up_pos, down_pos_list in upper_pos_dir.items() for down_pos in down_pos_list} pos2word = {} def is_caption(line_split): return line_split[0] == '=' and line_split[-1] == '=' def pos_tag_by_core(read_file_name, write_dirty_name): from nltk.parse import CoreNLPParser pos_tagger = CoreNLPParser(url="http://localhost:9876", tagtype='pos') read_file = open(read_file_name, "r", encoding="utf-8") write_file = open(write_dirty_name, "w", encoding="utf-8") for idx, line in enumerate(read_file): line_split = line.strip().split() if len(line_split) != 0 and not is_caption(line_split): pos_result = pos_tagger.tag(line_split) for word_pos in pos_result: write_file.write(word_pos[0]) write_file.write(" ") write_file.write(word_pos[1]) write_file.write(" ") write_file.write("\n") if idx % 1000 == 0: logging.info("Finish tag {} lines.".format(idx)) read_file.close() write_file.close() def main(): logging.info("tagging data") pos_tag_by_core(args.input_data_file, args.output_data_file) if __name__ == '__main__': main()
python
from keras.models import load_model import cv2 import numpy as np from mtcnn.mtcnn import MTCNN cap = cv2.VideoCapture(0) model = load_model('../model/face-detector-model.h5') size = (200, 200) detector = MTCNN() while True: ret, frame = cap.read() faces = detector.detect_faces(frame) for face in faces: x1, y1, w, h = face['box'] x2 = x1 + w y2 = y1 + h roi = frame[y1: y2, x1:x2] if np.sum([roi]) != 0: roi = cv2.resize(roi, size) roi = (roi.astype('float')/255.0) roi = np.reshape(roi, [1, 200, 200, 3]) pred = model.predict([[roi]]) pred = pred[0] print(pred) if pred[0] >= pred[1]: label = 'NO MASK' color = (0,0,255) else: label = 'MASK' color = (0, 255, 0) cv2.rectangle(frame, (x1, y1), (x2, y2), color, 2) cv2.putText(frame, label, (x1, y1 - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.8, color, 2) cv2.imshow("MASK DETECTOR", frame) key = cv2.waitKey(1) if key == ord('q'): break cap.release() cv2.destroyAllWindows()
python
# Copyright 2018 The TensorFlow Authors. 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 ragged.elementwise_ops.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from absl.testing import parameterized import numpy as np from tensorflow.python.framework import dtypes from tensorflow.python.framework import errors from tensorflow.python.framework import ops from tensorflow.python.framework import test_util from tensorflow.python.ops import array_ops from tensorflow.python.ops import ragged from tensorflow.python.platform import googletest # Constants listing various op types to test. Each elementwise operation # should be included in at least one list below, or tested separately if # necessary (e.g., because it expects additional arguments). UNARY_FLOAT_OPS = [ ragged.abs, ragged.acos, ragged.acosh, ragged.angle, ragged.asin, ragged.asinh, ragged.atan, ragged.atanh, ragged.ceil, ragged.conj, ragged.cos, ragged.cosh, ragged.digamma, ragged.erf, ragged.erfc, ragged.exp, ragged.expm1, ragged.floor, ragged.imag, ragged.is_finite, ragged.is_inf, ragged.is_nan, ragged.lgamma, ragged.log, ragged.log1p, ragged.log_sigmoid, ragged.negative, ragged.real, ragged.reciprocal, ragged.rint, ragged.round, ragged.rsqrt, ragged.sign, ragged.sin, ragged.sinh, ragged.sqrt, ragged.square, ragged.tan, ragged.as_string, ragged.identity, ragged.ones_like, ragged.zeros_like, ] UNARY_BOOL_OPS = [ ragged.logical_not, ] UNARY_STRING_OPS = [ ragged.decode_base64, ragged.encode_base64, ragged.string_strip, ragged.decode_compressed, ] BINARY_FLOAT_OPS = [ ragged.add, ragged.atan2, ragged.complex, ragged.div, ragged.div_no_nan, ragged.divide, ragged.equal, ragged.floordiv, ragged.floormod, ragged.greater, ragged.greater_equal, ragged.less, ragged.less_equal, ragged.maximum, ragged.minimum, ragged.multiply, ragged.not_equal, ragged.pow, ragged.realdiv, ragged.squared_difference, ragged.subtract, ragged.truediv, ] BINARY_BOOL_OPS = [ ragged.logical_and, ragged.logical_or, ragged.logical_xor, ] UNARY_INT_OPS = [ ragged.unicode_script, ] BINARY_INT_OPS = [ ragged.truncatediv, ragged.truncatemod, ] class RaggedElementwiseOpsTest(test_util.TensorFlowTestCase, parameterized.TestCase): def assertSameShape(self, x, y): """Checks that x and y have the same shape (including ragged shapes).""" if isinstance(x, ragged.RaggedTensor): self.assertIsInstance(y, ragged.RaggedTensor) self.assertEqual(x.ragged_rank, y.ragged_rank) for (x_splits, y_splits) in zip(x.nested_row_splits, y.nested_row_splits): self.assertAllEqual(x_splits, y_splits) self.assertAllEqual( array_ops.shape(x.inner_values), array_ops.shape(y.inner_values)) else: self.assertIsInstance(y, ops.Tensor) self.assertAllEqual(array_ops.shape(x), array_ops.shape(y)) @parameterized.parameters( #========================================================================= # Test different input shapes. #========================================================================= [ # 0-dimensional input {'x': 12}, # 1-dimensional input {'x': [1, -2, 3]}, # 2-dimensional input {'x': [[-2, 3], [-3, 4]]}, {'x': ragged.constant_value([[-2, 3], [-3]], ragged_rank=1)}, # 3-dimensional inputs {'x': [[[-2, 3], [3, 4]], [[7, 6], [5, 4]]]}, {'x': ragged.constant_value([[[-2, 3], [3, 4]], [[7, 6]]], ragged_rank=1)}, {'x': ragged.constant_value([[[-2, 3, 4], []], [[7, 6]], []], ragged_rank=2)}, ] + #========================================================================= # Test each unary op. #========================================================================= [{'x': ragged.constant_value([[-2.0, 3.0], [-3.0]]), 'op': op} for op in UNARY_FLOAT_OPS] + [{'x': ragged.constant_value([[True, False], [True]]), 'op': op} for op in UNARY_BOOL_OPS] + [{'x': ragged.constant_value([[18, 512], [12412]], np.int32), 'op': op} for op in UNARY_INT_OPS] + [{'x': ragged.constant_value([['abcd', 'efgh'], ['aabbccdd']]), 'op': op} for op in UNARY_STRING_OPS] + [ {'op': ragged.clip_by_value, 'x': ragged.constant_value([[-2.0, 3.0], [-3.0]]), 'clip_value_min': 0.1, 'clip_value_max': 4.0}, {'op': ragged.cast, 'x': ragged.constant_value([[-2.0, 3.0], [-3.0]]), 'dtype': dtypes.int32}, {'op': ragged.saturate_cast, 'x': ragged.constant_value([[-2.0, 3.0], [-3.0]]), 'dtype': dtypes.int32}, {'op': ragged.string_to_hash_bucket, 'x': ragged.constant_value([['abcd', 'efgh'], ['aabbccdd']]), 'num_buckets': 1000}, {'op': ragged.string_to_hash_bucket_fast, 'x': ragged.constant_value([['abcd', 'efgh'], ['aabbccdd']]), 'num_buckets': 1000}, {'op': ragged.string_to_hash_bucket_strong, 'x': ragged.constant_value([['abcd', 'efgh'], ['aabbccdd']]), 'num_buckets': 1000, 'key': [1231, 12512]}, {'op': ragged.string_to_number, 'x': ragged.constant_value([['-2.0', '3.0'], ['-3.0']])}, {'op': ragged.regex_full_match, 'x': ragged.constant_value([['hello', '123'], ['1+1']]), 'pattern': r'\w+'}, {'op': ragged.regex_replace, 'x': ragged.constant_value([['hello', '123'], ['1+1']]), 'pattern': r'\d', 'rewrite': '#'}, {'op': ragged.substr, 'x': ragged.constant_value([['hello', '123'], ['1+1']]), 'pos': 2, 'len': 3}, {'op': ragged.check_numerics, 'x': ragged.constant_value([[-2.0, 3.0], [-3.0]]), 'message': 'check-numerics'}, ] ) # pyformat: disable def testUnaryOp(self, x, op=ragged.abs, **extra_args): x = ragged.convert_to_tensor_or_ragged_tensor(x) result = op(x, **extra_args) # Run the wrapped op on the dense values, for comparison. dense_x = x.inner_values if isinstance(x, ragged.RaggedTensor) else x expected_flat_values = array_ops.reshape( op.__wrapped__(dense_x, **extra_args), [-1]) with self.test_session(): # Check that the result has the expected shape. self.assertSameShape(x, result) # Check that the result has the expected (flattened) values. if isinstance(result, ragged.RaggedTensor): result_flat_values = array_ops.reshape(result.inner_values, [-1]) else: result_flat_values = array_ops.reshape(result, [-1]) self.assertAllEqual(expected_flat_values, result_flat_values) @parameterized.parameters( [ #===================================================================== # Without broadcasting -- i.e., shapes match exactly. #===================================================================== # Shapes: x:(), y:() {'x': 12, 'y': 8}, # Shapes: x:(3,), y:(3,) {'x': [7, 8, 9], 'y': [1, -2, 3]}, # Shapes: x:(2, 2), y:(2, 2) {'x': [[-2, 3], [-3, -4]], 'y': [[1, 2], [3, 4]]}, # Shapes: x:(2, None), y:(2, None) {'x': ragged.constant_value([[-2, 3], [-3]]), 'y': ragged.constant_value([[5, 6], [7]])}, # Shapes: x:(2, 2, 2), y:(2, 2, 2) {'x': [[[1, 2], [3, 4]], [[5, 6], [7, 8]]], 'y': [[[9, 3], [3, 4]], [[5, 2], [7, 6]]]}, # Shapes: x:(2, None, None), y: (2, None, None) {'x': ragged.constant_value([[[1, 2], [3], [4]], [[], [5, 7, 8]]]), 'y': ragged.constant_value([[[3, 8], [2], [5]], [[], [1, 9, 8]]])}, # Shapes: x:(2, None, 2), y: (2, None, 2) {'x': ragged.constant_value([[[1, 2]], [[3, 4], [5, 6], [7, 8]]], ragged_rank=1), 'y': ragged.constant_value([[[9, 3]], [[5, 2], [3, 4], [7, 6]]], ragged_rank=1)}, #===================================================================== # With broadcasting #===================================================================== # Shapes: x:(), y:(3,) {'x': 12, # Broadcast () -> (3,) 'y': [1, -2, 3]}, # Shapes: x:(1,), y:(3,) {'x': [12], # Broadcast (1,) -> (3,) 'y': [1, -2, 3]}, # Shapes: x:(), y:(2, 2) {'x': 12, # Broadcast () -> (2, 2) 'y': [[1, 2], [3, 4]]}, # Shapes: x:(1,), y:(2, 2) {'x': 12, # Broadcast (1,) -> (2, 2) 'y': [[1, 2], [3, 4]]}, # Shapes: x:(2, 1), y:(2, 2) {'x': [[10], [20]], # Broadcast (2, 1) -> (2, 2) 'y': [[1, 2], [3, 4]]}, # Shapes: x:(), y:(2, None) {'x': 10, # Broadcast () -> (2, None) 'y': ragged.constant_value([[1, 2], [3]], dtype=np.int32)}, # TODO(edloper): Add tests for more advanced broadcasting, once we add # support for it. #===================================================================== # Keyword Args #===================================================================== {'x': ragged.constant_value([[[1, 2], [3], [4]], [[], [5, 7, 8]]]), 'y': ragged.constant_value([[[3, 8], [2], [5]], [[], [1, 9, 8]]]), 'use_kwargs': True}, {'x': ragged.constant_value([[[1, 2]], [[3, 4], [5, 6], [7, 8]]], ragged_rank=1), 'y': ragged.constant_value([[[9, 3]], [[5, 2], [3, 4], [7, 6]]], ragged_rank=1), 'use_kwargs': True}, ] + #========================================================================= # Test each unary op. #========================================================================= [{'x': ragged.constant_value([[-2.0, 3.0], [-3.0]]), 'y': ragged.constant_value([[5.0, 1.0], [12.0]]), 'op': op} for op in BINARY_FLOAT_OPS] + [{'x': ragged.constant_value([[-2, 3], [-3]]), 'y': ragged.constant_value([[5, 1], [12]]), 'op': op} for op in BINARY_INT_OPS] + [{'x': ragged.constant_value([[True, True], [False]]), 'y': ragged.constant_value([[False, True], [False]]), 'op': op} for op in BINARY_BOOL_OPS] + [ ] ) # pyformat: disable def testBinaryOp(self, x, y, op=ragged.add, **extra_args): use_kwargs = extra_args.pop('use_kwargs', False) x = ragged.convert_to_tensor_or_ragged_tensor(x) y = ragged.convert_to_tensor_or_ragged_tensor(y) if use_kwargs: result = op(x=x, y=y, **extra_args) else: result = op(x, y, **extra_args) # Run the wrapped op on the dense values, for comparison. dense_x = x.inner_values if isinstance(x, ragged.RaggedTensor) else x dense_y = y.inner_values if isinstance(y, ragged.RaggedTensor) else y expected_flat_values = array_ops.reshape( op.__wrapped__(dense_x, dense_y, **extra_args), [-1]) with self.test_session(): # Check that the result has the expected shape. self.assertSameShape(y, result) # Check that the result has the expected (flattened) values. if isinstance(result, ragged.RaggedTensor): result_flat_values = array_ops.reshape(result.inner_values, [-1]) else: result_flat_values = array_ops.reshape(result, [-1]) self.assertAllEqual(expected_flat_values, result_flat_values) @parameterized.parameters( [ {'inputs': (12, 8, 3)}, {'inputs': ([1, 2, 3], [7, 8, 9], [3, 6, 9])}, {'inputs': ([[1, 2]], [[3, 4]], [[5, 6]])}, {'inputs': (ragged.constant_value([[1, 3], [-3]]), ragged.constant_value([[4, 7], [88]]), ragged.constant_value([[2, 9], [12]]))}, {'inputs': (ragged.constant_value([[[1, 3], [-3]], [[1]]]), ragged.constant_value([[[4, 7], [88]], [[2]]]), ragged.constant_value([[[2, 9], [12]], [[8]]]))}, {'inputs': (ragged.constant_value([[[1, 3], [3, 4]], [[1, 5]]], ragged_rank=1), ragged.constant_value([[[4, 7], [1, 2]], [[2, 2]]], ragged_rank=1), ragged.constant_value([[[2, 9], [5, 2]], [[8, 0]]], ragged_rank=1))}, {'inputs': (ragged.constant_value([[[1, 3], [-3]], [[1]]]), ragged.constant_value([[[4, 7], [88]], [[2]]]), ragged.constant_value([[[2, 9], [12]], [[8]]])), 'use_kwargs': True}, ] + [ {'op': ragged.add_n, 'inputs': (ragged.constant_value([[1, 3], [-3]]), ragged.constant_value([[4, 7], [88]]), ragged.constant_value([[2, 9], [12]]))}, {'op': ragged.string_join, 'inputs': (ragged.constant_value([['a', 'b'], ['c']]), ragged.constant_value([['foo', 'bar'], ['baz']]), ragged.constant_value([['2', '9'], ['12']]))}, ]) # pyformat: disable def testListValuedOp(self, inputs, op=ragged.add_n, **extra_args): use_kwargs = extra_args.pop('use_kwargs', False) inputs = [ragged.convert_to_tensor_or_ragged_tensor(x) for x in inputs] if use_kwargs: result = op(inputs=inputs, **extra_args) else: result = op(inputs, **extra_args) # Run the wrapped op on the dense values, for comparison. dense_inputs = [ x.inner_values if isinstance(x, ragged.RaggedTensor) else x for x in inputs ] expected_flat_values = array_ops.reshape( op.__wrapped__(dense_inputs, **extra_args), [-1]) with self.test_session(): # Check that the result has the expected shape. self.assertSameShape(inputs[0], result) # Check that the result has the expected (flattened) values. if isinstance(result, ragged.RaggedTensor): result_flat_values = array_ops.reshape(result.inner_values, [-1]) else: result_flat_values = array_ops.reshape(result, [-1]) self.assertAllEqual(expected_flat_values, result_flat_values) def testUnknownRankError(self): x = ragged.constant([[1, 2], [3]]) y = ragged.from_row_splits( array_ops.placeholder_with_default([1, 2, 3], shape=None), x.row_splits) with self.assertRaisesRegexp( ValueError, r'Ragged elementwise ops require that rank \(number ' r'of dimensions\) be statically known.'): ragged.add(x, y) def testBroadcastError1(self): x = ragged.constant([[1, 2], [3]]) y = [[12]] with self.assertRaisesRegexp( ValueError, 'Ragged elementwise ops do not support broadcasting yet'): ragged.add(x, y) def testBroadcastError2(self): x = ragged.constant([[[1, 2], [3, 4]], [[5]]], ragged_rank=2) y = ragged.constant([[[8], [3]], [[2]]], ragged_rank=1) with self.assertRaisesRegexp(ValueError, 'Inputs must have identical ragged splits'): ragged.add(x, y) def testBroadcastError3(self): x = ragged.constant([[[1, 2], [3]], [[4, 5], [6]]], ragged_rank=2) y = ragged.constant([[7, 8], [9]], ragged_rank=1) with self.assertRaisesRegexp( ValueError, 'Ragged elementwise ops do not support broadcasting yet'): ragged.add(x, y) def testBroadcastError4(self): x = ragged.constant([[[1]]]) y = ragged.constant([[1]]) with self.assertRaisesRegexp( ValueError, 'Ragged elementwise ops do not support broadcasting yet'): ragged.add(x, y) def testShapeMismatch(self): x = ragged.constant([[1, 2, 3], [4, 5]]) y = ragged.constant([[1, 2, 3], [4, 5, 6]]) with self.assertRaisesRegexp(errors.InvalidArgumentError, 'Inputs must have identical ragged splits'): ragged.add(x, y) def testDocstring(self): self.assertRegexpMatches( ragged.add.__doc__, 'Ragged version of the elementwise operation `tf.math.add`') self.assertEqual(ragged.add.__name__, 'add') if __name__ == '__main__': googletest.main()
python
from mayan.apps.testing.tests.base import BaseTestCase from ..events import event_otp_disabled, event_otp_enabled from .mixins import AuthenticationOTPTestMixin class UserOTPDataTestCase(AuthenticationOTPTestMixin, BaseTestCase): create_test_case_superuser = True def test_method_get_absolute_url(self): self._test_case_superuser.otp_data.get_absolute_url() def test_otp_disable(self): self._enable_test_otp() self._clear_events() self._test_case_superuser.otp_data.disable() events = self._get_test_events() self.assertEqual(events.count(), 1) self.assertEqual(events[0].action_object, None) self.assertEqual(events[0].actor, self._test_case_superuser) self.assertEqual(events[0].target, self._test_case_superuser) self.assertEqual(events[0].verb, event_otp_disabled.id) def test_otp_enable(self): self._clear_events() self._enable_test_otp() events = self._get_test_events() self.assertEqual(events.count(), 1) self.assertEqual(events[0].action_object, None) self.assertEqual(events[0].actor, self._test_case_superuser) self.assertEqual(events[0].target, self._test_case_superuser) self.assertEqual(events[0].verb, event_otp_enabled.id)
python
import xlwings as xw import requests from aruba import Config, switch def vlans(data): """Enumera las VLANs del switch""" # Obtengo el workbook, las coordenadas y la dirección IP del servidor API wb, row, col, api_host = splitExcel(data) # Y ahora, obtengo los datos del switch with switch.session(Config(), api_host=api_host, verify=False) as session: vlans = requests.get(session.api_url + "/vlans", headers=session.headers(), verify=False) if vlans.status_code != 200: wb.sheets[0].range("%s%d"%(col, row)).value = "Error leyendo switch, "+vlans.text return for vlan in vlans.json()["vlan_element"]: wb.sheets[0].range(col+str(row)).value = "{} ({})".format(str(vlan["vlan_id"]), vlan["name"]) row += 1 def splitExcel(data): """Des-serializa los datos recibidos de excel Por algún motivo, xlWings no me funciona bien si la funcion python a la que se llama desde VBA recibe más de un parámetro. Así que hasta que averigüe por qué, lo que estoy haciendo es serializar los datos. La función VBA tiene que pasar una cadena de texto con los siguientes parñametros, separados por ";": - Dirección IP / nombre al que se quiere conectar - Número de fila desde donde se invoca a esta funcion. - Nombre de columna desde donde se invoca a esta función Por ejemplo: "192.168.x.x;5;B" Esta función devuelve 4 objetos: el workbook, la fila, la columna, y la dirección. """ # Los datos me vienen en formato direccion ; row ; col ... cosas de VBA addr, row, col = data.split(";") addr = addr.strip() or None row = int(row)+1 col = col.strip() # Borro toda la columna, desde la celda hacia abajo wb = xw.Book.caller() wb.sheets[0].range(col + str(row)).expand('down').clear_contents() # Y devuelvo workbook, fila, columna y direccion IP del api_host return (wb, row, col, addr)
python
""" module(requirement) - Python依赖. Main members: # check_requirement - 检查依赖. """ from qytPython import logger # 模块与pypi对应关系 module_pypi_config = { 'docx': 'python-docx', 'yaml': 'PyYAML' } def check_requirement(module_obj, module_name): """ 检查依赖. @params: module_obj - 模块对象. module_name - 模块名. @return: On success - 检查成功返回True. On failure - 依赖缺少Exception信息. """ logger.info('module_obj:{}'.format(module_obj)) if module_obj is None: pypi_name = module_pypi_config.get(module_name, module_name) raise Exception('缺少依赖,您可以执行以下命令进行安装: \npip install {}'.format(pypi_name)) return True
python
import numpy as np # See discussion around this question: https://stackoverflow.com/questions/2018178/finding-the-best-trade-off-point-on-a-curve/2022348#2022348 def index_of_elbow(points): """Returns the index of the "elbow" in ``points``. Decently fast and pretty approximate. Performs worse with disproportionately long "flat" tails. For example, in a dataset with a nearly right-angle elbow, it overestimates the elbow by 1 starting at a before/after ratio of 1/4. """ # Sort in descending order points = np.sort(points)[::-1] points = np.column_stack([np.arange(len(points)), points]) line_vector = points[-1] - points[0] line_vector /= np.linalg.norm(line_vector) from_first = points - points[0] component_along_line = np.sum(from_first * line_vector, axis = 1) along_line = np.outer(component_along_line, line_vector) dist_to_line = np.linalg.norm(from_first - along_line, axis = 1) return np.argmax(dist_to_line)
python
from .abstract import * from .. import schema class Lead( ListableAPIResource, MutableAPIResource ): """ Attributes: assessment_run_id (str): ID of the associated assessment run confidence (mage.schema.Confidence): Confidence level of the lead created_at (str): When the lead was created (e.g., '2020-01-02T03:04:56.789Z') description (str): Description of the lead evidence (mage.schema.AWSJSON): Evidence supporting the lead file_links (list of str): Associated files files (list of mage.schema.S3Object): Associated files id (str): Unique lead ID references (list of str): List of references to additional information title (str): Title of the lead updated_at (str): When the lead was last updated (e.g., '2020-01-02T03:04:56.789Z') """ _SEARCH_FN = 'search_leads' _UPDATE_FN = 'update_lead' _DELETE_FN = 'delete_lead' __field_names__ = schema.Lead.__field_names__ @property def assessment(self): """ Warning: Not Implemented. Use assessment_run instead. Todo: Rename assessment to assessment_run in the schema and remove this method. """ raise NotImplementedError("Call 'assessment_run' instead of 'assessment'") @property def assessment_run(self): """ The associated assessment run. Returns: `AssessmentRun <assessment_run.AssessmentRun>` Todo: Rename assessment to assessment_run in the schema then update this method by renaming assessment to assessment_run. """ from .assessment_run import AssessmentRun return self._nested_resource(AssessmentRun, 'assessment') @classmethod def create(cls, title, description, assessment_run_id, **kwargs): """ Creates a lead for an assessment run. Args: title (str): description (str): assessment_run_id (str): **kwargs: Additional arguments to initialize the lead with Returns: `Lead <lead.Lead>` Example: >>> import mage >>> mage.connect() >>> mage.Lead.create('Default Password on WEBSRV1', 'Password has not been changed yet.', '11111111-1111-1111-1111-111111111111') """ retval = cls.mutate('create_lead', input={'description': description, 'title': title, 'assessmentRunId': assessment_run_id, **kwargs}) if retval: retval = cls.init(retval) return retval
python
# Generated by Django 3.1.4 on 2021-01-02 07:11 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Category', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=20, verbose_name='名称')), ('sort', models.IntegerField(default=1, verbose_name='排序')), ('add_menu', models.BooleanField(default=True, verbose_name='添加到导航栏')), ('icon', models.CharField(default='fas fa-home', max_length=30, verbose_name='图标')), ], options={ 'verbose_name': '分类', 'verbose_name_plural': '分类', }, ), migrations.CreateModel( name='Item', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('title', models.CharField(max_length=10, verbose_name='标题')), ('desc', models.TextField(max_length=50, verbose_name='描述')), ('url', models.URLField(blank=True, verbose_name='网址')), ('img', models.URLField(default='https://jwt1399.top/favicon.png', verbose_name='图片')), ('category', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='webscan.category', verbose_name='分类')), ], options={ 'verbose_name': '导航条目', 'verbose_name_plural': '导航条目', }, ), ]
python
import unittest import numpy as np from svreg.summation import Rho, FFG from tests._testStructs import _all_test_structs, r0 class Test_Summation(unittest.TestCase): def setUp(self): self.ffg = FFG( name='ffg', allElements=['H', 'He'], neighborElements=['H', 'He'], components=['f_A', 'f_B', 'g_AA', 'g_BB', 'g_AB'], inputTypes={ 'f_A': ['H'], 'f_B': ['He'], 'g_AA': ['H', 'H'], 'g_AB': ['H', 'He'], 'g_BB': ['He', 'He'] }, numParams={'f_A': 7, 'f_B': 7, 'g_AA': 9, 'g_BB': 9, 'g_AB': 9}, restrictions={ 'f_A': [(6, 0), (8, 0)], 'f_B': [(6, 0), (8, 0)], 'g_AA':[], 'g_AB':[], 'g_BB':[], }, paramRanges={ 'f_A': None, 'f_B': None, 'g_AA': None, 'g_AB': None, 'g_BB': None }, bonds={ 'ffg_AA': ['f_A', 'f_A', 'g_AA'], 'ffg_AB': ['f_A', 'f_B', 'g_AB'], 'ffg_BB': ['f_B', 'f_B', 'g_BB'], }, bondMapping="lambda i,j: 'ffg_AA' if i+j==0 else ('ffg_AB' if i+j==1 else 'ffg_BB')", cutoffs=[1.0, 30.0], numElements=2, bc_type='fixed', ) self.rho = Rho( name='rho', allElements=['H', 'He'], neighborElements=['H', 'He'], components=['rho_A', 'rho_B'], inputTypes={'rho_A': ['H'], 'rho_B': ['He']}, numParams={'rho_A': 7, 'rho_B': 7}, restrictions={'rho_A': [(6, 0), (8, 0)], 'rho_B': [(6, 0), (8, 0)]}, paramRanges={'rho_A': None, 'rho_B': None}, bonds={ 'rho_A': ['rho_A'], 'rho_B': ['rho_B'], }, bondMapping="lambda i: 'rho_A' if i == 0 else 'rho_B'", cutoffs=[1.0, 3.1], numElements=2, bc_type='fixed', ) def test_sv_rho_dimers(self): params = { 'rho_A': np.array([1, 1, 1, 1, 1, 1, 1, 0, 0]), 'rho_B': np.array([2, 2, 2, 2, 2, 2, 2, 0, 0]), } expected = { 'aa': {'rho_A': 2.0, 'rho_B': 0.0}, 'ab': {'rho_A': 1.0, 'rho_B': 2.0}, 'bb': {'rho_A': 0.0, 'rho_B': 4.0}, } for struct in ['aa', 'ab', 'bb']: atoms = _all_test_structs[struct] engSV, _ = self.rho.loop(atoms, evalType='vector') for bondType in ['rho_A', 'rho_B']: res = engSV[bondType].dot(params[bondType]) self.assertEqual(sum(res), expected[struct][bondType]) def test_sv_rho_trimers(self): params = { 'rho_A': np.array([1, 1, 1, 1, 1, 1, 1, 0, 0]), 'rho_B': np.array([2, 2, 2, 2, 2, 2, 2, 0, 0]), } expected = { 'aaa': {'rho_A': 6.0, 'rho_B': 0.0}, 'bbb': {'rho_A': 0.0, 'rho_B': 12.0}, 'abb': {'rho_A': 2.0, 'rho_B': 8.0}, 'bab': {'rho_A': 2.0, 'rho_B': 8.0}, 'baa': {'rho_A': 4.0, 'rho_B': 4.0}, 'aba': {'rho_A': 4.0, 'rho_B': 4.0}, } for struct in ['aaa', 'bbb', 'abb', 'bab', 'baa', 'aba']: atoms = _all_test_structs[struct] engSV, _ = self.rho.loop(atoms, evalType='vector') for bondType in ['rho_A', 'rho_B']: res = engSV[bondType].dot(params[bondType]) self.assertEqual(sum(res), expected[struct][bondType]) def test_sv_ffg_dimers(self): params = { 'ffg_AA': np.vstack([ np.array([1, 1, 1, 1, 1, 1, 1, 0, 0]), np.array([2, 2, 2, 2, 2, 2, 2, 0, 0]), ]), 'ffg_AB': np.vstack([ np.array([1, 1, 1, 1, 1, 1, 1, 0, 0]), np.array([1, 1, 1, 1, 1, 1, 1, 0, 0]), np.array([3, 3, 3, 3, 3, 3, 3, 0, 0]), ]), 'ffg_BB': np.vstack([ np.array([1, 1, 1, 1, 1, 1, 1, 0, 0]), np.array([4, 4, 4, 4, 4, 4, 4, 0, 0]), ]), } params['ffg_AA'] = np.outer( np.outer( params['ffg_AA'][0], params['ffg_AA'][0] ).ravel(), params['ffg_AA'][1] ).ravel() params['ffg_AB'] = np.outer( np.outer( params['ffg_AB'][0], params['ffg_AB'][1] ).ravel(), params['ffg_AB'][2] ).ravel() params['ffg_BB'] = np.outer( np.outer( params['ffg_BB'][0], params['ffg_BB'][0] ).ravel(), params['ffg_BB'][1] ).ravel() expected = { 'aa': {'ffg_AA': 0.0, 'ffg_AB': 0.0, 'ffg_BB': 0.0}, 'ab': {'ffg_AA': 0.0, 'ffg_AB': 0.0, 'ffg_BB': 0.0}, 'bb': {'ffg_AA': 0.0, 'ffg_AB': 0.0, 'ffg_BB': 0.0}, } for struct in ['aa', 'ab', 'bb']: atoms = _all_test_structs[struct] engSV, _ = self.ffg.loop(atoms, evalType='vector') for bondType in ['ffg_AA', 'ffg_AB', 'ffg_BB']: res = engSV[bondType].dot(params[bondType]) self.assertEqual(sum(res), expected[struct][bondType]) def test_sv_ffg_trimers(self): params = { 'ffg_AA': np.vstack([ np.array([1, 1, 1, 1, 1, 1, 1, 0, 0]), np.array([2, 2, 2, 2, 2, 2, 2, 0, 0]), ]), 'ffg_AB': np.vstack([ np.array([1, 1, 1, 1, 1, 1, 1, 0, 0]), np.array([1, 1, 1, 1, 1, 1, 1, 0, 0]), np.array([3, 3, 3, 3, 3, 3, 3, 0, 0]), ]), 'ffg_BB': np.vstack([ np.array([1, 1, 1, 1, 1, 1, 1, 0, 0]), np.array([4, 4, 4, 4, 4, 4, 4, 0, 0]), ]), } params['ffg_AA'] = np.outer( np.outer( params['ffg_AA'][0], params['ffg_AA'][0] ).ravel(), params['ffg_AA'][1] ).ravel() params['ffg_AB'] = np.outer( np.outer( params['ffg_AB'][0], params['ffg_AB'][1] ).ravel(), params['ffg_AB'][2] ).ravel() params['ffg_BB'] = np.outer( np.outer( params['ffg_BB'][0], params['ffg_BB'][0] ).ravel(), params['ffg_BB'][1] ).ravel() # 2 per ffg_AA # 3 per ffg_AB # 4 per ffg_BB expected = { 'aaa': {'ffg_AA': 6.0, 'ffg_AB': 0.0, 'ffg_BB': 0.0}, 'bbb': {'ffg_AA': 0.0, 'ffg_AB': 0.0, 'ffg_BB': 12.0}, 'abb': {'ffg_AA': 0.0, 'ffg_AB': 6.0, 'ffg_BB': 4.0}, 'bab': {'ffg_AA': 0.0, 'ffg_AB': 6.0, 'ffg_BB': 4.0}, 'baa': {'ffg_AA': 2.0, 'ffg_AB': 6.0, 'ffg_BB': 0.0}, 'aba': {'ffg_AA': 2.0, 'ffg_AB': 6.0, 'ffg_BB': 0.0}, } for struct in ['aaa', 'bbb', 'abb', 'bab', 'baa', 'aba']: atoms = _all_test_structs[struct] engSV, _ = self.ffg.loop(atoms, evalType='vector') for bondType in ['ffg_AA', 'ffg_AB', 'ffg_BB']: res = engSV[bondType].dot(params[bondType]) np.testing.assert_almost_equal( sum(res), expected[struct][bondType] ) def test_sv_ffg_trimers_asymmetric(self): lineParams = np.concatenate([np.linspace(1.0, 30.0, 7), [1, 1]]) params = { 'ffg_AA': np.vstack([ lineParams, np.array([1, 1, 1, 1, 1, 1, 1, 0, 0]), ]), 'ffg_AB': np.vstack([ lineParams, lineParams*3, np.array([1, 1, 1, 1, 1, 1, 1, 0, 0]), ]), 'ffg_BB': np.vstack([ lineParams, np.array([1, 1, 1, 1, 1, 1, 1, 0, 0]), ]), } params['ffg_AA'] = np.outer( np.outer( params['ffg_AA'][0], params['ffg_AA'][0] ).ravel(), params['ffg_AA'][1] ).ravel() params['ffg_AB'] = np.outer( np.outer( params['ffg_AB'][0], params['ffg_AB'][1] ).ravel(), params['ffg_AB'][2] ).ravel() params['ffg_BB'] = np.outer( np.outer( params['ffg_BB'][0], params['ffg_BB'][0] ).ravel(), params['ffg_BB'][1] ).ravel() # r1*r2 for ffg_AA and ffg_BB # rA*(3*rB) for ffg_AB, to help detect incorrect j,k ordering """ TODO: this still isn't testing what I want. Any test that uses a potential whose splines only scale their inputs will fail to detect the bug that you want since it will scale the wrong input, but they're all being multiplied together anyways. """ expected = { 'aaa': { 'ffg_AA': 14*r0*13*r0+14*r0*9*r0+9*r0*13*r0, 'ffg_AB': 0.0, 'ffg_BB': 0.0 }, 'bbb': { 'ffg_AA': 0.0, 'ffg_AB': 0.0, 'ffg_BB': 14*r0*13*r0+14*r0*9*r0+9*r0*13*r0, }, 'abb': { 'ffg_AA': 0.0, # 'ffg_AB': 14*r0*3*9*r0+13*r0*3*9*r0, 'ffg_AB': 3*14*r0*9*r0+3*13*r0*9*r0, 'ffg_BB': 14*r0*13*r0, }, 'bab': { 'ffg_AA': 0.0, 'ffg_AB': 14*r0*3*13*r0+3*13*r0*9*r0, 'ffg_BB': 14*r0*9*r0 }, 'baa': { 'ffg_AA': 14*r0*13*r0, 'ffg_AB': 3*14*r0*9*r0+3*13*r0*9*r0, 'ffg_BB': 0.0 }, 'aba': { 'ffg_AA': 14*r0*9*r0, 'ffg_AB': 13*r0*3*14*r0+3*9*r0*13*r0, 'ffg_BB': 0.0 }, } for struct in ['aaa', 'bbb', 'abb', 'bab', 'baa', 'aba']: atoms = _all_test_structs[struct+'_asym'] engSV, _ = self.ffg.loop(atoms, evalType='vector') for bondType in ['ffg_AA', 'ffg_AB', 'ffg_BB']: res = engSV[bondType].dot(params[bondType]) np.testing.assert_almost_equal( sum(res), expected[struct][bondType] ) def test_sv_ffg_quad(self): """ The purpose is this function is to test a very specific bug that can occur when a B*A triplet (which is correctly mapped into the A*B bond) is evaluated incorrectly because rB is incorrectly dotted with the f_A parameters. """ pass
python
from .testing import Tester from .training import Trainer from .dataloader import multiview_dataloader def get_trainer(cfg, net, optimizer, device=None): return Trainer(cfg=cfg, net=net, optimizer=optimizer, device=device) def get_tester(cfg, net, device=None): return Tester(cfg=cfg, net=net, device=device) def get_dataloader(config, mode): return multiview_dataloader(config=config, mode=mode)
python
from datetime import timedelta, datetime from django.conf import settings from django.utils.timezone import make_aware import pytz from rest_framework import exceptions from rest_framework.authentication import TokenAuthentication import logging logger = logging.getLogger(__name__) class BearerAuthentication(TokenAuthentication): """ Simple token based authentication. Clients should authenticate by passing the token key in the "Authorization" HTTP header, prepended with the string "Bearer ". For example: Authorization: Bearer 401f7ac837da42b97f613d789819ff93537bee6a """ keyword = 'Bearer' def authenticate_credentials(self, key): model = self.get_model() try: token = model.objects.select_related('user').get(key=key) except model.DoesNotExist: logger.error("#Auth error for key: {}".format(key)) raise exceptions.AuthenticationFailed('Invalid token.') if not token.user.is_active: logger.error("#Auth error for user: {}, user inactive or deleted".format(token.user)) raise exceptions.AuthenticationFailed('User inactive or deleted.') # This is required for the time comparison now = datetime.now() now = now.replace(tzinfo=pytz.timezone(settings.TIME_ZONE)) valid = make_aware(now.now() - timedelta(days=60)) if token.created < valid: logger.debug("#Auth error user: {} Token Expired : {}".format(token.user, token.created-valid)) raise exceptions.AuthenticationFailed('Token has expired') return token.user, token
python
#!/usr/bin/env python # -*- coding: utf-8 -*- """ hdf5events.py Description: """ # Package Header # from ..__header__ import * # Header # __author__ = __author__ __credits__ = __credits__ __maintainer__ = __maintainer__ __email__ = __email__ # Imports # # Standard Libraries # import datetime import time import uuid # Third-Party Packages # from bidict import bidict import h5py import numpy as np # Local Packages # from .basehdf5 import BaseHDF5, HDF5hierarchicalDatasets # Todo: Adapt this to new style # Definitions # # Classes # class HDF5eventLogger(BaseHDF5): FILE_TYPE = "EventLog" VERSION = "0.0.1" EVENT_FIELDS = bidict(Time=0, DeltaTime=1, StartTime=2, Type=3) TIME_NAME = "Time" DELTA_NAME = "DeltaTime" START_NAME = "StartTime" TYPE_NAME = "Type" LINK_NAME = "LinkID" EVENT_DTYPE = np.dtype([(TIME_NAME, np.float), (DELTA_NAME, np.float), (START_NAME, np.float), (TYPE_NAME, h5py.string_dtype(encoding="utf-8")), (LINK_NAME, h5py.string_dtype(encoding="utf-8"))]) # Instantiation/Destruction def __init__(self, path=None, io_trigger=None, init=False): super().__init__(path=path) self.default_child_kwargs = {} self.event_types = {} self.start_datetime = None self.start_time_counter = None self.start_time_offset = None self.hierarchy = None if io_trigger is None: self.io_trigger = AudioTrigger() else: self.io_trigger = io_trigger if init: self.construct() # Container Magic Methods def __len__(self): return self.Events.len() def __getitem__(self, item): if isinstance(item, str): return super().__getitem__(item) elif isinstance(item, int) or isinstance(item, slice): return self.get_item((item, 0)) else: return self.get_item(item) # Representations def __repr__(self): return repr(self.start_datetime) # Constructors def construct(self, open_=False, **kwargs): super().construct(open_=open_, **kwargs) self.hierarchy = HDF5hierarchicalDatasets(h5_container=self, dataset=self.Events, name="Events", child_name=self.TYPE_NAME, link_name=self.LINK_NAME) def create_file(self, open_=False): super().create_file(open_=open_) self.create_event_dataset(name="Events", dtype=self.EVENT_DTYPE) # Datasets def create_event_dataset(self, name, dtype=None, data=None, **kwargs): if data is not None: m = data.shape[0] n = data.shape[1] else: m = 0 n = 1 defaults = {"shape": (m, n), "dtype": dtype, "maxshape": (None, n)} args = merge_dict(defaults, kwargs) return self.create_dataset(name=name, data=data, **args) # Sequence Methods def get_item(self, item): return self.hierarchy.get_items(item) def append(self, type_, **kwargs): if isinstance(type_, dict): self.append_event(type_) else: event = self.create_event(type_=type_, **kwargs) self.append_event(event) def insert(self, i, type_, **kwargs): if isinstance(type_, dict): super().insert(i, type_) else: event = self.create_event(type_=type_, **kwargs) super().insert(i, event) def clear(self): self.start_datetime = None self.start_time_counter = None self._path = None super().clear() # User Event Methods def create_event(self, type_, **kwargs): seconds = self.start_time_offset + round(time.perf_counter() - self.start_time_counter, 6) now = self.start_datetime + datetime.timedelta(seconds=seconds) return {"Time": now, "DeltaTime": seconds, "StartTime": self.start_datetime, self.TYPE_NAME: type_, **kwargs} def append_event(self, event, axis=0, child_kwargs=None): child_name = event[self.TYPE_NAME] if child_name not in self.hierarchy.child_datasets: child_event = event.copy() for field in self.EVENT_FIELDS.keys(): if field in child_event: child_event.pop(field) if self.LINK_NAME not in child_event: child_event[self.LINK_NAME] = str(uuid.uuid4()) child_dtype = self.event2dtype(child_event) if child_kwargs is None: child_kwargs = self.default_child_kwargs child_dataset = self.create_event_dataset(child_name, dtype=child_dtype, **child_kwargs) self.hierarchy.add_child_dataset(child_name, child_dataset) self.hierarchy.append_item(event, (child_name,), axis) def set_time(self): self.start_datetime = datetime.datetime.now() self.start_time_counter = time.perf_counter() self.start_time_offset = 0 self.append({"Time": self.start_datetime, "DeltaTime": 0, "StartTime": self.start_datetime, self.TYPE_NAME: "TimeSet"}) def resume_time(self, name=None, index=None): now_datatime = datetime.datetime.now() self.start_time_counter = time.perf_counter() if name is None: name = "TimeSet" if index is None: index = -1 start_event = self.hierarchy.get_item(index, name) self.start_datetime = datetime.datetime.fromtimestamp(start_event[self.TIME_NAME]) self.start_time_offset = (now_datatime - self.start_datetime).total_seconds() self.append({"Time": now_datatime, "DeltaTime": self.start_time_offset, "StartTime": self.start_datetime, self.TYPE_NAME: "ResumeTime"}) def get_event_type(self, name, id_info=False): return self.hierarchy.get_dataset(name, id_info) # Event Querying def find_event(self, time_, type_=None, bisect_="bisect"): if isinstance(time_, datetime.datetime): time_stamp = time_.timestamp() else: time_stamp = time_ if type_ is None or type_ == "Events": events = self times = self.Events[self.TIME_NAME] else: events = self.hierarchy.get_dataset(name=type_) times = [e[self.TIME_NAME] for e in events] index = bisect.bisect_left(times, time_stamp) if index >= len(times): index -= 1 elif times[index] == time_: pass elif bisect_ == "bisect": if index > 0: index -= 1 - (np.abs(times[index-1:index+1]-time_)).argmin() elif bisect_ == "left": if index > 0: index -= 1 elif bisect_ == "right": pass else: return -1, None return index, events[index] def find_event_range(self, start, end, type_=None): if type_ is None or type_ == "Events": events = self else: events = self.hierarchy.get_dataset(name=type_) first, _ = self.find_event(start, type_=type_, bisect_="right") last, _ = self.find_event(end, type_=type_, bisect_="left") return range(first, last+1), events[first:last+1] # Trigger Methods def trigger(self): self.io_trigger.trigger() def trigger_event(self, **kwargs): self.trigger() self.append(type_="Trigger", **kwargs) # Static Methods @staticmethod def event2dtype(event): dtypes = [] for key, value in event.items(): if isinstance(value, int): dtype = np.int elif isinstance(value, float): dtype = np.float elif isinstance(value, datetime.datetime): dtype = np.float else: dtype = h5py.string_dtype(encoding="utf-8") dtypes.append((key, dtype)) return dtypes class SubjectEventLogger(HDF5eventLogger): FILE_TYPE = "SubjectEventLog" VERSION = "0.0.1" SUBJECT_NAME = "Subject" EXPERIMENT_NAME = "Task" EXPERIMENT_NUMBER = "Block" # Instantiation/Destruction def __init__(self, path=None, subject="", x_name="", x_number="", io_trigger=None, init=False): super().__init__(path, io_trigger) self._subject = subject self._experiment_name = x_name self._experiment_number = x_number if init: self.construct() # Constructors def construct(self, open_=False, **kwargs): super().construct(open_=open_, **kwargs) def create_file(self, open_=False): super().create_file(open_=open_) self.add_file_attributes({self.SUBJECT_NAME: self._subject, self.EXPERIMENT_NAME: self._experiment_name, self.EXPERIMENT_NUMBER: self._experiment_number})
python
# -*- coding: utf-8 -*- # ----------------------------------------------------------------------------- # Module Level Imports # ----------------------------------------------------------------------------- from .typings import ( missing, snowflake, nullable, string, optional, snowflakearray, boolean, ) from .user import User from . import PWRCordType class Emoji(PWRCordType): _fields_mapper = [ "id", "name", "roles", "user", "require_colons", "managed", "animated", "available", ] id: nullable[snowflake] = None """emoji id""" name: nullable[string] = None """emoji name""" roles: optional[snowflakearray] = missing """roles allowed to use this emojiS""" user: optional[User] = missing """user that created this emoji""" require_colons: optional[boolean] = missing """whether this emoji must be wrapped in colons""" managed: optional[boolean] = missing """whether this emoji is managed""" animated: optional[boolean] = missing """whether this emoji is animated""" available: optional[boolean] = missing """whether this emoji can be used, may be false due to loss of Server Boosts""" @classmethod def initialize_json(cls, data: dict): """[summary] :param data: [description] :type data: dict :return: [description] :rtype: [type] """ object_initialized = cls() # Fill fields with their respective values for field in data: d = data[field] if isinstance(d, dict): # Probably we are interacting with object fields if field == "user": d = User.initialize_json(d) object_initialized.__setattr__(field, d) return object_initialized
python
import os import numpy as np import pandas as pd import matplotlib.pyplot as plt class Logger: def __init__(self, cnf): self.dat, self.acc, self.cnf = [], 0, cnf self.path_out = cnf.path_out self.path_out += '/{0}/'.format(self.cnf.log_name) self.path_trial = self.path_out + 'trials' if not os.path.isdir(self.path_trial): os.makedirs(self.path_trial) def logging(self, epo, error, C, hid_w, out_w): self.acc = 0 for i in range(self.cnf.N): if C[i] == self.cnf.iris.target[i]: self.acc += 1 self.acc = self.acc/self.cnf.N sls = [epo, error, self.acc] sls.extend(hid_w.flatten()) sls.extend(out_w.flatten()) self.dat.append(sls) def logging_detail(self, epo, Y, C): dat_dtl = [] for i in range(self.cnf.N): sls_dtl = [i+1] sls_dtl.extend(self.cnf.X[i]) sls_dtl.extend(Y[i]) if C[i] == self.cnf.iris.target[i]: acc = 1 else: acc = 0 sls_dtl += [int(C[i]), int(self.cnf.iris.target[i]), acc] dat_dtl.append(sls_dtl) head = "N,sepal_l,sepal_w,petal_l,petal_w,setosa,versicolor,virginica,predict,answer,true" np.savetxt(self.path_trial +'/trial{}_epo{}.csv'.format(self.cnf.seed, epo), np.array(dat_dtl), delimiter=',', header = head) print("trial: {:03}\tepoch: {}\taccuracy: {}".format(self.cnf.seed, epo, self.acc)) def outLog(self): head = "epoch,error,accuracy," + ','.join(["hid_w{}".format(i) for i in range(self.cnf.hid_lay*(self.cnf.inp_lay+1))]) + ',' + ','.join(["out_w{}".format(i) for i in range(self.cnf.out_lay*(self.cnf.hid_lay+1))]) np.savetxt(self.path_trial +'/trial{}.csv'.format(self.cnf.seed), np.array(self.dat), delimiter=',', header = head) self.dat = [] class Statistics: def __init__(self, cnf, path_out, path_dat): self.path_out = path_out self.path_dat = path_dat self.cnf = cnf def outStatistics(self): df = None for i in range(self.cnf.max_trial): dat = pd.read_csv(self.path_dat+'/trial{}.csv'.format(i+1), index_col = 0) if i == 0: df = pd.DataFrame({'trial{}'.format(i+1) : np.array(dat['accuracy'])}, index = dat.index) else: df['trial{}'.format(i+1)] = np.array(dat['accuracy']) df.to_csv(self.path_out + "all_trials.csv") _min, _max, _q25, _med, _q75, _ave, _std = [], [], [], [], [], [], [] for i in range(len(df.index)): dat = np.array(df.loc[df.index[i]]) res = np.percentile(dat, [25, 50, 75]) _min.append(dat.min()) _max.append(dat.max()) _q25.append(res[0]) _med.append(res[1]) _q75.append(res[2]) _ave.append(dat.mean()) _std.append(dat.std()) _out = pd.DataFrame({ 'min' : np.array(_min), 'q25' : np.array(_q25), 'med' : np.array(_med), 'q75' : np.array(_q75), 'max' : np.array(_max), 'ave' : np.array(_ave), 'std' : np.array(_std) },index = df.index) _out.to_csv(self.path_out + "statistics.csv")
python
import speech_recognition as sr import subprocess from subprocess import call import os import gnk import time os.environ["GOOGLE_APPLICATION_CREDENTIALS"] = "//add_credentials" def prepare_date(self): self.response = self.response + self.result[2:18] def prepare_time(self): self.response = self.response + self.result[2:-2] def assistant(data): if "how are you" in data: speak("I am fine") if "what time is it" in data: speak(ctime()) if "where is" in data: data = data.split(" ") location = data[2] speak("Hold on, I will show you where " + location + " is.") os.system("chromium-browser https://www.google.nl/maps/place/" + location + "/&amp;") class Action(object): def __init__(self, command, response, preparator=None): super(Action, self).__init__() self.command = command self.response = response self.result = None if preparator: self.prepare_response = preparator else: self.prepare_response = lambda: None def execute(self): self.result = str(subprocess.check_output(self.command)) def respond(self): self.prepare_response(self) print(self.response) gnk.synthesize_text(self.response) gnk.play_audio() r = sr.Recognizer() m = sr.Microphone() action_mapper = dict() action_mapper['increase brightness'] = Action('xbacklight -inc 40 && xbacklight', 'I have increased the brightness by 40%') action_mapper['current user'] = Action('whoami', '') action_mapper['decrease brightness'] = Action('xbacklight -dec 40 && xbacklight', 'I have decreased the brightness by 40%') action_mapper['date'] = Action(['date', '-R'], 'The date is ', prepare_date) action_mapper['time'] = Action(['date', '+%r'], 'The time is ', prepare_time) action_mapper['disk usage'] = Action('du', 'View the terminal') action_mapper['current session information'] = Action('w', 'View the terminal for the current session info') action_mapper['free disk space'] = Action('df', 'free disk space dsiplayed on the terminal') action_mapper['editor'] = Action('gedit', 'i have opened the editor') try: print("A moment of silence, please...") with m as source: r.adjust_for_ambient_noise(source) print("Set minimum energy threshold to {}".format(r.energy_threshold)) while True: print("Say something!") with m as source: audio = r.listen(source) print("Got it! Trying to recognize...") try: # speech to text value = r.recognize_google_cloud(audio) print("You said {}".format(value)) assistant(value) action_obj = action_mapper[value.strip()] action_obj.execute() action_obj.respond() except sr.UnknownValueError: print("Oops! Didn't catch that") except KeyError: try: gnk.play_audio("google_lookup.mp3") player = gnk.search(value.strip()) except (IndexError, KeyError): gnk.play_audio("no_results.mp3") except sr.RequestError as e: print("Uh oh! Couldn't request results from Google Speech Recognition service; {0}".format(e)) time.sleep(13) except KeyboardInterrupt: pass
python
'''Checkout how many servers I'm used in!''' import discord from discord.ext import commands from packages.utils import Embed, ImproperType import textwrap import lorem import math from mongoclient import DBClient client = discord.Client class Command(commands.Cog): def __init__(self, client): self.client = client @commands.Cog.listener() async def on_ready(self): print("Dev only servers command ready!") @commands.command() async def servernum(self, ctx): #activeservers = list (self.client.guilds) #return await ctx.send('This command is currently under maintenance. The developers will try to get it up again as soon as possible. In the meantime feel free to use `n.help` to get the other commands. Thank you for your understanding!') #if (ctx.author.id) in [505338178287173642, 637638904513691658, 396075607420567552]: dbclient = DBClient() pcollection = dbclient.db.premium pdata = await dbclient.get_big_array(pcollection, 'premium') premnum = len(pdata['premium']) prempercentage = premnum/len(self.client.guilds)*100 totalusers = 0 for guild in self.client.guilds: totalusers += guild.member_count comma_users = "{:,}".format(totalusers) guilds = len(self.client.guilds) divided_users = totalusers/guilds '''embed=Embed(':1234: Server Number', f'Check in how many servers I\'m used in!') embed.field('**__Guilds:__**', f'**`{len(self.client.guilds)}`**') embed.field('**__Total users:__**', f'**`{comma_users}`**') embed.field('**__Average users per guild:__**', f'**`{round(divided_users, 2)}`**') embed.field('**__Invite me:__**', '**`n.invite`**') embed.thumbnail('https://cdn.discordapp.com/avatars/713352863153258556/47823ecf46a380f770769b7a4a7c3449.png?size=256') return await embed.send(ctx)''' embed=Embed('Server Number', f'**__Guilds:__ `{len(self.client.guilds)}`**\n\n**__Premium guilds:__ **`{premnum} ({round(prempercentage,3)}%)`\n\n**__Total users:__ `{comma_users}`**\n\n**__Users per guild:__ `{round(divided_users, 2)}`**\n\n**__Invite me:__ `n.invite`**', '1234') embed.thumbnail('https://cdn.discordapp.com/avatars/713352863153258556/47823ecf46a380f770769b7a4a7c3449.png?size=256') return await embed.send(ctx) '''embed=Embed('Server Number', f'Lacan NTSport is currently used in `{len(self.client.guilds)}` servers by `{comma_users}` users. \nThis is an average of `{round(divided_users, 2)}` users per server.\nIn order to invite me to your server, use `n.invite.`', '1234') embed.thumbnail('https://media.discordapp.net/attachments/719414661686099993/799587106673655838/Official_Lacan_NTSport_Logo.png?width=495&height=493') return await embed.send(ctx)''' def setup(client): client.add_cog(Command(client))
python
# Copyright 2020 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. # This script generates header/source files with C++ language bindings # for the X11 protocol and its extensions. The protocol information # is obtained from xcbproto which provides XML files describing the # wire format. However, we don't parse the XML here; xcbproto ships # with xcbgen, a python library that parses the files into python data # structures for us. from __future__ import print_function import argparse import collections import itertools import os import re import sys import types # __main__.output must be defined before importing xcbgen, # so this global is unavoidable. output = collections.defaultdict(int) RENAME = { 'ANIMCURSORELT': 'AnimationCursorElement', 'CA': 'ChangeAlarmAttribute', 'CHAR2B': 'Char16', 'CHARINFO': 'CharInfo', 'COLORITEM': 'ColorItem', 'COLORMAP': 'ColorMap', 'Connection': 'RandRConnection', 'CP': 'CreatePictureAttribute', 'CS': 'ClientSpec', 'CW': 'CreateWindowAttribute', 'DAMAGE': 'DamageId', 'DIRECTFORMAT': 'DirectFormat', 'DOTCLOCK': 'DotClock', 'FBCONFIG': 'FbConfig', 'FONTPROP': 'FontProperty', 'GC': 'GraphicsContextAttribute', 'GCONTEXT': 'GraphicsContext', 'GLYPHINFO': 'GlyphInfo', 'GLYPHSET': 'GlyphSet', 'INDEXVALUE': 'IndexValue', 'KB': 'Keyboard', 'KEYCODE': 'KeyCode', 'KEYCODE32': 'KeyCode32', 'KEYSYM': 'KeySym', 'LINEFIX': 'LineFix', 'OP': 'Operation', 'PBUFFER': 'PBuffer', 'PCONTEXT': 'PContext', 'PICTDEPTH': 'PictDepth', 'PICTFORMAT': 'PictFormat', 'PICTFORMINFO': 'PictFormInfo', 'PICTSCREEN': 'PictScreen', 'PICTVISUAL': 'PictVisual', 'POINTFIX': 'PointFix', 'SPANFIX': 'SpanFix', 'SUBPICTURE': 'SubPicture', 'SYSTEMCOUNTER': 'SystemCounter', 'TIMECOORD': 'TimeCoord', 'TIMESTAMP': 'Time', 'VISUALID': 'VisualId', 'VISUALTYPE': 'VisualType', 'WAITCONDITION': 'WaitCondition', } READ_SPECIAL = set([ ('xcb', 'Setup'), ]) WRITE_SPECIAL = set([ ('xcb', 'ClientMessage'), ('xcb', 'Expose'), ('xcb', 'UnmapNotify'), ('xcb', 'SelectionNotify'), ('xcb', 'MotionNotify'), ('xcb', 'Key'), ('xcb', 'Button'), ('xcb', 'PropertyNotify'), ]) FILE_HEADER = \ '''// Copyright 2021 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // This file was automatically generated with: // %s ''' % ' \\\n// '.join(sys.argv) def adjust_type_name(name): if name in RENAME: return RENAME[name] # If there's an underscore, then this is either snake case or upper case. if '_' in name: return ''.join([ token[0].upper() + token[1:].lower() for token in name.split('_') ]) if name.isupper(): name = name.lower() # Now the only possibilities are caml case and pascal case. It could also # be snake case with a single word, but that would be same as caml case. # To convert all of these, just capitalize the first letter. return name[0].upper() + name[1:] # Given a list of event names like ["KeyPress", "KeyRelease"], returns a name # suitable for use as a base event like "Key". def event_base_name(names): # If there's only one event in this group, the "common name" is just # the event name. if len(names) == 1: return names[0] # Handle a few special cases where the longest common prefix is empty: eg. # EnterNotify/LeaveNotify/FocusIn/FocusOut -> Crossing. EVENT_NAMES = [ ('TouchBegin', 'Device'), ('RawTouchBegin', 'RawDevice'), ('Enter', 'Crossing'), ('EnterNotify', 'Crossing'), ('DeviceButtonPress', 'LegacyDevice'), ] for name, rename in EVENT_NAMES: if name in names: return rename # Use the longest common prefix of the event names as the base name. name = ''.join( chars[0] for chars in itertools.takewhile(lambda chars: len(set(chars)) == 1, zip(*names))) assert name return name def list_size(name, list_type): separator = '->' if list_type.is_ref_counted_memory else '.' return '%s%ssize()' % (name, separator) # Left-pad with 2 spaces while this class is alive. class Indent: def __init__(self, xproto, opening_line, closing_line): self.xproto = xproto self.opening_line = opening_line self.closing_line = closing_line def __enter__(self): self.xproto.write(self.opening_line) self.xproto.indent += 1 def __exit__(self, exc_type, exc_value, exc_traceback): self.xproto.indent -= 1 self.xproto.write(self.closing_line) # Make all members of |obj|, given by |fields|, visible in # the local scope while this class is alive. class ScopedFields: def __init__(self, xproto, obj, fields): self.xproto = xproto self.obj = obj self.fields = fields self.n_pushed = 0 def __enter__(self): for field in self.fields: self.n_pushed += self.xproto.add_field_to_scope(field, self.obj) if self.n_pushed: self.xproto.write() def __exit__(self, exc_type, exc_value, exc_traceback): for _ in range(self.n_pushed): self.xproto.scope.pop() # Ensures |name| is usable as a C++ field by avoiding keywords and # symbols that start with numbers. def safe_name(name): RESERVED = [ 'and', 'xor', 'or', 'class', 'explicit', 'new', 'delete', 'default', 'private', ] if name[0].isdigit() or name in RESERVED: return 'c_' + name return name class FileWriter: def __init__(self): self.indent = 0 # Write a line to the current file. def write(self, line=''): indent = self.indent if line and not line.startswith('#') else 0 print((' ' * indent) + line, file=self.file) def write_header(self): for header_line in FILE_HEADER.split('\n'): self.write(header_line) class GenXproto(FileWriter): def __init__(self, proto, proto_dir, gen_dir, xcbgen, all_types): FileWriter.__init__(self) # Command line arguments self.proto = proto self.xml_filename = os.path.join(proto_dir, '%s.xml' % proto) self.header_file = open(os.path.join(gen_dir, '%s.h' % proto), 'w') self.source_file = open(os.path.join(gen_dir, '%s.cc' % proto), 'w') # Top-level xcbgen python module self.xcbgen = xcbgen # Types for every module including this one self.all_types = all_types # The last used UID for making unique names self.prev_id = -1 # Current file to write to self.file = None # Flag to indicate if we're generating code to serialize or # deserialize data. self.is_read = False # List of the fields in scope self.scope = [] # Current place in C++ namespace hierarchy (including classes) self.namespace = [] # Map from type names to a set of types. Certain types # like enums and simple types can alias each other. self.types = collections.defaultdict(list) # Set of names of simple types to be replaced with enums self.replace_with_enum = set() # Map of enums to their underlying types self.enum_types = collections.defaultdict(set) # Map from (XML tag, XML name) to XML element self.module_names = {} # Enums that represent bit masks. self.bitenums = [] # Geenerate an ID suitable for use in temporary variable names. def new_uid(self, ): self.prev_id += 1 return self.prev_id def type_suffix(self, t): if isinstance(t, self.xcbgen.xtypes.Error): return 'Error' elif isinstance(t, self.xcbgen.xtypes.Request): return 'Request' elif t.is_reply: return 'Reply' elif t.is_event: return 'Event' return '' def rename_type(self, t, name): name = list(name) if name[0] == 'xcb': # Use namespace x11 instead of xcb. name[0] = 'x11' for i in range(1, len(name)): name[i] = adjust_type_name(name[i]) name[-1] += self.type_suffix(t) return name # Given an unqualified |name| like ('Window') and a namespace like ['x11'], # returns a fully qualified name like ('x11', 'Window'). def qualify_type(self, name, namespace): if tuple(namespace + name) in self.all_types: return namespace + name return self.qualify_type(name, namespace[:-1]) # Given an xcbgen.xtypes.Type, returns a C++-namespace-qualified # string that looks like Input::InputClass::Key. def qualtype(self, t, name): name = self.rename_type(t, name) # Try to avoid adding namespace qualifiers if they're not necessary. chop = 0 for t1, t2 in zip(name, self.namespace): if t1 != t2: break if self.qualify_type(name[chop + 1:], self.namespace) != name: break chop += 1 return '::'.join(name[chop:]) def fieldtype(self, field): if field.isfd: return 'RefCountedFD' return self.qualtype(field.type, field.enum if field.enum else field.field_type) def switch_fields(self, switch): fields = [] for case in switch.bitcases: if case.field_name: fields.append(case) else: fields.extend(case.type.fields) return fields def add_field_to_scope(self, field, obj): if not field.visible or (not field.wire and not field.isfd): return 0 field_name = safe_name(field.field_name) if field.type.is_switch: self.write('auto& %s = %s;' % (field_name, obj)) return 0 self.scope.append(field) if field.for_list or field.for_switch: self.write('%s %s{};' % (self.fieldtype(field), field_name)) else: self.write('auto& %s = %s.%s;' % (field_name, obj, field_name)) if field.type.is_list: len_name = field_name + '_len' if not self.field_from_scope(len_name): len_expr = list_size(field_name, field.type) if field.type.is_ref_counted_memory: len_expr = '%s ? %s : 0' % (field_name, len_expr) self.write('size_t %s = %s;' % (len_name, len_expr)) return 1 # Lookup |name| in the current scope. Returns the deepest # (most local) occurrence of |name|. def field_from_scope(self, name): for field in reversed(self.scope): if field.field_name == name: return field return None def expr(self, expr): if expr.op == 'popcount': return 'PopCount(%s)' % self.expr(expr.rhs) if expr.op == '~': return 'BitNot(%s)' % self.expr(expr.rhs) if expr.op == '&': return 'BitAnd(%s, %s)' % (self.expr(expr.lhs), self.expr( expr.rhs)) if expr.op in ('+', '-', '*', '/', '|'): return ('(%s) %s (%s)' % (self.expr(expr.lhs), expr.op, self.expr(expr.rhs))) if expr.op == 'calculate_len': return expr.lenfield_name if expr.op == 'sumof': tmp_id = self.new_uid() lenfield = self.field_from_scope(expr.lenfield_name) elem_type = lenfield.type.member fields = elem_type.fields if elem_type.is_container else [] header = 'auto sum%d_ = SumOf([](%sauto& listelem_ref) {' % ( tmp_id, '' if self.is_read else 'const ') footer = '}, %s);' % expr.lenfield_name with Indent(self, header, footer), ScopedFields(self, 'listelem_ref', fields): body = self.expr(expr.rhs) if expr.rhs else 'listelem_ref' self.write('return %s;' % body) return 'sum%d_' % tmp_id if expr.op == 'listelement-ref': return 'listelem_ref' if expr.op == 'enumref': return '%s::%s' % (self.qualtype( expr.lenfield_type, expr.lenfield_type.name), safe_name(expr.lenfield_name)) assert expr.op == None if expr.nmemb: return str(expr.nmemb) assert expr.lenfield_name return expr.lenfield_name def get_xidunion_element(self, name): key = ('xidunion', name[-1]) return self.module_names.get(key, None) def declare_xidunion(self, xidunion, xidname): names = [type_element.text for type_element in xidunion] types = list(set([self.module.get_type(name) for name in names])) assert len(types) == 1 value_type = types[0] value_typename = self.qualtype(value_type, value_type.name) with Indent(self, 'struct %s {' % xidname, '};'): self.write('%s() : value{} {}' % xidname) self.write() for name in names: cpp_name = self.module.get_type_name(name) typename = self.qualtype(value_type, cpp_name) self.write('%s(%s value) : value{static_cast<%s>(value)} {}' % (xidname, typename, value_typename)) self.write( 'operator %s() const { return static_cast<%s>(value); }' % (typename, typename)) self.write() self.write('%s value{};' % value_typename) def declare_simple(self, item, name): renamed = tuple(self.rename_type(item, name)) if renamed in self.replace_with_enum: return xidunion = self.get_xidunion_element(name) if xidunion: self.declare_xidunion(xidunion, renamed[-1]) else: self.write('enum class %s : %s {};' % (renamed[-1], self.qualtype(item, item.name))) self.write() def copy_primitive(self, name): if self.is_read: self.write('Read(&%s, &buf);' % name) else: self.write('buf.Write(&%s);' % name) def copy_fd(self, field, name): if self.is_read: self.write('%s = RefCountedFD(buf.TakeFd());' % name) else: # We take the request struct as const&, so dup() the fd to preserve # const-correctness because XCB close()s it after writing it. self.write('buf.fds().push_back(HANDLE_EINTR(dup(%s.get())));' % name) def copy_special_field(self, field): type_name = self.fieldtype(field) name = safe_name(field.field_name) def copy_basic(): self.write('%s %s;' % (type_name, name)) self.copy_primitive(name) if name in ('major_opcode', 'minor_opcode'): assert not self.is_read is_ext = self.module.namespace.is_ext self.write( '%s %s = %s;' % (type_name, name, 'info_.major_opcode' if is_ext and name == 'major_opcode' else field.parent[0].opcode)) self.copy_primitive(name) elif name == 'response_type': if self.is_read: copy_basic() else: container_type, container_name = field.parent assert container_type.is_event # Extension events require offsetting the opcode, so make # sure this path is only hit for non-extension events for now. assert not self.module.namespace.is_ext opcode = container_type.opcodes.get(container_name, 'obj.opcode') self.write('%s %s = %s;' % (type_name, name, opcode)) self.copy_primitive(name) elif name in ('extension', 'error_code', 'event_type'): assert self.is_read copy_basic() elif name == 'length': if not self.is_read: self.write('// Caller fills in length for writes.') self.write('Pad(&buf, sizeof(%s));' % type_name) else: copy_basic() else: assert field.type.is_expr assert (not isinstance(field.type, self.xcbgen.xtypes.Enum)) self.write('%s %s = %s;' % (type_name, name, self.expr(field.type.expr))) self.copy_primitive(name) def declare_case(self, case): assert case.type.is_case != case.type.is_bitcase fields = [ field for case_field in case.type.fields for field in self.declare_field(case_field) ] if not case.field_name: return fields name = safe_name(case.field_name) typename = adjust_type_name(name) with Indent(self, 'struct %s {' % typename, '};'): for field in fields: self.write('%s %s{};' % field) return [(typename, name)] def copy_case(self, case, switch_name): op = 'CaseEq' if case.type.is_case else 'CaseAnd' condition = ' || '.join([ '%s(%s_expr, %s)' % (op, switch_name, self.expr(expr)) for expr in case.type.expr ]) with Indent(self, 'if (%s) {' % condition, '}'): if case.field_name: fields = [case] obj = '(*%s.%s)' % (switch_name, safe_name(case.field_name)) else: fields = case.type.fields obj = '*' + switch_name for case_field in fields: name = safe_name(case_field.field_name) if case_field.visible and self.is_read: self.write('%s.%s.emplace();' % (switch_name, name)) with ScopedFields(self, obj, case.type.fields): for case_field in case.type.fields: self.copy_field(case_field) def declare_switch(self, field): return [('absl::optional<%s>' % field_type, field_name) for case in field.type.bitcases for field_type, field_name in self.declare_case(case)] def copy_switch(self, field): t = field.type name = safe_name(field.field_name) self.write('auto %s_expr = %s;' % (name, self.expr(t.expr))) for case in t.bitcases: self.copy_case(case, name) def declare_list(self, field): t = field.type type_name = self.fieldtype(field) name = safe_name(field.field_name) assert (t.nmemb not in (0, 1)) if t.is_ref_counted_memory: type_name = 'scoped_refptr<base::RefCountedMemory>' elif t.nmemb: type_name = 'std::array<%s, %d>' % (type_name, t.nmemb) elif type_name == 'char': type_name = 'std::string' else: type_name = 'std::vector<%s>' % type_name return [(type_name, name)] def copy_list(self, field): t = field.type name = safe_name(field.field_name) size = self.expr(t.expr) if t.is_ref_counted_memory: if self.is_read: self.write('%s = buffer->ReadAndAdvance(%s);' % (name, size)) else: self.write('buf.AppendBuffer(%s, %s);' % (name, size)) return if not t.nmemb: if self.is_read: self.write('%s.resize(%s);' % (name, size)) else: left = 'static_cast<size_t>(%s)' % size self.write('DCHECK_EQ(%s, %s.size());' % (left, name)) with Indent(self, 'for (auto& %s_elem : %s) {' % (name, name), '}'): elem_name = name + '_elem' elem_type = t.member elem_field = self.xcbgen.expr.Field(elem_type, field.field_type, elem_name, field.visible, field.wire, field.auto, field.enum, field.isfd) elem_field.for_list = None elem_field.for_switch = None self.copy_field(elem_field) def generate_switch_var(self, field): name = safe_name(field.field_name) for case in field.for_switch.type.bitcases: case_field = case if case.field_name else case.type.fields[0] self.write('SwitchVar(%s, %s.%s.has_value(), %s, &%s);' % (self.expr(case.type.expr[0]), safe_name(field.for_switch.field_name), safe_name(case_field.field_name), 'true' if case.type.is_bitcase else 'false', name)) def is_field_hidden_from_api(self, field): return not field.visible or getattr( field, 'for_list', False) or getattr(field, 'for_switch', False) def declare_field(self, field): t = field.type name = safe_name(field.field_name) if self.is_field_hidden_from_api(field): return [] if t.is_switch: return self.declare_switch(field) if t.is_list: return self.declare_list(field) return [(self.fieldtype(field), name)] def copy_field(self, field): if not field.wire and not field.isfd: return t = field.type renamed = tuple(self.rename_type(field.type, field.field_type)) if t.is_list: t.member = self.all_types.get(renamed, t.member) else: t = self.all_types.get(renamed, t) name = safe_name(field.field_name) self.write('// ' + name) # If this is a generated field, initialize the value of the field # variable from the given context. if not self.is_read: if field.for_list: size = list_size(safe_name(field.for_list.field_name), field.for_list.type) self.write('%s = %s;' % (name, size)) if field.for_switch: self.generate_switch_var(field) if t.is_pad: if t.align > 1: assert t.nmemb == 1 assert t.align in (2, 4) self.write('Align(&buf, %d);' % t.align) else: self.write('Pad(&buf, %d);' % t.nmemb) elif not field.visible: self.copy_special_field(field) elif t.is_switch: self.copy_switch(field) elif t.is_list: self.copy_list(field) elif t.is_union: self.copy_primitive(name) elif t.is_container: with Indent(self, '{', '}'): self.copy_container(t, name) else: assert t.is_simple if field.isfd: self.copy_fd(field, name) elif field.enum: self.copy_enum(field) else: self.copy_primitive(name) self.write() def declare_enum(self, enum): def declare_enum_entry(name, value): name = safe_name(name) self.write('%s = %s,' % (name, value)) with Indent( self, 'enum class %s : %s {' % (adjust_type_name(enum.name[-1]), self.enum_types[enum.name][0] if enum.name in self.enum_types else 'int'), '};'): bitnames = set([name for name, _ in enum.bits]) for name, value in enum.values: if name not in bitnames: declare_enum_entry(name, value) for name, value in enum.bits: declare_enum_entry(name, '1 << ' + value) self.write() def copy_enum(self, field): # The size of enum types may be different depending on the # context, so they should always be casted to the contextual # underlying type before calling Read() or Write(). underlying_type = self.qualtype(field.type, field.type.name) tmp_name = 'tmp%d' % self.new_uid() real_name = safe_name(field.field_name) self.write('%s %s;' % (underlying_type, tmp_name)) if not self.is_read: self.write('%s = static_cast<%s>(%s);' % (tmp_name, underlying_type, real_name)) self.copy_primitive(tmp_name) if self.is_read: enum_type = self.qualtype(field.type, field.enum) self.write('%s = static_cast<%s>(%s);' % (real_name, enum_type, tmp_name)) def declare_fields(self, fields): for field in fields: for field_type_name in self.declare_field(field): self.write('%s %s{};' % field_type_name) # This tries to match XEvent.xany.window, except the window will be # Window::None for events that don't have a window, unlike the XEvent # union which will get whatever data happened to be at the offset of # xany.window. def get_window_field(self, event): # The window field is not stored at any particular offset in the event, # so get a list of all the window fields. WINDOW_TYPES = set([ ('xcb', 'WINDOW'), ('xcb', 'DRAWABLE'), ('xcb', 'Glx', 'DRAWABLE'), ]) # The window we want may not be the first in the list if there are # multiple windows. This is a list of all possible window names, # ordered from highest to lowest priority. WINDOW_NAMES = [ 'event', 'window', 'request_window', 'owner', ] windows = set([ field.field_name for field in event.fields if field.field_type in WINDOW_TYPES ]) if len(windows) == 0: return '' if len(windows) == 1: return list(windows)[0] for name in WINDOW_NAMES: if name in windows: return name assert False def declare_event(self, event, name): event_name = name[-1] + 'Event' with Indent(self, 'struct %s {' % adjust_type_name(event_name), '};'): self.write('static constexpr int type_id = %d;' % event.type_id) if len(event.opcodes) == 1: self.write('static constexpr uint8_t opcode = %s;' % event.opcodes[name]) else: with Indent(self, 'enum Opcode {', '} opcode{};'): items = [(int(x), y) for (y, x) in event.enum_opcodes.items()] for opcode, opname in sorted(items): self.write('%s = %s,' % (opname, opcode)) self.write('bool send_event{};') self.declare_fields(event.fields) self.write() window_field = self.get_window_field(event) ret = ('reinterpret_cast<x11::Window*>(&%s)' % window_field if window_field else 'nullptr') self.write('x11::Window* GetWindow() { return %s; }' % ret) self.write() def declare_error(self, error, name): name = adjust_type_name(name[-1] + 'Error') with Indent(self, 'struct %s : public x11::Error {' % name, '};'): self.declare_fields(error.fields) self.write() self.write('std::string ToString() const override;') self.write() def declare_container(self, struct, struct_name): name = struct_name[-1] + self.type_suffix(struct) with Indent(self, 'struct %s {' % adjust_type_name(name), '};'): self.declare_fields(struct.fields) self.write() def copy_container(self, struct, name): assert not struct.is_union with ScopedFields(self, name, struct.fields): for field in struct.fields: self.copy_field(field) def read_special_container(self, struct, name): self.namespace = ['x11'] name = self.qualtype(struct, name) self.write('template <> COMPONENT_EXPORT(X11)') self.write('%s Read<%s>(' % (name, name)) with Indent(self, ' ReadBuffer* buffer) {', '}'): self.write('auto& buf = *buffer;') self.write('%s obj;' % name) self.write() self.is_read = True self.copy_container(struct, 'obj') self.write('return obj;') self.write() def write_special_container(self, struct, name): self.namespace = ['x11'] name = self.qualtype(struct, name) self.write('template <> COMPONENT_EXPORT(X11)') self.write('WriteBuffer Write<%s>(' % name) with Indent(self, ' const %s& obj) {' % name, '}'): self.write('WriteBuffer buf;') self.write() self.is_read = False self.copy_container(struct, 'obj') self.write('return buf;') self.write() def declare_union(self, union): name = union.name[-1] if union.elt.tag == 'eventstruct': # There's only one of these in all of the protocol descriptions. # It's just used to represent any 32-byte event for XInput. self.write('using %s = std::array<uint8_t, 32>;' % name) return with Indent(self, 'union %s {' % name, '};'): self.write('%s() { memset(this, 0, sizeof(*this)); }' % name) self.write() for field in union.fields: field_type_names = self.declare_field(field) assert len(field_type_names) == 1 self.write('%s %s;' % field_type_names[0]) self.write( 'static_assert(std::is_trivially_copyable<%s>::value, "");' % name) self.write() # Returns a list of strings suitable for use as a default-initializer for # |field|. There may be 0 strings (if the field is hidden from the public # API), 1 string (for normal cases), or many strings (for switch fields). def get_initializer(self, field): if self.is_field_hidden_from_api(field): return [] if field.type.is_switch: return ['absl::nullopt'] * len(self.declare_switch(field)) if field.type.is_list or not field.type.is_container: return ['{}'] # While using {} as an initializer for structs is fine when nested # in other structs, it causes compiler errors when used as a default # argument initializer, so explicitly initialize each field. return [ '{%s}' % ', '.join([ init for subfield in field.type.fields if not self.is_field_hidden_from_api(subfield) for init in self.get_initializer(subfield) ]) ] def declare_request(self, request): method_name = request.name[-1] request_name = method_name + 'Request' reply_name = method_name + 'Reply' if request.reply else 'void' in_class = self.namespace == ['x11', self.class_name] if not in_class or self.module.namespace.is_ext: self.declare_container(request, request.name) if request.reply: self.declare_container(request.reply, request.reply.name) self.write('using %sResponse = Response<%s>;' % (method_name, reply_name)) self.write() if in_class: # Generate a request method that takes a Request object. self.write('Future<%s> %s(' % (reply_name, method_name)) self.write(' const %s& request);' % request_name) self.write() # Generate a request method that takes fields as arguments and # forwards them as a Request object to the above implementation. field_type_names = [ field_type_name for field in request.fields for field_type_name in self.declare_field(field) ] inits = [ init for field in request.fields for init in self.get_initializer(field) ] assert len(field_type_names) == len(inits) args = [ 'const %s& %s = %s' % (field_type_name + (init, )) for (field_type_name, init) in zip(field_type_names, inits) ] self.write('Future<%s> %s(%s);' % (reply_name, method_name, ', '.join(args))) self.write() def define_request(self, request): method_name = '%s::%s' % (self.class_name, request.name[-1]) prefix = (method_name if self.module.namespace.is_ext else request.name[-1]) request_name = prefix + 'Request' reply_name = prefix + 'Reply' reply = request.reply if not reply: reply_name = 'void' # Generate a request method that takes a Request object. self.write('Future<%s>' % reply_name) self.write('%s(' % method_name) with Indent(self, ' const %s& request) {' % request_name, '}'): cond = '!connection_->Ready()' if self.module.namespace.is_ext: cond += ' || !present()' self.write('if (%s)' % cond) self.write(' return {};') self.write() self.namespace = ['x11', self.class_name] self.write('WriteBuffer buf;') self.write() self.is_read = False self.copy_container(request, 'request') self.write('Align(&buf, 4);') self.write() reply_has_fds = reply and any(field.isfd for field in reply.fields) self.write( 'return connection_->SendRequest<%s>(&buf, "%s", %s);' % (reply_name, prefix, 'true' if reply_has_fds else 'false')) self.write() # Generate a request method that takes fields as arguments and # forwards them as a Request object to the above implementation. self.write('Future<%s>' % reply_name) self.write('%s(' % method_name) args = [ 'const %s& %s' % field_type_name for field in request.fields for field_type_name in self.declare_field(field) ] with Indent(self, '%s) {' % ', '.join(args), '}'): self.write('return %s(%s{%s});' % (method_name, request_name, ', '.join([ field_name for field in request.fields for (_, field_name) in self.declare_field(field) ]))) self.write() if not reply: return self.write('template<> COMPONENT_EXPORT(X11)') self.write('std::unique_ptr<%s>' % reply_name) sig = 'detail::ReadReply<%s>(ReadBuffer* buffer) {' % reply_name with Indent(self, sig, '}'): self.namespace = ['x11'] self.write('auto& buf = *buffer;') self.write('auto reply = std::make_unique<%s>();' % reply_name) self.write() self.is_read = True self.copy_container(reply, '(*reply)') self.write('Align(&buf, 4);') offset = 'buf.offset < 32 ? 0 : buf.offset - 32' self.write('DCHECK_EQ(%s, 4 * length);' % offset) self.write() self.write('return reply;') self.write() def define_event(self, event, name): self.namespace = ['x11'] name = self.qualtype(event, name) self.write('template <> COMPONENT_EXPORT(X11)') self.write('void ReadEvent<%s>(' % name) with Indent(self, ' %s* event_, ReadBuffer* buffer) {' % name, '}'): self.write('auto& buf = *buffer;') self.write() self.is_read = True self.copy_container(event, '(*event_)') if event.is_ge_event: self.write('Align(&buf, 4);') self.write('DCHECK_EQ(buf.offset, 32 + 4 * length);') else: self.write('DCHECK_LE(buf.offset, 32ul);') self.write() def define_error(self, error, name): self.namespace = ['x11'] name = self.qualtype(error, name) with Indent(self, 'std::string %s::ToString() const {' % name, '}'): self.write('std::stringstream ss_;') self.write('ss_ << "%s{";' % name) fields = [field for field in error.fields if field.visible] for i, field in enumerate(fields): terminator = '' if i == len(fields) - 1 else ' << ", "' self.write('ss_ << ".%s = " << static_cast<uint64_t>(%s)%s;' % (field.field_name, field.field_name, terminator)) self.write('ss_ << "}";') self.write('return ss_.str();') self.write() self.write('template <>') self.write('void ReadError<%s>(' % name) with Indent(self, ' %s* error_, ReadBuffer* buffer) {' % name, '}'): self.write('auto& buf = *buffer;') self.write() self.is_read = True self.copy_container(error, '(*error_)') self.write('DCHECK_LE(buf.offset, 32ul);') def define_type(self, item, name): if name in READ_SPECIAL: self.read_special_container(item, name) if name in WRITE_SPECIAL: self.write_special_container(item, name) if isinstance(item, self.xcbgen.xtypes.Request): self.define_request(item) elif item.is_event: self.define_event(item, name) elif isinstance(item, self.xcbgen.xtypes.Error): self.define_error(item, name) def declare_type(self, item, name): if item.is_union: self.declare_union(item) elif isinstance(item, self.xcbgen.xtypes.Request): self.declare_request(item) elif item.is_event: self.declare_event(item, name) elif isinstance(item, self.xcbgen.xtypes.Error): self.declare_error(item, name) elif item.is_container: self.declare_container(item, name) elif isinstance(item, self.xcbgen.xtypes.Enum): self.declare_enum(item) else: assert item.is_simple self.declare_simple(item, name) # Additional type information identifying the enum/mask is present in the # XML data, but xcbgen doesn't make use of it: it only uses the underlying # type, as it appears on the wire. We want additional type safety, so # extract this information the from XML directly. def resolve_element(self, xml_element, fields): for child in xml_element: if 'name' not in child.attrib: if child.tag == 'case' or child.tag == 'bitcase': self.resolve_element(child, fields) continue name = child.attrib['name'] field = fields[name] field.elt = child enums = [ child.attrib[attr] for attr in ['enum', 'mask'] if attr in child.attrib ] if enums: assert len(enums) == 1 enum = enums[0] field.enum = self.module.get_type(enum).name self.enum_types[enum].add(field.type.name) else: field.enum = None def resolve_type(self, t, name): renamed = tuple(self.rename_type(t, name)) assert renamed[0] == 'x11' assert t not in self.types[renamed] self.types[renamed].append(t) self.all_types[renamed] = t if isinstance(t, self.xcbgen.xtypes.Enum): self.bitenums.append((t, name)) if not t.is_container: return fields = { field.field_name: field for field in (self.switch_fields(t) if t.is_switch else t.fields) } self.resolve_element(t.elt, fields) for field in fields.values(): if field.field_name == 'sequence': field.visible = True field.parent = (t, name) if field.type.is_list: # xcb uses void* in some places to represent arbitrary data. field.type.is_ref_counted_memory = ( not field.type.nmemb and field.field_type[0] == 'void') # |for_list| and |for_switch| may have already been set when # processing other fields in this structure. field.for_list = getattr(field, 'for_list', None) field.for_switch = getattr(field, 'for_switch', None) for is_type, for_type in ((field.type.is_list, 'for_list'), (field.type.is_switch, 'for_switch')): if not is_type: continue expr = field.type.expr field_name = expr.lenfield_name if (expr.op in (None, 'calculate_len') and field_name in fields): setattr(fields[field_name], for_type, field) if field.type.is_switch or field.type.is_case_or_bitcase: self.resolve_type(field.type, field.field_type) if isinstance(t, self.xcbgen.xtypes.Request) and t.reply: self.resolve_type(t.reply, t.reply.name) # Multiple event names may map to the same underlying event. For these # cases, we want to avoid duplicating the event structure. Instead, put # all of these events under one structure with an additional opcode field # to indicate the type of event. def uniquify_events(self): types = [] events = set() for name, t in self.module.all: if not t.is_event or len(t.opcodes) == 1: types.append((name, t)) continue renamed = tuple(self.rename_type(t, name)) self.all_types[renamed] = t if t in events: continue events.add(t) names = [name[-1] for name in t.opcodes.keys()] name = name[:-1] + (event_base_name(names), ) types.append((name, t)) t.enum_opcodes = {} for opname in t.opcodes: opcode = t.opcodes[opname] opname = opname[-1] if opname.startswith(name[-1]): opname = opname[len(name[-1]):] t.enum_opcodes[opname] = opcode self.module.all = types # Perform preprocessing like renaming, reordering, and adding additional # data fields. def resolve(self): self.class_name = (adjust_type_name(self.module.namespace.ext_name) if self.module.namespace.is_ext else 'XProto') self.uniquify_events() for name, t in self.module.all: self.resolve_type(t, name) for enum, types in list(self.enum_types.items()): if len(types) == 1: self.enum_types[enum] = list(types)[0] else: del self.enum_types[enum] for t in self.types: l = self.types[t] if len(l) == 1: continue # Allow simple types and enums to alias each other after renaming. # This is done because we want strong typing even for simple types. # If the types were not merged together, then a cast would be # necessary to convert from eg. AtomEnum to AtomSimple. assert len(l) == 2 if isinstance(l[0], self.xcbgen.xtypes.Enum): enum = l[0] simple = l[1] elif isinstance(l[1], self.xcbgen.xtypes.Enum): enum = l[1] simple = l[0] assert simple.is_simple assert enum and simple self.replace_with_enum.add(t) self.enum_types[enum.name] = simple.name for node in self.module.namespace.root: if 'name' in node.attrib: key = (node.tag, node.attrib['name']) assert key not in self.module_names self.module_names[key] = node # The order of types in xcbproto's xml files are inconsistent, so sort # them in the order {type aliases, enums, xidunions, structs, # requests/replies}. def type_order_priority(module_type): name, item = module_type if item.is_simple: return 2 if self.get_xidunion_element(name) else 0 if isinstance(item, self.xcbgen.xtypes.Enum): return 1 if isinstance(item, self.xcbgen.xtypes.Request): return 4 return 3 # sort() is guaranteed to be stable. self.module.all.sort(key=type_order_priority) def gen_header(self): self.file = self.header_file self.write_header() include_guard = 'UI_GFX_X_GENERATED_PROTOS_%s_' % ( self.header_file.name.split('/')[-1].upper().replace('.', '_')) self.write('#ifndef ' + include_guard) self.write('#define ' + include_guard) self.write() self.write('#include <array>') self.write('#include <cstddef>') self.write('#include <cstdint>') self.write('#include <cstring>') self.write('#include <vector>') self.write() self.write('#include "base/component_export.h"') self.write('#include "base/memory/ref_counted_memory.h"') self.write('#include "base/memory/scoped_refptr.h"') self.write('#include "third_party/abseil-cpp/absl/types/optional.h"') self.write('#include "base/files/scoped_file.h"') self.write('#include "ui/gfx/x/ref_counted_fd.h"') self.write('#include "ui/gfx/x/error.h"') imports = set(self.module.direct_imports) if self.module.namespace.is_ext: imports.add(('xproto', 'xproto')) for direct_import in sorted(list(imports)): self.write('#include "%s.h"' % direct_import[-1]) self.write() self.write('namespace x11 {') self.write() self.write('class Connection;') self.write() self.write('template <typename Reply>') self.write('struct Response;') self.write() self.write('template <typename Reply>') self.write('class Future;') self.write() self.namespace = ['x11'] if not self.module.namespace.is_ext: for (name, item) in self.module.all: self.declare_type(item, name) name = self.class_name with Indent(self, 'class COMPONENT_EXPORT(X11) %s {' % name, '};'): self.namespace = ['x11', self.class_name] self.write('public:') if self.module.namespace.is_ext: self.write('static constexpr unsigned major_version = %s;' % self.module.namespace.major_version) self.write('static constexpr unsigned minor_version = %s;' % self.module.namespace.minor_version) self.write() self.write(name + '(Connection* connection,') self.write(' const x11::QueryExtensionReply& info);') self.write() with Indent(self, 'uint8_t present() const {', '}'): self.write('return info_.present;') with Indent(self, 'uint8_t major_opcode() const {', '}'): self.write('return info_.major_opcode;') with Indent(self, 'uint8_t first_event() const {', '}'): self.write('return info_.first_event;') with Indent(self, 'uint8_t first_error() const {', '}'): self.write('return info_.first_error;') else: self.write('explicit %s(Connection* connection);' % name) self.write() self.write( 'Connection* connection() const { return connection_; }') self.write() for (name, item) in self.module.all: if self.module.namespace.is_ext: self.declare_type(item, name) elif isinstance(item, self.xcbgen.xtypes.Request): self.declare_request(item) self.write('private:') self.write('Connection* const connection_;') if self.module.namespace.is_ext: self.write('x11::QueryExtensionReply info_{};') self.write() self.write('} // namespace x11') self.write() self.namespace = [] def binop(op, name): self.write('inline constexpr %s operator%s(' % (name, op)) with Indent(self, ' {0} l, {0} r)'.format(name) + ' {', '}'): self.write('using T = std::underlying_type_t<%s>;' % name) self.write('return static_cast<%s>(' % name) self.write(' static_cast<T>(l) %s static_cast<T>(r));' % op) self.write() for enum, name in self.bitenums: name = self.qualtype(enum, name) binop('|', name) binop('&', name) self.write() self.write('#endif // ' + include_guard) def gen_source(self): self.file = self.source_file self.write_header() self.write('#include "%s.h"' % self.module.namespace.header) self.write() self.write('#include <xcb/xcb.h>') self.write('#include <xcb/xcbext.h>') self.write() self.write('#include "base/logging.h"') self.write('#include "base/posix/eintr_wrapper.h"') self.write('#include "ui/gfx/x/xproto_internal.h"') self.write() self.write('namespace x11 {') self.write() ctor = '%s::%s' % (self.class_name, self.class_name) if self.module.namespace.is_ext: self.write(ctor + '(Connection* connection,') self.write(' const x11::QueryExtensionReply& info)') self.write(' : connection_(connection), info_(info) {}') else: self.write(ctor + '(Connection* connection) : connection_(connection) {}') self.write() for (name, item) in self.module.all: self.define_type(item, name) self.write('} // namespace x11') def parse(self): self.module = self.xcbgen.state.Module(self.xml_filename, None) self.module.register() self.module.resolve() def generate(self): self.gen_header() self.gen_source() class GenExtensionManager(FileWriter): def __init__(self, gen_dir, genprotos): FileWriter.__init__(self) self.gen_dir = gen_dir self.genprotos = genprotos self.extensions = [ proto for proto in genprotos if proto.module.namespace.is_ext ] def gen_header(self): self.file = open(os.path.join(self.gen_dir, 'extension_manager.h'), 'w') self.write_header() self.write('#ifndef UI_GFX_X_GENERATED_PROTOS_EXTENSION_MANAGER_H_') self.write('#define UI_GFX_X_GENERATED_PROTOS_EXTENSION_MANAGER_H_') self.write() self.write('#include <memory>') self.write() self.write('#include "base/component_export.h"') self.write() self.write('namespace x11 {') self.write() self.write('class Connection;') self.write() for genproto in self.genprotos: self.write('class %s;' % genproto.class_name) self.write() with Indent(self, 'class COMPONENT_EXPORT(X11) ExtensionManager {', '};'): self.write('public:') self.write('ExtensionManager();') self.write('~ExtensionManager();') self.write() for extension in self.extensions: name = extension.proto self.write('%s& %s() { return *%s_; }' % (extension.class_name, name, name)) self.write() self.write('protected:') self.write('void Init(Connection* conn);') self.write() self.write('private:') for extension in self.extensions: self.write('std::unique_ptr<%s> %s_;' % (extension.class_name, extension.proto)) self.write() self.write('} // namespace x11') self.write() self.write('#endif // UI_GFX_X_GENERATED_PROTOS_EXTENSION_MANAGER_H_') def gen_source(self): self.file = open(os.path.join(self.gen_dir, 'extension_manager.cc'), 'w') self.write_header() self.write('#include "ui/gfx/x/extension_manager.h"') self.write() self.write('#include "ui/gfx/x/connection.h"') self.write('#include "ui/gfx/x/xproto_internal.h"') for genproto in self.genprotos: self.write('#include "ui/gfx/x/%s.h"' % genproto.proto) self.write() self.write('namespace x11 {') self.write() init = 'void ExtensionManager::Init' with Indent(self, init + '(Connection* conn) {', '}'): for extension in self.extensions: self.write( 'auto %s_future = conn->QueryExtension("%s");' % (extension.proto, extension.module.namespace.ext_xname)) # Flush so all requests are sent before waiting on any replies. self.write('conn->Flush();') self.write() for extension in self.extensions: name = extension.proto self.write( '%s_ = MakeExtension<%s>(conn, std::move(%s_future));' % (name, extension.class_name, name)) self.write() self.write('ExtensionManager::ExtensionManager() = default;') self.write('ExtensionManager::~ExtensionManager() = default;') self.write() self.write('} // namespace x11') class GenReadEvent(FileWriter): def __init__(self, gen_dir, genprotos): FileWriter.__init__(self) self.gen_dir = gen_dir self.genprotos = genprotos self.events = [] for proto in self.genprotos: for name, item in proto.module.all: if item.is_event: self.events.append((name, item, proto)) def event_condition(self, event, typename, proto): ext = 'conn->%s()' % proto.proto conds = [] if not proto.module.namespace.is_ext: # Core protocol event opcode = 'evtype' elif event.is_ge_event: # GenericEvent extension event conds.extend([ 'evtype == GeGenericEvent::opcode', '%s.present()' % ext, 'ge->extension == %s.major_opcode()' % ext, ]) opcode = 'ge->event_type' else: # Extension event opcode = 'evtype - %s.first_event()' % ext conds.append('%s.present()' % ext) if len(event.opcodes) == 1: conds.append('%s == %s::opcode' % (opcode, typename)) else: conds.append('(%s)' % ' || '.join([ '%s == %s::%s' % (opcode, typename, opname) for opname in event.enum_opcodes.keys() ])) return ' && '.join(conds), opcode def gen_event(self, name, event, proto): # We can't ever have a plain generic event. It must be a concrete # event provided by an extension. if name == ('xcb', 'GeGeneric'): return name = [adjust_type_name(part) for part in name[1:]] typename = '::'.join(name) + 'Event' cond, opcode = self.event_condition(event, typename, proto) with Indent(self, 'if (%s) {' % cond, '}'): self.write('event->type_id_ = %d;' % event.type_id) with Indent(self, 'event->deleter_ = [](void* event) {', '};'): self.write('delete reinterpret_cast<%s*>(event);' % typename) self.write('auto* event_ = new %s;' % typename) self.write('ReadEvent(event_, buffer);') if len(event.opcodes) > 1: self.write('{0} = static_cast<decltype({0})>({1});'.format( 'event_->opcode', opcode)) self.write('event_->send_event = send_event;') self.write('event->event_ = event_;') self.write('event->window_ = event_->GetWindow();') self.write('return;') self.write() def gen_source(self): self.file = open(os.path.join(self.gen_dir, 'read_event.cc'), 'w') self.write_header() self.write('#include "ui/gfx/x/event.h"') self.write() self.write('#include <xcb/xcb.h>') self.write() self.write('#include "ui/gfx/x/connection.h"') self.write('#include "ui/gfx/x/xproto_types.h"') for genproto in self.genprotos: self.write('#include "ui/gfx/x/%s.h"' % genproto.proto) self.write() self.write('namespace x11 {') self.write() self.write('void ReadEvent(') args = 'Event* event, Connection* conn, ReadBuffer* buffer' with Indent(self, ' %s) {' % args, '}'): self.write('auto* buf = buffer->data->data();') cast = 'auto* %s = reinterpret_cast<const %s*>(buf);' self.write(cast % ('ev', 'xcb_generic_event_t')) self.write(cast % ('ge', 'xcb_ge_generic_event_t')) self.write('auto evtype = ev->response_type & ~kSendEventMask;') self.write('bool send_event = ev->response_type & kSendEventMask;') self.write() for name, event, proto in self.events: self.gen_event(name, event, proto) self.write('NOTREACHED();') self.write() self.write('} // namespace x11') class GenReadError(FileWriter): def __init__(self, gen_dir, genprotos, xcbgen): FileWriter.__init__(self) self.gen_dir = gen_dir self.genprotos = genprotos self.xcbgen = xcbgen def get_errors_for_proto(self, proto): errors = {} for _, item in proto.module.all: if isinstance(item, self.xcbgen.xtypes.Error): for name in item.opcodes: id = int(item.opcodes[name]) if id < 0: continue name = [adjust_type_name(part) for part in name[1:]] typename = '::'.join(name) + 'Error' errors[id] = typename return errors def gen_errors_for_proto(self, errors, proto): if proto.module.namespace.is_ext: cond = 'if (%s().present()) {' % proto.proto first_error = '%s().first_error()' % proto.proto else: cond = '{' first_error = '0' with Indent(self, cond, '}'): self.write('uint8_t first_error = %s;' % first_error) for id, name in sorted(errors.items()): with Indent(self, '{', '}'): self.write('auto error_code = first_error + %d;' % id) self.write('auto parse = MakeError<%s>;' % name) self.write('add_parser(error_code, first_error, parse);') self.write() def gen_init_error_parsers(self): self.write('uint8_t first_errors[256];') self.write('memset(first_errors, 0, sizeof(first_errors));') self.write() args = 'uint8_t error_code, uint8_t first_error, ErrorParser parser' with Indent(self, 'auto add_parser = [&](%s) {' % args, '};'): cond = ('!error_parsers_[error_code] || ' + 'first_error > first_errors[error_code]') with Indent(self, 'if (%s) {' % cond, '}'): self.write('first_errors[error_code] = error_code;') self.write('error_parsers_[error_code] = parser;') self.write() for proto in self.genprotos: errors = self.get_errors_for_proto(proto) if errors: self.gen_errors_for_proto(errors, proto) def gen_source(self): self.file = open(os.path.join(self.gen_dir, 'read_error.cc'), 'w') self.write_header() self.write('#include "ui/gfx/x/connection.h"') self.write('#include "ui/gfx/x/error.h"') self.write('#include "ui/gfx/x/xproto_internal.h"') self.write() for genproto in self.genprotos: self.write('#include "ui/gfx/x/%s.h"' % genproto.proto) self.write() self.write('namespace x11 {') self.write() self.write('namespace {') self.write() self.write('template <typename T>') sig = 'std::unique_ptr<Error> MakeError(Connection::RawError error_)' with Indent(self, '%s {' % sig, '}'): self.write('ReadBuffer buf(error_);') self.write('auto error = std::make_unique<T>();') self.write('ReadError(error.get(), &buf);') self.write('return error;') self.write() self.write('} // namespace') self.write() with Indent(self, 'void Connection::InitErrorParsers() {', '}'): self.gen_init_error_parsers() self.write() self.write('} // namespace x11') def main(): parser = argparse.ArgumentParser() parser.add_argument('xcbproto_dir', type=str) parser.add_argument('gen_dir', type=str) parser.add_argument('protos', type=str, nargs='*') args = parser.parse_args() sys.path.insert(1, args.xcbproto_dir) import xcbgen.xtypes import xcbgen.state all_types = {} proto_src_dir = os.path.join(args.xcbproto_dir, 'src') genprotos = [ GenXproto(proto, proto_src_dir, args.gen_dir, xcbgen, all_types) for proto in args.protos ] for genproto in genprotos: genproto.parse() for genproto in genprotos: genproto.resolve() # Give each event a unique type ID. This is used by Event to # implement downcasting for events. type_id = 1 for proto in genprotos: for _, item in proto.module.all: if item.is_event: item.type_id = type_id type_id += 1 for genproto in genprotos: genproto.generate() gen_extension_manager = GenExtensionManager(args.gen_dir, genprotos) gen_extension_manager.gen_header() gen_extension_manager.gen_source() GenReadEvent(args.gen_dir, genprotos).gen_source() GenReadError(args.gen_dir, genprotos, xcbgen).gen_source() return 0 if __name__ == '__main__': sys.exit(main())
python
from math import sin, radians #for i in range(100): # r = radians(i) # # print(f" sinus z {i} = {sin(i)}") # print(f" sinus z {r} = {sin(r)}") x = 0 i = 0 while x < 1: i = i + 1 r = radians(i) x = sin(r) print(i,r,x) x = 0 i = 0 while True: i = i + 1 r = radians(i) x = sin(r) if i > 360: break print("Koniec",i,r,x)
python
# Generated by Django 2.2.13 on 2020-06-18 21:11 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('oidc_provider', '0027_token_refresh_token_expire_at'), ] operations = [ migrations.AddField( model_name='client', name='backchannel_logout_uri', field=models.URLField(blank=True, default='', max_length=255, verbose_name='Back-channel logout URI'), ), ]
python
#!/usr/bin/env python # -*- coding: utf-8 -*- import json from alipay.aop.api.constant.ParamConstants import * class AlipayBossRelatedCompanyConsultModel(object): def __init__(self): self._biz_time_in_mills = None self._is_whole_month_valid = None self._type = None self._value = None @property def biz_time_in_mills(self): return self._biz_time_in_mills @biz_time_in_mills.setter def biz_time_in_mills(self, value): self._biz_time_in_mills = value @property def is_whole_month_valid(self): return self._is_whole_month_valid @is_whole_month_valid.setter def is_whole_month_valid(self, value): self._is_whole_month_valid = value @property def type(self): return self._type @type.setter def type(self, value): self._type = value @property def value(self): return self._value @value.setter def value(self, value): self._value = value def to_alipay_dict(self): params = dict() if self.biz_time_in_mills: if hasattr(self.biz_time_in_mills, 'to_alipay_dict'): params['biz_time_in_mills'] = self.biz_time_in_mills.to_alipay_dict() else: params['biz_time_in_mills'] = self.biz_time_in_mills if self.is_whole_month_valid: if hasattr(self.is_whole_month_valid, 'to_alipay_dict'): params['is_whole_month_valid'] = self.is_whole_month_valid.to_alipay_dict() else: params['is_whole_month_valid'] = self.is_whole_month_valid if self.type: if hasattr(self.type, 'to_alipay_dict'): params['type'] = self.type.to_alipay_dict() else: params['type'] = self.type if self.value: if hasattr(self.value, 'to_alipay_dict'): params['value'] = self.value.to_alipay_dict() else: params['value'] = self.value return params @staticmethod def from_alipay_dict(d): if not d: return None o = AlipayBossRelatedCompanyConsultModel() if 'biz_time_in_mills' in d: o.biz_time_in_mills = d['biz_time_in_mills'] if 'is_whole_month_valid' in d: o.is_whole_month_valid = d['is_whole_month_valid'] if 'type' in d: o.type = d['type'] if 'value' in d: o.value = d['value'] return o
python
from .cprint import aprint, printInfo from .utils import Utils
python
#!/usr/bin/env python # Copyright 2018 Criteo # # 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. """Asynchronous task runner.""" import enum from concurrent import futures from datetime import datetime from biggraphite.cli.web import context from biggraphite.cli.web.capture import Capture # TODO: add a scheduler to purge old tasks class TaskRunner: """Task runner.""" def __init__(self): """Init TaskRunner.""" self.tasks = [] self._executor = futures.ThreadPoolExecutor( max_workers=10, thread_name_prefix="bgutil_worker" ) def submit(self, label, command, opts): """Submit a bgutil command to run it asynchronously.""" task = BgUtilTask(label, datetime.now()) self.tasks.append(task) def _done_callback(f): try: result = f.result() task.completed(result) except futures.CancelledError as e: task.cancelled(e) except futures.TimeoutError as e: task.timed_out(e) except Exception as e: task.failed(e) future = self._executor.submit( self._wrap_command, task, context.accessor, command, opts ) task.submitted() future.add_done_callback(_done_callback) @staticmethod def _wrap_command(task, accessor, cmd, opts): task.started() with Capture() as capture: cmd.run(accessor, opts) return capture.get_content() class BgUtilTask: """BgUtil task.""" def __init__( self, label, submitted_on, started_on=None, completed_on=None, result=None ): """Init a bgutil task.""" self.label = label self.submitted_on = submitted_on self.started_on = started_on self.completed_on = completed_on self.result = result self.status = BgUtilTaskStatus.CREATED def submitted(self): """Mark the task as submitted.""" self.submitted_on = datetime.now() self.status = BgUtilTaskStatus.SUBMITTED def started(self): """Mark the task as started.""" self.started_on = datetime.now() self.status = BgUtilTaskStatus.STARTED def completed(self, result): """Mark the task as completed.""" self.result = result self.completed_on = datetime.now() self.status = BgUtilTaskStatus.COMPLETED def failed(self, result=None): """Mark the task as failed.""" self.result = result self.status = BgUtilTaskStatus.FAILED def cancelled(self, result=None): """Mark the task as cancelled.""" self.result = result self.status = BgUtilTaskStatus.CANCELLED def timed_out(self, result=None): """Mark the task as timed out.""" self.result = result self.status = BgUtilTaskStatus.TIMED_OUT def is_finished(self): """Is the task finished.""" return self.status not in [ BgUtilTaskStatus.CREATED, BgUtilTaskStatus.SUBMITTED, BgUtilTaskStatus.STARTED ] class BgUtilTaskStatus(enum.Enum): """Status of a BgUtilTask.""" CREATED = "created" SUBMITTED = "submitted" STARTED = "started" COMPLETED = "completed" CANCELLED = "cancelled" TIMED_OUT = "timed_out" FAILED = "failed"
python
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- from ._models_py3 import Actor from ._models_py3 import CallbackConfig from ._models_py3 import EncryptionProperty from ._models_py3 import Event from ._models_py3 import EventContent from ._models_py3 import EventInfo from ._models_py3 import EventListResult from ._models_py3 import EventRequestMessage from ._models_py3 import EventResponseMessage from ._models_py3 import ExportPipeline from ._models_py3 import ExportPipelineListResult from ._models_py3 import ExportPipelineTargetProperties from ._models_py3 import IPRule from ._models_py3 import IdentityProperties from ._models_py3 import ImportImageParameters from ._models_py3 import ImportPipeline from ._models_py3 import ImportPipelineListResult from ._models_py3 import ImportPipelineSourceProperties from ._models_py3 import ImportSource from ._models_py3 import ImportSourceCredentials from ._models_py3 import KeyVaultProperties from ._models_py3 import NetworkRuleSet from ._models_py3 import OperationDefinition from ._models_py3 import OperationDisplayDefinition from ._models_py3 import OperationListResult from ._models_py3 import OperationLogSpecificationDefinition from ._models_py3 import OperationMetricSpecificationDefinition from ._models_py3 import OperationServiceSpecificationDefinition from ._models_py3 import PipelineRun from ._models_py3 import PipelineRunListResult from ._models_py3 import PipelineRunRequest from ._models_py3 import PipelineRunResponse from ._models_py3 import PipelineRunSourceProperties from ._models_py3 import PipelineRunTargetProperties from ._models_py3 import PipelineSourceTriggerDescriptor from ._models_py3 import PipelineSourceTriggerProperties from ._models_py3 import PipelineTriggerDescriptor from ._models_py3 import PipelineTriggerProperties from ._models_py3 import Policies from ._models_py3 import PrivateEndpoint from ._models_py3 import PrivateEndpointConnection from ._models_py3 import PrivateEndpointConnectionListResult from ._models_py3 import PrivateLinkResource from ._models_py3 import PrivateLinkResourceListResult from ._models_py3 import PrivateLinkServiceConnectionState from ._models_py3 import ProgressProperties from ._models_py3 import ProxyResource from ._models_py3 import QuarantinePolicy from ._models_py3 import RegenerateCredentialParameters from ._models_py3 import Registry from ._models_py3 import RegistryListCredentialsResult from ._models_py3 import RegistryListResult from ._models_py3 import RegistryNameCheckRequest from ._models_py3 import RegistryNameStatus from ._models_py3 import RegistryPassword from ._models_py3 import RegistryUpdateParameters from ._models_py3 import RegistryUsage from ._models_py3 import RegistryUsageListResult from ._models_py3 import Replication from ._models_py3 import ReplicationListResult from ._models_py3 import ReplicationUpdateParameters from ._models_py3 import Request from ._models_py3 import Resource from ._models_py3 import RetentionPolicy from ._models_py3 import Sku from ._models_py3 import Source from ._models_py3 import Status from ._models_py3 import SystemData from ._models_py3 import Target from ._models_py3 import TrustPolicy from ._models_py3 import UserIdentityProperties from ._models_py3 import VirtualNetworkRule from ._models_py3 import Webhook from ._models_py3 import WebhookCreateParameters from ._models_py3 import WebhookListResult from ._models_py3 import WebhookUpdateParameters from ._container_registry_management_client_enums import ( Action, ActionsRequired, ConnectionStatus, CreatedByType, DefaultAction, EncryptionStatus, ImportMode, LastModifiedByType, NetworkRuleBypassOptions, PasswordName, PipelineOptions, PipelineRunSourceType, PipelineRunTargetType, PipelineSourceType, PolicyStatus, ProvisioningState, PublicNetworkAccess, RegistryUsageUnit, ResourceIdentityType, SkuName, SkuTier, TriggerStatus, TrustPolicyType, WebhookAction, WebhookStatus, ) __all__ = [ 'Actor', 'CallbackConfig', 'EncryptionProperty', 'Event', 'EventContent', 'EventInfo', 'EventListResult', 'EventRequestMessage', 'EventResponseMessage', 'ExportPipeline', 'ExportPipelineListResult', 'ExportPipelineTargetProperties', 'IPRule', 'IdentityProperties', 'ImportImageParameters', 'ImportPipeline', 'ImportPipelineListResult', 'ImportPipelineSourceProperties', 'ImportSource', 'ImportSourceCredentials', 'KeyVaultProperties', 'NetworkRuleSet', 'OperationDefinition', 'OperationDisplayDefinition', 'OperationListResult', 'OperationLogSpecificationDefinition', 'OperationMetricSpecificationDefinition', 'OperationServiceSpecificationDefinition', 'PipelineRun', 'PipelineRunListResult', 'PipelineRunRequest', 'PipelineRunResponse', 'PipelineRunSourceProperties', 'PipelineRunTargetProperties', 'PipelineSourceTriggerDescriptor', 'PipelineSourceTriggerProperties', 'PipelineTriggerDescriptor', 'PipelineTriggerProperties', 'Policies', 'PrivateEndpoint', 'PrivateEndpointConnection', 'PrivateEndpointConnectionListResult', 'PrivateLinkResource', 'PrivateLinkResourceListResult', 'PrivateLinkServiceConnectionState', 'ProgressProperties', 'ProxyResource', 'QuarantinePolicy', 'RegenerateCredentialParameters', 'Registry', 'RegistryListCredentialsResult', 'RegistryListResult', 'RegistryNameCheckRequest', 'RegistryNameStatus', 'RegistryPassword', 'RegistryUpdateParameters', 'RegistryUsage', 'RegistryUsageListResult', 'Replication', 'ReplicationListResult', 'ReplicationUpdateParameters', 'Request', 'Resource', 'RetentionPolicy', 'Sku', 'Source', 'Status', 'SystemData', 'Target', 'TrustPolicy', 'UserIdentityProperties', 'VirtualNetworkRule', 'Webhook', 'WebhookCreateParameters', 'WebhookListResult', 'WebhookUpdateParameters', 'Action', 'ActionsRequired', 'ConnectionStatus', 'CreatedByType', 'DefaultAction', 'EncryptionStatus', 'ImportMode', 'LastModifiedByType', 'NetworkRuleBypassOptions', 'PasswordName', 'PipelineOptions', 'PipelineRunSourceType', 'PipelineRunTargetType', 'PipelineSourceType', 'PolicyStatus', 'ProvisioningState', 'PublicNetworkAccess', 'RegistryUsageUnit', 'ResourceIdentityType', 'SkuName', 'SkuTier', 'TriggerStatus', 'TrustPolicyType', 'WebhookAction', 'WebhookStatus', ]
python
''' Script to check the correctness of the clustering. ''' import unittest import os import numpy as np from pixel_clusterizer.clusterizer import HitClusterizer, default_hits_dtype, default_clusters_dtype, default_clusters_descr, default_cluster_hits_dtype def create_hits(n_hits, max_column, max_row, max_frame, max_charge, hit_dtype=default_hits_dtype, hit_fields=None): hits = np.zeros(shape=(n_hits, ), dtype=hit_dtype) if not hit_fields: for i in range(n_hits): hits[i]['event_number'], hits[i]['frame'], hits[i]['column'], hits[i]['row'], hits[i]['charge'] = i / 3, i % max_frame, i % max_column + 1, 2 * i % max_row + 1, i % max_charge else: hit_fields_inverse = dict((v, k) for k, v in hit_fields.items()) for i in range(n_hits): hits[i][hit_fields_inverse['event_number']], hits[i][hit_fields_inverse['frame']], hits[i][hit_fields_inverse['column']], hits[i][hit_fields_inverse['row']], hits[i][hit_fields_inverse['charge']] = i / 3, i % max_frame, i % max_column + 1, 2 * i % max_row + 1, i % max_charge return hits class TestClusterizer(unittest.TestCase): @classmethod def setUpClass(cls): cls.pure_python = os.getenv('PURE_PYTHON', False) def test_exceptions(self): # TEST 1: Set Custom mapping that is correct and should not throw an exception hit_mapping = { 'event_number': 'event_number', 'column': 'column', 'row': 'row', 'charge': 'charge', 'frame': 'frame'} hit_dtype = np.dtype([ ('event_number', '<i8'), ('frame', '<u2'), ('column', '<u2'), ('row', '<u2'), ('charge', '<f4')]) _ = HitClusterizer(hit_fields=hit_mapping, hit_dtype=hit_dtype, pure_python=self.pure_python) # TEST 2: Set custom clustered hit struct that is incorrect and should throw an exception hit_dtype_new = np.dtype([ ('not_defined', '<i8'), ('frame', '<u2'), ('column', '<u2'), ('row', '<u2'), ('charge', '<f4')]) clusterizer = HitClusterizer(hit_fields=hit_mapping, hit_dtype=hit_dtype_new, pure_python=self.pure_python) with self.assertRaises(TypeError): _, _ = clusterizer.cluster_hits(np.array([], dtype=hit_dtype)) # missing "not_defined" with self.assertRaises(TypeError): _, _ = clusterizer.cluster_hits(np.array([], dtype=hit_dtype_new)) # missing "event_number" # TEST 3 Set custom and correct hit mapping, no eception expected hit_mapping = { 'not_defined': 'event_number', 'column': 'column', 'row': 'row', 'charge': 'charge', 'frame': 'frame'} clusterizer = HitClusterizer(hit_fields=hit_mapping, hit_dtype=hit_dtype_new, pure_python=self.pure_python) _, _ = clusterizer.cluster_hits(np.array([], dtype=hit_dtype_new)) # TEST 4 Set custom and correct hit mapping, decrease event_number hits = np.ones(shape=(2, ), dtype=hit_dtype_new) hits[0]['column'], hits[0]['row'], hits[0]['charge'], hits[0]['not_defined'] = 17, 36, 30, 19 hits[1]['column'], hits[1]['row'], hits[1]['charge'], hits[1]['not_defined'] = 18, 36, 6, 18 with self.assertRaises(RuntimeError): _, _ = clusterizer.cluster_hits(hits) def test_cluster_algorithm(self): # Basic functionality checks # Initialize Clusterizer with default arguments clusterizer = HitClusterizer(pure_python=self.pure_python) hits = create_hits(n_hits=15, max_column=100, max_row=100, max_frame=1, max_charge=2) # Dioganal hits[1]["row"] = 2 hits[2]["column"] = 4 hits[2]["row"] = 4 # Same row hits[4]["row"] = 7 hits[5]["column"] = 7 hits[5]["row"] = 7 # Same column hits[7]["column"] = 7 hits[7]["row"] = 14 hits[8]["column"] = 7 hits[8]["row"] = 16 # Test frame hits[10]["row"] = 20 hits[10]["frame"] = 1 # Same location hits[14]["column"] = 13 hits[14]["row"] = 25 cluster_hits, clusters = clusterizer.cluster_hits(hits) # cluster hits # Define expected output expected_clusters = np.zeros(shape=(11, ), dtype=default_clusters_dtype) expected_clusters['event_number'] = [0, 0, 1, 1, 2, 2, 3, 3, 3, 4, 4] expected_clusters['ID'] = [0, 1, 0, 1, 0, 1, 0, 1, 2, 0, 1] expected_clusters['n_hits'] = [2, 1, 2, 1, 2, 1, 1, 1, 1, 1, 1] expected_clusters['charge'] = [1.0, 0.0, 1.0, 1.0, 1.0, 0.0, 1.0, 0.0, 1.0, 0.0, 1.0] expected_clusters['seed_column'] = [2, 4, 4, 7, 7, 7, 10, 11, 12, 13, 14] expected_clusters['seed_row'] = [2, 4, 7, 7, 14, 16, 19, 20, 23, 25, 27] expected_clusters['mean_column'] = [1.5, 4.0, 4.5, 7.0, 7.0, 7.0, 10.0, 11.0, 12.0, 13.0, 14.0] expected_clusters['mean_row'] = [1.5, 4.0, 7.0, 7.0, 13.5, 16.0, 19.0, 20.0, 23.0, 25.0, 27.0] # Define expected output expected_cluster_hits = np.zeros(shape=(15, ), dtype=default_cluster_hits_dtype) expected_cluster_hits['event_number'] = hits['event_number'] expected_cluster_hits['frame'] = hits['frame'] expected_cluster_hits['column'] = hits['column'] expected_cluster_hits['row'] = hits['row'] expected_cluster_hits['charge'] = hits['charge'] expected_cluster_hits['cluster_ID'] = [0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 1, 2, 0, 1, -2] expected_cluster_hits['is_seed'] = [0, 1, 1, 1, 0, 1, 0, 1, 1, 1, 1, 1, 1, 1, 0] expected_cluster_hits['cluster_size'] = [2, 2, 1, 2, 2, 1, 2, 2, 1, 1, 1, 1, 1, 1, 0] expected_cluster_hits['n_cluster'] = [2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 2, 2, 2] # Test results self.assertTrue(np.array_equal(clusters, expected_clusters)) self.assertTrue(np.array_equal(cluster_hits, expected_cluster_hits)) # Initialize Clusterizer and test charge weighted clustering clusterizer = HitClusterizer(pure_python=self.pure_python, charge_weighted_clustering=True) # Create some fake data hits = np.ones(shape=(4, ), dtype=default_hits_dtype) hits[0]['column'], hits[0]['row'], hits[0]['charge'], hits[0]['event_number'] = 17, 36, 0, 19 hits[1]['column'], hits[1]['row'], hits[1]['charge'], hits[1]['event_number'] = 18, 37, 10, 19 hits[2]['column'], hits[2]['row'], hits[2]['charge'], hits[2]['event_number'] = 17, 36, 1, 20 hits[3]['column'], hits[3]['row'], hits[3]['charge'], hits[3]['event_number'] = 18, 37, 10, 20 cluster_hits, clusters = clusterizer.cluster_hits(hits) # cluster hits # Define expected output expected_clusters = np.zeros(shape=(2, ), dtype=default_clusters_dtype) expected_clusters['event_number'] = [19, 20] expected_clusters['n_hits'] = [2, 2] expected_clusters['charge'] = [10.0, 11.0] expected_clusters['seed_column'] = [18, 18] expected_clusters['seed_row'] = [37, 37] expected_clusters['mean_column'] = [18.0, (1.0 * 17 + 10.0 * 18) / 11.0] expected_clusters['mean_row'] = [37.0, (1.0 * 36 + 10.0 * 37) / 11.0] # Define expected output expected_cluster_hits = np.zeros(shape=(4, ), dtype=default_cluster_hits_dtype) expected_cluster_hits['event_number'] = hits['event_number'] expected_cluster_hits['frame'] = hits['frame'] expected_cluster_hits['column'] = hits['column'] expected_cluster_hits['row'] = hits['row'] expected_cluster_hits['charge'] = hits['charge'] expected_cluster_hits['is_seed'] = [0, 1, 0, 1] expected_cluster_hits['cluster_size'] = [2, 2, 2, 2] expected_cluster_hits['n_cluster'] = [1, 1, 1, 1] # Test results self.assertTrue(np.array_equal(clusters, expected_clusters)) self.assertTrue(np.array_equal(cluster_hits, expected_cluster_hits)) # Initialize Clusterizer and test charge weighted clustering and charge correction clusterizer = HitClusterizer(pure_python=self.pure_python, charge_correction=1, charge_weighted_clustering=True) # Create some fake data hits = np.ones(shape=(4, ), dtype=default_hits_dtype) hits[0]['column'], hits[0]['row'], hits[0]['charge'], hits[0]['event_number'] = 17, 36, 0, 19 hits[1]['column'], hits[1]['row'], hits[1]['charge'], hits[1]['event_number'] = 18, 37, 10, 19 hits[2]['column'], hits[2]['row'], hits[2]['charge'], hits[2]['event_number'] = 17, 36, 1, 20 hits[3]['column'], hits[3]['row'], hits[3]['charge'], hits[3]['event_number'] = 18, 37, 10, 20 cluster_hits, clusters = clusterizer.cluster_hits(hits) # cluster hits # Define expected output expected_clusters = np.zeros(shape=(2, ), dtype=default_clusters_dtype) expected_clusters['event_number'] = [19, 20] expected_clusters['n_hits'] = [2, 2] expected_clusters['charge'] = [10.0, 11.0] expected_clusters['seed_column'] = [18, 18] expected_clusters['seed_row'] = [37, 37] expected_clusters['mean_column'] = [(1.0 * 17 + 11.0 * 18) / 12.0, (2.0 * 17 + 11.0 * 18) / 13.0] expected_clusters['mean_row'] = [(1.0 * 36 + 11.0 * 37) / 12.0, (2.0 * 36 + 11.0 * 37) / 13.0] # Define expected output expected_cluster_hits = np.zeros(shape=(4, ), dtype=default_cluster_hits_dtype) expected_cluster_hits['event_number'] = hits['event_number'] expected_cluster_hits['frame'] = hits['frame'] expected_cluster_hits['column'] = hits['column'] expected_cluster_hits['row'] = hits['row'] expected_cluster_hits['charge'] = hits['charge'] expected_cluster_hits['is_seed'] = [0, 1, 0, 1] expected_cluster_hits['cluster_size'] = [2, 2, 2, 2] expected_cluster_hits['n_cluster'] = [1, 1, 1, 1] # Test results self.assertTrue(np.array_equal(clusters, expected_clusters)) self.assertTrue(np.array_equal(cluster_hits, expected_cluster_hits)) # Initialize Clusterizer clusterizer = HitClusterizer(pure_python=self.pure_python, min_hit_charge=0, max_hit_charge=13, charge_correction=1, charge_weighted_clustering=True, column_cluster_distance=2, row_cluster_distance=2, frame_cluster_distance=4, ignore_same_hits=True) hits = create_hits(n_hits=10, max_column=100, max_row=100, max_frame=1, max_charge=2) cluster_hits, clusters = clusterizer.cluster_hits(hits) # cluster hits # Define expected output expected_clusters = np.zeros(shape=(4, ), dtype=default_clusters_dtype) expected_clusters['event_number'] = [0, 1, 2, 3] expected_clusters['n_hits'] = [3, 3, 3, 1] expected_clusters['charge'] = [1, 2, 1, 1] expected_clusters['seed_column'] = [2, 4, 8, 10] expected_clusters['seed_row'] = [3, 7, 15, 19] expected_clusters['mean_column'] = [2.0, 5.0, 8.0, 10.0] expected_clusters['mean_row'] = [3.0, 9.0, 15.0, 19.0] # Define expected output expected_cluster_hits = np.zeros(shape=(10, ), dtype=default_cluster_hits_dtype) expected_cluster_hits['event_number'] = hits['event_number'] expected_cluster_hits['frame'] = hits['frame'] expected_cluster_hits['column'] = hits['column'] expected_cluster_hits['row'] = hits['row'] expected_cluster_hits['charge'] = hits['charge'] expected_cluster_hits['is_seed'] = [0, 1, 0, 1, 0, 0, 0, 1, 0, 1] expected_cluster_hits['cluster_size'] = [3, 3, 3, 3, 3, 3, 3, 3, 3, 1] expected_cluster_hits['n_cluster'] = 1 # Test results self.assertTrue(np.array_equal(clusters, expected_clusters)) self.assertTrue(np.array_equal(cluster_hits, expected_cluster_hits)) def test_cluster_cuts(self): # Create some fake data hits = np.ones(shape=(2, ), dtype=default_hits_dtype) hits[0]['column'], hits[0]['row'], hits[0]['charge'], hits[0]['event_number'] = 17, 36, 30, 19 hits[1]['column'], hits[1]['row'], hits[1]['charge'], hits[1]['event_number'] = 18, 36, 6, 19 # Create clusterizer object clusterizer = HitClusterizer(pure_python=self.pure_python, min_hit_charge=0, max_hit_charge=13, charge_correction=1, charge_weighted_clustering=True, column_cluster_distance=2, row_cluster_distance=2, frame_cluster_distance=4, ignore_same_hits=True) # Case 1: Test max hit charge cut, accept all hits clusterizer.set_max_hit_charge(30) # only add hits with charge <= 30 cluster_hits, clusters = clusterizer.cluster_hits(hits) # cluster hits # Check cluster expected_clusters = np.zeros(shape=(1, ), dtype=default_clusters_dtype) expected_clusters['event_number'] = [19] expected_clusters['n_hits'] = [2] expected_clusters['charge'] = [36] expected_clusters['seed_column'] = [17] expected_clusters['seed_row'] = [36] expected_clusters['mean_column'] = [17.18420982] expected_clusters['mean_row'] = [36.0] # Check cluster hit info expected_cluster_hits = np.zeros(shape=(2, ), dtype=default_cluster_hits_dtype) expected_cluster_hits['event_number'] = hits['event_number'] expected_cluster_hits['frame'] = hits['frame'] expected_cluster_hits['column'] = hits['column'] expected_cluster_hits['row'] = hits['row'] expected_cluster_hits['charge'] = hits['charge'] expected_cluster_hits['is_seed'] = [1, 0] expected_cluster_hits['cluster_size'] = [2, 2] expected_cluster_hits['n_cluster'] = 1 # Test results self.assertTrue(np.array_equal(clusters, expected_clusters)) self.assertTrue(np.array_equal(cluster_hits, expected_cluster_hits)) # Case 2: Test max hit charge cut, omit hits with charge > 29 hits['event_number'] = 20 clusterizer.set_max_hit_charge(29) # only add hits with charge <= 30 cluster_hits, clusters = clusterizer.cluster_hits(hits) # cluster hits # Check cluster expected_clusters = np.zeros(shape=(1, ), dtype=default_clusters_dtype) expected_clusters['event_number'] = [20] expected_clusters['n_hits'] = [1] expected_clusters['charge'] = [6] expected_clusters['seed_column'] = [18] expected_clusters['seed_row'] = [36] expected_clusters['mean_column'] = [18.0] expected_clusters['mean_row'] = [36.0] # Check cluster hit info expected_cluster_hits = np.zeros(shape=(2, ), dtype=default_cluster_hits_dtype) expected_cluster_hits['event_number'] = hits['event_number'] expected_cluster_hits['frame'] = hits['frame'] expected_cluster_hits['column'] = hits['column'] expected_cluster_hits['row'] = hits['row'] expected_cluster_hits['charge'] = hits['charge'] expected_cluster_hits['cluster_ID'] = [-1, 0] expected_cluster_hits['is_seed'] = [0, 1] expected_cluster_hits['cluster_size'] = [0, 1] expected_cluster_hits['n_cluster'] = [1, 1] # Test results self.assertTrue(np.array_equal(clusters, expected_clusters)) self.assertTrue(np.array_equal(cluster_hits, expected_cluster_hits)) # Case 3: Add the same hit within an event # Create some fake data hits = np.ones(shape=(3, ), dtype=default_hits_dtype) hits[0]['column'], hits[0]['row'], hits[0]['charge'], hits[0]['event_number'] = 18, 36, 6, 19 hits[1]['column'], hits[1]['row'], hits[1]['charge'], hits[1]['event_number'] = 18, 36, 6, 19 hits[2]['column'], hits[2]['row'], hits[2]['charge'], hits[2]['event_number'] = 18, 38, 6, 19 expected_cluster_hits = np.zeros(shape=(3, ), dtype=default_cluster_hits_dtype) expected_clusters = np.zeros(shape=(1, ), dtype=default_clusters_dtype) expected_cluster_hits['event_number'] = hits['event_number'] expected_cluster_hits['frame'] = hits['frame'] expected_cluster_hits['column'] = hits['column'] expected_cluster_hits['row'] = hits['row'] expected_cluster_hits['charge'] = hits['charge'] expected_cluster_hits['cluster_ID'] = [0, -2, 0] expected_cluster_hits['is_seed'] = [1, 0, 0] expected_cluster_hits['cluster_size'] = [2, 0, 2] expected_cluster_hits['n_cluster'] = [1, 1, 1] expected_clusters['event_number'] = [19] expected_clusters['n_hits'] = [2] expected_clusters['charge'] = [12] expected_clusters['seed_column'] = [18] expected_clusters['seed_row'] = [36] expected_clusters['mean_column'] = [18.0] expected_clusters['mean_row'] = [37.0] clusterizer.ignore_same_hits(True) # If a hit occurred 2 times in an event it is ignored and gets the cluster index -2 cluster_hits, clusters = clusterizer.cluster_hits(hits) # Cluster hits # Test results self.assertTrue(np.array_equal(clusters, expected_clusters)) self.assertTrue(np.array_equal(cluster_hits, expected_cluster_hits)) clusterizer.ignore_same_hits(False) # If a hit occurred 2 times in an event it is used as a normal hit cluster_hits, clusters = clusterizer.cluster_hits(hits) # Cluster hits expected_cluster_hits['cluster_ID'] = [0, 0, 0] expected_cluster_hits['is_seed'] = [1, 0, 0] expected_cluster_hits['cluster_size'] = [3, 3, 3] expected_cluster_hits['n_cluster'] = [1, 1, 1] expected_clusters['n_hits'] = [3] expected_clusters['charge'] = [18] expected_clusters['mean_row'] = [(2 * 36 + 38) / 3.0] # Test results self.assertTrue(np.array_equal(clusters, expected_clusters)) self.assertTrue(np.array_equal(cluster_hits, expected_cluster_hits)) def test_set_end_of_cluster_function(self): # Initialize clusterizer object clusterizer = HitClusterizer(pure_python=self.pure_python, min_hit_charge=0, max_hit_charge=13, charge_correction=1, charge_weighted_clustering=True, column_cluster_distance=2, row_cluster_distance=2, frame_cluster_distance=4, ignore_same_hits=True) hits = create_hits(n_hits=10, max_column=100, max_row=100, max_frame=1, max_charge=2) # Define expected output modified_clusters_descr = default_clusters_descr[:] modified_clusters_descr.append(('seed_charge', 'f4')) expected_clusters = np.zeros(shape=(4, ), dtype=np.dtype(modified_clusters_descr)) expected_clusters['event_number'] = [0, 1, 2, 3] expected_clusters['n_hits'] = [3, 3, 3, 1] expected_clusters['charge'] = [1, 2, 1, 1] expected_clusters['seed_column'] = [2, 4, 8, 10] expected_clusters['seed_row'] = [3, 7, 15, 19] expected_clusters['mean_column'] = [2.0, 5.0, 8.0, 10.0] expected_clusters['mean_row'] = [3.0, 9.0, 15.0, 19.0] expected_clusters['seed_charge'] = [1., 1., 1., 1.] expected_cluster_hits = np.zeros(shape=(10, ), dtype=default_cluster_hits_dtype) expected_cluster_hits['event_number'] = hits['event_number'] expected_cluster_hits['frame'] = hits['frame'] expected_cluster_hits['column'] = hits['column'] expected_cluster_hits['row'] = hits['row'] expected_cluster_hits['charge'] = hits['charge'] expected_cluster_hits['is_seed'] = [0, 1, 0, 1, 0, 0, 0, 1, 0, 1] expected_cluster_hits['cluster_size'] = [3, 3, 3, 3, 3, 3, 3, 3, 3, 1] expected_cluster_hits['n_cluster'] = 1 clusterizer.add_cluster_field(description=('seed_charge', 'f4')) # Add an additional field to hold the result of the end_of_cluster_function calculation (here: seed charge) # The end of loop function has to define all of the following arguments, even when they are not used # It has to be compile able by numba in non python mode # This end_of_cluster_function sets the additional seed_charge field def end_of_cluster_function(hits, clusters, cluster_size, cluster_hit_indices, cluster_index, cluster_id, charge_correction, noisy_pixels, disabled_pixels, seed_hit_index): clusters[cluster_index]['seed_charge'] = hits[seed_hit_index]['charge'] clusterizer.set_end_of_cluster_function(end_of_cluster_function) # Set the new end_of_cluster_function # Main function cluster_hits, clusters = clusterizer.cluster_hits(hits) # cluster hits # Test results self.assertTrue(np.array_equal(clusters, expected_clusters)) self.assertTrue(np.array_equal(cluster_hits, expected_cluster_hits)) end_of_cluster_function_jitted = clusterizer._jitted(end_of_cluster_function) clusterizer.set_end_of_cluster_function(end_of_cluster_function_jitted) # Set jitted end_of_cluster_function # Main function cluster_hits, clusters = clusterizer.cluster_hits(hits) # cluster hits # Test results self.assertTrue(np.array_equal(clusters, expected_clusters)) self.assertTrue(np.array_equal(cluster_hits, expected_cluster_hits)) def test_set_end_of_event_function(self): # Initialize clusterizer object clusterizer = HitClusterizer(pure_python=self.pure_python, min_hit_charge=0, max_hit_charge=13, charge_correction=1, charge_weighted_clustering=True, column_cluster_distance=2, row_cluster_distance=2, frame_cluster_distance=4, ignore_same_hits=True) hits = create_hits(n_hits=10, max_column=100, max_row=100, max_frame=1, max_charge=2) # Define expected output modified_clusters_descr = default_clusters_descr[:] modified_clusters_descr.append(('n_cluster', '<u2')) expected_clusters = np.zeros(shape=(4, ), dtype=np.dtype(modified_clusters_descr)) expected_clusters['event_number'] = [0, 1, 2, 3] expected_clusters['n_hits'] = [3, 3, 3, 1] expected_clusters['charge'] = [1, 2, 1, 1] expected_clusters['seed_column'] = [2, 4, 8, 10] expected_clusters['seed_row'] = [3, 7, 15, 19] expected_clusters['mean_column'] = [2.0, 5.0, 8.0, 10.0] expected_clusters['mean_row'] = [3.0, 9.0, 15.0, 19.0] expected_clusters['n_cluster'] = [1, 1, 1, 1] expected_cluster_hits = np.zeros(shape=(10, ), dtype=default_cluster_hits_dtype) expected_cluster_hits['event_number'] = hits['event_number'] expected_cluster_hits['frame'] = hits['frame'] expected_cluster_hits['column'] = hits['column'] expected_cluster_hits['row'] = hits['row'] expected_cluster_hits['charge'] = hits['charge'] expected_cluster_hits['is_seed'] = [0, 1, 0, 1, 0, 0, 0, 1, 0, 1] expected_cluster_hits['cluster_size'] = [3, 3, 3, 3, 3, 3, 3, 3, 3, 1] expected_cluster_hits['n_cluster'] = 1 clusterizer.add_cluster_field(description=('n_cluster', '<u2')) # Add an additional field to hold the result of the end_of_cluster_function calculation (here: seed charge) # The end of loop function has to define all of the following arguments, even when they are not used # It has to be compile able by numba in non python mode # This end_of_event_function sets the additional n_cluster field def end_of_event_function(hits, clusters, start_event_hit_index, stop_event_hit_index, start_event_cluster_index, stop_event_cluster_index): # Set the number of clusters info (n_cluster)for clusters of the event for i in range(start_event_cluster_index, stop_event_cluster_index): clusters[i]['n_cluster'] = hits["n_cluster"][start_event_hit_index] clusterizer.set_end_of_event_function(end_of_event_function) # Set the new end_of_cluster_function # Main function cluster_hits, clusters = clusterizer.cluster_hits(hits) # cluster hits # Test results self.assertTrue(np.array_equal(clusters, expected_clusters)) self.assertTrue(np.array_equal(cluster_hits, expected_cluster_hits)) end_of_event_function_jitted = clusterizer._jitted(end_of_event_function) clusterizer.set_end_of_event_function(end_of_event_function_jitted) # Set jitted end_of_cluster_function # Main function cluster_hits, clusters = clusterizer.cluster_hits(hits) # cluster hits # Test results self.assertTrue(np.array_equal(clusters, expected_clusters)) self.assertTrue(np.array_equal(cluster_hits, expected_cluster_hits)) def test_chunked_clustering(self): # Big tables have to be chunked and analyzed with clusterizer.cluster_hits(hits_chunk) calls clusterizer = HitClusterizer( pure_python=self.pure_python, min_hit_charge=0, max_hit_charge=13, column_cluster_distance=2, row_cluster_distance=2, frame_cluster_distance=4, ignore_same_hits=True) n_hits = 100 hits = create_hits(n_hits=n_hits, max_column=100, max_row=100, max_frame=1, max_charge=2) cluster_hits, clusters = clusterizer.cluster_hits(hits) # Cluster all at once cluster_hits, clusters = cluster_hits.copy(), clusters.copy() # Be aware that the returned array are references to be stored! An additional call of clusterizer.cluster_hits will overwrite the data cluster_hits_chunked, clusters_chunked = None, None chunk_size = 6 # Chunk size has to be chosen to not split events between chunks! for i in range(int(n_hits / chunk_size + 1)): # Cluster in chunks hits_chunk = hits[i * chunk_size:i * chunk_size + chunk_size] cluster_hits_chunk, clusters_chunk = clusterizer.cluster_hits(hits_chunk) if cluster_hits_chunked is None: cluster_hits_chunked = cluster_hits_chunk.copy() else: cluster_hits_chunked = np.append(cluster_hits_chunked, cluster_hits_chunk) if clusters_chunked is None: clusters_chunked = clusters_chunk.copy() else: clusters_chunked = np.append(clusters_chunked, clusters_chunk) # Test results self.assertTrue(np.array_equal(clusters, clusters_chunked)) self.assertTrue(np.array_equal(cluster_hits, cluster_hits_chunked)) if __name__ == '__main__': suite = unittest.TestLoader().loadTestsFromTestCase(TestClusterizer) unittest.TextTestRunner(verbosity=2).run(suite)
python
# -*- coding: utf-8 -*- # Copyright CERN since 2022 # # 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. """ Storage-Consistency-Actions is a daemon to delete dark files, and re-subscribe the missing ones, identified previously in a Storage-Consistency-Scanner run. """ import csv import glob import json import logging import os import re import socket import time import threading import traceback from datetime import datetime from rucio.common import exception from rucio.common.logging import formatted_logger, setup_logging from rucio.common.types import InternalAccount, InternalScope from rucio.common.utils import daemon_sleep from rucio.core.heartbeat import live, die, sanity_check from rucio.core.monitor import record_gauge, record_counter from rucio.core.quarantined_replica import add_quarantined_replicas from rucio.core.replica import __exist_replicas, update_replicas_states from rucio.core.rse import list_rses, get_rse_id from rucio.rse.rsemanager import lfns2pfns, get_rse_info, parse_pfns # FIXME: these are needed by local version of declare_bad_file_replicas() # TODO: remove after move of this code to core/replica.py - see https://github.com/rucio/rucio/pull/5068 from rucio.db.sqla import models from rucio.db.sqla.session import transactional_session from rucio.db.sqla.constants import (ReplicaState, BadFilesStatus) from sqlalchemy.exc import DatabaseError, IntegrityError from sqlalchemy.orm.exc import FlushError graceful_stop = threading.Event() # FIXME: declare_bad_file_replicas will be used directly from core/replica.py when handling of DID is added there # TODO: remove after move to core/replica.py @transactional_session def declare_bad_file_replicas(dids, rse_id, reason, issuer, status=BadFilesStatus.BAD, scheme=None, session=None): """ Declare a list of bad replicas. :param dids: The list of DIDs. :param rse_id: The RSE id. :param reason: The reason of the loss. :param issuer: The issuer account. :param status: Either BAD or SUSPICIOUS. :param scheme: The scheme of the PFNs. :param session: The database session in use. """ unknown_replicas = [] replicas = [] for did in dids: scope = InternalScope(did['scope'], vo=issuer.vo) name = did['name'] path = None scope, name, path, exists, already_declared, size = __exist_replicas(rse_id, [(scope, name, path)], session=session)[0] if exists and ((str(status) == str(BadFilesStatus.BAD) and not already_declared) or str(status) == str(BadFilesStatus.SUSPICIOUS)): replicas.append({'scope': scope, 'name': name, 'rse_id': rse_id, 'state': ReplicaState.BAD}) new_bad_replica = models.BadReplicas(scope=scope, name=name, rse_id=rse_id, reason=reason, state=status, account=issuer, bytes=size) new_bad_replica.save(session=session, flush=False) session.query(models.Source).filter_by(scope=scope, name=name, rse_id=rse_id).delete(synchronize_session=False) else: if already_declared: unknown_replicas.append('%s:%s %s' % (did['scope'], did['name'], 'Already declared')) else: unknown_replicas.append('%s:%s %s' % (did['scope'], did['name'], 'Unknown replica')) if str(status) == str(BadFilesStatus.BAD): # For BAD file, we modify the replica state, not for suspicious try: # there shouldn't be any exceptions since all replicas exist update_replicas_states(replicas, session=session) except exception.UnsupportedOperation: raise exception.ReplicaNotFound("One or several replicas don't exist.") try: session.flush() except IntegrityError as error: raise exception.RucioException(error.args) except DatabaseError as error: raise exception.RucioException(error.args) except FlushError as error: raise exception.RucioException(error.args) return unknown_replicas # TODO: This is Igor's Stats class.It will be factored out as a separate class in a future version of the code. # - Igor Mandrichenko <[email protected]>, 2018 class Stats(object): def __init__(self, path): self.path = path self.Data = {} def __getitem__(self, name): return self.Data[name] def __setitem__(self, name, value): self.Data[name] = value self.save() def get(self, name, default=None): return self.Data.get(name, default) def update(self, data): self.Data.update(data) self.save() def save(self): try: with open(self.path, "r") as f: data = f.read() except: data = "" data = json.loads(data or "{}") data.update(self.Data) open(self.path, "w").write(json.dumps(data, indent=4)) def write_stats(my_stats, stats_file, stats_key=None): if stats_file: stats = {} if os.path.isfile(stats_file): with open(stats_file, "r") as f: stats = json.loads(f.read()) if stats_key: stats[stats_key] = my_stats else: stats.update(my_stats) open(stats_file, "w").write(json.dumps(stats)) # TODO: Consider throwing an error here if stats_file is not defined # TODO: Consider breaking the logic into two functions, following discussion in https://github.com/rucio/rucio/pull/5120#discussion_r792673599 def cmp2dark(new_list, old_list, comm_list, stats_file): t0 = time.time() stats_key = "cmp2dark" my_stats = stats = None with open(new_list, "r") as a_list, open(old_list, "r") as b_list,\ open(comm_list, "w") as out_list: if stats_file is not None: stats = Stats(stats_file) my_stats = { "elapsed": None, "start_time": t0, "end_time": None, "new_list": new_list, "old_list": old_list, "out_list": out_list.name, "status": "started" } stats[stats_key] = my_stats a_set = set(line.strip() for line in a_list) b_set = set(line.strip() for line in b_list) # The intersection of the two sets is what can be deleted out_set = a_set & b_set out_list.writelines("\n".join(sorted(list(out_set)))) t1 = time.time() if stats_file: my_stats.update({ "elapsed": t1 - t0, "end_time": t1, "status": "done" }) stats[stats_key] = my_stats # TODO: Changes suggested in https://github.com/rucio/rucio/pull/5120#discussion_r792681245 def parse_filename(fn): # filename looks like this: # # <rse>_%Y_%m_%d_%H_%M_<type>.<extension> # fn, ext = fn.rsplit(".", 1) parts = fn.split("_") typ = parts[-1] timestamp_parts = parts[-6:-1] timestamp = "_".join(timestamp_parts) rse = "_".join(parts[:-6]) return rse, timestamp, typ, ext def list_cc_scanned_rses(path): files = glob.glob(f"{path}/*_stats.json") rses = set() for path in files: fn = path.rsplit("/", 1)[-1] rse, timestamp, typ, ext = parse_filename(fn) rses.add(rse) return sorted(list(rses)) def list_runs_by_age(path, rse, reffile): files = glob.glob(f"{path}/{rse}_*_stats.json") r, reftimestamp, typ, ext = parse_filename(reffile) reftime = datetime.strptime(reftimestamp, '%Y_%m_%d_%H_%M') runs = {} for path in files: fn = path.rsplit("/", 1)[-1] if os.stat(path).st_size > 0: r, timestamp, typ, ext = parse_filename(fn) filetime = datetime.strptime(timestamp, '%Y_%m_%d_%H_%M') fileagedays = (reftime - filetime).days if r == rse: # if the RSE was X, then rses like X_Y will appear in this list too, # so double check that we get the right RSE runs.update({path: fileagedays}) return {k: v for k, v in sorted(runs.items(), reverse=True)} def list_runs(path, rse, nlast=0): files = glob.glob(f"{path}/{rse}_*_stats.json") runs = [] for path in files: fn = path.rsplit("/", 1)[-1] if os.stat(path).st_size > 0: r, timestamp, typ, ext = parse_filename(fn) if r == rse: # if the RSE was X, then rses like X_Y will appear in this list too, # so double check that we get the right RSE runs.append(path) if nlast == 0: nlast = len(runs) return sorted(runs, reverse=False)[-nlast:] def list_unprocessed_runs(path, rse, nlast=0): files = glob.glob(f"{path}/{rse}_*_stats.json") unproc_runs = [] for path in files: fn = path.rsplit("/", 1)[-1] if os.stat(path).st_size > 0: r, timestamp, typ, ext = parse_filename(fn) if r == rse: # if the RSE was X, then rses like X_Y will appear in this list too, # so double check that we get the right RSE if not was_cc_attempted(path): unproc_runs.append(timestamp) if nlast == 0: nlast = len(unproc_runs) return sorted(unproc_runs, reverse=True)[-nlast:] def was_cc_attempted(stats_file): try: f = open(stats_file, "r") except: print("get_data: error ", stats_file) return None stats = json.loads(f.read()) if "cc_dark" in stats or "cc_miss" in stats: return True else: return False def was_cc_processed(stats_file): try: f = open(stats_file, "r") except: print("get_data: error ", stats_file) return None stats = json.loads(f.read()) cc_dark_status = '' cc_miss_status = '' if "cc_dark" in stats: if "status" in stats['cc_dark']: cc_dark_status = stats['cc_dark']['status'] if "cc_miss" in stats: if "status" in stats['cc_miss']: cc_miss_status = stats['cc_miss']['status'] if cc_dark_status == 'done' or cc_miss_status == 'done': return True else: return False def process_dark_files(path, scope, rse, latest_run, max_dark_fraction, max_files_at_site, old_enough_run, force_proceed): """ Process the Dark Files. """ prefix = 'storage-consistency-actions (process_dark_files())' logger = formatted_logger(logging.log, prefix + '%s') # Create a cc_dark section in the stats file t0 = time.time() stats_key = "cc_dark" cc_stats = stats = None stats = Stats(latest_run) cc_stats = { "start_time": t0, "end_time": None, "initial_dark_files": 0, "confirmed_dark_files": 0, "x-check_run": old_enough_run, "status": "started" } stats[stats_key] = cc_stats # Compare the two lists, and take only the dark files that are in both latest_dark = re.sub('_stats.json$', '_D.list', latest_run) old_enough_dark = re.sub('_stats.json$', '_D.list', old_enough_run) logger(logging.INFO, 'latest_dark = %s' % latest_dark) logger(logging.INFO, 'old_enough_dark = %s' % old_enough_dark) confirmed_dark = re.sub('_stats.json$', '_DeletionList.csv', latest_run) cmp2dark(new_list=latest_dark, old_list=old_enough_dark, comm_list=confirmed_dark, stats_file=latest_run) ### # SAFEGUARD # If a large fraction (larger than 'max_dark_fraction') of the files at a site # are reported as 'dark', do NOT proceed with the deletion. # Instead, put a warning in the _stats.json file, so that an operator can have a look. ### # Get the number of files recorded by the scanner dark_files = sum(1 for line in open(latest_dark)) confirmed_dark_files = sum(1 for line in open(confirmed_dark)) logger(logging.INFO, 'dark_files %d' % dark_files) logger(logging.INFO, 'confirmed_dark_files %d' % confirmed_dark_files) logger(logging.INFO, 'confirmed_dark_files/max_files_at_sit = %f' % (confirmed_dark_files / max_files_at_site)) logger(logging.INFO, 'max_dark_fraction configured for this RSE: %f' % max_dark_fraction) # Labels for the Prometheus counters/gauges labels = {'rse': rse} record_gauge('storage.consistency.actions_dark_files_found', confirmed_dark_files, labels=labels) record_gauge('storage.consistency.actions_dark_files_confirmed', confirmed_dark_files, labels=labels) deleted_files = 0 if confirmed_dark_files / max_files_at_site < max_dark_fraction or force_proceed is True: logger(logging.INFO, 'Can proceed with dark files deletion') # Then, do the real deletion (code from DeleteReplicas.py) issuer = InternalAccount('root') with open(confirmed_dark, 'r') as csvfile: reader = csv.reader(csvfile) for name, in reader: logger(logging.INFO, 'Processing a dark file:\n RSE %s Scope: %s Name: %s' % (rse, scope, name)) rse_id = get_rse_id(rse=rse) Intscope = InternalScope(scope=scope, vo=issuer.vo) lfns = [{'scope': scope, 'name': name}] attributes = get_rse_info(rse=rse) pfns = lfns2pfns(rse_settings=attributes, lfns=lfns, operation='delete') pfn_key = scope + ':' + name url = pfns[pfn_key] urls = [url] paths = parse_pfns(attributes, urls, operation='delete') replicas = [{'scope': Intscope, 'rse_id': rse_id, 'name': name, 'path': paths[url]['path'] + paths[url]['name']}] add_quarantined_replicas(rse_id, replicas, session=None) deleted_files += 1 labels = {'rse': rse} record_counter('storage.consistency.actions_dark_files_deleted_counter', delta=1, labels=labels) # Update the stats t1 = time.time() cc_stats.update({ "end_time": t1, "initial_dark_files": dark_files, "confirmed_dark_files": deleted_files, "status": "done" }) stats[stats_key] = cc_stats record_gauge('storage.consistency.actions_dark_files_deleted', deleted_files, labels=labels) else: darkperc = 100. * confirmed_dark_files / max_files_at_site logger(logging.WARNING, '\n ATTENTION: Too many DARK files! (%3.2f%%) \n\ Stopping and asking for operators help.' % darkperc) # Update the stats t1 = time.time() cc_stats.update({ "end_time": t1, "initial_dark_files": dark_files, "confirmed_dark_files": 0, "status": "ABORTED", "aborted_reason": "%3.2f%% dark" % darkperc, }) stats[stats_key] = cc_stats record_gauge('storage.consistency.actions_dark_files_deleted', 0, labels=labels) def process_miss_files(path, scope, rse, latest_run, max_miss_fraction, max_files_at_site, old_enough_run, force_proceed): """ Process the Missing Replicas. """ prefix = 'storage-consistency-actions (process_miss_files())' logger = formatted_logger(logging.log, prefix + '%s') latest_miss = re.sub('_stats.json$', '_M.list', latest_run) logger(logging.INFO, 'latest_missing = %s' % latest_miss) # Create a cc_miss section in the stats file t0 = time.time() stats_key = "cc_miss" cc_stats = stats = None stats = Stats(latest_run) cc_stats = { "start_time": t0, "end_time": None, "initial_miss_files": 0, "confirmed_miss_files": 0, "x-check_run": old_enough_run, "status": "started" } stats[stats_key] = cc_stats ### # SAFEGUARD # If a large fraction (larger than 'max_miss_fraction') of the files at a site are reported as # 'missing', do NOT proceed with the invalidation. # Instead, put a warning in the _stats.json file, so that an operator can have a look. ### miss_files = sum(1 for line in open(latest_miss)) logger(logging.INFO, 'miss_files = %d' % miss_files) logger(logging.INFO, 'miss_files/max_files_at_site = %f' % (miss_files / max_files_at_site)) logger(logging.INFO, 'max_miss_fraction configured for this RSE (in %%): %f' % max_miss_fraction) labels = {'rse': rse} record_gauge('storage.consistency.actions_miss_files_found', miss_files, labels=labels) if miss_files / max_files_at_site < max_miss_fraction or force_proceed is True: logger(logging.INFO, 'Can proceed with missing files retransfer') invalidated_files = 0 issuer = InternalAccount('root') with open(latest_miss, 'r') as csvfile: reader = csv.reader(csvfile) reason = "invalidating damaged/missing replica" for name, in reader: logger(logging.INFO, 'Processing invalid replica:\n RSE: %s Scope: %s Name: %s' % (rse, scope, name)) rse_id = get_rse_id(rse=rse) dids = [{'scope': scope, 'name': name}] declare_bad_file_replicas(dids=dids, rse_id=rse_id, reason=reason, issuer=issuer) invalidated_files += 1 record_counter('storage.consistency.actions_miss_files_to_retransfer_counter', delta=1, labels=labels) # TODO: The stats updating can be refactored in a future version of the Stats class. # See: https://github.com/rucio/rucio/pull/5120#discussion_r792688019 # Update the stats t1 = time.time() cc_stats.update({ "end_time": t1, "initial_miss_files": miss_files, "confirmed_miss": invalidated_files, "status": "done" }) stats[stats_key] = cc_stats record_gauge('storage.consistency.actions_miss_files_to_retransfer', invalidated_files, labels=labels) else: missperc = 100. * miss_files / max_files_at_site logger(logging.WARNING, '\n Too many MISS files (%3.2f%%)!\n\ Stopping and asking for operators help.' % missperc) # Update the stats t1 = time.time() cc_stats.update({ "end_time": t1, "initial_miss_files": miss_files, "confirmed_miss_files": 0, "status": "ABORTED", "aborted_reason": "%3.2f%% miss" % missperc, }) stats[stats_key] = cc_stats record_gauge('storage.consistency.actions_miss_files_to_retransfer', 0, labels=labels) def deckard(scope, rse, dark_min_age, dark_threshold_percent, miss_threshold_percent, force_proceed, scanner_files_path): """ The core of CC actions. Use the results of the CC Scanner to check one RSE for confirmed dark files and delete them. Re-subscribe missing files. """ prefix = 'storage-consistency-actions (running original deckard code)' logger = formatted_logger(logging.log, prefix + '%s') logger(logging.INFO, 'Now running the original deckard code...') path = scanner_files_path minagedark = dark_min_age max_dark_fraction = dark_threshold_percent max_miss_fraction = miss_threshold_percent logger(logging.INFO, 'Scanner Output Path: %s \n minagedark: %d \n max_dark_fraction: %f\ \n max_miss_fraction: %f' % (path, minagedark, max_dark_fraction, max_miss_fraction)) scanner_files = 0 dbdump_before_files = 0 dbdump_after_files = 0 # Check if we have any scans available for that RSE if rse in list_cc_scanned_rses(path): # Have any of them still not been processed? # (no CC_dark or CC-miss sections in _stats.json) np_runs = list_unprocessed_runs(path, rse) logger(logging.INFO, 'Found %d unprocessed runs for RSE: %s' % (len(np_runs), rse)) latest_run = list_runs(path, rse, 1)[0] # Get the number of files recorded by the scanner logger(logging.INFO, 'latest_run %s' % latest_run) with open(latest_run, "r") as f: fstats = json.loads(f.read()) if "scanner" in fstats: scanner_stats = fstats["scanner"] if "total_files" in scanner_stats: scanner_files = scanner_stats["total_files"] else: scanner_files = 0 for root_info in scanner_stats["roots"]: scanner_files += root_info["files"] if "dbdump_before" in fstats: dbdump_before_files = fstats["dbdump_before"]["files"] if "dbdump_after" in fstats: dbdump_after_files = fstats["dbdump_after"]["files"] max_files_at_site = max(scanner_files, dbdump_before_files, dbdump_after_files) if max_files_at_site == 0: logger(logging.WARNING, '\n No files reported by scanner for this run.\ Will skip processing.') logger(logging.INFO, 'scanner_files: %d \n dbdump_before_files: %d\ \n dbdump_after_files: %d \n max_files_at_site: %d' % (scanner_files, dbdump_before_files, dbdump_after_files, max_files_at_site)) # Was the latest run ever attempted to be processed? logger(logging.INFO, 'Was the latest run %s attempted to be processed already? - %s' % (latest_run, was_cc_attempted(latest_run))) if max_files_at_site > 0 and (was_cc_attempted(latest_run) is False or force_proceed is True): logger(logging.INFO, 'Will try to process the run') # Is there another run, at least "minagedark" old, for this RSE? old_enough_run = None d = list_runs_by_age(path, rse, latest_run) if len([k for k in d if d[k] > minagedark]) > 0: # i.e. there is another dark run with appropriate age old_enough_run = [k for k in d if d[k] > minagedark][0] logger(logging.INFO, 'Found another run %d days older than the latest.\ \n Will compare the dark files in the two.' % minagedark) logger(logging.INFO, 'The first %d days older run is: %s' % (minagedark, old_enough_run)) process_dark_files(path, scope, rse, latest_run, max_dark_fraction, max_files_at_site, old_enough_run, force_proceed) else: logger(logging.INFO, 'There is no other run for this RSE at least %d days older,\ so cannot safely proceed with dark files deleteion.' % minagedark) process_miss_files(path, scope, rse, latest_run, max_miss_fraction, max_files_at_site, old_enough_run, force_proceed) else: # This run was already processed logger(logging.INFO, 'Nothing to do here') else: # No scans outputs are available for this RSE logger(logging.INFO, 'No scans available for this RSE') def deckard_loop(scope, rses, dark_min_age, dark_threshold_percent, miss_threshold_percent, force_proceed, scanner_files_path): prefix = 'storage-consistency-actions (deckard_loop())' logger = formatted_logger(logging.log, prefix + '%s') logger(logging.INFO, 'A loop over all RSEs') for rse in rses: logger(logging.INFO, 'Now processing RSE: %s' % rse) deckard(scope, rse, dark_min_age, dark_threshold_percent, miss_threshold_percent, force_proceed, scanner_files_path) def actions_loop(once, scope, rses, sleep_time, dark_min_age, dark_threshold_percent, miss_threshold_percent, force_proceed, scanner_files_path): """ Main loop to apply the CC actions """ hostname = socket.gethostname() pid = os.getpid() current_thread = threading.current_thread() executable = 'storage-consistency-actions' heartbeat = live(executable=executable, hostname=hostname, pid=pid, thread=current_thread) # Make an initial heartbeat # so that all storage-consistency-actions have the correct worker number on the next try prefix = 'storage-consistency-actions[%i/%i] ' %\ (heartbeat['assign_thread'], heartbeat['nr_threads']) logger = formatted_logger(logging.log, prefix + '%s') logger(logging.INFO, 'hostname: %s pid: %d current_thread: %s' % (hostname, pid, current_thread)) graceful_stop.wait(1) while not graceful_stop.is_set(): try: heartbeat = live(executable=executable, hostname=hostname, pid=pid, thread=current_thread) logger(logging.INFO, 'heartbeat? %s' % heartbeat) prefix = 'storage-consistency-actions[%i/%i] ' %\ (heartbeat['assign_thread'], heartbeat['nr_threads']) logger(logging.INFO, 'prefix: %s' % prefix) start = time.time() logger(logging.DEBUG, 'Start time: %f' % start) deckard_loop(scope, rses, dark_min_age, dark_threshold_percent, miss_threshold_percent, force_proceed, scanner_files_path) daemon_sleep(start_time=start, sleep_time=sleep_time, graceful_stop=graceful_stop, logger=logger) except Exception as e: traceback.print_exc() logger(logging.WARNING, '\n Something went wrong here... %s' % e) logger(logging.WARNING, '\n Something went wrong here... %s ' % (e.__class__.__name__)) if once: break die(executable=executable, hostname=hostname, pid=pid, thread=current_thread) def stop(signum=None, frame=None): """ Graceful exit. """ graceful_stop.set() def run(once=False, scope=None, rses=None, sleep_time=60, default_dark_min_age=28, default_dark_threshold_percent=1.0, default_miss_threshold_percent=1.0, force_proceed=False, default_scanner_files_path="/var/cache/consistency-dump", threads=1): """ Starts up the Consistency-Actions. """ setup_logging() prefix = 'storage-consistency-actions (run())' logger = formatted_logger(logging.log, prefix + '%s') # TODO: These variables should be sourced from the RSE config in the future. # For now, they are passed as arguments, and to emphasize that fact, we are re-assigning them: dark_min_age = default_dark_min_age dark_threshold_percent = default_dark_threshold_percent miss_threshold_percent = default_miss_threshold_percent scanner_files_path = default_scanner_files_path if rses == []: logger(logging.INFO, 'NO RSEs passed. Will loop over all writable RSEs.') rses = [rse['rse'] for rse in list_rses({'availability_write': True})] # Could limit it only to Tier-2s: # rses = [rse['rse'] for rse in list_rses({'tier': 2, 'availability_write': True})] logging.info('\n RSEs: %s' % rses) logger(logging.INFO, '\n RSEs: %s \n run once: %r \n Sleep time: %d \n Dark min age (days): %d\ \n Dark files threshold %%: %f \n Missing files threshold %%: %f \n Force proceed: %r\ \n Scanner files path: %s ' % (rses, once, sleep_time, dark_min_age, dark_threshold_percent, miss_threshold_percent, force_proceed, scanner_files_path)) executable = 'storage-consistency-actions' hostname = socket.gethostname() sanity_check(executable=executable, hostname=hostname) # It was decided that for the time being this daemon is best executed in a single thread # TODO: If this decicion is reversed in the future, the following line should be removed. threads = 1 if once: actions_loop(once, scope, rses, sleep_time, dark_min_age, dark_threshold_percent, miss_threshold_percent, force_proceed, scanner_files_path) else: logging.info('Consistency Actions starting %s threads' % str(threads)) threads = [threading.Thread(target=actions_loop, kwargs={'once': once, 'scope': scope, 'rses': rses, 'sleep_time': sleep_time, 'dark_min_age': dark_min_age, 'dark_threshold_percent': dark_threshold_percent, 'miss_threshold_percent': miss_threshold_percent, 'force_proceed': force_proceed, 'scanner_files_path': scanner_files_path}) for i in range(0, threads)] logger(logging.INFO, 'Threads: %d' % len(threads)) [t.start() for t in threads] # Interruptible joins require a timeout. while threads[0].is_alive(): [t.join(timeout=3.14) for t in threads]
python
import os import sys sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) from tests.test_files import html_doc def mocked_requests_get(*args, **kwargs): """this method will be used by the mock to replace requests.get""" class MockResponse: def __init__(self, html, status_code): self.html = html self.status_code = status_code def text(self): return self.html def status_code(self): return self.status_code if args[0] == 'http://example.com/': return MockResponse(200, (200, html_doc.doc)) return MockResponse(404, (404, 'Not Found')) def return_html_document(): """Return the 'github-python-trending' html document""" with open('tests/test_files/html-document.html', 'r') as html_file: html_document = html_file.read() return html_document
python
from checkov.terraform.checks.resource.base_resource_check import BaseResourceCheck from checkov.common.models.enums import CheckResult, CheckCategories class GoogleComputeIPForward(BaseResourceCheck): def __init__(self): name = "Ensure that IP forwarding is not enabled on Instances" id = "CKV_GCP_36" supported_resources = ['google_compute_instance'] categories = [CheckCategories.NETWORKING] super().__init__(name=name, id=id, categories=categories, supported_resources=supported_resources) def scan_resource_conf(self, conf): # Instances created by GKE should be excluded because they need to have IP forwarding enabled if conf['name'][0].startswith('gke-'): return CheckResult.PASSED elif 'can_ip_forward' in conf.keys(): if conf['can_ip_forward'][0]: return CheckResult.FAILED return CheckResult.PASSED check = GoogleComputeIPForward()
python
import pytest from leapp.exceptions import InvalidTagDefinitionError from leapp.tags import Tag, get_tags, ExperimentalTag, DisabledTag class TestTag(Tag): name = "test-tag" def test_tag_members_correctly_set(): assert hasattr(TestTag, 'Common') and TestTag.Common.name == 'common-test-tag' assert hasattr(TestTag, 'Before') and TestTag.Before.name == 'before-test-tag' assert hasattr(TestTag.Before, 'Common') and TestTag.Before.Common.name == 'common-before-test-tag' assert hasattr(TestTag, 'After') and TestTag.After.name == 'after-test-tag' assert hasattr(TestTag.After, 'Common') and TestTag.After.Common.name == 'common-after-test-tag' assert not hasattr(TestTag.Common, 'Common') assert not hasattr(TestTag.Common, 'After') assert not hasattr(TestTag.Common, 'Before') assert not hasattr(TestTag.After, 'Before') assert not hasattr(TestTag.After, 'After') assert not hasattr(TestTag.Before, 'Before') assert not hasattr(TestTag.Before, 'After') assert not TestTag.actors assert not TestTag.Common.actors assert not TestTag.Before.actors assert not TestTag.After.actors assert not TestTag.Before.Common.actors assert not TestTag.After.Common.actors assert not hasattr(TestTag, 'parent') assert TestTag.Common.parent is TestTag assert TestTag.Before.parent is TestTag assert TestTag.After.parent is TestTag assert TestTag.Before.Common.parent is TestTag assert TestTag.After.Common.parent is TestTag def test_get_tags(): tags = [tag for tag in get_tags() if tag not in (ExperimentalTag, DisabledTag)] assert len(tags) % 6 == 0 assert TestTag in tags assert TestTag.Common in tags assert TestTag.Before in tags assert TestTag.After in tags assert TestTag.Before.Common in tags assert TestTag.After.Common in tags TestTag.name = None with pytest.raises(InvalidTagDefinitionError): get_tags()
python
from django.contrib import admin from .models import name_cat,items_cat from django.db import models from mdeditor.widgets import MDEditorWidget # Register your models here. @admin.register(name_cat) class Name_admin(admin.ModelAdmin): prepopulated_fields = { 'slug': ('name',)} @admin.register(items_cat) class Items_index(admin.ModelAdmin): prepopulated_fields={'slug':('name',)} list_display=['name','categoy'] formfield_overrides = { models.TextField:{'widget':MDEditorWidget} }
python
import json import os from solc import compile_standard from web3.contract import ConciseContract from web3 import Web3, HTTPProvider OUTPUT_DIR = os.environ['HOME'] + '/plasma-dex/plasma/root_chain/build/contracts' class Deployer(object): def __init__(self, eth_node_endpoint): provider = HTTPProvider(eth_node_endpoint) self.w3 = Web3(provider) @staticmethod def get_contract_data(contract_name): """Returns the contract data for a given contract Args: contract_name (str): Name of the contract to return. Returns: str, str: ABI and bytecode of the contract """ contract_data_path = OUTPUT_DIR + '/{0}.json'.format(contract_name) with open(contract_data_path, 'r') as contract_data_file: contract_data = json.load(contract_data_file) abi = contract_data['abi'] return abi def get_contract_at_address(self, contract_name, address, concise=True): """Returns a Web3 instance of the given contract at the given address Args: contract_name (str): Name of the contract. Must already be compiled. address (str): Address of the contract. concise (bool): Whether to return a Contract or ConciseContract instance. Returns: Contract: A Web3 contract instance. """ abi = self.get_contract_data(contract_name) contract_instance = self.w3.eth.contract(abi=abi, address=address) return ConciseContract(contract_instance) if concise else contract_instance
python
# Unit test for bayesnet_inf_autodiff import numpy as onp # original numpy import jax.numpy as np from jax import grad import bayesnet_inf_autodiff as bn # Example from fig 3 of Darwiche'03 paper # Note that we assume 0=False, 1=True so we order the entries differently thetaA = np.array([0.5, 0.5]) # thetaA[a] = P(A=a) thetaB = np.array([[1.0, 0.0], [0.0, 1.0]]) # thetaB[b,a] = P(B=b|A=a) thetaC = np.array([[0.8, 0.2], [0.2, 0.8]]) # thetaC[c,a] = P(C=c|A=a) params = {'A': thetaA, 'B': thetaB, 'C':thetaC} cardinality = {name: np.shape(cpt)[0] for name, cpt in params.items()} dag = {'A':[], 'B':['A'], 'C':['A']} assert bn.make_einsum_string(dag) == 'A,B,C,A,BA,CA->' #evidence = [1, None, 0] # a=T, c=F evidence = {'A':1, 'C':0} evectors = bn.make_evidence_vectors(cardinality, evidence) fe = bn.network_poly(dag, params, evectors) # probability of evidence assert fe==0.1 # compare numbers to table 1 of Darwiche03 f = lambda ev: bn.network_poly(dag, params, ev) grads = grad(f)(evectors) # list of derivatives wrt evectors assert np.allclose(grads['A'], [0.4, 0.1]) # A assert np.allclose(grads['B'], [0.0, 0.1]) # B assert np.allclose(grads['C'], [0.1, 0.4]) # C prob_ev, probs = bn.marginal_probs(dag, params, evidence) assert prob_ev==0.1 assert np.allclose(probs['B'], [0.0, 1.0])
python
#! /usr/bin/env python #IDN #This node subscribes to the topics which include motor RPM speeds published by arduino analog outputs def wheels2twist(w1,w2,w3,w4): l_x = 0.33 r = 0.0762*2 l_y = 0.33 d=1/(l_x+l_y) I_J = np.array([[ 1, 1, 1, 1 ], [ 1, -1, -1, 1 ], [1*d, -1*d, 1*d, -1*d]])*r/4 motor_vels = np.array([w1, w2, w3, w4]) motor_vels.shape = (4,1) tw = np.dot(I_J, motor_vels) return tw.flatten().tolist() import rospy, numpy as np from std_msgs.msg import Float32MultiArray,Int16MultiArray, Float32 from geometry_msgs.msg import Twist rospy.init_node('fwd_kinematics', anonymous=True) w = [0,0,0,0] wheel_rpm=94 #just change this value, if you have changed the ESCON Studio motor speed parameters kinematic_constant=3.14159*wheel_rpm/2/30/1000 #(-2V,2V) voltage values are turning into RPM- then twist values def callback(msg): global w, kinematic_constant w[0]=msg.data[0]*kinematic_constant*-1 #motor turning direction is reversed(mechanically) w[1]=msg.data[1]*kinematic_constant w[2]=msg.data[2]*kinematic_constant*-1 #motor turning direction is reversed(mechanically) w[3]=msg.data[3]*kinematic_constant tw=wheels2twist(w[0],w[1],w[2],w[3]) twists = Float32MultiArray(data=tw) pub.publish(twists) print "Fw.Kin. Ready" #### definition of publisher/subscriber and services ### pub = rospy.Publisher('/twist_speeds', Float32MultiArray, queue_size=10) rospy.Subscriber('/motor_vel_fb', Int16MultiArray, callback) rospy.spin()
python
import serial import config from time import sleep config.x = 0 config.y = 0 config.PORT = '/dev/ttyACM0' ser = None def setup(): global ser ser = serial.Serial(config.PORT, 9600, timeout=1) st = serial_read() print(st) def serial_write(s): t = s global ser if ser is None: return "Error" ser.write(s.encode('utf-8')) return serial_read(t) def serial_read(cmd=""): global ser while True: if ser.isOpen(): rl = ser.readline() else: print("Serial is not available") continue try: rl = rl.decode('utf-8') except UnicodeDecodeError: rl = str(rl) if(rl == "2" or rl == "3" or rl == "4" or rl == "5" or rl == "6" or rl == "7" or rl == "8" or rl == "9"): print('POSITIONING DONE') return('SUCCESS') elif(rl == "SETUP DONE"): return rl elif(rl == ""): pass else: print('msg recieve='+rl) return rl def get_XY(): return [config.x, config.y] def reset(): if(serial.writeTimeoutError("0") == "RST"): config.x = 0 config.y = 0 #300 mm for long_x positioning def long_x_positive(): print("long_x+ positioning") if config.x > 700: print("out of range long_x+") return false if(serial_write("2") == 'SUCCESS'): print('long_x+ success') config.x += 300 return True else: print("long_x+ error") return False def long_x_negative(): print("long_x- positioning") if config.x < 300: print("out of range long_x-") return False if(serial_write("3") == 'SUCCESS'): print('long_x- success') config.x -= 300 return True else: print("long_x- error") return False #50mm for short_x positioning def short_x_positive(): print("short_x+ positioning") if config.x > 950: print("out of range short_x+") return False if(serial_write("4") == 'SUCCESS'): print('short_x+ success') config.x += 50 return True else: print("short_x+ error") return False def short_x_negative(): print("short_x- positioning") if config.x < 50: print("out of range short_x-") return False if(serial_write("5") == 'SUCCESS'): print('short_x- success') config.x -= 50 return True else: print("short_x- error") return False #200mm for long_y positioning def long_y_positive(): print("long_y+ positioning") if config.y > 350: print("out of range long_y+") return False if(serial_write("6") == 'SUCCESS'): print('long_y+ success') config.y += 200 return True else: print("long_y+ error") return False def long_y_negative(): print("long_y- positioning") if config.y < 200: print("out of range long_y-") return False if(serial_write("7") == 'SUCCESS'): print('long_y- success') config.y -= 200 return True else: print("long_y- error") return False #50mm for short_y positioning def short_y_positive(): print("short_y+ positioning") if config.y > 500: print("out of range short_y+") return False if(serial_write("8") == 'SUCCESS'): print('short_y+ success') config.y += 50 return True else: print("short_y+ error") return False def short_y_negative(): print("short_y- positioning") if config.y < 50: print("out of range short_y-") return False if(serial_write("9") == 'SUCCESS'): print('short_y- success') config.y -= 50 return True else: print("short_y- error") return False def stop(): print("Stopping") if(serial_write("0") == 'SUCCESS'): print('Stop success') return True else: print('Stop unsuccessful') return False if __name__ == '__main__': pass #setup() # for i in range(20): # short_y_positive() # short_y_negative() # long_x_positive() #long_x_negative()
python